ekuma

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 26, 2026 License: 0BSD Imports: 19 Imported by: 1 module, 1 package

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Ekuma

Ekuma is a JavaScript engine written in pure Go. Its bytecode interpreter runs without a JIT, and it uses unsafe only for OS APIs. It implements nearly all of ES2026. The Go API is unstable. See Status.

package main

import (
	"context"
	"fmt"
	"log"

	"github.com/hajimehoshi/ekuma"
)

func main() {
	var vm ekuma.VM
	script, err := vm.ParseScript("hello.js", `"Hello, " + ["wor", "ld"].join("")`)
	if err != nil {
		log.Fatalf("parse: %v", err)
	}
	result, err := script.Evaluate(context.Background())
	if err != nil {
		log.Fatalf("evaluate: %v", err)
	}
	fmt.Println(result.String()) // Hello, world
}

The zero value of ekuma.VM is ready to use. A VM must not be copied after first use.

Differences from other engines for Go

Ekuma goja Sobek moejs otto modernc.org/jit/js modernc.org/quickjs QJS v8go
Latest release v0.1.0 (2026-11-26) None None v0.1.1 (2026-11-15) v0.5.1 (2024-11-05) v0.5.0 (2026-11-22) v0.27.0 (2026-10-24) v0.0.6 (2025-10-28) v0.44.0 (2026-11-12)
Implementation Written in Go Written in Go Written in Go Written in Go Written in Go QuickJS, translated from C to Go QuickJS, translated from C to Go QuickJS-ng, compiled to WebAssembly and run by wazero Bindings to V8
Execution strategy Bytecode interpreter Bytecode interpreter Bytecode interpreter Bytecode interpreter AST interpreter Bytecode interpreter with a JIT on Linux amd64 Bytecode interpreter Bytecode interpreter, compiled to machine code by wazero's AOT compiler on amd64 and arm64 JIT compiler, or bytecode interpreter with --jitless
Pure Go ✅ ✅ ✅ ✅ ✅ ✅ ✅ ✅ ❌
unsafe-free ⚠️ Except for OS API access ❌ ❌ ❌ ✅ ❌ ❌ ❌ ❌
ECMAScript ES2026 ES5.1, and much of ES2015 and later ES5.1, and much of ES2015 and later Much of modern ECMAScript ES5 ES2023 ES2023 ES2023 ES2025
Modules ✅ ❌ ⚠️ Experimental ✅ ❌ ✅ ✅ ✅ ❌
Intl ✅ ❌ ❌ ⚠️ Partial ❌ ⚠️ DateTimeFormat and NumberFormat in en-US ⚠️ DateTimeFormat and NumberFormat in en-US ❌ ✅
Temporal ✅ ❌ ❌ ❌ ❌ ❌ ❌ ❌ ❌

goja and Sobek were compared at their latest commits as of 2026-11-16.

Ekuma uses a register-based interpreter, hidden classes, inline property caches, and dense array storage. JavaScript calls reuse interpreter stack space, including proper tail calls. On 64-bit platforms, a value occupies two words and can hold a number, a signed 64-bit BigInt, or a short string inline. Strings use WTF-8, preserving UTF-16 semantics and allowing well-formed strings to cross the Go boundary without transcoding.

Performance

Each value is the geometric mean of the benchmark times relative to Ekuma in one round of the suite. Lower is faster.

                     V8 benchmark    QuickJS
                     suite v7        microbench     Version
Ekuma                 1.00           1.00           v0.0.0-20261126103810-5acd587489b5
goja                  7.55           5.75           v0.0.0-20261118204651-8dfece3d1e1d
Sobek                 7.43           5.77           v0.0.0-20261119094010-6eceb967bb5b
moejs                 0.975          1.21           v0.1.1
otto                 35.7    (9/10)   n/a           v0.5.1
modernc.org/quickjs   5.07           3.88           v0.27.0
QJS                   6.76   (6/10)  6.17  (69/74)  v0.0.6
QuickJS (C)           1.58           1.05           v0.0.0-20260604125329-3d5e064e9dd6
v8go --jitless        0.862          0.702          v0.44.0
v8go                  0.0426         0.137          v0.44.0

Measured on 2026-11-26: Apple M3 Pro, macOS 27.2, go1.27.4.

(k/n) means that the engine and Ekuma both completed k of n benchmarks. The mean covers those paired results. See the benchmark method, individual results, and Ekuma CPU profile.

Host API

The API follows syscall/js for working with values and functions. JavaScript exceptions return to Go as errors. Calls that execute scripts or invoke functions take a context.Context for cancellation. The package documentation describes cancellation, host panics, and pending jobs.

Scripts

A parsed Script can be evaluated repeatedly. A second evaluation in the same realm throws a SyntaxError if the script declares a top-level let, const, or class. To share one parse across VMs, use ParseUnboundScript and bind the result in each VM with VM.BindScript.

Modules

Use VM.ParseModule, VM.ParseJSONModule, or VM.NewSyntheticModule to create a module. The host supplies a synchronous loader through VM.SetModuleLoader, including for import(). Module.Evaluate loads, links, and evaluates the module and returns a promise.

Realms

VM.NewRealm creates a global object with its own built-ins. Realms in a VM share values, jobs, and settings. Use separate VMs for independent JavaScript environments.

Promises and jobs

VM.NewPromise returns a promise and a resolver for completing it from Go. Pending promise jobs run before the outermost Go call that executes JavaScript returns. VM.SetUnhandledRejection receives rejections still unhandled after those jobs run. Promise continuations, including await, preserve the host value set by VM.WithContinuationData when they were registered.

Time and randomness

Date, Temporal, and Intl.DateTimeFormat use the local time zone by default. Override it with VM.SetTimeZone, the clock with VM.SetClock, and the source of Math.random with VM.SetRandomSource.

Intl

Import the optional intl package to enable Intl, locale-aware string and formatting methods, and additional Temporal calendars in every VM.

import _ "github.com/hajimehoshi/ekuma/intl"

With Go 1.27.4 and default build flags, the import increases the hello-world binary from 9.1 to 18.0 MiB on macOS arm64 and from 12.0 to 21.2 MiB on js/wasm. VM.SetLocale overrides the host default locale. iOS builds with intl require CGO_ENABLED=1. See the intl package documentation for host locale selection and License for distribution notices.

Agents

VMs on different goroutines share the memory of a SharedArrayBuffer as agents do: Value.SharedDataBlock returns the memory, which VM.ValueOf turns into a new SharedArrayBuffer of another VM.

Atomics.wait throws unless VM.SetCanBlock lets the VM block. When another VM notifies a waiter of Atomics.waitAsync, its promise is settled by the jobs that the waiting VM runs at the end of its current or next outermost call from Go. VM.AwaitJobs runs pending jobs. If none are ready, it waits for an asynchronous waiter to be notified or time out. With no pending jobs or waiters, it returns immediately.

Execution limits

Use a context with a deadline to cancel script execution and the promise jobs it runs. Property operations such as Value.Get and Value.Set can run JavaScript through getters, setters, or proxies. These operations inherit the current context inside a host callback and can run without a deadline when called directly from Go.

Each VM runs in the host process. For untrusted scripts, run Ekuma in a separate process with operating-system resource limits. See Missing for the current gaps in per-VM resource controls.

Status

53,791 of the 53,795 tests of test262 pass (99.99%). The other 4 fail for known reasons, which test262-failures.txt lists.

Ekuma checks its pure Go implementation of Intl (ECMA-402) against ICU’s own tests for collation, segmentation, and locale-aware formatting. The suite also checks Unicode normalization and Temporal calendars. In 122 of 131 subtests, Ekuma matched the pinned ICU 78.3 and 79.1 fixtures on every case it ran. The other nine recorded 302 expected differences, including 281 where only the spacing in a formatted date range differed. The run had no unexpected failures. See the ICU coverage inventory.

Implemented
  • Nearly all of the syntax and standard library up to ES2026 and Annex B, with RegExp on its own backtracking engine
  • Temporal, explicit resource management, import defer, and the newer Error, Iterator, Promise and ArrayBuffer additions
  • ShadowRealm, which is a proposal and not yet standard
  • Decorators, auto-accessors (accessor) and decorator metadata (Symbol.metadata), which are proposals and not yet standard
Notes on behavior
  • Date truncates historical UTC offsets to whole minutes. Temporal.ZonedDateTime uses the full offset for a named time zone.
  • Ekuma's generated Unicode tables follow the Go release in go.mod (Unicode 17.0.0 for Go 1.27). The parser uses the build toolchain's Unicode tables for JavaScript identifiers and may reject letters added in later Unicode versions.
  • Native builds load named time zones from system zoneinfo and Go's time.LoadLocation sources. With GOOS=js, the host's Intl.DateTimeFormat must also recognize the zone. Local Date operations use the JavaScript host's Date by default.
  • Without Intl, Temporal supports only the iso8601 calendar, the toLocale*String methods of Date use a fixed English format and those of numbers ignore the locale, localeCompare compares normalized code units, and case conversion ignores the locale.
  • Intl.Collator follows the CLDR root collation, in which Han characters sort by code point, and the tailorings of CLDR; ICU sorts Han by radical and stroke in the root
  • Intl.Segmenter uses dictionary word boundaries for Chinese, Japanese, Thai, Khmer and Burmese text in every locale. Greek locales also tailor sentence breaks at question marks
  • Intl.DisplayNames uses a regular CLDR variant's canonical subtag when the display locale has no translation. If another subtag has no display name, the result is the canonical language code, or undefined with fallback: "none"
  • Intl.DurationFormat separates the fields of the digital style as CLDR's duration patterns do, such as 1.02.03 in Serbian, where ICU uses the time separator
  • Intl.DateTimeFormat uses the names that CLDR's root locale gives a metazone through another one, such as Greenwich Mean Time for London in winter, where ICU uses the offset
  • Best-fit locale matching keeps the lookup match of a request whose script is too far from every available locale, such as ha for ha-Arab, where ICU selects the default locale
  • A BigInt has at most 2^30 bits, as in V8: an operation or a conversion whose result would be larger throws a RangeError, and a larger literal is a SyntaxError. ValueOf panics for a larger *big.Int, and a Func that returns one throws a RangeError
  • Source phase imports and %AbstractModuleSource% exist, but importing the source of any module throws a SyntaxError, since no host API gives a module a module source
  • Function.prototype[Symbol.metadata] is null, as the spec text of the decorator metadata proposal defines it, so a class without decorators inherits null unless its superclass has metadata
  • The caller and arguments properties of sloppy functions, a legacy extension that the specification leaves to implementations, are accessors of each function. Browsers instead change the accessors of Function.prototype, which the specification defines to throw. As in SpiderMonkey, caller is null for a call from strict code, a generator, an async function or a built-in function. A proper tail call from strict code leaves no frame of the strict function, so the function that it calls sees the caller of the strict function instead
  • A WeakMap or WeakSet entry is stored with its key, since Go's garbage collector has no ephemerons. A value that refers back to its WeakMap therefore keeps the map alive for as long as the key is alive
  • When a Map or Set is compacted, an unfinished iterator keeps the positions of deleted entries until its next step so it can resume in insertion order
Missing

Host API for these, some of which the engine has and only the tests use:

  • Giving a module a module source
  • Property descriptors, and listing the keys of an object
  • Limits on stack depth or memory, and statistics of the memory that a VM uses

Running the tests

go test ./...

Use go test -short ./... to run the local regression tests and skip external suites. Add -tags=ekumavalidate to check bytecode generation and execution.

Conformance tests

go test . runs the external suites when their checkouts are available. Set the environment variables below or place the checkouts at the listed paths under the user cache directory. The CI setup checks out Test262 in full, lists the V8 paths, and selects ICU files from the upstream path inventory.

Suite Environment variable Default cache path CI revision Expectations
ICU 78.3 (Unicode 17, CLDR 48.2 collation) EKUMA_ICU ekuma/icu Revision Expected failures
ICU 79.1 (CLDR 49 locale and formatting data) EKUMA_ICU_CLDR ekuma/icu-cldr Revision Expected failures
Test262 EKUMA_TEST262 ekuma/test262 Revision Expected failures
V8 Intl, mjsunit, Mozilla, and WebKit EKUMA_V8 ekuma/v8 Revision Test expectations

See the ICU fixture inventory for coverage and focused test commands.

When a fixture and a published specification or data release disagree, record what the fixture expects, which revision Ekuma follows, and what change would warrant revisiting the decision. Put the note beside the expected failure, or beside the local regression test when the fixture passes.

For V8's Mozilla suite, fetch the data revision pinned by V8 from the Ekuma repository root:

bash internal/jstest/checkout-mozilla.sh "$EKUMA_V8"

With both V8 and Test262 checked out, TestV8Test262 also runs V8's local Test262 cases.

Use -test262.dir or -v8.dir to select a checkout-relative directory, or the corresponding filter flag to match part of a test path.

go test -count=1 -v -run '^TestTest262$' . -test262.dir test/intl402/Collator
go test -count=1 -v -run '^TestV8$' . -v8.dir test/intl/collator

License

Ekuma's code is licensed under 0BSD. The data tables Ekuma generates from Unicode, CLDR, and ICU releases are licensed under the Unicode License v3. The historical Chinese and Korean calendar tables are licensed under the MIT License.

Every build includes Unicode character and emoji data, so all distributions must include the Unicode copyright and permission notice.

Documentation

Overview

Package ekuma is a JavaScript engine written in pure Go.

The API follows syscall/js where possible. The differences come from JavaScript running inside the process: there can be several VMs, an exception is returned as an error and not thrown as a panic, and the methods that run a script or call a function take a context.Context that stops them.

A context stops everything that runs under it: when a Func reads a property or calls a function, that is stopped by the context of the call that led to the Func. When a Func makes a call with another context and that context stops the call, everything stops: the outermost Go call that executes JavaScript returns the cause of that context, and the Func does not continue. A Func that recovers the stop runs no more JavaScript, and the stop continues when it returns. A context that becomes done after its call returns has no effect.

Internal operation failures return an *InternalError from the outermost Go call executing JavaScript. They stop execution without running JavaScript catch or finally blocks, discard pending jobs, and reject unfinished module evaluations. Side effects remain.

Pending promise jobs run before the outermost Go call that executes JavaScript returns, including property operations and calls that throw. Calls reentered from host callbacks leave jobs to the outermost call. An interruption discards pending jobs and closes generators whose execution it unwinds. Operations without a context can run JavaScript and jobs without a cancellation limit, unless reentered under a call with a context. VM.AwaitJobs waits for asynchronous notifications and runs their jobs.

A panic in a Func, or in another host function called by JavaScript, passes through Go calls unchanged after restoring the VM's execution state. Host callbacks may recover panics from reentrant calls. At the outermost boundary, pending jobs and unhandled rejection reports are discarded and unfinished module evaluations are rejected. Abandoned synchronous module evaluations are rejected before returning to the host. Aborted generators are closed without running JavaScript catch or finally blocks. Side effects remain, and promises for abandoned async work may remain pending. Host callbacks must not call runtime.Goexit, which leaves the VM unusable.

The ekumavalidate build tag enables internal checks on the bytecode the compiler emits and on its execution by the VM.

Example (Modules)

This example runs a module that imports a module and a JSON module from a file system.

package main

import (
	"context"
	"fmt"
	"io/fs"
	"path"
	"testing/fstest"

	"github.com/hajimehoshi/ekuma"
)

func main() {
	fsys := fstest.MapFS{
		"main.js": {Data: []byte(`
			import { greet } from "./lib/greet.js";
			import config from "./config.json" with { type: "json" };
			export const message = greet(config.name);`)},
		"lib/greet.js": {Data: []byte(`
			export function greet(name) { return "Hello, " + name; }`)},
		"config.json": {Data: []byte(`{"name": "modules"}`)},
	}

	var vm ekuma.VM
	modules := map[string]*ekuma.Module{}
	load := func(req ekuma.ModuleRequest) (*ekuma.Module, error) {
		// A specifier is relative to the importing module.
		name := path.Join(path.Dir(req.ReferrerName), req.Specifier)
		if m, ok := modules[name]; ok {
			return m, nil
		}
		src, err := fs.ReadFile(fsys, name)
		if err != nil {
			return nil, err
		}
		var m *ekuma.Module
		if req.Attributes["type"] == "json" {
			m, err = vm.ParseJSONModule(name, string(src))
		} else {
			m, err = vm.ParseModule(name, string(src))
		}
		if err != nil {
			return nil, err
		}
		modules[name] = m
		return m, nil
	}
	vm.SetModuleLoader(load)

	m, err := load(ekuma.ModuleRequest{Specifier: "main.js"})
	if err != nil {
		panic(err)
	}
	// Evaluate loads and links the modules first.
	p, err := m.Evaluate(context.Background())
	if err != nil {
		panic(err)
	}
	state, _ := p.PromiseState()
	fmt.Println(state)

	ns, err := m.Namespace()
	if err != nil {
		panic(err)
	}
	msg, err := ns.Get("message")
	if err != nil {
		panic(err)
	}
	fmt.Println(msg.String())

}
Output:
fulfilled
Hello, modules
Example (SharedArrayBuffer)

This example hands the memory of a SharedArrayBuffer to a VM on another goroutine, whose store the first VM reads after Atomics.wait: the wait blocks until the notification, or returns at once when the store came first.

package main

import (
	"context"
	"fmt"

	"github.com/hajimehoshi/ekuma"
)

func main() {
	ctx := context.Background()
	blocks := make(chan *ekuma.SharedDataBlock)
	done := make(chan error)
	go func() {
		var worker ekuma.VM
		if err := worker.Global().Set("sab", <-blocks); err != nil {
			done <- err
			return
		}
		s, err := worker.ParseScript("worker.js", `
			const ia = new Int32Array(sab);
			Atomics.store(ia, 0, 42);
			Atomics.notify(ia, 0);`)
		if err != nil {
			done <- err
			return
		}
		_, err = s.Evaluate(ctx)
		done <- err
	}()

	var vm ekuma.VM
	vm.SetCanBlock(true)
	main, err := vm.ParseScript("main.js", `globalThis.ia = new Int32Array(new SharedArrayBuffer(4)); ia.buffer`)
	if err != nil {
		fmt.Println(err)
		return
	}
	sab, err := main.Evaluate(ctx)
	if err != nil {
		fmt.Println(err)
		return
	}
	blocks <- sab.SharedDataBlock()
	wait, err := vm.ParseScript("wait.js", `Atomics.wait(ia, 0, 0); Atomics.load(ia, 0)`)
	if err != nil {
		fmt.Println(err)
		return
	}
	v, err := wait.Evaluate(ctx)
	if err != nil {
		fmt.Println(err)
		return
	}
	if err := <-done; err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(v.Int())
}
Output:
42

Index

Examples

Constants

This section is empty.

Variables

View Source
var ErrRunning = errors.New("ekuma: AwaitJobs called while JavaScript runs")

ErrRunning is returned by VM.AwaitJobs when the VM is running JavaScript.

Functions

func CopyBytesToGo

func CopyBytesToGo(dst []byte, src Value) int

CopyBytesToGo copies bytes from the Uint8Array or Uint8ClampedArray src to dst and returns the number of bytes copied, which is the minimum of their lengths. A detached or out of bounds src has no bytes. It panics with a *ValueError when src is neither a Uint8Array nor a Uint8ClampedArray.

func CopyBytesToJS

func CopyBytesToJS(dst Value, src []byte) int

CopyBytesToJS copies bytes from src to the Uint8Array or Uint8ClampedArray dst and returns the number of bytes copied, which is the minimum of their lengths. A detached or out of bounds dst has no bytes. It panics with a *ValueError when dst is neither a Uint8Array nor a Uint8ClampedArray, or is backed by an immutable ArrayBuffer.

Types

type Func

type Func func(this Value, args []Value) (any, error)

Func is a function implemented in Go.

args is valid only until the function returns. The result is converted with Realm.ValueOf of the realm of the function, except that a *big.Int result of more than 2^30 bits throws a RangeError, as a BigInt operation of JavaScript with such a result does.

A non-nil error is thrown as a JavaScript exception: a *ScriptError throws its value, and any other error throws a new Error object made from the error, with its message. ScriptError.Unwrap of a *ScriptError holding that object returns the error.

type InternalError

type InternalError struct {
	// Err is the underlying failure.
	Err error
}

InternalError is a failure of an internal engine operation.

func (*InternalError) Error

func (e *InternalError) Error() string

func (*InternalError) Unwrap

func (e *InternalError) Unwrap() error

Unwrap returns the underlying failure.

type Module

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

Module is a module record of a VM.

Running a module involves three steps: Module.LoadRequestedModules, Module.Link and Module.Evaluate. Each step first completes any unfinished prerequisites. Module.Namespace performs the first two steps. These methods may be called in any order; completed steps are not repeated. A call from inside the module loader that has to load a module that is still being loaded returns a *ScriptError holding a TypeError.

func (*Module) Evaluate

func (m *Module) Evaluate(ctx context.Context) (Value, error)

Evaluate evaluates m and its dependencies and returns a promise for the evaluation. It calls Module.Link first. An exception thrown by a module rejects the promise. Evaluating a source text module again returns the same promise. A synthetic or JSON module returns a new fulfilled promise each time.

Pending promise jobs run before the outermost Go call that executes JavaScript returns. An Evaluate call made from a host callback can return with jobs still pending. An interruption discards pending jobs.

The error is the error of Module.Link. When ctx is done, the evaluation stops at its next loop iteration or call, and the error is the cause of ctx. Any call that a context stops ends the evaluations in progress with an Error, which rejects their promises: ScriptError.Unwrap of a *ScriptError holding such a reason returns the cause of ctx. Internal operation failures return an *InternalError.

func (m *Module) Link() error

Link links m and its dependencies: it resolves their imports without evaluating module code. It calls Module.LoadRequestedModules first. Module.Evaluate and Module.Namespace call it, so calling it is needed only to link before evaluating. The error is the error of Module.LoadRequestedModules, or a *ScriptError holding a JavaScript SyntaxError for an import that does not resolve. Link may be retried after a failure.

func (*Module) LoadRequestedModules

func (m *Module) LoadRequestedModules() error

LoadRequestedModules loads the modules that m and its dependencies import, with the loader of the VM. Module.Link, Module.Evaluate and Module.Namespace call it, so calling it is needed only to load before linking. A failed import returns a *ScriptError holding the value thrown as described by VM.SetModuleLoader. When the loader returns an ordinary Go error, errors.Is matches that error through the returned *ScriptError.

func (*Module) Name

func (m *Module) Name() string

Name returns the name that m was created with.

func (*Module) Namespace

func (m *Module) Namespace() (Value, error)

Namespace returns the module namespace object of m. It calls Module.Link first, and the error is the error of Module.Link. Before m is evaluated, reading an export that is not initialized yet throws a ReferenceError.

type ModuleRequest

type ModuleRequest struct {
	// Realm is the realm of the code requesting the import.
	Realm *Realm

	// Referrer is the importing module, or nil if the import is not requested by a module.
	Referrer *Module

	// ReferrerName is the name of the importing script or module, or empty.
	ReferrerName string

	// Specifier is the module specifier of the import.
	Specifier string

	// Attributes are the import attributes of the with clause.
	Attributes map[string]string
}

ModuleRequest is a request to load a module.

type PromiseResolver

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

PromiseResolver resolves or rejects the promise that Realm.NewPromise returns with it, as the resolving functions of the promise do: once the promise is resolved, later calls of PromiseResolver.Resolve and PromiseResolver.Reject have no effect. A PromiseResolver must not be used while its VM is used on another goroutine.

func (*PromiseResolver) Reject

func (r *PromiseResolver) Reject(ctx context.Context, v any) error

Reject is like PromiseResolver.Resolve, but rejects the promise with v. A rejected promise without a handler is reported to the callback of VM.SetUnhandledRejection after the jobs ran, unless ctx stops them.

func (*PromiseResolver) Resolve

func (r *PromiseResolver) Resolve(ctx context.Context, v any) error

Resolve resolves the promise with VM.ValueOf(v), or with Realm.ValueOf(v) of its realm for a promise of another realm. A thenable is adopted, and reading its then property can run JavaScript. The pending jobs run before Resolve returns, unless it is called from a host callback.

If ctx is already done, Resolve does not attempt to settle the promise. If ctx stops JavaScript at a loop iteration or call, pending jobs are discarded. An interruption after resolution begins can leave the promise pending even though later calls to the resolver have no effect.

If ctx stops an outermost call to Resolve, Resolve returns the cause of ctx. If ctx stops a call from a host callback, the interruption unwinds the callback and the outermost call reports the cause. Internal operation failures return an *InternalError.

type PromiseState

type PromiseState int

PromiseState is the state of a promise.

const (
	PromisePending PromiseState = iota
	PromiseFulfilled
	PromiseRejected
)

func (PromiseState) String

func (s PromiseState) String() string

type Realm

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

Realm is a realm of a VM: a global object with its own standard built-in objects.

The realms of a VM share its promise jobs, settings and other state, except for their global objects and built-in objects. Values may pass between realms. A realm is not a security boundary: an object of a realm gives access to the built-in objects of its realm.

func (*Realm) BindScript

func (r *Realm) BindScript(u *UnboundScript) *Script

BindScript returns the script of u for r: the script that Realm.ParseScript of r returns for the name and source text of u.

func (*Realm) FuncOf

func (r *Realm) FuncOf(name string, f Func) Value

FuncOf is like VM.FuncOf, but the function belongs to and runs in r. If f returns a *ScriptError, directly or wrapped, the function throws its stored value, which may be a primitive or an object from any realm of the same VM. For any other non-nil error, the function throws a new Error object in r.

func (*Realm) Global

func (r *Realm) Global() Value

Global returns the global object of r.

func (*Realm) NewArrayBuffer

func (r *Realm) NewArrayBuffer(b []byte) Value

NewArrayBuffer is like VM.NewArrayBuffer, but the ArrayBuffer belongs to r.

func (*Realm) NewPromise

func (r *Realm) NewPromise() (Value, *PromiseResolver)

NewPromise returns a new pending promise of r and the resolver that settles it.

func (*Realm) NewSyntheticModule

func (r *Realm) NewSyntheticModule(name string, v Value) *Module

NewSyntheticModule returns a module of r whose only export is default, with the value v. It panics if v belongs to another VM.

func (*Realm) ParseJSONModule

func (r *Realm) ParseJSONModule(name, src string) (*Module, error)

ParseJSONModule returns a JSON module of r: a module whose only export is default, with the value returned by JSON.parse in r for src. The error is a *ScriptError holding a JavaScript SyntaxError when src is not valid JSON.

func (*Realm) ParseModule

func (r *Realm) ParseModule(name, src string) (*Module, error)

ParseModule parses src as the source text of a module of r. name identifies the module in error messages and stack traces, and in the ModuleRequest.ReferrerName of its imports. The error is a *SyntaxError when src is not a valid module.

func (*Realm) ParseScript

func (r *Realm) ParseScript(name, src string) (*Script, error)

ParseScript parses src as the source text of a script of r. name identifies the script in error messages and stack traces, and in the ModuleRequest.ReferrerName of its import() calls. The error is a *SyntaxError when src is not a valid script.

func (*Realm) ValueOf

func (r *Realm) ValueOf(x any) Value

ValueOf is like VM.ValueOf, but the objects that it creates belong to r.

type Script

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

Script is a script of a realm, from Realm.ParseScript or Realm.BindScript.

func (*Script) Evaluate

func (s *Script) Evaluate(ctx context.Context) (Value, error)

Evaluate evaluates s and returns its completion value. A script may be evaluated more than once, but evaluating it again throws a JavaScript SyntaxError when s declares a top-level let, const or class.

Pending promise jobs run before the outermost Go call that executes JavaScript returns. An Evaluate call made from a host callback can return with jobs still pending. An interruption discards pending jobs.

The error is a *ScriptError when the script throws. When ctx is done, the script stops at its next loop iteration or call, and the error is the cause of ctx. Internal operation failures return an *InternalError.

type ScriptError

type ScriptError struct {
	// Value is the thrown value.
	Value Value
}

ScriptError is a JavaScript exception: one that reached Go, or one for a Func to throw.

Example
package main

import (
	"context"
	"errors"
	"fmt"

	"github.com/hajimehoshi/ekuma"
)

func main() {
	var vm ekuma.VM
	s, err := vm.ParseScript("order.js", `throw { code: "OUT_OF_STOCK" }`)
	if err != nil {
		panic(err)
	}
	_, err = s.Evaluate(context.Background())
	exception, ok := errors.AsType[*ekuma.ScriptError](err)
	if !ok {
		panic(fmt.Sprintf("expected a JavaScript exception, got %v", err))
	}
	code, err := exception.Value.Get("code")
	if err != nil {
		panic(err)
	}
	fmt.Println(code.String())

}
Output:
OUT_OF_STOCK

func (*ScriptError) Error

func (e *ScriptError) Error() string

Error returns the stack trace or the message of a thrown error object, and a description of any other thrown value. It runs no JavaScript.

func (*ScriptError) Unwrap

func (e *ScriptError) Unwrap() error

Unwrap returns the Go error that e.Value was made from, or nil when it was not.

type SharedDataBlock

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

SharedDataBlock is the memory of a SharedArrayBuffer, usable by any VM on any goroutine.

type SyntaxError

type SyntaxError struct {
	// File is the name of the script or module.
	File string

	// Line is the 1-based line number of the error.
	Line int

	Message string
}

SyntaxError reports a failure to parse or compile a script or module.

func (*SyntaxError) Error

func (e *SyntaxError) Error() string

type Type

type Type int

Type is the type of a JavaScript value. Null has type TypeNull, and callable objects have type TypeFunction, including those with [[IsHTMLDDA]].

const (
	TypeUndefined Type = iota
	TypeNull
	TypeBoolean
	TypeNumber
	TypeString
	TypeSymbol
	TypeBigInt
	TypeObject
	TypeFunction
)

func (Type) String

func (t Type) String() string

type UnboundScript

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

UnboundScript is a script parsed for no particular VM, which Realm.BindScript binds to a realm. An UnboundScript is immutable: any number of VMs and realms may bind it, also from different goroutines at the same time.

func ParseUnboundScript

func ParseUnboundScript(name, src string) (*UnboundScript, error)

ParseUnboundScript parses src as the source text of a script, as Realm.ParseScript does, but for no particular VM. The error is a *SyntaxError when src is not a valid script.

Example
package main

import (
	"context"
	"fmt"

	"github.com/hajimehoshi/ekuma"
)

func main() {
	s, err := ekuma.ParseUnboundScript("greeting.js", `"Hello, " + name`)
	if err != nil {
		panic(err)
	}

	for _, name := range []string{"Alice", "Bob"} {
		var vm ekuma.VM
		if err := vm.Global().Set("name", name); err != nil {
			panic(err)
		}
		v, err := vm.BindScript(s).Evaluate(context.Background())
		if err != nil {
			panic(err)
		}
		fmt.Println(v.String())
	}

}
Output:
Hello, Alice
Hello, Bob

type VM

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

VM is a JavaScript virtual machine with the standard built-in objects. The zero value is ready to use. A VM must not be copied after first use. A VM and its values and realms must not be used from more than one goroutine at a time.

func (*VM) AwaitJobs

func (vm *VM) AwaitJobs(ctx context.Context) (bool, error)

AwaitJobs runs pending jobs, waiting for an Atomics.waitAsync waiter to be notified or time out if necessary. It reports true if jobs were run, or false without blocking if there are no pending jobs or asynchronous waiters. It returns ErrRunning if the VM is running JavaScript, or the cause of ctx if ctx is already done or interrupts the wait or job execution.

func (*VM) BindScript

func (vm *VM) BindScript(u *UnboundScript) *Script

BindScript is Realm.BindScript of the initial realm.

func (*VM) ContinuationData

func (vm *VM) ContinuationData() any

ContinuationData returns the continuation data set by the innermost VM.WithContinuationData call or running job, or nil if there is none.

func (*VM) DetachArrayBuffer

func (vm *VM) DetachArrayBuffer(v Value)

DetachArrayBuffer detaches the ArrayBuffer v, so that v and its views have no bytes. Detaching a detached ArrayBuffer does nothing. DetachArrayBuffer panics with a *ValueError when v is not a mutable ArrayBuffer.

func (*VM) FuncOf

func (vm *VM) FuncOf(name string, f Func) Value

FuncOf returns a JavaScript function of the initial realm that calls f. name is the name of the function, which stack traces show. FuncOf panics when f is nil.

Example
package main

import (
	"context"
	"errors"
	"fmt"
	"strings"

	"github.com/hajimehoshi/ekuma"
)

func main() {
	var vm ekuma.VM
	uppercase := vm.FuncOf("uppercase", func(_ ekuma.Value, args []ekuma.Value) (any, error) {
		if len(args) != 1 || args[0].Type() != ekuma.TypeString {
			return nil, errors.New("uppercase expects one string")
		}
		return strings.ToUpper(args[0].String()), nil
	})
	if err := vm.Global().Set("uppercase", uppercase); err != nil {
		panic(err)
	}

	s, err := vm.ParseScript("greeting.js", `"Hello, " + uppercase("Ekuma")`)
	if err != nil {
		panic(err)
	}
	v, err := s.Evaluate(context.Background())
	if err != nil {
		panic(err)
	}
	fmt.Println(v.String())

}
Output:
Hello, EKUMA

func (*VM) Global

func (vm *VM) Global() Value

Global returns the global object of the initial realm.

func (*VM) InitialRealm

func (vm *VM) InitialRealm() *Realm

InitialRealm returns the realm created with vm, in which the methods of vm operate.

func (*VM) NewArrayBuffer

func (vm *VM) NewArrayBuffer(b []byte) Value

NewArrayBuffer returns an ArrayBuffer of the initial realm whose bytes are b, without copying. Its length is len(b) and does not change.

The VM reads and writes b only during calls into this package, and never after the ArrayBuffer is detached with VM.DetachArrayBuffer. Go may read and write b whenever it may call the VM, including in a Func, and either side sees the writes of the other at once.

JavaScript cannot detach the ArrayBuffer: its transfer, transferToFixedLength and transferToImmutable methods throw a TypeError. NewArrayBuffer panics when b is longer than an ArrayBuffer may be.

Example
package main

import (
	"context"
	"fmt"

	"github.com/hajimehoshi/ekuma"
)

func main() {
	var vm ekuma.VM
	pixels := []byte{10, 20, 30, 255}
	if err := vm.Global().Set("pixels", vm.NewArrayBuffer(pixels)); err != nil {
		panic(err)
	}
	s, err := vm.ParseScript("invert.js", `
		const rgba = new Uint8Array(pixels);
		for (let i = 0; i < 3; i++) {
			rgba[i] = 255 - rgba[i];
		}
	`)
	if err != nil {
		panic(err)
	}
	if _, err := s.Evaluate(context.Background()); err != nil {
		panic(err)
	}
	fmt.Println(pixels)

}
Output:
[245 235 225 255]

func (*VM) NewPromise

func (vm *VM) NewPromise() (Value, *PromiseResolver)

NewPromise is Realm.NewPromise of the initial realm.

Example
package main

import (
	"context"
	"fmt"

	"github.com/hajimehoshi/ekuma"
)

func main() {
	ctx := context.Background()
	var vm ekuma.VM
	promise, resolver := vm.NewPromise()
	if err := vm.Global().Set("message", promise); err != nil {
		panic(err)
	}
	s, err := vm.ParseScript("greeting.js", `message.then((name) => "Hello, " + name)`)
	if err != nil {
		panic(err)
	}
	greeting, err := s.Evaluate(ctx)
	if err != nil {
		panic(err)
	}
	state, _ := greeting.PromiseState()
	fmt.Println(state)

	if err := resolver.Resolve(ctx, "Ekuma"); err != nil {
		panic(err)
	}
	state, value := greeting.PromiseState()
	fmt.Println(state, value.String())

}
Output:
pending
fulfilled Hello, Ekuma

func (*VM) NewRealm

func (vm *VM) NewRealm() *Realm

NewRealm returns a new realm of vm.

Example
package main

import (
	"context"
	"fmt"

	"github.com/hajimehoshi/ekuma"
)

func main() {
	var vm ekuma.VM
	r := vm.NewRealm()
	if err := vm.Global().Set("other", r.Global()); err != nil {
		fmt.Println(err)
		return
	}
	s, err := vm.ParseScript("main.js", `
		Array.prototype.first = function() { return this[0]; };
		[typeof [].first, typeof other.eval("[]").first, other.Array === Array].join()`)
	if err != nil {
		fmt.Println(err)
		return
	}
	v, err := s.Evaluate(context.Background())
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(v)
}
Output:
function,undefined,false

func (*VM) NewSyntheticModule

func (vm *VM) NewSyntheticModule(name string, v Value) *Module

NewSyntheticModule is Realm.NewSyntheticModule of the initial realm.

func (*VM) ParseJSONModule

func (vm *VM) ParseJSONModule(name, src string) (*Module, error)

ParseJSONModule is Realm.ParseJSONModule of the initial realm.

func (*VM) ParseModule

func (vm *VM) ParseModule(name, src string) (*Module, error)

ParseModule is Realm.ParseModule of the initial realm.

func (*VM) ParseScript

func (vm *VM) ParseScript(name, src string) (*Script, error)

ParseScript is Realm.ParseScript of the initial realm.

Example

This example parses a script once and evaluates it several times.

package main

import (
	"context"
	"fmt"

	"github.com/hajimehoshi/ekuma"
)

func main() {
	var vm ekuma.VM
	s, err := vm.ParseScript("count.js", `globalThis.n = (globalThis.n ?? 0) + 1`)
	if err != nil {
		fmt.Println(err)
		return
	}
	for range 3 {
		v, err := s.Evaluate(context.Background())
		if err != nil {
			fmt.Println(err)
			return
		}
		fmt.Println(v.Int())
	}
}
Output:
1
2
3

func (*VM) SetCanBlock

func (vm *VM) SetCanBlock(canBlock bool)

SetCanBlock sets whether Atomics.wait may block the VM. The default is false.

func (*VM) SetClock

func (vm *VM) SetClock(now func() time.Time)

SetClock sets now as the clock that gives the current time to Date, Temporal.Now, the default date of Intl.DateTimeFormat, and the timeouts of Atomics.wait and Atomics.waitAsync. A nil now restores time.Now. Only the instant of a time matters, not its location; VM.SetTimeZone sets the time zone. A timeout ends no earlier than the clock passes it, and for Atomics.wait no earlier than its duration in real time. A time outside the range of Date reads as the nearest end of the range. now is called on the goroutine that runs JavaScript in the VM.

func (*VM) SetImportMeta

func (vm *VM) SetImportMeta(f func(m *Module) map[string]any)

SetImportMeta sets f as the implementation of HostGetImportMetaProperties. On first use of import.meta in a module, f supplies its properties, which are converted with Realm.ValueOf in the module's realm. A nil f supplies no properties.

A reentrant access during f sees the same object, which receives the properties after f returns. If f panics, the next access retries initialization on that object.

func (*VM) SetLocale

func (vm *VM) SetLocale(locale string) error

SetLocale sets the default locale for locale-sensitive operations in every realm. A locale that is not available uses its longest available prefix, such as "ja" for "ja-XX", and an empty locale or one without an available prefix uses the host default. Existing Intl instances keep their locale. A malformed locale returns an error without changing the default.

func (*VM) SetModuleLoader

func (vm *VM) SetModuleLoader(f func(req ModuleRequest) (*Module, error))

SetModuleLoader sets f as the implementation of HostLoadImportedModule, which import declarations and import() use. f must return a *Module belonging to vm and return the same *Module for repeated requests for the same module.

The error of f is thrown the way the error of a Func is, except that a *SyntaxError throws a JavaScript SyntaxError. import() rejects its promise with it, and the methods of Module return it as a *ScriptError.

Unsupported attributes cause a SyntaxError when loading a static import and cause import() to reject its promise with a TypeError.

An import fails with a TypeError when there is no loader, when f returns a nil *Module without an error, or when the module is being loaded by a call that has not finished. A nil f removes the loader. The loader applies to subsequent module loads. Already loaded modules retain their loaded dependencies.

func (*VM) SetRandomSource

func (vm *VM) SetRandomSource(src rand.Source)

SetRandomSource sets src as the source of random numbers for Math.random. A nil src restores the default, a source that is seeded randomly. The source applies to the later calls of Math.random, which return the numbers that rand.New(src).Float64 would.

func (*VM) SetTimeZone

func (vm *VM) SetTimeZone(loc *time.Location)

SetTimeZone sets loc as the local time zone for Date, the system time zone for Temporal, and the default time zone for new Intl.DateTimeFormat instances. A nil loc restores the local time zone of the host. Date uses loc's rules when loc is time.Local or the platform does not recognize its name. Otherwise Date uses the platform's rules for that name. Temporal and Intl resolve the zone by identifier even for time.Local. If loc has no usable identifier, they use its current UTC offset.

func (*VM) SetUnhandledRejection

func (vm *VM) SetUnhandledRejection(f func(promise, reason Value))

SetUnhandledRejection sets f as the callback for each promise rejected with reason that has no rejection handler. f is called when the outermost call from Go into vm has run the pending jobs, once for each such promise, in the order of rejection. A promise is reported once, and a handler added later does not undo the report. This includes the promise that Module.Evaluate returns for a module that throws.

f may call into vm and run JavaScript. The jobs that this queues, and the reports of the promises that this rejects, run before the outermost call returns.

The reports that are made after the call go to f, including those of promises that were rejected earlier in a call that is running. A nil f stops the reports, and the promises that would have been reported are discarded.

func (*VM) ValueOf

func (vm *VM) ValueOf(x any) Value

ValueOf returns x as a JavaScript value:

| Go                     | JavaScript             |
| ---------------------- | ---------------------- |
| Value                  | [its value]            |
| Func                   | function               |
| nil                    | null                   |
| bool                   | boolean                |
| integers and floats    | number                 |
| *big.Int               | bigint                 |
| *SharedDataBlock       | new SharedArrayBuffer  |
| string                 | string                 |
| []any                  | new array              |
| map[string]any         | new object             |

A string is taken to be UTF-8. The keys of a map become properties in sorted order. A function of the type underlying Func is taken as a Func. ValueOf panics when x is not one of the expected types, or is a nil pointer or a nil Func, or a *big.Int of more than 2^30 bits, the largest BigInt. It panics for a string, symbol, object or function of another VM, including values nested in arrays and maps, and for a map or slice that contains itself.

The objects that ValueOf creates belong to the initial realm.

func (*VM) WithContinuationData

func (vm *VM) WithContinuationData(data any, f func())

WithContinuationData calls f with data as the continuation data, and restores the previous continuation data when f returns or panics.

A promise job runs with the continuation data that was current when it was registered: when then was called, await was reached, or a promise was resolved with a thenable. The cleanup callback of a FinalizationRegistry runs with the continuation data that was current when the registry was made.

type Value

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

Value is a JavaScript value. The zero value is undefined.

Values cannot be compared with ==. Use Value.Equal to compare them with JavaScript === semantics.

Strings, symbols, objects and functions belong to their creating VM and may pass between its realms. Passing them into another VM panics, including through host callback results and exceptions. Other primitives may pass between VMs. To share SharedArrayBuffer memory, pass its SharedDataBlock to VM.ValueOf.

var (
	// Undefined is the value undefined.
	Undefined Value

	// Null is the value null.
	Null = fromEngine(storage.Null)
)

func (Value) BigInt

func (v Value) BigInt() *big.Int

BigInt returns the BigInt v as a new *big.Int. It panics with a *ValueError when v is not a BigInt.

func (Value) Bool

func (v Value) Bool() bool

Bool returns the boolean v. It panics with a *ValueError when v is not a boolean.

func (Value) Call

func (v Value) Call(ctx context.Context, name string, args ...any) (Value, error)

Call calls the method named name on v with v as this. The arguments are converted with VM.ValueOf. The errors are those of Value.Get, and a method that does not exist is a *ScriptError holding a TypeError. When ctx is done, the call stops at its next loop iteration or call, and the error is the cause of ctx.

func (Value) CallWithValueKey

func (v Value) CallWithValueKey(ctx context.Context, key Value, args ...any) (Value, error)

CallWithValueKey is like Value.Call, but takes key as Value.GetWithValueKey does.

func (Value) Delete

func (v Value) Delete(name string) error

Delete deletes the property named name from v, as the delete operator in strict mode does. The errors are those of Value.Get.

func (Value) DeleteWithValueKey

func (v Value) DeleteWithValueKey(key Value) error

DeleteWithValueKey is like Value.Delete, but takes key as Value.GetWithValueKey does.

func (Value) Equal

func (v Value) Equal(w Value) bool

Equal reports whether v and w are equal according to the JavaScript === operator.

func (Value) Float

func (v Value) Float() float64

Float returns the number v. A NaN always has the bits 0x7ff8000000000000. Float panics with a *ValueError when v is not a number.

func (Value) Get

func (v Value) Get(name string) (Value, error)

Get returns the value of the property named name on v.

The error is a *ValueError when v is not an object, a function or a string, and a *ScriptError when the operation throws a JavaScript exception.

func (Value) GetWithValueKey

func (v Value) GetWithValueKey(key Value) (Value, error)

GetWithValueKey is like Value.Get, but key is converted to a property key the way the expression v[key] converts it, and a conversion that throws is a *ScriptError. It panics if key belongs to a different VM from v.

func (Value) Index

func (v Value) Index(i int) (Value, error)

Index returns the property of v named by the decimal representation of i. The errors are those of Value.Get.

func (Value) InstanceOf

func (v Value) InstanceOf(t Value) (bool, error)

InstanceOf reports whether v is an instance of the constructor t, as the instanceof operator does. The errors are those of Value.Get, for t. It panics if v belongs to a different VM from t.

func (Value) Int

func (v Value) Int() int

Int returns the number v truncated toward zero to an int. NaN gives 0, and a number below or above the range of an int gives math.MinInt or math.MaxInt. It panics with a *ValueError when v is not a number.

func (Value) Invoke

func (v Value) Invoke(ctx context.Context, args ...any) (Value, error)

Invoke calls the function v with undefined as this. The arguments are converted with VM.ValueOf. The error is a *ValueError when v is not a function, and a *ScriptError when it throws. When ctx is done, the call stops at its next loop iteration or call, and the error is the cause of ctx.

Example
package main

import (
	"context"
	"fmt"

	"github.com/hajimehoshi/ekuma"
)

func main() {
	ctx := context.Background()
	var vm ekuma.VM
	s, err := vm.ParseScript("total.js", `(order) => order.price * order.quantity`)
	if err != nil {
		panic(err)
	}
	total, err := s.Evaluate(ctx)
	if err != nil {
		panic(err)
	}
	v, err := total.Invoke(ctx, map[string]any{
		"price":    12,
		"quantity": 3,
	})
	if err != nil {
		panic(err)
	}
	fmt.Println(v.Int())

}
Output:
36

func (Value) IsNaN

func (v Value) IsNaN() bool

IsNaN reports whether v is the number NaN.

func (Value) IsNull

func (v Value) IsNull() bool

IsNull reports whether v is null.

func (Value) IsPromise

func (v Value) IsPromise() bool

IsPromise reports whether v is a Promise object. A mere thenable is not a Promise object.

func (Value) IsUndefined

func (v Value) IsUndefined() bool

IsUndefined reports whether v is undefined.

func (Value) New

func (v Value) New(ctx context.Context, args ...any) (Value, error)

New calls the function v as a constructor, as the new operator does. The arguments are converted with VM.ValueOf. The errors are those of Value.Invoke.

func (Value) PromiseState

func (v Value) PromiseState() (PromiseState, Value)

PromiseState returns the state of the promise v and, unless it is pending, its result: the value it was fulfilled with or the reason it was rejected with. It runs no JavaScript and does not mark a rejected promise as handled. It panics with a *ValueError when v is not a promise.

func (Value) Set

func (v Value) Set(name string, x any) error

Set sets the property named name on v to VM.ValueOf(x), as an assignment in strict mode does. The errors are those of Value.Get.

func (Value) SetIndex

func (v Value) SetIndex(i int, x any) error

SetIndex sets the property of v named by the decimal representation of i to VM.ValueOf(x). The errors are those of Value.Get.

func (Value) SetWithValueKey

func (v Value) SetWithValueKey(key Value, x any) error

SetWithValueKey is like Value.Set, but takes key as Value.GetWithValueKey does.

func (Value) SharedDataBlock

func (v Value) SharedDataBlock() *SharedDataBlock

SharedDataBlock returns the data block of the SharedArrayBuffer v. It panics with a *ValueError when v is not a SharedArrayBuffer.

func (Value) String

func (v Value) String() string

String returns the string v as UTF-8, with lone surrogates replaced by U+FFFD. For a value of another type, it returns a description such as "<object>" or "<number: 42>" and runs no JavaScript.

func (Value) Truthy

func (v Value) Truthy() bool

Truthy returns the boolean that v converts to.

func (Value) Type

func (v Value) Type() Type

Type returns the type of v.

type ValueError

type ValueError struct {
	Method string
	Type   Type
}

ValueError reports an operation that is unsupported for a Value's type. Operations that do not return an error panic with a *ValueError instead.

func (*ValueError) Error

func (e *ValueError) Error() string

Directories

Path Synopsis
internal
ast
Package ast defines the syntax tree and the scope records of ECMAScript source text.
Package ast defines the syntax tree and the scope records of ECMAScript source text.
builtin
Package builtin installs the standard ECMAScript built-in objects in each realm.
Package builtin installs the standard ECMAScript built-in objects in each realm.
builtin/intl
Package intl implements the Intl built-in objects of ECMA-402.
Package intl implements the Intl built-in objects of ECMA-402.
bytecode
Package bytecode defines the instructions that the compiler emits and the interpreter executes.
Package bytecode defines the instructions that the compiler emits and the interpreter executes.
collection
Package collection implements the ordered tables of the keyed collections Map and Set.
Package collection implements the ordered tables of the keyed collections Map and Set.
compiler
Package compiler translates a syntax tree to bytecode.
Package compiler translates a syntax tree to bytecode.
datetime
Package datetime implements the date and time operations of ECMAScript.
Package datetime implements the date and time operations of ECMAScript.
element
Package element provides the element types of typed arrays and the encodings of their elements.
Package element provides the element types of typed arrays and the encodings of their elements.
engine
Package engine implements the JavaScript virtual machine: the interpreter and the abstract operations of the language.
Package engine implements the JavaScript virtual machine: the interpreter and the abstract operations of the language.
icutest
Package icutest runs ICU test data against Ekuma.
Package icutest runs ICU test data against Ekuma.
intl/calendar
Package calendar implements the calendars of ECMA-402 other than ISO 8601: their arithmetic, month codes and eras.
Package calendar implements the calendars of ECMA-402 other than ISO 8601: their arithmetic, month codes and eras.
intl/collate
Package collate implements the Unicode Collation Algorithm with the CLDR root collation and the tailorings of CLDR.
Package collate implements the Unicode Collation Algorithm with the CLDR root collation and the tailorings of CLDR.
intl/date
Package date formats dates and times as Intl.DateTimeFormat does, with the CLDR data of package cldr.
Package date formats dates and times as Intl.DateTimeFormat does, with the CLDR data of package cldr.
intl/displaynames
Package displaynames provides the display names of Intl.DisplayNames.
Package displaynames provides the display names of Intl.DisplayNames.
intl/duration
Package duration formats durations as Intl.DurationFormat does.
Package duration formats durations as Intl.DurationFormat does.
intl/list
Package list formats lists as Intl.ListFormat does.
Package list formats lists as Intl.ListFormat does.
intl/locale
Package locale resolves Unicode BCP 47 locale identifiers against CLDR data.
Package locale resolves Unicode BCP 47 locale identifiers against CLDR data.
intl/number
Package number implements the locale-independent and locale-dependent number formatting of ECMA-402: the Intl mathematical values, their rounding, and the parts that Intl.NumberFormat formats them into.
Package number implements the locale-independent and locale-dependent number formatting of ECMA-402: the Intl mathematical values, their rounding, and the parts that Intl.NumberFormat formats them into.
intl/plural
Package plural implements the plural rules of the Unicode Common Locale Data Repository.
Package plural implements the plural rules of the Unicode Common Locale Data Repository.
intl/reltime
Package reltime provides the patterns of relative times for Intl.RelativeTimeFormat.
Package reltime provides the patterns of relative times for Intl.RelativeTimeFormat.
intl/segment
Package segment implements UAX #29 segmentation with dictionary word boundaries and locale tailorings.
Package segment implements UAX #29 segmentation with dictionary word boundaries and locale tailorings.
json
Package json implements JSON for JavaScript values, whose strings are in WTF-8: parsing text into values, calling a reviver on them, converting values to text, and the lexical grammar.
Package json implements JSON for JavaScript values, whose strings are in WTF-8: parsing text into values, calling a reviver on them, converting values to text, and the lexical grammar.
jstest
Package jstest runs Ekuma's JavaScript test suites from the repository root.
Package jstest runs Ekuma's JavaScript test suites from the repository root.
localetag
Package localetag parses Unicode BCP 47 locale identifiers.
Package localetag parses Unicode BCP 47 locale identifiers.
modulegraph
Package modulegraph resolves the exports of modules.
Package modulegraph resolves the exports of modules.
numconv
Package numconv implements the conversions between JavaScript numbers and strings, the integer and binary16 conversions of numbers, and arithmetic of numbers and BigInts.
Package numconv implements the conversions between JavaScript numbers and strings, the integer and binary16 conversions of numbers, and arithmetic of numbers and BigInts.
parser
Package parser parses ECMAScript source text into the syntax tree of package ast.
Package parser parses ECMAScript source text into the syntax tree of package ast.
quiet
Package quiet holds the operations that run no script or host code, for the engine and for the built-in objects, and the fast forms of built-in functions made of them.
Package quiet holds the operations that run no script or host code, for the engine and for the built-in objects, and the fast forms of built-in functions made of them.
regexp
Package regexp implements ECMAScript regular expressions.
Package regexp implements ECMAScript regular expressions.
shortstrings
Package shortstrings operates on packed canonical WTF-8 strings.
Package shortstrings operates on packed canonical WTF-8 strings.
srcpos
Package srcpos converts byte offsets in source text into lines and columns.
Package srcpos converts byte offsets in source text into lines and columns.
storage
Package storage holds the values, the objects and the shapes of JavaScript, and the operations on them that run no code.
Package storage holds the values, the objects and the shapes of JavaScript, and the operations on them that run no code.
temporal
Package temporal implements the abstract operations of the Temporal built-in objects: the ISO 8601 calendar, epoch nanoseconds, durations and their rounding, time zones, and the RFC 9557 string format.
Package temporal implements the abstract operations of the Temporal built-in objects: the ISO 8601 calendar, epoch nanoseconds, durations and their rounding, time zones, and the RFC 9557 string format.
unorm
Package unorm implements the Unicode normalization forms of UAX #15 for any length of the runs of non-starters.
Package unorm implements the Unicode normalization forms of UAX #15 for any length of the runs of non-starters.
waiterlist
Package waiterlist provides lists of waiters that refer to the waiters weakly.
Package waiterlist provides lists of waiters that refer to the waiters weakly.
wtf8
Package wtf8 implements JavaScript string semantics on Go strings.
Package wtf8 implements JavaScript string semantics on Go strings.
xerrors
Package xerrors carries failures that cannot be handled by JavaScript.
Package xerrors carries failures that cannot be handled by JavaScript.
xmath
Package xmath implements floating-point functions more accurate than those of package math.
Package xmath implements floating-point functions more accurate than those of package math.
xstrings
Package xstrings provides substring search and ECMAScript whitespace trimming for WTF-8 strings, and case mapping for valid UTF-8 strings.
Package xstrings provides substring search and ECMAScript whitespace trimming for WTF-8 strings, and case mapping for valid UTF-8 strings.
Package intl adds the ECMAScript Internationalization API (ECMA-402) to the VMs of package github.com/hajimehoshi/ekuma.
Package intl adds the ECMAScript Internationalization API (ECMA-402) to the VMs of package github.com/hajimehoshi/ekuma.

Jump to

Keyboard shortcuts

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