about summary refs log tree commit diff
path: root/pkg/lang/vm/code/builder.go
blob: 3aa6b6bf4f14be19b2d4512eba5f01535597e8e2 (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
package code

import (
	"encoding/binary"
	"math"
)

type Builder struct {
	code      []byte
	debugInfo DebugInfo
}

func NewBuilder() Builder {
	return Builder{
		code:      make([]byte, 0, 64),
		debugInfo: NewDebugInfo("unknown file"),
	}
}

func (b *Builder) AppendOp(op Op) {
	b.code = append(b.code, byte(op))
}

func (b *Builder) AppendInt(x int64) {
	b.code = append(b.code, make([]byte, 8)...)
	binary.LittleEndian.PutUint64(b.code[len(b.code)-8:], uint64(x))
}

func (b *Builder) AppendFloat(x float64) {
	b.AppendInt(int64(math.Float64bits(x)))
}

func (b *Builder) AppendString(s string) {
	b.code = append(b.code, []byte(s)...)
	b.code = append(b.code, 0)
}

func (b *Builder) AppendRaw(raw Raw) {
	b.code = append(b.code, raw...)
}

func (b *Builder) AppendLine(line int) {
	b.debugInfo.AppendLine(len(b.code)-1, line)
}

func (b *Builder) SetInt(at int, x int64) {
	binary.LittleEndian.PutUint64(b.code[at:], uint64(x))
}

func (b *Builder) Code() Raw {
	return Raw(b.code)
}

func (b *Builder) Len() int {
	return len(b.code)
}

func (b *Builder) Build() Code {
	return New(b.code, b.debugInfo)
}