Skip to content

Commit

Permalink
fix a bug in bytecode optimization code (#292)
Browse files Browse the repository at this point in the history
* fix a bug in bytecode optimization code

* add a test
  • Loading branch information
d5 committed May 23, 2020
1 parent d08a636 commit d1dd014
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 3 deletions.
12 changes: 9 additions & 3 deletions bytecode.go
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@ func (b *Bytecode) RemoveDuplicates() {
var deduped []Object

indexMap := make(map[int]int) // mapping from old constant index to new index
fns := make(map[*CompiledFunction]int)
ints := make(map[int64]int)
strings := make(map[string]int)
floats := make(map[float64]int)
Expand All @@ -106,9 +107,14 @@ func (b *Bytecode) RemoveDuplicates() {
for curIdx, c := range b.Constants {
switch c := c.(type) {
case *CompiledFunction:
// add to deduped list
indexMap[curIdx] = len(deduped)
deduped = append(deduped, c)
if newIdx, ok := fns[c]; ok {
indexMap[curIdx] = newIdx
} else {
newIdx = len(deduped)
fns[c] = newIdx
indexMap[curIdx] = newIdx
deduped = append(deduped, c)
}
case *ImmutableMap:
modName := inferModuleName(c)
newIdx, ok := immutableMaps[modName]
Expand Down
19 changes: 19 additions & 0 deletions vm_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2654,6 +2654,25 @@ export func(a) {
expectRun(t, `out = import("mod0")`,
Opts().Module("mod0", `for v:=0;;v++ { if v == 3 { break } } }`),
tengo.UndefinedValue)

// duplicate compiled functions
// NOTE: module "mod" has a function with some local variable, and it's
// imported twice by the main script. That causes the same CompiledFunction
// put in constants twice and the Bytecode optimization (removing duplicate
// constants) should still work correctly.
expectRun(t, `
m1 := import("mod")
m2 := import("mod")
out = m1.x
`,
Opts().Module("mod", `
f1 := func(a, b) {
c := a + b + 1
return a + b + 1
}
export { x: 1 }
`),
1)
}

func TestModuleBlockScopes(t *testing.T) {
Expand Down

0 comments on commit d1dd014

Please sign in to comment.