A JavaScript interpreter in Go (golang)

otto

--

import "github.com/robertkrimen/otto"

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

if value, err := vm.Get("abc"); err == nil {
    if value_int, err := value.ToInteger(); err == nil {
	fmt.Printf("", value_int, 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

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 window 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:

Usage

var ErrVersion = errors.New("version mismatch")

type Error

type Error struct {
}

An Error represents a runtime error, e.g. a TypeError, a ReferenceError, etc.

func (Error) Error

func (err Error) Error() string

Error returns a description of the error

TypeError: 'def' is not a function

func (Error) String

func (err Error) String() string

String 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

type FunctionCall struct {
	This         Value
	ArgumentList []Value
	Otto         *Otto
}

FunctionCall is an encapsulation of a JavaScript function call.

func (FunctionCall) Argument

func (self FunctionCall) Argument(index int) Value

Argument will return the value of the argument at the given index.

If no such argument exists, undefined is returned.

type Object

type Object struct {
}

Object is the representation of a JavaScript object.

func (Object) Call

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:

1. There is an error during conversion of the argument list
2. The property is not actually a function
3. An (uncaught) exception is thrown

func (Object) Class

func (self Object) Class() string

Class will return the class string of the object.

The return value will (generally) be one of:

Object
Function
Array
String
Number
Boolean
Date
RegExp

func (Object) Get

func (self Object) Get(name string) (Value, error)

Get the value of the property with the given name.

func (Object) Keys

func (self Object) Keys() []string

Get the keys for the object

Equivalent to calling Object.keys on the object

func (Object) Set

func (self Object) Set(name string, value interface{}) error

Set the property of the given name to the given value.

An error will result if the setting the property triggers an exception (i.e. read-only), or there is an error during conversion of the given value.

func (Object) Value

func (self Object) Value() Value

Value will return self as a value.

type Otto

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

func New() *Otto

New will allocate a new JavaScript runtime

func Run

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 (Otto) Call

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 (*Otto) Compile

func (self *Otto) Compile(filename string, src interface{}) (*Script, error)

Compile will parse the given source and return a Script value or nil and an error if there was a problem during compilation.

script, err := vm.Compile("", `var abc; if (!abc) abc = 0; abc += 2; abc;`)
vm.Run(script)

func (*Otto) Copy

func (in *Otto) Copy() *Otto

Copy 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 (Otto) Get

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 (Otto) Object

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 (Otto) Run

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 (Otto) Set

func (self Otto) Set(name string, value interface{}) error

Set the top-level binding of the given name to the given value.

Set will automatically apply ToValue to the given value in order to convert it to a JavaScript value (type Value).

If there is an error (like the binding is read-only, or the ToValue conversion fails), then an error is returned.

If the top-level binding does not exist, it will be created.

func (Otto) ToValue

func (self Otto) ToValue(value interface{}) (Value, error)

ToValue will convert an interface{} value to a value digestible by otto/JavaScript.

type Script

type Script struct {
}

Script is a handle for some (reusable) JavaScript. Passing a Script value to a run method will evaluate the JavaScript.

func (*Script) String

func (self *Script) String() string

type Value

type Value struct {
}

Value is the representation of a JavaScript value.

func FalseValue

func FalseValue() Value

FalseValue will return a value representing false.

It is equivalent to:

ToValue(false)

func NaNValue

func NaNValue() Value

NaNValue will return a value representing NaN.

It is equivalent to:

ToValue(math.NaN())

func NullValue

func NullValue() Value

NullValue will return a Value representing null.

func ToValue

func ToValue(value interface{}) (Value, error)

ToValue will convert an interface{} value to a value digestible by otto/JavaScript

This function will not work for advanced types (struct, map, slice/array, etc.) and you should use Otto.ToValue instead.

func TrueValue

func TrueValue() Value

TrueValue will return a value representing true.

It is equivalent to:

ToValue(true)

func UndefinedValue

func UndefinedValue() Value

UndefinedValue will return a Value representing undefined.

func (Value) Call

func (value Value) Call(this Value, argumentList ...interface{}) (Value, error)

Call the value as a function with the given this value and argument list and return the result of invocation. It is essentially equivalent to:

value.apply(thisValue, argumentList)

An undefined value and an error will result if:

1. There is an error during conversion of the argument list
2. The value is not actually a function
3. An (uncaught) exception is thrown

func (Value) Class

func (value Value) Class() string

Class will return the class string of the value or the empty string if value is not an object.

The return value will (generally) be one of:

Object
Function
Array
String
Number
Boolean
Date
RegExp

func (Value) Export

func (self Value) Export() (interface{}, error)

Export will attempt to convert the value to a Go representation and return it via an interface{} kind.

Export returns an error, but it will always be nil. It is present for backwards compatibility.

If a reasonable conversion is not possible, then the original value is returned.

undefined   -> nil (FIXME?: Should be Value{})
null        -> nil
boolean     -> bool
number      -> A number type (int, float32, uint64, ...)
string      -> string
Array       -> []interface{}
Object      -> map[string]interface{}

func (Value) IsBoolean

func (value Value) IsBoolean() bool

IsBoolean will return true if value is a boolean (primitive).

func (Value) IsDefined

func (value Value) IsDefined() bool

IsDefined will return false if the value is undefined, and true otherwise.

func (Value) IsFunction

func (value Value) IsFunction() bool

IsFunction will return true if value is a function.

func (Value) IsNaN

func (value Value) IsNaN() bool

IsNaN will return true if value is NaN (or would convert to NaN).

func (Value) IsNull

func (value Value) IsNull() bool

IsNull will return true if the value is null, and false otherwise.

func (Value) IsNumber

func (value Value) IsNumber() bool

IsNumber will return true if value is a number (primitive).

func (Value) IsObject

func (value Value) IsObject() bool

IsObject will return true if value is an object.

func (Value) IsPrimitive

func (value Value) IsPrimitive() bool

IsPrimitive will return true if value is a primitive (any kind of primitive).

func (Value) IsString

func (value Value) IsString() bool

IsString will return true if value is a string (primitive).

func (Value) IsUndefined

func (value Value) IsUndefined() bool

IsUndefined will return true if the value is undefined, and false otherwise.

func (Value) Object

func (value Value) Object() *Object

Object will return the object of the value, or nil if value is not an object.

This method will not do any implicit conversion. For example, calling this method on a string primitive value will not return a String object.

func (Value) String

func (value Value) String() string

String will return the value as a string.

This method will make return the empty string if there is an error.

func (Value) ToBoolean

func (value Value) ToBoolean() (bool, error)

ToBoolean will convert the value to a boolean (bool).

ToValue(0).ToBoolean() => false
ToValue("").ToBoolean() => false
ToValue(true).ToBoolean() => true
ToValue(1).ToBoolean() => true
ToValue("Nothing happens").ToBoolean() => true

If there is an error during the conversion process (like an uncaught exception), then the result will be false and an error.

func (Value) ToFloat

func (value Value) ToFloat() (float64, error)

ToFloat will convert the value to a number (float64).

ToValue(0).ToFloat() => 0.
ToValue(1.1).ToFloat() => 1.1
ToValue("11").ToFloat() => 11.

If there is an error during the conversion process (like an uncaught exception), then the result will be 0 and an error.

func (Value) ToInteger

func (value Value) ToInteger() (int64, error)

ToInteger will convert the value to a number (int64).

ToValue(0).ToInteger() => 0
ToValue(1.1).ToInteger() => 1
ToValue("11").ToInteger() => 11

If there is an error during the conversion process (like an uncaught exception), then the result will be 0 and an error.

func (Value) ToString

func (value Value) ToString() (string, error)

ToString will convert the value to a string (string).

ToValue(0).ToString() => "0"
ToValue(false).ToString() => "false"
ToValue(1.1).ToString() => "1.1"
ToValue("11").ToString() => "11"
ToValue('Nothing happens.').ToString() => "Nothing happens."

If there is an error during the conversion process (like an uncaught exception), then the result will be the empty string ("") and an error.

-- godocdown http://github.com/robertkrimen/godocdown

Comments
  • Is there a way to install otto via go get? Error when running go get.

    Is there a way to install otto via go get? Error when running go get.

    I am new to golang and therefore to otto. I am having problems trying to install this package to use in my project. Is there a way to install it via go get or do I have to clone the project into my src folder?

    Sorry if this is a dumb question, but I am really struggling with this.

  • TestBinaryShiftOperation test fails

    TestBinaryShiftOperation test fails

    got ./...
    panic triggered: test
    interrupt
    interrupt
    ~~~ FAIL: (Terst)
    	runtime_test.go:592:
    		FAIL (==)
    		     got: 1073741823 (int32)
    		expected: -1073741824 (int)
    --- FAIL: TestBinaryShiftOperation (0.00s)
    
  • Resource control

    Resource control

    I am interested in letting end users create and run js on my server. To make this safe, I would like to control the amount of memory and cpu they can use.

    Would this be feasible in otto? Would it be hard to implement? Where should I begin?

  • Support for Interrupt VM without panic

    Support for Interrupt VM without panic

    Hi,

    In my project: https://github.com/prsolucoes/goci

    I have added support to stop plugin execution. Everything is working fine on CLI and JS plugin.

    The problem is when i stop the VM using Interrupt channel, i dont have another alternative of PANIC and it kill the host application and we need restart the server again and others execution is killed too.

    Have any alternative to this behaviour?

    Line: https://github.com/prsolucoes/goci/blob/master/models/domain/plugin_js.go#L284

  • Project dead?

    Project dead?

    The author (Robert Krimen) hasn't updated the project since September (and, in fact, no real activity since July). I wrote him an email asking for info on otto's status, but didn't get any answer at all.

  • Memleak caused by Otto clones?

    Memleak caused by Otto clones?

    I'm holding a few otto runtimes in memory and use .Clone() to get quick copies before adding some context specific stuff to them.

    It is then executed and Otto objects get just out of scope. There is no permanent storage of these clones.

    It seems this memory is never freed. mem profiling:

    github.com/robertkrimen/otto.objectClone - 20% of total heap
    github.com/robertkrimen/otto.(*declarativeEnvironment).clone - 62%
    
  • Improving call arguments conversion

    Improving call arguments conversion

    Passing nil to a 'non-native' go function results in "Call using zero Value argument". Also, passing custom types (for example passing uint32 to a function that expects type a uint32) results in a panic. This addresses both issues. Please consider merging.

  • unable to interpret react.js

    unable to interpret react.js

    I am a huge fan of react.js at the moment. Unfortunately, rendering the page on the client side has some disadvantages and clients that do not support JS (e.g. crawlers) will see nothing. I thought otto and react.js new renderComponentToString feature might be a good fit for rendering the page on the server side.

    Unfortunately, otto isn't able to interpret the react.js source at the moment. I'm creating this issue because I think it isn't related to the different regexp syntax.

    Example:

    package main
    
    import (
        "github.com/robertkrimen/otto"
        "io/ioutil"
        "log"
        "net/http"
    )
    
    func main() {
        resp, err := http.Get("http://fb.me/react-0.10.0.js")
        if err != nil {
            log.Fatalln(err)
        }
        body, err := ioutil.ReadAll(resp.Body)
        if err != nil {
            log.Fatalln(err)
        }
        vm := otto.New()
        _, err = vm.Run(string(body))
        if err != nil {
            log.Fatalln(err)
        }
    }
    

    Error:

    Cannot access member 'React' of undefined
    
  • Switch over to a regular expression package that claims to be Perl 5 compatible

    Switch over to a regular expression package that claims to be Perl 5 compatible

    Regular expressions in ECMAScript 5 are modelled after the regular expression facility in the Perl 5 programming language (ECMA 5 spec).

    This pull requests switches over from the regexp package to P5R, which is compatible with Perl 5 regular expressions.

    More testing is needed in order to confirm for sure that Perl 5 regular expressions will be supported correctly for all cases, but it's a start.

    For some functions that are supported by regexp but not yet by P5R, the regular expression struct is converted to a regexp struct and the same method call as was used before is being used. This might have a small performance hit (since the regular expression string is recompiled), but from my initial testing it should not have too large of an impact.

    In the future, it will probably be better to use the functions from P5R instead, which takes different parameters (and often can return an error where regexp returns none). I have added comments in the code where I think this might be a good idea.

    Hopefully this pull request can bring Otto one step closer to becoming ECMAScript 5 compatible, which would be an advantage.

  • GoCI - Trying to use otto js parser in my project

    GoCI - Trying to use otto js parser in my project

    Hi,

    I have a project called GoCI: https://github.com/prsolucoes/goci

    This project use Anko script parser in Go to make the CI builds. Users can create a script.ank file to execute every process need to build a task.

    My questions is about how i can do the same things using otto js parser. What i need understand in otto js parser:

    1 - Export Go functions to javascript, like make http request, exec command line, get environment vars ... everything here: https://github.com/prsolucoes/goci

    2 - I need export my own package called "goci". This custom package has some goci system functions, some variables, etc. There is a way to export it as object? Like "var job = goci.Job"!

    3 - If script crash/error, i can get this status without crash all the "goci" process ?

    Thanks for the help!

  • Seed math/rand with UnixNano for truly random numbers.

    Seed math/rand with UnixNano for truly random numbers.

    While creating a random level generator for my game engine I noticed that each time I generated a level (this happens on startup) it was the same. This is a fix that removes this bug/issue. Perhaps this is desired behaviour, but I figure that this way otto will behave more like other javascript implementations, all of which have unpredictable random numbers.

    Good Day!

  • feat: regexp engine configuration

    feat: regexp engine configuration

    Add support for ECMAScript compatible regular expression engine via regexp2 using functional options e.g.

    vm := New(RegExp(regexp2.Creator{}))
    

    This also adds function option support for the existing options:

    • Debugger - Deprecates: SetDebuggerHandler
    • RandomSource - Deprecates: SetRandomSource.
    • Stack - Deprecates: SetStackLimit.
    • StackTrace - Deprecates: SetStackTraceLimit.
  • Errors caused by different go versions

    Errors caused by different go versions

    This is my code. It is normal in version 1.18.1, but there is a problem in version 1.18.7

    vm := otto.New()
    _, err := vm.Run(js)
    key:="488,853,642"
    k, err := vm.Call("func_get_k", nil, key, 32)
    

    The result of 1.18.1 is as follows: d11e9c49e54677f584c5f8fa5e132a7d The result of 1.18.7 is as follows: 00000000000000000000000000000000

    This is "js"code:

    function func_get_k(string, bit) {
        function func_get_k_RotateLeft(lValue, iShiftBits) {
            return (lValue << iShiftBits) | (lValue >>> (32 - iShiftBits));
        }
    
        function func_get_k_mGr51T5WIX(lX, lY) {
            var lX4, lY4, lX8, lY8, lResult;
            lX8 = (lX & 0x80000000);
            lY8 = (lY & 0x80000000);
            lX4 = (lX & 0x40000000);
            lY4 = (lY & 0x40000000);
            lResult = (lX & 0x3FFFFFFF) + (lY & 0x3FFFFFFF);
            if (lX4 & lY4) {
                return (lResult ^ 0x80000000 ^ lX8 ^ lY8);
            }
            if (lX4 | lY4) {
                if (lResult & 0x40000000) {
                    return (lResult ^ 0xC0000000 ^ lX8 ^ lY8);
                } else {
                    return (lResult ^ 0x40000000 ^ lX8 ^ lY8);
                }
            } else {
                return (lResult ^ lX8 ^ lY8);
            }
        }
    
        function func_get_k_F(x, y, z) {
            return (x & y) | ((~x) & z);
        }
    
        function func_get_k_G(x, y, z) {
            return (x & z) | (y & (~z));
        }
    
        function func_get_k_H(x, y, z) {
            return (x ^ y ^ z);
        }
    
        function func_get_k_I(x, y, z) {
            return (y ^ (x | (~z)));
        }
    
        function func_get_k_FF(a, b, c, d, x, s, ac) {
            a = func_get_k_mGr51T5WIX(a, func_get_k_mGr51T5WIX(func_get_k_mGr51T5WIX(func_get_k_F(b, c, d), x), ac));
            return func_get_k_mGr51T5WIX(func_get_k_RotateLeft(a, s), b);
        };
    
        function func_get_k_GG(a, b, c, d, x, s, ac) {
            a = func_get_k_mGr51T5WIX(a, func_get_k_mGr51T5WIX(func_get_k_mGr51T5WIX(func_get_k_G(b, c, d), x), ac));
            return func_get_k_mGr51T5WIX(func_get_k_RotateLeft(a, s), b);
        };
    
        function func_get_k_HH(a, b, c, d, x, s, ac) {
            a = func_get_k_mGr51T5WIX(a, func_get_k_mGr51T5WIX(func_get_k_mGr51T5WIX(func_get_k_H(b, c, d), x), ac));
            return func_get_k_mGr51T5WIX(func_get_k_RotateLeft(a, s), b);
        };
    
        function func_get_k_II(a, b, c, d, x, s, ac) {
            a = func_get_k_mGr51T5WIX(a, func_get_k_mGr51T5WIX(func_get_k_mGr51T5WIX(func_get_k_I(b, c, d), x), ac));
            return func_get_k_mGr51T5WIX(func_get_k_RotateLeft(a, s), b);
        };
    
        function func_get_k_ConvertToWordArray(string) {
            var lWordCount;
            var lMessageLength = string.length;
            var lNumberOfWords_temp1 = lMessageLength + 8;
            var lNumberOfWords_temp2 = (lNumberOfWords_temp1 - (lNumberOfWords_temp1 % 64)) / 64;
            var lNumberOfWords = (lNumberOfWords_temp2 + 1) * 16;
            var lWordArray = Array(lNumberOfWords - 1);
            var lBytePosition = 0;
            var lByteCount = 0;
            while (lByteCount < lMessageLength) {
                lWordCount = (lByteCount - (lByteCount % 4)) / 4;
                lBytePosition = (lByteCount % 4) * 8;
                lWordArray[lWordCount] = (lWordArray[lWordCount] | (string.charCodeAt(lByteCount) << lBytePosition));
                lByteCount++;
            }
            lWordCount = (lByteCount - (lByteCount % 4)) / 4;
            lBytePosition = (lByteCount % 4) * 8;
            lWordArray[lWordCount] = lWordArray[lWordCount] | (0x80 << lBytePosition);
            lWordArray[lNumberOfWords - 2] = lMessageLength << 3;
            lWordArray[lNumberOfWords - 1] = lMessageLength >>> 29;
            return lWordArray;
        };
    
        function func_get_k_WordToHex(lValue) {
            var WordToHexValue = "", WordToHexValue_temp = "", lByte, lCount;
            for (lCount = 0; lCount <= 3; lCount++) {
                lByte = (lValue >>> (lCount * 8)) & 255;
                WordToHexValue_temp = "0" + lByte.toString(16);
                WordToHexValue = WordToHexValue + WordToHexValue_temp.substr(WordToHexValue_temp.length - 2, 2);
            }
            return WordToHexValue;
        };
    
        function func_get_k_FcCSRiu0tp(string) {
            string = string.replace(/\r\n/g, "\n");
            var utftext = "";
            for (var n = 0; n < string.length; n++) {
                var c = string.charCodeAt(n);
                if (c < 128) {
                    utftext += String.fromCharCode(c);
                } else if ((c > 127) && (c < 2048)) {
                    utftext += String.fromCharCode((c >> 6) | 192);
                    utftext += String.fromCharCode((c & 63) | 128);
                } else {
                    utftext += String.fromCharCode((c >> 12) | 224);
                    utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                    utftext += String.fromCharCode((c & 63) | 128);
                }
            }
            return utftext;
        };
        var x = Array();
        var k, AA, BB, CC, DD, a, b, c, d;
        var S11 = 7, S12 = 12, S13 = 17, S14 = 22;
        var S21 = 5, S22 = 9, S23 = 14, S24 = 20;
        var S31 = 4, S32 = 11, S33 = 16, S34 = 23;
        var S41 = 6, S42 = 10, S43 = 15, S44 = 21;
        string = func_get_k_FcCSRiu0tp(string);
        x = func_get_k_ConvertToWordArray(string);
        a = 0x67452301;
        b = 0xEFCDAB89;
        c = 0x98BADCFE;
        d = 0x10325476;
        for (k = 0; k < x.length; k += 16) {
            AA = a;
            BB = b;
            CC = c;
            DD = d;
            a = func_get_k_FF(a, b, c, d, x[k + 0], S11, 0xD76AA478);
            d = func_get_k_FF(d, a, b, c, x[k + 1], S12, 0xE8C7B756);
            c = func_get_k_FF(c, d, a, b, x[k + 2], S13, 0x242070DB);
            b = func_get_k_FF(b, c, d, a, x[k + 3], S14, 0xC1BDCEEE);
            a = func_get_k_FF(a, b, c, d, x[k + 4], S11, 0xF57C0FAF);
            d = func_get_k_FF(d, a, b, c, x[k + 5], S12, 0x4787C62A);
            c = func_get_k_FF(c, d, a, b, x[k + 6], S13, 0xA8304613);
            b = func_get_k_FF(b, c, d, a, x[k + 7], S14, 0xFD469501);
            a = func_get_k_FF(a, b, c, d, x[k + 8], S11, 0x698098D8);
            d = func_get_k_FF(d, a, b, c, x[k + 9], S12, 0x8B44F7AF);
            c = func_get_k_FF(c, d, a, b, x[k + 10], S13, 0xFFFF5BB1);
            b = func_get_k_FF(b, c, d, a, x[k + 11], S14, 0x895CD7BE);
            a = func_get_k_FF(a, b, c, d, x[k + 12], S11, 0x6B901122);
            d = func_get_k_FF(d, a, b, c, x[k + 13], S12, 0xFD987193);
            c = func_get_k_FF(c, d, a, b, x[k + 14], S13, 0xA679438E);
            b = func_get_k_FF(b, c, d, a, x[k + 15], S14, 0x49B40821);
            a = func_get_k_GG(a, b, c, d, x[k + 1], S21, 0xF61E2562);
            d = func_get_k_GG(d, a, b, c, x[k + 6], S22, 0xC040B340);
            c = func_get_k_GG(c, d, a, b, x[k + 11], S23, 0x265E5A51);
            b = func_get_k_GG(b, c, d, a, x[k + 0], S24, 0xE9B6C7AA);
            a = func_get_k_GG(a, b, c, d, x[k + 5], S21, 0xD62F105D);
            d = func_get_k_GG(d, a, b, c, x[k + 10], S22, 0x2441453);
            c = func_get_k_GG(c, d, a, b, x[k + 15], S23, 0xD8A1E681);
            b = func_get_k_GG(b, c, d, a, x[k + 4], S24, 0xE7D3FBC8);
            a = func_get_k_GG(a, b, c, d, x[k + 9], S21, 0x21E1CDE6);
            d = func_get_k_GG(d, a, b, c, x[k + 14], S22, 0xC33707D6);
            c = func_get_k_GG(c, d, a, b, x[k + 3], S23, 0xF4D50D87);
            b = func_get_k_GG(b, c, d, a, x[k + 8], S24, 0x455A14ED);
            a = func_get_k_GG(a, b, c, d, x[k + 13], S21, 0xA9E3E905);
            d = func_get_k_GG(d, a, b, c, x[k + 2], S22, 0xFCEFA3F8);
            c = func_get_k_GG(c, d, a, b, x[k + 7], S23, 0x676F02D9);
            b = func_get_k_GG(b, c, d, a, x[k + 12], S24, 0x8D2A4C8A);
            a = func_get_k_HH(a, b, c, d, x[k + 5], S31, 0xFFFA3942);
            d = func_get_k_HH(d, a, b, c, x[k + 8], S32, 0x8771F681);
            c = func_get_k_HH(c, d, a, b, x[k + 11], S33, 0x6D9D6122);
            b = func_get_k_HH(b, c, d, a, x[k + 14], S34, 0xFDE5380C);
            a = func_get_k_HH(a, b, c, d, x[k + 1], S31, 0xA4BEEA44);
            d = func_get_k_HH(d, a, b, c, x[k + 4], S32, 0x4BDECFA9);
            c = func_get_k_HH(c, d, a, b, x[k + 7], S33, 0xF6BB4B60);
            b = func_get_k_HH(b, c, d, a, x[k + 10], S34, 0xBEBFBC70);
            a = func_get_k_HH(a, b, c, d, x[k + 13], S31, 0x289B7EC6);
            d = func_get_k_HH(d, a, b, c, x[k + 0], S32, 0xEAA127FA);
            c = func_get_k_HH(c, d, a, b, x[k + 3], S33, 0xD4EF3085);
            b = func_get_k_HH(b, c, d, a, x[k + 6], S34, 0x4881D05);
            a = func_get_k_HH(a, b, c, d, x[k + 9], S31, 0xD9D4D039);
            d = func_get_k_HH(d, a, b, c, x[k + 12], S32, 0xE6DB99E5);
            c = func_get_k_HH(c, d, a, b, x[k + 15], S33, 0x1FA27CF8);
            b = func_get_k_HH(b, c, d, a, x[k + 2], S34, 0xC4AC5665);
            a = func_get_k_II(a, b, c, d, x[k + 0], S41, 0xF4292244);
            d = func_get_k_II(d, a, b, c, x[k + 7], S42, 0x432AFF97);
            c = func_get_k_II(c, d, a, b, x[k + 14], S43, 0xAB9423A7);
            b = func_get_k_II(b, c, d, a, x[k + 5], S44, 0xFC93A039);
            a = func_get_k_II(a, b, c, d, x[k + 12], S41, 0x655B59C3);
            d = func_get_k_II(d, a, b, c, x[k + 3], S42, 0x8F0CCC92);
            c = func_get_k_II(c, d, a, b, x[k + 10], S43, 0xFFEFF47D);
            b = func_get_k_II(b, c, d, a, x[k + 1], S44, 0x85845DD1);
            a = func_get_k_II(a, b, c, d, x[k + 8], S41, 0x6FA87E4F);
            d = func_get_k_II(d, a, b, c, x[k + 15], S42, 0xFE2CE6E0);
            c = func_get_k_II(c, d, a, b, x[k + 6], S43, 0xA3014314);
            b = func_get_k_II(b, c, d, a, x[k + 13], S44, 0x4E0811A1);
            a = func_get_k_II(a, b, c, d, x[k + 4], S41, 0xF7537E82);
            d = func_get_k_II(d, a, b, c, x[k + 11], S42, 0xBD3AF235);
            c = func_get_k_II(c, d, a, b, x[k + 2], S43, 0x2AD7D2BB);
            b = func_get_k_II(b, c, d, a, x[k + 9], S44, 0xEB86D391);
            a = func_get_k_mGr51T5WIX(a, AA);
            b = func_get_k_mGr51T5WIX(b, BB);
            c = func_get_k_mGr51T5WIX(c, CC);
            d = func_get_k_mGr51T5WIX(d, DD);
        }
        if (bit == 32) {
            return (func_get_k_WordToHex(a) + func_get_k_WordToHex(b) + func_get_k_WordToHex(c) + func_get_k_WordToHex(d)).toLowerCase();
        }
        return (func_get_k_WordToHex(b) + func_get_k_WordToHex(c)).toLowerCase();
    }
    
  • Add a console option

    Add a console option

    This PR adds an options pattern to the otto.New() function and provides a per-VM WithLogger() option utilising a logger interface. At this point it is more a proof of concept. We'd still need to determine if this should be a Logger or a Console interface.

    Note: I realise this overlaps with https://github.com/robertkrimen/otto/pull/341, I'd be happy to make this a ConsoleWriter. I'd maintain that it should be per VM.

  • Compile throws error

    Compile throws error

    Consider the following function

    function swap(a) {
      var c = a['name'].split(' ');
      a['name'] = c[1] + ' ' + c[0];
    }
    
    swap(args);
    

    args is a map passed during runtime before Run(), using Set(), this code executes perfectly well, however, the same when passed to Compile() throws the following error.

    (anonymous): Line 1: 32 Unexpected identifier (and 3 more errors)
    

    I'm using the latest version of otto github.com/robertkrimen/otto v0.0.0-20221025135307-511d75fba9f8 from go.mod. Any help is really appreciated.

  • value export object

    value export object

    when value.kind == object, call export method.the undefined value will ignore value.go

    object.enumerate(false, func(name string) bool {
            value := object.get(name)
            if value.IsDefined() {
    	        result[name] = value.export()
            }
            return true
    })
    

    =>

    object.enumerate(false, func(name string) bool {
            value := object.get(name)
            result[name] = value.export()
            return true
    })
    

    can be ?

Interpreter - The Official Interpreter for the Infant Lang written in Go

Infant Lang Interpreter Infant Lang Minimalistic Less Esoteric Programming Langu

Jan 10, 2022
v8 javascript engine binding for golang

Go-V8 V8 JavaScript engine bindings for Go. Features Thread safe Thorough and careful testing Boolean, Number, String, Object, Array, Regexp, Function

Nov 21, 2022
Scriptable interpreter written in golang
Scriptable interpreter written in golang

Anko Anko is a scriptable interpreter written in Go. (Picture licensed under CC BY-SA 3.0, photo by Ocdp) Usage Example - Embedded package main impor

Dec 23, 2022
A BASIC interpreter written in golang.
A BASIC interpreter written in golang.

05 PRINT "Index" 10 PRINT "GOBASIC!" 20 PRINT "Limitations" Arrays Line Numbers IF Statement DATA / READ Statements Builtin Functions Types 30 PRINT "

Dec 24, 2022
A simple virtual machine - compiler & interpreter - written in golang

go.vm Installation Build without Go Modules (Go before 1.11) Build with Go Modules (Go 1.11 or higher) Usage Opcodes Notes The compiler The interprete

Dec 17, 2022
interpreter for the basic language written in golang
interpreter for the basic language written in golang

jirachi interpreter for the basic language written in golang The plan supports the following functions: Arithmetic Operations (+, -, *, /, ^) Comparis

Sep 17, 2022
Monkey-go - Writing An Interpreter In Golang

monkey-go Learning how to write an Interpreter called Monkey using Go! If you're

Oct 5, 2022
BfInterpreterGo - Brainfuck interpreter built in golang

bfInterpreterGo Brainfuck interpreter built in golang. Usage main.exe --filename

Jan 7, 2022
Brainfuck interpreter in golang

Brainfuck Interpreter in Go brianfuck interpreter implimented in go brianfuck he

Aug 2, 2022
ECMAScript/JavaScript engine in pure Go

goja ECMAScript 5.1(+) implementation in Go. Goja is an implementation of ECMAScript 5.1 in pure Go with emphasis on standard compliance and performan

Dec 29, 2022
A Go API for the V8 javascript engine.

V8 Bindings for Go The v8 bindings allow a user to execute javascript from within a go executable. The bindings are tested to work with several recent

Dec 15, 2022
Execute JavaScript from Go
Execute JavaScript from Go

Execute JavaScript from Go Usage import "rogchap.com/v8go" Running a script ctx, _ := v8go.NewContext() // creates a new V8 context with a new Isolate

Jan 9, 2023
❄️ Elsa is a minimal, fast and secure runtime for JavaScript and TypeScript written in Go

Elsa Elsa is a minimal, fast and secure runtime for JavaScript and TypeScript written in Go, leveraging the power from QuickJS. Features URL based imp

Jan 7, 2023
⛳ A minimal programming language inspired by Ink, JavaScript, and Python.

⛳ Golfcart My blog post: Creating the Golfcart Programming Language Getting Started Scope Rules Usage Building and tests Contributions License Golfcar

Sep 6, 2022
A POSIX-compliant AWK interpreter written in Go

GoAWK: an AWK interpreter written in Go AWK is a fascinating text-processing language, and somehow after reading the delightfully-terse The AWK Progra

Dec 31, 2022
Prolog interpreter in Go

golog Prolog interpreter in Go with aspirations to be ISO compatible. See the full package documentation for usage details. Install with go get github

Nov 12, 2022
Yaegi is Another Elegant Go Interpreter
Yaegi is Another Elegant Go Interpreter

Yaegi is Another Elegant Go Interpreter. It powers executable Go scripts and plugins, in embedded interpreters or interactive shells, on top of the Go

Dec 30, 2022
A shell parser, formatter, and interpreter with bash support; includes shfmt

sh A shell parser, formatter, and interpreter. Supports POSIX Shell, Bash, and mksh. Requires Go 1.14 or later. Quick start To parse shell scripts, in

Jan 8, 2023
Lisp Interpreter

golisp Lisp Interpreter Usage $ golisp < foo.lisp Installation $ go get github.com/mattn/golisp/cmd/golisp Features Call Go functions. Print random in

Dec 15, 2022