ECMA-262 in Lean

Reading page · generated from spec/spectec/prose/10-host.spectec and spec/spectec/prose/*-host-laws*.spectec

The host and its laws

What the specification leaves to the host (§4.2), and the 72 SpecTec laws it requires of one, by topic, restricted to the transitive closure of Host and Host.WF. Each object and law names its clause, quotes the sentence that governs it, and says how SpecTec reads it (4 have no single sentence and say why). Auxiliary definitions are folded and expand on click.

The host

From spec/spectec/prose/10-host.spectec

What the specification leaves to the host (Host): the host-defined and implementation-defined operations, by clause, and its choices at the points the specification names, by primitive. Every call of the host is logged in State.hostLog: the host reads the state and the log, and only the machine appends to the log. The laws a host must meet are Host.WF.

syntax record

Host

10-host.spectec:18

The host (§2, sec-conformance; §4.2, sec-hosts-and-implementations): the operations the specification leaves to it (host-defined and implementation-defined operations, by clause), and its choices at the points the specification names (implementation-approximated values, implementation-defined choices, whether it is a web browser), by primitive, and its choice of integers.

syntax Host (M : Model) record

the next job to run (§9.5): the log position of the call that scheduled it, or none

nextJob : Run(M, Option(Nat)) := Run.stop(.residue);

the jobs the host may take in this state, by their scheduling's log position: the surrounding agent's, ready now

owns : State(M) -> Nat -> Bool := fun _ _ => true;

the milliseconds elapsed by the host's own clock as it takes its next job in this state; unlike TimeNow's time value it never goes back (Host.WF.elapsedMono)

elapsed : State(M) -> M.Math := fun _ => M.ofNat(0);

the host-defined preparation steps of a job, by that position

prepareJob : Nat -> Run(M, Unit) := fun _ => Run.stop(.residue);

the host-defined cleanup steps of a job, by that position

cleanupJob : Nat -> Run(M, Unit) := fun _ => Run.stop(.residue);

what the host does when the agent has no Job to run (§9.5 leaves the scheduling to the host, §9.7 the other agents of the cluster): an algorithm of its own to run as one, its preparation done, after which the agent's Jobs go on unless it answers empty; or none, and the agent's Jobs are done

idle : Run(M, Option(AlgId)) := pure(none);

a Job of the host's own that the agent runs before its next queued one (§9.6: its scripts and modules): an algorithm of the host's and its arguments, its preparation done; or none

first : Run(M, Option(AlgId times List(Val(M)))) := pure(none);

the host-defined cleanup steps after first's or idle's algorithm, given what it returned: none where the agent's Jobs are done; else whether it ran ECMAScript code, so that ClearKeptObjects and the host's collection follow as after a Job (§9.10)

idleEnd : Val(M) -> Run(M, Option(Bool)) := fun _ => pure(none);

whether the host performs ClearKeptObjects (§9.10) now, a synchronous run of ECMAScript code having ended (§9.9.1 leaves its scheduling to the host)

clearsKept : Run(M, Bool) := Run.stop(.residue);

the objects and symbols the host collects at a job boundary (§9.10.3), having emptied their WeakRefs and cells (Host.WF.collect); none by default

collect : Run(M, List(Val(M))) := pure([]);

whether the host's resources run out at pushing an execution context in this state

exhausts : State(M) -> Bool := fun _ => false;

whether the host's resources run out at allocating an object (MakeBasicObject) in this state

exhaustsHeap : State(M) -> Bool := fun _ => false;
Auxiliary definition: activeScriptOrModule
def

activeScriptOrModule

10-host.spectec:89

The active script or module (§9.4.1): the ScriptOrModule of the topmost execution context that has a non-null one, else null.

def activeScriptOrModule (s : State(M)) : Val(M) := M.seqFoldl(fun r ctx => match ctx with  | .ref(a) => match M.heapGet(s.heap, a) with      | some(.record(_, fs)) => match M.recGet(fs, Known.fScriptOrModule) with          | some(.null) | none => r          | some(v) => v        end      | _ => r    end  | _ => rend, .null, s.stack)

The laws of a host

From spec/spectec/prose/26-host-laws.spectec

What the specification requires of the host, stated over a Host and never assumed: a law constrains what one call of the host gives, given the state and the host-call log (State.hostLog) before it. The machine owns the log: a host reads it, and a host step adds only its own entry. Each law is a field of the structure of its topic (Ecma/Host/Laws/), and its docstring says the clause of the specification it reads, quotes the sentence that governs it, and gives its reading (scripts/law_quotes.py checks the quotations against spec.html).

laws

Host.WF

26-host-laws.spectec:23

The laws of a host (§2, sec-conformance; §4.2, sec-hosts-and-implementations): those of every topic.

Proved of the engine's host under every option set: Engine.SpecHost.wfBy, which is Implements.host.

laws Host.WF {M : Model} (H : Host(M)) extends [H.JobLaws, H.TimeLaws, H.MemoryLaws, H.RegExpLaws, H.OrderLaws, H.LocaleLaws, H.OptionalLaws, H.ValueLaws, H.HookLaws, H.ChangeLaws] {}

All 72 laws

Each law is a law declaration in the SpecTec laws block of its topic, and Host.WF extends all of them. Two read their sentence more strictly than it is written, and are for the list of proposed normative changes; two more weakly:

  • escapePattern stricter requires \/ and the line terminators' escapes, where the text also allows an unescaped / in a character class.
  • nativeFunctionSource stricter one ASCII form, function name() { [native code] }, where the text allows any NativeFunction.
  • collect weaker approximates liveness by syntactic heap reachability at job boundaries (omitting future-execution observability and cleanup-job scheduling guarantees).
  • agentNextJob weaker there is no law about a timeout.
LawTopicClauseReading
nextJobJob9.5 Jobs and Host Operations to Enqueue JobsThe job the host takes next is one it may take now (Host.mayRun), each taken once.
agentNextJob
weaker
Job9.5 Jobs and Host Operations to Enqueue JobsAgentNextJob answers empty or a job it may take now (Host.mayRun), the state as it was.
ownsAgentJob9.5 Jobs and Host Operations to Enqueue JobsWith more than one agent in the cluster, a job the host may take is the surrounding agent's.
ownsSingleJob9.5 Jobs and Host Operations to Enqueue JobsWith one agent in the cluster, the host may take every scheduled job, so that none is left when its Jobs are done (drained).
promiseJobPreparedJob9.5.5 HostEnqueuePromiseJobThe host's preparation of a promise job whose realm is not null does both (promisePrepared).
agentPrepareJobJob9.5 Jobs and Host Operations to Enqueue JobsAgentPrepareJob(k) answers the job scheduled at k, prepared as promisePrepared says.
jobCleanupJob9.5 Jobs and Host Operations to Enqueue JobsAfter a job's cleanup the execution context stack is empty.
agentCleanupJobJob9.5 Jobs and Host Operations to Enqueue JobsAgentCleanupJob answers unused and leaves the agent's execution context stack empty.
jobCallbackDefaultJob9.5.2 HostMakeJobCallbackWhere the host answers that it is not a web browser, HostJobCallbackData answers empty and the steps around the callback's call unused, the state as it was.
callJobCallbackJob9.5.3 HostCallJobCallbackThe host's steps before and after the call answer unused, so the call's result is returned.
selectAgentJob9.8 Forward ProgressHostSelectAgent answers empty or another Agent Record of the cluster that can run (canRunAgent), the state as it was.
timeNowTime21.4.3.1 Date.nowTimeNow answers a time value identifying an instant (instantTimeValue), the state as it was.
elapsedMonoTimeNo sentenceAs the host takes its next job, its clock reads no less than any elapsed time logged.
timeoutAfterTime9.5.6 HostEnqueueTimeoutJobAs the host takes a timeout job, its clock reads at least milliseconds past the elapsed time logged before the call that scheduled it.
additionalTimeoutTime25.4.3.14 DoWaitAdditionalTimeout answers a non-negative mathematical value, the state as it was.
timeZoneNameSuffixTime21.4.4.41.3 TimeZoneStringTimeZoneNameSuffix answers "" or " (" name ")", the state as it was.
systemTimeZoneStringTime21.4.1.24 SystemTimeZoneIdentifierSystemTimeZoneString answers "UTC", an available named time zone identifier whose IsNonPrimaryTimeZoneId is false, or a String UTCOffset matches (utcOffsetNs), the state as it was.
primaryTimeZoneIdTime21.4.1.23 AvailableNamedTimeZoneIdentifiersPrimaryTimeZoneId answers "UTC" or an available named time zone identifier whose IsNonPrimaryTimeZoneId is false, the state as it was.
supportsOnlyUTCTime21.4.1.24 SystemTimeZoneIdentifierSupportsOnlyUTC answers a Boolean, the state as it was.
parseDateStringTime21.4.3.2 Date.parseParseDateString answers NaN or a time value (instantTimeValue), never -0𝔽, the state as it was.
dateFormUTCTime21.4.3.2 Date.parseA valid String of the format that is no local time gives the time value of its fields less its offset, NaN out of a time value's range (sec-expanded-years).
dateFormLocalTime21.4.3.2 Date.parseA valid date-time form without an offset gives UTC of its fields (sec-utc-t): the fields themselves where the system time zone is "UTC", less the offset where it is an offset time zone.
dateFormIllegalTime21.4.3.2 Date.parseA String of the format's shape with an out-of-bounds element gives NaN.
expandedYearFormTime21.4.4.36 Date.prototype.toISOStringExpandedYearForm, whether a year from 0 to 9999 is written as an expanded year, answers a Boolean, the state as it was.
nanEncodingMemory25.1.3.17 NumericToRawBytesFor a NaN and a format with a trailing significand field (2 ≤ p), NaNEncoding answers one NaN bit pattern of the format in every state, the state as it was.
canAllocateMemory6.2.9.1 CreateByteDataBlockCanAllocate, whether such a Data Block can be created, answers a Boolean, the state as it was.
resizeArrayBufferMemory25.1.3.8 HostResizeArrayBufferbuffer's [[ArrayBufferData]] does not become null; on handled its [[ArrayBufferByteLength]] is newByteLength.
omitSharedArrayBufferMemory25.2.3 The SharedArrayBuffer ConstructorOmitSharedArrayBuffer is one Boolean in every state, the state as it was.
spinWaitHintMemory25.4.12 Atomics.pauseSpinWaitHint answers unused, the state as it was.
chooseReadsBytesFromMemory25.1.3.15 GetRawBytesFromSharedBlockChooseReadsBytesFrom(execution, eventsRecord, block, byteIndex, elementSize) answers a new List of elementSize events of execution, the one at index i a write event on block whose memory range contains byteIndex + i; the state as it was but for the new List.
chooseReadsValidMemory29.7.5 Valid ExecutionsWhere execution is a valid execution whose memory order agrees with the interleaving order and whose Shared Data Block events are formed, it stays one with the read appended to eventsRecord, reading the chosen events.
escapePattern
stricter
RegExp22.2.6.13.1 EscapeRegExpPatternEscapePattern answers a String S, the same for the same pattern and flags at every call, the state as it was: pattern with each / kept or written \/ and each LineTerminator written as its escape, the empty pattern as (?:) (EscapeOf), which as far as / and LineTerminators go can be a RegularExpressionBody (BodySafe). That S "must behave identically" is the specification's claim about its own semantics, no law: it was proved of this engine's escape at the git tag escape-sim-proved.
sortStepOrder23.1.3.30.1 SortIndexedPropertiesAt the host's state and the last result a sort of n elements reaches by the calls h, SortStep asks for a call on two indices less than n, or answers a permutation that, for every consistent comparator giving every result in h, meets its conditions; otherwise the order is the host's.
sortStepEndsOrder23.1.3.30.1 SortIndexedPropertiesThe sequence is finite: a sort makes finitely many calls, whatever their results.
forInStepOrder14.7.5.9 EnumerateObjectPropertiesAfter a history that obeyed the rules (ForInRun), ForInStep answers an action that obeys them (ForInRules); and CreateForInIterator(obj)'s next action where no object of the chain is exotic, none changed shape since the enumeration began (State.shapeLog), and every action so far was its.
propertyOrderOrder9.3.2 CreateIntrinsicsPropertyOrder, the order an intrinsic's properties are created in, answers a new List of the given properties, each once.
listSeparatorLocale23.1.3.32.1 LocalizedListSeparatorLocalizedListSeparator answers a String, the state as it was.
localeCaseLocale22.1.3.26 String.prototype.toLocaleLowerCaseLocaleLowercase and LocaleUppercase answer a new List of code points.
localeCompareLocale22.1.3.12 String.prototype.localeCompareBy one total preorder of all Strings, LocaleCompare answers a negative, positive or zero Number, never NaN, and +0𝔽 for canonically equivalent Strings, the state as it was.
localeNumberStringLocale21.1.3.4 Number.prototype.toLocaleStringLocaleNumberString answers a String, or empty for toString's, the state as it was.
localeDateStringLocale21.4.4.38 Date.prototype.toLocaleDateStringLocaleDateString answers a String, or empty for the form without a locale, for an object with a [[DateValue]] slot, and a String or throw (a TypeError) for any other value, the state as it was.
webBrowserOptionalB Additional ECMAScript Features for Web BrowsersWebBrowser, whether the host is a web browser or otherwise supports the feature its arguments name, is one Boolean for the same arguments in every state, the state as it was.
webBrowserSupportsOptionalB Additional ECMAScript Features for Web BrowsersWhere the host is a web browser, it is a web browser or otherwise supports every clause c.
debuggerEnabledOptional14.16.1 Runtime Semantics: EvaluationDebuggerEnabled answers a Boolean, the state as it was.
debuggerActionOptional14.16.1 Runtime Semantics: EvaluationDebuggerAction answers unused; what it may change is invariantsKept's.
nativeFunctionSource
stricter
Optional20.2.3.5 Function.prototype.toStringNativeFunctionSource answers function , a name nativeName admits and () { [native code] }, the name func.[[InitialName]] where that is a String, the state as it was.
approxValue21.3.2.9 Math.cbrtApprox answers a Number, the state as it was.
approxPowerValue6.1.6.1.3 Number::exponentiateApproxPower(base, exponent) answers a Number, the state as it was.
approxIntegerValue19.2.5 parseIntApproxInteger answers an integer, the state as it was.
bigIntTooLargeValueNo sentenceBigIntTooLarge answers a Boolean, the state as it was.
stringTooLargeValueNo sentenceStringTooLarge answers a Boolean, the state as it was.
hostChoiceValue7.1.4.1.3 RoundMVResultHostChoice answers one of its arguments, the state as it was.
mathRandomValue21.3.2.28 Math.randomMath.random answers such a Number (unitNum), never an abrupt completion, the state as it was.
hookCompletionHook4.2 Hosts and ImplementationsA host hook's answer is no break, continue or return completion (a value that is no Completion Record is a normal completion's).
privateElementSameKindHook7.3.29 HostEnsureCanAddPrivateElementThe [[Type]] of HostEnsureCanAddPrivateElement's answer is one function of its argument, whatever the state of the call.
supportedImportAttributesHook16.2.1.12.1 HostGetSupportedImportAttributesEvery call answers a List of the same Strings in the same order (the default's new empty List at each call conforms, so "the same List" is its contents).
getCodeForEvalHook19.2.1.3 HostGetCodeForEvalHostGetCodeForEval answers a String or no-code.
hasSourceTextAvailableHook20.2.5 HostHasSourceTextAvailableHostHasSourceTextAvailable's answer is one function of its argument, whatever the state of the call.
invariantsKeptChange6.1.7.3 Invariants of the Essential Internal MethodsAcross a host step every object is still an object and keeps to the invariants (objKept).
agentFixedChange9.6 AgentsA host step keeps the surrounding agent, its Agent Record's sort and those fields (agentKept).
hostGlobalObjectChange9.3.1 InitializeHostDefinedRealmHostGlobalObject answers empty (the state as it was) or an Object.
hostThisValueChange9.3.1 InitializeHostDefinedRealmHostThisValue answers empty (the state as it was) or an Object.
hostGlobalPropertiesChange9.3.1 InitializeHostDefinedRealmHostGlobalProperties answers unused and changes only global's own properties (onlyPropsOf).
hostExtendIntrinsicsChange2 ConformanceHostExtendIntrinsics(realm) answers unused and only adds own properties to realm's intrinsics (intrinsicOf), none to an object whose [[Extensible]] is not true, and no "caller" or "arguments" to a function.
hostExtendObjectChange2 ConformanceHostExtendObject(o) answers unused and only adds own properties to o, none if its [[Extensible]] is not true, and no "caller" or "arguments" to a function.
hostInitializeBuiltinContextChange10.3.3 BuiltinCallOrConstructHostInitializeBuiltinContext answers unused and changes only calleeContext, which keeps its kind and every component the execution context tables define (contextField).
hostReportCleanupErrorChange9.9.4.1 HostEnqueueFinalizationRegistryCleanupJobHostReportCleanupError answers unused.
hostReportErrorsChangeNo sentenceHostReportErrors answers unused.
mayCleanupChange9.12 CleanupFinalizationRegistryMayCleanup answers empty or such a cell (emptyCell), the state as it was.
discardContextResourcesChange15.10.3 PrepareForTailCallDiscardContextResources answers unused, the state as it was.
contextResourcesChange15.10.3 PrepareForTailCallThe host's resources run out at a push onto the execution context stack (Host.exhausts) only while some context on it holds resources no DiscardContextResources discarded (liveContexts).
collect
weaker
Change9.9.3 ExecutionThe host's collection empties, together, the WeakRefs, FinalizationRegistry cells, WeakMap entries and WeakSet elements of a set of objects and Symbols none of which is kept alive, and changes nothing else (Collected); a host that collects nothing meets it.

The laws of jobs and agents

From spec/spectec/prose/16-host-laws-jobs.spectec

Which job the host takes next, its preparation and cleanup, the job callbacks, and which agent runs (sec-jobs, sec-agents, sec-forward-progress). A job is named by the log position of the call that scheduled it. The host takes jobs through two interfaces, Host.nextJob/prepareJob/cleanupJob for the surrounding agent and the choices AgentNextJob, AgentPrepareJob and AgentCleanupJob for an agent of a cluster; one set of requirements (Host.mayRun, promisePrepared) governs both.

Auxiliary definitions (12): wakeFinite, pendingFinite, hasScheduledJob, canRunAgent, …
def

wakeFinite

16-host-laws-jobs.spectec:14

Whether SuspendAgentUntil's timeout wakes within maxTime.

def wakeFinite {M : Model} : List(Val(M)) -> Bool  | [_, .math(t)] => !M.lt(M.ofNat(maxTime), t)  | _ => falseend
def

pendingFinite

16-host-laws-jobs.spectec:21

The agent x's pending suspension in a log with agents: whether its wake time is finite (wakeFinite), or none if it is not suspended or a newer WakeAgent woke its signifier sig.

def pendingFinite {M : Model} (x sig : Val(M)) : List(HostCall(M) times Val(M)) -> Option(Bool)  | [] => none  | (.choice(q, vs, _), a) :: es => if q == Known.pWakeAgent && vs.any(Val.same(sig)) then none else if q == Known.pSuspendAgentUntil && Val.same(a, x) then some(wakeFinite(vs)) else pendingFinite(x, sig, es)  | _ :: es => pendingFinite(x, sig, es)end
def

hasScheduledJob

16-host-laws-jobs.spectec:28

Whether the agent x has a job scheduled in the log that has not been taken.

def hasScheduledJob {M : Model} (s : State(M)) (x : Val(M)) : Bool := let ags := jobAgents(s) in s.hostLog.reverse.zipIdx.any(fun (e, k) => e.schedulesJob && ags[k]?.any(Val.same(sigOf(s, x))) && !s.hostLog.any(fun _dot0 => _dot0.takes(k)))
def

canRunAgent

16-host-laws-jobs.spectec:32

Whether the agent x can run: it is not suspended with an infinite timeout, or it waits for a message or a job (idleWait) and has a scheduled job (hasScheduledJob).

def canRunAgent {M : Model} (s : State(M)) (x : Val(M)) : Bool := pendingFinite(x, sigOf(s, x), withAgents(s.agent, s.hostLog)).getD(true) || idleWait(s, x) && hasScheduledJob(s, x)
def

HostCall.callOf

16-host-laws-jobs.spectec:37

A logged call is one of the host-defined operation with that sec-… clause id.

def HostCall.callOf (sec : String) : HostCall(M) -> Bool  | .hook(c, _, _, _, _) => Gen.clauses[c]? == some(sec)  | _ => falseend
def

calledAt

16-host-laws-jobs.spectec:43

The call at log position k (counted from the first) is one of the host-defined operation sec.

def calledAt (log : List(HostCall(M))) (sec : String) (k : Nat) : Prop := log.reverse[k]?.any(fun _dot0 => _dot0.callOf(sec)) = true
def

taken

16-host-laws-jobs.spectec:46

The job scheduled at log position k has been taken to run.

def taken (log : List(HostCall(M))) (k : Nat) : Prop := log.any(fun _dot0 => _dot0.takes(k)) = true
def

jobHooks

16-host-laws-jobs.spectec:50
def jobHooks : List(String) := ["sec-hostenqueuegenericjob", "sec-hostenqueuepromisejob", "sec-hostenqueuetimeoutjob", "sec-host-cleanup-finalization-registry"]
def

Host.mayRun

16-host-laws-jobs.spectec:55

The job scheduled at log position k may be taken now: a HostEnqueue…Job call scheduled it, it has not been taken, the host may take it (Host.owns), and a promise job only after every earlier-scheduled promise job the host may take.

def Host.mayRun (H : Host(M)) (s : State(M)) (k : Nat) : Prop := (exists sec mem jobHooks, calledAt(s.hostLog, sec, k)) /\ not taken(s.hostLog, k) /\ H.owns(s, k) = true /\ (calledAt(s.hostLog, "sec-hostenqueuepromisejob", k) -> (forall i < k, calledAt(s.hostLog, "sec-hostenqueuepromisejob", i) -> H.owns(s, i) = true -> taken(s.hostLog, i)))
def

preparedToEvaluate

16-host-laws-jobs.spectec:59

An execution is prepared to evaluate ECMAScript code (sec-jobs): the execution context stack is not empty, and the Realm component of its topmost execution context is a Realm Record.

def preparedToEvaluate (s : State(M)) : Prop := M.eq(M.seqLen(s.stack), M.ofNat(0)) = false /\ exists pre top r, stackList(s) = pre ++ [top] /\ fieldOf(s, Known.fRealm, top) = some(r) /\ isRecordOf(s, "Realm Record", r) = true
def

activeIs

16-host-laws-jobs.spectec:64

sm is the active script or module (sec-jobs): GetActiveScriptOrModule() is sm, and if sm is a Script Record or Module Record, the Realm component of the topmost execution context whose ScriptOrModule component is sm is sm.[[Realm]].

def activeIs (s : State(M)) (sm : Val(M)) : Prop := activeScriptOrModule(s) = sm /\ (isRecordOf(s, "Script Record", sm) = true \/ isRecordOf(s, "Module Record", sm) = true -> (exists pre ec post, stackList(s) = pre ++ ec :: post /\ fieldOf(s, Known.fScriptOrModule, ec) = some(sm) /\ (forall c mem post, fieldOf(s, Known.fScriptOrModule, c) <> some(sm)) /\ exists r, fieldOf(s, Known.fRealm, ec) = some(r) /\ fieldOf(s, Known.fRealm, sm) = some(r)))
def

promisePrepared

16-host-laws-jobs.spectec:69

After the preparation of the job scheduled at log position k, from s to s': where a HostEnqueuePromiseJob call whose realm is not null scheduled it, execution is prepared to evaluate ECMAScript code, and the script or module active at that call is active.

def promisePrepared (s : State(M)) (k : Nat) (s' : State(M)) : Prop := forall c job realm xs sm rl r, s.hostLog.reverse[k]? = some(.hook(c, job :: realm :: xs, sm, rl, r)) -> Gen.clauses[c]? = some("sec-hostenqueuepromisejob") -> realm <> .null -> preparedToEvaluate(s') /\ activeIs(s', sm)
laws

Host.JobLaws

16-host-laws-jobs.spectec:72

The laws of jobs and agents (§9.5, sec-jobs; §9.6, sec-agents).

Proved as part of Host.WF.

laws Host.JobLaws (H : Host(M))

11 laws

9.5 Jobs and Host Operations to Enqueue Jobs the requirements' first item sec-jobs

At some future point in time, when there is no running context in the agent for which the job is scheduled and that agent's execution context stack is empty, the implementation must: … Invoke the Job Abstract Closure.

9.5.5 HostEnqueuePromiseJob sec-hostenqueuepromisejob

Jobs must run in the same order as the HostEnqueuePromiseJob invocations that scheduled them.

The job the host takes next is one it may take now (Host.mayRun), each taken once.

nextJob
SpecTec
law nextJob : forall s k s', H.nextJob(s) = .ok(some(k), s') -> H.mayRun(s, k);
9.5 Jobs and Host Operations to Enqueue Jobs the requirements' first item, in an agent of a cluster sec-jobs

At some future point in time, when there is no running context in the agent for which the job is scheduled and that agent's execution context stack is empty, the implementation must: … Invoke the Job Abstract Closure.

9.5 Jobs and Host Operations to Enqueue Jobs the requirements' first item sec-jobs

in the agent for which the job is scheduled

9.5 Jobs and Host Operations to Enqueue Jobs the requirements' first item sec-jobs

At some future point in time, when there is no running context in the agent for which the job is scheduled and that agent's execution context stack is empty, the implementation must:

With one agent in the cluster, the host may take every scheduled job, so that none is left when its Jobs are done (drained).

ownsSingle
SpecTec
law ownsSingle : forall s k, clusterSigs(s).length <= 1 -> (exists sec mem jobHooks, calledAt(s.hostLog, sec, k)) -> H.owns(s, k) = true;
9.5.5 HostEnqueuePromiseJob the requirements sec-hostenqueuepromisejob

If realm is not null, each time job is invoked the implementation must perform implementation-defined steps such that execution is prepared to evaluate ECMAScript code at the time of job's invocation.

If realm is not null, each time job is invoked the implementation must perform implementation-defined steps such that scriptOrModule is the active script or module at the time of job's invocation.

9.5 Jobs and Host Operations to Enqueue Jobs the requirements' first item, in an agent of a cluster sec-jobs

Perform any host-defined preparation steps. Invoke the Job Abstract Closure.

9.5.5 HostEnqueuePromiseJob sec-hostenqueuepromisejob

each time job is invoked the implementation must perform implementation-defined steps such that execution is prepared to evaluate ECMAScript code at the time of job's invocation

9.5 Jobs and Host Operations to Enqueue Jobs the requirements' first item sec-jobs

Perform any host-defined cleanup steps, after which the execution context stack must be empty.

9.5 Jobs and Host Operations to Enqueue Jobs the requirements' first item, in an agent of a cluster sec-jobs

Perform any host-defined cleanup steps, after which the execution context stack must be empty.

9.5.2 HostMakeJobCallback sec-hostmakejobcallback

ECMAScript hosts that are not web browsers must use the default implementation of HostMakeJobCallback.

9.5.3 HostCallJobCallback sec-hostcalljobcallback

ECMAScript hosts that are not web browsers must use the default implementation of HostCallJobCallback.

Where the host answers that it is not a web browser, HostJobCallbackData answers empty and the steps around the callback's call unused, the state as it was.

jobCallbackDefault
SpecTec
law jobCallbackDefault : forall q vs s r s', H.choice(Known.pWebBrowser, [.choice(1), .absent], s) = .ok(.bool(false), s) -> q mem [Known.pHostJobCallbackData, Known.pHostPrepareCallJobCallback, Known.pHostCleanupCallJobCallback] -> Run.boundary(H.choice(q, vs), s) = .ok(r, s') -> s' = s /\ r = .enum(if q = Known.pHostJobCallbackData then Known.eEmpty else Known.eUnused);
9.5.3 HostCallJobCallback the requirements sec-hostcalljobcallback

It must perform and return the result of Call(jobCallback.[[Callback]], thisValue, argList).

9.8 Forward Progress sec-forward-progress

in a set of agents that share an executing thread, one agent eventually makes forward progress

The laws of time and dates

From spec/spectec/prose/17-host-laws-time.spectec

The host's clock, its time zone and Date.parse (sec-time-values-and-time-range, sec-systemtimezoneidentifier, sec-date.parse). The model has no local political rules for any time zone: GetNamedTimeZoneOffsetNanoseconds and GetNamedTimeZoneEpochNanoseconds run their default implementations, so "UTC" is the one available named time zone, and the system time zone is it or an offset time zone.

Auxiliary definitions (6): instantTimeValue, timeZoneNameSuffix, digits2, fractionNs, …
def

instantTimeValue

17-host-laws-time.spectec:16

n is a time value identifying an instant: a finite integral Number from -8.64 × 10^15 to 8.64 × 10^15 (sec-time-values-and-time-range).

def instantTimeValue (n : M.Num) : Prop := M.numView(n) = .posZero \/ M.numView(n) = .negZero \/ exists m, M.numView(n) = .finite(m) /\ M.isInt(m) = true /\ M.lt(m, M.neg(M.ofNat(maxTime))) = false /\ M.lt(M.ofNat(maxTime), m) = false
def

timeZoneNameSuffix

17-host-laws-time.spectec:19

x is the empty String, or " (" then a time zone name then ")" (TimeZoneString step 9).

def timeZoneNameSuffix (x : M.Str) : Prop := M.strEq(x, M.strLit("")) = true \/ exists n, M.strEq(x, M.strConcat(M.strLit(" ("), M.strConcat(n, M.strLit(")")))) = true
def

digits2

17-host-laws-time.spectec:22

Two decimal digits at the front of l: their value and the rest.

def digits2 : List(Nat) -> Option(Nat times List(Nat))  | a :: b :: l => if 48 <= a /\ a <= 57 /\ 48 <= b /\ b <= 57 then some(((a - 48) * 10 + (b - 48), l)) else none  | _ => noneend
def

fractionNs

17-host-laws-time.spectec:28

A TemporalDecimalFraction's 1 to 9 digits as nanoseconds.

def fractionNs (ds : List(Nat)) : Option(Nat) := if 1 <= ds.length /\ ds.length <= 9 /\ ds.all(fun c => 48 <= c /\ c <= 57) then some((ds ++ List.replicate(9 - ds.length, 48)).foldl(fun a c => a * 10 + (c - 48), 0)) else none
def

utcOffsetNs

17-host-laws-time.spectec:33

ParseTimeZoneOffsetString of a String UTCOffset matches, by its code units: its sign, Hour, MinuteSeconds (the TimeSeparators all ":" or all empty) and fraction as nanoseconds; none where UTCOffset does not match (IsTimeZoneOffsetString is false).

SpecTec, 36 lines
def utcOffsetNs : List(Nat) -> Option(Int)  | [] => none  | c :: l => do {      let sign : Int <- if c = 43 then some(1) else if c = 45 then some(-1) else none;      let (h, l) <- digits2(l);      guard(h <= 23);      let ns <- match l with        | [] => some(0)        | l => do {            let (ext, l) := match l with              | 58 :: l => (true, l)              | l => (false, l)            end;            let (mi, l) <- digits2(l);            guard(mi <= 59);            match l with              | [] => some(mi * 60 * 10 ^ 9)              | l => do {                  let l <- if ext then match l with                    | 58 :: l => some(l)                    | _ => none                  end else some(l);                  let (sc, l) <- digits2(l);                  guard(sc <= 59);                  let f <- match l with                    | [] => some(0)                    | c :: ds => if c = 46 \/ c = 44 then fractionNs(ds) else none                  end;                  some((mi * 60 + sc) * 10 ^ 9 + f);                }            end;          }      end;      return sign * ((h * 3600 * 10 ^ 9 + ns : Nat) : Int);    }end
def

sysTimeZone

17-host-laws-time.spectec:72

SystemTimeZoneIdentifier() at s is id: "UTC" where SupportsOnlyUTC() is true, else SystemTimeZoneString().

def sysTimeZone (H : Host(M)) (s : State(M)) (id : M.Str) : Prop := H.choice(Known.pSupportsOnlyUTC, [], s) = .ok(.bool(true), s) /\ M.strEq(id, M.strLit("UTC")) = true \/ H.choice(Known.pSupportsOnlyUTC, [], s) = .ok(.bool(false), s) /\ H.choice(Known.pSystemTimeZoneString, [], s) = .ok(.str(id), s)
laws

Host.TimeLaws

17-host-laws-time.spectec:75

The laws of time and dates (§21.4.1.1, sec-time-values-and-time-range; §21.4.1.32, sec-date-time-string-format).

Proved as part of Host.WF.

laws Host.TimeLaws (H : Host(M))

13 laws

21.4.3.1 Date.now sec-date.now

This function returns the time value designating the UTC date and time of the occurrence of the call to it.

No sentence the host's clock (Host.elapsed, logged as it takes each job) is what timeoutAfter's "after" is measured on; that it never goes back is what makes "after" mean later.
9.5.6 HostEnqueueTimeoutJob sec-hostenqueuetimeoutjob

It schedules timeoutJob in the realm realm in the agent signified by realm.[[AgentSignifier]] to be performed after at least milliseconds milliseconds.

As the host takes a timeout job, its clock reads at least milliseconds past the elapsed time logged before the call that scheduled it.

timeoutAfter
SpecTec
law timeoutAfter : forall s pre c job realm ms a rl r rest s', s.hostLog = pre ++ .hook(c, [job, realm, .num(ms)], a, rl, r) :: rest -> Gen.clauses[c]? = some("sec-hostenqueuetimeoutjob") -> H.nextJob(s) = .ok(some(rest.length), s') -> mathAfter(lastElapsed(rest), H.elapsed(s), ms) = true;
25.4.3.14 DoWait step 23 sec-dowait

Let additionalTimeout be an implementation-defined non-negative mathematical value.

21.4.4.41.3 TimeZoneString step 9 sec-timezoneestring

either the empty String or the string-concatenation of the code unit 0x0020 (SPACE), the code unit 0x0028 (LEFT PARENTHESIS), an implementation-defined time zone name, and the code unit 0x0029 (RIGHT PARENTHESIS)

21.4.1.24 SystemTimeZoneIdentifier step 2 sec-systemtimezoneidentifier

Let systemTimeZoneString be the String representing the host environment's current time zone, either a primary time zone identifier or an offset time zone identifier.

21.4.1.19 Time Zone Identifiers sec-time-zone-identifiers

ECMAScript implementations must support an available named time zone with the identifier "UTC", which must be the primary time zone identifier for the UTC time zone.

SystemTimeZoneString answers "UTC", an available named time zone identifier whose IsNonPrimaryTimeZoneId is false, or a String UTCOffset matches (utcOffsetNs), the state as it was.

systemTimeZoneString
SpecTec
law systemTimeZoneString : H.asks(Known.pSystemTimeZoneString, fun _ s r => exists x, r = .str(x) /\ (M.strEq(x, M.strLit("UTC")) = true \/ (exists a s' xs, H.choice(Known.pAvailableNamedTimeZoneIds, [], s) = .ok(.ref(a), s') /\ listAt(s', .ref(a)) = some(xs) /\ Val.str(x) mem xs /\ H.choice(Known.pIsNonPrimaryTimeZoneId, [.str(x)], s) = .ok(.bool(false), s)) \/ exists l, unitsAre(x, l) /\ utcOffsetNs(l).isSome));
21.4.1.23 AvailableNamedTimeZoneIdentifiers step 4.b.i sec-availablenamedtimezoneidentifiers

Set primary to the primary time zone identifier associated with identifier.

PrimaryTimeZoneId answers "UTC" or an available named time zone identifier whose IsNonPrimaryTimeZoneId is false, the state as it was.

primaryTimeZoneId
SpecTec
law primaryTimeZoneId : H.asks(Known.pPrimaryTimeZoneId, fun _ s r => exists x, r = .str(x) /\ (M.strEq(x, M.strLit("UTC")) = true \/ exists a s' xs, H.choice(Known.pAvailableNamedTimeZoneIds, [], s) = .ok(.ref(a), s') /\ listAt(s', .ref(a)) = some(xs) /\ Val.str(x) mem xs /\ H.choice(Known.pIsNonPrimaryTimeZoneId, [.str(x)], s) = .ok(.bool(false), s)));
21.4.1.24 SystemTimeZoneIdentifier step 1 sec-systemtimezoneidentifier

If the implementation only supports the UTC time zone, return "UTC".

21.4.3.2 Date.parse sec-date.parse

it returns a Number, the UTC time value corresponding to the date and time

21.4.3.2 Date.parse sec-date.parse

When the MM or DD elements are absent, "01" is used. When the HH, mm, or ss elements are absent, "00" is used. When the sss element is absent, "000" is used. When the UTC offset representation is absent, date-only forms are interpreted as a UTC time

21.4.3.2 Date.parse sec-date.parse

When the UTC offset representation is absent, date-only forms are interpreted as a UTC time and date-time forms are interpreted as a local time.

A valid date-time form without an offset gives UTC of its fields (sec-utc-t): the fields themselves where the system time zone is "UTC", less the offset where it is an offset time zone.

dateFormLocal
SpecTec
law dateFormLocal : forall x s r s' (f : DateForm) id, H.choice(Known.pParseDateString, [.str(x)], s) = .ok(r, s') -> f.fits -> f.legal -> f.isLocal = true -> unitsAre(x, f.units) -> sysTimeZone(H, s, id) -> (M.strEq(id, M.strLit("UTC")) = true -> tvResult(r, f.ms)) /\ forall l o, unitsAre(id, l) -> utcOffsetNs(l) = some(o) -> tvResult(r, f.ms - o.tdiv(1000000));
21.4.3.2 Date.parse sec-date.parse

Strings that are unrecognizable or contain out-of-bounds format element values shall cause this function to return NaN.

21.4.4.36 Date.prototype.toISOString step 7 sec-date.prototype.toisostring

Return a String representation of tv in the Date Time String Format on the UTC time scale, including all format elements and the UTC offset representation "Z".

ExpandedYearForm, whether a year from 0 to 9999 is written as an expanded year, answers a Boolean, the state as it was.

expandedYearForm
SpecTec
law expandedYearForm : H.asks(Known.pExpandedYearForm, fun _ _ r => exists b, r = .bool(b));

The laws of shared memory and buffers

From spec/spectec/prose/18-host-laws-memory.spectec

NaN encodings, Data Blocks, HostResizeArrayBuffer, and the bytes a shared read takes (sec-numerictorawbytes, sec-createbytedatablock, sec-hostresizearraybuffer, sec-memory-model). The memory model's validity (Ecma.MemoryModel) is read by chooseReadsValid alone.

Auxiliary definitions (15): cutArgs, HostCall.cutOf, cutsOf, eventPlace, …
def

cutArgs

18-host-laws-memory.spectec:14

HostSelectAgent's agent and n.

def cutArgs {M : Model} : List(Val(M)) -> Option(Val(M) times M.Math)  | [a, n] => match n with      | .math(n) => some((a, n))      | _ => none    end  | _ => noneend
def

HostCall.cutOf

18-host-laws-memory.spectec:24

A logged HostSelectAgent that selected an agent: the agent it was called in and the number of events of its [[EventList]] it gave.

def HostCall.cutOf {M : Model} : HostCall(M) -> Option(Val(M) times M.Math)  | .choice(q, vs, r) => if q == Known.pHostSelectAgent && selects(r) then cutArgs(vs) else none  | _ => noneend
def

cutsOf

18-host-laws-memory.spectec:30

The switches of a log (newest first), oldest first.

def cutsOf {M : Model} (log : List(HostCall(M))) : List(Val(M) times M.Math) := log.reverse.filterMap(HostCall.cutOf)
def

eventPlace

18-host-laws-memory.spectec:35

The place in the interleaving order of event i of the [[EventList]] of the agent whose signifier is sig: the first of the switches cuts away from that agent after the event (past all of them where there is none), then i.

def eventPlace {M : Model} (s : State(M)) (cuts : List(Val(M) times M.Math)) (sig : Val(M)) (i : Nat) : Nat times Nat := (cuts.findIdx?(fun c => Val.same(sigOf(s, c.1), sig) && M.lt(M.ofNat(i), c.2)).getD(cuts.length), i)
def

placeLe

18-host-laws-memory.spectec:38

The place p is not after q.

def placeLe (p q : Nat times Nat) : Bool := p.1 < q.1 || p.1 == q.1 && p.2 <= q.2
def

placed

18-host-laws-memory.spectec:41

The events es from position i, each with its place f.

def placed {M : Model} (f : Nat -> Nat times Nat) : Nat -> List(Val(M)) -> List(Val(M) times Nat times Nat)  | _, [] => []  | i, e :: es => (e, f(i)) :: placed(f, i + 1, es)end
def

fieldElems

18-host-laws-memory.spectec:47

The elements of the List in field f of the Record v; none where there is none.

def fieldElems {M : Model} (s : State(M)) (f : FieldId) (v : Val(M)) : List(Val(M)) := fieldOf(s, f, v).bind(listElems(s)).getD([])
def

execEvents

18-host-laws-memory.spectec:50

The events of the candidate execution ex: its Agent Events Records' [[EventList]]s.

def execEvents {M : Model} (s : State(M)) (ex : Val(M)) : List(Val(M)) := fieldElems(s, Known.fEventsRecords, ex).flatMap(fieldElems(s, Known.fEventList))
def

placedEvents

18-host-laws-memory.spectec:53

The events of ex, each with its place in the interleaving order of the switches cuts.

def placedEvents {M : Model} (s : State(M)) (cuts : List(Val(M) times M.Math)) (ex : Val(M)) : List(Val(M) times Nat times Nat) := fieldElems(s, Known.fEventsRecords, ex).flatMap(fun er => placed(eventPlace(s, cuts, fieldOf(s, Known.fAgentSignifier, er).getD(.absent)), 0, fieldElems(s, Known.fEventList, er)))
def

mathField

18-host-laws-memory.spectec:56

The mathematical value in field f of the Record v; none where there is none.

def mathField {M : Model} (s : State(M)) (f : FieldId) (v : Val(M)) : Option(M.Math) := match fieldOf(s, f, v) with  | some(.math(x)) => some(x)  | _ => noneend
def

writesByte

18-host-laws-memory.spectec:62

e is a write event (isWrite) whose [[Block]] is block and whose memory range contains loc.

def writesByte {M : Model} (isWrite : State(M) -> Val(M) -> Bool) (s : State(M)) (block : Val(M)) (loc : M.Math) (e : Val(M)) : Bool := isWrite(s, e) && fieldOf(s, Known.fBlock, e).any(fun _dot0 => Val.same(_dot0, block)) && (match mathField(s, Known.fByteIndex, e), mathField(s, Known.fElementSize, e) with  | some(i), some(k) => !M.lt(loc, i) && M.lt(loc, M.add(i, k))  | _, _ => falseend)
def

nanBits

18-host-laws-memory.spectec:72

A natural number is a NaN's encoding in the IEEE 754-2019 binary interchange format of w exponent bits and precision p: w + p bits (the sign free), the biased exponent all ones and the trailing significand not zero.

def nanBits (w p k : Nat) : Prop := k < 2 ^ (w + p) /\ k / 2 ^ (p - 1) % 2 ^ w = 2 ^ w - 1 /\ k % 2 ^ (p - 1) <> 0
def

isWriteEvent

18-host-laws-memory.spectec:75

A WriteSharedMemory or ReadModifyWriteSharedMemory event.

def isWriteEvent (s : State(M)) (e : Val(M)) : Bool := isRecordOf(s, "WriteSharedMemory", e) || isRecordOf(s, "ReadModifyWriteSharedMemory", e)
def

memNames

18-host-laws-memory.spectec:78

The memory model's names: Data's fields, enums and sorts.

def memNames : MemoryModel.View.Names := ctor(Gen.fields.idxOf?, Gen.enums.idxOf?, Gen.sorts.idxOf?)
def

interleaved

18-host-laws-memory.spectec:82

mo orders the events of the candidate execution ex as the interleaving order of the log's switches places them.

def interleaved (s : State(M)) (ex : Val(M)) (mo : MemoryModel.Rel(M.Addr)) : Prop := forall a b pa pb, (.ref(a), pa) mem placedEvents(s, cutsOf(s.hostLog), ex) -> (.ref(b), pb) mem placedEvents(s, cutsOf(s.hostLog), ex) -> a <> b -> placeLe(pa, pb) = true -> mo(a, b)
laws

Host.MemoryLaws

18-host-laws-memory.spectec:85

The laws of shared memory and buffers (§6.2.9, sec-data-blocks; §29, sec-memory-model).

Proved as part of Host.WF.

laws Host.MemoryLaws (H : Host(M))

7 laws

25.1.3.17 NumericToRawBytes step 1 sec-numerictorawbytes

An implementation must always choose the same encoding for each implementation distinguishable NaN value.

For a NaN and a format with a trailing significand field (2 ≤ p), NaNEncoding answers one NaN bit pattern of the format in every state, the state as it was.

nanEncoding
SpecTec
law nanEncoding : forall (v : M.Num) (w p : Nat), M.numView(v) = .nan -> 2 <= p -> (exists k, nanBits(w, p, k) /\ forall s, H.choice(Known.pNaNEncoding, [.num(v), .math(M.ofNat(w)), .math(M.ofNat(p))], s) = .ok(.math(M.ofNat(k)), s));
6.2.9.1 CreateByteDataBlock step 2 sec-createbytedatablock

If it is impossible to create such a Data Block, throw a RangeError exception.

CanAllocate, whether such a Data Block can be created, answers a Boolean, the state as it was.

canAllocate
SpecTec
law canAllocate : H.asks(Known.pCanAllocate, fun _ _ r => exists b, r = .bool(b));
25.1.3.8 HostResizeArrayBuffer the requirements sec-hostresizearraybuffer

The abstract operation does not detach buffer.

If the abstract operation completes normally with handled, buffer.[[ArrayBufferByteLength]] is newByteLength.

buffer's [[ArrayBufferData]] does not become null; on handled its [[ArrayBufferByteLength]] is newByteLength.

resizeArrayBuffer
SpecTec
law resizeArrayBuffer : forall c a n s r s', Gen.clauses[c]? = some("sec-hostresizearraybuffer") -> H.answers(c, [.obj(a), n], s, r, s') -> (forall f, Gen.fields[f]? = some("ArrayBufferData") -> slotOf(s, a, f) <> some(.null) -> slotOf(s', a, f) <> some(.null)) /\ forall e, normalValue(r) = some(.enum(e)) -> Gen.enums[e]? = some("handled") -> (forall f m, Gen.fields[f]? = some("ArrayBufferByteLength") -> n = .math(m) -> (exists m', slotOf(s', a, f) = some(.math(m')) /\ M.eq(m', m) = true));
25.2.3 The SharedArrayBuffer Constructor sec-sharedarraybuffer-constructor

Whenever a host does not provide concurrent access to SharedArrayBuffers it may omit the "SharedArrayBuffer" property of the global object.

25.4.12 Atomics.pause sec-atomics.pause

It has no observable behaviour other than timing.

25.1.3.15 GetRawBytesFromSharedBlock step 6 sec-getrawbytesfromsharedblock

Let rawValue be a List of length elementSize whose elements are nondeterministically chosen byte values.

ChooseReadsBytesFrom(execution, eventsRecord, block, byteIndex, elementSize) answers a new List of elementSize events of execution, the one at index i a write event on block whose memory range contains byteIndex + i; the state as it was but for the new List.

chooseReadsBytesFrom
SpecTec
law chooseReadsBytesFrom : forall vs s r s', H.choice(Known.pChooseReadsBytesFrom, vs, s) = .ok(r, s') -> (exists ex er block idx size ws, vs = [ex, er, block, .math(idx), .math(size)] /\ listOf(ws, s) = .ok(r, s') /\ M.eq(M.ofNat(ws.length), size) = true /\ forall j w, ws[j]? = some(w) -> w mem execEvents(s, ex) /\ writesByte(isWriteEvent, s, block, M.add(idx, M.ofNat(j)), w) = true);
29.7.5 Valid Executions sec-valid-executions

A candidate execution execution is a valid execution (or simply an execution) if all of the following are true.

Where execution is a valid execution whose memory order agrees with the interleaving order and whose Shared Data Block events are formed, it stays one with the read appended to eventsRecord, reading the chosen events.

chooseReadsValid
SpecTec
law chooseReadsValid : forall vs s r s', H.choice(Known.pChooseReadsBytesFrom, vs, s) = .ok(r, s') -> (forall ex er b idx size, vs = [ex, er, .ref(b), .math(idx), .math(size)] -> (exists (ws : List(M.Addr)), listOf(ws.map(.ref), s) = .ok(r, s') /\ forall (d : CloSite -> List(Val(M)) -> List(Val(M)) -> Run(M, Val(M))) rbf hsw mo k (ev : MemoryModel.NewEvent(M)), let x := MemoryModel.View.exec(memNames, d, s, ex) in MemoryModel.ValidWith(x, rbf, hsw) -> MemoryModel.MemoryOrder(x, rbf, hsw, mo) -> interleaved(s, ex, mo) -> MemoryModel.View.Formed(memNames, d, s, ex) -> x.records[k]? = some(MemoryModel.View.eventsRecord(memNames, s, er)) -> ev.IsRead -> ev.block = b -> ev.byteIndex = idx -> ev.elementSize = size -> (exists m, size = M.ofNat(m)) -> MemoryModel.ReadsValid(x, rbf, hsw, k, ev, ws)));

The law of EscapeRegExpPattern

From spec/spectec/prose/19-host-laws-regexp.spectec

EscapePattern's String (sec-escaperegexppattern step 5), over code units.

Auxiliary definitions (2): lineTerminatorUnit, terminatorEscape
def

lineTerminatorUnit

19-host-laws-regexp.spectec:12

A LineTerminator's code unit (§12.3): LF, CR, LS, PS.

def lineTerminatorUnit (c : Nat) : Bool := c == 0x0A || c == 0x0D || c == 0x2028 || c == 0x2029
def

terminatorEscape

19-host-laws-regexp.spectec:15

What follows the \ in a LineTerminator's escape: n, r, u2028, u2029.

def terminatorEscape (c : Nat) : List(Nat) := if c == 0x0A then [110] else if c == 0x0D then [114] else if c == 0x2028 then [117, 50, 48, 50, 56] else [117, 50, 48, 50, 57]
relation

Escaped

19-host-laws-regexp.spectec:20

Escaped b p e: e is p with code units escaped (§22.2.6.13.1, sec-escaperegexppattern, step 5): a / kept or written \/, a LineTerminator written as its escape (terminatorEscape), every other unit kept. b: the unit before is an unescaped \, so that a LineTerminator after it is written as the escape's letters alone.

relation Escaped : Bool -> List(Nat) -> List(Nat) -> Prop
Auxiliary definitions (3): EscapeOf, bodySafe, BodySafe
def

EscapeOf

19-host-laws-regexp.spectec:29

EscapePattern's String for the pattern p, as code units: the empty pattern as (?:), any other escaped.

def EscapeOf (p e : List(Nat)) : Prop := p = [] /\ e = [40, 63, 58, 41] \/ p <> [] /\ Escaped(false, p, e)
def

bodySafe

19-host-laws-regexp.spectec:33

One scan of e for BodySafe: no LineTerminator, and each / follows an unescaped \ or is within a class. esc: the unit before is an unescaped \; cls: within a class, where [ is a character and ] closes it.

def bodySafe : (esc cls : Bool) -> List(Nat) -> Bool  | _, _, [] => true  | true, cls, c :: e => !lineTerminatorUnit(c) && bodySafe(false, cls, e)  | false, cls, c :: e => !lineTerminatorUnit(c) && (cls || c != 47) && bodySafe(c == 92, if c == 91 then true else if c == 93 then false else cls, e)end
def

BodySafe

19-host-laws-regexp.spectec:43

As far as / and LineTerminators go, e can be the text of a RegularExpressionBody (§12.9.5): it is not empty, holds no LineTerminator, and each / follows an unescaped \ or is within a class […] (RegularExpressionClass). Where a class or an escape is left open at the end is not checked: that is not a Pattern either.

def BodySafe (e : List(Nat)) : Prop := e <> [] /\ bodySafe(false, false, e) = true
laws

Host.RegExpLaws

19-host-laws-regexp.spectec:46

The law of EscapeRegExpPattern (§22.2.6.13.1, sec-escaperegexppattern).

Proved as part of Host.WF.

laws Host.RegExpLaws (H : Host(M))

1 laws

22.2.6.13.1 EscapeRegExpPattern steps 4–5 sec-escaperegexppattern

Let escapedPattern be a String in the form of a patternSymbol equivalent to pattern interpreted as UTF-16 encoded Unicode code points

Multiple calls to this abstract operation using the same values for pattern and flags must produce identical results.

The code points / or any LineTerminator occurring in the pattern shall be escaped in escapedPattern as necessary to ensure that the string-concatenation of "/", escapedPattern, "/", and flags can be parsed (in an appropriate lexical context) as a RegularExpressionLiteral

EscapePattern answers a String S, the same for the same pattern and flags at every call, the state as it was: pattern with each / kept or written \/ and each LineTerminator written as its escape, the empty pattern as (?:) (EscapeOf), which as far as / and LineTerminators go can be a RegularExpressionBody (BodySafe). That S "must behave identically" is the specification's claim about its own semantics, no law: it was proved of this engine's escape at the git tag escape-sim-proved.

escapePattern
SpecTec
law escapePattern : forall pattern flags s r s', H.choice(Known.pEscapePattern, [.str(pattern), .str(flags)], s) = .ok(r, s') -> s' = s /\ (exists S, r = .str(S) /\ exists p e, unitsAre(pattern, p) /\ unitsAre(S, e) /\ EscapeOf(p, e) /\ BodySafe(e)) /\ forall s2 r2 s2', H.choice(Known.pEscapePattern, [.str(pattern), .str(flags)], s2) = .ok(r2, s2') -> r2 = r;

The laws of sorting and enumeration

From spec/spectec/prose/20-host-laws-order.spectec

The order SortIndexedProperties sorts in, the steps of EnumerateObjectProperties, and the order of the intrinsics' properties.

Auxiliary definitions (6): sortCall, sortDone, cmpOrder, consistentCmp, …
def

sortCall

20-host-laws-order.spectec:12

SortStep's answer to call the comparator on the elements at j and k, the host's state then st: a new List « j, k, st ».

def sortCall {M : Model} (j k : Nat) (st : Val(M)) : Run(M, Val(M)) := listOf([.math(M.ofNat(j)), .math(M.ofNat(k)), st])
def

sortDone

20-host-laws-order.spectec:15

SortStep's answer to finish with the order σ: a new Record whose [[Value]] is a new List of σ.

def sortDone {M : Model} (σ : List(Nat)) : Run(M, Val(M)) := do {  let l <- listOf(σ.map(fun i => .math(M.ofNat(i))));  return .ref(<- alloc(.record(Known.sRecord, M.recSet(M.recEmpty, Known.fValue, l))));}
def

cmpOrder

20-host-laws-order.spectec:24

The order a comparator's result gives (§23.1.3.30.1 <C, =C, >C): none for NaN and for ±∞, whose ℝ is not defined (§5.2.6).

def cmpOrder (r : M.Num) : Option(Ordering) := match M.numView(r) with  | .posZero | .negZero => some(.eq)  | .finite(m) => some(if M.lt(m, M.ofNat(0)) then .lt else .gt)  | _ => noneend
def

consistentCmp

20-host-laws-order.spectec:32

§23.1.3.30.1: c is a consistent comparator for the elements at the indices less than n: a non-NaN Number for each pair, =C reflexive and symmetric, =C, <C and >C transitive.

def consistentCmp (n : Nat) (c : Nat -> Nat -> M.Num) : Prop := (forall a b, a < n -> b < n -> cmpOrder(c(a, b)) <> none) /\ (forall a, a < n -> cmpOrder(c(a, a)) = some(.eq)) /\ (forall a b, a < n -> b < n -> cmpOrder(c(a, b)) = some(.eq) -> cmpOrder(c(b, a)) = some(.eq)) /\ forall (o : Ordering) a b d, a < n -> b < n -> d < n -> cmpOrder(c(a, b)) = some(o) -> cmpOrder(c(b, d)) = some(o) -> cmpOrder(c(a, d)) = some(o)
def

sortOrderOk

20-host-laws-order.spectec:36

§23.1.3.30.1: the order σ (new[i] is old[σ[i]], so π(j) is j's index in σ) puts each element before every element it is <C, and before every later element it is =C (stable).

def sortOrderOk (n : Nat) (c : Nat -> Nat -> M.Num) (σ : List(Nat)) : Prop := forall j k, j < n -> k < n -> (cmpOrder(c(j, k)) = some(.lt) -> σ.idxOf(j) < σ.idxOf(k)) /\ (j < k -> cmpOrder(c(j, k)) = some(.eq) -> σ.idxOf(j) < σ.idxOf(k))
def

sortCallStep

20-host-laws-order.spectec:40

One call of a sort of n elements: SortStep, given the host's state st and the result res, asks for a call on the elements at j and k, with the state st' it is given back.

def sortCallStep (H : Host(M)) (n : Nat) (st res st' : Val(M)) (j k : Nat) : Prop := exists s r s', H.choice(Known.pSortStep, [.math(M.ofNat(n)), st, res], s) = .ok(r, s') /\ sortCall(j, k, st', s) = .ok(r, s')
relation

SortReach

20-host-laws-order.spectec:45

A sort of n elements (§23.1.3.30.1, sec-sortindexedproperties) reaches SortStep's arguments st (the host's state) and res (the last call's result) by the calls h, oldest first, each with the Number it returned: it starts from empty and empty, and each call SortStep asks for returns any Number.

relation SortReach (H : Host(M)) (n : Nat) : Val(M) -> Val(M) -> List(Nat times Nat times M.Num) -> Prop
Auxiliary definition: sortNext
def

sortNext

20-host-laws-order.spectec:52

A sort of n elements goes from SortStep's arguments b to a: from arguments the sort reaches, a call whose result is any Number.

def sortNext (H : Host(M)) (n : Nat) (a b : Val(M) times Val(M)) : Prop := (exists h, SortReach(H, n, b.1, b.2, h)) /\ exists j k x, sortCallStep(H, n, b.1, b.2, a.1, j, k) /\ a.2 = .num(x)
laws

Host.OrderLaws

20-host-laws-order.spectec:56

The laws of sorting and enumeration (§23.1.3.30.1, sec-sortindexedproperties; §14.7.5.9, sec-enumerate-object-properties).

Proved as part of Host.WF.

laws Host.OrderLaws (H : Host(M))

4 laws

23.1.3.30.1 SortIndexedProperties step 4 and the paragraph after it sec-sortindexedproperties

Sort items using an implementation-defined sequence of calls to sortCompare.

Unless the sort order is specified to be implementation-defined, it must satisfy all of the following conditions

At the host's state and the last result a sort of n elements reaches by the calls h, SortStep asks for a call on two indices less than n, or answers a permutation that, for every consistent comparator giving every result in h, meets its conditions; otherwise the order is the host's.

sortStep
SpecTec
law sortStep : forall n st res h s r s', SortReach(H, n, st, res, h) -> H.choice(Known.pSortStep, [.math(M.ofNat(n)), st, res], s) = .ok(r, s') -> (exists j k st', j < n /\ k < n /\ sortCall(j, k, st', s) = .ok(r, s')) \/ exists σ, σ.Perm(List.range(n)) /\ (forall c, consistentCmp(n, c) -> (forall e mem h, c(e.1, e.2.1) = e.2.2) -> sortOrderOk(n, c, σ)) /\ sortDone(σ, s) = .ok(r, s');
23.1.3.30.1 SortIndexedProperties steps 4–5 sec-sortindexedproperties

Sort items using an implementation-defined sequence of calls to sortCompare.

The sequence is finite: a sort makes finitely many calls, whatever their results.

sortStepEnds
SpecTec
law sortStepEnds : forall n, WellFounded(sortNext(H, n));
14.7.5.9 EnumerateObjectProperties sec-enumerate-object-properties

The mechanics and order of enumerating the properties is not specified but must conform to the rules specified below.

the iterator must behave as would the iterator given by CreateForInIterator(obj) until one of the following occurs

After a history that obeyed the rules (ForInRun), ForInStep answers an action that obeys them (ForInRules); and CreateForInIterator(obj)'s next action where no object of the chain is exotic, none changed shape since the enumeration began (State.shapeLog), and every action so far was its.

forInStep
SpecTec
law forInStep : forall obj h s r s', H.choice(Known.pForInStep, [.obj(obj), h], s) = .ok(r, s') -> (forall es, forInHist(s, h) = some(es) -> ForInRun(obj, es) -> (exists act, actRecord(act, s) = .ok(r, s') /\ ForInRules(obj, es, act) /\ (cfiApplies(s, obj, h, es) -> act = cfiNext(obj, es))));
9.3.2 CreateIntrinsics step 2 sec-createintrinsics

Set fields of realmRecord.[[Intrinsics]] with the values listed in

PropertyOrder, the order an intrinsic's properties are created in, answers a new List of the given properties, each once.

propertyOrder
SpecTec
law propertyOrder : forall o l s r s', H.choice(Known.pPropertyOrder, [o, l], s) = .ok(r, s') -> (exists xs ys, listElems(s, l) = some(xs) /\ ys.Perm(xs) /\ listOf(ys, s) = .ok(r, s'));

The laws of the locale-sensitive methods

From spec/spectec/prose/21-host-laws-locale.spectec

The list separator, locale case mapping and comparison, and the locale forms of Number and Date.

Auxiliary definitions (5): dateValued, negNum, posNum, zeroNum, …
def

dateValued

21-host-laws-locale.spectec:10

The value is an object with a [[DateValue]] internal slot.

def dateValued {M : Model} (s : State(M)) : Val(M) -> Bool  | .obj(a) => slotOf(s, a, Known.fDateValue).isSome  | _ => falseend
def

negNum

21-host-laws-locale.spectec:18

n is a negative Number.

def negNum (n : M.Num) : Prop := M.numView(n) = .negInf \/ exists m, M.numView(n) = .finite(m) /\ M.lt(m, M.ofNat(0)) = true
def

posNum

21-host-laws-locale.spectec:21

n is a positive Number.

def posNum (n : M.Num) : Prop := M.numView(n) = .posInf \/ exists m, M.numView(n) = .finite(m) /\ M.lt(M.ofNat(0), m) = true
def

zeroNum

21-host-laws-locale.spectec:24

n is +0𝔽 or -0𝔽.

def zeroNum (n : M.Num) : Prop := M.numView(n) = .posZero \/ M.numView(n) = .negZero
def

canonEquiv

21-host-laws-locale.spectec:28

Two Strings are canonically equivalent according to the Unicode Standard: their code points have the same canonical decomposition (NFD, UAX #15).

def canonEquiv (a b : M.Str) : Prop := M.normalize(.NFD, Prims.Strings.strPoints(a)) = M.normalize(.NFD, Prims.Strings.strPoints(b))
laws

Host.LocaleLaws

21-host-laws-locale.spectec:31

The laws of the locale-sensitive methods (§22.1.3.11, sec-string.prototype.localecompare).

Proved as part of Host.WF.

laws Host.LocaleLaws (H : Host(M))

5 laws

23.1.3.32.1 LocalizedListSeparator sec-localizedlistseparator

LocalizedListSeparator ( ): a String

It returns an implementation-defined String appropriate for use as a list separator in the host environment's current locale (such as ", ").

LocalizedListSeparator answers a String, the state as it was.

listSeparator
SpecTec
law listSeparator : forall c xs s r s', Gen.clauses[c]? = some("sec-localizedlistseparator") -> H.answers(c, xs, s, r, s') -> s' = s /\ exists x, r = .str(x);

It works exactly the same as toLowerCase except that it is intended to yield a locale-sensitive result corresponding with conventions of the host environment's current locale.

22.1.3.12 String.prototype.localeCompare sec-string.prototype.localecompare

this method, when considered as a method of two arguments, is required to be a consistent comparator defining a total ordering on the set of all Strings

This method is also required to recognize and honour canonical equivalence according to the Unicode Standard

By one total preorder of all Strings, LocaleCompare answers a negative, positive or zero Number, never NaN, and +0𝔽 for canonically equivalent Strings, the state as it was.

localeCompare
SpecTec
law localeCompare : exists (le : M.Str -> M.Str -> Prop), (forall a b, le(a, b) \/ le(b, a)) /\ (forall a b c, le(a, b) -> le(b, c) -> le(a, c)) /\ forall a b s r s', H.choice(Known.pLocaleCompare, [.str(a), .str(b)], s) = .ok(r, s') -> s' = s /\ exists n, r = .num(n) /\ (not le(b, a) -> negNum(n)) /\ (not le(a, b) -> posNum(n)) /\ (le(a, b) -> le(b, a) -> zeroNum(n)) /\ (canonEquiv(a, b) -> M.numView(n) = .posZero);
21.1.3.4 Number.prototype.toLocaleString sec-number.prototype.tolocalestring

This method is implementation-defined, and it is permissible, but not encouraged, for it to return the same thing as toString.

21.4.4.38 Date.prototype.toLocaleDateString (and toLocaleString, toLocaleTimeString) sec-date.prototype.tolocaledatestring

This method returns a String value. The contents of the String are implementation-defined

LocaleDateString answers a String, or empty for the form without a locale, for an object with a [[DateValue]] slot, and a String or throw (a TypeError) for any other value, the state as it was.

localeDateString
SpecTec
law localeDateString : forall k v s r s', H.choice(Known.pLocaleDateString, [k, v], s) = .ok(r, s') -> s' = s /\ (dateValued(s, v) = true -> r = .enum(Known.eEmpty) \/ exists x, r = .str(x)) /\ (dateValued(s, v) = false -> r = .enum(Known.eThrow) \/ exists x, r = .str(x));

The laws of the optional features

From spec/spectec/prose/22-host-laws-optional.spectec

Whether the host is a web browser and the normative optional features it supports, the debugger statement, and a built-in function's source text.

Auxiliary definitions (5): identLike, keyLike, nameLike, nativeName, …
def

identLike

22-host-laws-optional.spectec:10

An ASCII IdentifierName.

def identLike : List(Char) -> Bool  | c :: cs => (c.isAlpha || c == '_' || c == '$') && cs.all(fun c => c.isAlphanum || c == '_' || c == '$')  | [] => falseend
def

keyLike

22-host-laws-optional.spectec:16

A built-in's property key as its name: an IdentifierName or [Symbol. IdentifierName ].

def keyLike (cs : List(Char)) : Bool := identLike(cs) || "[Symbol.".toList.isPrefixOf(cs) && cs.getLast? == some(']') && identLike(cs.drop(8).dropLast)
def

nameLike

22-host-laws-optional.spectec:20

A name of these forms is matched by |NativeFunctionAccessor?| PropertyName: a key, or get or set and a key.

def nameLike (cs : List(Char)) : Bool := keyLike(cs) || ("get ".toList.isPrefixOf(cs) || "set ".toList.isPrefixOf(cs)) && keyLike(cs.drop(4))
def

nativeName

22-host-laws-optional.spectec:23

A name NativeFunctionSource's law admits: empty, or of those forms.

def nativeName (cs : List(Char)) : Bool := cs.isEmpty || nameLike(cs)
def

nativeWrap

22-host-laws-optional.spectec:26

function NAME() { [native code] }.

def nativeWrap (cs : List(Char)) : String := "function " ++ String.ofList(cs) ++ "() { [native code] }"
laws

Host.OptionalLaws

22-host-laws-optional.spectec:32

Proved as part of Host.WF.

laws Host.OptionalLaws (H : Host(M))

5 laws

B Additional ECMAScript Features for Web Browsers sec-additional-ecmascript-features-for-web-browsers

The ECMAScript language syntax and semantics defined in this annex are required when the ECMAScript host is a web browser.

WebBrowser, whether the host is a web browser or otherwise supports the feature its arguments name, is one Boolean for the same arguments in every state, the state as it was.

webBrowser
SpecTec
law webBrowser : forall vs, exists b, forall s, H.choice(Known.pWebBrowser, vs, s) = .ok(.bool(b), s);
B Additional ECMAScript Features for Web Browsers sec-additional-ecmascript-features-for-web-browsers

Web browsers are required to support all such features.

14.16.1 Runtime Semantics: Evaluation step 1 sec-debugger-statement-runtime-semantics-evaluation

If an implementation-defined debugging facility is available and enabled, then

14.16.1 Runtime Semantics: Evaluation step 1.a sec-debugger-statement-runtime-semantics-evaluation

Perform an implementation-defined debugging action.

20.2.3.5 Function.prototype.toString step 3 sec-function.prototype.tostring

The representation must have the syntax of a NativeFunction. Additionally, if func has an [[InitialName]] internal slot and func.[[InitialName]] is a String, the portion of the returned String that would be matched by NativeFunctionAccessor? PropertyName must be func.[[InitialName]].

NativeFunctionSource answers function , a name nativeName admits and () { [native code] }, the name func.[[InitialName]] where that is a String, the state as it was.

nativeFunctionSource
SpecTec
law nativeFunctionSource : forall f s r s', H.choice(Known.pNativeFunctionSource, [f], s) = .ok(r, s') -> s' = s /\ exists cs, nativeName(cs) = true /\ r = .str(M.strLit(nativeWrap(cs))) /\ forall a sl ps y, f = .obj(a) -> M.heapGet(s.heap, a) = some(.object(sl, ps)) -> M.recGet(sl, Known.fInitialName) = some(.str(y)) -> M.strEq(y, M.strLit(String.ofList(cs))) = true;

The laws of the values the implementation chooses

From spec/spectec/prose/23-host-laws-values.spectec

Implementation-approximated values, implementation-defined choices, Math.random, and the maximum BigInt size.

Auxiliary definition: unitNum
def

unitNum

23-host-laws-values.spectec:12

n is a Number with positive sign, greater than or equal to +0 and less than 1.

def unitNum (n : M.Num) : Prop := M.numView(n) = .posZero \/ exists m, M.numView(n) = .finite(m) /\ M.lt(M.ofNat(0), m) = true /\ M.lt(m, M.ofNat(1)) = true
laws

Host.ValueLaws

23-host-laws-values.spectec:15

The laws of the values the implementation chooses (§5.2, sec-algorithm-conventions; §21.3, sec-math-object).

Proved as part of Host.WF.

laws Host.ValueLaws (H : Host(M))

7 laws

21.3.2.9 Math.cbrt step 3, and every "implementation-approximated Number value" of the Math functions sec-math.cbrt

Return an implementation-approximated Number value representing the cube root of ℝ(n).

Approx answers a Number, the state as it was.

approx
SpecTec
law approx : H.asks(Known.pApprox, fun _ _ r => exists n, r = .num(n));
6.1.6.1.3 Number::exponentiate step 13 sec-numeric-types-number-exponentiate

Return an implementation-approximated Number value representing the result of raising ℝ(base) to the ℝ(exponent) power.

19.2.5 parseInt step 11 sec-parseint-string-radix

mathInt may be an implementation-approximated integer representing the integer value denoted by numberString in radix-radixMV notation

No sentence ECMA-262 sets no maximum size of a BigInt (sec-ecmascript-language-types-bigint-type: "The value may be any size and is not limited to a particular bit-width"); the proposed reading of erratum BigIntMaximumSize, a proposed normative change, asks the host whether a result would exceed the implementation's maximum.
No sentence ECMA-262 defines String values up to length 2^53 - 1 and leaves implementations' smaller maximum String lengths unspecified; the proposed reading of erratum StringMaximumLength asks the host whether a String of length len exceeds the implementation's maximum String length.
7.1.4.1.3 RoundMVResult step 4, and every "implementation-defined choice of either" two values sec-roundmvresult

Let chosen be an implementation-defined choice of either option1 or option2.

21.3.2.28 Math.random sec-math.random

This function returns a Number value with positive sign, greater than or equal to +0𝔽 but strictly less than 1𝔽

Math.random answers such a Number (unitNum), never an abrupt completion, the state as it was.

mathRandom
SpecTec
law mathRandom : forall c xs s r s', Gen.clauses[c]? = some("sec-math.random") -> H.answers(c, xs, s, r, s') -> s' = s /\ exists n, r = .num(n) /\ unitNum(n);

The laws of the host hooks

From spec/spectec/prose/24-host-laws-hooks.spectec

What every host hook returns, and the hooks that must answer alike at every call (sec-hosts-and-implementations).

laws

Host.HookLaws

24-host-laws-hooks.spectec:12

The laws of the host hooks (§4.2, sec-hosts-and-implementations).

Proved as part of Host.WF.

laws Host.HookLaws (H : Host(M))

5 laws

4.2 Hosts and Implementations sec-hosts-and-implementations

A host hook must conform to at least the following requirements: It must return either a normal completion or a throw completion.

7.3.29 HostEnsureCanAddPrivateElement the requirements sec-hostensurecanaddprivateelement

Any two calls of this abstract operation with the same argument must return the same kind of Completion Record.

The [[Type]] of HostEnsureCanAddPrivateElement's answer is one function of its argument, whatever the state of the call.

privateElementSameKind
SpecTec
law privateElementSameKind : exists (kind : List(Val(M)) -> EnumId), forall c xs s r s', Gen.clauses[c]? = some("sec-hostensurecanaddprivateelement") -> H.answers(c, xs, s, r, s') -> compType(r) = kind(xs);
16.2.1.12.1 HostGetSupportedImportAttributes the requirements sec-hostgetsupportedimportattributes

It must return a List of Strings, each indicating a supported attribute. Each time this operation is called, it must return the same List with the same contents in the same order.

Every call answers a List of the same Strings in the same order (the default's new empty List at each call conforms, so "the same List" is its contents).

supportedImportAttributes
SpecTec
law supportedImportAttributes : exists (ids : List(M.Str)), forall c xs s r s', Gen.clauses[c]? = some("sec-hostgetsupportedimportattributes") -> H.answers(c, xs, s, r, s') -> listElems(s', r) = some(ids.map(.str));
19.2.1.3 HostGetCodeForEval sec-hostgetcodeforeval

HostGetCodeForEval ( arg: an Object, ): a String or no-code

HostGetCodeForEval answers a String or no-code.

getCodeForEval
SpecTec
law getCodeForEval : forall c xs s r s', Gen.clauses[c]? = some("sec-hostgetcodeforeval") -> H.answers(c, xs, s, r, s') -> (exists e, r = .enum(e) /\ Gen.enums[e]? = some("no-code")) \/ exists x, r = .str(x);
20.2.5 HostHasSourceTextAvailable the requirements sec-hosthassourcetextavailable

It must be deterministic with respect to its parameters. Each time it is called with a specific func as its argument, it must return the same result.

HostHasSourceTextAvailable's answer is one function of its argument, whatever the state of the call.

hasSourceTextAvailable
SpecTec
law hasSourceTextAvailable : exists (f : List(Val(M)) -> Val(M)), forall c xs s r s', Gen.clauses[c]? = some("sec-hosthassourcetextavailable") -> H.answers(c, xs, s, r, s') -> r = f(xs);

The laws of what a host step may change

From spec/spectec/prose/25-host-laws-changes.spectec

The objects' invariants, the agent's fixed fields, the Realm's global object and its properties, extensions, execution contexts, the FinalizationRegistry cleanup, tail calls' resources, and collection.

Auxiliary definitions (8): discardedIn, liveContexts, onlyPropsOf, onlyAdds, …
def

discardedIn

25-host-laws-changes.spectec:13

The log has a DiscardContextResources choice for the execution context ctx.

def discardedIn (log : List(HostCall(M))) : Val(M) -> Bool  | .ref(a) => log.any(fun      | .choice(q, [.ref(b)], _) => q == Known.pDiscardContextResources && M.addrEq(a, b)      | _ => false    end)  | _ => falseend
def

liveContexts

25-host-laws-changes.spectec:22

The execution contexts on the stack whose resources no DiscardContextResources choice discarded.

def liveContexts (s : State(M)) : Nat := stackList(s).countP(fun _dot0 => !discardedIn(s.hostLog, _dot0))
def

onlyPropsOf

25-host-laws-changes.spectec:26

s' is s but for its heap, where every cell but g's is as it was and g keeps its internal slots: only g's own properties change, and new cells may be allocated.

def onlyPropsOf (g : M.Addr) (s s' : State(M)) : Prop := s' = { s with heap := s'.heap } /\ (forall a c, a <> g -> M.heapGet(s.heap, a) = some(c) -> M.heapGet(s'.heap, a) = some(c)) /\ forall sl ps, M.heapGet(s.heap, g) = some(.object(sl, ps)) -> (exists ps', M.heapGet(s'.heap, g) = some(.object(sl, ps')))
def

onlyAdds

25-host-laws-changes.spectec:31

s' is s but for its heap, where only the objects to admits gain own properties: every other cell is as it was, and such an object keeps its internal slots and the properties it had, and gains none unless its [[Extensible]] is true; new cells may be allocated.

def onlyAdds (to : M.Addr -> Prop) (s s' : State(M)) : Prop := s' = { s with heap := s'.heap } /\ (forall a c, M.heapGet(s.heap, a) = some(c) -> (forall sl ps, to(a) -> c <> .object(sl, ps)) -> M.heapGet(s'.heap, a) = some(c)) /\ forall a sl ps, to(a) -> M.heapGet(s.heap, a) = some(.object(sl, ps)) -> (exists ps', M.heapGet(s'.heap, a) = some(.object(sl, ps')) /\ (forall k v, M.propsGet(ps, k) = some(v) -> M.propsGet(ps', k) = some(v)) /\ (M.recGet(sl, Known.fExtensible) <> some(.bool(true)) -> (forall k, M.propsGet(ps', k).isSome -> M.propsGet(ps, k).isSome)))
def

attrsAt

25-host-laws-changes.spectec:34

The fields of the attribute Record that the property k of ps refers to in s.

def attrsAt (s : State(M)) (ps : M.Props(Val(M))) (k : M.Str sum M.Sym) : Option(M.Rec(Val(M))) := match M.propsGet(ps, k) with  | some(.ref(p)) => match M.heapGet(s.heap, p) with      | some(.record(_, fs)) => some(fs)      | _ => none    end  | _ => noneend
def

attrsKept

25-host-laws-changes.spectec:45

§6.1.7.3 at a non-configurable property, from its attributes fs to fs': every attribute but [[Writable]] and [[Value]] is as it was; [[Writable]] is as it was or turns from true to false; [[Value]] is as it was unless [[Writable]] was true.

def attrsKept (fs fs' : M.Rec(Val(M))) : Prop := (forall f, f <> Known.fWritable -> f <> Known.fValue -> M.recGet(fs', f) = M.recGet(fs, f)) /\ (M.recGet(fs', Known.fWritable) = M.recGet(fs, Known.fWritable) \/ M.recGet(fs, Known.fWritable) = some(.bool(true)) /\ M.recGet(fs', Known.fWritable) = some(.bool(false))) /\ (M.recGet(fs, Known.fWritable) <> some(.bool(true)) -> M.recGet(fs', Known.fValue) = M.recGet(fs, Known.fValue))
def

objKept

25-host-laws-changes.spectec:51

sec-invariants-of-the-essential-internal-methods at an object, from slots sl and properties ps in s to sl' and ps' in s': [[Extensible]] is as it was or turns from true to false; an object whose [[Extensible]] is not true keeps its [[Prototype]] and gains no property; a non-configurable property stays, its attributes as attrsKept allows.

def objKept (s s' : State(M)) (sl : M.Rec(Val(M))) (ps : M.Props(Val(M))) (sl' : M.Rec(Val(M))) (ps' : M.Props(Val(M))) : Prop := (M.recGet(sl', Known.fExtensible) = M.recGet(sl, Known.fExtensible) \/ M.recGet(sl, Known.fExtensible) = some(.bool(true)) /\ M.recGet(sl', Known.fExtensible) = some(.bool(false))) /\ (M.recGet(sl, Known.fExtensible) <> some(.bool(true)) -> M.recGet(sl', Known.fPrototype) = M.recGet(sl, Known.fPrototype) /\ forall k, M.propsGet(ps', k).isSome -> M.propsGet(ps, k).isSome) /\ forall k fs, attrsAt(s, ps, k) = some(fs) -> M.recGet(fs, Known.fConfigurable) <> some(.bool(true)) -> (exists fs', attrsAt(s', ps', k) = some(fs') /\ attrsKept(fs, fs'))
def

contextField

25-host-laws-changes.spectec:55

The components every execution context has (§9.4 Table 26), and those of an ECMAScript code execution context (Table 27) and a generator's (Table 28).

def contextField (f : FieldId) : Prop := f = Known.fCodeState \/ f = Known.fFunction \/ f = Known.fRealm \/ f = Known.fScriptOrModule \/ f = Known.fLexicalEnvironment \/ f = Known.fVariableEnvironment \/ f = Known.fPrivateEnvironment \/ f = Known.fGenerator
relation

intrinsicOf

25-host-laws-changes.spectec:61

§6.1.7.4 (sec-well-known-intrinsic-objects), §9.3 (sec-code-realms): a is one of realm's intrinsics in s: an object realm.[[Intrinsics]] holds, or one a property of an intrinsic holds ([[Value]], [[Get]] or [[Set]]). Right after CreateIntrinsics(realm) these are the objects it created (IntrinsicObjects: the well-known intrinsics and every object their properties hold).

relation intrinsicOf (s : State(M)) (realm : M.Addr) : M.Addr -> Prop
Auxiliary definitions (4): noForbiddenProps, emptyCell, agentFixedField, agentKept
def

noForbiddenProps

25-host-laws-changes.spectec:68

§17.1: a function object (one with a [[Call]]) has an own "caller" or "arguments" property in s' only if it had it in s.

def noForbiddenProps (s s' : State(M)) : Prop := forall a sl ps' k, M.heapGet(s'.heap, a) = some(.object(sl, ps')) -> M.recGet(sl, Known.fCall).isSome -> M.strEq(k, M.strLit("caller")) = true \/ M.strEq(k, M.strLit("arguments")) = true -> M.propsGet(ps', .inl(k)).isSome -> (exists ps, M.heapGet(s.heap, a) = some(.object(sl, ps)) /\ M.propsGet(ps, .inl(k)).isSome)
def

emptyCell

25-host-laws-changes.spectec:71

c is a Record that reg.[[Cells]] contains, whose [[WeakRefTarget]] is empty.

def emptyCell (s : State(M)) (reg : Val(M)) (c : M.Addr) : Prop := exists r sl ps l xs o i k fs, reg = .obj(r) /\ M.heapGet(s.heap, r) = some(.object(sl, ps)) /\ M.recGet(sl, Known.fCells) = some(.ref(l)) /\ M.heapGet(s.heap, l) = some(.list(xs, o)) /\ M.seqGet(xs, i) = some(.ref(c)) /\ M.heapGet(s.heap, c) = some(.record(k, fs)) /\ M.recGet(fs, Known.fWeakRefTarget) = some(.enum(Known.eEmpty))
def

agentFixedField

25-host-laws-changes.spectec:75

The Agent Record fields whose values cannot change (§9.7: [[LittleEndian]], [[Signifier]], [[IsLockFreeN]]) and [[GlobalSymbolRegistry]], which is never reassigned.

def agentFixedField (f : FieldId) : Prop := f = fieldNamed("LittleEndian") \/ f = fieldNamed("Signifier") \/ f = fieldNamed("IsLockFree1") \/ f = fieldNamed("IsLockFree2") \/ f = fieldNamed("IsLockFree8") \/ f = fieldNamed("GlobalSymbolRegistry")
def

agentKept

25-host-laws-changes.spectec:79

From s to s', the surrounding agent is the same, and its Agent Record keeps its sort and the fields agentFixedField names.

def agentKept (s s' : State(M)) : Prop := s'.agent = s.agent /\ forall a k fs, s.agent = .ref(a) -> M.heapGet(s.heap, a) = some(.record(k, fs)) -> (exists fs', M.heapGet(s'.heap, a) = some(.record(k, fs')) /\ forall f, agentFixedField(f) -> M.recGet(fs', f) = M.recGet(fs, f))

Collection (sec-weakref-execution).

Auxiliary definitions (6): keptAlive, weakMapEntry, weakSetData, Rec.Emptied, …
def

keptAlive

25-host-laws-changes.spectec:84

v is in the [[KeptAlive]] List of an agent's Agent Record in s.

def keptAlive (s : State(M)) (v : Val(M)) : Prop := exists ag l xs, isRecordOf(s, "Agent Record", ag) = true /\ fieldOf(s, fieldNamed("KeptAlive"), ag) = some(l) /\ listAt(s, l) = some(xs) /\ v mem xs
def

weakMapEntry

25-host-laws-changes.spectec:87

a is a Record a WeakMap's [[WeakMapData]] List contains.

def weakMapEntry (s : State(M)) (a : M.Addr) : Prop := exists o sl ps l es, M.heapGet(s.heap, o) = some(.object(sl, ps)) /\ M.recGet(sl, fieldNamed("WeakMapData")) = some(l) /\ listAt(s, l) = some(es) /\ Val.ref(a) mem es
def

weakSetData

25-host-laws-changes.spectec:90

a is the List a WeakSet's [[WeakSetData]] is.

def weakSetData (s : State(M)) (a : M.Addr) : Prop := exists o sl ps, M.heapGet(s.heap, o) = some(.object(sl, ps)) /\ M.recGet(sl, fieldNamed("WeakSetData")) = some(.ref(a))
def

Rec.Emptied

25-host-laws-changes.spectec:93

fs' is fs with the fields gs set to empty where its field k is an element of xs, else fs.

def Rec.Emptied (xs : List(Val(M))) (k : FieldId) (gs : List(FieldId)) (fs fs' : M.Rec(Val(M))) : Prop := (exists v mem xs, M.recGet(fs, k) = some(v)) /\ fs' = gs.foldl(fun r g => M.recSet(r, g, .enum(Known.eEmpty)), fs) \/ (not exists v mem xs, M.recGet(fs, k) = some(v)) /\ fs' = fs
def

Cell.Emptied

25-host-laws-changes.spectec:99

The cell c at a becomes c' by sec-weakref-execution's steps for the set xs: a WeakRef's and a FinalizationRegistry cell's [[WeakRefTarget]] in xs is set to empty; a WeakMap entry whose [[Key]] is in xs has its [[Key]] and [[Value]] set to empty; a WeakSet's elements in xs are replaced by empty; nothing else changes.

def Cell.Emptied (s : State(M)) (xs : List(Val(M))) (a : M.Addr) : Cell(M) -> Cell(M) -> Prop  | .object(sl, ps), .object(sl', ps') => ps' = ps /\ Rec.Emptied(xs, Known.fWeakRefTarget, [Known.fWeakRefTarget], sl, sl')  | .record(k, fs), .record(k', fs') => k' = k /\ (weakMapEntry(s, a) /\ Rec.Emptied(xs, fieldNamed("Key"), [fieldNamed("Key"), Known.fValue], fs, fs') \/ not weakMapEntry(s, a) /\ Rec.Emptied(xs, Known.fWeakRefTarget, [Known.fWeakRefTarget], fs, fs'))  | .list(ys, o), .list(ys', o') => o' = o /\ (not weakSetData(s, a) -> ys' = ys) /\ M.seqLen(ys') = M.seqLen(ys) /\ forall i v, M.seqGet(ys, i) = some(v) -> v mem xs /\ M.seqGet(ys', i) = some(.enum(Known.eEmpty)) \/ v notmem xs /\ M.seqGet(ys', i) = some(v)  | c, c' => c' = cend
def

Val.Holds

25-host-laws-changes.spectec:107

Subvalues referenced by a compound value.

def Val.Holds {M : Model} : Val(M) -> Val(M) -> Prop  | .comp(_, x, y), v => v = x \/ v = y  | .clo(_, caps), v => v mem caps  | .ty(_, _, _, env), v => v mem env  | .cond(_, _, _, _, env), v => v mem env  | .tuple(vs), v => v mem vs  | _, _ => Falseend
relation

Reachable

25-host-laws-changes.spectec:121

§9.5 (sec-jobs), §9.9.2 (sec-liveness): values strongly reachable from the roots of s (including un-taken queued job arguments in s.hostLog) without following weak references (WeakRef.[[WeakRefTarget]], WeakSet.[[WeakSetData]], WeakMap.[[WeakMapData]] entries whose [[Key]] is not itself reachable, or FinalizationRegistry cell [[WeakRefTarget]] / [[UnregisterToken]] fields).

relation Reachable (s : State(M)) : Val(M) -> Prop
Auxiliary definition: Collected
def

Collected

25-host-laws-changes.spectec:149

sec-weakref-execution: s' is s after the steps, performed atomically, for the set xs of objects and Symbols, none of them in an agent's [[KeptAlive]] List or strongly reachable (Reachable) (sec-liveness): every cell as Cell.Emptied says, every other component as it was.

def Collected (s : State(M)) (xs : List(Val(M))) (s' : State(M)) : Prop := (forall x mem xs, ((exists a, x = .obj(a)) \/ exists y, x = .sym(y)) /\ not keptAlive(s, x) /\ not Reachable(s, x)) /\ s' = { s with heap := s'.heap } /\ forall a, M.heapGet(s'.heap, a).isSome = M.heapGet(s.heap, a).isSome /\ forall c, M.heapGet(s.heap, a) = some(c) -> (exists c', M.heapGet(s'.heap, a) = some(c') /\ Cell.Emptied(s, xs, a, c, c'))
laws

Host.ChangeLaws

25-host-laws-changes.spectec:153

The laws of what a host step may change (§6.1.7.3, sec-invariants-of-the-essential-internal-methods; §9.6, sec-agents; §9.9.3, sec-weakref-execution).

Proved as part of Host.WF.

laws Host.ChangeLaws (H : Host(M))

14 laws

6.1.7.3 Invariants of the Essential Internal Methods sec-invariants-of-the-essential-internal-methods

An implementation must not allow these invariants to be circumvented in any manner such as by providing alternative interfaces that implement the functionality of the essential internal methods without enforcing their invariants.

Across a host step every object is still an object and keeps to the invariants (objKept).

invariantsKept
SpecTec
law invariantsKept : forall s s', H.Step(s, s') -> (forall a sl ps, M.heapGet(s.heap, a) = some(.object(sl, ps)) -> (exists sl' ps', M.heapGet(s'.heap, a) = some(.object(sl', ps')) /\ objKept(s, s', sl, ps, sl', ps')));
9.6 Agents sec-agents

The values of [[LittleEndian]], [[Signifier]], [[IsLockFree1]], [[IsLockFree2]], and [[IsLockFree8]] cannot change.

The [[GlobalSymbolRegistry]] List is append-only and never reassigned.

A host step keeps the surrounding agent, its Agent Record's sort and those fields (agentKept).

agentFixed
SpecTec
law agentFixed : forall s s', H.Step(s, s') -> agentKept(s, s');
9.3.1 InitializeHostDefinedRealm steps 10–10.a sec-initializehostdefinedrealm

If the host requires use of a specific object to serve as realm's global object, then … Let global be such an object created in a host-defined manner.

9.3.1 InitializeHostDefinedRealm steps 12–12.a sec-initializehostdefinedrealm

If the host requires that the this binding in realm's global scope return an object other than the global object, then … Let thisValue be such an object created in a host-defined manner.

9.3.1 InitializeHostDefinedRealm step 17 sec-initializehostdefinedrealm

Create any host-defined global object properties on global.

2 Conformance sec-conformance

a conforming implementation of ECMAScript may provide properties not described in this specification, and values for those properties, for objects that are described in this specification

17.1 Forbidden Extensions sec-forbidden-extensions

Built-in functions, strict functions created using the Function constructor, generator functions created using the Generator constructor, async functions created using the AsyncFunction constructor, and functions created using the bind method also must not be created with such own properties.

2 Conformance sec-conformance

a conforming implementation of ECMAScript may provide properties not described in this specification, and values for those properties, for objects that are described in this specification

10.3.3 BuiltinCallOrConstruct step 8 sec-builtincallorconstruct

Perform any necessary implementation-defined initialization of calleeContext.

HostInitializeBuiltinContext answers unused and changes only calleeContext, which keeps its kind and every component the execution context tables define (contextField).

hostInitializeBuiltinContext
SpecTec
law hostInitializeBuiltinContext : forall ctx s r s', H.choice(Known.pHostInitializeBuiltinContext, [.ref(ctx)], s) = .ok(r, s') -> r = .enum(Known.eUnused) /\ s' = { s with heap := s'.heap } /\ (forall a c, a <> ctx -> M.heapGet(s.heap, a) = some(c) -> M.heapGet(s'.heap, a) = some(c)) /\ forall k fs, M.heapGet(s.heap, ctx) = some(.record(k, fs)) -> (exists fs', M.heapGet(s'.heap, ctx) = some(.record(k, fs')) /\ forall f, contextField(f) -> M.recGet(fs', f) = M.recGet(fs, f));
9.9.4.1 HostEnqueueFinalizationRegistryCleanupJob step 2 sec-host-cleanup-finalization-registry

If cleanupResult is an abrupt completion, perform any host-defined steps for reporting the error.

No sentence HostReportErrors is HTML's report-an-exception hook invoked on an abrupt settle result in PromiseReactionJob (sec-newpromisereactionjob).
9.12 CleanupFinalizationRegistry step 3 sec-cleanup-finalization-registry

While finalizationRegistry.[[Cells]] contains a Record cell such that cell.[[WeakRefTarget]] is empty, an implementation may perform the following steps: 1. Choose any such cell.

15.10.3 PrepareForTailCall step 2 sec-preparefortailcall

Discard all resources associated with the current execution context.

15.10.3 PrepareForTailCall sec-preparefortailcall

A tail position call must either release any transient internal resources associated with the currently executing function execution context before invoking the target function or reuse those resources in support of the target function.

9.9.3 Execution sec-weakref-execution

At any time, if a set of objects and/or symbols objSet is not live, an ECMAScript implementation may perform the following steps atomically

9.9.2 Liveness sec-liveness

Any element in objSet is included in any agent's [[KeptAlive]] List.

The host's collection empties, together, the WeakRefs, FinalizationRegistry cells, WeakMap entries and WeakSet elements of a set of objects and Symbols none of which is kept alive, and changes nothing else (Collected); a host that collects nothing meets it.

collect
SpecTec
law collect : forall s xs s', H.collect(s) = .ok(xs, s') -> Collected(s, xs, s');

What the host's laws are stated over

From spec/spectec/prose/14-host-laws-basic.spectec

A host's answer (Host.answers, Host.asks), a host step (Host.Step), and the readings of the state the laws share: Completion Records' kinds, Records by sort, the execution context stack, Strings as code units, and the agent and elapsed-time helpers.

Auxiliary definitions (28): selects, numValue, lastElapsed, mathAfter, …
def

selects

14-host-laws-basic.spectec:16

A HostSelectAgent answer that selects an agent.

def selects {M : Model} : Val(M) -> Bool  | .ref(_) => true  | _ => falseend
def

numValue

14-host-laws-basic.spectec:22

The mathematical value of a finite or zero Number; none for ±∞𝔽 and NaN.

def numValue {M : Model} (n : M.Num) : Option(M.Math) := match M.numView(n) with  | .posZero | .negZero => some(M.ofNat(0))  | .finite(m) => some(m)  | _ => noneend
def

lastElapsed

14-host-laws-basic.spectec:29

The elapsed time the newest next of the log logged; 0 where there is none.

def lastElapsed {M : Model} : List(HostCall(M)) -> M.Math  | [] => M.ofNat(0)  | .next(_, t) :: _ => t  | _ :: log => lastElapsed(log)end
def

mathAfter

14-host-laws-basic.spectec:36

t₁ ≥ t₀ + ℝ(ms): never for ms +∞, always for ms −∞ or NaN.

def mathAfter {M : Model} (t₀ t₁ : M.Math) (ms : M.Num) : Bool := match numValue(ms) with  | some(m) => !M.lt(t₁, M.add(t₀, m))  | none => match M.numView(ms) with      | .posInf => false      | _ => true    endend
def

fieldOf

14-host-laws-basic.spectec:45

A field of the Record a value refers to.

def fieldOf {M : Model} (s : State(M)) (f : FieldId) : Val(M) -> Option(Val(M))  | .ref(a) => match M.heapGet(s.heap, a) with      | some(.record(_, fs)) => M.recGet(fs, f)      | _ => none    end  | _ => noneend
def

slotOf

14-host-laws-basic.spectec:54

An internal slot of the object at a.

def slotOf {M : Model} (s : State(M)) (a : M.Addr) (f : FieldId) : Option(Val(M)) := match M.heapGet(s.heap, a) with  | some(.object(sl, _)) => M.recGet(sl, f)  | _ => noneend
def

listElems

14-host-laws-basic.spectec:60

The elements of the List a value refers to.

def listElems {M : Model} (s : State(M)) : Val(M) -> Option(List(Val(M)))  | .ref(a) => match M.heapGet(s.heap, a) with      | some(.list(xs, _)) => some(M.seqFoldl(fun l v => l ++ [v], [], xs))      | _ => none    end  | _ => noneend
def

HostCall.switchFrom

14-host-laws-basic.spectec:69

A logged HostSelectAgent that selected an agent: the surrounding agent it was called in.

def HostCall.switchFrom {M : Model} : HostCall(M) -> Option(Val(M))  | .choice(q, a :: _, .ref(_)) => if q == Known.pHostSelectAgent then some(a) else none  | _ => noneend
def

withAgents

14-host-laws-basic.spectec:76

The log (newest first), each call with the agent it ran in: cur after the newest switch, a switch's surrounding agent at it and before it.

def withAgents {M : Model} (cur : Val(M)) : List(HostCall(M)) -> List(HostCall(M) times Val(M))  | [] => []  | e :: log => let a := e.switchFrom.getD(cur) in (e, a) :: withAgents(a, log)end
def

sigOf

14-host-laws-basic.spectec:82

An Agent Record's signifier, its [[Signifier]].

def sigOf {M : Model} (s : State(M)) (x : Val(M)) : Val(M) := fieldOf(s, Known.fSignifier, x).getD(.absent)
def

isEmptyV

14-host-laws-basic.spectec:85

empty.

def isEmptyV {M : Model} : Val(M) -> Bool  | .enum(e) => e == Known.eEmpty  | _ => falseend
def

pendingList

14-host-laws-basic.spectec:91

The waiter list of the agent x's pending suspension (signifier sig) in a log with agents.

def pendingList {M : Model} (x sig : Val(M)) : List(HostCall(M) times Val(M)) -> Option(Val(M))  | [] => none  | (.choice(q, vs, _), a) :: es => if q == Known.pWakeAgent && vs.any(Val.same(sig)) then none else if q == Known.pSuspendAgentUntil && Val.same(a, x) then vs.head? else pendingList(x, sig, es)  | _ :: es => pendingList(x, sig, es)end
def

idleWait

14-host-laws-basic.spectec:99

The agent x's pending suspension is the host's own wait for a message or a job: its waiter list is empty (SuspendThisAgent's is a WaiterList).

def idleWait {M : Model} (s : State(M)) (x : Val(M)) : Bool := pendingList(x, sigOf(s, x), withAgents(s.agent, s.hostLog)).map(isEmptyV).getD(false)
def

jobAgentOf

14-host-laws-basic.spectec:104

The signifier of the agent whose job a logged call e, run in the agent a, schedules: its realm's [[AgentSignifier]] (§9.5: "in the agent signified by realm.[[AgentSignifier]]"), else (a promise job of no realm) a's.

def jobAgentOf {M : Model} (s : State(M)) : HostCall(M) times Val(M) -> Val(M)  | (.hook(_, _ :: realm :: _, _, _, _), a) => fieldOf(s, Known.fAgentSignifier, realm).getD(sigOf(s, a))  | (_, a) => sigOf(s, a)end
def

jobAgents

14-host-laws-basic.spectec:110

The signifiers of the agents of the jobs the log's calls schedule, by log position.

def jobAgents {M : Model} (s : State(M)) : Array(Val(M)) := withAgents(s.agent, s.hostLog).map(jobAgentOf(s)).reverse.toArray
def

clusterSigs

14-host-laws-basic.spectec:114

The signifiers of the surrounding agent's cluster: its candidate execution's Agent Events Records' [[AgentSignifier]]s.

def clusterSigs {M : Model} (s : State(M)) : List(Val(M)) := match fieldOf(s, Known.fCandidateExecution, s.agent).bind(fieldOf(s, Known.fEventsRecords)).bind(listElems(s)) with  | some(ers) => ers.filterMap(fieldOf(s, Known.fAgentSignifier))  | none => []end
def

Host.answers

14-host-laws-basic.spectec:123

r is the host-defined operation c's answer to xs in s, the state then s'; an escaping completion is its answer.

def Host.answers (H : Host(M)) (c : ClauseId) (xs : List(Val(M))) (s : State(M)) (r : Val(M)) (s' : State(M)) : Prop := Run.boundary(H.hook(c, xs), s) = .ok(r, s')
def

Host.asks

14-host-laws-basic.spectec:126

The host answers the question q without changing the state, and its answer has P.

def Host.asks (H : Host(M)) (q : PrimId) (P : List(Val(M)) -> State(M) -> Val(M) -> Prop) : Prop := forall vs s r s', H.choice(q, vs, s) = .ok(r, s') -> s' = s /\ P(vs, s, r)
def

Host.Step

14-host-laws-basic.spectec:131

A host step from s to s': a host-defined operation's or a host choice's answer, the next job, whether to clear kept objects, a job's preparation or cleanup, the host's own first Job, what it does when the agent has no Job, and its cleanup after either.

def Host.Step (H : Host(M)) (s s' : State(M)) : Prop := (exists c xs r, H.answers(c, xs, s, r, s')) \/ (exists q vs r, Run.boundary(H.choice(q, vs), s) = .ok(r, s')) \/ (exists k, H.nextJob(s) = .ok(k, s')) \/ (exists b, H.clearsKept(s) = .ok(b, s')) \/ (exists k, H.prepareJob(k, s) = .ok((), s')) \/ (exists k, H.cleanupJob(k, s) = .ok((), s')) \/ (exists a, H.first(s) = .ok(a, s')) \/ (exists a, H.idle(s) = .ok(a, s')) \/ exists v b, H.idleEnd(v, s) = .ok(b, s')
def

compType

14-host-laws-basic.spectec:134

A Completion Record's [[Type]]; a value that is no Completion Record is a normal completion's.

def compType : Val(M) -> EnumId  | .comp(t, _, _) => t  | _ => Known.eNormalend
def

normalValue

14-host-laws-basic.spectec:140

The value of a normal completion; a value that is no Completion Record is its own.

def normalValue : Val(M) -> Option(Val(M))  | .comp(t, v, _) => if t == Known.eNormal then some(v) else none  | v => some(v)end
def

dataSubSort

14-host-laws-basic.spectec:146

k is the sort t or a subsort of it, by the data's SortDef.super (to depth f).

def dataSubSort : Nat -> SortId -> SortId -> Bool  | 0, k, t => k == t  | f + 1, k, t => k == t || Gen.sortDefs[k]?.join.map(fun _dot0 => _dot0.super).getD([]).any(fun _dot0 => dataSubSort(f, _dot0, t))end
def

isRecordOf

14-host-laws-basic.spectec:152

A value is a Record of the sort named sort, or of a subsort of it.

def isRecordOf (s : State(M)) (sort : String) : Val(M) -> Bool  | .ref(a) => match M.heapGet(s.heap, a), Gen.sorts.idxOf?(sort) with      | some(.record(k, _)), some(t) => dataSubSort(64, k, t)      | _, _ => false    end  | _ => falseend
def

fieldNamed

14-host-laws-basic.spectec:161

A field id by its name in the data.

def fieldNamed (f : String) : FieldId := Gen.fields.idxOf?(f).getD(0)
def

stackList

14-host-laws-basic.spectec:164

The execution context stack as a List, the topmost last.

def stackList (s : State(M)) : List(Val(M)) := M.seqFoldl(fun l v => l ++ [v], [], s.stack)
def

listAt

14-host-laws-basic.spectec:167

The elements of the List a value refers to.

def listAt (s : State(M)) : Val(M) -> Option(List(Val(M)))  | .ref(a) => match M.heapGet(s.heap, a) with      | some(.list(sq, _)) => some(seqList(sq))      | _ => none    end  | _ => noneend
def

unitsMatch

14-host-laws-basic.spectec:176

The code units us are the naturals l.

def unitsMatch : List(M.Math) -> List(Nat) -> Prop  | [], [] => True  | u :: us, c :: l => M.eq(u, M.ofNat(c)) = true /\ unitsMatch(us, l)  | _, _ => Falseend
def

unitsAre

14-host-laws-basic.spectec:183

The String x's code units are l.

def unitsAre (x : M.Str) (l : List(Nat)) : Prop := unitsMatch(seqList(M.strUnits(x)), l)

From spec/spectec/prose/13-jobs.spectec

The Job a logged call scheduled, whether every scheduled Job has been taken, the host's next-job answer as a log entry, and what the host does at a job boundary (§9.5, §9.10).

Auxiliary definition: scheduled
def

scheduled

13-jobs.spectec:13

The Job Abstract Closure the host-call log's entry at position k scheduled: its first argument.

def scheduled (log : List(HostCall(M))) (k : Nat) : Option(Val(M)) := match log.reverse[k]? with  | some(.hook(_, job :: _, _, _, _)) => some(job)  | _ => noneend

The Date Time String Format, over code units

From spec/spectec/prose/15-date-format.spectec

The Strings of the Date Time String Format (sec-date-time-string-format) as integers and code units: what ParseDateString's laws (Ecma.Host.TimeLaws) are stated over.

Auxiliary definitions (4): decUnits, numIs, tvResult, daysInMonth
def

decUnits

15-date-format.spectec:11

The last n decimal digits of v, the most significant first, as code units.

def decUnits : Nat -> Nat -> List(Nat)  | 0, _ => []  | n + 1, v => (48 + v / 10 ^ n % 10) :: decUnits(n, v)end
def

numIs

15-date-format.spectec:17

n is the integral Number t: +0𝔽 for 0, else the finite Number whose value is t.

def numIs {M : Model} (n : M.Num) (t : Int) : Prop := if t = 0 then M.numView(n) = .posZero else exists m, M.numView(n) = .finite(m) /\ M.eq(m, intMath(t)) = true
def

tvResult

15-date-format.spectec:20

r is the time value of the instant t: t where it is in range, else NaN.

def tvResult {M : Model} (r : Val(M)) (t : Int) : Prop := exists n, r = .num(n) /\ if inTime(t) then numIs(n, t) else M.numView(n) = .nan
def

daysInMonth

15-date-format.spectec:23

The days of month mo (1 to 12) of year y.

def daysInMonth (y : Int) (mo : Nat) : Nat := [31, 28 + leapDays(y), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31].getD(mo - 1, 0)
syntax record

DateTimePart

15-date-format.spectec:28

A date-time form's time part (§21.4.1.32, sec-date-time-string-format): THH:mm, then optionally :ss and then optionally .sss, then the UTC offset representation: none, "Z" (some none), or a sign (true for "-"), HH, ":" and mm.

syntax DateTimePart record
h : Nat;
mi : Nat;
sec : Option(Nat times Option(Nat));
off : Option(Option(Bool times Nat times Nat));
syntax record

DateForm

15-date-format.spectec:38

A String of the Date Time String Format's shape (§21.4.1.32, sec-date-time-string-format): YYYY, or an expanded year's sign (true for "-") and six digits; optionally -MM and then optionally -DD; optionally a time part.

syntax DateForm record
sign : Option(Bool);
md : Option(Nat times Option(Nat));
Auxiliary definitions (22): DateForm.signUnits, DateForm.offUnits, DateForm.secPart, DateForm.timeUnits, …
def

DateForm.signUnits

15-date-format.spectec:47

"-" or "+".

def signUnits (neg : Bool) : List(Nat) := if neg then [45] else [43]
def

DateForm.offUnits

15-date-format.spectec:50

The UTC offset representation's code units.

def offUnits : Option(Option(Bool times Nat times Nat)) -> List(Nat)  | none => []  | some(none) => [90]  | some(some((n, h, m))) => signUnits(n) ++ decUnits(2, h) ++ [58] ++ decUnits(2, m)end
def

DateForm.secPart

15-date-format.spectec:57

:ss and .sss's code units.

def secPart : Option(Nat times Option(Nat)) -> List(Nat)  | none => []  | some((sc, none)) => [58] ++ decUnits(2, sc)  | some((sc, some(ms))) => [58] ++ decUnits(2, sc) ++ [46] ++ decUnits(3, ms)end
def

DateForm.timeUnits

15-date-format.spectec:64

A time part's code units.

def timeUnits (p : DateTimePart) : List(Nat) := [84] ++ decUnits(2, p.h) ++ [58] ++ decUnits(2, p.mi) ++ secPart(p.sec) ++ offUnits(p.off)
def

DateForm.yearPart

15-date-format.spectec:67

The year's code units.

def yearPart (f : DateForm) : List(Nat) := match f.sign with  | none => decUnits(4, f.year)  | some(n) => signUnits(n) ++ decUnits(6, f.year)end
def

DateForm.mdPart

15-date-format.spectec:73

-MM and -DD's code units.

def mdPart : Option(Nat times Option(Nat)) -> List(Nat)  | none => []  | some((mo, none)) => [45] ++ decUnits(2, mo)  | some((mo, some(d))) => [45] ++ decUnits(2, mo) ++ [45] ++ decUnits(2, d)end
def

DateForm.timePart

15-date-format.spectec:80

The time part's code units, if any.

def timePart : Option(DateTimePart) -> List(Nat)  | none => []  | some(p) => timeUnits(p)end
def

DateForm.units

15-date-format.spectec:86

The String's code units.

def units (f : DateForm) : List(Nat) := f.yearPart ++ mdPart(f.md) ++ timePart(f.time)
def

DateForm.yearInt

15-date-format.spectec:89

The year.

def yearInt (f : DateForm) : Int := if f.sign = some(true) then -(f.year : Int) else f.year
def

DateForm.month

15-date-format.spectec:92

The month, "01" where absent.

def month (f : DateForm) : Nat := f.md.map(fun _dot0 => _dot0.1).getD(1)
def

DateForm.day

15-date-format.spectec:95

The day, "01" where absent.

def day (f : DateForm) : Nat := f.md.bind(fun _dot0 => _dot0.2).getD(1)
def

DateForm.hour

15-date-format.spectec:98

The hour, "00" where absent.

def hour (f : DateForm) : Nat := f.time.map(fun _dot0 => _dot0.h).getD(0)
def

DateForm.minute

15-date-format.spectec:101

The minute, "00" where absent.

def minute (f : DateForm) : Nat := f.time.map(fun _dot0 => _dot0.mi).getD(0)
def

DateForm.second

15-date-format.spectec:104

The second, "00" where absent.

def second (f : DateForm) : Nat := f.time.bind(fun p => p.sec.map(fun _dot0 => _dot0.1)).getD(0)
def

DateForm.milli

15-date-format.spectec:107

The millisecond, "000" where absent.

def milli (f : DateForm) : Nat := f.time.bind(fun p => p.sec.bind(fun _dot0 => _dot0.2)).getD(0)
def

DateForm.offset

15-date-format.spectec:110

The UTC offset representation's sign, hours and minutes; none for "Z" or none.

def offset (f : DateForm) : Option(Bool times Nat times Nat) := f.time.bind(fun _dot0 => _dot0.off).join
def

DateForm.offsetMin

15-date-format.spectec:113

The UTC offset in minutes, 0 for "Z" or none.

def offsetMin (f : DateForm) : Int := match f.offset with  | some((n, h, m)) => (if n then -1 else 1) * ((h * 60 + m : Nat) : Int)  | none => 0end
def

DateForm.isLocal

15-date-format.spectec:119

A date-time form without a UTC offset: a local time.

def isLocal (f : DateForm) : Bool := match f.time with  | some(p) => p.off.isNone  | none => falseend
def

DateForm.ms

15-date-format.spectec:125

The time value of the fields, before the UTC offset is applied.

def ms (f : DateForm) : Int := dateMs(f.yearInt, f.month, f.day, f.hour, f.minute, f.second, f.milli)
def

DateForm.fits

15-date-format.spectec:128

Each element's value has as many digits as the element.

def fits (f : DateForm) : Prop := f.year < (if f.sign.isSome then 10 ^ 6 else 10 ^ 4) /\ f.month < 100 /\ f.day < 100 /\ f.hour < 100 /\ f.minute < 100 /\ f.second < 100 /\ f.milli < 1000 /\ forall n h m, f.offset = some((n, h, m)) -> h < 100 /\ m < 100
def

DateForm.legal

15-date-format.spectec:133

A valid instance of the format: each element in bounds, a day of the month, "24" only as 24:00, 24:00:00 or 24:00:00.000, an offset's HH from 00 to 23 (UTCOffset's Hour), and no year 0 as -000000 (§21.4.1.32.1).

def legal (f : DateForm) : Prop := 1 <= f.month /\ f.month <= 12 /\ 1 <= f.day /\ f.day <= daysInMonth(f.yearInt, f.month) /\ (f.hour <= 23 \/ f.hour = 24 /\ f.minute = 0 /\ f.second = 0 /\ f.milli = 0) /\ f.minute <= 59 /\ f.second <= 59 /\ (forall n h m, f.offset = some((n, h, m)) -> h <= 23 /\ m <= 59) /\ not (f.sign = some(true) /\ f.year = 0)
def

DateForm.illegal

15-date-format.spectec:137

An element out of the bounds the format's table gives it (MM 01 to 12, DD 01 to 31, HH 00 to 24, mm and ss 00 to 59), or the year 0 as -000000.

def illegal (f : DateForm) : Prop := f.month = 0 \/ 12 < f.month \/ f.day = 0 \/ 31 < f.day \/ 24 < f.hour \/ 59 < f.minute \/ 59 < f.second \/ (exists n h m, f.offset = some((n, h, m)) /\ (24 < h \/ 59 < m)) \/ f.sign = some(true) /\ f.year = 0

From spec/spectec/prose/11-date-parse.spectec

Time-value range (maxTime, inTime) and the calendar epoch calculation (leapDays, daysBefore, yearDay, dateMs) used by the host date laws (Ecma.Host.Laws.DateFormat).

Auxiliary definitions (7): intMath, maxTime, inTime, leapDays, …
def

intMath

11-date-parse.spectec:14

An integer as a model mathematical value.

def intMath {M : Model} : Int -> M.Math  | .ofNat(n) => M.ofNat(n)  | .negSucc(n) => M.neg(M.ofNat(n + 1))end
def

maxTime

11-date-parse.spectec:20

The time value limit, 8.64 × 10^15 milliseconds (§21.4.1.1).

def maxTime : Nat := 8640000000000000
def

inTime

11-date-parse.spectec:23

Whether t is within ECMAScript's time value range (|t| ≤ 8.64 × 10^15).

def inTime (t : Int) : Bool := decide(t.natAbs <= maxTime)
def

leapDays

11-date-parse.spectec:26

Whether year y is a leap year (1 or 0 extra days, §21.4.1.3).

def leapDays (y : Int) : Nat := if y % 4 <> 0 then 0 else if y % 100 <> 0 then 1 else if y % 400 <> 0 then 0 else 1
def

daysBefore

11-date-parse.spectec:29

Days in year y before 1-based month mo (1..12).

def daysBefore (y : Int) (mo : Nat) : Nat := [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334].getD(mo - 1, 0) + (if 2 < mo then leapDays(y) else 0)
def

yearDay

11-date-parse.spectec:32

DayFromYear(y) (§21.4.1.3).

def yearDay (y : Int) : Int := 365 * (y - 1970) + (y - 1969) / 4 - (y - 1901) / 100 + (y - 1601) / 400
def

dateMs

11-date-parse.spectec:35

Time value in milliseconds from year, 1-based month, day, hour, minute, second and millisecond.

def dateMs (y : Int) (mo d h mi sc ms : Nat) : Int := (yearDay(y) + daysBefore(y, mo) + ((d : Int) - 1)) * 86400000 + (((h * 60 + mi) * 60 + sc) * 1000 + ms : Nat)

EnumerateObjectProperties as a host strategy

From spec/spectec/prose/12-for-in.spectec

The actions and history of ForInStep (ForInAct, ForInEntry, forInHist, actRecord), the rules of EnumerateObjectProperties over the history (ForInRules, ForInRun), the state machine of %ForInIteratorPrototype%.next (CfiSt, cfiNext, CfiOk), and the conditions under which its replay applies (cfiApplies).

syntax

ForInAct

12-for-in.spectec:16

An action of the enumeration (§14.7.5.9, sec-enumerate-object-properties): call [[OwnPropertyKeys]], [[GetOwnProperty]] or [[GetPrototypeOf]] of an object, return a key, or end.

syntax ForInAct (M : Model)
syntax

ForInEntry

12-for-in.spectec:26

An action of the history with its result (§14.7.5.9, sec-enumerate-object-properties): the keys; undefined (none) or a Property Descriptor and whether its [[Enumerable]] is true; the prototype, none for null.

syntax ForInEntry (M : Model)
Auxiliary definitions (8): ForInEntry.act, recIn, listIn, actIn, …
def

ForInEntry.act

12-for-in.spectec:34

The action an entry made.

def ForInEntry.act : ForInEntry(M) -> ForInAct(M)  | .keys(o, _) => .keys(o)  | .own(o, k, _) => .own(o, k)  | .proto(o, _) => .proto(o)  | .yield(k) => .yield(k)end
def

recIn

12-for-in.spectec:42

The fields of the Record a value refers to.

def recIn (s : State(M)) : Val(M) -> Option(M.Rec(Val(M)))  | .ref(a) => match M.heapGet(s.heap, a) with      | some(.record(_, fs)) => some(fs)      | _ => none    end  | _ => noneend
def

listIn

12-for-in.spectec:51

The elements of the List a value refers to.

def listIn (s : State(M)) : Val(M) -> Option(List(Val(M)))  | .ref(a) => match M.heapGet(s.heap, a) with      | some(.list(xs, _)) => some(M.seqFoldl(fun l v => l ++ [v], [], xs))      | _ => none    end  | _ => noneend
def

actIn

12-for-in.spectec:60

The action an action Record states.

def actIn (s : State(M)) (v : Val(M)) : Option(ForInAct(M)) := do {  let fs <- recIn(s, v);  match M.recGet(fs, Known.fKind), M.recGet(fs, Known.fObject), M.recGet(fs, Known.fKey) with    | some(.enum(k)), some(.obj(o)), _ => if k == Known.eOwnPropertyKeys then some(.keys(o)) else if k == Known.eGetPrototypeOf then some(.proto(o)) else if k == Known.eGetOwnProperty then M.recGet(fs, Known.fKey).map(.own(o)) else none    | some(.enum(k)), _, some(.str(x)) => if k == Known.eYield then some(.yield(x)) else none    | some(.enum(k)), _, _ => if k == Known.eDone then some(.done) else none    | _, _, _ => none  end;}
def

entryInBy

12-for-in.spectec:71

An entry of the history: a Record { [[Action]], [[Result]] }, its Lists' elements read by rd.

SpecTec, 19 lines
def entryInBy (rd : State(M) -> Val(M) -> Option(List(Val(M)))) (s : State(M)) (v : Val(M)) : Option(ForInEntry(M)) := do {  let fs <- recIn(s, v);  let a <- M.recGet(fs, Known.fAction);  let r <- M.recGet(fs, Known.fResult);  match <- actIn(s, a) with    | .keys(o) => rd(s, r).map(.keys(o))    | .own(o, k) => match r with        | .undefined => some(.own(o, k, none))        | d => recIn(s, d).map(fun dfs => .own(o, k, some(M.recGet(dfs, Known.fEnumerable) matches some(.bool(true)))))      end    | .proto(o) => match r with        | .obj(p) => some(.proto(o, some(p)))        | .null => some(.proto(o, none))        | _ => none      end    | .yield(k) => some(.yield(k))    | .done => none  end;}
def

entryIn

12-for-in.spectec:92

An entry of the history: a Record { [[Action]], [[Result]] }.

def entryIn (s : State(M)) (v : Val(M)) : Option(ForInEntry(M)) := entryInBy(listIn, s, v)
def

forInHist

12-for-in.spectec:95

The history ForInStep is given, as entries.

def forInHist (s : State(M)) (h : Val(M)) : Option(List(ForInEntry(M))) := listIn(s, h).bind(fun vs => vs.mapM(entryIn(s)))
def

actRecord

12-for-in.spectec:98

A new action Record { [[Kind]], [[Object]], [[Key]] }, empty where the action has none.

def actRecord (a : ForInAct(M)) : Run(M, Val(M)) := do {  let (k, o, x) : EnumId times Val(M) times Val(M) := match a with    | .keys(o) => (Known.eOwnPropertyKeys, .obj(o), .enum(Known.eEmpty))    | .own(o, k) => (Known.eGetOwnProperty, .obj(o), k)    | .proto(o) => (Known.eGetPrototypeOf, .obj(o), .enum(Known.eEmpty))    | .yield(k) => (Known.eYield, .enum(Known.eEmpty), .str(k))    | .done => (Known.eDone, .enum(Known.eEmpty), .enum(Known.eEmpty))  end;  return .ref(<- alloc(.record(Known.sRecord, M.recSet(M.recSet(M.recSet(M.recEmpty, Known.fKind, .enum(k)), Known.fObject, o), Known.fKey, x))));}
syntax record

CfiSt

12-for-in.spectec:111

A For-In Iterator's state (§14.7.5.10, sec-for-in-iterator-objects): [[Object]] (none for null), [[ObjectWasVisited]], [[VisitedKeys]], [[RemainingKeys]], and the key next returns before it continues.

syntax CfiSt (M : Model) record
Auxiliary definitions (6): CfiSt.init, strKeys, cfiSkip, CfiSt.next, …
def

CfiSt.init

12-for-in.spectec:120

CreateForInIterator(obj).

def CfiSt.init (obj : M.Addr) : CfiSt(M) := ctor(some(obj), false, [], [], none)
def

strKeys

12-for-in.spectec:123

The keys that are Strings.

def strKeys (ks : List(Val(M))) : List(M.Str) := ks.filterMap(fun  | .str(k) => some(k)  | _ => noneend)
def

cfiSkip

12-for-in.spectec:129

[[RemainingKeys]] without its first keys that [[VisitedKeys]] contains.

def cfiSkip (vis : List(M.Str)) : List(M.Str) -> List(M.Str)  | [] => []  | k :: r => if vis.any(fun _dot0 => M.strEq(_dot0, k)) then cfiSkip(vis, r) else k :: rend
def

CfiSt.next

12-for-in.spectec:135

The next action of next.

def CfiSt.next (st : CfiSt(M)) : ForInAct(M) := match st.pending, st.cur with  | some(k), _ => .yield(k)  | none, none => .done  | none, some(o) => if !st.was then .keys(o) else match cfiSkip(st.visited, st.remaining) with      | k :: _ => .own(o, .str(k))      | [] => .proto(o)    endend
def

CfiSt.step

12-for-in.spectec:145

The state after an action and its result.

def CfiSt.step (st : CfiSt(M)) : ForInEntry(M) -> CfiSt(M)  | .keys(_, ks) => { st with was := true, remaining := st.remaining ++ strKeys(ks) }  | .own(_, _, d) => match cfiSkip(st.visited, st.remaining) with      | k :: r => ctor(st.cur, st.was, if d.isSome then st.visited ++ [k] else st.visited, r, if d = some(true) then some(k) else none)      | [] => st    end  | .proto(_, p) => { st with cur := p, was := false, remaining := [] }  | .yield(_) => { st with pending := none }end
def

cfiNext

12-for-in.spectec:156

The action next makes after the entries es.

def cfiNext (obj : M.Addr) (es : List(ForInEntry(M))) : ForInAct(M) := es.foldl(CfiSt.step, CfiSt.init(obj)).next

The rules (§14.7.5.9 EnumerateObjectProperties), over the entries before an action.

Auxiliary definitions (4): chainObj, accounted, ForInRules, ForInRun
def

chainObj

12-for-in.spectec:161

o is obj or an object a [[GetPrototypeOf]] call gave: an object of obj's prototype chain.

def chainObj (obj : M.Addr) (es : List(ForInEntry(M))) (o : M.Addr) : Prop := o = obj \/ exists p, ForInEntry.proto(p, some(o)) mem es
def

accounted

12-for-in.spectec:165

A key is accounted for: returned, or a [[GetOwnProperty]] call for it gave undefined or a property that is not enumerable.

def accounted (es : List(ForInEntry(M))) (k : M.Str) : Prop := ForInEntry.yield(k) mem es \/ exists o d, ForInEntry.own(o, .str(k), d) mem es /\ d <> some(true)
def

ForInRules

12-for-in.spectec:168

The rules an action obeys after the entries es.

def ForInRules (obj : M.Addr) (es : List(ForInEntry(M))) : ForInAct(M) -> Prop  | .keys(o) => chainObj(obj, es, o)  | .own(o, k) => chainObj(obj, es, o) /\ exists ks, ForInEntry.keys(o, ks) mem es /\ k mem ks  | .proto(o) => chainObj(obj, es, o)  | .yield(k) => (forall e mem es, e <> .yield(k)) /\ exists (i : Nat) (o : M.Addr), es[i]? = some(.own(o, .str(k), some(true))) /\ chainObj(obj, es, o) /\ (o <> obj -> (forall j < i, forall o' d, es[j]? = some(.own(o', .str(k), some(d))) -> o' = o))  | .done => (exists o, chainObj(obj, es, o) /\ ForInEntry.proto(o, none) mem es) /\ (forall o, chainObj(obj, es, o) -> (exists ks, ForInEntry.keys(o, ks) mem es)) /\ forall o ks k, ForInEntry.keys(o, ks) mem es -> Val.str(k) mem ks -> accounted(es, k)end
def

ForInRun

12-for-in.spectec:177

Every entry obeyed the rules after the entries before it.

def ForInRun (obj : M.Addr) (es : List(ForInEntry(M))) : Prop := forall (i : Nat) (h : i < es.length), ForInRules(obj, es.take(i), es[i].act)

The replay of %ForInIteratorPrototype%.next (§14.7.5.10.2.1).

Auxiliary definition: CfiOk
def

CfiOk

12-for-in.spectec:182

Each entry is the action next makes from the state before it.

def CfiOk : CfiSt(M) -> List(ForInEntry(M)) -> Prop  | _, [] => True  | st, e :: es => e.act = st.next /\ CfiOk(st.step(e), es)end

The conditions of ¶3 under which the iterator behaves as CreateForInIterator(obj)'s.

relation

InChain

12-for-in.spectec:191

o is obj or an object of its prototype chain, by the [[Prototype]] slots of s (§14.7.5.9, sec-enumerate-object-properties).

relation InChain (s : State(M)) (obj : M.Addr) : M.Addr -> Prop
Auxiliary definitions (4): exoticSlots, plainChain, shapeKept, cfiApplies
def

exoticSlots

12-for-in.spectec:197

The slots of a Proxy exotic object, a TypedArray and a module namespace exotic object.

def exoticSlots : List(FieldId) := [Known.fProxyHandler, Known.fTypedArrayName, Known.fExports]
def

plainChain

12-for-in.spectec:201

No object of obj's prototype chain is a Proxy exotic object, TypedArray or module namespace exotic object; the model's objects have no other internal methods than the specification's.

def plainChain (s : State(M)) (obj : M.Addr) : Prop := forall o sl ps, InChain(s, obj, o) -> M.heapGet(s.heap, o) = some(.object(sl, ps)) -> (forall f mem exoticSlots, M.recGet(sl, f) = none)
def

shapeKept

12-for-in.spectec:205

No object of the chain changed shape since the enumeration's first ForInStep call (a property added to obj itself aside): for-in calls next right after EnumerateObjectProperties returns.

def shapeKept (s : State(M)) (obj : M.Addr) (h : Val(M)) : Prop := forall c mem s.shapeLog, InChain(s, obj, c.obj) -> c.added = true /\ c.obj = obj \/ forall i ans, s.hostLog.reverse[i]? = some(.choice(Known.pForInStep, [.obj(obj), h], ans)) -> c.stamp <= i
def

cfiApplies

12-for-in.spectec:208

¶3's conditions hold, and every action so far was CreateForInIterator's.

def cfiApplies (s : State(M)) (obj : M.Addr) (h : Val(M)) (es : List(ForInEntry(M))) : Prop := plainChain(s, obj) /\ shapeKept(s, obj, h) /\ CfiOk(CfiSt.init(obj), es)