-
Notifications
You must be signed in to change notification settings - Fork 6
/
map.go
90 lines (74 loc) · 1.4 KB
/
map.go
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
package ast
import (
"errors"
"fmt"
"sort"
"strings"
"github.com/NicoNex/tau/internal/code"
"github.com/NicoNex/tau/internal/compiler"
"github.com/NicoNex/tau/internal/obj"
)
type Map struct {
m [][2]Node
pos int
}
func NewMap(pos int, pairs ...[2]Node) Node {
return Map{
m: pairs,
pos: pos,
}
}
func (m Map) Eval() (obj.Object, error) {
return obj.NullObj, errors.New("ast.Index: not a constant expression")
}
func (m Map) String() string {
var (
buf strings.Builder
i = 1
)
buf.WriteString("{")
for _, pair := range m.m {
var (
k = pair[0]
v = pair[1]
key string
val string
)
if s, ok := k.(String); ok {
key = s.Quoted()
} else {
key = k.String()
}
if s, ok := v.(String); ok {
val = s.Quoted()
} else {
val = v.String()
}
buf.WriteString(fmt.Sprintf("%s: %s", key, val))
if i < len(m.m) {
buf.WriteString(", ")
}
i += 1
}
buf.WriteString("}")
return buf.String()
}
func (m Map) Compile(c *compiler.Compiler) (position int, err error) {
sort.Slice(m.m, func(i, j int) bool {
return m.m[i][0].String() < m.m[j][0].String()
})
for _, pair := range m.m {
if position, err = pair[0].Compile(c); err != nil {
return
}
if position, err = pair[1].Compile(c); err != nil {
return
}
}
position = c.Emit(code.OpMap, len(m.m)*2)
c.Bookmark(m.pos)
return
}
func (m Map) IsConstExpression() bool {
return false
}