v8

package module
v0.0.0-...-b246692 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 10, 2013 License: MIT Imports: 5 Imported by: 0

README

Go-V8

V8 JavaScript engine bindings for Go.

Features

  • Thread safe
  • Thorough and careful testing
  • Boolean, Number, String, Object, Array, Regexp, Function
  • Compile and run JavaScript
  • Save and load pre-compiled script data
  • Create JavaScript context with global object template
  • Operate JavaScript object properties and array elements in Go
  • Define JavaScript object template in Go with property accessors and interceptors
  • Define JavaScript function template in Go
  • Catch JavaScript exception in Go
  • Throw JavaScript exception by Go
  • JSON parse and generate

Install

For 'curl' user. please run this shell command:

curl -O https://raw.github.com/idada/go-v8/master/get.sh && chmod +x get.sh && ./get.sh go-v8

For 'wget' user. Please run this shell command:

wget https://raw.github.com/idada/go-v8/master/get.sh && chmod +x get.sh && ./get.sh go-v8

Note: require Go version 1.2 and Git.

Hello World

This 'Hello World' program shows how to use go-v8 to compile and run JavaScript code then get the result.

package main

import "github.com/idada/go-v8"

func main() {
	engine := v8.NewEngine()
	script := engine.Compile([]byte("'Hello ' + 'World!'"), nil, nil)
	context := engine.NewContext(nil)

	context.Scope(func(cs v8.ContextScope) {
		result := script.Run()
		println(result.ToString())
	})
}

Performance and Stability

The benchmark result on my iMac:

NewContext     249474 ns/op
NewInteger        984 ns/op
NewString         983 ns/op
NewObject        1036 ns/op
NewArray0        1130 ns/op
NewArray5        1314 ns/op
NewArray20       1666 ns/op
NewArray100      3124 ns/op
Compile         11059 ns/op
PreCompile      11697 ns/op
RunScript        1085 ns/op
JsFunction       1114 ns/op
GoFunction       1630 ns/op
Getter           2060 ns/op
Setter           2934 ns/op
TryCatch        43097 ns/op

I write many test and benchmark to make sure go-v8 stable and efficient.

There is a shell script named 'test.sh' in the project.

It can auto configure cgo environment variables and run test.

For example:

./test.sh . .

The above command will run all of test and benchmark.

The first argument of test.sh is test name pattern, second argument is benchmark name pattern.

For example:

./test.sh ThreadSafe Array

The above command will run all of thread safe test and all of benchmark about Array type.

Concepts

Engine

In go-v8, engine type is the wrapper of v8::Isolate.

Because V8 engine use thread-local storage but cgo calls may be execute in different thread. So go-v8 use v8::Locker to make sure V8 engine's thread-local data initialized. And the locker make go-v8 thread safe.

You can create different engine instance for data isolate or improve efficiency of concurrent purpose.

engine1 := v8.NewEngine()
engine2 := v8.NewEngine()

Script

When you want to run some JavaScript. You need to compile first.

Scripts can run many times or run in different context.

script := engine.Compile([]byte(`"Hello " + "World!"`), nil, nil)

The Engine.Compile() method take 3 arguments.

The first is the code.

The second is a ScriptOrigin, it stores script's file name or line number offset etc. You can use ScriptOrigin to make error message and stack trace friendly.

name := "my_file.js"
real := ReadFile(name)
code := "function(_export){\n" + real + "\n}"
origin := engine.NewScriptOrigin(name, 1, 0)
script := engine.Compile(code, origin, nil)

The third is a ScriptData, it's pre-parsing data, as obtained by Engine.PreCompile(). If you want to compile a script many time, you can use ScriptData to speeds compilation.

code := []byte(`"Hello " + "World!"`)
data := engine.PreCompile(code)
script1 := engine.Compile(code, nil, data)
script2 := engine.Compile(code, nil, data)

Context

The description in V8 embedding guide:

In V8, a context is an execution environment that allows separate, unrelated, JavaScript applications to run in a single instance of V8. You must explicitly specify the context in which you want any JavaScript code to be run.

In go-v8, you can create many contexts from a V8 engine instance. When you want to run some JavaScript in a context. You need to enter the context by calling Scope() and run the JavaScript in the callback.

context.Scope(func(cs v8.ContextScope){
	script.Run()
})

Context in V8 is necessary. So in go-v8 you can do this:

context.Scope(func(cs v8.ContextScope) {
	context2 := engine.NewContext(nil)
	context2.Scope(func(cs2 v8.ContextScope) {

	})
})

Please note. Don't take any JavaScript value out scope.

When the outermost Scope() return, all of the JavaScript value created in this scope or nested scope will be destroyed.

More

Please read 'v8_all_test.go' for more information.

Documentation

Index

Constants

View Source
const (
	PA_None       PropertyAttribute = 0
	PA_ReadOnly                     = 1 << 0
	PA_DontEnum                     = 1 << 1
	PA_DontDelete                   = 1 << 2
)
View Source
const (
	RF_None       RegExpFlags = 0
	RF_Global                 = 1
	RF_IgnoreCase             = 2
	RF_Multiline              = 4
)

Regular expression flag bits. They can be or'ed to enable a set of flags.

View Source
const (
	AC_DEFAULT               AccessControl = 0
	AC_ALL_CAN_READ                        = 1
	AC_ALL_CAN_WRITE                       = 1 << 1
	AC_PROHIBITS_OVERWRITING               = 1 << 2
)

Access control specifications.

Some accessors should be accessible across contexts. These accessors have an explicit access control parameter which specifies the kind of cross-context access that should be allowed.

Additionally, for security, accessors can prohibit overwriting by accessors defined in JavaScript. For objects that have such accessors either locally or in their prototype chain it is not possible to overwrite the accessor by using __defineGetter__ or __defineSetter__ from JavaScript code.

Variables

This section is empty.

Functions

func AppendJSON

func AppendJSON(dst []byte, value *Value) []byte

func GetVersion

func GetVersion() string

func SetArrayBufferAllocator

func SetArrayBufferAllocator(
	ac ArrayBufferAllocateCallback,
	fc ArrayBufferFreeCallback)

Call SetArrayBufferAllocator first if you want use any of ArrayBuffer, ArrayBufferView, Int8Array... Please be sure to call this function once and keep allocator Please set ac and fc to nil if you don't want a custom one

func SetCaptureStackTraceForUncaughtExceptions

func SetCaptureStackTraceForUncaughtExceptions(capture bool, frameLimit int)

func SetFlagsFromString

func SetFlagsFromString(cmd string)

func ToJSON

func ToJSON(value *Value) []byte

Types

type AccessControl

type AccessControl int

type AccessorCallbackInfo

type AccessorCallbackInfo struct {
	// contains filtered or unexported fields
}

Property getter callback info

func (AccessorCallbackInfo) CurrentScope

func (ac AccessorCallbackInfo) CurrentScope() ContextScope

func (AccessorCallbackInfo) Data

func (ac AccessorCallbackInfo) Data() interface{}

func (AccessorCallbackInfo) Holder

func (ac AccessorCallbackInfo) Holder() *Object

func (*AccessorCallbackInfo) ReturnValue

func (ac *AccessorCallbackInfo) ReturnValue() ReturnValue

func (AccessorCallbackInfo) This

func (ac AccessorCallbackInfo) This() *Object

type AccessorGetterCallback

type AccessorGetterCallback func(name string, info AccessorCallbackInfo)

type AccessorSetterCallback

type AccessorSetterCallback func(name string, value *Value, info AccessorCallbackInfo)

type Array

type Array struct {
	*Object
}

An instance of the built-in array constructor (ECMA-262, 15.4.2).

func (*Array) Length

func (a *Array) Length() int

type ArrayBufferAllocateCallback

type ArrayBufferAllocateCallback func(int, bool) unsafe.Pointer

type ArrayBufferAllocator

type ArrayBufferAllocator struct {
	// contains filtered or unexported fields
}

type ArrayBufferFreeCallback

type ArrayBufferFreeCallback func(unsafe.Pointer, int)

type Context

type Context struct {
	// contains filtered or unexported fields
}

A sandboxed execution context with its own set of built-in objects and functions.

func (Context) GetPrivateData

func (this Context) GetPrivateData() interface{}

func (*Context) Scope

func (c *Context) Scope(callback func(ContextScope))

func (*Context) SetPrivateData

func (this *Context) SetPrivateData(data interface{})

type ContextScope

type ContextScope struct {
	// contains filtered or unexported fields
}

func (ContextScope) AddMessageListener

func (cs ContextScope) AddMessageListener(simple bool, callback MessageCallback, data interface{})

func (ContextScope) Eval

func (cs ContextScope) Eval(code string) *Value

func (ContextScope) GetEngine

func (cs ContextScope) GetEngine() *Engine

func (ContextScope) GetPrivateData

func (cs ContextScope) GetPrivateData() interface{}

func (ContextScope) Global

func (cs ContextScope) Global() *Object

func (ContextScope) NewArray

func (cs ContextScope) NewArray(length int) *Array

func (ContextScope) NewBoolean

func (cs ContextScope) NewBoolean(value bool) *Value

func (ContextScope) NewInteger

func (cs ContextScope) NewInteger(value int64) *Value

func (ContextScope) NewNumber

func (cs ContextScope) NewNumber(value float64) *Value

func (*ContextScope) NewObject

func (cs *ContextScope) NewObject() *Value

func (ContextScope) NewRegExp

func (cs ContextScope) NewRegExp(pattern string, flags RegExpFlags) *Value

Creates a regular expression from the given pattern string and the flags bit field. May throw a JavaScript exception as described in ECMA-262, 15.10.4.1.

For example,

NewRegExp("foo", RF_Global | RF_Multiline)

is equivalent to evaluating "/foo/gm".

func (ContextScope) NewString

func (cs ContextScope) NewString(value string) *Value

func (ContextScope) ParseJSON

func (cs ContextScope) ParseJSON(json string) *Value

func (ContextScope) SetPrivateData

func (cs ContextScope) SetPrivateData(data interface{})

func (ContextScope) ThrowException

func (cs ContextScope) ThrowException(err string)

func (ContextScope) TryCatch

func (cs ContextScope) TryCatch(simple bool, callback func()) string

type Engine

type Engine struct {
	// contains filtered or unexported fields
}

Represents an isolated instance of the V8 engine. Objects from one engine must not be used in other engine.

func NewEngine

func NewEngine() *Engine

func (*Engine) Compile

func (e *Engine) Compile(code []byte, origin *ScriptOrigin, data *ScriptData) *Script

Compiles the specified script (context-independent). 'data' is the Pre-parsing data, as obtained by PreCompile() using pre_data speeds compilation if it's done multiple times.

func (*Engine) False

func (e *Engine) False() *Value

func (Engine) GetPrivateData

func (this Engine) GetPrivateData() interface{}

func (*Engine) NewContext

func (e *Engine) NewContext(globalTemplate *ObjectTemplate) *Context

func (*Engine) NewFunctionTemplate

func (e *Engine) NewFunctionTemplate(callback FunctionCallback, data interface{}) *FunctionTemplate

func (*Engine) NewObjectTemplate

func (e *Engine) NewObjectTemplate() *ObjectTemplate

func (*Engine) NewScriptOrigin

func (e *Engine) NewScriptOrigin(name string, lineOffset, columnOffset int) *ScriptOrigin

func (*Engine) Null

func (e *Engine) Null() *Value

func (*Engine) PreCompile

func (e *Engine) PreCompile(code []byte) *ScriptData

Pre-compiles the specified script (context-independent).

func (*Engine) SetPrivateData

func (this *Engine) SetPrivateData(data interface{})

func (*Engine) True

func (e *Engine) True() *Value

func (*Engine) Undefined

func (e *Engine) Undefined() *Value

type Function

type Function struct {
	*Object
}

A JavaScript function object (ECMA-262, 15.3).

func (*Function) Call

func (f *Function) Call(args ...*Value) *Value

type FunctionCallback

type FunctionCallback func(FunctionCallbackInfo)

type FunctionCallbackInfo

type FunctionCallbackInfo struct {
	// contains filtered or unexported fields
}

Function callback info

func (FunctionCallbackInfo) Callee

func (fc FunctionCallbackInfo) Callee() *Function

func (FunctionCallbackInfo) CurrentScope

func (fc FunctionCallbackInfo) CurrentScope() ContextScope

func (FunctionCallbackInfo) Data

func (fc FunctionCallbackInfo) Data() interface{}

func (FunctionCallbackInfo) Get

func (fc FunctionCallbackInfo) Get(i int) *Value

func (FunctionCallbackInfo) Holder

func (fc FunctionCallbackInfo) Holder() *Object

func (FunctionCallbackInfo) Length

func (fc FunctionCallbackInfo) Length() int

func (*FunctionCallbackInfo) ReturnValue

func (fc *FunctionCallbackInfo) ReturnValue() ReturnValue

func (FunctionCallbackInfo) This

func (fc FunctionCallbackInfo) This() *Object

type FunctionTemplate

type FunctionTemplate struct {
	sync.Mutex
	// contains filtered or unexported fields
}

func (*FunctionTemplate) Dispose

func (ft *FunctionTemplate) Dispose()

func (*FunctionTemplate) InstanceTemplate

func (ft *FunctionTemplate) InstanceTemplate() *ObjectTemplate

func (*FunctionTemplate) NewFunction

func (ft *FunctionTemplate) NewFunction() *Value

func (*FunctionTemplate) SetClassName

func (ft *FunctionTemplate) SetClassName(name string)

type IndexedPropertyDeleterCallback

type IndexedPropertyDeleterCallback func(uint32, PropertyCallbackInfo)

type IndexedPropertyEnumeratorCallback

type IndexedPropertyEnumeratorCallback func(PropertyCallbackInfo)

type IndexedPropertyGetterCallback

type IndexedPropertyGetterCallback func(uint32, PropertyCallbackInfo)

type IndexedPropertyQueryCallback

type IndexedPropertyQueryCallback func(uint32, PropertyCallbackInfo)

type IndexedPropertySetterCallback

type IndexedPropertySetterCallback func(uint32, *Value, PropertyCallbackInfo)

type MessageCallback

type MessageCallback func(message string, data interface{})

type NamedPropertyDeleterCallback

type NamedPropertyDeleterCallback func(string, PropertyCallbackInfo)

type NamedPropertyEnumeratorCallback

type NamedPropertyEnumeratorCallback func(PropertyCallbackInfo)

type NamedPropertyGetterCallback

type NamedPropertyGetterCallback func(string, PropertyCallbackInfo)

type NamedPropertyQueryCallback

type NamedPropertyQueryCallback func(string, PropertyCallbackInfo)

type NamedPropertySetterCallback

type NamedPropertySetterCallback func(string, *Value, PropertyCallbackInfo)

type Object

type Object struct {
	*Value
}

A JavaScript object (ECMA-262, 4.3.3)

func (*Object) DeleteElement

func (o *Object) DeleteElement(index int) bool

func (*Object) DeleteProperty

func (o *Object) DeleteProperty(key string) bool

func (*Object) ForceDeleteProperty

func (o *Object) ForceDeleteProperty(key string) bool

Delete a property on this object bypassing interceptors and ignoring dont-delete attributes.

func (*Object) ForceSetProperty

func (o *Object) ForceSetProperty(key string, value *Value, attribs PropertyAttribute) bool

Sets a local property on this object bypassing interceptors and overriding accessors or read-only properties.

Note that if the object has an interceptor the property will be set locally, but since the interceptor takes precedence the local property will only be returned if the interceptor doesn't return a value.

Note also that this only works for named properties.

func (*Object) GetElement

func (o *Object) GetElement(index int) *Value

func (*Object) GetInternalField

func (o *Object) GetInternalField(index int) interface{}

func (*Object) GetOwnPropertyNames

func (o *Object) GetOwnPropertyNames() *Array

This function has the same functionality as GetPropertyNames but the returned array doesn't contain the names of properties from prototype objects.

func (*Object) GetProperty

func (o *Object) GetProperty(key string) *Value

func (*Object) GetPropertyAttributes

func (o *Object) GetPropertyAttributes(key string) PropertyAttribute

func (*Object) GetPropertyNames

func (o *Object) GetPropertyNames() *Array

Returns an array containing the names of the enumerable properties of this object, including properties from prototype objects. The array returned by this method contains the same values as would be enumerated by a for-in statement over this object.

func (*Object) GetPrototype

func (o *Object) GetPrototype() *Object

Get the prototype object. This does not skip objects marked to be skipped by __proto__ and it does not consult the security handler.

func (*Object) HasElement

func (o *Object) HasElement(index int) bool

func (*Object) HasProperty

func (o *Object) HasProperty(key string) bool

func (*Object) InternalFieldCount

func (o *Object) InternalFieldCount() int

func (*Object) SetElement

func (o *Object) SetElement(index int, value *Value) bool

func (*Object) SetInternalField

func (o *Object) SetInternalField(index int, value interface{})

func (*Object) SetProperty

func (o *Object) SetProperty(key string, value *Value, attribs PropertyAttribute) bool

func (*Object) SetPrototype

func (o *Object) SetPrototype(proto *Object) bool

Set the prototype object. This does not skip objects marked to be skipped by __proto__ and it does not consult the security handler.

type ObjectTemplate

type ObjectTemplate struct {
	sync.Mutex
	// contains filtered or unexported fields
}

func (*ObjectTemplate) Dispose

func (ot *ObjectTemplate) Dispose()

func (*ObjectTemplate) InternalFieldCount

func (ot *ObjectTemplate) InternalFieldCount() int

func (*ObjectTemplate) NewObject

func (ot *ObjectTemplate) NewObject() *Value

func (*ObjectTemplate) SetAccessor

func (ot *ObjectTemplate) SetAccessor(
	key string,
	getter AccessorGetterCallback,
	setter AccessorSetterCallback,
	data interface{},
	attribs PropertyAttribute,
)

func (*ObjectTemplate) SetIndexedPropertyHandler

func (ot *ObjectTemplate) SetIndexedPropertyHandler(
	getter IndexedPropertyGetterCallback,
	setter IndexedPropertySetterCallback,
	query IndexedPropertyQueryCallback,
	deleter IndexedPropertyDeleterCallback,
	enumerator IndexedPropertyEnumeratorCallback,
	data interface{},
)

func (*ObjectTemplate) SetInternalFieldCount

func (ot *ObjectTemplate) SetInternalFieldCount(count int)

func (*ObjectTemplate) SetNamedPropertyHandler

func (ot *ObjectTemplate) SetNamedPropertyHandler(
	getter NamedPropertyGetterCallback,
	setter NamedPropertySetterCallback,
	query NamedPropertyQueryCallback,
	deleter NamedPropertyDeleterCallback,
	enumerator NamedPropertyEnumeratorCallback,
	data interface{},
)

func (*ObjectTemplate) SetProperty

func (ot *ObjectTemplate) SetProperty(key string, value *Value, attribs PropertyAttribute)

func (*ObjectTemplate) WrapObject

func (ot *ObjectTemplate) WrapObject(value *Value)

type PropertyAttribute

type PropertyAttribute int

type PropertyCallbackInfo

type PropertyCallbackInfo struct {
	// contains filtered or unexported fields
}

func (PropertyCallbackInfo) CurrentScope

func (p PropertyCallbackInfo) CurrentScope() ContextScope

func (PropertyCallbackInfo) Data

func (p PropertyCallbackInfo) Data() interface{}

func (PropertyCallbackInfo) Holder

func (p PropertyCallbackInfo) Holder() *Object

func (PropertyCallbackInfo) ReturnValue

func (p PropertyCallbackInfo) ReturnValue() ReturnValue

func (PropertyCallbackInfo) This

func (p PropertyCallbackInfo) This() *Object

type RegExp

type RegExp struct {
	*Object
	// contains filtered or unexported fields
}

func (*RegExp) Flags

func (r *RegExp) Flags() RegExpFlags

Returns the flags bit field.

func (*RegExp) Pattern

func (r *RegExp) Pattern() string

Returns the value of the source property: a string representing the regular expression.

type RegExpFlags

type RegExpFlags int

type ReturnValue

type ReturnValue struct {
	// contains filtered or unexported fields
}

Function and property return value

func (ReturnValue) Set

func (rv ReturnValue) Set(value *Value)

func (ReturnValue) SetBoolean

func (rv ReturnValue) SetBoolean(value bool)

func (ReturnValue) SetInt32

func (rv ReturnValue) SetInt32(value int32)

func (ReturnValue) SetNull

func (rv ReturnValue) SetNull()

func (ReturnValue) SetNumber

func (rv ReturnValue) SetNumber(value float64)

func (ReturnValue) SetString

func (rv ReturnValue) SetString(value string)

func (ReturnValue) SetUint32

func (rv ReturnValue) SetUint32(value uint32)

func (ReturnValue) SetUndefined

func (rv ReturnValue) SetUndefined()

type Script

type Script struct {
	// contains filtered or unexported fields
}

A compiled JavaScript script.

func (*Script) Run

func (s *Script) Run() *Value

Runs the script returning the resulting value.

type ScriptData

type ScriptData struct {
	// contains filtered or unexported fields
}

Pre-compilation data that can be associated with a script. This data can be calculated for a script in advance of actually compiling it, and can be stored between compilations. When script data is given to the compile method compilation will be faster.

func NewScriptData

func NewScriptData(data []byte) *ScriptData

Load previous pre-compilation data.

func (*ScriptData) Data

func (sd *ScriptData) Data() []byte

Returns a serialized representation of this ScriptData that can later be passed to New(). NOTE: Serialized data is platform-dependent.

func (*ScriptData) HasError

func (sd *ScriptData) HasError() bool

Returns true if the source code could not be parsed.

func (*ScriptData) Length

func (sd *ScriptData) Length() int

Returns the length of Data().

type ScriptOrigin

type ScriptOrigin struct {
	Name         string
	LineOffset   int
	ColumnOffset int
	// contains filtered or unexported fields
}

The origin, within a file, of a script.

type Value

type Value struct {
	// contains filtered or unexported fields
}

The superclass of all JavaScript values and objects.

func (*Value) IsArray

func (v *Value) IsArray() bool

func (*Value) IsBoolean

func (v *Value) IsBoolean() bool

func (*Value) IsBooleanObject

func (v *Value) IsBooleanObject() bool

func (*Value) IsDate

func (v *Value) IsDate() bool

func (*Value) IsExternal

func (v *Value) IsExternal() bool

func (*Value) IsFalse

func (v *Value) IsFalse() bool

func (*Value) IsFunction

func (v *Value) IsFunction() bool

func (*Value) IsInt32

func (v *Value) IsInt32() bool

func (*Value) IsNativeError

func (v *Value) IsNativeError() bool

func (*Value) IsNull

func (v *Value) IsNull() bool

func (*Value) IsNumber

func (v *Value) IsNumber() bool

func (*Value) IsNumberObject

func (v *Value) IsNumberObject() bool

func (*Value) IsObject

func (v *Value) IsObject() bool

func (*Value) IsRegExp

func (v *Value) IsRegExp() bool

func (*Value) IsString

func (v *Value) IsString() bool

func (*Value) IsStringObject

func (v *Value) IsStringObject() bool

func (*Value) IsTrue

func (v *Value) IsTrue() bool

func (*Value) IsUint32

func (v *Value) IsUint32() bool

func (*Value) IsUndefined

func (v *Value) IsUndefined() bool

func (*Value) ToArray

func (v *Value) ToArray() *Array

func (*Value) ToBoolean

func (v *Value) ToBoolean() bool

func (*Value) ToFunction

func (v *Value) ToFunction() *Function

func (*Value) ToInt32

func (v *Value) ToInt32() int32

func (*Value) ToInteger

func (v *Value) ToInteger() int64

func (*Value) ToNumber

func (v *Value) ToNumber() float64

func (*Value) ToObject

func (v *Value) ToObject() *Object

func (*Value) ToRegExp

func (v *Value) ToRegExp() *RegExp

func (*Value) ToString

func (v *Value) ToString() string

func (*Value) ToUint32

func (v *Value) ToUint32() uint32

Directories

Path Synopsis
samples

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL