~mna/snow

ref: wip-post-ast snow/pkg/semantic/translate_pass.go -rw-r--r-- 11.8 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
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
package semantic

import (
	"fmt"
	"strconv"

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

// The translate pass translates the AST produced by the parser to the semantic
// tree, which has less noise and more dense and precise information about the
// program.
//
// After this pass, the semantic graph is still high-level (close to the source
// AST) but has no comment and scopes are resolved, but not types nor
// identifier references.
func translate(files []*ast.File, errh func(token.Pos, string)) *Unit {
	unit := &Unit{
		Files: make([]*File, 0, len(files)),
	}
	universe := NewUniverse(unit)
	unit.scope = universe

	tv := &translateVisitor{
		errh:      errh,
		scope:     universe,
		generated: unit,
	}
	for _, astf := range files {
		ast.Walk(tv, astf)
	}
	return unit
}

type translateVisitor struct {
	errh              func(token.Pos, string)
	scope             *Scope
	preventBlockScope bool
	generated         Node
}

func (t *translateVisitor) clone(s *Scope) *translateVisitor {
	return &translateVisitor{
		errh:  t.errh,
		scope: s,
	}
}

func (t *translateVisitor) registerSymbol(ident *ast.Ident, decl Decl, lbl string) {
	if !t.scope.Register(ident.Name, decl) {
		t.errh(ident.Pos(), fmt.Sprintf("%s %s: symbol already declared in this scope", lbl, ident.Name))
		return
	}
}

func (t *translateVisitor) Visit(n ast.Node) ast.Visitor {
	switch n := n.(type) {

	// ************** FILE *****************
	case *ast.File:
		var f File
		f.pos = n.Pos()
		f.scope = t.scope // the file is in the Unit's scope

		scope := t.scope.New(&f)
		tt := t.clone(scope)
		for _, decl := range n.Decls {
			ast.Walk(tt, decl)
			switch gn := tt.generated.(type) {
			case *Var:
				f.Vars = append(f.Vars, gn)
			case *Fn:
				f.Fns = append(f.Fns, gn)
			case *Struct:
				f.Structs = append(f.Structs, gn)
			default:
				panic(fmt.Sprintf("invalid top-level declaration in file: %T", gn))
			}
		}
		unit := t.generated.(*Unit)
		unit.Files = append(unit.Files, &f)

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

	case *ast.FnDecl:
		var fn Fn
		fn.pos = n.Name.Pos()
		fn.scope = t.scope
		fn.ident = n.Name.Name
		fn.IsRef = n.Ref.IsValid()
		fn.Attrs = make([]*Call, len(n.Attrs))
		fn.Params = make([]*Var, len(n.Signature.Params))
		t.registerSymbol(n.Name, &fn, token.Fn.String())

		// attributes and return type expression is in the same scope as the fn
		for i, attr := range n.Attrs {
			ast.Walk(t, attr)
			call := t.generated.(*Call)
			call.AttrOf = &fn
			fn.Attrs[i] = call
		}
		if n.Signature.RetType != nil {
			ast.Walk(t, n.Signature.RetType)
			fn.ReturnExpr = t.generated.(Expr)
		}

		// parameters and body (possibly missing for external functions) are in a new scope
		bodyScope := t.scope.New(&fn)
		tt := t.clone(bodyScope)
		tt.preventBlockScope = true
		if str, ok := fn.scope.Owner.(*Struct); ok {
			fn.MethodOf = str
			generateSelfVar(&fn, n.Body, bodyScope)
		}
		for i, param := range n.Signature.Params {
			ast.Walk(tt, param)
			v := tt.generated.(*Var)
			v.ParamOf = &fn
			fn.Params[i] = v
		}
		if n.Body != nil {
			ast.Walk(tt, n.Body)
			fn.Body = tt.generated.(*Block)
		}
		t.generated = &fn

	case *ast.VarDecl:
		v := t.buildVarOrExpr(n.Kw, n.Name, n.Type).(*Var)
		v.Ctx = Immutable
		if n.Kw == token.Var {
			v.Ctx = Mutable
		}
		if n.Value != nil {
			ast.Walk(t, n.Value)
			v.Value = t.generated.(Expr)
		}
		if str, ok := v.scope.Owner.(*Struct); ok {
			v.PropOf = str
		}
		t.generated = v

	case *ast.StructDecl:
		var str Struct
		str.pos = n.Name.Pos()
		str.scope = t.scope
		str.ident = n.Name.Name
		t.registerSymbol(n.Name, &str, token.Struct.String())

		scope := t.scope.New(&str)
		str.BodyScope = scope
		tt := t.clone(scope)
		for _, decl := range n.Decls {
			ast.Walk(tt, decl)
			switch gn := tt.generated.(type) {
			case *Var:
				str.Vars = append(str.Vars, gn)
			case *Fn:
				str.Fns = append(str.Fns, gn)
			case *Struct:
				str.Structs = append(str.Structs, gn)
			default:
				panic(fmt.Sprintf("invalid declaration in struct %s: %T", str.ident, gn))
			}
		}
		t.generated = &str

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

	case *ast.IfStmt:
		var ifs If
		ifs.pos = n.Pos()
		ifs.scope = t.scope // the scope containing the if, not the scope of the if body

		// declarations in conditions and if body are in a new scope
		scope := t.scope.New(&ifs)
		tt := t.clone(scope)
		for _, cond := range n.Conds {
			ast.Walk(tt, cond)
			ifs.Conds = append(ifs.Conds, tt.generated.(Expr))
		}
		if n.Body != nil {
			tt.preventBlockScope = true
			ast.Walk(tt, n.Body)
			ifs.Body = tt.generated.(*Block)
		}

		// the else starts in the same scope as the if, and the new scope will be open
		// by walking it - it's an If or a Block.
		if n.Else != nil {
			ast.Walk(t, n.Else)
			ifs.Else = t.generated.(Stmt)
		}
		t.generated = &ifs

	case *ast.GuardStmt:
		var g Guard
		g.pos = n.Pos()
		g.scope = t.scope

		// declarations in conditions are in the same scope as the guard
		for _, cond := range n.Conds {
			ast.Walk(t, cond)
			g.Conds = append(g.Conds, t.generated.(Expr))
		}

		// the Else is a Block opened by the Guard, but has no other symbols than those
		// in the block.
		if n.Else != nil {
			tt := t.clone(t.scope.New(&g))
			tt.preventBlockScope = true
			ast.Walk(tt, n.Else)
			g.Else = tt.generated.(*Block)
		}
		t.generated = &g

	case *ast.Block:
		preventScope := t.preventBlockScope
		t.preventBlockScope = false

		var b Block
		b.pos = n.Pos()
		b.scope = t.scope

		tt := t
		if !preventScope {
			tt = t.clone(t.scope.New(&b))
		}
		for _, stmt := range n.Stmts {
			ast.Walk(tt, stmt)
			b.Stmts = append(b.Stmts, tt.generated.(Stmt))
		}
		t.generated = &b

	case *ast.ReturnStmt:
		var r Return
		r.pos = n.Pos()
		r.scope = t.scope

		if n.Value != nil {
			ast.Walk(t, n.Value)
			r.Value = t.generated.(Expr)
		}
		t.generated = &r

	case *ast.AssignStmt:
		var a Assign
		a.pos = n.Pos()
		a.scope = t.scope
		a.Op = token.Assign

		if n.Left != nil {
			ast.Walk(t, n.Left)
			a.Left = t.generated.(Expr)
		}
		if n.Right != nil {
			ast.Walk(t, n.Right)
			a.Right = t.generated.(Expr)
		}
		t.generated = &a

	case *ast.ExprStmt:
		var e ExprStmt
		e.pos = n.Pos()
		e.scope = t.scope

		if n.Value != nil {
			ast.Walk(t, n.Value)
			e.Value = t.generated.(Expr)
		}
		t.generated = &e

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

	case *ast.FnType:
		var fn FnTypeExpr
		fn.pos = n.Pos()
		fn.scope = t.scope
		fn.Params = make([]Expr, len(n.Params))

		for i, p := range n.Params {
			ast.Walk(t, p)
			fn.Params[i] = t.generated.(Expr)
		}
		if n.RetType != nil {
			ast.Walk(t, n.RetType)
			fn.Return = t.generated.(Expr)
		}
		t.generated = &fn

	case *ast.TupleType:
		var tup TupleTypeExpr
		tup.pos = n.Pos()
		tup.scope = t.scope
		tup.Fields = make([]Expr, len(n.Types))

		for i, field := range n.Types {
			ast.Walk(t, field)
			tup.Fields[i] = t.generated.(Expr)
		}
		t.generated = &tup

	case *ast.TupleExpr:
		var tup TupleVal
		tup.pos = n.Pos()
		tup.scope = t.scope
		tup.Values = make([]Expr, len(n.Values))

		for i, val := range n.Values {
			ast.Walk(t, val)
			tup.Values[i] = t.generated.(Expr)
		}
		t.generated = &tup

	case *ast.BinaryExpr:
		var bin Binary
		bin.pos = n.Pos()
		bin.scope = t.scope
		bin.Op = n.Op

		if n.Left != nil {
			ast.Walk(t, n.Left)
			bin.Left = t.generated.(Expr)
		}
		if n.Right != nil {
			ast.Walk(t, n.Right)
			bin.Right = t.generated.(Expr)
		}
		t.generated = &bin

	case *ast.UnaryExpr:
		var un Unary
		un.pos = n.Pos()
		un.scope = t.scope
		un.Op = n.Op

		if n.Right != nil {
			ast.Walk(t, n.Right)
			un.Right = t.generated.(Expr)
		}
		t.generated = &un

	case *ast.ParenExpr:
		var par Paren
		par.pos = n.Pos()
		par.scope = t.scope

		if n.Value != nil {
			ast.Walk(t, n.Value)
			par.Value = t.generated.(Expr)
		}
		t.generated = &par

	case *ast.CallExpr:
		var call Call
		call.pos = n.Pos()
		call.scope = t.scope
		call.Labels = make([]string, len(n.Args))
		call.Args = make([]Expr, len(n.Args))

		if n.Left != nil {
			ast.Walk(t, n.Left)
			call.Fun = t.generated.(Expr)
		}
		for i, arg := range n.Args {
			ast.Walk(t, arg)
			if arg.Label != nil {
				call.Labels[i] = arg.Label.Name
			}
			call.Args[i] = t.generated.(Expr)
		}
		t.generated = &call

	case *ast.SelectorExpr:
		var sel Selector
		sel.pos = n.Pos()
		sel.scope = t.scope

		if n.Left != nil {
			ast.Walk(t, n.Left)
			sel.Left = t.generated.(Expr)
		}
		if n.Sel != nil {
			ast.Walk(t, n.Sel)
			sel.Sel = t.generated.(*Ident)
		}
		t.generated = &sel

	case *ast.Ident:
		var id Ident
		id.pos = n.Pos()
		id.scope = t.scope
		id.Name = n.Name
		id.Index = -1
		if ix, err := strconv.Atoi(n.Name); err == nil && ix >= 0 {
			id.Index = ix
		}
		t.generated = &id

	case *ast.BasicLit:
		var ce commonExpr
		ce.pos = n.Pos()
		ce.scope = t.scope

		var expr Expr
		switch n.Literal {
		case token.String:
			// TODO: currently, the string lit supports the same escapes as Go's
			val, err := strconv.Unquote(n.Value)
			if err != nil {
				panic(fmt.Sprintf("invalid string literal value for %s: %s", n.Value, err))
			}
			expr = &LitString{
				commonExpr: ce,
				Repr:       n.Value,
				Value:      val,
			}

		case token.Int:
			// TODO: currently, the integer lit only supports digits, but could be underscore and prefixes in the future
			val, err := strconv.Atoi(n.Value)
			if err != nil {
				panic(fmt.Sprintf("invalid integer literal value for %s: %s", n.Value, err))
			}
			expr = &LitInt{
				commonExpr: ce,
				Repr:       n.Value,
				Value:      val,
			}

		default:
			panic(fmt.Sprintf("invalid literal token: %s", n.Literal))
		}
		t.generated = expr

		// ************** SUPPORTING NODES *****************

	case *ast.ParamDef:
		// ParamDef are treated just like VarDecl if there is a Name, otherwise
		// just an Expr (the type).
		ve := t.buildVarOrExpr(token.Let, n.Name, n.Type)
		if v, ok := ve.(*Var); ok {
			v.Ctx = Immutable
		}
		t.generated = ve

	case *ast.ExprItem:
		// ExprItem ignores the label (it is extracted directly in CallExpr, the
		// only place where this is allowed) and returns just the Expr.
		ast.Walk(t, n.Expr)

	case *ast.Attr:
		// Attributes are translated to Call expressions.
		var call Call
		call.pos = n.Pos()
		call.scope = t.scope
		call.Labels = make([]string, len(n.Fields))
		call.Args = make([]Expr, len(n.Fields))
		call.IsAttr = true

		if n.Name != nil {
			ast.Walk(t, n.Name)
			call.Fun = t.generated.(Expr)
		}
		for i, field := range n.Fields {
			ast.Walk(t, field.Value)
			if field.Key != nil {
				call.Labels[i] = field.Key.Name
			}
			call.Args[i] = t.generated.(Expr)
		}
		t.generated = &call

	case *ast.ElseClause:
		return t

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

func (t *translateVisitor) buildVarOrExpr(kw token.Token, ident *ast.Ident, typ ast.Expr) Node {
	var v Var
	v.scope = t.scope
	if typ != nil {
		ast.Walk(t, typ)
		v.TypeExpr = t.generated.(Expr)
	}

	if ident != nil {
		v.pos = ident.Pos()
		v.ident = ident.Name
		t.registerSymbol(ident, &v, kw.String())
		return &v
	}
	return v.TypeExpr
}

func generateSelfVar(fn *Fn, body *ast.Block, bodyScope *Scope) {
	// nothing to do if there is no body
	if body == nil {
		return
	}

	/*
		// TODO: remove if that works...
			// make "self" a var if the function is a ref
			kw := token.Let
			if fn.IsRef {
				kw = token.Var
			}
			self := &ast.VarDecl{
				Kw:    kw,
				KwPos: body.Pos(),
				Name:  &ast.Ident{Name: SelfVarName, IdentPos: body.Pos()},
				Colon: body.Pos(),
				Type:  &ast.Ident{Name: fn.MethodOf.Ident(), IdentPos: body.Pos()},
			}
			body.Stmts = append([]ast.Stmt{self}, body.Stmts...)
	*/
	// just register the "self" var in the scope
	var self Var
	self.Ctx = Immutable
	if fn.IsRef {
		self.Ctx = Mutable
	}
	self.pos = body.Pos()
	self.scope = bodyScope
	self.ident = SelfVarName
	self.typ = &StructType{Decl: fn.MethodOf}
	bodyScope.Register(SelfVarName, &self)
}