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
- Variables
- func CopyDataProperties(target *Object, src Value)
- func DefineField(obj Value, key PropKey, v Value)
- func Delete(v Value, key PropKey) bool
- func FromUnits(u []uint16) string
- func In(key Value, obj Value) bool
- func InheritStatics(ctor *Object, parent Value)
- func IsArray(v Value) bool
- func IsConstructor(v Value) bool
- func IsNullish(v Value) bool
- func Itoa(i int) string
- func Join(a []Value, sep string) string
- func LooseEquals(a, b Value) bool
- func Nullish(v Value) bool
- func NumberToString(x float64) string
- func PrivateAccessor(obj Value, name *PrivateName, get, set Value)
- func PrivateDefine(obj Value, name *PrivateName, v Value)
- func PrivateSet(obj Value, name *PrivateName, v Value)
- func QuoteJSON(b *strings.Builder, s string)
- func RequireObjectCoercible(v Value)
- func SameValue(a, b Value) bool
- func SameValueZero(a, b Value) bool
- func Set(v Value, key PropKey, val Value)
- func SetProtoFromLiteral(o *Object, v Value)
- func SetV(v Value, k Value, val Value)
- func StrictEquals(a, b Value) bool
- func StringToNumber(s string) float64
- func SuperSet(proto *Object, key PropKey, v Value, this Value)
- func ToDisplay(v Value) string
- func ToFixed(x float64, d int) string
- func ToGo(v Value) any
- func ToInt32(v Value) int32
- func ToIntegerOrInfinity(v Value) float64
- func ToNumber(v Value) float64
- func ToString(v Value) string
- func ToUint32(v Value) uint32
- func TrimJSSpace(s string) string
- func Truthy(v Value) bool
- func Typeof(v Value) string
- func Units(s string) []uint16
- type FnInfo
- type Gen
- type GlobalRef
- type IC
- type Object
- func (o *Object) Define(key PropKey, v Value)
- func (o *Object) DefineAccessor(key PropKey, get, set *Object, enumerable bool)
- func (o *Object) DefineHidden(key PropKey, v Value)
- func (o *Object) DefineProperty(key PropKey, desc *Object)
- func (o *Object) Delete(key PropKey) bool
- func (o *Object) Elems() []Value
- func (o *Object) EnumerableOwn(fn func(key string, v Value))
- func (o *Object) Freeze()
- func (o *Object) Get(key PropKey) Value
- func (o *Object) GetFrom(key PropKey, receiver Value) Value
- func (o *Object) GetOwn(key PropKey) (Value, bool)
- func (o *Object) Has(key PropKey) bool
- func (o *Object) HasOwn(key PropKey) bool
- func (o *Object) IsCallable() bool
- func (o *Object) IsFrozen() bool
- func (o *Object) OwnKeys(onlyEnumerable, withSymbols bool) []PropKey
- func (o *Object) Proto() *Object
- func (o *Object) Push(v ...Value)
- func (o *Object) Set(key PropKey, v Value)
- func (o *Object) SetConstruct(fn func(args []Value, newTarget *Object) Value)
- func (o *Object) SetFrom(key PropKey, v Value, receiver Value)
- func (o *Object) SetInfo(info *FnInfo)
- func (o *Object) SetProto(p *Object)
- type PrivateName
- type PropKey
- type Realm
- func (rt *Realm) Add(a, b Value) Value
- func (rt *Realm) ArrayValues() Value
- func (rt *Realm) CallIC(c *IC, obj Value, key string, args ...Value) Value
- func (rt *Realm) CallMethod(obj Value, key PropKey, args ...Value) Value
- func (rt *Realm) CallMethodV(obj Value, key Value, args ...Value) Value
- func (rt *Realm) CompareStrings(a, b string) int
- func (rt *Realm) Concat(a, b string) string
- func (rt *Realm) CopyDataPropertiesExcluding(src Value, excluded []PropKey) *Object
- func (rt *Realm) DropJobs()
- func (rt *Realm) ExportLive(ns *Object, name string, get func() Value)
- func (rt *Realm) ForInKeys(v Value) func() (Value, bool)
- func (rt *Realm) ForOf(v Value, fn func(Value) bool)
- func (rt *Realm) Get(v Value, key PropKey) Value
- func (rt *Realm) GetIC(c *IC, v Value, key string) Value
- func (rt *Realm) GetOptional(v Value, key PropKey) Value
- func (rt *Realm) GetV(v Value, k Value) Value
- func (rt *Realm) GlobalGet(name string) Value
- func (rt *Realm) GlobalGetCached(c *GlobalRef, name string) Value
- func (rt *Realm) GlobalSet(name string, v Value)
- func (rt *Realm) Greater(a, b Value) bool
- func (rt *Realm) GreaterEq(a, b Value) bool
- func (rt *Realm) HostFunc(name string, fn func(args []any) (any, error))
- func (rt *Realm) Index16(s, sub string, from int) int
- func (rt *Realm) InstanceOf(v Value, ctor Value) bool
- func (rt *Realm) Interrupt()
- func (rt *Realm) Iterate(v Value) func() (Value, bool)
- func (rt *Realm) Len16(s string) int
- func (rt *Realm) Less(a, b Value) bool
- func (rt *Realm) LessEq(a, b Value) bool
- func (rt *Realm) NewArguments(args []Value) *Object
- func (rt *Realm) NewArray(elems []Value) *Object
- func (rt *Realm) NewArrayBuffer(data []byte) *Object
- func (rt *Realm) NewArrayWithHoles(elems []Value) *Object
- func (rt *Realm) NewAsyncFunction(name string, length int, call func(this Value, args []Value) func(*Gen) Value) *Object
- func (rt *Realm) NewConstructor(name string, length int, call func(this Value, args []Value) Value, ...) *Object
- func (rt *Realm) NewDate(ms float64) *Object
- func (rt *Realm) NewFunction(name string, length int, fn func(this Value, args []Value) Value) *Object
- func (rt *Realm) NewFunctionOf(info *FnInfo, fn func(this Value, args []Value) Value) *Object
- func (rt *Realm) NewGeneratorFunction(name string, length int, call func(this Value, args []Value) func(*Gen) Value) *Object
- func (rt *Realm) NewIterator(next func() (Value, bool)) *Object
- func (rt *Realm) NewPlainObject() *Object
- func (rt *Realm) NewProxy(target, handler *Object) *Object
- func (rt *Realm) NewRegExp(source, flags string) *Object
- func (rt *Realm) NonArrow(f *Object) *Object
- func (rt *Realm) Obj(kv ...Value) *Object
- func (rt *Realm) ObjectToString(v Value) string
- func (rt *Realm) ParseJSON(s string) (Value, error)
- func (rt *Realm) RegExpLiteral(source, flags string) Value
- func (rt *Realm) Remaining(next func() (Value, bool)) *Object
- func (rt *Realm) Reset()
- func (rt *Realm) Rest(args []Value, i int) *Object
- func (rt *Realm) RunJobs()
- func (rt *Realm) SetIC(c *IC, obj Value, key string, v Value)
- func (rt *Realm) Slice16(s string, start, end int) string
- func (rt *Realm) Spread(v Value) []Value
- func (rt *Realm) Stringify(v, replacer, space Value) (string, bool)
- func (rt *Realm) TemplateObject(site int, cooked []Value, raw []string) Value
- func (rt *Realm) Tick()
- func (rt *Realm) ToObject(v Value) *Object
- func (rt *Realm) TreeShaken(spec, name string) Value
- func (rt *Realm) Try(body func() (int, Value), catch func(Value) (int, Value), ...) (ctl int, val Value)
- func (rt *Realm) TypeofGlobal(name string) string
- func (rt *Realm) UnitAt(s string, i int) int
- type Shape
- type Sources
- type Symbol
- type Throw
- type Unsupported
- type Value
- func Arg(args []Value, i int) Value
- func BitAnd(a, b Value) Value
- func BitNot(a Value) Value
- func BitOr(a, b Value) Value
- func BitXor(a, b Value) Value
- func Box(f float64) Value
- func Call(f Value, this Value, args ...Value) Value
- func CheckThis(v Value) Value
- func Construct(f Value, args ...Value) Value
- func ConstructWith(f Value, newTarget *Object, args ...Value) Value
- func Dec(v Value) Value
- func Div(a, b Value) Value
- func Fail(what string) Value
- func FromGo(v any) Value
- func Inc(v Value) Value
- func ListFromArrayLike(v Value) []Value
- func MissingExport(module, name string) Value
- func MissingImport(spec, name string) Value
- func Mod(a, b Value) Value
- func Mul(a, b Value) Value
- func Neg(a Value) Value
- func Num[...](n T) Value
- func Plus(a Value) Value
- func Pow(a, b Value) Value
- func PrivateGet(obj Value, name *PrivateName) Value
- func PrivateIn(name *PrivateName, obj Value) Value
- func Shl(a, b Value) Value
- func Shr(a, b Value) Value
- func Sub(a, b Value) Value
- func SuperGet(proto *Object, key PropKey, this Value) Value
- func ToPrimitive(v Value, hint string) Value
- func ToStringValue(v Value) Value
- func UShr(a, b Value) Value
- func V(v Value) Value
Constants ¶
const ( CtlNone = iota CtlReturn CtlBreak CtlContinue )
Control codes: how a try block's closure was left.
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 ¶
var ( SymbolIterator = &Symbol{"Symbol.iterator"} SymbolToPrimitive = &Symbol{"Symbol.toPrimitive"} SymbolToStringTag = &Symbol{"Symbol.toStringTag"} )
Well-known symbols.
var ErrInterrupted = errors.New("js: interrupted")
ErrInterrupted is what a realm's code panics with once Interrupt is called.
var Hole = hole
Hole is the element of an elision in an array literal.
var UnknownPrivate = &PrivateName{Description: "#unknown"}
UnknownPrivate stands for a private name the compiler couldn't find.
Functions ¶
func CopyDataProperties ¶
CopyDataProperties is object spread: {...src}.
func DefineField ¶
DefineField is a class field: an own, enumerable property.
func InheritStatics ¶
InheritStatics makes a subclass's constructor inherit the parent's statics.
func NumberToString ¶
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 ¶
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 SameValueZero ¶
SameValueZero is SameValueZero, for includes and Map keys.
func SetProtoFromLiteral ¶
SetProtoFromLiteral is __proto__: v in an object literal.
func StringToNumber ¶
StringToNumber is StringToNumber: decimal, 0x/0o/0b integers, Infinity, and the empty string as 0.
func ToGo ¶
ToGo converts a primitive to Go: nil, bool, int (for whole numbers), float64 or string. Objects become their string conversion's result.
func ToIntegerOrInfinity ¶
ToIntegerOrInfinity is ToIntegerOrInfinity.
func TrimJSSpace ¶
TrimJSSpace trims what String.prototype.trim trims.
Types ¶
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.
type Gen ¶
type Gen struct {
// contains filtered or unexported fields
}
Gen is a generator object's state.
func (*Gen) Await ¶
Await is an await expression: the body waits for v to settle, and gets its value, or its reason thrown.
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 ClassParentProto ¶
ClassParentProto is the prototype of a class's instances' prototype: the superclass's prototype, or null for extends null.
func OrdinaryCreateFromConstructor ¶
OrdinaryCreateFromConstructor makes the object a constructor builds: its prototype is newTarget.prototype, or fallback.
func (*Object) Define ¶
Define makes an own, enumerable, writable data property, as an object literal does.
func (*Object) DefineAccessor ¶
DefineAccessor makes a getter and/or setter property. Object literals' accessors are enumerable; classes' are not.
func (*Object) DefineHidden ¶
DefineHidden makes an own, non-enumerable data property, as built-ins and class methods have.
func (*Object) DefineProperty ¶
DefineProperty is Object.defineProperty with a parsed descriptor.
func (*Object) EnumerableOwn ¶
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) GetFrom ¶
GetFrom is [[Get]] with another receiver, for getters on prototypes and for primitives' methods.
func (*Object) IsCallable ¶
IsCallable reports whether o is a function.
func (*Object) OwnKeys ¶
OwnKeys lists own property keys in JavaScript's order: array indexes ascending, then strings in creation order, then symbols.
func (*Object) Set ¶
Set is [Set] in strict mode code: it throws where sloppy code would silently fail.
func (*Object) SetConstruct ¶
SetConstruct makes an existing function a constructor.
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 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
// 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) ArrayValues ¶
ArrayValues is Array.prototype.values, to tell built-in iteration apart.
func (*Realm) CallMethod ¶
CallMethod is obj[key](...args), with obj as this.
func (*Realm) CallMethodV ¶
CallMethodV is obj[key](...args) with a computed key.
func (*Realm) CompareStrings ¶
CompareStrings orders strings by UTF-16 code units, as < does.
func (*Realm) CopyDataPropertiesExcluding ¶
CopyDataPropertiesExcluding is an object pattern's rest element.
func (*Realm) ExportLive ¶
ExportLive adds a live binding to a namespace.
func (*Realm) ForInKeys ¶
ForInKeys returns a for…in's next function: enumerable string keys of the object and its prototypes, each once.
func (*Realm) GetOptional ¶
GetOptional is v?.[key]: undefined when v is nullish.
func (*Realm) GlobalGetCached ¶
GlobalGetCached is GlobalGet with a cache, valid until globalThis's own properties change. Accessors and inherited properties aren't cached.
func (*Realm) GlobalSet ¶
GlobalSet assigns an undeclared identifier, which strict mode only allows when globalThis has it.
func (*Realm) HostFunc ¶
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) InstanceOf ¶
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) NewArguments ¶
NewArguments is a function's arguments object.
func (*Realm) NewArrayBuffer ¶
NewArrayBuffer makes an ArrayBuffer holding data.
func (*Realm) NewArrayWithHoles ¶
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) 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) 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 ¶
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 ¶
NewIterator makes an iterator object from a next function.
func (*Realm) NewPlainObject ¶
NewPlainObject makes an object like an object literal does.
func (*Realm) NewRegExp ¶
NewRegExp compiles a regular expression literal or new RegExp(source, flags).
func (*Realm) NonArrow ¶
NonArrow makes a function declaration or expression constructible, as non-arrow functions are.
func (*Realm) ObjectToString ¶
ObjectToString is Object.prototype.toString.
func (*Realm) RegExpLiteral ¶
RegExpLiteral evaluates a regular expression literal: a new object each time, sharing the compiled pattern.
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) RunJobs ¶
func (rt *Realm) RunJobs()
RunJobs runs queued jobs, and the jobs they queue, until none are left.
func (*Realm) SetIC ¶
SetIC is obj.key = v with a cache, for a writable own property or for adding one.
func (*Realm) TemplateObject ¶
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) TreeShaken ¶
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 ¶
TypeofGlobal is typeof of an undeclared identifier.
type Shape ¶
type Shape struct {
// contains filtered or unexported fields
}
Shape is the layout of objects' own properties.
type Sources ¶
type Sources struct {
// 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.
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 ¶
RangeErrorf makes a RangeError exception.
func ReferenceErrorf ¶
ReferenceErrorf makes a ReferenceError exception.
func SyntaxErrorf ¶
SyntaxErrorf makes a SyntaxError exception.
func TypeErrorf ¶
TypeErrorf makes a TypeError exception.
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.
The two values that aren't objects or primitives of a Go type.
func ConstructWith ¶
ConstructWith is construct with an explicit new target, for super(...).
func ListFromArrayLike ¶
ListFromArrayLike turns an array or array-like object into arguments.
func MissingExport ¶
MissingExport stands for an import of a name the module doesn't export.
func MissingImport ¶
MissingImport stands for a binding imported from a module the IR doesn't have; reading it raises Unsupported.
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 Pow ¶
Pow is **, where JavaScript differs from math.Pow: 1 ** NaN and (-1) ** ±Infinity are NaN.
func ToPrimitive ¶
ToPrimitive with a hint of "default", "number" or "string".
func ToStringValue ¶
ToStringValue is ToString as a Value: a string comes back as it is, without the allocation of boxing it again.
Source Files
¶
- async.go
- builtins_array.go
- builtins_collections.go
- builtins_date.go
- builtins_json.go
- builtins_math.go
- builtins_number.go
- builtins_object.go
- builtins_promise.go
- builtins_proxy.go
- builtins_regexp.go
- builtins_string.go
- builtins_typed.go
- builtins_uri.go
- compiled.go
- concat.go
- convert.go
- errors.go
- function.go
- generator.go
- host.go
- ic.go
- object.go
- ops.go
- realm.go
- shape.go
- sources.go
- strings16.go
- value.go