Draft ECMA-262 / June 25, 2026

ECMAScript® 2027 言語仕様

この仕様について

https://tc39.es/ecma262/ にある文書は、最も正確で最新のECMAScript仕様です。これは、最新の年次スナップショットの内容に加えて、完了した提案 — すなわち、提案プロセスにおいてStage 4に到達し、したがって複数の実装で実装され、次の年次スナップショットに含まれるもの — を含みます。過去のスナップショットは https://ecma-international.org/publications-and-standards/standards/ecma-262/ で入手できます。

この文書は、単一ページおよび複数ページとして利用できます。

この仕様への貢献

この仕様は、ECMAScriptコミュニティの助けを借りてGitHub上で開発されています。この仕様の開発に貢献する方法はいくつかあります:

この文書がどのように作成されるかについての詳細は、奥付を参照してください。

導入

このEcma標準は、ECMAScript 2027言語を定義します。これはECMAScript言語仕様の第18版です。ECMAScriptは、いくつかの起源となる技術に基づいており、最もよく知られているものはJavaScript(Netscape)とJScript(Microsoft)です。この言語はNetscapeのBrendan Eichによって発明され、同社のNavigator 2.0ブラウザーで初めて登場しました。Webブラウザーに組み込まれた言語として最もよく知られていますが、サーバーや組み込みアプリケーションを含むブラウザー外での利用にも広く採用され、世界で最も広く使われている汎用プログラミング言語の一つへと成長しました。

ECMAScript言語仕様の開発は1996年11月に始まりました。このEcma標準の第1版は、1997年6月のEcma総会で採択されました。

そのEcma標準は、ファストトラック手続きに基づく採択のためISO/IEC JTC 1に提出され、1998年4月に国際標準ISO/IEC 16262として承認されました。1998年6月のEcma総会は、ISO/IEC 16262との完全な整合性を維持するため、ECMA-262の第2版を承認しました。第1版と第2版の間の変更は編集上の性質のものです。

標準の第3版では、強力な正規表現、より優れた文字列処理、新しい制御文、try/catch例外処理、エラーのより厳密な定義、数値出力の書式化、および将来の言語の成長を見越した小さな変更が導入されました。ECMAScript標準の第3版は1999年12月のEcma総会で採択され、2002年6月にISO/IEC 16262:2002として発行されました。

第3版の発行後、ECMAScriptは、ほぼすべてのWebブラウザーでサポートされるプログラミング言語となったWorld Wide Webと連動して大規模に普及しました。ECMAScriptの第4版を開発するために重要な作業が行われました。しかし、その作業は完了せず、ECMAScriptの第4版として発行されることもありませんでしたが、その一部は第6版の開発に組み込まれました。

ECMAScriptの第5版(ECMA-262第5th版として発行)は、ブラウザー実装の間で一般的になっていた言語仕様の事実上の解釈を明文化し、第3版の発行以降に登場した新機能のサポートを追加しました。そのような機能には、アクセサープロパティ、オブジェクトの反射的な作成と検査、プロパティ属性のプログラムによる制御、追加の配列操作関数、JSONオブジェクトエンコーディング形式のサポート、強化されたエラーチェックとプログラムセキュリティを提供するstrict modeが含まれます。第5版は2009年12月のEcma総会で採択されました。

第5版は、ファストトラック手続きに基づく採択のためISO/IEC JTC 1に提出され、国際標準ISO/IEC 16262:2011として承認されました。ECMAScript標準の5.1版は軽微な訂正を取り込み、ISO/IEC 16262:2011と同一のテキストです。5.1版は2011年6月のEcma総会で採択されました。

第6版の集中的な開発は、第5版が発行に向けて準備されていた2009年に始まりました。しかし、その前には、1999年の第3版の発行に遡る重要な実験と、言語拡張の設計作業が行われていました。非常に現実的な意味で、第6版の完成は15年にわたる努力の集大成です。この版の目標には、大規模アプリケーション、ライブラリ作成、および他の言語のコンパイルターゲットとしてのECMAScriptの利用をよりよくサポートすることが含まれていました。その主な拡張には、モジュール、クラス宣言、レキシカルなブロックスコープ、イテレーターとジェネレーター、非同期プログラミングのためのpromise、分割代入パターン、proper tail callsが含まれていました。ECMAScriptの組み込みライブラリは、map、set、およびバイナリ数値の配列を含む追加のデータ抽象化、ならびに文字列と正規表現におけるUnicode補助文字の追加サポートを提供するよう拡張されました。組み込みもサブクラス化を通じて拡張可能にされました。第6版は、定期的で漸進的な言語およびライブラリの拡張の基盤を提供します。第6版は2015年6月の総会で採択されました。

ECMAScript 2016は、Ecma TC39の新しい年次リリース周期とオープンな開発プロセスの下でリリースされた最初のECMAScript版でした。ECMAScript 2015のソース文書から平文のソース文書が構築され、GitHub上で完全に進められるさらなる開発の基盤として機能しました。この標準の開発期間を通じて、何百ものpull requestとissueが提出され、何千ものバグ修正、編集上の修正、その他の改善を表していました。さらに、この取り組みを支援するため、Ecmarkup、Ecmarkdown、Grammarkdownを含む多数のソフトウェアツールが開発されました。ES2016には、新しいべき乗演算子のサポートも含まれ、Array.prototypeincludesという新しいメソッドが追加されました。

ECMAScript 2017では、Async Functions、Shared Memory、Atomicsが導入され、さらに小規模な言語およびライブラリの拡張、バグ修正、編集上の更新が行われました。Async functionsは、promiseを返す関数のための構文を提供することで、非同期プログラミング体験を改善します。Shared MemoryとAtomicsは、並列CPU上であっても明確に定義された実行順序を保証するアトミック操作を使用して、複数のエージェントからなるプログラムが通信できるようにする新しいメモリモデルを導入します。また、Objectに新しい静的メソッドとしてObject.valuesObject.entriesObject.getOwnPropertyDescriptorsが含まれました。

ECMAScript 2018では、async iterator protocolとasync generatorsによる非同期反復のサポートが導入されました。また、4つの新しい正規表現機能、すなわちdotAllフラグ、名前付きキャプチャグループ、Unicodeプロパティエスケープ、および後読みアサーションも含まれました。最後に、object restおよびspreadプロパティも含まれました。

ECMAScript 2019では、いくつかの新しい組み込み関数が導入されました。配列を平坦化するためのArray.prototype上のflatflatMapObject.entriesの戻り値を直接新しいObjectに変換するObject.fromEntries、および広く実装されていたものの非標準であったString.prototype.trimLeftおよびtrimRight組み込みの、よりよい名前の代替としてのString.prototype上のtrimStarttrimEndです。さらに、構文と意味論に対するいくつかの小さな更新も含まれました。更新された構文には、任意のcatch束縛パラメーター、およびJSONとの整合のために文字列リテラル内でU+2028(LINE SEPARATOR)とU+2029(PARAGRAPH SEPARATOR)を許可することが含まれました。その他の更新には、Array.prototype.sortが安定ソートであることを要求すること、JSON.stringifyが入力に関係なく整形式UTF-8を返すことを要求すること、およびFunction.prototype.toStringが対応する元のソーステキストまたは標準のプレースホルダーのいずれかを返すことを要求することで明確化することが含まれました。

ECMAScript 2020、第11th版では、globalな正規表現によって生成されるすべてのmatchオブジェクトに対するiteratorを生成する、StringsのためのmatchAllメソッド、動的なspecifierでModulesを非同期にimportする構文であるimport()、任意精度整数を扱うための新しい数値プリミティブであるBigInt、短絡しない新しいPromiseコンビネーターであるPromise.allSettled、globalなthis値にアクセスする普遍的な方法であるglobalThis、modules内で使用するための専用構文export * as ns from 'module'for-in列挙順序の標準化の拡大、Module内で利用可能で、そのModuleに関する文脈情報を含み得るhost-populated objectであるimport.metaが導入され、さらに“nullish”な値(undefinedまたはnull)を扱う作業を改善する2つの新しい構文機能、すなわち値選択演算子であるnullish coalescingと、アクセス/呼び出し対象の値がnullishである場合に短絡するプロパティアクセスおよび関数呼び出し演算子であるoptional chainingが追加されました。

ECMAScript 2021、第12th版では、StringsのためのreplaceAllメソッド、入力値がfulfilledになったときに短絡するPromiseコンビネーターであるPromise.any、複数のエラーを一度に表すための新しいError型であるAggregateError、論理代入演算子(??=&&=||=)、対象オブジェクトをガベージコレクションから保持することなく参照するためのWeakRef、対象オブジェクトがガベージコレクトされたときに実行されるcleanup操作の登録と登録解除を管理するFinalizationRegistry、数値リテラルの区切り文字(1_000)が導入され、またArray.prototype.sortはより精密にされ、実装定義のソート順序となる場合の数が減らされました。

ECMAScript 2022、第13th版では、top-level awaitが導入され、moduleのトップレベルでそのキーワードを使用できるようになりました。新しいclass要素として、publicおよびprivateのinstance fields、publicおよびprivateのstatic fields、private instance methodsおよびaccessors、private static methodsおよびaccessors、classごとの評価初期化を行うためのclass内のstatic blocks、オブジェクト上のprivate fieldsの存在をテストするための#x in obj構文、matched substringsの開始および終了インデックスを提供する/dフラグによる正規表現match indices、エラーに因果関係の連鎖を記録するために使用できるErrorオブジェクト上のcauseプロパティ、相対インデックス指定を可能にするStrings、Arrays、TypedArraysのためのatメソッド、およびObject.prototype.hasOwnPropertyの便利な代替であるObject.hasOwnが導入されました。

ECMAScript 2023、第14th版では、Array.prototypeおよびTypedArray.prototype上のtoSortedtoReversedwithfindLastfindLastIndexメソッド、ならびにArray.prototype上のtoSplicedメソッドが導入されました。また、実行可能なECMAScriptファイルをより扱いやすくするため、ファイルの先頭における#!コメントのサポートが追加され、ほとんどのSymbolsをweak collectionsのキーとして使用できるようになりました。

ECMAScript 2024、第15th版では、ArrayBuffersおよびSharedArrayBuffersのサイズ変更と転送のための機能が追加されました。文字列の集合を扱うためのより高度な機能を持つRegExpsを作成する新しいRegExp /vフラグが追加され、Promisesを構築するための便利なメソッドであるPromise.withResolvers、データを集約するためのObject.groupByおよびMap.groupByメソッド、shared memoryの変更を非同期に待つためのAtomics.waitAsyncメソッド、および文字列が整形式Unicodeのみを含むかをチェックし保証するためのString.prototype.isWellFormedおよびString.prototype.toWellFormedメソッドが導入されました。

ECMAScript 2025、第16th版では、iteratorsを扱うための関連する静的およびprototypeメソッドを持つ新しいIterator globalが追加されました。Setsに対して一般的な操作を実行するためのSet.prototype上のメソッドが追加され、JSON modulesをimportするサポート、およびimported modulesの属性を宣言する構文が追加されました。文字列を正規表現内で安全に使用できるようエスケープするためのRegExp.escapeメソッド、正規表現内でmodifier flagsをインラインで有効化および無効化する構文、Promiseを返す場合も返さない場合もある関数を呼び出し、結果が常にPromiseになることを保証するPromise.tryメソッド、ならびに新しいFloat16Array TypedArray kindと、関連するDataView.prototype.getFloat16DataView.prototype.setFloat16Math.f16roundメソッドが追加されました。

ECMAScript 2026、第17th版では、大きさの異なるNumbersのiterableを、精度損失を最小化しながら合計するためのMath.sumPreciseiteratorsを連結するためのIterator.concatasync iterablesおよびその他のasync sourcesからArraysを構築するためのArray.fromAsync、error objectsを識別するためのError.isError、keyがまだ存在しない場合に取得時に使用するdefault valueを提供するためのMap.prototypeおよびWeakMap.prototype上のメソッド、16進数およびbase64でエンコードされたバイナリデータのStringsとの変換を行うためのUint8Array上のメソッド、JSON sourceの一致したsegmentにアクセスするためのJSON.parse reviversへのパラメーター、およびprimitive valuesに対するJSON.stringify出力を細かく制御するためのJSON.rawJSONが追加されました。

多くの組織を代表する数十人の個人が、Ecma TC39内で、この版および以前の版の開発に非常に重要な貢献をしてきました。さらに、TC39のECMAScriptへの取り組みを支援する活発なコミュニティが生まれました。このコミュニティは、多数のdraftをレビューし、何千ものbug reportを提出し、実装実験を行い、test suitesに貢献し、世界中のdeveloperコミュニティにECMAScriptについて教育してきました。残念ながら、この取り組みに貢献したすべての人および組織を特定して謝意を示すことは不可能です。

Allen Wirfs-Brock
ECMA-262、第6th版、Project Editor

Brian Terlson
ECMA-262、第7th版から第10th版まで、Project Editor

Jordan Harband
ECMA-262、第10th版から第12th版まで、Project Editor

Kevin Gibbons
ECMA-262、第12th版から第17th版まで、Project Editor

Shu-yu Guo
ECMA-262、第12th版から第18th版まで、Project Editor

Michael Ficarra
ECMA-262、第12th版から第18th版まで、Project Editor

Richard Gibson
ECMA-262、第18th版、Project Editor

Ron Buckton
ECMA-262、第18th版、Project Editor

Nicolò Ribaudo
ECMA-262、第18th版、Project Editor

Linus Groh
ECMA-262、第18th版、Project Editor

1 適用範囲

この標準は、汎用プログラミング言語ECMAScript 2027を定義します。

2 適合性

ECMAScriptの適合実装は、この仕様に記述されるすべての型、値、オブジェクト、プロパティ、関数、およびプログラムの構文と意味論を提供し、サポートしなければなりません。

ECMAScriptの適合実装は、Unicode StandardおよびISO/IEC 10646の最新バージョンに適合して、ソーステキスト入力を解釈しなければなりません。

異なる人間の言語および国で使用される言語的・文化的慣習に適応する必要のあるプログラムをサポートするアプリケーションプログラミングインターフェイス(API)を提供するECMAScriptの適合実装は、この仕様と互換性のあるECMA-402の最新版で定義されるインターフェイスを実装しなければなりません。

ECMAScriptの適合実装は、この仕様に記述されるものを超えて、追加の型、値、オブジェクト、プロパティ、および関数を提供しても構いません。特に、ECMAScriptの適合実装は、この仕様に記述されるオブジェクトについて、この仕様に記述されていないプロパティ、およびそれらのプロパティの値を提供しても構いません。

ECMAScriptの適合実装は、この仕様に記述されていないプログラムおよび正規表現の構文をサポートしても構いません。特に、ECMAScriptの適合実装は、この仕様の副節12.7.2で示される任意の“future reserved words”を使用するプログラム構文をサポートしても構いません。

ECMAScriptの適合実装は、副節17.1でForbidden Extensionとして列挙されるいかなる拡張も実装してはなりません。

ECMAScriptの適合実装は、implementation-definedimplementation-approximated、またはhost-definedではないいかなる機能も再定義してはなりません。

ECMAScriptの適合実装は、別途示されない限り、Normative Optional副節を実装するか実装しないかを選択しても構いません。Web browsersは一般に、すべてのnormative optional副節を実装することが要求されます。(Annex Bを参照してください。)何らかのNormative Optionalな振る舞いが実装される場合、そのNormative Optional clauseに含まれるすべての振る舞いが実装されなければなりません。Normative Optional clauseは、この仕様では下に示すように、色付きのボックス内の“Normative Optional”という語で示されます。

2.1 Normative Optional Clause Headingの例

clause内容の例。

ECMAScriptの適合実装は、Normative Optionalとしてもマークされている場合を除き、Legacy副節を実装しなければなりません。Legacy副節内で指定されるすべての言語機能および振る舞いは、1つ以上の望ましくない特性を持ちます。しかし、既存のアプリケーションにおける継続的な使用により、この仕様からそれらを削除することは妨げられています。これらの機能は、ECMAScript言語の中核部分とは見なされません。プログラマーは、新しいECMAScriptコードを書く際に、これらの機能および振る舞いを使用したり、それらの存在を仮定したりするべきではありません。

2.2 Legacy Clause Headingの例

clause内容の例。

2.3 Legacy Normative Optional Clause Headingの例

clause内容の例。

3 規範的参照

以下の参照文書は、この文書の適用に不可欠です。日付付き参照については、引用された版のみが適用されます。日付なし参照については、参照文書の最新版(すべての修正を含む)が適用されます。

IEEE 754-2019, IEEE Standard for Floating-Point Arithmetic.

The Unicode Standard.
https://unicode.org/versions/latest

ISO/IEC 10646, Information Technology — Universal Multiple-Octet Coded Character Set (UCS) plus Amendment 1:2005, Amendment 2:2006, Amendment 3:2008, Amendment 4:2008, and additional amendments and corrigenda, or successor.

ECMA-402, ECMAScript Internationalization API Specification, specifically the annual edition corresponding to this edition of this specification.
https://www.ecma-international.org/publications-and-standards/standards/ecma-402/

ECMA-404, The JSON Data Interchange Format.
https://www.ecma-international.org/publications-and-standards/standards/ecma-404/

4 概要

この節は、ECMAScript言語の非規範的な概要を含みます。

ECMAScriptは、ホスト環境内で計算を実行し、計算上のオブジェクトを操作するためのオブジェクト指向プログラミング言語です。ここで定義されるECMAScriptは、計算上自足することを意図していません。実際、この仕様には外部データの入力や計算結果の出力に関する規定はありません。その代わり、ECMAScriptプログラムの計算環境は、この仕様で記述されるオブジェクトやその他の機能だけでなく、ある種の環境固有オブジェクトも提供することが期待されます。それらの記述および振る舞いは、この仕様の範囲外ですが、それらがECMAScriptプログラムからアクセス可能な特定のプロパティや呼び出し可能な特定の関数を提供し得ることを示す場合を除きます。

ECMAScriptはもともとスクリプト言語として使用されるよう設計されましたが、汎用プログラミング言語として広く使用されるようになりました。スクリプト言語とは、既存のシステムの機能を操作、カスタマイズ、および自動化するために使用されるプログラミング言語です。そのようなシステムでは、有用な機能がすでにユーザーインターフェイスを通じて利用可能であり、スクリプト言語はその機能をプログラム制御に公開するための仕組みです。このようにして、既存のシステムはオブジェクトと機能のホスト環境を提供すると言われ、それがスクリプト言語の能力を完成させます。スクリプト言語は、専門家および非専門家のプログラマーの双方によって使用されることを意図しています。

ECMAScriptはもともと、ブラウザー内のWebページを活性化し、Webベースのクライアントサーバーアーキテクチャの一部としてサーバー計算を実行する仕組みを提供する、Webスクリプト言語として設計されました。ECMAScriptは現在、さまざまなホスト環境に中核的なスクリプト機能を提供するために使用されています。したがって、中核言語は、特定のホスト環境から切り離してこの文書で規定されます。

ECMAScriptの使用は単純なスクリプティングを超え、現在では多くの異なる環境と規模におけるプログラミング作業の全範囲に使用されています。ECMAScriptの使用が拡大するにつれて、それが提供する特徴や機能も拡大してきました。ECMAScriptは現在、十分な機能を備えた汎用プログラミング言語です。

4.1 Webスクリプティング

Webブラウザーは、クライアント側計算のためのECMAScriptホスト環境を提供します。これには、たとえば、ウィンドウ、メニュー、ポップアップ、ダイアログボックス、テキスト領域、アンカー、フレーム、履歴、Cookie、および入出力を表すオブジェクトが含まれます。さらに、ホスト環境は、フォーカスの変更、ページおよび画像の読み込み、アンロード、エラーおよび中断、選択、フォーム送信、およびマウス操作などのイベントにスクリプトコードを結び付ける手段を提供します。スクリプトコードはHTML内に現れ、表示されるページはユーザーインターフェイス要素と固定および計算されたテキストと画像の組み合わせです。スクリプトコードはユーザー操作に反応し、メインプログラムは不要です。

Webサーバーは、サーバー側計算のための異なるホスト環境を提供します。これには、リクエスト、クライアント、およびファイルを表すオブジェクト、ならびにデータをロックして共有する仕組みが含まれます。ブラウザー側とサーバー側のスクリプティングを組み合わせて使用することで、Webベースのアプリケーションにカスタマイズされたユーザーインターフェイスを提供しながら、クライアントとサーバーの間で計算を分散することが可能です。

ECMAScriptをサポートする各Webブラウザーおよびサーバーは、それぞれ独自のホスト環境を提供し、ECMAScript実行環境を完成させます。

4.2 ホストと実装

ECMAScriptをホスト環境に統合することを助けるため、この仕様は特定の機能(例:抽象操作)の定義を、全体または一部において、この仕様の外部のソースに委ねます。編集上、この仕様は以下の種類の委譲を区別します。

実装とは、Annex Dに列挙される機能、またはimplementation-definedあるいはimplementation-approximatedとしてマークされる機能をさらに定義する外部ソースです。非公式な用法では、実装は特定のWebブラウザーなどの具体的な人工物を指します。

implementation-definedな機能とは、さらなる限定なしに、その定義を外部ソースに委ねるものです。この仕様は特定の振る舞いについていかなる推奨も行わず、適合実装はこの仕様によって課される制約の範囲内で任意の振る舞いを自由に選択できます。

implementation-approximatedな機能とは、理想的な振る舞いを推奨しつつ、その定義を外部ソースに委ねるものです。適合実装はこの仕様によって課される制約の範囲内で任意の振る舞いを自由に選択できますが、その理想に近づくよう努力することが推奨されます。Math.expなどの一部の数学演算は、implementation-approximatedです。

ホストとは、Annex Dに列挙される機能をさらに定義する外部ソースですが、他のimplementation-definedまたはimplementation-approximatedな機能をさらに定義しないものです。非公式な用法では、ホストは、Annex Dを介して同じ方法でこの仕様とインターフェイスする、すべてのWebブラウザーの集合など、すべての実装の集合を指します。ホストは、WHATWG HTML(https://html.spec.whatwg.org/)などの外部仕様であることが多いです。言い換えれば、host-definedな機能は、多くの場合、外部仕様でさらに定義されます。

ホストフックとは、全体または一部が外部ソースによって定義される抽象操作です。すべてのホストフックはAnnex Dに列挙されなければなりません。ホストフックは少なくとも以下の要件に適合しなければなりません:

host-definedな機能とは、さらなる限定なしにその定義を外部ソースに委ね、Annex Dに列挙されるものです。ホストでない実装も、host-definedな機能の定義を提供しても構いません。

ホスト環境とは、すべてのhost-definedな機能についての定義の特定の選択です。ホスト環境は通常、グローバルオブジェクトのhost-definedなプロパティとして入力を取得し出力を提供できるオブジェクトまたは関数を含みます。

この仕様は、常に最も具体的な用語を使用するという編集上の慣例に従います。たとえば、ある機能がhost-definedである場合、それをimplementation-definedと呼ぶべきではありません。

ホストと実装の双方は、この中で定義される言語型、仕様型、抽象操作、文法生成、組み込みオブジェクト、および組み込みシンボルを介して、この仕様とインターフェイスしても構いません。

4.3 ECMAScriptの概要

以下はECMAScriptの非公式な概要です — 言語のすべての部分が記述されているわけではありません。この概要は、標準本体の一部ではありません。

ECMAScriptはオブジェクトベースです。基本的な言語機能およびホスト機能はオブジェクトによって提供され、ECMAScriptプログラムは通信し合うオブジェクトの集合です。ECMAScriptにおいて、オブジェクトは0個以上のプロパティの集合であり、それぞれのプロパティは、そのプロパティがどのように使用できるかを決定する属性を持ちます。たとえば、あるプロパティのWritable属性がfalseに設定されている場合、実行されたECMAScriptコードがそのプロパティに異なる値を代入しようとすると失敗します。プロパティは、他のオブジェクト、プリミティブ値、または関数を保持するコンテナーです。プリミティブ値は、次の組み込み型のいずれかのメンバーです:UndefinedNullBooleanNumberBigIntString、およびSymbol; オブジェクトは組み込み型Objectのメンバーです。そして関数は呼び出し可能なオブジェクトです。プロパティを介してオブジェクトに関連付けられた関数は、メソッドと呼ばれます。

ECMAScriptは、ECMAScriptエンティティの定義を補完する組み込みオブジェクトの集合を定義します。これらの組み込みオブジェクトには、グローバルオブジェクト、ObjectFunctionBooleanSymbol、およびさまざまなErrorオブジェクトを含む、言語のruntime semanticsに基本的なオブジェクト、MathNumberDateを含む数値を表し操作するオブジェクト、テキスト処理オブジェクトであるStringRegExpArrayおよび要素がすべて特定の数値データ表現を持つ9種類のTyped Arraysを含む値のindexed collectionsであるオブジェクト、MapおよびSetオブジェクトを含むkeyed collections、JSONオブジェクト、ArrayBufferSharedArrayBufferDataViewを含む構造化データをサポートするオブジェクト、generator functionsおよびPromiseオブジェクトを含む制御抽象化をサポートするオブジェクト、ならびにProxyReflectを含むreflectionオブジェクトが含まれます。

ECMAScriptはまた、一連の組み込み演算子を定義します。ECMAScript演算子には、さまざまな単項演算、乗法演算子、加法演算子、ビットシフト演算子、関係演算子、等価演算子、二項ビット演算子、二項論理演算子、代入演算子、およびカンマ演算子が含まれます。

大規模なECMAScriptプログラムはモジュールによってサポートされます。モジュールにより、プログラムを複数の文および宣言の列へ分割できます。各モジュールは、自身が使用する宣言のうち他のモジュールによって提供される必要があるもの、および自身の宣言のうち他のモジュールから使用可能なものを明示的に識別します。

ECMAScriptの構文は意図的にJava構文に似ています。ECMAScriptの構文は、使いやすいスクリプト言語として機能できるよう緩やかにされています。たとえば、変数はその型を宣言する必要がなく、プロパティにも型は関連付けられず、定義された関数はそれらへの呼び出しより前にテキスト上で宣言が現れる必要もありません。

4.3.1 オブジェクト

ECMAScriptにはclass定義の構文が含まれているものの、ECMAScriptオブジェクトは、C++、Smalltalk、Javaにおけるもののように根本的にclassベースではありません。その代わり、オブジェクトは、リテラル記法やコンストラクターなど、さまざまな方法で作成できます。コンストラクターはオブジェクトを作成し、その後、それらのプロパティに初期値を代入することで、その全部または一部を初期化するコードを実行します。各コンストラクターは、"prototype"という名前のプロパティを持つ関数であり、これはプロトタイプベースの継承および共有プロパティを実装するために使用されます。オブジェクトは、new式でコンストラクターを使用して作成されます。たとえば、new Date(2009, 11)は新しいDateオブジェクトを作成します。newを使用せずにコンストラクターを呼び出すと、コンストラクターに応じた結果になります。たとえば、Date()はオブジェクトではなく現在の日付と時刻の文字列表現を生成します。

コンストラクターによって作成されたすべてのオブジェクトは、そのコンストラクターの"prototype"プロパティの値への暗黙の参照(オブジェクトのプロトタイプと呼ばれます)を持ちます。さらに、プロトタイプはそのプロトタイプへの非nullの暗黙の参照を持つ場合があり、以下同様です。これはプロトタイプチェーンと呼ばれます。オブジェクト内のプロパティへの参照が行われると、その参照は、プロトタイプチェーン内でその名前のプロパティを含む最初のオブジェクト内のその名前のプロパティを指します。言い換えれば、まず直接言及されたオブジェクトがそのようなプロパティを持つか調べられます。そのオブジェクトが名前付きプロパティを含む場合、それが参照の対象となるプロパティです。そのオブジェクトが名前付きプロパティを含まない場合、そのオブジェクトのプロトタイプが次に調べられ、以下同様に進みます。

Figure 1: Object/Prototype Relationships
An image of lots of boxes and arrows.

classベースのオブジェクト指向言語では、一般に、状態はインスタンスによって担われ、メソッドはクラスによって担われ、継承は構造と振る舞いのみのものです。ECMAScriptでは、状態とメソッドはオブジェクトによって担われ、一方で構造、振る舞い、および状態はすべて継承されます。

自分自身では、プロトタイプが含む特定のプロパティを直接含まないすべてのオブジェクトは、そのプロパティとその値を共有します。図1はこれを示しています:

CFはコンストラクター(かつオブジェクト)です。new式を使用して5つのオブジェクトが作成されています:cf1cf2cf3cf4、およびcf5です。これらの各オブジェクトは、"q1"および"q2"という名前のプロパティを含みます。破線は暗黙のプロトタイプ関係を表します。したがって、たとえば、cf3のプロトタイプはCFpです。コンストラクターCFは、それ自体に"P1"および"P2"という名前の2つのプロパティを持ちますが、これらはCFpcf1cf2cf3cf4、またはcf5からは見えません。CFp内の"CFP1"という名前のプロパティは、cf1cf2cf3cf4、およびcf5によって共有されます(ただしCFによっては共有されません)。同様に、CFpの暗黙のプロトタイプチェーン内に見つかる、"q1""q2"、または"CFP1"という名前でない任意のプロパティも共有されます。CFCFpの間には暗黙のプロトタイプリンクがないことに注意してください。

ほとんどのclassベースのオブジェクト言語とは異なり、プロパティは値を代入することによって動的にオブジェクトへ追加できます。つまり、コンストラクターは、構築されるオブジェクトのすべてまたはいずれかのプロパティを命名したり、それらに値を代入したりする必要はありません。上の図では、CFp内のプロパティに新しい値を代入することにより、cf1cf2cf3cf4、およびcf5のための新しい共有プロパティを追加できます。

ECMAScriptオブジェクトは本質的にclassベースではありませんが、コンストラクター関数、プロトタイプオブジェクト、およびメソッドの共通パターンに基づくclass風の抽象化を定義することが便利な場合がよくあります。ECMAScriptの組み込みオブジェクト自体も、そのようなclass風のパターンに従います。ECMAScript 2015以降、ECMAScript言語には構文上のclass定義が含まれ、プログラマーは組み込みオブジェクトで使用される同じclass風抽象化パターンに適合するオブジェクトを簡潔に定義できます。

4.3.2 ECMAScriptのStrictバリアント

ECMAScript言語は、この言語の一部のユーザーが、言語で利用可能な一部の機能の使用を制限したいと望む可能性を認識しています。彼らは、セキュリティの利益のため、自分たちがエラーを起こしやすいと考える機能を避けるため、強化されたエラーチェックを得るため、またはその他の自ら選ぶ理由のために、そうするかもしれません。この可能性をサポートするため、ECMAScriptは言語のstrictバリアントを定義します。言語のstrictバリアントは、通常のECMAScript言語の特定の構文的および意味的機能を除外し、一部の機能の詳細な意味論を変更します。strictバリアントはまた、非strict形式の言語ではエラーとして指定されていない状況で、エラー例外をthrowすることによって報告されなければならない追加のエラー条件を指定します。

ECMAScriptのstrictバリアントは、一般に言語のstrict modeと呼ばれます。strict modeの選択、およびECMAScriptのstrict mode構文と意味論の使用は、11.2.2で記述されるように、個々のECMAScript source text unitのレベルで明示的に行われます。strict modeは構文的なsource text unitのレベルで選択されるため、strict modeはそのようなsource text unit内で局所的な効果を持つ制限のみを課します。strict modeは、複数のsource text unitにわたって一貫して動作しなければならないECMAScript意味論のいかなる側面も制限または変更しません。完全なECMAScriptプログラムは、strict modeおよびnon-strict modeのECMAScript source text unitの双方から構成されても構いません。この場合、strict modeは、strict mode source text unit内で定義されたコードを実際に実行するときにのみ適用されます。

この仕様に適合するため、ECMAScript実装は、この仕様で定義される完全で無制限なECMAScript言語とECMAScript言語のstrictバリアントの双方を実装しなければなりません。さらに、実装は、無制限およびstrict modeのsource text unitを単一の複合プログラムへ組み合わせることをサポートしなければなりません。

4.4 用語と定義

この文書の目的のため、以下の用語および定義が適用されます。

4.4.1 implementation-approximated

implementation-approximatedな機能は、全体または一部が外部ソースによって定義されますが、この仕様において推奨される理想的な振る舞いを持ちます

4.4.2 implementation-defined

implementation-definedな機能は、全体または一部が、この仕様に対する外部ソースによって定義されます

4.4.3 host-defined

implementation-definedと同じ

Note

編集上、節4.2を参照してください。

4.4.4 type

6で定義されるデータ値の集合

4.4.5 primitive value

6で定義されるUndefined、Null、Boolean、Number、BigInt、Symbol、またはStringのいずれかの型のメンバー

Note

primitive valueは、言語実装の最下位レベルで直接表現されるデータです。

4.4.6 object

Object型のメンバー

Note

オブジェクトはプロパティの集合であり、単一のプロトタイプオブジェクトを持ちます。プロトタイプはnullであっても構いません。

4.4.7 constructor

オブジェクトを作成し初期化するfunction object

Note

コンストラクターの"prototype"プロパティの値は、継承および共有プロパティを実装するために使用されるプロトタイプオブジェクトです。

4.4.8 prototype

他のオブジェクトに共有プロパティを提供するオブジェクト

Note

コンストラクターがオブジェクトを作成すると、そのオブジェクトはプロパティ参照を解決する目的で、コンストラクターの"prototype"プロパティを暗黙に参照します。コンストラクターの"prototype"プロパティは、プログラム式constructor.prototypeによって参照でき、オブジェクトのプロトタイプに追加されたプロパティは、継承を通じて、そのプロトタイプを共有するすべてのオブジェクトによって共有されます。あるいは、Object.create組み込み関数を使用して、明示的に指定されたプロトタイプを持つ新しいオブジェクトを作成することもできます。

4.4.9 ordinary object

すべてのオブジェクトがサポートしなければならないessential internal methodsについて、デフォルトの振る舞いを持つオブジェクト

4.4.10 exotic object

essential internal methodsの1つ以上について、デフォルトの振る舞いを持たないオブジェクト

Note

ordinary objectでない任意のオブジェクトはexotic objectです。

4.4.11 standard object

その意味論がこの仕様によって定義されるオブジェクト

4.4.12 built-in object

ECMAScript実装によって指定され提供されるオブジェクト

Note

標準built-in objectsはこの仕様で定義されます。ECMAScript実装は、追加の種類のbuilt-in objectsを指定し提供しても構いません。

4.4.13 undefined value

変数に値が代入されていないときに使用されるprimitive value

4.4.14 Undefined type

その唯一の値がundefined値である型

4.4.15 null value

任意のオブジェクト値の意図的な不在を表すprimitive value

4.4.16 Null type

その唯一の値がnull値である型

4.4.17 Boolean value

Boolean型のメンバー

Note

Boolean値はtruefalseの2つだけです。

4.4.18 Boolean type

primitive valuesであるtrueおよびfalseからなる型

4.4.19 Boolean object

標準組み込みBooleanコンストラクターのインスタンスであるObject型のメンバー

Note

Boolean objectは、new式でBooleanコンストラクターを使用し、引数としてBoolean値を供給することで作成されます。結果のオブジェクトは、その値がBoolean値であるinternal slotを持ちます。Boolean objectはBoolean値へ強制変換できます。

4.4.20 String value

0個以上の16ビット符号なし整数値の有限順序列であるprimitive value

Note

String valueはString型のメンバーです。列内の各整数値は通常、UTF-16テキストの単一の16ビット単位を表します。しかし、ECMAScriptは、それらが16ビット符号なし整数でなければならないことを除き、その値にいかなる制限や要件も課しません。

4.4.21 String type

すべての可能なString valuesの集合

4.4.22 String object

標準組み込みStringコンストラクターのインスタンスであるObject型のメンバー

Note

String objectは、new式でStringコンストラクターを使用し、引数としてString値を供給することで作成されます。結果のオブジェクトは、その値がString値であるinternal slotを持ちます。String objectは、Stringコンストラクターを関数として呼び出すことでString値へ強制変換できます(22.1.1.1)。

4.4.23 Number value

倍精度64ビットバイナリ形式のIEEE 754-2019値に対応するprimitive value

Note

Number valueはNumber型のメンバーであり、数の直接表現です。

4.4.24 Number type

NaN(“not a number”)、+∞𝔽(正の無限大)、および-∞𝔽(負の無限大)を含むすべての可能なNumber valuesの集合

4.4.25 Number object

標準組み込みNumberコンストラクターのインスタンスであるObject型のメンバー

Note

Number objectは、new式でNumberコンストラクターを使用し、引数としてNumber値を供給することで作成されます。結果のオブジェクトは、その値がNumber値であるinternal slotを持ちます。Number objectは、Numberコンストラクターを関数として呼び出すことでNumber値へ強制変換できます(21.1.1.1)。

4.4.26 Infinity

正の無限Number値であるNumber value

4.4.27 NaN

IEEE 754-2019 NaN(“not a number”)値であるNumber value

4.4.28 BigInt value

任意精度整数値に対応するprimitive value

4.4.29 BigInt type

すべての可能なBigInt valuesの集合

4.4.30 BigInt object

標準組み込みBigIntコンストラクターのインスタンスであるObject型のメンバー

4.4.31 Symbol value

一意で非StringのObject property keyを表すprimitive value

4.4.32 Symbol type

すべての可能なSymbol valuesの集合

4.4.33 Symbol object

標準組み込みSymbolコンストラクターのインスタンスであるObject型のメンバー

4.4.34 function

サブルーチンとして呼び出され得るObject型のメンバー

Note

そのプロパティに加えて、関数は呼び出されたときにどのように振る舞うかを決定する実行可能コードと状態を含みます。関数のコードはECMAScriptで書かれている場合も、そうでない場合もあります。

4.4.35 built-in function

関数であるbuilt-in object

Note

built-in functionsの例には、parseIntおよびMath.expが含まれます。ホストまたは実装は、この仕様に記述されていない追加のbuilt-in functionsを提供しても構いません。

4.4.36 built-in constructor

コンストラクターであるbuilt-in function

Note

built-in constructorsの例には、ObjectおよびFunctionが含まれます。ホストまたは実装は、この仕様に記述されていない追加のbuilt-in constructorsを提供しても構いません。

4.4.37 property

key(String値またはSymbol値のいずれか)と値を関連付けるオブジェクトの一部

Note

プロパティの形式によって、値はデータ値(primitive value、オブジェクト、またはfunction object)として直接表現される場合も、accessor functionsの対によって間接的に表現される場合もあります。

4.4.38 method

プロパティの値である関数

Note

関数がオブジェクトのメソッドとして呼び出されると、そのオブジェクトは関数にそのthis値として渡されます。

4.4.39 built-in method

built-in functionであるメソッド

Note

標準built-in methodsはこの仕様で定義されます。ホストまたは実装は、この仕様に記述されていない追加のbuilt-in methodsを提供しても構いません。

4.4.40 attribute

プロパティの何らかの特性を定義する内部値

4.4.41 own property

そのオブジェクトによって直接含まれるプロパティ

4.4.42 inherited property

own propertyではないが、そのオブジェクトのプロトタイプのプロパティ(ownまたはinheritedのいずれか)であるオブジェクトのプロパティ

4.5 この仕様の構成

この仕様の残りは、以下のように構成されます:

Clause 5は、この仕様全体で使用される記法上の慣例を定義します。

Clauses 6から10までは、ECMAScriptプログラムが動作する実行環境を定義します。

Clauses 11から17までは、実際のECMAScriptプログラミング言語を、その構文的エンコーディングおよびすべての言語機能の実行意味論を含めて定義します。

Clauses 18から28までは、ECMAScript標準ライブラリを定義します。それらは、ECMAScriptプログラムが実行される際に利用可能なすべての標準オブジェクトの定義を含みます。

Clause 29は、SharedArrayBuffer-backed memory上のアクセスおよびAtomicsオブジェクトのメソッドのメモリ整合性モデルを記述します。

5 記法上の慣例

5.1 構文文法と字句文法

5.1.1 文脈自由文法

文脈自由文法は、いくつかの生成から構成されます。各生成は、その左辺として非終端記号と呼ばれる抽象記号を持ち、その右辺として0個以上の非終端記号および終端記号の列を持ちます。各文法について、終端記号は指定されたアルファベットから取られます。

chain productionとは、右辺にちょうど1つの非終端記号と0個以上の終端記号を持つ生成です。

goal symbolと呼ばれる単一の区別された非終端記号からなる文から始めて、与えられた文脈自由文法は言語、すなわち、列内の任意の非終端を、その非終端を左辺とする生成の右辺で繰り返し置き換えることによって得られる可能性のある終端記号列の(おそらく無限の)集合を指定します。

5.1.2 字句文法とRegExp文法

ECMAScriptの字句文法は、clause 12に示されます。この文法は、11.1で定義されるSourceCharacterの規則に適合するUnicode符号位置を終端記号として持ちます。これは、goal symbol InputElementDivInputElementTemplateTailInputElementRegExpInputElementRegExpOrTemplateTail、またはInputElementHashbangOrRegExpから始まる生成の集合を定義し、そのような符号位置の列がどのように入力要素の列へ変換されるかを記述します。

white spaceおよびcomments以外の入力要素は、ECMAScriptの構文文法の終端記号を形成し、ECMAScript tokensと呼ばれます。これらのtokensは、ECMAScript言語のreserved words、identifiers、literals、およびpunctuatorsです。さらに、line terminatorsは、tokensとは見なされないものの、入力要素のストリームの一部にもなり、自動セミコロン挿入(12.10)の過程を導きます。単純なwhite spaceおよびsingle-line commentsは破棄され、構文文法の入力要素のストリームには現れません。MultiLineComment(すなわち、複数行にまたがるかどうかにかかわらず、/**/という形式のcomment)も、line terminatorを含まない場合は同様に単に破棄されます。しかし、MultiLineCommentが1個以上のline terminatorsを含む場合、それは単一のline terminatorで置き換えられ、そのline terminatorが構文文法の入力要素のストリームの一部になります。

ECMAScriptのRegExp文法は、22.2.1に示されます。この文法も、SourceCharacterによって定義される符号位置を終端記号として持ちます。これは、goal symbol Patternから始まる生成の集合を定義し、符号位置の列がどのように正規表現パターンへ変換されるかを記述します。

字句文法およびRegExp文法の生成は、区切り句読点として2つのコロン“::”を持つことで区別されます。字句文法とRegExp文法はいくつかの生成を共有します。

5.1.3 数値文字列文法

数値文字列文法は、7.1.4.1に現れます。これはSourceCharacterを終端記号として持ち、goal symbol StringNumericLiteralから始めてStringsを数値へ変換するために使用されます(これは数値リテラルの字句文法に似ていますが、それとは別個です)。

数値文字列文法の生成は、句読点として3つのコロン“:::”を持つことで区別され、source textの解析には決して使用されません。

5.1.4 構文文法

ECMAScriptの構文文法は、clauses 13から16までに示されます。この文法は、字句文法によって定義されるECMAScript tokensを終端記号として持ちます(5.1.2)。これは、2つの代替goal symbols ScriptおよびModuleから始まる生成の集合を定義し、tokensの列がどのようにECMAScriptプログラムの構文的に正しい独立コンポーネントを形成するかを記述します。

符号位置のストリームをECMAScript ScriptまたはModuleとして解析するとき、それはまず字句文法の反復適用によって入力要素のストリームへ変換されます。この入力要素のストリームは、その後、構文文法の単一適用によって解析されます。入力要素のストリーム内のtokensが、tokensを残すことなく、goal nonterminal(ScriptまたはModule)の単一のインスタンスとして解析できない場合、入力ストリームは構文的にエラーです。

解析が成功すると、それはparse tree、すなわち各ノードがParse Nodeである根付き木構造を構築します。各Parse Nodeは文法内の記号のインスタンスです。それは、その記号から導出できるsource textの範囲を表します。source text全体を表すparse treeのルートノードは、解析のgoal symbolのインスタンスです。Parse Nodeが非終端のインスタンスである場合、それは、その非終端を左辺とする何らかの生成のインスタンスでもあります。さらに、それは0個以上のchildrenを持ち、生成の右辺上の各記号に対して1つずつあります。各childは、対応する記号のインスタンスであるParse Nodeです。

新しいParse Nodesは、parserの各呼び出しごとにインスタンス化され、同一のsource textの解析であっても、解析間で再利用されることはありません。Parse Nodesは、それらがsource textの同じ範囲を表し、同じ文法記号のインスタンスであり、同じparser呼び出しから得られた場合に限り、同じParse Nodeと見なされます。

Note 1

同じStringを複数回解析すると、異なるParse Nodesが生じます。たとえば、次を考えてください:

let str = "1 + 1;";
eval(str);
eval(str);

evalへの各呼び出しは、strの値をECMAScript source textへ変換し、それ自身の別個のParse Nodesの木を作成する独立した解析を実行します。各解析は同じString値から導出されたsource textに対して動作するものの、それらの木は別個です。

Note 2
Parse Nodesは仕様上の人工物であり、実装は類似のデータ構造を使用する必要はありません。

構文文法の生成は、句読点として1つのコロン“:”だけを持つことで区別されます。

clauses 13から16までに提示される構文文法は、どのtoken列が正しいECMAScript ScriptまたはModuleとして受理されるかについての完全な説明ではありません。特定の追加のtoken列も受理されます。すなわち、特定の場所(line terminator文字の前など)にセミコロンが追加されていれば文法によって記述されるであろうものです。さらに、文法によって記述される特定のtoken列は、line terminator文字が特定の“扱いにくい”場所に現れる場合、受理可能とは見なされません。

特定の場合には、曖昧さを避けるため、構文文法は有効なECMAScript ScriptまたはModuleを形成しないtoken列を許す一般化された生成を使用します。たとえば、この技法はオブジェクトリテラルおよびオブジェクト分割代入パターンに使用されます。そのような場合、受理可能なtoken列をさらに制限する、より制約の強い補足文法が提供されます。通常、early error ruleは、特定の文脈で“p must cover an n”と述べます。ここでpはParse Node(一般化された生成のインスタンス)であり、nは補足文法の非終端です。これは以下を意味します:

  1. もともとpに一致したtokensの列が、ngoal symbolとして再度解析されます。nが文法パラメーターを取る場合、それらはpがもともと解析されたときに使用されたものと同じ値に設定されます。
  2. tokensの列が、tokensを残すことなく、nの単一のインスタンスとして解析できる場合:
    1. そのnのインスタンス(与えられたpに対して一意なParse Node)を、“pによってcoveredされるn”と呼びます。
    2. nおよびその導出生成に対するすべてのEarly Error rulesも、pによってcoveredされるnに適用されます。
  3. それ以外(解析が失敗した場合)は、early Syntax Errorです。

5.1.5 文法記法

5.1.5.1 終端記号

ECMAScript文法において、一部の終端記号はfixed-widthフォントで示されます。これらはsource textに書かれたとおり正確に現れるものです。この方法で指定されるすべての終端記号符号位置は、他のUnicode範囲の似た見た目の符号位置ではなく、Basic Latinブロックからの適切なUnicode符号位置として理解されます。終端記号内の符号位置は、\ UnicodeEscapeSequenceによって表現することはできません。

終端記号が個々のUnicode符号位置である文法(すなわち、字句文法、RegExp文法、および数値文字列文法)では、生成内に現れる複数のfixed-width符号位置の連続した並びは、独立した終端記号として書かれた同じ符号位置列の単純な省略形です。

たとえば、生成:

HexIntegerLiteral :: 0x HexDigits

は、次の省略形です:

HexIntegerLiteral :: 0 x HexDigits

対照的に、構文文法では、fixed-width符号位置の連続した並びは単一の終端記号です。

終端記号には、他に2つの形式があります:

  • 字句文法およびRegExp文法では、慣用的な印字表現を持たないUnicode符号位置は、代わりに“<ABBREV>”という形式で示されます。ここで“ABBREV”は、その符号位置または符号位置集合のためのニーモニックです。これらの形式は、Unicode Format-Control CharactersWhite Space、およびLine Terminatorsで定義されます。
  • 構文文法では、特定の終端記号(例:IdentifierNameおよびRegularExpressionLiteral)はイタリック体で示されます。これは、それらが字句文法内の同名の非終端を参照するためです。

5.1.5.2 非終端記号と生成

非終端記号はitalic体で示されます。非終端の定義(“production”とも呼ばれます)は、定義される非終端の名前の後に1つ以上のコロンを続けることで導入されます。(コロンの数は、その生成がどの文法に属するかを示します。)その後、非終端に対する1つ以上の代替右辺が続く行に示されます。たとえば、構文上の定義:

WhileStatement : while ( Expression ) Statement

は、非終端WhileStatementが、token while、左括弧token、Expression、右括弧token、Statementの順で構成されることを述べています。ExpressionおよびStatementの出現は、それ自体が非終端です。別の例として、構文上の定義:

ArgumentList : AssignmentExpression ArgumentList , AssignmentExpression

は、ArgumentListが単一のAssignmentExpressionを表す場合も、ArgumentListに続いてカンマ、その後にAssignmentExpressionが続くものを表す場合もあることを述べています。このArgumentListの定義は再帰的です。つまり、それ自身を用いて定義されています。その結果、ArgumentListは、カンマで区切られた任意の正の個数のargumentsを含むことができ、各argument expressionはAssignmentExpressionです。このような非終端の再帰的定義は一般的です。

5.1.5.3 任意記号

終端または非終端の後に現れることがある下付き接尾辞“opt”は、任意記号を示します。任意記号を含む代替は、実際には、任意要素を省略するものとそれを含むものの2つの右辺を指定します。これは、次が:

VariableDeclaration : BindingIdentifier Initializeropt

次の便利な省略形であることを意味します:

VariableDeclaration : BindingIdentifier BindingIdentifier Initializer

また、次が:

ForStatement : for ( LexicalDeclaration Expressionopt ; Expressionopt ) Statement

次の便利な省略形であることも意味します:

ForStatement : for ( LexicalDeclaration ; Expressionopt ) Statement for ( LexicalDeclaration Expression ; Expressionopt ) Statement

これはさらに次の省略形です:

ForStatement : for ( LexicalDeclaration ; ) Statement for ( LexicalDeclaration ; Expression ) Statement for ( LexicalDeclaration Expression ; ) Statement for ( LexicalDeclaration Expression ; Expression ) Statement

したがって、この例では、非終端ForStatementは実際には4つの代替右辺を持ちます。

5.1.5.4 文法パラメーター

生成は、その生成によって定義される非終端記号の接尾辞として現れることがある、“[parameters]”という形式の下付き注釈によってパラメーター化されても構いません。“parameters”は、単一の名前またはカンマ区切りの名前のリストのいずれかです。パラメーター化された生成は、パラメーター名のすべての組み合わせを定義する生成の集合の省略形であり、各パラメーター名にはアンダースコアが前置され、パラメーター化された非終端記号に追加されます。これは、次が:

StatementList[Return] : ReturnStatement ExpressionStatement

次の便利な省略形であることを意味します:

StatementList : ReturnStatement ExpressionStatement StatementList_Return : ReturnStatement ExpressionStatement

また、次が:

StatementList[Return, In] : ReturnStatement ExpressionStatement

次の省略形であることも意味します:

StatementList : ReturnStatement ExpressionStatement StatementList_Return : ReturnStatement ExpressionStatement StatementList_In : ReturnStatement ExpressionStatement StatementList_Return_In : ReturnStatement ExpressionStatement

複数のパラメーターは組み合わせ的な数の生成を生み出しますが、そのすべてが完全な文法内で必ずしも参照されるわけではありません。

生成の右辺上の非終端への参照もパラメーター化できます。たとえば:

StatementList : ReturnStatement ExpressionStatement[+In]

は、次のように言うことと等価です:

StatementList : ReturnStatement ExpressionStatement_In

また:

StatementList : ReturnStatement ExpressionStatement[~In]

は、次と等価です:

StatementList : ReturnStatement ExpressionStatement

非終端参照は、パラメーターリストと“opt”接尾辞の双方を持つことができます。たとえば:

VariableDeclaration : BindingIdentifier Initializer[+In]opt

は、次の省略形です:

VariableDeclaration : BindingIdentifier BindingIdentifier Initializer_In

右辺の非終端参照でパラメーター名に“?”を前置すると、そのパラメーター値は現在の生成の左辺記号への参照におけるそのパラメーター名の出現に依存します。たとえば:

VariableDeclaration[In] : BindingIdentifier Initializer[?In]

は、次の省略形です:

VariableDeclaration : BindingIdentifier Initializer VariableDeclaration_In : BindingIdentifier Initializer_In

右辺の代替が“[+parameter]”で前置されている場合、その代替は、生成の非終端記号を参照する際にその名前付きパラメーターが使用された場合にのみ利用可能です。右辺の代替が“[~parameter]”で前置されている場合、その代替は、生成の非終端記号を参照する際にその名前付きパラメーターが使用されなかった場合にのみ利用可能です。これは、次が:

StatementList[Return] : [+Return] ReturnStatement ExpressionStatement

次の省略形であることを意味します:

StatementList : ExpressionStatement StatementList_Return : ReturnStatement ExpressionStatement

また、次が:

StatementList[Return] : [~Return] ReturnStatement ExpressionStatement

次の省略形であることも意味します:

StatementList : ReturnStatement ExpressionStatement StatementList_Return : ExpressionStatement

5.1.5.5 one of

文法定義内でコロンの後に“one of”という語が続く場合、それは後続の行または複数行上の終端記号の各々が代替定義であることを意味します。たとえば、ECMAScriptの字句文法には次の生成が含まれます:

NonZeroDigit :: one of 1 2 3 4 5 6 7 8 9

これは単に次の便利な省略形です:

NonZeroDigit :: 1 2 3 4 5 6 7 8 9

5.1.5.6 [empty]

“[empty]”という句が生成の右辺として現れる場合、それはその生成の右辺が終端も非終端も含まないことを示します。

5.1.5.7 先読み制約

“[lookahead = seq]”という句が生成の右辺に現れる場合、それは直後に続く入力token列のprefixがtoken列seqである場合にのみ、その生成を使用できることを示します。同様に、“[lookahead ∈ set]”は、setがtoken列の有限の非空集合である場合、直後に続くtoken列のprefixがsetのいずれかの要素である場合にのみ、その生成を使用できることを示します。便宜上、その集合は非終端として書くこともでき、その場合、それはその非終端が展開され得るすべてのtoken列の集合を表します。その非終端が無限に多くの異なるtoken列へ展開され得る場合、それは編集上の誤りと見なされます。

これらの条件は否定できます。“[lookahead ≠ seq]”は、含まれる生成が、seqが直後に続く入力token列のprefixでない場合にのみ使用できることを示し、“[lookahead ∉ set]”は、setいずれの要素も直後に続くtoken列のprefixでない場合にのみ、その生成を使用できることを示します。

例として、次の定義が与えられた場合:

DecimalDigit :: one of 0 1 2 3 4 5 6 7 8 9 DecimalDigits :: DecimalDigit DecimalDigits DecimalDigit

この定義:

LookaheadExample :: n [lookahead ∉ { 1, 3, 5, 7, 9 }] DecimalDigits DecimalDigit [lookahead ∉ DecimalDigit]

は、文字nに続いて1個以上の10進数字があり、その最初のものが偶数であるもの、または、別の10進数字が後続しない10進数字のいずれかに一致します。

これらの句が構文文法で使用される場合、後続のtokensを決定するには後の位置でどの字句goal symbolを使用するかを知る必要があるため、直後に続くtoken列を曖昧さなく識別できない場合があることに注意してください。そのため、これらが構文文法で使用される場合、使用する字句goal symbolsの選択によってseqが結果のtoken列のprefixであるかどうかが変わり得るならば、token列seqが先読み制約内(列集合の一部としての場合を含む)に現れることは編集上の誤りと見なされます。

5.1.5.8 [no LineTerminator here]

“[no LineTerminator here]”という句が構文文法の生成の右辺に現れる場合、それはその生成が制限された生成であることを示します。すなわち、示された位置で入力ストリーム内にLineTerminatorが発生する場合、その生成を使用してはなりません。たとえば、生成:

ThrowStatement : throw [no LineTerminator here] Expression ;

は、script内でthrow tokenとExpressionの間にLineTerminatorが発生する場合、その生成を使用してはならないことを示します。

LineTerminatorの存在が制限された生成によって禁止されていない限り、入力要素のストリーム内で任意の2つの連続するtokensの間に任意の数のLineTerminatorが現れても、scriptの構文上の受理可能性には影響しません。

5.1.5.9 but not

生成の右辺は、“but not”という句を使用し、その後に除外される展開を示すことで、特定の展開が許可されないことを指定できます。たとえば、生成:

Identifier :: IdentifierName but not ReservedWord

は、非終端Identifierが、IdentifierNameを置き換え得る任意の符号位置列であって、同じ符号位置列がReservedWordを置き換え得ないものによって置き換えられることを意味します。

5.1.5.10 説明句

最後に、いくつかの非終端記号は、すべての代替を列挙することが非実用的である場合に、sans-serif体の説明句によって記述されます:

SourceCharacter :: any Unicode code point

5.2 アルゴリズムの慣例

この仕様は、アルゴリズムのステップを指定するために番号付きリストをよく使用します。これらのアルゴリズムは、ECMAScript言語構造の要求される意味論を正確に指定するために使用されます。これらのアルゴリズムは、特定の実装技法の使用を暗示することを意図していません。実際には、与えられた機能を実装するために、より効率的なアルゴリズムが利用可能である場合があります。

アルゴリズムは、順序付きのカンマ区切りのalias名の列によって明示的にパラメーター化されても構いません。これらのalias名は、アルゴリズムステップ内でその位置に渡されたargumentを参照するために使用できます。任意パラメーターは、周囲の角括弧([ , name ])で示され、アルゴリズムステップ内では必須パラメーターと何ら異なりません。restパラメーターは、leading ellipsis(, ...name)で示され、パラメーターリストの末尾に現れても構いません。restパラメーターは、必須および任意パラメーターの後に提供されたすべてのargumentsをListへ取り込みます。そのような追加のargumentsがない場合、そのListは空です。

アルゴリズムステップは、順次的なサブステップへ細分化されても構いません。サブステップはインデントされ、それ自体もさらにインデントされたサブステップへ分割されても構いません。サブステップを識別するためにアウトライン番号付けの慣例が使用され、第一レベルのサブステップは小文字のアルファベット文字で、第二レベルのサブステップは小文字のローマ数字でラベル付けされます。3レベルを超える必要がある場合、これらの規則は繰り返され、第4レベルでは数値ラベルが使用されます。たとえば:

  1. トップレベルステップ
    1. サブステップ。
    2. サブステップ。
      1. サブサブステップ。
        1. サブサブサブステップ
          1. サブサブサブサブステップ
            1. サブサブサブサブサブステップ

ステップまたはサブステップは、そのサブステップを条件付ける“if”述語として書かれることがあります。この場合、サブステップは述語がtrueである場合にのみ適用されます。ステップまたはサブステップが“else”という語で始まる場合、それは同じレベルの直前の“if”述語ステップの否定である述語です。

ステップは、そのサブステップの反復適用を指定するために“For each”または“Repeat”で始まることがあります。

Assert:”で始まるステップは、そのアルゴリズムの不変条件を表明します。そのような表明は、そうでなければ暗黙であるアルゴリズム上の不変条件を明示するために使用されます。同様に、“NOTE:”で始まるステップは、近くのステップに関する関連する文脈を提供します。Assertion stepsおよびnote stepsは厳密に情報提供であり、追加の意味的要件を加えないため、実装によってチェックされる必要はありません。

アルゴリズムステップは、“Let x be someValue”という形式を使用して任意の値に名前付きaliasを宣言できます。これらのaliasは、xsomeValueの双方が同じ基礎データを参照し、どちらに対する変更も双方から見えるという点で参照のようなものです。この参照のような振る舞いを避けたいアルゴリズムステップは、右辺のコピーを明示的に作成するべきです:“Let x be a copy of someValue”はsomeValueの浅いコピーを作成します。

一度宣言されると、aliasは後続の任意のステップで参照できますが、aliasの宣言より前のステップから参照してはなりません。aliasは、“Set x to someOtherValue”という形式を使用して変更できます。

5.2.1 評価順序

複雑な式がアルゴリズムステップ内に現れる場合、それらは左から右、内側から外側の順序で評価されるものと理解されます。たとえば、ステップ

  1. A(B(), C.[[D]]) + E(F())を返す。

は次と等価です

  1. tmp1 をB()とする。
  2. tmp2 をC.[[D]]とする。
  3. tmp3 をA(tmp1, tmp2)とする。
  4. tmp4 をF()とする。
  5. tmp5 をE(tmp4)とする。
  6. tmp6tmp3 + tmp5とする。
  7. tmp6 を返す。

ここで、さまざまなtmpN aliasesは一時的なものであり、これらのステップ内でのみ見えます。

5.2.2 抽象操作

この仕様の複数の部分での使用を容易にするため、abstract operationsと呼ばれる一部のアルゴリズムは、名前付きで、パラメーター化された関数形式で書かれ、他のアルゴリズム内から名前によって参照できるようにされています。抽象操作は通常、OperationName(arg1, arg2)のような関数適用スタイルを使用して参照されます。一部の抽象操作は、class風の仕様抽象化のpolymorphically dispatched methodsとして扱われます。そのようなmethod風の抽象操作は通常、someValue.OperationName(arg1, arg2)のようなメソッド適用スタイルを使用して参照されます。

5.2.3 Syntax-Directed Operations

syntax-directed operationとは、名前付き操作であり、その定義はアルゴリズムから構成され、それぞれがECMAScript文法のいずれかの1つ以上の生成に関連付けられます。複数の代替定義を持つ生成は通常、各代替について別個のアルゴリズムを持ちます。アルゴリズムが文法生成に関連付けられる場合、それはその生成代替の終端および非終端記号を、あたかもアルゴリズムのパラメーターであるかのように参照できます。この方法で使用される場合、非終端記号は、source textを解析する際に一致した実際の代替定義を指します。文法生成またはそれから導出されたParse Nodeによって一致されたsource textとは、その一致に参加した最初の終端の開始から始まり、その一致に参加した最後の終端の終了で終わるsource textの部分です。

アルゴリズムが生成代替に関連付けられる場合、その代替は通常、“[ ]”文法注釈なしで示されます。そのような注釈は、その代替の構文認識にのみ影響するべきであり、その代替に関連付けられた意味論には影響しません。

Syntax-directed operationsは、以下のアルゴリズム内のステップ13、および4上の慣例を使用して、parse nodeと、任意で他のパラメーターとともに呼び出されます:

  1. statusSomeNonTerminalのSyntaxDirectedOperationとする。
  2. someParseNode を何らかのsource textのparseとする。
  3. someParseNode のSyntaxDirectedOperationを実行する。
  4. argument "value" 付きでsomeParseNode のSyntaxDirectedOperationを実行する。

明示的に別途指定されない限り、すべてのchain productionsは、その生成の左辺非終端に適用され得るすべての操作について暗黙の定義を持ちます。暗黙の定義は、同じ操作を、同じパラメーターがあればそれらとともに、chain productionの唯一の右辺非終端へ再適用し、その後結果を返すだけです。たとえば、あるアルゴリズムに“Return Evaluation of Block”という形式のステップがあり、次の生成があると仮定します:

Block : { StatementList }

しかしEvaluation操作がその生成とアルゴリズムを関連付けていない場合、そのときEvaluation操作は暗黙に次の形式の関連付けを含みます:

Runtime Semantics: Evaluation

Block : { StatementList }
  1. StatementListEvaluationを返す。

5.2.4 Runtime Semantics

runtimeで呼び出されなければならない意味論を指定するアルゴリズムは、runtime semanticsと呼ばれます。Runtime semanticsは、abstract operationsまたはsyntax-directed operationsによって定義されます。

5.2.4.1 Completion ( completionRecord )

The abstract operation Completion takes argument completionRecord (a Completion Record) and returns a Completion Record. Completion Recordが返されていることを強調するために使用されます。 It performs the following steps when called:

  1. Assert: completionRecordCompletion Recordである。
  2. completionRecord を返す。

5.2.4.2 Throw

アルゴリズムステップにおいて、“throw”という語は、ThrowCompletionを呼び出した結果を返すことの省略形です。たとえば、

  1. result.[[Error]]noneでないなら、result.[[Error]]をthrowする。

は次と等価です

  1. result.[[Error]]noneでないなら、ThrowCompletion(result.[[Error]])を返す。

特定の型の例外をthrowすると述べるアルゴリズムステップは、throwされるその型の例外を構築します。たとえば、

  1. TypeError例外をthrowする。

は次と等価です

  1. ThrowCompletion(newly created TypeError object)を返す。

5.2.4.3 Completion Recordsをアンラップするための省略形

Prefix “?”および“!”は、Completion Recordsをアンラップする省略形として使用されます。“?”は、abrupt completionを呼び出し元へ伝播するか、そうでなければnormal completionをアンラップするために使用されます。“!”は、Completion Recordがnormalであることを表明し、それをアンラップするために使用されます。形式的には、ステップ

  1. result を ? record とする。

は次と等価です

  1. Assert: recordCompletion Recordである。
  2. recordabrupt completionなら、record を返す。
  3. resultrecord.[[Value]]とする。

同様に、ステップ

  1. result を ! record とする。

は次と等価です

  1. Assert: recordnormal completionである。
  2. resultrecord.[[Value]]とする。

“?”または“!”が他の任意の文脈で使用される場合、この規則が適用できるようになるまで、まず評価順序で与えられる書き換えを適用し、その後この規則を適用します。たとえば、ステップ

  1. AO(? Other())を実行する。

は次のように書き換えることができます

  1. tmp1 をOther()とする。
  2. tmp2 を ? tmp1 とする。
  3. AO(tmp2)を実行する。

これはさらに次のように展開されます

  1. tmp1 をOther()とする。
  2. Assert: tmp1Completion Recordである。
  3. tmp1abrupt completionなら、tmp1 を返す。
  4. tmp2tmp1.[[Value]]とする。
  5. AO(tmp2)を実行する。

5.2.4.4 暗黙のNormal Completion

Completion Recordを返すと宣言されているabstract operations内のアルゴリズム、およびすべてのbuilt-in functions内では、返された値はまずNormalCompletionへ渡され、その結果が代わりに使用されます。この規則は、Completionアルゴリズム内、または返される値がそのステップでCompletion Recordとして明確にマークされている場合には適用されません。これらの場合は以下です:

Completion Recordがそのようなabstract operationから他の手段で返される場合、それは編集上の誤りです。たとえば、これらのabstract operations内では、

  1. true を返す。

は次のいずれとも同じ意味です

  1. NormalCompletion(true)を返す。

または

  1. completionNormalCompletion(true)とする。
  2. Completion(completion)を返す。

または

  1. Completion Record { [[Type]]: normal, [[Value]]: true, [[Target]]: empty }を返す。

?省略形の展開を通じて、次の例は許可されることに注意してください。展開後のステップ内では、abruptの場合にCompletionを適用した結果が直接返され、normalの場合にアンラップ後に暗黙のNormalCompletion適用が発生するためです。

  1. completion を返す。

次の例は、Completion Recordがそのステップで注釈されずに返されているため、編集上の誤りになります。

  1. completionNormalCompletion(true)とする。
  2. completion を返す。

5.2.5 Static Semantics

文脈自由文法は、入力要素のストリームが、評価され得る有効なECMAScript ScriptまたはModuleを形成するかどうかを定義するすべての規則を表現するには十分に強力ではありません。状況によっては、ECMAScriptアルゴリズム慣例または散文要件のいずれかを使用して表現され得る追加の規則が必要です。そのような規則は常に文法の生成に関連付けられ、その生成のstatic semanticsと呼ばれます。

Static Semantic Rulesには名前があり、通常はアルゴリズムを使用して定義されます。名前付きStatic Semantic Rulesは文法生成に関連付けられ、複数の代替定義を持つ生成は通常、適用可能な各名前付きstatic semantic ruleについて、各代替に対して別個のアルゴリズムを持ちます。

static semantic ruleの特別な種類は、Early Error Ruleです。Early error rulesは、特定の文法生成に関連付けられたearly error conditions(clause 17を参照)を定義します。ほとんどのearly error rulesの評価は、この仕様のアルゴリズム内で明示的に呼び出されません。適合実装は、ScriptまたはModuleの最初の評価の前に、そのScriptまたはModuleを解析するために使用された生成のすべてのearly error rulesを検証しなければなりません。early error rulesのいずれかが違反された場合、そのScriptまたはModuleは無効であり、評価できません。

5.2.6 数学演算

この仕様は、以下の種類の数値を参照します:

  • Mathematical values: デフォルトの数値型として使用される任意の実数。
  • Extended mathematical values: Mathematical valuesに+∞および-∞を加えたもの。
  • Numbers: IEEE 754-2019 binary64(二倍精度浮動小数点)値。
  • BigInts: 任意の整数を一対一対応で表すECMAScript言語値

この仕様の言語では、数値は下付き接尾辞を使用して異なる数値種別の間で区別されます。下付き文字𝔽はNumbersを指し、下付き文字はBigIntsを指します。下付き接尾辞のない数値はmathematical valuesを指します。この仕様はほとんどの数値を10進法で表します。また、0xに続いて0-9またはA-Fの数字が続く形式の数値を16進値として使用します。

一般に、この仕様が“the length of y”や“the integer represented by the four hexadecimal digits ...”などの句で数値を参照し、数値種別を明示的に指定しない場合、その句はmathematical valueを指します。NumberまたはBigInt値を指す句は、そのように明示的に注釈されます。たとえば、“the Number value for the number of code points in …”または“the BigInt value for …”です。

この仕様でintegerという用語が使用される場合、別途述べられない限り、それは整数の集合に属するmathematical valueを指します。この仕様でintegral Numberという用語が使用される場合、それは、そのmathematical valueが整数の集合に属する有限のNumber値を指します。

+, ×, =, ≥などの数値演算子は、オペランドの型によって決定されるそれらの演算を指します。mathematical valuesに適用される場合、演算子は通常の数学演算を指します。extended mathematical valuesに適用される場合、演算子は拡張実数上の通常の数学演算を指します。不定形は定義されず、この仕様でそれらを使用することは編集上の誤りと見なされるべきです。Numbersに適用される場合、演算子はIEEE 754-2019内の関連する演算を指します。BigIntsに適用される場合、演算子はBigIntのmathematical valueに適用される通常の数学演算を指します。混合型のオペランド(Numberとmathematical valueなど)に適用される数値演算子は定義されず、この仕様では編集上の誤りと見なされるべきです。

mathematical valuesとNumbersまたはBigIntsの間の変換は、この文書では常に明示的です。mathematical valueまたはextended mathematical value x からNumberへの変換は、“the Number value for x”または𝔽(x)と表され、6.1.6.1で定義されます。integer x からBigIntへの変換は、“the BigInt value for x”またはℤ(x)と表されます。NumberまたはBigInt x からmathematical valueへの変換は、“the mathematical value of x”、またはℝ(x)と表されます。+0𝔽および-0𝔽mathematical valueは、mathematical value 0です。非有限値のmathematical valueは定義されません。xextended mathematical value ofは、有限値についてはxmathematical valueであり、+∞𝔽および-∞𝔽についてはそれぞれ+∞および-∞です。NaNについては定義されません。

数学関数abs(x)は、x の絶対値を生成します。これは、x < 0であれば-xであり、それ以外ではx 自身です。

数学関数ln(x)は、x の自然対数を生成します。数学関数log10(x)は、x の10を底とする対数を生成します。数学関数log2(x)は、x の2を底とする対数を生成します。

数学関数min(x1, x2, … , xN)は、x1からxNまでのうち数学的に最小のものを生成します。数学関数max(x1, x2, ..., xN)は、x1からxNまでのうち数学的に最大のものを生成します。これらの数学関数の定義域と値域はextended mathematical valuesです。

記法“x modulo y”(y は有限かつ非ゼロでなければなりません)は、y と同じ符号(またはゼロ)を持つ値k を計算します。ここでabs(k) < abs(y) and x - k = q × yが何らかのinteger q について成り立ちます。

“the result of clamping x between lower and upper”という句(ここでxextended mathematical valueであり、lower およびupperlowerupperを満たすmathematical valuesです)は、x < lowerならlower を生成し、x > upperならupper を生成し、それ以外ではx を生成します。

数学関数floor(x)は、x より大きくない最大のinteger(+∞に最も近いもの)を生成します。

Note

floor(x) = x - (x modulo 1)

数学関数truncate(x)は、ゼロ方向に丸めることでx の小数部分を取り除き、x < 0なら-floor(-x)を生成し、それ以外ではfloor(x)を生成します。

数学関数minmaxabsfloor、およびtruncateはNumbersおよびBigIntsについて定義されず、非mathematical value argumentsを持つそれらのメソッドの任意の使用は、この仕様では編集上の誤りとなります。

下限a から上限b までのintervalは、同じ数値型の数値の、無限であり得る、空であり得る集合です。各境界はinclusiveまたはexclusiveのいずれかとして記述されますが、両方ではありません。intervalには以下の4種類があります:

  • a(inclusive)からb(inclusive)までのinterval、別名inclusive interval from a to bは、同じ数値型のすべての値x であって axbを満たすものを含み、それ以外を含みません。
  • a(inclusive)からb(exclusive)までのintervalは、同じ数値型のすべての値x であって ax < bを満たすものを含み、それ以外を含みません。
  • a(exclusive)からb(inclusive)までのintervalは、同じ数値型のすべての値x であって a < xbを満たすものを含み、それ以外を含みません。
  • a(exclusive)からb(exclusive)までのintervalは、同じ数値型のすべての値x であって a < x < bを満たすものを含み、それ以外を含みません。

たとえば、1(inclusive)から2(exclusive)までのintervalは、1と2の間のすべてのmathematical valuesからなり、1を含み、2を含みません。intervalを定義する目的では、-0𝔽 < +0𝔽です。したがって、たとえば下限が+0𝔽であるinclusive interval+0𝔽を含みますが、-0𝔽は含みません。NaNintervalに決して含まれません。

5.2.7 値記法

この仕様では、ECMAScript言語値boldで表示されます。例にはnulltrue、または"hello"が含まれます。これらは、Function.prototype.applylet n = 42;などのECMAScript source textと区別されます。

5.2.8 同一性

この仕様では、仕様値とECMAScript言語値の双方が等価性について比較されます。等価性について比較する場合、値は2つのカテゴリのいずれかに分かれます。同一性を持たない値は、それらの生得的な特性がすべて同じである場合、他の同一性を持たない値と等しいです。特性とは、integerの大きさや列の長さなどです。同一性を持たない値は、その特性を完全に記述することで、事前の参照なしに明示できます。対照的に、各同一性を持つ値は一意であり、したがって自分自身にのみ等しいです。同一性を持つ値は、同一性を持たない値に似ていますが、同一性と呼ばれる追加の推測不能で変更不能で全世界的に一意な特性を持ちます。既存の同一性を持つ値への参照は、単にそれらを記述することでは明示できません。同一性そのものが記述不能であるためです。代わりに、これらの値への参照は、ある場所から別の場所へ明示的に渡されなければなりません。一部の同一性を持つ値はmutableであり、そのためその特性(同一性を除く)をin-placeで変更でき、その値を保持するすべてのものが新しい特性を観測することになります。同一性を持たない値は、同一性を持つ値と決して等しくありません。

この仕様の観点から、2つの値を等価性について比較するために、“If bool is true, then ...”のように“is”という語が使用され、等価性比較を使用してリスト内部の値を検索するために、“If list contains a Record r such that r.[[Foo]] is true, then ...”のように“contains”という語が使用されます。値のspecification identityはこれらの比較の結果を決定し、この仕様では公理的なものです。

ECMAScript言語の観点から、言語値はSameValue抽象操作およびそれが推移的に呼び出す抽象操作を使用して等価性について比較されます。これらの比較抽象操作のアルゴリズムは、ECMAScript言語値language identityを決定します。

仕様値について、specification identityを持たない値の例には、mathematical valuesおよびextended mathematical valuesECMAScript source textsurrogate pairsDirective Prologuesなど、UTF-16 code units、Unicode code points、enumsabstract operationssyntax-directed operationshost hooksなどを含む)、およびordered pairsが含まれますが、これらに限定されません。specification identityを持つ仕様値の例には、Property DescriptorsPrivateElementsなどを含む任意の種類のRecordsParse NodesListsSetsおよびRelationsAbstract ClosuresData BlocksPrivate Namesexecution contextsおよびexecution context stacksagent signifiers、ならびにWaiterList Recordsが含まれますが、これらに限定されません。

Specification identityは、Symbol.forによって生成されたSymbol valuesを除くすべてのECMAScript言語値についてlanguage identityと一致します。specification identityもlanguage identityも持たないECMAScript言語値は、undefinednullBooleansStringsNumbers、およびBigIntsです。specification identityとlanguage identityを持つECMAScript言語値は、SymbolsのうちSymbol.forによって生成されていないもの、およびObjectsです。Symbol.forによって生成されたSymbol valuesはspecification identityを持ちますが、language identityは持ちません。

6 ECMAScriptのデータ型と値

この仕様内のアルゴリズムは、それぞれに関連付けられた型を持つ値を操作します。可能な値の型は、この節で定義されるものに正確に限られます。型はさらにECMAScript言語型と仕様型に分類されます。

6.1 ECMAScript言語型

ECMAScript言語型は、ECMAScriptプログラマーがECMAScript言語を使用して直接操作する値に対応します。ECMAScript言語型はUndefined、Null、Boolean、String、Symbol、Number、BigInt、およびObjectです。ECMAScript言語値とは、ECMAScript言語型によって特徴付けられる値です。

6.1.1 Undefined型

Undefined型は、undefinedと呼ばれるちょうど1つの値を持ちます。値が代入されていない任意の変数は、値undefinedを持ちます。

6.1.2 Null型

Null型は、nullと呼ばれるちょうど1つの値を持ちます。

6.1.3 Boolean型

Boolean型は、trueおよびfalseと呼ばれる2つの値を持つ論理的実体を表します。

6.1.4 String型

String型は、最大長253 - 1要素までの、0個以上の16ビット符号なし整数値(“要素”)のすべての順序列の集合です。String型は一般に、実行中のECMAScriptプログラム内でテキストデータを表すために使用され、その場合、String内の各要素はUTF-16コード単位値として扱われます。各要素は、その列内の位置を占めるものと見なされます。これらの位置は非負整数でインデックス付けされます。最初の要素(存在する場合)はindex 0にあり、次の要素(存在する場合)はindex 1にあり、以下同様です。Stringの長さは、その中の要素(すなわち16ビット値)の数です。空のStringは長さ0であり、したがって要素を含みません。

Stringの内容を解釈しないECMAScript操作は、それ以上の意味論を適用しません。String値を解釈する操作は、各要素を単一のUTF-16コード単位として扱います。しかし、ECMAScriptはこれらのコード単位の値や相互関係を制限しないため、Stringの内容をUTF-16でエンコードされたUnicode符号位置列としてさらに解釈する操作は、不正な部分列を考慮しなければなりません。そのような操作は、0xD800から0xDBFFまでの包含区間内の数値を持つすべてのコード単位(Unicode Standardによってleading surrogate、またはより正式にはhigh-surrogate code unitとして定義される)と、0xDC00から0xDFFFまでの包含区間内の数値を持つすべてのコード単位(trailing surrogate、またはより正式にはlow-surrogate code unitとして定義される)に対して、以下の規則を使用して特別な扱いを適用します:

  • leading surrogateでもtrailing surrogateでもないコード単位は、同じ値を持つ符号位置として解釈されます。
  • 2つのコード単位の列であって、最初のコード単位c1leading surrogateであり、2番目のコード単位c2trailing surrogateであるものは、surrogate pairであり、値(c1 - 0xD800) × 0x400 + (c2 - 0xDC00) + 0x10000を持つ符号位置として解釈されます。(11.1.3を参照)
  • leading surrogateまたはtrailing surrogateであるが、surrogate pairの一部ではないコード単位は、同じ値を持つ符号位置として解釈されます。

関数String.prototype.normalize22.1.3.15を参照)は、String値を明示的に正規化するために使用できます。String.prototype.localeCompare22.1.3.12を参照)は内部的にString値を正規化しますが、他の操作はそれが作用する文字列を暗黙に正規化しません。別途述べられない限り、操作結果は言語および/またはlocaleに依存しません。

Note

この設計の根拠は、Stringsの実装を可能な限り単純かつ高性能に保つことでした。ECMAScript source textがNormalized Form Cである場合、Unicode escape sequencesを含まない限り、文字列リテラルも正規化されていることが保証されます。

この仕様では、“A, B, ...のstring-concatenation”(各argumentがString値、コード単位、またはコード単位列である場合)という句は、各argumentのコード単位(順序どおり)の連結(順序どおり)であるコード単位列を持つString値を表します。

inclusiveStartからexclusiveEndまでのstringsubstring”(stringがString値またはコード単位列であり、inclusiveStartおよびexclusiveEndが整数である場合)という句は、index inclusiveStartから始まりindex exclusiveEndの直前で終わる、stringの連続するコード単位からなるString値を表します(inclusiveStart = exclusiveEndの場合は空のString)。"to"接尾辞が省略された場合、stringの長さがexclusiveEndの値として使用されます。

the ASCII word characters”という句は、Unicode Basic Latinブロック内のすべての文字および数字にU+005F(LOW LINE)を加えたもののみからなる、以下のString値を表します:
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_".
歴史的な理由により、これはさまざまなアルゴリズムにおいて重要性を持ちます。

6.1.4.1 StringIndexOf ( string, searchValue, fromIndex )

The abstract operation StringIndexOf takes arguments string (a String), searchValue (a String), and fromIndex (a non-negative integer) and returns a non-negative integer or not-found. It performs the following steps when called:

  1. lengthstringの長さとする。
  2. searchValueが空のStringであり、fromIndexlengthなら、fromIndexを返す。
  3. searchLengthsearchValueの長さとする。
  4. fromIndexilength - searchLengthである各整数iについて、昇順で、以下を行う
    1. candidatestringiからi + searchLengthまでのsubstringとする。
    2. candidatesearchValueなら、iを返す。
  5. not-foundを返す。
Note 1

searchValueが空のStringであり、fromIndexstringの長さである場合、このアルゴリズムはfromIndexを返します。空のStringは、最後のコード単位の後を含め、文字列内のすべての位置で実質的に見つかります。

Note 2

このアルゴリズムは、fromIndex + searchValueの長さ > stringの長さである場合、常にnot-foundを返します。

6.1.4.2 StringLastIndexOf ( string, searchValue, fromIndex )

The abstract operation StringLastIndexOf takes arguments string (a String), searchValue (a String), and fromIndex (a non-negative integer) and returns a non-negative integer or not-found. It performs the following steps when called:

  1. lengthstringの長さとする。
  2. searchLengthsearchValueの長さとする。
  3. Assert: fromIndex + searchLengthlength
  4. 0 ≤ ifromIndexである各整数iについて、降順で、以下を行う
    1. candidatestringiからi + searchLengthまでのsubstringとする。
    2. candidatesearchValueなら、iを返す。
  5. not-foundを返す。
Note

searchValueが空のStringである場合、このアルゴリズムはfromIndexを返します。空のStringは、最後のコード単位の後を含め、文字列内のすべての位置で実質的に見つかります。

6.1.5 Symbol型

Symbol型は、Objectプロパティのキーとして使用できるすべての非String値の集合です(6.1.7)。

各Symbolは一意で不変です。

各Symbolは不変の[[Description]] internal slotを持ち、その値はStringまたはundefinedのいずれかです。

6.1.5.1 Well-Known Symbols

well-known symbolsは、この仕様のアルゴリズムによって明示的に参照される組み込みSymbol値です。それらは通常、仕様アルゴリズムの拡張点として機能する値を持つプロパティのキーとして使用されます。別途指定されない限り、well-known symbols値はすべてのrealmsによって共有されます(9.3)。

この仕様内では、well-known symbolは、Table 1に列挙される値の1つであるintrinsicを用いて、標準のintrinsic notationで参照されます。

Note
この仕様の以前の版では、現在の版で%Symbol.name%を使用する箇所に@@nameという形式の記法を使用していました。特に、以下の名前が使用されていました:@@asyncIterator、@@hasInstance、@@isConcatSpreadable、@@iterator、@@match、@@matchAll、@@replace、@@search、@@species、@@split、@@toPrimitive、@@toStringTag、および@@unscopables。
Table 1: よく知られたシンボル
仕様名 [[Description]] 値と目的
%Symbol.asyncDispose% "Symbol.asyncDispose" オブジェクト上で非同期にリソースのクリーンアップを実行するメソッド。それを含むスコープの評価が完了したときに、AsyncDisposableStack オブジェクトおよび await using 宣言によって呼び出される。
%Symbol.asyncIterator% "Symbol.asyncIterator" オブジェクトのデフォルト非同期イテレータを返すメソッド。for-await-of 文のセマンティクスによって呼び出される。
%Symbol.dispose% "Symbol.dispose" オブジェクト上で明示的なリソースのクリーンアップを実行するメソッド。それを含むスコープの評価が完了したときに、DisposableStack オブジェクト、AsyncDisposableStack オブジェクト、および using 宣言によって呼び出される。
%Symbol.hasInstance% "Symbol.hasInstance" コンストラクタオブジェクトが、あるオブジェクトをそのコンストラクタのインスタンスの1つとして認識するかどうかを判定するメソッド。instanceof 演算子のセマンティクスによって呼び出される。
%Symbol.isConcatSpreadable% "Symbol.isConcatSpreadable" true の場合、オブジェクトが Array.prototype.concat によってその配列要素へと平坦化されるべきことを示す Boolean 値のプロパティ。
%Symbol.iterator% "Symbol.iterator" オブジェクトのデフォルトイテレータを返すメソッド。for-of 文のセマンティクスによって呼び出される。
%Symbol.match% "Symbol.match" 正規表現を文字列に照合する正規表現メソッド。String.prototype.match メソッドによって呼び出される。
%Symbol.matchAll% "Symbol.matchAll" 文字列に対する正規表現の一致を yield するイテレータを返す正規表現メソッド。String.prototype.matchAll メソッドによって呼び出される。
%Symbol.replace% "Symbol.replace" 文字列の一致した部分文字列を置換する正規表現メソッド。String.prototype.replace メソッドによって呼び出される。
%Symbol.search% "Symbol.search" 正規表現に一致する文字列内のインデックスを返す正規表現メソッド。String.prototype.search メソッドによって呼び出される。
%Symbol.species% "Symbol.species" 派生オブジェクトを作成するために使用されるコンストラクタ関数である、関数値のプロパティ。
%Symbol.split% "Symbol.split" 正規表現に一致するインデックスで文字列を分割する正規表現メソッド。String.prototype.split メソッドによって呼び出される。
%Symbol.toPrimitive% "Symbol.toPrimitive" オブジェクトを対応するプリミティブ値へ変換するメソッド。ToPrimitive 抽象操作によって呼び出される。
%Symbol.toStringTag% "Symbol.toStringTag" オブジェクトのデフォルトの文字列表現を作成する際に使用される String 値のプロパティ。組み込みメソッド Object.prototype.toString によってアクセスされる。
%Symbol.unscopables% "Symbol.unscopables" 自身および継承されたプロパティ名が、関連付けられたオブジェクトの with 環境束縛から除外されるプロパティ名である、オブジェクト値のプロパティ。

6.1.6 数値型

ECMAScriptには2つの組み込み数値型、NumberとBigIntがあります。以下の抽象操作は、これらの数値型上で定義されます。“Result”列は戻り型を示し、その操作の一部の呼び出しがabrupt completionを返す可能性があるかどうかも示します。

Table 2: Numeric Type Operations
操作 例のsource ...のEvaluation意味論によって呼び出される 結果
Number::unaryMinus -x Unary - Operator Number
BigInt::unaryMinus BigInt
Number::bitwiseNOT ~x Bitwise NOT Operator ( ~ ) Number
BigInt::bitwiseNOT BigInt
Number::exponentiate x ** y Exponentiation Operator およびMath.pow ( base, exponent ) Number
BigInt::exponentiate BigIntを含むnormal completionまたはthrow completionのいずれか
Number::multiply x * y Multiplicative Operators Number
BigInt::multiply BigInt
Number::divide x / y Multiplicative Operators Number
BigInt::divide BigIntを含むnormal completionまたはthrow completionのいずれか
Number::remainder x % y Multiplicative Operators Number
BigInt::remainder BigIntを含むnormal completionまたはthrow completionのいずれか
Number::add x ++
++ x
x + y
Postfix Increment Operator, Prefix Increment Operator, およびThe Addition Operator ( + ) Number
BigInt::add BigInt
Number::subtract x --
-- x
x - y
Postfix Decrement Operator, Prefix Decrement Operator, およびThe Subtraction Operator ( - ) Number
BigInt::subtract BigInt
Number::leftShift x << y The Left Shift Operator ( << ) Number
BigInt::leftShift BigInt
Number::signedRightShift x >> y The Signed Right Shift Operator ( >> ) Number
BigInt::signedRightShift BigInt
Number::unsignedRightShift x >>> y The Unsigned Right Shift Operator ( >>> ) Number
BigInt::unsignedRightShift throw completion
Number::lessThan x < y
x > y
x <= y
x >= y
Relational Operators, IsLessThan ( x, y, leftFirst )経由 Booleanまたはundefined(順序不能な入力の場合)
BigInt::lessThan Boolean
Number::equal x == y
x != y
x === y
x !== y
Equality Operators, IsStrictlyEqual ( x, y )経由 Boolean
BigInt::equal
Number::sameValue Object.is(x, y) Object internal methods, 正確な値の等価性をテストするためにSameValue ( x, y )経由 Boolean
Number::sameValueZero [x].includes(y) Array、Map、およびSetメソッドにおけるように、+0𝔽-0𝔽の違いを無視して値の等価性をテストするために、SameValueZero ( x, y )経由 Boolean
Number::bitwiseAND x & y Binary Bitwise Operators Number
BigInt::bitwiseAND BigInt
Number::bitwiseXOR x ^ y Number
BigInt::bitwiseXOR BigInt
Number::bitwiseOR x | y Number
BigInt::bitwiseOR BigInt
Number::toString String(x) 多くの式および組み込み関数、ToString ( arg )経由 String
BigInt::toString

数値型は一般に、精度の損失や切り捨てなしには変換できないため、ECMAScript言語はこれらの型間の暗黙変換を提供しません。プログラマーは、別の型を必要とする関数を呼び出すとき、型間で変換するためにNumberおよびBigInt関数を明示的に呼び出さなければなりません。

Note

ECMAScriptの第1版およびその後の版は、特定の演算子について、精度を失ったり切り捨てたりする可能性のある暗黙の数値変換を提供してきました。これらのlegacy implicit conversionsは後方互換性のために維持されていますが、プログラマーのエラーの機会を最小化し、将来の版における一般化されたvalue typesの選択肢を残すため、BigIntには提供されません。

6.1.6.1 Number型

Number型は、正確に18,437,736,874,454,810,627個(すなわち264 - 253 + 3個)の値を持ち、IEEE Standard for Binary Floating-Point Arithmeticで指定されるIEEE 754-2019 binary64の倍精度浮動小数点値を表します。ただし、IEEE Standardの9,007,199,254,740,990個(すなわち253 - 2個)の異なるNaN値は、ECMAScriptでは単一の特別なNaN値として表されます。(NaN値はプログラム式NaNによって生成されることに注意してください。)一部の実装では、外部コードがさまざまなNaN値の違いを検出できる場合がありますが、そのような振る舞いはimplementation-definedです。ECMAScriptコードにとって、すべてのNaN値は互いに区別できません。

Note

Number値がArrayBuffer(25.1を参照)またはSharedArrayBuffer(25.2を参照)に格納された後に観測され得るビットパターンは、ECMAScript実装によって使用されるそのNumber値の内部表現と必ずしも同じではありません。

他に2つの特別な値があり、positive Infinityおよびnegative Infinityと呼ばれます。簡潔さのため、これらの値は説明目的でそれぞれ記号+∞𝔽および-∞𝔽によっても参照されます。(これら2つの無限Number値は、プログラム式+Infinity(または単にInfinity)および-Infinityによって生成されることに注意してください。)

その他の18,437,736,874,454,810,624個(すなわち264 - 253個)の値はfinite numbersと呼ばれます。これらの半分は正の数であり、半分は負の数です。各有限の正のNumber値には、同じ大きさを持つ対応する負の値があります。

positive zeronegative zeroの双方が存在することに注意してください。簡潔さのため、これらの値は説明目的でそれぞれ記号+0𝔽および-0𝔽によっても参照されます。(これら2つの異なるzero Number値は、プログラム式+0(または単に0)および-0によって生成されることに注意してください。)

18,437,736,874,454,810,622個(すなわち264 - 253 - 2個)の有限非ゼロ値には2種類あります:

そのうち18,428,729,675,200,069,632個(すなわち264 - 254個)はnormalizedであり、次の形式を持ちます

s × m × 2e

ここでsは1または-1、mは252(inclusive)から253(exclusive)までのinterval内のintegereは-1074から971までの包含区間内のintegerです。

残りの9,007,199,254,740,990個(すなわち253 - 2個)の値はdenormalizedであり、次の形式を持ちます

s × m × 2e

ここでsは1または-1、mは0(exclusive)から252(exclusive)までのinterval内のintegereは-1074です。

大きさが253以下であるすべての正および負のintegersは、Number型で表現可能であることに注意してください。integer 0はNumber型において2つの表現を持ちます:+0𝔽および-0𝔽です。

有限数は、非ゼロであり、それを表現するために使用されるinteger m(上に示した2つの形式のいずれか)が奇数である場合、odd significandを持ちます。それ以外の場合、even significandを持ちます。

この仕様では、“xNumber value for”という句は、xが正確な実数数学量(πのような無理数であってもよい)を表す場合、以下の方法で選ばれたNumber値を意味します。Number型のすべてのfinite valuesの集合から-0𝔽を取り除き、Number型では表現できない2つの追加値、すなわち21024(これは+1 × 253 × 2971)および-21024(これは-1 × 253 × 2971)を加えた集合を考えます。この集合のメンバーのうち、値がxに最も近いものを選びます。集合内の2つの値が等しく近い場合、even significandを持つものが選ばれます。この目的のため、追加の2つの値21024および-21024はeven significandsを持つものと見なされます。最後に、21024が選ばれた場合、それを+∞𝔽で置き換えます。-21024が選ばれた場合、それを-∞𝔽で置き換えます。+0𝔽が選ばれた場合、x < 0である場合に限り、それを-0𝔽で置き換えます。その他の選ばれた値は変更せずに使用されます。その結果がxのNumber valueです。(この手続きはIEEE 754-2019 roundTiesToEven modeの振る舞いに正確に対応します。)

+∞のNumber valueは+∞𝔽であり、-∞のNumber valueは-∞𝔽です。

一部のECMAScript演算子は、-231から231 - 1までの包含区間や、0から216 - 1までの包含区間など、特定範囲のintegersのみを扱います。これらの演算子はNumber型の任意の値を受け入れますが、まずそのような各値を期待される範囲内のinteger値へ変換します。7.1内の数値変換操作の記述を参照してください。

6.1.6.1.1 Number::unaryMinus ( number )

The abstract operation Number::unaryMinus takes argument number (a Number) and returns a Number. It performs the following steps when called:

  1. numberNaNなら、NaNを返す。
  2. numberの否定を返す。すなわち、同じ大きさで反対の符号を持つNumberを計算する。

6.1.6.1.2 Number::bitwiseNOT ( number )

The abstract operation Number::bitwiseNOT takes argument number (a Number) and returns an integral Number. It performs the following steps when called:

  1. oldValueを ! ToInt32(number) とする。
  2. oldValueのビットごとの補数を返す。結果のmathematical valueは32ビットtwo's complement bit stringとして正確に表現可能です。

6.1.6.1.3 Number::exponentiate ( base, exponent )

The abstract operation Number::exponentiate takes arguments base (a Number) and exponent (a Number) and returns a Number. これはbaseexponent乗した結果を表すimplementation-approximatedな値を返します。 It performs the following steps when called:

  1. exponentNaNなら、NaNを返す。
  2. exponent+0𝔽または-0𝔽のいずれかなら、1𝔽を返す。
  3. baseNaNなら、NaNを返す。
  4. base+∞𝔽なら、
    1. exponent > +0𝔽なら、+∞𝔽を返す。
    2. +0𝔽を返す。
  5. base-∞𝔽なら、
    1. exponent > +0𝔽なら、
      1. exponentがodd integral Numberなら、-∞𝔽を返す。
      2. +∞𝔽を返す。
    2. exponentがodd integral Numberなら、-0𝔽を返す。
    3. +0𝔽を返す。
  6. base+0𝔽なら、
    1. exponent > +0𝔽なら、+0𝔽を返す。
    2. +∞𝔽を返す。
  7. base-0𝔽なら、
    1. exponent > +0𝔽なら、
      1. exponentがodd integral Numberなら、-0𝔽を返す。
      2. +0𝔽を返す。
    2. exponentがodd integral Numberなら、-∞𝔽を返す。
    3. +∞𝔽を返す。
  8. Assert: basefiniteであり、+0𝔽でも-0𝔽でもない。
  9. exponent+∞𝔽なら、
    1. abs((base)) > 1なら、+∞𝔽を返す。
    2. abs((base)) = 1なら、NaNを返す。
    3. +0𝔽を返す。
  10. exponent-∞𝔽なら、
    1. abs((base)) > 1なら、+0𝔽を返す。
    2. abs((base)) = 1なら、NaNを返す。
    3. +∞𝔽を返す。
  11. Assert: exponentfiniteであり、+0𝔽でも-0𝔽でもない。
  12. base < -0𝔽かつexponentintegral Numberでないなら、NaNを返す。
  13. (base)を(exponent)乗した結果を表すimplementation-approximatedなNumber値を返す。
Note

base1𝔽または-1𝔽であり、exponent+∞𝔽または-∞𝔽である場合、またはbase1𝔽でありexponentNaNである場合のbase ** exponentの結果は、IEEE 754-2019とは異なります。ECMAScriptの第1版はこの操作の結果をNaNと指定していましたが、IEEE 754の後の改訂では1𝔽と指定しました。歴史的なECMAScriptの振る舞いは互換性の理由により保持されています。

6.1.6.1.4 Number::multiply ( x, y )

The abstract operation Number::multiply takes arguments x (a Number) and y (a Number) and returns a Number. IEEE 754-2019 binary double-precision arithmeticの規則に従って乗算を実行し、xyの積を生成します。 It performs the following steps when called:

  1. xNaNまたはyNaNなら、NaNを返す。
  2. x+∞𝔽または-∞𝔽のいずれかなら、
    1. y+0𝔽または-0𝔽のいずれかなら、NaNを返す。
    2. y > +0𝔽なら、xを返す。
    3. -xを返す。
  3. y+∞𝔽または-∞𝔽のいずれかなら、
    1. x+0𝔽または-0𝔽のいずれかなら、NaNを返す。
    2. x > +0𝔽なら、yを返す。
    3. -yを返す。
  4. x-0𝔽なら、
    1. y-0𝔽またはy < -0𝔽なら、+0𝔽を返す。
    2. -0𝔽を返す。
  5. y-0𝔽なら、
    1. x < -0𝔽なら、+0𝔽を返す。
    2. -0𝔽を返す。
  6. 𝔽((x) × (y))を返す。
Note

有限精度の乗算は可換ですが、常に結合的であるとは限りません。

6.1.6.1.5 Number::divide ( x, y )

The abstract operation Number::divide takes arguments x (a Number) and y (a Number) and returns a Number. IEEE 754-2019 binary double-precision arithmeticの規則に従って除算を実行し、xをdividend、yをdivisorとするxyのquotientを生成します。 It performs the following steps when called:

  1. xNaNまたはyNaNなら、NaNを返す。
  2. x+∞𝔽または-∞𝔽のいずれかなら、
    1. y+∞𝔽または-∞𝔽のいずれかなら、NaNを返す。
    2. y+0𝔽またはy > +0𝔽なら、xを返す。
    3. -xを返す。
  3. y+∞𝔽なら、
    1. x+0𝔽またはx > +0𝔽なら、+0𝔽を返す。
    2. -0𝔽を返す。
  4. y-∞𝔽なら、
    1. x+0𝔽またはx > +0𝔽なら、-0𝔽を返す。
    2. +0𝔽を返す。
  5. x+0𝔽または-0𝔽のいずれかなら、
    1. y+0𝔽または-0𝔽のいずれかなら、NaNを返す。
    2. y > +0𝔽なら、xを返す。
    3. -xを返す。
  6. y+0𝔽なら、
    1. x > +0𝔽なら、+∞𝔽を返す。
    2. -∞𝔽を返す。
  7. y-0𝔽なら、
    1. x > +0𝔽なら、-∞𝔽を返す。
    2. +∞𝔽を返す。
  8. 𝔽((x) / (y))を返す。

6.1.6.1.6 Number::remainder ( numerator, denominator )

The abstract operation Number::remainder takes arguments numerator (a Number) and denominator (a Number) and returns a Number. numeratorをdividend、denominatorをdivisorとする、そのオペランドの暗黙の除算からremainderを生成します。 It performs the following steps when called:

  1. numeratorNaNまたはdenominatorNaNなら、NaNを返す。
  2. numerator+∞𝔽または-∞𝔽のいずれかなら、NaNを返す。
  3. denominator+∞𝔽または-∞𝔽のいずれかなら、numeratorを返す。
  4. denominator+0𝔽または-0𝔽のいずれかなら、NaNを返す。
  5. numerator+0𝔽または-0𝔽のいずれかなら、numeratorを返す。
  6. Assert: numeratordenominatorfiniteかつnon-zeroである。
  7. quotient(numerator) / (denominator)とする。
  8. truncatedQuotienttruncate(quotient)とする。
  9. remainder(numerator) - ((denominator) × truncatedQuotient)とする。
  10. remainder = 0かつnumerator < -0𝔽なら、-0𝔽を返す。
  11. 𝔽(remainder)を返す。
Note 1

CおよびC++では、remainder演算子はintegral operandsのみを受け入れます。ECMAScriptでは、floating-point operandsも受け入れます。

Note 2
%演算子によって計算されるfloating-point remainder操作の結果は、IEEE 754-2019で定義される“remainder”操作と同じではありません。IEEE 754-2019の“remainder”操作は、truncating divisionではなくrounding divisionからremainderを計算するため、その振る舞いは通常のinteger remainder演算子の振る舞いとは類似していません。その代わり、ECMAScript言語はfloating-point操作上の%を、Javaのinteger remainder演算子に類似した方法で振る舞うよう定義します。これはCライブラリ関数fmodと比較され得ます。

6.1.6.1.7 Number::add ( x, y )

The abstract operation Number::add takes arguments x (a Number) and y (a Number) and returns a Number. IEEE 754-2019 binary double-precision arithmeticの規則に従って加算を実行し、そのargumentsの和を生成します。 It performs the following steps when called:

  1. xNaNまたはyNaNなら、NaNを返す。
  2. x+∞𝔽かつy-∞𝔽なら、NaNを返す。
  3. x-∞𝔽かつy+∞𝔽なら、NaNを返す。
  4. x+∞𝔽または-∞𝔽のいずれかなら、xを返す。
  5. y+∞𝔽または-∞𝔽のいずれかなら、yを返す。
  6. Assert: xyはともにfiniteである。
  7. x-0𝔽かつy-0𝔽なら、-0𝔽を返す。
  8. 𝔽((x) + (y))を返す。
Note

有限精度の加算は可換ですが、常に結合的であるとは限りません。

6.1.6.1.8 Number::subtract ( x, y )

The abstract operation Number::subtract takes arguments x (a Number) and y (a Number) and returns a Number. 減算を実行し、そのオペランドの差を生成します。xはminuendであり、yはsubtrahendです。 It performs the following steps when called:

  1. Number::add(x, Number::unaryMinus(y))を返す。
Note

x - yは常にx + (-y)と同じ結果を生成します。

6.1.6.1.9 Number::leftShift ( x, y )

The abstract operation Number::leftShift takes arguments x (a Number) and y (a Number) and returns an integral Number. It performs the following steps when called:

  1. leftNumberを ! ToInt32(x) とする。
  2. rightNumberを ! ToUint32(y) とする。
  3. shiftCount(rightNumber) modulo 32とする。
  4. leftNumbershiftCountビット左シフトした結果を返す。結果のmathematical valueは32ビットtwo's complement bit stringとして正確に表現可能です。

6.1.6.1.10 Number::signedRightShift ( x, y )

The abstract operation Number::signedRightShift takes arguments x (a Number) and y (a Number) and returns an integral Number. It performs the following steps when called:

  1. leftNumberを ! ToInt32(x) とする。
  2. rightNumberを ! ToUint32(y) とする。
  3. shiftCount(rightNumber) modulo 32とする。
  4. leftNumbershiftCountビットだけsign-extending right shiftした結果を返す。最上位ビットが伝播されます。結果のmathematical valueは32ビットtwo's complement bit stringとして正確に表現可能です。

6.1.6.1.11 Number::unsignedRightShift ( x, y )

The abstract operation Number::unsignedRightShift takes arguments x (a Number) and y (a Number) and returns an integral Number. It performs the following steps when called:

  1. leftNumberを ! ToUint32(x) とする。
  2. rightNumberを ! ToUint32(y) とする。
  3. shiftCount(rightNumber) modulo 32とする。
  4. leftNumbershiftCountビットだけzero-filling right shiftした結果を返す。空いたビットはゼロで埋められます。結果のmathematical valueは32ビットunsigned bit stringとして正確に表現可能です。

6.1.6.1.12 Number::lessThan ( x, y )

The abstract operation Number::lessThan takes arguments x (a Number) and y (a Number) and returns a Boolean or undefined. It performs the following steps when called:

  1. xNaNなら、undefinedを返す。
  2. yNaNなら、undefinedを返す。
  3. xyなら、falseを返す。
  4. x+0𝔽かつy-0𝔽なら、falseを返す。
  5. x-0𝔽かつy+0𝔽なら、falseを返す。
  6. x+∞𝔽なら、falseを返す。
  7. y+∞𝔽なら、trueを返す。
  8. y-∞𝔽なら、falseを返す。
  9. x-∞𝔽なら、trueを返す。
  10. Assert: xyfiniteである。
  11. (x) < (y)なら、trueを返す。
  12. falseを返す。

6.1.6.1.13 Number::equal ( x, y )

The abstract operation Number::equal takes arguments x (a Number) and y (a Number) and returns a Boolean. It performs the following steps when called:

  1. xNaNなら、falseを返す。
  2. yNaNなら、falseを返す。
  3. xyなら、trueを返す。
  4. x+0𝔽かつy-0𝔽なら、trueを返す。
  5. x-0𝔽かつy+0𝔽なら、trueを返す。
  6. falseを返す。

6.1.6.1.14 Number::sameValue ( x, y )

The abstract operation Number::sameValue takes arguments x (a Number) and y (a Number) and returns a Boolean. It performs the following steps when called:

  1. xNaNかつyNaNなら、trueを返す。
  2. x+0𝔽かつy-0𝔽なら、falseを返す。
  3. x-0𝔽かつy+0𝔽なら、falseを返す。
  4. xyなら、trueを返す。
  5. falseを返す。

6.1.6.1.15 Number::sameValueZero ( x, y )

The abstract operation Number::sameValueZero takes arguments x (a Number) and y (a Number) and returns a Boolean. It performs the following steps when called:

  1. xNaNかつyNaNなら、trueを返す。
  2. x+0𝔽かつy-0𝔽なら、trueを返す。
  3. x-0𝔽かつy+0𝔽なら、trueを返す。
  4. xyなら、trueを返す。
  5. falseを返す。

6.1.6.1.16 NumberBitwiseOp ( op, x, y )

The abstract operation NumberBitwiseOp takes arguments op (&, ^, or |), x (a Number), and y (a Number) and returns an integral Number. It performs the following steps when called:

  1. leftNumberを ! ToInt32(x) とする。
  2. rightNumberを ! ToInt32(y) とする。
  3. leftBits(leftNumber)を表す32ビットtwo's complement bit stringとする。
  4. rightBits(rightNumber)を表す32ビットtwo's complement bit stringとする。
  5. op&なら、
    1. resultleftBitsおよびrightBitsにbitwise AND操作を適用した結果とする。
  6. そうでなく、op^なら、
    1. resultleftBitsおよびrightBitsにbitwise exclusive OR(XOR)操作を適用した結果とする。
  7. そうでなければ、
    1. Assert: op|である。
    2. resultleftBitsおよびrightBitsにbitwise inclusive OR操作を適用した結果とする。
  8. 32ビットtwo's complement bit string resultによって表されるintegerのNumber valueを返す。

6.1.6.1.17 Number::bitwiseAND ( x, y )

The abstract operation Number::bitwiseAND takes arguments x (a Number) and y (a Number) and returns an integral Number. It performs the following steps when called:

  1. NumberBitwiseOp(&, x, y)を返す。

6.1.6.1.18 Number::bitwiseXOR ( x, y )

The abstract operation Number::bitwiseXOR takes arguments x (a Number) and y (a Number) and returns an integral Number. It performs the following steps when called:

  1. NumberBitwiseOp(^, x, y)を返す。

6.1.6.1.19 Number::bitwiseOR ( x, y )

The abstract operation Number::bitwiseOR takes arguments x (a Number) and y (a Number) and returns an integral Number. It performs the following steps when called:

  1. NumberBitwiseOp(|, x, y)を返す。

6.1.6.1.20 Number::toString ( x, radix )

The abstract operation Number::toString takes arguments x (a Number) and radix (an integer in the inclusive interval from 2 to 36) and returns a String. radixを基数とする位取り記数法を使用してxをStringとして表します。基数rを使用する数の表現に用いられるdigitsは、"0123456789abcdefghijklmnopqrstuvwxyz"の最初のr個のコード単位から順に取られます。大きさが1𝔽以上の数の表現は、leading zeroesを決して含みません。 It performs the following steps when called:

  1. xNaNなら、"NaN"を返す。
  2. x+0𝔽または-0𝔽のいずれかなら、"0"を返す。
  3. x < -0𝔽なら、"-"Number::toString(-x, radix)のstring-concatenationを返す。
  4. x+∞𝔽なら、"Infinity"を返す。
  5. nk、およびsを、k ≥ 1、radixk - 1s < radixk𝔽(s × radixn - k) がxであり、かつkが可能な限り小さいようなintegersとする。kradixを用いるsの表現内のdigitsの数であり、sradixで割り切れず、sの最下位digitはこれらの基準によって必ずしも一意に決定されないことに注意。
  6. radix ≠ 10またはnが-5から21までの包含区間内にあるなら、
    1. nkなら、
      1. 以下のstring-concatenationを返す:
        • radixを使用するsの表現のk個のdigitsのコード単位
        • コード単位0x0030(DIGIT ZERO)のn - k回の出現
    2. n > 0なら、
      1. 以下のstring-concatenationを返す:
        • radixを使用するsの表現の最上位n個のdigitsのコード単位
        • コード単位0x002E(FULL STOP)
        • radixを使用するsの表現の残りのk - n個のdigitsのコード単位
    3. Assert: n ≤ 0。
    4. 以下のstring-concatenationを返す:
      • コード単位0x0030(DIGIT ZERO)
      • コード単位0x002E(FULL STOP)
      • コード単位0x0030(DIGIT ZERO)の-n回の出現
      • radixを使用するsの表現のk個のdigitsのコード単位
  7. NOTE: この場合、入力は1.2e+3のような科学的E記法を使用して表されます。
  8. Assert: radixは10である。
  9. n < 0なら、
    1. exponentSignをコード単位0x002D(HYPHEN-MINUS)とする。
  10. そうでなければ、
    1. exponentSignをコード単位0x002B(PLUS SIGN)とする。
  11. k = 1なら、
    1. 以下のstring-concatenationを返す:
      • sの単一digitのコード単位
      • コード単位0x0065(LATIN SMALL LETTER E)
      • exponentSign
      • abs(n - 1)の10進表現のコード単位
  12. 以下のstring-concatenationを返す:
    • sの10進表現の最上位digitのコード単位
    • コード単位0x002E(FULL STOP)
    • sの10進表現の残りのk - 1個のdigitsのコード単位
    • コード単位0x0065(LATIN SMALL LETTER E)
    • exponentSign
    • abs(n - 1)の10進表現のコード単位
Note 1

以下の観察は実装の指針として有用である場合がありますが、この標準の規範的要件の一部ではありません:

  • xが-0𝔽以外の任意のNumber値である場合、ToNumber(ToString(x))はxです。
  • sの最下位digitは、ステップ5に列挙された要件によって常に一意に決定されるとは限りません。
Note 2

上記の規則で要求されるより正確な変換を提供する実装については、ステップ5の以下の代替版を指針として使用することが推奨されます:

  1. nk、およびsを、k ≥ 1、radixk - 1s < radixk𝔽(s × radixn - k) がxであり、かつkが可能な限り小さいようなintegersとする。sに複数の可能性がある場合、s × radixn - k(x)に最も近くなるようにsを選ぶ。そのようなsの値が2つある場合、偶数であるものを選ぶ。kradixを使用するsの表現内のdigitsの数であり、sradixで割り切れないことに注意。
Note 3

ECMAScriptの実装者は、floating-point numbersのbinary-to-decimal変換についてDavid M. Gayが書いた論文およびコードを有用と感じるかもしれません:

Gay, David M. Correctly Rounded Binary-Decimal and Decimal-Binary Conversions. Numerical Analysis, Manuscript 90-10. AT&T Bell Laboratories (Murray Hill, New Jersey). 30 November 1990. Available as
https://ampl.com/_archive/first-website/REFS/rounding.pdf. Associated code available as
http://netlib.sandia.gov/fp/dtoa.c and as
http://netlib.sandia.gov/fp/g_fmt.c and may also be found at the various netlib mirror sites.

6.1.6.2 BigInt型

BigInt型integer値を表します。その値は任意の大きさであってよく、特定のbit-widthに制限されません。一般に、別途注記されない限り、操作は正確な数学的答えを返すように設計されています。二項操作では、BigIntsはtwo's complement binary stringsとして振る舞い、負の数は左側に無限にbitsが設定されているものとして扱われます。

6.1.6.2.1 BigInt::unaryMinus ( bigint )

The abstract operation BigInt::unaryMinus takes argument bigint (a BigInt) and returns a BigInt. It performs the following steps when called:

  1. bigint = 0なら、0を返す。
  2. -bigintを返す。

6.1.6.2.2 BigInt::bitwiseNOT ( bigint )

The abstract operation BigInt::bitwiseNOT takes argument bigint (a BigInt) and returns a BigInt. bigintのone's complementを返します。 It performs the following steps when called:

  1. -bigint - 1を返す。

6.1.6.2.3 BigInt::exponentiate ( base, exponent )

The abstract operation BigInt::exponentiate takes arguments base (a BigInt) and exponent (a BigInt) and returns either a normal completion containing a BigInt or a throw completion. It performs the following steps when called:

  1. exponent < 0なら、RangeError例外をthrowする。
  2. base = 0かつexponent = 0なら、1を返す。
  3. baseexponent乗したものを返す。

6.1.6.2.4 BigInt::multiply ( x, y )

The abstract operation BigInt::multiply takes arguments x (a BigInt) and y (a BigInt) and returns a BigInt. It performs the following steps when called:

  1. x × yを返す。
Note
結果が入力よりはるかに大きなbit widthを持つ場合でも、正確な数学的答えが与えられます。

6.1.6.2.5 BigInt::divide ( x, y )

The abstract operation BigInt::divide takes arguments x (a BigInt) and y (a BigInt) and returns either a normal completion containing a BigInt or a throw completion. It performs the following steps when called:

  1. y = 0なら、RangeError例外をthrowする。
  2. quotient(x) / (y)とする。
  3. (truncate(quotient))を返す。

6.1.6.2.6 BigInt::remainder ( numerator, denominator )

The abstract operation BigInt::remainder takes arguments numerator (a BigInt) and denominator (a BigInt) and returns either a normal completion containing a BigInt or a throw completion. It performs the following steps when called:

  1. denominator = 0なら、RangeError例外をthrowする。
  2. numerator = 0なら、0を返す。
  3. quotient(numerator) / (denominator)とする。
  4. truncatedQuotient(truncate(quotient))とする。
  5. numerator - (denominator × truncatedQuotient)を返す。
Note
結果の符号はdividendの符号です。

6.1.6.2.7 BigInt::add ( x, y )

The abstract operation BigInt::add takes arguments x (a BigInt) and y (a BigInt) and returns a BigInt. It performs the following steps when called:

  1. x + yを返す。

6.1.6.2.8 BigInt::subtract ( x, y )

The abstract operation BigInt::subtract takes arguments x (a BigInt) and y (a BigInt) and returns a BigInt. It performs the following steps when called:

  1. x - yを返す。

6.1.6.2.9 BigInt::leftShift ( x, y )

The abstract operation BigInt::leftShift takes arguments x (a BigInt) and y (a BigInt) and returns a BigInt. It performs the following steps when called:

  1. y < 0なら、
    1. (floor((x) / 2-(y)))を返す。
  2. x × 2yを返す。
Note
ここでの意味論は、BigIntを無限長のbinary two's complement digitsの文字列として扱うbitwise shiftと等価であるべきです。

6.1.6.2.10 BigInt::signedRightShift ( x, y )

The abstract operation BigInt::signedRightShift takes arguments x (a BigInt) and y (a BigInt) and returns a BigInt. It performs the following steps when called:

  1. BigInt::leftShift(x, -y)を返す。

6.1.6.2.11 BigInt::unsignedRightShift ( x, y )

The abstract operation BigInt::unsignedRightShift takes arguments x (a BigInt) and y (a BigInt) and returns a throw completion. It performs the following steps when called:

  1. TypeError例外をthrowする。

6.1.6.2.12 BigInt::lessThan ( x, y )

The abstract operation BigInt::lessThan takes arguments x (a BigInt) and y (a BigInt) and returns a Boolean. It performs the following steps when called:

  1. (x) < (y)なら、trueを返す。
  2. falseを返す。

6.1.6.2.13 BigInt::equal ( x, y )

The abstract operation BigInt::equal takes arguments x (a BigInt) and y (a BigInt) and returns a Boolean. It performs the following steps when called:

  1. (x) = (y)なら、trueを返す。
  2. falseを返す。

6.1.6.2.14 BinaryAnd ( x, y )

The abstract operation BinaryAnd takes arguments x (0 or 1) and y (0 or 1) and returns 0 or 1. It performs the following steps when called:

  1. x = 1かつy = 1なら、1を返す。
  2. 0を返す。

6.1.6.2.15 BinaryOr ( x, y )

The abstract operation BinaryOr takes arguments x (0 or 1) and y (0 or 1) and returns 0 or 1. It performs the following steps when called:

  1. x = 1またはy = 1なら、1を返す。
  2. 0を返す。

6.1.6.2.16 BinaryXor ( x, y )

The abstract operation BinaryXor takes arguments x (0 or 1) and y (0 or 1) and returns 0 or 1. It performs the following steps when called:

  1. x = 1かつy = 0なら、1を返す。
  2. x = 0かつy = 1なら、1を返す。
  3. 0を返す。

6.1.6.2.17 BigIntBitwiseOp ( op, x, y )

The abstract operation BigIntBitwiseOp takes arguments op (&, ^, or |), x (a BigInt), and y (a BigInt) and returns a BigInt. It performs the following steps when called:

  1. x(x)に設定する。
  2. y(y)に設定する。
  3. resultを0とする。
  4. shiftを0とする。
  5. (x = 0またはx = -1)かつ(y = 0またはy = -1)になるまで、繰り返す
    1. xDigitx modulo 2とする。
    2. yDigity modulo 2とする。
    3. op&なら、
      1. resultresult + 2shift × BinaryAnd(xDigit, yDigit)に設定する。
    4. そうでなく、op|なら、
      1. resultresult + 2shift × BinaryOr(xDigit, yDigit)に設定する。
    5. そうでなければ、
      1. Assert: op^である。
      2. resultresult + 2shift × BinaryXor(xDigit, yDigit)に設定する。
    6. shiftshift + 1に設定する。
    7. xを(x - xDigit) / 2に設定する。
    8. yを(y - yDigit) / 2に設定する。
  6. op&なら、
    1. signBitBinaryAnd(x modulo 2, y modulo 2)とする。
  7. そうでなく、op|なら、
    1. signBitBinaryOr(x modulo 2, y modulo 2)とする。
  8. そうでなければ、
    1. Assert: op^である。
    2. signBitBinaryXor(x modulo 2, y modulo 2)とする。
  9. signBit ≠ 0なら、
    1. resultresult - 2shiftに設定する。
    2. NOTE: これは符号を拡張します。
  10. resultのBigInt valueを返す。

6.1.6.2.18 BigInt::bitwiseAND ( x, y )

The abstract operation BigInt::bitwiseAND takes arguments x (a BigInt) and y (a BigInt) and returns a BigInt. It performs the following steps when called:

  1. BigIntBitwiseOp(&, x, y)を返す。

6.1.6.2.19 BigInt::bitwiseXOR ( x, y )

The abstract operation BigInt::bitwiseXOR takes arguments x (a BigInt) and y (a BigInt) and returns a BigInt. It performs the following steps when called:

  1. BigIntBitwiseOp(^, x, y)を返す。

6.1.6.2.20 BigInt::bitwiseOR ( x, y )

The abstract operation BigInt::bitwiseOR takes arguments x (a BigInt) and y (a BigInt) and returns a BigInt. It performs the following steps when called:

  1. BigIntBitwiseOp(|, x, y)を返す。

6.1.6.2.21 BigInt::toString ( x, radix )

The abstract operation BigInt::toString takes arguments x (a BigInt) and radix (an integer in the inclusive interval from 2 to 36) and returns a String. radixを基数とする位取り記数法を使用してxをStringとして表します。基数rを使用するBigIntの表現に用いられるdigitsは、"0123456789abcdefghijklmnopqrstuvwxyz"の最初のr個のコード単位から順に取られます。0以外のBigIntsの表現は、leading zeroesを決して含みません。 It performs the following steps when called:

  1. x < 0なら、"-"BigInt::toString(-x, radix)のstring-concatenationを返す。
  2. radixを使用するxの表現からなるString値を返す。

6.1.7 Object型

Object型の各インスタンス(単に“Object”とも呼ばれる)は、プロパティの集合を表します。各プロパティは、data propertyまたはaccessor propertyのいずれかです:

  • data propertyは、キー値をECMAScript言語値およびBoolean属性の集合に関連付けます。
  • accessor propertyは、キー値を1つまたは2つのaccessor functions、およびBoolean属性の集合に関連付けます。accessor functionsは、そのプロパティに関連付けられたECMAScript言語値を格納または取得するために使用されます。

オブジェクトのプロパティは、property keysを使用して一意に識別されます。property keyは、StringまたはSymbolのいずれかです。空のStringを含め、すべてのStringsおよびSymbolsはproperty keysとして有効です。property nameは、Stringであるproperty keyです。

integer indexは、CanonicalNumericIndexString(n)が+0𝔽から𝔽(253 - 1)までの包含区間内のintegral Numberを返すようなproperty name nです。array indexは、CanonicalNumericIndexString(n)が+0𝔽から𝔽(232 - 2)までの包含区間内のintegral Numberを返すようなinteger index nです。

Note

すべての非負のsafe integerには、対応するinteger indexがあります。232 - 1を除くすべての32ビット符号なし整数には、対応するarray indexがあります。"-0"integer indexでもarray indexでもありません。

Property keysは、プロパティおよびその値へアクセスするために使用されます。プロパティへのアクセスには2種類あります:値の取得および代入にそれぞれ対応するgetおよびsetです。getおよびsetアクセスを通じてアクセス可能なプロパティには、オブジェクトの直接の一部であるown propertiesと、プロパティ継承関係を通じて別の関連付けられたオブジェクトによって提供されるinherited propertiesの両方が含まれます。Inherited propertiesは、その関連付けられたオブジェクトのown propertiesまたはinherited propertiesのいずれであってもよいです。オブジェクトの各own propertyは、そのオブジェクトの他のown propertiesのキー値とは異なるキー値をそれぞれ持たなければなりません。

すべてのオブジェクトは論理的にはプロパティの集合ですが、そのプロパティへのアクセスおよび操作の意味論が異なる複数の形式のオブジェクトがあります。複数の形式のオブジェクトの定義については、6.1.7.2を参照してください。

加えて、一部のオブジェクトはcallableです。これらはfunctionsまたはfunction objectsと呼ばれ、以下でさらに説明されます。ECMAScriptにおけるすべてのfunctionsはObject型のメンバーです。

6.1.7.1 プロパティ属性

属性は、この仕様において、Table 3に記述されるObjectプロパティの状態を定義し説明するために使用されます。明示的に指定されない限り、各属性の初期値はそのDefault Valueです。

Table 3: Attributes of an Object property
属性名 それが存在するプロパティの種類 値のドメイン Default Value 説明
[[Value]] data property ECMAScript言語値 undefined プロパティのgetアクセスによって取得される値。
[[Writable]] data property Boolean false falseの場合、ECMAScriptコードが[[Set]]を使用してそのプロパティの[[Value]]属性を変更しようとしても成功しません。
[[Get]] accessor property Objectまたはundefined undefined 値がObjectである場合、それはfunction objectでなければなりません。プロパティのgetアクセスが実行されるたびに、プロパティ値を取得するため、空のarguments listでそのfunctionの[[Call]] internal method(Table 5)が呼び出されます。
[[Set]] accessor property Objectまたはundefined undefined 値がObjectである場合、それはfunction objectでなければなりません。プロパティのsetアクセスが実行されるたびに、代入された値を唯一のargumentとして含むarguments listでそのfunctionの[[Call]] internal method(Table 5)が呼び出されます。プロパティの[[Set]] internal methodの効果は、そのプロパティの[[Get]] internal methodへの後続の呼び出しによって返される値に影響を及ぼすことがありますが、必須ではありません。
[[Enumerable]] data propertyまたはaccessor property Boolean false trueの場合、そのプロパティはfor-in列挙(14.7.5を参照)によって列挙されます。そうでない場合、そのプロパティはnon-enumerableであると言われます。
[[Configurable]] data propertyまたはaccessor property Boolean false falseの場合、そのプロパティを削除したり、data propertyからaccessor propertyへ、またはaccessor propertyからdata propertyへ変更したり、その属性に変更を加えたり(既存の[[Value]]を置き換えること、または[[Writable]]falseに設定することを除く)しようとしても失敗します。

6.1.7.2 Object Internal Methods and Internal Slots

ECMAScriptにおけるオブジェクトの実際の意味論は、internal methodsと呼ばれるアルゴリズムを通じて指定されます。ECMAScriptエンジン内の各オブジェクトは、その実行時の振る舞いを定義するinternal methodsの集合に関連付けられています。これらのinternal methodsはECMAScript言語の一部ではありません。これらは、この仕様によって説明目的でのみ定義されます。しかし、ECMAScriptの実装内の各オブジェクトは、それに関連付けられたinternal methodsによって指定されるとおりに振る舞わなければなりません。これが実現される正確な方法は実装によって決定されます。

Internal method namesは多態的です。これは、共通のinternal method nameが異なるオブジェクト値に対して呼び出されたとき、それらが異なるアルゴリズムを実行し得ることを意味します。internal methodが呼び出される実際のオブジェクトは、その呼び出しの“target”です。実行時に、あるアルゴリズムの実装が、そのオブジェクトがサポートしていないinternal methodを使用しようとした場合、TypeError例外がthrowされます。

Internal slotsは、オブジェクト、Symbols、またはPrivate Namesに関連付けられ、さまざまなECMAScript仕様アルゴリズムによって使用される内部状態に対応します。Internal slotsはオブジェクトのプロパティではなく、継承されません。特定のinternal slot仕様に応じて、そのような状態は任意のECMAScript言語型の値、または特定のECMAScript仕様型の値で構成される場合があります。明示的に別途指定されない限り、internal slotsはオブジェクト、Symbol、またはPrivate Nameを作成する過程の一部として割り当てられ、動的に追加されることはありません。別途指定されない限り、internal slotの初期値は値undefinedです。この仕様内のさまざまなアルゴリズムは、internal slotsを持つ値を作成します。しかし、ECMAScript言語はinternal slotsを操作する直接の方法を提供しません。

すべてのオブジェクトは[[PrivateElements]]という名前のinternal slotを持ち、これはPrivateElementsListです。このListは、そのオブジェクトのprivate fields、methods、およびaccessorsの値を表します。初期状態では、空のListです。

Internal methodsおよびinternal slotsは、この仕様内では二重角括弧[[ ]]で囲まれた名前を使用して識別されます。

Table 4は、この仕様で使用され、ECMAScriptコードによって作成または操作されるすべてのオブジェクトに適用可能なessential internal methodsを要約します。すべてのオブジェクトは、すべてのessential internal methodsについてアルゴリズムを持たなければなりません。しかし、すべてのオブジェクトがそれらのメソッドについて同じアルゴリズムを使用するとは限りません。

ordinary objectは、以下のすべての基準を満たすオブジェクトです:

  • Table 4に列挙されるinternal methodsについて、そのオブジェクトは10.1で定義されるものを使用します。
  • そのオブジェクトが[[Call]] internal methodを持つ場合、10.2.1で定義されるもの、または10.3.1で定義されるもののいずれかを使用します。
  • そのオブジェクトが[[Construct]] internal methodを持つ場合、10.2.2で定義されるもの、または10.3.2で定義されるもののいずれかを使用します。

exotic objectは、ordinary objectではないオブジェクトです。

この仕様は、exotic objectsの異なる種類を、それらのオブジェクトのinternal methodsによって認識します。特定の種類のexotic objectArray exotic objectbound function exotic objectなど)と振る舞い上は等価であるが、その種類について指定されたinternal methodsの同じ集合を持たないオブジェクトは、その種類のexotic objectとして認識されません。

Table 4および他の同様の表の“Signature”列は、各internal methodの呼び出しパターンを記述します。呼び出しパターンは常に、説明的なparameter namesの括弧付きリストを含みます。parameter nameがECMAScript型名と同じである場合、その名前はparameter値の必要な型を記述します。internal methodが明示的に値を返す場合、そのparameter listの後に記号“→”および返される値の型名が続きます。signaturesで使用される型名は、6節で定義される型に、以下の追加名を加えたものを指します。“any”は、その値が任意のECMAScript言語型であってよいことを意味します。

internal methodは、そのparametersに加えて、常にそのmethod invocationのtargetであるオブジェクトへアクセスできます。

internal methodは暗黙的にCompletion Recordを返します。これは、その呼び出しパターンに示された戻り型の値を包むnormal completion、またはthrow completionのいずれかです。

Table 4: Essential Internal Methods
Internal Method Signature 説明
[[GetPrototypeOf]] ( ) Object | Null このオブジェクトにinherited propertiesを提供するオブジェクトを決定します。null値は、inherited propertiesが存在しないことを示します。
[[SetPrototypeOf]] (Object | Null) Boolean このオブジェクトを、inherited propertiesを提供する別のオブジェクトに関連付けます。nullを渡すことは、inherited propertiesが存在しないことを示します。操作が正常に完了したことを示すtrue、または操作が成功しなかったことを示すfalseを返します。
[[IsExtensible]] ( ) Boolean このオブジェクトに追加のプロパティを加えることが許可されているかどうかを決定します。
[[PreventExtensions]] ( ) Boolean このオブジェクトに新しいプロパティを追加できるかどうかを制御します。操作が成功した場合はtrue、操作が失敗した場合はfalseを返します。
[[GetOwnProperty]] (propertyKey) Undefined | Property Descriptor キーがpropertyKeyであるこのオブジェクトのown propertyについてProperty Descriptorを返すか、そのようなプロパティが存在しない場合はundefinedを返します。
[[DefineOwnProperty]] (propertyKey, propertyDesc) Boolean キーがpropertyKeyであるown propertyを作成または変更し、propertyDescによって記述される状態を持たせます。そのプロパティが正常に作成/更新された場合はtrueを返し、プロパティを作成または更新できなかった場合はfalseを返します。
[[HasProperty]] (propertyKey) Boolean このオブジェクトが、キーがpropertyKeyであるownまたはinherited propertyのいずれかを既に持っているかどうかを示すBoolean値を返します。
[[Get]] (propertyKey, receiver) any このオブジェクトから、キーがpropertyKeyであるプロパティの値を返します。プロパティ値を取得するために何らかのECMAScriptコードを実行する必要がある場合、receiverはそのコードを評価する際のthis値として使用されます。
[[Set]] (propertyKey, value, receiver) Boolean キーがpropertyKeyであるプロパティの値をvalueに設定します。プロパティ値を設定するために何らかのECMAScriptコードを実行する必要がある場合、receiverはそのコードを評価する際のthis値として使用されます。プロパティ値が設定された場合はtrue、設定できなかった場合はfalseを返します。
[[Delete]] (propertyKey) Boolean キーがpropertyKeyであるown propertyをこのオブジェクトから削除します。プロパティが削除されず、まだ存在している場合はfalseを返します。プロパティが削除された、または存在しない場合はtrueを返します。
[[OwnPropertyKeys]] ( ) List of property keys 要素がそのオブジェクトのすべてのown property keysであるListを返します。

Table 5は、functionsとして呼び出され得るオブジェクトによってサポートされる追加のessential internal methodsを要約します。function objectは、[[Call]] internal methodをサポートするオブジェクトです。constructorは、[[Construct]] internal methodをサポートするオブジェクトです。[[Construct]]をサポートするすべてのオブジェクトは[[Call]]をサポートしなければなりません。すなわち、すべてのconstructorfunction objectでなければなりません。したがって、constructorconstructor functionまたはconstructor function objectとも呼ばれ得ます。

Table 5: Additional Essential Internal Methods of Function Objects
Internal Method Signature 説明
[[Call]] (any, a List of any) any このオブジェクトに関連付けられたコードを実行します。function call expressionを通じて呼び出されます。internal methodへのargumentsは、this値と、call expressionによってfunctionに渡されたargumentsを要素とするListです。このinternal methodを実装するオブジェクトはcallableです。
[[Construct]] (a List of any, Object) Object オブジェクトを作成します。new演算子またはsuper呼び出しを通じて呼び出されます。internal methodへの最初のargumentは、constructor呼び出しまたはsuper呼び出しのargumentsを要素とするListです。2番目のargumentは、new演算子が最初に適用されたオブジェクトです。このinternal methodを実装するオブジェクトはconstructorsと呼ばれます。function objectは必ずしもconstructorではなく、そのようなnon-constructor function objects[[Construct]] internal methodを持ちません。

ordinary objectsおよびstandard exotic objectsについてのessential internal methodsの意味論は、10節で指定されます。exotic objectのinternal methodの指定された使用が実装によってサポートされない場合、その使用が試みられたときにTypeError例外をthrowしなければなりません。

6.1.7.3 Essential Internal Methodsの不変条件

ECMAScriptエンジンのObjectsのInternal Methodsは、以下で指定される不変条件の一覧に従わなければなりません。通常のECMAScript Objectsおよびこの仕様におけるすべてのstandard exotic objectsは、これらの不変条件を維持します。ECMAScript Proxy objectsは、[[ProxyHandler]]オブジェクト上で呼び出されるtrapsの結果に対するruntime checksによって、これらの不変条件を維持します。

実装が提供する任意のexotic objectsも、それらのオブジェクトについてこれらの不変条件を維持しなければなりません。これらの不変条件に違反すると、ECMAScriptコードが予測不能な振る舞いを示し、セキュリティ問題を生じさせる可能性があります。ただし、これらの不変条件への違反が実装のメモリ安全性を損なうことは決してあってはなりません。

実装は、その不変条件を強制せずにessential internal methodsの機能を実装する代替インターフェイスを提供するなど、いかなる方法でもこれらの不変条件が迂回されることを許してはなりません。

定義:

  • internal methodのtargetは、そのinternal methodが呼び出されるオブジェクトです。
  • targetは、その[[IsExtensible]] internal methodからfalseを返すこと、またはその[[PreventExtensions]] internal methodからtrueを返すことが観測されている場合、non-extensibleです。
  • non-existentプロパティは、non-extensible target上にown propertyとして存在しないプロパティです。
  • SameValueへのすべての参照は、SameValueアルゴリズムの定義に従います。

戻り値:

任意のinternal methodによって返される値は、以下のいずれかを持つCompletion Recordでなければなりません:

  • [[Type]] = normal[[Target]] = empty、および[[Value]] = そのinternal methodについて下に示される“normal return type”の値、または
  • [[Type]] = throw[[Target]] = empty、および[[Value]] = 任意のECMAScript言語値
Note 1

internal methodは、continue completionbreak completion、またはreturn completionを返してはなりません。

[[GetPrototypeOf]] ( )

  • normal return typeはObjectまたはNullのいずれかです。
  • targetがnon-extensibleであり、[[GetPrototypeOf]]が値protoを返す場合、[[GetPrototypeOf]]への将来の呼び出しはSameValueprotoとして返すべきです。
Note 2

オブジェクトのprototype chainは有限長であるべきです(すなわち、任意のオブジェクトから開始して、[[GetPrototypeOf]] internal methodをその結果に再帰的に適用すると、最終的に値nullに到達するべきです)。しかし、prototype chainに、[[GetPrototypeOf]]についてordinary object定義を使用しないexotic objectsが含まれる場合、この要件をオブジェクトレベルの不変条件として強制することはできません。そのような循環prototype chainは、オブジェクトプロパティへアクセスする際に無限ループをもたらす可能性があります。

[[SetPrototypeOf]] ( proto )

  • normal return typeはBooleanです。
  • targetがnon-extensibleである場合、protoがtargetの観測された[[GetPrototypeOf]]値とSameValueでない限り、[[SetPrototypeOf]]falseを返さなければなりません。

[[IsExtensible]] ( )

  • normal return typeはBooleanです。
  • [[IsExtensible]]falseを返す場合、target上の[[IsExtensible]]への将来のすべての呼び出しはfalseを返さなければなりません。

[[PreventExtensions]] ( )

  • normal return typeはBooleanです。
  • [[PreventExtensions]]trueを返す場合、target上の[[IsExtensible]]への将来のすべての呼び出しはfalseを返さなければならず、targetは現在non-extensibleと見なされます。

[[GetOwnProperty]] ( propertyKey )

  • normal return typeはProperty DescriptorまたはUndefinedのいずれかです。
  • 戻り値がProperty Descriptorである場合、それはfully populated Property Descriptorでなければなりません。
  • propertyKeyがnon-configurable、non-writable own data propertyとして記述される場合、[[GetOwnProperty]] ( propertyKey )への将来のすべての呼び出しは、[[Value]]propertyKey[[Value]]属性とSameValueであるProperty Descriptorを返さなければなりません。
  • [[Writable]]および[[Value]]以外のpropertyKeyの属性が時間の経過とともに変化し得る場合、またはそのプロパティが削除され得る場合、propertyKey[[Configurable]]属性はtrueでなければなりません。
  • [[Writable]]属性がfalseからtrueへ変化し得る場合、[[Configurable]]属性はtrueでなければなりません。
  • targetがnon-extensibleであり、propertyKeyがnon-existentである場合、target上の[[GetOwnProperty]] (propertyKey)への将来のすべての呼び出しは、propertyKeyをnon-existentとして記述しなければなりません(すなわち、[[GetOwnProperty]] (propertyKey)はundefinedを返さなければなりません)。
Note 3

3番目の不変条件の結果として、あるプロパティがdata propertyとして記述され、時間の経過とともに異なる値を返し得る場合、他のessential internal methodsを通じて値を変更する仕組みが公開されていない場合でも、[[Writable]]属性および[[Configurable]]属性のいずれか一方または両方がtrueでなければなりません。

[[DefineOwnProperty]] ( propertyKey, propertyDesc )

  • normal return typeはBooleanです。
  • propertyKeyが以前にtargetのnon-configurable own propertyとして観測されている場合、以下のいずれかでない限り、[[DefineOwnProperty]]falseを返さなければなりません:
    1. propertyKeyがwritable data propertyである。non-configurable writable data propertyは、non-configurable non-writable data propertyに変更できます。
    2. propertyDescのすべての属性がpropertyKeyの属性とSameValueである。
  • targetがnon-extensibleであり、propertyKeyがnon-existent own propertyである場合、[[DefineOwnProperty]] (propertyKey, propertyDesc)はfalseを返さなければなりません。すなわち、non-extensible target objectは新しいプロパティで拡張できません。

[[HasProperty]] ( propertyKey )

  • normal return typeはBooleanです。
  • propertyKeyが以前にtargetのnon-configurable own dataまたはaccessor propertyとして観測されている場合、[[HasProperty]]trueを返さなければなりません。

[[Get]] ( propertyKey, receiver )

  • normal return typeは任意のECMAScript言語型です。
  • propertyKeyが以前に、targetの値valueを持つnon-configurable、non-writable own data propertyとして観測されている場合、[[Get]]valueSameValueを返さなければなりません。
  • propertyKeyが以前に、[[Get]]属性がundefinedであるtargetのnon-configurable own accessor propertyとして観測されている場合、[[Get]]操作はundefinedを返さなければなりません。

[[Set]] ( propertyKey, value, receiver )

  • normal return typeはBooleanです。
  • propertyKeyが以前にtargetのnon-configurable、non-writable own data propertyとして観測されている場合、valuepropertyKey[[Value]]属性とSameValueでない限り、[[Set]]falseを返さなければなりません。
  • propertyKeyが以前に、[[Set]]属性がundefinedであるtargetのnon-configurable own accessor propertyとして観測されている場合、[[Set]]操作はfalseを返さなければなりません。

[[Delete]] ( propertyKey )

  • normal return typeはBooleanです。
  • propertyKeyが以前にtargetのnon-configurable own dataまたはaccessor propertyとして観測されている場合、[[Delete]]falseを返さなければなりません。

[[OwnPropertyKeys]] ( )

  • normal return typeはListです。
  • 返されるListは重複するentriesを含んではなりません。
  • 返されるListの各要素はproperty keyでなければなりません。
  • 返されるListは、以前に観測されたすべてのnon-configurable own propertiesのkeysを少なくとも含まなければなりません。
  • targetがnon-extensibleである場合、返されるListは、[[GetOwnProperty]]を使用して観測可能なtargetのすべてのown propertiesのkeysのみを含まなければなりません。

[[Call]] ( )

[[Construct]] ( )

  • normal return typeはObjectです。
  • targetは[[Call]] internal methodも持たなければなりません。

6.1.7.4 Well-Known Intrinsic Objects

well-known intrinsicsは、この仕様のアルゴリズムによって明示的に参照される組み込みオブジェクトであり、通常realm固有のidentityを持ちます。別途指定されない限り、各intrinsic objectは実際には、realmごとに1つずつ、類似したオブジェクトの集合に対応します。

この仕様内では、%name%のような参照は、current realmに関連付けられ、そのnameに対応するintrinsic objectを意味します。%name.a.b%のような参照は、ECMAScriptコードが評価される前にintrinsic object %name%の"a"プロパティの値の"b"プロパティにアクセスしたかのように意味します。current realmおよびそのintrinsicsの決定は9.4で記述されます。well-known intrinsicsはTable 6に列挙されます。

Table 6: よく知られた組込みオブジェクト
組込み名 グローバル名 ECMAScript 言語での関連付け
%AggregateError% "AggregateError" AggregateError コンストラクタ (20.5.7.1)
%Array% "Array" Array コンストラクタ (23.1.1)
%ArrayBuffer% "ArrayBuffer" ArrayBuffer コンストラクタ (25.1.4)
%ArrayIteratorPrototype% Array Iterator オブジェクトのプロトタイプ (23.1.5)
%AsyncDisposableStack% "AsyncDisposableStack" AsyncDisposableStack コンストラクタ (27.4.1)
%AsyncFromSyncIteratorPrototype% Async-from-Sync Iterator オブジェクトのプロトタイプ (27.1.5)
%AsyncFunction% async 関数オブジェクトのコンストラクタ (27.10.1)
%AsyncGeneratorFunction% async generator 関数オブジェクトのコンストラクタ (27.7.1)
%AsyncGeneratorPrototype% async generator オブジェクトのプロトタイプ (27.9)
%AsyncIteratorPrototype% すべての標準組込み async iterator オブジェクトが間接的に継承するオブジェクト
%Atomics% "Atomics" Atomics オブジェクト (25.4)
%BigInt% "BigInt" BigInt コンストラクタ (21.2.1)
%BigInt64Array% "BigInt64Array" BigInt64Array コンストラクタ (23.2)
%BigUint64Array% "BigUint64Array" BigUint64Array コンストラクタ (23.2)
%Boolean% "Boolean" Boolean コンストラクタ (20.3.1)
%DataView% "DataView" DataView コンストラクタ (25.3.2)
%Date% "Date" Date コンストラクタ (21.4.2)
%decodeURI% "decodeURI" decodeURI 関数 (19.2.6.1)
%decodeURIComponent% "decodeURIComponent" decodeURIComponent 関数 (19.2.6.2)
%DisposableStack% "DisposableStack" DisposableStack コンストラクタ (27.3.1)
%encodeURI% "encodeURI" encodeURI 関数 (19.2.6.3)
%encodeURIComponent% "encodeURIComponent" encodeURIComponent 関数 (19.2.6.4)
%Error% "Error" Error コンストラクタ (20.5.1)
%eval% "eval" eval 関数 (19.2.1)
%EvalError% "EvalError" EvalError コンストラクタ (20.5.5.1)
%FinalizationRegistry% "FinalizationRegistry" FinalizationRegistry コンストラクタ (26.2.1)
%Float16Array% "Float16Array" Float16Array コンストラクタ (23.2)
%Float32Array% "Float32Array" Float32Array コンストラクタ (23.2)
%Float64Array% "Float64Array" Float64Array コンストラクタ (23.2)
%ForInIteratorPrototype% For-In Iterator オブジェクトのプロトタイプ (14.7.5.10)
%Function% "Function" Function コンストラクタ (20.2.1)
%GeneratorFunction% generator 関数オブジェクトのコンストラクタ (27.6.1)
%GeneratorPrototype% generator オブジェクトのプロトタイプ (27.8)
%Int8Array% "Int8Array" Int8Array コンストラクタ (23.2)
%Int16Array% "Int16Array" Int16Array コンストラクタ (23.2)
%Int32Array% "Int32Array" Int32Array コンストラクタ (23.2)
%isFinite% "isFinite" isFinite 関数 (19.2.2)
%isNaN% "isNaN" isNaN 関数 (19.2.3)
%Iterator% "Iterator" Iterator コンストラクタ (27.1.3.1)
%IteratorHelperPrototype% Iterator Helper オブジェクトのプロトタイプ (27.1.2.1)
%JSON% "JSON" JSON オブジェクト (25.5)
%Map% "Map" Map コンストラクタ (24.1.1)
%MapIteratorPrototype% Map Iterator オブジェクトのプロトタイプ (24.1.5)
%Math% "Math" Math オブジェクト (21.3)
%Number% "Number" Number コンストラクタ (21.1.1)
%Object% "Object" Object コンストラクタ (20.1.1)
%parseFloat% "parseFloat" parseFloat 関数 (19.2.4)
%parseInt% "parseInt" parseInt 関数 (19.2.5)
%Promise% "Promise" Promise コンストラクタ (27.5.3)
%Proxy% "Proxy" Proxy コンストラクタ (28.2.1)
%RangeError% "RangeError" RangeError コンストラクタ (20.5.5.2)
%ReferenceError% "ReferenceError" ReferenceError コンストラクタ (20.5.5.3)
%Reflect% "Reflect" Reflect オブジェクト (28.1)
%RegExp% "RegExp" RegExp コンストラクタ (22.2.4)
%RegExpStringIteratorPrototype% RegExp String Iterator オブジェクトのプロトタイプ (22.2.9)
%Set% "Set" Set コンストラクタ (24.2.2)
%SetIteratorPrototype% Set Iterator オブジェクトのプロトタイプ (24.2.6)
%SharedArrayBuffer% "SharedArrayBuffer" SharedArrayBuffer コンストラクタ (25.2.3)
%String% "String" String コンストラクタ (22.1.1)
%StringIteratorPrototype% String Iterator オブジェクトのプロトタイプ (22.1.5)
%SuppressedError% "SuppressedError" SuppressedError コンストラクタ (20.5.8.1)
%Symbol% "Symbol" Symbol コンストラクタ (20.4.1)
%SyntaxError% "SyntaxError" SyntaxError コンストラクタ (20.5.5.4)
%ThrowTypeError% 無条件に %TypeError% の新しいインスタンスを投げる関数オブジェクト
%TypedArray% すべての typed Array コンストラクタのスーパークラス (23.2.1)
%TypeError% "TypeError" TypeError コンストラクタ (20.5.5.5)
%Uint8Array% "Uint8Array" Uint8Array コンストラクタ (23.2)
%Uint8ClampedArray% "Uint8ClampedArray" Uint8ClampedArray コンストラクタ (23.2)
%Uint16Array% "Uint16Array" Uint16Array コンストラクタ (23.2)
%Uint32Array% "Uint32Array" Uint32Array コンストラクタ (23.2)
%URIError% "URIError" URIError コンストラクタ (20.5.5.6)
%WeakMap% "WeakMap" WeakMap コンストラクタ (24.3.1)
%WeakRef% "WeakRef" WeakRef コンストラクタ (26.1.1)
%WeakSet% "WeakSet" WeakSet コンストラクタ (24.4.1)
%WrapForValidIteratorPrototype% Iterator.from によって返されるラップ済みイテレータオブジェクトのプロトタイプ (27.1.3.2.2.1)
Note

Table 103に追加のentriesがあります。

6.2 ECMAScript仕様型

仕様型は、ECMAScript言語構文およびECMAScript言語型の意味論を記述するためにアルゴリズム内で使用されるメタ値に対応します。仕様型には、Reference RecordListCompletion RecordProperty DescriptorEnvironment RecordAbstract Closure、およびData Blockが含まれます。仕様型値は、ECMAScript実装内の特定の実体に必ずしも対応しない仕様上の人工物です。仕様型値は、ECMAScript式評価の中間結果を記述するために使用される場合がありますが、そのような値をオブジェクトのプロパティやECMAScript言語変数の値として格納することはできません。

6.2.1 Enum仕様型

Enumsは、仕様内部の値であり、ECMAScriptコードから直接観測できません。Enumsはsans-serif書体を使用したupper kebab caseで表記されます。たとえば、Completion Record[[Type]]フィールドは、normalreturn、またはthrowのような値を取ります。Enumsはその名前以外の特徴を持ちません。enumの名前は、それを他のenumsと区別すること以外の目的を持たず、文脈におけるその使用法や意味について何も含意しません。

6.2.2 ListおよびRecord仕様型

List型は、new式、関数呼び出し、および単純な順序付き値リストが必要な他のアルゴリズムにおけるargument lists(13.3.8を参照)の評価を説明するために使用されます。List型の値は、個々の値を含むlist elementsの単純な順序列です。これらの列は任意の長さであってよいです。listの要素は、0-origin indicesを使用してランダムアクセスできます。表記上の便宜のため、List要素へアクセスするためにarray-like syntaxを使用できます。たとえば、args[2]はList argsの3rd要素を表す省略表現です。

アルゴリズムが順序を指定せずにListの要素を反復する場合、使用される順序はList内の要素の順序です。

この仕様内では、表記上の便宜のため、新しいList値を表現するためにliteral syntaxを使用できます。たとえば、« 1, 2 »は、それぞれ特定の値に初期化された2つの要素を持つList値を定義します。新しい空のListは« »として表現できます。

この仕様では、“A, B, ...のlist-concatenation”(各argumentが空であってもよいListである場合)という句は、各argumentの要素(順序どおり)の連結(順序どおり)を要素とする新しいList値を表します。

StringsのListに適用される場合、“lexicographic code unit orderに従ってソートされる”という句は、より短い文字列の長さまで各コード単位の数値でソートし、すべてが等しい場合はより短い文字列をより長い文字列の前にソートすることを意味します。これは抽象操作IsLessThanで記述されます。

Record型は、この仕様のアルゴリズム内のデータ集約を記述するために使用されます。Record型値は、1つ以上の名前付きフィールドで構成されます。各フィールドの値はECMAScript言語値または仕様値です。フィールド名は常に二重角括弧で囲まれます。たとえば[[Value]]です。

この仕様内では、表記上の便宜のため、Record値を表現するためにobject literal-like syntaxを使用できます。たとえば、{ [[Field1]]: 42, [[Field2]]: false, [[Field3]]: empty }は、それぞれ特定の値に初期化された3つのフィールドを持つRecord値を定義します。フィールド名の順序は重要ではありません。明示的に列挙されていないフィールドは存在しないものと見なされます。

仕様テキストおよびアルゴリズムでは、Record値の特定のフィールドを参照するためにdot notationを使用できます。たとえば、Rが前段落に示されたrecordである場合、R.[[Field2]]は“Rの[[Field2]]という名前のフィールド”を表す省略表現です。

一般的に使用されるRecordフィールドの組み合わせに対するSchemaには名前が付けられる場合があり、その名前は、記述されている特定の種類の集約を識別するためにliteral Record値の接頭辞として使用できます。例:PropertyDescriptor { [[Value]]: 42, [[Writable]]: false, [[Configurable]]: true }。

6.2.3 SetおよびRelation仕様型

Set型は、memory modelで使用するための順序なし要素の集合を説明するために使用されます。これは同じ名前のECMAScriptコレクション型とは異なります。曖昧さを避けるため、この仕様内ではECMAScriptコレクションのインスタンスは一貫して“Set objects”と呼ばれます。Set型の値は要素の単純な集合であり、同じ要素が複数回現れることはありません。要素はSetsへ追加されたり、Setsから削除されたりできます。Setsは互いにunion、intersection、またはsubtractionを行うことができます。

Relation型は、Sets上の制約を説明するために使用されます。Relation型の値は、その値域からの値の順序対のSetです。たとえば、Memory events上のRelationは、Memory eventsの順序対の集合です。Relation Rと、Rの値域内の2つの値aおよびbについて、a R bは、順序対(a, b)がRのメンバーであることを表す省略表現です。Relationは、ある条件に関して、その条件を満たす最小のRelationである場合、least Relationです。

strict partial orderは、以下を満たすRelation値Rです。

  • Rのdomain内のすべてのab、およびcについて:

    • a R aではなく、かつ
    • a R bかつb R cなら、a R cである。
Note 1

上記の2つの性質は、それぞれirreflexivityおよびtransitivityと呼ばれます。

strict total orderは、以下を満たすRelation値Rです。

  • Rのdomain内のすべてのab、およびcについて:

    • abである、またはa R bである、またはb R aであり、かつ
    • a R aではなく、かつ
    • a R bかつb R cなら、a R cである。
Note 2

上記の3つの性質は、それぞれtotality、irreflexivity、およびtransitivityと呼ばれます。

6.2.4 Completion Record仕様型

Completion Record仕様型は、値の実行時伝播および、制御の非局所的移動を行う文(breakcontinuereturnおよびthrow)の振る舞いなどの制御フローを説明するために使用されます。

Completion Recordsは、Table 7で定義されるフィールドを持ちます。

Table 7: Completion Record Fields
フィールド名 意味
[[Type]] normal, break, continue, return, or throw 発生したcompletionの種類。
[[Value]] Completion Recordを除く任意の値 生成された値。
[[Target]] Stringまたはempty directed control transfersのtarget label。

以下の省略用語は、Completion Recordsを参照するために使用されることがあります。

  • normal completionは、[[Type]]値がnormalである任意のCompletion Recordを指します。
  • break completionは、[[Type]]値がbreakである任意のCompletion Recordを指します。
  • continue completionは、[[Type]]値がcontinueである任意のCompletion Recordを指します。
  • return completionは、[[Type]]値がreturnである任意のCompletion Recordを指します。
  • throw completionは、[[Type]]値がthrowである任意のCompletion Recordを指します。
  • abrupt completionは、[[Type]]値がnormal以外である任意のCompletion Recordを指します。
  • ある型の値を含むnormal completionは、その[[Value]]フィールドにその型の値を持つnormal completionを指します。

この仕様で定義されるcallable objectsは、normal completionまたはthrow completionのみを返します。他の種類のCompletion Recordを返すことは編集上の誤りと見なされます。

Implementation-defined callable objectsは、normal completionまたはthrow completionのいずれかを返さなければなりません。

6.2.4.1 NormalCompletion ( value )

The abstract operation NormalCompletion takes argument value (any value except a Completion Record) and returns a normal completion. It performs the following steps when called:

  1. Completion Record { [[Type]]: normal, [[Value]]: value, [[Target]]: empty }を返す。

6.2.4.2 ThrowCompletion ( value )

The abstract operation ThrowCompletion takes argument value (an ECMAScript language value) and returns a throw completion. It performs the following steps when called:

  1. Completion Record { [[Type]]: throw, [[Value]]: value, [[Target]]: empty }を返す。

6.2.4.3 ReturnCompletion ( value )

The abstract operation ReturnCompletion takes argument value (an ECMAScript language value) and returns a return completion. It performs the following steps when called:

  1. Completion Record { [[Type]]: return, [[Value]]: value, [[Target]]: empty }を返す。

6.2.4.4 UpdateEmpty ( completionRecord, value )

The abstract operation UpdateEmpty takes arguments completionRecord (a Completion Record) and value (any value except a Completion Record) and returns a Completion Record. It performs the following steps when called:

  1. Assert: completionRecordreturn completionまたはthrow completionのいずれかであるなら、completionRecord.[[Value]]emptyではない。
  2. completionRecord.[[Value]]emptyでないなら、? completionRecordを返す。
  3. Completion Record { [[Type]]: completionRecord.[[Type]], [[Value]]: value, [[Target]]: completionRecord.[[Target]] }を返す。

6.2.5 Reference Record仕様型

Reference Record型は、deletetypeof、代入演算子、superキーワード、およびその他の言語機能のような演算子の振る舞いを説明するために使用されます。たとえば、代入の左辺オペランドはReference Recordを生成することが期待されます。

Reference Recordは、解決済みの名前または(まだ解決されていない可能性のある)プロパティ束縛です。そのフィールドはTable 8によって定義されます。

Table 8: Reference Record Fields
フィールド名 意味
[[Base]] ECMAScript言語値Environment Record、またはunresolvable 束縛を保持する値またはEnvironment Recordunresolvable[[Base]]は、その束縛を解決できなかったことを示します。
[[ReferencedName]] ECMAScript言語値またはPrivate Name 束縛の名前。[[Base]]値がEnvironment Recordである場合は常にStringです。そうでない場合、ToPropertyKeyが実行されるまでは、StringまたはSymbol以外のECMAScript言語値である場合があります。
[[Strict]] Boolean Reference Recordstrict mode codeに由来する場合はtrue、そうでない場合はfalse
[[ThisValue]] ECMAScript言語値またはempty emptyでない場合、そのReference Recordsuperキーワードを使用して表現されたプロパティ束縛を表します。これはSuper Reference Recordと呼ばれ、その[[Base]]値は決してEnvironment Recordにはなりません。この場合、[[ThisValue]]フィールドはReference Recordが作成された時点のthis値を保持します。

以下の抽象操作は、この仕様においてReference Recordsを操作するために使用されます:

6.2.5.1 IsPropertyReference ( refRecord )

The abstract operation IsPropertyReference takes argument refRecord (a Reference Record) and returns a Boolean. It performs the following steps when called:

  1. refRecord.[[Base]]unresolvableなら、falseを返す。
  2. refRecord.[[Base]]Environment Recordなら、falseを返す。
  3. trueを返す。

6.2.5.2 IsUnresolvableReference ( refRecord )

The abstract operation IsUnresolvableReference takes argument refRecord (a Reference Record) and returns a Boolean. It performs the following steps when called:

  1. refRecord.[[Base]]unresolvableなら、trueを返す。
  2. falseを返す。

6.2.5.3 IsSuperReference ( refRecord )

The abstract operation IsSuperReference takes argument refRecord (a Reference Record) and returns a Boolean. It performs the following steps when called:

  1. refRecord.[[ThisValue]]emptyなら、falseを返す。
  2. trueを返す。

6.2.5.4 IsPrivateReference ( refRecord )

The abstract operation IsPrivateReference takes argument refRecord (a Reference Record) and returns a Boolean. It performs the following steps when called:

  1. refRecord.[[ReferencedName]]Private Nameなら、trueを返す。
  2. falseを返す。

6.2.5.5 GetValue ( refRecord )

The abstract operation GetValue takes argument refRecord (a Reference Record or an ECMAScript language value) and returns either a normal completion containing an ECMAScript language value or an abrupt completion. It performs the following steps when called:

  1. refRecordReference Recordでないなら、refRecordを返す。
  2. IsUnresolvableReference(refRecord)がtrueなら、ReferenceError例外をthrowする。
  3. IsPropertyReference(refRecord)がtrueなら、
    1. baseObjを ? ToObject(refRecord.[[Base]]) とする。
    2. IsPrivateReference(refRecord)がtrueなら、
      1. PrivateGet(baseObj, refRecord.[[ReferencedName]])を返す。
    3. refRecord.[[ReferencedName]]property keyでないなら、
      1. refRecord.[[ReferencedName]]を ? ToPropertyKey(refRecord.[[ReferencedName]]) に設定する。
    4. baseObj.[[Get]](refRecord.[[ReferencedName]], GetThisValue(refRecord))を返す。
  4. baserefRecord.[[Base]]とする。
  5. Assert: baseEnvironment Recordである。
  6. base.GetBindingValue(refRecord.[[ReferencedName]], refRecord.[[Strict]])を返す(9.1を参照)。
Note

ステップ3.aで作成され得るオブジェクトは、上記の抽象操作およびordinary object [[Get]] internal methodの外部からはアクセスできません。実装は、そのオブジェクトの実際の作成を避けることを選択する場合があります。

6.2.5.6 PutValue ( refRecord, value )

The abstract operation PutValue takes arguments refRecord (a Reference Record or an ECMAScript language value) and value (an ECMAScript language value) and returns either a normal completion containing unused or an abrupt completion. It performs the following steps when called:

  1. refRecordReference Recordでないなら、ReferenceError例外をthrowする。
  2. IsUnresolvableReference(refRecord)がtrueなら、
    1. refRecord.[[Strict]]trueなら、ReferenceError例外をthrowする。
    2. globalObjGetGlobalObject()とする。
    3. Set(globalObj, refRecord.[[ReferencedName]], value, false)を実行する。
    4. unusedを返す。
  3. IsPropertyReference(refRecord)がtrueなら、
    1. baseObjを ? ToObject(refRecord.[[Base]]) とする。
    2. IsPrivateReference(refRecord)がtrueなら、
      1. PrivateSet(baseObj, refRecord.[[ReferencedName]], value)を返す。
    3. refRecord.[[ReferencedName]]property keyでないなら、
      1. refRecord.[[ReferencedName]]を ? ToPropertyKey(refRecord.[[ReferencedName]]) に設定する。
    4. succeededを ? baseObj.[[Set]](refRecord.[[ReferencedName]], value, GetThisValue(refRecord)) とする。
    5. succeededfalseかつrefRecord.[[Strict]]trueなら、TypeError例外をthrowする。
    6. unusedを返す。
  4. baserefRecord.[[Base]]とする。
  5. Assert: baseEnvironment Recordである。
  6. base.SetMutableBinding(refRecord.[[ReferencedName]], value, refRecord.[[Strict]])を返す(9.1を参照)。
Note

ステップ3.aで作成され得るオブジェクトは、上記の抽象操作およびordinary object [[Set]] internal methodの外部からはアクセスできません。実装は、そのオブジェクトの実際の作成を避けることを選択する場合があります。

6.2.5.7 GetThisValue ( refRecord )

The abstract operation GetThisValue takes argument refRecord (a Reference Record) and returns an ECMAScript language value. It performs the following steps when called:

  1. Assert: IsPropertyReference(refRecord)はtrueである。
  2. IsSuperReference(refRecord)がtrueなら、refRecord.[[ThisValue]]を返す。
  3. refRecord.[[Base]]を返す。

6.2.5.8 InitializeReferencedBinding ( refRecord, value )

The abstract operation InitializeReferencedBinding takes arguments refRecord (a Reference Record) and value (an ECMAScript language value) and returns either a normal completion containing unused or an abrupt completion. It performs the following steps when called:

  1. Assert: IsUnresolvableReference(refRecord)はfalseである。
  2. baserefRecord.[[Base]]とする。
  3. Assert: baseEnvironment Recordである。
  4. base.InitializeBinding(refRecord.[[ReferencedName]], value)を返す。

6.2.5.9 MakePrivateReference ( baseValue, privateIdentifier )

The abstract operation MakePrivateReference takes arguments baseValue (an ECMAScript language value) and privateIdentifier (a String) and returns a Reference Record. It performs the following steps when called:

  1. privateEnvrunning execution contextのPrivateEnvironmentとする。
  2. Assert: privateEnvnullでない。
  3. privateNameResolvePrivateIdentifier(privateEnv, privateIdentifier)とする。
  4. Reference Record { [[Base]]: baseValue, [[ReferencedName]]: privateName, [[Strict]]: true, [[ThisValue]]: empty }を返す。

6.2.6 Property Descriptor仕様型

Property Descriptor型は、Objectプロパティ属性の操作および具象化を説明するために使用されます。Property Descriptorは0個以上のフィールドを持つRecordであり、各フィールドの名前は属性名であり、その値は6.1.7.1で指定される対応する属性値です。この仕様内でProperty Descriptor recordsのliteral descriptionsにタグ付けするために使用されるschema nameは“PropertyDescriptor”です。

Property Descriptor値は、特定のフィールドの存在または使用に基づいて、data Property Descriptorsおよびaccessor Property Descriptorsにさらに分類される場合があります。data Property Descriptorは、[[Value]]または[[Writable]]という名前のフィールドのいずれかを含むものです。accessor Property Descriptorは、[[Get]]または[[Set]]という名前のフィールドのいずれかを含むものです。任意のProperty Descriptorは、[[Enumerable]]および[[Configurable]]という名前のフィールドを持つことができます。Property Descriptor値はdata Property Descriptorかつaccessor Property Descriptorの両方であってはなりません。ただし、どちらでもない場合があります(その場合、それはgeneric Property Descriptorです)。fully populated Property Descriptorは、accessor Property Descriptorまたはdata Property Descriptorのいずれかであり、Table 3で定義される対応するフィールドのすべてを持つものです。

以下の抽象操作は、この仕様においてProperty Descriptor値を操作するために使用されます:

6.2.6.1 IsAccessorDescriptor ( propertyDesc )

The abstract operation IsAccessorDescriptor takes argument propertyDesc (a Property Descriptor) and returns a Boolean. It performs the following steps when called:

  1. propertyDesc[[Get]]フィールドを持つなら、trueを返す。
  2. propertyDesc[[Set]]フィールドを持つなら、trueを返す。
  3. falseを返す。

6.2.6.2 IsDataDescriptor ( propertyDesc )

The abstract operation IsDataDescriptor takes argument propertyDesc (a Property Descriptor) and returns a Boolean. It performs the following steps when called:

  1. propertyDesc[[Value]]フィールドを持つなら、trueを返す。
  2. propertyDesc[[Writable]]フィールドを持つなら、trueを返す。
  3. falseを返す。

6.2.6.3 IsGenericDescriptor ( propertyDesc )

The abstract operation IsGenericDescriptor takes argument propertyDesc (a Property Descriptor) and returns a Boolean. It performs the following steps when called:

  1. IsAccessorDescriptor(propertyDesc)がtrueなら、falseを返す。
  2. IsDataDescriptor(propertyDesc)がtrueなら、falseを返す。
  3. trueを返す。

6.2.6.4 FromPropertyDescriptor ( propertyDesc )

The abstract operation FromPropertyDescriptor takes argument propertyDesc (a Property Descriptor or undefined) and returns an Object or undefined. It performs the following steps when called:

  1. propertyDescundefinedなら、undefinedを返す。
  2. objOrdinaryObjectCreate(%Object.prototype%)とする。
  3. Assert: objはown propertiesを持たないextensible ordinary objectである。
  4. propertyDesc[[Value]]フィールドを持つなら、
    1. CreateDataPropertyOrThrow(obj, "value", propertyDesc.[[Value]])を実行する。
  5. propertyDesc[[Writable]]フィールドを持つなら、
    1. CreateDataPropertyOrThrow(obj, "writable", propertyDesc.[[Writable]])を実行する。
  6. propertyDesc[[Get]]フィールドを持つなら、
    1. CreateDataPropertyOrThrow(obj, "get", propertyDesc.[[Get]])を実行する。
  7. propertyDesc[[Set]]フィールドを持つなら、
    1. CreateDataPropertyOrThrow(obj, "set", propertyDesc.[[Set]])を実行する。
  8. propertyDesc[[Enumerable]]フィールドを持つなら、
    1. CreateDataPropertyOrThrow(obj, "enumerable", propertyDesc.[[Enumerable]])を実行する。
  9. propertyDesc[[Configurable]]フィールドを持つなら、
    1. CreateDataPropertyOrThrow(obj, "configurable", propertyDesc.[[Configurable]])を実行する。
  10. objを返す。

6.2.6.5 ToPropertyDescriptor ( obj )

The abstract operation ToPropertyDescriptor takes argument obj (an ECMAScript language value) and returns either a normal completion containing a Property Descriptor or a throw completion. It performs the following steps when called:

  1. objがObjectでないなら、TypeError例外をthrowする。
  2. propertyDescを、初期状態でフィールドを持たない新しいProperty Descriptorとする。
  3. hasEnumerableを ? HasProperty(obj, "enumerable") とする。
  4. hasEnumerabletrueなら、
    1. enumerableToBoolean(? Get(obj, "enumerable"))とする。
    2. propertyDesc.[[Enumerable]]enumerableに設定する。
  5. hasConfigurableを ? HasProperty(obj, "configurable") とする。
  6. hasConfigurabletrueなら、
    1. configurableToBoolean(? Get(obj, "configurable"))とする。
    2. propertyDesc.[[Configurable]]configurableに設定する。
  7. hasValueを ? HasProperty(obj, "value") とする。
  8. hasValuetrueなら、
    1. valueを ? Get(obj, "value") とする。
    2. propertyDesc.[[Value]]valueに設定する。
  9. hasWritableを ? HasProperty(obj, "writable") とする。
  10. hasWritabletrueなら、
    1. writableToBoolean(? Get(obj, "writable"))とする。
    2. propertyDesc.[[Writable]]writableに設定する。
  11. hasGetを ? HasProperty(obj, "get") とする。
  12. hasGettrueなら、
    1. getterを ? Get(obj, "get") とする。
    2. IsCallable(getter)がfalseかつgetterundefinedでないなら、TypeError例外をthrowする。
    3. propertyDesc.[[Get]]getterに設定する。
  13. hasSetを ? HasProperty(obj, "set") とする。
  14. hasSettrueなら、
    1. setterを ? Get(obj, "set") とする。
    2. IsCallable(setter)がfalseかつsetterundefinedでないなら、TypeError例外をthrowする。
    3. propertyDesc.[[Set]]setterに設定する。
  15. propertyDesc[[Get]]フィールドを持つ、またはpropertyDesc[[Set]]フィールドを持つなら、
    1. propertyDesc[[Value]]フィールドを持つ、またはpropertyDesc[[Writable]]フィールドを持つなら、TypeError例外をthrowする。
  16. propertyDescを返す。

6.2.6.6 CompletePropertyDescriptor ( propertyDesc )

The abstract operation CompletePropertyDescriptor takes argument propertyDesc (a Property Descriptor) and returns unused. It performs the following steps when called:

  1. likeRecord { [[Value]]: undefined, [[Writable]]: false, [[Get]]: undefined, [[Set]]: undefined, [[Enumerable]]: false, [[Configurable]]: false }とする。
  2. IsGenericDescriptor(propertyDesc)がtrueまたはIsDataDescriptor(propertyDesc)がtrueなら、
    1. propertyDesc[[Value]]フィールドを持たないなら、propertyDesc.[[Value]]like.[[Value]]に設定する。
    2. propertyDesc[[Writable]]フィールドを持たないなら、propertyDesc.[[Writable]]like.[[Writable]]に設定する。
  3. そうでなければ、
    1. propertyDesc[[Get]]フィールドを持たないなら、propertyDesc.[[Get]]like.[[Get]]に設定する。
    2. propertyDesc[[Set]]フィールドを持たないなら、propertyDesc.[[Set]]like.[[Set]]に設定する。
  4. propertyDesc[[Enumerable]]フィールドを持たないなら、propertyDesc.[[Enumerable]]like.[[Enumerable]]に設定する。
  5. propertyDesc[[Configurable]]フィールドを持たないなら、propertyDesc.[[Configurable]]like.[[Configurable]]に設定する。
  6. unusedを返す。

6.2.7 Environment Record仕様型

Environment Record型は、ネストされた関数およびブロックにおける名前解決の振る舞いを説明するために使用されます。この型およびそれに対する操作は、9.1で定義されます。

6.2.8 Abstract Closure仕様型

Abstract Closure仕様型は、値の集合とともにアルゴリズムステップを参照するために使用されます。Abstract Closuresはメタ値であり、closure(arg1, arg2)のような関数適用形式を使用して呼び出されます。抽象操作と同様に、呼び出しはAbstract Closureによって記述されたアルゴリズムステップを実行します。

Abstract Closureを作成するアルゴリズムステップでは、値は動詞“capture”の後にaliasesのリストを続けることで捕捉されます。Abstract Closureが作成されると、その時点で各aliasに関連付けられている値を捕捉します。Abstract Closureが呼び出されたときに実行されるアルゴリズムを指定するステップでは、各捕捉された値は、その値を捕捉するために使用されたaliasによって参照されます。

Abstract ClosureがCompletion Recordを返す場合、そのCompletion Recordnormal completionまたはthrow completionのいずれかでなければなりません。

Abstract Closuresは、他のアルゴリズムの一部としてインラインで作成されます。以下の例に示します。

  1. addendを41とする。
  2. closureを、parameters (x)を持ち、addendをcaptureし、呼び出されたときに以下のステップを実行する新しいAbstract Closureとする:
    1. x + addendを返す。
  3. valueclosure(1)とする。
  4. Assert: valueは42である。

6.2.9 Data Blocks

Data Block仕様型は、byte-sized(8 bit)の数値の、別個で可変な列を記述するために使用されます。byte valueは、0から255までの包含区間内の整数です。Data Block値は、各byteが初期値0を持つ固定数のbytesで作成されます。

この仕様内では、表記上の便宜のため、Data Block値の個々のbytesへアクセスするためにarray-like syntaxを使用できます。この表記は、Data Block値を0-basedのinteger-indexedなbytes列として提示します。たとえば、dataBlockが5 byteのData Block値である場合、dataBlock[2]を使用してその3rd byteへアクセスできます。

複数のagentsから同時に参照できるメモリ内に存在するdata blockは、Shared Data Blockと指定されます。Shared Data Blockは、(Shared Data Block値の等価性テストの目的で)address-freeであるidentityを持ちます。すなわち、それはblockが任意のprocess内でマップされるvirtual addressesに結び付くのではなく、そのblockが表すメモリ内のlocationsの集合に結び付きます。2つのdata blocksは、それらが含むlocationsの集合が等しい場合に限り等しく、それ以外の場合は等しくなく、それらが含むlocationsの集合のintersectionは空です。最後に、Shared Data BlocksはData Blocksから区別できます。

Shared Data Blocksの意味論は、memory modelによってShared Data Block eventsを使用して定義されます。以下の抽象操作はShared Data Block eventsを導入し、評価意味論とmemory modelのevent semanticsとの間のinterfaceとして機能します。eventsはcandidate executionを形成し、その上でmemory modelがfilterとして機能します。完全な意味論についてはmemory modelを参照してください。

Shared Data Block eventsは、memory modelで定義されるRecordsによってモデル化されます。

以下の抽象操作は、この仕様においてData Block値を操作するために使用されます:

6.2.9.1 CreateByteDataBlock ( size )

The abstract operation CreateByteDataBlock takes argument size (a non-negative integer) and returns either a normal completion containing a Data Block or a throw completion. It performs the following steps when called:

  1. size > 253 - 1なら、RangeError例外をthrowする。
  2. dataBlocksize bytesからなる新しいData Block値とする。そのようなData Blockを作成することが不可能な場合、RangeError例外をthrowする。
  3. dataBlockのすべてのbytesを0に設定する。
  4. dataBlockを返す。

6.2.9.2 CreateSharedByteDataBlock ( size )

The abstract operation CreateSharedByteDataBlock takes argument size (a non-negative integer) and returns either a normal completion containing a Shared Data Block or a throw completion. It performs the following steps when called:

  1. dataBlocksize bytesからなる新しいShared Data Block値とする。そのようなShared Data Blockを作成することが不可能な場合、RangeError例外をthrowする。
  2. agentRecordsurrounding agentAgent Recordとする。
  3. executionagentRecord.[[CandidateExecution]]とする。
  4. eventsRecordを、[[AgentSignifier]]AgentSignifier()であるexecution.[[EventsRecords]]Agent Events Recordとする。
  5. zeroを« 0 »とする。
  6. dataBlockの各index indexについて、以下を行う
    1. WriteSharedMemory { [[Order]]: init, [[NoTear]]: true, [[Block]]: dataBlock, [[ByteIndex]]: index, [[ElementSize]]: 1, [[Payload]]: zero }をeventsRecord.[[EventList]]へappendする。
  7. dataBlockを返す。

6.2.9.3 CopyDataBlockBytes ( toBlock, toIndex, fromBlock, fromIndex, count )

The abstract operation CopyDataBlockBytes takes arguments toBlock (a Data Block or a Shared Data Block), toIndex (a non-negative integer), fromBlock (a Data Block or a Shared Data Block), fromIndex (a non-negative integer), and count (a non-negative integer) and returns unused. It performs the following steps when called:

  1. Assert: fromBlocktoBlockは別個の値である。
  2. fromSizefromBlock内のbytesの数とする。
  3. Assert: fromIndex + countfromSize
  4. toSizetoBlock内のbytesの数とする。
  5. Assert: toIndex + counttoSize
  6. count > 0の間、繰り返す
    1. fromBlockShared Data Blockなら、
      1. agentRecordsurrounding agentAgent Recordとする。
      2. executionagentRecord.[[CandidateExecution]]とする。
      3. eventsRecordを、[[AgentSignifier]]AgentSignifier()であるexecution.[[EventsRecords]]Agent Events Recordとする。
      4. bytesを、唯一の要素が非決定的に選択されたbyte valueであるListとする。
      5. NOTE: 実装では、bytesは基礎となるハードウェア上のnon-atomic read instructionの結果です。この非決定性は、weak consistencyを持つハードウェアの観測可能な振る舞いを記述するためのmemory modelの意味論的規定です。
      6. readEventReadSharedMemory { [[Order]]: unordered, [[NoTear]]: true, [[Block]]: fromBlock, [[ByteIndex]]: fromIndex, [[ElementSize]]: 1 }とする。
      7. readEventeventsRecord.[[EventList]]へappendする。
      8. Chosen Value Record { [[Event]]: readEvent, [[ChosenValue]]: bytes }をexecution.[[ChosenValues]]へappendする。
      9. toBlockShared Data Blockなら、
        1. WriteSharedMemory { [[Order]]: unordered, [[NoTear]]: true, [[Block]]: toBlock, [[ByteIndex]]: toIndex, [[ElementSize]]: 1, [[Payload]]: bytes }をeventsRecord.[[EventList]]へappendする。
      10. そうでなければ、
        1. toBlock[toIndex]をbytes[0]に設定する。
    2. そうでなければ、
      1. Assert: toBlockShared Data Blockではない。
      2. toBlock[toIndex]をfromBlock[fromIndex]に設定する。
    3. toIndextoIndex + 1に設定する。
    4. fromIndexfromIndex + 1に設定する。
    5. countcount - 1に設定する。
  7. unusedを返す。

6.2.10 PrivateElement仕様型

PrivateElement型は、private class fields、methods、およびaccessorsの仕様で使用されるRecordです。Property Descriptorsはprivate elementsには使用されませんが、private fieldsはnon-configurable、non-enumerable、writable data propertiesと同様に振る舞い、private methodsはnon-configurable、non-enumerable、non-writable data propertiesと同様に振る舞い、private accessorsはnon-configurable、non-enumerable accessor propertiesと同様に振る舞います。

PrivateElement型の値は、Table 9によって定義されるフィールドを持つRecord値です。そのような値はPrivateElementsと呼ばれます。

Table 9: PrivateElement Fields
フィールド名 それが存在する[[Kind]]フィールドの値 意味
[[Key]] All Private Name field、method、またはaccessorの名前。
[[Kind]] All field, method, or accessor elementの種類。
[[Value]] field and method ECMAScript言語値 fieldの値。
[[Get]] accessor function objectまたはundefined private accessorのgetter。
[[Set]] accessor function objectまたはundefined private accessorのsetter。

6.2.11 ClassFieldDefinition Record仕様型

ClassFieldDefinition型は、class fieldsの仕様で使用されるRecordです。

ClassFieldDefinition型の値は、Table 10によって定義されるフィールドを持つRecord値です。そのような値はClassFieldDefinition Recordsと呼ばれます。

Table 10: ClassFieldDefinition Record Fields
フィールド名 意味
[[Name]] Private Name、String、またはSymbol fieldの名前。
[[Initializer]] ECMAScript function objectまたはempty fieldのinitializer(存在する場合)。

6.2.12 Private Names

Private Name仕様型は、private class element(field、method、またはaccessor)のキーを表す、グローバルに一意な値(それ以外は区別できない場合でも、他のいかなるPrivate Nameとも異なるもの)を記述するために使用されます。各Private Nameは、不変の[[Description]] internal slotを持ち、これはStringです。Private NameはPrivateFieldAddまたはPrivateMethodOrAccessorAddによって任意のECMAScriptオブジェクトにインストールでき、その後PrivateGetおよびPrivateSetを使用して読み書きできます。

6.2.13 ClassStaticBlockDefinition Record仕様型

ClassStaticBlockDefinition Recordは、class static initialization blockの実行可能コードをカプセル化するために使用されるRecord値です。

ClassStaticBlockDefinition Recordsは、Table 11に列挙されるフィールドを持ちます。

Table 11: ClassStaticBlockDefinition Record Fields
フィールド名 意味
[[BodyFunction]] ECMAScript function object classのstatic initialization中に呼び出されるfunction object

7 抽象操作

これらの操作はECMAScript言語の一部ではありません。これらは、ECMAScript言語の意味論の仕様を補助するためだけにここで定義されます。その他の、より特殊化された抽象操作は、この仕様全体にわたって定義されます。

7.1 型変換

ECMAScript言語は、必要に応じて自動的な型変換を暗黙に実行します。特定の構文の意味論を明確にするため、変換抽象操作の集合を定義することが有用です。変換抽象操作は多態的です。任意のECMAScript言語型の値を受け入れることができます。ただし、これらの操作では他の仕様型は使用されません。

BigInt型にはECMAScript言語における暗黙変換はありません。プログラマーは、他の型から値を変換するにはBigIntを明示的に呼び出さなければなりません。

7.1.1 ToPrimitive ( input [ , preferredType ] )

The abstract operation ToPrimitive takes argument input (an ECMAScript language value) and optional argument preferredType (string or number) and returns either a normal completion containing an ECMAScript language value or a throw completion. これはinput argumentを非Object型へ変換します。オブジェクトが複数のprimitive型へ変換可能である場合、optional hint preferredTypeを使用してその型を優先することがあります。 It performs the following steps when called:

  1. inputがObjectなら、
    1. exoticToPrimitiveを ? GetMethod(input, %Symbol.toPrimitive%) とする。
    2. exoticToPrimitiveundefinedでないなら、
      1. preferredTypeが存在しないなら、
        1. hint"default"とする。
      2. そうでなく、preferredTypestringなら、
        1. hint"string"とする。
      3. そうでなければ、
        1. Assert: preferredTypenumberである。
        2. hint"number"とする。
      4. resultを ? Call(exoticToPrimitive, input, « hint ») とする。
      5. resultがObjectでないなら、resultを返す。
      6. TypeError例外をthrowする。
    3. preferredTypeが存在しないなら、preferredTypenumberに設定する。
    4. OrdinaryToPrimitive(input, preferredType)を返す。
  2. inputを返す。
Note

ToPrimitiveがhintなしで呼び出された場合、一般にhintがnumberであるかのように振る舞います。ただし、オブジェクトは%Symbol.toPrimitive%メソッドを定義することでこの振る舞いを上書きできます。この仕様で定義されるオブジェクトのうち、Dates(21.4.4.45を参照)およびSymbol objects(20.4.3.5を参照)のみがデフォルトのToPrimitiveの振る舞いを上書きします。Datesはhintが存在しないことを、hintがstringであるかのように扱います。

7.1.1.1 OrdinaryToPrimitive ( obj, hint )

The abstract operation OrdinaryToPrimitive takes arguments obj (an Object) and hint (string or number) and returns either a normal completion containing an ECMAScript language value or a throw completion. It performs the following steps when called:

  1. hintstringなら、
    1. methodNamesを« "toString", "valueOf" »とする。
  2. そうでなければ、
    1. methodNamesを« "valueOf", "toString" »とする。
  3. methodNamesの各要素nameについて、以下を行う
    1. methodを ? Get(obj, name) とする。
    2. IsCallable(method)がtrueなら、
      1. resultを ? Call(method, obj) とする。
      2. resultがObjectでないなら、resultを返す。
  4. TypeError例外をthrowする。

7.1.2 ToBoolean ( arg )

The abstract operation ToBoolean takes argument arg (an ECMAScript language value) and returns a Boolean. これはargBoolean型の値へ変換します。 It performs the following steps when called:

  1. argがBooleanなら、argを返す。
  2. argundefinednull+0𝔽-0𝔽NaN0、または空のStringのいずれかなら、falseを返す。
  3. hostがweb browserであるか、または他の方法で[[IsHTMLDDA]] Internal Slotをサポートするなら、
    1. argがObjectであり、arg[[IsHTMLDDA]] internal slotを持つなら、falseを返す。
  4. trueを返す。

7.1.3 ToNumeric ( arg )

The abstract operation ToNumeric takes argument arg (an ECMAScript language value) and returns either a normal completion containing either a Number or a BigInt, or a throw completion. これはargをNumberまたはBigIntへ変換して返します。 It performs the following steps when called:

  1. primitiveValueを ? ToPrimitive(arg, number) とする。
  2. primitiveValueがBigIntなら、primitiveValueを返す。
  3. ToNumber(primitiveValue)を返す。

7.1.4 ToNumber ( arg )

The abstract operation ToNumber takes argument arg (an ECMAScript language value) and returns either a normal completion containing a Number or a throw completion. これはargNumber型の値へ変換します。 It performs the following steps when called:

  1. argがNumberなら、argを返す。
  2. argがSymbolまたはBigIntのいずれかなら、TypeError例外をthrowする。
  3. argundefinedなら、NaNを返す。
  4. argnullまたはfalseのいずれかなら、+0𝔽を返す。
  5. argtrueなら、1𝔽を返す。
  6. argがStringなら、StringToNumber(arg)を返す。
  7. Assert: argはObjectである。
  8. primitiveValueを ? ToPrimitive(arg, number) とする。
  9. Assert: primitiveValueはObjectでない。
  10. ToNumber(primitiveValue)を返す。

7.1.4.1 String型に適用されるToNumber

抽象操作StringToNumberは、以下の文法を使用してString値をNumber値へ変換する方法を指定します。

構文

StringNumericLiteral ::: StrWhiteSpaceopt StrWhiteSpaceopt StrNumericLiteral StrWhiteSpaceopt StrWhiteSpace ::: StrWhiteSpaceChar StrWhiteSpaceopt StrWhiteSpaceChar ::: WhiteSpace LineTerminator StrNumericLiteral ::: StrDecimalLiteral NonDecimalIntegerLiteral[~Sep] StrDecimalLiteral ::: StrUnsignedDecimalLiteral + StrUnsignedDecimalLiteral - StrUnsignedDecimalLiteral StrUnsignedDecimalLiteral ::: Infinity DecimalDigits[~Sep] . DecimalDigits[~Sep]opt ExponentPart[~Sep]opt . DecimalDigits[~Sep] ExponentPart[~Sep]opt DecimalDigits[~Sep] ExponentPart[~Sep]opt

上で明示的に定義されていないすべてのgrammar symbolsは、numeric literalsのLexical Grammarで使用される定義を持ちます(12.9.3

Note

StringNumericLiteralNumericLiteralの構文の間には、いくつかの違いがあることに注意すべきです:

7.1.4.1.1 StringToNumber ( string )

The abstract operation StringToNumber takes argument string (a String) and returns a Number. It performs the following steps when called:

  1. literalParseText(string, StringNumericLiteral)とする。
  2. literalがerrorsのListなら、NaNを返す。
  3. literalStringNumericValueを返す。

7.1.4.1.2 Runtime Semantics: StringNumericValue

The syntax-directed operation StringNumericValue takes no arguments and returns a Number.

Note

StringNumericLiteralからNumber値への変換は、全体としてNumericLiteralNumericValueの決定(12.9.3を参照)に似ていますが、詳細の一部は異なります。

It is defined piecewise over the following productions:

StringNumericLiteral ::: StrWhiteSpaceopt
  1. +0𝔽を返す。
StringNumericLiteral ::: StrWhiteSpaceopt StrNumericLiteral StrWhiteSpaceopt
  1. StrNumericLiteralStringNumericValueを返す。
StrNumericLiteral ::: NonDecimalIntegerLiteral
  1. 𝔽(NonDecimalIntegerLiteralのMV)を返す。
StrDecimalLiteral ::: - StrUnsignedDecimalLiteral
  1. aStrUnsignedDecimalLiteralStringNumericValueとする。
  2. a+0𝔽なら、-0𝔽を返す。
  3. -aを返す。
StrUnsignedDecimalLiteral ::: Infinity
  1. +∞𝔽を返す。
StrUnsignedDecimalLiteral ::: DecimalDigits . DecimalDigitsopt ExponentPartopt
  1. aを最初のDecimalDigitsのMVとする。
  2. 2番目のDecimalDigitsが存在するなら、
    1. bを2番目のDecimalDigitsのMVとする。
    2. nを2番目のDecimalDigits内のcode pointsの数とする。
  3. そうでなければ、
    1. bを0とする。
    2. nを0とする。
  4. ExponentPartが存在するなら、eExponentPartのMVとする。そうでなければ、eを0とする。
  5. RoundMVResult((a + (b × 10-n)) × 10e)を返す。
StrUnsignedDecimalLiteral ::: . DecimalDigits ExponentPartopt
  1. bDecimalDigitsのMVとする。
  2. ExponentPartが存在するなら、eExponentPartのMVとする。そうでなければ、eを0とする。
  3. nDecimalDigits内のcode pointsの数とする。
  4. RoundMVResult(b × 10e - n)を返す。
StrUnsignedDecimalLiteral ::: DecimalDigits ExponentPartopt
  1. aDecimalDigitsのMVとする。
  2. ExponentPartが存在するなら、eExponentPartのMVとする。そうでなければ、eを0とする。
  3. RoundMVResult(a × 10e)を返す。

7.1.4.1.3 RoundMVResult ( n )

The abstract operation RoundMVResult takes argument n (a mathematical value) and returns a Number. これはnimplementation-definedな方法でNumberへ変換します。この抽象操作の目的では、digitは、それがzeroでない場合、またはその左にnon-zero digitがあり、かつその右にnon-zero digitがある場合にsignificantです。この抽象操作の目的では、mathematical valueの表現が“表すmathematical value”は、mathematical valueの“decimal representation”の逆です。 It performs the following steps when called:

  1. nのdecimal representationが20個以下のsignificant digitsを持つなら、𝔽(n)を返す。
  2. option1を、nのdecimal representation内の20番目以降の各significant digitを0 digitで置き換えた結果が表すmathematical valueとする。
  3. option2を、nのdecimal representation内の20番目以降の各significant digitを0 digitで置き換え、その後20番目の位置でそれをincrementした結果(必要に応じて繰り上がりを伴う)が表すmathematical valueとする。
  4. chosenoption1またはoption2のいずれかのimplementation-definedな選択とする。
  5. 𝔽(chosen)を返す。

7.1.5 ToIntegerOrInfinity ( arg )

The abstract operation ToIntegerOrInfinity takes argument arg (an ECMAScript language value) and returns either a normal completion containing either an integer, +∞, or -∞, or a throw completion. これはargを、そのNumber値の小数部を切り捨てたものを表すintegerへ、またはそのNumber値が無限である場合は+∞または-∞へ変換します。 It performs the following steps when called:

  1. numberを ? ToNumber(arg) とする。
  2. numberNaN+0𝔽、または-0𝔽のいずれかなら、0を返す。
  3. number+∞𝔽なら、+∞を返す。
  4. number-∞𝔽なら、-∞を返す。
  5. truncate((number))を返す。
Note
𝔽(ToIntegerOrInfinity(x))は、xの任意の値について決して-0𝔽を返しません。小数部の切り捨ては、xmathematical valueへ変換した後に実行されます。

7.1.6 ToFixedSizeInteger ( int, signed, bitWidth )

The abstract operation ToFixedSizeInteger takes arguments int (an integer, +∞, or -∞), signed (unsigned or signed), and bitWidth (a positive integer) and returns an integer. これはintを、signedunsignedの場合は0から2bitWidth - 1までの包含区間内の2bitWidth個のintegersの1つへ、またはsignedsignedの場合は-2bitWidth - 1から2bitWidth - 1 - 1までの包含区間内の2bitWidth個のintegersの1つへ写像します。 It performs the following steps when called:

  1. int = +∞またはint = -∞なら、0を返す。
  2. fixedIntint modulo 2bitWidthとする。
  3. NOTE: 次のステップはfixedIntのtwo's complement representationを変更しません。
  4. signedsignedかつfixedInt ≥ 2bitWidth - 1なら、fixedIntfixedInt - 2bitWidthに設定する。
  5. fixedIntを返す。
Note

ToFixedSizeIntegerはidempotentです。任意のECMAScript言語値xについて、ToFixedSizeInteger(ToFixedSizeInteger(x, signed, bitWidth), signed, bitWidth)はToFixedSizeInteger(x, signed, bitWidth)と同じです。実際、+∞および-∞は0へ写像されるため、この不変条件はsignedの反転後にも維持されます(例:ToFixedSizeInteger(ToFixedSizeInteger(x, signed, 32), unsigned, 32)はToFixedSizeInteger(x, unsigned, 32)と同じです)。

7.1.7 ToInt32 ( arg )

The abstract operation ToInt32 takes argument arg (an ECMAScript language value) and returns either a normal completion containing an integral Number or a throw completion. これはargを、𝔽(-231)から𝔽(231 - 1)までの包含区間内の、-0𝔽を除く232個のintegral Number値の1つへ変換します。 It performs the following steps when called:

  1. intを ? ToIntegerOrInfinity(arg) とする。
  2. 𝔽(ToFixedSizeInteger(int, signed, 32))を返す。

7.1.8 ToUint32 ( arg )

The abstract operation ToUint32 takes argument arg (an ECMAScript language value) and returns either a normal completion containing an integral Number or a throw completion. これはargを、+0𝔽から𝔽(232 - 1)までの包含区間内の232個のintegral Number値の1つへ変換します。 It performs the following steps when called:

  1. intを ? ToIntegerOrInfinity(arg) とする。
  2. 𝔽(ToFixedSizeInteger(int, unsigned, 32))を返す。

7.1.9 ToInt16 ( arg )

The abstract operation ToInt16 takes argument arg (an ECMAScript language value) and returns either a normal completion containing an integral Number or a throw completion. これはargを、𝔽(-215)から𝔽(215 - 1)までの包含区間内の、-0𝔽を除く216個のintegral Number値の1つへ変換します。 It performs the following steps when called:

  1. intを ? ToIntegerOrInfinity(arg) とする。
  2. 𝔽(ToFixedSizeInteger(int, signed, 16))を返す。

7.1.10 ToUint16 ( arg )

The abstract operation ToUint16 takes argument arg (an ECMAScript language value) and returns either a normal completion containing an integral Number or a throw completion. これはargを、+0𝔽から𝔽(216 - 1)までの包含区間内の216個のintegral Number値の1つへ変換します。 It performs the following steps when called:

  1. intを ? ToIntegerOrInfinity(arg) とする。
  2. 𝔽(ToFixedSizeInteger(int, unsigned, 16))を返す。

7.1.11 ToInt8 ( arg )

The abstract operation ToInt8 takes argument arg (an ECMAScript language value) and returns either a normal completion containing an integral Number or a throw completion. これはargを、-128𝔽から127𝔽までの包含区間内の、-0𝔽を除く28個のintegral Number値の1つへ変換します。 It performs the following steps when called:

  1. intを ? ToIntegerOrInfinity(arg) とする。
  2. 𝔽(ToFixedSizeInteger(int, signed, 8))を返す。

7.1.12 ToUint8 ( arg )

The abstract operation ToUint8 takes argument arg (an ECMAScript language value) and returns either a normal completion containing an integral Number or a throw completion. これはargを、+0𝔽から255𝔽までの包含区間内の28個のintegral Number値の1つへ変換します。 It performs the following steps when called:

  1. intを ? ToIntegerOrInfinity(arg) とする。
  2. 𝔽(ToFixedSizeInteger(int, unsigned, 8))を返す。

7.1.13 ToUint8Clamp ( arg )

The abstract operation ToUint8Clamp takes argument arg (an ECMAScript language value) and returns either a normal completion containing an integral Number or a throw completion. これはargをclampして丸め、+0𝔽から255𝔽までの包含区間内の28個のintegral Number値の1つへ変換します。 It performs the following steps when called:

  1. numberを ? ToNumber(arg) とする。
  2. numberNaNなら、+0𝔽を返す。
  3. mvnumberextended mathematical valueとする。
  4. clampedmvを0から255の間にclampした結果とする。
  5. ffloor(clamped)とする。
  6. clamped < f + 0.5なら、𝔽(f)を返す。
  7. clamped > f + 0.5なら、𝔽(f + 1)を返す。
  8. fがevenなら、𝔽(f)を返す。
  9. 𝔽(f + 1)を返す。
Note

他のほとんどのECMAScript整数変換操作とは異なり、ToUint8Clampは非整数値を切り捨てるのではなく丸めます。また、“round half to even”のtie-breakingを使用します。これはMath.roundの“round half up”のtie-breakingとは異なります。

7.1.14 ToBigInt ( arg )

The abstract operation ToBigInt takes argument arg (an ECMAScript language value) and returns either a normal completion containing a BigInt or a throw completion. これはargをBigInt値へ変換するか、Numberからの暗黙変換が必要な場合はthrowします。 It performs the following steps when called:

  1. primitiveを ? ToPrimitive(arg, number) とする。
  2. primitiveTable 12で対応する値を返す。
Table 12: BigInt Conversions
Argument Type 結果
Undefined TypeError例外をthrowする。
Null TypeError例外をthrowする。
Boolean primitivetrueなら1nを返し、primitivefalseなら0nを返す。
BigInt primitiveを返す。
Number TypeError例外をthrowする。
String
  1. nStringToBigInt(primitive)とする。
  2. nundefinedなら、SyntaxError例外をthrowする。
  3. nを返す。
Symbol TypeError例外をthrowする。

7.1.15 StringToBigInt ( string )

The abstract operation StringToBigInt takes argument string (a String) and returns a BigInt or undefined. It performs the following steps when called:

  1. literalParseText(string, StringIntegerLiteral)とする。
  2. literalがerrorsのListなら、undefinedを返す。
  3. mvliteralのMVとする。
  4. Assert: mvintegerである。
  5. (mv)を返す。

7.1.15.1 StringIntegerLiteral文法

StringToBigIntは以下の文法を使用します。

構文

StringIntegerLiteral ::: StrWhiteSpaceopt StrWhiteSpaceopt StrIntegerLiteral StrWhiteSpaceopt StrIntegerLiteral ::: SignedInteger[~Sep] NonDecimalIntegerLiteral[~Sep]

7.1.15.2 Runtime Semantics: MV

7.1.16 ToBigInt64 ( arg )

The abstract operation ToBigInt64 takes argument arg (an ECMAScript language value) and returns either a normal completion containing a BigInt or a throw completion. これはargを、(-263)から(263 - 1)までの包含区間内の264個のBigInt値の1つへ変換します。 It performs the following steps when called:

  1. int(? ToBigInt(arg))とする。
  2. (ToFixedSizeInteger(int, signed, 64))を返す。

7.1.17 ToBigUint64 ( arg )

The abstract operation ToBigUint64 takes argument arg (an ECMAScript language value) and returns either a normal completion containing a BigInt or a throw completion. これはargを、0から(264 - 1)までの包含区間内の264個のBigInt値の1つへ変換します。 It performs the following steps when called:

  1. int(? ToBigInt(arg))とする。
  2. (ToFixedSizeInteger(int, unsigned, 64))を返す。

7.1.18 ToString ( arg )

The abstract operation ToString takes argument arg (an ECMAScript language value) and returns either a normal completion containing a String or a throw completion. これはargString型の値へ変換します。 It performs the following steps when called:

  1. argがStringなら、argを返す。
  2. argがSymbolなら、TypeError例外をthrowする。
  3. argundefinedなら、"undefined"を返す。
  4. argnullなら、"null"を返す。
  5. argtrueなら、"true"を返す。
  6. argfalseなら、"false"を返す。
  7. argがNumberなら、Number::toString(arg, 10)を返す。
  8. argがBigIntなら、BigInt::toString(arg, 10)を返す。
  9. Assert: argはObjectである。
  10. primitiveValueを ? ToPrimitive(arg, string) とする。
  11. Assert: primitiveValueはObjectでない。
  12. ToString(primitiveValue)を返す。

7.1.19 ToObject ( arg )

The abstract operation ToObject takes argument arg (an ECMAScript language value) and returns either a normal completion containing an Object or a throw completion. これはargObject型の値へ変換します。 It performs the following steps when called:

  1. argundefinedまたはnullのいずれかなら、TypeError例外をthrowする。
  2. argがBooleanなら、[[BooleanData]] internal slotがargに設定された新しいBoolean objectを返す。Boolean objectsの説明については20.3を参照。
  3. argがNumberなら、[[NumberData]] internal slotがargに設定された新しいNumber objectを返す。Number objectsの説明については21.1を参照。
  4. argがStringなら、[[StringData]] internal slotがargに設定された新しいString objectを返す。String objectsの説明については22.1を参照。
  5. argがSymbolなら、[[SymbolData]] internal slotがargに設定された新しいSymbol objectを返す。Symbol objectsの説明については20.4を参照。
  6. argがBigIntなら、[[BigIntData]] internal slotがargに設定された新しいBigInt objectを返す。BigInt objectsの説明については21.2を参照。
  7. Assert: argはObjectである。
  8. argを返す。

7.1.20 ToPropertyKey ( arg )

The abstract operation ToPropertyKey takes argument arg (an ECMAScript language value) and returns either a normal completion containing a property key or a throw completion. これはargproperty keyとして使用できる値へ変換します。 It performs the following steps when called:

  1. keyを ? ToPrimitive(arg, string) とする。
  2. keyがSymbolなら、
    1. keyを返す。
  3. ToString(key)を返す。

7.1.21 ToLength ( arg )

The abstract operation ToLength takes argument arg (an ECMAScript language value) and returns either a normal completion containing a non-negative integral Number or a throw completion. これはargを、array-like objectのlengthとして使用するのに適したnon-negative integral Numberへclampして切り捨てます。 It performs the following steps when called:

  1. lengthを ? ToIntegerOrInfinity(arg) とする。
  2. length ≤ 0なら、+0𝔽を返す。
  3. 𝔽(min(length, 253 - 1))を返す。

7.1.22 CanonicalNumericIndexString ( arg )

The abstract operation CanonicalNumericIndexString takes argument arg (a String) and returns a Number or undefined. arg"-0"であるか、あるNumber値nについてToString(n)と正確に一致する場合、それぞれのNumber値を返します。そうでなければ、undefinedを返します。 It performs the following steps when called:

  1. arg"-0"なら、-0𝔽を返す。
  2. nを ! ToNumber(arg) とする。
  3. ToString(n)がargなら、nを返す。
  4. undefinedを返す。

canonical numeric stringとは、CanonicalNumericIndexString抽象操作がundefinedを返さない任意のStringです。

7.1.23 ToIndex ( arg )

The abstract operation ToIndex takes argument arg (an ECMAScript language value) and returns either a normal completion containing a non-negative integer or a throw completion. これはargintegerへ変換し、そのintegerがnon-negativeでありinteger indexに対応する場合はそのintegerを返します。そうでなければ、例外をthrowします。 It performs the following steps when called:

  1. intを ? ToIntegerOrInfinity(arg) とする。
  2. intが0から253 - 1までの包含区間内にないなら、RangeError例外をthrowする。
  3. intを返す。

7.2 テストおよび比較操作

7.2.1 RequireObjectCoercible ( arg )

The abstract operation RequireObjectCoercible takes argument arg (an ECMAScript language value) and returns either a normal completion containing unused or a throw completion. これはargToObjectを使用してObjectへ変換できない値である場合、エラーをthrowします。 It performs the following steps when called:

  1. argundefinedまたはnullのいずれかなら、TypeError例外をthrowする。
  2. unusedを返す。

7.2.2 IsArray ( arg )

The abstract operation IsArray takes argument arg (an ECMAScript language value) and returns either a normal completion containing a Boolean or a throw completion. It performs the following steps when called:

  1. argがObjectでないなら、falseを返す。
  2. argArray exotic objectなら、trueを返す。
  3. argProxy exotic objectなら、
    1. ValidateNonRevokedProxy(arg)を実行する。
    2. proxyTargetarg.[[ProxyTarget]]とする。
    3. IsArray(proxyTarget)を返す。
  4. falseを返す。

7.2.3 IsCallable ( arg )

The abstract operation IsCallable takes argument arg (an ECMAScript language value) and returns a Boolean. これはarg[[Call]] internal methodを持つcallable functionであるかどうかを決定します。 It performs the following steps when called:

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

7.2.4 IsConstructor ( arg )

The abstract operation IsConstructor takes argument arg (an ECMAScript language value) and returns a Boolean. これはarg[[Construct]] internal methodを持つfunction objectであるかどうかを決定します。 It performs the following steps when called:

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

7.2.5 IsExtensible ( obj )

The abstract operation IsExtensible takes argument obj (an Object) and returns either a normal completion containing a Boolean or a throw completion. これは追加のプロパティをobjへ追加できるかどうかを決定するために使用されます。 It performs the following steps when called:

  1. obj.[[IsExtensible]]()を返す。

7.2.6 IsRegExp ( arg )

The abstract operation IsRegExp takes argument arg (an ECMAScript language value) and returns either a normal completion containing a Boolean or a throw completion. It performs the following steps when called:

  1. argがObjectでないなら、falseを返す。
  2. matcherを ? Get(arg, %Symbol.match%) とする。
  3. matcherundefinedでないなら、ToBoolean(matcher)を返す。
  4. arg[[RegExpMatcher]] internal slotを持つなら、trueを返す。
  5. falseを返す。

7.2.7 Static Semantics: IsStringWellFormedUnicode ( string )

The abstract operation IsStringWellFormedUnicode takes argument string (a String) and returns a Boolean. これは6.1.4で記述されるように、stringをUTF-16でエンコードされたcode pointsの列として解釈し、それがwell formedなUTF-16列であるかどうかを決定します。 It performs the following steps when called:

  1. lengthstringの長さとする。
  2. kを0とする。
  3. k < lengthの間、繰り返す
    1. codePointCodePointAt(string, k)とする。
    2. codePoint.[[IsUnpairedSurrogate]]trueなら、falseを返す。
    3. kk + codePoint.[[CodeUnitCount]]に設定する。
  4. trueを返す。

7.2.8 SameType ( x, y )

The abstract operation SameType takes arguments x (an ECMAScript language value) and y (an ECMAScript language value) and returns a Boolean. これは2つのargumentsが同じ型であるかどうかを決定します。 It performs the following steps when called:

  1. xundefinedかつyundefinedなら、trueを返す。
  2. xnullかつynullなら、trueを返す。
  3. xがBooleanかつyがBooleanなら、trueを返す。
  4. xがNumberかつyがNumberなら、trueを返す。
  5. xがBigIntかつyがBigIntなら、trueを返す。
  6. xがSymbolかつyがSymbolなら、trueを返す。
  7. xがStringかつyがStringなら、trueを返す。
  8. xがObjectかつyがObjectなら、trueを返す。
  9. falseを返す。

7.2.9 SameValue ( x, y )

The abstract operation SameValue takes arguments x (an ECMAScript language value) and y (an ECMAScript language value) and returns a Boolean. これは2つのargumentsが同じ値であるかどうかを決定します。 It performs the following steps when called:

  1. SameType(x, y)がfalseなら、falseを返す。
  2. xがNumberなら、
    1. Number::sameValue(x, y)を返す。
  3. SameValueNonNumber(x, y)を返す。
Note

このアルゴリズムは、すべてのNaN値を等価として扱い、+0𝔽-0𝔽を区別する点で、IsStrictlyEqualアルゴリズムと異なります。

7.2.10 SameValueZero ( x, y )

The abstract operation SameValueZero takes arguments x (an ECMAScript language value) and y (an ECMAScript language value) and returns a Boolean. これは2つのargumentsが同じ値であるかどうかを決定します(+0𝔽-0𝔽の違いを無視します)。 It performs the following steps when called:

  1. SameType(x, y)がfalseなら、falseを返す。
  2. xがNumberなら、
    1. Number::sameValueZero(x, y)を返す。
  3. SameValueNonNumber(x, y)を返す。
Note

SameValueZeroは、+0𝔽-0𝔽を等価として扱う点でのみSameValueと異なります。

7.2.11 SameValueNonNumber ( x, y )

The abstract operation SameValueNonNumber takes arguments x (an ECMAScript language value, but not a Number) and y (an ECMAScript language value, but not a Number) and returns a Boolean. It performs the following steps when called:

  1. Assert: SameType(x, y)はtrueである。
  2. xundefinedまたはnullのいずれかなら、trueを返す。
  3. xがBigIntなら、
    1. BigInt::equal(x, y)を返す。
  4. xがStringなら、
    1. xyが同じ長さを持ち、同じ位置に同じcode unitsを持つなら、trueを返す。
    2. falseを返す。
  5. xがBooleanなら、
    1. xtrueかつytrueなら、trueを返す。
    2. xfalseかつyfalseなら、trueを返す。
    3. falseを返す。
  6. NOTE: その他すべてのECMAScript言語値はidentityによって比較されます。
  7. xyなら、trueを返す。
  8. falseを返す。
Note 1
説明の目的で、このアルゴリズム内では、不要であってもいくつかの場合が別々に処理されます。
Note 2
x is y”が何を意味するかの詳細は、5.2.8に記されています。

7.2.12 IsLessThan ( x, y, leftFirst )

The abstract operation IsLessThan takes arguments x (an ECMAScript language value), y (an ECMAScript language value), and leftFirst (a Boolean) and returns either a normal completion containing either a Boolean or undefined, or a throw completion. これは比較x < yの意味論を提供し、truefalse、またはundefined(operandsを同じ数値型の比較可能な値へcoerceできなかったことを示す)を返します。leftFirstフラグは、xおよびyに対して潜在的に可視な副作用を持つ操作が実行される順序を制御するために使用されます。これは、ECMAScriptが式の左から右への評価を指定するため必要です。leftFirsttrueなら、xparameterはyparameterに対応する式の左側に現れる式に対応します。leftFirstfalseなら、その逆であり、操作はxより前にyに対して実行されなければなりません。 It performs the following steps when called:

  1. leftFirsttrueなら、
    1. pxを ? ToPrimitive(x, number) とする。
    2. pyを ? ToPrimitive(y, number) とする。
  2. そうでなければ、
    1. NOTE: 左から右への評価を保持するため、評価の順序を反転する必要があります。
    2. pyを ? ToPrimitive(y, number) とする。
    3. pxを ? ToPrimitive(x, number) とする。
  3. pxがStringかつpyがStringなら、
    1. lxpxの長さとする。
    2. lypyの長さとする。
    3. 0 ≤ i < min(lx, ly)である各integer iについて、昇順で、以下を行う
      1. cxpx内のindex iにあるcode unitの数値とする。
      2. cypy内のindex iにあるcode unitの数値とする。
      3. cx < cyなら、trueを返す。
      4. cx > cyなら、falseを返す。
    4. lx < lyなら、trueを返す。
    5. falseを返す。
  4. pxがBigIntかつpyがStringなら、
    1. nyStringToBigInt(py)とする。
    2. nyundefinedなら、undefinedを返す。
    3. BigInt::lessThan(px, ny)を返す。
  5. pxがStringかつpyがBigIntなら、
    1. nxStringToBigInt(px)とする。
    2. nxundefinedなら、undefinedを返す。
    3. BigInt::lessThan(nx, py)を返す。
  6. NOTE: pxpyはprimitive valuesであるため、評価順序は重要ではありません。
  7. nxを ? ToNumeric(px) とする。
  8. nyを ? ToNumeric(py) とする。
  9. SameType(nx, ny)がtrueなら、
    1. nxがNumberなら、Number::lessThan(nx, ny)を返す。
    2. Assert: nxはBigIntである。
    3. BigInt::lessThan(nx, ny)を返す。
  10. Assert: nxはBigIntかつnyはNumberである、またはnxはNumberかつnyはBigIntである。
  11. nxNaNまたはnyNaNなら、undefinedを返す。
  12. nx-∞𝔽またはny+∞𝔽なら、trueを返す。
  13. nx+∞𝔽またはny-∞𝔽なら、falseを返す。
  14. (nx) < (ny)なら、trueを返す。
  15. falseを返す。
Note 1

ステップ3は、+加算演算子を処理するアルゴリズム(13.15.3)内のステップ1.cとは、logical-or操作の代わりにlogical-and操作を使用する点で異なります。

Note 2

Stringsの比較は、UTF-16 code unit値の列に対する単純なlexicographic orderingを使用します。Unicode仕様で定義される文字または文字列の等価性およびcollating orderについての、より複雑で意味論志向の定義を使用しようとはしません。したがって、Unicode Standardに従ってcanonically equalであるString値でも、同じ正規化形式でない場合は等しくないと判定され得ます。また、surrogate pairsを含むStringsについては、code unitによるlexicographic orderingはcode pointによるorderingとは異なることにも注意してください。

7.2.13 IsLooselyEqual ( x, y )

The abstract operation IsLooselyEqual takes arguments x (an ECMAScript language value) and y (an ECMAScript language value) and returns either a normal completion containing a Boolean or a throw completion. これは==演算子の意味論を提供します。 It performs the following steps when called:

  1. SameType(x, y)がtrueなら、
    1. IsStrictlyEqual(x, y)を返す。
  2. xnullかつyundefinedなら、trueを返す。
  3. xundefinedかつynullなら、trueを返す。
  4. hostがweb browserであるか、または他の方法で[[IsHTMLDDA]] Internal Slotをサポートするなら、
    1. xがObjectであり、x[[IsHTMLDDA]] internal slotを持ち、かつyundefinedまたはnullのいずれかなら、trueを返す。
    2. xundefinedまたはnullのいずれかであり、yがObjectであり、かつy[[IsHTMLDDA]] internal slotを持つなら、trueを返す。
  5. xがNumberかつyがStringなら、! IsLooselyEqual(x, ! ToNumber(y))を返す。
  6. xがStringかつyがNumberなら、! IsLooselyEqual(! ToNumber(x), y)を返す。
  7. xがBigIntかつyがStringなら、
    1. nStringToBigInt(y)とする。
    2. nundefinedなら、falseを返す。
    3. IsLooselyEqual(x, n)を返す。
  8. xがStringかつyがBigIntなら、! IsLooselyEqual(y, x)を返す。
  9. xがBooleanなら、! IsLooselyEqual(! ToNumber(x), y)を返す。
  10. yがBooleanなら、! IsLooselyEqual(x, ! ToNumber(y))を返す。
  11. xがString、Number、BigInt、またはSymbolのいずれかであり、yがObjectなら、! IsLooselyEqual(x, ? ToPrimitive(y))を返す。
  12. xがObjectであり、yがString、Number、BigInt、またはSymbolのいずれかなら、! IsLooselyEqual(? ToPrimitive(x), y)を返す。
  13. xがBigIntかつyがNumberである、またはxがNumberかつyがBigIntであるなら、
    1. xfiniteでない、またはyfiniteでないなら、falseを返す。
    2. (x) = (y)なら、trueを返す。
    3. falseを返す。
  14. falseを返す。

7.2.14 IsStrictlyEqual ( x, y )

The abstract operation IsStrictlyEqual takes arguments x (an ECMAScript language value) and y (an ECMAScript language value) and returns a Boolean. これは===演算子の意味論を提供します。 It performs the following steps when called:

  1. SameType(x, y)がfalseなら、falseを返す。
  2. xがNumberなら、
    1. Number::equal(x, y)を返す。
  3. SameValueNonNumber(x, y)を返す。
Note

このアルゴリズムは、signed zeroesおよびNaNsの扱いにおいてSameValueアルゴリズムと異なります。

7.3 オブジェクト上の操作

7.3.1 MakeBasicObject ( internalSlotsList )

The abstract operation MakeBasicObject takes argument internalSlotsList (a List of internal slot names) and returns an Object. これは、ordinary objectsexotic objectsの両方を含む、アルゴリズムによって作成されるすべてのECMAScriptオブジェクトの源です。すべてのオブジェクトの作成で使用される共通ステップを切り出し、オブジェクト作成を一元化します。 It performs the following steps when called:

  1. internalSlotsListを、internalSlotsListと« [[PrivateElements]] »のlist-concatenationに設定する。
  2. objを、internalSlotsList内の各名前に対するinternal slotを持つ新しく作成されたオブジェクトとする。
  3. NOTE: Object Internal Methods and Internal Slotsで記述されるように、各そのようなinternal slotの初期値は、別途指定されない限りundefinedです。
  4. obj.[[PrivateElements]]を新しい空のListに設定する。
  5. objのessential internal methodsを、10.1で指定されるデフォルトのordinary object定義に設定する。
  6. Assert: 呼び出し元がobj[[GetPrototypeOf]]および[[SetPrototypeOf]] essential internal methodsの両方を上書きしないなら、internalSlotsList[[Prototype]]を含む。
  7. Assert: 呼び出し元がobj[[SetPrototypeOf]][[IsExtensible]]、および[[PreventExtensions]] essential internal methodsのすべてを上書きしないなら、internalSlotsList[[Extensible]]を含む。
  8. internalSlotsList[[Extensible]]を含むなら、obj.[[Extensible]]trueに設定する。
  9. objを返す。
Note

この仕様内では、exotic objectsは、ArrayCreateBoundFunctionCreateなどの抽象操作で、まずMakeBasicObjectを呼び出して基本的な基礎オブジェクトを取得し、その後そのオブジェクトのinternal methodsの一部または全部を上書きすることによって作成されます。exotic object作成をカプセル化するため、そのオブジェクトのessential internal methodsは、それらの操作の外部では決して変更されません。

7.3.2 Get ( obj, propertyKey )

The abstract operation Get takes arguments obj (an Object) and propertyKey (a property key) and returns either a normal completion containing an ECMAScript language value or a throw completion. これは、オブジェクトの特定のプロパティの値を取得するために使用されます。 It performs the following steps when called:

  1. obj.[[Get]](propertyKey, obj)を返す。

7.3.3 GetV ( value, propertyKey )

The abstract operation GetV takes arguments value (an ECMAScript language value) and propertyKey (a property key) and returns either a normal completion containing an ECMAScript language value or a throw completion. これは、ECMAScript言語値の特定のプロパティの値を取得するために使用されます。値がオブジェクトでない場合、プロパティ検索はその値の型に適したwrapper objectを使用して実行されます。 It performs the following steps when called:

  1. objを ? ToObject(value) とする。
  2. obj.[[Get]](propertyKey, value)を返す。

7.3.4 Set ( obj, propertyKey, value, throw )

The abstract operation Set takes arguments obj (an Object), propertyKey (a property key), value (an ECMAScript language value), and throw (a Boolean) and returns either a normal completion containing unused or a throw completion. これは、オブジェクトの特定のプロパティの値を設定するために使用されます。valueはそのプロパティの新しい値です。 It performs the following steps when called:

  1. successを ? obj.[[Set]](propertyKey, value, obj) とする。
  2. successfalseかつthrowtrueなら、TypeError例外をthrowする。
  3. unusedを返す。

7.3.5 CreateDataProperty ( obj, propertyKey, value )

The abstract operation CreateDataProperty takes arguments obj (an Object), propertyKey (a property key), and value (an ECMAScript language value) and returns either a normal completion containing a Boolean or a throw completion. これは、オブジェクトの新しいown propertyを作成するために使用されます。 It performs the following steps when called:

  1. newDescをPropertyDescriptor { [[Value]]: value, [[Writable]]: true, [[Enumerable]]: true, [[Configurable]]: true }とする。
  2. obj.[[DefineOwnProperty]](propertyKey, newDesc)を返す。
Note

この抽象操作は、ECMAScript言語の代入演算子によって作成されるプロパティに使用されるものと同じデフォルトに属性が設定されたプロパティを作成します。通常、そのプロパティはまだ存在しません。存在していてconfigurableでない場合、またはobjがextensibleでない場合、[[DefineOwnProperty]]falseを返します。

7.3.6 CreateDataPropertyOrThrow ( obj, propertyKey, value )

The abstract operation CreateDataPropertyOrThrow takes arguments obj (an Object), propertyKey (a property key), and value (an ECMAScript language value) and returns either a normal completion containing unused or a throw completion. これは、オブジェクトの新しいown propertyを作成するために使用されます。要求されたプロパティ更新を実行できない場合、TypeError例外をthrowします。 It performs the following steps when called:

  1. successを ? CreateDataProperty(obj, propertyKey, value) とする。
  2. successfalseなら、TypeError例外をthrowする。
  3. unusedを返す。
Note

この抽象操作は、ECMAScript言語の代入演算子によって作成されるプロパティに使用されるものと同じデフォルトに属性が設定されたプロパティを作成します。通常、そのプロパティはまだ存在しません。存在していてconfigurableでない場合、またはobjがextensibleでない場合、[[DefineOwnProperty]]falseを返し、この操作にTypeError例外をthrowさせます。

7.3.7 CreateNonEnumerableDataPropertyOrThrow ( obj, propertyKey, value )

The abstract operation CreateNonEnumerableDataPropertyOrThrow takes arguments obj (an Object), propertyKey (a property key), and value (an ECMAScript language value) and returns unused. これは、ordinary objectの新しいnon-enumerable own propertyを作成するために使用されます。 It performs the following steps when called:

  1. Assert: objはnon-configurable propertiesを持たないordinaryかつextensibleなオブジェクトである。
  2. newDescをPropertyDescriptor { [[Value]]: value, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: true }とする。
  3. DefinePropertyOrThrow(obj, propertyKey, newDesc)を実行する。
  4. unusedを返す。
Note

この抽象操作は、enumerableでない点を除き、ECMAScript言語の代入演算子によって作成されるプロパティに使用されるものと同じデフォルトに属性が設定されたプロパティを作成します。通常、そのプロパティはまだ存在しません。存在する場合でも、DefinePropertyOrThrowは正常に完了することが保証されています。

7.3.8 DefinePropertyOrThrow ( obj, propertyKey, propertyDesc )

The abstract operation DefinePropertyOrThrow takes arguments obj (an Object), propertyKey (a property key), and propertyDesc (a Property Descriptor) and returns either a normal completion containing unused or a throw completion. これは、要求されたプロパティ更新を実行できない場合にTypeError例外をthrowする方法で、オブジェクトの[[DefineOwnProperty]] internal methodを呼び出すために使用されます。 It performs the following steps when called:

  1. successを ? obj.[[DefineOwnProperty]](propertyKey, propertyDesc) とする。
  2. successfalseなら、TypeError例外をthrowする。
  3. unusedを返す。

7.3.9 DeletePropertyOrThrow ( obj, propertyKey )

The abstract operation DeletePropertyOrThrow takes arguments obj (an Object) and propertyKey (a property key) and returns either a normal completion containing unused or a throw completion. これは、オブジェクトの特定のown propertyを削除するために使用されます。そのプロパティがconfigurableでない場合、例外をthrowします。 It performs the following steps when called:

  1. successを ? obj.[[Delete]](propertyKey) とする。
  2. successfalseなら、TypeError例外をthrowする。
  3. unusedを返す。

7.3.10 GetMethod ( value, propertyKey )

The abstract operation GetMethod takes arguments value (an ECMAScript language value) and propertyKey (a property key) and returns either a normal completion containing either a function object or undefined, or a throw completion. これは、ECMAScript言語値の特定のプロパティの値を、そのプロパティの値がfunctionであることが期待される場合に取得するために使用されます。 It performs the following steps when called:

  1. funcを ? GetV(value, propertyKey) とする。
  2. funcundefinedまたはnullのいずれかなら、undefinedを返す。
  3. IsCallable(func)がfalseなら、TypeError例外をthrowする。
  4. funcを返す。

7.3.11 HasProperty ( obj, propertyKey )

The abstract operation HasProperty takes arguments obj (an Object) and propertyKey (a property key) and returns either a normal completion containing a Boolean or a throw completion. これは、指定されたproperty keyを持つプロパティをオブジェクトが持っているかどうかを決定するために使用されます。そのプロパティはownまたはinheritedのいずれでもよいです。 It performs the following steps when called:

  1. obj.[[HasProperty]](propertyKey)を返す。

7.3.12 HasOwnProperty ( obj, propertyKey )

The abstract operation HasOwnProperty takes arguments obj (an Object) and propertyKey (a property key) and returns either a normal completion containing a Boolean or a throw completion. これは、指定されたproperty keyを持つown propertyをオブジェクトが持っているかどうかを決定するために使用されます。 It performs the following steps when called:

  1. propertyDescを ? obj.[[GetOwnProperty]](propertyKey) とする。
  2. propertyDescundefinedなら、falseを返す。
  3. trueを返す。

7.3.13 Call ( func, thisValue [ , argList ] )

The abstract operation Call takes arguments func (an ECMAScript language value) and thisValue (an ECMAScript language value) and optional argument argList (a List of ECMAScript language values) and returns either a normal completion containing an ECMAScript language value or a throw completion. これは、function object[[Call]] internal methodを呼び出すために使用されます。funcfunction objectthisValue[[Call]]this値であるECMAScript言語値argListはinternal methodの対応するargumentに渡される値です。argListが存在しない場合、新しい空のListがその値として使用されます。 It performs the following steps when called:

  1. argListが存在しないなら、argListを新しい空のListに設定する。
  2. IsCallable(func)がfalseなら、TypeError例外をthrowする。
  3. func.[[Call]](thisValue, argList)を返す。

7.3.14 Construct ( ctor [ , argList [ , newTarget ] ] )

The abstract operation Construct takes argument ctor (a constructor) and optional arguments argList (a List of ECMAScript language values) and newTarget (a constructor) and returns either a normal completion containing an Object or a throw completion. これは、function object[[Construct]] internal methodを呼び出すために使用されます。argListおよびnewTargetは、internal methodの対応するargumentsとして渡される値です。argListが存在しない場合、新しい空のListがその値として使用されます。newTargetが存在しない場合、ctorがその値として使用されます。 It performs the following steps when called:

  1. newTargetが存在しないなら、newTargetctorに設定する。
  2. argListが存在しないなら、argListを新しい空のListに設定する。
  3. ctor.[[Construct]](argList, newTarget)を返す。
Note

newTargetが存在しない場合、この操作はnew F(...argumentsList)と等価です。

7.3.15 SetIntegrityLevel ( obj, level )

The abstract operation SetIntegrityLevel takes arguments obj (an Object) and level (sealed or frozen) and returns either a normal completion containing a Boolean or a throw completion. これは、オブジェクトのown propertiesの集合を固定するために使用されます。 It performs the following steps when called:

  1. statusを ? obj.[[PreventExtensions]]() とする。
  2. statusfalseなら、falseを返す。
  3. keysを ? obj.[[OwnPropertyKeys]]() とする。
  4. levelsealedなら、
    1. keysの各要素keyについて、以下を行う
      1. DefinePropertyOrThrow(obj, key, PropertyDescriptor { [[Configurable]]: false })を実行する。
  5. そうでなければ、
    1. Assert: levelfrozenである。
    2. keysの各要素keyについて、以下を行う
      1. currentDescを ? obj.[[GetOwnProperty]](key) とする。
      2. currentDescundefinedでないなら、
        1. IsAccessorDescriptor(currentDesc)がtrueなら、
          1. propertyDescをPropertyDescriptor { [[Configurable]]: false }とする。
        2. そうでなければ、
          1. propertyDescをPropertyDescriptor { [[Configurable]]: false, [[Writable]]: false }とする。
        3. DefinePropertyOrThrow(obj, key, propertyDesc)を実行する。
  6. trueを返す。

7.3.16 TestIntegrityLevel ( obj, level )

The abstract operation TestIntegrityLevel takes arguments obj (an Object) and level (sealed or frozen) and returns either a normal completion containing a Boolean or a throw completion. これは、オブジェクトのown propertiesの集合が固定されているかどうかを決定するために使用されます。 It performs the following steps when called:

  1. extensibleを ? IsExtensible(obj) とする。
  2. extensibletrueなら、falseを返す。
  3. NOTE: オブジェクトがextensibleである場合、そのプロパティは一切検査されません。
  4. keysを ? obj.[[OwnPropertyKeys]]() とする。
  5. keysの各要素keyについて、以下を行う
    1. currentDescを ? obj.[[GetOwnProperty]](key) とする。
    2. currentDescundefinedでないなら、
      1. currentDesc.[[Configurable]]trueなら、falseを返す。
      2. levelfrozenかつIsDataDescriptor(currentDesc)がtrueなら、
        1. currentDesc.[[Writable]]trueなら、falseを返す。
  6. trueを返す。

7.3.17 CreateArrayFromList ( elements )

The abstract operation CreateArrayFromList takes argument elements (a List of ECMAScript language values) and returns an Array. これは、elementsによって提供される要素を持つArrayを作成するために使用されます。 It performs the following steps when called:

  1. arrayを ! ArrayCreate(0) とする。
  2. nを0とする。
  3. elementsの各要素elementについて、以下を行う
    1. CreateDataPropertyOrThrow(array, ! ToString(𝔽(n)), element)を実行する。
    2. nn + 1に設定する。
  4. arrayを返す。

7.3.18 LengthOfArrayLike ( obj )

The abstract operation LengthOfArrayLike takes argument obj (an Object) and returns either a normal completion containing a non-negative integer or a throw completion. これは、array-like objectの"length"プロパティの値を返します。 It performs the following steps when called:

  1. (? ToLength(? Get(obj, "length")))を返す。

array-like objectとは、この操作がnormal completionを返す任意のオブジェクトです。

Note 1
通常、array-like objectはinteger index namesを持ついくつかのプロパティも持つでしょう。ただし、それはこの定義の要件ではありません。
Note 2
ArraysおよびString objectsはarray-like objectsの例です。

7.3.19 CreateListFromArrayLike ( obj [ , validElementTypes ] )

The abstract operation CreateListFromArrayLike takes argument obj (an ECMAScript language value) and optional argument validElementTypes (all or property-key) and returns either a normal completion containing a List of ECMAScript language values or a throw completion. これは、objのindexed propertiesによって提供される要素を持つList値を作成するために使用されます。validElementTypesは、要素として許可される値の型を示します。 It performs the following steps when called:

  1. validElementTypesが存在しないなら、validElementTypesallに設定する。
  2. objがObjectでないなら、TypeError例外をthrowする。
  3. lengthを ? LengthOfArrayLike(obj) とする。
  4. listを新しい空のListとする。
  5. indexを0とする。
  6. index < lengthの間、繰り返す
    1. indexNameを ! ToString(𝔽(index)) とする。
    2. nextを ? Get(obj, indexName) とする。
    3. validElementTypesproperty-keyであり、nextproperty keyでないなら、TypeError例外をthrowする。
    4. nextlistへappendする。
    5. indexindex + 1に設定する。
  7. listを返す。

7.3.20 Invoke ( value, propertyKey [ , argList ] )

The abstract operation Invoke takes arguments value (an ECMAScript language value) and propertyKey (a property key) and optional argument argList (a List of ECMAScript language values) and returns either a normal completion containing an ECMAScript language value or a throw completion. これは、ECMAScript言語値のmethod propertyを呼び出すために使用されます。valueは、そのプロパティの検索点としても、その呼び出しのthis値としても機能します。argListは、そのmethodに渡されるarguments valuesのリストです。argListが存在しない場合、新しい空のListがその値として使用されます。 It performs the following steps when called:

  1. argListが存在しないなら、argListを新しい空のListに設定する。
  2. funcを ? GetV(value, propertyKey) とする。
  3. Call(func, value, argList)を返す。

7.3.21 OrdinaryHasInstance ( ctor, instance )

The abstract operation OrdinaryHasInstance takes arguments ctor (an ECMAScript language value) and instance (an ECMAScript language value) and returns either a normal completion containing a Boolean or a throw completion. これは、instancectorによって提供されるinstance object inheritance pathから継承しているかどうかを決定するデフォルトアルゴリズムを実装します。 It performs the following steps when called:

  1. IsCallable(ctor)がfalseなら、falseを返す。
  2. ctor[[BoundTargetFunction]] internal slotを持つなら、
    1. boundCtorctor.[[BoundTargetFunction]]とする。
    2. InstanceofOperator(instance, boundCtor)を返す。
  3. instanceがObjectでないなら、falseを返す。
  4. protoを ? Get(ctor, "prototype") とする。
  5. protoがObjectでないなら、TypeError例外をthrowする。
  6. 繰り返す
    1. instanceを ? instance.[[GetPrototypeOf]]() に設定する。
    2. instancenullなら、falseを返す。
    3. SameValue(proto, instance)がtrueなら、trueを返す。

7.3.22 SpeciesConstructor ( obj, defaultCtor )

The abstract operation SpeciesConstructor takes arguments obj (an Object) and defaultCtor (a constructor) and returns either a normal completion containing a constructor or a throw completion. これは、objから派生する新しいオブジェクトを作成するために使用されるべきconstructorを取得するために使用されます。defaultCtorは、objから開始してconstructor %Symbol.species%プロパティを見つけられない場合に使用するconstructorです。 It performs the following steps when called:

  1. ctorを ? Get(obj, "constructor") とする。
  2. ctorundefinedなら、defaultCtorを返す。
  3. ctorがObjectでないなら、TypeError例外をthrowする。
  4. speciesを ? Get(ctor, %Symbol.species%) とする。
  5. speciesundefinedまたはnullのいずれかなら、defaultCtorを返す。
  6. IsConstructor(species)がtrueなら、speciesを返す。
  7. TypeError例外をthrowする。

7.3.23 EnumerableOwnProperties ( obj, kind )

The abstract operation EnumerableOwnProperties takes arguments obj (an Object) and kind (key, value, or key+value) and returns either a normal completion containing a List of ECMAScript language values or a throw completion. It performs the following steps when called:

  1. ownKeysを ? obj.[[OwnPropertyKeys]]() とする。
  2. resultsを新しい空のListとする。
  3. ownKeysの各要素keyについて、以下を行う
    1. keyがStringなら、
      1. propertyDescを ? obj.[[GetOwnProperty]](key) とする。
      2. propertyDescundefinedでなく、かつpropertyDesc.[[Enumerable]]trueなら、
        1. kindkeyなら、
          1. keyresultsへappendする。
        2. そうでなければ、
          1. valueを ? Get(obj, key) とする。
          2. kindvalueなら、
            1. valueresultsへappendする。
          3. そうでなければ、
            1. Assert: kindkey+valueである。
            2. entryCreateArrayFromListkey, value »)とする。
            3. entryresultsへappendする。
  4. resultsを返す。

7.3.24 GetFunctionRealm ( func )

The abstract operation GetFunctionRealm takes argument func (a function object) and returns either a normal completion containing a Realm Record or a throw completion. It performs the following steps when called:

  1. func[[Realm]] internal slotを持つなら、
    1. func.[[Realm]]を返す。
  2. funcbound function exotic objectなら、
    1. boundTargetFuncfunc.[[BoundTargetFunction]]とする。
    2. GetFunctionRealm(boundTargetFunc)を返す。
  3. funcProxy exotic objectなら、
    1. ValidateNonRevokedProxy(func)を実行する。
    2. proxyTargetfunc.[[ProxyTarget]]とする。
    3. Assert: proxyTargetfunction objectである。
    4. GetFunctionRealm(proxyTarget)を返す。
  4. current Realm Recordを返す。
Note

ステップ4は、func[[Realm]] internal slotを持たないnon-standard function exotic objectである場合にのみ到達します。

7.3.25 CopyDataProperties ( target, source, excludedItems )

The abstract operation CopyDataProperties takes arguments target (an Object), source (an ECMAScript language value), and excludedItems (a List of property keys) and returns either a normal completion containing unused or a throw completion. It performs the following steps when called:

  1. sourceundefinedまたはnullのいずれかなら、unusedを返す。
  2. fromを ! ToObject(source) とする。
  3. keysを ? from.[[OwnPropertyKeys]]() とする。
  4. keysの各要素nextKeyについて、以下を行う
    1. excludedfalseとする。
    2. excludedItemsの各要素elementについて、以下を行う
      1. SameValue(element, nextKey)がtrueなら、
        1. excludedtrueに設定する。
    3. excludedfalseなら、
      1. propertyDescを ? from.[[GetOwnProperty]](nextKey) とする。
      2. propertyDescundefinedでなく、かつpropertyDesc.[[Enumerable]]trueなら、
        1. propertyValueを ? Get(from, nextKey) とする。
        2. CreateDataPropertyOrThrow(target, nextKey, propertyValue)を実行する。
  5. unusedを返す。
Note

ここで渡されるtargetは常に新しく作成されたオブジェクトであり、エラーがthrowされた場合に直接アクセスできません。

7.3.26 PrivateElementFind ( obj, privateName )

The abstract operation PrivateElementFind takes arguments obj (an Object) and privateName (a Private Name) and returns a PrivateElement or empty. It performs the following steps when called:

  1. obj.[[PrivateElements]]が、entry.[[Key]]privateNameであるようなPrivateElement entryを含むなら、
    1. entryを返す。
  2. emptyを返す。

7.3.27 PrivateFieldAdd ( obj, privateName, value )

The abstract operation PrivateFieldAdd takes arguments obj (an Object), privateName (a Private Name), and value (an ECMAScript language value) and returns either a normal completion containing unused or a throw completion. It performs the following steps when called:

  1. hostがweb browserなら、
    1. HostEnsureCanAddPrivateElement(obj)を実行する。
  2. entryPrivateElementFind(obj, privateName)とする。
  3. entryemptyでないなら、TypeError例外をthrowする。
  4. PrivateElement { [[Key]]: privateName, [[Kind]]: field, [[Value]]: value }をobj.[[PrivateElements]]へappendする。
  5. unusedを返す。

7.3.28 PrivateMethodOrAccessorAdd ( obj, method )

The abstract operation PrivateMethodOrAccessorAdd takes arguments obj (an Object) and method (a PrivateElement) and returns either a normal completion containing unused or a throw completion. It performs the following steps when called:

  1. Assert: method.[[Kind]]methodまたはaccessorのいずれかである。
  2. hostがweb browserなら、
    1. HostEnsureCanAddPrivateElement(obj)を実行する。
  3. entryPrivateElementFind(obj, method.[[Key]])とする。
  4. entryemptyでないなら、TypeError例外をthrowする。
  5. methodobj.[[PrivateElements]]へappendする。
  6. unusedを返す。
Note

private methodsおよびaccessorsの値は、インスタンス間で共有されます。この操作はmethodまたはaccessorの新しいcopyを作成しません。

7.3.29 HostEnsureCanAddPrivateElement ( obj )

The host-defined abstract operation HostEnsureCanAddPrivateElement takes argument obj (an Object) and returns either a normal completion containing unused or a throw completion. これは、host environmentsが特定のhost-defined exotic objectsへのprivate elementsの追加を防ぐことを可能にします。

HostEnsureCanAddPrivateElementの実装は、以下の要件に従わなければなりません:

  • objhost-defined exotic objectでない場合、この抽象操作はNormalCompletion(unused)を返し、他のステップを実行してはなりません。
  • 同じargumentでこの抽象操作を2回呼び出した場合、同じ種類のCompletion Recordを返さなければなりません。

HostEnsureCanAddPrivateElementのデフォルト実装は、NormalCompletion(unused)を返すことです。

この抽象操作は、web browsersであるECMAScript hostsによってのみ呼び出されます。

7.3.30 PrivateGet ( obj, privateName )

The abstract operation PrivateGet takes arguments obj (an Object) and privateName (a Private Name) and returns either a normal completion containing an ECMAScript language value or a throw completion. It performs the following steps when called:

  1. entryPrivateElementFind(obj, privateName)とする。
  2. entryemptyなら、TypeError例外をthrowする。
  3. entry.[[Kind]]fieldまたはmethodのいずれかなら、
    1. entry.[[Value]]を返す。
  4. Assert: entry.[[Kind]]accessorである。
  5. entry.[[Get]]undefinedなら、TypeError例外をthrowする。
  6. getterentry.[[Get]]とする。
  7. Call(getter, obj)を返す。

7.3.31 PrivateSet ( obj, privateName, value )

The abstract operation PrivateSet takes arguments obj (an Object), privateName (a Private Name), and value (an ECMAScript language value) and returns either a normal completion containing unused or a throw completion. It performs the following steps when called:

  1. entryPrivateElementFind(obj, privateName)とする。
  2. entryemptyなら、TypeError例外をthrowする。
  3. entry.[[Kind]]methodなら、TypeError例外をthrowする。
  4. entry.[[Kind]]fieldなら、
    1. entry.[[Value]]valueに設定する。
  5. そうでなければ、
    1. Assert: entry.[[Kind]]accessorである。
    2. entry.[[Set]]undefinedなら、TypeError例外をthrowする。
    3. setterentry.[[Set]]とする。
    4. Call(setter, obj, « value »)を実行する。
  6. unusedを返す。

7.3.32 DefineField ( receiver, fieldRecord )

The abstract operation DefineField takes arguments receiver (an Object) and fieldRecord (a ClassFieldDefinition Record) and returns either a normal completion containing unused or a throw completion. It performs the following steps when called:

  1. fieldNamefieldRecord.[[Name]]とする。
  2. initializerfieldRecord.[[Initializer]]とする。
  3. initializeremptyでないなら、
    1. initValueを ? Call(initializer, receiver) とする。
  4. そうでなければ、
    1. initValueundefinedとする。
  5. fieldNamePrivate Nameなら、
    1. PrivateFieldAdd(receiver, fieldName, initValue)を実行する。
  6. そうでなければ、
    1. Assert: fieldNameproperty keyである。
    2. CreateDataPropertyOrThrow(receiver, fieldName, initValue)を実行する。
  7. unusedを返す。

7.3.33 InitializeInstanceElements ( obj, ctor )

The abstract operation InitializeInstanceElements takes arguments obj (an Object) and ctor (an ECMAScript function object or a built-in function object) and returns either a normal completion containing unused or a throw completion. It performs the following steps when called:

  1. methodsctor.[[PrivateMethods]]とする。
  2. methodsの各PrivateElement methodについて、以下を行う
    1. PrivateMethodOrAccessorAdd(obj, method)を実行する。
  3. fieldsctor.[[Fields]]とする。
  4. fieldsの各要素fieldRecordについて、以下を行う
    1. DefineField(obj, fieldRecord)を実行する。
  5. unusedを返す。

7.3.34 AddValueToKeyedGroup ( groups, key, value )

The abstract operation AddValueToKeyedGroup takes arguments groups (a List of Records with fields [[Key]] (an ECMAScript language value) and [[Elements]] (a List of ECMAScript language values)), key (an ECMAScript language value), and value (an ECMAScript language value) and returns unused. It performs the following steps when called:

  1. groupsの各Record { [[Key]], [[Elements]] } groupについて、以下を行う
    1. SameValue(group.[[Key]], key)がtrueなら、
      1. Assert: groupsのちょうど1つの要素がこの基準を満たす。
      2. valuegroup.[[Elements]]へappendする。
      3. unusedを返す。
  2. groupRecord { [[Key]]: key, [[Elements]]: « value » }とする。
  3. groupgroupsへappendする。
  4. unusedを返す。

7.3.35 GroupBy ( items, callback, keyCoercion )

The abstract operation GroupBy takes arguments items (an ECMAScript language value), callback (an ECMAScript language value), and keyCoercion (property or collection) and returns either a normal completion containing a List of Records with fields [[Key]] (an ECMAScript language value) and [[Elements]] (a List of ECMAScript language values), or a throw completion. It performs the following steps when called:

  1. RequireObjectCoercible(items)を実行する。
  2. IsCallable(callback)がfalseなら、TypeError例外をthrowする。
  3. groupsを新しい空のListとする。
  4. iteratorRecordを ? GetIterator(items, sync) とする。
  5. kを0とする。
  6. 繰り返す
    1. k ≥ 253 - 1なら、
      1. errorThrowCompletion(a newly created TypeError object)とする。
      2. IteratorClose(iteratorRecord, error)を返す。
    2. nextを ? IteratorStepValue(iteratorRecord) とする。
    3. nextdoneなら、
      1. groupsを返す。
    4. valuenextとする。
    5. keyCompletion(Call(callback, undefined, « value, 𝔽(k) »))とする。
    6. IfAbruptCloseIterator(key, iteratorRecord).
    7. keyCoercionpropertyなら、
      1. keyCompletion(ToPropertyKey(key))に設定する。
      2. IfAbruptCloseIterator(key, iteratorRecord).
    8. そうでなければ、
      1. Assert: keyCoercioncollectionである。
      2. keyCanonicalizeKeyedCollectionKey(key)に設定する。
    9. AddValueToKeyedGroup(groups, key, value)を実行する。
    10. kk + 1に設定する。

7.3.36 GetOptionsObject ( options )

The abstract operation GetOptionsObject takes argument options (an ECMAScript language value) and returns either a normal completion containing an Object or a throw completion. It performs the following steps when called:

  1. optionsundefinedなら、
    1. OrdinaryObjectCreate(null)を返す。
  2. optionsがObjectなら、
    1. optionsを返す。
  3. TypeError例外をthrowする。

7.3.37 SetterThatIgnoresPrototypeProperties ( thisValue, home, propertyKey, value )

The abstract operation SetterThatIgnoresPrototypeProperties takes arguments thisValue (an ECMAScript language value), home (an Object), propertyKey (a property key), and value (an ECMAScript language value) and returns either a normal completion containing unused or a throw completion. It performs the following steps when called:

  1. thisValueがObjectでないなら、
    1. TypeError例外をthrowする。
  2. SameValue(thisValue, home)がtrueなら、
    1. NOTE: ここでthrowすることは、strict mode codeにおいてhomeオブジェクト上のnon-writable data propertyへ代入することを模倣します。
    2. TypeError例外をthrowする。
  3. propertyDescを ? thisValue.[[GetOwnProperty]](propertyKey) とする。
  4. propertyDescundefinedなら、
    1. CreateDataPropertyOrThrow(thisValue, propertyKey, value)を実行する。
  5. そうでなければ、
    1. Set(thisValue, propertyKey, value, true)を実行する。
  6. unusedを返す。

7.4 Iterator Objects上の操作

Common Iteration Interfaces(27.1を参照)。

7.4.1 Iterator Records

Iterator Recordは、iteratorまたはasync iteratornextメソッドとともにカプセル化するために使用されるRecord値です。

Iterator Recordsは、Table 13に列挙されるフィールドを持ちます。

Table 13: Iterator Record Fields
フィールド名 意味
[[Iterator]] Object iterator interfaceまたはasync iterator interfaceに適合するオブジェクト。
[[NextMethod]] ECMAScript言語値 [[Iterator]]オブジェクトのnextメソッド。
[[Done]] Boolean iteratorが完了したか、または閉じられたかどうか。

7.4.2 GetIteratorDirect ( obj )

The abstract operation GetIteratorDirect takes argument obj (an Object) and returns either a normal completion containing an Iterator Record or a throw completion. It performs the following steps when called:

  1. nextMethodを ? Get(obj, "next") とする。
  2. iteratorRecordIterator Record { [[Iterator]]: obj, [[NextMethod]]: nextMethod, [[Done]]: false }とする。
  3. iteratorRecordを返す。

7.4.3 GetIteratorFromMethod ( obj, method )

The abstract operation GetIteratorFromMethod takes arguments obj (an ECMAScript language value) and method (a function object) and returns either a normal completion containing an Iterator Record or a throw completion. It performs the following steps when called:

  1. iteratorを ? Call(method, obj) とする。
  2. iteratorがObjectでないなら、TypeError例外をthrowする。
  3. GetIteratorDirect(iterator)を返す。

7.4.4 GetIterator ( obj, kind )

The abstract operation GetIterator takes arguments obj (an ECMAScript language value) and kind (sync or async) and returns either a normal completion containing an Iterator Record or a throw completion. It performs the following steps when called:

  1. kindasyncなら、
    1. methodを ? GetMethod(obj, %Symbol.asyncIterator%) とする。
    2. methodundefinedなら、
      1. syncMethodを ? GetMethod(obj, %Symbol.iterator%) とする。
      2. syncMethodundefinedなら、TypeError例外をthrowする。
      3. syncIteratorRecordを ? GetIteratorFromMethod(obj, syncMethod) とする。
      4. CreateAsyncFromSyncIterator(syncIteratorRecord)を返す。
  2. そうでなければ、
    1. methodを ? GetMethod(obj, %Symbol.iterator%) とする。
  3. methodundefinedなら、TypeError例外をthrowする。
  4. GetIteratorFromMethod(obj, method)を返す。

7.4.5 GetIteratorFlattenable ( obj, primitiveHandling )

The abstract operation GetIteratorFlattenable takes arguments obj (an ECMAScript language value) and primitiveHandling (iterate-string-primitives or reject-primitives) and returns either a normal completion containing an Iterator Record or a throw completion. It performs the following steps when called:

  1. objがObjectでないなら、
    1. primitiveHandlingreject-primitivesなら、TypeError例外をthrowする。
    2. Assert: primitiveHandlingiterate-string-primitivesである。
    3. objがStringでないなら、TypeError例外をthrowする。
  2. methodを ? GetMethod(obj, %Symbol.iterator%) とする。
  3. methodundefinedなら、
    1. iteratorobjとする。
  4. そうでなければ、
    1. iteratorを ? Call(method, obj) とする。
  5. iteratorがObjectでないなら、TypeError例外をthrowする。
  6. GetIteratorDirect(iterator)を返す。

7.4.6 IteratorNext ( iteratorRecord [ , value ] )

The abstract operation IteratorNext takes argument iteratorRecord (an Iterator Record) and optional argument value (an ECMAScript language value) and returns either a normal completion containing an Object or a throw completion. It performs the following steps when called:

  1. valueが存在しないなら、
    1. resultCompletion(Call(iteratorRecord.[[NextMethod]], iteratorRecord.[[Iterator]]))とする。
  2. そうでなければ、
    1. resultCompletion(Call(iteratorRecord.[[NextMethod]], iteratorRecord.[[Iterator]], « value »))とする。
  3. resultthrow completionなら、
    1. iteratorRecord.[[Done]]trueに設定する。
    2. resultを返す。
  4. resultを ! result に設定する。
  5. resultがObjectでないなら、
    1. iteratorRecord.[[Done]]trueに設定する。
    2. TypeError例外をthrowする。
  6. resultを返す。

7.4.7 IteratorComplete ( iteratorResult )

The abstract operation IteratorComplete takes argument iteratorResult (an Object) and returns either a normal completion containing a Boolean or a throw completion. It performs the following steps when called:

  1. ToBoolean(? Get(iteratorResult, "done")))を返す。

7.4.8 IteratorValue ( iteratorResult )

The abstract operation IteratorValue takes argument iteratorResult (an Object) and returns either a normal completion containing an ECMAScript language value or a throw completion. It performs the following steps when called:

  1. Get(iteratorResult, "value")を返す。

7.4.9 IteratorStep ( iteratorRecord )

The abstract operation IteratorStep takes argument iteratorRecord (an Iterator Record) and returns either a normal completion containing either an Object or done, or a throw completion. これは、iteratorRecord.[[NextMethod]]を呼び出すことでiteratorRecord.[[Iterator]]から次の値を要求し、iteratorが終端に到達したことを示すdone、または次の値が利用可能な場合はIteratorResultオブジェクトを返します。 It performs the following steps when called:

  1. resultを ? IteratorNext(iteratorRecord) とする。
  2. doneCompletion(IteratorComplete(result))とする。
  3. donethrow completionなら、
    1. iteratorRecord.[[Done]]trueに設定する。
    2. doneを返す。
  4. doneを ! done に設定する。
  5. donetrueなら、
    1. iteratorRecord.[[Done]]trueに設定する。
    2. doneを返す。
  6. resultを返す。

7.4.10 IteratorStepValue ( iteratorRecord )

The abstract operation IteratorStepValue takes argument iteratorRecord (an Iterator Record) and returns either a normal completion containing either an ECMAScript language value or done, or a throw completion. これは、iteratorRecord.[[NextMethod]]を呼び出すことでiteratorRecord.[[Iterator]]から次の値を要求し、iteratorが終端に到達したことを示すdone、または次の値が利用可能な場合はIteratorResultオブジェクトからの値を返します。 It performs the following steps when called:

  1. resultを ? IteratorStep(iteratorRecord) とする。
  2. resultdoneなら、
    1. doneを返す。
  3. valueCompletion(IteratorValue(result))とする。
  4. valuethrow completionなら、
    1. iteratorRecord.[[Done]]trueに設定する。
  5. valueを返す。

7.4.11 IteratorClose ( iteratorRecord, completion )

The abstract operation IteratorClose takes arguments iteratorRecord (an Iterator Record) and completion (a Completion Record) and returns a Completion Record. これは、iteratorが完了状態に到達したときに通常実行する任意の動作を実行すべきであることを、そのiteratorへ通知するために使用されます。 It performs the following steps when called:

  1. Assert: iteratorRecord.[[Iterator]]はObjectである。
  2. iteratoriteratorRecord.[[Iterator]]とする。
  3. innerResultCompletion(GetMethod(iterator, "return")))とする。
  4. innerResultnormal completionなら、
    1. returninnerResult.[[Value]]とする。
    2. returnundefinedなら、? completionを返す。
    3. innerResultCompletion(Call(return, iterator))に設定する。
  5. completionthrow completionなら、? completionを返す。
  6. innerResultthrow completionなら、? innerResultを返す。
  7. innerResult.[[Value]]がObjectでないなら、TypeError例外をthrowする。
  8. completionを返す。

7.4.12 IteratorCloseAll ( iterators, completion )

The abstract operation IteratorCloseAll takes arguments iterators (a List of Iterator Records) and completion (a Completion Record) and returns a Completion Record. It performs the following steps when called:

  1. iteratorsの各要素iteratorについて、Listの逆順で、以下を行う
    1. completionCompletion(IteratorClose(iterator, completion))に設定する。
  2. completionを返す。

7.4.13 IfAbruptCloseIterator ( value, iteratorRecord )

IfAbruptCloseIteratorは、Iterator Recordを使用する一連のアルゴリズムステップの省略表現です。次の形式のアルゴリズムステップ:

  1. IfAbruptCloseIterator(value, iteratorRecord).

は、次と同じことを意味します:

  1. Assert: valueCompletion Recordである。
  2. valueabrupt completionなら、? IteratorClose(iteratorRecord, value)を返す。
  3. valueを ! value に設定する。

7.4.14 IfAbruptCloseIterators ( value, iteratorRecords )

IfAbruptCloseIteratorsは、Iterator Recordsのリストを使用する一連のアルゴリズムステップの省略表現です。次の形式のアルゴリズムステップ:

  1. IfAbruptCloseIterators(value, iteratorRecords).

は、次と同じことを意味します:

  1. Assert: valueCompletion Recordである。
  2. valueabrupt completionなら、? IteratorCloseAll(iteratorRecords, value)を返す。
  3. valueを ! value に設定する。

7.4.15 AsyncIteratorClose ( iteratorRecord, completion )

The abstract operation AsyncIteratorClose takes arguments iteratorRecord (an Iterator Record) and completion (a Completion Record) and returns a Completion Record. これは、async iteratorが完了状態に到達したときに通常実行する任意の動作を実行すべきであることを、そのasync iteratorへ通知するために使用されます。 It performs the following steps when called:

  1. Assert: iteratorRecord.[[Iterator]]はObjectである。
  2. iteratoriteratorRecord.[[Iterator]]とする。
  3. innerResultCompletion(GetMethod(iterator, "return")))とする。
  4. innerResultnormal completionなら、
    1. returninnerResult.[[Value]]とする。
    2. returnundefinedなら、? completionを返す。
    3. innerResultCompletion(Call(return, iterator))に設定する。
    4. innerResultnormal completionなら、innerResultCompletion(Await(innerResult.[[Value]]))に設定する。
  5. completionthrow completionなら、? completionを返す。
  6. innerResultthrow completionなら、? innerResultを返す。
  7. innerResult.[[Value]]がObjectでないなら、TypeError例外をthrowする。
  8. completionを返す。

7.4.16 IfAbruptCloseAsyncIterator ( value, iteratorRecord )

IfAbruptCloseAsyncIteratorは、Iterator Recordを使用する一連のアルゴリズムステップの省略表現です。次の形式のアルゴリズムステップ:

  1. IfAbruptCloseAsyncIterator(value, iteratorRecord).

は、次と同じことを意味します:

  1. Assert: valueCompletion Recordである。
  2. valueabrupt completionなら、? AsyncIteratorClose(iteratorRecord, value)を返す。
  3. valueを ! value に設定する。

7.4.17 CreateIteratorResultObject ( value, done )

The abstract operation CreateIteratorResultObject takes arguments value (an ECMAScript language value) and done (a Boolean) and returns an Object that conforms to the IteratorResult interface. これはIteratorResult interfaceに適合するオブジェクトを作成します。 It performs the following steps when called:

  1. objOrdinaryObjectCreate(%Object.prototype%)とする。
  2. CreateDataPropertyOrThrow(obj, "value", value)を実行する。
  3. CreateDataPropertyOrThrow(obj, "done", done)を実行する。
  4. objを返す。

7.4.18 CreateListIteratorRecord ( list )

The abstract operation CreateListIteratorRecord takes argument list (a List of ECMAScript language values) and returns an Iterator Record. これは、[[NextMethod]]listの連続する要素を返すIterator Recordを作成します。 It performs the following steps when called:

  1. closureを、parametersを持たず、listをcaptureし、呼び出されたときに以下のステップを実行する新しいAbstract Closureとする:
    1. listの各要素valueについて、以下を行う
      1. GeneratorYield(CreateIteratorResultObject(value, false))を実行する。
    2. NormalCompletion(undefined)を返す。
  2. iteratorCreateIteratorFromClosure(closure, empty, %Iterator.prototype%)とする。
  3. Iterator Record { [[Iterator]]: iterator, [[NextMethod]]: %GeneratorPrototype.next%, [[Done]]: false }を返す。
Note

list iterator objectは、ECMAScriptコードから直接アクセス可能になることは決してありません。

7.4.19 IteratorToList ( iteratorRecord )

The abstract operation IteratorToList takes argument iteratorRecord (an Iterator Record) and returns either a normal completion containing a List of ECMAScript language values or a throw completion. It performs the following steps when called:

  1. valuesを新しい空のListとする。
  2. 繰り返す
    1. nextを ? IteratorStepValue(iteratorRecord) とする。
    2. nextdoneなら、
      1. valuesを返す。
    3. nextvaluesへappendする。

7.5 Disposable オブジェクトに対する操作

共通リソース管理インターフェイスを参照(27.2.1)。

7.5.1 DisposableResource レコード

DisposableResource レコードは、破棄可能なオブジェクトを、そのオブジェクトを破棄するために使用されるメソッドとともにカプセル化するために使用される Record 値である。DisposableResource レコードは、CreateDisposableResource 抽象操作によって生成される。

DisposableResource レコードは、Table 14 に列挙されるフィールドを持つ:

Table 14: DisposableResource レコードのフィールド
フィールド名 意味
[[ResourceValue]] Object または undefined 破棄される値。
[[Kind]] sync-dispose または async-dispose リソースが using 宣言または DisposableStack オブジェクトによって追加されたか(sync-dispose)、それとも await using 宣言または AsyncDisposableStack オブジェクトによって追加されたか(async-dispose)を示す。
[[DisposeMethod]] 関数オブジェクトまたは undefined リソースが破棄されるときに、[[ResourceValue]] をその this 値として呼び出される関数オブジェクト。

7.5.2 AddDisposableResource ( disposableResourceStack, value, kind [ , method ] )

The abstract operation AddDisposableResource takes arguments disposableResourceStack (DisposableResource レコードList), value (ECMAScript 言語値), and kind (sync-dispose または async-dispose) and optional argument method (関数オブジェクト) and returns unused を含む normal completion または throw completion. It performs the following steps when called:

  1. method が存在する場合、then
    1. Assert: valueundefined である。
    2. Let resource be ? CreateDisposableResource(undefined, kind, method).
  2. Else,
    1. valuenull または undefined のいずれかであり、かつ kindsync-dispose である場合、unused を返す。
    2. NOTE: valuenull または undefined のいずれかであり、かつ kindasync-dispose である場合、後でリソースが破棄されるときにも Await が実行されることを確保するため、そのリソースが評価されたことを記録する。
    3. Let resource be ? CreateDisposableResource(value, kind).
  3. resourcedisposableResourceStack に追加する。
  4. Return unused.

7.5.3 CreateDisposableResource ( value, kind [ , method ] )

The abstract operation CreateDisposableResource takes arguments value (ECMAScript 言語値) and kind (sync-dispose または async-dispose) and optional argument method (関数オブジェクト) and returns DisposableResource レコードを含む normal completion または throw completion. It performs the following steps when called:

  1. method が存在しない場合、then
    1. valuenull または undefined のいずれかである場合、then
      1. Set value to undefined.
      2. Set method to undefined.
    2. Else,
      1. Set method to ? GetDisposeMethod(value, kind).
      2. methodundefined である場合、TypeError 例外を投げる。
  2. Return the DisposableResource Record { [[ResourceValue]]: value, [[Kind]]: kind, [[DisposeMethod]]: method }.

7.5.4 GetDisposeMethod ( value, kind )

The abstract operation GetDisposeMethod takes arguments value (ECMAScript 言語値) and kind (sync-dispose または async-dispose) and returns 関数オブジェクトまたは undefined のいずれかを含む normal completion、または throw completion. It performs the following steps when called:

  1. value が Object でない場合、TypeError 例外を投げる。
  2. kindsync-dispose である場合、return ? GetMethod(value, %Symbol.dispose%).
  3. Assert: kindasync-dispose である。
  4. Let asyncMethod be ? GetMethod(value, %Symbol.asyncDispose%).
  5. asyncMethodundefined でない場合、asyncMethod を返す。
  6. Let syncMethod be ? GetMethod(value, %Symbol.dispose%).
  7. syncMethodundefined である場合、undefined を返す。
  8. Let closure be a new Abstract Closure with no parameters that captures syncMethod and performs the following steps when called:
    1. Let obj be the this value.
    2. Let promiseCapability be ! NewPromiseCapability(%Promise%).
    3. Let result be Completion(Call(syncMethod, obj)).
    4. IfAbruptRejectPromise(result, promiseCapability).
    5. Perform ! Call(promiseCapability.[[Resolve]], undefined, « undefined »).
    6. Return promiseCapability.[[Promise]].
  9. NOTE: この関数はユーザーコードから観測できない。この関数は、同期的な %Symbol.dispose% メソッドから返された Promise が await されないこと、および同期的な例外が rejected Promise に変換されることを確保するために使用される。
  10. Return CreateBuiltinFunction(closure, 0, "", « »).

7.5.5 DisposeResources ( disposableResourceStack, completion )

The abstract operation DisposeResources takes arguments disposableResourceStack (DisposableResource レコードList) and completion (ECMAScript 言語値または empty のいずれかを含む normal completion、または abrupt completion) and returns ECMAScript 言語値または empty のいずれかを含む normal completion、または abrupt completion. It performs the following steps when called:

  1. Let needsAwait be false.
  2. Let hasAwaited be false.
  3. Let outputCompletion be completion.
  4. disposableResourceStack の各要素 resource について、List の逆順で、do
    1. Let value be resource.[[ResourceValue]].
    2. Let kind be resource.[[Kind]].
    3. Let method be resource.[[DisposeMethod]].
    4. kindsync-dispose であり、needsAwaittrue であり、かつ hasAwaitedfalse である場合、then
      1. Perform ! Await(undefined).
      2. Set needsAwait to false.
    5. methodundefined でない場合、then
      1. Let result be Completion(Call(method, value)).
      2. resultnormal completion であり、かつ kindasync-dispose である場合、then
        1. Set result to Completion(Await(result.[[Value]])).
        2. Set hasAwaited to true.
      3. resultthrow completion である場合、then
        1. outputCompletionthrow completion である場合、then
          1. Set result to result.[[Value]].
          2. Let suppressed be outputCompletion.[[Value]].
          3. Let error be a newly created SuppressedError object.
          4. Perform CreateNonEnumerableDataPropertyOrThrow(error, "error", result).
          5. Perform CreateNonEnumerableDataPropertyOrThrow(error, "suppressed", suppressed).
          6. Set outputCompletion to ThrowCompletion(error).
        2. Else,
          1. Set outputCompletion to result.
    6. Else,
      1. Assert: kindasync-dispose である。
      2. Set needsAwait to true.
      3. NOTE: これは、await using 宣言の初期化値が null または undefined のいずれかであった場合にのみ起こり得ることを示す。
  5. needsAwaittrue であり、かつ hasAwaitedfalse である場合、then
    1. Perform ! Await(undefined).
  6. NOTE: この時点で disposableResourceStack は二度と使用されない。disposableResourceStack の内容は、ガベージコレクションなどにより、実装内で破棄できる。
  7. Return ? outputCompletion.

8 構文指向操作

この節で定義されるものに加えて、特殊化された構文指向操作がこの仕様全体にわたって定義されます。

8.1 Runtime Semantics: Evaluation

The syntax-directed operation Evaluation takes no arguments and returns a Completion Record.

Note
この操作の定義は、この仕様の“ECMAScript Language”節全体に分散しています。各定義は、関連するproductionsの定義出現の後に現れます。

8.2 Scope Analysis

8.2.1 Static Semantics: BoundNames

The syntax-directed operation BoundNames takes no arguments and returns a List of Strings.

Note

"*default*"は、この仕様内で、moduleのdefault exportが別の名前を持たない場合の合成名として使用されます。moduleの[[Environment]]内にはその名前のentryが作成され、対応する値を保持します。また、そのmoduleについてResolveExport ( exportName [ , resolveSet ] )を呼び出して"default"という名前のexportを解決すると、[[BindingName]]"*default*"であるResolvedBinding Recordが返され、それがmoduleの[[Environment]]内で上記の値に解決されます。これは、anonymous default exportsを他のexportと同様に解決できるようにするための仕様上の便宜のためだけに行われます。この"*default*"文字列は、ECMAScriptコードにもmodule linking algorithmにも決してアクセス可能ではありません。

It is defined piecewise over the following productions:

BindingIdentifier : Identifier
  1. 唯一の要素がIdentifierStringValueであるListを返す。
BindingIdentifier : yield
  1. « "yield" »を返す。
BindingIdentifier : await
  1. « "await" »を返す。
LexicalDeclaration : LetOrConst BindingList ;
  1. BindingListBoundNames を返す。
UsingDeclaration : using BindingList ; AwaitUsingDeclaration : CoverAwaitExpressionAndAwaitUsingDeclarationHead BindingList ;
  1. BindingListBoundNamesを返す。
BindingList : BindingList , LexicalBinding
  1. names1BindingListBoundNamesとする。
  2. names2LexicalBindingBoundNamesとする。
  3. names1names2list-concatenationを返す。
LexicalBinding : BindingIdentifier Initializeropt
  1. BindingIdentifierBoundNamesを返す。
LexicalBinding : BindingPattern Initializer
  1. BindingPatternBoundNamesを返す。
VariableDeclarationList : VariableDeclarationList , VariableDeclaration
  1. names1VariableDeclarationListBoundNamesとする。
  2. names2VariableDeclarationBoundNamesとする。
  3. names1names2list-concatenationを返す。
VariableDeclaration : BindingIdentifier Initializeropt
  1. BindingIdentifierBoundNamesを返す。
VariableDeclaration : BindingPattern Initializer
  1. BindingPatternBoundNamesを返す。
ObjectBindingPattern : { }
  1. 新しい空のListを返す。
ObjectBindingPattern : { BindingPropertyList , BindingRestProperty }
  1. names1BindingPropertyListBoundNamesとする。
  2. names2BindingRestPropertyBoundNamesとする。
  3. names1names2list-concatenationを返す。
ArrayBindingPattern : [ Elisionopt ]
  1. 新しい空のListを返す。
ArrayBindingPattern : [ Elisionopt BindingRestElement ]
  1. BindingRestElementBoundNamesを返す。
ArrayBindingPattern : [ BindingElementList , Elisionopt ]
  1. BindingElementListBoundNamesを返す。
ArrayBindingPattern : [ BindingElementList , Elisionopt BindingRestElement ]
  1. names1BindingElementListBoundNamesとする。
  2. names2BindingRestElementBoundNamesとする。
  3. names1names2list-concatenationを返す。
BindingPropertyList : BindingPropertyList , BindingProperty
  1. names1BindingPropertyListBoundNamesとする。
  2. names2BindingPropertyBoundNamesとする。
  3. names1names2list-concatenationを返す。
BindingElementList : BindingElementList , BindingElisionElement
  1. names1BindingElementListBoundNamesとする。
  2. names2BindingElisionElementBoundNamesとする。
  3. names1names2list-concatenationを返す。
BindingElisionElement : Elisionopt BindingElement
  1. BindingElementBoundNamesを返す。
BindingProperty : PropertyName : BindingElement
  1. BindingElementBoundNamesを返す。
SingleNameBinding : BindingIdentifier Initializeropt
  1. BindingIdentifierBoundNamesを返す。
BindingElement : BindingPattern Initializeropt
  1. BindingPatternBoundNamesを返す。
ForDeclaration : LetOrConst ForBinding
  1. ForBindingBoundNamesを返す。
FunctionDeclaration : function BindingIdentifier ( FormalParameters ) { FunctionBody }
  1. BindingIdentifierBoundNamesを返す。
FunctionDeclaration : function ( FormalParameters ) { FunctionBody }
  1. « "*default*" »を返す。
FormalParameters : [empty]
  1. 新しい空のListを返す。
FormalParameters : FormalParameterList , FunctionRestParameter
  1. names1FormalParameterListBoundNamesとする。
  2. names2FunctionRestParameterBoundNamesとする。
  3. names1names2list-concatenationを返す。
FormalParameterList : FormalParameterList , FormalParameter
  1. names1FormalParameterListBoundNamesとする。
  2. names2FormalParameterBoundNamesとする。
  3. names1names2list-concatenationを返す。
ArrowParameters : CoverParenthesizedExpressionAndArrowParameterList
  1. formalsを、CoverParenthesizedExpressionAndArrowParameterListによってcoverされるArrowFormalParametersとする。
  2. formalsBoundNamesを返す。
GeneratorDeclaration : function * BindingIdentifier ( FormalParameters ) { GeneratorBody }
  1. BindingIdentifierBoundNamesを返す。
GeneratorDeclaration : function * ( FormalParameters ) { GeneratorBody }
  1. « "*default*" »を返す。
AsyncGeneratorDeclaration : async function * BindingIdentifier ( FormalParameters ) { AsyncGeneratorBody }
  1. BindingIdentifierBoundNamesを返す。
AsyncGeneratorDeclaration : async function * ( FormalParameters ) { AsyncGeneratorBody }
  1. « "*default*" »を返す。
ClassDeclaration : class BindingIdentifier ClassTail
  1. BindingIdentifierBoundNamesを返す。
ClassDeclaration : class ClassTail
  1. « "*default*" »を返す。
AsyncFunctionDeclaration : async function BindingIdentifier ( FormalParameters ) { AsyncFunctionBody }
  1. BindingIdentifierBoundNamesを返す。
AsyncFunctionDeclaration : async function ( FormalParameters ) { AsyncFunctionBody }
  1. « "*default*" »を返す。
CoverCallExpressionAndAsyncArrowHead : MemberExpression Arguments
  1. headを、CoverCallExpressionAndAsyncArrowHeadによってcoverされるAsyncArrowHeadとする。
  2. headBoundNamesを返す。
ImportDeclaration : import ImportClause FromClause WithClauseopt ;
  1. ImportClauseBoundNamesを返す。
ImportDeclaration : import ModuleSpecifier WithClauseopt ;
  1. 新しい空のListを返す。
ImportClause : ImportedDefaultBinding , NameSpaceImport
  1. names1ImportedDefaultBindingBoundNamesとする。
  2. names2NameSpaceImportBoundNamesとする。
  3. names1names2list-concatenationを返す。
ImportClause : ImportedDefaultBinding , NamedImports
  1. names1ImportedDefaultBindingBoundNamesとする。
  2. names2NamedImportsBoundNamesとする。
  3. names1names2list-concatenationを返す。
NamedImports : { }
  1. 新しい空のListを返す。
ImportsList : ImportsList , ImportSpecifier
  1. names1ImportsListBoundNamesとする。
  2. names2ImportSpecifierBoundNamesとする。
  3. names1names2list-concatenationを返す。
ImportSpecifier : ModuleExportName as ImportedBinding
  1. ImportedBindingBoundNamesを返す。
ExportDeclaration : export ExportFromClause FromClause WithClauseopt ; export NamedExports ;
  1. 新しい空のListを返す。
ExportDeclaration : export VariableStatement
  1. VariableStatementBoundNamesを返す。
ExportDeclaration : export Declaration
  1. DeclarationBoundNamesを返す。
ExportDeclaration : export default HoistableDeclaration
  1. declNamesHoistableDeclarationBoundNamesとする。
  2. declNamesが要素"*default*"を含まないなら、"*default*"declNamesへappendする。
  3. declNamesを返す。
ExportDeclaration : export default ClassDeclaration
  1. declNamesClassDeclarationBoundNamesとする。
  2. declNamesが要素"*default*"を含まないなら、"*default*"declNamesへappendする。
  3. declNamesを返す。
ExportDeclaration : export default AssignmentExpression ;
  1. « "*default*" »を返す。

8.2.2 Static Semantics: DeclarationPart

The syntax-directed operation DeclarationPart takes no arguments and returns a Parse Node. It is defined piecewise over the following productions:

HoistableDeclaration : FunctionDeclaration
  1. FunctionDeclarationを返す。
HoistableDeclaration : GeneratorDeclaration
  1. GeneratorDeclarationを返す。
HoistableDeclaration : AsyncFunctionDeclaration
  1. AsyncFunctionDeclarationを返す。
HoistableDeclaration : AsyncGeneratorDeclaration
  1. AsyncGeneratorDeclarationを返す。
Declaration : ClassDeclaration
  1. ClassDeclarationを返す。
Declaration : LexicalDeclaration
  1. LexicalDeclarationを返す。

8.2.3 Static Semantics: IsConstantDeclaration

The syntax-directed operation IsConstantDeclaration takes no arguments and returns a Boolean. It is defined piecewise over the following productions:

LexicalDeclaration : LetOrConst BindingList ;
  1. LetOrConstIsConstantDeclarationを返す。
LetOrConst : let
  1. falseを返す。
LetOrConst : const
  1. true を返す。
UsingDeclaration : using BindingList ; AwaitUsingDeclaration : CoverAwaitExpressionAndAwaitUsingDeclarationHead BindingList ;
  1. trueを返す。
FunctionDeclaration : function BindingIdentifier ( FormalParameters ) { FunctionBody } function ( FormalParameters ) { FunctionBody } GeneratorDeclaration : function * BindingIdentifier ( FormalParameters ) { GeneratorBody } function * ( FormalParameters ) { GeneratorBody } AsyncGeneratorDeclaration : async function * BindingIdentifier ( FormalParameters ) { AsyncGeneratorBody } async function * ( FormalParameters ) { AsyncGeneratorBody } AsyncFunctionDeclaration : async function BindingIdentifier ( FormalParameters ) { AsyncFunctionBody } async function ( FormalParameters ) { AsyncFunctionBody }
  1. falseを返す。
ClassDeclaration : class BindingIdentifier ClassTail class ClassTail
  1. falseを返す。
ExportDeclaration : export ExportFromClause FromClause ; export NamedExports ; export default AssignmentExpression ;
  1. falseを返す。
Note

export default AssignmentExpressionをconstant declarationとして扱う必要はありません。なぜなら、moduleのdefault objectを参照するために使用される内部束縛名への代入を許可する構文は存在しないからです。

8.2.4 Static Semantics: IsUsingDeclaration

The syntax-directed operation IsUsingDeclaration takes no arguments and returns Boolean. It is defined piecewise over the following productions:

LexicalDeclaration : LetOrConst BindingList ;
  1. false を返す。
UsingDeclaration : using BindingList ; AwaitUsingDeclaration : CoverAwaitExpressionAndAwaitUsingDeclarationHead BindingList ;
  1. true を返す。
ForDeclaration : LetOrConst ForBinding
  1. false を返す。
ForDeclaration : using ForBinding await using ForBinding
  1. true を返す。
FunctionDeclaration : function BindingIdentifier ( FormalParameters ) { FunctionBody } function ( FormalParameters ) { FunctionBody } GeneratorDeclaration : function * BindingIdentifier ( FormalParameters ) { GeneratorBody } function * ( FormalParameters ) { GeneratorBody } AsyncGeneratorDeclaration : async function * BindingIdentifier ( FormalParameters ) { AsyncGeneratorBody } async function * ( FormalParameters ) { AsyncGeneratorBody } AsyncFunctionDeclaration : async function BindingIdentifier ( FormalParameters ) { AsyncFunctionBody } async function ( FormalParameters ) { AsyncFunctionBody }
  1. false を返す。
ClassDeclaration : class BindingIdentifier ClassTail class ClassTail
  1. false を返す。

8.2.5 Static Semantics: IsAwaitUsingDeclaration

The syntax-directed operation IsAwaitUsingDeclaration takes no arguments and returns Boolean. It is defined piecewise over the following productions:

LexicalDeclaration : LetOrConst BindingList ;
  1. false を返す。
UsingDeclaration : using BindingList ;
  1. false を返す。
AwaitUsingDeclaration : CoverAwaitExpressionAndAwaitUsingDeclarationHead BindingList ;
  1. true を返す。
ForDeclaration : LetOrConst ForBinding
  1. false を返す。
ForDeclaration : using ForBinding
  1. false を返す。
ForDeclaration : await using ForBinding
  1. true を返す。
FunctionDeclaration : function BindingIdentifier ( FormalParameters ) { FunctionBody } function ( FormalParameters ) { FunctionBody } GeneratorDeclaration : function * BindingIdentifier ( FormalParameters ) { GeneratorBody } function * ( FormalParameters ) { GeneratorBody } AsyncGeneratorDeclaration : async function * BindingIdentifier ( FormalParameters ) { AsyncGeneratorBody } async function * ( FormalParameters ) { AsyncGeneratorBody } AsyncFunctionDeclaration : async function BindingIdentifier ( FormalParameters ) { AsyncFunctionBody } async function ( FormalParameters ) { AsyncFunctionBody }
  1. false を返す。
ClassDeclaration : class BindingIdentifier ClassTail class ClassTail
  1. false を返す。

8.2.6 Static Semantics: LexicallyDeclaredNames

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

Block : { }
  1. 新しい空のListを返す。
StatementList : StatementList StatementListItem
  1. names1StatementListLexicallyDeclaredNamesとする。
  2. names2StatementListItemLexicallyDeclaredNamesとする。
  3. names1names2list-concatenationを返す。
StatementListItem : Statement
  1. Statement Statement : LabelledStatement であるなら、LabelledStatementLexicallyDeclaredNamesを返す。
  2. 新しい空のListを返す。
StatementListItem : Declaration
  1. DeclarationBoundNamesを返す。
CaseBlock : { }
  1. 新しい空のListを返す。
CaseBlock : { CaseClausesopt DefaultClause CaseClausesopt }
  1. 最初のCaseClausesが存在するなら、names1を最初のCaseClausesLexicallyDeclaredNamesとする。
  2. そうでなければ、names1を新しい空のListとする。
  3. names2DefaultClauseLexicallyDeclaredNamesとする。
  4. 2番目のCaseClausesが存在するなら、names3を2番目のCaseClausesLexicallyDeclaredNamesとする。
  5. そうでなければ、names3を新しい空のListとする。
  6. names1names2、およびnames3list-concatenationを返す。
CaseClauses : CaseClauses CaseClause
  1. names1CaseClausesLexicallyDeclaredNamesとする。
  2. names2CaseClauseLexicallyDeclaredNamesとする。
  3. names1names2list-concatenationを返す。
CaseClause : case Expression : StatementListopt
  1. StatementListが存在するなら、StatementListLexicallyDeclaredNamesを返す。
  2. 新しい空のListを返す。
DefaultClause : default : StatementListopt
  1. StatementListが存在するなら、StatementListLexicallyDeclaredNamesを返す。
  2. 新しい空のListを返す。
LabelledStatement : LabelIdentifier : LabelledItem
  1. LabelledItemLexicallyDeclaredNamesを返す。
LabelledItem : Statement
  1. 新しい空のListを返す。
LabelledItem : FunctionDeclaration
  1. FunctionDeclarationBoundNamesを返す。
FunctionStatementList : [empty]
  1. 新しい空のListを返す。
FunctionStatementList : StatementList
  1. StatementListTopLevelLexicallyDeclaredNamesを返す。
ClassStaticBlockStatementList : [empty]
  1. 新しい空のListを返す。
ClassStaticBlockStatementList : StatementList
  1. StatementListTopLevelLexicallyDeclaredNamesを返す。
ConciseBody : ExpressionBody
  1. 新しい空のListを返す。
AsyncConciseBody : ExpressionBody
  1. 新しい空のListを返す。
Script : [empty]
  1. 新しい空のListを返す。
ScriptBody : StatementList
  1. StatementListTopLevelLexicallyDeclaredNamesを返す。
Note 1

Scriptのtop levelでは、function declarationsはlexical declarationsのようにではなく、var declarationsのように扱われます。

Note 2

ModuleのLexicallyDeclaredNamesには、そのすべてのimported bindingsの名前が含まれます。

ModuleItemList : ModuleItemList ModuleItem
  1. names1ModuleItemListLexicallyDeclaredNamesとする。
  2. names2ModuleItemLexicallyDeclaredNamesとする。
  3. names1names2list-concatenationを返す。
ModuleItem : ImportDeclaration
  1. ImportDeclarationBoundNamesを返す。
ModuleItem : ExportDeclaration
  1. ExportDeclarationexport VariableStatementであるなら、新しい空のListを返す。
  2. ExportDeclarationBoundNamesを返す。
ModuleItem : StatementListItem
  1. StatementListItemLexicallyDeclaredNamesを返す。
Note 3

Moduleのtop levelでは、function declarationsはvar declarationsのようにではなく、lexical declarationsのように扱われます。

8.2.7 Static Semantics: LexicallyScopedDeclarations

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

StatementList : StatementList StatementListItem
  1. decls1StatementListLexicallyScopedDeclarationsとする。
  2. decls2StatementListItemLexicallyScopedDeclarationsとする。
  3. decls1decls2list-concatenationを返す。
StatementListItem : Statement
  1. Statement Statement : LabelledStatement であるなら、LabelledStatementLexicallyScopedDeclarationsを返す。
  2. 新しい空のListを返す。
StatementListItem : Declaration
  1. 唯一の要素がDeclarationDeclarationPartであるListを返す。
CaseBlock : { }
  1. 新しい空のListを返す。
CaseBlock : { CaseClausesopt DefaultClause CaseClausesopt }
  1. 最初のCaseClausesが存在するなら、decls1を最初のCaseClausesLexicallyScopedDeclarationsとする。
  2. そうでなければ、decls1を新しい空のListとする。
  3. decls2DefaultClauseLexicallyScopedDeclarationsとする。
  4. 2番目のCaseClausesが存在するなら、decls3を2番目のCaseClausesLexicallyScopedDeclarationsとする。
  5. そうでなければ、decls3を新しい空のListとする。
  6. decls1decls2、およびdecls3list-concatenationを返す。
CaseClauses : CaseClauses CaseClause
  1. decls1CaseClausesLexicallyScopedDeclarationsとする。
  2. decls2CaseClauseLexicallyScopedDeclarationsとする。
  3. decls1decls2list-concatenationを返す。
CaseClause : case Expression : StatementListopt
  1. StatementListが存在するなら、StatementListLexicallyScopedDeclarationsを返す。
  2. 新しい空のListを返す。
DefaultClause : default : StatementListopt
  1. StatementListが存在するなら、StatementListLexicallyScopedDeclarationsを返す。
  2. 新しい空のListを返す。
LabelledStatement : LabelIdentifier : LabelledItem
  1. LabelledItemLexicallyScopedDeclarationsを返す。
LabelledItem : Statement
  1. 新しい空のListを返す。
LabelledItem : FunctionDeclaration
  1. « FunctionDeclaration »を返す。
FunctionStatementList : [empty]
  1. 新しい空のListを返す。
FunctionStatementList : StatementList
  1. StatementListTopLevelLexicallyScopedDeclarationsを返す。
ClassStaticBlockStatementList : [empty]
  1. 新しい空のListを返す。
ClassStaticBlockStatementList : StatementList
  1. StatementListTopLevelLexicallyScopedDeclarationsを返す。
ConciseBody : ExpressionBody
  1. 新しい空のListを返す。
AsyncConciseBody : ExpressionBody
  1. 新しい空のListを返す。
Script : [empty]
  1. 新しい空のListを返す。
ScriptBody : StatementList
  1. StatementListTopLevelLexicallyScopedDeclarationsを返す。
Module : [empty]
  1. 新しい空のListを返す。
ModuleItemList : ModuleItemList ModuleItem
  1. decls1ModuleItemListLexicallyScopedDeclarationsとする。
  2. decls2ModuleItemLexicallyScopedDeclarationsとする。
  3. decls1decls2list-concatenationを返す。
ModuleItem : ImportDeclaration
  1. 新しい空のListを返す。
ExportDeclaration : export ExportFromClause FromClause WithClauseopt ; export NamedExports ; export VariableStatement
  1. 新しい空のListを返す。
ExportDeclaration : export Declaration
  1. 唯一の要素がDeclarationDeclarationPartであるListを返す。
ExportDeclaration : export default HoistableDeclaration
  1. 唯一の要素がHoistableDeclarationDeclarationPartであるListを返す。
ExportDeclaration : export default ClassDeclaration
  1. 唯一の要素がClassDeclarationであるListを返す。
ExportDeclaration : export default AssignmentExpression ;
  1. 唯一の要素がこのExportDeclarationであるListを返す。

8.2.8 Static Semantics: VarDeclaredNames

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

Statement : EmptyStatement ExpressionStatement ContinueStatement BreakStatement ReturnStatement ThrowStatement DebuggerStatement
  1. 新しい空のListを返す。
Block : { }
  1. 新しい空のListを返す。
StatementList : StatementList StatementListItem
  1. names1StatementListVarDeclaredNamesとする。
  2. names2StatementListItemVarDeclaredNamesとする。
  3. names1names2list-concatenationを返す。
StatementListItem : Declaration
  1. 新しい空のListを返す。
VariableStatement : var VariableDeclarationList ;
  1. VariableDeclarationListBoundNamesを返す。
IfStatement : if ( Expression ) Statement else Statement
  1. names1を最初のStatementVarDeclaredNamesとする。
  2. names2を2番目のStatementVarDeclaredNamesとする。
  3. names1names2list-concatenationを返す。
IfStatement : if ( Expression ) Statement
  1. StatementVarDeclaredNamesを返す。
DoWhileStatement : do Statement while ( Expression ) ;
  1. StatementVarDeclaredNamesを返す。
WhileStatement : while ( Expression ) Statement
  1. StatementVarDeclaredNamesを返す。
ForStatement : for ( Expressionopt ; Expressionopt ; Expressionopt ) Statement
  1. StatementVarDeclaredNamesを返す。
ForStatement : for ( var VariableDeclarationList ; Expressionopt ; Expressionopt ) Statement
  1. names1VariableDeclarationListBoundNamesとする。
  2. names2StatementVarDeclaredNamesとする。
  3. names1names2list-concatenationを返す。
ForStatement : for ( LexicalDeclaration Expressionopt ; Expressionopt ) Statement
  1. StatementVarDeclaredNamesを返す。
ForInOfStatement : for ( LeftHandSideExpression in Expression ) Statement for ( ForDeclaration in Expression ) Statement for ( LeftHandSideExpression of AssignmentExpression ) Statement for ( ForDeclaration of AssignmentExpression ) Statement for await ( LeftHandSideExpression of AssignmentExpression ) Statement for await ( ForDeclaration of AssignmentExpression ) Statement
  1. StatementVarDeclaredNamesを返す。
ForInOfStatement : for ( var ForBinding in Expression ) Statement for ( var ForBinding of AssignmentExpression ) Statement for await ( var ForBinding of AssignmentExpression ) Statement
  1. names1ForBindingBoundNamesとする。
  2. names2StatementVarDeclaredNamesとする。
  3. names1names2list-concatenationを返す。
Note

この節はAnnex B.3.5によって拡張されます。

WithStatement : with ( Expression ) Statement
  1. StatementVarDeclaredNamesを返す。
SwitchStatement : switch ( Expression ) CaseBlock
  1. CaseBlockVarDeclaredNamesを返す。
CaseBlock : { }
  1. 新しい空のListを返す。
CaseBlock : { CaseClausesopt DefaultClause CaseClausesopt }
  1. 最初のCaseClausesが存在するなら、names1を最初のCaseClausesVarDeclaredNamesとする。
  2. そうでなければ、names1を新しい空のListとする。
  3. names2DefaultClauseVarDeclaredNamesとする。
  4. 2番目のCaseClausesが存在するなら、names3を2番目のCaseClausesVarDeclaredNamesとする。
  5. そうでなければ、names3を新しい空のListとする。
  6. names1names2、およびnames3list-concatenationを返す。
CaseClauses : CaseClauses CaseClause
  1. names1CaseClausesVarDeclaredNamesとする。
  2. names2CaseClauseVarDeclaredNamesとする。
  3. names1names2list-concatenationを返す。
CaseClause : case Expression : StatementListopt
  1. StatementListが存在するなら、StatementListVarDeclaredNamesを返す。
  2. 新しい空のListを返す。
DefaultClause : default : StatementListopt
  1. StatementListが存在するなら、StatementListVarDeclaredNamesを返す。
  2. 新しい空のListを返す。
LabelledStatement : LabelIdentifier : LabelledItem
  1. LabelledItemVarDeclaredNamesを返す。
LabelledItem : FunctionDeclaration
  1. 新しい空のListを返す。
TryStatement : try Block Catch
  1. names1BlockVarDeclaredNamesとする。
  2. names2CatchVarDeclaredNamesとする。
  3. names1names2list-concatenationを返す。
TryStatement : try Block Finally
  1. names1BlockVarDeclaredNamesとする。
  2. names2FinallyVarDeclaredNamesとする。
  3. names1names2list-concatenationを返す。
TryStatement : try Block Catch Finally
  1. names1BlockVarDeclaredNamesとする。
  2. names2CatchVarDeclaredNamesとする。
  3. names3FinallyVarDeclaredNamesとする。
  4. names1names2、およびnames3list-concatenationを返す。
Catch : catch ( CatchParameter ) Block
  1. BlockVarDeclaredNamesを返す。
FunctionStatementList : [empty]
  1. 新しい空のListを返す。
FunctionStatementList : StatementList
  1. StatementListTopLevelVarDeclaredNamesを返す。
ClassStaticBlockStatementList : [empty]
  1. 新しい空のListを返す。
ClassStaticBlockStatementList : StatementList
  1. StatementListTopLevelVarDeclaredNamesを返す。
ConciseBody : ExpressionBody
  1. 新しい空のListを返す。
AsyncConciseBody : ExpressionBody
  1. 新しい空のListを返す。
Script : [empty]
  1. 新しい空のListを返す。
ScriptBody : StatementList
  1. StatementListTopLevelVarDeclaredNamesを返す。
ModuleItemList : ModuleItemList ModuleItem
  1. names1ModuleItemListVarDeclaredNamesとする。
  2. names2ModuleItemVarDeclaredNamesとする。
  3. names1names2list-concatenationを返す。
ModuleItem : ImportDeclaration
  1. 新しい空のListを返す。
ModuleItem : ExportDeclaration
  1. ExportDeclarationexport VariableStatementであるなら、ExportDeclarationBoundNamesを返す。
  2. 新しい空のListを返す。

8.2.9 Static Semantics: VarScopedDeclarations

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

Statement : EmptyStatement ExpressionStatement ContinueStatement BreakStatement ReturnStatement ThrowStatement DebuggerStatement
  1. 新しい空のListを返す。
Block : { }
  1. 新しい空のListを返す。
StatementList : StatementList StatementListItem
  1. decls1StatementListVarScopedDeclarationsとする。
  2. decls2StatementListItemVarScopedDeclarationsとする。
  3. decls1decls2list-concatenationを返す。
StatementListItem : Declaration
  1. 新しい空のListを返す。
VariableDeclarationList : VariableDeclaration
  1. « VariableDeclaration »を返す。
VariableDeclarationList : VariableDeclarationList , VariableDeclaration
  1. decls1VariableDeclarationListVarScopedDeclarationsとする。
  2. decls1と« VariableDeclaration »のlist-concatenationを返す。
IfStatement : if ( Expression ) Statement else Statement
  1. decls1を最初のStatementVarScopedDeclarationsとする。
  2. decls2を2番目のStatementVarScopedDeclarationsとする。
  3. decls1decls2list-concatenationを返す。
IfStatement : if ( Expression ) Statement
  1. StatementVarScopedDeclarationsを返す。
DoWhileStatement : do Statement while ( Expression ) ;
  1. StatementVarScopedDeclarationsを返す。
WhileStatement : while ( Expression ) Statement
  1. StatementVarScopedDeclarationsを返す。
ForStatement : for ( Expressionopt ; Expressionopt ; Expressionopt ) Statement
  1. StatementVarScopedDeclarationsを返す。
ForStatement : for ( var VariableDeclarationList ; Expressionopt ; Expressionopt ) Statement
  1. decls1VariableDeclarationListVarScopedDeclarationsとする。
  2. decls2StatementVarScopedDeclarationsとする。
  3. decls1decls2list-concatenationを返す。
ForStatement : for ( LexicalDeclaration Expressionopt ; Expressionopt ) Statement
  1. StatementVarScopedDeclarationsを返す。
ForInOfStatement : for ( LeftHandSideExpression in Expression ) Statement for ( ForDeclaration in Expression ) Statement for ( LeftHandSideExpression of AssignmentExpression ) Statement for ( ForDeclaration of AssignmentExpression ) Statement for await ( LeftHandSideExpression of AssignmentExpression ) Statement for await ( ForDeclaration of AssignmentExpression ) Statement
  1. StatementVarScopedDeclarationsを返す。
ForInOfStatement : for ( var ForBinding in Expression ) Statement for ( var ForBinding of AssignmentExpression ) Statement for await ( var ForBinding of AssignmentExpression ) Statement
  1. decls1を« ForBinding »とする。
  2. decls2StatementVarScopedDeclarationsとする。
  3. decls1decls2list-concatenationを返す。
Note

この節はAnnex B.3.5によって拡張されます。

WithStatement : with ( Expression ) Statement
  1. StatementVarScopedDeclarationsを返す。
SwitchStatement : switch ( Expression ) CaseBlock
  1. CaseBlockVarScopedDeclarationsを返す。
CaseBlock : { }
  1. 新しい空のListを返す。
CaseBlock : { CaseClausesopt DefaultClause CaseClausesopt }
  1. 最初のCaseClausesが存在するなら、decls1を最初のCaseClausesVarScopedDeclarationsとする。
  2. そうでなければ、decls1を新しい空のListとする。
  3. decls2DefaultClauseVarScopedDeclarationsとする。
  4. 2番目のCaseClausesが存在するなら、decls3を2番目のCaseClausesVarScopedDeclarationsとする。
  5. そうでなければ、decls3を新しい空のListとする。
  6. decls1decls2、およびdecls3list-concatenationを返す。
CaseClauses : CaseClauses CaseClause
  1. decls1CaseClausesVarScopedDeclarationsとする。
  2. decls2CaseClauseVarScopedDeclarationsとする。
  3. decls1decls2list-concatenationを返す。
CaseClause : case Expression : StatementListopt
  1. StatementListが存在するなら、StatementListVarScopedDeclarationsを返す。
  2. 新しい空のListを返す。
DefaultClause : default : StatementListopt
  1. StatementListが存在するなら、StatementListVarScopedDeclarationsを返す。
  2. 新しい空のListを返す。
LabelledStatement : LabelIdentifier : LabelledItem
  1. LabelledItemVarScopedDeclarationsを返す。
LabelledItem : FunctionDeclaration
  1. 新しい空のListを返す。
TryStatement : try Block Catch
  1. decls1BlockVarScopedDeclarationsとする。
  2. decls2CatchVarScopedDeclarationsとする。
  3. decls1decls2list-concatenationを返す。
TryStatement : try Block Finally
  1. decls1BlockVarScopedDeclarationsとする。
  2. decls2FinallyVarScopedDeclarationsとする。
  3. decls1decls2list-concatenationを返す。
TryStatement : try Block Catch Finally
  1. decls1BlockVarScopedDeclarationsとする。
  2. decls2CatchVarScopedDeclarationsとする。
  3. decls3FinallyVarScopedDeclarationsとする。
  4. decls1decls2、およびdecls3list-concatenationを返す。
Catch : catch ( CatchParameter ) Block
  1. BlockVarScopedDeclarationsを返す。
FunctionStatementList : [empty]
  1. 新しい空のListを返す。
FunctionStatementList : StatementList
  1. StatementListTopLevelVarScopedDeclarationsを返す。
ClassStaticBlockStatementList : [empty]
  1. 新しい空のListを返す。
ClassStaticBlockStatementList : StatementList
  1. StatementListTopLevelVarScopedDeclarationsを返す。
ConciseBody : ExpressionBody
  1. 新しい空のListを返す。
AsyncConciseBody : ExpressionBody
  1. 新しい空のListを返す。
Script : [empty]
  1. 新しい空のListを返す。
ScriptBody : StatementList
  1. StatementListTopLevelVarScopedDeclarationsを返す。
Module : [empty]
  1. 新しい空のListを返す。
ModuleItemList : ModuleItemList ModuleItem
  1. decls1ModuleItemListVarScopedDeclarationsとする。
  2. decls2ModuleItemVarScopedDeclarationsとする。
  3. decls1decls2list-concatenationを返す。
ModuleItem : ImportDeclaration
  1. 新しい空のListを返す。
ExportDeclaration : export ExportFromClause FromClause WithClauseopt ; export NamedExports ; export VariableStatement
  1. 新しい空のListを返す。
ExportDeclaration : export Declaration
  1. 唯一の要素がDeclarationDeclarationPartであるListを返す。
ExportDeclaration : export default HoistableDeclaration
  1. 唯一の要素がHoistableDeclarationDeclarationPartであるListを返す。
ExportDeclaration : export default ClassDeclaration
  1. 唯一の要素がClassDeclarationであるListを返す。
ExportDeclaration : export default AssignmentExpression ;
  1. 唯一の要素がこのExportDeclarationであるListを返す。

8.2.10 Static Semantics: TopLevelLexicallyDeclaredNames

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

StatementList : StatementList StatementListItem
  1. names1StatementListTopLevelLexicallyDeclaredNamesとする。
  2. names2StatementListItemTopLevelLexicallyDeclaredNamesとする。
  3. names1names2list-concatenationを返す。
StatementListItem : Statement
  1. 新しい空のListを返す。
StatementListItem : Declaration
  1. Declaration Declaration : HoistableDeclaration であるなら、
    1. 新しい空のListを返す。
  2. DeclarationBoundNamesを返す。
Note

functionまたはscriptのtop levelでは、function declarationsはlexical declarationsのようにではなく、var declarationsのように扱われます。

8.2.11 Static Semantics: TopLevelLexicallyScopedDeclarations

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

StatementList : StatementList StatementListItem
  1. decls1StatementListTopLevelLexicallyScopedDeclarationsとする。
  2. decls2StatementListItemTopLevelLexicallyScopedDeclarationsとする。
  3. decls1decls2list-concatenationを返す。
StatementListItem : Statement
  1. 新しい空のListを返す。
StatementListItem : Declaration
  1. Declaration Declaration : HoistableDeclaration であるなら、
    1. 新しい空のListを返す。
  2. « Declaration »を返す。

8.2.12 Static Semantics: TopLevelVarDeclaredNames

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

StatementList : StatementList StatementListItem
  1. names1StatementListTopLevelVarDeclaredNamesとする。
  2. names2StatementListItemTopLevelVarDeclaredNamesとする。
  3. names1names2list-concatenationを返す。
StatementListItem : Declaration
  1. Declaration Declaration : HoistableDeclaration であるなら、
    1. HoistableDeclarationBoundNamesを返す。
  2. 新しい空のListを返す。
StatementListItem : Statement
  1. Statement Statement : LabelledStatement であるなら、StatementTopLevelVarDeclaredNamesを返す。
  2. StatementVarDeclaredNamesを返す。
Note

functionまたはscriptのtop levelでは、inner function declarationsはvar declarationsのように扱われます。

LabelledStatement : LabelIdentifier : LabelledItem
  1. LabelledItemTopLevelVarDeclaredNamesを返す。
LabelledItem : Statement
  1. Statement Statement : LabelledStatement であるなら、StatementTopLevelVarDeclaredNamesを返す。
  2. StatementVarDeclaredNamesを返す。
LabelledItem : FunctionDeclaration
  1. FunctionDeclarationBoundNamesを返す。

8.2.13 Static Semantics: TopLevelVarScopedDeclarations

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

StatementList : StatementList StatementListItem
  1. decls1StatementListTopLevelVarScopedDeclarationsとする。
  2. decls2StatementListItemTopLevelVarScopedDeclarationsとする。
  3. decls1decls2list-concatenationを返す。
StatementListItem : Statement
  1. Statement Statement : LabelledStatement であるなら、StatementTopLevelVarScopedDeclarationsを返す。
  2. StatementVarScopedDeclarationsを返す。
StatementListItem : Declaration
  1. Declaration Declaration : HoistableDeclaration であるなら、
    1. declHoistableDeclarationDeclarationPartとする。
    2. « decl »を返す。
  2. 新しい空のListを返す。
LabelledStatement : LabelIdentifier : LabelledItem
  1. LabelledItemTopLevelVarScopedDeclarationsを返す。
LabelledItem : Statement
  1. Statement Statement : LabelledStatement であるなら、StatementTopLevelVarScopedDeclarationsを返す。
  2. StatementVarScopedDeclarationsを返す。
LabelledItem : FunctionDeclaration
  1. « FunctionDeclaration »を返す。

8.3 ラベル

8.3.1 Static Semantics: ContainsDuplicateLabels

The syntax-directed operation ContainsDuplicateLabels takes argument labelSet (a List of Strings) and returns a Boolean. It is defined piecewise over the following productions:

Statement : VariableStatement EmptyStatement ExpressionStatement ContinueStatement BreakStatement ReturnStatement ThrowStatement DebuggerStatement Block : { } StatementListItem : Declaration
  1. falseを返す。
StatementList : StatementList StatementListItem
  1. hasDuplicatesを、引数labelSetを伴うStatementListContainsDuplicateLabelsとする。
  2. hasDuplicatestrueなら、trueを返す。
  3. 引数labelSetを伴うStatementListItemContainsDuplicateLabelsを返す。
IfStatement : if ( Expression ) Statement else Statement
  1. hasDuplicateを、引数labelSetを伴う最初のStatementContainsDuplicateLabelsとする。
  2. hasDuplicatetrueなら、trueを返す。
  3. 引数labelSetを伴う2番目のStatementContainsDuplicateLabelsを返す。
IfStatement : if ( Expression ) Statement
  1. 引数labelSetを伴うStatementContainsDuplicateLabelsを返す。
DoWhileStatement : do Statement while ( Expression ) ;
  1. 引数labelSetを伴うStatementContainsDuplicateLabelsを返す。
WhileStatement : while ( Expression ) Statement
  1. 引数labelSetを伴うStatementContainsDuplicateLabelsを返す。
ForStatement : for ( Expressionopt ; Expressionopt ; Expressionopt ) Statement for ( var VariableDeclarationList ; Expressionopt ; Expressionopt ) Statement for ( LexicalDeclaration Expressionopt ; Expressionopt ) Statement
  1. 引数labelSetを伴うStatementContainsDuplicateLabelsを返す。
ForInOfStatement : for ( LeftHandSideExpression in Expression ) Statement for ( var ForBinding in Expression ) Statement for ( ForDeclaration in Expression ) Statement for ( LeftHandSideExpression of AssignmentExpression ) Statement for ( var ForBinding of AssignmentExpression ) Statement for ( ForDeclaration of AssignmentExpression ) Statement for await ( LeftHandSideExpression of AssignmentExpression ) Statement for await ( var ForBinding of AssignmentExpression ) Statement for await ( ForDeclaration of AssignmentExpression ) Statement
  1. 引数labelSetを伴うStatementContainsDuplicateLabelsを返す。
Note

この節はAnnex B.3.5によって拡張されます。

WithStatement : with ( Expression ) Statement
  1. 引数labelSetを伴うStatementContainsDuplicateLabelsを返す。
SwitchStatement : switch ( Expression ) CaseBlock
  1. 引数labelSetを伴うCaseBlockContainsDuplicateLabelsを返す。
CaseBlock : { }
  1. falseを返す。
CaseBlock : { CaseClausesopt DefaultClause CaseClausesopt }
  1. 最初のCaseClausesが存在するなら、
    1. 引数labelSetを伴う最初のCaseClausesContainsDuplicateLabelstrueなら、trueを返す。
  2. 引数labelSetを伴うDefaultClauseContainsDuplicateLabelstrueなら、trueを返す。
  3. 2番目のCaseClausesが存在しないなら、falseを返す。
  4. 引数labelSetを伴う2番目のCaseClausesContainsDuplicateLabelsを返す。
CaseClauses : CaseClauses CaseClause
  1. hasDuplicatesを、引数labelSetを伴うCaseClausesContainsDuplicateLabelsとする。
  2. hasDuplicatestrueなら、trueを返す。
  3. 引数labelSetを伴うCaseClauseContainsDuplicateLabelsを返す。
CaseClause : case Expression : StatementListopt
  1. StatementListが存在するなら、引数labelSetを伴うStatementListContainsDuplicateLabelsを返す。
  2. falseを返す。
DefaultClause : default : StatementListopt
  1. StatementListが存在するなら、引数labelSetを伴うStatementListContainsDuplicateLabelsを返す。
  2. falseを返す。
LabelledStatement : LabelIdentifier : LabelledItem
  1. labelLabelIdentifierStringValueとする。
  2. labelSetlabelを含むなら、trueを返す。
  3. newLabelSetlabelSetと« label »のlist-concatenationとする。
  4. 引数newLabelSetを伴うLabelledItemContainsDuplicateLabelsを返す。
LabelledItem : FunctionDeclaration
  1. falseを返す。
TryStatement : try Block Catch
  1. hasDuplicatesを、引数labelSetを伴うBlockContainsDuplicateLabelsとする。
  2. hasDuplicatestrueなら、trueを返す。
  3. 引数labelSetを伴うCatchContainsDuplicateLabelsを返す。
TryStatement : try Block Finally
  1. hasDuplicatesを、引数labelSetを伴うBlockContainsDuplicateLabelsとする。
  2. hasDuplicatestrueなら、trueを返す。
  3. 引数labelSetを伴うFinallyContainsDuplicateLabelsを返す。
TryStatement : try Block Catch Finally
  1. 引数labelSetを伴うBlockContainsDuplicateLabelstrueなら、trueを返す。
  2. 引数labelSetを伴うCatchContainsDuplicateLabelstrueなら、trueを返す。
  3. 引数labelSetを伴うFinallyContainsDuplicateLabelsを返す。
Catch : catch ( CatchParameter ) Block
  1. 引数labelSetを伴うBlockContainsDuplicateLabelsを返す。
FunctionStatementList : [empty]
  1. falseを返す。
ClassStaticBlockStatementList : [empty]
  1. falseを返す。
ModuleItemList : ModuleItemList ModuleItem
  1. hasDuplicatesを、引数labelSetを伴うModuleItemListContainsDuplicateLabelsとする。
  2. hasDuplicatestrueなら、trueを返す。
  3. 引数labelSetを伴うModuleItemContainsDuplicateLabelsを返す。
ModuleItem : ImportDeclaration ExportDeclaration
  1. falseを返す。

8.3.2 Static Semantics: ContainsUndefinedBreakTarget

The syntax-directed operation ContainsUndefinedBreakTarget takes argument labelSet (a List of Strings) and returns a Boolean. It is defined piecewise over the following productions:

Statement : VariableStatement EmptyStatement ExpressionStatement ContinueStatement ReturnStatement ThrowStatement DebuggerStatement Block : { } StatementListItem : Declaration
  1. falseを返す。
StatementList : StatementList StatementListItem
  1. hasUndefinedLabelsを、引数labelSetを伴うStatementListContainsUndefinedBreakTargetとする。
  2. hasUndefinedLabelstrueなら、trueを返す。
  3. 引数labelSetを伴うStatementListItemContainsUndefinedBreakTargetを返す。
IfStatement : if ( Expression ) Statement else Statement
  1. hasUndefinedLabelsを、引数labelSetを伴う最初のStatementContainsUndefinedBreakTargetとする。
  2. hasUndefinedLabelstrueなら、trueを返す。
  3. 引数labelSetを伴う2番目のStatementContainsUndefinedBreakTargetを返す。
IfStatement : if ( Expression ) Statement
  1. 引数labelSetを伴うStatementContainsUndefinedBreakTargetを返す。
DoWhileStatement : do Statement while ( Expression ) ;
  1. 引数labelSetを伴うStatementContainsUndefinedBreakTargetを返す。
WhileStatement : while ( Expression ) Statement
  1. 引数labelSetを伴うStatementContainsUndefinedBreakTargetを返す。
ForStatement : for ( Expressionopt ; Expressionopt ; Expressionopt ) Statement for ( var VariableDeclarationList ; Expressionopt ; Expressionopt ) Statement for ( LexicalDeclaration Expressionopt ; Expressionopt ) Statement
  1. 引数labelSetを伴うStatementContainsUndefinedBreakTargetを返す。
ForInOfStatement : for ( LeftHandSideExpression in Expression ) Statement for ( var ForBinding in Expression ) Statement for ( ForDeclaration in Expression ) Statement for ( LeftHandSideExpression of AssignmentExpression ) Statement for ( var ForBinding of AssignmentExpression ) Statement for ( ForDeclaration of AssignmentExpression ) Statement for await ( LeftHandSideExpression of AssignmentExpression ) Statement for await ( var ForBinding of AssignmentExpression ) Statement for await ( ForDeclaration of AssignmentExpression ) Statement
  1. 引数labelSetを伴うStatementContainsUndefinedBreakTargetを返す。
Note

この節はAnnex B.3.5によって拡張されます。

BreakStatement : break ;
  1. falseを返す。
BreakStatement : break LabelIdentifier ;
  1. labelSetLabelIdentifierStringValueを含むなら、falseを返す。
  2. trueを返す。
WithStatement : with ( Expression ) Statement
  1. 引数labelSetを伴うStatementContainsUndefinedBreakTargetを返す。
SwitchStatement : switch ( Expression ) CaseBlock
  1. 引数labelSetを伴うCaseBlockContainsUndefinedBreakTargetを返す。
CaseBlock : { }
  1. falseを返す。
CaseBlock : { CaseClausesopt DefaultClause CaseClausesopt }
  1. 最初のCaseClausesが存在するなら、
    1. 引数labelSetを伴う最初のCaseClausesContainsUndefinedBreakTargettrueなら、trueを返す。
  2. 引数labelSetを伴うDefaultClauseContainsUndefinedBreakTargettrueなら、trueを返す。
  3. 2番目のCaseClausesが存在しないなら、falseを返す。
  4. 引数labelSetを伴う2番目のCaseClausesContainsUndefinedBreakTargetを返す。
CaseClauses : CaseClauses CaseClause
  1. hasUndefinedLabelsを、引数labelSetを伴うCaseClausesContainsUndefinedBreakTargetとする。
  2. hasUndefinedLabelstrueなら、trueを返す。
  3. 引数labelSetを伴うCaseClauseContainsUndefinedBreakTargetを返す。
CaseClause : case Expression : StatementListopt
  1. StatementListが存在するなら、引数labelSetを伴うStatementListContainsUndefinedBreakTargetを返す。
  2. falseを返す。
DefaultClause : default : StatementListopt
  1. StatementListが存在するなら、引数labelSetを伴うStatementListContainsUndefinedBreakTargetを返す。
  2. falseを返す。
LabelledStatement : LabelIdentifier : LabelledItem
  1. labelLabelIdentifierStringValueとする。
  2. newLabelSetlabelSetと« label »のlist-concatenationとする。
  3. 引数newLabelSetを伴うLabelledItemContainsUndefinedBreakTargetを返す。
LabelledItem : FunctionDeclaration
  1. falseを返す。
TryStatement : try Block Catch
  1. hasUndefinedLabelsを、引数labelSetを伴うBlockContainsUndefinedBreakTargetとする。
  2. hasUndefinedLabelstrueなら、trueを返す。
  3. 引数labelSetを伴うCatchContainsUndefinedBreakTargetを返す。
TryStatement : try Block Finally
  1. hasUndefinedLabelsを、引数labelSetを伴うBlockContainsUndefinedBreakTargetとする。
  2. hasUndefinedLabelstrueなら、trueを返す。
  3. 引数labelSetを伴うFinallyContainsUndefinedBreakTargetを返す。
TryStatement : try Block Catch Finally
  1. 引数labelSetを伴うBlockContainsUndefinedBreakTargettrueなら、trueを返す。
  2. 引数labelSetを伴うCatchContainsUndefinedBreakTargettrueなら、trueを返す。
  3. 引数labelSetを伴うFinallyContainsUndefinedBreakTargetを返す。
Catch : catch ( CatchParameter ) Block
  1. 引数labelSetを伴うBlockContainsUndefinedBreakTargetを返す。
FunctionStatementList : [empty]
  1. falseを返す。
ClassStaticBlockStatementList : [empty]
  1. falseを返す。
ModuleItemList : ModuleItemList ModuleItem
  1. hasUndefinedLabelsを、引数labelSetを伴うModuleItemListContainsUndefinedBreakTargetとする。
  2. hasUndefinedLabelstrueなら、trueを返す。
  3. 引数labelSetを伴うModuleItemContainsUndefinedBreakTargetを返す。
ModuleItem : ImportDeclaration ExportDeclaration
  1. falseを返す。

8.3.3 Static Semantics: ContainsUndefinedContinueTarget

The syntax-directed operation ContainsUndefinedContinueTarget takes arguments iterationSet (a List of Strings) and labelSet (a List of Strings) and returns a Boolean. It is defined piecewise over the following productions:

Statement : VariableStatement EmptyStatement ExpressionStatement BreakStatement ReturnStatement ThrowStatement DebuggerStatement Block : { } StatementListItem : Declaration
  1. falseを返す。
Statement : BlockStatement
  1. 引数iterationSetおよび« »を伴うBlockStatementContainsUndefinedContinueTargetを返す。
BreakableStatement : IterationStatement
  1. newIterationSetiterationSetlabelSetlist-concatenationとする。
  2. 引数newIterationSetおよび« »を伴うIterationStatementContainsUndefinedContinueTargetを返す。
StatementList : StatementList StatementListItem
  1. hasUndefinedLabelsを、引数iterationSetおよび« »を伴うStatementListContainsUndefinedContinueTargetとする。
  2. hasUndefinedLabelstrueなら、trueを返す。
  3. 引数iterationSetおよび« »を伴うStatementListItemContainsUndefinedContinueTargetを返す。
IfStatement : if ( Expression ) Statement else Statement
  1. hasUndefinedLabelsを、引数iterationSetおよび« »を伴う最初のStatementContainsUndefinedContinueTargetとする。
  2. hasUndefinedLabelstrueなら、trueを返す。
  3. 引数iterationSetおよび« »を伴う2番目のStatementContainsUndefinedContinueTargetを返す。
IfStatement : if ( Expression ) Statement
  1. 引数iterationSetおよび« »を伴うStatementContainsUndefinedContinueTargetを返す。
DoWhileStatement : do Statement while ( Expression ) ;
  1. 引数iterationSetおよび« »を伴うStatementContainsUndefinedContinueTargetを返す。
WhileStatement : while ( Expression ) Statement
  1. 引数iterationSetおよび« »を伴うStatementContainsUndefinedContinueTargetを返す。
ForStatement : for ( Expressionopt ; Expressionopt ; Expressionopt ) Statement for ( var VariableDeclarationList ; Expressionopt ; Expressionopt ) Statement for ( LexicalDeclaration Expressionopt ; Expressionopt ) Statement
  1. 引数iterationSetおよび« »を伴うStatementContainsUndefinedContinueTargetを返す。
ForInOfStatement : for ( LeftHandSideExpression in Expression ) Statement for ( var ForBinding in Expression ) Statement for ( ForDeclaration in Expression ) Statement for ( LeftHandSideExpression of AssignmentExpression ) Statement for ( var ForBinding of AssignmentExpression ) Statement for ( ForDeclaration of AssignmentExpression ) Statement for await ( LeftHandSideExpression of AssignmentExpression ) Statement for await ( var ForBinding of AssignmentExpression ) Statement for await ( ForDeclaration of AssignmentExpression ) Statement
  1. 引数iterationSetおよび« »を伴うStatementContainsUndefinedContinueTargetを返す。
Note

この節はAnnex B.3.5によって拡張されます。

ContinueStatement : continue ;
  1. falseを返す。
ContinueStatement : continue LabelIdentifier ;
  1. iterationSetLabelIdentifierStringValueを含むなら、falseを返す。
  2. trueを返す。
WithStatement : with ( Expression ) Statement
  1. 引数iterationSetおよび« »を伴うStatementContainsUndefinedContinueTargetを返す。
SwitchStatement : switch ( Expression ) CaseBlock
  1. 引数iterationSetおよび« »を伴うCaseBlockContainsUndefinedContinueTargetを返す。
CaseBlock : { }
  1. falseを返す。
CaseBlock : { CaseClausesopt DefaultClause CaseClausesopt }
  1. 最初のCaseClausesが存在するなら、
    1. 引数iterationSetおよび« »を伴う最初のCaseClausesContainsUndefinedContinueTargettrueなら、trueを返す。
  2. 引数iterationSetおよび« »を伴うDefaultClauseContainsUndefinedContinueTargettrueなら、trueを返す。
  3. 2番目のCaseClausesが存在しないなら、falseを返す。
  4. 引数iterationSetおよび« »を伴う2番目のCaseClausesContainsUndefinedContinueTargetを返す。
CaseClauses : CaseClauses CaseClause
  1. hasUndefinedLabelsを、引数iterationSetおよび« »を伴うCaseClausesContainsUndefinedContinueTargetとする。
  2. hasUndefinedLabelstrueなら、trueを返す。
  3. 引数iterationSetおよび« »を伴うCaseClauseContainsUndefinedContinueTargetを返す。
CaseClause : case Expression : StatementListopt
  1. StatementListが存在するなら、引数iterationSetおよび« »を伴うStatementListContainsUndefinedContinueTargetを返す。
  2. falseを返す。
DefaultClause : default : StatementListopt
  1. StatementListが存在するなら、引数iterationSetおよび« »を伴うStatementListContainsUndefinedContinueTargetを返す。
  2. falseを返す。
LabelledStatement : LabelIdentifier : LabelledItem
  1. labelLabelIdentifierStringValueとする。
  2. newLabelSetlabelSetと« label »のlist-concatenationとする。
  3. 引数iterationSetおよびnewLabelSetを伴うLabelledItemContainsUndefinedContinueTargetを返す。
LabelledItem : FunctionDeclaration
  1. falseを返す。
TryStatement : try Block Catch
  1. hasUndefinedLabelsを、引数iterationSetおよび« »を伴うBlockContainsUndefinedContinueTargetとする。
  2. hasUndefinedLabelstrueなら、trueを返す。
  3. 引数iterationSetおよび« »を伴うCatchContainsUndefinedContinueTargetを返す。
TryStatement : try Block Finally
  1. hasUndefinedLabelsを、引数iterationSetおよび« »を伴うBlockContainsUndefinedContinueTargetとする。
  2. hasUndefinedLabelstrueなら、trueを返す。
  3. 引数iterationSetおよび« »を伴うFinallyContainsUndefinedContinueTargetを返す。
TryStatement : try Block Catch Finally
  1. 引数iterationSetおよび« »を伴うBlockContainsUndefinedContinueTargettrueなら、trueを返す。
  2. 引数iterationSetおよび« »を伴うCatchContainsUndefinedContinueTargettrueなら、trueを返す。
  3. 引数iterationSetおよび« »を伴うFinallyContainsUndefinedContinueTargetを返す。
Catch : catch ( CatchParameter ) Block
  1. 引数iterationSetおよび« »を伴うBlockContainsUndefinedContinueTargetを返す。
FunctionStatementList : [empty]
  1. falseを返す。
ClassStaticBlockStatementList : [empty]
  1. falseを返す。
ModuleItemList : ModuleItemList ModuleItem
  1. hasUndefinedLabelsを、引数iterationSetおよび« »を伴うModuleItemListContainsUndefinedContinueTargetとする。
  2. hasUndefinedLabelstrueなら、trueを返す。
  3. 引数iterationSetおよび« »を伴うModuleItemContainsUndefinedContinueTargetを返す。
ModuleItem : ImportDeclaration ExportDeclaration
  1. falseを返す。

8.4 関数名推論

8.4.1 Static Semantics: HasName

The syntax-directed operation HasName takes no arguments and returns a Boolean. It is defined piecewise over the following productions:

PrimaryExpression : CoverParenthesizedExpressionAndArrowParameterList
  1. exprを、CoverParenthesizedExpressionAndArrowParameterListによってcoverされるParenthesizedExpressionとする。
  2. exprIsFunctionDefinitionfalseなら、falseを返す。
  3. exprHasNameを返す。
FunctionExpression : function ( FormalParameters ) { FunctionBody } GeneratorExpression : function * ( FormalParameters ) { GeneratorBody } AsyncGeneratorExpression : async function * ( FormalParameters ) { AsyncGeneratorBody } AsyncFunctionExpression : async function ( FormalParameters ) { AsyncFunctionBody } ArrowFunction : ArrowParameters => ConciseBody AsyncArrowFunction : async AsyncArrowBindingIdentifier => AsyncConciseBody CoverCallExpressionAndAsyncArrowHead => AsyncConciseBody ClassExpression : class ClassTail
  1. falseを返す。
FunctionExpression : function BindingIdentifier ( FormalParameters ) { FunctionBody } GeneratorExpression : function * BindingIdentifier ( FormalParameters ) { GeneratorBody } AsyncGeneratorExpression : async function * BindingIdentifier ( FormalParameters ) { AsyncGeneratorBody } AsyncFunctionExpression : async function BindingIdentifier ( FormalParameters ) { AsyncFunctionBody } ClassExpression : class BindingIdentifier ClassTail
  1. trueを返す。

8.4.2 Static Semantics: IsFunctionDefinition

The syntax-directed operation IsFunctionDefinition takes no arguments and returns a Boolean. It is defined piecewise over the following productions:

PrimaryExpression : CoverParenthesizedExpressionAndArrowParameterList
  1. exprを、CoverParenthesizedExpressionAndArrowParameterListによってcoverされるParenthesizedExpressionとする。
  2. exprIsFunctionDefinitionを返す。
PrimaryExpression : this IdentifierReference Literal ArrayLiteral ObjectLiteral RegularExpressionLiteral TemplateLiteral MemberExpression : MemberExpression [ Expression ] MemberExpression . IdentifierName MemberExpression TemplateLiteral SuperProperty MetaProperty new MemberExpression Arguments MemberExpression . PrivateIdentifier NewExpression : new NewExpression LeftHandSideExpression : CallExpression OptionalExpression UpdateExpression : LeftHandSideExpression ++ LeftHandSideExpression -- ++ UnaryExpression -- UnaryExpression UnaryExpression : delete UnaryExpression void UnaryExpression typeof UnaryExpression + UnaryExpression - UnaryExpression ~ UnaryExpression ! UnaryExpression CoverAwaitExpressionAndAwaitUsingDeclarationHead ExponentiationExpression : UpdateExpression ** ExponentiationExpression MultiplicativeExpression : MultiplicativeExpression MultiplicativeOperator ExponentiationExpression AdditiveExpression : AdditiveExpression + MultiplicativeExpression AdditiveExpression - MultiplicativeExpression ShiftExpression : ShiftExpression << AdditiveExpression ShiftExpression >> AdditiveExpression ShiftExpression >>> AdditiveExpression RelationalExpression : RelationalExpression < ShiftExpression RelationalExpression > ShiftExpression RelationalExpression <= ShiftExpression RelationalExpression >= ShiftExpression RelationalExpression instanceof ShiftExpression RelationalExpression in ShiftExpression PrivateIdentifier in ShiftExpression EqualityExpression : EqualityExpression == RelationalExpression EqualityExpression != RelationalExpression EqualityExpression === RelationalExpression EqualityExpression !== RelationalExpression BitwiseANDExpression : BitwiseANDExpression & EqualityExpression BitwiseXORExpression : BitwiseXORExpression ^ BitwiseANDExpression BitwiseORExpression : BitwiseORExpression | BitwiseXORExpression LogicalANDExpression : LogicalANDExpression && BitwiseORExpression LogicalORExpression : LogicalORExpression || LogicalANDExpression CoalesceExpression : CoalesceExpressionHead ?? BitwiseORExpression ConditionalExpression : ShortCircuitExpression ? AssignmentExpression : AssignmentExpression AssignmentExpression : YieldExpression LeftHandSideExpression = AssignmentExpression LeftHandSideExpression AssignmentOperator AssignmentExpression LeftHandSideExpression &&= AssignmentExpression LeftHandSideExpression ||= AssignmentExpression LeftHandSideExpression ??= AssignmentExpression Expression : Expression , AssignmentExpression
  1. falseを返す。
AssignmentExpression : ArrowFunction AsyncArrowFunction FunctionExpression : function BindingIdentifieropt ( FormalParameters ) { FunctionBody } GeneratorExpression : function * BindingIdentifieropt ( FormalParameters ) { GeneratorBody } AsyncGeneratorExpression : async function * BindingIdentifieropt ( FormalParameters ) { AsyncGeneratorBody } AsyncFunctionExpression : async function BindingIdentifieropt ( FormalParameters ) { AsyncFunctionBody } ClassExpression : class BindingIdentifieropt ClassTail
  1. trueを返す。

8.4.3 Static Semantics: IsAnonymousFunctionDefinition ( expr )

The abstract operation IsAnonymousFunctionDefinition takes argument expr (an AssignmentExpression Parse Node, an Initializer Parse Node, or an Expression Parse Node) and returns a Boolean. これは、その引数が名前を束縛しない関数定義であるかどうかを決定します。 It performs the following steps when called:

  1. exprIsFunctionDefinitionfalseなら、falseを返す。
  2. hasNameexprHasNameとする。
  3. hasNametrueなら、falseを返す。
  4. trueを返す。

8.4.4 Static Semantics: IsIdentifierRef

The syntax-directed operation IsIdentifierRef takes no arguments and returns a Boolean. It is defined piecewise over the following productions:

PrimaryExpression : IdentifierReference
  1. trueを返す。
PrimaryExpression : this Literal ArrayLiteral ObjectLiteral FunctionExpression ClassExpression GeneratorExpression AsyncFunctionExpression AsyncGeneratorExpression RegularExpressionLiteral TemplateLiteral CoverParenthesizedExpressionAndArrowParameterList MemberExpression : MemberExpression [ Expression ] MemberExpression . IdentifierName MemberExpression TemplateLiteral SuperProperty MetaProperty new MemberExpression Arguments MemberExpression . PrivateIdentifier NewExpression : new NewExpression LeftHandSideExpression : CallExpression OptionalExpression
  1. falseを返す。

8.4.5 Runtime Semantics: NamedEvaluation

The syntax-directed operation NamedEvaluation takes argument name (a property key or a Private Name) and returns either a normal completion containing a function object or an abrupt completion. It is defined piecewise over the following productions:

PrimaryExpression : CoverParenthesizedExpressionAndArrowParameterList
  1. exprを、CoverParenthesizedExpressionAndArrowParameterListによってcoverされるParenthesizedExpressionとする。
  2. 引数nameを伴うexprNamedEvaluationを ? で返す。
ParenthesizedExpression : ( Expression )
  1. Assert: IsAnonymousFunctionDefinition(Expression)はtrueである。
  2. 引数nameを伴うExpressionNamedEvaluationを ? で返す。
FunctionExpression : function ( FormalParameters ) { FunctionBody }
  1. 引数nameを伴うFunctionExpressionInstantiateOrdinaryFunctionExpressionを返す。
GeneratorExpression : function * ( FormalParameters ) { GeneratorBody }
  1. 引数nameを伴うGeneratorExpressionInstantiateGeneratorFunctionExpressionを返す。
AsyncGeneratorExpression : async function * ( FormalParameters ) { AsyncGeneratorBody }
  1. 引数nameを伴うAsyncGeneratorExpressionInstantiateAsyncGeneratorFunctionExpressionを返す。
AsyncFunctionExpression : async function ( FormalParameters ) { AsyncFunctionBody }
  1. 引数nameを伴うAsyncFunctionExpressionInstantiateAsyncFunctionExpressionを返す。
ArrowFunction : ArrowParameters => ConciseBody
  1. 引数nameを伴うArrowFunctionInstantiateArrowFunctionExpressionを返す。
AsyncArrowFunction : async AsyncArrowBindingIdentifier => AsyncConciseBody CoverCallExpressionAndAsyncArrowHead => AsyncConciseBody
  1. 引数nameを伴うAsyncArrowFunctionInstantiateAsyncArrowFunctionExpressionを返す。
ClassExpression : class ClassTail
  1. sourceTextを、ClassExpressionに一致したsource textとする。
  2. 引数undefinedname、およびsourceTextを伴うClassTailClassDefinitionEvaluationを ? で返す。

8.5 Contains

8.5.1 Static Semantics: Contains

The syntax-directed operation Contains takes argument symbol (a grammar symbol) and returns a Boolean.

以下に列挙されていない、この仕様内のすべてのgrammar production alternativeは、暗黙的に次のContainsのデフォルト定義を持ちます:

  1. このParse Nodeの各child node childについて、以下を行う
    1. childsymbolのinstanceなら、trueを返す。
    2. childがnonterminalのinstanceなら、
      1. containedchild Contains symbolの結果とする。
      2. containedtrueなら、trueを返す。
  2. falseを返す。
FunctionDeclaration : function BindingIdentifier ( FormalParameters ) { FunctionBody } function ( FormalParameters ) { FunctionBody } FunctionExpression : function BindingIdentifieropt ( FormalParameters ) { FunctionBody } GeneratorDeclaration : function * BindingIdentifier ( FormalParameters ) { GeneratorBody } function * ( FormalParameters ) { GeneratorBody } GeneratorExpression : function * BindingIdentifieropt ( FormalParameters ) { GeneratorBody } AsyncGeneratorDeclaration : async function * BindingIdentifier ( FormalParameters ) { AsyncGeneratorBody } async function * ( FormalParameters ) { AsyncGeneratorBody } AsyncGeneratorExpression : async function * BindingIdentifieropt ( FormalParameters ) { AsyncGeneratorBody } AsyncFunctionDeclaration : async function BindingIdentifier ( FormalParameters ) { AsyncFunctionBody } async function ( FormalParameters ) { AsyncFunctionBody } AsyncFunctionExpression : async function BindingIdentifieropt ( FormalParameters ) { AsyncFunctionBody }
  1. falseを返す。
Note 1

部分構造に依存する静的意味規則は、一般に関数定義の内部を見ません。

ClassTail : ClassHeritageopt { ClassBody }
  1. symbolClassBodyなら、trueを返す。
  2. symbolClassHeritageなら、
    1. ClassHeritageが存在するなら、trueを返す。
    2. falseを返す。
  3. ClassHeritageが存在するなら、
    1. ClassHeritage Contains symboltrueなら、trueを返す。
  4. 引数symbolを伴うClassBodyComputedPropertyContainsの結果を返す。
Note 2

部分構造に依存する静的意味規則は、PropertyNameを除いて、一般にclass bodiesの内部を見ません。

ClassStaticBlock : static { ClassStaticBlockBody }
  1. falseを返す。
Note 3

部分構造に依存する静的意味規則は、一般にstatic初期化ブロックの内部を見ません。

ArrowFunction : ArrowParameters => ConciseBody
  1. symbolNewTargetSuperPropertySuperCallsuper、またはthisのいずれでもないなら、falseを返す。
  2. ArrowParameters Contains symboltrueなら、trueを返す。
  3. ConciseBody Contains symbolを返す。
ArrowParameters : CoverParenthesizedExpressionAndArrowParameterList
  1. formalsを、CoverParenthesizedExpressionAndArrowParameterListによってcoverされるArrowFormalParametersとする。
  2. formals Contains symbolを返す。
AsyncArrowFunction : async AsyncArrowBindingIdentifier => AsyncConciseBody
  1. symbolNewTargetSuperPropertySuperCallsuper、またはthisのいずれでもないなら、falseを返す。
  2. AsyncConciseBody Contains symbolを返す。
AsyncArrowFunction : CoverCallExpressionAndAsyncArrowHead => AsyncConciseBody
  1. symbolNewTargetSuperPropertySuperCallsuper、またはthisのいずれでもないなら、falseを返す。
  2. headを、CoverCallExpressionAndAsyncArrowHeadによってcoverされるAsyncArrowHeadとする。
  3. head Contains symboltrueなら、trueを返す。
  4. AsyncConciseBody Contains symbolを返す。
Note 4

Containsは、ArrowFunctionまたはAsyncArrowFunction内でのnew.targetthis、およびsuperの使用を検出するために使用されます。

PropertyDefinition : MethodDefinition
  1. symbolMethodDefinitionなら、trueを返す。
  2. 引数symbolを伴うMethodDefinitionComputedPropertyContainsの結果を返す。
LiteralPropertyName : IdentifierName
  1. falseを返す。
MemberExpression : MemberExpression . IdentifierName
  1. MemberExpression Contains symboltrueなら、trueを返す。
  2. falseを返す。
SuperProperty : super . IdentifierName
  1. symbolReservedWord superなら、trueを返す。
  2. falseを返す。
CallExpression : CallExpression . IdentifierName
  1. CallExpression Contains symboltrueなら、trueを返す。
  2. falseを返す。
OptionalChain : ?. IdentifierName
  1. falseを返す。
OptionalChain : OptionalChain . IdentifierName
  1. OptionalChain Contains symboltrueなら、trueを返す。
  2. falseを返す。

8.5.2 Static Semantics: ComputedPropertyContains

The syntax-directed operation ComputedPropertyContains takes argument symbol (a grammar symbol) and returns a Boolean. It is defined piecewise over the following productions:

ClassElementName : PrivateIdentifier PropertyName : LiteralPropertyName
  1. falseを返す。
PropertyName : ComputedPropertyName
  1. ComputedPropertyName Contains symbolの結果を返す。
MethodDefinition : ClassElementName ( UniqueFormalParameters ) { FunctionBody } get ClassElementName ( ) { FunctionBody } set ClassElementName ( PropertySetParameterList ) { FunctionBody }
  1. 引数symbolを伴うClassElementNameComputedPropertyContainsの結果を返す。
GeneratorMethod : * ClassElementName ( UniqueFormalParameters ) { GeneratorBody }
  1. 引数symbolを伴うClassElementNameComputedPropertyContainsの結果を返す。
AsyncGeneratorMethod : async * ClassElementName ( UniqueFormalParameters ) { AsyncGeneratorBody }
  1. 引数symbolを伴うClassElementNameComputedPropertyContainsの結果を返す。
ClassElementList : ClassElementList ClassElement
  1. inListを、引数symbolを伴うClassElementListComputedPropertyContainsとする。
  2. inListtrueなら、trueを返す。
  3. 引数symbolを伴うClassElementComputedPropertyContainsの結果を返す。
ClassElement : ClassStaticBlock
  1. falseを返す。
ClassElement : ;
  1. falseを返す。
AsyncMethod : async ClassElementName ( UniqueFormalParameters ) { AsyncFunctionBody }
  1. 引数symbolを伴うClassElementNameComputedPropertyContainsの結果を返す。
FieldDefinition : ClassElementName Initializeropt
  1. 引数symbolを伴うClassElementNameComputedPropertyContainsの結果を返す。

8.6 その他

これらの操作は、この仕様全体の複数の箇所で使用されます。

8.6.1 Runtime Semantics: InstantiateFunctionObject

The syntax-directed operation InstantiateFunctionObject takes arguments envRecord (an Environment Record) and privateEnv (a PrivateEnvironment Record or null) and returns an ECMAScript function object. It is defined piecewise over the following productions:

FunctionDeclaration : function BindingIdentifier ( FormalParameters ) { FunctionBody } function ( FormalParameters ) { FunctionBody }
  1. 引数envRecordおよびprivateEnvを伴うFunctionDeclarationInstantiateOrdinaryFunctionObjectを返す。
GeneratorDeclaration : function * BindingIdentifier ( FormalParameters ) { GeneratorBody } function * ( FormalParameters ) { GeneratorBody }
  1. 引数envRecordおよびprivateEnvを伴うGeneratorDeclarationInstantiateGeneratorFunctionObjectを返す。
AsyncGeneratorDeclaration : async function * BindingIdentifier ( FormalParameters ) { AsyncGeneratorBody } async function * ( FormalParameters ) { AsyncGeneratorBody }
  1. 引数envRecordおよびprivateEnvを伴うAsyncGeneratorDeclarationInstantiateAsyncGeneratorFunctionObjectを返す。
AsyncFunctionDeclaration : async function BindingIdentifier ( FormalParameters ) { AsyncFunctionBody } async function ( FormalParameters ) { AsyncFunctionBody }
  1. 引数envRecordおよびprivateEnvを伴うAsyncFunctionDeclarationInstantiateAsyncFunctionObjectを返す。

8.6.2 Runtime Semantics: BindingInitialization

The syntax-directed operation BindingInitialization takes arguments value (an ECMAScript language value) and envRecord (an Environment Record or undefined) and returns either a normal completion containing unused or an abrupt completion.

Note

envRecordundefinedが渡されることは、初期化値を代入するためにPutValue操作を使用すべきであることを示します。これはvar statementsおよび一部のnon-strict functionsのformal parameter listsの場合に該当します(10.2.11を参照)。それらの場合、lexical bindingは、そのinitializerの評価に先立ってhoistされ、事前初期化されます。

It is defined piecewise over the following productions:

BindingIdentifier : Identifier
  1. nameIdentifierStringValueとする。
  2. InitializeBoundName(name, value, envRecord)を ? で返す。
BindingIdentifier : yield
  1. InitializeBoundName("yield", value, envRecord)を ? で返す。
BindingIdentifier : await
  1. InitializeBoundName("await", value, envRecord)を ? で返す。
BindingPattern : ObjectBindingPattern
  1. RequireObjectCoercible(value)を ? で実行する。
  2. 引数valueおよびenvRecordを伴うObjectBindingPatternBindingInitializationを ? で返す。
BindingPattern : ArrayBindingPattern
  1. iteratorRecordを ? GetIterator(value, sync) とする。
  2. resultを、引数iteratorRecordおよびenvRecordを伴うArrayBindingPatternIteratorBindingInitializationCompletionとする。
  3. iteratorRecord.[[Done]]falseなら、IteratorClose(iteratorRecord, result)を ? で返す。
  4. resultを ? で返す。
ObjectBindingPattern : { }
  1. unusedを返す。
ObjectBindingPattern : { BindingPropertyList } { BindingPropertyList , }
  1. 引数valueおよびenvRecordを伴うBindingPropertyListPropertyBindingInitializationを ? で実行する。
  2. unusedを返す。
ObjectBindingPattern : { BindingRestProperty }
  1. excludedNamesを新しい空のListとする。
  2. 引数valueenvRecord、およびexcludedNamesを伴うBindingRestPropertyRestBindingInitializationを ? で返す。
ObjectBindingPattern : { BindingPropertyList , BindingRestProperty }
  1. excludedNamesを、引数valueおよびenvRecordを伴うBindingPropertyListPropertyBindingInitializationの ? 結果とする。
  2. 引数valueenvRecord、およびexcludedNamesを伴うBindingRestPropertyRestBindingInitializationを ? で返す。

8.6.2.1 InitializeBoundName ( name, value, envRecord )

The abstract operation InitializeBoundName takes arguments name (a String), value (an ECMAScript language value), and envRecord (an Environment Record or undefined) and returns either a normal completion containing unused or an abrupt completion. It performs the following steps when called:

  1. envRecordundefinedでないなら、
    1. envRecord.InitializeBinding(name, value)を ! で実行する。
    2. unusedを返す。
  2. lhsを ? ResolveBinding(name) とする。
  3. PutValue(lhs, value)を ? で返す。

8.6.3 Runtime Semantics: IteratorBindingInitialization

The syntax-directed operation IteratorBindingInitialization takes arguments iteratorRecord (an Iterator Record) and envRecord (an Environment Record or undefined) and returns either a normal completion containing unused or an abrupt completion.

Note

envRecordundefinedが渡される場合、それは初期化値を代入するためにPutValue操作を使用すべきであることを示します。これはnon-strict functionsのformal parameter listsの場合に該当します。その場合、同じ名前を持つ複数のparametersの可能性に対処するため、formal parameter bindingsは事前初期化されます。

It is defined piecewise over the following productions:

ArrayBindingPattern : [ ]
  1. unusedを返す。
ArrayBindingPattern : [ Elision ]
  1. 引数iteratorRecordを伴うElisionIteratorDestructuringAssignmentEvaluationを ? で返す。
ArrayBindingPattern : [ Elisionopt BindingRestElement ]
  1. Elisionが存在するなら、
    1. 引数iteratorRecordを伴うElisionIteratorDestructuringAssignmentEvaluationを ? で実行する。
  2. 引数iteratorRecordおよびenvRecordを伴うBindingRestElementIteratorBindingInitializationを ? で返す。
ArrayBindingPattern : [ BindingElementList , Elision ]
  1. 引数iteratorRecordおよびenvRecordを伴うBindingElementListIteratorBindingInitializationを ? で実行する。
  2. 引数iteratorRecordを伴うElisionIteratorDestructuringAssignmentEvaluationを ? で返す。
ArrayBindingPattern : [ BindingElementList , Elisionopt BindingRestElement ]
  1. 引数iteratorRecordおよびenvRecordを伴うBindingElementListIteratorBindingInitializationを ? で実行する。
  2. Elisionが存在するなら、
    1. 引数iteratorRecordを伴うElisionIteratorDestructuringAssignmentEvaluationを ? で実行する。
  3. 引数iteratorRecordおよびenvRecordを伴うBindingRestElementIteratorBindingInitializationを ? で返す。
BindingElementList : BindingElementList , BindingElisionElement
  1. 引数iteratorRecordおよびenvRecordを伴うBindingElementListIteratorBindingInitializationを ? で実行する。
  2. 引数iteratorRecordおよびenvRecordを伴うBindingElisionElementIteratorBindingInitializationを ? で返す。
BindingElisionElement : Elision BindingElement
  1. 引数iteratorRecordを伴うElisionIteratorDestructuringAssignmentEvaluationを ? で実行する。
  2. 引数iteratorRecordおよびenvRecordを伴うBindingElementIteratorBindingInitializationを ? で返す。
SingleNameBinding : BindingIdentifier Initializeropt
  1. bindingIdBindingIdentifierStringValueとする。
  2. lhsを ? ResolveBinding(bindingId, envRecord) とする。
  3. vundefinedとする。
  4. iteratorRecord.[[Done]]falseなら、
    1. nextを ? IteratorStepValue(iteratorRecord) とする。
    2. nextdoneでないなら、
      1. vnextに設定する。
  5. Initializerが存在し、かつvundefinedなら、
    1. IsAnonymousFunctionDefinition(Initializer)がtrueなら、
      1. vを、引数bindingIdを伴うInitializerNamedEvaluationの ? 結果に設定する。
    2. そうでなければ、
      1. defaultValueInitializerEvaluationの ? 結果とする。
      2. vを ? GetValue(defaultValue) に設定する。
  6. envRecordundefinedなら、PutValue(lhs, v)を ? で返す。
  7. InitializeReferencedBinding(lhs, v)を ? で返す。
BindingElement : BindingPattern Initializeropt
  1. vundefinedとする。
  2. iteratorRecord.[[Done]]falseなら、
    1. nextを ? IteratorStepValue(iteratorRecord) とする。
    2. nextdoneでないなら、
      1. vnextに設定する。
  3. Initializerが存在し、かつvundefinedなら、
    1. defaultValueInitializerEvaluationの ? 結果とする。
    2. vを ? GetValue(defaultValue) に設定する。
  4. 引数vおよびenvRecordを伴うBindingPatternBindingInitializationを ? で返す。
BindingRestElement : ... BindingIdentifier
  1. lhsを ? ResolveBinding(StringValue of BindingIdentifier, envRecord) とする。
  2. arrayを ! ArrayCreate(0) とする。
  3. nを0とする。
  4. 繰り返す
    1. nextdoneとする。
    2. iteratorRecord.[[Done]]falseなら、
      1. nextを ? IteratorStepValue(iteratorRecord) に設定する。
    3. nextdoneなら、
      1. envRecordundefinedなら、PutValue(lhs, array)を ? で返す。
      2. InitializeReferencedBinding(lhs, array)を ? で返す。
    4. CreateDataPropertyOrThrow(array, ! ToString(𝔽(n)), next)を ! で実行する。
    5. nn + 1に設定する。
BindingRestElement : ... BindingPattern
  1. arrayを ! ArrayCreate(0) とする。
  2. nを0とする。
  3. 繰り返す
    1. nextdoneとする。
    2. iteratorRecord.[[Done]]falseなら、
      1. nextを ? IteratorStepValue(iteratorRecord) に設定する。
    3. nextdoneなら、
      1. 引数arrayおよびenvRecordを伴うBindingPatternBindingInitializationを ? で返す。
    4. CreateDataPropertyOrThrow(array, ! ToString(𝔽(n)), next)を ! で実行する。
    5. nn + 1に設定する。
FormalParameters : [empty]
  1. unusedを返す。
FormalParameters : FormalParameterList , FunctionRestParameter
  1. 引数iteratorRecordおよびenvRecordを伴うFormalParameterListIteratorBindingInitializationを ? で実行する。
  2. 引数iteratorRecordおよびenvRecordを伴うFunctionRestParameterIteratorBindingInitializationを ? で返す。
FormalParameterList : FormalParameterList , FormalParameter
  1. 引数iteratorRecordおよびenvRecordを伴うFormalParameterListIteratorBindingInitializationを ? で実行する。
  2. 引数iteratorRecordおよびenvRecordを伴うFormalParameterIteratorBindingInitializationを ? で返す。
ArrowParameters : BindingIdentifier
  1. vundefinedとする。
  2. Assert: iteratorRecord.[[Done]]falseである。
  3. nextを ? IteratorStepValue(iteratorRecord) とする。
  4. nextdoneでないなら、
    1. vnextに設定する。
  5. 引数vおよびenvRecordを伴うBindingIdentifierBindingInitializationを ? で返す。
ArrowParameters : CoverParenthesizedExpressionAndArrowParameterList
  1. formalsを、CoverParenthesizedExpressionAndArrowParameterListによってcoverされるArrowFormalParametersとする。
  2. 引数iteratorRecordおよびenvRecordを伴うformalsIteratorBindingInitializationを ? で返す。
AsyncArrowBindingIdentifier : BindingIdentifier
  1. vundefinedとする。
  2. Assert: iteratorRecord.[[Done]]falseである。
  3. nextを ? IteratorStepValue(iteratorRecord) とする。
  4. nextdoneでないなら、
    1. vnextに設定する。
  5. 引数vおよびenvRecordを伴うBindingIdentifierBindingInitializationを ? で返す。

8.6.4 Static Semantics: AssignmentTargetType

The syntax-directed operation AssignmentTargetType takes no arguments and returns simple, web-compat, or invalid. It is defined piecewise over the following productions:

IdentifierReference : Identifier
  1. IsStrict(this IdentifierReference)がtrueであり、かつIdentifierStringValue"eval"または"arguments"のいずれかなら、invalidを返す。
  2. simpleを返す。
IdentifierReference : yield await CallExpression : CallExpression [ Expression ] CallExpression . IdentifierName CallExpression . PrivateIdentifier MemberExpression : MemberExpression [ Expression ] MemberExpression . IdentifierName SuperProperty MemberExpression . PrivateIdentifier
  1. simpleを返す。
PrimaryExpression : CoverParenthesizedExpressionAndArrowParameterList
  1. exprを、CoverParenthesizedExpressionAndArrowParameterListによってcoverされるParenthesizedExpressionとする。
  2. exprAssignmentTargetTypeを返す。
CallExpression : CoverCallExpressionAndAsyncArrowHead CallExpression Arguments
  1. hostがweb browserであるか、または他の方法でFunction Call Assignment Targetsに対するRuntime Errorsをサポートしており、かつIsStrict(this CallExpression)がfalseなら、
    1. web-compatを返す。
  2. invalidを返す。
PrimaryExpression : this Literal ArrayLiteral ObjectLiteral FunctionExpression ClassExpression GeneratorExpression AsyncFunctionExpression AsyncGeneratorExpression RegularExpressionLiteral TemplateLiteral CallExpression : SuperCall ImportCall CallExpression TemplateLiteral NewExpression : new NewExpression MemberExpression : MemberExpression TemplateLiteral new MemberExpression Arguments NewTarget : new . target ImportMeta : import . meta LeftHandSideExpression : OptionalExpression UpdateExpression : LeftHandSideExpression ++ LeftHandSideExpression -- ++ UnaryExpression -- UnaryExpression UnaryExpression : delete UnaryExpression void UnaryExpression typeof UnaryExpression + UnaryExpression - UnaryExpression ~ UnaryExpression ! UnaryExpression CoverAwaitExpressionAndAwaitUsingDeclarationHead ExponentiationExpression : UpdateExpression ** ExponentiationExpression MultiplicativeExpression : MultiplicativeExpression MultiplicativeOperator ExponentiationExpression AdditiveExpression : AdditiveExpression + MultiplicativeExpression AdditiveExpression - MultiplicativeExpression ShiftExpression : ShiftExpression << AdditiveExpression ShiftExpression >> AdditiveExpression ShiftExpression >>> AdditiveExpression RelationalExpression : RelationalExpression < ShiftExpression RelationalExpression > ShiftExpression RelationalExpression <= ShiftExpression RelationalExpression >= ShiftExpression RelationalExpression instanceof ShiftExpression RelationalExpression in ShiftExpression PrivateIdentifier in ShiftExpression EqualityExpression : EqualityExpression == RelationalExpression EqualityExpression != RelationalExpression EqualityExpression === RelationalExpression EqualityExpression !== RelationalExpression BitwiseANDExpression : BitwiseANDExpression & EqualityExpression BitwiseXORExpression : BitwiseXORExpression ^ BitwiseANDExpression BitwiseORExpression : BitwiseORExpression | BitwiseXORExpression LogicalANDExpression : LogicalANDExpression && BitwiseORExpression LogicalORExpression : LogicalORExpression || LogicalANDExpression CoalesceExpression : CoalesceExpressionHead ?? BitwiseORExpression ConditionalExpression : ShortCircuitExpression ? AssignmentExpression : AssignmentExpression AssignmentExpression : YieldExpression ArrowFunction AsyncArrowFunction LeftHandSideExpression = AssignmentExpression LeftHandSideExpression AssignmentOperator AssignmentExpression LeftHandSideExpression &&= AssignmentExpression LeftHandSideExpression ||= AssignmentExpression LeftHandSideExpression ??= AssignmentExpression Expression : Expression , AssignmentExpression
  1. invalidを返す。

8.6.5 Static Semantics: PropName

The syntax-directed operation PropName takes no arguments and returns a String or empty. It is defined piecewise over the following productions:

PropertyDefinition : IdentifierReference
  1. IdentifierReferenceStringValueを返す。
PropertyDefinition : ... AssignmentExpression
  1. emptyを返す。
PropertyDefinition : PropertyName : AssignmentExpression
  1. PropertyNamePropNameを返す。
LiteralPropertyName : IdentifierName AttributeKey : IdentifierName
  1. IdentifierNameStringValueを返す。
LiteralPropertyName : StringLiteral AttributeKey : StringLiteral
  1. StringLiteralSVを返す。
LiteralPropertyName : NumericLiteral
  1. numberNumericLiteralNumericValueとする。
  2. ToString(number)を返す。
ComputedPropertyName : [ AssignmentExpression ]
  1. emptyを返す。
MethodDefinition : ClassElementName ( UniqueFormalParameters ) { FunctionBody } get ClassElementName ( ) { FunctionBody } set ClassElementName ( PropertySetParameterList ) { FunctionBody }
  1. ClassElementNamePropNameを返す。
GeneratorMethod : * ClassElementName ( UniqueFormalParameters ) { GeneratorBody }
  1. ClassElementNamePropNameを返す。
AsyncGeneratorMethod : async * ClassElementName ( UniqueFormalParameters ) { AsyncGeneratorBody }
  1. ClassElementNamePropNameを返す。
ClassElement : ClassStaticBlock
  1. emptyを返す。
ClassElement : ;
  1. emptyを返す。
AsyncMethod : async ClassElementName ( UniqueFormalParameters ) { AsyncFunctionBody }
  1. ClassElementNamePropNameを返す。
FieldDefinition : ClassElementName Initializeropt
  1. ClassElementNamePropNameを返す。
ClassElementName : PrivateIdentifier
  1. emptyを返す。

8.6.6 Static Semantics: ContainsUsing

The syntax-directed operation ContainsUsing takes no arguments and returns Boolean. It is defined piecewise over the following productions:

StatementList : StatementList StatementListItem
  1. 派生した StatementListContainsUsingtrue である場合、true を返す。
  2. StatementListItemContainsUsingtrue である場合、true を返す。
  3. false を返す。
StatementListItem : Statement
  1. false を返す。
StatementListItem : Declaration
  1. DeclarationIsUsingDeclarationtrue である場合、true を返す。
  2. DeclarationIsAwaitUsingDeclarationtrue である場合、true を返す。
  3. false を返す。

9 実行可能コードと実行コンテキスト

9.1 Environment Records

Environment Recordは、ECMAScriptコードの字句的な入れ子構造に基づいて、Identifierと特定の変数および関数との関連付けを定義するために使用される仕様型です。通常、Environment Recordは、FunctionDeclarationBlockStatement、またはTryStatementCatch節など、ECMAScriptコードの何らかの特定の構文構造に関連付けられます。そのようなコードが評価されるたびに、そのコードによって作成されるidentifier bindingsを記録するため、新しいEnvironment Recordが作成されます。

すべてのEnvironment Recordは[[OuterEnv]]フィールドを持ち、これはnullまたは外側のEnvironment Recordへの参照のいずれかです。これは、Environment Record値の論理的な入れ子をモデル化するために使用されます。(内側の)Environment Recordの外側参照は、その内側のEnvironment Recordを論理的に取り囲むEnvironment Recordへの参照です。もちろん、外側のEnvironment Recordは、それ自身の外側のEnvironment Recordを持つ場合があります。1つのEnvironment Recordは、複数の内側Environment Recordsの外側環境として機能できます。たとえば、FunctionDeclarationが2つの入れ子になったFunctionDeclarationを含む場合、それぞれの入れ子関数のEnvironment Recordsは、周囲の関数の現在の評価のEnvironment Recordを、自身の外側Environment Recordとして持ちます。

Environment Recordsは純粋に仕様上の仕組みであり、ECMAScript実装の特定のartefactに対応する必要はありません。ECMAScriptプログラムがそのような値に直接アクセスしたり操作したりすることは不可能です。

9.1.1 Environment Record型階層

Environment Recordsは、Environment Recordが抽象クラスであり、Declarative Environment RecordObject Environment Record、およびGlobal Environment Recordという3つの具体サブクラスを持つ、単純なオブジェクト指向階層内に存在すると考えることができます。Function Environment RecordsおよびModule Environment Recordsは、Declarative Environment Recordのサブクラスです。

  • Environment Record(抽象)

    • Declarative Environment Recordは、FunctionDeclarationVariableDeclaration、およびCatch節など、identifier bindingsをECMAScript言語値と直接関連付けるECMAScript言語構文要素の効果を定義するために使用されます。

      • Function Environment Recordは、ECMAScript function objectの呼び出しに対応し、その関数内のtop-level declarationsに対するbindingsを含みます。これは新しいthis bindingを確立する場合があります。また、super method呼び出しをサポートするために必要な状態もcaptureします。

      • Module Environment Recordは、Moduleのtop-level declarationsに対するbindingsを含みます。また、Moduleによって明示的にimportされるbindingsも含みます。その[[OuterEnv]]Global Environment Recordです。

    • Object Environment Recordは、identifier bindingsを何らかのオブジェクトのプロパティと関連付けるWithStatementなどのECMAScript要素の効果を定義するために使用されます。

    • Global Environment Recordは、Scriptのglobal declarationsに使用されます。これは外側環境を持たず、その[[OuterEnv]]nullです。identifier bindingsが事前に設定されている場合があり、関連付けられたglobal objectを含み、そのプロパティはglobal environmentのidentifier bindingsの一部を提供します。ECMAScriptコードが実行されるにつれて、global objectに追加のプロパティが追加され、初期プロパティが変更される場合があります。

Environment Record抽象クラスは、Table 15で定義される抽象仕様メソッドを含みます。これらの抽象メソッドは、具体サブクラスごとに異なる具体アルゴリズムを持ちます。

Table 15: Abstract Methods of Environment Records
メソッド 目的 定義
HasBinding ( name )

The abstract method HasBinding takes argument name (a String) and returns either a normal completion containing a Boolean or a throw completion.

これは、Environment Recordnameに対するbindingを持つかどうかを決定します。
これは次の型に具体定義を持ちます:
CreateMutableBinding ( name, deletable )

The abstract method CreateMutableBinding takes arguments name (a String) and deletable (a Boolean) and returns either a normal completion containing unused or a throw completion.

これは、Environment Record内に、新しいが未初期化のmutable bindingを作成します。nameはbound nameのテキストです。deletabletrueなら、そのbindingは後で削除される場合があります。
これは次の型に具体定義を持ちます:
CreateImmutableBinding ( name, strict )

The abstract method CreateImmutableBinding takes arguments name (a String) and strict (a Boolean) and returns either a normal completion containing unused or a throw completion.

これは、Environment Record内に、新しいが未初期化のimmutable bindingを作成します。nameはbound nameのテキストです。stricttrueなら、それが初期化された後に設定しようとする試みは、そのbindingを参照する操作のstrict mode設定にかかわらず、常に例外をthrowします。
これは次の型に具体定義を持ちます:
InitializeBinding ( name, value )

The abstract method InitializeBinding takes arguments name (a String) and value (an ECMAScript language value) and returns either a normal completion containing unused or a throw completion.

これは、Environment Record内の既存だが未初期化のbindingの値を設定します。nameはbound nameのテキストです。valueはそのbindingの値です。
これは次の型に具体定義を持ちます:
SetMutableBinding ( name, value, strict )

The abstract method SetMutableBinding takes arguments name (a String), value (an ECMAScript language value), and strict (a Boolean) and returns either a normal completion containing unused or a throw completion.

これは、Environment Record内の既存のmutable bindingの値を設定します。nameはbound nameのテキストです。valueはそのbindingの値です。stricttrueで、そのbindingを設定できない場合、これはTypeError例外をthrowします。
これは次の型に具体定義を持ちます:
GetBindingValue ( name, strict )

The abstract method GetBindingValue takes arguments name (a String) and strict (a Boolean) and returns either a normal completion containing an ECMAScript language value or a throw completion.

これは、Environment Recordから既存のbindingの値を返します。nameはbound nameのテキストです。strictは、strict mode codeに由来する参照、またはそれ以外でstrict mode reference semanticsを必要とする参照を識別するために使用されます。stricttrueでbindingが存在しない場合、これはReferenceError例外をthrowします。bindingが存在していても未初期化である場合、strictの値にかかわらずReferenceErrorがthrowされます。
これは次の型に具体定義を持ちます:
DeleteBinding ( name )

The abstract method DeleteBinding takes argument name (a String) and returns either a normal completion containing a Boolean or a throw completion.

これは、Environment Recordからbindingを削除します。nameはbound nameのテキストです。nameに対するbindingが存在する場合、これはbindingを削除してtrueを返します。bindingは存在するが削除できない場合、これはfalseを返します。bindingが存在しない場合、これはtrueを返します。
これは次の型に具体定義を持ちます:
HasThisBinding ( )

The abstract method HasThisBinding takes no arguments and returns a Boolean.

これは、Environment Recordthis bindingを確立するかどうかを決定します。確立する場合はtrueを返し、そうでない場合はfalseを返します。
これは次の型に具体定義を持ちます:
GetThisBinding ( )

The abstract method GetThisBinding takes no arguments and returns either a normal completion containing an ECMAScript language value or a throw completion.

これは、このEnvironment Recordthis bindingの値を返します。this bindingが初期化されていない場合、ReferenceErrorをthrowします。
これは次の型に具体定義を持ちます:
HasSuperBinding ( )

The abstract method HasSuperBinding takes no arguments and returns a Boolean.

これは、Environment Recordsuper method bindingを確立するかどうかを決定します。確立する場合はtrueを返し、そうでない場合はfalseを返します。trueを返す場合、そのEnvironment RecordFunction Environment Recordであることを含意しますが、その逆は成り立ちません。
これは次の型に具体定義を持ちます:
WithBaseObject ( )

The abstract method WithBaseObject takes no arguments and returns an Object or undefined.

このEnvironment Recordwith statementに関連付けられている場合、これはwith objectを返します。そうでない場合、undefinedを返します。
これは次の型に具体定義を持ちます:

9.1.1.1 Declarative Environment Records

Declarative Environment Recordは、variable、constant、let、class、module、import、および/またはfunction declarationsを含むECMAScriptプログラムscopeに関連付けられます。Declarative Environment Recordは、そのscope内に含まれるdeclarationsによって定義される識別子集合をbindします。

すべての Declarative Environment Record はまた [[DisposableResourceStack]] フィールドを持ち、これは DisposableResource RecordsList を含む。このリストの要素は、Environment Record を構築した Evaluation ステップが完了したときに破棄されなければならない using 宣言および await using 宣言によって追跡される。

9.1.1.1.1 HasBinding ( name )

The HasBinding concrete method of an Declarative Environment Record envRecord takes argument name (a String) and returns a normal completion containing a Boolean. これは、argument identifierがそのrecordによってbindされるidentifiersの1つであるかどうかを決定します。 It performs the following steps when called:

  1. envRecordnameに対するbindingを持つなら、trueを返す。
  2. falseを返す。

9.1.1.1.2 CreateMutableBinding ( name, deletable )

The CreateMutableBinding concrete method of an Declarative Environment Record envRecord takes arguments name (a String) and deletable (a Boolean) and returns a normal completion containing unused. これは、未初期化である名前nameに対する新しいmutable bindingを作成します。このEnvironment Record内にnameに対するbindingが既に存在してはなりません。deletabletrueなら、新しいbindingは削除対象であるとして印付けられます。 It performs the following steps when called:

  1. Assert: envRecordnameに対するbindingを既に持っていない。
  2. envRecord内にnameに対するmutable bindingを作成し、それが未初期化であることを記録する。deletabletrueなら、新しく作成されたbindingが後続のDeleteBinding呼び出しによって削除され得ることを記録する。
  3. unusedを返す。

9.1.1.1.3 CreateImmutableBinding ( name, strict )

The CreateImmutableBinding concrete method of an Declarative Environment Record envRecord takes arguments name (a String) and strict (a Boolean) and returns a normal completion containing unused. これは、未初期化である名前nameに対する新しいimmutable bindingを作成します。このEnvironment Record内にnameに対するbindingが既に存在してはなりません。stricttrueなら、新しいbindingはstrict bindingとして印付けられます。 It performs the following steps when called:

  1. Assert: envRecordnameに対するbindingを既に持っていない。
  2. envRecord内にnameに対するimmutable bindingを作成し、それが未初期化であることを記録する。stricttrueなら、新しく作成されたbindingがstrict bindingであることを記録する。
  3. unusedを返す。

9.1.1.1.4 InitializeBinding ( name, value )

The InitializeBinding concrete method of an Declarative Environment Record envRecord takes arguments name (a String) and value (an ECMAScript language value) and returns a normal completion containing unused. これは、名前がnameであるidentifierの現在のbindingのbound valueを、値valueに設定するために使用されます。nameに対する未初期化のbindingが既に存在していなければなりません。 It performs the following steps when called:

  1. Assert: envRecordnameに対する未初期化のbindingを持っていなければならない。
  2. envRecord内のnameに対するbound valueをvalueに設定する。
  3. envRecord内のnameに対するbindingが初期化済みであることをRecordする。
  4. unusedを返す。

9.1.1.1.5 SetMutableBinding ( name, value, strict )

The SetMutableBinding concrete method of an Declarative Environment Record envRecord takes arguments name (a String), value (an ECMAScript language value), and strict (a Boolean) and returns either a normal completion containing unused or a throw completion. これは、名前がnameであるidentifierの現在のbindingのbound valueを、値valueに変更しようとします。nameに対するbindingは通常既に存在しますが、まれに存在しない場合があります。bindingがimmutable bindingである場合、stricttrueならTypeErrorがthrowされます。 It performs the following steps when called:

  1. envRecordnameに対するbindingを持たないなら、
    1. stricttrueなら、ReferenceError例外をthrowする。
    2. envRecord.CreateMutableBinding(name, true)を実行する。
    3. envRecord.InitializeBinding(name, value)を実行する。
    4. unusedを返す。
  2. envRecord内のnameに対するbindingがstrict bindingなら、stricttrueに設定する。
  3. envRecord内のnameに対するbindingがまだ初期化されていないなら、
    1. ReferenceError例外をthrowする。
  4. そうでなく、envRecord内のnameに対するbindingがmutable bindingなら、
    1. そのbound valueをvalueへ変更する。
  5. そうでなければ、
    1. Assert: これはimmutable bindingの値を変更しようとする試みである。
    2. stricttrueなら、TypeError例外をthrowする。
  6. unusedを返す。
Note

ステップ1でmissing bindingになるECMAScriptコードの例は次のとおりです:

function f() { eval("var x; x = (delete x, 0);"); }

9.1.1.1.6 GetBindingValue ( name, strict )

The GetBindingValue concrete method of an Declarative Environment Record envRecord takes arguments name (a String) and strict (a Boolean) and returns either a normal completion containing an ECMAScript language value or a throw completion. これは、名前がnameである自身のbound identifierの値を返します。bindingが存在するが未初期化である場合、strictの値にかかわらずReferenceErrorがthrowされます。 It performs the following steps when called:

  1. Assert: envRecordnameに対するbindingを持つ。
  2. envRecord内のnameに対するbindingが未初期化のbindingなら、ReferenceError例外をthrowする。
  3. envRecord内でnameに現在bindされている値を返す。

9.1.1.1.7 DeleteBinding ( name )

The DeleteBinding concrete method of an Declarative Environment Record envRecord takes argument name (a String) and returns a normal completion containing a Boolean. これは、明示的に削除対象として指定されたbindingsのみを削除できます。 It performs the following steps when called:

  1. Assert: envRecordnameに対するbindingを持つ。
  2. envRecord内のnameに対するbindingを削除できないなら、falseを返す。
  3. envRecordからnameに対するbindingを削除する。
  4. trueを返す。

9.1.1.1.8 HasThisBinding ( )

The HasThisBinding concrete method of an Declarative Environment Record envRecord takes no arguments and returns false. It performs the following steps when called:

  1. falseを返す。
Note

通常のDeclarative Environment Record(すなわち、Function Environment RecordでもModule Environment Recordでもないもの)は、this bindingを提供しません。

9.1.1.1.9 GetThisBinding ( )

Declarative Environment RecordGetThisBinding concrete methodは、この仕様内では決して使用されません。

9.1.1.1.10 HasSuperBinding ( )

The HasSuperBinding concrete method of an Declarative Environment Record envRecord takes no arguments and returns false. It performs the following steps when called:

  1. falseを返す。
Note

通常のDeclarative Environment Record(すなわち、Function Environment RecordでもModule Environment Recordでもないもの)は、super bindingを提供しません。

9.1.1.1.11 WithBaseObject ( )

The WithBaseObject concrete method of an Declarative Environment Record envRecord takes no arguments and returns undefined. It performs the following steps when called:

  1. undefinedを返す。

9.1.1.2 Object Environment Records

Object Environment Recordは、自身のbinding objectと呼ばれるオブジェクトに関連付けられます。Object Environment Recordは、そのbinding objectのプロパティ名に直接対応するstring identifier namesの集合をbindします。IdentifierName形式のstringsでないproperty keysは、bound identifiersの集合に含まれません。own propertiesとinherited propertiesの両方が、その[[Enumerable]]属性の設定にかかわらず集合に含まれます。プロパティはオブジェクトに動的に追加および削除できるため、Object Environment Recordによってbindされるidentifiersの集合は、プロパティを追加または削除する任意の操作のside-effectとして変化する可能性があります。そのようなside-effectの結果として作成されるbindingsは、対応するプロパティのWritable属性がfalseであってもmutable bindingとみなされます。Object Environment Recordsにはimmutable bindingsは存在しません。

with statements(14.11)のために作成されるObject Environment Recordsは、function callsで使用するための暗黙のthis値として、そのbinding objectを提供できます。この能力はBoolean [[IsWithEnvironment]]フィールドによって制御されます。

Object Environment Recordsは、Table 16に列挙される追加の状態フィールドを持ちます。

Table 16: Additional Fields of Object Environment Records
フィールド名 意味
[[BindingObject]] Object このEnvironment Recordのbinding object。
[[IsWithEnvironment]] Boolean このEnvironment Recordwith statementのために作成されたかどうかを示します。

9.1.1.2.1 HasBinding ( name )

The HasBinding concrete method of an Object Environment Record envRecord takes argument name (a String) and returns either a normal completion containing a Boolean or a throw completion. これは、自身に関連付けられたbinding objectが、名前がnameであるプロパティを持つかどうかを決定します。 It performs the following steps when called:

  1. bindingObjenvRecord.[[BindingObject]]とする。
  2. foundBindingを ? HasProperty(bindingObj, name) とする。
  3. foundBindingfalseなら、falseを返す。
  4. envRecord.[[IsWithEnvironment]]falseなら、trueを返す。
  5. unscopablesを ? Get(bindingObj, %Symbol.unscopables%) とする。
  6. unscopablesがObjectなら、
    1. blockedToBoolean(? Get(unscopables, name))とする。
    2. blockedtrueなら、falseを返す。
  7. trueを返す。

9.1.1.2.2 CreateMutableBinding ( name, deletable )

The CreateMutableBinding concrete method of an Object Environment Record envRecord takes arguments name (a String) and deletable (a Boolean) and returns either a normal completion containing unused or a throw completion. これは、Environment Recordに関連付けられたbinding object内に、名前がnameであるプロパティを作成し、それを値undefinedで初期化します。deletabletrueなら、新しいプロパティの[[Configurable]]属性はtrueに設定されます。そうでなければfalseに設定されます。 It performs the following steps when called:

  1. bindingObjenvRecord.[[BindingObject]]とする。
  2. DefinePropertyOrThrow(bindingObj, name, PropertyDescriptor { [[Value]]: undefined, [[Writable]]: true, [[Enumerable]]: true, [[Configurable]]: deletable })を実行する。
  3. unusedを返す。
Note

通常、envRecordnameに対するbindingを持ちませんが、持つ場合、DefinePropertyOrThrowの意味論は、既存のbindingが置換またはshadowされる結果になるか、abrupt completionが返される原因となる場合があります。

9.1.1.2.3 CreateImmutableBinding ( name, strict )

Object Environment RecordCreateImmutableBinding concrete methodは、この仕様内では決して使用されません。

9.1.1.2.4 InitializeBinding ( name, value )

The InitializeBinding concrete method of an Object Environment Record envRecord takes arguments name (a String) and value (an ECMAScript language value) and returns either a normal completion containing unused or a throw completion. これは、名前がnameであるidentifierの現在のbindingのbound valueを、値valueに設定するために使用されます。 It performs the following steps when called:

  1. envRecord.SetMutableBinding(name, value, false)を実行する。
  2. unusedを返す。
Note

この仕様では、Object Environment Recordsに対するCreateMutableBindingのすべての使用は、直後に同じ名前に対するInitializeBindingの呼び出しが続きます。したがって、この仕様はObject Environment Records内のbindingsの初期化状態を明示的に追跡しません。

9.1.1.2.5 SetMutableBinding ( name, value, strict )

The SetMutableBinding concrete method of an Object Environment Record envRecord takes arguments name (a String), value (an ECMAScript language value), and strict (a Boolean) and returns either a normal completion containing unused or a throw completion. これは、Environment Recordに関連付けられたbinding objectの、名前がnameであるプロパティの値を、値valueに設定しようとします。nameという名前のプロパティは通常既に存在しますが、存在しない場合や現在writableでない場合、error handlingはstrictによって決定されます。 It performs the following steps when called:

  1. bindingObjenvRecord.[[BindingObject]]とする。
  2. stillExistsを ? HasProperty(bindingObj, name) とする。
  3. stillExistsfalseかつstricttrueなら、ReferenceError例外をthrowする。
  4. Set(bindingObj, name, value, strict)を実行する。
  5. unusedを返す。

9.1.1.2.6 GetBindingValue ( name, strict )

The GetBindingValue concrete method of an Object Environment Record envRecord takes arguments name (a String) and strict (a Boolean) and returns either a normal completion containing an ECMAScript language value or a throw completion. これは、自身に関連付けられたbinding objectの、名前がnameであるプロパティの値を返します。そのプロパティは既に存在するべきですが、存在しない場合、結果はstrictに依存します。 It performs the following steps when called:

  1. bindingObjenvRecord.[[BindingObject]]とする。
  2. valueを ? HasProperty(bindingObj, name) とする。
  3. valuefalseなら、
    1. strictfalseなら、undefinedを返す。
    2. ReferenceError例外をthrowする。
  4. Get(bindingObj, name)を返す。

9.1.1.2.7 DeleteBinding ( name )

The DeleteBinding concrete method of an Object Environment Record envRecord takes argument name (a String) and returns either a normal completion containing a Boolean or a throw completion. これは、environment objectのプロパティに対応するbindingsのうち、その[[Configurable]]属性の値がtrueであるもののみを削除できます。 It performs the following steps when called:

  1. bindingObjenvRecord.[[BindingObject]]とする。
  2. bindingObj.[[Delete]](name)を返す。

9.1.1.2.8 HasThisBinding ( )

The HasThisBinding concrete method of an Object Environment Record envRecord takes no arguments and returns false. It performs the following steps when called:

  1. falseを返す。
Note

Object Environment Recordsthis bindingを提供しません。

9.1.1.2.9 GetThisBinding ( )

Object Environment RecordGetThisBinding concrete methodは、この仕様内では決して使用されません。

9.1.1.2.10 HasSuperBinding ( )

The HasSuperBinding concrete method of an Object Environment Record envRecord takes no arguments and returns false. It performs the following steps when called:

  1. falseを返す。
Note

Object Environment Recordssuper bindingを提供しません。

9.1.1.2.11 WithBaseObject ( )

The WithBaseObject concrete method of an Object Environment Record envRecord takes no arguments and returns an Object or undefined. It performs the following steps when called:

  1. envRecord.[[IsWithEnvironment]]trueなら、envRecord.[[BindingObject]]を返す。
  2. undefinedを返す。

9.1.1.3 Function Environment Records

Function Environment Recordは、functionのtop-level scopeを表すために使用されるDeclarative Environment Recordであり、そのfunctionがArrowFunction functionまたはAsyncArrowFunction functionでない場合、this bindingを提供します。functionがArrowFunction functionまたはAsyncArrowFunction functionでなく、かつsuperを参照する場合、そのFunction Environment Recordは、function内からsuper method呼び出しを実行するために使用される状態も含みます。

Function Environment Recordsは、Table 17に列挙される追加の状態フィールドを持ちます。

Table 17: Additional Fields of Function Environment Records
フィールド名 意味
[[ThisValue]] ECMAScript言語値 これは、このfunctionのこの呼び出しに使用されるthis値です。
[[ThisBindingStatus]] lexical, initialized, or uninitialized 値がlexicalである場合、これはArrowFunctionまたはAsyncArrowFunctionであり、localなthis値を持ちません。
[[FunctionObject]] ECMAScript function object このEnvironment Recordが作成される原因となった呼び出しのfunction object
[[NewTarget]] constructorまたはundefined このEnvironment Record[[Construct]] internal methodによって作成された場合、[[NewTarget]][[Construct]] newTarget parameterの値です。そうでない場合、その値はundefinedです。

Function Environment Recordsは、Table 15に列挙されるすべてのDeclarative Environment Record methodsをサポートし、HasThisBindingGetThisBinding、およびHasSuperBindingを除くそれらすべてのメソッドについて同じ仕様を共有します。

9.1.1.3.1 BindThisValue ( envRecord, value )

The abstract operation BindThisValue takes arguments envRecord (a Function Environment Record) and value (an ECMAScript language value) and returns either a normal completion containing unused or a throw completion. これはenvRecord.[[ThisValue]]を設定し、それが初期化済みであることを記録します。 It performs the following steps when called:

  1. Assert: envRecord.[[ThisBindingStatus]]lexicalでない。
  2. envRecord.[[ThisBindingStatus]]initializedなら、ReferenceError例外をthrowする。
  3. envRecord.[[ThisValue]]valueに設定する。
  4. envRecord.[[ThisBindingStatus]]initializedに設定する。
  5. unusedを返す。

9.1.1.3.2 HasThisBinding ( )

The HasThisBinding concrete method of a Function Environment Record envRecord takes no arguments and returns a Boolean. It performs the following steps when called:

  1. envRecord.[[ThisBindingStatus]]lexicalなら、falseを返す。
  2. trueを返す。

9.1.1.3.3 GetThisBinding ( )

The GetThisBinding concrete method of a Function Environment Record envRecord takes no arguments and returns either a normal completion containing an ECMAScript language value or a throw completion. It performs the following steps when called:

  1. Assert: envRecord.[[ThisBindingStatus]]lexicalでない。
  2. envRecord.[[ThisBindingStatus]]uninitializedなら、ReferenceError例外をthrowする。
  3. envRecord.[[ThisValue]]を返す。

9.1.1.3.4 HasSuperBinding ( )

The HasSuperBinding concrete method of a Function Environment Record envRecord takes no arguments and returns a Boolean. It performs the following steps when called:

  1. envRecord.[[ThisBindingStatus]]lexicalなら、falseを返す。
  2. envRecord.[[FunctionObject]].[[HomeObject]]undefinedなら、falseを返す。
  3. trueを返す。

9.1.1.3.5 GetSuperBase ( envRecord )

The abstract operation GetSuperBase takes argument envRecord (a Function Environment Record) and returns an Object, null, or undefined. これは、envRecord内でbindされたsuper property accessesのbaseであるオブジェクトを返します。値undefinedは、そのようなアクセスがruntime errorsを生成することを示します。 It performs the following steps when called:

  1. homeenvRecord.[[FunctionObject]].[[HomeObject]]とする。
  2. homeundefinedなら、undefinedを返す。
  3. Assert: homeordinary objectである。
  4. home.[[GetPrototypeOf]]()を返す。

9.1.1.4 Global Environment Records

Global Environment Recordは、共通のrealmで処理されるすべてのECMAScript Script要素によって共有される最も外側のscopeを表すために使用されます。Global Environment Recordは、built-in globals(19節)、global objectのプロパティ、およびScript内で出現するすべてのtop-level declarations(8.2.118.2.13)に対するbindingsを提供します。

Global Environment Recordは論理的には単一のrecordですが、Object Environment RecordDeclarative Environment Recordをカプセル化する合成物として指定されます。Object Environment Recordは、関連付けられたRealm Recordglobal objectをbase objectとして持ちます。このglobal objectは、Global Environment RecordのGetThisBinding concrete methodによって返される値です。Global Environment RecordのObject Environment Record componentは、すべてのbuilt-in globals(19節)に対するbindings、およびglobal codeに含まれるFunctionDeclarationGeneratorDeclarationAsyncFunctionDeclarationAsyncGeneratorDeclaration、またはVariableStatementによって導入されるすべてのbindingsを含みます。global code内の他のすべてのECMAScript declarationsに対するbindingsは、Global Environment RecordのDeclarative Environment Record componentに含まれます。

プロパティはglobal object上に直接作成される場合があります。したがって、Global Environment RecordのObject Environment Record componentは、FunctionDeclarationGeneratorDeclarationAsyncFunctionDeclarationAsyncGeneratorDeclaration、またはVariableDeclaration declarationsによって明示的に作成されるbindingsと、global objectのプロパティとして暗黙的に作成されるbindingsの両方を含む場合があります。

Global Environment Recordsは、Table 18に列挙される追加フィールドを持ちます。

Table 18: Additional Fields of Global Environment Records
フィールド名 意味
[[ObjectRecord]] Object Environment Record Binding objectはglobal objectです。これは、global built-in bindingsに加えて、関連realmのglobal code内のFunctionDeclarationGeneratorDeclarationAsyncFunctionDeclarationAsyncGeneratorDeclaration、およびVariableDeclaration bindingsを含みます。
[[GlobalThisValue]] Object global scope内のthisによって返される値です。hostsは任意のECMAScript Object値を提供できます。
[[DeclarativeRecord]] Declarative Environment Record 関連realm codeのglobal code内のすべてのdeclarationsに対するbindingsをContainsします。ただし、FunctionDeclarationGeneratorDeclarationAsyncFunctionDeclarationAsyncGeneratorDeclaration、およびVariableDeclaration bindingsは除きます。

9.1.1.4.1 HasBinding ( name )

The HasBinding concrete method of a Global Environment Record envRecord takes argument name (a String) and returns either a normal completion containing a Boolean or a throw completion. これは、argument identifierがそのrecordによってbindされるidentifiersの1つであるかどうかを決定します。 It performs the following steps when called:

  1. declRecordenvRecord.[[DeclarativeRecord]]とする。
  2. declRecord.HasBinding(name)がtrueなら、trueを返す。
  3. objRecordenvRecord.[[ObjectRecord]]とする。
  4. objRecord.HasBinding(name)を返す。

9.1.1.4.2 CreateMutableBinding ( name, deletable )

The CreateMutableBinding concrete method of a Global Environment Record envRecord takes arguments name (a String) and deletable (a Boolean) and returns either a normal completion containing unused or a throw completion. これは、未初期化である名前nameに対する新しいmutable bindingを作成します。bindingは関連付けられたDeclarativeRecord内に作成されます。nameに対するbindingは、DeclarativeRecord内に既に存在してはなりません。deletabletrueなら、新しいbindingは削除対象であるとして印付けられます。 It performs the following steps when called:

  1. declRecordenvRecord.[[DeclarativeRecord]]とする。
  2. declRecord.HasBinding(name)がtrueなら、TypeError例外をthrowする。
  3. declRecord.CreateMutableBinding(name, deletable)を返す。

9.1.1.4.3 CreateImmutableBinding ( name, strict )

The CreateImmutableBinding concrete method of a Global Environment Record envRecord takes arguments name (a String) and strict (a Boolean) and returns either a normal completion containing unused or a throw completion. これは、未初期化である名前nameに対する新しいimmutable bindingを作成します。このEnvironment Record内にnameに対するbindingが既に存在してはなりません。stricttrueなら、新しいbindingはstrict bindingとして印付けられます。 It performs the following steps when called:

  1. declRecordenvRecord.[[DeclarativeRecord]]とする。
  2. declRecord.HasBinding(name)がtrueなら、TypeError例外をthrowする。
  3. declRecord.CreateImmutableBinding(name, strict)を返す。

9.1.1.4.4 InitializeBinding ( name, value )

The InitializeBinding concrete method of a Global Environment Record envRecord takes arguments name (a String) and value (an ECMAScript language value) and returns either a normal completion containing unused or a throw completion. これは、名前がnameであるidentifierの現在のbindingのbound valueを、値valueに設定するために使用されます。nameに対する未初期化のbindingが既に存在していなければなりません。 It performs the following steps when called:

  1. declRecordenvRecord.[[DeclarativeRecord]]とする。
  2. declRecord.HasBinding(name)がtrueなら、
    1. declRecord.InitializeBinding(name, value)を返す。
  3. Assert: bindingが存在するなら、それはObject Environment Record内になければならない。
  4. objRecordenvRecord.[[ObjectRecord]]とする。
  5. objRecord.InitializeBinding(name, value)を返す。

9.1.1.4.5 SetMutableBinding ( name, value, strict )

The SetMutableBinding concrete method of a Global Environment Record envRecord takes arguments name (a String), value (an ECMAScript language value), and strict (a Boolean) and returns either a normal completion containing unused or a throw completion. これは、名前がnameであるidentifierの現在のbindingのbound valueを、値valueに変更しようとします。bindingがimmutable bindingであり、stricttrueの場合、TypeErrorがthrowされます。nameという名前のbindingは通常既に存在しますが、存在しない場合や現在writableでない場合、error handlingはstrictによって決定されます。 It performs the following steps when called:

  1. declRecordenvRecord.[[DeclarativeRecord]]とする。
  2. declRecord.HasBinding(name)がtrueなら、
    1. declRecord.SetMutableBinding(name, value, strict)を返す。
  3. objRecordenvRecord.[[ObjectRecord]]とする。
  4. objRecord.SetMutableBinding(name, value, strict)を返す。

9.1.1.4.6 GetBindingValue ( name, strict )

The GetBindingValue concrete method of a Global Environment Record envRecord takes arguments name (a String) and strict (a Boolean) and returns either a normal completion containing an ECMAScript language value or a throw completion. これは、名前がnameである自身のbound identifierの値を返します。bindingが未初期化のbindingである場合、ReferenceError例外をthrowします。nameという名前のbindingは通常既に存在しますが、存在しない場合や現在writableでない場合、error handlingはstrictによって決定されます。 It performs the following steps when called:

  1. declRecordenvRecord.[[DeclarativeRecord]]とする。
  2. declRecord.HasBinding(name)がtrueなら、
    1. declRecord.GetBindingValue(name, strict)を返す。
  3. objRecordenvRecord.[[ObjectRecord]]とする。
  4. objRecord.GetBindingValue(name, strict)を返す。

9.1.1.4.7 DeleteBinding ( name )

The DeleteBinding concrete method of a Global Environment Record envRecord takes argument name (a String) and returns either a normal completion containing a Boolean or a throw completion. これは、明示的に削除対象として指定されたbindingsのみを削除できます。 It performs the following steps when called:

  1. declRecordenvRecord.[[DeclarativeRecord]]とする。
  2. declRecord.HasBinding(name)がtrueなら、
    1. declRecord.DeleteBinding(name)を返す。
  3. objRecordenvRecord.[[ObjectRecord]]とする。
  4. globalObjobjRecord.[[BindingObject]]とする。
  5. existingPropertyを ? HasOwnProperty(globalObj, name) とする。
  6. existingPropertytrueなら、
    1. objRecord.DeleteBinding(name)を返す。
  7. trueを返す。

9.1.1.4.8 HasThisBinding ( )

The HasThisBinding concrete method of a Global Environment Record envRecord takes no arguments and returns true. It performs the following steps when called:

  1. trueを返す。
Note

Global Environment Recordsは常にthis bindingを提供します。

9.1.1.4.9 GetThisBinding ( )

The GetThisBinding concrete method of a Global Environment Record envRecord takes no arguments and returns a normal completion containing an Object. It performs the following steps when called:

  1. envRecord.[[GlobalThisValue]]を返す。

9.1.1.4.10 HasSuperBinding ( )

The HasSuperBinding concrete method of a Global Environment Record envRecord takes no arguments and returns false. It performs the following steps when called:

  1. falseを返す。
Note

Global Environment Recordssuper bindingを提供しません。

9.1.1.4.11 WithBaseObject ( )

The WithBaseObject concrete method of a Global Environment Record envRecord takes no arguments and returns undefined. It performs the following steps when called:

  1. undefinedを返す。

9.1.1.4.12 HasLexicalDeclaration ( envRecord, name )

The abstract operation HasLexicalDeclaration takes arguments envRecord (a Global Environment Record) and name (a String) and returns a Boolean. これは、argument identifierが、LexicalDeclarationClassDeclarationなどのlexical declarationを使用して作成されたbindingをenvRecord内に持つかどうかを決定します。 It performs the following steps when called:

  1. declRecordenvRecord.[[DeclarativeRecord]]とする。
  2. declRecord.HasBinding(name)を返す。

9.1.1.4.13 HasRestrictedGlobalProperty ( envRecord, name )

The abstract operation HasRestrictedGlobalProperty takes arguments envRecord (a Global Environment Record) and name (a String) and returns either a normal completion containing a Boolean or a throw completion. これは、argument identifierが、global lexical bindingによってshadowされてはならないglobal objectのプロパティの名前であるかどうかを決定します。 It performs the following steps when called:

  1. objRecordenvRecord.[[ObjectRecord]]とする。
  2. globalObjobjRecord.[[BindingObject]]とする。
  3. existingPropertyを ? globalObj.[[GetOwnProperty]](name) とする。
  4. existingPropertyundefinedなら、falseを返す。
  5. existingProperty.[[Configurable]]trueなら、falseを返す。
  6. trueを返す。
Note

varまたはfunction declarationを使用して宣言されたのではなく、直接作成されたプロパティがglobal object上に存在する場合があります。global objectのnon-configurable propertyと同じ名前を持つglobal lexical bindingは作成できません。global property "undefined"は、そのようなプロパティの例です。

9.1.1.4.14 CanDeclareGlobalVar ( envRecord, name )

The abstract operation CanDeclareGlobalVar takes arguments envRecord (a Global Environment Record) and name (a String) and returns either a normal completion containing a Boolean or a throw completion. これは、同じargument nameで呼び出された場合に、対応するCreateGlobalVarBinding呼び出しが成功するかどうかを決定します。冗長なvar declarationsおよび既存のglobal object propertiesに対するvar declarationsは許可されます。 It performs the following steps when called:

  1. objRecordenvRecord.[[ObjectRecord]]とする。
  2. globalObjobjRecord.[[BindingObject]]とする。
  3. hasPropertyを ? HasOwnProperty(globalObj, name) とする。
  4. hasPropertytrueなら、trueを返す。
  5. IsExtensible(globalObj)を返す。

9.1.1.4.15 CanDeclareGlobalFunction ( envRecord, name )

The abstract operation CanDeclareGlobalFunction takes arguments envRecord (a Global Environment Record) and name (a String) and returns either a normal completion containing a Boolean or a throw completion. これは、同じargument nameで呼び出された場合に、対応するCreateGlobalFunctionBinding呼び出しが成功するかどうかを決定します。 It performs the following steps when called:

  1. objRecordenvRecord.[[ObjectRecord]]とする。
  2. globalObjobjRecord.[[BindingObject]]とする。
  3. existingPropertyを ? globalObj.[[GetOwnProperty]](name) とする。
  4. existingPropertyundefinedなら、? IsExtensible(globalObj)を返す。
  5. existingProperty.[[Configurable]]trueなら、trueを返す。
  6. IsDataDescriptor(existingProperty)がtrueであり、かつexistingPropertyがattribute values { [[Writable]]: true, [[Enumerable]]: true }を持つなら、trueを返す。
  7. falseを返す。

9.1.1.4.16 CreateGlobalVarBinding ( envRecord, name, deletable )

The abstract operation CreateGlobalVarBinding takes arguments envRecord (a Global Environment Record), name (a String), and deletable (a Boolean) and returns either a normal completion containing unused or a throw completion. これは、関連付けられたObject Environment Record内にmutable bindingを作成し、初期化します。bindingが既に存在する場合、それは再利用され、初期化済みであると仮定されます。 It performs the following steps when called:

  1. objRecordenvRecord.[[ObjectRecord]]とする。
  2. globalObjobjRecord.[[BindingObject]]とする。
  3. hasPropertyを ? HasOwnProperty(globalObj, name) とする。
  4. extensibleを ? IsExtensible(globalObj) とする。
  5. hasPropertyfalseかつextensibletrueなら、
    1. objRecord.CreateMutableBinding(name, deletable)を実行する。
    2. objRecord.InitializeBinding(name, undefined)を実行する。
  6. unusedを返す。

9.1.1.4.17 CreateGlobalFunctionBinding ( envRecord, name, value, deletable )

The abstract operation CreateGlobalFunctionBinding takes arguments envRecord (a Global Environment Record), name (a String), value (an ECMAScript function object), and deletable (a Boolean) and returns either a normal completion containing unused or a throw completion. これは、関連付けられたObject Environment Record内にmutable bindingを作成し、初期化します。bindingが既に存在する場合、それは置き換えられます。 It performs the following steps when called:

  1. objRecordenvRecord.[[ObjectRecord]]とする。
  2. globalObjobjRecord.[[BindingObject]]とする。
  3. existingPropertyを ? globalObj.[[GetOwnProperty]](name) とする。
  4. existingPropertyundefinedまたはexistingProperty.[[Configurable]]trueなら、
    1. propertyDescをPropertyDescriptor { [[Value]]: value, [[Writable]]: true, [[Enumerable]]: true, [[Configurable]]: deletable }とする。
  5. そうでなければ、
    1. propertyDescをPropertyDescriptor { [[Value]]: value }とする。
  6. DefinePropertyOrThrow(globalObj, name, propertyDesc)を実行する。
  7. Set(globalObj, name, value, false)を実行する。
  8. unusedを返す。
Note

Global function declarationsは常にglobal objectのown propertiesとして表現されます。可能であれば、既存のown propertyは標準的なattribute valuesの集合を持つように再構成されます。ステップ7は、InitializeBinding concrete methodを呼び出すことが行うことと等価であり、globalObjがProxyである場合、同じ一連のProxy trap呼び出しを生成します。

9.1.1.5 Module Environment Records

Module Environment Recordは、ECMAScript Moduleの外側scopeを表すために使用されるDeclarative Environment Recordです。通常のmutable bindingsおよびimmutable bindingsに加えて、Module Environment Recordsはimmutable import bindingsも提供します。これは、別のEnvironment Record内に存在するtarget bindingへの間接アクセスを提供するbindingsです。

Module Environment Recordsは、Table 15に列挙されるすべてのDeclarative Environment Record methodsをサポートし、GetBindingValueDeleteBindingHasThisBinding、およびGetThisBindingを除くそれらすべてのメソッドについて同じ仕様を共有します。

9.1.1.5.1 GetBindingValue ( name, strict )

The GetBindingValue concrete method of a Module Environment Record envRecord takes arguments name (a String) and strict (a Boolean) and returns either a normal completion containing an ECMAScript language value or a throw completion. これは、名前がnameである自身のbound identifierの値を返します。ただし、bindingがindirect bindingである場合、target bindingの値が返されます。bindingが存在するが未初期化である場合、ReferenceErrorがthrowされます。 It performs the following steps when called:

  1. Assert: stricttrueである。
  2. Assert: envRecordnameに対するbindingを持つ。
  3. nameに対するbindingがindirect bindingであるなら、
    1. moduleおよびtargetNameを、このnameに対するbindingが作成されたときに提供されたindirection valuesとする。
    2. targetEnvmodule.[[Environment]]とする。
    3. targetEnvemptyなら、ReferenceError例外をthrowする。
    4. targetEnv.GetBindingValue(targetName, true)を返す。
  4. envRecord内のnameに対するbindingが未初期化のbindingなら、ReferenceError例外をthrowする。
  5. envRecord内でnameに現在bindされている値を返す。
Note

Moduleは常にstrict mode codeであるため、strictは常にtrueになります。

9.1.1.5.2 DeleteBinding ( name )

Module Environment RecordDeleteBinding concrete methodは、この仕様内では決して使用されません。

Note

Module Environment Recordsはstrict code内でのみ使用され、early error ruleは、strict codeにおいて、Module Environment Record bindingへ解決されるReference Recordにdelete operatorが適用されることを防ぎます。13.5.1.1を参照してください。

9.1.1.5.3 HasThisBinding ( )

The HasThisBinding concrete method of a Module Environment Record envRecord takes no arguments and returns true. It performs the following steps when called:

  1. trueを返す。
Note

Module Environment Recordsは常にthis bindingを提供します。

9.1.1.5.4 GetThisBinding ( )

The GetThisBinding concrete method of a Module Environment Record envRecord takes no arguments and returns a normal completion containing undefined. It performs the following steps when called:

  1. undefinedを返す。

9.1.1.5.5 CreateImportBinding ( envRecord, name, targetModule, targetName )

The abstract operation CreateImportBinding takes arguments envRecord (a Module Environment Record), name (a String), targetModule (a Module Record), and targetName (a String) and returns unused. これは、名前nameに対して、新しい初期化済みimmutable indirect bindingを作成します。envRecord内にnameに対するbindingが既に存在してはなりません。targetNameは、targetModuleModule Environment Record内に存在するbindingの名前です。新しいbindingの値へのアクセスは、target bindingのbound valueに間接的にアクセスします。 It performs the following steps when called:

  1. Assert: envRecordnameに対するbindingを既に持っていない。
  2. Assert: targetModule.[[Environment]]がinstantiatedされるとき、それはtargetNameに対するdirect bindingを持つ。
  3. envRecord内にnameに対するimmutable indirect bindingを作成し、それがtargetModuleおよびtargetNameをそのtarget bindingとして参照することを記録し、bindingが初期化済みであることを記録する。
  4. unusedを返す。

9.1.2 Environment Record操作

以下の抽象操作は、この仕様においてEnvironment Recordsに対して操作を行うために使用されます:

9.1.2.1 GetIdentifierReference ( envRecord, name, strict )

The abstract operation GetIdentifierReference takes arguments envRecord (an Environment Record or null), name (a String), and strict (a Boolean) and returns either a normal completion containing a Reference Record or a throw completion. It performs the following steps when called:

  1. envRecordnullなら、
    1. Reference Record { [[Base]]: unresolvable, [[ReferencedName]]: name, [[Strict]]: strict, [[ThisValue]]: empty }を返す。
  2. existsを ? envRecord.HasBinding(name) とする。
  3. existstrueなら、
    1. Reference Record { [[Base]]: envRecord, [[ReferencedName]]: name, [[Strict]]: strict, [[ThisValue]]: empty }を返す。
  4. outerenvRecord.[[OuterEnv]]とする。
  5. GetIdentifierReference(outer, name, strict)を返す。

9.1.2.2 NewDeclarativeEnvironment ( outerEnv )

The abstract operation NewDeclarativeEnvironment takes argument outerEnv (an Environment Record or null) and returns a Declarative Environment Record. It performs the following steps when called:

  1. envRecord を、束縛を含まない新しい Declarative Environment Record とする。
  2. envRecord.[[OuterEnv]]outerEnv に設定する。
  3. envRecord.[[DisposableResourceStack]] を新しい空の List に設定する。
  4. envRecord を返す。

9.1.2.3 NewObjectEnvironment ( obj, isWithEnv, outerEnv )

The abstract operation NewObjectEnvironment takes arguments obj (an Object), isWithEnv (a Boolean), and outerEnv (an Environment Record or null) and returns an Object Environment Record. It performs the following steps when called:

  1. envRecordを新しいObject Environment Recordとする。
  2. envRecord.[[BindingObject]]objに設定する。
  3. envRecord.[[IsWithEnvironment]]isWithEnvに設定する。
  4. envRecord.[[OuterEnv]]outerEnvに設定する。
  5. envRecordを返す。

9.1.2.4 NewFunctionEnvironment ( func, newTarget )

The abstract operation NewFunctionEnvironment takes arguments func (an ECMAScript function object) and newTarget (an Object or undefined) and returns a Function Environment Record. It performs the following steps when called:

  1. envRecord を、束縛を含まない新しい Function Environment Record とする。
  2. envRecord.[[FunctionObject]]func に設定する。
  3. func.[[ThisMode]]lexical である場合、envRecord.[[ThisBindingStatus]]lexical に設定する。
  4. Else, envRecord.[[ThisBindingStatus]]uninitialized に設定する。
  5. envRecord.[[NewTarget]]newTarget に設定する。
  6. envRecord.[[OuterEnv]]func.[[Environment]] に設定する。
  7. envRecord.[[DisposableResourceStack]] を新しい空の List に設定する。
  8. envRecord を返す。

9.1.2.5 NewGlobalEnvironment ( obj, thisValue )

The abstract operation NewGlobalEnvironment takes arguments obj (an Object) and thisValue (an Object) and returns a Global Environment Record. It performs the following steps when called:

  1. objRecordNewObjectEnvironment(obj, false, null)とする。
  2. declRecordNewDeclarativeEnvironment(null)とする。
  3. envRecordを新しいGlobal Environment Recordとする。
  4. envRecord.[[ObjectRecord]]objRecordに設定する。
  5. envRecord.[[GlobalThisValue]]thisValueに設定する。
  6. envRecord.[[DeclarativeRecord]]declRecordに設定する。
  7. envRecord.[[OuterEnv]]nullに設定する。
  8. envRecordを返す。

9.1.2.6 NewModuleEnvironment ( outerEnv )

The abstract operation NewModuleEnvironment takes argument outerEnv (a Global Environment Record) and returns a Module Environment Record. It performs the following steps when called:

  1. envRecord を、束縛を含まない新しい Module Environment Record とする。
  2. envRecord.[[OuterEnv]]outerEnv に設定する。
  3. envRecord.[[DisposableResourceStack]] を新しい空の List に設定する。
  4. envRecord を返す。

9.2 PrivateEnvironment Records

PrivateEnvironment Recordは、ECMAScriptコード内のClassDeclarationおよびClassExpressionの字句的な入れ子構造に基づいて、Private Namesを追跡するために使用される仕様上の仕組みです。これらはEnvironment Recordsに似ていますが、それとは異なります。各PrivateEnvironment Recordは、ClassDeclarationまたはClassExpressionに関連付けられます。そのようなclassが評価されるたびに、そのclassによって宣言されたPrivate Namesを記録するため、新しいPrivateEnvironment Recordが作成されます。

PrivateEnvironment Recordは、Table 19で定義されるフィールドを持ちます。

Table 19: PrivateEnvironment Record Fields
フィールド名 値の型 意味
[[OuterPrivateEnvironment]] PrivateEnvironment Recordまたはnull 最も近い包含classのPrivateEnvironment Record。このPrivateEnvironment Recordに関連付けられたclassが他のclassに含まれていない場合はnull
[[Names]] Private NamesList このclassによって宣言されたPrivate Names

9.2.1 PrivateEnvironment Record操作

以下の抽象操作は、この仕様においてPrivateEnvironment Recordsに対して操作を行うために使用されます:

9.2.1.1 NewPrivateEnvironment ( outerPrivateEnv )

The abstract operation NewPrivateEnvironment takes argument outerPrivateEnv (a PrivateEnvironment Record or null) and returns a PrivateEnvironment Record. It performs the following steps when called:

  1. namesを新しい空のListとする。
  2. PrivateEnvironment Record { [[OuterPrivateEnvironment]]: outerPrivateEnv, [[Names]]: names }を返す。

9.2.1.2 ResolvePrivateIdentifier ( privateEnv, identifier )

The abstract operation ResolvePrivateIdentifier takes arguments privateEnv (a PrivateEnvironment Record) and identifier (a String) and returns a Private Name. It performs the following steps when called:

  1. namesprivateEnv.[[Names]]とする。
  2. namesの各Private Name privateNameについて、以下を行う
    1. privateName.[[Description]]identifierなら、
      1. privateNameを返す。
  3. outerPrivateEnvprivateEnv.[[OuterPrivateEnvironment]]とする。
  4. Assert: outerPrivateEnvnullでない。
  5. ResolvePrivateIdentifier(outerPrivateEnv, identifier)を返す。

9.3 Realms

評価される前に、すべてのECMAScriptコードはrealmに関連付けられていなければなりません。概念的には、realmは、intrinsic objectsの集合、ECMAScript global environment、そのglobal environmentのscope内に読み込まれたすべてのECMAScriptコード、およびその他の関連状態とリソースから構成されます。

realmは、この仕様ではRealm Recordとして表され、Table 20で指定されるフィールドを持ちます:

Table 20: Realm Record Fields
フィールド名 意味
[[AgentSignifier]] agent signifier このrealmを所有するagent
[[Intrinsics]] フィールド名がintrinsic keysであり、その値がobjectsであるRecord このrealmに関連付けられたコードによって使用されるintrinsic values
[[GlobalObject]] Object このrealmglobal object
[[GlobalEnv]] Global Environment Record このrealmのglobal environment
[[TemplateMap]] フィールド[[Site]]TemplateLiteral Parse Node)および[[Array]](Array)を持つRecordsList

Template objectsは、そのRealm Record[[TemplateMap]]を使用して、realmごとに個別にcanonicalizeされます。各[[Site]]値はTemplateLiteralであるParse Nodeです。関連付けられた[[Array]]値は、tag functionに渡される対応するtemplate objectです。

Note 1
Parse Nodeが到達不能になると、対応する[[Array]]も到達不能になり、実装がそのpairを[[TemplateMap]] listから削除しても観測不能です。
[[LoadedModules]] LoadedModuleRequest RecordsList

このrealmによってimportされたspecifier stringsから、解決済みModule Recordへのmap。このlistは、ModuleRequestsEqual(r1, r2)がtrueであるような2つの異なるRecords r1およびr2を含みません。

Note 2
HostLoadImportedModule16.2.1.10 Note 1)で述べたように、Realm Records内の[[LoadedModules]]は、active scriptまたはmoduleが存在しないcontextでimport() expressionを実行する場合にのみ使用されます。
[[HostDefined]] anything(デフォルト値はundefined Realm Recordに追加情報を関連付ける必要があるhostsによる使用のために予約されたフィールド。

9.3.1 InitializeHostDefinedRealm ( )

The abstract operation InitializeHostDefinedRealm takes no arguments and returns either a normal completion containing unused or a throw completion. It performs the following steps when called:

  1. realmを新しいRealm Recordとする。
  2. CreateIntrinsics(realm)を実行する。
  3. realm.[[AgentSignifier]]AgentSignifier()に設定する。
  4. realm.[[TemplateMap]]を新しい空のListに設定する。
  5. newContextを新しいexecution contextとする。
  6. newContextのFunctionをnullに設定する。
  7. newContextRealmrealmに設定する。
  8. newContextのScriptOrModuleをnullに設定する。
  9. newContextexecution context stackへpushする;newContextは現在running execution contextである。
  10. hostが、realmglobal objectとして機能する特定のオブジェクトの使用を要求するなら、
    1. globalを、host-defined mannerで作成されたそのようなオブジェクトとする。
  11. そうでなければ、
    1. globalOrdinaryObjectCreate(realm.[[Intrinsics]].[[%Object.prototype%]])とする。
  12. hostが、realmのglobal scope内のthis bindingにglobal object以外のオブジェクトを返すことを要求するなら、
    1. thisValueを、host-defined mannerで作成されたそのようなオブジェクトとする。
  13. そうでなければ、
    1. thisValueglobalとする。
  14. realm.[[GlobalObject]]globalに設定する。
  15. realm.[[GlobalEnv]]NewGlobalEnvironment(global, thisValue)に設定する。
  16. SetDefaultGlobalBindings(realm)を実行する。
  17. host-defined global object propertiesをglobal上に作成する。
  18. unusedを返す。

9.3.2 CreateIntrinsics ( realmRecord )

The abstract operation CreateIntrinsics takes argument realmRecord (a Realm Record) and returns unused. It performs the following steps when called:

  1. realmRecord.[[Intrinsics]]を新しいRecordに設定する。
  2. realmRecord.[[Intrinsics]]のフィールドを、Table 6に列挙される値で設定する。フィールド名は、その表の“Intrinsic Name”列に列挙される名前です。各フィールドの値は、19節から28節までの各オブジェクトの仕様によって定義されるproperty valuesで完全かつ再帰的にpopulatedされた新しいobject valueです。すべてのobject property valuesは新しく作成されたobject valuesです。built-in function objectsであるすべての値は、CreateBuiltinFunction(steps, length, name, slots, realmRecord, proto, async)を実行することによって作成されます。ここで、stepsはこの仕様によって提供されるその関数の定義、nameはその関数の"name" propertyの初期値、lengthはその関数の"length" propertyの初期値、slotsはその関数の指定されたinternal slotsの名前のlist(もしあれば)、protoはその関数の[[Prototype]] internal slotの指定値、asyncはその関数が“async”として記述されている場合はtrue、そうでない場合はfalseです。intrinsicsおよびそれらのpropertiesの作成は、まだ作成されていないオブジェクトへの依存を避けるように順序付けられていなければなりません。
  3. AddRestrictedFunctionProperties(realmRecord.[[Intrinsics]].[[%Function.prototype%]], realmRecord)を実行する。
  4. unusedを返す。

9.3.3 SetDefaultGlobalBindings ( realmRecord )

The abstract operation SetDefaultGlobalBindings takes argument realmRecord (a Realm Record) and returns either a normal completion containing unused or a throw completion. It performs the following steps when called:

  1. globalrealmRecord.[[GlobalObject]]とする。
  2. 19節で指定されるGlobal Objectの各propertyについて、以下を行う
    1. nameproperty nameのString値とする。
    2. propertyDescを、そのpropertyの指定されたattributesを含む、そのpropertyの完全にpopulatedされたdata Property Descriptorとする。19.219.3、または19.4に列挙されるpropertiesについては、[[Value]]属性の値はrealmRecordからの対応するintrinsic objectです。
    3. DefinePropertyOrThrow(global, name, propertyDesc)を実行する。
  3. unusedを返す。

9.4 Execution Contexts

execution contextは、ECMAScript実装によるコードのruntime評価を追跡するために使用される仕様上の装置です。任意の時点で、実際にコードを実行しているexecution contextは、agentごとに最大1つです。これはそのagentrunning execution contextとして知られます。この仕様におけるrunning execution contextへのすべての参照は、周囲のagentrunning execution contextを示します。

execution context stackは、execution contextsを追跡するために使用されます。running execution contextは常にこのstackのtop elementです。現在running execution contextに関連付けられたexecutable codeから、そのexecution contextに関連付けられていないexecutable codeへ制御が移されるたびに、新しいexecution contextが作成されます。新しく作成されたexecution contextはstackへpushされ、running execution contextになります。

execution contextは、それに関連付けられたコードの実行進行を追跡するために必要な実装固有の状態を含みます。各execution contextは、少なくともTable 21に列挙される状態componentsを持ちます。

Table 21: State Components for All Execution Contexts
Component 目的
code evaluation state このexecution contextに関連付けられたコードの評価を実行、一時停止、および再開するために必要な任意の状態。
Function このexecution contextfunction objectのコードを評価している場合、このcomponentの値はそのfunction objectです。contextがScriptまたはModuleのコードを評価している場合、その値はnullです。
Realm 関連付けられたコードがECMAScriptリソースへアクセスする元となるRealm Record
ScriptOrModule 関連付けられたコードの由来となるModule RecordまたはScript RecordInitializeHostDefinedRealmで作成される元のexecution contextの場合のように、由来となるscriptまたはmoduleが存在しない場合、その値はnullです。

running execution contextによるコードの評価は、この仕様内で定義されるさまざまな点で一時停止される場合があります。running execution contextが一時停止されると、別のexecution contextがrunning execution contextになり、そのコードの評価を開始する場合があります。後の時点で、一時停止されたexecution contextが再びrunning execution contextになり、以前に一時停止された点からそのコードの評価を継続する場合があります。execution contexts間でのrunning execution context状態の遷移は、通常stack-like last-in/first-out mannerで発生します。ただし、一部のECMAScript featuresは、running execution contextの非LIFO遷移を必要とします。

running execution contextRealm componentの値は、current Realm Recordとも呼ばれます。running execution contextのFunction componentの値は、active function objectとも呼ばれます。

ECMAScript code execution contextsは、Table 22に列挙される追加の状態componentsを持ちます。

Table 22: Additional State Components for ECMAScript Code Execution Contexts
Component 目的
LexicalEnvironment このexecution context内のコードによって行われるidentifier referencesを解決するために使用されるEnvironment Recordを識別します。
VariableEnvironment このexecution context内のVariableStatementによって作成されたbindingsを保持するEnvironment Recordを識別します。
PrivateEnvironment 最も近い包含class内のClassElementによって作成されたPrivate Namesを保持するPrivateEnvironment Recordを識別します。包含classが存在しない場合はnull

execution contextのLexicalEnvironmentおよびVariableEnvironment componentsは、常にEnvironment Recordsです。

Generatorsの評価を表すexecution contextsは、Table 23に列挙される追加の状態componentsを持ちます。

Table 23: Additional State Components for Generator Execution Contexts
Component 目的
Generator このexecution contextが評価しているGenerator。

ほとんどの状況では、この仕様内のアルゴリズムによって直接操作されるのは、running execution contextexecution context stackのtop)のみです。したがって、“LexicalEnvironment”および“VariableEnvironment”という用語が修飾なしで使用される場合、それらはrunning execution contextのそれらのcomponentsを参照します。

execution contextは純粋に仕様上の仕組みであり、ECMAScript実装の特定のartefactに対応する必要はありません。ECMAScriptコードがexecution contextへ直接アクセスしたり観測したりすることは不可能です。

9.4.1 GetActiveScriptOrModule ( )

The abstract operation GetActiveScriptOrModule takes no arguments and returns a Script Record, a Module Record, or null. これは、running execution contextに基づいて、running scriptまたはmoduleを決定するために使用されます。 It performs the following steps when called:

  1. execution context stackが空なら、nullを返す。
  2. executionContextを、execution context stack上でScriptOrModule componentがnullでない最上位のexecution contextとする。
  3. そのようなexecution contextが存在しないなら、nullを返す。
  4. executionContextのScriptOrModuleを返す。

9.4.2 ResolveBinding ( name [ , envRecord ] )

The abstract operation ResolveBinding takes argument name (a String) and optional argument envRecord (an Environment Record or undefined) and returns either a normal completion containing a Reference Record or a throw completion. これはnameのbindingを決定するために使用されます。envRecordは、bindingを検索するEnvironment Recordを明示的に提供するために使用できます。 It performs the following steps when called:

  1. envRecordが存在しない、またはenvRecordundefinedなら、
    1. envRecordrunning execution contextのLexicalEnvironmentに設定する。
  2. Assert: envRecordEnvironment Recordである。
  3. strictを、評価中のsyntactic productionのIsStrictとする。
  4. GetIdentifierReference(envRecord, name, strict)を返す。
Note

ResolveBindingの結果は、常に[[ReferencedName]]フィールドがnameであるReference Recordです。

9.4.3 GetThisEnvironment ( )

The abstract operation GetThisEnvironment takes no arguments and returns an Environment Record. これは、現在keyword thisのbindingを供給しているEnvironment Recordを見つけます。 It performs the following steps when called:

  1. envRecordrunning execution contextのLexicalEnvironmentとする。
  2. 繰り返す
    1. existsenvRecord.HasThisBinding()とする。
    2. existstrueなら、envRecordを返す。
    3. outerenvRecord.[[OuterEnv]]とする。
    4. Assert: outernullでない。
    5. envRecordouterに設定する。
Note

ステップ2のloopは常に終了します。なぜなら、environmentsのlistは常にthis bindingを持つglobal environmentで終わるからです。

9.4.4 ResolveThisBinding ( )

The abstract operation ResolveThisBinding takes no arguments and returns either a normal completion containing an ECMAScript language value or a throw completion. これは、running execution contextのLexicalEnvironmentを使用して、keyword thisのbindingを決定します。 It performs the following steps when called:

  1. envRecordGetThisEnvironment()とする。
  2. envRecord.GetThisBinding()を返す。

9.4.5 GetNewTarget ( )

The abstract operation GetNewTarget takes no arguments and returns an Object or undefined. これは、running execution contextのLexicalEnvironmentを使用して、NewTarget値を決定します。 It performs the following steps when called:

  1. envRecordGetThisEnvironment()とする。
  2. Assert: envRecord[[NewTarget]]フィールドを持つ。
  3. envRecord.[[NewTarget]]を返す。

9.4.6 GetGlobalObject ( )

The abstract operation GetGlobalObject takes no arguments and returns an Object. これは、現在running execution contextによって使用されるglobal objectを返します。 It performs the following steps when called:

  1. currentRealmcurrent Realm Recordとする。
  2. currentRealm.[[GlobalObject]]を返す。

9.4.7 RunSuspendedContext ( context, completionRecord )

The abstract operation RunSuspendedContext takes arguments context (an execution context) and completionRecord (a Completion Record) and returns either a normal completion containing either an ECMAScript language value or unused, or an abrupt completion. これはcontextを再開し(completionRecordを再開値として送信します)、その結果を待ちます。 It performs the following steps when called:

  1. callerContextrunning execution contextとする。
  2. callerContextを一時停止する。
  3. contextexecution context stackへpushする;contextは現在running execution contextである。
  4. contextの一時停止された評価を再開する。このとき、completionRecordを、それを一時停止した操作の結果として使用する。resultを、再開された計算によって返されたCompletion Recordとする。
  5. Assert: このステップに到達したとき、contextはすでにexecution context stackから取り除かれており、callerContextが再びrunning execution contextである。
  6. Completion(result)を返す。

9.4.8 RunCallerContext ( value )

The abstract operation RunCallerContext takes argument value (ECMAScript言語値またはempty) and returns Completion Record. これは呼び出し元コンテキストを再開し(再開値としてvalueを送信する)、もしあればその結果を待つ。 It performs the following steps when called:

  1. genContextを、実行中の実行コンテキストとする。
  2. 実行コンテキストスタックからgenContextを取り除き、実行コンテキストスタックの先頭にある実行コンテキストを実行中の実行コンテキストとして復元する。
  3. callerContextを、実行中の実行コンテキストとする。
  4. NormalCompletion(value)を渡して、callerContextを再開する。
  5. NOTE: 上記の手順は制御をcallerContextに移し、一時停止する。このアルゴリズムで一時停止が解除され、後続の手順へ制御が進む唯一の方法は、genContextが再び再開されることであり、それは決して起こらない可能性がある。
  6. Assert: genContextは実行中の実行コンテキストである。
  7. resultを、genContextがたった今再開されたときのCompletion Recordとする。
  8. Completion(result)を返す。

9.5 JobsおよびJobsをEnqueueするHost Operations

Jobは、他のECMAScript計算が現在進行中でないときにECMAScript計算を開始する、parametersを持たないAbstract Closureです。

Jobsは、特定のagent内のECMAScript host environmentsによって実行のためにscheduleされます。この仕様は、jobsをscheduleするためのhost hooksであるHostEnqueueGenericJobHostEnqueueFinalizationRegistryCleanupJobHostEnqueuePromiseJob、およびHostEnqueueTimeoutJobを記述します。この仕様内のhost hooksは、jobsのschedulingに課される追加制約によって編成されています。Hostsは、jobsをscheduleする追加のabstract operationsを定義できます。そのようなoperationsは、Job Abstract ClosurerealmRealm Recordまたはnull)をparametersとして受け取ります。Realm Recordが提供された場合、これらのoperationsは、realmを所有するagent内で、提供されたrealmにおいて将来のある時点でjobが実行されるようscheduleします。realmとして代わりにnullが提供された場合、そのjobはECMAScriptコードを評価しません。それらの実装は、次の要件に適合しなければなりません:

  • 将来のある時点で、jobがscheduleされたagentにrunning contextが存在せず、そのagentexecution context stackが空であるとき、実装は次を行わなければならない:
    1. 任意のhost-defined準備ステップを実行する。
    2. Job Abstract ClosureInvokeする。
    3. 任意のhost-defined cleanup stepsを実行し、その後execution context stackは空でなければならない。
  • 任意の時点で、agent内でactiveに評価中であるJobは1つだけであってよい。
  • Jobの評価が開始したら、そのagent内で他のJobの評価が開始する前に完了まで実行されなければならない。
  • Abstract Closurenormal completionを返さなければならず、自身でerrorsの処理を実装する。
Note 1
Host environmentsは、schedulingに関してJobsを一律に扱うことを要求されません。たとえば、web browsersおよびNode.jsは、Promise-handling Jobsを他の作業より高いpriorityとして扱います;将来のfeaturesは、そのような高いpriorityとして扱われないJobsを追加する場合があります。

任意の特定の時点で、次の条件のすべてがtrueであるなら、scriptOrModuleScript RecordModule Record、またはnull)はactive script or moduleです:

任意の特定の時点で、次の条件のすべてがtrueであるなら、executionはECMAScriptコードを評価する準備ができているものとします:

Note 2

Host environmentsは、execution contextsexecution context stackへpushすることによって、コードを評価するためのexecutionをprepareする場合があります。具体的なstepsはimplementation-definedです。

Realmの具体的な選択はhost environment次第です。この初期execution contextおよびRealmは、callback functionが呼び出される前にのみ使用されます。Promise handlerのようなJobに関連するcallback functionが呼び出されると、その呼び出しは自身のexecution contextおよびRealmをpushします。

特定の種類のJobsには追加のconformance requirementsがあります。

9.5.1 JobCallback Records

JobCallback Recordは、function objectおよびhost-defined valueを格納するために使用されるRecord値です。hostによってenqueuedされたJobを通じて呼び出されるfunction objectsは、追加のhost-defined contextを持つ場合があります。その状態を伝播するために、Job Abstract Closuresfunction objectsを直接captureしてcallすべきではありません。代わりに、HostMakeJobCallbackおよびHostCallJobCallbackを使用します。

Note

たとえば、WHATWG HTML specification(https://html.spec.whatwg.org/)は、Promise callbacksのincumbent settings objectを伝播するためにhost-defined valueを使用します。

JobCallback Recordsは、Table 24に列挙されるフィールドを持ちます。

Table 24: JobCallback Record Fields
フィールド名 意味
[[Callback]] function object Jobが呼び出されたときに呼び出すfunction。
[[HostDefined]] anything(デフォルト値はempty hostsによる使用のために予約されたフィールド。

9.5.2 HostMakeJobCallback ( callback )

The host-defined abstract operation HostMakeJobCallback takes argument callback (a function object) and returns a JobCallback Record.

HostMakeJobCallbackの実装は、次の要件に適合しなければなりません:

  • [[Callback]]フィールドがcallbackであるJobCallback Recordを返さなければならない。

HostMakeJobCallbackのデフォルト実装は、呼び出されたときに次のstepsを実行します:

  1. JobCallback Record { [[Callback]]: callback, [[HostDefined]]: empty }を返す。

web browsersでないECMAScript hostsは、HostMakeJobCallbackのデフォルト実装を使用しなければなりません。

Note

これは、callbackが最終的にscheduleされ実行されることを担うfunctionに渡された時点で呼び出されます。たとえば、promise.then(thenAction)は、reaction Jobをscheduleする時点ではなく、Promise.prototype.thenを呼び出す時点でthenActionに対してMakeJobCallbackを呼び出します。

9.5.3 HostCallJobCallback ( jobCallback, thisValue, argList )

The host-defined abstract operation HostCallJobCallback takes arguments jobCallback (a JobCallback Record), thisValue (an ECMAScript language value), and argList (a List of ECMAScript language values) and returns either a normal completion containing an ECMAScript language value or a throw completion.

HostCallJobCallbackの実装は、次の要件に適合しなければなりません:

  • Call(jobCallback.[[Callback]], thisValue, argList)の結果を実行して返さなければならない。
Note

この要件は、hostsがこの仕様で定義されるfunction objects[[Call]] behaviourを変更できないことを意味します。

HostCallJobCallbackのデフォルト実装は、呼び出されたときに次のstepsを実行します:

  1. Assert: IsCallable(jobCallback.[[Callback]])はtrueである。
  2. Call(jobCallback.[[Callback]], thisValue, argList)を返す。

web browsersでないECMAScript hostsは、HostCallJobCallbackのデフォルト実装を使用しなければなりません。

9.5.4 HostEnqueueGenericJob ( job, realm )

The host-defined abstract operation HostEnqueueGenericJob takes arguments job (a Job Abstract Closure) and realm (a Realm Record) and returns unused. これは、realm.[[AgentSignifier]]によって示されるagent内のrealm realmにおいて、将来のある時点で実行されるようにjobをscheduleします。このalgorithmとともに使用されるAbstract Closuresは、priorityやorderingなどの追加制約なしでscheduleされることを意図しています。

HostEnqueueGenericJobの実装は、9.5の要件に適合しなければなりません。

9.5.5 HostEnqueuePromiseJob ( job, realm )

The host-defined abstract operation HostEnqueuePromiseJob takes arguments job (a Job Abstract Closure) and realm (a Realm Record or null) and returns unused. これは、将来のある時点で実行されるようにjobをscheduleします。このalgorithmとともに使用されるAbstract Closuresは、Promisesの処理に関連する、またはそれ以外でPromise handling operationsと同じpriorityでscheduleされることを意図しています。

HostEnqueuePromiseJobの実装は、9.5の要件に加えて、次に適合しなければなりません:

  • realmnullでないなら、jobが呼び出されるたびに、jobの呼び出し時点でexecutionがECMAScriptコードを評価する準備ができるように、implementation-defined stepsを実行しなければならない。
  • HostEnqueuePromiseJobが呼び出された時点のGetActiveScriptOrModule()をscriptOrModuleとする。realmnullでないなら、jobが呼び出されるたびに、jobの呼び出し時点でscriptOrModuleactive script or moduleであるように、implementation-defined stepsを実行しなければならない。
  • Jobsは、それらをscheduleしたHostEnqueuePromiseJob呼び出しと同じ順序で実行されなければならない。
Note

NewPromiseResolveThenableJobによって返されるJobsrealmは通常、then function objectに対してGetFunctionRealmを呼び出した結果です。NewPromiseReactionJobによって返されるJobsrealmは通常、handlerがundefinedでない場合、そのhandlerに対してGetFunctionRealmを呼び出した結果です。handlerがundefinedである場合、realmnullです。両方の種類のJobsについて、GetFunctionRealmがabnormallyに完了する場合(すなわちrevoked Proxy上で呼び出された場合)、realmGetFunctionRealm呼び出し時点のcurrent Realm Recordです。realmnullの場合、user ECMAScript codeは評価されず、新しいECMAScript objects(例:Error objects)は作成されません。たとえば、WHATWG HTML specification(https://html.spec.whatwg.org/)は、scriptを実行できる能力およびentry conceptを確認するためにrealmを使用します。

9.5.6 HostEnqueueTimeoutJob ( timeoutJob, realm, milliseconds )

The host-defined abstract operation HostEnqueueTimeoutJob takes arguments timeoutJob (a Job Abstract Closure), realm (a Realm Record), and milliseconds (a non-negative finite Number) and returns unused. これは、realm.[[AgentSignifier]]によって示されるagent内のrealm realmにおいて、少なくともmillisecondsミリ秒後に実行されるようにtimeoutJobをscheduleします。

HostEnqueueTimeoutJobの実装は、9.5の要件に適合しなければなりません。

9.6 Agents

agentは、ECMAScript execution contextsの集合、execution context stackrunning execution contextAgent Record、およびexecuting threadから構成されます。executing threadを除き、agentの構成要素はそのagentのみに属します。

agentexecuting threadは、他のagentsから独立して、そのagentexecution contexts上でalgorithmic stepsを実行します。ただし、threadを共有するどのagent[[CanBlock]]フィールドがtrueであるAgent Recordを持たない場合、executing threadは複数のagentsによってexecuting threadとして使用される場合があります。

Note 1

たとえば、一部のweb browsersは、browser windowの複数の無関係なtabs間で単一のexecuting threadを共有します。

agentexecuting threadがalgorithmic stepsを実行している間、そのagentはそれらのstepsに対するsurrounding agentです。stepsは、agent内に保持される仕様レベルのexecution objects、すなわちrunning execution contextexecution context stack、およびAgent Recordのfieldsにアクセスするためにsurrounding agentを使用します。

agent signifierは、Agentを識別するために使用されるglobally-unique opaque valueです。

Table 25: エージェントレコードのフィールド
フィールド名 意味
[[LittleEndian]] Boolean 値 アルゴリズム GetValueFromBuffer および SetValueInBuffer で必要とされるときに、isLittleEndian パラメーターについて計算される既定値。この選択は実装定義であり、実装にとって最も効率的な代替であるべきである。
[[CanBlock]] Boolean 値 エージェントがブロックできるかどうかを決定する。
[[Signifier]] エージェント記号子 そのエージェントクラスター内でエージェントを一意に識別する。
[[IsLockFree1]] Boolean 値 1バイト値に対するアトミック操作がロックフリーであれば true、そうでなければ false
[[IsLockFree2]] Boolean 値 2バイト値に対するアトミック操作がロックフリーであれば true、そうでなければ false
[[IsLockFree8]] Boolean 値 8バイト値に対するアトミック操作がロックフリーであれば true、そうでなければ false
[[CandidateExecution]] 候補実行 Record メモリーモデルを参照。
[[KeptAlive]] Object または Symbol のいずれかの List 初期状態では新しい空の List であり、現在の Job の終了まで生存させておくオブジェクトおよび/またはシンボルのリストを表す
[[ModuleAsyncEvaluationCount]] 整数 初期状態では 0 であり、非同期である、または非同期依存関係を持つモジュールの [[AsyncEvaluationOrder]] フィールドに、一意に増加する値を割り当てるために使用される。
[[GlobalSymbolRegistry]] GlobalSymbolRegistry RecordList 初期状態では新しい空の List であり、Symbol.for によって生成される Symbol 値のリストを表す。

[[LittleEndian]][[Signifier]][[IsLockFree1]][[IsLockFree2]]、および [[IsLockFree8]] の値は変更できない。

[[GlobalSymbolRegistry]] List は追加専用であり、再割り当てされることはない。

Note 2

[[IsLockFree1]][[IsLockFree2]]、および[[IsLockFree8]]の値は、必ずしもhardwareによって決定されるとは限らず、時間の経過やECMAScript実装間で変化し得るimplementation choicesを反映する場合もあります。

[[IsLockFree4]]フィールドはありません:4-byte atomic operationsは常にlock-freeです。

実際には、atomic operationが何らかの種類のlockで実装されている場合、そのoperationはlock-freeではありません。Lock-freeはwait-freeを意味しません:lock-free atomic operationを完了するために必要となるmachine stepsの数に上限はありません。

サイズnのatomic accessがlock-freeであることは、サイズnのnon-atomic accessesの(知覚される)atomicityについて何も意味しません。具体的には、non-atomic accessesは依然として複数の個別memory accessesのsequenceとして実行される場合があります。詳細はReadSharedMemoryおよびWriteSharedMemoryを参照してください。

Note 3

agentは仕様上の仕組みであり、ECMAScript実装の特定のartefactに対応する必要はありません。

9.6.1 AgentSignifier ( )

The abstract operation AgentSignifier takes no arguments and returns an agent signifier. It performs the following steps when called:

  1. agentRecordsurrounding agentAgent Recordとする。
  2. agentRecord.[[Signifier]]を返す。

9.6.2 AgentCanSuspend ( )

The abstract operation AgentCanSuspend takes no arguments and returns a Boolean. It performs the following steps when called:

  1. agentRecordsurrounding agentAgent Recordとする。
  2. agentRecord.[[CanBlock]]を返す。
Note

一部のenvironmentsでは、特定のagentがsuspendすることが合理的でない場合があります。たとえば、web browser environmentでは、documentのmain event handling threadのsuspendingを許可しない一方で、workersのevent handling threadsがsuspendすることは許可するのが合理的な場合があります。

9.6.3 IncrementModuleAsyncEvaluationCount ( )

The abstract operation IncrementModuleAsyncEvaluationCount takes no arguments and returns a non-negative integer. It performs the following steps when called:

  1. agentRecordsurrounding agentAgent Recordとする。
  2. countagentRecord.[[ModuleAsyncEvaluationCount]]とする。
  3. agentRecord.[[ModuleAsyncEvaluationCount]]count + 1に設定する。
  4. countを返す。
Note

この値は、pending modules間の相対的なevaluation orderを追跡するためだけに使用されます。実装は、pending modulesが存在しないときはいつでも、観測不能に[[ModuleAsyncEvaluationCount]]を0へresetしてよいです。

9.7 Agent Clusters

agent clusterは、shared memory上で操作することによって通信できるagentsのmaximal setです。

Note 1

異なるagents内のprogramsは、unspecified meansによってmemoryを共有する場合があります。最低限、SharedArrayBuffersのbacking memoryはcluster内のagents間で共有できます。

message passingによって通信できるがmemoryを共有できないagentsが存在する場合があります;それらが同じagent cluster内に入ることは決してありません。

すべてのagentはちょうど1つのagent clusterに属します。

Note 2

cluster内のagentsは、特定の時点で必ずしもすべてaliveである必要はありません。agent Aが別のagent Bを作成し、その後Aが終了し、Bagent Cを作成した場合、Aが何らかのmemoryをBと共有でき、かつBが何らかのmemoryをCと共有できるなら、この3つのagentsは同じcluster内にあります。

cluster内のすべてのagentsは、それぞれのAgent Records内の[[LittleEndian]]フィールドについて同じ値を持たなければなりません。

Note 3

agent cluster内の異なるagents[[LittleEndian]]の異なる値を持つ場合、multi-byte dataにshared memoryを使用することが困難になります。

cluster内のすべてのagentsは、それぞれのAgent Records内の[[IsLockFree1]]フィールドについて同じ値を持たなければなりません;[[IsLockFree2]]および[[IsLockFree8]]フィールドについても同様です。

cluster内のすべてのagentsは、それぞれのAgent Records内の[[Signifier]]フィールドについて異なる値を持たなければなりません。

embeddingは、agentの知識または協力なしに、agentをdeactivate(forward progressを停止)またはactivate(forward progressを再開)する場合があります。embeddingがそうする場合、cluster内の一部のagentsをactiveのままにし、同じcluster内の他のagentsを無期限にdeactivatedにしておいてはなりません。

Note 4

前述の制限の目的は、別のagentがdeactivatedされたためにagentがdeadlockまたはstarveする状況を避けることです。たとえば、任意のwindows内のdocumentsとは独立したlifetimeを持つHTML shared workerが、そのような独立したdocumentのdedicated workerとmemoryを共有することを許可された場合、documentとそのdedicated workerが、dedicated workerがlockを保持している間にdeactivatedされ(たとえば、documentがwindowのhistoryにpushされる)、shared workerがそのlockをacquireしようとすると、そのshared workerはdedicated workerが再びactivatedされるまで、もしされるなら、その間blockedされます。その間、他のwindowsからshared workerへアクセスしようとする他のworkersはstarveします。

この制限の含意は、embedding内で同じsuspend/wake collectiveに属さないagents間ではmemoryを共有できないということです。

embeddingは、agentのcluster内の他のagentsの事前の知識または協力なしに、agentをterminateする場合があります。agentが、自身またはcluster内の別のagentのprogrammatic actionによってではなく、cluster外部の力によってterminatedされる場合、embeddingは2つの戦略のいずれかを選択しなければなりません:cluster内のすべてのagentsをterminateするか、またはcluster内のagentsがcoordinationできるreliable APIsを提供し、clusterの少なくとも1つの残存memberがterminationを検出でき、termination dataがterminatedされたagentを識別するのに十分な情報を含むようにするか、のいずれかです。

Note 5

その種のterminationの例は次のとおりです:operating systemsまたはusersが別processで実行中のagentsをterminateすること;embedding自体が、per-agent resource accountingによりagentがrunawayであると示されたとき、他のagentsと同じprocess内で実行中のagentをterminateすること。

次の仕様値、およびそれらから推移的に到達可能な値は、それぞれちょうど1つのagent clusterに属します。

cluster内の任意のagentによる任意のECMAScriptコードの評価に先立ち、cluster内のすべてのagentsAgent Record[[CandidateExecution]]フィールドは、initial candidate executionに設定されます。initial candidate executionは空のcandidate executionであり、その[[EventsRecords]]フィールドは、各agentについて、そのagentagent signifier[[AgentSignifier]]フィールドに持ち、[[EventList]]および[[AgentSynchronizesWith]]フィールドが空のListsであるAgent Events Recordを含むListです。

Note 6

agent cluster内のすべてのagentsは、そのAgent Record[[CandidateExecution]]フィールド内で同じcandidate executionを共有します。candidate executionmemory modelによって使用される仕様上の仕組みです。

Note 7

agent clusterは仕様上の仕組みであり、ECMAScript実装の特定のartefactに対応する必要はありません。

9.8 Forward Progress

agentforward progressを行うとは、この仕様に従ってevaluation stepを実行することです。

agentは、そのrunning execution contextが外部eventを同期的かつ無期限に待つとき、blockedになります。この意味でblockedになれるのは、そのAgent Record[[CanBlock]]フィールドがtrueであるagentsだけです。unblocked agentとは、blockedでないagentです。

実装は次を保証しなければなりません:

  • dedicated executing threadを持つすべてのunblocked agentは、最終的にforward progressを行う
  • executing threadを共有するagentsの集合では、1つのagentが最終的にforward progressを行う
  • agentは、blockingを提供する明示的なAPIsを通じる場合を除き、別のagentをblockedにさせない。
Note

これは、memory model内のliveness guaranteeとともに、すべてのseq-cst writesが最終的にすべてのagentsに観測可能になることを保証します。

9.9 WeakRefおよびFinalizationRegistry TargetsのProcessing Model

9.9.1 目的

この仕様は、任意のobjectまたはsymbolがgarbage collectedされることについて、いかなる保証も行いません。liveでないobjectsまたはsymbolsは、長期間の後にreleaseされる場合もあれば、まったくreleaseされない場合もあります。この理由により、この仕様はgarbage collectionによってtriggerされるbehaviourを記述するときに“may”という用語を使用します。

WeakRefsおよびFinalizationRegistrysのsemanticsは、特定の時点で発生する2つのoperationsに基づきます:

  • WeakRef.prototype.derefが呼び出されると、referent(undefinedが返されない場合)は、その後の同期的なアクセスも同じ値を返すようにaliveに保持されます。このlistは、ClearKeptObjects abstract operationを使用して同期的な作業が完了したときにresetされます。
  • FinalizationRegistryに登録されたobjectまたはsymbolが到達不能になると、同期的なECMAScript実行が完了した後に、FinalizationRegistryのcleanup callbackの呼び出しが最終的に行われる場合があります。FinalizationRegistry cleanupは、CleanupFinalizationRegistry abstract operationによって実行されます。

これらのactions(ClearKeptObjectsまたはCleanupFinalizationRegistry)のいずれも、同期的なECMAScript実行をinterruptしてはなりません。hostsはより長い同期的なECMAScript実行runsを構成する場合があるため、この仕様はClearKeptObjectsおよびCleanupFinalizationRegistryのschedulingをhost environmentへ委ねます。

一部のECMAScript実装には、ECMAScriptがidleであるときを含め、backgroundで実行されるgarbage collector implementationsが含まれます。host environmentにCleanupFinalizationRegistryをscheduleさせることで、finalizer workを実行するためにECMAScript実行を再開でき、held valuesを解放して全体的なmemory usageを減らせる場合があります。

9.9.2 Liveness

objectsおよび/またはsymbolsの集合objSetについて、objSetに関するhypothetical WeakRef-oblivious executionとは、referentがobjSetの要素であるWeakRefのabstract operation WeakRefDerefが常にundefinedを返すexecutionです。

Note 1
WeakRef-obliviousnessは、livenessとともに、2つの概念を捉えます。1つ目は、WeakRef自体はそのreferentをaliveに保持しないこと。2つ目は、livenessにおけるcyclesが、値がliveであることを意味しないことです。具体的には、vのlivenessの決定がWeakRef referent rのlivenessの決定に依存する場合、rのlivenessはvのlivenessを仮定できません。それは循環推論になるためです。
Note 2
WeakRef-obliviousnessは、cyclesを考慮するため、個別の値ではなくobjectsまたはsymbolsの集合上で定義されます。もし個別の値上で定義されていたなら、cycle内のWeakRef referentは、そのidentityがcycle内の他のWeakRef referentsを通じてのみ観測される場合でもliveとみなされます。
Note 3
口語的には、個々のobjectまたはsymbolは、それを含むすべての集合がliveであるならliveであると言います。

評価中の任意の時点で、objectsおよび/またはsymbolsの集合objSetは、次の条件のいずれかが満たされる場合、liveとみなされます:

  • objSet内の任意の要素が、任意のagent[[KeptAlive]] Listに含まれている。
  • objSetに関するvalid future hypothetical WeakRef-oblivious executionが存在し、そのexecutionがobjSet内の任意の値のidentityを観測する。
Note 4
上記の2番目の条件は、値のidentityがnon-WeakRef手段を通じて観測可能である場合、その値はliveであるという直観を捉えることを意図しています。値のidentityは、strict equality comparisonを観測すること、または値がMap内のkeyとして使用されることを観測することによって観測される場合があります。
Note 5

field、internal slot、またはproperty内にobjectまたはsymbolが存在することは、その値がliveであることを意味しません。たとえば、問題の値がprogramへ返されることがないなら、それは観測できません。

これは、WeakMap内のkeys、WeakSetのmembers、ならびにFinalizationRegistry Cell recordの[[WeakRefTarget]]および[[UnregisterToken]]フィールドに当てはまります。

上記の定義は、WeakMap内のkeyがliveでないなら、その対応するvalueも必ずしもliveではないことを含意します。

Note 6
Livenessは、どのWeakRefsをenginesが空にしてはならないかを保証する下限です。ここで定義されるLivenessは決定不能です。実際には、enginesはreachabilityなどの保守的近似を使用します。かなりのimplementation leewayがあることが期待されます。

9.9.3 Execution

任意の時点で、objectsおよび/またはsymbolsの集合objSetliveでない場合、ECMAScript実装は次のstepsをatomicallyに実行してよいです:

  1. objSetの各要素valueについて、以下を行う
    1. ref.[[WeakRefTarget]]valueであるような各WeakRef refについて、以下を行う
      1. ref.[[WeakRefTarget]]emptyに設定する。
    2. finalizationRegistry.[[Cells]]が、cell.[[WeakRefTarget]]valueであるようなRecord cellを含む各FinalizationRegistry finalizationRegistryについて、以下を行う
      1. cell.[[WeakRefTarget]]emptyに設定する。
      2. enqueueCleanupを、trueまたはfalseのいずれかのimplementation-defined choiceとする。
      3. enqueueCleanuptrueなら、HostEnqueueFinalizationRegistryCleanupJob(finalizationRegistry)を実行する。
    3. map.[[WeakMapData]]が、entry.[[Key]]valueであるようなRecord entryを含む各WeakMap mapについて、以下を行う
      1. entry.[[Key]]emptyに設定する。
      2. entry.[[Value]]emptyに設定する。
    4. set.[[WeakSetData]]valueを含む各WeakSet setについて、以下を行う
      1. 値がvalueであるset.[[WeakSetData]]の要素を、値がemptyである要素で置き換える。
Note 1

livenessの定義とともに、このclauseは、WeakRefsに関して実装が適用してよいoptimizationsを規定します。

objectのidentityを観測せずにそのobjectへアクセスすることは可能です。identityが観測されないnon-escaping objectsのpropertiesに対するdead variable eliminationやscalar replacementなどのoptimizationsは許可されます。したがって、これらのoptimizationsは、そのようなobjectsを指すWeakRefsを観測可能にemptyにすることが許可されます。

一方、objectのidentityが観測可能であり、そのobjectがWeakRef[[WeakRefTarget]] internal slot内にある場合、WeakRefを観測可能にemptyにするrematerializationなどのoptimizationsは禁止されます。

HostEnqueueFinalizationRegistryCleanupJobの呼び出しはoptionalであるため、FinalizationRegistry内のregistered objectsは、そのFinalizationRegistryを必ずしもliveに保持しません。実装は、任意の理由でFinalizationRegistry callbacksを省略してよく、たとえばFinalizationRegistry自体がdeadになる場合、またはapplicationがshutting downする場合があります。

Note 2

実装は、non-live objectsまたはsymbolsのmaximal setsについてWeakRefsをemptyにする義務を負いません。

実装がWeakRefsをemptyにするnon-live set objSetを選択した場合、この定義はobjSet内のすべての値に対するWeakRefsを同時にemptyにすることを要求します。言い換えると、空にされなければvの値を観測するexecutionが生じ得る他のWeakRefsをemptyにせずに、値vを指すWeakRefをemptyにすることは、実装にとってconformantではありません。

9.9.4 Host Hooks

9.9.4.1 HostEnqueueFinalizationRegistryCleanupJob ( finalizationRegistry )

The host-defined abstract operation HostEnqueueFinalizationRegistryCleanupJob takes argument finalizationRegistry (a FinalizationRegistry) and returns unused.

cleanupJobを、finalizationRegistryをcaptureし、呼び出されたときに次のstepsを実行する、parametersを持たない新しいJob Abstract Closureとする:

  1. cleanupResultCompletion(CleanupFinalizationRegistry(finalizationRegistry))とする。
  2. cleanupResultabrupt completionであるなら、errorをreportするための任意のhost-defined stepsを実行する。
  3. unusedを返す。

HostEnqueueFinalizationRegistryCleanupJobの実装は、可能であれば、将来のある時点でcleanupJobが実行されるようscheduleします。また、9.5の要件にも適合しなければなりません。

9.10 ClearKeptObjects ( )

The abstract operation ClearKeptObjects takes no arguments and returns unused. ECMAScript実装は、ECMAScript実行の同期的sequenceが完了したときにClearKeptObjectsを呼び出すことが期待されます。 It performs the following steps when called:

  1. agentRecordsurrounding agentAgent Recordとする。
  2. agentRecord.[[KeptAlive]]を新しい空のListに設定する。
  3. unusedを返す。

9.11 AddToKeptObjects ( value )

The abstract operation AddToKeptObjects takes argument value (an Object or a Symbol) and returns unused. It performs the following steps when called:

  1. agentRecordsurrounding agentAgent Recordとする。
  2. valueagentRecord.[[KeptAlive]]へappendする。
  3. unusedを返す。
Note
abstract operation AddToKeptObjectsがtarget objectまたはsymbolとともに呼び出されると、それはClearKeptObjectsが呼び出されるまでtargetをstronglyに指すlistへtargetを追加します。

9.12 CleanupFinalizationRegistry ( finalizationRegistry )

The abstract operation CleanupFinalizationRegistry takes argument finalizationRegistry (a FinalizationRegistry) and returns either a normal completion containing unused or a throw completion. It performs the following steps when called:

  1. Assert: finalizationRegistry[[Cells]]および[[CleanupCallback]] internal slotsを持つ。
  2. callbackfinalizationRegistry.[[CleanupCallback]]とする。
  3. finalizationRegistry.[[Cells]]cell.[[WeakRefTarget]]emptyであるRecord cellを含む間、実装は次のstepsを実行してよい:
    1. そのようなcellを任意に選択する。
    2. cellfinalizationRegistry.[[Cells]]から削除する。
    3. HostCallJobCallback(callback, undefined, « cell.[[HeldValue]] »)を実行する。
  4. unusedを返す。

9.13 CanBeHeldWeakly ( arg )

The abstract operation CanBeHeldWeakly takes argument arg (an ECMAScript language value) and returns a Boolean. これは、argがweak referenceとして使用するのに適している場合に限り、trueを返します。weak referenceとして使用するのに適した値のみが、WeakMapのkey、WeakSetのelement、WeakRefのtarget、またはFinalizationRegistryのtargetsの1つになれます。 It performs the following steps when called:

  1. argがObjectなら、trueを返す。
  2. argがSymbolであり、KeyForSymbol(arg)がundefinedなら、trueを返す。
  3. falseを返す。
Note

language identityを持たないlanguage valueは、事前の参照なしにmanifestでき、weak referenceとして使用するには適していません。Symbol.forによって生成されたSymbol valueは、他のSymbol valuesと異なり、language identityを持たず、weak referenceとして使用するには適していません。Well-known symbolsはcollectionされることがない可能性が高いですが、数が限られており、したがってさまざまなimplementation approachesで管理可能であるため、それでもweak referenceとして使用するのに適しているものとして扱われます。ただし、live WeakMap内でwell-known symbolに関連付けられた任意の値はcollectionされにくく、実装においてmemory resourcesを“leak”する可能性があります。

10 Ordinary ObjectsおよびExotic Objectsの振る舞い

10.1 Ordinary Object Internal Methods and Internal Slots

すべてのordinary objectsは、[[Prototype]]と呼ばれるinternal slotを持ちます。このinternal slotの値はnullまたはobjectのいずれかであり、inheritanceの実装に使用されます。propertyKeyという名前のpropertyがordinary object objには存在しないが、その[[Prototype]] object上には存在すると仮定します。propertyKey[[Prototype]] object上のdata propertyを参照する場合、objはget accessについてそれを継承し、propertyKeyobjのpropertyであるかのように振る舞います。propertyKey[[Prototype]] object上のwritable data propertyを参照する場合、obj上のpropertyKeyのset accessは、obj上にpropertyKeyという名前の新しいdata propertyを作成します。propertyKey[[Prototype]] object上のnon-writable data propertyを参照する場合、obj上のpropertyKeyのset accessは失敗します。propertyKey[[Prototype]] object上のaccessor propertyを参照する場合、そのaccessorはget accessとset accessの両方についてobjに継承されます。

すべてのordinary objectはBoolean値の[[Extensible]] internal slotを持ち、これは6.1.7.3で指定されるextensibility関連のinternal method invariantsを満たすために使用されます。すなわち、objectの[[Extensible]] internal slotの値がいったんfalseに設定されると、そのobjectにpropertiesを追加すること、そのobjectの[[Prototype]] internal slotの値を変更すること、またはその後[[Extensible]]の値をtrueへ変更することは、もはや不可能になります。

以下のalgorithm descriptionsでは、objordinary objectpropertyKeyproperty key値、valueは任意のECMAScript言語値propertyDescProperty Descriptor recordであると仮定します。

ordinary object internal methodは、同様の名前を持つabstract operationへ委譲します。そのようなabstract operationが別のinternal methodに依存する場合、その同様の名前を持つabstract operationを直接呼び出すのではなく、internal methodがobj上で呼び出されます。これらのsemanticsは、ordinary object internal methodsがexotic objectsに適用されたとき、exotic objectsのoverridden internal methodsが呼び出されることを保証します。

10.1.1 [[GetPrototypeOf]] ( )

The [[GetPrototypeOf]] internal method of ordinary object obj takes no arguments and returns a normal completion containing either an Object or null. It performs the following steps when called:

  1. OrdinaryGetPrototypeOf(obj)を返す。

10.1.1.1 OrdinaryGetPrototypeOf ( obj )

The abstract operation OrdinaryGetPrototypeOf takes argument obj (an Object) and returns an Object or null. It performs the following steps when called:

  1. obj.[[Prototype]]を返す。

10.1.2 [[SetPrototypeOf]] ( proto )

The [[SetPrototypeOf]] internal method of ordinary object obj takes argument proto (an Object or null) and returns a normal completion containing a Boolean. It performs the following steps when called:

  1. OrdinarySetPrototypeOf(obj, proto)を返す。

10.1.2.1 OrdinarySetPrototypeOf ( obj, proto )

The abstract operation OrdinarySetPrototypeOf takes arguments obj (an Object) and proto (an Object or null) and returns a Boolean. It performs the following steps when called:

  1. currentobj.[[Prototype]]とする。
  2. SameValue(proto, current)がtrueなら、trueを返す。
  3. extensibleobj.[[Extensible]]とする。
  4. extensiblefalseなら、falseを返す。
  5. cursorprotoとする。
  6. donefalseとする。
  7. donefalseである間、繰り返す
    1. cursornullなら、
      1. donetrueに設定する。
    2. そうでなく、SameValue(cursor, obj)がtrueなら、
      1. falseを返す。
    3. そうでなければ、
      1. cursor.[[GetPrototypeOf]]10.1.1で定義されるordinary object internal methodでないなら、donetrueに設定する。
      2. そうでなければ、cursorcursor.[[Prototype]]に設定する。
  8. obj.[[Prototype]]protoに設定する。
  9. trueを返す。
Note

ステップ7のloopは、[[GetPrototypeOf]]および[[SetPrototypeOf]]についてordinary object definitionsを使用するobjectsのみを含む任意のprototype chainにcyclesが存在しないことを保証します。

10.1.3 [[IsExtensible]] ( )

The [[IsExtensible]] internal method of ordinary object obj takes no arguments and returns a normal completion containing a Boolean. It performs the following steps when called:

  1. OrdinaryIsExtensible(obj)を返す。

10.1.3.1 OrdinaryIsExtensible ( obj )

The abstract operation OrdinaryIsExtensible takes argument obj (an Object) and returns a Boolean. It performs the following steps when called:

  1. obj.[[Extensible]]を返す。

10.1.4 [[PreventExtensions]] ( )

The [[PreventExtensions]] internal method of ordinary object obj takes no arguments and returns a normal completion containing true. It performs the following steps when called:

  1. OrdinaryPreventExtensions(obj)を返す。

10.1.4.1 OrdinaryPreventExtensions ( obj )

The abstract operation OrdinaryPreventExtensions takes argument obj (an Object) and returns true. It performs the following steps when called:

  1. obj.[[Extensible]]falseに設定する。
  2. trueを返す。

10.1.5 [[GetOwnProperty]] ( propertyKey )

The [[GetOwnProperty]] internal method of ordinary object obj takes argument propertyKey (a property key) and returns a normal completion containing either a Property Descriptor or undefined. It performs the following steps when called:

  1. OrdinaryGetOwnProperty(obj, propertyKey)を返す。

10.1.5.1 OrdinaryGetOwnProperty ( obj, propertyKey )

The abstract operation OrdinaryGetOwnProperty takes arguments obj (an Object) and propertyKey (a property key) and returns a Property Descriptor or undefined. It performs the following steps when called:

  1. objがkey propertyKeyを持つown propertyを持たないなら、undefinedを返す。
  2. propertyDescを、fieldsを持たない新しく作成されたProperty Descriptorとする。
  3. ownPropertyを、keyがpropertyKeyであるobjのown propertyとする。
  4. ownPropertydata propertyなら、
    1. propertyDesc.[[Value]]ownProperty[[Value]]属性の値に設定する。
    2. propertyDesc.[[Writable]]ownProperty[[Writable]]属性の値に設定する。
  5. そうでなければ、
    1. Assert: ownPropertyaccessor propertyである。
    2. propertyDesc.[[Get]]ownProperty[[Get]]属性の値に設定する。
    3. propertyDesc.[[Set]]ownProperty[[Set]]属性の値に設定する。
  6. propertyDesc.[[Enumerable]]ownProperty[[Enumerable]]属性の値に設定する。
  7. propertyDesc.[[Configurable]]ownProperty[[Configurable]]属性の値に設定する。
  8. propertyDescを返す。

10.1.6 [[DefineOwnProperty]] ( propertyKey, propertyDesc )

The [[DefineOwnProperty]] internal method of ordinary object obj takes arguments propertyKey (a property key) and propertyDesc (a Property Descriptor) and returns either a normal completion containing a Boolean or a throw completion. It performs the following steps when called:

  1. OrdinaryDefineOwnProperty(obj, propertyKey, propertyDesc)を返す。

10.1.6.1 OrdinaryDefineOwnProperty ( obj, propertyKey, propertyDesc )

The abstract operation OrdinaryDefineOwnProperty takes arguments obj (an Object), propertyKey (a property key), and propertyDesc (a Property Descriptor) and returns either a normal completion containing a Boolean or a throw completion. It performs the following steps when called:

  1. currentを ? obj.[[GetOwnProperty]](propertyKey) とする。
  2. extensibleを ? IsExtensible(obj) とする。
  3. ValidateAndApplyPropertyDescriptor(obj, propertyKey, extensible, propertyDesc, current)を返す。

10.1.6.2 IsCompatiblePropertyDescriptor ( extensible, propertyDesc, current )

The abstract operation IsCompatiblePropertyDescriptor takes arguments extensible (a Boolean), propertyDesc (a Property Descriptor), and current (a Property Descriptor or undefined) and returns a Boolean. It performs the following steps when called:

  1. ValidateAndApplyPropertyDescriptor(undefined, "", extensible, propertyDesc, current)を返す。

10.1.6.3 ValidateAndApplyPropertyDescriptor ( obj, propertyKey, extensible, propertyDesc, current )

The abstract operation ValidateAndApplyPropertyDescriptor takes arguments obj (an Object or undefined), propertyKey (a property key), extensible (a Boolean), propertyDesc (a Property Descriptor), and current (a Property Descriptor or undefined) and returns a Boolean. これは、invariantsを維持しつつ、指定されたextensibilityおよび現在のproperty currentを持つobjectのpropertyとしてpropertyDescを適用できる場合に限りtrueを返します。そのような適用が可能であり、objundefinedでない場合、propertyKeyという名前のpropertyについてそれが実行されます(必要であれば作成されます)。 It performs the following steps when called:

  1. Assert: propertyKeyproperty keyである。
  2. currentundefinedなら、
    1. extensiblefalseなら、falseを返す。
    2. objundefinedなら、trueを返す。
    3. IsAccessorDescriptor(propertyDesc)がtrueなら、
      1. object objpropertyKeyという名前のown accessor propertyを作成する。その[[Get]][[Set]][[Enumerable]]、および[[Configurable]]属性は、propertyDescが対応するfieldを持つ場合はpropertyDesc内の対応するfieldの値に、そうでない場合はその属性のdefault valueに設定される。
    4. そうでなければ、
      1. object objpropertyKeyという名前のown data propertyを作成する。その[[Value]][[Writable]][[Enumerable]]、および[[Configurable]]属性は、propertyDescが対応するfieldを持つ場合はpropertyDesc内の対応するfieldの値に、そうでない場合はその属性のdefault valueに設定される。
    5. trueを返す。
  3. Assert: currentfully populated Property Descriptorである。
  4. propertyDescがfieldsをまったく持たないなら、trueを返す。
  5. current.[[Configurable]]falseなら、
    1. propertyDesc[[Configurable]] fieldを持ち、propertyDesc.[[Configurable]]trueなら、falseを返す。
    2. propertyDesc[[Enumerable]] fieldを持ち、propertyDesc.[[Enumerable]]current.[[Enumerable]]でないなら、falseを返す。
    3. IsGenericDescriptor(propertyDesc)がfalseであり、かつIsAccessorDescriptor(propertyDesc)がIsAccessorDescriptor(current)でないなら、falseを返す。
    4. IsAccessorDescriptor(current)がtrueなら、
      1. propertyDesc[[Get]] fieldを持ち、SameValue(propertyDesc.[[Get]], current.[[Get]])がfalseなら、falseを返す。
      2. propertyDesc[[Set]] fieldを持ち、SameValue(propertyDesc.[[Set]], current.[[Set]])がfalseなら、falseを返す。
    5. そうでなく、current.[[Writable]]falseなら、
      1. propertyDesc[[Writable]] fieldを持ち、propertyDesc.[[Writable]]trueなら、falseを返す。
      2. NOTE: SameValueNaN valuesに対してtrueを返しますが、それらは他の手段によって区別可能な場合があります。ここで返すことにより、objの既存propertyが変更されないことが保証されます。
      3. propertyDesc[[Value]] fieldを持つなら、SameValue(propertyDesc.[[Value]], current.[[Value]])を返す。
  6. objundefinedでないなら、
    1. IsDataDescriptor(current)がtrueであり、かつIsAccessorDescriptor(propertyDesc)がtrueなら、
      1. propertyDesc[[Configurable]] fieldを持つなら、configurablepropertyDesc.[[Configurable]]とする;そうでなければ、configurablecurrent.[[Configurable]]とする。
      2. propertyDesc[[Enumerable]] fieldを持つなら、enumerablepropertyDesc.[[Enumerable]]とする;そうでなければ、enumerablecurrent.[[Enumerable]]とする。
      3. object objpropertyKeyという名前のpropertyをaccessor propertyで置き換える。その[[Configurable]]および[[Enumerable]]属性はそれぞれconfigurableおよびenumerableに設定され、その[[Get]]および[[Set]]属性は、propertyDescが対応するfieldを持つ場合はpropertyDesc内の対応するfieldの値に、そうでない場合はその属性のdefault valueに設定される。
    2. そうでなく、IsAccessorDescriptor(current)がtrueであり、かつIsDataDescriptor(propertyDesc)がtrueなら、
      1. propertyDesc[[Configurable]] fieldを持つなら、configurablepropertyDesc.[[Configurable]]とする;そうでなければ、configurablecurrent.[[Configurable]]とする。
      2. propertyDesc[[Enumerable]] fieldを持つなら、enumerablepropertyDesc.[[Enumerable]]とする;そうでなければ、enumerablecurrent.[[Enumerable]]とする。
      3. object objpropertyKeyという名前のpropertyをdata propertyで置き換える。その[[Configurable]]および[[Enumerable]]属性はそれぞれconfigurableおよびenumerableに設定され、その[[Value]]および[[Writable]]属性は、propertyDescが対応するfieldを持つ場合はpropertyDesc内の対応するfieldの値に、そうでない場合はその属性のdefault valueに設定される。
    3. そうでなければ、
      1. propertyDescの各field name fieldNameについて、object objpropertyKeyという名前のpropertyのfieldNameという名前の属性を、propertyDescfieldName fieldの値に設定する。
  7. trueを返す。

10.1.7 [[HasProperty]] ( propertyKey )

The [[HasProperty]] internal method of ordinary object obj takes argument propertyKey (a property key) and returns either a normal completion containing a Boolean or a throw completion. It performs the following steps when called:

  1. OrdinaryHasProperty(obj, propertyKey)を返す。

10.1.7.1 OrdinaryHasProperty ( obj, propertyKey )

The abstract operation OrdinaryHasProperty takes arguments obj (an Object) and propertyKey (a property key) and returns either a normal completion containing a Boolean or a throw completion. It performs the following steps when called:

  1. hasOwnを ? obj.[[GetOwnProperty]](propertyKey) とする。
  2. hasOwnundefinedでないなら、trueを返す。
  3. parentを ? obj.[[GetPrototypeOf]]() とする。
  4. parentnullでないなら、
    1. parent.[[HasProperty]](propertyKey)を返す。
  5. falseを返す。

10.1.8 [[Get]] ( propertyKey, receiver )

The [[Get]] internal method of ordinary object obj takes arguments propertyKey (a property key) and receiver (an ECMAScript language value) and returns either a normal completion containing an ECMAScript language value or a throw completion. It performs the following steps when called:

  1. OrdinaryGet(obj, propertyKey, receiver)を返す。

10.1.8.1 OrdinaryGet ( obj, propertyKey, receiver )

The abstract operation OrdinaryGet takes arguments obj (an Object), propertyKey (a property key), and receiver (an ECMAScript language value) and returns either a normal completion containing an ECMAScript language value or a throw completion. It performs the following steps when called:

  1. propertyDescを ? obj.[[GetOwnProperty]](propertyKey) とする。
  2. propertyDescundefinedなら、
    1. parentを ? obj.[[GetPrototypeOf]]() とする。
    2. parentnullなら、undefinedを返す。
    3. parent.[[Get]](propertyKey, receiver)を返す。
  3. IsDataDescriptor(propertyDesc)がtrueなら、propertyDesc.[[Value]]を返す。
  4. Assert: IsAccessorDescriptor(propertyDesc)はtrueである。
  5. getterpropertyDesc.[[Get]]とする。
  6. getterundefinedなら、undefinedを返す。
  7. Call(getter, receiver)を返す。

10.1.9 [[Set]] ( propertyKey, value, receiver )

The [[Set]] internal method of ordinary object obj takes arguments propertyKey (a property key), value (an ECMAScript language value), and receiver (an ECMAScript language value) and returns either a normal completion containing a Boolean or a throw completion. It performs the following steps when called:

  1. OrdinarySet(obj, propertyKey, value, receiver)を返す。

10.1.9.1 OrdinarySet ( obj, propertyKey, value, receiver )

The abstract operation OrdinarySet takes arguments obj (an Object), propertyKey (a property key), value (an ECMAScript language value), and receiver (an ECMAScript language value) and returns either a normal completion containing a Boolean or a throw completion. It performs the following steps when called:

  1. ownDescを ? obj.[[GetOwnProperty]](propertyKey) とする。
  2. OrdinarySetWithOwnDescriptor(obj, propertyKey, value, receiver, ownDesc)を返す。

10.1.9.2 OrdinarySetWithOwnDescriptor ( obj, propertyKey, value, receiver, ownDesc )

The abstract operation OrdinarySetWithOwnDescriptor takes arguments obj (an Object), propertyKey (a property key), value (an ECMAScript language value), receiver (an ECMAScript language value), and ownDesc (a Property Descriptor or undefined) and returns either a normal completion containing a Boolean or a throw completion. It performs the following steps when called:

  1. ownDescundefinedなら、
    1. parentを ? obj.[[GetPrototypeOf]]() とする。
    2. parentnullでないなら、? parent.[[Set]](propertyKey, value, receiver)を返す。
    3. ownDescをPropertyDescriptor { [[Value]]: undefined, [[Writable]]: true, [[Enumerable]]: true, [[Configurable]]: true }に設定する。
  2. IsDataDescriptor(ownDesc)がtrueなら、
    1. ownDesc.[[Writable]]falseなら、falseを返す。
    2. receiverがObjectでないなら、falseを返す。
    3. existingDescを ? receiver.[[GetOwnProperty]](propertyKey) とする。
    4. existingDescundefinedなら、
      1. Assert: receiverは現在property propertyKeyを持たない。
      2. CreateDataProperty(receiver, propertyKey, value)を返す。
    5. IsAccessorDescriptor(existingDesc)がtrueなら、falseを返す。
    6. existingDesc.[[Writable]]falseなら、falseを返す。
    7. valueDescをPropertyDescriptor { [[Value]]: value }とする。
    8. receiver.[[DefineOwnProperty]](propertyKey, valueDesc)を返す。
  3. Assert: IsAccessorDescriptor(ownDesc)はtrueである。
  4. setterownDesc.[[Set]]とする。
  5. setterundefinedなら、falseを返す。
  6. Call(setter, receiver, « value »)を実行する。
  7. trueを返す。

10.1.10 [[Delete]] ( propertyKey )

The [[Delete]] internal method of ordinary object obj takes argument propertyKey (a property key) and returns either a normal completion containing a Boolean or a throw completion. It performs the following steps when called:

  1. OrdinaryDelete(obj, propertyKey)を返す。

10.1.10.1 OrdinaryDelete ( obj, propertyKey )

The abstract operation OrdinaryDelete takes arguments obj (an Object) and propertyKey (a property key) and returns either a normal completion containing a Boolean or a throw completion. It performs the following steps when called:

  1. propertyDescを ? obj.[[GetOwnProperty]](propertyKey) とする。
  2. propertyDescundefinedなら、trueを返す。
  3. propertyDesc.[[Configurable]]trueなら、
    1. objからpropertyKeyという名前のown propertyを削除する。
    2. trueを返す。
  4. falseを返す。

10.1.11 [[OwnPropertyKeys]] ( )

The [[OwnPropertyKeys]] internal method of ordinary object obj takes no arguments and returns a normal completion containing a List of property keys. It performs the following steps when called:

  1. OrdinaryOwnPropertyKeys(obj)を返す。

10.1.11.1 OrdinaryOwnPropertyKeys ( obj )

The abstract operation OrdinaryOwnPropertyKeys takes argument obj (an Object) and returns a List of property keys. It performs the following steps when called:

  1. keysを新しい空のListとする。
  2. array indexであるようなobjの各own property key propertyKeyについて、ascending numeric index orderで、以下を行う
    1. propertyKeykeysへappendする。
  3. Stringであり、array indexでないようなobjの各own property key propertyKeyについて、property creationのascending chronological orderで、以下を行う
    1. propertyKeykeysへappendする。
  4. Symbolであるようなobjの各own property key propertyKeyについて、property creationのascending chronological orderで、以下を行う
    1. propertyKeykeysへappendする。
  5. keysを返す。

10.1.12 OrdinaryObjectCreate ( proto [ , additionalInternalSlotsList ] )

The abstract operation OrdinaryObjectCreate takes argument proto (an Object or null) and optional argument additionalInternalSlotsList (a List of names of internal slots) and returns an Object. これは、新しいordinary objectsのruntime creationを指定するために使用されます。additionalInternalSlotsListは、[[Prototype]]および[[Extensible]]を超えて、objectの一部として定義されなければならない追加internal slotsの名前を含みます。additionalInternalSlotsListが提供されない場合、新しい空のListが使用されます。 It performs the following steps when called:

  1. internalSlotsListを« [[Prototype]], [[Extensible]] »とする。
  2. additionalInternalSlotsListが存在するなら、internalSlotsListinternalSlotsListadditionalInternalSlotsListlist-concatenationに設定する。
  3. objMakeBasicObject(internalSlotsList)とする。
  4. obj.[[Prototype]]protoに設定する。
  5. objを返す。
Note

OrdinaryObjectCreateはMakeBasicObjectを呼び出す以上のことはほとんどしませんが、その使用はordinary objectを作成する意図を伝え、exotic objectを作成する意図ではないことを伝えます。したがって、この仕様内では、その結果がnon-ordinaryになるような方法でobjectのinternal methodsを後で変更するalgorithmからは呼び出されません。exotic objectsを作成するoperationsはMakeBasicObjectを直接invokeします。

10.1.13 OrdinaryCreateFromConstructor ( ctor, intrinsicDefaultProto [ , internalSlotsList ] )

The abstract operation OrdinaryCreateFromConstructor takes arguments ctor (a function object) and intrinsicDefaultProto (a String) and optional argument internalSlotsList (a List of names of internal slots) and returns either a normal completion containing an Object or a throw completion. これは、存在する場合にはconstructor"prototype" propertyから[[Prototype]]値を取得したordinary objectを作成します。そうでない場合、intrinsicDefaultProtoによって名付けられたintrinsicが[[Prototype]]に使用されます。internalSlotsListは、objectの一部として定義されなければならない追加internal slotsの名前を含みます。internalSlotsListが提供されない場合、新しい空のListが使用されます。 It performs the following steps when called:

  1. Assert: intrinsicDefaultProtoはこの仕様におけるintrinsic objectの名前である。対応するobjectは、objectの[[Prototype]]値として使用されることを意図したintrinsicでなければならない。
  2. protoを ? GetPrototypeFromConstructor(ctor, intrinsicDefaultProto) とする。
  3. internalSlotsListが存在するなら、slotsinternalSlotsListとする。
  4. そうでなければ、slotsを新しい空のListとする。
  5. OrdinaryObjectCreate(proto, slots)を返す。

10.1.14 GetPrototypeFromConstructor ( ctor, intrinsicDefaultProto )

The abstract operation GetPrototypeFromConstructor takes arguments ctor (a function object) and intrinsicDefaultProto (a String) and returns either a normal completion containing an Object or a throw completion. これは、特定のconstructorに対応するobjectを作成するために使用すべき[[Prototype]]値を決定します。その値は、存在する場合にはconstructor"prototype" propertyから取得されます。そうでない場合、intrinsicDefaultProtoによって名付けられたintrinsicが[[Prototype]]に使用されます。 It performs the following steps when called:

  1. Assert: intrinsicDefaultProtoはこの仕様におけるintrinsic objectの名前である。対応するobjectは、objectの[[Prototype]]値として使用されることを意図したintrinsicでなければならない。
  2. protoを ? Get(ctor, "prototype") とする。
  3. protoがObjectでないなら、
    1. realmを ? GetFunctionRealm(ctor) とする。
    2. protointrinsicDefaultProtoという名前のrealmのintrinsic objectに設定する。
  4. protoを返す。
Note

ctor[[Prototype]]値を供給しない場合、使用されるdefault valueはrunning execution contextからではなく、ctor functionのrealmから取得されます。

10.1.15 RequireInternalSlot ( obj, internalSlot )

The abstract operation RequireInternalSlot takes arguments obj (an ECMAScript language value) and internalSlot (an internal slot name) and returns either a normal completion containing unused or a throw completion. これは、objがObjectであり、指定されたinternal slotを持つ場合を除き、例外をthrowします。 It performs the following steps when called:

  1. objがObjectでないなら、TypeError例外をthrowする。
  2. objinternalSlot internal slotを持たないなら、TypeError例外をthrowする。
  3. unusedを返す。

10.2 ECMAScript関数オブジェクト

ECMAScript function objectsは、lexical environmentで閉じ込められたparameterized ECMAScript codeをカプセル化し、そのコードの動的評価をサポートします。ECMAScript function objectordinary objectであり、他のordinary objectsと同じinternal slotsおよび同じinternal methodsを持ちます。ECMAScript function objectのコードは、strict mode code11.2.2)またはnon-strict codeのいずれかであり得ます。コードがstrict mode codeであるECMAScript function objectstrict functionと呼ばれます。コードがstrict mode codeでないものはnon-strict functionと呼ばれます。

[[Extensible]]および[[Prototype]]に加えて、ECMAScript function objectsTable 26に列挙されるinternal slotsも持ちます。

Table 26: Internal Slots of ECMAScript Function Objects
Internal Slot 説明
[[Environment]] Environment Record functionがclosed overされたEnvironment Record。functionのコードを評価するときにouter environmentとして使用されます。
[[PrivateEnvironment]] PrivateEnvironment Recordまたはnull functionがclosed overされたPrivate NamesのためのPrivateEnvironment Record。このfunctionが構文上class内に含まれていない場合はnull。functionのコードを評価するとき、inner classesのouter PrivateEnvironmentとして使用されます。
[[FormalParameters]] Parse Node functionのformal parameter listを定義するsource textのroot parse node。
[[ECMAScriptCode]] Parse Node functionのbodyを定義するsource textのroot parse node。
[[ConstructorKind]] baseまたはderived functionがderived class constructorであるかどうか。
[[Realm]] Realm Record functionが作成されたrealmであり、functionの評価時にアクセスされる任意のintrinsic objectsを提供するもの。
[[ScriptOrModule]] Script RecordまたはModule Record functionが作成されたscriptまたはmodule。
[[ThisMode]] lexical, strict, or global functionのformal parametersおよびcode body内でthis参照がどのように解釈されるかを定義します。lexicalは、thisが字句的に囲むfunctionのthis値を参照することを意味します。strictは、functionの呼び出しによって提供されたthis値がそのまま使用されることを意味します。globalは、undefinedまたはnullthis値がglobal objectへの参照として解釈され、その他のthis値はまずToObjectに渡されることを意味します。
[[Strict]] Boolean これがstrict functionである場合はtruenon-strict functionである場合はfalse
[[HomeObject]] Objectまたはundefined functionがsuperを使用する場合、これは、その[[GetPrototypeOf]]super property lookupsを開始するobjectを提供するobjectです。
[[SourceText]] Unicode code pointsのsequence functionを定義するsource text
[[Fields]] ClassFieldDefinition RecordsList functionがclassである場合、これはclassのnon-static fieldsおよび対応するinitializersを表すRecordsのlistです。
[[PrivateMethods]] PrivateElementsList functionがclassである場合、これはclassのnon-static private methodsおよびaccessorsを表すlistです。
[[ClassFieldInitializerName]] String、Symbol、Private Name、またはempty functionがclass fieldのinitializerとして作成された場合、そのfieldのNamedEvaluationに使用する名前;それ以外の場合はempty
[[IsClassConstructor]] Boolean functionがclass constructorであるかどうかを示します。(trueの場合、functionの[[Call]]を呼び出すと直ちにTypeError例外がthrowされます。)

すべてのECMAScript function objectsは、ここで定義される[[Call]] internal methodを持ちます。constructorでもあるECMAScript functionsは、さらに[[Construct]] internal methodを持ちます。

10.2.1 [[Call]] ( thisArg, argList )

The [[Call]] internal method of ECMAScript function object func takes arguments thisArg (an ECMAScript language value) and argList (a List of ECMAScript language values) and returns either a normal completion containing an ECMAScript language value or a throw completion. It performs the following steps when called:

  1. callerContextrunning execution contextとする。
  2. calleeContextPrepareForOrdinaryCall(func, undefined)とする。
  3. Assert: calleeContextは現在running execution contextである。
  4. func.[[IsClassConstructor]]trueなら、
    1. errorを新しく作成されたTypeError objectとする。
    2. NOTE: errorは、funcに関連付けられたRealm Recordを伴うcalleeContext内で作成される。
    3. calleeContextexecution context stackから削除し、callerContextrunning execution contextとして復元する。
    4. errorをthrowする。
  5. OrdinaryCallBindThis(func, calleeContext, thisArg)を実行する。
  6. resultCompletion(OrdinaryCallEvaluateBody(func, argList))とする。
  7. calleeContextexecution context stackから削除し、callerContextrunning execution contextとして復元する。
  8. resultreturn completionなら、result.[[Value]]を返す。
  9. Assert: resultthrow completionである。
  10. resultを返す。
Note

ステップ7calleeContextexecution context stackから削除されるとき、それがsuspendedであり、accessible Generatorによる後続のresumptionのために保持されている場合、破棄してはなりません。

10.2.1.1 PrepareForOrdinaryCall ( func, newTarget )

The abstract operation PrepareForOrdinaryCall takes arguments func (an ECMAScript function object) and newTarget (an Object or undefined) and returns an execution context. It performs the following steps when called:

  1. callerContextrunning execution contextとする。
  2. calleeContextを新しいECMAScript code execution contextとする。
  3. calleeContextのFunctionをfuncに設定する。
  4. calleeRealmfunc.[[Realm]]とする。
  5. calleeContextRealmcalleeRealmに設定する。
  6. calleeContextのScriptOrModuleをfunc.[[ScriptOrModule]]に設定する。
  7. localEnvNewFunctionEnvironment(func, newTarget)とする。
  8. calleeContextのLexicalEnvironmentをlocalEnvに設定する。
  9. calleeContextのVariableEnvironmentをlocalEnvに設定する。
  10. calleeContextのPrivateEnvironmentをfunc.[[PrivateEnvironment]]に設定する。
  11. callerContextがまだsuspendedでないなら、callerContextをsuspendする。
  12. calleeContextexecution context stackへpushする;calleeContextは現在running execution contextである。
  13. NOTE: この時点以降に生成される任意のexception objectsはcalleeRealmに関連付けられる。
  14. calleeContextを返す。

10.2.1.2 OrdinaryCallBindThis ( func, calleeContext, thisArg )

The abstract operation OrdinaryCallBindThis takes arguments func (an ECMAScript function object), calleeContext (an execution context), and thisArg (an ECMAScript language value) and returns unused. It performs the following steps when called:

  1. thisModefunc.[[ThisMode]]とする。
  2. thisModelexicalなら、unusedを返す。
  3. calleeRealmfunc.[[Realm]]とする。
  4. localEnvcalleeContextのLexicalEnvironmentとする。
  5. thisModestrictなら、
    1. thisValuethisArgとする。
  6. そうでなければ、
    1. thisArgundefinedまたはnullのいずれかなら、
      1. globalEnvcalleeRealm.[[GlobalEnv]]とする。
      2. Assert: globalEnvGlobal Environment Recordである。
      3. thisValueglobalEnv.[[GlobalThisValue]]とする。
    2. そうでなければ、
      1. thisValueを ! ToObject(thisArg) とする。
      2. NOTE: ToObjectcalleeRealmを使用してwrapper objectsを生成する。
  7. Assert: localEnvFunction Environment Recordである。
  8. Assert: 次のstepはabrupt completionを返すことはない。なぜならlocalEnv.[[ThisBindingStatus]]initializedでないからである。
  9. BindThisValue(localEnv, thisValue)を実行する。
  10. unusedを返す。

10.2.1.3 Runtime Semantics: EvaluateBody

The syntax-directed operation EvaluateBody takes arguments func (an ECMAScript function object) and argList (a List of ECMAScript language values) and returns a return completion or a throw completion. It is defined piecewise over the following productions:

FunctionBody : FunctionStatementList
  1. 引数funcおよびargListを伴うFunctionBodyEvaluateFunctionBodyを ? で返す。
ConciseBody : ExpressionBody
  1. 引数funcおよびargListを伴うConciseBodyEvaluateConciseBodyを ? で返す。
GeneratorBody : FunctionBody
  1. 引数funcおよびargListを伴うGeneratorBodyEvaluateGeneratorBodyを ? で返す。
AsyncGeneratorBody : FunctionBody
  1. 引数funcおよびargListを伴うAsyncGeneratorBodyEvaluateAsyncGeneratorBodyを ? で返す。
AsyncFunctionBody : FunctionBody
  1. 引数funcおよびargListを伴うAsyncFunctionBodyEvaluateAsyncFunctionBodyを ? で返す。
AsyncConciseBody : ExpressionBody
  1. 引数funcおよびargListを伴うAsyncConciseBodyEvaluateAsyncConciseBodyを ? で返す。
Initializer : = AssignmentExpression
  1. Assert: argListは空である。
  2. Assert: func.[[ClassFieldInitializerName]]emptyでない。
  3. IsAnonymousFunctionDefinition(AssignmentExpression)がtrueなら、
    1. valueを、引数func.[[ClassFieldInitializerName]]を伴うInitializerNamedEvaluationの ? 結果とする。
  4. そうでなければ、
    1. rhsAssignmentExpressionEvaluationの ? 結果とする。
    2. valueを ? GetValue(rhs) とする。
  5. ReturnCompletion(value)を返す。
Note

field initializersはfunction boundaryを構成しますが、FunctionDeclarationInstantiationの呼び出しには観測可能な効果がないため省略されます。

ClassStaticBlockBody : ClassStaticBlockStatementList
  1. Assert: argListは空である。
  2. 引数funcを伴うClassStaticBlockBodyEvaluateClassStaticBlockBodyを ? で返す。

10.2.1.4 OrdinaryCallEvaluateBody ( func, argList )

The abstract operation OrdinaryCallEvaluateBody takes arguments func (an ECMAScript function object) and argList (a List of ECMAScript language values) and returns a return completion or a throw completion. It performs the following steps when called:

  1. 引数funcおよびargListを伴うfunc.[[ECMAScriptCode]]EvaluateBodyを ? で返す。

10.2.2 [[Construct]] ( argList, newTarget )

The [[Construct]] internal method of ECMAScript function object func takes arguments argList (a List of ECMAScript language values) and newTarget (a constructor) and returns either a normal completion containing an Object or a throw completion. It performs the following steps when called:

  1. callerContextrunning execution contextとする。
  2. kindfunc.[[ConstructorKind]]とする。
  3. kindbaseなら、
    1. thisArgを ? OrdinaryCreateFromConstructor(newTarget, "%Object.prototype%") とする。
  4. calleeContextPrepareForOrdinaryCall(func, newTarget)とする。
  5. Assert: calleeContextは現在running execution contextである。
  6. kindbaseなら、
    1. OrdinaryCallBindThis(func, calleeContext, thisArg)を実行する。
    2. initializeResultCompletion(InitializeInstanceElements(thisArg, func))とする。
    3. initializeResultabrupt completionなら、
      1. calleeContextexecution context stackから削除し、callerContextrunning execution contextとして復元する。
      2. initializeResultを返す。
  7. ctorEnvcalleeContextのLexicalEnvironmentとする。
  8. resultCompletion(OrdinaryCallEvaluateBody(func, argList))とする。
  9. calleeContextexecution context stackから削除し、callerContextrunning execution contextとして復元する。
  10. resultthrow completionなら、
    1. resultを返す。
  11. Assert: resultreturn completionである。
  12. result.[[Value]]がObjectなら、result.[[Value]]を返す。
  13. kindbaseなら、thisArgを返す。
  14. result.[[Value]]undefinedでないなら、TypeError例外をthrowする。
  15. thisBindingを ? ctorEnv.GetThisBinding() とする。
  16. Assert: thisBindingはObjectである。
  17. thisBindingを返す。

10.2.3 OrdinaryFunctionCreate ( proto, sourceText, paramList, body, thisMode, envRecord, privateEnv )

The abstract operation OrdinaryFunctionCreate takes arguments proto (an Object), sourceText (a sequence of Unicode code points), paramList (a Parse Node), body (a Parse Node), thisMode (lexical-this or non-lexical-this), envRecord (an Environment Record), and privateEnv (a PrivateEnvironment Record or null) and returns an ECMAScript function object. これは、デフォルトの[[Call]] internal methodを持ち、[[Construct]] internal methodを持たない新しいfunctionのruntime creationを指定するために使用されます(ただし、後でMakeConstructorなどのoperationによって追加される場合があります)。sourceTextは、作成されるfunctionのsyntactic definitionのsource textです。 It performs the following steps when called:

  1. internalSlotsListTable 26に列挙されるinternal slotsとする。
  2. funcOrdinaryObjectCreate(proto, internalSlotsList)とする。
  3. func.[[Call]]10.2.1で指定される定義に設定する。
  4. func.[[SourceText]]sourceTextに設定する。
  5. func.[[FormalParameters]]paramListに設定する。
  6. func.[[ECMAScriptCode]]bodyに設定する。
  7. strictIsStrict(body)とする。
  8. func.[[Strict]]strictに設定する。
  9. thisModelexical-thisなら、func.[[ThisMode]]lexicalに設定する。
  10. そうでなく、stricttrueなら、func.[[ThisMode]]strictに設定する。
  11. そうでなければ、func.[[ThisMode]]globalに設定する。
  12. func.[[IsClassConstructor]]falseに設定する。
  13. func.[[Environment]]envRecordに設定する。
  14. func.[[PrivateEnvironment]]privateEnvに設定する。
  15. func.[[ScriptOrModule]]GetActiveScriptOrModule()に設定する。
  16. func.[[Realm]]current Realm Recordに設定する。
  17. func.[[HomeObject]]undefinedに設定する。
  18. func.[[Fields]]を新しい空のListに設定する。
  19. func.[[PrivateMethods]]を新しい空のListに設定する。
  20. func.[[ClassFieldInitializerName]]emptyに設定する。
  21. lengthparamListExpectedArgumentCountとする。
  22. SetFunctionLength(func, length)を実行する。
  23. funcを返す。

10.2.4 AddRestrictedFunctionProperties ( func, realm )

The abstract operation AddRestrictedFunctionProperties takes arguments func (a function object) and realm (a Realm Record) and returns unused. It performs the following steps when called:

  1. Assert: realm.[[Intrinsics]].[[%ThrowTypeError%]]は存在し、初期化済みである。
  2. throwerrealm.[[Intrinsics]].[[%ThrowTypeError%]]とする。
  3. DefinePropertyOrThrow(func, "caller", PropertyDescriptor { [[Get]]: thrower, [[Set]]: thrower, [[Enumerable]]: false, [[Configurable]]: true })を実行する。
  4. DefinePropertyOrThrow(func, "arguments", PropertyDescriptor { [[Get]]: thrower, [[Set]]: thrower, [[Enumerable]]: false, [[Configurable]]: true })を実行する。
  5. unusedを返す。

10.2.4.1 %ThrowTypeError% ( )

このfunctionは%ThrowTypeError% intrinsic objectです。

これは、realmごとに1回定義されるanonymous built-in function objectです。

呼び出されたとき、次のstepsを実行します:

  1. TypeError例外をthrowする。

このfunctionの[[Extensible]] internal slotの値はfalseです。

このfunctionの"length" propertyは、attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }を持ちます。

このfunctionの"name" propertyは、attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }を持ちます。

10.2.5 MakeConstructor ( func [ , writableProto [ , proto ] ] )

The abstract operation MakeConstructor takes argument func (an ECMAScript function object or a built-in function object) and optional arguments writableProto (a Boolean) and proto (an Object) and returns unused. これはfuncconstructorへ変換します。 It performs the following steps when called:

  1. funcがECMAScript function objectなら、
    1. Assert: IsConstructor(func)はfalseである。
    2. Assert: funcはextensible objectであり、"prototype" own propertyを持たない。
    3. func.[[Construct]]10.2.2で指定される定義に設定する。
  2. そうでなければ、
    1. func.[[Construct]]10.3.2で指定される定義に設定する。
  3. func.[[ConstructorKind]]baseに設定する。
  4. writableProtoが存在しないなら、writablePrototrueに設定する。
  5. protoが存在しないなら、
    1. protoOrdinaryObjectCreate(%Object.prototype%)に設定する。
    2. DefinePropertyOrThrow(proto, "constructor", PropertyDescriptor { [[Value]]: func, [[Writable]]: writableProto, [[Enumerable]]: false, [[Configurable]]: true })を実行する。
  6. DefinePropertyOrThrow(func, "prototype", PropertyDescriptor { [[Value]]: proto, [[Writable]]: writableProto, [[Enumerable]]: false, [[Configurable]]: false })を実行する。
  7. unusedを返す。

10.2.6 MakeClassConstructor ( func )

The abstract operation MakeClassConstructor takes argument func (an ECMAScript function object) and returns unused. It performs the following steps when called:

  1. Assert: func.[[IsClassConstructor]]falseである。
  2. func.[[IsClassConstructor]]trueに設定する。
  3. unusedを返す。

10.2.7 MakeMethod ( func, homeObj )

The abstract operation MakeMethod takes arguments func (an ECMAScript function object) and homeObj (an Object) and returns unused. これはfuncをmethodとしてconfigureします。 It performs the following steps when called:

  1. Assert: homeObjordinary objectである。
  2. func.[[HomeObject]]homeObjに設定する。
  3. unusedを返す。

10.2.8 DefineMethodProperty ( homeObj, name, closure, enumerable )

The abstract operation DefineMethodProperty takes arguments homeObj (an Object), name (a property key or Private Name), closure (a function object), and enumerable (a Boolean) and returns either a normal completion containing either a PrivateElement or unused, or an abrupt completion. It performs the following steps when called:

  1. Assert: homeObjはordinaryかつextensible objectである。
  2. namePrivate Nameなら、PrivateElement { [[Key]]: name, [[Kind]]: method, [[Value]]: closure }を返す。
  3. propertyDescをPropertyDescriptor { [[Value]]: closure, [[Writable]]: true, [[Enumerable]]: enumerable, [[Configurable]]: true }とする。
  4. DefinePropertyOrThrow(homeObj, name, propertyDesc)を実行する。
  5. NOTE: DefinePropertyOrThrowabrupt completionを返すのは、name"prototype"であるclass static methodを定義しようとする場合だけである。
  6. unusedを返す。

10.2.9 SetFunctionName ( func, name [ , prefix ] )

The abstract operation SetFunctionName takes arguments func (a function object) and name (a property key or Private Name) and optional argument prefix (a String) and returns unused. これはfunc"name" propertyを追加します。 It performs the following steps when called:

  1. Assert: funcはextensible objectであり、"name" own propertyを持たない。
  2. nameがSymbolなら、
    1. descriptionname.[[Description]]とする。
    2. descriptionundefinedなら、nameを空のStringに設定する。
    3. そうでなければ、name"["description、および"]"string-concatenationに設定する。
  3. そうでなく、namePrivate Nameなら、
    1. namename.[[Description]]に設定する。
  4. func[[InitialName]] internal slotを持つなら、
    1. func.[[InitialName]]nameに設定する。
  5. prefixが存在するなら、
    1. prefixedNameを、prefix、code unit 0x0020 (SPACE)、およびnamestring-concatenationとする。
    2. func[[InitialName]] internal slotを持つなら、
      1. NOTE: 次のstepの選択は、このAbstract Operationが呼び出されるたびに独立して行われる。
      2. func.[[InitialName]]nameまたはprefixedNameのいずれかのimplementation-defined choiceに設定する。
    3. nameprefixedNameに設定する。
  6. DefinePropertyOrThrow(func, "name", PropertyDescriptor { [[Value]]: name, [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true })を実行する。
  7. unusedを返す。

10.2.10 SetFunctionLength ( func, length )

The abstract operation SetFunctionLength takes arguments func (a function object) and length (a non-negative integer or +∞) and returns unused. これはfunc"length" propertyを追加します。 It performs the following steps when called:

  1. Assert: funcはextensible objectであり、"length" own propertyを持たない。
  2. DefinePropertyOrThrow(func, "length", PropertyDescriptor { [[Value]]: 𝔽(length), [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true })を実行する。
  3. unusedを返す。

10.2.11 FunctionDeclarationInstantiation ( func, argList )

The abstract operation FunctionDeclarationInstantiation takes arguments func (an ECMAScript function object) and argList (a List of ECMAScript language values) and returns either a normal completion containing unused or a throw completion. funcは、execution contextが確立されている対象のfunction objectです。

Note

ECMAScript functionを評価するためにexecution contextが確立されると、新しいFunction Environment Recordが作成され、そのEnvironment Record内に各formal parameterのbindingsがinstantiateされます。function body内の各declarationもinstantiateされます。functionのformal parametersがdefault value initializersを含まない場合、body declarationsはparametersと同じEnvironment Record内でinstantiateされます。default value parameter initializersが存在する場合、body declarationsのために2番目のEnvironment Recordが作成されます。Formal parametersおよびfunctionsはFunctionDeclarationInstantiationの一部として初期化されます。他のすべてのbindingsはfunction bodyの評価中に初期化されます。

呼び出されたとき、次のstepsを実行します:

  1. 実行中の実行コンテキストをcalleeContextとする。
  2. func.[[ECMAScriptCode]]codeとする。
  3. func.[[Strict]]strictとする。
  4. func.[[FormalParameters]]formalsとする。
  5. formalsBoundNamesparamNamesとする。
  6. paramNamesに重複するエントリがある場合、hasDuplicatestrueとする。そうでなければ、hasDuplicatesfalseとする。
  7. formalsIsSimpleParameterListsimpleParamListとする。
  8. formalsContainsExpressionhasParamExprsとする。
  9. codeVarDeclaredNamesvariableNamesとする。
  10. codeVarScopedDeclarationsvariableDeclsとする。
  11. codeLexicallyDeclaredNameslexicalNamesとする。
  12. funcNamesを新しい空のListとする。
  13. funcsToInitializeを新しい空のListとする。
  14. variableDeclsの各要素variableDeclについて、Listの逆順で、次を行う。
    1. variableDeclVariableDeclarationForBindingBindingIdentifierのいずれでもない場合、
      1. Assert: variableDeclは、FunctionDeclarationGeneratorDeclarationAsyncFunctionDeclaration、またはAsyncGeneratorDeclarationのいずれかである。
      2. variableDeclBoundNamesの唯一の要素をfuncNameとする。
      3. funcNamesfuncNameを含まない場合、
        1. funcNamefuncNamesの最初の要素として挿入する。
        2. NOTE: 同じ名前に対して複数の関数宣言がある場合、最後の宣言が使用される。
        3. variableDeclfuncsToInitializeの最初の要素として挿入する。
  15. argumentsObjNeededtrueとする。
  16. func.[[ThisMode]]lexicalである場合、
    1. NOTE: アロー関数はargumentsオブジェクトを持たない。
    2. argumentsObjNeededfalseに設定する。
  17. そうでなく、paramNames"arguments"を含む場合、
    1. argumentsObjNeededfalseに設定する。
  18. そうでなく、hasParamExprsfalseである場合、
    1. funcNames"arguments"を含む、またはlexicalNames"arguments"を含む場合、
      1. argumentsObjNeededfalseに設定する。
  19. stricttrueである、またはhasParamExprsfalseである場合、
    1. NOTE: パラメータには単一のEnvironment Recordだけが必要である。これは、strict modeコード内のevalへの呼び出しが、evalの外側で可視となる新しい束縛を作成できないためである。
    2. calleeContextのLexicalEnvironmentをenvRecordとする。
  20. そうでなければ、
    1. NOTE: 仮引数リスト内のdirect eval呼び出しによって作成された束縛が、パラメータが宣言される環境の外側にあることを保証するため、別個のEnvironment Recordが必要である。
    2. calleeContextのLexicalEnvironmentをcalleeEnvとする。
    3. NewDeclarativeEnvironment(calleeEnv)をenvRecordとする。
    4. Assert: calleeContextのVariableEnvironmentとcalleeEnvは同じEnvironment Recordである。
    5. calleeContextのLexicalEnvironmentをenvRecordに設定する。
  21. paramNamesの各String paramNameについて、次を行う。
    1. envRecord.HasBinding(paramName)をalreadyDeclaredとする。
    2. NOTE: Early errorにより、重複するパラメータ名は、パラメータ既定値またはrestパラメータを持たない非strict関数でのみ発生できることが保証される。
    3. alreadyDeclaredfalseである場合、
      1. envRecord.CreateMutableBinding(paramName, false)を実行する。
      2. hasDuplicatestrueである場合、
        1. envRecord.InitializeBinding(paramName, undefined)を実行する。
  22. argumentsObjNeededtrueである場合、
    1. stricttrueである、またはsimpleParamListfalseである場合、
      1. CreateUnmappedArgumentsObject(argList)をargumentsObjとする。
    2. そうでなければ、
      1. NOTE: マップされたargumentsオブジェクトは、restパラメータ、パラメータ既定値初期化子、または分割代入パラメータを持たない非strict関数に対してのみ提供される。
      2. CreateMappedArgumentsObject(func, formals, argList, envRecord)をargumentsObjとする。
    3. stricttrueである場合、
      1. envRecord.CreateImmutableBinding("arguments", false)を実行する。
      2. NOTE: strict modeコードでは、この束縛に代入しようとすることがEarly errorによって防止されるため、その可変性は観測できない。
    4. そうでなければ、
      1. envRecord.CreateMutableBinding("arguments", false)を実行する。
    5. envRecord.InitializeBinding("arguments", argumentsObj)を実行する。
    6. paramNamesと« "arguments" »のlist-concatenationparamBindingsとする。
  23. そうでなければ、
    1. paramNamesparamBindingsとする。
  24. CreateListIteratorRecord(argList)をiteratorRecordとする。
  25. hasDuplicatestrueである場合、
    1. usedEnvundefinedとする。
  26. そうでなければ、
    1. envRecordusedEnvとする。
  27. NOTE: 次のステップはReturnCompletionを返すことができない。これは、式位置でそのようなcompletionが発生する唯一の方法はYieldExpressionの使用によるものであり、これは15.5.1および15.6.1のEarly Error規則により、パラメータリストでは禁止されているためである。
  28. iteratorRecordおよびusedEnvを引数として、formalsIteratorBindingInitializationを実行する。
  29. hasParamExprsfalseである場合、
    1. NOTE: パラメータとトップレベルのvarには単一のEnvironment Recordだけが必要である。
    2. List paramBindingsのコピーをinstantiatedVariableNamesとする。
    3. variableNamesの各要素nameについて、次を行う。
      1. instantiatedVariableNamesnameを含まない場合、
        1. nameinstantiatedVariableNamesに追加する。
        2. envRecord.CreateMutableBinding(name, false)を実行する。
        3. envRecord.InitializeBinding(name, undefined)を実行する。
    4. envRecordvariableEnvとする。
  30. そうでなければ、
    1. NOTE: 仮引数リスト内の式によって作成されたクロージャが、関数本体内の宣言を可視にしないことを保証するため、別個のEnvironment Recordが必要である。
    2. NewDeclarativeEnvironment(envRecord)をvariableEnvとする。
    3. calleeContextのVariableEnvironmentをvariableEnvに設定する。
    4. instantiatedVariableNamesを新しい空のListとする。
    5. variableNamesの各要素nameについて、次を行う。
      1. instantiatedVariableNamesnameを含まない場合、
        1. nameinstantiatedVariableNamesに追加する。
        2. variableEnv.CreateMutableBinding(name, false)を実行する。
        3. paramBindingsnameを含まない、またはfuncNamesnameを含む場合、
          1. initialValueundefinedとする。
        4. そうでなければ、
          1. envRecord.GetBindingValue(name, false)をinitialValueとする。
        5. variableEnv.InitializeBinding(name, initialValue)を実行する。
        6. NOTE: 仮引数と同じ名前を持つvarは、最初は対応する初期化済みパラメータと同じ値を持つ。
  31. stricttrueである場合、
    1. variableEnvlexicalEnvとする。
  32. そうでなければ、
    1. ホストがWebブラウザである、またはその他の形でBlock-Level Function Declarations Web Legacy Compatibility Semanticsをサポートする場合、
      1. code Contains xtrueであるような任意のBlockCaseClause、またはDefaultClause xStatementListに直接含まれる各FunctionDeclaration funcDeclについて、次を行う。
        1. funcDeclBindingIdentifierStringValuefuncNameとする。
        2. FunctionDeclaration funcDeclを、funcNameBindingIdentifierとして持つVariableStatementに置き換えても、funcに対してEarly Errorsが発生せず、かつparamNamesfuncNameを含まない場合、
          1. NOTE: funcNameに対するvar束縛は、それがVarDeclaredName、仮引数の名前、または別のFunctionDeclarationのいずれでもない場合にのみ、ここでインスタンス化される。
          2. instantiatedVariableNamesfuncNameを含まず、かつfuncName"arguments"でない場合、
            1. variableEnv.CreateMutableBinding(funcName, false)を実行する。
            2. variableEnv.InitializeBinding(funcName, undefined)を実行する。
            3. funcNameinstantiatedVariableNamesに追加する。
          3. FunctionDeclaration funcDeclが評価されるとき、15.2.6で提供されるFunctionDeclaration Evaluationアルゴリズムの代わりに、次のステップを実行する。
            1. 実行中の実行コンテキストのVariableEnvironmentをfuncEnvとする。
            2. 実行中の実行コンテキストのLexicalEnvironmentをblockEnvとする。
            3. blockEnv.GetBindingValue(funcName, false)をfuncObjとする。
            4. funcEnv.SetMutableBinding(funcName, funcObj, false)を実行する。
            5. unusedを返す。
    2. NewDeclarativeEnvironment(variableEnv)をlexicalEnvとする。
    3. NOTE: 非strict関数は、トップレベルのlexical宣言に別個のEnvironment Recordを使用する。これにより、direct evalは、evalコードによって導入されたvar scoped宣言が、既存のトップレベルのlexically scoped宣言と競合するかどうかを判断できる。strict関数では、strict direct evalが常にすべての宣言を新しいEnvironment Recordに配置するため、これは不要である。
  33. calleeContextのLexicalEnvironmentをlexicalEnvに設定する。
  34. codeLexicallyScopedDeclarationslexicalDeclsとする。
  35. lexicalDeclsの各要素lexicalDeclについて、次を行う。
    1. NOTE: lexically declared nameは、関数/ジェネレータ宣言、仮引数、またはvar名と同じにすることはできない。Lexically declared nameはここでインスタンス化されるだけで、初期化はされない。
    2. lexicalDeclBoundNamesの各要素nameについて、次を行う。
      1. lexicalDeclIsConstantDeclarationtrueである場合、
        1. lexicalEnv.CreateImmutableBinding(name, true)を実行する。
      2. そうでなければ、
        1. lexicalEnv.CreateMutableBinding(name, false)を実行する。
  36. calleeContextのPrivateEnvironmentをprivateEnvとする。
  37. funcsToInitializeの各Parse Node funcDeclについて、次を行う。
    1. funcDeclBoundNamesの唯一の要素をfuncNameとする。
    2. lexicalEnvおよびprivateEnvを引数として、funcDeclInstantiateFunctionObjectfuncObjとする。
    3. variableEnv.SetMutableBinding(funcName, funcObj, false)を実行する。
  38. unusedを返す。

10.3 Built-in Function Objects

built-in function objectordinary objectです;10.1に定められたordinary objectsの要件を満たさなければなりません。

すべてのordinary objectに要求されるinternal slots(10.1を参照)に加えて、built-in function objectは次のinternal slotsも持たなければなりません:

  • [[Realm]]。functionが作成されたrealmを表すRealm Record
  • [[InitialName]]。functionの初期名であるString。20.2.3.5によって使用されます。
  • [[Async]]。そのfunctionがBuiltinCallOrConstructにおいてasync function callおよびconstruct behaviourを持つかどうかを示すBoolean。

built-in function object[[Prototype]] internal slotの初期値は、別途指定されない限り%Function.prototype%です。

built-in function objectは、10.3.1の定義に適合する[[Call]] internal methodを持たなければなりません。

built-in function objectは、それが“constructor”として記述されている場合、またはこの仕様内の何らかのalgorithmが明示的にその[[Construct]] internal methodを設定する場合に限り、[[Construct]] internal methodを持ちます。そのような[[Construct]] internal methodは、10.3.2の定義に適合しなければなりません。

実装は、この仕様で定義されていない追加のbuilt-in function objectsを提供してよいです。

10.3.1 [[Call]] ( thisArg, argList )

The [[Call]] internal method of built-in function object func takes arguments thisArg (an ECMAScript language value) and argList (a List of ECMAScript language values) and returns either a normal completion containing an ECMAScript language value or a throw completion. It performs the following steps when called:

  1. BuiltinCallOrConstruct(func, thisArg, argList, undefined)を返す。

10.3.2 [[Construct]] ( argList, newTarget )

The [[Construct]] internal method of built-in function object func(methodが存在する場合) takes arguments argList (a List of ECMAScript language values) and newTarget (a constructor) and returns either a normal completion containing an Object or a throw completion. It performs the following steps when called:

  1. resultを ? BuiltinCallOrConstruct(func, uninitialized, argList, newTarget) とする。
  2. Assert: resultはObjectである。
  3. resultを返す。

10.3.3 BuiltinCallOrConstruct ( func, thisArg, argList, newTarget )

The abstract operation BuiltinCallOrConstruct takes arguments func (a built-in function object), thisArg (an ECMAScript language value or uninitialized), argList (a List of ECMAScript language values), and newTarget (a constructor or undefined) and returns either a normal completion containing an ECMAScript language value or a throw completion. It performs the following steps when called:

  1. callerContextrunning execution contextとする。
  2. callerContextがまだsuspendedでないなら、callerContextをsuspendする。
  3. calleeContextを新しいexecution contextとする。
  4. calleeContextのFunctionをfuncに設定する。
  5. calleeRealmfunc.[[Realm]]とする。
  6. calleeContextRealmcalleeRealmに設定する。
  7. calleeContextのScriptOrModuleをnullに設定する。
  8. calleeContextの任意の必要なimplementation-defined initializationを実行する。
  9. calleeContextexecution context stackへpushする;calleeContextは現在running execution contextである。
  10. func.[[Async]]trueなら、
    1. promiseCapabilityを ! NewPromiseCapability(%Promise%) とする。
    2. resultsClosureを、functhisArgargList、およびnewTargetをcaptureし、呼び出されたときに次のstepsを実行する、parametersを持たない新しいAbstract Closureとする:
      1. resultを、funcの仕様に適合する方法でfunc評価した結果であるCompletion Recordとする。thisArguninitializedである場合、this値はuninitializedである;そうでなければthisArgthis値を提供する。argListはnamed parametersを提供する。newTargetはNewTarget値を提供する。
      2. NOTE: funcがこの文書内で定義されている場合、“funcの仕様”とは、algorithm stepsまたはその他の手段によってそれに対して指定されたbehaviourである。
      3. Completion(result)を返す。
    3. AsyncFunctionStart(promiseCapability, resultsClosure)を実行する。
    4. calleeContextexecution context stackから削除し、callerContextrunning execution contextとして復元する。
    5. promiseCapability.[[Promise]]を返す。
  11. resultを、funcの仕様に適合する方法でfunc評価した結果であるCompletion Recordとする。thisArguninitializedである場合、this値はuninitializedである;そうでなければthisArgthis値を提供する。argListはnamed parametersを提供する。newTargetはNewTarget値を提供する。
  12. NOTE: funcがこの文書内で定義されている場合、“funcの仕様”とは、algorithm stepsまたはその他の手段によってそれに対して指定されたbehaviourである。
  13. calleeContextexecution context stackから削除し、callerContextrunning execution contextとして復元する。
  14. resultを返す。
Note

calleeContextexecution context stackから削除されるとき、それがsuspendedされ、accessible Generatorによる後続のresumptionのために保持されている場合、破棄してはなりません。

10.3.4 CreateBuiltinFunction ( behaviour, length, name, additionalInternalSlotsList [ , realm [ , proto [ , prefix [ , async ] ] ] ] )

The abstract operation CreateBuiltinFunction takes arguments behaviour (an Abstract Closure, a set of algorithm steps, or some other definition of a function's behaviour provided in this specification), length (a non-negative integer or +∞), name (a property key or a Private Name), and additionalInternalSlotsList (a List of names of internal slots) and optional arguments realm (a Realm Record), proto (an Object or null), prefix (a String), and async (a Boolean) and returns a built-in function object. additionalInternalSlotsListは、objectの一部として定義されなければならない追加internal slotsの名前を含みます。このoperationはbuilt-in function objectを作成します。 It performs the following steps when called:

  1. realmが存在しないなら、realmcurrent Realm Recordに設定する。
  2. protoが存在しないなら、protorealm.[[Intrinsics]].[[%Function.prototype%]]に設定する。
  3. asyncが存在しないなら、asyncfalseに設定する。
  4. internalSlotsListを、10.3がこれから作成されるbuilt-in function objectに要求するすべてのinternal slotsの名前を含むListとする。
  5. additionalInternalSlotsListの要素をinternalSlotsListへappendする。
  6. funcを、呼び出されたときに、提供されたargumentsをbehaviourによって指定される対応parametersの値として使用して、behaviourによって記述されるactionを実行する新しいbuilt-in function objectとする。新しいfunction objectは、internalSlotsListの要素を名前とするinternal slots、および[[InitialName]] internal slotを持つ。
  7. func.[[Async]]asyncに設定する。
  8. func.[[Prototype]]protoに設定する。
  9. func.[[Extensible]]trueに設定する。
  10. func.[[Realm]]realmに設定する。
  11. func.[[InitialName]]nullに設定する。
  12. SetFunctionLength(func, length)を実行する。
  13. prefixが存在しないなら、
    1. SetFunctionName(func, name)を実行する。
  14. そうでなければ、
    1. SetFunctionName(func, name, prefix)を実行する。
  15. funcを返す。

この仕様で定義される各built-in functionは、CreateBuiltinFunction abstract operationを呼び出すことによって作成されます。

10.4 Built-in Exotic Object Internal Methods and Slots

この仕様は、いくつかの種類のbuilt-in exotic objectsを定義します。これらのobjectsは一般に、いくつかの特定の状況を除いてordinary objectsと同様に振る舞います。次のexotic objectsは、以下で明示的に別途指定される場合を除き、ordinary object internal methodsを使用します:

10.4.1 Bound Function Exotic Objects

bound function exotic objectは、別のfunction objectをwrapするexotic objectです。bound function exotic objectはcallableです([[Call]] internal methodを持ち、[[Construct]] internal methodを持つ場合があります)。bound function exotic objectを呼び出すと、一般にそのwrapped functionがcallされます。

objectは、その[[Call]]および(該当する場合)[[Construct]] internal methodsが次の実装を使用し、その他のessential internal methodsが10.1にある定義を使用する場合、bound function exotic objectです。これらのmethodsはBoundFunctionCreateでinstallされます。

Bound function exotic objectsは、Table 26に列挙されるECMAScript function objectsのinternal slotsを持ちません。代わりに、[[Prototype]]および[[Extensible]]に加えて、Table 27に列挙されるinternal slotsを持ちます。

Table 27: Internal Slots of Bound Function Exotic Objects
Internal Slot 説明
[[BoundTargetFunction]] callable Object wrapped function object
[[BoundThis]] ECMAScript言語値 wrapped functionを呼び出すときに常にthis値として渡される値。
[[BoundArguments]] ECMAScript言語値List その要素がwrapped functionへの任意のcallの最初のargumentsとして使用される値のlist。

10.4.1.1 [[Call]] ( thisArg, argList )

The [[Call]] internal method of bound function exotic object func takes arguments thisArg (an ECMAScript language value) and argList (a List of ECMAScript language values) and returns either a normal completion containing an ECMAScript language value or a throw completion. It performs the following steps when called:

  1. targetfunc.[[BoundTargetFunction]]とする。
  2. boundThisfunc.[[BoundThis]]とする。
  3. boundArgsfunc.[[BoundArguments]]とする。
  4. argsboundArgsargListlist-concatenationとする。
  5. Call(target, boundThis, args)を返す。

10.4.1.2 [[Construct]] ( argList, newTarget )

The [[Construct]] internal method of bound function exotic object func takes arguments argList (a List of ECMAScript language values) and newTarget (a constructor) and returns either a normal completion containing an Object or a throw completion. It performs the following steps when called:

  1. targetfunc.[[BoundTargetFunction]]とする。
  2. Assert: IsConstructor(target)はtrueである。
  3. boundArgsfunc.[[BoundArguments]]とする。
  4. argsboundArgsargListlist-concatenationとする。
  5. SameValue(func, newTarget)がtrueなら、newTargettargetに設定する。
  6. Construct(target, args, newTarget)を返す。

10.4.1.3 BoundFunctionCreate ( targetFunc, boundThis, boundArgs )

The abstract operation BoundFunctionCreate takes arguments targetFunc (a function object), boundThis (an ECMAScript language value), and boundArgs (a List of ECMAScript language values) and returns either a normal completion containing a function object or a throw completion. これは、新しいbound function exotic objectsの作成を指定するために使用されます。 It performs the following steps when called:

  1. protoを ? targetFunc.[[GetPrototypeOf]]() とする。
  2. internalSlotsListを、« [[Prototype]], [[Extensible]] »とTable 27に列挙されるinternal slotsのlist-concatenationとする。
  3. objMakeBasicObject(internalSlotsList)とする。
  4. obj.[[Prototype]]protoに設定する。
  5. obj.[[Call]]10.4.1.1で指定されるように設定する。
  6. IsConstructor(targetFunc)がtrueなら、
    1. obj.[[Construct]]10.4.1.2で指定されるように設定する。
  7. obj.[[BoundTargetFunction]]targetFuncに設定する。
  8. obj.[[BoundThis]]boundThisに設定する。
  9. obj.[[BoundArguments]]boundArgsに設定する。
  10. objを返す。

10.4.2 Array Exotic Objects

Arrayは、array index property keysを特別に扱うexotic objectです(6.1.7を参照)。property namearray indexであるpropertyはelementとも呼ばれます。すべてのArrayは、non-configurableな"length" propertyを持ち、その値は常に、その数学的値が232未満である非負整数のNumberです。"length" propertyの値は、名前がarray indexであるすべてのown propertyの名前より数値的に大きいです;Arrayのown propertyが作成または変更されるたびに、このinvariantを維持するために必要に応じて他のpropertiesが調整されます。具体的には、名前がarray indexであるown propertyが追加されるたびに、"length" propertyの値は、必要なら、そのarray indexの数値に1を加えた値へ変更されます;また、"length" propertyの値が変更されるたびに、その値が新しいlength以上であるarray indexを名前に持つすべてのown propertyが削除されます。この制約はArrayのown propertiesにのみ適用され、そのprototypesから継承される可能性のある"length"またはarray index propertiesには影響されません。

objectは、その[[DefineOwnProperty]] internal methodが次の実装を使用し、その他のessential internal methodsが10.1にある定義を使用する場合、Array exotic object(または単にArray)です。これらのmethodsはArrayCreateでinstallされます。

10.4.2.1 [[DefineOwnProperty]] ( propertyKey, propertyDesc )

The [[DefineOwnProperty]] internal method of Array exotic object array takes arguments propertyKey (a property key) and propertyDesc (a Property Descriptor) and returns either a normal completion containing a Boolean or a throw completion. It performs the following steps when called:

  1. propertyKey"length"なら、? ArraySetLength(array, propertyDesc)を返す。
  2. propertyKeyarray indexなら、
    1. lengthDescOrdinaryGetOwnProperty(array, "length")とする。
    2. Assert: lengthDescundefinedでない。
    3. Assert: IsDataDescriptor(lengthDesc)はtrueである。
    4. Assert: lengthDesc.[[Configurable]]falseである。
    5. lengthlengthDesc.[[Value]]とする。
    6. Assert: lengthは非負整数のNumberである。
    7. indexを ! ToUint32(propertyKey) とする。
    8. indexlengthかつlengthDesc.[[Writable]]falseなら、falseを返す。
    9. succeededを ! OrdinaryDefineOwnProperty(array, propertyKey, propertyDesc) とする。
    10. succeededfalseなら、falseを返す。
    11. indexlengthなら、
      1. lengthDesc.[[Value]]index + 1𝔽に設定する。
      2. succeededを ! OrdinaryDefineOwnProperty(array, "length", lengthDesc) に設定する。
      3. Assert: succeededtrueである。
    12. trueを返す。
  3. OrdinaryDefineOwnProperty(array, propertyKey, propertyDesc)を返す。

10.4.2.2 ArrayCreate ( length [ , proto ] )

The abstract operation ArrayCreate takes argument length (a non-negative integer) and optional argument proto (an Object) and returns either a normal completion containing an Array exotic object or a throw completion. これは、新しいArraysの作成を指定するために使用されます。 It performs the following steps when called:

  1. length > 232 - 1なら、RangeError例外をthrowする。
  2. protoが存在しないなら、proto%Array.prototype%に設定する。
  3. arrayMakeBasicObject[[Prototype]], [[Extensible]] »)とする。
  4. array.[[Prototype]]protoに設定する。
  5. array.[[DefineOwnProperty]]10.4.2.1で指定されるように設定する。
  6. OrdinaryDefineOwnProperty(array, "length", PropertyDescriptor { [[Value]]: 𝔽(length), [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false })を実行する。
  7. arrayを返す。

10.4.2.3 ArraySpeciesCreate ( originalArray, length )

The abstract operation ArraySpeciesCreate takes arguments originalArray (an Object) and length (a non-negative integer) and returns either a normal completion containing an Object or a throw completion. これは、originalArrayから派生したconstructor functionを使用して、新しいArrayまたは類似objectの作成を指定するために使用されます。constructor functionがArrayを返すことは強制しません。 It performs the following steps when called:

  1. isArrayを ? IsArray(originalArray) とする。
  2. isArrayfalseなら、? ArrayCreate(length)を返す。
  3. ctorを ? Get(originalArray, "constructor") とする。
  4. IsConstructor(ctor)がtrueなら、
    1. thisRealmcurrent Realm Recordとする。
    2. ctorRealmを ? GetFunctionRealm(ctor) とする。
    3. thisRealmctorRealmが同じRealm Recordでないなら、
      1. SameValue(ctor, ctorRealm.[[Intrinsics]].[[%Array%]])がtrueなら、ctorundefinedに設定する。
  5. ctorがObjectなら、
    1. ctorを ? Get(ctor, %Symbol.species%) に設定する。
    2. ctornullなら、ctorundefinedに設定する。
  6. ctorundefinedなら、? ArrayCreate(length)を返す。
  7. IsConstructor(ctor)がfalseなら、TypeError例外をthrowする。
  8. Construct(ctor, « 𝔽(length) »)を返す。
Note

originalArrayrunning execution contextrealmではないrealmのstandard built-in Array constructorを使用して作成された場合、新しいArrayはrunning execution contextrealmを使用して作成されます。これは、現在ArraySpeciesCreateを使用して定義されるArray.prototype methodsについて、歴史的にそのbehaviourを持っていたWeb browsersとの互換性を維持します。

10.4.2.4 ArraySetLength ( array, propertyDesc )

The abstract operation ArraySetLength takes arguments array (an Array) and propertyDesc (a Property Descriptor) and returns either a normal completion containing a Boolean or a throw completion. It performs the following steps when called:

  1. propertyDesc[[Value]] fieldを持たないなら、
    1. OrdinaryDefineOwnProperty(array, "length", propertyDesc)を返す。
  2. newLengthDescpropertyDescのcopyとする。
  3. newLengthを ? ToUint32(propertyDesc.[[Value]]) とする。
  4. numberLengthを ? ToNumber(propertyDesc.[[Value]]) とする。
  5. SameValueZero(newLength, numberLength)がfalseなら、RangeError例外をthrowする。
  6. newLengthDesc.[[Value]]newLengthに設定する。
  7. oldLengthDescOrdinaryGetOwnProperty(array, "length")とする。
  8. Assert: oldLengthDescundefinedでない。
  9. Assert: IsDataDescriptor(oldLengthDesc)はtrueである。
  10. Assert: oldLengthDesc.[[Configurable]]falseである。
  11. oldLengtholdLengthDesc.[[Value]]とする。
  12. newLengtholdLengthなら、
    1. OrdinaryDefineOwnProperty(array, "length", newLengthDesc)を返す。
  13. oldLengthDesc.[[Writable]]falseなら、falseを返す。
  14. newLengthDesc[[Writable]] fieldを持たない、またはnewLengthDesc.[[Writable]]trueなら、
    1. newWritabletrueとする。
  15. そうでなければ、
    1. NOTE: 任意のelementsを削除できない場合に備えて、[[Writable]]属性をfalseに設定することはdeferされる。
    2. newWritablefalseとする。
    3. newLengthDesc.[[Writable]]trueに設定する。
  16. succeededを ! OrdinaryDefineOwnProperty(array, "length", newLengthDesc) とする。
  17. succeededfalseなら、falseを返す。
  18. array indexであり、! ToUint32(propertyKey) ≥ newLengthであるようなarrayの各own property key propertyKeyについて、descending numeric index orderで、以下を行う
    1. deleteSucceededを ! array.[[Delete]](propertyKey) とする。
    2. deleteSucceededfalseなら、
      1. newLengthDesc.[[Value]]を ! ToUint32(propertyKey) + 1𝔽に設定する。
      2. newWritablefalseなら、newLengthDesc.[[Writable]]falseに設定する。
      3. OrdinaryDefineOwnProperty(array, "length", newLengthDesc)を実行する。
      4. falseを返す。
  19. newWritablefalseなら、
    1. succeededを ! OrdinaryDefineOwnProperty(array, "length", PropertyDescriptor { [[Writable]]: false }) に設定する。
    2. Assert: succeededtrueである。
  20. trueを返す。
Note

ステップ3および4において、propertyDesc.[[Value]]がobjectである場合、そのvalueOf methodは2回呼び出されます。これは、この仕様の第2からこのeffectを伴って指定されていたlegacy behaviourです。

10.4.3 String Exotic Objects

String objectは、String値をカプセル化し、String値の個々のcode unit elementsに対応するvirtual integer-indexed data propertiesを公開するexotic objectです。String exotic objectsは常に、カプセル化されたString値のlengthを値に持つ"length"という名前のdata propertyを持ちます。code unit data properties"length" propertyはいずれもnon-writableかつnon-configurableです。

objectは、その[[GetOwnProperty]][[DefineOwnProperty]]、および[[OwnPropertyKeys]] internal methodsが次の実装を使用し、その他のessential internal methodsが10.1にある定義を使用する場合、String exotic object(または単にString object)です。これらのmethodsはStringCreateでinstallされます。

String exotic objectsordinary objectsと同じinternal slotsを持ちます。また、[[StringData]] internal slotも持ちます。

10.4.3.1 [[GetOwnProperty]] ( propertyKey )

The [[GetOwnProperty]] internal method of String exotic object string takes argument propertyKey (a property key) and returns a normal completion containing either a Property Descriptor or undefined. It performs the following steps when called:

  1. propertyDescOrdinaryGetOwnProperty(string, propertyKey)とする。
  2. propertyDescundefinedでないなら、propertyDescを返す。
  3. StringGetOwnProperty(string, propertyKey)を返す。

10.4.3.2 [[DefineOwnProperty]] ( propertyKey, propertyDesc )

The [[DefineOwnProperty]] internal method of String exotic object string takes arguments propertyKey (a property key) and propertyDesc (a Property Descriptor) and returns a normal completion containing a Boolean. It performs the following steps when called:

  1. stringDescStringGetOwnProperty(string, propertyKey)とする。
  2. stringDescundefinedでないなら、
    1. extensiblestring.[[Extensible]]とする。
    2. IsCompatiblePropertyDescriptor(extensible, propertyDesc, stringDesc)を返す。
  3. OrdinaryDefineOwnProperty(string, propertyKey, propertyDesc)を返す。

10.4.3.3 [[OwnPropertyKeys]] ( )

The [[OwnPropertyKeys]] internal method of String exotic object obj takes no arguments and returns a normal completion containing a List of property keys. It performs the following steps when called:

  1. keysを新しい空のListとする。
  2. stringobj.[[StringData]]とする。
  3. Assert: stringはStringである。
  4. lengthstringのlengthとする。
  5. 0 ≤ i < lengthである各integer iについて、昇順で、以下を行う
    1. ToString(𝔽(i))をkeysへappendする。
  6. array indexであり、! ToIntegerOrInfinity(propertyKey) ≥ lengthであるようなobjの各own property key propertyKeyについて、ascending numeric index orderで、以下を行う
    1. propertyKeykeysへappendする。
  7. Stringであり、array indexでないようなobjの各own property key propertyKeyについて、property creationのascending chronological orderで、以下を行う
    1. propertyKeykeysへappendする。
  8. Symbolであるようなobjの各own property key propertyKeyについて、property creationのascending chronological orderで、以下を行う
    1. propertyKeykeysへappendする。
  9. keysを返す。

10.4.3.4 StringCreate ( value, proto )

The abstract operation StringCreate takes arguments value (a String) and proto (an Object) and returns a String exotic object. これは、新しいString exotic objectsの作成を指定するために使用されます。 It performs the following steps when called:

  1. stringMakeBasicObject[[Prototype]], [[Extensible]], [[StringData]] »)とする。
  2. string.[[Prototype]]protoに設定する。
  3. string.[[StringData]]valueに設定する。
  4. string.[[GetOwnProperty]]10.4.3.1で指定されるように設定する。
  5. string.[[DefineOwnProperty]]10.4.3.2で指定されるように設定する。
  6. string.[[OwnPropertyKeys]]10.4.3.3で指定されるように設定する。
  7. lengthvalueのlengthとする。
  8. DefinePropertyOrThrow(string, "length", PropertyDescriptor { [[Value]]: 𝔽(length), [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false })を実行する。
  9. stringを返す。

10.4.3.5 StringGetOwnProperty ( string, propertyKey )

The abstract operation StringGetOwnProperty takes arguments string (an Object that has a [[StringData]] internal slot) and propertyKey (a property key) and returns a Property Descriptor or undefined. It performs the following steps when called:

  1. propertyKeyがStringでないなら、undefinedを返す。
  2. numericIndexCanonicalNumericIndexString(propertyKey)とする。
  3. numericIndexintegral Numberでないなら、undefinedを返す。
  4. numericIndex-0𝔽またはnumericIndex < -0𝔽なら、undefinedを返す。
  5. stringDatastring.[[StringData]]とする。
  6. Assert: stringDataはStringである。
  7. lengthstringDataのlengthとする。
  8. (numericIndex) ≥ lengthなら、undefinedを返す。
  9. resultString(numericIndex)から(numericIndex) + 1までのstringDatasubstringとする。
  10. PropertyDescriptor { [[Value]]: resultString, [[Writable]]: false, [[Enumerable]]: true, [[Configurable]]: false }を返す。

10.4.4 Arguments Exotic Objects

ほとんどのECMAScript functionsは、そのコードからarguments objectを利用可能にします。function definitionの特性に応じて、そのarguments objectはordinary objectまたはarguments exotic objectのいずれかです。arguments exotic objectは、array index propertiesが、その関連ECMAScript functionの呼び出しのformal parameters bindingsへmapするexotic objectです。

objectは、そのinternal methodsが次の実装を使用し、ここで指定されていないものは10.1にある定義を使用する場合、arguments exotic objectです。これらのmethodsはCreateMappedArgumentsObjectでinstallされます。

Note 1

CreateUnmappedArgumentsObjectはこのclauseにgroup化されていますが、arguments exotic objectではなくordinary objectを作成します。

Arguments exotic objectsordinary objectsと同じinternal slotsを持ちます。また、[[ParameterMap]] internal slotも持ちます。Ordinary arguments objectsも[[ParameterMap]] internal slotを持ち、その値は常にundefinedです。ordinary argument objectsについては、[[ParameterMap]] internal slotはObject.prototype.toString20.1.3.6)がそれらをそのようなものとして識別するためにのみ使用されます。

Note 2

numeric name valuesが対応するfunction objectのformal parametersの数より小さいarguments exotic objectinteger-indexed data propertiesは、初期状態で、functionのexecution context内の対応するargument bindingsと値を共有します。これは、propertyを変更すると対応するargument bindingの値が変更され、その逆も成り立つことを意味します。この対応関係は、そのようなpropertyが削除されてから再定義された場合、またはそのpropertyがaccessor propertyへ変更された場合に破られます。arguments objectがordinary objectである場合、そのpropertiesの値は、単にfunctionへ渡されたargumentsのcopyであり、property valuesとformal parameter valuesの間に動的なlinkageはありません。

Note 3

ParameterMap objectおよびそのproperty valuesは、arguments objectとargument bindingsとの対応を指定するための装置として使用されます。ParameterMap objectおよびそのpropertiesの値であるobjectsは、ECMAScriptコードから直接観測可能ではありません。ECMAScript実装は、指定されたsemanticsを実装するために、そのようなobjectsを実際に作成または使用する必要はありません。

Note 4

Ordinary arguments objectsは、アクセス時にTypeError例外をthrowする、"callee"という名前のnon-configurable accessor propertyを定義します。"callee" propertyは、一部のclassのnon-strict functionsに対してのみ作成されるarguments exotic objectsについて、より具体的な意味を持ちます。ordinary variantにおけるこのpropertyの定義は、conforming ECMAScript implementationsによって他の方法で定義されないことを保証するために存在します。

Note 5

arguments exotic objectsのECMAScript実装は、歴史的に"caller"という名前のaccessor propertyを含んでいました。ECMAScript 2017より前、この仕様にはordinary arguments objects上のthrowing "caller" propertyの定義が含まれていました。実装はもはやこの拡張を含まないため、ECMAScript 2017はthrowing "caller" accessorの要件を削除しました。

10.4.4.1 [[GetOwnProperty]] ( propertyKey )

The [[GetOwnProperty]] internal method of arguments exotic object args takes argument propertyKey (a property key) and returns a normal completion containing either a Property Descriptor or undefined. It performs the following steps when called:

  1. propertyDescOrdinaryGetOwnProperty(args, propertyKey)とする。
  2. propertyDescundefinedなら、undefinedを返す。
  3. mapargs.[[ParameterMap]]とする。
  4. isMappedを ! HasOwnProperty(map, propertyKey) とする。
  5. isMappedtrueなら、
    1. propertyDesc.[[Value]]を ! Get(map, propertyKey) に設定する。
  6. propertyDescを返す。

10.4.4.2 [[DefineOwnProperty]] ( propertyKey, propertyDesc )

The [[DefineOwnProperty]] internal method of arguments exotic object args takes arguments propertyKey (a property key) and propertyDesc (a Property Descriptor) and returns a normal completion containing a Boolean. It performs the following steps when called:

  1. mapargs.[[ParameterMap]]とする。
  2. isMappedを ! HasOwnProperty(map, propertyKey) とする。
  3. newArgDescpropertyDescとする。
  4. isMappedtrueであり、かつIsDataDescriptor(propertyDesc)がtrueなら、
    1. propertyDesc[[Value]] fieldを持たず、propertyDesc[[Writable]] fieldを持ち、かつpropertyDesc.[[Writable]]falseなら、
      1. newArgDescpropertyDescのcopyに設定する。
      2. newArgDesc.[[Value]]を ! Get(map, propertyKey) に設定する。
  5. allowedを ! OrdinaryDefineOwnProperty(args, propertyKey, newArgDesc) とする。
  6. allowedfalseなら、falseを返す。
  7. isMappedtrueなら、
    1. IsAccessorDescriptor(propertyDesc)がtrueなら、
      1. map.[[Delete]](propertyKey)を実行する。
    2. そうでなければ、
      1. propertyDesc[[Value]] fieldを持つなら、
        1. Assert: formal parameters mapped by arguments objectsは常にwritableであるため、次のSetは成功する。
        2. Set(map, propertyKey, propertyDesc.[[Value]], false)を実行する。
      2. propertyDesc[[Writable]] fieldを持ち、propertyDesc.[[Writable]]falseなら、
        1. map.[[Delete]](propertyKey)を実行する。
  8. trueを返す。

10.4.4.3 [[Get]] ( propertyKey, receiver )

The [[Get]] internal method of arguments exotic object args takes arguments propertyKey (a property key) and receiver (an ECMAScript language value) and returns either a normal completion containing an ECMAScript language value or a throw completion. It performs the following steps when called:

  1. mapargs.[[ParameterMap]]とする。
  2. isMappedを ! HasOwnProperty(map, propertyKey) とする。
  3. isMappedfalseなら、? OrdinaryGet(args, propertyKey, receiver)を返す。
  4. Assert: mappropertyKeyに対するformal parameter mappingを含む。
  5. Get(map, propertyKey)を返す。

10.4.4.4 [[Set]] ( propertyKey, value, receiver )

The [[Set]] internal method of arguments exotic object args takes arguments propertyKey (a property key), value (an ECMAScript language value), and receiver (an ECMAScript language value) and returns either a normal completion containing a Boolean or a throw completion. It performs the following steps when called:

  1. SameValue(args, receiver)がfalseなら、
    1. isMappedfalseとする。
  2. そうでなければ、
    1. mapargs.[[ParameterMap]]とする。
    2. isMappedを ! HasOwnProperty(map, propertyKey) とする。
  3. isMappedtrueなら、
    1. Assert: formal parameters mapped by arguments objectsは常にwritableであるため、次のSetは成功する。
    2. Set(map, propertyKey, value, false)を実行する。
  4. OrdinarySet(args, propertyKey, value, receiver)を返す。

10.4.4.5 [[Delete]] ( propertyKey )

The [[Delete]] internal method of arguments exotic object args takes argument propertyKey (a property key) and returns either a normal completion containing a Boolean or a throw completion. It performs the following steps when called:

  1. mapargs.[[ParameterMap]]とする。
  2. isMappedを ! HasOwnProperty(map, propertyKey) とする。
  3. resultを ? OrdinaryDelete(args, propertyKey) とする。
  4. resulttrueかつisMappedtrueなら、
    1. map.[[Delete]](propertyKey)を実行する。
  5. resultを返す。

10.4.4.6 CreateUnmappedArgumentsObject ( argList )

The abstract operation CreateUnmappedArgumentsObject takes argument argList (a List of ECMAScript language values) and returns an ordinary object. It performs the following steps when called:

  1. lengthargList内の要素数とする。
  2. objOrdinaryObjectCreate(%Object.prototype%, « [[ParameterMap]] »)とする。
  3. obj.[[ParameterMap]]undefinedに設定する。
  4. DefinePropertyOrThrow(obj, "length", PropertyDescriptor { [[Value]]: 𝔽(length), [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: true })を実行する。
  5. indexを0とする。
  6. index < lengthである間、繰り返す
    1. valueargList[index]とする。
    2. CreateDataPropertyOrThrow(obj, ! ToString(𝔽(index)), value)を実行する。
    3. indexindex + 1に設定する。
  7. DefinePropertyOrThrow(obj, %Symbol.iterator%, PropertyDescriptor { [[Value]]: %Array.prototype.values%, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: true })を実行する。
  8. DefinePropertyOrThrow(obj, "callee", PropertyDescriptor { [[Get]]: %ThrowTypeError%, [[Set]]: %ThrowTypeError%, [[Enumerable]]: false, [[Configurable]]: false })を実行する。
  9. objを返す。

10.4.4.7 CreateMappedArgumentsObject ( func, formals, argList, envRecord )

The abstract operation CreateMappedArgumentsObject takes arguments func (an ECMAScript function object), formals (a Parse Node), argList (a List of ECMAScript language values), and envRecord (an Environment Record) and returns an arguments exotic object. It performs the following steps when called:

  1. Assert: formalsはrest parameter、任意のbinding patterns、または任意のinitializersを含まない。duplicate identifiersを含む場合がある。
  2. lengthargList内の要素数とする。
  3. objMakeBasicObject[[Prototype]], [[Extensible]], [[ParameterMap]] »)とする。
  4. obj.[[GetOwnProperty]]10.4.4.1で指定されるように設定する。
  5. obj.[[DefineOwnProperty]]10.4.4.2で指定されるように設定する。
  6. obj.[[Get]]10.4.4.3で指定されるように設定する。
  7. obj.[[Set]]10.4.4.4で指定されるように設定する。
  8. obj.[[Delete]]10.4.4.5で指定されるように設定する。
  9. obj.[[Prototype]]%Object.prototype%に設定する。
  10. mapOrdinaryObjectCreate(null)とする。
  11. obj.[[ParameterMap]]mapに設定する。
  12. paramNamesformalsBoundNamesとする。
  13. paramCountparamNames内の要素数とする。
  14. indexを0とする。
  15. index < lengthである間、繰り返す
    1. valueargList[index]とする。
    2. CreateDataPropertyOrThrow(obj, ! ToString(𝔽(index)), value)を実行する。
    3. indexindex + 1に設定する。
  16. DefinePropertyOrThrow(obj, "length", PropertyDescriptor { [[Value]]: 𝔽(length), [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: true })を実行する。
  17. mappedNamesを新しい空のListとする。
  18. indexparamCount - 1に設定する。
  19. index ≥ 0である間、繰り返す
    1. nameparamNames[index]とする。
    2. mappedNamesnameを含まないなら、
      1. namemappedNamesへappendする。
      2. index < lengthなら、
        1. getterMakeArgGetter(name, envRecord)とする。
        2. setterMakeArgSetter(name, envRecord)とする。
        3. map.[[DefineOwnProperty]](! ToString(𝔽(index)), PropertyDescriptor { [[Set]]: setter, [[Get]]: getter, [[Enumerable]]: false, [[Configurable]]: true })を実行する。
    3. indexindex - 1に設定する。
  20. DefinePropertyOrThrow(obj, %Symbol.iterator%, PropertyDescriptor { [[Value]]: %Array.prototype.values%, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: true })を実行する。
  21. DefinePropertyOrThrow(obj, "callee", PropertyDescriptor { [[Value]]: func, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: true })を実行する。
  22. objを返す。

10.4.4.7.1 MakeArgGetter ( name, envRecord )

The abstract operation MakeArgGetter takes arguments name (a String) and envRecord (an Environment Record) and returns a function object. これは、実行されたときにenvRecord内でnameにbindされた値を返すbuilt-in function objectを作成します。 It performs the following steps when called:

  1. getterClosureを、nameおよびenvRecordをcaptureし、呼び出されたときに次のstepsを実行する、parametersを持たない新しいAbstract Closureとする:
    1. NormalCompletion(! envRecord.GetBindingValue(name, false))を返す。
  2. getterCreateBuiltinFunction(getterClosure, 0, "", « »)とする。
  3. NOTE: getterはECMAScriptコードから直接アクセス可能になることは決してない。
  4. getterを返す。

10.4.4.7.2 MakeArgSetter ( name, envRecord )

The abstract operation MakeArgSetter takes arguments name (a String) and envRecord (an Environment Record) and returns a function object. これは、実行されたときにenvRecord内でnameにbindされた値を設定するbuilt-in function objectを作成します。 It performs the following steps when called:

  1. setterClosureを、nameおよびenvRecordをcaptureし、呼び出されたときに次のstepsを実行するparameters (value)を持つ新しいAbstract Closureとする:
    1. NormalCompletion(! envRecord.SetMutableBinding(name, value, false))を返す。
  2. setterCreateBuiltinFunction(setterClosure, 1, "", « »)とする。
  3. NOTE: setterはECMAScriptコードから直接アクセス可能になることは決してない。
  4. setterを返す。

10.4.5 TypedArray Exotic Objects

TypedArrayは、canonical numeric stringsであるproperty keysを特別に処理するexotic objectです。in-bounds integer indicesであるsubsetを使用してuniform typeのelementsをindexし、残りはprototype chain traversalを発生させずに存在しないというinvariantを強制します。

Note

任意のNumber nについてToString(n)はcanonical numeric stringであるため、実装は、実際にstring conversionを実行せずに、NumbersをTypedArraysproperty keysとして扱ってよいです。

TypedArraysordinary objectsと同じinternal slotsを持ち、さらに[[ViewedArrayBuffer]][[TypedArrayName]][[ContentType]][[ByteLength]][[ByteOffset]]、および[[ArrayLength]] internal slotsを持ちます。

objectは、その[[PreventExtensions]][[GetOwnProperty]][[HasProperty]][[DefineOwnProperty]][[Get]][[Set]][[Delete]]、および[[OwnPropertyKeys]] internal methodsがこのsectionの定義を使用し、その他のessential internal methodsが10.1にある定義を使用する場合、TypedArrayです。これらのmethodsはTypedArrayCreateによってinstallされます。

10.4.5.1 [[PreventExtensions]] ( )

The [[PreventExtensions]] internal method of TypedArray obj takes no arguments and returns a normal completion containing a Boolean. It performs the following steps when called:

  1. NOTE: 6.1.7.3で指定されるextensibility-related invariantsは、objがpropertiesを得る(または失ってから再び得る)可能性があるとき、このmethodがtrueを返すことを許可しない。これは、そのunderlying bufferがresizeされるとき、integer index namesを持つpropertiesについて発生する場合がある。
  2. IsTypedArrayFixedLength(obj)がfalseなら、falseを返す。
  3. OrdinaryPreventExtensions(obj)を返す。

10.4.5.2 [[GetOwnProperty]] ( propertyKey )

The [[GetOwnProperty]] internal method of TypedArray obj takes argument propertyKey (a property key) and returns a normal completion containing either a Property Descriptor or undefined. It performs the following steps when called:

  1. propertyKeyがStringなら、
    1. numericIndexCanonicalNumericIndexString(propertyKey)とする。
    2. numericIndexundefinedでないなら、
      1. valueTypedArrayGetElement(obj, numericIndex)とする。
      2. valueundefinedなら、undefinedを返す。
      3. PropertyDescriptor { [[Value]]: value, [[Writable]]: true, [[Enumerable]]: true, [[Configurable]]: true }を返す。
  2. OrdinaryGetOwnProperty(obj, propertyKey)を返す。

10.4.5.3 [[HasProperty]] ( propertyKey )

The [[HasProperty]] internal method of TypedArray obj takes argument propertyKey (a property key) and returns either a normal completion containing a Boolean or a throw completion. It performs the following steps when called:

  1. propertyKeyがStringなら、
    1. numericIndexCanonicalNumericIndexString(propertyKey)とする。
    2. numericIndexundefinedでないなら、IsValidIntegerIndex(obj, numericIndex)を返す。
  2. OrdinaryHasProperty(obj, propertyKey)を返す。

10.4.5.4 [[DefineOwnProperty]] ( propertyKey, propertyDesc )

The [[DefineOwnProperty]] internal method of TypedArray obj takes arguments propertyKey (a property key) and propertyDesc (a Property Descriptor) and returns either a normal completion containing a Boolean or a throw completion. It performs the following steps when called:

  1. propertyKeyがStringなら、
    1. numericIndexCanonicalNumericIndexString(propertyKey)とする。
    2. numericIndexundefinedでないなら、
      1. IsValidIntegerIndex(obj, numericIndex)がfalseなら、falseを返す。
      2. propertyDesc[[Configurable]] fieldを持ち、propertyDesc.[[Configurable]]falseなら、falseを返す。
      3. propertyDesc[[Enumerable]] fieldを持ち、propertyDesc.[[Enumerable]]falseなら、falseを返す。
      4. IsAccessorDescriptor(propertyDesc)がtrueなら、falseを返す。
      5. propertyDesc[[Writable]] fieldを持ち、propertyDesc.[[Writable]]falseなら、falseを返す。
      6. propertyDesc[[Value]] fieldを持つなら、? TypedArraySetElement(obj, numericIndex, propertyDesc.[[Value]])を実行する。
      7. trueを返す。
  2. OrdinaryDefineOwnProperty(obj, propertyKey, propertyDesc)を返す。

10.4.5.5 [[Get]] ( propertyKey, receiver )

The [[Get]] internal method of TypedArray obj takes arguments propertyKey (a property key) and receiver (an ECMAScript language value) and returns either a normal completion containing an ECMAScript language value or a throw completion. It performs the following steps when called:

  1. propertyKeyがStringなら、
    1. numericIndexCanonicalNumericIndexString(propertyKey)とする。
    2. numericIndexundefinedでないなら、
      1. TypedArrayGetElement(obj, numericIndex)を返す。
  2. OrdinaryGet(obj, propertyKey, receiver)を返す。

10.4.5.6 [[Set]] ( propertyKey, value, receiver )

The [[Set]] internal method of TypedArray obj takes arguments propertyKey (a property key), value (an ECMAScript language value), and receiver (an ECMAScript language value) and returns either a normal completion containing a Boolean or a throw completion. It performs the following steps when called:

  1. propertyKeyがStringなら、
    1. numericIndexCanonicalNumericIndexString(propertyKey)とする。
    2. numericIndexundefinedでないなら、
      1. SameValue(obj, receiver)がtrueなら、
        1. TypedArraySetElement(obj, numericIndex, value)を実行する。
        2. trueを返す。
      2. IsValidIntegerIndex(obj, numericIndex)がfalseなら、trueを返す。
  2. OrdinarySet(obj, propertyKey, value, receiver)を返す。

10.4.5.7 [[Delete]] ( propertyKey )

The [[Delete]] internal method of TypedArray obj takes argument propertyKey (a property key) and returns a normal completion containing a Boolean. It performs the following steps when called:

  1. propertyKeyがStringなら、
    1. numericIndexCanonicalNumericIndexString(propertyKey)とする。
    2. numericIndexundefinedでないなら、
      1. IsValidIntegerIndex(obj, numericIndex)がfalseなら、trueを返す。
      2. falseを返す。
  2. OrdinaryDelete(obj, propertyKey)を返す。

10.4.5.8 [[OwnPropertyKeys]] ( )

The [[OwnPropertyKeys]] internal method of TypedArray obj takes no arguments and returns a normal completion containing a List of property keys. It performs the following steps when called:

  1. taRecordMakeTypedArrayWithBufferWitnessRecord(obj, seq-cst)とする。
  2. keysを新しい空のListとする。
  3. IsTypedArrayOutOfBounds(taRecord)がfalseなら、
    1. lengthTypedArrayLength(taRecord)とする。
    2. 0 ≤ i < lengthである各integer iについて、昇順で、以下を行う
      1. ToString(𝔽(i))をkeysへappendする。
  4. Stringであり、integer indexでないようなobjの各own property key propertyKeyについて、property creationのascending chronological orderで、以下を行う
    1. propertyKeykeysへappendする。
  5. Symbolであるようなobjの各own property key propertyKeyについて、property creationのascending chronological orderで、以下を行う
    1. propertyKeykeysへappendする。
  6. keysを返す。

10.4.5.9 TypedArray With Buffer Witness Records

TypedArray With Buffer Witness Recordは、TypedArrayを、viewed bufferのcached byte lengthとともにカプセル化するために使用されるRecord値です。viewed bufferがgrowable SharedArrayBufferであるとき、byte length data blockの単一のReadSharedMemory eventが存在することを保証する助けとして使用されます。

TypedArray With Buffer Witness Recordsは、Table 28に列挙されるフィールドを持ちます。

Table 28: TypedArray With Buffer Witness Record Fields
フィールド名 意味
[[Object]] TypedArray そのbufferのbyte lengthがloadされるTypedArray
[[CachedBufferByteLength]] 非負整数またはdetached Recordが作成されたときのobjectの[[ViewedArrayBuffer]]のbyte length。

10.4.5.10 MakeTypedArrayWithBufferWitnessRecord ( obj, order )

The abstract operation MakeTypedArrayWithBufferWitnessRecord takes arguments obj (a TypedArray) and order (seq-cst or unordered) and returns a TypedArray 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. TypedArray With Buffer Witness Record { [[Object]]: obj, [[CachedBufferByteLength]]: byteLength }を返す。

10.4.5.11 TypedArrayCreate ( proto )

The abstract operation TypedArrayCreate takes argument proto (an Object) and returns a TypedArray. これは、新しいTypedArraysの作成を指定するために使用されます。 It performs the following steps when called:

  1. internalSlotsListを« [[Prototype]], [[Extensible]], [[ViewedArrayBuffer]], [[TypedArrayName]], [[ContentType]], [[ByteLength]], [[ByteOffset]], [[ArrayLength]] »とする。
  2. taMakeBasicObject(internalSlotsList)とする。
  3. ta.[[PreventExtensions]]10.4.5.1で指定されるように設定する。
  4. ta.[[GetOwnProperty]]10.4.5.2で指定されるように設定する。
  5. ta.[[HasProperty]]10.4.5.3で指定されるように設定する。
  6. ta.[[DefineOwnProperty]]10.4.5.4で指定されるように設定する。
  7. ta.[[Get]]10.4.5.5で指定されるように設定する。
  8. ta.[[Set]]10.4.5.6で指定されるように設定する。
  9. ta.[[Delete]]10.4.5.7で指定されるように設定する。
  10. ta.[[OwnPropertyKeys]]10.4.5.8で指定されるように設定する。
  11. ta.[[Prototype]]protoに設定する。
  12. taを返す。

10.4.5.12 TypedArrayByteLength ( taRecord )

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

  1. Assert: IsTypedArrayOutOfBounds(taRecord)はfalseである。
  2. objtaRecord.[[Object]]とする。
  3. obj.[[ByteLength]]autoでないなら、obj.[[ByteLength]]を返す。
  4. lengthTypedArrayLength(taRecord)とする。
  5. elementSizeTypedArrayElementSize(obj)とする。
  6. NOTE: underlying bufferが非整数倍にresizeされている場合でも、返されるbyte lengthは常にelementSizeの整数倍である。
  7. length × elementSizeを返す。

10.4.5.13 TypedArrayLength ( taRecord )

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

  1. Assert: IsTypedArrayOutOfBounds(taRecord)はfalseである。
  2. objtaRecord.[[Object]]とする。
  3. obj.[[ArrayLength]]autoでないなら、obj.[[ArrayLength]]を返す。
  4. Assert: IsFixedLengthArrayBuffer(obj.[[ViewedArrayBuffer]])はfalseである。
  5. byteOffsetobj.[[ByteOffset]]とする。
  6. elementSizeTypedArrayElementSize(obj)とする。
  7. byteLengthtaRecord.[[CachedBufferByteLength]]とする。
  8. Assert: byteLengthdetachedでない。
  9. floor((byteLength - byteOffset) / elementSize)を返す。

10.4.5.14 IsTypedArrayOutOfBounds ( taRecord )

The abstract operation IsTypedArrayOutOfBounds takes argument taRecord (a TypedArray With Buffer Witness Record) and returns a Boolean. これは、objectのnumeric propertiesのいずれかがunderlying bufferのbounds内に含まれないindexにある値を参照するかどうかをcheckします。 It performs the following steps when called:

  1. objtaRecord.[[Object]]とする。
  2. bufferByteLengthtaRecord.[[CachedBufferByteLength]]とする。
  3. IsDetachedBuffer(obj.[[ViewedArrayBuffer]])がtrueなら、
    1. Assert: bufferByteLengthdetachedである。
    2. trueを返す。
  4. Assert: bufferByteLengthは非負整数である。
  5. byteOffsetStartobj.[[ByteOffset]]とする。
  6. obj.[[ArrayLength]]autoなら、
    1. byteOffsetEndbufferByteLengthとする。
  7. そうでなければ、
    1. elementSizeTypedArrayElementSize(obj)とする。
    2. arrayByteLengthobj.[[ArrayLength]] × elementSizeとする。
    3. byteOffsetEndbyteOffsetStart + arrayByteLengthとする。
  8. NOTE: [[ByteOffset]]bufferByteLengthである0-length TypedArrayはout-of-boundsとはみなされない。
  9. byteOffsetStart > bufferByteLengthまたはbyteOffsetEnd > bufferByteLengthなら、trueを返す。
  10. falseを返す。

10.4.5.15 IsTypedArrayFixedLength ( obj )

The abstract operation IsTypedArrayFixedLength takes argument obj (a TypedArray) and returns a Boolean. It performs the following steps when called:

  1. obj.[[ArrayLength]]autoなら、falseを返す。
  2. bufferobj.[[ViewedArrayBuffer]]とする。
  3. IsFixedLengthArrayBuffer(buffer)がfalseかつIsSharedArrayBuffer(buffer)がfalseなら、falseを返す。
  4. trueを返す。

10.4.5.16 IsValidIntegerIndex ( obj, index )

The abstract operation IsValidIntegerIndex takes arguments obj (a TypedArray) and index (a Number) and returns a Boolean. It performs the following steps when called:

  1. IsDetachedBuffer(obj.[[ViewedArrayBuffer]])がtrueなら、falseを返す。
  2. indexintegral Numberでないなら、falseを返す。
  3. index-0𝔽またはindex < -0𝔽なら、falseを返す。
  4. taRecordMakeTypedArrayWithBufferWitnessRecord(obj, unordered)とする。
  5. NOTE: objのbacking bufferがgrowable SharedArrayBufferである場合、Bounds checkingはsynchronizing operationではない。
  6. IsTypedArrayOutOfBounds(taRecord)がtrueなら、falseを返す。
  7. lengthTypedArrayLength(taRecord)とする。
  8. (index) ≥ lengthなら、falseを返す。
  9. trueを返す。

10.4.5.17 TypedArrayGetElement ( obj, index )

The abstract operation TypedArrayGetElement takes arguments obj (a TypedArray) and index (a Number) and returns a Number, a BigInt, or undefined. It performs the following steps when called:

  1. IsValidIntegerIndex(obj, index)がfalseなら、undefinedを返す。
  2. offsetobj.[[ByteOffset]]とする。
  3. elementSizeTypedArrayElementSize(obj)とする。
  4. byteIndexInBufferを((index) × elementSize) + offsetとする。
  5. elementTypeTypedArrayElementType(obj)とする。
  6. GetValueFromBuffer(obj.[[ViewedArrayBuffer]], byteIndexInBuffer, elementType, true, unordered)を返す。

10.4.5.18 TypedArraySetElement ( obj, index, value )

The abstract operation TypedArraySetElement takes arguments obj (a TypedArray), index (a Number), and value (an ECMAScript language value) and returns either a normal completion containing unused or a throw completion. It performs the following steps when called:

  1. obj.[[ContentType]]bigintなら、numberを ? ToBigInt(value) とする。
  2. そうでなければ、numberを ? ToNumber(value) とする。
  3. IsValidIntegerIndex(obj, index)がtrueなら、
    1. offsetobj.[[ByteOffset]]とする。
    2. elementSizeTypedArrayElementSize(obj)とする。
    3. byteIndexInBufferを((index) × elementSize) + offsetとする。
    4. elementTypeTypedArrayElementType(obj)とする。
    5. SetValueInBuffer(obj.[[ViewedArrayBuffer]], byteIndexInBuffer, elementType, number, true, unordered)を実行する。
  4. unusedを返す。
Note

このoperationは常に成功するように見えますが、TypedArrayの末尾を越えてwriteしようとする場合、またはdetached ArrayBufferによってbackされるTypedArrayへwriteしようとする場合、効果はありません。

10.4.5.19 IsArrayBufferViewOutOfBounds ( obj )

The abstract operation IsArrayBufferViewOutOfBounds takes argument obj (a TypedArray or a DataView) and returns a Boolean. これは、TypedArrayのnumeric propertiesのいずれか、またはDataView objectのmethodsが、underlying data blockのbounds内に含まれないindexにある値を参照できるかどうかをcheckします。このabstract operationは、upstream specificationsの便宜のために存在します。 It performs the following steps when called:

  1. obj[[DataView]] internal slotを持つなら、
    1. viewRecordMakeDataViewWithBufferWitnessRecord(obj, seq-cst)とする。
    2. IsViewOutOfBounds(viewRecord)を返す。
  2. taRecordMakeTypedArrayWithBufferWitnessRecord(obj, seq-cst)とする。
  3. IsTypedArrayOutOfBounds(taRecord)を返す。

10.4.6 Module Namespace Exotic Objects

module namespace exotic objectは、ECMAScript Moduleからexportされたbindingsを公開するexotic objectです(16.2.3を参照)。module namespace exotic objectのString-keyed own propertiesと、Moduleによってexportされたbinding namesの間には1対1の対応があります。exported bindingsには、export * export itemsを使用してindirectlyにexportされた任意のbindingsが含まれます。各String-valued own property keyは、対応するexported binding nameのStringValueです。これらはmodule namespace exotic objectの唯一のString-keyed propertiesです。そのような各propertyは、attributes { [[Writable]]: true, [[Enumerable]]: true, [[Configurable]]: false }を持ちます。Module namespace exotic objectsはextensibleではありません。

objectは、その[[GetPrototypeOf]][[SetPrototypeOf]][[IsExtensible]][[PreventExtensions]][[GetOwnProperty]][[DefineOwnProperty]][[HasProperty]][[Get]][[Set]][[Delete]]、および[[OwnPropertyKeys]] internal methodsがこのsectionの定義を使用し、その他のessential internal methodsが10.1にある定義を使用する場合、module namespace exotic objectです。これらのmethodsはModuleNamespaceCreateによってinstallされます。

Module namespace exotic objectsは、Table 29で定義されるinternal slotsを持ちます。

Table 29: Internal Slots of Module Namespace Exotic Objects
Internal Slot 説明
[[Module]] Module Record このnamespaceが公開するexportsを持つModule Record
[[Exports]] StringsのList 要素が、このobjectのown propertiesとして公開されるexported namesのString値であるList。このlistはlexicographic code unit orderに従ってsortされます。

10.4.6.1 [[GetPrototypeOf]] ( )

The [[GetPrototypeOf]] internal method of module namespace exotic object takes no arguments and returns a normal completion containing null. It performs the following steps when called:

  1. nullを返す。

10.4.6.2 [[SetPrototypeOf]] ( proto )

The [[SetPrototypeOf]] internal method of module namespace exotic object obj takes argument proto (an Object or null) and returns a normal completion containing a Boolean. It performs the following steps when called:

  1. SetImmutablePrototype(obj, proto)を返す。

10.4.6.3 [[IsExtensible]] ( )

The [[IsExtensible]] internal method of module namespace exotic object takes no arguments and returns a normal completion containing false. It performs the following steps when called:

  1. falseを返す。

10.4.6.4 [[PreventExtensions]] ( )

The [[PreventExtensions]] internal method of module namespace exotic object takes no arguments and returns a normal completion containing true. It performs the following steps when called:

  1. trueを返す。

10.4.6.5 [[GetOwnProperty]] ( propertyKey )

The [[GetOwnProperty]] internal method of module namespace exotic object obj takes argument propertyKey (a property key) and returns either a normal completion containing either a Property Descriptor or undefined, or a throw completion. It performs the following steps when called:

  1. propertyKeyがSymbolなら、OrdinaryGetOwnProperty(obj, propertyKey)を返す。
  2. exportsobj.[[Exports]]とする。
  3. exportspropertyKeyを含まないなら、undefinedを返す。
  4. valueを ? obj.[[Get]](propertyKey, obj) とする。
  5. PropertyDescriptor { [[Value]]: value, [[Writable]]: true, [[Enumerable]]: true, [[Configurable]]: false }を返す。

10.4.6.6 [[DefineOwnProperty]] ( propertyKey, propertyDesc )

The [[DefineOwnProperty]] internal method of module namespace exotic object obj takes arguments propertyKey (a property key) and propertyDesc (a Property Descriptor) and returns either a normal completion containing a Boolean or a throw completion. It performs the following steps when called:

  1. propertyKeyがSymbolなら、! OrdinaryDefineOwnProperty(obj, propertyKey, propertyDesc)を返す。
  2. currentを ? obj.[[GetOwnProperty]](propertyKey) とする。
  3. currentundefinedなら、falseを返す。
  4. propertyDesc[[Configurable]] fieldを持ち、propertyDesc.[[Configurable]]trueなら、falseを返す。
  5. propertyDesc[[Enumerable]] fieldを持ち、propertyDesc.[[Enumerable]]falseなら、falseを返す。
  6. IsAccessorDescriptor(propertyDesc)がtrueなら、falseを返す。
  7. propertyDesc[[Writable]] fieldを持ち、propertyDesc.[[Writable]]falseなら、falseを返す。
  8. propertyDesc[[Value]] fieldを持つなら、SameValue(propertyDesc.[[Value]], current.[[Value]])を返す。
  9. trueを返す。

10.4.6.7 [[HasProperty]] ( propertyKey )

The [[HasProperty]] internal method of module namespace exotic object obj takes argument propertyKey (a property key) and returns a normal completion containing a Boolean. It performs the following steps when called:

  1. propertyKeyがSymbolなら、! OrdinaryHasProperty(obj, propertyKey)を返す。
  2. exportsobj.[[Exports]]とする。
  3. exportspropertyKeyを含むなら、trueを返す。
  4. falseを返す。

10.4.6.8 [[Get]] ( propertyKey, receiver )

The [[Get]] internal method of module namespace exotic object obj takes arguments propertyKey (a property key) and receiver (an ECMAScript language value) and returns either a normal completion containing an ECMAScript language value or a throw completion. It performs the following steps when called:

  1. propertyKeyがSymbolなら、
    1. OrdinaryGet(obj, propertyKey, receiver)を返す。
  2. exportsobj.[[Exports]]とする。
  3. exportspropertyKeyを含まないなら、undefinedを返す。
  4. moduleobj.[[Module]]とする。
  5. bindingmodule.ResolveExport(propertyKey)とする。
  6. Assert: bindingResolvedBinding Recordである。
  7. targetModulebinding.[[Module]]とする。
  8. Assert: targetModuleundefinedでない。
  9. binding.[[BindingName]]namespaceなら、
    1. GetModuleNamespace(targetModule)を返す。
  10. targetEnvtargetModule.[[Environment]]とする。
  11. targetEnvemptyなら、ReferenceError例外をthrowする。
  12. targetEnv.GetBindingValue(binding.[[BindingName]], true)を返す。
Note

ResolveExportはside-effect freeです。このoperationが特定のexportNameresolveSet pairをargumentsとして呼び出されるたびに、同じ結果を返さなければなりません。実装は、各module namespace exotic object[[Exports]]についてResolveExportの結果をpre-computeまたはcacheすることを選択する場合があります。

10.4.6.9 [[Set]] ( propertyKey, value, receiver )

The [[Set]] internal method of module namespace exotic object takes arguments propertyKey (a property key), value (an ECMAScript language value), and receiver (an ECMAScript language value) and returns a normal completion containing false. It performs the following steps when called:

  1. falseを返す。

10.4.6.10 [[Delete]] ( propertyKey )

The [[Delete]] internal method of module namespace exotic object obj takes argument propertyKey (a property key) and returns a normal completion containing a Boolean. It performs the following steps when called:

  1. propertyKeyがSymbolなら、
    1. OrdinaryDelete(obj, propertyKey)を返す。
  2. exportsobj.[[Exports]]とする。
  3. exportspropertyKeyを含むなら、falseを返す。
  4. trueを返す。

10.4.6.11 [[OwnPropertyKeys]] ( )

The [[OwnPropertyKeys]] internal method of module namespace exotic object obj takes no arguments and returns a normal completion containing a List of property keys. It performs the following steps when called:

  1. exportsobj.[[Exports]]とする。
  2. symbolKeysOrdinaryOwnPropertyKeys(obj)とする。
  3. exportssymbolKeyslist-concatenationを返す。

10.4.6.12 ModuleNamespaceCreate ( module, exports )

The abstract operation ModuleNamespaceCreate takes arguments module (a Module Record) and exports (a List of Strings) and returns a module namespace exotic object. これは、新しいmodule namespace exotic objectsの作成を指定するために使用されます。 It performs the following steps when called:

  1. Assert: module.[[Namespace]]emptyである。
  2. internalSlotsListTable 29に列挙されるinternal slotsとする。
  3. namespaceMakeBasicObject(internalSlotsList)とする。
  4. namespaceのessential internal methodsを10.4.6で指定される定義に設定する。
  5. namespace.[[Module]]moduleに設定する。
  6. sortedExportsを、exportsの要素をlexicographic code unit orderに従ってsortした要素を持つListとする。
  7. namespace.[[Exports]]sortedExportsに設定する。
  8. 28.3の定義に対応するnamespaceのown propertiesを作成する。
  9. module.[[Namespace]]namespaceに設定する。
  10. namespaceを返す。

10.4.7 Immutable Prototype Exotic Objects

immutable prototype exotic objectは、初期化されると変更されない[[Prototype]] internal slotを持つexotic objectです。

objectは、その[[SetPrototypeOf]] internal methodが次の実装を使用する場合、immutable prototype exotic objectです。(その他のessential internal methodsは、対象となる具体的なimmutable prototype exotic objectに応じて、任意の実装を使用できます。)

Note

他のexotic objectsとは異なり、immutable prototype exotic objectsには専用のcreation abstract operationは提供されていません。これは、それらが%Object.prototype%およびhost environmentsによってのみ使用され、host environmentsでは、関連objectsが他の方法でもpotentially exoticであるため、それら自身の専用creation operationを必要とするからです。

10.4.7.1 [[SetPrototypeOf]] ( proto )

The [[SetPrototypeOf]] internal method of immutable prototype exotic object obj takes argument proto (an Object or null) and returns either a normal completion containing a Boolean or a throw completion. It performs the following steps when called:

  1. SetImmutablePrototype(obj, proto)を返す。

10.4.7.2 SetImmutablePrototype ( obj, proto )

The abstract operation SetImmutablePrototype takes arguments obj (an Object) and proto (an Object or null) and returns either a normal completion containing a Boolean or a throw completion. It performs the following steps when called:

  1. currentを ? obj.[[GetPrototypeOf]]() とする。
  2. SameValue(proto, current)がtrueなら、trueを返す。
  3. falseを返す。

10.5 Proxy Object Internal Methods and Internal Slots

Proxy objectは、そのessential internal methodsが部分的にECMAScriptコードを使用して実装されるexotic objectです。すべてのProxy objectは[[ProxyHandler]]と呼ばれるinternal slotを持ちます。[[ProxyHandler]]の値は、proxyのhandler objectと呼ばれるobject、またはnullです。handler objectのmethods(Table 30を参照)は、Proxy objectの1つ以上のinternal methodsの実装を補強するために使用される場合があります。すべてのProxy objectは[[ProxyTarget]]と呼ばれるinternal slotも持ち、その値はobjectまたはnullのいずれかです。このobjectはproxyのtarget objectと呼ばれます。

objectは、そのessential internal methods(該当する場合は[[Call]]および[[Construct]]を含む)がこのsectionの定義を使用する場合、Proxy exotic objectです。これらのinternal methodsはProxyCreateでinstallされます。

Table 30: Proxy Handler Methods
Internal Method Handler Method
[[GetPrototypeOf]] getPrototypeOf
[[SetPrototypeOf]] setPrototypeOf
[[IsExtensible]] isExtensible
[[PreventExtensions]] preventExtensions
[[GetOwnProperty]] getOwnPropertyDescriptor
[[DefineOwnProperty]] defineProperty
[[HasProperty]] has
[[Get]] get
[[Set]] set
[[Delete]] deleteProperty
[[OwnPropertyKeys]] ownKeys
[[Call]] apply
[[Construct]] construct

handler methodがProxy object internal methodの実装を提供するために呼び出されるとき、handler methodにはproxyのtarget objectがparameterとして渡されます。proxyのhandler objectは、すべてのessential internal methodに対応するmethodを必ずしも持つわけではありません。proxy上でinternal methodをinvokeすると、handler objectがinternal trapに対応するmethodを持たない場合、proxyのtarget object上で対応するinternal methodがinvokeされます。

Proxy objectの[[ProxyHandler]]および[[ProxyTarget]] internal slotsは、objectが作成されるときに常に初期化され、通常は変更できません。一部のProxy objectsは、後でrevokedできるような方法で作成されます。proxyがrevokedされると、その[[ProxyHandler]]および[[ProxyTarget]] internal slotsはnullに設定され、そのProxy object上で後続のinternal methodsのinvocationsがTypeError例外をthrowするようになります。

Proxy objectsはinternal methodsの実装を任意のECMAScriptコードによって提供することを許可するため、handler methodsが6.1.7.3で定義されるinvariantsに違反するProxy objectを定義することが可能です。6.1.7.3で定義されるinternal method invariantsの一部はessential integrity invariantsです。これらのinvariantsは、このsectionで指定されるProxy object internal methodsによって明示的に強制されます。ECMAScript実装は、あらゆる可能なinvariant violationsが存在する場合にも堅牢でなければなりません。

以下のalgorithm descriptionsでは、objはECMAScript Proxy object、propertyKeyproperty key値、valueは任意のECMAScript language value、propertyDescProperty Descriptor recordであると仮定します。

10.5.1 [[GetPrototypeOf]] ( )

The [[GetPrototypeOf]] internal method of Proxy exotic object obj takes no arguments and returns either a normal completion containing either an Object or null, or a throw completion. It performs the following steps when called:

  1. ValidateNonRevokedProxy(obj)を実行する。
  2. targetobj.[[ProxyTarget]]とする。
  3. handlerobj.[[ProxyHandler]]とする。
  4. Assert: handlerはObjectである。
  5. trapを ? GetMethod(handler, "getPrototypeOf") とする。
  6. trapundefinedなら、
    1. target.[[GetPrototypeOf]]()を返す。
  7. handlerProtoを ? Call(trap, handler, « target ») とする。
  8. handlerProtoがObjectでなく、かつhandlerProtonullでないなら、TypeError例外をthrowする。
  9. extensibleTargetを ? IsExtensible(target) とする。
  10. extensibleTargettrueなら、handlerProtoを返す。
  11. targetProtoを ? target.[[GetPrototypeOf]]() とする。
  12. SameValue(handlerProto, targetProto)がfalseなら、TypeError例外をthrowする。
  13. handlerProtoを返す。
Note

Proxy objectsに対する[[GetPrototypeOf]]は次のinvariantsを強制します:

  • [[GetPrototypeOf]]の結果はObjectまたはnullのいずれかでなければならない。
  • target objectがextensibleでない場合、Proxy objectに適用された[[GetPrototypeOf]]は、Proxy objectのtarget objectに適用された[[GetPrototypeOf]]と同じ値を返さなければならない。

10.5.2 [[SetPrototypeOf]] ( proto )

The [[SetPrototypeOf]] internal method of Proxy exotic object obj takes argument proto (an Object or null) and returns either a normal completion containing a Boolean or a throw completion. It performs the following steps when called:

  1. ValidateNonRevokedProxy(obj)を実行する。
  2. targetobj.[[ProxyTarget]]とする。
  3. handlerobj.[[ProxyHandler]]とする。
  4. Assert: handlerはObjectである。
  5. trapを ? GetMethod(handler, "setPrototypeOf") とする。
  6. trapundefinedなら、
    1. target.[[SetPrototypeOf]](proto)を返す。
  7. boolTrapResultToBoolean(? Call(trap, handler, « target, proto »))とする。
  8. boolTrapResultfalseなら、falseを返す。
  9. extensibleTargetを ? IsExtensible(target) とする。
  10. extensibleTargettrueなら、trueを返す。
  11. targetProtoを ? target.[[GetPrototypeOf]]() とする。
  12. SameValue(proto, targetProto)がfalseなら、TypeError例外をthrowする。
  13. trueを返す。
Note

Proxy objectsに対する[[SetPrototypeOf]]は次のinvariantsを強制します:

  • [[SetPrototypeOf]]の結果はBoolean値である。
  • target objectがextensibleでない場合、argument値はtarget objectに適用された[[GetPrototypeOf]]の結果と同じでなければならない。

10.5.3 [[IsExtensible]] ( )

The [[IsExtensible]] internal method of Proxy exotic object obj takes no arguments and returns either a normal completion containing a Boolean or a throw completion. It performs the following steps when called:

  1. ValidateNonRevokedProxy(obj)を実行する。
  2. targetobj.[[ProxyTarget]]とする。
  3. handlerobj.[[ProxyHandler]]とする。
  4. Assert: handlerはObjectである。
  5. trapを ? GetMethod(handler, "isExtensible") とする。
  6. trapundefinedなら、
    1. IsExtensible(target)を返す。
  7. boolTrapResultToBoolean(? Call(trap, handler, « target »))とする。
  8. targetResultを ? IsExtensible(target) とする。
  9. boolTrapResulttargetResultでないなら、TypeError例外をthrowする。
  10. boolTrapResultを返す。
Note

Proxy objectsに対する[[IsExtensible]]は次のinvariantsを強制します:

  • [[IsExtensible]]の結果はBoolean値である。
  • Proxy objectに適用された[[IsExtensible]]は、同じargumentを伴ってProxy objectのtarget objectに適用された[[IsExtensible]]と同じ値を返さなければならない。

10.5.4 [[PreventExtensions]] ( )

The [[PreventExtensions]] internal method of Proxy exotic object obj takes no arguments and returns either a normal completion containing a Boolean or a throw completion. It performs the following steps when called:

  1. ValidateNonRevokedProxy(obj)を実行する。
  2. targetobj.[[ProxyTarget]]とする。
  3. handlerobj.[[ProxyHandler]]とする。
  4. Assert: handlerはObjectである。
  5. trapを ? GetMethod(handler, "preventExtensions") とする。
  6. trapundefinedなら、
    1. target.[[PreventExtensions]]()を返す。
  7. boolTrapResultToBoolean(? Call(trap, handler, « target »))とする。
  8. boolTrapResulttrueなら、
    1. extensibleTargetを ? IsExtensible(target) とする。
    2. extensibleTargettrueなら、TypeError例外をthrowする。
  9. boolTrapResultを返す。
Note

Proxy objectsに対する[[PreventExtensions]]は次のinvariantsを強制します:

  • [[PreventExtensions]]の結果はBoolean値である。
  • Proxy objectに適用された[[PreventExtensions]]は、Proxy objectのtarget objectに適用された[[IsExtensible]]falseである場合にのみtrueを返す。

10.5.5 [[GetOwnProperty]] ( propertyKey )

The [[GetOwnProperty]] internal method of Proxy exotic object obj takes argument propertyKey (a property key) and returns either a normal completion containing either a Property Descriptor or undefined, or a throw completion. It performs the following steps when called:

  1. ValidateNonRevokedProxy(obj)を実行する。
  2. targetobj.[[ProxyTarget]]とする。
  3. handlerobj.[[ProxyHandler]]とする。
  4. Assert: handlerはObjectである。
  5. trapを ? GetMethod(handler, "getOwnPropertyDescriptor") とする。
  6. trapundefinedなら、
    1. target.[[GetOwnProperty]](propertyKey)を返す。
  7. trapResultObjを ? Call(trap, handler, « target, propertyKey ») とする。
  8. trapResultObjがObjectでなく、かつtrapResultObjundefinedでないなら、TypeError例外をthrowする。
  9. targetDescを ? target.[[GetOwnProperty]](propertyKey) とする。
  10. trapResultObjundefinedなら、
    1. targetDescundefinedなら、undefinedを返す。
    2. targetDesc.[[Configurable]]falseなら、TypeError例外をthrowする。
    3. extensibleTargetを ? IsExtensible(target) とする。
    4. extensibleTargetfalseなら、TypeError例外をthrowする。
    5. undefinedを返す。
  11. extensibleTargetを ? IsExtensible(target) とする。
  12. resultDescを ? ToPropertyDescriptor(trapResultObj) とする。
  13. CompletePropertyDescriptor(resultDesc)を実行する。
  14. validIsCompatiblePropertyDescriptor(extensibleTarget, resultDesc, targetDesc)とする。
  15. validfalseなら、TypeError例外をthrowする。
  16. resultDesc.[[Configurable]]falseなら、
    1. targetDescundefinedまたはtargetDesc.[[Configurable]]trueなら、
      1. TypeError例外をthrowする。
    2. resultDesc[[Writable]] fieldを持ち、resultDesc.[[Writable]]falseなら、
      1. Assert: targetDesc[[Writable]] fieldを持つ。
      2. targetDesc.[[Writable]]trueなら、TypeError例外をthrowする。
  17. resultDescを返す。
Note

Proxy objectsに対する[[GetOwnProperty]]は次のinvariantsを強制します:

  • [[GetOwnProperty]]の結果はProperty Descriptorまたはundefinedのいずれかでなければならない。
  • propertyがtarget objectのnon-configurable own propertyとして存在する場合、そのpropertyをnon-existentとして報告することはできない。
  • propertyがnon-extensible target objectのown propertyとして存在する場合、そのpropertyをnon-existentとして報告することはできない。
  • propertyがtarget objectのown propertyとして存在せず、かつtarget objectがextensibleでない場合、そのpropertyをexistentとして報告することはできない。
  • propertyがtarget objectのnon-configurable own propertyとして存在しない限り、そのpropertyをnon-configurableとして報告することはできない。
  • propertyがtarget objectのnon-configurable, non-writable own propertyとして存在しない限り、そのpropertyをnon-configurableかつnon-writableとして報告することはできない。

10.5.6 [[DefineOwnProperty]] ( propertyKey, propertyDesc )

The [[DefineOwnProperty]] internal method of Proxy exotic object obj takes arguments propertyKey (a property key) and propertyDesc (a Property Descriptor) and returns either a normal completion containing a Boolean or a throw completion. It performs the following steps when called:

  1. ValidateNonRevokedProxy(obj)を実行する。
  2. targetobj.[[ProxyTarget]]とする。
  3. handlerobj.[[ProxyHandler]]とする。
  4. Assert: handlerはObjectである。
  5. trapを ? GetMethod(handler, "defineProperty") とする。
  6. trapundefinedなら、
    1. target.[[DefineOwnProperty]](propertyKey, propertyDesc)を返す。
  7. propertyDescObjFromPropertyDescriptor(propertyDesc)とする。
  8. boolTrapResultToBoolean(? Call(trap, handler, « target, propertyKey, propertyDescObj »))とする。
  9. boolTrapResultfalseなら、falseを返す。
  10. targetDescを ? target.[[GetOwnProperty]](propertyKey) とする。
  11. extensibleTargetを ? IsExtensible(target) とする。
  12. propertyDesc[[Configurable]] fieldを持ち、propertyDesc.[[Configurable]]falseなら、
    1. settingConfigFalsetrueとする。
  13. そうでなければ、
    1. settingConfigFalsefalseとする。
  14. targetDescundefinedなら、
    1. extensibleTargetfalseなら、TypeError例外をthrowする。
    2. settingConfigFalsetrueなら、TypeError例外をthrowする。
  15. そうでなければ、
    1. IsCompatiblePropertyDescriptor(extensibleTarget, propertyDesc, targetDesc)がfalseなら、TypeError例外をthrowする。
    2. settingConfigFalsetrueかつtargetDesc.[[Configurable]]trueなら、TypeError例外をthrowする。
    3. IsDataDescriptor(targetDesc)がtruetargetDesc.[[Configurable]]false、かつtargetDesc.[[Writable]]trueなら、
      1. propertyDesc[[Writable]] fieldを持ち、propertyDesc.[[Writable]]falseなら、TypeError例外をthrowする。
  16. trueを返す。
Note

Proxy objectsに対する[[DefineOwnProperty]]は次のinvariantsを強制します:

  • [[DefineOwnProperty]]の結果はBoolean値である。
  • target objectがextensibleでない場合、propertyを追加することはできない。
  • target objectの対応するnon-configurable own propertyが存在しない限り、propertyはnon-configurableになれない。
  • target objectの対応するnon-configurable, non-writable own propertyが存在しない限り、non-configurable propertyはnon-writableになれない。
  • propertyに対応するtarget object propertyが存在する場合、そのpropertyのProperty Descriptor[[DefineOwnProperty]]を使用してtarget objectに適用しても例外はthrowされない。

10.5.7 [[HasProperty]] ( propertyKey )

The [[HasProperty]] internal method of Proxy exotic object obj takes argument propertyKey (a property key) and returns either a normal completion containing a Boolean or a throw completion. It performs the following steps when called:

  1. ValidateNonRevokedProxy(obj)を実行する。
  2. targetobj.[[ProxyTarget]]とする。
  3. handlerobj.[[ProxyHandler]]とする。
  4. Assert: handlerはObjectである。
  5. trapを ? GetMethod(handler, "has") とする。
  6. trapundefinedなら、
    1. target.[[HasProperty]](propertyKey)を返す。
  7. boolTrapResultToBoolean(? Call(trap, handler, « target, propertyKey »))とする。
  8. boolTrapResultfalseなら、
    1. targetDescを ? target.[[GetOwnProperty]](propertyKey) とする。
    2. targetDescundefinedでないなら、
      1. targetDesc.[[Configurable]]falseなら、TypeError例外をthrowする。
      2. extensibleTargetを ? IsExtensible(target) とする。
      3. extensibleTargetfalseなら、TypeError例外をthrowする。
  9. boolTrapResultを返す。
Note

Proxy objectsに対する[[HasProperty]]は次のinvariantsを強制します:

  • [[HasProperty]]の結果はBoolean値である。
  • propertyがtarget objectのnon-configurable own propertyとして存在する場合、そのpropertyをnon-existentとして報告することはできない。
  • propertyがtarget objectのown propertyとして存在し、かつtarget objectがextensibleでない場合、そのpropertyをnon-existentとして報告することはできない。

10.5.8 [[Get]] ( propertyKey, receiver )

The [[Get]] internal method of Proxy exotic object obj takes arguments propertyKey (a property key) and receiver (an ECMAScript language value) and returns either a normal completion containing an ECMAScript language value or a throw completion. It performs the following steps when called:

  1. ValidateNonRevokedProxy(obj)を実行する。
  2. targetobj.[[ProxyTarget]]とする。
  3. handlerobj.[[ProxyHandler]]とする。
  4. Assert: handlerはObjectである。
  5. trapを ? GetMethod(handler, "get") とする。
  6. trapundefinedなら、
    1. target.[[Get]](propertyKey, receiver)を返す。
  7. trapResultを ? Call(trap, handler, « target, propertyKey, receiver ») とする。
  8. targetDescを ? target.[[GetOwnProperty]](propertyKey) とする。
  9. targetDescundefinedでなく、かつtargetDesc.[[Configurable]]falseなら、
    1. IsDataDescriptor(targetDesc)がtrueであり、かつtargetDesc.[[Writable]]falseなら、
      1. SameValue(trapResult, targetDesc.[[Value]])がfalseなら、TypeError例外をthrowする。
    2. IsAccessorDescriptor(targetDesc)がtrueであり、かつtargetDesc.[[Get]]undefinedなら、
      1. trapResultundefinedでないなら、TypeError例外をthrowする。
  10. trapResultを返す。
Note

Proxy objectsに対する[[Get]]は次のinvariantsを強制します:

  • propertyについて報告される値は、target object propertyがnon-writable, non-configurable own data propertyである場合、対応するtarget object propertyの値と同じでなければならない。
  • 対応するtarget object propertyが[[Get]]属性としてundefinedを持つnon-configurable own accessor propertyである場合、propertyについて報告される値はundefinedでなければならない。

10.5.9 [[Set]] ( propertyKey, value, receiver )

The [[Set]] internal method of Proxy exotic object obj takes arguments propertyKey (a property key), value (an ECMAScript language value), and receiver (an ECMAScript language value) and returns either a normal completion containing a Boolean or a throw completion. It performs the following steps when called:

  1. ValidateNonRevokedProxy(obj)を実行する。
  2. targetobj.[[ProxyTarget]]とする。
  3. handlerobj.[[ProxyHandler]]とする。
  4. Assert: handlerはObjectである。
  5. trapを ? GetMethod(handler, "set") とする。
  6. trapundefinedなら、
    1. target.[[Set]](propertyKey, value, receiver)を返す。
  7. boolTrapResultToBoolean(? Call(trap, handler, « target, propertyKey, value, receiver »))とする。
  8. boolTrapResultfalseなら、falseを返す。
  9. targetDescを ? target.[[GetOwnProperty]](propertyKey) とする。
  10. targetDescundefinedでなく、かつtargetDesc.[[Configurable]]falseなら、
    1. IsDataDescriptor(targetDesc)がtrueであり、かつtargetDesc.[[Writable]]falseなら、
      1. SameValue(value, targetDesc.[[Value]])がfalseなら、TypeError例外をthrowする。
    2. IsAccessorDescriptor(targetDesc)がtrueなら、
      1. targetDesc.[[Set]]undefinedなら、TypeError例外をthrowする。
  11. trueを返す。
Note

Proxy objectsに対する[[Set]]は次のinvariantsを強制します:

  • [[Set]]の結果はBoolean値である。
  • 対応するtarget object propertyがnon-writable, non-configurable own data propertyである場合、propertyの値を、対応するtarget object propertyの値と異なるものに変更することはできない。
  • 対応するtarget object propertyが[[Set]]属性としてundefinedを持つnon-configurable own accessor propertyである場合、propertyの値を設定することはできない。

10.5.10 [[Delete]] ( propertyKey )

The [[Delete]] internal method of Proxy exotic object obj takes argument propertyKey (a property key) and returns either a normal completion containing a Boolean or a throw completion. It performs the following steps when called:

  1. ValidateNonRevokedProxy(obj)を実行する。
  2. targetobj.[[ProxyTarget]]とする。
  3. handlerobj.[[ProxyHandler]]とする。
  4. Assert: handlerはObjectである。
  5. trapを ? GetMethod(handler, "deleteProperty") とする。
  6. trapundefinedなら、
    1. target.[[Delete]](propertyKey)を返す。
  7. boolTrapResultToBoolean(? Call(trap, handler, « target, propertyKey »))とする。
  8. boolTrapResultfalseなら、falseを返す。
  9. targetDescを ? target.[[GetOwnProperty]](propertyKey) とする。
  10. targetDescundefinedなら、trueを返す。
  11. targetDesc.[[Configurable]]falseなら、TypeError例外をthrowする。
  12. extensibleTargetを ? IsExtensible(target) とする。
  13. extensibleTargetfalseなら、TypeError例外をthrowする。
  14. trueを返す。
Note

Proxy objectsに対する[[Delete]]は次のinvariantsを強制します:

  • [[Delete]]の結果はBoolean値である。
  • propertyがtarget objectのnon-configurable own propertyとして存在する場合、そのpropertyをdeletedとして報告することはできない。
  • propertyがtarget objectのown propertyとして存在し、かつtarget objectがnon-extensibleである場合、そのpropertyをdeletedとして報告することはできない。

10.5.11 [[OwnPropertyKeys]] ( )

The [[OwnPropertyKeys]] internal method of Proxy exotic object obj takes no arguments and returns either a normal completion containing a List of property keys or a throw completion. It performs the following steps when called:

  1. ValidateNonRevokedProxy(obj)を実行する。
  2. targetobj.[[ProxyTarget]]とする。
  3. handlerobj.[[ProxyHandler]]とする。
  4. Assert: handlerはObjectである。
  5. trapを ? GetMethod(handler, "ownKeys") とする。
  6. trapundefinedなら、
    1. target.[[OwnPropertyKeys]]()を返す。
  7. trapResultArrayを ? Call(trap, handler, « target ») とする。
  8. trapResultを ? CreateListFromArrayLike(trapResultArray, property-key) とする。
  9. trapResultが重複entriesを含むなら、TypeError例外をthrowする。
  10. extensibleTargetを ? IsExtensible(target) とする。
  11. targetKeysを ? target.[[OwnPropertyKeys]]() とする。
  12. Assert: targetKeysproperty keysListである。
  13. Assert: targetKeysは重複entriesを含まない。
  14. targetConfigurableKeysを新しい空のListとする。
  15. targetNonconfigurableKeysを新しい空のListとする。
  16. targetKeysの各要素keyについて、以下を行う
    1. propertyDescを ? target.[[GetOwnProperty]](key) とする。
    2. propertyDescundefinedでなく、かつpropertyDesc.[[Configurable]]falseなら、
      1. keytargetNonconfigurableKeysへappendする。
    3. そうでなければ、
      1. keytargetConfigurableKeysへappendする。
  17. extensibleTargettrueであり、かつtargetNonconfigurableKeysが空なら、
    1. trapResultを返す。
  18. uncheckedResultKeysを、要素がtrapResultの要素であるListとする。
  19. targetNonconfigurableKeysの各要素keyについて、以下を行う
    1. uncheckedResultKeyskeyを含まないなら、TypeError例外をthrowする。
    2. keyuncheckedResultKeysから削除する。
  20. extensibleTargettrueなら、trapResultを返す。
  21. targetConfigurableKeysの各要素keyについて、以下を行う
    1. uncheckedResultKeyskeyを含まないなら、TypeError例外をthrowする。
    2. keyuncheckedResultKeysから削除する。
  22. uncheckedResultKeysが空でないなら、TypeError例外をthrowする。
  23. trapResultを返す。
Note

Proxy objectsに対する[[OwnPropertyKeys]]は次のinvariantsを強制します:

  • [[OwnPropertyKeys]]の結果はListである。
  • 返されるListは重複entriesを含まない。
  • 返されるListの各要素はproperty keyである。
  • result Listは、target objectのすべてのnon-configurable own propertiesのkeysを含まなければならない。
  • target objectがextensibleでない場合、result Listはtarget objectのown propertiesのすべてのkeysを含み、他の値を含んではならない。

10.5.12 [[Call]] ( thisArg, argList )

The [[Call]] internal method of Proxy exotic object obj takes arguments thisArg (an ECMAScript language value) and argList (a List of ECMAScript language values) and returns either a normal completion containing an ECMAScript language value or a throw completion. It performs the following steps when called:

  1. ValidateNonRevokedProxy(obj)を実行する。
  2. targetobj.[[ProxyTarget]]とする。
  3. handlerobj.[[ProxyHandler]]とする。
  4. Assert: handlerはObjectである。
  5. trapを ? GetMethod(handler, "apply") とする。
  6. trapundefinedなら、
    1. Call(target, thisArg, argList)を返す。
  7. argArrayCreateArrayFromList(argList)とする。
  8. Call(trap, handler, « target, thisArg, argArray »)を返す。
Note

Proxy exotic object[[Call]] internal methodを持つのは、その[[ProxyTarget]] internal slotの初期値が[[Call]] internal methodを持つobjectである場合のみです。

10.5.13 [[Construct]] ( argList, newTarget )

The [[Construct]] internal method of Proxy exotic object obj takes arguments argList (a List of ECMAScript language values) and newTarget (a constructor) and returns either a normal completion containing an Object or a throw completion. It performs the following steps when called:

  1. ValidateNonRevokedProxy(obj)を実行する。
  2. targetobj.[[ProxyTarget]]とする。
  3. Assert: IsConstructor(target)はtrueである。
  4. handlerobj.[[ProxyHandler]]とする。
  5. Assert: handlerはObjectである。
  6. trapを ? GetMethod(handler, "construct") とする。
  7. trapundefinedなら、
    1. Construct(target, argList, newTarget)を返す。
  8. argArrayCreateArrayFromList(argList)とする。
  9. newObjを ? Call(trap, handler, « target, argArray, newTarget ») とする。
  10. newObjがObjectでないなら、TypeError例外をthrowする。
  11. newObjを返す。
Note 1

Proxy exotic object[[Construct]] internal methodを持つのは、その[[ProxyTarget]] internal slotの初期値が[[Construct]] internal methodを持つobjectである場合のみです。

Note 2

Proxy objectsに対する[[Construct]]は次のinvariantsを強制します:

  • [[Construct]]の結果はObjectでなければならない。

10.5.14 ValidateNonRevokedProxy ( proxy )

The abstract operation ValidateNonRevokedProxy takes argument proxy (a Proxy exotic object) and returns either a normal completion containing unused or a throw completion. これはproxyがrevokedされている場合、TypeError例外をthrowします。 It performs the following steps when called:

  1. proxy.[[ProxyTarget]]nullなら、TypeError例外をthrowする。
  2. Assert: proxy.[[ProxyHandler]]nullでない。
  3. unusedを返す。

10.5.15 ProxyCreate ( target, handler )

The abstract operation ProxyCreate takes arguments target (an ECMAScript language value) and handler (an ECMAScript language value) and returns either a normal completion containing a Proxy exotic object or a throw completion. これは、新しいProxy objectsの作成を指定するために使用されます。 It performs the following steps when called:

  1. targetがObjectでないなら、TypeError例外をthrowする。
  2. handlerがObjectでないなら、TypeError例外をthrowする。
  3. proxyMakeBasicObject[[ProxyHandler]], [[ProxyTarget]] »)とする。
  4. , [[Call]]および[[Construct]]を除き、proxyのessential internal methodsを10.5で指定される定義に設定する。
  5. IsCallable(target)がtrueなら、
    1. proxy.[[Call]]10.5.12で指定されるように設定する。
    2. IsConstructor(target)がtrueなら、
      1. proxy.[[Construct]]10.5.13で指定されるように設定する。
  6. proxy.[[ProxyTarget]]targetに設定する。
  7. proxy.[[ProxyHandler]]handlerに設定する。
  8. proxyを返す。

11 ECMAScript Language: Source Text

11.1 Source Text

Syntax

SourceCharacter :: any Unicode code point

ECMAScript source textはUnicode code pointsのsequenceです。surrogate code pointsを含むU+0000からU+10FFFFまでのすべてのUnicode code point valuesは、ECMAScript grammarsによって許可される場所でECMAScript source textに出現してよいです。ECMAScript source textを格納および交換するために使用される実際のencodingsは、この仕様には関係ありません。外部source text encodingにかかわらず、conforming ECMAScript implementationはsource textを、各SourceCharacterがUnicode code pointである、等価なSourceCharacter値のsequenceであるかのように処理します。Conforming ECMAScript implementationsは、source textのnormalizationを実行する必要はなく、source textのnormalizationを実行しているかのように振る舞う必要もありません。

combining character sequenceのcomponentsは、ユーザーがsequence全体を単一のcharacterと考える場合でも、個々のUnicode code pointsとして扱われます。

Note

string literals、regular expression literals、template literalsおよびidentifiersでは、任意のUnicode code pointは、code pointの数値を明示的に表すUnicode escape sequencesを使用して表すこともできます。comment内では、そのようなescape sequenceはcommentの一部として事実上無視されます。

ECMAScriptは、Unicode escape sequencesの振る舞いにおいてJava programming languageとは異なります。Javaプログラムでは、例えばUnicode escape sequence \u000Aがsingle-line comment内に出現した場合、それはline terminator(Unicode code point U+000AはLINE FEED (LF))として解釈されるため、次のcode pointはcommentの一部ではありません。同様に、Unicode escape sequence \u000AがJavaプログラムのstring literal内に出現した場合、それも同様にline terminatorとして解釈されますが、これはstring literal内では許可されません—LINE FEED (LF)をstring literalの値の一部にするには、\u000Aではなく\nと書かなければなりません。ECMAScriptプログラムでは、comment内に出現するUnicode escape sequenceは決して解釈されず、したがってcommentの終了に寄与することはありません。同様に、ECMAScriptプログラムのstring literal内に出現するUnicode escape sequenceは常にliteralに寄与し、line terminatorとして、またはstring literalを終了させる可能性のあるcode pointとして解釈されることはありません。

11.1.1 Static Semantics: UTF16EncodeCodePoint ( codePoint )

The abstract operation UTF16EncodeCodePoint takes argument codePoint (a Unicode code point) and returns a String. It performs the following steps when called:

  1. Assert: 0 ≤ codePoint ≤ 0x10FFFF.
  2. codePoint ≤ 0xFFFFなら、数値がcodePointであるcode unitから成るString値を返す。
  3. cu1を、数値がfloor((codePoint - 0x10000) / 0x400) + 0xD800であるcode unitとする。
  4. cu2を、数値が((codePoint - 0x10000) modulo 0x400) + 0xDC00であるcode unitとする。
  5. cu1cu2string-concatenationを返す。

11.1.2 Static Semantics: CodePointsToString ( text )

The abstract operation CodePointsToString takes argument text (a sequence of Unicode code points) and returns a String. これは、6.1.4で説明されるように、textをString値へ変換します。 It performs the following steps when called:

  1. resultを空のStringとする。
  2. textの各code point codePointについて、以下を行う
    1. resultresultUTF16EncodeCodePoint(codePoint)のstring-concatenationに設定する。
  3. resultを返す。

11.1.3 Static Semantics: UTF16SurrogatePairToCodePoint ( lead, trail )

The abstract operation UTF16SurrogatePairToCodePoint takes arguments lead (a code unit) and trail (a code unit) and returns a code point. UTF-16 surrogate pairを形成する2つのcode unitsはcode pointへ変換されます。 It performs the following steps when called:

  1. Assert: leadleading surrogateであり、trailtrailing surrogateである。
  2. codePointを(lead - 0xD800) × 0x400 + (trail - 0xDC00) + 0x10000とする。
  3. code point codePointを返す。

11.1.4 Static Semantics: CodePointAt ( string, position )

The abstract operation CodePointAt takes arguments string (a String) and position (a non-negative integer) and returns a Record with fields [[CodePoint]] (a code point), [[CodeUnitCount]] (a positive integer), and [[IsUnpairedSurrogate]] (a Boolean). これは、6.1.4で説明されるようにstringをUTF-16 encoded code pointsのsequenceとして解釈し、index positionのcode unitから始まる単一のcode pointをそこから読み取ります。 It performs the following steps when called:

  1. sizestringのlengthとする。
  2. Assert: position ≥ 0 かつ position < size.
  3. firststring内のindex positionにあるcode unitとする。
  4. codePointを、数値がfirstの数値であるcode pointとする。
  5. firstleading surrogateでもtrailing surrogateでもないなら、
    1. Record { [[CodePoint]]: codePoint, [[CodeUnitCount]]: 1, [[IsUnpairedSurrogate]]: false }を返す。
  6. firsttrailing surrogate、またはposition + 1 = sizeなら、
    1. Record { [[CodePoint]]: codePoint, [[CodeUnitCount]]: 1, [[IsUnpairedSurrogate]]: true }を返す。
  7. secondstring内のindex position + 1にあるcode unitとする。
  8. secondtrailing surrogateでないなら、
    1. Record { [[CodePoint]]: codePoint, [[CodeUnitCount]]: 1, [[IsUnpairedSurrogate]]: true }を返す。
  9. codePointUTF16SurrogatePairToCodePoint(first, second)に設定する。
  10. Record { [[CodePoint]]: codePoint, [[CodeUnitCount]]: 2, [[IsUnpairedSurrogate]]: false }を返す。

11.1.5 Static Semantics: StringToCodePoints ( string )

The abstract operation StringToCodePoints takes argument string (a String) and returns a List of code points. これは、6.1.4で説明されるようにstringをUTF-16 encoded Unicode textとして解釈した結果となるUnicode code pointsのsequenceを返します。 It performs the following steps when called:

  1. codePointsを新しい空のListとする。
  2. sizestringのlengthとする。
  3. positionを0とする。
  4. position < sizeである間、繰り返す
    1. codePointCodePointAt(string, position)とする。
    2. codePoint.[[CodePoint]]codePointsへappendする。
    3. positionposition + codePoint.[[CodeUnitCount]]に設定する。
  5. codePointsを返す。

11.1.6 Static Semantics: ParseText ( sourceText, goalSymbol )

The abstract operation ParseText takes arguments sourceText (a String or a sequence of Unicode code points) and goalSymbol (a nonterminal in one of the ECMAScript grammars) and returns a Parse Node or a non-empty List of SyntaxError objects. It performs the following steps when called:

  1. sourceTextがStringなら、sourceTextStringToCodePoints(sourceText)に設定する。
  2. goalSymbolgoal symbolとして使用してsourceTextのparseを試み、parse resultにearly error conditionsがないか分析する。Parsingとearly error detectionは、implementation-definedな方法でinterleavedされる場合があります。
  3. parseが成功し、early errorsが見つからなかったなら、parseの結果得られたparse treeのrootにあるParse NodegoalSymbolのinstance)を返す。
  4. parsing errorsおよび/またはearly errorsを表す1つ以上のSyntaxError objectsのListを返す。複数のparsing errorまたはearly errorが存在する場合、list内のerror objectsの数および順序はimplementation-definedですが、少なくとも1つは存在しなければなりません。
Note 1

特定の位置にearly errorがあり、さらに後の位置にsyntax errorもあるtextを考えます。parse passに続いてearly errors passを実行する実装は、syntax errorを報告し、early errors passに進まない場合があります。2つのactivitiesをinterleaveする実装は、early errorを報告し、syntax errorを見つける処理に進まない場合があります。第3の実装は両方のerrorsを報告する場合があります。これらのbehavioursはすべてconformantです。

Note 2

clause 17も参照してください。

11.2 Types of Source Code

ECMAScript codeには4つのtypesがあります:

Note 1

Function codeは一般に、Function Definitions(15.2)、Arrow Function Definitions(15.3)、Method Definitions(15.4)、Generator Function Definitions(15.5)、Async Function Definitions(15.8)、Async Generator Function Definitions(15.6)、およびAsync Arrow Functions(15.9)のbodiesとして提供されます。Function codeは、Function constructor20.2.1.1)、GeneratorFunction constructor27.6.1.1)、AsyncFunction constructor27.10.1.1)、およびAsyncGeneratorFunction constructor27.7.1.1)へのargumentsからもderivedされます。

Note 2

BindingIdentifierをfunction codeに含めることの実際上の効果は、strict mode codeに対するEarly Errorsが、周囲のcodeがstrict mode codeでない場合でも、bodyにUse Strict Directiveを含むfunctionの名前であるBindingIdentifierに適用されることです。

11.2.1 Directive Prologues and the Use Strict Directive

Directive Prologueは、FunctionBodyScriptBody、またはModuleBodyの初期StatementListItemsまたはModuleItemsとして出現するExpressionStatementsの最長sequenceであり、そのsequence内の各ExpressionStatementが、semicolonに続くStringLiteral tokenのみで構成されるものです。semicolonは明示的に現れてもよく、automatic semicolon insertion(12.10)によって挿入されてもよいです。Directive Prologueは空のsequenceであってもよいです。

Use Strict Directiveは、Directive Prologue内のExpressionStatementであり、そのStringLiteralが正確なcode point sequences "use strict"または'use strict'のいずれかであるものです。Use Strict DirectiveEscapeSequenceまたはLineContinuationを含んではなりません。

Directive Prologueは複数のUse Strict Directiveを含む場合があります。ただし、実装はこれが発生した場合にwarningを発してよいです。

Note

Directive PrologueExpressionStatementsは、含むproductionの評価中に通常どおり評価されます。実装は、Use Strict DirectiveではなくDirective Prologue内に出現するExpressionStatementsについて、implementation specificな意味を定義してよいです。適切なnotification mechanismが存在する場合、実装は、Directive Prologue内で、Use Strict Directiveではなく、かつ実装によって定義された意味を持たないExpressionStatementに遭遇した場合、warningを発するべきです。

11.2.2 Strict Mode Code

ECMAScript syntactic unitは、unrestrictedまたはstrict mode syntax and semantics(4.3.2)のいずれかを使用して処理される場合があります。Codeは次の状況でstrict mode codeとして解釈されます:

strict mode codeではないECMAScript codeはnon-strict codeと呼ばれます。

11.2.2.1 Static Semantics: IsStrict ( parseNode )

The abstract operation IsStrict takes argument parseNode (a Parse Node) and returns a Boolean. It performs the following steps when called:

  1. parseNodeに一致するsource textがstrict mode codeなら、trueを返す。
  2. falseを返す。

11.2.3 Non-ECMAScript Functions

ECMAScript implementationは、評価的振る舞いがECMAScript source text以外のhost-defined formのexecutable codeで表現されるfunction exotic objectsの評価をサポートしてよいです。function objectがECMAScript code内で定義されているか、built-in functionであるかは、そのようなfunction objectを呼び出す、またはそのようなfunction objectによって呼び出されるECMAScript codeの観点からは観測可能ではありません。

12 ECMAScript Language: Lexical Grammar

ECMAScript ScriptまたはModuleのsource textは、まずinput elementsのsequenceへ変換されます。input elementsはtokens、line terminators、comments、またはwhite spaceです。source textは左から右へscanされ、次のinput elementとして可能な最長のcode pointsのsequenceを繰り返し取得します。

lexical input elementsの識別が、そのinput elementsを消費しているsyntactic grammar contextに依存する状況がいくつかあります。このため、lexical grammarには複数のgoal symbolsが必要です。InputElementHashbangOrRegExp goalは、ScriptまたはModuleの開始時に使用されます。InputElementRegExpOrTemplateTail goalは、RegularExpressionLiteralTemplateMiddle、またはTemplateTailが許可されるsyntactic grammar contextsで使用されます。InputElementRegExp goal symbolは、RegularExpressionLiteralが許可されるが、TemplateMiddleTemplateTailも許可されないすべてのsyntactic grammar contextsで使用されます。InputElementTemplateTail goalは、TemplateMiddleまたはTemplateTailが許可されるが、RegularExpressionLiteralが許可されないすべてのsyntactic grammar contextsで使用されます。その他すべてのcontextsでは、InputElementDivがlexical goal symbolとして使用されます。

Note

複数のlexical goalsの使用により、automatic semicolon insertionに影響するlexical ambiguitiesが存在しないことが保証されます。例えば、leading divisionまたはdivision-assignmentと、leading RegularExpressionLiteralの両方が許可されるsyntactic grammar contextsは存在しません。これはsemicolon insertion(12.10を参照)の影響を受けません;次のような例では:

a = b
/hi/g.exec(c).map(d);

LineTerminatorの後の最初のnon-whitespace、non-comment code pointがU+002F (SOLIDUS)であり、syntactic contextがdivisionまたはdivision-assignmentを許可している場合、LineTerminatorでsemicolonは挿入されません。つまり、上の例は次と同じ方法で解釈されます:

a = b / hi / g.exec(c).map(d);

Syntax

InputElementDiv :: WhiteSpace LineTerminator Comment CommonToken DivPunctuator RightBracePunctuator InputElementRegExp :: WhiteSpace LineTerminator Comment CommonToken RightBracePunctuator RegularExpressionLiteral InputElementRegExpOrTemplateTail :: WhiteSpace LineTerminator Comment CommonToken RegularExpressionLiteral TemplateSubstitutionTail InputElementTemplateTail :: WhiteSpace LineTerminator Comment CommonToken DivPunctuator TemplateSubstitutionTail InputElementHashbangOrRegExp :: WhiteSpace LineTerminator Comment CommonToken HashbangComment RegularExpressionLiteral

12.1 Unicode Format-Control Characters

Unicode format-control characters(すなわち、LEFT-TO-RIGHT MARKやRIGHT-TO-LEFT MARKなど、Unicode Character Databaseのcategory “Cf”にあるcharacters)は、これに対するより高レベルのprotocols(mark-up languagesなど)が存在しない場合に、textの範囲のformattingを制御するために使用されるcontrol codesです。

source text内でformat-control charactersを許可することは、editingおよびdisplayを容易にするために有用です。すべてのformat control charactersは、comments内、およびstring literals、template literals、regular expression literals内で使用できます。

U+FEFF (ZERO WIDTH NO-BREAK SPACE)は、主にtextの開始時に、それがUnicodeであることをmarkし、textのencodingおよびbyte orderの検出を可能にするために使用されるformat-control characterです。この目的のために意図された<ZWNBSP> charactersは、例えばfilesを連結した結果として、textの開始後に現れることもあります。ECMAScript source textでは、<ZWNBSP> code pointsは、comments、string literals、template literals、regular expression literalsの外側ではwhite space characters(12.2を参照)として扱われます。

12.2 White Space

White space code pointsは、source textのreadabilityを向上させ、tokens(分割できないlexical units)を互いに分離するために使用されますが、それ以外では重要ではありません。White space code pointsは任意の2つのtokensの間、およびinputの開始または終了に出現できます。White space code pointsは、StringLiteralRegularExpressionLiteralTemplate、またはTemplateSubstitutionTail内に出現する場合があり、その場合literal valueの一部を形成するsignificant code pointsとみなされます。Comment内にも出現できますが、他の種類のtoken内に現れることはできません。

ECMAScript white space code pointsはTable 31に列挙されています。

Table 31: White Space Code Points
Code Points Name Abbreviation
U+0009 CHARACTER TABULATION <TAB>
U+000B LINE TABULATION <VT>
U+000C FORM FEED (FF) <FF>
U+FEFF ZERO WIDTH NO-BREAK SPACE <ZWNBSP>
general category “Space_Separator”内の任意のcode point <USP>
Note 1

U+0020 (SPACE)およびU+00A0 (NO-BREAK SPACE) code pointsは<USP>の一部です。

Note 2

Table 31に列挙されたcode pointsを除き、ECMAScript WhiteSpaceは、Unicode “White_Space” propertyを持つがgeneral category “Space_Separator”(“Zs”)に分類されないすべてのcode pointsを意図的に除外します。

Syntax

WhiteSpace :: <TAB> <VT> <FF> <ZWNBSP> <USP>

12.3 Line Terminators

white space code pointsと同様に、line terminator code pointsはsource textのreadabilityを向上させ、tokens(分割できないlexical units)を互いに分離するために使用されます。しかし、white space code pointsとは異なり、line terminatorsはsyntactic grammarの振る舞いにある程度影響します。一般に、line terminatorsは任意の2つのtokensの間に出現できますが、syntactic grammarによって禁止される場所がいくつかあります。Line terminatorsはautomatic semicolon insertion(12.10)のprocessにも影響します。line terminatorは、StringLiteralTemplate、またはTemplateSubstitutionTailを除くどのtoken内にも出現できません。<LF>および<CR> line terminatorsは、LineContinuationの一部としてでなければ、StringLiteral token内に出現できません。

line terminatorはMultiLineComment内に出現できますが、SingleLineComment内には出現できません。

Line terminatorsは、regular expressions内の\s classによってmatchされるwhite space code pointsのsetに含まれます。

ECMAScript line terminator code pointsはTable 32に列挙されています。

Table 32: Line Terminator Code Points
Code Point Unicode Name Abbreviation
U+000A LINE FEED (LF) <LF>
U+000D CARRIAGE RETURN (CR) <CR>
U+2028 LINE SEPARATOR <LS>
U+2029 PARAGRAPH SEPARATOR <PS>

Table 32内のUnicode code pointsだけがline terminatorsとして扱われます。他のnew lineまたはline breaking Unicode code pointsはline terminatorsとして扱われませんが、Table 31に列挙された要件を満たす場合はwhite spaceとして扱われます。sequence <CR><LF>は一般にline terminatorとして使用されます。line numbersを報告する目的では、これは単一のSourceCharacterとみなされるべきです。

Syntax

LineTerminator :: <LF> <CR> <LS> <PS> LineTerminatorSequence :: <LF> <CR> [lookahead ≠ <LF>] <LS> <PS> <CR> <LF>

12.4 Comments

Commentsはsingle-lineまたはmulti-lineのいずれかです。Multi-line commentsはnestできません。

single-line commentはLineTerminator code pointを除く任意のUnicode code pointを含むことができ、またtokenは常に可能な限り長くなるという一般規則があるため、single-line commentは常に// markerから行末までのすべてのcode pointsで構成されます。ただし、行末のLineTerminatorはsingle-line commentの一部とはみなされません;これはlexical grammarによって別個に認識され、syntactic grammarのためのinput elementsのstreamの一部になります。この点は非常に重要です。なぜなら、single-line commentsの有無がautomatic semicolon insertionのprocessに影響しないことを意味するからです(12.10を参照)。

Commentsはwhite spaceのように振る舞い破棄されますが、MultiLineCommentがline terminator code pointを含む場合、そのcomment全体はsyntactic grammarによるparsingの目的でLineTerminatorとみなされます。

Syntax

Comment :: MultiLineComment SingleLineComment MultiLineComment :: /* MultiLineCommentCharsopt */ MultiLineCommentChars :: MultiLineNotAsteriskChar MultiLineCommentCharsopt * PostAsteriskCommentCharsopt PostAsteriskCommentChars :: MultiLineNotForwardSlashOrAsteriskChar MultiLineCommentCharsopt * PostAsteriskCommentCharsopt MultiLineNotAsteriskChar :: SourceCharacter but not * MultiLineNotForwardSlashOrAsteriskChar :: SourceCharacter but not one of / or * SingleLineComment :: // SingleLineCommentCharsopt SingleLineCommentChars :: SingleLineCommentChar SingleLineCommentCharsopt SingleLineCommentChar :: SourceCharacter but not LineTerminator

このsectionのいくつかのproductionsには、section B.1.1でalternative definitionsが与えられています

12.5 Hashbang Comments

Hashbang Commentsはlocation-sensitiveであり、他のtypes of commentsと同様に、syntactic grammarのinput elementsのstreamから破棄されます。

Syntax

HashbangComment :: #! SingleLineCommentCharsopt

12.6 Tokens

Syntax

CommonToken :: IdentifierName PrivateIdentifier Punctuator NumericLiteral StringLiteral Template Note

DivPunctuatorRegularExpressionLiteralRightBracePunctuator、およびTemplateSubstitutionTail productionsは、CommonToken productionに含まれない追加tokensをderiveします。

12.7 Names and Keywords

IdentifierNameおよびReservedWordは、Unicode Standard Annex #31, Identifier and Pattern Syntaxに示されるDefault Identifier Syntaxに従って解釈されるtokensですが、いくつかの小さな変更があります。ReservedWordIdentifierNameのenumerated subsetです。syntactic grammarは、IdentifierReservedWordでないIdentifierNameとして定義します。Unicode identifier grammarは、Unicode Standardによって指定されるcharacter propertiesに基づいています。Unicode Standardのlatest versionにおける指定categories内のUnicode code pointsは、すべてのconforming ECMAScript implementationsによってそれらのcategoriesにあるものとして扱われなければなりません。ECMAScript implementationsは、Unicode Standardの後続editionで定義されたidentifier code pointsを認識してよいです。

Note 1

この標準は特定のcode point additionsを指定します:U+0024 (DOLLAR SIGN)およびU+005F (LOW LINE)はIdentifierName内の任意の場所で許可されます。

Syntax

PrivateIdentifier :: # IdentifierName IdentifierName :: IdentifierStart IdentifierName IdentifierPart IdentifierStart :: IdentifierStartChar \ UnicodeEscapeSequence IdentifierPart :: IdentifierPartChar \ UnicodeEscapeSequence IdentifierStartChar :: UnicodeIDStart $ _ IdentifierPartChar :: UnicodeIDContinue $ AsciiLetter :: one of a b c d e f g h i j k l m n o p q r s t u v w x y z A B C D E F G H I J K L M N O P Q R S T U V W X Y Z UnicodeIDStart :: any Unicode code point with the Unicode property “ID_Start” UnicodeIDContinue :: any Unicode code point with the Unicode property “ID_Continue”

nonterminal UnicodeEscapeSequenceの定義は12.9.4に与えられています。

Note 2

nonterminal IdentifierPartUnicodeIDContinueを介して_をderiveします。

Note 3

Unicode properties “ID_Start”および“ID_Continue”を持つcode pointsのsetsは、それぞれUnicode properties “Other_ID_Start”および“Other_ID_Continue”を持つcode pointsを含みます。

12.7.1 Identifier Names

Unicode escape sequencesはIdentifierName内で許可され、そこでUnicodeEscapeSequenceIdentifierCodePointと等しい単一のUnicode code pointに寄与します。UnicodeEscapeSequenceの前にある\はどのcode pointsにも寄与しません。UnicodeEscapeSequenceは、そうでなければinvalidとなるcode pointをIdentifierNameに寄与するために使用することはできません。言い換えれば、\ UnicodeEscapeSequence sequenceが、それが寄与するSourceCharacterで置き換えられた場合、その結果はなおvalidなIdentifierNameであり、元のIdentifierNameとまったく同じSourceCharacter elementsのsequenceを持たなければなりません。この仕様内のIdentifierNameのすべての解釈は、特定のcode pointに寄与するためにescape sequenceが使用されたかどうかにかかわらず、実際のcode pointsに基づきます。

Unicode Standardに従ってcanonically equivalentである2つのIdentifierNamesは、各UnicodeEscapeSequenceの置換後に、完全に同じcode pointsのsequenceで表されない限り、等しくありません

12.7.1.1 Static Semantics: Early Errors

IdentifierStart :: \ UnicodeEscapeSequence IdentifierPart :: \ UnicodeEscapeSequence

12.7.1.2 Static Semantics: IdentifierCodePoints

The syntax-directed operation IdentifierCodePoints takes no arguments and returns a List of code points. It is defined piecewise over the following productions:

IdentifierName :: IdentifierStart
  1. codePointIdentifierStartIdentifierCodePointとする。
  2. « codePoint »を返す。
IdentifierName :: IdentifierName IdentifierPart
  1. codePoints をderived IdentifierNameIdentifierCodePointsとする。
  2. codePointIdentifierPartIdentifierCodePointとする。
  3. codePoints と« codePoint »のlist-concatenationを返す。

12.7.1.3 Static Semantics: IdentifierCodePoint

The syntax-directed operation IdentifierCodePoint takes no arguments and returns a code point. It is defined piecewise over the following productions:

IdentifierStart :: IdentifierStartChar
  1. IdentifierStartCharによってmatchされたcode pointを返す。
IdentifierPart :: IdentifierPartChar
  1. IdentifierPartCharによってmatchされたcode pointを返す。
UnicodeEscapeSequence :: u Hex4Digits
  1. 数値がHex4DigitsのMVであるcode pointを返す。
UnicodeEscapeSequence :: u{ CodePoint }
  1. 数値がCodePointのMVであるcode pointを返す。

12.7.2 Keywords and Reserved Words

keywordIdentifierNameにmatchするtokenですが、syntactic useも持ちます;つまり、何らかのsyntactic production内に、fixed width fontでliteralに現れます。ECMAScriptのkeywordsには、ifwhileasyncawait、その他多数が含まれます。

reserved wordはidentifierとして使用できないIdentifierNameです。多くのkeywordsはreserved wordsですが、そうでないものもあり、また特定のcontextsでのみreservedであるものもあります。ifおよびwhileはreserved wordsです。awaitはasync functionsおよびmodulesの内部でのみreservedです。asyncはreservedではありません;制限なくvariable nameまたはstatement labelとして使用できます。

この仕様は、grammatical productionsとearly error rulesの組み合わせを使用して、どのnamesがvalid identifiersであり、どれがreserved wordsであるかを指定します。下のReservedWord list内のすべてのtokensは、awaitおよびyieldを除き、無条件にreservedです。awaitおよびyieldに対する例外は、parameterized syntactic productionsを使用して13.1で指定されます。最後に、いくつかのearly error rulesがvalid identifiersのsetを制限します。13.1.114.3.1.114.7.5.1、および15.7.1を参照してください。まとめると、identifier namesには5つのcategoriesがあります:

  • MathwindowtoString、および_など、常にidentifiersとして許可され、keywordsではないもの;

  • 下に列挙されるReservedWordsのうち、awaitおよびyieldを除いた、identifiersとして決して許可されないもの;

  • awaitおよびyieldという、contextuallyにidentifiersとして許可されるもの;

  • strict mode codeにおいて、contextuallyにidentifiersとして許可されないもの:letstaticimplementsinterfacepackageprivateprotected、およびpublic

  • 常にidentifiersとして許可されるが、特定のsyntactic productions内で、Identifierが許可されない場所にkeywordsとしても現れるもの:asasyncfromgetmetaofset、およびtarget

用語conditional keyword、またはcontextual keywordは、最後の3つのcategoriesに属し、したがってあるcontextsではidentifiersとして、別のcontextsではkeywordsとして使用できるkeywordsを指すために使われることがあります。

Syntax

ReservedWord :: one of await break case catch class const continue debugger default delete do else enum export extends false finally for function if import in instanceof new null return super switch this throw true try typeof var void while with yield Note 1

5.1.5に従い、grammar内のkeywordsは特定のSourceCharacter elementsのliteral sequencesにmatchします。keyword内のcode pointを\ UnicodeEscapeSequenceによって表すことはできません。

IdentifierName\ UnicodeEscapeSequencesを含むことができますが、els\u{65}と綴ることによって“else”という名前のvariableを宣言することはできません。13.1.1内のearly error rulesは、reserved wordと同じStringValueを持つidentifiersを除外します。

Note 2

enumは現在、この仕様内でkeywordとして使用されていません。これは、将来のlanguage extensionsでkeywordとして使用するために取っておかれたfuture reserved wordです。

同様に、implementsinterfacepackageprivateprotected、およびpublicstrict mode codeにおけるfuture reserved wordsです。

Note 3

names argumentsおよびevalはkeywordsではありませんが、strict mode codeではいくつかの制限を受けます。13.1.18.6.415.2.115.5.115.6.1、および15.8.1を参照してください。

12.8 Punctuators

Syntax

Punctuator :: OptionalChainingPunctuator OtherPunctuator OptionalChainingPunctuator :: ?. [lookahead ∉ DecimalDigit] OtherPunctuator :: one of { ( ) [ ] . ... ; , < > <= >= == != === !== + - * % ** ++ -- << >> >>> & | ^ ! ~ && || ?? ? : = += -= *= %= **= <<= >>= >>>= &= |= ^= &&= ||= ??= => DivPunctuator :: / /= RightBracePunctuator :: }

12.9 Literals

12.9.1 Null Literals

Syntax

NullLiteral :: null

12.9.2 Boolean Literals

Syntax

BooleanLiteral :: true false

12.9.3 Numeric Literals

Syntax

NumericLiteralSeparator :: _ NumericLiteral :: DecimalLiteral DecimalBigIntegerLiteral NonDecimalIntegerLiteral[+Sep] NonDecimalIntegerLiteral[+Sep] BigIntLiteralSuffix LegacyOctalIntegerLiteral DecimalBigIntegerLiteral :: 0 BigIntLiteralSuffix NonZeroDigit DecimalDigits[+Sep]opt BigIntLiteralSuffix NonZeroDigit NumericLiteralSeparator DecimalDigits[+Sep] BigIntLiteralSuffix NonDecimalIntegerLiteral[Sep] :: BinaryIntegerLiteral[?Sep] OctalIntegerLiteral[?Sep] HexIntegerLiteral[?Sep] BigIntLiteralSuffix :: n DecimalLiteral :: DecimalIntegerLiteral . DecimalDigits[+Sep]opt ExponentPart[+Sep]opt . DecimalDigits[+Sep] ExponentPart[+Sep]opt DecimalIntegerLiteral ExponentPart[+Sep]opt DecimalIntegerLiteral :: 0 NonZeroDigit NonZeroDigit NumericLiteralSeparatoropt DecimalDigits[+Sep] NonOctalDecimalIntegerLiteral DecimalDigits[Sep] :: DecimalDigit DecimalDigits[?Sep] DecimalDigit [+Sep] DecimalDigits[+Sep] NumericLiteralSeparator DecimalDigit DecimalDigit :: one of 0 1 2 3 4 5 6 7 8 9 NonZeroDigit :: one of 1 2 3 4 5 6 7 8 9 ExponentPart[Sep] :: ExponentIndicator SignedInteger[?Sep] ExponentIndicator :: one of e E SignedInteger[Sep] :: DecimalDigits[?Sep] + DecimalDigits[?Sep] - DecimalDigits[?Sep] BinaryIntegerLiteral[Sep] :: 0b BinaryDigits[?Sep] 0B BinaryDigits[?Sep] BinaryDigits[Sep] :: BinaryDigit BinaryDigits[?Sep] BinaryDigit [+Sep] BinaryDigits[+Sep] NumericLiteralSeparator BinaryDigit BinaryDigit :: one of 0 1 OctalIntegerLiteral[Sep] :: 0o OctalDigits[?Sep] 0O OctalDigits[?Sep] OctalDigits[Sep] :: OctalDigit OctalDigits[?Sep] OctalDigit [+Sep] OctalDigits[+Sep] NumericLiteralSeparator OctalDigit LegacyOctalIntegerLiteral :: 0 OctalDigit LegacyOctalIntegerLiteral OctalDigit NonOctalDecimalIntegerLiteral :: 0 NonOctalDigit LegacyOctalLikeDecimalIntegerLiteral NonOctalDigit NonOctalDecimalIntegerLiteral DecimalDigit LegacyOctalLikeDecimalIntegerLiteral :: 0 OctalDigit LegacyOctalLikeDecimalIntegerLiteral OctalDigit OctalDigit :: one of 0 1 2 3 4 5 6 7 NonOctalDigit :: one of 8 9 HexIntegerLiteral[Sep] :: 0x HexDigits[?Sep] 0X HexDigits[?Sep] HexDigits[Sep] :: HexDigit HexDigits[?Sep] HexDigit [+Sep] HexDigits[+Sep] NumericLiteralSeparator HexDigit HexDigit :: one of 0 1 2 3 4 5 6 7 8 9 a b c d e f A B C D E F

NumericLiteralの直後に続くSourceCharacterは、IdentifierStartまたはDecimalDigitであってはなりません。

Note

例えば:3inはerrorであり、2つのinput elements 3およびinではありません。

12.9.3.1 Static Semantics: Early Errors

NumericLiteral :: LegacyOctalIntegerLiteral DecimalIntegerLiteral :: NonOctalDecimalIntegerLiteral
  • IsStrict(this production)がtrueなら、それはSyntax Errorです。
Note
non-strict codeでは、このsyntaxはLegacyです。

12.9.3.2 Static Semantics: MV

numeric literalはNumber typeまたはBigInt typeの値を表します。

12.9.3.3 Static Semantics: NumericValue

The syntax-directed operation NumericValue takes no arguments and returns a Number or a BigInt. It is defined piecewise over the following productions:

NumericLiteral :: DecimalLiteral
  1. RoundMVResult(DecimalLiteralのMV)を返す。
NumericLiteral :: NonDecimalIntegerLiteral
  1. 𝔽(NonDecimalIntegerLiteralのMV)を返す。
NumericLiteral :: LegacyOctalIntegerLiteral
  1. 𝔽(LegacyOctalIntegerLiteralのMV)を返す。
NumericLiteral :: NonDecimalIntegerLiteral BigIntLiteralSuffix
  1. NonDecimalIntegerLiteralのMVに対するBigInt値を返す。
DecimalBigIntegerLiteral :: 0 BigIntLiteralSuffix
  1. 0を返す。
DecimalBigIntegerLiteral :: NonZeroDigit BigIntLiteralSuffix
  1. NonZeroDigitのMVに対するBigInt値を返す。
DecimalBigIntegerLiteral :: NonZeroDigit DecimalDigits BigIntLiteralSuffix NonZeroDigit NumericLiteralSeparator DecimalDigits BigIntLiteralSuffix
  1. nを、NumericLiteralSeparatorのすべての出現を除いたDecimalDigits内のcode pointsの数とする。
  2. mvを(NonZeroDigitのMV × 10n)にDecimalDigitsのMVを加えたものとする。
  3. (mv)を返す。

12.9.4 String Literals

Note 1

string literalは、single quotesまたはdouble quotesで囲まれた0個以上のUnicode code pointsです。Unicode code pointsはescape sequenceによって表すこともできます。closing quote code points、U+005C (REVERSE SOLIDUS)、U+000D (CARRIAGE RETURN)、およびU+000A (LINE FEED)を除き、すべてのcode pointsはstring literal内にliteralに現れてよいです。任意のcode pointsはescape sequenceの形式で現れてよいです。String literalsはECMAScript String valuesにevaluateされます。これらのString valuesを生成するとき、Unicode code pointsは11.1.1で定義されるようにUTF-16 encodedされます。Basic Multilingual Planeに属するcode pointsは、stringの単一のcode unit elementとしてencodedされます。それ以外のすべてのcode pointsは、stringの2つのcode unit elementsとしてencodedされます。

Syntax

StringLiteral :: " DoubleStringCharactersopt " ' SingleStringCharactersopt ' DoubleStringCharacters :: DoubleStringCharacter DoubleStringCharactersopt SingleStringCharacters :: SingleStringCharacter SingleStringCharactersopt DoubleStringCharacter :: SourceCharacter but not one of " or \ or LineTerminator <LS> <PS> \ EscapeSequence LineContinuation SingleStringCharacter :: SourceCharacter but not one of ' or \ or LineTerminator <LS> <PS> \ EscapeSequence LineContinuation LineContinuation :: \ LineTerminatorSequence EscapeSequence :: CharacterEscapeSequence 0 [lookahead ∉ DecimalDigit] LegacyOctalEscapeSequence NonOctalDecimalEscapeSequence HexEscapeSequence UnicodeEscapeSequence CharacterEscapeSequence :: SingleEscapeCharacter NonEscapeCharacter SingleEscapeCharacter :: one of ' " \ b f n r t v NonEscapeCharacter :: SourceCharacter but not one of EscapeCharacter or LineTerminator EscapeCharacter :: SingleEscapeCharacter DecimalDigit x u LegacyOctalEscapeSequence :: 0 [lookahead ∈ { 8, 9 }] NonZeroOctalDigit [lookahead ∉ OctalDigit] ZeroToThree OctalDigit [lookahead ∉ OctalDigit] FourToSeven OctalDigit ZeroToThree OctalDigit OctalDigit NonZeroOctalDigit :: OctalDigit but not 0 ZeroToThree :: one of 0 1 2 3 FourToSeven :: one of 4 5 6 7 NonOctalDecimalEscapeSequence :: one of 8 9 HexEscapeSequence :: x HexDigit HexDigit UnicodeEscapeSequence :: u Hex4Digits u{ CodePoint } Hex4Digits :: HexDigit HexDigit HexDigit HexDigit

nonterminal HexDigitの定義は12.9.3に与えられています。SourceCharacter11.1で定義されます。

Note 2

<LF>および<CR>は、空のcode points sequenceを生成するためのLineContinuationの一部としてでない限り、string literal内に現れることはできません。string literalのString値にこれらのいずれかを含める適切な方法は、\nまたは\u000Aなどのescape sequenceを使用することです。

12.9.4.1 Static Semantics: Early Errors

EscapeSequence :: LegacyOctalEscapeSequence NonOctalDecimalEscapeSequence
  • IsStrict(this production)がtrueなら、それはSyntax Errorです。
Note 1
non-strict codeでは、このsyntaxはLegacyです。
Note 2

string literalsが、それを囲むcodeをstrict modeに置くUse Strict Directiveより前に出現することは可能であり、implementationsはそのようなliteralsについて上記rulesを強制するよう注意しなければなりません。例えば、次のsource textはSyntax Errorを含みます:

function invalid() { "\7"; "use strict"; }

12.9.4.2 Static Semantics: SV

The syntax-directed operation SV takes no arguments and returns a String.

string literalはString typeの値を表します。SVは、string literalのさまざまなpartsへのrecursive applicationを通じて、string literalsに対するString valuesを生成します。このprocessの一部として、string literal内の一部のUnicode code pointsは、以下または12.9.3で説明されるように、mathematical valueを持つものとして解釈されます。

Table 33: String Single Character Escape Sequences
Escape Sequence Code Unit Value Unicode Character Name Symbol
\b 0x0008 BACKSPACE <BS>
\t 0x0009 CHARACTER TABULATION <HT>
\n 0x000A LINE FEED (LF) <LF>
\v 0x000B LINE TABULATION <VT>
\f 0x000C FORM FEED (FF) <FF>
\r 0x000D CARRIAGE RETURN (CR) <CR>
\" 0x0022 QUOTATION MARK "
\' 0x0027 APOSTROPHE '
\\ 0x005C REVERSE SOLIDUS \

12.9.4.3 Static Semantics: MV

12.9.5 Regular Expression Literals

Note 1

regular expression literalは、literalがevaluateされるたびにRegExp object(22.2を参照)へ変換されるinput elementです。program内の2つのregular expression literalsは、2つのliteralsのcontentsが同一であっても、互いに===としてcompareされることのないregular expression objectsへevaluateされます。RegExp objectは、runtimeにnew RegExpによって、またはRegExp constructorをfunctionとして呼び出すことによっても作成できます(22.2.4を参照)。

以下のproductionsはregular expression literalのsyntaxを記述し、input element scannerがregular expression literalの終端を見つけるために使用されます。RegularExpressionBodyおよびRegularExpressionFlagsを構成するsource textは、その後、より厳密なECMAScript Regular Expression grammar(22.2.1)を使用して再びparseされます。

実装は22.2.1で定義されるECMAScript Regular Expression grammarを拡張してよいですが、以下で定義されるRegularExpressionBodyおよびRegularExpressionFlags productions、またはこれらのproductionsによって使用されるproductionsを拡張してはなりません。

Syntax

RegularExpressionLiteral :: / RegularExpressionBody / RegularExpressionFlags RegularExpressionBody :: RegularExpressionFirstChar RegularExpressionChars RegularExpressionChars :: [empty] RegularExpressionChars RegularExpressionChar RegularExpressionFirstChar :: RegularExpressionNonTerminator but not one of * or \ or / or [ RegularExpressionBackslashSequence RegularExpressionClass RegularExpressionChar :: RegularExpressionNonTerminator but not one of \ or / or [ RegularExpressionBackslashSequence RegularExpressionClass RegularExpressionBackslashSequence :: \ RegularExpressionNonTerminator RegularExpressionNonTerminator :: SourceCharacter but not LineTerminator RegularExpressionClass :: [ RegularExpressionClassChars ] RegularExpressionClassChars :: [empty] RegularExpressionClassChars RegularExpressionClassChar RegularExpressionClassChar :: RegularExpressionNonTerminator but not one of ] or \ RegularExpressionBackslashSequence RegularExpressionFlags :: [empty] RegularExpressionFlags IdentifierPartChar Note 2

Regular expression literalsは空であってはなりません;空のregular expression literalを表す代わりに、code unit sequence //はsingle-line commentを開始します。空のregular expressionを指定するには、/(?:)/を使用してください。

12.9.5.1 Static Semantics: BodyText

The syntax-directed operation BodyText takes no arguments and returns source text. It is defined piecewise over the following productions:

RegularExpressionLiteral :: / RegularExpressionBody / RegularExpressionFlags
  1. RegularExpressionBodyとして認識されたsource textを返す。

12.9.5.2 Static Semantics: FlagText

The syntax-directed operation FlagText takes no arguments and returns source text. It is defined piecewise over the following productions:

RegularExpressionLiteral :: / RegularExpressionBody / RegularExpressionFlags
  1. RegularExpressionFlagsとして認識されたsource textを返す。

12.9.6 Template Literal Lexical Components

Syntax

Template :: NoSubstitutionTemplate TemplateHead NoSubstitutionTemplate :: ` TemplateCharactersopt ` TemplateHead :: ` TemplateCharactersopt ${ TemplateSubstitutionTail :: TemplateMiddle TemplateTail TemplateMiddle :: } TemplateCharactersopt ${ TemplateTail :: } TemplateCharactersopt ` TemplateCharacters :: TemplateCharacter TemplateCharactersopt TemplateCharacter :: $ [lookahead ≠ {] \ TemplateEscapeSequence \ NotEscapeSequence LineContinuation LineTerminatorSequence SourceCharacter but not one of ` or \ or $ or LineTerminator TemplateEscapeSequence :: CharacterEscapeSequence 0 [lookahead ∉ DecimalDigit] HexEscapeSequence UnicodeEscapeSequence NotEscapeSequence :: 0 DecimalDigit DecimalDigit but not 0 x [lookahead ∉ HexDigit] x HexDigit [lookahead ∉ HexDigit] u [lookahead ∉ HexDigit] [lookahead ≠ {] u HexDigit [lookahead ∉ HexDigit] u HexDigit HexDigit [lookahead ∉ HexDigit] u HexDigit HexDigit HexDigit [lookahead ∉ HexDigit] u { [lookahead ∉ HexDigit] u { NotCodePoint [lookahead ∉ HexDigit] u { CodePoint [lookahead ∉ HexDigit] [lookahead ≠ }] NotCodePoint :: HexDigits[~Sep] but only if the MV of HexDigits > 0x10FFFF CodePoint :: HexDigits[~Sep] but only if the MV of HexDigits ≤ 0x10FFFF Note

TemplateSubstitutionTailInputElementTemplateTail alternative lexical goalによって使用されます。

12.9.6.1 Static Semantics: TV

The syntax-directed operation TV takes no arguments and returns a String or undefined. template literal componentは、TVによってString typeの値として解釈されます。TVはtemplate objectのindexed components(口語的にはtemplate values)を構築するために使用されます。TVでは、escape sequencesは、escape sequenceによって表されるUnicode code pointのUTF-16 code unit(s)に置き換えられます。

12.9.6.2 Static Semantics: TRV

The syntax-directed operation TRV takes no arguments and returns a String. template literal componentは、TRVによってString typeの値として解釈されます。TRVはtemplate objectのraw components(口語的にはtemplate raw values)を構築するために使用されます。TRVはTVと似ていますが、TRVではescape sequencesがliteral内に現れたままに解釈される点が異なります。

Note

TVLineContinuationのcode unitsを除外する一方、TRVはそれらを含みます。<CR><LF>および<CR> LineTerminatorSequencesは、TVとTRVの両方について<LF>にnormalizedされます。<CR>または<CR><LF> sequenceを含めるには、明示的なTemplateEscapeSequenceが必要です。

12.10 Automatic Semicolon Insertion

ほとんどのECMAScript statementsおよびdeclarationsはsemicolonで終了しなければなりません。そのようなsemicolonsはsource text内に常に明示的に現れてよいです。しかし便宜上、そのようなsemicolonsは特定の状況ではsource textから省略されてもよいです。これらの状況は、そのような状況でsemicolonsがsource code token streamに自動的に挿入される、と述べることで説明されます。

12.10.1 Rules of Automatic Semicolon Insertion

次のrulesでは、“token”とは、clause 12で説明されるように、現在のlexical goal symbolを使用して決定される、実際に認識されたlexical tokenを意味します。

semicolon insertionには3つの基本rulesがあります:

  1. source textが左から右へparseされるとき、grammarのどのproductionによっても許可されないtoken(offending tokenと呼ばれる)に遭遇した場合、次の条件の1つ以上がtrueであれば、そのoffending tokenの前にsemicolonが自動的に挿入されます:

    • offending tokenがprevious tokenから少なくとも1つのLineTerminatorによって分離されている。
    • offending tokenが}である。
    • previous tokenが)であり、挿入されたsemicolonがdo-while statement(14.7.2)のterminating semicolonとしてparseされる。
  2. source textが左から右へparseされるとき、tokensのinput streamの終端に遭遇し、parserがinput token streamをgoal nonterminalの単一のinstanceとしてparseできない場合、input streamの終端にsemicolonが自動的に挿入されます。
  3. source textが左から右へparseされるとき、grammarのあるproductionによって許可されるtokenに遭遇したが、そのproductionがrestricted productionであり、そのtokenがrestricted production内の注釈“[no LineTerminator here]”の直後にあるterminalまたはnonterminalの最初のtokenとなる場合(したがって、そのようなtokenはrestricted tokenと呼ばれる)、かつrestricted tokenがprevious tokenから少なくとも1つのLineTerminatorによって分離されている場合、そのrestricted tokenの前にsemicolonが自動的に挿入されます。

ただし、上記rulesには追加のoverriding conditionがあります:semicolonがempty statementとしてparseされることになる場合、またはそのsemicolonがfor statement(14.7.4を参照)のheader内の2つのsemicolonsの1つになる場合、semicolonは自動的には決して挿入されません。

Note

grammar内のrestricted productionsは次のものだけです:

UpdateExpression[Yield, Await] : LeftHandSideExpression[?Yield, ?Await] [no LineTerminator here] ++ LeftHandSideExpression[?Yield, ?Await] [no LineTerminator here] -- UsingDeclaration[In, Yield, Await] : using [no LineTerminator here] BindingList[?In, ?Yield, ?Await, ~Pattern] ; ContinueStatement[Yield, Await] : continue ; continue [no LineTerminator here] LabelIdentifier[?Yield, ?Await] ; BreakStatement[Yield, Await] : break ; break [no LineTerminator here] LabelIdentifier[?Yield, ?Await] ; ReturnStatement[Yield, Await] : return ; return [no LineTerminator here] Expression[+In, ?Yield, ?Await] ; ThrowStatement[Yield, Await] : throw [no LineTerminator here] Expression[+In, ?Yield, ?Await] ; YieldExpression[In, Await] : yield yield [no LineTerminator here] AssignmentExpression[?In, +Yield, ?Await] yield [no LineTerminator here] * AssignmentExpression[?In, +Yield, ?Await] ArrowFunction[In, Yield, Await] : ArrowParameters[?Yield, ?Await] [no LineTerminator here] => ConciseBody[?In] AsyncFunctionDeclaration[Yield, Await, Default] : async [no LineTerminator here] function BindingIdentifier[?Yield, ?Await] ( FormalParameters[~Yield, +Await] ) { AsyncFunctionBody } [+Default] async [no LineTerminator here] function ( FormalParameters[~Yield, +Await] ) { AsyncFunctionBody } AsyncFunctionExpression : async [no LineTerminator here] function BindingIdentifier[~Yield, +Await]opt ( FormalParameters[~Yield, +Await] ) { AsyncFunctionBody } AsyncMethod[Yield, Await] : async [no LineTerminator here] ClassElementName[?Yield, ?Await] ( UniqueFormalParameters[~Yield, +Await] ) { AsyncFunctionBody } AsyncGeneratorDeclaration[Yield, Await, Default] : async [no LineTerminator here] function * BindingIdentifier[?Yield, ?Await] ( FormalParameters[+Yield, +Await] ) { AsyncGeneratorBody } [+Default] async [no LineTerminator here] function * ( FormalParameters[+Yield, +Await] ) { AsyncGeneratorBody } AsyncGeneratorExpression : async [no LineTerminator here] function * BindingIdentifier[+Yield, +Await]opt ( FormalParameters[+Yield, +Await] ) { AsyncGeneratorBody } AsyncGeneratorMethod[Yield, Await] : async [no LineTerminator here] * ClassElementName[?Yield, ?Await] ( UniqueFormalParameters[+Yield, +Await] ) { AsyncGeneratorBody } AsyncArrowFunction[In, Yield, Await] : async [no LineTerminator here] AsyncArrowBindingIdentifier[?Yield] [no LineTerminator here] => AsyncConciseBody[?In] CoverCallExpressionAndAsyncArrowHead[?Yield, ?Await] [no LineTerminator here] => AsyncConciseBody[?In] AsyncArrowHead : async [no LineTerminator here] ArrowFormalParameters[~Yield, +Await]

これらのrestricted productionsの実際上の効果は次のとおりです:

  • パーサが後置演算子として扱う位置で ++ または -- トークンに遭遇し、直前のトークンと ++ または -- トークンの間に少なくとも1つの LineTerminator が出現していた場合、セミコロンは ++ または -- トークンの前に自動的に挿入される。
  • using トークンに遭遇し、IdentifierName トークンの前に LineTerminator が遭遇された場合、セミコロンは using トークンの後に自動的に挿入される。
  • continuebreakreturnthrow、または yield トークンに遭遇し、次のトークンの前に LineTerminator が遭遇された場合、セミコロンは continuebreakreturnthrow、または yield トークンの後に自動的に挿入される。
  • アロー関数のパラメータが => トークンの前の LineTerminator に続く場合、セミコロンが自動的に挿入され、その区切り子は構文エラーを引き起こす。
  • async トークンの後に、functionIdentifierName、または ( トークンの前の LineTerminator が続く場合、セミコロンが自動的に挿入され、async トークンは後続のトークンと同じ式またはクラス要素の一部として扱われない。
  • async トークンの後に、* トークンの前の LineTerminator が続く場合、セミコロンが自動的に挿入され、その区切り子は構文エラーを引き起こす。

結果として、ECMAScript プログラマに対する実践的な助言は次のとおりである:

  • 後置 ++ または -- 演算子は、そのオペランドと同じ行に置かれるべきである。
  • using 宣言内の BindingList は、using トークンと同じ行で開始するべきである。
  • return または throw 文内の Expression、または yield 式内の AssignmentExpression は、returnthrow、または yield トークンと同じ行で開始するべきである。
  • break または continue 文内の LabelIdentifier は、break または continue トークンと同じ行に置かれるべきである。
  • アロー関数のパラメータの終端とその => は、同じ行に置かれるべきである。
  • 非同期関数またはメソッドの前にある async トークンは、直後に続くトークンと同じ行に置かれるべきである。

12.10.2 Examples of Automatic Semicolon Insertion

This section is non-normative.

source

{ 1 2 } 3

は、automatic semicolon insertion rulesを用いても、ECMAScript grammarにおけるvalid sentenceではありません。対照的に、source

{ 1
2 } 3

もvalidなECMAScript sentenceではありませんが、automatic semicolon insertionによって次のように変換されます:

{ 1
;2 ;} 3;

これはvalidなECMAScript sentenceです。

source

for (a; b
)

はvalidなECMAScript sentenceではなく、automatic semicolon insertionによって変更されません。なぜなら、semicolonはfor statementのheaderに必要だからです。Automatic semicolon insertionは、for statementのheader内の2つのsemicolonsの1つを決して挿入しません。

source

return
a + b

はautomatic semicolon insertionによって次のように変換されます:

return;
a + b;
Note 1

LineTerminatorがexpression a + bをtoken returnから分離しているため、expression a + breturn statementによって返される値として扱われません。

source

a = b
++c

はautomatic semicolon insertionによって次のように変換されます:

a = b;
++c;
Note 2

++ tokenは、variable bに適用されるpostfix operatorとして扱われません。なぜなら、b++の間にLineTerminatorが出現するからです。

source

if (a > b)
else c = d

はvalidなECMAScript sentenceではなく、その時点でgrammarのどのproductionも適用されないにもかかわらず、else tokenの前にautomatic semicolon insertionによって変更されません。なぜなら、自動的に挿入されたsemicolonはempty statementとしてparseされることになるからです。

source

a = b + c
(d + e).print()

はautomatic semicolon insertionによって変換されません。なぜなら、2行目を開始するparenthesized expressionはfunction callのargument listとして解釈できるからです:

a = b + c(d + e).print()

assignment statementがleft parenthesisで開始しなければならない状況では、programmerはautomatic semicolon insertionに頼るのではなく、preceding statementの終端に明示的なsemicolonを提供することがよい考えです。

12.10.3 Interesting Cases of Automatic Semicolon Insertion

This section is non-normative.

ECMAScript programsは、automatic semicolon insertionに頼ることで、非常に少ないsemicolonsのstyleで書くことができます。上で説明したように、semicolonsはすべてのnewlineで挿入されるわけではなく、automatic semicolon insertionはline terminatorsをまたいだ複数のtokensに依存する場合があります。

新しいsyntactic featuresがECMAScriptに追加されるにつれて、その前でautomatic semicolon insertionに頼っている行がparseされるときにgrammar productionsを変更させる追加grammar productionsが追加される可能性があります。

このsectionの目的では、automatic semicolon insertionのcaseは、その前にあるsource textに応じてsemicolonが挿入される場合もされない場合もある場所であるなら、interestingとみなされます。このsectionの残りでは、このversion of ECMAScriptにおけるautomatic semicolon insertionのいくつかのinteresting casesを説明します。

12.10.3.1 Interesting Cases of Automatic Semicolon Insertion in Statement Lists

StatementListでは、多くのStatementListItemsはsemicolonsで終わり、automatic semicolon insertionを使用して省略される場合があります。上記rulesの帰結として、expressionで終わる行の終端では、次の行が以下のいずれかで始まる場合、semicolonが必要です:

  • opening parenthesis((。semicolonがない場合、2つの行は一緒にCallExpressionとして扱われます。
  • opening square bracket([。semicolonがない場合、2つの行はArrayLiteralまたはArrayAssignmentPatternではなくproperty accessとして扱われます。
  • template literal(`。semicolonがない場合、2つの行は、previous expressionをMemberExpressionとするtagged Template(13.3.11)として解釈されます。
  • Unary +または-。semicolonがない場合、2つの行は対応するbinary operatorの使用として解釈されます。
  • RegExp literal。semicolonがない場合、2つの行は、例えばRegExpにflagsがある場合、代わりに/ MultiplicativeOperatorとしてparseされる可能性があります。

12.10.3.2 Cases of Automatic Semicolon Insertion and “[no LineTerminator here]”

This section is non-normative.

ECMAScriptには、“[no LineTerminator here]”を含むgrammar productionsがあります。これらのproductionsは、grammar内にoptional operandsを持つための手段である場合があります。これらの場所にLineTerminatorを導入すると、optional operandを持たないgrammar productionを使用することにより、source textのgrammar productionが変更されます。

このsectionの残りでは、このversion of ECMAScriptで“[no LineTerminator here]”を使用するいくつかのproductionsを説明します。

12.10.3.2.1 List of Grammar Productions with Optional Operands and “[no LineTerminator here]”

13 ECMAScript Language: Expressions

13.1 Identifiers

Syntax

IdentifierReference[Yield, Await] : Identifier [~Yield] yield [~Await] await BindingIdentifier[Yield, Await] : Identifier yield await LabelIdentifier[Yield, Await] : Identifier [~Yield] yield [~Await] await Identifier : IdentifierName but not ReservedWord Note

yieldおよびawaitはgrammar内でBindingIdentifierとして許可され、以下のstatic semanticsで禁止されます。これは、次のような場合にautomatic semicolon insertionを禁止するためです

let
await 0;

13.1.1 Static Semantics: Early Errors

BindingIdentifier : Identifier
  • IsStrict(this production)がtrueであり、かつIdentifierStringValue"arguments"または"eval"のいずれかである場合、それはSyntax Errorです。
IdentifierReference : yield BindingIdentifier : yield LabelIdentifier : yield
  • IsStrict(this production)がtrueなら、それはSyntax Errorです。
IdentifierReference : await BindingIdentifier : await LabelIdentifier : await BindingIdentifier[Yield, Await] : yield
  • このproductionが[Yield] parameterを持つ場合、それはSyntax Errorです。
BindingIdentifier[Yield, Await] : await
  • このproductionが[Await] parameterを持つ場合、それはSyntax Errorです。
IdentifierReference[Yield, Await] : Identifier BindingIdentifier[Yield, Await] : Identifier LabelIdentifier[Yield, Await] : Identifier
  • このproductionが[Yield] parameterを持ち、かつIdentifierStringValue"yield"である場合、それはSyntax Errorです。
  • このproductionが[Await] parameterを持ち、かつIdentifierStringValue"await"である場合、それはSyntax Errorです。
Identifier : IdentifierName but not ReservedWord Note

IdentifierNameStringValueIdentifierName内の任意のUnicode escape sequencesをnormalizeするため、そのようなescapesを使用して、code point sequenceがReservedWordと同じであるIdentifierを書くことはできません。

13.1.2 Static Semantics: StringValue

The syntax-directed operation StringValue takes no arguments and returns a String. It is defined piecewise over the following productions:

IdentifierName :: IdentifierStart IdentifierName IdentifierPart
  1. idTextUnescapedIdentifierNameIdentifierCodePointsとする。
  2. CodePointsToString(idTextUnescaped)を返す。
IdentifierReference : yield BindingIdentifier : yield LabelIdentifier : yield
  1. "yield"を返す。
IdentifierReference : await BindingIdentifier : await LabelIdentifier : await
  1. "await"を返す。
Identifier : IdentifierName but not ReservedWord
  1. IdentifierNameStringValueを返す。
PrivateIdentifier :: # IdentifierName
  1. 0x0023 (NUMBER SIGN)とIdentifierNameStringValuestring-concatenationを返す。
ModuleExportName : StringLiteral
  1. StringLiteralSVを返す。

13.1.3 Runtime Semantics: Evaluation

IdentifierReference : Identifier
  1. ResolveBinding(IdentifierStringValue)を返す。
IdentifierReference : yield
  1. ResolveBinding("yield")を返す。
IdentifierReference : await
  1. ResolveBinding("await")を返す。
Note 1

IdentifierReferenceを評価した結果は常にReference型の値です。

Note 2

non-strict codeでは、keyword yieldをidentifierとして使用できます。IdentifierReferenceを評価すると、yieldIdentifierであったかのように、そのbindingがresolveされます。Early Error restrictionにより、そのような評価はnon-strict codeでのみ発生し得ることが保証されます。

13.2 Primary Expression

Syntax

PrimaryExpression[Yield, Await] : this IdentifierReference[?Yield, ?Await] Literal ArrayLiteral[?Yield, ?Await] ObjectLiteral[?Yield, ?Await] FunctionExpression ClassExpression[?Yield, ?Await] GeneratorExpression AsyncFunctionExpression AsyncGeneratorExpression RegularExpressionLiteral TemplateLiteral[?Yield, ?Await, ~Tagged] CoverParenthesizedExpressionAndArrowParameterList[?Yield, ?Await] CoverParenthesizedExpressionAndArrowParameterList[Yield, Await] : ( Expression[+In, ?Yield, ?Await] ) ( Expression[+In, ?Yield, ?Await] , ) ( ) ( ... BindingIdentifier[?Yield, ?Await] ) ( ... BindingPattern[?Yield, ?Await] ) ( Expression[+In, ?Yield, ?Await] , ... BindingIdentifier[?Yield, ?Await] ) ( Expression[+In, ?Yield, ?Await] , ... BindingPattern[?Yield, ?Await] )

Supplemental Syntax

production
PrimaryExpression[Yield, Await] : CoverParenthesizedExpressionAndArrowParameterList[?Yield, ?Await]
のinstanceを処理するとき、CoverParenthesizedExpressionAndArrowParameterListのinterpretationは次のgrammarを使用してrefineされます:

ParenthesizedExpression[Yield, Await] : ( Expression[+In, ?Yield, ?Await] )

13.2.1 The this Keyword

13.2.1.1 Runtime Semantics: Evaluation

PrimaryExpression : this
  1. ResolveThisBinding()を返す。

13.2.2 Identifier Reference

IdentifierReferenceについては13.1を参照してください。

13.2.3 Literals

Syntax

Literal : NullLiteral BooleanLiteral NumericLiteral StringLiteral

13.2.3.1 Runtime Semantics: Evaluation

Literal : NullLiteral
  1. nullを返す。
Literal : BooleanLiteral
  1. BooleanLiteralがtoken falseなら、falseを返す。
  2. BooleanLiteralがtoken trueなら、trueを返す。
Literal : NumericLiteral
  1. 12.9.3で定義されるNumericLiteralNumericValueを返す。
Literal : StringLiteral
  1. 12.9.4.2で定義されるStringLiteralSVを返す。

13.2.4 Array Initializer

Note

ArrayLiteralは、square bracketsで囲まれた、array elementを表す0個以上のexpressionsのlistを使用して、Arrayのinitializationを記述するexpressionです。elementsはliteralsである必要はありません;それらはarray initializerが評価されるたびに評価されます。

Array elementsはelement listのbeginning、middle、またはendでelideされる場合があります。element list内のcommaの直前にAssignmentExpressionがない場合(すなわち、beginningのcomma、または別のcommaの後のcomma)、missing array elementはArrayのlengthに寄与し、後続elementsのindexを増加させます。Elided array elementsは定義されません。arrayのendでelementがelideされる場合、そのelementはArrayのlengthに寄与しません。

Syntax

ArrayLiteral[Yield, Await] : [ Elisionopt ] [ ElementList[?Yield, ?Await] ] [ ElementList[?Yield, ?Await] , Elisionopt ] ElementList[Yield, Await] : Elisionopt AssignmentExpression[+In, ?Yield, ?Await] Elisionopt SpreadElement[?Yield, ?Await] ElementList[?Yield, ?Await] , Elisionopt AssignmentExpression[+In, ?Yield, ?Await] ElementList[?Yield, ?Await] , Elisionopt SpreadElement[?Yield, ?Await] Elision : , Elision , SpreadElement[Yield, Await] : ... AssignmentExpression[+In, ?Yield, ?Await]

13.2.4.1 Runtime Semantics: ArrayAccumulation

The syntax-directed operation ArrayAccumulation takes arguments array (an Array) and nextIndex (an integer) and returns either a normal completion containing an integer or an abrupt completion. It is defined piecewise over the following productions:

Elision : ,
  1. lengthnextIndex + 1とする。
  2. Set(array, "length", 𝔽(length), true)を実行する。
  3. NOTE: 上記stepは、lengthが232 - 1を超える場合にthrowする。
  4. lengthを返す。
Elision : Elision ,
  1. 引数arrayおよび(nextIndex + 1)を伴うElisionの ? ArrayAccumulationを返す。
ElementList : Elisionopt AssignmentExpression
  1. Elisionが存在するなら、
    1. nextIndexを、引数arrayおよびnextIndexを伴うElisionの ? ArrayAccumulationに設定する。
  2. initResultAssignmentExpressionの ? Evaluationとする。
  3. initValueを ? GetValue(initResult) とする。
  4. CreateDataPropertyOrThrow(array, ! ToString(𝔽(nextIndex)), initValue)を実行する。
  5. nextIndex + 1を返す。
ElementList : Elisionopt SpreadElement
  1. Elisionが存在するなら、
    1. nextIndexを、引数arrayおよびnextIndexを伴うElisionの ? ArrayAccumulationに設定する。
  2. 引数arrayおよびnextIndexを伴うSpreadElementの ? ArrayAccumulationを返す。
ElementList : ElementList , Elisionopt AssignmentExpression
  1. nextIndexを、引数arrayおよびnextIndexを伴うderived ElementListの ? ArrayAccumulationに設定する。
  2. Elisionが存在するなら、
    1. nextIndexを、引数arrayおよびnextIndexを伴うElisionの ? ArrayAccumulationに設定する。
  3. initResultAssignmentExpressionの ? Evaluationとする。
  4. initValueを ? GetValue(initResult) とする。
  5. CreateDataPropertyOrThrow(array, ! ToString(𝔽(nextIndex)), initValue)を実行する。
  6. nextIndex + 1を返す。
ElementList : ElementList , Elisionopt SpreadElement
  1. nextIndexを、引数arrayおよびnextIndexを伴うderived ElementListの ? ArrayAccumulationに設定する。
  2. Elisionが存在するなら、
    1. nextIndexを、引数arrayおよびnextIndexを伴うElisionの ? ArrayAccumulationに設定する。
  3. 引数arrayおよびnextIndexを伴うSpreadElementの ? ArrayAccumulationを返す。
SpreadElement : ... AssignmentExpression
  1. spreadRefAssignmentExpressionの ? Evaluationとする。
  2. spreadObjを ? GetValue(spreadRef) とする。
  3. iteratorRecordを ? GetIterator(spreadObj, sync) とする。
  4. 繰り返す
    1. nextを ? IteratorStepValue(iteratorRecord) とする。
    2. nextdoneなら、nextIndexを返す。
    3. CreateDataPropertyOrThrow(array, ! ToString(𝔽(nextIndex)), next)を実行する。
    4. nextIndexnextIndex + 1に設定する。
Note

CreateDataPropertyOrThrowは、standard built-in Array prototype object[[Set]]を使用した新しいown propertiesの作成を妨げるような方法で変更されている場合でも、arrayにown propertiesが定義されることを保証するために使用されます。

13.2.4.2 Runtime Semantics: Evaluation

ArrayLiteral : [ Elisionopt ]
  1. arrayを ! ArrayCreate(0) とする。
  2. Elisionが存在するなら、
    1. 引数arrayおよび0を伴うElisionの ? ArrayAccumulationを実行する。
  3. arrayを返す。
ArrayLiteral : [ ElementList ]
  1. arrayを ! ArrayCreate(0) とする。
  2. 引数arrayおよび0を伴うElementListの ? ArrayAccumulationを実行する。
  3. arrayを返す。
ArrayLiteral : [ ElementList , Elisionopt ]
  1. arrayを ! ArrayCreate(0) とする。
  2. nextIndexを、引数arrayおよび0を伴うElementListの ? ArrayAccumulationとする。
  3. Elisionが存在するなら、
    1. 引数arrayおよびnextIndexを伴うElisionの ? ArrayAccumulationを実行する。
  4. arrayを返す。

13.2.5 Object Initializer

Note 1

object initializerは、literalに似た形式で書かれた、Objectのinitializationを記述するexpressionです。これは、curly bracketsで囲まれた、0個以上のproperty keysと関連valuesのpairsのlistです。valuesはliteralsである必要はありません;それらはobject initializerが評価されるたびに評価されます。

Syntax

ObjectLiteral[Yield, Await] : { } { PropertyDefinitionList[?Yield, ?Await] } { PropertyDefinitionList[?Yield, ?Await] , } PropertyDefinitionList[Yield, Await] : PropertyDefinition[?Yield, ?Await] PropertyDefinitionList[?Yield, ?Await] , PropertyDefinition[?Yield, ?Await] PropertyDefinition[Yield, Await] : IdentifierReference[?Yield, ?Await] CoverInitializedName[?Yield, ?Await] PropertyName[?Yield, ?Await] : AssignmentExpression[+In, ?Yield, ?Await] MethodDefinition[?Yield, ?Await] ... AssignmentExpression[+In, ?Yield, ?Await] PropertyName[Yield, Await] : LiteralPropertyName ComputedPropertyName[?Yield, ?Await] LiteralPropertyName : IdentifierName StringLiteral NumericLiteral ComputedPropertyName[Yield, Await] : [ AssignmentExpression[+In, ?Yield, ?Await] ] CoverInitializedName[Yield, Await] : IdentifierReference[?Yield, ?Await] Initializer[+In, ?Yield, ?Await] Initializer[In, Yield, Await] : = AssignmentExpression[?In, ?Yield, ?Await] Note 2

MethodDefinition15.4で定義されます。

Note 3

特定のcontextsでは、ObjectLiteralはより制限されたsecondary grammarのcover grammarとして使用されます。CoverInitializedName productionは、これらのsecondary grammarsを完全にcoverするために必要です。ただし、このproductionの使用は、実際のObjectLiteralが期待されるnormal contextsではearly Syntax Errorをもたらします。

13.2.5.1 Static Semantics: Early Errors

PropertyDefinition : MethodDefinition

実際のobject initializerを記述することに加えて、ObjectLiteral productionsはObjectAssignmentPatternのcover grammarとしても使用され、CoverParenthesizedExpressionAndArrowParameterListの一部として認識される場合があります。ObjectAssignmentPatternが必要なcontextにObjectLiteralが現れる場合、次のEarly Error rulesは適用されません。さらに、それらはCoverParenthesizedExpressionAndArrowParameterListまたはCoverCallExpressionAndAsyncArrowHeadを最初にparseするときにも適用されません。

PropertyDefinition : CoverInitializedName
  • 任意のsource textがこのproductionによってmatchされる場合、それはSyntax Errorです。
Note 1

このproductionは、ObjectLiteralObjectAssignmentPatternのcover grammarとして機能できるように存在します。これは実際のobject initializer内では出現できません。

ObjectLiteral : { PropertyDefinitionList } { PropertyDefinitionList , } Note 2

PropertyNameListによって返されるListには、ComputedPropertyNameを使用して定義されたproperty namesは含まれません。

13.2.5.2 Static Semantics: IsComputedPropertyKey

The syntax-directed operation IsComputedPropertyKey takes no arguments and returns a Boolean. It is defined piecewise over the following productions:

PropertyName : LiteralPropertyName
  1. falseを返す。
PropertyName : ComputedPropertyName
  1. trueを返す。

13.2.5.3 Static Semantics: PropertyDefinitionNodes

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

ObjectLiteral : { }
  1. 新しい空のListを返す。
PropertyDefinitionList : PropertyDefinition
  1. « PropertyDefinition »を返す。
PropertyDefinitionList : PropertyDefinitionList , PropertyDefinition
  1. headをderived PropertyDefinitionListPropertyDefinitionNodesとする。
  2. headと« PropertyDefinition »のlist-concatenationを返す。

13.2.5.4 Static Semantics: PropertyNameList

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

PropertyDefinitionList : PropertyDefinition
  1. propertyNamePropertyDefinitionPropNameとする。
  2. propertyNameemptyなら、新しい空のListを返す。
  3. « propertyName »を返す。
PropertyDefinitionList : PropertyDefinitionList , PropertyDefinition
  1. listPropertyDefinitionListPropertyNameListとする。
  2. propertyNamePropertyDefinitionPropNameとする。
  3. propertyNameemptyなら、listを返す。
  4. listと« propertyName »のlist-concatenationを返す。

13.2.5.5 Runtime Semantics: Evaluation

ObjectLiteral : { }
  1. OrdinaryObjectCreate(%Object.prototype%)を返す。
ObjectLiteral : { PropertyDefinitionList } { PropertyDefinitionList , }
  1. objOrdinaryObjectCreate(%Object.prototype%)とする。
  2. 引数objを伴うPropertyDefinitionListの ? PropertyDefinitionEvaluationを実行する。
  3. objを返す。
LiteralPropertyName : IdentifierName
  1. IdentifierNameStringValueを返す。
LiteralPropertyName : StringLiteral
  1. StringLiteralSVを返す。
LiteralPropertyName : NumericLiteral
  1. numberNumericLiteralNumericValueとする。
  2. ToString(number)を返す。
ComputedPropertyName : [ AssignmentExpression ]
  1. exprValueAssignmentExpressionの ? Evaluationとする。
  2. propertyNameを ? GetValue(exprValue) とする。
  3. ToPropertyKey(propertyName)を返す。

13.2.5.6 Runtime Semantics: PropertyDefinitionEvaluation

The syntax-directed operation PropertyDefinitionEvaluation takes argument obj (an Object) and returns either a normal completion containing unused or an abrupt completion. It is defined piecewise over the following productions:

PropertyDefinitionList : PropertyDefinitionList , PropertyDefinition
  1. 引数objを伴うPropertyDefinitionListの ? PropertyDefinitionEvaluationを実行する。
  2. 引数objを伴うPropertyDefinitionの ? PropertyDefinitionEvaluationを実行する。
  3. unusedを返す。
PropertyDefinition : ... AssignmentExpression
  1. exprValueAssignmentExpressionの ? Evaluationとする。
  2. fromValueを ? GetValue(exprValue) とする。
  3. excludedNamesを新しい空のListとする。
  4. CopyDataProperties(obj, fromValue, excludedNames)を実行する。
  5. unusedを返す。
PropertyDefinition : IdentifierReference
  1. propertyNameIdentifierReferenceStringValueとする。
  2. exprValueIdentifierReferenceの ? Evaluationとする。
  3. propertyValueを ? GetValue(exprValue) とする。
  4. Assert: objはordinaryでextensibleなobjectであり、non-configurable propertiesを持たない。
  5. CreateDataPropertyOrThrow(obj, propertyName, propertyValue)を実行する。
  6. unusedを返す。
PropertyDefinition : PropertyName : AssignmentExpression
  1. propertyKeyPropertyNameの ? Evaluationとする。
  2. このPropertyDefinitionParseJSONのために評価されているScript内に含まれるなら(ParseJSONのstep 6を参照)、
    1. isProtoSetterfalseとする。
  3. そうでなく、propertyKey"__proto__"であり、かつPropertyNameIsComputedPropertyKeyfalseなら、
    1. isProtoSettertrueとする。
  4. そうでなければ、
    1. isProtoSetterfalseとする。
  5. IsAnonymousFunctionDefinition(AssignmentExpression)がtrueであり、かつisProtoSetterfalseなら、
    1. propertyValueを、引数propertyKeyを伴うAssignmentExpressionの ? NamedEvaluationとする。
  6. そうでなければ、
    1. exprValueRefAssignmentExpressionの ? Evaluationとする。
    2. propertyValueを ? GetValue(exprValueRef) とする。
  7. isProtoSettertrueなら、
    1. propertyValueがObjectまたはpropertyValuenullなら、
      1. obj.[[SetPrototypeOf]](propertyValue)を実行する。
    2. unusedを返す。
  8. Assert: objはordinaryでextensibleなobjectであり、non-configurable propertiesを持たない。
  9. CreateDataPropertyOrThrow(obj, propertyKey, propertyValue)を実行する。
  10. unusedを返す。
PropertyDefinition : MethodDefinition
  1. 引数objおよびtrueを伴うMethodDefinitionの ? MethodDefinitionEvaluationを実行する。
  2. unusedを返す。

13.2.6 Function Defining Expressions

PrimaryExpression : FunctionExpression については15.2を参照してください。

PrimaryExpression : GeneratorExpression については15.5を参照してください。

PrimaryExpression : ClassExpression については15.7を参照してください。

PrimaryExpression : AsyncFunctionExpression については15.8を参照してください。

PrimaryExpression : AsyncGeneratorExpression については15.6を参照してください。

13.2.7 Regular Expression Literals

Syntax

12.9.5を参照してください。

13.2.7.1 Static Semantics: Early Errors

PrimaryExpression : RegularExpressionLiteral

13.2.7.2 Static Semantics: IsValidRegularExpressionLiteral ( literal )

The abstract operation IsValidRegularExpressionLiteral takes argument literal (a RegularExpressionLiteral Parse Node) and returns a Boolean. これは、そのargumentがvalid regular expression literalであるかどうかを決定します。 It performs the following steps when called:

  1. flagsliteralFlagTextとする。
  2. flagsdgimsuv、またはy以外のcode pointsを含むなら、falseを返す。
  3. flagsが任意のcode pointを複数回含むなら、falseを返す。
  4. flagsuを含むなら、utrueとする;そうでなければ、ufalseとする。
  5. flagsvを含むなら、vtrueとする;そうでなければ、vfalseとする。
  6. patternTextliteralBodyTextとする。
  7. ufalseであり、かつvfalseなら、
    1. stringValueCodePointsToString(patternText)とする。
    2. patternTextを、stringValueの16-bit elementsのそれぞれをUnicode BMP code pointとして解釈した結果となるcode pointsのsequenceに設定する。UTF-16 decodingはelementsに適用されない。
  8. parseResultParsePattern(patternText, u, v)とする。
  9. parseResultParse Nodeなら、trueを返す。
  10. falseを返す。

13.2.7.3 Runtime Semantics: Evaluation

PrimaryExpression : RegularExpressionLiteral
  1. patternCodePointsToString(RegularExpressionLiteralBodyText)とする。
  2. flagsCodePointsToString(RegularExpressionLiteralFlagText)とする。
  3. RegExpCreate(pattern, flags)を返す。

13.2.8 Template Literals

Syntax

TemplateLiteral[Yield, Await, Tagged] : NoSubstitutionTemplate SubstitutionTemplate[?Yield, ?Await, ?Tagged] SubstitutionTemplate[Yield, Await, Tagged] : TemplateHead Expression[+In, ?Yield, ?Await] TemplateSpans[?Yield, ?Await, ?Tagged] TemplateSpans[Yield, Await, Tagged] : TemplateTail TemplateMiddleList[?Yield, ?Await, ?Tagged] TemplateTail TemplateMiddleList[Yield, Await, Tagged] : TemplateMiddle Expression[+In, ?Yield, ?Await] TemplateMiddleList[?Yield, ?Await, ?Tagged] TemplateMiddle Expression[+In, ?Yield, ?Await]

13.2.8.1 Static Semantics: Early Errors

TemplateLiteral[Yield, Await, Tagged] : NoSubstitutionTemplate TemplateLiteral[Yield, Await, Tagged] : SubstitutionTemplate[?Yield, ?Await, ?Tagged] SubstitutionTemplate[Yield, Await, Tagged] : TemplateHead Expression[+In, ?Yield, ?Await] TemplateSpans[?Yield, ?Await, ?Tagged] TemplateSpans[Yield, Await, Tagged] : TemplateTail TemplateMiddleList[Yield, Await, Tagged] : TemplateMiddle Expression[+In, ?Yield, ?Await] TemplateMiddleList[?Yield, ?Await, ?Tagged] TemplateMiddle Expression[+In, ?Yield, ?Await]

13.2.8.2 Static Semantics: TemplateStrings

The syntax-directed operation TemplateStrings takes argument raw (a Boolean) and returns a List of either Strings or undefined. It is defined piecewise over the following productions:

TemplateLiteral : NoSubstitutionTemplate
  1. « TemplateString(NoSubstitutionTemplate, raw) »を返す。
SubstitutionTemplate : TemplateHead Expression TemplateSpans
  1. headを« TemplateString(TemplateHead, raw) »とする。
  2. tailを、argument rawを伴うTemplateSpansTemplateStringsとする。
  3. headtaillist-concatenationを返す。
TemplateSpans : TemplateTail
  1. « TemplateString(TemplateTail, raw) »を返す。
TemplateSpans : TemplateMiddleList TemplateTail
  1. middleを、argument rawを伴うTemplateMiddleListTemplateStringsとする。
  2. tailを« TemplateString(TemplateTail, raw) »とする。
  3. middletaillist-concatenationを返す。
TemplateMiddleList : TemplateMiddle Expression
  1. « TemplateString(TemplateMiddle, raw) »を返す。
TemplateMiddleList : TemplateMiddleList TemplateMiddle Expression
  1. frontを、argument rawを伴うTemplateMiddleListTemplateStringsとする。
  2. lastを« TemplateString(TemplateMiddle, raw) »とする。
  3. frontlastlist-concatenationを返す。

13.2.8.3 Static Semantics: TemplateString ( templateToken, raw )

The abstract operation TemplateString takes arguments templateToken (a NoSubstitutionTemplate Parse Node, a TemplateHead Parse Node, a TemplateMiddle Parse Node, or a TemplateTail Parse Node) and raw (a Boolean) and returns a String or undefined. It performs the following steps when called:

  1. rawtrueなら、
    1. stringtemplateTokenTRVとする。
  2. そうでなければ、
    1. stringtemplateTokenTVとする。
  3. stringを返す。
Note

このoperationは、rawfalseであり、かつtemplateTokenNotEscapeSequenceを含む場合、undefinedを返します。それ以外の場合、Stringを返します。

13.2.8.4 GetTemplateObject ( templateLiteral )

The abstract operation GetTemplateObject takes argument templateLiteral (a Parse Node) and returns an Array. It performs the following steps when called:

  1. realmcurrent Realm Recordとする。
  2. templateRegistryrealm.[[TemplateMap]]とする。
  3. templateRegistryの各要素elementについて、以下を行う
    1. element.[[Site]]templateLiteral同じParse Nodeなら、
      1. element.[[Array]]を返す。
  4. rawStringsを、argument trueを伴うtemplateLiteralTemplateStringsとする。
  5. Assert: rawStringsはStringsのListである。
  6. cookedStringsを、argument falseを伴うtemplateLiteralTemplateStringsとする。
  7. countList cookedStrings内のelements数とする。
  8. Assert: count ≤ 232 - 1.
  9. templateを ! ArrayCreate(count) とする。
  10. rawObjを ! ArrayCreate(count) とする。
  11. indexを0とする。
  12. index < countである間、繰り返す
    1. propertyKeyを ! ToString(𝔽(index)) とする。
    2. cookedValuecookedStrings[index]とする。
    3. DefinePropertyOrThrow(template, propertyKey, PropertyDescriptor { [[Value]]: cookedValue, [[Writable]]: false, [[Enumerable]]: true, [[Configurable]]: false })を実行する。
    4. rawValueをString値rawStrings[index]とする。
    5. DefinePropertyOrThrow(rawObj, propertyKey, PropertyDescriptor { [[Value]]: rawValue, [[Writable]]: false, [[Enumerable]]: true, [[Configurable]]: false })を実行する。
    6. indexindex + 1に設定する。
  13. SetIntegrityLevel(rawObj, frozen)を実行する。
  14. DefinePropertyOrThrow(template, "raw", PropertyDescriptor { [[Value]]: rawObj, [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false })を実行する。
  15. SetIntegrityLevel(template, frozen)を実行する。
  16. Record { [[Site]]: templateLiteral, [[Array]]: template }をrealm.[[TemplateMap]]へappendする。
  17. templateを返す。
Note 1

template objectの作成はabrupt completionをもたらすことはありません。

Note 2

realmのprogram code内の各TemplateLiteralには、tagged Templates(13.2.8.6)のevaluationで使用される一意なtemplate objectが関連付けられます。template objectsはfrozenであり、特定のtagged Templateが評価されるたびに同じtemplate objectが使用されます。template objectsがTemplateLiteralの初回評価時にlazilyに作成されるか、初回評価前にeagerlyに作成されるかは、ECMAScript codeから観測できないimplementation choiceです。

Note 3

この仕様の将来のeditionsでは、template objectsの追加non-enumerable propertiesを定義する場合があります。

13.2.8.5 Runtime Semantics: SubstitutionEvaluation

The syntax-directed operation SubstitutionEvaluation takes no arguments and returns either a normal completion containing a List of ECMAScript language values or an abrupt completion. It is defined piecewise over the following productions:

TemplateSpans : TemplateTail
  1. 新しい空のListを返す。
TemplateSpans : TemplateMiddleList TemplateTail
  1. TemplateMiddleListの ? SubstitutionEvaluationを返す。
TemplateMiddleList : TemplateMiddle Expression
  1. subRefExpressionの ? Evaluationとする。
  2. subを ? GetValue(subRef) とする。
  3. « sub »を返す。
TemplateMiddleList : TemplateMiddleList TemplateMiddle Expression
  1. precedingTemplateMiddleListの ? SubstitutionEvaluationとする。
  2. nextRefExpressionの ? Evaluationとする。
  3. nextを ? GetValue(nextRef) とする。
  4. precedingと« next »のlist-concatenationを返す。

13.2.8.6 Runtime Semantics: Evaluation

TemplateLiteral : NoSubstitutionTemplate
  1. 12.9.6で定義されるNoSubstitutionTemplateTVを返す。
SubstitutionTemplate : TemplateHead Expression TemplateSpans
  1. head12.9.6で定義されるTemplateHeadTVとする。
  2. subRefExpressionの ? Evaluationとする。
  3. subを ? GetValue(subRef) とする。
  4. middleを ? ToString(sub) とする。
  5. tailTemplateSpansの ? Evaluationとする。
  6. headmiddle、およびtailstring-concatenationを返す。
Note 1

Expression値に適用されるstring conversion semanticsは、+ operatorではなくString.prototype.concatに似ています。

TemplateSpans : TemplateTail
  1. 12.9.6で定義されるTemplateTailTVを返す。
TemplateSpans : TemplateMiddleList TemplateTail
  1. headTemplateMiddleListの ? Evaluationとする。
  2. tail12.9.6で定義されるTemplateTailTVとする。
  3. headtailstring-concatenationを返す。
TemplateMiddleList : TemplateMiddle Expression
  1. head12.9.6で定義されるTemplateMiddleTVとする。
  2. subRefExpressionの ? Evaluationとする。
  3. subを ? GetValue(subRef) とする。
  4. middleを ? ToString(sub) とする。
  5. headmiddlestring-concatenationを返す。
Note 2

Expression値に適用されるstring conversion semanticsは、+ operatorではなくString.prototype.concatに似ています。

TemplateMiddleList : TemplateMiddleList TemplateMiddle Expression
  1. restTemplateMiddleListの ? Evaluationとする。
  2. middle12.9.6で定義されるTemplateMiddleTVとする。
  3. subRefExpressionの ? Evaluationとする。
  4. subを ? GetValue(subRef) とする。
  5. lastを ? ToString(sub) とする。
  6. restmiddle、およびlaststring-concatenationを返す。
Note 3

Expression値に適用されるstring conversion semanticsは、+ operatorではなくString.prototype.concatに似ています。

13.2.9 The Grouping Operator

13.2.9.1 Static Semantics: Early Errors

PrimaryExpression : CoverParenthesizedExpressionAndArrowParameterList

13.2.9.2 Runtime Semantics: Evaluation

PrimaryExpression : CoverParenthesizedExpressionAndArrowParameterList
  1. exprCoverParenthesizedExpressionAndArrowParameterListによってcoverされるParenthesizedExpressionとする。
  2. exprの ? Evaluationを返す。
ParenthesizedExpression : ( Expression )
  1. Expressionの ? Evaluationを返す。これはReference型であり得る。
Note

このalgorithmはExpressionEvaluationGetValueを適用しません。これの主要な動機は、deletetypeofなどのoperatorsをparenthesized expressionsに適用できるようにするためです。

13.3 Left-Hand-Side Expressions

Syntax

MemberExpression[Yield, Await] : PrimaryExpression[?Yield, ?Await] MemberExpression[?Yield, ?Await] [ Expression[+In, ?Yield, ?Await] ] MemberExpression[?Yield, ?Await] . IdentifierName MemberExpression[?Yield, ?Await] TemplateLiteral[?Yield, ?Await, +Tagged] SuperProperty[?Yield, ?Await] MetaProperty new MemberExpression[?Yield, ?Await] Arguments[?Yield, ?Await] MemberExpression[?Yield, ?Await] . PrivateIdentifier SuperProperty[Yield, Await] : super [ Expression[+In, ?Yield, ?Await] ] super . IdentifierName MetaProperty : NewTarget ImportMeta NewTarget : new . target ImportMeta : import . meta NewExpression[Yield, Await] : MemberExpression[?Yield, ?Await] new NewExpression[?Yield, ?Await] CallExpression[Yield, Await] : CoverCallExpressionAndAsyncArrowHead[?Yield, ?Await] SuperCall[?Yield, ?Await] ImportCall[?Yield, ?Await] CallExpression[?Yield, ?Await] Arguments[?Yield, ?Await] CallExpression[?Yield, ?Await] [ Expression[+In, ?Yield, ?Await] ] CallExpression[?Yield, ?Await] . IdentifierName CallExpression[?Yield, ?Await] TemplateLiteral[?Yield, ?Await, +Tagged] CallExpression[?Yield, ?Await] . PrivateIdentifier SuperCall[Yield, Await] : super Arguments[?Yield, ?Await] ImportCall[Yield, Await] : import ( AssignmentExpression[+In, ?Yield, ?Await] ,opt ) import ( AssignmentExpression[+In, ?Yield, ?Await] , AssignmentExpression[+In, ?Yield, ?Await] ,opt ) Arguments[Yield, Await] : ( ) ( ArgumentList[?Yield, ?Await] ) ( ArgumentList[?Yield, ?Await] , ) ArgumentList[Yield, Await] : AssignmentExpression[+In, ?Yield, ?Await] ... AssignmentExpression[+In, ?Yield, ?Await] ArgumentList[?Yield, ?Await] , AssignmentExpression[+In, ?Yield, ?Await] ArgumentList[?Yield, ?Await] , ... AssignmentExpression[+In, ?Yield, ?Await] OptionalExpression[Yield, Await] : MemberExpression[?Yield, ?Await] OptionalChain[?Yield, ?Await] CallExpression[?Yield, ?Await] OptionalChain[?Yield, ?Await] OptionalExpression[?Yield, ?Await] OptionalChain[?Yield, ?Await] OptionalChain[Yield, Await] : ?. Arguments[?Yield, ?Await] ?. [ Expression[+In, ?Yield, ?Await] ] ?. IdentifierName ?. TemplateLiteral[?Yield, ?Await, +Tagged] ?. PrivateIdentifier OptionalChain[?Yield, ?Await] Arguments[?Yield, ?Await] OptionalChain[?Yield, ?Await] [ Expression[+In, ?Yield, ?Await] ] OptionalChain[?Yield, ?Await] . IdentifierName OptionalChain[?Yield, ?Await] TemplateLiteral[?Yield, ?Await, +Tagged] OptionalChain[?Yield, ?Await] . PrivateIdentifier LeftHandSideExpression[Yield, Await] : NewExpression[?Yield, ?Await] CallExpression[?Yield, ?Await] OptionalExpression[?Yield, ?Await]

Supplemental Syntax

production
CallExpression : CoverCallExpressionAndAsyncArrowHead
のinstanceを処理するとき、CoverCallExpressionAndAsyncArrowHeadのinterpretationは次のgrammarを使用してrefineされます:

CallMemberExpression[Yield, Await] : MemberExpression[?Yield, ?Await] Arguments[?Yield, ?Await]

13.3.1 Static Semantics

13.3.1.1 Static Semantics: Early Errors

OptionalChain : ?. TemplateLiteral OptionalChain TemplateLiteral
  • 任意のsource textがこのproductionによってmatchされる場合、それはSyntax Errorです。
Note

このproductionは、automatic semicolon insertion rules(12.10)が次のcodeに適用されることを防ぐために存在します:

a?.b
`c`

これにより、それが2つのvalid statementsとして解釈されることを防ぎます。目的は、optional chainingを使用しない類似のcodeとの一貫性を維持することです:

a.b
`c`

これはvalid statementであり、automatic semicolon insertionは適用されません。

ImportMeta : import . meta

13.3.2 Property Accessors

Note

Propertiesは、dot notationを使用してnameによってaccessされます:

またはbracket notationを使用します:

dot notationは、次のsyntactic conversionによって説明されます:

は、その振る舞いにおいて次と同一です

MemberExpression [ <identifier-name-string> ]

同様に

は、その振る舞いにおいて次と同一です

CallExpression [ <identifier-name-string> ]

ここで、<identifier-name-string>はIdentifierNameStringValueです。

13.3.2.1 Runtime Semantics: Evaluation

MemberExpression : MemberExpression [ Expression ]
  1. baseRefMemberExpressionの ? Evaluationとする。
  2. baseValueを ? GetValue(baseRef) とする。
  3. strictIsStrict(this MemberExpression)とする。
  4. EvaluatePropertyAccessWithExpressionKey(baseValue, Expression, strict)を返す。
MemberExpression : MemberExpression . IdentifierName
  1. baseRefMemberExpressionの ? Evaluationとする。
  2. baseValueを ? GetValue(baseRef) とする。
  3. strictIsStrict(this MemberExpression)とする。
  4. EvaluatePropertyAccessWithIdentifierKey(baseValue, IdentifierName, strict)を返す。
MemberExpression : MemberExpression . PrivateIdentifier
  1. baseRefMemberExpressionの ? Evaluationとする。
  2. baseValueを ? GetValue(baseRef) とする。
  3. fieldNameStringPrivateIdentifierStringValueとする。
  4. MakePrivateReference(baseValue, fieldNameString)を返す。
CallExpression : CallExpression [ Expression ]
  1. baseRefCallExpressionの ? Evaluationとする。
  2. baseValueを ? GetValue(baseRef) とする。
  3. strictIsStrict(this CallExpression)とする。
  4. EvaluatePropertyAccessWithExpressionKey(baseValue, Expression, strict)を返す。
CallExpression : CallExpression . IdentifierName
  1. baseRefCallExpressionの ? Evaluationとする。
  2. baseValueを ? GetValue(baseRef) とする。
  3. strictIsStrict(this CallExpression)とする。
  4. EvaluatePropertyAccessWithIdentifierKey(baseValue, IdentifierName, strict)を返す。
CallExpression : CallExpression . PrivateIdentifier
  1. baseRefCallExpressionの ? Evaluationとする。
  2. baseValueを ? GetValue(baseRef) とする。
  3. fieldNameStringPrivateIdentifierStringValueとする。
  4. MakePrivateReference(baseValue, fieldNameString)を返す。

13.3.3 EvaluatePropertyAccessWithExpressionKey ( baseValue, expr, strict )

The abstract operation EvaluatePropertyAccessWithExpressionKey takes arguments baseValue (an ECMAScript language value), expr (an Expression Parse Node), and strict (a Boolean) and returns either a normal completion containing a Reference Record or an abrupt completion. It performs the following steps when called:

  1. propertyNameRefexprの ? Evaluationとする。
  2. propertyNameValueを ? GetValue(propertyNameRef) とする。
  3. NOTE: ほとんどの場合、ToPropertyKeyはこのstepの直後にpropertyNameValueに対して実行される。しかし、a[b] = cの場合には、cの評価後まで実行されない。
  4. Reference Record { [[Base]]: baseValue, [[ReferencedName]]: propertyNameValue, [[Strict]]: strict, [[ThisValue]]: empty }を返す。

13.3.4 EvaluatePropertyAccessWithIdentifierKey ( baseValue, identifierName, strict )

The abstract operation EvaluatePropertyAccessWithIdentifierKey takes arguments baseValue (an ECMAScript language value), identifierName (an IdentifierName Parse Node), and strict (a Boolean) and returns a Reference Record. It performs the following steps when called:

  1. propertyNameStringidentifierNameStringValueとする。
  2. Reference Record { [[Base]]: baseValue, [[ReferencedName]]: propertyNameString, [[Strict]]: strict, [[ThisValue]]: empty }を返す。

13.3.5 The new Operator

13.3.5.1 Runtime Semantics: Evaluation

NewExpression : new NewExpression
  1. EvaluateNew(NewExpression, empty)を返す。
MemberExpression : new MemberExpression Arguments
  1. EvaluateNew(MemberExpression, Arguments)を返す。

13.3.5.1.1 EvaluateNew ( constructExpr, argumentsNode )

The abstract operation EvaluateNew takes arguments constructExpr (a NewExpression Parse Node or a MemberExpression Parse Node) and argumentsNode (empty or an Arguments Parse Node) and returns either a normal completion containing an Object or an abrupt completion. It performs the following steps when called:

  1. refconstructExprの ? Evaluationとする。
  2. ctorを ? GetValue(ref) とする。
  3. argumentsNodeemptyなら、
    1. argListを新しい空のListとする。
  4. そうでなければ、
    1. argListargumentsNodeの ? ArgumentListEvaluationとする。
  5. IsConstructor(ctor)がfalseなら、TypeError例外をthrowする。
  6. Construct(ctor, argList)を返す。

13.3.6 Function Calls

13.3.6.1 Runtime Semantics: Evaluation

CallExpression : CoverCallExpressionAndAsyncArrowHead
  1. exprCoverCallExpressionAndAsyncArrowHeadによってcoverされるCallMemberExpressionとする。
  2. memberExprexprMemberExpressionとする。
  3. argsexprArgumentsとする。
  4. refmemberExprの ? Evaluationとする。
  5. funcを ? GetValue(ref) とする。
  6. refReference Recordであり、IsPropertyReference(ref)がfalseであり、かつref.[[ReferencedName]]"eval"なら、
    1. SameValue(func, %eval%)がtrueなら、
      1. argListargsの ? ArgumentListEvaluationとする。
      2. argListがelementsを持たないなら、undefinedを返す。
      3. evalArgargListの最初のelementとする。
      4. IsStrict(this CallExpression)がtrueなら、strictCallertrueとする;そうでなければ、strictCallerfalseとする。
      5. PerformEval(evalArg, strictCaller, true)を返す。
  7. thisCallをthis CallExpressionとする。
  8. tailCallIsInTailPosition(thisCall)とする。
  9. EvaluateCall(func, ref, args, tailCall)を返す。

step 6.a.vを実行するCallExpression evaluationはdirect evalです。

CallExpression : CallExpression Arguments
  1. refCallExpressionの ? Evaluationとする。
  2. funcを ? GetValue(ref) とする。
  3. thisCallをthis CallExpressionとする。
  4. tailCallIsInTailPosition(thisCall)とする。
  5. EvaluateCall(func, ref, Arguments, tailCall)を返す。

13.3.6.2 EvaluateCall ( func, thisValueRef, argumentListNode, tailPosition )

The abstract operation EvaluateCall takes arguments func (an ECMAScript language value), thisValueRef (an ECMAScript language value or a Reference Record), argumentListNode (a Parse Node), and tailPosition (a Boolean) and returns either a normal completion containing an ECMAScript language value or an abrupt completion. It performs the following steps when called:

  1. thisValueRefReference Recordなら、
    1. IsPropertyReference(thisValueRef)がtrueなら、
      1. thisValueGetThisValue(thisValueRef)とする。
    2. そうでなければ、
      1. refEnvthisValueRef.[[Base]]とする。
      2. Assert: refEnvEnvironment Recordである。
      3. thisValuerefEnv.WithBaseObject()とする。
  2. そうでなければ、
    1. thisValueundefinedとする。
  3. argListargumentListNodeの ? ArgumentListEvaluationとする。
  4. funcがObjectでないなら、TypeError例外をthrowする。
  5. IsCallable(func)がfalseなら、TypeError例外をthrowする。
  6. tailPositiontrueなら、PrepareForTailCall()を実行する。
  7. Call(func, thisValue, argList)を返す。

13.3.7 The super Keyword

13.3.7.1 Runtime Semantics: Evaluation

SuperProperty : super [ Expression ]
  1. envRecordGetThisEnvironment()とする。
  2. actualThisを ? envRecord.GetThisBinding() とする。
  3. propertyNameRefExpressionの ? Evaluationとする。
  4. propertyNameValueを ? GetValue(propertyNameRef) とする。
  5. strictIsStrict(this SuperProperty)とする。
  6. NOTE: ほとんどの場合、ToPropertyKeyはこのstepの直後にpropertyNameValueに対して実行される。しかし、super[b] = cの場合には、cの評価後まで実行されない。
  7. MakeSuperPropertyReference(actualThis, propertyNameValue, strict)を返す。
SuperProperty : super . IdentifierName
  1. envRecordGetThisEnvironment()とする。
  2. actualThisを ? envRecord.GetThisBinding() とする。
  3. propertyKeyIdentifierNameStringValueとする。
  4. strictIsStrict(this SuperProperty)とする。
  5. MakeSuperPropertyReference(actualThis, propertyKey, strict)を返す。
SuperCall : super Arguments
  1. newTargetGetNewTarget()とする。
  2. Assert: newTargetconstructorである。
  3. superCtorGetSuperConstructor()とする。
  4. argListArgumentsの ? ArgumentListEvaluationとする。
  5. IsConstructor(superCtor)がfalseなら、TypeError例外をthrowする。
  6. resultを ? Construct(superCtor, argList, newTarget) とする。
  7. thisERGetThisEnvironment()とする。
  8. Assert: thisERFunction Environment Recordである。
  9. BindThisValue(thisER, result)を実行する。
  10. funcObjthisER.[[FunctionObject]]とする。
  11. Assert: funcObjはECMAScript function objectである。
  12. InitializeInstanceElements(result, funcObj)を実行する。
  13. resultを返す。

13.3.7.2 GetSuperConstructor ( )

The abstract operation GetSuperConstructor takes no arguments and returns an Object or null. It performs the following steps when called:

  1. envRecordGetThisEnvironment()とする。
  2. Assert: envRecordFunction Environment Recordである。
  3. activeFuncenvRecord.[[FunctionObject]]とする。
  4. Assert: activeFuncはECMAScript function objectである。
  5. superCtorを ! activeFunc.[[GetPrototypeOf]]() とする。
  6. superCtorを返す。

13.3.7.3 MakeSuperPropertyReference ( actualThis, propertyKey, strict )

The abstract operation MakeSuperPropertyReference takes arguments actualThis (an ECMAScript language value), propertyKey (an ECMAScript language value), and strict (a Boolean) and returns a Super Reference Record. It performs the following steps when called:

  1. envRecordGetThisEnvironment()とする。
  2. Assert: envRecord.HasSuperBinding()はtrueである。
  3. Assert: envRecordFunction Environment Recordである。
  4. baseValueGetSuperBase(envRecord)とする。
  5. Reference Record { [[Base]]: baseValue, [[ReferencedName]]: propertyKey, [[Strict]]: strict, [[ThisValue]]: actualThis }を返す。

13.3.8 Argument Lists

Note

argument listのevaluationはvaluesのListを生成します。

13.3.8.1 Runtime Semantics: ArgumentListEvaluation

The syntax-directed operation ArgumentListEvaluation takes no arguments and returns either a normal completion containing a List of ECMAScript language values or an abrupt completion. It is defined piecewise over the following productions:

Arguments : ( )
  1. 新しい空のListを返す。
ArgumentList : AssignmentExpression
  1. refAssignmentExpressionの ? Evaluationとする。
  2. argを ? GetValue(ref) とする。
  3. « arg »を返す。
ArgumentList : ... AssignmentExpression
  1. listを新しい空のListとする。
  2. spreadRefAssignmentExpressionの ? Evaluationとする。
  3. spreadObjを ? GetValue(spreadRef) とする。
  4. iteratorRecordを ? GetIterator(spreadObj, sync) とする。
  5. 繰り返す
    1. nextを ? IteratorStepValue(iteratorRecord) とする。
    2. nextdoneなら、listを返す。
    3. nextlistへappendする。
ArgumentList : ArgumentList , AssignmentExpression
  1. precedingArgsArgumentListの ? ArgumentListEvaluationとする。
  2. refAssignmentExpressionの ? Evaluationとする。
  3. argを ? GetValue(ref) とする。
  4. precedingArgsと« arg »のlist-concatenationを返す。
ArgumentList : ArgumentList , ... AssignmentExpression
  1. precedingArgsArgumentListの ? ArgumentListEvaluationとする。
  2. spreadRefAssignmentExpressionの ? Evaluationとする。
  3. iteratorRecordを ? GetIterator(? GetValue(spreadRef), sync) とする。
  4. 繰り返す
    1. nextを ? IteratorStepValue(iteratorRecord) とする。
    2. nextdoneなら、precedingArgsを返す。
    3. nextprecedingArgsへappendする。
TemplateLiteral : NoSubstitutionTemplate
  1. templateLiteralをthis TemplateLiteralとする。
  2. siteObjGetTemplateObject(templateLiteral)とする。
  3. « siteObj »を返す。
TemplateLiteral : SubstitutionTemplate
  1. templateLiteralをthis TemplateLiteralとする。
  2. siteObjGetTemplateObject(templateLiteral)とする。
  3. remainingSubstitutionTemplateの ? ArgumentListEvaluationとする。
  4. « siteObj »とremaininglist-concatenationを返す。
SubstitutionTemplate : TemplateHead Expression TemplateSpans
  1. firstSubRefExpressionの ? Evaluationとする。
  2. firstSubを ? GetValue(firstSubRef) とする。
  3. restSubTemplateSpansの ? SubstitutionEvaluationとする。
  4. Assert: restSubはpossibly empty Listである。
  5. « firstSub »とrestSublist-concatenationを返す。

13.3.9 Optional Chains

Note
optional chainは、1つ以上のproperty accessesおよびfunction callsのchainであり、その最初のものがtoken ?.で始まります。

13.3.9.1 Runtime Semantics: Evaluation

OptionalExpression : MemberExpression OptionalChain
  1. baseRefMemberExpressionの ? Evaluationとする。
  2. baseValueを ? GetValue(baseRef) とする。
  3. baseValueundefinedまたはnullのいずれかなら、
    1. undefinedを返す。
  4. 引数baseValueおよびbaseRefを伴うOptionalChainの ? ChainEvaluationを返す。
OptionalExpression : CallExpression OptionalChain
  1. baseRefCallExpressionの ? Evaluationとする。
  2. baseValueを ? GetValue(baseRef) とする。
  3. baseValueundefinedまたはnullのいずれかなら、
    1. undefinedを返す。
  4. 引数baseValueおよびbaseRefを伴うOptionalChainの ? ChainEvaluationを返す。
OptionalExpression : OptionalExpression OptionalChain
  1. baseRefOptionalExpressionの ? Evaluationとする。
  2. baseValueを ? GetValue(baseRef) とする。
  3. baseValueundefinedまたはnullのいずれかなら、
    1. undefinedを返す。
  4. 引数baseValueおよびbaseRefを伴うOptionalChainの ? ChainEvaluationを返す。

13.3.9.2 Runtime Semantics: ChainEvaluation

The syntax-directed operation ChainEvaluation takes arguments baseValue (an ECMAScript language value) and baseRef (an ECMAScript language value or a Reference Record) and returns either a normal completion containing either an ECMAScript language value or a Reference Record, or an abrupt completion. It is defined piecewise over the following productions:

OptionalChain : ?. Arguments
  1. thisChainをthis OptionalChainとする。
  2. tailCallIsInTailPosition(thisChain)とする。
  3. EvaluateCall(baseValue, baseRef, Arguments, tailCall)を返す。
OptionalChain : ?. [ Expression ]
  1. strictIsStrict(this OptionalChain)とする。
  2. EvaluatePropertyAccessWithExpressionKey(baseValue, Expression, strict)を返す。
OptionalChain : ?. IdentifierName
  1. strictIsStrict(this OptionalChain)とする。
  2. EvaluatePropertyAccessWithIdentifierKey(baseValue, IdentifierName, strict)を返す。
OptionalChain : ?. PrivateIdentifier
  1. fieldNameStringPrivateIdentifierStringValueとする。
  2. MakePrivateReference(baseValue, fieldNameString)を返す。
OptionalChain : OptionalChain Arguments
  1. optionalChainOptionalChainとする。
  2. newRefを、引数baseValueおよびbaseRefを伴うoptionalChainの ? ChainEvaluationとする。
  3. newValueを ? GetValue(newRef) とする。
  4. thisChainをthis OptionalChainとする。
  5. tailCallIsInTailPosition(thisChain)とする。
  6. EvaluateCall(newValue, newRef, Arguments, tailCall)を返す。
OptionalChain : OptionalChain [ Expression ]
  1. optionalChainOptionalChainとする。
  2. newRefを、引数baseValueおよびbaseRefを伴うoptionalChainの ? ChainEvaluationとする。
  3. newValueを ? GetValue(newRef) とする。
  4. strictIsStrict(this OptionalChain)とする。
  5. EvaluatePropertyAccessWithExpressionKey(newValue, Expression, strict)を返す。
OptionalChain : OptionalChain . IdentifierName
  1. optionalChainOptionalChainとする。
  2. newRefを、引数baseValueおよびbaseRefを伴うoptionalChainの ? ChainEvaluationとする。
  3. newValueを ? GetValue(newRef) とする。
  4. strictIsStrict(this OptionalChain)とする。
  5. EvaluatePropertyAccessWithIdentifierKey(newValue, IdentifierName, strict)を返す。
OptionalChain : OptionalChain . PrivateIdentifier
  1. optionalChainOptionalChainとする。
  2. newRefを、引数baseValueおよびbaseRefを伴うoptionalChainの ? ChainEvaluationとする。
  3. newValueを ? GetValue(newRef) とする。
  4. fieldNameStringPrivateIdentifierStringValueとする。
  5. MakePrivateReference(newValue, fieldNameString)を返す。

13.3.10 Import Calls

13.3.10.1 Runtime Semantics: Evaluation

ImportCall : import ( AssignmentExpression ,opt )
  1. EvaluateImportCall(AssignmentExpression)を返す。
ImportCall : import ( AssignmentExpression , AssignmentExpression ,opt )
  1. EvaluateImportCall(最初のAssignmentExpression, 2番目のAssignmentExpression)を返す。

13.3.10.2 EvaluateImportCall ( specifierExpr [ , optionsExpr ] )

The abstract operation EvaluateImportCall takes argument specifierExpr (a Parse Node) and optional argument optionsExpr (a Parse Node) and returns either a normal completion containing a Promise or an abrupt completion. It performs the following steps when called:

  1. referrerGetActiveScriptOrModule()とする。
  2. referrernullなら、referrercurrent Realm Recordに設定する。
  3. specifierRefspecifierExprの ? Evaluationとする。
  4. specifierを ? GetValue(specifierRef) とする。
  5. optionsExprが存在するなら、
    1. optionsRefoptionsExprの ? Evaluationとする。
    2. optionsを ? GetValue(optionsRef) とする。
  6. そうでなければ、
    1. optionsundefinedとする。
  7. promiseCapabilityを ! NewPromiseCapability(%Promise%) とする。
  8. specifierStringCompletion(ToString(specifier))とする。
  9. IfAbruptRejectPromise(specifierString, promiseCapability).
  10. attrsを新しい空のListとする。
  11. optionsundefinedでないなら、
    1. optionsがObjectでないなら、
      1. Call(promiseCapability.[[Reject]], undefined, « 新しく作成されたTypeError object »)を実行する。
      2. promiseCapability.[[Promise]]を返す。
    2. attrsObjCompletion(Get(options, "with")))とする。
    3. IfAbruptRejectPromise(attrsObj, promiseCapability).
    4. attrsObjundefinedでないなら、
      1. attrsObjがObjectでないなら、
        1. Call(promiseCapability.[[Reject]], undefined, « 新しく作成されたTypeError object »)を実行する。
        2. promiseCapability.[[Promise]]を返す。
      2. entriesCompletion(EnumerableOwnProperties(attrsObj, key+value))とする。
      3. IfAbruptRejectPromise(entries, promiseCapability).
      4. entriesの各要素entryについて、以下を行う
        1. keyを ! Get(entry, "0") とする。
        2. valueを ! Get(entry, "1") とする。
        3. keyがStringなら、
          1. valueがStringでないなら、
            1. Call(promiseCapability.[[Reject]], undefined, « 新しく作成されたTypeError object »)を実行する。
            2. promiseCapability.[[Promise]]を返す。
          2. ImportAttribute Record { [[Key]]: key, [[Value]]: value }をattrsへappendする。
    5. AllImportAttributesSupported(attrs)がfalseなら、
      1. Call(promiseCapability.[[Reject]], undefined, « 新しく作成されたTypeError object »)を実行する。
      2. promiseCapability.[[Promise]]を返す。
    6. attrsを、その[[Key]] fieldのlexicographic orderに従ってsortし、そのような各fieldの値をUTF-16 code unit valuesのsequenceとして扱う。NOTE: このsortingは、hostsがattributesのenumerated順序に基づいてbehaviourを変更することを禁止されているという点でのみobservableです。
  12. moduleRequestを新しいModuleRequest Record { [[Specifier]]: specifierString, [[Attributes]]: attrs }とする。
  13. HostLoadImportedModule(referrer, moduleRequest, empty, promiseCapability)を実行する。
  14. promiseCapability.[[Promise]]を返す。

13.3.10.3 ContinueDynamicImport ( promiseCapability, moduleCompletion )

The abstract operation ContinueDynamicImport takes arguments promiseCapability (a PromiseCapability Record) and moduleCompletion (either a normal completion containing a Module Record or a throw completion) and returns unused. これは、import() callによって最初に開始されたdynamic importのprocessを完了し、そのcallによって返されたpromiseを適切にresolveまたはrejectします。 It performs the following steps when called:

  1. moduleCompletionabrupt completionなら、
    1. Call(promiseCapability.[[Reject]], undefined, « moduleCompletion.[[Value]] »)を実行する。
    2. unusedを返す。
  2. modulemoduleCompletion.[[Value]]とする。
  3. loadPromisemodule.LoadRequestedModules()とする。
  4. promiseCapabilityをcaptureし、呼び出されたときに次のstepsを実行する、parameters (reason)を持つ新しいAbstract ClosureとしてrejectedClosureを作成する:
    1. Call(promiseCapability.[[Reject]], undefined, « reason »)を実行する。
    2. NormalCompletion(undefined)を返す。
  5. onRejectedCreateBuiltinFunction(rejectedClosure, 1, "", « »)とする。
  6. modulepromiseCapability、およびonRejectedをcaptureし、呼び出されたときに次のstepsを実行する、parametersを持たない新しいAbstract ClosureとしてlinkAndEvaluateClosureを作成する:
    1. linkCompletion(module.Link())とする。
    2. linkabrupt completionなら、
      1. Call(promiseCapability.[[Reject]], undefined, « link.[[Value]] »)を実行する。
      2. NormalCompletion(undefined)を返す。
    3. evaluatePromisemodule.Evaluate()とする。
    4. moduleおよびpromiseCapabilityをcaptureし、呼び出されたときに次のstepsを実行する、parametersを持たない新しいAbstract ClosureとしてfulfilledClosureを作成する:
      1. namespaceGetModuleNamespace(module)とする。
      2. Call(promiseCapability.[[Resolve]], undefined, « namespace »)を実行する。
      3. NormalCompletion(undefined)を返す。
    5. onFulfilledCreateBuiltinFunction(fulfilledClosure, 0, "", « »)とする。
    6. PerformPromiseThen(evaluatePromise, onFulfilled, onRejected)を実行する。
    7. unusedを返す。
  7. linkAndEvaluateCreateBuiltinFunction(linkAndEvaluateClosure, 0, "", « »)とする。
  8. PerformPromiseThen(loadPromise, linkAndEvaluate, onRejected)を実行する。
  9. unusedを返す。

13.3.11 Tagged Templates

Note

tagged templateは、そのcallのargumentsがTemplateLiteral13.2.8)からderivedされるfunction callです。実際のargumentsには、template object(13.2.8.4)と、TemplateLiteral内に埋め込まれたexpressionsを評価することによって生成されるvaluesが含まれます。

13.3.11.1 Runtime Semantics: Evaluation

MemberExpression : MemberExpression TemplateLiteral
  1. tagRefMemberExpressionの ? Evaluationとする。
  2. tagFuncを ? GetValue(tagRef) とする。
  3. thisCallをthis MemberExpressionとする。
  4. tailCallIsInTailPosition(thisCall)とする。
  5. EvaluateCall(tagFunc, tagRef, TemplateLiteral, tailCall)を返す。
CallExpression : CallExpression TemplateLiteral
  1. tagRefCallExpressionの ? Evaluationとする。
  2. tagFuncを ? GetValue(tagRef) とする。
  3. thisCallをthis CallExpressionとする。
  4. tailCallIsInTailPosition(thisCall)とする。
  5. EvaluateCall(tagFunc, tagRef, TemplateLiteral, tailCall)を返す。

13.3.12 Meta Properties

13.3.12.1 Runtime Semantics: Evaluation

NewTarget : new . target
  1. GetNewTarget()を返す。
ImportMeta : import . meta
  1. moduleGetActiveScriptOrModule()とする。
  2. Assert: moduleSource Text Module Recordである。
  3. importMetamodule.[[ImportMeta]]とする。
  4. importMetaemptyなら、
    1. importMetaOrdinaryObjectCreate(null)に設定する。
    2. importMetaValuesHostGetImportMetaProperties(module)とする。
    3. importMetaValuesの各Record { [[Key]], [[Value]] } entryについて、以下を行う
      1. CreateDataPropertyOrThrow(importMeta, entry.[[Key]], entry.[[Value]])を実行する。
    4. HostFinalizeImportMeta(importMeta, module)を実行する。
    5. module.[[ImportMeta]]importMetaに設定する。
    6. importMetaを返す。
  5. Assert: importMetaはObjectである。
  6. importMetaを返す。

13.3.12.1.1 HostGetImportMetaProperties ( moduleRecord )

The host-defined abstract operation HostGetImportMetaProperties takes argument moduleRecord (a Module Record) and returns a List of Records with fields [[Key]] (a property key) and [[Value]] (an ECMAScript language value). これは、hostsimport.metaから返されるobjectにproperty keysおよびvaluesを提供できるようにします。

HostGetImportMetaPropertiesのdefault implementationは、新しい空のListを返すことです。

13.3.12.1.2 HostFinalizeImportMeta ( importMeta, moduleRecord )

The host-defined abstract operation HostFinalizeImportMeta takes arguments importMeta (an Object) and moduleRecord (a Module Record) and returns unused. これは、hostsimport.metaから返されるobjectを準備するために任意のextraordinary operationsを実行できるようにします。

ほとんどのhostsは単にHostGetImportMetaPropertiesを定義し、HostFinalizeImportMetaはそのdefault behaviourのままにできます。ただし、HostFinalizeImportMetaは、ECMAScript codeにexposedされる前にobjectを直接manipulateする必要があるhostsのための“escape hatch”を提供します。

HostFinalizeImportMetaのdefault implementationは、unusedを返すことです。

13.4 Update Expressions

Syntax

UpdateExpression[Yield, Await] : LeftHandSideExpression[?Yield, ?Await] LeftHandSideExpression[?Yield, ?Await] [no LineTerminator here] ++ LeftHandSideExpression[?Yield, ?Await] [no LineTerminator here] -- ++ UnaryExpression[?Yield, ?Await] -- UnaryExpression[?Yield, ?Await]

13.4.1 Static Semantics: Early Errors

UpdateExpression : LeftHandSideExpression ++ LeftHandSideExpression -- UpdateExpression : ++ UnaryExpression -- UnaryExpression

13.4.2 Postfix Increment Operator

13.4.2.1 Runtime Semantics: Evaluation

UpdateExpression : LeftHandSideExpression ++
  1. lhsLeftHandSideExpressionの ? Evaluationとする。
  2. LeftHandSideExpressionAssignmentTargetTypeweb-compatなら、ReferenceError例外をthrowする。
  3. oldValueを ? ToNumeric(? GetValue(lhs)) とする。
  4. oldValueがNumberなら、
    1. newValueNumber::add(oldValue, 1𝔽)とする。
  5. そうでなければ、
    1. Assert: oldValueはBigIntである。
    2. newValueBigInt::add(oldValue, 1)とする。
  6. PutValue(lhs, newValue)を実行する。
  7. oldValueを返す。

13.4.3 Postfix Decrement Operator

13.4.3.1 Runtime Semantics: Evaluation

UpdateExpression : LeftHandSideExpression --
  1. lhsLeftHandSideExpressionの ? Evaluationとする。
  2. LeftHandSideExpressionAssignmentTargetTypeweb-compatなら、ReferenceError例外をthrowする。
  3. oldValueを ? ToNumeric(? GetValue(lhs)) とする。
  4. oldValueがNumberなら、
    1. newValueNumber::subtract(oldValue, 1𝔽)とする。
  5. そうでなければ、
    1. Assert: oldValueはBigIntである。
    2. newValueBigInt::subtract(oldValue, 1)とする。
  6. PutValue(lhs, newValue)を実行する。
  7. oldValueを返す。

13.4.4 Prefix Increment Operator

13.4.4.1 Runtime Semantics: Evaluation

UpdateExpression : ++ UnaryExpression
  1. exprUnaryExpressionの ? Evaluationとする。
  2. UnaryExpressionAssignmentTargetTypeweb-compatなら、ReferenceError例外をthrowする。
  3. oldValueを ? ToNumeric(? GetValue(expr)) とする。
  4. oldValueがNumberなら、
    1. newValueNumber::add(oldValue, 1𝔽)とする。
  5. そうでなければ、
    1. Assert: oldValueはBigIntである。
    2. newValueBigInt::add(oldValue, 1)とする。
  6. PutValue(expr, newValue)を実行する。
  7. newValueを返す。

13.4.5 Prefix Decrement Operator

13.4.5.1 Runtime Semantics: Evaluation

UpdateExpression : -- UnaryExpression
  1. exprUnaryExpressionの ? Evaluationとする。
  2. UnaryExpressionAssignmentTargetTypeweb-compatなら、ReferenceError例外をthrowする。
  3. oldValueを ? ToNumeric(? GetValue(expr)) とする。
  4. oldValueがNumberなら、
    1. newValueNumber::subtract(oldValue, 1𝔽)とする。
  5. そうでなければ、
    1. Assert: oldValueはBigIntである。
    2. newValueBigInt::subtract(oldValue, 1)とする。
  6. PutValue(expr, newValue)を実行する。
  7. newValueを返す。

13.5 Unary Operators

Syntax

UnaryExpression[Yield, Await] : UpdateExpression[?Yield, ?Await] delete UnaryExpression[?Yield, ?Await] void UnaryExpression[?Yield, ?Await] typeof UnaryExpression[?Yield, ?Await] + UnaryExpression[?Yield, ?Await] - UnaryExpression[?Yield, ?Await] ~ UnaryExpression[?Yield, ?Await] ! UnaryExpression[?Yield, ?Await] [+Await] CoverAwaitExpressionAndAwaitUsingDeclarationHead[?Yield] CoverAwaitExpressionAndAwaitUsingDeclarationHead[Yield] : await UnaryExpression[?Yield, +Await]

補足構文

生成規則のインスタンスを処理する際
UnaryExpression : CoverAwaitExpressionAndAwaitUsingDeclarationHead
CoverAwaitExpressionAndAwaitUsingDeclarationHead の解釈は、次の文法を使用して精緻化される:

AwaitExpression[Yield] : await UnaryExpression[?Yield, +Await]

13.5.1 The delete Operator

13.5.1.1 Static Semantics: Early Errors

UnaryExpression : delete UnaryExpression Note

最後のruleは、delete (((foo)))のようなexpressionsが、最初のruleのrecursive applicationによりearly errorsを生じることを意味します。

13.5.1.2 Runtime Semantics: Evaluation

UnaryExpression : delete UnaryExpression
  1. refUnaryExpressionの ? Evaluationとする。
  2. refReference Recordでないなら、trueを返す。
  3. IsUnresolvableReference(ref)がtrueなら、
    1. Assert: ref.[[Strict]]falseである。
    2. trueを返す。
  4. IsPropertyReference(ref)がtrueなら、
    1. Assert: IsPrivateReference(ref)はfalseである。
    2. IsSuperReference(ref)がtrueなら、ReferenceError例外をthrowする。
    3. baseObjを ? ToObject(ref.[[Base]]) とする。
    4. ref.[[ReferencedName]]property keyでないなら、
      1. ref.[[ReferencedName]]を ? ToPropertyKey(ref.[[ReferencedName]]) に設定する。
    5. deleteStatusを ? baseObj.[[Delete]](ref.[[ReferencedName]]) とする。
    6. deleteStatusfalseであり、かつref.[[Strict]]trueなら、TypeError例外をthrowする。
    7. deleteStatusを返す。
  5. baseref.[[Base]]とする。
  6. Assert: baseEnvironment Recordである。
  7. base.DeleteBinding(ref.[[ReferencedName]])を返す。
Note 1

delete operatorがstrict mode code内に出現すると、そのUnaryExpressionがvariable、function argument、またはfunction nameへのdirect referenceである場合、SyntaxError例外がthrowされます。さらに、delete operatorがstrict mode code内に出現し、削除されるpropertyがattribute { [[Configurable]]: false }を持つ(またはその他の理由で削除できない)場合、TypeError例外がthrowされます。

Note 2

step 4.cで作成される可能性のあるobjectは、上記abstract operationおよびordinary object [[Delete]] internal methodの外部からはaccessできません。実装は、そのobjectの実際の作成を避けることを選択してもよいです。

13.5.2 The void Operator

13.5.2.1 Runtime Semantics: Evaluation

UnaryExpression : void UnaryExpression
  1. exprUnaryExpressionの ? Evaluationとする。
  2. GetValue(expr)を実行する。
  3. undefinedを返す。
Note

その値は使用されませんが、observable side-effectsを持つ場合があるため、GetValueは呼び出されなければなりません。

13.5.3 The typeof Operator

13.5.3.1 Runtime Semantics: Evaluation

UnaryExpression : typeof UnaryExpression
  1. valueUnaryExpressionの ? Evaluationとする。
  2. valueReference Recordなら、
    1. IsUnresolvableReference(value)がtrueなら、"undefined"を返す。
  3. valueを ? GetValue(value) に設定する。
  4. valueundefinedなら、"undefined"を返す。
  5. valuenullなら、"object"を返す。
  6. valueがStringなら、"string"を返す。
  7. valueがSymbolなら、"symbol"を返す。
  8. valueがBooleanなら、"boolean"を返す。
  9. valueがNumberなら、"number"を返す。
  10. valueがBigIntなら、"bigint"を返す。
  11. Assert: valueはObjectである。
  12. hostがweb browserである、またはその他の形で[[IsHTMLDDA]] Internal Slotをサポートするなら、
    1. value[[IsHTMLDDA]] internal slotを持つなら、"undefined"を返す。
  13. value[[Call]] internal methodを持つなら、"function"を返す。
  14. "object"を返す。

13.5.4 Unary + Operator

Note

unary + operatorは、そのoperandをNumber typeへ変換します。

13.5.4.1 Runtime Semantics: Evaluation

UnaryExpression : + UnaryExpression
  1. exprUnaryExpressionの ? Evaluationとする。
  2. ToNumber(? GetValue(expr))を返す。

13.5.5 Unary - Operator

Note

unary - operatorは、そのoperandをnumeric valueへ変換し、その後それをnegateします。+0𝔽をnegateすると-0𝔽が生成され、-0𝔽をnegateすると+0𝔽が生成されます。

13.5.5.1 Runtime Semantics: Evaluation

UnaryExpression : - UnaryExpression
  1. exprUnaryExpressionの ? Evaluationとする。
  2. oldValueを ? ToNumeric(? GetValue(expr)) とする。
  3. oldValueがNumberなら、Number::unaryMinus(oldValue)を返す。
  4. Assert: oldValueはBigIntである。
  5. BigInt::unaryMinus(oldValue)を返す。

13.5.6 Bitwise NOT Operator ( ~ )

13.5.6.1 Runtime Semantics: Evaluation

UnaryExpression : ~ UnaryExpression
  1. exprUnaryExpressionの ? Evaluationとする。
  2. oldValueを ? ToNumeric(? GetValue(expr)) とする。
  3. oldValueがNumberなら、Number::bitwiseNOT(oldValue)を返す。
  4. Assert: oldValueはBigIntである。
  5. BigInt::bitwiseNOT(oldValue)を返す。

13.5.7 Logical NOT Operator ( ! )

13.5.7.1 Runtime Semantics: Evaluation

UnaryExpression : ! UnaryExpression
  1. exprUnaryExpressionの ? Evaluationとする。
  2. oldValueToBoolean(? GetValue(expr))とする。
  3. oldValuetrueなら、falseを返す。
  4. trueを返す。

13.6 Exponentiation Operator

Syntax

ExponentiationExpression[Yield, Await] : UnaryExpression[?Yield, ?Await] UpdateExpression[?Yield, ?Await] ** ExponentiationExpression[?Yield, ?Await]

13.6.1 Runtime Semantics: Evaluation

ExponentiationExpression : UpdateExpression ** ExponentiationExpression
  1. EvaluateStringOrNumericBinaryExpression(UpdateExpression, **, ExponentiationExpression)を返す。

13.7 Multiplicative Operators

Syntax

MultiplicativeExpression[Yield, Await] : ExponentiationExpression[?Yield, ?Await] MultiplicativeExpression[?Yield, ?Await] MultiplicativeOperator ExponentiationExpression[?Yield, ?Await] MultiplicativeOperator : one of * / % Note
  • * operatorはmultiplicationを実行し、そのoperandsのproductを生成します。
  • / operatorはdivisionを実行し、そのoperandsのquotientを生成します。
  • % operatorは、暗黙のdivisionからそのoperandsのremainderを生成します。

13.7.1 Runtime Semantics: Evaluation

MultiplicativeExpression : MultiplicativeExpression MultiplicativeOperator ExponentiationExpression
  1. opTextMultiplicativeOperatorによってmatchされたsource textとする。
  2. EvaluateStringOrNumericBinaryExpression(MultiplicativeExpression, opText, ExponentiationExpression)を返す。

13.8 Additive Operators

Syntax

AdditiveExpression[Yield, Await] : MultiplicativeExpression[?Yield, ?Await] AdditiveExpression[?Yield, ?Await] + MultiplicativeExpression[?Yield, ?Await] AdditiveExpression[?Yield, ?Await] - MultiplicativeExpression[?Yield, ?Await]

13.8.1 The Addition Operator ( + )

Note

addition operatorは、string concatenationまたはnumeric additionのいずれかを実行します。

13.8.1.1 Runtime Semantics: Evaluation

AdditiveExpression : AdditiveExpression + MultiplicativeExpression
  1. EvaluateStringOrNumericBinaryExpression(AdditiveExpression, +, MultiplicativeExpression)を返す。

13.8.2 The Subtraction Operator ( - )

Note

- operatorはsubtractionを実行し、そのoperandsのdifferenceを生成します。

13.8.2.1 Runtime Semantics: Evaluation

AdditiveExpression : AdditiveExpression - MultiplicativeExpression
  1. EvaluateStringOrNumericBinaryExpression(AdditiveExpression, -, MultiplicativeExpression)を返す。

13.9 Bitwise Shift Operators

Syntax

ShiftExpression[Yield, Await] : AdditiveExpression[?Yield, ?Await] ShiftExpression[?Yield, ?Await] << AdditiveExpression[?Yield, ?Await] ShiftExpression[?Yield, ?Await] >> AdditiveExpression[?Yield, ?Await] ShiftExpression[?Yield, ?Await] >>> AdditiveExpression[?Yield, ?Await]

13.9.1 The Left Shift Operator ( << )

Note

right operandによって指定された量だけ、left operandに対してbitwise left shift operationを実行します。

13.9.1.1 Runtime Semantics: Evaluation

ShiftExpression : ShiftExpression << AdditiveExpression
  1. EvaluateStringOrNumericBinaryExpression(ShiftExpression, <<, AdditiveExpression)を返す。

13.9.2 The Signed Right Shift Operator ( >> )

Note

right operandによって指定された量だけ、left operandに対してsign-filling bitwise right shift operationを実行します。

13.9.2.1 Runtime Semantics: Evaluation

ShiftExpression : ShiftExpression >> AdditiveExpression
  1. EvaluateStringOrNumericBinaryExpression(ShiftExpression, >>, AdditiveExpression)を返す。

13.9.3 The Unsigned Right Shift Operator ( >>> )

Note

right operandによって指定された量だけ、left operandに対してzero-filling bitwise right shift operationを実行します。

13.9.3.1 Runtime Semantics: Evaluation

ShiftExpression : ShiftExpression >>> AdditiveExpression
  1. EvaluateStringOrNumericBinaryExpression(ShiftExpression, >>>, AdditiveExpression)を返す。

13.10 Relational Operators

Note 1

relational operatorを評価した結果は常にBoolean型であり、そのoperatorによって名付けられた関係が2つのoperandsの間に成り立つかどうかを反映します。

Syntax

RelationalExpression[In, Yield, Await] : ShiftExpression[?Yield, ?Await] RelationalExpression[?In, ?Yield, ?Await] < ShiftExpression[?Yield, ?Await] RelationalExpression[?In, ?Yield, ?Await] > ShiftExpression[?Yield, ?Await] RelationalExpression[?In, ?Yield, ?Await] <= ShiftExpression[?Yield, ?Await] RelationalExpression[?In, ?Yield, ?Await] >= ShiftExpression[?Yield, ?Await] RelationalExpression[?In, ?Yield, ?Await] instanceof ShiftExpression[?Yield, ?Await] [+In] RelationalExpression[+In, ?Yield, ?Await] in ShiftExpression[?Yield, ?Await] [+In] PrivateIdentifier in ShiftExpression[?Yield, ?Await] Note 2

[In] grammar parameterは、relational expression内のin operatorとfor statement内のin operatorを混同することを避けるために必要です。

13.10.1 Runtime Semantics: Evaluation

RelationalExpression : RelationalExpression < ShiftExpression
  1. leftRefRelationalExpressionの ? Evaluationとする。
  2. leftValueを ? GetValue(leftRef) とする。
  3. rightRefShiftExpressionの ? Evaluationとする。
  4. rightValueを ? GetValue(rightRef) とする。
  5. resultを ? IsLessThan(leftValue, rightValue, true) とする。
  6. resultundefinedなら、falseを返す。
  7. resultを返す。
RelationalExpression : RelationalExpression > ShiftExpression
  1. leftRefRelationalExpressionの ? Evaluationとする。
  2. leftValueを ? GetValue(leftRef) とする。
  3. rightRefShiftExpressionの ? Evaluationとする。
  4. rightValueを ? GetValue(rightRef) とする。
  5. resultを ? IsLessThan(rightValue, leftValue, false) とする。
  6. resultundefinedなら、falseを返す。
  7. resultを返す。
RelationalExpression : RelationalExpression <= ShiftExpression
  1. leftRefRelationalExpressionの ? Evaluationとする。
  2. leftValueを ? GetValue(leftRef) とする。
  3. rightRefShiftExpressionの ? Evaluationとする。
  4. rightValueを ? GetValue(rightRef) とする。
  5. resultを ? IsLessThan(rightValue, leftValue, false) とする。
  6. resulttrueまたはundefinedのいずれかなら、falseを返す。
  7. trueを返す。
RelationalExpression : RelationalExpression >= ShiftExpression
  1. leftRefRelationalExpressionの ? Evaluationとする。
  2. leftValueを ? GetValue(leftRef) とする。
  3. rightRefShiftExpressionの ? Evaluationとする。
  4. rightValueを ? GetValue(rightRef) とする。
  5. resultを ? IsLessThan(leftValue, rightValue, true) とする。
  6. resulttrueまたはundefinedのいずれかなら、falseを返す。
  7. trueを返す。
RelationalExpression : RelationalExpression instanceof ShiftExpression
  1. leftRefRelationalExpressionの ? Evaluationとする。
  2. leftValueを ? GetValue(leftRef) とする。
  3. rightRefShiftExpressionの ? Evaluationとする。
  4. rightValueを ? GetValue(rightRef) とする。
  5. InstanceofOperator(leftValue, rightValue)を返す。
RelationalExpression : RelationalExpression in ShiftExpression
  1. leftRefRelationalExpressionの ? Evaluationとする。
  2. leftValueを ? GetValue(leftRef) とする。
  3. rightRefShiftExpressionの ? Evaluationとする。
  4. rightValueを ? GetValue(rightRef) とする。
  5. rightValueがObjectでないなら、TypeError例外をthrowする。
  6. HasProperty(rightValue, ? ToPropertyKey(leftValue))を返す。
RelationalExpression : PrivateIdentifier in ShiftExpression
  1. privateIdentifierPrivateIdentifierStringValueとする。
  2. rightRefShiftExpressionの ? Evaluationとする。
  3. rightValueを ? GetValue(rightRef) とする。
  4. rightValueがObjectでないなら、TypeError例外をthrowする。
  5. privateEnvrunning execution contextのPrivateEnvironmentとする。
  6. Assert: privateEnvnullでない。
  7. privateNameResolvePrivateIdentifier(privateEnv, privateIdentifier)とする。
  8. PrivateElementFind(rightValue, privateName)がemptyなら、falseを返す。
  9. trueを返す。

13.10.2 InstanceofOperator ( value, target )

The abstract operation InstanceofOperator takes arguments value (an ECMAScript language value) and target (an ECMAScript language value) and returns either a normal completion containing a Boolean or a throw completion. これは、target%Symbol.hasInstance% methodをconsultすることによって、またはそれが存在しない場合には、target"prototype" propertyの値がvalueのprototype chain内に存在するかどうかを判定することによって、valuetargetのinstanceであるかどうかを判定するgeneric algorithmを実装します。 It performs the following steps when called:

  1. targetがObjectでないなら、TypeError例外をthrowする。
  2. instOfHandlerを ? GetMethod(target, %Symbol.hasInstance%) とする。
  3. instOfHandlerundefinedでないなら、
    1. ToBoolean(? Call(instOfHandler, target, « value »))を返す。
  4. IsCallable(target)がfalseなら、TypeError例外をthrowする。
  5. OrdinaryHasInstance(target, value)を返す。
Note

Steps 4および5は、instanceof operator semanticsを定義するために%Symbol.hasInstance% methodを使用しなかったECMAScriptの以前のeditionsとのcompatibilityを提供します。objectが%Symbol.hasInstance%を定義または継承していない場合、default instanceof semanticsを使用します。

13.11 Equality Operators

Note

equality operatorを評価した結果は常にBoolean型であり、そのoperatorによって名付けられた関係が2つのoperandsの間に成り立つかどうかを反映します。

Syntax

EqualityExpression[In, Yield, Await] : RelationalExpression[?In, ?Yield, ?Await] EqualityExpression[?In, ?Yield, ?Await] == RelationalExpression[?In, ?Yield, ?Await] EqualityExpression[?In, ?Yield, ?Await] != RelationalExpression[?In, ?Yield, ?Await] EqualityExpression[?In, ?Yield, ?Await] === RelationalExpression[?In, ?Yield, ?Await] EqualityExpression[?In, ?Yield, ?Await] !== RelationalExpression[?In, ?Yield, ?Await]

13.11.1 Runtime Semantics: Evaluation

EqualityExpression : EqualityExpression == RelationalExpression
  1. leftRefEqualityExpressionの ? Evaluationとする。
  2. leftValueを ? GetValue(leftRef) とする。
  3. rightRefRelationalExpressionの ? Evaluationとする。
  4. rightValueを ? GetValue(rightRef) とする。
  5. IsLooselyEqual(rightValue, leftValue)を返す。
EqualityExpression : EqualityExpression != RelationalExpression
  1. leftRefEqualityExpressionの ? Evaluationとする。
  2. leftValueを ? GetValue(leftRef) とする。
  3. rightRefRelationalExpressionの ? Evaluationとする。
  4. rightValueを ? GetValue(rightRef) とする。
  5. resultを ? IsLooselyEqual(rightValue, leftValue) とする。
  6. resulttrueなら、falseを返す。
  7. trueを返す。
EqualityExpression : EqualityExpression === RelationalExpression
  1. leftRefEqualityExpressionの ? Evaluationとする。
  2. leftValueを ? GetValue(leftRef) とする。
  3. rightRefRelationalExpressionの ? Evaluationとする。
  4. rightValueを ? GetValue(rightRef) とする。
  5. IsStrictlyEqual(rightValue, leftValue)を返す。
EqualityExpression : EqualityExpression !== RelationalExpression
  1. leftRefEqualityExpressionの ? Evaluationとする。
  2. leftValueを ? GetValue(leftRef) とする。
  3. rightRefRelationalExpressionの ? Evaluationとする。
  4. rightValueを ? GetValue(rightRef) とする。
  5. resultIsStrictlyEqual(rightValue, leftValue)とする。
  6. resulttrueなら、falseを返す。
  7. trueを返す。
Note 1

equality operatorsは次のinvariantsを維持します:

  • A != B!(A == B)と等価です。
  • A == Bは、AおよびBのevaluation順序を除き、B == Aと等価です。
Note 2

equality operatorは常にtransitiveであるとは限りません。例えば、同じString値を表す2つのdistinct String objectsが存在する場合があります;各String objectは== operatorによってString値と等しいとみなされますが、2つのString objectsは互いに等しいとはみなされません。例えば:

  • new String("a") == "a"および"a" == new String("a")はいずれもtrueです。
  • new String("a") == new String("a")falseです。
Note 3

Stringsのcomparisonは、code unit valuesのsequencesに対する単純なequality testを使用します。Unicode specificationで定義される、より複雑でsemantically orientedなcharacterまたはstring equalityおよびcollating orderのdefinitionsを使用する試みはありません。したがって、Unicode Standardに従ってcanonically equalであるStrings valuesが、unequalとしてtestされる可能性があります。実際には、このalgorithmは両方のStringsがすでにnormalized formにあると仮定します。

13.12 Binary Bitwise Operators

Syntax

BitwiseANDExpression[In, Yield, Await] : EqualityExpression[?In, ?Yield, ?Await] BitwiseANDExpression[?In, ?Yield, ?Await] & EqualityExpression[?In, ?Yield, ?Await] BitwiseXORExpression[In, Yield, Await] : BitwiseANDExpression[?In, ?Yield, ?Await] BitwiseXORExpression[?In, ?Yield, ?Await] ^ BitwiseANDExpression[?In, ?Yield, ?Await] BitwiseORExpression[In, Yield, Await] : BitwiseXORExpression[?In, ?Yield, ?Await] BitwiseORExpression[?In, ?Yield, ?Await] | BitwiseXORExpression[?In, ?Yield, ?Await]

13.12.1 Runtime Semantics: Evaluation

BitwiseANDExpression : BitwiseANDExpression & EqualityExpression
  1. EvaluateStringOrNumericBinaryExpression(BitwiseANDExpression, &, EqualityExpression)を返す。
BitwiseXORExpression : BitwiseXORExpression ^ BitwiseANDExpression
  1. EvaluateStringOrNumericBinaryExpression(BitwiseXORExpression, ^, BitwiseANDExpression)を返す。
BitwiseORExpression : BitwiseORExpression | BitwiseXORExpression
  1. EvaluateStringOrNumericBinaryExpression(BitwiseORExpression, |, BitwiseXORExpression)を返す。

13.13 Binary Logical Operators

Syntax

LogicalANDExpression[In, Yield, Await] : BitwiseORExpression[?In, ?Yield, ?Await] LogicalANDExpression[?In, ?Yield, ?Await] && BitwiseORExpression[?In, ?Yield, ?Await] LogicalORExpression[In, Yield, Await] : LogicalANDExpression[?In, ?Yield, ?Await] LogicalORExpression[?In, ?Yield, ?Await] || LogicalANDExpression[?In, ?Yield, ?Await] CoalesceExpression[In, Yield, Await] : CoalesceExpressionHead[?In, ?Yield, ?Await] ?? BitwiseORExpression[?In, ?Yield, ?Await] CoalesceExpressionHead[In, Yield, Await] : CoalesceExpression[?In, ?Yield, ?Await] BitwiseORExpression[?In, ?Yield, ?Await] ShortCircuitExpression[In, Yield, Await] : LogicalORExpression[?In, ?Yield, ?Await] CoalesceExpression[?In, ?Yield, ?Await] Note

&&または|| operatorによって生成される値は、必ずしもBoolean型ではありません。生成される値は常に2つのoperand expressionsのいずれかの値になります。

13.13.1 Runtime Semantics: Evaluation

LogicalANDExpression : LogicalANDExpression && BitwiseORExpression
  1. leftRefLogicalANDExpressionの ? Evaluationとする。
  2. leftValueを ? GetValue(leftRef) とする。
  3. ToBoolean(leftValue)がfalseなら、leftValueを返す。
  4. rightRefBitwiseORExpressionの ? Evaluationとする。
  5. GetValue(rightRef)を返す。
LogicalORExpression : LogicalORExpression || LogicalANDExpression
  1. leftRefLogicalORExpressionの ? Evaluationとする。
  2. leftValueを ? GetValue(leftRef) とする。
  3. ToBoolean(leftValue)がtrueなら、leftValueを返す。
  4. rightRefLogicalANDExpressionの ? Evaluationとする。
  5. GetValue(rightRef)を返す。
CoalesceExpression : CoalesceExpressionHead ?? BitwiseORExpression
  1. leftRefCoalesceExpressionHeadの ? Evaluationとする。
  2. leftValueを ? GetValue(leftRef) とする。
  3. leftValueundefinedでもnullでもないなら、leftValueを返す。
  4. rightRefBitwiseORExpressionの ? Evaluationとする。
  5. GetValue(rightRef)を返す。

13.14 Conditional Operator ( ? : )

Syntax

ConditionalExpression[In, Yield, Await] : ShortCircuitExpression[?In, ?Yield, ?Await] ShortCircuitExpression[?In, ?Yield, ?Await] ? AssignmentExpression[+In, ?Yield, ?Await] : AssignmentExpression[?In, ?Yield, ?Await] Note

ECMAScriptにおけるConditionalExpressionのgrammarは、CおよびJavaのものとはわずかに異なります。CおよびJavaでは、second subexpressionがExpressionであることを許可しますが、third expressionはConditionalExpressionに制限します。ECMAScriptでこの違いがある動機は、assignment expressionがconditionalのいずれのarmによってもgovernedできるようにし、centre expressionとしてのcomma expressionという紛らわしく、かなり役に立たないcaseを排除するためです。

13.14.1 Runtime Semantics: Evaluation

ConditionalExpression : ShortCircuitExpression ? AssignmentExpression : AssignmentExpression
  1. leftRefShortCircuitExpressionの ? Evaluationとする。
  2. leftValueToBoolean(? GetValue(leftRef))とする。
  3. leftValuetrueなら、
    1. trueRefを最初のAssignmentExpressionの ? Evaluationとする。
    2. GetValue(trueRef)を返す。
  4. falseRefを2番目のAssignmentExpressionの ? Evaluationとする。
  5. GetValue(falseRef)を返す。

13.15 Assignment Operators

Syntax

AssignmentExpression[In, Yield, Await] : ConditionalExpression[?In, ?Yield, ?Await] [+Yield] YieldExpression[?In, ?Await] ArrowFunction[?In, ?Yield, ?Await] AsyncArrowFunction[?In, ?Yield, ?Await] LeftHandSideExpression[?Yield, ?Await] = AssignmentExpression[?In, ?Yield, ?Await] LeftHandSideExpression[?Yield, ?Await] AssignmentOperator AssignmentExpression[?In, ?Yield, ?Await] LeftHandSideExpression[?Yield, ?Await] &&= AssignmentExpression[?In, ?Yield, ?Await] LeftHandSideExpression[?Yield, ?Await] ||= AssignmentExpression[?In, ?Yield, ?Await] LeftHandSideExpression[?Yield, ?Await] ??= AssignmentExpression[?In, ?Yield, ?Await] AssignmentOperator : one of *= /= %= += -= <<= >>= >>>= &= ^= |= **=

13.15.1 Static Semantics: Early Errors

AssignmentExpression : LeftHandSideExpression = AssignmentExpression AssignmentExpression : LeftHandSideExpression AssignmentOperator AssignmentExpression AssignmentExpression : LeftHandSideExpression &&= AssignmentExpression LeftHandSideExpression ||= AssignmentExpression LeftHandSideExpression ??= AssignmentExpression

13.15.2 Runtime Semantics: Evaluation

AssignmentExpression : LeftHandSideExpression = AssignmentExpression
  1. LeftHandSideExpressionObjectLiteralでもArrayLiteralでもないなら、
    1. leftRefLeftHandSideExpressionの ? Evaluationとする。
    2. LeftHandSideExpressionAssignmentTargetTypeweb-compatなら、ReferenceError例外をthrowする。
    3. IsAnonymousFunctionDefinition(AssignmentExpression)がtrueであり、かつLeftHandSideExpressionIsIdentifierReftrueなら、
      1. lhsLeftHandSideExpressionStringValueとする。
      2. rightValueを、引数lhsを伴うAssignmentExpressionの ? NamedEvaluationとする。
    4. そうでなければ、
      1. rightRefAssignmentExpressionの ? Evaluationとする。
      2. rightValueを ? GetValue(rightRef) とする。
    5. PutValue(leftRef, rightValue)を実行する。
    6. rightValueを返す。
  2. assignmentPatternLeftHandSideExpressionによってcoverされるAssignmentPatternとする。
  3. rightRefAssignmentExpressionの ? Evaluationとする。
  4. rightValueを ? GetValue(rightRef) とする。
  5. 引数rightValueを伴うassignmentPatternの ? DestructuringAssignmentEvaluationを実行する。
  6. rightValueを返す。
AssignmentExpression : LeftHandSideExpression AssignmentOperator AssignmentExpression
  1. leftRefLeftHandSideExpressionの ? Evaluationとする。
  2. LeftHandSideExpressionAssignmentTargetTypeweb-compatなら、ReferenceError例外をthrowする。
  3. leftValueを ? GetValue(leftRef) とする。
  4. rightRefAssignmentExpressionの ? Evaluationとする。
  5. rightValueを ? GetValue(rightRef) とする。
  6. assignmentOpTextAssignmentOperatorによってmatchされたsource textとする。
  7. opTextを、次のtable内でassignmentOpTextに関連付けられたUnicode code pointsのsequenceとする:
    assignmentOpText opText
    **= **
    *= *
    /= /
    %= %
    += +
    -= -
    <<= <<
    >>= >>
    >>>= >>>
    &= &
    ^= ^
    |= |
  8. resultを ? ApplyStringOrNumericBinaryOperator(leftValue, opText, rightValue) とする。
  9. PutValue(leftRef, result)を実行する。
  10. resultを返す。
AssignmentExpression : LeftHandSideExpression &&= AssignmentExpression
  1. leftRefLeftHandSideExpressionの ? Evaluationとする。
  2. leftValueを ? GetValue(leftRef) とする。
  3. ToBoolean(leftValue)がfalseなら、leftValueを返す。
  4. IsAnonymousFunctionDefinition(AssignmentExpression)がtrueであり、かつLeftHandSideExpressionIsIdentifierReftrueなら、
    1. lhsLeftHandSideExpressionStringValueとする。
    2. rightValueを、引数lhsを伴うAssignmentExpressionの ? NamedEvaluationとする。
  5. そうでなければ、
    1. rightRefAssignmentExpressionの ? Evaluationとする。
    2. rightValueを ? GetValue(rightRef) とする。
  6. PutValue(leftRef, rightValue)を実行する。
  7. rightValueを返す。
AssignmentExpression : LeftHandSideExpression ||= AssignmentExpression
  1. leftRefLeftHandSideExpressionの ? Evaluationとする。
  2. leftValueを ? GetValue(leftRef) とする。
  3. ToBoolean(leftValue)がtrueなら、leftValueを返す。
  4. IsAnonymousFunctionDefinition(AssignmentExpression)がtrueであり、かつLeftHandSideExpressionIsIdentifierReftrueなら、
    1. lhsLeftHandSideExpressionStringValueとする。
    2. rightValueを、引数lhsを伴うAssignmentExpressionの ? NamedEvaluationとする。
  5. そうでなければ、
    1. rightRefAssignmentExpressionの ? Evaluationとする。
    2. rightValueを ? GetValue(rightRef) とする。
  6. PutValue(leftRef, rightValue)を実行する。
  7. rightValueを返す。
AssignmentExpression : LeftHandSideExpression ??= AssignmentExpression
  1. leftRefLeftHandSideExpressionの ? Evaluationとする。
  2. leftValueを ? GetValue(leftRef) とする。
  3. leftValueundefinedでもnullでもないなら、leftValueを返す。
  4. IsAnonymousFunctionDefinition(AssignmentExpression)がtrueであり、かつLeftHandSideExpressionIsIdentifierReftrueなら、
    1. lhsLeftHandSideExpressionStringValueとする。
    2. rightValueを、引数lhsを伴うAssignmentExpressionの ? NamedEvaluationとする。
  5. そうでなければ、
    1. rightRefAssignmentExpressionの ? Evaluationとする。
    2. rightValueを ? GetValue(rightRef) とする。
  6. PutValue(leftRef, rightValue)を実行する。
  7. rightValueを返す。
Note

このexpressionがstrict mode code内に出現する場合、step 1.e3222におけるleftRefがunresolvable referenceであるなら、それはruntime errorです。そうであれば、ReferenceError例外がthrowされます。さらに、step 9666におけるleftRefが、attribute value { [[Writable]]: false }を持つdata property、attribute value { [[Set]]: undefined }を持つaccessor property、またはIsExtensible predicateが値falseを返すobjectのnon-existent propertyへのreferenceである場合、それはruntime errorです。これらの場合、TypeError例外がthrowされます。

13.15.3 ApplyStringOrNumericBinaryOperator ( leftValue, opText, rightValue )

The abstract operation ApplyStringOrNumericBinaryOperator takes arguments leftValue (an ECMAScript language value), opText (**, *, /, %, +, -, <<, >>, >>>, &, ^, or |), and rightValue (an ECMAScript language value) and returns either a normal completion containing either a String, a BigInt, or a Number, or a throw completion. It performs the following steps when called:

  1. opText+なら、
    1. leftPrimitiveを ? ToPrimitive(leftValue) とする。
    2. rightPrimitiveを ? ToPrimitive(rightValue) とする。
    3. leftPrimitiveがStringまたはrightPrimitiveがStringなら、
      1. leftStringを ? ToString(leftPrimitive) とする。
      2. rightStringを ? ToString(rightPrimitive) とする。
      3. leftStringrightStringstring-concatenationを返す。
    4. leftValueleftPrimitiveに設定する。
    5. rightValuerightPrimitiveに設定する。
  2. NOTE: この時点では、numeric operationでなければならない。
  3. leftNumberを ? ToNumeric(leftValue) とする。
  4. rightNumberを ? ToNumeric(rightValue) とする。
  5. SameType(leftNumber, rightNumber)がfalseなら、TypeError例外をthrowする。
  6. leftNumberがBigIntなら、
    1. opText**なら、? BigInt::exponentiate(leftNumber, rightNumber)を返す。
    2. opText/なら、? BigInt::divide(leftNumber, rightNumber)を返す。
    3. opText%なら、? BigInt::remainder(leftNumber, rightNumber)を返す。
    4. opText>>>なら、? BigInt::unsignedRightShift(leftNumber, rightNumber)を返す。
    5. operationを、次のtable内でopTextに関連付けられたabstract operationとする:
      opText operation
      * BigInt::multiply
      + BigInt::add
      - BigInt::subtract
      << BigInt::leftShift
      >> BigInt::signedRightShift
      & BigInt::bitwiseAND
      ^ BigInt::bitwiseXOR
      | BigInt::bitwiseOR
  7. そうでなければ、
    1. Assert: leftNumberはNumberである。
    2. operationを、次のtable内でopTextに関連付けられたabstract operationとする:
      opText operation
      ** Number::exponentiate
      * Number::multiply
      / Number::divide
      % Number::remainder
      + Number::add
      - Number::subtract
      << Number::leftShift
      >> Number::signedRightShift
      >>> Number::unsignedRightShift
      & Number::bitwiseAND
      ^ Number::bitwiseXOR
      | Number::bitwiseOR
  8. operation(leftNumber, rightNumber)を返す。
Note 1

steps 1.aおよび1.bにおけるToPrimitiveへのcallsでは、hintは提供されません。Datesを除くすべてのstandard objectsは、hintがないことをnumberが与えられたかのように処理します;Datesは、hintがないことをstringが与えられたかのように処理します。Exotic objectsは、hintがないことを別の方法で処理する場合があります。

Note 2

Step 1.cは、logical-and operationではなくlogical-or operationを使用する点で、IsLessThan algorithmのstep 3とは異なります。

13.15.4 EvaluateStringOrNumericBinaryExpression ( leftOperand, opText, rightOperand )

The abstract operation EvaluateStringOrNumericBinaryExpression takes arguments leftOperand (a Parse Node), opText (**, *, /, %, +, -, <<, >>, >>>, &, ^, or |), and rightOperand (a Parse Node) and returns either a normal completion containing either a String, a BigInt, or a Number, or an abrupt completion. It performs the following steps when called:

  1. leftRefleftOperandの ? Evaluationとする。
  2. leftValueを ? GetValue(leftRef) とする。
  3. rightRefrightOperandの ? Evaluationとする。
  4. rightValueを ? GetValue(rightRef) とする。
  5. ApplyStringOrNumericBinaryOperator(leftValue, opText, rightValue)を返す。

13.15.5 Destructuring Assignment

Supplemental Syntax

特定の状況で、production
AssignmentExpression : LeftHandSideExpression = AssignmentExpression
のinstanceを処理するとき、LeftHandSideExpressionのinterpretationは次のgrammarを使用してrefineされます:

AssignmentPattern[Yield, Await] : ObjectAssignmentPattern[?Yield, ?Await] ArrayAssignmentPattern[?Yield, ?Await] ObjectAssignmentPattern[Yield, Await] : { } { AssignmentRestProperty[?Yield, ?Await] } { AssignmentPropertyList[?Yield, ?Await] } { AssignmentPropertyList[?Yield, ?Await] , AssignmentRestProperty[?Yield, ?Await]opt } ArrayAssignmentPattern[Yield, Await] : [ Elisionopt AssignmentRestElement[?Yield, ?Await]opt ] [ AssignmentElementList[?Yield, ?Await] ] [ AssignmentElementList[?Yield, ?Await] , Elisionopt AssignmentRestElement[?Yield, ?Await]opt ] AssignmentRestProperty[Yield, Await] : ... DestructuringAssignmentTarget[?Yield, ?Await] AssignmentPropertyList[Yield, Await] : AssignmentProperty[?Yield, ?Await] AssignmentPropertyList[?Yield, ?Await] , AssignmentProperty[?Yield, ?Await] AssignmentElementList[Yield, Await] : AssignmentElisionElement[?Yield, ?Await] AssignmentElementList[?Yield, ?Await] , AssignmentElisionElement[?Yield, ?Await] AssignmentElisionElement[Yield, Await] : Elisionopt AssignmentElement[?Yield, ?Await] AssignmentProperty[Yield, Await] : IdentifierReference[?Yield, ?Await] Initializer[+In, ?Yield, ?Await]opt PropertyName[?Yield, ?Await] : AssignmentElement[?Yield, ?Await] AssignmentElement[Yield, Await] : DestructuringAssignmentTarget[?Yield, ?Await] Initializer[+In, ?Yield, ?Await]opt AssignmentRestElement[Yield, Await] : ... DestructuringAssignmentTarget[?Yield, ?Await] DestructuringAssignmentTarget[Yield, Await] : LeftHandSideExpression[?Yield, ?Await]

13.15.5.1 Static Semantics: Early Errors

AssignmentProperty : IdentifierReference Initializeropt AssignmentRestProperty : ... DestructuringAssignmentTarget DestructuringAssignmentTarget : LeftHandSideExpression

13.15.5.2 Runtime Semantics: DestructuringAssignmentEvaluation

The syntax-directed operation DestructuringAssignmentEvaluation takes argument value (an ECMAScript language value) and returns either a normal completion containing unused or an abrupt completion. It is defined piecewise over the following productions:

ObjectAssignmentPattern : { }
  1. RequireObjectCoercible(value)を実行する。
  2. unusedを返す。
ObjectAssignmentPattern : { AssignmentPropertyList } { AssignmentPropertyList , }
  1. RequireObjectCoercible(value)を実行する。
  2. 引数valueを伴うAssignmentPropertyListの ? PropertyDestructuringAssignmentEvaluationを実行する。
  3. unusedを返す。
ObjectAssignmentPattern : { AssignmentRestProperty }
  1. RequireObjectCoercible(value)を実行する。
  2. excludedNamesを新しい空のListとする。
  3. 引数valueおよびexcludedNamesを伴うAssignmentRestPropertyの ? RestDestructuringAssignmentEvaluationを返す。
ObjectAssignmentPattern : { AssignmentPropertyList , AssignmentRestProperty }
  1. RequireObjectCoercible(value)を実行する。
  2. excludedNamesを、引数valueを伴うAssignmentPropertyListの ? PropertyDestructuringAssignmentEvaluationとする。
  3. 引数valueおよびexcludedNamesを伴うAssignmentRestPropertyの ? RestDestructuringAssignmentEvaluationを返す。
ArrayAssignmentPattern : [ ]
  1. iteratorRecordを ? GetIterator(value, sync) とする。
  2. IteratorClose(iteratorRecord, NormalCompletion(unused))を返す。
ArrayAssignmentPattern : [ Elision ]
  1. iteratorRecordを ? GetIterator(value, sync) とする。
  2. resultを、引数iteratorRecordを伴うElisionIteratorDestructuringAssignmentEvaluationCompletionとする。
  3. iteratorRecord.[[Done]]falseなら、? IteratorClose(iteratorRecord, result)を返す。
  4. resultを返す。
ArrayAssignmentPattern : [ Elisionopt AssignmentRestElement ]
  1. iteratorRecordを ? GetIterator(value, sync) とする。
  2. Elisionが存在するなら、
    1. statusを、引数iteratorRecordを伴うElisionIteratorDestructuringAssignmentEvaluationCompletionとする。
    2. statusabrupt completionなら、
      1. Assert: iteratorRecord.[[Done]]trueである。
      2. statusを返す。
  3. resultを、引数iteratorRecordを伴うAssignmentRestElementIteratorDestructuringAssignmentEvaluationCompletionとする。
  4. iteratorRecord.[[Done]]falseなら、? IteratorClose(iteratorRecord, result)を返す。
  5. resultを返す。
ArrayAssignmentPattern : [ AssignmentElementList ]
  1. iteratorRecordを ? GetIterator(value, sync) とする。
  2. resultを、引数iteratorRecordを伴うAssignmentElementListIteratorDestructuringAssignmentEvaluationCompletionとする。
  3. iteratorRecord.[[Done]]falseなら、? IteratorClose(iteratorRecord, result)を返す。
  4. resultを返す。
ArrayAssignmentPattern : [ AssignmentElementList , Elisionopt AssignmentRestElementopt ]
  1. iteratorRecordを ? GetIterator(value, sync) とする。
  2. statusを、引数iteratorRecordを伴うAssignmentElementListIteratorDestructuringAssignmentEvaluationCompletionとする。
  3. statusabrupt completionなら、
    1. iteratorRecord.[[Done]]falseなら、? IteratorClose(iteratorRecord, status)を返す。
    2. statusを返す。
  4. Elisionが存在するなら、
    1. statusを、引数iteratorRecordを伴うElisionIteratorDestructuringAssignmentEvaluationCompletionに設定する。
    2. statusabrupt completionなら、
      1. Assert: iteratorRecord.[[Done]]trueである。
      2. statusを返す。
  5. AssignmentRestElementが存在するなら、
    1. statusを、引数iteratorRecordを伴うAssignmentRestElementIteratorDestructuringAssignmentEvaluationCompletionに設定する。
  6. iteratorRecord.[[Done]]falseなら、? IteratorClose(iteratorRecord, status)を返す。
  7. statusを返す。

13.15.5.3 Runtime Semantics: PropertyDestructuringAssignmentEvaluation

The syntax-directed operation PropertyDestructuringAssignmentEvaluation takes argument value (an ECMAScript language value) and returns either a normal completion containing a List of property keys or an abrupt completion. これは、destructured property keysすべてのlistを収集します。 It is defined piecewise over the following productions:

AssignmentPropertyList : AssignmentPropertyList , AssignmentProperty
  1. propertyNamesを、引数valueを伴うAssignmentPropertyListの ? PropertyDestructuringAssignmentEvaluationとする。
  2. nextNamesを、引数valueを伴うAssignmentPropertyの ? PropertyDestructuringAssignmentEvaluationとする。
  3. propertyNamesnextNameslist-concatenationを返す。
AssignmentProperty : IdentifierReference Initializeropt
  1. propertyNameIdentifierReferenceStringValueとする。
  2. leftRefを ? ResolveBinding(propertyName) とする。
  3. valueを ? GetV(value, propertyName) に設定する。
  4. Initializerが存在し、かつvalueundefinedなら、
    1. IsAnonymousFunctionDefinition(Initializer)がtrueなら、
      1. valueを、引数propertyNameを伴うInitializerの ? NamedEvaluationに設定する。
    2. そうでなければ、
      1. defaultValueInitializerの ? Evaluationとする。
      2. valueを ? GetValue(defaultValue) に設定する。
  5. PutValue(leftRef, value)を実行する。
  6. « propertyName »を返す。
AssignmentProperty : PropertyName : AssignmentElement
  1. namePropertyNameの ? Evaluationとする。
  2. 引数valueおよびnameを伴うAssignmentElementの ? KeyedDestructuringAssignmentEvaluationを実行する。
  3. « name »を返す。

13.15.5.4 Runtime Semantics: RestDestructuringAssignmentEvaluation

The syntax-directed operation RestDestructuringAssignmentEvaluation takes arguments value (an ECMAScript language value) and excludedNames (a List of property keys) and returns either a normal completion containing unused or an abrupt completion. It is defined piecewise over the following productions:

AssignmentRestProperty : ... DestructuringAssignmentTarget
  1. leftRefDestructuringAssignmentTargetの ? Evaluationとする。
  2. restObjOrdinaryObjectCreate(%Object.prototype%)とする。
  3. CopyDataProperties(restObj, value, excludedNames)を実行する。
  4. PutValue(leftRef, restObj)を返す。

13.15.5.5 Runtime Semantics: IteratorDestructuringAssignmentEvaluation

The syntax-directed operation IteratorDestructuringAssignmentEvaluation takes argument iteratorRecord (an Iterator Record) and returns either a normal completion containing unused or an abrupt completion. It is defined piecewise over the following productions:

AssignmentElementList : AssignmentElisionElement
  1. 引数iteratorRecordを伴うAssignmentElisionElementの ? IteratorDestructuringAssignmentEvaluationを返す。
AssignmentElementList : AssignmentElementList , AssignmentElisionElement
  1. 引数iteratorRecordを伴うAssignmentElementListの ? IteratorDestructuringAssignmentEvaluationを実行する。
  2. 引数iteratorRecordを伴うAssignmentElisionElementの ? IteratorDestructuringAssignmentEvaluationを返す。
AssignmentElisionElement : AssignmentElement
  1. 引数iteratorRecordを伴うAssignmentElementの ? IteratorDestructuringAssignmentEvaluationを返す。
AssignmentElisionElement : Elision AssignmentElement
  1. 引数iteratorRecordを伴うElisionの ? IteratorDestructuringAssignmentEvaluationを実行する。
  2. 引数iteratorRecordを伴うAssignmentElementの ? IteratorDestructuringAssignmentEvaluationを返す。
Elision : ,
  1. iteratorRecord.[[Done]]falseなら、
    1. IteratorStep(iteratorRecord)を実行する。
  2. unusedを返す。
Elision : Elision ,
  1. 引数iteratorRecordを伴うElisionの ? IteratorDestructuringAssignmentEvaluationを実行する。
  2. iteratorRecord.[[Done]]falseなら、
    1. IteratorStep(iteratorRecord)を実行する。
  3. unusedを返す。
AssignmentElement : DestructuringAssignmentTarget Initializeropt
  1. DestructuringAssignmentTargetObjectLiteralでもArrayLiteralでもないなら、
    1. leftRefDestructuringAssignmentTargetの ? Evaluationとする。
  2. valueundefinedとする。
  3. iteratorRecord.[[Done]]falseなら、
    1. nextを ? IteratorStepValue(iteratorRecord) とする。
    2. nextdoneでないなら、
      1. valuenextに設定する。
  4. Initializerが存在し、かつvalueundefinedなら、
    1. IsAnonymousFunctionDefinition(Initializer)がtrueであり、かつDestructuringAssignmentTargetIsIdentifierReftrueなら、
      1. targetDestructuringAssignmentTargetStringValueとする。
      2. vを、引数targetを伴うInitializerの ? NamedEvaluationとする。
    2. そうでなければ、
      1. defaultValueInitializerの ? Evaluationとする。
      2. vを ? GetValue(defaultValue) とする。
  5. そうでなければ、
    1. vvalueとする。
  6. DestructuringAssignmentTargetObjectLiteralまたはArrayLiteralのいずれかなら、
    1. nestedAssignmentPatternDestructuringAssignmentTargetによってcoverされるAssignmentPatternとする。
    2. 引数vを伴うnestedAssignmentPatternの ? DestructuringAssignmentEvaluationを返す。
  7. PutValue(leftRef, v)を返す。
Note

left to right evaluation orderは、iteratorへaccessする前、またはInitializerを評価する前に、destructuring patternではないDestructuringAssignmentTargetを評価することによって維持されます。

AssignmentRestElement : ... DestructuringAssignmentTarget
  1. DestructuringAssignmentTargetObjectLiteralでもArrayLiteralでもないなら、
    1. leftRefDestructuringAssignmentTargetの ? Evaluationとする。
  2. arrayを ! ArrayCreate(0) とする。
  3. nを0とする。
  4. iteratorRecord.[[Done]]falseである間、繰り返す
    1. nextを ? IteratorStepValue(iteratorRecord) とする。
    2. nextdoneでないなら、
      1. CreateDataPropertyOrThrow(array, ! ToString(𝔽(n)), next)を実行する。
      2. nn + 1に設定する。
  5. DestructuringAssignmentTargetObjectLiteralでもArrayLiteralでもないなら、
    1. PutValue(leftRef, array)を返す。
  6. nestedAssignmentPatternDestructuringAssignmentTargetによってcoverされるAssignmentPatternとする。
  7. 引数arrayを伴うnestedAssignmentPatternの ? DestructuringAssignmentEvaluationを返す。

13.15.5.6 Runtime Semantics: KeyedDestructuringAssignmentEvaluation

The syntax-directed operation KeyedDestructuringAssignmentEvaluation takes arguments value (an ECMAScript language value) and propertyName (a property key) and returns either a normal completion containing unused or an abrupt completion. It is defined piecewise over the following productions:

AssignmentElement : DestructuringAssignmentTarget Initializeropt
  1. DestructuringAssignmentTargetObjectLiteralでもArrayLiteralでもないなら、
    1. leftRefDestructuringAssignmentTargetの ? Evaluationとする。
  2. valueを ? GetV(value, propertyName) に設定する。
  3. Initializerが存在し、かつvalueundefinedなら、
    1. IsAnonymousFunctionDefinition(Initializer)がtrueであり、かつDestructuringAssignmentTargetIsIdentifierReftrueなら、
      1. targetDestructuringAssignmentTargetStringValueとする。
      2. rhsValueを、引数targetを伴うInitializerの ? NamedEvaluationとする。
    2. そうでなければ、
      1. defaultValueInitializerの ? Evaluationとする。
      2. rhsValueを ? GetValue(defaultValue) とする。
  4. そうでなければ、
    1. rhsValuevalueとする。
  5. DestructuringAssignmentTargetObjectLiteralまたはArrayLiteralのいずれかなら、
    1. assignmentPatternDestructuringAssignmentTargetによってcoverされるAssignmentPatternとする。
    2. 引数rhsValueを伴うassignmentPatternの ? DestructuringAssignmentEvaluationを返す。
  6. PutValue(leftRef, rhsValue)を返す。

13.16 Comma Operator ( , )

Syntax

Expression[In, Yield, Await] : AssignmentExpression[?In, ?Yield, ?Await] Expression[?In, ?Yield, ?Await] , AssignmentExpression[?In, ?Yield, ?Await]

13.16.1 Runtime Semantics: Evaluation

Expression : Expression , AssignmentExpression
  1. leftRefExpressionの ? Evaluationとする。
  2. GetValue(leftRef)を実行する。
  3. rightRefAssignmentExpressionの ? Evaluationとする。
  4. GetValue(rightRef)を返す。
Note

その値は使用されませんが、observable side-effectsを持つ場合があるため、GetValueは呼び出されなければなりません。

14 ECMAScript Language: Statements and Declarations

Syntax

Statement[Yield, Await, Return] : BlockStatement[?Yield, ?Await, ?Return] VariableStatement[?Yield, ?Await] EmptyStatement ExpressionStatement[?Yield, ?Await] IfStatement[?Yield, ?Await, ?Return] BreakableStatement[?Yield, ?Await, ?Return] ContinueStatement[?Yield, ?Await] BreakStatement[?Yield, ?Await] [+Return] ReturnStatement[?Yield, ?Await] WithStatement[?Yield, ?Await, ?Return] LabelledStatement[?Yield, ?Await, ?Return] ThrowStatement[?Yield, ?Await] TryStatement[?Yield, ?Await, ?Return] DebuggerStatement Declaration[Yield, Await] : HoistableDeclaration[?Yield, ?Await, ~Default] ClassDeclaration[?Yield, ?Await, ~Default] LexicalDeclaration[+In, ?Yield, ?Await] HoistableDeclaration[Yield, Await, Default] : FunctionDeclaration[?Yield, ?Await, ?Default] GeneratorDeclaration[?Yield, ?Await, ?Default] AsyncFunctionDeclaration[?Yield, ?Await, ?Default] AsyncGeneratorDeclaration[?Yield, ?Await, ?Default] BreakableStatement[Yield, Await, Return] : IterationStatement[?Yield, ?Await, ?Return] SwitchStatement[?Yield, ?Await, ?Return]

14.1 Statement Semantics

14.1.1 Runtime Semantics: Evaluation

HoistableDeclaration : GeneratorDeclaration AsyncFunctionDeclaration AsyncGeneratorDeclaration
  1. emptyを返す。
HoistableDeclaration : FunctionDeclaration
  1. FunctionDeclarationの ? Evaluationを返す。
BreakableStatement : IterationStatement SwitchStatement
  1. newLabelSetを新しい空のListとする。
  2. 引数newLabelSetを伴うthis BreakableStatementの ? LabelledEvaluationを返す。

14.2 Block

Syntax

BlockStatement[Yield, Await, Return] : Block[?Yield, ?Await, ?Return] Block[Yield, Await, Return] : { StatementList[?Yield, ?Await, ?Return]opt } StatementList[Yield, Await, Return] : StatementListItem[?Yield, ?Await, ?Return] StatementList[?Yield, ?Await, ?Return] StatementListItem[?Yield, ?Await, ?Return] StatementListItem[Yield, Await, Return] : Statement[?Yield, ?Await, ?Return] Declaration[?Yield, ?Await]

14.2.1 Static Semantics: Early Errors

Block : { StatementList }

14.2.2 Runtime Semantics: Evaluation

Block : { }
  1. emptyを返す。
Block : { StatementList }
  1. oldEnv を、実行中の実行コンテキストの LexicalEnvironment とする。
  2. blockEnvNewDeclarativeEnvironment(oldEnv) とする。
  3. BlockDeclarationInstantiation(StatementList, blockEnv) を実行する。
  4. 実行中の実行コンテキストの LexicalEnvironment を blockEnv に設定する。
  5. blockValueStatementListEvaluationCompletion とする。
  6. blockValueCompletion(DisposeResources(blockEnv.[[DisposableResourceStack]], blockValue)) に設定する。
  7. 実行中の実行コンテキストの LexicalEnvironment を oldEnv に設定する。
  8. Return ? blockValue.
Note 1

controlがどのようにBlockから離れても、LexicalEnvironmentは常に以前のstateへ復元されます。

StatementList : StatementList StatementListItem
  1. slStatementListの ? Evaluationとする。
  2. sStatementListItemEvaluationCompletionとする。
  3. UpdateEmpty(s, sl)を返す。
Note 2

StatementListの値は、StatementList内で値を生成する最後のitemの値です。例えば、次のeval functionへのcallsはすべて値1を返します:

eval("1;;;;;")
eval("1;{}")
eval("1;var a;")

14.2.3 BlockDeclarationInstantiation ( code, envRecord )

The abstract operation BlockDeclarationInstantiation takes arguments code (a Parse Node) and envRecord (a Declarative Environment Record) and returns unused. codeはblockのbodyに対応するParse Nodeです。envRecordはbindingsが作成されるEnvironment Recordです。

Note

BlockまたはCaseBlockが評価されるとき、新しいDeclarative Environment Recordが作成され、block内でdeclaredされた各block scoped variable、constant、function、またはclassに対するbindingsがEnvironment Record内でinstantiatedされます。

これは呼び出されたとき、次のstepsを実行します:

  1. codeLexicallyScopedDeclarationsdeclsとする。
  2. 実行中の実行コンテキストのPrivateEnvironmentをprivateEnvとする。
  3. declsの各要素declについて、次を行う。
    1. declBoundNamesの各要素nameについて、次を行う。
      1. declIsConstantDeclarationtrueである場合、
        1. envRecord.CreateImmutableBinding(name, true)を実行する。
      2. そうでなければ、
        1. ホストがWebブラウザである、またはその他の形でBlock-Level Function Declarations Web Legacy Compatibility Semanticsをサポートする場合、
          1. envRecord.HasBinding(name)がfalseである場合、
            1. envRecord.CreateMutableBinding(name, false)を実行する。
        2. そうでなければ、
          1. envRecord.CreateMutableBinding(name, false)を実行する。
    2. declFunctionDeclarationGeneratorDeclarationAsyncFunctionDeclaration、またはAsyncGeneratorDeclarationのいずれかである場合、
      1. declBoundNamesの唯一の要素をfuncNameとする。
      2. envRecordおよびprivateEnvを引数として、declInstantiateFunctionObjectfuncObjとする。
      3. ホストがWebブラウザである、またはその他の形でBlock-Level Function Declarations Web Legacy Compatibility Semanticsをサポートする場合、
        1. envRecord内のfuncNameに対する束縛が未初期化束縛である場合、
          1. envRecord.InitializeBinding(funcName, funcObj)を実行する。
        2. そうでなければ、
          1. Assert: declFunctionDeclarationである。
          2. envRecord.SetMutableBinding(funcName, funcObj, false)を実行する。
      4. そうでなければ、
        1. envRecord.InitializeBinding(funcName, funcObj)を実行する。
  4. unusedを返す。

14.3 Declarations and the Variable Statement

14.3.1 Let、Const、Using、および Await Using 宣言

Note

letconstusing、および await using 宣言は、実行中の実行コンテキストの LexicalEnvironment にスコープされる変数を定義する。変数は、それを含む Environment Record がインスタンス化されるときに作成されるが、その変数の LexicalBinding が評価されるまで、いかなる方法でもアクセスできない。Initializer を持つ LexicalBinding によって定義される変数には、変数が作成されるときではなく、LexicalBinding が評価されるときに、その InitializerAssignmentExpression の値が代入される。let 宣言内の LexicalBindingInitializer を持たない場合、その LexicalBinding が評価されるときに、変数には値 undefined が代入される。

構文

LexicalDeclaration[In, Yield, Await] : LetOrConst BindingList[?In, ?Yield, ?Await, +Pattern] ; UsingDeclaration[?In, ?Yield, ?Await] [+Await] AwaitUsingDeclaration[?In, ?Yield] LetOrConst : let const UsingDeclaration[In, Yield, Await] : using [no LineTerminator here] BindingList[?In, ?Yield, ?Await, ~Pattern] ; AwaitUsingDeclaration[In, Yield] : CoverAwaitExpressionAndAwaitUsingDeclarationHead[?Yield] [no LineTerminator here] BindingList[?In, ?Yield, +Await, ~Pattern] ; BindingList[In, Yield, Await, Pattern] : LexicalBinding[?In, ?Yield, ?Await, ?Pattern] BindingList[?In, ?Yield, ?Await, ?Pattern] , LexicalBinding[?In, ?Yield, ?Await, ?Pattern] LexicalBinding[In, Yield, Await, Pattern] : BindingIdentifier[?Yield, ?Await] Initializer[?In, ?Yield, ?Await]opt [+Pattern] BindingPattern[?Yield, ?Await] Initializer[?In, ?Yield, ?Await]

補足構文

生成規則のインスタンスを処理する際
AwaitUsingDeclaration : CoverAwaitExpressionAndAwaitUsingDeclarationHead BindingList ;
CoverAwaitExpressionAndAwaitUsingDeclarationHead の解釈は、次の文法を使用して精緻化される:

AwaitUsingDeclarationHead : await [no LineTerminator here] using

14.3.1.1 Static Semantics: 早期エラー

LexicalDeclaration : LetOrConst BindingList ; UsingDeclaration : using BindingList ; AwaitUsingDeclaration : CoverAwaitExpressionAndAwaitUsingDeclarationHead BindingList ; LexicalBinding : BindingIdentifier Initializeropt

14.3.1.2 Runtime Semantics: Evaluation

LexicalDeclaration : LetOrConst BindingList ;
  1. 引数 normalBindingListBindingEvaluation を実行する。
  2. empty を返す。
UsingDeclaration : using BindingList ;
  1. 引数 sync-disposeBindingListBindingEvaluation を実行する。
  2. empty を返す。
AwaitUsingDeclaration : CoverAwaitExpressionAndAwaitUsingDeclarationHead BindingList ;
  1. 引数 async-disposeBindingListBindingEvaluation を実行する。
  2. empty を返す。

14.3.1.3 Runtime Semantics: BindingEvaluation

The syntax-directed operation BindingEvaluation takes argument kind (normalsync-dispose、または async-dispose) and returns unused を含む normal completion または abrupt completion. It is defined piecewise over the following productions:

BindingList : BindingList , LexicalBinding
  1. 引数 kind で、派生した BindingListBindingEvaluation を実行する。
  2. 引数 kindLexicalBindingBindingEvaluation を返す。
LexicalBinding : BindingIdentifier
  1. Assert: kindnormal である。
  2. lhs を ! ResolveBinding(BindingIdentifierStringValue) とする。
  3. InitializeReferencedBinding(lhs, undefined) を実行する。
  4. unused を返す。
Note

静的意味論の規則により、この形式の LexicalBindingconstusing、または await using 宣言では決して発生しないことが保証される。

LexicalBinding : BindingIdentifier Initializer
  1. bindingIdBindingIdentifierStringValue とする。
  2. lhs を ! ResolveBinding(bindingId) とする。
  3. IsAnonymousFunctionDefinition(Initializer) が true である場合、then
    1. value を、引数 bindingIdInitializerNamedEvaluation とする。
  4. Else,
    1. rhsInitializerEvaluation とする。
    2. value を ? GetValue(rhs) とする。
  5. kindnormal でない場合、then
    1. Assert: IsUnresolvableReference(lhs) は false である。
    2. baselhs.[[Base]] とする。
    3. Assert: baseDeclarative Environment Record である。
    4. AddDisposableResource(base.[[DisposableResourceStack]], value, kind) を実行する。
  6. InitializeReferencedBinding(lhs, value) を実行する。
  7. unused を返す。
LexicalBinding : BindingPattern Initializer
  1. Assert: kindnormal である。
  2. rhsInitializerEvaluation とする。
  3. value を ? GetValue(rhs) とする。
  4. envRecord を、実行中の実行コンテキストの LexicalEnvironment とする。
  5. 引数 value および envRecord で、BindingPatternBindingInitialization を返す。

14.3.2 Variable Statement

Note

var statementは、running execution contextのVariableEnvironmentにscopedされるvariablesを宣言します。Var variablesは、それらを含むEnvironment Recordがinstantiatedされるときに作成され、作成時にundefinedへinitializedされます。任意のVariableEnvironmentのscope内では、共通のBindingIdentifierが複数のVariableDeclarationに現れてよいですが、それらのdeclarationsはcollectivelyに1つのvariableのみを定義します。Initializerを持つVariableDeclarationによって定義されるvariableには、variableが作成されたときではなく、VariableDeclarationが実行されるときに、そのInitializerAssignmentExpressionの値が割り当てられます。

Syntax

VariableStatement[Yield, Await] : var VariableDeclarationList[+In, ?Yield, ?Await] ; VariableDeclarationList[In, Yield, Await] : VariableDeclaration[?In, ?Yield, ?Await] VariableDeclarationList[?In, ?Yield, ?Await] , VariableDeclaration[?In, ?Yield, ?Await] VariableDeclaration[In, Yield, Await] : BindingIdentifier[?Yield, ?Await] Initializer[?In, ?Yield, ?Await]opt BindingPattern[?Yield, ?Await] Initializer[?In, ?Yield, ?Await]

14.3.2.1 Runtime Semantics: Evaluation

VariableStatement : var VariableDeclarationList ;
  1. VariableDeclarationListの ? Evaluationを実行する。
  2. emptyを返す。
VariableDeclarationList : VariableDeclarationList , VariableDeclaration
  1. VariableDeclarationListの ? Evaluationを実行する。
  2. VariableDeclarationの ? Evaluationを返す。
VariableDeclaration : BindingIdentifier
  1. emptyを返す。
VariableDeclaration : BindingIdentifier Initializer
  1. bindingIdBindingIdentifierStringValueとする。
  2. lhsを ? ResolveBinding(bindingId) とする。
  3. IsAnonymousFunctionDefinition(Initializer)がtrueなら、
    1. valueを、引数bindingIdを伴うInitializerの ? NamedEvaluationとする。
  4. そうでなければ、
    1. rhsInitializerの ? Evaluationとする。
    2. valueを ? GetValue(rhs) とする。
  5. PutValue(lhs, value)を実行する。
  6. emptyを返す。
Note

VariableDeclarationがwith statement内にnestedされており、VariableDeclaration内のBindingIdentifierがwith statementのObject Environment Recordのbinding objectのproperty nameと同じである場合、step 5valueIdentifierのVariableEnvironment bindingへ割り当てる代わりに、そのpropertyへ割り当てます。

VariableDeclaration : BindingPattern Initializer
  1. rhsInitializerの ? Evaluationとする。
  2. rightValueを ? GetValue(rhs) とする。
  3. 引数rightValueおよびundefinedを伴うBindingPatternの ? BindingInitializationを返す。

14.3.3 Destructuring Binding Patterns

Syntax

BindingPattern[Yield, Await] : ObjectBindingPattern[?Yield, ?Await] ArrayBindingPattern[?Yield, ?Await] ObjectBindingPattern[Yield, Await] : { } { BindingRestProperty[?Yield, ?Await] } { BindingPropertyList[?Yield, ?Await] } { BindingPropertyList[?Yield, ?Await] , BindingRestProperty[?Yield, ?Await]opt } ArrayBindingPattern[Yield, Await] : [ Elisionopt BindingRestElement[?Yield, ?Await]opt ] [ BindingElementList[?Yield, ?Await] ] [ BindingElementList[?Yield, ?Await] , Elisionopt BindingRestElement[?Yield, ?Await]opt ] BindingRestProperty[Yield, Await] : ... BindingIdentifier[?Yield, ?Await] BindingPropertyList[Yield, Await] : BindingProperty[?Yield, ?Await] BindingPropertyList[?Yield, ?Await] , BindingProperty[?Yield, ?Await] BindingElementList[Yield, Await] : BindingElisionElement[?Yield, ?Await] BindingElementList[?Yield, ?Await] , BindingElisionElement[?Yield, ?Await] BindingElisionElement[Yield, Await] : Elisionopt BindingElement[?Yield, ?Await] BindingProperty[Yield, Await] : SingleNameBinding[?Yield, ?Await] PropertyName[?Yield, ?Await] : BindingElement[?Yield, ?Await] BindingElement[Yield, Await] : SingleNameBinding[?Yield, ?Await] BindingPattern[?Yield, ?Await] Initializer[+In, ?Yield, ?Await]opt SingleNameBinding[Yield, Await] : BindingIdentifier[?Yield, ?Await] Initializer[+In, ?Yield, ?Await]opt BindingRestElement[Yield, Await] : ... BindingIdentifier[?Yield, ?Await] ... BindingPattern[?Yield, ?Await]

14.3.3.1 Runtime Semantics: PropertyBindingInitialization

The syntax-directed operation PropertyBindingInitialization takes arguments value (an ECMAScript language value) and envRecord (an Environment Record or undefined) and returns either a normal completion containing a List of property keys or an abrupt completion. これは、bound property namesすべてのlistを収集します。 It is defined piecewise over the following productions:

BindingPropertyList : BindingPropertyList , BindingProperty
  1. boundNamesを、引数valueおよびenvRecordを伴うBindingPropertyListの ? PropertyBindingInitializationとする。
  2. nextNamesを、引数valueおよびenvRecordを伴うBindingPropertyの ? PropertyBindingInitializationとする。
  3. boundNamesnextNameslist-concatenationを返す。
BindingProperty : SingleNameBinding
  1. nameSingleNameBindingBoundNamesの唯一の要素とする。
  2. 引数valueenvRecord、およびnameを伴うSingleNameBindingの ? KeyedBindingInitializationを実行する。
  3. « name »を返す。
BindingProperty : PropertyName : BindingElement
  1. propertyKeyPropertyNameの ? Evaluationとする。
  2. 引数valueenvRecord、およびpropertyKeyを伴うBindingElementの ? KeyedBindingInitializationを実行する。
  3. « propertyKey »を返す。

14.3.3.2 Runtime Semantics: RestBindingInitialization

The syntax-directed operation RestBindingInitialization takes arguments value (an ECMAScript language value), envRecord (an Environment Record or undefined), and excludedNames (a List of property keys) and returns either a normal completion containing unused or an abrupt completion. It is defined piecewise over the following productions:

BindingRestProperty : ... BindingIdentifier
  1. lhsを ? ResolveBinding(BindingIdentifierStringValue, envRecord) とする。
  2. restObjOrdinaryObjectCreate(%Object.prototype%)とする。
  3. CopyDataProperties(restObj, value, excludedNames)を実行する。
  4. envRecordundefinedなら、? PutValue(lhs, restObj)を返す。
  5. InitializeReferencedBinding(lhs, restObj)を返す。

14.3.3.3 Runtime Semantics: KeyedBindingInitialization

The syntax-directed operation KeyedBindingInitialization takes arguments value (an ECMAScript language value), envRecord (an Environment Record or undefined), and propertyName (a property key) and returns either a normal completion containing unused or an abrupt completion.

Note

envRecordundefinedが渡された場合、それはinitialization valueを割り当てるためにPutValue operationが使用されるべきであることを示します。これはnon-strict functionsのformal parameter listsの場合です。その場合、同じ名前を持つ複数のparametersの可能性に対処するため、formal parameter bindingsはpreinitializedされます。

It is defined piecewise over the following productions:

BindingElement : BindingPattern Initializeropt
  1. valueを ? GetV(value, propertyName) に設定する。
  2. Initializerが存在し、かつvalueundefinedなら、
    1. defaultValueInitializerの ? Evaluationとする。
    2. valueを ? GetValue(defaultValue) に設定する。
  3. 引数valueおよびenvRecordを伴うBindingPatternの ? BindingInitializationを返す。
SingleNameBinding : BindingIdentifier Initializeropt
  1. bindingIdBindingIdentifierStringValueとする。
  2. lhsを ? ResolveBinding(bindingId, envRecord) とする。
  3. valueを ? GetV(value, propertyName) に設定する。
  4. Initializerが存在し、かつvalueundefinedなら、
    1. IsAnonymousFunctionDefinition(Initializer)がtrueなら、
      1. valueを、引数bindingIdを伴うInitializerの ? NamedEvaluationに設定する。
    2. そうでなければ、
      1. defaultValueInitializerの ? Evaluationとする。
      2. valueを ? GetValue(defaultValue) に設定する。
  5. envRecordundefinedなら、? PutValue(lhs, value)を返す。
  6. InitializeReferencedBinding(lhs, value)を返す。

14.4 Empty Statement

Syntax

EmptyStatement : ;

14.4.1 Runtime Semantics: Evaluation

EmptyStatement : ;
  1. emptyを返す。

14.5 Expression Statement

Syntax

ExpressionStatement[Yield, Await] : [lookahead ∉ { {, function, async [no LineTerminator here] function, class, let [ }] Expression[+In, ?Yield, ?Await] ; Note

ExpressionStatementはU+007B (LEFT CURLY BRACKET)で開始できません。これはBlockとのambiguityを生じさせる可能性があるためです。ExpressionStatementfunctionまたはclass keywordsで開始できません。これはFunctionDeclarationGeneratorDeclaration、またはClassDeclarationとのambiguityを生じさせるためです。ExpressionStatementasync functionで開始できません。これはAsyncFunctionDeclarationまたはAsyncGeneratorDeclarationとのambiguityを生じさせるためです。ExpressionStatementはtwo token sequence let [で開始できません。これは、最初のLexicalBindingArrayBindingPatternであるlet LexicalDeclarationとのambiguityを生じさせるためです。

14.5.1 Runtime Semantics: Evaluation

ExpressionStatement : Expression ;
  1. exprRefExpressionの ? Evaluationとする。
  2. GetValue(exprRef)を返す。

14.6 The if Statement

Syntax

IfStatement[Yield, Await, Return] : if ( Expression[+In, ?Yield, ?Await] ) Statement[?Yield, ?Await, ?Return] else Statement[?Yield, ?Await, ?Return] if ( Expression[+In, ?Yield, ?Await] ) Statement[?Yield, ?Await, ?Return] [lookahead ≠ else] Note
lookahead-restriction [lookahead ≠ else]は、古典的な“dangling else”問題を通常の方法で解決します。つまり、関連付けられるifの選択が他の点ではambiguousである場合、elseは候補となるifのうち最も近い(最も内側の)ものに関連付けられます

14.6.1 Static Semantics: Early Errors

IfStatement : if ( Expression ) Statement else Statement IfStatement : if ( Expression ) Statement Note

このruleを適用する必要があるのは、B.3.1で指定されるextensionが実装されている場合だけです。

14.6.2 Runtime Semantics: Evaluation

IfStatement : if ( Expression ) Statement else Statement
  1. exprRefExpressionの ? Evaluationとする。
  2. exprValueToBoolean(? GetValue(exprRef))とする。
  3. exprValuetrueなら、
    1. stmtCompletionを最初のStatementEvaluationCompletionとする。
  4. そうでなければ、
    1. stmtCompletionを2番目のStatementEvaluationCompletionとする。
  5. UpdateEmpty(stmtCompletion, undefined)を返す。
IfStatement : if ( Expression ) Statement
  1. exprRefExpressionの ? Evaluationとする。
  2. exprValueToBoolean(? GetValue(exprRef))とする。
  3. exprValuefalseなら、undefinedを返す。
  4. stmtCompletionStatementEvaluationCompletionとする。
  5. UpdateEmpty(stmtCompletion, undefined)を返す。

14.7 Iteration Statements

Syntax

IterationStatement[Yield, Await, Return] : DoWhileStatement[?Yield, ?Await, ?Return] WhileStatement[?Yield, ?Await, ?Return] ForStatement[?Yield, ?Await, ?Return] ForInOfStatement[?Yield, ?Await, ?Return]

14.7.1 Semantics

14.7.1.1 LoopContinues ( completion, labelSet )

The abstract operation LoopContinues takes arguments completion (a Completion Record) and labelSet (a List of Strings) and returns a Boolean. It performs the following steps when called:

  1. completionnormal completionなら、trueを返す。
  2. completioncontinue completionでないなら、falseを返す。
  3. completion.[[Target]]emptyなら、trueを返す。
  4. labelSetcompletion.[[Target]]を含むなら、trueを返す。
  5. falseを返す。
Note

IterationStatementStatement部分内では、ContinueStatementを使用して新しいiterationを開始できます。

14.7.1.2 Runtime Semantics: LoopEvaluation

The syntax-directed operation LoopEvaluation takes argument labelSet (a List of Strings) and returns either a normal completion containing an ECMAScript language value or an abrupt completion. It is defined piecewise over the following productions:

IterationStatement : DoWhileStatement
  1. 引数labelSetを伴うDoWhileStatementの ? DoWhileLoopEvaluationを返す。
IterationStatement : WhileStatement
  1. 引数labelSetを伴うWhileStatementの ? WhileLoopEvaluationを返す。
IterationStatement : ForStatement
  1. 引数labelSetを伴うForStatementの ? ForLoopEvaluationを返す。
IterationStatement : ForInOfStatement
  1. 引数labelSetを伴うForInOfStatementの ? ForIn/OfLoopEvaluationを返す。

14.7.2 The do-while Statement

Syntax

DoWhileStatement[Yield, Await, Return] : do Statement[?Yield, ?Await, ?Return] while ( Expression[+In, ?Yield, ?Await] ) ;

14.7.2.1 Static Semantics: Early Errors

DoWhileStatement : do Statement while ( Expression ) ; Note

このruleを適用する必要があるのは、B.3.1で指定されるextensionが実装されている場合だけです。

14.7.2.2 Runtime Semantics: DoWhileLoopEvaluation

The syntax-directed operation DoWhileLoopEvaluation takes argument labelSet (a List of Strings) and returns either a normal completion containing an ECMAScript language value or an abrupt completion. It is defined piecewise over the following productions:

DoWhileStatement : do Statement while ( Expression ) ;
  1. iterationResultundefinedとする。
  2. 繰り返す
    1. stmtResultStatementEvaluationCompletionとする。
    2. LoopContinues(stmtResult, labelSet)がfalseなら、? UpdateEmpty(stmtResult, iterationResult)を返す。
    3. stmtResult.[[Value]]emptyでないなら、iterationResultstmtResult.[[Value]]に設定する。
    4. exprRefExpressionの ? Evaluationとする。
    5. exprValueを ? GetValue(exprRef) とする。
    6. ToBoolean(exprValue)がfalseなら、iterationResultを返す。

14.7.3 The while Statement

Syntax

WhileStatement[Yield, Await, Return] : while ( Expression[+In, ?Yield, ?Await] ) Statement[?Yield, ?Await, ?Return]

14.7.3.1 Static Semantics: Early Errors

WhileStatement : while ( Expression ) Statement Note

このruleを適用する必要があるのは、B.3.1で指定されるextensionが実装されている場合だけです。

14.7.3.2 Runtime Semantics: WhileLoopEvaluation

The syntax-directed operation WhileLoopEvaluation takes argument labelSet (a List of Strings) and returns either a normal completion containing an ECMAScript language value or an abrupt completion. It is defined piecewise over the following productions:

WhileStatement : while ( Expression ) Statement
  1. iterationResultundefinedとする。
  2. 繰り返す
    1. exprRefExpressionの ? Evaluationとする。
    2. exprValueを ? GetValue(exprRef) とする。
    3. ToBoolean(exprValue)がfalseなら、iterationResultを返す。
    4. stmtResultStatementEvaluationCompletionとする。
    5. LoopContinues(stmtResult, labelSet)がfalseなら、? UpdateEmpty(stmtResult, iterationResult)を返す。
    6. stmtResult.[[Value]]emptyでないなら、iterationResultstmtResult.[[Value]]に設定する。

14.7.4 The for Statement

Syntax

ForStatement[Yield, Await, Return] : for ( [lookahead ≠ let [] Expression[~In, ?Yield, ?Await]opt ; Expression[+In, ?Yield, ?Await]opt ; Expression[+In, ?Yield, ?Await]opt ) Statement[?Yield, ?Await, ?Return] for ( var VariableDeclarationList[~In, ?Yield, ?Await] ; Expression[+In, ?Yield, ?Await]opt ; Expression[+In, ?Yield, ?Await]opt ) Statement[?Yield, ?Await, ?Return] for ( LexicalDeclaration[~In, ?Yield, ?Await] Expression[+In, ?Yield, ?Await]opt ; Expression[+In, ?Yield, ?Await]opt ) Statement[?Yield, ?Await, ?Return]

14.7.4.1 Static Semantics: Early Errors

ForStatement : for ( Expressionopt ; Expressionopt ; Expressionopt ) Statement for ( var VariableDeclarationList ; Expressionopt ; Expressionopt ) Statement for ( LexicalDeclaration Expressionopt ; Expressionopt ) Statement Note

このruleを適用する必要があるのは、B.3.1で指定されるextensionが実装されている場合だけです。

ForStatement : for ( LexicalDeclaration Expressionopt ; Expressionopt ) Statement

14.7.4.2 Runtime Semantics: ForLoopEvaluation

The syntax-directed operation ForLoopEvaluation takes argument labelSet (a List of Strings) and returns either a normal completion containing an ECMAScript language value or an abrupt completion. It is defined piecewise over the following productions:

ForStatement : for ( Expressionopt ; Expressionopt ; Expressionopt ) Statement
  1. 最初のExpressionが存在するなら、
    1. exprRefを最初のExpressionの ? Evaluationとする。
    2. GetValue(exprRef)を実行する。
  2. 2番目のExpressionが存在するなら、testを2番目のExpressionとする;そうでなければ、testemptyとする。
  3. 3番目のExpressionが存在するなら、incrementを3番目のExpressionとする;そうでなければ、incrementemptyとする。
  4. ForBodyEvaluation(test, increment, Statement, « », labelSet)を返す。
ForStatement : for ( var VariableDeclarationList ; Expressionopt ; Expressionopt ) Statement
  1. VariableDeclarationListの ? Evaluationを実行する。
  2. 最初のExpressionが存在するなら、testを最初のExpressionとする;そうでなければ、testemptyとする。
  3. 2番目のExpressionが存在するなら、incrementを2番目のExpressionとする;そうでなければ、incrementemptyとする。
  4. ForBodyEvaluation(test, increment, Statement, « », labelSet)を返す。
ForStatement : for ( LexicalDeclaration Expressionopt ; Expressionopt ) Statement
  1. oldEnv を、実行中の実行コンテキストの LexicalEnvironment とする。
  2. loopEnvNewDeclarativeEnvironment(oldEnv) とする。
  3. isConstLexicalDeclarationIsConstantDeclaration とする。
  4. boundNamesLexicalDeclarationBoundNames とする。
  5. boundNames の各要素 name について、do
    1. isConsttrue である場合、then
      1. loopEnv.CreateImmutableBinding(name, true) を実行する。
    2. Else,
      1. loopEnv.CreateMutableBinding(name, false) を実行する。
  6. 実行中の実行コンテキストの LexicalEnvironment を loopEnv に設定する。
  7. forDeclLexicalDeclarationEvaluationCompletion とする。
  8. forDeclabrupt completion である場合、then
    1. forDeclCompletion(DisposeResources(loopEnv.[[DisposableResourceStack]], forDecl)) に設定する。
    2. Assert: forDeclabrupt completion である。
    3. 実行中の実行コンテキストの LexicalEnvironment を oldEnv に設定する。
    4. Return ? forDecl.
  9. isConstfalse である場合、perIterationLetsboundNames とする。そうでなければ、perIterationLets を新しい空の List とする。
  10. 最初の Expression が存在する場合、test を最初の Expression とする。そうでなければ、testempty とする。
  11. 2番目の Expression が存在する場合、increment を2番目の Expression とする。そうでなければ、incrementempty とする。
  12. bodyResultCompletion(ForBodyEvaluation(test, increment, Statement, perIterationLets, labelSet)) とする。
  13. bodyResultCompletion(DisposeResources(loopEnv.[[DisposableResourceStack]], bodyResult)) に設定する。
  14. Assert: bodyResultnormal completion である場合、bodyResult.[[Value]]empty でない。
  15. 実行中の実行コンテキストの LexicalEnvironment を oldEnv に設定する。
  16. Return ? bodyResult.

14.7.4.3 ForBodyEvaluation ( test, increment, stmt, perIterationBindings, labelSet )

The abstract operation ForBodyEvaluation takes arguments test (an Expression Parse Node or empty), increment (an Expression Parse Node or empty), stmt (a Statement Parse Node), perIterationBindings (a List of Strings), and labelSet (a List of Strings) and returns either a normal completion containing an ECMAScript language value or an abrupt completion. It performs the following steps when called:

  1. iterationResultundefinedとする。
  2. CreatePerIterationEnvironment(perIterationBindings)を実行する。
  3. 繰り返す
    1. testemptyでないなら、
      1. testReftestの ? Evaluationとする。
      2. testValueを ? GetValue(testRef) とする。
      3. ToBoolean(testValue)がfalseなら、iterationResultを返す。
    2. resultstmtEvaluationCompletionとする。
    3. LoopContinues(result, labelSet)がfalseなら、? UpdateEmpty(result, iterationResult)を返す。
    4. result.[[Value]]emptyでないなら、iterationResultresult.[[Value]]に設定する。
    5. CreatePerIterationEnvironment(perIterationBindings)を実行する。
    6. incrementemptyでないなら、
      1. incRefincrementの ? Evaluationとする。
      2. GetValue(incRef)を実行する。

14.7.4.4 CreatePerIterationEnvironment ( perIterationBindings )

The abstract operation CreatePerIterationEnvironment takes argument perIterationBindings (a List of Strings) and returns either a normal completion containing unused or a throw completion. It performs the following steps when called:

  1. perIterationBindingsに要素がある場合、
    1. 実行中の実行コンテキストのLexicalEnvironmentをlastIterationEnvとする。
    2. lastIterationEnv.[[OuterEnv]]outerとする。
    3. Assert: outernullではない。
    4. NewDeclarativeEnvironment(outer)をthisIterationEnvとする。
    5. perIterationBindingsの各要素nameについて、次を行う。
      1. thisIterationEnv.CreateMutableBinding(name, false)を実行する。
      2. lastIterationEnv.GetBindingValue(name, true)をlastValueとする。
      3. thisIterationEnv.InitializeBinding(name, lastValue)を実行する。
    6. 実行中の実行コンテキストのLexicalEnvironmentをthisIterationEnvに設定する。
  2. unusedを返す。

14.7.5 The for-in, for-of, and for-await-of Statements

Syntax

ForInOfStatement[Yield, Await, Return] : for ( [lookahead ≠ let [] LeftHandSideExpression[?Yield, ?Await] in Expression[+In, ?Yield, ?Await] ) Statement[?Yield, ?Await, ?Return] for ( var ForBinding[?Yield, ?Await, +Pattern] in Expression[+In, ?Yield, ?Await] ) Statement[?Yield, ?Await, ?Return] for ( ForDeclaration[?Yield, ?Await, ~Using] in Expression[+In, ?Yield, ?Await] ) Statement[?Yield, ?Await, ?Return] for ( [lookahead ∉ { let, async of }] LeftHandSideExpression[?Yield, ?Await] of AssignmentExpression[+In, ?Yield, ?Await] ) Statement[?Yield, ?Await, ?Return] for ( var ForBinding[?Yield, ?Await, +Pattern] of AssignmentExpression[+In, ?Yield, ?Await] ) Statement[?Yield, ?Await, ?Return] for ( [lookahead ≠ using of] ForDeclaration[?Yield, ?Await, +Using] of AssignmentExpression[+In, ?Yield, ?Await] ) Statement[?Yield, ?Await, ?Return] [+Await] for await ( [lookahead ≠ let] LeftHandSideExpression[?Yield, ?Await] of AssignmentExpression[+In, ?Yield, ?Await] ) Statement[?Yield, ?Await, ?Return] [+Await] for await ( var ForBinding[?Yield, ?Await, +Pattern] of AssignmentExpression[+In, ?Yield, ?Await] ) Statement[?Yield, ?Await, ?Return] [+Await] for await ( [lookahead ≠ using of] ForDeclaration[?Yield, ?Await, +Using] of AssignmentExpression[+In, ?Yield, ?Await] ) Statement[?Yield, ?Await, ?Return] ForDeclaration[Yield, Await, Using] : LetOrConst ForBinding[?Yield, ?Await, +Pattern] [+Using] using [no LineTerminator here] ForBinding[?Yield, ?Await, ~Pattern] [+Using, +Await] await [no LineTerminator here] using [no LineTerminator here] ForBinding[?Yield, +Await, ~Pattern] ForBinding[Yield, Await, Pattern] : BindingIdentifier[?Yield, ?Await] [+Pattern] BindingPattern[?Yield, ?Await] Note

このsectionはAnnex B.3.5によって拡張されます。

14.7.5.1 Static Semantics: Early Errors

ForInOfStatement : for ( LeftHandSideExpression in Expression ) Statement for ( var ForBinding in Expression ) Statement for ( ForDeclaration in Expression ) Statement for ( LeftHandSideExpression of AssignmentExpression ) Statement for ( var ForBinding of AssignmentExpression ) Statement for ( ForDeclaration of AssignmentExpression ) Statement for await ( LeftHandSideExpression of AssignmentExpression ) Statement for await ( var ForBinding of AssignmentExpression ) Statement for await ( ForDeclaration of AssignmentExpression ) Statement Note

このruleを適用する必要があるのは、B.3.1で指定されるextensionが実装されている場合だけです。

ForInOfStatement : for ( LeftHandSideExpression in Expression ) Statement for ( LeftHandSideExpression of AssignmentExpression ) Statement for await ( LeftHandSideExpression of AssignmentExpression ) Statement ForInOfStatement : for ( ForDeclaration in Expression ) Statement for ( ForDeclaration of AssignmentExpression ) Statement for await ( ForDeclaration of AssignmentExpression ) Statement

14.7.5.2 Static Semantics: IsDestructuring

The syntax-directed operation IsDestructuring takes no arguments and returns a Boolean. It is defined piecewise over the following productions:

MemberExpression : PrimaryExpression
  1. PrimaryExpressionObjectLiteralまたはArrayLiteralのいずれかなら、trueを返す。
  2. falseを返す。
MemberExpression : MemberExpression [ Expression ] MemberExpression . IdentifierName MemberExpression TemplateLiteral SuperProperty MetaProperty new MemberExpression Arguments MemberExpression . PrivateIdentifier NewExpression : new NewExpression LeftHandSideExpression : CallExpression OptionalExpression
  1. falseを返す。
ForDeclaration : LetOrConst ForBinding
  1. ForBindingIsDestructuringを返す。
ForBinding : BindingIdentifier
  1. falseを返す。
ForBinding : BindingPattern
  1. trueを返す。
Note

このsectionはAnnex B.3.5によって拡張されます。

14.7.5.3 Runtime Semantics: ForDeclarationBindingInitialization

The syntax-directed operation ForDeclarationBindingInitialization takes arguments value (an ECMAScript language value) and envRecord (an Environment Record) and returns either a normal completion containing unused or an abrupt completion. It is defined piecewise over the following productions:

ForDeclaration : LetOrConst ForBinding
  1. 引数valueおよびenvRecordを伴うForBindingの ? BindingInitializationを返す。
ForDeclaration : using ForBinding await using ForBinding
  1. SyntaxError 例外を投げる。

14.7.5.4 Runtime Semantics: ForDeclarationBindingInstantiation

The syntax-directed operation ForDeclarationBindingInstantiation takes argument envRecord (a Declarative Environment Record) and returns unused. It is defined piecewise over the following productions:

ForDeclaration : LetOrConst ForBinding
  1. ForBindingBoundNamesの各要素nameについて、以下を行う
    1. LetOrConstIsConstantDeclarationtrueなら、
      1. envRecord.CreateImmutableBinding(name, true)を実行する。
    2. そうでなければ、
      1. envRecord.CreateMutableBinding(name, false)を実行する。
  2. unusedを返す。
ForDeclaration : using ForBinding await using ForBinding
  1. ForBindingBoundNames の各要素 name について、do
    1. envRecord.CreateImmutableBinding(name, true) を実行する。
  2. unused を返す。

14.7.5.5 Runtime Semantics: ForIn/OfLoopEvaluation

The syntax-directed operation ForIn/OfLoopEvaluation takes argument labelSet (a List of Strings) and returns either a normal completion containing an ECMAScript language value or an abrupt completion. It is defined piecewise over the following productions:

ForInOfStatement : for ( LeftHandSideExpression in Expression ) Statement
  1. keyResultを ? ForIn/OfHeadEvaluation(« », Expression, enumerate) とする。
  2. ForIn/OfBodyEvaluation(LeftHandSideExpression, Statement, keyResult, enumerate, assignment, labelSet)を返す。
ForInOfStatement : for ( var ForBinding in Expression ) Statement
  1. keyResultを ? ForIn/OfHeadEvaluation(« », Expression, enumerate) とする。
  2. ForIn/OfBodyEvaluation(ForBinding, Statement, keyResult, enumerate, var-binding, labelSet)を返す。
ForInOfStatement : for ( ForDeclaration in Expression ) Statement
  1. keyResultを ? ForIn/OfHeadEvaluation(ForDeclarationBoundNames, Expression, enumerate) とする。
  2. ForIn/OfBodyEvaluation(ForDeclaration, Statement, keyResult, enumerate, lexical-binding, labelSet)を返す。
ForInOfStatement : for ( LeftHandSideExpression of AssignmentExpression ) Statement
  1. keyResultを ? ForIn/OfHeadEvaluation(« », AssignmentExpression, iterate) とする。
  2. ForIn/OfBodyEvaluation(LeftHandSideExpression, Statement, keyResult, iterate, assignment, labelSet)を返す。
ForInOfStatement : for ( var ForBinding of AssignmentExpression ) Statement
  1. keyResultを ? ForIn/OfHeadEvaluation(« », AssignmentExpression, iterate) とする。
  2. ForIn/OfBodyEvaluation(ForBinding, Statement, keyResult, iterate, var-binding, labelSet)を返す。
ForInOfStatement : for ( ForDeclaration of AssignmentExpression ) Statement
  1. keyResultを ? ForIn/OfHeadEvaluation(ForDeclarationBoundNames, AssignmentExpression, iterate) とする。
  2. ForIn/OfBodyEvaluation(ForDeclaration, Statement, keyResult, iterate, lexical-binding, labelSet)を返す。
ForInOfStatement : for await ( LeftHandSideExpression of AssignmentExpression ) Statement
  1. keyResultを ? ForIn/OfHeadEvaluation(« », AssignmentExpression, async-iterate) とする。
  2. ForIn/OfBodyEvaluation(LeftHandSideExpression, Statement, keyResult, iterate, assignment, labelSet, async)を返す。
ForInOfStatement : for await ( var ForBinding of AssignmentExpression ) Statement
  1. keyResultを ? ForIn/OfHeadEvaluation(« », AssignmentExpression, async-iterate) とする。
  2. ForIn/OfBodyEvaluation(ForBinding, Statement, keyResult, iterate, var-binding, labelSet, async)を返す。
ForInOfStatement : for await ( ForDeclaration of AssignmentExpression ) Statement
  1. keyResultを ? ForIn/OfHeadEvaluation(ForDeclarationBoundNames, AssignmentExpression, async-iterate) とする。
  2. ForIn/OfBodyEvaluation(ForDeclaration, Statement, keyResult, iterate, lexical-binding, labelSet, async)を返す。
Note

このsectionはAnnex B.3.5によって拡張されます。

14.7.5.6 ForIn/OfHeadEvaluation ( uninitializedBoundNames, expr, iterationKind )

The abstract operation ForIn/OfHeadEvaluation takes arguments uninitializedBoundNames (a List of Strings), expr (an Expression Parse Node or an AssignmentExpression Parse Node), and iterationKind (enumerate, iterate, or async-iterate) and returns either a normal completion containing an Iterator Record or an abrupt completion. It performs the following steps when called:

  1. oldEnvrunning execution contextのLexicalEnvironmentとする。
  2. uninitializedBoundNamesが空でないなら、
    1. Assert: uninitializedBoundNamesは重複entriesを持たない。
    2. newEnvNewDeclarativeEnvironment(oldEnv)とする。
    3. uninitializedBoundNamesの各String nameについて、以下を行う
      1. newEnv.CreateMutableBinding(name, false)を実行する。
    4. running execution contextのLexicalEnvironmentをnewEnvに設定する。
  3. exprRefexprEvaluationCompletionとする。
  4. running execution contextのLexicalEnvironmentをoldEnvに設定する。
  5. exprValueを ? GetValue(? exprRef) とする。
  6. iterationKindenumerateなら、
    1. exprValueundefinedまたはnullのいずれかなら、
      1. Completion Record { [[Type]]: break, [[Value]]: empty, [[Target]]: empty }を返す。
    2. objを ! ToObject(exprValue) とする。
    3. iteratorEnumerateObjectProperties(obj)とする。
    4. nextMethodを ! GetV(iterator, "next") とする。
    5. Iterator Record { [[Iterator]]: iterator, [[NextMethod]]: nextMethod, [[Done]]: false }を返す。
  7. Assert: iterationKinditerateまたはasync-iterateのいずれかである。
  8. iterationKindasync-iterateなら、iteratorKindasyncとする。
  9. そうでなければ、iteratorKindsyncとする。
  10. GetIterator(exprValue, iteratorKind)を返す。

14.7.5.7 ForIn/OfBodyEvaluation ( lhs, stmt, iteratorRecord, iterationKind, lhsKind, labelSet [ , iteratorKind ] )

The abstract operation ForIn/OfBodyEvaluation takes arguments lhs (a Parse Node), stmt (a Statement Parse Node), iteratorRecord (an Iterator Record), iterationKind (enumerate or iterate), lhsKind (assignment, var-binding, or lexical-binding), and labelSet (a List of Strings) and optional argument iteratorKind (sync or async) and returns either a normal completion containing an ECMAScript language value or an abrupt completion. It performs the following steps when called:

  1. iteratorKind が存在しない場合、iteratorKindsync に設定する。
  2. oldEnv を、実行中の実行コンテキストの LexicalEnvironment とする。
  3. iterationResultundefined とする。
  4. lhsKindlexical-binding である場合、then
    1. Assert: lhsForDeclaration である。
    2. lhsIsAwaitUsingDeclarationtrue である場合、then
      1. declarationKindasync-dispose とする。
    3. Else if lhsIsUsingDeclarationtrue である場合、then
      1. declarationKindsync-dispose とする。
    4. Else,
      1. declarationKindnormal とする。
  5. Else,
    1. declarationKindnormal とする。
  6. destructuringlhsIsDestructuring とする。
  7. destructuringtrue であり、かつ lhsKindassignment である場合、then
    1. Assert: lhsLeftHandSideExpression である。
    2. assignmentPattern を、lhs によってカバーされる AssignmentPattern とする。
  8. Repeat,
    1. nextResult を ? Call(iteratorRecord.[[NextMethod]], iteratorRecord.[[Iterator]]) とする。
    2. iteratorKindasync である場合、nextResult を ? Await(nextResult) に設定する。
    3. nextResult が Object でない場合、TypeError 例外を投げる。
    4. done を ? IteratorComplete(nextResult) とする。
    5. donetrue である場合、iterationResult を返す。
    6. nextValue を ? IteratorValue(nextResult) とする。
    7. lhsKindassignment または var-binding のいずれかである場合、then
      1. destructuringtrue である場合、then
        1. lhsKindassignment である場合、then
          1. status を、引数 nextValueassignmentPatternDestructuringAssignmentEvaluationCompletion とする。
        2. Else,
          1. Assert: lhsKindvar-binding である。
          2. Assert: lhsForBinding である。
          3. status を、引数 nextValue および undefinedlhsBindingInitializationCompletion とする。
      2. Else,
        1. lhsReflhsEvaluationCompletion とする。(これは繰り返し評価されることがある。)
        2. lhsKindassignment であり、かつ lhsAssignmentTargetTypeweb-compat である場合、ReferenceError 例外を投げる。
        3. lhsRefabrupt completion である場合、then
          1. statuslhsRef とする。
        4. Else,
          1. statusCompletion(PutValue(lhsRef.[[Value]], nextValue)) とする。
      3. iterationEnvundefined とする。
    8. Else,
      1. Assert: lhsKindlexical-binding である。
      2. Assert: lhsForDeclaration である。
      3. iterationEnvNewDeclarativeEnvironment(oldEnv) とする。
      4. 引数 iterationEnvlhsForDeclarationBindingInstantiation を実行する。
      5. 実行中の実行コンテキストの LexicalEnvironment を iterationEnv に設定する。
      6. destructuringtrue である場合、then
        1. status を、引数 nextValue および iterationEnvlhsForDeclarationBindingInitializationCompletion とする。
      7. Else,
        1. Assert: lhs は単一の名前を束縛する。
        2. lhsNamelhsBoundNames の唯一の要素とする。
        3. lhsRef を ! ResolveBinding(lhsName) とする。
        4. declarationKindnormal でない場合、then
          1. Assert: IsUnresolvableReference(lhsRef) は false である。
          2. baselhsRef.[[Base]] とする。
          3. Assert: baseDeclarative Environment Record である。
          4. statusCompletion(AddDisposableResource(base.[[DisposableResourceStack]], nextValue, declarationKind)) とする。
        5. Else,
          1. statusNormalCompletion(unused) とする。
        6. statusnormal completion である場合、then
          1. statusCompletion(InitializeReferencedBinding(lhsRef, nextValue)) に設定する。
    9. statusabrupt completion である場合、then
      1. iterationEnvundefined でない場合、then
        1. statusCompletion(DisposeResources(iterationEnv.[[DisposableResourceStack]], status)) に設定する。
        2. Assert: statusabrupt completion である。
      2. 実行中の実行コンテキストの LexicalEnvironment を oldEnv に設定する。
      3. iterationKindenumerate である場合、return ? status.
      4. Assert: iterationKinditerate である。
      5. iteratorKindasync である場合、return ? AsyncIteratorClose(iteratorRecord, status).
      6. Return ? IteratorClose(iteratorRecord, status).
    10. resultstmtEvaluationCompletion とする。
    11. iterationEnvundefined でない場合、then
      1. resultCompletion(DisposeResources(iterationEnv.[[DisposableResourceStack]], result)) に設定する。
    12. 実行中の実行コンテキストの LexicalEnvironment を oldEnv に設定する。
    13. LoopContinues(result, labelSet) が false である場合、then
      1. statusCompletion(UpdateEmpty(result, iterationResult)) に設定する。
      2. iterationKindenumerate である場合、return ? status.
      3. Assert: iterationKinditerate である。
      4. iteratorKindasync である場合、return ? AsyncIteratorClose(iteratorRecord, status).
      5. Return ? IteratorClose(iteratorRecord, status).
    14. result.[[Value]]empty でない場合、iterationResultresult.[[Value]] に設定する。

14.7.5.8 Runtime Semantics: Evaluation

BindingIdentifier : Identifier yield await
  1. bindingIdBindingIdentifierStringValueとする。
  2. ResolveBinding(bindingId)を返す。

14.7.5.9 EnumerateObjectProperties ( obj )

The abstract operation EnumerateObjectProperties takes argument obj (an Object) and returns an iterator object. It performs the following steps when called:

  1. objのenumerable propertiesのString値keysすべてを反復するnext methodを持つiterator objectを返す。iterator objectはECMAScript codeから直接accessできることは決してありません。propertiesをenumeratingするmechanicsおよびorderは指定されませんが、以下で指定されるrulesにconformしなければなりません。

iteratorthrowおよびreturn methodsはnullであり、決して呼び出されません。iteratornext methodは、property keyiterator valueとして返すべきかどうかを判定するためにobject propertiesを処理します。返されるproperty keysにはSymbolsであるkeysは含まれません。target objectのpropertiesはenumeration中に削除される場合があります。iteratornext methodによって処理される前に削除されたpropertyは無視されます。enumeration中にtarget objectへ新しいpropertiesが追加された場合、新しく追加されたpropertiesはactive enumerationで処理されることが保証されません。property nameは、どのenumerationでもiteratornext methodによって最大1回だけ返されます。

target objectのpropertiesをenumeratingすることには、そのprototype、そのprototypeのprototype、以下同様にrecursiveにpropertiesをenumeratingすることが含まれます;ただし、prototypeのpropertyは、iteratornext methodによってすでに処理されたpropertyと同じ名前を持つ場合、処理されません。prototype objectのpropertyがすでに処理されたかどうかを判定するとき、[[Enumerable]] attributesの値は考慮されません。prototype objectsのenumerable property namesは、そのprototype objectをargumentとして渡してEnumerateObjectPropertiesを呼び出すことで取得されなければなりません。EnumerateObjectPropertiesは、target objectの[[OwnPropertyKeys]] internal methodを呼び出すことで、そのown property keysを取得しなければなりません。target objectのProperty attributesは、その[[GetOwnProperty]] internal methodを呼び出すことで取得されなければなりません。

さらに、objも、そのprototype chain内のどのobjectもProxy exotic objectTypedArraymodule namespace exotic object、またはimplementation provided exotic objectでない場合、iteratorは、次のいずれかが発生するまで、CreateForInIterator(obj)によって与えられるiteratorのように振る舞わなければなりません:

  • objまたはそのprototype chain内のobjectの[[Prototype]] internal slotの値が変更される、
  • objまたはそのprototype chain内のobjectからpropertyが削除される、
  • objのprototype chain内のobjectへpropertyが追加される、または
  • objまたはそのprototype chain内のobjectのpropertyの[[Enumerable]] attributeの値が変更される。
Note 1

ECMAScript implementationsは、14.7.5.10.2.1内のalgorithmを直接実装する必要はありません。前段落のconstraintsの1つがviolatedされない限り、そのalgorithmからbehaviourが逸脱しない任意のimplementationを選択してよいです。

以下は、これらのrulesにconformするECMAScript generator functionのinformative definitionです:

function* EnumerateObjectProperties(obj) {
  const visited = new Set();
  for (const key of Reflect.ownKeys(obj)) {
    if (typeof key === "symbol") continue;
    const desc = Reflect.getOwnPropertyDescriptor(obj, key);
    if (desc) {
      visited.add(key);
      if (desc.enumerable) yield key;
    }
  }
  const proto = Reflect.getPrototypeOf(obj);
  if (proto === null) return;
  for (const protoKey of EnumerateObjectProperties(proto)) {
    if (!visited.has(protoKey)) yield protoKey;
  }
}
Note 2
implementationsがCreateForInIteratorとmatchする必要がないexotic objectsのlistは、implementationsがhistoricallyにこれらの場合でbehaviourに違いがあり、その他すべてでは一致していたため、選択されました。

14.7.5.10 For-In Iterator Objects

For-In Iteratorは、特定のobjectに対する特定のiterationを表すobjectです。For-In Iterator objectsはECMAScript codeから直接accessできることは決してありません;それらはEnumerateObjectPropertiesのbehaviourをillustrateするためだけに存在します。

14.7.5.10.1 CreateForInIterator ( obj )

The abstract operation CreateForInIterator takes argument obj (an Object) and returns a For-In Iterator. これは、objのownおよびinherited enumerable string propertiesを特定のorderで反復するFor-In Iterator objectを作成するために使用されます。 It performs the following steps when called:

  1. iteratorOrdinaryObjectCreate(%ForInIteratorPrototype%, « [[Object]], [[ObjectWasVisited]], [[VisitedKeys]], [[RemainingKeys]] »)とする。
  2. iterator.[[Object]]objに設定する。
  3. iterator.[[ObjectWasVisited]]falseに設定する。
  4. iterator.[[VisitedKeys]]を新しい空のListに設定する。
  5. iterator.[[RemainingKeys]]を新しい空のListに設定する。
  6. iteratorを返す。

14.7.5.10.2 The %ForInIteratorPrototype% Object

%ForInIteratorPrototype% object:

  • すべてのFor-In Iterator objectsによってinheritedされるpropertiesを持ちます。
  • ordinary objectです。
  • その値が%Iterator.prototype%である[[Prototype]] internal slotを持ちます。
  • ECMAScript codeから直接accessできることは決してありません。
  • 次のpropertiesを持ちます:

14.7.5.10.2.1 %ForInIteratorPrototype%.next ( )

  1. iteratorthis valueとする。
  2. Assert: iteratorはObjectである。
  3. Assert: iteratorFor-In Iterator instanceのinternal slotsすべてを持つ(14.7.5.10.3)。
  4. objiterator.[[Object]]とする。
  5. 繰り返す
    1. iterator.[[ObjectWasVisited]]falseなら、
      1. keysを ? obj.[[OwnPropertyKeys]]() とする。
      2. keysの各要素keyについて、以下を行う
        1. keyがStringなら、
          1. keyiterator.[[RemainingKeys]]へappendする。
      3. iterator.[[ObjectWasVisited]]trueに設定する。
    2. iterator.[[RemainingKeys]]が空でない間、繰り返す
      1. keyiterator.[[RemainingKeys]]の最初の要素とする。
      2. iterator.[[RemainingKeys]]から最初の要素をremoveする。
      3. iterator.[[VisitedKeys]]keyを含まないなら、
        1. propertyDescを ? obj.[[GetOwnProperty]](key) とする。
        2. propertyDescundefinedでないなら、
          1. keyiterator.[[VisitedKeys]]へappendする。
          2. propertyDesc.[[Enumerable]]trueなら、CreateIteratorResultObject(key, false)を返す。
    3. objを ? obj.[[GetPrototypeOf]]() に設定する。
    4. iterator.[[Object]]objに設定する。
    5. iterator.[[ObjectWasVisited]]falseに設定する。
    6. objnullなら、CreateIteratorResultObject(undefined, true)を返す。

14.7.5.10.3 Properties of For-In Iterator Instances

For-In Iterator instancesは、%ForInIteratorPrototype% intrinsic objectからpropertiesをinheritするordinary objectsです。For-In Iterator instancesは、Table 34に列挙されたinternal slotsを持つものとしてinitiallyに作成されます。

Table 34: Internal Slots of For-In Iterator Instances
Internal Slot Type Description
[[Object]] an Object propertiesがiteratedされているObject値。
[[ObjectWasVisited]] a Boolean iterator[[Object]]に対して[[OwnPropertyKeys]]をinvokedしているならtrue、そうでなければfalse
[[VisitedKeys]] a List of Strings このiteratorによってこれまでにemittedされた値。
[[RemainingKeys]] a List of Strings そのprototypeがnullでない場合に、そのprototypeのpropertiesをiteratingする前に、current objectについてemitされるためにremainingしている値。

14.8 The continue Statement

Syntax

ContinueStatement[Yield, Await] : continue ; continue [no LineTerminator here] LabelIdentifier[?Yield, ?Await] ;

14.8.1 Static Semantics: Early Errors

ContinueStatement : continue ; continue LabelIdentifier ;
  • このContinueStatementが、直接的または間接的に(ただしfunctionまたはstatic initialization blockのboundariesを越えずに)IterationStatement内にnestedされていない場合、それはSyntax Errorです。

14.8.2 Runtime Semantics: Evaluation

ContinueStatement : continue ;
  1. Completion Record { [[Type]]: continue, [[Value]]: empty, [[Target]]: empty }を返す。
ContinueStatement : continue LabelIdentifier ;
  1. labelLabelIdentifierStringValueとする。
  2. Completion Record { [[Type]]: continue, [[Value]]: empty, [[Target]]: label }を返す。

14.9 The break Statement

Syntax

BreakStatement[Yield, Await] : break ; break [no LineTerminator here] LabelIdentifier[?Yield, ?Await] ;

14.9.1 Static Semantics: Early Errors

BreakStatement : break ;
  • このBreakStatementが、直接的または間接的に(ただしfunctionまたはstatic initialization blockのboundariesを越えずに)IterationStatementまたはSwitchStatement内にnestedされていない場合、それはSyntax Errorです。

14.9.2 Runtime Semantics: Evaluation

BreakStatement : break ;
  1. Completion Record { [[Type]]: break, [[Value]]: empty, [[Target]]: empty }を返す。
BreakStatement : break LabelIdentifier ;
  1. labelLabelIdentifierStringValueとする。
  2. Completion Record { [[Type]]: break, [[Value]]: empty, [[Target]]: label }を返す。

14.10 The return Statement

Syntax

ReturnStatement[Yield, Await] : return ; return [no LineTerminator here] Expression[+In, ?Yield, ?Await] ; Note

return statementはfunctionのexecutionを停止させ、ほとんどの場合、callerへ値を返します。Expressionが省略された場合、return valueはundefinedです。そうでなければ、return valueはExpressionの値です。return statementは、surrounding contextによっては、実際にはcallerへ値を返さない場合があります。例えば、try blockでは、return statementのCompletion Recordfinally blockのevaluation中に別のCompletion Recordへ置き換えられる場合があります。

14.10.1 Runtime Semantics: Evaluation

ReturnStatement : return ;
  1. ReturnCompletion(undefined)を返す。
ReturnStatement : return Expression ;
  1. exprRefExpressionの ? Evaluationとする。
  2. exprValueを ? GetValue(exprRef) とする。
  3. GetGeneratorKind()がasyncなら、exprValueを ? Await(exprValue) に設定する。
  4. ReturnCompletion(exprValue)を返す。

14.11 The with Statement

Note 1

新しいECMAScript codeではLegacy with statementの使用はdiscouragedされます。strict mode codeおよびnon-strict codeの両方で許可される代替手段、例えばdestructuring assignmentを検討してください。

Syntax

WithStatement[Yield, Await, Return] : with ( Expression[+In, ?Yield, ?Await] ) Statement[?Yield, ?Await, ?Return] Note 2

with statementは、computed objectに対するObject Environment Recordrunning execution contextのlexical environmentへ追加します。その後、このaugmented lexical environmentを使用してstatementを実行します。最後に、original lexical environmentを復元します。

14.11.1 Static Semantics: Early Errors

WithStatement : with ( Expression ) Statement Note

second ruleを適用する必要があるのは、B.3.1で指定されるextensionが実装されている場合だけです。

14.11.2 Runtime Semantics: Evaluation

WithStatement : with ( Expression ) Statement
  1. valueExpressionの ? Evaluationとする。
  2. objを ? ToObject(? GetValue(value)) とする。
  3. oldEnvrunning execution contextのLexicalEnvironmentとする。
  4. newEnvNewObjectEnvironment(obj, true, oldEnv)とする。
  5. running execution contextのLexicalEnvironmentをnewEnvに設定する。
  6. stmtCompletionStatementEvaluationCompletionとする。
  7. running execution contextのLexicalEnvironmentをoldEnvに設定する。
  8. UpdateEmpty(stmtCompletion, undefined)を返す。
Note

controlがembedded Statementからどのように離れても、通常であれ何らかのabrupt completionまたはexceptionによるものであれ、LexicalEnvironmentは常に以前のstateへ復元されます。

14.12 The switch Statement

Syntax

SwitchStatement[Yield, Await, Return] : switch ( Expression[+In, ?Yield, ?Await] ) CaseBlock[?Yield, ?Await, ?Return] CaseBlock[Yield, Await, Return] : { CaseClauses[?Yield, ?Await, ?Return]opt } { CaseClauses[?Yield, ?Await, ?Return]opt DefaultClause[?Yield, ?Await, ?Return] CaseClauses[?Yield, ?Await, ?Return]opt } CaseClauses[Yield, Await, Return] : CaseClause[?Yield, ?Await, ?Return] CaseClauses[?Yield, ?Await, ?Return] CaseClause[?Yield, ?Await, ?Return] CaseClause[Yield, Await, Return] : case Expression[+In, ?Yield, ?Await] : StatementList[?Yield, ?Await, ?Return]opt DefaultClause[Yield, Await, Return] : default : StatementList[?Yield, ?Await, ?Return]opt

14.12.1 Static Semantics: Early Errors

SwitchStatement : switch ( Expression ) CaseBlock CaseClause : case Expression : StatementList DefaultClause : default : StatementList

14.12.2 Runtime Semantics: CaseBlockEvaluation

The syntax-directed operation CaseBlockEvaluation takes argument input (an ECMAScript language value) and returns either a normal completion containing an ECMAScript language value or an abrupt completion. It is defined piecewise over the following productions:

CaseBlock : { }
  1. undefinedを返す。
CaseBlock : { CaseClauses }
  1. resultValueundefinedとする。
  2. caseClausesを、source text orderにおけるCaseClauses内のCaseClause itemsのListとする。
  3. foundfalseとする。
  4. caseClausesの各CaseClause clauseについて、以下を行う
    1. foundfalseなら、
      1. foundを ? CaseClauseIsSelected(clause, input) に設定する。
    2. foundtrueなら、
      1. completionclauseEvaluationCompletionとする。
      2. completion.[[Value]]emptyでないなら、resultValuecompletion.[[Value]]に設定する。
      3. completionabrupt completionなら、? UpdateEmpty(completion, resultValue)を返す。
  5. resultValueを返す。
CaseBlock : { CaseClausesopt DefaultClause CaseClausesopt }
  1. resultValueundefinedとする。
  2. 最初のCaseClausesが存在するなら、
    1. caseClausesを、source text orderにおける最初のCaseClauses内のCaseClause itemsのListとする。
  3. そうでなければ、
    1. caseClausesを新しい空のListとする。
  4. foundfalseとする。
  5. caseClausesの各CaseClause clauseについて、以下を行う
    1. foundfalseなら、
      1. foundを ? CaseClauseIsSelected(clause, input) に設定する。
    2. foundtrueなら、
      1. completionclauseEvaluationCompletionとする。
      2. completion.[[Value]]emptyでないなら、resultValuecompletion.[[Value]]に設定する。
      3. completionabrupt completionなら、? UpdateEmpty(completion, resultValue)を返す。
  6. foundInBfalseとする。
  7. 2番目のCaseClausesが存在するなら、
    1. secondCaseClausesを、source text orderにおける2番目のCaseClauses内のCaseClause itemsのListとする。
  8. そうでなければ、
    1. secondCaseClausesを新しい空のListとする。
  9. foundfalseなら、
    1. secondCaseClausesの各CaseClause clauseについて、以下を行う
      1. foundInBfalseなら、
        1. foundInBを ? CaseClauseIsSelected(clause, input) に設定する。
      2. foundInBtrueなら、
        1. completionCaseClause clauseEvaluationCompletionとする。
        2. completion.[[Value]]emptyでないなら、resultValuecompletion.[[Value]]に設定する。
        3. completionabrupt completionなら、? UpdateEmpty(completion, resultValue)を返す。
  10. foundInBtrueなら、resultValueを返す。
  11. defaultRDefaultClauseEvaluationCompletionとする。
  12. defaultR.[[Value]]emptyでないなら、resultValuedefaultR.[[Value]]に設定する。
  13. defaultRabrupt completionなら、? UpdateEmpty(defaultR, resultValue)を返す。
  14. NOTE: 以下は2番目のCaseClausesのもう1つの完全なiterationです。
  15. secondCaseClausesの各CaseClause clauseについて、以下を行う
    1. completionCaseClause clauseEvaluationCompletionとする。
    2. completion.[[Value]]emptyでないなら、resultValuecompletion.[[Value]]に設定する。
    3. completionabrupt completionなら、? UpdateEmpty(completion, resultValue)を返す。
  16. resultValueを返す。

14.12.3 CaseClauseIsSelected ( caseClauseNode, input )

The abstract operation CaseClauseIsSelected takes arguments caseClauseNode (a CaseClause Parse Node) and input (an ECMAScript language value) and returns either a normal completion containing a Boolean or an abrupt completion. これはcaseClauseNodeinputにmatchするかどうかを判定します。 It performs the following steps when called:

  1. Assert: caseClauseNodeはproduction CaseClause : case Expression : StatementListopt のinstanceである。
  2. exprRefcaseClauseNodeExpressionの ? Evaluationとする。
  3. clauseSelectorを ? GetValue(exprRef) とする。
  4. IsStrictlyEqual(input, clauseSelector)を返す。
Note

このoperationはcaseClauseNodeStatementList(存在する場合)を実行しません。CaseBlock algorithmは、どのStatementListの実行を開始するかを判定するためにそのreturn valueを使用します。

14.12.4 Runtime Semantics: Evaluation

SwitchStatement : switch ( Expression ) CaseBlock
  1. exprRefExpressionEvaluation とする。
  2. switchValue を ? GetValue(exprRef) とする。
  3. oldEnv を、実行中の実行コンテキストの LexicalEnvironment とする。
  4. blockEnvNewDeclarativeEnvironment(oldEnv) とする。
  5. BlockDeclarationInstantiation(CaseBlock, blockEnv) を実行する。
  6. 実行中の実行コンテキストの LexicalEnvironment を blockEnv に設定する。
  7. blockResult を、引数 switchValueCaseBlockCaseBlockEvaluationCompletion とする。
  8. Assert: blockEnv.[[DisposableResourceStack]] は空の List である。
  9. 実行中の実行コンテキストの LexicalEnvironment を oldEnv に設定する。
  10. Return blockResult.
Note

controlがどのようにSwitchStatementから離れても、LexicalEnvironmentは常に以前のstateへ復元されます。

CaseClause : case Expression :
  1. emptyを返す。
CaseClause : case Expression : StatementList
  1. StatementListの ? Evaluationを返す。
DefaultClause : default :
  1. emptyを返す。
DefaultClause : default : StatementList
  1. StatementListの ? Evaluationを返す。

14.13 Labelled Statements

Syntax

LabelledStatement[Yield, Await, Return] : LabelIdentifier[?Yield, ?Await] : LabelledItem[?Yield, ?Await, ?Return] LabelledItem[Yield, Await, Return] : Statement[?Yield, ?Await, ?Return] FunctionDeclaration[?Yield, ?Await, ~Default] Note

Statementにはlabelをprefixできます。Labelled statementsはlabelled breakおよびcontinue statementsと組み合わせてのみ使用されます。ECMAScriptにはgoto statementはありません。StatementLabelledStatementの一部であり得、それ自体がLabelledStatementの一部であり得、以下同様です。この方法でintroducedされるlabelsは、個々のstatementsのsemanticsを記述するとき、collectivelyに“current label set”と呼ばれます。

14.13.1 Static Semantics: Early Errors

LabelledItem : FunctionDeclaration
  • 任意のsource textがこのproductionによってmatchされる場合、それはSyntax Errorです。ただし、そのsource textがnon-strict codeであり、かつhostがweb browserである、またはその他の形でLabelled Function Declarationsをサポートする場合を除きます

14.13.2 Static Semantics: IsLabelledFunction ( stmt )

The abstract operation IsLabelledFunction takes argument stmt (a Statement Parse Node) and returns a Boolean. It performs the following steps when called:

  1. stmtLabelledStatementでないなら、falseを返す。
  2. itemstmtLabelledItemとする。
  3. item LabelledItem : FunctionDeclaration なら、trueを返す。
  4. subStmtitemStatementとする。
  5. IsLabelledFunction(subStmt)を返す。

14.13.3 Runtime Semantics: Evaluation

LabelledStatement : LabelIdentifier : LabelledItem
  1. 引数« »を伴うthis LabelledStatementの ? LabelledEvaluationを返す。

14.13.4 Runtime Semantics: LabelledEvaluation

The syntax-directed operation LabelledEvaluation takes argument labelSet (a List of Strings) and returns either a normal completion containing either an ECMAScript language value or empty, or an abrupt completion. It is defined piecewise over the following productions:

BreakableStatement : IterationStatement
  1. stmtResultを、引数labelSetを伴うIterationStatementLoopEvaluationCompletionとする。
  2. stmtResultbreak completionなら、
    1. stmtResult.[[Target]]emptyなら、
      1. stmtResult.[[Value]]emptyなら、stmtResultNormalCompletion(undefined)に設定する。
      2. そうでなければ、stmtResultNormalCompletion(stmtResult.[[Value]])に設定する。
  3. stmtResultを返す。
BreakableStatement : SwitchStatement
  1. stmtResultSwitchStatementEvaluationCompletionとする。
  2. stmtResultbreak completionなら、
    1. stmtResult.[[Target]]emptyなら、
      1. stmtResult.[[Value]]emptyなら、stmtResultNormalCompletion(undefined)に設定する。
      2. そうでなければ、stmtResultNormalCompletion(stmtResult.[[Value]])に設定する。
  3. stmtResultを返す。
Note 1

BreakableStatementは、unlabelled BreakStatementを介してexitできるものです。

LabelledStatement : LabelIdentifier : LabelledItem
  1. labelLabelIdentifierStringValueとする。
  2. newLabelSetlabelSetと« label »のlist-concatenationとする。
  3. stmtResultを、引数newLabelSetを伴うLabelledItemLabelledEvaluationCompletionとする。
  4. stmtResultbreak completionであり、かつstmtResult.[[Target]]labelであるなら、
    1. stmtResultNormalCompletion(stmtResult.[[Value]])に設定する。
  5. stmtResultを返す。
LabelledItem : FunctionDeclaration
  1. FunctionDeclarationの ? Evaluationを返す。
Statement : BlockStatement VariableStatement EmptyStatement ExpressionStatement IfStatement ContinueStatement BreakStatement ReturnStatement WithStatement ThrowStatement TryStatement DebuggerStatement
  1. Statementの ? Evaluationを返す。
Note 2

LabelledEvaluationに対してspecial semanticsを持つStatementのproductionsは、BreakableStatementおよびLabelledStatementの2つだけです。

14.14 The throw Statement

Syntax

ThrowStatement[Yield, Await] : throw [no LineTerminator here] Expression[+In, ?Yield, ?Await] ;

14.14.1 Runtime Semantics: Evaluation

ThrowStatement : throw Expression ;
  1. exprRefExpressionの ? Evaluationとする。
  2. exprValueを ? GetValue(exprRef) とする。
  3. exprValueをThrowする。

14.15 The try Statement

Syntax

TryStatement[Yield, Await, Return] : try Block[?Yield, ?Await, ?Return] Catch[?Yield, ?Await, ?Return] try Block[?Yield, ?Await, ?Return] Finally[?Yield, ?Await, ?Return] try Block[?Yield, ?Await, ?Return] Catch[?Yield, ?Await, ?Return] Finally[?Yield, ?Await, ?Return] Catch[Yield, Await, Return] : catch ( CatchParameter[?Yield, ?Await] ) Block[?Yield, ?Await, ?Return] catch Block[?Yield, ?Await, ?Return] Finally[Yield, Await, Return] : finally Block[?Yield, ?Await, ?Return] CatchParameter[Yield, Await] : BindingIdentifier[?Yield, ?Await] BindingPattern[?Yield, ?Await] Note

try statementは、runtime errorやthrow statementなど、exceptional conditionが発生し得るcodeのblockを囲みます。catch clauseはexception-handling codeを提供します。catch clauseがexceptionをcatchすると、そのCatchParameterはそのexceptionにboundされます。

14.15.1 Static Semantics: Early Errors

Catch : catch ( CatchParameter ) Block

14.15.2 Runtime Semantics: CatchClauseEvaluation

The syntax-directed operation CatchClauseEvaluation takes argument thrownValue (an ECMAScript language value) and returns either a normal completion containing either an ECMAScript language value or empty, or an abrupt completion. It is defined piecewise over the following productions:

Catch : catch ( CatchParameter ) Block
  1. oldEnvrunning execution contextのLexicalEnvironmentとする。
  2. catchEnvNewDeclarativeEnvironment(oldEnv)とする。
  3. CatchParameterBoundNamesの各要素argNameについて、以下を行う
    1. catchEnv.CreateMutableBinding(argName, false)を実行する。
  4. running execution contextのLexicalEnvironmentをcatchEnvに設定する。
  5. statusを、引数thrownValueおよびcatchEnvを伴うCatchParameterBindingInitializationCompletionとする。
  6. statusabrupt completionなら、
    1. running execution contextのLexicalEnvironmentをoldEnvに設定する。
    2. statusを返す。
  7. blockCompletionBlockEvaluationCompletionとする。
  8. running execution contextのLexicalEnvironmentをoldEnvに設定する。
  9. blockCompletionを返す。
Catch : catch Block
  1. Blockの ? Evaluationを返す。
Note

controlがどのようにBlockから離れても、LexicalEnvironmentは常に以前のstateへ復元されます。

14.15.3 Runtime Semantics: Evaluation

TryStatement : try Block Catch
  1. blockResultBlockEvaluationCompletionとする。
  2. blockResultthrow completionなら、catchResultを、引数blockResult.[[Value]]を伴うCatchCatchClauseEvaluationCompletionとする。
  3. そうでなければ、catchResultblockResultとする。
  4. UpdateEmpty(catchResult, undefined)を返す。
TryStatement : try Block Finally
  1. blockResultBlockEvaluationCompletionとする。
  2. finallyResultFinallyEvaluationCompletionとする。
  3. finallyResultnormal completionなら、finallyResultblockResultに設定する。
  4. UpdateEmpty(finallyResult, undefined)を返す。
TryStatement : try Block Catch Finally
  1. blockResultBlockEvaluationCompletionとする。
  2. blockResultthrow completionなら、catchResultを、引数blockResult.[[Value]]を伴うCatchCatchClauseEvaluationCompletionとする。
  3. そうでなければ、catchResultblockResultとする。
  4. finallyResultFinallyEvaluationCompletionとする。
  5. finallyResultnormal completionなら、finallyResultcatchResultに設定する。
  6. UpdateEmpty(finallyResult, undefined)を返す。

14.16 The debugger Statement

Syntax

DebuggerStatement : debugger ;

14.16.1 Runtime Semantics: Evaluation

Note

DebuggerStatementを評価すると、debuggerの下で実行されている場合、implementationがbreakpointを発生させることを可能にする場合があります。debuggerが存在しない、またはactiveでない場合、このstatementにはobservable effectはありません。

DebuggerStatement : debugger ;
  1. implementation-defined debugging facilityがavailableかつenabledであるなら、
    1. implementation-defined debugging actionを実行する。
    2. 新しいimplementation-defined Completion Recordを返す。
  2. emptyを返す。

15 ECMAScript Language: Functions and Classes

Note

さまざまなECMAScript language elementsは、ECMAScript function objects10.2)の作成を引き起こします。そのようなfunctionsのevaluationは、それらの[[Call]] internal method(10.2.1)の実行から開始します。

15.1 Parameter Lists

Syntax

UniqueFormalParameters[Yield, Await] : FormalParameters[?Yield, ?Await] FormalParameters[Yield, Await] : [empty] FunctionRestParameter[?Yield, ?Await] FormalParameterList[?Yield, ?Await] FormalParameterList[?Yield, ?Await] , FormalParameterList[?Yield, ?Await] , FunctionRestParameter[?Yield, ?Await] FormalParameterList[Yield, Await] : FormalParameter[?Yield, ?Await] FormalParameterList[?Yield, ?Await] , FormalParameter[?Yield, ?Await] FunctionRestParameter[Yield, Await] : BindingRestElement[?Yield, ?Await] FormalParameter[Yield, Await] : BindingElement[?Yield, ?Await]

15.1.1 Static Semantics: Early Errors

UniqueFormalParameters : FormalParameters FormalParameters : FormalParameterList Note

FormalParameterList内で同じBindingIdentifierが複数回出現することは、simple parameter listsを持ち、かつstrict mode code内で定義されていないfunctionsに対してのみ許可されます。

15.1.2 Static Semantics: ContainsExpression

The syntax-directed operation ContainsExpression takes no arguments and returns a Boolean. It is defined piecewise over the following productions:

ObjectBindingPattern : { } { BindingRestProperty }
  1. falseを返す。
ObjectBindingPattern : { BindingPropertyList , BindingRestProperty }
  1. BindingPropertyListContainsExpressionを返す。
ArrayBindingPattern : [ Elisionopt ]
  1. falseを返す。
ArrayBindingPattern : [ Elisionopt BindingRestElement ]
  1. BindingRestElementContainsExpressionを返す。
ArrayBindingPattern : [ BindingElementList , Elisionopt ]
  1. BindingElementListContainsExpressionを返す。
ArrayBindingPattern : [ BindingElementList , Elisionopt BindingRestElement ]
  1. hasBindingElementListContainsExpressionとする。
  2. hastrueなら、trueを返す。
  3. BindingRestElementContainsExpressionを返す。
BindingPropertyList : BindingPropertyList , BindingProperty
  1. hasBindingPropertyListContainsExpressionとする。
  2. hastrueなら、trueを返す。
  3. BindingPropertyContainsExpressionを返す。
BindingElementList : BindingElementList , BindingElisionElement
  1. hasBindingElementListContainsExpressionとする。
  2. hastrueなら、trueを返す。
  3. BindingElisionElementContainsExpressionを返す。
BindingElisionElement : Elisionopt BindingElement
  1. BindingElementContainsExpressionを返す。
BindingProperty : PropertyName : BindingElement
  1. hasPropertyNameIsComputedPropertyKeyとする。
  2. hastrueなら、trueを返す。
  3. BindingElementContainsExpressionを返す。
BindingElement : BindingPattern Initializer
  1. trueを返す。
SingleNameBinding : BindingIdentifier
  1. falseを返す。
SingleNameBinding : BindingIdentifier Initializer
  1. trueを返す。
BindingRestElement : ... BindingIdentifier
  1. falseを返す。
BindingRestElement : ... BindingPattern
  1. BindingPatternContainsExpressionを返す。
FormalParameters : [empty]
  1. falseを返す。
FormalParameters : FormalParameterList , FunctionRestParameter
  1. FormalParameterListContainsExpressiontrueなら、trueを返す。
  2. FunctionRestParameterContainsExpressionを返す。
FormalParameterList : FormalParameterList , FormalParameter
  1. FormalParameterListContainsExpressiontrueなら、trueを返す。
  2. FormalParameterContainsExpressionを返す。
ArrowParameters : BindingIdentifier
  1. falseを返す。
ArrowParameters : CoverParenthesizedExpressionAndArrowParameterList
  1. formalsCoverParenthesizedExpressionAndArrowParameterListによってcoverされるArrowFormalParametersとする。
  2. formalsContainsExpressionを返す。
AsyncArrowBindingIdentifier : BindingIdentifier
  1. falseを返す。

15.1.3 Static Semantics: IsSimpleParameterList

The syntax-directed operation IsSimpleParameterList takes no arguments and returns a Boolean. It is defined piecewise over the following productions:

BindingElement : BindingPattern
  1. falseを返す。
BindingElement : BindingPattern Initializer
  1. falseを返す。
SingleNameBinding : BindingIdentifier
  1. trueを返す。
SingleNameBinding : BindingIdentifier Initializer
  1. falseを返す。
FormalParameters : [empty]
  1. trueを返す。
FormalParameters : FunctionRestParameter
  1. falseを返す。
FormalParameters : FormalParameterList , FunctionRestParameter
  1. falseを返す。
FormalParameterList : FormalParameterList , FormalParameter
  1. FormalParameterListIsSimpleParameterListfalseなら、falseを返す。
  2. FormalParameterIsSimpleParameterListを返す。
FormalParameter : BindingElement
  1. BindingElementIsSimpleParameterListを返す。
ArrowParameters : BindingIdentifier
  1. trueを返す。
ArrowParameters : CoverParenthesizedExpressionAndArrowParameterList
  1. formalsCoverParenthesizedExpressionAndArrowParameterListによってcoverされるArrowFormalParametersとする。
  2. formalsIsSimpleParameterListを返す。
AsyncArrowBindingIdentifier : BindingIdentifier
  1. trueを返す。
CoverCallExpressionAndAsyncArrowHead : MemberExpression Arguments
  1. headCoverCallExpressionAndAsyncArrowHeadによってcoverされるAsyncArrowHeadとする。
  2. headIsSimpleParameterListを返す。

15.1.4 Static Semantics: HasInitializer

The syntax-directed operation HasInitializer takes no arguments and returns a Boolean. It is defined piecewise over the following productions:

BindingElement : BindingPattern
  1. falseを返す。
BindingElement : BindingPattern Initializer
  1. trueを返す。
SingleNameBinding : BindingIdentifier
  1. falseを返す。
SingleNameBinding : BindingIdentifier Initializer
  1. trueを返す。
FormalParameterList : FormalParameterList , FormalParameter
  1. FormalParameterListHasInitializertrueなら、trueを返す。
  2. FormalParameterHasInitializerを返す。

15.1.5 Static Semantics: ExpectedArgumentCount

The syntax-directed operation ExpectedArgumentCount takes no arguments and returns a non-negative integer. It is defined piecewise over the following productions:

FormalParameters : [empty] FunctionRestParameter
  1. 0を返す。
FormalParameters : FormalParameterList , FunctionRestParameter
  1. FormalParameterListExpectedArgumentCountを返す。
Note

FormalParameterListのExpectedArgumentCountは、rest parameterまたはInitializerを持つ最初のFormalParameterのいずれかの左側にあるFormalParametersの数です。initializerを持たないFormalParameterは、initializerを持つ最初のparameterの後に許可されますが、そのようなparametersはundefinedをdefault valueとするoptionalと見なされます。

FormalParameterList : FormalParameter
  1. FormalParameterHasInitializertrueなら、0を返す。
  2. 1を返す。
FormalParameterList : FormalParameterList , FormalParameter
  1. countFormalParameterListExpectedArgumentCountとする。
  2. FormalParameterListHasInitializertrue、またはFormalParameterHasInitializertrueなら、countを返す。
  3. count + 1を返す。
ArrowParameters : BindingIdentifier
  1. 1を返す。
ArrowParameters : CoverParenthesizedExpressionAndArrowParameterList
  1. formalsCoverParenthesizedExpressionAndArrowParameterListによってcoverされるArrowFormalParametersとする。
  2. formalsExpectedArgumentCountを返す。
PropertySetParameterList : FormalParameter
  1. FormalParameterHasInitializertrueなら、0を返す。
  2. 1を返す。
AsyncArrowBindingIdentifier : BindingIdentifier
  1. 1を返す。

15.2 Function Definitions

Syntax

FunctionDeclaration[Yield, Await, Default] : function BindingIdentifier[?Yield, ?Await] ( FormalParameters[~Yield, ~Await] ) { FunctionBody[~Yield, ~Await] } [+Default] function ( FormalParameters[~Yield, ~Await] ) { FunctionBody[~Yield, ~Await] } FunctionExpression : function BindingIdentifier[~Yield, ~Await]opt ( FormalParameters[~Yield, ~Await] ) { FunctionBody[~Yield, ~Await] } FunctionBody[Yield, Await] : FunctionStatementList[?Yield, ?Await] FunctionStatementList[Yield, Await] : StatementList[?Yield, ?Await, +Return]opt

15.2.1 Static Semantics: Early Errors

FunctionDeclaration : function BindingIdentifier ( FormalParameters ) { FunctionBody } function ( FormalParameters ) { FunctionBody } FunctionExpression : function BindingIdentifieropt ( FormalParameters ) { FunctionBody } Note

FunctionBodyLexicallyDeclaredNamesには、varまたはfunction declarationsを使用してboundされるidentifiersは含まれません。

FunctionBody : FunctionStatementList

15.2.2 Static Semantics: FunctionBodyContainsUseStrict

The syntax-directed operation FunctionBodyContainsUseStrict takes no arguments and returns a Boolean. It is defined piecewise over the following productions:

FunctionBody : FunctionStatementList
  1. FunctionBodyDirective PrologueUse Strict Directiveを含むなら、trueを返す。
  2. falseを返す。

15.2.3 Runtime Semantics: EvaluateFunctionBody

The syntax-directed operation EvaluateFunctionBody takes arguments funcObj (an ECMAScript function object) and argList (a List of ECMAScript language values) and returns a return completion or a throw completion. It is defined piecewise over the following productions:

FunctionBody : FunctionStatementList
  1. FunctionDeclarationInstantiation(funcObj, argList)を実行する。
  2. FunctionStatementListの ? Evaluationを実行する。
  3. NOTE: previous stepがnormal completionをもたらした場合、evaluationはFunctionStatementListの終端を越えて進むことで終了した。
  4. ReturnCompletion(undefined)を返す。

15.2.4 Runtime Semantics: InstantiateOrdinaryFunctionObject

The syntax-directed operation InstantiateOrdinaryFunctionObject takes arguments envRecord (an Environment Record) and privateEnv (a PrivateEnvironment Record or null) and returns an ECMAScript function object. It is defined piecewise over the following productions:

FunctionDeclaration : function BindingIdentifier ( FormalParameters ) { FunctionBody }
  1. nameBindingIdentifierStringValueとする。
  2. sourceTextFunctionDeclarationによってmatchされたsource textとする。
  3. closureOrdinaryFunctionCreate(%Function.prototype%, sourceText, FormalParameters, FunctionBody, non-lexical-this, envRecord, privateEnv)とする。
  4. SetFunctionName(closure, name)を実行する。
  5. MakeConstructor(closure)を実行する。
  6. closureを返す。
FunctionDeclaration : function ( FormalParameters ) { FunctionBody }
  1. sourceTextFunctionDeclarationによってmatchされたsource textとする。
  2. closureOrdinaryFunctionCreate(%Function.prototype%, sourceText, FormalParameters, FunctionBody, non-lexical-this, envRecord, privateEnv)とする。
  3. SetFunctionName(closure, "default")を実行する。
  4. MakeConstructor(closure)を実行する。
  5. closureを返す。
Note

anonymous FunctionDeclarationexport default declarationの一部としてのみ出現できるため、そのfunction codeは常にstrict mode codeです。

15.2.5 Runtime Semantics: InstantiateOrdinaryFunctionExpression

The syntax-directed operation InstantiateOrdinaryFunctionExpression takes optional argument name (a property key or a Private Name) and returns an ECMAScript function object. It is defined piecewise over the following productions:

FunctionExpression : function ( FormalParameters ) { FunctionBody }
  1. nameが存在しない場合、nameをempty Stringに設定する。
  2. envRecordrunning execution contextのLexicalEnvironmentとする。
  3. privateEnvrunning execution contextのPrivateEnvironmentとする。
  4. sourceTextFunctionExpressionによってmatchされたsource textとする。
  5. closureOrdinaryFunctionCreate(%Function.prototype%, sourceText, FormalParameters, FunctionBody, non-lexical-this, envRecord, privateEnv)とする。
  6. SetFunctionName(closure, name)を実行する。
  7. MakeConstructor(closure)を実行する。
  8. closureを返す。
FunctionExpression : function BindingIdentifier ( FormalParameters ) { FunctionBody }
  1. Assert: nameは存在しない。
  2. nameBindingIdentifierStringValueに設定する。
  3. outerEnvrunning execution contextのLexicalEnvironmentとする。
  4. funcEnvNewDeclarativeEnvironment(outerEnv)とする。
  5. funcEnv.CreateImmutableBinding(name, false)を実行する。
  6. privateEnvrunning execution contextのPrivateEnvironmentとする。
  7. sourceTextFunctionExpressionによってmatchされたsource textとする。
  8. closureOrdinaryFunctionCreate(%Function.prototype%, sourceText, FormalParameters, FunctionBody, non-lexical-this, funcEnv, privateEnv)とする。
  9. SetFunctionName(closure, name)を実行する。
  10. MakeConstructor(closure)を実行する。
  11. funcEnv.InitializeBinding(name, closure)を実行する。
  12. closureを返す。
Note

FunctionExpression内のBindingIdentifierは、functionがそれ自身を再帰的に呼び出せるように、FunctionExpressionFunctionBody内部からreferenceできます。ただし、FunctionDeclarationの場合とは異なり、FunctionExpression内のBindingIdentifierは、FunctionExpressionを囲むscopeからreferenceできず、そのscopeに影響しません。

15.2.6 Runtime Semantics: Evaluation

FunctionDeclaration : function BindingIdentifier ( FormalParameters ) { FunctionBody }
  1. emptyを返す。
Note 1 FunctionDeclaration : function ( FormalParameters ) { FunctionBody }
  1. emptyを返す。
FunctionExpression : function BindingIdentifieropt ( FormalParameters ) { FunctionBody }
  1. FunctionExpressionInstantiateOrdinaryFunctionExpressionを返す。
Note 2

FunctionDeclarationまたはFunctionExpressionを使用して定義されたすべてのfunctionには、そのfunctionがconstructorとして使用される可能性を許容するために、"prototype" propertyが自動的に作成されます。

FunctionStatementList : [empty]
  1. undefinedを返す。
FunctionStatementList : StatementList
  1. resultStatementListEvaluationCompletion とする。
  2. env を、実行中の実行コンテキストの LexicalEnvironment とする。
  3. Assert: envDeclarative Environment Record である。
  4. Return ? DisposeResources(env.[[DisposableResourceStack]], result).

15.3 Arrow Function Definitions

Syntax

ArrowFunction[In, Yield, Await] : ArrowParameters[?Yield, ?Await] [no LineTerminator here] => ConciseBody[?In] ArrowParameters[Yield, Await] : BindingIdentifier[?Yield, ?Await] CoverParenthesizedExpressionAndArrowParameterList[?Yield, ?Await] ConciseBody[In] : [lookahead ≠ {] ExpressionBody[?In, ~Await] { FunctionBody[~Yield, ~Await] } ExpressionBody[In, Await] : AssignmentExpression[?In, ~Yield, ?Await]

Supplemental Syntax

production
ArrowParameters[Yield, Await] : CoverParenthesizedExpressionAndArrowParameterList[?Yield, ?Await]
のinstanceを処理するとき、CoverParenthesizedExpressionAndArrowParameterListのinterpretationは次のgrammarを使用してrefineされます:

ArrowFormalParameters[Yield, Await] : ( UniqueFormalParameters[?Yield, ?Await] )

15.3.1 Static Semantics: Early Errors

ArrowFunction : ArrowParameters => ConciseBody ArrowParameters : CoverParenthesizedExpressionAndArrowParameterList

15.3.2 Static Semantics: ConciseBodyContainsUseStrict

The syntax-directed operation ConciseBodyContainsUseStrict takes no arguments and returns a Boolean. It is defined piecewise over the following productions:

ConciseBody : ExpressionBody
  1. falseを返す。
ConciseBody : { FunctionBody }
  1. FunctionBodyFunctionBodyContainsUseStrictを返す。

15.3.3 Runtime Semantics: EvaluateConciseBody

The syntax-directed operation EvaluateConciseBody takes arguments funcObj (an ECMAScript function object) and argList (a List of ECMAScript language values) and returns a return completion or a throw completion. It is defined piecewise over the following productions:

ConciseBody : ExpressionBody
  1. FunctionDeclarationInstantiation(funcObj, argList)を実行する。
  2. ExpressionBodyの ? Evaluationを返す。

15.3.4 Runtime Semantics: InstantiateArrowFunctionExpression

The syntax-directed operation InstantiateArrowFunctionExpression takes optional argument name (a property key or a Private Name) and returns an ECMAScript function object. It is defined piecewise over the following productions:

ArrowFunction : ArrowParameters => ConciseBody
  1. nameが存在しない場合、nameをempty Stringに設定する。
  2. envRecordrunning execution contextのLexicalEnvironmentとする。
  3. privateEnvrunning execution contextのPrivateEnvironmentとする。
  4. sourceTextArrowFunctionによってmatchされたsource textとする。
  5. closureOrdinaryFunctionCreate(%Function.prototype%, sourceText, ArrowParameters, ConciseBody, lexical-this, envRecord, privateEnv)とする。
  6. SetFunctionName(closure, name)を実行する。
  7. closureを返す。
Note

ArrowFunctionargumentssuperthis、またはnew.targetに対するlocal bindingsを定義しません。ArrowFunction内のargumentssuperthis、またはnew.targetへのreferenceはいずれも、lexically enclosing environment内のbindingへresolveされなければなりません。通常、これは直ちに囲むfunctionのFunction Environmentになります。ArrowFunctionsuperへのreferencesを含む場合でも、step 5で作成されるfunction objectMakeMethodを実行することによってmethodにはされません。superをreferenceするArrowFunctionは常にnon-ArrowFunction内に含まれ、superを実装するために必要なstateは、ArrowFunctionfunction objectによってcaptureされるenvRecordを介してaccessできます。

15.3.5 Runtime Semantics: Evaluation

ArrowFunction : ArrowParameters => ConciseBody
  1. ArrowFunctionInstantiateArrowFunctionExpressionを返す。
ExpressionBody : AssignmentExpression
  1. exprRefAssignmentExpressionの ? Evaluationとする。
  2. exprValueを ? GetValue(exprRef) とする。
  3. ReturnCompletion(exprValue)を返す。

15.4 Method Definitions

Syntax

MethodDefinition[Yield, Await] : ClassElementName[?Yield, ?Await] ( UniqueFormalParameters[~Yield, ~Await] ) { FunctionBody[~Yield, ~Await] } GeneratorMethod[?Yield, ?Await] AsyncMethod[?Yield, ?Await] AsyncGeneratorMethod[?Yield, ?Await] get ClassElementName[?Yield, ?Await] ( ) { FunctionBody[~Yield, ~Await] } set ClassElementName[?Yield, ?Await] ( PropertySetParameterList ) { FunctionBody[~Yield, ~Await] } PropertySetParameterList : FormalParameter[~Yield, ~Await]

15.4.1 Static Semantics: Early Errors

MethodDefinition : ClassElementName ( UniqueFormalParameters ) { FunctionBody } MethodDefinition : set ClassElementName ( PropertySetParameterList ) { FunctionBody }

15.4.2 Static Semantics: HasDirectSuper

The syntax-directed operation HasDirectSuper takes no arguments and returns a Boolean. It is defined piecewise over the following productions:

MethodDefinition : ClassElementName ( UniqueFormalParameters ) { FunctionBody }
  1. UniqueFormalParameters Contains SuperCalltrueなら、trueを返す。
  2. FunctionBody Contains SuperCallを返す。
MethodDefinition : get ClassElementName ( ) { FunctionBody }
  1. FunctionBody Contains SuperCallを返す。
MethodDefinition : set ClassElementName ( PropertySetParameterList ) { FunctionBody }
  1. PropertySetParameterList Contains SuperCalltrueなら、trueを返す。
  2. FunctionBody Contains SuperCallを返す。
GeneratorMethod : * ClassElementName ( UniqueFormalParameters ) { GeneratorBody }
  1. UniqueFormalParameters Contains SuperCalltrueなら、trueを返す。
  2. GeneratorBody Contains SuperCallを返す。
AsyncGeneratorMethod : async * ClassElementName ( UniqueFormalParameters ) { AsyncGeneratorBody }
  1. UniqueFormalParameters Contains SuperCalltrueなら、trueを返す。
  2. AsyncGeneratorBody Contains SuperCallを返す。
AsyncMethod : async ClassElementName ( UniqueFormalParameters ) { AsyncFunctionBody }
  1. UniqueFormalParameters Contains SuperCalltrueなら、trueを返す。
  2. AsyncFunctionBody Contains SuperCallを返す。

15.4.3 Static Semantics: SpecialMethod

The syntax-directed operation SpecialMethod takes no arguments and returns a Boolean. It is defined piecewise over the following productions:

MethodDefinition : ClassElementName ( UniqueFormalParameters ) { FunctionBody }
  1. falseを返す。
MethodDefinition : GeneratorMethod AsyncMethod AsyncGeneratorMethod get ClassElementName ( ) { FunctionBody } set ClassElementName ( PropertySetParameterList ) { FunctionBody }
  1. trueを返す。

15.4.4 Runtime Semantics: DefineMethod

The syntax-directed operation DefineMethod takes argument obj (an Object) and optional argument proto (an Object) and returns either a normal completion containing a Record with fields [[Key]] (a property key) and [[Closure]] (an ECMAScript function object) or an abrupt completion. It is defined piecewise over the following productions:

MethodDefinition : ClassElementName ( UniqueFormalParameters ) { FunctionBody }
  1. propertyKeyClassElementNameの ? Evaluationとする。
  2. envRecordrunning execution contextのLexicalEnvironmentとする。
  3. privateEnvrunning execution contextのPrivateEnvironmentとする。
  4. protoが存在しないなら、proto%Function.prototype%に設定する。
  5. sourceTextMethodDefinitionによってmatchされたsource textとする。
  6. closureOrdinaryFunctionCreate(proto, sourceText, UniqueFormalParameters, FunctionBody, non-lexical-this, envRecord, privateEnv)とする。
  7. MakeMethod(closure, obj)を実行する。
  8. Record { [[Key]]: propertyKey, [[Closure]]: closure }を返す。

15.4.5 Runtime Semantics: MethodDefinitionEvaluation

The syntax-directed operation MethodDefinitionEvaluation takes arguments obj (an Object) and enumerable (a Boolean) and returns either a normal completion containing either a PrivateElement or unused, or an abrupt completion. It is defined piecewise over the following productions:

MethodDefinition : ClassElementName ( UniqueFormalParameters ) { FunctionBody }
  1. methodDefを、argument objを伴うMethodDefinitionの ? DefineMethodとする。
  2. SetFunctionName(methodDef.[[Closure]], methodDef.[[Key]])を実行する。
  3. DefineMethodProperty(obj, methodDef.[[Key]], methodDef.[[Closure]], enumerable)を返す。
MethodDefinition : get ClassElementName ( ) { FunctionBody }
  1. propertyKeyClassElementNameの ? Evaluationとする。
  2. envRecordrunning execution contextのLexicalEnvironmentとする。
  3. privateEnvrunning execution contextのPrivateEnvironmentとする。
  4. sourceTextMethodDefinitionによってmatchされたsource textとする。
  5. formalParamListをproduction FormalParameters : [empty] のinstanceとする。
  6. closureOrdinaryFunctionCreate(%Function.prototype%, sourceText, formalParamList, FunctionBody, non-lexical-this, envRecord, privateEnv)とする。
  7. MakeMethod(closure, obj)を実行する。
  8. SetFunctionName(closure, propertyKey, "get")を実行する。
  9. propertyKeyPrivate Nameなら、
    1. PrivateElement { [[Key]]: propertyKey, [[Kind]]: accessor, [[Get]]: closure, [[Set]]: undefined }を返す。
  10. propertyDescをPropertyDescriptor { [[Get]]: closure, [[Enumerable]]: enumerable, [[Configurable]]: true }とする。
  11. DefinePropertyOrThrow(obj, propertyKey, propertyDesc)を実行する。
  12. unusedを返す。
MethodDefinition : set ClassElementName ( PropertySetParameterList ) { FunctionBody }
  1. propertyKeyClassElementNameの ? Evaluationとする。
  2. envRecordrunning execution contextのLexicalEnvironmentとする。
  3. privateEnvrunning execution contextのPrivateEnvironmentとする。
  4. sourceTextMethodDefinitionによってmatchされたsource textとする。
  5. closureOrdinaryFunctionCreate(%Function.prototype%, sourceText, PropertySetParameterList, FunctionBody, non-lexical-this, envRecord, privateEnv)とする。
  6. MakeMethod(closure, obj)を実行する。
  7. SetFunctionName(closure, propertyKey, "set")を実行する。
  8. propertyKeyPrivate Nameなら、
    1. PrivateElement { [[Key]]: propertyKey, [[Kind]]: accessor, [[Get]]: undefined, [[Set]]: closure }を返す。
  9. propertyDescをPropertyDescriptor { [[Set]]: closure, [[Enumerable]]: enumerable, [[Configurable]]: true }とする。
  10. DefinePropertyOrThrow(obj, propertyKey, propertyDesc)を実行する。
  11. unusedを返す。
GeneratorMethod : * ClassElementName ( UniqueFormalParameters ) { GeneratorBody }
  1. propertyKeyClassElementNameの ? Evaluationとする。
  2. envRecordrunning execution contextのLexicalEnvironmentとする。
  3. privateEnvrunning execution contextのPrivateEnvironmentとする。
  4. sourceTextGeneratorMethodによってmatchされたsource textとする。
  5. closureOrdinaryFunctionCreate(%GeneratorFunction.prototype%, sourceText, UniqueFormalParameters, GeneratorBody, non-lexical-this, envRecord, privateEnv)とする。
  6. MakeMethod(closure, obj)を実行する。
  7. SetFunctionName(closure, propertyKey)を実行する。
  8. protoOrdinaryObjectCreate(%GeneratorPrototype%)とする。
  9. DefinePropertyOrThrow(closure, "prototype", PropertyDescriptor { [[Value]]: proto, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false })を実行する。
  10. DefineMethodProperty(obj, propertyKey, closure, enumerable)を返す。
AsyncGeneratorMethod : async * ClassElementName ( UniqueFormalParameters ) { AsyncGeneratorBody }
  1. propertyKeyClassElementNameの ? Evaluationとする。
  2. envRecordrunning execution contextのLexicalEnvironmentとする。
  3. privateEnvrunning execution contextのPrivateEnvironmentとする。
  4. sourceTextAsyncGeneratorMethodによってmatchされたsource textとする。
  5. closureOrdinaryFunctionCreate(%AsyncGeneratorFunction.prototype%, sourceText, UniqueFormalParameters, AsyncGeneratorBody, non-lexical-this, envRecord, privateEnv)とする。
  6. MakeMethod(closure, obj)を実行する。
  7. SetFunctionName(closure, propertyKey)を実行する。
  8. protoOrdinaryObjectCreate(%AsyncGeneratorPrototype%)とする。
  9. DefinePropertyOrThrow(closure, "prototype", PropertyDescriptor { [[Value]]: proto, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false })を実行する。
  10. DefineMethodProperty(obj, propertyKey, closure, enumerable)を返す。
AsyncMethod : async ClassElementName ( UniqueFormalParameters ) { AsyncFunctionBody }
  1. propertyKeyClassElementNameの ? Evaluationとする。
  2. envRecordrunning execution contextのLexicalEnvironmentとする。
  3. privateEnvrunning execution contextのPrivateEnvironmentとする。
  4. sourceTextAsyncMethodによってmatchされたsource textとする。
  5. closureOrdinaryFunctionCreate(%AsyncFunction.prototype%, sourceText, UniqueFormalParameters, AsyncFunctionBody, non-lexical-this, envRecord, privateEnv)とする。
  6. MakeMethod(closure, obj)を実行する。
  7. SetFunctionName(closure, propertyKey)を実行する。
  8. DefineMethodProperty(obj, propertyKey, closure, enumerable)を返す。

15.5 Generator Function Definitions

Syntax

GeneratorDeclaration[Yield, Await, Default] : function * BindingIdentifier[?Yield, ?Await] ( FormalParameters[+Yield, ~Await] ) { GeneratorBody } [+Default] function * ( FormalParameters[+Yield, ~Await] ) { GeneratorBody } GeneratorExpression : function * BindingIdentifier[+Yield, ~Await]opt ( FormalParameters[+Yield, ~Await] ) { GeneratorBody } GeneratorMethod[Yield, Await] : * ClassElementName[?Yield, ?Await] ( UniqueFormalParameters[+Yield, ~Await] ) { GeneratorBody } GeneratorBody : FunctionBody[+Yield, ~Await] YieldExpression[In, Await] : yield yield [no LineTerminator here] AssignmentExpression[?In, +Yield, ?Await] yield [no LineTerminator here] * AssignmentExpression[?In, +Yield, ?Await] Note 1

yieldの直後のsyntactic contextでは、InputElementRegExpOrTemplateTail lexical goalの使用が必要です。

Note 2

YieldExpressionはgenerator functionのFormalParameters内では使用できません。なぜなら、FormalParametersの一部であるexpressionsは、結果として得られるGeneratorがresumable stateになる前に評価されるからです。

Note 3

Generatorsに関係するabstract operations27.8.3で定義されます。

15.5.1 Static Semantics: Early Errors

GeneratorMethod : * ClassElementName ( UniqueFormalParameters ) { GeneratorBody } GeneratorDeclaration : function * BindingIdentifier ( FormalParameters ) { GeneratorBody } function * ( FormalParameters ) { GeneratorBody } GeneratorExpression : function * BindingIdentifieropt ( FormalParameters ) { GeneratorBody }

15.5.2 Runtime Semantics: EvaluateGeneratorBody

The syntax-directed operation EvaluateGeneratorBody takes arguments funcObj (an ECMAScript function object) and argList (a List of ECMAScript language values) and returns a throw completion or a return completion. It is defined piecewise over the following productions:

GeneratorBody : FunctionBody
  1. FunctionDeclarationInstantiation(funcObj, argList)を実行する。
  2. genを ? OrdinaryCreateFromConstructor(funcObj, "%GeneratorPrototype%", « [[GeneratorState]], [[GeneratorContext]], [[GeneratorBrand]] ») とする。
  3. gen.[[GeneratorBrand]]emptyに設定する。
  4. gen.[[GeneratorState]]suspended-startに設定する。
  5. GeneratorStart(gen, FunctionBody)を実行する。
  6. ReturnCompletion(gen)を返す。

15.5.3 Runtime Semantics: InstantiateGeneratorFunctionObject

The syntax-directed operation InstantiateGeneratorFunctionObject takes arguments envRecord (an Environment Record) and privateEnv (a PrivateEnvironment Record or null) and returns an ECMAScript function object. It is defined piecewise over the following productions:

GeneratorDeclaration : function * BindingIdentifier ( FormalParameters ) { GeneratorBody }
  1. nameBindingIdentifierStringValueとする。
  2. sourceTextGeneratorDeclarationによってmatchされたsource textとする。
  3. closureOrdinaryFunctionCreate(%GeneratorFunction.prototype%, sourceText, FormalParameters, GeneratorBody, non-lexical-this, envRecord, privateEnv)とする。
  4. SetFunctionName(closure, name)を実行する。
  5. protoOrdinaryObjectCreate(%GeneratorPrototype%)とする。
  6. DefinePropertyOrThrow(closure, "prototype", PropertyDescriptor { [[Value]]: proto, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false })を実行する。
  7. closureを返す。
GeneratorDeclaration : function * ( FormalParameters ) { GeneratorBody }
  1. sourceTextGeneratorDeclarationによってmatchされたsource textとする。
  2. closureOrdinaryFunctionCreate(%GeneratorFunction.prototype%, sourceText, FormalParameters, GeneratorBody, non-lexical-this, envRecord, privateEnv)とする。
  3. SetFunctionName(closure, "default")を実行する。
  4. protoOrdinaryObjectCreate(%GeneratorPrototype%)とする。
  5. DefinePropertyOrThrow(closure, "prototype", PropertyDescriptor { [[Value]]: proto, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false })を実行する。
  6. closureを返す。
Note

anonymous GeneratorDeclarationexport default declarationの一部としてのみ出現できるため、そのfunction codeは常にstrict mode codeです。

15.5.4 Runtime Semantics: InstantiateGeneratorFunctionExpression

The syntax-directed operation InstantiateGeneratorFunctionExpression takes optional argument name (a property key or a Private Name) and returns an ECMAScript function object. It is defined piecewise over the following productions:

GeneratorExpression : function * ( FormalParameters ) { GeneratorBody }
  1. nameが存在しない場合、nameをempty Stringに設定する。
  2. envRecordrunning execution contextのLexicalEnvironmentとする。
  3. privateEnvrunning execution contextのPrivateEnvironmentとする。
  4. sourceTextGeneratorExpressionによってmatchされたsource textとする。
  5. closureOrdinaryFunctionCreate(%GeneratorFunction.prototype%, sourceText, FormalParameters, GeneratorBody, non-lexical-this, envRecord, privateEnv)とする。
  6. SetFunctionName(closure, name)を実行する。
  7. protoOrdinaryObjectCreate(%GeneratorPrototype%)とする。
  8. DefinePropertyOrThrow(closure, "prototype", PropertyDescriptor { [[Value]]: proto, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false })を実行する。
  9. closureを返す。
GeneratorExpression : function * BindingIdentifier ( FormalParameters ) { GeneratorBody }
  1. Assert: nameは存在しない。
  2. nameBindingIdentifierStringValueに設定する。
  3. outerEnvrunning execution contextのLexicalEnvironmentとする。
  4. funcEnvNewDeclarativeEnvironment(outerEnv)とする。
  5. funcEnv.CreateImmutableBinding(name, false)を実行する。
  6. privateEnvrunning execution contextのPrivateEnvironmentとする。
  7. sourceTextGeneratorExpressionによってmatchされたsource textとする。
  8. closureOrdinaryFunctionCreate(%GeneratorFunction.prototype%, sourceText, FormalParameters, GeneratorBody, non-lexical-this, funcEnv, privateEnv)とする。
  9. SetFunctionName(closure, name)を実行する。
  10. protoOrdinaryObjectCreate(%GeneratorPrototype%)とする。
  11. DefinePropertyOrThrow(closure, "prototype", PropertyDescriptor { [[Value]]: proto, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false })を実行する。
  12. funcEnv.InitializeBinding(name, closure)を実行する。
  13. closureを返す。
Note

GeneratorExpression内のBindingIdentifierは、generator codeがそれ自身を再帰的に呼び出せるように、GeneratorExpressionFunctionBody内部からreferenceできます。ただし、GeneratorDeclarationの場合とは異なり、GeneratorExpression内のBindingIdentifierは、GeneratorExpressionを囲むscopeからreferenceできず、そのscopeに影響しません。

15.5.5 Runtime Semantics: Evaluation

GeneratorExpression : function * BindingIdentifieropt ( FormalParameters ) { GeneratorBody }
  1. GeneratorExpressionInstantiateGeneratorFunctionExpressionを返す。
YieldExpression : yield
  1. Yield(undefined)を返す。
YieldExpression : yield AssignmentExpression
  1. exprRefAssignmentExpressionの ? Evaluationとする。
  2. valueを ? GetValue(exprRef) とする。
  3. Yield(value)を返す。
YieldExpression : yield * AssignmentExpression
  1. genKindGetGeneratorKind()とする。
  2. Assert: genKindsyncまたはasyncのいずれかである。
  3. exprRefAssignmentExpressionの ? Evaluationとする。
  4. valueを ? GetValue(exprRef) とする。
  5. iteratorRecordを ? GetIterator(value, genKind) とする。
  6. iteratoriteratorRecord.[[Iterator]]とする。
  7. receivedNormalCompletion(undefined)とする。
  8. 繰り返す
    1. receivednormal completionなら、
      1. innerResultを ? Call(iteratorRecord.[[NextMethod]], iteratorRecord.[[Iterator]], « received.[[Value]] ») とする。
      2. genKindasyncなら、innerResultを ? Await(innerResult) に設定する。
      3. innerResultがObjectでないなら、TypeError例外をthrowする。
      4. doneを ? IteratorComplete(innerResult) とする。
      5. donetrueなら、
        1. IteratorValue(innerResult)を返す。
      6. genKindasyncなら、receivedCompletion(AsyncGeneratorYield(? IteratorValue(innerResult)))に設定する。
      7. そうでなければ、receivedCompletion(GeneratorYield(innerResult))に設定する。
    2. そうでなく、receivedthrow completionなら、
      1. throwを ? GetMethod(iterator, "throw") とする。
      2. throwundefinedでないなら、
        1. innerResultを ? Call(throw, iterator, « received.[[Value]] ») とする。
        2. genKindasyncなら、innerResultを ? Await(innerResult) に設定する。
        3. NOTE: inner iteratorthrow methodからのexceptionsは伝播される。inner throw methodからのnormal completionsは、inner nextと同様に処理される。
        4. innerResultがObjectでないなら、TypeError例外をthrowする。
        5. doneを ? IteratorComplete(innerResult) とする。
        6. donetrueなら、
          1. IteratorValue(innerResult)を返す。
        7. genKindasyncなら、receivedCompletion(AsyncGeneratorYield(? IteratorValue(innerResult)))に設定する。
        8. そうでなければ、receivedCompletion(GeneratorYield(innerResult))に設定する。
      3. そうでなければ、
        1. NOTE: iteratorthrow methodを持たない場合、このthrowはyield* loopを終了させることになる。しかし、まずiteratorにclean upの機会を与える必要がある。
        2. closeCompletionNormalCompletion(empty)とする。
        3. genKindasyncなら、? AsyncIteratorClose(iteratorRecord, closeCompletion)を実行する。
        4. そうでなければ、? IteratorClose(iteratorRecord, closeCompletion)を実行する。
        5. NOTE: next stepは、yield* protocol violationがあったこと、すなわちiteratorthrow methodを持たないことを示すためにTypeErrorをthrowする。
        6. TypeError例外をthrowする。
    3. そうでなければ、
      1. Assert: receivedreturn completionである。
      2. returnを ? GetMethod(iterator, "return") とする。
      3. returnundefinedなら、
        1. receivedValuereceived.[[Value]]とする。
        2. genKindasyncなら、
          1. receivedValueを ? Await(receivedValue) に設定する。
        3. ReturnCompletion(receivedValue)を返す。
      4. innerReturnResultを ? Call(return, iterator, « received.[[Value]] ») とする。
      5. genKindasyncなら、innerReturnResultを ? Await(innerReturnResult) に設定する。
      6. innerReturnResultがObjectでないなら、TypeError例外をthrowする。
      7. doneを ? IteratorComplete(innerReturnResult) とする。
      8. donetrueなら、
        1. returnedValueを ? IteratorValue(innerReturnResult) とする。
        2. ReturnCompletion(returnedValue)を返す。
      9. genKindasyncなら、receivedCompletion(AsyncGeneratorYield(? IteratorValue(innerReturnResult)))に設定する。
      10. そうでなければ、receivedCompletion(GeneratorYield(innerReturnResult))に設定する。

15.6 Async Generator Function Definitions

Syntax

AsyncGeneratorDeclaration[Yield, Await, Default] : async [no LineTerminator here] function * BindingIdentifier[?Yield, ?Await] ( FormalParameters[+Yield, +Await] ) { AsyncGeneratorBody } [+Default] async [no LineTerminator here] function * ( FormalParameters[+Yield, +Await] ) { AsyncGeneratorBody } AsyncGeneratorExpression : async [no LineTerminator here] function * BindingIdentifier[+Yield, +Await]opt ( FormalParameters[+Yield, +Await] ) { AsyncGeneratorBody } AsyncGeneratorMethod[Yield, Await] : async [no LineTerminator here] * ClassElementName[?Yield, ?Await] ( UniqueFormalParameters[+Yield, +Await] ) { AsyncGeneratorBody } AsyncGeneratorBody : FunctionBody[+Yield, +Await] Note 1

YieldExpressionおよびAwaitExpressionはasync generator functionのFormalParameters内では使用できません。なぜなら、FormalParametersの一部であるexpressionsは、結果として得られるAsyncGeneratorがresumable stateになる前に評価されるからです。

Note 2

AsyncGeneratorsに関係するabstract operations27.9.3で定義されます。

15.6.1 Static Semantics: Early Errors

AsyncGeneratorMethod : async * ClassElementName ( UniqueFormalParameters ) { AsyncGeneratorBody } AsyncGeneratorDeclaration : async function * BindingIdentifier ( FormalParameters ) { AsyncGeneratorBody } async function * ( FormalParameters ) { AsyncGeneratorBody } AsyncGeneratorExpression : async function * BindingIdentifieropt ( FormalParameters ) { AsyncGeneratorBody }

15.6.2 Runtime Semantics: EvaluateAsyncGeneratorBody

The syntax-directed operation EvaluateAsyncGeneratorBody takes arguments funcObj (an ECMAScript function object) and argList (a List of ECMAScript language values) and returns a throw completion or a return completion. It is defined piecewise over the following productions:

AsyncGeneratorBody : FunctionBody
  1. FunctionDeclarationInstantiation(funcObj, argList)を実行する。
  2. genを ? OrdinaryCreateFromConstructor(funcObj, "%AsyncGeneratorPrototype%", « [[AsyncGeneratorState]], [[AsyncGeneratorContext]], [[AsyncGeneratorQueue]], [[GeneratorBrand]] ») とする。
  3. gen.[[GeneratorBrand]]emptyに設定する。
  4. gen.[[AsyncGeneratorState]]suspended-startに設定する。
  5. AsyncGeneratorStart(gen, FunctionBody)を実行する。
  6. ReturnCompletion(gen)を返す。

15.6.3 Runtime Semantics: InstantiateAsyncGeneratorFunctionObject

The syntax-directed operation InstantiateAsyncGeneratorFunctionObject takes arguments envRecord (an Environment Record) and privateEnv (a PrivateEnvironment Record or null) and returns an ECMAScript function object. It is defined piecewise over the following productions:

AsyncGeneratorDeclaration : async function * BindingIdentifier ( FormalParameters ) { AsyncGeneratorBody }
  1. nameBindingIdentifierStringValueとする。
  2. sourceTextAsyncGeneratorDeclarationによってmatchされたsource textとする。
  3. closureOrdinaryFunctionCreate(%AsyncGeneratorFunction.prototype%, sourceText, FormalParameters, AsyncGeneratorBody, non-lexical-this, envRecord, privateEnv)とする。
  4. SetFunctionName(closure, name)を実行する。
  5. protoOrdinaryObjectCreate(%AsyncGeneratorPrototype%)とする。
  6. DefinePropertyOrThrow(closure, "prototype", PropertyDescriptor { [[Value]]: proto, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false })を実行する。
  7. closureを返す。
AsyncGeneratorDeclaration : async function * ( FormalParameters ) { AsyncGeneratorBody }
  1. sourceTextAsyncGeneratorDeclarationによってmatchされたsource textとする。
  2. closureOrdinaryFunctionCreate(%AsyncGeneratorFunction.prototype%, sourceText, FormalParameters, AsyncGeneratorBody, non-lexical-this, envRecord, privateEnv)とする。
  3. SetFunctionName(closure, "default")を実行する。
  4. protoOrdinaryObjectCreate(%AsyncGeneratorPrototype%)とする。
  5. DefinePropertyOrThrow(closure, "prototype", PropertyDescriptor { [[Value]]: proto, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false })を実行する。
  6. closureを返す。
Note

anonymous AsyncGeneratorDeclarationexport default declarationの一部としてのみ出現できます。

15.6.4 Runtime Semantics: InstantiateAsyncGeneratorFunctionExpression

The syntax-directed operation InstantiateAsyncGeneratorFunctionExpression takes optional argument name (a property key or a Private Name) and returns an ECMAScript function object. It is defined piecewise over the following productions:

AsyncGeneratorExpression : async function * ( FormalParameters ) { AsyncGeneratorBody }
  1. nameが存在しない場合、nameをempty Stringに設定する。
  2. envRecordrunning execution contextのLexicalEnvironmentとする。
  3. privateEnvrunning execution contextのPrivateEnvironmentとする。
  4. sourceTextAsyncGeneratorExpressionによってmatchされたsource textとする。
  5. closureOrdinaryFunctionCreate(%AsyncGeneratorFunction.prototype%, sourceText, FormalParameters, AsyncGeneratorBody, non-lexical-this, envRecord, privateEnv)とする。
  6. SetFunctionName(closure, name)を実行する。
  7. protoOrdinaryObjectCreate(%AsyncGeneratorPrototype%)とする。
  8. DefinePropertyOrThrow(closure, "prototype", PropertyDescriptor { [[Value]]: proto, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false })を実行する。
  9. closureを返す。
AsyncGeneratorExpression : async function * BindingIdentifier ( FormalParameters ) { AsyncGeneratorBody }
  1. Assert: nameは存在しない。
  2. nameBindingIdentifierStringValueに設定する。
  3. outerEnvrunning execution contextのLexicalEnvironmentとする。
  4. funcEnvNewDeclarativeEnvironment(outerEnv)とする。
  5. funcEnv.CreateImmutableBinding(name, false)を実行する。
  6. privateEnvrunning execution contextのPrivateEnvironmentとする。
  7. sourceTextAsyncGeneratorExpressionによってmatchされたsource textとする。
  8. closureOrdinaryFunctionCreate(%AsyncGeneratorFunction.prototype%, sourceText, FormalParameters, AsyncGeneratorBody, non-lexical-this, funcEnv, privateEnv)とする。
  9. SetFunctionName(closure, name)を実行する。
  10. protoOrdinaryObjectCreate(%AsyncGeneratorPrototype%)とする。
  11. DefinePropertyOrThrow(closure, "prototype", PropertyDescriptor { [[Value]]: proto, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false })を実行する。
  12. funcEnv.InitializeBinding(name, closure)を実行する。
  13. closureを返す。
Note

AsyncGeneratorExpression内のBindingIdentifierは、generator codeがそれ自身を再帰的に呼び出せるように、AsyncGeneratorExpressionAsyncGeneratorBody内部からreferenceできます。ただし、AsyncGeneratorDeclarationの場合とは異なり、AsyncGeneratorExpression内のBindingIdentifierは、AsyncGeneratorExpressionを囲むscopeからreferenceできず、そのscopeに影響しません。

15.6.5 Runtime Semantics: Evaluation

AsyncGeneratorExpression : async function * BindingIdentifieropt ( FormalParameters ) { AsyncGeneratorBody }
  1. AsyncGeneratorExpressionInstantiateAsyncGeneratorFunctionExpressionを返す。

15.7 Class Definitions

Syntax

ClassDeclaration[Yield, Await, Default] : class BindingIdentifier[?Yield, ?Await] ClassTail[?Yield, ?Await] [+Default] class ClassTail[?Yield, ?Await] ClassExpression[Yield, Await] : class BindingIdentifier[?Yield, ?Await]opt ClassTail[?Yield, ?Await] ClassTail[Yield, Await] : ClassHeritage[?Yield, ?Await]opt { ClassBody[?Yield, ?Await]opt } ClassHeritage[Yield, Await] : extends LeftHandSideExpression[?Yield, ?Await] ClassBody[Yield, Await] : ClassElementList[?Yield, ?Await] ClassElementList[Yield, Await] : ClassElement[?Yield, ?Await] ClassElementList[?Yield, ?Await] ClassElement[?Yield, ?Await] ClassElement[Yield, Await] : MethodDefinition[?Yield, ?Await] static MethodDefinition[?Yield, ?Await] FieldDefinition[?Yield, ?Await] ; static FieldDefinition[?Yield, ?Await] ; ClassStaticBlock ; FieldDefinition[Yield, Await] : ClassElementName[?Yield, ?Await] Initializer[+In, ?Yield, ?Await]opt ClassElementName[Yield, Await] : PropertyName[?Yield, ?Await] PrivateIdentifier ClassStaticBlock : static { ClassStaticBlockBody } ClassStaticBlockBody : ClassStaticBlockStatementList ClassStaticBlockStatementList : StatementList[~Yield, +Await, ~Return]opt Note

class definitionは常にstrict mode codeです。

15.7.1 Static Semantics: Early Errors

ClassTail : ClassHeritageopt { ClassBody } ClassBody : ClassElementList
  • ClassElementListPrototypePropertyNameList"constructor"の出現を複数含む場合、それはSyntax Errorです。
  • ClassElementListPrivateBoundIdentifiersが重複entriesを含む場合、それはSyntax Errorです。ただし、そのnameがgetterに1回、setterに1回だけ使用され、他のentriesでは使用されず、getterとsetterが両方ともstaticまたは両方ともnon-staticである場合を除きます。
ClassElement : MethodDefinition ClassElement : static MethodDefinition ClassElement : FieldDefinition ; ClassElement : static FieldDefinition ;
  • FieldDefinitionPropName"prototype"または"constructor"のいずれかである場合、それはSyntax Errorです。
FieldDefinition : ClassElementName Initializeropt ClassElementName : PrivateIdentifier ClassStaticBlockBody : ClassStaticBlockStatementList

15.7.2 Static Semantics: ClassElementKind

The syntax-directed operation ClassElementKind takes no arguments and returns constructor-method, non-constructor-method, or empty. It is defined piecewise over the following productions:

ClassElement : MethodDefinition
  1. MethodDefinitionPropName"constructor"なら、constructor-methodを返す。
  2. non-constructor-methodを返す。
ClassElement : static MethodDefinition FieldDefinition ; static FieldDefinition ;
  1. non-constructor-methodを返す。
ClassElement : ClassStaticBlock
  1. non-constructor-methodを返す。
ClassElement : ;
  1. emptyを返す。

15.7.3 Static Semantics: ConstructorMethod

The syntax-directed operation ConstructorMethod takes no arguments and returns a ClassElement Parse Node or empty. It is defined piecewise over the following productions:

ClassElementList : ClassElement
  1. ClassElementClassElementKindconstructor-methodなら、ClassElementを返す。
  2. emptyを返す。
ClassElementList : ClassElementList ClassElement
  1. headClassElementListConstructorMethodとする。
  2. heademptyでないなら、headを返す。
  3. ClassElementClassElementKindconstructor-methodなら、ClassElementを返す。
  4. emptyを返す。
Note

Early Error rulesは、"constructor"と名付けられたmethod definitionが1つだけ存在し、それがaccessor propertyまたはgenerator definitionでないことを保証します。

15.7.4 Static Semantics: IsStatic

The syntax-directed operation IsStatic takes no arguments and returns a Boolean. It is defined piecewise over the following productions:

ClassElement : MethodDefinition
  1. falseを返す。
ClassElement : static MethodDefinition
  1. trueを返す。
ClassElement : FieldDefinition ;
  1. falseを返す。
ClassElement : static FieldDefinition ;
  1. trueを返す。
ClassElement : ClassStaticBlock
  1. trueを返す。
ClassElement : ;
  1. falseを返す。

15.7.5 Static Semantics: NonConstructorElements

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

ClassElementList : ClassElement
  1. ClassElementClassElementKindnon-constructor-methodなら、
    1. « ClassElement »を返す。
  2. 新しい空のListを返す。
ClassElementList : ClassElementList ClassElement
  1. listClassElementListNonConstructorElementsとする。
  2. ClassElementClassElementKindnon-constructor-methodなら、
    1. ClassElementlistへappendする。
  3. listを返す。

15.7.6 Static Semantics: PrototypePropertyNameList

The syntax-directed operation PrototypePropertyNameList takes no arguments and returns a List of property keys. It is defined piecewise over the following productions:

ClassElementList : ClassElement
  1. propertyNameClassElementPropNameとする。
  2. propertyNameemptyなら、新しい空のListを返す。
  3. ClassElementIsStatictrueなら、新しい空のListを返す。
  4. « propertyName »を返す。
ClassElementList : ClassElementList ClassElement
  1. listClassElementListPrototypePropertyNameListとする。
  2. propertyNameClassElementPropNameとする。
  3. propertyNameemptyなら、listを返す。
  4. ClassElementIsStatictrueなら、listを返す。
  5. listと« propertyName »のlist-concatenationを返す。

15.7.7 Static Semantics: AllPrivateIdentifiersValid

The syntax-directed operation AllPrivateIdentifiersValid takes argument names (a List of Strings) and returns a Boolean.

この仕様内で下に列挙されていないすべてのgrammar production alternativeは、暗黙的にAllPrivateIdentifiersValidの次のdefault definitionを持ちます:

  1. このParse Nodeの各child node childについて、以下を行う
    1. childがnonterminalのinstanceなら、
      1. argument namesを伴うchildAllPrivateIdentifiersValidfalseなら、falseを返す。
  2. trueを返す。
MemberExpression : MemberExpression . PrivateIdentifier
  1. namesPrivateIdentifierStringValueを含むなら、
    1. argument namesを伴うMemberExpressionAllPrivateIdentifiersValidを返す。
  2. falseを返す。
CallExpression : CallExpression . PrivateIdentifier
  1. namesPrivateIdentifierStringValueを含むなら、
    1. argument namesを伴うCallExpressionAllPrivateIdentifiersValidを返す。
  2. falseを返す。
OptionalChain : ?. PrivateIdentifier
  1. namesPrivateIdentifierStringValueを含むなら、trueを返す。
  2. falseを返す。
OptionalChain : OptionalChain . PrivateIdentifier
  1. namesPrivateIdentifierStringValueを含むなら、
    1. argument namesを伴うOptionalChainAllPrivateIdentifiersValidを返す。
  2. falseを返す。
ClassBody : ClassElementList
  1. newNamesnamesClassBodyPrivateBoundIdentifierslist-concatenationとする。
  2. argument newNamesを伴うClassElementListAllPrivateIdentifiersValidを返す。
RelationalExpression : PrivateIdentifier in ShiftExpression
  1. namesPrivateIdentifierStringValueを含むなら、
    1. argument namesを伴うShiftExpressionAllPrivateIdentifiersValidを返す。
  2. falseを返す。

15.7.8 Static Semantics: PrivateBoundIdentifiers

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

FieldDefinition : ClassElementName Initializeropt
  1. ClassElementNamePrivateBoundIdentifiersを返す。
ClassElementName : PrivateIdentifier
  1. 唯一の要素がPrivateIdentifierStringValueであるListを返す。
ClassElementName : PropertyName ClassElement : ClassStaticBlock ;
  1. 新しい空のListを返す。
ClassElementList : ClassElementList ClassElement
  1. names1ClassElementListPrivateBoundIdentifiersとする。
  2. names2ClassElementPrivateBoundIdentifiersとする。
  3. names1names2list-concatenationを返す。
MethodDefinition : ClassElementName ( UniqueFormalParameters ) { FunctionBody } get ClassElementName ( ) { FunctionBody } set ClassElementName ( PropertySetParameterList ) { FunctionBody } GeneratorMethod : * ClassElementName ( UniqueFormalParameters ) { GeneratorBody } AsyncMethod : async ClassElementName ( UniqueFormalParameters ) { AsyncFunctionBody } AsyncGeneratorMethod : async * ClassElementName ( UniqueFormalParameters ) { AsyncGeneratorBody }
  1. ClassElementNamePrivateBoundIdentifiersを返す。

15.7.9 Static Semantics: ContainsArguments

The syntax-directed operation ContainsArguments takes no arguments and returns a Boolean.

この仕様内で下に列挙されていないすべてのgrammar production alternativeは、暗黙的にContainsArgumentsの次のdefault definitionを持ちます:

  1. このParse Nodeの各child node childについて、以下を行う
    1. childがnonterminalのinstanceなら、
      1. childContainsArgumentstrueなら、trueを返す。
  2. falseを返す。
IdentifierReference : Identifier
  1. IdentifierStringValue"arguments"なら、trueを返す。
  2. falseを返す。
FunctionDeclaration : function BindingIdentifier ( FormalParameters ) { FunctionBody } function ( FormalParameters ) { FunctionBody } FunctionExpression : function BindingIdentifieropt ( FormalParameters ) { FunctionBody } GeneratorDeclaration : function * BindingIdentifier ( FormalParameters ) { GeneratorBody } function * ( FormalParameters ) { GeneratorBody } GeneratorExpression : function * BindingIdentifieropt ( FormalParameters ) { GeneratorBody } AsyncGeneratorDeclaration : async function * BindingIdentifier ( FormalParameters ) { AsyncGeneratorBody } async function * ( FormalParameters ) { AsyncGeneratorBody } AsyncGeneratorExpression : async function * BindingIdentifieropt ( FormalParameters ) { AsyncGeneratorBody } AsyncFunctionDeclaration : async function BindingIdentifier ( FormalParameters ) { AsyncFunctionBody } async function ( FormalParameters ) { AsyncFunctionBody } AsyncFunctionExpression : async function BindingIdentifieropt ( FormalParameters ) { AsyncFunctionBody }
  1. falseを返す。
MethodDefinition : ClassElementName ( UniqueFormalParameters ) { FunctionBody } get ClassElementName ( ) { FunctionBody } set ClassElementName ( PropertySetParameterList ) { FunctionBody } GeneratorMethod : * ClassElementName ( UniqueFormalParameters ) { GeneratorBody } AsyncGeneratorMethod : async * ClassElementName ( UniqueFormalParameters ) { AsyncGeneratorBody } AsyncMethod : async ClassElementName ( UniqueFormalParameters ) { AsyncFunctionBody }
  1. ClassElementNameContainsArgumentsを返す。

15.7.10 Runtime Semantics: ClassFieldDefinitionEvaluation

The syntax-directed operation ClassFieldDefinitionEvaluation takes argument homeObj (an Object) and returns either a normal completion containing a ClassFieldDefinition Record or an abrupt completion. It is defined piecewise over the following productions:

FieldDefinition : ClassElementName Initializeropt
  1. nameClassElementNameの ? Evaluationとする。
  2. Initializerが存在するなら、
    1. formalParamListをproduction FormalParameters : [empty] のinstanceとする。
    2. envRecordrunning execution contextのLexicalEnvironmentとする。
    3. privateEnvrunning execution contextのPrivateEnvironmentとする。
    4. sourceTextをUnicode code pointsのempty sequenceとする。
    5. initializerOrdinaryFunctionCreate(%Function.prototype%, sourceText, formalParamList, Initializer, non-lexical-this, envRecord, privateEnv)とする。
    6. MakeMethod(initializer, homeObj)を実行する。
    7. initializer.[[ClassFieldInitializerName]]nameに設定する。
  3. そうでなければ、
    1. initializeremptyとする。
  4. ClassFieldDefinition Record { [[Name]]: name, [[Initializer]]: initializer }を返す。
Note
initializerのために作成されるfunctionは、ECMAScript codeから直接accessできることは決してありません。

15.7.11 Runtime Semantics: ClassStaticBlockDefinitionEvaluation

The syntax-directed operation ClassStaticBlockDefinitionEvaluation takes argument homeObj (an Object) and returns a ClassStaticBlockDefinition Record. It is defined piecewise over the following productions:

ClassStaticBlock : static { ClassStaticBlockBody }
  1. 実行中の実行コンテキストのLexicalEnvironmentをlexicalEnvとする。
  2. 実行中の実行コンテキストのPrivateEnvironmentをprivateEnvとする。
  3. 空のUnicode符号点列をsourceTextとする。
  4. 生成規則 FormalParameters : [empty] のインスタンスをformalParamsとする。
  5. OrdinaryFunctionCreate(%Function.prototype%, sourceText, formalParams, ClassStaticBlockBody, non-lexical-this, lexicalEnv, privateEnv)をbodyFuncとする。
  6. MakeMethod(bodyFunc, homeObj)を実行する。
  7. ClassStaticBlockDefinition Record { [[BodyFunction]]: bodyFunc }を返す。
Note
function bodyFuncはECMAScript codeから直接accessできることは決してありません。

15.7.12 Runtime Semantics: EvaluateClassStaticBlockBody

The syntax-directed operation EvaluateClassStaticBlockBody takes argument funcObj (an ECMAScript function object) and returns a return completion or a throw completion. It is defined piecewise over the following productions:

ClassStaticBlockBody : ClassStaticBlockStatementList
  1. Assert: funcObjClassStaticBlockDefinitionEvaluation ステップ 5 によって作成された合成関数である。
  2. FunctionDeclarationInstantiation(funcObj, « ») を実行する。
  3. resultClassStaticBlockStatementListEvaluationCompletion とする。
  4. envRecord を、実行中の実行コンテキストの LexicalEnvironment とする。
  5. Assert: envRecordDeclarative Environment Record である。
  6. DisposeResources(envRecord.[[DisposableResourceStack]], result) を実行する。
  7. ReturnCompletion(undefined) を返す。

15.7.13 Runtime Semantics: ClassElementEvaluation

The syntax-directed operation ClassElementEvaluation takes argument obj (an Object) and returns either a normal completion containing either a ClassFieldDefinition Record, a ClassStaticBlockDefinition Record, a PrivateElement, or unused, or an abrupt completion. It is defined piecewise over the following productions:

ClassElement : FieldDefinition ; static FieldDefinition ;
  1. argument objを伴うFieldDefinitionの ? ClassFieldDefinitionEvaluationを返す。
ClassElement : MethodDefinition static MethodDefinition
  1. arguments objおよびfalseを伴うMethodDefinitionの ? MethodDefinitionEvaluationを返す。
ClassElement : ClassStaticBlock
  1. argument objを伴うClassStaticBlockClassStaticBlockDefinitionEvaluationを返す。
ClassElement : ;
  1. unusedを返す。

15.7.14 Runtime Semantics: ClassDefinitionEvaluation

The syntax-directed operation ClassDefinitionEvaluation takes arguments classBinding (a String or undefined), className (a property key or a Private Name), and sourceText (ECMAScript source text) and returns either a normal completion containing a function object or an abrupt completion.

Note

specificationの容易さのため、private methodsおよびaccessorsは、private fieldsと並んでclass instancesの[[PrivateElements]] slotに含められます。ただし、任意のobjectは、与えられたclassによって定義されるprivate methodsおよびaccessorsのすべてを持つか、まったく持たないかのいずれかです。この機能は、implementationsが各methodまたはaccessorを個別にtrackする必要のないstrategyを使用してprivate methodsおよびaccessorsを実装することを選択できるように設計されています。

例えば、implementationはinstance private methodsをそれらに対応するPrivate Nameへ直接関連付け、各objectについて、どのclass constructorsがそのobjectをthis valueとして実行されたかをtrackできます。object上でinstance private methodをlookupすることは、そのmethodを定義するclass constructorがそのobjectをinitializeするために使用されたことをcheckし、その後Private Nameに関連付けられたmethodを返すことからなります。

これはprivate fieldsとは異なります。field initializersはclass instantiation中にthrowする可能性があるため、個々のobjectは与えられたclassのprivate fieldsのproper subsetだけを持つ場合があり、そのためprivate fieldsは一般に個別にtrackされなければなりません。

It is defined piecewise over the following productions:

ClassTail : ClassHeritageopt { ClassBodyopt }
  1. envRecordrunning execution contextのLexicalEnvironmentとする。
  2. classEnvNewDeclarativeEnvironment(envRecord)とする。
  3. classBindingundefinedでないなら、
    1. classEnv.CreateImmutableBinding(classBinding, true)を実行する。
  4. outerPrivateEnvrunning execution contextのPrivateEnvironmentとする。
  5. classPrivateEnvNewPrivateEnvironment(outerPrivateEnv)とする。
  6. ClassBodyが存在するなら、
    1. ClassBodyPrivateBoundIdentifiersの各String descriptionについて、以下を行う
      1. classPrivateEnv.[[Names]]が、[[Description]]descriptionであるPrivate Name privateNameを含むなら、
        1. Assert: これはgetter/setter pairsの場合にのみ可能である。
      2. そうでなければ、
        1. nameを、その[[Description]]descriptionである新しいPrivate Nameとする。
        2. nameclassPrivateEnv.[[Names]]へappendする。
  7. ClassHeritageが存在しないなら、
    1. protoParent%Object.prototype%とする。
    2. ctorParent%Function.prototype%とする。
  8. そうでなければ、
    1. running execution contextのLexicalEnvironmentをclassEnvに設定する。
    2. NOTE: ClassHeritageを評価するとき、running execution contextのPrivateEnvironmentはouterPrivateEnvである。
    3. superclassRefClassHeritageEvaluationCompletionとする。
    4. running execution contextのLexicalEnvironmentをenvRecordに設定する。
    5. superclassを ? GetValue(? superclassRef) とする。
    6. superclassnullなら、
      1. protoParentnullとする。
      2. ctorParent%Function.prototype%とする。
    7. そうでなく、IsConstructor(superclass)がfalseなら、
      1. TypeError例外をthrowする。
    8. そうでなければ、
      1. protoParentを ? Get(superclass, "prototype") とする。
      2. protoParentがObjectでなく、かつprotoParentnullでないなら、TypeError例外をthrowする。
      3. ctorParentsuperclassとする。
  9. protoOrdinaryObjectCreate(protoParent)とする。
  10. ClassBodyが存在しないなら、ctoremptyとする。
  11. そうでなければ、ctorClassBodyConstructorMethodとする。
  12. running execution contextのLexicalEnvironmentをclassEnvに設定する。
  13. running execution contextのPrivateEnvironmentをclassPrivateEnvに設定する。
  14. ctoremptyなら、
    1. defaultCtorを、parametersを持たず、何もcaptureせず、呼び出されたときに次のstepsを実行する新しいAbstract Closureとする:
      1. argsを、このfunctionに[[Call]]または[[Construct]]によって渡されたargumentsのListとする。
      2. NewTargetがundefinedなら、TypeError例外をthrowする。
      3. ctorFuncactive function objectとする。
      4. ctorFunc.[[ConstructorKind]]derivedなら、
        1. NOTE: このbranchはconstructor(...args) { super(...args); }と同様に振る舞う。最も注目すべき違いは、前述のECMAScript source text%Array.prototype%上の%Symbol.iterator% methodをobservablyに呼び出すのに対し、このfunctionはそれを行わないことである。
        2. funcを ! ctorFunc.[[GetPrototypeOf]]() とする。
        3. IsConstructor(func)がfalseなら、TypeError例外をthrowする。
        4. resultを ? Construct(func, args, NewTarget) とする。
      5. そうでなければ、
        1. NOTE: このbranchはconstructor() {}と同様に振る舞う。
        2. resultを ? OrdinaryCreateFromConstructor(NewTarget, "%Object.prototype%") とする。
      6. InitializeInstanceElements(result, ctorFunc)を実行する。
      7. NormalCompletion(result)を返す。
    2. ctorFuncCreateBuiltinFunction(defaultCtor, 0, className, « [[ConstructorKind]], [[SourceText]], [[PrivateMethods]], [[Fields]] », the current Realm Record, ctorParent)とする。
  15. そうでなければ、
    1. ctorInfoを、arguments protoおよびctorParentを伴うctorの ! DefineMethodとする。
    2. ctorFuncctorInfo.[[Closure]]とする。
    3. MakeClassConstructor(ctorFunc)を実行する。
    4. SetFunctionName(ctorFunc, className)を実行する。
  16. ctorFunc.[[SourceText]]sourceTextに設定する。
  17. MakeConstructor(ctorFunc, false, proto)を実行する。
  18. ClassHeritageが存在するなら、ctorFunc.[[ConstructorKind]]derivedに設定する。
  19. DefineMethodProperty(proto, "constructor", ctorFunc, false)を実行する。
  20. ClassBodyが存在しないなら、classElementsを新しい空のListとする。
  21. そうでなければ、classElementsClassBodyNonConstructorElementsとする。
  22. instancePrivateMethodsを新しい空のListとする。
  23. staticPrivateMethodsを新しい空のListとする。
  24. instanceFieldsを新しい空のListとする。
  25. staticElementsを新しい空のListとする。
  26. classElementsの各ClassElement classElementについて、以下を行う
    1. classElementIsStaticfalseなら、
      1. elementを、argument protoを伴うclassElementClassElementEvaluationCompletionとする。
    2. そうでなければ、
      1. elementを、argument ctorFuncを伴うclassElementClassElementEvaluationCompletionとする。
    3. elementabrupt completionなら、
      1. running execution contextのLexicalEnvironmentをenvRecordに設定する。
      2. running execution contextのPrivateEnvironmentをouterPrivateEnvに設定する。
      3. elementを返す。
    4. elementを ! element に設定する。
    5. elementPrivateElementなら、
      1. Assert: element.[[Kind]]methodまたはaccessorのいずれかである。
      2. classElementIsStaticfalseなら、containerinstancePrivateMethodsとする。
      3. そうでなければ、containerstaticPrivateMethodsとする。
      4. containerが、その[[Key]]element.[[Key]]であるPrivateElement existingElementを含むなら、
        1. Assert: element.[[Kind]]existingElement.[[Kind]]は両方ともaccessorである。
        2. element.[[Get]]undefinedなら、
          1. combinedPrivateElement { [[Key]]: element.[[Key]], [[Kind]]: accessor, [[Get]]: existingElement.[[Get]], [[Set]]: element.[[Set]] }とする。
        3. そうでなければ、
          1. combinedPrivateElement { [[Key]]: element.[[Key]], [[Kind]]: accessor, [[Get]]: element.[[Get]], [[Set]]: existingElement.[[Set]] }とする。
        4. container内のexistingElementcombinedで置き換える。
      5. そうでなければ、
        1. elementcontainerへappendする。
    6. そうでなく、elementClassFieldDefinition Recordなら、
      1. classElementIsStaticfalseなら、elementinstanceFieldsへappendする。
      2. そうでなければ、elementstaticElementsへappendする。
    7. そうでなく、elementClassStaticBlockDefinition Recordなら、
      1. elementstaticElementsへappendする。
  27. running execution contextのLexicalEnvironmentをenvRecordに設定する。
  28. classBindingundefinedでないなら、
    1. classEnv.InitializeBinding(classBinding, ctorFunc)を実行する。
  29. ctorFunc.[[PrivateMethods]]instancePrivateMethodsに設定する。
  30. ctorFunc.[[Fields]]instanceFieldsに設定する。
  31. staticPrivateMethodsの各PrivateElement methodについて、以下を行う
    1. PrivateMethodOrAccessorAdd(ctorFunc, method)を実行する。
  32. staticElementsの各要素elementRecordについて、以下を行う
    1. elementRecordClassFieldDefinition Recordなら、
      1. resultDefineField(ctorFunc, elementRecord)のCompletionとする。
    2. そうでなければ、
      1. Assert: elementRecordClassStaticBlockDefinition Recordである。
      2. resultCall(elementRecord.[[BodyFunction]], ctorFunc)のCompletionとする。
    3. resultabrupt completionなら、
      1. running execution contextのPrivateEnvironmentをouterPrivateEnvに設定する。
      2. resultを返す。
  33. running execution contextのPrivateEnvironmentをouterPrivateEnvに設定する。
  34. ctorFuncを返す。

15.7.15 Runtime Semantics: BindingClassDeclarationEvaluation

The syntax-directed operation BindingClassDeclarationEvaluation takes no arguments and returns either a normal completion containing a function object or an abrupt completion. It is defined piecewise over the following productions:

ClassDeclaration : class BindingIdentifier ClassTail
  1. classNameBindingIdentifierStringValueとする。
  2. sourceTextClassDeclarationによってmatchされたsource textとする。
  3. valueを、arguments classNameclassName、およびsourceTextを伴うClassTailの ? ClassDefinitionEvaluationとする。
  4. envRecordrunning execution contextのLexicalEnvironmentとする。
  5. InitializeBoundName(className, value, envRecord)を実行する。
  6. valueを返す。
ClassDeclaration : class ClassTail
  1. sourceTextClassDeclarationによってmatchされたsource textとする。
  2. arguments undefined"default"、およびsourceTextを伴うClassTailの ? ClassDefinitionEvaluationを返す。
Note

ClassDeclaration : class ClassTail ExportDeclarationの一部としてのみ出現し、そのbindingの確立はそのproductionに対するevaluation actionの一部として処理されます。16.2.3.7を参照してください。

15.7.16 Runtime Semantics: Evaluation

ClassDeclaration : class BindingIdentifier ClassTail
  1. this ClassDeclarationの ? BindingClassDeclarationEvaluationを実行する。
  2. emptyを返す。
Note

ClassDeclaration : class ClassTail ExportDeclarationの一部としてのみ出現し、直接評価されることは決してありません。

ClassExpression : class ClassTail
  1. sourceTextClassExpressionによってmatchされたsource textとする。
  2. arguments undefined、empty String、およびsourceTextを伴うClassTailの ? ClassDefinitionEvaluationを返す。
ClassExpression : class BindingIdentifier ClassTail
  1. classNameBindingIdentifierStringValueとする。
  2. sourceTextClassExpressionによってmatchされたsource textとする。
  3. arguments classNameclassName、およびsourceTextを伴うClassTailの ? ClassDefinitionEvaluationを返す。
ClassElementName : PrivateIdentifier
  1. privateIdentifierPrivateIdentifierStringValueとする。
  2. privateEnvRecordrunning execution contextのPrivateEnvironmentとする。
  3. namesprivateEnvRecord.[[Names]]とする。
  4. Assert: namesのちょうど1つの要素が、その[[Description]]privateIdentifierであるPrivate Nameである。
  5. privateNameを、names内の、その[[Description]]privateIdentifierであるPrivate Nameとする。
  6. privateNameを返す。
ClassStaticBlockStatementList : [empty]
  1. undefinedを返す。

15.8 Async Function Definitions

Syntax

AsyncFunctionDeclaration[Yield, Await, Default] : async [no LineTerminator here] function BindingIdentifier[?Yield, ?Await] ( FormalParameters[~Yield, +Await] ) { AsyncFunctionBody } [+Default] async [no LineTerminator here] function ( FormalParameters[~Yield, +Await] ) { AsyncFunctionBody } AsyncFunctionExpression : async [no LineTerminator here] function BindingIdentifier[~Yield, +Await]opt ( FormalParameters[~Yield, +Await] ) { AsyncFunctionBody } AsyncMethod[Yield, Await] : async [no LineTerminator here] ClassElementName[?Yield, ?Await] ( UniqueFormalParameters[~Yield, +Await] ) { AsyncFunctionBody } AsyncFunctionBody : FunctionBody[~Yield, +Await] AwaitExpression[Yield] : await UnaryExpression[?Yield, +Await] Note 1

[Await] parameterが存在するとき、awaitAwaitExpressionkeywordとしてparseされます。[Await] parameterは次のcontextsのtop levelに存在しますが、FunctionBodyなどのnonterminalsによっては一部のcontextsでそのparameterが存在しない場合があります:

Scriptがsyntactic goal symbolである場合、[Await] parameterが存在しないとき、awaitはidentifierとしてparseされる場合があります。これには次のcontextsが含まれます:

Note 2

YieldExpressionとは異なり、AwaitExpressionのoperandを省略することはSyntax Errorです。何かをawaitしなければなりません。

15.8.1 Static Semantics: Early Errors

AsyncMethod : async ClassElementName ( UniqueFormalParameters ) { AsyncFunctionBody } AsyncFunctionDeclaration : async function BindingIdentifier ( FormalParameters ) { AsyncFunctionBody } async function ( FormalParameters ) { AsyncFunctionBody } AsyncFunctionExpression : async function BindingIdentifieropt ( FormalParameters ) { AsyncFunctionBody }

15.8.2 Runtime Semantics: InstantiateAsyncFunctionObject

The syntax-directed operation InstantiateAsyncFunctionObject takes arguments envRecord (an Environment Record) and privateEnv (a PrivateEnvironment Record or null) and returns an ECMAScript function object. It is defined piecewise over the following productions:

AsyncFunctionDeclaration : async function BindingIdentifier ( FormalParameters ) { AsyncFunctionBody }
  1. nameBindingIdentifierStringValueとする。
  2. sourceTextAsyncFunctionDeclarationによってmatchされたsource textとする。
  3. closureOrdinaryFunctionCreate(%AsyncFunction.prototype%, sourceText, FormalParameters, AsyncFunctionBody, non-lexical-this, envRecord, privateEnv)とする。
  4. SetFunctionName(closure, name)を実行する。
  5. closureを返す。
AsyncFunctionDeclaration : async function ( FormalParameters ) { AsyncFunctionBody }
  1. sourceTextAsyncFunctionDeclarationによってmatchされたsource textとする。
  2. closureOrdinaryFunctionCreate(%AsyncFunction.prototype%, sourceText, FormalParameters, AsyncFunctionBody, non-lexical-this, envRecord, privateEnv)とする。
  3. SetFunctionName(closure, "default")を実行する。
  4. closureを返す。

15.8.3 Runtime Semantics: InstantiateAsyncFunctionExpression

The syntax-directed operation InstantiateAsyncFunctionExpression takes optional argument name (a property key or a Private Name) and returns an ECMAScript function object. It is defined piecewise over the following productions:

AsyncFunctionExpression : async function ( FormalParameters ) { AsyncFunctionBody }
  1. nameが存在しない場合、nameをempty Stringに設定する。
  2. envRecordrunning execution contextのLexicalEnvironmentとする。
  3. privateEnvrunning execution contextのPrivateEnvironmentとする。
  4. sourceTextAsyncFunctionExpressionによってmatchされたsource textとする。
  5. closureOrdinaryFunctionCreate(%AsyncFunction.prototype%, sourceText, FormalParameters, AsyncFunctionBody, non-lexical-this, envRecord, privateEnv)とする。
  6. SetFunctionName(closure, name)を実行する。
  7. closureを返す。
AsyncFunctionExpression : async function BindingIdentifier ( FormalParameters ) { AsyncFunctionBody }
  1. Assert: nameは存在しない。
  2. nameBindingIdentifierStringValueに設定する。
  3. outerEnvrunning execution contextのLexicalEnvironmentとする。
  4. funcEnvNewDeclarativeEnvironment(outerEnv)とする。
  5. funcEnv.CreateImmutableBinding(name, false)を実行する。
  6. privateEnvrunning execution contextのPrivateEnvironmentとする。
  7. sourceTextAsyncFunctionExpressionによってmatchされたsource textとする。
  8. closureOrdinaryFunctionCreate(%AsyncFunction.prototype%, sourceText, FormalParameters, AsyncFunctionBody, non-lexical-this, funcEnv, privateEnv)とする。
  9. SetFunctionName(closure, name)を実行する。
  10. funcEnv.InitializeBinding(name, closure)を実行する。
  11. closureを返す。
Note

AsyncFunctionExpression内のBindingIdentifierは、functionがそれ自身を再帰的に呼び出せるように、AsyncFunctionExpressionAsyncFunctionBody内部からreferenceできます。ただし、FunctionDeclarationの場合とは異なり、AsyncFunctionExpression内のBindingIdentifierは、AsyncFunctionExpressionを囲むscopeからreferenceできず、そのscopeに影響しません。

15.8.4 Runtime Semantics: EvaluateAsyncFunctionBody

The syntax-directed operation EvaluateAsyncFunctionBody takes arguments funcObj (an ECMAScript function object) and argList (a List of ECMAScript language values) and returns a return completion. It is defined piecewise over the following productions:

AsyncFunctionBody : FunctionBody
  1. promiseCapabilityを ! NewPromiseCapability(%Promise%) とする。
  2. completionCompletion(FunctionDeclarationInstantiation(funcObj, argList))とする。
  3. completionabrupt completionなら、
    1. Call(promiseCapability.[[Reject]], undefined, « completion.[[Value]] »)を実行する。
  4. そうでなければ、
    1. AsyncFunctionStart(promiseCapability, FunctionBody)を実行する。
  5. ReturnCompletion(promiseCapability.[[Promise]])を返す。

15.8.5 Runtime Semantics: Evaluation

AsyncFunctionExpression : async function BindingIdentifieropt ( FormalParameters ) { AsyncFunctionBody }
  1. AsyncFunctionExpressionInstantiateAsyncFunctionExpressionを返す。
UnaryExpression : CoverAwaitExpressionAndAwaitUsingDeclarationHead
  1. expr を、CoverAwaitExpressionAndAwaitUsingDeclarationHead によってカバーされる AwaitExpression とする。
  2. Return ? Evaluation of expr.
AwaitExpression : await UnaryExpression
  1. exprRefUnaryExpressionの ? Evaluationとする。
  2. valueを ? GetValue(exprRef) とする。
  3. Await(value)を返す。

15.9 Async Arrow Function Definitions

Syntax

AsyncArrowFunction[In, Yield, Await] : async [no LineTerminator here] AsyncArrowBindingIdentifier[?Yield] [no LineTerminator here] => AsyncConciseBody[?In] CoverCallExpressionAndAsyncArrowHead[?Yield, ?Await] [no LineTerminator here] => AsyncConciseBody[?In] AsyncConciseBody[In] : [lookahead ≠ {] ExpressionBody[?In, +Await] { AsyncFunctionBody } AsyncArrowBindingIdentifier[Yield] : BindingIdentifier[?Yield, +Await] CoverCallExpressionAndAsyncArrowHead[Yield, Await] : MemberExpression[?Yield, ?Await] Arguments[?Yield, ?Await]

Supplemental Syntax

production
AsyncArrowFunction : CoverCallExpressionAndAsyncArrowHead => AsyncConciseBody
のinstanceを処理するとき、CoverCallExpressionAndAsyncArrowHeadのinterpretationは次のgrammarを使用してrefineされます:

AsyncArrowHead : async [no LineTerminator here] ArrowFormalParameters[~Yield, +Await]

15.9.1 Static Semantics: Early Errors

AsyncArrowFunction : async AsyncArrowBindingIdentifier => AsyncConciseBody AsyncArrowFunction : CoverCallExpressionAndAsyncArrowHead => AsyncConciseBody

15.9.2 Static Semantics: AsyncConciseBodyContainsUseStrict

The syntax-directed operation AsyncConciseBodyContainsUseStrict takes no arguments and returns a Boolean. It is defined piecewise over the following productions:

AsyncConciseBody : ExpressionBody
  1. falseを返す。
AsyncConciseBody : { AsyncFunctionBody }
  1. AsyncFunctionBodyFunctionBodyContainsUseStrictを返す。

15.9.3 Runtime Semantics: EvaluateAsyncConciseBody

The syntax-directed operation EvaluateAsyncConciseBody takes arguments funcObj (an ECMAScript function object) and argList (a List of ECMAScript language values) and returns a return completion. It is defined piecewise over the following productions:

AsyncConciseBody : ExpressionBody
  1. promiseCapabilityを ! NewPromiseCapability(%Promise%) とする。
  2. completionCompletion(FunctionDeclarationInstantiation(funcObj, argList))とする。
  3. completionabrupt completionなら、
    1. Call(promiseCapability.[[Reject]], undefined, « completion.[[Value]] »)を実行する。
  4. そうでなければ、
    1. AsyncFunctionStart(promiseCapability, ExpressionBody)を実行する。
  5. ReturnCompletion(promiseCapability.[[Promise]])を返す。

15.9.4 Runtime Semantics: InstantiateAsyncArrowFunctionExpression

The syntax-directed operation InstantiateAsyncArrowFunctionExpression takes optional argument name (a property key or a Private Name) and returns an ECMAScript function object. It is defined piecewise over the following productions:

AsyncArrowFunction : async AsyncArrowBindingIdentifier => AsyncConciseBody
  1. nameが存在しない場合、nameをempty Stringに設定する。
  2. envRecordrunning execution contextのLexicalEnvironmentとする。
  3. privateEnvrunning execution contextのPrivateEnvironmentとする。
  4. sourceTextAsyncArrowFunctionによってmatchされたsource textとする。
  5. paramsAsyncArrowBindingIdentifierとする。
  6. closureOrdinaryFunctionCreate(%AsyncFunction.prototype%, sourceText, params, AsyncConciseBody, lexical-this, envRecord, privateEnv)とする。
  7. SetFunctionName(closure, name)を実行する。
  8. closureを返す。
AsyncArrowFunction : CoverCallExpressionAndAsyncArrowHead => AsyncConciseBody
  1. nameが存在しない場合、nameをempty Stringに設定する。
  2. envRecordrunning execution contextのLexicalEnvironmentとする。
  3. privateEnvrunning execution contextのPrivateEnvironmentとする。
  4. sourceTextAsyncArrowFunctionによってmatchされたsource textとする。
  5. headCoverCallExpressionAndAsyncArrowHeadによってcoverされるAsyncArrowHeadとする。
  6. paramsheadArrowFormalParametersとする。
  7. closureOrdinaryFunctionCreate(%AsyncFunction.prototype%, sourceText, params, AsyncConciseBody, lexical-this, envRecord, privateEnv)とする。
  8. SetFunctionName(closure, name)を実行する。
  9. closureを返す。

15.9.5 Runtime Semantics: Evaluation

AsyncArrowFunction : async AsyncArrowBindingIdentifier => AsyncConciseBody CoverCallExpressionAndAsyncArrowHead => AsyncConciseBody
  1. AsyncArrowFunctionInstantiateAsyncArrowFunctionExpressionを返す。

15.10 Tail Position Calls

15.10.1 Static Semantics: IsInTailPosition ( call )

The abstract operation IsInTailPosition takes argument call (a CallExpression Parse Node, a MemberExpression Parse Node, or an OptionalChain Parse Node) and returns a Boolean. It performs the following steps when called:

  1. IsStrict(call)がfalseなら、falseを返す。
  2. callFunctionBodyConciseBody、またはAsyncConciseBody内に含まれていないなら、falseを返す。
  3. bodycallを最も近く含むFunctionBodyConciseBody、またはAsyncConciseBodyとする。
  4. bodyGeneratorBodyFunctionBodyなら、falseを返す。
  5. bodyAsyncFunctionBodyFunctionBodyなら、falseを返す。
  6. bodyAsyncGeneratorBodyFunctionBodyなら、falseを返す。
  7. bodyAsyncConciseBodyなら、falseを返す。
  8. argument callを伴うbodyHasCallInTailPositionの結果を返す。
Note

Tail Position callsはstrict mode code内でのみ定義されます。これは、caller contextsのchainの観測を可能にする一般的なnon-standard language extension(10.2.4を参照)のためです。

15.10.2 Static Semantics: HasCallInTailPosition

The syntax-directed operation HasCallInTailPosition takes argument call (a CallExpression Parse Node, a MemberExpression Parse Node, or an OptionalChain Parse Node) and returns a Boolean.

Note 1

call は、ソーステキストの特定の範囲を表す Parse Node である。次のアルゴリズムが call を別の Parse Node と比較する場合、それらが同じソーステキストを表しているかどうかのテストである。

Note 2

呼び出し結果の return GetValue が直後に続く可能な末尾位置呼び出しも、可能な末尾位置呼び出しである。関数呼び出しは Reference Record を返すことができないため、そのような GetValue 操作は常に、実際の関数呼び出し結果と同じ値を返す。

Note 3

同じ BlockForStatementForInOfStatementFunctionBodyGeneratorBodyAsyncGeneratorBodyAsyncFunctionBody、または ClassStaticBlockBody 内で呼び出しに先行する using 宣言または await using 宣言は、その呼び出しが可能な末尾位置呼び出しになることを防ぐ。

It is defined piecewise over the following productions:

StatementList : StatementList StatementListItem
  1. has を、引数 call で派生した StatementListHasCallInTailPosition とする。
  2. hastrue である場合、true を返す。
  3. 派生した StatementListContainsUsingtrue である場合、false を返す。
  4. 引数 callStatementListItemHasCallInTailPosition を返す。
FunctionStatementList : [empty] StatementListItem : Declaration Statement : VariableStatement EmptyStatement ExpressionStatement ContinueStatement BreakStatement ThrowStatement DebuggerStatement Block : { } ReturnStatement : return ; LabelledItem : FunctionDeclaration ForInOfStatement : for ( LeftHandSideExpression of AssignmentExpression ) Statement for ( var ForBinding of AssignmentExpression ) Statement for ( ForDeclaration of AssignmentExpression ) Statement CaseBlock : { }
  1. falseを返す。
IfStatement : if ( Expression ) Statement else Statement
  1. hasを、argument callを伴う最初のStatementHasCallInTailPositionとする。
  2. hastrueなら、trueを返す。
  3. argument callを伴う2番目のStatementHasCallInTailPositionを返す。
IfStatement : if ( Expression ) Statement DoWhileStatement : do Statement while ( Expression ) ; WhileStatement : while ( Expression ) Statement ForStatement : for ( Expressionopt ; Expressionopt ; Expressionopt ) Statement for ( var VariableDeclarationList ; Expressionopt ; Expressionopt ) Statement for ( LexicalDeclaration Expressionopt ; Expressionopt ) Statement ForInOfStatement : for ( LeftHandSideExpression in Expression ) Statement for ( var ForBinding in Expression ) Statement for ( ForDeclaration in Expression ) Statement WithStatement : with ( Expression ) Statement
  1. argument callを伴うStatementHasCallInTailPositionを返す。
LabelledStatement : LabelIdentifier : LabelledItem
  1. argument callを伴うLabelledItemHasCallInTailPositionを返す。
ReturnStatement : return Expression ;
  1. argument callを伴うExpressionHasCallInTailPositionを返す。
SwitchStatement : switch ( Expression ) CaseBlock
  1. argument callを伴うCaseBlockHasCallInTailPositionを返す。
CaseBlock : { CaseClausesopt DefaultClause CaseClausesopt }
  1. hasfalseとする。
  2. 最初のCaseClausesが存在するなら、hasを、argument callを伴う最初のCaseClausesHasCallInTailPositionに設定する。
  3. hastrueなら、trueを返す。
  4. hasを、argument callを伴うDefaultClauseHasCallInTailPositionに設定する。
  5. hastrueなら、trueを返す。
  6. 2番目のCaseClausesが存在するなら、hasを、argument callを伴う2番目のCaseClausesHasCallInTailPositionに設定する。
  7. hasを返す。
CaseClauses : CaseClauses CaseClause
  1. hasを、argument callを伴うCaseClausesHasCallInTailPositionとする。
  2. hastrueなら、trueを返す。
  3. argument callを伴うCaseClauseHasCallInTailPositionを返す。
CaseClause : case Expression : StatementListopt DefaultClause : default : StatementListopt
  1. StatementListが存在するなら、argument callを伴うStatementListHasCallInTailPositionを返す。
  2. falseを返す。
TryStatement : try Block Catch
  1. argument callを伴うCatchHasCallInTailPositionを返す。
TryStatement : try Block Finally try Block Catch Finally
  1. argument callを伴うFinallyHasCallInTailPositionを返す。
Catch : catch ( CatchParameter ) Block
  1. argument callを伴うBlockHasCallInTailPositionを返す。
AssignmentExpression : YieldExpression ArrowFunction AsyncArrowFunction LeftHandSideExpression = AssignmentExpression LeftHandSideExpression AssignmentOperator AssignmentExpression LeftHandSideExpression &&= AssignmentExpression LeftHandSideExpression ||= AssignmentExpression LeftHandSideExpression ??= AssignmentExpression BitwiseANDExpression : BitwiseANDExpression & EqualityExpression BitwiseXORExpression : BitwiseXORExpression ^ BitwiseANDExpression BitwiseORExpression : BitwiseORExpression | BitwiseXORExpression EqualityExpression : EqualityExpression == RelationalExpression EqualityExpression != RelationalExpression EqualityExpression === RelationalExpression EqualityExpression !== RelationalExpression RelationalExpression : RelationalExpression < ShiftExpression RelationalExpression > ShiftExpression RelationalExpression <= ShiftExpression RelationalExpression >= ShiftExpression RelationalExpression instanceof ShiftExpression RelationalExpression in ShiftExpression PrivateIdentifier in ShiftExpression ShiftExpression : ShiftExpression << AdditiveExpression ShiftExpression >> AdditiveExpression ShiftExpression >>> AdditiveExpression AdditiveExpression : AdditiveExpression + MultiplicativeExpression AdditiveExpression - MultiplicativeExpression MultiplicativeExpression : MultiplicativeExpression MultiplicativeOperator ExponentiationExpression ExponentiationExpression : UpdateExpression ** ExponentiationExpression UpdateExpression : LeftHandSideExpression ++ LeftHandSideExpression -- ++ UnaryExpression -- UnaryExpression UnaryExpression : delete UnaryExpression void UnaryExpression typeof UnaryExpression + UnaryExpression - UnaryExpression ~ UnaryExpression ! UnaryExpression CoverAwaitExpressionAndAwaitUsingDeclarationHead CallExpression : SuperCall ImportCall CallExpression [ Expression ] CallExpression . IdentifierName CallExpression . PrivateIdentifier NewExpression : new NewExpression MemberExpression : MemberExpression [ Expression ] MemberExpression . IdentifierName SuperProperty MetaProperty new MemberExpression Arguments MemberExpression . PrivateIdentifier PrimaryExpression : this IdentifierReference Literal ArrayLiteral ObjectLiteral FunctionExpression ClassExpression GeneratorExpression AsyncFunctionExpression AsyncGeneratorExpression RegularExpressionLiteral TemplateLiteral
  1. falseを返す。
Expression : AssignmentExpression Expression , AssignmentExpression
  1. argument callを伴うAssignmentExpressionHasCallInTailPositionを返す。
ConditionalExpression : ShortCircuitExpression ? AssignmentExpression : AssignmentExpression
  1. hasを、argument callを伴う最初のAssignmentExpressionHasCallInTailPositionとする。
  2. hastrueなら、trueを返す。
  3. argument callを伴う2番目のAssignmentExpressionHasCallInTailPositionを返す。
LogicalANDExpression : LogicalANDExpression && BitwiseORExpression
  1. argument callを伴うBitwiseORExpressionHasCallInTailPositionを返す。
LogicalORExpression : LogicalORExpression || LogicalANDExpression
  1. argument callを伴うLogicalANDExpressionHasCallInTailPositionを返す。
CoalesceExpression : CoalesceExpressionHead ?? BitwiseORExpression
  1. argument callを伴うBitwiseORExpressionHasCallInTailPositionを返す。
CallExpression : CoverCallExpressionAndAsyncArrowHead CallExpression Arguments CallExpression TemplateLiteral
  1. this CallExpressioncallなら、trueを返す。
  2. falseを返す。
OptionalExpression : MemberExpression OptionalChain CallExpression OptionalChain OptionalExpression OptionalChain
  1. argument callを伴うOptionalChainHasCallInTailPositionを返す。
OptionalChain : ?. [ Expression ] ?. IdentifierName ?. PrivateIdentifier OptionalChain [ Expression ] OptionalChain . IdentifierName OptionalChain . PrivateIdentifier
  1. falseを返す。
OptionalChain : ?. Arguments OptionalChain Arguments
  1. this OptionalChaincallなら、trueを返す。
  2. falseを返す。
MemberExpression : MemberExpression TemplateLiteral
  1. this MemberExpressioncallなら、trueを返す。
  2. falseを返す。
PrimaryExpression : CoverParenthesizedExpressionAndArrowParameterList
  1. exprCoverParenthesizedExpressionAndArrowParameterListによってcoverされるParenthesizedExpressionとする。
  2. argument callを伴うexprHasCallInTailPositionを返す。
ParenthesizedExpression : ( Expression )
  1. argument callを伴うExpressionHasCallInTailPositionを返す。

15.10.3 PrepareForTailCall ( )

The abstract operation PrepareForTailCall takes no arguments and returns unused. It performs the following steps when called:

  1. Assert: current execution contextは、以後いかなるECMAScript codeまたはbuilt-in functionsのevaluationにも使用されない。このabstract operationの呼び出しに続くCallの呼び出しは、そのようなevaluationを実行する前に新しいexecution contextを作成してpushする。
  2. current execution contextに関連付けられたすべてのresourcesを破棄する。
  3. unusedを返す。

tail position callは、target functionを呼び出す前に、現在実行中のfunction execution contextに関連付けられたtransient internal resourcesを解放するか、target functionをsupportするためにそれらのresourcesを再利用しなければなりません。

Note

例えば、tail position callは、target functionのactivation recordのsizeがcalling functionのactivation recordのsizeを超える分だけ、implementationのactivation record stackを増加させるべきです。target functionのactivation recordの方が小さい場合、stackのtotal sizeは減少するべきです。

16 ECMAScript Language: Scripts and Modules

16.1 Scripts

Syntax

Script : ScriptBodyopt ScriptBody : StatementList[~Yield, ~Await, ~Return]

16.1.1 Static Semantics: Early Errors

Script : ScriptBody ScriptBody : StatementList

16.1.2 Static Semantics: ScriptIsStrict

The syntax-directed operation ScriptIsStrict takes no arguments and returns a Boolean. It is defined piecewise over the following productions:

Script : ScriptBodyopt
  1. ScriptBodyが存在し、かつScriptBodyDirective PrologueUse Strict Directiveを含むなら、trueを返す。
  2. falseを返す。

16.1.3 Runtime Semantics: Evaluation

Script : [empty]
  1. undefinedを返す。

16.1.4 Script Records

Script Recordは、評価されているscriptに関する情報をencapsulateします。各script recordはTable 35に列挙されたfieldsを含みます。

Table 35: Script Record Fields
Field Name Value Type Meaning
[[Realm]] a Realm Record このscriptが作成されたrealm
[[ECMAScriptCode]] a Script Parse Node このscriptのsource textをparseした結果。
[[LoadedModules]] a List of LoadedModuleRequest Records このscriptによってimportされたspecifier stringsからresolved Module Recordへのmap。このlistは、ModuleRequestsEqual(r1, r2)がtrueであるような2つの異なるRecords r1およびr2を含みません。
[[HostDefined]] anything (default value is empty) scriptに追加情報を関連付ける必要があるhost environmentsによる使用のために予約されたfield。

16.1.5 ParseScript ( sourceText, realm, hostDefined )

The abstract operation ParseScript takes arguments sourceText (a String or a sequence of Unicode code points), realm (a Realm Record), and hostDefined (anything) and returns a Script Record or a non-empty List of SyntaxError objects. sourceTextScriptとしてparseした結果に基づいてScript Recordを作成します。 It performs the following steps when called:

  1. scriptParseText(sourceText, Script)とする。
  2. scriptがerrorsのListなら、scriptを返す。
  3. Script Record { [[Realm]]: realm, [[ECMAScriptCode]]: script, [[LoadedModules]]: « », [[HostDefined]]: hostDefined }を返す。
Note

implementationは、そのscript source textに対するParseScriptのevaluationより前に、script source textをparseし、それをEarly Error conditionsについてanalyseしてもよいです。ただし、errorsのreportingは、この仕様が実際にそのsource textに対してParseScriptを実行する時点までdeferされなければなりません。

16.1.6 ScriptEvaluation ( scriptRecord )

The abstract operation ScriptEvaluation takes argument scriptRecord (a Script Record) and returns either a normal completion containing an ECMAScript language value or an abrupt completion. It performs the following steps when called:

  1. globalEnvscriptRecord.[[Realm]].[[GlobalEnv]]とする。
  2. scriptContextを新しいECMAScript code execution contextとする。
  3. scriptContextのFunctionをnullに設定する。
  4. scriptContextRealmscriptRecord.[[Realm]]に設定する。
  5. scriptContextのScriptOrModuleをscriptRecordに設定する。
  6. scriptContextのVariableEnvironmentをglobalEnvに設定する。
  7. scriptContextのLexicalEnvironmentをglobalEnvに設定する。
  8. scriptContextのPrivateEnvironmentをnullに設定する。
  9. running execution contextをsuspendする。
  10. scriptContextexecution context stackへpushする;scriptContextは現在running execution contextである。
  11. scriptNodescriptRecord.[[ECMAScriptCode]]とする。
  12. resultCompletion(GlobalDeclarationInstantiation(scriptNode, globalEnv))とする。
  13. resultnormal completionなら、
    1. resultCompletion(scriptNodeEvaluation)に設定する。
    2. resultnormal completionであり、かつresult.[[Value]]emptyなら、
      1. resultNormalCompletion(undefined)に設定する。
  14. scriptContextをsuspendし、それをexecution context stackからremoveする。
  15. Assert: execution context stackは空でない。
  16. execution context stackのtopにあるcontextをrunning execution contextとしてresumeする。
  17. resultを返す。

16.1.7 GlobalDeclarationInstantiation ( script, envRecord )

The abstract operation GlobalDeclarationInstantiation takes arguments script (a Script Parse Node) and envRecord (a Global Environment Record) and returns either a normal completion containing unused or a throw completion. scriptexecution contextが確立される対象のScriptです。envRecordはbindingsが作成されるglobal environmentです。

Note 1

scriptsを評価するためにexecution contextが確立されるとき、declarationsはcurrent global environment内でinstantiatedされます。code内でdeclaredされた各global bindingがinstantiatedされます。

これは呼び出されたとき、次のstepsを実行します:

  1. scriptLexicallyDeclaredNameslexicalNamesとする。
  2. scriptVarDeclaredNamesvariableNamesとする。
  3. lexicalNamesの各要素nameについて、次を行う。
    1. HasLexicalDeclaration(envRecord, name)がtrueである場合、SyntaxError例外を投げる。
    2. HasRestrictedGlobalProperty(envRecord, name)をhasRestrictedGlobalとする。
    3. NOTE: グローバルvarおよびfunction束縛(非strict direct evalによって導入されるものを除く)は構成不可であり、したがって制限されたグローバルプロパティである。
    4. hasRestrictedGlobaltrueである場合、SyntaxError例外を投げる。
  4. variableNamesの各要素nameについて、次を行う。
    1. HasLexicalDeclaration(envRecord, name)がtrueである場合、SyntaxError例外を投げる。
  5. scriptVarScopedDeclarationsvariableDeclsとする。
  6. funcsToInitializeを新しい空のListとする。
  7. declaredFuncNamesを新しい空のListとする。
  8. variableDeclsの各要素variableDeclについて、Listの逆順で、次を行う。
    1. variableDeclVariableDeclarationForBinding、またはBindingIdentifierのいずれでもない場合、
      1. Assert: variableDeclは、FunctionDeclarationGeneratorDeclarationAsyncFunctionDeclaration、またはAsyncGeneratorDeclarationのいずれかである。
      2. NOTE: 同じ名前に対して複数の関数宣言がある場合、最後の宣言が使用される。
      3. variableDeclBoundNamesの唯一の要素をfuncNameとする。
      4. declaredFuncNamesfuncNameを含まない場合、
        1. CanDeclareGlobalFunction(envRecord, funcName)をfuncDefinableとする。
        2. funcDefinablefalseである場合、TypeError例外を投げる。
        3. funcNamedeclaredFuncNamesに追加する。
        4. variableDeclfuncsToInitializeの最初の要素として挿入する。
  9. declaredVariableNamesを新しい空のListとする。
  10. variableDeclsの各要素variableDeclについて、次を行う。
    1. variableDeclVariableDeclarationForBinding、またはBindingIdentifierのいずれかである場合、
      1. variableDeclBoundNamesの各String nameについて、次を行う。
        1. declaredFuncNamesnameを含まない場合、
          1. CanDeclareGlobalVar(envRecord, name)をvariableDefinableとする。
          2. variableDefinablefalseである場合、TypeError例外を投げる。
          3. declaredVariableNamesnameを含まない場合、
            1. namedeclaredVariableNamesに追加する。
  11. NOTE: グローバルオブジェクトがordinary objectである場合、このアルゴリズムステップ以降で異常終了は発生しない。しかし、グローバルオブジェクトがProxy exotic objectである場合、以下のステップの一部で異常終了を引き起こす挙動を示すことがある。
  12. ホストがWebブラウザである、またはその他の形でBlock-Level Function Declarations Web Legacy Compatibility Semanticsをサポートする場合、
    1. scriptScriptIsStrictstrictとする。
    2. strictfalseである場合、
      1. declaredFuncNamesdeclaredVariableNameslist-concatenationdeclaredFuncOrVariableNamesとする。
      2. script Contains xtrueであるような任意のBlockCaseClause、またはDefaultClause xStatementListに直接含まれる各FunctionDeclaration funcDeclについて、次を行う。
        1. funcDeclBindingIdentifierStringValuefuncNameとする。
        2. FunctionDeclaration funcDeclを、funcNameBindingIdentifierとして持つVariableStatementに置き換えても、scriptに対してEarly Errorsが発生しない場合、
          1. HasLexicalDeclaration(envRecord, funcName)がfalseである場合、
            1. CanDeclareGlobalVar(envRecord, funcName)をfuncDefinableとする。
            2. funcDefinabletrueである場合、
              1. NOTE: funcNameに対するvar束縛は、それがVarDeclaredNameでも別のFunctionDeclarationの名前でもない場合にのみ、ここでインスタンス化される。
              2. declaredFuncOrVariableNamesfuncNameを含まない場合、
                1. CreateGlobalVarBinding(envRecord, funcName, false)を実行する。
                2. funcNamedeclaredFuncOrVariableNamesに追加する。
              3. FunctionDeclaration funcDeclが評価されるとき、15.2.6で提供されるFunctionDeclaration Evaluationアルゴリズムの代わりに、次のステップを実行する。
                1. 実行中の実行コンテキストのVariableEnvironmentをglobalEnvとする。
                2. 実行中の実行コンテキストのLexicalEnvironmentをblockEnvとする。
                3. blockEnv.GetBindingValue(funcName, false)をfuncObjとする。
                4. globalEnv.SetMutableBinding(funcName, funcObj, false)を実行する。
                5. unusedを返す。
  13. scriptLexicallyScopedDeclarationslexicalDeclsとする。
  14. privateEnvnullとする。
  15. lexicalDeclsの各要素lexicalDeclについて、次を行う。
    1. NOTE: Lexically declared nameは、ここでインスタンス化されるだけで、初期化されない。
    2. lexicalDeclBoundNamesの各要素nameについて、次を行う。
      1. lexicalDeclIsConstantDeclarationtrueである場合、
        1. envRecord.CreateImmutableBinding(name, true)を実行する。
      2. そうでなければ、
        1. envRecord.CreateMutableBinding(name, false)を実行する。
  16. funcsToInitializeの各Parse Node funcDeclについて、次を行う。
    1. funcDeclBoundNamesの唯一の要素をfuncNameとする。
    2. envRecordおよびprivateEnvを引数として、funcDeclInstantiateFunctionObjectfuncObjとする。
    3. CreateGlobalFunctionBinding(envRecord, funcName, funcObj, false)を実行する。
  17. declaredVariableNamesの各String variableNameについて、次を行う。
    1. CreateGlobalVarBinding(envRecord, variableName, false)を実行する。
  18. unusedを返す。
Note 2

16.1.1で指定されるearly errorsは、単一のScript内に含まれるdeclarationについて、function/var declarationsとlet/const/class declarationsの間のname conflicts、ならびにlet/const/class bindingsのredeclarationを防止します。ただし、複数のScriptにまたがるそのようなconflictsおよびredeclarationsは、GlobalDeclarationInstantiation中にruntime errorsとして検出されます。そのようなerrorsが検出された場合、そのscriptに対するbindingsは一切instantiatedされません。ただし、global objectProxy exotic objectsを使用して定義されている場合、conflicting declarationsに対するruntime testsは信頼できないことがあり、その結果としてabrupt completionが発生し、一部のglobal declarationsがinstantiatedされない場合があります。この場合、Scriptのcodeは評価されません。

explicit varまたはfunction declarationsとは異なり、global object上に直接作成されるpropertiesは、let/const/class declarationsによってshadowされ得るglobal bindingsをもたらします。

16.2 Modules

Syntax

Module : ModuleBodyopt ModuleBody : ModuleItemList ModuleItemList : ModuleItem ModuleItemList ModuleItem ModuleItem : ImportDeclaration ExportDeclaration StatementListItem[~Yield, +Await, ~Return] ModuleExportName : IdentifierName StringLiteral

16.2.1 Module Semantics

16.2.1.1 Static Semantics: Early Errors

ModuleBody : ModuleItemList Note

重複ExportedNames ruleは、ModuleBody内の複数のexport default ExportDeclaration itemsがSyntax Errorであることを意味します。conflictingまたはduplicate declarationsに関係する追加のerror conditionsは、Moduleのevaluationより前のmodule linking中にcheckされます。そのようなerrorsが検出された場合、Moduleは評価されません。

ModuleExportName : StringLiteral

16.2.1.2 Static Semantics: ImportedLocalNames ( importEntries )

The abstract operation ImportedLocalNames takes argument importEntries (a List of ImportEntry Records) and returns a List of Strings. importEntriesによって定義されるすべてのlocal name bindingsのListを作成します。 It performs the following steps when called:

  1. localNamesを新しい空のListとする。
  2. importEntriesの各ImportEntry Record importEntryについて、次を行う。
    1. importEntry.[[LocalName]]localNamesに追加する。
  3. localNamesを返す。

16.2.1.3 ModuleRequest Records

ModuleRequest Recordは、与えられたimport attributesでmoduleをimportするrequestを表します。これは次のfieldsから構成されます:

Table 36: ModuleRequest Record Fields
Field Name Value Type Meaning
[[Specifier]] a String module specifier
[[Attributes]] a List of ImportAttribute Records import attributes

LoadedModuleRequest Recordは、moduleをimportするrequestを、その結果として得られるModule Recordとともに表します。これは、Table 36で定義された同じfieldsに、[[Module]]を追加したものから構成されます:

Table 37: LoadedModuleRequest Record Fields
Field Name Value Type Meaning
[[Specifier]] a String module specifier
[[Attributes]] a List of ImportAttribute Records import attributes
[[Module]] a Module Record このmodule requestに対応するloaded module

ImportAttribute Recordは次のfieldsから構成されます:

Table 38: ImportAttribute Record Fields
Field Name Value Type Meaning
[[Key]] a String attribute key
[[Value]] a String attribute value

16.2.1.3.1 ModuleRequestsEqual ( x, y )

The abstract operation ModuleRequestsEqual takes arguments x (a ModuleRequest Record or a LoadedModuleRequest Record) and y (a ModuleRequest Record or a LoadedModuleRequest Record) and returns a Boolean. It performs the following steps when called:

  1. x.[[Specifier]]y.[[Specifier]]でないなら、falseを返す。
  2. xAttrsx.[[Attributes]]とする。
  3. yAttrsy.[[Attributes]]とする。
  4. xAttrsCountxAttrs内の要素数とする。
  5. yAttrsCountyAttrs内の要素数とする。
  6. xAttrsCountyAttrsCountなら、falseを返す。
  7. xAttrsの各ImportAttribute Record xAttrについて、以下を行う
    1. yAttrsが、xAttr.[[Key]]yAttr.[[Key]]であり、かつxAttr.[[Value]]yAttr.[[Value]]であるようなImportAttribute Record yAttrを含まないなら、falseを返す。
  8. trueを返す。

16.2.1.4 Static Semantics: ModuleRequests

The syntax-directed operation ModuleRequests takes no arguments and returns a List of ModuleRequest Records. It is defined piecewise over the following productions:

Module : [empty]
  1. 新しい空のListを返す。
ModuleItemList : ModuleItem
  1. ModuleItemModuleRequestsを返す。
ModuleItemList : ModuleItemList ModuleItem
  1. ModuleItemListModuleRequestsrequestsとする。
  2. ModuleItemModuleRequestsadditionalRequestsとする。
  3. additionalRequestsの各ModuleRequest Record moduleRequestについて、次を行う。
    1. ModuleRequestsEqual(moduleRequest, otherModuleRequest)がtrueであるようなModuleRequest Record otherModuleRequestrequestsが含まない場合、
      1. moduleRequestrequestsに追加する。
  4. requestsを返す。
ModuleItem : StatementListItem
  1. 新しい空のListを返す。
ImportDeclaration : import ImportClause FromClause ;
  1. specifierFromClauseSVとする。
  2. 唯一の要素がModuleRequest Record { [[Specifier]]: specifier, [[Attributes]]: « » }であるListを返す。
ImportDeclaration : import ImportClause FromClause WithClause ;
  1. specifierFromClauseSVとする。
  2. attrsWithClauseWithClauseToAttributesとする。
  3. 唯一の要素がModuleRequest Record { [[Specifier]]: specifier, [[Attributes]]: attrs }であるListを返す。
ImportDeclaration : import ModuleSpecifier ;
  1. specifierModuleSpecifierSVとする。
  2. 唯一の要素がModuleRequest Record { [[Specifier]]: specifier, [[Attributes]]: « » }であるListを返す。
ImportDeclaration : import ModuleSpecifier WithClause ;
  1. specifierModuleSpecifierSVとする。
  2. attrsWithClauseWithClauseToAttributesとする。
  3. 唯一の要素がModuleRequest Record { [[Specifier]]: specifier, [[Attributes]]: attrs }であるListを返す。
ExportDeclaration : export ExportFromClause FromClause ;
  1. specifierFromClauseSVとする。
  2. 唯一の要素がModuleRequest Record { [[Specifier]]: specifier, [[Attributes]]: « » }であるListを返す。
ExportDeclaration : export ExportFromClause FromClause WithClause ;
  1. specifierFromClauseSVとする。
  2. attrsWithClauseWithClauseToAttributesとする。
  3. 唯一の要素がModuleRequest Record { [[Specifier]]: specifier, [[Attributes]]: attrs }であるListを返す。
ExportDeclaration : export NamedExports ; export VariableStatement export Declaration export default HoistableDeclaration export default ClassDeclaration export default AssignmentExpression ;
  1. 新しい空のListを返す。

16.2.1.5 Abstract Module Records

Module Recordは、単一moduleのimportsおよびexportsに関するstructural informationをencapsulateします。この情報は、connected modulesのsetsのimportsおよびexportsをlinkするために使用されます。Module Recordには、moduleを評価するときにのみ使用される4つのfieldsが含まれます。

specification purposesのため、Module Record値はRecord specification typeの値であり、Module Recordがabstract classであり、abstractおよびconcrete subclassesの両方を持つsimple object-oriented hierarchy内に存在するものとして考えることができます。この仕様は、Cyclic Module Recordという名前のabstract subclassと、そのconcrete subclassであるSource Text Module Recordを定義します。他の仕様およびimplementationsは、それらが定義するalternative module definition facilitiesに対応する追加のModule Record subclassesを定義してもよいです。

Module RecordはTable 39に列挙されたfieldsを定義します。すべてのModule Definition subclassesは少なくともそれらのfieldsを含みます。Module Recordはまた、Table 40内のabstract method listを定義します。すべてのModule definition subclassesは、これらのabstract methodsのconcrete implementationsを提供しなければなりません。

Table 39: Module Record Fields
Field Name Value Type Meaning
[[Realm]] a Realm Record このmoduleが作成されたRealm
[[Environment]] a Module Environment Record or empty このmoduleに対するtop level bindingsを含むEnvironment Record。このfieldはmoduleがlinkedされたときに設定されます。
[[Namespace]] an Object or empty このmoduleに対して作成されている場合のModule Namespace Object(28.3)。
[[HostDefined]] anything (default value is undefined) moduleに追加情報を関連付ける必要があるhost environmentsによる使用のために予約されたfield。
Table 40: Abstract Methods of Module Records
Method Purpose Definitions
LoadRequestedModules ( [ hostDefined ] )

The abstract method LoadRequestedModules takes optional argument hostDefined (anything) and returns a Promise.

そのすべてのdependenciesを再帰的にloadすることで、linkingのためにmoduleを準備します。

この仕様内では、これは次のtypes内にdefinitionsを持ちます;hostsは独自のdefinitionsを持つ追加のtypesを提供してもよいです:
GetExportedNames ( [ exportStarSet ] )

The abstract method GetExportedNames takes optional argument exportStarSet (a List of Source Text Module Records) and returns a List of Strings.

このmoduleから直接または間接的にexportされるすべてのnamesのlistを返します。

このmethodをinvokeする前に、LoadRequestedModulesはsuccessfullyに完了していなければなりません。

この仕様内では、これは次のtypes内にdefinitionsを持ちます;hostsは独自のdefinitionsを持つ追加のtypesを提供してもよいです:
ResolveExport ( exportName [ , resolveSet ] )

The abstract method ResolveExport takes argument exportName (a String) and optional argument resolveSet (a List of Records with fields [[Module]] (a Module Record) and [[ExportName]] (a String)) and returns a ResolvedBinding Record, null, or ambiguous.

このmoduleによってexportされるnameのbindingを返します。Bindingsは、{ [[Module]]: Module Record, [[BindingName]]: String | namespace }という形式のResolvedBinding Recordによって表されます。exportがどのmoduleにもdirect bindingを持たないModule Namespace Objectである場合、[[BindingName]]namespaceに設定されます。nameをresolveできない場合はnullを返し、複数のbindingsが見つかった場合はambiguousを返します。

このoperationが特定のexportNameresolveSet pairをargumentsとして呼び出されるたびに、同じresultを返さなければなりません。

このmethodをinvokeする前に、LoadRequestedModulesはsuccessfullyに完了していなければなりません。

この仕様内では、これは次のtypes内にdefinitionsを持ちます;hostsは独自のdefinitionsを持つ追加のtypesを提供してもよいです:
Evaluate ( )

The abstract method Evaluate takes no arguments and returns a Promise.

このmoduleおよびそのdependenciesのevaluationに対するpromiseを返します。このpromiseは、successful evaluation時またはすでにsuccessfullyに評価済みである場合にresolveされ、evaluation error時またはすでにunsuccessfullyに評価済みである場合にrejectされます。promiseがrejectedされる場合、hostsはpromise rejectionをhandleし、evaluation errorをrethrowすることが期待されます。このmoduleがCyclic Module Recordでない限り、返されるpromiseはすでにsettledでなければなりません。

このmethodをinvokeする前に、Linkはsuccessfullyに完了していなければなりません。

この仕様内では、これは次のtypes内にdefinitionsを持ちます;hostsは独自のdefinitionsを持つ追加のtypesを提供してもよいです:

16.2.1.5.1 EvaluateModuleSync ( module )

The abstract operation EvaluateModuleSync takes argument module (a Module Record) and returns either a normal completion containing unused or a throw completion. callerがmoduleのevaluationがすでにsettledされたpromiseを返すことをguaranteeする場合に、moduleをsynchronouslyに評価します。 It performs the following steps when called:

  1. Assert: moduleCyclic Module Recordでない。
  2. promisemodule.Evaluate()とする。
  3. Assert: promise.[[PromiseState]]fulfilledまたはrejectedのいずれかである。
  4. promise.[[PromiseState]]rejectedなら、
    1. promise.[[PromiseIsHandled]]falseなら、HostPromiseRejectionTracker(promise, "handle")を実行する。
    2. promise.[[PromiseIsHandled]]trueに設定する。
    3. promise.[[PromiseResult]]をThrowする。
  5. unusedを返す。

16.2.1.6 Cyclic Module Records

Cyclic Module Recordは、Cyclic Module Record typeのsubclassesである他のmodulesとdependency cyclesに参加できるmoduleに関する情報を表すために使用されます。Cyclic Module Record typeのsubclassesでないModule Recordsは、Source Text Module Recordsとのdependency cyclesに参加してはなりません。

Table 39で定義されるfieldsに加えて、Cyclic Module RecordsTable 41に列挙された追加のfieldsを持ちます

Table 41: Additional Fields of Cyclic Module Records
Field Name Value Type Meaning
[[Status]] new, unlinked, linking, linked, evaluating, evaluating-async, or evaluated Initially new。moduleがそのlifecycleを通じて進むにつれて、unlinkedlinkinglinkedevaluating、場合によりevaluating-asyncevaluatedへ(この順に)transitionします。evaluating-asyncは、このmoduleがそのasynchronous dependenciesのcompletion時にexecuteするためにqueuedされていること、または[[HasTLA]] fieldがtrueであり、すでにexecutedされてtop-level completionをpendingしているmoduleであることを示します。
[[EvaluationError]] a throw completion or empty evaluation中に発生したexceptionを表すthrow completion。exceptionが発生しなかった場合、または[[Status]]evaluatedでない場合はempty
[[DFSAncestorIndex]] an integer or empty LinkおよびEvaluate中にのみ使用されるauxiliary field。[[Status]]linkingまたはevaluatingのいずれかである場合、これはmoduleのdepth-first traversal indexまたは同じstrongly connected component内の“earlier” moduleのそれです。
[[RequestedModules]] a List of ModuleRequest Records このmodule内のimportsに関連付けられたModuleRequest RecordsList。このListはimportsのsource text occurrence orderです。
[[LoadedModules]] a List of LoadedModuleRequest Records このrecordによって表されるmoduleが、relative import attributesとともにmoduleのimportationをrequestするために使用したspecifier stringsから、resolved Module Recordへのmap。このlistは、ModuleRequestsEqual(r1, r2)がtrueであるような2つの異なるRecords r1およびr2を含みません。
[[CycleRoot]] a Cyclic Module Record or empty cycleの最初にvisitedされたmodule、strongly connected componentのroot DFS ancestor。cycle内にないmoduleについては、これはmodule自身になります。Evaluateが完了すると、moduleの[[DFSAncestorIndex]]はその[[CycleRoot]]のdepth-first traversal indexです。
[[HasTLA]] a Boolean このmoduleが個別にasynchronousであるかどうか(例えば、top-level awaitを含むSource Text Module Recordである場合)。asynchronous dependencyを持つことは、このfieldがtrueであることを意味しません。このfieldはmoduleがparsedされた後に変更されてはなりません。
[[AsyncEvaluationOrder]] unset, an integer, or done このfieldはinitiallyにunsetに設定され、完全にsynchronousなmodulesについてはunsetのままです。自身がasynchronousであるかasynchronous dependencyを持つmodulesについては、16.2.1.6.1.3.4によってpending modulesのexecutionがqueuedされるorderを決定するintegerに設定されます。pending moduleがsuccessfullyにexecutedされると、このfieldはdoneに設定されます。
[[TopLevelCapability]] a PromiseCapability Record or empty このmoduleが何らかのcycleの[[CycleRoot]]であり、そのcycle内の何らかのmoduleに対してEvaluate()が呼び出された場合、このfieldはそのevaluation全体に対するPromiseCapability Recordを含みます。これはEvaluate() abstract methodから返されるPromise objectをsettleするために使用されます。このfieldは、そのmoduleのdependenciesについては、それらのdependenciesのいずれかに対してtop-level Evaluate()が開始されていない限りemptyになります。
[[AsyncParentModules]] a List of Cyclic Module Records このmoduleまたはdependencyが[[HasTLA]] trueを持ち、executionが進行中である場合、これはtop-level execution jobに対するこのmoduleのparent importersをtrackします。これらのparent modulesは、このmoduleがsuccessfullyにexecutionを完了する前にはexecuteを開始しません。
[[PendingAsyncDependencies]] an integer or empty このmoduleがasynchronous dependenciesを持つ場合、これはこのmoduleのためにexecuteがremainingしているasynchronous dependency modulesの数をtrackします。asynchronous dependenciesを持つmoduleは、このfieldが0に到達し、execution errorsがない場合にexecutedされます。

Table 40で定義されるmethodsに加えて、Cyclic Module RecordsTable 42に列挙された追加のmethodsを持ちます:

Table 42: Additional Abstract Methods of Cyclic Module Records
Method Purpose Definitions
InitializeEnvironment ( )

The abstract method InitializeEnvironment takes no arguments and returns either a normal completion containing unused or a throw completion.

すべてのimported bindingsのresolvingを含め、moduleのEnvironment Recordをinitializeし、moduleのexecution contextを作成します。
この仕様内では、これは次のtypes内にdefinitionsを持ちます;hostsは独自のdefinitionsを持つ追加のtypesを提供してもよいです:
ExecuteModule ( [ capability ] )

The abstract method ExecuteModule takes optional argument capability (a PromiseCapability Record) and returns either a normal completion containing unused or a throw completion.

moduleのexecution context内でmoduleのcodeを評価します。このmoduleの[[HasTLA]]trueである場合、PromiseCapability Recordがargumentとして渡され、methodは与えられたcapabilityをresolveまたはrejectすることが期待されます。この場合、methodはexceptionをthrowしてはならず、必要に応じてPromiseCapability Recordをrejectしなければなりません。
この仕様内では、これは次のtypes内にdefinitionsを持ちます;hostsは独自のdefinitionsを持つ追加のtypesを提供してもよいです:

GraphLoadingState Recordは、module graphのloading processに関する情報を含むRecordです。これはHostLoadImportedModuleのcall後にloadingをcontinueするために使用されます。各GraphLoadingState RecordTable 43で定義されるfieldsを持ちます:

Table 43: GraphLoadingState Record Fields
Field Name Value Type Meaning
[[PromiseCapability]] a PromiseCapability Record loading processがfinishしたときにresolveするpromise。
[[IsLoading]] a Boolean loading processがまだfinishしておらず、successfullyでもerrorでもない場合はtrueです。
[[PendingModulesCount]] a non-negative integer pending HostLoadImportedModule callsの数をtrackします。
[[Visited]] a List of Cyclic Module Records circular dependenciesによるinfinite loopsを避けるため、current loading processによってすでにloadedされたCyclic Module Recordsのlistです。
[[HostDefined]] anything (default value is empty) LoadRequestedModules callerからHostLoadImportedModuleへ渡すhost-defined dataを含みます。

16.2.1.6.1 Implementation of Module Record Abstract Methods

以下は、Table 40で定義される対応するModule Record abstract methodsを実装するCyclic Module Recordのconcrete methodsです。

16.2.1.6.1.1 LoadRequestedModules ( [ hostDefined ] )

The LoadRequestedModules concrete method of a Cyclic Module Record module takes optional argument hostDefined (anything) and returns a Promise. moduleのdependency graph内のすべてのModule Records[[LoadedModules]]をpopulateします(作業の大半はauxiliary function InnerModuleLoadingによって行われます)。これはHostLoadImportedModule hookへ渡されるoptional hostDefined parameterを取ります。 It performs the following steps when called:

  1. hostDefinedが存在しないなら、hostDefinedemptyに設定する。
  2. promiseCapabilityを ! NewPromiseCapability(%Promise%) とする。
  3. stateGraphLoadingState Record { [[IsLoading]]: true, [[PendingModulesCount]]: 1, [[Visited]]: « », [[PromiseCapability]]: promiseCapability, [[HostDefined]]: hostDefined }とする。
  4. InnerModuleLoading(state, module)を実行する。
  5. promiseCapability.[[Promise]]を返す。
Note
hostDefined parameterは、imported modulesをfetchするために必要な追加情報を渡すために使用できます。例えばHTMLでは、<link rel="preload" as="..."> tagsに対して正しいfetch destinationを設定するために使用されます。 import() expressionsは決してhostDefined parameterを設定しません。

16.2.1.6.1.1.1 InnerModuleLoading ( state, module )

The abstract operation InnerModuleLoading takes arguments state (a GraphLoadingState Record) and module (a Module Record) and returns unused. LoadRequestedModulesによって使用され、moduleのdependency graphに対するactual loading processをrecursiveに実行します。 It performs the following steps when called:

  1. Assert: state.[[IsLoading]]trueである。
  2. moduleCyclic Module Recordであり、module.[[Status]]newであり、かつstate.[[Visited]]moduleを含まないなら、
    1. modulestate.[[Visited]]へappendする。
    2. requestedModulesCountmodule.[[RequestedModules]]内の要素数とする。
    3. state.[[PendingModulesCount]]state.[[PendingModulesCount]] + requestedModulesCountに設定する。
    4. module.[[RequestedModules]]の各ModuleRequest Record requestについて、以下を行う
      1. AllImportAttributesSupported(request.[[Attributes]])がfalseなら、
        1. errorThrowCompletion(a newly created SyntaxError object)とする。
        2. ContinueModuleLoading(state, error)を実行する。
      2. そうでなく、module.[[LoadedModules]]ModuleRequestsEqual(record, request)がtrueであるようなLoadedModuleRequest Record recordを含むなら、
        1. InnerModuleLoading(state, record.[[Module]])を実行する。
      3. そうでなければ、
        1. HostLoadImportedModule(module, request, state.[[HostDefined]], state)を実行する。
        2. NOTE: HostLoadImportedModuleFinishLoadingImportedModuleをcallし、これはContinueModuleLoadingを通じてgraph loading processへre-enterする。
      4. state.[[IsLoading]]falseなら、unusedを返す。
  3. Assert: state.[[PendingModulesCount]] ≥ 1である。
  4. state.[[PendingModulesCount]]state.[[PendingModulesCount]] - 1に設定する。
  5. state.[[PendingModulesCount]] = 0なら、
    1. state.[[IsLoading]]falseに設定する。
    2. state.[[Visited]]の各Cyclic Module Record loadedについて、以下を行う
      1. loaded.[[Status]]newなら、loaded.[[Status]]unlinkedに設定する。
    3. Call(state.[[PromiseCapability]].[[Resolve]], undefined, « undefined »)を実行する。
  6. unusedを返す。

16.2.1.6.1.1.2 ContinueModuleLoading ( state, moduleCompletion )

The abstract operation ContinueModuleLoading takes arguments state (a GraphLoadingState Record) and moduleCompletion (either a normal completion containing a Module Record or a throw completion) and returns unused. HostLoadImportedModuleへのcall後にloading processへre-enterするために使用されます。 It performs the following steps when called:

  1. state.[[IsLoading]]falseなら、unusedを返す。
  2. moduleCompletionnormal completionなら、
    1. InnerModuleLoading(state, moduleCompletion.[[Value]])を実行する。
  3. そうでなければ、
    1. state.[[IsLoading]]falseに設定する。
    2. Call(state.[[PromiseCapability]].[[Reject]], undefined, « moduleCompletion.[[Value]] »)を実行する。
  4. unusedを返す。

16.2.1.6.1.2 Link ( )

The Link concrete method of a Cyclic Module Record module takes no arguments and returns either a normal completion containing unused or a throw completion. success時、Linkはこのmoduleの[[Status]]unlinkedからlinkedへtransitionします。failure時、exceptionがthrowされ、このmoduleの[[Status]]unlinkedのままです。(作業の大半はauxiliary function InnerModuleLinkingによって行われます。) It performs the following steps when called:

  1. Assert: module.[[Status]]unlinkedlinkedevaluating-async、またはevaluatedのいずれかである。
  2. stackを新しい空のListとする。
  3. Completion(InnerModuleLinking(module, stack, 0))をresultとする。
  4. resultabrupt completionである場合、
    1. stackの各Cyclic Module Record requiredModuleについて、次を行う。
      1. Assert: requiredModule.[[Status]]linkingである。
      2. requiredModule.[[Status]]unlinkedに設定する。
    2. Assert: module.[[Status]]unlinkedである。
    3. resultを返す。
  5. Assert: module.[[Status]]linkedevaluating-async、またはevaluatedのいずれかである。
  6. Assert: stackは空である。
  7. unusedを返す。

16.2.1.6.1.2.1 InnerModuleLinking ( module, stack, index )

The abstract operation InnerModuleLinking takes arguments module (a Module Record), stack (a List of Cyclic Module Records), and index (a non-negative integer) and returns either a normal completion containing a non-negative integer or a throw completion. Linkによって使用され、moduleに対するactual linking processを実行し、dependency graph内の他のすべてのmodulesに対してもrecursiveに実行します。stackおよびindex parameters、ならびにmoduleの[[DFSAncestorIndex]] fieldは、depth-first search (DFS) traversalをtrackします。特に、[[DFSAncestorIndex]]はstrongly connected components (SCCs)をdiscoverするために使用され、SCC内のすべてのmodulesは一緒にlinkedへtransitionします。 It performs the following steps when called:

  1. moduleCyclic Module Recordでないなら、
    1. module.Link()を実行する。
    2. indexを返す。
  2. module.[[Status]]linkinglinkedevaluating-async、またはevaluatedのいずれかなら、
    1. indexを返す。
  3. Assert: module.[[Status]]unlinkedである。
  4. module.[[Status]]linkingに設定する。
  5. moduleIndexindexとする。
  6. module.[[DFSAncestorIndex]]indexに設定する。
  7. indexindex + 1に設定する。
  8. modulestackへappendする。
  9. module.[[RequestedModules]]の各ModuleRequest Record requestについて、以下を行う
    1. requiredModuleGetImportedModule(module, request)とする。
    2. indexを ? InnerModuleLinking(requiredModule, stack, index) に設定する。
    3. requiredModuleCyclic Module Recordなら、
      1. Assert: requiredModule.[[Status]]linkinglinkedevaluating-async、またはevaluatedのいずれかである。
      2. Assert: requiredModule.[[Status]]linkingであることとstackrequiredModuleを含むことは同値である。
      3. requiredModule.[[Status]]linkingなら、
        1. module.[[DFSAncestorIndex]]min(module.[[DFSAncestorIndex]], requiredModule.[[DFSAncestorIndex]])に設定する。
  10. module.InitializeEnvironment()を実行する。
  11. Assert: modulestack内にちょうど1回出現する。
  12. Assert: module.[[DFSAncestorIndex]]moduleIndexである。
  13. module.[[DFSAncestorIndex]] = moduleIndexなら、
    1. donefalseとする。
    2. donefalseである間、繰り返す
      1. requiredModulestackの最後の要素とする。
      2. stackの最後の要素をremoveする。
      3. Assert: requiredModuleCyclic Module Recordである。
      4. requiredModule.[[Status]]linkedに設定する。
      5. requiredModulemoduleが同じModule Recordなら、donetrueに設定する。
  14. indexを返す。

16.2.1.6.1.3 Evaluate ( )

The Evaluate concrete method of a Cyclic Module Record module takes no arguments and returns a Promise. Evaluateはこのmoduleの[[Status]]linkedからevaluating-asyncまたはevaluatedのいずれかへtransitionします。与えられたstrongly connected component内のmoduleに対して初めて呼び出されると、EvaluateはmoduleのevaluationがfinishしたときにresolveするPromiseを作成して返します。このPromiseはcomponentの[[CycleRoot]][[TopLevelCapability]] fieldにstoredされます。component内の任意のmoduleに対するfuture invocations of Evaluateは同じPromiseを返します。(作業の大半はauxiliary function InnerModuleEvaluationによって行われます。) It performs the following steps when called:

  1. Assert: このEvaluateへの呼び出しは、周囲のagent内の別のEvaluateへの呼び出しと同時には発生していない。
  2. Assert: module.[[Status]]linkedevaluating-async、またはevaluatedのいずれかである。
  3. module.[[Status]]evaluating-asyncまたはevaluatedのいずれかである場合、
    1. module.[[CycleRoot]]emptyでない場合、
      1. modulemodule.[[CycleRoot]]に設定する。
    2. そうでなければ、
      1. Assert: module.[[Status]]evaluatedであり、module.[[EvaluationError]]throw completionである。
  4. module.[[TopLevelCapability]]emptyでない場合、
    1. module.[[TopLevelCapability]].[[Promise]]を返す。
  5. stackを新しい空のListとする。
  6. NewPromiseCapability(%Promise%)をpromiseCapabilityとする。
  7. module.[[TopLevelCapability]]promiseCapabilityに設定する。
  8. Completion(InnerModuleEvaluation(module, stack, 0))をresultとする。
  9. resultabrupt completionである場合、
    1. stackの各Cyclic Module Record requiredModuleについて、次を行う。
      1. Assert: requiredModule.[[Status]]evaluatingである。
      2. requiredModule.[[Status]]evaluatedに設定する。
      3. requiredModule.[[EvaluationError]]resultに設定する。
    2. Assert: module.[[Status]]evaluatedである。
    3. Assert: module.[[EvaluationError]]resultは同じCompletion Recordである。
    4. Call(promiseCapability.[[Reject]], undefined, « result.[[Value]] »)を実行する。
  10. そうでなければ、
    1. Assert: module.[[Status]]evaluating-asyncまたはevaluatedのいずれかである。
    2. Assert: module.[[EvaluationError]]emptyである。
    3. module.[[Status]]evaluatedである場合、
      1. Assert: module.[[AsyncEvaluationOrder]]unsetまたはdoneのいずれかである。
      2. NOTE: module.[[AsyncEvaluationOrder]]doneであるのは、moduleが既に評価済みであり、かつその評価が非同期であった場合に限る。
      3. Call(promiseCapability.[[Resolve]], undefined, « undefined »)を実行する。
    4. Assert: stackは空である。
  11. promiseCapability.[[Promise]]を返す。

16.2.1.6.1.3.1 InnerModuleEvaluation ( module, stack, index )

The abstract operation InnerModuleEvaluation takes arguments module (a Module Record), stack (a List of Cyclic Module Records), and index (a non-negative integer) and returns either a normal completion containing a non-negative integer or a throw completion. Evaluateによって使用され、moduleに対するactual evaluation processを実行し、dependency graph内の他のすべてのmodulesに対してもrecursiveに実行します。stackおよびindex parameters、ならびにmodule[[DFSAncestorIndex]] fieldは、InnerModuleLinkingと同じ方法で使用されます。 It performs the following steps when called:

  1. moduleCyclic Module Recordでないなら、
    1. EvaluateModuleSync(module)を実行する。
    2. indexを返す。
  2. module.[[Status]]evaluating-asyncまたはevaluatedのいずれかなら、
    1. module.[[EvaluationError]]emptyなら、indexを返す。
    2. module.[[EvaluationError]]を返す。
  3. module.[[Status]]evaluatingなら、indexを返す。
  4. Assert: module.[[Status]]linkedである。
  5. module.[[Status]]evaluatingに設定する。
  6. moduleIndexindexとする。
  7. module.[[DFSAncestorIndex]]indexに設定する。
  8. module.[[PendingAsyncDependencies]]を0に設定する。
  9. indexindex + 1に設定する。
  10. modulestackへappendする。
  11. module.[[RequestedModules]]の各ModuleRequest Record requestについて、以下を行う
    1. requiredModuleGetImportedModule(module, request)とする。
    2. indexを ? InnerModuleEvaluation(requiredModule, stack, index) に設定する。
    3. requiredModuleCyclic Module Recordなら、
      1. Assert: requiredModule.[[Status]]evaluatingevaluating-async、またはevaluatedのいずれかである。
      2. Assert: requiredModule.[[Status]]evaluatingであることとstackrequiredModuleを含むことは同値である。
      3. requiredModule.[[Status]]evaluatingなら、
        1. module.[[DFSAncestorIndex]]min(module.[[DFSAncestorIndex]], requiredModule.[[DFSAncestorIndex]])に設定する。
      4. そうでなければ、
        1. requiredModulerequiredModule.[[CycleRoot]]に設定する。
        2. Assert: requiredModule.[[Status]]evaluating-asyncまたはevaluatedのいずれかである。
        3. requiredModule.[[EvaluationError]]emptyでないなら、? requiredModule.[[EvaluationError]]を返す。
      5. requiredModule.[[AsyncEvaluationOrder]]integerなら、
        1. module.[[PendingAsyncDependencies]]module.[[PendingAsyncDependencies]] + 1に設定する。
        2. modulerequiredModule.[[AsyncParentModules]]へappendする。
  12. module.[[PendingAsyncDependencies]] > 0またはmodule.[[HasTLA]]trueなら、
    1. Assert: module.[[AsyncEvaluationOrder]]unsetである。
    2. module.[[AsyncEvaluationOrder]]IncrementModuleAsyncEvaluationCount()に設定する。
    3. module.[[PendingAsyncDependencies]] = 0なら、ExecuteAsyncModule(module)を実行する。
  13. そうでなければ、
    1. module.ExecuteModule()を実行する。
  14. Assert: modulestack内にちょうど1回出現する。
  15. Assert: module.[[DFSAncestorIndex]]moduleIndexである。
  16. module.[[DFSAncestorIndex]] = moduleIndexなら、
    1. donefalseとする。
    2. donefalseである間、繰り返す
      1. requiredModulestackの最後の要素とする。
      2. stackの最後の要素をremoveする。
      3. Assert: requiredModuleCyclic Module Recordである。
      4. Assert: requiredModule.[[AsyncEvaluationOrder]]integerまたはunsetのいずれかである。
      5. requiredModule.[[AsyncEvaluationOrder]]unsetなら、requiredModule.[[Status]]evaluatedに設定する。
      6. そうでなければ、requiredModule.[[Status]]evaluating-asyncに設定する。
      7. requiredModulemoduleが同じModule Recordなら、donetrueに設定する。
      8. requiredModule.[[CycleRoot]]moduleに設定する。
  17. indexを返す。
Note 1

moduleは、InnerModuleEvaluationによってtraversedされている間はevaluatingです。moduleはexecution completion時にevaluatedとなり、またはその[[HasTLA]] fieldがtrueであるかasynchronous dependenciesを持つ場合、execution中はevaluating-asyncになります。

Note 2

asynchronous cycleのmoduleに依存する任意のmodulesは、そのcycleがevaluatingでないとき、その代わりに[[CycleRoot]]を介してcycleのrootのexecutionに依存します。これにより、cycle stateをそのroot module stateを通じて単一のstrongly connected componentとして扱うことが保証されます。

16.2.1.6.1.3.2 ExecuteAsyncModule ( module )

The abstract operation ExecuteAsyncModule takes argument module (a Cyclic Module Record) and returns unused. It performs the following steps when called:

  1. Assert: module.[[Status]]evaluatingまたはevaluating-asyncのいずれかである。
  2. Assert: module.[[HasTLA]]trueである。
  3. promiseCapabilityを ! NewPromiseCapability(%Promise%) とする。
  4. moduleをcaptureし、呼び出されたとき次のstepsを実行する、parametersを持たない新しいAbstract Closure fulfilledClosureとする:
    1. AsyncModuleExecutionFulfilled(module)を実行する。
    2. NormalCompletion(undefined)を返す。
  5. onFulfilledCreateBuiltinFunction(fulfilledClosure, 0, "", « »)とする。
  6. moduleをcaptureし、呼び出されたとき次のstepsを実行する、parameters (error)を持つ新しいAbstract Closure rejectedClosureとする:
    1. AsyncModuleExecutionRejected(module, error)を実行する。
    2. NormalCompletion(undefined)を返す。
  7. onRejectedCreateBuiltinFunction(rejectedClosure, 0, "", « »)とする。
  8. PerformPromiseThen(promiseCapability.[[Promise]], onFulfilled, onRejected)を実行する。
  9. module.ExecuteModule(promiseCapability)を実行する。
  10. unusedを返す。

16.2.1.6.1.3.3 GatherAvailableAncestors ( module, execList )

The abstract operation GatherAvailableAncestors takes arguments module (a Cyclic Module Record) and execList (a List of Cyclic Module Records) and returns unused. It performs the following steps when called:

  1. module.[[AsyncParentModules]]の各Cyclic Module Record ancestorModuleについて、以下を行う
    1. execListancestorModuleを含まず、かつancestorModule.[[CycleRoot]].[[EvaluationError]]emptyであるなら、
      1. Assert: ancestorModule.[[Status]]evaluating-asyncである。
      2. Assert: ancestorModule.[[EvaluationError]]emptyである。
      3. Assert: ancestorModule.[[AsyncEvaluationOrder]]integerである。
      4. Assert: ancestorModule.[[PendingAsyncDependencies]] > 0である。
      5. ancestorModule.[[PendingAsyncDependencies]]ancestorModule.[[PendingAsyncDependencies]] - 1に設定する。
      6. ancestorModule.[[PendingAsyncDependencies]] = 0なら、
        1. ancestorModuleexecListへappendする。
        2. ancestorModule.[[HasTLA]]falseなら、GatherAvailableAncestors(ancestorModule, execList)を実行する。
  2. unusedを返す。
Note

root moduleに対するasynchronous executionがfulfilledされると、このfunctionは、このcompletion時に一緒にsynchronouslyにexecuteできるmodulesのlistを決定し、それらをexecListにpopulateします。

16.2.1.6.1.3.4 AsyncModuleExecutionFulfilled ( module )

The abstract operation AsyncModuleExecutionFulfilled takes argument module (a Cyclic Module Record) and returns unused. It performs the following steps when called:

  1. module.[[Status]]evaluatedなら、
    1. Assert: module.[[EvaluationError]]emptyでない。
    2. unusedを返す。
  2. Assert: module.[[Status]]evaluating-asyncである。
  3. Assert: module.[[AsyncEvaluationOrder]]integerである。
  4. Assert: module.[[EvaluationError]]emptyである。
  5. module.[[AsyncEvaluationOrder]]doneに設定する。
  6. module.[[Status]]evaluatedに設定する。
  7. module.[[TopLevelCapability]]emptyでないなら、
    1. Assert: module.[[CycleRoot]]moduleは同じModule Recordである。
    2. Call(module.[[TopLevelCapability]].[[Resolve]], undefined, « undefined »)を実行する。
  8. execListを新しい空のListとする。
  9. GatherAvailableAncestors(module, execList)を実行する。
  10. Assert: execListのすべての要素は、その[[AsyncEvaluationOrder]] fieldがintegerに、[[PendingAsyncDependencies]] fieldが0に、[[EvaluationError]] fieldがemptyに設定されている。
  11. sortedExecListを、その要素がexecListの要素であり、それらの[[AsyncEvaluationOrder]] fieldの昇順でsortedされたListとする。
  12. sortedExecListの各Cyclic Module Record ancestorModuleについて、以下を行う
    1. ancestorModule.[[Status]]evaluatedなら、
      1. Assert: ancestorModule.[[EvaluationError]]emptyでない。
    2. そうでなく、ancestorModule.[[HasTLA]]trueなら、
      1. ExecuteAsyncModule(ancestorModule)を実行する。
    3. そうでなければ、
      1. resultCompletion(ancestorModule.ExecuteModule())とする。
      2. resultabrupt completionなら、
        1. AsyncModuleExecutionRejected(ancestorModule, result.[[Value]])を実行する。
      3. そうでなければ、
        1. ancestorModule.[[AsyncEvaluationOrder]]doneに設定する。
        2. ancestorModule.[[Status]]evaluatedに設定する。
        3. ancestorModule.[[TopLevelCapability]]emptyでないなら、
          1. Assert: ancestorModule.[[CycleRoot]]ancestorModuleは同じModule Recordである。
          2. Call(ancestorModule.[[TopLevelCapability]].[[Resolve]], undefined, « undefined »)を実行する。
  13. unusedを返す。

16.2.1.6.1.3.5 AsyncModuleExecutionRejected ( module, error )

The abstract operation AsyncModuleExecutionRejected takes arguments module (a Cyclic Module Record) and error (an ECMAScript language value) and returns unused. It performs the following steps when called:

  1. module.[[Status]]evaluatedなら、
    1. Assert: module.[[EvaluationError]]emptyでない。
    2. unusedを返す。
  2. Assert: module.[[Status]]evaluating-asyncである。
  3. Assert: module.[[AsyncEvaluationOrder]]integerである。
  4. Assert: module.[[EvaluationError]]emptyである。
  5. module.[[EvaluationError]]ThrowCompletion(error)に設定する。
  6. module.[[Status]]evaluatedに設定する。
  7. module.[[AsyncEvaluationOrder]]doneに設定する。
  8. NOTE: module.[[AsyncEvaluationOrder]]AsyncModuleExecutionFulfilledとのsymmetryのためにdoneに設定される。InnerModuleEvaluationにおいて、moduleの[[AsyncEvaluationOrder]] internal slotの値は、その[[EvaluationError]] internal slotがemptyでない場合には使用されない。
  9. module.[[TopLevelCapability]]emptyでないなら、
    1. Assert: module.[[CycleRoot]]moduleは同じModule Recordである。
    2. Call(module.[[TopLevelCapability]].[[Reject]], undefined, « error »)を実行する。
  10. module.[[AsyncParentModules]]の各Cyclic Module Record ancestorModuleについて、以下を行う
    1. AsyncModuleExecutionRejected(ancestorModule, error)を実行する。
  11. unusedを返す。

16.2.1.6.2 Example Cyclic Module Record Graphs

このnon-normative sectionは、errorsがどのように発生し得るかに特にfocusして、いくつかのcommon module graphsのlinkingおよびevaluationの一連のexamplesを示します。

まず、次のsimple module graphを考えます:

Figure 2: A simple module graph
A module graph in which module A depends on module B, and module B depends on module C

まず、error conditionsがないと仮定します。hostが最初にA.LoadRequestedModules()をcallすると、これは仮定によりsuccessfullyに完了し、BおよびCのdependencies(それぞれCおよびnone)もrecursiveにloadし、その後A.[[Status]] = B.[[Status]] = C.[[Status]] = unlinkedを設定します。次に、hostがA.Link()をcallすると、これは(再び仮定により)successfullyに完了し、A.[[Status]] = B.[[Status]] = C.[[Status]] = linkedとなります。これらのpreparatory stepsは任意の時点で実行できます。後にhostがmodulesのpossible side effectsをincurする準備ができたとき、A.Evaluate()をcallでき、これはsuccessfullyに完了し、undefinedへresolveするPromiseを返し(再び仮定により)、まずC、次にBをrecursiveに評価済みにします。この時点で各moduleの[[Status]]evaluatedになります。

次に、A.LoadRequestedModules()へのsuccessful callの後にlinking errorsが関係するcasesを考えます。CInnerModuleLinkingがsucceedsしたが、その後Bについてfailsする場合、例えばBCが提供しないものをimportするためにfailsする場合、original A.Link()はfailし、AB[[Status]]unlinkedのままです。ただしC[[Status]]linkedになっています。

最後に、Link()へのsuccessful call後にevaluation errorsが関係するcaseを考えます。CInnerModuleEvaluationがsucceedsしたが、その後Bについてfailsする場合、例えばBがexceptionをthrowするcodeを含むためにfailsする場合、original A.Evaluate()はfailし、rejected Promiseを返します。結果として生じるexceptionはAB[[EvaluationError]] fieldsの両方にrecordedされ、それらの[[Status]]evaluatedになります。Cevaluatedになりますが、AおよびBとは対照的に、successfullyにevaluationを完了したため[[EvaluationError]]を持たないままです。exceptionをstoreすることで、hostがAまたはBをreuseしようとしてEvaluate() methodをcallするたびに、同じexceptionにencounterすることが保証されます。(HostsCyclic Module Recordsをreuseする必要はありません;同様に、hostsはこれらのmethodsによってthrownされたexception objectsをexposeする必要はありません。ただし、この仕様はそのようなusesを可能にします。)

次に、異なるtypeのerror conditionを考えます:

Figure 3: A module graph with an unresolvable module
A module graph in which module A depends on a missing (unresolvable) module, represented by ???

このscenarioでは、module Aが何らかの他のmoduleへのdependencyをdeclareしていますが、そのmoduleに対するModule Recordは存在しません。すなわち、HostLoadImportedModuleは、それを求められたときexceptionを伴ってFinishLoadingImportedModuleをcallします。これは、対応するresourceが存在しない、またはresourceは存在するがresulting source textをparseしようとしたときParseModuleが何らかのerrorsを返すなど、さまざまなreasonsで発生し得ます。Hostsは、FinishLoadingImportedModuleへ渡すcompletionを通じてfailureのcauseをexposeすることを選択できます。いずれの場合も、このexceptionはloading failureを引き起こし、その結果A[[Status]]newのままになります。

ここでのloading、linking、evaluation errorsの違いは、次のcharacteristicに起因します:

  • Evaluationはside effectsを引き起こす可能性があるため、1回だけ実行されなければなりません;したがって、たとえunsuccessfullyであったとしても、evaluationがすでに実行されたかどうかをrememberすることが重要です。(error caseでは、そうしなければsubsequent Evaluate() callsが新しいexceptionをsynthesizeしなければならないため、exceptionもrememberすることに意味があります。)
  • 一方、Linkingはside-effect-freeであるため、failしたとしても、問題なくlater timeにretryできます。
  • Loadingはhostとcloselyにinteractsし、hostsによってはfailed loadsをusersがretryできるようにすることがdesirableである場合があります(例えば、failureがtemporarily bad network conditionsによって引き起こされた場合)。

次に、cycleを持つmodule graphを考えます:

Figure 4: A cyclic module graph
A module graph in which module A depends on module B and C, but module B also depends on module A

ここではentry pointがmodule Aであると仮定します。そのため、hostはA.LoadRequestedModules()をcallして進み、これはAに対してInnerModuleLoadingを実行します。これはさらにBおよびCに対してInnerModuleLoadingをcallします。cycleのため、これは再びAに対してInnerModuleLoadingをtriggerしますが、この時点では、このLoadRequestedModules process中にAのdependencies loadingがすでにtriggerされているため、no-opです。graph内のすべてのmodulesがsuccessfullyにloadedされると、それらの[[Status]]は同時にnewからunlinkedへtransitionします。

その後、hostはA.Link()をcallして進み、これはAに対してInnerModuleLinkingを実行します。これはさらにBに対してInnerModuleLinkingをcallします。cycleのため、これは再びAに対してInnerModuleLinkingをtriggerしますが、この時点ではA.[[Status]]がすでにlinkingであるためno-opです。controlがAへ戻り、Cに対してInnerModuleLinkingがtriggerされるとき、B.[[Status]]自体はlinkingのままです。これがC.[[Status]]linkedになって戻った後、ABは一緒にlinkingからlinkedへtransitionします;これは、それらがstrongly connected componentを形成しているため、by designです。このphaseではmodule graphがdepth-first searchでtraversedされるため、同じSCC内のmodulesのstatusを同時にtransitionすることが可能です。

cyclic module graphのevaluation phaseについても、success caseではanalogous storyが発生します。

次に、Aにlinking errorがあるcaseを考えます;例えば、ACから存在しないbindingをimportしようとする場合です。その場合、上記のstepsはやはり発生し、Aに対する2回目のInnerModuleLinking callからのearly returnも含まれます。しかし、original InnerModuleLinking on Aまでunwindすると、InitializeEnvironment中、すなわちC.ResolveExport()の直後にfailします。thrown SyntaxError exceptionはA.Linkへpropagateし、これはcurrently stack上にあるすべてのmodules(これらは常にちょうどまだlinkingであるmodulesです)をresetします。したがってABの両方がunlinkedになります。Clinkedのまま残ることに注意してください。

あるいは、Aにevaluation errorがあるcaseを考えます;例えば、そのsource codeがexceptionをthrowする場合です。その場合、上記stepsのevaluation-time analogueはやはり発生し、Aに対する2回目のInnerModuleEvaluation callからのearly returnも含まれます。しかし、original InnerModuleEvaluation on Aまでunwindすると、仮定によりfailします。thrown exceptionはA.Evaluate()へpropagateし、これはcurrently stack上にあるすべてのmodules(すなわちまだevaluatingであるmodules)にerrorをrecordし、またtop-level awaitを含む、またはそれに依存するmodulesのchainをdependency graph全体に形成する[[AsyncParentModules]]を介して、AsyncModuleExecutionRejected algorithmによってもrecordします。したがってABの両方がevaluatedになり、exceptionはAB[[EvaluationError]] fieldsの両方にrecordedされる一方、C[[EvaluationError]]なしでevaluatedのまま残ります。

最後に、すべてのmodulesがasynchronouslyにcompleteするcycleを持つmodule graphを考えます:

Figure 5: An asynchronous cyclic module graph
A module graph in which module A depends on module B and C, module B depends on module D, module C depends on module D and E, and module D depends on module A

Loadingおよびlinkingは以前と同様に発生し、すべてのmodulesは[[Status]]linkedに設定されて終了します。

A.Evaluate()をcallすると、ABDに対してInnerModuleEvaluationがcallされ、それらはすべてevaluatingへtransitionします。その後、Aに対してInnerModuleEvaluationが再びcallされますが、すでにevaluatingであるためno-opです。この時点でD.[[PendingAsyncDependencies]]は0なので、ExecuteAsyncModule(D)がcallされ、Dのasynchronous executionをtrackする新しいPromiseCapabilityを伴ってD.ExecuteModuleをcallします。Bに対するInnerModuleEvaluationまでunwindし、B.[[PendingAsyncDependencies]]を1に、B.[[AsyncEvaluationOrder]]を1に設定します。original InnerModuleEvaluation on Aまでunwindし、A.[[PendingAsyncDependencies]]を1に設定します。Aのdependenciesに対するloopの次のiterationで、Cに対して、したがってD(再びno-op)およびEに対してInnerModuleEvaluationをcallします。Eにはdependenciesがなくcycleの一部でないため、Dと同じ方法でExecuteAsyncModule(E)をcallし、Eは直ちにstackからremoveされます。もう一度Cに対するInnerModuleEvaluationまでunwindし、C.[[AsyncEvaluationOrder]]を3に設定します。これでAのdependenciesに対するloopをfinishし、A.[[AsyncEvaluationOrder]]を4に設定し、entire strongly connected componentをstackからremoveして、すべてのmodulesを一度にevaluating-asyncへtransitionします。この時点で、modulesのfieldsはTable 44に示す通りです。

Table 44: Module fields after the initial Evaluate() call
Field
Module
A B C D E
[[DFSAncestorIndex]] 0 0 0 0 4
[[Status]] evaluating-async evaluating-async evaluating-async evaluating-async evaluating-async
[[AsyncEvaluationOrder]] 4 1 3 0 2
[[AsyncParentModules]] « » « A » « A » « B, C » « C »
[[PendingAsyncDependencies]] 2 (B and C) 1 (D) 2 (D and E) 0 0

Eが最初にexecutingをfinishすると仮定します。その場合、AsyncModuleExecutionFulfilledがcallされ、E.[[Status]]evaluatedに設定され、C.[[PendingAsyncDependencies]]はdecrementされて1になります。updated modulesのfieldsはTable 45に示す通りです。

Table 45: Module fields after module E finishes executing
Field
Module
C E
[[DFSAncestorIndex]] 0 4
[[Status]] evaluating-async evaluated
[[AsyncEvaluationOrder]] 3 done
[[AsyncParentModules]] « A » « C »
[[PendingAsyncDependencies]] 1 (D) 0

次にfinishするのはDです(まだexecutingしていた唯一のmoduleだったため)。その場合、AsyncModuleExecutionFulfilledが再びcallされ、D.[[Status]]evaluatedに設定されます。executionにavailableなそのancestorsはB(その[[AsyncEvaluationOrder]]は1)とC(その[[AsyncEvaluationOrder]]は3)であるため、Bが最初にhandledされます:B.[[PendingAsyncDependencies]]はdecrementされて0になり、ExecuteAsyncModuleBに対してcallされ、executingを開始します。C.[[PendingAsyncDependencies]]もdecrementされて0になり、Cがexecutingを開始します(Bawaitを含む場合、potentiallyにBとparallelに)。updated modulesのfieldsはTable 46に示す通りです。

Table 46: Module fields after module D finishes executing
Field
Module
B C D
[[DFSAncestorIndex]] 0 0 0
[[Status]] evaluating-async evaluating-async evaluated
[[AsyncEvaluationOrder]] 1 3 done
[[AsyncParentModules]] « A » « A » « B, C »
[[PendingAsyncDependencies]] 0 0 0

Cが次にexecutingをfinishすると仮定します。その場合、AsyncModuleExecutionFulfilledが再びcallされ、C.[[Status]]evaluatedに設定され、A.[[PendingAsyncDependencies]]はdecrementされて1になります。updated modulesのfieldsはTable 47に示す通りです。

Table 47: Module fields after module C finishes executing
Field
Module
A C
[[DFSAncestorIndex]] 0 0
[[Status]] evaluating-async evaluated
[[AsyncEvaluationOrder]] 4 done
[[AsyncParentModules]] « » « A »
[[PendingAsyncDependencies]] 1 (B) 0

次に、Bがexecutingをfinishします。その場合、AsyncModuleExecutionFulfilledが再びcallされ、B.[[Status]]evaluatedに設定されます。A.[[PendingAsyncDependencies]]はdecrementされて0になるため、ExecuteAsyncModuleがcallされ、Aがexecutingを開始します。updated modulesのfieldsはTable 48に示す通りです。

Table 48: Module fields after module B finishes executing
Field
Module
A B
[[DFSAncestorIndex]] 0 0
[[Status]] evaluating-async evaluated
[[AsyncEvaluationOrder]] 4 done
[[AsyncParentModules]] « » « A »
[[PendingAsyncDependencies]] 0 0

最後に、Aがexecutingをfinishします。その場合、AsyncModuleExecutionFulfilledが再びcallされ、A.[[Status]]evaluatedに設定されます。この時点で、A.[[TopLevelCapability]]内のPromise(A.Evaluate()から返されたもの)がresolvedされ、このmodule graphのhandlingは終了します。updated moduleのfieldsはTable 49に示す通りです。

Table 49: Module fields after module A finishes executing
Field
Module
A
[[DFSAncestorIndex]] 0
[[Status]] evaluated
[[AsyncEvaluationOrder]] done
[[AsyncParentModules]] « »
[[PendingAsyncDependencies]] 0

あるいは、Bがexecutingをfinishする前にCがexecutionにfailし、errorを返すfailure caseを考えます。その場合、AsyncModuleExecutionRejectedがcallされ、これはC.[[Status]]evaluatedに、C.[[EvaluationError]]をそのerrorに設定します。その後、各AsyncParentModulesに対してAsyncModuleExecutionRejectedを実行することで、このerrorをすべてのAsyncParentModulesへpropagateします。updated modulesのfieldsはTable 50に示す通りです。

Table 50: Module fields after module C finishes with an error
Field
Module
A C
[[DFSAncestorIndex]] 0 0
[[Status]] evaluated evaluated
[[AsyncEvaluationOrder]] done done
[[AsyncParentModules]] « » « A »
[[PendingAsyncDependencies]] 1 (B) 0
[[EvaluationError]] empty C's evaluation error

CCのerrorを伴ってAに対してAsyncModuleExecutionRejectedをcallするため、ACと同じerrorでrejectedされます。A.[[Status]]evaluatedに設定されます。この時点でA.[[TopLevelCapability]]内のPromise(A.Evaluate()から返されたもの)はrejectedされます。updated moduleのfieldsはTable 51に示す通りです。

Table 51: Module fields after module A is rejected
Field
Module
A
[[DFSAncestorIndex]] 0
[[Status]] evaluated
[[AsyncEvaluationOrder]] done
[[AsyncParentModules]] « »
[[PendingAsyncDependencies]] 0
[[EvaluationError]] C's Evaluation Error

その後、Bがerrorなしでexecutingをfinishします。その場合、AsyncModuleExecutionFulfilledが再びcallされ、B.[[Status]]evaluatedに設定されます。GatherAvailableAncestorsBに対してcallされます。しかし、A.[[CycleRoot]]Aであり、これはevaluation errorを持つため、返されるsortedExecListには追加されず、AsyncModuleExecutionFulfilledはさらなるprocessingなしでreturnします。Bの任意のfuture importerは、cycle root A上に設定されたCからのevaluation errorから、B.[[CycleRoot]].[[EvaluationError]]のrejectionをresolveします。updated modulesのfieldsはTable 52に示す通りです。

Table 52: Module fields after module B finishes executing in an erroring graph
Field
Module
A B
[[DFSAncestorIndex]] 0 0
[[Status]] evaluated evaluated
[[AsyncEvaluationOrder]] 4 1
[[AsyncParentModules]] « » « A »
[[PendingAsyncDependencies]] 0 0
[[EvaluationError]] C's Evaluation Error empty

16.2.1.7 Source Text Module Records

Source Text Module Recordは、goal symbol Moduleを使用してparsedされたECMAScript source text11)から定義されたmoduleに関する情報を表すために使用されます。そのfieldsは、moduleによってimportおよびexportされるnamesに関するdigested informationを含み、そのconcrete methodsはこれらのdigestsを使用してmoduleをlinkおよびevaluateします。

Source Text Module Recordは、abstract Module Record typeの他のsubclassesとともにmodule graph内に存在でき、Cyclic Module Record typeの他のsubclassesとともにcyclesに参加できます。

Table 41で定義されるfieldsに加えて、Source Text Module RecordsTable 53に列挙された追加のfieldsを持ちます。これらの各fieldはParseModule内でinitiallyに設定されます。

Table 53: Additional Fields of Source Text Module Records
Field Name Value Type Meaning
[[ECMAScriptCode]] a Parse Node Modulegoal symbolとして使用してこのmoduleのsource textをparseした結果。
[[Context]] an ECMAScript code execution context or empty このmoduleに関連付けられたexecution context。moduleのenvironmentがinitializedされるまではemptyです。
[[ImportMeta]] an Object or empty import.meta meta propertyを通じてexposedされるobject。ECMAScript codeによってaccessされるまではemptyです。
[[ImportEntries]] a List of ImportEntry Records このmoduleのcodeからderivedされたImportEntry recordsのList
[[LocalExportEntries]] a List of ExportEntry Records module内でoccurするdeclarationsに対応する、このmoduleのcodeからderivedされたExportEntry recordsのList
[[IndirectExportEntries]] a List of ExportEntry Records module内でoccurするreexported imports、またはexport * as namespace declarationsからのexportsに対応する、このmoduleのcodeからderivedされたExportEntry recordsのList
[[StarExportEntries]] a List of ExportEntry Records module内でoccurするexport * declarationsに対応する、このmoduleのcodeからderivedされたExportEntry recordsのList。ただしexport * as namespace declarationsは含まれません。

ImportEntry Recordは、単一のdeclarative importに関する情報をdigestするRecordです。各ImportEntry RecordTable 54で定義されるfieldsを持ちます:

Table 54: ImportEntry Record Fields
Field Name Value Type Meaning
[[ModuleRequest]] a ModuleRequest Record ImportDeclarationModuleSpecifierおよびimport attributesを表すModuleRequest Record
[[ImportName]] a String or namespace [[ModuleRequest]]によってidentifiedされるmoduleによってdesired bindingがexportされているname。値namespaceは、import requestがtarget moduleのnamespace objectに対するものであることを示します。
[[LocalName]] a String importing module内からimported valueにlocallyにaccessするために使用されるname。
Note 1

Table 55は、syntactic import formsを表すために使用されるImportEntry records fieldsのexamplesを示します:

Table 55 (Informative): Import Forms Mappings to ImportEntry Records
Import Statement Form [[ModuleRequest]] [[ImportName]] [[LocalName]]
import v from "mod"; "mod" "default" "v"
import * as ns from "mod"; "mod" namespace "ns"
import {x} from "mod"; "mod" "x" "x"
import {x as v} from "mod"; "mod" "x" "v"
import "mod"; ImportEntry Recordは作成されません。

ExportEntry Recordは、単一のdeclarative exportに関する情報をdigestするRecordです。各ExportEntry RecordTable 56で定義されるfieldsを持ちます:

Table 56: ExportEntry Record Fields
Field Name Value Type Meaning
[[ExportName]] a String or null このmoduleによってこのbindingをexportするために使用されるname。
[[ModuleRequest]] a ModuleRequest Record or null ExportDeclarationModuleSpecifierおよびimport attributesを表すModuleRequest RecordExportDeclarationModuleSpecifierを持たない場合はnull
[[ImportName]] a String, null, namespace, or all-but-default [[ModuleRequest]]によってidentifiedされるmoduleによってdesired bindingがexportされているname。ExportDeclarationModuleSpecifierを持たない場合はnullnamespaceexport * as ns from "mod" declarationsに使用されます。all-but-defaultexport * from "mod" declarationsに使用されます。
[[LocalName]] a String or null importing module内からexported valueにlocallyにaccessするために使用されるname。exported valueがmodule内からlocallyにaccessできない場合はnull
Note 2

Table 57は、syntactic export formsを表すために使用されるExportEntry record fieldsのexamplesを示します:

Table 57 (Informative): Export Forms Mappings to ExportEntry Records
Export Statement Form [[ExportName]] [[ModuleRequest]] [[ImportName]] [[LocalName]]
export var v; "v" null null "v"
export default function f() {} "default" null null "f"
export default function () {} "default" null null "*default*"
export default 42; "default" null null "*default*"
export {x}; "x" null null "x"
export {v as x}; "x" null null "v"
export {x} from "mod"; "x" "mod" "x" null
export {v as x} from "mod"; "x" "mod" "v" null
export * from "mod"; null "mod" all-but-default null
export * as ns from "mod"; "ns" "mod" namespace null

次のdefinitionsは、Source Text Module Recordsに対してrequired concrete methodsおよびその他のabstract operationsを指定します

16.2.1.7.1 ParseModule ( sourceText, realm, hostDefined )

The abstract operation ParseModule takes arguments sourceText (a String or a sequence of Unicode code points), realm (a Realm Record), and hostDefined (anything) and returns a Source Text Module Record or a non-empty List of SyntaxError objects. sourceTextModuleとしてparseした結果に基づいてSource Text Module Recordを作成します。 It performs the following steps when called:

  1. bodyParseText(sourceText, Module)とする。
  2. bodyがerrorsのListなら、bodyを返す。
  3. requestedModulesbodyModuleRequestsとする。
  4. importEntriesbodyImportEntriesとする。
  5. importedBoundNamesImportedLocalNames(importEntries)とする。
  6. indirectExportEntriesを新しい空のListとする。
  7. localExportEntriesを新しい空のListとする。
  8. starExportEntriesを新しい空のListとする。
  9. exportEntriesbodyExportEntriesとする。
  10. exportEntriesの各ExportEntry Record exportEntryについて、以下を行う
    1. exportEntry.[[ModuleRequest]]nullなら、
      1. importedBoundNamesexportEntry.[[LocalName]]を含まないなら、
        1. exportEntrylocalExportEntriesへappendする。
      2. そうでなければ、
        1. NOTE: もともと別のmoduleからimportされたbindingまたはnamespace objectをexportするとき、ExportEntry Recordは、bindingまたはnamespace objectがimportされてからexportされるのではなく、original moduleから直接re-exportされていた場合のformにmatchするようにrewrittenされる。これにより、export * fromを通じて同じbindingまたはnamespaceを同じnameで2回exportすることから生じるconflictsは、Source Text Module RecordsのResolveExport concrete methodのstep 9.e.iiiでambiguousとして扱われるのではなく、ignoredできる。
        2. importEntryimportEntriesのうち[[LocalName]]exportEntry.[[LocalName]]である要素とする。
        3. ExportEntry Record { [[ModuleRequest]]: importEntry.[[ModuleRequest]], [[ImportName]]: importEntry.[[ImportName]], [[LocalName]]: null, [[ExportName]]: exportEntry.[[ExportName]] }をindirectExportEntriesへappendする。
    2. そうでなく、exportEntry.[[ImportName]]all-but-defaultなら、
      1. Assert: exportEntry.[[ExportName]]nullである。
      2. exportEntrystarExportEntriesへappendする。
    3. そうでなければ、
      1. exportEntryindirectExportEntriesへappendする。
  11. asyncbody Contains awaitとする。
  12. Source Text Module Record { [[Realm]]: realm, [[Environment]]: empty, [[Namespace]]: empty, [[CycleRoot]]: empty, [[HasTLA]]: async, [[AsyncEvaluationOrder]]: unset, [[TopLevelCapability]]: empty, [[AsyncParentModules]]: « », [[PendingAsyncDependencies]]: empty, [[Status]]: new, [[EvaluationError]]: empty, [[HostDefined]]: hostDefined, [[ECMAScriptCode]]: body, [[Context]]: empty, [[ImportMeta]]: empty, [[RequestedModules]]: requestedModules, [[LoadedModules]]: « », [[ImportEntries]]: importEntries, [[LocalExportEntries]]: localExportEntries, [[IndirectExportEntries]]: indirectExportEntries, [[StarExportEntries]]: starExportEntries, [[DFSAncestorIndex]]: empty }を返す。
Note

implementationは、そのmodule source textに対するParseModuleのevaluationより前に、module source textをparseし、それをEarly Error conditionsについてanalyseしてもよいです。ただし、errorsのreportingは、この仕様が実際にそのsource textに対してParseModuleを実行する時点までdeferされなければなりません。

16.2.1.7.2 Implementation of Module Record Abstract Methods

以下は、Table 40で定義される対応するModule Record abstract methodsを実装するSource Text Module Recordのconcrete methodsです。

16.2.1.7.2.1 GetExportedNames ( [ exportStarSet ] )

The GetExportedNames concrete method of a Source Text Module Record module takes optional argument exportStarSet (a List of Source Text Module Records) and returns a List of Strings. It performs the following steps when called:

  1. Assert: module.[[Status]]newではない。
  2. exportStarSetが存在しない場合、exportStarSetを新しい空のListに設定する。
  3. exportStarSetmoduleを含む場合、
    1. Assert: export *の循環の開始点に到達している。
    2. 新しい空のListを返す。
  4. moduleexportStarSetに追加する。
  5. exportedNamesを新しい空のListとする。
  6. module.[[LocalExportEntries]]の各ExportEntry Record exportEntryについて、次を行う。
    1. Assert: moduleはこのエクスポートに対する直接束縛を提供する。
    2. Assert: exportEntry.[[ExportName]]nullではない。
    3. exportEntry.[[ExportName]]exportedNamesに追加する。
  7. module.[[IndirectExportEntries]]の各ExportEntry Record exportEntryについて、次を行う。
    1. Assert: moduleはこのエクスポートに対する特定の束縛をインポートしている。
    2. Assert: exportEntry.[[ExportName]]nullではない。
    3. exportEntry.[[ExportName]]exportedNamesに追加する。
  8. module.[[StarExportEntries]]の各ExportEntry Record exportEntryについて、次を行う。
    1. Assert: exportEntry.[[ModuleRequest]]nullではない。
    2. GetImportedModule(module, exportEntry.[[ModuleRequest]])をrequestedModuleとする。
    3. requestedModule.GetExportedNames(exportStarSet)をstarNamesとする。
    4. starNamesの各要素nameについて、次を行う。
      1. name"default"でない場合、
        1. exportedNamesnameを含まない場合、
          1. nameexportedNamesに追加する。
  9. exportedNamesを返す。
Note

GetExportedNamesは、ambiguous star export bindingsを持つnamesをfilter outしたり、それに対してexceptionをthrowしたりしません。

16.2.1.7.2.2 ResolveExport ( exportName [ , resolveSet ] )

The ResolveExport concrete method of a Source Text Module Record module takes argument exportName (a String) and optional argument resolveSet (a List of Records with fields [[Module]] (a Module Record) and [[ExportName]] (a String)) and returns a ResolvedBinding Record, null, or ambiguous.

ResolveExportは、imported bindingをactual defining moduleおよびlocal binding nameへresolveすることを試みます。defining moduleは、このmethodがinvokedされたModule Recordによって表されるmoduleである場合も、そのmoduleによってimportされる他のmoduleである場合もあります。parameter resolveSetは、unresolved circular import/export pathsをdetectするために使用されます。specific Module RecordexportNameからなるpairがすでにresolveSet内にある状態で到達された場合、import circularityにencounterしています。ResolveExportをrecursiveにcallする前に、moduleexportNameからなるpairがresolveSetに追加されます。

defining moduleが見つかった場合、ResolvedBinding Record { [[Module]], [[BindingName]] }が返されます。このrecordは、これがlocal bindingを持たないnamespaceのexportでない限り、originally requested exportのresolved bindingをidentifyします。この場合、[[BindingName]]namespaceに設定されます。definitionが見つからなかった場合、またはrequestがcircularであることが見つかった場合、nullが返されます。requestがambiguousであることが見つかった場合、ambiguousが返されます。

It performs the following steps when called:

  1. Assert: module.[[Status]]newではない。
  2. resolveSetが存在しない場合、resolveSetを新しい空のListに設定する。
  3. resolveSetの各Record { [[Module]], [[ExportName]] } recordについて、次を行う。
    1. modulerecord.[[Module]]が同じModule Recordであり、かつexportNamerecord.[[ExportName]]である場合、
      1. Assert: これは循環import要求である。
      2. nullを返す。
  4. Record { [[Module]]: module, [[ExportName]]: exportName }をresolveSetに追加する。
  5. module.[[LocalExportEntries]]の各ExportEntry Record exportEntryについて、次を行う。
    1. exportEntry.[[ExportName]]exportNameである場合、
      1. Assert: moduleはこのエクスポートに対する直接束縛を提供する。
      2. ResolvedBinding Record { [[Module]]: module, [[BindingName]]: exportEntry.[[LocalName]] }を返す。
  6. module.[[IndirectExportEntries]]の各ExportEntry Record exportEntryについて、次を行う。
    1. exportEntry.[[ExportName]]exportNameである場合、
      1. Assert: exportEntry.[[ModuleRequest]]nullではない。
      2. GetImportedModule(module, exportEntry.[[ModuleRequest]])をimportedModuleとする。
      3. exportEntry.[[ImportName]]namespaceである場合、
        1. Assert: moduleはこのエクスポートに対する直接束縛を提供しない。
        2. ResolvedBinding Record { [[Module]]: importedModule, [[BindingName]]: namespace }を返す。
      4. Assert: moduleはこのエクスポートに対する特定の束縛をインポートしている。
      5. Assert: exportEntry.[[ImportName]]はStringである。
      6. importedModule.ResolveExport(exportEntry.[[ImportName]], resolveSet)を返す。
  7. exportName"default"である場合、
    1. Assert: defaultエクスポートはこのモジュールによって明示的に定義されていなかった。
    2. nullを返す。
    3. NOTE: defaultエクスポートはexport * from "mod"宣言によって提供されることはできない。
  8. starResolutionnullとする。
  9. module.[[StarExportEntries]]の各ExportEntry Record exportEntryについて、次を行う。
    1. Assert: exportEntry.[[ModuleRequest]]nullではない。
    2. GetImportedModule(module, exportEntry.[[ModuleRequest]])をimportedModuleとする。
    3. importedModule.ResolveExport(exportName, resolveSet)をresolutionとする。
    4. resolutionambiguousである場合、ambiguousを返す。
    5. resolutionnullでない場合、
      1. Assert: resolutionResolvedBinding Recordである。
      2. starResolutionnullである場合、
        1. starResolutionresolutionに設定する。
      3. そうでなければ、
        1. Assert: 要求された名前を含む*エクスポートが複数存在する。
        2. resolution.[[Module]]starResolution.[[Module]]が同じModule Recordでない場合、ambiguousを返す。
        3. resolution.[[BindingName]]starResolution.[[BindingName]]でない場合、ambiguousを返す。
  10. starResolutionを返す。

16.2.1.7.3 Implementation of Cyclic Module Record Abstract Methods

以下は、Table 42で定義される対応するCyclic Module Record abstract methodsを実装するSource Text Module Recordのconcrete methodsです。

16.2.1.7.3.1 InitializeEnvironment ( )

The InitializeEnvironment concrete method of a Source Text Module Record module takes no arguments and returns either a normal completion containing unused or a throw completion. It performs the following steps when called:

  1. module.[[IndirectExportEntries]]の各ExportEntry Record exportEntryについて、次を行う。
    1. Assert: exportEntry.[[ExportName]]nullではない。
    2. module.ResolveExport(exportEntry.[[ExportName]])をresolutionとする。
    3. resolutionnullまたはambiguousのいずれかである場合、SyntaxError例外を投げる。
    4. Assert: resolutionResolvedBinding Recordである。
  2. Assert: moduleからのすべての名前付きエクスポートは解決可能である。
  3. module.[[Realm]]realmとする。
  4. Assert: realmundefinedではない。
  5. NewModuleEnvironment(realm.[[GlobalEnv]])をenvRecordとする。
  6. module.[[Environment]]envRecordに設定する。
  7. module.[[ImportEntries]]の各ImportEntry Record importEntryについて、次を行う。
    1. GetImportedModule(module, importEntry.[[ModuleRequest]])をimportedModuleとする。
    2. importEntry.[[ImportName]]namespaceである場合、
      1. GetModuleNamespace(importedModule)をnamespaceとする。
      2. envRecord.CreateImmutableBinding(importEntry.[[LocalName]], true)を実行する。
      3. envRecord.InitializeBinding(importEntry.[[LocalName]], namespace)を実行する。
    3. そうでなければ、
      1. Assert: importEntry.[[ImportName]]はStringである。
      2. importedModule.ResolveExport(importEntry.[[ImportName]])をresolutionとする。
      3. resolutionnullまたはambiguousのいずれかである場合、SyntaxError例外を投げる。
      4. resolution.[[BindingName]]namespaceである場合、
        1. GetModuleNamespace(resolution.[[Module]])をnamespaceとする。
        2. envRecord.CreateImmutableBinding(importEntry.[[LocalName]], true)を実行する。
        3. envRecord.InitializeBinding(importEntry.[[LocalName]], namespace)を実行する。
      5. そうでなければ、
        1. CreateImportBinding(envRecord, importEntry.[[LocalName]], resolution.[[Module]], resolution.[[BindingName]])を実行する。
  8. moduleContextを新しいECMAScriptコード実行コンテキストとする。
  9. moduleContextのFunctionをnullに設定する。
  10. Assert: module.[[Realm]]undefinedではない。
  11. moduleContextRealmmodule.[[Realm]]に設定する。
  12. moduleContextのScriptOrModuleをmoduleに設定する。
  13. moduleContextのVariableEnvironmentをmodule.[[Environment]]に設定する。
  14. moduleContextのLexicalEnvironmentをmodule.[[Environment]]に設定する。
  15. moduleContextのPrivateEnvironmentをnullに設定する。
  16. module.[[Context]]moduleContextに設定する。
  17. moduleContextを実行コンテキストスタックにプッシュする。moduleContextは現在、実行中の実行コンテキストである。
  18. module.[[ECMAScriptCode]]codeとする。
  19. codeVarScopedDeclarationsvariableDeclsとする。
  20. declaredVariableNamesを新しい空のListとする。
  21. variableDeclsの各要素variableDeclについて、次を行う。
    1. variableDeclBoundNamesの各要素nameについて、次を行う。
      1. declaredVariableNamesnameを含まない場合、
        1. envRecord.CreateMutableBinding(name, false)を実行する。
        2. envRecord.InitializeBinding(name, undefined)を実行する。
        3. namedeclaredVariableNamesに追加する。
  22. codeLexicallyScopedDeclarationslexicalDeclsとする。
  23. privateEnvnullとする。
  24. lexicalDeclsの各要素lexicalDeclについて、次を行う。
    1. lexicalDeclBoundNamesの各要素nameについて、次を行う。
      1. lexicalDeclIsConstantDeclarationtrueである場合、
        1. envRecord.CreateImmutableBinding(name, true)を実行する。
      2. そうでなければ、
        1. envRecord.CreateMutableBinding(name, false)を実行する。
      3. lexicalDeclFunctionDeclarationGeneratorDeclarationAsyncFunctionDeclaration、またはAsyncGeneratorDeclarationのいずれかである場合、
        1. envRecordおよびprivateEnvを引数として、lexicalDeclInstantiateFunctionObjectfuncObjとする。
        2. envRecord.InitializeBinding(name, funcObj)を実行する。
  25. moduleContextを実行コンテキストスタックから取り除く。
  26. unusedを返す。

16.2.1.7.3.2 ExecuteModule ( [ capability ] )

The ExecuteModule concrete method of a Source Text Module Record module takes optional argument capability (a PromiseCapability Record) and returns either a normal completion containing unused or a throw completion. It performs the following steps when called:

  1. Assert: module はリンク済みであり、そのモジュール環境内の宣言はインスタンス化済みである。
  2. moduleContextmodule.[[Context]] とする。
  3. module.[[HasTLA]]false である場合、then
    1. Assert: capability は存在しない。
    2. envmodule.[[Environment]] とする。
    3. 実行中の実行コンテキストを一時停止する。
    4. moduleContext を実行コンテキストスタックにプッシュする。moduleContext は今や実行中の実行コンテキストである。
    5. resultmodule.[[ECMAScriptCode]]EvaluationCompletion とする。
    6. resultCompletion(DisposeResources(env.[[DisposableResourceStack]], result)) に設定する。
    7. moduleContext を一時停止し、それを実行コンテキストスタックから取り除く。
    8. 現在実行コンテキストスタックの最上位にあるコンテキストを、実行中の実行コンテキストとして再開する。
    9. resultabrupt completion である場合、then
      1. Return ? result.
  4. Else,
    1. Assert: capabilityPromiseCapability Record である。
    2. AsyncBlockStart(capability, module.[[ECMAScriptCode]], moduleContext) を実行する。
  5. unused を返す。

16.2.1.8 Synthetic Module Records

Synthetic Module Recordは、specificationsによって定義されるmoduleに関する情報を表すために使用されます。そのexported namesはcreation時にstaticallyに定義され、一方でそれらに対応するvaluesはSetSyntheticModuleExportを使用して時間とともに変更できます。これはimportsまたはdependenciesを持ちません。

Note
Synthetic Module Recordは、さまざまなmodule typesを定義するために使用できます:例えば、JSON modulesやCSS modulesです。

Table 39で定義されるfieldsに加えて、Synthetic Module RecordsはTable 58に列挙された追加のfieldsを持ちます。

Table 58: Additional Fields of Synthetic Module Records
Field Name Value Type Meaning
[[ExportNames]] a List of Strings moduleのexportsのnames。このlistはduplicatesを含みません。
[[EvaluationSteps]] an Abstract Closure moduleのevaluation時に実行するinitialization logicであり、Synthetic Module Recordを唯一のargumentとして取ります。これは[[ExportNames]]を変更してはなりません。これはabrupt completionを返してもよいです。

16.2.1.8.1 CreateDefaultExportSyntheticModule ( defaultExport )

The abstract operation CreateDefaultExportSyntheticModule takes argument defaultExport (an ECMAScript language value) and returns a Synthetic Module Record. default exportがdefaultExportであるSynthetic Module Recordを作成します。 It performs the following steps when called:

  1. realmcurrent Realm Recordとする。
  2. defaultExportをcaptureし、呼び出されたとき次のstepsを実行する、parameters (module)を持つ新しいAbstract Closure setDefaultExportとする:
    1. SetSyntheticModuleExport(module, "default", defaultExport)を実行する。
    2. NormalCompletion(unused)を返す。
  3. Synthetic Module Record { [[Realm]]: realm, [[Environment]]: empty, [[Namespace]]: empty, [[HostDefined]]: undefined, [[ExportNames]]: « "default" », [[EvaluationSteps]]: setDefaultExport }を返す。

16.2.1.8.2 ParseJSONModule ( source )

The abstract operation ParseJSONModule takes argument source (a String) and returns either a normal completion containing a Synthetic Module Record, or a throw completion. It performs the following steps when called:

  1. parseResultを ? ParseJSON(source) とする。
  2. CreateDefaultExportSyntheticModule(parseResult.[[Value]])を返す。

16.2.1.8.3 SetSyntheticModuleExport ( module, exportName, exportValue )

The abstract operation SetSyntheticModuleExport takes arguments module (a Synthetic Module Record), exportName (a String), and exportValue (an ECMAScript language value) and returns unused. Synthetic Module Recordの既存のexportに対するexported valueをsetまたはchangeするために使用できます。 It performs the following steps when called:

  1. Assert: module.[[ExportNames]]exportNameを含む。
  2. envRecordmodule.[[Environment]]とする。
  3. Assert: envRecordemptyでない。
  4. envRecord.SetMutableBinding(exportName, exportValue, true)を実行する。
  5. unusedを返す。

16.2.1.8.4 Implementation of Module Record Abstract Methods

以下は、Table 40で定義される対応するModule Record abstract methodsを実装するSynthetic Module Recordのconcrete methodsです。

16.2.1.8.4.1 LoadRequestedModules ( [ hostDefined ] )

The LoadRequestedModules concrete method of a Synthetic Module Record module takes optional argument hostDefined (anything) and returns a Promise. It performs the following steps when called:

  1. NOTE: LoadRequestedModulesのこのimplementationはhostDefinedを使用しない。
  2. PromiseResolve(%Promise%, undefined)を返す。
Note
Synthetic Module Recordsはdependenciesを持ちません。

16.2.1.8.4.2 GetExportedNames ( [ exportStarSet ] )

The GetExportedNames concrete method of a Synthetic Module Record module takes optional argument exportStarSet (a List of Source Text Module Records) and returns a List of Strings. It performs the following steps when called:

  1. NOTE: GetExportedNamesのこのimplementationはexportStarSetを使用しない。
  2. module.[[ExportNames]]を返す。

16.2.1.8.4.3 ResolveExport ( exportName [ , resolveSet ] )

The ResolveExport concrete method of a Synthetic Module Record module takes argument exportName (a String) and optional argument resolveSet (a List of Records with fields [[Module]] (a Module Record) and [[ExportName]] (a String)) and returns a ResolvedBinding Record, null, or ambiguous. It performs the following steps when called:

  1. NOTE: ResolveExportのこのimplementationはresolveSetを使用しない。
  2. module.[[ExportNames]]exportNameを含まないなら、nullを返す。
  3. ResolvedBinding Record { [[Module]]: module, [[BindingName]]: exportName }を返す。

16.2.1.8.4.4 Link ( )

The Link concrete method of a Synthetic Module Record module takes no arguments and returns a normal completion containing unused. It performs the following steps when called:

  1. realmmodule.[[Realm]]とする。
  2. envRecordNewModuleEnvironment(realm.[[GlobalEnv]])とする。
  3. module.[[Environment]]envRecordに設定する。
  4. module.[[ExportNames]]の各String exportNameについて、以下を行う
    1. envRecord.CreateMutableBinding(exportName, false)を実行する。
    2. envRecord.InitializeBinding(exportName, undefined)を実行する。
  5. NormalCompletion(unused)を返す。

16.2.1.8.4.5 Evaluate ( )

The Evaluate concrete method of a Synthetic Module Record module takes no arguments and returns a Promise. It performs the following steps when called:

  1. moduleContextを新しいECMAScript code execution contextとする。
  2. moduleContextのFunctionをnullに設定する。
  3. moduleContextRealmmodule.[[Realm]]に設定する。
  4. moduleContextのScriptOrModuleをmoduleに設定する。
  5. moduleContextのVariableEnvironmentをmodule.[[Environment]]に設定する。
  6. moduleContextのLexicalEnvironmentをmodule.[[Environment]]に設定する。
  7. running execution contextをsuspendする。
  8. moduleContextexecution context stackへpushする;moduleContextは現在running execution contextである。
  9. stepsmodule.[[EvaluationSteps]]とする。
  10. resultCompletion(steps(module))とする。
  11. moduleContextをsuspendし、それをexecution context stackからremoveする。
  12. execution context stackのtopにあるcontextをrunning execution contextとしてresumeする。
  13. promiseCapabilityを ! NewPromiseCapability(%Promise%) とする。
  14. IfAbruptRejectPromise(result, promiseCapability)。
  15. Call(promiseCapability.[[Resolve]], undefined, « undefined »)を実行する。
  16. promiseCapability.[[Promise]]を返す。

16.2.1.9 GetImportedModule ( referrer, request )

The abstract operation GetImportedModule takes arguments referrer (a Cyclic Module Record) and request (a ModuleRequest Record) and returns a Module Record. It performs the following steps when called:

  1. recordsを、referrer.[[LoadedModules]]の各LoadedModuleRequest Record rのうち、ModuleRequestsEqual(r, request)がtrueであるものから構成されるListとする。
  2. Assert: このabstract operationをinvokeする前にLoadRequestedModulesreferrer上でsuccessfullyに完了しているため、recordsはちょうど1つの要素を持つ。
  3. recordrecordsの唯一の要素とする。
  4. record.[[Module]]を返す。

16.2.1.10 HostLoadImportedModule ( referrer, moduleRequest, hostDefined, payload )

The host-defined abstract operation HostLoadImportedModule takes arguments referrer (a Script Record, a Cyclic Module Record, or a Realm Record), moduleRequest (a ModuleRequest Record), hostDefined (anything), and payload (a GraphLoadingState Record or a PromiseCapability Record) and returns unused.

Note 1

referrerRealm Recordになり得る場合のexampleはweb browser host内にあります。そこでは、userが次によって与えられるcontrolをclickする場合、

<button type="button" onclick="import('./foo.mjs')">Click me</button>

import() expressionがrunsするとき、active scriptまたはmoduleは存在しません。より一般には、hostがnull ScriptOrModule componentsを持つexecution contextsexecution context stackへpushする任意の状況で、これは発生し得ます。

HostLoadImportedModuleのimplementationは次のrequirementsにconformしなければなりません:

  • host environmentは、FinishLoadingImportedModule(referrer, moduleRequest, payload, result)を実行しなければなりません。ここでresultはloaded Module Record含むnormal completionまたはthrow completionのいずれかであり、synchronouslyまたはasynchronouslyのいずれかで実行されます。
  • このoperationが、次を満たす2つの(referrer, moduleRequest) pairsで複数回callされた場合:

    • first referrerがsecond referrerと同じである;
    • ModuleRequestsEqual(the first moduleRequest, the second moduleRequest)がtrueである;

    かつ、resultnormal completionであるFinishLoadingImportedModule(referrer, moduleRequest, payload, result)を実行する場合、毎回同じresultを伴ってFinishLoadingImportedModule(referrer, moduleRequest, payload, result)を実行しなければなりません。

  • moduleRequest.[[Attributes]]が、entry.[[Key]]"type"であり、entry.[[Value]]"json"であるentry entryを持つ場合、host environmentがFinishLoadingImportedModule(referrer, moduleRequest, payload, result)を実行するとき、resultParseJSONModuleのinvocationによって返されたCompletion Recordまたはthrow completionのいずれかでなければなりません。

  • operationはpayloadFinishLoadingImportedModuleへpass throughされるopaque valueとして扱わなければなりません。

actual processはhost-definedですが、通常はappropriate Module Recordをloadするために必要な任意のI/O operationsを実行することから構成されます。複数の異なる(referrer, moduleRequest.[[Specifier]], moduleRequest.[[Attributes]]) triplesが同じModule Record instanceへmapされる場合があります。actual mapping semanticsはhost-definedですが、通常はmapping processの一部としてspecifierにnormalization processが適用されます。typical normalization processには、relativeおよびabbreviated path specifiersのexpansionなどのactionsが含まれます。

Note 2

上記のtextは、type: "json"でimportされたとき(かつHostLoadImportedModuleがnormallyにcompleteする場合)、hostsがJSON modulesをsupportすることをrequireしますが、type: "json"なしでimportされたときにhostsがJSON modulesをsupportすることをprohibitするものではありません。

16.2.1.11 FinishLoadingImportedModule ( referrer, moduleRequest, payload, result )

The abstract operation FinishLoadingImportedModule takes arguments referrer (a Script Record, a Cyclic Module Record, or a Realm Record), moduleRequest (a ModuleRequest Record), payload (a GraphLoadingState Record or a PromiseCapability Record), and result (either a normal completion containing a Module Record or a throw completion) and returns unused. It performs the following steps when called:

  1. resultnormal completionなら、
    1. referrer.[[LoadedModules]]が、ModuleRequestsEqual(record, moduleRequest)がtrueであるようなLoadedModuleRequest Record recordを含むなら、
      1. Assert: record.[[Module]]result.[[Value]]は同じModule Recordである。
    2. そうでなければ、
      1. LoadedModuleRequest Record { [[Specifier]]: moduleRequest.[[Specifier]], [[Attributes]]: moduleRequest.[[Attributes]], [[Module]]: result.[[Value]] }をreferrer.[[LoadedModules]]へappendする。
  2. payloadGraphLoadingState Recordなら、
    1. ContinueModuleLoading(payload, result)を実行する。
  3. そうでなければ、
    1. ContinueDynamicImport(payload, result)を実行する。
  4. unusedを返す。

16.2.1.12 AllImportAttributesSupported ( attrs )

The abstract operation AllImportAttributesSupported takes argument attrs (a List of ImportAttribute Records) and returns a Boolean. It performs the following steps when called:

  1. supportedHostGetSupportedImportAttributes()とする。
  2. attrsの各ImportAttribute Record attrについて、以下を行う
    1. supportedattr.[[Key]]を含まないなら、falseを返す。
  3. trueを返す。

16.2.1.12.1 HostGetSupportedImportAttributes ( )

The host-defined abstract operation HostGetSupportedImportAttributes takes no arguments and returns a List of Strings. host environmentsがsupportするimport attributesを指定できるようにします。supported keysを持つattributesのみがhostに提供されます。

HostGetSupportedImportAttributesのimplementationは次のrequirementsにconformしなければなりません:

  • これは、それぞれがsupported attributeを示すStringsのListを返さなければなりません。
  • このoperationが呼び出されるたびに、同じcontentsを同じorderで持つ同じListを返さなければなりません。

HostGetSupportedImportAttributesのdefault implementationは、新しい空のListを返すことです。

Note
hostがsupported import attributesを指定することをrequireし、すべてのattributesをhostに渡してhostがhandleしたいものを選ぶようにしない目的は、unsupported attributesが異なるhosts間でconsistentな方法でhandledされることを保証するためです。

16.2.1.13 GetModuleNamespace ( module )

The abstract operation GetModuleNamespace takes argument module (an instance of a concrete subclass of Module Record) and returns a Module Namespace Object. moduleのexportsを表すModule Namespace Objectをretrieveし、初回request時にlazilyに作成して、future retrievalのためにmodule.[[Namespace]]へstoreします。 It performs the following steps when called:

  1. Assert: moduleCyclic Module Recordなら、module.[[Status]]newでもunlinkedでもない。
  2. namespacemodule.[[Namespace]]とする。
  3. namespaceemptyなら、
    1. exportedNamesmodule.GetExportedNames()とする。
    2. unambiguousNamesを新しい空のListとする。
    3. exportedNamesの各要素nameについて、以下を行う
      1. resolutionmodule.ResolveExport(name)とする。
      2. resolutionResolvedBinding Recordなら、nameunambiguousNamesへappendする。
    4. namespaceModuleNamespaceCreate(module, unambiguousNames)に設定する。
  4. namespaceを返す。
Note

GetModuleNamespaceは決してthrowしません。代わりに、unresolvable namesはこの時点で単にnamespaceから除外されます。それらは、どこでもexplicitly requestedされていないambiguous star exportsだけでない限り、後でreal linking errorにつながります。

16.2.1.14 Runtime Semantics: Evaluation

Module : [empty]
  1. undefinedを返す。
ModuleBody : ModuleItemList
  1. resultModuleItemListEvaluationCompletionとする。
  2. resultnormal completionであり、かつresult.[[Value]]emptyであるなら、
    1. undefinedを返す。
  3. resultを返す。
ModuleItemList : ModuleItemList ModuleItem
  1. slModuleItemListの ? Evaluationとする。
  2. sModuleItemEvaluationCompletionとする。
  3. UpdateEmpty(s, sl)を返す。
Note

ModuleItemListの値は、ModuleItemList内で値を生成する最後のitemの値です。

ModuleItem : ImportDeclaration
  1. emptyを返す。

16.2.2 Imports

Syntax

ImportDeclaration : import ImportClause FromClause WithClauseopt ; import ModuleSpecifier WithClauseopt ; ImportClause : ImportedDefaultBinding NameSpaceImport NamedImports ImportedDefaultBinding , NameSpaceImport ImportedDefaultBinding , NamedImports ImportedDefaultBinding : ImportedBinding NameSpaceImport : * as ImportedBinding NamedImports : { } { ImportsList } { ImportsList , } FromClause : from ModuleSpecifier ImportsList : ImportSpecifier ImportsList , ImportSpecifier ImportSpecifier : ImportedBinding ModuleExportName as ImportedBinding ModuleSpecifier : StringLiteral ImportedBinding : BindingIdentifier[~Yield, +Await] WithClause : with { } with { WithEntries ,opt } WithEntries : AttributeKey : StringLiteral AttributeKey : StringLiteral , WithEntries AttributeKey : IdentifierName StringLiteral

16.2.2.1 Static Semantics: Early Errors

ModuleItem : ImportDeclaration WithClause : with { WithEntries ,opt }
  • WithClauseWithClauseToAttributesが、a.[[Key]]b.[[Key]]であるような2つの異なるentries aおよびbを持つ場合、それはSyntax Errorです。

16.2.2.2 Static Semantics: ImportEntries

The syntax-directed operation ImportEntries takes no arguments and returns a List of ImportEntry Records. It is defined piecewise over the following productions:

Module : [empty]
  1. 新しい空のListを返す。
ModuleItemList : ModuleItemList ModuleItem
  1. entries1ModuleItemListImportEntriesとする。
  2. entries2ModuleItemImportEntriesとする。
  3. entries1entries2list-concatenationを返す。
ModuleItem : ExportDeclaration StatementListItem
  1. 新しい空のListを返す。
ImportDeclaration : import ImportClause FromClause WithClauseopt ;
  1. moduleImportDeclarationModuleRequestsの唯一の要素とする。
  2. argument moduleを伴うImportClauseImportEntriesForModuleを返す。
ImportDeclaration : import ModuleSpecifier WithClauseopt ;
  1. 新しい空のListを返す。

16.2.2.3 Static Semantics: ImportEntriesForModule

The syntax-directed operation ImportEntriesForModule takes argument module (a ModuleRequest Record) and returns a List of ImportEntry Records. It is defined piecewise over the following productions:

ImportClause : ImportedDefaultBinding , NameSpaceImport
  1. entries1を、argument moduleを伴うImportedDefaultBindingImportEntriesForModuleとする。
  2. entries2を、argument moduleを伴うNameSpaceImportImportEntriesForModuleとする。
  3. entries1entries2list-concatenationを返す。
ImportClause : ImportedDefaultBinding , NamedImports
  1. entries1を、argument moduleを伴うImportedDefaultBindingImportEntriesForModuleとする。
  2. entries2を、argument moduleを伴うNamedImportsImportEntriesForModuleとする。
  3. entries1entries2list-concatenationを返す。
ImportedDefaultBinding : ImportedBinding
  1. localNameImportedBindingBoundNamesの唯一の要素とする。
  2. defaultEntryImportEntry Record { [[ModuleRequest]]: module, [[ImportName]]: "default", [[LocalName]]: localName }とする。
  3. « defaultEntry »を返す。
NameSpaceImport : * as ImportedBinding
  1. localNameImportedBindingStringValueとする。
  2. entryImportEntry Record { [[ModuleRequest]]: module, [[ImportName]]: namespace, [[LocalName]]: localName }とする。
  3. « entry »を返す。
NamedImports : { }
  1. 新しい空のListを返す。
ImportsList : ImportsList , ImportSpecifier
  1. specs1を、argument moduleを伴うImportsListImportEntriesForModuleとする。
  2. specs2を、argument moduleを伴うImportSpecifierImportEntriesForModuleとする。
  3. specs1specs2list-concatenationを返す。
ImportSpecifier : ImportedBinding
  1. localNameImportedBindingBoundNamesの唯一の要素とする。
  2. entryImportEntry Record { [[ModuleRequest]]: module, [[ImportName]]: localName, [[LocalName]]: localName }とする。
  3. « entry »を返す。
ImportSpecifier : ModuleExportName as ImportedBinding
  1. importNameModuleExportNameStringValueとする。
  2. localNameImportedBindingStringValueとする。
  3. entryImportEntry Record { [[ModuleRequest]]: module, [[ImportName]]: importName, [[LocalName]]: localName }とする。
  4. « entry »を返す。

16.2.2.4 Static Semantics: WithClauseToAttributes

The syntax-directed operation WithClauseToAttributes takes no arguments and returns a List of ImportAttribute Records. It is defined piecewise over the following productions:

WithClause : with { }
  1. 新しい空のListを返す。
WithClause : with { WithEntries ,opt }
  1. attrsWithEntriesWithClauseToAttributesとする。
  2. attrsを、それらの[[Key]] fieldのlexicographic orderに従ってsortする。このとき各fieldの値をUTF-16 code unit valuesのsequenceとして扱う。NOTE: このsortingは、hostsがattributesがenumeratedされるorderに基づいてbehaviourを変更することをprohibitedされる点でのみobservableである。
  3. attrsを返す。
WithEntries : AttributeKey : StringLiteral
  1. keyAttributeKeyPropNameとする。
  2. entryImportAttribute Record { [[Key]]: key, [[Value]]: StringLiteralSV }とする。
  3. « entry »を返す。
WithEntries : AttributeKey : StringLiteral , WithEntries
  1. keyAttributeKeyPropNameとする。
  2. entryImportAttribute Record { [[Key]]: key, [[Value]]: StringLiteralSV }とする。
  3. restWithEntriesWithClauseToAttributesとする。
  4. « entry »とrestlist-concatenationを返す。

16.2.3 Exports

Syntax

ExportDeclaration : export ExportFromClause FromClause WithClauseopt ; export NamedExports ; export VariableStatement[~Yield, +Await] export [lookahead ∉ { using, await }] Declaration[~Yield, +Await] export default HoistableDeclaration[~Yield, +Await, +Default] export default ClassDeclaration[~Yield, +Await, +Default] export default [lookahead ∉ { function, async [no LineTerminator here] function, class }] AssignmentExpression[+In, ~Yield, +Await] ; ExportFromClause : * * as ModuleExportName NamedExports NamedExports : { } { ExportsList } { ExportsList , } ExportsList : ExportSpecifier ExportsList , ExportSpecifier ExportSpecifier : ModuleExportName ModuleExportName as ModuleExportName

16.2.3.1 Static Semantics: Early Errors

ExportDeclaration : export NamedExports ; Note

上記のruleは、NamedExportsの各ReferencedBindingsIdentifierReferenceとして扱われることを意味します。

16.2.3.2 Static Semantics: ExportedBindings

The syntax-directed operation ExportedBindings takes no arguments and returns a List of Strings.

Note

ExportedBindingsは、ModuleExportedNamesにexplicitlyに関連付けられたlocally bound namesです。

It is defined piecewise over the following productions:

ModuleItemList : ModuleItemList ModuleItem
  1. names1ModuleItemListExportedBindingsとする。
  2. names2ModuleItemExportedBindingsとする。
  3. names1names2list-concatenationを返す。
ModuleItem : ImportDeclaration StatementListItem
  1. 新しい空のListを返す。
ExportDeclaration : export ExportFromClause FromClause WithClauseopt ;
  1. 新しい空のListを返す。
ExportDeclaration : export NamedExports ;
  1. NamedExportsExportedBindingsを返す。
ExportDeclaration : export VariableStatement
  1. VariableStatementBoundNamesを返す。
ExportDeclaration : export Declaration
  1. DeclarationBoundNamesを返す。
ExportDeclaration : export default HoistableDeclaration export default ClassDeclaration export default AssignmentExpression ;
  1. this ExportDeclarationBoundNamesを返す。
NamedExports : { }
  1. 新しい空のListを返す。
ExportsList : ExportsList , ExportSpecifier
  1. names1ExportsListExportedBindingsとする。
  2. names2ExportSpecifierExportedBindingsとする。
  3. names1names2list-concatenationを返す。
ExportSpecifier : ModuleExportName
  1. 唯一の要素がModuleExportNameStringValueであるListを返す。
ExportSpecifier : ModuleExportName as ModuleExportName
  1. 唯一の要素が最初のModuleExportNameStringValueであるListを返す。

16.2.3.3 Static Semantics: ExportedNames

The syntax-directed operation ExportedNames takes no arguments and returns a List of Strings.

Note

ExportedNamesは、Moduleがそのlocal name bindingsの1つへexplicitlyにmapするexternally visible namesです。

It is defined piecewise over the following productions:

ModuleItemList : ModuleItemList ModuleItem
  1. names1ModuleItemListExportedNamesとする。
  2. names2ModuleItemExportedNamesとする。
  3. names1names2list-concatenationを返す。
ModuleItem : ExportDeclaration
  1. ExportDeclarationExportedNamesを返す。
ModuleItem : ImportDeclaration StatementListItem
  1. 新しい空のListを返す。
ExportDeclaration : export ExportFromClause FromClause WithClauseopt ;
  1. ExportFromClauseExportedNamesを返す。
ExportFromClause : *
  1. 新しい空のListを返す。
ExportFromClause : * as ModuleExportName
  1. 唯一の要素がModuleExportNameStringValueであるListを返す。
ExportFromClause : NamedExports
  1. NamedExportsExportedNamesを返す。
ExportDeclaration : export VariableStatement
  1. VariableStatementBoundNamesを返す。
ExportDeclaration : export Declaration
  1. DeclarationBoundNamesを返す。
ExportDeclaration : export default HoistableDeclaration export default ClassDeclaration export default AssignmentExpression ;
  1. « "default" »を返す。
NamedExports : { }
  1. 新しい空のListを返す。
ExportsList : ExportsList , ExportSpecifier
  1. names1ExportsListExportedNamesとする。
  2. names2ExportSpecifierExportedNamesとする。
  3. names1names2list-concatenationを返す。
ExportSpecifier : ModuleExportName
  1. 唯一の要素がModuleExportNameStringValueであるListを返す。
ExportSpecifier : ModuleExportName as ModuleExportName
  1. 唯一の要素が2番目のModuleExportNameStringValueであるListを返す。

16.2.3.4 Static Semantics: ExportEntries

The syntax-directed operation ExportEntries takes no arguments and returns a List of ExportEntry Records. It is defined piecewise over the following productions:

Module : [empty]
  1. 新しい空のListを返す。
ModuleItemList : ModuleItemList ModuleItem
  1. entries1ModuleItemListExportEntriesとする。
  2. entries2ModuleItemExportEntriesとする。
  3. entries1entries2list-concatenationを返す。
ModuleItem : ImportDeclaration StatementListItem
  1. 新しい空のListを返す。
ExportDeclaration : export ExportFromClause FromClause WithClauseopt ;
  1. moduleExportDeclarationModuleRequestsの唯一の要素とする。
  2. argument moduleを伴うExportFromClauseExportEntriesForModuleを返す。
ExportDeclaration : export NamedExports ;
  1. argument nullを伴うNamedExportsExportEntriesForModuleを返す。
ExportDeclaration : export VariableStatement
  1. entriesを新しい空のListとする。
  2. namesVariableStatementBoundNamesとする。
  3. namesの各要素nameについて、以下を行う
    1. ExportEntry Record { [[ModuleRequest]]: null, [[ImportName]]: null, [[LocalName]]: name, [[ExportName]]: name }をentriesへappendする。
  4. entriesを返す。
ExportDeclaration : export Declaration
  1. entriesを新しい空のListとする。
  2. namesDeclarationBoundNamesとする。
  3. namesの各要素nameについて、以下を行う
    1. ExportEntry Record { [[ModuleRequest]]: null, [[ImportName]]: null, [[LocalName]]: name, [[ExportName]]: name }をentriesへappendする。
  4. entriesを返す。
ExportDeclaration : export default HoistableDeclaration
  1. namesHoistableDeclarationBoundNamesとする。
  2. localNamenamesの唯一の要素とする。
  3. 唯一の要素が新しいExportEntry Record { [[ModuleRequest]]: null, [[ImportName]]: null, [[LocalName]]: localName, [[ExportName]]: "default" }であるListを返す。
ExportDeclaration : export default ClassDeclaration
  1. namesClassDeclarationBoundNamesとする。
  2. localNamenamesの唯一の要素とする。
  3. 唯一の要素が新しいExportEntry Record { [[ModuleRequest]]: null, [[ImportName]]: null, [[LocalName]]: localName, [[ExportName]]: "default" }であるListを返す。
ExportDeclaration : export default AssignmentExpression ;
  1. entryExportEntry Record { [[ModuleRequest]]: null, [[ImportName]]: null, [[LocalName]]: "*default*", [[ExportName]]: "default" }とする。
  2. « entry »を返す。
Note

"*default*"は、この仕様内でanonymous default export valuesに対するsynthetic nameとして使用されます。詳細についてはthis noteを参照してください。

16.2.3.5 Static Semantics: ExportEntriesForModule

The syntax-directed operation ExportEntriesForModule takes argument module (a ModuleRequest Record or null) and returns a List of ExportEntry Records. It is defined piecewise over the following productions:

ExportFromClause : *
  1. entryExportEntry Record { [[ModuleRequest]]: module, [[ImportName]]: all-but-default, [[LocalName]]: null, [[ExportName]]: null }とする。
  2. « entry »を返す。
ExportFromClause : * as ModuleExportName
  1. exportNameModuleExportNameStringValueとする。
  2. entryExportEntry Record { [[ModuleRequest]]: module, [[ImportName]]: namespace, [[LocalName]]: null, [[ExportName]]: exportName }とする。
  3. « entry »を返す。
NamedExports : { }
  1. 新しい空のListを返す。
ExportsList : ExportsList , ExportSpecifier
  1. specs1を、argument moduleを伴うExportsListExportEntriesForModuleとする。
  2. specs2を、argument moduleを伴うExportSpecifierExportEntriesForModuleとする。
  3. specs1specs2list-concatenationを返す。
ExportSpecifier : ModuleExportName
  1. sourceNameModuleExportNameStringValueとする。
  2. modulenullなら、
    1. localNamesourceNameとする。
    2. importNamenullとする。
  3. そうでなければ、
    1. localNamenullとする。
    2. importNamesourceNameとする。
  4. 唯一の要素が新しいExportEntry Record { [[ModuleRequest]]: module, [[ImportName]]: importName, [[LocalName]]: localName, [[ExportName]]: sourceName }であるListを返す。
ExportSpecifier : ModuleExportName as ModuleExportName
  1. sourceNameを最初のModuleExportNameStringValueとする。
  2. exportNameを2番目のModuleExportNameStringValueとする。
  3. modulenullなら、
    1. localNamesourceNameとする。
    2. importNamenullとする。
  4. そうでなければ、
    1. localNamenullとする。
    2. importNamesourceNameとする。
  5. 唯一の要素が新しいExportEntry Record { [[ModuleRequest]]: module, [[ImportName]]: importName, [[LocalName]]: localName, [[ExportName]]: exportName }であるListを返す。

16.2.3.6 Static Semantics: ReferencedBindings

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

NamedExports : { }
  1. 新しい空のListを返す。
ExportsList : ExportsList , ExportSpecifier
  1. names1ExportsListReferencedBindingsとする。
  2. names2ExportSpecifierReferencedBindingsとする。
  3. names1names2list-concatenationを返す。
ExportSpecifier : ModuleExportName as ModuleExportName
  1. 最初のModuleExportNameReferencedBindingsを返す。
ModuleExportName : IdentifierName
  1. 唯一の要素がIdentifierNameであるListを返す。
ModuleExportName : StringLiteral
  1. 唯一の要素がStringLiteralであるListを返す。

16.2.3.7 Runtime Semantics: Evaluation

ExportDeclaration : export ExportFromClause FromClause WithClauseopt ; export NamedExports ;
  1. emptyを返す。
ExportDeclaration : export VariableStatement
  1. VariableStatementの ? Evaluationを返す。
ExportDeclaration : export Declaration
  1. Declarationの ? Evaluationを返す。
ExportDeclaration : export default HoistableDeclaration
  1. HoistableDeclarationの ? Evaluationを返す。
ExportDeclaration : export default ClassDeclaration
  1. valueClassDeclarationの ? BindingClassDeclarationEvaluationとする。
  2. classNameClassDeclarationBoundNamesの唯一の要素とする。
  3. className"*default*"なら、
    1. envRecordrunning execution contextのLexicalEnvironmentとする。
    2. InitializeBoundName("*default*", value, envRecord)を実行する。
  4. emptyを返す。
ExportDeclaration : export default AssignmentExpression ;
  1. IsAnonymousFunctionDefinition(AssignmentExpression)がtrueなら、
    1. valueを、argument "default"を伴うAssignmentExpressionの ? NamedEvaluationとする。
  2. そうでなければ、
    1. rhsAssignmentExpressionの ? Evaluationとする。
    2. valueを ? GetValue(rhs) とする。
  3. envRecordrunning execution contextのLexicalEnvironmentとする。
  4. InitializeBoundName("*default*", value, envRecord)を実行する。
  5. emptyを返す。

17 Error Handling and Language Extensions

implementationは、ほとんどのerrorsを、関連するECMAScript language constructが評価される時点でreportしなければなりません。early errorは、そのerrorを含むScript内のどのconstructのevaluationよりも前にdetectおよびreportできるerrorです。early errorの存在は、そのconstructのevaluationを妨げます。implementationは、ParseScriptでそのScriptをparseする一部として、Script内のearly errorsをreportしなければなりません。Module内のearly errorsは、Moduleが評価されるはずの時点でreportされ、Moduleは決してinitializedされません。eval code内のearly errorsは、evalが呼び出された時点でreportされ、eval codeのevaluationを妨げます。early errorsでないすべてのerrorsはruntime errorsです。

implementationは、この仕様の“Static Semantics: Early Errors” subclauseに列挙されているconditionの任意のoccurrenceをearly errorとしてreportしなければなりません。

implementationは、compilerがあるconstructがどのようなcircumstancesの下でもerrorなしにexecuteできないことをproveできる場合であっても、他の種類のerrorsをearly errorsとして扱ってはなりません。implementationはそのような場合にearly warningを発行してもよいですが、関連するconstructが実際にexecutedされるまでerrorをreportすべきではありません。

implementationは、以下を除き、指定された通りにすべてのerrorsをreportしなければなりません:

17.1 Forbidden Extensions

implementationは、以下の方法でこの仕様を拡張してはなりません:

18 ECMAScript Standard Built-in Objects

ECMAScript ScriptまたはModuleがexecutionを開始するときには常に利用可能な特定のbuilt-in objectsがあります。その1つであるglobal objectは、executing programのglobal environmentの一部です。その他は、global objectのinitial propertiesとして、またはaccessible built-in objectsのpropertiesとして間接的にaccessできます。

特に指定されない限り、functionとしてcallableなbuilt-in objectは、10.3で記述されるcharacteristicsを持つbuilt-in function objectです。特に指定されない限り、built-in objectの[[Extensible]] internal slotはinitiallyにtrueというvalueを持ちます。すべてのbuilt-in function object[[Realm]] internal slotを持ち、そのvalueは、そのobjectがinitiallyに作成されたrealmRealm Recordです。

多くのbuilt-in objectsはfunctionsです:それらはargumentsを伴ってinvokedできます。さらにその一部はconstructorsです:それらはnew operatorとともに使用することを意図したfunctionsです。各built-in functionについて、この仕様は、そのfunctionが要求するargumentsと、そのfunction objectのpropertiesを記述します。各built-in constructorについて、この仕様はさらに、そのconstructorのprototype objectのpropertiesと、そのconstructorをinvokeするnew expressionによって返される特定のobject instancesのpropertiesを記述します。

特定のfunctionのdescriptionで別途指定されない限り、built-in functionまたはconstructorに、そのfunctionが要求すると指定される数より少ないargumentsが与えられた場合、そのfunctionまたはconstructorは、十分な追加argumentsが与えられ、それらの各argumentがundefined valueであったかのように、正確にbehaveしなければなりません。そのようなmissing argumentsは“not present”であるとみなされ、specification algorithmsによってそのようにidentifyされる場合があります。特定のfunctionのdescriptionにおいて、terms “this value”および“NewTarget”は、10.3で与えられる意味を持ちます。

特定のfunctionのdescriptionで別途指定されない限り、記述されるbuilt-in functionまたはconstructorに、そのfunctionが許すと指定される数より多いargumentsが与えられた場合、extra argumentsはcallによってevaluatedされ、その後functionによってignoredされます。ただし、implementationは、extra argumentの存在だけを根拠としてTypeError例外をthrowするものではない限り、そのようなargumentsに関係するimplementation specific behaviourを定義してもよいです。

Note 1

built-in functionsのsetに追加のcapabilitiesを加えるimplementationsは、既存のfunctionsに新しいparametersを追加するのではなく、新しいfunctionsを追加することによってそれを行うことが推奨されます。

特に指定されない限り、すべてのbuilt-in functionおよびすべてのbuilt-in constructorは、式Function.prototype20.2.3)のinitial valueであるFunction prototype objectを、その[[Prototype]] internal slotのvalueとして持ちます。

特に指定されない限り、すべてのbuilt-in prototype objectは、Object prototype object自体を除き、式Object.prototype20.1.3)のinitial valueであるObject prototype objectを、その[[Prototype]] internal slotのvalueとして持ちます。

この仕様がbuilt-in constructorのbehaviourをalgorithm stepsによって定義する場合、それは[[Call]][[Construct]]の両方のpurposesにおけるそのbehaviourです。そのようなalgorithmが2つの場合を区別する必要がある場合、NewTargetがundefinedであるかどうかをcheckし、これは[[Call]] invocationを示します。

constructorsとしてidentifyされていないbuilt-in function objectsは、特定のfunctionのdescriptionで別途指定されない限り、[[Construct]] internal methodをimplementしません。

constructorsでないbuilt-in function objectsは、特定のfunctionのdescriptionで別途指定されない限り、"prototype" propertyを持ちません。

この仕様で定義される各built-in functionは、CreateBuiltinFunction abstract operation(10.3.4)をcallすることによって作成されます。lengthおよびname parametersのvaluesは、以下で議論される"length"および"name" propertiesのinitial valuesです。prefix parameterのvaluesも同様に以下で議論されます。

constructorsを含むすべてのbuilt-in function objectは、そのvalueがnon-negative integral Numberである"length" propertyを持ちます。特に指定されない限り、このvalueは、function descriptionのsubclause headingに示されるrequired parametersの数です。Optional parametersおよびrest parametersはparameter countに含まれません。

Note 2

例えば、Array prototype object"map" propertyのinitial valueであるfunction objectは、subclause heading «Array.prototype.map (callback [ , thisArg])» の下で記述され、そこには2つのnamed arguments callbackおよびthisArgが示されており、後者はoptionalです;したがって、そのfunction object"length" propertyのvalueは1𝔽です。

特に指定されない限り、built-in function object"length" propertyはattributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }を持ちます。

constructorsを含むすべてのbuilt-in function objectは、そのvalueがStringである"name" propertyを持ちます。特に指定されない限り、このvalueは、この仕様でそのfunctionに与えられるnameです。anonymous functionsとしてidentifyされるfunctionsは、empty Stringを"name" propertyのvalueとして使用します。objectsのpropertiesとして指定されるfunctionsについては、name valueは、そのfunctionにaccessするために使用されるproperty name stringです。built-in propertiesのgetまたはset accessor functionsとして指定されるfunctionsは、CreateBuiltinFunctionをcallするときにprefix parameterへ"get"または"set"(それぞれ)が渡されます。

"name" propertyのvalueは、property keyがSymbol valueである各built-in functionsについてexplicitlyに指定されます。そのようなexplicitly specified valueがprefix "get "または"set "で始まり、それが指定されるfunctionがbuilt-in propertyのgetまたはset accessor functionである場合、prefixを除いたvalueがname parameterへ渡され、value "get"または"set"(それぞれ)がCreateBuiltinFunctionをcallするときにprefix parameterへ渡されます。

特に指定されない限り、built-in function object"name" propertyはattributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }を持ちます。

clauses 19から28まで、およびAnnex B.2に記述されるその他すべてのdata propertyは、特に指定されない限りattributes { [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: true }を持ちます。

clauses 19から28まで、およびAnnex B.2に記述されるすべてのaccessor propertyは、特に指定されない限りattributes { [[Enumerable]]: false, [[Configurable]]: true }を持ちます。get accessor functionだけが記述されている場合、set accessor functionはdefault valueであるundefinedです。set accessorだけが記述されている場合、get accessorはdefault valueであるundefinedです。

19 The Global Object

global objectは:

19.1 Value Properties of the Global Object

19.1.1 globalThis

Realm Record realm内のglobal object"globalThis" propertyのinitial valueは、realm.[[GlobalEnv]].[[GlobalThisValue]]です。

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

19.1.2 Infinity

global object"Infinity" propertyのinitial valueは+∞𝔽6.1.6.1を参照)です。

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

19.1.3 NaN

global object"NaN" propertyのinitial valueはNaN6.1.6.1を参照)です。

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

19.1.4 undefined

global object"undefined" propertyのinitial valueはundefined6.1.1を参照)です。

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

19.2 Function Properties of the Global Object

19.2.1 eval ( source )

このfunctionは%eval% intrinsic objectです。

これは呼び出されたとき、次のstepsを実行します:

  1. PerformEval(source, false, false)を返す。

19.2.1.1 PerformEval ( source, strictCaller, direct )

The abstract operation PerformEval takes arguments source (an ECMAScript language value), strictCaller (a Boolean), and direct (a Boolean) and returns either a normal completion containing an ECMAScript language value or a throw completion. It performs the following steps when called:

  1. Assert: directfalseなら、strictCallerfalseである。
  2. sourceがStringでないなら、sourceを返す。
  3. evalRealmcurrent Realm Recordとする。
  4. NOTE: direct evalの場合、evalRealmevalのcallerとeval function自身の両方のrealmである。
  5. HostEnsureCanCompileStrings(evalRealm, « », source, direct)を実行する。
  6. inFuncfalseとする。
  7. inMethodfalseとする。
  8. inDerivedCtorfalseとする。
  9. inClassFieldInitializerfalseとする。
  10. directtrueなら、
    1. thisEnvRecordGetThisEnvironment()とする。
    2. thisEnvRecordFunction Environment Recordなら、
      1. functhisEnvRecord.[[FunctionObject]]とする。
      2. inFunctrueに設定する。
      3. inMethodthisEnvRecord.HasSuperBinding()に設定する。
      4. func.[[ConstructorKind]]derivedなら、inDerivedCtortrueに設定する。
      5. classFieldInitializerNamefunc.[[ClassFieldInitializerName]]とする。
      6. classFieldInitializerNameemptyでないなら、inClassFieldInitializertrueに設定する。
  11. 次のsubstepsをimplementation-defined orderで実行し、parsingとerror detectionをinterleaveしてもよい:
    1. scriptParseText(source, Script)とする。
    2. scriptがerrorsのListなら、SyntaxError例外をthrowする。
    3. script Contains ScriptBodyfalseなら、undefinedを返す。
    4. bodyscriptScriptBodyとする。
    5. inFuncfalseであり、body Contains NewTargetであるなら、SyntaxError例外をthrowする。
    6. inMethodfalseであり、body Contains SuperPropertyであるなら、SyntaxError例外をthrowする。
    7. inDerivedCtorfalseであり、body Contains SuperCallであるなら、SyntaxError例外をthrowする。
    8. inClassFieldInitializertrueであり、bodyContainsArgumentstrueであるなら、SyntaxError例外をthrowする。
  12. strictCallertrueなら、strictEvaltrueとする。
  13. そうでなければ、strictEvalscriptScriptIsStrictとする。
  14. runningContextrunning execution contextとする。
  15. NOTE: directtrueなら、runningContextdirect evalを実行したexecution contextである。directfalseなら、runningContexteval functionのinvocationに対するexecution contextである。
  16. directtrueなら、
    1. lexicalEnvNewDeclarativeEnvironment(runningContextのLexicalEnvironment)とする。
    2. variableEnvrunningContextのVariableEnvironmentとする。
    3. privateEnvrunningContextのPrivateEnvironmentとする。
  17. そうでなければ、
    1. lexicalEnvNewDeclarativeEnvironment(evalRealm.[[GlobalEnv]])とする。
    2. variableEnvevalRealm.[[GlobalEnv]]とする。
    3. privateEnvnullとする。
  18. strictEvaltrueなら、variableEnvlexicalEnvに設定する。
  19. runningContextがまだsuspendedでないなら、runningContextをsuspendする。
  20. evalContextを新しいECMAScript code execution contextとする。
  21. evalContextのFunctionをnullに設定する。
  22. evalContextRealmevalRealmに設定する。
  23. evalContextのScriptOrModuleをrunningContextのScriptOrModuleに設定する。
  24. evalContextのVariableEnvironmentをvariableEnvに設定する。
  25. evalContextのLexicalEnvironmentをlexicalEnvに設定する。
  26. evalContextのPrivateEnvironmentをprivateEnvに設定する。
  27. evalContextexecution context stackへpushする;evalContextは現在running execution contextである。
  28. resultCompletion(EvalDeclarationInstantiation(body, variableEnv, lexicalEnv, privateEnv, strictEval))とする。
  29. resultnormal completionなら、
    1. resultCompletion(bodyEvaluation)に設定する。
  30. resultnormal completionであり、result.[[Value]]emptyであるなら、
    1. resultNormalCompletion(undefined)に設定する。
  31. evalContextをsuspendし、execution context stackからremoveする。
  32. execution context stackのtopにあるcontextをrunning execution contextとしてresumeする。
  33. resultを返す。
Note

calling contextのcodeまたはeval codeのいずれかがstrict mode codeである場合、eval codeは、evalをinvokeしたcalling contextのvariable environment内にvariableまたはfunction bindingsをinstantiateできません。代わりに、そのようなbindingsはeval codeからのみaccessibleな新しいVariableEnvironment内にinstantiatedされます。letconst、またはclass declarationsによってintroducedされるbindingsは、常に新しいLexicalEnvironment内にinstantiatedされます。

19.2.1.2 HostEnsureCanCompileStrings ( calleeRealm, paramStrings, bodyString, direct )

The host-defined abstract operation HostEnsureCanCompileStrings takes arguments calleeRealm (a Realm Record), paramStrings (a List of Strings), bodyString (a String), and direct (a Boolean) and returns either a normal completion containing unused or a throw completion. developersがstringsをECMAScript codeとしてinterpretおよびevaluateできるようにする特定のECMAScript functionsを、host environmentsがblockできるようにします。

paramStringsは、function constructorsのいずれかを使用するとき、parameters listをbuildするためにconcatenateされるstringsを表します。bodyStringは、function bodyまたはeval callに渡されるstringを表します。 directは、evaluationがdirect evalであるかどうかを示します。

HostEnsureCanCompileStringsのdefault implementationはNormalCompletion(unused)を返すことです。

19.2.1.3 EvalDeclarationInstantiation ( body, variableEnv, lexicalEnv, privateEnv, strict )

The abstract operation EvalDeclarationInstantiation takes arguments body (a ScriptBody Parse Node), variableEnv (an Environment Record), lexicalEnv (a Declarative Environment Record), privateEnv (a PrivateEnvironment Record or null), and strict (a Boolean) and returns either a normal completion containing unused or a throw completion. It performs the following steps when called:

  1. bodyVarDeclaredNamesvariableNamesとする。
  2. bodyVarScopedDeclarationsvariableDeclsとする。
  3. strictfalseである場合、
    1. variableEnvGlobal Environment Recordである場合、
      1. variableNamesの各要素nameについて、次を行う。
        1. HasLexicalDeclaration(variableEnv, name)がtrueである場合、SyntaxError例外を投げる。
        2. NOTE: evalは、グローバルlexical宣言によってシャドーイングされることになるグローバルvar宣言を作成しない。
    2. lexicalEnvthisEnvとする。
    3. Assert: 次のループは終了する。
    4. thisEnvvariableEnvが同じEnvironment Recordでない間、繰り返す。
      1. thisEnvObject Environment Recordでない場合、
        1. NOTE: with文の環境はlexical宣言を含むことができないため、var/letの巻き上げの競合を確認する必要はない。
        2. variableNamesの各要素nameについて、次を行う。
          1. thisEnv.HasBinding(name)がtrueである場合、
            1. ホストがWebブラウザである、またはその他の形でCatch Blocks内のVariableStatementsをサポートする場合、
              1. thisEnvCatch節のEnvironment Recordでない場合、SyntaxError例外を投げる。
            2. そうでなければ、
              1. SyntaxError例外を投げる。
          2. NOTE: direct evalは、同名のlexical宣言を越えてvar宣言を巻き上げない。
      2. thisEnvthisEnv.[[OuterEnv]]に設定する。
  4. privateIdentifiersを新しい空のListとする。
  5. privateEnvpointerとする。
  6. pointernullでない間、繰り返す。
    1. pointer.[[Names]]の各Private Name bindingについて、次を行う。
      1. privateIdentifiersbinding.[[Description]]を含まない場合、binding.[[Description]]privateIdentifiersに追加する。
    2. pointerpointer.[[OuterPrivateEnvironment]]に設定する。
  7. privateIdentifiersを引数とするbodyAllPrivateIdentifiersValidfalseである場合、SyntaxError例外を投げる。
  8. funcsToInitializeを新しい空のListとする。
  9. declaredFuncNamesを新しい空のListとする。
  10. variableDeclsの各要素variableDeclについて、Listの逆順で、次を行う。
    1. variableDeclVariableDeclarationForBinding、またはBindingIdentifierのいずれでもない場合、
      1. Assert: variableDeclは、FunctionDeclarationGeneratorDeclarationAsyncFunctionDeclaration、またはAsyncGeneratorDeclarationのいずれかである。
      2. NOTE: 同じ名前に対して複数の関数宣言がある場合、最後の宣言が使用される。
      3. variableDeclBoundNamesの唯一の要素をfuncNameとする。
      4. declaredFuncNamesfuncNameを含まない場合、
        1. variableEnvGlobal Environment Recordである場合、
          1. CanDeclareGlobalFunction(variableEnv, funcName)をfuncDefinableとする。
          2. funcDefinablefalseである場合、TypeError例外を投げる。
        2. funcNamedeclaredFuncNamesに追加する。
        3. variableDeclfuncsToInitializeの最初の要素として挿入する。
  11. declaredVariableNamesを新しい空のListとする。
  12. variableDeclsの各要素variableDeclについて、次を行う。
    1. variableDeclVariableDeclarationForBinding、またはBindingIdentifierのいずれかである場合、
      1. variableDeclBoundNamesの各String nameについて、次を行う。
        1. declaredFuncNamesnameを含まない場合、
          1. variableEnvGlobal Environment Recordである場合、
            1. CanDeclareGlobalVar(variableEnv, name)をvariableDefinableとする。
            2. variableDefinablefalseである場合、TypeError例外を投げる。
          2. declaredVariableNamesnameを含まない場合、
            1. namedeclaredVariableNamesに追加する。
  13. strictfalseであり、かつホストがWebブラウザである、またはその他の形でBlock-Level Function Declarations Web Legacy Compatibility Semanticsをサポートする場合、
    1. declaredFuncNamesdeclaredVariableNameslist-concatenationdeclaredFuncOrVariableNamesとする。
    2. body Contains xtrueであるような任意のBlockCaseClause、またはDefaultClause xStatementListに直接含まれる各FunctionDeclaration funcDeclについて、次を行う。
      1. funcDeclBindingIdentifierStringValuefuncNameとする。
      2. FunctionDeclaration funcDeclを、funcNameBindingIdentifierとして持つVariableStatementに置き換えても、bodyに対してEarly Errorsが発生しない場合、
        1. bindingExistsfalseとする。
        2. thisEnvlexicalEnvに設定する。
        3. Assert: 次のループは終了する。
        4. thisEnvvariableEnvでない間、繰り返す。
          1. thisEnvObject Environment Recordでない場合、
            1. thisEnv.HasBinding(funcName)がtrueである場合、
              1. ホストがWebブラウザである、またはその他の形でCatch Blocks内のVariableStatementsをサポートする場合、
                1. thisEnvCatch節のEnvironment Recordでない場合、bindingExiststrueに設定する。
              2. そうでなければ、
                1. bindingExiststrueに設定する。
          2. thisEnvthisEnv.[[OuterEnv]]に設定する。
        5. bindingExistsfalseであり、かつvariableEnvGlobal Environment Recordである場合、
          1. HasLexicalDeclaration(variableEnv, funcName)がfalseである場合、
            1. CanDeclareGlobalVar(variableEnv, funcName)をfuncDefinableとする。
          2. そうでなければ、
            1. funcDefinablefalseとする。
        6. そうでなければ、
          1. funcDefinabletrueとする。
        7. bindingExistsfalseであり、かつfuncDefinabletrueである場合、
          1. declaredFuncOrVariableNamesfuncNameを含まない場合、
            1. variableEnvGlobal Environment Recordである場合、
              1. CreateGlobalVarBinding(variableEnv, funcName, true)を実行する。
            2. そうでなければ、
              1. variableEnv.HasBinding(funcName)をbindingExistsに設定する。
              2. bindingExistsfalseである場合、
                1. variableEnv.CreateMutableBinding(funcName, true)を実行する。
                2. variableEnv.InitializeBinding(funcName, undefined)を実行する。
            3. funcNamedeclaredFuncOrVariableNamesに追加する。
          2. FunctionDeclaration funcDeclが評価されるとき、15.2.6で提供されるFunctionDeclaration Evaluationアルゴリズムの代わりに、次のステップを実行する。
            1. 実行中の実行コンテキストのVariableEnvironmentをglobalEnvとする。
            2. 実行中の実行コンテキストのLexicalEnvironmentをblockEnvとする。
            3. blockEnv.GetBindingValue(funcName, false)をfuncObjとする。
            4. globalEnv.SetMutableBinding(funcName, funcObj, false)を実行する。
            5. unusedを返す。
  14. NOTE: variableEnvGlobal Environment Recordであり、かつグローバルオブジェクトがProxy exotic objectである場合を除き、このアルゴリズムステップ以降に異常終了は発生しない。
  15. bodyLexicallyScopedDeclarationslexicalDeclsとする。
  16. lexicalDeclsの各要素lexicalDeclについて、次を行う。
    1. NOTE: Lexically declared nameは、ここでインスタンス化されるだけで、初期化されない。
    2. lexicalDeclBoundNamesの各要素nameについて、次を行う。
      1. lexicalDeclIsConstantDeclarationtrueである場合、
        1. lexicalEnv.CreateImmutableBinding(name, true)を実行する。
      2. そうでなければ、
        1. lexicalEnv.CreateMutableBinding(name, false)を実行する。
  17. funcsToInitializeの各Parse Node funcDeclについて、次を行う。
    1. funcDeclBoundNamesの唯一の要素をfuncNameとする。
    2. lexicalEnvおよびprivateEnvを引数として、funcDeclInstantiateFunctionObjectfuncObjとする。
    3. variableEnvGlobal Environment Recordである場合、
      1. CreateGlobalFunctionBinding(variableEnv, funcName, funcObj, true)を実行する。
    4. そうでなければ、
      1. variableEnv.HasBinding(funcName)をbindingExistsとする。
      2. bindingExistsfalseである場合、
        1. NOTE: 次の呼び出しは、ステップ14に先立つ検証により、abrupt completionを返すことができない。
        2. variableEnv.CreateMutableBinding(funcName, true)を実行する。
        3. variableEnv.InitializeBinding(funcName, funcObj)を実行する。
      3. そうでなければ、
        1. variableEnv.SetMutableBinding(funcName, funcObj, false)を実行する。
  18. declaredVariableNamesの各String variableNameについて、次を行う。
    1. variableEnvGlobal Environment Recordである場合、
      1. CreateGlobalVarBinding(variableEnv, variableName, true)を実行する。
    2. そうでなければ、
      1. variableEnv.HasBinding(variableName)をbindingExistsとする。
      2. bindingExistsfalseである場合、
        1. NOTE: 次の呼び出しは、ステップ14に先立つ検証により、abrupt completionを返すことができない。
        2. variableEnv.CreateMutableBinding(variableName, true)を実行する。
        3. variableEnv.InitializeBinding(variableName, undefined)を実行する。
  19. unusedを返す。

19.2.2 isFinite ( value )

このfunctionは%isFinite% intrinsic objectです。

これは呼び出されたとき、次のstepsを実行します:

  1. numberを ? ToNumber(value) とする。
  2. numberfiniteなら、trueを返す。
  3. falseを返す。

19.2.3 isNaN ( value )

このfunctionは%isNaN% intrinsic objectです。

これは呼び出されたとき、次のstepsを実行します:

  1. numberを ? ToNumber(value) とする。
  2. numberNaNなら、trueを返す。
  3. falseを返す。
Note

ECMAScript codeがvalue XNaNかどうかをtestするreliableな方法は、X !== Xという形式のexpressionです。そのresultは、XNaNである場合に限りtrueになります。

19.2.4 parseFloat ( string )

このfunctionは、string argumentのcontentsをdecimal literalとしてinterpretすることによってdictatedされるNumber valueをproduceします。

これは%parseFloat% intrinsic objectです。

これは呼び出されたとき、次のstepsを実行します:

  1. inputStringを ? ToString(string) とする。
  2. trimmedStringを ! TrimString(inputString, start) とする。
  3. trimmedStringToCodePoints(trimmedString)とする。
  4. trimmedPrefixを、StrDecimalLiteralのsyntaxをsatisfiesするtrimmedのlongest prefixとする。これはtrimmed自身である場合があります。そのようなprefixがない場合、NaNを返す。
  5. parsedNumberParseText(trimmedPrefix, StrDecimalLiteral)とする。
  6. Assert: parsedNumberParse Nodeである。
  7. parsedNumberStringNumericValueを返す。
Note

このfunctionは、stringのleading portionだけをNumber valueとしてinterpretする場合があります;decimal literalのnotationの一部としてinterpretできないcode unitsは無視され、そのようなcode unitsが無視されたことを示すindicationは与えられません。

19.2.5 parseInt ( string, radix )

このfunctionは、指定されたradixに従ってstringのcontentsをinterpretすることによってdictatedされるintegral Numberをproduceします。string内のleading white spaceは無視されます。radixが0へcoerceされる場合(undefinedである場合など)、number representationが"0x"または"0X"で始まる場合を除き、10であるとassumedされます。その場合は16であるとassumedされます。radixが16である場合、number representationはoptionalに"0x"または"0X"で始まってもよいです。

これは%parseInt% intrinsic objectです。

これは呼び出されたとき、次のstepsを実行します:

  1. inputStringを ? ToString(string) とする。
  2. trimmedStringを ! TrimString(inputString, start) とする。
  3. signを1とする。
  4. trimmedStringがemptyでなく、trimmedStringの最初のcode unitがcode unit 0x002D (HYPHEN-MINUS)であるなら、signを-1に設定する。
  5. trimmedStringがemptyでなく、trimmedStringの最初のcode unitがcode unit 0x002B (PLUS SIGN)またはcode unit 0x002D (HYPHEN-MINUS)のいずれかであるなら、trimmedStringをindex 1からのtrimmedStringsubstringに設定する。
  6. radixMV(? ToInt32(radix))とする。
  7. stripPrefixtrueとする。
  8. radixMV ≠ 0なら、
    1. radixMV < 2またはradixMV > 36なら、NaNを返す。
    2. radixMV ≠ 16なら、stripPrefixfalseに設定する。
  9. そうでなければ、
    1. radixMVを10に設定する。
  10. stripPrefixtrueなら、
    1. trimmedStringのlengthが≥ 2であり、trimmedStringの最初の2つのcode unitsが"0x"または"0X"のいずれかであるなら、
      1. trimmedStringをindex 2からのtrimmedStringsubstringに設定する。
      2. radixMVを16に設定する。
  11. trimmedStringがradix-radixMV digitでないcode unitを含むなら、endtrimmedString内の最初のそのようなcode unitのindexとする;そうでなければ、endtrimmedStringのlengthとする。
  12. numberStringを0からendまでのtrimmedStringsubstringとする。
  13. numberStringがemptyなら、NaNを返す。
  14. mathIntを、radix-radixMV notationにおいてnumberStringによって表されるinteger valueとする。values 10から35のdigitsにはletters A through Zおよびa through zを使用する。(ただし、radixMV = 10であり、numberStringが20を超えるsignificant digitsを含む場合、20番目以降の各significant digitはimplementationの選択により0 digitで置き換えられてもよい;またradixMVが2、4、8、10、16、または32のいずれでもない場合、mathIntはradix-radixMV notationでnumberStringによってdenotedされるinteger valueを表すimplementation-approximated integerであってもよい。)
  15. mathInt = 0なら、
    1. sign = -1なら、-0𝔽を返す。
    2. +0𝔽を返す。
  16. 𝔽(sign × mathInt)を返す。
Note

このfunctionは、stringのleading portionだけをinteger valueとしてinterpretする場合があります;integerのnotationの一部としてinterpretできないcode unitsは無視され、そのようなcode unitsが無視されたことを示すindicationは与えられません。

19.2.6 URI Handling Functions

Uniform Resource Identifiers、すなわちURIsは、resources(例えばweb pagesやfiles)およびそれらにaccessするためのtransport protocols(例えばHTTPやFTP)をInternet上でidentifyするStringsです。ECMAScript language自身は、このsectionで記述されるようにURIsをencodeおよびdecodeするfunctionsを除き、URIsを使用するためのsupportを提供しません。encodeURIおよびdecodeURIはcomplete URIsとともに動作することを意図しています;それらは、reserved charactersがspecial meaning(例えばdelimitersとして)を持つことが意図されているとassumeし、したがってencodeされません。encodeURIComponentおよびdecodeURIComponentはURIのindividual componentsとともに動作することを意図しています;それらは、reserved charactersがtextを表し、componentがcomplete URIの一部であるときspecial meaningを避けるためにencodeされなければならないとassumeします。

Note 1

reserved charactersのsetはRFC 2396に基づいており、よりrecentなRFC 3986によってintroducedされたchangesを反映していません。

Note 2

ECMAScriptの多くのimplementationsは、web pagesをmanipulateする追加のfunctionsおよびmethodsを提供します;これらのfunctionsはこのstandardのscope外です。

19.2.6.1 decodeURI ( encodedURI )

このfunctionは、encodeURI functionによってintroducedされ得る種類の各escape sequenceおよびUTF-8 encodingが、それが表すcode pointのUTF-16 encodingで置き換えられたURIのnew versionをcomputesします。encodeURIによってintroducedされ得なかったescape sequencesは置き換えられません。

これは%decodeURI% intrinsic objectです。

これは呼び出されたとき、次のstepsを実行します:

  1. uriStringを ? ToString(encodedURI) とする。
  2. preserveEscapeSet";/?:@&=+$,#"とする。
  3. Decode(uriString, preserveEscapeSet)を返す。

19.2.6.2 decodeURIComponent ( encodedURIComponent )

このfunctionは、encodeURIComponent functionによってintroducedされ得る種類の各escape sequenceおよびUTF-8 encodingが、それが表すcode pointのUTF-16 encodingで置き換えられたURIのnew versionをcomputesします。

これは%decodeURIComponent% intrinsic objectです。

これは呼び出されたとき、次のstepsを実行します:

  1. componentStringを ? ToString(encodedURIComponent) とする。
  2. preserveEscapeSetをempty Stringとする。
  3. Decode(componentString, preserveEscapeSet)を返す。

19.2.6.3 encodeURI ( uri )

このfunctionは、UTF-16 encoded(6.1.4)URIのnew versionをcomputesします。その中では、特定のcode pointsの各instanceが、そのcode pointのUTF-8 encodingを表す1つ、2つ、3つ、または4つのescape sequencesによって置き換えられます。

これは%encodeURI% intrinsic objectです。

これは呼び出されたとき、次のstepsを実行します:

  1. uriStringを ? ToString(uri) とする。
  2. extraUnescaped";/?:@&=+$,#"とする。
  3. Encode(uriString, extraUnescaped)を返す。

19.2.6.4 encodeURIComponent ( uriComponent )

このfunctionは、UTF-16 encoded(6.1.4)URIのnew versionをcomputesします。その中では、特定のcode pointsの各instanceが、そのcode pointのUTF-8 encodingを表す1つ、2つ、3つ、または4つのescape sequencesによって置き換えられます。

これは%encodeURIComponent% intrinsic objectです。

これは呼び出されたとき、次のstepsを実行します:

  1. componentStringを ? ToString(uriComponent) とする。
  2. extraUnescapedをempty Stringとする。
  3. Encode(componentString, extraUnescaped)を返す。

19.2.6.5 Encode ( string, extraUnescaped )

The abstract operation Encode takes arguments string (a String) and extraUnescaped (a String) and returns either a normal completion containing a String or a throw completion. これはURI encodingおよびescapingを実行し、string6.1.4で記述されるUTF-16 encoded code pointsのsequenceとしてinterpretします。characterがRFC 2396でunreservedとしてidentifiedされるか、extraUnescaped内にappearする場合、それはescapedされません。 It performs the following steps when called:

  1. lengthstringのlengthとする。
  2. resultをempty Stringとする。
  3. alwaysUnescapedをASCII word charactersと"-.!~*'()"string-concatenationとする。
  4. unescapedSetalwaysUnescapedextraUnescapedstring-concatenationとする。
  5. kを0とする。
  6. k < lengthの間、繰り返す
    1. codeUnitstring内のindex kにあるcode unitとする。
    2. unescapedSetcodeUnitを含むなら、
      1. kk + 1に設定する。
      2. resultresultcodeUnitstring-concatenationに設定する。
    3. そうでなければ、
      1. codePointCodePointAt(string, k)とする。
      2. codePoint.[[IsUnpairedSurrogate]]trueなら、URIError例外をthrowする。
      3. kk + codePoint.[[CodeUnitCount]]に設定する。
      4. octetscodePoint.[[CodePoint]]にUTF-8 transformationをapplyした結果のoctetsのListとする。
      5. octetsの各要素octetについて、以下を行う
        1. hexoctetのString representationとし、uppercase hexadecimal numberとしてformattedする。
        2. resultresult"%"、およびStringPad(hex, 2, "0", start)のstring-concatenationに設定する。
  7. resultを返す。
Note

percent-encodingはindividual octetsを表すために使用されるため、単一のcode pointはmultiple consecutive escape sequences(その8-bit UTF-8 code unitsのそれぞれに1つ)として表現される場合があります。

19.2.6.6 Decode ( string, preserveEscapeSet )

The abstract operation Decode takes arguments string (a String) and preserveEscapeSet (a String) and returns either a normal completion containing a String or a throw completion. これはURI unescapingおよびdecodingを実行し、preserveEscapeSet内のBasic Latin charactersに対応する任意のescape sequencesをpreserveします。 It performs the following steps when called:

  1. lengthstringのlengthとする。
  2. resultをempty Stringとする。
  3. kを0とする。
  4. k < lengthの間、繰り返す
    1. codeUnitstring内のindex kにあるcode unitとする。
    2. segmentcodeUnitとする。
    3. codeUnitがcode unit 0x0025 (PERCENT SIGN)であるなら、
      1. k + 3 > lengthなら、URIError例外をthrowする。
      2. escapekからk + 3までのstringsubstringとする。
      3. firstOctetParseHexOctet(string, k + 1)とする。
      4. firstOctetintegerでないなら、URIError例外をthrowする。
      5. kk + 2に設定する。
      6. nfirstOctet内のleading 1 bitsの数とする。
      7. n = 0なら、
        1. asciiCharを、numeric valueがfirstOctetであるcode unitとする。
        2. preserveEscapeSetasciiCharを含むなら、segmentescapeに設定する;そうでなければ、segmentasciiCharに設定する。
      8. そうでなければ、
        1. n = 1またはn > 4なら、URIError例外をthrowする。
        2. octetsを« firstOctet »とする。
        3. jを1とする。
        4. j < nの間、繰り返す
          1. kk + 1に設定する。
          2. k + 3 > lengthなら、URIError例外をthrowする。
          3. string内のindex kにあるcode unitがcode unit 0x0025 (PERCENT SIGN)でないなら、URIError例外をthrowする。
          4. continuationByteParseHexOctet(string, k + 1)とする。
          5. continuationByteintegerでないなら、URIError例外をthrowする。
          6. continuationByteoctetsへappendする。
          7. kk + 2に設定する。
          8. jj + 1に設定する。
        5. Assert: octetsのlengthはnである。
        6. octetsがUnicode code pointのvalid UTF-8 encodingを含まないなら、URIError例外をthrowする。
        7. codePointを、UTF-8 transformationをoctetsにapplyして得られるcode point、すなわちoctetsのListから21-bit valueへの変換で得られるものとする。
        8. segmentUTF16EncodeCodePoint(codePoint)に設定する。
    4. resultresultsegmentstring-concatenationに設定する。
    5. kk + 1に設定する。
  5. resultを返す。
Note

RFC 3629はinvalid UTF-8 octet sequencesのdecodingをprohibitしています。例えば、invalid sequence 0xC0 0x80はcode unit 0x0000へdecodeしてはなりません。Decode algorithmのimplementationsは、そのようなinvalid sequencesにencounterしたときURIErrorをthrowすることがrequiredされます。

19.2.6.7 ParseHexOctet ( string, position )

The abstract operation ParseHexOctet takes arguments string (a String) and position (a non-negative integer) and returns either a non-negative integer or a non-empty List of SyntaxError objects. string内の指定されたpositionにある2つのhexadecimal charactersのsequenceをunsigned 8-bit integerへparseします。 It performs the following steps when called:

  1. lengthstringのlengthとする。
  2. Assert: position + 2 ≤ lengthである。
  3. hexDigitspositionからposition + 2までのstringsubstringとする。
  4. parseResultParseText(hexDigits, HexDigits[~Sep])とする。
  5. parseResultParse Nodeでないなら、parseResultを返す。
  6. nparseResultのMVとする。
  7. Assert: nは0から255までのinclusive interval内にある。
  8. nを返す。

19.3 Constructor Properties of the Global Object

19.3.1 AggregateError ( . . . )

20.5.7.1を参照してください。

19.3.2 Array ( . . . )

23.1.1を参照してください。

19.3.3 ArrayBuffer ( . . . )

25.1.4を参照してください。

19.3.4 AsyncDisposableStack ( . . . )

27.4.1を参照してください。

19.3.5 BigInt ( . . . )

21.2.1を参照してください。

19.3.6 BigInt64Array ( . . . )

23.2.5を参照してください。

19.3.7 BigUint64Array ( . . . )

23.2.5を参照してください。

19.3.8 Boolean ( . . . )

20.3.1を参照してください。

19.3.9 DataView ( . . . )

25.3.2を参照してください。

19.3.10 Date ( . . . )

21.4.2を参照してください。

19.3.11 DisposableStack ( . . . )

27.3.1を参照してください。

19.3.12 Error ( . . . )

20.5.1を参照してください。

19.3.13 EvalError ( . . . )

20.5.5.1を参照してください。

19.3.14 FinalizationRegistry ( . . . )

26.2.1を参照してください。

19.3.15 Float16Array ( . . . )

23.2.5を参照してください。

19.3.16 Float32Array ( . . . )

23.2.5を参照してください。

19.3.17 Float64Array ( . . . )

23.2.5を参照してください。

19.3.18 Function ( . . . )

20.2.1を参照してください。

19.3.19 Int8Array ( . . . )

23.2.5を参照してください。

19.3.20 Int16Array ( . . . )

23.2.5を参照してください。

19.3.21 Int32Array ( . . . )

23.2.5を参照してください。

19.3.22 Iterator ( . . . )

27.1.3.1を参照してください。

19.3.23 Map ( . . . )

24.1.1を参照してください。

19.3.24 Number ( . . . )

21.1.1を参照してください。

19.3.25 Object ( . . . )

20.1.1を参照してください。

19.3.26 Promise ( . . . )

27.5.3を参照してください。

19.3.27 Proxy ( . . . )

28.2.1を参照してください。

19.3.28 RangeError ( . . . )

20.5.5.2を参照してください。

19.3.29 ReferenceError ( . . . )

20.5.5.3を参照してください。

19.3.30 RegExp ( . . . )

22.2.4を参照してください。

19.3.31 Set ( . . . )

24.2.2を参照してください。

19.3.32 SharedArrayBuffer ( . . . )

25.2.3を参照してください。

19.3.33 String ( . . . )

22.1.1を参照してください。

19.3.34 SuppressedError ( . . . )

20.5.8.1を参照してください。

19.3.35 Symbol ( . . . )

20.4.1を参照してください。

19.3.36 SyntaxError ( . . . )

20.5.5.4を参照してください。

19.3.37 TypeError ( . . . )

20.5.5.5を参照してください。

19.3.38 Uint8Array ( . . . )

23.2.5を参照してください。

19.3.39 Uint8ClampedArray ( . . . )

23.2.5を参照してください。

19.3.40 Uint16Array ( . . . )

23.2.5を参照してください。

19.3.41 Uint32Array ( . . . )

23.2.5を参照してください。

19.3.42 URIError ( . . . )

20.5.5.6を参照してください。

19.3.43 WeakMap ( . . . )

24.3.1を参照してください。

19.3.44 WeakRef ( . . . )

26.1.1を参照してください。

19.3.45 WeakSet ( . . . )

24.4を参照してください。

19.4 Other Properties of the Global Object

19.4.1 Atomics

25.4を参照してください。

19.4.2 JSON

25.5を参照してください。

19.4.3 Math

21.3を参照してください。

19.4.4 Reflect

28.1を参照してください。

20 Fundamental Objects

20.1 Object Objects

20.1.1 The Object Constructor

Object constructorは:

  • %Object%です。
  • global object"Object" propertyのinitial valueです。
  • constructorとして呼び出されたとき、新しいordinary objectを作成します。
  • constructorとしてではなくfunctionとして呼び出されたとき、type conversionを実行します。
  • class definitionのextends clauseのvalueとして使用できます。

20.1.1.1 Object ( value )

このfunctionは呼び出されたとき、次のstepsを実行します:

  1. NewTargetがundefinedでもactive function objectでもないなら、
    1. OrdinaryCreateFromConstructor(NewTarget, "%Object.prototype%")を返す。
  2. valueundefinedまたはnullのいずれかなら、OrdinaryObjectCreate(%Object.prototype%)を返す。
  3. ToObject(value)を返す。

20.1.2 Properties of the Object Constructor

Object constructorは:

  • valueが%Function.prototype%である[[Prototype]] internal slotを持ちます。
  • 次の追加propertiesを持ちます:

20.1.2.1 Object.assign ( target, ...sources )

このfunctionは、1つ以上のsource objectsからすべてのenumerable own propertiesのvaluesをtarget objectへcopyします。

これは呼び出されたとき、次のstepsを実行します:

  1. ToObject(target)をtargetObjとする。
  2. 引数が1個だけ渡された場合、targetObjを返す。
  3. sourcesの各要素nextSourceについて、次を行う。
    1. nextSourceundefinedでもnullでもない場合、
      1. ToObject(nextSource)をfromとする。
      2. from.[[OwnPropertyKeys]]()keysとする。
      3. keysの各要素nextKeyについて、次を行う。
        1. from.[[GetOwnProperty]](nextKey)propertyDescとする。
        2. propertyDescundefinedでなく、かつpropertyDesc.[[Enumerable]]trueである場合、
          1. Get(from, nextKey)をpropertyValueとする。
          2. Set(targetObj, nextKey, propertyValue, true)を実行する。
  4. targetObjを返す。

このfunctionの"length" propertyは2𝔽です。

20.1.2.2 Object.create ( proto, properties )

このfunctionは、指定されたprototypeを持つ新しいobjectを作成します。

これは呼び出されたとき、次のstepsを実行します:

  1. protoがObjectでなく、かつprotonullでないなら、TypeError例外をthrowする。
  2. objOrdinaryObjectCreate(proto)とする。
  3. propertiesundefinedでないなら、
    1. ObjectDefineProperties(obj, properties)を返す。
  4. objを返す。

20.1.2.3 Object.defineProperties ( obj, properties )

このfunctionは、objectのown propertiesを追加し、かつ/または既存のown propertiesのattributesをupdateします。

これは呼び出されたとき、次のstepsを実行します:

  1. objがObjectでないなら、TypeError例外をthrowする。
  2. ObjectDefineProperties(obj, properties)を返す。

20.1.2.3.1 ObjectDefineProperties ( obj, properties )

The abstract operation ObjectDefineProperties takes arguments obj (an Object) and properties (an ECMAScript language value) and returns either a normal completion containing an Object or a throw completion. It performs the following steps when called:

  1. propertiesを ? ToObject(properties) に設定する。
  2. keysを ? properties.[[OwnPropertyKeys]]() とする。
  3. propertyDescsを新しい空のListとする。
  4. keysの各要素nextKeyについて、以下を行う
    1. currentPropertyDescを ? properties.[[GetOwnProperty]](nextKey) とする。
    2. currentPropertyDescundefinedでなく、currentPropertyDesc.[[Enumerable]]trueなら、
      1. propertyDescObjを ? Get(properties, nextKey) とする。
      2. propertyDescを ? ToPropertyDescriptor(propertyDescObj) とする。
      3. Record { [[Key]]: nextKey, [[Descriptor]]: propertyDesc }をpropertyDescsへappendする。
  5. propertyDescsの各要素propertyについて、以下を行う
    1. DefinePropertyOrThrow(obj, property.[[Key]], property.[[Descriptor]])を実行する。
  6. objを返す。

20.1.2.4 Object.defineProperty ( obj, key, attrs )

このfunctionは、objectのown propertyを追加し、かつ/または既存のown propertyのattributesをupdateします。

これは呼び出されたとき、次のstepsを実行します:

  1. objがObjectでないなら、TypeError例外をthrowする。
  2. propertyKeyを ? ToPropertyKey(key) とする。
  3. propertyDescを ? ToPropertyDescriptor(attrs) とする。
  4. DefinePropertyOrThrow(obj, propertyKey, propertyDesc)を実行する。
  5. objを返す。

20.1.2.5 Object.entries ( obj )

このfunctionは呼び出されたとき、次のstepsを実行します:

  1. coercedを ? ToObject(obj) とする。
  2. entryListを ? EnumerableOwnProperties(coerced, key+value) とする。
  3. CreateArrayFromList(entryList)を返す。

20.1.2.6 Object.freeze ( obj )

このfunctionは呼び出されたとき、次のstepsを実行します:

  1. objがObjectでないなら、objを返す。
  2. statusを ? SetIntegrityLevel(obj, frozen) とする。
  3. statusfalseなら、TypeError例外をthrowする。
  4. objを返す。

20.1.2.7 Object.fromEntries ( iterable )

このfunctionは呼び出されたとき、次のstepsを実行します:

  1. RequireObjectCoercible(iterable)を実行する。
  2. objOrdinaryObjectCreate(%Object.prototype%)とする。
  3. Assert: objはown propertiesを持たないextensible ordinary objectである。
  4. objをcaptureし、呼び出されたとき次のstepsを実行する、parameters (key, value)を持つ新しいAbstract Closure closureとする:
    1. propertyKeyを ? ToPropertyKey(key) とする。
    2. CreateDataPropertyOrThrow(obj, propertyKey, value)を実行する。
    3. NormalCompletion(undefined)を返す。
  5. adderCreateBuiltinFunction(closure, 2, "", « »)とする。
  6. AddEntriesFromIterable(obj, iterable, adder)を返す。
Note
adderのために作成されたfunctionは、ECMAScript codeから直接accessできることはありません。

20.1.2.8 Object.getOwnPropertyDescriptor ( obj, key )

このfunctionは呼び出されたとき、次のstepsを実行します:

  1. coercedを ? ToObject(obj) とする。
  2. propertyKeyを ? ToPropertyKey(key) とする。
  3. propertyDescを ? coerced.[[GetOwnProperty]](propertyKey) とする。
  4. FromPropertyDescriptor(propertyDesc)を返す。

20.1.2.9 Object.getOwnPropertyDescriptors ( obj )

このfunctionは呼び出されたとき、次のstepsを実行します:

  1. coercedを ? ToObject(obj) とする。
  2. ownKeysを ? coerced.[[OwnPropertyKeys]]() とする。
  3. descsOrdinaryObjectCreate(%Object.prototype%)とする。
  4. ownKeysの各要素keyについて、以下を行う
    1. propertyDescを ? coerced.[[GetOwnProperty]](key) とする。
    2. propertyDescObjFromPropertyDescriptor(propertyDesc)とする。
    3. propertyDescObjundefinedでないなら、! CreateDataPropertyOrThrow(descs, key, propertyDescObj)を実行する。
  5. descsを返す。

20.1.2.10 Object.getOwnPropertyNames ( obj )

このfunctionは呼び出されたとき、次のstepsを実行します:

  1. CreateArrayFromList(? GetOwnPropertyKeys(obj, string))を返す。

20.1.2.11 Object.getOwnPropertySymbols ( obj )

このfunctionは呼び出されたとき、次のstepsを実行します:

  1. CreateArrayFromList(? GetOwnPropertyKeys(obj, symbol))を返す。

20.1.2.11.1 GetOwnPropertyKeys ( value, type )

The abstract operation GetOwnPropertyKeys takes arguments value (an ECMAScript language value) and type (string or symbol) and returns either a normal completion containing a List of property keys or a throw completion. It performs the following steps when called:

  1. objを ? ToObject(value) とする。
  2. keysを ? obj.[[OwnPropertyKeys]]() とする。
  3. nameListを新しい空のListとする。
  4. keysの各要素nextKeyについて、以下を行う
    1. nextKeyがSymbolでありtypesymbolである、またはnextKeyがStringでありtypestringであるなら、
      1. nextKeynameListへappendする。
  5. nameListを返す。

20.1.2.12 Object.getPrototypeOf ( obj )

このfunctionは呼び出されたとき、次のstepsを実行します:

  1. coercedを ? ToObject(obj) とする。
  2. coerced.[[GetPrototypeOf]]()を返す。

20.1.2.13 Object.groupBy ( items, callback )

Note

callbackは2つのargumentsをacceptするfunctionであるべきです。groupByitems内の各elementについてascending orderでcallbackを1回呼び出し、新しいobjectをconstructします。callbackによって返される各valueはproperty keyへcoercedされます。そのような各property keyについて、result objectは、そのkeyがそのproperty keyであり、そのvalueがcallbackのreturn valueがそのkeyへcoercedされたすべてのelementsを含むarrayであるpropertyを持ちます。

callbackは2つのarguments、すなわちelementのvalueとelementのindexを伴って呼び出されます。

groupByのreturn valueは%Object.prototype%からinheritしないobjectです。

このfunctionは呼び出されたとき、次のstepsを実行します:

  1. GroupBy(items, callback, property)をgroupsとする。
  2. OrdinaryObjectCreate(null)をobjとする。
  3. groupsの各Record { [[Key]], [[Elements]] } groupについて、次を行う。
    1. CreateArrayFromList(group.[[Elements]])をelementsとする。
    2. CreateDataPropertyOrThrow(obj, group.[[Key]], elements)を実行する。
  4. objを返す。

20.1.2.14 Object.hasOwn ( obj, key )

このfunctionは呼び出されたとき、次のstepsを実行します:

  1. coercedを ? ToObject(obj) とする。
  2. propertyKeyを ? ToPropertyKey(key) とする。
  3. HasOwnProperty(coerced, propertyKey)を返す。

20.1.2.15 Object.is ( value1, value2 )

このfunctionは呼び出されたとき、次のstepsを実行します:

  1. SameValue(value1, value2)を返す。

20.1.2.16 Object.isExtensible ( obj )

このfunctionは呼び出されたとき、次のstepsを実行します:

  1. objがObjectでないなら、falseを返す。
  2. IsExtensible(obj)を返す。

20.1.2.17 Object.isFrozen ( obj )

このfunctionは呼び出されたとき、次のstepsを実行します:

  1. objがObjectでないなら、trueを返す。
  2. TestIntegrityLevel(obj, frozen)を返す。

20.1.2.18 Object.isSealed ( obj )

このfunctionは呼び出されたとき、次のstepsを実行します:

  1. objがObjectでないなら、trueを返す。
  2. TestIntegrityLevel(obj, sealed)を返す。

20.1.2.19 Object.keys ( obj )

このfunctionは呼び出されたとき、次のstepsを実行します:

  1. coercedを ? ToObject(obj) とする。
  2. keyListを ? EnumerableOwnProperties(coerced, key) とする。
  3. CreateArrayFromList(keyList)を返す。

20.1.2.20 Object.preventExtensions ( obj )

このfunctionは呼び出されたとき、次のstepsを実行します:

  1. objがObjectでないなら、objを返す。
  2. statusを ? obj.[[PreventExtensions]]() とする。
  3. statusfalseなら、TypeError例外をthrowする。
  4. objを返す。

20.1.2.21 Object.prototype

Object.prototypeのinitial valueはObject prototype objectです。

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

20.1.2.22 Object.seal ( obj )

このfunctionは呼び出されたとき、次のstepsを実行します:

  1. objがObjectでないなら、objを返す。
  2. statusを ? SetIntegrityLevel(obj, sealed) とする。
  3. statusfalseなら、TypeError例外をthrowする。
  4. objを返す。

20.1.2.23 Object.setPrototypeOf ( obj, proto )

このfunctionは呼び出されたとき、次のstepsを実行します:

  1. RequireObjectCoercible(obj)を実行する。
  2. protoがObjectでなく、かつprotonullでないなら、TypeError例外をthrowする。
  3. objがObjectでないなら、objを返す。
  4. statusを ? obj.[[SetPrototypeOf]](proto) とする。
  5. statusfalseなら、TypeError例外をthrowする。
  6. objを返す。

20.1.2.24 Object.values ( obj )

このfunctionは呼び出されたとき、次のstepsを実行します:

  1. coercedを ? ToObject(obj) とする。
  2. valueListを ? EnumerableOwnProperties(coerced, value) とする。
  3. CreateArrayFromList(valueList)を返す。

20.1.3 Properties of the Object Prototype Object

Object prototype objectは:

  • %Object.prototype%です。
  • valueがtrueである[[Extensible]] internal slotを持ちます。
  • ordinary objectsのために定義されるinternal methodsを持ちます。ただし[[SetPrototypeOf]] methodは例外で、10.4.7.1で定義される通りです。(したがって、これはimmutable prototype exotic objectです。)
  • valueがnullである[[Prototype]] internal slotを持ちます。

20.1.3.1 Object.prototype.constructor

Object.prototype.constructorのinitial valueは%Object%です。

20.1.3.2 Object.prototype.hasOwnProperty ( value )

このmethodは呼び出されたとき、次のstepsを実行します:

  1. propertyKeyを ? ToPropertyKey(value) とする。
  2. objを ? ToObject(this value) とする。
  3. HasOwnProperty(obj, propertyKey)を返す。
Note

steps 1および2のorderingは、this valueがundefinedまたはnullであっても、この仕様のprevious editionsにおいてstep 1によってthrowされていたであろう任意のexceptionが引き続きthrowされることを保証するために選ばれています。

20.1.3.3 Object.prototype.isPrototypeOf ( value )

このmethodは呼び出されたとき、次のstepsを実行します:

  1. valueがObjectでないなら、falseを返す。
  2. objを ? ToObject(this value) とする。
  3. 繰り返す
    1. valueを ? value.[[GetPrototypeOf]]() に設定する。
    2. valuenullなら、falseを返す。
    3. SameValue(obj, value)がtrueなら、trueを返す。
Note

steps 1および2のorderingは、valueがobjectでなく、this valueがundefinedまたはnullであるcaseについて、この仕様のprevious editionsで指定されたbehaviourをpreserveします。

20.1.3.4 Object.prototype.propertyIsEnumerable ( value )

このmethodは呼び出されたとき、次のstepsを実行します:

  1. propertyKeyを ? ToPropertyKey(value) とする。
  2. objを ? ToObject(this value) とする。
  3. propertyDescを ? obj.[[GetOwnProperty]](propertyKey) とする。
  4. propertyDescundefinedなら、falseを返す。
  5. propertyDesc.[[Enumerable]]を返す。
Note 1

このmethodはprototype chain内のobjectsを考慮しません。

Note 2

steps 1および2のorderingは、this valueがundefinedまたはnullであっても、この仕様のprevious editionsにおいてstep 1によってthrowされていたであろう任意のexceptionが引き続きthrowされることを保証するために選ばれています。

20.1.3.5 Object.prototype.toLocaleString ( [ reserved1 [ , reserved2 ] ] )

このmethodは呼び出されたとき、次のstepsを実行します:

  1. thisValuethis valueとする。
  2. Invoke(thisValue, "toString")を返す。

このmethodのoptional parametersは使用されませんが、ECMA-402 toLocaleString methodsによって使用されるparameter patternに対応することを意図しています。ECMA-402 supportを含まないimplementationsは、これらのparameter positionsを他のpurposesのために使用してはなりません。

Note 1

このmethodは、locale-sensitiveなtoString behaviourを持たないobjectsに対してgenericなtoLocaleString implementationを提供します。ArrayNumberDate、および%TypedArray%は、それぞれ独自のlocale-sensitiveなtoLocaleString methodsを提供します。

Note 2

ECMA-402は意図的に、このdefault implementationのalternativeを提供していません。

20.1.3.6 Object.prototype.toString ( )

このmethodは呼び出されたとき、次のstepsを実行します:

  1. this valueがundefinedなら、"[object Undefined]"を返す。
  2. this valueがnullなら、"[object Null]"を返す。
  3. objを ! ToObject(this value) とする。
  4. isArrayを ? IsArray(obj) とする。
  5. isArraytrueなら、builtinTag"Array"とする。
  6. そうでなく、obj[[ParameterMap]] internal slotを持つなら、builtinTag"Arguments"とする。
  7. そうでなく、obj[[Call]] internal methodを持つなら、builtinTag"Function"とする。
  8. そうでなく、obj[[ErrorData]] internal slotを持つなら、builtinTag"Error"とする。
  9. そうでなく、obj[[BooleanData]] internal slotを持つなら、builtinTag"Boolean"とする。
  10. そうでなく、obj[[NumberData]] internal slotを持つなら、builtinTag"Number"とする。
  11. そうでなく、obj[[StringData]] internal slotを持つなら、builtinTag"String"とする。
  12. そうでなく、obj[[DateValue]] internal slotを持つなら、builtinTag"Date"とする。
  13. そうでなく、obj[[RegExpMatcher]] internal slotを持つなら、builtinTag"RegExp"とする。
  14. そうでなければ、builtinTag"Object"とする。
  15. tagを ? Get(obj, %Symbol.toStringTag%) とする。
  16. tagがStringでないなら、tagbuiltinTagに設定する。
  17. "[object "tag、および"]"string-concatenationを返す。
Note

Historically、このmethodは、この仕様のprevious editionsでさまざまなbuilt-in objectsのnominal type tagとして使用されていた[[Class]] internal slotのString valueにaccessするために時々使用されていました。上記のtoStringのdefinitionは、toStringをそれら特定の種類のbuilt-in objectsに対するtestとして使用するlegacy codeとのcompatibilityをpreserveします。これは他の種類のbuilt-inまたはprogram defined objectsに対するreliable type testing mechanismを提供しません。加えて、programsは、そのようなlegacy type testsのreliabilityを無効にする方法で%Symbol.toStringTag%を使用できます。

20.1.3.7 Object.prototype.valueOf ( )

このmethodは呼び出されたとき、次のstepsを実行します:

  1. ToObject(this value)を返す。

20.1.3.8 Object.prototype.__proto__

Object.prototype.__proto__はattributes { [[Enumerable]]: false, [[Configurable]]: true }を持つaccessor propertyです。[[Get]]および[[Set]] attributesは次のように定義されます:

20.1.3.8.1 get Object.prototype.__proto__

[[Get]] attributeのvalueは、argumentsを要求しないbuilt-in functionです。これは呼び出されたとき、次のstepsを実行します:

  1. objを ? ToObject(this value) とする。
  2. obj.[[GetPrototypeOf]]()を返す。

20.1.3.8.2 set Object.prototype.__proto__

[[Set]] attributeのvalueは、argument protoを取るbuilt-in functionです。これは呼び出されたとき、次のstepsを実行します:

  1. thisValuethis valueとする。
  2. RequireObjectCoercible(thisValue)を実行する。
  3. protoがObjectでなく、かつprotonullでないなら、undefinedを返す。
  4. thisValueがObjectでないなら、undefinedを返す。
  5. statusを ? thisValue.[[SetPrototypeOf]](proto) とする。
  6. statusfalseなら、TypeError例外をthrowする。
  7. undefinedを返す。

20.1.3.9 Legacy Object.prototype Accessor Methods

20.1.3.9.1 Object.prototype.__defineGetter__ ( key, getter )

このmethodは呼び出されたとき、次のstepsを実行します:

  1. objを ? ToObject(this value) とする。
  2. IsCallable(getter)がfalseなら、TypeError例外をthrowする。
  3. propertyDescをPropertyDescriptor { [[Get]]: getter, [[Enumerable]]: true, [[Configurable]]: true }とする。
  4. propertyKeyを ? ToPropertyKey(key) とする。
  5. DefinePropertyOrThrow(obj, propertyKey, propertyDesc)を実行する。
  6. undefinedを返す。

20.1.3.9.2 Object.prototype.__defineSetter__ ( key, setter )

このmethodは呼び出されたとき、次のstepsを実行します:

  1. objを ? ToObject(this value) とする。
  2. IsCallable(setter)がfalseなら、TypeError例外をthrowする。
  3. propertyDescをPropertyDescriptor { [[Set]]: setter, [[Enumerable]]: true, [[Configurable]]: true }とする。
  4. propertyKeyを ? ToPropertyKey(key) とする。
  5. DefinePropertyOrThrow(obj, propertyKey, propertyDesc)を実行する。
  6. undefinedを返す。

20.1.3.9.3 Object.prototype.__lookupGetter__ ( key )

このmethodは呼び出されたとき、次のstepsを実行します:

  1. objを ? ToObject(this value) とする。
  2. propertyKeyを ? ToPropertyKey(key) とする。
  3. 繰り返す
    1. propertyDescを ? obj.[[GetOwnProperty]](propertyKey) とする。
    2. propertyDescundefinedでないなら、
      1. IsAccessorDescriptor(propertyDesc)がtrueなら、propertyDesc.[[Get]]を返す。
      2. undefinedを返す。
    3. objを ? obj.[[GetPrototypeOf]]() に設定する。
    4. objnullなら、undefinedを返す。

20.1.3.9.4 Object.prototype.__lookupSetter__ ( key )

このmethodは呼び出されたとき、次のstepsを実行します:

  1. objを ? ToObject(this value) とする。
  2. propertyKeyを ? ToPropertyKey(key) とする。
  3. 繰り返す
    1. propertyDescを ? obj.[[GetOwnProperty]](propertyKey) とする。
    2. propertyDescundefinedでないなら、
      1. IsAccessorDescriptor(propertyDesc)がtrueなら、propertyDesc.[[Set]]を返す。
      2. undefinedを返す。
    3. objを ? obj.[[GetPrototypeOf]]() に設定する。
    4. objnullなら、undefinedを返す。

20.1.4 Properties of Object Instances

Object instancesは、Object prototype objectからinheritedされるもの以外にspecial propertiesを持ちません。

20.2 Function Objects

20.2.1 The Function Constructor

Function constructorは:

  • %Function%です。
  • global object"Function" propertyのinitial valueです。
  • constructorとしてではなくfunctionとして呼び出されたとき、新しいfunction objectを作成およびinitializeします。したがってfunction call Function(…)は、同じargumentsを伴うobject creation expression new Function(…)と同等です。
  • class definitionのextends clauseのvalueとして使用できます。指定されたFunction behaviourをinheritしようとするsubclass constructorsは、built-in function behaviourに必要なinternal slotsを持つsubclass instanceを作成およびinitializeするために、Function constructorへのsuper callを含まなければなりません。function objectsを定義するすべてのECMAScript syntactic formsはFunctionのinstancesを作成します。built-in GeneratorFunction、AsyncFunction、およびAsyncGeneratorFunction subclassesを除き、Function subclassesのinstancesを作成するsyntactic meansはありません。

20.2.1.1 Function ( ...paramArgs, bodyArg )

最後のargument(ある場合)はfunctionのbody(executable code)を指定します;それより前のargumentsはformal parametersを指定します。

このfunctionは呼び出されたとき、次のstepsを実行します:

  1. ctoractive function objectとする。
  2. bodyArgが存在しないなら、bodyArgをempty Stringに設定する。
  3. CreateDynamicFunction(ctor, NewTarget, normal, paramArgs, bodyArg)を返す。
Note

指定される各formal parameterごとに1つのargumentを持つことは許されますが、必要ではありません。例えば、次の3つのexpressionsはすべて同じresultをproduceします:

new Function("a", "b", "c", "return a+b+c")
new Function("a, b, c", "return a+b+c")
new Function("a,b", "c", "return a+b+c")

20.2.1.1.1 CreateDynamicFunction ( ctor, newTarget, kind, paramArgs, bodyArg )

The abstract operation CreateDynamicFunction takes arguments ctor (a constructor), newTarget (a constructor or undefined), kind (normal, generator, async, or async-generator), paramArgs (a List of ECMAScript language values), and bodyArg (an ECMAScript language value) and returns either a normal completion containing an ECMAScript function object or a throw completion. ctorはこのactionを実行しているconstructor functionです。newTargetnewがinitiallyに適用されたconstructorです。paramArgsおよびbodyArgctorへ渡されたargument valuesをreflectします。 It performs the following steps when called:

  1. newTargetundefinedなら、newTargetctorに設定する。
  2. kindnormalなら、
    1. prefix"function"とする。
    2. exprGrammarをgrammar symbol FunctionExpressionとする。
    3. bodyGrammarをgrammar symbol FunctionBody[~Yield, ~Await]とする。
    4. paramGrammarをgrammar symbol FormalParameters[~Yield, ~Await]とする。
    5. fallbackProto"%Function.prototype%"とする。
  3. そうでなく、kindgeneratorなら、
    1. prefix"function*"とする。
    2. exprGrammarをgrammar symbol GeneratorExpressionとする。
    3. bodyGrammarをgrammar symbol GeneratorBodyとする。
    4. paramGrammarをgrammar symbol FormalParameters[+Yield, ~Await]とする。
    5. fallbackProto"%GeneratorFunction.prototype%"とする。
  4. そうでなく、kindasyncなら、
    1. prefix"async function"とする。
    2. exprGrammarをgrammar symbol AsyncFunctionExpressionとする。
    3. bodyGrammarをgrammar symbol AsyncFunctionBodyとする。
    4. paramGrammarをgrammar symbol FormalParameters[~Yield, +Await]とする。
    5. fallbackProto"%AsyncFunction.prototype%"とする。
  5. そうでなければ、
    1. Assert: kindasync-generatorである。
    2. prefix"async function*"とする。
    3. exprGrammarをgrammar symbol AsyncGeneratorExpressionとする。
    4. bodyGrammarをgrammar symbol AsyncGeneratorBodyとする。
    5. paramGrammarをgrammar symbol FormalParameters[+Yield, +Await]とする。
    6. fallbackProto"%AsyncGeneratorFunction.prototype%"とする。
  6. argCountparamArgs内の要素数とする。
  7. paramStringsを新しい空のListとする。
  8. paramArgsの各要素argについて、以下を行う
    1. ToString(arg)をparamStringsへappendする。
  9. bodyStringを ? ToString(bodyArg) とする。
  10. currentRealmcurrent Realm Recordとする。
  11. HostEnsureCanCompileStrings(currentRealm, paramStrings, bodyString, false)を実行する。
  12. paramStringをempty Stringとする。
  13. argCount > 0なら、
    1. paramStringparamStrings[0]に設定する。
    2. kを1とする。
    3. k < argCountの間、繰り返す
      1. nextArgStringparamStrings[k]とする。
      2. paramStringparamString","(comma)、およびnextArgStringstring-concatenationに設定する。
      3. kk + 1に設定する。
  14. bodyParseStringを0x000A (LINE FEED)、bodyString、および0x000A (LINE FEED)のstring-concatenationとする。
  15. sourceStringprefix" anonymous("paramString、0x000A (LINE FEED)、") {"bodyParseString、および"}"string-concatenationとする。
  16. sourceTextStringToCodePoints(sourceString)とする。
  17. paramsParseText(paramString, paramGrammar)とする。
  18. paramsがerrorsのListなら、SyntaxError例外をthrowする。
  19. bodyParseText(bodyParseString, bodyGrammar)とする。
  20. bodyがerrorsのListなら、SyntaxError例外をthrowする。
  21. NOTE: parametersとbodyは、それぞれが単独でvalidであることを保証するためにseparatelyにparsedされる。例えば、new Function("/*", "*/ ) {")はfunctionへevaluateされない。
  22. NOTE: このstepに到達した場合、sourceTextexprGrammarのsyntaxを持っていなければならない(ただしそのreverse implicationは成り立たない)。次の2つのstepsの目的は、exprGrammarにdirectlyにapplyされる任意のEarly Error rulesをenforceすることである。
  23. exprParseText(sourceText, exprGrammar)とする。
  24. exprがerrorsのListなら、SyntaxError例外をthrowする。
  25. funcProtoを ? GetPrototypeFromConstructor(newTarget, fallbackProto) とする。
  26. envRecordcurrentRealm.[[GlobalEnv]]とする。
  27. privateEnvnullとする。
  28. funcOrdinaryFunctionCreate(funcProto, sourceText, params, body, non-lexical-this, envRecord, privateEnv)とする。
  29. SetFunctionName(func, "anonymous")を実行する。
  30. kindgeneratorなら、
    1. protoProtoOrdinaryObjectCreate(%GeneratorPrototype%)とする。
    2. DefinePropertyOrThrow(func, "prototype", PropertyDescriptor { [[Value]]: protoProto, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false })を実行する。
  31. そうでなく、kindasync-generatorなら、
    1. protoProtoOrdinaryObjectCreate(%AsyncGeneratorPrototype%)とする。
    2. DefinePropertyOrThrow(func, "prototype", PropertyDescriptor { [[Value]]: protoProto, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false })を実行する。
  32. そうでなく、kindnormalなら、
    1. MakeConstructor(func)を実行する。
  33. NOTE: kindasyncであるfunctionsはconstructableではなく、[[Construct]] internal methodまたは"prototype" propertyを持たない。
  34. funcを返す。
Note

CreateDynamicFunctionは、そのkindasyncでない、作成する任意のfunctionに対して"prototype" propertyを定義し、そのfunctionがconstructorとして使用される可能性に備えます。

20.2.2 Properties of the Function Constructor

Function constructorは:

  • それ自体がbuilt-in function objectです。
  • valueが%Function.prototype%である[[Prototype]] internal slotを持ちます。
  • valueが1𝔽である"length" propertyを持ちます。
  • 次のpropertiesを持ちます:

20.2.2.1 Function.prototype

Function.prototypeのvalueはFunction prototype objectです。

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

20.2.3 Properties of the Function Prototype Object

Function prototype objectは:

  • %Function.prototype%です。
  • それ自体がbuilt-in function objectです。
  • 任意のargumentsをacceptし、invokedされたときundefinedを返します。
  • [[Construct]] internal methodを持ちません;new operatorを伴うconstructorとして使用できません。
  • valueが%Object.prototype%である[[Prototype]] internal slotを持ちます。
  • "prototype" propertyを持ちません。
  • valueが+0𝔽である"length" propertyを持ちます。
  • valueがempty Stringである"name" propertyを持ちます。
Note

Function prototype objectは、ECMAScript 2015 specificationより前に作成されたECMAScript codeとのcompatibilityを保証するため、function objectであると指定されています。

20.2.3.1 Function.prototype.apply ( thisArg, argArray )

このmethodは呼び出されたとき、次のstepsを実行します:

  1. functhis valueとする。
  2. IsCallable(func)がfalseなら、TypeError例外をthrowする。
  3. argArrayundefinedまたはnullのいずれかなら、
    1. PrepareForTailCall()を実行する。
    2. Call(func, thisArg)を返す。
  4. argListを ? CreateListFromArrayLike(argArray) とする。
  5. PrepareForTailCall()を実行する。
  6. Call(func, thisArg, argList)を返す。
Note 1

thisArg valueは、modificationなしでthis valueとして渡されます。これはEdition 3からのchangeであり、そこではundefinedまたはnullthisArgglobal objectで置き換えられ、他のすべてのvaluesにはToObjectが適用され、そのresultがthis valueとして渡されていました。thisArgはmodificationなしで渡されますが、non-strict functionsはfunctionへのentry時に引き続きこれらのtransformationsを実行します。

Note 2

funcがarrow functionまたはbound function exotic objectのいずれかである場合、step 6のfunction [[Call]]によってthisArgはignoredされます。

20.2.3.2 Function.prototype.bind ( thisArg, ...args )

このmethodは呼び出されたとき、次のstepsを実行します:

  1. targetthis valueとする。
  2. IsCallable(target)がfalseなら、TypeError例外をthrowする。
  3. boundFuncを ? BoundFunctionCreate(target, thisArg, args) とする。
  4. lengthを0とする。
  5. targetHasLengthを ? HasOwnProperty(target, "length") とする。
  6. targetHasLengthtrueなら、
    1. targetLengthを ? Get(target, "length") とする。
    2. targetLengthがNumberなら、
      1. targetLength+∞𝔽なら、
        1. lengthを+∞に設定する。
      2. そうでなく、targetLength-∞𝔽なら、
        1. lengthを0に設定する。
      3. そうでなければ、
        1. targetLengthAsIntを ! ToIntegerOrInfinity(targetLength) とする。
        2. Assert: targetLengthAsIntfiniteである。
        3. argCountargs内の要素数とする。
        4. lengthmax(targetLengthAsInt - argCount, 0)に設定する。
  7. SetFunctionLength(boundFunc, length)を実行する。
  8. targetNameを ? Get(target, "name") とする。
  9. targetNameがStringでないなら、targetNameをempty Stringに設定する。
  10. SetFunctionName(boundFunc, targetName, "bound")を実行する。
  11. boundFuncを返す。
Note 1

Function.prototype.bindを使用して作成されたFunction objectsexotic objectsです。それらはまた"prototype" propertyを持ちません。

Note 2

targetがarrow functionまたはbound function exotic objectのいずれかである場合、このmethodに渡されたthisArgfuncへのsubsequent callsによって使用されません。

20.2.3.3 Function.prototype.call ( thisArg, ...args )

このmethodは呼び出されたとき、次のstepsを実行します:

  1. functhis valueとする。
  2. IsCallable(func)がfalseなら、TypeError例外をthrowする。
  3. PrepareForTailCall()を実行する。
  4. Call(func, thisArg, args)を返す。
Note 1

thisArg valueは、modificationなしでthis valueとして渡されます。これはEdition 3からのchangeであり、そこではundefinedまたはnullthisArgglobal objectで置き換えられ、他のすべてのvaluesにはToObjectが適用され、そのresultがthis valueとして渡されていました。thisArgはmodificationなしで渡されますが、non-strict functionsはfunctionへのentry時に引き続きこれらのtransformationsを実行します。

Note 2

funcがarrow functionまたはbound function exotic objectのいずれかである場合、step 4のfunction [[Call]]によってthisArgはignoredされます。

20.2.3.4 Function.prototype.constructor

Function.prototype.constructorのinitial valueは%Function%です。

20.2.3.5 Function.prototype.toString ( )

このmethodは呼び出されたとき、次のstepsを実行します:

  1. functhis valueとする。
  2. funcがObjectであり、func[[SourceText]] internal slotを持ち、func.[[SourceText]]がUnicode code pointsのsequenceであり、かつHostHasSourceTextAvailable(func)がtrueなら、
    1. CodePointsToString(func.[[SourceText]])を返す。
  3. funcbuilt-in function objectなら、funcimplementation-defined String source code representationを返す。そのrepresentationはNativeFunctionのsyntaxを持たなければなりません。加えて、func[[InitialName]] internal slotを持ち、func.[[InitialName]]がStringである場合、NativeFunctionAccessoropt PropertyNameにmatchするreturned Stringのportionはfunc.[[InitialName]]でなければなりません。
  4. funcがObjectであり、IsCallable(func)がtrueなら、funcimplementation-defined String source code representationを返す。そのrepresentationはNativeFunctionのsyntaxを持たなければなりません。
  5. TypeError例外をThrowする。
NativeFunction : function NativeFunctionAccessoropt PropertyName[~Yield, ~Await]opt ( FormalParameters[~Yield, ~Await] ) { [ native code ] } NativeFunctionAccessor : get set

20.2.3.6 Function.prototype [ %Symbol.hasInstance% ] ( value )

このmethodは呼び出されたとき、次のstepsを実行します:

  1. thisValuethis valueとする。
  2. OrdinaryHasInstance(thisValue, value)を返す。

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

Note

これは、ほとんどのfunctionsがinheritする%Symbol.hasInstance%のdefault implementationです。%Symbol.hasInstance%は、valueがspecific constructorのinstanceであるかどうかをdetermineするためにinstanceof operatorによって呼び出されます。次のようなexpressionは、

v instanceof F

次のようにevaluatesされます

F[%Symbol.hasInstance%](v)

constructor functionは、function上に異なる%Symbol.hasInstance% methodをexposeすることによって、instanceofによってどのobjectsがそのinstancesとしてrecognizedされるかをcontrolできます。

このpropertyは、bound functionのtarget functionをgloballyにexposeするために使用され得るtamperingを防ぐため、non-writableかつnon-configurableです。

このmethodの"name" propertyのvalueは"[Symbol.hasInstance]"です。

20.2.4 Function Instances

すべてのFunction instanceはECMAScript function objectであり、Table 26に列挙されたinternal slotsを持ちます。Function.prototype.bind method(20.2.3.2)を使用して作成されたFunction objectsは、Table 27に列挙されたinternal slotsを持ちます。

Function instancesは次のpropertiesを持ちます:

20.2.4.1 length

"length" propertyのvalueは、functionによってexpectedされるtypical number of argumentsを示すintegral Numberです。ただし、languageはfunctionが他のnumber of argumentsでinvokedされることを許します。"length" propertyによって指定される数以外のnumber of argumentsでinvokedされたときのfunctionのbehaviourは、そのfunctionに依存します。このpropertyはattributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }を持ちます。

20.2.4.2 name

"name" propertyのvalueは、functionをdescriptiveするStringです。nameにsemantic significanceはありませんが、通常はECMAScript source text内のdefinition pointでfunctionをreferするために使用されるvariableまたはproperty nameです。このpropertyはattributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }を持ちます。

この仕様によってcontextual nameが関連付けられていないAnonymous function objectsは、"name" propertyのvalueとしてempty Stringを使用します。

20.2.4.3 prototype

constructorとして使用できるFunction instancesは"prototype" propertyを持ちます。そのようなFunction instanceが作成されるたびに、別のordinary objectも作成され、functionの"prototype" propertyのinitial valueになります。特に指定されない限り、"prototype" propertyのvalueは、そのfunctionがconstructorとしてinvokedされたときに作成されるobjectの[[Prototype]] internal slotをinitializeするために使用されます。

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

Note

Function.prototype.bindを使用して作成されたFunction objects、またはMethodDefinitionGeneratorMethodまたはAsyncGeneratorMethodでないもの)もしくはArrowFunctionをevaluateすることによって作成されたFunction objectsは、"prototype" propertyを持ちません。

20.2.5 HostHasSourceTextAvailable ( func )

The host-defined abstract operation HostHasSourceTextAvailable takes argument func (a function object) and returns a Boolean. host environmentsfuncに対してsource textが提供されることをpreventできるようにします。

HostHasSourceTextAvailableのimplementationは、次のrequirementsにconformしなければなりません:

  • これはそのparametersに関してdeterministicでなければなりません。specific funcをargumentとして呼び出されるたびに、同じresultを返さなければなりません。

HostHasSourceTextAvailableのdefault implementationはtrueを返すことです。

20.3 Boolean Objects

20.3.1 The Boolean Constructor

Boolean constructorは:

  • %Boolean%です。
  • global object"Boolean" propertyのinitial valueです。
  • constructorとして呼び出されたとき、新しいBoolean objectを作成およびinitializeします。
  • constructorとしてではなくfunctionとして呼び出されたとき、type conversionを実行します。
  • class definitionのextends clauseのvalueとして使用できます。指定されたBoolean behaviourをinheritしようとするsubclass constructorsは、[[BooleanData]] internal slotを持つsubclass instanceを作成およびinitializeするために、Boolean constructorへのsuper callを含まなければなりません。

20.3.1.1 Boolean ( value )

このfunctionは呼び出されたとき、次のstepsを実行します:

  1. boolToBoolean(value)とする。
  2. NewTargetがundefinedなら、boolを返す。
  3. objを ? OrdinaryCreateFromConstructor(NewTarget, "%Boolean.prototype%", « [[BooleanData]] ») とする。
  4. obj.[[BooleanData]]boolに設定する。
  5. objを返す。

20.3.2 Properties of the Boolean Constructor

Boolean constructorは:

  • valueが%Function.prototype%である[[Prototype]] internal slotを持ちます。
  • 次のpropertiesを持ちます:

20.3.2.1 Boolean.prototype

Boolean.prototypeのinitial valueはBoolean prototype objectです。

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

20.3.3 Properties of the Boolean Prototype Object

Boolean prototype objectは:

  • %Boolean.prototype%です。
  • ordinary objectです。
  • それ自体がBoolean objectです;valueがfalseである[[BooleanData]] internal slotを持ちます。
  • valueが%Object.prototype%である[[Prototype]] internal slotを持ちます。

20.3.3.1 Boolean.prototype.constructor

Boolean.prototype.constructorのinitial valueは%Boolean%です。

20.3.3.2 Boolean.prototype.toString ( )

このmethodは呼び出されたとき、次のstepsを実行します:

  1. boolを ? ThisBooleanValue(this value) とする。
  2. booltrueなら、"true"を返す。
  3. "false"を返す。

20.3.3.3 Boolean.prototype.valueOf ( )

このmethodは呼び出されたとき、次のstepsを実行します:

  1. ThisBooleanValue(this value)を返す。

20.3.3.3.1 ThisBooleanValue ( arg )

The abstract operation ThisBooleanValue takes argument arg (an ECMAScript language value) and returns either a normal completion containing a Boolean or a throw completion. It performs the following steps when called:

  1. argがBooleanなら、argを返す。
  2. argがObjectであり、arg[[BooleanData]] internal slotを持つなら、
    1. boolarg.[[BooleanData]]とする。
    2. Assert: boolはBooleanである。
    3. boolを返す。
  3. TypeError例外をThrowする。

20.3.4 Properties of Boolean Instances

Boolean instancesは、Boolean prototype objectからpropertiesをinheritするordinary objectsです。Boolean instancesは[[BooleanData]] internal slotを持ちます。[[BooleanData]] internal slotは、このBoolean objectによって表されるBoolean valueです。

20.4 Symbol Objects

20.4.1 The Symbol Constructor

Symbol constructorは:

  • %Symbol%です。
  • global object"Symbol" propertyのinitial valueです。
  • functionとして呼び出されたとき、新しいSymbol valueを返します。
  • new operatorとともに使用されることを意図していません。
  • subclassedされることを意図していません。
  • class definitionのextends clauseのvalueとして使用できますが、それへのsuper callはexceptionを引き起こします。

20.4.1.1 Symbol ( [ description ] )

このfunctionは呼び出されたとき、次のstepsを実行します:

  1. NewTargetがundefinedでないなら、TypeError例外をthrowする。
  2. descriptionundefinedなら、descStringundefinedとする。
  3. そうでなければ、descStringを ? ToString(description) とする。
  4. ... [[Description]]descStringである新しいSymbolを返す。

20.4.2 Properties of the Symbol Constructor

Symbol constructorは:

  • valueが%Function.prototype%である[[Prototype]] internal slotを持ちます。
  • 次のpropertiesを持ちます:

20.4.2.1 Symbol.asyncIterator

Symbol.asyncIteratorのinitial valueはwell-known symbol %Symbol.asyncIterator%Table 1)です。

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

20.4.2.2 Symbol.for ( key )

このfunctionは呼び出されたとき、次のstepsを実行します:

  1. stringKey を ? ToString(key) とする。
  2. agentRecord を周囲のエージェントの Agent Record とする。
  3. globalSymbolRegistryagentRecord.[[GlobalSymbolRegistry]] とする。
  4. globalSymbolRegistry の各要素 element について、次を行う。
    1. element.[[Key]]stringKey である場合、element.[[Symbol]] を返す。
  5. Assert: globalSymbolRegistry は現在、stringKey に対するエントリーを含んでいない。
  6. newSymbol を、[[Description]]stringKey である新しい Symbol とする。
  7. GlobalSymbolRegistry Record { [[Key]]: stringKey, [[Symbol]]: newSymbol } を globalSymbolRegistry に追加する。
  8. newSymbol を返す。

20.4.2.3 Symbol.hasInstance

Symbol.hasInstanceのinitial valueはwell-known symbol %Symbol.hasInstance%Table 1)です。

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

20.4.2.4 Symbol.isConcatSpreadable

Symbol.isConcatSpreadableのinitial valueはwell-known symbol %Symbol.isConcatSpreadable%Table 1)です。

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

20.4.2.5 Symbol.iterator

Symbol.iteratorのinitial valueはwell-known symbol %Symbol.iterator%Table 1)です。

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

20.4.2.6 Symbol.keyFor ( symbol )

このfunctionは呼び出されたとき、次のstepsを実行します:

  1. symbolがSymbolでないなら、TypeError例外をthrowする。
  2. KeyForSymbol(symbol)を返す。

20.4.2.7 Symbol.match

Symbol.matchのinitial valueはwell-known symbol %Symbol.match%Table 1)です。

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

20.4.2.8 Symbol.matchAll

Symbol.matchAllのinitial valueはwell-known symbol %Symbol.matchAll%Table 1)です。

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

20.4.2.9 Symbol.prototype

Symbol.prototypeのinitial valueはSymbol prototype objectです。

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

20.4.2.10 Symbol.replace

Symbol.replaceのinitial valueはwell-known symbol %Symbol.replace%Table 1)です。

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

20.4.2.11 Symbol.search

Symbol.searchのinitial valueはwell-known symbol %Symbol.search%Table 1)です。

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

20.4.2.12 Symbol.species

Symbol.speciesのinitial valueはwell-known symbol %Symbol.species%Table 1)です。

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

20.4.2.13 Symbol.split

Symbol.splitのinitial valueはwell-known symbol %Symbol.split%Table 1)です。

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

20.4.2.14 Symbol.toPrimitive

Symbol.toPrimitiveのinitial valueはwell-known symbol %Symbol.toPrimitive%Table 1)です。

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

20.4.2.15 Symbol.toStringTag

Symbol.toStringTagのinitial valueはwell-known symbol %Symbol.toStringTag%Table 1)です。

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

20.4.2.16 Symbol.unscopables

Symbol.unscopablesのinitial valueはwell-known symbol %Symbol.unscopables%Table 1)です。

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

20.4.3 Properties of the Symbol Prototype Object

Symbol prototype objectは:

  • %Symbol.prototype%です。
  • ordinary objectです。
  • Symbol instanceではなく、[[SymbolData]] internal slotを持ちません。
  • valueが%Object.prototype%である[[Prototype]] internal slotを持ちます。

20.4.3.1 Symbol.prototype.constructor

Symbol.prototype.constructorのinitial valueは%Symbol%です。

20.4.3.2 get Symbol.prototype.description

Symbol.prototype.descriptionは、set accessor functionがundefinedであるaccessor propertyです。そのget accessor functionは呼び出されたとき、次のstepsを実行します:

  1. symbolを ? ThisSymbolValue(this value) とする。
  2. symbol.[[Description]]を返す。

20.4.3.3 Symbol.prototype.toString ( )

このmethodは呼び出されたとき、次のstepsを実行します:

  1. symbolを ? ThisSymbolValue(this value) とする。
  2. SymbolDescriptiveString(symbol)を返す。

20.4.3.3.1 SymbolDescriptiveString ( symbol )

The abstract operation SymbolDescriptiveString takes argument symbol (a Symbol) and returns a String. It performs the following steps when called:

  1. symbol.[[Description]]descriptionとする。
  2. descriptionundefinedである場合、descriptionを空のStringに設定する。
  3. Assert: descriptionはStringである。
  4. "Symbol("description、および")"string-concatenationを返す。

20.4.3.4 Symbol.prototype.valueOf ( )

このmethodは呼び出されたとき、次のstepsを実行します:

  1. ThisSymbolValue(this value)を返す。

20.4.3.4.1 ThisSymbolValue ( arg )

The abstract operation ThisSymbolValue takes argument arg (an ECMAScript language value) and returns either a normal completion containing a Symbol or a throw completion. It performs the following steps when called:

  1. argがSymbolなら、argを返す。
  2. argがObjectであり、arg[[SymbolData]] internal slotを持つなら、
    1. symbolarg.[[SymbolData]]とする。
    2. Assert: symbolはSymbolである。
    3. symbolを返す。
  3. TypeError例外をThrowする。

20.4.3.5 Symbol.prototype [ %Symbol.toPrimitive% ] ( hint )

このmethodは、Symbol objectをprimitive valueへconvertするためにECMAScript language operatorsによって呼び出されます。

これは呼び出されたとき、次のstepsを実行します:

  1. ThisSymbolValue(this value)を返す。
Note

argumentはignoredされます。

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

このmethodの"name" propertyのvalueは"[Symbol.toPrimitive]"です。

20.4.3.6 Symbol.prototype [ %Symbol.toStringTag% ]

%Symbol.toStringTag% propertyのinitial valueはString value "Symbol"です。

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

20.4.4 Properties of Symbol Instances

Symbol instancesは、Symbol prototype objectからpropertiesをinheritするordinary objectsです。Symbol instancesは[[SymbolData]] internal slotを持ちます。[[SymbolData]] internal slotは、このSymbol objectによって表されるSymbol valueです。

20.4.5 Abstract Operations for Symbols

20.4.5.1 GlobalSymbolRegistry Records

GlobalSymbolRegistry Record は、Symbol.for を通じて登録された Symbol 値に String キーを関連付けるために使用される Record 値である。

GlobalSymbolRegistry Records は、Table 59 に列挙されたフィールドを持つ。

Table 59: GlobalSymbolRegistry Record のフィールド
フィールド名 用途
[[Key]] String Symbol をグローバルに識別するために使用される文字列キー。
[[Symbol]] Symbol 任意の realm から取得できるシンボル。

20.4.5.2 KeyForSymbol ( symbol )

The abstract operation KeyForSymbol takes argument symbol (a Symbol) and returns a String or undefined. symbol が周囲のエージェントの [[GlobalSymbolRegistry]] List 内にある場合、symbol の登録に使用された String が返される。 It performs the following steps when called:

  1. agentRecord を周囲のエージェントの Agent Record とする。
  2. globalSymbolRegistryagentRecord.[[GlobalSymbolRegistry]] とする。
  3. globalSymbolRegistry の各要素 element について、次を行う。
    1. SameValue(element.[[Symbol]], symbol) が true である場合、element.[[Key]] を返す。
  4. Assert: globalSymbolRegistry は現在、symbol に対するエントリーを含んでいない。
  5. undefined を返す。

20.5 Error Objects

runtime errorsが発生したとき、Error objectsのinstancesはexceptionsとしてthrownされます。Error objectsはuser-defined exception classesのbase objectsとしてもserveする場合があります。

ECMAScript 実装が実行時エラーを検出した場合、20.5.5 で定義される NativeError オブジェクトのいずれかの新しいインスタンス、または 20.5.7 で定義される AggregateError オブジェクト、もしくは 20.5.8 で定義される SuppressedError オブジェクトの新しいインスタンスを投げる。これらの各オブジェクトは以下に記述される構造を持ち、違いは NativeError の代わりにコンストラクタ名として使用される名前、プロトタイプオブジェクトの "name" プロパティ、プロトタイプオブジェクトの実装定義の "message" プロパティ、および %AggregateError% 固有の "errors" プロパティまたは %SuppressedError% 固有の "error" および "suppressed" プロパティの存在のみである。

20.5.1 The Error Constructor

Error constructorは:

  • %Error%です。
  • global object"Error" propertyのinitial valueです。
  • constructorとしてではなくfunctionとして呼び出されたとき、新しいError objectを作成およびinitializeします。したがってfunction call Error(…)は、同じargumentsを伴うobject creation expression new Error(…)と同等です。
  • class definitionのextends clauseのvalueとして使用できます。指定されたError behaviourをinheritしようとするsubclass constructorsは、[[ErrorData]] internal slotを持つsubclass instancesを作成およびinitializeするために、Error constructorへのsuper callを含まなければなりません。

20.5.1.1 Error ( message [ , options ] )

このfunctionは呼び出されたとき、次のstepsを実行します:

  1. NewTargetがundefinedなら、newTargetactive function objectとする;そうでなければ、newTargetをNewTargetとする。
  2. objを ? OrdinaryCreateFromConstructor(newTarget, "%Error.prototype%", « [[ErrorData]] ») とする。
  3. messageundefinedでないなら、
    1. messageStringを ? ToString(message) とする。
    2. CreateNonEnumerableDataPropertyOrThrow(obj, "message", messageString)を実行する。
  4. InstallErrorCause(obj, options)を実行する。
  5. objを返す。

20.5.2 Properties of the Error Constructor

Error constructorは:

  • valueが%Function.prototype%である[[Prototype]] internal slotを持ちます。
  • 次のpropertiesを持ちます:

20.5.2.1 Error.isError ( arg )

このfunctionは呼び出されたとき、次のstepsを実行します:

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

20.5.2.2 Error.prototype

Error.prototypeのinitial valueはError prototype objectです。

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

20.5.3 Properties of the Error Prototype Object

Error prototype objectは:

  • %Error.prototype%です。
  • ordinary objectです。
  • Error instanceではなく、[[ErrorData]] internal slotを持ちません。
  • valueが%Object.prototype%である[[Prototype]] internal slotを持ちます。

20.5.3.1 Error.prototype.constructor

Error.prototype.constructorのinitial valueは%Error%です。

20.5.3.2 Error.prototype.message

Error.prototype.messageのinitial valueはempty Stringです。

20.5.3.3 Error.prototype.name

Error.prototype.nameのinitial valueは"Error"です。

20.5.3.4 Error.prototype.toString ( )

このmethodは呼び出されたとき、次のstepsを実行します:

  1. objthis valueとする。
  2. objがObjectでないなら、TypeError例外をthrowする。
  3. nameを ? Get(obj, "name") とする。
  4. nameundefinedなら、name"Error"に設定する;そうでなければ、nameを ? ToString(name) に設定する。
  5. messageを ? Get(obj, "message") とする。
  6. messageundefinedなら、messageをempty Stringに設定する;そうでなければ、messageを ? ToString(message) に設定する。
  7. nameがempty Stringなら、messageを返す。
  8. messageがempty Stringなら、nameを返す。
  9. name、code unit 0x003A (COLON)、code unit 0x0020 (SPACE)、およびmessagestring-concatenationを返す。

20.5.4 Properties of Error Instances

Error インスタンスは、Error プロトタイプオブジェクトからプロパティを継承し、値が undefined である [[ErrorData]] 内部スロットを持つ通常のオブジェクトである。[[ErrorData]] の唯一の仕様上の用途は、Object.prototype.toString および Error.isError において、Error、AggregateError、SuppressedError、および NativeError インスタンスを Error オブジェクトとして識別することである。

20.5.5 Native Error Types Used in This Standard

実行時エラーが検出された場合、以下の NativeError オブジェクトのいずれか、または AggregateError オブジェクトもしくは SuppressedError オブジェクトの新しいインスタンスが投げられる。すべての NativeError オブジェクトは、20.5.6 に記述される同じ構造を共有する。

20.5.5.1 EvalError

EvalError constructor%EvalError%です。

このexceptionは現在この仕様内では使用されていません。このobjectは、この仕様のprevious editionsとのcompatibilityのために残されています。

20.5.5.2 RangeError

RangeError constructor%RangeError%です。

allowable valuesのsetまたはrange内にないvalueを示します。

20.5.5.3 ReferenceError

ReferenceError constructor%ReferenceError%です。

invalid referenceがdetectedされたことを示します。

20.5.5.4 SyntaxError

SyntaxError constructor%SyntaxError%です。

parsing errorが発生したことを示します。

20.5.5.5 TypeError

TypeError constructor%TypeError%です。

TypeErrorは、他のNativeError objectsのいずれもfailure causeのappropriate indicationでない場合に、unsuccessful operationを示すために使用されます。

20.5.5.6 URIError

URIError constructor%URIError%です。

global URI handling functionsの1つが、そのdefinitionとincompatibleな方法で使用されたことを示します。

20.5.6 NativeError Object Structure

これらの各objectは、constructor nameとして使用されるnameおよびprototype objectの"name" propertyだけが異なり、以下に記述されるstructureを持ちます。

各error objectについて、definition内のNativeErrorへのreferencesは、20.5.5からのappropriate error object nameで置き換えられるべきです。

20.5.6.1 The NativeError Constructors

NativeError constructorは:

  • constructorとしてではなくfunctionとして呼び出されたとき、新しいNativeError objectを作成およびinitializeします。functionとしてのobjectのcallは、同じargumentsでconstructorとして呼び出すことと同等です。したがってfunction call NativeError(…)は、同じargumentsを伴うobject creation expression new NativeError(…)と同等です。
  • class definitionのextends clauseのvalueとして使用できます。指定されたNativeError behaviourをinheritしようとするsubclass constructorsは、[[ErrorData]] internal slotを持つsubclass instancesを作成およびinitializeするために、NativeError constructorへのsuper callを含まなければなりません。

20.5.6.1.1 NativeError ( message [ , options ] )

NativeError functionは呼び出されたとき、次のstepsを実行します:

  1. NewTargetがundefinedなら、newTargetactive function objectとする;そうでなければ、newTargetをNewTargetとする。
  2. objを ? OrdinaryCreateFromConstructor(newTarget, "%NativeError.prototype%", « [[ErrorData]] ») とする。
  3. messageundefinedでないなら、
    1. messageStringを ? ToString(message) とする。
    2. CreateNonEnumerableDataPropertyOrThrow(obj, "message", messageString)を実行する。
  4. InstallErrorCause(obj, options)を実行する。
  5. objを返す。

step 2で渡されるstringのactual valueは、定義されているNativeError constructorに対応して、"%EvalError.prototype%""%RangeError.prototype%""%ReferenceError.prototype%""%SyntaxError.prototype%""%TypeError.prototype%"、または"%URIError.prototype%"のいずれかです。

20.5.6.2 Properties of the NativeError Constructors

NativeError constructorは:

  • valueが%Error%である[[Prototype]] internal slotを持ちます。
  • valueがString value "NativeError"である"name" propertyを持ちます。
  • 次のpropertiesを持ちます:

20.5.6.2.1 NativeError.prototype

NativeError.prototypeのinitial valueはNativeError prototype object(20.5.6.3)です。各NativeError constructorはdistinct prototype objectを持ちます。

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

20.5.6.3 Properties of the NativeError Prototype Objects

NativeError prototype objectは:

  • ordinary objectです。
  • Error instanceではなく、[[ErrorData]] internal slotを持ちません。
  • valueが%Error.prototype%である[[Prototype]] internal slotを持ちます。

20.5.6.3.1 NativeError.prototype.constructor

与えられたNativeError constructorに対するprototypeの"constructor" propertyのinitial valueは、そのconstructor自身です。

20.5.6.3.2 NativeError.prototype.message

与えられたNativeError constructorに対するprototypeの"message" propertyのinitial valueはempty Stringです。

20.5.6.3.3 NativeError.prototype.name

与えられたNativeError constructorに対するprototypeの"name" propertyのinitial valueは、constructorのname(NativeErrorの代わりに使用されるname)から構成されるString valueです。

20.5.6.4 Properties of NativeError Instances

NativeError インスタンスは、自身の NativeError プロトタイプオブジェクトからプロパティを継承し、値が undefined である [[ErrorData]] 内部スロットを持つ通常のオブジェクトである。[[ErrorData]] の唯一の仕様上の用途は、Object.prototype.toString20.1.3.6)および Error.isError20.5.2.1)によって、Error、AggregateError、SuppressedError、または NativeError インスタンスを識別することである。

20.5.7 AggregateError Objects

20.5.7.1 The AggregateError Constructor

AggregateError constructorは:

  • %AggregateError%です。
  • global object"AggregateError" propertyのinitial valueです。
  • constructorとしてではなくfunctionとして呼び出されたとき、新しいAggregateError objectを作成およびinitializeします。したがってfunction call AggregateError(…)は、同じargumentsを伴うobject creation expression new AggregateError(…)と同等です。
  • class definitionのextends clauseのvalueとして使用できます。指定されたAggregateError behaviourをinheritしようとするsubclass constructorsは、[[ErrorData]] internal slotを持つsubclass instancesを作成およびinitializeするために、AggregateError constructorへのsuper callを含まなければなりません。

20.5.7.1.1 AggregateError ( errors, message [ , options ] )

このfunctionは呼び出されたとき、次のstepsを実行します:

  1. NewTargetがundefinedなら、newTargetactive function objectとする;そうでなければ、newTargetをNewTargetとする。
  2. objを ? OrdinaryCreateFromConstructor(newTarget, "%AggregateError.prototype%", « [[ErrorData]] ») とする。
  3. messageundefinedでないなら、
    1. messageStringを ? ToString(message) とする。
    2. CreateNonEnumerableDataPropertyOrThrow(obj, "message", messageString)を実行する。
  4. InstallErrorCause(obj, options)を実行する。
  5. errorsListを ? IteratorToList(? GetIterator(errors, sync)) とする。
  6. DefinePropertyOrThrow(obj, "errors", PropertyDescriptor { [[Configurable]]: true, [[Enumerable]]: false, [[Writable]]: true, [[Value]]: CreateArrayFromList(errorsList) })を実行する。
  7. objを返す。

20.5.7.2 Properties of the AggregateError Constructor

AggregateError constructorは:

  • valueが%Error%である[[Prototype]] internal slotを持ちます。
  • 次のpropertiesを持ちます:

20.5.7.2.1 AggregateError.prototype

AggregateError.prototypeのinitial valueは%AggregateError.prototype%です。

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

20.5.7.3 Properties of the AggregateError Prototype Object

AggregateError prototype objectは:

  • %AggregateError.prototype%です。
  • ordinary objectです。
  • Error instanceでもAggregateError instanceでもなく、[[ErrorData]] internal slotを持ちません。
  • valueが%Error.prototype%である[[Prototype]] internal slotを持ちます。

20.5.7.3.1 AggregateError.prototype.constructor

AggregateError.prototype.constructorのinitial valueは%AggregateError%です。

20.5.7.3.2 AggregateError.prototype.message

AggregateError.prototype.messageのinitial valueはempty Stringです。

20.5.7.3.3 AggregateError.prototype.name

AggregateError.prototype.nameのinitial valueは"AggregateError"です。

20.5.7.4 AggregateError インスタンスのプロパティ

AggregateError インスタンスは、自身の AggregateError プロトタイプオブジェクトからプロパティを継承し、値が undefined である [[ErrorData]] 内部スロットを持つ通常のオブジェクトである。[[ErrorData]] の唯一の仕様上の用途は、Object.prototype.toString20.1.3.6)および Error.isError20.5.2.1)によって、Error、AggregateError、SuppressedError、または NativeError インスタンスを識別することである。

20.5.8 SuppressedError オブジェクト

20.5.8.1 SuppressedError コンストラクタ

SuppressedError コンストラクタは次のとおりである:

  • %SuppressedError% である。
  • グローバルオブジェクトの "SuppressedError" プロパティの初期値である。
  • コンストラクタとしてではなく関数として呼び出された場合、新しい SuppressedError オブジェクトを作成して初期化する。したがって、関数呼び出し SuppressedError(…) は、同じ引数を持つオブジェクト作成式 new SuppressedError(…) と等価である。
  • クラス定義の extends 節の値として使用できる。指定された SuppressedError の振る舞いを継承しようとするサブクラスコンストラクタは、[[ErrorData]] 内部スロットを持つサブクラスインスタンスを作成して初期化するために、SuppressedError コンストラクタへの super 呼び出しを含めなければならない。

20.5.8.1.1 SuppressedError ( error, suppressed, message )

この関数は、呼び出されたときに次のステップを実行する:

  1. NewTarget が undefined である場合、newTarget をアクティブな関数オブジェクトとする。そうでなければ、newTarget を NewTarget とする。
  2. obj を ? OrdinaryCreateFromConstructor(newTarget, "%SuppressedError.prototype%", « [[ErrorData]] ») とする。
  3. messageundefined でない場合、then
    1. messageString を ? ToString(message) とする。
    2. CreateNonEnumerableDataPropertyOrThrow(obj, "message", messageString) を実行する。
  4. CreateNonEnumerableDataPropertyOrThrow(obj, "error", error) を実行する。
  5. CreateNonEnumerableDataPropertyOrThrow(obj, "suppressed", suppressed) を実行する。
  6. obj を返す。

20.5.8.2 SuppressedError コンストラクタのプロパティ

SuppressedError コンストラクタは次のとおりである:

  • 値が %Error% である [[Prototype]] 内部スロットを持つ。
  • 次のプロパティを持つ:

20.5.8.2.1 SuppressedError.prototype

SuppressedError.prototype の初期値は SuppressedError プロトタイプオブジェクトである。

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

20.5.8.3 SuppressedError プロトタイプオブジェクトのプロパティ

SuppressedError プロトタイプオブジェクトは次のとおりである:

  • %SuppressedError.prototype% である。
  • 通常のオブジェクトである。
  • Error インスタンスでも SuppressedError インスタンスでもなく、[[ErrorData]] 内部スロットを持たない。
  • 値が %Error.prototype% である [[Prototype]] 内部スロットを持つ。

20.5.8.3.1 SuppressedError.prototype.constructor

SuppressedError.prototype.constructor の初期値は %SuppressedError% である。

20.5.8.3.2 SuppressedError.prototype.message

SuppressedError.prototype.message の初期値は空の String である。

20.5.8.3.3 SuppressedError.prototype.name

SuppressedError.prototype.name の初期値は "SuppressedError" である。

20.5.8.4 SuppressedError インスタンスのプロパティ

SuppressedError インスタンスは、自身の SuppressedError プロトタイプオブジェクトからプロパティを継承し、値が undefined である [[ErrorData]] 内部スロットを持つ通常のオブジェクトである。[[ErrorData]] の唯一の仕様上の用途は、Object.prototype.toString および Error.isError において、Error、AggregateError、SuppressedError、および NativeError インスタンスを Error オブジェクトとして識別することである。

20.5.9 Abstract Operations for Error Objects

20.5.9.1 InstallErrorCause ( obj, options )

The abstract operation InstallErrorCause takes arguments obj (an Object) and options (an ECMAScript language value) and returns either a normal completion containing unused or a throw completion. options上に"cause" propertyが存在する場合に、obj上に"cause" propertyを作成するために使用されます。 It performs the following steps when called:

  1. optionsがObjectであり、? HasProperty(options, "cause")がtrueなら、
    1. causeを ? Get(options, "cause") とする。
    2. CreateNonEnumerableDataPropertyOrThrow(obj, "cause", cause)を実行する。
  2. unusedを返す。

21 Numbers and Dates

21.1 Number Objects

21.1.1 The Number Constructor

Number constructorは:

  • %Number%です。
  • global object"Number" propertyのinitial valueです。
  • constructorとして呼び出されたとき、新しいNumber objectを作成およびinitializeします。
  • constructorとしてではなくfunctionとして呼び出されたとき、type conversionを実行します。
  • class definitionのextends clauseのvalueとして使用できます。指定されたNumber behaviourをinheritしようとするsubclass constructorsは、[[NumberData]] internal slotを持つsubclass instanceを作成およびinitializeするために、Number constructorへのsuper callを含まなければなりません。

21.1.1.1 Number ( value )

このfunctionは呼び出されたとき、次のstepsを実行します:

  1. valueが存在するなら、
    1. primitiveを ? ToNumeric(value) とする。
    2. primitiveがBigIntなら、n𝔽((primitive))とする。
    3. そうでなければ、nprimitiveとする。
  2. そうでなければ、
    1. n+0𝔽とする。
  3. NewTargetがundefinedなら、nを返す。
  4. objを ? OrdinaryCreateFromConstructor(NewTarget, "%Number.prototype%", « [[NumberData]] ») とする。
  5. obj.[[NumberData]]nに設定する。
  6. objを返す。

21.1.2 Properties of the Number Constructor

Number constructorは:

  • valueが%Function.prototype%である[[Prototype]] internal slotを持ちます。
  • 次のpropertiesを持ちます:

21.1.2.1 Number.EPSILON

Number.EPSILONのvalueは、1と、Number valueとしてrepresentableな1より大きい最小のvalueとの差のmagnitudeに対するNumber valueであり、およそ2.2204460492503130808472633361816 × 10-16です。

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

21.1.2.2 Number.isFinite ( number )

このfunctionは呼び出されたとき、次のstepsを実行します:

  1. numberがNumberでないなら、falseを返す。
  2. numberfiniteでないなら、falseを返す。
  3. trueを返す。

21.1.2.3 Number.isInteger ( number )

このfunctionは呼び出されたとき、次のstepsを実行します:

  1. numberintegral Numberなら、trueを返す。
  2. falseを返す。

21.1.2.4 Number.isNaN ( number )

このfunctionは呼び出されたとき、次のstepsを実行します:

  1. numberがNumberでないなら、falseを返す。
  2. numberNaNなら、trueを返す。
  3. falseを返す。
Note

このfunctionは、NaNであるかどうかをdetermineする前にそのargumentをNumberへconvertしないという点で、global isNaN function(19.2.3)とは異なります。

21.1.2.5 Number.isSafeInteger ( number )

Note

integer n は、nに対するNumber valueが他のどのintegerに対するNumber valueでもない場合に限り、“safe integer”です。

このfunctionは呼び出されたとき、次のstepsを実行します:

  1. numberintegral Numberなら、
    1. abs((number)) ≤ 253 - 1なら、trueを返す。
  2. falseを返す。

21.1.2.6 Number.MAX_SAFE_INTEGER

Note

IEEE 754-2019のprecision limitationsによって必要とされるrounding behaviourのため、Number.MAX_SAFE_INTEGERより大きいすべてのintegerに対するNumber valueは、少なくとも1つの他のintegerとsharedされます。したがって、そのようなlarge-magnitude integerssafeではなく、Number valuesとして正確にrepresentableであること、または互いにdistinguishableであることすらguaranteeされません。例えば、90071992547409929007199254740993はいずれもNumber value 9007199254740992𝔽へevaluateされます。

Number.MAX_SAFE_INTEGERのvalueは9007199254740991𝔽𝔽(253 - 1))です。

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

21.1.2.7 Number.MAX_VALUE

Number.MAX_VALUEのvalueはNumber typeのlargest positive finite valueであり、およそ1.7976931348623157 × 10308です。

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

21.1.2.8 Number.MIN_SAFE_INTEGER

Note

IEEE 754-2019のprecision limitationsによって必要とされるrounding behaviourのため、Number.MIN_SAFE_INTEGERより小さいすべてのintegerに対するNumber valueは、少なくとも1つの他のintegerとsharedされます。したがって、そのようなlarge-magnitude integerssafeではなく、Number valuesとして正確にrepresentableであること、または互いにdistinguishableであることすらguaranteeされません。例えば、-9007199254740992-9007199254740993はいずれもNumber value -9007199254740992𝔽へevaluateされます。

Number.MIN_SAFE_INTEGERのvalueは-9007199254740991𝔽𝔽(-(253 - 1)))です。

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

21.1.2.9 Number.MIN_VALUE

Number.MIN_VALUEのvalueはNumber typeのsmallest positive valueであり、およそ5 × 10-324です。

IEEE 754-2019 double precision binary representationでは、smallest possible valueはdenormalized numberです。implementationがdenormalized valuesをsupportしない場合、Number.MIN_VALUEのvalueは、そのimplementationによって実際にrepresentできるsmallest non-zero positive valueでなければなりません。

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

21.1.2.10 Number.NaN

Number.NaNのvalueはNaNです。

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

21.1.2.11 Number.NEGATIVE_INFINITY

Number.NEGATIVE_INFINITYのvalueは-∞𝔽です。

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

21.1.2.12 Number.parseFloat ( string )

"parseFloat" propertyのinitial valueは%parseFloat%です。

21.1.2.13 Number.parseInt ( string, radix )

"parseInt" propertyのinitial valueは%parseInt%です。

21.1.2.14 Number.POSITIVE_INFINITY

Number.POSITIVE_INFINITYのvalueは+∞𝔽です。

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

21.1.2.15 Number.prototype

Number.prototypeのinitial valueはNumber prototype objectです。

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

21.1.3 Properties of the Number Prototype Object

Number prototype objectは:

  • %Number.prototype%です。
  • ordinary objectです。
  • それ自体がNumber objectです;valueが+0𝔽である[[NumberData]] internal slotを持ちます。
  • valueが%Object.prototype%である[[Prototype]] internal slotを持ちます。

明示的に別途述べられない限り、以下で定義されるNumber prototype objectのmethodsはgenericではなく、それらに渡されるthis valueは、Number valueであるか、Number valueへinitialize済みの[[NumberData]] internal slotを持つobjectでなければなりません。

methodのspecification内の“this Number value”というphraseは、method invocationのthis valueをargumentとして渡してabstract operation ThisNumberValueを呼び出した結果を指します。

21.1.3.1 Number.prototype.constructor

Number.prototype.constructorのinitial valueは%Number%です。

21.1.3.2 Number.prototype.toExponential ( fractionDigits )

このmethodは、this Number valueを、significandのdecimal pointの前に1桁、significandのdecimal pointの後にfractionDigits桁を持つdecimal exponential notationで表したStringを返します。fractionDigitsundefinedなら、Numberを一意に指定するために必要なだけのsignificand digitsを含めます(ToStringの場合と同様ですが、この場合Numberは常にexponential notationでoutputされる点が異なります)。

これは呼び出されたとき、次のstepsを実行します:

  1. numberを ? ThisNumberValue(this value) とする。
  2. fractionCountを ? ToIntegerOrInfinity(fractionDigits) とする。
  3. Assert: fractionDigitsundefinedなら、fractionCountは0である。
  4. numberfiniteでないなら、Number::toString(number, 10)を返す。
  5. fractionCount < 0またはfractionCount > 100なら、RangeError例外をthrowする。
  6. number(number)に設定する。
  7. signをempty Stringとする。
  8. number < 0なら、
    1. sign"-"に設定する。
    2. numberを-numberに設定する。
  9. number = 0なら、
    1. significandを、code unit 0x0030 (DIGIT ZERO)がfractionCount + 1回出現するString valueとする。
    2. exponentを0とする。
  10. そうでなければ、
    1. fractionDigitsundefinedでないなら、
      1. exponentおよびintSignificandを、10fractionCountintSignificand < 10fractionCount + 1であり、intSignificand × 10exponent - fractionCount - numberが可能な限りzeroに近くなるようなintegersとする。そのようなexponentおよびintSignificandのsetsが2つある場合、intSignificand × 10exponent - fractionCountがより大きい方のexponentおよびintSignificandを選ぶ。
    2. そうでなければ、
      1. exponentintSignificand、およびffを、ff ≥ 0、10ffintSignificand < 10ff + 1𝔽(intSignificand × 10exponent - ff)が𝔽(number)であり、ffが可能な限りsmallであるようなintegersとする。intSignificandのdecimal representationはff + 1 digitsを持ち、intSignificandは10で割り切れず、intSignificandのleast significant digitはこれらのcriteriaによって必ずしも一意にdeterminedされないことに注意。
      2. fractionCountffに設定する。
    3. significandを、intSignificandのdecimal representationのdigitsからなるString value(order通り、leading zeroesなし)とする。
  11. fractionCount ≠ 0なら、
    1. intPartsignificandの最初のcode unitとする。
    2. fractionalPartsignificandの他のfractionCount個のcode unitsとする。
    3. significandintPart"."、およびfractionalPartstring-concatenationに設定する。
  12. exponent = 0なら、
    1. exponentSign"+"とする。
    2. exponentDigits"0"とする。
  13. そうでなければ、
    1. exponent > 0なら、
      1. exponentSign"+"とする。
    2. そうでなければ、
      1. Assert: exponent < 0である。
      2. exponentSign"-"とする。
      3. exponentを-exponentに設定する。
    3. exponentDigitsを、exponentのdecimal representationのdigitsからなるString value(order通り、leading zeroesなし)とする。
  14. significandsignificand"e"exponentSign、およびexponentDigitsstring-concatenationに設定する。
  15. signsignificandstring-concatenationを返す。
Note

上記のrulesでrequiredされるよりもaccurateなconversionsを提供するimplementationsについては、step 10.b.iの次のalternative versionをguidelineとして使用することがrecommendedされます:

  1. exponentintSignificand、およびffを、ff ≥ 0、10ffintSignificand < 10ff + 1𝔽(intSignificand × 10exponent - ff)が𝔽(number)であり、ffが可能な限りsmallであるようなintegersとする。intSignificandについて複数のpossibilitiesがある場合、𝔽(intSignificand × 10exponent - ff)が𝔽(number)にclosestであるようにintSignificandを選ぶ。そのようなintSignificandのpossible valuesが2つある場合、evenである方を選ぶ。

21.1.3.3 Number.prototype.toFixed ( fractionDigits )

Note 1

このmethodは、this Number valueをdecimal fixed-point notationで表し、decimal pointの後にfractionDigits桁を持つStringを返します。fractionDigitsundefinedなら、0がassumedされます。

これは呼び出されたとき、次のstepsを実行します:

  1. numberを ? ThisNumberValue(this value) とする。
  2. fractionCountを ? ToIntegerOrInfinity(fractionDigits) とする。
  3. Assert: fractionDigitsundefinedなら、fractionCountは0である。
  4. fractionCountfiniteでないなら、RangeError例外をthrowする。
  5. fractionCount < 0またはfractionCount > 100なら、RangeError例外をthrowする。
  6. numberfiniteでないなら、Number::toString(number, 10)を返す。
  7. number(number)に設定する。
  8. signをempty Stringとする。
  9. number < 0なら、
    1. sign"-"に設定する。
    2. numberを-numberに設定する。
  10. number ≥ 1021なら、
    1. digitStringを ! ToString(𝔽(number)) とする。
  11. そうでなければ、
    1. intValueを、intValue / 10fractionCount - numberが可能な限りzeroに近くなるintegerとする。そのようなintValueが2つある場合、より大きいintValueを選ぶ。
    2. intValue = 0なら、digitString"0"とする;そうでなければ、digitStringintValueのdecimal representationのdigitsからなるString value(order通り、leading zeroesなし)とする。
    3. fractionCount ≠ 0なら、
      1. digitCountdigitStringのlengthとする。
      2. digitCountfractionCountなら、
        1. zeroPadを、code unit 0x0030 (DIGIT ZERO)がfractionCount + 1 - digitCount回出現するString valueとする。
        2. digitStringzeroPaddigitStringstring-concatenationに設定する。
        3. digitCountfractionCount + 1に設定する。
      3. intPartdigitStringの最初のdigitCount - fractionCount個のcode unitsとする。
      4. fractionalPartdigitStringの他のfractionCount個のcode unitsとする。
      5. digitStringintPart"."、およびfractionalPartstring-concatenationに設定する。
  12. signdigitStringstring-concatenationを返す。
Note 2

toFixedのoutputは、一部のvaluesについてtoStringよりもpreciseである場合があります。これは、toStringがnumberをadjacent Number valuesとdistinguishするのに十分なsignificant digitsだけをprintするためです。例えば、

(1000000000000000128).toString()"1000000000000000100"を返す一方、
(1000000000000000128).toFixed(0)"1000000000000000128"を返します。

21.1.3.4 Number.prototype.toLocaleString ( [ reserved1 [ , reserved2 ] ] )

ECMA-402 Internationalization APIを含むECMAScript implementationは、このmethodをECMA-402 specificationで指定される通りにimplementしなければなりません。ECMAScript implementationがECMA-402 APIを含まない場合、このmethodの次のspecificationが使用されます:

このmethodは、host environmentのcurrent localeのconventionsに従ってformattedされたthis Number valueを表すString valueをproduceします。このmethodはimplementation-definedであり、toStringと同じものを返すことはpermissibleですが、encouragedはされません。

このmethodのoptional parametersのmeaningsはECMA-402 specificationで定義されます;ECMA-402 supportを含まないimplementationsは、それらのparameter positionsを他の目的に使用してはなりません。

21.1.3.5 Number.prototype.toPrecision ( precision )

このmethodは、this Number valueを、significandのdecimal pointの前に1桁、significandのdecimal pointの後にprecision - 1桁を持つdecimal exponential notation、またはprecision significant digitsを持つdecimal fixed notationのいずれかで表したStringを返します。precisionundefinedなら、代わりにToStringを呼び出します。

これは呼び出されたとき、次のstepsを実行します:

  1. numberを ? ThisNumberValue(this value) とする。
  2. precisionundefinedなら、! ToString(number)を返す。
  3. precisionCountを ? ToIntegerOrInfinity(precision) とする。
  4. numberfiniteでないなら、Number::toString(number, 10)を返す。
  5. precisionCount < 1またはprecisionCount > 100なら、RangeError例外をthrowする。
  6. number(number)に設定する。
  7. signをempty Stringとする。
  8. number < 0なら、
    1. signをcode unit 0x002D (HYPHEN-MINUS)に設定する。
    2. numberを-numberに設定する。
  9. number = 0なら、
    1. significandを、code unit 0x0030 (DIGIT ZERO)がprecisionCount回出現するString valueとする。
    2. exponentを0とする。
  10. そうでなければ、
    1. exponentおよびintSignificandを、10precisionCount - 1intSignificand < 10precisionCountであり、intSignificand × 10exponent - precisionCount + 1 - numberが可能な限りzeroに近くなるようなintegersとする。そのようなexponentおよびintSignificandのsetsが2つある場合、intSignificand × 10exponent - precisionCount + 1がより大きい方のexponentおよびintSignificandを選ぶ。
    2. significandを、intSignificandのdecimal representationのdigitsからなるString value(order通り、leading zeroesなし)とする。
    3. exponent < -6またはexponentprecisionCountなら、
      1. Assert: exponent ≠ 0である。
      2. precisionCount ≠ 1なら、
        1. intPartsignificandの最初のcode unitとする。
        2. fractionalPartsignificandの他のprecisionCount - 1個のcode unitsとする。
        3. significandintPart"."、およびfractionalPartstring-concatenationに設定する。
      3. exponent > 0なら、
        1. exponentSignをcode unit 0x002B (PLUS SIGN)とする。
      4. そうでなければ、
        1. Assert: exponent < 0である。
        2. exponentSignをcode unit 0x002D (HYPHEN-MINUS)とする。
        3. exponentを-exponentに設定する。
      5. exponentDigitsを、exponentのdecimal representationのdigitsからなるString value(order通り、leading zeroesなし)とする。
      6. signsignificand、code unit 0x0065 (LATIN SMALL LETTER E)、exponentSign、およびexponentDigitsstring-concatenationを返す。
  11. exponent = precisionCount - 1なら、signsignificandstring-concatenationを返す。
  12. exponent ≥ 0なら、
    1. significandを、significandの最初のexponent + 1個のcode units、code unit 0x002E (FULL STOP)、およびsignificandの残りのprecisionCount - (exponent + 1)個のcode unitsのstring-concatenationに設定する。
  13. そうでなければ、
    1. significandを、code unit 0x0030 (DIGIT ZERO)、code unit 0x002E (FULL STOP)、code unit 0x0030 (DIGIT ZERO)の-(exponent + 1)回のoccurrences、およびString significandstring-concatenationに設定する。
  14. signsignificandstring-concatenationを返す。

21.1.3.6 Number.prototype.toString ( [ radix ] )

Note

optional radixは、2𝔽から36𝔽までのinclusive interval内にあるintegral Number valueであるべきです。radixundefinedなら、10𝔽radixのvalueとして使用されます。

このmethodは呼び出されたとき、次のstepsを実行します:

  1. xを ? ThisNumberValue(this value) とする。
  2. radixundefinedなら、radixMVを10とする。
  3. そうでなければ、radixMVを ? ToIntegerOrInfinity(radix) とする。
  4. radixMVが2から36までのinclusive interval内にないなら、RangeError例外をthrowする。
  5. Number::toString(x, radixMV)を返す。

このmethodはgenericではありません;そのthis valueがNumberまたはNumber objectでない場合、TypeError例外をthrowします。したがって、methodとして使用するために他の種類のobjectsへtransferすることはできません。

このmethodの"length" propertyは1𝔽です。

21.1.3.7 Number.prototype.valueOf ( )

  1. ThisNumberValue(this value)を返す。

21.1.3.7.1 ThisNumberValue ( arg )

The abstract operation ThisNumberValue takes argument arg (an ECMAScript language value) and returns either a normal completion containing a Number or a throw completion. It performs the following steps when called:

  1. argがNumberなら、argを返す。
  2. argがObjectであり、arg[[NumberData]] internal slotを持つなら、
    1. numberarg.[[NumberData]]とする。
    2. Assert: numberはNumberである。
    3. numberを返す。
  3. TypeError例外をThrowする。

21.1.4 Properties of Number Instances

Number instancesは、Number prototype objectからpropertiesをinheritするordinary objectsです。Number instancesはまた[[NumberData]] internal slotを持ちます。[[NumberData]] internal slotは、このNumber objectによって表されるNumber valueです。

21.2 BigInt Objects

21.2.1 The BigInt Constructor

BigInt constructorは:

  • %BigInt%です。
  • global object"BigInt" propertyのinitial valueです。
  • constructorとしてではなくfunctionとして呼び出されたとき、type conversionを実行します。
  • new operatorとともに使用すること、またはsubclassedされることを意図していません。class definitionのextends clauseのvalueとして使用できますが、BigInt constructorへのsuper callはexceptionを引き起こします。

21.2.1.1 BigInt ( value )

このfunctionは呼び出されたとき、次のstepsを実行します:

  1. NewTargetがundefinedでないなら、TypeError例外をthrowする。
  2. primitiveを ? ToPrimitive(value, number) とする。
  3. primitiveがNumberなら、? NumberToBigInt(primitive)を返す。
  4. ToBigInt(primitive)を返す。

21.2.1.1.1 NumberToBigInt ( number )

The abstract operation NumberToBigInt takes argument number (a Number) and returns either a normal completion containing a BigInt or a throw completion. It performs the following steps when called:

  1. numberintegral Numberでないなら、RangeError例外をthrowする。
  2. ((number))を返す。

21.2.2 Properties of the BigInt Constructor

BigInt constructorは:

  • valueが%Function.prototype%である[[Prototype]] internal slotを持ちます。
  • 次のpropertiesを持ちます:

21.2.2.1 BigInt.asIntN ( bits, bigint )

このfunctionは呼び出されたとき、次のstepsを実行します:

  1. bitsを? ToIndex(bits)に設定する。
  2. bigintを? ToBigInt(bigint)に設定する。
  3. (bigint) modulo 2bitsremainderとする。
  4. remainder ≥ 2bits - 1である場合、(remainder - 2bits)を返す。
  5. (remainder)を返す。

21.2.2.2 BigInt.asUintN ( bits, bigint )

このfunctionは呼び出されたとき、次のstepsを実行します:

  1. bitsを ? ToIndex(bits) に設定する。
  2. bigintを ? ToBigInt(bigint) に設定する。
  3. ((bigint) modulo 2bits)を返す。

21.2.2.3 BigInt.prototype

BigInt.prototypeのinitial valueはBigInt prototype objectです。

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

21.2.3 Properties of the BigInt Prototype Object

BigInt prototype objectは:

  • %BigInt.prototype%です。
  • ordinary objectです。
  • BigInt objectではなく、[[BigIntData]] internal slotを持ちません。
  • valueが%Object.prototype%である[[Prototype]] internal slotを持ちます。

methodのspecification内の“this BigInt value”というphraseは、method invocationのthis valueをargumentとして渡してabstract operation ThisBigIntValueを呼び出した結果を指します。

21.2.3.1 BigInt.prototype.constructor

BigInt.prototype.constructorのinitial valueは%BigInt%です。

21.2.3.2 BigInt.prototype.toLocaleString ( [ reserved1 [ , reserved2 ] ] )

ECMA-402 Internationalization APIを含むECMAScript implementationは、このmethodをECMA-402 specificationで指定される通りにimplementしなければなりません。ECMAScript implementationがECMA-402 APIを含まない場合、このmethodの次のspecificationが使用されます:

このmethodは、host environmentのcurrent localeのconventionsに従ってformattedされたthis BigInt valueを表すString valueをproduceします。このmethodはimplementation-definedであり、toStringと同じものを返すことはpermissibleですが、encouragedはされません。

このmethodのoptional parametersのmeaningsはECMA-402 specificationで定義されます;ECMA-402 supportを含まないimplementationsは、それらのparameter positionsを他の目的に使用してはなりません。

21.2.3.3 BigInt.prototype.toString ( [ radix ] )

Note

optional radixは、2𝔽から36𝔽までのinclusive interval内にあるintegral Number valueであるべきです。radixundefinedなら、10𝔽radixのvalueとして使用されます。

このmethodは呼び出されたとき、次のstepsを実行します:

  1. xを ? ThisBigIntValue(this value) とする。
  2. radixundefinedなら、radixMVを10とする。
  3. そうでなければ、radixMVを ? ToIntegerOrInfinity(radix) とする。
  4. radixMVが2から36までのinclusive interval内にないなら、RangeError例外をthrowする。
  5. BigInt::toString(x, radixMV)を返す。

このmethodはgenericではありません;そのthis valueがBigIntまたはBigInt objectでない場合、TypeError例外をthrowします。したがって、methodとして使用するために他の種類のobjectsへtransferすることはできません。

21.2.3.4 BigInt.prototype.valueOf ( )

  1. ThisBigIntValue(this value)を返す。

21.2.3.4.1 ThisBigIntValue ( arg )

The abstract operation ThisBigIntValue takes argument arg (an ECMAScript language value) and returns either a normal completion containing a BigInt or a throw completion. It performs the following steps when called:

  1. argがBigIntなら、argを返す。
  2. argがObjectであり、arg[[BigIntData]] internal slotを持つなら、
    1. Assert: arg.[[BigIntData]]はBigIntである。
    2. arg.[[BigIntData]]を返す。
  3. TypeError例外をThrowする。

21.2.3.5 BigInt.prototype [ %Symbol.toStringTag% ]

%Symbol.toStringTag% propertyのinitial valueはString value "BigInt"です。

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

21.2.4 Properties of BigInt Instances

BigInt instancesは、BigInt prototype objectからpropertiesをinheritするordinary objectsです。BigInt instancesはまた[[BigIntData]] internal slotを持ちます。[[BigIntData]] internal slotは、このBigInt objectによって表されるBigInt valueです。

21.3 The Math Object

Math objectは:

  • %Math%です。
  • global object"Math" propertyのinitial valueです。
  • ordinary objectです。
  • valueが%Object.prototype%である[[Prototype]] internal slotを持ちます。
  • function objectではありません。
  • [[Construct]] internal methodを持ちません;new operatorを伴うconstructorとして使用できません。
  • [[Call]] internal methodを持ちません;functionとして呼び出せません。
Note

この仕様では、“the Number value for x”というphraseは、6.1.6.1で定義されるtechnical meaningを持ちます。

21.3.1 Value Properties of the Math Object

21.3.1.1 Math.E

e、すなわちnatural logarithmsのbaseに対するNumber valueであり、およそ2.7182818284590452354です。

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

21.3.1.2 Math.LN10

10のnatural logarithmに対するNumber valueであり、およそ2.302585092994046です。

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

21.3.1.3 Math.LN2

2のnatural logarithmに対するNumber valueであり、およそ0.6931471805599453です。

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

21.3.1.4 Math.LOG10E

e、すなわちnatural logarithmsのbaseのbase-10 logarithmに対するNumber valueです;このvalueはおよそ0.4342944819032518です。

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

Note

Math.LOG10EのvalueはMath.LN10のvalueのreciprocalにおおよそ等しいです。

21.3.1.5 Math.LOG2E

e、すなわちnatural logarithmsのbaseのbase-2 logarithmに対するNumber valueです;このvalueはおよそ1.4426950408889634です。

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

Note

Math.LOG2EのvalueはMath.LN2のvalueのreciprocalにおおよそ等しいです。

21.3.1.6 Math.PI

π、すなわちcircleのcircumferenceとdiameterのratioに対するNumber valueであり、およそ3.1415926535897932です。

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

21.3.1.7 Math.SQRT1_2

½のsquare rootに対するNumber valueであり、およそ0.7071067811865476です。

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

Note

Math.SQRT1_2のvalueはMath.SQRT2のvalueのreciprocalにおおよそ等しいです。

21.3.1.8 Math.SQRT2

2のsquare rootに対するNumber valueであり、およそ1.4142135623730951です。

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

21.3.1.9 Math [ %Symbol.toStringTag% ]

%Symbol.toStringTag% propertyのinitial valueはString value "Math"です。

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

21.3.2 Function Properties of the Math Object

Note

functions acosacoshasinasinhatanatanhatan2cbrtcoscoshexpexpm1hypotloglog1plog2log10powrandomsinsinhtan、およびtanhのbehaviourは、interestのあるboundary casesを表す特定のargument valuesに対してspecific resultsをrequireすることを除き、ここではpreciselyに指定されません。他のargument valuesについては、これらのfunctionsはfamiliar mathematical functionsのresultsへのapproximationsをcomputeすることを意図していますが、approximation algorithmsの選択にはある程度のlatitudeが許されます。general intentは、implementerが、与えられたhardware platform上のECMAScriptに対して、そのplatform上のC programmersが利用できる同じmathematical libraryを使用できるようにすることです。

algorithmsの選択はimplementationに任されますが、implementationsは、Sun Microsystemsのfreely distributable mathematical libraryであるfdlibmhttp://www.netlib.org/fdlibm)に含まれるIEEE 754-2019 arithmetic用のapproximation algorithmsを使用することがrecommendedされます(ただしこのstandardによって指定されるものではありません)。

21.3.2.1 Math.abs ( x )

このfunctionはxのabsolute valueを返します;resultはxと同じmagnitudeを持ちますが、positive signを持ちます。

これは呼び出されたとき、次のstepsを実行します:

  1. nを ? ToNumber(x) とする。
  2. nNaNなら、NaNを返す。
  3. n-0𝔽なら、+0𝔽を返す。
  4. n-∞𝔽なら、+∞𝔽を返す。
  5. n < -0𝔽なら、-nを返す。
  6. nを返す。

21.3.2.2 Math.acos ( x )

このfunctionはxのinverse cosineを返します。resultはradiansで表され、+0𝔽から𝔽(π)までのinclusive interval内にあります。

これは呼び出されたとき、次のstepsを実行します:

  1. nを ? ToNumber(x) とする。
  2. nNaNn > 1𝔽、またはn < -1𝔽のいずれかなら、NaNを返す。
  3. n1𝔽なら、+0𝔽を返す。
  4. (n)のinverse cosineを表すimplementation-approximated Number valueを返す。

21.3.2.3 Math.acosh ( x )

このfunctionはxのinverse hyperbolic cosineを返します。

これは呼び出されたとき、次のstepsを実行します:

  1. nを ? ToNumber(x) とする。
  2. nNaNまたは+∞𝔽のいずれかなら、nを返す。
  3. n1𝔽なら、+0𝔽を返す。
  4. n < 1𝔽なら、NaNを返す。
  5. (n)のinverse hyperbolic cosineを表すimplementation-approximated Number valueを返す。

21.3.2.4 Math.asin ( x )

このfunctionはxのinverse sineを返します。resultはradiansで表され、𝔽(-π / 2)から𝔽(π / 2)までのinclusive interval内にあります。

これは呼び出されたとき、次のstepsを実行します:

  1. nを ? ToNumber(x) とする。
  2. nNaN+0𝔽、または-0𝔽のいずれかなら、nを返す。
  3. n > 1𝔽またはn < -1𝔽なら、NaNを返す。
  4. (n)のinverse sineを表すimplementation-approximated Number valueを返す。

21.3.2.5 Math.asinh ( x )

このfunctionはxのinverse hyperbolic sineを返します。

これは呼び出されたとき、次のstepsを実行します:

  1. nを ? ToNumber(x) とする。
  2. nfiniteでない、またはn+0𝔽または-0𝔽のいずれかなら、nを返す。
  3. (n)のinverse hyperbolic sineを表すimplementation-approximated Number valueを返す。

21.3.2.6 Math.atan ( x )

このfunctionはxのinverse tangentを返します。resultはradiansで表され、𝔽(-π / 2)から𝔽(π / 2)までのinclusive interval内にあります。

これは呼び出されたとき、次のstepsを実行します:

  1. nを ? ToNumber(x) とする。
  2. nNaN+0𝔽、または-0𝔽のいずれかなら、nを返す。
  3. n+∞𝔽なら、π / 2を表すimplementation-approximated Number valueを返す。
  4. n-∞𝔽なら、-π / 2を表すimplementation-approximated Number valueを返す。
  5. (n)のinverse tangentを表すimplementation-approximated Number valueを返す。

21.3.2.7 Math.atanh ( x )

このfunctionはxのinverse hyperbolic tangentを返します。

これは呼び出されたとき、次のstepsを実行します:

  1. nを ? ToNumber(x) とする。
  2. nNaN+0𝔽、または-0𝔽のいずれかなら、nを返す。
  3. n > 1𝔽またはn < -1𝔽なら、NaNを返す。
  4. n1𝔽なら、+∞𝔽を返す。
  5. n-1𝔽なら、-∞𝔽を返す。
  6. (n)のinverse hyperbolic tangentを表すimplementation-approximated Number valueを返す。

21.3.2.8 Math.atan2 ( y, x )

このfunctionはarguments yおよびxのquotient y / xのinverse tangentを返します。ここで、yおよびxのsignsはresultのquadrantをdetermineするために使用されます。2-argument inverse tangent functionでは、yという名前のargumentがfirstで、xという名前のargumentがsecondであることはintentionalかつtraditionalであることに注意してください。resultはradiansで表され、-πから+πまでのinclusive interval内にあります。

これは呼び出されたとき、次のstepsを実行します:

  1. nyを ? ToNumber(y) とする。
  2. nxを ? ToNumber(x) とする。
  3. nyNaNまたはnxNaNなら、NaNを返す。
  4. ny+∞𝔽なら、
    1. nx+∞𝔽なら、π / 4を表すimplementation-approximated Number valueを返す。
    2. nx-∞𝔽なら、3π / 4を表すimplementation-approximated Number valueを返す。
    3. π / 2を表すimplementation-approximated Number valueを返す。
  5. ny-∞𝔽なら、
    1. nx+∞𝔽なら、-π / 4を表すimplementation-approximated Number valueを返す。
    2. nx-∞𝔽なら、-3π / 4を表すimplementation-approximated Number valueを返す。
    3. -π / 2を表すimplementation-approximated Number valueを返す。
  6. ny+0𝔽なら、
    1. nx > +0𝔽またはnx+0𝔽なら、+0𝔽を返す。
    2. πを表すimplementation-approximated Number valueを返す。
  7. ny-0𝔽なら、
    1. nx > +0𝔽またはnx+0𝔽なら、-0𝔽を返す。
    2. -πを表すimplementation-approximated Number valueを返す。
  8. Assert: nyfiniteであり、+0𝔽でも-0𝔽でもない。
  9. ny > +0𝔽なら、
    1. nx+∞𝔽なら、+0𝔽を返す。
    2. nx-∞𝔽なら、πを表すimplementation-approximated Number valueを返す。
    3. nx+0𝔽または-0𝔽のいずれかなら、π / 2を表すimplementation-approximated Number valueを返す。
  10. ny < -0𝔽なら、
    1. nx+∞𝔽なら、-0𝔽を返す。
    2. nx-∞𝔽なら、-πを表すimplementation-approximated Number valueを返す。
    3. nx+0𝔽または-0𝔽のいずれかなら、-π / 2を表すimplementation-approximated Number valueを返す。
  11. Assert: nxfiniteであり、+0𝔽でも-0𝔽でもない。
  12. resultabs((ny) / (nx))のinverse tangentとする。
  13. nx < -0𝔽なら、
    1. ny > +0𝔽なら、resultをπ - resultに設定する。
    2. そうでなければ、resultを-π + resultに設定する。
  14. そうでなければ、
    1. ny < -0𝔽なら、resultを-resultに設定する。
  15. resultを表すimplementation-approximated Number valueを返す。

21.3.2.9 Math.cbrt ( x )

このfunctionはxのcube rootを返します。

これは呼び出されたとき、次のstepsを実行します:

  1. nを ? ToNumber(x) とする。
  2. nfiniteでない、またはn+0𝔽または-0𝔽のいずれかなら、nを返す。
  3. (n)のcube rootを表すimplementation-approximated Number valueを返す。

21.3.2.10 Math.ceil ( x )

このfunctionは、x以上であるsmallest(-∞にclosest)integral Number valueを返します。xがすでにintegral Numberである場合、resultはxです。

これは呼び出されたとき、次のstepsを実行します:

  1. nを ? ToNumber(x) とする。
  2. nfiniteでない、またはn+0𝔽または-0𝔽のいずれかなら、nを返す。
  3. n < -0𝔽かつn > -1𝔽なら、-0𝔽を返す。
  4. nintegral Numberなら、nを返す。
  5. n以上であるsmallest(-∞にclosest)integral Number valueを返す。
Note

Math.ceil(x)のvalueは-Math.floor(-x)のvalueと同じです。

21.3.2.11 Math.clz32 ( x )

このfunctionは呼び出されたとき、次のstepsを実行します:

  1. nを ? ToUint32(x) とする。
  2. pnのunsigned 32-bit binary representationにおけるleading zero bitsの数とする。
  3. 𝔽(p)を返す。
Note

n+0𝔽または-0𝔽のいずれかである場合、このmethodは32𝔽を返します。nの32-bit binary encodingのmost significant bitが1である場合、このmethodは+0𝔽を返します。

21.3.2.12 Math.cos ( x )

このfunctionはxのcosineを返します。argumentはradiansで表されます。

これは呼び出されたとき、次のstepsを実行します:

  1. nを ? ToNumber(x) とする。
  2. nfiniteでないなら、NaNを返す。
  3. n+0𝔽または-0𝔽のいずれかなら、1𝔽を返す。
  4. (n)のcosineを表すimplementation-approximated Number valueを返す。

21.3.2.13 Math.cosh ( x )

このfunctionはxのhyperbolic cosineを返します。

これは呼び出されたとき、次のstepsを実行します:

  1. nを ? ToNumber(x) とする。
  2. nNaNなら、NaNを返す。
  3. n+∞𝔽または-∞𝔽のいずれかなら、+∞𝔽を返す。
  4. n+0𝔽または-0𝔽のいずれかなら、1𝔽を返す。
  5. (n)のhyperbolic cosineを表すimplementation-approximated Number valueを返す。
Note

Math.cosh(x)のvalueは(Math.exp(x) + Math.exp(-x)) / 2のvalueと同じです。

21.3.2.14 Math.exp ( x )

このfunctionはxのexponential function(ex乗したもの。ここでeはnatural logarithmsのbase)を返します。

これは呼び出されたとき、次のstepsを実行します:

  1. nを ? ToNumber(x) とする。
  2. nNaNまたは+∞𝔽のいずれかなら、nを返す。
  3. n+0𝔽または-0𝔽のいずれかなら、1𝔽を返す。
  4. n-∞𝔽なら、+0𝔽を返す。
  5. (n)のexponential functionを表すimplementation-approximated Number valueを返す。

21.3.2.15 Math.expm1 ( x )

このfunctionはxのexponential function(ex乗したもの。ここでeはnatural logarithmsのbase)から1をsubtractしたresultを返します。resultは、xのvalueが0に近い場合でもaccurateになるようにcomputedされます。

これは呼び出されたとき、次のstepsを実行します:

  1. nを ? ToNumber(x) とする。
  2. nNaN+0𝔽-0𝔽、または+∞𝔽のいずれかなら、nを返す。
  3. n-∞𝔽なら、-1𝔽を返す。
  4. exp(n)のexponential functionとする。
  5. exp - 1を表すimplementation-approximated Number valueを返す。

21.3.2.16 Math.floor ( x )

このfunctionは、x以下であるgreatest(+∞にclosest)integral Number valueを返します。xがすでにintegral Numberである場合、resultはxです。

これは呼び出されたとき、次のstepsを実行します:

  1. nを ? ToNumber(x) とする。
  2. nfiniteでない、またはn+0𝔽または-0𝔽のいずれかなら、nを返す。
  3. n < 1𝔽かつn > +0𝔽なら、+0𝔽を返す。
  4. nintegral Numberなら、nを返す。
  5. n以下であるgreatest(+∞にclosest)integral Number valueを返す。
Note

Math.floor(x)のvalueは-Math.ceil(-x)のvalueと同じです。

21.3.2.17 Math.fround ( x )

このfunctionは呼び出されたとき、次のstepsを実行します:

  1. nを ? ToNumber(x) とする。
  2. nNaNなら、NaNを返す。
  3. n+0𝔽-0𝔽+∞𝔽、または-∞𝔽のいずれかなら、nを返す。
  4. n32を、roundTiesToEven modeを使用してnIEEE 754-2019 binary32 formatへconvertしたresultとする。
  5. n64を、n32IEEE 754-2019 binary64 formatへconvertしたresultとする。
  6. n64に対応するECMAScript Number valueを返す。

21.3.2.18 Math.f16round ( x )

このfunctionは呼び出されたとき、次のstepsを実行します:

  1. nを ? ToNumber(x) とする。
  2. nNaNなら、NaNを返す。
  3. n+0𝔽-0𝔽+∞𝔽、または-∞𝔽のいずれかなら、nを返す。
  4. n16を、roundTiesToEven modeを使用してnIEEE 754-2019 binary16 formatへconvertしたresultとする。
  5. n64を、n16IEEE 754-2019 binary64 formatへconvertしたresultとする。
  6. n64に対応するECMAScript Number valueを返す。
Note

このoperationは、binary32へcastしてからbinary16へcastすることと同じではありません。double-roundingの可能性があるためです:例えばnumber k = 1.00048828125000022204𝔽を考えると、Math.f16round(k)は1.0009765625𝔽ですが、Math.f16round(Math.fround(k))は1𝔽です。

すべてのplatformsがbinary64からbinary16へのcastingにnative supportを提供するわけではありません。これを提供できるlibrariesはさまざまあり、MIT-licensedのhalf libraryも含まれます。あるいは、まずroundTiesToEvenの下でbinary64からbinary32へcastし、そのresultがincorrect double-roundingにつながる可能性があるかどうかをcheckすることもできます。そのようなcasesは、binary32 valueのmantissaをadjustし、initial castをroundTiesToOddの下で実行した場合にproduceされるvalueになるようにすることで明示的にhandleできます。adjusted valueをroundTiesToEvenの下でbinary16へcastすると、correct valueがproduceされます。

21.3.2.19 Math.hypot ( ...args )

zero以上のargumentsが与えられると、このfunctionはそのargumentsのsquaresのsumのsquare rootを返します。

これは呼び出されたとき、次のstepsを実行します:

  1. coercedを新しい空のListとする。
  2. argsの各要素argについて、以下を行う
    1. nを ? ToNumber(arg) とする。
    2. ncoercedへappendする。
  3. coercedの各要素numberについて、以下を行う
    1. number+∞𝔽または-∞𝔽のいずれかなら、+∞𝔽を返す。
  4. onlyZerotrueとする。
  5. coercedの各要素numberについて、以下を行う
    1. numberNaNなら、NaNを返す。
    2. number+0𝔽でも-0𝔽でもないなら、onlyZerofalseに設定する。
  6. onlyZerotrueなら、+0𝔽を返す。
  7. coercedの要素のmathematical valuesのsquaresのsumのsquare rootを表すimplementation-approximated Number valueを返す。

このfunctionの"length" propertyは2𝔽です。

Note

このfunctionが2つ以上のargumentsで呼び出されるときにnaive implementationsで発生しやすいoverflowsおよびunderflowsによるprecision lossを避けるよう、implementationsは注意すべきです。

21.3.2.20 Math.imul ( x, y )

このfunctionは呼び出されたとき、次のstepsを実行します:

  1. a(? ToUint32(x))とする。
  2. b(? ToUint32(y))とする。
  3. productを(a × b) modulo 232とする。
  4. product ≥ 231なら、𝔽(product - 232)を返す。
  5. 𝔽(product)を返す。

21.3.2.21 Math.log ( x )

このfunctionはxのnatural logarithmを返します。

これは呼び出されたとき、次のstepsを実行します:

  1. nを ? ToNumber(x) とする。
  2. nNaNまたは+∞𝔽のいずれかなら、nを返す。
  3. n1𝔽なら、+0𝔽を返す。
  4. n+0𝔽または-0𝔽のいずれかなら、-∞𝔽を返す。
  5. n < -0𝔽なら、NaNを返す。
  6. ln((n))を表すimplementation-approximated Number valueを返す。

21.3.2.22 Math.log1p ( x )

このfunctionは1 + xのnatural logarithmを返します。resultは、xのvalueがzeroに近い場合でもaccurateになるようにcomputedされます。

これは呼び出されたとき、次のstepsを実行します:

  1. nを ? ToNumber(x) とする。
  2. nNaN+0𝔽-0𝔽、または+∞𝔽のいずれかなら、nを返す。
  3. n-1𝔽なら、-∞𝔽を返す。
  4. n < -1𝔽なら、NaNを返す。
  5. ln(1 + (n))を表すimplementation-approximated Number valueを返す。

21.3.2.23 Math.log10 ( x )

このfunctionはxのbase 10 logarithmを返します。

これは呼び出されたとき、次のstepsを実行します:

  1. nを ? ToNumber(x) とする。
  2. nNaNまたは+∞𝔽のいずれかなら、nを返す。
  3. n1𝔽なら、+0𝔽を返す。
  4. n+0𝔽または-0𝔽のいずれかなら、-∞𝔽を返す。
  5. n < -0𝔽なら、NaNを返す。
  6. log10((n))を表すimplementation-approximated Number valueを返す。

21.3.2.24 Math.log2 ( x )

このfunctionはxのbase 2 logarithmを返します。

これは呼び出されたとき、次のstepsを実行します:

  1. nを ? ToNumber(x) とする。
  2. nNaNまたは+∞𝔽のいずれかなら、nを返す。
  3. n1𝔽なら、+0𝔽を返す。
  4. n+0𝔽または-0𝔽のいずれかなら、-∞𝔽を返す。
  5. n < -0𝔽なら、NaNを返す。
  6. log2((n))を表すimplementation-approximated Number valueを返す。

21.3.2.25 Math.max ( ...args )

zero以上のargumentsが与えられると、このfunctionはargumentsのそれぞれにToNumberをcallし、得られたvaluesのlargestを返します。

これは呼び出されたとき、次のstepsを実行します:

  1. coercedを新しい空のListとする。
  2. argsの各要素argについて、以下を行う
    1. nを ? ToNumber(arg) とする。
    2. ncoercedへappendする。
  3. highest-∞𝔽とする。
  4. coercedの各要素numberについて、以下を行う
    1. numberNaNなら、NaNを返す。
    2. number+0𝔽であり、highest-0𝔽なら、highest+0𝔽に設定する。
    3. number > highestなら、highestnumberに設定する。
  5. highestを返す。
Note

largest valueをdetermineするためのvaluesのcomparisonは、+0𝔽-0𝔽より大きいとみなされることを除き、IsLessThan algorithmを使用して行われます。

このfunctionの"length" propertyは2𝔽です。

21.3.2.26 Math.min ( ...args )

zero以上のargumentsが与えられると、このfunctionはargumentsのそれぞれにToNumberをcallし、得られたvaluesのsmallestを返します。

これは呼び出されたとき、次のstepsを実行します:

  1. coercedを新しい空のListとする。
  2. argsの各要素argについて、以下を行う
    1. nを ? ToNumber(arg) とする。
    2. ncoercedへappendする。
  3. lowest+∞𝔽とする。
  4. coercedの各要素numberについて、以下を行う
    1. numberNaNなら、NaNを返す。
    2. number-0𝔽であり、lowest+0𝔽なら、lowest-0𝔽に設定する。
    3. number < lowestなら、lowestnumberに設定する。
  5. lowestを返す。
Note

smallest valueをdetermineするためのvaluesのcomparisonは、+0𝔽-0𝔽より大きいとみなされることを除き、IsLessThan algorithmを使用して行われます。

このfunctionの"length" propertyは2𝔽です。

21.3.2.27 Math.pow ( base, exponent )

このfunctionは呼び出されたとき、次のstepsを実行します:

  1. baseを ? ToNumber(base) に設定する。
  2. exponentを ? ToNumber(exponent) に設定する。
  3. Number::exponentiate(base, exponent)を返す。

21.3.2.28 Math.random ( )

このfunctionは、positive signを持ち、+0𝔽以上かつ1𝔽未満であり、そのrange上でおおよそuniform distributionに従ってrandomlyまたはpseudo randomlyに選ばれたNumber valueを、implementation-defined algorithmまたはstrategyを使用して返します。

distinct realmsに対して作成された各Math.random functionは、successive callsからdistinct sequence of valuesをproduceしなければなりません。

21.3.2.29 Math.round ( x )

このfunctionは、xにclosestでありintegralであるNumber valueを返します。2つのintegral Numbersxにequally closeである場合、resultは+∞にcloserなNumber valueです。xがすでにintegralである場合、resultはxです。

これは呼び出されたとき、次のstepsを実行します:

  1. nを ? ToNumber(x) とする。
  2. nfiniteでない、またはnintegral Numberなら、nを返す。
  3. n < 0.5𝔽かつn > +0𝔽なら、+0𝔽を返す。
  4. n < -0𝔽かつn-0.5𝔽なら、-0𝔽を返す。
  5. nにclosestなintegral Numberを返し、tieの場合は+∞にcloserなNumberを優先する。
Note 1

Math.round(3.5)は4を返しますが、Math.round(-3.5)は-3を返します。

Note 2

Math.round(x)のvalueは、常にMath.floor(x + 0.5)のvalueと同じとは限りません。x-0𝔽である場合、またはx-0𝔽より小さく、かつ-0.5𝔽以上である場合、Math.round(x)-0𝔽を返しますが、Math.floor(x + 0.5)+0𝔽を返します。Math.round(x)はまた、x + 0.5をcomputeするときのinternal roundingのため、Math.floor(x + 0.5)のvalueと異なる場合があります。

21.3.2.30 Math.sign ( x )

このfunctionはxのsignを返し、xがpositive、negative、またはzeroであるかを示します。

これは呼び出されたとき、次のstepsを実行します:

  1. nを ? ToNumber(x) とする。
  2. nNaN+0𝔽、または-0𝔽のいずれかなら、nを返す。
  3. n < -0𝔽なら、-1𝔽を返す。
  4. 1𝔽を返す。

21.3.2.31 Math.sin ( x )

このfunctionはxのsineを返します。argumentはradiansで表されます。

これは呼び出されたとき、次のstepsを実行します:

  1. nを ? ToNumber(x) とする。
  2. nNaN+0𝔽、または-0𝔽のいずれかなら、nを返す。
  3. n+∞𝔽または-∞𝔽のいずれかなら、NaNを返す。
  4. (n)のsineを表すimplementation-approximated Number valueを返す。

21.3.2.32 Math.sinh ( x )

このfunctionはxのhyperbolic sineを返します。

これは呼び出されたとき、次のstepsを実行します:

  1. nを ? ToNumber(x) とする。
  2. nfiniteでない、またはn+0𝔽または-0𝔽のいずれかなら、nを返す。
  3. (n)のhyperbolic sineを表すimplementation-approximated Number valueを返す。
Note

Math.sinh(x)のvalueは(Math.exp(x) - Math.exp(-x)) / 2のvalueと同じです。

21.3.2.33 Math.sqrt ( x )

このfunctionはxのsquare rootを返します。

これは呼び出されたとき、次のstepsを実行します:

  1. nを ? ToNumber(x) とする。
  2. nNaN+0𝔽-0𝔽、または+∞𝔽のいずれかなら、nを返す。
  3. n < -0𝔽なら、NaNを返す。
  4. 𝔽((n)のsquare root)を返す。

21.3.2.34 Math.sumPrecise ( items )

Numbersのiterableが与えられると、このfunctionはiterable内の各valueをsumし、それらのsumを返します。何らかのvalueがNumberでない場合、TypeError例外をthrowします。

これは呼び出されたとき、次のstepsを実行します:

  1. RequireObjectCoercible(items)を実行する。
  2. iteratorRecordを ? GetIterator(items, sync) とする。
  3. stateminus-zeroとする。
  4. sumを0とする。
  5. countを0とする。
  6. nextnot-startedとする。
  7. nextdoneでない間、繰り返す
    1. nextを ? IteratorStepValue(iteratorRecord) に設定する。
    2. nextdoneでないなら、
      1. count ≥ 253 - 1なら、
        1. NOTE: このstepは実際には到達しないことが期待されており、implementationsがこの仕様に違反することなくinputsが“reasonably sized”であることに依存できるようにするためだけに含まれる。
        2. errorThrowCompletion(a newly created RangeError object)とする。
        3. IteratorClose(iteratorRecord, error)を返す。
      2. nextがNumberでないなら、
        1. errorThrowCompletion(a newly created TypeError object)とする。
        2. IteratorClose(iteratorRecord, error)を返す。
      3. nnextとする。
      4. statenot-a-numberでないなら、
        1. nNaNなら、
          1. statenot-a-numberに設定する。
        2. そうでなく、n+∞𝔽なら、
          1. stateminus-infinityなら、statenot-a-numberに設定する。
          2. そうでなければ、stateplus-infinityに設定する。
        3. そうでなく、n-∞𝔽なら、
          1. stateplus-infinityなら、statenot-a-numberに設定する。
          2. そうでなければ、stateminus-infinityに設定する。
        4. そうでなく、n-0𝔽でなく、かつstateminus-zeroまたはfiniteのいずれかなら、
          1. statefiniteに設定する。
          2. sumsum + (n)に設定する。
      5. countcount + 1に設定する。
  8. statenot-a-numberなら、NaNを返す。
  9. stateplus-infinityなら、+∞𝔽を返す。
  10. stateminus-infinityなら、-∞𝔽を返す。
  11. stateminus-zeroなら、-0𝔽を返す。
  12. 𝔽(sum)を返す。
Note

sumのvalueは、さまざまなalgorithmsによってarbitrary-precision arithmeticなしでcomputedできます。その1つは、Jonathan Richard ShewchukによるAdaptive Precision Floating-Point Arithmetic and Fast Robust Geometric Predicatesに示されている“Grow-Expansion” algorithmです。よりrecentなalgorithmは“Fast exact summation using small and large superaccumulators”に示されており、そのcodeはhttps://gitlab.com/radfordneal/xsumで利用できます。

21.3.2.35 Math.tan ( x )

このfunctionはxのtangentを返します。argumentはradiansで表されます。

これは呼び出されたとき、次のstepsを実行します:

  1. nを ? ToNumber(x) とする。
  2. nNaN+0𝔽、または-0𝔽のいずれかなら、nを返す。
  3. n+∞𝔽または-∞𝔽のいずれかなら、NaNを返す。
  4. (n)のtangentを表すimplementation-approximated Number valueを返す。

21.3.2.36 Math.tanh ( x )

このfunctionはxのhyperbolic tangentを返します。

これは呼び出されたとき、次のstepsを実行します:

  1. nを ? ToNumber(x) とする。
  2. nNaN+0𝔽、または-0𝔽のいずれかなら、nを返す。
  3. n+∞𝔽なら、1𝔽を返す。
  4. n-∞𝔽なら、-1𝔽を返す。
  5. (n)のhyperbolic tangentを表すimplementation-approximated Number valueを返す。
Note

Math.tanh(x)のvalueは(Math.exp(x) - Math.exp(-x)) / (Math.exp(x) + Math.exp(-x))のvalueと同じです。

21.3.2.37 Math.trunc ( x )

このfunctionはnumber xのintegral partを返し、fractional digitsをremoveします。xがすでにintegralである場合、resultはxです。

これは呼び出されたとき、次のstepsを実行します:

  1. nを ? ToNumber(x) とする。
  2. nfiniteでない、またはn+0𝔽または-0𝔽のいずれかなら、nを返す。
  3. n < 1𝔽かつn > +0𝔽なら、+0𝔽を返す。
  4. n < -0𝔽かつn > -1𝔽なら、-0𝔽を返す。
  5. +0𝔽の方向にnにnearestなintegral Numberを返す。

21.4 Date Objects

21.4.1 Overview of Date Objects and Definitions of Abstract Operations

以下のabstract operationstime values21.4.1.1で定義)に対してoperateします。いずれの場合も、これらのfunctionsのいずれかへの任意のargumentがNaNである場合、resultはNaNになります。

21.4.1.1 Time Values and Time Range

ECMAScriptにおけるtime measurementはPOSIXにおけるtime measurementに類似しており、特にproleptic Gregorian calendar、1970年1月1日UTCの開始時のmidnightをepochとすること、およびすべての日を正確に86,400秒(各秒は1000 milliseconds)から構成されるものとしてaccountingすることによるdefinitionを共有します。

ECMAScriptのtime valueはNumberであり、millisecond precisionでtime内のinstantを表すfinite integral Number、またはspecific instantを表さないNaNのいずれかです。24 × 60 × 60 × 1000 = 86,400,000のmultipleであるtime value(すなわち、あるinteger dについて86,400,000 × dであるもの)は、epochからd whole UTC days後(negative dではepochより前)に続くUTC dayのstartのinstantを表します。他のすべてのfinite time value tvは、そのようなmultipleであるgreatest preceding time value sにrelativeに定義され、sと同じUTC day内で発生し、(tv - s) millisecondsだけ後に続くinstantを表します。

Time valuesはUTC leap secondsをaccountしません—positive leap seconds内のinstantsを表すtime valuesは存在せず、negative leap secondsによってUTC timelineからremovedされたinstantsを表すtime valuesが存在します。しかしながら、time valuesのdefinitionは、それにもかかわらずUTCとのpiecewise alignmentをもたらし、discontinuitiesはleap second boundariesにのみ存在し、leap secondsの外側ではzero differenceになります。

Numberは-9,007,199,254,740,992から9,007,199,254,740,992までのすべてのintegersをexactlyにrepresentできます(21.1.2.8および21.1.2.6)。time valueは、-8,640,000,000,000,000から8,640,000,000,000,000 millisecondsまでのやや小さいrangeをsupportします。これにより、1970年1月1日UTCの開始時のmidnightを基準として、正確に-100,000,000 daysから100,000,000 daysまでのsupported time value rangeが得られます。

1970年1月1日UTCの開始時のmidnightのexact momentは、time value +0𝔽によって表されます。

Note

proleptic Gregorian calendarでは、leap yearsは、4でdivisibleであり、かつ400でdivisibleであるか100でdivisibleでないものです。

proleptic Gregorian calendarの400 year cycleには97 leap yearsが含まれます。これにより、yearあたり平均365.2425 days、すなわち31,556,952,000 millisecondsになります。したがって、Numberがmillisecond precisionでexactlyにrepresentできるmaximum rangeは、1970年を基準としておよそ-285,426年から285,426年です。このsectionで指定されるtime valueによってsupportされるsmaller rangeは、1970年を基準としておよそ-273,790年から273,790年です。

21.4.1.2 Time-related Constants

これらのconstantsは、以下のsectionsのalgorithmsによって参照されます。

HoursPerDay = 24
MinutesPerHour = 60
SecondsPerMinute = 60
msPerSecond = 1000𝔽
msPerMinute = 60000𝔽 = msPerSecond × 𝔽(SecondsPerMinute)
msPerHour = 3600000𝔽 = msPerMinute × 𝔽(MinutesPerHour)
msPerDay = 86400000𝔽 = msPerHour × 𝔽(HoursPerDay)

21.4.1.3 Day ( tv )

The abstract operation Day takes argument tv (a finite time value) and returns an integral Number. tvが属するdayのday numberを返します。 It performs the following steps when called:

  1. 𝔽(floor((tv / msPerDay)))を返す。

21.4.1.4 TimeWithinDay ( tv )

The abstract operation TimeWithinDay takes argument tv (a finite time value) and returns an integral Number in the interval from +0𝔽 (inclusive) to msPerDay (exclusive). tvが属するdayのstartからのmillisecondsの数を返します。 It performs the following steps when called:

  1. 𝔽((tv) modulo (msPerDay))を返す。

21.4.1.5 DaysInYear ( y )

The abstract operation DaysInYear takes argument y (an integral Number) and returns 365𝔽 or 366𝔽. year yに含まれるdaysの数を返します。Leap yearsは366 daysを持ちます;他のすべてのyearsは365です。 It performs the following steps when called:

  1. ry(y)とする。
  2. (ry modulo 400) = 0なら、366𝔽を返す。
  3. (ry modulo 100) = 0なら、365𝔽を返す。
  4. (ry modulo 4) = 0なら、366𝔽を返す。
  5. 365𝔽を返す。

21.4.1.6 DayFromYear ( y )

The abstract operation DayFromYear takes argument y (an integral Number) and returns an integral Number. year yのfirst dayのday numberを返します。 It performs the following steps when called:

  1. ry(y)とする。
  2. NOTE: 以下のstepsでは、numberYears1numberYears4numberYears100、およびnumberYears400は、それぞれepochとyear yのstartとの間に現れる、1、4、100、および400でdivisibleなyearsの数を表す。yepochより前なら、この数はnegativeである。
  3. numberYears1を(ry - 1970)とする。
  4. numberYears4floor((ry - 1969) / 4)とする。
  5. numberYears100floor((ry - 1901) / 100)とする。
  6. numberYears400floor((ry - 1601) / 400)とする。
  7. 𝔽(365 × numberYears1 + numberYears4 - numberYears100 + numberYears400)を返す。

21.4.1.7 TimeFromYear ( y )

The abstract operation TimeFromYear takes argument y (an integral Number) and returns a time value. year yのstartのtime valueを返します。 It performs the following steps when called:

  1. msPerDay × DayFromYear(y)を返す。

21.4.1.8 YearFromTime ( tv )

The abstract operation YearFromTime takes argument tv (a finite time value) and returns an integral Number. tvが属するyearを返します。 It performs the following steps when called:

  1. TimeFromYear(y) ≤ tvであるようなlargest integral Number y(+∞にclosest)を返す。

21.4.1.9 DayWithinYear ( tv )

The abstract operation DayWithinYear takes argument tv (a finite time value) and returns an integral Number in the inclusive interval from +0𝔽 to 365𝔽. It performs the following steps when called:

  1. Day(tv) - DayFromYear(YearFromTime(tv))を返す。

21.4.1.10 InLeapYear ( tv )

The abstract operation InLeapYear takes argument tv (a finite time value) and returns +0𝔽 or 1𝔽. tvがleap year内にある場合は1𝔽を返し、そうでなければ+0𝔽を返します。 It performs the following steps when called:

  1. DaysInYear(YearFromTime(tv))が366𝔽なら、1𝔽を返す。
  2. +0𝔽を返す。

21.4.1.11 MonthFromTime ( tv )

The abstract operation MonthFromTime takes argument tv (a finite time value) and returns an integral Number in the inclusive interval from +0𝔽 to 11𝔽. tvが属するmonthをidentifyするNumberを返します。month value +0𝔽はJanuaryを指定します;1𝔽はFebruaryを指定します;2𝔽はMarchを指定します;3𝔽はAprilを指定します;4𝔽はMayを指定します;5𝔽はJuneを指定します;6𝔽はJulyを指定します;7𝔽はAugustを指定します;8𝔽はSeptemberを指定します;9𝔽はOctoberを指定します;10𝔽はNovemberを指定します;そして11𝔽はDecemberを指定します。MonthFromTime(+0𝔽) = +0𝔽であり、これはThursday, 1 January 1970に対応することに注意してください。 It performs the following steps when called:

  1. inLeapYearInLeapYear(tv)とする。
  2. dayWithinYearDayWithinYear(tv)とする。
  3. dayWithinYear < 31𝔽なら、+0𝔽を返す。
  4. dayWithinYear < 59𝔽 + inLeapYearなら、1𝔽を返す。
  5. dayWithinYear < 90𝔽 + inLeapYearなら、2𝔽を返す。
  6. dayWithinYear < 120𝔽 + inLeapYearなら、3𝔽を返す。
  7. dayWithinYear < 151𝔽 + inLeapYearなら、4𝔽を返す。
  8. dayWithinYear < 181𝔽 + inLeapYearなら、5𝔽を返す。
  9. dayWithinYear < 212𝔽 + inLeapYearなら、6𝔽を返す。
  10. dayWithinYear < 243𝔽 + inLeapYearなら、7𝔽を返す。
  11. dayWithinYear < 273𝔽 + inLeapYearなら、8𝔽を返す。
  12. dayWithinYear < 304𝔽 + inLeapYearなら、9𝔽を返す。
  13. dayWithinYear < 334𝔽 + inLeapYearなら、10𝔽を返す。
  14. Assert: dayWithinYear < 365𝔽 + inLeapYearである。
  15. 11𝔽を返す。

21.4.1.12 DateFromTime ( tv )

The abstract operation DateFromTime takes argument tv (a finite time value) and returns an integral Number in the inclusive interval from 1𝔽 to 31𝔽. tvが属するmonth内のdayを返します。 It performs the following steps when called:

  1. inLeapYearInLeapYear(tv)とする。
  2. dayWithinYearDayWithinYear(tv)とする。
  3. monthMonthFromTime(tv)とする。
  4. month+0𝔽なら、dayWithinYear + 1𝔽を返す。
  5. month1𝔽なら、dayWithinYear - 30𝔽を返す。
  6. month2𝔽なら、dayWithinYear - 58𝔽 - inLeapYearを返す。
  7. month3𝔽なら、dayWithinYear - 89𝔽 - inLeapYearを返す。
  8. month4𝔽なら、dayWithinYear - 119𝔽 - inLeapYearを返す。
  9. month5𝔽なら、dayWithinYear - 150𝔽 - inLeapYearを返す。
  10. month6𝔽なら、dayWithinYear - 180𝔽 - inLeapYearを返す。
  11. month7𝔽なら、dayWithinYear - 211𝔽 - inLeapYearを返す。
  12. month8𝔽なら、dayWithinYear - 242𝔽 - inLeapYearを返す。
  13. month9𝔽なら、dayWithinYear - 272𝔽 - inLeapYearを返す。
  14. month10𝔽なら、dayWithinYear - 303𝔽 - inLeapYearを返す。
  15. Assert: month11𝔽である。
  16. dayWithinYear - 333𝔽 - inLeapYearを返す。

21.4.1.13 WeekDay ( tv )

The abstract operation WeekDay takes argument tv (a finite time value) and returns an integral Number in the inclusive interval from +0𝔽 to 6𝔽. tvが属するweekのdayをidentifyするNumberを返します。weekday value +0𝔽はSundayを指定します;1𝔽はMondayを指定します;2𝔽はTuesdayを指定します;3𝔽はWednesdayを指定します;4𝔽はThursdayを指定します;5𝔽はFridayを指定します;そして6𝔽はSaturdayを指定します。WeekDay(+0𝔽) = 4𝔽であり、これはThursday, 1 January 1970に対応することに注意してください。 It performs the following steps when called:

  1. 𝔽((Day(tv) + 4𝔽) modulo 7)を返す。

21.4.1.14 HourFromTime ( tv )

The abstract operation HourFromTime takes argument tv (a finite time value) and returns an integral Number in the inclusive interval from +0𝔽 to 23𝔽. tvが属するdayのhourを返します。 It performs the following steps when called:

  1. 𝔽(floor((tv / msPerHour)) modulo HoursPerDay)を返す。

21.4.1.15 MinFromTime ( tv )

The abstract operation MinFromTime takes argument tv (a finite time value) and returns an integral Number in the inclusive interval from +0𝔽 to 59𝔽. tvが属するhourのminuteを返します。 It performs the following steps when called:

  1. 𝔽(floor((tv / msPerMinute)) modulo MinutesPerHour)を返す。

21.4.1.16 SecFromTime ( tv )

The abstract operation SecFromTime takes argument tv (a finite time value) and returns an integral Number in the inclusive interval from +0𝔽 to 59𝔽. tvが属するminuteのsecondを返します。 It performs the following steps when called:

  1. 𝔽(floor((tv / msPerSecond)) modulo SecondsPerMinute)を返す。

21.4.1.17 msFromTime ( tv )

The abstract operation msFromTime takes argument tv (a finite time value) and returns an integral Number in the inclusive interval from +0𝔽 to 999𝔽. tvが属するsecondのmillisecondを返します。 It performs the following steps when called:

  1. 𝔽((tv) modulo (msPerSecond))を返す。

21.4.1.18 GetUTCEpochNanoseconds ( year, month, day, hour, minute, second, millisecond, microsecond, nanosecond )

The abstract operation GetUTCEpochNanoseconds takes arguments year (an integer), month (an integer in the inclusive interval from 1 to 12), day (an integer in the inclusive interval from 1 to 31), hour (an integer in the inclusive interval from 0 to 23), minute (an integer in the inclusive interval from 0 to 59), second (an integer in the inclusive interval from 0 to 59), millisecond (an integer in the inclusive interval from 0 to 999), microsecond (an integer in the inclusive interval from 0 to 999), and nanosecond (an integer in the inclusive interval from 0 to 999) and returns a BigInt. 返されるvalueは、与えられたISO 8601 calendar dateおよびUTCのwall-clock timeに対応する、epochからのnanosecondsの数を表します。 It performs the following steps when called:

  1. dateMakeDay(𝔽(year), 𝔽(month - 1), 𝔽(day))とする。
  2. timeMakeTime(𝔽(hour), 𝔽(minute), 𝔽(second), 𝔽(millisecond))とする。
  3. msMakeDate(date, time)とする。
  4. Assert: msintegral Numberである。
  5. ((ms) × 106 + microsecond × 103 + nanosecond)を返す。

21.4.1.19 Time Zone Identifiers

ECMAScriptにおけるtime zonesは、time zone identifiersによって表されます。これは、0x0000から0x007Fまでのinclusive interval内のcode unitsのみで構成されるStringsです。 ECMAScript implementationによってsupportされるtime zonesは、AvailableNamedTimeZoneIdentifiersによって返されるTime Zone Identifier Records[[Identifier]] fieldによって表されるavailable named time zones、またはIsTimeZoneOffsetStringtrueを返すStringsによって表されるoffset time zonesであり得ます。

primary time zone identifierは、available named time zoneのpreferred identifierです。 non-primary time zone identifierは、primary time zone identifierではないavailable named time zoneのidentifierです。 available named time zone identifierは、primary time zone identifierまたはnon-primary time zone identifierのいずれかです。 各available named time zone identifierは、exactly one available named time zoneにassociatedされます。 各available named time zoneは、exactly one primary time zone identifierおよびzero or more non-primary time zone identifiersにassociatedされます。

ECMAScript implementationsは、identifier "UTC"を持つavailable named time zoneをsupportしなければならず、これはUTC time zoneのprimary time zone identifierでなければなりません。 さらに、implementationsは任意の数の他のavailable named time zonesをsupportしてもよいです。

ECMA-402 Internationalization API specificationで記述されるtime zonesのrequirementsに従うimplementationsは、time zone awareと呼ばれます。 Time zone aware implementationsは、IANA Time Zone DatabaseのZoneおよびLink namesに対応するavailable named time zonesのみをsupportしなければなりません。 Time zone aware implementationsでは、ECMA-402 specificationで指定されるAvailableNamedTimeZoneIdentifiersによってspecificにoverriddenされる場合を除き、primary time zone identifierはIANA Time Zone DatabaseにおけるZone nameであり、non-primary time zone identifierはLink nameです。 IANA Time Zone Database全体をsupportしないimplementationsにも、time zonesを表すidentifiersとしてIANA Time Zone Database namesを使用することがrecommendedされます。

21.4.1.20 GetNamedTimeZoneEpochNanoseconds ( timeZoneIdentifier, year, month, day, hour, minute, second, millisecond, microsecond, nanosecond )

The implementation-defined abstract operation GetNamedTimeZoneEpochNanoseconds takes arguments timeZoneIdentifier (a String), year (an integer), month (an integer in the inclusive interval from 1 to 12), day (an integer in the inclusive interval from 1 to 31), hour (an integer in the inclusive interval from 0 to 23), minute (an integer in the inclusive interval from 0 to 59), second (an integer in the inclusive interval from 0 to 59), millisecond (an integer in the inclusive interval from 0 to 999), microsecond (an integer in the inclusive interval from 0 to 999), and nanosecond (an integer in the inclusive interval from 0 to 999) and returns a List of BigInts. 返されるList内の各valueは、timeZoneIdentifierによってidentifiedされるnamed time zone内の、与えられたISO 8601 calendar dateおよびwall-clock timeに対応する、epochからのnanosecondsの数を表します。

inputがnegative time zone transitionのために複数回発生するlocal timeを表す場合(例えばdaylight saving timeが終了するとき、またはtime zone rule changeによりtime zone offsetがdecreasedされるとき)、返されるListは複数のelementsを持ち、ascending numerical valueでsortedされます。 inputがpositive time zone transitionのためにskippedされたlocal timeを表す場合(例えばdaylight saving timeが開始するとき、またはtime zone rule changeによりtime zone offsetがincreasedされるとき)、返されるListはemptyになります。 それ以外の場合、返されるListはone elementを持ちます。

time zonesに関するlocal political rulesを含まないECMAScript implementationsで使用されるGetNamedTimeZoneEpochNanosecondsのdefault implementationは、呼び出されたとき次のstepsを実行します:

  1. Assert: timeZoneIdentifier"UTC"である。
  2. epochNanosecondsGetUTCEpochNanoseconds(year, month, day, hour, minute, second, millisecond, microsecond, nanosecond)とする。
  3. « epochNanoseconds »を返す。
Note

time zone aware implementations(およびその他すべて)には、IANA Time Zone Database https://www.iana.org/time-zones/のtime zone informationを使用することがrequired(その他すべてにはrecommended)です。

America/New_Yorkにおける2017年11月5日の1:30 AMは2回repeatedされるため、GetNamedTimeZoneEpochNanoseconds("America/New_York", 2017, 11, 5, 1, 30, 0, 0, 0, 0)はlength 2のListを返し、そのfirst elementは05:30 UTC(UTC offset -04:00の01:30 US Eastern Daylight Timeに対応)を表し、second elementは06:30 UTC(UTC offset -05:00の01:30 US Eastern Standard Timeに対応)を表します。

America/New_Yorkにおける2017年3月12日の2:30 AMは存在しないため、GetNamedTimeZoneEpochNanoseconds("America/New_York", 2017, 3, 12, 2, 30, 0, 0, 0, 0)はempty Listを返します。

21.4.1.21 GetNamedTimeZoneOffsetNanoseconds ( timeZoneIdentifier, epochNanoseconds )

The implementation-defined abstract operation GetNamedTimeZoneOffsetNanoseconds takes arguments timeZoneIdentifier (a String) and epochNanoseconds (a BigInt) and returns an integer.

返されるintegerは、timeZoneIdentifierによってidentifiedされるnamed time zoneのUTCからのoffsetを表し、epochNanosecondsに対応するepoch relativeなinstantにおける値であり、いずれもnanoseconds単位です。

time zonesに関するlocal political rulesを含まないECMAScript implementationsで使用されるGetNamedTimeZoneOffsetNanosecondsのdefault implementationは、呼び出されたとき次のstepsを実行します:

  1. Assert: timeZoneIdentifier"UTC"である。
  2. 0を返す。
Note

Time zone offset valuesはpositiveまたはnegativeであり得ます。

21.4.1.22 Time Zone Identifier Record

Time Zone Identifier Recordは、available named time zone identifierおよびそれに対応するprimary time zone identifierをdescribeするために使用されるRecordです。

Time Zone Identifier Recordsは、Table 60にlistedされたfieldsを持ちます。

Table 60: Time Zone Identifier Record Fields
Field Name Value Meaning
[[Identifier]] a String implementationによってsupportされるavailable named time zone identifier
[[PrimaryIdentifier]] a String [[Identifier]]がresolveするprimary time zone identifier
Note

[[Identifier]]primary time zone identifierである場合、[[Identifier]][[PrimaryIdentifier]]です。

21.4.1.23 AvailableNamedTimeZoneIdentifiers ( )

The implementation-defined abstract operation AvailableNamedTimeZoneIdentifiers takes no arguments and returns a List of Time Zone Identifier Records. そのresultは、このimplementation内のすべてのavailable named time zone identifiers、および各available named time zone identifierに対応するprimary time zone identifierをdescribeします。 Listは各Time Zone Identifier Record[[Identifier]] fieldに従ってorderedされます。

ECMA-402 Internationalization APIをimplementするすべてのimplementationsを含むtime zone aware implementationsは、AvailableNamedTimeZoneIdentifiers abstract operationをECMA-402 specificationで指定される通りにimplementしなければなりません。 time zone awareでないimplementationsについて、AvailableNamedTimeZoneIdentifiersは呼び出されたとき次のstepsを実行します:

  1. implementationがtime zonesに関するlocal political rulesをまったく含まないなら、
    1. « the Time Zone Identifier Record { [[Identifier]]: "UTC", [[PrimaryIdentifier]]: "UTC" } »を返す。
  2. identifiersを、lexicographic code unit orderに従ってsortedされた、unique available named time zone identifiersListとする。
  3. resultを新しい空のListとする。
  4. identifiersの各要素identifierについて、以下を行う
    1. primaryidentifierとする。
    2. identifierがこのimplementation内のnon-primary time zone identifierであり、かつidentifier"UTC"でないなら、
      1. primaryidentifierにassociatedされたprimary time zone identifierに設定する。
      2. NOTE: implementationはprimary time zone identifierをobtainするためにidentifierをiterativelyにresolveする必要がある場合がある。
    3. recordTime Zone Identifier Record { [[Identifier]]: identifier, [[PrimaryIdentifier]]: primary }とする。
    4. recordresultへappendする。
  5. Assert: resultは、record.[[Identifier]]"UTC"であり、record.[[PrimaryIdentifier]]"UTC"であるようなTime Zone Identifier Record recordを含む。
  6. resultを返す。

21.4.1.24 SystemTimeZoneIdentifier ( )

The implementation-defined abstract operation SystemTimeZoneIdentifier takes no arguments and returns a String. host environmentのcurrent time zoneを表すStringを返します。これは、IsTimeZoneOffsetStringtrueを返すUTC offsetを表すString、またはprimary time zone identifierのいずれかです。 It performs the following steps when called:

  1. implementationがUTC time zoneのみをsupportするなら、"UTC"を返す。
  2. systemTimeZoneStringを、host environmentのcurrent time zoneを表すString、すなわちprimary time zone identifierまたはoffset time zone identifierとする。
  3. systemTimeZoneStringを返す。
Note

implementationsがDate objectのmethodsにおいてcommonlyに提供するlevel of functionalityをensureするため、SystemTimeZoneIdentifierは、そのようなものが存在する場合、host environmentのtime zone settingに対応するIANA time zone nameを返すことがrecommendedされます。 GetNamedTimeZoneEpochNanosecondsおよびGetNamedTimeZoneOffsetNanosecondsは、そのようなrulesが存在する場合、そのtime zoneにおけるstandard timeおよびdaylight saving timeに関するlocal political rulesをreflectしなければなりません。

例えば、host environmentが、userがtime zoneとしてUS Eastern Timeを選択したsystem上のbrowserである場合、SystemTimeZoneIdentifierは"America/New_York"を返します。

21.4.1.25 LocalTime ( tv )

The abstract operation LocalTime takes argument tv (a finite time value) and returns an integral Number. tvをUTCからlocal timeへconvertします。 tvにおいて有効なstandard timeおよびdaylight saving timeに関するlocal political rulesは、このsectionで指定される方法でresultをdetermineするために使用されるべきです。 It performs the following steps when called:

  1. systemTimeZoneIdentifierSystemTimeZoneIdentifier()とする。
  2. IsTimeZoneOffsetString(systemTimeZoneIdentifier)がtrueなら、
    1. offsetNsParseTimeZoneOffsetString(systemTimeZoneIdentifier)とする。
  3. そうでなければ、
    1. offsetNsGetNamedTimeZoneOffsetNanoseconds(systemTimeZoneIdentifier, ((tv) × 106))とする。
  4. offsetMstruncate(offsetNs / 106)とする。
  5. tv + 𝔽(offsetMs)を返す。
Note 1

local time tvに関するpolitical rulesがimplementation内でavailableでない場合、resultはtvです。なぜならSystemTimeZoneIdentifier"UTC"を返し、GetNamedTimeZoneOffsetNanosecondsは0を返すためです。

Note 2

time zone aware implementations(およびその他すべて)には、IANA Time Zone Database https://www.iana.org/time-zones/のtime zone informationを使用することがrequired(その他すべてにはrecommended)です。

Note 3

異なる2つのinput time values tvUTCは、repeated timesが存在するnegative time zone transition(例えばdaylight saving timeが終了するとき、またはtime zone adjustmentがdecreasedされるとき)に、同じlocal time tlocalへconvertedされます。

LocalTime(UTC(tvlocal))は、必ずしも常にtvlocalにequalであるとは限りません。対応して、UTC(LocalTime(tvUTC))も、必ずしも常にtvUTCにequalであるとは限りません。

21.4.1.26 UTC ( t )

The abstract operation UTC takes argument t (a Number) and returns a time value. tをlocal timeからUTC time valueへconvertします。 tにおいて有効なstandard timeおよびdaylight saving timeに関するlocal political rulesは、このsectionで指定される方法でresultをdetermineするために使用されるべきです。 It performs the following steps when called:

  1. tfiniteでないなら、NaNを返す。
  2. systemTimeZoneIdentifierSystemTimeZoneIdentifier()とする。
  3. IsTimeZoneOffsetString(systemTimeZoneIdentifier)がtrueなら、
    1. offsetNsParseTimeZoneOffsetString(systemTimeZoneIdentifier)とする。
  4. そうでなければ、
    1. possibleInstantsGetNamedTimeZoneEpochNanoseconds(systemTimeZoneIdentifier, (YearFromTime(t)), (MonthFromTime(t)) + 1, (DateFromTime(t)), (HourFromTime(t)), (MinFromTime(t)), (SecFromTime(t)), (msFromTime(t)), 0, 0)とする。
    2. NOTE: 以下のstepsは、tがnegative time zone transition(例えばdaylight saving timeが終了するとき、またはtime zone rule changeによりtime zone offsetがdecreasedされるとき)で複数回repeatingするlocal time、またはpositive time zone transition(例えばdaylight saving timeが開始するとき、またはtime zone rule changeによりtime zone offsetがincreasedされるとき)でskippedされるlocal timeを表す場合、tがtransition前のtime zone offsetを使用してinterpretedされることをensureする。
    3. possibleInstantsがemptyでないなら、
      1. disambiguatedInstantpossibleInstants[0]とする。
    4. そうでなければ、
      1. NOTE: tはpositive time zone transitionでskippedされたlocal timeを表す(例えばdaylight saving timeの開始、またはUTC offsetをincreaseするtime zone rule changeによる)。
      2. possibleInstantsBeforeGetNamedTimeZoneEpochNanoseconds(systemTimeZoneIdentifier, (YearFromTime(tBefore)), (MonthFromTime(tBefore)) + 1, (DateFromTime(tBefore)), (HourFromTime(tBefore)), (MinFromTime(tBefore)), (SecFromTime(tBefore)), (msFromTime(tBefore)), 0, 0)とする。ここで、tBeforepossibleInstantsBeforeがemptyでないようなt未満のlargest integral Numberである(すなわち、tBeforeはtransition前のlast local timeを表す)。
      3. disambiguatedInstantpossibleInstantsBeforeのlast elementとする。
    5. offsetNsGetNamedTimeZoneOffsetNanoseconds(systemTimeZoneIdentifier, disambiguatedInstant)とする。
  5. offsetMstruncate(offsetNs / 106)とする。
  6. t - 𝔽(offsetMs)を返す。

Input tはnominallyにはtime valueですが、任意のNumber valueであり得ます。 algorithmはttime value rangeにlimitしてはなりません。これにより、time value rangeのboundaryに対応するinputsが、local UTC offsetにかかわらずsupportされます。 例えば、maximum time valueは8.64 × 1015であり、"+275760-09-13T00:00:00Z"に対応します。 local time zone offsetがそのinstantでUTCより1 hour進んでいるenvironmentでは、これはより大きいinputである8.64 × 1015 + 3.6 × 106、すなわち"+275760-09-13T01:00:00+01:00"に対応するものとして表されます。

local time tに関するpolitical rulesがimplementation内でavailableでない場合、resultはtです。なぜならSystemTimeZoneIdentifier"UTC"を返し、GetNamedTimeZoneOffsetNanosecondsは0を返すためです。

Note 1

time zone aware implementations(およびその他すべて)には、IANA Time Zone Database https://www.iana.org/time-zones/のtime zone informationを使用することがrequired(その他すべてにはrecommended)です。

America/New_Yorkにおける2017年11月5日の1:30 AMは2回repeatedされます(fall backward)が、1:30 AM UTC-05ではなく1:30 AM UTC-04としてinterpretedされなければなりません。 UTC(TimeClip(MakeDate(MakeDay(2017, 10, 5), MakeTime(1, 30, 0, 0))))において、offsetMsのvalueは-4 × msPerHourです。

America/New_Yorkにおける2017年3月12日の2:30 AMは存在しませんが、2:30 AM UTC-05(3:30 AM UTC-04にequivalent)としてinterpretedされなければなりません。 UTC(TimeClip(MakeDate(MakeDay(2017, 2, 12), MakeTime(2, 30, 0, 0))))において、offsetMsのvalueは-5 × msPerHourです。

Note 2

UTC(LocalTime(tUTC))は、必ずしも常にtUTCにequalであるとは限りません。対応して、LocalTime(UTC(tlocal))も、必ずしも常にtlocalにequalであるとは限りません。

21.4.1.27 MakeTime ( hour, min, sec, ms )

The abstract operation MakeTime takes arguments hour (a Number), min (a Number), sec (a Number), and ms (a Number) and returns a Number. millisecondsの数をcalculateします。 It performs the following steps when called:

  1. hourfiniteでない、minfiniteでない、secfiniteでない、またはmsfiniteでないなら、NaNを返す。
  2. h𝔽(! ToIntegerOrInfinity(hour))とする。
  3. m𝔽(! ToIntegerOrInfinity(min))とする。
  4. s𝔽(! ToIntegerOrInfinity(sec))とする。
  5. milli𝔽(! ToIntegerOrInfinity(ms))とする。
  6. ((h × msPerHour + m × msPerMinute) + s × msPerSecond) + milliを返す。
Note

MakeTime内のarithmeticはfloating-point arithmeticであり、associativeではないため、operationsはcorrect orderでperformされなければなりません。

21.4.1.28 MakeDay ( year, month, date )

The abstract operation MakeDay takes arguments year (a Number), month (a Number), and date (a Number) and returns a finite Number or NaN. daysの数をcalculateします。 It performs the following steps when called:

  1. yearfiniteでない、monthfiniteでない、またはdatefiniteでないなら、NaNを返す。
  2. y𝔽(! ToIntegerOrInfinity(year))とする。
  3. m𝔽(! ToIntegerOrInfinity(month))とする。
  4. dt𝔽(! ToIntegerOrInfinity(date))とする。
  5. ymy + 𝔽(floor((m) / 12))とする。
  6. ymfiniteでないなら、NaNを返す。
  7. mn𝔽((m) modulo 12)とする。
  8. YearFromTime(tv)がymであり、MonthFromTime(tv)がmnであり、DateFromTime(tv)が1𝔽であるようなfinite time value tvを見つける;ただし、これが可能でない場合(あるargumentがout of rangeであるため)、NaNを返す。
  9. Day(tv) + dt - 1𝔽を返す。

21.4.1.29 MakeDate ( day, time )

The abstract operation MakeDate takes arguments day (a Number) and time (a Number) and returns a finite Number or NaN. millisecondsの数をcalculateします。 It performs the following steps when called:

  1. dayfiniteでない、またはtimefiniteでないなら、NaNを返す。
  2. tvday × msPerDay + timeとする。
  3. tvfiniteでないなら、NaNを返す。
  4. tvを返す。

21.4.1.30 MakeFullYear ( year )

The abstract operation MakeFullYear takes argument year (a Number) and returns an integral Number or NaN. yearinteger partにassociatedされたfull yearを返します。0から99までのinclusive interval内の任意のvalueは、1900年のstartからのyearsのcountとしてinterpretingされます。proleptic Gregorian calendarとのalignmentのため、“full year”はyear 0(1 B.C.)のstartからのcomplete yearsのsigned countとして定義されます。 It performs the following steps when called:

  1. yearNaN+∞𝔽、または-∞𝔽のいずれかなら、NaNを返す。
  2. truncatedを ! ToIntegerOrInfinity(year) とする。
  3. truncatedが0から99までのinclusive interval内にあるなら、1900𝔽 + 𝔽(truncated)を返す。
  4. 𝔽(truncated)を返す。

21.4.1.31 TimeClip ( time )

The abstract operation TimeClip takes argument time (a Number) and returns a time value. millisecondsの数をcalculateします。 It performs the following steps when called:

  1. timefiniteでないなら、NaNを返す。
  2. abs((time)) > 8.64 × 1015なら、NaNを返す。
  3. 𝔽(! ToIntegerOrInfinity(time))を返す。

21.4.1.32 Date Time String Format

ECMAScriptは、ISO 8601 calendar date extended formatのsimplificationに基づくdate-timesのstring interchange formatを定義します。formatは次の通りです:YYYY-MM-DDTHH:mm:ss.sssZ

elementsは次の通りです:

YYYY proleptic Gregorian calendarにおけるyearであり、0000から9999までのfour decimal digits、または"+"または"-"の後にsix decimal digitsが続くexpanded yearです。
- "-"(hyphen)はstring内にliteralに2回appearsします。
MM yearのmonthであり、01(January)から12(December)までのtwo decimal digitsです。
DD monthのdayであり、01から31までのtwo decimal digitsです。
T time elementのbeginningを示すため、"T"がstring内にliteralにappearsします。
HH midnightから経過したcomplete hoursの数であり、00から24までのtwo decimal digitsです。
: ":"(colon)はstring内にliteralに2回appearsします。
mm hourのstartからのcomplete minutesの数であり、00から59までのtwo decimal digitsです。
ss minuteのstartからのcomplete secondsの数であり、00から59までのtwo decimal digitsです。
. "."(dot)はstring内にliteralにappearsします。
sss secondのstartからのcomplete millisecondsの数であり、three decimal digitsです。
Z UTC offset representationであり、"Z"(offsetなしのUTC)として、または"+"または"-"の後にtime expression HH:mmが続くものとしてspecifiedされます(UTCよりaheadまたはbehindであるlocal timeをそれぞれ示すためのtime zone offset string formatのsubset)

このformatはdate-only formsを含みます:

YYYY
YYYY-MM
YYYY-MM-DD
        

また、上記のdate-only formsのいずれかの直後に、optional UTC offset representationがappendedされた以下のtime formsのいずれかが続く“date-time” formsも含みます:

THH:mm
THH:mm:ss
THH:mm:ss.sss
        

out-of-boundsまたはnonconforming elementsを含むstringは、このformatのvalid instanceではありません。

Note 1

すべての日はmidnightでstartしmidnightでendするため、notation 00:00および24:00の2つは、one dateにassociatedされ得る2つのmidnightsをdistinguishするためにavailableです。これは、次の2つのnotationsがexactly same point in timeをreferすることを意味します:1995-02-04T24:00および1995-02-05T00:00。後者のformを“calendar dayのend”としてinterpretすることは、そのspecificationがtime intervalsをdescribingするためにreservedし、single points in timeのrepresentations内ではpermitしていないとしても、ISO 8601とconsistentです。

Note 2

CET、ESTなどのcivil time zonesのabbreviationsをspecifyするinternational standardは存在せず、ときには同じabbreviationが非常に異なる2つのtime zonesに使用されることすらあります。この理由により、ISO 8601とこのformatの両方は、time zone offsetsのnumeric representationsを指定します。

21.4.1.32.1 Expanded Years

1970年1月1日からforwardまたはbackwardにおよそ273,790年というfull time value range(21.4.1.1)をcoverするには、0より前または9999より後のyearsをrepresentする必要があります。ISO 8601はyear representationのexpansionをpermitしますが、information interchangeのpartners間のmutual agreementによる場合に限ります。simplified ECMAScript formatでは、そのようなexpanded year representationは6 digitsを持ち、常に+または- signでprefixedされなければなりません。year 0はpositiveとみなされ、+ signでprefixedされなければなりません。year 0を-000000として表すrepresentationはinvalidです。time valueのrange外のinstants in timeを表すexpanded yearsを持つDate Time String FormatにmatchingするStringsは、Date.parseによってunrecognizableとして扱われ、そのfunctionはimplementation-specific behaviourまたはheuristicsにfall backせずにNaNを返します。

Note

expanded yearsを持つdate-time valuesのexamples:

-271821-04-20T00:00:00Z 271822 B.C.
-000001-01-01T00:00:00Z 2 B.C.
+000000-01-01T00:00:00Z 1 B.C.
+000001-01-01T00:00:00Z 1 A.D.
+001970-01-01T00:00:00Z 1970 A.D.
+002009-12-15T00:00:00Z 2009 A.D.
+275760-09-13T00:00:00Z 275760 A.D.

21.4.1.33 Time Zone Offset String Format

ECMAScriptは、ISO 8601からderivedされたUTC offsetsのstring interchange formatを定義します。 formatは以下のgrammarによってdescribedされます。

Syntax

UTCOffset ::: ASCIISign Hour ASCIISign Hour HourSubcomponents[+Extended] ASCIISign Hour HourSubcomponents[~Extended] ASCIISign ::: one of + - Hour ::: 0 DecimalDigit 1 DecimalDigit 20 21 22 23 HourSubcomponents[Extended] ::: TimeSeparator[?Extended] MinuteSecond TimeSeparator[?Extended] MinuteSecond TimeSeparator[?Extended] MinuteSecond TemporalDecimalFractionopt TimeSeparator[Extended] ::: [+Extended] : [~Extended] [empty] MinuteSecond ::: 0 DecimalDigit 1 DecimalDigit 2 DecimalDigit 3 DecimalDigit 4 DecimalDigit 5 DecimalDigit TemporalDecimalFraction ::: TemporalDecimalSeparator DecimalDigit TemporalDecimalSeparator DecimalDigit DecimalDigit TemporalDecimalSeparator DecimalDigit DecimalDigit DecimalDigit TemporalDecimalSeparator DecimalDigit DecimalDigit DecimalDigit DecimalDigit TemporalDecimalSeparator DecimalDigit DecimalDigit DecimalDigit DecimalDigit DecimalDigit TemporalDecimalSeparator DecimalDigit DecimalDigit DecimalDigit DecimalDigit DecimalDigit DecimalDigit TemporalDecimalSeparator DecimalDigit DecimalDigit DecimalDigit DecimalDigit DecimalDigit DecimalDigit DecimalDigit TemporalDecimalSeparator DecimalDigit DecimalDigit DecimalDigit DecimalDigit DecimalDigit DecimalDigit DecimalDigit DecimalDigit TemporalDecimalSeparator DecimalDigit DecimalDigit DecimalDigit DecimalDigit DecimalDigit DecimalDigit DecimalDigit DecimalDigit DecimalDigit TemporalDecimalSeparator ::: one of . ,

21.4.1.33.1 IsTimeZoneOffsetString ( offsetString )

The abstract operation IsTimeZoneOffsetString takes argument offsetString (a String) and returns a Boolean. return valueは、offsetStringUTCOffsetによって与えられるgrammarにconformするかどうかを示します。 It performs the following steps when called:

  1. parseResultParseText(offsetString, UTCOffset)とする。
  2. parseResultがerrorsのListなら、falseを返す。
  3. trueを返す。

21.4.1.33.2 ParseTimeZoneOffsetString ( offsetString )

The abstract operation ParseTimeZoneOffsetString takes argument offsetString (a String) and returns an integer. return valueは、String offsetStringに対応するUTC offsetであり、nanosecondsの数です。 It performs the following steps when called:

  1. parseResultParseText(offsetString, UTCOffset)とする。
  2. Assert: parseResultはerrorsのListではない。
  3. Assert: parseResultASCIISign Parse Nodeを含む。
  4. parsedSignparseResult内に含まれるASCIISign Parse Nodeにmatchedするsource textとする。
  5. parsedSignがsingle code point U+002D (HYPHEN-MINUS)なら、
    1. signを-1とする。
  6. そうでなければ、
    1. signを1とする。
  7. NOTE: 以下のStringToNumberのapplicationsはprecisionを失わない。なぜなら、parsed valuesのそれぞれは十分に短いdecimal digitsのstringであることがguaranteedされるからである。
  8. Assert: parseResultHour Parse Nodeを含む。
  9. parsedHoursparseResult内に含まれるHour Parse Nodeにmatchedするsource textとする。
  10. hours(StringToNumber(CodePointsToString(parsedHours)))とする。
  11. parseResultMinuteSecond Parse Nodeを含まないなら、
    1. minutesを0とする。
  12. そうでなければ、
    1. parsedMinutesparseResult内に含まれるfirst MinuteSecond Parse Nodeにmatchedするsource textとする。
    2. minutes(StringToNumber(CodePointsToString(parsedMinutes)))とする。
  13. parseResultがtwo MinuteSecond Parse Nodesを含まないなら、
    1. secondsを0とする。
  14. そうでなければ、
    1. parsedSecondsparseResult内に含まれるsecond MinuteSecond Parse Nodeにmatchedするsource textとする。
    2. seconds(StringToNumber(CodePointsToString(parsedSeconds)))とする。
  15. parseResultTemporalDecimalFraction Parse Nodeを含まないなら、
    1. nanosecondsを0とする。
  16. そうでなければ、
    1. parsedFractionparseResult内に含まれるTemporalDecimalFraction Parse Nodeにmatchedするsource textとする。
    2. fractionCodePointsToString(parsedFraction)と"000000000"string-concatenationとする。
    3. nanosecondsStringfractionの1から10までのsubstringとする。
    4. nanoseconds(StringToNumber(nanosecondsString))とする。
  17. sign × (((hours × 60 + minutes) × 60 + seconds) × 109 + nanoseconds)を返す。

21.4.2 The Date Constructor

Date constructorは:

  • %Date%です。
  • global object"Date" propertyのinitial valueです。
  • constructorとして呼び出されたとき、新しいDateを作成およびinitializeします。
  • constructorとしてではなくfunctionとして呼び出されたとき、current time(UTC)を表すStringを返します。
  • そのbehaviourがargumentsのnumberおよびtypesに基づいて異なるfunctionです。
  • class definitionのextends clauseのvalueとして使用できます。指定されたDate behaviourをinheritしようとするsubclass constructorsは、[[DateValue]] internal slotを持つsubclass instanceを作成およびinitializeするために、Date constructorへのsuper callを含まなければなりません。

21.4.2.1 Date ( ...values )

このfunctionは呼び出されたとき、次のstepsを実行します:

  1. NewTargetがundefinedなら、
    1. nowをcurrent timeをidentifyするtime value(UTC)とする。
    2. ToDateString(now)を返す。
  2. numberOfArgsvalues内のelementsの数とする。
  3. numberOfArgs = 0なら、
    1. dvをcurrent timeをidentifyするtime value(UTC)とする。
  4. そうでなく、numberOfArgs = 1なら、
    1. valuevalues[0]とする。
    2. valueがObjectであり、value[[DateValue]] internal slotを持つなら、
      1. tvvalue.[[DateValue]]とする。
    3. そうでなければ、
      1. vを ? ToPrimitive(value) とする。
      2. vがStringなら、
        1. Assert: vはStringであるため、next stepはabrupt completionを返すことはない。
        2. tvを、parse method(21.4.3.2)の場合とexactly same mannerで、vをdateとしてparsingしたresultとする。
      3. そうでなければ、
        1. tvを ? ToNumber(v) とする。
    4. dvTimeClip(tv)とする。
  5. そうでなければ、
    1. Assert: numberOfArgs ≥ 2である。
    2. yを ? ToNumber(values[0]) とする。
    3. mを ? ToNumber(values[1]) とする。
    4. numberOfArgs > 2なら、dtを ? ToNumber(values[2]) とする;そうでなければ、dt1𝔽とする。
    5. numberOfArgs > 3なら、hを ? ToNumber(values[3]) とする;そうでなければ、h+0𝔽とする。
    6. numberOfArgs > 4なら、minを ? ToNumber(values[4]) とする;そうでなければ、min+0𝔽とする。
    7. numberOfArgs > 5なら、sを ? ToNumber(values[5]) とする;そうでなければ、s+0𝔽とする。
    8. numberOfArgs > 6なら、milliを ? ToNumber(values[6]) とする;そうでなければ、milli+0𝔽とする。
    9. yrMakeFullYear(y)とする。
    10. finalDateMakeDate(MakeDay(yr, m, dt), MakeTime(h, min, s, milli))とする。
    11. dvTimeClip(UTC(finalDate))とする。
  6. objを ? OrdinaryCreateFromConstructor(NewTarget, "%Date.prototype%", « [[DateValue]] ») とする。
  7. obj.[[DateValue]]dvに設定する。
  8. objを返す。

21.4.3 Properties of the Date Constructor

Date constructorは:

  • valueが%Function.prototype%である[[Prototype]] internal slotを持ちます。
  • valueが7𝔽である"length" propertyを持ちます。
  • 次のpropertiesを持ちます:

21.4.3.1 Date.now ( )

このfunctionは、それへのcallのoccurrenceのUTC dateおよびtimeをdesignateするtime valueを返します。

21.4.3.2 Date.parse ( string )

このfunctionは、そのargumentにToString operatorをapplyします。ToStringabrupt completionとなった場合、Completion Recordがimmediatelyに返されます。そうでなければ、このfunctionは得られたStringをdateおよびtimeとしてinterpretします;これは、dateおよびtimeに対応するUTC time valueであるNumberを返します。Stringのcontentsに応じて、Stringはlocal time、UTC time、またはsome other time zoneのtimeとしてinterpretedされ得ます。functionはまず、expanded yearsを含め、Date Time String Format(21.4.1.32)でdescribedされたformatに従ってStringをparseしようとします。Stringがそのformatにconformしない場合、functionは任意のimplementation-specific heuristicsまたはimplementation-specific date formatsにfall backしてもよいです。unrecognizableである、またはout-of-bounds format element valuesを含むStringsは、このfunctionにNaNを返させなければなりません。

StringがDate Time String Formatにconformする場合、absent format elementsのplaceにはsubstitute valuesが入ります。MMまたはDD elementsがabsentである場合、"01"が使用されます。HHmm、またはss elementsがabsentである場合、"00"が使用されます。sss elementがabsentである場合、"000"が使用されます。UTC offset representationがabsentである場合、date-only formsはUTC timeとしてinterpretedされ、date-time formsはlocal timeとしてinterpretedされます。

xが、ECMAScriptの特定のimplementation内でmilliseconds amountがzeroである任意のDateである場合、referencedされるすべてのpropertiesがinitial valuesを持つなら、以下のexpressionsはすべて、そのimplementation内でsame numeric valueをproduceすべきです:

x.valueOf()
Date.parse(x.toString())
Date.parse(x.toUTCString())
Date.parse(x.toISOString())

しかし、expression

Date.parse(x.toLocaleString())

は、preceding three expressionsとsame Number valueをproduceすることはrequiredではなく、generalに、このfunctionによってproduceされるvalueは、Date Time String Format(21.4.1.32)にconformせず、かつそのimplementationでtoStringまたはtoUTCString methodによってproduceされ得ない任意のString valueが与えられた場合、implementation-definedです。

21.4.3.3 Date.prototype

Date.prototypeのinitial valueはDate prototype objectです。

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

21.4.3.4 Date.UTC ( year [ , month [ , date [ , hours [ , minutes [ , seconds [ , ms ] ] ] ] ] ] )

このfunctionは呼び出されたとき、次のstepsを実行します:

  1. yを ? ToNumber(year) とする。
  2. monthがpresentなら、mを ? ToNumber(month) とする;そうでなければ、m+0𝔽とする。
  3. dateがpresentなら、dtを ? ToNumber(date) とする;そうでなければ、dt1𝔽とする。
  4. hoursがpresentなら、hを ? ToNumber(hours) とする;そうでなければ、h+0𝔽とする。
  5. minutesがpresentなら、minを ? ToNumber(minutes) とする;そうでなければ、min+0𝔽とする。
  6. secondsがpresentなら、sを ? ToNumber(seconds) とする;そうでなければ、s+0𝔽とする。
  7. msがpresentなら、milliを ? ToNumber(ms) とする;そうでなければ、milli+0𝔽とする。
  8. yrMakeFullYear(y)とする。
  9. TimeClip(MakeDate(MakeDay(yr, m, dt), MakeTime(h, min, s, milli)))を返す。

このfunctionの"length" propertyは7𝔽です。

Note

このfunctionはDate constructorと2つの点で異なります:これはDateを作成するのではなくNumberとしてtime valueを返し、argumentsをlocal timeとしてではなくUTCとしてinterpretします。

21.4.4 Properties of the Date Prototype Object

Date prototype objectは:

  • %Date.prototype%です。
  • それ自体がordinary objectです。
  • Date instanceではなく、[[DateValue]] internal slotを持ちません。
  • valueが%Object.prototype%である[[Prototype]] internal slotを持ちます。

明示的に別途定義されない限り、以下で定義されるDate prototype objectのmethodsはgenericではなく、それらに渡されるthis valueは、time valueへinitialized済みの[[DateValue]] internal slotを持つobjectでなければなりません。

21.4.4.1 Date.prototype.constructor

Date.prototype.constructorのinitial valueは%Date%です。

21.4.4.2 Date.prototype.getDate ( )

このmethodは呼び出されたとき、次のstepsを実行します:

  1. dateObjthis valueとする。
  2. RequireInternalSlot(dateObj, [[DateValue]])を実行する。
  3. tvdateObj.[[DateValue]]とする。
  4. tvNaNなら、NaNを返す。
  5. DateFromTime(LocalTime(tv))を返す。

21.4.4.3 Date.prototype.getDay ( )

このmethodは呼び出されたとき、次のstepsを実行します:

  1. dateObjthis valueとする。
  2. RequireInternalSlot(dateObj, [[DateValue]])を実行する。
  3. tvdateObj.[[DateValue]]とする。
  4. tvNaNなら、NaNを返す。
  5. WeekDay(LocalTime(tv))を返す。

21.4.4.4 Date.prototype.getFullYear ( )

このmethodは呼び出されたとき、次のstepsを実行します:

  1. dateObjthis valueとする。
  2. RequireInternalSlot(dateObj, [[DateValue]])を実行する。
  3. tvdateObj.[[DateValue]]とする。
  4. tvNaNなら、NaNを返す。
  5. YearFromTime(LocalTime(tv))を返す。

21.4.4.5 Date.prototype.getHours ( )

このmethodは呼び出されたとき、次のstepsを実行します:

  1. dateObjthis valueとする。
  2. RequireInternalSlot(dateObj, [[DateValue]])を実行する。
  3. tvdateObj.[[DateValue]]とする。
  4. tvNaNなら、NaNを返す。
  5. HourFromTime(LocalTime(tv))を返す。

21.4.4.6 Date.prototype.getMilliseconds ( )

このmethodは呼び出されたとき、次のstepsを実行します:

  1. dateObjthis valueとする。
  2. RequireInternalSlot(dateObj, [[DateValue]])を実行する。
  3. tvdateObj.[[DateValue]]とする。
  4. tvNaNなら、NaNを返す。
  5. msFromTime(LocalTime(tv))を返す。

21.4.4.7 Date.prototype.getMinutes ( )

このmethodは呼び出されたとき、次のstepsを実行します:

  1. dateObjthis valueとする。
  2. RequireInternalSlot(dateObj, [[DateValue]])を実行する。
  3. tvdateObj.[[DateValue]]とする。
  4. tvNaNなら、NaNを返す。
  5. MinFromTime(LocalTime(tv))を返す。

21.4.4.8 Date.prototype.getMonth ( )

このmethodは呼び出されたとき、次のstepsを実行します:

  1. dateObjthis valueとする。
  2. RequireInternalSlot(dateObj, [[DateValue]])を実行する。
  3. tvdateObj.[[DateValue]]とする。
  4. tvNaNなら、NaNを返す。
  5. MonthFromTime(LocalTime(tv))を返す。

21.4.4.9 Date.prototype.getSeconds ( )

このmethodは呼び出されたとき、次のstepsを実行します:

  1. dateObjthis valueとする。
  2. RequireInternalSlot(dateObj, [[DateValue]])を実行する。
  3. tvdateObj.[[DateValue]]とする。
  4. tvNaNなら、NaNを返す。
  5. SecFromTime(LocalTime(tv))を返す。

21.4.4.10 Date.prototype.getTime ( )

このmethodは呼び出されたとき、次のstepsを実行します:

  1. dateObjthis valueとする。
  2. RequireInternalSlot(dateObj, [[DateValue]])を実行する。
  3. dateObj.[[DateValue]]を返す。

21.4.4.11 Date.prototype.getTimezoneOffset ( )

このmethodは呼び出されたとき、次のstepsを実行します:

  1. dateObjthis valueとする。
  2. RequireInternalSlot(dateObj, [[DateValue]])を実行する。
  3. tvdateObj.[[DateValue]]とする。
  4. tvNaNなら、NaNを返す。
  5. (tv - LocalTime(tv)) / msPerMinuteを返す。

21.4.4.12 Date.prototype.getUTCDate ( )

このmethodは呼び出されたとき、次のstepsを実行します:

  1. dateObjthis valueとする。
  2. RequireInternalSlot(dateObj, [[DateValue]])を実行する。
  3. tvdateObj.[[DateValue]]とする。
  4. tvNaNなら、NaNを返す。
  5. DateFromTime(tv)を返す。

21.4.4.13 Date.prototype.getUTCDay ( )

このmethodは呼び出されたとき、次のstepsを実行します:

  1. dateObjthis valueとする。
  2. RequireInternalSlot(dateObj, [[DateValue]])を実行する。
  3. tvdateObj.[[DateValue]]とする。
  4. tvNaNなら、NaNを返す。
  5. WeekDay(tv)を返す。

21.4.4.14 Date.prototype.getUTCFullYear ( )

このmethodは呼び出されたとき、次のstepsを実行します:

  1. dateObjthis valueとする。
  2. RequireInternalSlot(dateObj, [[DateValue]])を実行する。
  3. tvdateObj.[[DateValue]]とする。
  4. tvNaNなら、NaNを返す。
  5. YearFromTime(tv)を返す。

21.4.4.15 Date.prototype.getUTCHours ( )

このmethodは呼び出されたとき、次のstepsを実行します:

  1. dateObjthis valueとする。
  2. RequireInternalSlot(dateObj, [[DateValue]])を実行する。
  3. tvdateObj.[[DateValue]]とする。
  4. tvNaNなら、NaNを返す。
  5. HourFromTime(tv)を返す。

21.4.4.16 Date.prototype.getUTCMilliseconds ( )

このmethodは呼び出されたとき、次のstepsを実行します:

  1. dateObjthis valueとする。
  2. RequireInternalSlot(dateObj, [[DateValue]])を実行する。
  3. tvdateObj.[[DateValue]]とする。
  4. tvNaNなら、NaNを返す。
  5. msFromTime(tv)を返す。

21.4.4.17 Date.prototype.getUTCMinutes ( )

このmethodは呼び出されたとき、次のstepsを実行します:

  1. dateObjthis valueとする。
  2. RequireInternalSlot(dateObj, [[DateValue]])を実行する。
  3. tvdateObj.[[DateValue]]とする。
  4. tvNaNなら、NaNを返す。
  5. MinFromTime(tv)を返す。

21.4.4.18 Date.prototype.getUTCMonth ( )

このmethodは呼び出されたとき、次のstepsを実行します:

  1. dateObjthis valueとする。
  2. RequireInternalSlot(dateObj, [[DateValue]])を実行する。
  3. tvdateObj.[[DateValue]]とする。
  4. tvNaNなら、NaNを返す。
  5. MonthFromTime(tv)を返す。

21.4.4.19 Date.prototype.getUTCSeconds ( )

このmethodは呼び出されたとき、次のstepsを実行します:

  1. dateObjthis valueとする。
  2. RequireInternalSlot(dateObj, [[DateValue]])を実行する。
  3. tvdateObj.[[DateValue]]とする。
  4. tvNaNなら、NaNを返す。
  5. SecFromTime(tv)を返す。

21.4.4.20 Date.prototype.setDate ( date )

このmethodは呼び出されたとき、次のstepsを実行します:

  1. dateObjthis valueとする。
  2. RequireInternalSlot(dateObj, [[DateValue]])を実行する。
  3. tvdateObj.[[DateValue]]とする。
  4. dtを ? ToNumber(date) とする。
  5. tvNaNなら、NaNを返す。
  6. tvLocalTime(tv)に設定する。
  7. newDateMakeDate(MakeDay(YearFromTime(tv), MonthFromTime(tv), dt), TimeWithinDay(tv))とする。
  8. uTimeClip(UTC(newDate))とする。
  9. dateObj.[[DateValue]]uに設定する。
  10. uを返す。

21.4.4.21 Date.prototype.setFullYear ( year [ , month [ , date ] ] )

このmethodは呼び出されたとき、次のstepsを実行します:

  1. dateObjthis valueとする。
  2. RequireInternalSlot(dateObj, [[DateValue]])を実行する。
  3. tvdateObj.[[DateValue]]とする。
  4. yを ? ToNumber(year) とする。
  5. tvNaNなら、tv+0𝔽に設定する;そうでなければ、tvLocalTime(tv)に設定する。
  6. monthがpresentなら、mを ? ToNumber(month) とする;そうでなければ、mMonthFromTime(tv)とする。
  7. dateがpresentなら、dtを ? ToNumber(date) とする;そうでなければ、dtDateFromTime(tv)とする。
  8. newDateMakeDate(MakeDay(y, m, dt), TimeWithinDay(tv))とする。
  9. uTimeClip(UTC(newDate))とする。
  10. dateObj.[[DateValue]]uに設定する。
  11. uを返す。

このmethodの"length" propertyは3𝔽です。

Note

monthがpresentでない場合、このmethodはmonthがvalue getMonth()でpresentであったかのようにbehaveします。dateがpresentでない場合、dateがvalue getDate()でpresentであったかのようにbehaveします。

21.4.4.22 Date.prototype.setHours ( hour [ , min [ , sec [ , ms ] ] ] )

このmethodは呼び出されたとき、次のstepsを実行します:

  1. dateObjthis valueとする。
  2. RequireInternalSlot(dateObj, [[DateValue]])を実行する。
  3. tvdateObj.[[DateValue]]とする。
  4. hを ? ToNumber(hour) とする。
  5. minがpresentなら、mを ? ToNumber(min) とする。
  6. secがpresentなら、sを ? ToNumber(sec) とする。
  7. msがpresentなら、milliを ? ToNumber(ms) とする。
  8. tvNaNなら、NaNを返す。
  9. tvLocalTime(tv)に設定する。
  10. minがpresentでないなら、mMinFromTime(tv)とする。
  11. secがpresentでないなら、sSecFromTime(tv)とする。
  12. msがpresentでないなら、millimsFromTime(tv)とする。
  13. dateMakeDate(Day(tv), MakeTime(h, m, s, milli))とする。
  14. uTimeClip(UTC(date))とする。
  15. dateObj.[[DateValue]]uに設定する。
  16. uを返す。

このmethodの"length" propertyは4𝔽です。

Note

minがpresentでない場合、このmethodはminがvalue getMinutes()でpresentであったかのようにbehaveします。secがpresentでない場合、secがvalue getSeconds()でpresentであったかのようにbehaveします。msがpresentでない場合、msがvalue getMilliseconds()でpresentであったかのようにbehaveします。

21.4.4.23 Date.prototype.setMilliseconds ( ms )

このmethodは呼び出されたとき、次のstepsを実行します:

  1. dateObjthis valueとする。
  2. RequireInternalSlot(dateObj, [[DateValue]])を実行する。
  3. tvdateObj.[[DateValue]]とする。
  4. msを ? ToNumber(ms) に設定する。
  5. tvNaNなら、NaNを返す。
  6. tvLocalTime(tv)に設定する。
  7. timeMakeTime(HourFromTime(tv), MinFromTime(tv), SecFromTime(tv), ms)とする。
  8. uTimeClip(UTC(MakeDate(Day(tv), time)))とする。
  9. dateObj.[[DateValue]]uに設定する。
  10. uを返す。

21.4.4.24 Date.prototype.setMinutes ( min [ , sec [ , ms ] ] )

このmethodは呼び出されたとき、次のstepsを実行します:

  1. dateObjthis valueとする。
  2. RequireInternalSlot(dateObj, [[DateValue]])を実行する。
  3. tvdateObj.[[DateValue]]とする。
  4. mを ? ToNumber(min) とする。
  5. secがpresentなら、sを ? ToNumber(sec) とする。
  6. msがpresentなら、milliを ? ToNumber(ms) とする。
  7. tvNaNなら、NaNを返す。
  8. tvLocalTime(tv)に設定する。
  9. secがpresentでないなら、sSecFromTime(tv)とする。
  10. msがpresentでないなら、millimsFromTime(tv)とする。
  11. dateMakeDate(Day(tv), MakeTime(HourFromTime(tv), m, s, milli))とする。
  12. uTimeClip(UTC(date))とする。
  13. dateObj.[[DateValue]]uに設定する。
  14. uを返す。

このmethodの"length" propertyは3𝔽です。

Note

secがpresentでない場合、このmethodはsecがvalue getSeconds()でpresentであったかのようにbehaveします。msがpresentでない場合、これはmsがvalue getMilliseconds()でpresentであったかのようにbehaveします。

21.4.4.25 Date.prototype.setMonth ( month [ , date ] )

このmethodは呼び出されたとき、次のstepsを実行します:

  1. dateObjthis valueとする。
  2. RequireInternalSlot(dateObj, [[DateValue]])を実行する。
  3. tvdateObj.[[DateValue]]とする。
  4. mを ? ToNumber(month) とする。
  5. dateがpresentなら、dtを ? ToNumber(date) とする。
  6. tvNaNなら、NaNを返す。
  7. tvLocalTime(tv)に設定する。
  8. dateがpresentでないなら、dtDateFromTime(tv)とする。
  9. newDateMakeDate(MakeDay(YearFromTime(tv), m, dt), TimeWithinDay(tv))とする。
  10. uTimeClip(UTC(newDate))とする。
  11. dateObj.[[DateValue]]uに設定する。
  12. uを返す。

このmethodの"length" propertyは2𝔽です。

Note

dateがpresentでない場合、このmethodはdateがvalue getDate()でpresentであったかのようにbehaveします。

21.4.4.26 Date.prototype.setSeconds ( sec [ , ms ] )

このmethodは呼び出されたとき、次のstepsを実行します:

  1. dateObjthis valueとする。
  2. RequireInternalSlot(dateObj, [[DateValue]])を実行する。
  3. tvdateObj.[[DateValue]]とする。
  4. sを ? ToNumber(sec) とする。
  5. msがpresentなら、milliを ? ToNumber(ms) とする。
  6. tvNaNなら、NaNを返す。
  7. tvLocalTime(tv)に設定する。
  8. msがpresentでないなら、millimsFromTime(tv)とする。
  9. dateMakeDate(Day(tv), MakeTime(HourFromTime(tv), MinFromTime(tv), s, milli))とする。
  10. uTimeClip(UTC(date))とする。
  11. dateObj.[[DateValue]]uに設定する。
  12. uを返す。

このmethodの"length" propertyは2𝔽です。

Note

msがpresentでない場合、このmethodはmsがvalue getMilliseconds()でpresentであったかのようにbehaveします。

21.4.4.27 Date.prototype.setTime ( time )

このmethodは呼び出されたとき、次のstepsを実行します:

  1. dateObjthis valueとする。
  2. RequireInternalSlot(dateObj, [[DateValue]])を実行する。
  3. tを ? ToNumber(time) とする。
  4. vTimeClip(t)とする。
  5. dateObj.[[DateValue]]vに設定する。
  6. vを返す。

21.4.4.28 Date.prototype.setUTCDate ( date )

このmethodは呼び出されたとき、次のstepsを実行します:

  1. dateObjthis valueとする。
  2. RequireInternalSlot(dateObj, [[DateValue]])を実行する。
  3. tvdateObj.[[DateValue]]とする。
  4. dtを ? ToNumber(date) とする。
  5. tvNaNなら、NaNを返す。
  6. newDateMakeDate(MakeDay(YearFromTime(tv), MonthFromTime(tv), dt), TimeWithinDay(tv))とする。
  7. vTimeClip(newDate)とする。
  8. dateObj.[[DateValue]]vに設定する。
  9. vを返す。

21.4.4.29 Date.prototype.setUTCFullYear ( year [ , month [ , date ] ] )

このmethodは呼び出されたとき、次のstepsを実行します:

  1. dateObjthis valueとする。
  2. RequireInternalSlot(dateObj, [[DateValue]])を実行する。
  3. tvdateObj.[[DateValue]]とする。
  4. tvNaNなら、tv+0𝔽に設定する。
  5. yを ? ToNumber(year) とする。
  6. monthがpresentなら、mを ? ToNumber(month) とする;そうでなければ、mMonthFromTime(tv)とする。
  7. dateがpresentなら、dtを ? ToNumber(date) とする;そうでなければ、dtDateFromTime(tv)とする。
  8. newDateMakeDate(MakeDay(y, m, dt), TimeWithinDay(tv))とする。
  9. vTimeClip(newDate)とする。
  10. dateObj.[[DateValue]]vに設定する。
  11. vを返す。

このmethodの"length" propertyは3𝔽です。

Note

monthがpresentでない場合、このmethodはmonthがvalue getUTCMonth()でpresentであったかのようにbehaveします。dateがpresentでない場合、dateがvalue getUTCDate()でpresentであったかのようにbehaveします。

21.4.4.30 Date.prototype.setUTCHours ( hour [ , min [ , sec [ , ms ] ] ] )

このmethodは呼び出されたとき、次のstepsを実行します:

  1. dateObjthis valueとする。
  2. RequireInternalSlot(dateObj, [[DateValue]])を実行する。
  3. tvdateObj.[[DateValue]]とする。
  4. hを ? ToNumber(hour) とする。
  5. minがpresentなら、mを ? ToNumber(min) とする。
  6. secがpresentなら、sを ? ToNumber(sec) とする。
  7. msがpresentなら、milliを ? ToNumber(ms) とする。
  8. tvNaNなら、NaNを返す。
  9. minがpresentでないなら、mMinFromTime(tv)とする。
  10. secがpresentでないなら、sSecFromTime(tv)とする。
  11. msがpresentでないなら、millimsFromTime(tv)とする。
  12. dateMakeDate(Day(tv), MakeTime(h, m, s, milli))とする。
  13. vTimeClip(date)とする。
  14. dateObj.[[DateValue]]vに設定する。
  15. vを返す。

このmethodの"length" propertyは4𝔽です。

Note

minがpresentでない場合、このmethodはminがvalue getUTCMinutes()でpresentであったかのようにbehaveします。secがpresentでない場合、secがvalue getUTCSeconds()でpresentであったかのようにbehaveします。msがpresentでない場合、msがvalue getUTCMilliseconds()でpresentであったかのようにbehaveします。

21.4.4.31 Date.prototype.setUTCMilliseconds ( ms )

このmethodは呼び出されたとき、次のstepsを実行します:

  1. dateObjthis valueとする。
  2. RequireInternalSlot(dateObj, [[DateValue]])を実行する。
  3. tvdateObj.[[DateValue]]とする。
  4. msを ? ToNumber(ms) に設定する。
  5. tvNaNなら、NaNを返す。
  6. timeMakeTime(HourFromTime(tv), MinFromTime(tv), SecFromTime(tv), ms)とする。
  7. vTimeClip(MakeDate(Day(tv), time))とする。
  8. dateObj.[[DateValue]]vに設定する。
  9. vを返す。

21.4.4.32 Date.prototype.setUTCMinutes ( min [ , sec [ , ms ] ] )

このmethodは呼び出されたとき、次のstepsを実行します:

  1. dateObjthis valueとする。
  2. RequireInternalSlot(dateObj, [[DateValue]])を実行する。
  3. tvdateObj.[[DateValue]]とする。
  4. mを ? ToNumber(min) とする。
  5. secがpresentなら、sを ? ToNumber(sec) とする。
  6. msがpresentなら、milliを ? ToNumber(ms) とする。
  7. tvNaNなら、NaNを返す。
  8. secがpresentでないなら、sSecFromTime(tv)とする。
  9. msがpresentでないなら、millimsFromTime(tv)とする。
  10. dateMakeDate(Day(tv), MakeTime(HourFromTime(tv), m, s, milli))とする。
  11. vTimeClip(date)とする。
  12. dateObj.[[DateValue]]vに設定する。
  13. vを返す。

このmethodの"length" propertyは3𝔽です。

Note

secがpresentでない場合、このmethodはsecがvalue getUTCSeconds()でpresentであったかのようにbehaveします。msがpresentでない場合、msgetUTCMilliseconds()によって返されるvalueでpresentであったかのようにbehaveします。

21.4.4.33 Date.prototype.setUTCMonth ( month [ , date ] )

このmethodは呼び出されたとき、次のstepsを実行します:

  1. dateObjthis valueとする。
  2. RequireInternalSlot(dateObj, [[DateValue]])を実行する。
  3. tvdateObj.[[DateValue]]とする。
  4. mを ? ToNumber(month) とする。
  5. dateがpresentなら、dtを ? ToNumber(date) とする。
  6. tvNaNなら、NaNを返す。
  7. dateがpresentでないなら、dtDateFromTime(tv)とする。
  8. newDateMakeDate(MakeDay(YearFromTime(tv), m, dt), TimeWithinDay(tv))とする。
  9. vTimeClip(newDate)とする。
  10. dateObj.[[DateValue]]vに設定する。
  11. vを返す。

このmethodの"length" propertyは2𝔽です。

Note

dateがpresentでない場合、このmethodはdateがvalue getUTCDate()でpresentであったかのようにbehaveします。

21.4.4.34 Date.prototype.setUTCSeconds ( sec [ , ms ] )

このmethodは呼び出されたとき、次のstepsを実行します:

  1. dateObjthis valueとする。
  2. RequireInternalSlot(dateObj, [[DateValue]])を実行する。
  3. tvdateObj.[[DateValue]]とする。
  4. sを ? ToNumber(sec) とする。
  5. msがpresentなら、milliを ? ToNumber(ms) とする。
  6. tvNaNなら、NaNを返す。
  7. msがpresentでないなら、millimsFromTime(tv)とする。
  8. dateMakeDate(Day(tv), MakeTime(HourFromTime(tv), MinFromTime(tv), s, milli))とする。
  9. vTimeClip(date)とする。
  10. dateObj.[[DateValue]]vに設定する。
  11. vを返す。

このmethodの"length" propertyは2𝔽です。

Note

msがpresentでない場合、このmethodはmsがvalue getUTCMilliseconds()でpresentであったかのようにbehaveします。

21.4.4.35 Date.prototype.toDateString ( )

このmethodは呼び出されたとき、次のstepsを実行します:

  1. dateObjthis valueとする。
  2. RequireInternalSlot(dateObj, [[DateValue]])を実行する。
  3. tvdateObj.[[DateValue]]とする。
  4. tvNaNなら、"Invalid Date"を返す。
  5. tLocalTime(tv)とする。
  6. DateString(t)を返す。

21.4.4.36 Date.prototype.toISOString ( )

このmethodは呼び出されたとき、次のstepsを実行します:

  1. dateObjthis valueとする。
  2. RequireInternalSlot(dateObj, [[DateValue]])を実行する。
  3. tvdateObj.[[DateValue]]とする。
  4. tvNaNなら、RangeError例外をthrowする。
  5. Assert: tvintegral Numberである。
  6. tvDate Time String Formatでrepresentできないyearに対応するなら、RangeError例外をthrowする。
  7. UTC time scale上で、すべてのformat elementsおよびUTC offset representation "Z"を含む、Date Time String FormatにおけるtvのString representationを返す。

21.4.4.37 Date.prototype.toJSON ( key )

このmethodは、JSON.stringify25.5.4)による使用のためにDateのString representationを提供します。

これは呼び出されたとき、次のstepsを実行します:

  1. objを ? ToObject(this value) とする。
  2. tvを ? ToPrimitive(obj, number) とする。
  3. tvがNumberであり、かつtvfiniteでないなら、nullを返す。
  4. Invoke(obj, "toISOString")を返す。
Note 1

argumentはignoredされます。

Note 2

このmethodは意図的にgenericです;そのthis valueがDateであることをrequireしません。したがって、methodとして使用するために他の種類のobjectsへtransferできます。ただし、そのようなobjectはtoISOString methodを持つ必要があります。

21.4.4.38 Date.prototype.toLocaleDateString ( [ reserved1 [ , reserved2 ] ] )

ECMA-402 Internationalization APIを含むECMAScript implementationは、このmethodをECMA-402 specificationで指定される通りにimplementしなければなりません。ECMAScript implementationがECMA-402 APIを含まない場合、このmethodの次のspecificationが使用されます:

このmethodはString valueを返します。Stringのcontentsはimplementation-definedですが、host environmentのcurrent localeのconventionsに対応するconvenientでhuman-readableなformで、current time zoneにおけるDateの“date” portionを表すことを意図しています。

このmethodのoptional parametersのmeaningはECMA-402 specificationで定義されます;ECMA-402 supportを含まないimplementationsは、それらのparameter positionsを他の目的に使用してはなりません。

21.4.4.39 Date.prototype.toLocaleString ( [ reserved1 [ , reserved2 ] ] )

ECMA-402 Internationalization APIを含むECMAScript implementationは、このmethodをECMA-402 specificationで指定される通りにimplementしなければなりません。ECMAScript implementationがECMA-402 APIを含まない場合、このmethodの次のspecificationが使用されます:

このmethodはString valueを返します。Stringのcontentsはimplementation-definedですが、host environmentのcurrent localeのconventionsに対応するconvenientでhuman-readableなformで、current time zoneにおけるDateを表すことを意図しています。

このmethodのoptional parametersのmeaningはECMA-402 specificationで定義されます;ECMA-402 supportを含まないimplementationsは、それらのparameter positionsを他の目的に使用してはなりません。

21.4.4.40 Date.prototype.toLocaleTimeString ( [ reserved1 [ , reserved2 ] ] )

ECMA-402 Internationalization APIを含むECMAScript implementationは、このmethodをECMA-402 specificationで指定される通りにimplementしなければなりません。ECMAScript implementationがECMA-402 APIを含まない場合、このmethodの次のspecificationが使用されます:

このmethodはString valueを返します。Stringのcontentsはimplementation-definedですが、host environmentのcurrent localeのconventionsに対応するconvenientでhuman-readableなformで、current time zoneにおけるDateの“time” portionを表すことを意図しています。

このmethodのoptional parametersのmeaningはECMA-402 specificationで定義されます;ECMA-402 supportを含まないimplementationsは、それらのparameter positionsを他の目的に使用してはなりません。

21.4.4.41 Date.prototype.toString ( )

このmethodは呼び出されたとき、次のstepsを実行します:

  1. dateObjthis valueとする。
  2. RequireInternalSlot(dateObj, [[DateValue]])を実行する。
  3. tvdateObj.[[DateValue]]とする。
  4. ToDateString(tv)を返す。
Note 1

d.[[DateValue]]が1000でevenly divisibleである任意のDate dについて、Date.parse(d.toString()) = d.valueOf()のresultになります。21.4.3.2を参照してください。

Note 2

このmethodはgenericではありません;そのthis valueがDateでない場合、TypeError例外をthrowします。したがって、methodとして使用するために他の種類のobjectsへtransferすることはできません。

21.4.4.41.1 TimeString ( tv )

The abstract operation TimeString takes argument tv (a Number, but not NaN) and returns a String. It performs the following steps when called:

  1. hourToZeroPaddedDecimalString((HourFromTime(tv)), 2)とする。
  2. minuteToZeroPaddedDecimalString((MinFromTime(tv)), 2)とする。
  3. secondToZeroPaddedDecimalString((SecFromTime(tv)), 2)とする。
  4. hour":"minute":"second、code unit 0x0020 (SPACE)、および"GMT"string-concatenationを返す。

21.4.4.41.2 DateString ( tv )

The abstract operation DateString takes argument tv (a Number, but not NaN) and returns a String. It performs the following steps when called:

  1. weekdayを、WeekDay(tv)のNumberを持つTable 61内のentryのNameとする。
  2. monthを、MonthFromTime(tv)のNumberを持つTable 62内のentryのNameとする。
  3. dayToZeroPaddedDecimalString((DateFromTime(tv)), 2)とする。
  4. yvYearFromTime(tv)とする。
  5. yv+0𝔽またはyv > +0𝔽なら、yearSignをempty Stringとする;そうでなければ、yearSign"-"とする。
  6. paddedYearToZeroPaddedDecimalString(abs((yv)), 4)とする。
  7. weekday、code unit 0x0020 (SPACE)、month、code unit 0x0020 (SPACE)、day、code unit 0x0020 (SPACE)、yearSign、およびpaddedYearstring-concatenationを返す。
Table 61: Names of days of the week
Number Name
+0𝔽 "Sun"
1𝔽 "Mon"
2𝔽 "Tue"
3𝔽 "Wed"
4𝔽 "Thu"
5𝔽 "Fri"
6𝔽 "Sat"
Table 62: Names of months of the year
Number Name
+0𝔽 "Jan"
1𝔽 "Feb"
2𝔽 "Mar"
3𝔽 "Apr"
4𝔽 "May"
5𝔽 "Jun"
6𝔽 "Jul"
7𝔽 "Aug"
8𝔽 "Sep"
9𝔽 "Oct"
10𝔽 "Nov"
11𝔽 "Dec"

21.4.4.41.3 TimeZoneString ( tv )

The abstract operation TimeZoneString takes argument tv (an integral Number) and returns a String. It performs the following steps when called:

  1. systemTimeZoneIdentifierSystemTimeZoneIdentifier()とする。
  2. IsTimeZoneOffsetString(systemTimeZoneIdentifier)がtrueなら、
    1. offsetNsParseTimeZoneOffsetString(systemTimeZoneIdentifier)とする。
  3. そうでなければ、
    1. offsetNsGetNamedTimeZoneOffsetNanoseconds(systemTimeZoneIdentifier, ((tv) × 106))とする。
  4. offset𝔽(truncate(offsetNs / 106))とする。
  5. offset+0𝔽またはoffset > +0𝔽なら、
    1. offsetSign"+"とする。
    2. absOffsetoffsetとする。
  6. そうでなければ、
    1. offsetSign"-"とする。
    2. absOffsetを-offsetとする。
  7. offsetMinToZeroPaddedDecimalString((MinFromTime(absOffset)), 2)とする。
  8. offsetHourToZeroPaddedDecimalString((HourFromTime(absOffset)), 2)とする。
  9. tzNameを、empty String、またはcode unit 0x0020 (SPACE)、code unit 0x0028 (LEFT PARENTHESIS)、implementation-defined timezone name、およびcode unit 0x0029 (RIGHT PARENTHESIS)のstring-concatenationのいずれかであるimplementation-defined stringとする。
  10. offsetSignoffsetHouroffsetMin、およびtzNamestring-concatenationを返す。

21.4.4.41.4 ToDateString ( tv )

The abstract operation ToDateString takes argument tv (an integral Number or NaN) and returns a String. It performs the following steps when called:

  1. tvNaNなら、"Invalid Date"を返す。
  2. localTimeLocalTime(tv)とする。
  3. DateString(localTime)、code unit 0x0020 (SPACE)、TimeString(localTime)、およびTimeZoneString(tv)のstring-concatenationを返す。

21.4.4.42 Date.prototype.toTimeString ( )

このmethodは呼び出されたとき、次のstepsを実行します:

  1. dateObjthis valueとする。
  2. RequireInternalSlot(dateObj, [[DateValue]])を実行する。
  3. tvdateObj.[[DateValue]]とする。
  4. tvNaNなら、"Invalid Date"を返す。
  5. localTimeLocalTime(tv)とする。
  6. TimeString(localTime)とTimeZoneString(tv)のstring-concatenationを返す。

21.4.4.43 Date.prototype.toUTCString ( )

このmethodは、this valueに対応するinstant in timeを表すString valueを返します。StringのformatはRFC 7231のHTTP-dateに基づき、ECMAScript Datesによってsupportされるfull range of timesをsupportするようgeneralizedされています。

これは呼び出されたとき、次のstepsを実行します:

  1. dateObjthis valueとする。
  2. RequireInternalSlot(dateObj, [[DateValue]])を実行する。
  3. tvdateObj.[[DateValue]]とする。
  4. tvNaNなら、"Invalid Date"を返す。
  5. weekdayを、WeekDay(tv)のNumberを持つTable 61内のentryのNameとする。
  6. monthを、MonthFromTime(tv)のNumberを持つTable 62内のentryのNameとする。
  7. dayToZeroPaddedDecimalString((DateFromTime(tv)), 2)とする。
  8. yvYearFromTime(tv)とする。
  9. yv+0𝔽またはyv > +0𝔽なら、yearSignをempty Stringとする;そうでなければ、yearSign"-"とする。
  10. paddedYearToZeroPaddedDecimalString(abs((yv)), 4)とする。
  11. weekday","、code unit 0x0020 (SPACE)、day、code unit 0x0020 (SPACE)、month、code unit 0x0020 (SPACE)、yearSignpaddedYear、code unit 0x0020 (SPACE)、およびTimeString(tv)のstring-concatenationを返す。

21.4.4.44 Date.prototype.valueOf ( )

このmethodは呼び出されたとき、次のstepsを実行します:

  1. dateObjthis valueとする。
  2. RequireInternalSlot(dateObj, [[DateValue]])を実行する。
  3. dateObj.[[DateValue]]を返す。

21.4.4.45 Date.prototype [ %Symbol.toPrimitive% ] ( hint )

このmethodは、Dateをprimitive valueへconvertするためにECMAScript language operatorsによって呼び出されます。hintにallowedなvaluesは"default""number"、および"string"です。Datesは、"default""string"とequivalentとして扱うという点でbuilt-in ECMAScript objectの中でuniqueです。他のすべてのbuilt-in ECMAScript objectsは"default""number"とequivalentとして扱います。

これは呼び出されたとき、次のstepsを実行します:

  1. objthis valueとする。
  2. objがObjectでないなら、TypeError例外をthrowする。
  3. hint"string"または"default"のいずれかなら、
    1. tryFirststringとする。
  4. そうでなく、hint"number"なら、
    1. tryFirstnumberとする。
  5. そうでなければ、
    1. TypeError例外をThrowする。
  6. OrdinaryToPrimitive(obj, tryFirst)を返す。

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

このmethodの"name" propertyのvalueは"[Symbol.toPrimitive]"です。

21.4.5 Properties of Date Instances

Date instancesは、Date prototype objectからpropertiesをinheritするordinary objectsです。Date instancesはまた[[DateValue]] internal slotを持ちます。[[DateValue]] internal slotは、このDateによって表されるtime valueです。

22 Text Processing

22.1 String Objects

22.1.1 The String Constructor

String constructorは:

  • %String%です。
  • global object"String" propertyのinitial valueです。
  • constructorとして呼び出されたとき、新しいString objectを作成およびinitializeします。
  • constructorとしてではなくfunctionとして呼び出されたとき、type conversionを実行します。
  • class definitionのextends clauseのvalueとして使用できます。指定されたString behaviourをinheritしようとするsubclass constructorsは、[[StringData]] internal slotを持つsubclass instanceを作成およびinitializeするために、String constructorへのsuper callを含まなければなりません。

22.1.1.1 String ( value )

このfunctionは呼び出されたとき、次のstepsを実行します:

  1. valueがpresentでないなら、
    1. stringをempty Stringとする。
  2. そうでなければ、
    1. NewTargetがundefinedであり、かつvalueがSymbolなら、SymbolDescriptiveString(value)を返す。
    2. stringを ? ToString(value) とする。
  3. NewTargetがundefinedなら、stringを返す。
  4. StringCreate(string, ? GetPrototypeFromConstructor(NewTarget, "%String.prototype%"))を返す。

22.1.2 Properties of the String Constructor

String constructorは:

  • valueが%Function.prototype%である[[Prototype]] internal slotを持ちます。
  • 次のpropertiesを持ちます:

22.1.2.1 String.fromCharCode ( ...codeUnits )

このfunctionは、rest parameter codeUnitsを形成する任意の数のargumentsで呼び出すことができます。

これは呼び出されたとき、次のstepsを実行します:

  1. resultをempty Stringとする。
  2. codeUnitsの各要素nextについて、以下を行う
    1. nextCUを、numeric valueが(? ToUint16(next))であるcode unitとする。
    2. resultresultnextCUstring-concatenationに設定する。
  3. resultを返す。

このfunctionの"length" propertyは1𝔽です。

22.1.2.2 String.fromCodePoint ( ...codePoints )

このfunctionは、rest parameter codePointsを形成する任意の数のargumentsで呼び出すことができます。

これは呼び出されたとき、次のstepsを実行します:

  1. resultをempty Stringとする。
  2. codePointsの各要素nextについて、以下を行う
    1. nextCPを ? ToNumber(next) とする。
    2. nextCPintegral Numberでないなら、RangeError例外をthrowする。
    3. (nextCP) < 0または(nextCP) > 0x10FFFFなら、RangeError例外をthrowする。
    4. resultresultUTF16EncodeCodePoint((nextCP))のstring-concatenationに設定する。
  3. Assert: codePointsがemptyなら、resultはempty Stringである。
  4. resultを返す。

このfunctionの"length" propertyは1𝔽です。

22.1.2.3 String.prototype

String.prototypeのinitial valueはString prototype objectです。

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

22.1.2.4 String.raw ( template, ...substitutions )

このfunctionはvariable number of argumentsで呼び出すことができます。first argumentはtemplateであり、remaining argumentsはList substitutionsを形成します。

これは呼び出されたとき、次のstepsを実行します:

  1. substitutionCountsubstitutions内のelementsの数とする。
  2. cookedを ? ToObject(template) とする。
  3. literalsを ? ToObject(? Get(cooked, "raw")) とする。
  4. literalCountを ? LengthOfArrayLike(literals) とする。
  5. literalCount ≤ 0なら、empty Stringを返す。
  6. resultをempty Stringとする。
  7. nextIndexを0とする。
  8. 繰り返す:
    1. nextLiteralValueを ? Get(literals, ! ToString(𝔽(nextIndex))) とする。
    2. nextLiteralを ? ToString(nextLiteralValue) とする。
    3. resultresultnextLiteralstring-concatenationに設定する。
    4. nextIndex + 1 = literalCountなら、resultを返す。
    5. nextIndex < substitutionCountなら、
      1. nextSubValuesubstitutions[nextIndex]とする。
      2. nextSubを ? ToString(nextSubValue) とする。
      3. resultresultnextSubstring-concatenationに設定する。
    6. nextIndexnextIndex + 1に設定する。
Note

このfunctionはTagged Template(13.3.11)のtag functionとして使用することを意図しています。そのように呼び出されたとき、first argumentはwell formed template objectであり、rest parameterはsubstitution valuesを含みます。

22.1.3 Properties of the String Prototype Object

String prototype objectは:

  • %String.prototype%です。
  • String exotic objectであり、そのようなobjectsに対して指定されたinternal methodsを持ちます。
  • valueがempty Stringである[[StringData]] internal slotを持ちます。
  • initial valueが+0𝔽であり、attributesが { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false } である"length" propertyを持ちます。
  • valueが%Object.prototype%である[[Prototype]] internal slotを持ちます。

明示的に別途述べられない限り、以下で定義されるString prototype objectのmethodsはgenericではなく、それらに渡されるthis valueは、String valueであるか、String valueへinitialize済みの[[StringData]] internal slotを持つobjectでなければなりません。

22.1.3.1 String.prototype.at ( index )

  1. thisValuethis valueとする。
  2. RequireObjectCoercible(thisValue)を実行する。
  3. stringを ? ToString(thisValue) とする。
  4. lengthstringのlengthとする。
  5. relativeIndexを ? ToIntegerOrInfinity(index) とする。
  6. relativeIndex ≥ 0なら、
    1. krelativeIndexとする。
  7. そうでなければ、
    1. klength + relativeIndexとする。
  8. k < 0またはklengthなら、undefinedを返す。
  9. stringkからk + 1までのsubstringを返す。

22.1.3.2 String.prototype.charAt ( position )

Note 1

このmethodは、このobjectをStringへconvertしたresultであるString value内のindex positionにあるcode unitを含むsingle element Stringを返します。そのindexにelementが存在しない場合、resultはempty Stringです。resultはString valueであり、String objectではありません。

posintegral Numberである場合、x.charAt(pos)のresultはx.substring(pos, pos + 1)のresultとequivalentです。

このmethodは呼び出されたとき、次のstepsを実行します:

  1. thisValuethis valueとする。
  2. RequireObjectCoercible(thisValue)を実行する。
  3. stringを ? ToString(thisValue) とする。
  4. positionを ? ToIntegerOrInfinity(position) に設定する。
  5. sizestringのlengthとする。
  6. position < 0またはpositionsizeなら、empty Stringを返す。
  7. stringpositionからposition + 1までのsubstringを返す。
Note 2

このmethodは意図的にgenericです;そのthis valueがString objectであることをrequireしません。したがって、methodとして使用するために他の種類のobjectsへtransferできます。

22.1.3.3 String.prototype.charCodeAt ( position )

Note 1

このmethodは、このobjectをStringへconvertしたresultであるString内のindex positionにあるcode unitのnumeric valueであるNumber(216未満のnon-negative integral Number)を返します。そのindexにelementが存在しない場合、resultはNaNです。

このmethodは呼び出されたとき、次のstepsを実行します:

  1. thisValuethis valueとする。
  2. RequireObjectCoercible(thisValue)を実行する。
  3. stringを ? ToString(thisValue) とする。
  4. positionを ? ToIntegerOrInfinity(position) に設定する。
  5. sizestringのlengthとする。
  6. position < 0またはpositionsizeなら、NaNを返す。
  7. String string内のindex positionにあるcode unitのnumeric valueに対するNumber valueを返す。
Note 2

このmethodは意図的にgenericです;そのthis valueがString objectであることをrequireしません。したがって、methodとして使用するために他の種類のobjectsへtransferできます。

22.1.3.4 String.prototype.codePointAt ( position )

Note 1

このmethodは、このobjectをStringへconvertしたresultであるString内のindex positionのstring elementから始まるUTF-16 encoded code point(6.1.4)のnumeric valueである、0x10FFFF𝔽以下のnon-negative integral Numberを返します。そのindexにelementが存在しない場合、resultはundefinedです。valid UTF-16 surrogate pairpositionでbeginしない場合、resultはpositionにあるcode unitです。

このmethodは呼び出されたとき、次のstepsを実行します:

  1. thisValuethis valueとする。
  2. RequireObjectCoercible(thisValue)を実行する。
  3. stringを ? ToString(thisValue) とする。
  4. positionを ? ToIntegerOrInfinity(position) に設定する。
  5. sizestringのlengthとする。
  6. position < 0またはpositionsizeなら、undefinedを返す。
  7. codePointCodePointAt(string, position)とする。
  8. 𝔽(codePoint.[[CodePoint]])を返す。
Note 2

このmethodは意図的にgenericです;そのthis valueがString objectであることをrequireしません。したがって、methodとして使用するために他の種類のobjectsへtransferできます。

22.1.3.5 String.prototype.concat ( ...args )

Note 1

このmethodが呼び出されると、this value(Stringへconvertedされる)のcode unitsに、Stringへconvertedされた各argumentのcode unitsがfollowしたものからなるString valueを返します。resultはString valueであり、String objectではありません。

このmethodは呼び出されたとき、次のstepsを実行します:

  1. thisValuethis valueとする。
  2. RequireObjectCoercible(thisValue)を実行する。
  3. stringを ? ToString(thisValue) とする。
  4. resultstringとする。
  5. argsの各要素nextについて、以下を行う
    1. nextStringを ? ToString(next) とする。
    2. resultresultnextStringstring-concatenationに設定する。
  6. resultを返す。

このmethodの"length" propertyは1𝔽です。

Note 2

このmethodは意図的にgenericです;そのthis valueがString objectであることをrequireしません。したがって、methodとして使用するために他の種類のobjectsへtransferできます。

22.1.3.6 String.prototype.constructor

String.prototype.constructorのinitial valueは%String%です。

22.1.3.7 String.prototype.endsWith ( searchString [ , endPosition ] )

このmethodは呼び出されたとき、次のstepsを実行します:

  1. thisValuethis valueとする。
  2. RequireObjectCoercible(thisValue)を実行する。
  3. stringを ? ToString(thisValue) とする。
  4. isRegexpを ? IsRegExp(searchString) とする。
  5. isRegexptrueなら、TypeError例外をthrowする。
  6. searchStringを ? ToString(searchString) に設定する。
  7. lengthstringのlengthとする。
  8. endPositionundefinedなら、positionlengthとする;そうでなければ、positionを ? ToIntegerOrInfinity(endPosition) とする。
  9. endpositionを0とlengthの間にclampingしたresultとする。
  10. searchLengthsearchStringのlengthとする。
  11. searchLength = 0なら、trueを返す。
  12. startend - searchLengthとする。
  13. start < 0なら、falseを返す。
  14. substringstringstartからendまでのsubstringとする。
  15. substringsearchStringなら、trueを返す。
  16. falseを返す。
Note 1

first argumentがRegExpである場合にexceptionをthrowすることは、そのようなargument valuesをallowするextensionsをfuture editionsがdefineできるようにするために指定されています。

Note 2

このmethodは意図的にgenericです;そのthis valueがString objectであることをrequireしません。したがって、methodとして使用するために他の種類のobjectsへtransferできます。

22.1.3.8 String.prototype.includes ( searchString [ , position ] )

このmethodは呼び出されたとき、次のstepsを実行します:

  1. thisValuethis valueとする。
  2. RequireObjectCoercible(thisValue)を実行する。
  3. stringを ? ToString(thisValue) とする。
  4. isRegexpを ? IsRegExp(searchString) とする。
  5. isRegexptrueなら、TypeError例外をthrowする。
  6. searchStringを ? ToString(searchString) に設定する。
  7. positionIntを ? ToIntegerOrInfinity(position) とする。
  8. Assert: positionundefinedなら、positionIntは0である。
  9. lengthstringのlengthとする。
  10. startpositionIntを0とlengthの間にclampingしたresultとする。
  11. indexStringIndexOf(string, searchString, start)とする。
  12. indexnot-foundなら、falseを返す。
  13. trueを返す。
Note 1

searchStringが、このobjectをStringへconvertしたresultのsubstringとして、position以上である1つ以上のindicesにappearsする場合、このfunctionはtrueを返します;そうでなければfalseを返します。positionundefinedなら、String全体をsearchするために0がassumedされます。

Note 2

first argumentがRegExpである場合にexceptionをthrowすることは、そのようなargument valuesをallowするextensionsをfuture editionsがdefineできるようにするために指定されています。

Note 3

このmethodは意図的にgenericです;そのthis valueがString objectであることをrequireしません。したがって、methodとして使用するために他の種類のobjectsへtransferできます。

22.1.3.9 String.prototype.indexOf ( searchString [ , position ] )

Note 1

searchStringが、このobjectをStringへconvertしたresultのsubstringとして、position以上である1つ以上のindicesにappearsする場合、そのようなsmallest indexが返されます;そうでなければ、-1𝔽が返されます。positionundefinedなら、String全体をsearchするために+0𝔽がassumedされます。

このmethodは呼び出されたとき、次のstepsを実行します:

  1. thisValuethis valueとする。
  2. RequireObjectCoercible(thisValue)を実行する。
  3. stringを ? ToString(thisValue) とする。
  4. searchStringを ? ToString(searchString) に設定する。
  5. positionIntを ? ToIntegerOrInfinity(position) とする。
  6. Assert: positionundefinedなら、positionIntは0である。
  7. lengthstringのlengthとする。
  8. startpositionIntを0とlengthの間にclampingしたresultとする。
  9. resultStringIndexOf(string, searchString, start)とする。
  10. resultnot-foundなら、-1𝔽を返す。
  11. 𝔽(result)を返す。
Note 2

このmethodは意図的にgenericです;そのthis valueがString objectであることをrequireしません。したがって、methodとして使用するために他の種類のobjectsへtransferできます。

22.1.3.10 String.prototype.isWellFormed ( )

このmethodは呼び出されたとき、次のstepsを実行します:

  1. thisValuethis valueとする。
  2. RequireObjectCoercible(thisValue)を実行する。
  3. stringを ? ToString(thisValue) とする。
  4. IsStringWellFormedUnicode(string)を返す。

22.1.3.11 String.prototype.lastIndexOf ( searchString [ , position ] )

Note 1

searchStringが、このobjectをStringへconvertしたresultのsubstringとして、position以下である1つ以上のindicesにappearsする場合、そのようなgreatest indexが返されます;そうでなければ、-1𝔽が返されます。positionundefinedなら、String全体をsearchするためにString valueのlengthがassumedされます。

このmethodは呼び出されたとき、次のstepsを実行します:

  1. thisValuethis valueとする。
  2. RequireObjectCoercible(thisValue)を実行する。
  3. stringを ? ToString(thisValue) とする。
  4. searchStringを ? ToString(searchString) に設定する。
  5. numberPositionを ? ToNumber(position) とする。
  6. Assert: positionundefinedなら、numberPositionNaNである。
  7. numberPositionNaNなら、positionを+∞に設定する;そうでなければ、positionを ! ToIntegerOrInfinity(numberPosition) に設定する。
  8. lengthstringのlengthとする。
  9. searchLengthsearchStringのlengthとする。
  10. length < searchLengthなら、-1𝔽を返す。
  11. startpositionを0とlength - searchLengthの間にclampingしたresultとする。
  12. resultStringLastIndexOf(string, searchString, start)とする。
  13. resultnot-foundなら、-1𝔽を返す。
  14. 𝔽(result)を返す。
Note 2

このmethodは意図的にgenericです;そのthis valueがString objectであることをrequireしません。したがって、methodとして使用するために他の種類のobjectsへtransferできます。

22.1.3.12 String.prototype.localeCompare ( that [ , reserved1 [ , reserved2 ] ] )

ECMA-402 Internationalization APIを含むECMAScript implementationは、このmethodをECMA-402 specificationで指定される通りにimplementしなければなりません。ECMAScript implementationがECMA-402 APIを含まない場合、このmethodの次のspecificationが使用されます:

このmethodは、this value(String stringへconvertedされる)とthat(String thatValueへconvertedされる)とのimplementation-defined locale-sensitive String comparisonのresultを表す、NaN以外のNumberを返します。resultは、host environmentのcurrent localeのconventionsに従ったString valuesのsort orderに対応することを意図しており、stringthatValueより前にorderedされるときnegative、stringthatValueより後にorderedされるときpositive、その他すべての場合にはzero(stringthatValueの間にrelative orderingがないことを表す)になります。

comparisonsを実行する前に、このmethodはStringsをprepareするために次のstepsを実行します:

  1. thisValuethis valueとする。
  2. RequireObjectCoercible(thisValue)を実行する。
  3. stringを ? ToString(thisValue) とする。
  4. thatValueを ? ToString(that) とする。

このmethodのoptional secondおよびthird parametersのmeaningはECMA-402 specificationで定義されます;ECMA-402 supportを含まないimplementationsは、それらのparameter positionsに他のinterpretationをassignしてはなりません。

actual return valuesは、それらにadditional informationをencodingできるようimplementation-definedですが、このmethodは、two argumentsのmethodとしてconsideredされるとき、すべてのStringsのset上でtotal orderingを定義するconsistent comparatorであることがrequiredです。このmethodはまた、Unicode Standardに従うcanonical equivalenceをrecognizeおよびhonourすることがrequiredであり、canonically equivalentなdistinguishable Stringsを比較するときに+0𝔽を返すことを含みます。

Note 1

このmethod自体はArray.prototype.sortへのargumentとして直接適していません。後者はtwo argumentsのfunctionをrequireするためです。

Note 2

このmethodは、ECMAScript environmentがhost environmentから利用できる任意のlanguage- and/or locale-sensitive comparison functionalityにrelyしてもよく、host environmentのcurrent localeのconventionsに従ってcompareすることを意図しています。しかし、comparison capabilitiesにかかわらず、このmethodはUnicode Standardに従うcanonical equivalenceをrecognizeおよびhonourしなければなりません—例えば、以下のcomparisonsはすべて+0𝔽を返さなければなりません:

// Å ANGSTROM SIGN vs.
// Å LATIN CAPITAL LETTER A + COMBINING RING ABOVE
"\u212B".localeCompare("A\u030A")

// Ω OHM SIGN vs.
// Ω GREEK CAPITAL LETTER OMEGA
"\u2126".localeCompare("\u03A9")

// ṩ LATIN SMALL LETTER S WITH DOT BELOW AND DOT ABOVE vs.
// ṩ LATIN SMALL LETTER S + COMBINING DOT ABOVE + COMBINING DOT BELOW
"\u1E69".localeCompare("s\u0307\u0323")

// ḍ̇ LATIN SMALL LETTER D WITH DOT ABOVE + COMBINING DOT BELOW vs.
// ḍ̇ LATIN SMALL LETTER D WITH DOT BELOW + COMBINING DOT ABOVE
"\u1E0B\u0323".localeCompare("\u1E0D\u0307")

// 가 HANGUL CHOSEONG KIYEOK + HANGUL JUNGSEONG A vs.
// 가 HANGUL SYLLABLE GA
"\u1100\u1161".localeCompare("\uAC00")

canonical equivalenceのdefinitionおよびdiscussionについては、Unicode Standardのchapters 2および3に加えて、Unicode Standard Annex #15, Unicode Normalization FormsおよびUnicode Technical Note #5, Canonical Equivalence in Applicationsを参照してください。Unicode Technical Standard #10, Unicode Collation Algorithmも参照してください。

このmethodは、Unicode Standardのchapter 3, section 3.7で定義されるUnicode compatibility equivalentsまたはcompatibility decompositionsをhonourすべきでないことがrecommendedされます。

Note 3

このmethodは意図的にgenericです;そのthis valueがString objectであることをrequireしません。したがって、methodとして使用するために他の種類のobjectsへtransferできます。

22.1.3.13 String.prototype.match ( regexpOrPattern )

このmethodは呼び出されたとき、次のstepsを実行します:

  1. thisValuethis valueとする。
  2. RequireObjectCoercible(thisValue)を実行する。
  3. regexpOrPatternがObjectなら、
    1. matcherを ? GetMethod(regexpOrPattern, %Symbol.match%) とする。
    2. matcherundefinedでないなら、
      1. Call(matcher, regexpOrPattern, « thisValue »)を返す。
  4. stringを ? ToString(thisValue) とする。
  5. regexpを ? RegExpCreate(regexpOrPattern, undefined) とする。
  6. Invoke(regexp, %Symbol.match%, « string »)を返す。
Note

このmethodは意図的にgenericです;そのthis valueがString objectであることをrequireしません。したがって、methodとして使用するために他の種類のobjectsへtransferできます。

22.1.3.14 String.prototype.matchAll ( regexpOrPattern )

このmethodは、this valueを表すStringに対してregexpOrPatternとのregular expression matchを実行し、match resultsをyieldするiteratorを返します。各match resultは、matched portion of the Stringをfirst elementとして含み、その後にcapturing groupsによってmatchedされた任意のportionsが続くArrayです。regular expressionが決してmatchしない場合、返されるiteratorはmatch resultsをyieldしません。

これは呼び出されたとき、次のstepsを実行します:

  1. thisValuethis valueとする。
  2. RequireObjectCoercible(thisValue)を実行する。
  3. regexpOrPatternがObjectなら、
    1. isRegexpを ? IsRegExp(regexpOrPattern) とする。
    2. isRegexptrueなら、
      1. flagsを ? Get(regexpOrPattern, "flags") とする。
      2. RequireObjectCoercible(flags)を実行する。
      3. ToString(flags)が"g"を含まないなら、TypeError例外をthrowする。
    3. matcherを ? GetMethod(regexpOrPattern, %Symbol.matchAll%) とする。
    4. matcherundefinedでないなら、
      1. Call(matcher, regexpOrPattern, « thisValue »)を返す。
  4. stringを ? ToString(thisValue) とする。
  5. regexpを ? RegExpCreate(regexpOrPattern, "g") とする。
  6. Invoke(regexp, %Symbol.matchAll%, « string »)を返す。
Note 1
このmethodは意図的にgenericです;そのthis valueがString objectであることをrequireしません。したがって、methodとして使用するために他の種類のobjectsへtransferできます。
Note 2
String.prototype.splitと同様に、String.prototype.matchAllは通常、そのinputsをmutateせずにactするようにdesignedされています。

22.1.3.15 String.prototype.normalize ( [ form ] )

このmethodは呼び出されたとき、次のstepsを実行します:

  1. thisValuethis valueとする。
  2. RequireObjectCoercible(thisValue)を実行する。
  3. stringを ? ToString(thisValue) とする。
  4. formundefinedなら、form"NFC"に設定する。
  5. そうでなければ、formを ? ToString(form) に設定する。
  6. form"NFC""NFD""NFKC"、または"NFKD"のいずれでもないなら、RangeError例外をthrowする。
  7. normalを、the latest Unicode Standard, Normalization Formsで指定される通り、formによってnamedされたnormalization formへstringをnormalizingしたresultであるString valueとする。
  8. normalを返す。
Note

このmethodは意図的にgenericです;そのthis valueがString objectであることをrequireしません。したがって、methodとして使用するために他の種類のobjectsへtransferできます。

22.1.3.16 String.prototype.padEnd ( maxLength [ , fillString ] )

このmethodは呼び出されたとき、次のstepsを実行します:

  1. thisValuethis valueとする。
  2. RequireObjectCoercible(thisValue)を実行する。
  3. StringPaddingBuiltinsImpl(thisValue, maxLength, fillString, end)を返す。

22.1.3.17 String.prototype.padStart ( maxLength [ , fillString ] )

このmethodは呼び出されたとき、次のstepsを実行します:

  1. thisValuethis valueとする。
  2. RequireObjectCoercible(thisValue)を実行する。
  3. StringPaddingBuiltinsImpl(thisValue, maxLength, fillString, start)を返す。

22.1.3.17.1 StringPaddingBuiltinsImpl ( thisValue, maxLength, fillString, placement )

The abstract operation StringPaddingBuiltinsImpl takes arguments thisValue (an ECMAScript language value), maxLength (an ECMAScript language value), fillString (an ECMAScript language value), and placement (start or end) and returns either a normal completion containing a String or a throw completion. It performs the following steps when called:

  1. stringを ? ToString(thisValue) とする。
  2. intMaxLength(? ToLength(maxLength))とする。
  3. stringLengthstringのlengthとする。
  4. intMaxLengthstringLengthなら、stringを返す。
  5. fillStringundefinedなら、fillStringをcode unit 0x0020 (SPACE)のみからなるString valueに設定する。
  6. そうでなければ、fillStringを ? ToString(fillString) に設定する。
  7. StringPad(string, intMaxLength, fillString, placement)を返す。

22.1.3.17.2 StringPad ( string, maxLength, fillString, placement )

The abstract operation StringPad takes arguments string (a String), maxLength (a non-negative integer), fillString (a String), and placement (start or end) and returns a String. It performs the following steps when called:

  1. stringLengthstringのlengthとする。
  2. maxLengthstringLengthなら、stringを返す。
  3. fillStringがempty Stringなら、stringを返す。
  4. fillLengthmaxLength - stringLengthとする。
  5. truncatedStringFillerを、fillStringのrepeated concatenationsからなり、length fillLengthにtruncatedされたString valueとする。
  6. placementstartなら、truncatedStringFillerstringstring-concatenationを返す。
  7. stringtruncatedStringFillerstring-concatenationを返す。
Note 1

argument maxLengthは、stringのlengthより小さくならないようにclampedされます。

Note 2

argument fillString" "(code unit 0x0020 SPACEからなるString value)をdefaultとします。

22.1.3.17.3 ToZeroPaddedDecimalString ( n, minLength )

The abstract operation ToZeroPaddedDecimalString takes arguments n (a non-negative integer) and minLength (a non-negative integer) and returns a String. It performs the following steps when called:

  1. stringをdecimal numberとしてformattedされたnのString representationとする。
  2. StringPad(string, minLength, "0", start)を返す。

22.1.3.18 String.prototype.repeat ( count )

このmethodは呼び出されたとき、次のstepsを実行します:

  1. thisValuethis valueとする。
  2. RequireObjectCoercible(thisValue)を実行する。
  3. stringを ? ToString(thisValue) とする。
  4. nを ? ToIntegerOrInfinity(count) とする。
  5. n < 0またはn = +∞なら、RangeError例外をthrowする。
  6. n = 0なら、empty Stringを返す。
  7. stringn個のcopiesをappended togetherして作られたString valueを返す。
Note 1

このmethodは、this value(Stringへconvertedされる)のcode unitsがcount回repeatedされたものからなるString valueを作成します。

Note 2

このmethodは意図的にgenericです;そのthis valueがString objectであることをrequireしません。したがって、methodとして使用するために他の種類のobjectsへtransferできます。

22.1.3.19 String.prototype.replace ( searchValue, replaceValue )

このmethodは呼び出されたとき、次のstepsを実行します:

  1. thisValuethis valueとする。
  2. RequireObjectCoercible(thisValue)を実行する。
  3. searchValueがObjectなら、
    1. replacerを ? GetMethod(searchValue, %Symbol.replace%) とする。
    2. replacerundefinedでないなら、
      1. Call(replacer, searchValue, « thisValue, replaceValue »)を返す。
  4. stringを ? ToString(thisValue) とする。
  5. searchStringを ? ToString(searchValue) とする。
  6. functionalReplaceIsCallable(replaceValue)とする。
  7. functionalReplacefalseなら、
    1. replaceValueを ? ToString(replaceValue) に設定する。
  8. searchLengthsearchStringのlengthとする。
  9. positionStringIndexOf(string, searchString, 0)とする。
  10. positionnot-foundなら、stringを返す。
  11. precedingstringの0からpositionまでのsubstringとする。
  12. followingstringposition + searchLengthからのsubstringとする。
  13. functionalReplacetrueなら、
    1. replacementを ? ToString(? Call(replaceValue, undefined, « searchString, 𝔽(position), string »)) とする。
  14. そうでなければ、
    1. Assert: replaceValueはStringである。
    2. capturesを新しい空のListとする。
    3. replacementを ! GetSubstitution(searchString, string, position, captures, undefined, replaceValue) とする。
  15. precedingreplacement、およびfollowingstring-concatenationを返す。
Note

このmethodは意図的にgenericです;そのthis valueがString objectであることをrequireしません。したがって、methodとして使用するために他の種類のobjectsへtransferできます。

22.1.3.19.1 GetSubstitution ( matched, string, position, captures, namedCaptures, replacementTemplate )

The abstract operation GetSubstitution takes arguments matched (a String), string (a String), position (a non-negative integer), captures (a List of either Strings or undefined), namedCaptures (an Object or undefined), and replacementTemplate (a String) and returns either a normal completion containing a String or a throw completion. このabstract operationのpurposesにおいて、decimal digitは0x0030 (DIGIT ZERO)から0x0039 (DIGIT NINE)までのinclusive interval内のcode unitです。 It performs the following steps when called:

  1. stringLengthstringのlengthとする。
  2. Assert: positionstringLengthである。
  3. resultをempty Stringとする。
  4. templateRemainderreplacementTemplateとする。
  5. templateRemainderがempty Stringでない間、繰り返す
    1. NOTE: 以下のstepsはreftemplateRemainderのprefix)をisolateし、refReplacement(そのreplacement)をdetermineし、そのreplacementをresultへappendする。
    2. templateRemainder"$$"で始まるなら、
      1. ref"$$"とする。
      2. refReplacement"$"とする。
    3. そうでなく、templateRemainder"$`"で始まるなら、
      1. ref"$`"とする。
      2. refReplacementstringの0からpositionまでのsubstringとする。
    4. そうでなく、templateRemainder"$&"で始まるなら、
      1. ref"$&"とする。
      2. refReplacementmatchedとする。
    5. そうでなく、templateRemainder"$'"(0x0024 (DOLLAR SIGN) followed by 0x0027 (APOSTROPHE))で始まるなら、
      1. ref"$'"とする。
      2. matchLengthmatchedのlengthとする。
      3. tailPositionposition + matchLengthとする。
      4. refReplacementstringmin(tailPosition, stringLength)からのsubstringとする。
      5. NOTE: このabstract operationが、"exec" propertyがintrinsic %RegExp.prototype.exec%でないobject上の%RegExp.prototype%のintrinsic %Symbol.replace% methodへのcallによってinvokedされた場合にのみ、tailPositionstringLengthを超え得る。
    6. そうでなく、templateRemainder"$"の後に1つ以上のdecimal digitsが続くもので始まるなら、
      1. templateRemainder"$"の後に2つ以上のdecimal digitsが続くもので始まるなら、digitCountを2とする;そうでなければ、digitCountを1とする。
      2. digitstemplateRemainderの1から1 + digitCountまでのsubstringとする。
      3. index(StringToNumber(digits))とする。
      4. Assert: 0 ≤ index ≤ 99である。
      5. captureLengthcaptures内のelementsの数とする。
      6. index > captureLengthかつdigitCount = 2なら、
        1. NOTE: two-digit replacement patternがcapturing groupsのcountを超えるindexをspecifyする場合、それはone-digit replacement patternの後にliteral digitが続くものとして扱われる。
        2. digitCountを1に設定する。
        3. digitsdigitsの0から1までのsubstringに設定する。
        4. index(StringToNumber(digits))に設定する。
      7. reftemplateRemainderの0から1 + digitCountまでのsubstringとする。
      8. 1 ≤ indexcaptureLengthなら、
        1. capturecaptures[index - 1]とする。
        2. captureundefinedなら、
          1. refReplacementをempty Stringとする。
        3. そうでなければ、
          1. refReplacementcaptureとする。
      9. そうでなければ、
        1. refReplacementrefとする。
    7. そうでなく、templateRemainder"$<"で始まるなら、
      1. gtPositionStringIndexOf(templateRemainder, ">", 0)とする。
      2. gtPositionnot-foundまたはnamedCapturesundefinedなら、
        1. ref"$<"とする。
        2. refReplacementrefとする。
      3. そうでなければ、
        1. reftemplateRemainderの0からgtPosition + 1までのsubstringとする。
        2. groupNametemplateRemainderの2からgtPositionまでのsubstringとする。
        3. Assert: namedCapturesはObjectである。
        4. captureを ? Get(namedCaptures, groupName) とする。
        5. captureundefinedなら、
          1. refReplacementをempty Stringとする。
        6. そうでなければ、
          1. refReplacementを ? ToString(capture) とする。
    8. そうでなければ、
      1. reftemplateRemainderの0から1までのsubstringとする。
      2. refReplacementrefとする。
    9. refLengthrefのlengthとする。
    10. templateRemaindertemplateRemainderrefLengthからのsubstringに設定する。
    11. resultresultrefReplacementstring-concatenationに設定する。
  6. resultを返す。

22.1.3.20 String.prototype.replaceAll ( searchValue, replaceValue )

このmethodは呼び出されたとき、次のstepsを実行します:

  1. thisValuethis valueとする。
  2. RequireObjectCoercible(thisValue)を実行する。
  3. searchValueがObjectなら、
    1. isRegexpを ? IsRegExp(searchValue) とする。
    2. isRegexptrueなら、
      1. flagsを ? Get(searchValue, "flags") とする。
      2. RequireObjectCoercible(flags)を実行する。
      3. ToString(flags)が"g"を含まないなら、TypeError例外をthrowする。
    3. replacerを ? GetMethod(searchValue, %Symbol.replace%) とする。
    4. replacerundefinedでないなら、
      1. Call(replacer, searchValue, « thisValue, replaceValue »)を返す。
  4. stringを ? ToString(thisValue) とする。
  5. searchStringを ? ToString(searchValue) とする。
  6. functionalReplaceIsCallable(replaceValue)とする。
  7. functionalReplacefalseなら、
    1. replaceValueを ? ToString(replaceValue) に設定する。
  8. searchLengthsearchStringのlengthとする。
  9. advanceBymax(1, searchLength)とする。
  10. matchPositionsを新しい空のListとする。
  11. positionStringIndexOf(string, searchString, 0)とする。
  12. positionnot-foundでない間、繰り返す
    1. positionmatchPositionsへappendする。
    2. positionStringIndexOf(string, searchString, position + advanceBy)に設定する。
  13. endOfLastMatchを0とする。
  14. resultをempty Stringとする。
  15. matchPositionsの各要素matchPositionについて、以下を行う
    1. preservedstringendOfLastMatchからmatchPositionまでのsubstringとする。
    2. functionalReplacetrueなら、
      1. replacementを ? ToString(? Call(replaceValue, undefined, « searchString, 𝔽(matchPosition), string »)) とする。
    3. そうでなければ、
      1. Assert: replaceValueはStringである。
      2. capturesを新しい空のListとする。
      3. replacementを ! GetSubstitution(searchString, string, matchPosition, captures, undefined, replaceValue) とする。
    4. resultresultpreserved、およびreplacementstring-concatenationに設定する。
    5. endOfLastMatchmatchPosition + searchLengthに設定する。
  16. endOfLastMatch < stringのlengthなら、
    1. resultresultstringendOfLastMatchからのsubstringstring-concatenationに設定する。
  17. resultを返す。

22.1.3.21 String.prototype.search ( regexpOrPattern )

このmethodは呼び出されたとき、次のstepsを実行します:

  1. thisValuethis valueとする。
  2. RequireObjectCoercible(thisValue)を実行する。
  3. regexpOrPatternがObjectなら、
    1. searcherを ? GetMethod(regexpOrPattern, %Symbol.search%) とする。
    2. searcherundefinedでないなら、
      1. Call(searcher, regexpOrPattern, « thisValue »)を返す。
  4. stringを ? ToString(thisValue) とする。
  5. regexpを ? RegExpCreate(regexpOrPattern, undefined) とする。
  6. Invoke(regexp, %Symbol.search%, « string »)を返す。
Note

このmethodは意図的にgenericです;そのthis valueがString objectであることをrequireしません。したがって、methodとして使用するために他の種類のobjectsへtransferできます。

22.1.3.22 String.prototype.slice ( start, end )

このmethodは、このobjectをStringへconvertしたresultのsubstringを返します。これはindex startから始まり、index endまで(ただしendを含まない)runningします(またはendundefinedならStringのendまで)。startがnegativeなら、sourceLengthをStringのlengthとして、sourceLength + startとして扱われます。endがnegativeなら、sourceLengthをStringのlengthとして、sourceLength + endとして扱われます。resultはString valueであり、String objectではありません。

これは呼び出されたとき、次のstepsを実行します:

  1. thisValuethis valueとする。
  2. RequireObjectCoercible(thisValue)を実行する。
  3. stringを ? ToString(thisValue) とする。
  4. lengthstringのlengthとする。
  5. intStartを ? ToIntegerOrInfinity(start) とする。
  6. intStart = -∞なら、fromを0とする。
  7. そうでなく、intStart < 0なら、frommax(length + intStart, 0)とする。
  8. そうでなければ、frommin(intStart, length)とする。
  9. endundefinedなら、intEndlengthとする;そうでなければ、intEndを ? ToIntegerOrInfinity(end) とする。
  10. intEnd = -∞なら、toを0とする。
  11. そうでなく、intEnd < 0なら、tomax(length + intEnd, 0)とする。
  12. そうでなければ、tomin(intEnd, length)とする。
  13. fromtoなら、empty Stringを返す。
  14. stringfromからtoまでのsubstringを返す。
Note

このmethodは意図的にgenericです;そのthis valueがString objectであることをrequireしません。したがって、methodとして使用するために他の種類のobjectsへtransferできます。

22.1.3.23 String.prototype.split ( separator, limit )

このmethodは、このobjectをStringへconvertしたresultのsubstringsが格納されたArrayを返します。substringsは、separatorのoccurrencesをleft to rightにsearchすることによってdetermineされます;これらのoccurrencesはreturned array内のいかなるStringのpartでもありませんが、String valueをdivide upする役割を果たします。separatorのvalueは任意のlengthのStringであってもよく、またはRegExpのように%Symbol.split% methodを持つobjectであってもよいです。

これは呼び出されたとき、次のstepsを実行します:

  1. thisValuethis valueとする。
  2. RequireObjectCoercible(thisValue)を実行する。
  3. separatorがObjectなら、
    1. splitterを ? GetMethod(separator, %Symbol.split%) とする。
    2. splitterundefinedでないなら、
      1. Call(splitter, separator, « thisValue, limit »)を返す。
  4. stringを ? ToString(thisValue) とする。
  5. limitundefinedなら、limを232 - 1とする;そうでなければ、lim(? ToUint32(limit))とする。
  6. separatorStringを ? ToString(separator) とする。
  7. lim = 0なら、
    1. CreateArrayFromList(« »)を返す。
  8. separatorundefinedなら、
    1. CreateArrayFromListstring »)を返す。
  9. separatorLengthseparatorStringのlengthとする。
  10. separatorLength = 0なら、
    1. stringLengthstringのlengthとする。
    2. outLengthlimを0とstringLengthの間にclampingしたresultとする。
    3. headstringの0からoutLengthまでのsubstringとする。
    4. codeUnitsを、headのelementsであるcode unitsのsequenceからなるListとする。
    5. CreateArrayFromList(codeUnits)を返す。
  11. stringがempty Stringなら、CreateArrayFromListstring »)を返す。
  12. substringsを新しい空のListとする。
  13. searchStartを0とする。
  14. matchIndexStringIndexOf(string, separatorString, 0)とする。
  15. matchIndexnot-foundでない間、繰り返す
    1. substringstringsearchStartからmatchIndexまでのsubstringとする。
    2. substringsubstringsへappendする。
    3. substrings内のelementsの数がlimなら、CreateArrayFromList(substrings)を返す。
    4. searchStartmatchIndex + separatorLengthに設定する。
    5. matchIndexStringIndexOf(string, separatorString, searchStart)に設定する。
  16. substringstringsearchStartからのsubstringとする。
  17. substringsubstringsへappendする。
  18. CreateArrayFromList(substrings)を返す。
Note 1

separatorのvalueはempty Stringであってもよいです。この場合、separatorはinput Stringのbeginningまたはendにあるempty substringにはmatchせず、previous separator matchのendにあるempty substringにもmatchしません。separatorがempty Stringである場合、Stringはindividual code unit elementsへsplit upされます;result arrayのlengthはStringのlengthに等しく、各substringはone code unitを含みます。

this valueがempty Stringである(またはそれへconvertsされる)場合、resultはseparatorがempty Stringにmatchできるかどうかに依存します。matchできる場合、result arrayはelementsを含みません。そうでなければ、result arrayはone elementを含み、それはempty Stringです。

separatorundefinedである場合、result arrayはthis value(Stringへconvertedされる)であるone Stringだけを含みます。limitundefinedでない場合、output arrayはlimit elements以下を含むようにtruncatedされます。

Note 2

このmethodは意図的にgenericです;そのthis valueがString objectであることをrequireしません。したがって、methodとして使用するために他の種類のobjectsへtransferできます。

22.1.3.24 String.prototype.startsWith ( searchString [ , position ] )

このmethodは呼び出されたとき、次のstepsを実行します:

  1. thisValuethis valueとする。
  2. RequireObjectCoercible(thisValue)を実行する。
  3. stringを ? ToString(thisValue) とする。
  4. isRegexpを ? IsRegExp(searchString) とする。
  5. isRegexptrueなら、TypeError例外をthrowする。
  6. searchStringを ? ToString(searchString) に設定する。
  7. lengthstringのlengthとする。
  8. positionundefinedなら、positionを0に設定する;そうでなければ、positionを ? ToIntegerOrInfinity(position) に設定する。
  9. startpositionを0とlengthの間にclampingしたresultとする。
  10. searchLengthsearchStringのlengthとする。
  11. searchLength = 0なら、trueを返す。
  12. endstart + searchLengthとする。
  13. end > lengthなら、falseを返す。
  14. substringstringstartからendまでのsubstringとする。
  15. substringsearchStringなら、trueを返す。
  16. falseを返す。
Note 1

first argumentがRegExpである場合にexceptionをthrowすることは、そのようなargument valuesをallowするextensionsをfuture editionsがdefineできるようにするために指定されています。

Note 2

このmethodは意図的にgenericです;そのthis valueがString objectであることをrequireしません。したがって、methodとして使用するために他の種類のobjectsへtransferできます。

22.1.3.25 String.prototype.substring ( start, end )

このmethodは、このobjectをStringへconvertしたresultのsubstringを返します。これはindex startから始まり、Stringのindex endまで(ただしendを含まない)runningします(またはendundefinedならStringのendまで)。resultはString valueであり、String objectではありません。

いずれかのargumentがNaNまたはnegativeである場合、それはzeroで置き換えられます;いずれかのargumentがStringのlengthよりstrictly greaterである場合、それはStringのlengthで置き換えられます。

startendよりstrictly greaterである場合、それらはswappedされます。

これは呼び出されたとき、次のstepsを実行します:

  1. thisValuethis valueとする。
  2. RequireObjectCoercible(thisValue)を実行する。
  3. stringを ? ToString(thisValue) とする。
  4. lengthstringのlengthとする。
  5. intStartを ? ToIntegerOrInfinity(start) とする。
  6. endundefinedなら、intEndlengthとする;そうでなければ、intEndを ? ToIntegerOrInfinity(end) とする。
  7. finalStartintStartを0とlengthの間にclampingしたresultとする。
  8. finalEndintEndを0とlengthの間にclampingしたresultとする。
  9. frommin(finalStart, finalEnd)とする。
  10. tomax(finalStart, finalEnd)とする。
  11. stringfromからtoまでのsubstringを返す。
Note

このmethodは意図的にgenericです;そのthis valueがString objectであることをrequireしません。したがって、methodとして使用するために他の種類のobjectsへtransferできます。

22.1.3.26 String.prototype.toLocaleLowerCase ( [ reserved1 [ , reserved2 ] ] )

ECMA-402 Internationalization APIを含むECMAScript implementationは、このmethodをECMA-402 specificationで指定される通りにimplementしなければなりません。ECMAScript implementationがECMA-402 APIを含まない場合、このmethodの次のspecificationが使用されます:

このmethodは、6.1.4でdescribedされる通り、String valueをUTF-16 encoded code pointsのsequenceとしてinterpretします。

toLowerCaseとexactly the sameに動作しますが、host environmentのcurrent localeのconventionsに対応するlocale-sensitive resultをyieldすることを意図している点が異なります。regular Unicode case mappingsとそのlanguageのrulesがconflictする少数のcases(Turkishなど)にのみdifferenceが生じます。

このmethodのoptional parametersのmeaningはECMA-402 specificationで定義されます;ECMA-402 supportを含まないimplementationsは、それらのparameter positionsを他の目的に使用してはなりません。

Note

このmethodは意図的にgenericです;そのthis valueがString objectであることをrequireしません。したがって、methodとして使用するために他の種類のobjectsへtransferできます。

22.1.3.27 String.prototype.toLocaleUpperCase ( [ reserved1 [ , reserved2 ] ] )

ECMA-402 Internationalization APIを含むECMAScript implementationは、このmethodをECMA-402 specificationで指定される通りにimplementしなければなりません。ECMAScript implementationがECMA-402 APIを含まない場合、このmethodの次のspecificationが使用されます:

このmethodは、6.1.4でdescribedされる通り、String valueをUTF-16 encoded code pointsのsequenceとしてinterpretします。

toUpperCaseとexactly the sameに動作しますが、host environmentのcurrent localeのconventionsに対応するlocale-sensitive resultをyieldすることを意図している点が異なります。regular Unicode case mappingsとそのlanguageのrulesがconflictする少数のcases(Turkishなど)にのみdifferenceが生じます。

このmethodのoptional parametersのmeaningはECMA-402 specificationで定義されます;ECMA-402 supportを含まないimplementationsは、それらのparameter positionsを他の目的に使用してはなりません。

Note

このmethodは意図的にgenericです;そのthis valueがString objectであることをrequireしません。したがって、methodとして使用するために他の種類のobjectsへtransferできます。

22.1.3.28 String.prototype.toLowerCase ( )

このmethodは、6.1.4でdescribedされる通り、String valueをUTF-16 encoded code pointsのsequenceとしてinterpretします。

これは呼び出されたとき、次のstepsを実行します:

  1. thisValuethis valueとする。
  2. RequireObjectCoercible(thisValue)を実行する。
  3. stringを ? ToString(thisValue) とする。
  4. sTextStringToCodePoints(string)とする。
  5. lowerTextを、Unicode Default Case Conversion algorithmに従うtoLowercase(sText)とする。
  6. lowercaseStringCodePointsToString(lowerText)とする。
  7. lowercaseStringを返す。

resultは、Unicode Character Database内のlocale-insensitive case mappingsに従ってderivedされなければなりません(これは明示的にfile UnicodeData.txtだけでなく、それにaccompaniesするfile SpecialCasing.txt内のすべてのlocale-insensitive mappingsも含みます)。

Note 1

一部のcode pointsのcase mappingはmultiple code pointsをproduceする場合があります。この場合、result Stringはsource Stringとsame lengthでないことがあります。toUpperCasetoLowerCaseの両方がcontext-sensitive behaviourを持つため、methodsはsymmetricalではありません。言い換えると、s.toUpperCase().toLowerCase()は必ずしもs.toLowerCase()にequalではありません。

Note 2

このmethodは意図的にgenericです;そのthis valueがString objectであることをrequireしません。したがって、methodとして使用するために他の種類のobjectsへtransferできます。

22.1.3.29 String.prototype.toString ( )

このmethodは呼び出されたとき、次のstepsを実行します:

  1. ThisStringValue(this value)を返す。
Note

String objectについて、このmethodはvalueOf methodとsame thingを返すことになります。

22.1.3.30 String.prototype.toUpperCase ( )

このmethodは、6.1.4でdescribedされる通り、String valueをUTF-16 encoded code pointsのsequenceとしてinterpretします。

StringがUnicode Default Case ConversionのtoUppercase algorithmを使用してmappedされる点を除き、String.prototype.toLowerCaseとexactly the same wayにbehaveします。

Note

このmethodは意図的にgenericです;そのthis valueがString objectであることをrequireしません。したがって、methodとして使用するために他の種類のobjectsへtransferできます。

22.1.3.31 String.prototype.toWellFormed ( )

このmethodは、surrogate pairのpartではないすべてのleading surrogatesおよびtrailing surrogatesがU+FFFD (REPLACEMENT CHARACTER)で置き換えられた、このobjectのString representationを返します。

これは呼び出されたとき、次のstepsを実行します:

  1. thisValuethis valueとする。
  2. RequireObjectCoercible(thisValue)を実行する。
  3. stringを ? ToString(thisValue) とする。
  4. stringLengthstringのlengthとする。
  5. kを0とする。
  6. resultをempty Stringとする。
  7. k < stringLengthの間、繰り返す
    1. codePointCodePointAt(string, k)とする。
    2. codePoint.[[IsUnpairedSurrogate]]trueなら、
      1. resultresultと0xFFFD (REPLACEMENT CHARACTER)のstring-concatenationに設定する。
    3. そうでなければ、
      1. resultresultUTF16EncodeCodePoint(codePoint.[[CodePoint]])のstring-concatenationに設定する。
    4. kk + codePoint.[[CodeUnitCount]]に設定する。
  8. resultを返す。

22.1.3.32 String.prototype.trim ( )

このmethodは、6.1.4でdescribedされる通り、String valueをUTF-16 encoded code pointsのsequenceとしてinterpretします。

これは呼び出されたとき、次のstepsを実行します:

  1. thisValuethis valueとする。
  2. TrimString(thisValue, start+end)を返す。
Note

このmethodは意図的にgenericです;そのthis valueがString objectであることをrequireしません。したがって、methodとして使用するために他の種類のobjectsへtransferできます。

22.1.3.32.1 TrimString ( arg, where )

The abstract operation TrimString takes arguments arg (an ECMAScript language value) and where (start, end, or start+end) and returns either a normal completion containing a String or a throw completion. 6.1.4でdescribedされる通り、argをUTF-16 encoded code pointsのsequenceとしてinterpretします。 It performs the following steps when called:

  1. RequireObjectCoercible(arg)を実行する。
  2. stringを ? ToString(arg) とする。
  3. wherestartなら、
    1. trimmedStringを、stringからleading white spaceがremovedされたcopyであるString valueとする。
  4. そうでなく、whereendなら、
    1. trimmedStringを、stringからtrailing white spaceがremovedされたcopyであるString valueとする。
  5. そうでなければ、
    1. Assert: wherestart+endである。
    2. trimmedStringを、stringからleadingおよびtrailing white spaceの両方がremovedされたcopyであるString valueとする。
  6. trimmedStringを返す。

white spaceのdefinitionはWhiteSpaceLineTerminatorのunionです。Unicode code pointがUnicode general category “Space_Separator” (“Zs”)に属するかどうかをdetermineするとき、code unit sequencesは6.1.4で指定される通り、UTF-16 encoded code point sequencesとしてinterpretedされます。

22.1.3.33 String.prototype.trimEnd ( )

このmethodは、6.1.4でdescribedされる通り、String valueをUTF-16 encoded code pointsのsequenceとしてinterpretします。

これは呼び出されたとき、次のstepsを実行します:

  1. stringthis valueとする。
  2. TrimString(string, end)を返す。
Note

このmethodは意図的にgenericです;そのthis valueがString objectであることをrequireしません。したがって、methodとして使用するために他の種類のobjectsへtransferできます。

22.1.3.34 String.prototype.trimStart ( )

このmethodは、6.1.4でdescribedされる通り、String valueをUTF-16 encoded code pointsのsequenceとしてinterpretします。

これは呼び出されたとき、次のstepsを実行します:

  1. stringthis valueとする。
  2. TrimString(string, start)を返す。
Note

このmethodは意図的にgenericです;そのthis valueがString objectであることをrequireしません。したがって、methodとして使用するために他の種類のobjectsへtransferできます。

22.1.3.35 String.prototype.valueOf ( )

このmethodは呼び出されたとき、次のstepsを実行します:

  1. ThisStringValue(this value)を返す。

22.1.3.35.1 ThisStringValue ( arg )

The abstract operation ThisStringValue takes argument arg (an ECMAScript language value) and returns either a normal completion containing a String or a throw completion. It performs the following steps when called:

  1. argがStringなら、argを返す。
  2. argがObjectであり、かつarg[[StringData]] internal slotを持つなら、
    1. stringarg.[[StringData]]とする。
    2. Assert: stringはStringである。
    3. stringを返す。
  3. TypeError例外をThrowする。

22.1.3.36 String.prototype [ %Symbol.iterator% ] ( )

このmethodは、String valueのcode pointsをiterateし、各code pointをString valueとしてreturnするiterator objectを返します。

これは呼び出されたとき、次のstepsを実行します:

  1. stringthis valueとする。
  2. RequireObjectCoercible(string)を実行する。
  3. stringを ? ToString(string) に設定する。
  4. closureを、stringをcaptureし、呼び出されたとき次のstepsを実行する、parametersを持たない新しいAbstract Closureとする:
    1. lengthstringのlengthとする。
    2. positionを0とする。
    3. position < lengthの間、繰り返す
      1. codePointCodePointAt(string, position)とする。
      2. nextIndexposition + codePoint.[[CodeUnitCount]]とする。
      3. resultStringstringpositionからnextIndexまでのsubstringとする。
      4. positionnextIndexに設定する。
      5. GeneratorYield(CreateIteratorResultObject(resultString, false))を実行する。
    4. NormalCompletion(unused)を返す。
  5. CreateIteratorFromClosure(closure, "%StringIteratorPrototype%", %StringIteratorPrototype%)を返す。

このmethodの"name" propertyのvalueは"[Symbol.iterator]"です。

22.1.4 Properties of String Instances

String instancesはString exotic objectsであり、そのようなobjectsに対して指定されたinternal methodsを持ちます。String instancesはString prototype objectからpropertiesをinheritします。String instancesはまた[[StringData]] internal slotを持ちます。[[StringData]] internal slotは、このString objectによって表されるString valueです。

String instancesは"length" property、およびinteger-indexed namesを持つenumerable propertiesのsetを持ちます。

22.1.4.1 length

このString objectによって表されるString value内のelementsの数。

String objectがinitializeされると、このpropertyはunchangingです。これはattributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }を持ちます。

22.1.5 String Iterator Objects

String Iteratorは、特定のString instance objectに対するspecific iterationを表すobjectです。String Iterator objectsにはnamed constructorは存在しません。代わりに、String Iterator objectsはString instance objectsの特定のmethodsを呼び出すことで作成されます。

22.1.5.1 The %StringIteratorPrototype% Object

%StringIteratorPrototype% objectは:

22.1.5.1.1 %StringIteratorPrototype%.next ( )

  1. GeneratorResume(this value, empty, "%StringIteratorPrototype%")を返す。

22.1.5.1.2 %StringIteratorPrototype% [ %Symbol.toStringTag% ]

%Symbol.toStringTag% propertyのinitial valueはString value "String Iterator"です。

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

22.2 RegExp(Regular Expression)Objects

RegExp objectはregular expressionおよびassociated flagsを含みます。

Note

regular expressionsのformおよびfunctionalityは、Perl 5 programming languageのregular expression facilityをmodelにしています。

22.2.1 Patterns

RegExp constructorは、input pattern Stringに対して以下のgrammarを適用します。grammarがStringをPatternのexpansionとしてinterpretできない場合、errorが発生します。

Syntax

Pattern[UnicodeMode, UnicodeSetsMode, NamedCaptureGroups] :: Disjunction[?UnicodeMode, ?UnicodeSetsMode, ?NamedCaptureGroups] Disjunction[UnicodeMode, UnicodeSetsMode, NamedCaptureGroups] :: Alternative[?UnicodeMode, ?UnicodeSetsMode, ?NamedCaptureGroups] Alternative[?UnicodeMode, ?UnicodeSetsMode, ?NamedCaptureGroups] | Disjunction[?UnicodeMode, ?UnicodeSetsMode, ?NamedCaptureGroups] Alternative[UnicodeMode, UnicodeSetsMode, NamedCaptureGroups] :: [empty] Alternative[?UnicodeMode, ?UnicodeSetsMode, ?NamedCaptureGroups] Term[?UnicodeMode, ?UnicodeSetsMode, ?NamedCaptureGroups] Term[UnicodeMode, UnicodeSetsMode, NamedCaptureGroups] :: Assertion[?UnicodeMode, ?UnicodeSetsMode, ?NamedCaptureGroups] Atom[?UnicodeMode, ?UnicodeSetsMode, ?NamedCaptureGroups] Atom[?UnicodeMode, ?UnicodeSetsMode, ?NamedCaptureGroups] Quantifier Assertion[UnicodeMode, UnicodeSetsMode, NamedCaptureGroups] :: ^ $ \b \B (?= Disjunction[?UnicodeMode, ?UnicodeSetsMode, ?NamedCaptureGroups] ) (?! Disjunction[?UnicodeMode, ?UnicodeSetsMode, ?NamedCaptureGroups] ) (?<= Disjunction[?UnicodeMode, ?UnicodeSetsMode, ?NamedCaptureGroups] ) (?<! Disjunction[?UnicodeMode, ?UnicodeSetsMode, ?NamedCaptureGroups] ) Quantifier :: QuantifierPrefix QuantifierPrefix ? QuantifierPrefix :: * + ? { DecimalDigits[~Sep] } { DecimalDigits[~Sep] ,} { DecimalDigits[~Sep] , DecimalDigits[~Sep] } Atom[UnicodeMode, UnicodeSetsMode, NamedCaptureGroups] :: PatternCharacter . \ AtomEscape[?UnicodeMode, ?NamedCaptureGroups] CharacterClass[?UnicodeMode, ?UnicodeSetsMode] ( GroupSpecifier[?UnicodeMode]opt Disjunction[?UnicodeMode, ?UnicodeSetsMode, ?NamedCaptureGroups] ) (? RegularExpressionModifiers : Disjunction[?UnicodeMode, ?UnicodeSetsMode, ?NamedCaptureGroups] ) (? RegularExpressionModifiers - RegularExpressionModifiers : Disjunction[?UnicodeMode, ?UnicodeSetsMode, ?NamedCaptureGroups] ) RegularExpressionModifiers :: [empty] RegularExpressionModifiers RegularExpressionModifier RegularExpressionModifier :: one of i m s SyntaxCharacter :: one of ^ $ \ . * + ? ( ) [ ] { } | PatternCharacter :: SourceCharacter but not SyntaxCharacter AtomEscape[UnicodeMode, NamedCaptureGroups] :: DecimalEscape CharacterClassEscape[?UnicodeMode] CharacterEscape[?UnicodeMode] [+NamedCaptureGroups] k GroupName[?UnicodeMode] CharacterEscape[UnicodeMode] :: ControlEscape c AsciiLetter 0 [lookahead ∉ DecimalDigit] HexEscapeSequence RegExpUnicodeEscapeSequence[?UnicodeMode] IdentityEscape[?UnicodeMode] ControlEscape :: one of f n r t v GroupSpecifier[UnicodeMode] :: ? GroupName[?UnicodeMode] GroupName[UnicodeMode] :: < RegExpIdentifierName[?UnicodeMode] > RegExpIdentifierName[UnicodeMode] :: RegExpIdentifierStart[?UnicodeMode] RegExpIdentifierName[?UnicodeMode] RegExpIdentifierPart[?UnicodeMode] RegExpIdentifierStart[UnicodeMode] :: IdentifierStartChar \ RegExpUnicodeEscapeSequence[+UnicodeMode] [~UnicodeMode] UnicodeLeadSurrogate UnicodeTrailSurrogate RegExpIdentifierPart[UnicodeMode] :: IdentifierPartChar \ RegExpUnicodeEscapeSequence[+UnicodeMode] [~UnicodeMode] UnicodeLeadSurrogate UnicodeTrailSurrogate RegExpUnicodeEscapeSequence[UnicodeMode] :: [+UnicodeMode] u HexLeadSurrogate \u HexTrailSurrogate [+UnicodeMode] u HexLeadSurrogate [+UnicodeMode] u HexTrailSurrogate [+UnicodeMode] u HexNonSurrogate [~UnicodeMode] u Hex4Digits [+UnicodeMode] u{ CodePoint } UnicodeLeadSurrogate :: any Unicode code point in the inclusive interval from U+D800 to U+DBFF UnicodeTrailSurrogate :: any Unicode code point in the inclusive interval from U+DC00 to U+DFFF

associatedするu HexLeadSurrogateのchoiceがambiguousである各\u HexTrailSurrogateは、そうでなければ対応する\u HexTrailSurrogateを持たない、nearest possibleなu HexLeadSurrogateにassociatedされなければなりません。

HexLeadSurrogate :: Hex4Digits but only if the MV of Hex4Digits is in the inclusive interval from 0xD800 to 0xDBFF HexTrailSurrogate :: Hex4Digits but only if the MV of Hex4Digits is in the inclusive interval from 0xDC00 to 0xDFFF HexNonSurrogate :: Hex4Digits but only if the MV of Hex4Digits is not in the inclusive interval from 0xD800 to 0xDFFF IdentityEscape[UnicodeMode] :: [+UnicodeMode] SyntaxCharacter [+UnicodeMode] / [~UnicodeMode] SourceCharacter but not UnicodeIDContinue DecimalEscape :: NonZeroDigit DecimalDigits[~Sep]opt [lookahead ∉ DecimalDigit] CharacterClassEscape[UnicodeMode] :: d D s S w W [+UnicodeMode] p{ UnicodePropertyValueExpression } [+UnicodeMode] P{ UnicodePropertyValueExpression } UnicodePropertyValueExpression :: UnicodePropertyName = UnicodePropertyValue LoneUnicodePropertyNameOrValue UnicodePropertyName :: UnicodePropertyNameCharacters UnicodePropertyNameCharacters :: UnicodePropertyNameCharacter UnicodePropertyNameCharactersopt UnicodePropertyValue :: UnicodePropertyValueCharacters LoneUnicodePropertyNameOrValue :: UnicodePropertyValueCharacters UnicodePropertyValueCharacters :: UnicodePropertyValueCharacter UnicodePropertyValueCharactersopt UnicodePropertyValueCharacter :: UnicodePropertyNameCharacter DecimalDigit UnicodePropertyNameCharacter :: AsciiLetter _ CharacterClass[UnicodeMode, UnicodeSetsMode] :: [ [lookahead ≠ ^] ClassContents[?UnicodeMode, ?UnicodeSetsMode] ] [^ ClassContents[?UnicodeMode, ?UnicodeSetsMode] ] ClassContents[UnicodeMode, UnicodeSetsMode] :: [empty] [~UnicodeSetsMode] NonemptyClassRanges[?UnicodeMode] [+UnicodeSetsMode] ClassSetExpression NonemptyClassRanges[UnicodeMode] :: ClassAtom[?UnicodeMode] ClassAtom[?UnicodeMode] NonemptyClassRangesNoDash[?UnicodeMode] ClassAtom[?UnicodeMode] - ClassAtom[?UnicodeMode] ClassContents[?UnicodeMode, ~UnicodeSetsMode] NonemptyClassRangesNoDash[UnicodeMode] :: ClassAtom[?UnicodeMode] ClassAtomNoDash[?UnicodeMode] NonemptyClassRangesNoDash[?UnicodeMode] ClassAtomNoDash[?UnicodeMode] - ClassAtom[?UnicodeMode] ClassContents[?UnicodeMode, ~UnicodeSetsMode] ClassAtom[UnicodeMode] :: - ClassAtomNoDash[?UnicodeMode] ClassAtomNoDash[UnicodeMode] :: SourceCharacter but not one of \ or ] or - \ ClassEscape[?UnicodeMode] ClassEscape[UnicodeMode] :: b [+UnicodeMode] - CharacterClassEscape[?UnicodeMode] CharacterEscape[?UnicodeMode] ClassSetExpression :: ClassUnion ClassIntersection ClassSubtraction ClassUnion :: ClassSetRange ClassUnionopt ClassSetOperand ClassUnionopt ClassIntersection :: ClassSetOperand && [lookahead ≠ &] ClassSetOperand ClassIntersection && [lookahead ≠ &] ClassSetOperand ClassSubtraction :: ClassSetOperand -- ClassSetOperand ClassSubtraction -- ClassSetOperand ClassSetRange :: ClassSetCharacter - ClassSetCharacter ClassSetOperand :: NestedClass ClassStringDisjunction ClassSetCharacter NestedClass :: [ [lookahead ≠ ^] ClassContents[+UnicodeMode, +UnicodeSetsMode] ] [^ ClassContents[+UnicodeMode, +UnicodeSetsMode] ] \ CharacterClassEscape[+UnicodeMode] Note 1

ここでの最初の2行はCharacterClassとequivalentです。

ClassStringDisjunction :: \q{ ClassStringDisjunctionContents } ClassStringDisjunctionContents :: ClassString ClassString | ClassStringDisjunctionContents ClassString :: [empty] NonEmptyClassString NonEmptyClassString :: ClassSetCharacter NonEmptyClassStringopt ClassSetCharacter :: [lookahead ∉ ClassSetReservedDoublePunctuator] SourceCharacter but not ClassSetSyntaxCharacter \ CharacterEscape[+UnicodeMode] \ ClassSetReservedPunctuator \b ClassSetReservedDoublePunctuator :: one of && !! ## $$ %% ** ++ ,, .. :: ;; << == >> ?? @@ ^^ `` ~~ ClassSetSyntaxCharacter :: one of ( ) [ ] { } / - \ | ClassSetReservedPunctuator :: one of & - ! # % , : ; < = > @ ` ~ Note 2

このsection内のいくつかのproductionsには、section B.1.2でalternative definitionsが与えられています。

22.2.1.1 Static Semantics: Early Errors

Note

このsectionはB.1.2.1でamendedされます。

Pattern :: Disjunction QuantifierPrefix :: { DecimalDigits , DecimalDigits } Atom :: (? RegularExpressionModifiers : Disjunction ) Atom :: (? RegularExpressionModifiers - RegularExpressionModifiers : Disjunction ) AtomEscape :: k GroupName AtomEscape :: DecimalEscape NonemptyClassRanges :: ClassAtom - ClassAtom ClassContents NonemptyClassRangesNoDash :: ClassAtomNoDash - ClassAtom ClassContents RegExpIdentifierStart :: \ RegExpUnicodeEscapeSequence RegExpIdentifierStart :: UnicodeLeadSurrogate UnicodeTrailSurrogate RegExpIdentifierPart :: \ RegExpUnicodeEscapeSequence RegExpIdentifierPart :: UnicodeLeadSurrogate UnicodeTrailSurrogate UnicodePropertyValueExpression :: UnicodePropertyName = UnicodePropertyValue
  • UnicodePropertyNameにmatchedするsource textが、Table 65の“Property name and aliases” columnにlistedされているUnicode property nameまたはproperty aliasでない場合、Syntax Errorです。
  • UnicodePropertyValueにmatchedするsource textが、UnicodePropertyNameにmatchedするsource textによって与えられるUnicode propertyまたはproperty aliasに対するproperty valueまたはproperty value aliasとして、PropertyValueAliases.txtにlistedされていない場合、Syntax Errorです。
UnicodePropertyValueExpression :: LoneUnicodePropertyNameOrValue
  • LoneUnicodePropertyNameOrValueにmatchedするsource textが、PropertyValueAliases.txtにlistedされているGeneral_Category (gc) propertyに対するUnicode property valueまたはproperty value aliasでもなく、Table 66の“Property name and aliases” columnにlistedされているbinary propertyまたはbinary property aliasでもなく、Table 67の“Property name” columnにlistedされているbinary property of stringsでもない場合、Syntax Errorです。
  • enclosing Pattern[UnicodeSetsMode] parameterを持たず、かつLoneUnicodePropertyNameOrValueにmatchedするsource textがTable 67の“Property name” columnにlistedされているbinary property of stringsである場合、Syntax Errorです。
CharacterClassEscape :: P{ UnicodePropertyValueExpression } CharacterClass :: [^ ClassContents ] NestedClass :: [^ ClassContents ] ClassSetRange :: ClassSetCharacter - ClassSetCharacter

22.2.1.2 Static Semantics: CountLeftCapturingParensWithin ( parseNode )

The abstract operation CountLeftCapturingParensWithin takes argument parseNode (a Parse Node) and returns a non-negative integer. parseNode内のleft-capturing parenthesesの数を返します。left-capturing parenthesisとは、 Atom :: ( GroupSpecifieropt Disjunction ) productionの( terminalにmatchedする任意の( pattern characterです。

Note

このsectionはB.1.2.2でamendedされます。

It performs the following steps when called:

  1. Assert: parseNodethe RegExp Pattern grammar内のproductionのinstanceである。
  2. parseNode内にcontainedされる Atom :: ( GroupSpecifieropt Disjunction ) Parse Nodesの数を返す。

22.2.1.3 Static Semantics: CountLeftCapturingParensBefore ( parseNode )

The abstract operation CountLeftCapturingParensBefore takes argument parseNode (a Parse Node) and returns a non-negative integer. enclosing pattern内でparseNodeの左側にoccurするleft-capturing parenthesesの数を返します。

Note

このsectionはB.1.2.2でamendedされます。

It performs the following steps when called:

  1. Assert: parseNodethe RegExp Pattern grammar内のproductionのinstanceである。
  2. patternparseNodeを含むPatternとする。
  3. pattern内にcontainedされる Atom :: ( GroupSpecifieropt Disjunction ) Parse Nodesのうち、parseNodeより前にoccurするかparseNodeをcontainするものの数を返す。

22.2.1.4 Static Semantics: MightBothParticipate ( x, y )

The abstract operation MightBothParticipate takes arguments x (a Parse Node) and y (a Parse Node) and returns a Boolean. It performs the following steps when called:

  1. Assert: xおよびyは同じenclosing Patternを持つ。
  2. enclosing Patternが、xAlternative内にcontainedされyがderived Disjunction内にcontainedされる、またはxがderived Disjunction内にcontainedされyAlternative内にcontainedされるような Disjunction :: Alternative | Disjunction Parse Nodeを含むなら、falseを返す。
  3. trueを返す。

22.2.1.5 Static Semantics: CapturingGroupNumber

The syntax-directed operation CapturingGroupNumber takes no arguments and returns a positive integer.

Note

このsectionはB.1.2.1でamendedされます。

It is defined piecewise over the following productions:

DecimalEscape :: NonZeroDigit
  1. NonZeroDigitのMVを返す。
DecimalEscape :: NonZeroDigit DecimalDigits
  1. nDecimalDigits内のcode pointsの数とする。
  2. NonZeroDigitのMV × 10n plus DecimalDigitsのMV)を返す。

“the MV of NonZeroDigit”および“the MV of DecimalDigits”のdefinitionsは12.9.3にあります。

22.2.1.6 Static Semantics: IsCharacterClass

The syntax-directed operation IsCharacterClass takes no arguments and returns a Boolean.

Note

このsectionはB.1.2.3でamendedされます。

It is defined piecewise over the following productions:

ClassAtom :: - ClassAtomNoDash :: SourceCharacter but not one of \ or ] or - ClassEscape :: b - CharacterEscape
  1. falseを返す。
ClassEscape :: CharacterClassEscape
  1. trueを返す。

22.2.1.7 Static Semantics: CharacterValue

The syntax-directed operation CharacterValue takes no arguments and returns a non-negative integer.

Note 1

このsectionはB.1.2.4でamendedされます。

It is defined piecewise over the following productions:

ClassAtom :: -
  1. U+002D (HYPHEN-MINUS)のnumeric valueを返す。
ClassAtomNoDash :: SourceCharacter but not one of \ or ] or -
  1. codePointSourceCharacterにmatchedするcode pointとする。
  2. codePointのnumeric valueを返す。
ClassEscape :: b
  1. U+0008 (BACKSPACE)のnumeric valueを返す。
ClassEscape :: -
  1. U+002D (HYPHEN-MINUS)のnumeric valueを返す。
CharacterEscape :: ControlEscape
  1. Table 63に従ったnumeric valueを返す。
Table 63: ControlEscape Code Point Values
ControlEscape Numeric Value Code Point Unicode Name Symbol
t 9 U+0009 CHARACTER TABULATION <HT>
n 10 U+000A LINE FEED (LF) <LF>
v 11 U+000B LINE TABULATION <VT>
f 12 U+000C FORM FEED (FF) <FF>
r 13 U+000D CARRIAGE RETURN (CR) <CR>
CharacterEscape :: c AsciiLetter
  1. codePointAsciiLetterにmatchedするcode pointとする。
  2. icodePointのnumeric valueとする。
  3. iを32で割ったremainderを返す。
CharacterEscape :: 0 [lookahead ∉ DecimalDigit]
  1. U+0000 (NULL)のnumeric valueを返す。
Note 2

\0は<NUL> characterを表し、decimal digitをfollowすることはできません。

CharacterEscape :: HexEscapeSequence
  1. HexEscapeSequenceのMVを返す。
RegExpUnicodeEscapeSequence :: u HexLeadSurrogate \u HexTrailSurrogate
  1. leadHexLeadSurrogateCharacterValueとする。
  2. trailHexTrailSurrogateCharacterValueとする。
  3. codePointUTF16SurrogatePairToCodePoint(lead, trail)とする。
  4. codePointのnumeric valueを返す。
RegExpUnicodeEscapeSequence :: u Hex4Digits
  1. Hex4DigitsのMVを返す。
RegExpUnicodeEscapeSequence :: u{ CodePoint }
  1. CodePointのMVを返す。
HexLeadSurrogate :: Hex4Digits HexTrailSurrogate :: Hex4Digits HexNonSurrogate :: Hex4Digits
  1. Hex4DigitsのMVを返す。
CharacterEscape :: IdentityEscape
  1. codePointIdentityEscapeにmatchedするcode pointとする。
  2. codePointのnumeric valueを返す。
ClassSetCharacter :: SourceCharacter but not ClassSetSyntaxCharacter
  1. codePointSourceCharacterにmatchedするcode pointとする。
  2. codePointのnumeric valueを返す。
ClassSetCharacter :: \ ClassSetReservedPunctuator
  1. codePointClassSetReservedPunctuatorにmatchedするcode pointとする。
  2. codePointのnumeric valueを返す。
ClassSetCharacter :: \b
  1. U+0008 (BACKSPACE)のnumeric valueを返す。

22.2.1.8 Static Semantics: MayContainStrings

The syntax-directed operation MayContainStrings takes no arguments and returns a Boolean. It is defined piecewise over the following productions:

CharacterClassEscape :: d D s S w W P{ UnicodePropertyValueExpression } UnicodePropertyValueExpression :: UnicodePropertyName = UnicodePropertyValue NestedClass :: [^ ClassContents ] ClassContents :: [empty] NonemptyClassRanges ClassSetOperand :: ClassSetCharacter
  1. falseを返す。
UnicodePropertyValueExpression :: LoneUnicodePropertyNameOrValue
  1. LoneUnicodePropertyNameOrValueにmatchedするsource textがTable 67の“Property name” columnにlistedされているbinary property of stringsであるなら、trueを返す。
  2. falseを返す。
ClassUnion :: ClassSetRange ClassUnionopt
  1. ClassUnionがpresentなら、ClassUnionMayContainStringsを返す。
  2. falseを返す。
ClassUnion :: ClassSetOperand ClassUnionopt
  1. ClassSetOperandMayContainStringstrueなら、trueを返す。
  2. ClassUnionがpresentなら、ClassUnionMayContainStringsを返す。
  3. falseを返す。
ClassIntersection :: ClassSetOperand && ClassSetOperand
  1. first ClassSetOperandMayContainStringsfalseなら、falseを返す。
  2. second ClassSetOperandMayContainStringsfalseなら、falseを返す。
  3. trueを返す。
ClassIntersection :: ClassIntersection && ClassSetOperand
  1. ClassIntersectionMayContainStringsfalseなら、falseを返す。
  2. ClassSetOperandMayContainStringsfalseなら、falseを返す。
  3. trueを返す。
ClassSubtraction :: ClassSetOperand -- ClassSetOperand
  1. first ClassSetOperandMayContainStringsを返す。
ClassSubtraction :: ClassSubtraction -- ClassSetOperand
  1. ClassSubtractionMayContainStringsを返す。
ClassStringDisjunctionContents :: ClassString | ClassStringDisjunctionContents
  1. ClassStringMayContainStringstrueなら、trueを返す。
  2. ClassStringDisjunctionContentsMayContainStringsを返す。
ClassString :: [empty]
  1. trueを返す。
ClassString :: NonEmptyClassString
  1. NonEmptyClassStringMayContainStringsを返す。
NonEmptyClassString :: ClassSetCharacter NonEmptyClassStringopt
  1. NonEmptyClassStringがpresentなら、trueを返す。
  2. falseを返す。

22.2.1.9 Static Semantics: GroupSpecifiersThatMatch ( thisGroupName )

The abstract operation GroupSpecifiersThatMatch takes argument thisGroupName (a GroupName Parse Node) and returns a List of GroupSpecifier Parse Nodes. It performs the following steps when called:

  1. namethisGroupNameCapturingGroupNameとする。
  2. patternthisGroupNameを含むPatternとする。
  3. resultを新しい空のListとする。
  4. patternが含む各GroupSpecifier groupSpecifierについて、以下を行う
    1. groupSpecifierCapturingGroupNamenameであるなら、
      1. groupSpecifierresultへappendする。
  5. resultを返す。

22.2.1.10 Static Semantics: CapturingGroupName

The syntax-directed operation CapturingGroupName takes no arguments and returns a String. It is defined piecewise over the following productions:

GroupName :: < RegExpIdentifierName >
  1. idTextUnescapedRegExpIdentifierNameRegExpIdentifierCodePointsとする。
  2. CodePointsToString(idTextUnescaped)を返す。

22.2.1.11 Static Semantics: RegExpIdentifierCodePoints

The syntax-directed operation RegExpIdentifierCodePoints takes no arguments and returns a List of code points. It is defined piecewise over the following productions:

RegExpIdentifierName :: RegExpIdentifierStart
  1. codePointRegExpIdentifierStartRegExpIdentifierCodePointとする。
  2. « codePoint »を返す。
RegExpIdentifierName :: RegExpIdentifierName RegExpIdentifierPart
  1. 派生したRegExpIdentifierNameRegExpIdentifierCodePointscodePointsとする。
  2. RegExpIdentifierPartRegExpIdentifierCodePointcodePointとする。
  3. codePointsと« codePoint »のlist-concatenationを返す。

22.2.1.12 Static Semantics: RegExpIdentifierCodePoint

The syntax-directed operation RegExpIdentifierCodePoint takes no arguments and returns a code point. It is defined piecewise over the following productions:

RegExpIdentifierStart :: IdentifierStartChar
  1. IdentifierStartCharにmatchedするcode pointを返す。
RegExpIdentifierPart :: IdentifierPartChar
  1. IdentifierPartCharにmatchedするcode pointを返す。
RegExpIdentifierStart :: \ RegExpUnicodeEscapeSequence RegExpIdentifierPart :: \ RegExpUnicodeEscapeSequence
  1. numeric valueがRegExpUnicodeEscapeSequenceCharacterValueであるcode pointを返す。
RegExpIdentifierStart :: UnicodeLeadSurrogate UnicodeTrailSurrogate RegExpIdentifierPart :: UnicodeLeadSurrogate UnicodeTrailSurrogate
  1. leadを、numeric valueがUnicodeLeadSurrogateにmatchedするcode pointのnumeric valueであるcode unitとする。
  2. trailを、numeric valueがUnicodeTrailSurrogateにmatchedするcode pointのnumeric valueであるcode unitとする。
  3. UTF16SurrogatePairToCodePoint(lead, trail)を返す。

22.2.2 Pattern Semantics

regular expression patternは、以下でdescribedされるprocessを使用してAbstract Closureへconvertedされます。implementationは、resultsがsameである限り、以下にlistedされたものよりefficientなalgorithmsを使用することがencouragedされます。Abstract ClosureはRegExp objectの[[RegExpMatcher]] internal slotのvalueとして使用されます。

Patternは、そのassociated flagsがuvも含まない場合はBMP patternです。そうでなければ、Unicode patternです。BMP patternは、Basic Multilingual Planeのrange内にあるUnicode code pointsである16-bit valuesのsequenceからなるものとしてinterpretedされるStringに対してmatchします。Unicode patternは、UTF-16を使用してencodedされたUnicode code pointsからなるものとしてinterpretedされるStringに対してmatchします。BMP patternのbehaviourをdescribeするcontextにおいて、“character”はsingle 16-bit Unicode BMP code pointを意味します。Unicode patternのbehaviourをdescribeするcontextにおいて、“character”はUTF-16 encoded code point(6.1.4)を意味します。いずれのcontextでも、“character value”は対応するnon-encoded code pointのnumeric valueを意味します。

Patternのsyntaxおよびsemanticsは、Patternのsource textがSourceCharacter valuesのListであり、各SourceCharacterがUnicode code pointに対応するものとして定義されます。BMP patternがnon-BMP SourceCharacterを含む場合、entire patternはUTF-16を使用してencodedされ、そのencodingのindividual code unitsがListのelementsとして使用されます。

Note

例えば、single non-BMP character U+1D11E(MUSICAL SYMBOL G CLEF)としてsource textでexpressedされたpatternを考えます。Unicode patternとしてinterpretedされる場合、それはsingle code point U+1D11Eからなるsingle element(character)Listになります。しかし、BMP patternとしてinterpretedされる場合、まずUTF-16 encodedされ、code units 0xD834および0xDD1Eからなるtwo element Listをproduceします。

Patternsは、non-BMP charactersがUTF-16 encodedされているECMAScript String valuesとしてRegExp constructorへpassedされます。例えば、single character MUSICAL SYMBOL G CLEF patternは、String valueとしてexpressedされる場合、elementsがcode units 0xD834および0xDD1Eであるlength 2のStringです。したがって、two pattern charactersからなるBMP patternとしてprocessするために、stringのさらなるtranslationは必要ありません。しかし、Unicode patternとしてprocessするには、sole elementがsingle pattern character、すなわちcode point U+1D11EであるListをproduceする際にUTF16SurrogatePairToCodePointを使用しなければなりません。

implementationは、UTF-16への、またはUTF-16からのそのようなtranslationsを実際にはperformしなくてもよいですが、このspecificationのsemanticsは、pattern matchingのresultがそのようなtranslationsがperformedされたかのようになることをrequireします。

22.2.2.1 Notation

以下のdescriptionsでは、次のinternal data structuresを使用します:

  • CharSetElementは、次の2つのentitiesのうちの1つです:
    • regexpRecord.[[UnicodeSets]]falseなら、CharSetElementは上記のPattern Semanticsの意味におけるcharacterです。
    • regexpRecord.[[UnicodeSets]]trueなら、CharSetElementは、elementsが上記のPattern Semanticsの意味におけるcharactersであるsequenceです。これにはempty sequence、one characterのsequence、およびmore than one characterのsequenceが含まれます。convenienceのため、このkindのCharSetElementsを扱うとき、individual characterはone characterのsequenceとinterchangeablyに扱われます。
  • CharSetは、CharSetElementsのmathematical setです。
  • CaptureRangeは、captureに含まれるcharactersのrangeを表すRecord { [[StartIndex]], [[EndIndex]] }です。ここで、[[StartIndex]]input内のrangeのstart index(inclusive)を表すintegerであり、[[EndIndex]]input内のrangeのend index(exclusive)を表すintegerです。任意のCaptureRangeについて、これらのindicesは[[StartIndex]][[EndIndex]]というinvariantをsatisfyしなければなりません。
  • MatchStateは、Record { [[Input]], [[EndIndex]], [[Captures]] }です。ここで、[[Input]]はmatch対象のStringを表すcharactersのList[[EndIndex]]integer[[Captures]]はpattern内の各left-capturing parenthesisに1つずつ対応するvaluesのListです。MatchStatesはregular expression matching algorithms内でpartial match statesを表すために使用されます。[[EndIndex]]は、patternによってこれまでmatchedされたlast input characterのindexに1を加えたものです。一方、[[Captures]]はcapturing parenthesesのresultsを保持します。[[Captures]]nth elementは、nth set of capturing parenthesesによってcapturedされたcharactersのrangeを表すCaptureRange、またはnth set of capturing parenthesesがまだreachedされていない場合はundefinedです。backtrackingにより、matching process中の任意の時点でmany MatchStatesが使用され得ます。
  • MatcherContinuationは、one MatchState argumentを受け取り、MatchStateまたはfailureのいずれかを返すAbstract Closureです。MatcherContinuationは、its captured valuesによってspecifiedされるpatternのremaining portionを、MatchState argumentでgivenされたintermediate stateからstartingして、inputに対してmatchしようとします。matchがsucceedsする場合、MatcherContinuationはreachedしたfinal MatchStateを返します;matchがfailsする場合、MatcherContinuationfailureを返します。
  • Matcherは、two arguments—MatchStateおよびMatcherContinuation—を受け取り、MatchStateまたはfailureのいずれかを返すAbstract Closureです。Matcherは、patternのmiddle subpattern(closureのcaptured valuesによってspecifiedされる)を、MatchState argumentでgivenされたintermediate stateからstartingして、MatchState[[Input]]に対してmatchしようとします。MatcherContinuation argumentは、patternのrestをmatchするclosureであるべきです。patternのsubpatternをmatchしてnew MatchStateをobtainした後、Matcherはそのnew MatchState上でMatcherContinuationをcallし、patternのrestもmatchできるかどうかをtestします。できる場合、MatcherMatcherContinuationによってreturnedされたMatchStateを返します;そうでない場合、Matcherはchoice pointsでdifferent choicesをtryしてもよく、succeedsするかすべてのpossibilitiesがexhaustedされるまでMatcherContinuationをrepeatedlyにcallします。

22.2.2.1.1 RegExp Records

RegExp Recordは、compilation中およびpossibly matching中に必要なRegExpに関するinformationをstoreするために使用されるRecord valueです。

これは次のfieldsを持ちます:

Table 64: RegExp Record Fields
Field Name Value Meaning
[[IgnoreCase]] a Boolean "i"がRegExpのflagsにappearsするかどうかを示す
[[Multiline]] a Boolean "m"がRegExpのflagsにappearsするかどうかを示す
[[DotAll]] a Boolean "s"がRegExpのflagsにappearsするかどうかを示す
[[Unicode]] a Boolean "u"がRegExpのflagsにappearsするかどうかを示す
[[UnicodeSets]] a Boolean "v"がRegExpのflagsにappearsするかどうかを示す
[[CapturingGroupsCount]] a non-negative integer RegExpのpattern内のleft-capturing parenthesesの数

22.2.2.2 Runtime Semantics: CompilePattern

The syntax-directed operation CompilePattern takes argument regexpRecord (a RegExp Record) and returns an Abstract Closure that takes a List of characters and a non-negative integer and returns either a MatchState or failure. It is defined piecewise over the following productions:

Pattern :: Disjunction
  1. mを、arguments regexpRecordおよびforwardを伴うDisjunctionCompileSubpatternとする。
  2. regexpRecordおよびmをcaptureし、calledされたときに次のstepsをperformする、parameters (input, index)を持つnew Abstract Closureを返す:
    1. Assert: inputはcharactersのListである。
    2. Assert: 0 ≤ indexinput内のelementsの数である。
    3. cを、nothingをcaptureし、calledされたときに次のstepsをperformする、parameters (y)を持つnew MatcherContinuationとする:
      1. Assert: yMatchStateである。
      2. yを返す。
    4. capabilityを、1からregexpRecord.[[CapturingGroupsCount]]までindexedされたregexpRecord.[[CapturingGroupsCount]]個のundefined valuesのListとする。
    5. xMatchState { [[Input]]: input, [[EndIndex]]: index, [[Captures]]: capability }とする。
    6. m(x, c)を返す。
Note

PatternはAbstract Closure valueへcompileされます。RegExpBuiltinExecは、このprocedureをcharactersのListおよびそのList内のoffsetにapplyして、patternがList内のexactlyそのoffsetからstartingしてmatchするかどうか、またmatchする場合はcapturing parenthesesのvaluesが何になるかをdetermineできます。22.2.2内のalgorithmsは、patternをcompileするとSyntaxError例外をthrowし得るようdesignedされています;一方で、patternがsuccessfully compiledされた後、resulting Abstract ClosureをapplyしてcharactersのList内のmatchをfindすることは、exceptionをthrowできません(out-of-memoryなど、どこでもoccurし得るimplementation-defined exceptionsを除く)。

22.2.2.3 Runtime Semantics: CompileSubpattern

The syntax-directed operation CompileSubpattern takes arguments regexpRecord (a RegExp Record) and direction (forward or backward) and returns a Matcher.

Note 1

このsectionはB.1.2.5でamendedされます。

It is defined piecewise over the following productions:

Disjunction :: Alternative | Disjunction
  1. m1を、arguments regexpRecordおよびdirectionを伴うAlternativeCompileSubpatternとする。
  2. m2を、arguments regexpRecordおよびdirectionを伴うDisjunctionCompileSubpatternとする。
  3. MatchTwoAlternatives(m1, m2)を返す。
Note 2

| regular expression operatorはtwo alternativesをseparateします。patternはまずleft Alternative(regular expressionのsequelがfollowする)をmatchしようとします;それがfailした場合、right Disjunction(regular expressionのsequelがfollowする)をmatchしようとします。left Alternative、right Disjunction、およびsequelがすべてchoice pointsを持つ場合、left Alternative内のnext choiceに移る前にsequel内のすべてのchoicesがtriedされます。left Alternative内のchoicesがexhaustedされると、left Alternativeの代わりにright Disjunctionがtriedされます。|によってskippedされたpatternのportion内のcapturing parenthesesは、Stringsではなくundefined valuesをproduceします。したがって、例えば、

/a|ab/.exec("abc")

"ab"ではなくresult "a"を返します。さらに、

/((a)|(ab))((c)|(bc))/.exec("abc")

はarray

["abc", "a", "a", undefined, "bc", undefined, "bc"]

を返し、

["abc", "ab", undefined, "ab", "c", "c", undefined]

ではありません。two alternativesがtriedされるorderはdirectionのvalueにindependentです。

Alternative :: [empty]
  1. EmptyMatcher()を返す。
Alternative :: Alternative Term
  1. m1を、arguments regexpRecordおよびdirectionを伴うAlternativeCompileSubpatternとする。
  2. m2を、arguments regexpRecordおよびdirectionを伴うTermCompileSubpatternとする。
  3. MatchSequence(m1, m2, direction)を返す。
Note 3

Consecutive Termsは、inputのconsecutive portionsをsimultaneouslyにmatchしようとします。directionforwardであるとき、left Alternative、right Term、およびregular expressionのsequelがすべてchoice pointsを持つ場合、right Term内のnext choiceへmoving onする前にsequel内のすべてのchoicesがtriedされ、left Alternative内のnext choiceへmoving onする前にright Term内のすべてのchoicesがtriedされます。directionbackwardであるとき、AlternativeおよびTermのevaluation orderはreversedされます。

Term :: Assertion
  1. argument regexpRecordを伴うAssertionCompileAssertionを返す。
Note 4

resulting Matcherdirectionにindependentです。

Term :: Atom
  1. arguments regexpRecordおよびdirectionを伴うAtomCompileAtomを返す。
Term :: Atom Quantifier
  1. mを、arguments regexpRecordおよびdirectionを伴うAtomCompileAtomとする。
  2. qQuantifierCompileQuantifierとする。
  3. Assert: q.[[Min]]q.[[Max]]である。
  4. parenIndexCountLeftCapturingParensBefore(Term)とする。
  5. parenCountCountLeftCapturingParensWithin(Atom)とする。
  6. mqparenIndex、およびparenCountをcaptureし、calledされたときに次のstepsをperformする、parameters (x, c)を持つnew Matcherを返す:
    1. Assert: xMatchStateである。
    2. Assert: cMatcherContinuationである。
    3. RepeatMatcher(m, q.[[Min]], q.[[Max]], q.[[Greedy]], x, c, parenIndex, parenCount)を返す。

22.2.2.3.1 RepeatMatcher ( m, min, max, greedy, matchState, continue, parenIndex, parenCount )

The abstract operation RepeatMatcher takes arguments m (a Matcher), min (a non-negative integer), max (a non-negative integer or +∞), greedy (a Boolean), matchState (a MatchState), continue (a MatcherContinuation), parenIndex (a non-negative integer), and parenCount (a non-negative integer) and returns either a MatchState or failure. It performs the following steps when called:

  1. max = 0なら、continue(matchState)を返す。
  2. dを、mminmaxgreedymatchStatecontinueparenIndex、およびparenCountをcaptureし、calledされたときに次のstepsをperformする、parameters (y)を持つnew MatcherContinuationとする:
    1. Assert: yMatchStateである。
    2. min = 0かつy.[[EndIndex]] = matchState.[[EndIndex]]なら、failureを返す。
    3. min = 0なら、min2を0とする;そうでなければ、min2min - 1とする。
    4. max = +∞なら、max2を+∞とする;そうでなければ、max2max - 1とする。
    5. RepeatMatcher(m, min2, max2, greedy, y, continue, parenIndex, parenCount)を返す。
  3. capabilitymatchState.[[Captures]]のcopyとする。
  4. parenIndex + 1からparenIndex + parenCountまでのinclusive interval内の各integer kについて、capability[k]をundefinedに設定する。
  5. inputmatchState.[[Input]]とする。
  6. ematchState.[[EndIndex]]とする。
  7. xrMatchState { [[Input]]: input, [[EndIndex]]: e, [[Captures]]: capability }とする。
  8. min ≠ 0なら、m(xr, d)を返す。
  9. greedyfalseなら、
    1. zcontinue(matchState)とする。
    2. zfailureでないなら、zを返す。
    3. m(xr, d)を返す。
  10. zm(xr, d)とする。
  11. zfailureでないなら、zを返す。
  12. continue(matchState)を返す。
Note 1

QuantifierがfollowするAtomは、Quantifierによってspecifiedされたnumber of timesだけrepeatedされます。Quantifierはnon-greedyであることができ、その場合、Atom patternはsequelをstill matchingしながら可能な限りfew times repeatedされます。またはgreedyであることができ、その場合、Atom patternはsequelをstill matchingしながら可能な限りmany times repeatedされます。Atom patternは、それがmatchするinput character sequenceではなくrepeatedされるため、Atomのdifferent repetitionsはdifferent input substringsにmatchし得ます。

Note 2

Atomとregular expressionのsequelがすべてchoice pointsを持つ場合、Atomはまず可能な限りmany(またはnon-greedyならfew)times matchedされます。last repetition of Atom内のnext choiceへmoving onする前に、sequel内のすべてのchoicesがtriedされます。Atomのlast(nth)repetition内のすべてのchoicesは、Atomのnext-to-last(n - 1)st repetition内のnext choiceへmoving onする前にtriedされます;その時点で、Atomのmore or fewer repetitionsが今やpossibleであることが判明する場合があります;これらは(again, possibleな限りfewまたはmanyからstartingして)exhaustedされ、その後、Atomの(n - 1)st repetition内のnext choiceへmoving onし、以降も同様です。

Compare

/a[a-z]{2,4}/.exec("abcdefghi")

これは"abcde"を返します。これに対して、

/a[a-z]{2,4}?/.exec("abcdefghi")

"abc"を返します。

さらに次を考えます:

/(aa|aabaac|ba|b|c)*/.exec("aabaac")

これは、aboveのchoice point orderingにより、array

["aaba", "ba"]

を返し、次のいずれでもありません:

["aabaac", "aabaac"]
["aabaac", "c"]

上記のchoice pointsのorderingは、two numbers(unary notationでrepresented)のgreatest common divisorをcalculateするregular expressionを書くために使用できます。次のexampleは10と15のgcdをcalculateします:

"aaaaaaaaaa,aaaaaaaaaaaaaaa".replace(/^(a+)\1*,\1+$/, "$1")

これはunary notationでgcd "aaaaa"を返します。

Note 3

RepeatMatcherのstep 4は、AtomがrepeatedされるたびにAtomのcapturesをclearします。そのbehaviourはregular expression

/(z)((a+)?(b+)?(c))*/.exec("zaacbbbcac")

で見ることができ、これはarray

["zaacbbbcac", "z", "ac", "a", undefined, "c"]

を返し、

["zaacbbbcac", "z", "ac", "a", "bbb", "c"]

ではありません。なぜなら、outermost *の各iterationが、quantified Atom内にcontainedされるすべてのcaptured Stringsをclearし、このcaseではcapture Strings numbered 2, 3, 4, and 5を含むためです。

Note 4

RepeatMatcherのstep 2.bは、minimum number of repetitionsがsatisfiedされた後、empty character sequenceにmatchするAtomのmore expansionsはfurther repetitionsとしてconsideredされないことを述べています。これはregular expression engineが次のようなpatternsでinfinite loopにfalling intoすることをpreventします:

/(a*)*/.exec("b")

または少しmore complicatedな:

/(a*)b\1+/.exec("baaaac")

これはarray

["b", ""]

を返します。

22.2.2.3.2 EmptyMatcher ( )

The abstract operation EmptyMatcher takes no arguments and returns a Matcher. It performs the following steps when called:

  1. nothingをcaptureし、calledされたときに次のstepsをperformする、parameters (matchState, continue)を持つnew Matcherを返す:
    1. Assert: matchStateMatchStateである。
    2. Assert: continueMatcherContinuationである。
    3. continue(matchState)を返す。

22.2.2.3.3 MatchTwoAlternatives ( m1, m2 )

The abstract operation MatchTwoAlternatives takes arguments m1 (a Matcher) and m2 (a Matcher) and returns a Matcher. It performs the following steps when called:

  1. m1およびm2をcaptureし、calledされたときに次のstepsをperformする、parameters (matchState, continue)を持つnew Matcherを返す:
    1. Assert: matchStateMatchStateである。
    2. Assert: continueMatcherContinuationである。
    3. resultm1(matchState, continue)とする。
    4. resultfailureでないなら、resultを返す。
    5. m2(matchState, continue)を返す。

22.2.2.3.4 MatchSequence ( m1, m2, direction )

The abstract operation MatchSequence takes arguments m1 (a Matcher), m2 (a Matcher), and direction (forward or backward) and returns a Matcher. It performs the following steps when called:

  1. directionforwardなら、
    1. m1およびm2をcaptureし、calledされたときに次のstepsをperformする、parameters (matchState, continue)を持つnew Matcherを返す:
      1. Assert: matchStateMatchStateである。
      2. Assert: continueMatcherContinuationである。
      3. dを、continueおよびm2をcaptureし、calledされたときに次のstepsをperformする、parameters (y)を持つnew MatcherContinuationとする:
        1. Assert: yMatchStateである。
        2. m2(y, continue)を返す。
      4. m1(matchState, d)を返す。
  2. Assert: directionbackwardである。
  3. m1およびm2をcaptureし、calledされたときに次のstepsをperformする、parameters (matchState, continue)を持つnew Matcherを返す:
    1. Assert: matchStateMatchStateである。
    2. Assert: continueMatcherContinuationである。
    3. dを、continueおよびm1をcaptureし、calledされたときに次のstepsをperformする、parameters (y)を持つnew MatcherContinuationとする:
      1. Assert: yMatchStateである。
      2. m1(y, continue)を返す。
    4. m2(matchState, d)を返す。

22.2.2.4 Runtime Semantics: CompileAssertion

The syntax-directed operation CompileAssertion takes argument regexpRecord (a RegExp Record) and returns a Matcher.

Note 1

このsectionはB.1.2.6でamendedされます。

It is defined piecewise over the following productions:

Assertion :: ^
  1. regexpRecordをcaptureし、calledされたときに次のstepsをperformする、parameters (matchState, continue)を持つnew Matcherを返す:
    1. Assert: matchStateMatchStateである。
    2. Assert: continueMatcherContinuationである。
    3. inputmatchState.[[Input]]とする。
    4. ematchState.[[EndIndex]]とする。
    5. e = 0である、またはregexpRecord.[[Multiline]]trueでありcharacter input[e - 1]がLineTerminatorによってmatchedされるなら、
      1. continue(matchState)を返す。
    6. failureを返す。
Note 2

y flagがpatternとともに使用される場合であっても、^は常にinputのbeginning、または(regexpRecord.[[Multiline]]trueなら)lineのbeginningにのみmatchします。

Assertion :: $
  1. regexpRecordをcaptureし、calledされたときに次のstepsをperformする、parameters (matchState, continue)を持つnew Matcherを返す:
    1. Assert: matchStateMatchStateである。
    2. Assert: continueMatcherContinuationである。
    3. inputmatchState.[[Input]]とする。
    4. ematchState.[[EndIndex]]とする。
    5. inputLengthinput内のelementsの数とする。
    6. e = inputLengthである、またはregexpRecord.[[Multiline]]trueでありcharacter input[e]がLineTerminatorによってmatchedされるなら、
      1. continue(matchState)を返す。
    7. failureを返す。
Assertion :: \b
  1. regexpRecordをcaptureし、calledされたときに次のstepsをperformする、parameters (matchState, continue)を持つnew Matcherを返す:
    1. Assert: matchStateMatchStateである。
    2. Assert: continueMatcherContinuationである。
    3. inputmatchState.[[Input]]とする。
    4. ematchState.[[EndIndex]]とする。
    5. aIsWordChar(regexpRecord, input, e - 1)とする。
    6. bIsWordChar(regexpRecord, input, e)とする。
    7. atrueでありbfalseである、またはafalseでありbtrueであるなら、continue(matchState)を返す。
    8. failureを返す。
Assertion :: \B
  1. regexpRecordをcaptureし、calledされたときに次のstepsをperformする、parameters (matchState, continue)を持つnew Matcherを返す:
    1. Assert: matchStateMatchStateである。
    2. Assert: continueMatcherContinuationである。
    3. inputmatchState.[[Input]]とする。
    4. ematchState.[[EndIndex]]とする。
    5. aIsWordChar(regexpRecord, input, e - 1)とする。
    6. bIsWordChar(regexpRecord, input, e)とする。
    7. atrueでありbtrueである、またはafalseでありbfalseであるなら、continue(matchState)を返す。
    8. failureを返す。
Assertion :: (?= Disjunction )
  1. mを、arguments regexpRecordおよびforwardを伴うDisjunctionCompileSubpatternとする。
  2. mをcaptureし、calledされたときに次のstepsをperformする、parameters (matchState, continue)を持つnew Matcherを返す:
    1. Assert: matchStateMatchStateである。
    2. Assert: continueMatcherContinuationである。
    3. dを、nothingをcaptureし、calledされたときに次のstepsをperformする、parameters (y)を持つnew MatcherContinuationとする:
      1. Assert: yMatchStateである。
      2. yを返す。
    4. resultm(matchState, d)とする。
    5. resultfailureなら、failureを返す。
    6. Assert: resultMatchStateである。
    7. capabilityresult.[[Captures]]とする。
    8. inputmatchState.[[Input]]とする。
    9. xematchState.[[EndIndex]]とする。
    10. zMatchState { [[Input]]: input, [[EndIndex]]: xe, [[Captures]]: capability }とする。
    11. continue(z)を返す。
Note 3

form (?= Disjunction )はzero-width positive lookaheadをspecifyします。succeedするには、Disjunction内のpatternがcurrent positionでmatchしなければなりませんが、sequelをmatchingする前にcurrent positionはadvancedされません。Disjunctionがcurrent positionでseveral waysにmatchできる場合、first oneのみがtriedされます。他のregular expression operatorsとは異なり、(?= formへのbacktrackingはありません(このunusual behaviourはPerlからinheritedされています)。これは、Disjunctionがcapturing parenthesesを含み、かつpatternのsequelがそれらのcapturesへのbackreferencesを含む場合にのみmatterします。

例えば、

/(?=(a+))/.exec("baaabac")

はfirst bの直後のempty Stringにmatchし、したがってarrayを返します:

["", "aaa"]

lookaheadへのbacktrackingがないことをillustrateするため、次を考えます:

/(?=(a+))a*b\1/.exec("baaabac")

このexpressionは

["aba", "a"]

を返し、次ではありません:

["aaaba", "a"]
Assertion :: (?! Disjunction )
  1. mを、arguments regexpRecordおよびforwardを伴うDisjunctionCompileSubpatternとする。
  2. mをcaptureし、calledされたときに次のstepsをperformする、parameters (matchState, continue)を持つnew Matcherを返す:
    1. Assert: matchStateMatchStateである。
    2. Assert: continueMatcherContinuationである。
    3. dを、nothingをcaptureし、calledされたときに次のstepsをperformする、parameters (y)を持つnew MatcherContinuationとする:
      1. Assert: yMatchStateである。
      2. yを返す。
    4. resultm(matchState, d)とする。
    5. resultfailureでないなら、failureを返す。
    6. continue(matchState)を返す。
Note 4

form (?! Disjunction )はzero-width negative lookaheadをspecifyします。succeedするには、Disjunction内のpatternがcurrent positionでmatchにfailしなければなりません。sequelをmatchingする前にcurrent positionはadvancedされません。Disjunctionはcapturing parenthesesを含むことができますが、それらへのbackreferencesはDisjunction自体の内側からのみ意味を持ちます。pattern内の他の場所からこれらのcapturing parenthesesへのbackreferencesは、negative lookaheadがpatternをsucceedさせるためにfailしなければならないため、常にundefinedを返します。例えば、

/(.*?)a(?!(a+)b\2c)\2(.*)/.exec("baaabaac")

は、some positive number n of a's、b、another n a's(first \2でspecified)、およびcがimmediately followedしないaを探します。second \2はnegative lookaheadの外側にあるため、undefinedに対してmatchesし、したがって常にsucceedsします。whole expressionはarrayを返します:

["baaabaac", "ba", undefined, "abaac"]
Assertion :: (?<= Disjunction )
  1. mを、arguments regexpRecordおよびbackwardを伴うDisjunctionCompileSubpatternとする。
  2. mをcaptureし、calledされたときに次のstepsをperformする、parameters (matchState, continue)を持つnew Matcherを返す:
    1. Assert: matchStateMatchStateである。
    2. Assert: continueMatcherContinuationである。
    3. dを、nothingをcaptureし、calledされたときに次のstepsをperformする、parameters (y)を持つnew MatcherContinuationとする:
      1. Assert: yMatchStateである。
      2. yを返す。
    4. resultm(matchState, d)とする。
    5. resultfailureなら、failureを返す。
    6. Assert: resultMatchStateである。
    7. capabilityresult.[[Captures]]とする。
    8. inputmatchState.[[Input]]とする。
    9. xematchState.[[EndIndex]]とする。
    10. zMatchState { [[Input]]: input, [[EndIndex]]: xe, [[Captures]]: capability }とする。
    11. continue(z)を返す。
Assertion :: (?<! Disjunction )
  1. mを、arguments regexpRecordおよびbackwardを伴うDisjunctionCompileSubpatternとする。
  2. mをcaptureし、calledされたときに次のstepsをperformする、parameters (matchState, continue)を持つnew Matcherを返す:
    1. Assert: matchStateMatchStateである。
    2. Assert: continueMatcherContinuationである。
    3. dを、nothingをcaptureし、calledされたときに次のstepsをperformする、parameters (y)を持つnew MatcherContinuationとする:
      1. Assert: yMatchStateである。
      2. yを返す。
    4. resultm(matchState, d)とする。
    5. resultfailureでないなら、failureを返す。
    6. continue(matchState)を返す。

22.2.2.4.1 IsWordChar ( regexpRecord, input, e )

The abstract operation IsWordChar takes arguments regexpRecord (a RegExp Record), input (a List of characters), and e (an integer) and returns a Boolean. It performs the following steps when called:

  1. inputLengthinput内のelementsの数とする。
  2. e = -1またはe = inputLengthなら、falseを返す。
  3. charをcharacter input[e]とする。
  4. WordCharacters(regexpRecord)がcharを含むなら、trueを返す。
  5. falseを返す。

22.2.2.5 Runtime Semantics: CompileQuantifier

The syntax-directed operation CompileQuantifier takes no arguments and returns a Record with fields [[Min]] (a non-negative integer), [[Max]] (a non-negative integer or +∞), and [[Greedy]] (a Boolean). It is defined piecewise over the following productions:

Quantifier :: QuantifierPrefix
  1. qpQuantifierPrefixCompileQuantifierPrefixとする。
  2. Record { [[Min]]: qp.[[Min]], [[Max]]: qp.[[Max]], [[Greedy]]: true }を返す。
Quantifier :: QuantifierPrefix ?
  1. qpQuantifierPrefixCompileQuantifierPrefixとする。
  2. Record { [[Min]]: qp.[[Min]], [[Max]]: qp.[[Max]], [[Greedy]]: false }を返す。

22.2.2.6 Runtime Semantics: CompileQuantifierPrefix

The syntax-directed operation CompileQuantifierPrefix takes no arguments and returns a Record with fields [[Min]] (a non-negative integer) and [[Max]] (a non-negative integer or +∞). It is defined piecewise over the following productions:

QuantifierPrefix :: *
  1. Record { [[Min]]: 0, [[Max]]: +∞ }を返す。
QuantifierPrefix :: +
  1. Record { [[Min]]: 1, [[Max]]: +∞ }を返す。
QuantifierPrefix :: ?
  1. Record { [[Min]]: 0, [[Max]]: 1 }を返す。
QuantifierPrefix :: { DecimalDigits }
  1. iDecimalDigitsのMVとする(12.9.3を参照)。
  2. Record { [[Min]]: i, [[Max]]: i }を返す。
QuantifierPrefix :: { DecimalDigits ,}
  1. iDecimalDigitsのMVとする。
  2. Record { [[Min]]: i, [[Max]]: +∞ }を返す。
QuantifierPrefix :: { DecimalDigits , DecimalDigits }
  1. iをfirst DecimalDigitsのMVとする。
  2. jをsecond DecimalDigitsのMVとする。
  3. Record { [[Min]]: i, [[Max]]: j }を返す。

22.2.2.7 Runtime Semantics: CompileAtom

The syntax-directed operation CompileAtom takes arguments regexpRecord (a RegExp Record) and direction (forward or backward) and returns a Matcher.

Note 1

このsectionはB.1.2.7でamendedされます。

It is defined piecewise over the following productions:

Atom :: PatternCharacter
  1. charPatternCharacterにmatchedするcharacterとする。
  2. charSetをcharacter charを含むone-element CharSetとする。
  3. CharacterSetMatcher(regexpRecord, charSet, false, direction)を返す。
Atom :: .
  1. charSetAllCharacters(regexpRecord)とする。
  2. regexpRecord.[[DotAll]]trueでないなら、
    1. LineTerminator productionのright-hand side上のcode pointに対応するすべてのcharactersをcharSetからremoveする。
  3. CharacterSetMatcher(regexpRecord, charSet, false, direction)を返す。
Atom :: CharacterClass
  1. ccをargument regexpRecordを伴うCharacterClassCompileCharacterClassとする。
  2. cscc.[[CharSet]]とする。
  3. regexpRecord.[[UnicodeSets]]falseである、またはcsのすべてのCharSetElementがsingle characterからなる(csがemptyの場合を含む)なら、CharacterSetMatcher(regexpRecord, cs, cc.[[Invert]], direction)を返す。
  4. Assert: cc.[[Invert]]falseである。
  5. listOfMatchersMatchersのempty Listとする。
  6. cs内のmore than 1 characterを含む各CharSetElement sについて、lengthのdescending orderでiteratingして、以下を行う
    1. cs2sのlast code pointを含むone-element CharSetとする。
    2. m2CharacterSetMatcher(regexpRecord, cs2, false, direction)とする。
    3. s内の各code point c1について、そのsecond-to-last code pointからbackwardsにiteratingして、以下を行う
      1. cs1c1を含むone-element CharSetとする。
      2. m1CharacterSetMatcher(regexpRecord, cs1, false, direction)とする。
      3. m2MatchSequence(m1, m2, direction)に設定する。
    4. m2listOfMatchersへappendする。
  7. singlesを、single characterからなるcsのすべてのCharSetElementを含むCharSetとする。
  8. CharacterSetMatcher(regexpRecord, singles, false, direction)をlistOfMatchersへappendする。
  9. csがcharactersのempty sequenceを含むなら、EmptyMatcher()をlistOfMatchersへappendする。
  10. m2listOfMatchers内のlast Matcherとする。
  11. listOfMatchersの各Matcher m1について、そのsecond-to-last elementからbackwardsにiteratingして、以下を行う
    1. m2MatchTwoAlternatives(m1, m2)に設定する。
  12. m2を返す。
Atom :: ( GroupSpecifieropt Disjunction )
  1. mを、arguments regexpRecordおよびdirectionを伴うDisjunctionCompileSubpatternとする。
  2. parenIndexCountLeftCapturingParensBefore(Atom)とする。
  3. directionm、およびparenIndexをcaptureし、calledされたときに次のstepsをperformする、parameters (x, c)を持つnew Matcherを返す:
    1. Assert: xMatchStateである。
    2. Assert: cMatcherContinuationである。
    3. dを、xcdirection、およびparenIndexをcaptureし、calledされたときに次のstepsをperformする、parameters (y)を持つnew MatcherContinuationとする:
      1. Assert: yMatchStateである。
      2. capabilityy.[[Captures]]のcopyとする。
      3. inputx.[[Input]]とする。
      4. xex.[[EndIndex]]とする。
      5. yey.[[EndIndex]]とする。
      6. directionforwardなら、
        1. Assert: xeyeである。
        2. rCaptureRange { [[StartIndex]]: xe, [[EndIndex]]: ye }とする。
      7. そうでなければ、
        1. Assert: directionbackwardである。
        2. Assert: yexeである。
        3. rCaptureRange { [[StartIndex]]: ye, [[EndIndex]]: xe }とする。
      8. capability[parenIndex + 1]をrに設定する。
      9. zMatchState { [[Input]]: input, [[EndIndex]]: ye, [[Captures]]: capability }とする。
      10. c(z)を返す。
    4. m(x, d)を返す。
Note 2

form ( Disjunction )のparenthesesは、Disjunction patternのcomponentsをgroup togetherすることと、matchのresultをsaveすることの両方にserveします。resultは、backreference(\ followed by a non-zero decimal number)で使用されたり、replace Stringでreferencedされたり、regular expression matching Abstract Closureからarrayのpartとしてreturnedされたりできます。parenthesesのcapturing behaviourをinhibitするには、代わりにform (?: Disjunction )を使用します。

Atom :: (? RegularExpressionModifiers : Disjunction )
  1. addModifiersRegularExpressionModifiersにmatchedするsource textとする。
  2. removeModifiersをempty Stringとする。
  3. modifiedRerUpdateModifiers(regexpRecord, CodePointsToString(addModifiers), removeModifiers)とする。
  4. arguments modifiedRerおよびdirectionを伴うDisjunctionCompileSubpatternを返す。
Atom :: (? RegularExpressionModifiers - RegularExpressionModifiers : Disjunction )
  1. addModifiersをfirst RegularExpressionModifiersにmatchedするsource textとする。
  2. removeModifiersをsecond RegularExpressionModifiersにmatchedするsource textとする。
  3. modifiedRerUpdateModifiers(regexpRecord, CodePointsToString(addModifiers), CodePointsToString(removeModifiers))とする。
  4. arguments modifiedRerおよびdirectionを伴うDisjunctionCompileSubpatternを返す。
AtomEscape :: DecimalEscape
  1. nDecimalEscapeCapturingGroupNumberとする。
  2. Assert: nregexpRecord.[[CapturingGroupsCount]]である。
  3. BackreferenceMatcher(regexpRecord, « n », direction)を返す。
Note 3

\ followed by a non-zero decimal number nというformのescape sequenceは、nth set of capturing parentheses(22.2.2.1)のresultにmatchします。regular expressionがn個未満のcapturing parenthesesを持つ場合、errorになります。regular expressionがn個以上のcapturing parenthesesを持つが、nth oneが何もcapturedしていないためundefinedである場合、backreferenceは常にsucceedsします。

AtomEscape :: CharacterEscape
  1. charValueCharacterEscapeCharacterValueとする。
  2. charをcharacter valueがcharValueであるcharacterとする。
  3. charSetをcharacter charを含むone-element CharSetとする。
  4. CharacterSetMatcher(regexpRecord, charSet, false, direction)を返す。
AtomEscape :: CharacterClassEscape
  1. csをargument regexpRecordを伴うCharacterClassEscapeCompileToCharSetとする。
  2. regexpRecord.[[UnicodeSets]]falseである、またはcsのすべてのCharSetElementがsingle characterからなる(csがemptyの場合を含む)なら、CharacterSetMatcher(regexpRecord, cs, false, direction)を返す。
  3. listOfMatchersMatchersのempty Listとする。
  4. cs内のmore than 1 characterを含む各CharSetElement sについて、lengthのdescending orderでiteratingして、以下を行う
    1. cs2sのlast code pointを含むone-element CharSetとする。
    2. m2CharacterSetMatcher(regexpRecord, cs2, false, direction)とする。
    3. s内の各code point c1について、そのsecond-to-last code pointからbackwardsにiteratingして、以下を行う
      1. cs1c1を含むone-element CharSetとする。
      2. m1CharacterSetMatcher(regexpRecord, cs1, false, direction)とする。
      3. m2MatchSequence(m1, m2, direction)に設定する。
    4. m2listOfMatchersへappendする。
  5. singlesを、single characterからなるcsのすべてのCharSetElementを含むCharSetとする。
  6. CharacterSetMatcher(regexpRecord, singles, false, direction)をlistOfMatchersへappendする。
  7. csがcharactersのempty sequenceを含むなら、EmptyMatcher()をlistOfMatchersへappendする。
  8. m2listOfMatchers内のlast Matcherとする。
  9. listOfMatchersの各Matcher m1について、そのsecond-to-last elementからbackwardsにiteratingして、以下を行う
    1. m2MatchTwoAlternatives(m1, m2)に設定する。
  10. m2を返す。
AtomEscape :: k GroupName
  1. matchingGroupSpecifiersGroupSpecifiersThatMatch(GroupName)とする。
  2. parenIndicesを新しい空のListとする。
  3. matchingGroupSpecifiersの各GroupSpecifier groupSpecifierについて、以下を行う
    1. parenIndexCountLeftCapturingParensBefore(groupSpecifier)とする。
    2. parenIndexparenIndicesへappendする。
  4. BackreferenceMatcher(regexpRecord, parenIndices, direction)を返す。

22.2.2.7.1 CharacterSetMatcher ( regexpRecord, charSet, invert, direction )

The abstract operation CharacterSetMatcher takes arguments regexpRecord (a RegExp Record), charSet (a CharSet), invert (a Boolean), and direction (forward or backward) and returns a Matcher. It performs the following steps when called:

  1. regexpRecord.[[UnicodeSets]]trueなら、
    1. Assert: invertfalseである。
    2. Assert: charSetのすべてのCharSetElementはsingle characterからなる。
  2. regexpRecordcharSetinvert、およびdirectionをcaptureし、calledされたときに次のstepsをperformする、parameters (x, c)を持つnew Matcherを返す:
    1. Assert: xMatchStateである。
    2. Assert: cMatcherContinuationである。
    3. inputx.[[Input]]とする。
    4. endIndexx.[[EndIndex]]とする。
    5. directionforwardなら、fendIndex + 1とする。
    6. そうでなければ、fendIndex - 1とする。
    7. inputLengthinput内のelementsの数とする。
    8. f < 0またはf > inputLengthなら、failureを返す。
    9. indexmin(endIndex, f)とする。
    10. charをcharacter input[index]とする。
    11. ccCanonicalize(regexpRecord, char)とする。
    12. Canonicalize(regexpRecord, a)がccであるような、exactly one character aを含むCharSetElementcharSet内に存在するなら、foundtrueとする;そうでなければ、foundfalseとする。
    13. invertfalseであり、かつfoundfalseなら、failureを返す。
    14. inverttrueであり、かつfoundtrueなら、failureを返す。
    15. capabilityx.[[Captures]]とする。
    16. yMatchState { [[Input]]: input, [[EndIndex]]: f, [[Captures]]: capability }とする。
    17. c(y)を返す。

22.2.2.7.2 BackreferenceMatcher ( regexpRecord, ns, direction )

The abstract operation BackreferenceMatcher takes arguments regexpRecord (a RegExp Record), ns (a List of positive integers), and direction (forward or backward) and returns a Matcher. It performs the following steps when called:

  1. regexpRecordns、およびdirectionをcaptureし、calledされたときに次のstepsをperformする、parameters (x, c)を持つnew Matcherを返す:
    1. Assert: xMatchStateである。
    2. Assert: cMatcherContinuationである。
    3. inputx.[[Input]]とする。
    4. capabilityx.[[Captures]]とする。
    5. rundefinedとする。
    6. nsの各integer nについて、以下を行う
      1. capability[n]がundefinedでないなら、
        1. Assert: rundefinedである。
        2. rcapability[n]に設定する。
    7. rundefinedなら、c(x)を返す。
    8. endIndexx.[[EndIndex]]とする。
    9. rsr.[[StartIndex]]とする。
    10. rer.[[EndIndex]]とする。
    11. lengthre - rsとする。
    12. directionforwardなら、fendIndex + lengthとする。
    13. そうでなければ、fendIndex - lengthとする。
    14. inputLengthinput内のelementsの数とする。
    15. f < 0またはf > inputLengthなら、failureを返す。
    16. gmin(endIndex, f)とする。
    17. 0(inclusive)からlength(exclusive)までのinterval内に、Canonicalize(regexpRecord, input[rs + i])がCanonicalize(regexpRecord, input[g + i])でないようなinteger iが存在するなら、failureを返す。
    18. yMatchState { [[Input]]: input, [[EndIndex]]: f, [[Captures]]: capability }とする。
    19. c(y)を返す。

22.2.2.7.3 Canonicalize ( regexpRecord, char )

The abstract operation Canonicalize takes arguments regexpRecord (a RegExp Record) and char (a character) and returns a character. It performs the following steps when called:

  1. HasEitherUnicodeFlag(regexpRecord)がtrueであり、かつregexpRecord.[[IgnoreCase]]trueなら、
    1. Unicode Character Databaseのfile CaseFolding.txtcharに対するsimpleまたはcommon case folding mappingを提供するなら、そのmappingをcharにapplyしたresultを返す。
    2. charを返す。
  2. regexpRecord.[[IgnoreCase]]falseなら、charを返す。
  3. Assert: charはUTF-16 code unitである。
  4. codePointをnumeric valueがcharのnumeric valueであるcode pointとする。
  5. uを、Unicode Default Case Conversion algorithmに従ったtoUppercase(« codePoint »)とする。
  6. uStringCodePointsToString(u)とする。
  7. uStringのlength ≠ 1なら、charを返す。
  8. codeUnituStringのsingle code unit elementとする。
  9. charのnumeric value ≥ 128であり、かつcodeUnitのnumeric value < 128なら、charを返す。
  10. codeUnitを返す。
Note

HasEitherUnicodeFlag(regexpRecord)がtrueであるcase-insignificant matchesでは、すべてのcharactersは、comparedされる直前にUnicode Standardによってprovidedされるsimple mappingを使用してimplicitly case-foldedされます。simple mappingは常にsingle code pointへmapするため、例えばß(U+00DF LATIN SMALL LETTER SHARP S)をssSSへmapしません。ただし、Basic Latin blockの外側にあるcode pointsをその内側のcode pointsへmapすることはあります—例えば、ſ(U+017F LATIN SMALL LETTER LONG S)はs(U+0073 LATIN SMALL LETTER S)へcase-foldし、(U+212A KELVIN SIGN)はk(U+006B LATIN SMALL LETTER K)へcase-foldします。それらのcode pointsを含むStringsは/[a-z]/uiのようなregular expressionsによってmatchedされます。

HasEitherUnicodeFlag(regexpRecord)がfalseであるcase-insignificant matchesでは、mappingはtoCasefoldではなくUnicode Default Case Conversion algorithm toUppercaseに基づくため、いくつかのsubtle differencesが生じます。例えば、(U+2126 OHM SIGN)はtoUppercaseではitselfへmappedされますが、toCasefoldではΩ(U+03A9 GREEK CAPITAL LETTER OMEGA)とともにω(U+03C9 GREEK SMALL LETTER OMEGA)へmappedされるため、"\u2126"/[ω]/uiおよび/[\u03A9]/uiによってmatchedされますが、/[ω]/iまたは/[\u03A9]/iによってはmatchedされません。また、Basic Latin blockの外側のcode pointはその内側のcode pointへmappedされないため、"\u017F ſ""\u212A K"のようなstringsは/[a-z]/iによってmatchedされません。

22.2.2.7.4 UpdateModifiers ( regexpRecord, add, remove )

The abstract operation UpdateModifiers takes arguments regexpRecord (a RegExp Record), add (a String), and remove (a String) and returns a RegExp Record. It performs the following steps when called:

  1. Assert: addおよびremoveはcommon elementsを持たない。
  2. ignoreCaseregexpRecord.[[IgnoreCase]]とする。
  3. multilineregexpRecord.[[Multiline]]とする。
  4. dotAllregexpRecord.[[DotAll]]とする。
  5. unicoderegexpRecord.[[Unicode]]とする。
  6. unicodeSetsregexpRecord.[[UnicodeSets]]とする。
  7. capturingGroupsCountregexpRecord.[[CapturingGroupsCount]]とする。
  8. remove"i"を含むなら、ignoreCasefalseに設定する。
  9. そうでなく、add"i"を含むなら、ignoreCasetrueに設定する。
  10. remove"m"を含むなら、multilinefalseに設定する。
  11. そうでなく、add"m"を含むなら、multilinetrueに設定する。
  12. remove"s"を含むなら、dotAllfalseに設定する。
  13. そうでなく、add"s"を含むなら、dotAlltrueに設定する。
  14. RegExp Record { [[IgnoreCase]]: ignoreCase, [[Multiline]]: multiline, [[DotAll]]: dotAll, [[Unicode]]: unicode, [[UnicodeSets]]: unicodeSets, [[CapturingGroupsCount]]: capturingGroupsCount }を返す。

22.2.2.8 Runtime Semantics: CompileCharacterClass

The syntax-directed operation CompileCharacterClass takes argument regexpRecord (a RegExp Record) and returns a Record with fields [[CharSet]] (a CharSet) and [[Invert]] (a Boolean). It is defined piecewise over the following productions:

CharacterClass :: [ ClassContents ]
  1. charSetをargument regexpRecordを伴うClassContentsCompileToCharSetとする。
  2. Record { [[CharSet]]: charSet, [[Invert]]: false }を返す。
CharacterClass :: [^ ClassContents ]
  1. charSetをargument regexpRecordを伴うClassContentsCompileToCharSetとする。
  2. regexpRecord.[[UnicodeSets]]trueなら、
    1. Record { [[CharSet]]: CharacterComplement(regexpRecord, charSet), [[Invert]]: false }を返す。
  3. Record { [[CharSet]]: charSet, [[Invert]]: true }を返す。

22.2.2.9 Runtime Semantics: CompileToCharSet

The syntax-directed operation CompileToCharSet takes argument regexpRecord (a RegExp Record) and returns a CharSet.

Note 1

このsectionはB.1.2.8でamendedされます。

It is defined piecewise over the following productions:

ClassContents :: [empty]
  1. empty CharSetを返す。
NonemptyClassRanges :: ClassAtom NonemptyClassRangesNoDash
  1. charSetをargument regexpRecordを伴うClassAtomCompileToCharSetとする。
  2. otherSetをargument regexpRecordを伴うNonemptyClassRangesNoDashCompileToCharSetとする。
  3. CharSets charSetおよびotherSetのunionを返す。
NonemptyClassRanges :: ClassAtom - ClassAtom ClassContents
  1. charSetをargument regexpRecordを伴うfirst ClassAtomCompileToCharSetとする。
  2. otherSetをargument regexpRecordを伴うsecond ClassAtomCompileToCharSetとする。
  3. remainingSetをargument regexpRecordを伴うClassContentsCompileToCharSetとする。
  4. rangeSetCharacterRange(charSet, otherSet)とする。
  5. rangeSetおよびremainingSetのunionを返す。
NonemptyClassRangesNoDash :: ClassAtomNoDash NonemptyClassRangesNoDash
  1. charSetをargument regexpRecordを伴うClassAtomNoDashCompileToCharSetとする。
  2. otherSetをargument regexpRecordを伴うNonemptyClassRangesNoDashCompileToCharSetとする。
  3. CharSets charSetおよびotherSetのunionを返す。
NonemptyClassRangesNoDash :: ClassAtomNoDash - ClassAtom ClassContents
  1. charSetをargument regexpRecordを伴うClassAtomNoDashCompileToCharSetとする。
  2. otherSetをargument regexpRecordを伴うClassAtomCompileToCharSetとする。
  3. remainingSetをargument regexpRecordを伴うClassContentsCompileToCharSetとする。
  4. rangeSetCharacterRange(charSet, otherSet)とする。
  5. rangeSetおよびremainingSetのunionを返す。
Note 2

ClassContentsは、single ClassAtom、および/またはdashesでseparatedされたtwo ClassAtomのrangesへexpandできます。後者の場合、ClassContentsはfirst ClassAtomとsecond ClassAtomの間にあるすべてのcharactersをinclusiveに含みます;いずれかのClassAtomがsingle characterをrepresentしない場合(例えば、一方が\wである場合)、またはfirst ClassAtomのcharacter valueがsecond ClassAtomのcharacter valueよりstrictly greaterである場合、errorが発生します。

Note 3

patternがcaseをignoreする場合でも、rangeのtwo endsのcaseは、どのcharactersがrangeに属するかをdetermineする上でsignificantです。したがって、例えば、pattern /[E-F]/iはletters EFe、およびfのみにmatchします。一方、pattern /[E-f]/iはUnicode Basic Latin block内のすべてのuppercaseおよびlowercase lettersに加えて、symbols [, \, ], ^, _, and `にもmatchします。

Note 4

- characterはliterallyに扱われることも、rangeをdenoteすることもできます。これは、ClassContentsのfirstまたはlast characterである場合、range specificationのbeginningまたはend limitである場合、またはrange specificationの直後にfollowする場合、literallyに扱われます。

ClassAtom :: -
  1. single character - U+002D (HYPHEN-MINUS)を含むCharSetを返す。
ClassAtomNoDash :: SourceCharacter but not one of \ or ] or -
  1. SourceCharacterにmatchedするcharacterを含むCharSetを返す。
ClassEscape :: b - CharacterEscape
  1. charValueをこのClassEscapeCharacterValueとする。
  2. charをcharacter valueがcharValueであるcharacterとする。
  3. single character charを含むCharSetを返す。
Note 5

ClassAtomは、\b\B、およびbackreferencesを除き、regular expressionのrestでallowedされる任意のescape sequencesを使用できます。CharacterClassの内側では、\bはbackspace characterを意味し、\Bおよびbackreferencesはerrorsをraiseします。ClassAtomの内側でbackreferenceを使用するとerrorが発生します。

CharacterClassEscape :: d
  1. characters 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9を含むten-element CharSetを返す。
CharacterClassEscape :: D
  1. charSet CharacterClassEscape :: d によってreturnedされるCharSetとする。
  2. CharacterComplement(regexpRecord, charSet)を返す。
CharacterClassEscape :: s
  1. WhiteSpaceまたはLineTerminator productionsのright-hand side上のcode pointに対応するすべてのcharactersを含むCharSetを返す。
CharacterClassEscape :: S
  1. charSet CharacterClassEscape :: s によってreturnedされるCharSetとする。
  2. CharacterComplement(regexpRecord, charSet)を返す。
CharacterClassEscape :: w
  1. MaybeSimpleCaseFolding(regexpRecord, WordCharacters(regexpRecord))を返す。
CharacterClassEscape :: W
  1. charSet CharacterClassEscape :: w によってreturnedされるCharSetとする。
  2. CharacterComplement(regexpRecord, charSet)を返す。
CharacterClassEscape :: p{ UnicodePropertyValueExpression }
  1. argument regexpRecordを伴うUnicodePropertyValueExpressionCompileToCharSetを返す。
CharacterClassEscape :: P{ UnicodePropertyValueExpression }
  1. charSetをargument regexpRecordを伴うUnicodePropertyValueExpressionCompileToCharSetとする。
  2. Assert: charSetはsingle code pointsのみを含む。
  3. CharacterComplement(regexpRecord, charSet)を返す。
UnicodePropertyValueExpression :: UnicodePropertyName = UnicodePropertyValue
  1. psUnicodePropertyNameにmatchedするsource textとする。
  2. pUnicodeMatchProperty(regexpRecord, ps)とする。
  3. Assert: pTable 65の“Property name and aliases” columnにlistedされているUnicode property nameまたはproperty aliasである。
  4. vsUnicodePropertyValueにmatchedするsource textとする。
  5. vUnicodeMatchPropertyValue(p, vs)とする。
  6. charSetを、character database definitionがproperty p with value vを含むすべてのUnicode code pointsを含むCharSetとする。
  7. MaybeSimpleCaseFolding(regexpRecord, charSet)を返す。
UnicodePropertyValueExpression :: LoneUnicodePropertyNameOrValue
  1. sLoneUnicodePropertyNameOrValueにmatchedするsource textとする。
  2. UnicodeMatchPropertyValue(General_Category, s)が、PropertyValueAliases.txtにlistedされているGeneral_Category (gc) propertyに対するUnicode property valueまたはproperty value aliasであるなら、
    1. “General_Category” property with value sをcharacter database definitionが含むすべてのUnicode code pointsを含むCharSetを返す。
  3. pUnicodeMatchProperty(regexpRecord, s)とする。
  4. Assert: pTable 66の“Property name and aliases” columnにlistedされているbinary Unicode propertyまたはbinary property alias、またはTable 67の“Property name” columnにlistedされているbinary Unicode property of stringsである。
  5. charSetを、character database definitionがproperty p with value “True”を含むすべてのCharSetElementsを含むCharSetとする。
  6. MaybeSimpleCaseFolding(regexpRecord, charSet)を返す。
ClassUnion :: ClassSetRange ClassUnionopt
  1. charSetをargument regexpRecordを伴うClassSetRangeCompileToCharSetとする。
  2. ClassUnionがpresentなら、
    1. otherSetをargument regexpRecordを伴うClassUnionCompileToCharSetとする。
    2. CharSets charSetおよびotherSetのunionを返す。
  3. charSetを返す。
ClassUnion :: ClassSetOperand ClassUnionopt
  1. charSetをargument regexpRecordを伴うClassSetOperandCompileToCharSetとする。
  2. ClassUnionがpresentなら、
    1. otherSetをargument regexpRecordを伴うClassUnionCompileToCharSetとする。
    2. CharSets charSetおよびotherSetのunionを返す。
  3. charSetを返す。
ClassIntersection :: ClassSetOperand && ClassSetOperand
  1. charSetをargument regexpRecordを伴うfirst ClassSetOperandCompileToCharSetとする。
  2. otherSetをargument regexpRecordを伴うsecond ClassSetOperandCompileToCharSetとする。
  3. CharSets charSetおよびotherSetのintersectionを返す。
ClassIntersection :: ClassIntersection && ClassSetOperand
  1. charSetをargument regexpRecordを伴うClassIntersectionCompileToCharSetとする。
  2. otherSetをargument regexpRecordを伴うClassSetOperandCompileToCharSetとする。
  3. CharSets charSetおよびotherSetのintersectionを返す。
ClassSubtraction :: ClassSetOperand -- ClassSetOperand
  1. charSetをargument regexpRecordを伴うfirst ClassSetOperandCompileToCharSetとする。
  2. otherSetをargument regexpRecordを伴うsecond ClassSetOperandCompileToCharSetとする。
  3. otherSetのCharSetElementsでもあるものを除いた、charSetのCharSetElementsを含むCharSetを返す。
ClassSubtraction :: ClassSubtraction -- ClassSetOperand
  1. charSetをargument regexpRecordを伴うClassSubtractionCompileToCharSetとする。
  2. otherSetをargument regexpRecordを伴うClassSetOperandCompileToCharSetとする。
  3. otherSetのCharSetElementsでもあるものを除いた、charSetのCharSetElementsを含むCharSetを返す。
ClassSetRange :: ClassSetCharacter - ClassSetCharacter
  1. charSetをargument regexpRecordを伴うfirst ClassSetCharacterCompileToCharSetとする。
  2. otherSetをargument regexpRecordを伴うsecond ClassSetCharacterCompileToCharSetとする。
  3. MaybeSimpleCaseFolding(regexpRecord, CharacterRange(charSet, otherSet))を返す。
Note 6

resultはしばしばtwo or more rangesから構成されます。UnicodeSetsがtrueでありIgnoreCaseがtrueである場合、MaybeSimpleCaseFolding(regexpRecord, [Ā-č])はそのrangeのodd-numbered code pointsのみを含みます。

ClassSetOperand :: ClassSetCharacter
  1. charSetをargument regexpRecordを伴うClassSetCharacterCompileToCharSetとする。
  2. MaybeSimpleCaseFolding(regexpRecord, charSet)を返す。
ClassSetOperand :: ClassStringDisjunction
  1. charSetをargument regexpRecordを伴うClassStringDisjunctionCompileToCharSetとする。
  2. MaybeSimpleCaseFolding(regexpRecord, charSet)を返す。
ClassSetOperand :: NestedClass
  1. argument regexpRecordを伴うNestedClassCompileToCharSetを返す。
NestedClass :: [ ClassContents ]
  1. argument regexpRecordを伴うClassContentsCompileToCharSetを返す。
NestedClass :: [^ ClassContents ]
  1. charSetをargument regexpRecordを伴うClassContentsCompileToCharSetとする。
  2. CharacterComplement(regexpRecord, charSet)を返す。
NestedClass :: \ CharacterClassEscape
  1. argument regexpRecordを伴うCharacterClassEscapeCompileToCharSetを返す。
ClassStringDisjunction :: \q{ ClassStringDisjunctionContents }
  1. argument regexpRecordを伴うClassStringDisjunctionContentsCompileToCharSetを返す。
ClassStringDisjunctionContents :: ClassString
  1. sをargument regexpRecordを伴うClassStringCompileClassSetStringとする。
  2. one string sを含むCharSetを返す。
ClassStringDisjunctionContents :: ClassString | ClassStringDisjunctionContents
  1. sをargument regexpRecordを伴うClassStringCompileClassSetStringとする。
  2. charSetをone string sを含むCharSetとする。
  3. otherSetをargument regexpRecordを伴うClassStringDisjunctionContentsCompileToCharSetとする。
  4. CharSets charSetおよびotherSetのunionを返す。
ClassSetCharacter :: SourceCharacter but not ClassSetSyntaxCharacter \ CharacterEscape \ ClassSetReservedPunctuator
  1. charValueをこのClassSetCharacterCharacterValueとする。
  2. charをcharacter valueがcharValueであるcharacterとする。
  3. single character charを含むCharSetを返す。
ClassSetCharacter :: \b
  1. single character U+0008 (BACKSPACE)を含むCharSetを返す。

22.2.2.9.1 CharacterRange ( charSet, otherSet )

The abstract operation CharacterRange takes arguments charSet (a CharSet) and otherSet (a CharSet) and returns a CharSet. It performs the following steps when called:

  1. Assert: charSetおよびotherSetはそれぞれexactly one characterを含む。
  2. aCharSet charSet内のone characterとする。
  3. bCharSet otherSet内のone characterとする。
  4. iをcharacter aのcharacter valueとする。
  5. jをcharacter bのcharacter valueとする。
  6. Assert: ijである。
  7. iからjまでのinclusive interval内のcharacter valueを持つすべてのcharactersを含むCharSetを返す。

22.2.2.9.2 HasEitherUnicodeFlag ( regexpRecord )

The abstract operation HasEitherUnicodeFlag takes argument regexpRecord (a RegExp Record) and returns a Boolean. It performs the following steps when called:

  1. regexpRecord.[[Unicode]]trueまたはregexpRecord.[[UnicodeSets]]trueなら、trueを返す。
  2. falseを返す。

22.2.2.9.3 WordCharacters ( regexpRecord )

The abstract operation WordCharacters takes argument regexpRecord (a RegExp Record) and returns a CharSet. \b\B\w、および\Wのpurposesにおいて“word characters”とconsideredされるcharactersを含むCharSetを返します。 It performs the following steps when called:

  1. basicWordCharsをASCII word characters内のすべてのcharacterを含むCharSetとする。
  2. extraWordCharsを、basicWordChars内にないがCanonicalize(regexpRecord, c)がbasicWordChars内にあるようなすべてのcharacters cを含むCharSetとする。
  3. Assert: HasEitherUnicodeFlag(regexpRecord)がtrueかつregexpRecord.[[IgnoreCase]]trueでない限り、extraWordCharsはemptyである。
  4. basicWordCharsおよびextraWordCharsのunionを返す。

22.2.2.9.4 AllCharacters ( regexpRecord )

The abstract operation AllCharacters takes argument regexpRecord (a RegExp Record) and returns a CharSet. regular expression flagsに従った“all characters”のsetを返します。 It performs the following steps when called:

  1. regexpRecord.[[UnicodeSets]]trueであり、かつregexpRecord.[[IgnoreCase]]trueなら、
    1. Simple Case Folding mappingを持たない(すなわち、scf(c)=cである)すべてのUnicode code points cを含むCharSetを返す。
  2. HasEitherUnicodeFlag(regexpRecord)がtrueなら、
    1. すべてのcode point valuesを含むCharSetを返す。
  3. すべてのcode unit valuesを含むCharSetを返す。

22.2.2.9.5 MaybeSimpleCaseFolding ( regexpRecord, charSet )

The abstract operation MaybeSimpleCaseFolding takes arguments regexpRecord (a RegExp Record) and charSet (a CharSet) and returns a CharSet. regexpRecord.[[UnicodeSets]]falseまたはregexpRecord.[[IgnoreCase]]falseである場合、charSetを返します。そうでなければ、Unicode Character Databaseのfile CaseFolding.txt内のSimple Case Foldingscf(codePoint))definitions(それぞれsingle code pointをanother single code pointへmapする)を使用して、charSetの各CharSetElementをcharacter-by-characterにcanonical formへmapし、resulting CharSetを返します。 It performs the following steps when called:

  1. regexpRecord.[[UnicodeSets]]falseまたはregexpRecord.[[IgnoreCase]]falseなら、charSetを返す。
  2. otherSetをnew empty CharSetとする。
  3. charSetの各CharSetElement sについて、以下を行う
    1. tをcharactersのempty sequenceとする。
    2. s内の各single code point codePointについて、以下を行う
      1. scf(codePoint)をtへappendする。
    3. totherSetへaddする。
  4. otherSetを返す。

22.2.2.9.6 CharacterComplement ( regexpRecord, complement )

The abstract operation CharacterComplement takes arguments regexpRecord (a RegExp Record) and complement (a CharSet) and returns a CharSet. It performs the following steps when called:

  1. charSetAllCharacters(regexpRecord)とする。
  2. complementのCharSetElementsでもあるものを除いた、charSetのCharSetElementsを含むCharSetを返す。

22.2.2.9.7 UnicodeMatchProperty ( regexpRecord, p )

The abstract operation UnicodeMatchProperty takes arguments regexpRecord (a RegExp Record) and p (ECMAScript source text) and returns a Unicode property name. It performs the following steps when called:

  1. regexpRecord.[[UnicodeSets]]trueであり、かつpTable 67の“Property name” columnにlistedされているUnicode property nameであるなら、
    1. Unicode code points pListを返す。
  2. Assert: pTable 65またはTable 66の“Property name and aliases” columnにlistedされているUnicode property nameまたはproperty aliasである。
  3. cを、corresponding rowの“Canonical property name” columnでgivenされたpのcanonical property nameとする。
  4. Unicode code points cListを返す。

Implementationsは、Table 65Table 66、およびTable 67にlistedされているUnicode property namesおよびaliasesをsupportしなければなりません。interoperabilityをensureするため、implementationsは他のproperty namesまたはaliasesをsupportしてはなりません。

Note 1

例えば、Script_Extensionsproperty name)およびscx(property alias)はvalidですが、script_extensionsScxはvalidではありません。

Note 2

listed propertiesは、UTS18 RL1.2がrequireするもののsupersetを形成します。

Note 3

これらのtables内のentriesのspellings(casingを含む)は、Unicode Character Databaseのfile PropertyAliases.txtで使用されるspellingsとmatchします。そのfile内のprecise spellingsはstableであることがguaranteedされています

Table 65: Non-binary Unicode property aliases and their canonical property names
Property name and aliases Canonical property name
General_Category General_Category
gc
Script Script
sc
Script_Extensions Script_Extensions
scx
Table 66: Binary Unicode property aliases and their canonical property names
Property name and aliases Canonical property name
ASCII ASCII
ASCII_Hex_Digit ASCII_Hex_Digit
AHex
Alphabetic Alphabetic
Alpha
Any Any
Assigned Assigned
Bidi_Control Bidi_Control
Bidi_C
Bidi_Mirrored Bidi_Mirrored
Bidi_M
Case_Ignorable Case_Ignorable
CI
Cased Cased
Changes_When_Casefolded Changes_When_Casefolded
CWCF
Changes_When_Casemapped Changes_When_Casemapped
CWCM
Changes_When_Lowercased Changes_When_Lowercased
CWL
Changes_When_NFKC_Casefolded Changes_When_NFKC_Casefolded
CWKCF
Changes_When_Titlecased Changes_When_Titlecased
CWT
Changes_When_Uppercased Changes_When_Uppercased
CWU
Dash Dash
Default_Ignorable_Code_Point Default_Ignorable_Code_Point
DI
Deprecated Deprecated
Dep
Diacritic Diacritic
Dia
Emoji Emoji
Emoji_Component Emoji_Component
EComp
Emoji_Modifier Emoji_Modifier
EMod
Emoji_Modifier_Base Emoji_Modifier_Base
EBase
Emoji_Presentation Emoji_Presentation
EPres
Extended_Pictographic Extended_Pictographic
ExtPict
Extender Extender
Ext
Grapheme_Base Grapheme_Base
Gr_Base
Grapheme_Extend Grapheme_Extend
Gr_Ext
Hex_Digit Hex_Digit
Hex
IDS_Binary_Operator IDS_Binary_Operator
IDSB
IDS_Trinary_Operator IDS_Trinary_Operator
IDST
ID_Continue ID_Continue
IDC
ID_Start ID_Start
IDS
Ideographic Ideographic
Ideo
Join_Control Join_Control
Join_C
Logical_Order_Exception Logical_Order_Exception
LOE
Lowercase Lowercase
Lower
Math Math
Noncharacter_Code_Point Noncharacter_Code_Point
NChar
Pattern_Syntax Pattern_Syntax
Pat_Syn
Pattern_White_Space Pattern_White_Space
Pat_WS
Quotation_Mark Quotation_Mark
QMark
Radical Radical
Regional_Indicator Regional_Indicator
RI
Sentence_Terminal Sentence_Terminal
STerm
Soft_Dotted Soft_Dotted
SD
Terminal_Punctuation Terminal_Punctuation
Term
Unified_Ideograph Unified_Ideograph
UIdeo
Uppercase Uppercase
Upper
Variation_Selector Variation_Selector
VS
White_Space White_Space
space
XID_Continue XID_Continue
XIDC
XID_Start XID_Start
XIDS
Table 67: Binary Unicode properties of strings
Property name
Basic_Emoji
Emoji_Keycap_Sequence
RGI_Emoji_Modifier_Sequence
RGI_Emoji_Flag_Sequence
RGI_Emoji_Tag_Sequence
RGI_Emoji_ZWJ_Sequence
RGI_Emoji

22.2.2.9.8 UnicodeMatchPropertyValue ( p, v )

The abstract operation UnicodeMatchPropertyValue takes arguments p (ECMAScript source text) and v (ECMAScript source text) and returns a Unicode property value. It performs the following steps when called:

  1. Assert: pTable 65の“Canonical property name” columnにlistedされているcanonicalかつunaliasedなUnicode property nameである。
  2. Assert: vはUnicode property pに対するproperty valueまたはproperty value aliasであり、PropertyValueAliases.txtにlistedされている。
  3. valueを、corresponding rowの“Canonical property value” columnでgivenされたvのcanonical property valueとする。
  4. Unicode code points valueListを返す。

Implementationsは、Table 65にlistedされているpropertiesについて、PropertyValueAliases.txtにlistedされているUnicode property valuesおよびproperty value aliasesをsupportしなければなりません。interoperabilityをensureするため、implementationsは他のproperty valuesまたはproperty value aliasesをsupportしてはなりません。

Note 1

例えば、XpeoおよびOld_PersianはvalidなScript_Extensions valuesですが、xpeoおよびOld Persianはvalidではありません。

Note 2

このalgorithmはUAX44にlistedされているsymbolic valuesのmatching rulesとは異なります:case、white space、U+002D (HYPHEN-MINUS)、およびU+005F (LOW LINE)はignoredされず、Is prefixはsupportされません。

22.2.2.10 Runtime Semantics: CompileClassSetString

The syntax-directed operation CompileClassSetString takes argument regexpRecord (a RegExp Record) and returns a sequence of characters. It is defined piecewise over the following productions:

ClassString :: [empty]
  1. charactersのempty sequenceを返す。
ClassString :: NonEmptyClassString
  1. argument regexpRecordを伴うNonEmptyClassStringCompileClassSetStringを返す。
NonEmptyClassString :: ClassSetCharacter NonEmptyClassStringopt
  1. csをargument regexpRecordを伴うClassSetCharacterCompileToCharSetとする。
  2. s1を、csのsingle CharSetElementであるcharactersのsequenceとする。
  3. NonEmptyClassStringがpresentなら、
    1. s2をargument regexpRecordを伴うNonEmptyClassStringCompileClassSetStringとする。
    2. s1s2のconcatenationを返す。
  4. s1を返す。

22.2.3 Abstract Operations for RegExp Creation

22.2.3.1 RegExpCreate ( pattern, flags )

The abstract operation RegExpCreate takes arguments pattern (an ECMAScript language value) and flags (a String or undefined) and returns either a normal completion containing an Object or a throw completion. It performs the following steps when called:

  1. objを ! RegExpAlloc(%RegExp%) とする。
  2. RegExpInitialize(obj, pattern, flags)を返す。

22.2.3.2 RegExpAlloc ( newTarget )

The abstract operation RegExpAlloc takes argument newTarget (a constructor) and returns either a normal completion containing an Object or a throw completion. It performs the following steps when called:

  1. objを ? OrdinaryCreateFromConstructor(newTarget, "%RegExp.prototype%", « [[OriginalSource]], [[OriginalFlags]], [[RegExpRecord]], [[RegExpMatcher]] ») とする。
  2. DefinePropertyOrThrow(obj, "lastIndex", PropertyDescriptor { [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false })を実行する。
  3. objを返す。

22.2.3.3 RegExpInitialize ( obj, pattern, flags )

The abstract operation RegExpInitialize takes arguments obj (an Object), pattern (an ECMAScript language value), and flags (an ECMAScript language value) and returns either a normal completion containing an Object or a throw completion. It performs the following steps when called:

  1. patternundefinedなら、patternをempty Stringに設定する。
  2. そうでなければ、patternを ? ToString(pattern) に設定する。
  3. flagsundefinedなら、flagsをempty Stringに設定する。
  4. そうでなければ、flagsを ? ToString(flags) に設定する。
  5. flags"d""g""i""m""s""u""v"、または"y"以外のcode unitを含むなら、SyntaxError例外をthrowする。
  6. flagsが同じcode unitを複数回含むなら、SyntaxError例外をthrowする。
  7. flags"i"を含むなら、itrueとする;そうでなければ、ifalseとする。
  8. flags"m"を含むなら、mtrueとする;そうでなければ、mfalseとする。
  9. flags"s"を含むなら、strueとする;そうでなければ、sfalseとする。
  10. flags"u"を含むなら、utrueとする;そうでなければ、ufalseとする。
  11. flags"v"を含むなら、vtrueとする;そうでなければ、vfalseとする。
  12. utrueまたはvtrueなら、
    1. patternTextStringToCodePoints(pattern)とする。
  13. そうでなければ、
    1. patternTextを、patternの各16-bit elementをUnicode BMP code pointとしてinterpretingしたresultとする。UTF-16 decodingはelementsにapplyされない。
  14. parseResultParsePattern(patternText, u, v)とする。
  15. parseResultSyntaxError objectsのnon-empty Listなら、SyntaxError例外をthrowする。
  16. Assert: parseResultPattern Parse Nodeである。
  17. obj.[[OriginalSource]]patternに設定する。
  18. obj.[[OriginalFlags]]flagsに設定する。
  19. capturingGroupsCountCountLeftCapturingParensWithin(parseResult)とする。
  20. regexpRecordRegExp Record { [[IgnoreCase]]: i, [[Multiline]]: m, [[DotAll]]: s, [[Unicode]]: u, [[UnicodeSets]]: v, [[CapturingGroupsCount]]: capturingGroupsCount }とする。
  21. obj.[[RegExpRecord]]regexpRecordに設定する。
  22. obj.[[RegExpMatcher]]を、argument regexpRecordを伴うparseResultCompilePatternに設定する。
  23. Set(obj, "lastIndex", +0𝔽, true)を実行する。
  24. objを返す。

22.2.3.4 Static Semantics: ParsePattern ( patternText, u, v )

The abstract operation ParsePattern takes arguments patternText (a sequence of Unicode code points), u (a Boolean), and v (a Boolean) and returns a Parse Node or a non-empty List of SyntaxError objects.

Note

このsectionはB.1.2.9でamendedされます。

It performs the following steps when called:

  1. vtrueであり、かつutrueなら、
    1. parseResultを、one or more SyntaxError objectsを含むListとする。
  2. そうでなく、vtrueなら、
    1. parseResultParseText(patternText, Pattern[+UnicodeMode, +UnicodeSetsMode, +NamedCaptureGroups])とする。
  3. そうでなく、utrueなら、
    1. parseResultParseText(patternText, Pattern[+UnicodeMode, ~UnicodeSetsMode, +NamedCaptureGroups])とする。
  4. そうでなければ、
    1. parseResultParseText(patternText, Pattern[~UnicodeMode, ~UnicodeSetsMode, +NamedCaptureGroups])とする。
  5. parseResultを返す。

22.2.4 The RegExp Constructor

RegExp constructorは:

  • %RegExp%です。
  • global object"RegExp" propertyのinitial valueです。
  • constructorとして呼び出されたとき、新しいRegExp objectを作成およびinitializeします。
  • constructorとしてではなくfunctionとして呼び出されたとき、新しいRegExp object、またはonly argumentがRegExp objectである場合はargument自体のいずれかを返します。
  • class definitionのextends clauseのvalueとして使用できます。指定されたRegExp behaviourをinheritしようとするsubclass constructorsは、必要なinternal slotsを持つsubclass instancesを作成およびinitializeするために、RegExp constructorへのsuper callを含まなければなりません。

22.2.4.1 RegExp ( patternOrRegexp, flags )

このfunctionは呼び出されたとき、次のstepsを実行します:

  1. patternIsRegExpを ? IsRegExp(patternOrRegexp) とする。
  2. NewTargetがundefinedなら、
    1. newTargetactive function objectとする。
    2. patternIsRegExptrueであり、かつflagsundefinedなら、
      1. patternCtorを ? Get(patternOrRegexp, "constructor") とする。
      2. SameValue(newTarget, patternCtor)がtrueなら、patternOrRegexpを返す。
  3. そうでなければ、
    1. newTargetをNewTargetとする。
  4. patternOrRegexpがObjectであり、かつpatternOrRegexp[[RegExpMatcher]] internal slotを持つなら、
    1. patternSourcepatternOrRegexp.[[OriginalSource]]とする。
    2. flagsundefinedなら、flagspatternOrRegexp.[[OriginalFlags]]に設定する。
  5. そうでなく、patternIsRegExptrueなら、
    1. patternSourceを ? Get(patternOrRegexp, "source") とする。
    2. flagsundefinedなら、
      1. flagsを ? Get(patternOrRegexp, "flags") に設定する。
  6. そうでなければ、
    1. patternSourcepatternOrRegexpとする。
  7. objを ? RegExpAlloc(newTarget) とする。
  8. RegExpInitialize(obj, patternSource, flags)を返す。
Note

patternがStringLiteralを使用してsuppliedされる場合、Stringがこのfunctionによってprocessedされる前にusual escape sequence substitutionsがperformedされます。patternがこのfunctionによってrecognizedされるためにescape sequenceを含まなければならない場合、StringLiteralのcontentsがformedされるときにU+005C (REVERSE SOLIDUS) code pointsがremovedされることをpreventするため、任意のU+005C (REVERSE SOLIDUS) code pointsはStringLiteral内でescapedされなければなりません。

22.2.5 Properties of the RegExp Constructor

RegExp constructorは:

  • valueが%Function.prototype%である[[Prototype]] internal slotを持ちます。
  • 次のpropertiesを持ちます:

22.2.5.1 RegExp.escape ( string )

このfunctionは、regular expression Pattern内でpotentially specialであるcharactersがequivalent escape sequencesで置き換えられたstringのcopyを返します。

これは呼び出されたとき、次のstepsを実行します:

  1. stringがStringでないなら、TypeError例外をthrowする。
  2. escapedをempty Stringとする。
  3. codePointListStringToCodePoints(string)とする。
  4. codePointListの各code point codePointについて、以下を行う
    1. escapedがempty Stringであり、かつcodePointDecimalDigitまたはAsciiLetterのいずれかによってmatchedされるなら、
      1. NOTE: leading digitをescapeすると、outputが、\0 character escapeまたは\1のようなDecimalEscapeの後に使用され得るpattern textに対応し、preceding escape sequenceのextensionとしてinterpretedされるのではなく、なおstringにmatchすることをensureする。leading ASCII letterをescapeすることは、\cの後のcontextについて同じことを行う。
      2. numericValuecodePointのnumeric valueとする。
      3. hexNumber::toString(𝔽(numericValue), 16)とする。
      4. Assert: hexのlengthは2である。
      5. escapedをcode unit 0x005C (REVERSE SOLIDUS)、"x"、およびhexstring-concatenationに設定する。
    2. そうでなければ、
      1. escapedescapedEncodeForRegExpEscape(codePoint)のstring-concatenationに設定する。
  5. escapedを返す。
Note

similar namesを持つにもかかわらず、EscapeRegExpPatternRegExp.escapeはsimilar actionsをperformしません。前者はstringとしてrepresentationするためにpatternをescapeし、このfunctionはpatternの内側でrepresentationするためにstringをescapeします。

22.2.5.1.1 EncodeForRegExpEscape ( codePoint )

The abstract operation EncodeForRegExpEscape takes argument codePoint (a code point) and returns a String. これはcodePointにmatchingするためのPatternを表すStringを返します。codePointがwhite spaceまたはASCII punctuatorである場合、returned valueはescape sequenceです。そうでなければ、returned valueはcodePoint自体のString representationです。 It performs the following steps when called:

  1. codePointSyntaxCharacterによってmatchedされる、またはcodePointがU+002F (SOLIDUS)であるなら、
    1. 0x005C (REVERSE SOLIDUS)とUTF16EncodeCodePoint(codePoint)のstring-concatenationを返す。
  2. codePointTable 63の“Code Point” columnにlistedされているcode pointなら、
    1. 0x005C (REVERSE SOLIDUS)と、“Code Point” columnがcodePointを含むrowの“ControlEscape” column内のstringのstring-concatenationを返す。
  3. otherPunctuators",-=<>#&!%:;@~'`"とcode unit 0x0022 (QUOTATION MARK)のstring-concatenationとする。
  4. toEscapeStringToCodePoints(otherPunctuators)とする。
  5. toEscapecodePointを含む、codePointWhiteSpaceまたはLineTerminatorのいずれかによってmatchedされる、またはcodePointleading surrogateまたはtrailing surrogateとsame numeric valueを持つなら、
    1. codePointNumbercodePointのnumeric valueとする。
    2. codePointNumber ≤ 0xFFなら、
      1. hexNumber::toString(𝔽(codePointNumber), 16)とする。
      2. code unit 0x005C (REVERSE SOLIDUS)、"x"、およびStringPad(hex, 2, "0", start)のstring-concatenationを返す。
    3. escapedをempty Stringとする。
    4. codeUnitsUTF16EncodeCodePoint(codePoint)とする。
    5. codeUnitsの各code unit codeUnitについて、以下を行う
      1. escapedescapedUnicodeEscape(codeUnit)のstring-concatenationに設定する。
    6. escapedを返す。
  6. UTF16EncodeCodePoint(codePoint)を返す。

22.2.5.2 RegExp.prototype

RegExp.prototypeのinitial valueはRegExp prototype objectです。

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

22.2.5.3 get RegExp [ %Symbol.species% ]

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

  1. this valueを返す。

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

Note

RegExp prototype methodsは通常、そのthis valueのconstructorを使用してderived objectを作成します。しかし、subclass constructorは、その%Symbol.species% propertyをredefiningすることにより、そのdefault behaviourをover-rideしてもよいです。

22.2.6 Properties of the RegExp Prototype Object

RegExp prototype objectは:

  • %RegExp.prototype%です。
  • ordinary objectです。
  • RegExp instanceではなく、[[RegExpMatcher]] internal slotも、RegExp instance objectsの他のinternal slotsも持ちません。
  • valueが%Object.prototype%である[[Prototype]] internal slotを持ちます。
Note

RegExp prototype objectは自身の"valueOf" propertyを持ちません;しかし、Object prototype objectから"valueOf" propertyをinheritします。

22.2.6.1 RegExp.prototype.constructor

RegExp.prototype.constructorのinitial valueは%RegExp%です。

22.2.6.2 RegExp.prototype.exec ( string )

このmethodはstring内でregular expression patternのoccurrenceをsearchし、matchのresultsを含むArrayを返すか、stringがmatchしなかった場合はnullを返します。

これは呼び出されたとき、次のstepsを実行します:

  1. regexpthis valueとする。
  2. RequireInternalSlot(regexp, [[RegExpMatcher]])を実行する。
  3. stringを ? ToString(string) に設定する。
  4. RegExpBuiltinExec(regexp, string)を返す。

22.2.6.3 get RegExp.prototype.dotAll

RegExp.prototype.dotAllは、set accessor functionがundefinedであるaccessor propertyです。そのget accessor functionは呼び出されたとき、次のstepsを実行します:

  1. regexpthis valueとする。
  2. codeUnitをcode unit 0x0073 (LATIN SMALL LETTER S)とする。
  3. RegExpHasFlag(regexp, codeUnit)を返す。

22.2.6.4 get RegExp.prototype.flags

RegExp.prototype.flagsは、set accessor functionがundefinedであるaccessor propertyです。そのget accessor functionは呼び出されたとき、次のstepsを実行します:

  1. regexpthis valueとする。
  2. regexpがObjectでないなら、TypeError例外をthrowする。
  3. codeUnitsを新しい空のListとする。
  4. hasIndicesToBoolean(? Get(regexp, "hasIndices" ))とする。
  5. hasIndicestrueなら、code unit 0x0064 (LATIN SMALL LETTER D)をcodeUnitsへappendする。
  6. globalToBoolean(? Get(regexp, "global" ))とする。
  7. globaltrueなら、code unit 0x0067 (LATIN SMALL LETTER G)をcodeUnitsへappendする。
  8. ignoreCaseToBoolean(? Get(regexp, "ignoreCase" ))とする。
  9. ignoreCasetrueなら、code unit 0x0069 (LATIN SMALL LETTER I)をcodeUnitsへappendする。
  10. multilineToBoolean(? Get(regexp, "multiline" ))とする。
  11. multilinetrueなら、code unit 0x006D (LATIN SMALL LETTER M)をcodeUnitsへappendする。
  12. dotAllToBoolean(? Get(regexp, "dotAll" ))とする。
  13. dotAlltrueなら、code unit 0x0073 (LATIN SMALL LETTER S)をcodeUnitsへappendする。
  14. unicodeToBoolean(? Get(regexp, "unicode" ))とする。
  15. unicodetrueなら、code unit 0x0075 (LATIN SMALL LETTER U)をcodeUnitsへappendする。
  16. unicodeSetsToBoolean(? Get(regexp, "unicodeSets" ))とする。
  17. unicodeSetstrueなら、code unit 0x0076 (LATIN SMALL LETTER V)をcodeUnitsへappendする。
  18. stickyToBoolean(? Get(regexp, "sticky" ))とする。
  19. stickytrueなら、code unit 0x0079 (LATIN SMALL LETTER Y)をcodeUnitsへappendする。
  20. code unitsがList codeUnitsのelementsであるString valueを返す。codeUnitsがelementsを持たない場合、empty Stringが返される。

22.2.6.4.1 RegExpHasFlag ( regexp, codeUnit )

The abstract operation RegExpHasFlag takes arguments regexp (an ECMAScript language value) and codeUnit (a code unit) and returns either a normal completion containing either a Boolean or undefined, or a throw completion. It performs the following steps when called:

  1. regexpがObjectでないなら、TypeError例外をthrowする。
  2. regexp[[OriginalFlags]] internal slotを持たないなら、
    1. SameValue(regexp, %RegExp.prototype%)がtrueなら、undefinedを返す。
    2. TypeError例外をThrowする。
  3. flagsregexp.[[OriginalFlags]]とする。
  4. flagscodeUnitを含むなら、trueを返す。
  5. falseを返す。

22.2.6.5 get RegExp.prototype.global

RegExp.prototype.globalは、set accessor functionがundefinedであるaccessor propertyです。そのget accessor functionは呼び出されたとき、次のstepsを実行します:

  1. regexpthis valueとする。
  2. codeUnitをcode unit 0x0067 (LATIN SMALL LETTER G)とする。
  3. RegExpHasFlag(regexp, codeUnit)を返す。

22.2.6.6 get RegExp.prototype.hasIndices

RegExp.prototype.hasIndicesは、set accessor functionがundefinedであるaccessor propertyです。そのget accessor functionは呼び出されたとき、次のstepsを実行します:

  1. regexpthis valueとする。
  2. codeUnitをcode unit 0x0064 (LATIN SMALL LETTER D)とする。
  3. RegExpHasFlag(regexp, codeUnit)を返す。

22.2.6.7 get RegExp.prototype.ignoreCase

RegExp.prototype.ignoreCaseは、set accessor functionがundefinedであるaccessor propertyです。そのget accessor functionは呼び出されたとき、次のstepsを実行します:

  1. regexpthis valueとする。
  2. codeUnitをcode unit 0x0069 (LATIN SMALL LETTER I)とする。
  3. RegExpHasFlag(regexp, codeUnit)を返す。

22.2.6.8 RegExp.prototype [ %Symbol.match% ] ( string )

このmethodは呼び出されたとき、次のstepsを実行します:

  1. regexpthis valueとする。
  2. regexpがObjectでないなら、TypeError例外をthrowする。
  3. stringを ? ToString(string) に設定する。
  4. flagsを ? ToString(? Get(regexp, "flags" )) とする。
  5. flags"g"を含まないなら、? RegExpExec(regexp, string)を返す。
  6. flags"u"を含む、またはflags"v"を含むなら、fullUnicodetrueとする;そうでなければ、fullUnicodefalseとする。
  7. Set(regexp, "lastIndex", +0𝔽, true)を実行する。
  8. arrayを ! ArrayCreate(0) とする。
  9. matchCountを0とする。
  10. 繰り返す:
    1. resultを ? RegExpExec(regexp, string) とする。
    2. resultnullなら、
      1. matchCount = 0なら、nullを返す。
      2. arrayを返す。
    3. matchStringを ? ToString(? Get(result, "0" )) とする。
    4. CreateDataPropertyOrThrow(array, ! ToString(𝔽(matchCount)), matchString)を実行する。
    5. matchStringがempty Stringなら、
      1. thisIndex(? ToLength(? Get(regexp, "lastIndex")))とする。
      2. nextIndexAdvanceStringIndex(string, thisIndex, fullUnicode)とする。
      3. Set(regexp, "lastIndex", 𝔽(nextIndex), true)を実行する。
    6. matchCountmatchCount + 1に設定する。

このmethodの"name" propertyのvalueは"[Symbol.match]"です。

Note

%Symbol.match% propertyは、regular expressionsのbasic behaviourを持つobjectsをidentifyするためにIsRegExp abstract operationによって使用されます。%Symbol.match% propertyのabsence、またはそのようなpropertyが存在するがそのvalueがBoolean coerceしてtrueにならない場合、そのobjectがregular expression objectとして使用されることを意図していないことを示します。

22.2.6.9 RegExp.prototype [ %Symbol.matchAll% ] ( string )

このmethodは呼び出されたとき、次のstepsを実行します:

  1. regexpthis valueとする。
  2. regexpがObjectでないなら、TypeError例外をthrowする。
  3. stringを ? ToString(string) に設定する。
  4. speciesCtorを ? SpeciesConstructor(regexp, %RegExp%) とする。
  5. flagsを ? ToString(? Get(regexp, "flags" )) とする。
  6. matcherを ? Construct(speciesCtor, « regexp, flags ») とする。
  7. lastIndexを ? ToLength(? Get(regexp, "lastIndex" )) とする。
  8. Set(matcher, "lastIndex", lastIndex, true)を実行する。
  9. flags"g"を含むなら、globaltrueとする。
  10. そうでなければ、globalfalseとする。
  11. flags"u"を含む、またはflags"v"を含むなら、fullUnicodetrueとする。
  12. そうでなければ、fullUnicodefalseとする。
  13. CreateRegExpStringIterator(matcher, string, global, fullUnicode)を返す。

このmethodの"name" propertyのvalueは"[Symbol.matchAll]"です。

22.2.6.10 get RegExp.prototype.multiline

RegExp.prototype.multilineは、set accessor functionがundefinedであるaccessor propertyです。そのget accessor functionは呼び出されたとき、次のstepsを実行します:

  1. regexpthis valueとする。
  2. codeUnitをcode unit 0x006D (LATIN SMALL LETTER M)とする。
  3. RegExpHasFlag(regexp, codeUnit)を返す。

22.2.6.11 RegExp.prototype [ %Symbol.replace% ] ( string, replaceValue )

このmethodは呼び出されたとき、次のstepsを実行します:

  1. regexpthis valueとする。
  2. regexpがObjectでないなら、TypeError例外をthrowする。
  3. stringを ? ToString(string) に設定する。
  4. stringLengthstringのlengthとする。
  5. functionalReplaceIsCallable(replaceValue)とする。
  6. functionalReplacefalseなら、
    1. replaceValueを ? ToString(replaceValue) に設定する。
  7. flagsを ? ToString(? Get(regexp, "flags" )) とする。
  8. flags"g"を含むなら、globaltrueとする;そうでなければ、globalfalseとする。
  9. globaltrueなら、
    1. Set(regexp, "lastIndex", +0𝔽, true)を実行する。
  10. resultsを新しい空のListとする。
  11. donefalseとする。
  12. donefalseである間、繰り返す
    1. resultを ? RegExpExec(regexp, string) とする。
    2. resultnullなら、
      1. donetrueに設定する。
    3. そうでなければ、
      1. resultresultsへappendする。
      2. globalfalseなら、
        1. donetrueに設定する。
      3. そうでなければ、
        1. matchStringを ? ToString(? Get(result, "0" )) とする。
        2. matchStringがempty Stringなら、
          1. thisIndex(? ToLength(? Get(regexp, "lastIndex")))とする。
          2. flags"u"を含む、またはflags"v"を含むなら、fullUnicodetrueとする;そうでなければ、fullUnicodefalseとする。
          3. nextIndexAdvanceStringIndex(string, thisIndex, fullUnicode)とする。
          4. Set(regexp, "lastIndex", 𝔽(nextIndex), true)を実行する。
  13. accumulatedResultをempty Stringとする。
  14. nextSourcePositionを0とする。
  15. resultsの各要素resultについて、以下を行う
    1. resultLengthを ? LengthOfArrayLike(result) とする。
    2. capturesCountmax(resultLength - 1, 0)とする。
    3. matchedを ? ToString(? Get(result, "0" )) とする。
    4. matchLengthmatchedのlengthとする。
    5. positionを ? ToIntegerOrInfinity(? Get(result, "index" )) とする。
    6. positionを、0とstringLengthの間にclampingしたresultに設定する。
    7. capturesを新しい空のListとする。
    8. captureNumberを1とする。
    9. captureNumbercapturesCountの間、繰り返す
      1. captureを ? Get(result, ! ToString(𝔽(captureNumber))) とする。
      2. captureundefinedでないなら、
        1. captureを ? ToString(capture) に設定する。
      3. capturecapturesへappendする。
      4. NOTE: captureNumber = 1のとき、preceding stepはfirst elementをcapturesへputする(index 0に)。より一般に、captureNumberth capture(captureNumberth set of capturing parenthesesによってcapturedされたcharacters)はcaptures[captureNumber - 1]にある。
      5. captureNumbercaptureNumber + 1に設定する。
    10. namedCapturesを ? Get(result, "groups" ) とする。
    11. functionalReplacetrueなら、
      1. replacerArgsを« matched »、captures、および« 𝔽(position), string »のlist-concatenationとする。
      2. namedCapturesundefinedでないなら、
        1. namedCapturesreplacerArgsへappendする。
      3. replacementValueを ? Call(replaceValue, undefined, replacerArgs) とする。
      4. replacementStringを ? ToString(replacementValue) とする。
    12. そうでなければ、
      1. namedCapturesundefinedでないなら、
        1. namedCapturesを ? ToObject(namedCaptures) に設定する。
      2. replacementStringを ? GetSubstitution(matched, string, position, captures, namedCaptures, replaceValue) とする。
    13. positionnextSourcePositionなら、
      1. NOTE: positionは通常backwardsにmoveすべきではない。そうなる場合、それはill-behaving RegExp subclass、またはregexpのglobal flagやその他のcharacteristicsをchangeするためのaccess triggered side-effectの使用を示す。そのようなcasesでは、corresponding substitutionはignoredされる。
      2. accumulatedResultを、accumulatedResultstringnextSourcePositionからpositionまでのsubstring、およびreplacementStringstring-concatenationに設定する。
      3. nextSourcePositionposition + matchLengthに設定する。
  16. nextSourcePositionstringLengthなら、accumulatedResultを返す。
  17. accumulatedResultstringnextSourcePositionからのsubstringstring-concatenationを返す。

このmethodの"name" propertyのvalueは"[Symbol.replace]"です。

22.2.6.12 RegExp.prototype [ %Symbol.search% ] ( string )

このmethodは呼び出されたとき、次のstepsを実行します:

  1. regexpthis valueとする。
  2. regexpがObjectでないなら、TypeError例外をthrowする。
  3. stringを ? ToString(string) に設定する。
  4. previousLastIndexを ? Get(regexp, "lastIndex" ) とする。
  5. previousLastIndex+0𝔽でないなら、
    1. Set(regexp, "lastIndex", +0𝔽, true)を実行する。
  6. resultを ? RegExpExec(regexp, string) とする。
  7. currentLastIndexを ? Get(regexp, "lastIndex" ) とする。
  8. SameValue(currentLastIndex, previousLastIndex)がfalseなら、
    1. Set(regexp, "lastIndex", previousLastIndex, true)を実行する。
  9. resultnullなら、-1𝔽を返す。
  10. Get(result, "index" )を返す。

このmethodの"name" propertyのvalueは"[Symbol.search]"です。

Note

このRegExp objectの"lastIndex"および"global" propertiesのvalueは、searchをperformするときignoredされます。"lastIndex" propertyはunchangedのままです。

22.2.6.13 get RegExp.prototype.source

RegExp.prototype.sourceは、set accessor functionがundefinedであるaccessor propertyです。そのget accessor functionは呼び出されたとき、次のstepsを実行します:

  1. regexpthis valueとする。
  2. regexpがObjectでないなら、TypeError例外をthrowする。
  3. regexp[[OriginalSource]] internal slotを持たないなら、
    1. SameValue(regexp, %RegExp.prototype%)がtrueなら、"(?:)"を返す。
    2. TypeError例外をThrowする。
  4. Assert: regexp[[OriginalFlags]] internal slotを持つ。
  5. sourceregexp.[[OriginalSource]]とする。
  6. flagsregexp.[[OriginalFlags]]とする。
  7. EscapeRegExpPattern(source, flags)を返す。

22.2.6.13.1 EscapeRegExpPattern ( pattern, flags )

The abstract operation EscapeRegExpPattern takes arguments pattern (a String) and flags (a String) and returns a String. It performs the following steps when called:

  1. flags"v"を含むなら、
    1. patternSymbolPattern[+UnicodeMode, +UnicodeSetsMode]とする。
  2. そうでなく、flags"u"を含むなら、
    1. patternSymbolPattern[+UnicodeMode, ~UnicodeSetsMode]とする。
  3. そうでなければ、
    1. patternSymbolPattern[~UnicodeMode, ~UnicodeSetsMode]とする。
  4. escapedPatternを、UTF-16 encoded Unicode code points(6.1.4)としてinterpretedされたpatternにequivalentなpatternSymbolのformのStringとする。この中では、certain code pointsが以下でdescribedされる通りescapedされます。escapedPatternpatternとdifferしてもよいしdifferしなくてもよい;しかし、escapedPatternpatternSymbolとしてevaluatingすることでresultするAbstract Closureは、constructed objectの[[RegExpMatcher]] internal slotによってgivenされるAbstract Closureとidenticallyにbehaveしなければなりません。このabstract operationをpatternおよびflagsのsame valuesでmultiple callsすると、identical resultsをproduceしなければなりません。
  5. pattern内にoccurringするcode points /または任意のLineTerminatorは、" / "ではなく"/"escapedPattern"/"、およびflagsstring-concatenationが(appropriate lexical contextにおいて)constructed regular expressionとidenticallyにbehaveするRegularExpressionLiteralとしてparseできることをensureするため、必要に応じてescapedPattern内でescapedされなければなりません。例えば、pattern"/"なら、escapedPattern"\/"または"\u002F"などであり得ますが、"/"ではあり得ません。なぜなら、flagsがfollowする///RegularExpressionLiteralではなくSingleLineCommentとしてparseされるからです。patternがempty Stringなら、このspecificationはescapedPattern"(?:)"とすることで満たされ得ます。
  6. escapedPatternを返す。
Note

similar namesを持つにもかかわらず、RegExp.escapeとEscapeRegExpPatternはsimilar actionsをperformしません。前者はpatternの内側でrepresentationするためにstringをescapeし、このfunctionはstringとしてrepresentationするためにpatternをescapeします。

22.2.6.14 RegExp.prototype [ %Symbol.split% ] ( string, limit )

Note 1

このmethodは、stringをStringへconvertingしたresultのsubstringsがstoredされたArrayを返します。substringsは、this value regular expressionのmatchesをleft to rightにsearchすることでdeterminedされます;これらのoccurrencesはreturned array内のいかなるStringのpartでもありませんが、String valueをdivide upする役割を果たします。

this valueはempty regular expression、またはempty Stringにmatchできるregular expressionであり得ます。このcaseでは、regular expressionはinput Stringのbeginningまたはendにあるempty substringにはmatchせず、previous separator matchのendにあるempty substringにもmatchしません。(例えば、regular expressionがempty Stringにmatchする場合、Stringはindividual code unit elementsへsplit upされます;result arrayのlengthはStringのlengthに等しく、各substringはone code unitを含みます。)given index of the Stringにおけるfirst matchのみがconsideredされます。backtrackingによってそのindexでnon-empty substring matchがyieldされ得る場合であってもです。(例えば、/a*?/[Symbol.split]("ab")はarray ["a", "b"]へevaluatesされ、一方/a*/[Symbol.split]("ab")はarray ["","b"]へevaluatesされます。)

stringがempty Stringである(またはそれへconvertsされる)場合、resultはregular expressionがempty Stringにmatchできるかどうかに依存します。matchできる場合、result arrayはelementsを含みません。そうでなければ、result arrayはone elementを含み、それはempty Stringです。

regular expressionがcapturing parenthesesを含む場合、separatorがmatchedされるたびに、capturing parenthesesのresults(任意のundefined resultsを含む)がoutput arrayへsplicedされます。例えば、

/<(\/)?([^<>]+)>/[Symbol.split]("A<B>bold</B>and<CODE>coded</CODE>")

はarrayへevaluatesされます:

["A", undefined, "B", "bold", "/", "B", "and", undefined, "CODE", "coded", "/", "CODE", ""]

limitundefinedでない場合、output arrayはlimit elements以下を含むようにtruncatedされます。

このmethodは呼び出されたとき、次のstepsを実行します:

  1. regexpthis valueとする。
  2. regexpがObjectでないなら、TypeError例外をthrowする。
  3. stringを ? ToString(string) に設定する。
  4. speciesCtorを ? SpeciesConstructor(regexp, %RegExp%) とする。
  5. flagsを ? ToString(? Get(regexp, "flags" )) とする。
  6. flags"u"を含む、またはflags"v"を含むなら、unicodeMatchingtrueとする。
  7. そうでなければ、unicodeMatchingfalseとする。
  8. flags"y"を含むなら、newFlagsflagsとする。
  9. そうでなければ、newFlagsflags"y"string-concatenationとする。
  10. splitterを ? Construct(speciesCtor, « regexp, newFlags ») とする。
  11. arrayを ! ArrayCreate(0) とする。
  12. lengthAを0とする。
  13. limitundefinedなら、limを232 - 1とする;そうでなければ、lim(? ToUint32(limit))とする。
  14. lim = 0なら、arrayを返す。
  15. stringがempty Stringなら、
    1. matchResultを ? RegExpExec(splitter, string) とする。
    2. matchResultnullでないなら、arrayを返す。
    3. CreateDataPropertyOrThrow(array, "0", string)を実行する。
    4. arrayを返す。
  16. sizestringのlengthとする。
  17. lastMatchEndを0とする。
  18. searchIndexlastMatchEndとする。
  19. searchIndex < sizeの間、繰り返す
    1. Set(splitter, "lastIndex", 𝔽(searchIndex), true)を実行する。
    2. matchResultを ? RegExpExec(splitter, string) とする。
    3. matchResultnullなら、
      1. searchIndexAdvanceStringIndex(string, searchIndex, unicodeMatching)に設定する。
    4. そうでなければ、
      1. matchEnd(? ToLength(? Get(splitter, "lastIndex")))とする。
      2. matchEndmin(matchEnd, size)に設定する。
      3. matchEnd = lastMatchEndなら、
        1. searchIndexAdvanceStringIndex(string, searchIndex, unicodeMatching)に設定する。
      4. そうでなければ、
        1. substringstringlastMatchEndからsearchIndexまでのsubstringとする。
        2. CreateDataPropertyOrThrow(array, ! ToString(𝔽(lengthA)), substring)を実行する。
        3. lengthAlengthA + 1に設定する。
        4. lengthA = limなら、arrayを返す。
        5. lastMatchEndmatchEndに設定する。
        6. numberOfCapturesを ? LengthOfArrayLike(matchResult) とする。
        7. numberOfCapturesmax(numberOfCaptures - 1, 0)に設定する。
        8. captureIndexを1とする。
        9. captureIndexnumberOfCapturesの間、繰り返す
          1. nextCaptureを ? Get(matchResult, ! ToString(𝔽(captureIndex))) とする。
          2. CreateDataPropertyOrThrow(array, ! ToString(𝔽(lengthA)), nextCapture)を実行する。
          3. captureIndexcaptureIndex + 1に設定する。
          4. lengthAlengthA + 1に設定する。
          5. lengthA = limなら、arrayを返す。
        10. searchIndexlastMatchEndに設定する。
  20. substringstringlastMatchEndからsizeまでのsubstringとする。
  21. CreateDataPropertyOrThrow(array, ! ToString(𝔽(lengthA)), substring)を実行する。
  22. arrayを返す。

このmethodの"name" propertyのvalueは"[Symbol.split]"です。

Note 2

このmethodは、このRegExp objectの"global"および"sticky" propertiesのvalueをignoreします。

22.2.6.15 get RegExp.prototype.sticky

RegExp.prototype.stickyは、set accessor functionがundefinedであるaccessor propertyです。そのget accessor functionは呼び出されたとき、次のstepsを実行します:

  1. regexpthis valueとする。
  2. codeUnitをcode unit 0x0079 (LATIN SMALL LETTER Y)とする。
  3. RegExpHasFlag(regexp, codeUnit)を返す。

22.2.6.16 RegExp.prototype.test ( string )

このmethodは呼び出されたとき、次のstepsを実行します:

  1. regexpthis valueとする。
  2. regexpがObjectでないなら、TypeError例外をthrowする。
  3. stringを ? ToString(string) に設定する。
  4. matchを ? RegExpExec(regexp, string) とする。
  5. matchnullなら、falseを返す。
  6. trueを返す。

22.2.6.17 RegExp.prototype.toString ( )

  1. regexpthis valueとする。
  2. regexpがObjectでないなら、TypeError例外をthrowする。
  3. patternを ? ToString(? Get(regexp, "source" )) とする。
  4. flagsを ? ToString(? Get(regexp, "flags" )) とする。
  5. result"/"pattern"/"、およびflagsstring-concatenationとする。
  6. resultを返す。
Note

returned Stringは、このobjectとsame behaviourを持つanother RegExp objectへevaluatesされるRegularExpressionLiteralのformを持ちます。

22.2.6.18 get RegExp.prototype.unicode

RegExp.prototype.unicodeは、set accessor functionがundefinedであるaccessor propertyです。そのget accessor functionは呼び出されたとき、次のstepsを実行します:

  1. regexpthis valueとする。
  2. codeUnitをcode unit 0x0075 (LATIN SMALL LETTER U)とする。
  3. RegExpHasFlag(regexp, codeUnit)を返す。

22.2.6.19 get RegExp.prototype.unicodeSets

RegExp.prototype.unicodeSetsは、set accessor functionがundefinedであるaccessor propertyです。そのget accessor functionは呼び出されたとき、次のstepsを実行します:

  1. regexpthis valueとする。
  2. codeUnitをcode unit 0x0076 (LATIN SMALL LETTER V)とする。
  3. RegExpHasFlag(regexp, codeUnit)を返す。

22.2.7 Abstract Operations for RegExp Matching

22.2.7.1 RegExpExec ( regexp, string )

The abstract operation RegExpExec takes arguments regexp (an Object) and string (a String) and returns either a normal completion containing either an Object or null, or a throw completion. It performs the following steps when called:

  1. execを ? Get(regexp, "exec") とする。
  2. IsCallable(exec)がtrueなら、
    1. resultを ? Call(exec, regexp, « string ») とする。
    2. resultがObjectでなく、かつresultnullでないなら、TypeError例外をthrowする。
    3. resultを返す。
  3. RequireInternalSlot(regexp, [[RegExpMatcher]])を実行する。
  4. RegExpBuiltinExec(regexp, string)を返す。
Note

callableな"exec" propertyが見つからない場合、このalgorithmはbuilt-in RegExp matching algorithmの使用を試みることへfall backします。これは、regular expressionsを使用するmost built-in algorithmsが"exec"のdynamic property lookupをperformしなかったprior editions向けに書かれたcodeに対してcompatible behaviourを提供します。

22.2.7.2 RegExpBuiltinExec ( regexp, string )

The abstract operation RegExpBuiltinExec takes arguments regexp (an initialized RegExp instance) and string (a String) and returns either a normal completion containing either an Array exotic object or null, or a throw completion. It performs the following steps when called:

  1. lengthstringのlengthとする。
  2. lastIndex(? ToLength(! Get(regexp, "lastIndex")))とする。
  3. flagsregexp.[[OriginalFlags]]とする。
  4. flags"g"を含むなら、globaltrueとする;そうでなければ、globalfalseとする。
  5. flags"y"を含むなら、stickytrueとする;そうでなければ、stickyfalseとする。
  6. flags"d"を含むなら、hasIndicestrueとする;そうでなければ、hasIndicesfalseとする。
  7. globalfalseであり、かつstickyfalseなら、lastIndexを0に設定する。
  8. matcherregexp.[[RegExpMatcher]]とする。
  9. flags"u"を含む、またはflags"v"を含むなら、fullUnicodetrueとする;そうでなければ、fullUnicodefalseとする。
  10. matchSucceededfalseとする。
  11. fullUnicodetrueなら、inputStringToCodePoints(string)とする;そうでなければ、inputを、そのelementsがstringのelementsであるcode unitsであるListとする。
  12. NOTE: inputの各elementはcharacterであるとconsiderされる。
  13. matchSucceededfalseである間、繰り返す
    1. lastIndex > lengthなら、
      1. globaltrueまたはstickytrueなら、
        1. Set(regexp, "lastIndex", +0𝔽, true)を実行する。
      2. nullを返す。
    2. inputIndexを、stringのelement lastIndexからobtainedされたcharacterのinput内のindexとする。
    3. resultmatcher(input, inputIndex)とする。
    4. resultfailureなら、
      1. stickytrueなら、
        1. Set(regexp, "lastIndex", +0𝔽, true)を実行する。
        2. nullを返す。
      2. lastIndexAdvanceStringIndex(string, lastIndex, fullUnicode)に設定する。
    5. そうでなければ、
      1. Assert: resultMatchStateである。
      2. matchSucceededtrueに設定する。
  14. endIndexresult.[[EndIndex]]とする。
  15. fullUnicodetrueなら、endIndexGetStringIndex(string, endIndex)に設定する。
  16. globaltrueまたはstickytrueなら、
    1. Set(regexp, "lastIndex", 𝔽(endIndex), true)を実行する。
  17. capturingGroupsCountresult.[[Captures]]内のelementsの数とする。
  18. Assert: capturingGroupsCount = regexp.[[RegExpRecord]].[[CapturingGroupsCount]]である。
  19. Assert: capturingGroupsCount < 232 - 1である。
  20. arrayを ! ArrayCreate(capturingGroupsCount + 1) とする。
  21. Assert: array"length" propertyのmathematical valuecapturingGroupsCount + 1である。
  22. CreateDataPropertyOrThrow(array, "index", 𝔽(lastIndex))を実行する。
  23. CreateDataPropertyOrThrow(array, "input", string)を実行する。
  24. matchMatch Record { [[StartIndex]]: lastIndex, [[EndIndex]]: endIndex }とする。
  25. indicesを新しい空のListとする。
  26. groupNamesを新しい空のListとする。
  27. matchindicesへappendする。
  28. matchedSubstringGetMatchString(string, match)とする。
  29. CreateDataPropertyOrThrow(array, "0", matchedSubstring)を実行する。
  30. regexpが任意のGroupNameを含むなら、
    1. groupsOrdinaryObjectCreate(null)とする。
    2. hasGroupstrueとする。
  31. そうでなければ、
    1. groupsundefinedとする。
    2. hasGroupsfalseとする。
  32. CreateDataPropertyOrThrow(array, "groups", groups)を実行する。
  33. matchedGroupNamesを新しい空のListとする。
  34. 1 ≤ icapturingGroupsCountである各integer iについて、ascending orderで、以下を行う
    1. captureresult.[[Captures]]ith elementとする。
    2. captureundefinedなら、
      1. capturedValueundefinedとする。
      2. undefinedindicesへappendする。
    3. そうでなければ、
      1. captureStartcapture.[[StartIndex]]とする。
      2. captureEndcapture.[[EndIndex]]とする。
      3. fullUnicodetrueなら、
        1. captureStartGetStringIndex(string, captureStart)に設定する。
        2. captureEndGetStringIndex(string, captureEnd)に設定する。
      4. captureRecordMatch Record { [[StartIndex]]: captureStart, [[EndIndex]]: captureEnd }とする。
      5. capturedValueGetMatchString(string, captureRecord)とする。
      6. captureRecordindicesへappendする。
    4. CreateDataPropertyOrThrow(array, ! ToString(𝔽(i)), capturedValue)を実行する。
    5. regexpith captureがGroupNameでdefinedされていたなら、
      1. groupNameをそのGroupNameCapturingGroupNameとする。
      2. matchedGroupNamesgroupNameを含むなら、
        1. Assert: capturedValueundefinedである。
        2. undefinedgroupNamesへappendする。
      3. そうでなければ、
        1. capturedValueundefinedでないなら、groupNamematchedGroupNamesへappendする。
        2. NOTE: groupNameとnamedされたmultiple groupsが存在する場合、groupsはこの時点ですでにgroupName propertyを持っている可能性がある。しかし、groupsは、そのpropertiesがすべてwritable data propertiesであるordinary objectであるため、CreateDataPropertyOrThrowへのcallはそれでもsucceedすることがguaranteedされる。
        3. CreateDataPropertyOrThrow(groups, groupName, capturedValue)を実行する。
        4. groupNamegroupNamesへappendする。
    6. そうでなければ、
      1. undefinedgroupNamesへappendする。
  35. hasIndicestrueなら、
    1. indicesArrayMakeMatchIndicesIndexPairArray(string, indices, groupNames, hasGroups)とする。
    2. CreateDataPropertyOrThrow(array, "indices", indicesArray)を実行する。
  36. arrayを返す。

22.2.7.3 AdvanceStringIndex ( string, index, unicode )

The abstract operation AdvanceStringIndex takes arguments string (a String), index (a non-negative integer), and unicode (a Boolean) and returns a non-negative integer. It performs the following steps when called:

  1. Assert: index ≤ 253 - 1である。
  2. unicodefalseなら、index + 1を返す。
  3. lengthstringのlengthとする。
  4. index + 1 ≥ lengthなら、index + 1を返す。
  5. codePointCodePointAt(string, index)とする。
  6. index + codePoint.[[CodeUnitCount]]を返す。

22.2.7.4 GetStringIndex ( string, codePointIndex )

The abstract operation GetStringIndex takes arguments string (a String) and codePointIndex (a non-negative integer) and returns a non-negative integer. これは、6.1.4でdescribedされる通り、stringをUTF-16 encoded code pointsのsequenceとしてinterpretし、そのようなindexが存在する場合、code point index codePointIndexに対応するcode unit indexを返します。そうでなければ、stringのlengthを返します。 It performs the following steps when called:

  1. stringがempty Stringなら、0を返す。
  2. lengthstringのlengthとする。
  3. codeUnitCountを0とする。
  4. codePointCountを0とする。
  5. codeUnitCount < lengthの間、繰り返す
    1. codePointCount = codePointIndexなら、codeUnitCountを返す。
    2. codePointCodePointAt(string, codeUnitCount)とする。
    3. codeUnitCountcodeUnitCount + codePoint.[[CodeUnitCount]]に設定する。
    4. codePointCountcodePointCount + 1に設定する。
  6. lengthを返す。

22.2.7.5 Match Records

Match Recordは、regular expression matchまたはcaptureのstartおよびend indicesをencapsulateするために使用されるRecord valueです。

Match RecordsはTable 68にlistedされたfieldsを持ちます。

Table 68: Match Record Fields
Field Name Value Meaning
[[StartIndex]] a non-negative integer matchがbeginする(inclusive)stringのstartからのcode unitsの数。
[[EndIndex]] an integer[[StartIndex]] matchがendする(exclusive)stringのstartからのcode unitsの数。

22.2.7.6 GetMatchString ( string, match )

The abstract operation GetMatchString takes arguments string (a String) and match (a Match Record) and returns a String. It performs the following steps when called:

  1. Assert: match.[[StartIndex]]match.[[EndIndex]]stringのlengthである。
  2. stringmatch.[[StartIndex]]からmatch.[[EndIndex]]までのsubstringを返す。

22.2.7.7 GetMatchIndexPair ( string, match )

The abstract operation GetMatchIndexPair takes arguments string (a String) and match (a Match Record) and returns an Array. It performs the following steps when called:

  1. Assert: match.[[StartIndex]]match.[[EndIndex]]stringのlengthである。
  2. CreateArrayFromList𝔽(match.[[StartIndex]]), 𝔽(match.[[EndIndex]]) »)を返す。

22.2.7.8 MakeMatchIndicesIndexPairArray ( string, indices, groupNames, hasGroups )

The abstract operation MakeMatchIndicesIndexPairArray takes arguments string (a String), indices (a List of either Match Records or undefined), groupNames (a List of either Strings or undefined), and hasGroups (a Boolean) and returns an Array. It performs the following steps when called:

  1. nindices内のelementsの数とする。
  2. Assert: n < 232 - 1である。
  3. Assert: groupNamesn - 1個のelementsを持つ。
  4. NOTE: groupNames Listindices[1]からstartingしてindices Listとalignedされたelementsを含む。
  5. arrayを ! ArrayCreate(n) とする。
  6. hasGroupstrueなら、
    1. groupsOrdinaryObjectCreate(null)とする。
  7. そうでなければ、
    1. groupsundefinedとする。
  8. CreateDataPropertyOrThrow(array, "groups", groups)を実行する。
  9. 0 ≤ i < nである各integer iについて、ascending orderで、以下を行う
    1. matchIndicesindices[i]とする。
    2. matchIndicesundefinedでないなら、
      1. matchIndexPairGetMatchIndexPair(string, matchIndices)とする。
    3. そうでなければ、
      1. matchIndexPairundefinedとする。
    4. CreateDataPropertyOrThrow(array, ! ToString(𝔽(i)), matchIndexPair)を実行する。
    5. i > 0なら、
      1. namegroupNames[i - 1]とする。
      2. nameundefinedでないなら、
        1. Assert: groupsundefinedでない。
        2. NOTE: nameとnamedされたmultiple groupsが存在する場合、groupsはこの時点ですでにname propertyを持っている可能性がある。しかし、groupsは、そのpropertiesがすべてwritable data propertiesであるordinary objectであるため、CreateDataPropertyOrThrowへのcallはそれでもsucceedすることがguaranteedされる。
        3. CreateDataPropertyOrThrow(groups, name, matchIndexPair)を実行する。
  10. arrayを返す。

22.2.8 Properties of RegExp Instances

RegExp instancesはRegExp prototype objectからpropertiesをinheritするordinary objectsです。RegExp instancesはinternal slots [[OriginalSource]], [[OriginalFlags]], [[RegExpRecord]], および[[RegExpMatcher]]を持ちます。[[RegExpMatcher]] internal slotのvalueは、RegExp objectのPatternAbstract Closure representationです。

Note

ECMAScript 2015より前は、RegExp instancesはown data properties "source""global""ignoreCase"、および"multiline"を持つものとしてspecifiedされていました。現在、それらのpropertiesはRegExp.prototypeaccessor propertiesとしてspecifiedされています。

RegExp instancesはまた次のpropertyを持ちます:

22.2.8.1 lastIndex

"lastIndex" propertyのvalueは、next matchをstartするString indexをspecifyします。これは使用時にintegral Numberへcoercedされます(22.2.7.2を参照)。このpropertyはattributes { [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false }を持たなければなりません。

22.2.9 RegExp String Iterator Objects

RegExp String Iteratorは、some specific RegExp instance objectに対してmatchingしながら、some specific String instance object上のspecific iterationを表すobjectです。RegExp String Iterator objectsにはnamed constructorは存在しません。代わりに、RegExp String Iterator objectsはRegExp instance objectsのcertain methodsを呼び出すことで作成されます。

22.2.9.1 CreateRegExpStringIterator ( regexp, string, global, fullUnicode )

The abstract operation CreateRegExpStringIterator takes arguments regexp (an Object), string (a String), global (a Boolean), and fullUnicode (a Boolean) and returns an Object. It performs the following steps when called:

  1. iteratorOrdinaryObjectCreate(%RegExpStringIteratorPrototype%, « [[IteratingRegExp]], [[IteratedString]], [[Global]], [[Unicode]], [[Done]] »)とする。
  2. iterator.[[IteratingRegExp]]regexpに設定する。
  3. iterator.[[IteratedString]]stringに設定する。
  4. iterator.[[Global]]globalに設定する。
  5. iterator.[[Unicode]]fullUnicodeに設定する。
  6. iterator.[[Done]]falseに設定する。
  7. iteratorを返す。

22.2.9.2 The %RegExpStringIteratorPrototype% Object

%RegExpStringIteratorPrototype% objectは:

22.2.9.2.1 %RegExpStringIteratorPrototype%.next ( )

  1. iteratorObjthis valueとする。
  2. iteratorObjがObjectでないなら、TypeError例外をthrowする。
  3. iteratorObjRegExp String Iterator Object Instanceのすべてのinternal slotsを持たないなら(22.2.9.3を参照)、TypeError例外をthrowする。
  4. iteratorObj.[[Done]]trueなら、
    1. CreateIteratorResultObject(undefined, true)を返す。
  5. regexpiteratorObj.[[IteratingRegExp]]とする。
  6. stringiteratorObj.[[IteratedString]]とする。
  7. globaliteratorObj.[[Global]]とする。
  8. fullUnicodeiteratorObj.[[Unicode]]とする。
  9. matchを ? RegExpExec(regexp, string) とする。
  10. matchnullなら、
    1. iteratorObj.[[Done]]trueに設定する。
    2. CreateIteratorResultObject(undefined, true)を返す。
  11. globalfalseなら、
    1. iteratorObj.[[Done]]trueに設定する。
    2. CreateIteratorResultObject(match, false)を返す。
  12. matchStringを ? ToString(? Get(match, "0")) とする。
  13. matchStringがempty Stringなら、
    1. thisIndex(? ToLength(? Get(regexp, "lastIndex")))とする。
    2. nextIndexAdvanceStringIndex(string, thisIndex, fullUnicode)とする。
    3. Set(regexp, "lastIndex", 𝔽(nextIndex), true)を実行する。
  14. CreateIteratorResultObject(match, false)を返す。

22.2.9.2.2 %RegExpStringIteratorPrototype% [ %Symbol.toStringTag% ]

%Symbol.toStringTag% propertyのinitial valueはString value "RegExp String Iterator"です。

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

22.2.9.3 Properties of RegExp String Iterator Instances

RegExp String Iterator instancesは、%RegExpStringIteratorPrototype% intrinsic objectからpropertiesをinheritするordinary objectsです。RegExp String Iterator instancesは、Table 69にlistedされたinternal slotsを持ってinitiallyに作成されます。

Table 69: Internal Slots of RegExp String Iterator Instances
Internal Slot Type Description
[[IteratingRegExp]] an Object iterationに使用されるregular expression。IsRegExp([[IteratingRegExp]])はinitially trueです。
[[IteratedString]] a String iterateされているString value。
[[Global]] a Boolean [[IteratingRegExp]]がglobalであるかどうかを示します。
[[Unicode]] a Boolean [[IteratingRegExp]]がUnicode modeであるかどうかを示します。
[[Done]] a Boolean iterationがcompleteしているかどうかを示します。

23 Indexed Collections

23.1 Array Objects

Arraysは、あるclassのproperty namesにspecial treatmentを与えるexotic objectsです。このspecial treatmentのdefinitionについては、10.4.2を参照してください。

23.1.1 The Array Constructor

Array constructorは:

  • %Array%です。
  • global object"Array" propertyのinitial valueです。
  • constructorとして呼び出されたとき、新しいArrayを作成およびinitializeします。
  • constructorとしてではなくfunctionとして呼び出されたときも、新しいArrayを作成およびinitializeします。したがって、function call Array(…)は、same argumentsを伴うobject creation expression new Array(…)とequivalentです。
  • argumentsの数およびtypesに基づいてbehaviourが異なるfunctionです。
  • class definitionのextends clauseのvalueとして使用できます。exotic Array behaviourをinheritしようとするsubclass constructorsは、Array exotic objectsであるsubclass instancesをinitializeするために、Array constructorへのsuper callを含まなければなりません。しかし、Array.prototype methodsのほとんどは、そのthis valueがArray exotic objectであることに依存しないgeneric methodsです。

23.1.1.1 Array ( ...values )

このfunctionは呼び出されたとき、次のstepsを実行します:

  1. NewTargetがundefinedなら、newTargetactive function objectとする;そうでなければ、newTargetをNewTargetとする。
  2. protoを ? GetPrototypeFromConstructor(newTarget, "%Array.prototype%") とする。
  3. numberOfArgsvalues内のelementsの数とする。
  4. numberOfArgs = 0なら、! ArrayCreate(0, proto)を返す。
  5. numberOfArgs = 1なら、
    1. lengthvalues[0]とする。
    2. arrayを ! ArrayCreate(0, proto) とする。
    3. lengthがNumberでないなら、
      1. CreateDataPropertyOrThrow(array, "0", length)を実行する。
      2. intLength1𝔽とする。
    4. そうでなければ、
      1. intLengthを ! ToUint32(length) とする。
      2. SameValueZero(intLength, length)がfalseなら、RangeError例外をthrowする。
    5. Set(array, "length", intLength, true)を実行する。
    6. arrayを返す。
  6. Assert: numberOfArgs ≥ 2である。
  7. arrayを ? ArrayCreate(numberOfArgs, proto) とする。
  8. kを0とする。
  9. k < numberOfArgsの間、繰り返す
    1. propertyKeyを ! ToString(𝔽(k)) とする。
    2. itemKvalues[k]とする。
    3. CreateDataPropertyOrThrow(array, propertyKey, itemK)を実行する。
    4. kk + 1に設定する。
  10. Assert: array"length" propertyのmathematical valuenumberOfArgsである。
  11. arrayを返す。

23.1.2 Properties of the Array Constructor

Array constructorは:

  • valueが%Function.prototype%である[[Prototype]] internal slotを持ちます。
  • valueが1𝔽である"length" propertyを持ちます。
  • 次のpropertiesを持ちます:

23.1.2.1 Array.from ( items [ , mapper [ , thisArg ] ] )

このfunctionは呼び出されたとき、次のstepsを実行します:

  1. ctorthis valueとする。
  2. mapperundefinedなら、
    1. mappingfalseとする。
  3. そうでなければ、
    1. IsCallable(mapper)がfalseなら、TypeError例外をthrowする。
    2. mappingtrueとする。
  4. usingIteratorを ? GetMethod(items, %Symbol.iterator%) とする。
  5. usingIteratorundefinedでないなら、
    1. IsConstructor(ctor)がtrueなら、
      1. arrayを ? Construct(ctor) とする。
    2. そうでなければ、
      1. arrayを ! ArrayCreate(0) とする。
    3. iteratorRecordを ? GetIteratorFromMethod(items, usingIterator) とする。
    4. kを0とする。
    5. 繰り返す:
      1. k ≥ 253 - 1なら、
        1. errorThrowCompletion(a newly created TypeError object)とする。
        2. IteratorClose(iteratorRecord, error)を返す。
      2. propertyKeyを ! ToString(𝔽(k)) とする。
      3. nextを ? IteratorStepValue(iteratorRecord) とする。
      4. nextdoneなら、
        1. Set(array, "length", 𝔽(k), true)を実行する。
        2. arrayを返す。
      5. mappingtrueなら、
        1. mappedValueCompletion(Call(mapper, thisArg, « next, 𝔽(k) »))とする。
        2. IfAbruptCloseIterator(mappedValue, iteratorRecord).
      6. そうでなければ、
        1. mappedValuenextとする。
      7. defineStatusCompletion(CreateDataPropertyOrThrow(array, propertyKey, mappedValue))とする。
      8. IfAbruptCloseIterator(defineStatus, iteratorRecord).
      9. kk + 1に設定する。
  6. NOTE: itemsiterableでないため、array-like objectであるとassumeする。
  7. arrayLikeを ! ToObject(items) とする。
  8. lengthを ? LengthOfArrayLike(arrayLike) とする。
  9. IsConstructor(ctor)がtrueなら、
    1. arrayを ? Construct(ctor, « 𝔽(length) ») とする。
  10. そうでなければ、
    1. arrayを ? ArrayCreate(length) とする。
  11. kを0とする。
  12. k < lengthの間、繰り返す
    1. propertyKeyを ! ToString(𝔽(k)) とする。
    2. kValueを ? Get(arrayLike, propertyKey) とする。
    3. mappingtrueなら、
      1. mappedValueを ? Call(mapper, thisArg, « kValue, 𝔽(k) ») とする。
    4. そうでなければ、
      1. mappedValuekValueとする。
    5. CreateDataPropertyOrThrow(array, propertyKey, mappedValue)を実行する。
    6. kk + 1に設定する。
  13. Set(array, "length", 𝔽(length), true)を実行する。
  14. arrayを返す。
Note

このmethodは意図的にgenericなfactory methodです;そのthis valueがArray constructorであることをrequireしません。したがって、single numeric argumentで呼び出され得るany other constructorsへtransferまたはinheritできます。

23.1.2.2 Array.fromAsync ( items [ , mapper [ , thisArg ] ] )

このasync functionは呼び出されたとき、次のstepsを実行します:

  1. ctorthis valueとする。
  2. mappingfalseとする。
  3. mapperundefinedでないなら、
    1. IsCallable(mapper)がfalseなら、TypeError例外をthrowする。
    2. mappingtrueに設定する。
  4. iteratorRecordundefinedとする。
  5. usingAsyncIteratorを ? GetMethod(items, %Symbol.asyncIterator%) とする。
  6. usingAsyncIteratorundefinedなら、
    1. usingSyncIteratorを ? GetMethod(items, %Symbol.iterator%) とする。
    2. usingSyncIteratorundefinedでないなら、
      1. iteratorRecordCreateAsyncFromSyncIterator(? GetIteratorFromMethod(items, usingSyncIterator))に設定する。
  7. そうでなければ、
    1. iteratorRecordを ? GetIteratorFromMethod(items, usingAsyncIterator) に設定する。
  8. iteratorRecordundefinedでないなら、
    1. IsConstructor(ctor)がtrueなら、
      1. arrayを ? Construct(ctor) とする。
    2. そうでなければ、
      1. arrayを ! ArrayCreate(0) とする。
    3. kを0とする。
    4. 繰り返す:
      1. k ≥ 253 - 1なら、
        1. errorThrowCompletion(a newly created TypeError object)とする。
        2. AsyncIteratorClose(iteratorRecord, error)を返す。
      2. propertyKeyを ! ToString(𝔽(k)) とする。
      3. nextResultを ? Call(iteratorRecord.[[NextMethod]], iteratorRecord.[[Iterator]]) とする。
      4. nextResultを ? Await(nextResult) に設定する。
      5. nextResultがObjectでないなら、TypeError例外をthrowする。
      6. doneを ? IteratorComplete(nextResult) とする。
      7. donetrueなら、
        1. Set(array, "length", 𝔽(k), true)を実行する。
        2. arrayを返す。
      8. nextValueを ? IteratorValue(nextResult) とする。
      9. mappingtrueなら、
        1. mappedValueCompletion(Call(mapper, thisArg, « nextValue, 𝔽(k) »))とする。
        2. IfAbruptCloseAsyncIterator(mappedValue, iteratorRecord).
        3. mappedValueCompletion(Await(mappedValue))に設定する。
        4. IfAbruptCloseAsyncIterator(mappedValue, iteratorRecord).
      10. そうでなければ、
        1. mappedValuenextValueとする。
      11. defineStatusCompletion(CreateDataPropertyOrThrow(array, propertyKey, mappedValue))とする。
      12. IfAbruptCloseAsyncIterator(defineStatus, iteratorRecord).
      13. kk + 1に設定する。
  9. そうでなければ、
    1. NOTE: itemsasync iterableでもiterableでもないため、array-like objectであるとassumeする。
    2. arrayLikeを ! ToObject(items) とする。
    3. lengthを ? LengthOfArrayLike(arrayLike) とする。
    4. IsConstructor(ctor)がtrueなら、
      1. arrayを ? Construct(ctor, « 𝔽(length) ») とする。
    5. そうでなければ、
      1. arrayを ? ArrayCreate(length) とする。
    6. kを0とする。
    7. k < lengthの間、繰り返す
      1. propertyKeyを ! ToString(𝔽(k)) とする。
      2. kValueを ? Get(arrayLike, propertyKey) とする。
      3. kValueを ? Await(kValue) に設定する。
      4. mappingtrueなら、
        1. mappedValueを ? Call(mapper, thisArg, « kValue, 𝔽(k) ») とする。
        2. mappedValueを ? Await(mappedValue) に設定する。
      5. そうでなければ、
        1. mappedValuekValueとする。
      6. CreateDataPropertyOrThrow(array, propertyKey, mappedValue)を実行する。
      7. kk + 1に設定する。
    8. Set(array, "length", 𝔽(length), true)を実行する。
    9. arrayを返す。
Note

このmethodは意図的にgenericなfactory methodです;そのthis valueがArray constructorであることをrequireしません。したがって、single numeric argumentで呼び出され得るany other constructorsへtransferまたはinheritできます。

23.1.2.3 Array.isArray ( arg )

このfunctionは呼び出されたとき、次のstepsを実行します:

  1. IsArray(arg)を返す。

23.1.2.4 Array.of ( ...items )

このmethodは呼び出されたとき、次のstepsを実行します:

  1. lengthitems内のelementsの数とする。
  2. lengthNumber𝔽(length)とする。
  3. ctorthis valueとする。
  4. IsConstructor(ctor)がtrueなら、
    1. arrayを ? Construct(ctor, « lengthNumber ») とする。
  5. そうでなければ、
    1. arrayを ? ArrayCreate(length) とする。
  6. kを0とする。
  7. k < lengthの間、繰り返す
    1. kValueitems[k]とする。
    2. propertyKeyを ! ToString(𝔽(k)) とする。
    3. CreateDataPropertyOrThrow(array, propertyKey, kValue)を実行する。
    4. kk + 1に設定する。
  8. Set(array, "length", lengthNumber, true)を実行する。
  9. arrayを返す。
Note

このmethodは意図的にgenericなfactory methodです;そのthis valueがArray constructorであることをrequireしません。したがって、single numeric argumentで呼び出され得るother constructorsへtransferまたはinheritできます。

23.1.2.5 Array.prototype

Array.prototypeのvalueはArray prototype objectです。

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

23.1.2.6 get Array [ %Symbol.species% ]

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

  1. this valueを返す。

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

Note

Array prototype methodsは通常、そのthis valueのconstructorを使用してderived objectを作成します。しかし、subclass constructorは、その%Symbol.species% propertyをredefiningすることにより、そのdefault behaviourをover-rideしてもよいです。

23.1.3 Properties of the Array Prototype Object

Array prototype objectは:

  • %Array.prototype%です。
  • Array exotic objectであり、そのようなobjectsに対して指定されたinternal methodsを持ちます。
  • initial valueが+0𝔽であり、attributesが { [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false } である"length" propertyを持ちます。
  • valueが%Object.prototype%である[[Prototype]] internal slotを持ちます。
Note

Array prototype objectは、ECMAScript 2015 specificationより前に作成されたECMAScript codeとのcompatibilityをensureするために、Array exotic objectであるとspecifiedされています。

23.1.3.1 Array.prototype.at ( index )

  1. objを ? ToObject(this value) とする。
  2. lengthを ? LengthOfArrayLike(obj) とする。
  3. relativeIndexを ? ToIntegerOrInfinity(index) とする。
  4. relativeIndex ≥ 0なら、
    1. krelativeIndexとする。
  5. そうでなければ、
    1. klength + relativeIndexとする。
  6. k < 0またはklengthなら、undefinedを返す。
  7. Get(obj, ! ToString(𝔽(k)))を返す。

23.1.3.2 Array.prototype.concat ( ...items )

このmethodは、objectのarray elementsに各argumentのarray elementsがfollowしたものを含むarrayを返します。

これは呼び出されたとき、次のstepsを実行します:

  1. objを ? ToObject(this value) とする。
  2. arrayを ? ArraySpeciesCreate(obj, 0) とする。
  3. nextIndexを0とする。
  4. objitemsの先頭にprependする。
  5. itemsの各要素itemについて、以下を行う
    1. spreadableを ? IsConcatSpreadable(item) とする。
    2. spreadabletrueなら、
      1. lengthを ? LengthOfArrayLike(item) とする。
      2. nextIndex + length > 253 - 1なら、TypeError例外をthrowする。
      3. sourceIndexを0とする。
      4. sourceIndex < lengthの間、繰り返す
        1. propertyKeyを ! ToString(𝔽(sourceIndex)) とする。
        2. existsを ? HasProperty(item, propertyKey) とする。
        3. existstrueなら、
          1. subElementを ? Get(item, propertyKey) とする。
          2. CreateDataPropertyOrThrow(array, ! ToString(𝔽(nextIndex)), subElement)を実行する。
        4. nextIndexnextIndex + 1に設定する。
        5. sourceIndexsourceIndex + 1に設定する。
    3. そうでなければ、
      1. NOTE: itemはspreadされるのではなくsingle itemとしてaddedされる。
      2. nextIndex ≥ 253 - 1なら、TypeError例外をthrowする。
      3. CreateDataPropertyOrThrow(array, ! ToString(𝔽(nextIndex)), item)を実行する。
      4. nextIndexnextIndex + 1に設定する。
  6. Set(array, "length", 𝔽(nextIndex), true)を実行する。
  7. arrayを返す。

このmethodの"length" propertyは1𝔽です。

Note 1

step 6における"length" propertyのexplicit settingは、itemsのfinal non-empty elementがtrailing holesを持つ場合、またはarrayがbuilt-in Arrayでない場合に、lengthがcorrectであることをensureすることを意図しています。

Note 2

このmethodは意図的にgenericです;そのthis valueがArrayであることをrequireしません。したがって、methodとして使用するために他の種類のobjectsへtransferできます。

23.1.3.2.1 IsConcatSpreadable ( obj )

The abstract operation IsConcatSpreadable takes argument obj (an ECMAScript language value) and returns either a normal completion containing a Boolean or a throw completion. It performs the following steps when called:

  1. objがObjectでないなら、falseを返す。
  2. spreadableを ? Get(obj, %Symbol.isConcatSpreadable%) とする。
  3. spreadableundefinedでないなら、ToBoolean(spreadable)を返す。
  4. IsArray(obj)を返す。

23.1.3.3 Array.prototype.constructor

Array.prototype.constructorのinitial valueは%Array%です。

23.1.3.4 Array.prototype.copyWithin ( target, start [ , end ] )

Note 1

end argumentはoptionalです。providedされない場合、this valueのlengthが使用されます。

Note 2

targetがnegativeなら、lengthをarrayのlengthとして、length + targetとして扱われます。startがnegativeなら、length + startとして扱われます。endがnegativeなら、length + endとして扱われます。

このmethodは呼び出されたとき、次のstepsを実行します:

  1. objを ? ToObject(this value) とする。
  2. lengthを ? LengthOfArrayLike(obj) とする。
  3. relativeTargetを ? ToIntegerOrInfinity(target) とする。
  4. relativeTarget = -∞なら、toを0とする。
  5. そうでなく、relativeTarget < 0なら、tomax(length + relativeTarget, 0)とする。
  6. そうでなければ、tomin(relativeTarget, length)とする。
  7. relativeStartを ? ToIntegerOrInfinity(start) とする。
  8. relativeStart = -∞なら、fromを0とする。
  9. そうでなく、relativeStart < 0なら、frommax(length + relativeStart, 0)とする。
  10. そうでなければ、frommin(relativeStart, length)とする。
  11. endundefinedなら、relativeEndlengthとする;そうでなければ、relativeEndを ? ToIntegerOrInfinity(end) とする。
  12. relativeEnd = -∞なら、finalを0とする。
  13. そうでなく、relativeEnd < 0なら、finalmax(length + relativeEnd, 0)とする。
  14. そうでなければ、finalmin(relativeEnd, length)とする。
  15. countmin(final - from, length - to)とする。
  16. from < toかつto < from + countなら、
    1. directionを-1とする。
    2. fromfrom + count - 1に設定する。
    3. toto + count - 1に設定する。
  17. そうでなければ、
    1. directionを1とする。
  18. count > 0の間、繰り返す
    1. fromKeyを ! ToString(𝔽(from)) とする。
    2. toKeyを ! ToString(𝔽(to)) とする。
    3. fromPresentを ? HasProperty(obj, fromKey) とする。
    4. fromPresenttrueなら、
      1. fromValueを ? Get(obj, fromKey) とする。
      2. Set(obj, toKey, fromValue, true)を実行する。
    5. そうでなければ、
      1. Assert: fromPresentfalseである。
      2. DeletePropertyOrThrow(obj, toKey)を実行する。
    6. fromfrom + directionに設定する。
    7. toto + directionに設定する。
    8. countcount - 1に設定する。
  19. objを返す。
Note 3

このmethodは意図的にgenericです;そのthis valueがArrayであることをrequireしません。したがって、methodとして使用するために他の種類のobjectsへtransferできます。

23.1.3.5 Array.prototype.entries ( )

このmethodは呼び出されたとき、次のstepsを実行します:

  1. objを ? ToObject(this value) とする。
  2. CreateArrayIterator(obj, key+value)を返す。

23.1.3.6 Array.prototype.every ( callback [ , thisArg ] )

Note 1

callbackはthree argumentsをacceptし、Boolean valueへcoercibleなvalueを返すfunctionであるべきです。everyは、callbackfalseを返すoneをfindするまで、array内にpresentな各elementについてascending orderでcallbackをonce呼び出します。そのようなelementが見つかると、everyはimmediately falseを返します。そうでなければ、everytrueを返します。callbackは、arrayの実際にexistするelementsに対してのみ呼び出されます;arrayのmissing elementsに対しては呼び出されません。

thisArg parameterがprovidedされる場合、callbackの各invocationに対するthis valueとして使用されます。providedされない場合、代わりにundefinedが使用されます。

callbackはthree argumentsで呼び出されます:elementのvalue、elementのindex、およびtraversedされているobjectです。

everyは、それが呼び出されたobjectをdirectlyにはmutateしませんが、objectはcallbackへのcallsによってmutateされる可能性があります。

everyによってprocessedされるelementsのrangeは、callbackへのfirst callの前にsetされます。everyへのcallがbeginした後にarrayへappendedされたelementsは、callbackによってvisitedされません。arrayのexisting elementsがchangedされた場合、callbackへpassedされるそのvalueは、everyがそれらをvisitする時点のvalueになります;everyへのcallがbeginした後、visitedされる前にdeletedされたelementsはvisitedされません。everyは数学における“for all” quantifierのようにactします。特に、empty arrayについてはtrueを返します。

このmethodは呼び出されたとき、次のstepsを実行します:

  1. objを ? ToObject(this value) とする。
  2. lengthを ? LengthOfArrayLike(obj) とする。
  3. IsCallable(callback)がfalseなら、TypeError例外をthrowする。
  4. kを0とする。
  5. k < lengthの間、繰り返す
    1. propertyKeyを ! ToString(𝔽(k)) とする。
    2. kPresentを ? HasProperty(obj, propertyKey) とする。
    3. kPresenttrueなら、
      1. kValueを ? Get(obj, propertyKey) とする。
      2. testResultToBoolean(? Call(callback, thisArg, « kValue, 𝔽(k), obj »))とする。
      3. testResultfalseなら、falseを返す。
    4. kk + 1に設定する。
  6. trueを返す。
Note 2

このmethodは意図的にgenericです;そのthis valueがArrayであることをrequireしません。したがって、methodとして使用するために他の種類のobjectsへtransferできます。

23.1.3.7 Array.prototype.fill ( value [ , start [ , end ] ] )

Note 1

start argumentはoptionalです。providedされない場合、+0𝔽が使用されます。

end argumentはoptionalです。providedされない場合、this valueのlengthが使用されます。

Note 2

startがnegativeなら、lengthをarrayのlengthとして、length + startとして扱われます。endがnegativeなら、length + endとして扱われます。

このmethodは呼び出されたとき、次のstepsを実行します:

  1. objを ? ToObject(this value) とする。
  2. lengthを ? LengthOfArrayLike(obj) とする。
  3. relativeStartを ? ToIntegerOrInfinity(start) とする。
  4. relativeStart = -∞なら、kを0とする。
  5. そうでなく、relativeStart < 0なら、kmax(length + relativeStart, 0)とする。
  6. そうでなければ、kmin(relativeStart, length)とする。
  7. endundefinedなら、relativeEndlengthとする;そうでなければ、relativeEndを ? ToIntegerOrInfinity(end) とする。
  8. relativeEnd = -∞なら、finalを0とする。
  9. そうでなく、relativeEnd < 0なら、finalmax(length + relativeEnd, 0)とする。
  10. そうでなければ、finalmin(relativeEnd, length)とする。
  11. k < finalの間、繰り返す
    1. propertyKeyを ! ToString(𝔽(k)) とする。
    2. Set(obj, propertyKey, value, true)を実行する。
    3. kk + 1に設定する。
  12. objを返す。
Note 3

このmethodは意図的にgenericです;そのthis valueがArrayであることをrequireしません。したがって、methodとして使用するために他の種類のobjectsへtransferできます。

23.1.3.8 Array.prototype.filter ( callback [ , thisArg ] )

Note 1

callbackはthree argumentsをacceptし、Boolean valueへcoercibleなvalueを返すfunctionであるべきです。filterは、array内の各elementについてascending orderでcallbackをonce呼び出し、callbacktrueを返すすべてのvaluesからなるnew arrayをconstructします。callbackは、arrayの実際にexistするelementsに対してのみ呼び出されます;arrayのmissing elementsに対しては呼び出されません。

thisArg parameterがprovidedされる場合、callbackの各invocationに対するthis valueとして使用されます。providedされない場合、代わりにundefinedが使用されます。

callbackはthree argumentsで呼び出されます:elementのvalue、elementのindex、およびtraversedされているobjectです。

filterは、それが呼び出されたobjectをdirectlyにはmutateしませんが、objectはcallbackへのcallsによってmutateされる可能性があります。

filterによってprocessedされるelementsのrangeは、callbackへのfirst callの前にsetされます。filterへのcallがbeginした後にarrayへappendedされたelementsは、callbackによってvisitedされません。arrayのexisting elementsがchangedされた場合、callbackへpassedされるそのvalueは、filterがそれらをvisitする時点のvalueになります;filterへのcallがbeginした後、visitedされる前にdeletedされたelementsはvisitedされません。

このmethodは呼び出されたとき、次のstepsを実行します:

  1. objを ? ToObject(this value) とする。
  2. lengthを ? LengthOfArrayLike(obj) とする。
  3. IsCallable(callback)がfalseなら、TypeError例外をthrowする。
  4. arrayを ? ArraySpeciesCreate(obj, 0) とする。
  5. kを0とする。
  6. toを0とする。
  7. k < lengthの間、繰り返す
    1. propertyKeyを ! ToString(𝔽(k)) とする。
    2. kPresentを ? HasProperty(obj, propertyKey) とする。
    3. kPresenttrueなら、
      1. kValueを ? Get(obj, propertyKey) とする。
      2. selectedToBoolean(? Call(callback, thisArg, « kValue, 𝔽(k), obj »))とする。
      3. selectedtrueなら、
        1. CreateDataPropertyOrThrow(array, ! ToString(𝔽(to)), kValue)を実行する。
        2. toto + 1に設定する。
    4. kk + 1に設定する。
  8. arrayを返す。
Note 2

このmethodは意図的にgenericです;そのthis valueがArrayであることをrequireしません。したがって、methodとして使用するために他の種類のobjectsへtransferできます。

23.1.3.9 Array.prototype.find ( predicate [ , thisArg ] )

Note 1

このmethodは、predicatetrueへcoercesされるvalueを返すoneをfindするまで、arrayの各elementについてascending index orderでpredicateをonce呼び出します。そのようなelementが見つかると、findはimmediatelyそのelement valueを返します。そうでなければ、findundefinedを返します。

additional informationについてはFindViaPredicateを参照してください。

このmethodは呼び出されたとき、次のstepsを実行します:

  1. objを ? ToObject(this value) とする。
  2. lengthを ? LengthOfArrayLike(obj) とする。
  3. findRecordを ? FindViaPredicate(obj, length, ascending, predicate, thisArg) とする。
  4. findRecord.[[Value]]を返す。
Note 2

このmethodは意図的にgenericです;そのthis valueがArrayであることをrequireしません。したがって、methodとして使用するために他の種類のobjectsへtransferできます。

23.1.3.10 Array.prototype.findIndex ( predicate [ , thisArg ] )

Note 1

このmethodは、predicatetrueへcoercesされるvalueを返すoneをfindするまで、arrayの各elementについてascending index orderでpredicateをonce呼び出します。そのようなelementが見つかると、findIndexはimmediatelyそのelement valueのindexを返します。そうでなければ、findIndexは-1を返します。

additional informationについてはFindViaPredicateを参照してください。

このmethodは呼び出されたとき、次のstepsを実行します:

  1. objを ? ToObject(this value) とする。
  2. lengthを ? LengthOfArrayLike(obj) とする。
  3. findRecordを ? FindViaPredicate(obj, length, ascending, predicate, thisArg) とする。
  4. findRecord.[[Index]]を返す。
Note 2

このmethodは意図的にgenericです;そのthis valueがArrayであることをrequireしません。したがって、methodとして使用するために他の種類のobjectsへtransferできます。

23.1.3.11 Array.prototype.findLast ( predicate [ , thisArg ] )

Note 1

このmethodは、predicatetrueへcoercesされるvalueを返すoneをfindするまで、arrayの各elementについてdescending index orderでpredicateをonce呼び出します。そのようなelementが見つかると、findLastはimmediatelyそのelement valueを返します。そうでなければ、findLastundefinedを返します。

additional informationについてはFindViaPredicateを参照してください。

このmethodは呼び出されたとき、次のstepsを実行します:

  1. objを ? ToObject(this value) とする。
  2. lengthを ? LengthOfArrayLike(obj) とする。
  3. findRecordを ? FindViaPredicate(obj, length, descending, predicate, thisArg) とする。
  4. findRecord.[[Value]]を返す。
Note 2

このmethodは意図的にgenericです;そのthis valueがArray objectであることをrequireしません。したがって、methodとして使用するために他の種類のobjectsへtransferできます。

23.1.3.12 Array.prototype.findLastIndex ( predicate [ , thisArg ] )

Note 1

このmethodは、predicatetrueへcoercesされるvalueを返すoneをfindするまで、arrayの各elementについてdescending index orderでpredicateをonce呼び出します。そのようなelementが見つかると、findLastIndexはimmediatelyそのelement valueのindexを返します。そうでなければ、findLastIndexは-1を返します。

additional informationについてはFindViaPredicateを参照してください。

このmethodは呼び出されたとき、次のstepsを実行します:

  1. objを ? ToObject(this value) とする。
  2. lengthを ? LengthOfArrayLike(obj) とする。
  3. findRecordを ? FindViaPredicate(obj, length, descending, predicate, thisArg) とする。
  4. findRecord.[[Index]]を返す。
Note 2

このmethodは意図的にgenericです;そのthis valueがArray objectであることをrequireしません。したがって、methodとして使用するために他の種類のobjectsへtransferできます。

23.1.3.12.1 FindViaPredicate ( obj, length, direction, predicate, thisArg )

The abstract operation FindViaPredicate takes arguments obj (an Object), length (a non-negative integer), direction (ascending or descending), predicate (an ECMAScript language value), and thisArg (an ECMAScript language value) and returns either a normal completion containing a Record with fields [[Index]] (an integral Number) and [[Value]] (an ECMAScript language value) or a throw completion.

objarray-like objectまたはTypedArrayであるべきです。このoperationは、directionによって示される通り、ascending index orderまたはdescending index orderのいずれかで、predicatetrueへcoercesされるvalueを返すoneをfindするまで、objの各elementについてpredicateをonce呼び出します。その時点で、このoperationは見つかったelementのindexおよびvalueを与えるRecordを返します。そのようなelementが見つからない場合、このoperationはindexに-1𝔽、valueにundefinedをspecifyするRecordを返します。

predicateはfunctionであるべきです。arrayのelementについて呼び出されるとき、three argumentsが渡されます:elementのvalue、elementのindex、およびtraversedされているobjectです。そのreturn valueはBoolean valueへcoercedされます。

thisArgは、predicateの各invocationに対するthis valueとして使用されます。

このoperationは、それが呼び出されたobjectをdirectlyにはmutateしませんが、objectはpredicateへのcallsによってmutateされる可能性があります。

processedされるelementsのrangeは、predicateへのfirst callの前、traversalがbeginする直前にsetされます。この後にarrayへappendedされたelementsは、predicateによってvisitedされません。arrayのexisting elementsがchangedされた場合、predicateへpassedされるそのvalueは、このoperationがそれらをvisitする時点のvalueになります。traversalがbeginした後、visitedされる前にdeletedされたelementsはstill visitedされ、prototypeからlooked upされるか、undefinedになります。

It performs the following steps when called:

  1. IsCallable(predicate)がfalseなら、TypeError例外をthrowする。
  2. directionascendingなら、
    1. indicesを、0(inclusive)からlength(exclusive)までのinterval内のintegersListで、ascending orderとする。
  3. そうでなければ、
    1. indicesを、0(inclusive)からlength(exclusive)までのinterval内のintegersListで、descending orderとする。
  4. indicesの各integer kについて、以下を行う
    1. propertyKeyを ! ToString(𝔽(k)) とする。
    2. NOTE: objTypedArrayである場合、以下のGetのinvocationはnormal completionを返す。
    3. kValueを ? Get(obj, propertyKey) とする。
    4. testResultを ? Call(predicate, thisArg, « kValue, 𝔽(k), obj ») とする。
    5. ToBoolean(testResult)がtrueなら、Record { [[Index]]: 𝔽(k), [[Value]]: kValue }を返す。
  5. Record { [[Index]]: -1𝔽, [[Value]]: undefined }を返す。

23.1.3.13 Array.prototype.flat ( [ depth ] )

このmethodは呼び出されたとき、次のstepsを実行します:

  1. objを ? ToObject(this value) とする。
  2. sourceLengthを ? LengthOfArrayLike(obj) とする。
  3. depthNumberを1とする。
  4. depthundefinedでないなら、
    1. depthNumberを ? ToIntegerOrInfinity(depth) に設定する。
    2. depthNumber < 0なら、depthNumberを0に設定する。
  5. arrayを ? ArraySpeciesCreate(obj, 0) とする。
  6. FlattenIntoArray(array, obj, sourceLength, 0, depthNumber)を実行する。
  7. arrayを返す。

23.1.3.13.1 FlattenIntoArray ( target, source, sourceLength, start, depth [ , mapperFunc [ , thisArg ] ] )

The abstract operation FlattenIntoArray takes arguments target (an Object), source (an Object), sourceLength (a non-negative integer), start (a non-negative integer), and depth (a non-negative integer or +∞) and optional arguments mapperFunc (a function object) and thisArg (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. Assert: mapperFuncがpresentなら、IsCallable(mapperFunc)はtrueであり、thisArgはpresentであり、depthは1である。
  2. targetIndexstartとする。
  3. sourceIndex+0𝔽とする。
  4. (sourceIndex) < sourceLengthの間、繰り返す
    1. propertyKeyを ! ToString(sourceIndex) とする。
    2. existsを ? HasProperty(source, propertyKey) とする。
    3. existstrueなら、
      1. elementを ? Get(source, propertyKey) とする。
      2. mapperFuncがpresentなら、
        1. elementを ? Call(mapperFunc, thisArg, « element, sourceIndex, source ») に設定する。
      3. shouldFlattenfalseとする。
      4. depth > 0なら、
        1. shouldFlattenを ? IsArray(element) に設定する。
      5. shouldFlattentrueなら、
        1. depth = +∞なら、newDepthを+∞とする。
        2. そうでなければ、newDepthdepth - 1とする。
        3. elementLengthを ? LengthOfArrayLike(element) とする。
        4. targetIndexを ? FlattenIntoArray(target, element, elementLength, targetIndex, newDepth) に設定する。
      6. そうでなければ、
        1. targetIndex ≥ 253 - 1なら、TypeError例外をthrowする。
        2. CreateDataPropertyOrThrow(target, ! ToString(𝔽(targetIndex)), element)を実行する。
        3. targetIndextargetIndex + 1に設定する。
    4. sourceIndexsourceIndex + 1𝔽に設定する。
  5. targetIndexを返す。

23.1.3.14 Array.prototype.flatMap ( mapperFunc [ , thisArg ] )

このmethodは呼び出されたとき、次のstepsを実行します:

  1. objを ? ToObject(this value) とする。
  2. sourceLengthを ? LengthOfArrayLike(obj) とする。
  3. IsCallable(mapperFunc)がfalseなら、TypeError例外をthrowする。
  4. arrayを ? ArraySpeciesCreate(obj, 0) とする。
  5. FlattenIntoArray(array, obj, sourceLength, 0, 1, mapperFunc, thisArg)を実行する。
  6. arrayを返す。

23.1.3.15 Array.prototype.forEach ( callback [ , thisArg ] )

Note 1

callbackはthree argumentsをacceptするfunctionであるべきです。forEachは、array内にpresentな各elementについてascending orderでcallbackをonce呼び出します。callbackは、arrayの実際にexistするelementsに対してのみ呼び出されます;arrayのmissing elementsに対しては呼び出されません。

thisArg parameterがprovidedされる場合、callbackの各invocationに対するthis valueとして使用されます。providedされない場合、代わりにundefinedが使用されます。

callbackはthree argumentsで呼び出されます:elementのvalue、elementのindex、およびtraversedされているobjectです。

forEachは、それが呼び出されたobjectをdirectlyにはmutateしませんが、objectはcallbackへのcallsによってmutateされる可能性があります。

forEachによってprocessedされるelementsのrangeは、callbackへのfirst callの前にsetされます。forEachへのcallがbeginした後にarrayへappendedされたelementsは、callbackによってvisitedされません。arrayのexisting elementsがchangedされた場合、callbackへpassedされるそのvalueは、forEachがそれらをvisitする時点のvalueになります;forEachへのcallがbeginした後、visitedされる前にdeletedされたelementsはvisitedされません。

このmethodは呼び出されたとき、次のstepsを実行します:

  1. objを ? ToObject(this value) とする。
  2. lengthを ? LengthOfArrayLike(obj) とする。
  3. IsCallable(callback)がfalseなら、TypeError例外をthrowする。
  4. kを0とする。
  5. k < lengthの間、繰り返す
    1. propertyKeyを ! ToString(𝔽(k)) とする。
    2. kPresentを ? HasProperty(obj, propertyKey) とする。
    3. kPresenttrueなら、
      1. kValueを ? Get(obj, propertyKey) とする。
      2. Call(callback, thisArg, « kValue, 𝔽(k), obj »)を実行する。
    4. kk + 1に設定する。
  6. undefinedを返す。
Note 2

このmethodは意図的にgenericです;そのthis valueがArrayであることをrequireしません。したがって、methodとして使用するために他の種類のobjectsへtransferできます。

23.1.3.16 Array.prototype.includes ( searchElement [ , fromIndex ] )

Note 1

このmethodは、SameValueZero algorithmを使用してsearchElementをarrayのelementsとascending orderでcompareし、いずれかのpositionでfoundされる場合はtrueを返します;そうでなければ、falseを返します。

optional second argument fromIndex+0𝔽をdefaultとします(つまり、whole arrayがsearchedされます)。それがarrayのlength以上である場合、falseが返されます、つまりarrayはsearchedされません。それが-0𝔽より小さい場合、arrayのendからのoffsetとして使用され、fromIndexをcomputeします。computed indexが+0𝔽以下である場合、whole arrayがsearchedされます。

このmethodは呼び出されたとき、次のstepsを実行します:

  1. objを ? ToObject(this value) とする。
  2. lengthを ? LengthOfArrayLike(obj) とする。
  3. length = 0なら、falseを返す。
  4. startIndexを ? ToIntegerOrInfinity(fromIndex) とする。
  5. Assert: fromIndexundefinedなら、startIndexは0である。
  6. startIndex = +∞なら、falseを返す。
  7. startIndex = -∞なら、startIndexを0に設定する。
  8. startIndex ≥ 0なら、
    1. kstartIndexとする。
  9. そうでなければ、
    1. klength + startIndexとする。
    2. k < 0なら、kを0に設定する。
  10. k < lengthの間、繰り返す
    1. elementKを ? Get(obj, ! ToString(𝔽(k))) とする。
    2. SameValueZero(searchElement, elementK)がtrueなら、trueを返す。
    3. kk + 1に設定する。
  11. falseを返す。
Note 2

このmethodは意図的にgenericです;そのthis valueがArrayであることをrequireしません。したがって、methodとして使用するために他の種類のobjectsへtransferできます。

Note 3

このmethodは、similarなindexOf methodと意図的にtwo waysで異なります。First、それはIsStrictlyEqualではなくSameValueZero algorithmを使用するため、NaN array elementsをdetectできます。Second、それはmissing array elementsをskipせず、代わりにundefinedとして扱います。

23.1.3.17 Array.prototype.indexOf ( searchElement [ , fromIndex ] )

このmethodは、IsStrictlyEqual algorithmを使用してsearchElementをarrayのelementsとascending orderでcompareし、one or more indicesでfoundされる場合はそのsmallest such indexを返します;そうでなければ、-1𝔽を返します。

Note 1

optional second argument fromIndex+0𝔽をdefaultとします(つまり、whole arrayがsearchedされます)。それがarrayのlength以上である場合、-1𝔽が返されます、つまりarrayはsearchedされません。それが-0𝔽より小さい場合、arrayのendからのoffsetをcomputeするために使用されます。computed indexが+0𝔽以下である場合、whole arrayがsearchedされます。

このmethodは呼び出されたとき、次のstepsを実行します:

  1. objを ? ToObject(this value) とする。
  2. lengthを ? LengthOfArrayLike(obj) とする。
  3. length = 0なら、-1𝔽を返す。
  4. startIndexを ? ToIntegerOrInfinity(fromIndex) とする。
  5. Assert: fromIndexundefinedなら、startIndexは0である。
  6. startIndex = +∞なら、-1𝔽を返す。
  7. startIndex = -∞なら、startIndexを0に設定する。
  8. startIndex ≥ 0なら、
    1. kstartIndexとする。
  9. そうでなければ、
    1. klength + startIndexとする。
    2. k < 0なら、kを0に設定する。
  10. k < lengthの間、繰り返す
    1. propertyKeyを ! ToString(𝔽(k)) とする。
    2. kPresentを ? HasProperty(obj, propertyKey) とする。
    3. kPresenttrueなら、
      1. elementKを ? Get(obj, propertyKey) とする。
      2. IsStrictlyEqual(searchElement, elementK)がtrueなら、𝔽(k)を返す。
    4. kk + 1に設定する。
  11. -1𝔽を返す。
Note 2

このmethodは意図的にgenericです;そのthis valueがArrayであることをrequireしません。したがって、methodとして使用するために他の種類のobjectsへtransferできます。

23.1.3.18 Array.prototype.join ( separator )

このmethodはarrayのelementsをStringsへconvertし、その後、separatorのoccurrencesでseparatedしてそれらのStringsをconcatenateします。separatorがprovidedされない場合、single commaがseparatorとして使用されます。

これは呼び出されたとき、次のstepsを実行します:

  1. objを ? ToObject(this value) とする。
  2. lengthを ? LengthOfArrayLike(obj) とする。
  3. separatorundefinedなら、sep","とする。
  4. そうでなければ、sepを ? ToString(separator) とする。
  5. resultをempty Stringとする。
  6. kを0とする。
  7. k < lengthの間、繰り返す
    1. k > 0なら、resultresultsepstring-concatenationに設定する。
    2. elementを ? Get(obj, ! ToString(𝔽(k))) とする。
    3. elementundefinedでもnullでもないなら、
      1. elementStringを ? ToString(element) とする。
      2. resultresultelementStringstring-concatenationに設定する。
    4. kk + 1に設定する。
  8. resultを返す。
Note

このmethodは意図的にgenericです;そのthis valueがArrayであることをrequireしません。したがって、methodとして使用するために他の種類のobjectsへtransferできます。

23.1.3.19 Array.prototype.keys ( )

このmethodは呼び出されたとき、次のstepsを実行します:

  1. objを ? ToObject(this value) とする。
  2. CreateArrayIterator(obj, key)を返す。

23.1.3.20 Array.prototype.lastIndexOf ( searchElement [ , fromIndex ] )

Note 1

このmethodは、IsStrictlyEqual algorithmを使用してsearchElementをarrayのelementsとdescending orderでcompareし、one or more indicesでfoundされる場合はそのlargest such indexを返します;そうでなければ、-1𝔽を返します。

optional second argument fromIndexはarrayのlength minus oneをdefaultとします(つまり、whole arrayがsearchedされます)。それがarrayのlength以上である場合、whole arrayがsearchedされます。それが-0𝔽より小さい場合、arrayのendからのoffsetをcomputeするために使用されます。computed indexが-0𝔽より小さい場合、-1𝔽が返されます。

このmethodは呼び出されたとき、次のstepsを実行します:

  1. objを ? ToObject(this value) とする。
  2. lengthを ? LengthOfArrayLike(obj) とする。
  3. length = 0なら、-1𝔽を返す。
  4. fromIndexがpresentなら、startIndexを ? ToIntegerOrInfinity(fromIndex) とする;そうでなければ、startIndexlength - 1とする。
  5. startIndex = -∞なら、-1𝔽を返す。
  6. startIndex ≥ 0なら、
    1. kmin(startIndex, length - 1)とする。
  7. そうでなければ、
    1. klength + startIndexとする。
  8. k ≥ 0の間、繰り返す
    1. propertyKeyを ! ToString(𝔽(k)) とする。
    2. kPresentを ? HasProperty(obj, propertyKey) とする。
    3. kPresenttrueなら、
      1. elementKを ? Get(obj, propertyKey) とする。
      2. IsStrictlyEqual(searchElement, elementK)がtrueなら、𝔽(k)を返す。
    4. kk - 1に設定する。
  9. -1𝔽を返す。
Note 2

このmethodは意図的にgenericです;そのthis valueがArrayであることをrequireしません。したがって、methodとして使用するために他の種類のobjectsへtransferできます。

23.1.3.21 Array.prototype.map ( callback [ , thisArg ] )

Note 1

callbackはthree argumentsをacceptするfunctionであるべきです。mapは、array内の各elementについてascending orderでcallbackをonce呼び出し、そのresultsからnew Arrayをconstructします。callbackは、arrayの実際にexistするelementsに対してのみ呼び出されます;arrayのmissing elementsに対しては呼び出されません。

thisArg parameterがprovidedされる場合、callbackの各invocationに対するthis valueとして使用されます。providedされない場合、代わりにundefinedが使用されます。

callbackはthree argumentsで呼び出されます:elementのvalue、elementのindex、およびtraversedされているobjectです。

mapは、それが呼び出されたobjectをdirectlyにはmutateしませんが、objectはcallbackへのcallsによってmutateされる可能性があります。

mapによってprocessedされるelementsのrangeは、callbackへのfirst callの前にsetされます。mapへのcallがbeginした後にarrayへappendedされたelementsは、callbackによってvisitedされません。arrayのexisting elementsがchangedされた場合、callbackへpassedされるそのvalueは、mapがそれらをvisitする時点のvalueになります;mapへのcallがbeginした後、visitedされる前にdeletedされたelementsはvisitedされません。

このmethodは呼び出されたとき、次のstepsを実行します:

  1. objを ? ToObject(this value) とする。
  2. lengthを ? LengthOfArrayLike(obj) とする。
  3. IsCallable(callback)がfalseなら、TypeError例外をthrowする。
  4. arrayを ? ArraySpeciesCreate(obj, length) とする。
  5. kを0とする。
  6. k < lengthの間、繰り返す
    1. propertyKeyを ! ToString(𝔽(k)) とする。
    2. kPresentを ? HasProperty(obj, propertyKey) とする。
    3. kPresenttrueなら、
      1. kValueを ? Get(obj, propertyKey) とする。
      2. mappedValueを ? Call(callback, thisArg, « kValue, 𝔽(k), obj ») とする。
      3. CreateDataPropertyOrThrow(array, propertyKey, mappedValue)を実行する。
    4. kk + 1に設定する。
  7. arrayを返す。
Note 2

このmethodは意図的にgenericです;そのthis valueがArrayであることをrequireしません。したがって、methodとして使用するために他の種類のobjectsへtransferできます。

23.1.3.22 Array.prototype.pop ( )

Note 1

このmethodはarrayのlast elementをremoveし、それを返します。

このmethodは呼び出されたとき、次のstepsを実行します:

  1. objを ? ToObject(this value) とする。
  2. lengthを ? LengthOfArrayLike(obj) とする。
  3. length = 0なら、
    1. Set(obj, "length", +0𝔽, true)を実行する。
    2. undefinedを返す。
  4. Assert: length > 0である。
  5. newLength𝔽(length - 1)とする。
  6. indexを ! ToString(newLength) とする。
  7. elementを ? Get(obj, index) とする。
  8. DeletePropertyOrThrow(obj, index)を実行する。
  9. Set(obj, "length", newLength, true)を実行する。
  10. elementを返す。
Note 2

このmethodは意図的にgenericです;そのthis valueがArrayであることをrequireしません。したがって、methodとして使用するために他の種類のobjectsへtransferできます。

23.1.3.23 Array.prototype.push ( ...items )

Note 1

このmethodは、argumentsを、それらがappearするorderでarrayのendへappendします。これはarrayのnew lengthを返します。

このmethodは呼び出されたとき、次のstepsを実行します:

  1. objを ? ToObject(this value) とする。
  2. lengthを ? LengthOfArrayLike(obj) とする。
  3. argCountitems内のelementsの数とする。
  4. length + argCount > 253 - 1なら、TypeError例外をthrowする。
  5. itemsの各要素itemについて、以下を行う
    1. Set(obj, ! ToString(𝔽(length)), item, true)を実行する。
    2. lengthlength + 1に設定する。
  6. Set(obj, "length", 𝔽(length), true)を実行する。
  7. 𝔽(length)を返す。

このmethodの"length" propertyは1𝔽です。

Note 2

このmethodは意図的にgenericです;そのthis valueがArrayであることをrequireしません。したがって、methodとして使用するために他の種類のobjectsへtransferできます。

23.1.3.24 Array.prototype.reduce ( callback [ , initialValue ] )

Note 1

callbackはfour argumentsを取るfunctionであるべきです。reduceは、initialValueがprovidedされない限りfirst elementをskippingしながら、array内にpresentな各elementについてascending orderでcallbackをonce呼び出します。

callbackはfour argumentsで呼び出されます:previousValuecallbackへのprevious callからのvalue)、currentValue(current elementのvalue)、currentIndex、およびtraversedされているobjectです。callbackがfirst time呼び出されるとき、previousValuecurrentValueはtwo valuesのいずれかになり得ます。reduceへのcallでinitialValueがsuppliedされた場合、previousValueinitialValueになり、currentValueはarray内のfirst valueになります。initialValueがsuppliedされなかった場合、previousValueはarray内のfirst valueになり、currentValueはsecondになります。arrayがelementsを含まず、かつinitialValueがprovidedされない場合、TypeErrorです。

reduceは、それが呼び出されたobjectをdirectlyにはmutateしませんが、objectはcallbackへのcallsによってmutateされる可能性があります。

reduceによってprocessedされるelementsのrangeは、callbackへのfirst callの前にsetされます。reduceへのcallがbeginした後にarrayへappendedされたelementsは、callbackによってvisitedされません。arrayのexisting elementsがchangedされた場合、callbackへpassedされるそのvalueは、reduceがそれらをvisitする時点のvalueになります;reduceへのcallがbeginした後、visitedされる前にdeletedされたelementsはvisitedされません。

このmethodは呼び出されたとき、次のstepsを実行します:

  1. objを ? ToObject(this value) とする。
  2. lengthを ? LengthOfArrayLike(obj) とする。
  3. IsCallable(callback)がfalseなら、TypeError例外をthrowする。
  4. length = 0であり、かつinitialValueがpresentでないなら、TypeError例外をthrowする。
  5. kを0とする。
  6. accumulatorundefinedとする。
  7. initialValueがpresentなら、
    1. accumulatorinitialValueに設定する。
  8. そうでなければ、
    1. kPresentfalseとする。
    2. kPresentfalseであり、かつk < lengthである間、繰り返す
      1. propertyKeyを ! ToString(𝔽(k)) とする。
      2. kPresentを ? HasProperty(obj, propertyKey) に設定する。
      3. kPresenttrueなら、
        1. accumulatorを ? Get(obj, propertyKey) に設定する。
      4. kk + 1に設定する。
    3. kPresentfalseなら、TypeError例外をthrowする。
  9. k < lengthの間、繰り返す
    1. propertyKeyを ! ToString(𝔽(k)) とする。
    2. kPresentを ? HasProperty(obj, propertyKey) とする。
    3. kPresenttrueなら、
      1. kValueを ? Get(obj, propertyKey) とする。
      2. accumulatorを ? Call(callback, undefined, « accumulator, kValue, 𝔽(k), obj ») に設定する。
    4. kk + 1に設定する。
  10. accumulatorを返す。
Note 2

このmethodは意図的にgenericです;そのthis valueがArrayであることをrequireしません。したがって、methodとして使用するために他の種類のobjectsへtransferできます。

23.1.3.25 Array.prototype.reduceRight ( callback [ , initialValue ] )

Note 1

callbackはfour argumentsを取るfunctionであるべきです。reduceRightは、initialValueがprovidedされない限りfirst callをskippingしながら、array内にpresentな各elementについてdescending orderでcallbackをonce呼び出します。

callbackはfour argumentsで呼び出されます:previousValuecallbackへのprevious callからのvalue)、currentValue(current elementのvalue)、currentIndex、およびtraversedされているobjectです。functionがfirst time呼び出されるとき、previousValuecurrentValueはtwo valuesのいずれかになり得ます。reduceRightへのcallでinitialValueがsuppliedされた場合、previousValueinitialValueになり、currentValueはarray内のlast valueになります。initialValueがsuppliedされなかった場合、previousValueはarray内のlast valueになり、currentValueはsecond-to-last valueになります。arrayがelementsを含まず、かつinitialValueがprovidedされない場合、TypeErrorです。

reduceRightは、それが呼び出されたobjectをdirectlyにはmutateしませんが、objectはcallbackへのcallsによってmutateされる可能性があります。

reduceRightによってprocessedされるelementsのrangeは、callbackへのfirst callの前にsetされます。reduceRightへのcallがbeginした後にarrayへappendedされたelementsは、callbackによってvisitedされません。arrayのexisting elementsがcallbackによってchangedされた場合、callbackへpassedされるそのvalueは、reduceRightがそれらをvisitする時点のvalueになります;reduceRightへのcallがbeginした後、visitedされる前にdeletedされたelementsはvisitedされません。

このmethodは呼び出されたとき、次のstepsを実行します:

  1. objを ? ToObject(this value) とする。
  2. lengthを ? LengthOfArrayLike(obj) とする。
  3. IsCallable(callback)がfalseなら、TypeError例外をthrowする。
  4. length = 0であり、かつinitialValueがpresentでないなら、TypeError例外をthrowする。
  5. klength - 1とする。
  6. accumulatorundefinedとする。
  7. initialValueがpresentなら、
    1. accumulatorinitialValueに設定する。
  8. そうでなければ、
    1. kPresentfalseとする。
    2. kPresentfalseであり、かつk ≥ 0である間、繰り返す
      1. propertyKeyを ! ToString(𝔽(k)) とする。
      2. kPresentを ? HasProperty(obj, propertyKey) に設定する。
      3. kPresenttrueなら、
        1. accumulatorを ? Get(obj, propertyKey) に設定する。
      4. kk - 1に設定する。
    3. kPresentfalseなら、TypeError例外をthrowする。
  9. k ≥ 0の間、繰り返す
    1. propertyKeyを ! ToString(𝔽(k)) とする。
    2. kPresentを ? HasProperty(obj, propertyKey) とする。
    3. kPresenttrueなら、
      1. kValueを ? Get(obj, propertyKey) とする。
      2. accumulatorを ? Call(callback, undefined, « accumulator, kValue, 𝔽(k), obj ») に設定する。
    4. kk - 1に設定する。
  10. accumulatorを返す。
Note 2

このmethodは意図的にgenericです;そのthis valueがArrayであることをrequireしません。したがって、methodとして使用するために他の種類のobjectsへtransferできます。

23.1.3.26 Array.prototype.reverse ( )

Note 1

このmethodはarrayのelementsをrearrangeし、そのorderをreverseします。これはreversed arrayを返します。

このmethodは呼び出されたとき、次のstepsを実行します:

  1. objを ? ToObject(this value) とする。
  2. lengthを ? LengthOfArrayLike(obj) とする。
  3. middlefloor(length / 2)とする。
  4. lowerを0とする。
  5. lowermiddleの間、繰り返す
    1. upperlength - lower - 1とする。
    2. upperPを ! ToString(𝔽(upper)) とする。
    3. lowerPを ! ToString(𝔽(lower)) とする。
    4. lowerExistsを ? HasProperty(obj, lowerP) とする。
    5. lowerExiststrueなら、
      1. lowerValueを ? Get(obj, lowerP) とする。
    6. upperExistsを ? HasProperty(obj, upperP) とする。
    7. upperExiststrueなら、
      1. upperValueを ? Get(obj, upperP) とする。
    8. lowerExiststrueであり、かつupperExiststrueなら、
      1. Set(obj, lowerP, upperValue, true)を実行する。
      2. Set(obj, upperP, lowerValue, true)を実行する。
    9. そうでなく、lowerExistsfalseであり、かつupperExiststrueなら、
      1. Set(obj, lowerP, upperValue, true)を実行する。
      2. DeletePropertyOrThrow(obj, upperP)を実行する。
    10. そうでなく、lowerExiststrueであり、かつupperExistsfalseなら、
      1. DeletePropertyOrThrow(obj, lowerP)を実行する。
      2. Set(obj, upperP, lowerValue, true)を実行する。
    11. そうでなければ、
      1. Assert: lowerExistsおよびupperExistsはともにfalseである。
      2. NOTE: actionはrequiredされない。
    12. lowerlower + 1に設定する。
  6. objを返す。
Note 2

このmethodは意図的にgenericです;そのthis valueがArrayであることをrequireしません。したがって、methodとして使用するために他の種類のobjectsへtransferできます。

23.1.3.27 Array.prototype.shift ( )

このmethodはarrayのfirst elementをremoveし、それを返します。

これは呼び出されたとき、次のstepsを実行します:

  1. objを ? ToObject(this value) とする。
  2. lengthを ? LengthOfArrayLike(obj) とする。
  3. length = 0なら、
    1. Set(obj, "length", +0𝔽, true)を実行する。
    2. undefinedを返す。
  4. firstを ? Get(obj, "0") とする。
  5. kを1とする。
  6. k < lengthの間、繰り返す
    1. fromを ! ToString(𝔽(k)) とする。
    2. toを ! ToString(𝔽(k - 1)) とする。
    3. fromPresentを ? HasProperty(obj, from) とする。
    4. fromPresenttrueなら、
      1. fromValueを ? Get(obj, from) とする。
      2. Set(obj, to, fromValue, true)を実行する。
    5. そうでなければ、
      1. Assert: fromPresentfalseである。
      2. DeletePropertyOrThrow(obj, to)を実行する。
    6. kk + 1に設定する。
  7. DeletePropertyOrThrow(obj, ! ToString(𝔽(length - 1)))を実行する。
  8. Set(obj, "length", 𝔽(length - 1), true)を実行する。
  9. firstを返す。
Note

このmethodは意図的にgenericです;そのthis valueがArrayであることをrequireしません。したがって、methodとして使用するために他の種類のobjectsへtransferできます。

23.1.3.28 Array.prototype.slice ( start, end )

このmethodは、element startからelement endまで(ただしendを含まない)のarrayのelementsを含むarrayを返します(またはendundefinedならarrayのendまで)。startがnegativeなら、lengthをarrayのlengthとしてlength + startとして扱われます。endがnegativeなら、lengthをarrayのlengthとしてlength + endとして扱われます。

これは呼び出されたとき、次のstepsを実行します:

  1. objを ? ToObject(this value) とする。
  2. lengthを ? LengthOfArrayLike(obj) とする。
  3. relativeStartを ? ToIntegerOrInfinity(start) とする。
  4. relativeStart = -∞なら、kを0とする。
  5. そうでなく、relativeStart < 0なら、kmax(length + relativeStart, 0)とする。
  6. そうでなければ、kmin(relativeStart, length)とする。
  7. endundefinedなら、relativeEndlengthとする;そうでなければ、relativeEndを ? ToIntegerOrInfinity(end) とする。
  8. relativeEnd = -∞なら、finalを0とする。
  9. そうでなく、relativeEnd < 0なら、finalmax(length + relativeEnd, 0)とする。
  10. そうでなければ、finalmin(relativeEnd, length)とする。
  11. countmax(final - k, 0)とする。
  12. arrayを ? ArraySpeciesCreate(obj, count) とする。
  13. resultIndexを0とする。
  14. k < finalの間、繰り返す
    1. propertyKeyを ! ToString(𝔽(k)) とする。
    2. kPresentを ? HasProperty(obj, propertyKey) とする。
    3. kPresenttrueなら、
      1. kValueを ? Get(obj, propertyKey) とする。
      2. CreateDataPropertyOrThrow(array, ! ToString(𝔽(resultIndex)), kValue)を実行する。
    4. kk + 1に設定する。
    5. resultIndexresultIndex + 1に設定する。
  15. Set(array, "length", 𝔽(resultIndex), true)を実行する。
  16. arrayを返す。
Note 1

step 15における"length" propertyのexplicit settingは、arrayがbuilt-in Arrayでない場合であってもlengthがcorrectであることをensureすることを意図しています。

Note 2

このmethodは意図的にgenericです;そのthis valueがArrayであることをrequireしません。したがって、methodとして使用するために他の種類のobjectsへtransferできます。

23.1.3.29 Array.prototype.some ( callback [ , thisArg ] )

Note 1

callbackはthree argumentsをacceptし、Boolean valueへcoercibleなvalueを返すfunctionであるべきです。someは、callbacktrueを返すoneをfindするまで、array内にpresentな各elementについてascending orderでcallbackをonce呼び出します。そのようなelementが見つかると、someはimmediately trueを返します。そうでなければ、somefalseを返します。callbackは、arrayの実際にexistするelementsに対してのみ呼び出されます;arrayのmissing elementsに対しては呼び出されません。

thisArg parameterがprovidedされる場合、callbackの各invocationに対するthis valueとして使用されます。providedされない場合、代わりにundefinedが使用されます。

callbackはthree argumentsで呼び出されます:elementのvalue、elementのindex、およびtraversedされているobjectです。

someは、それが呼び出されたobjectをdirectlyにはmutateしませんが、objectはcallbackへのcallsによってmutateされる可能性があります。

someによってprocessedされるelementsのrangeは、callbackへのfirst callの前にsetされます。someへのcallがbeginした後にarrayへappendedされたelementsは、callbackによってvisitedされません。arrayのexisting elementsがchangedされた場合、callbackへpassedされるそのvalueは、someがそれらをvisitする時点のvalueになります;someへのcallがbeginした後、visitedされる前にdeletedされたelementsはvisitedされません。someは数学における“exists” quantifierのようにactします。特に、empty arrayについてはfalseを返します。

このmethodは呼び出されたとき、次のstepsを実行します:

  1. objを ? ToObject(this value) とする。
  2. lengthを ? LengthOfArrayLike(obj) とする。
  3. IsCallable(callback)がfalseなら、TypeError例外をthrowする。
  4. kを0とする。
  5. k < lengthの間、繰り返す
    1. propertyKeyを ! ToString(𝔽(k)) とする。
    2. kPresentを ? HasProperty(obj, propertyKey) とする。
    3. kPresenttrueなら、
      1. kValueを ? Get(obj, propertyKey) とする。
      2. testResultToBoolean(? Call(callback, thisArg, « kValue, 𝔽(k), obj »))とする。
      3. testResulttrueなら、trueを返す。
    4. kk + 1に設定する。
  6. falseを返す。
Note 2

このmethodは意図的にgenericです;そのthis valueがArrayであることをrequireしません。したがって、methodとして使用するために他の種類のobjectsへtransferできます。

23.1.3.30 Array.prototype.sort ( comparator )

このmethodはthis arrayのelementsをsortします。comparatorundefinedでないなら、それはtwo arguments xおよびyをacceptし、x < yならnegative Number、x > yならpositive Number、そうでなければzeroを返すfunctionであるべきです。

これは呼び出されたとき、次のstepsを実行します:

  1. comparatorundefinedでなく、かつIsCallable(comparator)がfalseなら、TypeError例外をthrowする。
  2. objを ? ToObject(this value) とする。
  3. lengthを ? LengthOfArrayLike(obj) とする。
  4. sortCompareを、comparatorをcaptureし、calledされたときに次のstepsを実行する、parameters (x, y)を持つnew Abstract Closureとする:
    1. CompareArrayElements(x, y, comparator)を返す。
  5. sortedListを ? SortIndexedProperties(obj, length, sortCompare, skip-holes) とする。
  6. itemCountsortedList内のelementsの数とする。
  7. jを0とする。
  8. j < itemCountの間、繰り返す
    1. Set(obj, ! ToString(𝔽(j)), sortedList[j], true)を実行する。
    2. jj + 1に設定する。
  9. NOTE: step 5SortIndexedPropertiesへのcallはskip-holesを使用する。remaining indicesは、sortからdetectedおよびexcludedされたholesの数をpreserveするためにdeletedされる。
  10. j < lengthの間、繰り返す
    1. DeletePropertyOrThrow(obj, ! ToString(𝔽(j)))を実行する。
    2. jj + 1に設定する。
  11. objを返す。
Note 1

non-existent property valuesは常にundefined property valuesよりgreaterとしてcompareされ、undefinedは常にany other valueよりgreaterとしてcompareされるため(CompareArrayElementsを参照)、undefined property valuesは常にresultのendへsortされ、その後にnon-existent property valuesがfollowします。

Note 2

steps 5および6内のToString abstract operationsによってperformedされるmethod callsは、sortCompareconsistent comparatorとしてbehaveしなくなる可能性があります。

Note 3

このmethodは意図的にgenericです;そのthis valueがArrayであることをrequireしません。したがって、methodとして使用するために他の種類のobjectsへtransferできます。

23.1.3.30.1 SortIndexedProperties ( obj, length, sortCompare, holes )

The abstract operation SortIndexedProperties takes arguments obj (an Object), length (a non-negative integer), sortCompare (an Abstract Closure with two parameters), and holes (skip-holes or read-through-holes) and returns either a normal completion containing a List of ECMAScript language values or a throw completion. It performs the following steps when called:

  1. itemsを新しい空のListとする。
  2. kを0とする。
  3. k < lengthの間、繰り返す
    1. propertyKeyを ! ToString(𝔽(k)) とする。
    2. holesskip-holesなら、
      1. kReadを ? HasProperty(obj, propertyKey) とする。
    3. そうでなければ、
      1. Assert: holesread-through-holesである。
      2. kReadtrueとする。
    4. kReadtrueなら、
      1. kValueを ? Get(obj, propertyKey) とする。
      2. kValueitemsへappendする。
    5. kk + 1に設定する。
  4. implementation-defined sequence of calls to sortCompareを使用してitemsをSortする。そのようなcallのいずれかがabrupt completionを返す場合、sortCompareへのそれ以上のcallsをperformする前にstopし、そのCompletion Recordを返す。
  5. itemsを返す。

sort orderは、上記algorithmのstep 4のcompletion後のitemsのorderingです。sortCompareitemsのelementsに対するconsistent comparatorでない場合、sort orderimplementation-definedです。SortIndexedPropertiesがArray.prototype.sortまたはArray.prototype.toSortedによってinvokedされる場合、comparatorundefinedであり、かつsortCompareへのargumentとしてpassedされたany specific valueへのToStringのすべてのapplicationsがsame resultをproduceしない場合にも、sort orderimplementation-definedです。

sort orderimplementation-definedであるとspecifiedされていない限り、次のconditionsのすべてをsatisfyしなければなりません:

  • itemCountより小さいnon-negative integersのmathematical permutation πが存在し、itemCountより小さいevery non-negative integer jについて、element old[j]new[π(j)]とexactly the sameでなければなりません。
  • そして、itemCountより小さいすべてのnon-negative integers jおよびkについて、(sortCompare(old[j], old[k])) < 0なら、π(j) < π(k)です。
  • さらに、j < k < itemCountであるすべてのnon-negative integers jおよびkについて、(sortCompare(old[j], old[k])) = 0なら、π(j) < π(k)です;つまり、sortはstableです。

ここでnotation old[j]は、step 4がexecutedされる前のitems[j]をreferするために使用され、notation new[j]は、step 4がexecutedされた後のitems[j]をreferするために使用されます。

Abstract Closureまたはfunction comparatorは、set values内のall values ab、およびc(possibly the same value)について以下のrequirementsのすべてが満たされる場合、valuesのset valuesに対するconsistent comparatorです:notation a <C b(comparator(a, b)) < 0を意味します;a =C b(comparator(a, b)) = 0を意味します;そしてa >C b(comparator(a, b)) > 0を意味します。

  • comparator(a, b)をcallingすると、two argumentsとしてspecific pair of values aおよびbがgivenされたとき、常にsame value vを返します。さらに、vはNumberであり、vNaNではありません。これは、given pair of aおよびbについて、a <C ba =C b、およびa >C bのexactly oneがtrueになることをimplyすることに注意してください。
  • comparator(a, b)をcallingしても、objまたはobjのprototype chain上のany objectをmodifyしません。
  • a =C a(reflexivity)
  • a =C bなら、b =C a(symmetry)
  • a =C bであり、かつb =C cなら、a =C c(transitivity of =C
  • a <C bであり、かつb <C cなら、a <C c(transitivity of <C
  • a >C bであり、かつb >C cなら、a >C c(transitivity of >C
Note

上記のconditionsは、comparatorがset valuesをequivalence classesへdivideし、これらのequivalence classesがtotally orderedであることをensureするためにnecessary and sufficientです。

23.1.3.30.2 CompareArrayElements ( x, y, comparator )

The abstract operation CompareArrayElements takes arguments x (an ECMAScript language value), y (an ECMAScript language value), and comparator (a function object or undefined) and returns either a normal completion containing a Number or an abrupt completion. It performs the following steps when called:

  1. xundefinedであり、かつyundefinedなら、+0𝔽を返す。
  2. xundefinedなら、1𝔽を返す。
  3. yundefinedなら、-1𝔽を返す。
  4. comparatorundefinedでないなら、
    1. resultを ? ToNumber(? Call(comparator, undefined, « x, y »)) とする。
    2. resultNaNなら、+0𝔽を返す。
    3. resultを返す。
  5. xStringを ? ToString(x) とする。
  6. yStringを ? ToString(y) とする。
  7. xSmallerを ! IsLessThan(xString, yString, true) とする。
  8. xSmallertrueなら、-1𝔽を返す。
  9. ySmallerを ! IsLessThan(yString, xString, true) とする。
  10. ySmallertrueなら、1𝔽を返す。
  11. +0𝔽を返す。

23.1.3.31 Array.prototype.splice ( start, deleteCount, ...items )

Note 1

このmethodはinteger index startからstartingするarrayのdeleteCount elementsをdeleteし、それらをitemsのelementsでreplaceします。これはdeleted elements(もしあれば)を含むArrayを返します。

このmethodは呼び出されたとき、次のstepsを実行します:

  1. objを ? ToObject(this value) とする。
  2. lengthを ? LengthOfArrayLike(obj) とする。
  3. relativeStartを ? ToIntegerOrInfinity(start) とする。
  4. relativeStart = -∞なら、actualStartを0とする。
  5. そうでなく、relativeStart < 0なら、actualStartmax(length + relativeStart, 0)とする。
  6. そうでなければ、actualStartmin(relativeStart, length)とする。
  7. itemCountitems内のelementsの数とする。
  8. startがpresentでないなら、
    1. actualDeleteCountを0とする。
  9. そうでなく、deleteCountがpresentでないなら、
    1. actualDeleteCountlength - actualStartとする。
  10. そうでなければ、
    1. dcを ? ToIntegerOrInfinity(deleteCount) とする。
    2. actualDeleteCountdcを0とlength - actualStartの間にclampingしたresultとする。
  11. length + itemCount - actualDeleteCount > 253 - 1なら、TypeError例外をthrowする。
  12. deletedArrayを ? ArraySpeciesCreate(obj, actualDeleteCount) とする。
  13. kを0とする。
  14. k < actualDeleteCountの間、繰り返す
    1. fromを ! ToString(𝔽(actualStart + k)) とする。
    2. HasProperty(obj, from)がtrueなら、
      1. fromValueを ? Get(obj, from) とする。
      2. CreateDataPropertyOrThrow(deletedArray, ! ToString(𝔽(k)), fromValue)を実行する。
    3. kk + 1に設定する。
  15. Set(deletedArray, "length", 𝔽(actualDeleteCount), true)を実行する。
  16. itemCount < actualDeleteCountなら、
    1. kactualStartに設定する。
    2. k < (length - actualDeleteCount)の間、繰り返す
      1. fromを ! ToString(𝔽(k + actualDeleteCount)) とする。
      2. toを ! ToString(𝔽(k + itemCount)) とする。
      3. HasProperty(obj, from)がtrueなら、
        1. fromValueを ? Get(obj, from) とする。
        2. Set(obj, to, fromValue, true)を実行する。
      4. そうでなければ、
        1. DeletePropertyOrThrow(obj, to)を実行する。
      5. kk + 1に設定する。
    3. klengthに設定する。
    4. k > (length - actualDeleteCount + itemCount)の間、繰り返す
      1. DeletePropertyOrThrow(obj, ! ToString(𝔽(k - 1)))を実行する。
      2. kk - 1に設定する。
  17. そうでなく、itemCount > actualDeleteCountなら、
    1. kを(length - actualDeleteCount)に設定する。
    2. k > actualStartの間、繰り返す
      1. fromを ! ToString(𝔽(k + actualDeleteCount - 1)) とする。
      2. toを ! ToString(𝔽(k + itemCount - 1)) とする。
      3. HasProperty(obj, from)がtrueなら、
        1. fromValueを ? Get(obj, from) とする。
        2. Set(obj, to, fromValue, true)を実行する。
      4. そうでなければ、
        1. DeletePropertyOrThrow(obj, to)を実行する。
      5. kk - 1に設定する。
  18. kactualStartに設定する。
  19. itemsの各要素itemについて、以下を行う
    1. Set(obj, ! ToString(𝔽(k)), item, true)を実行する。
    2. kk + 1に設定する。
  20. Set(obj, "length", 𝔽(length - actualDeleteCount + itemCount), true)を実行する。
  21. deletedArrayを返す。
Note 2

steps 15および20における"length" propertyのexplicit settingは、objectsがbuilt-in Arraysでない場合であってもlengthsがcorrectであることをensureすることを意図しています。

Note 3

このmethodは意図的にgenericです;そのthis valueがArrayであることをrequireしません。したがって、methodとして使用するために他の種類のobjectsへtransferできます。

23.1.3.32 Array.prototype.toLocaleString ( [ reserved1 [ , reserved2 ] ] )

ECMA-402 Internationalization APIを含むECMAScript implementationは、このmethodをECMA-402 specificationで指定される通りにimplementしなければなりません。ECMAScript implementationがECMA-402 APIを含まない場合、このmethodの次のspecificationが使用されます。

Note 1

ECMA-402のfirst editionは、このmethodのreplacement specificationを含みませんでした。

このmethodのoptional parametersのmeaningsはECMA-402 specificationで定義されます;ECMA-402 supportを含まないimplementationsは、それらのparameter positionsを他の何かに使用してはなりません。

このmethodは呼び出されたとき、次のstepsを実行します:

  1. arrayを ? ToObject(this value) とする。
  2. lengthを ? LengthOfArrayLike(array) とする。
  3. separatorを、host environmentのcurrent localeにappropriateなimplementation-defined list-separator String value(", "など)とする。
  4. resultをempty Stringとする。
  5. kを0とする。
  6. k < lengthの間、繰り返す
    1. k > 0なら、resultresultseparatorstring-concatenationに設定する。
    2. elementを ? Get(array, ! ToString(𝔽(k))) とする。
    3. elementundefinedでもnullでもないなら、
      1. elementStringを ? ToString(? Invoke(element, "toLocaleString")) とする。
      2. resultresultelementStringstring-concatenationに設定する。
    4. kk + 1に設定する。
  7. resultを返す。
Note 2

このmethodはarrayのelementsをそれらのtoLocaleString methodsを使用してStringsへconvertし、その後、implementation-defined locale-sensitive separator StringのoccurrencesでseparatedしてそれらのStringsをconcatenateします。このmethodはtoStringにanalogousですが、host environmentのcurrent localeのconventionsに対応するlocale-sensitive resultをyieldすることを意図している点が異なります。

Note 3

このmethodは意図的にgenericです;そのthis valueがArrayであることをrequireしません。したがって、methodとして使用するために他の種類のobjectsへtransferできます。

23.1.3.33 Array.prototype.toReversed ( )

このmethodは呼び出されたとき、次のstepsを実行します:

  1. objを ? ToObject(this value) とする。
  2. lengthを ? LengthOfArrayLike(obj) とする。
  3. arrayを ? ArrayCreate(length) とする。
  4. kを0とする。
  5. k < lengthの間、繰り返す
    1. fromを ! ToString(𝔽(length - k - 1)) とする。
    2. propertyKeyを ! ToString(𝔽(k)) とする。
    3. fromValueを ? Get(obj, from) とする。
    4. CreateDataPropertyOrThrow(array, propertyKey, fromValue)を実行する。
    5. kk + 1に設定する。
  6. arrayを返す。

23.1.3.34 Array.prototype.toSorted ( comparator )

このmethodは呼び出されたとき、次のstepsを実行します:

  1. comparatorundefinedでなく、かつIsCallable(comparator)がfalseなら、TypeError例外をthrowする。
  2. objを ? ToObject(this value) とする。
  3. lengthを ? LengthOfArrayLike(obj) とする。
  4. arrayを ? ArrayCreate(length) とする。
  5. sortCompareを、comparatorをcaptureし、calledされたときに次のstepsを実行する、parameters (x, y)を持つnew Abstract Closureとする:
    1. CompareArrayElements(x, y, comparator)を返す。
  6. sortedListを ? SortIndexedProperties(obj, length, sortCompare, read-through-holes) とする。
  7. jを0とする。
  8. j < lengthの間、繰り返す
    1. CreateDataPropertyOrThrow(array, ! ToString(𝔽(j)), sortedList[j])を実行する。
    2. jj + 1に設定する。
  9. arrayを返す。

23.1.3.35 Array.prototype.toSpliced ( start, skipCount, ...items )

このmethodは呼び出されたとき、次のstepsを実行します:

  1. objを ? ToObject(this value) とする。
  2. lengthを ? LengthOfArrayLike(obj) とする。
  3. relativeStartを ? ToIntegerOrInfinity(start) とする。
  4. relativeStart = -∞なら、actualStartを0とする。
  5. そうでなく、relativeStart < 0なら、actualStartmax(length + relativeStart, 0)とする。
  6. そうでなければ、actualStartmin(relativeStart, length)とする。
  7. insertCountitems内のelementsの数とする。
  8. startがpresentでないなら、
    1. actualSkipCountを0とする。
  9. そうでなく、skipCountがpresentでないなら、
    1. actualSkipCountlength - actualStartとする。
  10. そうでなければ、
    1. scを ? ToIntegerOrInfinity(skipCount) とする。
    2. actualSkipCountscを0とlength - actualStartの間にclampingしたresultとする。
  11. newLengthlength + insertCount - actualSkipCountとする。
  12. newLength > 253 - 1なら、TypeError例外をthrowする。
  13. newArrayを ? ArrayCreate(newLength) とする。
  14. writeIndexを0とする。
  15. readIndexactualStart + actualSkipCountとする。
  16. writeIndex < actualStartの間、繰り返す
    1. propertyKeyを ! ToString(𝔽(writeIndex)) とする。
    2. iValueを ? Get(obj, propertyKey) とする。
    3. CreateDataPropertyOrThrow(newArray, propertyKey, iValue)を実行する。
    4. writeIndexwriteIndex + 1に設定する。
  17. itemsの各要素itemについて、以下を行う
    1. propertyKeyを ! ToString(𝔽(writeIndex)) とする。
    2. CreateDataPropertyOrThrow(newArray, propertyKey, item)を実行する。
    3. writeIndexwriteIndex + 1に設定する。
  18. writeIndex < newLengthの間、繰り返す
    1. propertyKeyを ! ToString(𝔽(writeIndex)) とする。
    2. fromを ! ToString(𝔽(readIndex)) とする。
    3. fromValueを ? Get(obj, from) とする。
    4. CreateDataPropertyOrThrow(newArray, propertyKey, fromValue)を実行する。
    5. writeIndexwriteIndex + 1に設定する。
    6. readIndexreadIndex + 1に設定する。
  19. newArrayを返す。

23.1.3.36 Array.prototype.toString ( )

このmethodは呼び出されたとき、次のstepsを実行します:

  1. arrayを ? ToObject(this value) とする。
  2. funcを ? Get(array, "join") とする。
  3. IsCallable(func)がfalseなら、funcをintrinsic function %Object.prototype.toString%に設定する。
  4. Call(func, array)を返す。
Note

このmethodは意図的にgenericです;そのthis valueがArrayであることをrequireしません。したがって、methodとして使用するために他の種類のobjectsへtransferできます。

23.1.3.37 Array.prototype.unshift ( ...items )

このmethodは、argumentsをarrayのstartへprependし、array内でのそれらのorderがargument list内でappearするorderとsameになるようにします。

これは呼び出されたとき、次のstepsを実行します:

  1. objを ? ToObject(this value) とする。
  2. lengthを ? LengthOfArrayLike(obj) とする。
  3. argCountitems内のelementsの数とする。
  4. argCount > 0なら、
    1. length + argCount > 253 - 1なら、TypeError例外をthrowする。
    2. klengthとする。
    3. k > 0の間、繰り返す
      1. fromを ! ToString(𝔽(k - 1)) とする。
      2. toを ! ToString(𝔽(k + argCount - 1)) とする。
      3. fromPresentを ? HasProperty(obj, from) とする。
      4. fromPresenttrueなら、
        1. fromValueを ? Get(obj, from) とする。
        2. Set(obj, to, fromValue, true)を実行する。
      5. そうでなければ、
        1. Assert: fromPresentfalseである。
        2. DeletePropertyOrThrow(obj, to)を実行する。
      6. kk - 1に設定する。
    4. j+0𝔽とする。
    5. itemsの各要素itemについて、以下を行う
      1. Set(obj, ! ToString(j), item, true)を実行する。
      2. jj + 1𝔽に設定する。
  5. Set(obj, "length", 𝔽(length + argCount), true)を実行する。
  6. 𝔽(length + argCount)を返す。

このmethodの"length" propertyは1𝔽です。

Note

このmethodは意図的にgenericです;そのthis valueがArrayであることをrequireしません。したがって、methodとして使用するために他の種類のobjectsへtransferできます。

23.1.3.38 Array.prototype.values ( )

このmethodは呼び出されたとき、次のstepsを実行します:

  1. objを ? ToObject(this value) とする。
  2. CreateArrayIterator(obj, value)を返す。

23.1.3.39 Array.prototype.with ( index, value )

このmethodは呼び出されたとき、次のstepsを実行します:

  1. objを ? ToObject(this value) とする。
  2. lengthを ? LengthOfArrayLike(obj) とする。
  3. relativeIndexを ? ToIntegerOrInfinity(index) とする。
  4. relativeIndex ≥ 0なら、actualIndexrelativeIndexとする。
  5. そうでなければ、actualIndexlength + relativeIndexとする。
  6. actualIndexlengthまたはactualIndex < 0なら、RangeError例外をthrowする。
  7. arrayを ? ArrayCreate(length) とする。
  8. kを0とする。
  9. k < lengthの間、繰り返す
    1. propertyKeyを ! ToString(𝔽(k)) とする。
    2. k = actualIndexなら、fromValuevalueとする。
    3. そうでなければ、fromValueを ? Get(obj, propertyKey) とする。
    4. CreateDataPropertyOrThrow(array, propertyKey, fromValue)を実行する。
    5. kk + 1に設定する。
  10. arrayを返す。

23.1.3.40 Array.prototype [ %Symbol.iterator% ] ( )

%Symbol.iterator% propertyのinitial valueは、23.1.3.38で定義される%Array.prototype.values%です。

23.1.3.41 Array.prototype [ %Symbol.unscopables% ]

%Symbol.unscopables% data propertyのinitial valueは、次のstepsによって作成されるobjectです:

  1. unscopableListOrdinaryObjectCreate(null)とする。
  2. CreateDataPropertyOrThrow(unscopableList, "at", true)を実行する。
  3. CreateDataPropertyOrThrow(unscopableList, "copyWithin", true)を実行する。
  4. CreateDataPropertyOrThrow(unscopableList, "entries", true)を実行する。
  5. CreateDataPropertyOrThrow(unscopableList, "fill", true)を実行する。
  6. CreateDataPropertyOrThrow(unscopableList, "find", true)を実行する。
  7. CreateDataPropertyOrThrow(unscopableList, "findIndex", true)を実行する。
  8. CreateDataPropertyOrThrow(unscopableList, "findLast", true)を実行する。
  9. CreateDataPropertyOrThrow(unscopableList, "findLastIndex", true)を実行する。
  10. CreateDataPropertyOrThrow(unscopableList, "flat", true)を実行する。
  11. CreateDataPropertyOrThrow(unscopableList, "flatMap", true)を実行する。
  12. CreateDataPropertyOrThrow(unscopableList, "includes", true)を実行する。
  13. CreateDataPropertyOrThrow(unscopableList, "keys", true)を実行する。
  14. CreateDataPropertyOrThrow(unscopableList, "toReversed", true)を実行する。
  15. CreateDataPropertyOrThrow(unscopableList, "toSorted", true)を実行する。
  16. CreateDataPropertyOrThrow(unscopableList, "toSpliced", true)を実行する。
  17. CreateDataPropertyOrThrow(unscopableList, "values", true)を実行する。
  18. unscopableListを返す。

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

Note

このobjectのown property namesは、ECMAScript 2015 specificationより前にArray.prototypeのstandard propertiesとして含まれていなかったproperty namesです。これらのnamesは、binding purposesにおけるwith statementについてignoredされます。これは、outer scope内のbindingとしてこれらのnamesのいずれかを使用し、そのbindingがbinding objectがArrayであるwith statementによってshadowedされる可能性のあるexisting codeのbehaviourをpreserveするためです。

"with"unscopableListに含まれないreasonは、それがすでにreserved wordだからです。

23.1.4 Properties of Array Instances

Array instancesはArray exotic objectsであり、そのようなobjectsに対して指定されたinternal methodsを持ちます。Array instancesはArray prototype objectからpropertiesをinheritします。

Array instancesは"length" property、およびarray index namesを持つenumerable propertiesのsetを持ちます。

23.1.4.1 length

Array instanceの"length" propertyは、そのvalueが、nameがarray indexであるすべてのconfigurable own propertyのnameより常にnumerically greaterであるdata propertyです。

"length" propertyはinitially attributes { [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false }を持ちます。

Note

"length" propertyのvalueをreducingすることには、array indexがold length valueとnew length valueの間にあるown array elementsをdeletingするside-effectがあります。しかし、non-configurable propertiesはdeleteできません。Arrayの"length" propertyを、arrayのexisting non-configurable array-indexed propertyのlargest numeric own property name以下のnumeric valueへsetしようとすると、そのlengthは、そのnon-configurable numeric own property nameよりone greaterであるnumeric valueにsetされるresultになります。10.4.2.1を参照してください。

23.1.5 Array Iterator Objects

Array Iteratorは、some specific Array instance object上のspecific iterationを表すobjectです。Array Iterator objectsにはnamed constructorは存在しません。代わりに、Array Iterator objectsはArray instance objectsのcertain methodsを呼び出すことで作成されます。

23.1.5.1 CreateArrayIterator ( array, kind )

The abstract operation CreateArrayIterator takes arguments array (an Object) and kind (key+value, key, or value) and returns an Object. これは、そのようなiteratorsを返すArray methodsのためにiterator objectsを作成するために使用されます。 It performs the following steps when called:

  1. iteratorOrdinaryObjectCreate(%ArrayIteratorPrototype%, « [[IteratedArrayLike]], [[ArrayLikeNextIndex]], [[ArrayLikeIterationKind]] »)とする。
  2. iterator.[[IteratedArrayLike]]arrayに設定する。
  3. iterator.[[ArrayLikeNextIndex]]を0に設定する。
  4. iterator.[[ArrayLikeIterationKind]]kindに設定する。
  5. iteratorを返す。

23.1.5.2 The %ArrayIteratorPrototype% Object

%ArrayIteratorPrototype% objectは:

23.1.5.2.1 %ArrayIteratorPrototype%.next ( )

  1. iteratorObjthis valueとする。
  2. iteratorObjがObjectでないなら、TypeError例外をthrowする。
  3. iteratorObjArray Iterator Instanceのすべてのinternal slots(23.1.5.3)を持たないなら、TypeError例外をthrowする。
  4. arrayiteratorObj.[[IteratedArrayLike]]とする。
  5. arrayundefinedなら、CreateIteratorResultObject(undefined, true)を返す。
  6. indexiteratorObj.[[ArrayLikeNextIndex]]とする。
  7. kinditeratorObj.[[ArrayLikeIterationKind]]とする。
  8. array[[TypedArrayName]] internal slotを持つなら、
    1. taRecordMakeTypedArrayWithBufferWitnessRecord(array, seq-cst)とする。
    2. IsTypedArrayOutOfBounds(taRecord)がtrueなら、TypeError例外をthrowする。
    3. lengthTypedArrayLength(taRecord)とする。
  9. そうでなければ、
    1. lengthを ? LengthOfArrayLike(array) とする。
  10. indexlengthなら、
    1. iteratorObj.[[IteratedArrayLike]]undefinedに設定する。
    2. CreateIteratorResultObject(undefined, true)を返す。
  11. iteratorObj.[[ArrayLikeNextIndex]]index + 1に設定する。
  12. indexNumber𝔽(index)とする。
  13. kindkeyなら、
    1. resultindexNumberとする。
  14. そうでなければ、
    1. elementKeyを ! ToString(indexNumber) とする。
    2. elementValueを ? Get(array, elementKey) とする。
    3. kindvalueなら、
      1. resultelementValueとする。
    4. そうでなければ、
      1. Assert: kindkey+valueである。
      2. resultCreateArrayFromListindexNumber, elementValue »)とする。
  15. CreateIteratorResultObject(result, false)を返す。

23.1.5.2.2 %ArrayIteratorPrototype% [ %Symbol.toStringTag% ]

%Symbol.toStringTag% propertyのinitial valueはString value "Array Iterator"です。

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

23.1.5.3 Properties of Array Iterator Instances

Array Iterator instancesは、%ArrayIteratorPrototype% intrinsic objectからpropertiesをinheritするordinary objectsです。Array Iterator instancesは、Table 70にlistedされたinternal slotsを持ってinitiallyに作成されます。

Table 70: Internal Slots of Array Iterator Instances
Internal Slot Type Description
[[IteratedArrayLike]] an Object or undefined iterateされているarray-like object
[[ArrayLikeNextIndex]] a non-negative integer このiteratorによって次にexaminedされるelementのinteger index
[[ArrayLikeIterationKind]] key+value, key, or value iterationの各elementについて何がreturnedされるかをidentifyするvalue。

23.2 TypedArray Objects

TypedArrayは、underlying binary data buffer(25.1)のarray-like viewを提供します。TypedArray element typeは、TypedArray instanceのすべてのelementsが持つunderlying binary scalar data typeです。supported element typesのそれぞれについて、Table 71にlistedされているdistinctなTypedArray constructorがあります。Table 71内の各constructorは、corresponding distinct prototype objectを持ちます。

Table 71: The TypedArray Constructors
Constructor Name and Intrinsic Element Type Element Size Conversion Operation Description
Int8Array
%Int8Array%
int8 1 ToInt8 8-bit two's complement signed integer
Uint8Array
%Uint8Array%
uint8 1 ToUint8 8-bit unsigned integer
Uint8ClampedArray
%Uint8ClampedArray%
uint8clamped 1 ToUint8Clamp 8-bit unsigned integer (clamped conversion)
Int16Array
%Int16Array%
int16 2 ToInt16 16-bit two's complement signed integer
Uint16Array
%Uint16Array%
uint16 2 ToUint16 16-bit unsigned integer
Int32Array
%Int32Array%
int32 4 ToInt32 32-bit two's complement signed integer
Uint32Array
%Uint32Array%
uint32 4 ToUint32 32-bit unsigned integer
BigInt64Array
%BigInt64Array%
bigint64 8 ToBigInt64 64-bit two's complement signed integer
BigUint64Array
%BigUint64Array%
biguint64 8 ToBigUint64 64-bit unsigned integer
Float16Array
%Float16Array%
float16 2 16-bit IEEE floating point
Float32Array
%Float32Array%
float32 4 32-bit IEEE floating point
Float64Array
%Float64Array%
float64 8 64-bit IEEE floating point

以下のdefinitionsでは、TypedArrayへのreferencesは、上のtableからappropriate constructor nameで置き換えられるべきです。

23.2.1 The %TypedArray% Intrinsic Object

%TypedArray% intrinsic objectは:

  • すべてのTypedArray constructor objectsがinheritするconstructor function objectです。
  • そのcorresponding prototype objectとともに、すべてのTypedArray constructorsおよびそのinstancesによってinheritedされるcommon propertiesを提供します。
  • global nameを持たず、global objectのpropertyとして現れません。
  • various TypedArray constructorsのabstract superclassとしてactします。
  • abstract class constructorであるため、invokedされるとerrorをthrowします。TypedArray constructorsはこれに対するsuper callをperformしません。

23.2.1.1 %TypedArray% ( )

このfunctionは呼び出されたとき、次のstepsを実行します:

  1. TypeError例外をthrowする。

このfunctionの"length" propertyは+0𝔽です。

23.2.2 Properties of the %TypedArray% Intrinsic Object

%TypedArray% intrinsic objectは:

  • valueが%Function.prototype%である[[Prototype]] internal slotを持ちます。
  • valueが"TypedArray"である"name" propertyを持ちます。
  • 次のpropertiesを持ちます:

23.2.2.1 %TypedArray%.from ( source [ , mapper [ , thisArg ] ] )

このmethodは呼び出されたとき、次のstepsを実行します:

  1. ctorthis valueとする。
  2. IsConstructor(ctor)がfalseなら、TypeError例外をthrowする。
  3. mapperundefinedなら、
    1. mappingfalseとする。
  4. そうでなければ、
    1. IsCallable(mapper)がfalseなら、TypeError例外をthrowする。
    2. mappingtrueとする。
  5. usingIteratorを ? GetMethod(source, %Symbol.iterator%) とする。
  6. usingIteratorundefinedでないなら、
    1. valuesを ? IteratorToList(? GetIteratorFromMethod(source, usingIterator)) とする。
    2. lengthvalues内のelementsの数とする。
    3. targetObjを ? TypedArrayCreateFromConstructor(ctor, « 𝔽(length) ») とする。
    4. kを0とする。
    5. k < lengthの間、繰り返す
      1. propertyKeyを ! ToString(𝔽(k)) とする。
      2. kValuevaluesのfirst elementとする。
      3. valuesからfirst elementをremoveする。
      4. mappingtrueなら、
        1. mappedValueを ? Call(mapper, thisArg, « kValue, 𝔽(k) ») とする。
      5. そうでなければ、
        1. mappedValuekValueとする。
      6. Set(targetObj, propertyKey, mappedValue, true)を実行する。
      7. kk + 1に設定する。
    6. Assert: valuesは現在empty Listである。
    7. targetObjを返す。
  7. NOTE: sourceiterable objectではないため、すでにarray-like objectであるとassumeする。
  8. arrayLikeを ! ToObject(source) とする。
  9. lengthを ? LengthOfArrayLike(arrayLike) とする。
  10. targetObjを ? TypedArrayCreateFromConstructor(ctor, « 𝔽(length) ») とする。
  11. kを0とする。
  12. k < lengthの間、繰り返す
    1. propertyKeyを ! ToString(𝔽(k)) とする。
    2. kValueを ? Get(arrayLike, propertyKey) とする。
    3. mappingtrueなら、
      1. mappedValueを ? Call(mapper, thisArg, « kValue, 𝔽(k) ») とする。
    4. そうでなければ、
      1. mappedValuekValueとする。
    5. Set(targetObj, propertyKey, mappedValue, true)を実行する。
    6. kk + 1に設定する。
  13. targetObjを返す。

23.2.2.2 %TypedArray%.of ( ...items )

このmethodは呼び出されたとき、次のstepsを実行します:

  1. lengthitems内のelementsの数とする。
  2. ctorthis valueとする。
  3. IsConstructor(ctor)がfalseなら、TypeError例外をthrowする。
  4. newObjを ? TypedArrayCreateFromConstructor(ctor, « 𝔽(length) ») とする。
  5. kを0とする。
  6. k < lengthの間、繰り返す
    1. kValueitems[k]とする。
    2. propertyKeyを ! ToString(𝔽(k)) とする。
    3. Set(newObj, propertyKey, kValue, true)を実行する。
    4. kk + 1に設定する。
  7. newObjを返す。

23.2.2.3 %TypedArray%.prototype

%TypedArray%.prototypeのinitial valueは%TypedArray% prototype objectです。

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

23.2.2.4 get %TypedArray% [ %Symbol.species% ]

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

  1. this valueを返す。

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

Note

%TypedArray.prototype% methodsは通常、そのthis valueのconstructorを使用してderived objectを作成します。しかし、subclass constructorは、その%Symbol.species% propertyをredefiningすることにより、そのdefault behaviourをover-rideしてもよいです。

23.2.3 Properties of the %TypedArray% Prototype Object

%TypedArray% prototype objectは:

  • valueが%Object.prototype%である[[Prototype]] internal slotを持ちます。
  • %TypedArray.prototype%です。
  • ordinary objectです。
  • [[ViewedArrayBuffer]]や、TypedArray instance objectsにspecificなその他のinternal slotsを持ちません。

23.2.3.1 %TypedArray%.prototype.at ( index )

  1. objthis valueとする。
  2. taRecordを ? ValidateTypedArray(obj, seq-cst) とする。
  3. lengthTypedArrayLength(taRecord)とする。
  4. relativeIndexを ? ToIntegerOrInfinity(index) とする。
  5. relativeIndex ≥ 0なら、
    1. krelativeIndexとする。
  6. そうでなければ、
    1. klength + relativeIndexとする。
  7. k < 0またはklengthなら、undefinedを返す。
  8. Get(obj, ! ToString(𝔽(k)))を返す。

23.2.3.2 get %TypedArray%.prototype.buffer

%TypedArray%.prototype.bufferは、set accessor functionがundefinedであるaccessor propertyです。そのget accessor functionは呼び出されたとき、次のstepsを実行します:

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

23.2.3.3 get %TypedArray%.prototype.byteLength

%TypedArray%.prototype.byteLengthは、set accessor functionがundefinedであるaccessor propertyです。そのget accessor functionは呼び出されたとき、次のstepsを実行します:

  1. objthis valueとする。
  2. RequireInternalSlot(obj, [[TypedArrayName]])を実行する。
  3. Assert: obj[[ViewedArrayBuffer]] internal slotを持つ。
  4. taRecordMakeTypedArrayWithBufferWitnessRecord(obj, seq-cst)とする。
  5. IsTypedArrayOutOfBounds(taRecord)がtrueなら、+0𝔽を返す。
  6. sizeTypedArrayByteLength(taRecord)とする。
  7. 𝔽(size)を返す。

23.2.3.4 get %TypedArray%.prototype.byteOffset

%TypedArray%.prototype.byteOffsetは、set accessor functionがundefinedであるaccessor propertyです。そのget accessor functionは呼び出されたとき、次のstepsを実行します:

  1. objthis valueとする。
  2. RequireInternalSlot(obj, [[TypedArrayName]])を実行する。
  3. Assert: obj[[ViewedArrayBuffer]] internal slotを持つ。
  4. taRecordMakeTypedArrayWithBufferWitnessRecord(obj, seq-cst)とする。
  5. IsTypedArrayOutOfBounds(taRecord)がtrueなら、+0𝔽を返す。
  6. offsetobj.[[ByteOffset]]とする。
  7. 𝔽(offset)を返す。

23.2.3.5 %TypedArray%.prototype.constructor

%TypedArray%.prototype.constructorのinitial valueは%TypedArray%です。

23.2.3.6 %TypedArray%.prototype.copyWithin ( target, start [ , end ] )

このmethodのargumentsのinterpretationおよびuseは、23.1.3.4で定義されるArray.prototype.copyWithinと同じです。

このmethodは呼び出されたとき、次のstepsを実行します:

  1. objthis valueとする。
  2. taRecordを ? ValidateTypedArray(obj, seq-cst) とする。
  3. lengthTypedArrayLength(taRecord)とする。
  4. relativeTargetを ? ToIntegerOrInfinity(target) とする。
  5. relativeTarget = -∞なら、targetIndexを0とする。
  6. そうでなく、relativeTarget < 0なら、targetIndexmax(length + relativeTarget, 0)とする。
  7. そうでなければ、targetIndexmin(relativeTarget, length)とする。
  8. relativeStartを ? ToIntegerOrInfinity(start) とする。
  9. relativeStart = -∞なら、startIndexを0とする。
  10. そうでなく、relativeStart < 0なら、startIndexmax(length + relativeStart, 0)とする。
  11. そうでなければ、startIndexmin(relativeStart, length)とする。
  12. endundefinedなら、relativeEndlengthとする;そうでなければ、relativeEndを ? ToIntegerOrInfinity(end) とする。
  13. relativeEnd = -∞なら、endIndexを0とする。
  14. そうでなく、relativeEnd < 0なら、endIndexmax(length + relativeEnd, 0)とする。
  15. そうでなければ、endIndexmin(relativeEnd, length)とする。
  16. countmin(endIndex - startIndex, length - targetIndex)とする。
  17. count > 0なら、
    1. NOTE: copyingはsource dataのbit-level encodingをpreserveするmannerでperformedされなければならない。
    2. bufferobj.[[ViewedArrayBuffer]]とする。
    3. taRecordMakeTypedArrayWithBufferWitnessRecord(obj, seq-cst)に設定する。
    4. IsTypedArrayOutOfBounds(taRecord)がtrueなら、TypeError例外をthrowする。
    5. lengthTypedArrayLength(taRecord)に設定する。
    6. NOTE: 上記stepsのside-effectsによりobjのsizeがreducedされた可能性があり、そのcaseではcopyingはlongest still-applicable prefixでproceedすべきである。
    7. countmin(count, length - startIndex, length - targetIndex)に設定する。
    8. elementSizeTypedArrayElementSize(obj)とする。
    9. byteOffsetobj.[[ByteOffset]]とする。
    10. toByteIndexを(targetIndex × elementSize) + byteOffsetとする。
    11. fromByteIndexを(startIndex × elementSize) + byteOffsetとする。
    12. countBytescount × elementSizeとする。
    13. fromByteIndex < toByteIndexかつtoByteIndex < fromByteIndex + countBytesなら、
      1. directionを-1とする。
      2. fromByteIndexfromByteIndex + countBytes - 1に設定する。
      3. toByteIndextoByteIndex + countBytes - 1に設定する。
    14. そうでなければ、
      1. directionを1とする。
    15. countBytes > 0の間、繰り返す
      1. valueGetValueFromBuffer(buffer, fromByteIndex, uint8, true, unordered)とする。
      2. SetValueInBuffer(buffer, toByteIndex, uint8, value, true, unordered)を実行する。
      3. fromByteIndexfromByteIndex + directionに設定する。
      4. toByteIndextoByteIndex + directionに設定する。
      5. countBytescountBytes - 1に設定する。
  18. objを返す。

23.2.3.7 %TypedArray%.prototype.entries ( )

このmethodは呼び出されたとき、次のstepsを実行します:

  1. objthis valueとする。
  2. ValidateTypedArray(obj, seq-cst)を実行する。
  3. CreateArrayIterator(obj, key+value)を返す。

23.2.3.8 %TypedArray%.prototype.every ( callback [ , thisArg ] )

このmethodのargumentsのinterpretationおよびuseは、23.1.3.6で定義されるArray.prototype.everyと同じです。

このmethodは呼び出されたとき、次のstepsを実行します:

  1. objthis valueとする。
  2. taRecordを ? ValidateTypedArray(obj, seq-cst) とする。
  3. lengthTypedArrayLength(taRecord)とする。
  4. IsCallable(callback)がfalseなら、TypeError例外をthrowする。
  5. kを0とする。
  6. k < lengthの間、繰り返す
    1. propertyKeyを ! ToString(𝔽(k)) とする。
    2. kValueを ! Get(obj, propertyKey) とする。
    3. testResultToBoolean(? Call(callback, thisArg, « kValue, 𝔽(k), obj »))とする。
    4. testResultfalseなら、falseを返す。
    5. kk + 1に設定する。
  7. trueを返す。

このmethodはgenericではありません。this valueは[[TypedArrayName]] internal slotを持つobjectでなければなりません。

23.2.3.9 %TypedArray%.prototype.fill ( value [ , start [ , end ] ] )

このmethodのargumentsのinterpretationおよびuseは、23.1.3.7で定義されるArray.prototype.fillと同じです。

このmethodは呼び出されたとき、次のstepsを実行します:

  1. objthis valueとする。
  2. taRecordを ? ValidateTypedArray(obj, seq-cst) とする。
  3. lengthTypedArrayLength(taRecord)とする。
  4. obj.[[ContentType]]bigintなら、valueを ? ToBigInt(value) に設定する。
  5. そうでなければ、valueを ? ToNumber(value) に設定する。
  6. relativeStartを ? ToIntegerOrInfinity(start) とする。
  7. relativeStart = -∞なら、startIndexを0とする。
  8. そうでなく、relativeStart < 0なら、startIndexmax(length + relativeStart, 0)とする。
  9. そうでなければ、startIndexmin(relativeStart, length)とする。
  10. endundefinedなら、relativeEndlengthとする;そうでなければ、relativeEndを ? ToIntegerOrInfinity(end) とする。
  11. relativeEnd = -∞なら、endIndexを0とする。
  12. そうでなく、relativeEnd < 0なら、endIndexmax(length + relativeEnd, 0)とする。
  13. そうでなければ、endIndexmin(relativeEnd, length)とする。
  14. taRecordMakeTypedArrayWithBufferWitnessRecord(obj, seq-cst)に設定する。
  15. IsTypedArrayOutOfBounds(taRecord)がtrueなら、TypeError例外をthrowする。
  16. lengthTypedArrayLength(taRecord)に設定する。
  17. endIndexmin(endIndex, length)に設定する。
  18. kstartIndexとする。
  19. k < endIndexの間、繰り返す
    1. propertyKeyを ! ToString(𝔽(k)) とする。
    2. Set(obj, propertyKey, value, true)を実行する。
    3. kk + 1に設定する。
  20. objを返す。

23.2.3.10 %TypedArray%.prototype.filter ( callback [ , thisArg ] )

このmethodのargumentsのinterpretationおよびuseは、23.1.3.8で定義されるArray.prototype.filterと同じです。

このmethodは呼び出されたとき、次のstepsを実行します:

  1. objthis valueとする。
  2. taRecordを ? ValidateTypedArray(obj, seq-cst) とする。
  3. lengthTypedArrayLength(taRecord)とする。
  4. IsCallable(callback)がfalseなら、TypeError例外をthrowする。
  5. keptを新しい空のListとする。
  6. capturedを0とする。
  7. kを0とする。
  8. k < lengthの間、繰り返す
    1. propertyKeyを ! ToString(𝔽(k)) とする。
    2. kValueを ! Get(obj, propertyKey) とする。
    3. selectedToBoolean(? Call(callback, thisArg, « kValue, 𝔽(k), obj »))とする。
    4. selectedtrueなら、
      1. kValuekeptへappendする。
      2. capturedcaptured + 1に設定する。
    5. kk + 1に設定する。
  9. resultを ? TypedArraySpeciesCreate(obj, « 𝔽(captured) ») とする。
  10. nを0とする。
  11. keptの各要素elementについて、以下を行う
    1. Set(result, ! ToString(𝔽(n)), element, true)を実行する。
    2. nn + 1に設定する。
  12. resultを返す。

このmethodはgenericではありません。this valueは[[TypedArrayName]] internal slotを持つobjectでなければなりません。

23.2.3.11 %TypedArray%.prototype.find ( predicate [ , thisArg ] )

このmethodのargumentsのinterpretationおよびuseは、23.1.3.9で定義されるArray.prototype.findと同じです。

このmethodは呼び出されたとき、次のstepsを実行します:

  1. objthis valueとする。
  2. taRecordを ? ValidateTypedArray(obj, seq-cst) とする。
  3. lengthTypedArrayLength(taRecord)とする。
  4. findRecordを ? FindViaPredicate(obj, length, ascending, predicate, thisArg) とする。
  5. findRecord.[[Value]]を返す。

このmethodはgenericではありません。this valueは[[TypedArrayName]] internal slotを持つobjectでなければなりません。

23.2.3.12 %TypedArray%.prototype.findIndex ( predicate [ , thisArg ] )

このmethodのargumentsのinterpretationおよびuseは、23.1.3.10で定義されるArray.prototype.findIndexと同じです。

このmethodは呼び出されたとき、次のstepsを実行します:

  1. objthis valueとする。
  2. taRecordを ? ValidateTypedArray(obj, seq-cst) とする。
  3. lengthTypedArrayLength(taRecord)とする。
  4. findRecordを ? FindViaPredicate(obj, length, ascending, predicate, thisArg) とする。
  5. findRecord.[[Index]]を返す。

このmethodはgenericではありません。this valueは[[TypedArrayName]] internal slotを持つobjectでなければなりません。

23.2.3.13 %TypedArray%.prototype.findLast ( predicate [ , thisArg ] )

このmethodのargumentsのinterpretationおよびuseは、23.1.3.11で定義されるArray.prototype.findLastと同じです。

このmethodは呼び出されたとき、次のstepsを実行します:

  1. objthis valueとする。
  2. taRecordを ? ValidateTypedArray(obj, seq-cst) とする。
  3. lengthTypedArrayLength(taRecord)とする。
  4. findRecordを ? FindViaPredicate(obj, length, descending, predicate, thisArg) とする。
  5. findRecord.[[Value]]を返す。

このmethodはgenericではありません。this valueは[[TypedArrayName]] internal slotを持つobjectでなければなりません。

23.2.3.14 %TypedArray%.prototype.findLastIndex ( predicate [ , thisArg ] )

このmethodのargumentsのinterpretationおよびuseは、23.1.3.12で定義されるArray.prototype.findLastIndexと同じです。

このmethodは呼び出されたとき、次のstepsを実行します:

  1. objthis valueとする。
  2. taRecordを ? ValidateTypedArray(obj, seq-cst) とする。
  3. lengthTypedArrayLength(taRecord)とする。
  4. findRecordを ? FindViaPredicate(obj, length, descending, predicate, thisArg) とする。
  5. findRecord.[[Index]]を返す。

このmethodはgenericではありません。this valueは[[TypedArrayName]] internal slotを持つobjectでなければなりません。

23.2.3.15 %TypedArray%.prototype.forEach ( callback [ , thisArg ] )

このmethodのargumentsのinterpretationおよびuseは、23.1.3.15で定義されるArray.prototype.forEachと同じです。

このmethodは呼び出されたとき、次のstepsを実行します:

  1. objthis valueとする。
  2. taRecordを ? ValidateTypedArray(obj, seq-cst) とする。
  3. lengthTypedArrayLength(taRecord)とする。
  4. IsCallable(callback)がfalseなら、TypeError例外をthrowする。
  5. kを0とする。
  6. k < lengthの間、繰り返す
    1. propertyKeyを ! ToString(𝔽(k)) とする。
    2. kValueを ! Get(obj, propertyKey) とする。
    3. Call(callback, thisArg, « kValue, 𝔽(k), obj »)を実行する。
    4. kk + 1に設定する。
  7. undefinedを返す。

このmethodはgenericではありません。this valueは[[TypedArrayName]] internal slotを持つobjectでなければなりません。

23.2.3.16 %TypedArray%.prototype.includes ( searchElement [ , fromIndex ] )

このmethodのargumentsのinterpretationおよびuseは、23.1.3.16で定義されるArray.prototype.includesと同じです。

このmethodは呼び出されたとき、次のstepsを実行します:

  1. objthis valueとする。
  2. taRecordを ? ValidateTypedArray(obj, seq-cst) とする。
  3. lengthTypedArrayLength(taRecord)とする。
  4. length = 0なら、falseを返す。
  5. nを ? ToIntegerOrInfinity(fromIndex) とする。
  6. Assert: fromIndexundefinedなら、nは0である。
  7. n = +∞なら、falseを返す。
  8. n = -∞なら、nを0に設定する。
  9. n ≥ 0なら、
    1. knとする。
  10. そうでなければ、
    1. klength + nとする。
    2. k < 0なら、kを0に設定する。
  11. k < lengthの間、繰り返す
    1. elementKを ! Get(obj, ! ToString(𝔽(k))) とする。
    2. SameValueZero(searchElement, elementK)がtrueなら、trueを返す。
    3. kk + 1に設定する。
  12. falseを返す。

このmethodはgenericではありません。this valueは[[TypedArrayName]] internal slotを持つobjectでなければなりません。

23.2.3.17 %TypedArray%.prototype.indexOf ( searchElement [ , fromIndex ] )

このmethodのargumentsのinterpretationおよびuseは、23.1.3.17で定義されるArray.prototype.indexOfと同じです。

このmethodは呼び出されたとき、次のstepsを実行します:

  1. objthis valueとする。
  2. taRecordを ? ValidateTypedArray(obj, seq-cst) とする。
  3. lengthTypedArrayLength(taRecord)とする。
  4. length = 0なら、-1𝔽を返す。
  5. nを ? ToIntegerOrInfinity(fromIndex) とする。
  6. Assert: fromIndexundefinedなら、nは0である。
  7. n = +∞なら、-1𝔽を返す。
  8. n = -∞なら、nを0に設定する。
  9. n ≥ 0なら、
    1. knとする。
  10. そうでなければ、
    1. klength + nとする。
    2. k < 0なら、kを0に設定する。
  11. k < lengthの間、繰り返す
    1. propertyKeyを ! ToString(𝔽(k)) とする。
    2. kPresentを ! HasProperty(obj, propertyKey) とする。
    3. kPresenttrueなら、
      1. elementKを ! Get(obj, propertyKey) とする。
      2. IsStrictlyEqual(searchElement, elementK)がtrueなら、𝔽(k)を返す。
    4. kk + 1に設定する。
  12. -1𝔽を返す。

このmethodはgenericではありません。this valueは[[TypedArrayName]] internal slotを持つobjectでなければなりません。

23.2.3.18 %TypedArray%.prototype.join ( separator )

このmethodのargumentsのinterpretationおよびuseは、23.1.3.18で定義されるArray.prototype.joinと同じです。

このmethodは呼び出されたとき、次のstepsを実行します:

  1. objthis valueとする。
  2. taRecordを ? ValidateTypedArray(obj, seq-cst) とする。
  3. lengthTypedArrayLength(taRecord)とする。
  4. separatorundefinedなら、sep","とする。
  5. そうでなければ、sepを ? ToString(separator) とする。
  6. resultをempty Stringとする。
  7. kを0とする。
  8. k < lengthの間、繰り返す
    1. k > 0なら、resultresultsepstring-concatenationに設定する。
    2. elementを ! Get(obj, ! ToString(𝔽(k))) とする。
    3. elementundefinedでないなら、
      1. elementStringを ! ToString(element) とする。
      2. resultresultelementStringstring-concatenationに設定する。
    4. kk + 1に設定する。
  9. resultを返す。

このmethodはgenericではありません。this valueは[[TypedArrayName]] internal slotを持つobjectでなければなりません。

23.2.3.19 %TypedArray%.prototype.keys ( )

このmethodは呼び出されたとき、次のstepsを実行します:

  1. objthis valueとする。
  2. ValidateTypedArray(obj, seq-cst)を実行する。
  3. CreateArrayIterator(obj, key)を返す。

23.2.3.20 %TypedArray%.prototype.lastIndexOf ( searchElement [ , fromIndex ] )

このmethodのargumentsのinterpretationおよびuseは、23.1.3.20で定義されるArray.prototype.lastIndexOfと同じです。

このmethodは呼び出されたとき、次のstepsを実行します:

  1. objthis valueとする。
  2. taRecordを ? ValidateTypedArray(obj, seq-cst) とする。
  3. lengthTypedArrayLength(taRecord)とする。
  4. length = 0なら、-1𝔽を返す。
  5. fromIndexがpresentなら、nを ? ToIntegerOrInfinity(fromIndex) とする;そうでなければ、nlength - 1とする。
  6. n = -∞なら、-1𝔽を返す。
  7. n ≥ 0なら、
    1. kmin(n, length - 1)とする。
  8. そうでなければ、
    1. klength + nとする。
  9. k ≥ 0の間、繰り返す
    1. propertyKeyを ! ToString(𝔽(k)) とする。
    2. kPresentを ! HasProperty(obj, propertyKey) とする。
    3. kPresenttrueなら、
      1. elementKを ! Get(obj, propertyKey) とする。
      2. IsStrictlyEqual(searchElement, elementK)がtrueなら、𝔽(k)を返す。
    4. kk - 1に設定する。
  10. -1𝔽を返す。

このmethodはgenericではありません。this valueは[[TypedArrayName]] internal slotを持つobjectでなければなりません。

23.2.3.21 get %TypedArray%.prototype.length

%TypedArray%.prototype.lengthは、set accessor functionがundefinedであるaccessor propertyです。そのget accessor functionは呼び出されたとき、次のstepsを実行します:

  1. objthis valueとする。
  2. RequireInternalSlot(obj, [[TypedArrayName]])を実行する。
  3. Assert: obj[[ViewedArrayBuffer]]および[[ArrayLength]] internal slotsを持つ。
  4. taRecordMakeTypedArrayWithBufferWitnessRecord(obj, seq-cst)とする。
  5. IsTypedArrayOutOfBounds(taRecord)がtrueなら、+0𝔽を返す。
  6. lengthTypedArrayLength(taRecord)とする。
  7. 𝔽(length)を返す。

このfunctionはgenericではありません。this valueは[[TypedArrayName]] internal slotを持つobjectでなければなりません。

23.2.3.22 %TypedArray%.prototype.map ( callback [ , thisArg ] )

このmethodのargumentsのinterpretationおよびuseは、23.1.3.21で定義されるArray.prototype.mapと同じです。

このmethodは呼び出されたとき、次のstepsを実行します:

  1. objthis valueとする。
  2. taRecordを ? ValidateTypedArray(obj, seq-cst) とする。
  3. lengthTypedArrayLength(taRecord)とする。
  4. IsCallable(callback)がfalseなら、TypeError例外をthrowする。
  5. resultを ? TypedArraySpeciesCreate(obj, « 𝔽(length) ») とする。
  6. kを0とする。
  7. k < lengthの間、繰り返す
    1. propertyKeyを ! ToString(𝔽(k)) とする。
    2. kValueを ! Get(obj, propertyKey) とする。
    3. mappedValueを ? Call(callback, thisArg, « kValue, 𝔽(k), obj ») とする。
    4. Set(result, propertyKey, mappedValue, true)を実行する。
    5. kk + 1に設定する。
  8. resultを返す。

このmethodはgenericではありません。this valueは[[TypedArrayName]] internal slotを持つobjectでなければなりません。

23.2.3.23 %TypedArray%.prototype.reduce ( callback [ , initialValue ] )

このmethodのargumentsのinterpretationおよびuseは、23.1.3.24で定義されるArray.prototype.reduceと同じです。

このmethodは呼び出されたとき、次のstepsを実行します:

  1. objthis valueとする。
  2. taRecordを ? ValidateTypedArray(obj, seq-cst) とする。
  3. lengthTypedArrayLength(taRecord)とする。
  4. IsCallable(callback)がfalseなら、TypeError例外をthrowする。
  5. length = 0であり、かつinitialValueがpresentでないなら、TypeError例外をthrowする。
  6. kを0とする。
  7. accumulatorundefinedとする。
  8. initialValueがpresentなら、
    1. accumulatorinitialValueに設定する。
  9. そうでなければ、
    1. propertyKeyを ! ToString(𝔽(k)) とする。
    2. accumulatorを ! Get(obj, propertyKey) に設定する。
    3. kk + 1に設定する。
  10. k < lengthの間、繰り返す
    1. propertyKeyを ! ToString(𝔽(k)) とする。
    2. kValueを ! Get(obj, propertyKey) とする。
    3. accumulatorを ? Call(callback, undefined, « accumulator, kValue, 𝔽(k), obj ») に設定する。
    4. kk + 1に設定する。
  11. accumulatorを返す。

このmethodはgenericではありません。this valueは[[TypedArrayName]] internal slotを持つobjectでなければなりません。

23.2.3.24 %TypedArray%.prototype.reduceRight ( callback [ , initialValue ] )

このmethodのargumentsのinterpretationおよびuseは、23.1.3.25で定義されるArray.prototype.reduceRightと同じです。

このmethodは呼び出されたとき、次のstepsを実行します:

  1. objthis valueとする。
  2. taRecordを ? ValidateTypedArray(obj, seq-cst) とする。
  3. lengthTypedArrayLength(taRecord)とする。
  4. IsCallable(callback)がfalseなら、TypeError例外をthrowする。
  5. length = 0であり、かつinitialValueがpresentでないなら、TypeError例外をthrowする。
  6. klength - 1とする。
  7. accumulatorundefinedとする。
  8. initialValueがpresentなら、
    1. accumulatorinitialValueに設定する。
  9. そうでなければ、
    1. propertyKeyを ! ToString(𝔽(k)) とする。
    2. accumulatorを ! Get(obj, propertyKey) に設定する。
    3. kk - 1に設定する。
  10. k ≥ 0の間、繰り返す
    1. propertyKeyを ! ToString(𝔽(k)) とする。
    2. kValueを ! Get(obj, propertyKey) とする。
    3. accumulatorを ? Call(callback, undefined, « accumulator, kValue, 𝔽(k), obj ») に設定する。
    4. kk - 1に設定する。
  11. accumulatorを返す。

このmethodはgenericではありません。this valueは[[TypedArrayName]] internal slotを持つobjectでなければなりません。

23.2.3.25 %TypedArray%.prototype.reverse ( )

このmethodのargumentsのinterpretationおよびuseは、23.1.3.26で定義されるArray.prototype.reverseと同じです。

このmethodは呼び出されたとき、次のstepsを実行します:

  1. objthis valueとする。
  2. taRecordを ? ValidateTypedArray(obj, seq-cst) とする。
  3. lengthTypedArrayLength(taRecord)とする。
  4. middlefloor(length / 2)とする。
  5. lowerを0とする。
  6. lowermiddleの間、繰り返す
    1. upperlength - lower - 1とする。
    2. upperPを ! ToString(𝔽(upper)) とする。
    3. lowerPを ! ToString(𝔽(lower)) とする。
    4. lowerValueを ! Get(obj, lowerP) とする。
    5. upperValueを ! Get(obj, upperP) とする。
    6. Set(obj, lowerP, upperValue, true)を実行する。
    7. Set(obj, upperP, lowerValue, true)を実行する。
    8. lowerlower + 1に設定する。
  7. objを返す。

このmethodはgenericではありません。this valueは[[TypedArrayName]] internal slotを持つobjectでなければなりません。

23.2.3.26 %TypedArray%.prototype.set ( source [ , offset ] )

このmethodは、このTypedArray内のmultiple valuesをsetし、sourceからvaluesを読み取ります。detailsはsourceのtypeに基づいて異なります。optional offset valueは、valuesがwrittenされるこのTypedArray内のfirst element indexを示します。omittedされる場合、0であるとassumedされます。

これは呼び出されたとき、次のstepsを実行します:

  1. targetthis valueとする。
  2. RequireInternalSlot(target, [[TypedArrayName]])を実行する。
  3. Assert: target[[ViewedArrayBuffer]] internal slotを持つ。
  4. targetOffsetを ? ToIntegerOrInfinity(offset) とする。
  5. targetOffset < 0なら、RangeError例外をthrowする。
  6. source[[TypedArrayName]] internal slotを持つObjectなら、
    1. SetTypedArrayFromTypedArray(target, targetOffset, source)を実行する。
  7. そうでなければ、
    1. SetTypedArrayFromArrayLike(target, targetOffset, source)を実行する。
  8. undefinedを返す。

このmethodはgenericではありません。this valueは[[TypedArrayName]] internal slotを持つobjectでなければなりません。

23.2.3.26.1 SetTypedArrayFromArrayLike ( target, targetOffset, source )

The abstract operation SetTypedArrayFromArrayLike takes arguments target (a TypedArray), targetOffset (a non-negative integer or +∞), and source (an ECMAScript language value, but not a TypedArray) and returns either a normal completion containing unused or a throw completion. これは、target内でindex targetOffsetからstartingして、sourceからvaluesを読み取ってmultiple valuesをsetします。 It performs the following steps when called:

  1. targetRecordMakeTypedArrayWithBufferWitnessRecord(target, seq-cst)とする。
  2. IsTypedArrayOutOfBounds(targetRecord)がtrueなら、TypeError例外をthrowする。
  3. targetLengthTypedArrayLength(targetRecord)とする。
  4. sourceを ? ToObject(source) に設定する。
  5. sourceLengthを ? LengthOfArrayLike(source) とする。
  6. targetOffset = +∞なら、RangeError例外をthrowする。
  7. sourceLength + targetOffset > targetLengthなら、RangeError例外をthrowする。
  8. kを0とする。
  9. k < sourceLengthの間、繰り返す
    1. propertyKeyを ! ToString(𝔽(k)) とする。
    2. valueを ? Get(source, propertyKey) とする。
    3. targetIndex𝔽(targetOffset + k)とする。
    4. TypedArraySetElement(target, targetIndex, value)を実行する。
    5. kk + 1に設定する。
  10. unusedを返す。

23.2.3.26.2 SetTypedArrayFromTypedArray ( target, targetOffset, source )

The abstract operation SetTypedArrayFromTypedArray takes arguments target (a TypedArray), targetOffset (a non-negative integer or +∞), and source (a TypedArray) and returns either a normal completion containing unused or a throw completion. これは、target内でindex targetOffsetからstartingして、sourceからvaluesを読み取ってmultiple valuesをsetします。 It performs the following steps when called:

  1. targetBuffertarget.[[ViewedArrayBuffer]]とする。
  2. targetRecordMakeTypedArrayWithBufferWitnessRecord(target, seq-cst)とする。
  3. IsTypedArrayOutOfBounds(targetRecord)がtrueなら、TypeError例外をthrowする。
  4. targetLengthTypedArrayLength(targetRecord)とする。
  5. sourceBuffersource.[[ViewedArrayBuffer]]とする。
  6. sourceRecordMakeTypedArrayWithBufferWitnessRecord(source, seq-cst)とする。
  7. IsTypedArrayOutOfBounds(sourceRecord)がtrueなら、TypeError例外をthrowする。
  8. sourceLengthTypedArrayLength(sourceRecord)とする。
  9. targetTypeTypedArrayElementType(target)とする。
  10. targetElementSizeTypedArrayElementSize(target)とする。
  11. targetByteOffsettarget.[[ByteOffset]]とする。
  12. sourceTypeTypedArrayElementType(source)とする。
  13. sourceElementSizeTypedArrayElementSize(source)とする。
  14. sourceByteOffsetsource.[[ByteOffset]]とする。
  15. targetOffset = +∞なら、RangeError例外をthrowする。
  16. sourceLength + targetOffset > targetLengthなら、RangeError例外をthrowする。
  17. target.[[ContentType]]source.[[ContentType]]でないなら、TypeError例外をthrowする。
  18. IsSharedArrayBuffer(sourceBuffer)がtrueであり、IsSharedArrayBuffer(targetBuffer)がtrueであり、かつsourceBuffer.[[ArrayBufferData]]targetBuffer.[[ArrayBufferData]]であるなら、sameSharedArrayBuffertrueとする;そうでなければ、sameSharedArrayBufferfalseとする。
  19. SameValue(sourceBuffer, targetBuffer)がtrueまたはsameSharedArrayBuffertrueなら、
    1. sourceByteLengthTypedArrayByteLength(sourceRecord)とする。
    2. sourceBufferを ? CloneArrayBuffer(sourceBuffer, sourceByteOffset, sourceByteLength) に設定する。
    3. sourceByteIndexを0とする。
  20. そうでなければ、
    1. sourceByteIndexsourceByteOffsetとする。
  21. targetByteIndexを(targetOffset × targetElementSize) + targetByteOffsetとする。
  22. limittargetByteIndex + (targetElementSize × sourceLength)とする。
  23. sourceTypetargetTypeなら、
    1. NOTE: transferはsource dataのbit-level encodingをpreserveするmannerでperformedされなければならない。
    2. targetByteIndex < limitの間、繰り返す
      1. valueGetValueFromBuffer(sourceBuffer, sourceByteIndex, uint8, true, unordered)とする。
      2. SetValueInBuffer(targetBuffer, targetByteIndex, uint8, value, true, unordered)を実行する。
      3. sourceByteIndexsourceByteIndex + 1に設定する。
      4. targetByteIndextargetByteIndex + 1に設定する。
  24. そうでなければ、
    1. targetByteIndex < limitの間、繰り返す
      1. valueGetValueFromBuffer(sourceBuffer, sourceByteIndex, sourceType, true, unordered)とする。
      2. SetValueInBuffer(targetBuffer, targetByteIndex, targetType, value, true, unordered)を実行する。
      3. sourceByteIndexsourceByteIndex + sourceElementSizeに設定する。
      4. targetByteIndextargetByteIndex + targetElementSizeに設定する。
  25. unusedを返す。

23.2.3.27 %TypedArray%.prototype.slice ( start, end )

このmethodのargumentsのinterpretationおよびuseは、23.1.3.28で定義されるArray.prototype.sliceと同じです。

このmethodは呼び出されたとき、次のstepsを実行します:

  1. objthis valueとする。
  2. taRecordを ? ValidateTypedArray(obj, seq-cst) とする。
  3. sourceArrayLengthTypedArrayLength(taRecord)とする。
  4. relativeStartを ? ToIntegerOrInfinity(start) とする。
  5. relativeStart = -∞なら、startIndexを0とする。
  6. そうでなく、relativeStart < 0なら、startIndexmax(sourceArrayLength + relativeStart, 0)とする。
  7. そうでなければ、startIndexmin(relativeStart, sourceArrayLength)とする。
  8. endundefinedなら、relativeEndsourceArrayLengthとする;そうでなければ、relativeEndを ? ToIntegerOrInfinity(end) とする。
  9. relativeEnd = -∞なら、endIndexを0とする。
  10. そうでなく、relativeEnd < 0なら、endIndexmax(sourceArrayLength + relativeEnd, 0)とする。
  11. そうでなければ、endIndexmin(relativeEnd, sourceArrayLength)とする。
  12. countBytesmax(endIndex - startIndex, 0)とする。
  13. resultArrayを ? TypedArraySpeciesCreate(obj, « 𝔽(countBytes) ») とする。
  14. countBytes > 0なら、
    1. taRecordMakeTypedArrayWithBufferWitnessRecord(obj, seq-cst)に設定する。
    2. IsTypedArrayOutOfBounds(taRecord)がtrueなら、TypeError例外をthrowする。
    3. endIndexmin(endIndex, TypedArrayLength(taRecord))に設定する。
    4. countBytesmax(endIndex - startIndex, 0)に設定する。
    5. sourceTypeTypedArrayElementType(obj)とする。
    6. targetTypeTypedArrayElementType(resultArray)とする。
    7. sourceTypetargetTypeなら、
      1. NOTE: transferはsource dataのbit-level encodingをpreserveするmannerでperformedされなければならない。
      2. sourceBufferobj.[[ViewedArrayBuffer]]とする。
      3. targetBufferresultArray.[[ViewedArrayBuffer]]とする。
      4. elementSizeTypedArrayElementSize(obj)とする。
      5. sourceByteOffsetobj.[[ByteOffset]]とする。
      6. sourceByteIndexを(startIndex × elementSize) + sourceByteOffsetとする。
      7. targetByteIndexresultArray.[[ByteOffset]]とする。
      8. endByteIndextargetByteIndex + (countBytes × elementSize)とする。
      9. targetByteIndex < endByteIndexの間、繰り返す
        1. valueGetValueFromBuffer(sourceBuffer, sourceByteIndex, uint8, true, unordered)とする。
        2. SetValueInBuffer(targetBuffer, targetByteIndex, uint8, value, true, unordered)を実行する。
        3. sourceByteIndexsourceByteIndex + 1に設定する。
        4. targetByteIndextargetByteIndex + 1に設定する。
    8. そうでなければ、
      1. nを0とする。
      2. kstartIndexとする。
      3. k < endIndexの間、繰り返す
        1. propertyKeyを ! ToString(𝔽(k)) とする。
        2. kValueを ! Get(obj, propertyKey) とする。
        3. Set(resultArray, ! ToString(𝔽(n)), kValue, true)を実行する。
        4. kk + 1に設定する。
        5. nn + 1に設定する。
  15. resultArrayを返す。

このmethodはgenericではありません。this valueは[[TypedArrayName]] internal slotを持つobjectでなければなりません。

23.2.3.28 %TypedArray%.prototype.some ( callback [ , thisArg ] )

このmethodのargumentsのinterpretationおよびuseは、23.1.3.29で定義されるArray.prototype.someと同じです。

このmethodは呼び出されたとき、次のstepsを実行します:

  1. objthis valueとする。
  2. taRecordを ? ValidateTypedArray(obj, seq-cst) とする。
  3. lengthTypedArrayLength(taRecord)とする。
  4. IsCallable(callback)がfalseなら、TypeError例外をthrowする。
  5. kを0とする。
  6. k < lengthの間、繰り返す
    1. propertyKeyを ! ToString(𝔽(k)) とする。
    2. kValueを ! Get(obj, propertyKey) とする。
    3. testResultToBoolean(? Call(callback, thisArg, « kValue, 𝔽(k), obj »))とする。
    4. testResulttrueなら、trueを返す。
    5. kk + 1に設定する。
  7. falseを返す。

このmethodはgenericではありません。this valueは[[TypedArrayName]] internal slotを持つobjectでなければなりません。

23.2.3.29 %TypedArray%.prototype.sort ( comparator )

これはdistinct methodであり、以下でdescribedされる点を除き、23.1.3.30で定義されるArray.prototype.sortのrequirementsとsame requirementsをimplementします。このmethodのimplementationは、this valueがfixed lengthを持ち、そのinteger-indexed propertiesがsparseでないobjectであるというknowledgeを用いてoptimizedされてもよいです。

このmethodはgenericではありません。this valueは[[TypedArrayName]] internal slotを持つobjectでなければなりません。

これは呼び出されたとき、次のstepsを実行します:

  1. comparatorundefinedでなく、かつIsCallable(comparator)がfalseなら、TypeError例外をthrowする。
  2. objthis valueとする。
  3. taRecordを ? ValidateTypedArray(obj, seq-cst) とする。
  4. lengthTypedArrayLength(taRecord)とする。
  5. NOTE: 以下のclosureは、23.1.3.30で使用されるstring comparisonではなくnumeric comparisonをperformする。
  6. sortCompareを、comparatorをcaptureし、calledされたときに次のstepsを実行する、parameters (x, y)を持つnew Abstract Closureとする:
    1. CompareTypedArrayElements(x, y, comparator)を返す。
  7. sortedListを ? SortIndexedProperties(obj, length, sortCompare, read-through-holes) とする。
  8. jを0とする。
  9. j < lengthの間、繰り返す
    1. Set(obj, ! ToString(𝔽(j)), sortedList[j], true)を実行する。
    2. jj + 1に設定する。
  10. objを返す。
Note

NaNは常にany other valueよりgreaterとしてcompareされるため(CompareTypedArrayElementsを参照)、comparatorがprovidedされない場合、NaN property valuesは常にresultのendへsortされます。

23.2.3.30 %TypedArray%.prototype.subarray ( start, end )

このmethodは、element typeがこのTypedArrayのelement typeであり、ArrayBufferがこのTypedArrayのArrayBufferであるnew TypedArrayを返し、start(inclusive)からend(exclusive)までのinterval内のelementsをreferします。startまたはendのいずれかがnegativeである場合、beginningからではなく、arrayのendからのindexをreferします。

これは呼び出されたとき、次のstepsを実行します:

  1. objthis valueとする。
  2. RequireInternalSlot(obj, [[TypedArrayName]])を実行する。
  3. Assert: obj[[ViewedArrayBuffer]] internal slotを持つ。
  4. bufferobj.[[ViewedArrayBuffer]]とする。
  5. sourceRecordMakeTypedArrayWithBufferWitnessRecord(obj, seq-cst)とする。
  6. IsTypedArrayOutOfBounds(sourceRecord)がtrueなら、
    1. sourceLengthを0とする。
  7. そうでなければ、
    1. sourceLengthTypedArrayLength(sourceRecord)とする。
  8. relativeStartを ? ToIntegerOrInfinity(start) とする。
  9. relativeStart = -∞なら、startIndexを0とする。
  10. そうでなく、relativeStart < 0なら、startIndexmax(sourceLength + relativeStart, 0)とする。
  11. そうでなければ、startIndexmin(relativeStart, sourceLength)とする。
  12. elementSizeTypedArrayElementSize(obj)とする。
  13. sourceByteOffsetobj.[[ByteOffset]]とする。
  14. beginByteOffsetsourceByteOffset + (startIndex × elementSize)とする。
  15. obj.[[ArrayLength]]autoであり、かつendundefinedなら、
    1. argListを« buffer, 𝔽(beginByteOffset) »とする。
  16. そうでなければ、
    1. endundefinedなら、relativeEndsourceLengthとする;そうでなければ、relativeEndを ? ToIntegerOrInfinity(end) とする。
    2. relativeEnd = -∞なら、endIndexを0とする。
    3. そうでなく、relativeEnd < 0なら、endIndexmax(sourceLength + relativeEnd, 0)とする。
    4. そうでなければ、endIndexmin(relativeEnd, sourceLength)とする。
    5. newLengthmax(endIndex - startIndex, 0)とする。
    6. argListを« buffer, 𝔽(beginByteOffset), 𝔽(newLength) »とする。
  17. TypedArraySpeciesCreate(obj, argList)を返す。

このmethodはgenericではありません。this valueは[[TypedArrayName]] internal slotを持つobjectでなければなりません。

23.2.3.31 %TypedArray%.prototype.toLocaleString ( [ reserved1 [ , reserved2 ] ] )

これはdistinct methodであり、23.1.3.32で定義されるArray.prototype.toLocaleStringとsame algorithmをimplementします。ただし、"length"[[Get]]をperformする代わりにTypedArrayLengthがcalledされます。このalgorithmのimplementationは、underlying bufferがresizableでない場合にthis valueがfixed lengthを持ち、そのinteger-indexed propertiesがsparseでないというknowledgeを用いてoptimizedされてもよいです。しかし、そのようなoptimizationは、algorithmのspecified behaviourにobservable changesを導入してはなりません。

このmethodはgenericではありません。ValidateTypedArrayは、algorithmをevaluatingする前に、this valueおよびseq-cstをargumentsとして呼び出されます。そのresultがabrupt completionである場合、algorithmをevaluatingする代わりにそのexceptionがthrowされます。

Note

ECMAScript implementationがECMA-402 Internationalization APIを含む場合、このmethodはECMA-402 specification内のArray.prototype.toLocaleStringのalgorithmに基づきます。

23.2.3.32 %TypedArray%.prototype.toReversed ( )

このmethodは呼び出されたとき、次のstepsを実行します:

  1. objthis valueとする。
  2. taRecordを ? ValidateTypedArray(obj, seq-cst) とする。
  3. lengthTypedArrayLength(taRecord)とする。
  4. resultArrayを ? TypedArrayCreateSameType(obj, length) とする。
  5. kを0とする。
  6. k < lengthの間、繰り返す
    1. fromを ! ToString(𝔽(length - k - 1)) とする。
    2. propertyKeyを ! ToString(𝔽(k)) とする。
    3. fromValueを ! Get(obj, from) とする。
    4. Set(resultArray, propertyKey, fromValue, true)を実行する。
    5. kk + 1に設定する。
  7. resultArrayを返す。

23.2.3.33 %TypedArray%.prototype.toSorted ( comparator )

このmethodは呼び出されたとき、次のstepsを実行します:

  1. comparatorundefinedでなく、かつIsCallable(comparator)がfalseなら、TypeError例外をthrowする。
  2. objthis valueとする。
  3. taRecordを ? ValidateTypedArray(obj, seq-cst) とする。
  4. lengthTypedArrayLength(taRecord)とする。
  5. resultArrayを ? TypedArrayCreateSameType(obj, length) とする。
  6. NOTE: 以下のclosureは、23.1.3.34で使用されるstring comparisonではなくnumeric comparisonをperformする。
  7. sortCompareを、comparatorをcaptureし、calledされたときに次のstepsを実行する、parameters (x, y)を持つnew Abstract Closureとする:
    1. CompareTypedArrayElements(x, y, comparator)を返す。
  8. sortedListを ? SortIndexedProperties(obj, length, sortCompare, read-through-holes) とする。
  9. jを0とする。
  10. j < lengthの間、繰り返す
    1. Set(resultArray, ! ToString(𝔽(j)), sortedList[j], true)を実行する。
    2. jj + 1に設定する。
  11. resultArrayを返す。

23.2.3.34 %TypedArray%.prototype.toString ( )

"toString" propertyのinitial valueは、23.1.3.36で定義される%Array.prototype.toString%です。

23.2.3.35 %TypedArray%.prototype.values ( )

このmethodは呼び出されたとき、次のstepsを実行します:

  1. objthis valueとする。
  2. ValidateTypedArray(obj, seq-cst)を実行する。
  3. CreateArrayIterator(obj, value)を返す。

23.2.3.36 %TypedArray%.prototype.with ( index, value )

このmethodは呼び出されたとき、次のstepsを実行します:

  1. objthis valueとする。
  2. taRecordを ? ValidateTypedArray(obj, seq-cst) とする。
  3. lengthTypedArrayLength(taRecord)とする。
  4. relativeIndexを ? ToIntegerOrInfinity(index) とする。
  5. relativeIndex ≥ 0なら、actualIndexrelativeIndexとする。
  6. そうでなければ、actualIndexlength + relativeIndexとする。
  7. obj.[[ContentType]]bigintなら、numericValueを ? ToBigInt(value) とする。
  8. そうでなければ、numericValueを ? ToNumber(value) とする。
  9. IsValidIntegerIndex(obj, 𝔽(actualIndex))がfalseなら、RangeError例外をthrowする。
  10. resultArrayを ? TypedArrayCreateSameType(obj, length) とする。
  11. kを0とする。
  12. k < lengthの間、繰り返す
    1. propertyKeyを ! ToString(𝔽(k)) とする。
    2. k = actualIndexなら、fromValuenumericValueとする。
    3. そうでなければ、fromValueを ! Get(obj, propertyKey) とする。
    4. Set(resultArray, propertyKey, fromValue, true)を実行する。
    5. kk + 1に設定する。
  13. resultArrayを返す。

23.2.3.37 %TypedArray%.prototype [ %Symbol.iterator% ] ( )

%Symbol.iterator% propertyのinitial valueは、23.2.3.35で定義される%TypedArray.prototype.values%です。

23.2.3.38 get %TypedArray%.prototype [ %Symbol.toStringTag% ]

%TypedArray%.prototype[%Symbol.toStringTag%]は、set accessor functionがundefinedであるaccessor propertyです。そのget accessor functionは呼び出されたとき、次のstepsを実行します:

  1. objthis valueとする。
  2. objがObjectでないなら、undefinedを返す。
  3. obj[[TypedArrayName]] internal slotを持たないなら、undefinedを返す。
  4. nameobj.[[TypedArrayName]]とする。
  5. Assert: nameはStringである。
  6. nameを返す。

このpropertyはattributes { [[Enumerable]]: false, [[Configurable]]: true }を持ちます。

このfunctionの"name" propertyのinitial valueは"get [Symbol.toStringTag]"です。

23.2.4 Abstract Operations for TypedArray Objects

23.2.4.1 TypedArrayCreateFromConstructor ( ctor, argList )

The abstract operation TypedArrayCreateFromConstructor takes arguments ctor (a constructor) and argList (a List of ECMAScript language values) and returns either a normal completion containing a TypedArray or a throw completion. これは、constructor functionを使用したnew TypedArrayのcreationをspecifyするために使用されます。 It performs the following steps when called:

  1. taを ? Construct(ctor, argList) とする。
  2. taRecordを ? ValidateTypedArray(ta, seq-cst) とする。
  3. Assert: taProperties of TypedArray Instancesでmentionedされるすべてのinternal slotsを持つ。
  4. argList内のelementsの数が1であり、かつargList[0]がNumberなら、
    1. IsTypedArrayOutOfBounds(taRecord)がtrueなら、TypeError例外をthrowする。
    2. lengthTypedArrayLength(taRecord)とする。
    3. length < (argList[0])なら、TypeError例外をthrowする。
  5. taを返す。

23.2.4.2 TypedArrayCreateSameType ( exemplar, length )

The abstract operation TypedArrayCreateSameType takes arguments exemplar (a TypedArray) and length (a non-negative integer) and returns either a normal completion containing a TypedArray or a throw completion. これは、exemplarからderivedされたconstructor functionを使用したnew TypedArrayのcreationをspecifyするために使用されます。%Symbol.species%のuseを通じてcustom TypedArray subclassesをconstructできるTypedArraySpeciesCreateとは異なり、このoperationは常にbuilt-in TypedArray constructorsのoneを使用します。 It performs the following steps when called:

  1. ctorを、Table 71内のconstructor name exemplar.[[TypedArrayName]]にassociatedするintrinsic objectとする。
  2. resultを ? TypedArrayCreateFromConstructor(ctor, « 𝔽(length) ») とする。
  3. Assert: result[[TypedArrayName]]および[[ContentType]] internal slotsを持つ。
  4. Assert: result.[[ContentType]]exemplar.[[ContentType]]である。
  5. resultを返す。

23.2.4.3 TypedArraySpeciesCreate ( exemplar, argList )

The abstract operation TypedArraySpeciesCreate takes arguments exemplar (a TypedArray) and argList (a List of ECMAScript language values) and returns either a normal completion containing a TypedArray or a throw completion. これは、exemplarからderivedされたconstructor functionを使用したnew TypedArrayのcreationをspecifyするために使用されます。%Symbol.species%のuseを通じてnon-Array objectsをcreateできるArraySpeciesCreateとは異なり、このoperationはconstructor functionがactual TypedArrayをcreateすることをenforceします。 It performs the following steps when called:

  1. defaultCtorを、Table 71内のconstructor name exemplar.[[TypedArrayName]]にassociatedするintrinsic objectとする。
  2. ctorを ? SpeciesConstructor(exemplar, defaultCtor) とする。
  3. resultを ? TypedArrayCreateFromConstructor(ctor, argList) とする。
  4. result.[[ContentType]]exemplar.[[ContentType]]でないなら、TypeError例外をthrowする。
  5. resultを返す。

23.2.4.4 ValidateTypedArray ( obj, order )

The abstract operation ValidateTypedArray takes arguments obj (an ECMAScript language value) and order (seq-cst or unordered) 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. RequireInternalSlot(obj, [[TypedArrayName]])を実行する。
  2. Assert: obj[[ViewedArrayBuffer]] internal slotを持つ。
  3. taRecordMakeTypedArrayWithBufferWitnessRecord(obj, order)とする。
  4. IsTypedArrayOutOfBounds(taRecord)がtrueなら、TypeError例外をthrowする。
  5. taRecordを返す。

23.2.4.5 TypedArrayElementSize ( obj )

The abstract operation TypedArrayElementSize takes argument obj (a TypedArray) and returns a non-negative integer. It performs the following steps when called:

  1. obj.[[TypedArrayName]]についてTable 71でspecifiedされるElement Size valueを返す。

23.2.4.6 TypedArrayElementType ( obj )

The abstract operation TypedArrayElementType takes argument obj (a TypedArray) and returns a TypedArray element type. It performs the following steps when called:

  1. obj.[[TypedArrayName]]についてTable 71でspecifiedされるElement Type valueを返す。

23.2.4.7 CompareTypedArrayElements ( x, y, comparator )

The abstract operation CompareTypedArrayElements takes arguments x (a Number or a BigInt), y (a Number or a BigInt), and comparator (a function object or undefined) and returns either a normal completion containing a Number or an abrupt completion. It performs the following steps when called:

  1. Assert: xはNumberでありyはNumberである、またはxはBigIntでありyはBigIntである。
  2. comparatorundefinedでないなら、
    1. resultを ? ToNumber(? Call(comparator, undefined, « x, y »)) とする。
    2. resultNaNなら、+0𝔽を返す。
    3. resultを返す。
  3. xNaNであり、かつyNaNなら、+0𝔽を返す。
  4. xNaNなら、1𝔽を返す。
  5. yNaNなら、-1𝔽を返す。
  6. x < yなら、-1𝔽を返す。
  7. x > yなら、1𝔽を返す。
  8. x-0𝔽であり、かつy+0𝔽なら、-1𝔽を返す。
  9. x+0𝔽であり、かつy-0𝔽なら、1𝔽を返す。
  10. +0𝔽を返す。
Note
これは、23.1.3.30.2で使用されるstring comparisonではなくnumeric comparisonをperformします。

23.2.5 The TypedArray Constructors

TypedArray constructorは:

  • otherwise notedされる場合を除き、Table 71内で、TypedArrayの代わりにconstructor nameとして使用されるnameのみが異なる、以下でdescribedされるstructureを持つintrinsic objectです。
  • argumentsの数およびtypesに基づいてbehaviourが異なるfunctionです。TypedArrayのcallのactual behaviourは、それにpassedされるargumentsのnumberおよびkindに依存します。
  • functionとして呼び出されることを意図しておらず、そのようなmannerで呼び出されるとexceptionをthrowします。
  • クラス定義の extends 句の値として使用できる。指定された TypedArray の動作を継承しようとするサブクラスコンストラクターは、%TypedArray%.prototype の組み込みメソッドをサポートするために必要な内部状態でサブクラスインスタンスを作成し初期化するため、TypedArray コンストラクターへの super 呼び出しを含めなければならない。

23.2.5.1 TypedArray ( ...args )

TypedArray constructorは呼び出されたとき、次のstepsを実行します:

  1. NewTargetがundefinedなら、TypeError例外をthrowする。
  2. ctorNameを、this TypedArray constructorについてTable 71でspecifiedされるConstructor Name valueのString valueとする。
  3. proto"%TypedArray.prototype%"とする。
  4. numberOfArgsargs内のelementsの数とする。
  5. numberOfArgs = 0なら、? AllocateTypedArray(ctorName, NewTarget, proto, 0)を返す。
  6. firstArgargs[0]とする。
  7. firstArgがObjectなら、
    1. objを ? AllocateTypedArray(ctorName, NewTarget, proto) とする。
    2. firstArg[[TypedArrayName]] internal slotを持つなら、
      1. InitializeTypedArrayFromTypedArray(obj, firstArg)を実行する。
    3. そうでなく、firstArg[[ArrayBufferData]] internal slotを持つなら、
      1. numberOfArgs > 1なら、byteOffsetargs[1]とする;そうでなければ、byteOffsetundefinedとする。
      2. numberOfArgs > 2なら、lengthargs[2]とする;そうでなければ、lengthundefinedとする。
      3. InitializeTypedArrayFromArrayBuffer(obj, firstArg, byteOffset, length)を実行する。
    4. そうでなければ、
      1. Assert: firstArgはObjectであり、firstArg[[TypedArrayName]]および[[ArrayBufferData]] internal slotのいずれも持たない。
      2. usingIteratorを ? GetMethod(firstArg, %Symbol.iterator%) とする。
      3. usingIteratorundefinedでないなら、
        1. valuesを ? IteratorToList(? GetIteratorFromMethod(firstArg, usingIterator)) とする。
        2. InitializeTypedArrayFromList(obj, values)を実行する。
      4. そうでなければ、
        1. NOTE: firstArgiterable objectではないため、すでにarray-like objectであるとassumeする。
        2. InitializeTypedArrayFromArrayLike(obj, firstArg)を実行する。
    5. objを返す。
  8. Assert: firstArgはObjectではない。
  9. elementLengthを ? ToIndex(firstArg) とする。
  10. AllocateTypedArray(ctorName, NewTarget, proto, elementLength)を返す。

23.2.5.1.1 AllocateTypedArray ( ctorName, newTarget, defaultProto [ , length ] )

The abstract operation AllocateTypedArray takes arguments ctorName (a String which is the name of a TypedArray constructor in Table 71), newTarget (a constructor), and defaultProto (a String) and optional argument length (a non-negative integer) and returns either a normal completion containing a TypedArray or a throw completion. これは、TypedArray constructorのinstanceをvalidateおよびcreateするために使用されます。length argumentがpassedされる場合、そのlengthのArrayBufferもallocatedされ、new TypedArray instanceにassociatedされます。AllocateTypedArrayはTypedArrayによって使用されるcommon semanticsを提供します。 It performs the following steps when called:

  1. protoを ? GetPrototypeFromConstructor(newTarget, defaultProto) とする。
  2. objTypedArrayCreate(proto)とする。
  3. Assert: obj.[[ViewedArrayBuffer]]undefinedである。
  4. obj.[[TypedArrayName]]ctorNameに設定する。
  5. ctorName"BigInt64Array"または"BigUint64Array"のいずれかなら、obj.[[ContentType]]bigintに設定する。
  6. そうでなければ、obj.[[ContentType]]numberに設定する。
  7. lengthがpresentでないなら、
    1. obj.[[ByteLength]]を0に設定する。
    2. obj.[[ByteOffset]]を0に設定する。
    3. obj.[[ArrayLength]]を0に設定する。
  8. そうでなければ、
    1. AllocateTypedArrayBuffer(obj, length)を実行する。
  9. objを返す。

23.2.5.1.2 InitializeTypedArrayFromTypedArray ( obj, sourceArray )

The abstract operation InitializeTypedArrayFromTypedArray takes arguments obj (a TypedArray) and sourceArray (a TypedArray) and returns either a normal completion containing unused or a throw completion. It performs the following steps when called:

  1. sourceDatasourceArray.[[ViewedArrayBuffer]]とする。
  2. elementTypeTypedArrayElementType(obj)とする。
  3. elementSizeTypedArrayElementSize(obj)とする。
  4. sourceTypeTypedArrayElementType(sourceArray)とする。
  5. sourceElementSizeTypedArrayElementSize(sourceArray)とする。
  6. sourceByteOffsetsourceArray.[[ByteOffset]]とする。
  7. sourceRecordMakeTypedArrayWithBufferWitnessRecord(sourceArray, seq-cst)とする。
  8. IsTypedArrayOutOfBounds(sourceRecord)がtrueなら、TypeError例外をthrowする。
  9. elementLengthTypedArrayLength(sourceRecord)とする。
  10. byteLengthelementSize × elementLengthとする。
  11. elementTypesourceTypeなら、
    1. dataを ? CloneArrayBuffer(sourceData, sourceByteOffset, byteLength) とする。
  12. そうでなければ、
    1. dataを ? AllocateArrayBuffer(%ArrayBuffer%, byteLength) とする。
    2. sourceArray.[[ContentType]]obj.[[ContentType]]でないなら、TypeError例外をthrowする。
    3. sourceByteIndexsourceByteOffsetとする。
    4. targetByteIndexを0とする。
    5. countelementLengthとする。
    6. count > 0の間、繰り返す
      1. valueGetValueFromBuffer(sourceData, sourceByteIndex, sourceType, true, unordered)とする。
      2. SetValueInBuffer(data, targetByteIndex, elementType, value, true, unordered)を実行する。
      3. sourceByteIndexsourceByteIndex + sourceElementSizeに設定する。
      4. targetByteIndextargetByteIndex + elementSizeに設定する。
      5. countcount - 1に設定する。
  13. obj.[[ViewedArrayBuffer]]dataに設定する。
  14. obj.[[ByteLength]]byteLengthに設定する。
  15. obj.[[ByteOffset]]を0に設定する。
  16. obj.[[ArrayLength]]elementLengthに設定する。
  17. unusedを返す。

23.2.5.1.3 InitializeTypedArrayFromArrayBuffer ( obj, buffer, byteOffset, length )

The abstract operation InitializeTypedArrayFromArrayBuffer takes arguments obj (a TypedArray), buffer (an ArrayBuffer or a SharedArrayBuffer), byteOffset (an ECMAScript language value), and length (an ECMAScript language value) and returns either a normal completion containing unused or a throw completion. It performs the following steps when called:

  1. elementSizeTypedArrayElementSize(obj)とする。
  2. offsetを ? ToIndex(byteOffset) とする。
  3. offset modulo elementSize ≠ 0なら、RangeError例外をthrowする。
  4. bufferIsFixedLengthIsFixedLengthArrayBuffer(buffer)とする。
  5. lengthundefinedでないなら、
    1. newLengthを ? ToIndex(length) とする。
  6. IsDetachedBuffer(buffer)がtrueなら、TypeError例外をthrowする。
  7. bufferByteLengthArrayBufferByteLength(buffer, seq-cst)とする。
  8. lengthundefinedであり、かつbufferIsFixedLengthfalseなら、
    1. offset > bufferByteLengthなら、RangeError例外をthrowする。
    2. obj.[[ByteLength]]autoに設定する。
    3. obj.[[ArrayLength]]autoに設定する。
  9. そうでなければ、
    1. lengthundefinedなら、
      1. bufferByteLength modulo elementSize ≠ 0なら、RangeError例外をthrowする。
      2. newByteLengthbufferByteLength - offsetとする。
      3. newByteLength < 0なら、RangeError例外をthrowする。
    2. そうでなければ、
      1. newByteLengthnewLength × elementSizeとする。
      2. offset + newByteLength > bufferByteLengthなら、RangeError例外をthrowする。
    3. obj.[[ByteLength]]newByteLengthに設定する。
    4. obj.[[ArrayLength]]newByteLength / elementSizeに設定する。
  10. obj.[[ViewedArrayBuffer]]bufferに設定する。
  11. obj.[[ByteOffset]]offsetに設定する。
  12. unusedを返す。

23.2.5.1.4 InitializeTypedArrayFromList ( obj, values )

The abstract operation InitializeTypedArrayFromList takes arguments obj (a TypedArray) and values (a List of ECMAScript language values) and returns either a normal completion containing unused or a throw completion. It performs the following steps when called:

  1. lengthvalues内のelementsの数とする。
  2. AllocateTypedArrayBuffer(obj, length)を実行する。
  3. kを0とする。
  4. k < lengthの間、繰り返す
    1. propertyKeyを ! ToString(𝔽(k)) とする。
    2. kValuevaluesのfirst elementとする。
    3. valuesからfirst elementをremoveする。
    4. Set(obj, propertyKey, kValue, true)を実行する。
    5. kk + 1に設定する。
  5. Assert: valuesは現在empty Listである。
  6. unusedを返す。

23.2.5.1.5 InitializeTypedArrayFromArrayLike ( obj, arrayLike )

The abstract operation InitializeTypedArrayFromArrayLike takes arguments obj (a TypedArray) and arrayLike (an Object, but not a TypedArray or an ArrayBuffer) and returns either a normal completion containing unused or a throw completion. It performs the following steps when called:

  1. lengthを ? LengthOfArrayLike(arrayLike) とする。
  2. AllocateTypedArrayBuffer(obj, length)を実行する。
  3. kを0とする。
  4. k < lengthの間、繰り返す
    1. propertyKeyを ! ToString(𝔽(k)) とする。
    2. kValueを ? Get(arrayLike, propertyKey) とする。
    3. Set(obj, propertyKey, kValue, true)を実行する。
    4. kk + 1に設定する。
  5. unusedを返す。

23.2.5.1.6 AllocateTypedArrayBuffer ( obj, length )

The abstract operation AllocateTypedArrayBuffer takes arguments obj (a TypedArray) and length (a non-negative integer) and returns either a normal completion containing unused or a throw completion. これはArrayBufferをallocateし、それをobjにassociateします。 It performs the following steps when called:

  1. Assert: obj.[[ViewedArrayBuffer]]undefinedである。
  2. elementSizeTypedArrayElementSize(obj)とする。
  3. byteLengthelementSize × lengthとする。
  4. dataを ? AllocateArrayBuffer(%ArrayBuffer%, byteLength) とする。
  5. obj.[[ViewedArrayBuffer]]dataに設定する。
  6. obj.[[ByteLength]]byteLengthに設定する。
  7. obj.[[ByteOffset]]を0に設定する。
  8. obj.[[ArrayLength]]lengthに設定する。
  9. unusedを返す。

23.2.6 Properties of the TypedArray Constructors

TypedArray constructorは:

  • valueが%TypedArray%である[[Prototype]] internal slotを持ちます。
  • valueが3𝔽である"length" propertyを持ちます。
  • valueが、Table 71でそれについてspecifiedされるconstructor nameのString valueである"name" propertyを持ちます。
  • 次のpropertiesを持ちます:

23.2.6.1 TypedArray.BYTES_PER_ELEMENT

TypedArray.BYTES_PER_ELEMENTのvalueは、TypedArrayについてTable 71でspecifiedされるElement Size valueです。

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

23.2.6.2 TypedArray.prototype

TypedArray.prototypeのinitial valueは、corresponding TypedArray prototype intrinsic object(23.2.7)です。

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

23.2.7 Properties of the TypedArray Prototype Objects

TypedArray prototype objectは:

  • valueが%TypedArray.prototype%である[[Prototype]] internal slotを持ちます。
  • ordinary objectです。
  • [[ViewedArrayBuffer]]や、TypedArray instance objectsにspecificなその他のinternal slotsを持ちません。

23.2.7.1 TypedArray.prototype.BYTES_PER_ELEMENT

TypedArray.prototype.BYTES_PER_ELEMENTのvalueは、TypedArrayについてTable 71でspecifiedされるElement Size valueです。

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

23.2.7.2 TypedArray.prototype.constructor

given TypedArray constructorのprototypeの"constructor" propertyのinitial valueはconstructor自体です。

23.2.8 Properties of TypedArray Instances

TypedArray instancesはTypedArraysです。各TypedArray instanceは、corresponding TypedArray prototype objectからpropertiesをinheritします。各TypedArray instanceは、次のinternal slotsを持ちます:[[ViewedArrayBuffer]][[TypedArrayName]][[ContentType]][[ByteLength]][[ByteOffset]]、および[[ArrayLength]]

23.3 Uint8Arrayオブジェクト

Uint8Arrayは、上でdescribedされたTypedArrayのparticular kindです。加えて、Uint8Array constructor23.3.1)およびUint8Array prototype object(23.3.2)にはadditional methodsがあります。

23.3.1 Uint8Array Constructorの追加プロパティ

23.3.1.1 Uint8Array.fromBase64 ( string [ , options ] )

  1. stringがStringでないなら、TypeError例外をthrowする。
  2. optsを ? GetOptionsObject(options) とする。
  3. alphabetを ? Get(opts, "alphabet") とする。
  4. alphabetundefinedなら、alphabet"base64"に設定する。
  5. alphabet"base64"でも"base64url"でもないなら、TypeError例外をthrowする。
  6. lastChunkHandlingを ? Get(opts, "lastChunkHandling") とする。
  7. lastChunkHandlingundefinedなら、lastChunkHandling"loose"に設定する。
  8. lastChunkHandling"loose""strict"、または"stop-before-partial"のいずれでもないなら、TypeError例外をthrowする。
  9. resultFromBase64(string, alphabet, lastChunkHandling)とする。
  10. result.[[Error]]noneでないなら、
    1. result.[[Error]]をthrowする。
  11. resultLengthresult.[[Bytes]]内のelementsの数とする。
  12. taを ? AllocateTypedArray("Uint8Array", %Uint8Array%, "%Uint8Array.prototype%", resultLength) とする。
  13. Assert: ta.[[ViewedArrayBuffer]].[[ArrayBufferByteLength]]result.[[Bytes]]内のelementsの数である。
  14. ta.[[ViewedArrayBuffer]].[[ArrayBufferData]]の各indexのvalueを、result.[[Bytes]]のcorresponding indexのvalueに設定する。
  15. taを返す。

23.3.1.2 Uint8Array.fromHex ( string )

  1. stringがStringでないなら、TypeError例外をthrowする。
  2. resultFromHex(string)とする。
  3. result.[[Error]]noneでないなら、
    1. result.[[Error]]をthrowする。
  4. resultLengthresult.[[Bytes]]内のelementsの数とする。
  5. taを ? AllocateTypedArray("Uint8Array", %Uint8Array%, "%Uint8Array.prototype%", resultLength) とする。
  6. Assert: ta.[[ViewedArrayBuffer]].[[ArrayBufferByteLength]]result.[[Bytes]]内のelementsの数である。
  7. ta.[[ViewedArrayBuffer]].[[ArrayBufferData]]の各indexのvalueを、result.[[Bytes]]のcorresponding indexのvalueに設定する。
  8. taを返す。

23.3.2 Uint8Array Prototype Objectの追加プロパティ

23.3.2.1 Uint8Array.prototype.setFromBase64 ( string [ , options ] )

  1. intothis valueとする。
  2. ValidateUint8Array(into)を実行する。
  3. stringがStringでないなら、TypeError例外をthrowする。
  4. optsを ? GetOptionsObject(options) とする。
  5. alphabetを ? Get(opts, "alphabet") とする。
  6. alphabetundefinedなら、alphabet"base64"に設定する。
  7. alphabet"base64"でも"base64url"でもないなら、TypeError例外をthrowする。
  8. lastChunkHandlingを ? Get(opts, "lastChunkHandling") とする。
  9. lastChunkHandlingundefinedなら、lastChunkHandling"loose"に設定する。
  10. lastChunkHandling"loose""strict"、または"stop-before-partial"のいずれでもないなら、TypeError例外をthrowする。
  11. taRecordMakeTypedArrayWithBufferWitnessRecord(into, seq-cst)とする。
  12. IsTypedArrayOutOfBounds(taRecord)がtrueなら、TypeError例外をthrowする。
  13. byteLengthTypedArrayLength(taRecord)とする。
  14. resultFromBase64(string, alphabet, lastChunkHandling, byteLength)とする。
  15. bytesresult.[[Bytes]]とする。
  16. writtenbytes内のelementsの数とする。
  17. NOTE: FromBase64はuser codeをinvokeしないため、intoをbackingするArrayBufferはdetachedまたはshrunkされていることはない。
  18. Assert: writtenbyteLength
  19. SetUint8ArrayBytes(into, bytes)を実行する。
  20. result.[[Error]]noneでないなら、
    1. result.[[Error]]をthrowする。
  21. resultObjOrdinaryObjectCreate(%Object.prototype%)とする。
  22. CreateDataPropertyOrThrow(resultObj, "read", 𝔽(result.[[Read]]))を実行する。
  23. CreateDataPropertyOrThrow(resultObj, "written", 𝔽(written))を実行する。
  24. resultObjを返す。

23.3.2.2 Uint8Array.prototype.setFromHex ( string )

  1. intothis valueとする。
  2. ValidateUint8Array(into)を実行する。
  3. stringがStringでないなら、TypeError例外をthrowする。
  4. taRecordMakeTypedArrayWithBufferWitnessRecord(into, seq-cst)とする。
  5. IsTypedArrayOutOfBounds(taRecord)がtrueなら、TypeError例外をthrowする。
  6. byteLengthTypedArrayLength(taRecord)とする。
  7. resultFromHex(string, byteLength)とする。
  8. bytesresult.[[Bytes]]とする。
  9. writtenbytes内のelementsの数とする。
  10. NOTE: FromHexはuser codeをinvokeしないため、intoをbackingするArrayBufferはdetachedまたはshrunkされていることはない。
  11. Assert: writtenbyteLength
  12. SetUint8ArrayBytes(into, bytes)を実行する。
  13. result.[[Error]]noneでないなら、
    1. result.[[Error]]をthrowする。
  14. resultObjOrdinaryObjectCreate(%Object.prototype%)とする。
  15. CreateDataPropertyOrThrow(resultObj, "read", 𝔽(result.[[Read]]))を実行する。
  16. CreateDataPropertyOrThrow(resultObj, "written", 𝔽(written))を実行する。
  17. resultObjを返す。

23.3.2.3 Uint8Array.prototype.toBase64 ( [ options ] )

  1. objthis valueとする。
  2. ValidateUint8Array(obj)を実行する。
  3. optsを ? GetOptionsObject(options) とする。
  4. alphabetを ? Get(opts, "alphabet") とする。
  5. alphabetundefinedなら、alphabet"base64"に設定する。
  6. alphabet"base64"でも"base64url"でもないなら、TypeError例外をthrowする。
  7. omitPaddingToBoolean(? Get(opts, "omitPadding"))とする。
  8. toEncodeを ? GetUint8ArrayBytes(obj) とする。
  9. alphabet"base64"なら、
    1. outAsciiを、toEncodeRFC 4648のsection 4でspecifiedされるbase64 encodingに従ってencodingした結果のcode pointsのsequenceとする。Paddingは、omitPaddingfalseである場合に限りincludedされる。
  10. そうでなければ、
    1. Assert: alphabet"base64url"である。
    2. outAsciiを、toEncodeRFC 4648のsection 5でspecifiedされるbase64url encodingに従ってencodingした結果のcode pointsのsequenceとする。Paddingは、omitPaddingfalseである場合に限りincludedされる。
  11. CodePointsToString(outAscii)を返す。

23.3.2.4 Uint8Array.prototype.toHex ( )

  1. objthis valueとする。
  2. ValidateUint8Array(obj)を実行する。
  3. toEncodeを ? GetUint8ArrayBytes(obj) とする。
  4. outをempty Stringとする。
  5. toEncodeの各byte byteについて、以下を行う
    1. hexNumber::toString(𝔽(byte), 16)とする。
    2. hexStringPad(hex, 2, "0", start)に設定する。
    3. outouthexstring-concatenationに設定する。
  6. outを返す。

23.3.3 Uint8Arrayオブジェクトの抽象操作

23.3.3.1 ValidateUint8Array ( ta )

The abstract operation ValidateUint8Array takes argument ta (an ECMAScript language value) and returns either a normal completion containing unused or a throw completion. It performs the following steps when called:

  1. RequireInternalSlot(ta, [[TypedArrayName]])を実行する。
  2. ta.[[TypedArrayName]]"Uint8Array"でないなら、TypeError例外をthrowする。
  3. unusedを返す。

23.3.3.2 GetUint8ArrayBytes ( ta )

The abstract operation GetUint8ArrayBytes takes argument ta (a Uint8Array) and returns either a normal completion containing a List of byte values or a throw completion. It performs the following steps when called:

  1. bufferta.[[ViewedArrayBuffer]]とする。
  2. taRecordMakeTypedArrayWithBufferWitnessRecord(ta, seq-cst)とする。
  3. IsTypedArrayOutOfBounds(taRecord)がtrueなら、TypeError例外をthrowする。
  4. lengthTypedArrayLength(taRecord)とする。
  5. byteOffsetta.[[ByteOffset]]とする。
  6. bytesを新しい空のListとする。
  7. indexを0とする。
  8. index < lengthの間、繰り返す
    1. byteIndexbyteOffset + indexとする。
    2. byte(GetValueFromBuffer(buffer, byteIndex, uint8, true, unordered))とする。
    3. bytebytesへappendする。
    4. indexindex + 1に設定する。
  9. bytesを返す。

23.3.3.3 SetUint8ArrayBytes ( into, bytes )

The abstract operation SetUint8ArrayBytes takes arguments into (a Uint8Array) and bytes (a List of byte values) and returns unused. It performs the following steps when called:

  1. offsetinto.[[ByteOffset]]とする。
  2. lengthbytes内のelementsの数とする。
  3. indexを0とする。
  4. index < lengthの間、繰り返す
    1. bytebytes[index]とする。
    2. byteIndexInBufferindex + offsetとする。
    3. SetValueInBuffer(into.[[ViewedArrayBuffer]], byteIndexInBuffer, uint8, 𝔽(byte), true, unordered)を実行する。
    4. indexindex + 1に設定する。
  5. unusedを返す。

23.3.3.4 SkipAsciiWhitespace ( string, index )

The abstract operation SkipAsciiWhitespace takes arguments string (a String) and index (a non-negative integer) and returns a non-negative integer. It performs the following steps when called:

  1. lengthstringのlengthとする。
  2. index < lengthの間、繰り返す
    1. charstring内のindex indexにあるcode unitとする。
    2. charが0x0009 (TAB)、0x000A (LF)、0x000C (FF)、0x000D (CR)、または0x0020 (SPACE)のいずれでもないなら、
      1. indexを返す。
    3. indexindex + 1に設定する。
  3. indexを返す。

23.3.3.5 DecodeFinalBase64Chunk ( chunk, throwOnExtraBits )

The abstract operation DecodeFinalBase64Chunk takes arguments chunk (a String of length 2 or 3) and throwOnExtraBits (a Boolean) and returns either a normal completion containing a List of byte values, or a throw completion. It performs the following steps when called:

  1. chunkLengthchunkのlengthとする。
  2. chunkLength = 2なら、
    1. chunkchunk"AA"string-concatenationに設定する。
  3. そうでなければ、
    1. Assert: chunkLengthは3である。
    2. chunkchunk"A"string-concatenationに設定する。
  4. bytesDecodeFullLengthBase64Chunk(chunk)とする。
  5. chunkLength = 2なら、
    1. throwOnExtraBitstrueであり、かつbytes[1] ≠ 0なら、SyntaxError例外をthrowする。
    2. « bytes[0] »を返す。
  6. throwOnExtraBitstrueであり、かつbytes[2] ≠ 0なら、SyntaxError例外をthrowする。
  7. « bytes[0], bytes[1] »を返す。

23.3.3.6 DecodeFullLengthBase64Chunk ( chunk )

The abstract operation DecodeFullLengthBase64Chunk takes argument chunk (a String of length 4) and returns a List of byte values of length 3.

standard base64 alphabet"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"、すなわち、Unicode Basic Latin block内のすべてのletterおよびnumberにcorrespondingするcode unitsと、"+"および"/"からなるStringです。

  1. byteSequenceを、chunkをbase64としてdecodingした結果のunique sequence of 3 bytesとする(すなわち、byteSequenceRFC 4648のsection 4でspecifiedされるbase64 encodingをapplyingするとchunkをproduceするようなsequence)。
  2. elementsがbyteSequenceのelementsであり、orderを保ったListを返す。

23.3.3.7 FromBase64 ( string, alphabet, lastChunkHandling [ , maxLength ] )

The abstract operation FromBase64 takes arguments string (a String), alphabet ("base64" or "base64url"), and lastChunkHandling ("loose", "strict", or "stop-before-partial") and optional argument maxLength (a non-negative integer) and returns a Record with fields [[Read]] (an integer), [[Bytes]] (a List of byte values), and [[Error]] (a SyntaxError object or none). It performs the following steps when called:

  1. maxLengthがpresentでないなら、
    1. maxLengthを253 - 1に設定する。
    2. NOTE: inputはStringであるため、Stringsのlengthは253 - 1 charactersにlimitedされ、outputはinputが持つcharactersより多くのbytesを必要としないので、このlimitに達することは決してない。しかし、maxLengthfinite valueを使用することはeditorially convenientである。
  2. NOTE: 下のalgorithmにおけるvalidationおよびdecodingのorderはobservableではない。Implementationsは、最もefficientなorderでそれらをperformすることがencouragedされ、possibly validationとdecodingをinterleavingしてもよい。
  3. maxLength = 0なら、
    1. Record { [[Read]]: 0, [[Bytes]]: « », [[Error]]: none }を返す。
  4. readを0とする。
  5. bytesを新しい空のListとする。
  6. chunkをempty Stringとする。
  7. chunkLengthを0とする。
  8. indexを0とする。
  9. lengthstringのlengthとする。
  10. 繰り返す、
    1. Assert: bytes内のelementsの数は3でevenly divisibleである。
    2. indexSkipAsciiWhitespace(string, index)に設定する。
    3. index = lengthなら、
      1. chunkLength > 0なら、
        1. lastChunkHandling"stop-before-partial"なら、
          1. Record { [[Read]]: read, [[Bytes]]: bytes, [[Error]]: none }を返す。
        2. lastChunkHandling"strict"なら、
          1. errorをnewly created SyntaxError objectとする。
          2. Record { [[Read]]: read, [[Bytes]]: bytes, [[Error]]: error }を返す。
        3. Assert: lastChunkHandling"loose"である。
        4. chunkLength = 1なら、
          1. errorをnewly created SyntaxError objectとする。
          2. Record { [[Read]]: read, [[Bytes]]: bytes, [[Error]]: error }を返す。
        5. bytesを、bytesと ! DecodeFinalBase64Chunk(chunk, false) のlist-concatenationに設定する。
      2. Record { [[Read]]: length, [[Bytes]]: bytes, [[Error]]: none }を返す。
    4. charstringindexからindex + 1までのsubstringとする。
    5. indexindex + 1に設定する。
    6. char"="なら、
      1. chunkLength < 2なら、
        1. errorをnewly created SyntaxError objectとする。
        2. Record { [[Read]]: read, [[Bytes]]: bytes, [[Error]]: error }を返す。
      2. indexSkipAsciiWhitespace(string, index)に設定する。
      3. chunkLength = 2なら、
        1. index = lengthなら、
          1. lastChunkHandling"stop-before-partial"なら、
            1. Record { [[Read]]: read, [[Bytes]]: bytes, [[Error]]: none }を返す。
          2. errorをnewly created SyntaxError objectとする。
          3. Record { [[Read]]: read, [[Bytes]]: bytes, [[Error]]: error }を返す。
        2. charstringindexからindex + 1までのsubstringに設定する。
        3. char"="なら、
          1. indexSkipAsciiWhitespace(string, index + 1)に設定する。
      4. index < lengthなら、
        1. errorをnewly created SyntaxError objectとする。
        2. Record { [[Read]]: read, [[Bytes]]: bytes, [[Error]]: error }を返す。
      5. lastChunkHandling"strict"なら、throwOnExtraBitstrueとする;そうでなければ、throwOnExtraBitsfalseとする。
      6. decodeResultCompletion(DecodeFinalBase64Chunk(chunk, throwOnExtraBits))とする。
      7. decodeResultabrupt completionなら、
        1. errordecodeResult.[[Value]]とする。
        2. Record { [[Read]]: read, [[Bytes]]: bytes, [[Error]]: error }を返す。
      8. bytesを、bytesと ! decodeResultlist-concatenationに設定する。
      9. Record { [[Read]]: length, [[Bytes]]: bytes, [[Error]]: none }を返す。
    7. alphabet"base64url"なら、
      1. char"+"または"/"のいずれかなら、
        1. errorをnewly created SyntaxError objectとする。
        2. Record { [[Read]]: read, [[Bytes]]: bytes, [[Error]]: error }を返す。
      2. そうでなく、char"-"なら、
        1. char"+"に設定する。
      3. そうでなく、char"_"なら、
        1. char"/"に設定する。
    8. charのsole code unitがstandard base64 alphabetのelementでないなら、
      1. errorをnewly created SyntaxError objectとする。
      2. Record { [[Read]]: read, [[Bytes]]: bytes, [[Error]]: error }を返す。
    9. remainingmaxLength - bytes内のelementsの数とする。
    10. remaining = 1かつchunkLength = 2の場合、またはremaining = 2かつchunkLength = 3の場合、
      1. Record { [[Read]]: read, [[Bytes]]: bytes, [[Error]]: none }を返す。
    11. chunkchunkcharstring-concatenationに設定する。
    12. chunkLengthchunkのlengthに設定する。
    13. chunkLength = 4なら、
      1. bytesを、bytesDecodeFullLengthBase64Chunk(chunk)のlist-concatenationに設定する。
      2. chunkをempty Stringに設定する。
      3. chunkLengthを0に設定する。
      4. readindexに設定する。
      5. bytes内のelementsの数 = maxLengthなら、
        1. Record { [[Read]]: read, [[Bytes]]: bytes, [[Error]]: none }を返す。

23.3.3.8 FromHex ( string [ , maxLength ] )

The abstract operation FromHex takes argument string (a String) and optional argument maxLength (a non-negative integer) and returns a Record with fields [[Read]] (an integer), [[Bytes]] (a List of byte values), and [[Error]] (a SyntaxError object or none). It performs the following steps when called:

  1. maxLengthがpresentでないなら、maxLengthを253 - 1に設定する。
  2. lengthstringのlengthとする。
  3. bytesを新しい空のListとする。
  4. readを0とする。
  5. length modulo 2 ≠ 0なら、
    1. errorをnewly created SyntaxError objectとする。
    2. Record { [[Read]]: read, [[Bytes]]: bytes, [[Error]]: error }を返す。
  6. read < lengthであり、かつbytes内のelementsの数 < maxLengthである間、繰り返す
    1. hexitsstringreadからread + 2までのsubstringとする。
    2. hexits"0123456789abcdefABCDEF"内にないcode unitsを含むなら、
      1. errorをnewly created SyntaxError objectとする。
      2. Record { [[Read]]: read, [[Bytes]]: bytes, [[Error]]: error }を返す。
    3. readread + 2に設定する。
    4. byteを、values 10 through 15のdigitsとしてletters A through Fおよびa through fを使用するbase-16 notationでhexitsによりrepresentedされるinteger valueとする。
    5. bytebytesへappendする。
  7. Record { [[Read]]: read, [[Bytes]]: bytes, [[Error]]: none }を返す。

24 Keyed Collections

24.1 Mapオブジェクト

Mapはkey/value pairのcollectionであり、keysとvaluesはいずれも任意のECMAScript language valueであってよい。distinctなkey valueは、Mapのcollection内の1つのkey/value pairにだけ出現してよい。distinctなkey valuesはSameValueZero比較algorithmのsemanticsを用いて識別される。

Mapは、平均的にcollection内のelements数に対してsublinearなaccess timeを提供するhash tableまたはその他のmechanismsを用いて実装されなければならない。この仕様で用いられるdata structureは、Mapのrequired observable semanticsをdescribeすることだけを意図している。viable implementation modelであることは意図されていない。

24.1.1 Map Constructor

Map constructorは:

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

24.1.1.1 Map ( [ iterable ] )

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

  1. NewTargetがundefinedなら、TypeError例外をthrowする。
  2. mapを ? OrdinaryCreateFromConstructor(NewTarget, "%Map.prototype%", « [[MapData]] ») とする。
  3. map.[[MapData]]を新しい空のListに設定する。
  4. iterableundefinedまたはnullのどちらかなら、mapを返す。
  5. adderを ? Get(map, "set") とする。
  6. IsCallable(adder)がfalseなら、TypeError例外をthrowする。
  7. AddEntriesFromIterable(map, iterable, adder)を返す。
Note

parameter iterableがpresentである場合、それは%Symbol.iterator% methodを実装するobjectであることがexpectedされ、そのmethodは、first elementがMap keyとして使用されるvalueであり、second elementがそのkeyにassociateされるvalueであるtwo element array-like objectをproduceするiterator objectを返す。

24.1.1.2 AddEntriesFromIterable ( target, iterable, adder )

The abstract operation AddEntriesFromIterable takes arguments target (an Object), iterable (an ECMAScript language value, but not undefined or null), and adder (a function object) and returns either a normal completion containing an Object or a throw completion. adderは、targetをreceiverとしてinvokeされる。 It performs the following steps when called:

  1. iteratorRecordを ? GetIterator(iterable, sync) とする。
  2. 繰り返す、
    1. nextを ? IteratorStepValue(iteratorRecord) とする。
    2. nextdoneなら、targetを返す。
    3. nextがObjectでないなら、
      1. errorThrowCompletion(newly created TypeError object)とする。
      2. IteratorClose(iteratorRecord, error)を返す。
    4. keyCompletion(Get(next, "0"))とする。
    5. IfAbruptCloseIterator(key, iteratorRecord)。
    6. valueCompletion(Get(next, "1"))とする。
    7. IfAbruptCloseIterator(value, iteratorRecord)。
    8. statusCompletion(Call(adder, target, « key, value »))とする。
    9. IfAbruptCloseIterator(status, iteratorRecord)。
Note

parameter iterableは、%Symbol.iterator% methodを実装するobjectであることがexpectedされ、そのmethodは、first elementがMap keyとして使用されるvalueであり、second elementがそのkeyにassociateされるvalueであるtwo element array-like objectをproduceするiterator objectを返す。

24.1.2 Map Constructorのプロパティ

Map constructorは:

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

24.1.2.1 Map.groupBy ( items, callback )

Note

callbackはtwo argumentsをacceptするfunctionであるべきである。groupByitems内の各elementについてascending orderでcallbackを1回callし、新しいMapをconstructする。callbackによりreturnedされた各valueはMap内のkeyとして使用される。そのような各keyについて、result Mapはkeyがそのkeyであり、valueがcallbackがそのkeyを返したすべてのelementsを含むarrayであるentryを持つ。

callbackはtwo arguments、すなわちelementのvalueとelementのindexでcallされる。

groupByのreturn valueはMapである。

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

  1. groupsを ? GroupBy(items, callback, collection) とする。
  2. mapを ! Construct(%Map%) とする。
  3. groupsの各Record { [[Key]], [[Elements]] } groupについて、以下を行う
    1. elementsCreateArrayFromList(group.[[Elements]])とする。
    2. entryRecord { [[Key]]: group.[[Key]], [[Value]]: elements }とする。
    3. entrymap.[[MapData]]へappendする。
  4. mapを返す。

24.1.2.2 Map.prototype

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

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

24.1.2.3 get Map [ %Symbol.species% ]

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

  1. this valueを返す。

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

Note

derived collection objectsをcreateするmethodsは、derived objectsをcreateするために使用するconstructorをdetermineするため、%Symbol.species%をcallするべきである。Subclass constructor%Symbol.species%をover-rideしてdefault constructor assignmentを変更できる。

24.1.3 Map Prototype Objectのプロパティ

Map prototype objectは:

  • %Map.prototype%である。
  • valueが%Object.prototype%である[[Prototype]] internal slotを持つ。
  • ordinary objectである。
  • [[MapData]] internal slotを持たない。

24.1.3.1 Map.prototype.clear ( )

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

  1. mapthis valueとする。
  2. RequireInternalSlot(map, [[MapData]])を実行する。
  3. map.[[MapData]]の各Record { [[Key]], [[Value]] } entryについて、以下を行う
    1. entry.[[Key]]emptyに設定する。
    2. entry.[[Value]]emptyに設定する。
  4. undefinedを返す。
Note

そのListのiterationの途中でsuspendedされているexisting Map Iterator objectsが存在するかもしれないため、existing [[MapData]] Listはpreservedされる。

24.1.3.2 Map.prototype.constructor

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

24.1.3.3 Map.prototype.delete ( key )

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

  1. mapthis valueとする。
  2. RequireInternalSlot(map, [[MapData]])を実行する。
  3. keyCanonicalizeKeyedCollectionKey(key)に設定する。
  4. map.[[MapData]]の各Record { [[Key]], [[Value]] } entryについて、以下を行う
    1. entry.[[Key]]emptyでなく、SameValue(entry.[[Key]], key)がtrueなら、
      1. entry.[[Key]]emptyに設定する。
      2. entry.[[Value]]emptyに設定する。
      3. trueを返す。
  5. falseを返す。
Note

value emptyは、entryがdeletedされたことをindicateするためのspecification deviceとして使用される。実際のimplementationsは、entryをinternal data structuresからphysically removingするなど、他のactionsを取ってもよい。

24.1.3.4 Map.prototype.entries ( )

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

  1. mapthis valueとする。
  2. CreateMapIterator(map, key+value)を返す。

24.1.3.5 Map.prototype.forEach ( callback [ , thisArg ] )

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

  1. mapthis valueとする。
  2. RequireInternalSlot(map, [[MapData]])を実行する。
  3. IsCallable(callback)がfalseなら、TypeError例外をthrowする。
  4. entriesmap.[[MapData]]とする。
  5. entriesCountentries内のelementsの数とする。
  6. indexを0とする。
  7. index < entriesCountの間、繰り返す
    1. entryentries[index]とする。
    2. indexindex + 1に設定する。
    3. entry.[[Key]]emptyでないなら、
      1. Call(callback, thisArg, « entry.[[Value]], entry.[[Key]], map »)を実行する。
      2. NOTE: entries内のelementsの数はcallbackのexecution中に増加しているかもしれない。
      3. entriesCountentries内のelementsの数に設定する。
  8. undefinedを返す。
Note

callbackはthree argumentsをacceptするfunctionであるべきである。forEachはMap内にpresentな各key/value pairについて、key insertion orderでcallbackを1回callする。callbackは、実際に存在するMapのkeysについてのみcallされ、Mapからdeletedされたkeysについてはcallされない。

thisArg parameterがprovidedされた場合、それはcallbackの各invocationにおけるthis valueとして使用される。providedされない場合、代わりにundefinedが使用される。

callbackはthree arguments、すなわちitemのvalue、itemのkey、およびtraversedされるMapでcallされる。

forEachは、それが呼び出されたobjectをdirectly mutateしないが、そのobjectはcallbackのcallsによってmutatedされるかもしれない。mapの[[MapData]]の各entryは1回だけvisitedされる。forEachへのcallがbeginsした後にaddedされたnew keysはvisitedされる。keyがvisitedされた後にdeletedされ、その後forEach callがcompletesする前にre-addedされた場合、そのkeyはrevisitedされる。forEachへのcallがbeginsした後、visitedされる前にdeletedされたkeysは、forEach callがcompletesする前にkeyが再びaddedされない限り、visitedされない。

24.1.3.6 Map.prototype.get ( key )

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

  1. mapthis valueとする。
  2. RequireInternalSlot(map, [[MapData]])を実行する。
  3. keyCanonicalizeKeyedCollectionKey(key)に設定する。
  4. map.[[MapData]]の各Record { [[Key]], [[Value]] } entryについて、以下を行う
    1. entry.[[Key]]emptyでなく、SameValue(entry.[[Key]], key)がtrueなら、entry.[[Value]]を返す。
  5. undefinedを返す。

24.1.3.7 Map.prototype.getOrInsert ( key, value )

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

  1. mapthis valueとする。
  2. RequireInternalSlot(map, [[MapData]])を実行する。
  3. keyCanonicalizeKeyedCollectionKey(key)に設定する。
  4. map.[[MapData]]の各Record { [[Key]], [[Value]] } entryについて、以下を行う
    1. entry.[[Key]]emptyでなく、SameValue(entry.[[Key]], key)がtrueなら、entry.[[Value]]を返す。
  5. entryRecord { [[Key]]: key, [[Value]]: value }とする。
  6. entrymap.[[MapData]]へappendする。
  7. valueを返す。

24.1.3.8 Map.prototype.getOrInsertComputed ( key, callback )

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

  1. mapthis valueとする。
  2. RequireInternalSlot(map, [[MapData]])を実行する。
  3. IsCallable(callback)がfalseなら、TypeError例外をthrowする。
  4. keyCanonicalizeKeyedCollectionKey(key)に設定する。
  5. map.[[MapData]]の各Record { [[Key]], [[Value]] } entryについて、以下を行う
    1. entry.[[Key]]emptyでなく、SameValue(entry.[[Key]], key)がtrueなら、entry.[[Value]]を返す。
  6. valueを ? Call(callback, undefined, « key ») とする。
  7. NOTE: Mapはcallbackのexecution中にmodifiedされているかもしれない。
  8. map.[[MapData]]の各Record { [[Key]], [[Value]] } entryについて、以下を行う
    1. entry.[[Key]]emptyでなく、SameValue(entry.[[Key]], key)がtrueなら、
      1. entry.[[Value]]valueに設定する。
      2. valueを返す。
  9. entryRecord { [[Key]]: key, [[Value]]: value }とする。
  10. entrymap.[[MapData]]へappendする。
  11. valueを返す。

24.1.3.9 Map.prototype.has ( key )

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

  1. mapthis valueとする。
  2. RequireInternalSlot(map, [[MapData]])を実行する。
  3. keyCanonicalizeKeyedCollectionKey(key)に設定する。
  4. map.[[MapData]]の各Record { [[Key]], [[Value]] } entryについて、以下を行う
    1. entry.[[Key]]emptyでなく、SameValue(entry.[[Key]], key)がtrueなら、trueを返す。
  5. falseを返す。

24.1.3.10 Map.prototype.keys ( )

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

  1. mapthis valueとする。
  2. CreateMapIterator(map, key)を返す。

24.1.3.11 Map.prototype.set ( key, value )

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

  1. mapthis valueとする。
  2. RequireInternalSlot(map, [[MapData]])を実行する。
  3. keyCanonicalizeKeyedCollectionKey(key)に設定する。
  4. map.[[MapData]]の各Record { [[Key]], [[Value]] } entryについて、以下を行う
    1. entry.[[Key]]emptyでなく、SameValue(entry.[[Key]], key)がtrueなら、
      1. entry.[[Value]]valueに設定する。
      2. mapを返す。
  5. entryRecord { [[Key]]: key, [[Value]]: value }とする。
  6. entrymap.[[MapData]]へappendする。
  7. mapを返す。

24.1.3.12 get Map.prototype.size

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

  1. mapthis valueとする。
  2. RequireInternalSlot(map, [[MapData]])を実行する。
  3. countを0とする。
  4. map.[[MapData]]の各Record { [[Key]], [[Value]] } entryについて、以下を行う
    1. entry.[[Key]]emptyでないなら、countcount + 1に設定する。
  5. 𝔽(count)を返す。

24.1.3.13 Map.prototype.values ( )

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

  1. mapthis valueとする。
  2. CreateMapIterator(map, value)を返す。

24.1.3.14 Map.prototype [ %Symbol.iterator% ] ( )

%Symbol.iterator% propertyのinitial valueは、24.1.3.4でdefinedされる%Map.prototype.entries%である。

24.1.3.15 Map.prototype [ %Symbol.toStringTag% ]

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

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

24.1.4 Map Instancesのプロパティ

Map instancesはMap prototype objectからpropertiesをinheritするordinary objectsである。Map instancesは[[MapData]] internal slotも持つ。

24.1.5 Map Iteratorオブジェクト

Map Iteratorは、あるspecific Map instance objectに対するspecific iterationをrepresentするobjectである。Map Iterator objectsにはnamed constructorは存在しない。代わりに、Map Iterator objectsはMap instance objectsのcertain methodsをcallingすることでcreatedされる。

24.1.5.1 CreateMapIterator ( map, kind )

The abstract operation CreateMapIterator takes arguments map (an ECMAScript language value) and kind (key+value, key, or value) and returns either a normal completion containing a Generator or a throw completion. Map methodsがreturnするそのようなiteratorsiterator objectsをcreateするために使用される。 It performs the following steps when called:

  1. RequireInternalSlot(map, [[MapData]])を実行する。
  2. closureを、parametersを持たず、mapおよびkindをcapturesし、呼び出されたときに次のstepsを実行する新しいAbstract Closureとする:
    1. entriesmap.[[MapData]]とする。
    2. indexを0とする。
    3. entriesCountentries内のelementsの数とする。
    4. index < entriesCountの間、繰り返す
      1. entryentries[index]とする。
      2. indexindex + 1に設定する。
      3. entry.[[Key]]emptyでないなら、
        1. kindkeyなら、
          1. resultentry.[[Key]]とする。
        2. そうでなく、kindvalueなら、
          1. resultentry.[[Value]]とする。
        3. そうでなければ、
          1. Assert: kindkey+valueである。
          2. resultCreateArrayFromListentry.[[Key]], entry.[[Value]] »)とする。
        4. GeneratorYield(CreateIteratorResultObject(result, false))を実行する。
        5. NOTE: このabstract operationのexecutionがGeneratorYieldによりpausedされている間に、entries内のelementsの数が増加しているかもしれない。
        6. entriesCountentries内のelementsの数に設定する。
    5. NormalCompletion(unused)を返す。
  3. CreateIteratorFromClosure(closure, "%MapIteratorPrototype%", %MapIteratorPrototype%)を返す。

24.1.5.2 %MapIteratorPrototype% Object

%MapIteratorPrototype% objectは:

24.1.5.2.1 %MapIteratorPrototype%.next ( )

  1. GeneratorResume(this value, empty, "%MapIteratorPrototype%")を返す。

24.1.5.2.2 %MapIteratorPrototype% [ %Symbol.toStringTag% ]

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

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

24.2 Setオブジェクト

Set objectsECMAScript language valuesのcollectionsである。Setは各distinct valueを多くとも1回だけcontainできる。distinct valuesはSameValueZero comparison algorithmのsemanticsを用いて識別される。

Set objectsは、平均的にcollection内のelements数に対してsublinearなaccess timeを提供するhash tableまたはその他のmechanismsを用いて実装されなければならない。この仕様で用いられるdata structureは、Set objectsのrequired observable semanticsをdescribeすることだけを意図している。viable implementation modelであることは意図されていない。

24.2.1 Setオブジェクトの抽象操作

24.2.1.1 Set Records

Set Recordは、Setまたはsimilar objectのinterfaceをencapsulateするために使用されるRecord valueである。

Set RecordsはTable 72にlistedされるfieldsを持つ。

Table 72: Set Record Fields
Field Name Value Meaning
[[SetObject]] Object Setまたはsimilar object。
[[Size]] non-negative integerまたは+∞ objectのreported size。
[[Has]] function object objectのhas method。
[[Keys]] function object objectのkeys method。

24.2.1.2 GetSetRecord ( obj )

The abstract operation GetSetRecord takes argument obj (an ECMAScript language value) and returns either a normal completion containing a Set Record or a throw completion. It performs the following steps when called:

  1. objがObjectでないなら、TypeError例外をthrowする。
  2. rawSizeを ? Get(obj, "size") とする。
  3. numberSizeを ? ToNumber(rawSize) とする。
  4. NOTE: rawSizeundefinedなら、numberSizeNaNになる。
  5. numberSizeNaNなら、TypeError例外をthrowする。
  6. intSizeを ! ToIntegerOrInfinity(numberSize) とする。
  7. intSize < 0なら、RangeError例外をthrowする。
  8. hasを ? Get(obj, "has") とする。
  9. IsCallable(has)がfalseなら、TypeError例外をthrowする。
  10. keysを ? Get(obj, "keys") とする。
  11. IsCallable(keys)がfalseなら、TypeError例外をthrowする。
  12. 新しいSet Record { [[SetObject]]: obj, [[Size]]: intSize, [[Has]]: has, [[Keys]]: keys }を返す。

24.2.1.3 SetDataHas ( setData, value )

The abstract operation SetDataHas takes arguments setData (a List of either ECMAScript language values or empty) and value (an ECMAScript language value) and returns a Boolean. It performs the following steps when called:

  1. SetDataIndex(setData, value)がnot-foundなら、falseを返す。
  2. trueを返す。

24.2.1.4 SetDataIndex ( setData, value )

The abstract operation SetDataIndex takes arguments setData (a List of either ECMAScript language values or empty) and value (an ECMAScript language value) and returns a non-negative integer or not-found. It performs the following steps when called:

  1. valueCanonicalizeKeyedCollectionKey(value)に設定する。
  2. sizesetData内のelementsの数とする。
  3. indexを0とする。
  4. index < sizeの間、繰り返す
    1. elementsetData[index]とする。
    2. elementemptyでなく、elementvalueであるなら、
      1. indexを返す。
    3. indexindex + 1に設定する。
  5. not-foundを返す。

24.2.1.5 SetDataSize ( setData )

The abstract operation SetDataSize takes argument setData (a List of either ECMAScript language values or empty) and returns a non-negative integer. It performs the following steps when called:

  1. countを0とする。
  2. setDataの各element elementについて、以下を行う
    1. elementemptyでないなら、countcount + 1に設定する。
  3. countを返す。

24.2.2 Set Constructor

Set constructorは:

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

24.2.2.1 Set ( [ iterable ] )

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

  1. NewTargetがundefinedなら、TypeError例外をthrowする。
  2. setを ? OrdinaryCreateFromConstructor(NewTarget, "%Set.prototype%", « [[SetData]] ») とする。
  3. set.[[SetData]]を新しい空のListに設定する。
  4. iterableundefinedまたはnullのどちらかなら、setを返す。
  5. adderを ? Get(set, "add") とする。
  6. IsCallable(adder)がfalseなら、TypeError例外をthrowする。
  7. iteratorRecordを ? GetIterator(iterable, sync) とする。
  8. 繰り返す、
    1. nextを ? IteratorStepValue(iteratorRecord) とする。
    2. nextdoneなら、setを返す。
    3. statusCompletion(Call(adder, set, « next »))とする。
    4. IfAbruptCloseIterator(status, iteratorRecord)。

24.2.3 Set Constructorのプロパティ

Set constructorは:

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

24.2.3.1 Set.prototype

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

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

24.2.3.2 get Set [ %Symbol.species% ]

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

  1. this valueを返す。

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

Note

derived collection objectsをcreateするmethodsは、derived objectsをcreateするために使用するconstructorをdetermineするため、%Symbol.species%をcallするべきである。Subclass constructor%Symbol.species%をover-rideしてdefault constructor assignmentを変更できる。

24.2.4 Set Prototype Objectのプロパティ

Set prototype objectは:

  • %Set.prototype%である。
  • valueが%Object.prototype%である[[Prototype]] internal slotを持つ。
  • ordinary objectである。
  • [[SetData]] internal slotを持たない。

24.2.4.1 Set.prototype.add ( value )

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

  1. setthis valueとする。
  2. RequireInternalSlot(set, [[SetData]])を実行する。
  3. valueCanonicalizeKeyedCollectionKey(value)に設定する。
  4. set.[[SetData]]の各element entryについて、以下を行う
    1. entryemptyでなく、SameValue(entry, value)がtrueなら、
      1. setを返す。
  5. valueset.[[SetData]]へappendする。
  6. setを返す。

24.2.4.2 Set.prototype.clear ( )

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

  1. setthis valueとする。
  2. RequireInternalSlot(set, [[SetData]])を実行する。
  3. set.[[SetData]]の各element entryについて、以下を行う
    1. valueがentryであるset.[[SetData]]のelementを、valueがemptyであるelementでreplaceする。
  4. undefinedを返す。
Note

そのListのiterationの途中でsuspendedされているexisting Set Iterator objectsが存在するかもしれないため、existing [[SetData]] Listはpreservedされる。

24.2.4.3 Set.prototype.constructor

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

24.2.4.4 Set.prototype.delete ( value )

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

  1. setthis valueとする。
  2. RequireInternalSlot(set, [[SetData]])を実行する。
  3. valueCanonicalizeKeyedCollectionKey(value)に設定する。
  4. set.[[SetData]]の各element entryについて、以下を行う
    1. entryemptyでなく、SameValue(entry, value)がtrueなら、
      1. valueがentryであるset.[[SetData]]のelementを、valueがemptyであるelementでreplaceする。
      2. trueを返す。
  5. falseを返す。
Note

value emptyは、entryがdeletedされたことをindicateするためのspecification deviceとして使用される。実際のimplementationsは、entryをinternal data structuresからphysically removingするなど、他のactionsを取ってもよい。

24.2.4.5 Set.prototype.difference ( other )

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

  1. setthis valueとする。
  2. RequireInternalSlot(set, [[SetData]])を実行する。
  3. otherRecordを ? GetSetRecord(other) とする。
  4. resultSetDataset.[[SetData]]のcopyとする。
  5. SetDataSize(set.[[SetData]]) ≤ otherRecord.[[Size]]なら、
    1. thisSizeset.[[SetData]]内のelementsの数とする。
    2. indexを0とする。
    3. index < thisSizeの間、繰り返す
      1. entryresultSetData[index]とする。
      2. entryemptyでないなら、
        1. inOtherToBoolean(? Call(otherRecord.[[Has]], otherRecord.[[SetObject]], « entry »))とする。
        2. inOthertrueなら、
          1. resultSetData[index]をemptyに設定する。
      3. indexindex + 1に設定する。
  6. そうでなければ、
    1. keysIteratorを ? GetIteratorFromMethod(otherRecord.[[SetObject]], otherRecord.[[Keys]]) とする。
    2. nextnot-startedとする。
    3. nextdoneでない間、繰り返す
      1. nextを ? IteratorStepValue(keysIterator) に設定する。
      2. nextdoneでないなら、
        1. nextCanonicalizeKeyedCollectionKey(next)に設定する。
        2. valueIndexSetDataIndex(resultSetData, next)とする。
        3. valueIndexnot-foundでないなら、
          1. resultSetData[valueIndex]をemptyに設定する。
  7. resultOrdinaryObjectCreate(%Set.prototype%, « [[SetData]] »)とする。
  8. result.[[SetData]]resultSetDataに設定する。
  9. resultを返す。

24.2.4.6 Set.prototype.entries ( )

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

  1. setthis valueとする。
  2. CreateSetIterator(set, key+value)を返す。
Note

iteration purposesにおいて、Setは各entryがkeyとvalueに同じvalueを持つMapにsimilarに見える。

24.2.4.7 Set.prototype.forEach ( callback [ , thisArg ] )

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

  1. setthis valueとする。
  2. RequireInternalSlot(set, [[SetData]])を実行する。
  3. IsCallable(callback)がfalseなら、TypeError例外をthrowする。
  4. entriesset.[[SetData]]とする。
  5. entriesCountentries内のelementsの数とする。
  6. indexを0とする。
  7. index < entriesCountの間、繰り返す
    1. entryentries[index]とする。
    2. indexindex + 1に設定する。
    3. entryemptyでないなら、
      1. Call(callback, thisArg, « entry, entry, set »)を実行する。
      2. NOTE: entries内のelementsの数はcallbackのexecution中に増加しているかもしれない。
      3. entriesCountentries内のelementsの数に設定する。
  8. undefinedを返す。
Note

callbackはthree argumentsをacceptするfunctionであるべきである。forEachSet object内にpresentな各valueについて、value insertion orderでcallbackを1回callする。callbackは、実際に存在するSetのvaluesについてのみcallされ、setからdeletedされたkeysについてはcallされない。

thisArg parameterがprovidedされた場合、それはcallbackの各invocationにおけるthis valueとして使用される。providedされない場合、代わりにundefinedが使用される。

callbackはthree argumentsでcallされる:first two argumentsはSet内にcontainedされるvalueである。両方のargumentsには同じvalueがpassedされる。traversedされるSet objectがthird argumentとしてpassedされる。

MapおよびArrayのforEach methodsで使用されるcall back functionsとconsistentにするため、callbackはthree argumentsでcallされる。Setでは、各item valueはkeyとvalueの両方であるとconsideredされる。

forEachは、それが呼び出されたobjectをdirectly mutateしないが、そのobjectはcallbackのcallsによってmutatedされるかもしれない。

各valueは通常1回だけvisitedされる。しかし、valueがvisitedされた後にdeletedされ、その後forEach callがcompletesする前にre-addedされた場合、そのvalueはrevisitedされる。forEachへのcallがbeginsした後、visitedされる前にdeletedされたvaluesは、forEach callがcompletesする前にvalueが再びaddedされない限り、visitedされない。forEachへのcallがbeginsした後にaddedされたnew valuesはvisitedされる。

24.2.4.8 Set.prototype.has ( value )

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

  1. setthis valueとする。
  2. RequireInternalSlot(set, [[SetData]])を実行する。
  3. valueCanonicalizeKeyedCollectionKey(value)に設定する。
  4. set.[[SetData]]の各element entryについて、以下を行う
    1. entryemptyでなく、SameValue(entry, value)がtrueなら、trueを返す。
  5. falseを返す。

24.2.4.9 Set.prototype.intersection ( other )

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

  1. setthis valueとする。
  2. RequireInternalSlot(set, [[SetData]])を実行する。
  3. otherRecordを ? GetSetRecord(other) とする。
  4. resultSetDataを新しい空のListとする。
  5. SetDataSize(set.[[SetData]]) ≤ otherRecord.[[Size]]なら、
    1. thisSizeset.[[SetData]]内のelementsの数とする。
    2. indexを0とする。
    3. index < thisSizeの間、繰り返す
      1. entryset.[[SetData]][index]とする。
      2. indexindex + 1に設定する。
      3. entryemptyでないなら、
        1. inOtherToBoolean(? Call(otherRecord.[[Has]], otherRecord.[[SetObject]], « entry »))とする。
        2. inOthertrueなら、
          1. NOTE: otherRecord.[[Has]]へのearlier callsがset.[[SetData]]のelementをremoveしてre-addすることがpossibleであり、それによりこのiteration中に同じelementがtwice visitedされる可能性がある。
          2. SetDataHas(resultSetData, entry)がfalseなら、
            1. entryresultSetDataへappendする。
        3. NOTE: set.[[SetData]]内のelementsの数はotherRecord.[[Has]]のexecution中に増加しているかもしれない。
        4. thisSizeset.[[SetData]]内のelementsの数に設定する。
  6. そうでなければ、
    1. keysIteratorを ? GetIteratorFromMethod(otherRecord.[[SetObject]], otherRecord.[[Keys]]) とする。
    2. nextnot-startedとする。
    3. nextdoneでない間、繰り返す
      1. nextを ? IteratorStepValue(keysIterator) に設定する。
      2. nextdoneでないなら、
        1. nextCanonicalizeKeyedCollectionKey(next)に設定する。
        2. inThisSetDataHas(set.[[SetData]], next)とする。
        3. inThistrueなら、
          1. NOTE: otherはarbitrary objectであるため、その"keys" iteratorが同じvalueを複数回produceすることがpossibleである。
          2. SetDataHas(resultSetData, next)がfalseなら、
            1. nextresultSetDataへappendする。
  7. resultOrdinaryObjectCreate(%Set.prototype%, « [[SetData]] »)とする。
  8. result.[[SetData]]resultSetDataに設定する。
  9. resultを返す。

24.2.4.10 Set.prototype.isDisjointFrom ( other )

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

  1. setthis valueとする。
  2. RequireInternalSlot(set, [[SetData]])を実行する。
  3. otherRecordを ? GetSetRecord(other) とする。
  4. SetDataSize(set.[[SetData]]) ≤ otherRecord.[[Size]]なら、
    1. thisSizeset.[[SetData]]内のelementsの数とする。
    2. indexを0とする。
    3. index < thisSizeの間、繰り返す
      1. entryset.[[SetData]][index]とする。
      2. indexindex + 1に設定する。
      3. entryemptyでないなら、
        1. inOtherToBoolean(? Call(otherRecord.[[Has]], otherRecord.[[SetObject]], « entry »))とする。
        2. inOthertrueなら、falseを返す。
        3. NOTE: set.[[SetData]]内のelementsの数はotherRecord.[[Has]]のexecution中に増加しているかもしれない。
        4. thisSizeset.[[SetData]]内のelementsの数に設定する。
  5. そうでなければ、
    1. keysIteratorを ? GetIteratorFromMethod(otherRecord.[[SetObject]], otherRecord.[[Keys]]) とする。
    2. nextnot-startedとする。
    3. nextdoneでない間、繰り返す
      1. nextを ? IteratorStepValue(keysIterator) に設定する。
      2. nextdoneでないなら、
        1. SetDataHas(set.[[SetData]], next)がtrueなら、
          1. IteratorClose(keysIterator, NormalCompletion(unused))を実行する。
          2. falseを返す。
  6. trueを返す。

24.2.4.11 Set.prototype.isSubsetOf ( other )

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

  1. setthis valueとする。
  2. RequireInternalSlot(set, [[SetData]])を実行する。
  3. otherRecordを ? GetSetRecord(other) とする。
  4. SetDataSize(set.[[SetData]]) > otherRecord.[[Size]]なら、falseを返す。
  5. thisSizeset.[[SetData]]内のelementsの数とする。
  6. indexを0とする。
  7. index < thisSizeの間、繰り返す
    1. entryset.[[SetData]][index]とする。
    2. indexindex + 1に設定する。
    3. entryemptyでないなら、
      1. inOtherToBoolean(? Call(otherRecord.[[Has]], otherRecord.[[SetObject]], « entry »))とする。
      2. inOtherfalseなら、falseを返す。
      3. NOTE: set.[[SetData]]内のelementsの数はotherRecord.[[Has]]のexecution中に増加しているかもしれない。
      4. thisSizeset.[[SetData]]内のelementsの数に設定する。
  8. trueを返す。

24.2.4.12 Set.prototype.isSupersetOf ( other )

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

  1. setthis valueとする。
  2. RequireInternalSlot(set, [[SetData]])を実行する。
  3. otherRecordを ? GetSetRecord(other) とする。
  4. SetDataSize(set.[[SetData]]) < otherRecord.[[Size]]なら、falseを返す。
  5. keysIteratorを ? GetIteratorFromMethod(otherRecord.[[SetObject]], otherRecord.[[Keys]]) とする。
  6. nextnot-startedとする。
  7. nextdoneでない間、繰り返す
    1. nextを ? IteratorStepValue(keysIterator) に設定する。
    2. nextdoneでないなら、
      1. SetDataHas(set.[[SetData]], next)がfalseなら、
        1. IteratorClose(keysIterator, NormalCompletion(unused))を実行する。
        2. falseを返す。
  8. trueを返す。

24.2.4.13 Set.prototype.keys ( )

"keys" propertyのinitial valueは、24.2.4.17でdefinedされる%Set.prototype.values%である。

Note

iteration purposesにおいて、Setは各entryがkeyとvalueに同じvalueを持つMapにsimilarに見える。

24.2.4.14 get Set.prototype.size

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

  1. setthis valueとする。
  2. RequireInternalSlot(set, [[SetData]])を実行する。
  3. sizeSetDataSize(set.[[SetData]])とする。
  4. 𝔽(size)を返す。

24.2.4.15 Set.prototype.symmetricDifference ( other )

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

  1. setthis valueとする。
  2. RequireInternalSlot(set, [[SetData]])を実行する。
  3. otherRecordを ? GetSetRecord(other) とする。
  4. keysIteratorを ? GetIteratorFromMethod(otherRecord.[[SetObject]], otherRecord.[[Keys]]) とする。
  5. resultSetDataset.[[SetData]]のcopyとする。
  6. nextnot-startedとする。
  7. nextdoneでない間、繰り返す
    1. nextを ? IteratorStepValue(keysIterator) に設定する。
    2. nextdoneでないなら、
      1. nextCanonicalizeKeyedCollectionKey(next)に設定する。
      2. resultIndexSetDataIndex(resultSetData, next)とする。
      3. resultIndexnot-foundなら、alreadyInResultfalseとする;そうでなければ、alreadyInResulttrueとする。
      4. SetDataHas(set.[[SetData]], next)がtrueなら、
        1. alreadyInResulttrueなら、resultSetData[resultIndex]をemptyに設定する。
      5. そうでなければ、
        1. alreadyInResultfalseなら、nextresultSetDataへappendする。
  8. resultOrdinaryObjectCreate(%Set.prototype%, « [[SetData]] »)とする。
  9. result.[[SetData]]resultSetDataに設定する。
  10. resultを返す。

24.2.4.16 Set.prototype.union ( other )

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

  1. setthis valueとする。
  2. RequireInternalSlot(set, [[SetData]])を実行する。
  3. otherRecordを ? GetSetRecord(other) とする。
  4. keysIteratorを ? GetIteratorFromMethod(otherRecord.[[SetObject]], otherRecord.[[Keys]]) とする。
  5. resultSetDataset.[[SetData]]のcopyとする。
  6. nextnot-startedとする。
  7. nextdoneでない間、繰り返す
    1. nextを ? IteratorStepValue(keysIterator) に設定する。
    2. nextdoneでないなら、
      1. nextCanonicalizeKeyedCollectionKey(next)に設定する。
      2. SetDataHas(resultSetData, next)がfalseなら、
        1. nextresultSetDataへappendする。
  8. resultOrdinaryObjectCreate(%Set.prototype%, « [[SetData]] »)とする。
  9. result.[[SetData]]resultSetDataに設定する。
  10. resultを返す。

24.2.4.17 Set.prototype.values ( )

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

  1. setthis valueとする。
  2. CreateSetIterator(set, value)を返す。

24.2.4.18 Set.prototype [ %Symbol.iterator% ] ( )

%Symbol.iterator% propertyのinitial valueは、24.2.4.17でdefinedされる%Set.prototype.values%である。

24.2.4.19 Set.prototype [ %Symbol.toStringTag% ]

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

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

24.2.5 Set Instancesのプロパティ

Set instancesはSet prototype objectからpropertiesをinheritするordinary objectsである。Set instancesは[[SetData]] internal slotも持つ。

24.2.6 Set Iteratorオブジェクト

Set Iteratorは、下でdefinedされるstructureを持つordinary objectであり、あるspecific Set instance objectに対するspecific iterationをrepresentする。Set Iterator objectsにはnamed constructorは存在しない。代わりに、Set Iterator objectsはSet instance objectsのcertain methodsをcallingすることでcreatedされる。

24.2.6.1 CreateSetIterator ( set, kind )

The abstract operation CreateSetIterator takes arguments set (an ECMAScript language value) and kind (key+value or value) and returns either a normal completion containing a Generator or a throw completion. Set methodsがreturnするそのようなiteratorsiterator objectsをcreateするために使用される。 It performs the following steps when called:

  1. RequireInternalSlot(set, [[SetData]])を実行する。
  2. closureを、parametersを持たず、setおよびkindをcapturesし、呼び出されたときに次のstepsを実行する新しいAbstract Closureとする:
    1. indexを0とする。
    2. entriesset.[[SetData]]とする。
    3. entriesCountentries内のelementsの数とする。
    4. index < entriesCountの間、繰り返す
      1. entryentries[index]とする。
      2. indexindex + 1に設定する。
      3. entryemptyでないなら、
        1. kindkey+valueなら、
          1. resultCreateArrayFromListentry, entry »)とする。
          2. GeneratorYield(CreateIteratorResultObject(result, false))を実行する。
        2. そうでなければ、
          1. Assert: kindvalueである。
          2. GeneratorYield(CreateIteratorResultObject(entry, false))を実行する。
        3. NOTE: このabstract operationのexecutionがGeneratorYieldによりpausedされている間に、entries内のelementsの数が増加しているかもしれない。
        4. entriesCountentries内のelementsの数に設定する。
    5. NormalCompletion(unused)を返す。
  3. CreateIteratorFromClosure(closure, "%SetIteratorPrototype%", %SetIteratorPrototype%)を返す。

24.2.6.2 %SetIteratorPrototype% Object

%SetIteratorPrototype% objectは:

24.2.6.2.1 %SetIteratorPrototype%.next ( )

  1. GeneratorResume(this value, empty, "%SetIteratorPrototype%")を返す。

24.2.6.2.2 %SetIteratorPrototype% [ %Symbol.toStringTag% ]

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

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

24.3 WeakMapオブジェクト

WeakMapはkey/value pairのcollectionsであり、keysはobjectsおよび/またはsymbolsであり、valuesは任意のECMAScript language valuesであってよい。WeakMapは、specific keyを持つkey/value pairをcontainするかどうかqueryできるが、keysとして保持しているvaluesをenumerateするmechanismはprovidedされない。certain conditionsでは、liveでないvaluesはWeakMap keysとしてremovedされる。これは9.9.3でdescribedされる。

implementationは、WeakMapのkey/value pairがinaccessibleになる時点と、そのkey/value pairがWeakMapからremovedされる時点との間に、arbitrarily determined latencyをimposeしてもよい。このlatencyがECMAScript programにobservableであったなら、それはprogram executionに影響し得るindeterminacyのsourceとなる。そのため、ECMAScript implementationは、observed keyをobserverにpresentすることをrequireしないWeakMapのkeyをobserveするmeansを一切provideしてはならない。

WeakMapは、平均的にcollection内のkey/value pairs数に対してsublinearなaccess timeを提供するhash tableまたはその他のmechanismsを用いて実装されなければならない。この仕様で用いられるdata structureは、WeakMapのrequired observable semanticsをdescribeすることだけを意図している。viable implementation modelであることは意図されていない。

Note

WeakMapおよびWeakSetは、WeakMapまたはWeakSet instanceが存在しない場合にobjectまたはsymbolがotherwise inaccessibleとなり、implementationのgarbage collection mechanismsによるresource reclamationのsubjectとなるときに、memory resourcesを“leak”しないmannerでstateをobjectまたはsymbolにdynamically associatingするためのmechanismsをprovideすることを意図している。このcharacteristicは、WeakMapまたはWeakSet instancesからkeysへのinverted per-object/symbol mappingを使用することでachievedできる。あるいは、各WeakMapまたはWeakSet instanceはそのkeyおよびvalue dataをinternally storeしてもよいが、このapproachはWeakMapまたはWeakSet implementationとgarbage collectorとのcoordinationをrequireする。以下のreferencesは、WeakMapおよびWeakSetのimplementationsにusefulであり得るmechanismをdescribeする:

Barry Hayes. 1997. Ephemerons: a new finalization mechanism. In Proceedings of the 12th ACM SIGPLAN conference on Object-oriented programming, systems, languages, and applications (OOPSLA '97), A. Michael Berman (Ed.). ACM, New York, NY, USA, 176-183, http://doi.acm.org/10.1145/263698.263733.

Alexandra Barros, Roberto Ierusalimschy, Eliminating Cycles in Weak Tables. Journal of Universal Computer Science - J.UCS, vol. 14, no. 21, pp. 3481-3497, 2008, http://www.jucs.org/jucs_14_21/eliminating_cycles_in_weak

24.3.1 WeakMap Constructor

WeakMap constructorは:

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

24.3.1.1 WeakMap ( [ iterable ] )

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

  1. NewTargetがundefinedなら、TypeError例外をthrowする。
  2. mapを ? OrdinaryCreateFromConstructor(NewTarget, "%WeakMap.prototype%", « [[WeakMapData]] ») とする。
  3. map.[[WeakMapData]]を新しい空のListに設定する。
  4. iterableundefinedまたはnullのどちらかなら、mapを返す。
  5. adderを ? Get(map, "set") とする。
  6. IsCallable(adder)がfalseなら、TypeError例外をthrowする。
  7. AddEntriesFromIterable(map, iterable, adder)を返す。
Note

parameter iterableがpresentである場合、それは%Symbol.iterator% methodを実装するobjectであることがexpectedされ、そのmethodは、first elementがWeakMap keyとして使用されるvalueであり、second elementがそのkeyにassociateされるvalueであるtwo element array-like objectをproduceするiterator objectを返す。

24.3.2 WeakMap Constructorのプロパティ

WeakMap constructorは:

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

24.3.2.1 WeakMap.prototype

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

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

24.3.3 WeakMap Prototype Objectのプロパティ

WeakMap prototype objectは:

  • %WeakMap.prototype%である。
  • valueが%Object.prototype%である[[Prototype]] internal slotを持つ。
  • ordinary objectである。
  • [[WeakMapData]] internal slotを持たない。

24.3.3.1 WeakMap.prototype.constructor

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

24.3.3.2 WeakMap.prototype.delete ( key )

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

  1. weakMapthis valueとする。
  2. RequireInternalSlot(weakMap, [[WeakMapData]])を実行する。
  3. CanBeHeldWeakly(key)がfalseなら、falseを返す。
  4. weakMap.[[WeakMapData]]の各Record { [[Key]], [[Value]] } entryについて、以下を行う
    1. entry.[[Key]]emptyでなく、SameValue(entry.[[Key]], key)がtrueなら、
      1. entry.[[Key]]emptyに設定する。
      2. entry.[[Value]]emptyに設定する。
      3. trueを返す。
  5. falseを返す。
Note

value emptyは、entryがdeletedされたことをindicateするためのspecification deviceとして使用される。実際のimplementationsは、entryをinternal data structuresからphysically removingするなど、他のactionsを取ってもよい。

24.3.3.3 WeakMap.prototype.get ( key )

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

  1. weakMapthis valueとする。
  2. RequireInternalSlot(weakMap, [[WeakMapData]])を実行する。
  3. CanBeHeldWeakly(key)がfalseなら、undefinedを返す。
  4. weakMap.[[WeakMapData]]の各Record { [[Key]], [[Value]] } entryについて、以下を行う
    1. entry.[[Key]]emptyでなく、SameValue(entry.[[Key]], key)がtrueなら、entry.[[Value]]を返す。
  5. undefinedを返す。

24.3.3.4 WeakMap.prototype.getOrInsert ( key, value )

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

  1. weakMapthis valueとする。
  2. RequireInternalSlot(weakMap, [[WeakMapData]])を実行する。
  3. CanBeHeldWeakly(key)がfalseなら、TypeError例外をthrowする。
  4. weakMap.[[WeakMapData]]の各Record { [[Key]], [[Value]] } entryについて、以下を行う
    1. entry.[[Key]]emptyでなく、SameValue(entry.[[Key]], key)がtrueなら、entry.[[Value]]を返す。
  5. entryRecord { [[Key]]: key, [[Value]]: value }とする。
  6. entryweakMap.[[WeakMapData]]へappendする。
  7. valueを返す。

24.3.3.5 WeakMap.prototype.getOrInsertComputed ( key, callback )

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

  1. weakMapthis valueとする。
  2. RequireInternalSlot(weakMap, [[WeakMapData]])を実行する。
  3. CanBeHeldWeakly(key)がfalseなら、TypeError例外をthrowする。
  4. IsCallable(callback)がfalseなら、TypeError例外をthrowする。
  5. weakMap.[[WeakMapData]]の各Record { [[Key]], [[Value]] } entryについて、以下を行う
    1. entry.[[Key]]emptyでなく、SameValue(entry.[[Key]], key)がtrueなら、entry.[[Value]]を返す。
  6. valueを ? Call(callback, undefined, « key ») とする。
  7. NOTE: WeakMapはcallbackのexecution中にmodifiedされているかもしれない。
  8. weakMap.[[WeakMapData]]の各Record { [[Key]], [[Value]] } entryについて、以下を行う
    1. entry.[[Key]]emptyでなく、SameValue(entry.[[Key]], key)がtrueなら、
      1. entry.[[Value]]valueに設定する。
      2. valueを返す。
  9. entryRecord { [[Key]]: key, [[Value]]: value }とする。
  10. entryweakMap.[[WeakMapData]]へappendする。
  11. valueを返す。

24.3.3.6 WeakMap.prototype.has ( key )

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

  1. weakMapthis valueとする。
  2. RequireInternalSlot(weakMap, [[WeakMapData]])を実行する。
  3. CanBeHeldWeakly(key)がfalseなら、falseを返す。
  4. weakMap.[[WeakMapData]]の各Record { [[Key]], [[Value]] } entryについて、以下を行う
    1. entry.[[Key]]emptyでなく、SameValue(entry.[[Key]], key)がtrueなら、trueを返す。
  5. falseを返す。

24.3.3.7 WeakMap.prototype.set ( key, value )

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

  1. weakMapthis valueとする。
  2. RequireInternalSlot(weakMap, [[WeakMapData]])を実行する。
  3. CanBeHeldWeakly(key)がfalseなら、TypeError例外をthrowする。
  4. weakMap.[[WeakMapData]]の各Record { [[Key]], [[Value]] } entryについて、以下を行う
    1. entry.[[Key]]emptyでなく、SameValue(entry.[[Key]], key)がtrueなら、
      1. entry.[[Value]]valueに設定する。
      2. weakMapを返す。
  5. entryRecord { [[Key]]: key, [[Value]]: value }とする。
  6. entryweakMap.[[WeakMapData]]へappendする。
  7. weakMapを返す。

24.3.3.8 WeakMap.prototype [ %Symbol.toStringTag% ]

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

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

24.3.4 WeakMap Instancesのプロパティ

WeakMap instancesはWeakMap prototype objectからpropertiesをinheritするordinary objectsである。WeakMap instancesは[[WeakMapData]] internal slotも持つ。

24.4 WeakSetオブジェクト

WeakSetはobjectsおよび/またはsymbolsのcollectionsである。distinct objectまたはsymbolはWeakSetのcollectionのelementとして1回だけ出現してよい。WeakSetはspecific valueをcontainするかどうかqueryできるが、保持しているvaluesをenumerateするmechanismはprovidedされない。certain conditionsでは、liveでないvaluesはWeakSet elementsとしてremovedされる。これは9.9.3でdescribedされる。

implementationは、WeakSet内にcontainedされるvalueがinaccessibleになる時点と、そのvalueがWeakSetからremovedされる時点との間に、arbitrarily determined latencyをimposeしてもよい。このlatencyがECMAScript programにobservableであったなら、それはprogram executionに影響し得るindeterminacyのsourceとなる。そのため、ECMAScript implementationは、observed valueをobserverにpresentすることをrequireしないparticular valueをWeakSetがcontainするかどうかをdetermineするmeansを一切provideしてはならない。

WeakSetは、平均的にcollection内のelements数に対してsublinearなaccess timeを提供するhash tableまたはその他のmechanismsを用いて実装されなければならない。この仕様で用いられるdata structureは、WeakSetのrequired observable semanticsをdescribeすることだけを意図している。viable implementation modelであることは意図されていない。

Note

24.3内のNOTEを参照。

24.4.1 WeakSet Constructor

WeakSet constructorは:

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

24.4.1.1 WeakSet ( [ iterable ] )

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

  1. NewTargetがundefinedなら、TypeError例外をthrowする。
  2. setを ? OrdinaryCreateFromConstructor(NewTarget, "%WeakSet.prototype%", « [[WeakSetData]] ») とする。
  3. set.[[WeakSetData]]を新しい空のListに設定する。
  4. iterableundefinedまたはnullのどちらかなら、setを返す。
  5. adderを ? Get(set, "add") とする。
  6. IsCallable(adder)がfalseなら、TypeError例外をthrowする。
  7. iteratorRecordを ? GetIterator(iterable, sync) とする。
  8. 繰り返す、
    1. nextを ? IteratorStepValue(iteratorRecord) とする。
    2. nextdoneなら、setを返す。
    3. statusCompletion(Call(adder, set, « next »))とする。
    4. IfAbruptCloseIterator(status, iteratorRecord)。

24.4.2 WeakSet Constructorのプロパティ

WeakSet constructorは:

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

24.4.2.1 WeakSet.prototype

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

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

24.4.3 WeakSet Prototype Objectのプロパティ

WeakSet prototype objectは:

  • %WeakSet.prototype%である。
  • valueが%Object.prototype%である[[Prototype]] internal slotを持つ。
  • ordinary objectである。
  • [[WeakSetData]] internal slotを持たない。

24.4.3.1 WeakSet.prototype.add ( value )

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

  1. weakSetthis valueとする。
  2. RequireInternalSlot(weakSet, [[WeakSetData]])を実行する。
  3. CanBeHeldWeakly(value)がfalseなら、TypeError例外をthrowする。
  4. weakSet.[[WeakSetData]]の各element entryについて、以下を行う
    1. entryemptyでなく、SameValue(entry, value)がtrueなら、
      1. weakSetを返す。
  5. valueweakSet.[[WeakSetData]]へappendする。
  6. weakSetを返す。

24.4.3.2 WeakSet.prototype.constructor

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

24.4.3.3 WeakSet.prototype.delete ( value )

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

  1. weakSetthis valueとする。
  2. RequireInternalSlot(weakSet, [[WeakSetData]])を実行する。
  3. CanBeHeldWeakly(value)がfalseなら、falseを返す。
  4. weakSet.[[WeakSetData]]の各element entryについて、以下を行う
    1. entryemptyでなく、SameValue(entry, value)がtrueなら、
      1. valueがentryであるweakSet.[[WeakSetData]]のelementを、valueがemptyであるelementでreplaceする。
      2. trueを返す。
  5. falseを返す。
Note

value emptyは、entryがdeletedされたことをindicateするためのspecification deviceとして使用される。実際のimplementationsは、entryをinternal data structuresからphysically removingするなど、他のactionsを取ってもよい。

24.4.3.4 WeakSet.prototype.has ( value )

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

  1. weakSetthis valueとする。
  2. RequireInternalSlot(weakSet, [[WeakSetData]])を実行する。
  3. CanBeHeldWeakly(value)がfalseなら、falseを返す。
  4. weakSet.[[WeakSetData]]の各element entryについて、以下を行う
    1. entryemptyでなく、SameValue(entry, value)がtrueなら、trueを返す。
  5. falseを返す。

24.4.3.5 WeakSet.prototype [ %Symbol.toStringTag% ]

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

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

24.4.4 WeakSet Instancesのプロパティ

WeakSet instancesはWeakSet prototype objectからpropertiesをinheritするordinary objectsである。WeakSet instancesは[[WeakSetData]] internal slotも持つ。

24.5 Keyed Collectionsの抽象操作

24.5.1 CanonicalizeKeyedCollectionKey ( key )

The abstract operation CanonicalizeKeyedCollectionKey takes argument key (an ECMAScript language value) and returns an ECMAScript language value. It performs the following steps when called:

  1. key-0𝔽なら、+0𝔽を返す。
  2. keyを返す。

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 }を持つ。

26 メモリ管理

26.1 WeakRefオブジェクト

WeakRefは、target objectまたはsymbolをガベージコレクションから保持することなく参照するために使用されるobjectである。WeakRefsは、targetがガベージコレクションによって回収されていない場合に、target valueへのアクセスを可能にするためにdereferenceできる。

26.1.1 WeakRefコンストラクタ

WeakRef constructorは:

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

26.1.1.1 WeakRef ( target )

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

  1. NewTargetがundefinedなら、TypeError例外をthrowする。
  2. CanBeHeldWeakly(target)がfalseなら、TypeError例外をthrowする。
  3. weakRefを ? OrdinaryCreateFromConstructor(NewTarget, "%WeakRef.prototype%", « [[WeakRefTarget]] ») とする。
  4. AddToKeptObjects(target)を実行する。
  5. weakRef.[[WeakRefTarget]]targetに設定する。
  6. weakRefを返す。

26.1.2 WeakRefコンストラクタのプロパティ

WeakRef constructorは:

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

26.1.2.1 WeakRef.prototype

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

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

26.1.3 WeakRef Prototype Objectのプロパティ

WeakRef prototype objectは:

  • %WeakRef.prototype%である。
  • valueが%Object.prototype%である[[Prototype]] internal slotを持つ。
  • ordinary objectである。
  • [[WeakRefTarget]] internal slotを持たない。

26.1.3.1 WeakRef.prototype.constructor

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

26.1.3.2 WeakRef.prototype.deref ( )

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

  1. weakRefthis valueとする。
  2. RequireInternalSlot(weakRef, [[WeakRefTarget]])を実行する。
  3. WeakRefDeref(weakRef)を返す。
Note

WeakRefundefinedでないtarget valueを返す場合、このtarget valueは、ECMAScript codeのcurrent executionがcompletedするまでガベージコレクションされるべきではない。AddToKeptObjects operationは、read consistencyがmaintainedされることを確実にする。

let target = { foo() {} };
let weakRef = new WeakRef(target);

// ... later ...

if (weakRef.deref()) {
  weakRef.deref().foo();
}

上記の例では、first derefがundefinedにevaluateしない場合、second derefもそうなることはできない。

26.1.3.3 WeakRef.prototype [ %Symbol.toStringTag% ]

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

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

26.1.4 WeakRef Abstract Operations

26.1.4.1 WeakRefDeref ( weakRef )

The abstract operation WeakRefDeref takes argument weakRef (a WeakRef) and returns an ECMAScript language value. It performs the following steps when called:

  1. targetweakRef.[[WeakRefTarget]]とする。
  2. targetemptyでないなら、
    1. AddToKeptObjects(target)を実行する。
    2. targetを返す。
  3. undefinedを返す。
Note

このabstract operationは、livenessを簡潔にdefineできるようにするためだけに、WeakRef.prototype.derefからseparatelyにdefinedされている。

26.1.5 WeakRefインスタンスのプロパティ

WeakRef instancesは、WeakRef prototype objectからpropertiesをinheritするordinary objectsである。WeakRef instancesはまた、[[WeakRefTarget]] internal slotを持つ。

26.2 FinalizationRegistryオブジェクト

FinalizationRegistryは、target objectsおよびsymbolsがガベージコレクションされたときに実行されるcleanup operationsのregistrationおよびunregistrationをmanageするobjectである。

26.2.1 FinalizationRegistryコンストラクタ

FinalizationRegistry constructorは:

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

26.2.1.1 FinalizationRegistry ( cleanupCallback )

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

  1. NewTargetがundefinedである場合、TypeError例外を投げる。
  2. IsCallable(cleanupCallback)がfalseである場合、TypeError例外を投げる。
  3. OrdinaryCreateFromConstructor(NewTarget, "%FinalizationRegistry.prototype%", « [[Realm]], [[CleanupCallback]], [[Cells]] »)をfinalizationRegistryとする。
  4. アクティブな関数オブジェクトをactiveFuncとする。
  5. finalizationRegistry.[[Realm]]activeFunc.[[Realm]]に設定する。
  6. finalizationRegistry.[[CleanupCallback]]HostMakeJobCallback(cleanupCallback)に設定する。
  7. finalizationRegistry.[[Cells]]を新しい空のListに設定する。
  8. finalizationRegistryを返す。

26.2.2 FinalizationRegistryコンストラクタのプロパティ

FinalizationRegistry constructorは:

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

26.2.2.1 FinalizationRegistry.prototype

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

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

26.2.3 FinalizationRegistry Prototype Objectのプロパティ

FinalizationRegistry prototype objectは:

  • %FinalizationRegistry.prototype%である。
  • valueが%Object.prototype%である[[Prototype]] internal slotを持つ。
  • ordinary objectである。
  • [[Cells]]および[[CleanupCallback]] internal slotsを持たない。

26.2.3.1 FinalizationRegistry.prototype.constructor

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

26.2.3.2 FinalizationRegistry.prototype.register ( target, heldValue [ , unregisterToken ] )

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

  1. finalizationRegistrythis valueとする。
  2. RequireInternalSlot(finalizationRegistry, [[Cells]])を実行する。
  3. CanBeHeldWeakly(target)がfalseなら、TypeError例外をthrowする。
  4. SameValue(target, heldValue)がtrueなら、TypeError例外をthrowする。
  5. CanBeHeldWeakly(unregisterToken)がfalseなら、
    1. unregisterTokenundefinedでないなら、TypeError例外をthrowする。
    2. unregisterTokenemptyに設定する。
  6. cellRecord { [[WeakRefTarget]]: target, [[HeldValue]]: heldValue, [[UnregisterToken]]: unregisterToken }とする。
  7. cellfinalizationRegistry.[[Cells]]にappendする。
  8. undefinedを返す。
Note

このspecificationのalgorithmsおよびdefinitionsに基づくと、finalizationRegistry.[[Cells]]cellをcontainsするとき、cell.[[HeldValue]]liveである;しかし、これは必ずしもcell.[[UnregisterToken]]またはcell.[[Target]]liveであることを意味しない。例えば、objectをそれ自身をunregister tokenとしてregisterしても、そのobjectが永久にaliveに保たれることはない。

26.2.3.3 FinalizationRegistry.prototype.unregister ( unregisterToken )

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

  1. finalizationRegistrythis valueとする。
  2. RequireInternalSlot(finalizationRegistry, [[Cells]])を実行する。
  3. CanBeHeldWeakly(unregisterToken)がfalseなら、TypeError例外をthrowする。
  4. removedfalseとする。
  5. finalizationRegistry.[[Cells]]の各Record { [[WeakRefTarget]], [[HeldValue]], [[UnregisterToken]] } cellについて、
    1. cell.[[UnregisterToken]]emptyでなく、かつSameValue(cell.[[UnregisterToken]], unregisterToken)がtrueなら、
      1. finalizationRegistry.[[Cells]]からcellをremoveする。
      2. removedtrueに設定する。
  6. removedを返す。

26.2.3.4 FinalizationRegistry.prototype [ %Symbol.toStringTag% ]

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

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

26.2.4 FinalizationRegistryインスタンスのプロパティ

FinalizationRegistry instancesは、FinalizationRegistry prototype objectからpropertiesをinheritするordinary objectsである。FinalizationRegistry instancesはまた、[[Cells]]および[[CleanupCallback]] internal slotsを持つ。

27 制御抽象オブジェクト

27.1 反復

27.1.1 共通の反復インターフェイス

interfaceは、関連付けられた値が特定の仕様に一致するproperty keysの集合である。interfaceの仕様によって記述されたすべてのpropertiesを提供する任意のobjectは、そのinterfaceにconformsする。interfaceはdistinct objectによって表現されない。任意のinterfaceにconformする、別々に実装されたobjectsが多数存在しうる。個々のobjectは複数のinterfacesにconformしうる。

27.1.1.1 Iterableインターフェイス

iterable interfaceは、Table 79で記述されるpropertiesを含む:

Table 79: Iterable Interface Required Properties
Property Value Requirements
%Symbol.iterator% iterator objectを返すfunction 返されるobjectはiterator interfaceにconformしなければならない。

27.1.1.2 Iteratorインターフェイス

iterator interfaceを実装するobjectは、Table 80内のpropertyを含まなければならない。そのようなobjectsは、Table 81内のpropertiesを実装してもよい。

Table 80: Iterator Interface Required Properties
Property Value Requirements
"next" IteratorResult objectを返すfunction 返されるobjectはIteratorResult interfaceにconformしなければならない。iteratornext methodへの以前のcallが"done" propertyがtrueであるIteratorResult objectを返した場合、そのobjectのnext methodへの後続のすべてのcallsも、"done" propertyがtrueであるIteratorResult objectを返すべきである。ただし、このrequirementは強制されない。
Note 1

next functionにargumentsを渡してもよいが、それらの解釈およびvalidityはtarget iteratorに依存する。for-of statementおよびiteratorsの他の一般的な利用者はargumentsを渡さないため、そのような方法で使用されることを期待するiterator objectsは、argumentsなしで呼び出されることに対処できるよう準備されていなければならない。

Table 81: Iterator Interface Optional Properties
Property Value Requirements
"return" IteratorResult objectを返すfunction 返されるobjectはIteratorResult interfaceにconformしなければならない。このmethodをinvokeすると、呼び出し側がiteratorに対してこれ以上next method callsを行う意図がないことをiterator objectに通知する。返されるIteratorResult objectは、典型的にはvalueがtrueである"done" property、およびreturn methodのargumentとして渡された値を持つ"value" propertyを持つ。ただし、このrequirementは強制されない。
"throw" IteratorResult objectを返すfunction 返されるobjectはIteratorResult interfaceにconformしなければならない。このmethodをinvokeすると、呼び出し側がerror conditionを検出したことをiterator objectに通知する。argumentはerror conditionを識別するために使用されてもよく、典型的にはexception objectである。典型的な応答は、argumentとして渡されたvalueをthrowすることである。methodがthrowしない場合、返されるIteratorResult objectは、典型的にはvalueがtrueである"done" propertyを持つ。
Note 2

典型的には、これらのmethodsの呼び出し側は、それらをinvokeする前にそれらの存在をcheckすべきである。for-ofyield*、およびarray destructuringを含む特定のECMAScript language featuresは、existence checkを実行した後にこれらのmethodsをcallする。iterable objectsをargumentsとして受け入れるほとんどのECMAScript library functionsも、それらを条件付きでcallする。

27.1.1.3 Async Iterableインターフェイス

async iterable interfaceは、Table 82で記述されるpropertiesを含む:

Table 82: Async Iterable Interface Required Properties
Property Value Requirements
%Symbol.asyncIterator% async iterator objectを返すfunction 返されるobjectはasync iterator interfaceにconformしなければならない。

27.1.1.4 Async Iteratorインターフェイス

async iterator interfaceを実装するobjectは、Table 83内のpropertiesを含まなければならない。そのようなobjectsは、Table 84内のpropertiesを実装してもよい。

Table 83: Async Iterator Interface Required Properties
Property Value Requirements
"next" IteratorResult objectに対するpromiseを返すfunction

返されるpromiseは、fulfilledされたときに、IteratorResult interfaceにconformするobjectでfulfillしなければならない。async iteratornext methodへの以前のcallが"done" propertyがtrueであるIteratorResult objectに対するpromiseを返した場合、そのobjectのnext methodへの後続のすべてのcallsも、"done" propertyがtrueであるIteratorResult objectに対するpromiseを返すべきである。ただし、このrequirementは強制されない。

さらに、fulfillment valueとして機能するIteratorResult objectは、valueがpromise(または“thenable”)でない"value" propertyを持つべきである。ただし、このrequirementも強制されない。

Note 1

next functionにargumentsを渡してもよいが、それらの解釈およびvalidityはtarget async iteratorに依存する。for-await-of statementおよびasync iteratorsの他の一般的な利用者はargumentsを渡さないため、そのような方法で使用されることを期待するasync iterator objectsは、argumentsなしで呼び出されることに対処できるよう準備されていなければならない。

Table 84: Async Iterator Interface Optional Properties
Property Value Requirements
"return" IteratorResult objectに対するpromiseを返すfunction

返されるpromiseは、fulfilledされたときに、IteratorResult interfaceにconformするobjectでfulfillしなければならない。このmethodをinvokeすると、呼び出し側がasync iteratorに対してこれ以上next method callsを行う意図がないことをasync iterator objectに通知する。返されるpromiseはIteratorResult objectでfulfillし、そのobjectは典型的にはvalueがtrueである"done" property、およびreturn methodのargumentとして渡された値を持つ"value" propertyを持つ。ただし、このrequirementは強制されない。

さらに、fulfillment valueとして機能するIteratorResult objectは、valueがpromise(または“thenable”)でない"value" propertyを持つべきである。argument valueが典型的な方法で使用される場合、それがrejected promiseなら同じreasonでrejectedされたpromiseが返されるべきであり、それがfulfilled promiseなら、そのfulfillment valueが返されるpromiseのIteratorResult object fulfillment valueの"value" propertyとして使用されるべきである。ただし、これらのrequirementsも強制されない。

"throw" IteratorResult objectに対するpromiseを返すfunction

返されるpromiseは、fulfilledされたときに、IteratorResult interfaceにconformするobjectでfulfillしなければならない。このmethodをinvokeすると、呼び出し側がerror conditionを検出したことをasync iterator objectに通知する。argumentはerror conditionを識別するために使用されてもよく、典型的にはexception objectである。典型的な応答は、argumentとして渡されたvalueでrejectするrejected promiseを返すことである。

返されるpromiseがfulfilledされる場合、IteratorResult object fulfillment valueは、典型的にはvalueがtrueである"done" propertyを持つ。さらに、それはvalueがpromise(または“thenable”)でない"value" propertyを持つべきであるが、このrequirementは強制されない。

Note 2

典型的には、これらのmethodsの呼び出し側は、それらをinvokeする前にそれらの存在をcheckすべきである。for-await-ofおよびyield*を含む特定のECMAScript language featuresは、existence checkを実行した後にこれらのmethodsをcallする。

27.1.1.5 IteratorResultインターフェイス

IteratorResult interfaceは、Table 85に列挙されるpropertiesを含む:

Table 85: IteratorResult Interface Properties
Property Value Requirements
"done" Boolean これはiterator next method callのresult statusである。iteratorのendに到達した場合、"done"trueである。endに到達していない場合、"done"falseであり、valueが利用可能である。"done" property(ownまたはinherited)が存在しない場合、そのvalueはfalseであると見なされる。
"value" ECMAScript language value doneがfalseなら、これはcurrent iteration element valueである。doneがtrueなら、これはiteratorのreturn value(供給されている場合)である。iteratorにreturn valueがない場合、"value"undefinedである。その場合、conforming objectが明示的な"value" propertyをinheritしていないなら、"value" propertyは存在しなくてもよい。

27.1.2 Iterator Helperオブジェクト

Iterator Helper objectは、特定のsource iterator objectのlazy transformationを表すordinary objectである。Iterator Helper objectsにはnamed constructorは存在しない。代わりに、Iterator Helper objectsはIterator instance objectsの特定のmethodsをcallすることによって作成される。

27.1.2.1 %IteratorHelperPrototype%オブジェクト

%IteratorHelperPrototype% objectは:

27.1.2.1.1 %IteratorHelperPrototype%.next ( )

  1. GeneratorResume(this value, undefined, "Iterator Helper")を返す。

27.1.2.1.2 %IteratorHelperPrototype%.return ( )

  1. objthis valueとする。
  2. RequireInternalSlot(obj, [[UnderlyingIterators]])を実行する。
  3. Assert: obj[[GeneratorState]] internal slotを持つ。
  4. obj.[[GeneratorState]]suspended-startなら、
    1. obj.[[GeneratorState]]completedに設定する。
    2. NOTE: generatorがcompleted stateに入ると、そこから離れることはなく、関連付けられたexecution contextは再開されない。この時点で、objに関連付けられた任意のexecution stateは破棄できる。
    3. IteratorCloseAll(obj.[[UnderlyingIterators]], NormalCompletion(unused))を実行する。
    4. CreateIteratorResultObject(undefined, true)を返す。
  5. completionReturnCompletion(undefined)とする。
  6. GeneratorResumeAbrupt(obj, completion, "Iterator Helper")を返す。

27.1.2.1.3 %IteratorHelperPrototype% [ %Symbol.toStringTag% ]

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

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

27.1.3 Iteratorオブジェクト

27.1.3.1 Iteratorコンストラクタ

Iterator constructorは:

  • %Iterator%である。
  • global object"Iterator" propertyのinitial valueである。
  • subclassableであるようにdesignedされている。class definitionのextends clauseのvalueとして使用してもよい。

27.1.3.1.1 Iterator ( )

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

  1. NewTargetがundefinedまたはactive function objectなら、TypeError例外をthrowする。
  2. OrdinaryCreateFromConstructor(NewTarget, "%Iterator.prototype%")を返す。

27.1.3.2 Iteratorコンストラクタのプロパティ

Iterator constructorは:

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

27.1.3.2.1 Iterator.concat ( ...items )

  1. iterablesをnew empty Listとする。
  2. itemsの各element itemについて、
    1. itemがObjectでないなら、TypeError例外をthrowする。
    2. methodを ? GetMethod(item, %Symbol.iterator%) とする。
    3. methodundefinedなら、TypeError例外をthrowする。
    4. Record { [[OpenMethod]]: method, [[Iterable]]: item }をiterablesにappendする。
  3. closureを、iterablesをcaptureし、呼び出されたときに以下のstepsを実行する、parametersを持たないnew Abstract Closureとする:
    1. iterablesの各Record iterableについて、
      1. iteratorを ? Call(iterable.[[OpenMethod]], iterable.[[Iterable]]) とする。
      2. iteratorがObjectでないなら、TypeError例外をthrowする。
      3. iteratorRecordを ? GetIteratorDirect(iterator) とする。
      4. innerAlivetrueとする。
      5. innerAlivetrueである間、繰り返す:
        1. innerValueを ? IteratorStepValue(iteratorRecord) とする。
        2. innerValuedoneなら、
          1. innerAlivefalseに設定する。
        3. そうでなければ、
          1. completionCompletion(Yield(innerValue))とする。
          2. completionabrupt completionなら、
            1. IteratorClose(iteratorRecord, completion)を返す。
    2. ReturnCompletion(undefined)を返す。
  4. genCreateIteratorFromClosure(closure, "Iterator Helper", %IteratorHelperPrototype%, « [[UnderlyingIterators]] »)とする。
  5. gen.[[UnderlyingIterators]]をnew empty Listに設定する。
  6. genを返す。

27.1.3.2.2 Iterator.from ( obj )

  1. iteratorRecordを ? GetIteratorFlattenable(obj, iterate-string-primitives) とする。
  2. hasInstanceを ? OrdinaryHasInstance(%Iterator%, iteratorRecord.[[Iterator]]) とする。
  3. hasInstancetrueなら、
    1. iteratorRecord.[[Iterator]]を返す。
  4. wrapperOrdinaryObjectCreate(%WrapForValidIteratorPrototype%, « [[Iterated]] »)とする。
  5. wrapper.[[Iterated]]iteratorRecordに設定する。
  6. wrapperを返す。

27.1.3.2.2.1 %WrapForValidIteratorPrototype%オブジェクト

%WrapForValidIteratorPrototype% objectは:

27.1.3.2.2.1.1 %WrapForValidIteratorPrototype%.next ( )

  1. objthis valueとする。
  2. RequireInternalSlot(obj, [[Iterated]])を実行する。
  3. iteratorRecordobj.[[Iterated]]とする。
  4. Call(iteratorRecord.[[NextMethod]], iteratorRecord.[[Iterator]])を返す。

27.1.3.2.2.1.2 %WrapForValidIteratorPrototype%.return ( )

  1. objthis valueとする。
  2. RequireInternalSlot(obj, [[Iterated]])を実行する。
  3. iteratorobj.[[Iterated]].[[Iterator]]とする。
  4. Assert: iteratorはObjectである。
  5. returnMethodを ? GetMethod(iterator, "return") とする。
  6. returnMethodundefinedなら、
    1. CreateIteratorResultObject(undefined, true)を返す。
  7. Call(returnMethod, iterator)を返す。

27.1.3.2.3 Iterator.prototype

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

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

27.1.3.2.4 Iterator.zip ( iterables [ , options ] )

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

  1. iterablesがObjectでないなら、TypeError例外をthrowする。
  2. optionsを ? GetOptionsObject(options) に設定する。
  3. modeを ? Get(options, "mode") とする。
  4. modeundefinedなら、mode"shortest"に設定する。
  5. mode"shortest""longest"、または"strict"のいずれでもないなら、TypeError例外をthrowする。
  6. paddingOptionundefinedとする。
  7. mode"longest"なら、
    1. paddingOptionを ? Get(options, "padding") に設定する。
    2. paddingOptionundefinedでなく、かつObjectでないなら、TypeError例外をthrowする。
  8. itersをnew empty Listとする。
  9. paddingをnew empty Listとする。
  10. inputIterを ? GetIterator(iterables, sync) とする。
  11. nextnot-startedとする。
  12. nextdoneでない間、繰り返す:
    1. nextCompletion(IteratorStepValue(inputIter))に設定する。
    2. IfAbruptCloseIterators(next, iters).
    3. nextdoneでないなら、
      1. iterCompletion(GetIteratorFlattenable(next, reject-primitives))とする。
      2. needClosingを« inputIter »とiterslist-concatenationとする。
      3. IfAbruptCloseIterators(iter, needClosing).
      4. iteritersにappendする。
  13. iterCountitersのelements数とする。
  14. mode"longest"なら、
    1. paddingOptionundefinedなら、
      1. iterCount回繰り返す:
        1. undefinedpaddingにappendする。
    2. そうでなければ、
      1. paddingIterCompletion(GetIterator(paddingOption, sync))とする。
      2. IfAbruptCloseIterators(paddingIter, iters).
      3. usingIteratortrueとする。
      4. iterCount回繰り返す:
        1. usingIteratortrueなら、
          1. nextCompletion(IteratorStepValue(paddingIter))に設定する。
          2. IfAbruptCloseIterators(next, iters).
          3. nextdoneなら、
            1. usingIteratorfalseに設定する。
          4. そうでなければ、
            1. nextpaddingにappendする。
        2. usingIteratorfalseなら、undefinedpaddingにappendする。
      5. usingIteratortrueなら、
        1. completionCompletion(IteratorClose(paddingIter, NormalCompletion(unused)))とする。
        2. IfAbruptCloseIterators(completion, iters).
  15. finishResultsを、parameters (results)を持ち、何もcaptureせず、呼び出されたときに以下のstepsを実行するnew Abstract Closureとする:
    1. CreateArrayFromList(results)を返す。
  16. IteratorZip(iters, mode, padding, finishResults)を返す。

27.1.3.2.5 Iterator.zipKeyed ( iterables [ , options ] )

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

  1. iterablesがObjectでないなら、TypeError例外をthrowする。
  2. optionsを ? GetOptionsObject(options) に設定する。
  3. modeを ? Get(options, "mode") とする。
  4. modeundefinedなら、mode"shortest"に設定する。
  5. mode"shortest""longest"、または"strict"のいずれでもないなら、TypeError例外をthrowする。
  6. paddingOptionundefinedとする。
  7. mode"longest"なら、
    1. paddingOptionを ? Get(options, "padding") に設定する。
    2. paddingOptionundefinedでなく、かつObjectでないなら、TypeError例外をthrowする。
  8. itersをnew empty Listとする。
  9. paddingをnew empty Listとする。
  10. allKeysを ? iterables.[[OwnPropertyKeys]]() とする。
  11. keysをnew empty Listとする。
  12. allKeysの各element keyについて、
    1. propertyDescCompletion(iterables.[[GetOwnProperty]](key))とする。
    2. IfAbruptCloseIterators(propertyDesc, iters).
    3. propertyDescundefinedでなく、かつpropertyDesc.[[Enumerable]]trueなら、
      1. valueCompletion(Get(iterables, key))とする。
      2. IfAbruptCloseIterators(value, iters).
      3. valueundefinedでないなら、
        1. keykeysにappendする。
        2. iterCompletion(GetIteratorFlattenable(value, reject-primitives))とする。
        3. IfAbruptCloseIterators(iter, iters).
        4. iteritersにappendする。
  13. iterCountitersのelements数とする。
  14. mode"longest"なら、
    1. paddingOptionundefinedなら、
      1. iterCount回繰り返す:
        1. undefinedpaddingにappendする。
    2. そうでなければ、
      1. keysの各element keyについて、
        1. valueCompletion(Get(paddingOption, key))とする。
        2. IfAbruptCloseIterators(value, iters).
        3. valuepaddingにappendする。
  15. finishResultsを、parameters (results)を持ち、keysiterCountをcaptureし、呼び出されたときに以下のstepsを実行するnew Abstract Closureとする:
    1. objOrdinaryObjectCreate(null)とする。
    2. 0 ≤ i < iterCountである各integer iについて、昇順で、
      1. CreateDataPropertyOrThrow(obj, keys[i], results[i])を実行する。
    3. objを返す。
  16. IteratorZip(iters, mode, padding, finishResults)を返す。

27.1.3.3 Iterator Prototype Objectのプロパティ

Iterator prototype objectは:

Note

このspecificationでdefinedされる、iterator interfaceを実装するすべてのobjectsも%Iterator.prototype%からinheritする。ECMAScript codeも、%Iterator.prototype%からinheritするobjectsをdefineしてよい。%Iterator.prototype%は、すべてのiterator objectsに適用可能なadditional methodsを追加できる場所を提供する。

以下のexpressionは、ECMAScript codeが%Iterator.prototype% objectにaccessできる1つの方法である:

Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()))

27.1.3.3.1 Iterator.prototype.constructor

Iterator.prototype.constructorは、attributes { [[Enumerable]]: false, [[Configurable]]: true }を持つaccessor propertyである。[[Get]]および[[Set]] attributesは以下のようにdefinedされる:

27.1.3.3.1.1 get Iterator.prototype.constructor

[[Get]] attributeのvalueは、argumentsを必要としないbuilt-in functionである。呼び出されたときに以下のstepsを実行する:

  1. %Iterator%を返す。

27.1.3.3.1.2 set Iterator.prototype.constructor

[[Set]] attributeのvalueは、argument vを取るbuilt-in functionである。呼び出されたときに以下のstepsを実行する:

  1. SetterThatIgnoresPrototypeProperties(this value, %Iterator.prototype%, "constructor", v)を実行する。
  2. undefinedを返す。
Note

ほとんどのbuilt-in prototypes上の"constructor" propertyとは異なり、web-compatibilityの理由により、このpropertyはaccessorでなければならない。

27.1.3.3.2 Iterator.prototype.drop ( limit )

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

  1. objthis valueとする。
  2. objがObjectでないなら、TypeError例外をthrowする。
  3. iteratedIterator Record { [[Iterator]]: obj, [[NextMethod]]: undefined, [[Done]]: false }とする。
  4. numberLimitCompletion(ToNumber(limit))とする。
  5. IfAbruptCloseIterator(numberLimit, iterated).
  6. numberLimitNaNなら、
    1. errorThrowCompletion(a newly created RangeError object)とする。
    2. IteratorClose(iterated, error)を返す。
  7. intLimitを ! ToIntegerOrInfinity(numberLimit) とする。
  8. intLimit < 0なら、
    1. errorThrowCompletion(a newly created RangeError object)とする。
    2. IteratorClose(iterated, error)を返す。
  9. iteratedを ? GetIteratorDirect(obj) に設定する。
  10. closureを、iteratedintLimitをcaptureし、呼び出されたときに以下のstepsを実行する、parametersを持たないnew Abstract Closureとする:
    1. remainingintLimitとする。
    2. remaining > 0である間、繰り返す:
      1. remaining ≠ +∞なら、
        1. remainingremaining - 1に設定する。
      2. nextを ? IteratorStep(iterated) とする。
      3. nextdoneなら、ReturnCompletion(undefined)を返す。
    3. 繰り返す:
      1. valueを ? IteratorStepValue(iterated) とする。
      2. valuedoneなら、ReturnCompletion(undefined)を返す。
      3. completionCompletion(Yield(value))とする。
      4. IfAbruptCloseIterator(completion, iterated).
  11. resultCreateIteratorFromClosure(closure, "Iterator Helper", %IteratorHelperPrototype%, « [[UnderlyingIterators]] »)とする。
  12. result.[[UnderlyingIterators]]を« iterated »に設定する。
  13. resultを返す。

27.1.3.3.3 Iterator.prototype.every ( predicate )

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

  1. objthis valueとする。
  2. objがObjectでないなら、TypeError例外をthrowする。
  3. iteratedIterator Record { [[Iterator]]: obj, [[NextMethod]]: undefined, [[Done]]: false }とする。
  4. IsCallable(predicate)がfalseなら、
    1. errorThrowCompletion(a newly created TypeError object)とする。
    2. IteratorClose(iterated, error)を返す。
  5. iteratedを ? GetIteratorDirect(obj) に設定する。
  6. counterを0とする。
  7. 繰り返す:
    1. valueを ? IteratorStepValue(iterated) とする。
    2. valuedoneなら、trueを返す。
    3. resultCompletion(Call(predicate, undefined, « value, 𝔽(counter) »))とする。
    4. IfAbruptCloseIterator(result, iterated).
    5. ToBoolean(result)がfalseなら、? IteratorClose(iterated, NormalCompletion(false))を返す。
    6. countercounter + 1に設定する。

27.1.3.3.4 Iterator.prototype.filter ( predicate )

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

  1. objthis valueとする。
  2. objがObjectでないなら、TypeError例外をthrowする。
  3. iteratedIterator Record { [[Iterator]]: obj, [[NextMethod]]: undefined, [[Done]]: false }とする。
  4. IsCallable(predicate)がfalseなら、
    1. errorThrowCompletion(a newly created TypeError object)とする。
    2. IteratorClose(iterated, error)を返す。
  5. iteratedを ? GetIteratorDirect(obj) に設定する。
  6. closureを、iteratedpredicateをcaptureし、呼び出されたときに以下のstepsを実行する、parametersを持たないnew Abstract Closureとする:
    1. counterを0とする。
    2. 繰り返す:
      1. valueを ? IteratorStepValue(iterated) とする。
      2. valuedoneなら、ReturnCompletion(undefined)を返す。
      3. selectedCompletion(Call(predicate, undefined, « value, 𝔽(counter) »))とする。
      4. IfAbruptCloseIterator(selected, iterated).
      5. ToBoolean(selected)がtrueなら、
        1. completionCompletion(Yield(value))とする。
        2. IfAbruptCloseIterator(completion, iterated).
      6. countercounter + 1に設定する。
  7. resultCreateIteratorFromClosure(closure, "Iterator Helper", %IteratorHelperPrototype%, « [[UnderlyingIterators]] »)とする。
  8. result.[[UnderlyingIterators]]を« iterated »に設定する。
  9. resultを返す。

27.1.3.3.5 Iterator.prototype.find ( predicate )

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

  1. objthis valueとする。
  2. objがObjectでないなら、TypeError例外をthrowする。
  3. iteratedIterator Record { [[Iterator]]: obj, [[NextMethod]]: undefined, [[Done]]: false }とする。
  4. IsCallable(predicate)がfalseなら、
    1. errorThrowCompletion(a newly created TypeError object)とする。
    2. IteratorClose(iterated, error)を返す。
  5. iteratedを ? GetIteratorDirect(obj) に設定する。
  6. counterを0とする。
  7. 繰り返す:
    1. valueを ? IteratorStepValue(iterated) とする。
    2. valuedoneなら、undefinedを返す。
    3. resultCompletion(Call(predicate, undefined, « value, 𝔽(counter) »))とする。
    4. IfAbruptCloseIterator(result, iterated).
    5. ToBoolean(result)がtrueなら、? IteratorClose(iterated, NormalCompletion(value))を返す。
    6. countercounter + 1に設定する。

27.1.3.3.6 Iterator.prototype.flatMap ( mapper )

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

  1. objthis valueとする。
  2. objがObjectでないなら、TypeError例外をthrowする。
  3. iteratedIterator Record { [[Iterator]]: obj, [[NextMethod]]: undefined, [[Done]]: false }とする。
  4. IsCallable(mapper)がfalseなら、
    1. errorThrowCompletion(a newly created TypeError object)とする。
    2. IteratorClose(iterated, error)を返す。
  5. iteratedを ? GetIteratorDirect(obj) に設定する。
  6. closureを、iteratedmapperをcaptureし、呼び出されたときに以下のstepsを実行する、parametersを持たないnew Abstract Closureとする:
    1. counterを0とする。
    2. 繰り返す:
      1. valueを ? IteratorStepValue(iterated) とする。
      2. valuedoneなら、ReturnCompletion(undefined)を返す。
      3. mappedCompletion(Call(mapper, undefined, « value, 𝔽(counter) »))とする。
      4. IfAbruptCloseIterator(mapped, iterated).
      5. innerIteratorCompletion(GetIteratorFlattenable(mapped, reject-primitives))とする。
      6. IfAbruptCloseIterator(innerIterator, iterated).
      7. innerAlivetrueとする。
      8. innerAlivetrueである間、繰り返す:
        1. innerValueCompletion(IteratorStepValue(innerIterator))とする。
        2. IfAbruptCloseIterator(innerValue, iterated).
        3. innerValuedoneなら、
          1. innerAlivefalseに設定する。
        4. そうでなければ、
          1. completionCompletion(Yield(innerValue))とする。
          2. completionabrupt completionなら、
            1. backupCompletionCompletion(IteratorClose(innerIterator, completion))とする。
            2. IfAbruptCloseIterator(backupCompletion, iterated).
            3. IteratorClose(iterated, completion)を返す。
      9. countercounter + 1に設定する。
  7. resultCreateIteratorFromClosure(closure, "Iterator Helper", %IteratorHelperPrototype%, « [[UnderlyingIterators]] »)とする。
  8. result.[[UnderlyingIterators]]を« iterated »に設定する。
  9. resultを返す。

27.1.3.3.7 Iterator.prototype.forEach ( procedure )

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

  1. objthis valueとする。
  2. objがObjectでないなら、TypeError例外をthrowする。
  3. iteratedIterator Record { [[Iterator]]: obj, [[NextMethod]]: undefined, [[Done]]: false }とする。
  4. IsCallable(procedure)がfalseなら、
    1. errorThrowCompletion(a newly created TypeError object)とする。
    2. IteratorClose(iterated, error)を返す。
  5. iteratedを ? GetIteratorDirect(obj) に設定する。
  6. counterを0とする。
  7. 繰り返す:
    1. valueを ? IteratorStepValue(iterated) とする。
    2. valuedoneなら、undefinedを返す。
    3. resultCompletion(Call(procedure, undefined, « value, 𝔽(counter) »))とする。
    4. IfAbruptCloseIterator(result, iterated).
    5. countercounter + 1に設定する。

27.1.3.3.8 Iterator.prototype.map ( mapper )

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

  1. objthis valueとする。
  2. objがObjectでないなら、TypeError例外をthrowする。
  3. iteratedIterator Record { [[Iterator]]: obj, [[NextMethod]]: undefined, [[Done]]: false }とする。
  4. IsCallable(mapper)がfalseなら、
    1. errorThrowCompletion(a newly created TypeError object)とする。
    2. IteratorClose(iterated, error)を返す。
  5. iteratedを ? GetIteratorDirect(obj) に設定する。
  6. closureを、iteratedmapperをcaptureし、呼び出されたときに以下のstepsを実行する、parametersを持たないnew Abstract Closureとする:
    1. counterを0とする。
    2. 繰り返す:
      1. valueを ? IteratorStepValue(iterated) とする。
      2. valuedoneなら、ReturnCompletion(undefined)を返す。
      3. mappedCompletion(Call(mapper, undefined, « value, 𝔽(counter) »))とする。
      4. IfAbruptCloseIterator(mapped, iterated).
      5. completionCompletion(Yield(mapped))とする。
      6. IfAbruptCloseIterator(completion, iterated).
      7. countercounter + 1に設定する。
  7. resultCreateIteratorFromClosure(closure, "Iterator Helper", %IteratorHelperPrototype%, « [[UnderlyingIterators]] »)とする。
  8. result.[[UnderlyingIterators]]を« iterated »に設定する。
  9. resultを返す。

27.1.3.3.9 Iterator.prototype.reduce ( reducer [ , initialValue ] )

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

  1. objthis valueとする。
  2. objがObjectでないなら、TypeError例外をthrowする。
  3. iteratedIterator Record { [[Iterator]]: obj, [[NextMethod]]: undefined, [[Done]]: false }とする。
  4. IsCallable(reducer)がfalseなら、
    1. errorThrowCompletion(a newly created TypeError object)とする。
    2. IteratorClose(iterated, error)を返す。
  5. iteratedを ? GetIteratorDirect(obj) に設定する。
  6. initialValueが存在しないなら、
    1. accumulatorを ? IteratorStepValue(iterated) とする。
    2. accumulatordoneなら、TypeError例外をthrowする。
    3. counterを1とする。
  7. そうでなければ、
    1. accumulatorinitialValueとする。
    2. counterを0とする。
  8. 繰り返す:
    1. valueを ? IteratorStepValue(iterated) とする。
    2. valuedoneなら、accumulatorを返す。
    3. resultCompletion(Call(reducer, undefined, « accumulator, value, 𝔽(counter) »))とする。
    4. IfAbruptCloseIterator(result, iterated).
    5. accumulatorresultに設定する。
    6. countercounter + 1に設定する。

27.1.3.3.10 Iterator.prototype.some ( predicate )

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

  1. objthis valueとする。
  2. objがObjectでないなら、TypeError例外をthrowする。
  3. iteratedIterator Record { [[Iterator]]: obj, [[NextMethod]]: undefined, [[Done]]: false }とする。
  4. IsCallable(predicate)がfalseなら、
    1. errorThrowCompletion(a newly created TypeError object)とする。
    2. IteratorClose(iterated, error)を返す。
  5. iteratedを ? GetIteratorDirect(obj) に設定する。
  6. counterを0とする。
  7. 繰り返す:
    1. valueを ? IteratorStepValue(iterated) とする。
    2. valuedoneなら、falseを返す。
    3. resultCompletion(Call(predicate, undefined, « value, 𝔽(counter) »))とする。
    4. IfAbruptCloseIterator(result, iterated).
    5. ToBoolean(result)がtrueなら、? IteratorClose(iterated, NormalCompletion(true))を返す。
    6. countercounter + 1に設定する。

27.1.3.3.11 Iterator.prototype.take ( limit )

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

  1. objthis valueとする。
  2. objがObjectでないなら、TypeError例外をthrowする。
  3. iteratedIterator Record { [[Iterator]]: obj, [[NextMethod]]: undefined, [[Done]]: false }とする。
  4. numberLimitCompletion(ToNumber(limit))とする。
  5. IfAbruptCloseIterator(numberLimit, iterated).
  6. numberLimitNaNなら、
    1. errorThrowCompletion(a newly created RangeError object)とする。
    2. IteratorClose(iterated, error)を返す。
  7. intLimitを ! ToIntegerOrInfinity(numberLimit) とする。
  8. intLimit < 0なら、
    1. errorThrowCompletion(a newly created RangeError object)とする。
    2. IteratorClose(iterated, error)を返す。
  9. iteratedを ? GetIteratorDirect(obj) に設定する。
  10. closureを、iteratedintLimitをcaptureし、呼び出されたときに以下のstepsを実行する、parametersを持たないnew Abstract Closureとする:
    1. remainingintLimitとする。
    2. 繰り返す:
      1. remaining = 0なら、
        1. IteratorClose(iterated, ReturnCompletion(undefined))を返す。
      2. remaining ≠ +∞なら、
        1. remainingremaining - 1に設定する。
      3. valueを ? IteratorStepValue(iterated) とする。
      4. valuedoneなら、ReturnCompletion(undefined)を返す。
      5. completionCompletion(Yield(value))とする。
      6. IfAbruptCloseIterator(completion, iterated).
  11. resultCreateIteratorFromClosure(closure, "Iterator Helper", %IteratorHelperPrototype%, « [[UnderlyingIterators]] »)とする。
  12. result.[[UnderlyingIterators]]を« iterated »に設定する。
  13. resultを返す。

27.1.3.3.12 Iterator.prototype.toArray ( )

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

  1. objthis valueとする。
  2. objがObjectでないなら、TypeError例外をthrowする。
  3. iteratedを ? GetIteratorDirect(obj) とする。
  4. itemsをnew empty Listとする。
  5. 繰り返す:
    1. valueを ? IteratorStepValue(iterated) とする。
    2. valuedoneなら、CreateArrayFromList(items)を返す。
    3. valueitemsにappendする。

27.1.3.3.13 Iterator.prototype [ %Symbol.dispose% ] ( )

このメソッドは、呼び出されたときに次のステップを実行する:

  1. objthis 値とする。
  2. return を ? GetMethod(obj, "return") とする。
  3. returnundefined でない場合、then
    1. Call(return, obj) を実行する。
  4. undefined を返す。

このメソッドの "name" プロパティの値は "[Symbol.dispose]" である。

27.1.3.3.14 Iterator.prototype [ %Symbol.iterator% ] ( )

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

  1. this valueを返す。

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

27.1.3.3.15 Iterator.prototype [ %Symbol.toStringTag% ]

Iterator.prototype[%Symbol.toStringTag%]は、attributes { [[Enumerable]]: false, [[Configurable]]: true }を持つaccessor propertyである。[[Get]]および[[Set]] attributesは以下のようにdefinedされる:

27.1.3.3.15.1 get Iterator.prototype [ %Symbol.toStringTag% ]

[[Get]] attributeのvalueは、argumentsを必要としないbuilt-in functionである。呼び出されたときに以下のstepsを実行する:

  1. "Iterator"を返す。

27.1.3.3.15.2 set Iterator.prototype [ %Symbol.toStringTag% ]

[[Set]] attributeのvalueは、argument vを取るbuilt-in functionである。呼び出されたときに以下のstepsを実行する:

  1. SetterThatIgnoresPrototypeProperties(this value, %Iterator.prototype%, %Symbol.toStringTag%, v)を実行する。
  2. undefinedを返す。
Note

ほとんどのbuilt-in prototypes上の%Symbol.toStringTag% propertyとは異なり、web-compatibilityの理由により、このpropertyはaccessorでなければならない。

27.1.3.4 IteratorsのためのAbstract Operations

27.1.3.4.1 IteratorZip ( iters, mode, padding, finishResults )

The abstract operation IteratorZip takes arguments iters (a List of Iterator Records), mode ("shortest", "longest", or "strict"), padding (a List of ECMAScript language values), and finishResults (an Abstract Closure that takes a List of ECMAScript language values and returns an ECMAScript language value) and returns a Generator. It performs the following steps when called:

  1. iterCountitersのelements数とする。
  2. openItersitersのcopyとする。
  3. closureを、itersiterCountopenItersmodepadding、およびfinishResultsをcaptureし、呼び出されたときに以下のstepsを実行する、parametersを持たないnew Abstract Closureとする:
    1. iterCount = 0なら、ReturnCompletion(undefined)を返す。
    2. 繰り返す:
      1. resultsをnew empty Listとする。
      2. Assert: openItersはemptyでない。
      3. 0 ≤ i < iterCountである各integer iについて、昇順で、
        1. iteriters[i]とする。
        2. iternullなら、
          1. Assert: mode"longest"である。
          2. resultpadding[i]とする。
        3. そうでなければ、
          1. resultCompletion(IteratorStepValue(iter))とする。
          2. resultabrupt completionなら、
            1. openItersからiterをremoveする。
            2. IteratorCloseAll(openIters, result)を返す。
          3. resultを ! result に設定する。
          4. resultdoneなら、
            1. openItersからiterをremoveする。
            2. mode"shortest"なら、
              1. IteratorCloseAll(openIters, ReturnCompletion(undefined))を返す。
            3. そうでなく、mode"strict"なら、
              1. i ≠ 0なら、
                1. IteratorCloseAll(openIters, ThrowCompletion(a newly created TypeError object))を返す。
              2. 1 ≤ k < iterCountである各integer kについて、昇順で、
                1. Assert: iters[k]はnullでない。
                2. openCompletion(IteratorStep(iters[k]))とする。
                3. openabrupt completionなら、
                  1. openItersからiters[k]をremoveする。
                  2. IteratorCloseAll(openIters, open)を返す。
                4. openを ! open に設定する。
                5. opendoneなら、
                  1. openItersからiters[k]をremoveする。
                6. そうでなければ、
                  1. IteratorCloseAll(openIters, ThrowCompletion(a newly created TypeError object))を返す。
              3. ReturnCompletion(undefined)を返す。
            4. そうでなければ、
              1. Assert: mode"longest"である。
              2. openItersがemptyなら、ReturnCompletion(undefined)を返す。
              3. iters[i]をnullに設定する。
              4. resultpadding[i]に設定する。
        4. resultresultsにappendする。
      4. resultsfinishResults(results)に設定する。
      5. completionCompletion(Yield(results))とする。
      6. IfAbruptCloseIterators(completion, openIters).
  4. genCreateIteratorFromClosure(closure, "Iterator Helper", %IteratorHelperPrototype%, « [[UnderlyingIterators]] »)とする。
  5. gen.[[UnderlyingIterators]]openItersに設定する。
  6. genを返す。

27.1.4 %AsyncIteratorPrototype%オブジェクト

%AsyncIteratorPrototype% objectは:

Note

このspecificationでdefinedされる、async iterator interfaceを実装するすべてのobjectsも%AsyncIteratorPrototype%からinheritする。ECMAScript codeも、%AsyncIteratorPrototype%からinheritするobjectsをdefineしてよい。%AsyncIteratorPrototype% objectは、すべてのasync iterator objectsに適用可能なadditional methodsを追加できる場所を提供する。

27.1.4.1 %AsyncIteratorPrototype% [ %Symbol.asyncDispose% ] ( )

このメソッドは、呼び出されたときに次のステップを実行する:

  1. objthis 値とする。
  2. promiseCapability を ! NewPromiseCapability(%Promise%) とする。
  3. returnCompletion(GetMethod(obj, "return"))) とする。
  4. IfAbruptRejectPromise(return, promiseCapability).
  5. returnundefined である場合、then
    1. Call(promiseCapability.[[Resolve]], undefined, « undefined ») を実行する。
  6. Else,
    1. resultCompletion(Call(return, obj, « »)) とする。
    2. IfAbruptRejectPromise(result, promiseCapability).
    3. resultWrapperCompletion(PromiseResolve(%Promise%, result)) とする。
    4. IfAbruptRejectPromise(resultWrapper, promiseCapability).
    5. unwrap を、何もキャプチャせず、呼び出されたときに次のステップを実行する、パラメータを持たない新しい Abstract Closure とする:
      1. undefined を返す。
    6. onFulfilledCreateBuiltinFunction(unwrap, 1, "", « ») とする。
    7. PerformPromiseThen(resultWrapper, onFulfilled, undefined, promiseCapability) を実行する。
  7. promiseCapability.[[Promise]] を返す。

このメソッドの "name" プロパティの値は "[Symbol.asyncDispose]" である。

27.1.4.2 %AsyncIteratorPrototype% [ %Symbol.asyncIterator% ] ( )

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

  1. this valueを返す。

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

27.1.5 Async-from-Sync Iteratorオブジェクト

Async-from-Sync Iterator objectは、特定のsynchronous iteratorをadaptするasync iteratorである。Async-from-Sync Iterator objectsは、ECMAScript codeから直接accessされることは決してない。Async-from-Sync Iterator objectsにはnamed constructorは存在しない。代わりに、Async-from-Sync Iterator objectsは必要に応じてCreateAsyncFromSyncIterator abstract operationによって作成される。

27.1.5.1 CreateAsyncFromSyncIterator ( syncIteratorRecord )

The abstract operation CreateAsyncFromSyncIterator takes argument syncIteratorRecord (an Iterator Record) and returns an Iterator Record. これはsynchronous Iterator Recordからasync Iterator Recordをcreateするために使用される。 It performs the following steps when called:

  1. asyncIteratorOrdinaryObjectCreate(%AsyncFromSyncIteratorPrototype%, « [[SyncIteratorRecord]] »)とする。
  2. asyncIterator.[[SyncIteratorRecord]]syncIteratorRecordに設定する。
  3. nextMethodを ! Get(asyncIterator, "next") とする。
  4. iteratorRecordIterator Record { [[Iterator]]: asyncIterator, [[NextMethod]]: nextMethod, [[Done]]: false }とする。
  5. iteratorRecordを返す。

27.1.5.2 %AsyncFromSyncIteratorPrototype%オブジェクト

%AsyncFromSyncIteratorPrototype% objectは:

27.1.5.2.1 %AsyncFromSyncIteratorPrototype%.next ( [ value ] )

  1. objthis valueとする。
  2. Assert: obj[[SyncIteratorRecord]] internal slotを持つObjectである。
  3. promiseCapabilityを ! NewPromiseCapability(%Promise%) とする。
  4. syncIteratorRecordobj.[[SyncIteratorRecord]]とする。
  5. valueが存在するなら、
    1. resultCompletion(IteratorNext(syncIteratorRecord, value))とする。
  6. そうでなければ、
    1. resultCompletion(IteratorNext(syncIteratorRecord))とする。
  7. IfAbruptRejectPromise(result, promiseCapability).
  8. AsyncFromSyncIteratorContinuation(result, promiseCapability, syncIteratorRecord, true)を返す。

27.1.5.2.2 %AsyncFromSyncIteratorPrototype%.return ( [ value ] )

  1. objthis valueとする。
  2. Assert: obj[[SyncIteratorRecord]] internal slotを持つObjectである。
  3. promiseCapabilityを ! NewPromiseCapability(%Promise%) とする。
  4. syncIteratorRecordobj.[[SyncIteratorRecord]]とする。
  5. syncIteratorsyncIteratorRecord.[[Iterator]]とする。
  6. returnCompletion(GetMethod(syncIterator, "return"))とする。
  7. IfAbruptRejectPromise(return, promiseCapability).
  8. returnundefinedなら、
    1. iteratorResultCreateIteratorResultObject(value, true)とする。
    2. Call(promiseCapability.[[Resolve]], undefined, « iteratorResult »)を実行する。
    3. promiseCapability.[[Promise]]を返す。
  9. valueが存在するなら、
    1. resultCompletion(Call(return, syncIterator, « value »))とする。
  10. そうでなければ、
    1. resultCompletion(Call(return, syncIterator))とする。
  11. IfAbruptRejectPromise(result, promiseCapability).
  12. resultがObjectでないなら、
    1. Call(promiseCapability.[[Reject]], undefined, « a newly created TypeError object »)を実行する。
    2. promiseCapability.[[Promise]]を返す。
  13. AsyncFromSyncIteratorContinuation(result, promiseCapability, syncIteratorRecord, false)を返す。

27.1.5.2.3 %AsyncFromSyncIteratorPrototype%.throw ( [ value ] )

Note
このspecificationでは、valueは常に提供されるが、%AsyncFromSyncIteratorPrototype%.return ( [ value ] )との一貫性のためにoptionalのままにされている。
  1. objthis valueとする。
  2. Assert: obj[[SyncIteratorRecord]] internal slotを持つObjectである。
  3. promiseCapabilityを ! NewPromiseCapability(%Promise%) とする。
  4. syncIteratorRecordobj.[[SyncIteratorRecord]]とする。
  5. syncIteratorsyncIteratorRecord.[[Iterator]]とする。
  6. throwCompletion(GetMethod(syncIterator, "throw"))とする。
  7. IfAbruptRejectPromise(throw, promiseCapability).
  8. throwundefinedなら、
    1. NOTE: syncIteratorthrow methodがない場合、capabilityをrejectする前にcleanupの機会を与えるためにそれをcloseする。
    2. closeCompletionNormalCompletion(empty)とする。
    3. resultCompletion(IteratorClose(syncIteratorRecord, closeCompletion))とする。
    4. IfAbruptRejectPromise(result, promiseCapability).
    5. NOTE: 次のstepは、protocol violationがあったことを示すためにTypeErrorをthrowする:syncIteratorthrow methodを持たない。
    6. NOTE: syncIteratorのclosingがthrowしない場合、そのoperationのresultは、それがrejected promiseをyieldする場合であっても無視される。
    7. Call(promiseCapability.[[Reject]], undefined, « a newly created TypeError object »)を実行する。
    8. promiseCapability.[[Promise]]を返す。
  9. valueが存在するなら、
    1. resultCompletion(Call(throw, syncIterator, « value »))とする。
  10. そうでなければ、
    1. resultCompletion(Call(throw, syncIterator))とする。
  11. IfAbruptRejectPromise(result, promiseCapability).
  12. resultがObjectでないなら、
    1. Call(promiseCapability.[[Reject]], undefined, « a newly created TypeError object »)を実行する。
    2. promiseCapability.[[Promise]]を返す。
  13. AsyncFromSyncIteratorContinuation(result, promiseCapability, syncIteratorRecord, true)を返す。

27.1.5.3 Async-from-Sync Iteratorインスタンスのプロパティ

Async-from-Sync Iterator instancesは、%AsyncFromSyncIteratorPrototype% intrinsic objectからpropertiesをinheritするordinary objectsである。Async-from-Sync Iterator instancesは、最初にTable 86に列挙されるinternal slotsで作成される。

Table 86: Internal Slots of Async-from-Sync Iterator Instances
Internal Slot Type Description
[[SyncIteratorRecord]] Iterator Record adaptされているoriginal synchronous iteratorを表す。

27.1.5.4 AsyncFromSyncIteratorContinuation ( result, promiseCapability, syncIteratorRecord, closeOnRejection )

The abstract operation AsyncFromSyncIteratorContinuation takes arguments result (an Object), promiseCapability (a PromiseCapability Record for an intrinsic %Promise%), syncIteratorRecord (an Iterator Record), and closeOnRejection (a Boolean) and returns a Promise. It performs the following steps when called:

  1. NOTE: promiseCapabilityはintrinsic %Promise%からderivedされるため、下記のIfAbruptRejectPromiseの使用によって必要となるpromiseCapability.[[Reject]]へのcallsは、throwしないことがguaranteedされる。
  2. doneCompletion(IteratorComplete(result))とする。
  3. IfAbruptRejectPromise(done, promiseCapability).
  4. valueCompletion(IteratorValue(result))とする。
  5. IfAbruptRejectPromise(value, promiseCapability).
  6. valueWrapperCompletion(PromiseResolve(%Promise%, value))とする。
  7. valueWrapperabrupt completionで、donefalseで、closeOnRejectiontrueなら、
    1. valueWrapperCompletion(IteratorClose(syncIteratorRecord, valueWrapper))に設定する。
  8. IfAbruptRejectPromise(valueWrapper, promiseCapability).
  9. unwrapを、parameters (v)を持ち、doneをcaptureし、呼び出されたときに以下のstepsを実行するnew Abstract Closureとする:
    1. CreateIteratorResultObject(v, done)を返す。
  10. onFulfilledCreateBuiltinFunction(unwrap, 1, "", « »)とする。
  11. NOTE: onFulfilledは、IteratorResult object"value" propertyを処理するとき、そのvalueがpromiseである場合にそれを待ち、resultを新しい“unwrapped” IteratorResult objectに再packageするために使用される。
  12. donetrueまたはcloseOnRejectionfalseなら、
    1. onRejectedundefinedとする。
  13. そうでなければ、
    1. closeIteratorを、parameters (error)を持ち、syncIteratorRecordをcaptureし、呼び出されたときに以下のstepsを実行するnew Abstract Closureとする:
      1. IteratorClose(syncIteratorRecord, ThrowCompletion(error))を返す。
    2. onRejectedCreateBuiltinFunction(closeIterator, 1, "", « »)とする。
    3. NOTE: onRejectedは、IteratorがyieldするIteratorResult object"value" propertyがrejected promiseである場合に、そのIteratorをcloseするために使用される。
  14. PerformPromiseThen(valueWrapper, onFulfilled, onRejected, promiseCapability)を実行する。
  15. promiseCapability.[[Promise]]を返す。

27.2 リソース管理

27.2.1 共通リソース管理インターフェイス

27.2.1.1 Disposable インターフェイス

Disposable インターフェイスは、Table 87 に記述されるプロパティを含む:

Table 87: Disposable インターフェイスの必須プロパティ
プロパティ 要件
%Symbol.dispose% 関数オブジェクト

このメソッドを呼び出すことにより、呼び出し元がこのオブジェクトを引き続き使用する意図がないことを Disposable オブジェクトに通知する。このメソッドは、ファイルシステムハンドル、ストリーム、ホストオブジェクトなどを含むがこれらに限定されないリソースの明示的なクリーンアップを実行するために必要なロジックを実行するべきである。このメソッドから例外が投げられる場合、それは通常、そのリソースを明示的に解放できなかったことを意味する。

同じオブジェクトに対してこのメソッドを複数回呼び出す場合、すでに破棄済みのリソースに対してクリーンアップロジックを繰り返すことを避けるべきであり、最初の呼び出しで例外が投げられた場合であっても、例外を投げるべきではない。ただし、この要件は強制されない。

Disposable オブジェクトを using 宣言または await using 宣言とともに使用する場合、そのリソースは、その宣言を直接含む Block または Module が評価されたときに自動的に破棄される。

27.2.1.2 AsyncDisposable インターフェイス

AsyncDisposable インターフェイスは、Table 88 に記述されるプロパティを含む:

Table 88: AsyncDisposable インターフェイスの必須プロパティ
プロパティ 要件
%Symbol.asyncDispose% promise を返す関数オブジェクト

このメソッドを呼び出すことにより、呼び出し元がこのオブジェクトを引き続き使用する意図がないことを AsyncDisposable オブジェクトに通知する。このメソッドは、ファイルシステムハンドル、ストリーム、ホストオブジェクトなどを含むがこれらに限定されないリソースの明示的なクリーンアップを実行するために必要なロジックを実行するべきである。このメソッドが返す promise が reject される場合、それは通常、そのリソースを明示的に解放できなかったことを意味する。AsyncDisposable オブジェクトは、結果の Promise が fulfilled になるまで「破棄済み」とはみなされない。

同じオブジェクトに対してこのメソッドを複数回呼び出す場合、すでに破棄済みのリソースに対してクリーンアップロジックを繰り返すことを避けるべきであり、最初の呼び出しで例外が投げられた場合または rejected promise が返された場合であっても、例外を投げたり rejected promise を返したりするべきではない。ただし、この要件は強制されない。

AsyncDisposable オブジェクトを await using 宣言とともに使用する場合、そのリソースは、その宣言を直接含む Block または Module が評価されたときに自動的に破棄される。

27.3 DisposableStack オブジェクト

DisposableStack は、まとめて破棄されるべき1つ以上のリソースを格納するために使用できるオブジェクトである。

任意の DisposableStack オブジェクトは、互いに排他的な2つの状態、すなわち disposed または pending のいずれかにある。disposable stack d は、d.dispose()d.move()d に対して呼び出されていない場合に限り pending である。

27.3.1 DisposableStack コンストラクタ

DisposableStack コンストラクタは次のとおりである:

  • %DisposableStack% である。
  • グローバルオブジェクトの "DisposableStack" プロパティの初期値である。
  • コンストラクタとして呼び出されたとき、新しい DisposableStack を作成して初期化する。
  • 関数として呼び出されることは意図されておらず、そのように呼び出された場合は例外を投げる。
  • クラス定義の extends 節の値として使用できる。指定された DisposableStack の振る舞いを継承しようとするサブクラスコンストラクタは、DisposableStack.prototype の組込みメソッドをサポートするために必要な内部状態を持つサブクラスインスタンスを作成して初期化するために、DisposableStack コンストラクタへの super 呼び出しを含めなければならない。

27.3.1.1 DisposableStack ( )

この関数は、呼び出されたときに次のステップを実行する:

  1. NewTarget が undefined である場合、TypeError 例外を投げる。
  2. disposableStack を ? OrdinaryCreateFromConstructor(NewTarget, "%DisposableStack.prototype%", « [[DisposableState]], [[DisposableResourceStack]] ») とする。
  3. disposableStack.[[DisposableState]]pending に設定する。
  4. disposableStack.[[DisposableResourceStack]] を新しい空の List に設定する。
  5. disposableStack を返す。

27.3.2 DisposableStack コンストラクタのプロパティ

DisposableStack コンストラクタは次のとおりである:

  • 値が %Function.prototype% である [[Prototype]] 内部スロットを持つ。
  • 次のプロパティを持つ:

27.3.2.1 DisposableStack.prototype

DisposableStack.prototype の初期値は DisposableStack プロトタイプオブジェクトである。

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

27.3.3 DisposableStack プロトタイプオブジェクトのプロパティ

DisposableStack プロトタイプオブジェクトは次のとおりである:

  • %DisposableStack.prototype% である。
  • 値が %Object.prototype% である [[Prototype]] 内部スロットを持つ。
  • 通常のオブジェクトである。
  • [[DisposableState]] 内部スロットも、DisposableStack インスタンスのその他の内部スロットも持たない。

27.3.3.1 DisposableStack.prototype.adopt ( value, onDispose )

このメソッドは、呼び出されたときに次のステップを実行する:

  1. disposableStackthis 値とする。
  2. RequireInternalSlot(disposableStack, [[DisposableState]]) を実行する。
  3. disposableStack.[[DisposableState]]disposed である場合、ReferenceError 例外を投げる。
  4. IsCallable(onDispose) が false である場合、TypeError 例外を投げる。
  5. closure を、valueonDispose をキャプチャし、呼び出されたときに次のステップを実行する、パラメータを持たない新しい Abstract Closure とする:
    1. Return ? Call(onDispose, undefined, « value »).
  6. funcCreateBuiltinFunction(closure, 0, "", « ») とする。
  7. AddDisposableResource(disposableStack.[[DisposableResourceStack]], undefined, sync-dispose, func) を実行する。
  8. value を返す。

27.3.3.2 DisposableStack.prototype.constructor

DisposableStack.prototype.constructor の初期値は %DisposableStack% である。

27.3.3.3 DisposableStack.prototype.defer ( onDispose )

このメソッドは、呼び出されたときに次のステップを実行する:

  1. disposableStackthis 値とする。
  2. RequireInternalSlot(disposableStack, [[DisposableState]]) を実行する。
  3. disposableStack.[[DisposableState]]disposed である場合、ReferenceError 例外を投げる。
  4. IsCallable(onDispose) が false である場合、TypeError 例外を投げる。
  5. AddDisposableResource(disposableStack.[[DisposableResourceStack]], undefined, sync-dispose, onDispose) を実行する。
  6. undefined を返す。

27.3.3.4 DisposableStack.prototype.dispose ( )

このメソッドは、呼び出されたときに次のステップを実行する:

  1. disposableStackthis 値とする。
  2. RequireInternalSlot(disposableStack, [[DisposableState]]) を実行する。
  3. disposableStack.[[DisposableState]]disposed である場合、undefined を返す。
  4. disposableStack.[[DisposableState]]disposed に設定する。
  5. Return ? DisposeResources(disposableStack.[[DisposableResourceStack]], NormalCompletion(undefined)).

27.3.3.5 get DisposableStack.prototype.disposed

DisposableStack.prototype.disposed は、set アクセサ関数が undefined であるアクセサプロパティである。その get アクセサ関数は、呼び出されたときに次のステップを実行する:

  1. disposableStackthis 値とする。
  2. RequireInternalSlot(disposableStack, [[DisposableState]]) を実行する。
  3. disposableStack.[[DisposableState]]disposed である場合、true を返す。
  4. false を返す。

27.3.3.6 DisposableStack.prototype.move ( )

このメソッドは、呼び出されたときに次のステップを実行する:

  1. disposableStackthis 値とする。
  2. RequireInternalSlot(disposableStack, [[DisposableState]]) を実行する。
  3. disposableStack.[[DisposableState]]disposed である場合、ReferenceError 例外を投げる。
  4. newDisposableStack を ? OrdinaryCreateFromConstructor(%DisposableStack%, "%DisposableStack.prototype%", « [[DisposableState]], [[DisposableResourceStack]] ») とする。
  5. newDisposableStack.[[DisposableState]]pending に設定する。
  6. newDisposableStack.[[DisposableResourceStack]]disposableStack.[[DisposableResourceStack]] に設定する。
  7. disposableStack.[[DisposableResourceStack]] を新しい空の List に設定する。
  8. disposableStack.[[DisposableState]]disposed に設定する。
  9. newDisposableStack を返す。

27.3.3.7 DisposableStack.prototype.use ( value )

このメソッドは、呼び出されたときに次のステップを実行する:

  1. disposableStackthis 値とする。
  2. RequireInternalSlot(disposableStack, [[DisposableState]]) を実行する。
  3. disposableStack.[[DisposableState]]disposed である場合、ReferenceError 例外を投げる。
  4. AddDisposableResource(disposableStack.[[DisposableResourceStack]], value, sync-dispose) を実行する。
  5. value を返す。

27.3.3.8 DisposableStack.prototype [ %Symbol.dispose% ] ( )

%Symbol.dispose% プロパティの初期値は、27.3.3.4 で定義される %DisposableStack.prototype.dispose% である。

27.3.3.9 DisposableStack.prototype [ %Symbol.toStringTag% ]

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

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

27.3.4 DisposableStack インスタンスのプロパティ

DisposableStack インスタンスは、DisposableStack プロトタイプオブジェクト(組込み %DisposableStack.prototype%)からプロパティを継承する通常のオブジェクトである。DisposableStack インスタンスは、最初に Table 89 に記述される内部スロットを持つように作成される。

Table 89: DisposableStack インスタンスの内部スロット
内部スロット 説明
[[DisposableState]] pending または disposed disposable stack が自身の %Symbol.dispose% メソッドへの着信呼び出しにどのように反応するかを制御する。
[[DisposableResourceStack]] DisposableResource レコードList disposable stack が破棄されるときに破棄されるリソース。リソースは初期化された順に追加され、逆順に破棄される。

27.4 AsyncDisposableStack オブジェクト

AsyncDisposableStack は、非同期にまとめて破棄されるべき1つ以上のリソースを格納するために使用できるオブジェクトである。

任意の AsyncDisposableStack オブジェクトは、互いに排他的な2つの状態、すなわち disposed または pending のいずれかにある。async-disposable stack d は、d.disposeAsync()d.move()d に対して呼び出されていない場合に限り pending である。

27.4.1 AsyncDisposableStack コンストラクタ

AsyncDisposableStack コンストラクタは次のとおりである:

  • %AsyncDisposableStack% である。
  • グローバルオブジェクトの "AsyncDisposableStack" プロパティの初期値である。
  • コンストラクタとして呼び出されたとき、新しい AsyncDisposableStack を作成して初期化する。
  • 関数として呼び出されることは意図されておらず、そのように呼び出された場合は例外を投げる。
  • クラス定義の extends 節の値として使用できる。指定された AsyncDisposableStack の振る舞いを継承しようとするサブクラスコンストラクタは、AsyncDisposableStack.prototype の組込みメソッドをサポートするために必要な内部状態を持つサブクラスインスタンスを作成して初期化するために、AsyncDisposableStack コンストラクタへの super 呼び出しを含めなければならない。

27.4.1.1 AsyncDisposableStack ( )

この関数は、呼び出されたときに次のステップを実行する:

  1. NewTarget が undefined である場合、TypeError 例外を投げる。
  2. asyncDisposableStack を ? OrdinaryCreateFromConstructor(NewTarget, "%AsyncDisposableStack.prototype%", « [[AsyncDisposableState]], [[DisposableResourceStack]] ») とする。
  3. asyncDisposableStack.[[AsyncDisposableState]]pending に設定する。
  4. asyncDisposableStack.[[DisposableResourceStack]] を新しい空の List に設定する。
  5. asyncDisposableStack を返す。

27.4.2 AsyncDisposableStack コンストラクタのプロパティ

AsyncDisposableStack コンストラクタは次のとおりである:

  • 値が %Function.prototype% である [[Prototype]] 内部スロットを持つ。
  • 次のプロパティを持つ:

27.4.2.1 AsyncDisposableStack.prototype

AsyncDisposableStack.prototype の初期値は AsyncDisposableStack プロトタイプオブジェクトである。

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

27.4.3 AsyncDisposableStack プロトタイプオブジェクトのプロパティ

AsyncDisposableStack プロトタイプオブジェクトは次のとおりである:

  • %AsyncDisposableStack.prototype% である。
  • 値が %Object.prototype% である [[Prototype]] 内部スロットを持つ。
  • 通常のオブジェクトである。
  • [[AsyncDisposableState]] 内部スロットも、AsyncDisposableStack インスタンスのその他の内部スロットも持たない。

27.4.3.1 AsyncDisposableStack.prototype.adopt ( value, onDisposeAsync )

このメソッドは、呼び出されたときに次のステップを実行する:

  1. asyncDisposableStackthis 値とする。
  2. RequireInternalSlot(asyncDisposableStack, [[AsyncDisposableState]]) を実行する。
  3. asyncDisposableStack.[[AsyncDisposableState]]disposed である場合、ReferenceError 例外を投げる。
  4. IsCallable(onDisposeAsync) が false である場合、TypeError 例外を投げる。
  5. closure を、valueonDisposeAsync をキャプチャし、呼び出されたときに次のステップを実行する、パラメータを持たない新しい Abstract Closure とする:
    1. Return ? Call(onDisposeAsync, undefined, « value »).
  6. funcCreateBuiltinFunction(closure, 0, "", « ») とする。
  7. AddDisposableResource(asyncDisposableStack.[[DisposableResourceStack]], undefined, async-dispose, func) を実行する。
  8. value を返す。

27.4.3.2 AsyncDisposableStack.prototype.constructor

AsyncDisposableStack.prototype.constructor の初期値は %AsyncDisposableStack% である。

27.4.3.3 AsyncDisposableStack.prototype.defer ( onDisposeAsync )

このメソッドは、呼び出されたときに次のステップを実行する:

  1. asyncDisposableStackthis 値とする。
  2. RequireInternalSlot(asyncDisposableStack, [[AsyncDisposableState]]) を実行する。
  3. asyncDisposableStack.[[AsyncDisposableState]]disposed である場合、ReferenceError 例外を投げる。
  4. IsCallable(onDisposeAsync) が false である場合、TypeError 例外を投げる。
  5. AddDisposableResource(asyncDisposableStack.[[DisposableResourceStack]], undefined, async-dispose, onDisposeAsync) を実行する。
  6. undefined を返す。

27.4.3.4 AsyncDisposableStack.prototype.disposeAsync ( )

この async メソッドは、呼び出されたときに次のステップを実行する:

  1. asyncDisposableStackthis 値とする。
  2. RequireInternalSlot(asyncDisposableStack, [[AsyncDisposableState]]) を実行する。
  3. asyncDisposableStack.[[AsyncDisposableState]]disposed である場合、undefined を返す。
  4. asyncDisposableStack.[[AsyncDisposableState]]disposed に設定する。
  5. Return ? DisposeResources(asyncDisposableStack.[[DisposableResourceStack]], NormalCompletion(undefined)).

27.4.3.5 get AsyncDisposableStack.prototype.disposed

AsyncDisposableStack.prototype.disposed は、set アクセサ関数が undefined であるアクセサプロパティである。その get アクセサ関数は、呼び出されたときに次のステップを実行する:

  1. asyncDisposableStackthis 値とする。
  2. RequireInternalSlot(asyncDisposableStack, [[AsyncDisposableState]]) を実行する。
  3. asyncDisposableStack.[[AsyncDisposableState]]disposed である場合、true を返す。
  4. false を返す。

27.4.3.6 AsyncDisposableStack.prototype.move ( )

このメソッドは、呼び出されたときに次のステップを実行する:

  1. asyncDisposableStackthis 値とする。
  2. RequireInternalSlot(asyncDisposableStack, [[AsyncDisposableState]]) を実行する。
  3. asyncDisposableStack.[[AsyncDisposableState]]disposed である場合、ReferenceError 例外を投げる。
  4. newAsyncDisposableStack を ? OrdinaryCreateFromConstructor(%AsyncDisposableStack%, "%AsyncDisposableStack.prototype%", « [[AsyncDisposableState]], [[DisposableResourceStack]] ») とする。
  5. newAsyncDisposableStack.[[AsyncDisposableState]]pending に設定する。
  6. newAsyncDisposableStack.[[DisposableResourceStack]]asyncDisposableStack.[[DisposableResourceStack]] に設定する。
  7. asyncDisposableStack.[[DisposableResourceStack]] を新しい空の List に設定する。
  8. asyncDisposableStack.[[AsyncDisposableState]]disposed に設定する。
  9. newAsyncDisposableStack を返す。

27.4.3.7 AsyncDisposableStack.prototype.use ( value )

このメソッドは、呼び出されたときに次のステップを実行する:

  1. asyncDisposableStackthis 値とする。
  2. RequireInternalSlot(asyncDisposableStack, [[AsyncDisposableState]]) を実行する。
  3. asyncDisposableStack.[[AsyncDisposableState]]disposed である場合、ReferenceError 例外を投げる。
  4. AddDisposableResource(asyncDisposableStack.[[DisposableResourceStack]], value, async-dispose) を実行する。
  5. value を返す。

27.4.3.8 AsyncDisposableStack.prototype [ %Symbol.asyncDispose% ] ( )

%Symbol.asyncDispose% プロパティの初期値は、27.4.3.4 で定義される %AsyncDisposableStack.prototype.disposeAsync% である。

27.4.3.9 AsyncDisposableStack.prototype [ %Symbol.toStringTag% ]

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

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

27.4.4 AsyncDisposableStack インスタンスのプロパティ

AsyncDisposableStack インスタンスは、AsyncDisposableStack プロトタイプオブジェクト(組込み %AsyncDisposableStack.prototype%)からプロパティを継承する通常のオブジェクトである。AsyncDisposableStack インスタンスは、最初に Table 90 に記述される内部スロットを持つように作成される。

Table 90: AsyncDisposableStack インスタンスの内部スロット
内部スロット 説明
[[AsyncDisposableState]] pending または disposed disposable stack が自身の %Symbol.asyncDispose% メソッドへの着信呼び出しにどのように反応するかを制御する。
[[DisposableResourceStack]] DisposableResource レコードList disposable stack が破棄されるときに破棄されるリソース。リソースは初期化された順に追加され、逆順に破棄される。

27.5 Promiseオブジェクト

Promiseは、遅延された(かつ場合によっては非同期の)計算の最終的な結果のplaceholderとして使用されるobjectである。

任意のPromiseは、互いに排他的な3つのstate、すなわちfulfilledrejected、およびpendingのいずれかにある:

  • promise pは、p.then(f, r)がfunction fをcallするJobをただちにenqueueするならfulfilledである。
  • promise pは、p.then(f, r)がfunction rをcallするJobをただちにenqueueするならrejectedである。
  • promiseは、fulfilledでもrejectedでもないならpendingである。

promiseは、pendingでない場合、すなわちfulfilledまたはrejectedのいずれかである場合、settledであるという。

promiseは、settledであるか、または別のpromiseのstateと一致するように“locked in”されているなら、resolvedである。resolved promiseをresolveまたはrejectしようとしても効果はない。promiseは、resolvedでないならunresolvedである。unresolved promiseは常にpending stateにある。resolved promiseはpending、fulfilled、またはrejectedでありうる。

27.5.1 Promise Abstract Operations

27.5.1.1 PromiseCapability Records

PromiseCapability Recordは、Promiseまたはpromise-like objectを、そのpromiseをresolveまたはrejectできるfunctionsとともにencapsulateするために使用されるRecord valueである。PromiseCapability Recordsは、NewPromiseCapability abstract operationによって生成される。

PromiseCapability Recordsは、Table 91に列挙されるfieldsを持つ。

Table 91: PromiseCapability Record Fields
Field Name Value Meaning
[[Promise]] Object promiseとして使用可能なobject。
[[Resolve]] function object 与えられたpromiseをresolveするために使用されるfunction。
[[Reject]] function object 与えられたpromiseをrejectするために使用されるfunction。

27.5.1.1.1 IfAbruptRejectPromise ( value, capability )

IfAbruptRejectPromiseは、PromiseCapability Recordを使用するalgorithm stepsのsequenceに対するshorthandである。次の形式のalgorithm step:

  1. IfAbruptRejectPromise(value, capability).

は、次と同じ意味である:

  1. Assert: valueCompletion Recordである。
  2. valueabrupt completionなら、
    1. Call(capability.[[Reject]], undefined, « value.[[Value]] »)を実行する。
    2. capability.[[Promise]]を返す。
  3. valueを ! value に設定する。

27.5.1.2 PromiseReaction Records

PromiseReaction Recordは、promiseが与えられたvalueでresolvedまたはrejectedになったときに、どのようにreactすべきかについての情報を格納するために使用されるRecord valueである。PromiseReaction RecordsはPerformPromiseThen abstract operationによって作成され、NewPromiseReactionJobによって返されるAbstract Closureによって使用される。

PromiseReaction Recordsは、Table 92に列挙されるfieldsを持つ。

Table 92: PromiseReaction Record Fields
Field Name Value Meaning
[[Capability]] PromiseCapability Recordまたはundefined このrecordがreaction handlerを提供するpromiseのcapabilities。
[[Type]] fulfillまたはreject [[Type]]は、[[Handler]]emptyであるときに、settlement typeに固有のbehaviourを可能にするために使用される。
[[Handler]] JobCallback Recordまたはempty incoming valueに適用されるべきfunctionであり、そのreturn valueがderived promiseに何が起こるかをgovernする。[[Handler]]emptyである場合、代わりに[[Type]]のvalueに依存するfunctionが使用される。

27.5.1.3 CreateResolvingFunctions ( toResolve )

The abstract operation CreateResolvingFunctions takes argument toResolve (a Promise) and returns a Record with fields [[Resolve]] (a function object) and [[Reject]] (a function object). It performs the following steps when called:

  1. promiseOrEmptyRecord { [[Value]]: toResolve }とする。
  2. resolveStepsを、parameters (resolution)を持ち、promiseOrEmptyをcaptureし、呼び出されたときに以下のstepsを実行するnew Abstract Closureとする:
    1. promiseOrEmpty.[[Value]]emptyなら、undefinedを返す。
    2. promisepromiseOrEmpty.[[Value]]とする。
    3. promiseOrEmpty.[[Value]]emptyに設定する。
    4. SameValue(resolution, promise)がtrueなら、
      1. selfResolutionErrorをnewly created TypeError objectとする。
      2. RejectPromise(promise, selfResolutionError)を実行する。
      3. undefinedを返す。
    5. resolutionがObjectでないなら、
      1. FulfillPromise(promise, resolution)を実行する。
      2. undefinedを返す。
    6. thenCompletion(Get(resolution, "then"))とする。
    7. thenabrupt completionなら、
      1. RejectPromise(promise, then.[[Value]])を実行する。
      2. undefinedを返す。
    8. thenActionthen.[[Value]]とする。
    9. IsCallable(thenAction)がfalseなら、
      1. FulfillPromise(promise, resolution)を実行する。
      2. undefinedを返す。
    10. thenJobCallbackHostMakeJobCallback(thenAction)とする。
    11. jobNewPromiseResolveThenableJob(promise, resolution, thenJobCallback)とする。
    12. HostEnqueuePromiseJob(job.[[Job]], job.[[Realm]])を実行する。
    13. undefinedを返す。
  3. resolveCreateBuiltinFunction(resolveSteps, 1, "", « »)とする。
  4. rejectStepsを、parameters (reason)を持ち、promiseOrEmptyをcaptureし、呼び出されたときに以下のstepsを実行するnew Abstract Closureとする:
    1. promiseOrEmpty.[[Value]]emptyなら、undefinedを返す。
    2. promisepromiseOrEmpty.[[Value]]とする。
    3. promiseOrEmpty.[[Value]]emptyに設定する。
    4. RejectPromise(promise, reason)を実行する。
    5. undefinedを返す。
  5. rejectCreateBuiltinFunction(rejectSteps, 1, "", « »)とする。
  6. Record { [[Resolve]]: resolve, [[Reject]]: reject }を返す。

27.5.1.4 FulfillPromise ( promise, value )

The abstract operation FulfillPromise takes arguments promise (a Promise) and value (an ECMAScript language value) and returns unused. It performs the following steps when called:

  1. Assert: promise.[[PromiseState]]pendingである。
  2. reactionspromise.[[PromiseFulfillReactions]]とする。
  3. promise.[[PromiseResult]]valueに設定する。
  4. promise.[[PromiseFulfillReactions]]undefinedに設定する。
  5. promise.[[PromiseRejectReactions]]undefinedに設定する。
  6. promise.[[PromiseState]]fulfilledに設定する。
  7. TriggerPromiseReactions(reactions, value)を実行する。
  8. unusedを返す。

27.5.1.5 NewPromiseCapability ( ctor )

The abstract operation NewPromiseCapability takes argument ctor (an ECMAScript language value) and returns either a normal completion containing a PromiseCapability Record or a throw completion. これは、built-in Promise constructorの方式でctorconstructorとして使用し、promiseをcreateしてそのresolveおよびreject functionsをextractしようとする。promiseとresolveおよびreject functionsは、new PromiseCapability Recordをinitializeするために使用される。 It performs the following steps when called:

  1. IsConstructor(ctor)がfalseなら、TypeError例外をthrowする。
  2. NOTE: ctorは、Promise constructorのparameter conventionsをsupportするconstructor functionであるとassumedされる(27.5.3.1を参照)。
  3. resolvingFuncsRecord { [[Resolve]]: undefined, [[Reject]]: undefined }とする。
  4. executorClosureを、parameters (resolve, reject)を持ち、resolvingFuncsをcaptureし、呼び出されたときに以下のstepsを実行するnew Abstract Closureとする:
    1. resolvingFuncs.[[Resolve]]undefinedでないなら、TypeError例外をthrowする。
    2. resolvingFuncs.[[Reject]]undefinedでないなら、TypeError例外をthrowする。
    3. resolvingFuncs.[[Resolve]]resolveに設定する。
    4. resolvingFuncs.[[Reject]]rejectに設定する。
    5. NormalCompletion(undefined)を返す。
  5. executorCreateBuiltinFunction(executorClosure, 2, "", « »)とする。
  6. promiseを ? Construct(ctor, « executor ») とする。
  7. IsCallable(resolvingFuncs.[[Resolve]])がfalseなら、TypeError例外をthrowする。
  8. IsCallable(resolvingFuncs.[[Reject]])がfalseなら、TypeError例外をthrowする。
  9. PromiseCapability Record { [[Promise]]: promise, [[Resolve]]: resolvingFuncs.[[Resolve]], [[Reject]]: resolvingFuncs.[[Reject]] }を返す。
Note

このabstract operationはPromise subclassingをsupportする。これは、Promise constructorと同じ方法で渡されたexecutor function argumentをcallする任意のconstructorに対してgenericであるためである。これは、Promise constructorのstatic methodsを任意のsubclassにgeneralizeするために使用される。

27.5.1.6 IsPromise ( arg )

The abstract operation IsPromise takes argument arg (an ECMAScript language value) and returns a Boolean. これはobject上のpromise brandをcheckする。 It performs the following steps when called:

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

27.5.1.7 RejectPromise ( promise, reason )

The abstract operation RejectPromise takes arguments promise (a Promise) and reason (an ECMAScript language value) and returns unused. It performs the following steps when called:

  1. Assert: promise.[[PromiseState]]pendingである。
  2. reactionspromise.[[PromiseRejectReactions]]とする。
  3. promise.[[PromiseResult]]reasonに設定する。
  4. promise.[[PromiseFulfillReactions]]undefinedに設定する。
  5. promise.[[PromiseRejectReactions]]undefinedに設定する。
  6. promise.[[PromiseState]]rejectedに設定する。
  7. promise.[[PromiseIsHandled]]falseなら、HostPromiseRejectionTracker(promise, "reject")を実行する。
  8. TriggerPromiseReactions(reactions, reason)を実行する。
  9. unusedを返す。

27.5.1.8 TriggerPromiseReactions ( reactions, arg )

The abstract operation TriggerPromiseReactions takes arguments reactions (a List of PromiseReaction Records) and arg (an ECMAScript language value) and returns unused. これはreactions内の各recordについてnew Jobをenqueueする。そのような各JobPromiseReaction Record[[Type]]および[[Handler]]をprocessし、[[Handler]]emptyでない場合、与えられたargumentを渡してそれをcallする。[[Handler]]emptyである場合、behaviourは[[Type]]によってdeterminedされる。 It performs the following steps when called:

  1. reactionsの各element reactionについて、
    1. jobNewPromiseReactionJob(reaction, arg)とする。
    2. HostEnqueuePromiseJob(job.[[Job]], job.[[Realm]])を実行する。
  2. unusedを返す。

27.5.1.9 HostPromiseRejectionTracker ( promise, operation )

The host-defined abstract operation HostPromiseRejectionTracker takes arguments promise (a Promise) and operation ("reject" or "handle") and returns unused. これはhost environmentsがpromise rejectionsをtrackできるようにする。

HostPromiseRejectionTrackerのdefault implementationはunusedを返すことである。

Note 1

HostPromiseRejectionTrackerは2つのscenariosでcallされる:

  • promiseがhandlersなしでrejectedされるとき、operation argumentを"reject"に設定してcallされる。
  • rejected promiseに初めてhandlerが追加されるとき、operation argumentを"handle"に設定してcallされる。

HostPromiseRejectionTrackerの典型的なimplementationは、unhandled rejectionsをdevelopersに通知しようとしつつ、そのような以前のnotificationsが後から新しいhandlersのattachによってinvalidatedされる場合にも通知するよう注意するかもしれない。

Note 2

operation"handle"である場合、implementationはgarbage collectionを妨げるような方法でpromiseへのreferenceを保持すべきではない。operation"reject"である場合、rejectionsはrareでありhot code paths上にはないとexpectedされるため、implementationはpromiseへのreferenceを保持してもよい。

27.5.2 Promise Jobs

27.5.2.1 NewPromiseReactionJob ( reaction, arg )

The abstract operation NewPromiseReactionJob takes arguments reaction (a PromiseReaction Record) and arg (an ECMAScript language value) and returns a Record with fields [[Job]] (a Job Abstract Closure) and [[Realm]] (a Realm Record or null). これはincoming valueに適切なhandlerを適用し、そのhandlerのreturn valueを使用してそのhandlerに関連付けられたderived promiseをresolveまたはrejectするnew Job Abstract Closureを返す。 It performs the following steps when called:

  1. jobを、parametersを持たず、reactionおよびargをcaptureし、呼び出されたときに以下のstepsを実行するnew Job Abstract Closureとする:
    1. promiseCapabilityreaction.[[Capability]]とする。
    2. typereaction.[[Type]]とする。
    3. handlerreaction.[[Handler]]とする。
    4. handleremptyなら、
      1. typefulfillなら、
        1. handlerResultNormalCompletion(arg)とする。
      2. そうでなければ、
        1. Assert: typerejectである。
        2. handlerResultThrowCompletion(arg)とする。
    5. そうでなければ、
      1. handlerResultCompletion(HostCallJobCallback(handler, undefined, « arg »))とする。
    6. promiseCapabilityundefinedなら、
      1. Assert: handlerResultabrupt completionでない。
      2. emptyを返す。
    7. Assert: promiseCapabilityPromiseCapability Recordである。
    8. handlerResultabrupt completionなら、
      1. Call(promiseCapability.[[Reject]], undefined, « handlerResult.[[Value]] »)を返す。
    9. Call(promiseCapability.[[Resolve]], undefined, « handlerResult.[[Value]] »)を返す。
  2. handlerRealmnullとする。
  3. reaction.[[Handler]]emptyでないなら、
    1. getHandlerRealmResultCompletion(GetFunctionRealm(reaction.[[Handler]].[[Callback]]))とする。
    2. getHandlerRealmResultnormal completionなら、handlerRealmgetHandlerRealmResult.[[Value]]に設定する。
    3. そうでなければ、handlerRealmcurrent Realm Recordに設定する。
    4. NOTE: handlerがundefinedでない限り、handlerRealmは決してnullではない。handlerがrevoked ProxyでありECMAScript codeが実行されない場合、handlerRealmはerror objectsをcreateするために使用される。
  4. Record { [[Job]]: job, [[Realm]]: handlerRealm }を返す。

27.5.2.2 NewPromiseResolveThenableJob ( promiseToResolve, thenable, then )

The abstract operation NewPromiseResolveThenableJob takes arguments promiseToResolve (a Promise), thenable (an Object), and then (a JobCallback Record) and returns a Record with fields [[Job]] (a Job Abstract Closure) and [[Realm]] (a Realm Record). It performs the following steps when called:

  1. jobを、parametersを持たず、promiseToResolvethenable、およびthenをcaptureし、呼び出されたときに以下のstepsを実行するnew Job Abstract Closureとする:
    1. resolvingFuncsCreateResolvingFunctions(promiseToResolve)とする。
    2. thenCallResultCompletion(HostCallJobCallback(then, thenable, « resolvingFuncs.[[Resolve]], resolvingFuncs.[[Reject]] »))とする。
    3. thenCallResultabrupt completionなら、
      1. Call(resolvingFuncs.[[Reject]], undefined, « thenCallResult.[[Value]] »)を返す。
    4. thenCallResultを返す。
  2. getThenRealmResultCompletion(GetFunctionRealm(then.[[Callback]]))とする。
  3. getThenRealmResultnormal completionなら、thenRealmgetThenRealmResult.[[Value]]とする。
  4. そうでなければ、thenRealmcurrent Realm Recordとする。
  5. NOTE: thenRealmは決してnullではない。then.[[Callback]]がrevoked Proxyでありcodeが実行されない場合、thenRealmはerror objectsをcreateするために使用される。
  6. Record { [[Job]]: job, [[Realm]]: thenRealm }を返す。
Note

このJobは、supplied thenableおよびそのthen methodを使用して、与えられたpromiseをresolveする。このprocessは、then methodのevaluationが任意のsurrounding codeのevaluationが完了した後に発生することをensureするため、Jobとして行われなければならない。

27.5.3 Promiseコンストラクタ

Promise constructorは:

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

27.5.3.1 Promise ( executor )

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

  1. NewTargetがundefinedなら、TypeError例外をthrowする。
  2. IsCallable(executor)がfalseなら、TypeError例外をthrowする。
  3. promiseを ? OrdinaryCreateFromConstructor(NewTarget, "%Promise.prototype%", « [[PromiseState]], [[PromiseResult]], [[PromiseFulfillReactions]], [[PromiseRejectReactions]], [[PromiseIsHandled]] ») とする。
  4. promise.[[PromiseState]]pendingに設定する。
  5. promise.[[PromiseResult]]emptyに設定する。
  6. promise.[[PromiseFulfillReactions]]をnew empty Listに設定する。
  7. promise.[[PromiseRejectReactions]]をnew empty Listに設定する。
  8. promise.[[PromiseIsHandled]]falseに設定する。
  9. resolvingFuncsCreateResolvingFunctions(promise)とする。
  10. completionCompletion(Call(executor, undefined, « resolvingFuncs.[[Resolve]], resolvingFuncs.[[Reject]] »))とする。
  11. completionabrupt completionなら、
    1. Call(resolvingFuncs.[[Reject]], undefined, « completion.[[Value]] »)を実行する。
  12. promiseを返す。
Note

executor argumentはfunction objectでなければならない。これは、このPromiseによって表される、場合によってはdeferredされたactionの開始および完了報告のためにcallされる。executorは2つのarguments、resolverejectでcallされる。これらは、deferred computationの最終的なcompletionまたはfailureを報告するためにexecutor functionによって使用されうるfunctionsである。executor functionからreturnすることは、deferred actionが完了したことを意味するのではなく、deferred actionを最終的にperformするrequestがacceptedされたことだけを意味する。

executor functionに渡されるresolve functionは、single argumentを受け入れる。executor codeは最終的にresolve functionをcallして、関連付けられたPromiseをresolveしたいことを示してもよい。resolve functionに渡されるargumentは、deferred actionの最終的なvalueを表し、実際のfulfillment valueまたはfulfilledされた場合にvalueを提供する別のpromiseのいずれかでありうる。

executor functionに渡されるreject functionは、single argumentを受け入れる。executor codeは最終的にreject functionをcallして、関連付けられたPromiseがrejectedされ、決してfulfilledされないことを示してもよい。reject functionに渡されるargumentは、promiseのrejection valueとして使用される。典型的にはError objectである。

Promise constructorによってexecutor functionに渡されるresolveおよびreject functionsは、関連付けられたpromiseを実際にresolveおよびrejectするcapabilityを持つ。Subclassesは、resolveおよびrejectにcustomized valuesを渡す異なるconstructor behaviourを持ってもよい。

27.5.4 Promiseコンストラクタのプロパティ

Promise constructorは:

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

27.5.4.1 Promise.all ( iterable )

このfunctionは、渡されたpromisesのfulfillment valuesのarrayでfulfilledされる、または最初にrejectする渡されたpromiseのreasonでrejectされるnew promiseを返す。このalgorithmを実行する際、渡されたiterableのすべてのelementsをpromisesにresolveする。

  1. ctorthis valueとする。
  2. promiseCapabilityを ? NewPromiseCapability(ctor) とする。
  3. promiseResolveCompletion(GetPromiseResolve(ctor))とする。
  4. IfAbruptRejectPromise(promiseResolve, promiseCapability).
  5. iteratorRecordCompletion(GetIterator(iterable, sync))とする。
  6. IfAbruptRejectPromise(iteratorRecord, promiseCapability).
  7. resultCompletion(PerformPromiseAll(iteratorRecord, ctor, promiseCapability, promiseResolve))とする。
  8. resultabrupt completionなら、
    1. iteratorRecord.[[Done]]falseなら、resultCompletion(IteratorClose(iteratorRecord, result))に設定する。
    2. IfAbruptRejectPromise(result, promiseCapability).
  9. resultを返す。
Note

このfunctionは、そのthis valueがPromise constructorのparameter conventionsをsupportするconstructor functionであることをrequireする。

27.5.4.1.1 GetPromiseResolve ( promiseCtor )

The abstract operation GetPromiseResolve takes argument promiseCtor (a constructor) and returns either a normal completion containing a function object or a throw completion. It performs the following steps when called:

  1. promiseResolveを ? Get(promiseCtor, "resolve") とする。
  2. IsCallable(promiseResolve)がfalseなら、TypeError例外をthrowする。
  3. promiseResolveを返す。

27.5.4.1.2 PerformPromiseAll ( iteratorRecord, ctor, resultCapability, promiseResolve )

The abstract operation PerformPromiseAll takes arguments iteratorRecord (an Iterator Record), ctor (a constructor), resultCapability (a PromiseCapability Record), and promiseResolve (a function object) and returns either a normal completion containing an Object or a throw completion. It performs the following steps when called:

  1. valuesをnew empty Listとする。
  2. NOTE: remainingElementsCountは、input iteratorがexhaustedされる前に渡されたcallbackをcallするmisbehaving "then"が存在する場合でも、resultCapability.[[Resolve]]が一度だけcallされることをensureするため、0ではなく1から始まる。
  3. remainingElementsCountRecord { [[Value]]: 1 }とする。
  4. indexを0とする。
  5. 繰り返す:
    1. nextを ? IteratorStepValue(iteratorRecord) とする。
    2. nextdoneなら、
      1. remainingElementsCount.[[Value]]remainingElementsCount.[[Value]] - 1に設定する。
      2. remainingElementsCount.[[Value]] = 0なら、
        1. valuesArrayCreateArrayFromList(values)とする。
        2. Call(resultCapability.[[Resolve]], undefined, « valuesArray »)を実行する。
      3. resultCapability.[[Promise]]を返す。
    3. undefinedvaluesにappendする。
    4. nextPromiseを ? Call(promiseResolve, ctor, « next ») とする。
    5. fulfilledStepsを、parameters (value)を持ち、valuesresultCapability、およびremainingElementsCountをcaptureし、呼び出されたときに以下のstepsを実行するnew Abstract Closureとする:
      1. activeFuncactive function objectとする。
      2. activeFunc.[[AlreadyCalled]]trueなら、undefinedを返す。
      3. activeFunc.[[AlreadyCalled]]trueに設定する。
      4. thisIndexactiveFunc.[[Index]]とする。
      5. values[thisIndex]をvalueに設定する。
      6. remainingElementsCount.[[Value]]remainingElementsCount.[[Value]] - 1に設定する。
      7. remainingElementsCount.[[Value]] = 0なら、
        1. valuesArrayCreateArrayFromList(values)とする。
        2. Call(resultCapability.[[Resolve]], undefined, « valuesArray »)を返す。
      8. undefinedを返す。
    6. onFulfilledCreateBuiltinFunction(fulfilledSteps, 1, "", « [[AlreadyCalled]], [[Index]] »)とする。
    7. onFulfilled.[[AlreadyCalled]]falseに設定する。
    8. onFulfilled.[[Index]]indexに設定する。
    9. indexindex + 1に設定する。
    10. remainingElementsCount.[[Value]]remainingElementsCount.[[Value]] + 1に設定する。
    11. Invoke(nextPromise, "then", « onFulfilled, resultCapability.[[Reject]] »)を実行する。

27.5.4.2 Promise.allSettled ( iterable )

このfunctionは、original promisesがすべてsettled、すなわちfulfilledまたはrejectedのいずれかになるまで待ってから、promise state snapshotsのarrayでfulfilledされるpromiseを返す。このalgorithmを実行する際、渡されたiterableのすべてのelementsをpromisesにresolveする。

  1. ctorthis valueとする。
  2. promiseCapabilityを ? NewPromiseCapability(ctor) とする。
  3. promiseResolveCompletion(GetPromiseResolve(ctor))とする。
  4. IfAbruptRejectPromise(promiseResolve, promiseCapability).
  5. iteratorRecordCompletion(GetIterator(iterable, sync))とする。
  6. IfAbruptRejectPromise(iteratorRecord, promiseCapability).
  7. resultCompletion(PerformPromiseAllSettled(iteratorRecord, ctor, promiseCapability, promiseResolve))とする。
  8. resultabrupt completionなら、
    1. iteratorRecord.[[Done]]falseなら、resultCompletion(IteratorClose(iteratorRecord, result))に設定する。
    2. IfAbruptRejectPromise(result, promiseCapability).
  9. resultを返す。
Note

このfunctionは、そのthis valueがPromise constructorのparameter conventionsをsupportするconstructor functionであることをrequireする。

27.5.4.2.1 PerformPromiseAllSettled ( iteratorRecord, ctor, resultCapability, promiseResolve )

The abstract operation PerformPromiseAllSettled takes arguments iteratorRecord (an Iterator Record), ctor (a constructor), resultCapability (a PromiseCapability Record), and promiseResolve (a function object) and returns either a normal completion containing an Object or a throw completion. It performs the following steps when called:

  1. valuesをnew empty Listとする。
  2. NOTE: remainingElementsCountは、input iteratorがexhaustedされる前に渡されたcallbacksの1つをcallするmisbehaving "then"が存在する場合でも、resultCapability.[[Resolve]]が一度だけcallされることをensureするため、0ではなく1から始まる。
  3. remainingElementsCountRecord { [[Value]]: 1 }とする。
  4. indexを0とする。
  5. 繰り返す:
    1. nextを ? IteratorStepValue(iteratorRecord) とする。
    2. nextdoneなら、
      1. remainingElementsCount.[[Value]]remainingElementsCount.[[Value]] - 1に設定する。
      2. remainingElementsCount.[[Value]] = 0なら、
        1. valuesArrayCreateArrayFromList(values)とする。
        2. Call(resultCapability.[[Resolve]], undefined, « valuesArray »)を実行する。
      3. resultCapability.[[Promise]]を返す。
    3. undefinedvaluesにappendする。
    4. nextPromiseを ? Call(promiseResolve, ctor, « next ») とする。
    5. alreadyCalledRecord { [[Value]]: false }とする。
    6. fulfilledStepsを、parameters (value)を持ち、valuesresultCapability、およびremainingElementsCountをcaptureし、呼び出されたときに以下のstepsを実行するnew Abstract Closureとする:
      1. activeFuncactive function objectとする。
      2. activeFunc.[[AlreadyCalled]].[[Value]]trueなら、undefinedを返す。
      3. activeFunc.[[AlreadyCalled]].[[Value]]trueに設定する。
      4. objOrdinaryObjectCreate(%Object.prototype%)とする。
      5. CreateDataPropertyOrThrow(obj, "status", "fulfilled")を実行する。
      6. CreateDataPropertyOrThrow(obj, "value", value)を実行する。
      7. thisIndexactiveFunc.[[Index]]とする。
      8. values[thisIndex]をobjに設定する。
      9. remainingElementsCount.[[Value]]remainingElementsCount.[[Value]] - 1に設定する。
      10. remainingElementsCount.[[Value]] = 0なら、
        1. valuesArrayCreateArrayFromList(values)とする。
        2. Call(resultCapability.[[Resolve]], undefined, « valuesArray »)を返す。
      11. undefinedを返す。
    7. onFulfilledCreateBuiltinFunction(fulfilledSteps, 1, "", « [[AlreadyCalled]], [[Index]] »)とする。
    8. onFulfilled.[[AlreadyCalled]]alreadyCalledに設定する。
    9. onFulfilled.[[Index]]indexに設定する。
    10. rejectedStepsを、parameters (error)を持ち、valuesresultCapability、およびremainingElementsCountをcaptureし、呼び出されたときに以下のstepsを実行するnew Abstract Closureとする:
      1. activeFuncactive function objectとする。
      2. activeFunc.[[AlreadyCalled]].[[Value]]trueなら、undefinedを返す。
      3. activeFunc.[[AlreadyCalled]].[[Value]]trueに設定する。
      4. objOrdinaryObjectCreate(%Object.prototype%)とする。
      5. CreateDataPropertyOrThrow(obj, "status", "rejected")を実行する。
      6. CreateDataPropertyOrThrow(obj, "reason", error)を実行する。
      7. thisIndexactiveFunc.[[Index]]とする。
      8. values[thisIndex]をobjに設定する。
      9. remainingElementsCount.[[Value]]remainingElementsCount.[[Value]] - 1に設定する。
      10. remainingElementsCount.[[Value]] = 0なら、
        1. valuesArrayCreateArrayFromList(values)とする。
        2. Call(resultCapability.[[Resolve]], undefined, « valuesArray »)を返す。
      11. undefinedを返す。
    11. onRejectedCreateBuiltinFunction(rejectedSteps, 1, "", « [[AlreadyCalled]], [[Index]] »)とする。
    12. onRejected.[[AlreadyCalled]]alreadyCalledに設定する。
    13. onRejected.[[Index]]indexに設定する。
    14. indexindex + 1に設定する。
    15. remainingElementsCount.[[Value]]remainingElementsCount.[[Value]] + 1に設定する。
    16. Invoke(nextPromise, "then", « onFulfilled, onRejected »)を実行する。

27.5.4.3 Promise.any ( iterable )

このfunctionは、与えられたpromisesのうち最初にfulfilledされたpromiseによってfulfilledされるpromise、または与えられたpromisesがすべてrejectedされた場合にrejection reasonsを保持するAggregateErrorでrejectedされるpromiseを返す。このalgorithmを実行する際、渡されたiterableのすべてのelementsをpromisesにresolveする。

  1. ctorthis valueとする。
  2. promiseCapabilityを ? NewPromiseCapability(ctor) とする。
  3. promiseResolveCompletion(GetPromiseResolve(ctor))とする。
  4. IfAbruptRejectPromise(promiseResolve, promiseCapability).
  5. iteratorRecordCompletion(GetIterator(iterable, sync))とする。
  6. IfAbruptRejectPromise(iteratorRecord, promiseCapability).
  7. resultCompletion(PerformPromiseAny(iteratorRecord, ctor, promiseCapability, promiseResolve))とする。
  8. resultabrupt completionなら、
    1. iteratorRecord.[[Done]]falseなら、resultCompletion(IteratorClose(iteratorRecord, result))に設定する。
    2. IfAbruptRejectPromise(result, promiseCapability).
  9. resultを返す。
Note

このfunctionは、そのthis valueがPromise constructorのparameter conventionsをsupportするconstructor functionであることをrequireする。

27.5.4.3.1 PerformPromiseAny ( iteratorRecord, ctor, resultCapability, promiseResolve )

The abstract operation PerformPromiseAny takes arguments iteratorRecord (an Iterator Record), ctor (a constructor), resultCapability (a PromiseCapability Record), and promiseResolve (a function object) and returns either a normal completion containing an Object or a throw completion. It performs the following steps when called:

  1. errorsをnew empty Listとする。
  2. NOTE: remainingElementsCountは、input iteratorがexhaustedされる前に渡されたcallbackをcallするmisbehaving "then"が存在する場合でも、resultCapability.[[Reject]]が一度だけcallされることをensureするため、0ではなく1から始まる。
  3. remainingElementsCountRecord { [[Value]]: 1 }とする。
  4. indexを0とする。
  5. 繰り返す:
    1. nextを ? IteratorStepValue(iteratorRecord) とする。
    2. nextdoneなら、
      1. remainingElementsCount.[[Value]]remainingElementsCount.[[Value]] - 1に設定する。
      2. remainingElementsCount.[[Value]] = 0なら、
        1. aggregateErrorをnewly created AggregateError objectとする。
        2. DefinePropertyOrThrow(aggregateError, "errors", PropertyDescriptor { [[Configurable]]: true, [[Enumerable]]: false, [[Writable]]: true, [[Value]]: CreateArrayFromList(errors) })を実行する。
        3. Call(resultCapability.[[Reject]], undefined, « aggregateError »)を実行する。
      3. resultCapability.[[Promise]]を返す。
    3. undefinederrorsにappendする。
    4. nextPromiseを ? Call(promiseResolve, ctor, « next ») とする。
    5. rejectedStepsを、parameters (error)を持ち、errorsresultCapability、およびremainingElementsCountをcaptureし、呼び出されたときに以下のstepsを実行するnew Abstract Closureとする:
      1. activeFuncactive function objectとする。
      2. activeFunc.[[AlreadyCalled]]trueなら、undefinedを返す。
      3. activeFunc.[[AlreadyCalled]]trueに設定する。
      4. thisIndexactiveFunc.[[Index]]とする。
      5. errors[thisIndex]をerrorに設定する。
      6. remainingElementsCount.[[Value]]remainingElementsCount.[[Value]] - 1に設定する。
      7. remainingElementsCount.[[Value]] = 0なら、
        1. aggregateErrorをnewly created AggregateError objectとする。
        2. DefinePropertyOrThrow(aggregateError, "errors", PropertyDescriptor { [[Configurable]]: true, [[Enumerable]]: false, [[Writable]]: true, [[Value]]: CreateArrayFromList(errors) })を実行する。
        3. Call(resultCapability.[[Reject]], undefined, « aggregateError »)を返す。
      8. undefinedを返す。
    6. onRejectedCreateBuiltinFunction(rejectedSteps, 1, "", « [[AlreadyCalled]], [[Index]] »)とする。
    7. onRejected.[[AlreadyCalled]]falseに設定する。
    8. onRejected.[[Index]]indexに設定する。
    9. indexindex + 1に設定する。
    10. remainingElementsCount.[[Value]]remainingElementsCount.[[Value]] + 1に設定する。
    11. Invoke(nextPromise, "then", « resultCapability.[[Resolve]], onRejected »)を実行する。

27.5.4.4 Promise.prototype

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

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

27.5.4.5 Promise.race ( iterable )

このfunctionは、最初にsettleする渡されたpromiseと同じ方法でsettledされるnew promiseを返す。このalgorithmを実行する際、渡されたiterableのすべてのelementsをpromisesにresolveする。

  1. ctorthis valueとする。
  2. promiseCapabilityを ? NewPromiseCapability(ctor) とする。
  3. promiseResolveCompletion(GetPromiseResolve(ctor))とする。
  4. IfAbruptRejectPromise(promiseResolve, promiseCapability).
  5. iteratorRecordCompletion(GetIterator(iterable, sync))とする。
  6. IfAbruptRejectPromise(iteratorRecord, promiseCapability).
  7. resultCompletion(PerformPromiseRace(iteratorRecord, ctor, promiseCapability, promiseResolve))とする。
  8. resultabrupt completionなら、
    1. iteratorRecord.[[Done]]falseなら、resultCompletion(IteratorClose(iteratorRecord, result))に設定する。
    2. IfAbruptRejectPromise(result, promiseCapability).
  9. resultを返す。
Note 1

iterable argumentがvaluesをyieldしない場合、またはiterableによってyieldされたpromisesのどれもsettleしない場合、このmethodによって返されるpending promiseは決してsettledされない。

Note 2

このfunctionは、そのthis valueがPromise constructorのparameter conventionsをsupportするconstructor functionであることをexpectedする。また、そのthis valueがresolve methodをprovideすることもexpectedする。

27.5.4.5.1 PerformPromiseRace ( iteratorRecord, ctor, resultCapability, promiseResolve )

The abstract operation PerformPromiseRace takes arguments iteratorRecord (an Iterator Record), ctor (a constructor), resultCapability (a PromiseCapability Record), and promiseResolve (a function object) and returns either a normal completion containing an Object or a throw completion. It performs the following steps when called:

  1. 繰り返す:
    1. nextを ? IteratorStepValue(iteratorRecord) とする。
    2. nextdoneなら、
      1. resultCapability.[[Promise]]を返す。
    3. nextPromiseを ? Call(promiseResolve, ctor, « next ») とする。
    4. Invoke(nextPromise, "then", « resultCapability.[[Resolve]], resultCapability.[[Reject]] »)を実行する。

27.5.4.6 Promise.reject ( reason )

このfunctionは、渡されたargumentでrejectedされたnew promiseを返す。

  1. ctorthis valueとする。
  2. promiseCapabilityを ? NewPromiseCapability(ctor) とする。
  3. Call(promiseCapability.[[Reject]], undefined, « reason »)を実行する。
  4. promiseCapability.[[Promise]]を返す。
Note

このfunctionは、そのthis valueがPromise constructorのparameter conventionsをsupportするconstructor functionであることをexpectedする。

27.5.4.7 Promise.resolve ( resolution )

このfunctionは、渡されたargumentでresolvedされたnew promise、またはargumentがこのconstructorによって生成されたpromiseである場合はargument自体を返す。

  1. ctorthis valueとする。
  2. ctorがObjectでないなら、TypeError例外をthrowする。
  3. PromiseResolve(ctor, resolution)を返す。
Note

このfunctionは、そのthis valueがPromise constructorのparameter conventionsをsupportするconstructor functionであることをexpectedする。

27.5.4.7.1 PromiseResolve ( ctor, resolution )

The abstract operation PromiseResolve takes arguments ctor (an Object) and resolution (an ECMAScript language value) and returns either a normal completion containing an Object or a throw completion. これはresolutionでresolvedされたnew promiseを返す。 It performs the following steps when called:

  1. IsPromise(resolution)がtrueなら、
    1. resolutionCtorを ? Get(resolution, "constructor") とする。
    2. SameValue(resolutionCtor, ctor)がtrueなら、resolutionを返す。
  2. promiseCapabilityを ? NewPromiseCapability(ctor) とする。
  3. Call(promiseCapability.[[Resolve]], undefined, « resolution »)を実行する。
  4. promiseCapability.[[Promise]]を返す。

27.5.4.8 Promise.try ( callback, ...args )

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

  1. ctorthis valueとする。
  2. ctorがObjectでないなら、TypeError例外をthrowする。
  3. promiseCapabilityを ? NewPromiseCapability(ctor) とする。
  4. statusCompletion(Call(callback, undefined, args))とする。
  5. statusabrupt completionなら、
    1. Call(promiseCapability.[[Reject]], undefined, « status.[[Value]] »)を実行する。
  6. そうでなければ、
    1. Call(promiseCapability.[[Resolve]], undefined, « status.[[Value]] »)を実行する。
  7. promiseCapability.[[Promise]]を返す。
Note

このfunctionは、そのthis valueがPromise constructorのparameter conventionsをsupportするconstructor functionであることをexpectedする。

27.5.4.9 Promise.withResolvers ( )

このfunctionは、new promiseと、それに関連付けられたresolveおよびreject functionsからなる3つのpropertiesを持つobjectを返す。

  1. ctorthis valueとする。
  2. promiseCapabilityを ? NewPromiseCapability(ctor) とする。
  3. objOrdinaryObjectCreate(%Object.prototype%)とする。
  4. CreateDataPropertyOrThrow(obj, "promise", promiseCapability.[[Promise]])を実行する。
  5. CreateDataPropertyOrThrow(obj, "resolve", promiseCapability.[[Resolve]])を実行する。
  6. CreateDataPropertyOrThrow(obj, "reject", promiseCapability.[[Reject]])を実行する。
  7. objを返す。

27.5.4.10 get Promise [ %Symbol.species% ]

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

  1. this valueを返す。

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

Note

Promise prototype methodsは通常、derived objectをcreateするために、そのthis valueのconstructorを使用する。しかし、subclass constructorは、その%Symbol.species% propertyをredefiningすることによって、そのdefault behaviourをover-rideしてもよい。

27.5.5 Promise Prototype Objectのプロパティ

Promise prototype objectは:

  • %Promise.prototype%である。
  • valueが%Object.prototype%である[[Prototype]] internal slotを持つ。
  • ordinary objectである。
  • [[PromiseState]] internal slot、またはPromise instancesの他のinternal slotsを持たない。

27.5.5.1 Promise.prototype.catch ( onRejected )

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

  1. promisethis valueとする。
  2. Invoke(promise, "then", « undefined, onRejected »)を返す。

27.5.5.2 Promise.prototype.constructor

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

27.5.5.3 Promise.prototype.finally ( onFinally )

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

  1. promisethis valueとする。
  2. promiseがObjectでないなら、TypeError例外をthrowする。
  3. ctorを ? SpeciesConstructor(promise, %Promise%) とする。
  4. Assert: IsConstructor(ctor)はtrueである。
  5. IsCallable(onFinally)がfalseなら、
    1. thenFinallyonFinallyとする。
    2. catchFinallyonFinallyとする。
  6. そうでなければ、
    1. thenFinallyClosureを、parameters (value)を持ち、onFinallyおよびctorをcaptureし、呼び出されたときに以下のstepsを実行するnew Abstract Closureとする:
      1. resultを ? Call(onFinally, undefined) とする。
      2. pを ? PromiseResolve(ctor, result) とする。
      3. returnValueを、parametersを持たず、valueをcaptureし、呼び出されたときに以下のstepsを実行するnew Abstract Closureとする:
        1. NormalCompletion(value)を返す。
      4. valueThunkCreateBuiltinFunction(returnValue, 0, "", « »)とする。
      5. Invoke(p, "then", « valueThunk »)を返す。
    2. thenFinallyCreateBuiltinFunction(thenFinallyClosure, 1, "", « »)とする。
    3. catchFinallyClosureを、parameters (reason)を持ち、onFinallyおよびctorをcaptureし、呼び出されたときに以下のstepsを実行するnew Abstract Closureとする:
      1. resultを ? Call(onFinally, undefined) とする。
      2. pを ? PromiseResolve(ctor, result) とする。
      3. throwReasonを、parametersを持たず、reasonをcaptureし、呼び出されたときに以下のstepsを実行するnew Abstract Closureとする:
        1. reasonをThrowする。
      4. throwerCreateBuiltinFunction(throwReason, 0, "", « »)とする。
      5. Invoke(p, "then", « thrower »)を返す。
    4. catchFinallyCreateBuiltinFunction(catchFinallyClosure, 1, "", « »)とする。
  7. Invoke(promise, "then", « thenFinally, catchFinally »)を返す。

27.5.5.4 Promise.prototype.then ( onFulfilled, onRejected )

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

  1. promisethis valueとする。
  2. IsPromise(promise)がfalseなら、TypeError例外をthrowする。
  3. ctorを ? SpeciesConstructor(promise, %Promise%) とする。
  4. resultCapabilityを ? NewPromiseCapability(ctor) とする。
  5. PerformPromiseThen(promise, onFulfilled, onRejected, resultCapability)を返す。

27.5.5.4.1 PerformPromiseThen ( promise, onFulfilled, onRejected [ , resultCapability ] )

The abstract operation PerformPromiseThen takes arguments promise (a Promise), onFulfilled (an ECMAScript language value), and onRejected (an ECMAScript language value) and optional argument resultCapability (a PromiseCapability Record) and returns an Object or undefined. これは、promise上でonFulfilledおよびonRejectedをsettlement actionsとして使用して“then” operationを実行する。resultCapabilityが渡された場合、resultはresultCapabilityのpromiseを更新することによって格納される。渡されない場合、PerformPromiseThenはresultが重要でないspecification-internal operationによってcallされている。 It performs the following steps when called:

  1. Assert: IsPromise(promise)はtrueである。
  2. resultCapabilityが存在しないなら、
    1. resultCapabilityundefinedに設定する。
  3. IsCallable(onFulfilled)がfalseなら、
    1. onFulfilledJobCallbackemptyとする。
  4. そうでなければ、
    1. onFulfilledJobCallbackHostMakeJobCallback(onFulfilled)とする。
  5. IsCallable(onRejected)がfalseなら、
    1. onRejectedJobCallbackemptyとする。
  6. そうでなければ、
    1. onRejectedJobCallbackHostMakeJobCallback(onRejected)とする。
  7. fulfillReactionPromiseReaction Record { [[Capability]]: resultCapability, [[Type]]: fulfill, [[Handler]]: onFulfilledJobCallback }とする。
  8. rejectReactionPromiseReaction Record { [[Capability]]: resultCapability, [[Type]]: reject, [[Handler]]: onRejectedJobCallback }とする。
  9. promise.[[PromiseState]]pendingなら、
    1. fulfillReactionpromise.[[PromiseFulfillReactions]]にappendする。
    2. rejectReactionpromise.[[PromiseRejectReactions]]にappendする。
  10. そうでなく、promise.[[PromiseState]]fulfilledなら、
    1. valuepromise.[[PromiseResult]]とする。
    2. fulfillJobNewPromiseReactionJob(fulfillReaction, value)とする。
    3. HostEnqueuePromiseJob(fulfillJob.[[Job]], fulfillJob.[[Realm]])を実行する。
  11. そうでなければ、
    1. Assert: promise.[[PromiseState]]rejectedである。
    2. reasonpromise.[[PromiseResult]]とする。
    3. promise.[[PromiseIsHandled]]falseなら、HostPromiseRejectionTracker(promise, "handle")を実行する。
    4. rejectJobNewPromiseReactionJob(rejectReaction, reason)とする。
    5. HostEnqueuePromiseJob(rejectJob.[[Job]], rejectJob.[[Realm]])を実行する。
  12. promise.[[PromiseIsHandled]]trueに設定する。
  13. resultCapabilityundefinedなら、undefinedを返す。
  14. resultCapability.[[Promise]]を返す。

27.5.5.5 Promise.prototype [ %Symbol.toStringTag% ]

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

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

27.5.6 Promiseインスタンスのプロパティ

Promise instancesは、Promise prototype object(intrinsic、%Promise.prototype%)からpropertiesをinheritするordinary objectsである。Promise instancesは、最初にTable 93に記述されるinternal slotsで作成される。

Table 93: Internal Slots of Promise Instances
Internal Slot Type Description
[[PromiseState]] pending, fulfilled, or rejected promiseがそのthen methodへのincoming callsにどのようにreactするかをgovernする。
[[PromiseResult]] ECMAScript language valueまたはempty promiseがfulfilledまたはrejectedされたvalue(ある場合)。[[PromiseState]]pendingである場合かつその場合に限りemptyである。
[[PromiseFulfillReactions]] PromiseReaction RecordsList promiseがpending stateからfulfilled stateにtransitionするとき/する場合にprocessedされるRecords
[[PromiseRejectReactions]] PromiseReaction RecordsList promiseがpending stateからrejected stateにtransitionするとき/する場合にprocessedされるRecords
[[PromiseIsHandled]] Boolean promiseがこれまでにfulfillmentまたはrejection handlerを持ったことがあるかどうかを示す。unhandled rejection trackingで使用される。

27.6 GeneratorFunctionオブジェクト

GeneratorFunctionsは、通常、GeneratorDeclarationGeneratorExpression、およびGeneratorMethodを評価することによって作成されるfunctionsである。これらは%GeneratorFunction% intrinsicをcallすることによって作成されることもある。

Figure 6 (Informative): Generatorオブジェクトの関係
非常に多様なboxesとarrows。

27.6.1 GeneratorFunctionコンストラクタ

GeneratorFunction constructorは:

  • %GeneratorFunction%である。
  • Functionのsubclassである。
  • constructorとしてではなくfunctionとして呼び出されたときにnew GeneratorFunctionをcreateしてinitializeする。したがって、function call GeneratorFunction (…)は、同じargumentsを持つobject creation expression new GeneratorFunction (…)と等価である。
  • class definitionのextends clauseのvalueとして使用してもよい。指定されたGeneratorFunction behaviourをinheritすることを意図するsubclass constructorsは、built-in GeneratorFunction behaviourに必要なinternal slotsでsubclass instancesをcreateしてinitializeするために、GeneratorFunction constructorへのsuper callを含まなければならない。generator function objectsをdefineするすべてのECMAScript syntactic formsは、GeneratorFunctionのdirect instancesを作成する。GeneratorFunction subclassesのinstancesを作成するsyntactic meansは存在しない。

27.6.1.1 GeneratorFunction ( ...paramArgs, bodyArg )

最後のargument(ある場合)は、generator functionのbody(executable code)を指定する。それより前のargumentsはformal parametersを指定する。

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

  1. activeFuncactive function objectとする。
  2. bodyArgが存在しないなら、bodyArgをempty Stringに設定する。
  3. CreateDynamicFunction(activeFunc, NewTarget, generator, paramArgs, bodyArg)を返す。
Note

20.2.1.1NOTEを参照。

27.6.2 GeneratorFunctionコンストラクタのプロパティ

GeneratorFunction constructorは:

  • Function constructorからinheritするstandard built-in function objectである。
  • valueが%Function%である[[Prototype]] internal slotを持つ。
  • valueが1𝔽である"length" propertyを持つ。
  • valueが"GeneratorFunction"である"name" propertyを持つ。
  • 以下のpropertiesを持つ:

27.6.2.1 GeneratorFunction.prototype

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

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

27.6.3 GeneratorFunction Prototype Objectのプロパティ

GeneratorFunction prototype objectは:

27.6.3.1 GeneratorFunction.prototype.constructor

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

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

27.6.3.2 GeneratorFunction.prototype.prototype

GeneratorFunction.prototype.prototypeのinitial valueは%GeneratorPrototype%である。

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

27.6.3.3 GeneratorFunction.prototype [ %Symbol.toStringTag% ]

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

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

27.6.4 GeneratorFunctionインスタンス

すべてのGeneratorFunction instanceはECMAScript function objectであり、Table 26に列挙されるinternal slotsを持つ。そのようなすべてのinstancesにおける[[IsClassConstructor]] internal slotのvalueはfalseである。

各GeneratorFunction instanceは以下のown propertiesを持つ:

27.6.4.1 length

20.2.4.1で与えられるFunction instancesの"length" propertyの仕様は、GeneratorFunction instancesにも適用される。

27.6.4.2 name

20.2.4.2で与えられるFunction instancesの"name" propertyの仕様は、GeneratorFunction instancesにも適用される。

27.6.4.3 prototype

GeneratorFunction instanceが作成されるたびに、別のordinary objectも作成され、generator functionの"prototype" propertyのinitial valueになる。prototype propertyのvalueは、generator function object[[Call]]を使用してinvokedされたときに、新たに作成されるGeneratorの[[Prototype]] internal slotをinitializeするために使用される。

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

Note

Function instancesとは異なり、GeneratorFunctionの"prototype" propertyのvalueであるobjectは、valueがGeneratorFunction instanceである"constructor" propertyを持たない。

27.7 AsyncGeneratorFunctionオブジェクト

AsyncGeneratorFunctionsは、通常、AsyncGeneratorDeclarationAsyncGeneratorExpression、およびAsyncGeneratorMethod syntactic productionsを評価することによって作成されるfunctionsである。これらは%AsyncGeneratorFunction% intrinsicをcallすることによって作成されることもある。

27.7.1 AsyncGeneratorFunctionコンストラクタ

AsyncGeneratorFunction constructorは:

  • %AsyncGeneratorFunction%である。
  • Functionのsubclassである。
  • constructorとしてではなくfunctionとして呼び出されたときにnew AsyncGeneratorFunctionをcreateしてinitializeする。したがって、function call AsyncGeneratorFunction (...)は、同じargumentsを持つobject creation expression new AsyncGeneratorFunction (...)と等価である。
  • class definitionのextends clauseのvalueとして使用してもよい。指定されたAsyncGeneratorFunction behaviourをinheritすることを意図するsubclass constructorsは、built-in AsyncGeneratorFunction behaviourに必要なinternal slotsでsubclass instancesをcreateしてinitializeするために、AsyncGeneratorFunction constructorへのsuper callを含まなければならない。async generator function objectsをdefineするすべてのECMAScript syntactic formsは、AsyncGeneratorFunctionのdirect instancesを作成する。AsyncGeneratorFunction subclassesのinstancesを作成するsyntactic meansは存在しない。

27.7.1.1 AsyncGeneratorFunction ( ...paramArgs, bodyArg )

最後のargument(ある場合)は、async generator functionのbody(executable code)を指定する。それより前のargumentsはformal parametersを指定する。

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

  1. activeFuncactive function objectとする。
  2. bodyArgが存在しないなら、bodyArgをempty Stringに設定する。
  3. CreateDynamicFunction(activeFunc, NewTarget, async-generator, paramArgs, bodyArg)を返す。
Note

20.2.1.1NOTEを参照。

27.7.2 AsyncGeneratorFunctionコンストラクタのプロパティ

AsyncGeneratorFunction constructorは:

  • Function constructorからinheritするstandard built-in function objectである。
  • valueが%Function%である[[Prototype]] internal slotを持つ。
  • valueが1𝔽である"length" propertyを持つ。
  • valueが"AsyncGeneratorFunction"である"name" propertyを持つ。
  • 以下のpropertiesを持つ:

27.7.2.1 AsyncGeneratorFunction.prototype

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

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

27.7.3 AsyncGeneratorFunction Prototype Objectのプロパティ

AsyncGeneratorFunction prototype objectは:

27.7.3.1 AsyncGeneratorFunction.prototype.constructor

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

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

27.7.3.2 AsyncGeneratorFunction.prototype.prototype

AsyncGeneratorFunction.prototype.prototypeのinitial valueは%AsyncGeneratorPrototype%である。

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

27.7.3.3 AsyncGeneratorFunction.prototype [ %Symbol.toStringTag% ]

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

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

27.7.4 AsyncGeneratorFunctionインスタンス

すべてのAsyncGeneratorFunction instanceはECMAScript function objectであり、Table 26に列挙されるinternal slotsを持つ。そのようなすべてのinstancesにおける[[IsClassConstructor]] internal slotのvalueはfalseである。

各AsyncGeneratorFunction instanceは以下のown propertiesを持つ:

27.7.4.1 length

"length" propertyのvalueは、AsyncGeneratorFunctionが通常expectedするargumentsの数を示すintegral Numberである。ただし、このlanguageは、そのfunctionがそれ以外の数のargumentsでinvokedされることをpermitする。"length" propertyによってspecifiedされる数以外の数のargumentsでinvokedされたときのAsyncGeneratorFunctionのbehaviourは、そのfunctionに依存する。

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

27.7.4.2 name

20.2.4.2で与えられるFunction instancesの"name" propertyの仕様は、AsyncGeneratorFunction instancesにも適用される。

27.7.4.3 prototype

AsyncGeneratorFunction instanceが作成されるたびに、別のordinary objectも作成され、async generator functionの"prototype" propertyのinitial valueになる。prototype propertyのvalueは、generator function object[[Call]]を使用してinvokedされたときに、新たに作成されるAsyncGeneratorの[[Prototype]] internal slotをinitializeするために使用される。

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

Note

function instancesとは異なり、AsyncGeneratorFunctionの"prototype" propertyのvalueであるobjectは、valueがAsyncGeneratorFunction instanceである"constructor" propertyを持たない。

27.8 Generatorオブジェクト

Generatorは、generator functionをcallすることによって作成され、iterator interfaceiterable interfaceの両方にconformする。

Generator instancesは、そのinstanceを作成したgenerator functionの"prototype" propertyのinitial valueから直接propertiesをinheritする。Generator instancesは%GeneratorPrototype%から間接的にpropertiesをinheritする。

27.8.1 %GeneratorPrototype%オブジェクト

%GeneratorPrototype% objectは:

  • %GeneratorFunction.prototype.prototype%である。
  • ordinary objectである。
  • Generator instanceではなく、[[GeneratorState]] internal slotを持たない。
  • valueが%Iterator.prototype%である[[Prototype]] internal slotを持つ。
  • すべてのGenerator instancesによって間接的にinheritされるpropertiesを持つ。

27.8.1.1 %GeneratorPrototype%.constructor

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

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

27.8.1.2 %GeneratorPrototype%.next ( value )

  1. GeneratorResume(this value, value, empty)を返す。

27.8.1.3 %GeneratorPrototype%.return ( value )

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

  1. genthis valueとする。
  2. completionReturnCompletion(value)とする。
  3. GeneratorResumeAbrupt(gen, completion, empty)を返す。

27.8.1.4 %GeneratorPrototype%.throw ( exception )

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

  1. genthis valueとする。
  2. completionThrowCompletion(exception)とする。
  3. GeneratorResumeAbrupt(gen, completion, empty)を返す。

27.8.1.5 %GeneratorPrototype% [ %Symbol.toStringTag% ]

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

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

27.8.2 Generatorインスタンスのプロパティ

Generator instancesは、最初にTable 94に記述されるinternal slotsで作成される。

Table 94: Generatorインスタンスの内部スロット
Internal Slot Type Description
[[GeneratorState]] suspended-start, suspended-yield, executing, or completed generatorのcurrent execution state。
[[GeneratorContext]] execution context このgeneratorのcodeをexecutingするときに使用されるexecution context
[[GeneratorBrand]] Stringまたはempty 異なる種類のgeneratorsをdistinguishするために使用されるbrand。ECMAScript source textによってdeclaredされたgeneratorsの[[GeneratorBrand]]は常にemptyである。

27.8.3 Generator Abstract Operations

27.8.3.1 GeneratorStart ( gen, genBody )

The abstract operation GeneratorStart takes arguments gen (a Generator) and genBody (a FunctionBody Parse Node or an Abstract Closure with no parameters) and returns unused. It performs the following steps when called:

  1. Assert: gen.[[GeneratorState]]suspended-startである。
  2. genContextrunning execution contextとする。
  3. genContextのGenerator componentをgenに設定する。
  4. closureを、parametersを持たず、genBodyをcaptureし、呼び出されたときに以下のstepsを実行するnew Abstract Closureとする:
    1. acGenContextrunning execution contextとする。
    2. acGenacGenContextのGenerator componentとする。
    3. genBodyParse Nodeなら、
      1. resultCompletion(Evaluation of genBody)とする。
    4. そうでなければ、
      1. Assert: genBodyはparametersを持たないAbstract Closureである。
      2. resultCompletion(genBody())とする。
    5. Assert: ここにreturnした場合、generatorはexceptionをthrowしたか、implicitまたはexplicit returnのいずれかを実行した。
    6. acGenContextexecution context stackからremoveし、execution context stackのtopにあるexecution contextrunning execution contextとしてrestoreする。
    7. acGen.[[GeneratorState]]completedに設定する。
    8. NOTE: generatorがcompleted stateに入ると、決してそこからleaveせず、そのassociated execution contextは決してresumedされない。この時点で、acGenにassociatedする任意のexecution stateはdiscardできる。
    9. resultnormal completionなら、
      1. resultValueundefinedとする。
    10. そうでなく、resultreturn completionなら、
      1. resultValueresult.[[Value]]とする。
    11. そうでなければ、
      1. Assert: resultthrow completionである。
      2. resultを返す。
    12. NormalCompletion(CreateIteratorResultObject(resultValue, true))を返す。
  5. genContextのcode evaluation stateを、そのexecution contextについてevaluationがresumedされたときに、closureがargumentsなしでcallされるように設定する。
  6. gen.[[GeneratorContext]]genContextに設定する。
  7. unusedを返す。

27.8.3.2 GeneratorValidate ( gen, genBrand )

The abstract operation GeneratorValidate takes arguments gen (an ECMAScript language value) and genBrand (a String or empty) and returns either a normal completion containing one of suspended-start, suspended-yield, or completed, or a throw completion. It performs the following steps when called:

  1. RequireInternalSlot(gen, [[GeneratorState]])を実行する。
  2. RequireInternalSlot(gen, [[GeneratorBrand]])を実行する。
  3. gen.[[GeneratorBrand]]genBrandでないなら、TypeError例外をthrowする。
  4. Assert: gen[[GeneratorContext]] internal slotを持つ。
  5. stategen.[[GeneratorState]]とする。
  6. stateexecutingなら、TypeError例外をthrowする。
  7. stateを返す。

27.8.3.3 GeneratorResume ( gen, value, genBrand )

The abstract operation GeneratorResume takes arguments gen (an ECMAScript language value), value (an ECMAScript language value or empty), and genBrand (a String or empty) and returns either a normal completion containing an ECMAScript language value or a throw completion. It performs the following steps when called:

  1. stateを ? GeneratorValidate(gen, genBrand) とする。
  2. statecompletedなら、CreateIteratorResultObject(undefined, true)を返す。
  3. Assert: statesuspended-startまたはsuspended-yieldのいずれかである。
  4. genContextgen.[[GeneratorContext]]とする。
  5. gen.[[GeneratorState]]executingに設定する。
  6. RunSuspendedContext(genContext, NormalCompletion(value))を返す。

27.8.3.4 GeneratorResumeAbrupt ( gen, abruptCompletion, genBrand )

The abstract operation GeneratorResumeAbrupt takes arguments gen (an ECMAScript language value), abruptCompletion (a return completion or a throw completion), and genBrand (a String or empty) and returns either a normal completion containing an ECMAScript language value or a throw completion. It performs the following steps when called:

  1. stateを ? GeneratorValidate(gen, genBrand) とする。
  2. statesuspended-startなら、
    1. gen.[[GeneratorState]]completedに設定する。
    2. NOTE: generatorがcompleted stateに入ると、決してそこからleaveせず、そのassociated execution contextは決してresumedされない。この時点で、genにassociatedする任意のexecution stateはdiscardできる。
    3. statecompletedに設定する。
  3. statecompletedなら、
    1. abruptCompletionreturn completionなら、
      1. CreateIteratorResultObject(abruptCompletion.[[Value]], true)を返す。
    2. abruptCompletionを返す。
  4. Assert: statesuspended-yieldである。
  5. genContextgen.[[GeneratorContext]]とする。
  6. gen.[[GeneratorState]]executingに設定する。
  7. RunSuspendedContext(genContext, abruptCompletion)を返す。

27.8.3.5 GetGeneratorKind ( )

The abstract operation GetGeneratorKind takes no arguments and returns non-generator, sync, or async. It performs the following steps when called:

  1. genContextrunning execution contextとする。
  2. genContextがGenerator componentを持たないなら、non-generatorを返す。
  3. gengenContextのGenerator componentとする。
  4. gen[[AsyncGeneratorState]] internal slotを持つなら、asyncを返す。
  5. syncを返す。

27.8.3.6 GeneratorYield ( iteratorResult )

The abstract operation GeneratorYield takes argument iteratorResult (an Object that conforms to the IteratorResult interface) and returns either a normal completion containing an ECMAScript language value or an abrupt completion. It performs the following steps when called:

  1. genContextを、実行中の実行コンテキストとする。
  2. Assert: genContextはジェネレータの実行コンテキストである。
  3. genを、genContextのGeneratorコンポーネントの値とする。
  4. Assert: GetGeneratorKind()はsyncである。
  5. gen.[[GeneratorState]]suspended-yieldに設定する。
  6. Return ? RunCallerContext(iteratorResult)。

27.8.3.7 Yield ( arg )

The abstract operation Yield takes argument arg (an ECMAScript language value) and returns either a normal completion containing an ECMAScript language value or an abrupt completion. It performs the following steps when called:

  1. genKindGetGeneratorKind()とする。
  2. genKindasyncなら、? AsyncGeneratorYield(? Await(arg))を返す。
  3. GeneratorYield(CreateIteratorResultObject(arg, false))を返す。

27.8.3.8 CreateIteratorFromClosure ( closure, genBrand, genProto [ , extraSlots ] )

The abstract operation CreateIteratorFromClosure takes arguments closure (an Abstract Closure with no parameters), genBrand (a String or empty), and genProto (an Object) and optional argument extraSlots (a List of names of internal slots) and returns a Generator. It performs the following steps when called:

  1. NOTE: closureは、IteratorResult objectをyieldするためにYield operationのusesを含むことができる。
  2. extraSlotsが存在しないなら、extraSlotsをnew empty Listに設定する。
  3. internalSlotsListextraSlotsと« [[GeneratorState]], [[GeneratorContext]], [[GeneratorBrand]] »のlist-concatenationとする。
  4. genOrdinaryObjectCreate(genProto, internalSlotsList)とする。
  5. gen.[[GeneratorBrand]]genBrandに設定する。
  6. gen.[[GeneratorState]]suspended-startに設定する。
  7. callerContextrunning execution contextとする。
  8. calleeContextをnew execution contextとする。
  9. calleeContextのFunctionをnullに設定する。
  10. calleeContextRealmcurrent Realm Recordに設定する。
  11. calleeContextのScriptOrModuleをcallerContextのScriptOrModuleに設定する。
  12. callerContextがまだsuspendedでないなら、callerContextをsuspendする。
  13. calleeContextexecution context stackにPushする。calleeContextはいまrunning execution contextである。
  14. GeneratorStart(gen, closure)を実行する。
  15. calleeContextexecution context stackからremoveし、callerContextrunning execution contextとしてrestoreする。
  16. genを返す。

27.9 AsyncGeneratorオブジェクト

AsyncGeneratorは、async generator functionをcallすることによって作成され、async iterator interfaceasync iterable interfaceの両方にconformする。

AsyncGenerator instancesは、そのinstanceを作成したasync generator functionの"prototype" propertyのinitial valueから直接propertiesをinheritする。AsyncGenerator instancesは%AsyncGeneratorPrototype%から間接的にpropertiesをinheritする。

27.9.1 %AsyncGeneratorPrototype%オブジェクト

%AsyncGeneratorPrototype% objectは:

  • %AsyncGeneratorFunction.prototype.prototype%である。
  • ordinary objectである。
  • AsyncGenerator instanceではなく、[[AsyncGeneratorState]] internal slotを持たない。
  • valueが%AsyncIteratorPrototype%である[[Prototype]] internal slotを持つ。
  • すべてのAsyncGenerator instancesによって間接的にinheritされるpropertiesを持つ。

27.9.1.1 %AsyncGeneratorPrototype%.constructor

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

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

27.9.1.2 %AsyncGeneratorPrototype%.next ( value )

  1. genthis valueとする。
  2. promiseCapabilityを ! NewPromiseCapability(%Promise%) とする。
  3. resultCompletion(AsyncGeneratorValidate(gen, empty))とする。
  4. IfAbruptRejectPromise(result, promiseCapability).
  5. stategen.[[AsyncGeneratorState]]とする。
  6. statecompletedなら、
    1. iteratorResultCreateIteratorResultObject(undefined, true)とする。
    2. Call(promiseCapability.[[Resolve]], undefined, « iteratorResult »)を実行する。
    3. promiseCapability.[[Promise]]を返す。
  7. completionNormalCompletion(value)とする。
  8. AsyncGeneratorEnqueue(gen, completion, promiseCapability)を実行する。
  9. statesuspended-startまたはsuspended-yieldのいずれかなら、
    1. AsyncGeneratorResume(gen, completion)を実行する。
  10. そうでなければ、
    1. Assert: stateexecutingまたはdraining-queueのいずれかである。
  11. promiseCapability.[[Promise]]を返す。

27.9.1.3 %AsyncGeneratorPrototype%.return ( value )

  1. genthis valueとする。
  2. promiseCapabilityを ! NewPromiseCapability(%Promise%) とする。
  3. resultCompletion(AsyncGeneratorValidate(gen, empty))とする。
  4. IfAbruptRejectPromise(result, promiseCapability).
  5. completionReturnCompletion(value)とする。
  6. AsyncGeneratorEnqueue(gen, completion, promiseCapability)を実行する。
  7. stategen.[[AsyncGeneratorState]]とする。
  8. statesuspended-startまたはcompletedのいずれかなら、
    1. gen.[[AsyncGeneratorState]]draining-queueに設定する。
    2. AsyncGeneratorAwaitReturn(gen)を実行する。
  9. そうでなく、statesuspended-yieldなら、
    1. AsyncGeneratorResume(gen, completion)を実行する。
  10. そうでなければ、
    1. Assert: stateexecutingまたはdraining-queueのいずれかである。
  11. promiseCapability.[[Promise]]を返す。

27.9.1.4 %AsyncGeneratorPrototype%.throw ( exception )

  1. genthis valueとする。
  2. promiseCapabilityを ! NewPromiseCapability(%Promise%) とする。
  3. resultCompletion(AsyncGeneratorValidate(gen, empty))とする。
  4. IfAbruptRejectPromise(result, promiseCapability).
  5. stategen.[[AsyncGeneratorState]]とする。
  6. statesuspended-startなら、
    1. gen.[[AsyncGeneratorState]]completedに設定する。
    2. statecompletedに設定する。
  7. statecompletedなら、
    1. Call(promiseCapability.[[Reject]], undefined, « exception »)を実行する。
    2. promiseCapability.[[Promise]]を返す。
  8. completionThrowCompletion(exception)とする。
  9. AsyncGeneratorEnqueue(gen, completion, promiseCapability)を実行する。
  10. statesuspended-yieldなら、
    1. AsyncGeneratorResume(gen, completion)を実行する。
  11. そうでなければ、
    1. Assert: stateexecutingまたはdraining-queueのいずれかである。
  12. promiseCapability.[[Promise]]を返す。

27.9.1.5 %AsyncGeneratorPrototype% [ %Symbol.toStringTag% ]

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

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

27.9.2 AsyncGeneratorインスタンスのプロパティ

AsyncGenerator instancesは、最初に以下に記述されるinternal slotsで作成される:

Table 95: AsyncGeneratorインスタンスの内部スロット
Internal Slot Type Description
[[AsyncGeneratorState]] suspended-start, suspended-yield, executing, draining-queue, or completed async generatorのcurrent execution state。
[[AsyncGeneratorContext]] execution context このasync generatorのcodeをexecutingするときに使用されるexecution context
[[AsyncGeneratorQueue]] AsyncGeneratorRequest RecordsList async generatorをresumeするrequestsを表すRecords。state transitionsの間を除き、[[AsyncGeneratorState]]executingまたはdraining-queueのいずれかである場合かつその場合に限りnon-emptyである。
[[GeneratorBrand]] Stringまたはempty 異なる種類のasync generatorsをdistinguishするために使用されるbrand。ECMAScript source textによってdeclaredされたasync generatorsの[[GeneratorBrand]]は常にemptyである。

27.9.3 AsyncGenerator Abstract Operations

27.9.3.1 AsyncGeneratorRequest Records

AsyncGeneratorRequestは、async generatorがどのようにresumedされるべきかについての情報を格納し、対応するpromiseをfulfillまたはrejectするcapabilitiesを含むために使用されるRecord valueである。

これらは以下のfieldsを持つ:

Table 96: AsyncGeneratorRequest Record Fields
Field Name Value Meaning
[[Completion]] Completion Record async generatorをresumeするために使用されるべきCompletion Record
[[Capability]] PromiseCapability Record このrequestにassociatedするpromise capabilities。

27.9.3.2 AsyncGeneratorStart ( gen, genBody )

The abstract operation AsyncGeneratorStart takes arguments gen (an AsyncGenerator) and genBody (a FunctionBody Parse Node or an Abstract Closure with no parameters) and returns unused. It performs the following steps when called:

  1. Assert: gen.[[AsyncGeneratorState]]suspended-startである。
  2. genContextrunning execution contextとする。
  3. genContextのGenerator componentをgenに設定する。
  4. closureを、parametersを持たず、genBodyをcaptureし、呼び出されたときに以下のstepsを実行するnew Abstract Closureとする:
    1. acGenContextrunning execution contextとする。
    2. acGenacGenContextのGenerator componentとする。
    3. genBodyParse Nodeなら、
      1. resultCompletion(Evaluation of genBody)とする。
    4. そうでなければ、
      1. Assert: genBodyはparametersを持たないAbstract Closureである。
      2. resultCompletion(genBody())とする。
    5. Assert: ここにreturnした場合、async generatorはexceptionをthrowしたか、implicitまたはexplicit returnのいずれかを実行した。
    6. acGenContextexecution context stackからremoveし、execution context stackのtopにあるexecution contextrunning execution contextとしてrestoreする。
    7. acGen.[[AsyncGeneratorState]]draining-queueに設定する。
    8. resultnormal completionなら、resultNormalCompletion(undefined)に設定する。
    9. resultreturn completionなら、resultNormalCompletion(result.[[Value]])に設定する。
    10. AsyncGeneratorCompleteStep(acGen, result, true)を実行する。
    11. AsyncGeneratorDrainQueue(acGen)を実行する。
    12. NormalCompletion(undefined)を返す。
  5. genContextのcode evaluation stateを、そのexecution contextについてevaluationがresumedされたときに、closureがargumentsなしでcallされるように設定する。
  6. gen.[[AsyncGeneratorContext]]genContextに設定する。
  7. gen.[[AsyncGeneratorQueue]]をnew empty Listに設定する。
  8. unusedを返す。

27.9.3.3 AsyncGeneratorValidate ( gen, genBrand )

The abstract operation AsyncGeneratorValidate takes arguments gen (an ECMAScript language value) and genBrand (a String or empty) and returns either a normal completion containing unused or a throw completion. It performs the following steps when called:

  1. RequireInternalSlot(gen, [[AsyncGeneratorContext]])を実行する。
  2. RequireInternalSlot(gen, [[AsyncGeneratorState]])を実行する。
  3. RequireInternalSlot(gen, [[AsyncGeneratorQueue]])を実行する。
  4. gen.[[GeneratorBrand]]genBrandでないなら、TypeError例外をthrowする。
  5. unusedを返す。

27.9.3.4 AsyncGeneratorEnqueue ( gen, completion, promiseCapability )

The abstract operation AsyncGeneratorEnqueue takes arguments gen (an AsyncGenerator), completion (a Completion Record), and promiseCapability (a PromiseCapability Record) and returns unused. It performs the following steps when called:

  1. requestAsyncGeneratorRequest { [[Completion]]: completion, [[Capability]]: promiseCapability }とする。
  2. requestgen.[[AsyncGeneratorQueue]]にappendする。
  3. unusedを返す。

27.9.3.5 AsyncGeneratorCompleteStep ( gen, completion, done [ , realm ] )

The abstract operation AsyncGeneratorCompleteStep takes arguments gen (an AsyncGenerator), completion (a Completion Record), and done (a Boolean) and optional argument realm (a Realm Record) and returns unused. It performs the following steps when called:

  1. Assert: gen.[[AsyncGeneratorQueue]]はemptyでない。
  2. nextgen.[[AsyncGeneratorQueue]]のfirst elementとする。
  3. gen.[[AsyncGeneratorQueue]]からfirst elementをremoveする。
  4. promiseCapabilitynext.[[Capability]]とする。
  5. valuecompletion.[[Value]]とする。
  6. completionthrow completionなら、
    1. Call(promiseCapability.[[Reject]], undefined, « value »)を実行する。
  7. そうでなければ、
    1. Assert: completionnormal completionである。
    2. realmが存在するなら、
      1. oldRealmrunning execution contextRealmとする。
      2. running execution contextRealmrealmに設定する。
      3. iteratorResultCreateIteratorResultObject(value, done)とする。
      4. running execution contextRealmoldRealmに設定する。
    3. そうでなければ、
      1. iteratorResultCreateIteratorResultObject(value, done)とする。
    4. Call(promiseCapability.[[Resolve]], undefined, « iteratorResult »)を実行する。
  8. unusedを返す。

27.9.3.6 AsyncGeneratorResume ( gen, completion )

The abstract operation AsyncGeneratorResume takes arguments gen (an AsyncGenerator) and completion (a Completion Record) and returns unused. It performs the following steps when called:

  1. Assert: gen.[[AsyncGeneratorState]]suspended-startまたはsuspended-yieldのいずれかである。
  2. genContextgen.[[AsyncGeneratorContext]]とする。
  3. gen.[[AsyncGeneratorState]]executingに設定する。
  4. RunSuspendedContext(genContext, completion)を実行する。
  5. unusedを返す。

27.9.3.7 AsyncGeneratorUnwrapYieldResumption ( resumptionValue )

The abstract operation AsyncGeneratorUnwrapYieldResumption takes argument resumptionValue (a Completion Record) and returns either a normal completion containing an ECMAScript language value or an abrupt completion. It performs the following steps when called:

  1. resumptionValuereturn completionでないなら、? resumptionValueを返す。
  2. awaitedCompletion(Await(resumptionValue.[[Value]]))とする。
  3. awaitedthrow completionなら、? awaitedを返す。
  4. Assert: awaitednormal completionである。
  5. ReturnCompletion(awaited.[[Value]])を返す。

27.9.3.8 AsyncGeneratorYield ( arg )

The abstract operation AsyncGeneratorYield takes argument arg (an ECMAScript language value) and returns either a normal completion containing an ECMAScript language value or an abrupt completion. It performs the following steps when called:

  1. genContextを、実行中の実行コンテキストとする。
  2. Assert: genContextはジェネレータの実行コンテキストである。
  3. genを、genContextのGeneratorコンポーネントの値とする。
  4. Assert: GetGeneratorKind()はasyncである。
  5. completionを、NormalCompletion(arg)とする。
  6. Assert: 実行コンテキストスタックには少なくとも2つの要素がある。
  7. previousContextを、実行コンテキストスタックの先頭から2番目の要素とする。
  8. previousRealmを、previousContextRealmとする。
  9. AsyncGeneratorCompleteStep(gen, completion, false, previousRealm)を実行する。
  10. queueを、gen.[[AsyncGeneratorQueue]]とする。
  11. queueが空でない場合、
    1. NOTE: 実行はジェネレータを中断せずに継続する。
    2. toYieldを、queueの最初の要素とする。
    3. resumptionValueを、Completion(toYield.[[Completion]])とする。
    4. Return ? AsyncGeneratorUnwrapYieldResumption(resumptionValue)。
  12. gen.[[AsyncGeneratorState]]suspended-yieldに設定する。
  13. resumptionValueを、Completion(RunCallerContext(undefined))とする。
  14. Return ? AsyncGeneratorUnwrapYieldResumption(resumptionValue)。

27.9.3.9 AsyncGeneratorAwaitReturn ( gen )

The abstract operation AsyncGeneratorAwaitReturn takes argument gen (an AsyncGenerator) and returns unused. It performs the following steps when called:

  1. Assert: gen.[[AsyncGeneratorState]]draining-queueである。
  2. queuegen.[[AsyncGeneratorQueue]]とする。
  3. Assert: queueはemptyでない。
  4. nextqueueのfirst elementとする。
  5. completionCompletion(next.[[Completion]])とする。
  6. Assert: completionreturn completionである。
  7. promiseCompletionCompletion(PromiseResolve(%Promise%, completion.[[Value]]))とする。
  8. promiseCompletionabrupt completionなら、
    1. AsyncGeneratorCompleteStep(gen, promiseCompletion, true)を実行する。
    2. AsyncGeneratorDrainQueue(gen)を実行する。
    3. unusedを返す。
  9. Assert: promiseCompletionnormal completionである。
  10. promisepromiseCompletion.[[Value]]とする。
  11. fulfilledClosureを、parameters (value)を持ち、genをcaptureし、呼び出されたときに以下のstepsを実行するnew Abstract Closureとする:
    1. Assert: gen.[[AsyncGeneratorState]]draining-queueである。
    2. resultNormalCompletion(value)とする。
    3. AsyncGeneratorCompleteStep(gen, result, true)を実行する。
    4. AsyncGeneratorDrainQueue(gen)を実行する。
    5. NormalCompletion(undefined)を返す。
  12. onFulfilledCreateBuiltinFunction(fulfilledClosure, 1, "", « »)とする。
  13. rejectedClosureを、parameters (reason)を持ち、genをcaptureし、呼び出されたときに以下のstepsを実行するnew Abstract Closureとする:
    1. Assert: gen.[[AsyncGeneratorState]]draining-queueである。
    2. resultThrowCompletion(reason)とする。
    3. AsyncGeneratorCompleteStep(gen, result, true)を実行する。
    4. AsyncGeneratorDrainQueue(gen)を実行する。
    5. NormalCompletion(undefined)を返す。
  14. onRejectedCreateBuiltinFunction(rejectedClosure, 1, "", « »)とする。
  15. PerformPromiseThen(promise, onFulfilled, onRejected)を実行する。
  16. unusedを返す。

27.9.3.10 AsyncGeneratorDrainQueue ( gen )

The abstract operation AsyncGeneratorDrainQueue takes argument gen (an AsyncGenerator) and returns unused. これは、return completionを保持するAsyncGeneratorRequestにencounterするまで、generatorのAsyncGeneratorQueueをdrainする。 It performs the following steps when called:

  1. Assert: gen.[[AsyncGeneratorState]]draining-queueである。
  2. queuegen.[[AsyncGeneratorQueue]]とする。
  3. queueがemptyでない間、繰り返す:
    1. nextqueueのfirst elementとする。
    2. completionCompletion(next.[[Completion]])とする。
    3. completionreturn completionなら、
      1. AsyncGeneratorAwaitReturn(gen)を実行する。
      2. unusedを返す。
    4. completionnormal completionなら、
      1. completionNormalCompletion(undefined)に設定する。
    5. AsyncGeneratorCompleteStep(gen, completion, true)を実行する。
  4. gen.[[AsyncGeneratorState]]completedに設定する。
  5. unusedを返す。

27.10 AsyncFunctionオブジェクト

AsyncFunctionsは、通常、AsyncFunctionDeclarationAsyncFunctionExpressionAsyncMethod、およびAsyncArrowFunctionを評価することによって作成されるfunctionsである。これらは%AsyncFunction% intrinsicをcallすることによって作成されることもある。

27.10.1 AsyncFunctionコンストラクタ

AsyncFunction constructorは:

  • %AsyncFunction%である。
  • Functionのsubclassである。
  • constructorとしてではなくfunctionとして呼び出されたときにnew AsyncFunctionをcreateしてinitializeする。したがって、function call AsyncFunction(…)は、同じargumentsを持つobject creation expression new AsyncFunction(…)と等価である。
  • class definitionのextends clauseのvalueとして使用してもよい。指定されたAsyncFunction behaviourをinheritすることを意図するsubclass constructorsは、built-in async function behaviourに必要なinternal slotsでsubclass instanceをcreateしてinitializeするために、AsyncFunction constructorへのsuper callを含まなければならない。async function objectsをdefineするすべてのECMAScript syntactic formsは、AsyncFunctionのdirect instancesを作成する。AsyncFunction subclassesのinstancesを作成するsyntactic meansは存在しない。

27.10.1.1 AsyncFunction ( ...paramArgs, bodyArg )

最後のargument(ある場合)は、async functionのbody(executable code)を指定する。それより前のargumentsはformal parametersを指定する。

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

  1. activeFuncactive function objectとする。
  2. bodyArgが存在しないなら、bodyArgをempty Stringに設定する。
  3. CreateDynamicFunction(activeFunc, NewTarget, async, paramArgs, bodyArg)を返す。
Note
20.2.1.1NOTEを参照。

27.10.2 AsyncFunctionコンストラクタのプロパティ

AsyncFunction constructorは:

  • Function constructorからinheritするstandard built-in function objectである。
  • valueが%Function%である[[Prototype]] internal slotを持つ。
  • valueが1𝔽である"length" propertyを持つ。
  • valueが"AsyncFunction"である"name" propertyを持つ。
  • 以下のpropertiesを持つ:

27.10.2.1 AsyncFunction.prototype

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

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

27.10.3 AsyncFunction Prototype Objectのプロパティ

AsyncFunction prototype objectは:

27.10.3.1 AsyncFunction.prototype.constructor

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

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

27.10.3.2 AsyncFunction.prototype [ %Symbol.toStringTag% ]

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

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

27.10.4 AsyncFunctionインスタンス

すべてのAsyncFunction instanceはECMAScript function objectであり、Table 26に列挙されるinternal slotsを持つ。そのようなすべてのinstancesにおける[[IsClassConstructor]] internal slotのvalueはfalseである。AsyncFunction instancesはconstructorsではなく、[[Construct]] internal methodを持たない。AsyncFunction instancesはconstructableでないため、prototype propertyを持たない。

各AsyncFunction instanceは以下のown propertiesを持つ:

27.10.4.1 length

20.2.4.1で与えられるFunction instancesの"length" propertyの仕様は、AsyncFunction instancesにも適用される。

27.10.4.2 name

20.2.4.2で与えられるFunction instancesの"name" propertyの仕様は、AsyncFunction instancesにも適用される。

27.10.5 Async Functions Abstract Operations

27.10.5.1 AsyncFunctionStart ( promiseCapability, asyncFuncBody )

The abstract operation AsyncFunctionStart takes arguments promiseCapability (a PromiseCapability Record) and asyncFuncBody (a FunctionBody Parse Node, an ExpressionBody Parse Node, or an Abstract Closure with no parameters) and returns unused. It performs the following steps when called:

  1. runningContextrunning execution contextとする。
  2. asyncContextrunningContextのcopyとする。
  3. NOTE: execution stateのcopyingは、AsyncBlockStartがそのexecutionをresumeするためにrequiredである。現在executing中のcontextをresumeすることはill-definedである。
  4. AsyncBlockStart(promiseCapability, asyncFuncBody, asyncContext)を実行する。
  5. unusedを返す。

27.10.5.2 AsyncBlockStart ( promiseCapability, asyncBody, asyncContext )

The abstract operation AsyncBlockStart takes arguments promiseCapability (a PromiseCapability Record), asyncBody (a Parse Node or an Abstract Closure with no parameters), and asyncContext (an execution context) and returns unused. It performs the following steps when called:

  1. closureを、parametersを持たず、promiseCapabilityおよびasyncBodyをcaptureし、呼び出されたときに以下のstepsを実行するnew Abstract Closureとする:
    1. acAsyncContextrunning execution contextとする。
    2. asyncBodyParse Nodeなら、
      1. resultCompletion(Evaluation of asyncBody)とする。
    3. そうでなければ、
      1. Assert: asyncBodyはparametersを持たないAbstract Closureである。
      2. resultCompletion(asyncBody())とする。
    4. Assert: ここにreturnした場合、async functionはexceptionをthrowしたか、implicitまたはexplicit returnを実行した。すべてのawaitingは完了している。
    5. acAsyncContextexecution context stackからremoveし、execution context stackのtopにあるexecution contextrunning execution contextとしてrestoreする。
    6. resultnormal completionなら、
      1. Call(promiseCapability.[[Resolve]], undefined, « undefined »)を実行する。
    7. そうでなく、resultreturn completionなら、
      1. Call(promiseCapability.[[Resolve]], undefined, « result.[[Value]] »)を実行する。
    8. そうでなければ、
      1. Assert: resultthrow completionである。
      2. Call(promiseCapability.[[Reject]], undefined, « result.[[Value]] »)を実行する。
    9. NormalCompletion(unused)を返す。
  2. asyncContextのcode evaluation stateを、そのexecution contextについてevaluationがresumedされたときに、closureがargumentsなしでcallされるように設定する。
  3. resultを ! RunSuspendedContext(asyncContext, NormalCompletion(empty)) とする。
  4. Assert: resultunusedである。
  5. NOTE: result valuesのpossible sourcesは、Await、またはasync functionが何もawaitしない場合は上のstep 1.iである。
  6. unusedを返す。

27.10.5.3 Await ( arg )

The abstract operation Await takes argument arg (an ECMAScript language value) and returns either a normal completion containing either an ECMAScript language value or empty, or a throw completion. It performs the following steps when called:

  1. asyncContextを、実行中の実行コンテキストとする。
  2. promiseを、? PromiseResolve(%Promise%, arg)とする。
  3. fulfilledClosureを、asyncContextをキャプチャし、呼び出されたときに次の手順を実行する、パラメータ(v)を持つ新しいAbstract Closureとする。
    1. Completion(RunSuspendedContext(asyncContext, NormalCompletion(v)))を実行する。
    2. NOTE: RunSuspendedContextによって返されるCompletion Recordは意図的に無視される。
    3. NormalCompletion(undefined)を返す。
  4. onFulfilledを、CreateBuiltinFunction(fulfilledClosure, 1, "", « »)とする。
  5. rejectedClosureを、asyncContextをキャプチャし、呼び出されたときに次の手順を実行する、パラメータ(reason)を持つ新しいAbstract Closureとする。
    1. Completion(RunSuspendedContext(asyncContext, ThrowCompletion(reason)))を実行する。
    2. NOTE: RunSuspendedContextによって返されるCompletion Recordは意図的に無視される。
    3. NormalCompletion(undefined)を返す。
  6. onRejectedを、CreateBuiltinFunction(rejectedClosure, 1, "", « »)とする。
  7. PerformPromiseThen(promise, onFulfilled, onRejected)を実行する。
  8. Return ? RunCallerContext(empty)。

28 Reflection

28.1 Reflectオブジェクト

Reflect objectは:

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

28.1.1 Reflect.apply ( target, thisArg, args )

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

  1. IsCallable(target)がfalseなら、TypeError例外をthrowする。
  2. argListを ? CreateListFromArrayLike(args) とする。
  3. PrepareForTailCall()を実行する。
  4. Call(target, thisArg, argList)を返す。

28.1.2 Reflect.construct ( target, args [ , newTarget ] )

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

  1. IsConstructor(target)がfalseなら、TypeError例外をthrowする。
  2. newTargetが存在しないなら、newTargettargetに設定する。
  3. そうでなく、IsConstructor(newTarget)がfalseなら、TypeError例外をthrowする。
  4. argListを ? CreateListFromArrayLike(args) とする。
  5. Construct(target, argList, newTarget)を返す。

28.1.3 Reflect.defineProperty ( target, key, attrs )

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

  1. targetがObjectでないなら、TypeError例外をthrowする。
  2. propertyKeyを ? ToPropertyKey(key) とする。
  3. propertyDescを ? ToPropertyDescriptor(attrs) とする。
  4. target.[[DefineOwnProperty]](propertyKey, propertyDesc)を返す。

28.1.4 Reflect.deleteProperty ( target, key )

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

  1. targetがObjectでないなら、TypeError例外をthrowする。
  2. propertyKeyを ? ToPropertyKey(key) とする。
  3. target.[[Delete]](propertyKey)を返す。

28.1.5 Reflect.get ( target, key [ , receiver ] )

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

  1. targetがObjectでないなら、TypeError例外をthrowする。
  2. propertyKeyを ? ToPropertyKey(key) とする。
  3. receiverが存在しないなら、
    1. receivertargetに設定する。
  4. target.[[Get]](propertyKey, receiver)を返す。

28.1.6 Reflect.getOwnPropertyDescriptor ( target, key )

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

  1. targetがObjectでないなら、TypeError例外をthrowする。
  2. propertyKeyを ? ToPropertyKey(key) とする。
  3. propertyDescを ? target.[[GetOwnProperty]](propertyKey) とする。
  4. FromPropertyDescriptor(propertyDesc)を返す。

28.1.7 Reflect.getPrototypeOf ( target )

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

  1. targetがObjectでないなら、TypeError例外をthrowする。
  2. target.[[GetPrototypeOf]]()を返す。

28.1.8 Reflect.has ( target, key )

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

  1. targetがObjectでないなら、TypeError例外をthrowする。
  2. propertyKeyを ? ToPropertyKey(key) とする。
  3. target.[[HasProperty]](propertyKey)を返す。

28.1.9 Reflect.isExtensible ( target )

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

  1. targetがObjectでないなら、TypeError例外をthrowする。
  2. target.[[IsExtensible]]()を返す。

28.1.10 Reflect.ownKeys ( target )

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

  1. targetがObjectでないなら、TypeError例外をthrowする。
  2. keysを ? target.[[OwnPropertyKeys]]() とする。
  3. CreateArrayFromList(keys)を返す。

28.1.11 Reflect.preventExtensions ( target )

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

  1. targetがObjectでないなら、TypeError例外をthrowする。
  2. target.[[PreventExtensions]]()を返す。

28.1.12 Reflect.set ( target, key, value [ , receiver ] )

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

  1. targetがObjectでないなら、TypeError例外をthrowする。
  2. propertyKeyを ? ToPropertyKey(key) とする。
  3. receiverが存在しないなら、
    1. receivertargetに設定する。
  4. target.[[Set]](propertyKey, value, receiver)を返す。

28.1.13 Reflect.setPrototypeOf ( target, proto )

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

  1. targetがObjectでないなら、TypeError例外をthrowする。
  2. protoがObjectでなく、かつprotonullでないなら、TypeError例外をthrowする。
  3. target.[[SetPrototypeOf]](proto)を返す。

28.1.14 Reflect [ %Symbol.toStringTag% ]

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

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

28.2 Proxyオブジェクト

28.2.1 Proxyコンストラクタ

Proxy constructorは:

  • %Proxy%である。
  • global object"Proxy" propertyのinitial valueである。
  • constructorとして呼び出されたときにnew Proxy objectをcreateしてinitializeする。
  • functionとして呼び出されることを意図しておらず、そのように呼び出された場合はexceptionをthrowする。

28.2.1.1 Proxy ( target, handler )

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

  1. NewTargetがundefinedなら、TypeError例外をthrowする。
  2. ProxyCreate(target, handler)を返す。

28.2.2 Proxyコンストラクタのプロパティ

Proxy constructorは:

  • valueが%Function.prototype%である[[Prototype]] internal slotを持つ。
  • Proxy objectsはinitializationを必要とする[[Prototype]] internal slotを持たないため、"prototype" propertyを持たない。
  • 以下のpropertiesを持つ:

28.2.2.1 Proxy.revocable ( target, handler )

このfunctionはrevocable Proxy objectを作成する。

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

  1. ProxyCreate(target, handler)をproxyとする。
  2. パラメータを持たず、何も捕捉せず、呼び出されたときに次のステップを実行する新しいAbstract ClosurerevokerClosureとする。
    1. アクティブな関数オブジェクトをactiveFuncとする。
    2. activeFunc.[[RevocableProxy]]revocableProxyとする。
    3. revocableProxynullである場合、NormalCompletion(undefined)を返す。
    4. activeFunc.[[RevocableProxy]]nullに設定する。
    5. Assert: revocableProxyProxy exotic objectである。
    6. revocableProxy.[[ProxyTarget]]nullに設定する。
    7. revocableProxy.[[ProxyHandler]]nullに設定する。
    8. NormalCompletion(undefined)を返す。
  3. CreateBuiltinFunction(revokerClosure, 0, "", « [[RevocableProxy]] »)をrevokerとする。
  4. revoker.[[RevocableProxy]]proxyに設定する。
  5. OrdinaryObjectCreate(%Object.prototype%)をresultとする。
  6. CreateDataPropertyOrThrow(result, "proxy", proxy)を実行する。
  7. CreateDataPropertyOrThrow(result, "revoke", revoker)を実行する。
  8. resultを返す。

28.3 Module Namespaceオブジェクト

Module Namespace Objectは、moduleのexported bindingsへのruntime property-based accessを提供するmodule namespace exotic objectである。Module Namespace Objectsにはconstructor functionは存在しない。代わりに、そのようなobjectは、NameSpaceImportを含むImportDeclarationによってimportされる各moduleについて作成される。

10.4.6でspecifiedされるpropertiesに加えて、各Module Namespace Objectは以下のown propertyを持つ:

28.3.1 %Symbol.toStringTag%

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

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

29 Memory Model

memory consistency model、またはmemory modelは、SharedArrayBufferにbackされたTypedArray instancesへのaccessおよびAtomics object上のmethodsを介して生じるShared Data Block eventsの可能なorderingsをspecifiedする。programにdata races(以下で定義)がない場合、eventsのorderingはsequentially consistentとして現れる、すなわち各agentからのactionsのinterleavingとして現れる。programにdata racesがある場合、shared memory operationsはsequentially inconsistentに見えることがある。例えば、programsはcausality-violating behaviourやその他のastonishmentsを示すことがある。これらのastonishmentsはcompiler transformsおよびCPUsのdesign(例:out-of-order executionおよびspeculation)から生じる。memory modelは、programがsequentially consistent behaviourを示すprecise conditionsと、data racesからreadされ得るpossible valuesの両方をdefineする。すなわち、undefined behaviourは存在しない。

memory modelは、evaluation中にSharedArrayBuffer上のabstract operationsまたはAtomics object上のmethodsによって導入されるMemory eventsに対するrelational constraintsとして定義される。

Note

このsectionは、SharedArrayBuffers上のabstract operationsによって導入されるMemory eventsに関するaxiomatic modelを提供する。強調すべき点として、このmodelは、本仕様の他の部分と異なり、algorithmicallyに表現できない。abstract operationsによるeventsのnondeterministic introductionは、ECMAScript evaluationのoperational semanticsとmemory modelのaxiomatic semanticsとの間のinterfaceである。これらのeventsのsemanticsは、evaluation内のすべてのeventsのgraphsをconsiderすることで定義される。これらはStatic SemanticsでもRuntime Semanticsでもない。demonstrated algorithmic implementationは存在せず、代わりにparticular event graphがallowedまたはdisallowedかをdetermineするconstraintsのsetが存在する。

29.1 Memory Modelの基礎

Shared memory accesses(readsおよびwrites)は、以下で定義されるatomic accessesとdata accessesという2つのgroupsに分けられる。Atomic accessesはsequentially consistentである、すなわちagent cluster内のすべてのagentsによって合意されるeventsのstrict total orderingが存在する。Non-atomic accessesには、すべてのagentsによって合意されるstrict total orderingは存在しない、すなわちunorderedである。

Note 1

release-acquireなど、sequentially consistentより弱くunorderedより強いorderingsはsupportされない。

Shared Data Block eventは、ReadSharedMemoryWriteSharedMemory、またはReadModifyWriteSharedMemory Recordのいずれかである。read eventは、ReadSharedMemoryまたはReadModifyWriteSharedMemoryのいずれかである。write eventは、WriteSharedMemoryまたはReadModifyWriteSharedMemoryのいずれかである。

Table 97: ReadSharedMemory Event Fields
Field Name Value Meaning
[[Order]] seq-cst or unordered memory modelによってeventにguaranteedされる最もweakなordering。
[[NoTear]] Boolean このeventが、このeventとequal memory rangeを持つ複数のwrite eventsからreadすることをallowedされるかどうか。
[[Block]] Shared Data Block eventがoperateするblock。
[[ByteIndex]] non-negative integer [[Block]]内のreadのbyte address。
[[ElementSize]] non-negative integer readのsize。
Table 98: WriteSharedMemory Event Fields
Field Name Value Meaning
[[Order]] seq-cst, unordered, or init memory modelによってeventにguaranteedされる最もweakなordering。
[[NoTear]] Boolean このeventが、このeventとequal memory rangeを持つ複数のread eventsからreadされることをallowedされるかどうか。
[[Block]] Shared Data Block eventがoperateするblock。
[[ByteIndex]] non-negative integer [[Block]]内のwriteのbyte address。
[[ElementSize]] non-negative integer writeのsize。
[[Payload]] byte valuesList 他のeventsによってreadされるbyte valuesList
Table 99: ReadModifyWriteSharedMemory Event Fields
Field Name Value Meaning
[[Order]] seq-cst Read-modify-write eventsは常にsequentially consistentである。
[[NoTear]] true Read-modify-write eventsはtearできない。
[[Block]] Shared Data Block eventがoperateするblock。
[[ByteIndex]] non-negative integer [[Block]]内のread-modify-writeのbyte address。
[[ElementSize]] non-negative integer read-modify-writeのsize。
[[Payload]] byte valuesList [[ModifyOp]]に渡されるbyte valuesList
[[ModifyOp]] read-modify-write modification function readされたbyte valuesListおよび[[Payload]]からmodified byte valuesListを返すAbstract Closure

Shared Data Block eventsは、abstract operationsまたはAtomics object上のmethodsによってcandidate execution Agent Events Recordsに導入される。一部のoperationsは、Synchronize eventsも導入する。これらはfieldsを持たず、他のeventsのpermitted orderingsを直接constrainするためだけに存在する。そして最後に、host-specific eventsが存在する。Memory eventは、Shared Data Block event、Synchronize event、またはそのようなhost-specific eventのいずれかである。

Shared Data Block event ememory rangeを、e.[[ByteIndex]](inclusive)からe.[[ByteIndex]] + e.[[ElementSize]](exclusive)までのinterval内のすべてのintegersのSetとする。2つのeventsのmemory rangesは、eventsが同じ[[Block]][[ByteIndex]]、および[[ElementSize]]を持つときequalである。2つのeventsのmemory rangesは、eventsが同じ[[Block]]を持ち、rangesがequalでなく、かつそのintersectionがnon-emptyであるときoverlappingである。2つのeventsのmemory rangesは、eventsが同じ[[Block]]を持たないか、またはそれらのrangesがequalでもoverlappingでもないときdisjointである。

Note 2

考慮されるべきhost-specific synchronizing eventsの例は:SharedArrayBufferをあるagentから別のagentへ送信すること(例:browserにおけるpostMessage)、agentsのstartingおよびstopping、ならびにshared memory以外のchannelsを介したagent cluster内のcommunicationである。particular execution executionについて、それらのeventsはhost-synchronizes-with strict partial orderを介してhostによって提供される。さらに、hostsis-agent-order-before Relationにparticipateするために、host-specific synchronizing eventsをexecution.[[EventList]]に追加できる。

Eventsは、以下で定義されるrelationsによってcandidate executions内でorderedされる。

29.2 Agent Events Records

Agent Events Recordは、以下のfieldsを持つRecordである。

Table 100: Agent Events Record Fields
Field Name Value Meaning
[[AgentSignifier]] agent signifier このorderingをevaluationのresultとして生じさせたagent
[[EventList]] Memory eventsList Eventsはevaluation中にlistへappendされる。
[[AgentSynchronizesWith]] Synchronize eventsのpairsのList operational semanticsによって導入されたSynchronize relationships。

29.3 Chosen Value Records

Chosen Value Recordは、以下のfieldsを持つRecordである。

Table 101: Chosen Value Record Fields
Field Name Value Meaning
[[Event]] Shared Data Block event このchosen valueのために導入されたReadSharedMemoryまたはReadModifyWriteSharedMemory event。
[[ChosenValue]] byte valuesList evaluation中にnondeterministically chosenされたbytes。

29.4 Candidate Executions

agent clusterのevaluationのcandidate executionは、以下のfieldsを持つRecordである。

Table 102: Candidate Execution Record Fields
Field Name Value Meaning
[[EventsRecords]] Agent Events RecordsList agentを、evaluation中にappendedされたMemory eventsListsへmapする。
[[ChosenValues]] Chosen Value RecordsList ReadSharedMemoryまたはReadModifyWriteSharedMemory eventsを、evaluation中にchosenされたbyte valuesListへmapする。

empty candidate executionは、そのfieldsがempty Listsであるcandidate execution Recordである。

29.5 Memory ModelのAbstract Operations

29.5.1 EventSet ( execution )

The abstract operation EventSet takes argument execution (a candidate execution) and returns a Set of Memory events. It performs the following steps when called:

  1. eventsをempty Setとする。
  2. execution.[[EventsRecords]]の各Agent Events Record eventsRecordについて、
    1. eventsRecord.[[EventList]]の各Memory event eventについて、
      1. eventeventsにaddする。
  3. eventsを返す。

29.5.2 SharedDataBlockEventSet ( execution )

The abstract operation SharedDataBlockEventSet takes argument execution (a candidate execution) and returns a Set of Shared Data Block events. It performs the following steps when called:

  1. eventsをempty Setとする。
  2. EventSet(execution)の各Memory event eventについて、
    1. eventShared Data Block eventなら、eventeventsにaddする。
  3. eventsを返す。

29.5.3 HostEventSet ( execution )

The abstract operation HostEventSet takes argument execution (a candidate execution) and returns a Set of Memory events. It performs the following steps when called:

  1. EventSet(execution)のうちSharedDataBlockEventSet(execution)に含まれないすべてのelementsを含むnew Setを返す。

29.5.4 ComposeWriteEventBytes ( execution, byteIndex, writes )

The abstract operation ComposeWriteEventBytes takes arguments execution (a candidate execution), byteIndex (a non-negative integer), and writes (a List of either WriteSharedMemory or ReadModifyWriteSharedMemory events) and returns a List of byte values. It performs the following steps when called:

  1. byteLocationbyteIndexとする。
  2. bytesReadをnew empty Listとする。
  3. writesの各element writeEventについて、
    1. Assert: writeEventはそのmemory range内にbyteLocationを持つ。
    2. payloadIndexbyteLocation - writeEvent.[[ByteIndex]]とする。
    3. writeEventWriteSharedMemory eventなら、
      1. bytewriteEvent.[[Payload]][payloadIndex]とする。
    4. そうでなければ、
      1. Assert: writeEventReadModifyWriteSharedMemory eventである。
      2. bytesValueOfReadEvent(execution, writeEvent)とする。
      3. bytesModifiedwriteEvent.[[ModifyOp]](bytes, writeEvent.[[Payload]])とする。
      4. bytebytesModified[payloadIndex]とする。
    5. bytebytesReadにappendする。
    6. byteLocationbyteLocation + 1に設定する。
  4. bytesReadを返す。
Note 1

read-modify-write modification [[ModifyOp]]は、ReadModifyWriteSharedMemory eventsを導入するAtomics object上のfunction propertiesによって与えられる。

Note 2

このabstract operationは、write eventsListbyte valuesListへcomposeする。これはReadSharedMemoryおよびReadModifyWriteSharedMemory eventsのevent semanticsで使用される。

29.5.5 ValueOfReadEvent ( execution, readEvent )

The abstract operation ValueOfReadEvent takes arguments execution (a candidate execution) and readEvent (a ReadSharedMemory or ReadModifyWriteSharedMemory event) and returns a List of byte values. It performs the following steps when called:

  1. writesexecutionにおけるreads-bytes-from(readEvent)とする。
  2. Assert: writesは、lengthがreadEvent.[[ElementSize]]にequalなWriteSharedMemoryまたはReadModifyWriteSharedMemory eventsのListである。
  3. ComposeWriteEventBytes(execution, readEvent.[[ByteIndex]], writes)を返す。

29.6 Candidate ExecutionsのRelations

以下のrelationsおよびmathematical functionsは、particular candidate executionにparameterizedされ、そのMemory eventsをorderする。

29.6.1 is-agent-order-before

candidate execution executionについて、そのis-agent-order-before Relationは、以下をsatisfyするMemory events上のleast Relationである。

  • events eventAおよびeventBについて、execution.[[EventsRecords]]内に、eventAeventBの両方を含むeventsRecord.[[EventList]]を持つ何らかのAgent Events Record eventsRecordがあり、かつeventsRecord.[[EventList]]List orderにおいてeventAeventBより前であるなら、eventAexecutionにおいてeventBのis-agent-order-beforeである。
Note

agentはevaluation中にper-agent strict total orderでeventsを導入する。これはそれらのstrict total ordersのunionである。

29.6.2 reads-bytes-from

candidate execution executionについて、そのreads-bytes-from functionは、SharedDataBlockEventSet(execution)内のMemory eventsSharedDataBlockEventSet(execution)内のeventsのListsへmappingするmathematical functionであり、以下のconditionsをsatisfyする。

candidate executionは常にreads-bytes-from functionをadmitする。

29.6.3 reads-from

candidate execution executionについて、そのreads-from Relationは、以下をsatisfyするMemory events上のleast Relationである。

  • events readEventおよびwriteEventについて、SharedDataBlockEventSet(execution)がreadEventwriteEventの両方を含み、かつexecutionにおけるreads-bytes-from(readEvent)がwriteEventを含むなら、readEventexecutionにおいてwriteEventからreads-fromする。

29.6.4 host-synchronizes-with

candidate execution executionについて、そのhost-synchronizes-with Relationは、少なくとも以下をsatisfyするhost-provided strict partial order on host-specific Memory eventsである。

  • eventAexecutionにおいてeventBとhost-synchronizes-withであるなら、HostEventSet(execution)はeventAおよびeventBを含む。
  • executionにおけるhost-synchronizes-withとis-agent-order-beforeのunionにcycleは存在しない。
Note 1

candidate execution execution内の2つのhost-specific events eventAおよびeventBについて、eventAexecutionにおいてeventBとhost-synchronizes-withであることは、eventAexecutionにおいてeventBhappens-beforeであることをimplyする。

Note 2

このRelationは、hostがHTML workers間のpostMessageなどの追加のsynchronization mechanismsを提供することをallowする。

29.6.5 synchronizes-with

candidate execution executionについて、そのsynchronizes-with Relationは、以下をsatisfyするMemory events上のleast Relationである。

  • events readEventおよびwriteEventについて、readEventexecutionにおいてwriteEventからreads-fromし、readEvent.[[Order]]seq-cstであり、writeEvent.[[Order]]seq-cstであり、かつreadEventwriteEventがequal memory rangesを持つなら、writeEventexecutionにおいてreadEventとsynchronizes-withである。
  • execution.[[EventsRecords]]の各element eventsRecordについて、以下がtrueである。
    • events eventAおよびeventBについて、eventsRecord.[[AgentSynchronizesWith]]が(eventA, eventB)を含むなら、eventAexecutionにおいてeventBとsynchronizes-withである。
  • イベント eventA および eventB について、execution 内で eventAeventBhost-synchronizes-with する場合、execution 内で eventAeventB と synchronizes-with する。
Note 1

memory model literatureにおけるconventionにより、candidate execution executionにおいては、read eventswrite eventsとsynchronizes-withするのではなく、write eventsread eventsとsynchronizes-withする。

Note 2

candidate execution executionにおいて、init eventsはこのRelationにparticipateせず、代わりにhappens-beforeによって直接constrainedされる。

Note 3

candidate execution executionにおいて、reads-fromによってrelatedされるすべてのseq-cst eventsがsynchronizes-withによってrelatedされるわけではない。equal memory rangesも持つeventsだけがsynchronizes-withによってrelatedされる。

Note 4

candidate execution execution内のShared Data Block events readEventおよびwriteEventについて、writeEventreadEventとsynchronizes-withである場合、readEventwriteEvent以外のwritesからreads-fromすることがある。

29.6.6 happens-before

candidate execution executionについて、そのhappens-before Relationは、以下をsatisfyするMemory events上のleast Relationである。

  • events eventAおよびeventBについて、以下のconditionsのいずれかがtrueなら、eventAexecutionにおいてeventBのhappens-beforeである。

    • eventAexecutionにおいてeventBis-agent-order-beforeである。
    • eventAexecutionにおいてeventBsynchronizes-withである。
    • SharedDataBlockEventSet(execution)がeventAeventBの両方を含み、eventA.[[Order]]initであり、かつeventAeventBがoverlapping memory rangesを持つ。
    • executionにおいて、eventAeventCのhappens-beforeであり、かつeventCeventBのhappens-beforeであるようなevent eventCが存在する。
Note

happens-beforeはagent-orderのsupersetであるため、candidate executionはECMAScriptのsingle-thread evaluation semanticsとconsistentである。

29.7 Valid Executionsのプロパティ

29.7.1 Valid Chosen Reads

candidate execution executionは、以下のalgorithmがtrueを返すならvalid chosen readsを持つ。

  1. SharedDataBlockEventSet(execution)の各ReadSharedMemoryまたはReadModifyWriteSharedMemory event readEventについて、
    1. chosenValueRecordを、[[Event]] fieldがreadEventであるexecution.[[ChosenValues]]のelementとする。
    2. chosenValuechosenValueRecord.[[ChosenValue]]とする。
    3. readValueValueOfReadEvent(execution, readEvent)とする。
    4. chosenLengthchosenValue内のelementsの数とする。
    5. readLengthreadValue内のelementsの数とする。
    6. chosenLengthreadLengthなら、
      1. falseを返す。
    7. 0(inclusive)からchosenLength(exclusive)までのinterval内の何らかのinteger iについて、chosenValue[i] ≠ readValue[i]なら、
      1. falseを返す。
  2. trueを返す。

29.7.2 Coherent Reads

candidate execution executionは、以下のalgorithmがtrueを返すならcoherent readsを持つ。

  1. SharedDataBlockEventSet(execution)の各ReadSharedMemoryまたはReadModifyWriteSharedMemory event readEventについて、
    1. writesexecutionにおけるreads-bytes-from(readEvent)とする。
    2. byteLocationreadEvent.[[ByteIndex]]とする。
    3. writesの各element writeEventについて、
      1. readEventexecutionにおいてwriteEventhappens-beforeであるなら、
        1. falseを返す。
      2. byteLocationをそのmemory range内に持つWriteSharedMemoryまたはReadModifyWriteSharedMemory event valueであって、executionにおいてwriteEventvaluehappens-beforeであり、かつvaluereadEventhappens-beforeであるものが存在するなら、
        1. falseを返す。
      3. byteLocationbyteLocation + 1に設定する。
  2. trueを返す。

29.7.3 Tear Free Reads

candidate execution executionは、以下のalgorithmがtrueを返すならtear free readsを持つ。

  1. SharedDataBlockEventSet(execution)の各ReadSharedMemoryまたはReadModifyWriteSharedMemory event readEventについて、
    1. readEvent.[[NoTear]]trueなら、
      1. Assert: readEvent.[[ByteIndex]]readEvent.[[ElementSize]]でdivideしたremainderは0である。
      2. executionにおいてreadEventwriteEventからreads-fromし、かつwriteEvent.[[NoTear]]trueであるような各Memory event writeEventについて、
        1. readEventwriteEventがequal memory rangesを持ち、valuewriteEventがequal memory rangesを持ち、value.[[NoTear]]trueであり、writeEventvalueが同じShared Data Block eventではなく、かつexecutionにおいてreadEventvalueからreads-fromするようなMemory event valueが存在するなら、
          1. falseを返す。
  2. trueを返す。
Note

Shared Data Block event[[NoTear]] fieldは、そのeventがinteger TypedArrayへのaccessを介して導入されたときtrueであり、floating point TypedArrayまたはDataViewへのaccessを介して導入されたときfalseである。

直観的には、このrequirementは、memory rangeinteger TypedArrayを介してaligned fashionでaccessされる場合、そのrange上のsingle write eventが、equal rangesを持つ他のwrite eventsとのdata raceにおいて“win”しなければならない、ということを述べている。よりpreciselyには、このrequirementは、aligned read eventが、すべてequal rangesを持つ複数のdifferent write eventsからのbytesでcomposeされたvalueをreadできない、ということを述べている。ただし、aligned read eventがoverlapping rangesを持つ複数のwrite eventsからreadすることは可能である。

29.7.4 Sequentially Consistent Atomics

candidate execution executionについて、is-memory-order-beforeは、以下をsatisfyするEventSet(execution)内のすべてのMemory eventsstrict total orderである。

  • events eventAおよびeventBについて、eventAexecutionにおいてeventBhappens-beforeであるなら、eventAexecutionにおいてeventBのis-memory-order-beforeである。
  • executionにおいてreadEventwriteEventからreads-fromするようなevents readEventおよびwriteEventについて、SharedDataBlockEventSet(execution)内にWriteSharedMemoryまたはReadModifyWriteSharedMemory event valueであって、value.[[Order]]seq-cstであり、writeEventexecutionにおいてvalueのis-memory-order-beforeであり、valueexecutionにおいてreadEventのis-memory-order-beforeであり、かつ以下のconditionsのいずれかがtrueであるものは存在しない。

    • writeEventexecutionにおいてreadEventsynchronizes-withであり、かつvaluereadEventがequal memory rangesを持つ。
    • writeEventreadEventhappens-beforeであり、かつvalueexecutionにおいてreadEventhappens-beforeであり、writeEvent.[[Order]]seq-cstであり、かつwriteEventvalueがequal memory rangesを持つ。
    • writeEventreadEventhappens-beforeであり、かつwriteEventexecutionにおいてvaluehappens-beforeであり、readEvent.[[Order]]seq-cstであり、かつvaluereadEventがequal memory rangesを持つ。
    Note 1

    このclauseはさらにequal memory ranges上のseq-cst eventsをconstrainする。

  • SharedDataBlockEventSet(execution)内の各WriteSharedMemoryまたはReadModifyWriteSharedMemory event writeEventについて、writeEvent.[[Order]]seq-cstなら、equal memory rangeを持ち、writeEventのmemory-order beforeであるReadSharedMemoryまたはReadModifyWriteSharedMemory eventsがSharedDataBlockEventSet(execution)内にinfinite number存在する、ということはない。

    Note 2

    このclauseはagentsに関するforward progress guaranteeと合わせて、equal memory rangeを持つseq-cst writesfinite time内にseq-cst readsにvisibleになるというliveness conditionをensureする。

candidate executionは、is-memory-order-before Relationをadmitするならsequentially consistent atomicsを持つ。

Note 3

is-memory-order-beforeはEventSet(execution)内のすべてのeventsを含むが、executionにおいてhappens-beforeまたはsynchronizes-withによってconstrainedされていないものは、order内のどこに現れてもallowedされる。

29.7.5 Valid Executions

candidate execution executionは、以下のすべてがtrueであるならvalid execution(または単にexecution)である。

すべてのprogramsには少なくとも1つのvalid executionが存在する。

29.8 Races

execution executionと、SharedDataBlockEventSet(execution)に含まれるevents eventAおよびeventBについて、以下のalgorithmがtrueを返すなら、eventAeventBraceにある。

  1. eventAeventBが同じShared Data Block eventでないなら、
    1. executionにおいてeventAeventBhappens-beforeであり、かつeventBeventAhappens-beforeである、ということが成り立たないなら、
      1. eventAWriteSharedMemoryまたはReadModifyWriteSharedMemory eventのいずれかであり、eventBWriteSharedMemoryまたはReadModifyWriteSharedMemory eventのいずれかであり、かつeventAeventBがdisjoint memory rangesを持たないなら、
        1. trueを返す。
      2. eventAexecutionにおいてeventBからreads-fromする、またはeventBexecutionにおいてeventAからreads-fromするなら、
        1. trueを返す。
  2. falseを返す。

29.9 Data Races

execution executionと、SharedDataBlockEventSet(execution)に含まれるevents eventAおよびeventBについて、以下のalgorithmがtrueを返すなら、eventAeventBdata raceにある。

  1. eventAeventBexecutionにおいてraceにあるなら、
    1. eventA.[[Order]]seq-cstでない、またはeventB.[[Order]]seq-cstでないなら、
      1. trueを返す。
    2. eventAeventBがoverlapping memory rangesを持つなら、
      1. trueを返す。
  2. falseを返す。

29.10 Data Race Freedom

execution executionは、SharedDataBlockEventSet(execution)内にdata raceにある2つのeventsが存在しないなら、data race freeである。

programは、そのすべてのexecutionsがdata race freeであるならdata race freeである。

memory modelは、data race free programsについて、すべてのeventsのsequential consistencyをguaranteeする。

29.11 Shared Memory Guidelines

Note 1

以下は、shared memoryを扱うECMAScript programmers向けのguidelinesである。

programsはdata race freeに保つこと、すなわち同じmemory location上でconcurrent non-atomic operationsが発生することがimpossibleになるようにすることを推奨する。Data race free programsは、各agentのevaluation semanticsにおける各stepが互いにinterleavedされるinterleaving semanticsを持つ。data race free programsについては、memory modelのdetailsを理解する必要はない。そのdetailsは、より良いECMAScriptを書く助けとなるintuitionを構築する可能性が低い。

より一般には、programがdata race freeでない場合でも、atomic operationsがdata racesに関与せず、raceするoperationsがすべて同じaccess sizeを持つ限り、predictable behaviourを持つことがある。atomicsがracesに関与しないようにarrangeする最も単純な方法は、atomic operationsとnon-atomic operationsによってdifferent memory cellsが使用され、異なるsizesのatomic accessesが同じcellsを同時にaccessするために使用されないことをensureすることである。Effectively、programはshared memoryを可能な限りstrongly typedとして扱うべきである。raceするnon-atomic accessesのorderingおよびtimingに依存することは依然としてできないが、memoryがstrongly typedとして扱われるなら、racing accessesは“tear”しない(それらのvaluesのbitsが混ざらない)。

Note 2

以下は、shared memoryを使用するprogramsに対するcompiler transformationsを書くECMAScript implementers向けのguidelinesである。

multi-agent program内の各agentのperformanceがsingle-agent settingにおけるperformanceと同じくらい良くなることをensureするために、single-agent settingでvalidなほとんどのprogram transformationsをmulti-agent settingでもallowすることが望ましい。しばしばこれらのtransformationsはjudgeしにくい。ここでは、normativeとして扱われることを意図した(memory modelによってimpliedされる、またはmemory modelがimplyするものよりstrongerであるという意味で)program transformationsに関するいくつかのrulesをoutlineするが、exhaustiveではない可能性が高い。これらのrulesは、is-agent-order-before Relationを構成するMemory eventsのintroductionsにprecedeするprogram transformationsにapplyされることを意図している。

agent-order sliceを、single agentにpertainingするis-agent-order-before Relationのsubsetとする。

read eventpossible read valuesを、すべてのvalid executionsにわたるそのeventについてのValueOfReadEventのすべてのvaluesのsetとする。

shared memoryがない場合にvalidなagent-order sliceの任意のtransformationは、以下のexceptionsを除き、shared memoryがある場合にもvalidである。

  • Atomics are carved in stone:Program transformationsは、[[Order]]seq-cstであるShared Data Block eventsis-agent-order-before Relationからremoveさせてはならず、互いに対してreorderedさせてはならず、また[[Order]]unorderedであるeventsに対してagent-order slice内でreorderedさせてはならない。

    (実際には、reorderingsの禁止は、compilerに、すべてのseq-cst operationがsynchronizationであり、final is-memory-order-before Relationにincludedされるとassumeすることを強制する。これは通常、inter-agent program analysisがない場合にいずれにせよassumeしなければならないことである。また、calleeのmemory-orderへのeffectsがunknownであるすべてのcallがseq-cst operationsを含む可能性があるとcompilerにassumeさせる。)

  • Reads must be stable:任意のgiven shared memory readは、execution内でsingle valueのみをobserveしなければならない。

    (例えば、program内でsemanticallyにはsingle readであるものが複数回executedされた場合、その後programはreadされたvaluesのうち1つだけをobserveすることをallowedされる。rematerializationとして知られるtransformationはこのruleにviolateする可能性がある。)

  • Writes must be stable:shared memoryへのすべてのobservable writesは、execution内のprogram semanticsからfollowしなければならない。

    (例えば、transformationは、より小さいdatumを書くためにより大きなlocation上のread-modify-write operationsを使用すること、programがwriteできなかったvalueをmemoryにwriteすること、またはreadされたlocationがread後に別のagentによってoverwrittenされた可能性がある場合に、そのlocationへjust-read valueを書き戻すことなどにより、特定のobservable writesをintroduceしてはならない。)

  • Possible read values must be non-empty:Program transformationsは、shared memory readのpossible read valuesをemptyにしてはならない。

    (counterintuitively、このruleはeffectとしてwrites上のtransformationsを制限する。なぜなら、writesはread eventsによってreadされる限りにおいてmemory model内でforceを持つからである。例えば、writesは2つのseq-cst operationsの間でmovedおよびcoalescedされ、時にはreorderedされることがあるが、transformationはlocationをupdatesするすべてのwritesをremoveしてはならない;何らかのwriteはpreservedされなければならない。)

validのままであるtransformationsの例は:同じlocationからの複数のnon-atomic readsをmergeすること、non-atomic readsをreorderすること、speculative non-atomic readsをintroduceすること、同じlocationへの複数のnon-atomic writesをmergeすること、different locationsへのnon-atomic writesをreorderすること、およびterminationに影響する場合でもnon-atomic readsをloopsの外へhoistすること、である。一般に、aliased TypedArraysによりlocationsがdifferentであることをproveしにくくなる点に注意。

Note 3

以下は、shared memory accessesのためにmachine codeを生成するECMAScript implementers向けのguidelinesである。

memory modelsがARMまたはPowerのものと同程度以上にweakでないarchitecturesについては、non-atomic storesおよびloadsはtarget architecture上のbare storesおよびloadsへcompileしてよい。Atomic storesおよびloadsはsequential consistencyをguaranteeするinstructionsへcompileされてよい。そのようなinstructionsが存在しない場合、bare storeまたはloadの両側にbarriersを配置するなど、memory barriersをemployすることになる。Read-modify-write operationsは、x86上のLOCK-prefixed instructions、ARM上のload-exclusive/store-exclusive instructions、およびPower上のload-link/store-conditional instructionsなど、target architecture上のread-modify-write instructionsへcompileされてよい。

Specifically、memory modelは以下のようなcode generationをallowすることを意図している。

  • program内のすべてのatomic operationはnecessaryであるとassumedされる。
  • Atomic operationsは互いに、またはnon-atomic operationsとrearrangedされない。
  • Functionsは常にatomic operationsをperformするとassumedされる。
  • Atomic operationsは、larger data上のread-modify-write operationsとしては決してimplementedされず、platformがappropriate sizeのatomic operationsを持たない場合にはnon-lock-free atomicsとしてimplementedされる。(すべてのplatformがevery interesting sizeのnormal memory access operationsを持つことは既にassumeしている。)

Naive code generationはこれらのpatternsを使用する:

  • Regular loadsおよびstoresはsingle loadおよびstore instructionsへcompileされる。
  • Lock-free atomic loadsおよびstoresは、full(sequentially consistent)fence、regular loadまたはstore、およびfull fenceへcompileされる。
  • Lock-free atomic read-modify-write accessesは、full fence、atomic read-modify-write instruction sequence、およびfull fenceへcompileされる。
  • Non-lock-free atomicsは、spinlock acquire、full fence、一連のnon-atomic loadおよびstore instructions、full fence、およびspinlock releaseへcompileされる。

そのmappingは、memory range上のatomic operationがnon-atomic writeまたはdifferent sizeのatomic operationとraceしない限りcorrectである。ただし、それで必要十分である:memory modelは、raceにinvolvedしたatomic operationsをeffectively non-atomic statusへdemoteする。一方で、naive mappingはかなりstrongである:atomic operationsをsequentially consistent fencesとして使用することをallowするが、memory modelは実際にはそれをguaranteeしない。

memory modelのconstraintsに従う限り、それらのbasic patternsへのlocal improvementsもallowedされる。例えば:

  • redundant fencesをremoveする明らかなplatform-dependent improvementsが存在する。例えば、x86ではlock-free atomic loadsおよびstoresの周囲のfencesは、storeにfollowingするfenceを除き常にomittedでき、lock-free read-modify-write instructionsにはfenceはneededでない。これらはすべてLOCK-prefixed instructionsを使用するからである。多くのplatformsにはseveral strengthsのfencesがあり、sequential consistencyをdestroyしない特定のcontextsではweaker fencesを使用できる。
  • Most modern platformsは、ECMAScript atomicsによってrequiredされるすべてのdata sizesについてlock-free atomicsをsupportする。non-lock-free atomicsが必要な場合、atomic operationのbodyをsurroundするfencesは通常、lockおよびunlock stepsにfoldできる。non-lock-free atomicsの最も単純なsolutionは、SharedArrayBufferごとにsingle lock wordを持つことである。
  • code analysisを必要とする、よりcomplicatedなplatform-dependent local improvementsも存在する。例えば、back-to-backの2つのfencesはしばしばsingle fenceと同じeffectを持つため、sequence内の2つのatomic operationsのためにcodeがgeneratedされる場合、それらをseparateするfenceはsingle fenceだけでよい。x86では、atomic storesをseparatingするsingle fenceでさえomittedできる。なぜならstoreにfollowingするfenceは、storeをsubsequent loadからseparateするためにのみneededだからである。

Annex A (informative) Grammar Summary

A.1 Lexical Grammar

SourceCharacter :: any Unicode code point InputElementDiv :: WhiteSpace LineTerminator Comment CommonToken DivPunctuator RightBracePunctuator InputElementRegExp :: WhiteSpace LineTerminator Comment CommonToken RightBracePunctuator RegularExpressionLiteral InputElementRegExpOrTemplateTail :: WhiteSpace LineTerminator Comment CommonToken RegularExpressionLiteral TemplateSubstitutionTail InputElementTemplateTail :: WhiteSpace LineTerminator Comment CommonToken DivPunctuator TemplateSubstitutionTail InputElementHashbangOrRegExp :: WhiteSpace LineTerminator Comment CommonToken HashbangComment RegularExpressionLiteral WhiteSpace :: <TAB> <VT> <FF> <ZWNBSP> <USP> LineTerminator :: <LF> <CR> <LS> <PS> LineTerminatorSequence :: <LF> <CR> [lookahead ≠ <LF>] <LS> <PS> <CR> <LF> Comment :: MultiLineComment SingleLineComment MultiLineComment :: /* MultiLineCommentCharsopt */ MultiLineCommentChars :: MultiLineNotAsteriskChar MultiLineCommentCharsopt * PostAsteriskCommentCharsopt PostAsteriskCommentChars :: MultiLineNotForwardSlashOrAsteriskChar MultiLineCommentCharsopt * PostAsteriskCommentCharsopt MultiLineNotAsteriskChar :: SourceCharacter but not * MultiLineNotForwardSlashOrAsteriskChar :: SourceCharacter but not one of / or * SingleLineComment :: // SingleLineCommentCharsopt SingleLineCommentChars :: SingleLineCommentChar SingleLineCommentCharsopt SingleLineCommentChar :: SourceCharacter but not LineTerminator HashbangComment :: #! SingleLineCommentCharsopt CommonToken :: IdentifierName PrivateIdentifier Punctuator NumericLiteral StringLiteral Template PrivateIdentifier :: # IdentifierName IdentifierName :: IdentifierStart IdentifierName IdentifierPart IdentifierStart :: IdentifierStartChar \ UnicodeEscapeSequence IdentifierPart :: IdentifierPartChar \ UnicodeEscapeSequence IdentifierStartChar :: UnicodeIDStart $ _ IdentifierPartChar :: UnicodeIDContinue $ AsciiLetter :: one of a b c d e f g h i j k l m n o p q r s t u v w x y z A B C D E F G H I J K L M N O P Q R S T U V W X Y Z UnicodeIDStart :: any Unicode code point with the Unicode property “ID_Start” UnicodeIDContinue :: any Unicode code point with the Unicode property “ID_Continue” ReservedWord :: one of await break case catch class const continue debugger default delete do else enum export extends false finally for function if import in instanceof new null return super switch this throw true try typeof var void while with yield Punctuator :: OptionalChainingPunctuator OtherPunctuator OptionalChainingPunctuator :: ?. [lookahead ∉ DecimalDigit] OtherPunctuator :: one of { ( ) [ ] . ... ; , < > <= >= == != === !== + - * % ** ++ -- << >> >>> & | ^ ! ~ && || ?? ? : = += -= *= %= **= <<= >>= >>>= &= |= ^= &&= ||= ??= => DivPunctuator :: / /= RightBracePunctuator :: } NullLiteral :: null BooleanLiteral :: true false NumericLiteralSeparator :: _ NumericLiteral :: DecimalLiteral DecimalBigIntegerLiteral NonDecimalIntegerLiteral[+Sep] NonDecimalIntegerLiteral[+Sep] BigIntLiteralSuffix LegacyOctalIntegerLiteral DecimalBigIntegerLiteral :: 0 BigIntLiteralSuffix NonZeroDigit DecimalDigits[+Sep]opt BigIntLiteralSuffix NonZeroDigit NumericLiteralSeparator DecimalDigits[+Sep] BigIntLiteralSuffix NonDecimalIntegerLiteral[Sep] :: BinaryIntegerLiteral[?Sep] OctalIntegerLiteral[?Sep] HexIntegerLiteral[?Sep] BigIntLiteralSuffix :: n DecimalLiteral :: DecimalIntegerLiteral . DecimalDigits[+Sep]opt ExponentPart[+Sep]opt . DecimalDigits[+Sep] ExponentPart[+Sep]opt DecimalIntegerLiteral ExponentPart[+Sep]opt DecimalIntegerLiteral :: 0 NonZeroDigit NonZeroDigit NumericLiteralSeparatoropt DecimalDigits[+Sep] NonOctalDecimalIntegerLiteral DecimalDigits[Sep] :: DecimalDigit DecimalDigits[?Sep] DecimalDigit [+Sep] DecimalDigits[+Sep] NumericLiteralSeparator DecimalDigit DecimalDigit :: one of 0 1 2 3 4 5 6 7 8 9 NonZeroDigit :: one of 1 2 3 4 5 6 7 8 9 ExponentPart[Sep] :: ExponentIndicator SignedInteger[?Sep] ExponentIndicator :: one of e E SignedInteger[Sep] :: DecimalDigits[?Sep] + DecimalDigits[?Sep] - DecimalDigits[?Sep] BinaryIntegerLiteral[Sep] :: 0b BinaryDigits[?Sep] 0B BinaryDigits[?Sep] BinaryDigits[Sep] :: BinaryDigit BinaryDigits[?Sep] BinaryDigit [+Sep] BinaryDigits[+Sep] NumericLiteralSeparator BinaryDigit BinaryDigit :: one of 0 1 OctalIntegerLiteral[Sep] :: 0o OctalDigits[?Sep] 0O OctalDigits[?Sep] OctalDigits[Sep] :: OctalDigit OctalDigits[?Sep] OctalDigit [+Sep] OctalDigits[+Sep] NumericLiteralSeparator OctalDigit LegacyOctalIntegerLiteral :: 0 OctalDigit LegacyOctalIntegerLiteral OctalDigit NonOctalDecimalIntegerLiteral :: 0 NonOctalDigit LegacyOctalLikeDecimalIntegerLiteral NonOctalDigit NonOctalDecimalIntegerLiteral DecimalDigit LegacyOctalLikeDecimalIntegerLiteral :: 0 OctalDigit LegacyOctalLikeDecimalIntegerLiteral OctalDigit OctalDigit :: one of 0 1 2 3 4 5 6 7 NonOctalDigit :: one of 8 9 HexIntegerLiteral[Sep] :: 0x HexDigits[?Sep] 0X HexDigits[?Sep] HexDigits[Sep] :: HexDigit HexDigits[?Sep] HexDigit [+Sep] HexDigits[+Sep] NumericLiteralSeparator HexDigit HexDigit :: one of 0 1 2 3 4 5 6 7 8 9 a b c d e f A B C D E F StringLiteral :: " DoubleStringCharactersopt " ' SingleStringCharactersopt ' DoubleStringCharacters :: DoubleStringCharacter DoubleStringCharactersopt SingleStringCharacters :: SingleStringCharacter SingleStringCharactersopt DoubleStringCharacter :: SourceCharacter but not one of " or \ or LineTerminator <LS> <PS> \ EscapeSequence LineContinuation SingleStringCharacter :: SourceCharacter but not one of ' or \ or LineTerminator <LS> <PS> \ EscapeSequence LineContinuation LineContinuation :: \ LineTerminatorSequence EscapeSequence :: CharacterEscapeSequence 0 [lookahead ∉ DecimalDigit] LegacyOctalEscapeSequence NonOctalDecimalEscapeSequence HexEscapeSequence UnicodeEscapeSequence CharacterEscapeSequence :: SingleEscapeCharacter NonEscapeCharacter SingleEscapeCharacter :: one of ' " \ b f n r t v NonEscapeCharacter :: SourceCharacter but not one of EscapeCharacter or LineTerminator EscapeCharacter :: SingleEscapeCharacter DecimalDigit x u LegacyOctalEscapeSequence :: 0 [lookahead ∈ { 8, 9 }] NonZeroOctalDigit [lookahead ∉ OctalDigit] ZeroToThree OctalDigit [lookahead ∉ OctalDigit] FourToSeven OctalDigit ZeroToThree OctalDigit OctalDigit NonZeroOctalDigit :: OctalDigit but not 0 ZeroToThree :: one of 0 1 2 3 FourToSeven :: one of 4 5 6 7 NonOctalDecimalEscapeSequence :: one of 8 9 HexEscapeSequence :: x HexDigit HexDigit UnicodeEscapeSequence :: u Hex4Digits u{ CodePoint } Hex4Digits :: HexDigit HexDigit HexDigit HexDigit RegularExpressionLiteral :: / RegularExpressionBody / RegularExpressionFlags RegularExpressionBody :: RegularExpressionFirstChar RegularExpressionChars RegularExpressionChars :: [empty] RegularExpressionChars RegularExpressionChar RegularExpressionFirstChar :: RegularExpressionNonTerminator but not one of * or \ or / or [ RegularExpressionBackslashSequence RegularExpressionClass RegularExpressionChar :: RegularExpressionNonTerminator but not one of \ or / or [ RegularExpressionBackslashSequence RegularExpressionClass RegularExpressionBackslashSequence :: \ RegularExpressionNonTerminator RegularExpressionNonTerminator :: SourceCharacter but not LineTerminator RegularExpressionClass :: [ RegularExpressionClassChars ] RegularExpressionClassChars :: [empty] RegularExpressionClassChars RegularExpressionClassChar RegularExpressionClassChar :: RegularExpressionNonTerminator but not one of ] or \ RegularExpressionBackslashSequence RegularExpressionFlags :: [empty] RegularExpressionFlags IdentifierPartChar Template :: NoSubstitutionTemplate TemplateHead NoSubstitutionTemplate :: ` TemplateCharactersopt ` TemplateHead :: ` TemplateCharactersopt ${ TemplateSubstitutionTail :: TemplateMiddle TemplateTail TemplateMiddle :: } TemplateCharactersopt ${ TemplateTail :: } TemplateCharactersopt ` TemplateCharacters :: TemplateCharacter TemplateCharactersopt TemplateCharacter :: $ [lookahead ≠ {] \ TemplateEscapeSequence \ NotEscapeSequence LineContinuation LineTerminatorSequence SourceCharacter but not one of ` or \ or $ or LineTerminator TemplateEscapeSequence :: CharacterEscapeSequence 0 [lookahead ∉ DecimalDigit] HexEscapeSequence UnicodeEscapeSequence NotEscapeSequence :: 0 DecimalDigit DecimalDigit but not 0 x [lookahead ∉ HexDigit] x HexDigit [lookahead ∉ HexDigit] u [lookahead ∉ HexDigit] [lookahead ≠ {] u HexDigit [lookahead ∉ HexDigit] u HexDigit HexDigit [lookahead ∉ HexDigit] u HexDigit HexDigit HexDigit [lookahead ∉ HexDigit] u { [lookahead ∉ HexDigit] u { NotCodePoint [lookahead ∉ HexDigit] u { CodePoint [lookahead ∉ HexDigit] [lookahead ≠ }] NotCodePoint :: HexDigits[~Sep] but only if the MV of HexDigits > 0x10FFFF CodePoint :: HexDigits[~Sep] but only if the MV of HexDigits ≤ 0x10FFFF

A.2 Expressions

IdentifierReference[Yield, Await] : Identifier [~Yield] yield [~Await] await BindingIdentifier[Yield, Await] : Identifier yield await LabelIdentifier[Yield, Await] : Identifier [~Yield] yield [~Await] await Identifier : IdentifierName but not ReservedWord PrimaryExpression[Yield, Await] : this IdentifierReference[?Yield, ?Await] Literal ArrayLiteral[?Yield, ?Await] ObjectLiteral[?Yield, ?Await] FunctionExpression ClassExpression[?Yield, ?Await] GeneratorExpression AsyncFunctionExpression AsyncGeneratorExpression RegularExpressionLiteral TemplateLiteral[?Yield, ?Await, ~Tagged] CoverParenthesizedExpressionAndArrowParameterList[?Yield, ?Await] CoverParenthesizedExpressionAndArrowParameterList[Yield, Await] : ( Expression[+In, ?Yield, ?Await] ) ( Expression[+In, ?Yield, ?Await] , ) ( ) ( ... BindingIdentifier[?Yield, ?Await] ) ( ... BindingPattern[?Yield, ?Await] ) ( Expression[+In, ?Yield, ?Await] , ... BindingIdentifier[?Yield, ?Await] ) ( Expression[+In, ?Yield, ?Await] , ... BindingPattern[?Yield, ?Await] )

productionのinstanceを処理するとき、
PrimaryExpression[Yield, Await] : CoverParenthesizedExpressionAndArrowParameterList[?Yield, ?Await]
CoverParenthesizedExpressionAndArrowParameterListの解釈は、以下のgrammarを用いてrefineされる:

ParenthesizedExpression[Yield, Await] : ( Expression[+In, ?Yield, ?Await] )

 

Literal : NullLiteral BooleanLiteral NumericLiteral StringLiteral ArrayLiteral[Yield, Await] : [ Elisionopt ] [ ElementList[?Yield, ?Await] ] [ ElementList[?Yield, ?Await] , Elisionopt ] ElementList[Yield, Await] : Elisionopt AssignmentExpression[+In, ?Yield, ?Await] Elisionopt SpreadElement[?Yield, ?Await] ElementList[?Yield, ?Await] , Elisionopt AssignmentExpression[+In, ?Yield, ?Await] ElementList[?Yield, ?Await] , Elisionopt SpreadElement[?Yield, ?Await] Elision : , Elision , SpreadElement[Yield, Await] : ... AssignmentExpression[+In, ?Yield, ?Await] ObjectLiteral[Yield, Await] : { } { PropertyDefinitionList[?Yield, ?Await] } { PropertyDefinitionList[?Yield, ?Await] , } PropertyDefinitionList[Yield, Await] : PropertyDefinition[?Yield, ?Await] PropertyDefinitionList[?Yield, ?Await] , PropertyDefinition[?Yield, ?Await] PropertyDefinition[Yield, Await] : IdentifierReference[?Yield, ?Await] CoverInitializedName[?Yield, ?Await] PropertyName[?Yield, ?Await] : AssignmentExpression[+In, ?Yield, ?Await] MethodDefinition[?Yield, ?Await] ... AssignmentExpression[+In, ?Yield, ?Await] PropertyName[Yield, Await] : LiteralPropertyName ComputedPropertyName[?Yield, ?Await] LiteralPropertyName : IdentifierName StringLiteral NumericLiteral ComputedPropertyName[Yield, Await] : [ AssignmentExpression[+In, ?Yield, ?Await] ] CoverInitializedName[Yield, Await] : IdentifierReference[?Yield, ?Await] Initializer[+In, ?Yield, ?Await] Initializer[In, Yield, Await] : = AssignmentExpression[?In, ?Yield, ?Await] TemplateLiteral[Yield, Await, Tagged] : NoSubstitutionTemplate SubstitutionTemplate[?Yield, ?Await, ?Tagged] SubstitutionTemplate[Yield, Await, Tagged] : TemplateHead Expression[+In, ?Yield, ?Await] TemplateSpans[?Yield, ?Await, ?Tagged] TemplateSpans[Yield, Await, Tagged] : TemplateTail TemplateMiddleList[?Yield, ?Await, ?Tagged] TemplateTail TemplateMiddleList[Yield, Await, Tagged] : TemplateMiddle Expression[+In, ?Yield, ?Await] TemplateMiddleList[?Yield, ?Await, ?Tagged] TemplateMiddle Expression[+In, ?Yield, ?Await] MemberExpression[Yield, Await] : PrimaryExpression[?Yield, ?Await] MemberExpression[?Yield, ?Await] [ Expression[+In, ?Yield, ?Await] ] MemberExpression[?Yield, ?Await] . IdentifierName MemberExpression[?Yield, ?Await] TemplateLiteral[?Yield, ?Await, +Tagged] SuperProperty[?Yield, ?Await] MetaProperty new MemberExpression[?Yield, ?Await] Arguments[?Yield, ?Await] MemberExpression[?Yield, ?Await] . PrivateIdentifier SuperProperty[Yield, Await] : super [ Expression[+In, ?Yield, ?Await] ] super . IdentifierName MetaProperty : NewTarget ImportMeta NewTarget : new . target ImportMeta : import . meta NewExpression[Yield, Await] : MemberExpression[?Yield, ?Await] new NewExpression[?Yield, ?Await] CallExpression[Yield, Await] : CoverCallExpressionAndAsyncArrowHead[?Yield, ?Await] SuperCall[?Yield, ?Await] ImportCall[?Yield, ?Await] CallExpression[?Yield, ?Await] Arguments[?Yield, ?Await] CallExpression[?Yield, ?Await] [ Expression[+In, ?Yield, ?Await] ] CallExpression[?Yield, ?Await] . IdentifierName CallExpression[?Yield, ?Await] TemplateLiteral[?Yield, ?Await, +Tagged] CallExpression[?Yield, ?Await] . PrivateIdentifier

productionのinstanceを処理するとき、
CallExpression[Yield, Await] : CoverCallExpressionAndAsyncArrowHead[?Yield, ?Await]
CoverCallExpressionAndAsyncArrowHeadの解釈は、以下のgrammarを用いてrefineされる:

CallMemberExpression[Yield, Await] : MemberExpression[?Yield, ?Await] Arguments[?Yield, ?Await]

 

SuperCall[Yield, Await] : super Arguments[?Yield, ?Await] ImportCall[Yield, Await] : import ( AssignmentExpression[+In, ?Yield, ?Await] ,opt ) import ( AssignmentExpression[+In, ?Yield, ?Await] , AssignmentExpression[+In, ?Yield, ?Await] ,opt ) Arguments[Yield, Await] : ( ) ( ArgumentList[?Yield, ?Await] ) ( ArgumentList[?Yield, ?Await] , ) ArgumentList[Yield, Await] : AssignmentExpression[+In, ?Yield, ?Await] ... AssignmentExpression[+In, ?Yield, ?Await] ArgumentList[?Yield, ?Await] , AssignmentExpression[+In, ?Yield, ?Await] ArgumentList[?Yield, ?Await] , ... AssignmentExpression[+In, ?Yield, ?Await] OptionalExpression[Yield, Await] : MemberExpression[?Yield, ?Await] OptionalChain[?Yield, ?Await] CallExpression[?Yield, ?Await] OptionalChain[?Yield, ?Await] OptionalExpression[?Yield, ?Await] OptionalChain[?Yield, ?Await] OptionalChain[Yield, Await] : ?. Arguments[?Yield, ?Await] ?. [ Expression[+In, ?Yield, ?Await] ] ?. IdentifierName ?. TemplateLiteral[?Yield, ?Await, +Tagged] ?. PrivateIdentifier OptionalChain[?Yield, ?Await] Arguments[?Yield, ?Await] OptionalChain[?Yield, ?Await] [ Expression[+In, ?Yield, ?Await] ] OptionalChain[?Yield, ?Await] . IdentifierName OptionalChain[?Yield, ?Await] TemplateLiteral[?Yield, ?Await, +Tagged] OptionalChain[?Yield, ?Await] . PrivateIdentifier LeftHandSideExpression[Yield, Await] : NewExpression[?Yield, ?Await] CallExpression[?Yield, ?Await] OptionalExpression[?Yield, ?Await] UpdateExpression[Yield, Await] : LeftHandSideExpression[?Yield, ?Await] LeftHandSideExpression[?Yield, ?Await] [no LineTerminator here] ++ LeftHandSideExpression[?Yield, ?Await] [no LineTerminator here] -- ++ UnaryExpression[?Yield, ?Await] -- UnaryExpression[?Yield, ?Await] UnaryExpression[Yield, Await] : UpdateExpression[?Yield, ?Await] delete UnaryExpression[?Yield, ?Await] void UnaryExpression[?Yield, ?Await] typeof UnaryExpression[?Yield, ?Await] + UnaryExpression[?Yield, ?Await] - UnaryExpression[?Yield, ?Await] ~ UnaryExpression[?Yield, ?Await] ! UnaryExpression[?Yield, ?Await] [+Await] CoverAwaitExpressionAndAwaitUsingDeclarationHead[?Yield] CoverAwaitExpressionAndAwaitUsingDeclarationHead[Yield] : await UnaryExpression[?Yield, +Await]

生成規則のインスタンスを処理する際
UnaryExpression[Yield, Await] : [+Await] CoverAwaitExpressionAndAwaitUsingDeclarationHead[?Yield]
CoverAwaitExpressionAndAwaitUsingDeclarationHead の解釈は、次の文法を使用して精緻化される:

AwaitExpression[Yield] : await UnaryExpression[?Yield, +Await]

 

ExponentiationExpression[Yield, Await] : UnaryExpression[?Yield, ?Await] UpdateExpression[?Yield, ?Await] ** ExponentiationExpression[?Yield, ?Await] MultiplicativeExpression[Yield, Await] : ExponentiationExpression[?Yield, ?Await] MultiplicativeExpression[?Yield, ?Await] MultiplicativeOperator ExponentiationExpression[?Yield, ?Await] MultiplicativeOperator : one of * / % AdditiveExpression[Yield, Await] : MultiplicativeExpression[?Yield, ?Await] AdditiveExpression[?Yield, ?Await] + MultiplicativeExpression[?Yield, ?Await] AdditiveExpression[?Yield, ?Await] - MultiplicativeExpression[?Yield, ?Await] ShiftExpression[Yield, Await] : AdditiveExpression[?Yield, ?Await] ShiftExpression[?Yield, ?Await] << AdditiveExpression[?Yield, ?Await] ShiftExpression[?Yield, ?Await] >> AdditiveExpression[?Yield, ?Await] ShiftExpression[?Yield, ?Await] >>> AdditiveExpression[?Yield, ?Await] RelationalExpression[In, Yield, Await] : ShiftExpression[?Yield, ?Await] RelationalExpression[?In, ?Yield, ?Await] < ShiftExpression[?Yield, ?Await] RelationalExpression[?In, ?Yield, ?Await] > ShiftExpression[?Yield, ?Await] RelationalExpression[?In, ?Yield, ?Await] <= ShiftExpression[?Yield, ?Await] RelationalExpression[?In, ?Yield, ?Await] >= ShiftExpression[?Yield, ?Await] RelationalExpression[?In, ?Yield, ?Await] instanceof ShiftExpression[?Yield, ?Await] [+In] RelationalExpression[+In, ?Yield, ?Await] in ShiftExpression[?Yield, ?Await] [+In] PrivateIdentifier in ShiftExpression[?Yield, ?Await] EqualityExpression[In, Yield, Await] : RelationalExpression[?In, ?Yield, ?Await] EqualityExpression[?In, ?Yield, ?Await] == RelationalExpression[?In, ?Yield, ?Await] EqualityExpression[?In, ?Yield, ?Await] != RelationalExpression[?In, ?Yield, ?Await] EqualityExpression[?In, ?Yield, ?Await] === RelationalExpression[?In, ?Yield, ?Await] EqualityExpression[?In, ?Yield, ?Await] !== RelationalExpression[?In, ?Yield, ?Await] BitwiseANDExpression[In, Yield, Await] : EqualityExpression[?In, ?Yield, ?Await] BitwiseANDExpression[?In, ?Yield, ?Await] & EqualityExpression[?In, ?Yield, ?Await] BitwiseXORExpression[In, Yield, Await] : BitwiseANDExpression[?In, ?Yield, ?Await] BitwiseXORExpression[?In, ?Yield, ?Await] ^ BitwiseANDExpression[?In, ?Yield, ?Await] BitwiseORExpression[In, Yield, Await] : BitwiseXORExpression[?In, ?Yield, ?Await] BitwiseORExpression[?In, ?Yield, ?Await] | BitwiseXORExpression[?In, ?Yield, ?Await] LogicalANDExpression[In, Yield, Await] : BitwiseORExpression[?In, ?Yield, ?Await] LogicalANDExpression[?In, ?Yield, ?Await] && BitwiseORExpression[?In, ?Yield, ?Await] LogicalORExpression[In, Yield, Await] : LogicalANDExpression[?In, ?Yield, ?Await] LogicalORExpression[?In, ?Yield, ?Await] || LogicalANDExpression[?In, ?Yield, ?Await] CoalesceExpression[In, Yield, Await] : CoalesceExpressionHead[?In, ?Yield, ?Await] ?? BitwiseORExpression[?In, ?Yield, ?Await] CoalesceExpressionHead[In, Yield, Await] : CoalesceExpression[?In, ?Yield, ?Await] BitwiseORExpression[?In, ?Yield, ?Await] ShortCircuitExpression[In, Yield, Await] : LogicalORExpression[?In, ?Yield, ?Await] CoalesceExpression[?In, ?Yield, ?Await] ConditionalExpression[In, Yield, Await] : ShortCircuitExpression[?In, ?Yield, ?Await] ShortCircuitExpression[?In, ?Yield, ?Await] ? AssignmentExpression[+In, ?Yield, ?Await] : AssignmentExpression[?In, ?Yield, ?Await] AssignmentExpression[In, Yield, Await] : ConditionalExpression[?In, ?Yield, ?Await] [+Yield] YieldExpression[?In, ?Await] ArrowFunction[?In, ?Yield, ?Await] AsyncArrowFunction[?In, ?Yield, ?Await] LeftHandSideExpression[?Yield, ?Await] = AssignmentExpression[?In, ?Yield, ?Await] LeftHandSideExpression[?Yield, ?Await] AssignmentOperator AssignmentExpression[?In, ?Yield, ?Await] LeftHandSideExpression[?Yield, ?Await] &&= AssignmentExpression[?In, ?Yield, ?Await] LeftHandSideExpression[?Yield, ?Await] ||= AssignmentExpression[?In, ?Yield, ?Await] LeftHandSideExpression[?Yield, ?Await] ??= AssignmentExpression[?In, ?Yield, ?Await] AssignmentOperator : one of *= /= %= += -= <<= >>= >>>= &= ^= |= **=

特定の状況においてproductionのinstanceを処理するとき、
AssignmentExpression[In, Yield, Await] : LeftHandSideExpression[?Yield, ?Await] = AssignmentExpression[?In, ?Yield, ?Await]
LeftHandSideExpressionの解釈は、以下のgrammarを用いてrefineされる:

AssignmentPattern[Yield, Await] : ObjectAssignmentPattern[?Yield, ?Await] ArrayAssignmentPattern[?Yield, ?Await] ObjectAssignmentPattern[Yield, Await] : { } { AssignmentRestProperty[?Yield, ?Await] } { AssignmentPropertyList[?Yield, ?Await] } { AssignmentPropertyList[?Yield, ?Await] , AssignmentRestProperty[?Yield, ?Await]opt } ArrayAssignmentPattern[Yield, Await] : [ Elisionopt AssignmentRestElement[?Yield, ?Await]opt ] [ AssignmentElementList[?Yield, ?Await] ] [ AssignmentElementList[?Yield, ?Await] , Elisionopt AssignmentRestElement[?Yield, ?Await]opt ] AssignmentRestProperty[Yield, Await] : ... DestructuringAssignmentTarget[?Yield, ?Await] AssignmentPropertyList[Yield, Await] : AssignmentProperty[?Yield, ?Await] AssignmentPropertyList[?Yield, ?Await] , AssignmentProperty[?Yield, ?Await] AssignmentElementList[Yield, Await] : AssignmentElisionElement[?Yield, ?Await] AssignmentElementList[?Yield, ?Await] , AssignmentElisionElement[?Yield, ?Await] AssignmentElisionElement[Yield, Await] : Elisionopt AssignmentElement[?Yield, ?Await] AssignmentProperty[Yield, Await] : IdentifierReference[?Yield, ?Await] Initializer[+In, ?Yield, ?Await]opt PropertyName[?Yield, ?Await] : AssignmentElement[?Yield, ?Await] AssignmentElement[Yield, Await] : DestructuringAssignmentTarget[?Yield, ?Await] Initializer[+In, ?Yield, ?Await]opt AssignmentRestElement[Yield, Await] : ... DestructuringAssignmentTarget[?Yield, ?Await] DestructuringAssignmentTarget[Yield, Await] : LeftHandSideExpression[?Yield, ?Await]

 

Expression[In, Yield, Await] : AssignmentExpression[?In, ?Yield, ?Await] Expression[?In, ?Yield, ?Await] , AssignmentExpression[?In, ?Yield, ?Await]

A.3 Statements

Statement[Yield, Await, Return] : BlockStatement[?Yield, ?Await, ?Return] VariableStatement[?Yield, ?Await] EmptyStatement ExpressionStatement[?Yield, ?Await] IfStatement[?Yield, ?Await, ?Return] BreakableStatement[?Yield, ?Await, ?Return] ContinueStatement[?Yield, ?Await] BreakStatement[?Yield, ?Await] [+Return] ReturnStatement[?Yield, ?Await] WithStatement[?Yield, ?Await, ?Return] LabelledStatement[?Yield, ?Await, ?Return] ThrowStatement[?Yield, ?Await] TryStatement[?Yield, ?Await, ?Return] DebuggerStatement Declaration[Yield, Await] : HoistableDeclaration[?Yield, ?Await, ~Default] ClassDeclaration[?Yield, ?Await, ~Default] LexicalDeclaration[+In, ?Yield, ?Await] HoistableDeclaration[Yield, Await, Default] : FunctionDeclaration[?Yield, ?Await, ?Default] GeneratorDeclaration[?Yield, ?Await, ?Default] AsyncFunctionDeclaration[?Yield, ?Await, ?Default] AsyncGeneratorDeclaration[?Yield, ?Await, ?Default] BreakableStatement[Yield, Await, Return] : IterationStatement[?Yield, ?Await, ?Return] SwitchStatement[?Yield, ?Await, ?Return] BlockStatement[Yield, Await, Return] : Block[?Yield, ?Await, ?Return] Block[Yield, Await, Return] : { StatementList[?Yield, ?Await, ?Return]opt } StatementList[Yield, Await, Return] : StatementListItem[?Yield, ?Await, ?Return] StatementList[?Yield, ?Await, ?Return] StatementListItem[?Yield, ?Await, ?Return] StatementListItem[Yield, Await, Return] : Statement[?Yield, ?Await, ?Return] Declaration[?Yield, ?Await] LexicalDeclaration[In, Yield, Await] : LetOrConst BindingList[?In, ?Yield, ?Await, +Pattern] ; UsingDeclaration[?In, ?Yield, ?Await] [+Await] AwaitUsingDeclaration[?In, ?Yield] LetOrConst : let const UsingDeclaration[In, Yield, Await] : using [no LineTerminator here] BindingList[?In, ?Yield, ?Await, ~Pattern] ; AwaitUsingDeclaration[In, Yield] : CoverAwaitExpressionAndAwaitUsingDeclarationHead[?Yield] [no LineTerminator here] BindingList[?In, ?Yield, +Await, ~Pattern] ; BindingList[In, Yield, Await, Pattern] : LexicalBinding[?In, ?Yield, ?Await, ?Pattern] BindingList[?In, ?Yield, ?Await, ?Pattern] , LexicalBinding[?In, ?Yield, ?Await, ?Pattern] LexicalBinding[In, Yield, Await, Pattern] : BindingIdentifier[?Yield, ?Await] Initializer[?In, ?Yield, ?Await]opt [+Pattern] BindingPattern[?Yield, ?Await] Initializer[?In, ?Yield, ?Await]

生成規則のインスタンスを処理する際
AwaitUsingDeclaration[In, Yield] : CoverAwaitExpressionAndAwaitUsingDeclarationHead[?Yield] [no LineTerminator here] BindingList[?In, ?Yield, +Await, ~Pattern] ;
CoverAwaitExpressionAndAwaitUsingDeclarationHead の解釈は、次の文法を使用して精緻化される:

AwaitUsingDeclarationHead : await [no LineTerminator here] using

 

VariableStatement[Yield, Await] : var VariableDeclarationList[+In, ?Yield, ?Await] ; VariableDeclarationList[In, Yield, Await] : VariableDeclaration[?In, ?Yield, ?Await] VariableDeclarationList[?In, ?Yield, ?Await] , VariableDeclaration[?In, ?Yield, ?Await] VariableDeclaration[In, Yield, Await] : BindingIdentifier[?Yield, ?Await] Initializer[?In, ?Yield, ?Await]opt BindingPattern[?Yield, ?Await] Initializer[?In, ?Yield, ?Await] BindingPattern[Yield, Await] : ObjectBindingPattern[?Yield, ?Await] ArrayBindingPattern[?Yield, ?Await] ObjectBindingPattern[Yield, Await] : { } { BindingRestProperty[?Yield, ?Await] } { BindingPropertyList[?Yield, ?Await] } { BindingPropertyList[?Yield, ?Await] , BindingRestProperty[?Yield, ?Await]opt } ArrayBindingPattern[Yield, Await] : [ Elisionopt BindingRestElement[?Yield, ?Await]opt ] [ BindingElementList[?Yield, ?Await] ] [ BindingElementList[?Yield, ?Await] , Elisionopt BindingRestElement[?Yield, ?Await]opt ] BindingRestProperty[Yield, Await] : ... BindingIdentifier[?Yield, ?Await] BindingPropertyList[Yield, Await] : BindingProperty[?Yield, ?Await] BindingPropertyList[?Yield, ?Await] , BindingProperty[?Yield, ?Await] BindingElementList[Yield, Await] : BindingElisionElement[?Yield, ?Await] BindingElementList[?Yield, ?Await] , BindingElisionElement[?Yield, ?Await] BindingElisionElement[Yield, Await] : Elisionopt BindingElement[?Yield, ?Await] BindingProperty[Yield, Await] : SingleNameBinding[?Yield, ?Await] PropertyName[?Yield, ?Await] : BindingElement[?Yield, ?Await] BindingElement[Yield, Await] : SingleNameBinding[?Yield, ?Await] BindingPattern[?Yield, ?Await] Initializer[+In, ?Yield, ?Await]opt SingleNameBinding[Yield, Await] : BindingIdentifier[?Yield, ?Await] Initializer[+In, ?Yield, ?Await]opt BindingRestElement[Yield, Await] : ... BindingIdentifier[?Yield, ?Await] ... BindingPattern[?Yield, ?Await] EmptyStatement : ; ExpressionStatement[Yield, Await] : [lookahead ∉ { {, function, async [no LineTerminator here] function, class, let [ }] Expression[+In, ?Yield, ?Await] ; IfStatement[Yield, Await, Return] : if ( Expression[+In, ?Yield, ?Await] ) Statement[?Yield, ?Await, ?Return] else Statement[?Yield, ?Await, ?Return] if ( Expression[+In, ?Yield, ?Await] ) Statement[?Yield, ?Await, ?Return] [lookahead ≠ else] IterationStatement[Yield, Await, Return] : DoWhileStatement[?Yield, ?Await, ?Return] WhileStatement[?Yield, ?Await, ?Return] ForStatement[?Yield, ?Await, ?Return] ForInOfStatement[?Yield, ?Await, ?Return] DoWhileStatement[Yield, Await, Return] : do Statement[?Yield, ?Await, ?Return] while ( Expression[+In, ?Yield, ?Await] ) ; WhileStatement[Yield, Await, Return] : while ( Expression[+In, ?Yield, ?Await] ) Statement[?Yield, ?Await, ?Return] ForStatement[Yield, Await, Return] : for ( [lookahead ≠ let [] Expression[~In, ?Yield, ?Await]opt ; Expression[+In, ?Yield, ?Await]opt ; Expression[+In, ?Yield, ?Await]opt ) Statement[?Yield, ?Await, ?Return] for ( var VariableDeclarationList[~In, ?Yield, ?Await] ; Expression[+In, ?Yield, ?Await]opt ; Expression[+In, ?Yield, ?Await]opt ) Statement[?Yield, ?Await, ?Return] for ( LexicalDeclaration[~In, ?Yield, ?Await] Expression[+In, ?Yield, ?Await]opt ; Expression[+In, ?Yield, ?Await]opt ) Statement[?Yield, ?Await, ?Return] ForInOfStatement[Yield, Await, Return] : for ( [lookahead ≠ let [] LeftHandSideExpression[?Yield, ?Await] in Expression[+In, ?Yield, ?Await] ) Statement[?Yield, ?Await, ?Return] for ( var ForBinding[?Yield, ?Await, +Pattern] in Expression[+In, ?Yield, ?Await] ) Statement[?Yield, ?Await, ?Return] for ( ForDeclaration[?Yield, ?Await, ~Using] in Expression[+In, ?Yield, ?Await] ) Statement[?Yield, ?Await, ?Return] for ( [lookahead ∉ { let, async of }] LeftHandSideExpression[?Yield, ?Await] of AssignmentExpression[+In, ?Yield, ?Await] ) Statement[?Yield, ?Await, ?Return] for ( var ForBinding[?Yield, ?Await, +Pattern] of AssignmentExpression[+In, ?Yield, ?Await] ) Statement[?Yield, ?Await, ?Return] for ( [lookahead ≠ using of] ForDeclaration[?Yield, ?Await, +Using] of AssignmentExpression[+In, ?Yield, ?Await] ) Statement[?Yield, ?Await, ?Return] [+Await] for await ( [lookahead ≠ let] LeftHandSideExpression[?Yield, ?Await] of AssignmentExpression[+In, ?Yield, ?Await] ) Statement[?Yield, ?Await, ?Return] [+Await] for await ( var ForBinding[?Yield, ?Await, +Pattern] of AssignmentExpression[+In, ?Yield, ?Await] ) Statement[?Yield, ?Await, ?Return] [+Await] for await ( [lookahead ≠ using of] ForDeclaration[?Yield, ?Await, +Using] of AssignmentExpression[+In, ?Yield, ?Await] ) Statement[?Yield, ?Await, ?Return] ForDeclaration[Yield, Await, Using] : LetOrConst ForBinding[?Yield, ?Await, +Pattern] [+Using] using [no LineTerminator here] ForBinding[?Yield, ?Await, ~Pattern] [+Using, +Await] await [no LineTerminator here] using [no LineTerminator here] ForBinding[?Yield, +Await, ~Pattern] ForBinding[Yield, Await, Pattern] : BindingIdentifier[?Yield, ?Await] [+Pattern] BindingPattern[?Yield, ?Await] ContinueStatement[Yield, Await] : continue ; continue [no LineTerminator here] LabelIdentifier[?Yield, ?Await] ; BreakStatement[Yield, Await] : break ; break [no LineTerminator here] LabelIdentifier[?Yield, ?Await] ; ReturnStatement[Yield, Await] : return ; return [no LineTerminator here] Expression[+In, ?Yield, ?Await] ; WithStatement[Yield, Await, Return] : with ( Expression[+In, ?Yield, ?Await] ) Statement[?Yield, ?Await, ?Return] SwitchStatement[Yield, Await, Return] : switch ( Expression[+In, ?Yield, ?Await] ) CaseBlock[?Yield, ?Await, ?Return] CaseBlock[Yield, Await, Return] : { CaseClauses[?Yield, ?Await, ?Return]opt } { CaseClauses[?Yield, ?Await, ?Return]opt DefaultClause[?Yield, ?Await, ?Return] CaseClauses[?Yield, ?Await, ?Return]opt } CaseClauses[Yield, Await, Return] : CaseClause[?Yield, ?Await, ?Return] CaseClauses[?Yield, ?Await, ?Return] CaseClause[?Yield, ?Await, ?Return] CaseClause[Yield, Await, Return] : case Expression[+In, ?Yield, ?Await] : StatementList[?Yield, ?Await, ?Return]opt DefaultClause[Yield, Await, Return] : default : StatementList[?Yield, ?Await, ?Return]opt LabelledStatement[Yield, Await, Return] : LabelIdentifier[?Yield, ?Await] : LabelledItem[?Yield, ?Await, ?Return] LabelledItem[Yield, Await, Return] : Statement[?Yield, ?Await, ?Return] FunctionDeclaration[?Yield, ?Await, ~Default] ThrowStatement[Yield, Await] : throw [no LineTerminator here] Expression[+In, ?Yield, ?Await] ; TryStatement[Yield, Await, Return] : try Block[?Yield, ?Await, ?Return] Catch[?Yield, ?Await, ?Return] try Block[?Yield, ?Await, ?Return] Finally[?Yield, ?Await, ?Return] try Block[?Yield, ?Await, ?Return] Catch[?Yield, ?Await, ?Return] Finally[?Yield, ?Await, ?Return] Catch[Yield, Await, Return] : catch ( CatchParameter[?Yield, ?Await] ) Block[?Yield, ?Await, ?Return] catch Block[?Yield, ?Await, ?Return] Finally[Yield, Await, Return] : finally Block[?Yield, ?Await, ?Return] CatchParameter[Yield, Await] : BindingIdentifier[?Yield, ?Await] BindingPattern[?Yield, ?Await] DebuggerStatement : debugger ;

A.4 Functions and Classes

UniqueFormalParameters[Yield, Await] : FormalParameters[?Yield, ?Await] FormalParameters[Yield, Await] : [empty] FunctionRestParameter[?Yield, ?Await] FormalParameterList[?Yield, ?Await] FormalParameterList[?Yield, ?Await] , FormalParameterList[?Yield, ?Await] , FunctionRestParameter[?Yield, ?Await] FormalParameterList[Yield, Await] : FormalParameter[?Yield, ?Await] FormalParameterList[?Yield, ?Await] , FormalParameter[?Yield, ?Await] FunctionRestParameter[Yield, Await] : BindingRestElement[?Yield, ?Await] FormalParameter[Yield, Await] : BindingElement[?Yield, ?Await] FunctionDeclaration[Yield, Await, Default] : function BindingIdentifier[?Yield, ?Await] ( FormalParameters[~Yield, ~Await] ) { FunctionBody[~Yield, ~Await] } [+Default] function ( FormalParameters[~Yield, ~Await] ) { FunctionBody[~Yield, ~Await] } FunctionExpression : function BindingIdentifier[~Yield, ~Await]opt ( FormalParameters[~Yield, ~Await] ) { FunctionBody[~Yield, ~Await] } FunctionBody[Yield, Await] : FunctionStatementList[?Yield, ?Await] FunctionStatementList[Yield, Await] : StatementList[?Yield, ?Await, +Return]opt ArrowFunction[In, Yield, Await] : ArrowParameters[?Yield, ?Await] [no LineTerminator here] => ConciseBody[?In] ArrowParameters[Yield, Await] : BindingIdentifier[?Yield, ?Await] CoverParenthesizedExpressionAndArrowParameterList[?Yield, ?Await] ConciseBody[In] : [lookahead ≠ {] ExpressionBody[?In, ~Await] { FunctionBody[~Yield, ~Await] } ExpressionBody[In, Await] : AssignmentExpression[?In, ~Yield, ?Await]

productionのinstanceを処理するとき、
ArrowParameters[Yield, Await] : CoverParenthesizedExpressionAndArrowParameterList[?Yield, ?Await]
CoverParenthesizedExpressionAndArrowParameterListの解釈は、以下のgrammarを用いてrefineされる:

ArrowFormalParameters[Yield, Await] : ( UniqueFormalParameters[?Yield, ?Await] )

 

AsyncArrowFunction[In, Yield, Await] : async [no LineTerminator here] AsyncArrowBindingIdentifier[?Yield] [no LineTerminator here] => AsyncConciseBody[?In] CoverCallExpressionAndAsyncArrowHead[?Yield, ?Await] [no LineTerminator here] => AsyncConciseBody[?In] AsyncConciseBody[In] : [lookahead ≠ {] ExpressionBody[?In, +Await] { AsyncFunctionBody } AsyncArrowBindingIdentifier[Yield] : BindingIdentifier[?Yield, +Await] CoverCallExpressionAndAsyncArrowHead[Yield, Await] : MemberExpression[?Yield, ?Await] Arguments[?Yield, ?Await]

productionのinstanceを処理するとき、
AsyncArrowFunction[In, Yield, Await] : CoverCallExpressionAndAsyncArrowHead[?Yield, ?Await] [no LineTerminator here] => AsyncConciseBody[?In]
CoverCallExpressionAndAsyncArrowHeadの解釈は、以下のgrammarを用いてrefineされる:

AsyncArrowHead : async [no LineTerminator here] ArrowFormalParameters[~Yield, +Await]

 

MethodDefinition[Yield, Await] : ClassElementName[?Yield, ?Await] ( UniqueFormalParameters[~Yield, ~Await] ) { FunctionBody[~Yield, ~Await] } GeneratorMethod[?Yield, ?Await] AsyncMethod[?Yield, ?Await] AsyncGeneratorMethod[?Yield, ?Await] get ClassElementName[?Yield, ?Await] ( ) { FunctionBody[~Yield, ~Await] } set ClassElementName[?Yield, ?Await] ( PropertySetParameterList ) { FunctionBody[~Yield, ~Await] } PropertySetParameterList : FormalParameter[~Yield, ~Await] GeneratorDeclaration[Yield, Await, Default] : function * BindingIdentifier[?Yield, ?Await] ( FormalParameters[+Yield, ~Await] ) { GeneratorBody } [+Default] function * ( FormalParameters[+Yield, ~Await] ) { GeneratorBody } GeneratorExpression : function * BindingIdentifier[+Yield, ~Await]opt ( FormalParameters[+Yield, ~Await] ) { GeneratorBody } GeneratorMethod[Yield, Await] : * ClassElementName[?Yield, ?Await] ( UniqueFormalParameters[+Yield, ~Await] ) { GeneratorBody } GeneratorBody : FunctionBody[+Yield, ~Await] YieldExpression[In, Await] : yield yield [no LineTerminator here] AssignmentExpression[?In, +Yield, ?Await] yield [no LineTerminator here] * AssignmentExpression[?In, +Yield, ?Await] AsyncGeneratorDeclaration[Yield, Await, Default] : async [no LineTerminator here] function * BindingIdentifier[?Yield, ?Await] ( FormalParameters[+Yield, +Await] ) { AsyncGeneratorBody } [+Default] async [no LineTerminator here] function * ( FormalParameters[+Yield, +Await] ) { AsyncGeneratorBody } AsyncGeneratorExpression : async [no LineTerminator here] function * BindingIdentifier[+Yield, +Await]opt ( FormalParameters[+Yield, +Await] ) { AsyncGeneratorBody } AsyncGeneratorMethod[Yield, Await] : async [no LineTerminator here] * ClassElementName[?Yield, ?Await] ( UniqueFormalParameters[+Yield, +Await] ) { AsyncGeneratorBody } AsyncGeneratorBody : FunctionBody[+Yield, +Await] AsyncFunctionDeclaration[Yield, Await, Default] : async [no LineTerminator here] function BindingIdentifier[?Yield, ?Await] ( FormalParameters[~Yield, +Await] ) { AsyncFunctionBody } [+Default] async [no LineTerminator here] function ( FormalParameters[~Yield, +Await] ) { AsyncFunctionBody } AsyncFunctionExpression : async [no LineTerminator here] function BindingIdentifier[~Yield, +Await]opt ( FormalParameters[~Yield, +Await] ) { AsyncFunctionBody } AsyncMethod[Yield, Await] : async [no LineTerminator here] ClassElementName[?Yield, ?Await] ( UniqueFormalParameters[~Yield, +Await] ) { AsyncFunctionBody } AsyncFunctionBody : FunctionBody[~Yield, +Await] AwaitExpression[Yield] : await UnaryExpression[?Yield, +Await] ClassDeclaration[Yield, Await, Default] : class BindingIdentifier[?Yield, ?Await] ClassTail[?Yield, ?Await] [+Default] class ClassTail[?Yield, ?Await] ClassExpression[Yield, Await] : class BindingIdentifier[?Yield, ?Await]opt ClassTail[?Yield, ?Await] ClassTail[Yield, Await] : ClassHeritage[?Yield, ?Await]opt { ClassBody[?Yield, ?Await]opt } ClassHeritage[Yield, Await] : extends LeftHandSideExpression[?Yield, ?Await] ClassBody[Yield, Await] : ClassElementList[?Yield, ?Await] ClassElementList[Yield, Await] : ClassElement[?Yield, ?Await] ClassElementList[?Yield, ?Await] ClassElement[?Yield, ?Await] ClassElement[Yield, Await] : MethodDefinition[?Yield, ?Await] static MethodDefinition[?Yield, ?Await] FieldDefinition[?Yield, ?Await] ; static FieldDefinition[?Yield, ?Await] ; ClassStaticBlock ; FieldDefinition[Yield, Await] : ClassElementName[?Yield, ?Await] Initializer[+In, ?Yield, ?Await]opt ClassElementName[Yield, Await] : PropertyName[?Yield, ?Await] PrivateIdentifier ClassStaticBlock : static { ClassStaticBlockBody } ClassStaticBlockBody : ClassStaticBlockStatementList ClassStaticBlockStatementList : StatementList[~Yield, +Await, ~Return]opt

A.5 Scripts and Modules

Script : ScriptBodyopt ScriptBody : StatementList[~Yield, ~Await, ~Return] Module : ModuleBodyopt ModuleBody : ModuleItemList ModuleItemList : ModuleItem ModuleItemList ModuleItem ModuleItem : ImportDeclaration ExportDeclaration StatementListItem[~Yield, +Await, ~Return] ModuleExportName : IdentifierName StringLiteral ImportDeclaration : import ImportClause FromClause WithClauseopt ; import ModuleSpecifier WithClauseopt ; ImportClause : ImportedDefaultBinding NameSpaceImport NamedImports ImportedDefaultBinding , NameSpaceImport ImportedDefaultBinding , NamedImports ImportedDefaultBinding : ImportedBinding NameSpaceImport : * as ImportedBinding NamedImports : { } { ImportsList } { ImportsList , } FromClause : from ModuleSpecifier ImportsList : ImportSpecifier ImportsList , ImportSpecifier ImportSpecifier : ImportedBinding ModuleExportName as ImportedBinding ModuleSpecifier : StringLiteral ImportedBinding : BindingIdentifier[~Yield, +Await] WithClause : with { } with { WithEntries ,opt } WithEntries : AttributeKey : StringLiteral AttributeKey : StringLiteral , WithEntries AttributeKey : IdentifierName StringLiteral ExportDeclaration : export ExportFromClause FromClause WithClauseopt ; export NamedExports ; export VariableStatement[~Yield, +Await] export [lookahead ∉ { using, await }] Declaration[~Yield, +Await] export default HoistableDeclaration[~Yield, +Await, +Default] export default ClassDeclaration[~Yield, +Await, +Default] export default [lookahead ∉ { function, async [no LineTerminator here] function, class }] AssignmentExpression[+In, ~Yield, +Await] ; ExportFromClause : * * as ModuleExportName NamedExports NamedExports : { } { ExportsList } { ExportsList , } ExportsList : ExportSpecifier ExportsList , ExportSpecifier ExportSpecifier : ModuleExportName ModuleExportName as ModuleExportName

A.6 Number Conversions

StringNumericLiteral ::: StrWhiteSpaceopt StrWhiteSpaceopt StrNumericLiteral StrWhiteSpaceopt StrWhiteSpace ::: StrWhiteSpaceChar StrWhiteSpaceopt StrWhiteSpaceChar ::: WhiteSpace LineTerminator StrNumericLiteral ::: StrDecimalLiteral NonDecimalIntegerLiteral[~Sep] StrDecimalLiteral ::: StrUnsignedDecimalLiteral + StrUnsignedDecimalLiteral - StrUnsignedDecimalLiteral StrUnsignedDecimalLiteral ::: Infinity DecimalDigits[~Sep] . DecimalDigits[~Sep]opt ExponentPart[~Sep]opt . DecimalDigits[~Sep] ExponentPart[~Sep]opt DecimalDigits[~Sep] ExponentPart[~Sep]opt

StringNumericLiteral grammarによって明示的に定義されていないすべてのgrammar symbolsは、numeric literalsのLexical Grammarで使用されるdefinitionsを持つ。

StringIntegerLiteral ::: StrWhiteSpaceopt StrWhiteSpaceopt StrIntegerLiteral StrWhiteSpaceopt StrIntegerLiteral ::: SignedInteger[~Sep] NonDecimalIntegerLiteral[~Sep]

A.7 Time Zone Offset String Format

UTCOffset ::: ASCIISign Hour ASCIISign Hour HourSubcomponents[+Extended] ASCIISign Hour HourSubcomponents[~Extended] ASCIISign ::: one of + - Hour ::: 0 DecimalDigit 1 DecimalDigit 20 21 22 23 HourSubcomponents[Extended] ::: TimeSeparator[?Extended] MinuteSecond TimeSeparator[?Extended] MinuteSecond TimeSeparator[?Extended] MinuteSecond TemporalDecimalFractionopt TimeSeparator[Extended] ::: [+Extended] : [~Extended] [empty] MinuteSecond ::: 0 DecimalDigit 1 DecimalDigit 2 DecimalDigit 3 DecimalDigit 4 DecimalDigit 5 DecimalDigit TemporalDecimalFraction ::: TemporalDecimalSeparator DecimalDigit TemporalDecimalSeparator DecimalDigit DecimalDigit TemporalDecimalSeparator DecimalDigit DecimalDigit DecimalDigit TemporalDecimalSeparator DecimalDigit DecimalDigit DecimalDigit DecimalDigit TemporalDecimalSeparator DecimalDigit DecimalDigit DecimalDigit DecimalDigit DecimalDigit TemporalDecimalSeparator DecimalDigit DecimalDigit DecimalDigit DecimalDigit DecimalDigit DecimalDigit TemporalDecimalSeparator DecimalDigit DecimalDigit DecimalDigit DecimalDigit DecimalDigit DecimalDigit DecimalDigit TemporalDecimalSeparator DecimalDigit DecimalDigit DecimalDigit DecimalDigit DecimalDigit DecimalDigit DecimalDigit DecimalDigit TemporalDecimalSeparator DecimalDigit DecimalDigit DecimalDigit DecimalDigit DecimalDigit DecimalDigit DecimalDigit DecimalDigit DecimalDigit TemporalDecimalSeparator ::: one of . ,

A.8 Regular Expressions

Pattern[UnicodeMode, UnicodeSetsMode, NamedCaptureGroups] :: Disjunction[?UnicodeMode, ?UnicodeSetsMode, ?NamedCaptureGroups] Disjunction[UnicodeMode, UnicodeSetsMode, NamedCaptureGroups] :: Alternative[?UnicodeMode, ?UnicodeSetsMode, ?NamedCaptureGroups] Alternative[?UnicodeMode, ?UnicodeSetsMode, ?NamedCaptureGroups] | Disjunction[?UnicodeMode, ?UnicodeSetsMode, ?NamedCaptureGroups] Alternative[UnicodeMode, UnicodeSetsMode, NamedCaptureGroups] :: [empty] Alternative[?UnicodeMode, ?UnicodeSetsMode, ?NamedCaptureGroups] Term[?UnicodeMode, ?UnicodeSetsMode, ?NamedCaptureGroups] Term[UnicodeMode, UnicodeSetsMode, NamedCaptureGroups] :: Assertion[?UnicodeMode, ?UnicodeSetsMode, ?NamedCaptureGroups] Atom[?UnicodeMode, ?UnicodeSetsMode, ?NamedCaptureGroups] Atom[?UnicodeMode, ?UnicodeSetsMode, ?NamedCaptureGroups] Quantifier Assertion[UnicodeMode, UnicodeSetsMode, NamedCaptureGroups] :: ^ $ \b \B (?= Disjunction[?UnicodeMode, ?UnicodeSetsMode, ?NamedCaptureGroups] ) (?! Disjunction[?UnicodeMode, ?UnicodeSetsMode, ?NamedCaptureGroups] ) (?<= Disjunction[?UnicodeMode, ?UnicodeSetsMode, ?NamedCaptureGroups] ) (?<! Disjunction[?UnicodeMode, ?UnicodeSetsMode, ?NamedCaptureGroups] ) Quantifier :: QuantifierPrefix QuantifierPrefix ? QuantifierPrefix :: * + ? { DecimalDigits[~Sep] } { DecimalDigits[~Sep] ,} { DecimalDigits[~Sep] , DecimalDigits[~Sep] } Atom[UnicodeMode, UnicodeSetsMode, NamedCaptureGroups] :: PatternCharacter . \ AtomEscape[?UnicodeMode, ?NamedCaptureGroups] CharacterClass[?UnicodeMode, ?UnicodeSetsMode] ( GroupSpecifier[?UnicodeMode]opt Disjunction[?UnicodeMode, ?UnicodeSetsMode, ?NamedCaptureGroups] ) (? RegularExpressionModifiers : Disjunction[?UnicodeMode, ?UnicodeSetsMode, ?NamedCaptureGroups] ) (? RegularExpressionModifiers - RegularExpressionModifiers : Disjunction[?UnicodeMode, ?UnicodeSetsMode, ?NamedCaptureGroups] ) RegularExpressionModifiers :: [empty] RegularExpressionModifiers RegularExpressionModifier RegularExpressionModifier :: one of i m s SyntaxCharacter :: one of ^ $ \ . * + ? ( ) [ ] { } | PatternCharacter :: SourceCharacter but not SyntaxCharacter AtomEscape[UnicodeMode, NamedCaptureGroups] :: DecimalEscape CharacterClassEscape[?UnicodeMode] CharacterEscape[?UnicodeMode] [+NamedCaptureGroups] k GroupName[?UnicodeMode] CharacterEscape[UnicodeMode] :: ControlEscape c AsciiLetter 0 [lookahead ∉ DecimalDigit] HexEscapeSequence RegExpUnicodeEscapeSequence[?UnicodeMode] IdentityEscape[?UnicodeMode] ControlEscape :: one of f n r t v GroupSpecifier[UnicodeMode] :: ? GroupName[?UnicodeMode] GroupName[UnicodeMode] :: < RegExpIdentifierName[?UnicodeMode] > RegExpIdentifierName[UnicodeMode] :: RegExpIdentifierStart[?UnicodeMode] RegExpIdentifierName[?UnicodeMode] RegExpIdentifierPart[?UnicodeMode] RegExpIdentifierStart[UnicodeMode] :: IdentifierStartChar \ RegExpUnicodeEscapeSequence[+UnicodeMode] [~UnicodeMode] UnicodeLeadSurrogate UnicodeTrailSurrogate RegExpIdentifierPart[UnicodeMode] :: IdentifierPartChar \ RegExpUnicodeEscapeSequence[+UnicodeMode] [~UnicodeMode] UnicodeLeadSurrogate UnicodeTrailSurrogate RegExpUnicodeEscapeSequence[UnicodeMode] :: [+UnicodeMode] u HexLeadSurrogate \u HexTrailSurrogate [+UnicodeMode] u HexLeadSurrogate [+UnicodeMode] u HexTrailSurrogate [+UnicodeMode] u HexNonSurrogate [~UnicodeMode] u Hex4Digits [+UnicodeMode] u{ CodePoint } UnicodeLeadSurrogate :: any Unicode code point in the inclusive interval from U+D800 to U+DBFF UnicodeTrailSurrogate :: any Unicode code point in the inclusive interval from U+DC00 to U+DFFF

関連付けられるu HexLeadSurrogateの選択がambiguousである各\u HexTrailSurrogateは、対応する\u HexTrailSurrogateを他に持たないnearest possible u HexLeadSurrogateにassociatedされなければならない。

 

HexLeadSurrogate :: Hex4Digits but only if the MV of Hex4Digits is in the inclusive interval from 0xD800 to 0xDBFF HexTrailSurrogate :: Hex4Digits but only if the MV of Hex4Digits is in the inclusive interval from 0xDC00 to 0xDFFF HexNonSurrogate :: Hex4Digits but only if the MV of Hex4Digits is not in the inclusive interval from 0xD800 to 0xDFFF IdentityEscape[UnicodeMode] :: [+UnicodeMode] SyntaxCharacter [+UnicodeMode] / [~UnicodeMode] SourceCharacter but not UnicodeIDContinue DecimalEscape :: NonZeroDigit DecimalDigits[~Sep]opt [lookahead ∉ DecimalDigit] CharacterClassEscape[UnicodeMode] :: d D s S w W [+UnicodeMode] p{ UnicodePropertyValueExpression } [+UnicodeMode] P{ UnicodePropertyValueExpression } UnicodePropertyValueExpression :: UnicodePropertyName = UnicodePropertyValue LoneUnicodePropertyNameOrValue UnicodePropertyName :: UnicodePropertyNameCharacters UnicodePropertyNameCharacters :: UnicodePropertyNameCharacter UnicodePropertyNameCharactersopt UnicodePropertyValue :: UnicodePropertyValueCharacters LoneUnicodePropertyNameOrValue :: UnicodePropertyValueCharacters UnicodePropertyValueCharacters :: UnicodePropertyValueCharacter UnicodePropertyValueCharactersopt UnicodePropertyValueCharacter :: UnicodePropertyNameCharacter DecimalDigit UnicodePropertyNameCharacter :: AsciiLetter _ CharacterClass[UnicodeMode, UnicodeSetsMode] :: [ [lookahead ≠ ^] ClassContents[?UnicodeMode, ?UnicodeSetsMode] ] [^ ClassContents[?UnicodeMode, ?UnicodeSetsMode] ] ClassContents[UnicodeMode, UnicodeSetsMode] :: [empty] [~UnicodeSetsMode] NonemptyClassRanges[?UnicodeMode] [+UnicodeSetsMode] ClassSetExpression NonemptyClassRanges[UnicodeMode] :: ClassAtom[?UnicodeMode] ClassAtom[?UnicodeMode] NonemptyClassRangesNoDash[?UnicodeMode] ClassAtom[?UnicodeMode] - ClassAtom[?UnicodeMode] ClassContents[?UnicodeMode, ~UnicodeSetsMode] NonemptyClassRangesNoDash[UnicodeMode] :: ClassAtom[?UnicodeMode] ClassAtomNoDash[?UnicodeMode] NonemptyClassRangesNoDash[?UnicodeMode] ClassAtomNoDash[?UnicodeMode] - ClassAtom[?UnicodeMode] ClassContents[?UnicodeMode, ~UnicodeSetsMode] ClassAtom[UnicodeMode] :: - ClassAtomNoDash[?UnicodeMode] ClassAtomNoDash[UnicodeMode] :: SourceCharacter but not one of \ or ] or - \ ClassEscape[?UnicodeMode] ClassEscape[UnicodeMode] :: b [+UnicodeMode] - CharacterClassEscape[?UnicodeMode] CharacterEscape[?UnicodeMode] ClassSetExpression :: ClassUnion ClassIntersection ClassSubtraction ClassUnion :: ClassSetRange ClassUnionopt ClassSetOperand ClassUnionopt ClassIntersection :: ClassSetOperand && [lookahead ≠ &] ClassSetOperand ClassIntersection && [lookahead ≠ &] ClassSetOperand ClassSubtraction :: ClassSetOperand -- ClassSetOperand ClassSubtraction -- ClassSetOperand ClassSetRange :: ClassSetCharacter - ClassSetCharacter ClassSetOperand :: NestedClass ClassStringDisjunction ClassSetCharacter NestedClass :: [ [lookahead ≠ ^] ClassContents[+UnicodeMode, +UnicodeSetsMode] ] [^ ClassContents[+UnicodeMode, +UnicodeSetsMode] ] \ CharacterClassEscape[+UnicodeMode] ClassStringDisjunction :: \q{ ClassStringDisjunctionContents } ClassStringDisjunctionContents :: ClassString ClassString | ClassStringDisjunctionContents ClassString :: [empty] NonEmptyClassString NonEmptyClassString :: ClassSetCharacter NonEmptyClassStringopt ClassSetCharacter :: [lookahead ∉ ClassSetReservedDoublePunctuator] SourceCharacter but not ClassSetSyntaxCharacter \ CharacterEscape[+UnicodeMode] \ ClassSetReservedPunctuator \b ClassSetReservedDoublePunctuator :: one of && !! ## $$ %% ** ++ ,, .. :: ;; << == >> ?? @@ ^^ `` ~~ ClassSetSyntaxCharacter :: one of ( ) [ ] { } / - \ | ClassSetReservedPunctuator :: one of & - ! # % , : ; < = > @ ` ~

Annex B (normative) Webブラウザー向け追加ECMAScript機能

このannexで定義されるECMAScript言語のsyntaxおよびsemanticsは、ECMAScript hostがweb browserである場合にrequiredである。このannexの内容はnormativeであるが、ECMAScript hostがweb browserでない場合はoptionalである。

このannexで定義される一部のfeaturesはこのannexでspecifiedされ、一部はこの文書のmain bodyでspecifiedされる。

featureがmain bodyでspecifiedされる場合、それが文書に影響する各pointは、coloured box内の“Normative Optional”というwordsでmarkedされる。さらに、そのfeatureがalgorithmまたはearly error rule内のparticular wordingに関わる場合、これは関連するfeatureを“the host supports”するというconditionによってguardされる。Web browsersはそのようなfeaturesをすべてsupportすることがrequiredである。

Note

このannexは、web browser ECMAScript hostsの様々なlegacy featuresおよびその他のcharacteristicsをdescribeする。このannexでspecifiedされるlanguage featuresおよびbehavioursはすべて、1つ以上の望ましくないcharacteristicsを持ち、legacy usageがなければこのspecificationからremovedされるものである。しかし、既存の大量のweb pagesによるこれらfeaturesのusageは、web browsersがそれらをsupportし続けなければならないことを意味する。このannexのspecificationsは、これらlegacy featuresのinteroperable implementationsのrequirementsをdefineする。

これらfeaturesはcore ECMAScript languageの一部とはconsideredされない。Programmersは新しいECMAScript codeを書くとき、これらfeaturesおよびbehavioursのexistenceを使用またはassumeすべきでない。ECMAScript implementationsは、そのimplementationがweb browserの一部である場合、またはweb browsersがencounterするものと同じlegacy ECMAScript codeをrunすることがrequiredされる場合を除き、これらfeaturesをimplementすることをdiscouragedされる。

B.1 追加Syntax

B.1.1 HTML-like Comments

12.4のsyntaxおよびsemanticsは以下のようにextendedされる。ただし、このextensionはgoal symbol Moduleを使用してsource textをparseする場合にはallowedされない:

Syntax

InputElementHashbangOrRegExp :: WhiteSpace LineTerminator Comment CommonToken HashbangComment RegularExpressionLiteral HTMLCloseComment Comment :: MultiLineComment SingleLineComment SingleLineHTMLOpenComment SingleLineHTMLCloseComment SingleLineDelimitedComment MultiLineComment :: /* FirstCommentLineopt LineTerminator MultiLineCommentCharsopt */ HTMLCloseCommentopt FirstCommentLine :: SingleLineDelimitedCommentChars SingleLineHTMLOpenComment :: <!-- SingleLineCommentCharsopt SingleLineHTMLCloseComment :: LineTerminatorSequence HTMLCloseComment SingleLineDelimitedComment :: /* SingleLineDelimitedCommentCharsopt */ HTMLCloseComment :: WhiteSpaceSequenceopt SingleLineDelimitedCommentSequenceopt --> SingleLineCommentCharsopt SingleLineDelimitedCommentChars :: SingleLineNotAsteriskChar SingleLineDelimitedCommentCharsopt * SingleLinePostAsteriskCommentCharsopt SingleLineNotAsteriskChar :: SourceCharacter but not one of * or LineTerminator SingleLinePostAsteriskCommentChars :: SingleLineNotForwardSlashOrAsteriskChar SingleLineDelimitedCommentCharsopt * SingleLinePostAsteriskCommentCharsopt SingleLineNotForwardSlashOrAsteriskChar :: SourceCharacter but not one of / or * or LineTerminator WhiteSpaceSequence :: WhiteSpace WhiteSpaceSequenceopt SingleLineDelimitedCommentSequence :: SingleLineDelimitedComment WhiteSpaceSequenceopt SingleLineDelimitedCommentSequenceopt

line terminator code pointを含むMultiLineCommentと同様に、SingleLineHTMLCloseCommentはsyntactic grammarによるparsingの目的ではLineTerminatorであるとconsideredされる。

B.1.2 Regular Expressions Patterns

22.2.1のsyntaxは以下のようにmodifiedおよびextendedされる。これらのchangesはambiguitiesをintroduceし、それらはgrammar productionsのorderingおよびcontextual informationによって解消される。以下のgrammarを使用してparsingする場合、各alternativeは、それ以前のproduction alternativesがmatchしない場合にのみconsideredされる。

このalternative pattern grammarおよびsemanticsは、BMP patternsのsyntaxおよびsemanticsのみをchangeする。以下のgrammar extensionsには[UnicodeMode] parameterでparameterizedされたproductionsが含まれる。しかし、これらextensionsのいずれも、goal symbol上に[UnicodeMode] parameterがpresentでparseするときにrecognizedされるUnicode patternsのsyntaxをchangeしない。

Syntax

Term[UnicodeMode, UnicodeSetsMode, NamedCaptureGroups] :: [+UnicodeMode] Assertion[+UnicodeMode, ?UnicodeSetsMode, ?NamedCaptureGroups] [+UnicodeMode] Atom[+UnicodeMode, ?UnicodeSetsMode, ?NamedCaptureGroups] Quantifier [+UnicodeMode] Atom[+UnicodeMode, ?UnicodeSetsMode, ?NamedCaptureGroups] [~UnicodeMode] QuantifiableAssertion[?NamedCaptureGroups] Quantifier [~UnicodeMode] Assertion[~UnicodeMode, ~UnicodeSetsMode, ?NamedCaptureGroups] [~UnicodeMode] ExtendedAtom[?NamedCaptureGroups] Quantifier [~UnicodeMode] ExtendedAtom[?NamedCaptureGroups] Assertion[UnicodeMode, UnicodeSetsMode, NamedCaptureGroups] :: ^ $ \b \B [+UnicodeMode] (?= Disjunction[+UnicodeMode, ?UnicodeSetsMode, ?NamedCaptureGroups] ) [+UnicodeMode] (?! Disjunction[+UnicodeMode, ?UnicodeSetsMode, ?NamedCaptureGroups] ) [~UnicodeMode] QuantifiableAssertion[?NamedCaptureGroups] (?<= Disjunction[?UnicodeMode, ?UnicodeSetsMode, ?NamedCaptureGroups] ) (?<! Disjunction[?UnicodeMode, ?UnicodeSetsMode, ?NamedCaptureGroups] ) QuantifiableAssertion[NamedCaptureGroups] :: (?= Disjunction[~UnicodeMode, ~UnicodeSetsMode, ?NamedCaptureGroups] ) (?! Disjunction[~UnicodeMode, ~UnicodeSetsMode, ?NamedCaptureGroups] ) ExtendedAtom[NamedCaptureGroups] :: . \ AtomEscape[~UnicodeMode, ?NamedCaptureGroups] \ [lookahead = c] CharacterClass[~UnicodeMode, ~UnicodeSetsMode] ( GroupSpecifier[~UnicodeMode]opt Disjunction[~UnicodeMode, ~UnicodeSetsMode, ?NamedCaptureGroups] ) (? RegularExpressionModifiers : Disjunction[~UnicodeMode, ~UnicodeSetsMode, ?NamedCaptureGroups] ) (? RegularExpressionModifiers - RegularExpressionModifiers : Disjunction[~UnicodeMode, ~UnicodeSetsMode, ?NamedCaptureGroups] ) InvalidBracedQuantifier ExtendedPatternCharacter InvalidBracedQuantifier :: { DecimalDigits[~Sep] } { DecimalDigits[~Sep] ,} { DecimalDigits[~Sep] , DecimalDigits[~Sep] } ExtendedPatternCharacter :: SourceCharacter but not one of ^ $ \ . * + ? ( ) [ | AtomEscape[UnicodeMode, NamedCaptureGroups] :: [+UnicodeMode] DecimalEscape [~UnicodeMode] DecimalEscape but only if the CapturingGroupNumber of DecimalEscape is ≤ CountLeftCapturingParensWithin(the Pattern containing DecimalEscape) CharacterClassEscape[?UnicodeMode] CharacterEscape[?UnicodeMode, ?NamedCaptureGroups] [+NamedCaptureGroups] k GroupName[?UnicodeMode] CharacterEscape[UnicodeMode, NamedCaptureGroups] :: ControlEscape c AsciiLetter 0 [lookahead ∉ DecimalDigit] HexEscapeSequence RegExpUnicodeEscapeSequence[?UnicodeMode] [~UnicodeMode] LegacyOctalEscapeSequence IdentityEscape[?UnicodeMode, ?NamedCaptureGroups] IdentityEscape[UnicodeMode, NamedCaptureGroups] :: [+UnicodeMode] SyntaxCharacter [+UnicodeMode] / [~UnicodeMode] SourceCharacterIdentityEscape[?NamedCaptureGroups] SourceCharacterIdentityEscape[NamedCaptureGroups] :: [~NamedCaptureGroups] SourceCharacter but not c [+NamedCaptureGroups] SourceCharacter but not one of c or k ClassAtomNoDash[UnicodeMode, NamedCaptureGroups] :: SourceCharacter but not one of \ or ] or - \ ClassEscape[?UnicodeMode, ?NamedCaptureGroups] \ [lookahead = c] ClassEscape[UnicodeMode, NamedCaptureGroups] :: b [+UnicodeMode] - [~UnicodeMode] c ClassControlLetter CharacterClassEscape[?UnicodeMode] CharacterEscape[?UnicodeMode, ?NamedCaptureGroups] ClassControlLetter :: DecimalDigit _ Note

同じleft-hand sidesが[+UnicodeMode]および[~UnicodeMode] guardsの両方でoccurする場合、それはdisambiguation priorityをcontrolするためである。

B.1.2.1 Static Semantics: Early Errors

22.2.1.1のsemanticsは以下のようにextendedされる:

ExtendedAtom :: InvalidBracedQuantifier
  • このproductionによりsource textがmatchされる場合、それはSyntax Errorである。

さらに、以下のproductionsのrulesは、highlighted textのadditionによりmodifiedされる:

NonemptyClassRanges :: ClassAtom - ClassAtom ClassContents NonemptyClassRangesNoDash :: ClassAtomNoDash - ClassAtom ClassContents

B.1.2.2 Static Semantics: CountLeftCapturingParensWithin and CountLeftCapturingParensBefore

CountLeftCapturingParensWithinおよびCountLeftCapturingParensBeforeのdefinitionsにおいて、“ Atom :: ( GroupSpecifieropt Disjunction ) ”へのreferencesは、“ Atom :: ( GroupSpecifieropt Disjunction ) ”または“ ExtendedAtom :: ( GroupSpecifieropt Disjunction ) ”をmeaningするものとしてinterpretedされる。

B.1.2.3 Static Semantics: IsCharacterClass

22.2.1.6のsemanticsは以下のようにextendedされる:

ClassAtomNoDash :: \ [lookahead = c]
  1. falseを返す。

B.1.2.4 Static Semantics: CharacterValue

22.2.1.7のsemanticsは以下のようにextendedされる:

ClassAtomNoDash :: \ [lookahead = c]
  1. U+005C (REVERSE SOLIDUS)のnumeric valueを返す。
ClassEscape :: c ClassControlLetter
  1. codePointClassControlLetterによりmatchedされるcode pointとする。
  2. icodePointのnumeric valueとする。
  3. iを32で割ったremainderを返す。
CharacterEscape :: LegacyOctalEscapeSequence
  1. LegacyOctalEscapeSequenceのMVを返す(12.9.4.3を参照)。

B.1.2.5 Runtime Semantics: CompileSubpattern

CompileSubpatternのsemanticsは以下のようにextendedされる:

Term :: QuantifiableAssertion Quantifier のruleは、AtomQuantifiableAssertionでsubstitutedすることを除き、 Term :: Atom Quantifier の場合と同じである。

Term :: ExtendedAtom Quantifier のruleは、AtomExtendedAtomでsubstitutedすることを除き、 Term :: Atom Quantifier の場合と同じである。

Term :: ExtendedAtom のruleは、AtomExtendedAtomでsubstitutedすることを除き、 Term :: Atom の場合と同じである。

B.1.2.6 Runtime Semantics: CompileAssertion

Assertion :: (?= Disjunction ) および Assertion :: (?! Disjunction ) productionsのCompileAssertion rulesは、AssertionQuantifiableAssertionでsubstitutedすることを除き、QuantifiableAssertion productionsにも使用される。

B.1.2.7 Runtime Semantics: CompileAtom

Atom :: PatternCharacter を除くAtom productionsのCompileAtom rulesは、AtomExtendedAtomでsubstitutedすることを除き、ExtendedAtom productionsにも使用される。parameter directionを持つ以下のrulesもaddedされる:

ExtendedAtom :: \ [lookahead = c]
  1. charSetを、single character \ U+005C (REVERSE SOLIDUS)を含むCharSetとする。
  2. CharacterSetMatcher(regexpRecord, charSet, false, direction)を返す。
ExtendedAtom :: ExtendedPatternCharacter
  1. charExtendedPatternCharacterによりrepresentedされるcharacterとする。
  2. charSetをcharacter charを含むone-element CharSetとする。
  3. CharacterSetMatcher(regexpRecord, charSet, false, direction)を返す。

B.1.2.8 Runtime Semantics: CompileToCharSet

22.2.2.9のsemanticsは以下のようにextendedされる:

以下の2つのrulesは、CompileToCharSetのcorresponding rulesをreplaceする。

NonemptyClassRanges :: ClassAtom - ClassAtom ClassContents
  1. charSetをargument regexpRecordを伴うfirst ClassAtomCompileToCharSetとする。
  2. otherSetをargument regexpRecordを伴うsecond ClassAtomCompileToCharSetとする。
  3. remainingSetをargument regexpRecordを伴うClassContentsCompileToCharSetとする。
  4. rangeSetCharacterRangeOrUnion(regexpRecord, charSet, otherSet)とする。
  5. rangeSetremainingSetのunionを返す。
NonemptyClassRangesNoDash :: ClassAtomNoDash - ClassAtom ClassContents
  1. charSetをargument regexpRecordを伴うClassAtomNoDashCompileToCharSetとする。
  2. otherSetをargument regexpRecordを伴うClassAtomCompileToCharSetとする。
  3. remainingSetをargument regexpRecordを伴うClassContentsCompileToCharSetとする。
  4. rangeSetCharacterRangeOrUnion(regexpRecord, charSet, otherSet)とする。
  5. rangeSetremainingSetのunionを返す。

さらに、以下のrulesがCompileToCharSetにaddedされる。

ClassEscape :: c ClassControlLetter
  1. charValueをこのClassEscapeCharacterValueとする。
  2. charをcharacter valueがcharValueであるcharacterとする。
  3. single character charを含むCharSetを返す。
ClassAtomNoDash :: \ [lookahead = c]
  1. single character \ U+005C (REVERSE SOLIDUS)を含むCharSetを返す。
Note
このproductionは、acceptable control characterが続かないcharacter class内のsequence \cからのみreachedされうる。

B.1.2.8.1 CharacterRangeOrUnion ( regexpRecord, charSet, otherSet )

The abstract operation CharacterRangeOrUnion takes arguments regexpRecord (a RegExp Record), charSet (a CharSet), and otherSet (a CharSet) and returns a CharSet. It performs the following steps when called:

  1. HasEitherUnicodeFlag(regexpRecord)がfalseなら、
    1. charSetがexactly one characterをcontainしない、またはotherSetがexactly one characterをcontainしないなら、
      1. remainingSetをsingle character - U+002D (HYPHEN-MINUS)を含むCharSetとする。
      2. CharSets charSetotherSetおよびremainingSetのunionを返す。
  2. CharacterRange(charSet, otherSet)を返す。

B.1.2.9 Static Semantics: ParsePattern ( patternText, u, v )

22.2.3.4のsemanticsは以下のようにextendedされる:

abstract operation ParsePatternはarguments patternText(Unicode code pointsのsequence)、u(Boolean)、およびv(Boolean)を取る。呼び出されたとき、以下のstepsを実行する:

  1. vtrueでありutrueなら、
    1. parseResultを1つ以上のSyntaxError objectsを含むListとする。
  2. そうでなく、vtrueなら、
    1. parseResultParseText(patternText, Pattern[+UnicodeMode, +UnicodeSetsMode, +NamedCaptureGroups])とする。
  3. そうでなく、utrueなら、
    1. parseResultParseText(patternText, Pattern[+UnicodeMode, ~UnicodeSetsMode, +NamedCaptureGroups])とする。
  4. そうでなければ、
    1. parseResultParseText(patternText, Pattern[~UnicodeMode, ~UnicodeSetsMode, ~NamedCaptureGroups])とする。
    2. parseResultParse Nodeであり、parseResultGroupNameを含むなら、
      1. parseResultParseText(patternText, Pattern[~UnicodeMode, ~UnicodeSetsMode, +NamedCaptureGroups])に設定する。
  5. parseResultを返す。

B.2 追加Built-in Properties

ECMAScript hostがweb browserである場合、standard built-in objectsの以下のadditional propertiesがdefinedされる。

B.2.1 Global Objectの追加Properties

Table 103のentriesはTable 6にaddedされる。

Table 103: Additional Well-known Intrinsic Objects
Intrinsic Name Global Name ECMAScript Language Association
%escape% "escape" escape function(B.2.1.1
%unescape% "unescape" unescape function(B.2.1.2

B.2.1.1 escape ( string )

このfunctionはglobal objectのpropertyである。これは、特定のcode unitsがhexadecimal escape sequenceによってreplacedされたString valueのnew versionをcomputesする。

numeric valueが0x00FF以下のcode unitをreplacingするとき、%xx形式のtwo-digit escape sequenceが使用される。numeric valueが0x00FFよりstrictly greaterであるcode unitをreplacingするとき、%uxxxx形式のfour-digit escape sequenceが使用される。

これは%escape% intrinsic objectである。

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

  1. stringを ? ToString(string) に設定する。
  2. lengthstringのlengthとする。
  3. resultをempty Stringとする。
  4. unescapedSetをASCII word charactersと"@*+-./"string-concatenationとする。
  5. kを0とする。
  6. k < lengthである間、繰り返す:
    1. codeUnitstring内のindex kにあるcode unitとする。
    2. unescapedSetcodeUnitをcontainするなら、
      1. nextPartcodeUnitとする。
    3. そうでなければ、
      1. codeUnitNumbercodeUnitのnumeric valueとする。
      2. codeUnitNumber < 256なら、
        1. hexを、uppercase hexadecimal numberとしてformattedされたcodeUnitNumberのString representationとする。
        2. nextPart"%"StringPad(hex, 2, "0", start)のstring-concatenationとする。
      3. そうでなければ、
        1. hexを、uppercase hexadecimal numberとしてformattedされたcodeUnitNumberのString representationとする。
        2. nextPart"%u"StringPad(hex, 4, "0", start)のstring-concatenationとする。
    4. resultresultnextPartstring-concatenationに設定する。
    5. kk + 1に設定する。
  7. resultを返す。
Note

このencodingは、RFC 1738でdescribedされるencodingにpartly基づくが、このstandardでspecifiedされるentire encodingは、RFC 1738のcontentsに関係なく上にdescribedされる。このencodingは、RFC 3986によってRFC 1738に行われたchangesをreflectしない。

B.2.1.2 unescape ( string )

このfunctionはglobal objectのpropertyである。これは、escape functionによってintroducedされうるsortの各escape sequenceが、それがrepresentsするcode unitでreplacedされたString valueのnew versionをcomputesする。

これは%unescape% intrinsic objectである。

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

  1. stringを ? ToString(string) に設定する。
  2. lengthstringのlengthとする。
  3. resultをempty Stringとする。
  4. kを0とする。
  5. k < lengthである間、繰り返す:
    1. codeUnitstring内のindex kにあるcode unitとする。
    2. codeUnitがcode unit 0x0025 (PERCENT SIGN)であるなら、
      1. hexDigitsをempty Stringとする。
      2. optionalAdvanceを0とする。
      3. k + 5 < lengthであり、string内のindex k + 1にあるcode unitがcode unit 0x0075 (LATIN SMALL LETTER U)であるなら、
        1. hexDigitsstringk + 2からk + 6までのsubstringに設定する。
        2. optionalAdvanceを5に設定する。
      4. そうでなく、k + 3 ≤ lengthなら、
        1. hexDigitsstringk + 1からk + 3までのsubstringに設定する。
        2. optionalAdvanceを2に設定する。
      5. parseResultParseText(hexDigits, HexDigits[~Sep])とする。
      6. parseResultParse Nodeなら、
        1. codeUnitNumberparseResultのMVとする。
        2. codeUnitをnumeric valueがcodeUnitNumberであるcode unitに設定する。
        3. kk + optionalAdvanceに設定する。
    3. resultresultcodeUnitstring-concatenationに設定する。
    4. kk + 1に設定する。
  6. resultを返す。

B.2.2 String.prototype Objectの追加Properties

B.2.2.1 String.prototype.substr ( start, length )

このmethodは、this valueをStringにconvertingした結果のsubstringを返す。これはindex startから始まり、length code unitsだけ(またはlengthundefinedならStringのendまで)runningする。startがnegativeなら、それはsourceLength + startとしてtreatedされる。ここでsourceLengthはStringのlengthである。resultはString valueであり、String objectではない。

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

  1. objthis valueとする。
  2. RequireObjectCoercible(obj)を実行する。
  3. stringを ? ToString(obj) とする。
  4. sizestringのlengthとする。
  5. intStartを ? ToIntegerOrInfinity(start) とする。
  6. intStart = -∞なら、intStartを0に設定する。
  7. そうでなく、intStart < 0なら、intStartmax(size + intStart, 0)に設定する。
  8. そうでなければ、intStartmin(intStart, size)に設定する。
  9. lengthundefinedなら、intLengthsizeとする;そうでなければ、intLengthを ? ToIntegerOrInfinity(length) とする。
  10. intLengthを0とsizeの間にclampingしたresultに設定する。
  11. intEndmin(intStart + intLength, size)とする。
  12. stringintStartからintEndまでのsubstringを返す。
Note

このmethodはintentionally genericである;そのthis valueがString objectであることをrequireしない。したがって、methodとして使用するために他のkinds of objectsへtransferredできる。

B.2.2.2 String.prototype.anchor ( name )

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

  1. stringthis valueとする。
  2. CreateHTML(string, "a", "name", name)を返す。

B.2.2.2.1 CreateHTML ( contents, tag, attr, attrValue )

The abstract operation CreateHTML takes arguments contents (an ECMAScript language value), tag (a String), attr (a String), and attrValue (an ECMAScript language value) and returns either a normal completion containing a String or a throw completion. It performs the following steps when called:

  1. RequireObjectCoercible(contents)を実行する。
  2. contentsStringを ? ToString(contents) とする。
  3. part1"<"tagstring-concatenationとする。
  4. attrがempty Stringでないなら、
    1. attrValueStringを ? ToString(attrValue) とする。
    2. escapedAttrValueを、attrValueString内のcode unit 0x0022 (QUOTATION MARK)の各occurrenceがsix code unit sequence "&quot;"でreplacedされたことを除きattrValueStringと同じString valueとする。
    3. part1を以下のstring-concatenationに設定する:
      • part1
      • code unit 0x0020 (SPACE)
      • attr
      • code unit 0x003D (EQUALS SIGN)
      • code unit 0x0022 (QUOTATION MARK)
      • escapedAttrValue
      • code unit 0x0022 (QUOTATION MARK)
  5. part2part1">"string-concatenationとする。
  6. part3part2contentsStringstring-concatenationとする。
  7. part4part3"</"tag、および">"string-concatenationとする。
  8. part4を返す。

B.2.2.3 String.prototype.big ( )

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

  1. stringthis valueとする。
  2. CreateHTML(string, "big", "", "")を返す。

B.2.2.4 String.prototype.blink ( )

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

  1. stringthis valueとする。
  2. CreateHTML(string, "blink", "", "")を返す。

B.2.2.5 String.prototype.bold ( )

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

  1. stringthis valueとする。
  2. CreateHTML(string, "b", "", "")を返す。

B.2.2.6 String.prototype.fixed ( )

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

  1. stringthis valueとする。
  2. CreateHTML(string, "tt", "", "")を返す。

B.2.2.7 String.prototype.fontcolor ( colour )

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

  1. stringthis valueとする。
  2. CreateHTML(string, "font", "color", colour)を返す。

B.2.2.8 String.prototype.fontsize ( size )

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

  1. stringthis valueとする。
  2. CreateHTML(string, "font", "size", size)を返す。

B.2.2.9 String.prototype.italics ( )

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

  1. stringthis valueとする。
  2. CreateHTML(string, "i", "", "")を返す。

B.2.2.10 String.prototype.link ( url )

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

  1. stringthis valueとする。
  2. CreateHTML(string, "a", "href", url)を返す。

B.2.2.11 String.prototype.small ( )

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

  1. stringthis valueとする。
  2. CreateHTML(string, "small", "", "")を返す。

B.2.2.12 String.prototype.strike ( )

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

  1. stringthis valueとする。
  2. CreateHTML(string, "strike", "", "")を返す。

B.2.2.13 String.prototype.sub ( )

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

  1. stringthis valueとする。
  2. CreateHTML(string, "sub", "", "")を返す。

B.2.2.14 String.prototype.sup ( )

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

  1. stringthis valueとする。
  2. CreateHTML(string, "sup", "", "")を返す。

B.2.2.15 String.prototype.trimLeft ( )

Note

"trimStart" propertyがpreferredである。"trimLeft" propertyは主にold codeとのcompatibilityのためにprovidedされる。新しいECMAScript codeでは"trimStart" propertyを使用することがrecommendedされる。

"trimLeft" propertyのinitial valueは、22.1.3.34でdefinedされる%String.prototype.trimStart%である。

B.2.2.16 String.prototype.trimRight ( )

Note

"trimEnd" propertyがpreferredである。"trimRight" propertyは主にold codeとのcompatibilityのためにprovidedされる。新しいECMAScript codeでは"trimEnd" propertyを使用することがrecommendedされる。

"trimRight" propertyのinitial valueは、22.1.3.33でdefinedされる%String.prototype.trimEnd%である。

B.2.3 Date.prototype Objectの追加Properties

B.2.3.1 Date.prototype.getYear ( )

Note

getFullYear methodは“year 2000 problem”をavoidするため、ほぼすべての目的でpreferredされる。

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

  1. dateObjthis valueとする。
  2. RequireInternalSlot(dateObj, [[DateValue]])を実行する。
  3. tvdateObj.[[DateValue]]とする。
  4. tvNaNなら、NaNを返す。
  5. YearFromTime(LocalTime(tv)) - 1900𝔽を返す。

B.2.3.2 Date.prototype.setYear ( year )

Note

setFullYear methodは“year 2000 problem”をavoidするため、ほぼすべての目的でpreferredされる。

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

  1. dateObjthis valueとする。
  2. RequireInternalSlot(dateObj, [[DateValue]])を実行する。
  3. timedateObj.[[DateValue]]とする。
  4. yearを ? ToNumber(year) とする。
  5. timeNaNなら、time+0𝔽に設定する;そうでなければ、timeLocalTime(time)に設定する。
  6. fullYearMakeFullYear(year)とする。
  7. dayMakeDay(fullYear, MonthFromTime(time), DateFromTime(time))とする。
  8. dateMakeDate(day, TimeWithinDay(time))とする。
  9. utcTimestampTimeClip(UTC(date))とする。
  10. dateObj.[[DateValue]]utcTimestampに設定する。
  11. utcTimestampを返す。

B.2.3.3 Date.prototype.toGMTString ( )

Note

toUTCString methodがpreferredされる。このmethodは主にold codeとのcompatibilityのためにprovidedされる。

"toGMTString" propertyのinitial valueは、21.4.4.43でdefinedされる%Date.prototype.toUTCString%である。

B.2.4 RegExp.prototype Objectの追加Properties

B.2.4.1 RegExp.prototype.compile ( pattern, flags )

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

  1. objthis valueとする。
  2. RequireInternalSlot(obj, [[RegExpMatcher]])を実行する。
  3. patternがObjectであり、pattern[[RegExpMatcher]] internal slotを持つなら、
    1. flagsundefinedでないなら、TypeError例外をthrowする。
    2. flagspattern.[[OriginalFlags]]に設定する。
    3. patternpattern.[[OriginalSource]]に設定する。
  4. RegExpInitialize(obj, pattern, flags)を返す。
Note

このmethodはthis value RegExpをnew patternおよびflagsで完全にreinitializesする。Implementationは、このmethodの使用を、resulting RegExp objectが複数回使用されるためextra optimizationのcandidateであるというassertionとしてinterpretしてもよい。

B.3 その他の追加Features

B.3.1 Labelled Function Declarations

ECMAScript 2015より前、LabelledStatementのspecificationはstatement labelとFunctionDeclarationのassociationをallowしていなかった。しかし、labelled FunctionDeclarationnon-strict code向けのallowable extensionであり、ほとんどのbrowser-hosted ECMAScript implementationsがそのextensionをsupportしていた。ECMAScript 2015以降、LabelledStatementのgrammar productionはLabelledItemとしてFunctionDeclarationの使用をpermitするが、14.13.1には、それがoccurする場合にSyntax ErrorをproduceするEarly Error ruleが含まれる。そのruleは、このfeatureをhostがsupportする場合、non-strict codeにおいてSyntax Errorをsuppressするようにmodifiedされる。

Note

WithStatementIfStatement、およびIterationStatementearly error rulesは、これらstatementsがnon-strict code内でlabelled FunctionDeclarationをcontainすることをpreventする。

B.3.2 Block-Level Function Declarations Web Legacy Compatibility Semantics

ECMAScript 2015より前、ECMAScript specificationはBlock statementのStatementListのelementとしてのFunctionDeclarationのoccurrenceをdefineしていなかった。しかし、そのformのFunctionDeclarationのsupportはallowable extensionであり、ほとんどのbrowser-hosted ECMAScript implementationsがそれらをpermittedしていた。残念ながら、そのようなdeclarationsのsemanticsはそれらimplementations間で異なる。これらsemantic differencesのため、Block level function declarationsを使用する既存のweb ECMAScript source textは、そのusageがそのようなdeclarationsに関するすべてのbrowser implementationsのsemantic intersectionにのみ依存する場合に限り、browser implementations間でportableである。以下は、そのintersection semantics内に入るuse casesである:

  1. functionがdeclaredされ、single block内でのみreferencedされる。

    • BindingIdentifierがname fである1つ以上のFunctionDeclarationsが、enclosing function gのfunction code内にoccurし、そのdeclarationがBlock内にnestedされている。
    • fの他のdeclarationで、var declarationでないものは、gのfunction code内にoccurしない。
    • IdentifierReferenceとしてのfのすべてのoccurrencesは、fのdeclarationをcontainするBlockStatementList内にある。
  2. functionがdeclaredされ、single Block内でpossibly usedされるが、同じBlock内にcontainedされないinner function definitionによってalso referencedされる。

    • BindingIdentifierがname fである1つ以上のFunctionDeclarationsが、enclosing function gのfunction code内にoccurし、そのdeclarationがBlock内にnestedされている。
    • fの他のdeclarationで、var declarationでないものは、gのfunction code内にoccurしない。
    • fのdeclarationをcontainするBlockStatementList内に、IdentifierReferenceとしてのfのoccurrencesがあってもよい。
    • g内にnestedされた別のfunction h内に、IdentifierReferenceとしてのfのoccurrenceが少なくとも1つあり、h内からのfへのreferencesをshadowするfの他のdeclarationがない。
    • hのすべてのinvocationsは、fのdeclarationがevaluatedされた後にoccurする。
  3. functionがdeclaredされ、single block内でpossibly usedされるが、subsequent blocks内でもreferencedされる。

    • BindingIdentifierがname fである1つ以上のFunctionDeclarationが、enclosing function gのfunction code内にoccurし、そのdeclarationがBlock内にnestedされている。
    • fの他のdeclarationで、var declarationでないものは、gのfunction code内にoccurしない。
    • fのdeclarationをcontainするBlockStatementList内に、IdentifierReferenceとしてのfのoccurrencesがあってもよい。
    • fのdeclarationをcontainするBlockにlexically followsするgのfunction code内に、IdentifierReferenceとしてのfのoccurrenceが少なくとも1つある。

first use caseは、ECMAScript 2015によってprovidedされるBlock level function declarationsのsemanticsとinteroperableである。そのuse caseをemployするpre-existing ECMAScript source textは、clauses 1014、および15によってdefinedされるBlock level function declarations semanticsを使用してoperateする。

secondおよびthird use casesのECMAScript 2015 interoperabilityは、clause 10、clause 15、clause 19.2.1およびclause 16.1.7 semanticsへの以下のextensionsをrequireする。

ECMAScript implementationがdiagnostic warning messagesをreportするmechanismを持つ場合、これらcompatibility semanticsがappliedされ、non-compatibility semanticsからobservable differencesをintroduceするFunctionDeclarationをcodeがcontainするとき、warningがproducedされるべきである。例えば、var bindingのintroductionがearly errorをcreateするためにintroducedされない場合、warning messageはproducedされるべきでない。

このfeatureは以下のpointsでspecial semanticsをinvolvesする:

B.3.3 IfStatement Statement Clauses内のFunctionDeclarations

以下は14.6内のIfStatement productionをaugmentsする:

IfStatement[Yield, Await, Return] : if ( Expression[+In, ?Yield, ?Await] ) FunctionDeclaration[?Yield, ?Await, ~Default] else Statement[?Yield, ?Await, ?Return] if ( Expression[+In, ?Yield, ?Await] ) Statement[?Yield, ?Await, ?Return] else FunctionDeclaration[?Yield, ?Await, ~Default] if ( Expression[+In, ?Yield, ?Await] ) FunctionDeclaration[?Yield, ?Await, ~Default] else FunctionDeclaration[?Yield, ?Await, ~Default] if ( Expression[+In, ?Yield, ?Await] ) FunctionDeclaration[?Yield, ?Await, ~Default] [lookahead ≠ else]

このproductionは、non-strict codeをparsingするときにのみappliesする。このproductionによってmatchedされるsource textは、FunctionDeclaration[?Yield, ?Await, ~Default]の各matching occurrenceがsource text内のそのpositionをoccupyingするBlockStatementのsole StatementListItemであるかのようにprocessedされる。そのようなsynthetic BlockStatementのsemanticsには、B.3.2でspecifiedされるweb legacy compatibility semanticsが含まれる。

B.3.4 Catch Blocks内のVariableStatements

このfeatureでは、Catch clauseのBlockは、CatchParameterによってもboundされるnameをbindするvar declarationsをcontainしてもよい。これは、14.15.1内の Catch : catch ( CatchParameter ) Block に関するearly error ruleをmodifyingすることによってaccomplishedされる。

Note

runtimeでは、そのようなbindingsはVariableDeclarationEnvironment内でinstantiatedされる。それらはCatchParameterによってintroducedされるsame-named bindingsをshadowせず、したがってそのようなvar declarationsのInitializerは、var bindingではなくcorresponding catch parameterへassignする。

このmodified behaviourは、Catch clauseのBlock内にcontainedされるdirect eval callsによってintroducedされるvarおよびfunction declarationsにもappliesする。このchangeは、EvalDeclarationInstantiation内のsteps 3.d.i.2.a.iおよび13.b.ii.4.a.i.iをmodifyingすることによってaccomplishedされる。

B.3.5 ForIn Statement Heads内のInitializers

以下は14.7.5内のForInOfStatement productionをaugmentsする:

ForInOfStatement[Yield, Await, Return] : for ( var BindingIdentifier[?Yield, ?Await] Initializer[~In, ?Yield, ?Await] in Expression[+In, ?Yield, ?Await] ) Statement[?Yield, ?Await, ?Return]

このproductionは、non-strict codeをparsingするときにのみappliesする。

8.3.1内のContainsDuplicateLabelsstatic semanticsは以下でaugmentedされる:

ForInOfStatement : for ( var BindingIdentifier Initializer in Expression ) Statement
  1. argument labelSetを伴うStatementContainsDuplicateLabelsを返す。

8.3.2内のContainsUndefinedBreakTargetstatic semanticsは以下でaugmentedされる:

ForInOfStatement : for ( var BindingIdentifier Initializer in Expression ) Statement
  1. argument labelSetを伴うStatementContainsUndefinedBreakTargetを返す。

8.3.3内のContainsUndefinedContinueTargetstatic semanticsは以下でaugmentedされる:

ForInOfStatement : for ( var BindingIdentifier Initializer in Expression ) Statement
  1. arguments iterationSetおよび « » を伴うStatementContainsUndefinedContinueTargetを返す。

14.7.5.2内のIsDestructuringstatic semanticsは以下でaugmentedされる:

BindingIdentifier : Identifier yield await
  1. falseを返す。

8.2.8内のVarDeclaredNamesstatic semanticsは以下でaugmentedされる:

ForInOfStatement : for ( var BindingIdentifier Initializer in Expression ) Statement
  1. names1BindingIdentifierBoundNamesとする。
  2. names2StatementVarDeclaredNamesとする。
  3. names1names2list-concatenationを返す。

8.2.9内のVarScopedDeclarationsstatic semanticsは以下でaugmentedされる:

ForInOfStatement : for ( var BindingIdentifier Initializer in Expression ) Statement
  1. decls1を « BindingIdentifier » とする。
  2. decls2StatementVarScopedDeclarationsとする。
  3. decls1decls2list-concatenationを返す。

14.7.5.5内のForInOfLoopEvaluationのruntime semanticsは以下でaugmentedされる:

ForInOfStatement : for ( var BindingIdentifier Initializer in Expression ) Statement
  1. bindingIdBindingIdentifierStringValueとする。
  2. lhsを ? ResolveBinding(bindingId) とする。
  3. IsAnonymousFunctionDefinition(Initializer)がtrueなら、
    1. valueをargument bindingIdを伴うInitializerNamedEvaluationとする。
  4. そうでなければ、
    1. rhsを ? InitializerEvaluation とする。
    2. valueを ? GetValue(rhs) とする。
  5. PutValue(lhs, value)を実行する。
  6. keyResultを ? ForIn/OfHeadEvaluation(« », Expression, enumerate) とする。
  7. ForIn/OfBodyEvaluation(BindingIdentifier, Statement, keyResult, enumerate, var-binding, labelSet)を返す。

B.3.6 [[IsHTMLDDA]] Internal Slot

[[IsHTMLDDA]] internal slothost-defined objects上にexistしてもよい。[[IsHTMLDDA]] internal slotを持つObjectsは、ToBooleanおよびIsLooselyEqual abstract operationsにおいて、またtypeof operatorのoperandとして使用されるとき、undefinedのようにbehaveする。

Note

[[IsHTMLDDA]] internal slotを持つObjectsは、このspecificationによってcreatedされることはない。しかし、web browsersにおけるdocument.all objectは、web compatibility purposesのために存在するこのslotを持つhost-defined exotic objectである。このtypeのobjectの他のknown examplesはなく、implementationsはdocument.allのexceptionを除き、これを持つものをcreateすべきでない。

このfeatureは以下のpointsでspecial semanticsをinvolvesする:

B.3.7 HostMakeJobCallbackにおけるNon-default behaviour

HostMakeJobCallback abstract operationは、web browsersであるhostsがnon-default behaviourをspecifyできるようにする。

B.3.8 HostEnsureCanAddPrivateElementにおけるNon-default behaviour

HostEnsureCanAddPrivateElement abstract operationは、web browsersであるhostsがnon-default behaviourをspecifyできるようにする。

B.3.9 Function Call Assignment Targetsに対するRuntime Errors

function call(13.3.6)がnon-strict code内でassignment targetとして使用される場合、early errorをproduceする代わりに、assignmentのevaluation中にReferenceError例外がthrownされる。

Note

assignment targetがAssignmentExpressionLeftHandSideExpressionである場合、assignment operatorは=またはAssignmentOperatorでなければならない;特に、ここでのallowanceはlogical assignment operators(??=&&=||=)にはapplyしない。

CallExpression : CoverCallExpressionAndAsyncArrowHead および CallExpression : CallExpression Arguments に関するAssignmentTargetTypeのstep 1を参照。

Annex C (informative) ECMAScriptのStrict Mode

strict modeのrestrictionおよびexceptions

Annex D (informative) Host Layering Points

hostのdefinitionについては4.2を参照。

D.1 Host Hooks

HostCallJobCallback(...)

HostEnqueueFinalizationRegistryCleanupJob(...)

HostEnqueueGenericJob(...)

HostEnqueuePromiseJob(...)

HostEnqueueTimeoutJob(...)

HostEnsureCanCompileStrings(...)

HostFinalizeImportMeta(...)

HostGetImportMetaProperties(...)

HostGrowSharedArrayBuffer(...)

HostHasSourceTextAvailable(...)

HostLoadImportedModule(...)

HostGetSupportedImportAttributes(...)

HostMakeJobCallback(...)

HostPromiseRejectionTracker(...)

HostResizeArrayBuffer(...)

InitializeHostDefinedRealm(...)

D.2 Host-defined Fields

Realm Records上の[[HostDefined]]Table 20を参照。

Script Records上の[[HostDefined]]Table 35を参照。

Module Records上の[[HostDefined]]Table 39を参照。

JobCallback Records上の[[HostDefined]]Table 24を参照。

[[IsHTMLDDA]]B.3.6を参照。

D.3 Host-defined Objects

global object:clause 19を参照。

D.4 Running Jobs

Job Abstract Closuresのinvocation前のpreparation steps、および後のcleanup steps。9.5を参照。

D.5 Exotic ObjectsのInternal Methods

このspecification内でspecifiedされていない任意のexotic objectに関する、Table 4内のessential internal methodsのいずれか。

D.6 Built-in Objects and Methods

17.1でrestrictedされるものを除き、このspecification内でdefinedされていない任意のbuilt-in objectsおよびmethods。

Annex E (informative) 互換性に影響する可能性があるECMAScript 2015におけるCorrections and Clarifications

9.1.1.4.14-9.1.1.4.17 Edition 5および5.1は、新しいglobal declarationにcorrespondingするglobal object propertyが既にexistedするかどうかをdetermineするためにproperty existence testを使用した。ECMAScript 2015はown property existence testを使用する。これは、web browsersによってmost commonly implementedされてきたものにcorrespondsする。

10.4.2.1:5th Editionは、array indexまたはnew length valueのinteger conversionより前にcurrent array lengthをcaptureするようにmovedした。しかし、conversion processがarray lengthをchangingするside-effectを持つ場合、captured length valueはinvalidになりえた。ECMAScript 2015は、current array lengthがそのようなside-effectsのpossible occurrenceの後にcapturedされなければならないことをspecifiesする。

21.4.1.31:Previous editionsは、TimeClip abstract operationが0 time valueのrepresentationとして+0𝔽または-0𝔽のいずれかをreturnすることをpermittedしていた。ECMAScript 2015は、+0𝔽が常にreturnedされることをspecifiesする。これは、ECMAScript 2015ではDateのtime valueがobservably -0𝔽になることは決してなく、time valuesをreturnするmethodsが-0𝔽を決してreturnしないことを意味する。

21.4.1.32:UTC offset representationがpresentでない場合、local time zoneが使用される。Edition 5.1は、missing time zoneは"z"としてinterpretedされるべきだとincorrectly statedしていた。

21.4.4.3621.4.1.32でspecifiedされるDate Time String Formatを使用してyearをrepresentedできない場合、RangeError例外がthrownされる。Previous editionsはそのcaseのbehaviourをspecifyしていなかった。

21.4.4.41:Previous editionsは、time valueNaNであるときにDate.prototype.toStringによってreturnedされるvalueをspecifyしていなかった。ECMAScript 2015はresultをString value "Invalid Date"であるとspecifiesする。

22.2.4.1, 22.2.6.13.1:RegExp instanceの"source" propertyのvalue内の任意のLineTerminator code pointsは、escape sequenceを使用してexpressedされなければならない。Edition 5.1は/のescapingのみをrequiredしていた。

22.2.6.8, 22.2.6.11:previous editionsでは、String.prototype.matchおよびString.prototype.replaceのspecificationsは、pattern argumentがglobal flagをsetされたRegExp valueであるcasesについてincorrectであった。previous specificationsは、patternをmatchする各attemptについて、lastIndexがchangeしなかった場合、それは1だけincrementedされるべきだとstatedしていた。correct behaviourは、patternがempty Stringにmatchedした場合にのみlastIndexが1だけincrementedされるべきであるというものである。

23.1.3.30:Previous editionsは、Array.prototype.sortによってcomparatorからreturnedされるNaN valueがどのようにinterpretedされるかをspecifyしていなかった。ECMAScript 2015は、そのようなvalueがcomparatorから+0𝔽がreturnedされたかのようにtreatedされることをspecifiesする。ECMAScript 2015はまた、comparatorによってreturnedされるresultにToNumberがappliedされることをspecifiesする。previous editionsでは、Number valueでないcomparator resultのeffectはimplementation-definedであった。実際には、implementationsはToNumberをcallする。

Annex F (informative) 以前のEditionsとのIncompatibilitiesをIntroduceするAdditions and Changes

6.2.5:ECMAScript 2015では、Function callsはReference Recordをreturnすることがallowedされない。

7.1.4.1:ECMAScript 2015では、String valueにappliedされるToNumberは、BinaryIntegerLiteralおよびOctalIntegerLiteral numeric stringsをrecognizesしてconvertsするようになった。previous editionsでは、そのようなstringsはNaNへconvertedされていた。

9.3:ECMAScript 2018では、Template objectsは、previous editionsにおけるRealm内のそのtemplate literalまたはtagged templateのすべてのoccurrences acrossではなく、Parse Node(source location)に基づいてcanonicalizedされる。

12.2:ECMAScript 2016では、ECMAScript 2015がUnicode 5.1をmandatedしていたのに対し、Unicode 8.0.0以上がmandatedされる。特に、これはU+180E MONGOLIAN VOWEL SEPARATORを引き起こした。これはECMAScript 2015ではSpace_SeparatorZs)categoryにあり、したがってwhitespaceとしてtreatedされていたが、(Unicode 6.3.0以降)FormatCf)categoryへmovedされた。これにより、whitespace-sensitive methodsは異なってbehaveする。例えば、"\u180E".trim().lengthはprevious editionsでは0であったが、ECMAScript 2016以降では1である。さらに、ECMAScript 2017はUnicode Standardのlatest versionを常に使用することをmandatedした。

12.7:ECMAScript 2015では、IdentifierNameのvalid code pointsはUnicode properties “ID_Start”および“ID_Continue”のtermsでspecifiedされる。previous editionsでは、valid IdentifierNameまたはIdentifier code pointsは様々なUnicode code point categoriesをenumeratingすることでspecifiedされていた。

12.10.1:ECMAScript 2015では、semicolonがmissingしている場合、Automatic Semicolon Insertionはdo-while statementのendにsemicolonをaddsする。このchangeはspecificationをほとんどのexisting implementationsのactual behaviourにalignする。

13.2.5.1:ECMAScript 2015では、Object Initializersにduplicate property namesがあることはもはやearly errorではない。

13.15.1:ECMAScript 2015では、FunctionExpressionのfunction nameのようなimmutable bindingへのassignmentをcontainするstrict mode codeearly errorをproduceしない。代わりにruntime errorをproduceする。

14.2:ECMAScript 2015では、token letで始まり、その後にinput elements LineTerminator、次にIdentifierが続くStatementListLexicalDeclarationのstartである。previous editionsでは、automatic semicolon insertionは常にIdentifier input elementの前にsemicolonをinsertしていた。

14.5:ECMAScript 2015では、token letで始まりtoken [が続くStatementListItemLexicalDeclarationのstartである。previous editionsでは、そのようなsequenceはExpressionStatementのstartであった。

14.6.2:ECMAScript 2015では、IfStatementのnormal resultは決してvalue emptyではない。Statement partがevaluatedされない場合、またはevaluatedされたStatement partがempty含むnormal completionをproduceする場合、IfStatementのresultはundefinedである。

14.7:ECMAScript 2015では、for statementの( tokenの直後にtoken sequence let [が続く場合、そのletLexicalDeclarationのstartとしてtreatedされる。previous editionsでは、そのようなtoken sequenceはExpressionのstartであった。

14.7:ECMAScript 2015では、for-in statementの( tokenの直後にtoken sequence let [が続く場合、そのletForDeclarationのstartとしてtreatedされる。previous editionsでは、そのようなtoken sequenceはLeftHandSideExpressionのstartであった。

14.7:ECMAScript 2015より前、initialization expressionはin keywordにprecedeするVariableDeclarationのpartとしてappearできた。ECMAScript 2015では、同じpositionのForBindingはそのようなinitializerのoccurrenceをallowしない。ECMAScript 2017では、そのようなinitializerはnon-strict codeでのみpermittedされる。

14.7:ECMAScript 2015では、IterationStatementをevaluatingしたresultは、[[Value]]emptyであるnormal completionには決してならない。IterationStatementStatement partがevaluatedされない場合、またはStatement partのfinal evaluationが[[Value]]emptyであるnormal completionをproduceする場合、IterationStatementをevaluatingしたresultは[[Value]]undefinedであるnormal completionである。

14.11.2:ECMAScript 2015では、WithStatementをevaluatingしたresultは、[[Value]]emptyであるnormal completionには決してならない。WithStatementStatement partのevaluationが[[Value]]emptyであるnormal completionをproduceする場合、WithStatementをevaluatingしたresultは[[Value]]undefinedであるnormal completionである。

14.12.4:ECMAScript 2015では、SwitchStatementをevaluatingしたresultは、[[Value]]emptyであるnormal completionには決してならない。SwitchStatementCaseBlock partのevaluationが[[Value]]emptyであるnormal completionをproduceする場合、SwitchStatementをevaluatingしたresultは[[Value]]undefinedであるnormal completionである。

14.15:ECMAScript 2015では、Catch clauseがCatch clause parameterとしてappearする同じIdentifierに対するvar declarationをcontainすることはearly errorである。previous editionsでは、そのようなvariable declarationはenclosing variable environment内でinstantiatedされるが、declarationのInitializer valueはCatch parameterにassignedされていた。

14.15, 19.2.1.3:ECMAScript 2015では、Catch clauseがnon-strict direct evalをevaluatesし、そのeval codeがCatch clause parameterとしてappearする同じIdentifierをbindするvarまたはFunctionDeclaration declarationを含む場合、runtime SyntaxErrorがthrownされる。

14.15.3:ECMAScript 2015では、TryStatementのresultは決してvalue emptyではない。TryStatementBlock partがempty含むnormal completionへevaluatesする場合、TryStatementのresultはundefinedである。TryStatementBlock partがthrow completionへevaluatesし、empty含むnormal completionへevaluatesするCatch partを持つ場合、Finally clauseがない、またはそのFinally clauseがempty normal completionへevaluatesするなら、TryStatementのresultはundefinedである。

15.4.5 ECMAScript 2015では、ObjectLiteral内のaccessor properties[[Get]]または[[Set]] attributeのvaluesとしてcreatedされるfunction objectsconstructor functionsではなく、"prototype" own propertyを持たない。previous editionでは、それらはconstructorsであり、"prototype" propertyを持っていた。

20.1.2.6:ECMAScript 2015では、Object.freezeへのargumentがobjectでない場合、それはown propertiesを持たないnon-extensible ordinary objectであるかのようにtreatedされる。previous editionでは、non-object argumentは常にTypeErrorをthrowさせていた。

20.1.2.8:ECMAScript 2015では、Object.getOwnPropertyDescriptorへのargumentがobjectでない場合、ToObjectを使用してそのargumentをcoerceするattemptが行われる。coercionがsuccessfulなら、resultがoriginal argument valueの代わりに使用される。previous editionでは、non-object argumentは常にTypeErrorをthrowさせていた。

20.1.2.10:ECMAScript 2015では、Object.getOwnPropertyNamesへのargumentがobjectでない場合、ToObjectを使用してそのargumentをcoerceするattemptが行われる。coercionがsuccessfulなら、resultがoriginal argument valueの代わりに使用される。previous editionでは、non-object argumentは常にTypeErrorをthrowさせていた。

20.1.2.12:ECMAScript 2015では、Object.getPrototypeOfへのargumentがobjectでない場合、ToObjectを使用してそのargumentをcoerceするattemptが行われる。coercionがsuccessfulなら、resultがoriginal argument valueの代わりに使用される。previous editionでは、non-object argumentは常にTypeErrorをthrowさせていた。

20.1.2.16:ECMAScript 2015では、Object.isExtensibleへのargumentがobjectでない場合、それはown propertiesを持たないnon-extensible ordinary objectであるかのようにtreatedされる。previous editionでは、non-object argumentは常にTypeErrorをthrowさせていた。

20.1.2.17:ECMAScript 2015では、Object.isFrozenへのargumentがobjectでない場合、それはown propertiesを持たないnon-extensible ordinary objectであるかのようにtreatedされる。previous editionでは、non-object argumentは常にTypeErrorをthrowさせていた。

20.1.2.18:ECMAScript 2015では、Object.isSealedへのargumentがobjectでない場合、それはown propertiesを持たないnon-extensible ordinary objectであるかのようにtreatedされる。previous editionでは、non-object argumentは常にTypeErrorをthrowさせていた。

20.1.2.19:ECMAScript 2015では、Object.keysへのargumentがobjectでない場合、ToObjectを使用してそのargumentをcoerceするattemptが行われる。coercionがsuccessfulなら、resultがoriginal argument valueの代わりに使用される。previous editionでは、non-object argumentは常にTypeErrorをthrowさせていた。

20.1.2.20:ECMAScript 2015では、Object.preventExtensionsへのargumentがobjectでない場合、それはown propertiesを持たないnon-extensible ordinary objectであるかのようにtreatedされる。previous editionでは、non-object argumentは常にTypeErrorをthrowさせていた。

20.1.2.22:ECMAScript 2015では、Object.sealへのargumentがobjectでない場合、それはown propertiesを持たないnon-extensible ordinary objectであるかのようにtreatedされる。previous editionでは、non-object argumentは常にTypeErrorをthrowさせていた。

20.2.3.2:ECMAScript 2015では、bound functionの[[Prototype]] internal slotは、そのtarget functionの[[GetPrototypeOf]] valueに設定される。previous editionでは、[[Prototype]]は常に%Function.prototype%に設定されていた。

20.2.4.1:ECMAScript 2015では、function instancesの"length" propertyはconfigurableである。previous editionsではnon-configurableであった。

20.5.6.2:ECMAScript 2015では、NativeError constructor[[Prototype]] internal slotはError constructorである。previous editionsではFunction prototype objectであった。

21.4.4 ECMAScript 2015では、Date prototype objectはDate instanceではない。previous editionsでは、TimeValueがNaNであるDate instanceであった。

22.1.3.12 ECMAScript 2015では、String.prototype.localeCompare functionはUnicode Standardに従ってcanonically equivalentであるStringsをidenticalとしてtreatしなければならない。previous editionsでは、implementationsはcanonical equivalenceをignoreし、代わりにbit-wise comparisonを使用することがpermittedされていた。

22.1.3.28および22.1.3.30 ECMAScript 2015では、lowercase/upper conversion processingはcode points上でoperatesする。previous editionsでは、そのようなconversion processingはindividual code unitsにのみappliedされていた。affectedされるcode pointsはUnicodeのDeseret block内のものだけである。

22.1.3.32 ECMAScript 2015では、String.prototype.trim methodはUnicode BMP外にexistしうるwhite space code pointsをrecognizeするようにdefinedされる。しかし、Unicode 7時点ではそのようなcode pointsはdefinedされていない。previous editionsでは、そのようなcode pointsはwhite spaceとしてrecognizedされなかった。

22.2.4.1 ECMAScript 2015では、pattern argumentがRegExp instanceでありflags argumentがundefinedでない場合、patternと同じだがpatternのflagsがargument flagsでreplacedされたnew RegExp instanceがcreatedされる。previous editionsでは、patternがRegExp instanceでありflagsundefinedでない場合、TypeError例外がthrownされていた。

22.2.6 ECMAScript 2015では、RegExp prototype objectはRegExp instanceではない。previous editionsでは、patternがempty StringであるRegExp instanceであった。

22.2.6 ECMAScript 2015では、"source""global""ignoreCase"、および"multiline"RegExp prototype object上でdefinedされるaccessor propertiesである。previous editionsでは、それらはRegExp instances上でdefinedされるdata propertiesであった。

25.4.10:ECMAScript 2019では、Atomics.waitとのconfusionをpreventするため、Atomics.wakeAtomics.notifyへrenamedされた。

27.1.5.4, 27.9.3.6:ECMAScript 2019では、awaitによってenqueuedされるJobsのnumberがreducedされ、これはthen() callとawait expressionの間のresolution orderにobservable differenceをcreateしうる。

Bibliography

  1. IEEE 754-2019: IEEE Standard for Floating-Point Arithmetic. Institute of Electrical and Electronic Engineers, New York (2019) Note

    ECMA-262 specificationに影響するnormative changesは、IEEE 754-2008とIEEE 754-2019の間にない。

  2. The Unicode Standard、<https://unicode.org/versions/latest>で入手可能
  3. Unicode Technical Note #5: Canonical Equivalence in Applications、<https://unicode.org/notes/tn5/>で入手可能
  4. Unicode Technical Standard #10: Unicode Collation Algorithm、<https://unicode.org/reports/tr10/>で入手可能
  5. Unicode Standard Annex #15, Unicode Normalization Forms、<https://unicode.org/reports/tr15/>で入手可能
  6. Unicode Standard Annex #18: Unicode Regular Expressions、<https://unicode.org/reports/tr18/>で入手可能
  7. Unicode Standard Annex #24: Unicode Script Property、<https://unicode.org/reports/tr24/>で入手可能
  8. Unicode Standard Annex #31, Unicode Identifiers and Pattern Syntax、<https://unicode.org/reports/tr31/>で入手可能
  9. Unicode Standard Annex #44: Unicode Character Database、<https://unicode.org/reports/tr44/>で入手可能
  10. Unicode Technical Standard #51: Unicode Emoji、<https://unicode.org/reports/tr51/>で入手可能
  11. IANA Time Zone Database、<https://www.iana.org/time-zones>で入手可能
  12. ISO 8601:2004(E) Data elements and interchange formats — Information interchange — Representation of dates and times
  13. RFC 1738 “Uniform Resource Locators (URL)”、<https://tools.ietf.org/html/rfc1738>で入手可能
  14. RFC 2396 “Uniform Resource Identifiers (URI): Generic Syntax”、<https://tools.ietf.org/html/rfc2396>で入手可能
  15. RFC 3629 “UTF-8, a transformation format of ISO 10646”、<https://tools.ietf.org/html/rfc3629>で入手可能
  16. RFC 7231 “Hypertext Transfer Protocol (HTTP/1.1): Semantics and Content”、<https://tools.ietf.org/html/rfc7231>で入手可能

Colophon

このspecificationは、GitHub上で、Ecmarkupと呼ばれるplaintext source formatでauthoredされる。Ecmarkupは、plaintextでEcma specificationsをauthoringし、この文書のeditorial conventionsに従うfull-featured HTML renderingへspecificationをprocessingするためのframeworkおよびtoolsetを提供するHTML and Markdown dialectである。Ecmarkupは、syntaxをdefiningするためのGrammarkdownや、algorithm stepsをauthoringするためのEcmarkdownを含む、多数の他のformatsおよびtechnologiesをbuilds on and integratesする。このspecificationのPDF renderingsは、CSS Paged Media specificationを利用するprint stylesheetを使用してproducedされ、PrinceXMLを使用してconvertedされる。

このspecificationのprior editionsはWordを使用してauthoredされていた。このeditionのbasisをformedしたEcmarkup source textは、automated conversion toolを使用してECMAScript 2015 Word documentをEcmarkupへconvertingすることでproducedされた。

Copyright & Software License

Ecma International

Rue du Rhone 114

CH-1204 Geneva

Tel: +41 22 849 6000

Fax: +41 22 849 6001

Web: https://ecma-international.org/

Software License

All Software contained in this document ("Software") is protected by copyright and is being made available under the "BSD License", included below. This Software may be subject to third party rights (rights from parties other than Ecma International), including patent rights, and no licenses under such third party rights are granted under this license even if the third party concerned is a member of Ecma International. SEE THE ECMA CODE OF CONDUCT IN PATENT MATTERS AVAILABLE AT https://ecma-international.org/memento/codeofconduct.htm FOR INFORMATION REGARDING THE LICENSING OF PATENT CLAIMS THAT ARE REQUIRED TO IMPLEMENT ECMA INTERNATIONAL STANDARDS.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

  1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
  2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
  3. Neither the name of the authors nor Ecma International may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE ECMA INTERNATIONAL "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL ECMA INTERNATIONAL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.