Documentation
¶
Overview ¶
Package bytecode defines the moejs instruction set and the compiled-function template shared between the compiler and the engine's interpreter.
See doc.go for the ISA reference and opcodes.go for the encoding. The types in this file are the data model: nothing in a Function is mutated after compilation (but for the name index an EvalLevel caches, see EvalLevel.Slot), so one *Function is shared by every realm (and every goroutine) that instantiates the same module. Per-realm state (inline caches, materialized constants) lives in engine side tables keyed by *Function.
Package bytecode: instruction set reference.
Machine model ¶
moejs runs a register machine. A function executes in a window of NumRegs registers R[0..NumRegs-1] carved out of one contiguous per-realm value stack. Arguments arrive in R[0..argc-1]; missing parameters are undefined; when HasRest is set the surplus arguments are collected into an array in R[NumParams] before any other instruction runs, and when HasArguments is set an unmapped arguments object holding every argument is created in the next register (R[NumParams], or R[NumParams+1] after a rest array). `this` is held in the frame, not in a register. Registers above the parameters hold locals (un-captured let/const/var/function bindings) and expression temporaries; the compiler allocates them stack-like so that a call block (callee, this, args) is always the highest live group of registers.
Captured bindings never live in registers: they live in closure environments (Env). env^0 is the innermost environment; env^d is its d-th parent. A function whose CaptureLayout has n > 0 slots creates its own Env of n slots at entry (with the parameter registers listed in the layout copied in); otherwise it runs directly in the environment captured by its closure. Block scopes with captured bindings push and pop nested Envs.
Every instruction is one 32-bit word: op:8 | A:8 | B:8 | C:8, or op:8 | A:8 | Bx:16 (unsigned) / sBx:16 (signed). Ops marked +X below are followed by one ExtraArg word (a raw uint32); GetEnvChkW and GetImportW have two. Jump offsets are relative to the pc of the following word. Constants K[i] are Function.Consts; F[i] are Function.Children.
Exceptions unwind through Function.Handlers without panic/recover: the interpreter takes the first row whose [Start, End) covers the faulting pc, pops closure environments down to StackDepth, stores the thrown value as described by Kind, and resumes at Handler. Rows without a match propagate the error to the caller's frame. Interrupts (Realm.Interrupt) are checked at function entry and at every backward jump (Jmp, and the relational compare-and-branch ops JmpLt .. JmpNGe and JmpLtI .. JmpNGeI, which close rotated loops) and are not catchable.
Opcodes ¶
Loads and moves
LoadConst A Bx R[A] = K[Bx] (number, string or bigint constant) LoadInt A sBx R[A] = sBx (small integer) LoadUndef A R[A] = undefined LoadNull A R[A] = null LoadTrue A R[A] = true LoadFalse A R[A] = false LoadHole A R[A] = hole (the TDZ marker; never observable) LoadThis A R[A] = this (undefined at module top level; lexical in arrows) LoadCallee A R[A] = the function object being executed (named function expressions) Move A B R[A] = R[B] UndefRange A B R[A .. A+B-1] = undefined (var bindings at entry)
Closure environments
GetEnv A B C R[A] = env^B[C] GetEnv0 A B C GetEnv with B = 0 (the innermost environment) GetEnv1 A B C GetEnv with B = 1 (the enclosing environment) GetEnv2 A B C GetEnv with B = 2 (the one around it) GetEnvChk A B C +X R[A] = env^B[C]; ReferenceError "K[X] is not defined" if hole SetEnv A B C env^B[C] = R[A] GetEnvW A B +X R[A] = env^B[X] (slot >= 256) GetEnvChkW A B +X +X R[A] = env^B[X1] with TDZ check; X2 = name constant SetEnvW A B +X env^B[X] = R[A] PushEnv Bx env = new Env(env, Bx slots initialized to undefined) PopEnv env = env.parent CopyEnv env = copy of env with the same parent (per-iteration let bindings) CheckTDZ A +X ReferenceError "Cannot access 'K[X]' before initialization" if R[A] is hole
Module imports (env^B[C] holds a reference to the exporting module's binding, filled in when the module graph is instantiated)
GetImport A B C +X R[A] = the binding env^B[C] refers to; ReferenceError if hole; X = name constant GetImportW A B +X +X same with slot X1 (slot >= 256); X2 = name constant
Dynamic import and import.meta (off the interpreter's jump table, after the async ops; the compiler sets Function.ScriptOrModule on the root of code that uses them, and of a script or module holding a direct eval)
ImportCall A B R[A] = a new promise for import(R[B]): ToString(R[B]), then the host's module for
it in the running root's script or module, linked and evaluated in the realm's module
map, fulfils it with the module's namespace; any failure rejects it
ImportMeta A R[A] = import.meta of the running root module: a null-prototype object created, and
filled by the host, on the first read in the realm
Globals (X = name constant:16 | inline cache:16)
GetGlobal A +X R[A] = globalThis[name]; ReferenceError if absent
GetGlobalOrUndef A +X R[A] = globalThis[name] or undefined (typeof operand)
SetGlobal A +X globalThis[name] = R[A]; ReferenceError if absent in a strict function, else
a new global object property and a rejected write ignored (SetGlobalSloppy)
A global name resolves first in the realm's global declarative environment (the let, const and class declarations of scripts), then on the global object. Scripts reach their own top-level declarations by name too: GlobalDeclarationInstantiation (Realm.RunScript) creates them from Function.Extra.Globals before the body runs.
Properties
GetProp A B +X R[A] = R[B].name (X = name:16 | ic:16; TypeError on null/undefined base)
GetLen A B +X R[A] = R[B].length (array and string fast paths; X = ic in the high half)
SetProp A B +X R[A].name = R[B] (strict PutValue); C = SetPropSloppyFlag: SetPropSloppy's,
the form the compiler emits for sloppy code
GetElem A B C R[A] = R[B][R[C]] (dense array and string index fast paths)
GetElemRef A B C +X R[C] = the key R[X], converted by ToPropertyKey when it is an object and
the base R[B] is neither undefined nor null; then GetElem A B C: the read of a
compound assignment or update, whose key GetValue converts once, after ToObject
of the base, and PutValue reuses (X is a register, C or another)
GetElemInc A B C R[C] = ToNumeric(R[C]) + 1, then R[A] = R[B][R[C]]: Inc C C; GetElem A B C, the
read x[++k] of a register local k
SetElem A B C R[A][R[B]] = R[C]: PutValue, strict or not as the function is
DelProp A B +X R[A] = delete R[B].name (strict: TypeError when not configurable)
DelElem A B C R[A] = delete R[B][R[C]]
In A B C R[A] = R[B] in R[C]
InstanceOf A B C R[A] = R[B] instanceof R[C]
Literals
NewObject A Bx R[A] = {} (ordinary object, Bx = property count hint)
NewArray A Bx R[A] = [] (Bx = capacity hint)
DefineField A B +X CreateDataProperty(R[A], K[name], R[B]) (X = name:16 | ic:16; the IC caches the shape transition)
DefineElem A B C CreateDataProperty(R[A], ToPropertyKey(R[B]), R[C])
DefineMethod A B C DefineElem for an object-literal method with a computed key: SetFunctionName(R[C], key) first
DefineAccessor A B C +X DefinePropertyOrThrow(R[A], ToPropertyKey(R[B]), {[[Get]] or [[Set]]: R[C], [[Enumerable]], [[Configurable]]: true}),
merging with an existing accessor half; X = AccessorSetter | AccessorEnumerable | AccessorNameKey
(AccessorNameKey: SetFunctionName(R[C], key, "get"/"set") first, for computed keys)
SetProto A B if R[B] is an object or null, R[A].[[Prototype]] = R[B] (the __proto__: v literal form)
CopyDataProps A B copy own enumerable properties of R[B] into R[A] (object spread)
CopyDataPropsEx A B C same, skipping the keys listed in array R[C] (object rest pattern)
ArrayPush A B append R[B] to array R[A]
ArrayPushK A +X append the constants K[X.lo] .. K[X.lo+X.hi-1] (numbers, strings, null or
undefined, X.hi >= 1) to array R[A]: a run of an array literal's elements
NewArrayK A +X R[A] = a new array of the constants K[X.lo] .. K[X.lo+X.hi-1] (as ArrayPushK's),
an array literal whose elements are all constants
NewObjectLit A B C +X R[A] = a new ordinary object with the data properties K[X.lo] .. K[X.lo+C-1]
(property names, C >= 1) of the values R[B] .. R[B+C-1], in that order, as NewObject
and a DefineField of each would make it; X.hi is the inline cache that keeps the
object's shape, which no other instruction of the function names
ArrayHole A append a hole to array R[A] (length += 1)
AppendSpread A B append every value produced by iterating R[B] to array R[A]
Closure A Bx R[A] = new function object over F[Bx] closing over env (and this for arrows)
NewRegExp A Bx R[A] = new RegExp(K[Bx].pattern, K[Bx].flags)
RegExpTest A sBx +X R[A] = /K[X lo]/.test(R[X hi]) and pc += sBx: the call /lit/.test(x) of a literal
neither global nor sticky with x a local, when x is a string and the test and exec of
%RegExp.prototype% are the originals, so that no code could see the literal's object and
the match needs none. Else it falls through to the call, which it jumps over
GetTemplate A +X R[A] = the template object of K[X lo] (GetTemplateObject: frozen cooked strings with a frozen raw array), created on the site's first evaluation in the realm and cached in IC slot X hi
Arithmetic (number fast paths; BigInt operands take the slow path)
Add A B C R[A] = R[B] + R[C] (numbers, string concatenation, ToPrimitive)
Sub A B C R[A] = R[B] - R[C]
Mul A B C R[A] = R[B] * R[C]
Div A B C R[A] = R[B] / R[C]
Mod A B C R[A] = R[B] % R[C]
Exp A B C R[A] = R[B] ** R[C]
AddImm A B C R[A] = R[B] + int8(C) (Add semantics: strings concatenate)
SubImm A B C R[A] = R[B] - int8(C)
Inc A B R[A] = ToNumeric(R[B]) + 1 (++; never concatenates)
Dec A B R[A] = ToNumeric(R[B]) - 1 (--)
Neg A B R[A] = -R[B]
Plus A B R[A] = +R[B] (ToNumber)
Not A B R[A] = !ToBoolean(R[B])
BitNot A B R[A] = ~R[B]
ToNumeric A B R[A] = ToNumeric(R[B]) (postfix update result)
PostInc A B R[A] = ToNumeric(R[B]), then R[B] = R[A] + 1: ToNumeric A B; Inc B A, a postfix ++
whose value is used
PostDec A B R[A] = ToNumeric(R[B]), then R[B] = R[A] - 1: ToNumeric A B; Dec B A
RequireObjectCoercible A throw TypeError when R[A] is null or undefined (empty or rest-only destructuring pattern)
ToStr A B R[A] = ToString(R[B]) (template substitutions)
Concat A B C R[A] = R[B] + R[C], both already strings (rope above the threshold)
Typeof A B R[A] = typeof R[B]
TypeofIs A B C R[A] = typeof R[B] === TypeNames[C]
BitAnd A B C R[A] = R[B] & R[C]
BitOr A B C R[A] = R[B] | R[C]
BitXor A B C R[A] = R[B] ^ R[C]
Shl A B C R[A] = R[B] << R[C]
Shr A B C R[A] = R[B] >> R[C]
UShr A B C R[A] = R[B] >>> R[C]
Comparison
Eq A B C R[A] = R[B] == R[C] Ne A B C R[A] = R[B] != R[C] StrictEq A B C R[A] = R[B] === R[C] StrictNe A B C R[A] = R[B] !== R[C] Lt A B C R[A] = R[B] < R[C] Le A B C R[A] = R[B] <= R[C] Gt A B C R[A] = R[B] > R[C] Ge A B C R[A] = R[B] >= R[C]
Control flow (offsets relative to the next pc)
Jmp sBx pc += sBx; a negative offset is a loop back-edge and checks the interrupt flag
(so does a negative offset of the relational compare-and-branch ops below,
jumping or not: a for, while or do-while loop whose condition is a relational
comparison ends in its jump)
JmpT A sBx if ToBoolean(R[A]) pc += sBx
JmpF A sBx if !ToBoolean(R[A]) pc += sBx
JmpNullish A sBx if R[A] is null or undefined pc += sBx
JmpNotNullish A sBx if R[A] is neither null nor undefined pc += sBx
JmpNotUndef A sBx if R[A] is not undefined pc += sBx
JmpLt A sBx +X if R[A] < R[X] pc += sBx (offset relative to the X word); JmpLe, JmpGt, JmpGe
likewise with <=, >, >=. The compiler emits them for a comparison whose value
only decides a conditional jump; they convert and throw as Lt .. Ge do
JmpNLt A sBx +X if !(R[A] < R[X]) pc += sBx; JmpNLe, JmpNGt, JmpNGe likewise (NaN jumps).
An X of EnvOperand or more makes the right operand of JmpLt .. JmpNGe
env^0.slots[X>>8 & 0xff] instead (X's low byte is then A): the compiler emits it for
a binding closures share, initialized before any read (i < width)
JmpStrictEq A sBx +X if R[A] === R[X] pc += sBx; JmpStrictNe with !==
JmpLtI .. JmpStrictNeI A sBx +X JmpLt .. JmpStrictNe (same order) with the right operand the integer
int32(X) instead of R[X]: the compiler emits them for a comparison with an integer
literal that no register holds (n < 2)
JmpStrictEqK A sBx +X JmpStrictEq with the right operand K[X], a string, null or undefined: the
compiler emits it (and JmpStrictNeK) for a strict comparison with such a literal
that no register holds and for a switch's case of one
JmpTypeofIs A sBx +X if typeof R[A] === TypeNames[X] pc += sBx; JmpTypeofNot with !==: TypeofIs and the
jump on its result, for a typeof test that decides a jump
JmpCaseK A sBx +X JmpStrictEqK, then each JmpStrictEqK after it that tests R[A], with no dispatch
of its own: the compiler emits it for the first of a switch's cases on constants
that test the discriminant in a row (caseRunMin of them or more)
Calls
Call A B C R[A] = R[A](this = R[A+1], args R[A+2 .. A+1+B]); TypeError if not callable;
C&CallUndefThis: this is undefined and R[A+1] is not read (a plain call);
C&CallOverlap: the callee's registers start at R[A+2], its parameters the arguments
in place, and it writes over the caller's registers from there (the compiler marks
a call so only when they are dead after it, MarkOverlapCalls)
CallSpread A R[A] = R[A](this = R[A+1], ...array R[A+2])
ApplyArguments A B C R[A] = R[A](this = R[A+1], args R[A+2], R[B]): f.apply(x, arguments) in a function
with ForwardArguments, whose arguments register R[B] holds the count of the arguments
the frame keeps above its registers until the object exists. While it does not and
R[A] is the realm's %Function.prototype.apply%, R[A+1] is called with this R[A+2] and
those arguments (TypeError if not callable, as apply's). Else the object is created
into R[B] if it is not yet (C = 1: a mapped one, as with MapArguments B = 1), and
the call is Call A 2 with R[A+3] = R[B]
ArgsLen A B R[A] = R[B].length, arguments.length in a function with ForwardArguments: the count R[B]
holds until the arguments object exists, then its length property
ArgsGet A B C +X R[A] = R[B][R[C]], arguments[k] in a function with ForwardArguments: while the object
does not exist, the kept argument R[C] when R[C] is an int32 below the count; else the
object is created into R[B] first (X = 1: a mapped one, as with ApplyArguments C = 1)
New A B R[A] = new R[A](R[A+2 .. A+1+B]); TypeError if not a constructor
C&CallOverlap: the constructor's registers start at R[A+2], as a Call's
NewSpread A R[A] = new R[A](...array R[A+2])
Ret A return R[A]
RetUndef return undefined
Throw A throw R[A]
ThrowConstAssign +X throw TypeError("Assignment to constant variable.") (K[X] names the binding)
Iteration (for-of, spread and array destructuring share GetIterator and IteratorStepValue; R[A], R[A+1] hold the Iterator Record: the iterator and its next method, or, while the protocol is unobservable, the array or string itself and the next index; R[A] is undefined once done or closed)
IterInit A B R[A], R[A+1] = GetIterator(R[B]); TypeError if not iterable IterNext A sBx R[A+2] = next value; when exhausted pc += sBx IterValue A B R[B] = next value or undefined when exhausted (destructuring) IterRest A B R[B] = array of the remaining values (rest element) IterClose A sBx IteratorClose(R[A], normal completion) unless done; pc += sBx IterThrow A B IteratorClose(R[A], throw completion) unless done; throw R[B] ForInInit A B R[A] = enumerable string keys of R[B] (prototype chain, deduplicated), R[A+1] = 0, R[A+2] = the object ForInNext A sBx R[A+3] = next key still present as a property; when exhausted pc += sBx
Classes, super, new.target and private names (off the interpreter's jump table: they only run while classes are defined and in class code)
CtorEntry A R[A] = new.target; TypeError "Class constructor X cannot be invoked without 'new'" in a [[Call]] (first op of every class constructor)
LoadNewTarget A R[A] = new.target, undefined in a [[Call]] (first op of a function with NewTarget set)
LoadHome A R[A] = [[HomeObject]] of the running function
SetHome A B [[HomeObject]] of function R[A] = R[B]
CreateClass A B C finish class constructor R[A] (the Closure of a class-constructor template):
R[A+1] = the new prototype object, R[A].prototype = R[A+1] (read-only),
R[A+1].constructor = R[A] (non-enumerable), [[HomeObject]] of R[A] = R[A+1];
C&1: R[B] is the heritage (null, or a constructor whose prototype is an object or null);
C&2: first name R[A] after property key R[A+1] (an anonymous class field value)
DefineClassMethod A B C R[A][R[B]] := R[C] non-enumerable, [[HomeObject]] of R[C] = R[A];
an unnamed function is named after the key
ToPropertyKey A B R[A] = ToPropertyKey(R[B]) (computed field keys)
GetProtoOf A B R[A] = R[B].[[GetPrototypeOf]]() or null: the super base of home object R[B],
or the super constructor of active function R[B]
GetSuper A B C R[A] = super property R[C] of base R[B] read with receiver R[B+1];
TypeError if the base is null (A may equal B)
SetSuper A B C set super property R[B] of base R[A] to R[C] with receiver R[A+1]; TypeError if refused
SuperCall A B R[A] = Construct(R[A], args R[A+2 .. A+1+B], new.target R[A+1]); TypeError if not a constructor
SuperCallSpread A same with the argument array R[A+2] (AppendSpread-built, or the default constructor's rest array)
CheckSuper A ReferenceError "Super constructor may only be called once" unless R[A] is hole
DerivedResult A B R[A] = the value a derived constructor returns for return value R[A] and raw `this` R[B]:
an object as is; undefined gives `this` (ReferenceError if still hole); otherwise TypeError
NewPrivateName A Bx R[A] = a new private name described by K[Bx] ("#x", or the class name for a brand)
SetPrivateMethod A B C +X make R[B] the method, getter or setter of private name R[A], checked against
the brand R[C] (or, with PrivateStatic, the class constructor R[C]); X = Private* flags
GetPrivate A B C R[A] = R[B].#R[C]; TypeError when R[B] lacks it
SetPrivate A B C R[A].#R[B] = R[C]; TypeError when R[A] lacks it or it is a method
DefPrivate A B C add private field #R[B] = R[C] to object R[A]; TypeError if already present
AddBrand A B add class brand R[B] to object R[A]; TypeError if already present
InPrivate A B C R[A] = #R[B] in R[C]; TypeError if R[C] is not an object
ThrowError A Bx throw a new TypeError (A=ThrowTypeError) or ReferenceError (A=ThrowReferenceError) with message K[Bx]
Sloppy mode, script globals and with (off the interpreter's jump table, after the async ops: only sloppy code, script top levels, with statements and strict assignments of an undeclared name from a value that may run code use them)
SetGlobalSloppy A +X PutValue of an identifier resolved against the global environment in sloppy code:
an unresolvable name becomes a global object property; a rejected write is
ignored (X = name:16 | ic:16, the SetGlobal cache; not emitted by the compiler:
SetGlobal ignores it in a function that is not strict)
ResolveGlobal A +X R[A] = HasBinding(K[X.lo]) of the global environment: ResolveBinding of an
undeclared name in strict code, before the value assigned to it (X = name:16 | ic:16)
SetGlobalRef A B +X PutValue of R[A] to the reference ResolveGlobal resolved: ReferenceError unless
R[B] (its result) is true, else SetMutableBinding(K[X.lo], R[A], strict), whose
HasProperty throws a ReferenceError for a binding gone since (X = ResolveGlobal's)
InitGlobal A +X initialize the script's global lexical binding K[X.lo] to R[A] (X.hi = 1: const)
SetGlobalVar A +X evaluation of a sloppy block function declaration at script level (Annex B.3.2.2):
globalThis[K[X]] = R[A] as SetGlobalSloppy, skipped when a global lexical binding K[X] exists
DelGlobal A +X R[A] = delete K[X] for a name resolved against the global environment:
false for a global lexical binding, else globalThis.[[Delete]](K[X])
SetPropSloppy A B +X R[A].name = R[B], ignoring a rejected assignment (X = name:16 | ic:16)
SetElemSloppy A B C R[A][R[B]] = R[C], ignoring a rejected assignment (not emitted by the
compiler: SetElem ignores it in a function that is not strict)
DelPropSloppy A B +X R[A] = delete R[B].name; false instead of a TypeError when not configurable
DelElemSloppy A B C R[A] = delete R[B][R[C]]; false instead of a TypeError when not configurable
SetSuperSloppy A B C set super property R[B] of base R[A] to R[C] with receiver R[A+1], ignoring a
rejected assignment
ToObject A B R[A] = ToObject(R[B]); TypeError on null or undefined. Also makes the object a
member initializer or sloppy eval code defines fields on one for the verifier
JmpWith A sBx +X pc += sBx if the object environment of with object R[A] has binding K[X]:
HasProperty, then a truthy @@unscopables entry blocks it; falls through when R[A]
is not an object (a function's %evalvars before a direct eval declares a var)
WithGet A B +X R[A] = GetBindingValue(K[X.lo]) of the object environment of R[B]: undefined,
or with X.hi = 1 (strict) a ReferenceError, when the property is gone
WithSet A B +X SetMutableBinding(K[X.lo], R[B]) of the object environment of R[A]
(X.hi = 1: strict, a ReferenceError when the property is gone and a TypeError when rejected)
CoerceThis A this = the global object when undefined or null, else ToObject(this); R[A] = this
(the entry of a sloppy function that uses this, as LoadThis A)
MapArguments A B make the fresh arguments object R[A] a mapped one: its indices below both the argument
count and NumParams alias the parameters' slots of the function's own Env (CaptureLayout
entries below NumParams) and callee is the running function. B = 1 when no code writes
a parameter (nor can: no direct eval) and parameter i is Env slot i: the object then
keeps its elements and builds the alias on the first write, define or delete of one
CallEval A B C +X R[A] = Call as with Call (C = 1: CallSpread) of callee R[A], this R[A+1]; when the
callee is the realm's %eval% it is a direct eval (PerformEval) of the first argument
in the running Env, compiled against the call site's scope Extra.Evals[X]
Index ¶
- Constants
- Variables
- func DecodeA(w uint32) uint8
- func DecodeB(w uint32) uint8
- func DecodeBx(w uint32) uint16
- func DecodeC(w uint32) uint8
- func DecodeSBx(w uint32) int16
- func Disassemble(fn *Function) string
- func EncodeABC(op Op, a, b, c uint8) uint32
- func EncodeABx(op Op, a uint8, bx uint16) uint32
- func EncodeAsBx(op Op, a uint8, sbx int16) uint32
- func ExtraArg(lo, hi uint16) uint32
- func ExtraHi(x uint32) uint16
- func ExtraLo(x uint32) uint16
- func ImmediateOperand(n float64) (int32, bool)
- func JumpTarget(pc int, w uint32) int
- func KindOperands(op Op, w uint32, use func(r int, kind RegKind))
- func MarkOverlapCalls(fn *Function) int
- func RegisterSpans(op Op, w, x uint32, span func(r, k int)) bool
- func RegisterWrites(op Op, w, x uint32, write func(r, k int, kind RegKind)) bool
- func TypeNameIndex(name string) (uint8, bool)
- func VerifyRegisters(fn *Function) error
- type CaptureLayout
- type Const
- type ConstKind
- type EvalLevel
- type EvalScope
- type Export
- type Extra
- type Format
- type Function
- type GlobalNames
- type Handler
- type HandlerKind
- type Import
- type Kind
- type LineEntry
- type Links
- type Module
- type Op
- type Reexport
- type RegKind
- type Request
- type SourceInfo
- type Star
Constants ¶
const ( TypeUndefined uint8 = iota TypeObject TypeBoolean TypeNumber TypeString TypeSymbol TypeBigInt TypeFunction )
TypeName indices used by TypeofIs (operand C) and JmpTypeofIs (X).
const ( AccessorSetter uint32 = 1 << iota // define the setter half (otherwise the getter) AccessorEnumerable // the property is enumerable AccessorNameKey // name the function "get <key>"/"set <key>" at run time (computed keys) )
DefineAccessor flags (its ExtraArg word). Object literals set AccessorEnumerable; class accessors do not.
const ( PrivateGetter uint32 = 1 << iota // the function is the getter of an accessor PrivateSetter // the function is the setter of an accessor PrivateStatic // checked against the class constructor instead of a brand )
SetPrivateMethod flags (its ExtraArg word).
const ( ThrowTypeError uint8 = iota ThrowReferenceError )
ThrowError kinds (operand A).
const ( MaxRegister = 255 // registers are 8-bit operands MaxBx = 0xFFFF // unsigned 16-bit operand MaxSBx = 0x7FFF MinSBx = -0x8000 )
Instruction word layout constants.
const CallOverlap = 2
CallOverlap is the bit of the operand C of Call and New that lets the engine start the callee's frame at the call's arguments: the callee's registers begin at R[A+2], its parameters are the arguments where the caller left them, and nothing is copied. The callee writes its registers over the caller's from R[A+2] up, so the compiler sets the bit (MarkOverlapCalls) only on a call after which no register from R[A+2] up is read before it is written, on any path, the handler's that catches the call's throw included, and only in a function whose frame keeps nothing else above its call blocks: no generator or async function, which would save the callee's values with its registers at a suspension and keep them alive as long as it lives, no frame that keeps its arguments above its registers (ForwardArguments), and no module body, which may suspend. R[A] and R[A+1], the callee and this (New's is unused), stay the caller's: the stack walk and the memory measurement read them while the callee runs. VerifyRegisters proves it of every call that has the bit.
const CallUndefThis = 1
CallUndefThis is the Call operand C of a call whose this is undefined (a plain call f(x)): the callee gets undefined and R[A+1] is not read, so no LoadUndef fills it.
const EnvOperand = 1 << 16
EnvOperand marks the X word of JmpLt .. JmpNGe whose right operand is slot X>>8&0xff of env^0 instead of register X: a binding closures share that the op reads itself, as a loop's bound is. Its low byte is A.
const NoRegister uint16 = 0xFFFF
NoRegister marks a CaptureLayout slot that is not initialized from a parameter register.
const OpCount = int(opCount)
OpCount is the number of defined opcodes.
const PCBits = 24
PCBits bounds the pcs the engine stores to run a frame from later: a suspended generator's or async function's resume pc, the pc a frame reruns from, and a module body's first pc (Module.BodyPC). The engine packs the frame's environment depth above them.
const SetPropSloppyFlag = 1
SetProp's operand C in sloppy code: the write is SetPropSloppy's, which ignores a rejected assignment. The compiler emits this form for a named write in sloppy code, whose writes are as frequent as strict code's: the engine runs it in SetProp's case, which a SetPropSloppy leaves for coldOp, a call.
const UndefinedCooked = "\xff"
UndefinedCooked is the Const.Cooked entry of a tagged template chunk with an invalid escape, whose cooked value is undefined. The byte 0xFF never occurs in WTF-8.
Variables ¶
var DescribeCallee func(f *Function, pc uint32) string
DescribeCallee, when non-nil, returns the source form of the callee of the Call, CallSpread, New or NewSpread instruction at pc of f ("obj.foo", "f(...)"), or "" when it cannot tell. Package compiler installs it; the engine calls it only to word the TypeError of a call or construction of a value that is not callable, so no call site carries any extra data.
var TypeNames = [typeNameCount]string{"undefined", "object", "boolean", "number", "string", "symbol", "bigint", "function"}
TypeNames spells the TypeofIs operand.
Functions ¶
func Disassemble ¶
Disassemble renders fn (and, indented, its children) in a stable text form for tests and debugging.
func EncodeAsBx ¶
EncodeAsBx packs an AsBx instruction.
func ImmediateOperand ¶
ImmediateOperand reports whether n can be the X word of an immediate compare-and-branch op: an int32 other than -0.
func JumpTarget ¶
JumpTarget returns the pc that the jump w at pc names: its sBx counts from the word after the instruction's first, the X word of a compare-and-branch or JmpWith included.
func KindOperands ¶
KindOperands calls use(r, kind) for each register the instruction w reads as kind without looking at it: the engine's interpreter reads DefineField's instance as an object, the literal of ArrayPush and ArrayPushK as an array, and the for-in record of ForInNext as an object (the key list) and an index (engine run, coldOp and forInNext).
func MarkOverlapCalls ¶
MarkOverlapCalls sets CallOverlap on every Call and New of fn after which the registers from R[A+2] up are dead (CallOverlap), clears it on the others, and returns how many it marked. It records that it proved the marks (overlapSum), for VerifyRegisters to take them as they are while fn's code, handlers and frame stay the same. fn's code is VerifyRegisters' to check: on code it rejects (an op of no layout, a register past the frame, a jump into the middle of an instruction), what it marks does not matter, and it does not fail.
func RegisterSpans ¶
RegisterSpans calls span(r, k) for each run of k registers from r that the instruction w (with its first extra word x) names, and reports whether op has a known layout. Operands that are not registers (counts, immediates, flags, constant and child indexes, environment slots) are left out; a count gives the length of the run it describes. A layout may name more than an instruction touches (New's this slot, IterClose's next method), never less: the engine's checked build fails on a register access a layout leaves out.
func RegisterWrites ¶
RegisterWrites calls write(r, k, kind) for each run of k registers from r that the instruction w (with its first extra word x) may write, and reports whether op has a known layout. kind is what the instruction leaves in the run whenever it completes, given that its KindOperands hold: an object for NewObject, NewObjectLit and ToObject, an array for NewArray and NewArrayK, the key list and the index of ForInInit's record and ForInNext's index; RegAny for every other write. A row may name more than an instruction writes (the argument registers of a call, which a native callee gets as a slice of them), never less, and names only registers of the instruction's RegisterSpans: the verifier takes a register no row names to keep its value (verifyKinds), and the engine's checked build fails on an instruction that changes one or completes with another kind.
func TypeNameIndex ¶
TypeNameIndex returns the TypeofIs operand for a typeof result string.
func VerifyRegisters ¶
VerifyRegisters checks what the engine's interpreter relies on to index a frame's registers without bounds checks. It walks fn.Code from pc 0, one instruction and its extra words at a time, and checks that
- every register an instruction names, and every run of registers it reads or writes, lies below NumRegs: the operands A, B, C and the X word's register where they are registers, a call's or a construction's callee, this (or new.target) and arguments, the argument array of the spread forms, UndefRange's run, iterator, for-in and async-iterator records, the value and mode pair of a suspension (RegisterSpans), and the registers its handlers write;
- the interpreter runs no other instructions than the ones the walk checked: every jump lands on the start of one (Op.Jumps, JumpTarget), and so do every handler and the body of a module (Module.BodyPC). A jump onto an extra word would run it as an instruction whose operands no one checked: the X word of an immediate compare holds an integer of the source;
- the interpreter reads no word past the code, which it reads without bounds checks: every instruction's extra words are inside it, and the last instruction never continues at the next pc (a return, a throw, Jmp, IterClose or IterThrow: ends), so neither a fallthrough nor a suspension or rerun, which continues after its instruction, leaves the code. A function has at least one instruction;
- the inline cache an instruction names in its X word's high 16 bits (icOperand) is below ICCount, and a NewObjectLit's is named by no other instruction (verifyLiteralICs);
- a NewObjectLit makes at least one property, and its keys are property names;
- the pcs the engine stores fit in PCBits: a module body's, and every pc of a function that can suspend or rerun (Op.SavesPC);
- each handler's range lies inside the code, and it is a catch or a finally row (the engine enters a row of another kind as a finally);
- NumRegs is at most MaxRegister+1, the registers of the window;
- the constant an op reads as a given kind is one (constOperand): NewRegExp's and RegExpTest's (in its X word) a regular expression, NewPrivateName's and ThrowError's a string, and the name in the X word of a property or global binding access a property name, a string with Key set (keyOperand). The engine reads it as that kind without looking;
- so is the register an op reads as a given kind (KindOperands): every path to the op leaves one there (verifyKinds);
- the X word of JmpLt .. JmpNGe that names an environment slot (EnvOperand) has A in its low byte: the interpreter reads the register the low byte names before it looks at the rest;
- GetEnv0, GetEnv1 and GetEnv2 have B 0, 1 and 2: the interpreter reads the environment their op names, the engine's other readers of a GetEnv the one B names;
- a lazy MapArguments (B = 1) has parameter i in Env slot i, below the Env's size (paramsInOrder): the engine indexes the slot by the parameter. So does a mapped ApplyArguments (C = 1);
- a Call or New with CallOverlap is one after which no register from R[A+2] up is live, in a function that may have such calls (verifyOverlap); a Call's C has no other bits than CallUndefThis and CallOverlap, a New's no other than CallOverlap;
- ApplyArguments, ArgsLen and ArgsGet name the arguments register of a function with ForwardArguments, which is neither a generator nor async: the engine reads the arguments the entry kept above the registers. A mapped ArgsGet (X = 1) has the parameters at their Env slots, as a mapped ApplyArguments does;
A function with an opcode RegisterSpans has no layout for fails. A word that is no opcode names no register: the interpreter faults on it before it touches one. It does not look at fn's children.
The engine runs it on every function it materializes (engine fillMeta), and the checked build of the interpreter (go test -tags moejsregcheck ./engine) compares every register access with RegisterSpans and every pc it dispatches with the walk's instruction starts.
Types ¶
type CaptureLayout ¶
type CaptureLayout []uint16
CaptureLayout describes the function's own closure environment: its length is the number of Env slots created at function entry (zero means the function creates no Env and runs in its closure's environment), and entry i is the parameter register whose value is boxed into slot i at entry, or NoRegister for slots initialized to undefined.
type Const ¶
type Const struct {
Kind ConstKind
Num float64 // ConstNumber
Str string // ConstString (WTF-8), ConstBigInt (decimal or 0x hex), ConstRegExp (pattern)
IsASCII bool // ConstString: every byte of Str is < 0x80
Units []uint16 // ConstString: UTF-16 code units when !IsASCII (nil otherwise)
Key bool // ConstString: used as a property name (the engine interns it)
Flags string // ConstRegExp flags
Cooked []string // ConstTemplate cooked strings (WTF-8, or UndefinedCooked)
Raw []string // ConstTemplate raw strings (UTF-8)
Index int // ConstFunction: index into Function.Children
}
Const is a constant-pool entry. Only the fields relevant to Kind are set.
type ConstKind ¶
type ConstKind uint8
ConstKind tags a constant-pool entry.
const ( // ConstNumber is a float64 literal (Num). ConstNumber ConstKind = iota // ConstString is a string literal (Str, IsASCII, Units). ConstString // ConstBigInt is a BigInt literal stored as text (Str): decimal, or hex // after "0x" (see syntax.BigIntLit). ConstBigInt // ConstRegExp is a regular-expression literal (Str = pattern, Flags). ConstRegExp // ConstTemplate is a tagged template's strings (Cooked, Raw); untagged // templates are lowered to Concat. ConstTemplate // ConstFunction is an index into Function.Children (Index). Reserved; // Closure indexes Children directly. ConstFunction // ConstNull and ConstUndefined are null and undefined, as the right // operand of JmpStrictEqK, JmpStrictNeK and JmpCaseK. ConstNull ConstUndefined )
type EvalLevel ¶
type EvalLevel struct {
Kind uint8 // syntax.ScopeKind of the scope owning the Env
Names []string
Kinds []uint8
TDZ []bool
// Outer is the next Env up the chain, nil for the outermost.
Outer *EvalLevel
// contains filtered or unexported fields
}
EvalLevel is one Env of an EvalScope: its binding names in slot order ("" for a slot no binding owns), with the syntax.BindKind and whether the binding has a temporal dead zone for each.
func (*EvalLevel) Slot ¶
Slot returns the slot of the binding named name, or -1 when the Env has none. A large level indexes its names on first use, so that eval code using a few of them does not pay for all: the index is a cache every goroutine would build the same, stored atomically, and the one thing written to a Function after compilation.
type EvalScope ¶
type EvalScope struct {
// Env is the level of the running Env of the call site, nil when there
// is none; its Outer chain are the Envs outwards: level i is the Env i
// hops up the chain from the running Env. The script's global bindings
// are not levels; they are resolved through the global object and the
// global lexical environment.
Env *EvalLevel
// Var is the level holding the variable environment of the calling
// function (its %evalvars object), or -1 for the global one.
Var int
// This is the level of the Env of the function supplying this,
// new.target and super (the nearest non-arrow function), or -1 when
// the call site is not inside a function.
This int
// Fields is the level holding the %fields binding of the class of a
// derived constructor supplying this (super() in the eval code runs its
// field initializers), or -1.
Fields int
// FuncKind is the syntax.FuncKind of that function and Derived marks a
// derived class constructor.
FuncKind uint8
Derived bool
// Strict is the strictness of the calling code; InParams marks a call
// in the parameter list of a function whose body has its own variable
// environment; Module marks a call in module code.
Strict, InParams, Module bool
}
EvalScope describes the environment chain visible at a direct eval call site so that the compiler can resolve the eval code against it at run time. It is opaque to the engine, which hands it to the compile hook together with the source text. The call sites of a compilation share their EvalScopes and EvalLevels where they can: sites in one scope have the same EvalScope, and the chains of sites in nested scopes share their outer levels.
type Extra ¶
type Extra struct {
// Globals lists the names a script or global eval code declares at top
// level (nil when it declares none) for GlobalDeclarationInstantiation
// or EvalDeclarationInstantiation, which check and create them before
// the body runs.
Globals *GlobalNames
// Evals describes the scope of each direct eval call site (CallEval's
// X operand indexes it).
Evals []*EvalScope
}
Extra is the rarely needed part of a Function.
type Function ¶
type Function struct {
Name string // "" for anonymous functions
Length int // formal parameter count exposed as .length
Strict bool // strict mode code (modules, classes, "use strict"); else sloppy
Kind Kind
NumRegs uint16 // register window size
NumParams uint16 // declared parameters (excluding rest)
HasRest bool // the rest array is collected into R[NumParams] at entry
// HasArguments makes the entry create an unmapped arguments object in
// the register after the parameters (and the rest array); the prologue
// of a sloppy function with simple parameters maps it (MapArguments).
HasArguments bool
// ForwardArguments, with HasArguments, marks a function that is no
// generator nor async and whose code reads the arguments register only
// in ApplyArguments, ArgsLen and ArgsGet: the entry creates no object
// but copies the arguments above the register window, where the frame
// keeps them, and puts their count in the register. ApplyArguments
// and ArgsGet create the object when a call or a key needs it.
ForwardArguments bool
// NewTarget is set when the function reads new.target (LoadNewTarget):
// [[Construct]] then passes it through the realm. Class constructors
// always receive it.
NewTarget bool
// Generator marks a generator function (of kind KindMethod: not
// constructible); its body starts with GenStart.
Generator bool
// Async marks an async function, async generator function or module
// with top-level await (see compiler/async.go).
Async bool
// ScriptOrModule is set on the root template of a script or module
// whose code uses import() or import.meta: they need the script or
// module record the host gave for it at run time
// (GetActiveScriptOrModule), which a realm keeps only for such roots.
// It is set too on the root of a script or module holding a direct
// eval call: the code a realm compiles from a string shares the record
// of the code that evaluates it.
ScriptOrModule bool
// ICCount is the number of inline-cache slots this function needs. Their
// indices are assigned per realm on the function's first call there
// (engine.Realm.AllocIC); the template is never mutated.
ICCount uint32
Code []uint32
Consts []Const
Children []*Function
Handlers []Handler
CaptureLayout CaptureLayout
LineTable []LineEntry
Source *SourceInfo
// Module is the module record of a KindModule template (nil for any
// other kind).
Module *Module
// Extra holds the rarely needed data of scripts, eval code and
// functions containing a direct eval (nil for everything else, so
// ordinary functions pay one pointer word).
Extra *Extra
// contains filtered or unexported fields
}
Function is an immutable compiled-function template. A single *Function is shared by every realm that instantiates the same module, so nothing in it may be mutated after compilation; per-realm state (inline caches) lives in engine.Realm side tables keyed by *Function.
func (*Function) Position ¶
Position returns the source line and column of the instruction at pc, or (0, 0) when the function has no line table.
func (*Function) SourceText ¶
SourceText returns the function's source slice for Function.prototype.toString, or "" when unknown.
type GlobalNames ¶
type GlobalNames struct {
Lexical []string // let, const and class names
Function []string // function declaration names, each once
Var []string // var names that are not also function names
// AnnexB lists the names only block-level function declarations of
// sloppy code declare at top level (Annex B.3.2.2): each becomes a var
// unless a global lexical binding or a non-extensible global object
// prevents it.
AnnexB []string
// Eval marks the declarations of sloppy eval code, whose global
// bindings are created configurable (EvalDeclarationInstantiation) and
// which never declares global lexical bindings.
Eval bool
}
GlobalNames are the top-level declarations of a script, each list in source order.
type Handler ¶
type Handler struct {
Start uint32
End uint32
Handler uint32
StackDepth uint16
Kind HandlerKind
Reg uint16 // register receiving the exception (see HandlerKind)
}
Handler is one exception-table row: [Start, End) is the protected pc range, Handler is the pc to resume at and StackDepth the closure-environment depth (number of PushEnv levels relative to function entry) to unwind to. Rows are ordered innermost first; the interpreter takes the first row whose range covers the faulting pc.
type HandlerKind ¶
type HandlerKind uint8
HandlerKind distinguishes catch and finally rows of the handler table.
const ( // HandlerCatch receives the thrown value in R[Reg]. HandlerCatch HandlerKind = iota // HandlerFinally receives the completion kind (1 = throw) in R[Reg] and // the thrown value in R[Reg+1]. HandlerFinally )
type Import ¶
type Import struct {
Request int // index into Links.Requests
Name string // the imported name (unset for a namespace import)
Namespace bool
Slot int
Line, Col int32
}
Import is an import binding.
type Kind ¶
type Kind uint8
Kind classifies a compiled function template.
const ( // KindNormal is an ordinary function declaration or expression. KindNormal Kind = iota // KindArrow is an arrow function (lexical this, not constructible). KindArrow // KindMethod is a concise object-literal method (not constructible). KindMethod // KindModule is the module top-level body. KindModule // KindScript is a script top-level body (Realm.RunScript): its // top-level declarations are global bindings reached by name. KindScript // KindClassCtor is a base class constructor: [[Construct]] creates // `this` from new.target and [[Call]] throws (CtorEntry). The class // kinds come last so IsClassCtor is one comparison. KindClassCtor // KindDerivedCtor is the constructor of a class with an extends clause: // `this` stays uninitialized until super() returns. KindDerivedCtor )
func (Kind) IsClassCtor ¶
IsClassCtor reports whether k is a class constructor kind.
type Links ¶
type Links struct {
// Requests are the specifiers, each once ([[RequestedModules]]).
Requests []Request
// Imports are the import bindings: each Env slot holds a reference to
// the exporting binding (GetImport), or the namespace object when
// Namespace is set (`import * as ns`, read with GetEnv).
Imports []Import
// Reexports are the indirect exports: `export {x as y} from`, `export *
// as y from` (All), and `export {x as y}` of an import binding x.
Reexports []Reexport
// Stars are the requests of the `export * from` entries.
Stars []Star
}
Links are the module requests of a module and the entries that name them, each in source order. Line and Col (1-based, the column in code points) locate the specifier or the entry for the errors of linking.
type Module ¶
type Module struct {
// Exports are the local exports sorted by name.
Exports []Export
// BodyPC is the pc of the body after the prologue that writes the TDZ
// markers and creates the hoisted functions: linking a graph runs the
// prologue of every module before any body runs (InitializeEnvironment).
BodyPC int
// Links is nil when the module requests no other module and uses
// neither import() nor import.meta, which then evaluates without a
// module graph (a direct eval in its code alone sets ScriptOrModule
// and leaves Links nil); Requests is empty when it only uses those.
Links *Links
}
Module is what a module template records for the host and for linking (ECMA-262 §16.2.1.7 Source Text Module Records). The module Env is the top-level function's own Env, so every local binding, and every exported one, is a CaptureLayout slot.
type Op ¶
type Op uint8
Op is an opcode. Opcodes are dense so that the interpreter's switch compiles to a jump table. See doc.go for the semantics of every op.
const ( GetLen Op = iota // AB+X R[A] = R[B].length; X = ic:16 NewObject // ABx R[A] = {} with room for Bx properties LoadConst // ABx R[A] = K[Bx] Move // AB R[A] = R[B] Add // ABC R[A] = R[B] + R[C] Ret // A return R[A] Inc // AB R[A] = ToNumeric(R[B]) + 1 DefineField // AB+X R[A].name := R[B] (CreateDataProperty); X = name:16 | ic:16 Call // ABC R[A] = R[A].call(this = R[A+1], R[A+2 .. A+1+B]); C&CallUndefThis: this is undefined; C&CallOverlap: the callee's frame starts at R[A+2] // --- GetEnv of the innermost environment, without testing the depth // (GetEnv1 and GetEnv2 read the enclosing one and the one around that // without walking the chain) --- GetEnv0 // ABC GetEnv with B = 0 GetProp // AB+X R[A] = R[B].name; X = name:16 | ic:16 RetUndef // - return undefined IterNext // AsBx R[A+2] = next value of iterator R[A]; when done pc += sBx New // ABC R[A] = new R[A](R[A+2 .. A+1+B]); C&CallOverlap: the constructor's frame starts at R[A+2] GetGlobal // A+X R[A] = global[name]; ReferenceError if absent; X = name:16 | ic:16 GetGlobalOrUndef // A+X R[A] = global[name] or undefined (typeof) JmpT // AsBx if ToBoolean(R[A]) pc += sBx JmpF // AsBx if !ToBoolean(R[A]) pc += sBx Mul // ABC Jmp // sBx pc += sBx (negative offsets are back-edges: interrupt check) Eq // ABC R[A] = R[B] == R[C] Ne // ABC BitAnd // ABC BitOr // ABC BitXor // ABC Shl // ABC Shr // ABC signed >> UShr // ABC >>> // --- compare and branch (a comparison whose result only feeds a // conditional jump). The offset is relative to the X word. --- JmpLt // AsBx+X if R[A] < R[X] pc += sBx JmpLe // AsBx+X if R[A] <= R[X] pc += sBx JmpGt // AsBx+X if R[A] > R[X] pc += sBx JmpGe // AsBx+X if R[A] >= R[X] pc += sBx JmpNLt // AsBx+X if !(R[A] < R[X]) pc += sBx JmpNLe // AsBx+X if !(R[A] <= R[X]) pc += sBx JmpNGt // AsBx+X if !(R[A] > R[X]) pc += sBx JmpNGe // AsBx+X if !(R[A] >= R[X]) pc += sBx JmpStrictEq // AsBx+X if R[A] === R[X] pc += sBx JmpStrictNe // AsBx+X if R[A] !== R[X] pc += sBx GetEnv1 // ABC GetEnv with B = 1 SubImm // ABC R[A] = R[B] - int8(C) GetElem // ABC R[A] = R[B][R[C]] SetProp // AB+X R[A].name = R[B]; X = name:16 | ic:16; C = SetPropSloppy: SetPropSloppy AddImm // ABC R[A] = R[B] + int8(C) SetElem // ABC R[A][R[B]] = R[C] Closure // ABx R[A] = new function object from Children[Bx] // --- a typeof test and branch: TypeofIs and the jump on its result --- JmpTypeofIs // AsBx+X if typeof R[A] === TypeName(X) pc += sBx JmpTypeofNot // AsBx+X if typeof R[A] !== TypeName(X) pc += sBx StrictEq // ABC StrictNe // ABC CoerceThis // A this = the global object if undefined or null, else ToObject(this); R[A] = this (sloppy function entry) SetEnv // ABC env^B[C] = R[A] Throw // A throw R[A] LoadFalse // A R[A] = false // --- an update fused with the op that reads its value --- PostInc // AB ToNumeric A B, then Inc B A: a postfix ++ whose value is used LoadInt // AsBx R[A] = sBx JmpNullish // AsBx if R[A] is null or undefined GetEnv2 // ABC GetEnv with B = 2 Dec // AB R[A] = ToNumeric(R[B]) - 1 LoadNull // A R[A] = null // --- strict comparison and branch against a constant that is not a // number: JmpStrictEq and JmpStrictNe with the right operand K[X] --- JmpStrictEqK // AsBx+X if R[A] === K[X] pc += sBx JmpStrictNeK // AsBx+X if R[A] !== K[X] pc += sBx GetElemInc // ABC Inc C C, then GetElem A B C: x[++k] of a register local k GetElemRef // ABC+X R[C] = R[X], converted once; R[A] = R[B][R[C]]; X = register NewArray // ABx R[A] = [] with capacity Bx GetEnv // ABC R[A] = env^B[C] // --- compare and branch against an integer: JmpLt .. JmpStrictNe with // the right operand int32(X), in the same order --- JmpLtI // AsBx+X if R[A] < int32(X) pc += sBx JmpLeI // AsBx+X if R[A] <= int32(X) pc += sBx JmpGtI // AsBx+X if R[A] > int32(X) pc += sBx JmpGeI // AsBx+X if R[A] >= int32(X) pc += sBx JmpNLtI // AsBx+X if !(R[A] < int32(X)) pc += sBx JmpNLeI // AsBx+X if !(R[A] <= int32(X)) pc += sBx JmpNGtI // AsBx+X if !(R[A] > int32(X)) pc += sBx JmpNGeI // AsBx+X if !(R[A] >= int32(X)) pc += sBx JmpStrictEqI // AsBx+X if R[A] === int32(X) pc += sBx JmpStrictNeI // AsBx+X if R[A] !== int32(X) pc += sBx CopyEnv // - env = shallow copy of env (per-iteration bindings) JmpNotNullish // AsBx Sub // ABC Div // ABC Mod // ABC Exp // ABC R[A] = R[B] ** R[C] InstanceOf // ABC R[A] = R[B] instanceof R[C] ArrayPush // AB append R[B] to array R[A] LoadUndef // A R[A] = undefined LoadCallee // A R[A] = the running function object Not // AB R[A] = !R[B] TypeofIs // ABC R[A] = typeof R[B] === TypeName(C) SetGlobal // A+X global[name] = R[A]; ReferenceError if absent (strict function), else as SetGlobalSloppy IterInit // AB R[A], R[A+1] = iterator state over R[B] PostDec // AB ToNumeric A B, then Dec B A PushEnv // ABx env = new Env(parent env, Bx slots) LoadTrue // A R[A] = true UndefRange // AB R[A .. A+B-1] = undefined PopEnv // - env = env.parent ToStr // AB R[A] = ToString(R[B]) Lt // ABC Le // ABC Gt // ABC Ge // ABC JmpNotUndef // AsBx Concat // ABC R[A] = R[B] concatenated with R[C] (both strings) IterValue // AB R[B] = next value of iterator R[A], or undefined when done IterRest // AB R[B] = array of the remaining values of iterator R[A] IterClose // AsBx IteratorClose(R[A], normal); pc += sBx LoadThis // A R[A] = this // --- arguments.length and arguments[k] where the arguments object // R[B] may not exist yet (Function.ForwardArguments) --- ArgsLen // AB R[A] = R[B].length ArgsGet // ABC+X R[A] = R[B][R[C]] (X = 1: mapped) ForInNext // AsBx R[A+3] = next key still present on R[A+2]; when done pc += sBx // --- loads and moves --- LoadHole // A R[A] = hole (TDZ marker) // --- closure environments --- GetEnvChk // ABC+X R[A] = env^B[C]; ReferenceError if hole; X = name const GetEnvW // AB+X R[A] = env^B[X] GetEnvChkW // AB+X+X R[A] = env^B[X1]; ReferenceError if hole; X2 = name const SetEnvW // AB+X env^B[X] = R[A] CheckTDZ // A+X ReferenceError "Cannot access 'K[X]' before initialization" if R[A] is hole // --- properties --- DelProp // AB+X R[A] = delete R[B].name; X = name const DelElem // ABC R[A] = delete R[B][R[C]] In // ABC R[A] = R[B] in R[C] // --- literals --- DefineElem // ABC R[A][R[B]] := R[C] (CreateDataProperty) DefineMethod // ABC R[A][R[B]] := R[C], naming the function R[C] after the key (computed-key method) DefineAccessor // ABC+X define R[C] as the getter or setter of R[A][R[B]]; X = Accessor* flags SetProto // AB R[A].[[Prototype]] = R[B] when object or null (__proto__: v) CopyDataProps // AB copy own enumerable properties of R[B] into R[A] CopyDataPropsEx // ABC same, excluding the keys listed in array R[C] ArrayHole // A append a hole to array R[A] AppendSpread // AB append every element of iterable R[B] to array R[A] NewRegExp // ABx R[A] = new RegExp(K[Bx].pattern, K[Bx].flags) GetTemplate // A+X R[A] = template object of K[X] (GetTemplateObject); X = const:16 | ic:16 // --- arithmetic --- Neg // AB R[A] = -R[B] Plus // AB R[A] = +R[B] (ToNumber) BitNot // AB R[A] = ~R[B] ToNumeric // AB R[A] = ToNumeric(R[B]) // RequireObjectCoercible throws TypeError when R[A] is null or undefined // (destructuring through a pattern with no properties to read). RequireObjectCoercible // A Typeof // AB R[A] = typeof R[B] // --- calls --- CallSpread // A R[A] = R[A].call(this = R[A+1], ...R[A+2]) NewSpread // A R[A] = new R[A](...R[A+2]) ThrowConstAssign // +X throw TypeError("Assignment to constant variable."); X = name const // --- iteration --- IterThrow // AB IteratorClose(R[A], throw R[B]); throw R[B] ForInInit // AB R[A] = key list of R[B], R[A+1] = 0, R[A+2] = ToObject(R[B]) (or undefined) // --- classes (dispatched off the interpreter's jump table) --- CtorEntry // A R[A] = new.target; TypeError when a class constructor is called LoadNewTarget // A R[A] = new.target, or undefined in a [[Call]] LoadHome // A R[A] = [[HomeObject]] of the running function SetHome // AB [[HomeObject]] of function R[A] = R[B] CreateClass // ABC make R[A] a class constructor, R[A+1] = its prototype; C&1: R[B] is the heritage, C&2: named after key R[A+1] DefineClassMethod // ABC R[A][R[B]] := R[C] non-enumerable, [[HomeObject]] R[A] ToPropertyKey // AB R[A] = ToPropertyKey(R[B]) GetProtoOf // AB R[A] = R[B].[[GetPrototypeOf]]() (super base, super constructor) GetSuper // ABC R[A] = R[B][R[C]] with receiver R[B+1] SetSuper // ABC R[A][R[B]] = R[C] with receiver R[A+1] SuperCall // AB R[A] = Construct(R[A], R[A+2 .. A+1+B], new.target R[A+1]) SuperCallSpread // A R[A] = Construct(R[A], ...R[A+2], new.target R[A+1]) CheckSuper // A ReferenceError unless R[A] (the raw `this` binding) is hole DerivedResult // AB R[A] = result of a derived constructor returning R[A] with `this` R[B] NewPrivateName // ABx R[A] = new private name described by K[Bx] SetPrivateMethod // ABC+X private name R[A] names method R[B] owned by brand/class R[C]; X = Private* flags GetPrivate // ABC R[A] = R[B].#R[C] SetPrivate // ABC R[A].#R[B] = R[C] DefPrivate // ABC add private field #R[B] = R[C] to R[A] AddBrand // AB add class brand R[B] to R[A] InPrivate // ABC R[A] = #R[B] in R[C] ThrowError // ABx throw a new error of kind A (Throw* kinds) with message K[Bx] // --- generators (dispatched off the jump table after the class ops) --- GenFunc // A make the fresh closure R[A] a generator function GenStart // A R[A] = new generator with `this` R[A]; suspends it, and the call returns it Yield // ABC generator R[B] suspends yielding R[A] (C=1: R[A] is a result object, yielded as is); // resumed with the sent value in R[A] and the mode in R[A+1]: undefined next, true throw, false return GenIter // AB R[A] = GetIterator(R[B]) (never a fast mode), R[A+1] = its next method Delegate // AB one yield* step on the record R[B..B+1] with the value R[A] and mode R[A+1] (as Yield): // --- async functions and iteration (dispatched after the generator ops) --- AsyncFunc // A make the fresh closure R[A] an async function or async generator function AsyncStart // A unused: an async function body starts with a LoadThis (Await); the op keeps its number, by which the interpreter's jump table is laid out AsyncGenStart // A R[A] = new async generator with `this` R[A]; suspends it, and the call returns it Await // AB the frame awaits R[A] (R[B]: the async function call's this, then its state; or the async generator); resumed with R[A] = the result, R[A+1] = undefined (fulfilled) or true (rejected) AsyncReturn // AB resolve the async function call's promise (its state is R[B] once it awaited) with R[A]; R[A] = the promise AsyncThrow // AB reject the async function call's promise (its state is R[B] once it awaited) with R[A]; R[A] = the promise AsyncYield // AB async generator R[B] settles its head request with {value: R[A], done: false}; resumed as Yield AsyncIterInit // AB R[A] = GetIterator(R[B], async), R[A+1] = its next method AsyncIterNext // A R[A+2] = Call(R[A+1], R[A]) AsyncIterResult // AsBx TypeError unless R[A+2] is an object; when done pc += sBx, else R[A+2] = its value AsyncIterClose // AsBx R[A] = undefined; pc += sBx if the iterator has no return method, else R[A+2] = Call(return, iterator) AsyncIterClosed // A TypeError unless the awaited return result R[A+2] is an object AsyncDelegate // ABC one async yield* step on the record R[B..B+2] with value R[A] and mode R[A+1] (C=0 call, C=1 result) // --- modules --- GetImport // ABC+X R[A] = the binding env^B[C] refers to; ReferenceError if hole; X = name const GetImportW // AB+X+X R[A] = the binding env^B[X1] refers to; ReferenceError if hole; X2 = name const ImportCall // AB R[A] = import(R[B]): a promise for the namespace of the module the host loads for it ImportMeta // A R[A] = import.meta of the running script or module's root // --- sloppy mode, script globals and with (dispatched after the async ops) --- SetGlobalSloppy // A+X global[name] = R[A] in sloppy mode: creates an unresolvable name, a rejected write is ignored; X = name:16 | ic:16 ResolveGlobal // A+X R[A] = whether the global environment has a binding name (strict, before the value of an assignment); X = name:16 | ic:16 SetGlobalRef // AB+X global binding name = R[A] (strict) when R[B], ResolveGlobal's result, else ReferenceError; X = name:16 | ic:16 (ResolveGlobal's) InitGlobal // A+X initialize the script's global lexical binding name to R[A]; X = name:16 | const<<16 SetGlobalVar // A+X Annex B.3.2.2: global[name] = R[A] (sloppy) unless a global lexical binding name exists; X = name const DelGlobal // A+X R[A] = delete of the global binding name (false for a global lexical); X = name const SetPropSloppy // AB+X R[A].name = R[B], a rejected assignment ignored; X = name:16 | ic:16 SetElemSloppy // ABC R[A][R[B]] = R[C], a rejected assignment ignored DelPropSloppy // AB+X R[A] = delete R[B].name, false when rejected; X = name const DelElemSloppy // ABC R[A] = delete R[B][R[C]], false when rejected SetSuperSloppy // ABC R[A][R[B]] = R[C] with receiver R[A+1], a rejected assignment ignored ToObject // AB R[A] = ToObject(R[B]) (the with statement's object, DefineField's instance in initializers and eval code) JmpWith // AsBx+X pc += sBx if the with object R[A] has a binding name (HasProperty, not @@unscopables-blocked); X = name const WithGet // AB+X R[A] = binding name of the with object R[B]; X = name:16 | strict<<16 WithSet // AB+X set binding name of the with object R[A] to R[B]; X = name:16 | strict<<16 MapArguments // AB make the arguments object R[A] mapped to the parameters in the function's own Env (B = 1: lazily, no parameter is assigned) CallEval // ABC+X R[A] = call of callee R[A] with this R[A+1] and args R[A+2..] (B = argc, C = 1: one spread array), a direct eval when the callee is %eval%; X = index into Extra.Evals // --- the first of a switch's cases on constants that test R[A] in a row --- JmpCaseK // AsBx+X JmpStrictEqK, then each JmpStrictEqK after it that tests R[A] // --- a call that may need no object --- RegExpTest // AsBx+X R[A] = /K[X.lo]/.test(R[X.hi]) and pc += sBx when no code could see the literal's object; else on to the call // --- f.apply(x, arguments) where the arguments object R[B] may not // exist yet (Function.ForwardArguments) --- ApplyArguments // ABC R[A] = Call R[A] with this R[A+1] and arguments R[A+2], R[B] (C = 1: mapped) // --- a run of an array literal's elements that are constants --- ArrayPushK // A+X append K[X.lo] .. K[X.lo+X.hi-1] to array R[A] // --- an array literal whose elements are all constants --- NewArrayK // A+X R[A] = [K[X.lo], .., K[X.lo+X.hi-1]] // --- an object literal of data properties with static keys, made at // once from the values its properties evaluated to --- NewObjectLit // ABC+X R[A] = {K[X.lo]: R[B], .., K[X.lo+C-1]: R[B+C-1]}; X = key:16 | ic:16 )
Instruction formats. Every instruction is one 32-bit word:
ABC : op:8 | A:8 | B:8 | C:8 ABx : op:8 | A:8 | Bx:16 (Bx unsigned) AsBx: op:8 | A:8 | sBx:16 (sBx signed, jump offset relative to the next pc)
Ops marked "+X" in doc.go are followed by one ExtraArg word (a raw uint32) whose layout is given per op; a few use two.
func CompareJump ¶
CompareJump returns the op that jumps when the comparison op (Lt, Le, Gt, Ge, StrictEq or StrictNe) of R[A] and R[X] is jumpIf, and false for any other op.
func (Op) Constant ¶
Constant returns the form of JmpStrictEq or JmpStrictNe whose right operand is the constant the X word names instead of a register.
func (Op) ExtraWords ¶
ExtraWords returns how many ExtraArg words follow an instruction of op.
func (Op) Immediate ¶
Immediate returns the form of the compare-and-branch op (JmpLt .. JmpStrictNe) whose right operand is the integer in the X word instead of a register.
func (Op) Jumps ¶
Jumps reports whether an instruction of op may continue at the pc its sBx operand names (JumpTarget) instead of the next instruction: Jmp, the conditional and compare-and-branch jumps, and the iteration and with ops that branch (IterNext, IterClose, ForInNext, AsyncIterResult, AsyncIterClose, JmpWith). LoadInt's sBx is a value.
func (Op) SavesPC ¶
SavesPC reports whether the engine may run a frame again from the instruction after one of op: a suspension saves that pc to resume at (GenStart, Yield, AsyncGenStart, Await, AsyncYield), and CoerceThis and CallEval may rerun the frame from it. The engine stores it with the frame's environment depth above PCBits.
type Reexport ¶
type Reexport struct {
Name string // the exported name
Request int
Import string // the imported name (unset when All)
All bool
Line, Col int32
}
Reexport is an indirect export.
type RegKind ¶
type RegKind uint8
RegKind is a kind of value the verifier proves a register holds where an op reads it as that kind without looking (KindOperands).
type SourceInfo ¶
type SourceInfo struct {
Name string // file name used in stack traces
Src string // full module/script source text
Start int // byte offset of the function's first character
End int // byte offset one past the function's last character
}
SourceInfo locates a function template inside its source file. Function.prototype.toString slices Src[Start:End].