engine

package
v0.1.0-alpha.6 Latest Latest
Warning

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

Go to latest
Published: Oct 8, 2026 License: Apache-2.0 Imports: 32 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 DefaultMaxDynamicSource = 1 << 20

DefaultMaxDynamicSource is the length of the longest source text a realm compiles at run time unless RealmOptions.MaxDynamicSource says otherwise: 1 MiB.

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")
	AtomEval                      = staticAtom("eval")
	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")
	AtomCompile                   = staticAtom("compile")
)
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 ErrForeign = errors.New("moejs: function or generator of another runtime")

ErrForeign is FromGo's error for a function or generator of another realm (IsForeign), a Value or an *Object, which runs only in its own realm; the root package returns it as moejs.ErrForeign.

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 ErrMemoryLimit = errors.New("memory limit exceeded")

ErrMemoryLimit is the error a *MemoryLimitError unwraps to, so that errors.Is finds it through the *InterruptedError a hit stops the realm with.

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 Construct on bytecode functions until the interpreter sets constructFunction in its init().

View Source
var ErrNoResolver = errors.New("no resolver: the host must resolve the module's requests")

ErrNoResolver is the Err of the LinkError of a module that requests another when LinkOptions.Resolve is nil.

View Source
var ErrTooLarge = errors.New("moejs: decoded value too large")

ErrTooLarge is the error, wrapped with the limit it passed, of a decode whose JSON text passes one of its DecodeOptions limits; a value nested deeper than 10,000 arrays and objects, a cycle included, passes them all.

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 MeasureDecodeGo

func MeasureDecodeGo(g any, opts DecodeOptions) error

MeasureDecodeGo checks json.Marshal's text of g, a value ToGo returned, against opts, without writing it: a NaN or an infinity, which json.Marshal fails on, counts as null, and a value json.Marshal cannot write counts as null too.

func MeasureDecodeText

func MeasureDecodeText(text []byte, opts DecodeOptions) error

MeasureDecodeText checks text, a JSON text written by AppendJSON or json.Marshal, against opts: its length and the values in it.

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 SetCompiler

func SetCompiler(c Compiler)

SetCompiler installs the process-wide compiler behind eval, the Function constructors and Realm.EvalScript. The root package installs one when it is initialized; a host that uses the engine on its own may install the same (compiler.Hook) or none.

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 Compiler

type Compiler interface {
	// CompileScript compiles a classic script (sloppy unless it says "use
	// strict") into a bytecode.KindScript template for Realm.RunScript.
	CompileScript(name, src string, stop func() error) (*bytecode.Function, error)
	// CompileEval compiles eval code into a bytecode.KindArrow template
	// whose call returns the completion value. scope describes the
	// environment of a direct eval call site (the EvalScope of its CallEval
	// instruction); nil compiles an indirect eval, which runs as global
	// code. Var and function declarations of sloppy eval code that land in
	// the global variable environment are listed in Extra.Globals.
	CompileEval(name, src string, scope *bytecode.EvalScope, stop func() error) (*bytecode.Function, error)
	// CompileFunction compiles the function CreateDynamicFunction builds
	// from params and body: the result is a bytecode.KindScript template
	// that declares nothing and returns the new function object. The
	// parameters and the body are checked to parse on their own.
	CompileFunction(name, params, body string, generator, async bool, stop func() error) (*bytecode.Function, error)
}

Compiler compiles source text for the engine. Its methods may run on any goroutine; the templates they return are immutable and shared like any other. The engine passes each a stop function that returns the *InterruptedError of an interrupt pending in the realm, and nil otherwise: a compiler calls it now and then, so that an interrupt stops a long compile too, and returns its error as is.

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 DecodeOptions

type DecodeOptions struct {
	// MaxBytes bounds the length in bytes of the decode's JSON text:
	// AppendJSON's text of the value for Unmarshal, json.Marshal's text of
	// ToGo's value for ToGoInto and ToGo.
	MaxBytes int
	// MaxNodes bounds the number of values in that text: each object,
	// array, string, number, true, false and null counts one; keys and
	// members AppendJSON leaves out do not count.
	MaxNodes int
}

DecodeOptions bounds a decode of a JavaScript value into Go: a field that is zero (or negative) sets no limit.

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 ImportHooks

type ImportHooks struct {
	// Load returns the module specifier names for referrer
	// (HostLoadImportedModule): the host value of the importing script or
	// module (SetHostDefined, LinkOptions.HostDefined), nil when it has
	// none. It runs within import(), and its error rejects import()'s
	// promise: an *Exception with its value, an *InterruptedError stops
	// the running code, any other error rejects with an Error (as a native
	// function's error throws). Returning no module rejects with a
	// TypeError.
	Load func(r *Realm, referrer any, specifier string) (module any, err error)
	// Link returns the linked graph (LinkModules) whose entry is the module
	// Load returned. It runs from a job; its error rejects as Load's does.
	// The realm evaluates the graph as EvaluateGraph does, so a host that
	// links a module once per process and returns the same graph pays
	// only for the instantiation and the evaluation in each realm.
	Link func(r *Realm, module any) (*ModuleGraph, error)
	// Meta, when set, fills the import.meta object of module, the host
	// value of the module (LinkOptions.HostDefined), when import.meta is
	// first evaluated in the module in the realm
	// (HostGetImportMetaProperties and HostFinalizeImportMeta). The object
	// has a null prototype and no properties. Its error is thrown by the
	// import.meta expression, and the next one calls Meta again.
	Meta func(r *Realm, module any, meta *Object) error
}

ImportHooks are the host's hooks for import() and import.meta (SetImportHooks). They may be shared by any number of realms.

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.

func (*InterruptedError) Unwrap

func (e *InterruptedError) Unwrap() error

Unwrap returns Value when it is an error, so that errors.Is and errors.As see what Interrupt was called with: a host that interrupts with context.Cause(ctx) finds context.DeadlineExceeded or its own cause through the *InterruptedError. It returns nil for any other Value.

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 LinkError

type LinkError struct {
	Module    *bytecode.Function
	Line, Col int
	Specifier string
	Err       error
	Msg       string
}

LinkError is an error of LinkModules at the request, import or export entry of Module that caused it (Line and Col are 1-based, the column in code points). Err is the error of resolving Specifier; when it is nil, Msg is the SyntaxError message of an import or indirect export that does not resolve. EvaluateGraph returns one too, with Err set, for a request of a module the realm instantiated that the graph resolves to another module.

func (*LinkError) Error

func (e *LinkError) Error() string

func (*LinkError) Unwrap

func (e *LinkError) Unwrap() error

type LinkOptions

type LinkOptions struct {
	// Resolve returns the module that entry request of referrer's
	// Links.Requests names (HostLoadImportedModule). It is called once per
	// module and request of a graph. The template is the module's identity:
	// the same template is one module, of this graph and of every other
	// graph a realm evaluates, so Resolve must answer the same referrer and
	// request with the same template every time.
	Resolve func(referrer *bytecode.Function, request int) (*bytecode.Function, error)
	// EarlyExports, when set, returns the variant of an import-free module
	// compiled with its exported functions assumed to run before its body
	// (syntax.Options.EarlyExports). LinkModules asks for it when the
	// evaluation order lets another module call them that early, which only
	// an import cycle that reaches the module after one of its members ran
	// can do; without it, such a call can read the module's uninitialized
	// lexical bindings without the ReferenceError.
	EarlyExports func(code *bytecode.Function) (*bytecode.Function, error)
	// HostDefined, when set, returns the host value of a module whose code
	// uses import() or import.meta, or holds a direct eval call
	// (bytecode.Function.ScriptOrModule): the referrer import() in its code
	// and in its eval code passes ImportHooks.Load, and the module
	// ImportHooks.Meta fills the import.meta of. It is called once per such
	// module of the graph; a realm records the value of the graph that
	// first instantiates the module.
	HostDefined func(code *bytecode.Function) any
}

LinkOptions are the host hooks of LinkModules.

type MemoryLimitError

type MemoryLimitError struct {
	// Limit is the limit that was passed, in bytes.
	Limit int64
	// Allocated is what was charged since the last reset, the allocation
	// that passed the limit included.
	Allocated int64
	// Live is the retained size the last measurement of the realm's heap
	// found, which the limit counts with Allocated; 0 while none was made.
	Live int64
	// Stack is the JavaScript stack at the allocation, the "    at ..."
	// lines of an Error's stack; "" when no JavaScript ran.
	Stack string
}

MemoryLimitError is the value a realm interrupts itself with when what it allocated since the last reset passes its memory limit.

func (*MemoryLimitError) Error

func (e *MemoryLimitError) Error() string

Error implements error.

func (*MemoryLimitError) Unwrap

func (e *MemoryLimitError) Unwrap() error

Unwrap returns ErrMemoryLimit.

type ModuleBinding

type ModuleBinding struct {
	Module int32
	Slot   int32
}

ModuleBinding locates a binding of a linked graph: the Env slot Slot of the graph's module Module, or that module's namespace when Slot is -1.

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, module *bytecode.Module) *ModuleEnv

NewModuleEnv creates a module environment with nslots bindings and the local exports of module.

func (*ModuleEnv) ExportNames

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

ExportNames returns the names of the local exports, sorted.

func (*ModuleEnv) GetBindingValue

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

GetBindingValue returns the current value of a local export (the module's own binding, not one re-exported from another module). ok is false for unknown names. A Hole() value means the binding is in its TDZ.

type ModuleGraph

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

ModuleGraph is a linked module graph: the entry (module 0) and every module it requests, directly or not, each once.

func LinkModules

func LinkModules(entry *bytecode.Function, opts LinkOptions) (*ModuleGraph, error)

LinkModules loads the graph of entry, asking opts.Resolve for the module of each request, and links it (InnerModuleLinking, less the per-realm InitializeEnvironment of EvaluateGraph): every import and indirect export must resolve to one binding. The graph is immutable; any number of realms may evaluate it, concurrently.

func (*ModuleGraph) Binding

func (g *ModuleGraph) Binding(name string) (ModuleBinding, bool)

Binding returns what the entry's export name resolves to.

func (*ModuleGraph) Exports

func (g *ModuleGraph) Exports() []string

Exports returns the names of the entry's namespace, sorted by strings.Compare: its exports, re-exported ones included, without the names its star exports leave ambiguous.

func (*ModuleGraph) Records

func (g *ModuleGraph) Records() []*bytecode.Function

Records returns the templates of the graph's modules, the entry first, as the host resolved them.

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) HoldsCode

func (o *Object) HoldsCode() bool

HoldsCode reports whether o is a function, generator, async generator or proxy: the objects IsForeign can report, so that a host checks its arguments without a call for the rest.

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), and for a json.RawMessage JavaScript has not read a new RawMessage with its text; 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) IsModuleNamespace

func (o *Object) IsModuleNamespace() bool

IsModuleNamespace reports whether o is a module namespace object.

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). A shared intrinsic as the receiver rejects every assignment before any setter runs.

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. ok is also false when the elements are not aligned for their type, which only a buffer over host bytes (NewArrayBuffer) that do not start at a word boundary can give: the data the engine allocates always is aligned (newBytes), and a view's offset is a multiple of its element size.

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) AppendJSON

func (r *Realm) AppendJSON(dst []byte, v Value) ([]byte, bool, error)

AppendJSON appends JSONStringify(v) to dst as UTF-8 and reports whether v has a JSON representation; dst comes back unchanged when it has none or on an error. The output is written into dst's spare capacity, grown once to the last output's length plus an eighth (jsonSizeHint; after one very large output, a small dst is grown that much again), so a result that fits costs no copy; it never goes through UTF-16. Its limit is maxStringLength counted in bytes, which UTF-8 of text that is not ASCII reaches before JSONStringify's units do. Before any JavaScript runs (a toJSON, a getter, a proxy's trap) the output moves to a buffer of its own (own), so a host function that code calls may use dst: it is appended to when AppendJSON returns, as append(dst, text...) would.

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) CanToGoIntoDirect

func (r *Realm) CanToGoIntoDirect(v Value) bool

CanToGoIntoDirect is CanUnmarshalDirect for ToGoInto: ToGo reads v without running JavaScript and json.Marshal does not fail on what it gives.

func (*Realm) CanUnmarshalDirect

func (r *Realm) CanUnmarshalDirect(v Value) bool

CanUnmarshalDirect reports whether all of v is plain, as Unmarshal checks it before writing: AppendJSON writes its text without running JavaScript or failing, and Unmarshal stores it without the text when the target's type allows. It writes nothing and copies no host value; a pending interrupt makes it false.

func (*Realm) ChargeMemory

func (r *Realm) ChargeMemory(n int) error

ChargeMemory charges n bytes a host function allocates for JavaScript, such as a buffer it hands to NewArrayBuffer, to the realm's memory limit (none: a no-op). It returns the *InterruptedError of a pending interrupt, which the charge raises when it passes the limit, so that the host function can return it before it allocates.

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) 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 drops the payload's value.

func (*Realm) Concat

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

Concat returns a + b. A short result is a flat copy; a long one appends b to a in an append buffer (appendString) when b is the shorter and a is flat, and is a rope otherwise: a prepend, a join of two big pieces, or an append to a rope (wrapping `s = "(" + s + ")"` stays constant time a step). 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) DropJobs

func (r *Realm) DropJobs(err error)

DropJobs discards the queued jobs after a Go panic out of a call, which skipped the drain at the call's end (or the rest of it, for a panic out of a job): a host that recovers the panic at its outermost boundary calls it after RestoreCallState, so that the call's jobs do not run at the end of the next one. The modules in asynchronous evaluation those jobs would have continued fail with err. A no-op inside a call, where the jobs are the outermost call's. It also clears what a JSON.parse the panic stopped left on the realm's kept stack (jsonStack).

func (*Realm) DynamicCodeDisabled

func (r *Realm) DynamicCodeDisabled() bool

DynamicCodeDisabled reports whether the realm refuses to compile code at run time (RealmOptions.DisableDynamicCode).

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) EvalScript

func (r *Realm) EvalScript(name, src string) (Value, error)

EvalScript compiles src as a classic script named name with the installed compiler and runs it (RunScript). A compile error is a thrown SyntaxError, a missing compiler or DisableDynamicCode a thrown EvalError, and a src of more bytes than MaxDynamicSource a thrown RangeError; an interrupt stops the compile. The script is dynamic code (dynamic.go): the realm keeps nothing for it once the program no longer runs its functions.

func (*Realm) EvaluateGraph

func (r *Realm) EvaluateGraph(g *ModuleGraph) (*ModuleEnv, *Object, error)

EvaluateGraph evaluates the linked graph g in r: it instantiates the modules r has not instantiated yet, as ordered by g, and evaluates the entry (Evaluate), which runs the bodies of the modules it depends on that have not run. It returns the entry's environment, whose slots back its local exports (GraphBinding reads the others), and the promise of the evaluation when it is asynchronous (top-level await in the graph), which the job queue's drain before an outermost EvaluateGraph returns may have settled. The promise is already rejected when the entry's own top level threw before it first awaited. The error is that of a synchronous evaluation, which r caches for every module it failed: a later evaluation of one of them returns it again. An interrupt is cached that way too in each module whose evaluation it stops after an await, by stopping the module's top level resumed from a job or dropping the job that would resume it, or run it once the modules it waits on evaluated, and in each module waiting on one; the promise of such an evaluation stays pending. The environment is nil when an interrupt pending on entry stopped the evaluation before any module was instantiated.

The first graph that instantiates a module in r decides the modules it imports; the host's resolution must not change between the graphs a realm evaluates. A later graph that resolves a request of a module r instantiated to another module fails, before it instantiates any, with a *LinkError at the request, which an import() of the graph rejects with as an Error. A later graph that needs the EarlyExports variant of a module (see LinkOptions.EarlyExports) that r instantiated plain and has not run yet instantiates the variant in its place; a module whose top level ran, or started, keeps its template. A function of the plain template that the host read through GraphBinding before is not the module's any more then and must not be called.

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). A json.RawMessage converts as JSONParse of a copy of its text, the text of an object or an array on its first touch (hostraw.go). A named type whose underlying type is one of these converts as that type (a named map or slice lazily), and any other type encoding/json writes (a struct, a pointer, a map or slice of other element types, a type with a MarshalJSON or MarshalText method) converts from its json.Marshal text, parsed by JSONParse: a snapshot of the value (hostconv_types.go). A channel, a function that is not a NativeFunc, a complex number, an unsafe.Pointer, and without a MarshalJSON or MarshalText method an error and a struct none of whose fields json.Marshal writes, are an error, and so is a value json.Marshal fails on. A Value or *Object that is a function or generator of another realm is ErrForeign, and so is one inside a container: there the read of its member throws a TypeError with ErrForeign's text, as for a member of a type FromGo does not convert.

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) GraphBinding

func (r *Realm) GraphBinding(g *ModuleGraph, b ModuleBinding) (Value, bool)

GraphBinding reads the binding b of g in r, which evaluated g: the value of an export, re-exported ones included (see ModuleGraph.Binding), or a module's namespace, which it creates on first use. It is false when r has not instantiated the module or the binding is not initialized.

func (*Realm) GraphRan

func (r *Realm) GraphRan(g *ModuleGraph) bool

GraphRan reports whether the top level of g's entry, which r evaluated, ran to its end or its first await. A failure of the evaluation reported after that came from the entry's top level after its first await; one reported before came from it before, or from a module it imports, and left it unevaluated.

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) ImportHooks

func (r *Realm) ImportHooks() *ImportHooks

ImportHooks returns the realm's import hooks, or nil.

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) IsForeign

func (r *Realm) IsForeign(v Value) bool

IsForeign reports whether v is a function, generator or async generator whose code runs in another realm than r: a bytecode function another realm created, or the generator of a call to one, reached directly or through bound functions and proxy targets, or a callable proxy another realm created, whose traps are that realm's code whatever its target. That code's inline caches are bound in its own realm's table and its prototype checks follow that realm's epoch, so calling or resuming it from r gives wrong results or a Go panic; a host keeps the objects of a realm inside it (engine-api.md, "One realm per value"). Dynamic code (eval, the Function constructors) binds its caches in the calling realm and is not foreign. A revoked proxy of r has no target and runs no code (using it is a TypeError), so it is not foreign. IsForeign does not see a foreign function reached through an object of another realm, the traps of a proxy that is not callable among them.

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, except that nesting deeper than MaxToGoDepth arrays and objects is a RangeError.

func (*Realm) JSONParseGoString

func (r *Realm) JSONParseGoString(text string) (Value, error)

JSONParseGoString is JSONParse of the UTF-8 text, whose invalid bytes read as U+FFFD as FromGoString reads them. ASCII and valid UTF-8 text is parsed in place, never through UTF-16; the strings of the result may alias text.

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). Nesting deeper than MaxToGoDepth arrays and objects is a RangeError, as is running out of call depth: each 32 levels count as a call, since a toJSON method can start another stringify.

func (*Realm) JobsPending

func (r *Realm) JobsPending() bool

JobsPending reports whether jobs are queued for the end of the outermost call (or of the hold of HoldJobs): what a call or a conversion that ran code left to run, nothing when no code ran. The root AppendJSON asks it before it lets its output into dst (its jobs may use dst). It sits here, after (*String).flatten and out of line, for layout (realm_calldata.go): a symbol of one 32-byte slot in every binary, which with Unmarshal's growth keeps (*Runtime).Call on its 64-byte phase.

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) MaxDynamicSource

func (r *Realm) MaxDynamicSource() int

MaxDynamicSource returns the length of the longest source text the realm compiles at run time (RealmOptions.MaxDynamicSource), negative for no limit.

func (*Realm) MeasureToGo

func (r *Realm) MeasureToGo(v Value, opts DecodeOptions) (measured bool, err error)

MeasureToGo checks json.Marshal's text of what ToGo gives for v, the text of a decode by ToGoInto or ToGo, against opts before the decode, as MeasureUnmarshal does; it observes no interrupt, as ToGo observes none for such a value, and when measured is false and err is nil the host checks ToGo's value (MeasureDecodeGo).

func (*Realm) MeasureUnmarshal

func (r *Realm) MeasureUnmarshal(v Value, opts DecodeOptions) (measured bool, err error)

MeasureUnmarshal checks AppendJSON's text of v, the text of a decode by Unmarshal, against opts before the decode. err wraps ErrTooLarge when the text passes a limit, or is an interrupt, observed every 4096 values as AppendJSON observes it. measured reports whether the whole text was counted, within the limits; when it is false and err is nil, part of v can only be read by running JavaScript, and the host checks the text once it is written (MeasureDecodeText). No JavaScript runs, and nothing is written; a json.RawMessage FromGo converted and JavaScript did not read is parsed to be counted, unless a lower bound of its text, from one scan, already passes a limit.

func (*Realm) MemoryLimit

func (r *Realm) MemoryLimit() int64

MemoryLimit returns the realm's memory limit, 0 for none.

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) ReleaseCallData

func (r *Realm) ReleaseCallData()

ReleaseCallData drops the realm's references to the host values of finished calls, so a pooled realm does not keep the last request alive: the host conversion's chunks, whose placeholders hold the Go maps, slices and strings of the arguments (hostHeap); the registers and frame records the finished calls left above the live ones; the RegExp working copies of their subjects; and the last match, which the legacy RegExp statics (RegExp.$1, RegExp.input and the rest) describe: they read "" again, as in a new realm. Values already returned stay valid: their nodes keep their own storage. It also starts a new memory budget (ResetAllocation).

It ends the host conversion's period, which otherwise ends at the next top-level FromGo, so a host calls it where a request ends, after the request's last use of the realm (CallObject, ToGo, GetV, JSONStringify: each can run JavaScript): a request that runs several hooks on one realm is one period, whose usage sizes the next request's chunks. Calls do not do it themselves: clearing the register stack after each would tax every call, hosts that do not pool included, and split a request into periods.

Between calls only; a no-op inside one (from a native function).

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) ResetAllocation

func (r *Realm) ResetAllocation()

ResetAllocation starts a new budget: the bytes charged since the last reset go back to zero, and the last hit's error is forgotten. A pending interrupt, the hit's included, stays pending (ClearInterrupt). ReleaseCallData resets too; a host that does not pool calls this where a request starts. It may be called from a host function, which gives the running script a new budget.

func (*Realm) RestoreCallState

func (r *Realm) RestoreCallState(cs CallState)

RestoreCallState resets the call bookkeeping to a snapshot taken at the same host boundary. At the outermost boundary, DropJobs then discards the jobs the call left queued.

func (*Realm) RunScript

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

RunScript runs a compiled script and returns its completion value. GlobalDeclarationInstantiation runs first (sloppy.go): its var and function declarations become properties of the global object and its let, const and class declarations bindings of the realm's global declarative environment, which later scripts and modules resolve names against too. A failing check creates nothing and returns its SyntaxError or TypeError.

func (*Realm) SetDynamicCodeDisabled

func (r *Realm) SetDynamicCodeDisabled(disabled bool)

SetDynamicCodeDisabled sets whether the realm refuses to compile code at run time (see RealmOptions.DisableDynamicCode).

func (*Realm) SetHostDefined

func (r *Realm) SetHostDefined(code *bytecode.Function, host any)

SetHostDefined records host as the host value of the script or module template code (its [[HostDefined]]): import() in its code passes it to ImportHooks.Load as the referrer, and import.meta to ImportHooks.Meta. A host calls it for a script before RunScript; EvaluateGraph records the modules it instantiates from LinkOptions.HostDefined. Only a root template whose code uses import() or import.meta, or holds a direct eval call (bytecode.Function.ScriptOrModule), has a record, which the realm keeps as long as it lives, and code compiled from a string in its code shares (dynRoot.ref); SetHostDefined of any other template does nothing.

func (*Realm) SetImportHooks

func (r *Realm) SetImportHooks(h *ImportHooks)

SetImportHooks sets the hooks of import() and import.meta; nil removes them. Without Load and Link, import() rejects with a TypeError.

func (*Realm) SetMaxDynamicSource

func (r *Realm) SetMaxDynamicSource(n int)

SetMaxDynamicSource sets the length of the longest source text the realm compiles at run time: zero restores DefaultMaxDynamicSource, a negative n removes the limit (see RealmOptions.MaxDynamicSource).

func (*Realm) SetMemoryLimit

func (r *Realm) SetMemoryLimit(n int64)

SetMemoryLimit sets the number of bytes the realm may allocate for JavaScript between resets (ReleaseCallData, ResetAllocation) before it interrupts itself with a *MemoryLimitError; n <= 0 removes the limit and its counters. Changing a limit keeps what was counted.

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) Stats

func (r *Realm) Stats() Stats

Stats returns the realm's counters. Like every method but Interrupt and ClearInterrupt, it runs on the goroutine using the realm, and it may be called from a host function.

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) ThrownValue

func (r *Realm) ThrownValue(err error) (v Value, ok bool)

ThrownValue returns the value a catch sees when a native function returns err (NativeFunc): an *Exception's value, and for any other error an Error whose message is err.Error() and which keeps err for Exception.Unwrap. ok is false for nil and for an *InterruptedError, which no catch sees. It runs no user code.

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) ToGoInto

func (r *Realm) ToGoInto(v Value, target any) (complete bool)

ToGoInto stores v in the Go value target points to as encoding/json's Unmarshal stores the text json.Marshal writes for ToGoStrict(v), without the text, and reports whether it completed; when it did not, the caller is to finish with that round trip, which writes every part again. It writes nothing unless all of v, the parts target discards and the Go values of host placeholders included, is plain: ToGo runs no JavaScript for it, and json.Marshal does not fail on what ToGo gives (a NaN or an infinity, a cycle). It does not complete for: a bigint, a symbol, a function, an object that is not an ordinary object or an array (a Date, a Map, a typed array, a boxed primitive, a proxy), an accessor, a hole, a value whose text could pass the string length limit (plain's bound, kept as a bound of the walk), a host placeholder anywhere but in an empty interface or a json.RawMessage, and what Unmarshal does not complete for on the target's side. Strings are not copied. No interrupt is observed, as ToGo observes none for such a value.

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.

func (*Realm) Unmarshal

func (r *Realm) Unmarshal(v Value, target any) (complete bool, err error)

Unmarshal stores v in the Go value target points to as encoding/json's Unmarshal stores the text AppendJSON writes for v, without the text, and reports whether it completed; when it did not, the caller is to finish with the round trip (Unmarshal of AppendJSON's text), which writes every part again. It writes nothing unless all of v, the parts target discards and the Go values of host placeholders included, is plain; it does not complete for: a value AppendJSON would run JavaScript for (a toJSON, an accessor, a proxy, a function, which a toJSON could replace) or fail on (a BigInt, a cycle, a host's Go value it cannot write) or whose text could pass the string length limit (an upper bound of six bytes a code unit, one for a string known plain), an object that is not a plain object, dense array or host placeholder, a host placeholder anywhere but in an empty interface (but in a json.RawMessage, which receives the text of its value, rawInto), a target type that unmarshals itself (json.Unmarshaler, encoding.TextUnmarshaler; not json.RawMessage) or has an embedded or ",string" field, a non-empty interface, an interface holding a pointer, a []byte from a string, and any value the target's type rejects. Strings are not copied: the Go string of an ASCII string is the one v holds. err is an interrupt, observed every 4096 nodes of each walk (the check and the store), as AppendJSON's walk observes it, a host's Go string counting a node per 4096 bytes when the check of valid UTF-8 scans it; AppendJSON also observes one inside a JavaScript string it escapes, which the walks, copying no string, do not scan.

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

	// MaxDynamicSource is the length in bytes of the longest source text the
	// realm compiles at run time, in the UTF-8 the compiler parses: the
	// string of an eval, the parameters and body of a Function,
	// GeneratorFunction, AsyncFunction or AsyncGeneratorFunction call
	// together, and the source of Realm.EvalScript. Longer text throws a
	// RangeError before it is parsed, as parsing and compiling allocate many
	// times its size; a string of more code units than the limit is refused
	// by that count before it is converted. Zero means
	// DefaultMaxDynamicSource (1 MiB), a negative value no limit. It can be
	// changed later with Realm.SetMaxDynamicSource. Code the host compiles
	// (the compiler package) has no limit.
	MaxDynamicSource int

	// DisableDynamicCode makes the realm refuse to compile any source text at
	// run time: eval of a string, the Function, GeneratorFunction,
	// AsyncFunction and AsyncGeneratorFunction constructors and
	// Realm.EvalScript throw an EvalError where MaxDynamicSource would throw
	// its RangeError, once the arguments are converted to strings. eval of a
	// value that is not a string still returns it. It can be changed later
	// with Realm.SetDynamicCodeDisabled. Code the host compiles is not
	// affected.
	DisableDynamicCode bool

	// MemoryLimit is the number of bytes the realm may allocate for
	// JavaScript between resets (ReleaseCallData, ResetAllocation) before
	// it interrupts itself with a *MemoryLimitError (memlimit.go); 0 means
	// no limit. It can be changed later with Realm.SetMemoryLimit.
	MemoryLimit int64
}

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 Stats

type Stats struct {
	// AllocatedBytes is what was charged since the limit was set.
	AllocatedBytes int64
	// RequestAllocatedBytes is what was charged since the last reset
	// (ReleaseCallData, ResetAllocation), which the limit bounds.
	RequestAllocatedBytes int64
	// Objects, Strings and Shapes count the objects, strings and shapes
	// charged since the limit was set.
	Objects int64
	Strings int64
	Shapes  int64
	// MemoryLimitHits counts the times the limit stopped the realm.
	MemoryLimitHits int64
	// LastMemoryLimitError is the error of the last hit since the last
	// reset, or nil. The interrupt a hit raises is the realm's single
	// pending interrupt, which a concurrent Interrupt can replace (a host's
	// timeout): the hit is still counted, and its error kept, here.
	LastMemoryLimitError *MemoryLimitError
	// Interrupts counts the calls of Interrupt, memory limit hits included.
	Interrupts int64
	// ICEntries is the number of inline cache entries of the functions the
	// realm has run.
	ICEntries int
	// PendingJobs is the number of queued promise jobs and microtasks.
	PendingJobs int
	// RegisterStackBytes is the size of the interpreter's register stack.
	RegisterStackBytes int64
}

Stats are counters of a realm, each read in constant time. The allocation counters (AllocatedBytes to MemoryLimitHits) count only while a memory limit is set: they are the limit's account, which a realm without a limit does not keep. A host that wants them without a limit sets one it never reaches (math.MaxInt64).

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 mutations are the publication of a rope's flattened contents, which leaves the fields its readers read as they were (flatten), and the caching of hash/atom, both of which preserve the logical value. Concat writes past the end of a string in an append buffer, never into it.

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: one at a time until the first unit >= 0x80 has upgraded the builder, then the rest at once.

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