Pārlūkot izejas kodu

Added Runtime.MustCompile()

Dmitry Panov 8 gadi atpakaļ
vecāks
revīzija
d382686fd2
3 mainītis faili ar 16 papildinājumiem un 20 dzēšanām
  1. 11 0
      runtime.go
  2. 3 12
      runtime_test.go
  3. 2 8
      vm_test.go

+ 11 - 0
runtime.go

@@ -681,6 +681,17 @@ func Compile(name, src string, strict bool) (p *Program, err error) {
 	return compile(name, src, strict, false)
 }
 
+// MustCompile is like Compile but panics if the code cannot be compiled.
+// It simplifies safe initialization of global variables holding compiled JavaScript code.
+func MustCompile(name, src string, strict bool) *Program {
+	prg, err := Compile(name, src, strict)
+	if err != nil {
+		panic(err)
+	}
+
+	return prg
+}
+
 func compile(name, src string, strict, eval bool) (p *Program, err error) {
 	prg, err1 := parser.ParseFile(nil, name, src, 0)
 	if err1 != nil {

+ 3 - 12
runtime_test.go

@@ -751,10 +751,7 @@ func TestNilCallArg(t *testing.T) {
 	}
 	`
 	vm := New()
-	prg, err := Compile("test.js", SCRIPT, false)
-	if err != nil {
-		t.Fatal(err)
-	}
+	prg := MustCompile("test.js", SCRIPT, false)
 	vm.RunProgram(prg)
 	if f, ok := AssertFunction(vm.Get("f")); ok {
 		v, err := f(nil, nil)
@@ -772,10 +769,7 @@ func TestNullCallArg(t *testing.T) {
 	f(null);
 	`
 	vm := New()
-	prg, err := Compile("test.js", SCRIPT, false)
-	if err != nil {
-		t.Fatal(err)
-	}
+	prg := MustCompile("test.js", SCRIPT, false)
 	vm.Set("f", func(x *int) bool {
 		return x == nil
 	})
@@ -797,10 +791,7 @@ func TestObjectKeys(t *testing.T) {
 	`
 
 	vm := New()
-	prg, err := Compile("test.js", SCRIPT, false)
-	if err != nil {
-		t.Fatal(err)
-	}
+	prg := MustCompile("test.js", SCRIPT, false)
 
 	res, err := vm.RunProgram(prg)
 	if err != nil {

+ 2 - 8
vm_test.go

@@ -343,10 +343,7 @@ func BenchmarkEmptyLoop(b *testing.B) {
 	`
 	b.StopTimer()
 	vm := New()
-	prg, err := Compile("test.js", SCRIPT, false)
-	if err != nil {
-		b.Fatal(err)
-	}
+	prg := MustCompile("test.js", SCRIPT, false)
 	// prg.dumpCode(log.Printf)
 	b.StartTimer()
 	for i := 0; i < b.N; i++ {
@@ -379,10 +376,7 @@ func BenchmarkFuncCall(b *testing.B) {
 	b.StopTimer()
 
 	vm := New()
-	prg, err := Compile("test.js", SCRIPT, false)
-	if err != nil {
-		b.Fatal(err)
-	}
+	prg := MustCompile("test.js", SCRIPT, false)
 
 	vm.RunProgram(prg)
 	if f, ok := AssertFunction(vm.Get("f")); ok {