hook : ClauseId -> List(Val(M)) -> Run(M, Val(M));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.
Host
10-host.spectec:18The 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) recordchoice : PrimId -> List(Val(M)) -> Run(M, Val(M));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
activeScriptOrModule
10-host.spectec:89The 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).
Host.WF
26-host-laws.spectec:23The 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:
escapePatternstricter requires\/and the line terminators' escapes, where the text also allows an unescaped/in a character class.nativeFunctionSourcestricter one ASCII form,function name() { [native code] }, where the text allows any NativeFunction.collectweaker approximates liveness by syntactic heap reachability at job boundaries (omitting future-execution observability and cleanup-job scheduling guarantees).agentNextJobweaker there is no law about a timeout.
| Law | Topic | Clause | Reading |
|---|---|---|---|
nextJob | Job | 9.5 Jobs and Host Operations to Enqueue Jobs | The job the host takes next is one it may take now (Host.mayRun), each taken once. |
agentNextJobweaker | Job | 9.5 Jobs and Host Operations to Enqueue Jobs | AgentNextJob answers empty or a job it may take now (Host.mayRun), the state as it was. |
ownsAgent | Job | 9.5 Jobs and Host Operations to Enqueue Jobs | With more than one agent in the cluster, a job the host may take is the surrounding agent's. |
ownsSingle | Job | 9.5 Jobs and Host Operations to Enqueue Jobs | With one agent in the cluster, the host may take every scheduled job, so that none is left when its Jobs are done (drained). |
promiseJobPrepared | Job | 9.5.5 HostEnqueuePromiseJob | The host's preparation of a promise job whose realm is not null does both (promisePrepared). |
agentPrepareJob | Job | 9.5 Jobs and Host Operations to Enqueue Jobs | AgentPrepareJob(k) answers the job scheduled at k, prepared as promisePrepared says. |
jobCleanup | Job | 9.5 Jobs and Host Operations to Enqueue Jobs | After a job's cleanup the execution context stack is empty. |
agentCleanupJob | Job | 9.5 Jobs and Host Operations to Enqueue Jobs | AgentCleanupJob answers unused and leaves the agent's execution context stack empty. |
jobCallbackDefault | Job | 9.5.2 HostMakeJobCallback | 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. |
callJobCallback | Job | 9.5.3 HostCallJobCallback | The host's steps before and after the call answer unused, so the call's result is returned. |
selectAgent | Job | 9.8 Forward Progress | HostSelectAgent answers empty or another Agent Record of the cluster that can run (canRunAgent), the state as it was. |
timeNow | Time | 21.4.3.1 Date.now | TimeNow answers a time value identifying an instant (instantTimeValue), the state as it was. |
elapsedMono | Time | No sentence | As the host takes its next job, its clock reads no less than any elapsed time logged. |
timeoutAfter | Time | 9.5.6 HostEnqueueTimeoutJob | As the host takes a timeout job, its clock reads at least milliseconds past the elapsed time logged before the call that scheduled it. |
additionalTimeout | Time | 25.4.3.14 DoWait | AdditionalTimeout answers a non-negative mathematical value, the state as it was. |
timeZoneNameSuffix | Time | 21.4.4.41.3 TimeZoneString | TimeZoneNameSuffix answers "" or " (" name ")", the state as it was. |
systemTimeZoneString | Time | 21.4.1.24 SystemTimeZoneIdentifier | SystemTimeZoneString answers "UTC", an available named time zone identifier whose IsNonPrimaryTimeZoneId is false, or a String UTCOffset matches (utcOffsetNs), the state as it was. |
primaryTimeZoneId | Time | 21.4.1.23 AvailableNamedTimeZoneIdentifiers | PrimaryTimeZoneId answers "UTC" or an available named time zone identifier whose IsNonPrimaryTimeZoneId is false, the state as it was. |
supportsOnlyUTC | Time | 21.4.1.24 SystemTimeZoneIdentifier | SupportsOnlyUTC answers a Boolean, the state as it was. |
parseDateString | Time | 21.4.3.2 Date.parse | ParseDateString answers NaN or a time value (instantTimeValue), never -0𝔽, the state as it was. |
dateFormUTC | Time | 21.4.3.2 Date.parse | A 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). |
dateFormLocal | Time | 21.4.3.2 Date.parse | 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. |
dateFormIllegal | Time | 21.4.3.2 Date.parse | A String of the format's shape with an out-of-bounds element gives NaN. |
expandedYearForm | Time | 21.4.4.36 Date.prototype.toISOString | ExpandedYearForm, whether a year from 0 to 9999 is written as an expanded year, answers a Boolean, the state as it was. |
nanEncoding | Memory | 25.1.3.17 NumericToRawBytes | 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. |
canAllocate | Memory | 6.2.9.1 CreateByteDataBlock | CanAllocate, whether such a Data Block can be created, answers a Boolean, the state as it was. |
resizeArrayBuffer | Memory | 25.1.3.8 HostResizeArrayBuffer | buffer's [[ArrayBufferData]] does not become null; on handled its [[ArrayBufferByteLength]] is newByteLength. |
omitSharedArrayBuffer | Memory | 25.2.3 The SharedArrayBuffer Constructor | OmitSharedArrayBuffer is one Boolean in every state, the state as it was. |
spinWaitHint | Memory | 25.4.12 Atomics.pause | SpinWaitHint answers unused, the state as it was. |
chooseReadsBytesFrom | Memory | 25.1.3.15 GetRawBytesFromSharedBlock | 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. |
chooseReadsValid | Memory | 29.7.5 Valid Executions | 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. |
escapePatternstricter | RegExp | 22.2.6.13.1 EscapeRegExpPattern | 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. |
sortStep | Order | 23.1.3.30.1 SortIndexedProperties | 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. |
sortStepEnds | Order | 23.1.3.30.1 SortIndexedProperties | The sequence is finite: a sort makes finitely many calls, whatever their results. |
forInStep | Order | 14.7.5.9 EnumerateObjectProperties | 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. |
propertyOrder | Order | 9.3.2 CreateIntrinsics | PropertyOrder, the order an intrinsic's properties are created in, answers a new List of the given properties, each once. |
listSeparator | Locale | 23.1.3.32.1 LocalizedListSeparator | LocalizedListSeparator answers a String, the state as it was. |
localeCase | Locale | 22.1.3.26 String.prototype.toLocaleLowerCase | LocaleLowercase and LocaleUppercase answer a new List of code points. |
localeCompare | Locale | 22.1.3.12 String.prototype.localeCompare | 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. |
localeNumberString | Locale | 21.1.3.4 Number.prototype.toLocaleString | LocaleNumberString answers a String, or empty for toString's, the state as it was. |
localeDateString | Locale | 21.4.4.38 Date.prototype.toLocaleDateString | 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. |
webBrowser | Optional | B Additional ECMAScript Features for Web Browsers | 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. |
webBrowserSupports | Optional | B Additional ECMAScript Features for Web Browsers | Where the host is a web browser, it is a web browser or otherwise supports every clause c. |
debuggerEnabled | Optional | 14.16.1 Runtime Semantics: Evaluation | DebuggerEnabled answers a Boolean, the state as it was. |
debuggerAction | Optional | 14.16.1 Runtime Semantics: Evaluation | DebuggerAction answers unused; what it may change is invariantsKept's. |
nativeFunctionSourcestricter | Optional | 20.2.3.5 Function.prototype.toString | NativeFunctionSource answers function , a name nativeName admits and () { [native code] }, the name func.[[InitialName]] where that is a String, the state as it was. |
approx | Value | 21.3.2.9 Math.cbrt | Approx answers a Number, the state as it was. |
approxPower | Value | 6.1.6.1.3 Number::exponentiate | ApproxPower(base, exponent) answers a Number, the state as it was. |
approxInteger | Value | 19.2.5 parseInt | ApproxInteger answers an integer, the state as it was. |
bigIntTooLarge | Value | No sentence | BigIntTooLarge answers a Boolean, the state as it was. |
stringTooLarge | Value | No sentence | StringTooLarge answers a Boolean, the state as it was. |
hostChoice | Value | 7.1.4.1.3 RoundMVResult | HostChoice answers one of its arguments, the state as it was. |
mathRandom | Value | 21.3.2.28 Math.random | Math.random answers such a Number (unitNum), never an abrupt completion, the state as it was. |
hookCompletion | Hook | 4.2 Hosts and Implementations | A host hook's answer is no break, continue or return completion (a value that is no Completion Record is a normal completion's). |
privateElementSameKind | Hook | 7.3.29 HostEnsureCanAddPrivateElement | The [[Type]] of HostEnsureCanAddPrivateElement's answer is one function of its argument, whatever the state of the call. |
supportedImportAttributes | Hook | 16.2.1.12.1 HostGetSupportedImportAttributes | 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). |
getCodeForEval | Hook | 19.2.1.3 HostGetCodeForEval | HostGetCodeForEval answers a String or no-code. |
hasSourceTextAvailable | Hook | 20.2.5 HostHasSourceTextAvailable | HostHasSourceTextAvailable's answer is one function of its argument, whatever the state of the call. |
invariantsKept | Change | 6.1.7.3 Invariants of the Essential Internal Methods | Across a host step every object is still an object and keeps to the invariants (objKept). |
agentFixed | Change | 9.6 Agents | A host step keeps the surrounding agent, its Agent Record's sort and those fields (agentKept). |
hostGlobalObject | Change | 9.3.1 InitializeHostDefinedRealm | HostGlobalObject answers empty (the state as it was) or an Object. |
hostThisValue | Change | 9.3.1 InitializeHostDefinedRealm | HostThisValue answers empty (the state as it was) or an Object. |
hostGlobalProperties | Change | 9.3.1 InitializeHostDefinedRealm | HostGlobalProperties answers unused and changes only global's own properties (onlyPropsOf). |
hostExtendIntrinsics | Change | 2 Conformance | HostExtendIntrinsics(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. |
hostExtendObject | Change | 2 Conformance | HostExtendObject(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. |
hostInitializeBuiltinContext | Change | 10.3.3 BuiltinCallOrConstruct | HostInitializeBuiltinContext answers unused and changes only calleeContext, which keeps its kind and every component the execution context tables define (contextField). |
hostReportCleanupError | Change | 9.9.4.1 HostEnqueueFinalizationRegistryCleanupJob | HostReportCleanupError answers unused. |
hostReportErrors | Change | No sentence | HostReportErrors answers unused. |
mayCleanup | Change | 9.12 CleanupFinalizationRegistry | MayCleanup answers empty or such a cell (emptyCell), the state as it was. |
discardContextResources | Change | 15.10.3 PrepareForTailCall | DiscardContextResources answers unused, the state as it was. |
contextResources | Change | 15.10.3 PrepareForTailCall | The 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). |
collectweaker | Change | 9.9.3 Execution | 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. |
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, …
wakeFinite
16-host-laws-jobs.spectec:14Whether SuspendAgentUntil's timeout wakes within maxTime.
def wakeFinite {M : Model} : List(Val(M)) -> Bool | [_, .math(t)] => !M.lt(M.ofNat(maxTime), t) | _ => falseend
pendingFinite
16-host-laws-jobs.spectec:21The 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
hasScheduledJob
16-host-laws-jobs.spectec:28Whether 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)))canRunAgent
16-host-laws-jobs.spectec:32Whether 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)HostCall.callOf
16-host-laws-jobs.spectec:37A 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
calledAt
16-host-laws-jobs.spectec:43The 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)) = truetaken
16-host-laws-jobs.spectec:46The 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)) = truejobHooks
16-host-laws-jobs.spectec:50The host-defined operations that schedule a Job (sec-hostenqueuegenericjob, sec-hostenqueuepromisejob, sec-hostenqueuetimeoutjob, sec-host-cleanup-finalization-registry).
def jobHooks : List(String) := ["sec-hostenqueuegenericjob", "sec-hostenqueuepromisejob", "sec-hostenqueuetimeoutjob", "sec-host-cleanup-finalization-registry"]Host.mayRun
16-host-laws-jobs.spectec:55The 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)))preparedToEvaluate
16-host-laws-jobs.spectec:59An 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) = trueactiveIs
16-host-laws-jobs.spectec:64sm 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)))promisePrepared
16-host-laws-jobs.spectec:69After 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)Host.JobLaws
16-host-laws-jobs.spectec:72The 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
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-hostenqueuepromisejobJobs 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.
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.
AgentNextJob answers empty or a job it may take now (Host.mayRun), the state as it was.
agentNextJobSpecTec
law agentNextJob : H.asks(Known.pAgentNextJob, fun _ s r => r = .enum(Known.eEmpty) \/ exists k, r = .math(M.ofNat(k)) /\ H.mayRun(s, k));in the agent for which the job is scheduled
With more than one agent in the cluster, a job the host may take is the surrounding agent's.
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).
ownsSingleSpecTec
law ownsSingle : forall s k, clusterSigs(s).length <= 1 -> (exists sec mem jobHooks, calledAt(s.hostLog, sec, k)) -> H.owns(s, k) = true;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.
The host's preparation of a promise job whose realm is not null does both (promisePrepared).
promiseJobPreparedSpecTec
law promiseJobPrepared : forall s k s', H.prepareJob(k, s) = .ok((), s') -> promisePrepared(s, k, s');Perform any host-defined preparation steps. Invoke the Job Abstract Closure.
9.5.5 HostEnqueuePromiseJob sec-hostenqueuepromisejobeach 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
AgentPrepareJob(k) answers the job scheduled at k, prepared as promisePrepared says.
agentPrepareJobSpecTec
law agentPrepareJob : forall vs s r s', H.choice(Known.pAgentPrepareJob, vs, s) = .ok(r, s') -> (exists k, vs = [.math(M.ofNat(k))] /\ scheduled(s.hostLog, k) = some(r) /\ promisePrepared(s, k, s'));Perform any host-defined cleanup steps, after which the execution context stack must be empty.
After a job's cleanup the execution context stack is empty.
jobCleanupSpecTec
law jobCleanup : forall k s s', H.cleanupJob(k, s) = .ok((), s') -> M.eq(M.seqLen(s'.stack), M.ofNat(0)) = true;Perform any host-defined cleanup steps, after which the execution context stack must be empty.
AgentCleanupJob answers unused and leaves the agent's execution context stack empty.
agentCleanupJobSpecTec
law agentCleanupJob : forall vs s r s', H.choice(Known.pAgentCleanupJob, vs, s) = .ok(r, s') -> r = .enum(Known.eUnused) /\ M.eq(M.seqLen(s'.stack), M.ofNat(0)) = true;ECMAScript hosts that are not web browsers must use the default implementation of HostMakeJobCallback.
9.5.3 HostCallJobCallback sec-hostcalljobcallbackECMAScript 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.
jobCallbackDefaultSpecTec
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);It must perform and return the result of Call(jobCallback.[[Callback]], thisValue, argList).
The host's steps before and after the call answer unused, so the call's result is returned.
callJobCallbackSpecTec
law callJobCallback : forall q vs s r s', q = Known.pHostPrepareCallJobCallback \/ q = Known.pHostCleanupCallJobCallback -> Run.boundary(H.choice(q, vs), s) = .ok(r, s') -> r = .enum(Known.eUnused);in a set of agents that share an executing thread, one agent eventually makes forward progress
HostSelectAgent answers empty or another Agent Record of the cluster that can run (canRunAgent), the state as it was.
selectAgentSpecTec
law selectAgent : H.asks(Known.pHostSelectAgent, fun _ s r => r = .enum(Known.eEmpty) \/ isRecordOf(s, "Agent Record", r) = true /\ clusterSigs(s).any(Val.same(sigOf(s, r))) = true /\ Val.same(sigOf(s, r), sigOf(s, s.agent)) = false /\ Val.same(r, s.agent) = false /\ canRunAgent(s, r) = true);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, …
instantTimeValue
17-host-laws-time.spectec:16n 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) = falsetimeZoneNameSuffix
17-host-laws-time.spectec:19x 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(")")))) = truedigits2
17-host-laws-time.spectec:22Two 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
fractionNs
17-host-laws-time.spectec:28A 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 noneutcOffsetNs
17-host-laws-time.spectec:33ParseTimeZoneOffsetString 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
sysTimeZone
17-host-laws-time.spectec:72SystemTimeZoneIdentifier() 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)Host.TimeLaws
17-host-laws-time.spectec:75The 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
This function returns the time value designating the UTC date and time of the occurrence of the call to it.
TimeNow answers a time value identifying an instant (instantTimeValue), the state as it was.
timeNowSpecTec
law timeNow : H.asks(Known.pTimeNow, fun _ _ r => exists n, r = .num(n) /\ instantTimeValue(n));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.As the host takes its next job, its clock reads no less than any elapsed time logged.
elapsedMonoSpecTec
law elapsedMono : forall s k s', H.nextJob(s) = .ok(k, s') -> (forall j t, HostCall.next(j, t) mem s.hostLog -> M.lt(H.elapsed(s), t) = false);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.
timeoutAfterSpecTec
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;Let additionalTimeout be an implementation-defined non-negative mathematical value.
AdditionalTimeout answers a non-negative mathematical value, the state as it was.
additionalTimeoutSpecTec
law additionalTimeout : H.asks(Known.pAdditionalTimeout, fun _ _ r => exists m, r = .math(m) /\ M.lt(m, M.ofNat(0)) = false);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)
TimeZoneNameSuffix answers "" or " (" name ")", the state as it was.
timeZoneNameSuffixSpecTec
law timeZoneNameSuffix : H.asks(Known.pTimeZoneNameSuffix, fun _ _ r => exists x, r = .str(x) /\ timeZoneNameSuffix(x));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-identifiersECMAScript 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.
systemTimeZoneStringSpecTec
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));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.
primaryTimeZoneIdSpecTec
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)));If the implementation only supports the UTC time zone, return "UTC".
SupportsOnlyUTC answers a Boolean, the state as it was.
supportsOnlyUTCSpecTec
law supportsOnlyUTC : forall s r s', H.choice(Known.pSupportsOnlyUTC, [], s) = .ok(r, s') -> s' = s /\ exists b, r = .bool(b);it returns a Number, the UTC time value corresponding to the date and time
ParseDateString answers NaN or a time value (instantTimeValue), never -0𝔽, the state as it was.
parseDateStringSpecTec
law parseDateString : H.asks(Known.pParseDateString, fun _ _ r => exists n, r = .num(n) /\ (M.numView(n) = .nan \/ instantTimeValue(n)) /\ M.numView(n) <> .negZero);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
A 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).
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.
dateFormLocalSpecTec
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));Strings that are unrecognizable or contain out-of-bounds format element values shall cause this function to return NaN.
A String of the format's shape with an out-of-bounds element gives NaN.
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.
expandedYearFormSpecTec
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, …
cutArgs
18-host-laws-memory.spectec:14HostSelectAgent'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
HostCall.cutOf
18-host-laws-memory.spectec:24A 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
cutsOf
18-host-laws-memory.spectec:30The 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)eventPlace
18-host-laws-memory.spectec:35The 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)placeLe
18-host-laws-memory.spectec:38The 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.2placed
18-host-laws-memory.spectec:41The 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
fieldElems
18-host-laws-memory.spectec:47The 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([])execEvents
18-host-laws-memory.spectec:50The 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))placedEvents
18-host-laws-memory.spectec:53The 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)))mathField
18-host-laws-memory.spectec:56The 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
writesByte
18-host-laws-memory.spectec:62e 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)
nanBits
18-host-laws-memory.spectec:72A 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) <> 0isWriteEvent
18-host-laws-memory.spectec:75A WriteSharedMemory or ReadModifyWriteSharedMemory event.
def isWriteEvent (s : State(M)) (e : Val(M)) : Bool := isRecordOf(s, "WriteSharedMemory", e) || isRecordOf(s, "ReadModifyWriteSharedMemory", e)memNames
18-host-laws-memory.spectec:78The 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?)interleaved
18-host-laws-memory.spectec:82mo 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)Host.MemoryLaws
18-host-laws-memory.spectec:85The 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
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.
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.
canAllocateSpecTec
law canAllocate : H.asks(Known.pCanAllocate, fun _ _ r => exists b, r = .bool(b));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.
resizeArrayBufferSpecTec
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));Whenever a host does not provide concurrent access to SharedArrayBuffers it may omit the "SharedArrayBuffer" property of the global object.
OmitSharedArrayBuffer is one Boolean in every state, the state as it was.
omitSharedArrayBufferSpecTec
law omitSharedArrayBuffer : exists b, H.asks(Known.pOmitSharedArrayBuffer, fun _ _ r => r = .bool(b));It has no observable behaviour other than timing.
SpinWaitHint answers unused, the state as it was.
spinWaitHintSpecTec
law spinWaitHint : H.asks(Known.pSpinWaitHint, fun _ _ r => r = .enum(Known.eUnused));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.
chooseReadsBytesFromSpecTec
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);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.
chooseReadsValidSpecTec
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
lineTerminatorUnit
19-host-laws-regexp.spectec:12A LineTerminator's code unit (§12.3): LF, CR, LS, PS.
def lineTerminatorUnit (c : Nat) : Bool := c == 0x0A || c == 0x0D || c == 0x2028 || c == 0x2029terminatorEscape
19-host-laws-regexp.spectec:15What 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]Escaped
19-host-laws-regexp.spectec:20Escaped 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) -> Proprule nil (b) : Escaped(b, [], []);rule keep {b c p e} : Escaped(b, c :: p, c :: e) :- lineTerminatorUnit(c) = false, Escaped(!b && c == 92, p, e);rule slash {p e} : Escaped(false, 47 :: p, 92 :: 47 :: e) :- Escaped(false, p, e);rule terminator {c p e} : Escaped(false, c :: p, 92 :: terminatorEscape(c) ++ e) :- lineTerminatorUnit(c) = true, Escaped(false, p, e);rule terminatorAfter {c p e} : Escaped(true, c :: p, terminatorEscape(c) ++ e) :- lineTerminatorUnit(c) = true, Escaped(false, p, e);Auxiliary definitions (3): EscapeOf, bodySafe, BodySafe
EscapeOf
19-host-laws-regexp.spectec:29EscapePattern'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)bodySafe
19-host-laws-regexp.spectec:33One 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
BodySafe
19-host-laws-regexp.spectec:43As 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) = trueHost.RegExpLaws
19-host-laws-regexp.spectec:46The law of EscapeRegExpPattern (§22.2.6.13.1, sec-escaperegexppattern).
Proved as part of Host.WF.
laws Host.RegExpLaws (H : Host(M))1 laws
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.
escapePatternSpecTec
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, …
sortCall
20-host-laws-order.spectec:12SortStep'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])sortDone
20-host-laws-order.spectec:15SortStep'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))));}
cmpOrder
20-host-laws-order.spectec:24The 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
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)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))sortCallStep
20-host-laws-order.spectec:40One 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')SortReach
20-host-laws-order.spectec:45A 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) -> Proprule start : SortReach(H, n, .enum(Known.eEmpty), .enum(Known.eEmpty), []);rule call {st res h st' j k} (x : M.Num) : SortReach(H, n, st', .num(x), h ++ [(j, k, x)]) :- SortReach(H, n, st, res, h), sortCallStep(H, n, st, res, st', j, k);Auxiliary definition: sortNext
sortNext
20-host-laws-order.spectec:52A 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)Host.OrderLaws
20-host-laws-order.spectec:56The 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
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.
sortStepSpecTec
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');Sort items using an implementation-defined sequence of calls to sortCompare.
The sequence is finite: a sort makes finitely many calls, whatever their results.
sortStepEndsSpecTec
law sortStepEnds : forall n, WellFounded(sortNext(H, n));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.
forInStepSpecTec
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))));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.
propertyOrderSpecTec
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, …
dateValued
21-host-laws-locale.spectec:10The 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
negNum
21-host-laws-locale.spectec:18n 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)) = trueposNum
21-host-laws-locale.spectec:21n 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) = truezeroNum
21-host-laws-locale.spectec:24n is +0𝔽 or -0𝔽.
def zeroNum (n : M.Num) : Prop := M.numView(n) = .posZero \/ M.numView(n) = .negZerocanonEquiv
21-host-laws-locale.spectec:28Two 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))Host.LocaleLaws
21-host-laws-locale.spectec:31The 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
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.
listSeparatorSpecTec
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.
LocaleLowercase and LocaleUppercase answer a new List of code points.
localeCaseSpecTec
law localeCase : forall q l s r s', q = Known.pLocaleUppercase \/ q = Known.pLocaleLowercase -> H.choice(q, [l], s) = .ok(r, s') -> (exists (cps : List(M.Math)), (forall c mem cps, Prims.Strings.isPoint(c) = true) /\ listOf(cps.map(.math), s) = .ok(r, s'));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.
localeCompareSpecTec
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);This method is implementation-defined, and it is permissible, but not encouraged, for it to return the same thing as toString.
LocaleNumberString answers a String, or empty for toString's, the state as it was.
localeNumberStringSpecTec
law localeNumberString : H.asks(Known.pLocaleNumberString, fun _ _ r => r = .enum(Known.eEmpty) \/ exists x, r = .str(x));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.
localeDateStringSpecTec
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, …
identLike
22-host-laws-optional.spectec:10An ASCII IdentifierName.
def identLike : List(Char) -> Bool | c :: cs => (c.isAlpha || c == '_' || c == '$') && cs.all(fun c => c.isAlphanum || c == '_' || c == '$') | [] => falseend
keyLike
22-host-laws-optional.spectec:16A 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)nameLike
22-host-laws-optional.spectec:20A 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))nativeName
22-host-laws-optional.spectec:23A name NativeFunctionSource's law admits: empty, or of those forms.
def nativeName (cs : List(Char)) : Bool := cs.isEmpty || nameLike(cs)nativeWrap
22-host-laws-optional.spectec:26function NAME() { [native code] }.
def nativeWrap (cs : List(Char)) : String := "function " ++ String.ofList(cs) ++ "() { [native code] }"Host.OptionalLaws
22-host-laws-optional.spectec:32The laws of the optional features (§2.1, sec-conformance-normative-optional; Annex B, sec-additional-ecmascript-features-for-web-browsers).
Proved as part of Host.WF.
laws Host.OptionalLaws (H : Host(M))5 laws
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.
webBrowserSpecTec
law webBrowser : forall vs, exists b, forall s, H.choice(Known.pWebBrowser, vs, s) = .ok(.bool(b), s);Web browsers are required to support all such features.
Where the host is a web browser, it is a web browser or otherwise supports every clause c.
webBrowserSupportsSpecTec
law webBrowserSupports : forall c s, H.choice(Known.pWebBrowser, [.choice(1), .absent], s) = .ok(.bool(true), s) -> H.choice(Known.pWebBrowser, [.choice(0), .clause(c)], s) = .ok(.bool(true), s);If an implementation-defined debugging facility is available and enabled, then
DebuggerEnabled answers a Boolean, the state as it was.
debuggerEnabledSpecTec
law debuggerEnabled : H.asks(Known.pDebuggerEnabled, fun _ _ r => exists b, r = .bool(b));Perform an implementation-defined debugging action.
DebuggerAction answers unused; what it may change is invariantsKept's.
debuggerActionSpecTec
law debuggerAction : forall vs s r s', H.choice(Known.pDebuggerAction, vs, s) = .ok(r, s') -> r = .enum(Known.eUnused);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.
nativeFunctionSourceSpecTec
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
Host.ValueLaws
23-host-laws-values.spectec:15The 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
Return an implementation-approximated Number value representing the cube root of ℝ(n).
Approx answers a Number, the state as it was.
approxSpecTec
law approx : H.asks(Known.pApprox, fun _ _ r => exists n, r = .num(n));Return an implementation-approximated Number value representing the result of raising ℝ(base) to the ℝ(exponent) power.
ApproxPower(base, exponent) answers a Number, the state as it was.
approxPowerSpecTec
law approxPower : H.asks(Known.pApproxPower, fun _ _ r => exists n, r = .num(n));mathInt may be an implementation-approximated integer representing the integer value denoted by numberString in radix-radixMV notation
ApproxInteger answers an integer, the state as it was.
approxIntegerSpecTec
law approxInteger : forall (x : M.Math) s r s', H.choice(Known.pApproxInteger, [.math(x)], s) = .ok(r, s') -> s' = s /\ exists m, r = .math(m) /\ M.isInt(m) = true;BigIntTooLarge answers a Boolean, the state as it was.
bigIntTooLargeSpecTec
law bigIntTooLarge : H.asks(Known.pBigIntTooLarge, fun _ _ r => exists b, r = .bool(b));StringTooLarge answers a Boolean, the state as it was.
stringTooLargeSpecTec
law stringTooLarge : H.asks(Known.pStringTooLarge, fun _ _ r => exists b, r = .bool(b));Let chosen be an implementation-defined choice of either option1 or option2.
HostChoice answers one of its arguments, the state as it was.
hostChoiceSpecTec
law hostChoice : H.asks(Known.pHostChoice, fun vs _ r => r mem vs);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.
mathRandomSpecTec
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).
Host.HookLaws
24-host-laws-hooks.spectec:12The 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
A host hook must conform to at least the following requirements: It must return either a normal completion or a throw completion.
A host hook's answer is no break, continue or return completion (a value that is no Completion Record is a normal completion's).
hookCompletionSpecTec
law hookCompletion : forall c xs s r s', H.answers(c, xs, s, r, s') -> compType(r) = Known.eNormal \/ compType(r) = Known.eThrow;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.
privateElementSameKindSpecTec
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);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).
supportedImportAttributesSpecTec
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));HostGetCodeForEval ( arg: an Object, ): a String or no-code
HostGetCodeForEval answers a String or no-code.
getCodeForEvalSpecTec
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);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.
hasSourceTextAvailableSpecTec
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, …
discardedIn
25-host-laws-changes.spectec:13The 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
liveContexts
25-host-laws-changes.spectec:22The 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))onlyPropsOf
25-host-laws-changes.spectec:26s' 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')))onlyAdds
25-host-laws-changes.spectec:31s' 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)))attrsAt
25-host-laws-changes.spectec:34The 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
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))objKept
25-host-laws-changes.spectec:51sec-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'))contextField
25-host-laws-changes.spectec:55The 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.fGeneratorintrinsicOf
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 -> Proprule named {k fs i k' is f a} : intrinsicOf(s, realm, a) :- M.heapGet(s.heap, realm) = some(.record(k, fs)), M.recGet(fs, Known.fIntrinsics) = some(.ref(i)), M.heapGet(s.heap, i) = some(.record(k', is)), M.recGet(is, f) = some(.obj(a));rule held {o sl ps key p k fs f a} : intrinsicOf(s, realm, a) :- intrinsicOf(s, realm, o), M.heapGet(s.heap, o) = some(.object(sl, ps)), M.propsGet(ps, key) = some(.ref(p)), M.heapGet(s.heap, p) = some(.record(k, fs)), f = Known.fValue \/ f = Known.fGetter \/ f = Known.fSetter, M.recGet(fs, f) = some(.obj(a));Auxiliary definitions (4): noForbiddenProps, emptyCell, agentFixedField, agentKept
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)emptyCell
25-host-laws-changes.spectec:71c 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))agentFixedField
25-host-laws-changes.spectec:75The 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")agentKept
25-host-laws-changes.spectec:79From 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, …
keptAlive
25-host-laws-changes.spectec:84v 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 xsweakMapEntry
25-host-laws-changes.spectec:87a 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 esweakSetData
25-host-laws-changes.spectec:90a 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))Rec.Emptied
25-host-laws-changes.spectec:93fs' 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' = fsCell.Emptied
25-host-laws-changes.spectec:99The 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
Val.Holds
25-host-laws-changes.spectec:107Subvalues 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
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) -> Proprule stack {v} : Reachable(s, v) :- v mem stackList(s);rule resumed : Reachable(s, s.resumed);rule suspended : Reachable(s, s.suspended);rule agent : Reachable(s, s.agent);rule evalStep {p} : Reachable(s, p.2) :- p mem s.evalSteps;rule passed {v} : Reachable(s, v) :- v mem s.passed;rule pendingJob {k c args act rlm ans v} : Reachable(s, v) :- s.hostLog.reverse[k]? = some(.hook(c, args, act, rlm, ans)), HostCall.hook(c, args, act, rlm, ans).schedulesJob = true \/ Gen.clauses[c]? = some("sec-host-cleanup-finalization-registry"), s.hostLog.all(fun e => !e.takes(k)) = true, v mem args;rule waiterBlock {b i w} : Reachable(s, .ref(b)) :- (b, i, w) mem s.waiterLists;rule waiterRec {b i w} : Reachable(s, .ref(w)) :- (b, i, w) mem s.waiterLists;rule critical {w} : Reachable(s, .ref(w)) :- w mem s.critical;rule shared {b} : Reachable(s, .ref(b)) :- b mem s.shared;rule codeState {ctx v} : Reachable(s, v) :- Reachable(s, .ref(ctx)), s.suspendedHolds(ctx, v);rule val {u v} : Reachable(s, v) :- Reachable(s, u), u.Holds(v);rule objSlot {a sl ps f v} : Reachable(s, v) :- Reachable(s, .obj(a)), M.heapGet(s.heap, a) = some(.object(sl, ps)), f <> Known.fWeakRefTarget, f <> fieldNamed("WeakMapData"), f <> fieldNamed("WeakSetData"), f <> Known.fCells, M.recGet(sl, f) = some(v);rule objKeySym {a sl ps sym u} : Reachable(s, .sym(sym)) :- Reachable(s, .obj(a)), M.heapGet(s.heap, a) = some(.object(sl, ps)), M.propsGet(ps, .inr(sym)) = some(u);rule objProp {a sl ps k v} : Reachable(s, v) :- Reachable(s, .obj(a)), M.heapGet(s.heap, a) = some(.object(sl, ps)), M.propsGet(ps, k) = some(v);rule finRegHeld {a sl ps l cs c k fs v} : Reachable(s, v) :- Reachable(s, .obj(a)), M.heapGet(s.heap, a) = some(.object(sl, ps)), M.recGet(sl, Known.fCells) = some(.ref(l)), listAt(s, .ref(l)) = some(cs), .ref(c) mem cs, M.heapGet(s.heap, c) = some(.record(k, fs)), M.recGet(fs, fieldNamed("HeldValue")) = some(v);rule weakMapVal {a sl ps l es e ek fs k v} : Reachable(s, v) :- Reachable(s, .obj(a)), M.heapGet(s.heap, a) = some(.object(sl, ps)), M.recGet(sl, fieldNamed("WeakMapData")) = some(.ref(l)), listAt(s, .ref(l)) = some(es), .ref(e) mem es, M.heapGet(s.heap, e) = some(.record(ek, fs)), M.recGet(fs, fieldNamed("Key")) = some(k), Reachable(s, k), M.recGet(fs, Known.fValue) = some(v);rule recField {a k fs f v} : Reachable(s, v) :- Reachable(s, .ref(a)), M.heapGet(s.heap, a) = some(.record(k, fs)), M.recGet(fs, f) = some(v);rule listElem {a xs o v} : Reachable(s, v) :- Reachable(s, .ref(a)), M.heapGet(s.heap, a) = some(.list(xs, o)), v mem seqList(xs);rule envField {a k fs b f v} : Reachable(s, v) :- Reachable(s, .ref(a)), M.heapGet(s.heap, a) = some(.env(k, fs, b)), M.recGet(fs, f) = some(v);rule envBind {a k fs b nm v} : Reachable(s, v) :- Reachable(s, .ref(a)), M.heapGet(s.heap, a) = some(.env(k, fs, b)), M.propsGet(b, nm) = some(v);Auxiliary definition: Collected
Collected
25-host-laws-changes.spectec:149sec-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'))Host.ChangeLaws
25-host-laws-changes.spectec:153The 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
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).
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).
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.
HostGlobalObject answers empty (the state as it was) or an Object.
hostGlobalObjectSpecTec
law hostGlobalObject : forall vs s r s', H.choice(Known.pHostGlobalObject, vs, s) = .ok(r, s') -> r = .enum(Known.eEmpty) /\ s' = s \/ exists a, r = .obj(a);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.
HostThisValue answers empty (the state as it was) or an Object.
hostThisValueSpecTec
law hostThisValue : forall vs s r s', H.choice(Known.pHostThisValue, vs, s) = .ok(r, s') -> r = .enum(Known.eEmpty) /\ s' = s \/ exists a, r = .obj(a);Create any host-defined global object properties on global.
HostGlobalProperties answers unused and changes only global's own properties (onlyPropsOf).
hostGlobalPropertiesSpecTec
law hostGlobalProperties : forall realm g s r s', H.choice(Known.pHostGlobalProperties, [realm, .obj(g)], s) = .ok(r, s') -> r = .enum(Known.eUnused) /\ onlyPropsOf(g, s, s');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-extensionsBuilt-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.
HostExtendIntrinsics(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.
hostExtendIntrinsicsSpecTec
law hostExtendIntrinsics : forall vs s r s', H.choice(Known.pHostExtendIntrinsics, vs, s) = .ok(r, s') -> r = .enum(Known.eUnused) /\ onlyAdds(fun a => exists realm, vs = [.ref(realm)] /\ intrinsicOf(s, realm, a), s, s') /\ noForbiddenProps(s, s');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
HostExtendObject(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.
hostExtendObjectSpecTec
law hostExtendObject : forall o s r s', H.choice(Known.pHostExtendObject, [.obj(o)], s) = .ok(r, s') -> r = .enum(Known.eUnused) /\ onlyAdds(fun _dot0 => _dot0 = o, s, s') /\ noForbiddenProps(s, s');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).
hostInitializeBuiltinContextSpecTec
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));If cleanupResult is an abrupt completion, perform any host-defined steps for reporting the error.
HostReportCleanupError answers unused.
hostReportCleanupErrorSpecTec
law hostReportCleanupError : forall vs s r s', H.choice(Known.pHostReportCleanupError, vs, s) = .ok(r, s') -> r = .enum(Known.eUnused);HostReportErrors answers unused.
hostReportErrorsSpecTec
law hostReportErrors : forall vs s r s', H.choice(Known.pHostReportErrors, vs, s) = .ok(r, s') -> r = .enum(Known.eUnused);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.
MayCleanup answers empty or such a cell (emptyCell), the state as it was.
mayCleanupSpecTec
law mayCleanup : forall reg s r s', H.choice(Known.pMayCleanup, [reg], s) = .ok(r, s') -> s' = s /\ (r = .enum(Known.eEmpty) \/ exists c, r = .ref(c) /\ emptyCell(s, reg, c));Discard all resources associated with the current execution context.
DiscardContextResources answers unused, the state as it was.
discardContextResourcesSpecTec
law discardContextResources : H.asks(Known.pDiscardContextResources, fun _ _ r => r = .enum(Known.eUnused));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.
The 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).
contextResourcesSpecTec
law contextResources : forall s, H.exhausts(s) = true -> 0 < liveContexts(s);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-livenessAny 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.
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, …
selects
14-host-laws-basic.spectec:16A HostSelectAgent answer that selects an agent.
def selects {M : Model} : Val(M) -> Bool | .ref(_) => true | _ => falseend
numValue
14-host-laws-basic.spectec:22The 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
lastElapsed
14-host-laws-basic.spectec:29The 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
mathAfter
14-host-laws-basic.spectec:36t₁ ≥ 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
fieldOf
14-host-laws-basic.spectec:45A 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
slotOf
14-host-laws-basic.spectec:54An 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
listElems
14-host-laws-basic.spectec:60The 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
HostCall.switchFrom
14-host-laws-basic.spectec:69A 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
withAgents
14-host-laws-basic.spectec:76The 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
sigOf
14-host-laws-basic.spectec:82An 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)isEmptyV
14-host-laws-basic.spectec:85empty.
def isEmptyV {M : Model} : Val(M) -> Bool | .enum(e) => e == Known.eEmpty | _ => falseend
pendingList
14-host-laws-basic.spectec:91The 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
idleWait
14-host-laws-basic.spectec:99The 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)jobAgentOf
14-host-laws-basic.spectec:104The 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
jobAgents
14-host-laws-basic.spectec:110The 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.toArrayclusterSigs
14-host-laws-basic.spectec:114The 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
Host.answers
14-host-laws-basic.spectec:123r 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')Host.asks
14-host-laws-basic.spectec:126The 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)Host.Step
14-host-laws-basic.spectec:131A 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')compType
14-host-laws-basic.spectec:134A 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
normalValue
14-host-laws-basic.spectec:140The 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
dataSubSort
14-host-laws-basic.spectec:146k 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
isRecordOf
14-host-laws-basic.spectec:152A 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
fieldNamed
14-host-laws-basic.spectec:161A field id by its name in the data.
def fieldNamed (f : String) : FieldId := Gen.fields.idxOf?(f).getD(0)stackList
14-host-laws-basic.spectec:164The 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)listAt
14-host-laws-basic.spectec:167The 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
unitsMatch
14-host-laws-basic.spectec:176The 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
unitsAre
14-host-laws-basic.spectec:183The 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
scheduled
13-jobs.spectec:13The 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
decUnits
15-date-format.spectec:11The 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
numIs
15-date-format.spectec:17n 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)) = truetvResult
15-date-format.spectec:20r 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) = .nandaysInMonth
15-date-format.spectec:23The 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)DateTimePart
15-date-format.spectec:28A 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 recordDateForm
15-date-format.spectec:38A 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 recordAuxiliary definitions (22): DateForm.signUnits, DateForm.offUnits, DateForm.secPart, DateForm.timeUnits, …
DateForm.signUnits
15-date-format.spectec:47"-" or "+".
def signUnits (neg : Bool) : List(Nat) := if neg then [45] else [43]DateForm.offUnits
15-date-format.spectec:50The 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
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
DateForm.timeUnits
15-date-format.spectec:64A 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)DateForm.yearPart
15-date-format.spectec:67The 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
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
DateForm.timePart
15-date-format.spectec:80The time part's code units, if any.
def timePart : Option(DateTimePart) -> List(Nat) | none => [] | some(p) => timeUnits(p)end
DateForm.units
15-date-format.spectec:86The String's code units.
def units (f : DateForm) : List(Nat) := f.yearPart ++ mdPart(f.md) ++ timePart(f.time)DateForm.yearInt
15-date-format.spectec:89The year.
def yearInt (f : DateForm) : Int := if f.sign = some(true) then -(f.year : Int) else f.yearDateForm.month
15-date-format.spectec:92The month, "01" where absent.
def month (f : DateForm) : Nat := f.md.map(fun _dot0 => _dot0.1).getD(1)DateForm.day
15-date-format.spectec:95The day, "01" where absent.
def day (f : DateForm) : Nat := f.md.bind(fun _dot0 => _dot0.2).getD(1)DateForm.hour
15-date-format.spectec:98The hour, "00" where absent.
def hour (f : DateForm) : Nat := f.time.map(fun _dot0 => _dot0.h).getD(0)DateForm.minute
15-date-format.spectec:101The minute, "00" where absent.
def minute (f : DateForm) : Nat := f.time.map(fun _dot0 => _dot0.mi).getD(0)DateForm.second
15-date-format.spectec:104The second, "00" where absent.
def second (f : DateForm) : Nat := f.time.bind(fun p => p.sec.map(fun _dot0 => _dot0.1)).getD(0)DateForm.milli
15-date-format.spectec:107The millisecond, "000" where absent.
def milli (f : DateForm) : Nat := f.time.bind(fun p => p.sec.bind(fun _dot0 => _dot0.2)).getD(0)DateForm.offset
15-date-format.spectec:110The 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).joinDateForm.offsetMin
15-date-format.spectec:113The 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
DateForm.isLocal
15-date-format.spectec:119A 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
DateForm.ms
15-date-format.spectec:125The 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)DateForm.fits
15-date-format.spectec:128Each 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 < 100DateForm.legal
15-date-format.spectec:133A 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)DateForm.illegal
15-date-format.spectec:137An 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 = 0From 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, …
intMath
11-date-parse.spectec:14An 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
maxTime
11-date-parse.spectec:20The time value limit, 8.64 × 10^15 milliseconds (§21.4.1.1).
def maxTime : Nat := 8640000000000000inTime
11-date-parse.spectec:23Whether t is within ECMAScript's time value range (|t| ≤ 8.64 × 10^15).
def inTime (t : Int) : Bool := decide(t.natAbs <= maxTime)leapDays
11-date-parse.spectec:26Whether 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 1daysBefore
11-date-parse.spectec:29Days 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)yearDay
11-date-parse.spectec:32DayFromYear(y) (§21.4.1.3).
def yearDay (y : Int) : Int := 365 * (y - 1970) + (y - 1969) / 4 - (y - 1901) / 100 + (y - 1601) / 400dateMs
11-date-parse.spectec:35Time 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).
ForInAct
12-for-in.spectec:16An 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)ForInEntry
12-for-in.spectec:26An 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, …
ForInEntry.act
12-for-in.spectec:34The 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
recIn
12-for-in.spectec:42The 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
listIn
12-for-in.spectec:51The 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
actIn
12-for-in.spectec:60The 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;}
entryInBy
12-for-in.spectec:71An 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;}
entryIn
12-for-in.spectec:92An entry of the history: a Record { [[Action]], [[Result]] }.
def entryIn (s : State(M)) (v : Val(M)) : Option(ForInEntry(M)) := entryInBy(listIn, s, v)forInHist
12-for-in.spectec:95The 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)))actRecord
12-for-in.spectec:98A 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))));}
CfiSt
12-for-in.spectec:111A 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) recordAuxiliary definitions (6): CfiSt.init, strKeys, cfiSkip, CfiSt.next, …
CfiSt.init
12-for-in.spectec:120CreateForInIterator(obj).
def CfiSt.init (obj : M.Addr) : CfiSt(M) := ctor(some(obj), false, [], [], none)strKeys
12-for-in.spectec:123The keys that are Strings.
def strKeys (ks : List(Val(M))) : List(M.Str) := ks.filterMap(fun | .str(k) => some(k) | _ => noneend)
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
CfiSt.next
12-for-in.spectec:135The 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
CfiSt.step
12-for-in.spectec:145The 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
cfiNext
12-for-in.spectec:156The 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)).nextThe rules (§14.7.5.9 EnumerateObjectProperties), over the entries before an action.
Auxiliary definitions (4): chainObj, accounted, ForInRules, ForInRun
chainObj
12-for-in.spectec:161o 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 esaccounted
12-for-in.spectec:165A 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)ForInRules
12-for-in.spectec:168The 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
ForInRun
12-for-in.spectec:177Every 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
CfiOk
12-for-in.spectec:182Each 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.
InChain
12-for-in.spectec:191o 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 -> PropAuxiliary definitions (4): exoticSlots, plainChain, shapeKept, cfiApplies
exoticSlots
12-for-in.spectec:197The slots of a Proxy exotic object, a TypedArray and a module namespace exotic object.
def exoticSlots : List(FieldId) := [Known.fProxyHandler, Known.fTypedArrayName, Known.fExports]plainChain
12-for-in.spectec:201No 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)shapeKept
12-for-in.spectec:205No 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 <= icfiApplies
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)