summaryrefslogtreecommitdiff
path: root/parser/compiler.go
blob: e2b782378227aa1dd20e7b78f4e771c53c276717 (plain)
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
package parser

import (
	"fmt"
	"log"
	"reflect"
	"strconv"

	"github.com/gnolang/parscan/lang"
	"github.com/gnolang/parscan/scanner"
	"github.com/gnolang/parscan/vm"
)

type Compiler struct {
	*Parser
	Code  [][]int64 // produced code, to fill VM with
	Data  []any     // produced data, will be at the bottom of VM stack
	Entry int       // offset in Code to start execution from (skip function defintions)

	strings map[string]int // locations of strings in Data
}

func NewCompiler(scanner *scanner.Scanner) *Compiler {
	return &Compiler{
		Parser:  &Parser{Scanner: scanner, symbols: initUniverse(), labelCount: map[string]int{}},
		Entry:   -1,
		strings: map[string]int{},
	}
}

func (c *Compiler) Emit(op ...int64) int {
	op = append([]int64{}, op...)
	l := len(c.Code)
	c.Code = append(c.Code, op)
	return l
}

func (c *Compiler) AddSym(name string, value any) int {
	p := len(c.Data)
	c.Data = append(c.Data, value)
	c.Parser.AddSym(p, name, value)
	return p
}

func (c *Compiler) Codegen(tokens Tokens) (err error) {
	fixList := Tokens{}
	log.Println("Codegen tokens:", tokens)

	for i, t := range tokens {
		switch t.Id {
		case lang.Int:
			n, err := strconv.Atoi(t.Str)
			if err != nil {
				return err
			}
			c.Emit(int64(t.Pos), vm.Push, int64(n))

		case lang.String:
			s := t.Block()
			i, ok := c.strings[s]
			if !ok {
				i = len(c.Data)
				c.Data = append(c.Data, s)
				c.strings[s] = i
			}
			c.Emit(int64(t.Pos), vm.Dup, int64(i))

		case lang.Add:
			c.Emit(int64(t.Pos), vm.Add)

		case lang.Mul:
			c.Emit(int64(t.Pos), vm.Mul)

		case lang.Sub:
			c.Emit(int64(t.Pos), vm.Sub)

		case lang.Greater:
			c.Emit(int64(t.Pos), vm.Greater)

		case lang.Less:
			c.Emit(int64(t.Pos), vm.Lower)

		case lang.Call:
			c.Emit(int64(t.Pos), vm.Call)

		case lang.CallX:
			c.Emit(int64(t.Pos), vm.CallX, int64(t.Beg))

		case lang.Define:
			// TODO: support assignment to local, composite objects
			st := tokens[i-1]
			l := len(c.Data)
			c.Data = append(c.Data, nil)
			// TODO: symbol should be added at parse, not here.
			c.addSym(l, st.Str, nil, symVar, nil, false)
			c.Emit(int64(st.Pos), vm.Assign, int64(l))

		case lang.Assign:
			st := tokens[i-1]
			s, ok := c.symbols[st.Str]
			if !ok {
				return fmt.Errorf("symbol not found: %s", st.Str)
			}
			if s.local {
				c.Emit(int64(st.Pos), vm.Fassign, int64(s.index))
			} else {
				c.Emit(int64(st.Pos), vm.Assign, int64(s.index))
			}

		case lang.Equal:
			c.Emit(int64(t.Pos), vm.Equal)

		case lang.EqualSet:
			c.Emit(int64(t.Pos), vm.EqualSet)

		case lang.Ident:
			if i < len(tokens)-1 {
				switch t1 := tokens[i+1]; t1.Id {
				case lang.Define, lang.Assign, lang.Colon:
					continue
				}
			}
			s, ok := c.symbols[t.Str]
			if !ok {
				return fmt.Errorf("symbol not found: %s", t.Str)
			}
			if s.local {
				c.Emit(int64(t.Pos), vm.Fdup, int64(s.index))
			} else {
				if s.index < 0 {
					// This global symbol is defined but not yet used. Add it to data.
					s.index = len(c.Data)
					c.Data = append(c.Data, s.value)
				}
				c.Emit(int64(t.Pos), vm.Dup, int64(s.index))
			}

		case lang.Label:
			lc := len(c.Code)
			s, ok := c.symbols[t.Str]
			if ok {
				s.value = lc
				if s.kind == symFunc {
					// label is a function entry point, register its code address in data.
					s.index = len(c.Data)
					c.Data = append(c.Data, lc)
				} else {
					c.Data[s.index] = lc
				}
			} else {
				c.symbols[t.Str] = &symbol{kind: symLabel, value: lc}
			}

		case lang.JumpFalse:
			label := t.Str[10:]
			i := 0
			if s, ok := c.symbols[label]; !ok {
				// t.Beg contains the position in code which needs to be fixed.
				t.Beg = len(c.Code)
				fixList = append(fixList, t)
			} else {
				i = s.value.(int) - len(c.Code)
			}
			c.Emit(int64(t.Pos), vm.JumpFalse, int64(i))

		case lang.JumpSetFalse:
			label := t.Str[13:]
			i := 0
			if s, ok := c.symbols[label]; !ok {
				// t.Beg contains the position in code which needs to be fixed.
				t.Beg = len(c.Code)
				fixList = append(fixList, t)
			} else {
				i = s.value.(int) - len(c.Code)
			}
			c.Emit(int64(t.Pos), vm.JumpSetFalse, int64(i))

		case lang.JumpSetTrue:
			label := t.Str[12:]
			i := 0
			if s, ok := c.symbols[label]; !ok {
				// t.Beg contains the position in code which needs to be fixed.
				t.Beg = len(c.Code)
				fixList = append(fixList, t)
			} else {
				i = s.value.(int) - len(c.Code)
			}
			c.Emit(int64(t.Pos), vm.JumpSetTrue, int64(i))

		case lang.Goto:
			label := t.Str[5:]
			i := 0
			if s, ok := c.symbols[label]; !ok {
				t.Beg = len(c.Code)
				fixList = append(fixList, t)
			} else {
				i = s.value.(int) - len(c.Code)
			}
			c.Emit(int64(t.Pos), vm.Jump, int64(i))

		case lang.Return:
			c.Emit(int64(t.Pos), vm.Return, int64(t.Beg), int64(t.End))

		default:
			return fmt.Errorf("Codegen: unsupported token %v", t)
		}
	}

	// Finally we fix unresolved labels for jump destinations.
	for _, t := range fixList {
		var label string
		// TODO: this could be simplified.
		switch t.Id {
		case lang.Goto:
			label = t.Str[5:]
		case lang.JumpFalse:
			label = t.Str[10:]
		case lang.JumpSetFalse:
			label = t.Str[13:]
		case lang.JumpSetTrue:
			label = t.Str[12:]
		}
		s, ok := c.symbols[label]
		if !ok {
			return fmt.Errorf("label not found: %q", label)
		}
		c.Code[t.Beg][2] = int64(s.value.(int) - t.Beg)

	}
	return err
}

func (c *Compiler) PrintCode() {
	labels := map[int][]string{} // labels indexed by code location
	data := map[int]string{}     // data indexed by frame location

	for name, sym := range c.symbols {
		if sym.kind == symLabel || sym.kind == symFunc {
			i := sym.value.(int)
			labels[i] = append(labels[i], name)
		}
		if sym.used {
			data[sym.index] = name
		}
	}

	fmt.Println("# Code:")
	for i, l := range c.Code {
		for _, label := range labels[i] {
			fmt.Println(label + ":")
		}
		extra := ""
		switch l[1] {
		case vm.Jump, vm.JumpFalse, vm.JumpTrue, vm.JumpSetFalse, vm.JumpSetTrue, vm.Calli:
			if d, ok := labels[i+(int)(l[2])]; ok {
				extra = "// " + d[0]
			}
		case vm.Dup, vm.Assign, vm.Fdup, vm.Fassign:
			if d, ok := data[int(l[2])]; ok {
				extra = "// " + d
			}
		}
		fmt.Printf("%4d %-14v %v\n", i, vm.CodeString(l), extra)
	}

	for _, label := range labels[len(c.Code)] {
		fmt.Println(label + ":")
	}
	fmt.Println("# End code")
}

type entry struct {
	name string
	*symbol
}

func (c *Compiler) PrintData() {
	dict := map[int]entry{}
	for name, sym := range c.symbols {
		if !sym.used || sym.local || sym.kind == symLabel {
			continue
		}
		dict[sym.index] = entry{name, sym}
	}
	fmt.Println("# Data:")
	for i, d := range c.Data {
		fmt.Printf("%4d %T %v %v\n", i, d, d, dict[i])
	}
}

func (c *Compiler) NumIn(i int) (int, bool) {
	t := reflect.TypeOf(c.Data[i])
	if t.Kind() == reflect.Func {
		return t.NumIn(), t.IsVariadic()
	}
	return -1, false
}