hook : ClauseId → List (Val M) → Run M (Val M)Reading page · generated from lean/Ecma/Host.lean, lean/Ecma/Host/Laws/
The host and its laws
What the specification leaves to the host, and the 72 laws it requires of one, by topic. Each law names its clause, quotes the sentence that governs it, and says how the Lean reads it (4 law has no single sentence and says why). scripts/law_quotes.py checks every quotation against the pinned spec.html.
The host
From lean/Ecma/Host.lean
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 (Run.hostStep): the host reads the state and the log, and only the machine appends to the log. The laws a host must meet are Ecma.Host.Laws.
Host
Host.lean:24The host: 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.
structure Host (M : Model) wherechoice : 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 .residuethe 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 _ _ => truethe 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 0the host-defined preparation steps of a job, by that position
prepareJob : Nat → Run M Unit := fun _ => Run.stop .residuethe host-defined cleanup steps of a job, by that position
cleanupJob : Nat → Run M Unit := fun _ => Run.stop .residuewhat 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 nonea 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 × List (Val M))) := pure nonethe 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 nonewhether 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 .residuethe 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 _ => falsewhether the host's resources run out at allocating an object (MakeBasicObject) in this state
exhaustsHeap : State M → Bool := fun _ => falseState.hostView
Host.lean:63The state as the host reads it: the machine's bookkeeping of the running computation (the Parse Nodes whose SDOs are running, the built-in calls' arguments) empty.
def State.hostView (s : State M) : State M := { s with evalNodes := [], passed := [] }Books
Host.lean:66A state's bookkeeping (State.hostView's) and host-call log.
structure Books (M : Model) whereState.books
Host.lean:72s's bookkeeping and host-call log.
def State.books (s : State M) : Books M := { evalNodes := s.evalNodes, passed := s.passed, hostLog := s.hostLog }
State.restoreBooks
Host.lean:76t with the bookkeeping and host-call log pre.
def State.restoreBooks (t : State M) (pre : Books M) : State M := { t with evalNodes := pre.evalNodes, passed := pre.passed, hostLog := pre.hostLog }
Res.hostStep
Host.lean:83A host step's result over the books before it, pre: the host's writes to the log and the bookkeeping are dropped; an answer a adds the entry e a; a resumed step is run on the view of the state it is resumed with, over that state's books; a call runs on the step's state, and the same step goes on after it.
def Res.hostStep {α : Type} (pre : Books M) (e : α → HostCall M) : Res M α → Res M α | .ok a s => .ok a { s.restoreBooks pre with hostLog := e a :: pre.hostLog } | .esc c s => .esc c (s.restoreBooks pre) | .stop r => .stop r
Run.hostStep
Host.lean:90A host step, logged: the host reads the state's view (State.hostView) and the log, and only the machine appends to the log. The books are read first, so the host has the state's only reference.
def Run.hostStep {α : Type} (e : α → HostCall M) (m : Run M α) : Run M α := fun s => Res.hostStep s.books e (m s.hostView)
activeScriptOrModule
Host.lean:95The 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 | _ => r | _ => r) .null s.stack
ctxRealm
Host.lean:105The Realm component of the execution context ctx where it is an address, else null.
def ctxRealm (s : State M) : Val M → Val M | .ref a => match M.heapGet s.heap a with | some (.record _ fs) => match M.recGet fs Known.fRealm with | some (.ref r) => .ref r | _ => .null | _ => .null | _ => .null
runningRealm
Host.lean:114The running execution context's Realm (§9.4): the topmost execution context's, by ctxRealm.
def runningRealm (s : State M) : Val M := ctxRealm s (M.seqFoldl (fun _ ctx => ctx) .null s.stack)Host.hookL
Host.lean:118A host-defined operation, logged with the active script or module and the running Realm at the call; an escaping completion is its answer (the algorithm boundary).
def Host.hookL (H : Host M) (c : ClauseId) (xs : List (Val M)) : Run M (Val M) := fun s => Run.hostStep (.hook c xs (activeScriptOrModule s) (runningRealm s)) (Run.boundary (H.hook c xs)) s
Host.choiceL
Host.lean:122A host choice, logged; an escaping completion is its answer.
def Host.choiceL (H : Host M) (q : PrimId) (xs : List (Val M)) : Run M (Val M) := Run.hostStep (.choice q xs) (Run.boundary (H.choice q xs))
Host.supports
Host.lean:126Whether the host supports the Annex B section whose clause is c? (hostSupports, asked of H).
def Host.supports (H : Host M) : Option ClauseId → Run M Bool | some c => do bool (← H.choiceL Known.pWebBrowser [.choice 0, .clause c]) | none => return false
Host.allocL
Host.lean:132A Model primitive, an implementation limit at allocating an object when the host's resources run out (exhaustsHeap, read on the host's view of the state).
def Host.allocL (H : Host M) (q : PrimId) (xs : List (Val M)) : Run M (Val M) := fun s => if q == Known.pMakeObject && H.exhaustsHeap s.hostView then .stop .implLimit else prim q xs s
hostPrim
Host.lean:136A primitive the host decides.
Lean, 18 lines
def hostPrim (p : PrimId) : Bool := Known.pApprox ≤ p && p ≤ Known.pWebBrowser || p == Known.pNaNEncoding || p == Known.pApproxInteger || p == Known.pHostInitializeBuiltinContext || p == Known.pHostReportErrors || p == Known.pDiscardContextResources || p == Known.pSpinWaitHint || Known.pAdditionalTimeout ≤ p && p ≤ Known.pTimeNow || p == Known.pParseDateString || p == Known.pCanAllocate || Known.pDebuggerEnabled ≤ p && p ≤ Known.pNativeFunctionSource || p == Known.pEscapePattern || Known.pHasTimeZoneRules ≤ p && p ≤ Known.pLastTransitionBefore || Known.pHostGlobalObject ≤ p && p ≤ Known.pMayCleanup || p == Known.pSortStep || p == Known.pForInStep || p == Known.pPropertyOrder || p == Known.pOmitSharedArrayBuffer || p == Known.pHostSupportsOptional || Known.pLocaleUppercase ≤ p && p ≤ Known.pLocaleNumberString || p == Known.pLocaleDateString || p == Known.pSuspendAgentUntil || p == Known.pExpandedYearForm || p == Known.pHostExtendIntrinsics || p == Known.pHostExtendObject || Known.pHostJobCallbackData ≤ p && p ≤ Known.pHostCleanupCallJobCallback || Known.pHostSelectAgent ≤ p && p ≤ Known.pAgentWoken || p == Known.pWakeAgent || p == Known.pChooseReadsBytesFrom || Known.pAgentNextJob ≤ p && p ≤ Known.pAgentCleanupJob || p == Known.pApproxPower || p == Known.pBigIntTooLarge || p == Known.pStringTooLarge
builtinBind
Host.lean:159§18: a built-in function's parameters bound to the arguments args by its header: those before a rest parameter from the front, those after it from the end of the arguments past the front ones, the rest parameter's List the middle; a parameter without an argument is not present (.missing), extra arguments without a rest parameter are dropped.
def builtinBind (h : Header) (args : List (Val M)) : List (Slot × Val M) × Option (Slot × List (Val M)) := let fill (ps : List Param) (vs : List (Val M)) := ps.zipIdx.map fun (p, i) => (p.x, vs.getD i .missing) let front := h.params.takeWhile (!·.rest) match h.params.drop front.length with | [] => (fill front args, none) | r :: back => let mid := args.drop front.length let k := mid.length - min back.length mid.length (fill front args ++ fill back (mid.drop k), some (r.x, mid.take k))
The laws of a host
From lean/Ecma/Host/Laws.lean
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
Laws.lean:29The laws of a host: those of every topic.
Proved of the engine's host under every option set: Engine.SpecHost.wfBy, which is Implements.host.
structure Host.WF {M : Model} (H : Host M) : Prop 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 field of the structure of its topic, and Host.WF is 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/.nativeFunctionSourcestricter one form,function name() { [native code] }, where the text allows any NativeFunction.collectweaker liveness's second condition, about future executions, is left out.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 lean/Ecma/Host/Laws/Jobs.lean
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.
wakeFinite
Jobs.lean:20Whether SuspendAgentUntil's timeout wakes within maxTime.
def wakeFinite {M : Model} : List (Val M) → Bool | [_, .math t] => !M.lt (M.ofNat maxTime) t | _ => false
pendingFinite
Jobs.lean:26The 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 × 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
hasScheduledJob
Jobs.lean:35Whether 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 (s.hostLog.reverse.zipIdx).any fun (e, k) => e.schedulesJob && ags[k]?.any (Val.same (sigOf s x)) && !s.hostLog.any (·.takes k)
canRunAgent
Jobs.lean:42Whether 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
Jobs.lean:49A logged call is one of the host-defined operation with that sec-id.
def HostCall.callOf (sec : String) : HostCall M → Bool | .hook c _ _ _ _ => Gen.clauses[c]? == some sec | _ => false
calledAt
Jobs.lean:54The 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 (·.callOf sec) = true
taken
Jobs.lean:58The job scheduled at log position k has been taken to run.
def taken (log : List (HostCall M)) (k : Nat) : Prop := log.any (·.takes k) = truejobHooks
Jobs.lean:62The 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
Jobs.lean:69The 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 := (∃ sec ∈ jobHooks, calledAt s.hostLog sec k) ∧ ¬taken s.hostLog k ∧ H.owns s k = true ∧ (calledAt s.hostLog "sec-hostenqueuepromisejob" k → ∀ i < k, calledAt s.hostLog "sec-hostenqueuepromisejob" i → H.owns s i = true → taken s.hostLog i)
preparedToEvaluate
Jobs.lean:76An 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 ∧ ∃ pre top r, stackList s = pre ++ [top] ∧ fieldOf s Known.fRealm top = some r ∧ isRecordOf s "Realm Record" r = true
activeIs
Jobs.lean:84sm 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 → ∃ pre ec post, stackList s = pre ++ ec :: post ∧ fieldOf s Known.fScriptOrModule ec = some sm ∧ (∀ c ∈ post, fieldOf s Known.fScriptOrModule c ≠ some sm) ∧ ∃ r, fieldOf s Known.fRealm ec = some r ∧ fieldOf s Known.fRealm sm = some r)
promisePrepared
Jobs.lean:94After 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 := ∀ 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
Jobs.lean:99The laws of jobs and agents.
Proved as part of Host.WF.
structure Host.JobLaws (H : Host M) : Prop where11 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.
nextJobLean
nextJob : ∀ s k s', H.nextJob s = .ok (some k) s' → H.mayRun s kAt 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.
agentNextJobLean
agentNextJob : H.asks Known.pAgentNextJob fun _ s r => r = .enum Known.eEmpty ∨ ∃ 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.
ownsAgentLean
ownsAgent : ∀ s k, H.owns s k = true → (clusterSigs s).length ≤ 1 ∨ (jobAgents s)[k]?.any (Val.same (sigOf s s.agent)) = true
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).
ownsSingleLean
ownsSingle : ∀ s k, (clusterSigs s).length ≤ 1 → (∃ sec ∈ 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).
promiseJobPreparedLean
promiseJobPrepared : ∀ 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.
agentPrepareJobLean
agentPrepareJob : ∀ vs s r s', H.choice Known.pAgentPrepareJob vs s = .ok r s' → ∃ 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.
jobCleanupLean
jobCleanup : ∀ k s s', H.cleanupJob k s = .ok () s' → M.eq (M.seqLen s'.stack) (M.ofNat 0) = truePerform 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.
agentCleanupJobLean
agentCleanupJob : ∀ 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.
jobCallbackDefaultLean
jobCallbackDefault : ∀ q vs s r s', H.choice Known.pWebBrowser [.choice 1, .absent] s = .ok (.bool false) s → q ∈ [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.
callJobCallbackLean
callJobCallback : ∀ 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.
selectAgentLean
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 lean/Ecma/Host/Laws/Time.lean
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.
instantTimeValue
Time.lean:22n 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 ∨ ∃ m, M.numView n = .finite m ∧ M.isInt m = true ∧ M.lt m (M.neg (M.ofNat maxTime)) = false ∧ M.lt (M.ofNat maxTime) m = false
timeZoneNameSuffix
Time.lean:27x 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 ∨ ∃ n, M.strEq x (M.strConcat (M.strLit " (") (M.strConcat n (M.strLit ")"))) = true
digits2
Time.lean:32Two decimal digits at the front of l: their value and the rest.
def digits2 : List Nat → Option (Nat × List Nat) | a :: b :: l => if 48 ≤ a ∧ a ≤ 57 ∧ 48 ≤ b ∧ b ≤ 57 then some ((a - 48) * 10 + (b - 48), l) else none | _ => none
fractionNs
Time.lean:37A TemporalDecimalFraction's 1 to 9 digits as nanoseconds.
def fractionNs (ds : List Nat) : Option Nat := if 1 ≤ ds.length ∧ ds.length ≤ 9 ∧ ds.all (fun c => 48 ≤ c ∧ c ≤ 57) then some ((ds ++ List.replicate (9 - ds.length) 48).foldl (fun a c => a * 10 + (c - 48)) 0) else none
utcOffsetNs
Time.lean:45ParseTimeZoneOffsetString 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).
Lean, 27 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) 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) 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 some ((mi * 60 + sc) * 10 ^ 9 + f) return sign * ((h * 3600 * 10 ^ 9 + ns : Nat) : Int)
sysTimeZone
Time.lean:75SystemTimeZoneIdentifier() 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
Time.lean:81The laws of time and dates.
Proved as part of Host.WF.
structure Host.TimeLaws (H : Host M) : Prop where13 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.
timeNowLean
timeNow : H.asks Known.pTimeNow fun _ _ r => ∃ n, r = .num n ∧ instantTimeValue nHost.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.
elapsedMonoLean
elapsedMono : ∀ s k s', H.nextJob s = .ok k s' → ∀ j t, HostCall.next j t ∈ 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.
timeoutAfterLean
timeoutAfter : ∀ 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.
additionalTimeoutLean
additionalTimeout : H.asks Known.pAdditionalTimeout fun _ _ r => ∃ m, r = .math m ∧ M.lt m (M.ofNat 0) = falseeither 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.
timeZoneNameSuffixLean
timeZoneNameSuffix : H.asks Known.pTimeZoneNameSuffix fun _ _ r => ∃ x, r = .str x ∧ timeZoneNameSuffix xLet 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.
systemTimeZoneStringLean
systemTimeZoneString : H.asks Known.pSystemTimeZoneString fun _ s r => ∃ x, r = .str x ∧ (M.strEq x (M.strLit "UTC") = true ∨ (∃ a s' xs, H.choice Known.pAvailableNamedTimeZoneIds [] s = .ok (.ref a) s' ∧ listAt s' (.ref a) = some xs ∧ Val.str x ∈ xs ∧ H.choice Known.pIsNonPrimaryTimeZoneId [.str x] s = .ok (.bool false) s) ∨ ∃ 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.
primaryTimeZoneIdLean
primaryTimeZoneId : H.asks Known.pPrimaryTimeZoneId fun _ s r => ∃ x, r = .str x ∧ (M.strEq x (M.strLit "UTC") = true ∨ (∃ a s' xs, H.choice Known.pAvailableNamedTimeZoneIds [] s = .ok (.ref a) s' ∧ listAt s' (.ref a) = some xs ∧ Val.str x ∈ 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.
supportsOnlyUTCLean
supportsOnlyUTC : ∀ s r s', H.choice Known.pSupportsOnlyUTC [] s = .ok r s' → s' = s ∧ ∃ b, r = .bool bit 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.
parseDateStringLean
parseDateString : H.asks Known.pParseDateString fun _ _ r => ∃ 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.
dateFormLocalLean
dateFormLocal : ∀ 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) ∧ ∀ 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.
expandedYearFormLean
expandedYearForm : H.asks Known.pExpandedYearForm fun _ _ r => ∃ b, r = .bool bThe laws of shared memory and buffers
From lean/Ecma/Host/Laws/Memory.lean
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.
cutArgs
Memory.lean:20HostSelectAgent's agent and n.
def cutArgs {M : Model} : List (Val M) → Option (Val M × M.Math) | [a, n] => match n with | .math n => some (a, n) | _ => none | _ => none
HostCall.cutOf
Memory.lean:28A 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 × M.Math) | .choice q vs r => if q == Known.pHostSelectAgent && selects r then cutArgs vs else none | _ => none
cutsOf
Memory.lean:33The switches of a log (newest first), oldest first.
def cutsOf {M : Model} (log : List (HostCall M)) : List (Val M × M.Math) := log.reverse.filterMap HostCall.cutOfeventPlace
Memory.lean:38The 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 × M.Math)) (sig : Val M) (i : Nat) : Nat × Nat := ((cuts.findIdx? fun c => Val.same (sigOf s c.1) sig && M.lt (M.ofNat i) c.2).getD cuts.length, i)
placeLe
Memory.lean:42The place p is not after q.
def placeLe (p q : Nat × Nat) : Bool := p.1 < q.1 || p.1 == q.1 && p.2 ≤ q.2placed
Memory.lean:45The events es from position i, each with its place f.
def placed {M : Model} (f : Nat → Nat × Nat) : Nat → List (Val M) → List (Val M × (Nat × Nat)) | _, [] => [] | i, e :: es => (e, f i) :: placed f (i + 1) es
fieldElems
Memory.lean:50The 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
Memory.lean:54The 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
Memory.lean:58The 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 × M.Math)) (ex : Val M) : List (Val M × (Nat × 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
Memory.lean:63The 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 | _ => none
writesByte
Memory.lean:69e 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 (Val.same · 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) | _, _ => false
nanBits
Memory.lean:81A natural number is a NaN's encoding in the IEEE 754-2019 binary interchange format of w exponent bits and precision p: w + p bits (the sign free), the biased exponent all ones and the trailing significand not zero.
def nanBits (w p k : Nat) : Prop := k < 2 ^ (w + p) ∧ (k / 2 ^ (p - 1)) % 2 ^ w = 2 ^ w - 1 ∧ k % 2 ^ (p - 1) ≠ 0
isWriteEvent
Memory.lean:85A WriteSharedMemory or ReadModifyWriteSharedMemory event.
def isWriteEvent (s : State M) (e : Val M) : Bool := isRecordOf s "WriteSharedMemory" e || isRecordOf s "ReadModifyWriteSharedMemory" e
memNames
Memory.lean:89The memory model's names: Data's fields, enums and sorts.
def memNames : MemoryModel.View.Names := ⟨Gen.fields.idxOf?, Gen.enums.idxOf?, Gen.sorts.idxOf?⟩interleaved
Memory.lean:93mo 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 := ∀ a b pa pb, (.ref a, pa) ∈ placedEvents s (cutsOf s.hostLog) ex → (.ref b, pb) ∈ placedEvents s (cutsOf s.hostLog) ex → a ≠ b → placeLe pa pb = true → mo a b
Host.MemoryLaws
Memory.lean:98The laws of shared memory and buffers.
Proved as part of Host.WF.
structure Host.MemoryLaws (H : Host M) : Prop where7 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.
nanEncodingLean
nanEncoding : ∀ (v : M.Num) (w p : Nat), M.numView v = .nan → 2 ≤ p → ∃ k, nanBits w p k ∧ ∀ s, H.choice Known.pNaNEncoding [.num v, .math (M.ofNat w), .math (M.ofNat p)] s = .ok (.math (M.ofNat k)) s
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.
canAllocateLean
canAllocate : H.asks Known.pCanAllocate fun _ _ r => ∃ b, r = .bool bThe 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.
resizeArrayBufferLean
resizeArrayBuffer : ∀ c a n s r s', Gen.clauses[c]? = some "sec-hostresizearraybuffer" → H.answers c [.obj a, n] s r s' → (∀ f, Gen.fields[f]? = some "ArrayBufferData" → slotOf s a f ≠ some .null → slotOf s' a f ≠ some .null) ∧ (∀ e, normalValue r = some (.enum e) → Gen.enums[e]? = some "handled" → ∀ f m, Gen.fields[f]? = some "ArrayBufferByteLength" → n = .math m → ∃ 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.
omitSharedArrayBufferLean
omitSharedArrayBuffer : ∃ b, H.asks Known.pOmitSharedArrayBuffer fun _ _ r => r = .bool bIt has no observable behaviour other than timing.
SpinWaitHint answers unused, the state as it was.
spinWaitHintLean
spinWaitHint : H.asks Known.pSpinWaitHint fun _ _ r => r = .enum Known.eUnusedLet 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.
chooseReadsBytesFromLean
chooseReadsBytesFrom : ∀ vs s r s', H.choice Known.pChooseReadsBytesFrom vs s = .ok r s' → ∃ 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 ∧ ∀ j w, ws[j]? = some w → w ∈ 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.
chooseReadsValidLean
chooseReadsValid : ∀ vs s r s', H.choice Known.pChooseReadsBytesFrom vs s = .ok r s' → ∀ ex er b idx size, vs = [ex, er, .ref b, .math idx, .math size] → ∃ ws : List M.Addr, listOf (ws.map .ref) s = .ok r s' ∧ ∀ (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 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 → (∃ m, size = M.ofNat m) → MemoryModel.ReadsValid x rbf hsw k ev ws
The law of EscapeRegExpPattern
From lean/Ecma/Host/Laws/RegExp.lean
EscapePattern's String (sec-escaperegexppattern step 5), over code units.
lineTerminatorUnit
RegExp.lean:18A LineTerminator's code unit (§12.3): LF, CR, LS, PS.
def lineTerminatorUnit (c : Nat) : Bool := c == 0x0A || c == 0x0D || c == 0x2028 || c == 0x2029terminatorEscape
RegExp.lean:21What 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
RegExp.lean:28Escaped b p e: e is p with code units escaped (§22.2.6.13.1 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.
inductive Escaped : Bool → List Nat → List Nat → Prop | nil (b) : Escaped b [] [] | keep {b c p e} : lineTerminatorUnit c = false → Escaped (!b && c == 92) p e → Escaped b (c :: p) (c :: e) | slash {p e} : Escaped false p e → Escaped false (47 :: p) (92 :: 47 :: e) | terminator {c p e} : lineTerminatorUnit c = true → Escaped false p e → Escaped false (c :: p) (92 :: terminatorEscape c ++ e) | terminatorAfter {c p e} : lineTerminatorUnit c = true → Escaped false p e → Escaped true (c :: p) (terminatorEscape c ++ e)
EscapeOf
RegExp.lean:38EscapePattern'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
RegExp.lean:42One 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
BodySafe
RegExp.lean:52As 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
RegExp.lean:55The law of EscapeRegExpPattern.
Proved as part of Host.WF.
structure Host.RegExpLaws (H : Host M) : Prop where1 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.
escapePatternLean
escapePattern : ∀ pattern flags s r s', H.choice Known.pEscapePattern [.str pattern, .str flags] s = .ok r s' → s' = s ∧ (∃ S, r = .str S ∧ ∃ p e, unitsAre pattern p ∧ unitsAre S e ∧ EscapeOf p e ∧ BodySafe e) ∧ ∀ s2 r2 s2', H.choice Known.pEscapePattern [.str pattern, .str flags] s2 = .ok r2 s2' → r2 = r
The laws of sorting and enumeration
From lean/Ecma/Host/Laws/Order.lean
The order SortIndexedProperties sorts in, the steps of EnumerateObjectProperties, and the order of the intrinsics' properties.
sortCall
Order.lean:18SortStep'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
Order.lean:22SortStep'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
Order.lean:30The 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) | _ => none
consistentCmp
Order.lean:38§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 := (∀ a b, a < n → b < n → cmpOrder (c a b) ≠ none) ∧ (∀ a, a < n → cmpOrder (c a a) = some .eq) ∧ (∀ a b, a < n → b < n → cmpOrder (c a b) = some .eq → cmpOrder (c b a) = some .eq) ∧ ∀ (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
Order.lean:47§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 := ∀ 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
Order.lean:54One 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 := ∃ 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
Order.lean:60A sort of n elements 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.
inductive SortReach (H : Host M) (n : Nat) : Val M → Val M → List (Nat × Nat × M.Num) → Prop wheresortNext
Order.lean:67A 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 × Val M) : Prop := (∃ h, SortReach H n b.1 b.2 h) ∧ ∃ j k x, sortCallStep H n b.1 b.2 a.1 j k ∧ a.2 = .num x
Host.OrderLaws
Order.lean:71The laws of sorting and enumeration.
Proved as part of Host.WF.
structure Host.OrderLaws (H : Host M) : Prop where4 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.
sortStepLean
sortStep : ∀ 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' → (∃ j k st', j < n ∧ k < n ∧ sortCall j k st' s = .ok r s') ∨ ∃ σ, σ.Perm (List.range n) ∧ (∀ c, consistentCmp n c → (∀ e ∈ 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.
sortStepEndsLean
sortStepEnds : ∀ 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.
forInStepLean
forInStep : ∀ obj h s r s', H.choice Known.pForInStep [.obj obj, h] s = .ok r s' → ∀ es, forInHist s h = some es → ForInRun obj es → ∃ 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.
propertyOrderLean
propertyOrder : ∀ o l s r s', H.choice Known.pPropertyOrder [o, l] s = .ok r s' → ∃ xs ys, listElems s l = some xs ∧ ys.Perm xs ∧ listOf ys s = .ok r s'
The laws of the locale-sensitive methods
From lean/Ecma/Host/Laws/Locale.lean
The list separator, locale case mapping and comparison, and the locale forms of Number and Date.
dateValued
Locale.lean:16The 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 | _ => false
negNum
Locale.lean:23n is a negative Number.
def negNum (n : M.Num) : Prop := M.numView n = .negInf ∨ ∃ m, M.numView n = .finite m ∧ M.lt m (M.ofNat 0) = true
posNum
Locale.lean:27n is a positive Number.
def posNum (n : M.Num) : Prop := M.numView n = .posInf ∨ ∃ m, M.numView n = .finite m ∧ M.lt (M.ofNat 0) m = true
zeroNum
Locale.lean:31n is +0𝔽 or -0𝔽.
def zeroNum (n : M.Num) : Prop := M.numView n = .posZero ∨ M.numView n = .negZerocanonEquiv
Locale.lean:35Two 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
Locale.lean:39The laws of the locale-sensitive methods.
Proved as part of Host.WF.
structure Host.LocaleLaws (H : Host M) : Prop where5 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.
listSeparatorLean
listSeparator : ∀ c xs s r s', Gen.clauses[c]? = some "sec-localizedlistseparator" → H.answers c xs s r s' → s' = s ∧ ∃ 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.
localeCaseLean
localeCase : ∀ q l s r s', q = Known.pLocaleUppercase ∨ q = Known.pLocaleLowercase → H.choice q [l] s = .ok r s' → ∃ cps : List M.Math, (∀ c ∈ 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.
localeCompareLean
localeCompare : ∃ le : M.Str → M.Str → Prop, (∀ a b, le a b ∨ le b a) ∧ (∀ a b c, le a b → le b c → le a c) ∧ ∀ a b s r s', H.choice Known.pLocaleCompare [.str a, .str b] s = .ok r s' → s' = s ∧ ∃ n, r = .num n ∧ (¬le b a → negNum n) ∧ (¬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.
localeNumberStringLean
localeNumberString : H.asks Known.pLocaleNumberString fun _ _ r => r = .enum Known.eEmpty ∨ ∃ x, r = .str xThis 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.
localeDateStringLean
localeDateString : ∀ 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 ∨ ∃ x, r = .str x) ∧ (dateValued s v = false → r = .enum Known.eThrow ∨ ∃ x, r = .str x)
The laws of the optional features
From lean/Ecma/Host/Laws/Optional.lean
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.
identLike
Optional.lean:16An ASCII IdentifierName.
def identLike : List Char → Bool | c :: cs => (c.isAlpha || c == '_' || c == '$') && cs.all fun c => c.isAlphanum || c == '_' || c == '$' | [] => false
keyLike
Optional.lean:21A 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
Optional.lean:26A 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
Optional.lean:30A name NativeFunctionSource's law admits: empty, or of those forms.
def nativeName (cs : List Char) : Bool := cs.isEmpty || nameLike csnativeWrap
Optional.lean:33function NAME() { [native code] }.
def nativeWrap (cs : List Char) : String := "function " ++ String.ofList cs ++ "() { [native code] }"Host.OptionalLaws
Optional.lean:38The laws of the optional features.
Proved as part of Host.WF.
structure Host.OptionalLaws (H : Host M) : Prop where5 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.
webBrowserLean
webBrowser : ∀ vs, ∃ b, ∀ s, H.choice Known.pWebBrowser vs s = .ok (.bool b) sWeb 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.
webBrowserSupportsLean
webBrowserSupports : ∀ 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.
debuggerEnabledLean
debuggerEnabled : H.asks Known.pDebuggerEnabled fun _ _ r => ∃ b, r = .bool bPerform an implementation-defined debugging action.
DebuggerAction answers unused; what it may change is invariantsKept's.
debuggerActionLean
debuggerAction : ∀ vs s r s', H.choice Known.pDebuggerAction vs s = .ok r s' → r = .enum Known.eUnusedThe 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.
nativeFunctionSourceLean
nativeFunctionSource : ∀ f s r s', H.choice Known.pNativeFunctionSource [f] s = .ok r s' → s' = s ∧ ∃ cs, nativeName cs = true ∧ r = .str (M.strLit (nativeWrap cs)) ∧ ∀ 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 lean/Ecma/Host/Laws/Values.lean
Implementation-approximated values, implementation-defined choices, Math.random, and the maximum BigInt size.
unitNum
Values.lean:18n is a Number with positive sign, greater than or equal to +0 and less than 1.
def unitNum (n : M.Num) : Prop := M.numView n = .posZero ∨ ∃ m, M.numView n = .finite m ∧ M.lt (M.ofNat 0) m = true ∧ M.lt m (M.ofNat 1) = true
Host.ValueLaws
Values.lean:23The laws of the values the implementation chooses.
Proved as part of Host.WF.
structure Host.ValueLaws (H : Host M) : Prop where7 laws
Return an implementation-approximated Number value representing the cube root of ℝ(n).
Approx answers a Number, the state as it was.
approxLean
approx : H.asks Known.pApprox fun _ _ r => ∃ n, r = .num nReturn 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.
approxPowerLean
approxPower : H.asks Known.pApproxPower fun _ _ r => ∃ n, r = .num nmathInt 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.
approxIntegerLean
approxInteger : ∀ (x : M.Math) s r s', H.choice Known.pApproxInteger [.math x] s = .ok r s' → s' = s ∧ ∃ m, r = .math m ∧ M.isInt m = true
BigIntTooLarge answers a Boolean, the state as it was.
bigIntTooLargeLean
bigIntTooLarge : H.asks Known.pBigIntTooLarge fun _ _ r => ∃ b, r = .bool bStringTooLarge answers a Boolean, the state as it was.
stringTooLargeLean
stringTooLarge : H.asks Known.pStringTooLarge fun _ _ r => ∃ b, r = .bool bLet chosen be an implementation-defined choice of either option1 or option2.
HostChoice answers one of its arguments, the state as it was.
hostChoiceLean
hostChoice : H.asks Known.pHostChoice fun vs _ r => r ∈ vsThis 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.
mathRandomLean
mathRandom : ∀ c xs s r s', Gen.clauses[c]? = some "sec-math.random" → H.answers c xs s r s' → s' = s ∧ ∃ n, r = .num n ∧ unitNum n
The laws of the host hooks
From lean/Ecma/Host/Laws/Hooks.lean
What every host hook returns, and the hooks that must answer alike at every call (sec-hosts-and-implementations).
Host.HookLaws
Hooks.lean:18The laws of the host hooks.
Proved as part of Host.WF.
structure Host.HookLaws (H : Host M) : Prop where5 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).
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.
privateElementSameKindLean
privateElementSameKind : ∃ kind : List (Val M) → EnumId, ∀ 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).
supportedImportAttributesLean
supportedImportAttributes : ∃ ids : List M.Str, ∀ 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.
getCodeForEvalLean
getCodeForEval : ∀ c xs s r s', Gen.clauses[c]? = some "sec-hostgetcodeforeval" → H.answers c xs s r s' → (∃ e, r = .enum e ∧ Gen.enums[e]? = some "no-code") ∨ ∃ 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.
hasSourceTextAvailableLean
hasSourceTextAvailable : ∃ f : List (Val M) → Val M, ∀ 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 lean/Ecma/Host/Laws/Changes.lean
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.
discardedIn
Changes.lean:19The 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 | _ => false
liveContexts
Changes.lean:26The execution contexts on the stack whose resources no DiscardContextResources choice discarded.
def liveContexts (s : State M) : Nat := (stackList s).countP (!discardedIn s.hostLog ·)onlyPropsOf
Changes.lean:30s' 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 } ∧ (∀ a c, a ≠ g → M.heapGet s.heap a = some c → M.heapGet s'.heap a = some c) ∧ ∀ sl ps, M.heapGet s.heap g = some (.object sl ps) → ∃ ps', M.heapGet s'.heap g = some (.object sl ps')
onlyAdds
Changes.lean:38s' 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 } ∧ (∀ a c, M.heapGet s.heap a = some c → (∀ sl ps, to a → c ≠ .object sl ps) → M.heapGet s'.heap a = some c) ∧ ∀ a sl ps, to a → M.heapGet s.heap a = some (.object sl ps) → ∃ ps', M.heapGet s'.heap a = some (.object sl ps') ∧ (∀ k v, M.propsGet ps k = some v → M.propsGet ps' k = some v) ∧ (M.recGet sl Known.fExtensible ≠ some (.bool true) → ∀ k, (M.propsGet ps' k).isSome → (M.propsGet ps k).isSome)
attrsAt
Changes.lean:46The 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 ⊕ 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 | _ => none
attrsKept
Changes.lean:56§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 := (∀ 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
Changes.lean:66sec-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 ∧ ∀ k, (M.propsGet ps' k).isSome → (M.propsGet ps k).isSome) ∧ ∀ k fs, attrsAt s ps k = some fs → M.recGet fs Known.fConfigurable ≠ some (.bool true) → ∃ fs', attrsAt s' ps' k = some fs' ∧ attrsKept fs fs'
contextField
Changes.lean:77The components every execution context has (§9.4 Table 26), and those of an ECMAScript code execution context (Table 27) and a generator's (Table 28).
def contextField (f : FieldId) : Prop := f = Known.fCodeState ∨ f = Known.fFunction ∨ f = Known.fRealm ∨ f = Known.fScriptOrModule ∨ f = Known.fLexicalEnvironment ∨ f = Known.fVariableEnvironment ∨ f = Known.fPrivateEnvironment ∨ f = Known.fGenerator
intrinsicOf
Changes.lean:86a 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).
inductive intrinsicOf (s : State M) (realm : M.Addr) : M.Addr → Prop | named {k fs i k' is f 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) → intrinsicOf s realm a | held {o sl ps key p k fs f 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) → intrinsicOf s realm a
noForbiddenProps
Changes.lean:97§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 := ∀ 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 → ∃ ps, M.heapGet s.heap a = some (.object sl ps) ∧ (M.propsGet ps (.inl k)).isSome
emptyCell
Changes.lean:103c is a Record that reg.[[Cells]] contains, whose [[WeakRefTarget]] is empty.
def emptyCell (s : State M) (reg : Val M) (c : M.Addr) : Prop := ∃ 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
Changes.lean:111The 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
Changes.lean:117From 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 ∧ ∀ a k fs, s.agent = .ref a → M.heapGet s.heap a = some (.record k fs) → ∃ fs', M.heapGet s'.heap a = some (.record k fs') ∧ ∀ f, agentFixedField f → M.recGet fs' f = M.recGet fs f
Collection (sec-weakref-execution).
keptAlive
Changes.lean:124v is in the [[KeptAlive]] List of an agent's Agent Record in s.
def keptAlive (s : State M) (v : Val M) : Prop := ∃ ag l xs, isRecordOf s "Agent Record" ag = true ∧ fieldOf s (fieldNamed "KeptAlive") ag = some l ∧ listAt s l = some xs ∧ v ∈ xs
weakMapEntry
Changes.lean:129a is a Record a WeakMap's [[WeakMapData]] List contains.
def weakMapEntry (s : State M) (a : M.Addr) : Prop := ∃ 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 ∈ es
weakSetData
Changes.lean:134a is the List a WeakSet's [[WeakSetData]] is.
def weakSetData (s : State M) (a : M.Addr) : Prop := ∃ o sl ps, M.heapGet s.heap o = some (.object sl ps) ∧ M.recGet sl (fieldNamed "WeakSetData") = some (.ref a)
Rec.Emptied
Changes.lean:138fs' 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 := (∃ v ∈ xs, M.recGet fs k = some v) ∧ fs' = gs.foldl (fun r g => M.recSet r g (.enum Known.eEmpty)) fs ∨ (¬∃ v ∈ xs, M.recGet fs k = some v) ∧ fs' = fs
Cell.Emptied
Changes.lean:146The 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' ∨ ¬weakMapEntry s a ∧ Rec.Emptied xs Known.fWeakRefTarget [Known.fWeakRefTarget] fs fs') | .list ys o, .list ys' o' => o' = o ∧ (¬weakSetData s a → ys' = ys) ∧ M.seqLen ys' = M.seqLen ys ∧ ∀ i v, M.seqGet ys i = some v → v ∈ xs ∧ M.seqGet ys' i = some (.enum Known.eEmpty) ∨ v ∉ xs ∧ M.seqGet ys' i = some v | c, c' => c' = c
Machine.Kont.Holds
Changes.lean:157Values held directly by a continuation.
def Machine.Kont.Holds {M : Model} : Machine.Kont M → Val M → Prop | .args _ done _, v => v ∈ done | .all _ xs, v => v ∈ xs | .bind w, v => v = w | .scope (.passed outer inner), v => v ∈ outer ∨ v ∈ inner | .loop l, v | .test l, v => match l.st with | .each a _ _ | .keys a _ => v = .ref a | _ => False | .tstep _ _ _ key env _ _ _, v => v = key ∨ v ∈ env | _, _ => False
Machine.Frame.Holds
Changes.lean:169Values directly in a suspended execution context's frame.
def Machine.Frame.Holds {M : Model} (fr : Machine.Frame M) (v : Val M) : Prop := v ∈ fr.slots.toList ∨ ∃ k ∈ fr.konts, k.Holds v
Val.Holds
Changes.lean:173Subvalues 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 ∈ caps | .ty _ _ _ env, v => v ∈ env | .cond _ _ _ _ env, v => v ∈ env | .tuple vs, v => v ∈ vs | _, _ => False
Reachable
Changes.lean:185§9.9.2 (sec-liveness): values strongly reachable from the roots of s without following weak references (WeakRef.[[WeakRefTarget]], WeakSet.[[WeakSetData]], WeakMap.[[WeakMapData]] entries whose [[Key]] is not itself reachable, or FinalizationRegistry cell [[WeakRefTarget]] / [[UnregisterToken]] fields).
Lean, 39 lines
inductive Reachable (s : State M) : Val M → Prop | stack {v} : v ∈ stackList s → Reachable s v | resumed : Reachable s s.resumed | suspended : Reachable s s.suspended | agent : Reachable s s.agent | evalStep {p} : p ∈ s.evalSteps → Reachable s p.2 | passed {v} : v ∈ s.passed → Reachable s v | waiterBlock {b i w} : (b, i, w) ∈ s.waiterLists → Reachable s (.ref b) | waiterRec {b i w} : (b, i, w) ∈ s.waiterLists → Reachable s (.ref w) | critical {w} : w ∈ s.critical → Reachable s (.ref w) | shared {b} : b ∈ s.shared → Reachable s (.ref b) | frame {ctx frs fr v} : (ctx, frs) ∈ s.frames → Reachable s (.ref ctx) → fr ∈ frs → fr.Holds v → Reachable s v | val {u v} : Reachable s u → u.Holds v → Reachable s v | objSlot {a sl ps f 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 → Reachable s v | objKeySym {a sl ps sym u} : Reachable s (.obj a) → M.heapGet s.heap a = some (.object sl ps) → M.propsGet ps (.inr sym) = some u → Reachable s (.sym sym) | objProp {a sl ps k v} : Reachable s (.obj a) → M.heapGet s.heap a = some (.object sl ps) → M.propsGet ps k = some v → Reachable s v | finRegHeld {a sl ps l cs c k fs 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 ∈ cs → M.heapGet s.heap c = some (.record k fs) → M.recGet fs (fieldNamed "HeldValue") = some v → Reachable s v | weakMapVal {a sl ps l es e ek fs k 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 ∈ 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 → Reachable s v | recField {a k fs f v} : Reachable s (.ref a) → M.heapGet s.heap a = some (.record k fs) → M.recGet fs f = some v → Reachable s v | listElem {a xs o v} : Reachable s (.ref a) → M.heapGet s.heap a = some (.list xs o) → v ∈ seqList xs → Reachable s v | envField {a k fs b f v} : Reachable s (.ref a) → M.heapGet s.heap a = some (.env k fs b) → M.recGet fs f = some v → Reachable s v | envBind {a k fs b nm v} : Reachable s (.ref a) → M.heapGet s.heap a = some (.env k fs b) → M.propsGet b nm = some v → Reachable s v
Collected
Changes.lean:228sec-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 := (∀ x ∈ xs, ((∃ a, x = .obj a) ∨ ∃ y, x = .sym y) ∧ ¬keptAlive s x ∧ ¬Reachable s x) ∧ s' = { s with heap := s'.heap } ∧ ∀ a, (M.heapGet s'.heap a).isSome = (M.heapGet s.heap a).isSome ∧ ∀ c, M.heapGet s.heap a = some c → ∃ c', M.heapGet s'.heap a = some c' ∧ Cell.Emptied s xs a c c'
Host.ChangeLaws
Changes.lean:235The laws of what a host step may change.
Proved as part of Host.WF.
structure Host.ChangeLaws (H : Host M) : Prop where14 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).
invariantsKeptLean
invariantsKept : ∀ s s', H.Step s s' → ∀ a sl ps, M.heapGet s.heap a = some (.object sl ps) → ∃ sl' ps', M.heapGet s'.heap a = some (.object sl' ps') ∧ objKept s s' sl ps sl' ps'
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).
agentFixedLean
agentFixed : ∀ s s', H.Step s s' → agentKept s s'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.
hostGlobalObjectLean
hostGlobalObject : ∀ vs s r s', H.choice Known.pHostGlobalObject vs s = .ok r s' → r = .enum Known.eEmpty ∧ s' = s ∨ ∃ 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.
hostThisValueLean
hostThisValue : ∀ vs s r s', H.choice Known.pHostThisValue vs s = .ok r s' → r = .enum Known.eEmpty ∧ s' = s ∨ ∃ a, r = .obj a
Create any host-defined global object properties on global.
HostGlobalProperties answers unused and changes only global's own properties (onlyPropsOf).
hostGlobalPropertiesLean
hostGlobalProperties : ∀ 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.
hostExtendIntrinsicsLean
hostExtendIntrinsics : ∀ vs s r s', H.choice Known.pHostExtendIntrinsics vs s = .ok r s' → r = .enum Known.eUnused ∧ onlyAdds (fun a => ∃ 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.
hostExtendObjectLean
hostExtendObject : ∀ o s r s', H.choice Known.pHostExtendObject [.obj o] s = .ok r s' → r = .enum Known.eUnused ∧ onlyAdds (· = 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).
hostInitializeBuiltinContextLean
hostInitializeBuiltinContext : ∀ ctx s r s', H.choice Known.pHostInitializeBuiltinContext [.ref ctx] s = .ok r s' → r = .enum Known.eUnused ∧ s' = { s with heap := s'.heap } ∧ (∀ a c, a ≠ ctx → M.heapGet s.heap a = some c → M.heapGet s'.heap a = some c) ∧ ∀ k fs, M.heapGet s.heap ctx = some (.record k fs) → ∃ fs', M.heapGet s'.heap ctx = some (.record k fs') ∧ ∀ 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.
hostReportCleanupErrorLean
hostReportCleanupError : ∀ vs s r s', H.choice Known.pHostReportCleanupError vs s = .ok r s' → r = .enum Known.eUnused
HostReportErrors answers unused.
hostReportErrorsLean
hostReportErrors : ∀ 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.
mayCleanupLean
mayCleanup : ∀ reg s r s', H.choice Known.pMayCleanup [reg] s = .ok r s' → s' = s ∧ (r = .enum Known.eEmpty ∨ ∃ 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.
discardContextResourcesLean
discardContextResources : H.asks Known.pDiscardContextResources fun _ _ r => r = .enum Known.eUnusedA 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).
contextResourcesLean
contextResources : ∀ s, H.exhausts s = true → 0 < liveContexts sAt 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 lean/Ecma/Host/Laws/Basic.lean
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.
selects
Basic.lean:22A HostSelectAgent answer that selects an agent.
def selects {M : Model} : Val M → Bool | .ref _ => true | _ => false
numValue
Basic.lean:27The 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 | _ => none
lastElapsed
Basic.lean:34The 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
mathAfter
Basic.lean:40t₁ ≥ 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
fieldOf
Basic.lean:48A 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 | _ => none
slotOf
Basic.lean:55An 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 | _ => none
listElems
Basic.lean:61The 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 | _ => none
HostCall.switchFrom
Basic.lean:68A 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 | _ => none
withAgents
Basic.lean:74The 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 × Val M) | [] => [] | e :: log => let a := e.switchFrom.getD cur; (e, a) :: withAgents a log
sigOf
Basic.lean:79An Agent Record's signifier, its [[Signifier]].
def sigOf {M : Model} (s : State M) (x : Val M) : Val M := (fieldOf s Known.fSignifier x).getD .absentisEmptyV
Basic.lean:82empty.
def isEmptyV {M : Model} : Val M → Bool | .enum e => e == Known.eEmpty | _ => false
pendingList
Basic.lean:87The 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 × 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
idleWait
Basic.lean:97The 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
Basic.lean:103The 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 × Val M → Val M | (.hook _ (_ :: realm :: _) _ _ _, a) => (fieldOf s Known.fAgentSignifier realm).getD (sigOf s a) | (_, a) => sigOf s a
jobAgents
Basic.lean:108The signifiers of the agents of the jobs the log's calls schedule, by log position.
def jobAgents {M : Model} (s : State M) : Array (Val M) := ((withAgents s.agent s.hostLog).map (jobAgentOf s)).reverse.toArray
clusterSigs
Basic.lean:113The 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 => []
Host.answers
Basic.lean:122r 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
Basic.lean: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 := ∀ vs s r s', H.choice q vs s = .ok r s' → s' = s ∧ P vs s r
Host.Step
Basic.lean:132A 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 := (∃ c xs r, H.answers c xs s r s') ∨ (∃ q vs r, Run.boundary (H.choice q vs) s = .ok r s') ∨ (∃ k, H.nextJob s = .ok k s') ∨ (∃ b, H.clearsKept s = .ok b s') ∨ (∃ k, H.prepareJob k s = .ok () s') ∨ (∃ k, H.cleanupJob k s = .ok () s') ∨ (∃ a, H.first s = .ok a s') ∨ (∃ a, H.idle s = .ok a s') ∨ ∃ v b, H.idleEnd v s = .ok b s'
compType
Basic.lean:139A 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.eNormal
normalValue
Basic.lean:144The 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
dataSubSort
Basic.lean:149k 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 (·.super)).getD []).any (dataSubSort f · t)
isRecordOf
Basic.lean:154A 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 | _ => false
fieldNamed
Basic.lean:161A field id by its name in the data.
def fieldNamed (f : String) : FieldId := (Gen.fields.idxOf? f).getD 0stackList
Basic.lean: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.stacklistAt
Basic.lean: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 | _ => none
unitsMatch
Basic.lean:174The 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 | _, _ => False
unitsAre
Basic.lean:180The String x's code units are l.
def unitsAre (x : M.Str) (l : List Nat) : Prop := unitsMatch (seqList (M.strUnits x)) lThe Date Time String Format, over code units
From lean/Ecma/Host/Laws/DateFormat.lean
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.
decUnits
DateFormat.lean:17The 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
numIs
DateFormat.lean:22n 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 ∃ m, M.numView n = .finite m ∧ M.eq m (intMath t) = true
tvResult
DateFormat.lean:26r 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 := ∃ n, r = .num n ∧ if inTime t then numIs n t else M.numView n = .nan
daysInMonth
DateFormat.lean:30The 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
DateFormat.lean:36A date-time form's time part (§21.4.1.32): 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.
structure DateTimePart whereDateForm
DateFormat.lean:45A String of the Date Time String Format's shape (§21.4.1.32): YYYY, or an expanded year's sign (true for "-") and six digits; optionally -MM and then optionally -DD; optionally a time part.
structure DateForm whereDateForm.signUnits
DateFormat.lean:54"-" or "+".
def signUnits (neg : Bool) : List Nat := if neg then [45] else [43]DateForm.offUnits
DateFormat.lean:57The UTC offset representation's code units.
def offUnits : Option (Option (Bool × Nat × Nat)) → List Nat | none => [] | some none => [90] | some (some (n, h, m)) => signUnits n ++ decUnits 2 h ++ [58] ++ decUnits 2 m
DateForm.secPart
DateFormat.lean:63:ss and .sss's code units.
def secPart : Option (Nat × Option Nat) → List Nat | none => [] | some (sc, none) => [58] ++ decUnits 2 sc | some (sc, some ms) => [58] ++ decUnits 2 sc ++ [46] ++ decUnits 3 ms
DateForm.timeUnits
DateFormat.lean:69A 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
DateFormat.lean:73The 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
DateForm.mdPart
DateFormat.lean:79-MM and -DD's code units.
def mdPart : Option (Nat × Option Nat) → List Nat | none => [] | some (mo, none) => [45] ++ decUnits 2 mo | some (mo, some d) => [45] ++ decUnits 2 mo ++ [45] ++ decUnits 2 d
DateForm.timePart
DateFormat.lean:85The time part's code units, if any.
def timePart : Option DateTimePart → List Nat | none => [] | some p => timeUnits p
DateForm.units
DateFormat.lean:90The String's code units.
def units (f : DateForm) : List Nat := f.yearPart ++ mdPart f.md ++ timePart f.timeDateForm.yearInt
DateFormat.lean:93The year.
def yearInt (f : DateForm) : Int := if f.sign = some true then -(f.year : Int) else f.yearDateForm.month
DateFormat.lean:95The month, "01" where absent.
def month (f : DateForm) : Nat := (f.md.map (·.1)).getD 1DateForm.day
DateFormat.lean:97The day, "01" where absent.
def day (f : DateForm) : Nat := (f.md.bind (·.2)).getD 1DateForm.hour
DateFormat.lean:99The hour, "00" where absent.
def hour (f : DateForm) : Nat := (f.time.map (·.h)).getD 0DateForm.minute
DateFormat.lean:101The minute, "00" where absent.
def minute (f : DateForm) : Nat := (f.time.map (·.mi)).getD 0DateForm.second
DateFormat.lean:103The second, "00" where absent.
def second (f : DateForm) : Nat := (f.time.bind fun p => p.sec.map (·.1)).getD 0DateForm.milli
DateFormat.lean:105The millisecond, "000" where absent.
def milli (f : DateForm) : Nat := (f.time.bind fun p => p.sec.bind (·.2)).getD 0DateForm.offset
DateFormat.lean:108The UTC offset representation's sign, hours and minutes; none for "Z" or none.
def offset (f : DateForm) : Option (Bool × Nat × Nat) := (f.time.bind (·.off)).joinDateForm.offsetMin
DateFormat.lean:111The 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 => 0
DateForm.isLocal
DateFormat.lean:117A 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 => false
DateForm.ms
DateFormat.lean:122The 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.milliDateForm.fits
DateFormat.lean:125Each 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 ∧ ∀ n h m, f.offset = some (n, h, m) → h < 100 ∧ m < 100
DateForm.legal
DateFormat.lean:132A 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 ∧ (∀ n h m, f.offset = some (n, h, m) → h ≤ 23 ∧ m ≤ 59) ∧ ¬(f.sign = some true ∧ f.year = 0)
DateForm.illegal
DateFormat.lean:139An 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 ∨ (∃ n h m, f.offset = some (n, h, m) ∧ (24 < h ∨ 59 < m)) ∨ (f.sign = some true ∧ f.year = 0)