about summary refs log tree commit diff
path: root/pkg/lang/vm/text/compiler.go
blob: 1480171994bf7e7fb11824d2657c6d6d1f0a7c08 (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
package text

import (
	"encoding/binary"
	"io"
	"jinx/pkg/lang/vm/code"
	"jinx/pkg/libs/source"
	"math"
	"strconv"
	"strings"
	"unicode"
)

type Compiler struct {
	src     source.Walker
	codePos int

	labelPositions  map[string]int
	labelReferences []labelReference
}

func NewCompiler(src io.Reader) *Compiler {
	return &Compiler{
		src:     *source.NewWalker(src),
		codePos: 0,

		labelPositions:  map[string]int{},
		labelReferences: []labelReference{},
	}
}

func (cpl *Compiler) Compile() (code.Code, error) {
	res := []byte{}
	info := code.NewDebugInfo("unknown file")

	for {
		_, eof, err := cpl.src.Peek()
		if err != nil {
			return code.Code{}, err
		}

		if eof {
			break
		}

		line, err := cpl.compileLine()
		if err != nil {
			return code.Code{}, err
		}

		cpl.codePos += len(line)

		if line != nil {
			info.AppendLine(cpl.codePos-1, cpl.src.Loc().Row-1)
		}

		res = append(res, line...)
	}

	if err := cpl.linkLabels(res); err != nil {
		return code.Code{}, err
	}

	return code.New(res, info), nil
}

func (cpl *Compiler) compileLine() ([]byte, error) {
	res := []byte{}

	start, value, err := cpl.splitLine()
	if err != nil || start == "" {
		return nil, err
	}

	// Ignore lines starting with a comment.
	if start[0] == '#' {
		return nil, nil
	}

	// Save the position of the label.
	if start[0] == '@' {
		label := strings.Trim(start, "@:")
		if _, ok := cpl.labelPositions[label]; ok {
			return nil, ErrDuplicateLabel{label}
		}
		cpl.labelPositions[label] = cpl.codePos
		return nil, nil
	}

	// Find the operator.
	op, err := cpl.compileOp(start)
	if err != nil {
		return nil, err
	}

	res = append(res, byte(op))

	// Find the value, of which there is at most one.
	if value != "" {
		val, err := cpl.compileValue(value)
		if err != nil {
			return nil, err
		}

		res = append(res, val...)
	}

	return res, nil
}

func (cpl *Compiler) compileOp(str string) (code.Op, error) {
	op, err := StringToOp(str)
	if err != nil {
		return 0, err
	}

	return op, nil
}

func (cpl *Compiler) compileValue(str string) ([]byte, error) {
	res := make([]byte, 8)

	// Save label reference.
	if str[0] == '@' {
		label := strings.Trim(str, "@:")
		cpl.labelReferences = append(cpl.labelReferences, labelReference{
			label: label,
			at:    cpl.codePos + 1, // +1 to skip the opcode.
		})
		return res, nil
	}

	if unicode.IsDigit(rune(str[0])) || str[0] == '-' {
		if strings.Contains(str, ".") {
			val, err := strconv.ParseFloat(str, 64)
			if err != nil {
				return res, err
			}

			binary.LittleEndian.PutUint64(res, math.Float64bits(val))
		} else {
			val, err := strconv.ParseInt(str, 10, 64)
			if err != nil {
				return res, err
			}

			binary.LittleEndian.PutUint64(res, uint64(val))
		}

		return res, nil
	}

	if str[0] == '"' {
		str = strings.Trim(str, "\"")
		res = []byte(str)
		res = append(res, 0)

		return res, nil
	}

	return res, ErrInvalidValue{str}
}

func (cpl *Compiler) splitLine() (string, string, error) {
	line := ""

	for {
		c, eof, err := cpl.src.Next()
		if err != nil {
			return "", "", err
		}

		if eof || c == '\n' {
			break
		}

		line += string(c)
	}

	fields := strings.Fields(line)
	if len(fields) == 0 {
		return "", "", nil
	}

	start := fields[0]
	if len(fields) > 1 {
		return start, strings.Join(fields[1:], " "), nil
	}

	return start, "", nil
}

type labelReference struct {
	label string
	at    int
}

func (cpl *Compiler) linkLabels(code []byte) error {
	for _, ref := range cpl.labelReferences {
		pos, ok := cpl.labelPositions[ref.label]
		if !ok {
			return ErrUnkonwnLabel{ref.label}
		}

		binary.LittleEndian.PutUint64(code[ref.at:], uint64(pos))
	}
	return nil
}