js

package
v1.16.0 Latest Latest
Warning

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

Go to latest
Published: Nov 12, 2026 License: MIT Imports: 27 Imported by: 0

Documentation

Overview

Package js is a Go model of JavaScript values with the language's exact semantics, for components that tern build compiles to Go (ADR 0011). Generated code calls it; it is not covered by the stability promise.

A Value is one of:

Undefined, Null       the two sentinels
bool                  a boolean
float64               a number
string                a string, UTF-8 encoded; lengths and indexes are UTF-16
*Object               an object, including functions and arrays
*Symbol               a symbol

Index

Constants

View Source
const (
	CtlNone = iota
	CtlReturn
	CtlBreak
	CtlContinue
)

Control codes: how a try block's closure was left.

View Source
const MaxDepth = 10000

MaxDepth is how deep calls may nest before a RangeError, as engines have: Go's stack would otherwise overflow, which ends the process.

Variables

View Source
var (
	SymbolIterator    = &Symbol{"Symbol.iterator"}
	SymbolToPrimitive = &Symbol{"Symbol.toPrimitive"}
	// SymbolAsyncIterator is Symbol.asyncIterator.
	SymbolAsyncIterator = &Symbol{"Symbol.asyncIterator"}
	SymbolToStringTag   = &Symbol{"Symbol.toStringTag"}
)

Well-known symbols.

View Source
var ErrInterrupted = errors.New("js: interrupted")

ErrInterrupted is what a realm's code panics with once Interrupt is called.

View Source
var Hole = hole

Hole is the element of an elision in an array literal.

View Source
var UnknownPrivate = &PrivateName{Description: "#unknown"}

UnknownPrivate stands for a private name the compiler couldn't find.

Functions

func CopyDataProperties

func CopyDataProperties(target *Object, src Value)

CopyDataProperties is object spread: {...src}.

func DefineField

func DefineField(obj Value, key PropKey, v Value)

DefineField is a class field: an own, enumerable property.

func Delete

func Delete(v Value, key PropKey) bool

Delete is the delete operator on v[key].

func FromUnits

func FromUnits(u []uint16) string

FromUnits encodes UTF-16 code units, pairing surrogates where they pair.

func HasPrivate added in v1.8.0

func HasPrivate(obj Value, name *PrivateName) bool

HasPrivate is #name in obj.

func In

func In(key Value, obj Value) bool

In is the in operator.

func InheritStatics

func InheritStatics(ctor *Object, parent Value)

InheritStatics makes a subclass's constructor inherit the parent's statics.

func InstanceOfProto added in v1.6.0

func InstanceOfProto(v Value, proto *Object) bool

InstanceOfProto reports whether proto is on v's prototype chain.

func IsArray

func IsArray(v Value) bool

IsArray is Array.isArray.

func IsConstructor

func IsConstructor(v Value) bool

IsConstructor reports whether new can call v.

func IsNullish

func IsNullish(v Value) bool

IsNullish reports whether v is undefined or null.

func IsPlainArray added in v1.8.0

func IsPlainArray(o *Object) bool

IsPlainArray reports whether o is an array whose length is there without running code: an array, not a proxy of one.

func Itoa

func Itoa(i int) string

Itoa formats an integer index as a property key.

func Join

func Join(a []Value, sep string) string

Join is Array.prototype.join: undefined and null become "".

func LooseEquals

func LooseEquals(a, b Value) bool

LooseEquals is ==.

func Nullish

func Nullish(v Value) bool

Nullish is a ?? b's test.

func NumberToString

func NumberToString(x float64) string

NumberToString is Number::toString(x) with radix 10.

func PrivateAccessor

func PrivateAccessor(obj Value, name *PrivateName, get, set Value)

PrivateAccessor adds a private getter or setter.

func PrivateDefine

func PrivateDefine(obj Value, name *PrivateName, v Value)

PrivateDefine adds a private field or method to an object.

func PrivateSet

func PrivateSet(obj Value, name *PrivateName, v Value)

PrivateSet writes obj.#name.

func QuoteJSON

func QuoteJSON(b *strings.Builder, s string)

QuoteJSON writes s as a JSON string, as JSON.stringify quotes it: lone surrogates become \u escapes.

func RequireObjectCoercible

func RequireObjectCoercible(v Value)

RequireObjectCoercible throws for destructuring undefined or null.

func SameValue

func SameValue(a, b Value) bool

SameValue is Object.is.

func SameValueZero

func SameValueZero(a, b Value) bool

SameValueZero is SameValueZero, for includes and Map keys.

func Set

func Set(v Value, key PropKey, val Value)

Set is v[key] = val in strict mode code.

func SetProtoFromLiteral

func SetProtoFromLiteral(o *Object, v Value)

SetProtoFromLiteral is __proto__: v in an object literal.

func SetUndefined added in v1.16.0

func SetUndefined(first *Value, n int)

SetUndefined sets n Values in a row, from first, to Undefined: the fields of a compiled module's variables, which are js.Values one after another, so they're laid out without gaps.

func SetV

func SetV(v Value, k Value, val Value)

SetV is v[k] = val where k is any value.

func StrictEquals

func StrictEquals(a, b Value) bool

StrictEquals is ===.

func StringToNumber

func StringToNumber(s string) float64

StringToNumber is StringToNumber: decimal, 0x/0o/0b integers, Infinity, and the empty string as 0.

func SuperSet

func SuperSet(proto *Object, key PropKey, v Value, this Value)

SuperSet is super[key] = v.

func ToDisplay

func ToDisplay(v Value) string

ToDisplay describes a value for error messages, without running any code.

func ToFixed

func ToFixed(x float64, d int) string

ToFixed is Number.prototype.toFixed.

func ToGo

func ToGo(v Value) any

ToGo converts a primitive to Go: nil, bool, int (for whole numbers), float64 or string. Objects become their string conversion's result.

func ToInt32

func ToInt32(v Value) int32

ToInt32 is ToInt32, for the bitwise operators.

func ToIntegerOrInfinity

func ToIntegerOrInfinity(v Value) float64

ToIntegerOrInfinity is ToIntegerOrInfinity.

func ToNumber

func ToNumber(v Value) float64

ToNumber is the abstract operation ToNumber.

func ToString

func ToString(v Value) string

ToString is the abstract operation ToString.

func ToUint32

func ToUint32(v Value) uint32

ToUint32 is ToUint32.

func TrimJSSpace

func TrimJSSpace(s string) string

TrimJSSpace trims what String.prototype.trim trims.

func Truthy

func Truthy(v Value) bool

Truthy is ToBoolean.

func Typeof

func Typeof(v Value) string

Typeof is the typeof operator.

func Units

func Units(s string) []uint16

Units decodes s into UTF-16 code units.

Types

type Boxer added in v1.15.0

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

Boxer hands out the boxes of strings and numbers from slabs. Putting a string or a float64 in an interface allocates a box for it, 16 or 8 bytes, which is most of a render's allocations; a Boxer makes one allocation per slab instead. The Values are ordinary interfaces, and a slab stays alive while any of its Values does, which during a render is the render.

A Boxer belongs to one goroutine at a time, as a Realm does.

func (*Boxer) Num added in v1.15.0

func (b *Boxer) Num(f float64) Value

Num returns f as a Value; small integers need no box at all.

func (*Boxer) Str added in v1.15.0

func (b *Boxer) Str(s string) Value

Str returns s as a Value.

type FnInfo

type FnInfo struct {
	Name   string
	Length int
	// Src, Module, Start and End locate the source text: UTF-16 offsets
	// into one module of Src.
	Src                *Sources
	Module, Start, End int
}

FnInfo is what a function knows about itself: its name, its length (the number of declared parameters) and, for compiled functions, its source text, which toString returns. Compiled code has one per function in its source, shared by every closure made from it.

func (*FnInfo) Source

func (f *FnInfo) Source() string

Source is the function's source text, or "" for a built-in.

type Gen

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

Gen is a generator object's state.

func (*Gen) AsyncYield added in v1.6.0

func (g *Gen) AsyncYield(v Value) Value

AsyncYield is yield in an async generator: the value is awaited first.

func (*Gen) Await

func (g *Gen) Await(v Value) Value

Await is an await expression: the body waits for v to settle, and gets its value, or its reason thrown.

func (*Gen) Yield

func (g *Gen) Yield(v Value) Value

Yield is a yield expression: it hands v to the consumer and returns what the next call to next passes.

func (*Gen) YieldStar

func (g *Gen) YieldStar(v Value) Value

YieldStar is yield* v.

type GlobalRef

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

GlobalRef caches a global's value at one place in compiled code.

type IC

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

IC is one access site's cache.

type Object

type Object struct {

	// Internal slots: Map and Set data, a RegExp, a Date's time, a boxed primitive.
	Internal any
	// Class is the kind of built-in object, such as "Map" or "Error", for
	// Object.prototype.toString and instanceof checks of built-ins.
	Class string
	// contains filtered or unexported fields
}

Object is a JavaScript object. Functions, arrays and the built-in objects with internal slots (Map, Set, RegExp, Date, errors) are objects with the matching fields set.

func AsObject

func AsObject(v Value) *Object

AsObject asserts that a compiled function expression is a function object.

func ClassParentProto

func ClassParentProto(parent Value) *Object

ClassParentProto is the prototype of a class's instances' prototype: the superclass's prototype, or null for extends null.

func NewNamespace

func NewNamespace() *Object

NewNamespace makes a module namespace object.

func NewObject

func NewObject(proto *Object) *Object

NewObject makes an ordinary object with the given prototype (nil for none).

func OrdinaryCreateFromConstructor

func OrdinaryCreateFromConstructor(newTarget *Object, fallback *Object) *Object

OrdinaryCreateFromConstructor makes the object a constructor builds: its prototype is newTarget.prototype, or fallback.

func ProtoOf

func ProtoOf(v Value) *Object

ProtoOf is an object's prototype, for super in object literal methods.

func WithInfo

func WithInfo(o *Object, info *FnInfo) *Object

WithInfo sets o's info and returns o, for compiled code.

func (*Object) ArrayElements added in v1.8.0

func (o *Object) ArrayElements() ([]Value, bool)

ArrayElements is an array's elements, when it's a plain array: no holes, no proxy. ok is false otherwise.

func (*Object) Define

func (o *Object) Define(key PropKey, v Value)

Define makes an own, enumerable, writable data property, as an object literal does.

func (*Object) DefineAccessor

func (o *Object) DefineAccessor(key PropKey, get, set *Object, enumerable bool)

DefineAccessor makes a getter and/or setter property. Object literals' accessors are enumerable; classes' are not.

func (*Object) DefineHidden

func (o *Object) DefineHidden(key PropKey, v Value)

DefineHidden makes an own, non-enumerable data property, as built-ins and class methods have.

func (*Object) DefineProperty

func (o *Object) DefineProperty(key PropKey, desc *Object)

DefineProperty is Object.defineProperty with a parsed descriptor.

func (*Object) Delete

func (o *Object) Delete(key PropKey) bool

Delete is the delete operator.

func (*Object) Elems

func (o *Object) Elems() []Value

Elems returns an array's elements, which the caller may read but not keep.

func (*Object) EnumerableOwn

func (o *Object) EnumerableOwn(fn func(key string, v Value))

EnumerableOwn calls fn for each enumerable own string-keyed property, in order, as Object.keys, for…in over own keys and object spread do.

func (*Object) Freeze

func (o *Object) Freeze()

Freeze is Object.freeze.

func (*Object) Get

func (o *Object) Get(key PropKey) Value

Get is [[Get]] with o as the receiver.

func (*Object) GetFrom

func (o *Object) GetFrom(key PropKey, receiver Value) Value

GetFrom is [[Get]] with another receiver, for getters on prototypes and for primitives' methods.

func (*Object) GetOwn

func (o *Object) GetOwn(key PropKey) (Value, bool)

GetOwn returns an own data property's value without running getters.

func (*Object) Has

func (o *Object) Has(key PropKey) bool

Has is the in operator.

func (*Object) HasOwn

func (o *Object) HasOwn(key PropKey) bool

HasOwn is Object.hasOwn.

func (*Object) HasOwnString added in v1.8.0

func (o *Object) HasOwnString(key string) (has, ok bool)

HasOwnString is Object.prototype.hasOwnProperty for a string key, for ordinary objects; ok is false for proxies and exotic objects, where it could run code or needs the full algorithm.

func (*Object) IsCallable

func (o *Object) IsCallable() bool

IsCallable reports whether o is a function.

func (*Object) IsFrozen

func (o *Object) IsFrozen() bool

IsFrozen is Object.isFrozen.

func (*Object) OwnKeys

func (o *Object) OwnKeys(onlyEnumerable, withSymbols bool) []PropKey

OwnKeys lists own property keys in JavaScript's order: array indexes ascending, then strings in creation order, then symbols.

func (*Object) PlainEach added in v1.15.0

func (o *Object) PlainEach(fn func(key string, v Value)) (ok bool)

PlainEach calls fn with each own enumerable string-keyed property of an ordinary object, in property order, without allocating; ok is false where PlainEntries would be, and for objects with integer keys, which come first in property order.

func (*Object) PlainEntries added in v1.8.0

func (o *Object) PlainEntries() (keys []string, vals []Value, ok bool)

PlainEntries is Object.keys(o) with each key's value, when reading them can't run code: o is an ordinary object (not an array, typed array or proxy) whose own string-keyed properties are all data properties. ok is false otherwise, for code with a fast path for plain objects.

func (*Object) Proto

func (o *Object) Proto() *Object

Proto is the object's prototype, or nil.

func (*Object) Push

func (o *Object) Push(v ...Value)

Push appends to an array.

func (*Object) Set

func (o *Object) Set(key PropKey, v Value)

Set is [Set] in strict mode code: it throws where sloppy code would silently fail.

func (*Object) SetConstruct

func (o *Object) SetConstruct(fn func(args []Value, newTarget *Object) Value)

SetConstruct makes an existing function a constructor.

func (*Object) SetFrom

func (o *Object) SetFrom(key PropKey, v Value, receiver Value)

SetFrom is [Set] with a receiver.

func (*Object) SetInfo

func (o *Object) SetInfo(info *FnInfo)

SetInfo describes a function made another way, such as a class.

func (*Object) SetProto

func (o *Object) SetProto(p *Object)

SetProto changes the prototype. The shape follows: shapes know their prototype.

type PrivateName

type PrivateName struct{ Description string }

PrivateName is a class's #name; each evaluation of the class makes new ones.

func NewPrivateName

func NewPrivateName(desc string) *PrivateName

NewPrivateName makes a private name.

type PropKey

type PropKey = any

PropKey is a property key: a string or a *Symbol.

func ToPropertyKey

func ToPropertyKey(v Value) PropKey

ToPropertyKey is ToPropertyKey.

type Realm

type Realm struct {

	// The intrinsic objects.
	ObjectPrototype, FunctionPrototype, ArrayPrototype, StringPrototype *Object
	NumberPrototype, BooleanPrototype, SymbolPrototype, ErrorPrototype  *Object
	IteratorPrototype, DatePrototype, RegExpPrototype, PromisePrototype *Object

	ArrayBufferPrototype, TypedArrayPrototype, DataViewPrototype *Object
	GeneratorPrototype, GeneratorFunctionPrototype               *Object
	ObjectCtor, FunctionCtor, ArrayCtor, StringCtor, NumberCtor  *Object
	BooleanCtor, SymbolCtor                                      *Object
	Error, TypeError, RangeError, SyntaxError, ReferenceError    *Object

	BigIntPrototype         *Object
	AsyncIteratorPrototype  *Object
	AsyncGeneratorPrototype *Object

	// Global is globalThis.
	Global *Object
	// contains filtered or unexported fields
}

A Realm is a world of JavaScript objects: its own built-ins, globalThis and module state. Realms share nothing that changes, so each can run on its own goroutine; one realm runs one thing at a time.

func NewRealm

func NewRealm() *Realm

NewRealm makes a realm with the built-ins and an empty globalThis.

func (*Realm) Add

func (rt *Realm) Add(a, b Value) Value

Add is the + operator.

func (*Realm) ArrayValues

func (rt *Realm) ArrayValues() Value

ArrayValues is Array.prototype.values, to tell built-in iteration apart.

func (*Realm) AsyncIterate added in v1.6.0

func (rt *Realm) AsyncIterate(v Value) func() Value

AsyncIterate starts a for await: it returns the function that gets the next result's promise. A sync iterable is wrapped, its values awaited.

func (*Realm) CallIC

func (rt *Realm) CallIC(c *IC, obj Value, key string, args ...Value) Value

CallIC is obj.key(…args) with a cache.

func (*Realm) CallMethod

func (rt *Realm) CallMethod(obj Value, key PropKey, args ...Value) Value

CallMethod is obj[key](...args), with obj as this.

func (*Realm) CallMethodV

func (rt *Realm) CallMethodV(obj Value, key Value, args ...Value) Value

CallMethodV is obj[key](...args) with a computed key.

func (*Realm) CompareStrings

func (rt *Realm) CompareStrings(a, b string) int

CompareStrings orders strings by UTF-16 code units, as < does.

func (*Realm) Concat

func (rt *Realm) Concat(a, b string) string

Concat is a + b for strings.

func (*Realm) CopyDataPropertiesExcluding

func (rt *Realm) CopyDataPropertiesExcluding(src Value, excluded []PropKey) *Object

CopyDataPropertiesExcluding is an object pattern's rest element.

func (*Realm) DropJobs

func (rt *Realm) DropJobs()

DropJobs forgets the queued jobs.

func (*Realm) DynamicImport added in v1.6.0

func (rt *Realm) DynamicImport(load func() Value) *Object

DynamicImport is import() of a compiled module: a promise that loads the module in a job, as bundlers compile import(). A render never runs the job, in QuickJS or natively.

func (*Realm) ExportLive

func (rt *Realm) ExportLive(ns *Object, name string, get func() Value)

ExportLive adds a live binding to a namespace.

func (*Realm) FailedImport added in v1.6.0

func (rt *Realm) FailedImport(spec Value) *Object

FailedImport is import() of a module no bundle has, such as a Node built-in: a promise that rejects in a job.

func (*Realm) ForInKeys

func (rt *Realm) ForInKeys(v Value) func() (Value, bool)

ForInKeys returns a for…in's next function: enumerable string keys of the object and its prototypes, each once.

func (*Realm) ForOf

func (rt *Realm) ForOf(v Value, fn func(Value) bool)

ForOf runs fn for each value of a for…of over v, until fn returns false.

func (*Realm) Get

func (rt *Realm) Get(v Value, key PropKey) Value

Get is v[key] for any value: objects, and primitives through their prototypes.

func (*Realm) GetIC

func (rt *Realm) GetIC(c *IC, v Value, key string) Value

GetIC is obj.key with a cache.

func (*Realm) GetOptional

func (rt *Realm) GetOptional(v Value, key PropKey) Value

GetOptional is v?.[key]: undefined when v is nullish.

func (*Realm) GetV

func (rt *Realm) GetV(v Value, k Value) Value

GetV is v[k] where k is any value, with a fast path for array indexes.

func (*Realm) GlobalGet

func (rt *Realm) GlobalGet(name string) Value

GlobalGet reads an undeclared identifier from globalThis.

func (*Realm) GlobalGetCached

func (rt *Realm) GlobalGetCached(c *GlobalRef, name string) Value

GlobalGetCached is GlobalGet with a cache, valid until globalThis's own properties change. Accessors and inherited properties aren't cached.

func (*Realm) GlobalSet

func (rt *Realm) GlobalSet(name string, v Value)

GlobalSet assigns an undeclared identifier, which strict mode only allows when globalThis has it.

func (*Realm) Greater

func (rt *Realm) Greater(a, b Value) bool

Greater is >.

func (*Realm) GreaterEq

func (rt *Realm) GreaterEq(a, b Value) bool

GreaterEq is >=.

func (*Realm) HostFunc

func (rt *Realm) HostFunc(name string, fn func(args []any) (any, error))

HostFunc makes a global function that calls Go, as the QuickJS renderer's host functions do: arguments arrive as strings, numbers (int when whole), bools or nil, and the result goes back the same way. An error becomes a thrown Error.

func (*Realm) Index16

func (rt *Realm) Index16(s, sub string, from int) int

Index16 is s.indexOf(sub, from).

func (*Realm) InstanceOf

func (rt *Realm) InstanceOf(v Value, ctor Value) bool

InstanceOf is instanceof.

func (*Realm) Interrupt

func (rt *Realm) Interrupt()

Interrupt stops the realm's running code at its next call or loop turn; it may be called from any goroutine. The realm can't be used after.

func (*Realm) Iterate

func (rt *Realm) Iterate(v Value) func() (Value, bool)

Iterate returns a for…of's next function.

func (*Realm) Len16

func (rt *Realm) Len16(s string) int

Len16 is a string's length in UTF-16 code units.

func (*Realm) Less

func (rt *Realm) Less(a, b Value) bool

Less is <.

func (*Realm) LessEq

func (rt *Realm) LessEq(a, b Value) bool

LessEq is <=.

func (*Realm) NewArguments

func (rt *Realm) NewArguments(args []Value) *Object

NewArguments is a function's arguments object.

func (*Realm) NewArray

func (rt *Realm) NewArray(elems []Value) *Object

NewArray makes an array holding elems (which it keeps).

func (*Realm) NewArrayBuffer

func (rt *Realm) NewArrayBuffer(data []byte) *Object

NewArrayBuffer makes an ArrayBuffer holding data.

func (*Realm) NewArrayWithHoles

func (rt *Realm) NewArrayWithHoles(elems []Value) *Object

NewArrayWithHoles makes an array literal with elisions, like [1, , 3]: Hole marks each missing element.

func (*Realm) NewAsyncFunction

func (rt *Realm) NewAsyncFunction(name string, length int, call func(this Value, args []Value) func(*Gen) Value) *Object

NewAsyncFunction makes an async function. call binds the parameters and returns the body.

func (*Realm) NewAsyncGeneratorFunction added in v1.6.0

func (rt *Realm) NewAsyncGeneratorFunction(name string, length int, call func(this Value, args []Value) func(*Gen) Value) *Object

NewAsyncGeneratorFunction makes an async generator function.

func (*Realm) NewConstructor

func (rt *Realm) NewConstructor(name string, length int, call func(this Value, args []Value) Value, construct func(args []Value, newTarget *Object) Value, proto *Object) *Object

NewConstructor makes a function that new can call, with a prototype object whose constructor is the function. construct receives the new target, for subclasses.

func (*Realm) NewDate

func (rt *Realm) NewDate(ms float64) *Object

NewDate makes a Date for a time value in milliseconds.

func (*Realm) NewFunction

func (rt *Realm) NewFunction(name string, length int, fn func(this Value, args []Value) Value) *Object

NewFunction makes a function object.

func (*Realm) NewFunctionOf

func (rt *Realm) NewFunctionOf(info *FnInfo, fn func(this Value, args []Value) Value) *Object

NewFunctionOf makes a function object described by info.

func (*Realm) NewGeneratorFunction

func (rt *Realm) NewGeneratorFunction(name string, length int, call func(this Value, args []Value) func(*Gen) Value) *Object

NewGeneratorFunction makes a generator function. call runs when it's called: it binds the parameters and returns the body.

func (*Realm) NewIterator

func (rt *Realm) NewIterator(next func() (Value, bool)) *Object

NewIterator makes an iterator object from a next function.

func (*Realm) NewObjectFrom added in v1.8.0

func (rt *Realm) NewObjectFrom(keys []PropKey, vals []Value) *Object

NewObjectFrom makes the object JSON.parse makes for these members, in order: a repeated key's last value wins. keys and vals are copied.

func (*Realm) NewPlainObject

func (rt *Realm) NewPlainObject() *Object

NewPlainObject makes an object like an object literal does.

func (*Realm) NewProxy

func (rt *Realm) NewProxy(target, handler *Object) *Object

NewProxy is new Proxy(target, handler).

func (*Realm) NewRegExp

func (rt *Realm) NewRegExp(source, flags string) *Object

NewRegExp compiles a regular expression literal or new RegExp(source, flags).

func (*Realm) NonArrow

func (rt *Realm) NonArrow(f *Object) *Object

NonArrow makes a function declaration or expression constructible, as non-arrow functions are.

func (*Realm) NonArrowNewTarget added in v1.6.0

func (rt *Realm) NonArrowNewTarget(f *Object) *Object

NonArrowNewTarget is NonArrow for a function that reads new.target: its construct hands the new target over, which the function's first statement takes (TakeNewTarget).

func (*Realm) Num added in v1.15.0

func (rt *Realm) Num(f float64) Value

Num returns f as a Value, boxed from the realm's slabs.

func (*Realm) Obj

func (rt *Realm) Obj(kv ...Value) *Object

Obj makes an object literal from keys and values.

func (*Realm) ObjectToString

func (rt *Realm) ObjectToString(v Value) string

ObjectToString is Object.prototype.toString.

func (*Realm) ParseJSON

func (rt *Realm) ParseJSON(s string) (Value, error)

ParseJSON is JSON.parse without a reviver.

func (*Realm) PushPlain added in v1.8.0

func (rt *Realm) PushPlain(ic *IC, v, x Value) bool

PushPlain is v.push(x) for an array whose push is the built-in one, for Go code that appends where JavaScript would call push. It reports false, doing nothing, for anything else, which the caller then calls.

func (*Realm) RegExpLiteral

func (rt *Realm) RegExpLiteral(source, flags string) Value

RegExpLiteral evaluates a regular expression literal: a new object each time, sharing the compiled pattern.

func (*Realm) Remaining

func (rt *Realm) Remaining(next func() (Value, bool)) *Object

Remaining collects an iterator's remaining values, for [...rest].

func (*Realm) Reset

func (rt *Realm) Reset()

Reset clears what an interrupted or failed call left behind, for the next call: the argument stack, the call depth and queued jobs.

func (*Realm) Rest

func (rt *Realm) Rest(args []Value, i int) *Object

Rest is a rest parameter: the arguments from i on.

func (*Realm) RunJobs

func (rt *Realm) RunJobs()

RunJobs runs queued jobs, and the jobs they queue, until none are left.

func (*Realm) SetIC

func (rt *Realm) SetIC(c *IC, obj Value, key string, v Value)

SetIC is obj.key = v with a cache, for a writable own property or for adding one.

func (*Realm) Slice16

func (rt *Realm) Slice16(s string, start, end int) string

Slice16 is s.slice(start, end) after both are clamped to [0, len].

func (*Realm) Spread

func (rt *Realm) Spread(v Value) []Value

Spread collects the values of v, for [...v] and f(...v).

func (*Realm) Str added in v1.15.0

func (rt *Realm) Str(s string) Value

Str returns s as a Value, boxed from the realm's slabs.

func (*Realm) Stringify

func (rt *Realm) Stringify(v, replacer, space Value) (string, bool)

Stringify is JSON.stringify; ok is false when the result is undefined.

func (*Realm) TakeNewTarget added in v1.6.0

func (rt *Realm) TakeNewTarget() Value

TakeNewTarget is new.target in a function: the new target its construct handed over, or undefined for a call.

func (*Realm) TemplateObject

func (rt *Realm) TemplateObject(site int, cooked []Value, raw []string) Value

TemplateObject is a tagged template's strings array, the same object every time its call site runs.

func (*Realm) Tick

func (rt *Realm) Tick()

Tick is compiled into every loop: it stops interrupted code.

func (*Realm) ToObject

func (rt *Realm) ToObject(v Value) *Object

ToObject boxes primitives, for property access and Object(...).

func (*Realm) TreeShaken

func (rt *Realm) TreeShaken(spec, name string) Value

TreeShaken stands for a binding imported from a module the bundler left out, as nothing the bundle runs uses it: it can be passed around, but using it raises Unsupported, so the page falls back to the engine.

func (*Realm) Try

func (rt *Realm) Try(body func() (int, Value), catch func(Value) (int, Value), finally func() (int, Value)) (ctl int, val Value)

Try runs try…catch…finally. Each part returns how it ended: CtlNone to carry on, or a return, break or continue with its value (a break or continue carries the target's number).

func (*Realm) TypeofGlobal

func (rt *Realm) TypeofGlobal(name string) string

TypeofGlobal is typeof of an undeclared identifier.

func (*Realm) UnitAt

func (rt *Realm) UnitAt(s string, i int) int

UnitAt is s.charCodeAt(i), or -1 out of range.

type Shape

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

Shape is the layout of objects' own properties.

type Sources

type Sources struct {
	// GZ is the gzipped sources: generated code points it at an embedded
	// string, so a Sources, and the FnInfos that point at it, are data the
	// linker lays out rather than code that runs at start.
	GZ *string
	// contains filtered or unexported fields
}

Sources is the source text of compiled modules, for Function.prototype .toString: gzipped JSON, an array of each module's code, unpacked when first needed.

func NewSources

func NewSources(gz string) *Sources

NewSources holds gzipped sources.

func (*Sources) Module

func (s *Sources) Module(i int) string

Module is the code of module i.

type Symbol

type Symbol struct{ Description string }

Symbol is a JavaScript symbol. Each one is distinct.

type Throw

type Throw struct {
	// Value is what was thrown; nil for a runtime error not yet made.
	Value   Value
	Kind    string // the error constructor's name, for a runtime error
	Message string
}

Throw is a JavaScript exception in flight: compiled code panics with it, and try/catch recovers it.

The runtime's own errors, such as a TypeError, start with just a kind and a message: their error object is made in the realm that catches them, by In. Raising them needs no realm, so neither do the value operations that can fail.

func RangeErrorf

func RangeErrorf(format string, args ...any) *Throw

RangeErrorf makes a RangeError exception.

func ReferenceErrorf

func ReferenceErrorf(format string, args ...any) *Throw

ReferenceErrorf makes a ReferenceError exception.

func SyntaxErrorf

func SyntaxErrorf(format string, args ...any) *Throw

SyntaxErrorf makes a SyntaxError exception.

func ThrowValue

func ThrowValue(v Value) *Throw

ThrowValue makes a throw statement's panic.

func TypeErrorf

func TypeErrorf(format string, args ...any) *Throw

TypeErrorf makes a TypeError exception.

func URIErrorf

func URIErrorf(format string, args ...any) *Throw

URIErrorf makes a URIError exception.

func (*Throw) Error

func (t *Throw) Error() string

func (*Throw) In

func (t *Throw) In(r *Realm) Value

In returns the thrown value, making a runtime error's object in r.

type Unsupported

type Unsupported struct{ What string }

Unsupported is raised when compiled code meets something the compiler handles only partly; the request falls back to the JavaScript engine.

func NotSupported

func NotSupported(format string, args ...any) *Unsupported

NotSupported panics with an Unsupported.

func (*Unsupported) Error

func (u *Unsupported) Error() string

type Value

type Value = any

Value is a JavaScript value.

var (
	Inf     Value = math.Inf(1)
	NegInf  Value = math.Inf(-1)
	NaN     Value = math.NaN()
	NegZero Value = math.Copysign(0, -1)
)

Number constants that have no Go literal.

var (
	Undefined Value = undefinedType{}
	Null      Value = nullType{}
)

The two values that aren't objects or primitives of a Go type.

func Arg

func Arg(args []Value, i int) Value

Arg returns args[i], or undefined.

func BigIntLit added in v1.6.0

func BigIntLit(digits string) Value

BigIntLit is a BigInt literal's value, from its digits.

func BitAnd

func BitAnd(a, b Value) Value

BitAnd is &.

func BitNot

func BitNot(a Value) Value

BitNot is ~.

func BitOr

func BitOr(a, b Value) Value

BitOr is |.

func BitXor

func BitXor(a, b Value) Value

BitXor is ^.

func Box

func Box(f float64) Value

Box makes a number a Value, without allocating for small integers.

func Call

func Call(f Value, this Value, args ...Value) Value

Call calls f with a this value.

func CheckThis

func CheckThis(v Value) Value

CheckThis reads this in a derived constructor, which super() sets.

func Construct

func Construct(f Value, args ...Value) Value

Construct is the new operator.

func ConstructWith

func ConstructWith(f Value, newTarget *Object, args ...Value) Value

ConstructWith is construct with an explicit new target, for super(...).

func Dec

func Dec(v Value) Value

Dec is x - 1 for x-- and --x.

func Div

func Div(a, b Value) Value

Div is the / operator.

func Fail

func Fail(what string) Value

Fail is compiled in place of what the compiler can't compile.

func FromGo

func FromGo(v any) Value

FromGo converts a Go value to a primitive Value.

func Inc

func Inc(v Value) Value

Inc is x + 1 for x++ and ++x.

func ListFromArrayLike

func ListFromArrayLike(v Value) []Value

ListFromArrayLike turns an array or array-like object into arguments.

func MissingExport

func MissingExport(module, name string) Value

MissingExport stands for an import of a name the module doesn't export.

func MissingImport

func MissingImport(spec, name string) Value

MissingImport stands for a binding imported from a module the IR doesn't have; reading it raises Unsupported.

func Mod

func Mod(a, b Value) Value

Mod is the % operator: the result has the dividend's sign.

func Mul

func Mul(a, b Value) Value

Mul is the * operator.

func Neg

func Neg(a Value) Value

Neg is unary -.

func Num

func Num[T ~int | ~int8 | ~int16 | ~int32 | ~int64 | ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~float32 | ~float64](n T) Value

Num makes a number from any Go number, for generated code.

func Plus

func Plus(a Value) Value

Plus is unary +.

func Pow

func Pow(a, b Value) Value

Pow is **, where JavaScript differs from math.Pow: 1 ** NaN and (-1) ** ±Infinity are NaN.

func PrivateGet

func PrivateGet(obj Value, name *PrivateName) Value

PrivateGet reads obj.#name.

func PrivateIn

func PrivateIn(name *PrivateName, obj Value) Value

PrivateIn is #name in obj.

func Shl

func Shl(a, b Value) Value

Shl is <<.

func Shr

func Shr(a, b Value) Value

Shr is >>.

func Sub

func Sub(a, b Value) Value

Sub is the - operator.

func SuperGet

func SuperGet(proto *Object, key PropKey, this Value) Value

SuperGet is super[key] in a method.

func ToPrimitive

func ToPrimitive(v Value, hint string) Value

ToPrimitive with a hint of "default", "number" or "string".

func ToStringValue

func ToStringValue(v Value) Value

ToStringValue is ToString as a Value: a string comes back as it is, without the allocation of boxing it again.

func UShr

func UShr(a, b Value) Value

UShr is >>>.

func V

func V(v Value) Value

V is v. Compiled code wraps a variable read in it to keep the read in order with the calls around it (see internal/native).

Jump to

Keyboard shortcuts

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