25 構造化データ

25.1 ArrayBufferオブジェクト

25.1.1 記法

このsection、25.4、および29における以下のdescriptionsは、read-modify-write modification function internal data structureを使用する。

read-modify-write modification functionは、byte valuesの2つのListをargumentsとして取り、byte valuesListを返すAbstract Closureとしてrepresentedされるmathematical functionである。これらのAbstract Closuresは、以下のpropertiesをすべて満たす:

  • それらはすべてのalgorithm stepsをatomicallyに実行する。
  • それらのindividual algorithm stepsはobservableではない。
Note

read-modify-write modification functionのalgorithm stepsがpureなmathematical functionをconstituteすることのverificationを助けるため、以下のeditorial conventionsがrecommendedされる:

25.1.2 Fixed-lengthおよびResizable ArrayBufferオブジェクト

fixed-length ArrayBufferは、creation後にbyte lengthがchangeできないArrayBufferである。

resizable ArrayBufferは、ArrayBuffer.prototype.resize ( newLength )へのcallsを介してcreation後にbyte lengthがchangeしてもよいArrayBufferである。

createdされるArrayBuffer objectのkindは、ArrayBuffer ( length [ , options ] )にpassedされるargumentsに依存する。

25.1.3 ArrayBufferオブジェクト用の抽象操作

25.1.3.1 AllocateArrayBuffer ( ctor, byteLength [ , maxByteLength ] )

The abstract operation AllocateArrayBuffer takes arguments ctor (コンストラクタ) and byteLength (非負整数) and optional argument maxByteLength (非負整数または empty) and returns ArrayBufferを含む正常完了またはthrow完了. これはArrayBufferを作成するために使用される。 It performs the following steps when called:

  1. Let slots be « [[ArrayBufferData]], [[ArrayBufferByteLength]], [[ArrayBufferDetachKey]] ».
  2. If maxByteLength is present and maxByteLength is not empty, let allocatingResizableBuffer be true; else let allocatingResizableBuffer be false.
  3. If allocatingResizableBuffer is true, then
    1. If byteLength > maxByteLength, throw a RangeError exception.
    2. Append [[ArrayBufferMaxByteLength]] to slots.
  4. Let obj be ? OrdinaryCreateFromConstructor(ctor, "%ArrayBuffer.prototype%", slots).
  5. Let block be ? CreateByteDataBlock(byteLength).
  6. Set obj.[[ArrayBufferData]] to block.
  7. Set obj.[[ArrayBufferByteLength]] to byteLength.
  8. If allocatingResizableBuffer is true, then
    1. If it is not possible to create a Data Block block consisting of maxByteLength bytes, throw a RangeError exception.
    2. NOTE: Resizable ArrayBuffers are designed to be implementable with in-place growth. Implementations may throw if, for example, virtual memory cannot be reserved up front.
    3. Set obj.[[ArrayBufferMaxByteLength]] to maxByteLength.
  9. Return obj.

25.1.3.2 ArrayBufferByteLength ( arrayBuffer, order )

The abstract operation ArrayBufferByteLength takes arguments arrayBuffer (ArrayBufferまたはSharedArrayBuffer) and order (seq-cst または unordered) and returns 非負整数. It performs the following steps when called:

  1. IsGrowableSharedArrayBuffer(arrayBuffer) が true である場合、
    1. bufferByteLengthBlockarrayBuffer.[[ArrayBufferByteLengthData]] とする。
    2. rawLengthGetRawBytesFromSharedBlock(bufferByteLengthBlock, 0, biguint64, true, order) とする。
    3. agentRecord を周囲のエージェントのAgent Recordとする。
    4. isLittleEndianagentRecord.[[LittleEndian]] とする。
    5. (RawBytesToNumeric(biguint64, rawLength, isLittleEndian)) を返す。
  2. アサート: IsDetachedBuffer(arrayBuffer) は false である。
  3. arrayBuffer.[[ArrayBufferByteLength]] を返す。

25.1.3.3 ArrayBufferCopyAndDetach ( arrayBuffer, newLength, preserveResizability )

The abstract operation ArrayBufferCopyAndDetach takes arguments arrayBuffer (ECMAScript言語値), newLength (ECMAScript言語値), and preserveResizability (preserve-resizability または fixed-length) and returns ArrayBufferを含む正常完了またはthrow完了. It performs the following steps when called:

  1. RequireInternalSlot(arrayBuffer, [[ArrayBufferData]]) を実行する。
  2. IsSharedArrayBuffer(arrayBuffer) が true である場合、TypeError 例外を投げる。
  3. newLengthundefined である場合、
    1. newByteLengtharrayBuffer.[[ArrayBufferByteLength]] とする。
  4. そうでなければ、
    1. newByteLength を ? ToIndex(newLength) とする。
  5. IsDetachedBuffer(arrayBuffer) が true である場合、TypeError 例外を投げる。
  6. preserveResizabilitypreserve-resizability であり、かつ IsFixedLengthArrayBuffer(arrayBuffer) が false である場合、
    1. newMaxByteLengtharrayBuffer.[[ArrayBufferMaxByteLength]] とする。
  7. そうでなければ、
    1. newMaxByteLengthempty とする。
  8. arrayBuffer.[[ArrayBufferDetachKey]]undefined でない場合、TypeError 例外を投げる。
  9. newBuffer を ? AllocateArrayBuffer(%ArrayBuffer%, newByteLength, newMaxByteLength) とする。
  10. copyLengthmin(newByteLength, arrayBuffer.[[ArrayBufferByteLength]]) とする。
  11. fromBlockarrayBuffer.[[ArrayBufferData]] とする。
  12. toBlocknewBuffer.[[ArrayBufferData]] とする。
  13. CopyDataBlockBytes(toBlock, 0, fromBlock, 0, copyLength) を実行する。
  14. 注記: 新しいData Blockの作成も、古いData Blockからのコピーも観測可能ではない。実装はこのメソッドをゼロコピーの移動または realloc として実装してもよい。
  15. DetachArrayBuffer(arrayBuffer) を実行する。
  16. newBuffer を返す。

25.1.3.4 IsDetachedBuffer ( arrayBuffer )

The abstract operation IsDetachedBuffer takes argument arrayBuffer (ArrayBufferまたはSharedArrayBuffer) and returns Boolean. It performs the following steps when called:

  1. arrayBuffer.[[ArrayBufferData]]null である場合、true を返す。
  2. false を返す。

25.1.3.5 DetachArrayBuffer ( arrayBuffer [ , key ] )

The abstract operation DetachArrayBuffer takes argument arrayBuffer (ArrayBuffer) and optional argument key (任意) and returns unused を含む正常完了またはthrow完了. It performs the following steps when called:

  1. アサート: IsSharedArrayBuffer(arrayBuffer) は false である。
  2. key が存在しない場合、keyundefined に設定する。
  3. arrayBuffer.[[ArrayBufferDetachKey]]key でない場合、TypeError 例外を投げる。
  4. arrayBuffer.[[ArrayBufferData]]null に設定する。
  5. arrayBuffer.[[ArrayBufferByteLength]] を 0 に設定する。
  6. unused を返す。
Note

ArrayBufferインスタンスのデタッチは、そのバッキングストアとして使用されるData Blockをそのインスタンスから切り離し、バッファのバイト長を0に設定する。

25.1.3.6 CloneArrayBuffer ( sourceBuffer, sourceByteOffset, sourceLength )

The abstract operation CloneArrayBuffer takes arguments sourceBuffer (ArrayBufferまたはSharedArrayBuffer), sourceByteOffset (非負整数), and sourceLength (非負整数) and returns ArrayBufferを含む正常完了またはthrow完了. これは、sourceByteOffset から始まり sourceLength バイト続く範囲にわたって、sourceBuffer のデータのコピーであるデータを持つ新しいArrayBufferを作成する。 It performs the following steps when called:

  1. アサート: IsDetachedBuffer(sourceBuffer) は false である。
  2. targetBuffer を ? AllocateArrayBuffer(%ArrayBuffer%, sourceLength) とする。
  3. sourceBlocksourceBuffer.[[ArrayBufferData]] とする。
  4. targetBlocktargetBuffer.[[ArrayBufferData]] とする。
  5. CopyDataBlockBytes(targetBlock, 0, sourceBlock, sourceByteOffset, sourceLength) を実行する。
  6. targetBuffer を返す。

25.1.3.7 GetArrayBufferMaxByteLengthOption ( options )

The abstract operation GetArrayBufferMaxByteLengthOption takes argument options (ECMAScript言語値) and returns 非負整数または empty のいずれかを含む正常完了、またはthrow完了. It performs the following steps when called:

  1. options がObjectでない場合、empty を返す。
  2. maxByteLength を ? Get(options, "maxByteLength") とする。
  3. maxByteLengthundefined である場合、empty を返す。
  4. ToIndex(maxByteLength) を返す。

25.1.3.8 HostResizeArrayBuffer ( buffer, newByteLength )

The host-defined abstract operation HostResizeArrayBuffer takes arguments buffer (ArrayBuffer) and newByteLength (非負整数) and returns handled または unhandled のいずれかを含む正常完了、またはthrow完了. これは、ホストbuffer の実装定義のリサイズを実行する機会を与える。ホストbuffer のリサイズを扱わないことを選択する場合、既定の振る舞いのために unhandled を返してもよい。

HostResizeArrayBufferの実装は、次の要件に従わなければならない:

  • この抽象操作は buffer をデタッチしない。
  • この抽象操作が handled で正常完了する場合、buffer.[[ArrayBufferByteLength]]newByteLength である。

HostResizeArrayBufferの既定の実装は NormalCompletion(unhandled) を返すことである。

25.1.3.9 IsFixedLengthArrayBuffer ( arrayBuffer )

The abstract operation IsFixedLengthArrayBuffer takes argument arrayBuffer (ArrayBufferまたはSharedArrayBuffer) and returns Boolean. It performs the following steps when called:

  1. arrayBuffer[[ArrayBufferMaxByteLength]] 内部スロットを持つ場合、false を返す。
  2. true を返す。

25.1.3.10 IsUnsignedElementType ( type )

The abstract operation IsUnsignedElementType takes argument type (TypedArray要素型) and returns Boolean. これは、引数 type が符号なしTypedArray要素型であるかどうかを検証する。 It performs the following steps when called:

  1. typeuint8, uint8clamped, uint16, uint32, または biguint64 のいずれかである場合、true を返す。
  2. false を返す。

25.1.3.11 IsUnclampedIntegerElementType ( type )

The abstract operation IsUnclampedIntegerElementType takes argument type (TypedArray要素型) and returns Boolean. これは、引数 typeuint8clamped を含まないInteger TypedArray要素型であるかどうかを検証する。 It performs the following steps when called:

  1. typeint8, uint8, int16, uint16, int32, または uint32 のいずれかである場合、true を返す。
  2. false を返す。

25.1.3.12 IsBigIntElementType ( type )

The abstract operation IsBigIntElementType takes argument type (TypedArray要素型) and returns Boolean. これは、引数 type がBigInt TypedArray要素型であるかどうかを検証する。 It performs the following steps when called:

  1. typebiguint64 または bigint64 のいずれかである場合、true を返す。
  2. false を返す。

25.1.3.13 IsNoTearConfiguration ( type, order )

The abstract operation IsNoTearConfiguration takes arguments type (a TypedArray element type) and order (seq-cst, unordered, or init) and returns a Boolean. It performs the following steps when called:

  1. IsUnclampedIntegerElementType(type) が true である場合、true を返す。
  2. IsBigIntElementType(type) が true であり、かつ orderinit でも unordered でもない場合、true を返す。
  3. false を返す。

25.1.3.14 RawBytesToNumeric ( type, rawBytes, isLittleEndian )

The abstract operation RawBytesToNumeric takes arguments type (TypedArray要素型), rawBytes (バイト値のList), and isLittleEndian (Boolean) and returns NumberまたはBigInt. It performs the following steps when called:

  1. elementSize を、Element Type type に対して Table 71 で指定されるElement Size値とする。
  2. isLittleEndianfalse である場合、rawBytes の要素の順序を反転する。
  3. typefloat16 である場合、
    1. value を、rawBytes のバイト要素を連結し、IEEE 754-2019 binary16値のリトルエンディアン・ビット列エンコードとして解釈したものとする。
    2. value がNaNである場合、NaN を返す。
    3. value に対応するNumber値を返す。
  4. typefloat32 である場合、
    1. value を、rawBytes のバイト要素を連結し、IEEE 754-2019 binary32値のリトルエンディアン・ビット列エンコードとして解釈したものとする。
    2. value がNaNである場合、NaN を返す。
    3. value に対応するNumber値を返す。
  5. typefloat64 である場合、
    1. value を、rawBytes のバイト要素を連結し、IEEE 754-2019 binary64値のリトルエンディアン・ビット列エンコードとして解釈したものとする。
    2. value がNaNである場合、NaN を返す。
    3. value に対応するNumber値を返す。
  6. IsUnsignedElementType(type) が true である場合、
    1. intValue を、rawBytes のバイト要素を連結し、符号なしリトルエンディアン二進数のビット列エンコードとして解釈したものとする。
  7. そうでなければ、
    1. intValue を、rawBytes のバイト要素を連結し、ビット長 elementSize × 8 の二進リトルエンディアン2の補数のビット列エンコードとして解釈したものとする。
  8. IsBigIntElementType(type) が true である場合、intValue に対応するBigInt値を返す。
  9. intValue に対応するNumber値を返す。

25.1.3.15 GetRawBytesFromSharedBlock ( block, byteIndex, type, isTypedArray, order )

The abstract operation GetRawBytesFromSharedBlock takes arguments block (Shared Data Block), byteIndex (非負整数), type (TypedArray要素型), isTypedArray (Boolean), and order (seq-cst または unordered) and returns バイト値のList. It performs the following steps when called:

  1. elementSize を、Element Type type に対して Table 71 で指定されるElement Size値とする。
  2. agentRecord を周囲のエージェントのAgent Recordとする。
  3. executionagentRecord.[[CandidateExecution]] とする。
  4. eventsRecord を、execution.[[EventsRecords]] のうち [[AgentSignifier]]AgentSignifier() であるAgent Events Recordとする。
  5. isTypedArraytrue であり、かつ IsNoTearConfiguration(type, order) が true である場合、noTeartrue とする。そうでなければ noTearfalse とする。
  6. rawValue を、要素が非決定的に選択されたバイト値である、長さ elementSizeListとする。
  7. 注記: 実装では、rawValue は基礎となるハードウェア上の非アトミックまたはアトミック読み取り命令の結果である。非決定性は、弱い一貫性を持つハードウェアの観測可能な振る舞いを記述するための、メモリモデルの意味論的規定である。
  8. readEventReadSharedMemory { [[Order]]: order, [[NoTear]]: noTear, [[Block]]: block, [[ByteIndex]]: byteIndex, [[ElementSize]]: elementSize } とする。
  9. readEventeventsRecord.[[EventList]] に追加する。
  10. Chosen Value Record { [[Event]]: readEvent, [[ChosenValue]]: rawValue } を execution.[[ChosenValues]] に追加する。
  11. rawValue を返す。

25.1.3.16 GetValueFromBuffer ( arrayBuffer, byteIndex, type, isTypedArray, order [ , isLittleEndian ] )

The abstract operation GetValueFromBuffer takes arguments arrayBuffer (ArrayBufferまたはSharedArrayBuffer), byteIndex (非負整数), type (TypedArray要素型), isTypedArray (Boolean), and order (seq-cst または unordered) and optional argument isLittleEndian (Boolean) and returns NumberまたはBigInt. It performs the following steps when called:

  1. アサート: IsDetachedBuffer(arrayBuffer) は false である。
  2. アサート: arrayBuffer には、byteIndex から始まり type の値を表現するのに十分なバイトがある。
  3. blockarrayBuffer.[[ArrayBufferData]] とする。
  4. elementSize を、Element Type type に対して Table 71 で指定されるElement Size値とする。
  5. IsSharedArrayBuffer(arrayBuffer) が true である場合、
    1. アサート: blockShared Data Blockである。
    2. rawValueGetRawBytesFromSharedBlock(block, byteIndex, type, isTypedArray, order) とする。
  6. そうでなければ、
    1. rawValue を、block 内の byteIndex(含む)から byteIndex + elementSize(含まない)までの区間のインデックスにあるバイトを要素とするListとする。
  7. アサート: rawValue 内の要素数は elementSize である。
  8. isLittleEndian が存在しない場合、
    1. agentRecord を周囲のエージェントのAgent Recordとする。
    2. isLittleEndianagentRecord.[[LittleEndian]] に設定する。
  9. RawBytesToNumeric(type, rawValue, isLittleEndian) を返す。

25.1.3.17 NumericToRawBytes ( type, value, isLittleEndian )

The abstract operation NumericToRawBytes takes arguments type (TypedArray要素型), value (NumberまたはBigInt), and isLittleEndian (Boolean) and returns バイト値のList. It performs the following steps when called:

  1. typefloat16 である場合、
    1. rawBytes を、roundTiesToEvenモードを使用して valueIEEE 754-2019 binary16形式へ変換した結果である2バイトを要素とするListとする。これらのバイトはリトルエンディアン順に配置される。valueNaN である場合、rawBytes は実装が選択する任意のIEEE 754-2019 binary16形式のNaNエンコードに設定されてもよい。実装は、実装上区別可能な各 NaN 値に対して、常に同じエンコードを選択しなければならない。
  2. そうでなく typefloat32 である場合、
    1. rawBytes を、roundTiesToEvenモードを使用して valueIEEE 754-2019 binary32形式へ変換した結果である4バイトを要素とするListとする。これらのバイトはリトルエンディアン順に配置される。valueNaN である場合、rawBytes は実装が選択する任意のIEEE 754-2019 binary32形式のNaNエンコードに設定されてもよい。実装は、実装上区別可能な各 NaN 値に対して、常に同じエンコードを選択しなければならない。
  3. そうでなく typefloat64 である場合、
    1. rawBytes を、valueIEEE 754-2019 binary64形式エンコードである8バイトを要素とするListとする。これらのバイトはリトルエンディアン順に配置される。valueNaN である場合、rawBytes は実装が選択する任意のIEEE 754-2019 binary64形式のNaNエンコードに設定されてもよい。実装は、実装上区別可能な各 NaN 値に対して、常に同じエンコードを選択しなければならない。
  4. そうでなければ、
    1. n を、Element Type type に対して Table 71 で指定されるElement Size値とする。
    2. conversionOperation を、Element Type type に対して Table 71 の“Conversion Operation”列にある名前の抽象操作とする。
    3. intValue(! conversionOperation(value)) とする。
    4. intValue ≥ 0 である場合、
      1. rawBytes を、intValuen バイト二進エンコードを要素とするListとする。これらのバイトはリトルエンディアン順に並べられる。
    5. そうでなければ、
      1. rawBytes を、intValuen バイト二進2の補数エンコードを要素とするListとする。これらのバイトはリトルエンディアン順に並べられる。
  5. isLittleEndianfalse である場合、rawBytes の要素の順序を反転する。
  6. rawBytes を返す。

25.1.3.18 SetValueInBuffer ( arrayBuffer, byteIndex, type, value, isTypedArray, order [ , isLittleEndian ] )

The abstract operation SetValueInBuffer takes arguments arrayBuffer (an ArrayBuffer or SharedArrayBuffer), byteIndex (a non-negative integer), type (a TypedArray element type), value (a Number or a BigInt), isTypedArray (a Boolean), and order (seq-cst, unordered, or init) and optional argument isLittleEndian (a Boolean) and returns unused. It performs the following steps when called:

  1. アサート: IsDetachedBuffer(arrayBuffer) は false である。
  2. アサート: arrayBuffer には、byteIndex から始まり type の値を表現するのに十分なバイトがある。
  3. アサート: IsBigIntElementType(type) が true である場合、value はBigIntであり、そうでなければ value はNumberである。
  4. blockarrayBuffer.[[ArrayBufferData]] とする。
  5. elementSize を、Element Type type に対して Table 71 で指定されるElement Size値とする。
  6. agentRecord を周囲のエージェントのAgent Recordとする。
  7. isLittleEndian が存在しない場合、
    1. isLittleEndianagentRecord.[[LittleEndian]] に設定する。
  8. rawBytesNumericToRawBytes(type, value, isLittleEndian) とする。
  9. IsSharedArrayBuffer(arrayBuffer) が true である場合、
    1. executionagentRecord.[[CandidateExecution]] とする。
    2. eventsRecord を、execution.[[EventsRecords]] のうち [[AgentSignifier]]AgentSignifier() であるAgent Events Recordとする。
    3. isTypedArraytrue であり、かつ IsNoTearConfiguration(type, order) が true である場合、noTeartrue とする。そうでなければ noTearfalse とする。
    4. WriteSharedMemory { [[Order]]: order, [[NoTear]]: noTear, [[Block]]: block, [[ByteIndex]]: byteIndex, [[ElementSize]]: elementSize, [[Payload]]: rawBytes } を eventsRecord.[[EventList]] に追加する。
  10. そうでなければ、
    1. rawBytes の個々のバイトを、block[byteIndex] から始めて block に格納する。
  11. unused を返す。

25.1.3.19 GetModifySetValueInBuffer ( arrayBuffer, byteIndex, type, value, op )

The abstract operation GetModifySetValueInBuffer takes arguments arrayBuffer (ArrayBufferまたはSharedArrayBuffer), byteIndex (非負整数), type (TypedArray要素型), value (NumberまたはBigInt), and op (読み取り-変更-書き込み変更関数) and returns NumberまたはBigInt. It performs the following steps when called:

  1. アサート: IsDetachedBuffer(arrayBuffer) は false である。
  2. アサート: arrayBuffer には、byteIndex から始まり type の値を表現するのに十分なバイトがある。
  3. アサート: IsBigIntElementType(type) が true である場合、value はBigIntであり、そうでなければ value はNumberである。
  4. blockarrayBuffer.[[ArrayBufferData]] とする。
  5. elementSize を、Element Type type に対して Table 71 で指定されるElement Size値とする。
  6. agentRecord を周囲のエージェントのAgent Recordとする。
  7. isLittleEndianagentRecord.[[LittleEndian]] とする。
  8. rawBytesNumericToRawBytes(type, value, isLittleEndian) とする。
  9. IsSharedArrayBuffer(arrayBuffer) が true である場合、
    1. executionagentRecord.[[CandidateExecution]] とする。
    2. eventsRecord を、execution.[[EventsRecords]] のうち [[AgentSignifier]]AgentSignifier() であるAgent Events Recordとする。
    3. rawBytesRead を、要素が非決定的に選択されたバイト値である、長さ elementSizeListとする。
    4. 注記: 実装では、rawBytesRead は基礎となるハードウェア上のload-link、load-exclusive、または読み取り-変更-書き込み命令のオペランドの結果である。非決定性は、弱い一貫性を持つハードウェアの観測可能な振る舞いを記述するための、メモリモデルの意味論的規定である。
    5. rmwEventReadModifyWriteSharedMemory { [[Order]]: seq-cst, [[NoTear]]: true, [[Block]]: block, [[ByteIndex]]: byteIndex, [[ElementSize]]: elementSize, [[Payload]]: rawBytes, [[ModifyOp]]: op } とする。
    6. rmwEventeventsRecord.[[EventList]] に追加する。
    7. Chosen Value Record { [[Event]]: rmwEvent, [[ChosenValue]]: rawBytesRead } を execution.[[ChosenValues]] に追加する。
  10. そうでなければ、
    1. rawBytesRead を、block[byteIndex] から始まる elementSize バイトの並びを要素とする、長さ elementSizeListとする。
    2. rawBytesModifiedop(rawBytesRead, rawBytes) とする。
    3. rawBytesModified の個々のバイトを、block[byteIndex] から始めて block に格納する。
  11. RawBytesToNumeric(type, rawBytesRead, isLittleEndian) を返す。

25.1.4 ArrayBuffer Constructor

ArrayBuffer constructorは:

  • %ArrayBuffer%である。
  • global object"ArrayBuffer" propertyのinitial valueである。
  • constructorとして呼び出されたとき、新しいArrayBufferをcreateしてinitializeする。
  • functionとして呼び出されることは意図されておらず、そのように呼び出された場合はexceptionをthrowする。
  • クラス定義の extends 句の値として使用できる。指定された ArrayBuffer の動作を継承しようとするサブクラスコンストラクターは、ArrayBuffer.prototype の組み込みメソッドをサポートするために必要な内部状態でサブクラスインスタンスを作成し初期化するため、ArrayBuffer コンストラクターへの super 呼び出しを含めなければならない。

25.1.4.1 ArrayBuffer ( length [ , options ] )

このfunctionは、呼び出されたときに以下のstepsを実行する:

  1. NewTargetがundefinedなら、TypeError例外をthrowする。
  2. byteLengthを ? ToIndex(length) とする。
  3. requestedMaxByteLengthを ? GetArrayBufferMaxByteLengthOption(options) とする。
  4. AllocateArrayBuffer(NewTarget, byteLength, requestedMaxByteLength)を返す。

25.1.5 ArrayBuffer Constructorのプロパティ

ArrayBuffer constructorは:

  • valueが%Function.prototype%である[[Prototype]] internal slotを持つ。
  • 以下のpropertiesを持つ:

25.1.5.1 ArrayBuffer.isView ( arg )

このfunctionは、呼び出されたときに以下のstepsを実行する:

  1. argがObjectでないなら、falseを返す。
  2. arg[[ViewedArrayBuffer]] internal slotを持つなら、trueを返す。
  3. falseを返す。

25.1.5.2 ArrayBuffer.prototype

ArrayBuffer.prototypeのinitial valueはArrayBuffer prototype objectである。

このpropertyはattributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }を持つ。

25.1.5.3 get ArrayBuffer [ %Symbol.species% ]

ArrayBuffer[%Symbol.species%]は、set accessor functionがundefinedであるaccessor propertyである。そのget accessor functionは、呼び出されたときに以下のstepsを実行する:

  1. this valueを返す。

このfunctionの"name" propertyのvalueは"get [Symbol.species]"である。

Note

ArrayBuffer.prototype.slice ( start, end )は通常、そのthis valueのconstructorを使用してderived objectをcreateする。しかし、subclass constructorは、その%Symbol.species% propertyをredefiningすることで、ArrayBuffer.prototype.slice ( start, end ) methodのためにそのdefault behaviourをover-rideしてもよい。

25.1.6 ArrayBuffer Prototype Objectのプロパティ

ArrayBuffer prototype objectは:

  • %ArrayBuffer.prototype%である。
  • valueが%Object.prototype%である[[Prototype]] internal slotを持つ。
  • ordinary objectである。
  • [[ArrayBufferData]]または[[ArrayBufferByteLength]] internal slotを持たない。

25.1.6.1 get ArrayBuffer.prototype.byteLength

ArrayBuffer.prototype.byteLengthは、set accessor functionがundefinedであるaccessor propertyである。そのget accessor functionは、呼び出されたときに以下のstepsを実行する:

  1. objthis valueとする。
  2. RequireInternalSlot(obj, [[ArrayBufferData]])を実行する。
  3. IsSharedArrayBuffer(obj)がtrueなら、TypeError例外をthrowする。
  4. IsDetachedBuffer(obj)がtrueなら、+0𝔽を返す。
  5. lengthobj.[[ArrayBufferByteLength]]とする。
  6. 𝔽(length)を返す。

25.1.6.2 ArrayBuffer.prototype.constructor

ArrayBuffer.prototype.constructorのinitial valueは%ArrayBuffer%である。

25.1.6.3 get ArrayBuffer.prototype.detached

ArrayBuffer.prototype.detachedは、set accessor functionがundefinedであるaccessor propertyである。そのget accessor functionは、呼び出されたときに以下のstepsを実行する:

  1. objthis valueとする。
  2. RequireInternalSlot(obj, [[ArrayBufferData]])を実行する。
  3. IsSharedArrayBuffer(obj)がtrueなら、TypeError例外をthrowする。
  4. IsDetachedBuffer(obj)を返す。

25.1.6.4 get ArrayBuffer.prototype.maxByteLength

ArrayBuffer.prototype.maxByteLengthは、set accessor functionがundefinedであるaccessor propertyである。そのget accessor functionは、呼び出されたときに以下のstepsを実行する:

  1. objthis valueとする。
  2. RequireInternalSlot(obj, [[ArrayBufferData]])を実行する。
  3. IsSharedArrayBuffer(obj)がtrueなら、TypeError例外をthrowする。
  4. IsDetachedBuffer(obj)がtrueなら、+0𝔽を返す。
  5. IsFixedLengthArrayBuffer(obj)がtrueなら、
    1. lengthobj.[[ArrayBufferByteLength]]とする。
  6. そうでなければ、
    1. lengthobj.[[ArrayBufferMaxByteLength]]とする。
  7. 𝔽(length)を返す。

25.1.6.5 get ArrayBuffer.prototype.resizable

ArrayBuffer.prototype.resizableは、set accessor functionがundefinedであるaccessor propertyである。そのget accessor functionは、呼び出されたときに以下のstepsを実行する:

  1. objthis valueとする。
  2. RequireInternalSlot(obj, [[ArrayBufferData]])を実行する。
  3. IsSharedArrayBuffer(obj)がtrueなら、TypeError例外をthrowする。
  4. IsFixedLengthArrayBuffer(obj)がfalseなら、trueを返す。
  5. falseを返す。

25.1.6.6 ArrayBuffer.prototype.resize ( newLength )

このmethodは、呼び出されたときに以下のstepsを実行する:

  1. objthis valueとする。
  2. RequireInternalSlot(obj, [[ArrayBufferMaxByteLength]])を実行する。
  3. IsSharedArrayBuffer(obj)がtrueなら、TypeError例外をthrowする。
  4. newByteLengthを ? ToIndex(newLength) とする。
  5. IsDetachedBuffer(obj)がtrueなら、TypeError例外をthrowする。
  6. newByteLength > obj.[[ArrayBufferMaxByteLength]]なら、RangeError例外をthrowする。
  7. hostHandledを ? HostResizeArrayBuffer(obj, newByteLength) とする。
  8. hostHandledhandledなら、undefinedを返す。
  9. oldBlockobj.[[ArrayBufferData]]とする。
  10. newBlockを ? CreateByteDataBlock(newByteLength) とする。
  11. copyLengthmin(newByteLength, obj.[[ArrayBufferByteLength]])とする。
  12. CopyDataBlockBytes(newBlock, 0, oldBlock, 0, copyLength)を実行する。
  13. NOTE: 新しいData Blockのcreationもold Data Blockからのcopyingもobservableではない。Implementationsは、このmethodをin-place growthまたはshrinkageとしてimplementしてもよい。
  14. obj.[[ArrayBufferData]]newBlockに設定する。
  15. obj.[[ArrayBufferByteLength]]newByteLengthに設定する。
  16. undefinedを返す。

25.1.6.7 ArrayBuffer.prototype.slice ( start, end )

このmethodは、呼び出されたときに以下のstepsを実行する:

  1. objthis valueとする。
  2. RequireInternalSlot(obj, [[ArrayBufferData]])を実行する。
  3. IsSharedArrayBuffer(obj)がtrueなら、TypeError例外をthrowする。
  4. IsDetachedBuffer(obj)がtrueなら、TypeError例外をthrowする。
  5. lengthobj.[[ArrayBufferByteLength]]とする。
  6. relativeStartを ? ToIntegerOrInfinity(start) とする。
  7. relativeStart = -∞なら、firstを0とする。
  8. そうでなく、relativeStart < 0なら、firstmax(length + relativeStart, 0)とする。
  9. そうでなければ、firstmin(relativeStart, length)とする。
  10. endundefinedなら、relativeEndlengthとする;そうでなければ、relativeEndを ? ToIntegerOrInfinity(end) とする。
  11. relativeEnd = -∞なら、finalを0とする。
  12. そうでなく、relativeEnd < 0なら、finalmax(length + relativeEnd, 0)とする。
  13. そうでなければ、finalmin(relativeEnd, length)とする。
  14. newLengthmax(final - first, 0)とする。
  15. ctorを ? SpeciesConstructor(obj, %ArrayBuffer%) とする。
  16. newを ? Construct(ctor, « 𝔽(newLength) ») とする。
  17. RequireInternalSlot(new, [[ArrayBufferData]])を実行する。
  18. IsSharedArrayBuffer(new)がtrueなら、TypeError例外をthrowする。
  19. IsDetachedBuffer(new)がtrueなら、TypeError例外をthrowする。
  20. SameValue(new, obj)がtrueなら、TypeError例外をthrowする。
  21. new.[[ArrayBufferByteLength]] < newLengthなら、TypeError例外をthrowする。
  22. NOTE: 上記stepsのside-effectsにより、objがdetachedまたはresizedされている可能性がある。
  23. IsDetachedBuffer(obj)がtrueなら、TypeError例外をthrowする。
  24. fromBufobj.[[ArrayBufferData]]とする。
  25. toBufnew.[[ArrayBufferData]]とする。
  26. currentLengthobj.[[ArrayBufferByteLength]]とする。
  27. first < currentLengthなら、
    1. countmin(newLength, currentLength - first)とする。
    2. CopyDataBlockBytes(toBuf, 0, fromBuf, first, count)を実行する。
  28. newを返す。

25.1.6.8 ArrayBuffer.prototype.transfer ( [ newLength ] )

このmethodは、呼び出されたときに以下のstepsを実行する:

  1. objthis valueとする。
  2. ArrayBufferCopyAndDetach(obj, newLength, preserve-resizability)を返す。

25.1.6.9 ArrayBuffer.prototype.transferToFixedLength ( [ newLength ] )

このmethodは、呼び出されたときに以下のstepsを実行する:

  1. objthis valueとする。
  2. ArrayBufferCopyAndDetach(obj, newLength, fixed-length)を返す。

25.1.6.10 ArrayBuffer.prototype [ %Symbol.toStringTag% ]

%Symbol.toStringTag% propertyのinitial valueはString value "ArrayBuffer"である。

このpropertyはattributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }を持つ。

25.1.7 ArrayBuffer Instancesのプロパティ

ArrayBuffer instancesはArrayBuffer prototype objectからpropertiesをinheritする。ArrayBuffer instancesはそれぞれ[[ArrayBufferData]] internal slot、[[ArrayBufferByteLength]] internal slot、および[[ArrayBufferDetachKey]] internal slotを持つ。resizableなArrayBuffer instancesはそれぞれ[[ArrayBufferMaxByteLength]] internal slotを持つ。

[[ArrayBufferData]]nullであるArrayBuffer instancesはdetachedであるとconsideredされ、ArrayBuffer instanceにcontainedされるdataにaccessまたはmodifyするすべてのoperatorsはfailする。

[[ArrayBufferDetachKey]]undefined以外のvalueに設定されているArrayBuffer instancesでは、すべてのDetachArrayBuffer callsがその同じ“detach key”をargumentとしてpassする必要があり、そうでなければTypeErrorがresultする。このinternal slotはcertain embedding environmentsによってのみ設定され、この仕様のalgorithmsによって設定されることはない。

25.1.8 Resizable ArrayBuffer Guidelines

Note 1

以下は、resizable ArrayBufferを扱うECMAScript programmersのためのguidelinesである。

programsは、可能であればdeployment environmentsでtestedされることをrecommendする。available physical memoryの量はhardware devices間でgreatlyに異なる。同様に、virtual memory subsystemsもhardware devices間およびoperating systems間でgreatlyに異なる。64-bit desktop web browserでout-of-memory errorsなしにrunsするapplicationが、32-bit mobile web browserではout of memoryになる可能性がある。

resizable ArrayBuffer"maxByteLength" optionのvalueをchooseする場合、applicationにとって可能なsmallest sizeをchooseすることをrecommendする。"maxByteLength"は1,073,741,824(230 bytesまたは1GiB)をexceedしないことをrecommendする。

particular maximum sizeのresizable ArrayBufferのconstructionがsuccessfullyであっても、future resizesがsucceedすることはguaranteeされない点に注意。

Note 2

以下は、resizable ArrayBufferをimplementingするECMAScript implementersのためのguidelinesである。

Resizable ArrayBufferは、resize時にcopyingするものとして、virtual memoryをup frontにreservingすることによるin-place growthとして、またはconstructor"maxByteLength" optionのdifferent valuesに対する両者のcombinationとしてimplementできる。

hostがmulti-tenanted(すなわち、多数のECMAScript applicationsをsimultaneouslyにrunsする)である場合、web browserなどで、そのimplementationsがvirtual memoryをreservingすることでin-place growthをimplementすることをchooseするなら、32-bitおよび64-bitの両implementationsは、"maxByteLength" ≥ 1GiBから1.5GiBのvaluesに対してthrowすることをrecommendする。これは、single applicationがvirtual memory address spaceをexhaustできるlikelihoodをreduceし、interoperability riskをreduceするためである。

hostがMMUのないembedded devices上でrunningするもののようにvirtual memoryを持たない場合、またはhostがcopyingによるresizingのみをimplementする場合、"maxByteLength" optionについて任意のNumber value forをacceptしてもよい。しかし、requested sizeのmemory blockがnever allocatedできない場合にはRangeErrorがthrowされることをrecommendする。例えば、requested sizeがdevice上のusable memoryのmaximum amountよりもgreaterである場合である。

25.2 SharedArrayBufferオブジェクト

25.2.1 Fixed-lengthおよびGrowable SharedArrayBufferオブジェクト

fixed-length SharedArrayBufferは、creation後にbyte lengthがchangeできないSharedArrayBufferである。

growable SharedArrayBufferは、SharedArrayBuffer.prototype.grow ( newLength )へのcallsを介してcreation後にbyte lengthがincreaseしてもよいSharedArrayBufferである。

createdされるSharedArrayBuffer objectのkindは、SharedArrayBuffer ( length [ , options ] )にpassedされるargumentsに依存する。

25.2.2 SharedArrayBufferオブジェクトの抽象操作

25.2.2.1 AllocateSharedArrayBuffer ( ctor, byteLength [ , maxByteLength ] )

The abstract operation AllocateSharedArrayBuffer takes arguments ctor (a constructor) and byteLength (a non-negative integer) and optional argument maxByteLength (a non-negative integer or empty) and returns either a normal completion containing a SharedArrayBuffer or a throw completion. SharedArrayBufferをcreateするために使用される。 It performs the following steps when called:

  1. Let slots be « [[ArrayBufferData]] ».
  2. If maxByteLength is present and maxByteLength is not empty, let allocatingGrowableBuffer be true; else let allocatingGrowableBuffer be false.
  3. If allocatingGrowableBuffer is true, then
    1. If byteLength > maxByteLength, throw a RangeError exception.
    2. Append [[ArrayBufferByteLengthData]] and [[ArrayBufferMaxByteLength]] to slots.
  4. Else,
    1. Append [[ArrayBufferByteLength]] to slots.
  5. Let obj be ? OrdinaryCreateFromConstructor(ctor, "%SharedArrayBuffer.prototype%", slots).
  6. If allocatingGrowableBuffer is true, let allocLength be maxByteLength; else let allocLength be byteLength.
  7. Let block be ? CreateSharedByteDataBlock(allocLength).
  8. Set obj.[[ArrayBufferData]] to block.
  9. If allocatingGrowableBuffer is true, then
    1. Assert: byteLengthmaxByteLength.
    2. Let byteLengthBlock be ? CreateSharedByteDataBlock(8).
    3. Perform SetValueInBuffer(byteLengthBlock, 0, biguint64, (byteLength), true, seq-cst).
    4. Set obj.[[ArrayBufferByteLengthData]] to byteLengthBlock.
    5. Set obj.[[ArrayBufferMaxByteLength]] to maxByteLength.
  10. Else,
    1. Set obj.[[ArrayBufferByteLength]] to byteLength.
  11. Return obj.

25.2.2.2 IsSharedArrayBuffer ( obj )

The abstract operation IsSharedArrayBuffer takes argument obj (an ArrayBuffer or a SharedArrayBuffer) and returns a Boolean. objectがSharedArrayBufferであるかどうかをtestする。 It performs the following steps when called:

  1. obj.[[ArrayBufferData]]Shared Data Blockなら、trueを返す。
  2. falseを返す。

25.2.2.3 IsGrowableSharedArrayBuffer ( obj )

The abstract operation IsGrowableSharedArrayBuffer takes argument obj (an ArrayBuffer or a SharedArrayBuffer) and returns a Boolean. objectがgrowable SharedArrayBufferであるかどうかをtestする。 It performs the following steps when called:

  1. IsSharedArrayBuffer(obj)がtrueであり、obj[[ArrayBufferByteLengthData]] internal slotを持つなら、trueを返す。
  2. falseを返す。

25.2.2.4 HostGrowSharedArrayBuffer ( buffer, newByteLength )

The host-defined abstract operation HostGrowSharedArrayBuffer takes arguments buffer (a SharedArrayBuffer) and newByteLength (a non-negative integer) and returns either a normal completion containing either handled or unhandled, or a throw completion. hostに、bufferimplementation-defined growingをperformする機会を与える。hostがbufferのgrowingをhandleしないことをchooseした場合、default behaviourのためにunhandledを返してもよい。

HostGrowSharedArrayBufferのimplementationは、以下のrequirementsにconformしなければならない:

  • abstract operationがunhandledでnormally completeしない場合に、newByteLength < bufferのcurrent byte lengthまたはnewByteLength > buffer.[[ArrayBufferMaxByteLength]]であるなら、RangeError例外をthrowする。
  • agentRecordsurrounding agentAgent Recordとする。isLittleEndianagentRecord.[[LittleEndian]]とする。abstract operationがhandledでnormally completeする場合、[[Order]]seq-cst[[Payload]]NumericToRawBytes(biguint64, newByteLength, isLittleEndian)、[[Block]]buffer.[[ArrayBufferByteLengthData]][[ByteIndex]]が0、[[ElementSize]]が8であるWriteSharedMemoryまたはReadModifyWriteSharedMemory eventが、SharedArrayBuffer.prototype.grow ( newLength )へのracing callsが“lost”されない、すなわちsilently do nothingしないように、surrounding agentcandidate executionにaddedされる。
Note

上記のsecond requirementは、bufferのcurrent byte lengthがどのように、またはいつreadされるかについてintentionally vagueである。byte lengthはunderlying hardware上のatomic read-modify-write operationを介してupdatedされなければならないため、load-link/store-conditionalまたはload-exclusive/store-exclusive instruction pairsを使用するarchitecturesでは、paired instructionsをinstruction stream内でcloseに保ちたい場合がある。そのため、SharedArrayBuffer.prototype.grow ( newLength )自体はHostGrowSharedArrayBufferをcallingする前にnewByteLengthに対するbounds checkingをperformせず、current byte lengthがいつreadされるかに関するrequirementもない。

これは、0 ≤ newByteLengthbuffer.[[ArrayBufferMaxByteLength]]であることがguaranteedされるHostResizeArrayBufferとは対照的である。

HostGrowSharedArrayBufferのdefault implementationはNormalCompletion(unhandled)を返すことである。

25.2.3 SharedArrayBuffer Constructor

SharedArrayBuffer constructorは:

  • %SharedArrayBuffer%である。
  • そのpropertyがpresentである場合(belowを参照)、global object"SharedArrayBuffer" propertyのinitial valueである。
  • constructorとして呼び出されたとき、新しいSharedArrayBufferをcreateしてinitializeする。
  • functionとして呼び出されることは意図されておらず、そのように呼び出された場合はexceptionをthrowする。
  • クラス定義の extends 句の値として使用できる。指定された SharedArrayBuffer の動作を継承しようとするサブクラスコンストラクターは、SharedArrayBuffer.prototype の組み込みメソッドをサポートするために必要な内部状態でサブクラスインスタンスを作成し初期化するため、SharedArrayBuffer コンストラクターへの super 呼び出しを含めなければならない。

hostがSharedArrayBuffersへのconcurrent accessをprovideしない場合はいつでも、global object"SharedArrayBuffer" propertyをomitしてもよい。

Note

ArrayBufferとは異なり、SharedArrayBufferはdetachedになることができず、そのinternal [[ArrayBufferData]] slotは決してnullにならない。

25.2.3.1 SharedArrayBuffer ( length [ , options ] )

このfunctionは、呼び出されたときに以下のstepsを実行する:

  1. NewTargetがundefinedなら、TypeError例外をthrowする。
  2. byteLengthを ? ToIndex(length) とする。
  3. requestedMaxByteLengthを ? GetArrayBufferMaxByteLengthOption(options) とする。
  4. AllocateSharedArrayBuffer(NewTarget, byteLength, requestedMaxByteLength)を返す。

25.2.4 SharedArrayBuffer Constructorのプロパティ

SharedArrayBuffer constructorは:

  • valueが%Function.prototype%である[[Prototype]] internal slotを持つ。
  • 以下のpropertiesを持つ:

25.2.4.1 SharedArrayBuffer.prototype

SharedArrayBuffer.prototypeのinitial valueはSharedArrayBuffer prototype objectである。

このpropertyはattributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }を持つ。

25.2.4.2 get SharedArrayBuffer [ %Symbol.species% ]

SharedArrayBuffer[%Symbol.species%]は、set accessor functionがundefinedであるaccessor propertyである。そのget accessor functionは、呼び出されたときに以下のstepsを実行する:

  1. this valueを返す。

このfunctionの"name" propertyのvalueは"get [Symbol.species]"である。

25.2.5 SharedArrayBuffer Prototype Objectのプロパティ

SharedArrayBuffer prototype objectは:

  • %SharedArrayBuffer.prototype%である。
  • valueが%Object.prototype%である[[Prototype]] internal slotを持つ。
  • ordinary objectである。
  • [[ArrayBufferData]]または[[ArrayBufferByteLength]] internal slotを持たない。

25.2.5.1 get SharedArrayBuffer.prototype.byteLength

SharedArrayBuffer.prototype.byteLengthは、set accessor functionがundefinedであるaccessor propertyである。そのget accessor functionは、呼び出されたときに以下のstepsを実行する:

  1. objthis valueとする。
  2. RequireInternalSlot(obj, [[ArrayBufferData]])を実行する。
  3. IsSharedArrayBuffer(obj)がfalseなら、TypeError例外をthrowする。
  4. lengthArrayBufferByteLength(obj, seq-cst)とする。
  5. 𝔽(length)を返す。

25.2.5.2 SharedArrayBuffer.prototype.constructor

SharedArrayBuffer.prototype.constructorのinitial valueは%SharedArrayBuffer%である。

25.2.5.3 SharedArrayBuffer.prototype.grow ( newLength )

このmethodは、呼び出されたときに以下のstepsを実行する:

  1. objthis valueとする。
  2. RequireInternalSlot(obj, [[ArrayBufferMaxByteLength]])を実行する。
  3. IsSharedArrayBuffer(obj)がfalseなら、TypeError例外をthrowする。
  4. newByteLengthを ? ToIndex(newLength) とする。
  5. hostHandledを ? HostGrowSharedArrayBuffer(obj, newByteLength) とする。
  6. hostHandledhandledなら、undefinedを返す。
  7. agentRecordsurrounding agentAgent Recordとする。
  8. isLittleEndianagentRecord.[[LittleEndian]]とする。
  9. byteLengthBlockobj.[[ArrayBufferByteLengthData]]とする。
  10. currentByteLengthRawBytesGetRawBytesFromSharedBlock(byteLengthBlock, 0, biguint64, true, seq-cst)とする。
  11. newByteLengthRawBytesNumericToRawBytes(biguint64, (newByteLength), isLittleEndian)とする。
  12. Repeat,
    1. NOTE: これは、same bufferのparallelかつracingなgrowsがtotally orderedされ、lostされず、silently do nothingしないことをensureするためのcompare-and-exchange loopである。このloopは、uncontendedにgrowをattemptできた場合にexitする。
    2. currentByteLength(RawBytesToNumeric(biguint64, currentByteLengthRawBytes, isLittleEndian))とする。
    3. newByteLength = currentByteLengthなら、undefinedを返す。
    4. newByteLength < currentByteLengthまたはnewByteLength > obj.[[ArrayBufferMaxByteLength]]なら、RangeError例外をthrowする。
    5. byteLengthDeltanewByteLength - currentByteLengthとする。
    6. byteLengthDelta bytesからなるnew Shared Data Block valueをcreateすることがimpossibleなら、RangeError例外をthrowする。
    7. NOTE: ここではnew Shared Data Blockはconstructedもusedもされない。growable SharedArrayBuffersのobservable behaviourは、construction timeにmax-sized Shared Data Blockをallocatingすることでspecifiedされており、このstepは、out of memoryになったimplementationsがRangeErrorをthrowしなければならないというrequirementをcaptureする。
    8. readByteLengthRawBytesAtomicCompareExchangeInSharedBlock(byteLengthBlock, 0, 8, currentByteLengthRawBytes, newByteLengthRawBytes)とする。
    9. ByteListEqual(readByteLengthRawBytes, currentByteLengthRawBytes)がtrueなら、undefinedを返す。
    10. currentByteLengthRawBytesreadByteLengthRawBytesに設定する。
Note

lengthをupdateするcompare-exchangeのspurious failuresは禁止される。new lengthのbounds checkingがpassし、implementationがout of memoryでない場合、ReadModifyWriteSharedMemory event(すなわちsuccessful compare-exchange)は常にcandidate executionへaddedされる。

SharedArrayBuffer.prototype.growへのparallel callsはtotally orderedである。例えば、sab.grow(10)sab.grow(20)という2つのracing callsを考える。2つのcallsのうち一方がraceにwinすることがguaranteedされる。sab.grow(10)へのcallは、たとえsab.grow(20)が先にhappenedしたとしても、決してsabをshrinkしない;その場合は代わりにRangeErrorをthrowする。

25.2.5.4 get SharedArrayBuffer.prototype.growable

SharedArrayBuffer.prototype.growableは、set accessor functionがundefinedであるaccessor propertyである。そのget accessor functionは、呼び出されたときに以下のstepsを実行する:

  1. objthis valueとする。
  2. RequireInternalSlot(obj, [[ArrayBufferData]])を実行する。
  3. IsSharedArrayBuffer(obj)がfalseなら、TypeError例外をthrowする。
  4. IsFixedLengthArrayBuffer(obj)がfalseなら、trueを返す。
  5. falseを返す。

25.2.5.5 get SharedArrayBuffer.prototype.maxByteLength

SharedArrayBuffer.prototype.maxByteLengthは、set accessor functionがundefinedであるaccessor propertyである。そのget accessor functionは、呼び出されたときに以下のstepsを実行する:

  1. objthis valueとする。
  2. RequireInternalSlot(obj, [[ArrayBufferData]])を実行する。
  3. IsSharedArrayBuffer(obj)がfalseなら、TypeError例外をthrowする。
  4. IsFixedLengthArrayBuffer(obj)がtrueなら、
    1. lengthobj.[[ArrayBufferByteLength]]とする。
  5. そうでなければ、
    1. lengthobj.[[ArrayBufferMaxByteLength]]とする。
  6. 𝔽(length)を返す。

25.2.5.6 SharedArrayBuffer.prototype.slice ( start, end )

このmethodは、呼び出されたときに以下のstepsを実行する:

  1. objthis valueとする。
  2. RequireInternalSlot(obj, [[ArrayBufferData]])を実行する。
  3. IsSharedArrayBuffer(obj)がfalseなら、TypeError例外をthrowする。
  4. lengthArrayBufferByteLength(obj, seq-cst)とする。
  5. relativeStartを ? ToIntegerOrInfinity(start) とする。
  6. relativeStart = -∞なら、firstを0とする。
  7. そうでなく、relativeStart < 0なら、firstmax(length + relativeStart, 0)とする。
  8. そうでなければ、firstmin(relativeStart, length)とする。
  9. endundefinedなら、relativeEndlengthとする;そうでなければ、relativeEndを ? ToIntegerOrInfinity(end) とする。
  10. relativeEnd = -∞なら、finalを0とする。
  11. そうでなく、relativeEnd < 0なら、finalmax(length + relativeEnd, 0)とする。
  12. そうでなければ、finalmin(relativeEnd, length)とする。
  13. newLengthmax(final - first, 0)とする。
  14. ctorを ? SpeciesConstructor(obj, %SharedArrayBuffer%) とする。
  15. newを ? Construct(ctor, « 𝔽(newLength) ») とする。
  16. RequireInternalSlot(new, [[ArrayBufferData]])を実行する。
  17. IsSharedArrayBuffer(new)がfalseなら、TypeError例外をthrowする。
  18. new.[[ArrayBufferData]]obj.[[ArrayBufferData]]であるなら、TypeError例外をthrowする。
  19. ArrayBufferByteLength(new, seq-cst) < newLengthなら、TypeError例外をthrowする。
  20. fromBufobj.[[ArrayBufferData]]とする。
  21. toBufnew.[[ArrayBufferData]]とする。
  22. CopyDataBlockBytes(toBuf, 0, fromBuf, first, newLength)を実行する。
  23. newを返す。

25.2.5.7 SharedArrayBuffer.prototype [ %Symbol.toStringTag% ]

%Symbol.toStringTag% propertyのinitial valueはString value "SharedArrayBuffer"である。

このpropertyはattributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }を持つ。

25.2.6 SharedArrayBuffer Instancesのプロパティ

SharedArrayBuffer instancesはSharedArrayBuffer prototype objectからpropertiesをinheritする。SharedArrayBuffer instancesはそれぞれ[[ArrayBufferData]] internal slotを持つ。growableでないSharedArrayBuffer instancesはそれぞれ[[ArrayBufferByteLength]] internal slotを持つ。growableなSharedArrayBuffer instancesはそれぞれ[[ArrayBufferByteLengthData]] internal slotおよび[[ArrayBufferMaxByteLength]] internal slotを持つ。

Note

SharedArrayBuffer instancesは、ArrayBuffer instancesとは異なり、決してdetachedされない。

25.2.7 Growable SharedArrayBuffer Guidelines

Note 1

以下は、growable SharedArrayBufferを扱うECMAScript programmersのためのguidelinesである。

programsは、可能であればdeployment environmentsでtestedされることをrecommendする。available physical memoryの量はhardware devices間でgreatlyに異なる。同様に、virtual memory subsystemsもhardware devices間およびoperating systems間でgreatlyに異なる。64-bit desktop web browserでout-of-memory errorsなしにrunsするapplicationが、32-bit mobile web browserではout of memoryになる可能性がある。

growable SharedArrayBuffer"maxByteLength" optionのvalueをchooseする場合、applicationにとって可能なsmallest sizeをchooseすることをrecommendする。"maxByteLength"は1073741824、すなわち1GiBをexceedしないことをrecommendする。

particular maximum sizeのgrowable SharedArrayBufferのconstructionがsuccessfullyであっても、future growsがsucceedすることはguaranteeされない点に注意。

growable SharedArrayBufferのlengthのすべてのloadsがsynchronizing seq-cst loadsであるわけではない。integer-indexed property access(例:u8[idx])のbounds-checkingのためのlengthのloadsはsynchronizingではない。一般に、explicit synchronizationがない場合、あるproperty accessがin-boundであることは、同じagent内のsubsequent property accessもin-boundであることをimplyしない。対照的に、SharedArrayBuffer、%TypedArray%.prototype、およびDataView.prototype上のlengthおよびbyteLength gettersを介したlengthのexplicit loadsはsynchronizingである。TypedArrayがentirely out-of-boundsであるかをcheckするためにbuilt-in methodsによってperformedされるlengthのloadsもsynchronizingである。

Note 2

以下は、growable SharedArrayBufferをimplementingするECMAScript implementersのためのguidelinesである。

growable SharedArrayBufferは、virtual memoryをup frontにreservingすることによるin-place growthとしてimplementedされることをrecommendする。

grow operationsはgrowable SharedArrayBuffer上のmemory accessesとparallelにhappenできるため、memory modelのconstraintsは、unordered accessesであっても“tear”(それらのvaluesのbitsがmixedされる)しないことをrequireする。実際には、これはgrowable SharedArrayBufferのunderlying data blockが、worldをstoppingせずにcopyされることによってgrownできないことを意味する。serialization pointをintroduceしslowであるため、implementation strategyとしてstopping the worldはrecommendしない。

Grown memoryは、そのcreationの瞬間から、parallelなracy accessesに対しても含めて、zeroedにappearしなければならない。これはzero-filled-on-demand virtual memory pages、またはmanualにzeroing memoryする場合はcareful synchronizationによってaccomplishedできる。

growable SharedArrayBuffersのTypedArray views上のinteger-indexed property accessは、non-growable SharedArrayBuffersのTypedArray views上のaccessと同様にoptimizableであることがintendedされている。なぜなら、integer-indexed property loadsはunderlying bufferのlengthに対してsynchronizingではないからである(上記programmer guidelinesを参照)。例えば、property accessesのbounds checksは依然としてloopsの外へhoistedされてもよい。

MMUのないembedded devices上でrunningするhostsのようにvirtual memoryを持たないhostsでは、growable SharedArrayBufferをcopyingによってimplementすることは実際にはdifficultである。そのようなhostsにおけるgrowable SharedArrayBuffersのmemory usage behaviourは、virtual memoryを持つhostsのものとsignificantlyに異なる可能性がある。そのようなhostsは、memory usage expectationsをusersにclearly communicateするべきである。

25.3 DataViewオブジェクト

25.3.1 DataViewオブジェクトの抽象操作

25.3.1.1 DataView With Buffer Witness Records

DataView With Buffer Witness Recordは、viewed bufferのcached byte lengthとともにDataViewをencapsulateするために使用されるRecord valueである。viewed bufferがgrowable SharedArrayBufferである場合に、byte length data blockのReadSharedMemory eventがsingleであることをensureする助けとして使用される。

DataView With Buffer Witness Recordsは、Table 73にlistedされるfieldsを持つ。

Table 73: DataView With Buffer Witness Record Fields
Field Name Value Meaning
[[Object]] a DataView bufferのbyte lengthがloadedされるDataView object。
[[CachedBufferByteLength]] a non-negative integer or detached Recordがcreatedされたときのobjectの[[ViewedArrayBuffer]]のbyte length。

25.3.1.2 MakeDataViewWithBufferWitnessRecord ( obj, order )

The abstract operation MakeDataViewWithBufferWitnessRecord takes arguments obj (a DataView) and order (seq-cst or unordered) and returns a DataView With Buffer Witness Record. It performs the following steps when called:

  1. bufferobj.[[ViewedArrayBuffer]]とする。
  2. IsDetachedBuffer(buffer)がtrueなら、
    1. byteLengthdetachedとする。
  3. そうでなければ、
    1. byteLengthArrayBufferByteLength(buffer, order)とする。
  4. DataView With Buffer Witness Record { [[Object]]: obj, [[CachedBufferByteLength]]: byteLength }を返す。

25.3.1.3 GetViewByteLength ( viewRecord )

The abstract operation GetViewByteLength takes argument viewRecord (a DataView With Buffer Witness Record) and returns a non-negative integer. It performs the following steps when called:

  1. Assert: IsViewOutOfBounds(viewRecord)はfalseである。
  2. viewviewRecord.[[Object]]とする。
  3. view.[[ByteLength]]autoでないなら、view.[[ByteLength]]を返す。
  4. Assert: IsFixedLengthArrayBuffer(view.[[ViewedArrayBuffer]])はfalseである。
  5. byteOffsetview.[[ByteOffset]]とする。
  6. byteLengthviewRecord.[[CachedBufferByteLength]]とする。
  7. Assert: byteLengthdetachedでない。
  8. byteLength - byteOffsetを返す。

25.3.1.4 IsViewOutOfBounds ( viewRecord )

The abstract operation IsViewOutOfBounds takes argument viewRecord (a DataView With Buffer Witness Record) and returns a Boolean. It performs the following steps when called:

  1. viewviewRecord.[[Object]]とする。
  2. bufferByteLengthviewRecord.[[CachedBufferByteLength]]とする。
  3. IsDetachedBuffer(view.[[ViewedArrayBuffer]])がtrueなら、
    1. Assert: bufferByteLengthdetachedである。
    2. trueを返す。
  4. Assert: bufferByteLengthはnon-negative integerである。
  5. byteOffsetStartview.[[ByteOffset]]とする。
  6. view.[[ByteLength]]autoなら、
    1. byteOffsetEndbufferByteLengthとする。
  7. そうでなければ、
    1. byteOffsetEndbyteOffsetStart + view.[[ByteLength]]とする。
  8. NOTE: [[ByteOffset]]bufferByteLengthである0-length DataViewはout-of-boundsであるとはconsideredされない。
  9. byteOffsetStart > bufferByteLengthまたはbyteOffsetEnd > bufferByteLengthなら、trueを返す。
  10. falseを返す。

25.3.1.5 GetViewValue ( view, requestIndex, isLittleEndian, type )

The abstract operation GetViewValue takes arguments view (an ECMAScript language value), requestIndex (an ECMAScript language value), isLittleEndian (an ECMAScript language value), and type (a TypedArray element type) and returns either a normal completion containing either a Number or a BigInt, or a throw completion. DataView instances上のfunctionsによって、viewのbufferからvaluesをretrieveするために使用される。 It performs the following steps when called:

  1. RequireInternalSlot(view, [[DataView]])を実行する。
  2. Assert: view[[ViewedArrayBuffer]] internal slotを持つ。
  3. getIndexを ? ToIndex(requestIndex) とする。
  4. isLittleEndianToBoolean(isLittleEndian)に設定する。
  5. viewOffsetview.[[ByteOffset]]とする。
  6. viewRecordMakeDataViewWithBufferWitnessRecord(view, unordered)とする。
  7. NOTE: viewのbacking bufferがgrowable SharedArrayBufferである場合、Bounds checkingはsynchronizing operationではない。
  8. IsViewOutOfBounds(viewRecord)がtrueなら、TypeError例外をthrowする。
  9. viewSizeGetViewByteLength(viewRecord)とする。
  10. elementSizeを、Element Type typeについてTable 71でspecifiedされるElement Size valueとする。
  11. getIndex + elementSize > viewSizeなら、RangeError例外をthrowする。
  12. bufferIndexgetIndex + viewOffsetとする。
  13. GetValueFromBuffer(view.[[ViewedArrayBuffer]], bufferIndex, type, false, unordered, isLittleEndian)を返す。

25.3.1.6 SetViewValue ( view, requestIndex, isLittleEndian, type, value )

The abstract operation SetViewValue takes arguments view (an ECMAScript language value), requestIndex (an ECMAScript language value), isLittleEndian (an ECMAScript language value), type (a TypedArray element type), and value (an ECMAScript language value) and returns either a normal completion containing undefined or a throw completion. DataView instances上のfunctionsによって、viewのbufferへvaluesをstoreするために使用される。 It performs the following steps when called:

  1. RequireInternalSlot(view, [[DataView]])を実行する。
  2. Assert: view[[ViewedArrayBuffer]] internal slotを持つ。
  3. getIndexを ? ToIndex(requestIndex) とする。
  4. IsBigIntElementType(type)がtrueなら、numberを ? ToBigInt(value) とする。
  5. そうでなければ、numberを ? ToNumber(value) とする。
  6. isLittleEndianToBoolean(isLittleEndian)に設定する。
  7. viewOffsetview.[[ByteOffset]]とする。
  8. viewRecordMakeDataViewWithBufferWitnessRecord(view, unordered)とする。
  9. NOTE: viewのbacking bufferがgrowable SharedArrayBufferである場合、Bounds checkingはsynchronizing operationではない。
  10. IsViewOutOfBounds(viewRecord)がtrueなら、TypeError例外をthrowする。
  11. viewSizeGetViewByteLength(viewRecord)とする。
  12. elementSizeを、Element Type typeについてTable 71でspecifiedされるElement Size valueとする。
  13. getIndex + elementSize > viewSizeなら、RangeError例外をthrowする。
  14. bufferIndexgetIndex + viewOffsetとする。
  15. SetValueInBuffer(view.[[ViewedArrayBuffer]], bufferIndex, type, number, false, unordered, isLittleEndian)を実行する。
  16. undefinedを返す。

25.3.2 DataView Constructor

DataView constructorは:

  • %DataView%である。
  • global object"DataView" propertyのinitial valueである。
  • constructorとして呼び出されたとき、新しいDataViewをcreateしてinitializeする。
  • functionとして呼び出されることは意図されておらず、そのように呼び出された場合はexceptionをthrowする。
  • クラス定義の extends 句の値として使用できる。指定された DataView の動作を継承しようとするサブクラスコンストラクターは、DataView.prototype の組み込みメソッドをサポートするために必要な内部状態でサブクラスインスタンスを作成し初期化するため、DataView コンストラクターへの super 呼び出しを含めなければならない。

25.3.2.1 DataView ( buffer [ , byteOffset [ , byteLength ] ] )

このfunctionは、呼び出されたときに以下のstepsを実行する:

  1. NewTargetがundefinedなら、TypeError例外をthrowする。
  2. RequireInternalSlot(buffer, [[ArrayBufferData]])を実行する。
  3. offsetを ? ToIndex(byteOffset) とする。
  4. IsDetachedBuffer(buffer)がtrueなら、TypeError例外をthrowする。
  5. bufferByteLengthArrayBufferByteLength(buffer, seq-cst)とする。
  6. offset > bufferByteLengthなら、RangeError例外をthrowする。
  7. bufferIsFixedLengthIsFixedLengthArrayBuffer(buffer)とする。
  8. byteLengthundefinedなら、
    1. bufferIsFixedLengthtrueなら、
      1. viewByteLengthbufferByteLength - offsetとする。
    2. そうでなければ、
      1. viewByteLengthautoとする。
  9. そうでなければ、
    1. viewByteLengthを ? ToIndex(byteLength) とする。
    2. offset + viewByteLength > bufferByteLengthなら、RangeError例外をthrowする。
  10. objを ? OrdinaryCreateFromConstructor(NewTarget, "%DataView.prototype%", « [[DataView]], [[ViewedArrayBuffer]], [[ByteLength]], [[ByteOffset]] ») とする。
  11. IsDetachedBuffer(buffer)がtrueなら、TypeError例外をthrowする。
  12. bufferByteLengthArrayBufferByteLength(buffer, seq-cst)に設定する。
  13. offset > bufferByteLengthなら、RangeError例外をthrowする。
  14. byteLengthundefinedでないなら、
    1. offset + viewByteLength > bufferByteLengthなら、RangeError例外をthrowする。
  15. obj.[[ViewedArrayBuffer]]bufferに設定する。
  16. obj.[[ByteLength]]viewByteLengthに設定する。
  17. obj.[[ByteOffset]]offsetに設定する。
  18. objを返す。

25.3.3 DataView Constructorのプロパティ

DataView constructorは:

  • valueが%Function.prototype%である[[Prototype]] internal slotを持つ。
  • 以下のpropertiesを持つ:

25.3.3.1 DataView.prototype

DataView.prototypeのinitial valueはDataView prototype objectである。

このpropertyはattributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }を持つ。

25.3.4 DataView Prototype Objectのプロパティ

DataView prototype objectは:

  • %DataView.prototype%である。
  • valueが%Object.prototype%である[[Prototype]] internal slotを持つ。
  • ordinary objectである。
  • [[DataView]], [[ViewedArrayBuffer]], [[ByteLength]], または[[ByteOffset]] internal slotを持たない。

25.3.4.1 get DataView.prototype.buffer

DataView.prototype.bufferは、set accessor functionがundefinedであるaccessor propertyである。そのget accessor functionは、呼び出されたときに以下のstepsを実行する:

  1. objthis valueとする。
  2. RequireInternalSlot(obj, [[DataView]])を実行する。
  3. Assert: obj[[ViewedArrayBuffer]] internal slotを持つ。
  4. bufferobj.[[ViewedArrayBuffer]]とする。
  5. bufferを返す。

25.3.4.2 get DataView.prototype.byteLength

DataView.prototype.byteLengthは、set accessor functionがundefinedであるaccessor propertyである。そのget accessor functionは、呼び出されたときに以下のstepsを実行する:

  1. objthis valueとする。
  2. RequireInternalSlot(obj, [[DataView]])を実行する。
  3. Assert: obj[[ViewedArrayBuffer]] internal slotを持つ。
  4. viewRecordMakeDataViewWithBufferWitnessRecord(obj, seq-cst)とする。
  5. IsViewOutOfBounds(viewRecord)がtrueなら、TypeError例外をthrowする。
  6. sizeGetViewByteLength(viewRecord)とする。
  7. 𝔽(size)を返す。

25.3.4.3 get DataView.prototype.byteOffset

DataView.prototype.byteOffsetは、set accessor functionがundefinedであるaccessor propertyである。そのget accessor functionは、呼び出されたときに以下のstepsを実行する:

  1. objthis valueとする。
  2. RequireInternalSlot(obj, [[DataView]])を実行する。
  3. Assert: obj[[ViewedArrayBuffer]] internal slotを持つ。
  4. viewRecordMakeDataViewWithBufferWitnessRecord(obj, seq-cst)とする。
  5. IsViewOutOfBounds(viewRecord)がtrueなら、TypeError例外をthrowする。
  6. offsetobj.[[ByteOffset]]とする。
  7. 𝔽(offset)を返す。

25.3.4.4 DataView.prototype.constructor

DataView.prototype.constructorのinitial valueは%DataView%である。

25.3.4.5 DataView.prototype.getBigInt64 ( byteOffset [ , littleEndian ] )

このmethodは、呼び出されたときに以下のstepsを実行する:

  1. viewthis valueとする。
  2. GetViewValue(view, byteOffset, littleEndian, bigint64)を返す。

25.3.4.6 DataView.prototype.getBigUint64 ( byteOffset [ , littleEndian ] )

このmethodは、呼び出されたときに以下のstepsを実行する:

  1. viewthis valueとする。
  2. GetViewValue(view, byteOffset, littleEndian, biguint64)を返す。

25.3.4.7 DataView.prototype.getFloat16 ( byteOffset [ , littleEndian ] )

このmethodは、呼び出されたときに以下のstepsを実行する:

  1. viewthis valueとする。
  2. littleEndianがpresentでないなら、littleEndianfalseに設定する。
  3. GetViewValue(view, byteOffset, littleEndian, float16)を返す。

25.3.4.8 DataView.prototype.getFloat32 ( byteOffset [ , littleEndian ] )

このmethodは、呼び出されたときに以下のstepsを実行する:

  1. viewthis valueとする。
  2. littleEndianがpresentでないなら、littleEndianfalseに設定する。
  3. GetViewValue(view, byteOffset, littleEndian, float32)を返す。

25.3.4.9 DataView.prototype.getFloat64 ( byteOffset [ , littleEndian ] )

このmethodは、呼び出されたときに以下のstepsを実行する:

  1. viewthis valueとする。
  2. littleEndianがpresentでないなら、littleEndianfalseに設定する。
  3. GetViewValue(view, byteOffset, littleEndian, float64)を返す。

25.3.4.10 DataView.prototype.getInt8 ( byteOffset )

このmethodは、呼び出されたときに以下のstepsを実行する:

  1. viewthis valueとする。
  2. GetViewValue(view, byteOffset, true, int8)を返す。

25.3.4.11 DataView.prototype.getInt16 ( byteOffset [ , littleEndian ] )

このmethodは、呼び出されたときに以下のstepsを実行する:

  1. viewthis valueとする。
  2. littleEndianがpresentでないなら、littleEndianfalseに設定する。
  3. GetViewValue(view, byteOffset, littleEndian, int16)を返す。

25.3.4.12 DataView.prototype.getInt32 ( byteOffset [ , littleEndian ] )

このmethodは、呼び出されたときに以下のstepsを実行する:

  1. viewthis valueとする。
  2. littleEndianがpresentでないなら、littleEndianfalseに設定する。
  3. GetViewValue(view, byteOffset, littleEndian, int32)を返す。

25.3.4.13 DataView.prototype.getUint8 ( byteOffset )

このmethodは、呼び出されたときに以下のstepsを実行する:

  1. viewthis valueとする。
  2. GetViewValue(view, byteOffset, true, uint8)を返す。

25.3.4.14 DataView.prototype.getUint16 ( byteOffset [ , littleEndian ] )

このmethodは、呼び出されたときに以下のstepsを実行する:

  1. viewthis valueとする。
  2. littleEndianがpresentでないなら、littleEndianfalseに設定する。
  3. GetViewValue(view, byteOffset, littleEndian, uint16)を返す。

25.3.4.15 DataView.prototype.getUint32 ( byteOffset [ , littleEndian ] )

このmethodは、呼び出されたときに以下のstepsを実行する:

  1. viewthis valueとする。
  2. littleEndianがpresentでないなら、littleEndianfalseに設定する。
  3. GetViewValue(view, byteOffset, littleEndian, uint32)を返す。

25.3.4.16 DataView.prototype.setBigInt64 ( byteOffset, value [ , littleEndian ] )

このmethodは、呼び出されたときに以下のstepsを実行する:

  1. viewthis valueとする。
  2. SetViewValue(view, byteOffset, littleEndian, bigint64, value)を返す。

25.3.4.17 DataView.prototype.setBigUint64 ( byteOffset, value [ , littleEndian ] )

このmethodは、呼び出されたときに以下のstepsを実行する:

  1. viewthis valueとする。
  2. SetViewValue(view, byteOffset, littleEndian, biguint64, value)を返す。

25.3.4.18 DataView.prototype.setFloat16 ( byteOffset, value [ , littleEndian ] )

このmethodは、呼び出されたときに以下のstepsを実行する:

  1. viewthis valueとする。
  2. littleEndianがpresentでないなら、littleEndianfalseに設定する。
  3. SetViewValue(view, byteOffset, littleEndian, float16, value)を返す。

25.3.4.19 DataView.prototype.setFloat32 ( byteOffset, value [ , littleEndian ] )

このmethodは、呼び出されたときに以下のstepsを実行する:

  1. viewthis valueとする。
  2. littleEndianがpresentでないなら、littleEndianfalseに設定する。
  3. SetViewValue(view, byteOffset, littleEndian, float32, value)を返す。

25.3.4.20 DataView.prototype.setFloat64 ( byteOffset, value [ , littleEndian ] )

このmethodは、呼び出されたときに以下のstepsを実行する:

  1. viewthis valueとする。
  2. littleEndianがpresentでないなら、littleEndianfalseに設定する。
  3. SetViewValue(view, byteOffset, littleEndian, float64, value)を返す。

25.3.4.21 DataView.prototype.setInt8 ( byteOffset, value )

このmethodは、呼び出されたときに以下のstepsを実行する:

  1. viewthis valueとする。
  2. SetViewValue(view, byteOffset, true, int8, value)を返す。

25.3.4.22 DataView.prototype.setInt16 ( byteOffset, value [ , littleEndian ] )

このmethodは、呼び出されたときに以下のstepsを実行する:

  1. viewthis valueとする。
  2. littleEndianがpresentでないなら、littleEndianfalseに設定する。
  3. SetViewValue(view, byteOffset, littleEndian, int16, value)を返す。

25.3.4.23 DataView.prototype.setInt32 ( byteOffset, value [ , littleEndian ] )

このmethodは、呼び出されたときに以下のstepsを実行する:

  1. viewthis valueとする。
  2. littleEndianがpresentでないなら、littleEndianfalseに設定する。
  3. SetViewValue(view, byteOffset, littleEndian, int32, value)を返す。

25.3.4.24 DataView.prototype.setUint8 ( byteOffset, value )

このmethodは、呼び出されたときに以下のstepsを実行する:

  1. viewthis valueとする。
  2. SetViewValue(view, byteOffset, true, uint8, value)を返す。

25.3.4.25 DataView.prototype.setUint16 ( byteOffset, value [ , littleEndian ] )

このmethodは、呼び出されたときに以下のstepsを実行する:

  1. viewthis valueとする。
  2. littleEndianがpresentでないなら、littleEndianfalseに設定する。
  3. SetViewValue(view, byteOffset, littleEndian, uint16, value)を返す。

25.3.4.26 DataView.prototype.setUint32 ( byteOffset, value [ , littleEndian ] )

このmethodは、呼び出されたときに以下のstepsを実行する:

  1. viewthis valueとする。
  2. littleEndianがpresentでないなら、littleEndianfalseに設定する。
  3. SetViewValue(view, byteOffset, littleEndian, uint32, value)を返す。

25.3.4.27 DataView.prototype [ %Symbol.toStringTag% ]

%Symbol.toStringTag% propertyのinitial valueはString value "DataView"である。

このpropertyはattributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }を持つ。

25.3.5 DataView Instancesのプロパティ

DataView instancesはDataView prototype objectからpropertiesをinheritするordinary objectsである。DataView instancesはそれぞれ[[DataView]][[ViewedArrayBuffer]][[ByteLength]]、および[[ByteOffset]] internal slotsを持つ。

Note

[[DataView]] internal slotのvalueは、この仕様内では使用されない。そのinternal slotのsimple presenceが、DataView constructorを使用してcreatedされたobjectsをidentifyするために仕様内で使用される。

25.4 Atomicsオブジェクト

Atomicsオブジェクトは:

  • %Atomics%である。
  • global object"Atomics" propertyのinitial valueである。
  • ordinary objectである。
  • valueが%Object.prototype%である[[Prototype]] internal slotを持つ。
  • [[Construct]] internal methodを持たない;new operatorでconstructorとして使用できない。
  • [[Call]] internal methodを持たない;functionとしてinvokeできない。

Atomicsオブジェクトは、shared memory array cells上でindivisibly(atomically)にoperateするfunctionsと、agentsにprimitive eventsをwaitおよびdispatchさせるfunctionsをprovideする。disciplineをもって使用される場合、Atomics functionsは、shared memoryを介してcommunicateするmulti-agent programsが、parallel CPUs上であってもwell-understoodなorderでexecuteすることを可能にする。shared-memory communicationをgovernするrulesは、belowでdefinedされるmemory modelによってprovideされる。

Note

ECMAScriptでshared memoryをprogrammingおよびimplementingするためのinformative guidelinesについては、memory model sectionの末尾のnotesを参照。

25.4.1 Waiter Record

Waiter Recordは、Atomics.waitまたはAtomics.waitAsyncへのparticular callをdenoteするために使用されるRecord valueである。

Waiter Recordは、Table 74にlistedされるfieldsを持つ。

Table 74: Waiter Record Fields
フィールド名 意味
[[AgentSignifier]] an agent signifier Atomics.waitまたはAtomics.waitAsyncをcalledしたagent
[[PromiseCapability]] a PromiseCapability Record or blocking Atomics.waitAsyncへのcallをdenoteする場合はresulting promise、そうでなければblocking
[[TimeoutTime]] a non-negative extended mathematical value timeoutがtriggerされ得る最も早い時刻;time valuesを使用してcomputedされる。
[[Result]] "ok" or "timed-out" callのreturn value。

25.4.2 WaiterList Records

WaiterList Recordは、Atomics.waitAtomics.waitAsync、およびAtomics.notifyを介するagentsのwaitingおよびnotificationをexplainするために使用される。

WaiterList Recordは、Table 75にlistedされるfieldsを持つ。

Table 75: WaiterList Record Fields
フィールド名 意味
[[Waiters]] a List of Waiter Records このWaiterListがassociatedされるlocation上でwaitingしている、Atomics.waitまたはAtomics.waitAsyncへのcalls。
[[MostRecentLeaveEvent]] a Synchronize event or empty そのcritical sectionからmost recentにleavingしたevent、またはそのcritical sectionが一度もenteredされていない場合はempty

同じagent signifierを持つ複数のWaiter RecordsがWaiterList内に存在できる。

agent clusterはWaiterList Recordsのstoreを持つ;そのstoreは(block, i)によってindexedされる。ここで、blockShared Data Blockであり、iblockのmemory内へのbyte offsetである。WaiterList Recordsはagent-independentである:WaiterList Recordsのstoreにおける(block, i)によるlookupは、agent cluster内のどのagentにおいてもsame WaiterList Recordをresultする。

各WaiterList Recordは、evaluation中にそのWaiterList Recordへのexclusive accessをcontrolするcritical sectionを持つ。一度にsingle agentのみがWaiterList Recordのcritical sectionにenterできる。WaiterList Recordのcritical sectionへのenteringおよびleavingは、abstract operations EnterCriticalSectionおよびLeaveCriticalSectionによってcontrolledされる。WaiterList Record上のoperations—waiting agentsのaddingおよびremoving、agentsのlistのtraversing、list上のagentsのsuspendingおよびnotifying、Synchronize eventのsettingおよびretrieving—は、WaiterList Recordのcritical sectionにenteredしたagentsによってのみperformedされ得る。

25.4.3 Atomicsの抽象操作

25.4.3.1 ValidateIntegerTypedArray ( ta, waitable )

The abstract operation ValidateIntegerTypedArray takes arguments ta (an ECMAScript language value) and waitable (a Boolean) and returns either a normal completion containing a TypedArray With Buffer Witness Record, or a throw completion. It performs the following steps when called:

  1. taRecordを ? ValidateTypedArray(ta, unordered) とする。
  2. NOTE: taのbacking bufferがgrowable SharedArrayBufferである場合、Bounds checkingはsynchronizing operationではない。
  3. waitabletrueなら、
    1. ta.[[TypedArrayName]]"Int32Array"でも"BigInt64Array"でもないなら、TypeError例外をthrowする。
  4. そうでなければ、
    1. typeTypedArrayElementType(ta)とする。
    2. IsUnclampedIntegerElementType(type)がfalseであり、かつIsBigIntElementType(type)がfalseなら、TypeError例外をthrowする。
  5. taRecordを返す。

25.4.3.2 ValidateAtomicAccess ( taRecord, requestIndex )

The abstract operation ValidateAtomicAccess takes arguments taRecord (a TypedArray With Buffer Witness Record) and requestIndex (an ECMAScript language value) and returns either a normal completion containing a non-negative integer or a throw completion. It performs the following steps when called:

  1. lengthTypedArrayLength(taRecord)とする。
  2. accessIndexを ? ToIndex(requestIndex) とする。
  3. Assert: accessIndex ≥ 0である。
  4. accessIndexlengthなら、RangeError例外をthrowする。
  5. tataRecord.[[Object]]とする。
  6. elementSizeTypedArrayElementSize(ta)とする。
  7. offsetta.[[ByteOffset]]とする。
  8. (accessIndex × elementSize) + offsetを返す。

25.4.3.3 ValidateAtomicAccessOnIntegerTypedArray ( ta, requestIndex )

The abstract operation ValidateAtomicAccessOnIntegerTypedArray takes arguments ta (an ECMAScript language value) and requestIndex (an ECMAScript language value) and returns either a normal completion containing a non-negative integer or a throw completion. It performs the following steps when called:

  1. taRecordを ? ValidateIntegerTypedArray(ta, false) とする。
  2. ValidateAtomicAccess(taRecord, requestIndex)を返す。

25.4.3.4 RevalidateAtomicAccess ( ta, byteIndexInBuffer )

The abstract operation RevalidateAtomicAccess takes arguments ta (a TypedArray) and byteIndexInBuffer (a non-negative integer) and returns either a normal completion containing unused or a throw completion. このoperationは、Atomics methodsにおいてすべてのargument coercionsがperformedされた後、atomic operationsのためのbacking buffer内のindexをrevalidateする。argument coercionsはarbitrary side effectsを持ち得るため、bufferがout of boundsになる可能性がある。このoperationは、taのbacking bufferがSharedArrayBufferである場合にはthrowしない。 It performs the following steps when called:

  1. taRecordMakeTypedArrayWithBufferWitnessRecord(ta, unordered)とする。
  2. NOTE: taのbacking bufferがgrowable SharedArrayBufferである場合、Bounds checkingはsynchronizing operationではない。
  3. IsTypedArrayOutOfBounds(taRecord)がtrueなら、TypeError例外をthrowする。
  4. Assert: byteIndexInBufferta.[[ByteOffset]]である。
  5. byteIndexInBuffertaRecord.[[CachedBufferByteLength]]なら、RangeError例外をthrowする。
  6. unusedを返す。

25.4.3.5 GetWaiterList ( block, i )

The abstract operation GetWaiterList takes arguments block (a Shared Data Block) and i (a non-negative integer that is evenly divisible by 4) and returns a WaiterList Record. It performs the following steps when called:

  1. Assert: iおよびi + 3はblockのmemory内のvalid byte offsetsである。
  2. pair (block, i)によってreferencedされるWaiterList Recordを返す。

25.4.3.6 EnterCriticalSection ( waiterList )

The abstract operation EnterCriticalSection takes argument waiterList (a WaiterList Record) and returns unused. It performs the following steps when called:

  1. Assert: surrounding agentはいかなるWaiterList Recordについてもcritical section内にいない。
  2. waiterListcritical section内にagentがいなくなるまでwaitし、その後waiterListcritical sectionにenterする(他のagentがenterすることをallowせずに)。
  3. waiterList.[[MostRecentLeaveEvent]]emptyでないなら、
    1. NOTE: 少なくとも一度critical sectionにenteredされたwaiterListは、LeaveCriticalSectionによってsetされたSynchronize eventを持つ。
    2. agentRecordsurrounding agentAgent Recordとする。
    3. executionagentRecord.[[CandidateExecution]]とする。
    4. eventsRecordを、execution.[[EventsRecords]]のうち[[AgentSignifier]]AgentSignifier()であるAgent Events Recordとする。
    5. enterEventをnew Synchronize eventとする。
    6. enterEventeventsRecord.[[EventList]]にappendする。
    7. (waiterList.[[MostRecentLeaveEvent]], enterEvent)をeventsRecord.[[AgentSynchronizesWith]]にappendする。
  4. unusedを返す。

EnterCriticalSectionは、critical sectionへenterしようとするagentが別のagentのleavingをwaitしなければならない場合、contentionを持つ。contentionがない場合、EnterCriticalSection callsのFIFO orderはobservableである。contentionがある場合、implementationはarbitrary orderをchooseしてもよいが、agentをindefinitelyにwaitさせてはならない。

25.4.3.7 LeaveCriticalSection ( waiterList )

The abstract operation LeaveCriticalSection takes argument waiterList (a WaiterList Record) and returns unused. It performs the following steps when called:

  1. Assert: surrounding agentwaiterListcritical section内にいる。
  2. agentRecordsurrounding agentAgent Recordとする。
  3. executionagentRecord.[[CandidateExecution]]とする。
  4. eventsRecordを、execution.[[EventsRecords]]のうち[[AgentSignifier]]AgentSignifier()であるAgent Events Recordとする。
  5. leaveEventをnew Synchronize eventとする。
  6. leaveEventeventsRecord.[[EventList]]にappendする。
  7. waiterList.[[MostRecentLeaveEvent]]leaveEventに設定する。
  8. waiterListcritical sectionをleaveする。
  9. unusedを返す。

25.4.3.8 AddWaiter ( waiterList, waiterRecord )

The abstract operation AddWaiter takes arguments waiterList (a WaiterList Record) and waiterRecord (a Waiter Record) and returns unused. It performs the following steps when called:

  1. Assert: surrounding agentwaiterListcritical section内にいる。
  2. Assert: waiterList.[[Waiters]]内に、[[PromiseCapability]] fieldがwaiterRecord.[[PromiseCapability]]であり、かつ[[AgentSignifier]] fieldがwaiterRecord.[[AgentSignifier]]であるWaiter Recordは存在しない。
  3. waiterRecordwaiterList.[[Waiters]]にappendする。
  4. unusedを返す。

25.4.3.9 RemoveWaiter ( waiterList, waiterRecord )

The abstract operation RemoveWaiter takes arguments waiterList (a WaiterList Record) and waiterRecord (a Waiter Record) and returns unused. It performs the following steps when called:

  1. Assert: surrounding agentwaiterListcritical section内にいる。
  2. Assert: waiterList.[[Waiters]]waiterRecordを含む。
  3. waiterRecordwaiterList.[[Waiters]]からremoveする。
  4. unusedを返す。

25.4.3.10 RemoveWaiters ( waiterList, count )

The abstract operation RemoveWaiters takes arguments waiterList (a WaiterList Record) and count (a non-negative integer or +∞) and returns a List of Waiter Records. It performs the following steps when called:

  1. Assert: surrounding agentwaiterListcritical section内にいる。
  2. lengthwaiterList.[[Waiters]]内のelementsのnumberとする。
  3. countmin(count, length)に設定する。
  4. waitersを、elementsがwaiterList.[[Waiters]]のfirst count elementsであるListとする。
  5. waiterList.[[Waiters]]のfirst count elementsをremoveする。
  6. waitersを返す。

25.4.3.11 SuspendThisAgent ( waiterList, waiterRecord )

The abstract operation SuspendThisAgent takes arguments waiterList (a WaiterList Record) and waiterRecord (a Waiter Record) and returns unused. It performs the following steps when called:

  1. Assert: surrounding agentwaiterListcritical section内にいる。
  2. Assert: waiterList.[[Waiters]]waiterRecordを含む。
  3. thisAgentAgentSignifier()とする。
  4. Assert: waiterRecord.[[AgentSignifier]]thisAgentである。
  5. Assert: waiterRecord.[[PromiseCapability]]blockingである。
  6. Assert: AgentCanSuspend()はtrueである。
  7. LeaveCriticalSection(waiterList)を実行し、時刻がwaiterRecord.[[TimeoutTime]]になるまでsurrounding agentをsuspendする。critical sectionをexitedした後で、suspensionがtake effectする前にarrivesするnotificationがlostされないように、combined operationをperformする。surrounding agentは、timeoutによって、または別のagentがarguments waiterListおよびthisAgentNotifyWaiterをcallingすること(すなわちAtomics.notifyへのcallを介すること)によってのみ、suspensionからwakeできる。
  8. EnterCriticalSection(waiterList)を実行する。
  9. unusedを返す。

25.4.3.12 NotifyWaiter ( waiterList, waiterRecord )

The abstract operation NotifyWaiter takes arguments waiterList (a WaiterList Record) and waiterRecord (a Waiter Record) and returns unused. It performs the following steps when called:

  1. Assert: surrounding agentwaiterListcritical section内にいる。
  2. waiterRecord.[[PromiseCapability]]blockingなら、
    1. signifierがwaiterRecord.[[AgentSignifier]]であるagentをsuspensionからwakeする。
    2. NOTE: これは、agentSuspendThisAgent内でexecutionをresumeすることをcauseする。
  3. そうでなく、AgentSignifier()がwaiterRecord.[[AgentSignifier]]であるなら、
    1. promiseCapabilitywaiterRecord.[[PromiseCapability]]とする。
    2. Call(promiseCapability.[[Resolve]], undefined, « waiterRecord.[[Result]] »)を実行する。
  4. そうでなければ、
    1. EnqueueResolveInAgentJob(waiterRecord.[[AgentSignifier]], waiterRecord.[[PromiseCapability]], waiterRecord.[[Result]])を実行する。
  5. unusedを返す。
Note

agentは、hostへpassingすることを超えて、いかなるcapacityにおいても別のagentのpromise capabilityにaccessしてはならない。

25.4.3.13 EnqueueResolveInAgentJob ( agentSignifier, promiseCapability, resolution )

The abstract operation EnqueueResolveInAgentJob takes arguments agentSignifier (an agent signifier), promiseCapability (a PromiseCapability Record), and resolution ("ok" or "timed-out") and returns unused. It performs the following steps when called:

  1. resolveJobを、parametersを持たず、agentSignifierpromiseCapability、およびresolutionをcapturesし、calledされたときに以下のstepsを実行するnew Job Abstract Closureとする:
    1. Assert: AgentSignifier()はagentSignifierである。
    2. Call(promiseCapability.[[Resolve]], undefined, « resolution »)を実行する。
    3. unusedを返す。
  2. realmInTargetAgentを ! GetFunctionRealm(promiseCapability.[[Resolve]]) とする。
  3. Assert: agentSignifierrealmInTargetAgent.[[AgentSignifier]]である。
  4. HostEnqueueGenericJob(resolveJob, realmInTargetAgent)を実行する。
  5. unusedを返す。

25.4.3.14 DoWait ( mode, ta, index, value, timeout )

The abstract operation DoWait takes arguments mode (sync or async), ta (an ECMAScript language value), index (an ECMAScript language value), value (an ECMAScript language value), and timeout (an ECMAScript language value) and returns either a normal completion containing either an Object, "not-equal", "timed-out", or "ok", or a throw completion. It performs the following steps when called:

  1. taRecordを ? ValidateIntegerTypedArray(ta, true) とする。
  2. buffertaRecord.[[Object]].[[ViewedArrayBuffer]]とする。
  3. IsSharedArrayBuffer(buffer)がfalseなら、TypeError例外をthrowする。
  4. byteIndexInBufferを ? ValidateAtomicAccess(taRecord, index) とする。
  5. arrayTypeNameta.[[TypedArrayName]]とする。
  6. arrayTypeName"BigInt64Array"なら、expectedを ? ToBigInt64(value) とする。
  7. そうでなければ、expectedを ? ToInt32(value) とする。
  8. timeoutNumberを ? ToNumber(timeout) とする。
  9. timeoutNumberNaNまたは+∞𝔽のいずれかなら、realTimeoutを+∞とする。
  10. そうでなく、timeoutNumber-∞𝔽なら、realTimeoutを0とする。
  11. そうでなければ、realTimeoutmax((timeoutNumber), 0)とする。
  12. modesyncであり、AgentCanSuspend()がfalseなら、TypeError例外をthrowする。
  13. blockbuffer.[[ArrayBufferData]]とする。
  14. waiterListGetWaiterList(block, byteIndexInBuffer)とする。
  15. modesyncなら、
    1. promiseCapabilityblockingとする。
    2. resultObjundefinedとする。
  16. そうでなければ、
    1. promiseCapabilityを ! NewPromiseCapability(%Promise%) とする。
    2. resultObjOrdinaryObjectCreate(%Object.prototype%)とする。
  17. EnterCriticalSection(waiterList)を実行する。
  18. elementTypeTypedArrayElementType(ta)とする。
  19. witnessGetValueFromBuffer(buffer, byteIndexInBuffer, elementType, true, seq-cst)とする。
  20. expectedwitnessなら、
    1. LeaveCriticalSection(waiterList)を実行する。
    2. modesyncなら、"not-equal"を返す。
    3. CreateDataPropertyOrThrow(resultObj, "async", false)を実行する。
    4. CreateDataPropertyOrThrow(resultObj, "value", "not-equal")を実行する。
    5. resultObjを返す。
  21. realTimeout = 0かつmodeasyncなら、
    1. NOTE: synchronous immediate timeoutsにspecial handlingはない。Asynchronous immediate timeoutsは、fail fastし、unnecessary Promise jobsをavoidするためにspecial handlingを持つ。
    2. LeaveCriticalSection(waiterList)を実行する。
    3. CreateDataPropertyOrThrow(resultObj, "async", false)を実行する。
    4. CreateDataPropertyOrThrow(resultObj, "value", "timed-out")を実行する。
    5. resultObjを返す。
  22. thisAgentAgentSignifier()とする。
  23. nowをcurrent timeをidentifyingするtime value (UTC)とする。
  24. additionalTimeoutimplementation-defined non-negative mathematical valueとする。
  25. timeoutTime(now) + realTimeout + additionalTimeoutとする。
  26. NOTE: realTimeoutが+∞である場合、timeoutTimeも+∞である。
  27. waiterRecordをnew Waiter Record { [[AgentSignifier]]: thisAgent, [[PromiseCapability]]: promiseCapability, [[TimeoutTime]]: timeoutTime, [[Result]]: "ok" }とする。
  28. AddWaiter(waiterList, waiterRecord)を実行する。
  29. modesyncなら、
    1. SuspendThisAgent(waiterList, waiterRecord)を実行する。
  30. そうでなく、timeoutTimefiniteなら、
    1. EnqueueAtomicsWaitAsyncTimeoutJob(waiterList, waiterRecord)を実行する。
  31. LeaveCriticalSection(waiterList)を実行する。
  32. modesyncなら、waiterRecord.[[Result]]を返す。
  33. CreateDataPropertyOrThrow(resultObj, "async", true)を実行する。
  34. CreateDataPropertyOrThrow(resultObj, "value", promiseCapability.[[Promise]])を実行する。
  35. resultObjを返す。
Note

additionalTimeoutは、power consumptionのreducingやtiming attacksをmitigateするためのtimer resolutionのcoarseningなど、必要に応じてimplementationsがtimeoutsをpadすることを可能にする。このvalueはDoWaitのcallごとに異なってもよい。

25.4.3.15 EnqueueAtomicsWaitAsyncTimeoutJob ( waiterList, waiterRecord )

The abstract operation EnqueueAtomicsWaitAsyncTimeoutJob takes arguments waiterList (a WaiterList Record) and waiterRecord (a Waiter Record) and returns unused. It performs the following steps when called:

  1. timeoutJobを、parametersを持たず、waiterListおよびwaiterRecordをcapturesし、calledされたときに以下のstepsを実行するnew Job Abstract Closureとする:
    1. EnterCriticalSection(waiterList)を実行する。
    2. waiterList.[[Waiters]]waiterRecordを含むなら、
      1. timeOfJobExecutionをcurrent timeをidentifyingするtime value (UTC)とする。
      2. Assert: (timeOfJobExecution) ≥ waiterRecord.[[TimeoutTime]]である(time valuesのpotential non-monotonicityをignoringする)。
      3. waiterRecord.[[Result]]"timed-out"に設定する。
      4. RemoveWaiter(waiterList, waiterRecord)を実行する。
      5. NotifyWaiter(waiterList, waiterRecord)を実行する。
    3. LeaveCriticalSection(waiterList)を実行する。
    4. unusedを返す。
  2. nowをcurrent timeをidentifyingするtime value (UTC)とする。
  3. currentRealmcurrent Realm Recordとする。
  4. HostEnqueueTimeoutJob(timeoutJob, currentRealm, 𝔽(waiterRecord.[[TimeoutTime]]) - now)を実行する。
  5. unusedを返す。

25.4.3.16 AtomicCompareExchangeInSharedBlock ( block, byteIndexInBuffer, elementSize, expectedBytes, replacementBytes )

The abstract operation AtomicCompareExchangeInSharedBlock takes arguments block (a Shared Data Block), byteIndexInBuffer (an integer), elementSize (a non-negative integer), expectedBytes (a List of byte values), and replacementBytes (a List of byte values) and returns a List of byte values. It performs the following steps when called:

  1. agentRecordsurrounding agentAgent Recordとする。
  2. executionagentRecord.[[CandidateExecution]]とする。
  3. eventsRecordを、execution.[[EventsRecords]]のうち[[AgentSignifier]]AgentSignifier()であるAgent Events Recordとする。
  4. rawBytesReadを、elementsがnondeterministicallyにchosenされたbyte valuesであるlength elementSizeListとする。
  5. NOTE: implementationsにおいて、rawBytesReadはunderlying hardware上のload-link、load-exclusive、またはread-modify-write instructionのoperandのresultである。nondeterminismは、weak consistencyを持つhardwareのobservable behaviourをdescribeするためのmemory modelのsemantic prescriptionである。
  6. NOTE: expected valueとread valueのcomparisonは、expected valueがread valueとequalでない場合にneedlessly strong synchronizationをavoidするため、read-modify-write modification functionの外側でperformedされる。
  7. ByteListEqual(rawBytesRead, expectedBytes)がtrueなら、
    1. secondを、parameters (oldBytes, newBytes)を持ち、nothingをcapturesし、calledされたときに以下のstepsをatomicallyに実行するnew read-modify-write modification functionとする:
      1. newBytesを返す。
    2. eventReadModifyWriteSharedMemory { [[Order]]: seq-cst, [[NoTear]]: true, [[Block]]: block, [[ByteIndex]]: byteIndexInBuffer, [[ElementSize]]: elementSize, [[Payload]]: replacementBytes, [[ModifyOp]]: second }とする。
  8. そうでなければ、
    1. eventReadSharedMemory { [[Order]]: seq-cst, [[NoTear]]: true, [[Block]]: block, [[ByteIndex]]: byteIndexInBuffer, [[ElementSize]]: elementSize }とする。
  9. eventeventsRecord.[[EventList]]にappendする。
  10. Chosen Value Record { [[Event]]: event, [[ChosenValue]]: rawBytesRead }をexecution.[[ChosenValues]]にappendする。
  11. rawBytesReadを返す。

25.4.3.17 AtomicReadModifyWrite ( ta, index, value, op )

The abstract operation AtomicReadModifyWrite takes arguments ta (an ECMAScript language value), index (an ECMAScript language value), value (an ECMAScript language value), and op (a read-modify-write modification function) and returns either a normal completion containing either a Number or a BigInt, or a throw completion. opは2つのList of byte values argumentsを取り、List of byte valuesを返す。このoperationはvalueをatomicallyにloadし、それをanother valueとcombineし、そのcombinationをstoreする。これはloaded valueを返す。 It performs the following steps when called:

  1. byteIndexInBufferを ? ValidateAtomicAccessOnIntegerTypedArray(ta, index) とする。
  2. ta.[[ContentType]]bigintなら、coercedを ? ToBigInt(value) とする。
  3. そうでなければ、coerced𝔽(? ToIntegerOrInfinity(value))とする。
  4. RevalidateAtomicAccess(ta, byteIndexInBuffer)を実行する。
  5. bufferta.[[ViewedArrayBuffer]]とする。
  6. elementTypeTypedArrayElementType(ta)とする。
  7. GetModifySetValueInBuffer(buffer, byteIndexInBuffer, elementType, coerced, op)を返す。

25.4.3.18 ByteListBitwiseOp ( op, xBytes, yBytes )

The abstract operation ByteListBitwiseOp takes arguments op (&, ^, or |), xBytes (a List of byte values), and yBytes (a List of byte values) and returns a List of byte values. このoperationは、argumentsのすべてのbyte valuesに対してbitwise operationをatomicallyにperformし、List of byte valuesを返す。 It performs the following steps when called:

  1. Assert: xBytesyBytesは同じnumberのelementsを持つ。
  2. resultをnew empty Listとする。
  3. iを0とする。
  4. xBytesの各element xByteについて、
    1. yByteyBytes[i]とする。
    2. op&なら、
      1. resultByteを、xByteyByteにbitwise AND operationをapplyingしたresultとする。
    3. そうでなく、op^なら、
      1. resultByteを、xByteyByteにbitwise exclusive OR (XOR) operationをapplyingしたresultとする。
    4. そうでなければ、
      1. Assert: op|である。
      2. resultByteを、xByteyByteにbitwise inclusive OR operationをapplyingしたresultとする。
    5. ii + 1に設定する。
    6. resultByteresultにappendする。
  5. resultを返す。

25.4.3.19 ByteListEqual ( xBytes, yBytes )

The abstract operation ByteListEqual takes arguments xBytes (a List of byte values) and yBytes (a List of byte values) and returns a Boolean. It performs the following steps when called:

  1. xBytesyBytesが同じnumberのelementsを持たないなら、falseを返す。
  2. iを0とする。
  3. xBytesの各element xByteについて、
    1. yByteyBytes[i]とする。
    2. xByteyByteなら、falseを返す。
    3. ii + 1に設定する。
  4. trueを返す。

25.4.4 Atomics.add ( ta, index, value )

このfunctionは、呼び出されたときに以下のstepsを実行する:

  1. addを、parameters (xBytes, yBytes)を持ち、taをcapturesし、calledされたときに以下のstepsをatomicallyに実行するnew read-modify-write modification functionとする:
    1. typeTypedArrayElementType(ta)とする。
    2. agentRecordsurrounding agentAgent Recordとする。
    3. isLittleEndianagentRecord.[[LittleEndian]]とする。
    4. xRawBytesToNumeric(type, xBytes, isLittleEndian)とする。
    5. yRawBytesToNumeric(type, yBytes, isLittleEndian)とする。
    6. xがNumberなら、
      1. sumNumber::add(x, y)とする。
    7. そうでなければ、
      1. Assert: xはBigIntである。
      2. sumBigInt::add(x, y)とする。
    8. sumBytesNumericToRawBytes(type, sum, isLittleEndian)とする。
    9. Assert: sumBytesxBytes、およびyBytesは同じnumberのelementsを持つ。
    10. sumBytesを返す。
  2. AtomicReadModifyWrite(ta, index, value, add)を返す。

25.4.5 Atomics.and ( ta, index, value )

このfunctionは、呼び出されたときに以下のstepsを実行する:

  1. andを、parameters (xBytes, yBytes)を持ち、nothingをcapturesし、calledされたときに以下のstepsをatomicallyに実行するnew read-modify-write modification functionとする:
    1. ByteListBitwiseOp(&, xBytes, yBytes)を返す。
  2. AtomicReadModifyWrite(ta, index, value, and)を返す。

25.4.6 Atomics.compareExchange ( ta, index, expectedValue, replacementValue )

このfunctionは、呼び出されたときに以下のstepsを実行する:

  1. byteIndexInBufferを ? ValidateAtomicAccessOnIntegerTypedArray(ta, index) とする。
  2. bufferta.[[ViewedArrayBuffer]]とする。
  3. blockbuffer.[[ArrayBufferData]]とする。
  4. ta.[[ContentType]]bigintなら、
    1. expectedを ? ToBigInt(expectedValue) とする。
    2. replacementを ? ToBigInt(replacementValue) とする。
  5. そうでなければ、
    1. expected𝔽(? ToIntegerOrInfinity(expectedValue))とする。
    2. replacement𝔽(? ToIntegerOrInfinity(replacementValue))とする。
  6. RevalidateAtomicAccess(ta, byteIndexInBuffer)を実行する。
  7. elementTypeTypedArrayElementType(ta)とする。
  8. elementSizeTypedArrayElementSize(ta)とする。
  9. agentRecordsurrounding agentAgent Recordとする。
  10. isLittleEndianagentRecord.[[LittleEndian]]とする。
  11. expectedBytesNumericToRawBytes(elementType, expected, isLittleEndian)とする。
  12. replacementBytesNumericToRawBytes(elementType, replacement, isLittleEndian)とする。
  13. IsSharedArrayBuffer(buffer)がtrueなら、
    1. rawBytesReadAtomicCompareExchangeInSharedBlock(block, byteIndexInBuffer, elementSize, expectedBytes, replacementBytes)とする。
  14. そうでなければ、
    1. rawBytesReadを、elementsがblock[byteIndexInBuffer]でstartingするelementSize bytesのsequenceであるlength elementSizeListとする。
    2. ByteListEqual(rawBytesRead, expectedBytes)がtrueなら、
      1. replacementBytesのindividual bytesをblockに、block[byteIndexInBuffer]からstartingしてstoreする。
  15. RawBytesToNumeric(elementType, rawBytesRead, isLittleEndian)を返す。

25.4.7 Atomics.exchange ( ta, index, value )

このfunctionは、呼び出されたときに以下のstepsを実行する:

  1. secondを、parameters (oldBytes, newBytes)を持ち、nothingをcapturesし、calledされたときに以下のstepsをatomicallyに実行するnew read-modify-write modification functionとする:
    1. newBytesを返す。
  2. AtomicReadModifyWrite(ta, index, value, second)を返す。

25.4.8 Atomics.isLockFree ( size )

このfunctionは、呼び出されたときに以下のstepsを実行する:

  1. nを ? ToIntegerOrInfinity(size) とする。
  2. agentRecordsurrounding agentAgent Recordとする。
  3. n = 1なら、agentRecord.[[IsLockFree1]]を返す。
  4. n = 2なら、agentRecord.[[IsLockFree2]]を返す。
  5. n = 4なら、trueを返す。
  6. n = 8なら、agentRecord.[[IsLockFree8]]を返す。
  7. falseを返す。
Note

このfunctionはoptimization primitiveである。その直観は、size n bytesのdatum上のatomic primitive(compareExchangeloadstoreaddsubandorxor、またはexchange)のatomic stepが、surrounding agentがそのdatumをcomprisingするn bytesの外側でlockをacquiringすることなくperformedされるなら、Atomics.isLockFree(n)はtrueを返す、というものである。High-performance algorithmsは、critical sectionsにおいてlocksを使用するかatomic operationsを使用するかをdetermineするために、このfunctionを使用する。atomic primitiveがlock-freeでない場合、多くの場合、algorithmがown lockingをprovideする方がmore efficientである。

Atomics.isLockFree(4)は、すべてのknown relevant hardwareでsupportできるため、常にtrueを返す。これをassumeできることは、一般にprogramsをsimplifyする。

このfunctionによってreturnedされるvalueに関わらず、すべてのatomic operationsはatomicであることがguaranteedされる。例えば、それらはoperationの途中でvisible operationがtake placeすること(例:“tearing”)は決してない。

25.4.9 Atomics.load ( ta, index )

このfunctionは、呼び出されたときに以下のstepsを実行する:

  1. byteIndexInBufferを ? ValidateAtomicAccessOnIntegerTypedArray(ta, index) とする。
  2. RevalidateAtomicAccess(ta, byteIndexInBuffer)を実行する。
  3. bufferta.[[ViewedArrayBuffer]]とする。
  4. elementTypeTypedArrayElementType(ta)とする。
  5. GetValueFromBuffer(buffer, byteIndexInBuffer, elementType, true, seq-cst)を返す。

25.4.10 Atomics.notify ( ta, index, count )

この関数は、待機キュー内でスリープしているいくつかのエージェントに通知する。

呼び出されたとき、次の手順を実行する。

  1. taRecord を ? ValidateIntegerTypedArray(ta, true) とする。
  2. byteIndexInBuffer を ? ValidateAtomicAccess(taRecord, index) とする。
  3. countundefined である場合、
    1. count を +∞ に設定する。
  4. そうでなければ、
    1. intCount を ? ToIntegerOrInfinity(count) とする。
    2. countmax(intCount, 0) に設定する。
  5. bufferta.[[ViewedArrayBuffer]] とする。
  6. blockbuffer.[[ArrayBufferData]] とする。
  7. IsSharedArrayBuffer(buffer) が false である場合、+0𝔽 を返す。
  8. waiterListGetWaiterList(block, byteIndexInBuffer) とする。
  9. EnterCriticalSection(waiterList) を実行する。
  10. waitersRemoveWaiters(waiterList, count) とする。
  11. waiters の各要素 waiterRecord について、次を行う。
    1. NotifyWaiter(waiterList, waiterRecord) を実行する。
  12. LeaveCriticalSection(waiterList) を実行する。
  13. waitersCountwaiters 内の要素数とする。
  14. 𝔽(waitersCount) を返す。

25.4.11 Atomics.or ( ta, index, value )

この関数は、呼び出されたとき、次の手順を実行する。

  1. or を、パラメーター (xBytes, yBytes) を持ち、何もキャプチャせず、呼び出されたときに次の手順をアトミックに実行する、新しい読み取り-変更-書き込み変更関数とする。
    1. ByteListBitwiseOp(|, xBytes, yBytes) を返す。
  2. AtomicReadModifyWrite(ta, index, value, or) を返す。

25.4.12 Atomics.pause ( )

この関数は、値を待機している間プログラムがスピンループしていることを CPU に示すヒントを提供する。

呼び出されたとき、次の手順を実行する。

  1. ECMAScript 実装の実行環境が、現在実行中のコードがスピン待機ループ内にあることをオペレーティングシステムまたは CPU に通知することをサポートしている場合、その信号を送る。
  2. undefined を返す。
Note 1

このメソッドは、mutex 内の spinlock 高速パスなど、スピン待機ループを実装するプログラムが、値を待機している間スピンしていることを CPU に示すヒントを提供するために設計されている。これはタイミング以外に観測可能な動作を持たない。

実装は、基盤となるアーキテクチャのベストプラクティスがスピンループ内でそのような命令を推奨している場合、pause または yield 命令を実装することが期待される。例えば、Intel 最適化マニュアルpause 命令を推奨している。

実装には、一時停止する最大時間について、数十から数百ナノ秒程度の内部上限を持つことが推奨される。

Note 2

関数呼び出しのオーバーヘッドにより、最適化コンパイラーにおけるこのメソッドへのインライン化された呼び出しが、インライン化されていない呼び出しとは異なる時間だけ待機することは妥当である。

25.4.13 Atomics.store ( ta, index, value )

この関数は、呼び出されたとき、次の手順を実行する。

  1. byteIndexInBuffer を ? ValidateAtomicAccessOnIntegerTypedArray(ta, index) とする。
  2. ta.[[ContentType]]bigint である場合、coerced を ? ToBigInt(value) とする。
  3. そうでなければ、coerced𝔽(? ToIntegerOrInfinity(value)) とする。
  4. RevalidateAtomicAccess(ta, byteIndexInBuffer) を実行する。
  5. bufferta.[[ViewedArrayBuffer]] とする。
  6. elementTypeTypedArrayElementType(ta) とする。
  7. SetValueInBuffer(buffer, byteIndexInBuffer, elementType, coerced, true, seq-cst) を実行する。
  8. coerced を返す。

25.4.14 Atomics.sub ( ta, index, value )

この関数は、呼び出されたとき、次の手順を実行する。

  1. subtract を、パラメーター (xBytes, yBytes) を持ち、ta をキャプチャし、呼び出されたときに次の手順をアトミックに実行する、新しい読み取り-変更-書き込み変更関数とする。
    1. typeTypedArrayElementType(ta) とする。
    2. agentRecord を周囲のエージェントの Agent Record とする。
    3. isLittleEndianagentRecord.[[LittleEndian]] とする。
    4. xRawBytesToNumeric(type, xBytes, isLittleEndian) とする。
    5. yRawBytesToNumeric(type, yBytes, isLittleEndian) とする。
    6. x が Number である場合、
      1. differenceNumber::subtract(x, y) とする。
    7. そうでなければ、
      1. Assert: x は BigInt である。
      2. differenceBigInt::subtract(x, y) とする。
    8. differenceBytesNumericToRawBytes(type, difference, isLittleEndian) とする。
    9. Assert: differenceBytesxBytes、および yBytes は同じ数の要素を持つ。
    10. differenceBytes を返す。
  2. AtomicReadModifyWrite(ta, index, value, subtract) を返す。

25.4.15 Atomics.wait ( ta, index, value, timeout )

この関数は、周囲のエージェントを待機キューに入れ、通知されるか待機がタイムアウトするまでそのエージェントを一時停止し、それらの場合を区別する String を返す。

呼び出されたとき、次の手順を実行する。

  1. DoWait(sync, ta, index, value, timeout) を返す。

25.4.16 Atomics.waitAsync ( ta, index, value, timeout )

この関数は、呼び出し元エージェントが通知されるかタイムアウトに達したときに解決される Promise を返す。

呼び出されたとき、次の手順を実行する。

  1. DoWait(async, ta, index, value, timeout) を返す。

25.4.17 Atomics.xor ( ta, index, value )

この関数は、呼び出されたとき、次の手順を実行する。

  1. xor を、パラメーター (xBytes, yBytes) を持ち、何もキャプチャせず、呼び出されたときに次の手順をアトミックに実行する、新しい読み取り-変更-書き込み変更関数とする。
    1. ByteListBitwiseOp(^, xBytes, yBytes) を返す。
  2. AtomicReadModifyWrite(ta, index, value, xor) を返す。

25.4.18 Atomics [ %Symbol.toStringTag% ]

%Symbol.toStringTag% プロパティの初期値は String 値 "Atomics" である。

このプロパティは属性 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true } を持つ。

25.5 JSONオブジェクト

JSONオブジェクトは:

  • %JSON%である。
  • global object"JSON" propertyのinitial valueである。
  • ordinary objectである。
  • JSON textsをparseおよびconstructするために使用される、parseおよびstringifyという2つのfunctionsを含む。
  • valueが%Object.prototype%である[[Prototype]] internal slotを持つ。
  • [[Construct]] internal methodを持たない;new operatorでconstructorとして使用できない。
  • [[Call]] internal methodを持たない;functionとしてinvokeできない。

JSON Data Interchange FormatはECMA-404でdefinedされている。このspecificationで使用されるJSON interchange formatは、ECMA-404によってdescribedされるものとexactly sameである。JSON.parseおよびJSON.stringifyのconforming implementationsは、ECMA-404 specificationでdescribedされるexact interchange formatを、そのformatに対するdeletionsやextensionsなしにsupportしなければならない。

25.5.1 JSON.isRawJSON ( obj )

このfunctionは、呼び出されたときに以下のstepsを実行する:

  1. objがObjectであり、かつobj[[IsRawJSON]] internal slotを持つなら、trueを返す。
  2. falseを返す。

25.5.2 JSON.parse ( text [ , reviver ] )

このfunctionはJSON text(JSON形式のString)をparseし、ECMAScript language valueをproduceする。JSON formatは、ECMAScript literals、Array Initializers、およびObject Initializersのsyntaxにsimilarなsyntaxでliterals、arrays、およびobjectsをrepresentする。parsing後、JSON objectsはECMAScript objectsとしてrealizedされる。JSON arraysはECMAScript Array instancesとしてrealizedされる。JSON strings、numbers、booleans、およびnullはECMAScript Strings、Numbers、Booleans、およびnullとしてrealizedされる。

optional reviver parameterは、resultsをfilterおよびtransformできるfunctionである。parseによってproducedされる各valueについて、reviverは3つのarguments(associated property key、value、およびcontext object)でcalledされる。propertyがunmodifiedで、そのvalueがprimitiveである場合、provided context objectは、corresponding Parse Nodeのsource textを含む"source" propertyを持つ。callがundefinedを返す場合、propertyはdeletedされる。そうでなければ、propertyはreturn valueを使用するようredefinedされる。

  1. jsonStringを ? ToString(text) とする。
  2. parseResultを ? ParseJSON(jsonString) とする。
  3. unfilteredparseResult.[[Value]]とする。
  4. IsCallable(reviver)がfalseなら、unfilteredを返す。
  5. rootOrdinaryObjectCreate(%Object.prototype%)とする。
  6. rootNameをempty Stringとする。
  7. CreateDataPropertyOrThrow(root, rootName, unfiltered)を実行する。
  8. snapshotCreateJSONParseRecord(parseResult.[[ParseNode]], rootName, unfiltered)とする。
  9. InternalizeJSONProperty(root, rootName, reviver, snapshot)を返す。

このfunctionの"length" propertyは2𝔽である。

25.5.2.1 ParseJSON ( text )

The abstract operation ParseJSON takes argument text (a String) and returns either a normal completion containing a Record with fields [[ParseNode]] (a Parse Node) and [[Value]] (an ECMAScript language value), or a throw completion. It performs the following steps when called:

  1. StringToCodePoints(text)がECMA-404でspecifiedされるvalid JSON textでないなら、SyntaxError例外をthrowする。
  2. scriptString"("text、および");"string-concatenationとする。
  3. scriptParseText(scriptString, Script)とする。
  4. NOTE: 13.2.5.1でdefinedされるearly error rulesは、上記のParseTextのinvocationについてspecial handlingを持つ。
  5. Assert: scriptParse Nodeである。
  6. resultを ! Evaluation of script とする。
  7. NOTE: 13.2.5.6でdefinedされるPropertyDefinitionEvaluation semanticsは、上記のevaluationについてspecial handlingを持つ。
  8. Assert: resultはString、Number、Boolean、ArrayLiteralまたはObjectLiteralのいずれかによってdefinedされるObject、またはnullのいずれかである。
  9. Record { [[ParseNode]]: script, [[Value]]: result }を返す。

JSON.parseのconforming implementationがJSON grammarsをextendすることはpermittedされない。implementationがmodifiedまたはextended JSON interchange formatをsupportしたい場合、different parse functionをdefiningすることによってそうしなければならない。

Note 1

Valid JSON textはECMAScript PrimaryExpression syntaxのsubsetである。Step 1は、jsonStringがそのsubsetにconformsすることをverifyし、step 8はevaluationがappropriate typeのvalueを返すことをassertする。

しかし、ParseJSON中には13.2.5.6が異なってbehavesするため、same source textは、JSONとしてではなくPrimaryExpressionとしてevaluatedされた場合に異なるresultsをproduceできる。さらに、object literals内のduplicate "__proto__" propertiesに対するEarly Errorは、同様にParseJSON中にはapplyされないため、grammarにmatchingするにもかかわらず、ParseJSONにacceptedされるすべてのtextsがPrimaryExpressionとしてvalidであるわけではないことを意味する。

Note 2

object内にduplicate name Stringsがある場合、same keyに対するlexically preceding valuesはoverwrittenされる。

25.5.2.2 JSON Parse Record

JSON Parse Recordは、JSON textからparsedされたvalueのinitial stateをdescribeするために使用されるRecord valueである。

JSON Parse Recordsは、Table 76にlistedされるfieldsを持つ。

Table 76: JSON Parse Record Fields
フィールド名 意味
[[ParseNode]] a Parse Node context Parse Node
[[Key]] a property name [[Value]]がassociatedされるproperty name
[[Value]] an ECMAScript language value [[ParseNode]]のevaluationによってproducedされるvalue。
[[Elements]] a List of JSON Parse Records [[Value]]がArrayである場合、これは[[Value]]のelementsにcorrespondingするJSON Parse Recordsを含む。そうでなければ、これはempty Listである。
[[Entries]] a List of JSON Parse Records [[Value]]がnon-Array Objectである場合、これは[[Value]]のentriesにcorrespondingするJSON Parse Recordsを含む。そうでなければ、これはempty Listである。

25.5.2.3 CreateJSONParseRecord ( parseNode, key, value )

The abstract operation CreateJSONParseRecord takes arguments parseNode (a Parse Node), key (a property name), and value (an ECMAScript language value) and returns a JSON Parse Record. JSON textからparsedされたparseNodeと、そのevaluationによってproducedされたvalueをrecursivelyにcombineする。 It performs the following steps when called:

  1. typedValueNodeShallowestContainedJSONValue(parseNode)とする。
  2. Assert: typedValueNodeemptyでない。
  3. elementsをnew empty Listとする。
  4. entriesをnew empty Listとする。
  5. valueがObjectなら、
    1. isArrayを ! IsArray(value) とする。
    2. isArraytrueなら、
      1. Assert: typedValueNodeArrayLiteral Parse Nodeである。
      2. contentNodestypedValueNodeJSONArrayLiteralContentNodesとする。
      3. lengthcontentNodes内のelementsのnumberとする。
      4. valueLengthを ! LengthOfArrayLike(value) とする。
      5. Assert: valueLengthlengthである。
      6. indexを0とする。
      7. Repeat, while index < length,
        1. propertyNameを ! ToString(𝔽(index)) とする。
        2. elementParseRecordCreateJSONParseRecord(contentNodes[index], propertyName, ! Get(value, propertyName))とする。
        3. elementParseRecordelementsにappendする。
        4. indexindex + 1に設定する。
    3. そうでなければ、
      1. Assert: typedValueNodeObjectLiteral Parse Nodeである。
      2. propertyNodestypedValueNodePropertyDefinitionNodesとする。
      3. NOTE: valueはJSON textからproducedされ、modifiedされていないため、そのproperty keysはすべてStringsであり、exhaustively enumeratedされる。
      4. keysを ! EnumerableOwnProperties(value, key) とする。
      5. keysの各String propertyKeyについて、
        1. NOTE: JSON textがsingle objectについてsame nameを持つmultiple name/value pairs(例えば{"a":"lost","a":"kept"})をspecifyingする場合、resulting ECMAScript objectのcorresponding propertyのvalueは、そのnameを持つlast pairによってspecifiedされる。
        2. propertyDefinitionemptyとする。
        3. propertyNodesの各Parse Node propertyNodeについて、
          1. propertyNamepropertyNodePropNameとする。
          2. propertyNamepropertyKeyなら、propertyDefinitionpropertyNodeに設定する。
        4. Assert: propertyDefinition PropertyDefinition : PropertyName : AssignmentExpression である。
        5. propertyValueNodepropertyDefinitionAssignmentExpressionとする。
        6. entryParseRecordCreateJSONParseRecord(propertyValueNode, propertyKey, ! Get(value, propertyKey))とする。
        7. entryParseRecordentriesにappendする。
  6. そうでなければ、
    1. Assert: typedValueNodeArrayLiteral Parse NodeでもObjectLiteral Parse Nodeでもない。
  7. JSON Parse Record { [[ParseNode]]: typedValueNode, [[Key]]: key, [[Value]]: value, [[Elements]]: elements, [[Entries]]: entries }を返す。

25.5.2.4 InternalizeJSONProperty ( holder, name, reviver, parseRecord )

The abstract operation InternalizeJSONProperty takes arguments holder (an Object), name (a String), reviver (a function object), and parseRecord (a JSON Parse Record or empty) and returns either a normal completion containing an ECMAScript language value or a throw completion.

Note

このalgorithmは、[[Delete]]またはCreateDataPropertyのいずれかがfalseを返す場合でも、意図的にexceptionをthrowしない。

これは、呼び出されたときに以下のstepsを実行する:

  1. valueを ? Get(holder, name) とする。
  2. contextOrdinaryObjectCreate(%Object.prototype%)とする。
  3. parseRecordJSON Parse Recordであり、SameValue(parseRecord.[[Value]], value)がtrueなら、
    1. valueがObjectでないなら、
      1. parseNodeparseRecord.[[ParseNode]]とする。
      2. Assert: parseNodeArrayLiteral Parse NodeでもObjectLiteral Parse Nodeでもない。
      3. sourceTextparseNodeによってmatchedされるsource textとする。
      4. CreateDataPropertyOrThrow(context, "source", CodePointsToString(sourceText))を実行する。
    2. elementRecordsparseRecord.[[Elements]]とする。
    3. entryRecordsparseRecord.[[Entries]]とする。
  4. そうでなければ、
    1. elementRecordsをnew empty Listとする。
    2. entryRecordsをnew empty Listとする。
  5. valueがObjectなら、
    1. isArrayを ? IsArray(value) とする。
    2. isArraytrueなら、
      1. elementRecordsLengthelementRecords内のelementsのnumberとする。
      2. lengthを ? LengthOfArrayLike(value) とする。
      3. indexを0とする。
      4. Repeat, while index < length,
        1. propertyKeyを ! ToString(𝔽(index)) とする。
        2. index < elementRecordsLengthなら、elementRecordelementRecords[index]とする;そうでなければ、elementRecordemptyとする。
        3. newElementを ? InternalizeJSONProperty(value, propertyKey, reviver, elementRecord) とする。
        4. newElementundefinedなら、
          1. value.[[Delete]](propertyKey)を実行する。
        5. そうでなければ、
          1. CreateDataProperty(value, propertyKey, newElement)を実行する。
        6. indexindex + 1に設定する。
    3. そうでなければ、
      1. keysを ? EnumerableOwnProperties(value, key) とする。
      2. keysの各String propertyKeyについて、
        1. entryRecordsのelement entryであってentry.[[Key]]propertyKeyであるものが存在するなら、entryRecordentryとする;そうでなければ、entryRecordemptyとする。
        2. newElementを ? InternalizeJSONProperty(value, propertyKey, reviver, entryRecord) とする。
        3. newElementundefinedなら、
          1. value.[[Delete]](propertyKey)を実行する。
        4. そうでなければ、
          1. CreateDataProperty(value, propertyKey, newElement)を実行する。
  6. Call(reviver, holder, « name, value, context »)を返す。

25.5.2.5 Static Semantics: ShallowestContainedJSONValue ( root )

The abstract operation ShallowestContainedJSONValue takes argument root (a Parse Node) and returns a Parse Node or empty. rootをrootとするparse treeのbreadth-first searchをperformし、JSON valueにcorrespondingするnonterminalのinstanceであるfirst nodeを返す。または、そのようなnodeがない場合はemptyを返す。 It performs the following steps when called:

  1. activeFuncactive function objectとする。
  2. Assert: activeFuncJSON.parse built-in function objectである(JSON.parseを参照)。
  3. typesを« NullLiteral, BooleanLiteral, NumericLiteral, StringLiteral, ArrayLiteral, ObjectLiteral, UnaryExpression »とする。
  4. unaryExpremptyとする。
  5. queueを« root »とする。
  6. Repeat, while queue is not empty,
    1. candidatequeueのfirst elementとする。
    2. queueからfirst elementをremoveする。
    3. queuedChildrenfalseとする。
    4. typesの各nonterminal typeについて、
      1. candidatetypeのinstanceであるなら、
        1. NOTE: JSON grammarにおいて、number tokenはnegative valueをrepresentし得る。ECMAScriptでは、negationは、UnaryExpression-に続いてderived UnaryExpressionへparseするunary operationとしてrepresentedされる。
        2. typeUnaryExpressionなら、
          1. candidateのparentがUnaryExpression Parse Nodeでないなら、unaryExprcandidateに設定する。
        3. そうでなく、typeNumericLiteralなら、
          1. Assert: candidateunaryExpr内にcontainedされる。
          2. unaryExprを返す。
        4. そうでなければ、
          1. candidateを返す。
      2. queuedChildrenfalseであり、candidateがnonterminalのinstanceであり、かつcandidate Contains typetrueなら、
        1. childrenを、candidateの各child nodeをorder通りに含むListとする。
        2. queuequeuechildrenlist-concatenationに設定する。
        3. queuedChildrentrueに設定する。
  7. emptyを返す。

25.5.2.6 Static Semantics: JSONArrayLiteralContentNodes

The syntax-directed operation JSONArrayLiteralContentNodes takes no arguments and returns a List of Parse Nodes. It is defined piecewise over the following productions:

ArrayLiteral : [ Elisionopt ] [ ElementList ] [ ElementList , Elisionopt ]
  1. Assert: Elisionはpresentでない。
  2. ElementListがpresentでないなら、new empty Listを返す。
  3. ElementListJSONArrayLiteralContentNodesを返す。
ElementList : Elisionopt AssignmentExpression
  1. Assert: Elisionはpresentでない。
  2. « AssignmentExpression »を返す。
ElementList : ElementList , Elisionopt AssignmentExpression
  1. Assert: Elisionはpresentでない。
  2. elementsをderived ElementListJSONArrayLiteralContentNodesとする。
  3. elementsと« AssignmentExpression »のlist-concatenationを返す。
ElementList : Elisionopt SpreadElement ElementList , Elisionopt SpreadElement
  1. NOTE: ECMA-404でspecifiedされるJSON textはSpreadElementをincludeしない。
  2. Assert: このstepに到達することはない。

25.5.3 JSON.rawJSON ( text )

このfunctionは、string、number、boolean、またはnull valueのraw JSON textをrepresentするobjectを返す。

  1. jsonStringを ? ToString(text) とする。
  2. jsonStringがempty Stringなら、SyntaxError例外をthrowする。
  3. jsonStringのfirst code unitが、ASCII lowercase letter code unit(0x0061から0x007Aまで、inclusive)、ASCII digit code unit(0x0030から0x0039まで、inclusive)、0x0022 (QUOTATION MARK)、または0x002D (HYPHEN-MINUS)のいずれでもないなら、SyntaxError例外をthrowする。
  4. jsonStringのlast code unitが、ASCII lowercase letter code unit(0x0061から0x007Aまで、inclusive)、ASCII digit code unit(0x0030から0x0039まで、inclusive)、または0x0022 (QUOTATION MARK)のいずれでもないなら、SyntaxError例外をthrowする。
  5. parseResultを ? ParseJSON(jsonString) とする。
  6. Assert: parseResult.[[Value]]はString、Number、Boolean、またはnullのいずれかである。
  7. internalSlotsListを« [[IsRawJSON]] »とする。
  8. objOrdinaryObjectCreate(null, internalSlotsList)とする。
  9. CreateDataPropertyOrThrow(obj, "rawJSON", jsonString)を実行する。
  10. SetIntegrityLevel(obj, frozen)を実行する。
  11. objを返す。

25.5.4 JSON.stringify ( value [ , replacer [ , space ] ] )

このfunctionは、ECMAScript language valueをrepresentするUTF-16 encoded JSON formatのString、またはundefinedを返す。これは3つのparametersを取ることができる。value parameterはECMAScript language valueであり、通常はobjectまたはarrayであるが、String、Boolean、Number、またはnullでもあり得る。optional replacer parameterは、objectsおよびarraysがstringifiedされる方法をalterするfunction、またはstringifiedされるobject propertiesをselectするためのinclusion listとしてactsするStringsおよびNumbersのarrayのいずれかである。optional space parameterは、human readabilityをimproveするために、resultにwhite spaceをinjectedできるようにするStringまたはNumberである。

これは、呼び出されたときに以下のstepsを実行する:

  1. stackをnew empty Listとする。
  2. indentをempty Stringとする。
  3. propertyListundefinedとする。
  4. replacerFuncundefinedとする。
  5. replacerがObjectなら、
    1. IsCallable(replacer)がtrueなら、
      1. replacerFuncreplacerに設定する。
    2. そうでなければ、
      1. isArrayを ? IsArray(replacer) とする。
      2. isArraytrueなら、
        1. propertyListをnew empty Listに設定する。
        2. lengthを ? LengthOfArrayLike(replacer) とする。
        3. kを0とする。
        4. Repeat, while k < length,
          1. propertyKeyを ! ToString(𝔽(k)) とする。
          2. propertyValueを ? Get(replacer, propertyKey) とする。
          3. itemundefinedとする。
          4. propertyValueがStringなら、
            1. itempropertyValueに設定する。
          5. そうでなく、propertyValueがNumberなら、
            1. itemを ! ToString(propertyValue) に設定する。
          6. そうでなく、propertyValueがObjectなら、
            1. propertyValue[[StringData]]または[[NumberData]] internal slotを持つなら、itemを ? ToString(propertyValue) に設定する。
          7. itemundefinedでなく、かつpropertyListitemをcontainしないなら、
            1. itempropertyListにappendする。
          8. kk + 1に設定する。
  6. spaceがObjectなら、
    1. space[[NumberData]] internal slotを持つなら、
      1. spaceを ? ToNumber(space) に設定する。
    2. そうでなく、space[[StringData]] internal slotを持つなら、
      1. spaceを ? ToString(space) に設定する。
  7. spaceがNumberなら、
    1. spaceMVを ! ToIntegerOrInfinity(space) とする。
    2. spaceMVmin(10, spaceMV)に設定する。
    3. spaceMV < 1なら、gapをempty Stringとする;そうでなければ、gapをcode unit 0x0020 (SPACE)のspaceMV occurrencesを含むString valueとする。
  8. そうでなく、spaceがStringなら、
    1. spaceのlengthが10以下なら、gapspaceとする;そうでなければ、gapspaceの0から10までのsubstringとする。
  9. そうでなければ、
    1. gapをempty Stringとする。
  10. wrapperOrdinaryObjectCreate(%Object.prototype%)とする。
  11. CreateDataPropertyOrThrow(wrapper, the empty String, value)を実行する。
  12. stateJSON Serialization Record { [[ReplacerFunction]]: replacerFunc, [[Stack]]: stack, [[Indent]]: indent, [[Gap]]: gap, [[PropertyList]]: propertyList }とする。
  13. SerializeJSONProperty(state, the empty String, wrapper)を返す。

このfunctionの"length" propertyは3𝔽である。

Note 1

JSON structuresは任意のdepthまでnestedされることがallowedされるが、acyclicでなければならない。valueがcyclic structureである、またはそれを含む場合、このfunctionはTypeError例外をthrowしなければならない。これはstringifiedできないvalueの例である:

a = [];
a[0] = a;
my_text = JSON.stringify(a); // This must throw a TypeError.
Note 2

Symbolic primitive valuesは以下のようにrenderedされる:

  • null valueはJSON text内でString value "null"としてrenderedされる。
  • undefined valueはrenderedされない。
  • true valueはJSON text内でString value "true"としてrenderedされる。
  • false valueはJSON text内でString value "false"としてrenderedされる。
Note 3

String valuesはQUOTATION MARK (") code unitsでwrappedされる。code units "および\\ prefixesでescapedされる。Control characters code unitsはescape sequences \uHHHH、またはよりshorter formsである\b (BACKSPACE)、\f (FORM FEED)、\n (LINE FEED)、\r (CARRIAGE RETURN)、\t (CHARACTER TABULATION)にreplacedされる。

Note 4

Finite numbersはToString(number)をcallingしたかのようにstringifiedされる。NaNおよびInfinityはsignに関わらずString value "null"としてrepresentedされる。

Note 5

JSON representationを持たないvalues(undefinedやfunctionsなど)はStringをproduceしない。代わりにundefined valueをproduceする。arraysでは、これらのvaluesはString value "null"としてrepresentedされる。objectsでは、unrepresentable valueにより、そのpropertyはstringificationからexcludedされる。

Note 6

objectは、U+007B (LEFT CURLY BRACKET)に続いて、U+002C (COMMA)でseparatedされたzero or more propertiesが続き、U+007D (RIGHT CURLY BRACKET)でclosedされるものとしてrenderedされる。propertyは、property nameをrepresentするquoted String、U+003A (COLON)、そしてstringified property valueである。arrayは、opening U+005B (LEFT SQUARE BRACKET)に続いて、U+002C (COMMA)でseparatedされたzero or more valuesが続き、U+005D (RIGHT SQUARE BRACKET)でclosedされるものとしてrenderedされる。

25.5.4.1 JSON Serialization Record

JSON Serialization Recordは、JSON formatへのserializationをenableするために使用されるRecord valueである。

JSON Serialization Recordsは、Table 77にlistedされるfieldsを持つ。

Table 77: JSON Serialization Record Fields
フィールド名 意味
[[ReplacerFunction]] a function object or undefined object propertiesにreplacement valuesをsupplyできるfunction(JSON.stringifyのreplacer parameterから)。
[[PropertyList]] either a List of Strings or undefined non-array objectをserializingする際にincludeするpropertiesのnames(JSON.stringifyのreplacer parameterから)。
[[Gap]] a String indentationのunit(JSON.stringifyのspace parameterから)。
[[Stack]] a List of Objects serializedされるprocess中にあるnested objectsのset。cyclic structuresをdetectするためにusedされる。
[[Indent]] a String current indentation。

25.5.4.2 SerializeJSONProperty ( state, key, holder )

The abstract operation SerializeJSONProperty takes arguments state (a JSON Serialization Record), key (a String), and holder (an Object) and returns either a normal completion containing either a String or undefined, or a throw completion. It performs the following steps when called:

  1. valueを ? Get(holder, key) とする。
  2. valueがObjectまたはvalueがBigIntなら、
    1. toJSONを ? GetV(value, "toJSON") とする。
    2. IsCallable(toJSON)がtrueなら、
      1. valueを ? Call(toJSON, value, « key ») に設定する。
  3. state.[[ReplacerFunction]]undefinedでないなら、
    1. valueを ? Call(state.[[ReplacerFunction]], holder, « key, value ») に設定する。
  4. valueがObjectなら、
    1. value[[IsRawJSON]] internal slotを持つなら、
      1. rawJSONを ! Get(value, "rawJSON") とする。
      2. Assert: rawJSONはStringである。
      3. rawJSONを返す。
    2. value[[NumberData]] internal slotを持つなら、
      1. valueを ? ToNumber(value) に設定する。
    3. そうでなく、value[[StringData]] internal slotを持つなら、
      1. valueを ? ToString(value) に設定する。
    4. そうでなく、value[[BooleanData]] internal slotを持つなら、
      1. valuevalue.[[BooleanData]]に設定する。
    5. そうでなく、value[[BigIntData]] internal slotを持つなら、
      1. valuevalue.[[BigIntData]]に設定する。
  5. valuenullなら、"null"を返す。
  6. valuetrueなら、"true"を返す。
  7. valuefalseなら、"false"を返す。
  8. valueがStringなら、QuoteJSONString(value)を返す。
  9. valueがNumberなら、
    1. valuefiniteなら、! ToString(value)を返す。
    2. "null"を返す。
  10. valueがBigIntなら、TypeError例外をthrowする。
  11. valueがObjectであり、IsCallable(value)がfalseなら、
    1. isArrayを ? IsArray(value) とする。
    2. isArraytrueなら、
      1. SerializeJSONArray(state, value)を返す。
    3. SerializeJSONObject(state, value)を返す。
  12. undefinedを返す。

25.5.4.3 QuoteJSONString ( value )

The abstract operation QuoteJSONString takes argument value (a String) and returns a String. valueを0x0022 (QUOTATION MARK) code unitsでwrapし、その中のcertain other code unitsをescapeする。このoperationは、6.1.4でdescribedされるように、valueをUTF-16 encoded code pointsのsequenceとしてinterpretsする。 It performs the following steps when called:

  1. productを、code unit 0x0022 (QUOTATION MARK)のみからなるString valueとする。
  2. StringToCodePoints(value)の各code point codePointについて、
    1. codePointTable 78の“Code Point” columnにlistedされているなら、
      1. productを、productと、corresponding rowの“Escape Sequence” columnでspecifiedされるcodePointのescape sequenceとのstring-concatenationに設定する。
    2. そうでなく、codePointが0x0020 (SPACE)未満のnumeric valueを持つ、またはcodePointleading surrogateまたはtrailing surrogateとsame numeric valueを持つなら、
      1. unitを、numeric valueがcodePointのnumeric valueであるcode unitとする。
      2. productを、productUnicodeEscape(unit)のstring-concatenationに設定する。
    3. そうでなければ、
      1. productを、productUTF16EncodeCodePoint(codePoint)のstring-concatenationに設定する。
  3. productを、productとcode unit 0x0022 (QUOTATION MARK)のstring-concatenationに設定する。
  4. productを返す。
Table 78: JSON Single Character Escape Sequences
Code Point Unicode Character Name Escape Sequence
U+0008 BACKSPACE \b
U+0009 CHARACTER TABULATION \t
U+000A LINE FEED (LF) \n
U+000C FORM FEED (FF) \f
U+000D CARRIAGE RETURN (CR) \r
U+0022 QUOTATION MARK \"
U+005C REVERSE SOLIDUS \\

25.5.4.4 UnicodeEscape ( codeUnit )

The abstract operation UnicodeEscape takes argument codeUnit (a code unit) and returns a String. codeUnitをUnicode escape sequenceとしてrepresentsする。 It performs the following steps when called:

  1. ncodeUnitのnumeric valueとする。
  2. Assert: n ≤ 0xFFFFである。
  3. hexを、lowercase hexadecimal numberとしてformattedされたnのString representationとする。
  4. code unit 0x005C (REVERSE SOLIDUS)、"u"、およびStringPad(hex, 4, "0", start)のstring-concatenationを返す。

25.5.4.5 SerializeJSONObject ( state, value )

The abstract operation SerializeJSONObject takes arguments state (a JSON Serialization Record) and value (an Object) and returns either a normal completion containing a String or a throw completion. objectをserializesする。 It performs the following steps when called:

  1. state.[[Stack]]valueをcontainするなら、structureがcyclicalであるため、TypeError例外をthrowする。
  2. valuestate.[[Stack]]にappendする。
  3. stepBackstate.[[Indent]]とする。
  4. state.[[Indent]]state.[[Indent]]state.[[Gap]]string-concatenationに設定する。
  5. state.[[PropertyList]]undefinedでないなら、
    1. keysstate.[[PropertyList]]とする。
  6. そうでなければ、
    1. keysを ? EnumerableOwnProperties(value, key) とする。
  7. partialをnew empty Listとする。
  8. keysの各element propertyKeyについて、
    1. stringPを ? SerializeJSONProperty(state, propertyKey, value) とする。
    2. stringPundefinedでないなら、
      1. memberQuoteJSONString(propertyKey)とする。
      2. membermember":"string-concatenationに設定する。
      3. state.[[Gap]]がempty Stringでないなら、
        1. membermemberとcode unit 0x0020 (SPACE)のstring-concatenationに設定する。
      4. membermemberstringPstring-concatenationに設定する。
      5. memberpartialにappendする。
  9. partialがemptyなら、
    1. final"{}"とする。
  10. そうでなければ、
    1. state.[[Gap]]がempty Stringなら、
      1. propertiesを、partialのすべてのelement Stringsを、adjacent pair of Stringsごとにcode unit 0x002C (COMMA)でseparatedしてconcatenatingすることによってformedされるString valueとする。commaはfirst Stringの前にもlast Stringの後にもinsertedされない。
      2. final"{"properties、および"}"string-concatenationとする。
    2. そうでなければ、
      1. separatorをcode unit 0x002C (COMMA)、code unit 0x000A (LINE FEED)、およびstate.[[Indent]]string-concatenationとする。
      2. propertiesを、partialのすべてのelement Stringsを、adjacent pair of StringsごとにseparatorでseparatedしてconcatenatingすることによってformedされるString valueとする。separator Stringはfirst Stringの前にもlast Stringの後にもinsertedされない。
      3. final"{"、code unit 0x000A (LINE FEED)、state.[[Indent]]properties、code unit 0x000A (LINE FEED)、stepBack、および"}"string-concatenationとする。
  11. state.[[Stack]]のlast elementをremoveする。
  12. state.[[Indent]]stepBackに設定する。
  13. finalを返す。

25.5.4.6 SerializeJSONArray ( state, value )

The abstract operation SerializeJSONArray takes arguments state (a JSON Serialization Record) and value (an Object) and returns either a normal completion containing a String or a throw completion. arrayをserializesする。 It performs the following steps when called:

  1. state.[[Stack]]valueをcontainするなら、structureがcyclicalであるため、TypeError例外をthrowする。
  2. valuestate.[[Stack]]にappendする。
  3. stepBackstate.[[Indent]]とする。
  4. state.[[Indent]]state.[[Indent]]state.[[Gap]]string-concatenationに設定する。
  5. partialをnew empty Listとする。
  6. lengthを ? LengthOfArrayLike(value) とする。
  7. indexを0とする。
  8. Repeat, while index < length,
    1. stringPを ? SerializeJSONProperty(state, ! ToString(𝔽(index)), value) とする。
    2. stringPundefinedなら、
      1. "null"partialにappendする。
    3. そうでなければ、
      1. stringPpartialにappendする。
    4. indexindex + 1に設定する。
  9. partialがemptyなら、
    1. final"[]"とする。
  10. そうでなければ、
    1. state.[[Gap]]がempty Stringなら、
      1. propertiesを、partialのすべてのelement Stringsを、adjacent pair of Stringsごとにcode unit 0x002C (COMMA)でseparatedしてconcatenatingすることによってformedされるString valueとする。commaはfirst Stringの前にもlast Stringの後にもinsertedされない。
      2. final"["properties、および"]"string-concatenationとする。
    2. そうでなければ、
      1. separatorをcode unit 0x002C (COMMA)、code unit 0x000A (LINE FEED)、およびstate.[[Indent]]string-concatenationとする。
      2. propertiesを、partialのすべてのelement Stringsを、adjacent pair of StringsごとにseparatorでseparatedしてconcatenatingすることによってformedされるString valueとする。separator Stringはfirst Stringの前にもlast Stringの後にもinsertedされない。
      3. final"["、code unit 0x000A (LINE FEED)、state.[[Indent]]properties、code unit 0x000A (LINE FEED)、stepBack、および"]"string-concatenationとする。
  11. state.[[Stack]]のlast elementをremoveする。
  12. state.[[Indent]]stepBackに設定する。
  13. finalを返す。
Note

arraysのrepresentationは、+0𝔽(inclusive)からarray.length(exclusive)までのinterval内のelementsのみをincludeする。keysがarray indicesでないpropertiesはstringificationからexcludedされる。arrayは、opening LEFT SQUARE BRACKET、COMMAでseparatedされたelements、およびclosing RIGHT SQUARE BRACKETとしてstringifiedされる。

25.5.5 JSON [ %Symbol.toStringTag% ]

%Symbol.toStringTag% propertyのinitial valueはString value "JSON"である。

このpropertyはattributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }を持つ。