Skip to content

Commit 821f089

Browse files
committed
Improve location storage in program
1 parent 05175c9 commit 821f089

File tree

3 files changed

+24
-9
lines changed

3 files changed

+24
-9
lines changed

compiler/compiler.go

+7-8
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,8 @@ func Compile(tree *parser.Tree, config *conf.Config) (program *Program, err erro
2121
}()
2222

2323
c := &compiler{
24-
index: make(map[interface{}]uint16),
24+
index: make(map[interface{}]uint16),
25+
locations: make(map[int]file.Location),
2526
}
2627
if config != nil {
2728
c.mapEnv = config.MapEnv
@@ -47,7 +48,7 @@ func Compile(tree *parser.Tree, config *conf.Config) (program *Program, err erro
4748
}
4849

4950
type compiler struct {
50-
locations []file.Location
51+
locations map[int]file.Location
5152
constants []interface{}
5253
bytecode []byte
5354
index map[interface{}]uint16
@@ -61,13 +62,11 @@ func (c *compiler) emit(op byte, b ...byte) int {
6162
current := len(c.bytecode)
6263
c.bytecode = append(c.bytecode, b...)
6364

64-
for i := 0; i < 1+len(b); i++ {
65-
var loc file.Location
66-
if len(c.nodes) > 0 {
67-
loc = c.nodes[len(c.nodes)-1].Location()
68-
}
69-
c.locations = append(c.locations, loc)
65+
var loc file.Location
66+
if len(c.nodes) > 0 {
67+
loc = c.nodes[len(c.nodes)-1].Location()
7068
}
69+
c.locations[current-1] = loc
7170

7271
return current
7372
}

vm/program.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ import (
1010

1111
type Program struct {
1212
Source *file.Source
13-
Locations []file.Location
13+
Locations map[int]file.Location
1414
Constants []interface{}
1515
Bytecode []byte
1616
}

vm/vm_test.go

+16
Original file line numberDiff line numberDiff line change
@@ -107,3 +107,19 @@ func TestRun_memory_budget(t *testing.T) {
107107
_, err = vm.Run(program, nil)
108108
require.Error(t, err)
109109
}
110+
111+
func TestRun_runtime_error(t *testing.T) {
112+
input := `map(1..3, {1/(#-3)})`
113+
114+
tree, err := parser.Parse(input)
115+
require.NoError(t, err)
116+
117+
program, err := compiler.Compile(tree, nil)
118+
require.NoError(t, err)
119+
120+
_, err = vm.Run(program, nil)
121+
require.Error(t, err)
122+
require.Equal(t, `runtime error: integer divide by zero (1:13)
123+
| map(1..3, {1/(#-3)})
124+
| ............^`, err.Error())
125+
}

0 commit comments

Comments
 (0)