engine

package
v0.1.0-alpha.1 Latest Latest
Warning

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

Go to latest
Published: Sep 25, 2026 License: Apache-2.0 Imports: 30 Imported by: 0

Documentation

Index

Constants

View Source
const (
	CompareFalse     int8 = 0
	CompareTrue      int8 = 1
	CompareUndefined int8 = -1
)

Comparison results of IsLessThan.

View Source
const MaxCallDepth = 512

MaxCallDepth is the frame limit before "Maximum call stack size exceeded".

View Source
const MaxStringLength = 1<<30 - 24

MaxStringLength is the maximum JavaScript string length in code units. Every *String satisfies Len() <= MaxStringLength, which is what lets Concat add two int32 lengths as an int without overflow on any platform; producers whose output can outgrow their inputs check maxStringLength before allocating and raise RangeError: Invalid string length (Realm.invalidStringLength).

View Source
const MaxToGoDepth = 10000

MaxToGoDepth bounds container nesting in ToGo/ToGoStrict: a plugin can build a 3e6-deep array in well under a second, and exporting it recursively overflowed the Go stack, a fatal error. Past the limit ToGoStrict returns a RangeError and ToGo exports the deeper containers as nil.

Variables

View Source
var (
	AtomEmpty                     = staticAtom("")
	AtomLength                    = staticAtom("length")
	AtomPrototype                 = staticAtom("prototype")
	AtomConstructor               = staticAtom("constructor")
	AtomMessage                   = staticAtom("message")
	AtomName                      = staticAtom("name")
	AtomStack                     = staticAtom("stack")
	AtomStackTraceLimit           = staticAtom("stackTraceLimit")
	AtomCaptureStackTrace         = staticAtom("captureStackTrace")
	AtomCause                     = staticAtom("cause")
	AtomPush                      = staticAtom("push")
	AtomValue                     = staticAtom("value")
	AtomWritable                  = staticAtom("writable")
	AtomEnumerable                = staticAtom("enumerable")
	AtomConfigurable              = staticAtom("configurable")
	AtomGet                       = staticAtom("get")
	AtomSet                       = staticAtom("set")
	AtomToString                  = staticAtom("toString")
	AtomValueOf                   = staticAtom("valueOf")
	AtomToJSON                    = staticAtom("toJSON")
	AtomToLocaleString            = staticAtom("toLocaleString")
	AtomToPrimitive               = staticAtom("toPrimitive")
	AtomGlobalThis                = staticAtom("globalThis")
	AtomUndefined                 = staticAtom("undefined")
	AtomNaN                       = staticAtom("NaN")
	AtomInfinity                  = staticAtom("Infinity")
	AtomNegInfinity               = staticAtom("-Infinity")
	AtomNull                      = staticAtom("null")
	AtomTrue                      = staticAtom("true")
	AtomFalse                     = staticAtom("false")
	AtomTypeObject                = staticAtom("object")
	AtomTypeBoolean               = staticAtom("boolean")
	AtomTypeNumber                = staticAtom("number")
	AtomTypeString                = staticAtom("string")
	AtomTypeSymbol                = staticAtom("symbol")
	AtomTypeBigint                = staticAtom("bigint")
	AtomTypeFunction              = staticAtom("function")
	AtomDefault                   = staticAtom("default")
	AtomAnonymous                 = staticAtom("anonymous")
	AtomBoundSpace                = staticAtom("bound ")
	AtomObject                    = staticAtom("Object")
	AtomFunction                  = staticAtom("Function")
	AtomArray                     = staticAtom("Array")
	AtomString                    = staticAtom("String")
	AtomNumber                    = staticAtom("Number")
	AtomBoolean                   = staticAtom("Boolean")
	AtomError                     = staticAtom("Error")
	AtomTypeError                 = staticAtom("TypeError")
	AtomRangeError                = staticAtom("RangeError")
	AtomSyntaxError               = staticAtom("SyntaxError")
	AtomReferenceError            = staticAtom("ReferenceError")
	AtomEvalError                 = staticAtom("EvalError")
	AtomURIError                  = staticAtom("URIError")
	AtomInternalError             = staticAtom("InternalError")
	AtomJSON                      = staticAtom("JSON")
	AtomMath                      = staticAtom("Math")
	AtomRegExp                    = staticAtom("RegExp")
	AtomDate                      = staticAtom("Date")
	AtomSymbol                    = staticAtom("Symbol")
	AtomBigInt                    = staticAtom("BigInt")
	AtomParseInt                  = staticAtom("parseInt")
	AtomParseFloat                = staticAtom("parseFloat")
	AtomIsNaN                     = staticAtom("isNaN")
	AtomIsFinite                  = staticAtom("isFinite")
	AtomEncodeURIComponent        = staticAtom("encodeURIComponent")
	AtomDecodeURIComponent        = staticAtom("decodeURIComponent")
	AtomEncodeURI                 = staticAtom("encodeURI")
	AtomDecodeURI                 = staticAtom("decodeURI")
	AtomKeys                      = staticAtom("keys")
	AtomValues                    = staticAtom("values")
	AtomEntries                   = staticAtom("entries")
	AtomAssign                    = staticAtom("assign")
	AtomFreeze                    = staticAtom("freeze")
	AtomIsFrozen                  = staticAtom("isFrozen")
	AtomSeal                      = staticAtom("seal")
	AtomIsSealed                  = staticAtom("isSealed")
	AtomPreventExtensions         = staticAtom("preventExtensions")
	AtomIsExtensible              = staticAtom("isExtensible")
	AtomGetPrototypeOf            = staticAtom("getPrototypeOf")
	AtomSetPrototypeOf            = staticAtom("setPrototypeOf")
	AtomCreate                    = staticAtom("create")
	AtomDefineProperty            = staticAtom("defineProperty")
	AtomDefineProperties          = staticAtom("defineProperties")
	AtomGetOwnPropertyDescriptor  = staticAtom("getOwnPropertyDescriptor")
	AtomGetOwnPropertyDescriptors = staticAtom("getOwnPropertyDescriptors")
	AtomGetOwnPropertyNames       = staticAtom("getOwnPropertyNames")
	AtomGetOwnPropertySymbols     = staticAtom("getOwnPropertySymbols")
	AtomFromEntries               = staticAtom("fromEntries")
	AtomHasOwn                    = staticAtom("hasOwn")
	AtomIs                        = staticAtom("is")
	AtomHasOwnProperty            = staticAtom("hasOwnProperty")
	AtomIsPrototypeOf             = staticAtom("isPrototypeOf")
	AtomPropertyIsEnumerable      = staticAtom("propertyIsEnumerable")
	AtomDunderProto               = staticAtom("__proto__")
	AtomCall                      = staticAtom("call")
	AtomApply                     = staticAtom("apply")
	AtomBind                      = staticAtom("bind")
	AtomIsArray                   = staticAtom("isArray")
	AtomFrom                      = staticAtom("from")
	AtomOf                        = staticAtom("of")
	AtomPop                       = staticAtom("pop")
	AtomShift                     = staticAtom("shift")
	AtomUnshift                   = staticAtom("unshift")
	AtomSlice                     = staticAtom("slice")
	AtomSplice                    = staticAtom("splice")
	AtomConcat                    = staticAtom("concat")
	AtomJoin                      = staticAtom("join")
	AtomIndexOf                   = staticAtom("indexOf")
	AtomLastIndexOf               = staticAtom("lastIndexOf")
	AtomIncludes                  = staticAtom("includes")
	AtomFind                      = staticAtom("find")
	AtomFindIndex                 = staticAtom("findIndex")
	AtomFindLast                  = staticAtom("findLast")
	AtomFindLastIndex             = staticAtom("findLastIndex")
	AtomFilter                    = staticAtom("filter")
	AtomMap                       = staticAtom("map")
	AtomForEach                   = staticAtom("forEach")
	AtomSome                      = staticAtom("some")
	AtomEvery                     = staticAtom("every")
	AtomReduce                    = staticAtom("reduce")
	AtomReduceRight               = staticAtom("reduceRight")
	AtomReverse                   = staticAtom("reverse")
	AtomSort                      = staticAtom("sort")
	AtomFill                      = staticAtom("fill")
	AtomFlat                      = staticAtom("flat")
	AtomFlatMap                   = staticAtom("flatMap")
	AtomAt                        = staticAtom("at")
	AtomFromCharCode              = staticAtom("fromCharCode")
	AtomFromCodePoint             = staticAtom("fromCodePoint")
	AtomCharAt                    = staticAtom("charAt")
	AtomCharCodeAt                = staticAtom("charCodeAt")
	AtomCodePointAt               = staticAtom("codePointAt")
	AtomStartsWith                = staticAtom("startsWith")
	AtomEndsWith                  = staticAtom("endsWith")
	AtomSubstring                 = staticAtom("substring")
	AtomSubstr                    = staticAtom("substr")
	AtomToLowerCase               = staticAtom("toLowerCase")
	AtomToUpperCase               = staticAtom("toUpperCase")
	AtomTrim                      = staticAtom("trim")
	AtomTrimStart                 = staticAtom("trimStart")
	AtomTrimEnd                   = staticAtom("trimEnd")
	AtomSplit                     = staticAtom("split")
	AtomReplace                   = staticAtom("replace")
	AtomReplaceAll                = staticAtom("replaceAll")
	AtomMatch                     = staticAtom("match")
	AtomMatchAll                  = staticAtom("matchAll")
	AtomRepeat                    = staticAtom("repeat")
	AtomPadStart                  = staticAtom("padStart")
	AtomPadEnd                    = staticAtom("padEnd")
	AtomLocaleCompare             = staticAtom("localeCompare")
	AtomNormalize                 = staticAtom("normalize")
	AtomRaw                       = staticAtom("raw")
	AtomIsInteger                 = staticAtom("isInteger")
	AtomIsSafeInteger             = staticAtom("isSafeInteger")
	AtomMaxSafeInteger            = staticAtom("MAX_SAFE_INTEGER")
	AtomMinSafeInteger            = staticAtom("MIN_SAFE_INTEGER")
	AtomMaxValue                  = staticAtom("MAX_VALUE")
	AtomMinValue                  = staticAtom("MIN_VALUE")
	AtomEPSILON                   = staticAtom("EPSILON")
	AtomPositiveInfinity          = staticAtom("POSITIVE_INFINITY")
	AtomNegativeInfinity          = staticAtom("NEGATIVE_INFINITY")
	AtomToFixed                   = staticAtom("toFixed")
	AtomToPrecision               = staticAtom("toPrecision")
	AtomToExponential             = staticAtom("toExponential")
	AtomAbs                       = staticAtom("abs")
	AtomCeil                      = staticAtom("ceil")
	AtomFloor                     = staticAtom("floor")
	AtomRound                     = staticAtom("round")
	AtomTrunc                     = staticAtom("trunc")
	AtomSign                      = staticAtom("sign")
	AtomMax                       = staticAtom("max")
	AtomMin                       = staticAtom("min")
	AtomPow                       = staticAtom("pow")
	AtomSqrt                      = staticAtom("sqrt")
	AtomCbrt                      = staticAtom("cbrt")
	AtomHypot                     = staticAtom("hypot")
	AtomLog                       = staticAtom("log")
	AtomLog2                      = staticAtom("log2")
	AtomLog10                     = staticAtom("log10")
	AtomLog1p                     = staticAtom("log1p")
	AtomExp                       = staticAtom("exp")
	AtomExpm1                     = staticAtom("expm1")
	AtomSin                       = staticAtom("sin")
	AtomCos                       = staticAtom("cos")
	AtomTan                       = staticAtom("tan")
	AtomAsin                      = staticAtom("asin")
	AtomAcos                      = staticAtom("acos")
	AtomAtan                      = staticAtom("atan")
	AtomAtan2                     = staticAtom("atan2")
	AtomSinh                      = staticAtom("sinh")
	AtomCosh                      = staticAtom("cosh")
	AtomTanh                      = staticAtom("tanh")
	AtomAsinh                     = staticAtom("asinh")
	AtomAcosh                     = staticAtom("acosh")
	AtomAtanh                     = staticAtom("atanh")
	AtomRandom                    = staticAtom("random")
	AtomFround                    = staticAtom("fround")
	AtomImul                      = staticAtom("imul")
	AtomClz32                     = staticAtom("clz32")
	AtomPI                        = staticAtom("PI")
	AtomE                         = staticAtom("E")
	AtomLN2                       = staticAtom("LN2")
	AtomLN10                      = staticAtom("LN10")
	AtomLOG2E                     = staticAtom("LOG2E")
	AtomLOG10E                    = staticAtom("LOG10E")
	AtomSQRT2                     = staticAtom("SQRT2")
	AtomSqrt12                    = staticAtom("SQRT1_2")
	AtomParse                     = staticAtom("parse")
	AtomStringify                 = staticAtom("stringify")
	AtomTest                      = staticAtom("test")
	AtomExec                      = staticAtom("exec")
	AtomLastIndex                 = staticAtom("lastIndex")
	AtomSource                    = staticAtom("source")
	AtomFlags                     = staticAtom("flags")
	AtomGlobal                    = staticAtom("global")
	AtomIgnoreCase                = staticAtom("ignoreCase")
	AtomMultiline                 = staticAtom("multiline")
	AtomDotAll                    = staticAtom("dotAll")
	AtomUnicode                   = staticAtom("unicode")
	AtomUnicodeSets               = staticAtom("unicodeSets")
	AtomSticky                    = staticAtom("sticky")
	AtomHasIndices                = staticAtom("hasIndices")
	AtomIndex                     = staticAtom("index")
	AtomInput                     = staticAtom("input")
	AtomGroups                    = staticAtom("groups")
	AtomIndices                   = staticAtom("indices")
	AtomNow                       = staticAtom("now")
	AtomGetTime                   = staticAtom("getTime")
	AtomToISOString               = staticAtom("toISOString")
	AtomToDateString              = staticAtom("toDateString")
	AtomToUTCString               = staticAtom("toUTCString")
	AtomGetFullYear               = staticAtom("getFullYear")
	AtomNext                      = staticAtom("next")
	AtomDone                      = staticAtom("done")
	AtomReturn                    = staticAtom("return")
	AtomThrow                     = staticAtom("throw")
	AtomThen                      = staticAtom("then")
	AtomArguments                 = staticAtom("arguments")
	AtomCallee                    = staticAtom("callee")
	AtomCaller                    = staticAtom("caller")
	AtomIterator                  = staticAtom("iterator")
	AtomToStringTag               = staticAtom("toStringTag")
	AtomHasInstance               = staticAtom("hasInstance")
	AtomDescription               = staticAtom("description")
	AtomModel                     = staticAtom("model")
	AtomPrompt                    = staticAtom("prompt")
	AtomSize                      = staticAtom("size")
	AtomDuration                  = staticAtom("duration")
	AtomSeed                      = staticAtom("seed")
)
View Source
var (
	AtomGenerator         = staticAtom("Generator")
	AtomGeneratorFunction = staticAtom("GeneratorFunction")
	AtomAsyncFunction     = staticAtom("AsyncFunction")

	AtomAsyncGenerator         = staticAtom("AsyncGenerator")
	AtomAsyncGeneratorFunction = staticAtom("AsyncGeneratorFunction")

	AtomFromAsync = staticAtom("fromAsync")
)

Static atoms for generators and async functions. They live apart from atoms.go so parallel additions to that table merge mechanically.

View Source
var (
	AtomArrayBuffer       = staticAtom("ArrayBuffer")
	AtomSharedArrayBuffer = staticAtom("SharedArrayBuffer")
	AtomDataView          = staticAtom("DataView")

	// The typed array constructors, in elemType order (typedArrayCtorNames).
	AtomInt8Array         = staticAtom("Int8Array")
	AtomUint8Array        = staticAtom("Uint8Array")
	AtomUint8ClampedArray = staticAtom("Uint8ClampedArray")
	AtomInt16Array        = staticAtom("Int16Array")
	AtomUint16Array       = staticAtom("Uint16Array")
	AtomInt32Array        = staticAtom("Int32Array")
	AtomUint32Array       = staticAtom("Uint32Array")
	AtomFloat16Array      = staticAtom("Float16Array")
	AtomFloat32Array      = staticAtom("Float32Array")
	AtomFloat64Array      = staticAtom("Float64Array")
	AtomBigInt64Array     = staticAtom("BigInt64Array")
	AtomBigUint64Array    = staticAtom("BigUint64Array")

	AtomAtomics  = staticAtom("Atomics")
	AtomF16round = staticAtom("f16round")

	AtomTextEncoder = staticAtom("TextEncoder")
	AtomTextDecoder = staticAtom("TextDecoder")
)

Atoms of the binary data builtins (ArrayBuffer, SharedArrayBuffer, DataView, the typed arrays and Atomics) and of TextEncoder and TextDecoder. Only the global names are static, because coldGlobalKeys needs them at package init, and f16round, which the Math table names. The property names are interned with the first group of the process that needs them (binaryNames, textNames), so a process that never names one of its globals carries none of them. They live apart from atoms.go so parallel additions to that table merge mechanically; staticAtom deduplicates names.

View Source
var (
	AtomReflect               = staticAtom("Reflect")
	AtomConstruct             = staticAtom("construct")
	AtomDeleteProperty        = staticAtom("deleteProperty")
	AtomHas                   = staticAtom("has")
	AtomOwnKeys               = staticAtom("ownKeys")
	AtomCopyWithin            = staticAtom("copyWithin")
	AtomToReversed            = staticAtom("toReversed")
	AtomToSorted              = staticAtom("toSorted")
	AtomToSpliced             = staticAtom("toSpliced")
	AtomWith                  = staticAtom("with")
	AtomIsWellFormed          = staticAtom("isWellFormed")
	AtomToWellFormed          = staticAtom("toWellFormed")
	AtomToLocaleLowerCase     = staticAtom("toLocaleLowerCase")
	AtomToLocaleUpperCase     = staticAtom("toLocaleUpperCase")
	AtomTrimLeft              = staticAtom("trimLeft")
	AtomTrimRight             = staticAtom("trimRight")
	AtomAnchor                = staticAtom("anchor")
	AtomBig                   = staticAtom("big")
	AtomBlink                 = staticAtom("blink")
	AtomBold                  = staticAtom("bold")
	AtomFixed                 = staticAtom("fixed")
	AtomFontcolor             = staticAtom("fontcolor")
	AtomFontsize              = staticAtom("fontsize")
	AtomItalics               = staticAtom("italics")
	AtomLink                  = staticAtom("link")
	AtomSmall                 = staticAtom("small")
	AtomStrike                = staticAtom("strike")
	AtomSub                   = staticAtom("sub")
	AtomSup                   = staticAtom("sup")
	AtomEscape                = staticAtom("escape")
	AtomUnescape              = staticAtom("unescape")
	AtomAtob                  = staticAtom("atob")
	AtomBtoa                  = staticAtom("btoa")
	AtomCode                  = staticAtom("code")
	AtomInvalidCharacterError = staticAtom("InvalidCharacterError")
	AtomSumPrecise            = staticAtom("sumPrecise")
	AtomDefineGetter          = staticAtom("__defineGetter__")
	AtomDefineSetter          = staticAtom("__defineSetter__")
	AtomLookupGetter          = staticAtom("__lookupGetter__")
	AtomLookupSetter          = staticAtom("__lookupSetter__")
	AtomIsError               = staticAtom("isError")
)

Static atoms for Reflect, the ES2023 array and string methods and Annex B. They live apart from atoms.go so parallel additions to that table merge mechanically; staticAtom deduplicates names.

View Source
var (
	AtomPromise        = staticAtom("Promise")
	AtomQueueMicrotask = staticAtom("queueMicrotask")
	AtomAll            = staticAtom("all")
	AtomAllSettled     = staticAtom("allSettled")
	AtomAny            = staticAtom("any")
	AtomRace           = staticAtom("race")
	AtomReject         = staticAtom("reject")
	AtomResolve        = staticAtom("resolve")
	AtomTry            = staticAtom("try")
	AtomWithResolvers  = staticAtom("withResolvers")
	AtomCatch          = staticAtom("catch")
	AtomFinally        = staticAtom("finally")
)

Static atoms for Promise and queueMicrotask (builtin_promise.go, jobs.go).

View Source
var (
	AtomAsIntN     = staticAtom("asIntN")
	AtomAsUintN    = staticAtom("asUintN")
	AtomProxy      = staticAtom("Proxy")
	AtomProxyLower = staticAtom("proxy")
	AtomRevocable  = staticAtom("revocable")
	AtomRevoke     = staticAtom("revoke")
)

Static atoms for BigInt and Proxy. They live apart from atoms.go so parallel additions to that table merge mechanically; staticAtom deduplicates names.

View Source
var (
	AtomArrayIterator  = staticAtom("Array Iterator")
	AtomStringIterator = staticAtom("String Iterator")
)
View Source
var (
	AtomMapName        = staticAtom("Map")
	AtomSetName        = staticAtom("Set")
	AtomWeakMap        = staticAtom("WeakMap")
	AtomWeakSet        = staticAtom("WeakSet")
	AtomWeakRef        = staticAtom("WeakRef")
	AtomMapIterator    = staticAtom("Map Iterator")
	AtomSetIterator    = staticAtom("Set Iterator")
	AtomAggregateError = staticAtom("AggregateError")
	AtomErrors         = staticAtom("errors")
	AtomGroupBy        = staticAtom("groupBy")
	AtomDeref          = staticAtom("deref")
	AtomAdd            = staticAtom("add")
	AtomClear          = staticAtom("clear")
	AtomDelete         = staticAtom("delete")

	AtomUnion               = staticAtom("union")
	AtomIntersection        = staticAtom("intersection")
	AtomDifference          = staticAtom("difference")
	AtomSymmetricDifference = staticAtom("symmetricDifference")
	AtomIsSubsetOf          = staticAtom("isSubsetOf")
	AtomIsSupersetOf        = staticAtom("isSupersetOf")
	AtomIsDisjointFrom      = staticAtom("isDisjointFrom")
)

Atoms of the keyed collections, AggregateError and the Set methods. (Names that other builtin groups may also intern get a collection-specific Go name: staticAtom deduplicates the strings themselves.)

View Source
var (
	AtomFor                = staticAtom("for")
	AtomKeyFor             = staticAtom("keyFor")
	AtomAsyncIterator      = staticAtom("asyncIterator")
	AtomIsConcatSpreadable = staticAtom("isConcatSpreadable")
	AtomSearch             = staticAtom("search")
	AtomSpecies            = staticAtom("species")
	AtomUnscopables        = staticAtom("unscopables")
)
View Source
var (
	SymAsyncIterator      = wellKnownSymbol(staticAtom("Symbol.asyncIterator"))
	SymHasInstance        = wellKnownSymbol(staticAtom("Symbol.hasInstance"))
	SymIsConcatSpreadable = wellKnownSymbol(staticAtom("Symbol.isConcatSpreadable"))
	SymIterator           = wellKnownSymbol(staticAtom("Symbol.iterator"))
	SymMatch              = wellKnownSymbol(staticAtom("Symbol.match"))
	SymMatchAll           = wellKnownSymbol(staticAtom("Symbol.matchAll"))
	SymReplace            = wellKnownSymbol(staticAtom("Symbol.replace"))
	SymSearch             = wellKnownSymbol(staticAtom("Symbol.search"))
	SymSpecies            = wellKnownSymbol(staticAtom("Symbol.species"))
	SymSplit              = wellKnownSymbol(staticAtom("Symbol.split"))
	SymToPrimitive        = wellKnownSymbol(staticAtom("Symbol.toPrimitive"))
	SymToStringTag        = wellKnownSymbol(staticAtom("Symbol.toStringTag"))
	SymUnscopables        = wellKnownSymbol(staticAtom("Symbol.unscopables"))
)

Well-known symbols shared by all realms. They are immutable, so sharing is safe; their descriptions are static atoms (flat, hashed, read-only).

View Source
var AtomRegExpStringIterator = staticAtom("RegExp String Iterator")
View Source
var (
	AtomStructuredClone = staticAtom("structuredClone")
)
View Source
var ErrFromGoDepth = errors.New("engine: FromGo value nesting exceeds depth limit")

ErrFromGoDepth is not returned by FromGo: the lazy conversion converts one level per touch, so no depth needs bounding. The variable is kept so errors.Is checks against it still compile.

View Source
var ErrModulePending = errors.New("engine: module evaluation is still pending after the job queue drained")

ErrModulePending is EvaluateModule's error for a module with top-level await whose evaluation is still pending once the job queue has drained: it awaits a promise nothing settles.

View Source
var ErrNoInterpreter = errors.New("engine: bytecode interpreter is not linked")

ErrNoInterpreter is returned by Call/Construct on bytecode functions until the interpreter sets runFunction/constructFunction in its init().

Functions

func AppendNumber

func AppendNumber(dst []byte, f float64) []byte

AppendNumber appends Number::toString(10) of f to dst (used by builders that must not allocate an intermediate string, such as JSON.stringify).

func CanonicalNumericIndexString

func CanonicalNumericIndexString(s *String) (float64, bool)

CanonicalNumericIndexString implements the spec operation: it returns the number n such that ToString(n) == s (or -0 for "-0"), and ok == true.

func FormatStack

func FormatStack(r *Realm, frames []StackFrame) string

FormatStack renders captured frames the way the `stack` property does.

func IsArray

func IsArray(v Value) bool

IsArray implements the IsArray abstract operation (there are no proxies yet).

func IsCallable

func IsCallable(v Value) bool

IsCallable implements the IsCallable abstract operation.

func IsConstructor

func IsConstructor(v Value) bool

IsConstructor implements the IsConstructor abstract operation.

func NumberExponentiate

func NumberExponentiate(base, exponent float64) float64

NumberExponentiate implements Number::exponentiate (also the `**` operator): math.Pow with the cases where IEEE pow and ECMAScript differ fixed up.

func NumberToGoString

func NumberToGoString(f float64) string

NumberToGoString implements Number::toString(10) into a Go string.

func NumberToStringRadix

func NumberToStringRadix(value float64, radix int) string

NumberToStringRadix implements Number::toString(x, radix) for radix != 10: the fewest digits that read back as x, in positional notation. Of two equally short candidates it picks the one closer to x, as the spec's Note 2 recommends. Integers below 2^53 are their exact digits; other values go through shortestRadixDigits.

func SameValue

func SameValue(a, b Value) bool

SameValue implements SameValue (NaN equals NaN, +0 differs from -0).

func SameValueZero

func SameValueZero(a, b Value) bool

SameValueZero implements SameValueZero (NaN equals NaN, +0 equals -0).

func StrictEquals

func StrictEquals(a, b Value) bool

StrictEquals implements IsStrictlyEqual (===).

func StringToNumber

func StringToNumber(s *String) float64

StringToNumber implements StringToNumber (the StringNumericLiteral grammar).

func ToBoolean

func ToBoolean(v Value) bool

ToBoolean implements ToBoolean.

func ToInt32Float

func ToInt32Float(f float64) int32

ToInt32Float implements ToInt32 on a number.

func ToIntegerOrInfinityFloat

func ToIntegerOrInfinityFloat(f float64) float64

ToIntegerOrInfinityFloat implements ToIntegerOrInfinity on a number.

func ToUint32Float

func ToUint32Float(f float64) uint32

ToUint32Float implements ToUint32 on a number.

func ValidateAndApplyPropertyDescriptor

func ValidateAndApplyPropertyDescriptor(r *Realm, o *Object, key PropertyKey, extensible bool, desc PropertyDescriptor, current *PropertyDescriptor) bool

ValidateAndApplyPropertyDescriptor implements the spec operation for an ordinary property. current is nil when the property does not exist. When o is nil the operation only validates. It returns false when the change is not allowed.

Types

type Accessor

type Accessor struct {
	Get *Object
	Set *Object
}

Accessor is the getter/setter pair of an accessor property. Either may be nil (undefined).

type ArrayData

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

ArrayData is the internal payload of ClassArray objects.

type BigInt

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

BigInt is a JavaScript BigInt value: an immutable arbitrary-precision integer. The operators live in bigint_ops.go and the BigInt builtins in builtin_bigint.go; math/big runs only when one of them does.

func NewBigIntFromBig

func NewBigIntFromBig(x *big.Int) (*BigInt, bool)

NewBigIntFromBig copies x (for host import). ok is false when x exceeds the BigInt size limit (2^20 bits).

func NewBigIntFromDecimal

func NewBigIntFromDecimal(text string) (*BigInt, bool)

NewBigIntFromDecimal parses decimal text such as the digits of a `123n` literal (no sign, no suffix). ok is false on malformed input.

func NewBigIntFromInt64

func NewBigIntFromInt64(i int64) *BigInt

NewBigIntFromInt64 wraps an int64.

func NewBigIntFromUint64

func NewBigIntFromUint64(u uint64) *BigInt

NewBigIntFromUint64 wraps a uint64.

func StringToBigInt

func StringToBigInt(s *String) (*BigInt, bool)

StringToBigInt implements StringToBigInt (decimal, hex, octal and binary literals; empty string is 0n). ok is false when the string is not a valid StringIntegerLiteral or its value exceeds the BigInt size limit.

func (*BigInt) Big

func (b *BigInt) Big() *big.Int

Big returns a copy of the underlying math/big value (for host export).

func (*BigInt) Float64

func (b *BigInt) Float64() float64

Float64 returns the number nearest b (Number(bigint)).

func (*BigInt) Int64

func (b *BigInt) Int64() int64

Int64 returns b modulo 2^64 as a two's complement int64, the value ToBigInt64 stores.

func (*BigInt) IsZero

func (b *BigInt) IsZero() bool

IsZero reports whether the value is 0n (used by ToBoolean).

func (*BigInt) StrictEquals

func (b *BigInt) StrictEquals(o *BigInt) bool

StrictEquals reports mathematical equality.

func (*BigInt) ToString

func (b *BigInt) ToString() string

ToString returns the decimal representation without the `n` suffix.

func (*BigInt) Uint64

func (b *BigInt) Uint64() uint64

Uint64 returns b modulo 2^64, the value ToBigUint64 stores.

type CallState

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

CallState is a snapshot of the realm's call bookkeeping: the frame depth and the interpreter's register stack and frame table positions. A host takes it at its entry into the engine and restores it when a Go panic (a native's non-JavaScript panic, re-panicked to the host) unwound through interpreter frames without running their exits, so a host that recovers keeps a usable runtime.

type Class

type Class uint8

Class is the object's exotic/internal kind.

const (
	ClassObject Class = iota
	ClassArray
	ClassFunction
	ClassError
	ClassBoolean
	ClassNumber
	ClassString
	ClassSymbol
	ClassBigInt
	ClassRegExp
	ClassDate
	ClassArguments
	ClassArrayIterator
	ClassStringIterator
	ClassMap
	ClassSet
	ClassWeakMap
	ClassWeakSet
	ClassWeakRef
	ClassMapIterator
	ClassSetIterator
	ClassRegExpStringIterator
	ClassGenerator
	ClassPromise
	ClassProxy
	ClassArrayBuffer
	ClassSharedArrayBuffer
	ClassDataView
	ClassAsyncGenerator
	ClassTypedArray
	ClassTextEncoder
	ClassTextDecoder
)

func (Class) String

func (c Class) String() string

String returns the class name ("Object", "Array", ...).

type DateData

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

DateData is the internal payload of ClassDate objects: the time value in milliseconds since the epoch, NaN for an invalid date.

func (*DateData) TimeValue

func (d *DateData) TimeValue() float64

TimeValue returns the time value (ms since the epoch; NaN when invalid).

type Env

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

Env is a closure environment: captured bindings of one scope.

func NewEnv

func NewEnv(parent *Env, n int) *Env

NewEnv creates an environment with n slots initialized to undefined.

func (*Env) Len

func (e *Env) Len() int

Len returns the slot count.

func (*Env) Parent

func (e *Env) Parent() *Env

Parent returns the enclosing environment.

func (*Env) SetSlot

func (e *Env) SetSlot(i int, v Value)

SetSlot writes slot i.

func (*Env) Slot

func (e *Env) Slot(i int) Value

Slot reads slot i.

func (*Env) Slots

func (e *Env) Slots() []Value

Slots exposes the slot storage for the interpreter.

type ErrorData

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

ErrorData is the internal payload of ClassError objects.

func (*ErrorData) Frames

func (ed *ErrorData) Frames() []StackFrame

Frames returns the captured compact stack.

type ErrorKind

type ErrorKind uint8

ErrorKind selects an Error constructor family.

const (
	KindError ErrorKind = iota
	KindTypeError
	KindRangeError
	KindSyntaxError
	KindReferenceError
	KindEvalError
	KindURIError
)

func (ErrorKind) Name

func (k ErrorKind) Name() *String

Name returns the constructor name of the kind.

type Exception

type Exception struct {
	Value Value
	Stack string
}

Exception is a thrown JavaScript value travelling through Go error returns.

func (*Exception) Error

func (e *Exception) Error() string

Error renders the exception without running user code: "Name: message" for Error objects (or the string form of the value), followed by Stack when set.

func (*Exception) Message

func (e *Exception) Message() string

Message is the thrown value's `message` when it is a primitive data property (own or inherited), the value itself when a primitive was thrown, else "". undefined and null are "". It never runs a getter or toString.

func (*Exception) Name

func (e *Exception) Name() string

Name is the thrown value's `name` when it is a string data property (own or inherited, so "TypeError" for a TypeError), else "". It never runs a getter.

func (*Exception) String

func (e *Exception) String() string

String is Error.

func (*Exception) Unwrap

func (e *Exception) Unwrap() error

Unwrap returns the Go error a native function returned when the thrown value is the Error built for it (see hostErrorValue), so errors.Is and errors.As see through a throw that JavaScript did not replace.

type FuncKind

type FuncKind uint8

FuncKind classifies function objects for Call/Construct dispatch.

const (
	FuncNative FuncKind = iota
	FuncBytecode
	FuncBound
	FuncNativeData // a NativeDataFunc and its payload
	FuncProxy      // a callable proxy: dataFn is proxyCall, data the *proxyData
)

type FunctionData

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

FunctionData is the internal payload of ClassFunction objects. Fields used by one kind only share the struct with the others, and state only some functions of a kind have lives in data: at 96 bytes the payload fills a funcObject's 240-byte size class exactly and a nativeFuncObject's 224-byte one.

func (*FunctionData) BoundTarget

func (fd *FunctionData) BoundTarget() *Object

BoundTarget returns the target of a bound function (nil otherwise).

func (*FunctionData) Code

func (fd *FunctionData) Code() *bytecode.Function

Code returns the compiled template for bytecode functions.

func (*FunctionData) Data

func (fd *FunctionData) Data() any

Data returns the payload of a data native (nil otherwise).

func (*FunctionData) Env

func (fd *FunctionData) Env() *Env

Env returns the closure environment for bytecode functions.

func (*FunctionData) HomeObject

func (fd *FunctionData) HomeObject() *Object

HomeObject returns the [[HomeObject]] of a method (nil otherwise).

func (*FunctionData) IsConstructor

func (fd *FunctionData) IsConstructor() bool

IsConstructor reports whether the function has [[Construct]].

func (*FunctionData) Kind

func (fd *FunctionData) Kind() FuncKind

Kind returns the dispatch kind.

func (*FunctionData) Name

func (fd *FunctionData) Name() *String

Name returns the function's initial name (may be nil).

func (*FunctionData) Native

func (fd *FunctionData) Native() NativeFunc

Native returns the native implementation (nil for bytecode functions and data natives).

func (*FunctionData) Realm

func (fd *FunctionData) Realm() *Realm

Realm returns the realm that created the function, or nil for shared intrinsics (natives must use the realm passed to them instead).

func (*FunctionData) SetConstructor

func (fd *FunctionData) SetConstructor(ctor NativeCtor)

SetConstructor replaces the [[Construct]] behaviour of a native function.

func (*FunctionData) SetHomeObject

func (fd *FunctionData) SetHomeObject(o *Object)

SetHomeObject records the [[HomeObject]] of a method.

func (*FunctionData) SetNative

func (fd *FunctionData) SetNative(fn NativeFunc)

SetNative replaces the [[Call]] behaviour of a native function (used by the installers to complete stub constructors before the realm is shared).

func (*FunctionData) ThisValue

func (fd *FunctionData) ThisValue() Value

ThisValue returns the lexically captured this of an arrow function (the bound this of a bound function).

type Hint

type Hint uint8

Hint is the ToPrimitive preferred type.

const (
	HintDefault Hint = iota
	HintNumber
	HintString
)

type ICEntry

type ICEntry struct {
	Shape *Shape
	Epoch uint32
	// contains filtered or unexported fields
}

ICEntry is one inline-cache entry for a named property access. It is valid for a receiver iff the receiver's shape is Shape and the realm's prototype epoch still equals Epoch; then the property lives in slot Slot() of the object HolderDepth() prototypes up from the receiver (0 = own property). The epoch advances in steps of two, so it is always even: an entry for an accessor property stores the epoch with the low bit set, never passes the data check on the interpreter's hit path, and is validated by accessorIC in the slow paths instead. Slot and depth share one word so the entry is 16 bytes: a realm's IC table (one entry per property-access site of every function it instantiated) is the largest single item it retains.

func (*ICEntry) Holder

func (e *ICEntry) Holder(o *Object) *Object

Holder walks HolderDepth prototypes up from o. Only meaningful after Valid.

func (*ICEntry) HolderDepth

func (e *ICEntry) HolderDepth() uint8

HolderDepth returns how many prototypes up from the receiver the holder is.

func (*ICEntry) Slot

func (e *ICEntry) Slot() uint32

Slot returns the property's slot in the holder.

func (*ICEntry) Valid

func (e *ICEntry) Valid(r *Realm, o *Object) bool

Valid reports whether the entry can be used for o in realm r.

type InterruptedError

type InterruptedError struct {
	Value any
}

InterruptedError is returned when Realm.Interrupt stopped execution.

func (*InterruptedError) Error

func (e *InterruptedError) Error() string

Error implements error.

type Intrinsics

type Intrinsics struct {
	ObjectPrototype   *Object
	FunctionPrototype *Object
	ArrayPrototype    *Object
	StringPrototype   *Object
	NumberPrototype   *Object
	BooleanPrototype  *Object
	ErrorPrototype    *Object
	RegExpPrototype   *Object
	DatePrototype     *Object
	// BigIntPrototype carries toString and valueOf for bigint primitives;
	// the BigInt late global adds the rest (builtin_bigint.go). The shared
	// template has none: the BigInt group builds it (lateAt(lateBigInt)
	// before use).
	BigIntPrototype *Object
	// ArrayIteratorPrototype is %ArrayIteratorPrototype%, the prototype of
	// the objects returned by Array.prototype.keys/values/entries.
	ArrayIteratorPrototype *Object

	ObjectCtor   *Object
	FunctionCtor *Object
	ArrayCtor    *Object
	StringCtor   *Object
	NumberCtor   *Object
	BooleanCtor  *Object
	RegExpCtor   *Object
	DateCtor     *Object

	// JSON and Math are the namespace objects (filled by their installers).
	JSON *Object
	Math *Object
	// contains filtered or unexported fields
}

Intrinsics holds the intrinsic objects of a realm. A realm points at its own (allocated with it) or, in shared mode, at the process-wide template's, so the struct is written only while the intrinsics are built.

type IterKind

type IterKind uint8

IterKind selects what an array iterator yields.

const (
	IterValues IterKind = iota
	IterKeys
	IterEntries
)

type IteratorData

type IteratorData struct {
	Target Value
	Index  int
	Kind   IterKind
	Done   bool
}

IteratorData is the internal payload (Object.Internal()) of ClassArrayIterator and ClassStringIterator objects. Target is the iterated array or array-like object, or the string value; Index is the next position (element index for arrays, code-unit index for strings); Done is set once exhausted (the target is then released) so further next() calls return {value: undefined, done: true}.

func (*IteratorData) Next

func (d *IteratorData) Next(r *Realm) (Value, bool, error)

Next advances an engine iterator: arrays yield values, keys or [key, value] pairs according to Kind, reading the live length each step and holes as undefined; strings yield code points as strings. Array-likes (any other object target) are iterated through Get(length) and Get(index). A throwing step completes the iterator, as it completes the generator of the spec's CreateIteratorFromClosure.

type ModuleEnv

type ModuleEnv struct {
	*Env
	// contains filtered or unexported fields
}

ModuleEnv is the top-level environment of a module. Exports are live bindings: GetBindingValue reads the slot each time.

func NewModuleEnv

func NewModuleEnv(nslots int, exports map[string]int) *ModuleEnv

NewModuleEnv creates a module environment with nslots bindings and the given export-name -> slot mapping.

func (*ModuleEnv) ExportNames

func (m *ModuleEnv) ExportNames() []string

ExportNames returns the export names (unordered).

func (*ModuleEnv) GetBindingValue

func (m *ModuleEnv) GetBindingValue(name string) (Value, bool)

GetBindingValue returns the current value of an exported binding. ok is false for unknown names. A Hole() value means the binding is in its TDZ.

type NativeCtor

type NativeCtor func(r *Realm, args []Value, newTarget *Object) (Value, error)

NativeCtor is the [[Construct]] behaviour of a builtin constructor.

type NativeDataFunc

type NativeDataFunc func(r *Realm, fd *FunctionData, this Value, args []Value) (Value, error)

NativeDataFunc is the behaviour of a data native (NewNativeDataFunction): its per-function state is a value stored in the function object, read with fd.Data(), instead of variables captured by a closure, so one adapter serves every function of its kind and creating one costs only the function object. args may alias the register stack, as for NativeFunc.

type NativeFunc

type NativeFunc func(r *Realm, this Value, args []Value) (Value, error)

NativeFunc is the Go signature of a builtin function. args may alias the interpreter's register stack: natives MUST NOT retain the slice.

type Object

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

Object is a JavaScript object.

func (*Object) ArrayLength

func (o *Object) ArrayLength() uint32

ArrayLength returns the length of an array object (0 for non-arrays).

func (*Object) BufferData

func (o *Object) BufferData() (data []byte, ok bool)

BufferData returns the data of an ArrayBuffer or SharedArrayBuffer, or the bytes of its buffer a typed array or DataView views; ok is false for any other object. The slice is the buffer's data, not a copy, and is empty for a detached buffer and a view out of its buffer's bounds. It is valid until JavaScript next runs, which may detach or resize the buffer.

func (*Object) Class

func (o *Object) Class() Class

Class returns the object's class.

func (*Object) ClassName

func (o *Object) ClassName() string

ClassName returns the name of the object's class (Class.String).

func (*Object) CreateDataProperty

func (o *Object) CreateDataProperty(r *Realm, key PropertyKey, v Value) (bool, error)

CreateDataProperty implements CreateDataProperty.

func (*Object) CreateDataPropertyOrThrow

func (o *Object) CreateDataPropertyOrThrow(r *Realm, key PropertyKey, v Value) error

CreateDataPropertyOrThrow implements CreateDataPropertyOrThrow.

func (*Object) DateValue

func (o *Object) DateValue() (float64, bool)

DateValue returns the time value of a Date object; ok is false for other objects.

func (*Object) DefineLazyProperty

func (o *Object) DefineLazyProperty(r *Realm, key PropertyKey, init func(*Realm) Value)

DefineLazyProperty registers a property whose value is computed by init on first access. It is used for lazily materialized globals (Math, JSON, ...). The property is installed non-enumerable, writable and configurable.

func (*Object) DefineOwnAccessorFast

func (o *Object) DefineOwnAccessorFast(r *Realm, key PropertyKey, get, set *Object, attrs uint8)

DefineOwnAccessorFast adds an accessor property known to be absent.

func (*Object) DefineOwnDataFast

func (o *Object) DefineOwnDataFast(r *Realm, key PropertyKey, v Value, attrs uint8)

DefineOwnDataFast adds a data property to an object that is known not to have it yet (fresh objects during bootstrap, literals, host conversion).

func (*Object) DefineOwnProperty

func (o *Object) DefineOwnProperty(r *Realm, key PropertyKey, desc PropertyDescriptor) (bool, error)

DefineOwnProperty implements [[DefineOwnProperty]] including the Array and String exotic behaviour. The error is non-nil only for RangeError on an invalid array length or when coercing the length value throws.

func (*Object) DefinePropertyOrThrow

func (o *Object) DefinePropertyOrThrow(r *Realm, key PropertyKey, desc PropertyDescriptor) error

DefinePropertyOrThrow implements DefinePropertyOrThrow.

func (*Object) Delete

func (o *Object) Delete(r *Realm, key PropertyKey) bool

Delete implements [[Delete]] for an ordinary object. It returns false when the property exists and is not configurable. It runs no trap (Realm.deleteProperty does).

func (*Object) DeletePropertyOrThrow

func (o *Object) DeletePropertyOrThrow(r *Realm, key PropertyKey) error

DeletePropertyOrThrow implements the strict-mode `delete` operator.

func (*Object) Elements

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

Elements exposes dense storage for fast iteration; entries may be holes and the slice must not be retained across a call into user code. An unmaterialized host array (hostlazy.go) is materialized first.

func (*Object) ErrorData

func (o *Object) ErrorData() *ErrorData

ErrorData returns the payload of an error object created by the engine, or nil.

func (*Object) Freeze

func (o *Object) Freeze(r *Realm)

Freeze makes every own data property non-writable and non-configurable, every accessor non-configurable, and prevents extensions.

func (*Object) FunctionData

func (o *Object) FunctionData() *FunctionData

FunctionData returns the function payload or nil.

func (*Object) Get

func (o *Object) Get(r *Realm, key PropertyKey, receiver Value) (Value, error)

Get implements [[Get]] with an explicit receiver.

func (*Object) GetIndex

func (o *Object) GetIndex(r *Realm, i uint32) (Value, error)

GetIndex is [[Get]] for an array index.

func (*Object) GetOwnDataValue

func (o *Object) GetOwnDataValue(key PropertyKey) (Value, bool)

GetOwnDataValue returns the value of an own data property without invoking getters, or false when absent or an accessor. It never runs user code.

func (*Object) GetOwnProperty

func (o *Object) GetOwnProperty(key PropertyKey) (PropertyDescriptor, bool)

GetOwnProperty implements [[GetOwnProperty]].

func (*Object) GetProp

func (o *Object) GetProp(r *Realm, key PropertyKey) (Value, error)

GetProp is [[Get]] with the object itself as receiver.

func (*Object) HasOwnProperty

func (o *Object) HasOwnProperty(key PropertyKey) bool

HasOwnProperty reports whether key is an own property.

func (*Object) HasProperty

func (o *Object) HasProperty(key PropertyKey) bool

HasProperty implements [[HasProperty]] for a chain without proxies: it stops at a proxy, which has no own properties and a null prototype for the infallible methods. Realm.hasProperty runs the has trap.

func (*Object) HostValue

func (o *Object) HostValue() (v any, ok bool)

HostValue returns the Go map or slice o was converted from by FromGo when JavaScript has not modified o (see the file comment); ok is false for every other object.

func (*Object) Internal

func (o *Object) Internal() any

Internal returns the class-specific payload (nil for an ordinary object, including a host map node, whose internal is its Go map).

func (*Object) IsCallable

func (o *Object) IsCallable() bool

IsCallable reports whether the object has a [[Call]] internal method: a function, or a proxy whose target was callable.

func (*Object) IsDenseArray

func (o *Object) IsDenseArray() bool

IsDenseArray reports whether every index < length is present in dense storage (no holes, no sparse entries), enabling index-loop fast paths.

func (*Object) IsDetachedBuffer

func (o *Object) IsDetachedBuffer() bool

IsDetachedBuffer reports whether o is a detached ArrayBuffer.

func (*Object) IsDictionaryMode

func (o *Object) IsDictionaryMode() bool

IsDictionaryMode reports whether named properties live in the dictionary (materializing an unmaterialized host node first, like Shape).

func (*Object) IsExtensible

func (o *Object) IsExtensible() bool

IsExtensible reports [[Extensible]].

func (*Object) IsFrozen

func (o *Object) IsFrozen() bool

IsFrozen implements TestIntegrityLevel(frozen).

func (*Object) IsPrototypeObject

func (o *Object) IsPrototypeObject() bool

IsPrototypeObject reports whether o is used as some object's [[Prototype]].

func (*Object) IsRevokedProxy

func (o *Object) IsRevokedProxy() bool

IsRevokedProxy reports whether o is a proxy that has been revoked.

func (*Object) IsSealed

func (o *Object) IsSealed() bool

IsSealed implements TestIntegrityLevel(sealed).

func (*Object) IsShared

func (o *Object) IsShared() bool

IsShared reports whether o is a frozen intrinsic shared across realms.

func (*Object) Lookup

func (o *Object) Lookup(r *Realm, key PropertyKey) (v Value, found bool, err error)

Lookup is [[Get]] with the object itself as receiver that also reports whether the property was found, for hosts that tell an absent property from an undefined one: found is false when neither the object nor its prototype chain has it. No has trap runs: a proxy ending the chain answers with its get trap, found, or without one continues on its target.

func (*Object) OwnEnumerableStringKeys

func (o *Object) OwnEnumerableStringKeys() []PropertyKey

OwnEnumerableStringKeys returns own enumerable string keys in spec order (Object.keys, JSON.stringify, for-in). Indices are returned as index keys.

func (*Object) OwnPropertyKeys

func (o *Object) OwnPropertyKeys() []PropertyKey

OwnPropertyKeys implements [[OwnPropertyKeys]]: integer indices ascending, then strings in insertion order, then symbols in insertion order.

func (*Object) PreventExtensions

func (o *Object) PreventExtensions(r *Realm)

PreventExtensions implements [[PreventExtensions]]. It is a no-op on shared intrinsics, which are already non-extensible.

func (*Object) PrimitiveValue

func (o *Object) PrimitiveValue() (Value, bool)

PrimitiveValue returns the wrapped primitive of a Boolean/Number/String/ BigInt wrapper object.

func (*Object) PromiseResult

func (o *Object) PromiseResult() (state PromiseState, result Value, ok bool)

PromiseResult returns the state of the promise o and its result: the fulfillment value or the rejection reason, undefined while pending. ok is false when o is not a promise.

func (*Object) Proto

func (o *Object) Proto() *Object

Proto returns [[Prototype]] or nil.

func (*Object) Push

func (o *Object) Push(r *Realm, values ...Value) bool

Push appends values to an array as CreateDataProperty does (Array.prototype .push semantics when no prototype has indexed properties). It returns false when length is not writable or the array is not extensible.

func (*Object) RegExpData

func (o *Object) RegExpData() *RegExpData

RegExpData returns the payload of a RegExp object, or nil.

func (*Object) ReserveSlots

func (o *Object) ReserveSlots(r *Realm, n int)

ReserveSlots ensures capacity for n more named properties without reallocation (used before bulk installs).

func (*Object) Seal

func (o *Object) Seal(r *Realm)

Seal makes every own property non-configurable and prevents extensions.

func (*Object) Set

func (o *Object) Set(r *Realm, key PropertyKey, v Value, receiver Value) (bool, error)

Set implements OrdinarySet. It returns false when the assignment is rejected; strict-mode callers turn that into a TypeError (Realm.SetProp).

func (*Object) SetInternal

func (o *Object) SetInternal(v any)

SetInternal replaces the class-specific payload (for the builtins).

func (*Object) SetLength

func (o *Object) SetLength(r *Realm, n uint32) (bool, error)

SetLength sets an array's length as `a.length = n` would, returning false when rejected (strict callers throw).

func (*Object) SetProp

func (o *Object) SetProp(r *Realm, key PropertyKey, v Value) error

SetProp is [[Set]] with the object as receiver, throwing a TypeError in the strict-mode manner when the assignment is rejected.

func (*Object) SetPrototypeOf

func (o *Object) SetPrototypeOf(r *Realm, proto *Object) bool

SetPrototypeOf implements OrdinarySetPrototypeOf; the realm's Object.prototype is an immutable prototype exotic object.

func (*Object) SetSlot

func (o *Object) SetSlot(i uint32, v Value)

SetSlot writes named slot i. The caller must know the slot is a writable data property (an IC hit on a store); shared intrinsics have none.

func (*Object) Shape

func (o *Object) Shape() *Shape

Shape returns the current shape (the dictionary sentinel in dict mode). An unmaterialized host node (hostlazy.go) has no layout yet: Shape materializes it.

func (*Object) Slot

func (o *Object) Slot(i uint32) Value

Slot reads named slot i (shape mode only; callers hold a valid ICEntry).

func (*Object) TypedArrayElements

func (o *Object) TypedArrayElements() (elems any, ok bool)

TypedArrayElements returns the elements of a typed array as a Go slice of its element type: []int8, []uint8 (a Uint8Array or Uint8ClampedArray), []int16, []uint16 (also a Float16Array, as its IEEE 754 binary16 bits), []int32, []uint32, []float32, []float64, []int64 or []uint64; ok is false for any other object. Like BufferData, the slice is the buffer's memory, not a copy, and is nil when the array is out of bounds. The elements are in little-endian byte order, which the slice reads correctly on a little-endian host only. The buffer's data must be aligned for the element type: one the engine allocates always is (newBytes), and one over host bytes (NewArrayBuffer) is when those bytes start at a word boundary.

type PrivateName

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

PrivateName is one private name of one class evaluation (a new set is created every time a class definition is evaluated).

type PromiseRejectionOperation

type PromiseRejectionOperation uint8

PromiseRejectionOperation is the operation HostPromiseRejectionTracker reports.

const (
	// PromiseRejectionReject: the promise was rejected with no handler.
	PromiseRejectionReject PromiseRejectionOperation = iota
	// PromiseRejectionHandle: the first handler was added to the promise,
	// rejected earlier with none.
	PromiseRejectionHandle
)

type PromiseState

type PromiseState uint8

PromiseState is the [PromiseState] of a promise.

const (
	PromisePending PromiseState = iota
	PromiseFulfilled
	PromiseRejected
)

Promise states.

type PropertyDescriptor

type PropertyDescriptor struct {
	Value Value
	Get   Value // getter or undefined
	Set   Value // setter or undefined
	// contains filtered or unexported fields
}

PropertyDescriptor is the spec's Property Descriptor record. Absent fields are tracked in present; attribute values live in attrs.

func AccessorDescriptor

func AccessorDescriptor(get, set *Object, attrs uint8) PropertyDescriptor

AccessorDescriptor builds a complete accessor descriptor; get/set may be nil.

func DataDescriptor

func DataDescriptor(v Value, attrs uint8) PropertyDescriptor

DataDescriptor builds a complete data descriptor.

func (PropertyDescriptor) Attrs

func (d PropertyDescriptor) Attrs() uint8

Attrs returns the attribute bits (attrAccessor set for accessor descriptors).

func (PropertyDescriptor) Configurable

func (d PropertyDescriptor) Configurable() bool

Configurable returns [[Configurable]] (false when absent).

func (PropertyDescriptor) Enumerable

func (d PropertyDescriptor) Enumerable() bool

Enumerable returns [[Enumerable]] (false when absent).

func (PropertyDescriptor) GetterObject

func (d PropertyDescriptor) GetterObject() *Object

GetterObject returns the getter or nil.

func (PropertyDescriptor) HasConfigurable

func (d PropertyDescriptor) HasConfigurable() bool

HasConfigurable reports whether [[Configurable]] is present.

func (PropertyDescriptor) HasEnumerable

func (d PropertyDescriptor) HasEnumerable() bool

HasEnumerable reports whether [[Enumerable]] is present.

func (PropertyDescriptor) HasGet

func (d PropertyDescriptor) HasGet() bool

HasGet reports whether [[Get]] is present.

func (PropertyDescriptor) HasSet

func (d PropertyDescriptor) HasSet() bool

HasSet reports whether [[Set]] is present.

func (PropertyDescriptor) HasValue

func (d PropertyDescriptor) HasValue() bool

HasValue reports whether [Value] is present.

func (PropertyDescriptor) HasWritable

func (d PropertyDescriptor) HasWritable() bool

HasWritable reports whether [[Writable]] is present.

func (PropertyDescriptor) IsAccessorDescriptor

func (d PropertyDescriptor) IsAccessorDescriptor() bool

IsAccessorDescriptor reports whether [[Get]] or [[Set]] is present.

func (PropertyDescriptor) IsDataDescriptor

func (d PropertyDescriptor) IsDataDescriptor() bool

IsDataDescriptor reports whether [Value] or [[Writable]] is present.

func (PropertyDescriptor) IsGenericDescriptor

func (d PropertyDescriptor) IsGenericDescriptor() bool

IsGenericDescriptor reports whether the descriptor is neither data nor accessor.

func (*PropertyDescriptor) SetConfigurable

func (d *PropertyDescriptor) SetConfigurable(b bool)

SetConfigurable sets [[Configurable]].

func (*PropertyDescriptor) SetEnumerable

func (d *PropertyDescriptor) SetEnumerable(b bool)

SetEnumerable sets [[Enumerable]].

func (*PropertyDescriptor) SetGet

func (d *PropertyDescriptor) SetGet(v Value)

SetGet sets [[Get]] (object or undefined).

func (*PropertyDescriptor) SetSet

func (d *PropertyDescriptor) SetSet(v Value)

SetSet sets [[Set]] (object or undefined).

func (*PropertyDescriptor) SetValue

func (d *PropertyDescriptor) SetValue(v Value)

SetValue sets [Value].

func (*PropertyDescriptor) SetWritable

func (d *PropertyDescriptor) SetWritable(b bool)

SetWritable sets [[Writable]].

func (PropertyDescriptor) SetterObject

func (d PropertyDescriptor) SetterObject() *Object

SetterObject returns the setter or nil.

func (PropertyDescriptor) Writable

func (d PropertyDescriptor) Writable() bool

Writable returns [[Writable]] (false when absent).

type PropertyKey

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

PropertyKey identifies an own property. It is a Value restricted to an interned *String, a *Symbol, a canonical array index (an integer number in [0, 2^32-2]) or a class's *PrivateName (private.go). Two keys are equal iff their 16 bytes are equal, so keys are usable as Go map keys and never need string comparison.

func IndexKey

func IndexKey(i uint32) PropertyKey

IndexKey builds a key for a canonical array index.

func InternKey

func InternKey(g string) PropertyKey

InternKey is Realm.KeyFromGoString without a realm: the key comes from the process-wide tables, so it is valid in every realm. A host that resolves property names once (a hook path, a struct field) keeps the key and with it the atom alive.

func PrivateKey

func PrivateKey(pn *PrivateName) PropertyKey

PrivateKey returns the property key of a private name.

func StringKey

func StringKey(s *String) PropertyKey

StringKey builds a key from an interned string. The caller must pass an atom (Realm.Intern or a static Atom*); it is a programming error otherwise.

func SymbolKey

func SymbolKey(s *Symbol) PropertyKey

SymbolKey builds a key from a symbol.

func (PropertyKey) GoString

func (k PropertyKey) GoString() string

GoString renders the key for messages and host export (index -> decimal).

func (PropertyKey) Index

func (k PropertyKey) Index() uint32

Index returns the array index. Only valid when IsIndex.

func (PropertyKey) IsIndex

func (k PropertyKey) IsIndex() bool

IsIndex reports whether the key is an array index.

func (PropertyKey) IsPrivate

func (k PropertyKey) IsPrivate() bool

IsPrivate reports whether the key is a private name.

func (PropertyKey) IsString

func (k PropertyKey) IsString() bool

IsString reports whether the key is a string.

func (PropertyKey) IsSymbol

func (k PropertyKey) IsSymbol() bool

IsSymbol reports whether the key is a symbol.

func (PropertyKey) String

func (k PropertyKey) String() *String

String returns the interned string. Only valid when IsString.

func (PropertyKey) Symbol

func (k PropertyKey) Symbol() *Symbol

Symbol returns the symbol. Only valid when IsSymbol.

func (PropertyKey) ToJSString

func (k PropertyKey) ToJSString(r *Realm) *String

ToJSString returns the key as a JavaScript string (symbols are converted to their descriptive form; callers handling symbols must check first).

func (PropertyKey) Value

func (k PropertyKey) Value() Value

Value returns the key as a Value (index keys become numbers).

type Realm

type Realm struct {
	Global *Object
	*Intrinsics
	// contains filtered or unexported fields
}

Realm is one isolated JavaScript global environment. It is single-goroutine except for Interrupt/ClearInterrupt.

func NewRealm

func NewRealm() *Realm

NewRealm creates a realm with mutable, per-realm intrinsics.

func NewRealmWith

func NewRealmWith(opts RealmOptions) *Realm

NewRealmWith creates a realm according to opts.

func (*Realm) Add

func (r *Realm) Add(a, b Value) (Value, error)

Add implements the `+` operator.

func (*Realm) AllocIC

func (r *Realm) AllocIC(fn *bytecode.Function, count uint32) uint32

AllocIC reserves count IC entries for fn and returns the base index; a second call for the same template returns the same base.

func (*Realm) Call

func (r *Realm) Call(fn Value, this Value, args []Value) (Value, error)

Call implements the Call abstract operation.

func (*Realm) CallDepth

func (r *Realm) CallDepth() int

CallDepth returns the current frame count.

func (*Realm) CallObject

func (r *Realm) CallObject(fn *Object, this Value, args []Value) (Value, error)

CallObject calls a function object known to be callable.

func (*Realm) CallState

func (r *Realm) CallState() CallState

CallState returns the current call bookkeeping.

func (*Realm) CheckAccessorFunction

func (r *Realm) CheckAccessorFunction(v Value, setter bool) error

CheckAccessorFunction returns the TypeError ToPropertyDescriptor throws for a getter (or, when setter is set, a setter) that is neither callable nor undefined, and nil otherwise. Strings print unquoted.

func (*Realm) CheckGlobalDeclarations

func (r *Realm) CheckGlobalDeclarations(code *bytecode.Function) error

CheckGlobalDeclarations makes the checks of GlobalDeclarationInstantiation that can fail before a script runs: a lexical declaration may not shadow a non-configurable property of the global object, such as undefined; a function declaration may replace a global property only when it is configurable or a writable, enumerable data property (CanDeclareGlobalFunction); and a function or var name the global object does not have needs it extensible (CanDeclareGlobalVar).

func (*Realm) CheckInterrupt

func (r *Realm) CheckInterrupt() error

CheckInterrupt returns an *InterruptedError when an interrupt is pending. It builds the error itself rather than calling interruptError, which would cost the per-step checks of natives (interruptEvery, btMachine.tick) their inlining.

func (*Realm) ClearInterrupt

func (r *Realm) ClearInterrupt()

ClearInterrupt resets the interrupt flag and payload.

func (*Realm) Concat

func (r *Realm) Concat(a, b *String) (*String, error)

Concat returns a + b, building a rope when the result is long. A result longer than the string length limit is RangeError: Invalid string length, raised before anything is allocated (`s = s + s` builds ropes without copying, so the limit must be enforced on the length arithmetic itself).

func (*Realm) Construct

func (r *Realm) Construct(fn Value, args []Value, newTarget *Object) (Value, error)

Construct implements the Construct abstract operation. newTarget nil means the constructor itself.

func (*Realm) CreateListFromArrayLike

func (r *Realm) CreateListFromArrayLike(v Value) ([]Value, error)

CreateListFromArrayLike implements CreateListFromArrayLike (all element types allowed).

func (*Realm) DateTime

func (r *Realm) DateTime(tv float64) time.Time

DateTime converts a finite time value to a time.Time in the realm's time zone (the Go value a Date exports as).

func (*Realm) DetachArrayBuffer

func (r *Realm) DetachArrayBuffer(v Value) error

DetachArrayBuffer implements DetachArrayBuffer(v) for a host: v must be an ArrayBuffer (not a SharedArrayBuffer). Its data is released and every view over it becomes out of bounds.

func (*Realm) DisplayString

func (r *Realm) DisplayString(v Value) string

DisplayString renders a value for error messages without running user code: strings are quoted-free, objects show their class or function name.

func (*Realm) EnterCall

func (r *Realm) EnterCall() error

EnterCall accounts one frame; the interpreter calls it for JS-to-JS calls.

func (*Realm) EnumerableOwnKeys

func (r *Realm) EnumerableOwnKeys(o *Object) ([]PropertyKey, error)

EnumerableOwnKeys returns the own enumerable string keys as Object.keys does, through the ownKeys and getOwnPropertyDescriptor traps for a proxy.

func (*Realm) ErrorConstructorFor

func (r *Realm) ErrorConstructorFor(kind ErrorKind) *Object

ErrorConstructorFor returns the intrinsic constructor for an error kind.

func (*Realm) ErrorPrototypeFor

func (r *Realm) ErrorPrototypeFor(kind ErrorKind) *Object

ErrorPrototypeFor returns the intrinsic prototype for an error kind.

func (*Realm) EvaluateModule

func (r *Realm) EvaluateModule(code *bytecode.Function) (*ModuleEnv, error)

EvaluateModule instantiates and runs a compiled module in r and returns its environment, whose slots back the live export bindings, or nil when the evaluation failed before the module's body started (an interrupt pending on entry), so no binding was initialized. The compiled template is shared: only per-realm state (function objects, the module Env, inline caches) is created here. A module with top-level await evaluates asynchronously; the job queue drains before an outermost EvaluateModule returns, and its error is then ModuleEvaluationError's.

func (*Realm) EvaluateModuleAsync

func (r *Realm) EvaluateModuleAsync(code *bytecode.Function) (*ModuleEnv, *Object, error)

EvaluateModuleAsync is EvaluateModule returning the promise of the evaluation of a module with top-level await (code.Async), as the job queue's drain left it, instead of its outcome. The promise is nil for any other module, which evaluates synchronously, and when an interrupt stops the evaluation before it starts, which leaves no environment either.

func (*Realm) ExitCall

func (r *Realm) ExitCall()

ExitCall releases a frame taken by EnterCall.

func (*Realm) FromGo

func (r *Realm) FromGo(v any) (Value, error)

FromGo converts a Go value to a JavaScript value. Scalars convert at once; a *big.Int becomes a bigint (a copy; nil is null). The JSON-shaped containers (map[string]any, map[string]string, map[string][]string, []any, []string, []map[string]any) convert lazily (hostlazy.go): the result is a placeholder that reads the Go value on its first touch and converts one level then, its children becoming placeholders in turn. Every observable result is the one eager conversion produced (maps get their keys sorted and share a Shape per key set, slices become dense arrays); the Go value is read later, node by node, and must not change while the result is in use. A []byte becomes an ArrayBuffer over its bytes (NewArrayBuffer: not a copy, so the bytes must not change while JavaScript may read them), and any other type is an error.

func (*Realm) FromPropertyDescriptor

func (r *Realm) FromPropertyDescriptor(d PropertyDescriptor) Value

FromPropertyDescriptor implements FromPropertyDescriptor for a complete descriptor ([[GetOwnProperty]] results) in one allocation.

func (*Realm) GetMethod

func (r *Realm) GetMethod(v Value, key PropertyKey) (Value, error)

GetMethod implements GetMethod.

func (*Realm) GetPrototypeFromConstructor

func (r *Realm) GetPrototypeFromConstructor(newTarget, ctor, intrinsicDefault *Object) (*Object, error)

GetPrototypeFromConstructor implements GetPrototypeFromConstructor (ECMA-262 §10.1.14) for the [[Construct]] of a builtin constructor ctor: the prototype of the object it creates is newTarget.prototype when that is an object, else intrinsicDefault (the realm's own intrinsic: moejs has no cross-realm functions). This is what makes builtins subclassable: `new Sub()` for `class Sub extends Array` reaches arrayConstruct with newTarget Sub. newTarget nil (a [[Call]]) or ctor itself returns intrinsicDefault without a property read, so constructing the builtin directly pays nothing (ctor.prototype is intrinsicDefault and cannot change).

func (*Realm) GetV

func (r *Realm) GetV(v Value, key PropertyKey) (Value, error)

GetV implements GetV: property lookup on any value, using the primitive's prototype without allocating a wrapper.

func (*Realm) GreaterThan

func (r *Realm) GreaterThan(x, y Value) (bool, error)

GreaterThan implements x > y.

func (*Realm) GreaterThanOrEqual

func (r *Realm) GreaterThanOrEqual(x, y Value) (bool, error)

GreaterThanOrEqual implements x >= y.

func (*Realm) HasOwn

func (r *Realm) HasOwn(o *Object, key PropertyKey) (bool, error)

HasOwn is HasOwnProperty(o, key): the getOwnPropertyDescriptor trap for a proxy, whose error is returned; Object.HasOwnProperty is false for one.

func (*Realm) HasPropertyIn

func (r *Realm) HasPropertyIn(key, target Value) (bool, error)

HasPropertyIn implements the `in` operator: key in target.

func (*Realm) HasSharedIntrinsics

func (r *Realm) HasSharedIntrinsics() bool

HasSharedIntrinsics reports whether the realm uses the shared frozen intrinsics.

func (*Realm) HoldJobs

func (r *Realm) HoldJobs()

HoldJobs defers the drain for a host that has bookkeeping to finish after a call and before the call's jobs run, as package moejs's Load recording the module's environment does: it counts one frame, so the calls until ReleaseJobs return without running jobs, as calls inside a call do. Take any CallState snapshot before HoldJobs.

func (*Realm) ICSlots

func (r *Realm) ICSlots() []ICEntry

ICSlots returns the realm's inline-cache table (owned by the interpreter).

func (*Realm) InstanceOf

func (r *Realm) InstanceOf(v, target Value) (bool, error)

InstanceOf implements InstanceofOperator. A lookup of @@hasInstance that finds the original Function.prototype[@@hasInstance] skips the call.

func (*Realm) Intern

func (r *Realm) Intern(s *String) *String

Intern returns the process-wide canonical *String for the content of s. Interned strings compare by pointer, which is what PropertyKey equality relies on.

func (*Realm) InternGoString

func (r *Realm) InternGoString(g string) *String

InternGoString interns a Go string.

func (*Realm) Interrupt

func (r *Realm) Interrupt(v any)

Interrupt requests that the running program stop. It is safe to call from any goroutine; the interpreter observes the flag at loop back-edges and function entry, natives through CheckInterrupt.

func (*Realm) Interrupted

func (r *Realm) Interrupted() bool

Interrupted reports whether an interrupt is pending (one atomic load).

func (*Realm) IsArray

func (r *Realm) IsArray(v Value) (bool, error)

IsArray is the spec's IsArray: true for an array and for a proxy whose target is one (followed through nested proxies without running a trap), an error for a revoked proxy on the way. The package-level IsArray sees only arrays.

func (*Realm) IsLessThan

func (r *Realm) IsLessThan(x, y Value, leftFirst bool) (int8, error)

IsLessThan implements IsLessThan(x, y, leftFirst).

func (*Realm) JSONParse

func (r *Realm) JSONParse(text *String) (Value, error)

JSONParse parses text with the JSON grammar and no reviver (Go-callable entry point). Errors are JavaScript SyntaxErrors.

func (*Realm) JSONStringify

func (r *Realm) JSONStringify(v Value) (*String, error)

JSONStringify serializes v with no replacer and no indentation (Go-callable entry point). The result is nil when v is not serializable (undefined, functions, symbols).

func (*Realm) KeyFromGoString

func (r *Realm) KeyFromGoString(g string) PropertyKey

KeyFromGoString converts a Go string to a PropertyKey.

func (*Realm) KeyFromString

func (r *Realm) KeyFromString(s *String) PropertyKey

KeyFromString converts a string to a PropertyKey: canonical array indices become index keys, everything else is interned.

func (*Realm) LengthOfArrayLike

func (r *Realm) LengthOfArrayLike(o *Object) (int64, error)

LengthOfArrayLike implements LengthOfArrayLike.

func (*Realm) LessThan

func (r *Realm) LessThan(x, y Value) (bool, error)

LessThan implements x < y.

func (*Realm) LessThanOrEqual

func (r *Realm) LessThanOrEqual(x, y Value) (bool, error)

LessThanOrEqual implements x <= y.

func (*Realm) LooseEquals

func (r *Realm) LooseEquals(a, b Value) (bool, error)

LooseEquals implements IsLooselyEqual (==).

func (*Realm) ModuleEvaluationError

func (r *Realm) ModuleEvaluationError(p *Object, err error) error

ModuleEvaluationError returns the error of the evaluation of a module with top-level await, whose promise EvaluateModuleAsync returned, once the jobs ran: the rejection reason as an *Exception, else err, the jobs' error (see ReleaseJobs), else ErrModulePending while p is pending. The rejection wins over err as a call's own exception does over its jobs', and an interrupt in err over the rejection, as over a call's exception.

func (*Realm) NewArray

func (r *Realm) NewArray(items ...Value) *Object

NewArray creates a dense array holding items (the slice is retained).

func (*Realm) NewArrayBuffer

func (r *Realm) NewArrayBuffer(data []byte) (*Object, error)

NewArrayBuffer returns a fixed-length ArrayBuffer over data, which it does not copy: JavaScript reads and writes data itself, so the host must not modify data while JavaScript may read it. Nothing is written past len(data): a transfer to a longer buffer moves the bytes. A nil data is an empty buffer; one longer than 2 GiB - 1 bytes is a RangeError.

func (*Realm) NewArrayCap

func (r *Realm) NewArrayCap(n int) *Object

NewArrayCap creates an empty array with room for n elements (an array literal about to be filled by ArrayPush). An empty literal gets room for four elements because it is almost always pushed to afterwards.

func (*Realm) NewArrayFromSlice

func (r *Realm) NewArrayFromSlice(items []Value) *Object

NewArrayFromSlice creates a dense array that takes ownership of items.

func (*Realm) NewArrayLen

func (r *Realm) NewArrayLen(n uint32) *Object

NewArrayLen creates an array of the given length filled with holes; dense storage is preallocated only for modest lengths.

func (*Realm) NewBoundFunction

func (r *Realm) NewBoundFunction(target *Object, boundThis Value, boundArgs []Value) (*Object, error)

NewBoundFunction implements BoundFunctionCreate plus the `length`/`name` steps of Function.prototype.bind, so the bind method is a thin wrapper.

func (*Realm) NewDate

func (r *Realm) NewDate(t time.Time) *Object

NewDate creates a Date object for t (Go-callable entry point).

func (*Realm) NewError

func (r *Realm) NewError(kind ErrorKind, format string, args ...any) *Object

NewError creates an Error instance of the given kind with a formatted message and a captured stack. fmt is used only when args are present.

func (*Realm) NewErrorValue

func (r *Realm) NewErrorValue(kind ErrorKind, message *String) Value

NewErrorValue creates an error of kind with a preformatted message.

func (*Realm) NewNativeConstructor

func (r *Realm) NewNativeConstructor(name *String, length int, call NativeFunc, ctor NativeCtor) *Object

NewNativeConstructor creates a builtin constructor with both [[Call]] and [[Construct]] behaviour. call may be nil, in which case calling without `new` throws a TypeError.

func (*Realm) NewNativeDataFunction

func (r *Realm) NewNativeDataFunction(name *String, length int, fn NativeDataFunc, data any) *Object

NewNativeDataFunction creates a function object whose [[Call]] is fn with data as its payload (FunctionData.Data): a host binding creates one per Go value while fn stays one package-level adapter per Go signature. Data natives are not constructors.

func (*Realm) NewNativeFunction

func (r *Realm) NewNativeFunction(name *String, length int, fn NativeFunc) *Object

NewNativeFunction creates a builtin function object. name should be an atom; length is the value of the `length` property.

func (*Realm) NewObject

func (r *Realm) NewObject() *Object

NewObject creates an ordinary object whose prototype is Object.prototype.

func (*Realm) NewObjectCap

func (r *Realm) NewObjectCap(n int) *Object

NewObjectCap creates an ordinary object with room for n named properties (an object literal about to be filled by DefineField). An empty literal gets room for four properties because it is almost always assigned to afterwards.

func (*Realm) NewObjectWithProto

func (r *Realm) NewObjectWithProto(proto *Object) *Object

NewObjectWithProto creates an ordinary object with the given prototype (nil for a null prototype), as Object.create does.

func (*Realm) NewPromiseWithResolvers

func (r *Realm) NewPromiseWithResolvers() (p, resolve, reject *Object)

NewPromiseWithResolvers creates a pending promise and its resolve and reject functions, as Promise.withResolvers does. Calling them through CallObject settles the promise and, from the outermost call, runs the jobs that queues.

func (*Realm) NewRegExp

func (r *Realm) NewRegExp(pattern, flags *String) (*Object, error)

NewRegExp implements RegExpCreate(pattern, flags) with %RegExp.prototype% (used by the interpreter for regular expression literals and by the host API). It returns a SyntaxError for invalid flags or patterns.

func (*Realm) NewStringObject

func (r *Realm) NewStringObject(s *String) *Object

NewStringObject creates a String exotic wrapper.

func (*Realm) OrdinaryCreateFromConstructor

func (r *Realm) OrdinaryCreateFromConstructor(newTarget *Object, defaultProto *Object, class Class) (*Object, error)

OrdinaryCreateFromConstructor creates an object whose prototype is newTarget.prototype when that is an object, else defaultProto.

func (*Realm) OrdinaryHasInstance

func (r *Realm) OrdinaryHasInstance(c, o Value) (bool, error)

OrdinaryHasInstance implements OrdinaryHasInstance(C, O).

func (*Realm) OrdinaryToPrimitive

func (r *Realm) OrdinaryToPrimitive(o *Object, hint Hint) (Value, error)

OrdinaryToPrimitive implements OrdinaryToPrimitive.

func (*Realm) OwnKeys

func (r *Realm) OwnKeys(o *Object) ([]PropertyKey, error)

OwnKeys is o.[[OwnPropertyKeys]](): for a proxy the ownKeys trap runs and its error is returned. The Object methods see a proxy as an empty object without running code.

func (*Realm) ProtoEpoch

func (r *Realm) ProtoEpoch() uint32

ProtoEpoch returns the realm's prototype validity counter.

func (*Realm) PrototypeOf

func (r *Realm) PrototypeOf(o *Object) (*Object, error)

PrototypeOf is o.[[GetPrototypeOf]]() (the getPrototypeOf trap for a proxy; Object.Proto reads nil for one).

func (*Realm) RangeError

func (r *Realm) RangeError(format string, args ...any) error

RangeError returns a thrown RangeError.

func (*Realm) ReferenceError

func (r *Realm) ReferenceError(format string, args ...any) error

ReferenceError returns a thrown ReferenceError.

func (*Realm) RegExpExec

func (r *Realm) RegExpExec(rx *Object, s *String) (Value, error)

RegExpExec runs RegExpBuiltinExec on rx with subject s and returns the result array or null (Go-callable entry point).

func (*Realm) ReleaseJobs

func (r *Realm) ReleaseJobs(err error) error

ReleaseJobs releases the frame of HoldJobs and, when that was the outermost one, ends the job as the return of CallObject does. err is the error of what ran held; ReleaseJobs returns it, or what the drain returns in its place (see the file comment).

func (*Realm) RestoreCallState

func (r *Realm) RestoreCallState(cs CallState)

RestoreCallState resets the call bookkeeping to a snapshot taken at the same host boundary.

func (*Realm) RunScript

func (r *Realm) RunScript(code *bytecode.Function) (Value, error)

RunScript runs a compiled strict-mode script and returns its completion value. Top-level bindings live in the script's own environment (mirroring them onto the global object is TODO).

func (*Realm) SetNow

func (r *Realm) SetNow(now func() time.Time)

SetNow sets the clock used by Date.now() and new Date(); nil restores time.Now. Hosts freeze or offset time with it.

func (*Realm) SetPromiseRejectionTracker

func (r *Realm) SetPromiseRejectionTracker(f func(p *Object, op PromiseRejectionOperation))

SetPromiseRejectionTracker registers f to be called when a promise is rejected with no handler (PromiseRejectionReject) and when a promise so rejected gets its first handler (PromiseRejectionHandle), synchronously, as HostPromiseRejectionTracker. A promise told Reject and not Handle when the outermost call returns has an unhandled rejection. nil removes the tracker.

func (*Realm) SetStackHooks

func (r *Realm) SetStackHooks(capture func(r *Realm) []StackFrame, format func(r *Realm, frames []StackFrame) string)

SetStackHooks installs the interpreter's stack capture and formatter. capture returns the current frames (it may return nil or a slice it does not retain); format renders them as " at fn (file:line:col)" lines without a trailing newline. Either may be nil. Installing a capture hook replaces the interpreter's buffer-reusing capture.

func (*Realm) SetTimeZone

func (r *Realm) SetTimeZone(loc *time.Location)

SetTimeZone sets the realm's local time zone for Date (the local getters and setters, toString, parsing of strings without an offset and the time.Time exported for a Date); nil restores time.Local.

func (*Realm) SetV

func (r *Realm) SetV(target Value, key PropertyKey, v Value) error

SetV implements strict-mode PutValue on any base value.

func (*Realm) StackTrace

func (r *Realm) StackTrace(v Value) string

StackTrace returns the `stack` of an Error object created by the engine when it is a string (the header and the captured frames, formatted on first use, or a string assigned to it), else "". It never runs user code.

func (*Realm) SyntaxError

func (r *Realm) SyntaxError(format string, args ...any) error

SyntaxError returns a thrown SyntaxError.

func (*Realm) Throw

func (r *Realm) Throw(v Value) error

Throw wraps a JavaScript value as an error.

func (*Realm) TimeZone

func (r *Realm) TimeZone() *time.Location

TimeZone returns the realm's local time zone.

func (*Realm) ToBigInt

func (r *Realm) ToBigInt(v Value) (*BigInt, error)

ToBigInt implements ToBigInt: a bigint is returned as is, booleans and strings convert, and undefined, null, numbers and symbols throw a TypeError. A string that is not an integer literal is a SyntaxError.

func (*Realm) ToBigInt64

func (r *Realm) ToBigInt64(v Value) (int64, error)

ToBigInt64 implements ToBigInt64: ToBigInt modulo 2^64, as a signed value.

func (*Realm) ToBigUint64

func (r *Realm) ToBigUint64(v Value) (uint64, error)

ToBigUint64 implements ToBigUint64: ToBigInt modulo 2^64.

func (*Realm) ToGo

func (r *Realm) ToGo(v Value) any

ToGo exports a JavaScript value to Go: integral numbers within int64 range become int64 (except -0, which stays float64 so the sign survives), other numbers float64; null and undefined become nil; arrays become []any; other objects become map[string]any of their own enumerable string keys; function objects are exported as the *Object itself; Number/String/Boolean/BigInt wrappers export their primitive; Date objects export time.Time in the realm's time zone (the zero time for an invalid date); bigint exports *big.Int; symbols export the *Symbol. An ArrayBuffer or SharedArrayBuffer exports a copy of its bytes as a []byte, and a typed array or DataView a copy of the bytes of its buffer it views (nil for a detached buffer or a view out of its buffer's bounds, non-nil and empty for a zero-length one). A proxy exports through its traps as what it stands for: a callable proxy like a function (the *Object), one whose target is an array as []any (length and elements read with the get trap), any other as the map of Object.keys through ownKeys, getOwnPropertyDescriptor and get; a revoked proxy is an error. Cycles yield the already-exported container (a proxy array only once complete). Getters and traps that throw yield nil; use ToGoStrict to observe the error.

func (*Realm) ToGoStrict

func (r *Realm) ToGoStrict(v Value) (any, error)

ToGoStrict is ToGo that stops at the first error raised while reading a property (a throwing getter, or an interrupt observed while one runs) and returns it instead of a partial result.

func (*Realm) ToIndex

func (r *Realm) ToIndex(v Value) (int64, error)

ToIndex implements ToIndex.

func (*Realm) ToInt32

func (r *Realm) ToInt32(v Value) (int32, error)

ToInt32 implements ToInt32.

func (*Realm) ToIntegerOrInfinity

func (r *Realm) ToIntegerOrInfinity(v Value) (float64, error)

ToIntegerOrInfinity implements ToIntegerOrInfinity.

func (*Realm) ToLength

func (r *Realm) ToLength(v Value) (int64, error)

ToLength implements ToLength.

func (*Realm) ToNumber

func (r *Realm) ToNumber(v Value) (float64, error)

ToNumber implements ToNumber.

func (*Realm) ToNumeric

func (r *Realm) ToNumeric(v Value) (Value, error)

ToNumeric implements ToNumeric: the result is a number or a bigint Value.

func (*Realm) ToObject

func (r *Realm) ToObject(v Value) (*Object, error)

ToObject implements ToObject.

func (*Realm) ToPrimitive

func (r *Realm) ToPrimitive(v Value, hint Hint) (Value, error)

ToPrimitive implements ToPrimitive, including the @@toPrimitive lookup.

func (*Realm) ToPropertyKey

func (r *Realm) ToPropertyKey(v Value) (PropertyKey, error)

ToPropertyKey implements the ToPropertyKey abstract operation.

func (*Realm) ToString

func (r *Realm) ToString(v Value) (*String, error)

ToString implements ToString.

func (*Realm) ToUint32

func (r *Realm) ToUint32(v Value) (uint32, error)

ToUint32 implements ToUint32.

func (*Realm) TypeError

func (r *Realm) TypeError(format string, args ...any) error

TypeError returns a thrown TypeError.

func (*Realm) URIError

func (r *Realm) URIError(format string, args ...any) error

URIError returns a thrown URIError.

type RealmOptions

type RealmOptions struct {
	// SharedIntrinsics selects the Hardened-JS model: every intrinsic object
	// (prototypes, constructors, namespaces, builtin functions) is built once
	// per process, deeply frozen and shared by all such realms. Per-realm
	// mutable state is only the global object, module environments, inline
	// caches, the dynamic intern cache and the interrupt flag.
	SharedIntrinsics bool

	// TimeZone is the local time zone of Date; nil means time.Local. It can
	// be changed later with Realm.SetTimeZone.
	TimeZone *time.Location
}

RealmOptions configures NewRealmWith.

type RegExpData

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

RegExpData is the internal payload of ClassRegExp objects.

func (*RegExpData) Flags

func (d *RegExpData) Flags() *String

Flags returns the flags in canonical order ([[OriginalFlags]]).

func (*RegExpData) Source

func (d *RegExpData) Source() *String

Source returns the pattern text ([[OriginalSource]]).

type Shape

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

Shape is an immutable node of a realm's transition tree. A shape encodes the object's [[Prototype]] (through its root) and the ordered list of named properties with their attributes; the slot of a property is its index in the chain, so slot == position in Object.slots.

func (*Shape) Count

func (s *Shape) Count() int

Count returns the number of named properties.

func (*Shape) IsDictionary

func (s *Shape) IsDictionary() bool

IsDictionary reports whether s is the dictionary sentinel.

func (*Shape) IsShared

func (s *Shape) IsShared() bool

IsShared reports whether the shape belongs to the shared intrinsics.

func (*Shape) Lookup

func (s *Shape) Lookup(key PropertyKey) (slot uint32, attrs uint8, ok bool)

Lookup finds key in the shape and returns its slot and attributes.

func (*Shape) Props

func (s *Shape) Props() []shapeProp

Props returns the properties in insertion (slot) order. The slice is owned by the shape and must not be modified.

func (*Shape) Proto

func (s *Shape) Proto() *Object

Proto returns the [[Prototype]] encoded by the shape.

type StackFrame

type StackFrame struct {
	Fn    *Object
	Recv  *Object
	PC    uint32
	Flags uint32
}

StackFrame is one compact stack entry captured when an error object is created: the running function (bytecode, or a native called from the frame below it; nil when unknown) and, for bytecode, the pc of its current instruction. Recv and Flags describe how the function was called (see interp_stack.go). Formatting into text happens lazily on the first read of `stack`.

func (StackFrame) Code

func (f StackFrame) Code() *bytecode.Function

Code returns the compiled function of a bytecode frame, or nil.

type String

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

String is an immutable JavaScript string (a UTF-16 code unit sequence). Strings are shared freely; the only mutation is the one-time in-place flattening of a rope and the caching of hash/atom, both of which preserve the logical value.

func EmptyString

func EmptyString() *String

EmptyString returns the shared empty string.

func FromGoString

func FromGoString(s string) *String

FromGoString converts a Go (UTF-8) string. ASCII input is zero-copy; anything else is decoded to UTF-16 once, with invalid UTF-8 bytes becoming U+FFFD (Go's range semantics).

func FromUTF16

func FromUTF16(u []uint16) *String

FromUTF16 builds a string from code units. The slice is retained when the content is not ASCII, so callers must not modify it afterwards.

func LookupStaticAtom

func LookupStaticAtom(name string) (*String, bool)

LookupStaticAtom returns the static atom for an ASCII name, if any.

func NumberToString

func NumberToString(f float64) *String

NumberToString implements Number::toString(10).

func TrimJSWhitespace

func TrimJSWhitespace(s *String) *String

TrimJSWhitespace returns s without leading/trailing JS whitespace.

func TypeOf

func TypeOf(v Value) *String

TypeOf implements the typeof operator, returning an atom.

func (*String) ASCII

func (s *String) ASCII() (string, bool)

ASCII returns the underlying Go string and true when the string is ASCII.

func (*String) At

func (s *String) At(i int) uint16

At returns the code unit at index i (0 <= i < Len).

func (*String) Compare

func (s *String) Compare(t *String) int

Compare orders by code units: -1, 0 or 1.

func (*String) Equals

func (s *String) Equals(t *String) bool

Equals reports code-unit equality.

func (*String) EqualsGoString

func (s *String) EqualsGoString(g string) bool

EqualsGoString compares against an ASCII/UTF-8 Go string.

func (*String) GoString

func (s *String) GoString() string

GoString exports to a Go string. ASCII is zero-copy; UTF-16 is encoded to UTF-8 with lone surrogates replaced by U+FFFD.

func (*String) Hash

func (s *String) Hash() uint32

Hash returns the cached content hash (never 0).

func (*String) IndexOf

func (s *String) IndexOf(sub *String, from int) int

IndexOf returns the first index >= from at which sub occurs, or -1.

func (*String) IsASCII

func (s *String) IsASCII() bool

IsASCII reports whether the string (after flattening) is ASCII-only.

func (*String) IsInterned

func (s *String) IsInterned() bool

IsInterned reports whether s is an atom.

func (*String) IsWellFormed

func (s *String) IsWellFormed() bool

IsWellFormed reports whether the string has no lone surrogates.

func (*String) Len

func (s *String) Len() int

Len returns the length in UTF-16 code units.

func (*String) String

func (s *String) String() string

String implements fmt.Stringer for debugging.

func (*String) Substring

func (s *String) Substring(start, end int) *String

Substring returns the code units in [start, end). Bounds must be valid.

func (*String) UTF16

func (s *String) UTF16() []uint16

UTF16 returns the code units. For ASCII strings a fresh slice is built; for UTF-16 strings the internal slice is returned and must not be modified.

type StringBuilder

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

StringBuilder accumulates code units and produces a *String. It stores ASCII bytes until the first unit >= 0x80 is written, then upgrades to UTF-16 storage once.

The first smallASCIIMax ASCII bytes are written into an array inside the builder itself, addressed by index and never through a slice, so a builder declared as a local variable stays on the stack (nothing points into it), builds a short result without touching the heap, and String then hands out one co-allocated string. Longer results spill into a heap slice that the result aliases, as before.

func (*StringBuilder) Grow

func (sb *StringBuilder) Grow(n int)

Grow reserves capacity for n more code units.

func (*StringBuilder) Len

func (sb *StringBuilder) Len() int

Len returns the number of code units written so far. Only one of the three stores holds them (spill and upgrade empty the one they leave), so the sum is the length of that one, without branches.

func (*StringBuilder) Reset

func (sb *StringBuilder) Reset()

Reset clears the builder for reuse, keeping no reference to the old buffer.

func (*StringBuilder) String

func (sb *StringBuilder) String() *String

String finishes the builder and returns the result. The builder must not be reused without Reset.

func (*StringBuilder) WriteASCII

func (sb *StringBuilder) WriteASCII(c byte)

WriteASCII appends one byte that must be < 0x80.

func (*StringBuilder) WriteGoString

func (sb *StringBuilder) WriteGoString(s string)

WriteGoString appends a UTF-8 Go string.

func (*StringBuilder) WriteRune

func (sb *StringBuilder) WriteRune(r rune)

WriteRune appends a code point, encoding surrogate pairs as needed.

func (*StringBuilder) WriteString

func (sb *StringBuilder) WriteString(s *String)

WriteString appends a JavaScript string.

func (*StringBuilder) WriteUTF16

func (sb *StringBuilder) WriteUTF16(u []uint16)

WriteUTF16 appends raw code units.

func (*StringBuilder) WriteUnit

func (sb *StringBuilder) WriteUnit(c uint16)

WriteUnit appends one UTF-16 code unit.

type Symbol

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

Symbol is a JavaScript symbol. Symbols are immutable after creation, so a symbol value may be shared by any number of realms and goroutines.

func NewSymbol

func NewSymbol(description *String) *Symbol

NewSymbol creates a fresh symbol with the given description (may be nil).

func (*Symbol) Description

func (s *Symbol) Description() *String

Description returns the description or nil.

type Type

type Type uint8

Type is the coarse JavaScript type of a Value, for switch dispatch.

const (
	TypeUndefined Type = iota
	TypeNull
	TypeBoolean
	TypeNumber
	TypeString
	TypeSymbol
	TypeBigInt
	TypeObject
	// TypeHole is the internal hole marker; it never reaches user code.
	TypeHole
)

type Value

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

Value is the engine's universal JavaScript value. Numbers, booleans, undefined, null and the internal hole marker are stored inline (ptr == nil); strings, objects, symbols and bigints are pointers with a type tag in bits. The zero Value is the number +0.

func Arg

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

Arg returns args[i] or undefined when i is out of range.

func BigIntValue

func BigIntValue(b *BigInt) Value

BigIntValue boxes a BigInt. b must not be nil.

func Bool

func Bool(b bool) Value

Bool boxes a boolean.

func False

func False() Value

False returns the boolean false.

func Hole

func Hole() Value

Hole returns the internal array-hole / uninitialized-binding marker. It must never be observable from JavaScript.

func Int64Value

func Int64Value(i int64) Value

Int64Value boxes an int64 as a JavaScript number (may lose precision above 2^53).

func IntValue

func IntValue(i int) Value

IntValue boxes an integer as a JavaScript number.

func NaN

func NaN() Value

NaN returns the canonical NaN number.

func Null

func Null() Value

Null returns the null value.

func NumberValue

func NumberValue(f float64) Value

NumberValue boxes a float64, canonicalizing NaN.

func ObjectValue

func ObjectValue(o *Object) Value

ObjectValue boxes an object. o must not be nil.

func StringValue

func StringValue(s *String) Value

StringValue boxes a string. s must not be nil.

func SymbolValue

func SymbolValue(s *Symbol) Value

SymbolValue boxes a symbol. s must not be nil.

func True

func True() Value

True returns the boolean true.

func Uint32Value

func Uint32Value(i uint32) Value

Uint32Value boxes a uint32 as a JavaScript number.

func Undefined

func Undefined() Value

Undefined returns the undefined value.

func (Value) AsBigInt

func (v Value) AsBigInt() *BigInt

AsBigInt returns the *BigInt payload. Only valid when IsBigInt.

func (Value) AsBool

func (v Value) AsBool() bool

AsBool returns the boolean payload. Only valid when IsBool.

func (Value) AsNumber

func (v Value) AsNumber() float64

AsNumber returns the float64 payload. Only valid when IsNumber.

func (Value) AsObject

func (v Value) AsObject() *Object

AsObject returns the *Object payload. Only valid when IsObject.

func (Value) AsString

func (v Value) AsString() *String

AsString returns the *String payload. Only valid when IsString.

func (Value) AsSymbol

func (v Value) AsSymbol() *Symbol

AsSymbol returns the *Symbol payload. Only valid when IsSymbol.

func (Value) Bits

func (v Value) Bits() uint64

Bits exposes the raw payload for hashing and debugging.

func (Value) IsArrayIndex

func (v Value) IsArrayIndex() (uint32, bool)

IsArrayIndex reports whether v is a number that is a canonical array index (an integer in [0, 2^32-2]).

func (Value) IsBigInt

func (v Value) IsBigInt() bool

IsBigInt reports whether v is a bigint.

func (Value) IsBool

func (v Value) IsBool() bool

IsBool reports whether v is a boolean.

func (Value) IsFalse

func (v Value) IsFalse() bool

IsFalse reports whether v is the boolean false.

func (Value) IsHole

func (v Value) IsHole() bool

IsHole reports whether v is the internal hole marker.

func (Value) IsInt32

func (v Value) IsInt32() (int32, bool)

IsInt32 reports whether v is a number that is exactly representable as an int32 (excluding -0), and returns that integer.

func (Value) IsNull

func (v Value) IsNull() bool

IsNull reports whether v is null.

func (Value) IsNullish

func (v Value) IsNullish() bool

IsNullish reports whether v is undefined or null.

func (Value) IsNumber

func (v Value) IsNumber() bool

IsNumber reports whether v is a JavaScript number.

func (Value) IsObject

func (v Value) IsObject() bool

IsObject reports whether v is an object.

func (Value) IsPrimitive

func (v Value) IsPrimitive() bool

IsPrimitive reports whether v is not an object (hole included).

func (Value) IsString

func (v Value) IsString() bool

IsString reports whether v is a string.

func (Value) IsSymbol

func (v Value) IsSymbol() bool

IsSymbol reports whether v is a symbol.

func (Value) IsTrue

func (v Value) IsTrue() bool

IsTrue reports whether v is the boolean true.

func (Value) IsUndefined

func (v Value) IsUndefined() bool

IsUndefined reports whether v is undefined.

func (Value) String

func (v Value) String() string

String returns a debugging representation. It never throws and never invokes user code; use Realm.ToString for JavaScript semantics. A BigInt of more than 6400 bits reads "<a very large BigInt>" (see bigintDisplayBits).

func (Value) Type

func (v Value) Type() Type

Type returns the coarse type of v.

Source Files

Jump to

Keyboard shortcuts

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