From 5dd10d115fb1b55f4e8420cd36ced13009c39f02 Mon Sep 17 00:00:00 2001 From: Roger Chapman Date: Tue, 23 Mar 2021 17:38:37 +1100 Subject: [PATCH] Allow setting/unsetting of V8 feature flags --- v8go.cc | 6 +++++- v8go.go | 15 +++++++++++++++ v8go.h | 1 + v8go_test.go | 16 ++++++++++++++++ 4 files changed, 37 insertions(+), 1 deletion(-) diff --git a/v8go.cc b/v8go.cc index 19f09058..1a44c3df 100644 --- a/v8go.cc +++ b/v8go.cc @@ -1148,9 +1148,13 @@ ValuePtr ExceptionTypeError(IsolatePtr iso_ptr, const char* message) { return static_cast(val); } -/********** Version **********/ +/********** v8::V8 **********/ const char* Version() { return V8::GetVersion(); } + +void SetFlags(const char* flags) { + V8::SetFlagsFromString(flags); +} } diff --git a/v8go.go b/v8go.go index aa36d2fd..32990558 100644 --- a/v8go.go +++ b/v8go.go @@ -8,9 +8,24 @@ Package v8go provides an API to execute JavaScript. package v8go // #include "v8go.h" +// #include import "C" +import ( + "strings" + "unsafe" +) // Version returns the version of the V8 Engine with the -v8go suffix func Version() string { return C.GoString(C.Version()) } + +// SetFlags sets flags for V8. For possible flags: https://github.com/v8/v8/blob/master/src/flags/flag-definitions.h +// Flags are expected to be prefixed with `--`, for example: `--harmony`. +// Flags can be reverted using the `--no` prefix equivalent, for example: `--use_strict` vs `--nouse_strict`. +// Flags will affect all Isolates created, even after creation. +func SetFlags(flags ...string) { + cflags := C.CString(strings.Join(flags, " ")) + C.SetFlags(cflags) + C.free(unsafe.Pointer(cflags)) +} diff --git a/v8go.h b/v8go.h index f7677476..68fb52fe 100644 --- a/v8go.h +++ b/v8go.h @@ -181,6 +181,7 @@ extern ValuePtr ExceptionSyntaxError(IsolatePtr iso_ptr, const char* message); extern ValuePtr ExceptionTypeError(IsolatePtr iso_ptr, const char* message); const char* Version(); +extern void SetFlags(const char* flags); #ifdef __cplusplus } // extern "C" diff --git a/v8go_test.go b/v8go_test.go index 89d04d63..8d9df283 100644 --- a/v8go_test.go +++ b/v8go_test.go @@ -19,3 +19,19 @@ func TestVersion(t *testing.T) { t.Errorf("version string is in the incorrect format: %s", v) } } + +func TestSetFlag(t *testing.T) { + t.Parallel() + ctx, _ := v8go.NewContext() + if _, err := ctx.RunScript("a = 1", "default.js"); err != nil { + t.Errorf("expected error, but got: %v", err) + } + v8go.SetFlags("--use_strict") + if _, err := ctx.RunScript("b = 1", "use_strict.js"); err == nil { + t.Error("expected error but got ") + } + v8go.SetFlags("--nouse_strict") + if _, err := ctx.RunScript("c = 1", "nouse_strict.js"); err != nil { + t.Errorf("expected error, but got: %v", err) + } +}