Browse Source

Used sort.Search() in sourceOffset() (fixes #31)

Dmitry Panov 8 years ago
parent
commit
9e958edb3c
2 changed files with 18 additions and 9 deletions
  1. 8 9
      compiler.go
  2. 10 0
      compiler_test.go

+ 8 - 9
compiler.go

@@ -4,6 +4,7 @@ import (
 	"fmt"
 	"github.com/dop251/goja/ast"
 	"github.com/dop251/goja/file"
+	"sort"
 	"strconv"
 )
 
@@ -158,16 +159,14 @@ func (p *Program) _dumpCode(indent string, logger func(format string, args ...in
 }
 
 func (p *Program) sourceOffset(pc int) int {
-	// TODO use sort.Search()
-	for i, item := range p.srcMap {
-		if item.pc > pc {
-			if i > 0 {
-				return p.srcMap[i-1].srcPos
-			}
-			return 0
-		}
+	i := sort.Search(len(p.srcMap), func(idx int) bool {
+		return p.srcMap[idx].pc > pc
+	}) - 1
+	if i >= 0 {
+		return p.srcMap[i].srcPos
 	}
-	return p.srcMap[len(p.srcMap)-1].srcPos
+
+	return 0
 }
 
 func (s *scope) isFunction() bool {

+ 10 - 0
compiler_test.go

@@ -1797,6 +1797,16 @@ func TestObjectLiteral__Proto__(t *testing.T) {
 	testScript1(SCRIPT, _null, t)
 }
 
+func TestEmptyCodeError(t *testing.T) {
+	if _, err := New().RunString(`i`); err == nil {
+		t.Fatal("Expected an error")
+	} else {
+		if e := err.Error(); e != "ReferenceError: i is not defined at <eval>:1:1(0)" {
+			t.Fatalf("Unexpected error: '%s'", e)
+		}
+	}
+}
+
 // FIXME
 /*
 func TestDummyCompile(t *testing.T) {