A JavaScript interpreter in Go (golang)
Package otto is a JavaScript parser and interpreter written natively in Go.
To use import it with the following:
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
if value, err := vm.Get("abc"); err == nil {
if value_int, err := value.ToInteger(); err == nil {
fmt.Println(value_int)
} else {
fmt.Printf("Error during conversion: %v\n", err)
}
} else {
fmt.Printf("Error getting value: %v\n", err)
}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
_, 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
`)A separate parser is available in the parser package if you're interested in only building an AST. 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)You can run (Go) JavaScript from the command line with otto.
go install github.com/robertkrimen/otto/otto@latestRun JavaScript by entering some source on stdin or by giving otto a filename:
otto example.jsOptionally 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 be initialized with Underscore.For more information: underscore
The following are some limitations with otto:
use strict will parse, but does nothing.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 Go
re2.
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 errorA brief discussion of these limitations: Regexp (?!re)
More information about 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.
If you want to stop long running executions (like third-party code), you can use the interrupt channel to do this:
…Where is setTimeout / setInterval?
These timing functions are not part of the ECMA-262 specification. They typically belong to the window object in a browser environment. While it is possible to implement similar functionality in Go, it generally requires wrapping Otto in an event loop.
For an example of how this could be done in Go with otto, see natto.
Here is some more discussion of the issue:
var ErrVersion = errors.New("version mismatch")type Error struct {}An Error represents a runtime error, e.g. a TypeError, a ReferenceError, etc.
func (err Error) Error() stringError returns a string representation of the error
TypeError: 'def' is not a functionfunc (err Error) String() stringString returns a description of the error and a trace of where the error occurred.
TypeError: 'def' is not a function
at xyz (<anonymous>:3:9)
at <anonymous>:7:1/type FunctionCall struct {
This Value
ArgumentList []Value
Otto *Otto
}FunctionCall is an encapsulation of a JavaScript function call.
func (self FunctionCall) Argument(index int) ValueArgument will return the value of the argument at the given index.
If no such argument exists, undefined is returned.
type Object struct {}Object is the representation of a JavaScript object.
func (self Object) Call(name string, argumentList ...interface{}) (Value, error)Call a method on the object.
It is essentially equivalent to:
var method, _ := object.Get(name)
method.Call(object, argumentList...)An undefined value and an error will result if:
func (self Object) Class() stringClass will return the class string of the object.
The return value will (generally) be one of:
Object
Function
Array
String
Number
Boolean
Date
RegExpfunc (self Object) Get(name string) (Value, error)Get the value of the property with the given name.
func (self Object) Keys() []stringGet the keys for the object
This is equivalent to calling Object.keys on the object.
func (self Object) Set(name string, value interface{}) errorSet the property of the given name to the given value.
An error will result if setting the property triggers an exception (e.g. read-only) or if there is an error during conversion of the given value.
func (self Object) Value() ValueValue will return self as a value.
type Otto struct {
// Interrupt is a channel for interrupting the runtime. You can use this to halt a long running execution, for example.
// See "Halting Problem" for more information.
Interrupt chan func()
}Otto is the representation of the JavaScript runtime. Each instance of Otto has a self-contained namespace.
func New() *OttoNew will allocate a new JavaScript runtime
func Run(src interface{}) (*Otto, Value, error)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.
func (self Otto) Call(source string, this interface{}, argumentList ...interface{}) (Value, error)Call the given JavaScript with a given this and arguments.
If this is nil, then some special handling takes place to determine the proper this value, falling back to a "standard" invocation if necessary (where this is undefined).
If source begins with "new " (A lowercase new followed by a space), then Call will invoke the function constructor rather than performing a function call. In this case, the this argument has no effect.
// value is a String object
value, _ := vm.Call("Object", nil, "Hello, World.")
// Likewise...
value, _ := vm.Call("new Object", nil, "Hello, World.")
// This will perform a concat on the given array and return the result
// value is [ 1, 2, 3, undefined, 4, 5, 6, 7, "abc" ]
value, _ := vm.Call(`[ 1, 2, 3, undefined, 4 ].concat`, nil, 5, 6, 7, "abc")func (self *Otto) Compile(filename string, src interface{}) (*Script, error)Compile will parse the given source and return a Script value. If there is an error during compilation, it will return nil and an error.
script, err := vm.Compile("", `var abc; if (!abc) abc = 0; abc += 2; abc;`)
vm.Run(script)func (in *Otto) Copy() *OttoCopy will create a copy/clone of the runtime.
Copy is useful for saving some time when creating many similar runtimes.
This method works by walking the original runtime and cloning each object, scope, stash, etc. into a new runtime.
Be on the lookout for memory leaks or inadvertent sharing of resources.
func (self Otto) Get(name string) (Value, error)Get the value of the top-level binding of the given name.
If there is an error (like the binding does not exist), then the value will be undefined.
func (self Otto) Object(source string) (*Object, error)Object will run the given source and return the result as an object.
For example, accessing an existing object:
object, _ := vm.Object(`Number`)Or, creating a new object:
object, _ := vm.Object(`({ xyzzy: "Nothing happens." })`)Or, creating and assigning an object:
object, _ := vm.Object(`xyzzy = {}`)
object.Set("volume", 11)If there is an error (like the source does not result in an object), then nil and an error is returned.
func (self Otto) Run(src interface{}) (Value, error)Run will run the given source (parsing it first if necessary), returning the 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.
If the runtime is unable to parse source, then this function will return undefined and the parse error (nothing will be evaluated in this case).
src may also be a Script.
src may also be a Program, but if the AST has been modified, then runtime behavior is undefined.
func (self Otto) Set(name string, value interface{}) errorSet the top-level binding of the given name to the given value.
Set will automati
Support parallel execution of JS functions without global variables
Issues with parsing Go time.Time fields
`let x=1` and `const x=1` don't work.
Go structs with pointers to maps return unexpected type errors
Freezing GO struct to consume by javascript modules
Object.Call()/Value.Call() and Eval() don't work together
Is there an equiv of C's __LINE__ ?
.toString(36) not properly/fully implemented
parser not ES10 or ES2018
There is no adaptation for a=`${test}`