Documentation
¶
Overview ¶
Package otto is a JavaScript parser and interpreter written natively in Go.
http://godoc.org/github.com/robertkrimen/otto
import (
"github.com/robertkrimen/otto"
)
Run something in the VM
vm := otto.New()
vm.Run(`
abc = 2 + 2;
console.log("The value of abc is " + abc); // 4
`)
Get a value out of the VM
value, err := vm.Get("abc")
value, _ := value.ToInteger()
}
Set a number
vm.Set("def", 11)
vm.Run(`
console.log("The value of def is " + def);
// The value of def is 11
`)
Set a string
vm.Set("xyzzy", "Nothing happens.")
vm.Run(`
console.log(xyzzy.length); // 16
`)
Get the value of an expression
value, _ = vm.Run("xyzzy.length")
{
// value is an int64 with a value of 16
value, _ := value.ToInteger()
}
An error happens
value, err = vm.Run("abcdefghijlmnopqrstuvwxyz.length")
if err != nil {
// err = ReferenceError: abcdefghijlmnopqrstuvwxyz is not defined
// If there is an error, then value.IsUndefined() is true
...
}
Set a Go function
vm.Set("sayHello", func(call otto.FunctionCall) otto.Value {
fmt.Printf("Hello, %s.\n", call.Argument(0).String())
return otto.Value{}
})
Set a Go function that returns something useful
vm.Set("twoPlus", func(call otto.FunctionCall) otto.Value {
right, _ := call.Argument(0).ToInteger()
result, _ := vm.ToValue(2 + right)
return result
})
Use the functions in JavaScript
result, _ = vm.Run(`
sayHello("Xyzzy"); // Hello, Xyzzy.
sayHello(); // Hello, undefined
result = twoPlus(2.0); // 4
`)
Parser ¶
A separate parser is available in the parser package if you're just interested in building an AST.
http://godoc.org/github.com/robertkrimen/otto/parser
Parse and return an AST
filename := "" // A filename is optional
src := `
// Sample xyzzy example
(function(){
if (3.14159 > 0) {
console.log("Hello, World.");
return;
}
var xyzzy = NaN;
console.log("Nothing happens.");
return xyzzy;
})();
`
// Parse some JavaScript, yielding a *ast.Program and/or an ErrorList
program, err := parser.ParseFile(nil, filename, src, 0)
otto
You can run (Go) JavaScript from the commandline with: http://github.com/robertkrimen/otto/tree/master/otto
$ go get -v github.com/robertkrimen/otto/otto
Run JavaScript by entering some source on stdin or by giving otto a filename:
$ otto example.js
underscore
Optionally include the JavaScript utility-belt library, underscore, with this import:
import ( "github.com/robertkrimen/otto" _ "github.com/robertkrimen/otto/underscore" ) // Now every otto runtime will come loaded with underscore
For more information: http://github.com/robertkrimen/otto/tree/master/underscore
Caveat Emptor ¶
The following are some limitations with otto:
- "use strict" will parse, but does nothing.
- The regular expression engine (re2/regexp) is not fully compatible with the ECMA5 specification.
- Otto targets ES5. ES6 features (eg: Typed Arrays) are not supported.
Regular Expression Incompatibility ¶
Go translates JavaScript-style regular expressions into something that is "regexp" compatible via `parser.TransformRegExp`. Unfortunately, RegExp requires backtracking for some patterns, and backtracking is not supported by the standard Go engine: https://code.google.com/p/re2/wiki/Syntax
Therefore, the following syntax is incompatible:
(?=) // Lookahead (positive), currently a parsing error (?!) // Lookahead (backhead), currently a parsing error \1 // Backreference (\1, \2, \3, ...), currently a parsing error
A brief discussion of these limitations: "Regexp (?!re)" https://groups.google.com/forum/?fromgroups=#%21topic/golang-nuts/7qgSDWPIh_E
More information about re2: https://code.google.com/p/re2/
In addition to the above, re2 (Go) has a different definition for \s: [\t\n\f\r ]. The JavaScript definition, on the other hand, also includes \v, Unicode "Separator, Space", etc.
Halting Problem ¶
If you want to stop long running executions (like third-party code), you can use the interrupt channel to do this:
package main
import (
"errors"
"fmt"
"os"
"time"
"github.com/robertkrimen/otto"
)
var halt = errors.New("Stahp")
func main() {
runUnsafe(`var abc = [];`)
runUnsafe(`
while (true) {
// Loop forever
}`)
}
func runUnsafe(unsafe string) {
start := time.Now()
defer func() {
duration := time.Since(start)
if caught := recover(); caught != nil {
if caught == halt {
fmt.Fprintf(os.Stderr, "Some code took to long! Stopping after: %v\n", duration)
return
}
panic(caught) // Something else happened, repanic!
}
fmt.Fprintf(os.Stderr, "Ran code successfully: %v\n", duration)
}()
vm := otto.New()
vm.Interrupt = make(chan func(), 1) // The buffer prevents blocking
go func() {
time.Sleep(2 * time.Second) // Stop after two seconds
vm.Interrupt <- func() {
panic(halt)
}
}()
vm.Run(unsafe) // Here be dragons (risky code)
}
Where is setTimeout/setInterval?
These timing functions are not actually part of the ECMA-262 specification. Typically, they belong to the `windows` object (in the browser). It would not be difficult to provide something like these via Go, but you probably want to wrap otto in an event loop in that case.
For an example of how this could be done in Go with otto, see natto:
http://github.com/robertkrimen/natto
Here is some more discussion of the issue:
* http://book.mixu.net/node/ch2.html
Index ¶
- Variables
- func Run(src interface{}) (*Otto, Value, error)
- type Context
- type Error
- type FunctionCall
- type Object
- func (self Object) Call(name string, argumentList ...interface{}) (Value, error)
- func (self Object) Class() string
- func (self Object) Get(name string) (Value, error)
- func (self Object) Keys() []string
- func (self Object) KeysByParent() [][]string
- func (self Object) Set(name string, value interface{}) error
- func (self Object) Value() Value
- type Otto
- func (self Otto) Call(source string, this interface{}, argumentList ...interface{}) (Value, error)
- func (self *Otto) Compile(filename string, src interface{}) (*Script, error)
- func (self *Otto) CompileWithSourceMap(filename string, src, sm interface{}) (*Script, error)
- func (self Otto) Context() Context
- func (self Otto) ContextLimit(limit int) Context
- func (self Otto) ContextSkip(limit int, skipNative bool) (ctx Context)
- func (in *Otto) Copy() *Otto
- func (self Otto) Eval(src interface{}) (Value, error)
- func (self Otto) Get(name string) (Value, error)
- func (self Otto) MakeCustomError(name, message string) Value
- func (self Otto) MakeRangeError(message string) Value
- func (self Otto) MakeSyntaxError(message string) Value
- func (self Otto) MakeTypeError(message string) Value
- func (self Otto) Object(source string) (*Object, error)
- func (self Otto) Run(src interface{}) (Value, error)
- func (self Otto) Set(name string, value interface{}) error
- func (self Otto) SetDebuggerHandler(fn func(vm *Otto))
- func (self Otto) SetRandomSource(fn func() float64)
- func (self Otto) SetStackDepthLimit(limit int)
- func (self Otto) SetStackTraceLimit(limit int)
- func (self Otto) ToValue(value interface{}) (Value, error)
- type Script
- type Value
- func (value Value) Call(this Value, argumentList ...interface{}) (Value, error)
- func (value Value) Class() string
- func (self Value) Export() (interface{}, error)
- func (value Value) IsBoolean() bool
- func (value Value) IsDefined() bool
- func (value Value) IsFunction() bool
- func (value Value) IsNaN() bool
- func (value Value) IsNull() bool
- func (value Value) IsNumber() bool
- func (value Value) IsObject() bool
- func (value Value) IsPrimitive() bool
- func (value Value) IsString() bool
- func (value Value) IsUndefined() bool
- func (value Value) Object() *Object
- func (value Value) String() string
- func (value Value) ToBoolean() (bool, error)
- func (value Value) ToFloat() (float64, error)
- func (value Value) ToInteger() (int64, error)
- func (value Value) ToString() (string, error)
Constants ¶
This section is empty.
Variables ¶
var ErrVersion = errors.New("version mismatch")
Functions ¶
func Run ¶
Run will allocate a new JavaScript runtime, run the given source on the allocated runtime, and return the runtime, resulting value, and error (if any).
src may be a string, a byte slice, a bytes.Buffer, or an io.Reader, but it MUST always be in UTF-8.
src may also be a Script.
src may also be a Program, but if the AST has been modified, then runtime behavior is undefined.
Types ¶
type Context ¶
type Context struct {
Filename string
Line int
Column int
Callee string
Symbols map[string]Value
This Value
Stacktrace []string
}
Context is a structure that contains information about the current execution context.