Draft ECMA-262 / June 25, 2026 ECMAScript® 2027 言語仕様
導入
この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.prototypeにincludesという新しいメソッドが追加されました。
ECMAScript 2017では、Async Functions、Shared Memory、Atomicsが導入され、さらに小規模な言語およびライブラリの拡張、バグ修正、編集上の更新が行われました。Async functionsは、promiseを返す関数のための構文を提供することで、非同期プログラミング体験を改善します。Shared MemoryとAtomicsは、並列CPU上であっても明確に定義された実行順序を保証するアトミック操作を使用して、複数のエージェントからなるプログラムが通信できるようにする新しいメモリモデルを導入します。また、Objectに新しい静的メソッドとしてObject.values、Object.entries、Object.getOwnPropertyDescriptorsが含まれました。
ECMAScript 2018では、async iterator protocolとasync generatorsによる非同期反復のサポートが導入されました。また、4つの新しい正規表現機能、すなわちdotAllフラグ、名前付きキャプチャグループ、Unicodeプロパティエスケープ、および後読みアサーションも含まれました。最後に、object restおよびspreadプロパティも含まれました。
ECMAScript 2019では、いくつかの新しい組み込み関数が導入されました。配列を平坦化するためのArray.prototype上のflatとflatMap、Object.entriesの戻り値を直接新しいObjectに変換するObject.fromEntries、および広く実装されていたものの非標準であったString.prototype.trimLeftおよびtrimRight組み込みの、よりよい名前の代替としてのString.prototype上のtrimStartとtrimEndです。さらに、構文と意味論に対するいくつかの小さな更新も含まれました。更新された構文には、任意の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上のtoSorted、toReversed、with、findLast、findLastIndexメソッド、ならびに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.getFloat16、DataView.prototype.setFloat16、Math.f16roundメソッドが追加されました。
ECMAScript 2026、第17th 版では、大きさの異なるNumbersのiterable を、精度損失を最小化しながら合計するためのMath.sumPrecise、iterators を連結するためのIterator.concat、async 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-defined 、implementation-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コードがそのプロパティに異なる値を代入しようとすると失敗します。プロパティは、他のオブジェクト、プリミティブ値 、または関数 を保持するコンテナーです。プリミティブ値は、次の組み込み型のいずれかのメンバーです:Undefined 、Null 、Boolean 、Number 、BigInt 、String 、およびSymbol; オブジェクトは組み込み型Object のメンバーです。そして関数は呼び出し可能なオブジェクトです。プロパティを介してオブジェクトに関連付けられた関数は、メソッド と呼ばれます。
ECMAScriptは、ECMAScriptエンティティの定義を補完する組み込みオブジェクト の集合を定義します。これらの組み込みオブジェクトには、グローバルオブジェクト、Object、Function、Boolean、Symbol、およびさまざまなErrorオブジェクトを含む、言語のruntime semantics に基本的なオブジェクト、Math、Number、Dateを含む数値を表し操作するオブジェクト、テキスト処理オブジェクトであるStringとRegExp、Arrayおよび要素がすべて特定の数値データ表現を持つ9種類のTyped Arraysを含む値のindexed collectionsであるオブジェクト、MapおよびSetオブジェクトを含むkeyed collections、JSONオブジェクト、ArrayBuffer、SharedArrayBuffer、DataViewを含む構造化データをサポートするオブジェクト、generator functionsおよびPromiseオブジェクトを含む制御抽象化をサポートするオブジェクト、ならびにProxyとReflectを含む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
classベースのオブジェクト指向言語では、一般に、状態はインスタンスによって担われ、メソッドはクラスによって担われ、継承は構造と振る舞いのみのものです。ECMAScriptでは、状態とメソッドはオブジェクトによって担われ、一方で構造、振る舞い、および状態はすべて継承されます。
自分自身では、プロトタイプが含む特定のプロパティを直接含まないすべてのオブジェクトは、そのプロパティとその値を共有します。図1はこれを示しています:
CF はコンストラクター(かつオブジェクト)です。new式を使用して5つのオブジェクトが作成されています:cf1 、cf2 、cf3 、cf4 、およびcf5 です。これらの各オブジェクトは、"q1" および"q2" という名前のプロパティを含みます。破線は暗黙のプロトタイプ関係を表します。したがって、たとえば、cf3 のプロトタイプはCFp です。コンストラクターCF は、それ自体に"P1" および"P2" という名前の2つのプロパティを持ちますが、これらはCFp 、cf1 、cf2 、cf3 、cf4 、またはcf5 からは見えません。CFp 内の"CFP1" という名前のプロパティは、cf1 、cf2 、cf3 、cf4 、およびcf5 によって共有されます(ただしCF によっては共有されません)。同様に、CFp の暗黙のプロトタイプチェーン内に見つかる、"q1" 、"q2" 、または"CFP1" という名前でない任意のプロパティも共有されます。CF とCFp の間には暗黙のプロトタイプリンクがないことに注意してください。
ほとんどのclassベースのオブジェクト言語とは異なり、プロパティは値を代入することによって動的にオブジェクトへ追加できます。つまり、コンストラクターは、構築されるオブジェクトのすべてまたはいずれかのプロパティを命名したり、それらに値を代入したりする必要はありません。上の図では、CFp 内のプロパティに新しい値を代入することにより、cf1 、cf2 、cf3 、cf4 、および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.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
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値はtrue とfalse の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 InputElementDiv 、InputElementTemplateTail 、InputElementRegExp 、InputElementRegExpOrTemplateTail 、または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 は補足文法の非終端です。これは以下を意味します:
もともとp に一致したtokensの列が、n をgoal symbol として再度解析されます。n が文法パラメーターを取る場合、それらはp がもともと解析されたときに使用されたものと同じ値に設定されます。
tokensの列が、tokensを残すことなく、n の単一のインスタンスとして解析できる場合:
そのn のインスタンス(与えられたp に対して一意なParse Node)を、“p によってcovered されるn ”と呼びます。
n およびその導出生成に対するすべてのEarly Error rulesも、p によってcoveredされるn に適用されます。
それ以外(解析が失敗した場合)は、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つの形式があります:
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
Initializer opt
次の便利な省略形であることを意味します:
VariableDeclaration :
BindingIdentifier
BindingIdentifier
Initializer
また、次が:
ForStatement :
for
(
LexicalDeclaration
Expression opt
;
Expression opt
)
Statement
次の便利な省略形であることも意味します:
ForStatement :
for
(
LexicalDeclaration
;
Expression opt
)
Statement
for
(
LexicalDeclaration
Expression
;
Expression opt
)
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 が先読み制約内(列集合の一部としての場合を含む)に現れることは編集上の誤りと見なされます。
“[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レベルでは数値ラベルが使用されます。たとえば:
トップレベルステップサブステップ。 サブステップ。サブサブステップ。サブサブサブステップサブサブサブサブステップサブサブサブサブサブステップ
ステップまたはサブステップは、そのサブステップを条件付ける“if”述語として書かれることがあります。この場合、サブステップは述語がtrueである場合にのみ適用されます。ステップまたはサブステップが“else”という語で始まる場合、それは同じレベルの直前の“if”述語ステップの否定である述語です。
ステップは、そのサブステップの反復適用を指定するために“For each”または“Repeat”で始まることがあります。
“Assert :”で始まるステップは、そのアルゴリズムの不変条件を表明します。そのような表明は、そうでなければ暗黙であるアルゴリズム上の不変条件を明示するために使用されます。同様に、“NOTE :”で始まるステップは、近くのステップに関する関連する文脈を提供します。Assertion stepsおよびnote stepsは厳密に情報提供であり、追加の意味的要件を加えないため、実装によってチェックされる必要はありません。
アルゴリズムステップは、“Let x be someValue ”という形式を使用して任意の値に名前付きaliasを宣言できます。これらのaliasは、x とsomeValue の双方が同じ基礎データを参照し、どちらに対する変更も双方から見えるという点で参照のようなものです。この参照のような振る舞いを避けたいアルゴリズムステップは、右辺のコピーを明示的に作成するべきです:“Let x be a copy of someValue ”はsomeValue の浅いコピーを作成します。
一度宣言されると、aliasは後続の任意のステップで参照できますが、aliasの宣言より前のステップから参照してはなりません。aliasは、“Set x to someOtherValue ”という形式を使用して変更できます。
5.2.1 評価順序
複雑な式がアルゴリズムステップ内に現れる場合、それらは左から右、内側から外側の順序で評価されるものと理解されます。たとえば、ステップ
A(B(), C.[[D]] ) + E(F())を返す。
は次と等価です
tmp1 をB()とする。tmp2 をC.[[D]] とする。tmp3 をA(tmp1 , tmp2 )とする。tmp4 をF()とする。tmp5 をE(tmp4 )とする。tmp6 をtmp3 + tmp5 とする。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は、以下のアルゴリズム内のステップ1 、3 、および4 上の慣例を使用して、parse nodeと、任意で他のパラメーターとともに呼び出されます:
status をSomeNonTerminal のSyntaxDirectedOperationとする。someParseNode を何らかのsource textのparseとする。someParseNode のSyntaxDirectedOperationを実行する。argument "value" 付きでsomeParseNode のSyntaxDirectedOperationを実行する。
明示的に別途指定されない限り、すべてのchain productions は、その生成の左辺非終端に適用され得るすべての操作について暗黙の定義を持ちます。暗黙の定義は、同じ操作を、同じパラメーターがあればそれらとともに、chain production の唯一の右辺非終端へ再適用し、その後結果を返すだけです。たとえば、あるアルゴリズムに“Return Evaluation of Block ”という形式のステップがあり、次の生成があると仮定します:
Block :
{
StatementList
}
しかしEvaluation 操作がその生成とアルゴリズムを関連付けていない場合、そのときEvaluation 操作は暗黙に次の形式の関連付けを含みます:
Runtime Semantics: Evaluation
Block :
{
StatementList
}
StatementList のEvaluation を返す。
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:
Assert : completionRecord はCompletion Record である。completionRecord を返す。
5.2.4.2 Throw
アルゴリズムステップにおいて、“throw”という語は、ThrowCompletion を呼び出した結果を返すことの省略形です。たとえば、
result .[[Error]] がnone でないなら、result .[[Error]] をthrowする。
は次と等価です
result .[[Error]] がnone でないなら、ThrowCompletion (result .[[Error]] )を返す。
特定の型の例外をthrowすると述べるアルゴリズムステップは、throwされるその型の例外を構築します。たとえば、
TypeError 例外をthrowする。
は次と等価です
ThrowCompletion (newly created TypeError object)を返す。
5.2.4.3 Completion Recordsをアンラップするための省略形
Prefix “?”および“!”は、Completion Records をアンラップする省略形として使用されます。“?”は、abrupt completion を呼び出し元へ伝播するか、そうでなければnormal completion をアンラップするために使用されます。“!”は、Completion Record がnormalであることを表明し、それをアンラップするために使用されます。形式的には、ステップ
result を ? record とする。
は次と等価です
Assert : record はCompletion Record である。record がabrupt completion なら、record を返す。result をrecord .[[Value]] とする。
同様に、ステップ
result を ! record とする。
は次と等価です
Assert : record はnormal completion である。result をrecord .[[Value]] とする。
“?”または“!”が他の任意の文脈で使用される場合、この規則が適用できるようになるまで、まず評価順序 で与えられる書き換えを適用し、その後この規則を適用します。たとえば、ステップ
AO(? Other())を実行する。
は次のように書き換えることができます
tmp1 をOther()とする。tmp2 を ? tmp1 とする。AO(tmp2 )を実行する。
これはさらに次のように展開されます
tmp1 をOther()とする。Assert : tmp1 はCompletion Record である。tmp1 がabrupt completion なら、tmp1 を返す。tmp2 をtmp1 .[[Value]] とする。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 内では、
true を返す。
は次のいずれとも同じ意味です
NormalCompletion (true )を返す。
または
completion をNormalCompletion (true )とする。Completion (completion )を返す。
または
Completion Record { [[Type]] : normal , [[Value]] : true , [[Target]] : empty }を返す。
?省略形の展開 を通じて、次の例は許可されることに注意してください。展開後のステップ内では、abruptの場合にCompletion を適用した結果が直接返され、normalの場合にアンラップ後に暗黙のNormalCompletion 適用が発生するためです。
? completion を返す。
次の例は、Completion Record がそのステップで注釈されずに返されているため、編集上の誤りになります。
completion をNormalCompletion (true )とする。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 数学演算
この仕様は、以下の種類の数値を参照します:
この仕様の言語では、数値は下付き接尾辞を使用して異なる数値種別の間で区別されます。下付き文字𝔽 は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 は定義されません。x のextended mathematical value of は、有限値についてはx のmathematical 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 ”という句(ここでx はextended mathematical value であり、lower およびupper はlower ≤ upper を満たす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 ) を生成します。
数学関数min 、max 、abs 、floor 、および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 であって a ≤ x ≤ b を満たすものを含み、それ以外を含みません。
a (inclusive)からb (exclusive)までのinterval は、同じ数値型のすべての値x であって a ≤ x < b を満たすものを含み、それ以外を含みません。
a (exclusive)からb (inclusive)までのinterval は、同じ数値型のすべての値x であって a < x ≤ b を満たすものを含み、それ以外を含みません。
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 𝔽 は含みません。NaN はinterval に決して含まれません。
5.2.7 値記法
この仕様では、ECMAScript言語値 はbold で表示されます。例にはnull 、true 、または"hello" が含まれます。これらは、Function.prototype.applyやlet 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 values 、ECMAScript source text 、surrogate pairs 、Directive Prologues など、UTF-16 code units、Unicode code points、enums 、abstract operations (syntax-directed operations 、host hooks などを含む)、およびordered pairsが含まれますが、これらに限定されません。specification identityを持つ仕様値の例には、Property Descriptors 、PrivateElements などを含む任意の種類のRecords 、Parse Nodes 、Lists 、Sets およびRelations 、Abstract Closures 、Data Blocks 、Private Names 、execution contexts およびexecution context stacks 、agent signifiers 、ならびにWaiterList Records が含まれますが、これらに限定されません。
Specification identityは、Symbol.for によって生成されたSymbol valuesを除くすべてのECMAScript言語値 についてlanguage identityと一致します。specification identityもlanguage identityも持たないECMAScript言語値 は、undefined 、null 、Booleans 、Strings 、Numbers 、および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 として定義される)に対して、以下の規則を使用して特別な扱いを適用します:
関数String.prototype.normalize(22.1.3.15 を参照)は、String値を明示的に正規化するために使用できます。String.prototype.localeCompare(22.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 までのstring のsubstring ”(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:
length をstring の長さとする。searchValue が空のStringであり、fromIndex ≤ length なら、fromIndex を返す。searchLength をsearchValue の長さとする。fromIndex ≤ i ≤ length - searchLength である各整数i について、昇順で、以下を行うcandidate をstring のi からi + searchLength までのsubstring とする。candidate がsearchValue なら、i を返す。not-found を返す。
Note 1
searchValue が空のStringであり、fromIndex ≤ string の長さである場合、このアルゴリズムは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:
length をstring の長さとする。searchLength をsearchValue の長さとする。Assert : fromIndex + searchLength ≤ length 。0 ≤ i ≤ fromIndex である各整数i について、降順で、以下を行うcandidate をstring のi からi + searchLength までのsubstring とする。candidate がsearchValue なら、i を返す。 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 zero とnegative 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 内のinteger 、e は-1074から971までの包含区間内のinteger です。
残りの9,007,199,254,740,990個(すなわち253 - 2 個)の値はdenormalizedであり、次の形式を持ちます
s × m × 2e
ここでs は1または-1、m は0(exclusive)から252 (exclusive)までのinterval 内のinteger 、e は-1074です。
大きさが253 以下であるすべての正および負のintegers は、Number型で表現可能であることに注意してください。integer 0はNumber型において2つの表現を持ちます:+0 𝔽 および-0 𝔽 です。
有限数は、非ゼロであり、それを表現するために使用されるinteger m (上に示した2つの形式のいずれか)が奇数である場合、odd significand を持ちます。それ以外の場合、even significand を持ちます。
この仕様では、“x の Number 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:
number がNaN なら、NaN を返す。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:
oldValue を ! ToInt32 (number ) とする。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. これはbase をexponent 乗した結果を表すimplementation-approximated な値を返します。 It performs the following steps when called:
exponent がNaN なら、NaN を返す。exponent が+0 𝔽 または-0 𝔽 のいずれかなら、1 𝔽 を返す。base がNaN なら、NaN を返す。base が+∞ 𝔽 なら、exponent > +0 𝔽 なら、+∞ 𝔽 を返す。+0 𝔽 を返す。base が-∞ 𝔽 なら、exponent > +0 𝔽 なら、exponent がodd integral Number なら、-∞ 𝔽 を返す。+∞ 𝔽 を返す。exponent がodd integral Number なら、-0 𝔽 を返す。+0 𝔽 を返す。base が+0 𝔽 なら、exponent > +0 𝔽 なら、+0 𝔽 を返す。+∞ 𝔽 を返す。base が-0 𝔽 なら、exponent > +0 𝔽 なら、exponent がodd integral Number なら、-0 𝔽 を返す。+0 𝔽 を返す。exponent がodd integral Number なら、-∞ 𝔽 を返す。+∞ 𝔽 を返す。Assert : base はfinite であり、+0 𝔽 でも-0 𝔽 でもない。exponent が+∞ 𝔽 なら、abs (ℝ (base )) > 1なら、+∞ 𝔽 を返す。abs (ℝ (base )) = 1なら、NaN を返す。+0 𝔽 を返す。exponent が-∞ 𝔽 なら、abs (ℝ (base )) > 1なら、+0 𝔽 を返す。abs (ℝ (base )) = 1なら、NaN を返す。+∞ 𝔽 を返す。Assert : exponent はfinite であり、+0 𝔽 でも-0 𝔽 でもない。base < -0 𝔽 かつexponent がintegral Number でないなら、NaN を返す。ℝ (base )をℝ (exponent )乗した結果を表すimplementation-approximated なNumber値を返す。
Note
base が1 𝔽 または-1 𝔽 であり、exponent が+∞ 𝔽 または-∞ 𝔽 である場合、またはbase が1 𝔽 でありexponent がNaN である場合の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の規則に従って乗算を実行し、x とy の積を生成します。 It performs the following steps when called:
x がNaN またはy がNaN なら、NaN を返す。x が+∞ 𝔽 または-∞ 𝔽 のいずれかなら、y が+0 𝔽 または-0 𝔽 のいずれかなら、NaN を返す。y > +0 𝔽 なら、x を返す。-x を返す。 y が+∞ 𝔽 または-∞ 𝔽 のいずれかなら、x が+0 𝔽 または-0 𝔽 のいずれかなら、NaN を返す。x > +0 𝔽 なら、y を返す。-y を返す。 x が-0 𝔽 なら、y が-0 𝔽 またはy < -0 𝔽 なら、+0 𝔽 を返す。-0 𝔽 を返す。y が-0 𝔽 なら、x < -0 𝔽 なら、+0 𝔽 を返す。-0 𝔽 を返す。𝔽 (ℝ (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とするx とy のquotientを生成します。 It performs the following steps when called:
x がNaN またはy がNaN なら、NaN を返す。x が+∞ 𝔽 または-∞ 𝔽 のいずれかなら、y が+∞ 𝔽 または-∞ 𝔽 のいずれかなら、NaN を返す。y が+0 𝔽 またはy > +0 𝔽 なら、x を返す。-x を返す。 y が+∞ 𝔽 なら、x が+0 𝔽 またはx > +0 𝔽 なら、+0 𝔽 を返す。-0 𝔽 を返す。y が-∞ 𝔽 なら、x が+0 𝔽 またはx > +0 𝔽 なら、-0 𝔽 を返す。+0 𝔽 を返す。x が+0 𝔽 または-0 𝔽 のいずれかなら、y が+0 𝔽 または-0 𝔽 のいずれかなら、NaN を返す。y > +0 𝔽 なら、x を返す。-x を返す。 y が+0 𝔽 なら、x > +0 𝔽 なら、+∞ 𝔽 を返す。-∞ 𝔽 を返す。y が-0 𝔽 なら、x > +0 𝔽 なら、-∞ 𝔽 を返す。+∞ 𝔽 を返す。𝔽 (ℝ (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:
numerator がNaN またはdenominator がNaN なら、NaN を返す。numerator が+∞ 𝔽 または-∞ 𝔽 のいずれかなら、NaN を返す。denominator が+∞ 𝔽 または-∞ 𝔽 のいずれかなら、numerator を返す。denominator が+0 𝔽 または-0 𝔽 のいずれかなら、NaN を返す。numerator が+0 𝔽 または-0 𝔽 のいずれかなら、numerator を返す。Assert : numerator とdenominator はfinite かつnon-zeroである。quotient をℝ (numerator ) / ℝ (denominator )とする。truncatedQuotient をtruncate (quotient )とする。remainder をℝ (numerator ) - (ℝ (denominator ) × truncatedQuotient )とする。remainder = 0かつnumerator < -0 𝔽 なら、-0 𝔽 を返す。𝔽 (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:
x がNaN またはy がNaN なら、NaN を返す。x が+∞ 𝔽 かつy が-∞ 𝔽 なら、NaN を返す。x が-∞ 𝔽 かつy が+∞ 𝔽 なら、NaN を返す。x が+∞ 𝔽 または-∞ 𝔽 のいずれかなら、x を返す。y が+∞ 𝔽 または-∞ 𝔽 のいずれかなら、y を返す。Assert : x とy はともにfinite である。x が-0 𝔽 かつy が-0 𝔽 なら、-0 𝔽 を返す。𝔽 (ℝ (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:
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:
leftNumber を ! ToInt32 (x ) とする。rightNumber を ! ToUint32 (y ) とする。shiftCount をℝ (rightNumber ) modulo 32とする。leftNumber をshiftCount ビット左シフトした結果を返す。結果の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:
leftNumber を ! ToInt32 (x ) とする。rightNumber を ! ToUint32 (y ) とする。shiftCount をℝ (rightNumber ) modulo 32とする。leftNumber をshiftCount ビットだけ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:
leftNumber を ! ToUint32 (x ) とする。rightNumber を ! ToUint32 (y ) とする。shiftCount をℝ (rightNumber ) modulo 32とする。leftNumber をshiftCount ビットだけ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:
x がNaN なら、undefined を返す。y がNaN なら、undefined を返す。x がy なら、false を返す。x が+0 𝔽 かつy が-0 𝔽 なら、false を返す。x が-0 𝔽 かつy が+0 𝔽 なら、false を返す。x が+∞ 𝔽 なら、false を返す。y が+∞ 𝔽 なら、true を返す。y が-∞ 𝔽 なら、false を返す。x が-∞ 𝔽 なら、true を返す。Assert : x とy はfinite である。ℝ (x ) < ℝ (y )なら、true を返す。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:
x がNaN なら、false を返す。y がNaN なら、false を返す。x がy なら、true を返す。x が+0 𝔽 かつy が-0 𝔽 なら、true を返す。x が-0 𝔽 かつy が+0 𝔽 なら、true を返す。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:
x がNaN かつy がNaN なら、true を返す。x が+0 𝔽 かつy が-0 𝔽 なら、false を返す。x が-0 𝔽 かつy が+0 𝔽 なら、false を返す。x がy なら、true を返す。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:
x がNaN かつy がNaN なら、true を返す。x が+0 𝔽 かつy が-0 𝔽 なら、true を返す。x が-0 𝔽 かつy が+0 𝔽 なら、true を返す。x がy なら、true を返す。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:
leftNumber を ! ToInt32 (x ) とする。rightNumber を ! ToInt32 (y ) とする。leftBits をℝ (leftNumber )を表す32ビットtwo's complement bit stringとする。rightBits をℝ (rightNumber )を表す32ビットtwo's complement bit stringとする。op が&なら、result をleftBits およびrightBits にbitwise AND操作を適用した結果とする。そうでなく、op が^なら、result をleftBits およびrightBits にbitwise exclusive OR(XOR)操作を適用した結果とする。 そうでなければ、Assert : op は|である。result をleftBits およびrightBits にbitwise inclusive OR操作を適用した結果とする。 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:
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:
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:
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:
x がNaN なら、"NaN" を返す。x が+0 𝔽 または-0 𝔽 のいずれかなら、"0" を返す。x < -0 𝔽 なら、"-" とNumber::toString (-x , radix )のstring-concatenation を返す。x が+∞ 𝔽 なら、"Infinity" を返す。n 、k 、およびs を、k ≥ 1、radix k - 1 ≤ s < radix k 、𝔽 (s × radix n - k ) がx であり、かつk が可能な限り小さいようなintegers とする。k はradix を用いるs の表現内のdigitsの数であり、s はradix で割り切れず、s の最下位digitはこれらの基準によって必ずしも一意に決定されないことに注意。radix ≠ 10またはn が-5から21までの包含区間内にあるなら、n ≥ k なら、以下のstring-concatenation を返す:radix を使用するs の表現のk 個のdigitsのコード単位コード単位0x0030(DIGIT ZERO)のn - k 回の出現 n > 0なら、以下のstring-concatenation を返す:radix を使用するs の表現の最上位n 個のdigitsのコード単位コード単位0x002E(FULL STOP) radix を使用するs の表現の残りのk - n 個のdigitsのコード単位 Assert : n ≤ 0。以下のstring-concatenation を返す:コード単位0x0030(DIGIT ZERO) コード単位0x002E(FULL STOP) コード単位0x0030(DIGIT ZERO)の-n 回の出現 radix を使用するs の表現のk 個のdigitsのコード単位 NOTE : この場合、入力は1.2e+3のような科学的E記法を使用して表されます。Assert : radix は10である。n < 0なら、exponentSign をコード単位0x002D(HYPHEN-MINUS)とする。そうでなければ、exponentSign をコード単位0x002B(PLUS SIGN)とする。 k = 1なら、以下のstring-concatenation を返す:s の単一digitのコード単位コード単位0x0065(LATIN SMALL LETTER E) exponentSign abs (n - 1)の10進表現のコード単位 以下の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 の以下の代替版を指針として使用することが推奨されます:
n 、k 、およびs を、k ≥ 1、radix k - 1 ≤ s < radix k 、𝔽 (s × radix n - k ) がx であり、かつk が可能な限り小さいようなintegers とする。s に複数の可能性がある場合、s × radix n - k がℝ (x )に最も近くなるようにs を選ぶ。そのようなs の値が2つある場合、偶数であるものを選ぶ。k はradix を使用するs の表現内のdigitsの数であり、s はradix で割り切れないことに注意。
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:
bigint = 0 ℤ なら、0 ℤ を返す。-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:
-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:
exponent < 0 ℤ なら、RangeError 例外をthrowする。base = 0 ℤ かつexponent = 0 ℤ なら、1 ℤ を返す。base をexponent 乗したものを返す。
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:
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:
y = 0 ℤ なら、RangeError 例外をthrowする。quotient をℝ (x ) / ℝ (y )とする。ℤ (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:
denominator = 0 ℤ なら、RangeError 例外をthrowする。numerator = 0 ℤ なら、0 ℤ を返す。quotient をℝ (numerator ) / ℝ (denominator )とする。truncatedQuotient をℤ (truncate (quotient ))とする。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:
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:
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:
y < 0 ℤ なら、ℤ (floor (ℝ (x ) / 2-ℝ (y ) ))を返す。x × 2 ℤ y を返す。
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:
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:
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:
ℝ (x ) < ℝ (y )なら、true を返す。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:
ℝ (x ) = ℝ (y )なら、true を返す。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:
x = 1かつy = 1なら、1を返す。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:
x = 1またはy = 1なら、1を返す。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:
x = 1かつy = 0なら、1を返す。x = 0かつy = 1なら、1を返す。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:
x をℝ (x )に設定する。y をℝ (y )に設定する。result を0とする。shift を0とする。(x = 0またはx = -1)かつ(y = 0またはy = -1)になるまで、繰り返すxDigit をx modulo 2とする。yDigit をy modulo 2とする。op が&なら、result をresult + 2shift × BinaryAnd (xDigit , yDigit )に設定する。そうでなく、op が|なら、result をresult + 2shift × BinaryOr (xDigit , yDigit )に設定する。 そうでなければ、Assert : op は^である。result をresult + 2shift × BinaryXor (xDigit , yDigit )に設定する。 shift をshift + 1に設定する。x を(x - xDigit ) / 2に設定する。y を(y - yDigit ) / 2に設定する。 op が&なら、signBit をBinaryAnd (x modulo 2, y modulo 2)とする。そうでなく、op が|なら、signBit をBinaryOr (x modulo 2, y modulo 2)とする。 そうでなければ、Assert : op は^である。signBit をBinaryXor (x modulo 2, y modulo 2)とする。 signBit ≠ 0なら、result をresult - 2shift に設定する。NOTE : これは符号を拡張します。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:
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:
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:
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:
x < 0 ℤ なら、"-" とBigInt::toString (-x , radix )のstring-concatenation を返す。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
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を持ち、これはPrivateElements のList です。この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 object (Array exotic object やbound 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]] をサポートしなければなりません。すなわち、すべてのconstructor はfunction object でなければなりません。したがって、constructor はconstructor 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
[[GetPrototypeOf]] ( )
normal return typeはObjectまたはNullのいずれかです。
targetがnon-extensibleであり、[[GetPrototypeOf]] が値proto を返す場合、[[GetPrototypeOf]] への将来の呼び出しはSameValue をproto として返すべきです。
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 を返さなければなりません:
propertyKey がwritable data property である。non-configurable writable data property は、non-configurable non-writable data property に変更できます。
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]] はvalue とSameValue を返さなければなりません。
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 として観測されている場合、value がpropertyKey の[[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: よく知られた組込みオブジェクト
Note
Table 103 に追加のentriesがあります。
6.2 ECMAScript仕様型
仕様型は、ECMAScript言語構文およびECMAScript言語型 の意味論を記述するためにアルゴリズム内で使用されるメタ値に対応します。仕様型には、Reference Record 、List 、Completion Record 、Property Descriptor 、Environment Record 、Abstract Closure 、およびData Block が含まれます。仕様型値は、ECMAScript実装内の特定の実体に必ずしも対応しない仕様上の人工物です。仕様型値は、ECMAScript式評価の中間結果を記述するために使用される場合がありますが、そのような値をオブジェクトのプロパティやECMAScript言語変数の値として格納することはできません。
6.2.1 Enum仕様型
Enums は、仕様内部の値であり、ECMAScriptコードから直接観測できません。Enumsはsans-serif 書体を使用したupper kebab caseで表記されます。たとえば、Completion Record の[[Type]] フィールドは、normal 、return 、または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 です。
Note 1
上記の2つの性質は、それぞれirreflexivityおよびtransitivityと呼ばれます。
strict total order は、以下を満たすRelation値R です。
Note 2
上記の3つの性質は、それぞれtotality、irreflexivity、およびtransitivityと呼ばれます。
6.2.4 Completion Record仕様型
Completion Record 仕様型は、値の実行時伝播および、制御の非局所的移動を行う文(break、continue、returnおよび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:
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:
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:
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:
Assert : completionRecord がreturn completion またはthrow completion のいずれかであるなら、completionRecord .[[Value]] はempty ではない。completionRecord .[[Value]] がempty でないなら、? completionRecord を返す。Completion Record { [[Type]] : completionRecord .[[Type]] , [[Value]] : value , [[Target]] : completionRecord .[[Target]] }を返す。
6.2.5 Reference Record仕様型
Reference Record 型は、delete、typeof、代入演算子、superキーワード、およびその他の言語機能のような演算子の振る舞いを説明するために使用されます。たとえば、代入の左辺オペランドはReference Recordを生成することが期待されます。
Reference Recordは、解決済みの名前または(まだ解決されていない可能性のある)プロパティ束縛です。そのフィールドはTable 8 によって定義されます。
Table 8: Reference Record Fields
以下の抽象操作は、この仕様において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:
refRecord .[[Base]] がunresolvable なら、false を返す。refRecord .[[Base]] がEnvironment Record なら、false を返す。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:
refRecord .[[Base]] がunresolvable なら、true を返す。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:
refRecord .[[ThisValue]] がempty なら、false を返す。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:
refRecord .[[ReferencedName]] がPrivate Name なら、true を返す。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:
refRecord がReference Record でないなら、refRecord を返す。IsUnresolvableReference (refRecord )がtrue なら、ReferenceError 例外をthrowする。IsPropertyReference (refRecord )がtrue なら、baseObj を ? ToObject (refRecord .[[Base]] ) とする。IsPrivateReference (refRecord )がtrue なら、? PrivateGet (baseObj , refRecord .[[ReferencedName]] )を返す。 refRecord .[[ReferencedName]] がproperty key でないなら、refRecord .[[ReferencedName]] を ? ToPropertyKey (refRecord .[[ReferencedName]] ) に設定する。? baseObj .[[Get]] (refRecord .[[ReferencedName]] , GetThisValue (refRecord )) を返す。 base をrefRecord .[[Base]] とする。Assert : base はEnvironment Record である。? 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:
refRecord がReference Record でないなら、ReferenceError 例外をthrowする。IsUnresolvableReference (refRecord )がtrue なら、refRecord .[[Strict]] がtrue なら、ReferenceError 例外をthrowする。globalObj をGetGlobalObject ()とする。? Set (globalObj , refRecord .[[ReferencedName]] , value , false )を実行する。 unused を返す。IsPropertyReference (refRecord )がtrue なら、baseObj を ? ToObject (refRecord .[[Base]] ) とする。IsPrivateReference (refRecord )がtrue なら、? PrivateSet (baseObj , refRecord .[[ReferencedName]] , value )を返す。 refRecord .[[ReferencedName]] がproperty key でないなら、refRecord .[[ReferencedName]] を ? ToPropertyKey (refRecord .[[ReferencedName]] ) に設定する。succeeded を ? baseObj .[[Set]] (refRecord .[[ReferencedName]] , value , GetThisValue (refRecord )) とする。succeeded がfalse かつrefRecord .[[Strict]] がtrue なら、TypeError 例外をthrowする。unused を返す。base をrefRecord .[[Base]] とする。Assert : base はEnvironment Record である。? 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:
Assert : IsPropertyReference (refRecord )はtrue である。IsSuperReference (refRecord )がtrue なら、refRecord .[[ThisValue]] を返す。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:
Assert : IsUnresolvableReference (refRecord )はfalse である。base をrefRecord .[[Base]] とする。Assert : base はEnvironment Record である。? 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:
privateEnv をrunning execution context のPrivateEnvironmentとする。Assert : privateEnv はnull でない。privateName をResolvePrivateIdentifier (privateEnv , privateIdentifier )とする。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:
propertyDesc が[[Get]] フィールドを持つなら、true を返す。propertyDesc が[[Set]] フィールドを持つなら、true を返す。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:
propertyDesc が[[Value]] フィールドを持つなら、true を返す。propertyDesc が[[Writable]] フィールドを持つなら、true を返す。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:
IsAccessorDescriptor (propertyDesc )がtrue なら、false を返す。IsDataDescriptor (propertyDesc )がtrue なら、false を返す。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:
propertyDesc がundefined なら、undefined を返す。obj をOrdinaryObjectCreate (%Object.prototype% )とする。Assert : obj はown propertiesを持たないextensible ordinary object である。propertyDesc が[[Value]] フィールドを持つなら、! CreateDataPropertyOrThrow (obj , "value" , propertyDesc .[[Value]] )を実行する。 propertyDesc が[[Writable]] フィールドを持つなら、! CreateDataPropertyOrThrow (obj , "writable" , propertyDesc .[[Writable]] )を実行する。 propertyDesc が[[Get]] フィールドを持つなら、! CreateDataPropertyOrThrow (obj , "get" , propertyDesc .[[Get]] )を実行する。 propertyDesc が[[Set]] フィールドを持つなら、! CreateDataPropertyOrThrow (obj , "set" , propertyDesc .[[Set]] )を実行する。 propertyDesc が[[Enumerable]] フィールドを持つなら、! CreateDataPropertyOrThrow (obj , "enumerable" , propertyDesc .[[Enumerable]] )を実行する。 propertyDesc が[[Configurable]] フィールドを持つなら、! CreateDataPropertyOrThrow (obj , "configurable" , propertyDesc .[[Configurable]] )を実行する。 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:
obj がObjectでないなら、TypeError 例外をthrowする。propertyDesc を、初期状態でフィールドを持たない新しいProperty Descriptor とする。hasEnumerable を ? HasProperty (obj , "enumerable" ) とする。hasEnumerable がtrue なら、enumerable をToBoolean (? Get (obj , "enumerable" ))とする。propertyDesc .[[Enumerable]] をenumerable に設定する。hasConfigurable を ? HasProperty (obj , "configurable" ) とする。hasConfigurable がtrue なら、configurable をToBoolean (? Get (obj , "configurable" ))とする。propertyDesc .[[Configurable]] をconfigurable に設定する。hasValue を ? HasProperty (obj , "value" ) とする。hasValue がtrue なら、value を ? Get (obj , "value" ) とする。propertyDesc .[[Value]] をvalue に設定する。hasWritable を ? HasProperty (obj , "writable" ) とする。hasWritable がtrue なら、writable をToBoolean (? Get (obj , "writable" ))とする。propertyDesc .[[Writable]] をwritable に設定する。hasGet を ? HasProperty (obj , "get" ) とする。hasGet がtrue なら、getter を ? Get (obj , "get" ) とする。IsCallable (getter )がfalse かつgetter がundefined でないなら、TypeError 例外をthrowする。propertyDesc .[[Get]] をgetter に設定する。hasSet を ? HasProperty (obj , "set" ) とする。hasSet がtrue なら、setter を ? Get (obj , "set" ) とする。IsCallable (setter )がfalse かつsetter がundefined でないなら、TypeError 例外をthrowする。propertyDesc .[[Set]] をsetter に設定する。propertyDesc が[[Get]] フィールドを持つ、またはpropertyDesc が[[Set]] フィールドを持つなら、propertyDesc が[[Value]] フィールドを持つ、またはpropertyDesc が[[Writable]] フィールドを持つなら、TypeError 例外をthrowする。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:
like をRecord { [[Value]] : undefined , [[Writable]] : false , [[Get]] : undefined , [[Set]] : undefined , [[Enumerable]] : false , [[Configurable]] : false }とする。IsGenericDescriptor (propertyDesc )がtrue またはIsDataDescriptor (propertyDesc )がtrue なら、propertyDesc が[[Value]] フィールドを持たないなら、propertyDesc .[[Value]] をlike .[[Value]] に設定する。propertyDesc が[[Writable]] フィールドを持たないなら、propertyDesc .[[Writable]] をlike .[[Writable]] に設定する。そうでなければ、propertyDesc が[[Get]] フィールドを持たないなら、propertyDesc .[[Get]] をlike .[[Get]] に設定する。propertyDesc が[[Set]] フィールドを持たないなら、propertyDesc .[[Set]] をlike .[[Set]] に設定する。 propertyDesc が[[Enumerable]] フィールドを持たないなら、propertyDesc .[[Enumerable]] をlike .[[Enumerable]] に設定する。propertyDesc が[[Configurable]] フィールドを持たないなら、propertyDesc .[[Configurable]] をlike .[[Configurable]] に設定する。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 Record はnormal completion またはthrow completion のいずれかでなければなりません。
Abstract Closuresは、他のアルゴリズムの一部としてインラインで作成されます。以下の例に示します。
addend を41とする。closure を、parameters (x )を持ち、addend をcaptureし、呼び出されたときに以下のステップを実行する新しいAbstract Closure とする:x + addend を返す。value をclosure (1)とする。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:
size > 253 - 1なら、RangeError 例外をthrowする。dataBlock をsize bytesからなる新しいData Block 値とする。そのようなData Block を作成することが不可能な場合、RangeError 例外をthrowする。dataBlock のすべてのbytesを0に設定する。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:
dataBlock をsize bytesからなる新しいShared Data Block 値とする。そのようなShared Data Block を作成することが不可能な場合、RangeError 例外をthrowする。agentRecord をsurrounding agent のAgent Record とする。execution をagentRecord .[[CandidateExecution]] とする。eventsRecord を、[[AgentSignifier]] がAgentSignifier ()であるexecution .[[EventsRecords]] のAgent Events Record とする。zero を« 0 »とする。dataBlock の各index index について、以下を行うWriteSharedMemory { [[Order]] : init , [[NoTear]] : true , [[Block]] : dataBlock , [[ByteIndex]] : index , [[ElementSize]] : 1, [[Payload]] : zero }をeventsRecord .[[EventList]] へappendする。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:
Assert : fromBlock とtoBlock は別個の値である。fromSize をfromBlock 内のbytesの数とする。Assert : fromIndex + count ≤ fromSize 。toSize をtoBlock 内のbytesの数とする。Assert : toIndex + count ≤ toSize 。count > 0の間、繰り返すfromBlock がShared Data Block なら、agentRecord をsurrounding agent のAgent Record とする。execution をagentRecord .[[CandidateExecution]] とする。eventsRecord を、[[AgentSignifier]] がAgentSignifier ()であるexecution .[[EventsRecords]] のAgent Events Record とする。bytes を、唯一の要素が非決定的に選択されたbyte value であるList とする。NOTE : 実装では、bytes は基礎となるハードウェア上のnon-atomic read instructionの結果です。この非決定性は、weak consistencyを持つハードウェアの観測可能な振る舞いを記述するためのmemory model の意味論的規定です。readEvent をReadSharedMemory { [[Order]] : unordered , [[NoTear]] : true , [[Block]] : fromBlock , [[ByteIndex]] : fromIndex , [[ElementSize]] : 1 }とする。readEvent をeventsRecord .[[EventList]] へappendする。Chosen Value Record { [[Event]] : readEvent , [[ChosenValue]] : bytes }をexecution .[[ChosenValues]] へappendする。toBlock がShared Data Block なら、WriteSharedMemory { [[Order]] : unordered , [[NoTear]] : true , [[Block]] : toBlock , [[ByteIndex]] : toIndex , [[ElementSize]] : 1, [[Payload]] : bytes }をeventsRecord .[[EventList]] へappendする。そうでなければ、toBlock [toIndex ]をbytes [0]に設定する。 そうでなければ、Assert : toBlock はShared Data Block ではない。toBlock [toIndex ]をfromBlock [fromIndex ]に設定する。 toIndex をtoIndex + 1に設定する。fromIndex をfromIndex + 1に設定する。count をcount - 1に設定する。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
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:
input がObjectなら、exoticToPrimitive を ? GetMethod (input , %Symbol.toPrimitive% ) とする。exoticToPrimitive がundefined でないなら、preferredType が存在しないなら、hint を"default" とする。そうでなく、preferredType がstring なら、hint を"string" とする。 そうでなければ、Assert : preferredType はnumber である。hint を"number" とする。 result を ? Call (exoticToPrimitive , input , « hint ») とする。result がObjectでないなら、result を返す。TypeError 例外をthrowする。preferredType が存在しないなら、preferredType をnumber に設定する。? OrdinaryToPrimitive (input , preferredType )を返す。 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:
hint がstring なら、methodNames を« "toString" , "valueOf" »とする。そうでなければ、methodNames を« "valueOf" , "toString" »とする。 methodNames の各要素name について、以下を行うmethod を ? Get (obj , name ) とする。IsCallable (method )がtrue なら、result を ? Call (method , obj ) とする。result がObjectでないなら、result を返す。TypeError 例外をthrowする。
7.1.2 ToBoolean ( arg )
The abstract operation ToBoolean takes argument arg (an ECMAScript language value) and returns a Boolean. これはarg をBoolean型 の値へ変換します。 It performs the following steps when called:
arg がBooleanなら、arg を返す。arg がundefined 、null 、+0 𝔽 、-0 𝔽 、NaN 、0 ℤ 、または空のStringのいずれかなら、false を返す。hostがweb browserであるか、または他の方法で[[IsHTMLDDA]] Internal Slot をサポートするなら、arg がObjectであり、arg が[[IsHTMLDDA]] internal slotを持つなら、false を返す。 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:
primitiveValue を ? ToPrimitive (arg , number ) とする。primitiveValue がBigIntなら、primitiveValue を返す。? 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 . これはarg をNumber型 の値へ変換します。 It performs the following steps when called:
arg がNumberなら、arg を返す。arg がSymbolまたはBigIntのいずれかなら、TypeError 例外をthrowする。arg がundefined なら、NaN を返す。arg がnull またはfalse のいずれかなら、+0 𝔽 を返す。arg がtrue なら、1 𝔽 を返す。arg がStringなら、StringToNumber (arg )を返す。Assert : arg はObjectである。primitiveValue を ? ToPrimitive (arg , number ) とする。Assert : primitiveValue はObjectでない。? ToNumber (primitiveValue )を返す。
7.1.4.1 String型に適用されるToNumber
抽象操作StringToNumber は、以下の文法を使用してString値をNumber値へ変換する方法を指定します。
構文
StringNumericLiteral :::
StrWhiteSpace opt
StrWhiteSpace opt
StrNumericLiteral
StrWhiteSpace opt
StrWhiteSpace :::
StrWhiteSpaceChar
StrWhiteSpace opt
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
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:
literal をParseText (string , StringNumericLiteral )とする。literal がerrorsのList なら、NaN を返す。literal のStringNumericValue を返す。
7.1.4.1.2 Runtime Semantics: StringNumericValue
The syntax-directed operation StringNumericValue takes no arguments and returns a Number.
Note
It is defined piecewise over the following productions:
StringNumericLiteral ::: StrWhiteSpace opt
+0 𝔽 を返す。
StringNumericLiteral :::
StrWhiteSpace opt
StrNumericLiteral
StrWhiteSpace opt
StrNumericLiteral のStringNumericValue を返す。
StrNumericLiteral ::: NonDecimalIntegerLiteral
𝔽 (NonDecimalIntegerLiteral のMV)を返す。
StrDecimalLiteral :::
-
StrUnsignedDecimalLiteral
a をStrUnsignedDecimalLiteral のStringNumericValue とする。a が+0 𝔽 なら、-0 𝔽 を返す。-a を返す。
StrUnsignedDecimalLiteral ::: Infinity
+∞ 𝔽 を返す。
StrUnsignedDecimalLiteral :::
DecimalDigits
.
DecimalDigits opt
ExponentPart opt
a を最初のDecimalDigits のMVとする。2番目のDecimalDigits が存在するなら、b を2番目のDecimalDigits のMVとする。n を2番目のDecimalDigits 内のcode pointsの数とする。 そうでなければ、b を0とする。n を0とする。 ExponentPart が存在するなら、e をExponentPart のMVとする。そうでなければ、e を0とする。RoundMVResult ((a + (b × 10-n )) × 10e )を返す。
StrUnsignedDecimalLiteral :::
.
DecimalDigits
ExponentPart opt
b をDecimalDigits のMVとする。ExponentPart が存在するなら、e をExponentPart のMVとする。そうでなければ、e を0とする。n をDecimalDigits 内のcode pointsの数とする。RoundMVResult (b × 10e - n )を返す。
StrUnsignedDecimalLiteral :::
DecimalDigits
ExponentPart opt
a をDecimalDigits のMVとする。ExponentPart が存在するなら、e をExponentPart のMVとする。そうでなければ、e を0とする。RoundMVResult (a × 10e )を返す。
7.1.4.1.3 RoundMVResult ( n )
The abstract operation RoundMVResult takes argument n (a mathematical value ) and returns a Number. これはn をimplementation-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:
n のdecimal representationが20個以下のsignificant digitsを持つなら、𝔽 (n )を返す。option1 を、n のdecimal representation内の20番目以降の各significant digitを0 digitで置き換えた結果が表すmathematical value とする。option2 を、n のdecimal representation内の20番目以降の各significant digitを0 digitで置き換え、その後20番目の位置でそれをincrementした結果(必要に応じて繰り上がりを伴う)が表すmathematical value とする。chosen をoption1 またはoption2 のいずれかのimplementation-defined な選択とする。𝔽 (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:
number を ? ToNumber (arg ) とする。number がNaN 、+0 𝔽 、または-0 𝔽 のいずれかなら、0を返す。number が+∞ 𝔽 なら、+∞を返す。number が-∞ 𝔽 なら、-∞を返す。truncate (ℝ (number ))を返す。
Note
𝔽 (ToIntegerOrInfinity(
x ))は、
x の任意の値について決して
-0 𝔽 を返しません。小数部の切り捨ては、
x を
mathematical 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 を、signed がunsigned の場合は0から2bitWidth - 1までの包含区間内の2bitWidth 個のintegers の1つへ、またはsigned がsigned の場合は-2bitWidth - 1 から2bitWidth - 1 - 1までの包含区間内の2bitWidth 個のintegers の1つへ写像します。 It performs the following steps when called:
int = +∞またはint = -∞なら、0を返す。fixedInt をint modulo 2bitWidth とする。NOTE : 次のステップはfixedInt のtwo's complement representationを変更しません。signed がsigned かつfixedInt ≥ 2bitWidth - 1 なら、fixedInt をfixedInt - 2bitWidth に設定する。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:
int を ? ToIntegerOrInfinity (arg ) とする。𝔽 (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:
int を ? ToIntegerOrInfinity (arg ) とする。𝔽 (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:
int を ? ToIntegerOrInfinity (arg ) とする。𝔽 (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:
int を ? ToIntegerOrInfinity (arg ) とする。𝔽 (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:
int を ? ToIntegerOrInfinity (arg ) とする。𝔽 (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:
int を ? ToIntegerOrInfinity (arg ) とする。𝔽 (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:
number を ? ToNumber (arg ) とする。number がNaN なら、+0 𝔽 を返す。mv をnumber のextended mathematical value とする。clamped をmv を0から255の間にclampした結果とする。f をfloor (clamped )とする。clamped < f + 0.5なら、𝔽 (f )を返す。clamped > f + 0.5なら、𝔽 (f + 1)を返す。f がevenなら、𝔽 (f )を返す。𝔽 (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:
primitive を ? ToPrimitive (arg , number ) とする。primitive がTable 12 で対応する値を返す。
Table 12: BigInt Conversions
Argument Type
結果
Undefined
TypeError 例外をthrowする。
Null
TypeError 例外をthrowする。
Boolean
primitive がtrue なら1nを返し、primitive がfalse なら0nを返す。
BigInt
primitive を返す。
Number
TypeError 例外をthrowする。
String
n をStringToBigInt (primitive )とする。n がundefined なら、SyntaxError 例外をthrowする。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:
literal をParseText (string , StringIntegerLiteral )とする。literal がerrorsのList なら、undefined を返す。mv をliteral のMVとする。Assert : mv はinteger である。ℤ (mv )を返す。
7.1.15.1 StringIntegerLiteral文法
StringToBigInt は以下の文法を使用します。
構文
StringIntegerLiteral :::
StrWhiteSpace opt
StrWhiteSpace opt
StrIntegerLiteral
StrWhiteSpace opt
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:
int をℝ (? ToBigInt (arg ))とする。ℤ (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:
int をℝ (? ToBigInt (arg ))とする。ℤ (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 . これはarg をString型 の値へ変換します。 It performs the following steps when called:
arg がStringなら、arg を返す。arg がSymbolなら、TypeError 例外をthrowする。arg がundefined なら、"undefined" を返す。arg がnull なら、"null" を返す。arg がtrue なら、"true" を返す。arg がfalse なら、"false" を返す。arg がNumberなら、Number::toString (arg , 10)を返す。arg がBigIntなら、BigInt::toString (arg , 10)を返す。Assert : arg はObjectである。primitiveValue を ? ToPrimitive (arg , string ) とする。Assert : primitiveValue はObjectでない。? 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 . これはarg をObject型 の値へ変換します。 It performs the following steps when called:
arg がundefined またはnull のいずれかなら、TypeError 例外をthrowする。arg がBooleanなら、[[BooleanData]] internal slotがarg に設定された新しいBoolean objectを返す。Boolean objectsの説明については20.3 を参照。arg がNumberなら、[[NumberData]] internal slotがarg に設定された新しいNumber objectを返す。Number objectsの説明については21.1 を参照。arg がStringなら、[[StringData]] internal slotがarg に設定された新しいString objectを返す。String objectsの説明については22.1 を参照。arg がSymbolなら、[[SymbolData]] internal slotがarg に設定された新しいSymbol objectを返す。Symbol objectsの説明については20.4 を参照。arg がBigIntなら、[[BigIntData]] internal slotがarg に設定された新しいBigInt objectを返す。BigInt objectsの説明については21.2 を参照。Assert : arg はObjectである。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 . これはarg をproperty key として使用できる値へ変換します。 It performs the following steps when called:
key を ? ToPrimitive (arg , string ) とする。key がSymbolなら、key を返す。! 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:
length を ? ToIntegerOrInfinity (arg ) とする。length ≤ 0なら、+0 𝔽 を返す。𝔽 (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:
arg が"-0" なら、-0 𝔽 を返す。n を ! ToNumber (arg ) とする。! ToString (n )がarg なら、n を返す。 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 . これはarg をinteger へ変換し、そのinteger がnon-negativeでありinteger index に対応する場合はそのinteger を返します。そうでなければ、例外をthrowします。 It performs the following steps when called:
int を ? ToIntegerOrInfinity (arg ) とする。int が0から253 - 1までの包含区間内にないなら、RangeError 例外をthrowする。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 . これはarg がToObject を使用してObjectへ変換できない値である場合、エラーをthrowします。 It performs the following steps when called:
arg がundefined またはnull のいずれかなら、TypeError 例外をthrowする。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:
arg がObjectでないなら、false を返す。arg がArray exotic object なら、true を返す。arg がProxy exotic object なら、? ValidateNonRevokedProxy (arg )を実行する。 proxyTarget をarg .[[ProxyTarget]] とする。? IsArray (proxyTarget )を返す。 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:
arg がObjectでないなら、false を返す。arg が[[Call]] internal methodを持つなら、true を返す。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:
arg がObjectでないなら、false を返す。arg が[[Construct]] internal methodを持つなら、true を返す。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:
? 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:
arg がObjectでないなら、false を返す。matcher を ? Get (arg , %Symbol.match% ) とする。matcher がundefined でないなら、ToBoolean (matcher )を返す。arg が[[RegExpMatcher]] internal slotを持つなら、true を返す。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:
length をstring の長さとする。k を0とする。k < length の間、繰り返すcodePoint をCodePointAt (string , k )とする。codePoint .[[IsUnpairedSurrogate]] がtrue なら、false を返す。k をk + codePoint .[[CodeUnitCount]] に設定する。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:
x がundefined かつy がundefined なら、true を返す。x がnull かつy がnull なら、true を返す。x がBooleanかつy がBooleanなら、true を返す。x がNumberかつy がNumberなら、true を返す。x がBigIntかつy がBigIntなら、true を返す。x がSymbolかつy がSymbolなら、true を返す。x がStringかつy がStringなら、true を返す。x がObjectかつy がObjectなら、true を返す。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:
SameType (x , y )がfalse なら、false を返す。x がNumberなら、Number::sameValue (x , y )を返す。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:
SameType (x , y )がfalse なら、false を返す。x がNumberなら、Number::sameValueZero (x , y )を返す。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:
Assert : SameType (x , y )はtrue である。x がundefined またはnull のいずれかなら、true を返す。x がBigIntなら、BigInt::equal (x , y )を返す。x がStringなら、x とy が同じ長さを持ち、同じ位置に同じcode unitsを持つなら、true を返す。false を返す。x がBooleanなら、x がtrue かつy がtrue なら、true を返す。x がfalse かつy がfalse なら、true を返す。false を返す。NOTE : その他すべてのECMAScript言語値 はidentityによって比較されます。x がy なら、true を返す。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 の意味論を提供し、true 、false 、またはundefined (operandsを同じ数値型の比較可能な値へcoerceできなかったことを示す)を返します。leftFirst フラグは、x およびy に対して潜在的に可視な副作用を持つ操作が実行される順序を制御するために使用されます。これは、ECMAScriptが式の左から右への評価を指定するため必要です。leftFirst がtrue なら、x parameterはy parameterに対応する式の左側に現れる式に対応します。leftFirst がfalse なら、その逆であり、操作はx より前にy に対して実行されなければなりません。 It performs the following steps when called:
leftFirst がtrue なら、px を ? ToPrimitive (x , number ) とする。py を ? ToPrimitive (y , number ) とする。そうでなければ、NOTE : 左から右への評価を保持するため、評価の順序を反転する必要があります。py を ? ToPrimitive (y , number ) とする。px を ? ToPrimitive (x , number ) とする。 px がStringかつpy がStringなら、lx をpx の長さとする。ly をpy の長さとする。0 ≤ i < min (lx , ly )である各integer i について、昇順で、以下を行うcx をpx 内のindex i にあるcode unitの数値とする。cy をpy 内のindex i にあるcode unitの数値とする。cx < cy なら、true を返す。cx > cy なら、false を返す。 lx < ly なら、true を返す。false を返す。px がBigIntかつpy がStringなら、ny をStringToBigInt (py )とする。ny がundefined なら、undefined を返す。BigInt::lessThan (px , ny )を返す。px がStringかつpy がBigIntなら、nx をStringToBigInt (px )とする。nx がundefined なら、undefined を返す。BigInt::lessThan (nx , py )を返す。NOTE : px とpy はprimitive valuesであるため、評価順序は重要ではありません。nx を ? ToNumeric (px ) とする。ny を ? ToNumeric (py ) とする。SameType (nx , ny )がtrue なら、nx がNumberなら、Number::lessThan (nx , ny )を返す。Assert : nx はBigIntである。BigInt::lessThan (nx , ny )を返す。Assert : nx はBigIntかつny はNumberである、またはnx はNumberかつny はBigIntである。nx がNaN またはny がNaN なら、undefined を返す。nx が-∞ 𝔽 またはny が+∞ 𝔽 なら、true を返す。nx が+∞ 𝔽 またはny が-∞ 𝔽 なら、false を返す。ℝ (nx ) < ℝ (ny )なら、true を返す。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:
SameType (x , y )がtrue なら、IsStrictlyEqual (x , y )を返す。x がnull かつy がundefined なら、true を返す。x がundefined かつy がnull なら、true を返す。hostがweb browserであるか、または他の方法で[[IsHTMLDDA]] Internal Slot をサポートするなら、x がObjectであり、x が[[IsHTMLDDA]] internal slotを持ち、かつy がundefined またはnull のいずれかなら、true を返す。x がundefined またはnull のいずれかであり、y がObjectであり、かつy が[[IsHTMLDDA]] internal slotを持つなら、true を返す。 x がNumberかつy がStringなら、! IsLooselyEqual (x , ! ToNumber (y ))を返す。x がStringかつy がNumberなら、! IsLooselyEqual (! ToNumber (x ), y )を返す。x がBigIntかつy がStringなら、n をStringToBigInt (y )とする。n がundefined なら、false を返す。! IsLooselyEqual (x , n )を返す。 x がStringかつy がBigIntなら、! IsLooselyEqual (y , x )を返す。x がBooleanなら、! IsLooselyEqual (! ToNumber (x ), y )を返す。y がBooleanなら、! IsLooselyEqual (x , ! ToNumber (y ))を返す。x がString、Number、BigInt、またはSymbolのいずれかであり、y がObjectなら、! IsLooselyEqual (x , ? ToPrimitive (y ))を返す。x がObjectであり、y がString、Number、BigInt、またはSymbolのいずれかなら、! IsLooselyEqual (? ToPrimitive (x ), y )を返す。x がBigIntかつy がNumberである、またはx がNumberかつy がBigIntであるなら、x がfinite でない、またはy がfinite でないなら、false を返す。ℝ (x ) = ℝ (y )なら、true を返す。false を返す。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:
SameType (x , y )がfalse なら、false を返す。x がNumberなら、Number::equal (x , y )を返す。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 objects とexotic objects の両方を含む、アルゴリズムによって作成されるすべてのECMAScriptオブジェクトの源です。すべてのオブジェクトの作成で使用される共通ステップを切り出し、オブジェクト作成を一元化します。 It performs the following steps when called:
internalSlotsList を、internalSlotsList と« [[PrivateElements]] »のlist-concatenation に設定する。obj を、internalSlotsList 内の各名前に対するinternal slotを持つ新しく作成されたオブジェクトとする。NOTE : Object Internal Methods and Internal Slots で記述されるように、各そのようなinternal slotの初期値は、別途指定されない限りundefined です。obj .[[PrivateElements]] を新しい空のList に設定する。obj のessential internal methodsを、10.1 で指定されるデフォルトのordinary object 定義に設定する。Assert : 呼び出し元がobj の[[GetPrototypeOf]] および[[SetPrototypeOf]] essential internal methodsの両方を上書きしないなら、internalSlotsList は[[Prototype]] を含む。Assert : 呼び出し元がobj の[[SetPrototypeOf]] 、[[IsExtensible]] 、および[[PreventExtensions]] essential internal methodsのすべてを上書きしないなら、internalSlotsList は[[Extensible]] を含む。internalSlotsList が[[Extensible]] を含むなら、obj .[[Extensible]] をtrue に設定する。obj を返す。
Note
この仕様内では、exotic objects は、ArrayCreate やBoundFunctionCreate などの抽象操作で、まず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:
? 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:
obj を ? ToObject (value ) とする。? 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:
success を ? obj .[[Set]] (propertyKey , value , obj ) とする。success がfalse かつthrow がtrue なら、TypeError 例外をthrowする。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:
newDesc をPropertyDescriptor { [[Value]] : value , [[Writable]] : true , [[Enumerable]] : true , [[Configurable]] : true }とする。? 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:
success を ? CreateDataProperty (obj , propertyKey , value ) とする。success がfalse なら、TypeError 例外をthrowする。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:
Assert : obj はnon-configurable propertiesを持たないordinaryかつextensibleなオブジェクトである。newDesc をPropertyDescriptor { [[Value]] : value , [[Writable]] : true , [[Enumerable]] : false , [[Configurable]] : true }とする。! DefinePropertyOrThrow (obj , propertyKey , newDesc )を実行する。 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:
success を ? obj .[[DefineOwnProperty]] (propertyKey , propertyDesc ) とする。success がfalse なら、TypeError 例外をthrowする。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:
success を ? obj .[[Delete]] (propertyKey ) とする。success がfalse なら、TypeError 例外をthrowする。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:
func を ? GetV (value , propertyKey ) とする。func がundefined またはnull のいずれかなら、undefined を返す。IsCallable (func )がfalse なら、TypeError 例外をthrowする。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:
? 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:
propertyDesc を ? obj .[[GetOwnProperty]] (propertyKey ) とする。propertyDesc がundefined なら、false を返す。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を呼び出すために使用されます。func はfunction object 、thisValue は[[Call]] のthis 値であるECMAScript言語値 、argList はinternal methodの対応するargumentに渡される値です。argList が存在しない場合、新しい空のList がその値として使用されます。 It performs the following steps when called:
argList が存在しないなら、argList を新しい空のList に設定する。IsCallable (func )がfalse なら、TypeError 例外をthrowする。? 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:
newTarget が存在しないなら、newTarget をctor に設定する。argList が存在しないなら、argList を新しい空のList に設定する。? 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:
status を ? obj .[[PreventExtensions]] () とする。status がfalse なら、false を返す。keys を ? obj .[[OwnPropertyKeys]] () とする。level がsealed なら、keys の各要素key について、以下を行う? DefinePropertyOrThrow (obj , key , PropertyDescriptor { [[Configurable]] : false })を実行する。 そうでなければ、Assert : level はfrozen である。keys の各要素key について、以下を行うcurrentDesc を ? obj .[[GetOwnProperty]] (key ) とする。currentDesc がundefined でないなら、IsAccessorDescriptor (currentDesc )がtrue なら、propertyDesc をPropertyDescriptor { [[Configurable]] : false }とする。そうでなければ、propertyDesc をPropertyDescriptor { [[Configurable]] : false , [[Writable]] : false }とする。 ? DefinePropertyOrThrow (obj , key , propertyDesc )を実行する。 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:
extensible を ? IsExtensible (obj ) とする。extensible がtrue なら、false を返す。NOTE : オブジェクトがextensibleである場合、そのプロパティは一切検査されません。keys を ? obj .[[OwnPropertyKeys]] () とする。keys の各要素key について、以下を行うcurrentDesc を ? obj .[[GetOwnProperty]] (key ) とする。currentDesc がundefined でないなら、currentDesc .[[Configurable]] がtrue なら、false を返す。level がfrozen かつIsDataDescriptor (currentDesc )がtrue なら、currentDesc .[[Writable]] がtrue なら、false を返す。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:
array を ! ArrayCreate (0) とする。n を0とする。elements の各要素element について、以下を行う! CreateDataPropertyOrThrow (array , ! ToString (𝔽 (n )), element )を実行する。 n をn + 1に設定する。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:
ℝ (? 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:
validElementTypes が存在しないなら、validElementTypes をall に設定する。obj がObjectでないなら、TypeError 例外をthrowする。length を ? LengthOfArrayLike (obj ) とする。list を新しい空のList とする。index を0とする。index < length の間、繰り返すindexName を ! ToString (𝔽 (index )) とする。next を ? Get (obj , indexName ) とする。validElementTypes がproperty-key であり、next がproperty key でないなら、TypeError 例外をthrowする。next をlist へappendする。index をindex + 1に設定する。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:
argList が存在しないなら、argList を新しい空のList に設定する。func を ? GetV (value , propertyKey ) とする。? 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 . これは、instance がctor によって提供されるinstance object inheritance pathから継承しているかどうかを決定するデフォルトアルゴリズムを実装します。 It performs the following steps when called:
IsCallable (ctor )がfalse なら、false を返す。ctor が[[BoundTargetFunction]] internal slotを持つなら、boundCtor をctor .[[BoundTargetFunction]] とする。? InstanceofOperator (instance , boundCtor )を返す。 instance がObjectでないなら、false を返す。proto を ? Get (ctor , "prototype" ) とする。proto がObjectでないなら、TypeError 例外をthrowする。繰り返すinstance を ? instance .[[GetPrototypeOf]] () に設定する。instance がnull なら、false を返す。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:
ctor を ? Get (obj , "constructor" ) とする。ctor がundefined なら、defaultCtor を返す。ctor がObjectでないなら、TypeError 例外をthrowする。species を ? Get (ctor , %Symbol.species% ) とする。species がundefined またはnull のいずれかなら、defaultCtor を返す。IsConstructor (species )がtrue なら、species を返す。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:
ownKeys を ? obj .[[OwnPropertyKeys]] () とする。results を新しい空のList とする。ownKeys の各要素key について、以下を行うkey がStringなら、propertyDesc を ? obj .[[GetOwnProperty]] (key ) とする。propertyDesc がundefined でなく、かつpropertyDesc .[[Enumerable]] がtrue なら、kind がkey なら、key をresults へappendする。そうでなければ、value を ? Get (obj , key ) とする。kind がvalue なら、value をresults へappendする。そうでなければ、Assert : kind はkey+value である。entry をCreateArrayFromList (« key , value »)とする。entry をresults へappendする。 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:
func が[[Realm]] internal slotを持つなら、func .[[Realm]] を返す。func がbound function exotic object なら、boundTargetFunc をfunc .[[BoundTargetFunction]] とする。? GetFunctionRealm (boundTargetFunc )を返す。 func がProxy exotic object なら、? ValidateNonRevokedProxy (func )を実行する。 proxyTarget をfunc .[[ProxyTarget]] とする。Assert : proxyTarget はfunction object である。? GetFunctionRealm (proxyTarget )を返す。 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:
source がundefined またはnull のいずれかなら、unused を返す。from を ! ToObject (source ) とする。keys を ? from .[[OwnPropertyKeys]] () とする。keys の各要素nextKey について、以下を行うexcluded をfalse とする。excludedItems の各要素element について、以下を行うSameValue (element , nextKey )がtrue なら、excluded をtrue に設定する。excluded がfalse なら、propertyDesc を ? from .[[GetOwnProperty]] (nextKey ) とする。propertyDesc がundefined でなく、かつpropertyDesc .[[Enumerable]] がtrue なら、propertyValue を ? Get (from , nextKey ) とする。! CreateDataPropertyOrThrow (target , nextKey , propertyValue )を実行する。 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:
obj .[[PrivateElements]] が、entry .[[Key]] がprivateName であるようなPrivateElement entry を含むなら、entry を返す。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:
hostがweb browserなら、? HostEnsureCanAddPrivateElement (obj )を実行する。 entry をPrivateElementFind (obj , privateName )とする。entry がempty でないなら、TypeError 例外をthrowする。PrivateElement { [[Key]] : privateName , [[Kind]] : field , [[Value]] : value }をobj .[[PrivateElements]] へappendする。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:
Assert : method .[[Kind]] はmethod またはaccessor のいずれかである。hostがweb browserなら、? HostEnsureCanAddPrivateElement (obj )を実行する。 entry をPrivateElementFind (obj , method .[[Key]] )とする。entry がempty でないなら、TypeError 例外をthrowする。method をobj .[[PrivateElements]] へappendする。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の実装は、以下の要件に従わなければなりません:
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:
entry をPrivateElementFind (obj , privateName )とする。entry がempty なら、TypeError 例外をthrowする。entry .[[Kind]] がfield またはmethod のいずれかなら、entry .[[Value]] を返す。Assert : entry .[[Kind]] はaccessor である。entry .[[Get]] がundefined なら、TypeError 例外をthrowする。getter をentry .[[Get]] とする。? 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:
entry をPrivateElementFind (obj , privateName )とする。entry がempty なら、TypeError 例外をthrowする。entry .[[Kind]] がmethod なら、TypeError 例外をthrowする。entry .[[Kind]] がfield なら、entry .[[Value]] をvalue に設定する。そうでなければ、Assert : entry .[[Kind]] はaccessor である。entry .[[Set]] がundefined なら、TypeError 例外をthrowする。setter をentry .[[Set]] とする。? Call (setter , obj , « value »)を実行する。 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:
fieldName をfieldRecord .[[Name]] とする。initializer をfieldRecord .[[Initializer]] とする。initializer がempty でないなら、initValue を ? Call (initializer , receiver ) とする。そうでなければ、initValue をundefined とする。 fieldName がPrivate Name なら、? PrivateFieldAdd (receiver , fieldName , initValue )を実行する。 そうでなければ、Assert : fieldName はproperty key である。? CreateDataPropertyOrThrow (receiver , fieldName , initValue )を実行する。 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:
methods をctor .[[PrivateMethods]] とする。methods の各PrivateElement method について、以下を行う? PrivateMethodOrAccessorAdd (obj , method )を実行する。 fields をctor .[[Fields]] とする。fields の各要素fieldRecord について、以下を行う? DefineField (obj , fieldRecord )を実行する。 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:
groups の各Record { [[Key]] , [[Elements]] } group について、以下を行うSameValue (group .[[Key]] , key )がtrue なら、Assert : groups のちょうど1つの要素がこの基準を満たす。value をgroup .[[Elements]] へappendする。unused を返す。group をRecord { [[Key]] : key , [[Elements]] : « value » }とする。group をgroups へappendする。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:
? RequireObjectCoercible (items )を実行する。 IsCallable (callback )がfalse なら、TypeError 例外をthrowする。groups を新しい空のList とする。iteratorRecord を ? GetIterator (items , sync ) とする。k を0とする。繰り返すk ≥ 253 - 1なら、error をThrowCompletion (a newly created TypeError object)とする。? IteratorClose (iteratorRecord , error )を返す。 next を ? IteratorStepValue (iteratorRecord ) とする。next がdone なら、groups を返す。value をnext とする。key をCompletion (Call (callback , undefined , « value , 𝔽 (k ) »))とする。IfAbruptCloseIterator (key , iteratorRecord ).keyCoercion がproperty なら、key をCompletion (ToPropertyKey (key ))に設定する。IfAbruptCloseIterator (key , iteratorRecord ).そうでなければ、Assert : keyCoercion はcollection である。key をCanonicalizeKeyedCollectionKey (key )に設定する。 AddValueToKeyedGroup (groups , key , value )を実行する。k をk + 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:
options がundefined なら、OrdinaryObjectCreate (null )を返す。options がObjectなら、options を返す。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:
thisValue がObjectでないなら、TypeError 例外をthrowする。SameValue (thisValue , home )がtrue なら、NOTE : ここでthrowすることは、strict mode code においてhome オブジェクト上のnon-writable data property へ代入することを模倣します。TypeError 例外をthrowする。propertyDesc を ? thisValue .[[GetOwnProperty]] (propertyKey ) とする。propertyDesc がundefined なら、? CreateDataPropertyOrThrow (thisValue , propertyKey , value )を実行する。 そうでなければ、? Set (thisValue , propertyKey , value , true )を実行する。 unused を返す。
7.4 Iterator Objects上の操作
Common Iteration Interfaces(27.1 を参照)。
7.4.1 Iterator Records
Iterator Record は、iterator またはasync iterator をnextメソッドとともにカプセル化するために使用されるRecord 値です。
Iterator Recordsは、Table 13 に列挙されるフィールドを持ちます。
Table 13: Iterator Record Fields
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:
nextMethod を ? Get (obj , "next" ) とする。iteratorRecord をIterator Record { [[Iterator]] : obj , [[NextMethod]] : nextMethod , [[Done]] : false }とする。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:
iterator を ? Call (method , obj ) とする。iterator がObjectでないなら、TypeError 例外をthrowする。? 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:
kind がasync なら、method を ? GetMethod (obj , %Symbol.asyncIterator% ) とする。method がundefined なら、syncMethod を ? GetMethod (obj , %Symbol.iterator% ) とする。syncMethod がundefined なら、TypeError 例外をthrowする。syncIteratorRecord を ? GetIteratorFromMethod (obj , syncMethod ) とする。CreateAsyncFromSyncIterator (syncIteratorRecord )を返す。そうでなければ、method を ? GetMethod (obj , %Symbol.iterator% ) とする。 method がundefined なら、TypeError 例外をthrowする。? 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:
obj がObjectでないなら、primitiveHandling がreject-primitives なら、TypeError 例外をthrowする。Assert : primitiveHandling はiterate-string-primitives である。obj がStringでないなら、TypeError 例外をthrowする。method を ? GetMethod (obj , %Symbol.iterator% ) とする。method がundefined なら、iterator をobj とする。そうでなければ、iterator を ? Call (method , obj ) とする。 iterator がObjectでないなら、TypeError 例外をthrowする。? 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:
value が存在しないなら、result をCompletion (Call (iteratorRecord .[[NextMethod]] , iteratorRecord .[[Iterator]] ))とする。そうでなければ、result をCompletion (Call (iteratorRecord .[[NextMethod]] , iteratorRecord .[[Iterator]] , « value »))とする。 result がthrow completion なら、iteratorRecord .[[Done]] をtrue に設定する。? result を返す。 result を ! result に設定する。result がObjectでないなら、iteratorRecord .[[Done]] をtrue に設定する。TypeError 例外をthrowする。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:
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:
? 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:
result を ? IteratorNext (iteratorRecord ) とする。done をCompletion (IteratorComplete (result ))とする。done がthrow completion なら、iteratorRecord .[[Done]] をtrue に設定する。? done を返す。 done を ! done に設定する。done がtrue なら、iteratorRecord .[[Done]] をtrue に設定する。done を返す。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:
result を ? IteratorStep (iteratorRecord ) とする。result がdone なら、done を返す。value をCompletion (IteratorValue (result ))とする。value がthrow completion なら、iteratorRecord .[[Done]] をtrue に設定する。? 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:
Assert : iteratorRecord .[[Iterator]] はObjectである。iterator をiteratorRecord .[[Iterator]] とする。innerResult をCompletion (GetMethod (iterator , "return" )))とする。innerResult がnormal completion なら、return をinnerResult .[[Value]] とする。return がundefined なら、? completion を返す。innerResult をCompletion (Call (return , iterator ))に設定する。completion がthrow completion なら、? completion を返す。innerResult がthrow completion なら、? innerResult を返す。innerResult .[[Value]] がObjectでないなら、TypeError 例外をthrowする。? 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:
iterators の各要素iterator について、List の逆順で、以下を行うcompletion をCompletion (IteratorClose (iterator , completion ))に設定する。? completion を返す。
7.4.13 IfAbruptCloseIterator ( value , iteratorRecord )
IfAbruptCloseIteratorは、Iterator Record を使用する一連のアルゴリズムステップの省略表現です。次の形式のアルゴリズムステップ:
IfAbruptCloseIterator (value , iteratorRecord ).
は、次と同じことを意味します:
Assert : value はCompletion Record である。value がabrupt completion なら、? IteratorClose (iteratorRecord , value )を返す。value を ! value に設定する。
7.4.14 IfAbruptCloseIterators ( value , iteratorRecords )
IfAbruptCloseIteratorsは、Iterator Records のリストを使用する一連のアルゴリズムステップの省略表現です。次の形式のアルゴリズムステップ:
IfAbruptCloseIterators (value , iteratorRecords ).
は、次と同じことを意味します:
Assert : value はCompletion Record である。value がabrupt completion なら、? IteratorCloseAll (iteratorRecords , value )を返す。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:
Assert : iteratorRecord .[[Iterator]] はObjectである。iterator をiteratorRecord .[[Iterator]] とする。innerResult をCompletion (GetMethod (iterator , "return" )))とする。innerResult がnormal completion なら、return をinnerResult .[[Value]] とする。return がundefined なら、? completion を返す。innerResult をCompletion (Call (return , iterator ))に設定する。innerResult がnormal completion なら、innerResult をCompletion (Await (innerResult .[[Value]] ))に設定する。completion がthrow completion なら、? completion を返す。innerResult がthrow completion なら、? innerResult を返す。innerResult .[[Value]] がObjectでないなら、TypeError 例外をthrowする。? completion を返す。
7.4.16 IfAbruptCloseAsyncIterator ( value , iteratorRecord )
IfAbruptCloseAsyncIteratorは、Iterator Record を使用する一連のアルゴリズムステップの省略表現です。次の形式のアルゴリズムステップ:
IfAbruptCloseAsyncIterator (value , iteratorRecord ).
は、次と同じことを意味します:
Assert : value はCompletion Record である。value がabrupt completion なら、? AsyncIteratorClose (iteratorRecord , value )を返す。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:
obj をOrdinaryObjectCreate (%Object.prototype% )とする。! CreateDataPropertyOrThrow (obj , "value" , value )を実行する。 ! CreateDataPropertyOrThrow (obj , "done" , done )を実行する。 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:
closure を、parametersを持たず、list をcaptureし、呼び出されたときに以下のステップを実行する新しいAbstract Closure とする:list の各要素value について、以下を行う? GeneratorYield (CreateIteratorResultObject (value , false ))を実行する。 NormalCompletion (undefined )を返す。iterator をCreateIteratorFromClosure (closure , empty , %Iterator.prototype% )とする。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:
values を新しい空のList とする。繰り返すnext を ? IteratorStepValue (iteratorRecord ) とする。next がdone なら、values を返す。next をvalues へ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:
method が存在する場合、thenAssert : value は undefined である。Let resource be ? CreateDisposableResource (undefined , kind , method ). Else,value が null または undefined のいずれかであり、かつ kind が sync-dispose である場合、unused を返す。NOTE : value が null または undefined のいずれかであり、かつ kind が async-dispose である場合、後でリソースが破棄されるときにも Await が実行されることを確保するため、そのリソースが評価されたことを記録する。Let resource be ? CreateDisposableResource (value , kind ). resource を disposableResourceStack に追加する。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:
method が存在しない場合、thenvalue が null または undefined のいずれかである場合、thenSet value to undefined . Set method to undefined . Else,Set method to ? GetDisposeMethod (value , kind ). method が undefined である場合、TypeError 例外を投げる。 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:
value が Object でない場合、TypeError 例外を投げる。kind が sync-dispose である場合、return ? GetMethod (value , %Symbol.dispose% ).Assert : kind は async-dispose である。Let asyncMethod be ? GetMethod (value , %Symbol.asyncDispose% ). asyncMethod が undefined でない場合、asyncMethod を返す。Let syncMethod be ? GetMethod (value , %Symbol.dispose% ). syncMethod が undefined である場合、undefined を返す。Let closure be a new Abstract Closure with no parameters that captures syncMethod and performs the following steps when called:Let obj be the this value. Let promiseCapability be ! NewPromiseCapability (%Promise% ). Let result be Completion (Call (syncMethod , obj )). IfAbruptRejectPromise (result , promiseCapability ).Perform ! Call (promiseCapability .[[Resolve]] , undefined , « undefined »). Return promiseCapability .[[Promise]] . NOTE : この関数はユーザーコードから観測できない。この関数は、同期的な %Symbol.dispose% メソッドから返された Promise が await されないこと、および同期的な例外が rejected Promise に変換されることを確保するために使用される。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:
Let needsAwait be false . Let hasAwaited be false . Let outputCompletion be completion . disposableResourceStack の各要素 resource について、List の逆順で、doLet value be resource .[[ResourceValue]] . Let kind be resource .[[Kind]] . Let method be resource .[[DisposeMethod]] . kind が sync-dispose であり、needsAwait が true であり、かつ hasAwaited が false である場合、thenPerform ! Await (undefined ). Set needsAwait to false . method が undefined でない場合、thenLet result be Completion (Call (method , value )). result が normal completion であり、かつ kind が async-dispose である場合、thenSet result to Completion (Await (result .[[Value]] )). Set hasAwaited to true . result が throw completion である場合、thenoutputCompletion が throw completion である場合、thenSet result to result .[[Value]] . Let suppressed be outputCompletion .[[Value]] . Let error be a newly created SuppressedError object. Perform CreateNonEnumerableDataPropertyOrThrow (error , "error" , result ). Perform CreateNonEnumerableDataPropertyOrThrow (error , "suppressed" , suppressed ). Set outputCompletion to ThrowCompletion (error ). Else,Set outputCompletion to result . Else,Assert : kind は async-dispose である。Set needsAwait to true . NOTE : これは、await using 宣言の初期化値が null または undefined のいずれかであった場合にのみ起こり得ることを示す。 needsAwait が true であり、かつ hasAwaited が false である場合、thenPerform ! Await (undefined ). NOTE : この時点で disposableResourceStack は二度と使用されない。disposableResourceStack の内容は、ガベージコレクションなどにより、実装内で破棄できる。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
唯一の要素がIdentifier のStringValue であるList を返す。
BindingIdentifier : yield
« "yield" »を返す。
BindingIdentifier : await
« "await" »を返す。
LexicalDeclaration :
LetOrConst
BindingList
;
BindingList の BoundNames を返す。
UsingDeclaration :
using
BindingList
;
AwaitUsingDeclaration :
CoverAwaitExpressionAndAwaitUsingDeclarationHead
BindingList
;
BindingList のBoundNames を返す。
BindingList :
BindingList
,
LexicalBinding
names1 をBindingList のBoundNames とする。names2 をLexicalBinding のBoundNames とする。names1 とnames2 のlist-concatenation を返す。
LexicalBinding :
BindingIdentifier
Initializer opt
BindingIdentifier のBoundNames を返す。
LexicalBinding :
BindingPattern
Initializer
BindingPattern のBoundNames を返す。
VariableDeclarationList :
VariableDeclarationList
,
VariableDeclaration
names1 をVariableDeclarationList のBoundNames とする。names2 をVariableDeclaration のBoundNames とする。names1 とnames2 のlist-concatenation を返す。
VariableDeclaration :
BindingIdentifier
Initializer opt
BindingIdentifier のBoundNames を返す。
VariableDeclaration :
BindingPattern
Initializer
BindingPattern のBoundNames を返す。
ObjectBindingPattern :
{
}
新しい空のList を返す。
ObjectBindingPattern :
{
BindingPropertyList
,
BindingRestProperty
}
names1 をBindingPropertyList のBoundNames とする。names2 をBindingRestProperty のBoundNames とする。names1 とnames2 のlist-concatenation を返す。
ArrayBindingPattern :
[
Elision opt
]
新しい空のList を返す。
ArrayBindingPattern :
[
Elision opt
BindingRestElement
]
BindingRestElement のBoundNames を返す。
ArrayBindingPattern :
[
BindingElementList
,
Elision opt
]
BindingElementList のBoundNames を返す。
ArrayBindingPattern :
[
BindingElementList
,
Elision opt
BindingRestElement
]
names1 をBindingElementList のBoundNames とする。names2 をBindingRestElement のBoundNames とする。names1 とnames2 のlist-concatenation を返す。
BindingPropertyList :
BindingPropertyList
,
BindingProperty
names1 をBindingPropertyList のBoundNames とする。names2 をBindingProperty のBoundNames とする。names1 とnames2 のlist-concatenation を返す。
BindingElementList :
BindingElementList
,
BindingElisionElement
names1 をBindingElementList のBoundNames とする。names2 をBindingElisionElement のBoundNames とする。names1 とnames2 のlist-concatenation を返す。
BindingElisionElement :
Elision opt
BindingElement
BindingElement のBoundNames を返す。
BindingProperty :
PropertyName
:
BindingElement
BindingElement のBoundNames を返す。
SingleNameBinding :
BindingIdentifier
Initializer opt
BindingIdentifier のBoundNames を返す。
BindingElement :
BindingPattern
Initializer opt
BindingPattern のBoundNames を返す。
ForDeclaration :
LetOrConst
ForBinding
ForBinding のBoundNames を返す。
FunctionDeclaration :
function
BindingIdentifier
(
FormalParameters
)
{
FunctionBody
}
BindingIdentifier のBoundNames を返す。
FunctionDeclaration :
function
(
FormalParameters
)
{
FunctionBody
}
« "*default*" »を返す。
FormalParameters : [empty]
新しい空のList を返す。
FormalParameters :
FormalParameterList
,
FunctionRestParameter
names1 をFormalParameterList のBoundNames とする。names2 をFunctionRestParameter のBoundNames とする。names1 とnames2 のlist-concatenation を返す。
FormalParameterList :
FormalParameterList
,
FormalParameter
names1 をFormalParameterList のBoundNames とする。names2 をFormalParameter のBoundNames とする。names1 とnames2 のlist-concatenation を返す。
ArrowParameters : CoverParenthesizedExpressionAndArrowParameterList
formals を、CoverParenthesizedExpressionAndArrowParameterList によってcoverされるArrowFormalParameters とする。formals のBoundNames を返す。
GeneratorDeclaration :
function
*
BindingIdentifier
(
FormalParameters
)
{
GeneratorBody
}
BindingIdentifier のBoundNames を返す。
GeneratorDeclaration :
function
*
(
FormalParameters
)
{
GeneratorBody
}
« "*default*" »を返す。
AsyncGeneratorDeclaration :
async
function
*
BindingIdentifier
(
FormalParameters
)
{
AsyncGeneratorBody
}
BindingIdentifier のBoundNames を返す。
AsyncGeneratorDeclaration :
async
function
*
(
FormalParameters
)
{
AsyncGeneratorBody
}
« "*default*" »を返す。
ClassDeclaration :
class
BindingIdentifier
ClassTail
BindingIdentifier のBoundNames を返す。
ClassDeclaration :
class
ClassTail
« "*default*" »を返す。
AsyncFunctionDeclaration :
async
function
BindingIdentifier
(
FormalParameters
)
{
AsyncFunctionBody
}
BindingIdentifier のBoundNames を返す。
AsyncFunctionDeclaration :
async
function
(
FormalParameters
)
{
AsyncFunctionBody
}
« "*default*" »を返す。
CoverCallExpressionAndAsyncArrowHead :
MemberExpression
Arguments
head を、CoverCallExpressionAndAsyncArrowHead によってcoverされるAsyncArrowHead とする。head のBoundNames を返す。
ImportDeclaration :
import
ImportClause
FromClause
WithClause opt
;
ImportClause のBoundNames を返す。
ImportDeclaration :
import
ModuleSpecifier
WithClause opt
;
新しい空のList を返す。
ImportClause :
ImportedDefaultBinding
,
NameSpaceImport
names1 をImportedDefaultBinding のBoundNames とする。names2 をNameSpaceImport のBoundNames とする。names1 とnames2 のlist-concatenation を返す。
ImportClause :
ImportedDefaultBinding
,
NamedImports
names1 をImportedDefaultBinding のBoundNames とする。names2 をNamedImports のBoundNames とする。names1 とnames2 のlist-concatenation を返す。
NamedImports :
{
}
新しい空のList を返す。
ImportsList :
ImportsList
,
ImportSpecifier
names1 をImportsList のBoundNames とする。names2 をImportSpecifier のBoundNames とする。names1 とnames2 のlist-concatenation を返す。
ImportSpecifier :
ModuleExportName
as
ImportedBinding
ImportedBinding のBoundNames を返す。
ExportDeclaration :
export
ExportFromClause
FromClause
WithClause opt
;
export
NamedExports
;
新しい空のList を返す。
ExportDeclaration :
export
VariableStatement
VariableStatement のBoundNames を返す。
ExportDeclaration :
export
Declaration
Declaration のBoundNames を返す。
ExportDeclaration :
export
default
HoistableDeclaration
declNames をHoistableDeclaration のBoundNames とする。declNames が要素"*default*" を含まないなら、"*default*" をdeclNames へappendする。declNames を返す。
ExportDeclaration :
export
default
ClassDeclaration
declNames をClassDeclaration のBoundNames とする。declNames が要素"*default*" を含まないなら、"*default*" をdeclNames へappendする。declNames を返す。
ExportDeclaration :
export
default
AssignmentExpression
;
« "*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
FunctionDeclaration を返す。
HoistableDeclaration : GeneratorDeclaration
GeneratorDeclaration を返す。
HoistableDeclaration : AsyncFunctionDeclaration
AsyncFunctionDeclaration を返す。
HoistableDeclaration : AsyncGeneratorDeclaration
AsyncGeneratorDeclaration を返す。
Declaration : ClassDeclaration
ClassDeclaration を返す。
Declaration : LexicalDeclaration
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
;
LetOrConst のIsConstantDeclaration を返す。
LetOrConst : let
false を返す。
LetOrConst : const
true を返す。
UsingDeclaration :
using
BindingList
;
AwaitUsingDeclaration :
CoverAwaitExpressionAndAwaitUsingDeclarationHead
BindingList
;
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
}
false を返す。
ClassDeclaration :
class
BindingIdentifier
ClassTail
class
ClassTail
false を返す。
ExportDeclaration :
export
ExportFromClause
FromClause
;
export
NamedExports
;
export
default
AssignmentExpression
;
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
;
false を返す。
UsingDeclaration :
using
BindingList
;
AwaitUsingDeclaration :
CoverAwaitExpressionAndAwaitUsingDeclarationHead
BindingList
;
true を返す。
ForDeclaration :
LetOrConst
ForBinding
false を返す。
ForDeclaration :
using
ForBinding
await
using
ForBinding
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
}
false を返す。
ClassDeclaration :
class
BindingIdentifier
ClassTail
class
ClassTail
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
;
false を返す。
UsingDeclaration :
using
BindingList
;
false を返す。
AwaitUsingDeclaration :
CoverAwaitExpressionAndAwaitUsingDeclarationHead
BindingList
;
true を返す。
ForDeclaration :
LetOrConst
ForBinding
false を返す。
ForDeclaration :
using
ForBinding
false を返す。
ForDeclaration :
await
using
ForBinding
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
}
false を返す。
ClassDeclaration :
class
BindingIdentifier
ClassTail
class
ClassTail
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 :
{
}
新しい空のList を返す。
StatementList :
StatementList
StatementListItem
names1 をStatementList のLexicallyDeclaredNames とする。names2 をStatementListItem のLexicallyDeclaredNames とする。names1 とnames2 のlist-concatenation を返す。
StatementListItem : Statement
Statement が
Statement : LabelledStatement
であるなら、LabelledStatement のLexicallyDeclaredNames を返す。新しい空のList を返す。
StatementListItem : Declaration
Declaration のBoundNames を返す。
CaseBlock :
{
}
新しい空のList を返す。
CaseBlock :
{
CaseClauses opt
DefaultClause
CaseClauses opt
}
最初のCaseClauses が存在するなら、names1 を最初のCaseClauses のLexicallyDeclaredNames とする。 そうでなければ、names1 を新しい空のList とする。 names2 をDefaultClause のLexicallyDeclaredNames とする。2番目のCaseClauses が存在するなら、names3 を2番目のCaseClauses のLexicallyDeclaredNames とする。 そうでなければ、names3 を新しい空のList とする。 names1 、names2 、およびnames3 のlist-concatenation を返す。
CaseClauses :
CaseClauses
CaseClause
names1 をCaseClauses のLexicallyDeclaredNames とする。names2 をCaseClause のLexicallyDeclaredNames とする。names1 とnames2 のlist-concatenation を返す。
CaseClause :
case
Expression
:
StatementList opt
StatementList が存在するなら、StatementList のLexicallyDeclaredNames を返す。新しい空のList を返す。
DefaultClause :
default
:
StatementList opt
StatementList が存在するなら、StatementList のLexicallyDeclaredNames を返す。新しい空のList を返す。
LabelledStatement :
LabelIdentifier
:
LabelledItem
LabelledItem のLexicallyDeclaredNames を返す。
LabelledItem : Statement
新しい空のList を返す。
LabelledItem : FunctionDeclaration
FunctionDeclaration のBoundNames を返す。
FunctionStatementList : [empty]
新しい空のList を返す。
FunctionStatementList : StatementList
StatementList のTopLevelLexicallyDeclaredNames を返す。
ClassStaticBlockStatementList : [empty]
新しい空のList を返す。
ClassStaticBlockStatementList : StatementList
StatementList のTopLevelLexicallyDeclaredNames を返す。
ConciseBody : ExpressionBody
新しい空のList を返す。
AsyncConciseBody : ExpressionBody
新しい空のList を返す。
Script : [empty]
新しい空のList を返す。
ScriptBody : StatementList
StatementList のTopLevelLexicallyDeclaredNames を返す。
Note 1
Script のtop levelでは、function declarationsはlexical declarationsのようにではなく、var declarationsのように扱われます。
Note 2
Module のLexicallyDeclaredNamesには、そのすべてのimported bindingsの名前が含まれます。
ModuleItemList :
ModuleItemList
ModuleItem
names1 をModuleItemList のLexicallyDeclaredNames とする。names2 をModuleItem のLexicallyDeclaredNames とする。names1 とnames2 のlist-concatenation を返す。
ModuleItem : ImportDeclaration
ImportDeclaration のBoundNames を返す。
ModuleItem : ExportDeclaration
ExportDeclaration がexport VariableStatement であるなら、新しい空のList を返す。ExportDeclaration のBoundNames を返す。
ModuleItem : StatementListItem
StatementListItem のLexicallyDeclaredNames を返す。
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
decls1 をStatementList のLexicallyScopedDeclarations とする。decls2 をStatementListItem のLexicallyScopedDeclarations とする。decls1 とdecls2 のlist-concatenation を返す。
StatementListItem : Statement
Statement が
Statement : LabelledStatement
であるなら、LabelledStatement のLexicallyScopedDeclarations を返す。新しい空のList を返す。
StatementListItem : Declaration
唯一の要素がDeclaration のDeclarationPart であるList を返す。
CaseBlock :
{
}
新しい空のList を返す。
CaseBlock :
{
CaseClauses opt
DefaultClause
CaseClauses opt
}
最初のCaseClauses が存在するなら、decls1 を最初のCaseClauses のLexicallyScopedDeclarations とする。 そうでなければ、decls1 を新しい空のList とする。 decls2 をDefaultClause のLexicallyScopedDeclarations とする。2番目のCaseClauses が存在するなら、decls3 を2番目のCaseClauses のLexicallyScopedDeclarations とする。 そうでなければ、decls3 を新しい空のList とする。 decls1 、decls2 、およびdecls3 のlist-concatenation を返す。
CaseClauses :
CaseClauses
CaseClause
decls1 をCaseClauses のLexicallyScopedDeclarations とする。decls2 をCaseClause のLexicallyScopedDeclarations とする。decls1 とdecls2 のlist-concatenation を返す。
CaseClause :
case
Expression
:
StatementList opt
StatementList が存在するなら、StatementList のLexicallyScopedDeclarations を返す。新しい空のList を返す。
DefaultClause :
default
:
StatementList opt
StatementList が存在するなら、StatementList のLexicallyScopedDeclarations を返す。新しい空のList を返す。
LabelledStatement :
LabelIdentifier
:
LabelledItem
LabelledItem のLexicallyScopedDeclarations を返す。
LabelledItem : Statement
新しい空のList を返す。
LabelledItem : FunctionDeclaration
« FunctionDeclaration »を返す。
FunctionStatementList : [empty]
新しい空のList を返す。
FunctionStatementList : StatementList
StatementList のTopLevelLexicallyScopedDeclarations を返す。
ClassStaticBlockStatementList : [empty]
新しい空のList を返す。
ClassStaticBlockStatementList : StatementList
StatementList のTopLevelLexicallyScopedDeclarations を返す。
ConciseBody : ExpressionBody
新しい空のList を返す。
AsyncConciseBody : ExpressionBody
新しい空のList を返す。
Script : [empty]
新しい空のList を返す。
ScriptBody : StatementList
StatementList のTopLevelLexicallyScopedDeclarations を返す。
Module : [empty]
新しい空のList を返す。
ModuleItemList :
ModuleItemList
ModuleItem
decls1 をModuleItemList のLexicallyScopedDeclarations とする。decls2 をModuleItem のLexicallyScopedDeclarations とする。decls1 とdecls2 のlist-concatenation を返す。
ModuleItem : ImportDeclaration
新しい空のList を返す。
ExportDeclaration :
export
ExportFromClause
FromClause
WithClause opt
;
export
NamedExports
;
export
VariableStatement
新しい空のList を返す。
ExportDeclaration :
export
Declaration
唯一の要素がDeclaration のDeclarationPart であるList を返す。
ExportDeclaration :
export
default
HoistableDeclaration
唯一の要素がHoistableDeclaration のDeclarationPart であるList を返す。
ExportDeclaration :
export
default
ClassDeclaration
唯一の要素がClassDeclaration であるList を返す。
ExportDeclaration :
export
default
AssignmentExpression
;
唯一の要素がこの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
新しい空のList を返す。
Block :
{
}
新しい空のList を返す。
StatementList :
StatementList
StatementListItem
names1 をStatementList のVarDeclaredNames とする。names2 をStatementListItem のVarDeclaredNames とする。names1 とnames2 のlist-concatenation を返す。
StatementListItem : Declaration
新しい空のList を返す。
VariableStatement :
var
VariableDeclarationList
;
VariableDeclarationList のBoundNames を返す。
IfStatement :
if
(
Expression
)
Statement
else
Statement
names1 を最初のStatement のVarDeclaredNames とする。names2 を2番目のStatement のVarDeclaredNames とする。names1 とnames2 のlist-concatenation を返す。
IfStatement :
if
(
Expression
)
Statement
Statement のVarDeclaredNames を返す。
DoWhileStatement :
do
Statement
while
(
Expression
)
;
Statement のVarDeclaredNames を返す。
WhileStatement :
while
(
Expression
)
Statement
Statement のVarDeclaredNames を返す。
ForStatement :
for
(
Expression opt
;
Expression opt
;
Expression opt
)
Statement
Statement のVarDeclaredNames を返す。
ForStatement :
for
(
var
VariableDeclarationList
;
Expression opt
;
Expression opt
)
Statement
names1 をVariableDeclarationList のBoundNames とする。names2 をStatement のVarDeclaredNames とする。names1 とnames2 のlist-concatenation を返す。
ForStatement :
for
(
LexicalDeclaration
Expression opt
;
Expression opt
)
Statement
Statement のVarDeclaredNames を返す。
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
Statement のVarDeclaredNames を返す。
ForInOfStatement :
for
(
var
ForBinding
in
Expression
)
Statement
for
(
var
ForBinding
of
AssignmentExpression
)
Statement
for
await
(
var
ForBinding
of
AssignmentExpression
)
Statement
names1 をForBinding のBoundNames とする。names2 をStatement のVarDeclaredNames とする。names1 とnames2 のlist-concatenation を返す。
Note
この節はAnnex B.3.5 によって拡張されます。
WithStatement :
with
(
Expression
)
Statement
Statement のVarDeclaredNames を返す。
SwitchStatement :
switch
(
Expression
)
CaseBlock
CaseBlock のVarDeclaredNames を返す。
CaseBlock :
{
}
新しい空のList を返す。
CaseBlock :
{
CaseClauses opt
DefaultClause
CaseClauses opt
}
最初のCaseClauses が存在するなら、names1 を最初のCaseClauses のVarDeclaredNames とする。 そうでなければ、names1 を新しい空のList とする。 names2 をDefaultClause のVarDeclaredNames とする。2番目のCaseClauses が存在するなら、names3 を2番目のCaseClauses のVarDeclaredNames とする。 そうでなければ、names3 を新しい空のList とする。 names1 、names2 、およびnames3 のlist-concatenation を返す。
CaseClauses :
CaseClauses
CaseClause
names1 をCaseClauses のVarDeclaredNames とする。names2 をCaseClause のVarDeclaredNames とする。names1 とnames2 のlist-concatenation を返す。
CaseClause :
case
Expression
:
StatementList opt
StatementList が存在するなら、StatementList のVarDeclaredNames を返す。新しい空のList を返す。
DefaultClause :
default
:
StatementList opt
StatementList が存在するなら、StatementList のVarDeclaredNames を返す。新しい空のList を返す。
LabelledStatement :
LabelIdentifier
:
LabelledItem
LabelledItem のVarDeclaredNames を返す。
LabelledItem : FunctionDeclaration
新しい空のList を返す。
TryStatement :
try
Block
Catch
names1 をBlock のVarDeclaredNames とする。names2 をCatch のVarDeclaredNames とする。names1 とnames2 のlist-concatenation を返す。
TryStatement :
try
Block
Finally
names1 をBlock のVarDeclaredNames とする。names2 をFinally のVarDeclaredNames とする。names1 とnames2 のlist-concatenation を返す。
TryStatement :
try
Block
Catch
Finally
names1 をBlock のVarDeclaredNames とする。names2 をCatch のVarDeclaredNames とする。names3 をFinally のVarDeclaredNames とする。names1 、names2 、およびnames3 のlist-concatenation を返す。
Catch :
catch
(
CatchParameter
)
Block
Block のVarDeclaredNames を返す。
FunctionStatementList : [empty]
新しい空のList を返す。
FunctionStatementList : StatementList
StatementList のTopLevelVarDeclaredNames を返す。
ClassStaticBlockStatementList : [empty]
新しい空のList を返す。
ClassStaticBlockStatementList : StatementList
StatementList のTopLevelVarDeclaredNames を返す。
ConciseBody : ExpressionBody
新しい空のList を返す。
AsyncConciseBody : ExpressionBody
新しい空のList を返す。
Script : [empty]
新しい空のList を返す。
ScriptBody : StatementList
StatementList のTopLevelVarDeclaredNames を返す。
ModuleItemList :
ModuleItemList
ModuleItem
names1 をModuleItemList のVarDeclaredNames とする。names2 をModuleItem のVarDeclaredNames とする。names1 とnames2 のlist-concatenation を返す。
ModuleItem : ImportDeclaration
新しい空のList を返す。
ModuleItem : ExportDeclaration
ExportDeclaration がexport VariableStatement であるなら、ExportDeclaration のBoundNames を返す。新しい空の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
新しい空のList を返す。
Block :
{
}
新しい空のList を返す。
StatementList :
StatementList
StatementListItem
decls1 をStatementList のVarScopedDeclarations とする。decls2 をStatementListItem のVarScopedDeclarations とする。decls1 とdecls2 のlist-concatenation を返す。
StatementListItem : Declaration
新しい空のList を返す。
VariableDeclarationList : VariableDeclaration
« VariableDeclaration »を返す。
VariableDeclarationList :
VariableDeclarationList
,
VariableDeclaration
decls1 をVariableDeclarationList のVarScopedDeclarations とする。decls1 と« VariableDeclaration »のlist-concatenation を返す。
IfStatement :
if
(
Expression
)
Statement
else
Statement
decls1 を最初のStatement のVarScopedDeclarations とする。decls2 を2番目のStatement のVarScopedDeclarations とする。decls1 とdecls2 のlist-concatenation を返す。
IfStatement :
if
(
Expression
)
Statement
Statement のVarScopedDeclarations を返す。
DoWhileStatement :
do
Statement
while
(
Expression
)
;
Statement のVarScopedDeclarations を返す。
WhileStatement :
while
(
Expression
)
Statement
Statement のVarScopedDeclarations を返す。
ForStatement :
for
(
Expression opt
;
Expression opt
;
Expression opt
)
Statement
Statement のVarScopedDeclarations を返す。
ForStatement :
for
(
var
VariableDeclarationList
;
Expression opt
;
Expression opt
)
Statement
decls1 をVariableDeclarationList のVarScopedDeclarations とする。decls2 をStatement のVarScopedDeclarations とする。decls1 とdecls2 のlist-concatenation を返す。
ForStatement :
for
(
LexicalDeclaration
Expression opt
;
Expression opt
)
Statement
Statement のVarScopedDeclarations を返す。
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
Statement のVarScopedDeclarations を返す。
ForInOfStatement :
for
(
var
ForBinding
in
Expression
)
Statement
for
(
var
ForBinding
of
AssignmentExpression
)
Statement
for
await
(
var
ForBinding
of
AssignmentExpression
)
Statement
decls1 を« ForBinding »とする。decls2 をStatement のVarScopedDeclarations とする。decls1 とdecls2 のlist-concatenation を返す。
Note
この節はAnnex B.3.5 によって拡張されます。
WithStatement :
with
(
Expression
)
Statement
Statement のVarScopedDeclarations を返す。
SwitchStatement :
switch
(
Expression
)
CaseBlock
CaseBlock のVarScopedDeclarations を返す。
CaseBlock :
{
}
新しい空のList を返す。
CaseBlock :
{
CaseClauses opt
DefaultClause
CaseClauses opt
}
最初のCaseClauses が存在するなら、decls1 を最初のCaseClauses のVarScopedDeclarations とする。 そうでなければ、decls1 を新しい空のList とする。 decls2 をDefaultClause のVarScopedDeclarations とする。2番目のCaseClauses が存在するなら、decls3 を2番目のCaseClauses のVarScopedDeclarations とする。 そうでなければ、decls3 を新しい空のList とする。 decls1 、decls2 、およびdecls3 のlist-concatenation を返す。
CaseClauses :
CaseClauses
CaseClause
decls1 をCaseClauses のVarScopedDeclarations とする。decls2 をCaseClause のVarScopedDeclarations とする。decls1 とdecls2 のlist-concatenation を返す。
CaseClause :
case
Expression
:
StatementList opt
StatementList が存在するなら、StatementList のVarScopedDeclarations を返す。新しい空のList を返す。
DefaultClause :
default
:
StatementList opt
StatementList が存在するなら、StatementList のVarScopedDeclarations を返す。新しい空のList を返す。
LabelledStatement :
LabelIdentifier
:
LabelledItem
LabelledItem のVarScopedDeclarations を返す。
LabelledItem : FunctionDeclaration
新しい空のList を返す。
TryStatement :
try
Block
Catch
decls1 をBlock のVarScopedDeclarations とする。decls2 をCatch のVarScopedDeclarations とする。decls1 とdecls2 のlist-concatenation を返す。
TryStatement :
try
Block
Finally
decls1 をBlock のVarScopedDeclarations とする。decls2 をFinally のVarScopedDeclarations とする。decls1 とdecls2 のlist-concatenation を返す。
TryStatement :
try
Block
Catch
Finally
decls1 をBlock のVarScopedDeclarations とする。decls2 をCatch のVarScopedDeclarations とする。decls3 をFinally のVarScopedDeclarations とする。decls1 、decls2 、およびdecls3 のlist-concatenation を返す。
Catch :
catch
(
CatchParameter
)
Block
Block のVarScopedDeclarations を返す。
FunctionStatementList : [empty]
新しい空のList を返す。
FunctionStatementList : StatementList
StatementList のTopLevelVarScopedDeclarations を返す。
ClassStaticBlockStatementList : [empty]
新しい空のList を返す。
ClassStaticBlockStatementList : StatementList
StatementList のTopLevelVarScopedDeclarations を返す。
ConciseBody : ExpressionBody
新しい空のList を返す。
AsyncConciseBody : ExpressionBody
新しい空のList を返す。
Script : [empty]
新しい空のList を返す。
ScriptBody : StatementList
StatementList のTopLevelVarScopedDeclarations を返す。
Module : [empty]
新しい空のList を返す。
ModuleItemList :
ModuleItemList
ModuleItem
decls1 をModuleItemList のVarScopedDeclarations とする。decls2 をModuleItem のVarScopedDeclarations とする。decls1 とdecls2 のlist-concatenation を返す。
ModuleItem : ImportDeclaration
新しい空のList を返す。
ExportDeclaration :
export
ExportFromClause
FromClause
WithClause opt
;
export
NamedExports
;
export
VariableStatement
新しい空のList を返す。
ExportDeclaration :
export
Declaration
唯一の要素がDeclaration のDeclarationPart であるList を返す。
ExportDeclaration :
export
default
HoistableDeclaration
唯一の要素がHoistableDeclaration のDeclarationPart であるList を返す。
ExportDeclaration :
export
default
ClassDeclaration
唯一の要素がClassDeclaration であるList を返す。
ExportDeclaration :
export
default
AssignmentExpression
;
唯一の要素がこの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
names1 をStatementList のTopLevelLexicallyDeclaredNames とする。names2 をStatementListItem のTopLevelLexicallyDeclaredNames とする。names1 とnames2 のlist-concatenation を返す。
StatementListItem : Statement
新しい空のList を返す。
StatementListItem : Declaration
Declaration が
Declaration : HoistableDeclaration
であるなら、新しい空のList を返す。 Declaration のBoundNames を返す。
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
decls1 をStatementList のTopLevelLexicallyScopedDeclarations とする。decls2 をStatementListItem のTopLevelLexicallyScopedDeclarations とする。decls1 とdecls2 のlist-concatenation を返す。
StatementListItem : Statement
新しい空のList を返す。
StatementListItem : Declaration
Declaration が
Declaration : HoistableDeclaration
であるなら、新しい空のList を返す。 « 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
names1 をStatementList のTopLevelVarDeclaredNames とする。names2 をStatementListItem のTopLevelVarDeclaredNames とする。names1 とnames2 のlist-concatenation を返す。
StatementListItem : Declaration
Declaration が
Declaration : HoistableDeclaration
であるなら、HoistableDeclaration のBoundNames を返す。新しい空のList を返す。
StatementListItem : Statement
Statement が
Statement : LabelledStatement
であるなら、Statement のTopLevelVarDeclaredNames を返す。Statement のVarDeclaredNames を返す。
Note
functionまたはscriptのtop levelでは、inner function declarationsはvar declarationsのように扱われます。
LabelledStatement :
LabelIdentifier
:
LabelledItem
LabelledItem のTopLevelVarDeclaredNames を返す。
LabelledItem : Statement
Statement が
Statement : LabelledStatement
であるなら、Statement のTopLevelVarDeclaredNames を返す。Statement のVarDeclaredNames を返す。
LabelledItem : FunctionDeclaration
FunctionDeclaration のBoundNames を返す。
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
decls1 をStatementList のTopLevelVarScopedDeclarations とする。decls2 をStatementListItem のTopLevelVarScopedDeclarations とする。decls1 とdecls2 のlist-concatenation を返す。
StatementListItem : Statement
Statement が
Statement : LabelledStatement
であるなら、Statement のTopLevelVarScopedDeclarations を返す。Statement のVarScopedDeclarations を返す。
StatementListItem : Declaration
Declaration が
Declaration : HoistableDeclaration
であるなら、decl をHoistableDeclaration のDeclarationPart とする。« decl »を返す。 新しい空のList を返す。
LabelledStatement :
LabelIdentifier
:
LabelledItem
LabelledItem のTopLevelVarScopedDeclarations を返す。
LabelledItem : Statement
Statement が
Statement : LabelledStatement
であるなら、Statement のTopLevelVarScopedDeclarations を返す。Statement のVarScopedDeclarations を返す。
LabelledItem : FunctionDeclaration
« 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
false を返す。
StatementList :
StatementList
StatementListItem
hasDuplicates を、引数labelSet を伴うStatementList のContainsDuplicateLabels とする。hasDuplicates がtrue なら、true を返す。引数labelSet を伴うStatementListItem のContainsDuplicateLabels を返す。
IfStatement :
if
(
Expression
)
Statement
else
Statement
hasDuplicate を、引数labelSet を伴う最初のStatement のContainsDuplicateLabels とする。hasDuplicate がtrue なら、true を返す。引数labelSet を伴う2番目のStatement のContainsDuplicateLabels を返す。
IfStatement :
if
(
Expression
)
Statement
引数labelSet を伴うStatement のContainsDuplicateLabels を返す。
DoWhileStatement :
do
Statement
while
(
Expression
)
;
引数labelSet を伴うStatement のContainsDuplicateLabels を返す。
WhileStatement :
while
(
Expression
)
Statement
引数labelSet を伴うStatement のContainsDuplicateLabels を返す。
ForStatement :
for
(
Expression opt
;
Expression opt
;
Expression opt
)
Statement
for
(
var
VariableDeclarationList
;
Expression opt
;
Expression opt
)
Statement
for
(
LexicalDeclaration
Expression opt
;
Expression opt
)
Statement
引数labelSet を伴うStatement のContainsDuplicateLabels を返す。
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
引数labelSet を伴うStatement のContainsDuplicateLabels を返す。
Note
この節はAnnex B.3.5 によって拡張されます。
WithStatement :
with
(
Expression
)
Statement
引数labelSet を伴うStatement のContainsDuplicateLabels を返す。
SwitchStatement :
switch
(
Expression
)
CaseBlock
引数labelSet を伴うCaseBlock のContainsDuplicateLabels を返す。
CaseBlock :
{
}
false を返す。
CaseBlock :
{
CaseClauses opt
DefaultClause
CaseClauses opt
}
最初のCaseClauses が存在するなら、引数labelSet を伴う最初のCaseClauses のContainsDuplicateLabels がtrue なら、true を返す。 引数labelSet を伴うDefaultClause のContainsDuplicateLabels がtrue なら、true を返す。 2番目のCaseClauses が存在しないなら、false を返す。 引数labelSet を伴う2番目のCaseClauses のContainsDuplicateLabels を返す。
CaseClauses :
CaseClauses
CaseClause
hasDuplicates を、引数labelSet を伴うCaseClauses のContainsDuplicateLabels とする。hasDuplicates がtrue なら、true を返す。引数labelSet を伴うCaseClause のContainsDuplicateLabels を返す。
CaseClause :
case
Expression
:
StatementList opt
StatementList が存在するなら、引数labelSet を伴うStatementList のContainsDuplicateLabels を返す。false を返す。
DefaultClause :
default
:
StatementList opt
StatementList が存在するなら、引数labelSet を伴うStatementList のContainsDuplicateLabels を返す。false を返す。
LabelledStatement :
LabelIdentifier
:
LabelledItem
label をLabelIdentifier のStringValue とする。labelSet がlabel を含むなら、true を返す。newLabelSet をlabelSet と« label »のlist-concatenation とする。引数newLabelSet を伴うLabelledItem のContainsDuplicateLabels を返す。
LabelledItem : FunctionDeclaration
false を返す。
TryStatement :
try
Block
Catch
hasDuplicates を、引数labelSet を伴うBlock のContainsDuplicateLabels とする。hasDuplicates がtrue なら、true を返す。引数labelSet を伴うCatch のContainsDuplicateLabels を返す。
TryStatement :
try
Block
Finally
hasDuplicates を、引数labelSet を伴うBlock のContainsDuplicateLabels とする。hasDuplicates がtrue なら、true を返す。引数labelSet を伴うFinally のContainsDuplicateLabels を返す。
TryStatement :
try
Block
Catch
Finally
引数labelSet を伴うBlock のContainsDuplicateLabels がtrue なら、true を返す。 引数labelSet を伴うCatch のContainsDuplicateLabels がtrue なら、true を返す。 引数labelSet を伴うFinally のContainsDuplicateLabels を返す。
Catch :
catch
(
CatchParameter
)
Block
引数labelSet を伴うBlock のContainsDuplicateLabels を返す。
FunctionStatementList : [empty]
false を返す。
ClassStaticBlockStatementList : [empty]
false を返す。
ModuleItemList :
ModuleItemList
ModuleItem
hasDuplicates を、引数labelSet を伴うModuleItemList のContainsDuplicateLabels とする。hasDuplicates がtrue なら、true を返す。引数labelSet を伴うModuleItem のContainsDuplicateLabels を返す。
ModuleItem :
ImportDeclaration
ExportDeclaration
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
false を返す。
StatementList :
StatementList
StatementListItem
hasUndefinedLabels を、引数labelSet を伴うStatementList のContainsUndefinedBreakTarget とする。hasUndefinedLabels がtrue なら、true を返す。引数labelSet を伴うStatementListItem のContainsUndefinedBreakTarget を返す。
IfStatement :
if
(
Expression
)
Statement
else
Statement
hasUndefinedLabels を、引数labelSet を伴う最初のStatement のContainsUndefinedBreakTarget とする。hasUndefinedLabels がtrue なら、true を返す。引数labelSet を伴う2番目のStatement のContainsUndefinedBreakTarget を返す。
IfStatement :
if
(
Expression
)
Statement
引数labelSet を伴うStatement のContainsUndefinedBreakTarget を返す。
DoWhileStatement :
do
Statement
while
(
Expression
)
;
引数labelSet を伴うStatement のContainsUndefinedBreakTarget を返す。
WhileStatement :
while
(
Expression
)
Statement
引数labelSet を伴うStatement のContainsUndefinedBreakTarget を返す。
ForStatement :
for
(
Expression opt
;
Expression opt
;
Expression opt
)
Statement
for
(
var
VariableDeclarationList
;
Expression opt
;
Expression opt
)
Statement
for
(
LexicalDeclaration
Expression opt
;
Expression opt
)
Statement
引数labelSet を伴うStatement のContainsUndefinedBreakTarget を返す。
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
引数labelSet を伴うStatement のContainsUndefinedBreakTarget を返す。
Note
この節はAnnex B.3.5 によって拡張されます。
BreakStatement :
break
;
false を返す。
BreakStatement :
break
LabelIdentifier
;
labelSet がLabelIdentifier のStringValue を含むなら、false を返す。true を返す。
WithStatement :
with
(
Expression
)
Statement
引数labelSet を伴うStatement のContainsUndefinedBreakTarget を返す。
SwitchStatement :
switch
(
Expression
)
CaseBlock
引数labelSet を伴うCaseBlock のContainsUndefinedBreakTarget を返す。
CaseBlock :
{
}
false を返す。
CaseBlock :
{
CaseClauses opt
DefaultClause
CaseClauses opt
}
最初のCaseClauses が存在するなら、引数labelSet を伴う最初のCaseClauses のContainsUndefinedBreakTarget がtrue なら、true を返す。 引数labelSet を伴うDefaultClause のContainsUndefinedBreakTarget がtrue なら、true を返す。 2番目のCaseClauses が存在しないなら、false を返す。 引数labelSet を伴う2番目のCaseClauses のContainsUndefinedBreakTarget を返す。
CaseClauses :
CaseClauses
CaseClause
hasUndefinedLabels を、引数labelSet を伴うCaseClauses のContainsUndefinedBreakTarget とする。hasUndefinedLabels がtrue なら、true を返す。引数labelSet を伴うCaseClause のContainsUndefinedBreakTarget を返す。
CaseClause :
case
Expression
:
StatementList opt
StatementList が存在するなら、引数labelSet を伴うStatementList のContainsUndefinedBreakTarget を返す。false を返す。
DefaultClause :
default
:
StatementList opt
StatementList が存在するなら、引数labelSet を伴うStatementList のContainsUndefinedBreakTarget を返す。false を返す。
LabelledStatement :
LabelIdentifier
:
LabelledItem
label をLabelIdentifier のStringValue とする。newLabelSet をlabelSet と« label »のlist-concatenation とする。引数newLabelSet を伴うLabelledItem のContainsUndefinedBreakTarget を返す。
LabelledItem : FunctionDeclaration
false を返す。
TryStatement :
try
Block
Catch
hasUndefinedLabels を、引数labelSet を伴うBlock のContainsUndefinedBreakTarget とする。hasUndefinedLabels がtrue なら、true を返す。引数labelSet を伴うCatch のContainsUndefinedBreakTarget を返す。
TryStatement :
try
Block
Finally
hasUndefinedLabels を、引数labelSet を伴うBlock のContainsUndefinedBreakTarget とする。hasUndefinedLabels がtrue なら、true を返す。引数labelSet を伴うFinally のContainsUndefinedBreakTarget を返す。
TryStatement :
try
Block
Catch
Finally
引数labelSet を伴うBlock のContainsUndefinedBreakTarget がtrue なら、true を返す。 引数labelSet を伴うCatch のContainsUndefinedBreakTarget がtrue なら、true を返す。 引数labelSet を伴うFinally のContainsUndefinedBreakTarget を返す。
Catch :
catch
(
CatchParameter
)
Block
引数labelSet を伴うBlock のContainsUndefinedBreakTarget を返す。
FunctionStatementList : [empty]
false を返す。
ClassStaticBlockStatementList : [empty]
false を返す。
ModuleItemList :
ModuleItemList
ModuleItem
hasUndefinedLabels を、引数labelSet を伴うModuleItemList のContainsUndefinedBreakTarget とする。hasUndefinedLabels がtrue なら、true を返す。引数labelSet を伴うModuleItem のContainsUndefinedBreakTarget を返す。
ModuleItem :
ImportDeclaration
ExportDeclaration
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
false を返す。
Statement : BlockStatement
引数iterationSet および« »を伴うBlockStatement のContainsUndefinedContinueTarget を返す。
BreakableStatement : IterationStatement
newIterationSet をiterationSet とlabelSet のlist-concatenation とする。引数newIterationSet および« »を伴うIterationStatement のContainsUndefinedContinueTarget を返す。
StatementList :
StatementList
StatementListItem
hasUndefinedLabels を、引数iterationSet および« »を伴うStatementList のContainsUndefinedContinueTarget とする。hasUndefinedLabels がtrue なら、true を返す。引数iterationSet および« »を伴うStatementListItem のContainsUndefinedContinueTarget を返す。
IfStatement :
if
(
Expression
)
Statement
else
Statement
hasUndefinedLabels を、引数iterationSet および« »を伴う最初のStatement のContainsUndefinedContinueTarget とする。hasUndefinedLabels がtrue なら、true を返す。引数iterationSet および« »を伴う2番目のStatement のContainsUndefinedContinueTarget を返す。
IfStatement :
if
(
Expression
)
Statement
引数iterationSet および« »を伴うStatement のContainsUndefinedContinueTarget を返す。
DoWhileStatement :
do
Statement
while
(
Expression
)
;
引数iterationSet および« »を伴うStatement のContainsUndefinedContinueTarget を返す。
WhileStatement :
while
(
Expression
)
Statement
引数iterationSet および« »を伴うStatement のContainsUndefinedContinueTarget を返す。
ForStatement :
for
(
Expression opt
;
Expression opt
;
Expression opt
)
Statement
for
(
var
VariableDeclarationList
;
Expression opt
;
Expression opt
)
Statement
for
(
LexicalDeclaration
Expression opt
;
Expression opt
)
Statement
引数iterationSet および« »を伴うStatement のContainsUndefinedContinueTarget を返す。
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
引数iterationSet および« »を伴うStatement のContainsUndefinedContinueTarget を返す。
Note
この節はAnnex B.3.5 によって拡張されます。
ContinueStatement :
continue
;
false を返す。
ContinueStatement :
continue
LabelIdentifier
;
iterationSet がLabelIdentifier のStringValue を含むなら、false を返す。true を返す。
WithStatement :
with
(
Expression
)
Statement
引数iterationSet および« »を伴うStatement のContainsUndefinedContinueTarget を返す。
SwitchStatement :
switch
(
Expression
)
CaseBlock
引数iterationSet および« »を伴うCaseBlock のContainsUndefinedContinueTarget を返す。
CaseBlock :
{
}
false を返す。
CaseBlock :
{
CaseClauses opt
DefaultClause
CaseClauses opt
}
最初のCaseClauses が存在するなら、引数iterationSet および« »を伴う最初のCaseClauses のContainsUndefinedContinueTarget がtrue なら、true を返す。 引数iterationSet および« »を伴うDefaultClause のContainsUndefinedContinueTarget がtrue なら、true を返す。 2番目のCaseClauses が存在しないなら、false を返す。 引数iterationSet および« »を伴う2番目のCaseClauses のContainsUndefinedContinueTarget を返す。
CaseClauses :
CaseClauses
CaseClause
hasUndefinedLabels を、引数iterationSet および« »を伴うCaseClauses のContainsUndefinedContinueTarget とする。hasUndefinedLabels がtrue なら、true を返す。引数iterationSet および« »を伴うCaseClause のContainsUndefinedContinueTarget を返す。
CaseClause :
case
Expression
:
StatementList opt
StatementList が存在するなら、引数iterationSet および« »を伴うStatementList のContainsUndefinedContinueTarget を返す。false を返す。
DefaultClause :
default
:
StatementList opt
StatementList が存在するなら、引数iterationSet および« »を伴うStatementList のContainsUndefinedContinueTarget を返す。false を返す。
LabelledStatement :
LabelIdentifier
:
LabelledItem
label をLabelIdentifier のStringValue とする。newLabelSet をlabelSet と« label »のlist-concatenation とする。引数iterationSet およびnewLabelSet を伴うLabelledItem のContainsUndefinedContinueTarget を返す。
LabelledItem : FunctionDeclaration
false を返す。
TryStatement :
try
Block
Catch
hasUndefinedLabels を、引数iterationSet および« »を伴うBlock のContainsUndefinedContinueTarget とする。hasUndefinedLabels がtrue なら、true を返す。引数iterationSet および« »を伴うCatch のContainsUndefinedContinueTarget を返す。
TryStatement :
try
Block
Finally
hasUndefinedLabels を、引数iterationSet および« »を伴うBlock のContainsUndefinedContinueTarget とする。hasUndefinedLabels がtrue なら、true を返す。引数iterationSet および« »を伴うFinally のContainsUndefinedContinueTarget を返す。
TryStatement :
try
Block
Catch
Finally
引数iterationSet および« »を伴うBlock のContainsUndefinedContinueTarget がtrue なら、true を返す。 引数iterationSet および« »を伴うCatch のContainsUndefinedContinueTarget がtrue なら、true を返す。 引数iterationSet および« »を伴うFinally のContainsUndefinedContinueTarget を返す。
Catch :
catch
(
CatchParameter
)
Block
引数iterationSet および« »を伴うBlock のContainsUndefinedContinueTarget を返す。
FunctionStatementList : [empty]
false を返す。
ClassStaticBlockStatementList : [empty]
false を返す。
ModuleItemList :
ModuleItemList
ModuleItem
hasUndefinedLabels を、引数iterationSet および« »を伴うModuleItemList のContainsUndefinedContinueTarget とする。hasUndefinedLabels がtrue なら、true を返す。引数iterationSet および« »を伴うModuleItem のContainsUndefinedContinueTarget を返す。
ModuleItem :
ImportDeclaration
ExportDeclaration
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
expr を、CoverParenthesizedExpressionAndArrowParameterList によってcoverされるParenthesizedExpression とする。expr のIsFunctionDefinition がfalse なら、false を返す。expr のHasName を返す。
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
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
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
expr を、CoverParenthesizedExpressionAndArrowParameterList によってcoverされるParenthesizedExpression とする。expr のIsFunctionDefinition を返す。
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
false を返す。
AssignmentExpression :
ArrowFunction
AsyncArrowFunction
FunctionExpression :
function
BindingIdentifier opt
(
FormalParameters
)
{
FunctionBody
}
GeneratorExpression :
function
*
BindingIdentifier opt
(
FormalParameters
)
{
GeneratorBody
}
AsyncGeneratorExpression :
async
function
*
BindingIdentifier opt
(
FormalParameters
)
{
AsyncGeneratorBody
}
AsyncFunctionExpression :
async
function
BindingIdentifier opt
(
FormalParameters
)
{
AsyncFunctionBody
}
ClassExpression :
class
BindingIdentifier opt
ClassTail
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:
expr のIsFunctionDefinition がfalse なら、false を返す。hasName をexpr のHasName とする。hasName がtrue なら、false を返す。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
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
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
expr を、CoverParenthesizedExpressionAndArrowParameterList によってcoverされるParenthesizedExpression とする。引数name を伴うexpr のNamedEvaluation を ? で返す。
ParenthesizedExpression :
(
Expression
)
Assert : IsAnonymousFunctionDefinition (Expression )はtrue である。引数name を伴うExpression のNamedEvaluation を ? で返す。
FunctionExpression :
function
(
FormalParameters
)
{
FunctionBody
}
引数name を伴うFunctionExpression のInstantiateOrdinaryFunctionExpression を返す。
GeneratorExpression :
function
*
(
FormalParameters
)
{
GeneratorBody
}
引数name を伴うGeneratorExpression のInstantiateGeneratorFunctionExpression を返す。
AsyncGeneratorExpression :
async
function
*
(
FormalParameters
)
{
AsyncGeneratorBody
}
引数name を伴うAsyncGeneratorExpression のInstantiateAsyncGeneratorFunctionExpression を返す。
AsyncFunctionExpression :
async
function
(
FormalParameters
)
{
AsyncFunctionBody
}
引数name を伴うAsyncFunctionExpression のInstantiateAsyncFunctionExpression を返す。
ArrowFunction :
ArrowParameters
=>
ConciseBody
引数name を伴うArrowFunction のInstantiateArrowFunctionExpression を返す。
AsyncArrowFunction :
async
AsyncArrowBindingIdentifier
=>
AsyncConciseBody
CoverCallExpressionAndAsyncArrowHead
=>
AsyncConciseBody
引数name を伴うAsyncArrowFunction のInstantiateAsyncArrowFunctionExpression を返す。
ClassExpression :
class
ClassTail
sourceText を、ClassExpression に一致したsource textとする。引数undefined 、name 、およびsourceText を伴うClassTail のClassDefinitionEvaluation を ? で返す。
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のデフォルト定義を持ちます:
このParse Node の各child node child について、以下を行うchild がsymbol のinstanceなら、true を返す。child がnonterminalのinstanceなら、contained をchild Contains symbol の結果とする。contained がtrue なら、true を返す。 false を返す。
FunctionDeclaration :
function
BindingIdentifier
(
FormalParameters
)
{
FunctionBody
}
function
(
FormalParameters
)
{
FunctionBody
}
FunctionExpression :
function
BindingIdentifier opt
(
FormalParameters
)
{
FunctionBody
}
GeneratorDeclaration :
function
*
BindingIdentifier
(
FormalParameters
)
{
GeneratorBody
}
function
*
(
FormalParameters
)
{
GeneratorBody
}
GeneratorExpression :
function
*
BindingIdentifier opt
(
FormalParameters
)
{
GeneratorBody
}
AsyncGeneratorDeclaration :
async
function
*
BindingIdentifier
(
FormalParameters
)
{
AsyncGeneratorBody
}
async
function
*
(
FormalParameters
)
{
AsyncGeneratorBody
}
AsyncGeneratorExpression :
async
function
*
BindingIdentifier opt
(
FormalParameters
)
{
AsyncGeneratorBody
}
AsyncFunctionDeclaration :
async
function
BindingIdentifier
(
FormalParameters
)
{
AsyncFunctionBody
}
async
function
(
FormalParameters
)
{
AsyncFunctionBody
}
AsyncFunctionExpression :
async
function
BindingIdentifier opt
(
FormalParameters
)
{
AsyncFunctionBody
}
false を返す。
Note 1
部分構造に依存する静的意味規則は、一般に関数定義の内部を見ません。
ClassTail :
ClassHeritage opt
{
ClassBody
}
symbol がClassBody なら、true を返す。symbol がClassHeritage なら、ClassHeritage が存在するなら、true を返す。false を返す。ClassHeritage が存在するなら、ClassHeritage Contains symbol がtrue なら、true を返す。引数symbol を伴うClassBody のComputedPropertyContains の結果を返す。
Note 2
部分構造に依存する静的意味規則は、PropertyName を除いて、一般にclass bodiesの内部を見ません。
ClassStaticBlock :
static
{
ClassStaticBlockBody
}
false を返す。
Note 3
部分構造に依存する静的意味規則は、一般にstatic初期化ブロックの内部を見ません。
ArrowFunction :
ArrowParameters
=>
ConciseBody
symbol がNewTarget 、SuperProperty 、SuperCall 、super、またはthisのいずれでもないなら、false を返す。ArrowParameters Contains symbol がtrue なら、true を返す。ConciseBody Contains symbol を返す。
ArrowParameters : CoverParenthesizedExpressionAndArrowParameterList
formals を、CoverParenthesizedExpressionAndArrowParameterList によってcoverされるArrowFormalParameters とする。formals Contains symbol を返す。
AsyncArrowFunction :
async
AsyncArrowBindingIdentifier
=>
AsyncConciseBody
symbol がNewTarget 、SuperProperty 、SuperCall 、super、またはthisのいずれでもないなら、false を返す。AsyncConciseBody Contains symbol を返す。
AsyncArrowFunction :
CoverCallExpressionAndAsyncArrowHead
=>
AsyncConciseBody
symbol がNewTarget 、SuperProperty 、SuperCall 、super、またはthisのいずれでもないなら、false を返す。head を、CoverCallExpressionAndAsyncArrowHead によってcoverされるAsyncArrowHead とする。head Contains symbol がtrue なら、true を返す。AsyncConciseBody Contains symbol を返す。
Note 4
Containsは、ArrowFunction またはAsyncArrowFunction 内でのnew.target、this、およびsuperの使用を検出するために使用されます。
PropertyDefinition : MethodDefinition
symbol がMethodDefinition なら、true を返す。引数symbol を伴うMethodDefinition のComputedPropertyContains の結果を返す。
LiteralPropertyName : IdentifierName
false を返す。
MemberExpression :
MemberExpression
.
IdentifierName
MemberExpression Contains symbol がtrue なら、true を返す。false を返す。
SuperProperty :
super
.
IdentifierName
symbol がReservedWord superなら、true を返す。false を返す。
CallExpression :
CallExpression
.
IdentifierName
CallExpression Contains symbol がtrue なら、true を返す。false を返す。
OptionalChain :
?.
IdentifierName
false を返す。
OptionalChain :
OptionalChain
.
IdentifierName
OptionalChain Contains symbol がtrue なら、true を返す。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
false を返す。
PropertyName : ComputedPropertyName
ComputedPropertyName Contains symbol の結果を返す。
MethodDefinition :
ClassElementName
(
UniqueFormalParameters
)
{
FunctionBody
}
get
ClassElementName
(
)
{
FunctionBody
}
set
ClassElementName
(
PropertySetParameterList
)
{
FunctionBody
}
引数symbol を伴うClassElementName のComputedPropertyContains の結果を返す。
GeneratorMethod :
*
ClassElementName
(
UniqueFormalParameters
)
{
GeneratorBody
}
引数symbol を伴うClassElementName のComputedPropertyContains の結果を返す。
AsyncGeneratorMethod :
async
*
ClassElementName
(
UniqueFormalParameters
)
{
AsyncGeneratorBody
}
引数symbol を伴うClassElementName のComputedPropertyContains の結果を返す。
ClassElementList :
ClassElementList
ClassElement
inList を、引数symbol を伴うClassElementList のComputedPropertyContains とする。inList がtrue なら、true を返す。引数symbol を伴うClassElement のComputedPropertyContains の結果を返す。
ClassElement : ClassStaticBlock
false を返す。
ClassElement : ;
false を返す。
AsyncMethod :
async
ClassElementName
(
UniqueFormalParameters
)
{
AsyncFunctionBody
}
引数symbol を伴うClassElementName のComputedPropertyContains の結果を返す。
FieldDefinition :
ClassElementName
Initializer opt
引数symbol を伴うClassElementName のComputedPropertyContains の結果を返す。
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
}
引数envRecord およびprivateEnv を伴うFunctionDeclaration のInstantiateOrdinaryFunctionObject を返す。
GeneratorDeclaration :
function
*
BindingIdentifier
(
FormalParameters
)
{
GeneratorBody
}
function
*
(
FormalParameters
)
{
GeneratorBody
}
引数envRecord およびprivateEnv を伴うGeneratorDeclaration のInstantiateGeneratorFunctionObject を返す。
AsyncGeneratorDeclaration :
async
function
*
BindingIdentifier
(
FormalParameters
)
{
AsyncGeneratorBody
}
async
function
*
(
FormalParameters
)
{
AsyncGeneratorBody
}
引数envRecord およびprivateEnv を伴うAsyncGeneratorDeclaration のInstantiateAsyncGeneratorFunctionObject を返す。
AsyncFunctionDeclaration :
async
function
BindingIdentifier
(
FormalParameters
)
{
AsyncFunctionBody
}
async
function
(
FormalParameters
)
{
AsyncFunctionBody
}
引数envRecord およびprivateEnv を伴うAsyncFunctionDeclaration のInstantiateAsyncFunctionObject を返す。
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
envRecord にundefined が渡されることは、初期化値を代入するために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
name をIdentifier のStringValue とする。InitializeBoundName (name , value , envRecord )を ? で返す。
BindingIdentifier : yield
InitializeBoundName ("yield" , value , envRecord )を ? で返す。
BindingIdentifier : await
InitializeBoundName ("await" , value , envRecord )を ? で返す。
BindingPattern : ObjectBindingPattern
RequireObjectCoercible (value )を ? で実行する。引数value およびenvRecord を伴うObjectBindingPattern のBindingInitialization を ? で返す。
BindingPattern : ArrayBindingPattern
iteratorRecord を ? GetIterator (value , sync ) とする。result を、引数iteratorRecord およびenvRecord を伴うArrayBindingPattern のIteratorBindingInitialization のCompletion とする。iteratorRecord .[[Done]] がfalse なら、IteratorClose (iteratorRecord , result )を ? で返す。result を ? で返す。
ObjectBindingPattern :
{
}
unused を返す。
ObjectBindingPattern :
{
BindingPropertyList
}
{
BindingPropertyList
,
}
引数value およびenvRecord を伴うBindingPropertyList のPropertyBindingInitialization を ? で実行する。 unused を返す。
ObjectBindingPattern :
{
BindingRestProperty
}
excludedNames を新しい空のList とする。引数value 、envRecord 、およびexcludedNames を伴うBindingRestProperty のRestBindingInitialization を ? で返す。
ObjectBindingPattern :
{
BindingPropertyList
,
BindingRestProperty
}
excludedNames を、引数value およびenvRecord を伴うBindingPropertyList のPropertyBindingInitialization の ? 結果とする。引数value 、envRecord 、およびexcludedNames を伴うBindingRestProperty のRestBindingInitialization を ? で返す。
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:
envRecord がundefined でないなら、envRecord .InitializeBinding (name , value )を ! で実行する。unused を返す。lhs を ? ResolveBinding (name ) とする。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
envRecord にundefined が渡される場合、それは初期化値を代入するためにPutValue 操作を使用すべきであることを示します。これはnon-strict functions のformal parameter listsの場合に該当します。その場合、同じ名前を持つ複数のparametersの可能性に対処するため、formal parameter bindingsは事前初期化されます。
It is defined piecewise over the following productions:
ArrayBindingPattern :
[
]
unused を返す。
ArrayBindingPattern :
[
Elision
]
引数iteratorRecord を伴うElision のIteratorDestructuringAssignmentEvaluation を ? で返す。
ArrayBindingPattern :
[
Elision opt
BindingRestElement
]
Elision が存在するなら、引数iteratorRecord を伴うElision のIteratorDestructuringAssignmentEvaluation を ? で実行する。 引数iteratorRecord およびenvRecord を伴うBindingRestElement のIteratorBindingInitialization を ? で返す。
ArrayBindingPattern :
[
BindingElementList
,
Elision
]
引数iteratorRecord およびenvRecord を伴うBindingElementList のIteratorBindingInitialization を ? で実行する。 引数iteratorRecord を伴うElision のIteratorDestructuringAssignmentEvaluation を ? で返す。
ArrayBindingPattern :
[
BindingElementList
,
Elision opt
BindingRestElement
]
引数iteratorRecord およびenvRecord を伴うBindingElementList のIteratorBindingInitialization を ? で実行する。 Elision が存在するなら、引数iteratorRecord を伴うElision のIteratorDestructuringAssignmentEvaluation を ? で実行する。 引数iteratorRecord およびenvRecord を伴うBindingRestElement のIteratorBindingInitialization を ? で返す。
BindingElementList :
BindingElementList
,
BindingElisionElement
引数iteratorRecord およびenvRecord を伴うBindingElementList のIteratorBindingInitialization を ? で実行する。 引数iteratorRecord およびenvRecord を伴うBindingElisionElement のIteratorBindingInitialization を ? で返す。
BindingElisionElement :
Elision
BindingElement
引数iteratorRecord を伴うElision のIteratorDestructuringAssignmentEvaluation を ? で実行する。 引数iteratorRecord およびenvRecord を伴うBindingElement のIteratorBindingInitialization を ? で返す。
SingleNameBinding :
BindingIdentifier
Initializer opt
bindingId をBindingIdentifier のStringValue とする。lhs を ? ResolveBinding (bindingId , envRecord ) とする。v をundefined とする。iteratorRecord .[[Done]] がfalse なら、next を ? IteratorStepValue (iteratorRecord ) とする。next がdone でないなら、v をnext に設定する。Initializer が存在し、かつv がundefined なら、IsAnonymousFunctionDefinition (Initializer )がtrue なら、v を、引数bindingId を伴うInitializer のNamedEvaluation の ? 結果に設定する。そうでなければ、defaultValue をInitializer のEvaluation の ? 結果とする。v を ? GetValue (defaultValue ) に設定する。 envRecord がundefined なら、PutValue (lhs , v )を ? で返す。InitializeReferencedBinding (lhs , v )を ? で返す。
BindingElement :
BindingPattern
Initializer opt
v をundefined とする。iteratorRecord .[[Done]] がfalse なら、next を ? IteratorStepValue (iteratorRecord ) とする。next がdone でないなら、v をnext に設定する。Initializer が存在し、かつv がundefined なら、defaultValue をInitializer のEvaluation の ? 結果とする。v を ? GetValue (defaultValue ) に設定する。引数v およびenvRecord を伴うBindingPattern のBindingInitialization を ? で返す。
BindingRestElement :
...
BindingIdentifier
lhs を ? ResolveBinding (StringValue of BindingIdentifier , envRecord ) とする。array を ! ArrayCreate (0) とする。n を0とする。繰り返すnext をdone とする。iteratorRecord .[[Done]] がfalse なら、next を ? IteratorStepValue (iteratorRecord ) に設定する。next がdone なら、envRecord がundefined なら、PutValue (lhs , array )を ? で返す。InitializeReferencedBinding (lhs , array )を ? で返す。CreateDataPropertyOrThrow (array , ! ToString (𝔽 (n )), next )を ! で実行する。n をn + 1に設定する。
BindingRestElement :
...
BindingPattern
array を ! ArrayCreate (0) とする。n を0とする。繰り返すnext をdone とする。iteratorRecord .[[Done]] がfalse なら、next を ? IteratorStepValue (iteratorRecord ) に設定する。next がdone なら、引数array およびenvRecord を伴うBindingPattern のBindingInitialization を ? で返す。 CreateDataPropertyOrThrow (array , ! ToString (𝔽 (n )), next )を ! で実行する。n をn + 1に設定する。
FormalParameters : [empty]
unused を返す。
FormalParameters :
FormalParameterList
,
FunctionRestParameter
引数iteratorRecord およびenvRecord を伴うFormalParameterList のIteratorBindingInitialization を ? で実行する。 引数iteratorRecord およびenvRecord を伴うFunctionRestParameter のIteratorBindingInitialization を ? で返す。
FormalParameterList :
FormalParameterList
,
FormalParameter
引数iteratorRecord およびenvRecord を伴うFormalParameterList のIteratorBindingInitialization を ? で実行する。 引数iteratorRecord およびenvRecord を伴うFormalParameter のIteratorBindingInitialization を ? で返す。
ArrowParameters : BindingIdentifier
v をundefined とする。Assert : iteratorRecord .[[Done]] はfalse である。next を ? IteratorStepValue (iteratorRecord ) とする。next がdone でないなら、v をnext に設定する。引数v およびenvRecord を伴うBindingIdentifier のBindingInitialization を ? で返す。
ArrowParameters : CoverParenthesizedExpressionAndArrowParameterList
formals を、CoverParenthesizedExpressionAndArrowParameterList によってcoverされるArrowFormalParameters とする。引数iteratorRecord およびenvRecord を伴うformals のIteratorBindingInitialization を ? で返す。
AsyncArrowBindingIdentifier : BindingIdentifier
v をundefined とする。Assert : iteratorRecord .[[Done]] はfalse である。next を ? IteratorStepValue (iteratorRecord ) とする。next がdone でないなら、v をnext に設定する。引数v およびenvRecord を伴うBindingIdentifier のBindingInitialization を ? で返す。
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
IsStrict (this IdentifierReference )がtrue であり、かつIdentifier のStringValue が"eval" または"arguments" のいずれかなら、invalid を返す。simple を返す。
IdentifierReference :
yield
await
CallExpression :
CallExpression
[
Expression
]
CallExpression
.
IdentifierName
CallExpression
.
PrivateIdentifier
MemberExpression :
MemberExpression
[
Expression
]
MemberExpression
.
IdentifierName
SuperProperty
MemberExpression
.
PrivateIdentifier
simple を返す。
PrimaryExpression :
CoverParenthesizedExpressionAndArrowParameterList
expr を、CoverParenthesizedExpressionAndArrowParameterList によってcoverされるParenthesizedExpression とする。expr のAssignmentTargetType を返す。
CallExpression :
CoverCallExpressionAndAsyncArrowHead
CallExpression
Arguments
hostがweb browserであるか、または他の方法でFunction Call Assignment Targetsに対するRuntime Errors をサポートしており、かつIsStrict (this CallExpression )がfalse なら、web-compat を返す。 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
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
IdentifierReference のStringValue を返す。
PropertyDefinition :
...
AssignmentExpression
empty を返す。
PropertyDefinition :
PropertyName
:
AssignmentExpression
PropertyName のPropName を返す。
LiteralPropertyName : IdentifierName
AttributeKey : IdentifierName
IdentifierName のStringValue を返す。
LiteralPropertyName : StringLiteral
AttributeKey : StringLiteral
StringLiteral のSV を返す。
LiteralPropertyName : NumericLiteral
number をNumericLiteral のNumericValue とする。! ToString (number )を返す。
ComputedPropertyName :
[
AssignmentExpression
]
empty を返す。
MethodDefinition :
ClassElementName
(
UniqueFormalParameters
)
{
FunctionBody
}
get
ClassElementName
(
)
{
FunctionBody
}
set
ClassElementName
(
PropertySetParameterList
)
{
FunctionBody
}
ClassElementName のPropName を返す。
GeneratorMethod :
*
ClassElementName
(
UniqueFormalParameters
)
{
GeneratorBody
}
ClassElementName のPropName を返す。
AsyncGeneratorMethod :
async
*
ClassElementName
(
UniqueFormalParameters
)
{
AsyncGeneratorBody
}
ClassElementName のPropName を返す。
ClassElement : ClassStaticBlock
empty を返す。
ClassElement : ;
empty を返す。
AsyncMethod :
async
ClassElementName
(
UniqueFormalParameters
)
{
AsyncFunctionBody
}
ClassElementName のPropName を返す。
FieldDefinition :
ClassElementName
Initializer opt
ClassElementName のPropName を返す。
ClassElementName : PrivateIdentifier
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
派生した StatementList の ContainsUsing が true である場合、true を返す。 StatementListItem の ContainsUsing が true である場合、true を返す。false を返す。
StatementListItem : Statement
false を返す。
StatementListItem : Declaration
Declaration の IsUsingDeclaration が true である場合、true を返す。Declaration の IsAwaitUsingDeclaration が true である場合、true を返す。false を返す。
9 実行可能コードと実行コンテキスト
9.1 Environment Records
Environment Record は、ECMAScriptコードの字句的な入れ子構造に基づいて、Identifier と特定の変数および関数との関連付けを定義するために使用される仕様型です。通常、Environment Recordは、FunctionDeclaration 、BlockStatement 、またはTryStatement のCatch 節など、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 Record 、Object Environment Record 、およびGlobal Environment Record という3つの具体サブクラスを持つ、単純なオブジェクト指向階層内に存在すると考えることができます。Function Environment Records およびModule Environment Records は、Declarative Environment Record のサブクラスです。
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 Record がname に対する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のテキストです。deletable がtrue なら、その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のテキストです。strict がtrue なら、それが初期化された後に設定しようとする試みは、その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の値です。strict がtrue で、その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を必要とする参照を識別するために使用されます。strict がtrue で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 Record がthis 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 Record のthis bindingの値を返します。this bindingが初期化されていない場合、ReferenceError をthrowします。
これは次の型に具体定義を持ちます:
HasSuperBinding ( )
The abstract method HasSuperBinding takes no arguments and returns a Boolean.
これは、Environment Record がsuper method bindingを確立するかどうかを決定します。確立する場合はtrue を返し、そうでない場合はfalse を返します。true を返す場合、そのEnvironment Record がFunction Environment Record であることを含意しますが、その逆は成り立ちません。
これは次の型に具体定義を持ちます:
WithBaseObject ( )
The abstract method WithBaseObject takes no arguments and returns an Object or undefined .
このEnvironment Record がwith 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 Records の List を含む。このリストの要素は、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:
envRecord がname に対するbindingを持つなら、true を返す。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が既に存在してはなりません。deletable がtrue なら、新しいbindingは削除対象であるとして印付けられます。 It performs the following steps when called:
Assert : envRecord はname に対するbindingを既に持っていない。envRecord 内にname に対するmutable bindingを作成し、それが未初期化であることを記録する。deletable がtrue なら、新しく作成されたbindingが後続のDeleteBinding 呼び出しによって削除され得ることを記録する。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が既に存在してはなりません。strict がtrue なら、新しいbindingはstrict bindingとして印付けられます。 It performs the following steps when called:
Assert : envRecord はname に対するbindingを既に持っていない。envRecord 内にname に対するimmutable bindingを作成し、それが未初期化であることを記録する。strict がtrue なら、新しく作成されたbindingがstrict bindingであることを記録する。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:
Assert : envRecord はname に対する未初期化のbindingを持っていなければならない。envRecord 内のname に対するbound valueをvalue に設定する。envRecord 内のname に対するbindingが初期化済みであることをRecord する。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である場合、strict がtrue ならTypeError がthrowされます。 It performs the following steps when called:
envRecord がname に対するbindingを持たないなら、strict がtrue なら、ReferenceError 例外をthrowする。! envRecord .CreateMutableBinding (name , true )を実行する。 ! envRecord .InitializeBinding (name , value )を実行する。 unused を返す。envRecord 内のname に対するbindingがstrict bindingなら、strict をtrue に設定する。envRecord 内のname に対するbindingがまだ初期化されていないなら、ReferenceError 例外をthrowする。そうでなく、envRecord 内のname に対するbindingがmutable bindingなら、そのbound valueをvalue へ変更する。 そうでなければ、Assert : これはimmutable bindingの値を変更しようとする試みである。strict がtrue なら、TypeError 例外をthrowする。 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:
Assert : envRecord はname に対するbindingを持つ。envRecord 内のname に対するbindingが未初期化のbindingなら、ReferenceError 例外をthrowする。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:
Assert : envRecord はname に対するbindingを持つ。envRecord 内のname に対するbindingを削除できないなら、false を返す。envRecord からname に対するbindingを削除する。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:
false を返す。
Note
9.1.1.1.9 GetThisBinding ( )
Declarative Environment Record のGetThisBinding 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:
false を返す。
Note
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:
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
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:
bindingObj をenvRecord .[[BindingObject]] とする。foundBinding を ? HasProperty (bindingObj , name ) とする。foundBinding がfalse なら、false を返す。envRecord .[[IsWithEnvironment]] がfalse なら、true を返す。unscopables を ? Get (bindingObj , %Symbol.unscopables% ) とする。unscopables がObjectなら、blocked をToBoolean (? Get (unscopables , name ))とする。blocked がtrue なら、false を返す。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 で初期化します。deletable がtrue なら、新しいプロパティの[[Configurable]] 属性はtrue に設定されます。そうでなければfalse に設定されます。 It performs the following steps when called:
bindingObj をenvRecord .[[BindingObject]] とする。? DefinePropertyOrThrow (bindingObj , name , PropertyDescriptor { [[Value]] : undefined , [[Writable]] : true , [[Enumerable]] : true , [[Configurable]] : deletable })を実行する。 unused を返す。
Note
通常、envRecord はname に対するbindingを持ちませんが、持つ場合、DefinePropertyOrThrow の意味論は、既存のbindingが置換またはshadowされる結果になるか、abrupt completion が返される原因となる場合があります。
9.1.1.2.3 CreateImmutableBinding ( name , strict )
Object Environment Record のCreateImmutableBinding 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:
? envRecord .SetMutableBinding (name , value , false ) を実行する。 unused を返す。
Note
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:
bindingObj をenvRecord .[[BindingObject]] とする。stillExists を ? HasProperty (bindingObj , name ) とする。stillExists がfalse かつstrict がtrue なら、ReferenceError 例外をthrowする。? Set (bindingObj , name , value , strict )を実行する。 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:
bindingObj をenvRecord .[[BindingObject]] とする。value を ? HasProperty (bindingObj , name ) とする。value がfalse なら、strict がfalse なら、undefined を返す。ReferenceError 例外をthrowする。? 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:
bindingObj をenvRecord .[[BindingObject]] とする。? 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:
false を返す。
Note
9.1.1.2.9 GetThisBinding ( )
Object Environment Record のGetThisBinding 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:
false を返す。
Note
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:
envRecord .[[IsWithEnvironment]] がtrue なら、envRecord .[[BindingObject]] を返す。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
Function Environment Recordsは、Table 15 に列挙されるすべてのDeclarative Environment Record methodsをサポートし、HasThisBinding 、GetThisBinding 、および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:
Assert : envRecord .[[ThisBindingStatus]] はlexical でない。envRecord .[[ThisBindingStatus]] がinitialized なら、ReferenceError 例外をthrowする。envRecord .[[ThisValue]] をvalue に設定する。envRecord .[[ThisBindingStatus]] をinitialized に設定する。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:
envRecord .[[ThisBindingStatus]] がlexical なら、false を返す。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:
Assert : envRecord .[[ThisBindingStatus]] はlexical でない。envRecord .[[ThisBindingStatus]] がuninitialized なら、ReferenceError 例外をthrowする。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:
envRecord .[[ThisBindingStatus]] がlexical なら、false を返す。envRecord .[[FunctionObject]] .[[HomeObject]] がundefined なら、false を返す。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:
home をenvRecord .[[FunctionObject]] .[[HomeObject]] とする。home がundefined なら、undefined を返す。Assert : home はordinary object である。! 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.11 、8.2.13 )に対するbindingsを提供します。
Global Environment Recordは論理的には単一のrecordですが、Object Environment Record とDeclarative Environment Record をカプセル化する合成物として指定されます。Object Environment Record は、関連付けられたRealm Record のglobal 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に含まれるFunctionDeclaration 、GeneratorDeclaration 、AsyncFunctionDeclaration 、AsyncGeneratorDeclaration 、またはVariableStatement によって導入されるすべてのbindingsを含みます。global code内の他のすべてのECMAScript declarationsに対するbindingsは、Global Environment RecordのDeclarative Environment Record componentに含まれます。
プロパティはglobal object 上に直接作成される場合があります。したがって、Global Environment RecordのObject Environment Record componentは、FunctionDeclaration 、GeneratorDeclaration 、AsyncFunctionDeclaration 、AsyncGeneratorDeclaration 、またはVariableDeclaration declarationsによって明示的に作成されるbindingsと、global object のプロパティとして暗黙的に作成されるbindingsの両方を含む場合があります。
Global Environment Recordsは、Table 18 に列挙される追加フィールドを持ちます。
Table 18: Additional Fields of Global Environment Records
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:
declRecord をenvRecord .[[DeclarativeRecord]] とする。! declRecord .HasBinding (name )がtrue なら、true を返す。 objRecord をenvRecord .[[ObjectRecord]] とする。? 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内に既に存在してはなりません。deletable がtrue なら、新しいbindingは削除対象であるとして印付けられます。 It performs the following steps when called:
declRecord をenvRecord .[[DeclarativeRecord]] とする。! declRecord .HasBinding (name )がtrue なら、TypeError 例外をthrowする。 ! 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が既に存在してはなりません。strict がtrue なら、新しいbindingはstrict bindingとして印付けられます。 It performs the following steps when called:
declRecord をenvRecord .[[DeclarativeRecord]] とする。! declRecord .HasBinding (name )がtrue なら、TypeError 例外をthrowする。 ! 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:
declRecord をenvRecord .[[DeclarativeRecord]] とする。! declRecord .HasBinding (name )がtrue なら、! declRecord .InitializeBinding (name , value )を返す。 Assert : bindingが存在するなら、それはObject Environment Record 内になければならない。objRecord をenvRecord .[[ObjectRecord]] とする。? 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であり、strict がtrue の場合、TypeError がthrowされます。name という名前のbindingは通常既に存在しますが、存在しない場合や現在writableでない場合、error handlingはstrict によって決定されます。 It performs the following steps when called:
declRecord をenvRecord .[[DeclarativeRecord]] とする。! declRecord .HasBinding (name )がtrue なら、? declRecord .SetMutableBinding (name , value , strict )を返す。 objRecord をenvRecord .[[ObjectRecord]] とする。? 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:
declRecord をenvRecord .[[DeclarativeRecord]] とする。! declRecord .HasBinding (name )がtrue なら、? declRecord .GetBindingValue (name , strict )を返す。 objRecord をenvRecord .[[ObjectRecord]] とする。? 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:
declRecord をenvRecord .[[DeclarativeRecord]] とする。! declRecord .HasBinding (name )がtrue なら、! declRecord .DeleteBinding (name )を返す。 objRecord をenvRecord .[[ObjectRecord]] とする。globalObj をobjRecord .[[BindingObject]] とする。existingProperty を ? HasOwnProperty (globalObj , name ) とする。existingProperty がtrue なら、? objRecord .DeleteBinding (name ) を返す。 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:
true を返す。
Note
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:
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:
false を返す。
Note
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:
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が、LexicalDeclaration やClassDeclaration などのlexical declarationを使用して作成されたbindingをenvRecord 内に持つかどうかを決定します。 It performs the following steps when called:
declRecord をenvRecord .[[DeclarativeRecord]] とする。! 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:
objRecord をenvRecord .[[ObjectRecord]] とする。globalObj をobjRecord .[[BindingObject]] とする。existingProperty を ? globalObj .[[GetOwnProperty]] (name ) とする。existingProperty がundefined なら、false を返す。existingProperty .[[Configurable]] がtrue なら、false を返す。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:
objRecord をenvRecord .[[ObjectRecord]] とする。globalObj をobjRecord .[[BindingObject]] とする。hasProperty を ? HasOwnProperty (globalObj , name ) とする。hasProperty がtrue なら、true を返す。? 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:
objRecord をenvRecord .[[ObjectRecord]] とする。globalObj をobjRecord .[[BindingObject]] とする。existingProperty を ? globalObj .[[GetOwnProperty]] (name ) とする。existingProperty がundefined なら、? IsExtensible (globalObj )を返す。existingProperty .[[Configurable]] がtrue なら、true を返す。IsDataDescriptor (existingProperty )がtrue であり、かつexistingProperty がattribute values { [[Writable]] : true , [[Enumerable]] : true }を持つなら、true を返す。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:
objRecord をenvRecord .[[ObjectRecord]] とする。globalObj をobjRecord .[[BindingObject]] とする。hasProperty を ? HasOwnProperty (globalObj , name ) とする。extensible を ? IsExtensible (globalObj ) とする。hasProperty がfalse かつextensible がtrue なら、? objRecord .CreateMutableBinding (name , deletable ) を実行する。 ? objRecord .InitializeBinding (name , undefined ) を実行する。 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:
objRecord をenvRecord .[[ObjectRecord]] とする。globalObj をobjRecord .[[BindingObject]] とする。existingProperty を ? globalObj .[[GetOwnProperty]] (name ) とする。existingProperty がundefined またはexistingProperty .[[Configurable]] がtrue なら、propertyDesc をPropertyDescriptor { [[Value]] : value , [[Writable]] : true , [[Enumerable]] : true , [[Configurable]] : deletable }とする。そうでなければ、propertyDesc をPropertyDescriptor { [[Value]] : value }とする。 ? DefinePropertyOrThrow (globalObj , name , propertyDesc )を実行する。 ? Set (globalObj , name , value , false )を実行する。 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をサポートし、GetBindingValue 、DeleteBinding 、HasThisBinding 、および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:
Assert : strict はtrue である。Assert : envRecord はname に対するbindingを持つ。name に対するbindingがindirect bindingであるなら、module およびtargetName を、このname に対するbindingが作成されたときに提供されたindirection valuesとする。targetEnv をmodule .[[Environment]] とする。targetEnv がempty なら、ReferenceError 例外をthrowする。? targetEnv .GetBindingValue (targetName , true ) を返す。 envRecord 内のname に対するbindingが未初期化のbindingなら、ReferenceError 例外をthrowする。envRecord 内でname に現在bindされている値を返す。
Note
Module は常にstrict mode code であるため、strict は常にtrue になります。
9.1.1.5.2 DeleteBinding ( name )
Module Environment Record のDeleteBinding 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:
true を返す。
Note
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:
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 は、targetModule のModule Environment Record 内に存在するbindingの名前です。新しいbindingの値へのアクセスは、target bindingのbound valueに間接的にアクセスします。 It performs the following steps when called:
Assert : envRecord はname に対するbindingを既に持っていない。Assert : targetModule .[[Environment]] がinstantiatedされるとき、それはtargetName に対するdirect bindingを持つ。envRecord 内にname に対するimmutable indirect bindingを作成し、それがtargetModule およびtargetName をそのtarget bindingとして参照することを記録し、bindingが初期化済みであることを記録する。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:
envRecord がnull なら、Reference Record { [[Base]] : unresolvable , [[ReferencedName]] : name , [[Strict]] : strict , [[ThisValue]] : empty }を返す。exists を ? envRecord .HasBinding (name ) とする。exists がtrue なら、Reference Record { [[Base]] : envRecord , [[ReferencedName]] : name , [[Strict]] : strict , [[ThisValue]] : empty }を返す。outer をenvRecord .[[OuterEnv]] とする。? 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:
envRecord を、束縛を含まない新しい Declarative Environment Record とする。envRecord .[[OuterEnv]] を outerEnv に設定する。envRecord .[[DisposableResourceStack]] を新しい空の List に設定する。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:
envRecord を新しいObject Environment Record とする。envRecord .[[BindingObject]] をobj に設定する。envRecord .[[IsWithEnvironment]] をisWithEnv に設定する。envRecord .[[OuterEnv]] をouterEnv に設定する。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:
envRecord を、束縛を含まない新しい Function Environment Record とする。envRecord .[[FunctionObject]] を func に設定する。func .[[ThisMode]] が lexical である場合、envRecord .[[ThisBindingStatus]] を lexical に設定する。Else, envRecord .[[ThisBindingStatus]] を uninitialized に設定する。 envRecord .[[NewTarget]] を newTarget に設定する。envRecord .[[OuterEnv]] を func .[[Environment]] に設定する。envRecord .[[DisposableResourceStack]] を新しい空の List に設定する。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:
objRecord をNewObjectEnvironment (obj , false , null )とする。declRecord をNewDeclarativeEnvironment (null )とする。envRecord を新しいGlobal Environment Record とする。envRecord .[[ObjectRecord]] をobjRecord に設定する。envRecord .[[GlobalThisValue]] をthisValue に設定する。envRecord .[[DeclarativeRecord]] をdeclRecord に設定する。envRecord .[[OuterEnv]] をnull に設定する。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:
envRecord を、束縛を含まない新しい Module Environment Record とする。envRecord .[[OuterEnv]] を outerEnv に設定する。envRecord .[[DisposableResourceStack]] を新しい空の List に設定する。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
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:
names を新しい空のList とする。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:
names をprivateEnv .[[Names]] とする。names の各Private Name privateName について、以下を行うprivateName .[[Description]] がidentifier なら、privateName を返す。outerPrivateEnv をprivateEnv .[[OuterPrivateEnvironment]] とする。Assert : outerPrivateEnv はnull でない。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
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:
realm を新しいRealm Record とする。CreateIntrinsics (realm )を実行する。realm .[[AgentSignifier]] をAgentSignifier ()に設定する。realm .[[TemplateMap]] を新しい空のList に設定する。newContext を新しいexecution context とする。newContext のFunctionをnull に設定する。newContext のRealm をrealm に設定する。newContext のScriptOrModuleをnull に設定する。newContext をexecution context stack へpushする;newContext は現在running execution context である。hostが、realm のglobal object として機能する特定のオブジェクトの使用を要求するなら、global を、host-defined mannerで作成されたそのようなオブジェクトとする。 そうでなければ、global をOrdinaryObjectCreate (realm .[[Intrinsics]] .[[%Object.prototype% ]])とする。 hostが、realm のglobal scope内のthis bindingにglobal object 以外のオブジェクトを返すことを要求するなら、thisValue を、host-defined mannerで作成されたそのようなオブジェクトとする。 そうでなければ、thisValue をglobal とする。 realm .[[GlobalObject]] をglobal に設定する。realm .[[GlobalEnv]] をNewGlobalEnvironment (global , thisValue )に設定する。? SetDefaultGlobalBindings (realm )を実行する。 host-defined global object propertiesをglobal 上に作成する。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:
realmRecord .[[Intrinsics]] を新しいRecord に設定する。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の作成は、まだ作成されていないオブジェクトへの依存を避けるように順序付けられていなければなりません。AddRestrictedFunctionProperties (realmRecord .[[Intrinsics]] .[[%Function.prototype% ]], realmRecord )を実行する。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:
global をrealmRecord .[[GlobalObject]] とする。19 節で指定されるGlobal Objectの各propertyについて、以下を行うname をproperty name のString値とする。propertyDesc を、そのpropertyの指定されたattributesを含む、そのpropertyの完全にpopulatedされたdata Property Descriptor とする。19.2 、19.3 、または19.4 に列挙されるpropertiesについては、[[Value]] 属性の値はrealmRecord からの対応するintrinsic objectです。? DefinePropertyOrThrow (global , name , propertyDesc )を実行する。 unused を返す。
9.4 Execution Contexts
execution context は、ECMAScript実装によるコードのruntime評価を追跡するために使用される仕様上の装置です。任意の時点で、実際にコードを実行しているexecution contextは、agent ごとに最大1つです。これはそのagent のrunning execution context として知られます。この仕様におけるrunning execution context へのすべての参照は、周囲のagent のrunning 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
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 context のRealm 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
execution contextのLexicalEnvironmentおよびVariableEnvironment componentsは、常にEnvironment Records です。
Generatorsの評価を表すexecution contextsは、Table 23 に列挙される追加の状態componentsを持ちます。
Table 23: Additional State Components for Generator Execution Contexts
ほとんどの状況では、この仕様内のアルゴリズムによって直接操作されるのは、running execution context (execution 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:
execution context stack が空なら、null を返す。executionContext を、execution context stack 上でScriptOrModule componentがnull でない最上位のexecution context とする。そのようなexecution context が存在しないなら、null を返す。 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:
envRecord が存在しない、またはenvRecord がundefined なら、envRecord をrunning execution context のLexicalEnvironmentに設定する。Assert : envRecord はEnvironment Record である。strict を、評価中のsyntactic productionのIsStrict とする。? 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:
envRecord をrunning execution context のLexicalEnvironmentとする。繰り返すexists をenvRecord .HasThisBinding ()とする。exists がtrue なら、envRecord を返す。outer をenvRecord .[[OuterEnv]] とする。Assert : outer はnull でない。envRecord をouter に設定する。
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:
envRecord をGetThisEnvironment ()とする。? 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:
envRecord をGetThisEnvironment ()とする。Assert : envRecord は[[NewTarget]] フィールドを持つ。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:
currentRealm をcurrent Realm Record とする。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:
callerContext をrunning execution context とする。callerContext を一時停止する。context をexecution context stack へpushする;context は現在running execution context である。context の一時停止された評価を再開する 。このとき、completionRecord を、それを一時停止した操作の結果として使用する。result を、再開された計算によって返されたCompletion Record とする。Assert : このステップに到達したとき、context はすでにexecution context stack から取り除かれており、callerContext が再びrunning execution context である。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:
genContext を、実行中の実行コンテキストとする。実行コンテキストスタックからgenContext を取り除き、実行コンテキストスタックの先頭にある実行コンテキストを実行中の実行コンテキストとして復元する。 callerContext を、実行中の実行コンテキストとする。NormalCompletion (value )を渡して、callerContext を再開する。NOTE : 上記の手順は制御をcallerContext に移し、一時停止する。このアルゴリズムで一時停止が解除され、後続の手順へ制御が進む唯一の方法は、genContext が再び再開されることであり、それは決して起こらない可能性がある。Assert : genContext は実行中の実行コンテキストである。result を、genContext がたった今再開されたときのCompletion Record とする。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 であるHostEnqueueGenericJob 、HostEnqueueFinalizationRegistryCleanupJob 、HostEnqueuePromiseJob 、およびHostEnqueueTimeoutJob を記述します。この仕様内のhost hooks は、jobsのschedulingに課される追加制約によって編成されています。Hosts は、jobsをscheduleする追加のabstract operations を定義できます。そのようなoperationsは、Job Abstract Closure とrealm (Realm Record またはnull )をparametersとして受け取ります。Realm Record が提供された場合、これらのoperationsは、realm を所有するagent 内で、提供されたrealm において将来のある時点でjobが実行されるようscheduleします。realm として代わりにnull が提供された場合、そのjobはECMAScriptコードを評価しません。それらの実装は、次の要件に適合しなければなりません:
Note 1
Host environments は、schedulingに関して
Jobs を一律に扱うことを要求されません。たとえば、web browsersおよびNode.jsは、Promise-handling
Jobs を他の作業より高いpriorityとして扱います;将来のfeaturesは、そのような高いpriorityとして扱われない
Jobs を追加する場合があります。
任意の特定の時点で、次の条件のすべてがtrueであるなら、scriptOrModule (Script Record 、Module Record 、またはnull )はactive script or module です:
任意の特定の時点で、次の条件のすべてがtrueであるなら、executionはECMAScriptコードを評価する準備ができている ものとします:
Note 2
Host environments は、execution contexts をexecution 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 Closures はfunction 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の実装は、次の要件に適合しなければなりません:
HostMakeJobCallbackのデフォルト実装は、呼び出されたときに次のstepsを実行します:
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を実行します:
Assert : IsCallable (jobCallback .[[Callback]] )はtrue である。? 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 の要件に加えて、次に適合しなければなりません:
Note
NewPromiseResolveThenableJob によって返されるJobs のrealm は通常、then function object に対してGetFunctionRealm を呼び出した結果です。NewPromiseReactionJob によって返されるJobs のrealm は通常、handlerがundefined でない場合、そのhandlerに対してGetFunctionRealm を呼び出した結果です。handlerがundefined である場合、realm はnull です。両方の種類のJobs について、GetFunctionRealm がabnormallyに完了する場合(すなわちrevoked Proxy上で呼び出された場合)、realm はGetFunctionRealm 呼び出し時点のcurrent Realm Record です。realm がnull の場合、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 stack 、running execution context 、Agent Record 、およびexecuting thread から構成されます。executing thread を除き、agent の構成要素はそのagent のみに属します。
agent のexecuting thread は、他のagents から独立して、そのagent のexecution contexts 上でalgorithmic stepsを実行します。ただし、threadを共有するどのagent も[[CanBlock]] フィールドがtrue であるAgent Record を持たない場合、executing thread は複数のagents によってexecuting thread として使用される場合があります。
Note 1
たとえば、一部のweb browsersは、browser windowの複数の無関係なtabs間で単一のexecuting thread を共有します。
agent のexecuting thread がalgorithmic stepsを実行している間、そのagent はそれらのstepsに対するsurrounding agent です。stepsは、agent 内に保持される仕様レベルのexecution objects、すなわちrunning execution context 、execution 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 Record の List
初期状態では新しい空の 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:
agentRecord をsurrounding agent のAgent Record とする。agentRecord .[[Signifier]] を返す。
9.6.2 AgentCanSuspend ( )
The abstract operation AgentCanSuspend takes no arguments and returns a Boolean. It performs the following steps when called:
agentRecord をsurrounding agent のAgent Record とする。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:
agentRecord をsurrounding agent のAgent Record とする。count をagentRecord .[[ModuleAsyncEvaluationCount]] とする。agentRecord .[[ModuleAsyncEvaluationCount]] をcount + 1に設定する。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 が終了し、B がagent 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内のすべてのagents のAgent Record の[[CandidateExecution]] フィールドは、initial candidate execution に設定されます。initial candidate execution は空のcandidate execution であり、その[[EventsRecords]] フィールドは、各agent について、そのagent のagent signifier を[[AgentSignifier]] フィールドに持ち、[[EventList]] および[[AgentSynchronizesWith]] フィールドが空のLists であるAgent Events Record を含むList です。
Note 6
agent cluster内のすべてのagents は、そのAgent Record の[[CandidateExecution]] フィールド内で同じcandidate execution を共有します。candidate execution はmemory model によって使用される仕様上の仕組みです。
Note 7
agent clusterは仕様上の仕組みであり、ECMAScript実装の特定のartefactに対応する必要はありません。
9.8 Forward Progress
agent がforward progressを行う とは、この仕様に従ってevaluation stepを実行することです。
agent は、そのrunning execution context が外部eventを同期的かつ無期限に待つとき、blocked になります。この意味でblockedになれるのは、そのAgent Record の[[CanBlock]] フィールドがtrue であるagents だけです。unblocked agent とは、blockedでないagent です。
実装は次を保証しなければなりません:
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に基づきます:
これらの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の集合objSet がlive でない場合、ECMAScript実装は次のstepsをatomicallyに実行してよいです:
objSet の各要素value について、以下を行うref .[[WeakRefTarget]] がvalue であるような各WeakRef ref について、以下を行うref .[[WeakRefTarget]] をempty に設定する。finalizationRegistry .[[Cells]] が、cell .[[WeakRefTarget]] がvalue であるようなRecord cell を含む各FinalizationRegistry finalizationRegistry について、以下を行うcell .[[WeakRefTarget]] をempty に設定する。enqueueCleanup を、true またはfalse のいずれかのimplementation-defined choiceとする。enqueueCleanup がtrue なら、HostEnqueueFinalizationRegistryCleanupJob (finalizationRegistry )を実行する。map .[[WeakMapData]] が、entry .[[Key]] がvalue であるようなRecord entry を含む各WeakMap map について、以下を行うentry .[[Key]] をempty に設定する。entry .[[Value]] をempty に設定する。set .[[WeakSetData]] がvalue を含む各WeakSet set について、以下を行う値が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 とする:
cleanupResult をCompletion (CleanupFinalizationRegistry (finalizationRegistry ))とする。cleanupResult がabrupt completion であるなら、errorをreportするための任意のhost-defined stepsを実行する。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:
agentRecord をsurrounding agent のAgent Record とする。agentRecord .[[KeptAlive]] を新しい空のList に設定する。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:
agentRecord をsurrounding agent のAgent Record とする。value をagentRecord .[[KeptAlive]] へappendする。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:
Assert : finalizationRegistry は[[Cells]] および[[CleanupCallback]] internal slotsを持つ。callback をfinalizationRegistry .[[CleanupCallback]] とする。finalizationRegistry .[[Cells]] がcell .[[WeakRefTarget]] がempty であるRecord cell を含む間、実装は次のstepsを実行してよい:そのようなcell を任意に選択する。 cell をfinalizationRegistry .[[Cells]] から削除する。? HostCallJobCallback (callback , undefined , « cell .[[HeldValue]] »)を実行する。 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:
arg がObjectなら、true を返す。arg がSymbolであり、KeyForSymbol (arg )がundefined なら、true を返す。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についてそれを継承し、propertyKey がobj の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では、obj はordinary object 、propertyKey はproperty key 値、value は任意のECMAScript言語値 、propertyDesc はProperty 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:
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:
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:
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:
current をobj .[[Prototype]] とする。SameValue (proto , current )がtrue なら、true を返す。extensible をobj .[[Extensible]] とする。extensible がfalse なら、false を返す。cursor をproto とする。done をfalse とする。done がfalse である間、繰り返すcursor がnull なら、done をtrue に設定する。そうでなく、SameValue (cursor , obj )がtrue なら、false を返す。 そうでなければ、cursor .[[GetPrototypeOf]] が10.1.1 で定義されるordinary object internal methodでないなら、done をtrue に設定する。そうでなければ、cursor をcursor .[[Prototype]] に設定する。 obj .[[Prototype]] をproto に設定する。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:
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:
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:
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:
obj .[[Extensible]] をfalse に設定する。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:
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:
obj がkey propertyKey を持つown propertyを持たないなら、undefined を返す。propertyDesc を、fieldsを持たない新しく作成されたProperty Descriptor とする。ownProperty を、keyがpropertyKey であるobj のown propertyとする。ownProperty がdata property なら、propertyDesc .[[Value]] をownProperty の[[Value]] 属性の値に設定する。propertyDesc .[[Writable]] をownProperty の[[Writable]] 属性の値に設定する。そうでなければ、Assert : ownProperty はaccessor property である。propertyDesc .[[Get]] をownProperty の[[Get]] 属性の値に設定する。propertyDesc .[[Set]] をownProperty の[[Set]] 属性の値に設定する。 propertyDesc .[[Enumerable]] をownProperty の[[Enumerable]] 属性の値に設定する。propertyDesc .[[Configurable]] をownProperty の[[Configurable]] 属性の値に設定する。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:
? 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:
current を ? obj .[[GetOwnProperty]] (propertyKey ) とする。extensible を ? IsExtensible (obj ) とする。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:
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 を返します。そのような適用が可能であり、obj がundefined でない場合、propertyKey という名前のpropertyについてそれが実行されます(必要であれば作成されます)。 It performs the following steps when called:
Assert : propertyKey はproperty key である。current がundefined なら、extensible がfalse なら、false を返す。obj がundefined なら、true を返す。IsAccessorDescriptor (propertyDesc )がtrue なら、object obj のpropertyKey という名前のown accessor property を作成する。その[[Get]] 、[[Set]] 、[[Enumerable]] 、および[[Configurable]] 属性は、propertyDesc が対応するfieldを持つ場合はpropertyDesc 内の対応するfieldの値に、そうでない場合はその属性のdefault value に設定される。 そうでなければ、object obj のpropertyKey という名前のown data property を作成する。その[[Value]] 、[[Writable]] 、[[Enumerable]] 、および[[Configurable]] 属性は、propertyDesc が対応するfieldを持つ場合はpropertyDesc 内の対応するfieldの値に、そうでない場合はその属性のdefault value に設定される。 true を返す。Assert : current はfully populated Property Descriptor である。propertyDesc がfieldsをまったく持たないなら、true を返す。current .[[Configurable]] がfalse なら、propertyDesc が[[Configurable]] fieldを持ち、propertyDesc .[[Configurable]] がtrue なら、false を返す。propertyDesc が[[Enumerable]] fieldを持ち、propertyDesc .[[Enumerable]] がcurrent .[[Enumerable]] でないなら、false を返す。IsGenericDescriptor (propertyDesc )がfalse であり、かつIsAccessorDescriptor (propertyDesc )がIsAccessorDescriptor (current )でないなら、false を返す。IsAccessorDescriptor (current )がtrue なら、propertyDesc が[[Get]] fieldを持ち、SameValue (propertyDesc .[[Get]] , current .[[Get]] )がfalse なら、false を返す。propertyDesc が[[Set]] fieldを持ち、SameValue (propertyDesc .[[Set]] , current .[[Set]] )がfalse なら、false を返す。そうでなく、current .[[Writable]] がfalse なら、propertyDesc が[[Writable]] fieldを持ち、propertyDesc .[[Writable]] がtrue なら、false を返す。NOTE : SameValue はNaN valuesに対してtrue を返しますが、それらは他の手段によって区別可能な場合があります。ここで返すことにより、obj の既存propertyが変更されないことが保証されます。propertyDesc が[[Value]] fieldを持つなら、SameValue (propertyDesc .[[Value]] , current .[[Value]] )を返す。 obj がundefined でないなら、IsDataDescriptor (current )がtrue であり、かつIsAccessorDescriptor (propertyDesc )がtrue なら、propertyDesc が[[Configurable]] fieldを持つなら、configurable をpropertyDesc .[[Configurable]] とする;そうでなければ、configurable をcurrent .[[Configurable]] とする。propertyDesc が[[Enumerable]] fieldを持つなら、enumerable をpropertyDesc .[[Enumerable]] とする;そうでなければ、enumerable をcurrent .[[Enumerable]] とする。object obj のpropertyKey という名前のpropertyをaccessor property で置き換える。その[[Configurable]] および[[Enumerable]] 属性はそれぞれconfigurable およびenumerable に設定され、その[[Get]] および[[Set]] 属性は、propertyDesc が対応するfieldを持つ場合はpropertyDesc 内の対応するfieldの値に、そうでない場合はその属性のdefault value に設定される。 そうでなく、IsAccessorDescriptor (current )がtrue であり、かつIsDataDescriptor (propertyDesc )がtrue なら、propertyDesc が[[Configurable]] fieldを持つなら、configurable をpropertyDesc .[[Configurable]] とする;そうでなければ、configurable をcurrent .[[Configurable]] とする。propertyDesc が[[Enumerable]] fieldを持つなら、enumerable をpropertyDesc .[[Enumerable]] とする;そうでなければ、enumerable をcurrent .[[Enumerable]] とする。object obj のpropertyKey という名前のpropertyをdata property で置き換える。その[[Configurable]] および[[Enumerable]] 属性はそれぞれconfigurable およびenumerable に設定され、その[[Value]] および[[Writable]] 属性は、propertyDesc が対応するfieldを持つ場合はpropertyDesc 内の対応するfieldの値に、そうでない場合はその属性のdefault value に設定される。 そうでなければ、propertyDesc の各field name fieldName について、object obj のpropertyKey という名前のpropertyのfieldName という名前の属性を、propertyDesc のfieldName fieldの値に設定する。 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:
? 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:
hasOwn を ? obj .[[GetOwnProperty]] (propertyKey ) とする。hasOwn がundefined でないなら、true を返す。parent を ? obj .[[GetPrototypeOf]] () とする。parent がnull でないなら、? parent .[[HasProperty]] (propertyKey ) を返す。 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:
? 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:
propertyDesc を ? obj .[[GetOwnProperty]] (propertyKey ) とする。propertyDesc がundefined なら、parent を ? obj .[[GetPrototypeOf]] () とする。parent がnull なら、undefined を返す。? parent .[[Get]] (propertyKey , receiver ) を返す。 IsDataDescriptor (propertyDesc )がtrue なら、propertyDesc .[[Value]] を返す。Assert : IsAccessorDescriptor (propertyDesc )はtrue である。getter をpropertyDesc .[[Get]] とする。getter がundefined なら、undefined を返す。? 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:
? 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:
ownDesc を ? obj .[[GetOwnProperty]] (propertyKey ) とする。? 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:
ownDesc がundefined なら、parent を ? obj .[[GetPrototypeOf]] () とする。parent がnull でないなら、? parent .[[Set]] (propertyKey , value , receiver ) を返す。ownDesc をPropertyDescriptor { [[Value]] : undefined , [[Writable]] : true , [[Enumerable]] : true , [[Configurable]] : true }に設定する。IsDataDescriptor (ownDesc )がtrue なら、ownDesc .[[Writable]] がfalse なら、false を返す。receiver がObjectでないなら、false を返す。existingDesc を ? receiver .[[GetOwnProperty]] (propertyKey ) とする。existingDesc がundefined なら、Assert : receiver は現在property propertyKey を持たない。? CreateDataProperty (receiver , propertyKey , value )を返す。 IsAccessorDescriptor (existingDesc )がtrue なら、false を返す。existingDesc .[[Writable]] がfalse なら、false を返す。valueDesc をPropertyDescriptor { [[Value]] : value }とする。? receiver .[[DefineOwnProperty]] (propertyKey , valueDesc ) を返す。 Assert : IsAccessorDescriptor (ownDesc )はtrue である。setter をownDesc .[[Set]] とする。setter がundefined なら、false を返す。? Call (setter , receiver , « value »)を実行する。 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:
? 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:
propertyDesc を ? obj .[[GetOwnProperty]] (propertyKey ) とする。propertyDesc がundefined なら、true を返す。propertyDesc .[[Configurable]] がtrue なら、obj からpropertyKey という名前のown propertyを削除する。true を返す。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:
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:
keys を新しい空のList とする。array index であるようなobj の各own property key propertyKey について、ascending numeric index orderで、以下を行うpropertyKey をkeys へappendする。Stringであり、array index でないようなobj の各own property key propertyKey について、property creationのascending chronological orderで、以下を行うpropertyKey をkeys へappendする。 Symbolであるようなobj の各own property key propertyKey について、property creationのascending chronological orderで、以下を行うpropertyKey をkeys へappendする。 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:
internalSlotsList を« [[Prototype]] , [[Extensible]] »とする。additionalInternalSlotsList が存在するなら、internalSlotsList をinternalSlotsList とadditionalInternalSlotsList のlist-concatenation に設定する。obj をMakeBasicObject (internalSlotsList )とする。obj .[[Prototype]] をproto に設定する。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:
Assert : intrinsicDefaultProto はこの仕様におけるintrinsic objectの名前である。対応するobjectは、objectの[[Prototype]] 値として使用されることを意図したintrinsicでなければならない。proto を ? GetPrototypeFromConstructor (ctor , intrinsicDefaultProto ) とする。internalSlotsList が存在するなら、slots をinternalSlotsList とする。そうでなければ、slots を新しい空のList とする。 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:
Assert : intrinsicDefaultProto はこの仕様におけるintrinsic objectの名前である。対応するobjectは、objectの[[Prototype]] 値として使用されることを意図したintrinsicでなければならない。proto を ? Get (ctor , "prototype" ) とする。proto がObjectでないなら、realm を ? GetFunctionRealm (ctor ) とする。proto をintrinsicDefaultProto という名前のrealm のintrinsic objectに設定する。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:
obj がObjectでないなら、TypeError 例外をthrowする。obj がinternalSlot internal slotを持たないなら、TypeError 例外をthrowする。unused を返す。
10.2 ECMAScript関数オブジェクト
ECMAScript function objects は、lexical environmentで閉じ込められたparameterized ECMAScript codeをカプセル化し、そのコードの動的評価をサポートします。ECMAScript function object はordinary object であり、他のordinary objects と同じinternal slotsおよび同じinternal methodsを持ちます。ECMAScript function object のコードは、strict mode code (11.2.2 )またはnon-strict code のいずれかであり得ます。コードがstrict mode code であるECMAScript function object はstrict function と呼ばれます。コードがstrict mode code でないものはnon-strict function と呼ばれます。
[[Extensible]] および[[Prototype]] に加えて、ECMAScript function objects はTable 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 またはnull のthis 値がglobal object への参照として解釈され、その他のthis 値はまずToObject に渡されることを意味します。
[[Strict]]
Boolean
これがstrict function である場合はtrue 、non-strict function である場合はfalse 。
[[HomeObject]]
Objectまたはundefined
functionがsuperを使用する場合、これは、その[[GetPrototypeOf]] がsuper property lookupsを開始するobjectを提供するobjectです。
[[SourceText]]
Unicode code pointsのsequence
functionを定義するsource text 。
[[Fields]]
ClassFieldDefinition Records のList
functionがclassである場合、これはclassのnon-static fieldsおよび対応するinitializersを表すRecords のlistです。
[[PrivateMethods]]
PrivateElements のList
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:
callerContext をrunning execution context とする。calleeContext をPrepareForOrdinaryCall (func , undefined )とする。Assert : calleeContext は現在running execution context である。func .[[IsClassConstructor]] がtrue なら、error を新しく作成されたTypeError objectとする。NOTE : error は、func に関連付けられたRealm Record を伴うcalleeContext 内で作成される。calleeContext をexecution context stack から削除し、callerContext をrunning execution context として復元する。error をthrowする。OrdinaryCallBindThis (func , calleeContext , thisArg )を実行する。result をCompletion (OrdinaryCallEvaluateBody (func , argList ))とする。calleeContext をexecution context stack から削除し、callerContext をrunning execution context として復元する。result がreturn completion なら、result .[[Value]] を返す。Assert : result はthrow completion である。? result を返す。
Note
ステップ7 でcalleeContext がexecution 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:
callerContext をrunning execution context とする。calleeContext を新しいECMAScript code execution context とする。calleeContext のFunctionをfunc に設定する。calleeRealm をfunc .[[Realm]] とする。calleeContext のRealm をcalleeRealm に設定する。calleeContext のScriptOrModuleをfunc .[[ScriptOrModule]] に設定する。localEnv をNewFunctionEnvironment (func , newTarget )とする。calleeContext のLexicalEnvironmentをlocalEnv に設定する。calleeContext のVariableEnvironmentをlocalEnv に設定する。calleeContext のPrivateEnvironmentをfunc .[[PrivateEnvironment]] に設定する。callerContext がまだsuspendedでないなら、callerContext をsuspendする。calleeContext をexecution context stack へpushする;calleeContext は現在running execution context である。NOTE : この時点以降に生成される任意のexception objectsはcalleeRealm に関連付けられる。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:
thisMode をfunc .[[ThisMode]] とする。thisMode がlexical なら、unused を返す。calleeRealm をfunc .[[Realm]] とする。localEnv をcalleeContext のLexicalEnvironmentとする。thisMode がstrict なら、thisValue をthisArg とする。そうでなければ、thisArg がundefined またはnull のいずれかなら、globalEnv をcalleeRealm .[[GlobalEnv]] とする。Assert : globalEnv はGlobal Environment Record である。thisValue をglobalEnv .[[GlobalThisValue]] とする。そうでなければ、thisValue を ! ToObject (thisArg ) とする。NOTE : ToObject はcalleeRealm を使用してwrapper objectsを生成する。 Assert : localEnv はFunction Environment Record である。Assert : 次のstepはabrupt completion を返すことはない。なぜならlocalEnv .[[ThisBindingStatus]] はinitialized でないからである。! BindThisValue (localEnv , thisValue )を実行する。 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
引数func およびargList を伴うFunctionBody のEvaluateFunctionBody を ? で返す。
ConciseBody : ExpressionBody
引数func およびargList を伴うConciseBody のEvaluateConciseBody を ? で返す。
GeneratorBody : FunctionBody
引数func およびargList を伴うGeneratorBody のEvaluateGeneratorBody を ? で返す。
AsyncGeneratorBody : FunctionBody
引数func およびargList を伴うAsyncGeneratorBody のEvaluateAsyncGeneratorBody を ? で返す。
AsyncFunctionBody : FunctionBody
引数func およびargList を伴うAsyncFunctionBody のEvaluateAsyncFunctionBody を ? で返す。
AsyncConciseBody : ExpressionBody
引数func およびargList を伴うAsyncConciseBody のEvaluateAsyncConciseBody を ? で返す。
Initializer :
=
AssignmentExpression
Assert : argList は空である。Assert : func .[[ClassFieldInitializerName]] はempty でない。IsAnonymousFunctionDefinition (AssignmentExpression )がtrue なら、value を、引数func .[[ClassFieldInitializerName]] を伴うInitializer のNamedEvaluation の ? 結果とする。そうでなければ、rhs をAssignmentExpression のEvaluation の ? 結果とする。value を ? GetValue (rhs ) とする。 ReturnCompletion (value )を返す。
Note
field initializersはfunction boundaryを構成しますが、FunctionDeclarationInstantiation の呼び出しには観測可能な効果がないため省略されます。
ClassStaticBlockBody : ClassStaticBlockStatementList
Assert : argList は空である。引数func を伴うClassStaticBlockBody のEvaluateClassStaticBlockBody を ? で返す。
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:
引数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:
callerContext をrunning execution context とする。kind をfunc .[[ConstructorKind]] とする。kind がbase なら、thisArg を ? OrdinaryCreateFromConstructor (newTarget , "%Object.prototype%" ) とする。calleeContext をPrepareForOrdinaryCall (func , newTarget )とする。Assert : calleeContext は現在running execution context である。kind がbase なら、OrdinaryCallBindThis (func , calleeContext , thisArg )を実行する。initializeResult をCompletion (InitializeInstanceElements (thisArg , func ))とする。initializeResult がabrupt completion なら、calleeContext をexecution context stack から削除し、callerContext をrunning execution context として復元する。? initializeResult を返す。 ctorEnv をcalleeContext のLexicalEnvironmentとする。result をCompletion (OrdinaryCallEvaluateBody (func , argList ))とする。calleeContext をexecution context stack から削除し、callerContext をrunning execution context として復元する。result がthrow completion なら、? result を返す。 Assert : result はreturn completion である。result .[[Value]] がObjectなら、result .[[Value]] を返す。kind がbase なら、thisArg を返す。result .[[Value]] がundefined でないなら、TypeError 例外をthrowする。thisBinding を ? ctorEnv .GetThisBinding () とする。Assert : thisBinding はObjectである。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:
internalSlotsList をTable 26 に列挙されるinternal slotsとする。func をOrdinaryObjectCreate (proto , internalSlotsList )とする。func .[[Call]] を10.2.1 で指定される定義に設定する。func .[[SourceText]] をsourceText に設定する。func .[[FormalParameters]] をparamList に設定する。func .[[ECMAScriptCode]] をbody に設定する。strict をIsStrict (body )とする。func .[[Strict]] をstrict に設定する。thisMode がlexical-this なら、func .[[ThisMode]] をlexical に設定する。そうでなく、strict がtrue なら、func .[[ThisMode]] をstrict に設定する。 そうでなければ、func .[[ThisMode]] をglobal に設定する。 func .[[IsClassConstructor]] をfalse に設定する。func .[[Environment]] をenvRecord に設定する。func .[[PrivateEnvironment]] をprivateEnv に設定する。func .[[ScriptOrModule]] をGetActiveScriptOrModule ()に設定する。func .[[Realm]] をcurrent Realm Record に設定する。func .[[HomeObject]] をundefined に設定する。func .[[Fields]] を新しい空のList に設定する。func .[[PrivateMethods]] を新しい空のList に設定する。func .[[ClassFieldInitializerName]] をempty に設定する。length をparamList のExpectedArgumentCount とする。SetFunctionLength (func , length )を実行する。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:
Assert : realm .[[Intrinsics]] .[[%ThrowTypeError% ]]は存在し、初期化済みである。thrower をrealm .[[Intrinsics]] .[[%ThrowTypeError% ]]とする。! DefinePropertyOrThrow (func , "caller" , PropertyDescriptor { [[Get]] : thrower , [[Set]] : thrower , [[Enumerable]] : false , [[Configurable]] : true })を実行する。 ! DefinePropertyOrThrow (func , "arguments" , PropertyDescriptor { [[Get]] : thrower , [[Set]] : thrower , [[Enumerable]] : false , [[Configurable]] : true })を実行する。 unused を返す。
10.2.4.1 %ThrowTypeError% ( )
このfunctionは%ThrowTypeError% intrinsic objectです。
これは、realm ごとに1回定義されるanonymous built-in function object です。
呼び出されたとき、次のstepsを実行します:
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 . これはfunc をconstructor へ変換します。 It performs the following steps when called:
func がECMAScript function object なら、Assert : IsConstructor (func )はfalse である。Assert : func はextensible objectであり、"prototype" own propertyを持たない。func .[[Construct]] を10.2.2 で指定される定義に設定する。そうでなければ、func .[[Construct]] を10.3.2 で指定される定義に設定する。 func .[[ConstructorKind]] をbase に設定する。writableProto が存在しないなら、writableProto をtrue に設定する。proto が存在しないなら、proto をOrdinaryObjectCreate (%Object.prototype% )に設定する。! DefinePropertyOrThrow (proto , "constructor" , PropertyDescriptor { [[Value]] : func , [[Writable]] : writableProto , [[Enumerable]] : false , [[Configurable]] : true })を実行する。 ! DefinePropertyOrThrow (func , "prototype" , PropertyDescriptor { [[Value]] : proto , [[Writable]] : writableProto , [[Enumerable]] : false , [[Configurable]] : false })を実行する。 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:
Assert : func .[[IsClassConstructor]] はfalse である。func .[[IsClassConstructor]] をtrue に設定する。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:
Assert : homeObj はordinary object である。func .[[HomeObject]] をhomeObj に設定する。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:
Assert : homeObj はordinaryかつextensible objectである。name がPrivate Name なら、PrivateElement { [[Key]] : name , [[Kind]] : method , [[Value]] : closure }を返す。propertyDesc をPropertyDescriptor { [[Value]] : closure , [[Writable]] : true , [[Enumerable]] : enumerable , [[Configurable]] : true }とする。? DefinePropertyOrThrow (homeObj , name , propertyDesc )を実行する。 NOTE : DefinePropertyOrThrow がabrupt completion を返すのは、name が"prototype" であるclass static methodを定義しようとする場合だけである。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:
Assert : func はextensible objectであり、"name" own propertyを持たない。name がSymbolなら、description をname .[[Description]] とする。description がundefined なら、name を空のStringに設定する。そうでなければ、name を"[" 、description 、および"]" のstring-concatenation に設定する。 そうでなく、name がPrivate Name なら、name をname .[[Description]] に設定する。 func が[[InitialName]] internal slotを持つなら、func .[[InitialName]] をname に設定する。prefix が存在するなら、prefixedName を、prefix 、code unit 0x0020 (SPACE)、およびname のstring-concatenation とする。func が[[InitialName]] internal slotを持つなら、NOTE : 次のstepの選択は、このAbstract Operationが呼び出されるたびに独立して行われる。func .[[InitialName]] をname またはprefixedName のいずれかのimplementation-defined choiceに設定する。name をprefixedName に設定する。! DefinePropertyOrThrow (func , "name" , PropertyDescriptor { [[Value]] : name , [[Writable]] : false , [[Enumerable]] : false , [[Configurable]] : true })を実行する。 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:
Assert : func はextensible objectであり、"length" own propertyを持たない。! DefinePropertyOrThrow (func , "length" , PropertyDescriptor { [[Value]] : 𝔽 (length ), [[Writable]] : false , [[Enumerable]] : false , [[Configurable]] : true })を実行する。 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を実行します:
実行中の実行コンテキストをcalleeContext とする。 func .[[ECMAScriptCode]] をcode とする。func .[[Strict]] をstrict とする。func .[[FormalParameters]] をformals とする。formals のBoundNames をparamNames とする。paramNames に重複するエントリがある場合、hasDuplicates をtrue とする。そうでなければ、hasDuplicates をfalse とする。formals のIsSimpleParameterList をsimpleParamList とする。formals のContainsExpression をhasParamExprs とする。code のVarDeclaredNames をvariableNames とする。code のVarScopedDeclarations をvariableDecls とする。code のLexicallyDeclaredNames をlexicalNames とする。funcNames を新しい空のList とする。funcsToInitialize を新しい空のList とする。variableDecls の各要素variableDecl について、List の逆順で、次を行う。variableDecl がVariableDeclaration 、ForBinding 、BindingIdentifier のいずれでもない場合、Assert : variableDecl は、FunctionDeclaration 、GeneratorDeclaration 、AsyncFunctionDeclaration 、またはAsyncGeneratorDeclaration のいずれかである。variableDecl のBoundNames の唯一の要素をfuncName とする。funcNames がfuncName を含まない場合、funcName をfuncNames の最初の要素として挿入する。NOTE : 同じ名前に対して複数の関数宣言がある場合、最後の宣言が使用される。variableDecl をfuncsToInitialize の最初の要素として挿入する。argumentsObjNeeded をtrue とする。func .[[ThisMode]] がlexical である場合、NOTE : アロー関数はargumentsオブジェクトを持たない。argumentsObjNeeded をfalse に設定する。そうでなく、paramNames が"arguments" を含む場合、argumentsObjNeeded をfalse に設定する。 そうでなく、hasParamExprs がfalse である場合、funcNames が"arguments" を含む、またはlexicalNames が"arguments" を含む場合、argumentsObjNeeded をfalse に設定する。 strict がtrue である、またはhasParamExprs がfalse である場合、NOTE : パラメータには単一のEnvironment Record だけが必要である。これは、strict modeコード内のevalへの呼び出しが、evalの外側で可視となる新しい束縛を作成できないためである。calleeContext のLexicalEnvironmentをenvRecord とする。そうでなければ、NOTE : 仮引数リスト内のdirect eval 呼び出しによって作成された束縛が、パラメータが宣言される環境の外側にあることを保証するため、別個のEnvironment Record が必要である。calleeContext のLexicalEnvironmentをcalleeEnv とする。NewDeclarativeEnvironment (calleeEnv )をenvRecord とする。Assert : calleeContext のVariableEnvironmentとcalleeEnv は同じEnvironment Record である。calleeContext のLexicalEnvironmentをenvRecord に設定する。 paramNames の各String paramName について、次を行う。! envRecord .HasBinding (paramName )をalreadyDeclared とする。 NOTE : Early error により、重複するパラメータ名は、パラメータ既定値またはrestパラメータを持たない非strict関数でのみ発生できることが保証される。alreadyDeclared がfalse である場合、! envRecord .CreateMutableBinding (paramName , false )を実行する。 hasDuplicates がtrue である場合、! envRecord .InitializeBinding (paramName , undefined )を実行する。 argumentsObjNeeded がtrue である場合、strict がtrue である、またはsimpleParamList がfalse である場合、CreateUnmappedArgumentsObject (argList )をargumentsObj とする。そうでなければ、NOTE : マップされたargumentsオブジェクトは、restパラメータ、パラメータ既定値初期化子、または分割代入パラメータを持たない非strict関数に対してのみ提供される。CreateMappedArgumentsObject (func , formals , argList , envRecord )をargumentsObj とする。 strict がtrue である場合、! envRecord .CreateImmutableBinding ("arguments" , false )を実行する。 NOTE : strict modeコードでは、この束縛に代入しようとすることがEarly error によって防止されるため、その可変性は観測できない。そうでなければ、! envRecord .CreateMutableBinding ("arguments" , false )を実行する。 ! envRecord .InitializeBinding ("arguments" , argumentsObj )を実行する。 paramNames と« "arguments" »のlist-concatenation をparamBindings とする。そうでなければ、paramNames をparamBindings とする。 CreateListIteratorRecord (argList )をiteratorRecord とする。hasDuplicates がtrue である場合、usedEnv をundefined とする。そうでなければ、envRecord をusedEnv とする。 NOTE : 次のステップはReturnCompletion を返すことができない。これは、式位置でそのようなcompletionが発生する唯一の方法はYieldExpression の使用によるものであり、これは15.5.1 および15.6.1 のEarly Error規則により、パラメータリストでは禁止されているためである。iteratorRecord およびusedEnv を引数として、formals のIteratorBindingInitialization を実行する。hasParamExprs がfalse である場合、NOTE : パラメータとトップレベルのvarには単一のEnvironment Record だけが必要である。List paramBindings のコピーをinstantiatedVariableNames とする。variableNames の各要素name について、次を行う。instantiatedVariableNames がname を含まない場合、name をinstantiatedVariableNames に追加する。! envRecord .CreateMutableBinding (name , false )を実行する。 ! envRecord .InitializeBinding (name , undefined )を実行する。 envRecord をvariableEnv とする。そうでなければ、NOTE : 仮引数リスト内の式によって作成されたクロージャが、関数本体内の宣言を可視にしないことを保証するため、別個のEnvironment Record が必要である。NewDeclarativeEnvironment (envRecord )をvariableEnv とする。calleeContext のVariableEnvironmentをvariableEnv に設定する。instantiatedVariableNames を新しい空のList とする。variableNames の各要素name について、次を行う。instantiatedVariableNames がname を含まない場合、name をinstantiatedVariableNames に追加する。! variableEnv .CreateMutableBinding (name , false )を実行する。 paramBindings がname を含まない、またはfuncNames がname を含む場合、initialValue をundefined とする。そうでなければ、! envRecord .GetBindingValue (name , false )をinitialValue とする。 ! variableEnv .InitializeBinding (name , initialValue )を実行する。 NOTE : 仮引数と同じ名前を持つvarは、最初は対応する初期化済みパラメータと同じ値を持つ。 strict がtrue である場合、variableEnv をlexicalEnv とする。そうでなければ、ホスト がWebブラウザである、またはその他の形でBlock-Level Function Declarations Web Legacy Compatibility Semantics をサポートする場合、code Contains x がtrue であるような任意のBlock 、CaseClause 、またはDefaultClause x のStatementList に直接含まれる各FunctionDeclaration funcDecl について、次を行う。funcDecl のBindingIdentifier のStringValue をfuncName とする。FunctionDeclaration funcDecl を、funcName をBindingIdentifier として持つVariableStatement に置き換えても、func に対してEarly Errorsが発生せず、かつparamNames がfuncName を含まない場合、NOTE : funcName に対するvar束縛は、それがVarDeclaredName、仮引数の名前、または別のFunctionDeclaration のいずれでもない場合にのみ、ここでインスタンス化される。instantiatedVariableNames がfuncName を含まず、かつfuncName が"arguments" でない場合、! variableEnv .CreateMutableBinding (funcName , false )を実行する。 ! variableEnv .InitializeBinding (funcName , undefined )を実行する。 funcName をinstantiatedVariableNames に追加する。FunctionDeclaration funcDecl が評価されるとき、15.2.6 で提供されるFunctionDeclaration Evaluation アルゴリズムの代わりに、次のステップを実行する。実行中の実行コンテキストのVariableEnvironmentをfuncEnv とする。 実行中の実行コンテキストのLexicalEnvironmentをblockEnv とする。 ! blockEnv .GetBindingValue (funcName , false )をfuncObj とする。 ! funcEnv .SetMutableBinding (funcName , funcObj , false )を実行する。 unused を返す。NewDeclarativeEnvironment (variableEnv )をlexicalEnv とする。NOTE : 非strict関数は、トップレベルのlexical宣言に別個のEnvironment Record を使用する。これにより、direct eval は、evalコードによって導入されたvar scoped宣言が、既存のトップレベルのlexically scoped宣言と競合するかどうかを判断できる。strict関数では、strict direct eval が常にすべての宣言を新しいEnvironment Record に配置するため、これは不要である。 calleeContext のLexicalEnvironmentをlexicalEnv に設定する。code のLexicallyScopedDeclarations をlexicalDecls とする。lexicalDecls の各要素lexicalDecl について、次を行う。NOTE : lexically declared nameは、関数/ジェネレータ宣言、仮引数、またはvar名と同じにすることはできない。Lexically declared nameはここでインスタンス化されるだけで、初期化はされない。lexicalDecl のBoundNames の各要素name について、次を行う。lexicalDecl のIsConstantDeclaration がtrue である場合、! lexicalEnv .CreateImmutableBinding (name , true )を実行する。 そうでなければ、! lexicalEnv .CreateMutableBinding (name , false )を実行する。 calleeContext のPrivateEnvironmentをprivateEnv とする。funcsToInitialize の各Parse Node funcDecl について、次を行う。funcDecl のBoundNames の唯一の要素をfuncName とする。lexicalEnv およびprivateEnv を引数として、funcDecl のInstantiateFunctionObject をfuncObj とする。! variableEnv .SetMutableBinding (funcName , funcObj , false )を実行する。 unused を返す。
10.3 Built-in Function Objects
built-in function object はordinary object です;10.1 に定められたordinary objects の要件を満たさなければなりません。
すべてのordinary object に要求されるinternal slots(10.1 を参照)に加えて、built-in function object は次のinternal slotsも持たなければなりません:
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:
? 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:
result を ? BuiltinCallOrConstruct (func , uninitialized , argList , newTarget ) とする。Assert : result はObjectである。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:
callerContext をrunning execution context とする。callerContext がまだsuspendedでないなら、callerContext をsuspendする。calleeContext を新しいexecution context とする。calleeContext のFunctionをfunc に設定する。calleeRealm をfunc .[[Realm]] とする。calleeContext のRealm をcalleeRealm に設定する。calleeContext のScriptOrModuleをnull に設定する。calleeContext の任意の必要なimplementation-defined initializationを実行する。calleeContext をexecution context stack へpushする;calleeContext は現在running execution context である。func .[[Async]] がtrue なら、promiseCapability を ! NewPromiseCapability (%Promise% ) とする。resultsClosure を、func 、thisArg 、argList 、およびnewTarget をcaptureし、呼び出されたときに次のstepsを実行する、parametersを持たない新しいAbstract Closure とする:result を、func の仕様に適合する方法でfunc を評価した結果 であるCompletion Record とする。thisArg がuninitialized である場合、this 値はuninitializedである;そうでなければthisArg がthis 値を提供する。argList はnamed parametersを提供する。newTarget はNewTarget値を提供する。NOTE : func がこの文書内で定義されている場合、“func の仕様”とは、algorithm stepsまたはその他の手段によってそれに対して指定されたbehaviourである。Completion (result )を返す。AsyncFunctionStart (promiseCapability , resultsClosure )を実行する。calleeContext をexecution context stack から削除し、callerContext をrunning execution context として復元する。promiseCapability .[[Promise]] を返す。result を、func の仕様に適合する方法でfunc を評価した結果 であるCompletion Record とする。thisArg がuninitialized である場合、this 値はuninitializedである;そうでなければthisArg がthis 値を提供する。argList はnamed parametersを提供する。newTarget はNewTarget値を提供する。NOTE : func がこの文書内で定義されている場合、“func の仕様”とは、algorithm stepsまたはその他の手段によってそれに対して指定されたbehaviourである。calleeContext をexecution context stack から削除し、callerContext をrunning execution context として復元する。? result を返す。
Note
calleeContext がexecution 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:
realm が存在しないなら、realm をcurrent Realm Record に設定する。proto が存在しないなら、proto をrealm .[[Intrinsics]] .[[%Function.prototype% ]]に設定する。async が存在しないなら、async をfalse に設定する。internalSlotsList を、10.3 がこれから作成されるbuilt-in function object に要求するすべてのinternal slotsの名前を含むList とする。additionalInternalSlotsList の要素をinternalSlotsList へappendする。func を、呼び出されたときに、提供されたargumentsをbehaviour によって指定される対応parametersの値として使用して、behaviour によって記述されるactionを実行する新しいbuilt-in function object とする。新しいfunction object は、internalSlotsList の要素を名前とするinternal slots、および[[InitialName]] internal slotを持つ。func .[[Async]] をasync に設定する。func .[[Prototype]] をproto に設定する。func .[[Extensible]] をtrue に設定する。func .[[Realm]] をrealm に設定する。func .[[InitialName]] をnull に設定する。SetFunctionLength (func , length )を実行する。prefix が存在しないなら、SetFunctionName (func , name )を実行する。そうでなければ、SetFunctionName (func , name , prefix )を実行する。 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:
target をfunc .[[BoundTargetFunction]] とする。boundThis をfunc .[[BoundThis]] とする。boundArgs をfunc .[[BoundArguments]] とする。args をboundArgs とargList のlist-concatenation とする。? 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:
target をfunc .[[BoundTargetFunction]] とする。Assert : IsConstructor (target )はtrue である。boundArgs をfunc .[[BoundArguments]] とする。args をboundArgs とargList のlist-concatenation とする。SameValue (func , newTarget )がtrue なら、newTarget をtarget に設定する。? 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:
proto を ? targetFunc .[[GetPrototypeOf]] () とする。internalSlotsList を、« [[Prototype]] , [[Extensible]] »とTable 27 に列挙されるinternal slotsのlist-concatenation とする。obj をMakeBasicObject (internalSlotsList )とする。obj .[[Prototype]] をproto に設定する。obj .[[Call]] を10.4.1.1 で指定されるように設定する。IsConstructor (targetFunc )がtrue なら、obj .[[Construct]] を10.4.1.2 で指定されるように設定する。obj .[[BoundTargetFunction]] をtargetFunc に設定する。obj .[[BoundThis]] をboundThis に設定する。obj .[[BoundArguments]] をboundArgs に設定する。obj を返す。
10.4.2 Array Exotic Objects
Arrayは、array index property keys を特別に扱うexotic object です(6.1.7 を参照)。property name がarray 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:
propertyKey が"length" なら、? ArraySetLength (array , propertyDesc )を返す。propertyKey がarray index なら、lengthDesc をOrdinaryGetOwnProperty (array , "length" )とする。Assert : lengthDesc はundefined でない。Assert : IsDataDescriptor (lengthDesc )はtrue である。Assert : lengthDesc .[[Configurable]] はfalse である。length をlengthDesc .[[Value]] とする。Assert : length は非負整数のNumberである。index を ! ToUint32 (propertyKey ) とする。index ≥ length かつlengthDesc .[[Writable]] がfalse なら、false を返す。succeeded を ! OrdinaryDefineOwnProperty (array , propertyKey , propertyDesc ) とする。succeeded がfalse なら、false を返す。index ≥ length なら、lengthDesc .[[Value]] をindex + 1 𝔽 に設定する。succeeded を ! OrdinaryDefineOwnProperty (array , "length" , lengthDesc ) に設定する。Assert : succeeded はtrue である。true を返す。? 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:
length > 232 - 1なら、RangeError 例外をthrowする。proto が存在しないなら、proto を%Array.prototype% に設定する。array をMakeBasicObject (« [[Prototype]] , [[Extensible]] »)とする。array .[[Prototype]] をproto に設定する。array .[[DefineOwnProperty]] を10.4.2.1 で指定されるように設定する。! OrdinaryDefineOwnProperty (array , "length" , PropertyDescriptor { [[Value]] : 𝔽 (length ), [[Writable]] : true , [[Enumerable]] : false , [[Configurable]] : false })を実行する。 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:
isArray を ? IsArray (originalArray ) とする。isArray がfalse なら、? ArrayCreate (length )を返す。ctor を ? Get (originalArray , "constructor" ) とする。IsConstructor (ctor )がtrue なら、thisRealm をcurrent Realm Record とする。ctorRealm を ? GetFunctionRealm (ctor ) とする。thisRealm とctorRealm が同じRealm Record でないなら、SameValue (ctor , ctorRealm .[[Intrinsics]] .[[%Array% ]])がtrue なら、ctor をundefined に設定する。ctor がObjectなら、ctor を ? Get (ctor , %Symbol.species% ) に設定する。ctor がnull なら、ctor をundefined に設定する。ctor がundefined なら、? ArrayCreate (length )を返す。IsConstructor (ctor )がfalse なら、TypeError 例外をthrowする。? Construct (ctor , « 𝔽 (length ) »)を返す。
Note
originalArray がrunning execution context のrealm ではないrealm のstandard built-in Array constructor を使用して作成された場合、新しいArrayはrunning execution context のrealm を使用して作成されます。これは、現在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:
propertyDesc が[[Value]] fieldを持たないなら、! OrdinaryDefineOwnProperty (array , "length" , propertyDesc )を返す。 newLengthDesc をpropertyDesc のcopyとする。newLength を ? ToUint32 (propertyDesc .[[Value]] ) とする。numberLength を ? ToNumber (propertyDesc .[[Value]] ) とする。SameValueZero (newLength , numberLength )がfalse なら、RangeError 例外をthrowする。newLengthDesc .[[Value]] をnewLength に設定する。oldLengthDesc をOrdinaryGetOwnProperty (array , "length" )とする。Assert : oldLengthDesc はundefined でない。Assert : IsDataDescriptor (oldLengthDesc )はtrue である。Assert : oldLengthDesc .[[Configurable]] はfalse である。oldLength をoldLengthDesc .[[Value]] とする。newLength ≥ oldLength なら、! OrdinaryDefineOwnProperty (array , "length" , newLengthDesc )を返す。 oldLengthDesc .[[Writable]] がfalse なら、false を返す。newLengthDesc が[[Writable]] fieldを持たない、またはnewLengthDesc .[[Writable]] がtrue なら、newWritable をtrue とする。そうでなければ、NOTE : 任意のelementsを削除できない場合に備えて、[[Writable]] 属性をfalse に設定することはdeferされる。newWritable をfalse とする。newLengthDesc .[[Writable]] をtrue に設定する。 succeeded を ! OrdinaryDefineOwnProperty (array , "length" , newLengthDesc ) とする。succeeded がfalse なら、false を返す。array index であり、! ToUint32 (propertyKey ) ≥ newLength であるようなarray の各own property key propertyKey について、descending numeric index orderで、以下を行うdeleteSucceeded を ! array .[[Delete]] (propertyKey ) とする。deleteSucceeded がfalse なら、newLengthDesc .[[Value]] を ! ToUint32 (propertyKey ) + 1 𝔽 に設定する。newWritable がfalse なら、newLengthDesc .[[Writable]] をfalse に設定する。! OrdinaryDefineOwnProperty (array , "length" , newLengthDesc )を実行する。 false を返す。newWritable がfalse なら、succeeded を ! OrdinaryDefineOwnProperty (array , "length" , PropertyDescriptor { [[Writable]] : false }) に設定する。Assert : succeeded はtrue である。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 objects はordinary 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:
propertyDesc をOrdinaryGetOwnProperty (string , propertyKey )とする。propertyDesc がundefined でないなら、propertyDesc を返す。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:
stringDesc をStringGetOwnProperty (string , propertyKey )とする。stringDesc がundefined でないなら、extensible をstring .[[Extensible]] とする。IsCompatiblePropertyDescriptor (extensible , propertyDesc , stringDesc )を返す。! 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:
keys を新しい空のList とする。string をobj .[[StringData]] とする。Assert : string はStringである。length をstring のlengthとする。0 ≤ i < length である各integer i について、昇順で、以下を行う! ToString (𝔽 (i ))をkeys へappendする。 array index であり、! ToIntegerOrInfinity (propertyKey ) ≥ length であるようなobj の各own property key propertyKey について、ascending numeric index orderで、以下を行うpropertyKey をkeys へappendする。Stringであり、array index でないようなobj の各own property key propertyKey について、property creationのascending chronological orderで、以下を行うpropertyKey をkeys へappendする。 Symbolであるようなobj の各own property key propertyKey について、property creationのascending chronological orderで、以下を行うpropertyKey をkeys へappendする。 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:
string をMakeBasicObject (« [[Prototype]] , [[Extensible]] , [[StringData]] »)とする。string .[[Prototype]] をproto に設定する。string .[[StringData]] をvalue に設定する。string .[[GetOwnProperty]] を10.4.3.1 で指定されるように設定する。string .[[DefineOwnProperty]] を10.4.3.2 で指定されるように設定する。string .[[OwnPropertyKeys]] を10.4.3.3 で指定されるように設定する。length をvalue のlengthとする。! DefinePropertyOrThrow (string , "length" , PropertyDescriptor { [[Value]] : 𝔽 (length ), [[Writable]] : false , [[Enumerable]] : false , [[Configurable]] : false })を実行する。 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:
propertyKey がStringでないなら、undefined を返す。numericIndex をCanonicalNumericIndexString (propertyKey )とする。numericIndex がintegral Number でないなら、undefined を返す。numericIndex が-0 𝔽 またはnumericIndex < -0 𝔽 なら、undefined を返す。stringData をstring .[[StringData]] とする。Assert : stringData はStringである。length をstringData のlengthとする。ℝ (numericIndex ) ≥ length なら、undefined を返す。resultString をℝ (numericIndex )からℝ (numericIndex ) + 1までのstringData のsubstring とする。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
Arguments exotic objects はordinary objects と同じinternal slotsを持ちます。また、[[ParameterMap]] internal slotも持ちます。Ordinary arguments objectsも[[ParameterMap]] internal slotを持ち、その値は常にundefined です。ordinary argument objectsについては、[[ParameterMap]] internal slotはObject.prototype.toString(20.1.3.6 )がそれらをそのようなものとして識別するためにのみ使用されます。
Note 2
numeric name valuesが対応するfunction object のformal parametersの数より小さいarguments exotic object のinteger-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:
propertyDesc をOrdinaryGetOwnProperty (args , propertyKey )とする。propertyDesc がundefined なら、undefined を返す。map をargs .[[ParameterMap]] とする。isMapped を ! HasOwnProperty (map , propertyKey ) とする。isMapped がtrue なら、propertyDesc .[[Value]] を ! Get (map , propertyKey ) に設定する。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:
map をargs .[[ParameterMap]] とする。isMapped を ! HasOwnProperty (map , propertyKey ) とする。newArgDesc をpropertyDesc とする。isMapped がtrue であり、かつIsDataDescriptor (propertyDesc )がtrue なら、propertyDesc が[[Value]] fieldを持たず、propertyDesc が[[Writable]] fieldを持ち、かつpropertyDesc .[[Writable]] がfalse なら、newArgDesc をpropertyDesc のcopyに設定する。newArgDesc .[[Value]] を ! Get (map , propertyKey ) に設定する。allowed を ! OrdinaryDefineOwnProperty (args , propertyKey , newArgDesc ) とする。allowed がfalse なら、false を返す。isMapped がtrue なら、IsAccessorDescriptor (propertyDesc )がtrue なら、! map .[[Delete]] (propertyKey )を実行する。 そうでなければ、propertyDesc が[[Value]] fieldを持つなら、Assert : formal parameters mapped by arguments objectsは常にwritableであるため、次のSetは成功する。! Set (map , propertyKey , propertyDesc .[[Value]] , false )を実行する。 propertyDesc が[[Writable]] fieldを持ち、propertyDesc .[[Writable]] がfalse なら、! map .[[Delete]] (propertyKey )を実行する。 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:
map をargs .[[ParameterMap]] とする。isMapped を ! HasOwnProperty (map , propertyKey ) とする。isMapped がfalse なら、? OrdinaryGet (args , propertyKey , receiver )を返す。Assert : map はpropertyKey に対するformal parameter mappingを含む。! 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:
SameValue (args , receiver )がfalse なら、isMapped をfalse とする。そうでなければ、map をargs .[[ParameterMap]] とする。isMapped を ! HasOwnProperty (map , propertyKey ) とする。 isMapped がtrue なら、Assert : formal parameters mapped by arguments objectsは常にwritableであるため、次のSetは成功する。! Set (map , propertyKey , value , false )を実行する。 ? 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:
map をargs .[[ParameterMap]] とする。isMapped を ! HasOwnProperty (map , propertyKey ) とする。result を ? OrdinaryDelete (args , propertyKey ) とする。result がtrue かつisMapped がtrue なら、! map .[[Delete]] (propertyKey )を実行する。 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:
length をargList 内の要素数とする。obj をOrdinaryObjectCreate (%Object.prototype% , « [[ParameterMap]] »)とする。obj .[[ParameterMap]] をundefined に設定する。! DefinePropertyOrThrow (obj , "length" , PropertyDescriptor { [[Value]] : 𝔽 (length ), [[Writable]] : true , [[Enumerable]] : false , [[Configurable]] : true })を実行する。 index を0とする。index < length である間、繰り返すvalue をargList [index ]とする。! CreateDataPropertyOrThrow (obj , ! ToString (𝔽 (index )), value )を実行する。 index をindex + 1に設定する。! DefinePropertyOrThrow (obj , %Symbol.iterator% , PropertyDescriptor { [[Value]] : %Array.prototype.values%, [[Writable]] : true , [[Enumerable]] : false , [[Configurable]] : true })を実行する。 ! DefinePropertyOrThrow (obj , "callee" , PropertyDescriptor { [[Get]] : %ThrowTypeError% , [[Set]] : %ThrowTypeError% , [[Enumerable]] : false , [[Configurable]] : false })を実行する。 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:
Assert : formals はrest parameter、任意のbinding patterns、または任意のinitializersを含まない。duplicate identifiersを含む場合がある。length をargList 内の要素数とする。obj をMakeBasicObject (« [[Prototype]] , [[Extensible]] , [[ParameterMap]] »)とする。obj .[[GetOwnProperty]] を10.4.4.1 で指定されるように設定する。obj .[[DefineOwnProperty]] を10.4.4.2 で指定されるように設定する。obj .[[Get]] を10.4.4.3 で指定されるように設定する。obj .[[Set]] を10.4.4.4 で指定されるように設定する。obj .[[Delete]] を10.4.4.5 で指定されるように設定する。obj .[[Prototype]] を%Object.prototype% に設定する。map をOrdinaryObjectCreate (null )とする。obj .[[ParameterMap]] をmap に設定する。paramNames をformals のBoundNames とする。paramCount をparamNames 内の要素数とする。index を0とする。index < length である間、繰り返すvalue をargList [index ]とする。! CreateDataPropertyOrThrow (obj , ! ToString (𝔽 (index )), value )を実行する。 index をindex + 1に設定する。! DefinePropertyOrThrow (obj , "length" , PropertyDescriptor { [[Value]] : 𝔽 (length ), [[Writable]] : true , [[Enumerable]] : false , [[Configurable]] : true })を実行する。 mappedNames を新しい空のList とする。index をparamCount - 1に設定する。index ≥ 0である間、繰り返すname をparamNames [index ]とする。mappedNames がname を含まないなら、name をmappedNames へappendする。index < length なら、getter をMakeArgGetter (name , envRecord )とする。setter をMakeArgSetter (name , envRecord )とする。! map .[[DefineOwnProperty]] (! ToString (𝔽 (index )), PropertyDescriptor { [[Set]] : setter , [[Get]] : getter , [[Enumerable]] : false , [[Configurable]] : true })を実行する。 index をindex - 1に設定する。! DefinePropertyOrThrow (obj , %Symbol.iterator% , PropertyDescriptor { [[Value]] : %Array.prototype.values%, [[Writable]] : true , [[Enumerable]] : false , [[Configurable]] : true })を実行する。 ! DefinePropertyOrThrow (obj , "callee" , PropertyDescriptor { [[Value]] : func , [[Writable]] : true , [[Enumerable]] : false , [[Configurable]] : true })を実行する。 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:
getterClosure を、name およびenvRecord をcaptureし、呼び出されたときに次のstepsを実行する、parametersを持たない新しいAbstract Closure とする:NormalCompletion (! envRecord .GetBindingValue (name , false ))を返す。getter をCreateBuiltinFunction (getterClosure , 0, "" , « »)とする。NOTE : getter はECMAScriptコードから直接アクセス可能になることは決してない。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:
setterClosure を、name およびenvRecord をcaptureし、呼び出されたときに次のstepsを実行するparameters (value )を持つ新しいAbstract Closure とする:NormalCompletion (! envRecord .SetMutableBinding (name , value , false ))を返す。setter をCreateBuiltinFunction (setterClosure , 1, "" , « »)とする。NOTE : setter はECMAScriptコードから直接アクセス可能になることは決してない。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をTypedArrays のproperty keys として扱ってよいです。
TypedArrays はordinary 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:
NOTE : 6.1.7.3 で指定されるextensibility-related invariantsは、obj がpropertiesを得る(または失ってから再び得る)可能性があるとき、このmethodがtrue を返すことを許可しない。これは、そのunderlying bufferがresizeされるとき、integer index namesを持つpropertiesについて発生する場合がある。IsTypedArrayFixedLength (obj )がfalse なら、false を返す。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:
propertyKey がStringなら、numericIndex をCanonicalNumericIndexString (propertyKey )とする。numericIndex がundefined でないなら、value をTypedArrayGetElement (obj , numericIndex )とする。value がundefined なら、undefined を返す。PropertyDescriptor { [[Value]] : value , [[Writable]] : true , [[Enumerable]] : true , [[Configurable]] : true }を返す。 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:
propertyKey がStringなら、numericIndex をCanonicalNumericIndexString (propertyKey )とする。numericIndex がundefined でないなら、IsValidIntegerIndex (obj , numericIndex )を返す。? 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:
propertyKey がStringなら、numericIndex をCanonicalNumericIndexString (propertyKey )とする。numericIndex がundefined でないなら、IsValidIntegerIndex (obj , numericIndex )がfalse なら、false を返す。propertyDesc が[[Configurable]] fieldを持ち、propertyDesc .[[Configurable]] がfalse なら、false を返す。propertyDesc が[[Enumerable]] fieldを持ち、propertyDesc .[[Enumerable]] がfalse なら、false を返す。IsAccessorDescriptor (propertyDesc )がtrue なら、false を返す。propertyDesc が[[Writable]] fieldを持ち、propertyDesc .[[Writable]] がfalse なら、false を返す。propertyDesc が[[Value]] fieldを持つなら、? TypedArraySetElement (obj , numericIndex , propertyDesc .[[Value]] )を実行する。true を返す。! 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:
propertyKey がStringなら、numericIndex をCanonicalNumericIndexString (propertyKey )とする。numericIndex がundefined でないなら、TypedArrayGetElement (obj , numericIndex )を返す。? 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:
propertyKey がStringなら、numericIndex をCanonicalNumericIndexString (propertyKey )とする。numericIndex がundefined でないなら、SameValue (obj , receiver )がtrue なら、? TypedArraySetElement (obj , numericIndex , value )を実行する。 true を返す。IsValidIntegerIndex (obj , numericIndex )がfalse なら、true を返す。? 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:
propertyKey がStringなら、numericIndex をCanonicalNumericIndexString (propertyKey )とする。numericIndex がundefined でないなら、IsValidIntegerIndex (obj , numericIndex )がfalse なら、true を返す。false を返す。! 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:
taRecord をMakeTypedArrayWithBufferWitnessRecord (obj , seq-cst )とする。keys を新しい空のList とする。IsTypedArrayOutOfBounds (taRecord )がfalse なら、length をTypedArrayLength (taRecord )とする。0 ≤ i < length である各integer i について、昇順で、以下を行う! ToString (𝔽 (i ))をkeys へappendする。 Stringであり、integer index でないようなobj の各own property key propertyKey について、property creationのascending chronological orderで、以下を行うpropertyKey をkeys へappendする。 Symbolであるようなobj の各own property key propertyKey について、property creationのascending chronological orderで、以下を行うpropertyKey をkeys へappendする。 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:
buffer をobj .[[ViewedArrayBuffer]] とする。IsDetachedBuffer (buffer )がtrue なら、byteLength をdetached とする。そうでなければ、byteLength をArrayBufferByteLength (buffer , order )とする。 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:
internalSlotsList を« [[Prototype]] , [[Extensible]] , [[ViewedArrayBuffer]] , [[TypedArrayName]] , [[ContentType]] , [[ByteLength]] , [[ByteOffset]] , [[ArrayLength]] »とする。ta をMakeBasicObject (internalSlotsList )とする。ta .[[PreventExtensions]] を10.4.5.1 で指定されるように設定する。ta .[[GetOwnProperty]] を10.4.5.2 で指定されるように設定する。ta .[[HasProperty]] を10.4.5.3 で指定されるように設定する。ta .[[DefineOwnProperty]] を10.4.5.4 で指定されるように設定する。ta .[[Get]] を10.4.5.5 で指定されるように設定する。ta .[[Set]] を10.4.5.6 で指定されるように設定する。ta .[[Delete]] を10.4.5.7 で指定されるように設定する。ta .[[OwnPropertyKeys]] を10.4.5.8 で指定されるように設定する。ta .[[Prototype]] をproto に設定する。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:
Assert : IsTypedArrayOutOfBounds (taRecord )はfalse である。obj をtaRecord .[[Object]] とする。obj .[[ByteLength]] がauto でないなら、obj .[[ByteLength]] を返す。length をTypedArrayLength (taRecord )とする。elementSize をTypedArrayElementSize (obj )とする。NOTE : underlying bufferが非整数倍にresizeされている場合でも、返されるbyte lengthは常にelementSize の整数倍である。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:
Assert : IsTypedArrayOutOfBounds (taRecord )はfalse である。obj をtaRecord .[[Object]] とする。obj .[[ArrayLength]] がauto でないなら、obj .[[ArrayLength]] を返す。Assert : IsFixedLengthArrayBuffer (obj .[[ViewedArrayBuffer]] )はfalse である。byteOffset をobj .[[ByteOffset]] とする。elementSize をTypedArrayElementSize (obj )とする。byteLength をtaRecord .[[CachedBufferByteLength]] とする。Assert : byteLength はdetached でない。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:
obj をtaRecord .[[Object]] とする。bufferByteLength をtaRecord .[[CachedBufferByteLength]] とする。IsDetachedBuffer (obj .[[ViewedArrayBuffer]] )がtrue なら、Assert : bufferByteLength はdetached である。true を返す。Assert : bufferByteLength は非負整数である。byteOffsetStart をobj .[[ByteOffset]] とする。obj .[[ArrayLength]] がauto なら、byteOffsetEnd をbufferByteLength とする。そうでなければ、elementSize をTypedArrayElementSize (obj )とする。arrayByteLength をobj .[[ArrayLength]] × elementSize とする。byteOffsetEnd をbyteOffsetStart + arrayByteLength とする。 NOTE : [[ByteOffset]] がbufferByteLength である0-length TypedArray はout-of-boundsとはみなされない。byteOffsetStart > bufferByteLength またはbyteOffsetEnd > bufferByteLength なら、true を返す。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:
obj .[[ArrayLength]] がauto なら、false を返す。buffer をobj .[[ViewedArrayBuffer]] とする。IsFixedLengthArrayBuffer (buffer )がfalse かつIsSharedArrayBuffer (buffer )がfalse なら、false を返す。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:
IsDetachedBuffer (obj .[[ViewedArrayBuffer]] )がtrue なら、false を返す。index がintegral Number でないなら、false を返す。index が-0 𝔽 またはindex < -0 𝔽 なら、false を返す。taRecord をMakeTypedArrayWithBufferWitnessRecord (obj , unordered )とする。NOTE : obj のbacking bufferがgrowable SharedArrayBuffer である場合、Bounds checkingはsynchronizing operationではない。IsTypedArrayOutOfBounds (taRecord )がtrue なら、false を返す。length をTypedArrayLength (taRecord )とする。ℝ (index ) ≥ length なら、false を返す。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:
IsValidIntegerIndex (obj , index )がfalse なら、undefined を返す。offset をobj .[[ByteOffset]] とする。elementSize をTypedArrayElementSize (obj )とする。byteIndexInBuffer を(ℝ (index ) × elementSize ) + offset とする。elementType をTypedArrayElementType (obj )とする。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:
obj .[[ContentType]] がbigint なら、number を ? ToBigInt (value ) とする。そうでなければ、number を ? ToNumber (value ) とする。 IsValidIntegerIndex (obj , index )がtrue なら、offset をobj .[[ByteOffset]] とする。elementSize をTypedArrayElementSize (obj )とする。byteIndexInBuffer を(ℝ (index ) × elementSize ) + offset とする。elementType をTypedArrayElementType (obj )とする。SetValueInBuffer (obj .[[ViewedArrayBuffer]] , byteIndexInBuffer , elementType , number , true , unordered )を実行する。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:
obj が[[DataView]] internal slotを持つなら、viewRecord をMakeDataViewWithBufferWitnessRecord (obj , seq-cst )とする。IsViewOutOfBounds (viewRecord )を返す。taRecord をMakeTypedArrayWithBufferWitnessRecord (obj , seq-cst )とする。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
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:
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:
! 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:
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:
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:
propertyKey がSymbolなら、OrdinaryGetOwnProperty (obj , propertyKey )を返す。exports をobj .[[Exports]] とする。exports がpropertyKey を含まないなら、undefined を返す。value を ? obj .[[Get]] (propertyKey , obj ) とする。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:
propertyKey がSymbolなら、! OrdinaryDefineOwnProperty (obj , propertyKey , propertyDesc )を返す。current を ? obj .[[GetOwnProperty]] (propertyKey ) とする。current がundefined なら、false を返す。propertyDesc が[[Configurable]] fieldを持ち、propertyDesc .[[Configurable]] がtrue なら、false を返す。propertyDesc が[[Enumerable]] fieldを持ち、propertyDesc .[[Enumerable]] がfalse なら、false を返す。IsAccessorDescriptor (propertyDesc )がtrue なら、false を返す。propertyDesc が[[Writable]] fieldを持ち、propertyDesc .[[Writable]] がfalse なら、false を返す。propertyDesc が[[Value]] fieldを持つなら、SameValue (propertyDesc .[[Value]] , current .[[Value]] )を返す。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:
propertyKey がSymbolなら、! OrdinaryHasProperty (obj , propertyKey )を返す。exports をobj .[[Exports]] とする。exports がpropertyKey を含むなら、true を返す。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:
propertyKey がSymbolなら、! OrdinaryGet (obj , propertyKey , receiver )を返す。 exports をobj .[[Exports]] とする。exports がpropertyKey を含まないなら、undefined を返す。module をobj .[[Module]] とする。binding をmodule .ResolveExport (propertyKey )とする。Assert : binding はResolvedBinding Record である。targetModule をbinding .[[Module]] とする。Assert : targetModule はundefined でない。binding .[[BindingName]] がnamespace なら、GetModuleNamespace (targetModule )を返す。targetEnv をtargetModule .[[Environment]] とする。targetEnv がempty なら、ReferenceError 例外をthrowする。? targetEnv .GetBindingValue (binding .[[BindingName]] , true )を返す。
Note
ResolveExport はside-effect freeです。このoperationが特定のexportName 、resolveSet 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:
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:
propertyKey がSymbolなら、! OrdinaryDelete (obj , propertyKey )を返す。 exports をobj .[[Exports]] とする。exports がpropertyKey を含むなら、false を返す。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:
exports をobj .[[Exports]] とする。symbolKeys をOrdinaryOwnPropertyKeys (obj )とする。exports とsymbolKeys のlist-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:
Assert : module .[[Namespace]] はempty である。internalSlotsList をTable 29 に列挙されるinternal slotsとする。namespace をMakeBasicObject (internalSlotsList )とする。namespace のessential internal methodsを10.4.6 で指定される定義に設定する。namespace .[[Module]] をmodule に設定する。sortedExports を、exports の要素をlexicographic code unit order に従ってsortした要素を持つList とする。namespace .[[Exports]] をsortedExports に設定する。28.3 の定義に対応するnamespace のown propertiesを作成する。module .[[Namespace]] をnamespace に設定する。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:
? 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:
current を ? obj .[[GetPrototypeOf]] () とする。SameValue (proto , current )がtrue なら、true を返す。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、propertyKey はproperty key 値、value は任意のECMAScript language value、propertyDesc はProperty 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:
? ValidateNonRevokedProxy (obj )を実行する。 target をobj .[[ProxyTarget]] とする。handler をobj .[[ProxyHandler]] とする。Assert : handler はObjectである。trap を ? GetMethod (handler , "getPrototypeOf" ) とする。trap がundefined なら、? target .[[GetPrototypeOf]] () を返す。 handlerProto を ? Call (trap , handler , « target ») とする。handlerProto がObjectでなく、かつhandlerProto がnull でないなら、TypeError 例外をthrowする。extensibleTarget を ? IsExtensible (target ) とする。extensibleTarget がtrue なら、handlerProto を返す。targetProto を ? target .[[GetPrototypeOf]] () とする。SameValue (handlerProto , targetProto )がfalse なら、TypeError 例外をthrowする。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:
? ValidateNonRevokedProxy (obj )を実行する。 target をobj .[[ProxyTarget]] とする。handler をobj .[[ProxyHandler]] とする。Assert : handler はObjectである。trap を ? GetMethod (handler , "setPrototypeOf" ) とする。trap がundefined なら、? target .[[SetPrototypeOf]] (proto ) を返す。 boolTrapResult をToBoolean (? Call (trap , handler , « target , proto »))とする。boolTrapResult がfalse なら、false を返す。extensibleTarget を ? IsExtensible (target ) とする。extensibleTarget がtrue なら、true を返す。targetProto を ? target .[[GetPrototypeOf]] () とする。SameValue (proto , targetProto )がfalse なら、TypeError 例外をthrowする。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:
? ValidateNonRevokedProxy (obj )を実行する。 target をobj .[[ProxyTarget]] とする。handler をobj .[[ProxyHandler]] とする。Assert : handler はObjectである。trap を ? GetMethod (handler , "isExtensible" ) とする。trap がundefined なら、? IsExtensible (target )を返す。 boolTrapResult をToBoolean (? Call (trap , handler , « target »))とする。targetResult を ? IsExtensible (target ) とする。boolTrapResult がtargetResult でないなら、TypeError 例外をthrowする。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:
? ValidateNonRevokedProxy (obj )を実行する。 target をobj .[[ProxyTarget]] とする。handler をobj .[[ProxyHandler]] とする。Assert : handler はObjectである。trap を ? GetMethod (handler , "preventExtensions" ) とする。trap がundefined なら、? target .[[PreventExtensions]] () を返す。 boolTrapResult をToBoolean (? Call (trap , handler , « target »))とする。boolTrapResult がtrue なら、extensibleTarget を ? IsExtensible (target ) とする。extensibleTarget がtrue なら、TypeError 例外をthrowする。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:
? ValidateNonRevokedProxy (obj )を実行する。 target をobj .[[ProxyTarget]] とする。handler をobj .[[ProxyHandler]] とする。Assert : handler はObjectである。trap を ? GetMethod (handler , "getOwnPropertyDescriptor" ) とする。trap がundefined なら、? target .[[GetOwnProperty]] (propertyKey ) を返す。 trapResultObj を ? Call (trap , handler , « target , propertyKey ») とする。trapResultObj がObjectでなく、かつtrapResultObj がundefined でないなら、TypeError 例外をthrowする。targetDesc を ? target .[[GetOwnProperty]] (propertyKey ) とする。trapResultObj がundefined なら、targetDesc がundefined なら、undefined を返す。targetDesc .[[Configurable]] がfalse なら、TypeError 例外をthrowする。extensibleTarget を ? IsExtensible (target ) とする。extensibleTarget がfalse なら、TypeError 例外をthrowする。undefined を返す。extensibleTarget を ? IsExtensible (target ) とする。resultDesc を ? ToPropertyDescriptor (trapResultObj ) とする。CompletePropertyDescriptor (resultDesc )を実行する。valid をIsCompatiblePropertyDescriptor (extensibleTarget , resultDesc , targetDesc )とする。valid がfalse なら、TypeError 例外をthrowする。resultDesc .[[Configurable]] がfalse なら、targetDesc がundefined またはtargetDesc .[[Configurable]] がtrue なら、TypeError 例外をthrowする。resultDesc が[[Writable]] fieldを持ち、resultDesc .[[Writable]] がfalse なら、Assert : targetDesc は[[Writable]] fieldを持つ。targetDesc .[[Writable]] がtrue なら、TypeError 例外をthrowする。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:
? ValidateNonRevokedProxy (obj )を実行する。 target をobj .[[ProxyTarget]] とする。handler をobj .[[ProxyHandler]] とする。Assert : handler はObjectである。trap を ? GetMethod (handler , "defineProperty" ) とする。trap がundefined なら、? target .[[DefineOwnProperty]] (propertyKey , propertyDesc ) を返す。 propertyDescObj をFromPropertyDescriptor (propertyDesc )とする。boolTrapResult をToBoolean (? Call (trap , handler , « target , propertyKey , propertyDescObj »))とする。boolTrapResult がfalse なら、false を返す。targetDesc を ? target .[[GetOwnProperty]] (propertyKey ) とする。extensibleTarget を ? IsExtensible (target ) とする。propertyDesc が[[Configurable]] fieldを持ち、propertyDesc .[[Configurable]] がfalse なら、settingConfigFalse をtrue とする。そうでなければ、settingConfigFalse をfalse とする。 targetDesc がundefined なら、extensibleTarget がfalse なら、TypeError 例外をthrowする。settingConfigFalse がtrue なら、TypeError 例外をthrowする。そうでなければ、IsCompatiblePropertyDescriptor (extensibleTarget , propertyDesc , targetDesc )がfalse なら、TypeError 例外をthrowする。settingConfigFalse がtrue かつtargetDesc .[[Configurable]] がtrue なら、TypeError 例外をthrowする。IsDataDescriptor (targetDesc )がtrue 、targetDesc .[[Configurable]] がfalse 、かつtargetDesc .[[Writable]] がtrue なら、propertyDesc が[[Writable]] fieldを持ち、propertyDesc .[[Writable]] がfalse なら、TypeError 例外をthrowする。 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:
? ValidateNonRevokedProxy (obj )を実行する。 target をobj .[[ProxyTarget]] とする。handler をobj .[[ProxyHandler]] とする。Assert : handler はObjectである。trap を ? GetMethod (handler , "has" ) とする。trap がundefined なら、? target .[[HasProperty]] (propertyKey ) を返す。 boolTrapResult をToBoolean (? Call (trap , handler , « target , propertyKey »))とする。boolTrapResult がfalse なら、targetDesc を ? target .[[GetOwnProperty]] (propertyKey ) とする。targetDesc がundefined でないなら、targetDesc .[[Configurable]] がfalse なら、TypeError 例外をthrowする。extensibleTarget を ? IsExtensible (target ) とする。extensibleTarget がfalse なら、TypeError 例外をthrowする。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:
? ValidateNonRevokedProxy (obj )を実行する。 target をobj .[[ProxyTarget]] とする。handler をobj .[[ProxyHandler]] とする。Assert : handler はObjectである。trap を ? GetMethod (handler , "get" ) とする。trap がundefined なら、? target .[[Get]] (propertyKey , receiver ) を返す。 trapResult を ? Call (trap , handler , « target , propertyKey , receiver ») とする。targetDesc を ? target .[[GetOwnProperty]] (propertyKey ) とする。targetDesc がundefined でなく、かつtargetDesc .[[Configurable]] がfalse なら、IsDataDescriptor (targetDesc )がtrue であり、かつtargetDesc .[[Writable]] がfalse なら、SameValue (trapResult , targetDesc .[[Value]] )がfalse なら、TypeError 例外をthrowする。IsAccessorDescriptor (targetDesc )がtrue であり、かつtargetDesc .[[Get]] がundefined なら、trapResult がundefined でないなら、TypeError 例外をthrowする。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:
? ValidateNonRevokedProxy (obj )を実行する。 target をobj .[[ProxyTarget]] とする。handler をobj .[[ProxyHandler]] とする。Assert : handler はObjectである。trap を ? GetMethod (handler , "set" ) とする。trap がundefined なら、? target .[[Set]] (propertyKey , value , receiver ) を返す。 boolTrapResult をToBoolean (? Call (trap , handler , « target , propertyKey , value , receiver »))とする。boolTrapResult がfalse なら、false を返す。targetDesc を ? target .[[GetOwnProperty]] (propertyKey ) とする。targetDesc がundefined でなく、かつtargetDesc .[[Configurable]] がfalse なら、IsDataDescriptor (targetDesc )がtrue であり、かつtargetDesc .[[Writable]] がfalse なら、SameValue (value , targetDesc .[[Value]] )がfalse なら、TypeError 例外をthrowする。IsAccessorDescriptor (targetDesc )がtrue なら、targetDesc .[[Set]] がundefined なら、TypeError 例外をthrowする。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:
? ValidateNonRevokedProxy (obj )を実行する。 target をobj .[[ProxyTarget]] とする。handler をobj .[[ProxyHandler]] とする。Assert : handler はObjectである。trap を ? GetMethod (handler , "deleteProperty" ) とする。trap がundefined なら、? target .[[Delete]] (propertyKey ) を返す。 boolTrapResult をToBoolean (? Call (trap , handler , « target , propertyKey »))とする。boolTrapResult がfalse なら、false を返す。targetDesc を ? target .[[GetOwnProperty]] (propertyKey ) とする。targetDesc がundefined なら、true を返す。targetDesc .[[Configurable]] がfalse なら、TypeError 例外をthrowする。extensibleTarget を ? IsExtensible (target ) とする。extensibleTarget がfalse なら、TypeError 例外をthrowする。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:
? ValidateNonRevokedProxy (obj )を実行する。 target をobj .[[ProxyTarget]] とする。handler をobj .[[ProxyHandler]] とする。Assert : handler はObjectである。trap を ? GetMethod (handler , "ownKeys" ) とする。trap がundefined なら、? target .[[OwnPropertyKeys]] () を返す。 trapResultArray を ? Call (trap , handler , « target ») とする。trapResult を ? CreateListFromArrayLike (trapResultArray , property-key ) とする。trapResult が重複entriesを含むなら、TypeError 例外をthrowする。extensibleTarget を ? IsExtensible (target ) とする。targetKeys を ? target .[[OwnPropertyKeys]] () とする。Assert : targetKeys はproperty keys のList である。Assert : targetKeys は重複entriesを含まない。targetConfigurableKeys を新しい空のList とする。targetNonconfigurableKeys を新しい空のList とする。targetKeys の各要素key について、以下を行うpropertyDesc を ? target .[[GetOwnProperty]] (key ) とする。propertyDesc がundefined でなく、かつpropertyDesc .[[Configurable]] がfalse なら、key をtargetNonconfigurableKeys へappendする。そうでなければ、key をtargetConfigurableKeys へappendする。 extensibleTarget がtrue であり、かつtargetNonconfigurableKeys が空なら、trapResult を返す。uncheckedResultKeys を、要素がtrapResult の要素であるList とする。targetNonconfigurableKeys の各要素key について、以下を行うuncheckedResultKeys がkey を含まないなら、TypeError 例外をthrowする。key をuncheckedResultKeys から削除する。extensibleTarget がtrue なら、trapResult を返す。targetConfigurableKeys の各要素key について、以下を行うuncheckedResultKeys がkey を含まないなら、TypeError 例外をthrowする。key をuncheckedResultKeys から削除する。uncheckedResultKeys が空でないなら、TypeError 例外をthrowする。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:
? ValidateNonRevokedProxy (obj )を実行する。 target をobj .[[ProxyTarget]] とする。handler をobj .[[ProxyHandler]] とする。Assert : handler はObjectである。trap を ? GetMethod (handler , "apply" ) とする。trap がundefined なら、? Call (target , thisArg , argList )を返す。 argArray をCreateArrayFromList (argList )とする。? 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:
? ValidateNonRevokedProxy (obj )を実行する。 target をobj .[[ProxyTarget]] とする。Assert : IsConstructor (target )はtrue である。handler をobj .[[ProxyHandler]] とする。Assert : handler はObjectである。trap を ? GetMethod (handler , "construct" ) とする。trap がundefined なら、? Construct (target , argList , newTarget )を返す。 argArray をCreateArrayFromList (argList )とする。newObj を ? Call (trap , handler , « target , argArray , newTarget ») とする。newObj がObjectでないなら、TypeError 例外をthrowする。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:
proxy .[[ProxyTarget]] がnull なら、TypeError 例外をthrowする。Assert : proxy .[[ProxyHandler]] はnull でない。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:
target がObjectでないなら、TypeError 例外をthrowする。handler がObjectでないなら、TypeError 例外をthrowする。proxy をMakeBasicObject (« [[ProxyHandler]] , [[ProxyTarget]] »)とする。, [[Call]] および[[Construct]] を除き、proxy のessential internal methodsを10.5 で指定される定義に設定する。 IsCallable (target )がtrue なら、proxy .[[Call]] を10.5.12 で指定されるように設定する。IsConstructor (target )がtrue なら、proxy .[[Construct]] を10.5.13 で指定されるように設定する。proxy .[[ProxyTarget]] をtarget に設定する。proxy .[[ProxyHandler]] をhandler に設定する。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:
Assert : 0 ≤ codePoint ≤ 0x10FFFF.codePoint ≤ 0xFFFFなら、数値がcodePoint であるcode unitから成るString値を返す。cu1 を、数値がfloor ((codePoint - 0x10000) / 0x400) + 0xD800であるcode unitとする。cu2 を、数値が((codePoint - 0x10000) modulo 0x400) + 0xDC00であるcode unitとする。cu1 とcu2 のstring-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:
result を空のStringとする。text の各code point codePoint について、以下を行うresult をresult とUTF16EncodeCodePoint (codePoint )のstring-concatenation に設定する。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:
Assert : lead はleading surrogate であり、trail はtrailing surrogate である。codePoint を(lead - 0xD800) × 0x400 + (trail - 0xDC00) + 0x10000とする。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:
size をstring のlengthとする。Assert : position ≥ 0 かつ position < size .first をstring 内のindex position にあるcode unitとする。codePoint を、数値がfirst の数値であるcode pointとする。first がleading surrogate でもtrailing surrogate でもないなら、Record { [[CodePoint]] : codePoint , [[CodeUnitCount]] : 1, [[IsUnpairedSurrogate]] : false }を返す。first がtrailing surrogate 、またはposition + 1 = size なら、Record { [[CodePoint]] : codePoint , [[CodeUnitCount]] : 1, [[IsUnpairedSurrogate]] : true }を返す。second をstring 内のindex position + 1にあるcode unitとする。second がtrailing surrogate でないなら、Record { [[CodePoint]] : codePoint , [[CodeUnitCount]] : 1, [[IsUnpairedSurrogate]] : true }を返す。codePoint をUTF16SurrogatePairToCodePoint (first , second )に設定する。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:
codePoints を新しい空のList とする。size をstring のlengthとする。position を0とする。position < size である間、繰り返すcodePoint をCodePointAt (string , position )とする。codePoint .[[CodePoint]] をcodePoints へappendする。position をposition + codePoint .[[CodeUnitCount]] に設定する。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:
sourceText がStringなら、sourceText をStringToCodePoints (sourceText )に設定する。goalSymbol をgoal symbol として使用してsourceText のparseを試み、parse resultにearly error conditionsがないか分析する。Parsingとearly error detectionは、implementation-defined な方法でinterleavedされる場合があります。parseが成功し、early errors が見つからなかったなら、parseの結果得られたparse treeのrootにあるParse Node (goalSymbol のinstance)を返す。 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
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 constructor (20.2.1.1 )、GeneratorFunction constructor (27.6.1.1 )、AsyncFunction constructor (27.10.1.1 )、およびAsyncGeneratorFunction constructor (27.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 は、FunctionBody 、ScriptBody 、またはModuleBody の初期StatementListItem sまたはModuleItem sとして出現するExpressionStatement sの最長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 Directive はEscapeSequence またはLineContinuation を含んではなりません。
Directive Prologue は複数のUse Strict Directive を含む場合があります。ただし、実装はこれが発生した場合にwarningを発してよいです。
Note
Directive Prologue のExpressionStatement sは、含むproductionの評価中に通常どおり評価されます。実装は、Use Strict Directive ではなくDirective Prologue 内に出現するExpressionStatement sについて、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:
parseNode に一致するsource textがstrict mode code なら、true を返す。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は、RegularExpressionLiteral 、TemplateMiddle 、またはTemplateTail が許可されるsyntactic grammar contextsで使用されます。InputElementRegExp goal symbol は、RegularExpressionLiteral が許可されるが、TemplateMiddle もTemplateTail も許可されないすべての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は、StringLiteral 、RegularExpressionLiteral 、Template 、または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は、StringLiteral 、Template 、または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.5 Hashbang Comments
Hashbang Commentsはlocation-sensitiveであり、他のtypes of commentsと同様に、syntactic grammarのinput elementsのstreamから破棄されます。
Syntax
12.6 Tokens
Syntax
CommonToken ::
IdentifierName
PrivateIdentifier
Punctuator
NumericLiteral
StringLiteral
Template
Note
12.7 Names and Keywords
IdentifierName およびReservedWord は、Unicode Standard Annex #31, Identifier and Pattern Syntaxに示されるDefault Identifier Syntaxに従って解釈されるtokensですが、いくつかの小さな変更があります。ReservedWord はIdentifierName のenumerated subsetです。syntactic grammarは、Identifier をReservedWord でない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
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 内で許可され、そこでUnicodeEscapeSequence のIdentifierCodePoint と等しい単一の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つのIdentifierName sは、各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
codePoint をIdentifierStart のIdentifierCodePoint とする。« codePoint »を返す。
IdentifierName ::
IdentifierName
IdentifierPart
codePoints をderived IdentifierName のIdentifierCodePoints とする。codePoint をIdentifierPart のIdentifierCodePoint とする。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
IdentifierStartChar によってmatchされたcode pointを返す。
IdentifierPart :: IdentifierPartChar
IdentifierPartChar によってmatchされたcode pointを返す。
UnicodeEscapeSequence ::
u
Hex4Digits
数値がHex4Digits のMVであるcode pointを返す。
UnicodeEscapeSequence ::
u{
CodePoint
}
数値がCodePoint のMVであるcode pointを返す。
12.7.2 Keywords and Reserved Words
keyword はIdentifierName にmatchするtokenですが、syntactic useも持ちます;つまり、何らかのsyntactic production内に、fixed width fontでliteralに現れます。ECMAScriptのkeywordsには、if、while、async、await、その他多数が含まれます。
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.1 、14.3.1.1 、14.7.5.1 、および15.7.1 を参照してください。まとめると、identifier namesには5つのcategoriesがあります:
Math、window、toString、および_など、常にidentifiersとして許可され、keywordsではないもの;
下に列挙されるReservedWord sのうち、awaitおよびyieldを除いた、identifiersとして決して許可されないもの;
awaitおよびyieldという、contextuallyにidentifiersとして許可されるもの;
strict mode code において、contextuallyにidentifiersとして許可されないもの:let、static、implements、interface、package、private、protected、およびpublic;
常にidentifiersとして許可されるが、特定のsyntactic productions内で、Identifier が許可されない場所にkeywordsとしても現れるもの:as、async、from、get、meta、of、set、および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 は\ UnicodeEscapeSequence sを含むことができますが、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 です。
同様に、implements、interface、package、private、protected、およびpublicはstrict mode code におけるfuture reserved wordsです。
Note 3
names argumentsおよびevalはkeywordsではありませんが、strict mode code ではいくつかの制限を受けます。13.1.1 、8.6.4 、15.2.1 、15.5.1 、15.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
NumericLiteralSeparator opt
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
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
RoundMVResult (DecimalLiteral のMV)を返す。
NumericLiteral :: NonDecimalIntegerLiteral
𝔽 (NonDecimalIntegerLiteral のMV)を返す。
NumericLiteral :: LegacyOctalIntegerLiteral
𝔽 (LegacyOctalIntegerLiteral のMV)を返す。
NumericLiteral ::
NonDecimalIntegerLiteral
BigIntLiteralSuffix
NonDecimalIntegerLiteral のMVに対するBigInt値を返す。
DecimalBigIntegerLiteral ::
0
BigIntLiteralSuffix
0 ℤ を返す。
DecimalBigIntegerLiteral ::
NonZeroDigit
BigIntLiteralSuffix
NonZeroDigit のMVに対するBigInt値を返す。
DecimalBigIntegerLiteral ::
NonZeroDigit
DecimalDigits
BigIntLiteralSuffix
NonZeroDigit
NumericLiteralSeparator
DecimalDigits
BigIntLiteralSuffix
n を、NumericLiteralSeparator のすべての出現を除いたDecimalDigits 内のcode pointsの数とする。mv を(NonZeroDigit のMV × 10n )にDecimalDigits のMVを加えたものとする。ℤ (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 ::
"
DoubleStringCharacters opt
"
'
SingleStringCharacters opt
'
DoubleStringCharacters ::
DoubleStringCharacter
DoubleStringCharacters opt
SingleStringCharacters ::
SingleStringCharacter
SingleStringCharacters opt
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 に与えられています。SourceCharacter は11.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
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
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
RegularExpressionFlags として認識されたsource textを返す。
12.9.6 Template Literal Lexical Components
Syntax
Template ::
NoSubstitutionTemplate
TemplateHead
NoSubstitutionTemplate ::
`
TemplateCharacters opt
`
TemplateHead ::
`
TemplateCharacters opt
${
TemplateSubstitutionTail ::
TemplateMiddle
TemplateTail
TemplateMiddle ::
}
TemplateCharacters opt
${
TemplateTail ::
}
TemplateCharacters opt
`
TemplateCharacters ::
TemplateCharacter
TemplateCharacters opt
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
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
TV はLineContinuation のcode unitsを除外する一方、TRVはそれらを含みます。<CR><LF>および<CR> LineTerminatorSequence sは、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があります:
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される。
source textが左から右へparseされるとき、tokensのinput streamの終端に遭遇し、parserがinput token streamをgoal nonterminalの単一のinstanceとしてparseできない場合、input streamの終端にsemicolonが自動的に挿入されます。
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 トークンの後に自動的に挿入される。
continue、break、return、throw、または yield トークンに遭遇し、次のトークンの前に LineTerminator が遭遇された場合、セミコロンは continue、break、return、throw、または yield トークンの後に自動的に挿入される。
アロー関数のパラメータが => トークンの前の LineTerminator に続く場合、セミコロンが自動的に挿入され、その区切り子は構文エラーを引き起こす。
async トークンの後に、function、IdentifierName 、または ( トークンの前の LineTerminator が続く場合、セミコロンが自動的に挿入され、async トークンは後続のトークンと同じ式またはクラス要素の一部として扱われない。
async トークンの後に、* トークンの前の LineTerminator が続く場合、セミコロンが自動的に挿入され、その区切り子は構文エラーを引き起こす。
結果として、ECMAScript プログラマに対する実践的な助言は次のとおりである:
後置 ++ または -- 演算子は、そのオペランドと同じ行に置かれるべきである。
using 宣言内の BindingList は、using トークンと同じ行で開始するべきである。
return または throw 文内の Expression 、または yield 式内の AssignmentExpression は、return、throw、または 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 + bはreturn 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 では、多くのStatementListItem sは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
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
Identifier : IdentifierName but not ReservedWord
Note
IdentifierName のStringValue はIdentifierName 内の任意の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
idTextUnescaped をIdentifierName のIdentifierCodePoints とする。CodePointsToString (idTextUnescaped )を返す。
IdentifierReference : yield
BindingIdentifier : yield
LabelIdentifier : yield
"yield" を返す。
IdentifierReference : await
BindingIdentifier : await
LabelIdentifier : await
"await" を返す。
Identifier : IdentifierName but not ReservedWord
IdentifierName のStringValue を返す。
PrivateIdentifier ::
#
IdentifierName
0x0023 (NUMBER SIGN)とIdentifierName のStringValue のstring-concatenation を返す。
ModuleExportName : StringLiteral
StringLiteral のSV を返す。
13.1.3 Runtime Semantics: Evaluation
IdentifierReference : Identifier
? ResolveBinding (Identifier のStringValue )を返す。
IdentifierReference : yield
? ResolveBinding ("yield" )を返す。
IdentifierReference : await
? ResolveBinding ("await" )を返す。
Note 1
IdentifierReference を評価した結果は常にReference型の値です。
Note 2
non-strict code では、keyword yieldをidentifierとして使用できます。IdentifierReference を評価すると、yieldがIdentifier であったかのように、その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
? 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
null を返す。
Literal : BooleanLiteral
BooleanLiteral がtoken falseなら、false を返す。BooleanLiteral がtoken trueなら、true を返す。
Literal : NumericLiteral
12.9.3 で定義されるNumericLiteral のNumericValue を返す。
Literal : StringLiteral
12.9.4.2 で定義されるStringLiteral のSV を返す。
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] :
[
Elision opt
]
[
ElementList [?Yield, ?Await]
]
[
ElementList [?Yield, ?Await]
,
Elision opt
]
ElementList [Yield, Await] :
Elision opt
AssignmentExpression [+In, ?Yield, ?Await]
Elision opt
SpreadElement [?Yield, ?Await]
ElementList [?Yield, ?Await]
,
Elision opt
AssignmentExpression [+In, ?Yield, ?Await]
ElementList [?Yield, ?Await]
,
Elision opt
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 : ,
length をnextIndex + 1とする。? Set (array , "length" , 𝔽 (length ), true )を実行する。 NOTE : 上記stepは、length が232 - 1を超える場合にthrowする。length を返す。
Elision :
Elision
,
引数array および(nextIndex + 1)を伴うElision の ? ArrayAccumulation を返す。
ElementList :
Elision opt
AssignmentExpression
Elision が存在するなら、nextIndex を、引数array およびnextIndex を伴うElision の ? ArrayAccumulation に設定する。initResult をAssignmentExpression の ? Evaluation とする。initValue を ? GetValue (initResult ) とする。! CreateDataPropertyOrThrow (array , ! ToString (𝔽 (nextIndex )), initValue )を実行する。 nextIndex + 1を返す。
ElementList :
Elision opt
SpreadElement
Elision が存在するなら、nextIndex を、引数array およびnextIndex を伴うElision の ? ArrayAccumulation に設定する。引数array およびnextIndex を伴うSpreadElement の ? ArrayAccumulation を返す。
ElementList :
ElementList
,
Elision opt
AssignmentExpression
nextIndex を、引数array およびnextIndex を伴うderived ElementList の ? ArrayAccumulation に設定する。Elision が存在するなら、nextIndex を、引数array およびnextIndex を伴うElision の ? ArrayAccumulation に設定する。initResult をAssignmentExpression の ? Evaluation とする。initValue を ? GetValue (initResult ) とする。! CreateDataPropertyOrThrow (array , ! ToString (𝔽 (nextIndex )), initValue )を実行する。 nextIndex + 1を返す。
ElementList :
ElementList
,
Elision opt
SpreadElement
nextIndex を、引数array およびnextIndex を伴うderived ElementList の ? ArrayAccumulation に設定する。Elision が存在するなら、nextIndex を、引数array およびnextIndex を伴うElision の ? ArrayAccumulation に設定する。引数array およびnextIndex を伴うSpreadElement の ? ArrayAccumulation を返す。
SpreadElement :
...
AssignmentExpression
spreadRef をAssignmentExpression の ? Evaluation とする。spreadObj を ? GetValue (spreadRef ) とする。iteratorRecord を ? GetIterator (spreadObj , sync ) とする。繰り返すnext を ? IteratorStepValue (iteratorRecord ) とする。next がdone なら、nextIndex を返す。! CreateDataPropertyOrThrow (array , ! ToString (𝔽 (nextIndex )), next )を実行する。 nextIndex をnextIndex + 1に設定する。
Note
CreateDataPropertyOrThrow は、standard built-in Array prototype object が[[Set]] を使用した新しいown propertiesの作成を妨げるような方法で変更されている場合でも、arrayにown propertiesが定義されることを保証するために使用されます。
13.2.4.2 Runtime Semantics: Evaluation
ArrayLiteral :
[
Elision opt
]
array を ! ArrayCreate (0) とする。Elision が存在するなら、引数array および0を伴うElision の ? ArrayAccumulation を実行する。 array を返す。
ArrayLiteral :
[
ElementList
]
array を ! ArrayCreate (0) とする。引数array および0を伴うElementList の ? ArrayAccumulation を実行する。 array を返す。
ArrayLiteral :
[
ElementList
,
Elision opt
]
array を ! ArrayCreate (0) とする。nextIndex を、引数array および0を伴うElementList の ? ArrayAccumulation とする。Elision が存在するなら、引数array およびnextIndex を伴うElision の ? ArrayAccumulation を実行する。 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
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は、ObjectLiteral がObjectAssignmentPattern のcover grammarとして機能できるように存在します。これは実際のobject initializer内では出現できません。
ObjectLiteral :
{
PropertyDefinitionList
}
{
PropertyDefinitionList
,
}
Note 2
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
false を返す。
PropertyName : ComputedPropertyName
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 :
{
}
新しい空のList を返す。
PropertyDefinitionList : PropertyDefinition
« PropertyDefinition »を返す。
PropertyDefinitionList :
PropertyDefinitionList
,
PropertyDefinition
head をderived PropertyDefinitionList のPropertyDefinitionNodes とする。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
propertyName をPropertyDefinition のPropName とする。propertyName がempty なら、新しい空のList を返す。« propertyName »を返す。
PropertyDefinitionList :
PropertyDefinitionList
,
PropertyDefinition
list をPropertyDefinitionList のPropertyNameList とする。propertyName をPropertyDefinition のPropName とする。propertyName がempty なら、list を返す。list と« propertyName »のlist-concatenation を返す。
13.2.5.5 Runtime Semantics: Evaluation
ObjectLiteral :
{
}
OrdinaryObjectCreate (%Object.prototype% )を返す。
ObjectLiteral :
{
PropertyDefinitionList
}
{
PropertyDefinitionList
,
}
obj をOrdinaryObjectCreate (%Object.prototype% )とする。引数obj を伴うPropertyDefinitionList の ? PropertyDefinitionEvaluation を実行する。 obj を返す。
LiteralPropertyName : IdentifierName
IdentifierName のStringValue を返す。
LiteralPropertyName : StringLiteral
StringLiteral のSV を返す。
LiteralPropertyName : NumericLiteral
number をNumericLiteral のNumericValue とする。! ToString (number )を返す。
ComputedPropertyName :
[
AssignmentExpression
]
exprValue をAssignmentExpression の ? Evaluation とする。propertyName を ? GetValue (exprValue ) とする。? 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
引数obj を伴うPropertyDefinitionList の ? PropertyDefinitionEvaluation を実行する。 引数obj を伴うPropertyDefinition の ? PropertyDefinitionEvaluation を実行する。 unused を返す。
PropertyDefinition :
...
AssignmentExpression
exprValue をAssignmentExpression の ? Evaluation とする。fromValue を ? GetValue (exprValue ) とする。excludedNames を新しい空のList とする。? CopyDataProperties (obj , fromValue , excludedNames )を実行する。 unused を返す。
PropertyDefinition : IdentifierReference
propertyName をIdentifierReference のStringValue とする。exprValue をIdentifierReference の ? Evaluation とする。propertyValue を ? GetValue (exprValue ) とする。Assert : obj はordinaryでextensibleなobjectであり、non-configurable propertiesを持たない。! CreateDataPropertyOrThrow (obj , propertyName , propertyValue )を実行する。 unused を返す。
PropertyDefinition :
PropertyName
:
AssignmentExpression
propertyKey をPropertyName の ? Evaluation とする。このPropertyDefinition がParseJSON のために評価されているScript 内に含まれるなら(ParseJSON のstep 6 を参照)、isProtoSetter をfalse とする。 そうでなく、propertyKey が"__proto__" であり、かつPropertyName のIsComputedPropertyKey がfalse なら、isProtoSetter をtrue とする。 そうでなければ、isProtoSetter をfalse とする。 IsAnonymousFunctionDefinition (AssignmentExpression )がtrue であり、かつisProtoSetter がfalse なら、propertyValue を、引数propertyKey を伴うAssignmentExpression の ? NamedEvaluation とする。そうでなければ、exprValueRef をAssignmentExpression の ? Evaluation とする。propertyValue を ? GetValue (exprValueRef ) とする。 isProtoSetter がtrue なら、propertyValue がObjectまたはpropertyValue がnull なら、! obj .[[SetPrototypeOf]] (propertyValue ) を実行する。 unused を返す。Assert : obj はordinaryでextensibleなobjectであり、non-configurable propertiesを持たない。! CreateDataPropertyOrThrow (obj , propertyKey , propertyValue )を実行する。 unused を返す。
PropertyDefinition : MethodDefinition
引数obj およびtrue を伴うMethodDefinition の ? MethodDefinitionEvaluation を実行する。 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:
flags をliteral のFlagText とする。flags がd、g、i、m、s、u、v、またはy以外のcode pointsを含むなら、false を返す。flags が任意のcode pointを複数回含むなら、false を返す。flags がuを含むなら、u をtrue とする;そうでなければ、u をfalse とする。flags がvを含むなら、v をtrue とする;そうでなければ、v をfalse とする。patternText をliteral のBodyText とする。u がfalse であり、かつv がfalse なら、stringValue をCodePointsToString (patternText )とする。patternText を、stringValue の16-bit elementsのそれぞれをUnicode BMP code pointとして解釈した結果となるcode pointsのsequenceに設定する。UTF-16 decodingはelementsに適用されない。parseResult をParsePattern (patternText , u , v )とする。parseResult がParse Node なら、true を返す。false を返す。
13.2.7.3 Runtime Semantics: Evaluation
PrimaryExpression : RegularExpressionLiteral
pattern をCodePointsToString (RegularExpressionLiteral のBodyText )とする。flags をCodePointsToString (RegularExpressionLiteral のFlagText )とする。! 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
« TemplateString (NoSubstitutionTemplate , raw ) »を返す。
SubstitutionTemplate :
TemplateHead
Expression
TemplateSpans
head を« TemplateString (TemplateHead , raw ) »とする。tail を、argument raw を伴うTemplateSpans のTemplateStrings とする。head とtail のlist-concatenation を返す。
TemplateSpans : TemplateTail
« TemplateString (TemplateTail , raw ) »を返す。
TemplateSpans :
TemplateMiddleList
TemplateTail
middle を、argument raw を伴うTemplateMiddleList のTemplateStrings とする。tail を« TemplateString (TemplateTail , raw ) »とする。middle とtail のlist-concatenation を返す。
TemplateMiddleList :
TemplateMiddle
Expression
« TemplateString (TemplateMiddle , raw ) »を返す。
TemplateMiddleList :
TemplateMiddleList
TemplateMiddle
Expression
front を、argument raw を伴うTemplateMiddleList のTemplateStrings とする。last を« TemplateString (TemplateMiddle , raw ) »とする。front とlast のlist-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:
raw がtrue なら、string をtemplateToken のTRV とする。そうでなければ、string をtemplateToken のTV とする。 string を返す。
Note
このoperationは、raw がfalse であり、かつtemplateToken がNotEscapeSequence を含む場合、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:
realm をcurrent Realm Record とする。templateRegistry をrealm .[[TemplateMap]] とする。templateRegistry の各要素element について、以下を行うelement .[[Site]] がtemplateLiteral と同じParse Node なら、element .[[Array]] を返す。rawStrings を、argument true を伴うtemplateLiteral のTemplateStrings とする。Assert : rawStrings はStringsのList である。cookedStrings を、argument false を伴うtemplateLiteral のTemplateStrings とする。count をList cookedStrings 内のelements数とする。Assert : count ≤ 232 - 1.template を ! ArrayCreate (count ) とする。rawObj を ! ArrayCreate (count ) とする。index を0とする。index < count である間、繰り返すpropertyKey を ! ToString (𝔽 (index )) とする。cookedValue をcookedStrings [index ]とする。! DefinePropertyOrThrow (template , propertyKey , PropertyDescriptor { [[Value]] : cookedValue , [[Writable]] : false , [[Enumerable]] : true , [[Configurable]] : false })を実行する。 rawValue をString値rawStrings [index ]とする。! DefinePropertyOrThrow (rawObj , propertyKey , PropertyDescriptor { [[Value]] : rawValue , [[Writable]] : false , [[Enumerable]] : true , [[Configurable]] : false })を実行する。 index をindex + 1に設定する。! SetIntegrityLevel (rawObj , frozen )を実行する。 ! DefinePropertyOrThrow (template , "raw" , PropertyDescriptor { [[Value]] : rawObj , [[Writable]] : false , [[Enumerable]] : false , [[Configurable]] : false })を実行する。 ! SetIntegrityLevel (template , frozen )を実行する。 Record { [[Site]] : templateLiteral , [[Array]] : template }をrealm .[[TemplateMap]] へappendする。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
新しい空のList を返す。
TemplateSpans :
TemplateMiddleList
TemplateTail
TemplateMiddleList の ? SubstitutionEvaluation を返す。
TemplateMiddleList :
TemplateMiddle
Expression
subRef をExpression の ? Evaluation とする。sub を ? GetValue (subRef ) とする。« sub »を返す。
TemplateMiddleList :
TemplateMiddleList
TemplateMiddle
Expression
preceding をTemplateMiddleList の ? SubstitutionEvaluation とする。nextRef をExpression の ? Evaluation とする。next を ? GetValue (nextRef ) とする。preceding と« next »のlist-concatenation を返す。
13.2.8.6 Runtime Semantics: Evaluation
TemplateLiteral : NoSubstitutionTemplate
12.9.6 で定義されるNoSubstitutionTemplate のTV を返す。
SubstitutionTemplate :
TemplateHead
Expression
TemplateSpans
head を12.9.6 で定義されるTemplateHead のTV とする。subRef をExpression の ? Evaluation とする。sub を ? GetValue (subRef ) とする。middle を ? ToString (sub ) とする。tail をTemplateSpans の ? Evaluation とする。head 、middle 、およびtail のstring-concatenation を返す。
Note 1
Expression 値に適用されるstring conversion semanticsは、+ operatorではなくString.prototype.concatに似ています。
TemplateSpans : TemplateTail
12.9.6 で定義されるTemplateTail のTV を返す。
TemplateSpans :
TemplateMiddleList
TemplateTail
head をTemplateMiddleList の ? Evaluation とする。tail を12.9.6 で定義されるTemplateTail のTV とする。head とtail のstring-concatenation を返す。
TemplateMiddleList :
TemplateMiddle
Expression
head を12.9.6 で定義されるTemplateMiddle のTV とする。subRef をExpression の ? Evaluation とする。sub を ? GetValue (subRef ) とする。middle を ? ToString (sub ) とする。head とmiddle のstring-concatenation を返す。
Note 2
Expression 値に適用されるstring conversion semanticsは、+ operatorではなくString.prototype.concatに似ています。
TemplateMiddleList :
TemplateMiddleList
TemplateMiddle
Expression
rest をTemplateMiddleList の ? Evaluation とする。middle を12.9.6 で定義されるTemplateMiddle のTV とする。subRef をExpression の ? Evaluation とする。sub を ? GetValue (subRef ) とする。last を ? ToString (sub ) とする。rest 、middle 、およびlast のstring-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
expr をCoverParenthesizedExpressionAndArrowParameterList によってcoverされるParenthesizedExpression とする。expr の ? Evaluation を返す。
ParenthesizedExpression :
(
Expression
)
Expression の ? Evaluation を返す。これはReference型であり得る。
Note
このalgorithmはExpression のEvaluation にGetValue を適用しません。これの主要な動機は、deleteやtypeofなどの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によって説明されます:
は、その振る舞いにおいて次と同一です
同様に
は、その振る舞いにおいて次と同一です
ここで、<identifier-name-string >はIdentifierName のStringValue です。
13.3.2.1 Runtime Semantics: Evaluation
MemberExpression :
MemberExpression
[
Expression
]
baseRef をMemberExpression の ? Evaluation とする。baseValue を ? GetValue (baseRef ) とする。strict をIsStrict (this MemberExpression )とする。? EvaluatePropertyAccessWithExpressionKey (baseValue , Expression , strict )を返す。
MemberExpression :
MemberExpression
.
IdentifierName
baseRef をMemberExpression の ? Evaluation とする。baseValue を ? GetValue (baseRef ) とする。strict をIsStrict (this MemberExpression )とする。EvaluatePropertyAccessWithIdentifierKey (baseValue , IdentifierName , strict )を返す。
MemberExpression :
MemberExpression
.
PrivateIdentifier
baseRef をMemberExpression の ? Evaluation とする。baseValue を ? GetValue (baseRef ) とする。fieldNameString をPrivateIdentifier のStringValue とする。MakePrivateReference (baseValue , fieldNameString )を返す。
CallExpression :
CallExpression
[
Expression
]
baseRef をCallExpression の ? Evaluation とする。baseValue を ? GetValue (baseRef ) とする。strict をIsStrict (this CallExpression )とする。? EvaluatePropertyAccessWithExpressionKey (baseValue , Expression , strict )を返す。
CallExpression :
CallExpression
.
IdentifierName
baseRef をCallExpression の ? Evaluation とする。baseValue を ? GetValue (baseRef ) とする。strict をIsStrict (this CallExpression )とする。EvaluatePropertyAccessWithIdentifierKey (baseValue , IdentifierName , strict )を返す。
CallExpression :
CallExpression
.
PrivateIdentifier
baseRef をCallExpression の ? Evaluation とする。baseValue を ? GetValue (baseRef ) とする。fieldNameString をPrivateIdentifier のStringValue とする。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:
propertyNameRef をexpr の ? Evaluation とする。propertyNameValue を ? GetValue (propertyNameRef ) とする。NOTE : ほとんどの場合、ToPropertyKey はこのstepの直後にpropertyNameValue に対して実行される。しかし、a[b] = cの場合には、cの評価後まで実行されない。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:
propertyNameString をidentifierName のStringValue とする。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
? EvaluateNew (NewExpression , empty )を返す。
MemberExpression :
new
MemberExpression
Arguments
? 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:
ref をconstructExpr の ? Evaluation とする。ctor を ? GetValue (ref ) とする。argumentsNode がempty なら、argList を新しい空のList とする。そうでなければ、argList をargumentsNode の ? ArgumentListEvaluation とする。 IsConstructor (ctor )がfalse なら、TypeError 例外をthrowする。? Construct (ctor , argList )を返す。
13.3.6 Function Calls
13.3.6.1 Runtime Semantics: Evaluation
CallExpression : CoverCallExpressionAndAsyncArrowHead
expr をCoverCallExpressionAndAsyncArrowHead によってcoverされるCallMemberExpression とする。memberExpr をexpr のMemberExpression とする。args をexpr のArguments とする。ref をmemberExpr の ? Evaluation とする。func を ? GetValue (ref ) とする。ref がReference Record であり、IsPropertyReference (ref )がfalse であり、かつref .[[ReferencedName]] が"eval" なら、SameValue (func , %eval% )がtrue なら、argList をargs の ? ArgumentListEvaluation とする。argList がelementsを持たないなら、undefined を返す。evalArg をargList の最初のelementとする。IsStrict (this CallExpression )がtrue なら、strictCaller をtrue とする;そうでなければ、strictCaller をfalse とする。? PerformEval (evalArg , strictCaller , true )を返す。 thisCall をthis CallExpression とする。tailCall をIsInTailPosition (thisCall )とする。? EvaluateCall (func , ref , args , tailCall )を返す。
step 6.a.v を実行するCallExpression evaluationはdirect eval です。
CallExpression :
CallExpression
Arguments
ref をCallExpression の ? Evaluation とする。func を ? GetValue (ref ) とする。thisCall をthis CallExpression とする。tailCall をIsInTailPosition (thisCall )とする。? 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:
thisValueRef がReference Record なら、IsPropertyReference (thisValueRef )がtrue なら、thisValue をGetThisValue (thisValueRef )とする。そうでなければ、refEnv をthisValueRef .[[Base]] とする。Assert : refEnv はEnvironment Record である。thisValue をrefEnv .WithBaseObject ()とする。 そうでなければ、thisValue をundefined とする。 argList をargumentListNode の ? ArgumentListEvaluation とする。func がObjectでないなら、TypeError 例外をthrowする。IsCallable (func )がfalse なら、TypeError 例外をthrowする。tailPosition がtrue なら、PrepareForTailCall ()を実行する。? Call (func , thisValue , argList )を返す。
13.3.7 The super Keyword
13.3.7.1 Runtime Semantics: Evaluation
SuperProperty :
super
[
Expression
]
envRecord をGetThisEnvironment ()とする。actualThis を ? envRecord .GetThisBinding () とする。propertyNameRef をExpression の ? Evaluation とする。propertyNameValue を ? GetValue (propertyNameRef ) とする。strict をIsStrict (this SuperProperty )とする。NOTE : ほとんどの場合、ToPropertyKey はこのstepの直後にpropertyNameValue に対して実行される。しかし、super[b] = cの場合には、cの評価後まで実行されない。MakeSuperPropertyReference (actualThis , propertyNameValue , strict )を返す。
SuperProperty :
super
.
IdentifierName
envRecord をGetThisEnvironment ()とする。actualThis を ? envRecord .GetThisBinding () とする。propertyKey をIdentifierName のStringValue とする。strict をIsStrict (this SuperProperty )とする。MakeSuperPropertyReference (actualThis , propertyKey , strict )を返す。
SuperCall :
super
Arguments
newTarget をGetNewTarget ()とする。Assert : newTarget はconstructor である。superCtor をGetSuperConstructor ()とする。argList をArguments の ? ArgumentListEvaluation とする。IsConstructor (superCtor )がfalse なら、TypeError 例外をthrowする。result を ? Construct (superCtor , argList , newTarget ) とする。thisER をGetThisEnvironment ()とする。Assert : thisER はFunction Environment Record である。? BindThisValue (thisER , result )を実行する。 funcObj をthisER .[[FunctionObject]] とする。Assert : funcObj はECMAScript function object である。? InitializeInstanceElements (result , funcObj )を実行する。 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:
envRecord をGetThisEnvironment ()とする。Assert : envRecord はFunction Environment Record である。activeFunc をenvRecord .[[FunctionObject]] とする。Assert : activeFunc はECMAScript function object である。superCtor を ! activeFunc .[[GetPrototypeOf]] () とする。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:
envRecord をGetThisEnvironment ()とする。Assert : envRecord .HasSuperBinding ()はtrue である。Assert : envRecord はFunction Environment Record である。baseValue をGetSuperBase (envRecord )とする。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 :
(
)
新しい空のList を返す。
ArgumentList : AssignmentExpression
ref をAssignmentExpression の ? Evaluation とする。arg を ? GetValue (ref ) とする。« arg »を返す。
ArgumentList :
...
AssignmentExpression
list を新しい空のList とする。spreadRef をAssignmentExpression の ? Evaluation とする。spreadObj を ? GetValue (spreadRef ) とする。iteratorRecord を ? GetIterator (spreadObj , sync ) とする。繰り返すnext を ? IteratorStepValue (iteratorRecord ) とする。next がdone なら、list を返す。next をlist へappendする。
ArgumentList :
ArgumentList
,
AssignmentExpression
precedingArgs をArgumentList の ? ArgumentListEvaluation とする。ref をAssignmentExpression の ? Evaluation とする。arg を ? GetValue (ref ) とする。precedingArgs と« arg »のlist-concatenation を返す。
ArgumentList :
ArgumentList
,
...
AssignmentExpression
precedingArgs をArgumentList の ? ArgumentListEvaluation とする。spreadRef をAssignmentExpression の ? Evaluation とする。iteratorRecord を ? GetIterator (? GetValue (spreadRef ), sync ) とする。繰り返すnext を ? IteratorStepValue (iteratorRecord ) とする。next がdone なら、precedingArgs を返す。next をprecedingArgs へappendする。
TemplateLiteral : NoSubstitutionTemplate
templateLiteral をthis TemplateLiteral とする。siteObj をGetTemplateObject (templateLiteral )とする。« siteObj »を返す。
TemplateLiteral : SubstitutionTemplate
templateLiteral をthis TemplateLiteral とする。siteObj をGetTemplateObject (templateLiteral )とする。remaining をSubstitutionTemplate の ? ArgumentListEvaluation とする。« siteObj »とremaining のlist-concatenation を返す。
SubstitutionTemplate :
TemplateHead
Expression
TemplateSpans
firstSubRef をExpression の ? Evaluation とする。firstSub を ? GetValue (firstSubRef ) とする。restSub をTemplateSpans の ? SubstitutionEvaluation とする。Assert : restSub はpossibly empty List である。« firstSub »とrestSub のlist-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
baseRef をMemberExpression の ? Evaluation とする。baseValue を ? GetValue (baseRef ) とする。baseValue がundefined またはnull のいずれかなら、undefined を返す。引数baseValue およびbaseRef を伴うOptionalChain の ? ChainEvaluation を返す。
OptionalExpression :
CallExpression
OptionalChain
baseRef をCallExpression の ? Evaluation とする。baseValue を ? GetValue (baseRef ) とする。baseValue がundefined またはnull のいずれかなら、undefined を返す。引数baseValue およびbaseRef を伴うOptionalChain の ? ChainEvaluation を返す。
OptionalExpression :
OptionalExpression
OptionalChain
baseRef をOptionalExpression の ? Evaluation とする。baseValue を ? GetValue (baseRef ) とする。baseValue がundefined またはnull のいずれかなら、undefined を返す。引数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
thisChain をthis OptionalChain とする。tailCall をIsInTailPosition (thisChain )とする。? EvaluateCall (baseValue , baseRef , Arguments , tailCall )を返す。
OptionalChain :
?.
[
Expression
]
strict をIsStrict (this OptionalChain )とする。? EvaluatePropertyAccessWithExpressionKey (baseValue , Expression , strict )を返す。
OptionalChain :
?.
IdentifierName
strict をIsStrict (this OptionalChain )とする。EvaluatePropertyAccessWithIdentifierKey (baseValue , IdentifierName , strict )を返す。
OptionalChain :
?.
PrivateIdentifier
fieldNameString をPrivateIdentifier のStringValue とする。MakePrivateReference (baseValue , fieldNameString )を返す。
OptionalChain :
OptionalChain
Arguments
optionalChain をOptionalChain とする。newRef を、引数baseValue およびbaseRef を伴うoptionalChain の ? ChainEvaluation とする。newValue を ? GetValue (newRef ) とする。thisChain をthis OptionalChain とする。tailCall をIsInTailPosition (thisChain )とする。? EvaluateCall (newValue , newRef , Arguments , tailCall )を返す。
OptionalChain :
OptionalChain
[
Expression
]
optionalChain をOptionalChain とする。newRef を、引数baseValue およびbaseRef を伴うoptionalChain の ? ChainEvaluation とする。newValue を ? GetValue (newRef ) とする。strict をIsStrict (this OptionalChain )とする。? EvaluatePropertyAccessWithExpressionKey (newValue , Expression , strict )を返す。
OptionalChain :
OptionalChain
.
IdentifierName
optionalChain をOptionalChain とする。newRef を、引数baseValue およびbaseRef を伴うoptionalChain の ? ChainEvaluation とする。newValue を ? GetValue (newRef ) とする。strict をIsStrict (this OptionalChain )とする。EvaluatePropertyAccessWithIdentifierKey (newValue , IdentifierName , strict )を返す。
OptionalChain :
OptionalChain
.
PrivateIdentifier
optionalChain をOptionalChain とする。newRef を、引数baseValue およびbaseRef を伴うoptionalChain の ? ChainEvaluation とする。newValue を ? GetValue (newRef ) とする。fieldNameString をPrivateIdentifier のStringValue とする。MakePrivateReference (newValue , fieldNameString )を返す。
13.3.10 Import Calls
13.3.10.1 Runtime Semantics: Evaluation
ImportCall :
import
(
AssignmentExpression
,opt
)
? EvaluateImportCall (AssignmentExpression )を返す。
ImportCall :
import
(
AssignmentExpression
,
AssignmentExpression
,opt
)
? 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:
referrer をGetActiveScriptOrModule ()とする。referrer がnull なら、referrer をcurrent Realm Record に設定する。specifierRef をspecifierExpr の ? Evaluation とする。specifier を ? GetValue (specifierRef ) とする。optionsExpr が存在するなら、optionsRef をoptionsExpr の ? Evaluation とする。options を ? GetValue (optionsRef ) とする。そうでなければ、options をundefined とする。 promiseCapability を ! NewPromiseCapability (%Promise% ) とする。specifierString をCompletion (ToString (specifier ))とする。IfAbruptRejectPromise (specifierString , promiseCapability ).attrs を新しい空のList とする。options がundefined でないなら、options がObjectでないなら、! Call (promiseCapability .[[Reject]] , undefined , « 新しく作成されたTypeError object »)を実行する。 promiseCapability .[[Promise]] を返す。attrsObj をCompletion (Get (options , "with" )))とする。IfAbruptRejectPromise (attrsObj , promiseCapability ).attrsObj がundefined でないなら、attrsObj がObjectでないなら、! Call (promiseCapability .[[Reject]] , undefined , « 新しく作成されたTypeError object »)を実行する。 promiseCapability .[[Promise]] を返す。entries をCompletion (EnumerableOwnProperties (attrsObj , key+value ))とする。IfAbruptRejectPromise (entries , promiseCapability ).entries の各要素entry について、以下を行うkey を ! Get (entry , "0" ) とする。value を ! Get (entry , "1" ) とする。key がStringなら、value がStringでないなら、! Call (promiseCapability .[[Reject]] , undefined , « 新しく作成されたTypeError object »)を実行する。 promiseCapability .[[Promise]] を返す。ImportAttribute Record { [[Key]] : key , [[Value]] : value }をattrs へappendする。AllImportAttributesSupported (attrs )がfalse なら、! Call (promiseCapability .[[Reject]] , undefined , « 新しく作成されたTypeError object »)を実行する。 promiseCapability .[[Promise]] を返す。attrs を、その[[Key]] fieldのlexicographic orderに従ってsortし、そのような各fieldの値をUTF-16 code unit valuesのsequenceとして扱う。NOTE : このsortingは、hosts がattributesのenumerated順序に基づいてbehaviourを変更することを禁止されているという点でのみobservableです。moduleRequest を新しいModuleRequest Record { [[Specifier]] : specifierString , [[Attributes]] : attrs }とする。HostLoadImportedModule (referrer , moduleRequest , empty , promiseCapability )を実行する。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:
moduleCompletion がabrupt completion なら、! Call (promiseCapability .[[Reject]] , undefined , « moduleCompletion .[[Value]] »)を実行する。 unused を返す。module をmoduleCompletion .[[Value]] とする。loadPromise をmodule .LoadRequestedModules ()とする。promiseCapability をcaptureし、呼び出されたときに次のstepsを実行する、parameters (reason )を持つ新しいAbstract Closure としてrejectedClosure を作成する:! Call (promiseCapability .[[Reject]] , undefined , « reason »)を実行する。 NormalCompletion (undefined )を返す。onRejected をCreateBuiltinFunction (rejectedClosure , 1, "" , « »)とする。module 、promiseCapability 、およびonRejected をcaptureし、呼び出されたときに次のstepsを実行する、parametersを持たない新しいAbstract Closure としてlinkAndEvaluateClosure を作成する:link をCompletion (module .Link ())とする。link がabrupt completion なら、! Call (promiseCapability .[[Reject]] , undefined , « link .[[Value]] »)を実行する。 NormalCompletion (undefined )を返す。evaluatePromise をmodule .Evaluate ()とする。module およびpromiseCapability をcaptureし、呼び出されたときに次のstepsを実行する、parametersを持たない新しいAbstract Closure としてfulfilledClosure を作成する:namespace をGetModuleNamespace (module )とする。! Call (promiseCapability .[[Resolve]] , undefined , « namespace »)を実行する。 NormalCompletion (undefined )を返す。onFulfilled をCreateBuiltinFunction (fulfilledClosure , 0, "" , « »)とする。PerformPromiseThen (evaluatePromise , onFulfilled , onRejected )を実行する。unused を返す。linkAndEvaluate をCreateBuiltinFunction (linkAndEvaluateClosure , 0, "" , « »)とする。PerformPromiseThen (loadPromise , linkAndEvaluate , onRejected )を実行する。unused を返す。
13.3.11 Tagged Templates
Note
tagged templateは、そのcallのargumentsがTemplateLiteral (13.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
tagRef をMemberExpression の ? Evaluation とする。tagFunc を ? GetValue (tagRef ) とする。thisCall をthis MemberExpression とする。tailCall をIsInTailPosition (thisCall )とする。? EvaluateCall (tagFunc , tagRef , TemplateLiteral , tailCall )を返す。
CallExpression :
CallExpression
TemplateLiteral
tagRef をCallExpression の ? Evaluation とする。tagFunc を ? GetValue (tagRef ) とする。thisCall をthis CallExpression とする。tailCall をIsInTailPosition (thisCall )とする。? EvaluateCall (tagFunc , tagRef , TemplateLiteral , tailCall )を返す。
13.3.12 Meta Properties
13.3.12.1 Runtime Semantics: Evaluation
NewTarget :
new
.
target
GetNewTarget ()を返す。
ImportMeta :
import
.
meta
module をGetActiveScriptOrModule ()とする。Assert : module はSource Text Module Record である。importMeta をmodule .[[ImportMeta]] とする。importMeta がempty なら、importMeta をOrdinaryObjectCreate (null )に設定する。importMetaValues をHostGetImportMetaProperties (module )とする。importMetaValues の各Record { [[Key]] , [[Value]] } entry について、以下を行う! CreateDataPropertyOrThrow (importMeta , entry .[[Key]] , entry .[[Value]] )を実行する。 HostFinalizeImportMeta (importMeta , module )を実行する。module .[[ImportMeta]] をimportMeta に設定する。importMeta を返す。Assert : importMeta はObjectである。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). これは、hosts がimport.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 . これは、hosts がimport.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
++
lhs をLeftHandSideExpression の ? Evaluation とする。LeftHandSideExpression のAssignmentTargetType がweb-compat なら、ReferenceError 例外をthrowする。oldValue を ? ToNumeric (? GetValue (lhs )) とする。oldValue がNumberなら、newValue をNumber::add (oldValue , 1 𝔽 )とする。そうでなければ、Assert : oldValue はBigIntである。newValue をBigInt::add (oldValue , 1 ℤ )とする。 ? PutValue (lhs , newValue )を実行する。 oldValue を返す。
13.4.3 Postfix Decrement Operator
13.4.3.1 Runtime Semantics: Evaluation
UpdateExpression :
LeftHandSideExpression
--
lhs をLeftHandSideExpression の ? Evaluation とする。LeftHandSideExpression のAssignmentTargetType がweb-compat なら、ReferenceError 例外をthrowする。oldValue を ? ToNumeric (? GetValue (lhs )) とする。oldValue がNumberなら、newValue をNumber::subtract (oldValue , 1 𝔽 )とする。そうでなければ、Assert : oldValue はBigIntである。newValue をBigInt::subtract (oldValue , 1 ℤ )とする。 ? PutValue (lhs , newValue )を実行する。 oldValue を返す。
13.4.4 Prefix Increment Operator
13.4.4.1 Runtime Semantics: Evaluation
UpdateExpression :
++
UnaryExpression
expr をUnaryExpression の ? Evaluation とする。UnaryExpression のAssignmentTargetType がweb-compat なら、ReferenceError 例外をthrowする。oldValue を ? ToNumeric (? GetValue (expr )) とする。oldValue がNumberなら、newValue をNumber::add (oldValue , 1 𝔽 )とする。そうでなければ、Assert : oldValue はBigIntである。newValue をBigInt::add (oldValue , 1 ℤ )とする。 ? PutValue (expr , newValue )を実行する。 newValue を返す。
13.4.5 Prefix Decrement Operator
13.4.5.1 Runtime Semantics: Evaluation
UpdateExpression :
--
UnaryExpression
expr をUnaryExpression の ? Evaluation とする。UnaryExpression のAssignmentTargetType がweb-compat なら、ReferenceError 例外をthrowする。oldValue を ? ToNumeric (? GetValue (expr )) とする。oldValue がNumberなら、newValue をNumber::subtract (oldValue , 1 𝔽 )とする。そうでなければ、Assert : oldValue はBigIntである。newValue をBigInt::subtract (oldValue , 1 ℤ )とする。 ? PutValue (expr , newValue )を実行する。 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
ref をUnaryExpression の ? Evaluation とする。ref がReference Record でないなら、true を返す。IsUnresolvableReference (ref )がtrue なら、Assert : ref .[[Strict]] はfalse である。true を返す。IsPropertyReference (ref )がtrue なら、Assert : IsPrivateReference (ref )はfalse である。IsSuperReference (ref )がtrue なら、ReferenceError 例外をthrowする。baseObj を ? ToObject (ref .[[Base]] ) とする。ref .[[ReferencedName]] がproperty key でないなら、ref .[[ReferencedName]] を ? ToPropertyKey (ref .[[ReferencedName]] ) に設定する。deleteStatus を ? baseObj .[[Delete]] (ref .[[ReferencedName]] ) とする。deleteStatus がfalse であり、かつref .[[Strict]] がtrue なら、TypeError 例外をthrowする。deleteStatus を返す。base をref .[[Base]] とする。Assert : base はEnvironment Record である。? 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
expr をUnaryExpression の ? Evaluation とする。? GetValue (expr )を実行する。 undefined を返す。
Note
その値は使用されませんが、observable side-effectsを持つ場合があるため、GetValue は呼び出されなければなりません。
13.5.3 The typeof Operator
13.5.3.1 Runtime Semantics: Evaluation
UnaryExpression :
typeof
UnaryExpression
value をUnaryExpression の ? Evaluation とする。value がReference Record なら、IsUnresolvableReference (value )がtrue なら、"undefined" を返す。value を ? GetValue (value ) に設定する。value がundefined なら、"undefined" を返す。value がnull なら、"object" を返す。value がStringなら、"string" を返す。value がSymbolなら、"symbol" を返す。value がBooleanなら、"boolean" を返す。value がNumberなら、"number" を返す。value がBigIntなら、"bigint" を返す。Assert : value はObjectである。hostがweb browserである、またはその他の形で[[IsHTMLDDA]] Internal Slot をサポートするなら、value が[[IsHTMLDDA]] internal slotを持つなら、"undefined" を返す。 value が[[Call]] internal methodを持つなら、"function" を返す。"object" を返す。
13.5.4 Unary + Operator
Note
unary + operatorは、そのoperandをNumber typeへ変換します。
13.5.4.1 Runtime Semantics: Evaluation
UnaryExpression :
+
UnaryExpression
expr をUnaryExpression の ? Evaluation とする。? 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
expr をUnaryExpression の ? Evaluation とする。oldValue を ? ToNumeric (? GetValue (expr )) とする。oldValue がNumberなら、Number::unaryMinus (oldValue )を返す。Assert : oldValue はBigIntである。BigInt::unaryMinus (oldValue )を返す。
13.5.6 Bitwise NOT Operator ( ~ )
13.5.6.1 Runtime Semantics: Evaluation
UnaryExpression :
~
UnaryExpression
expr をUnaryExpression の ? Evaluation とする。oldValue を ? ToNumeric (? GetValue (expr )) とする。oldValue がNumberなら、Number::bitwiseNOT (oldValue )を返す。Assert : oldValue はBigIntである。BigInt::bitwiseNOT (oldValue )を返す。
13.5.7 Logical NOT Operator ( ! )
13.5.7.1 Runtime Semantics: Evaluation
UnaryExpression :
!
UnaryExpression
expr をUnaryExpression の ? Evaluation とする。oldValue をToBoolean (? GetValue (expr ))とする。oldValue がtrue なら、false を返す。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
? 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
opText をMultiplicativeOperator によってmatchされたsource textとする。? 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
? EvaluateStringOrNumericBinaryExpression (AdditiveExpression , +, MultiplicativeExpression )を返す。
13.8.2 The Subtraction Operator ( - )
Note
- operatorはsubtractionを実行し、そのoperandsのdifferenceを生成します。
13.8.2.1 Runtime Semantics: Evaluation
AdditiveExpression :
AdditiveExpression
-
MultiplicativeExpression
? 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
? 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
? 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
? 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
leftRef をRelationalExpression の ? Evaluation とする。leftValue を ? GetValue (leftRef ) とする。rightRef をShiftExpression の ? Evaluation とする。rightValue を ? GetValue (rightRef ) とする。result を ? IsLessThan (leftValue , rightValue , true ) とする。result がundefined なら、false を返す。result を返す。
RelationalExpression :
RelationalExpression
>
ShiftExpression
leftRef をRelationalExpression の ? Evaluation とする。leftValue を ? GetValue (leftRef ) とする。rightRef をShiftExpression の ? Evaluation とする。rightValue を ? GetValue (rightRef ) とする。result を ? IsLessThan (rightValue , leftValue , false ) とする。result がundefined なら、false を返す。result を返す。
RelationalExpression :
RelationalExpression
<=
ShiftExpression
leftRef をRelationalExpression の ? Evaluation とする。leftValue を ? GetValue (leftRef ) とする。rightRef をShiftExpression の ? Evaluation とする。rightValue を ? GetValue (rightRef ) とする。result を ? IsLessThan (rightValue , leftValue , false ) とする。result がtrue またはundefined のいずれかなら、false を返す。true を返す。
RelationalExpression :
RelationalExpression
>=
ShiftExpression
leftRef をRelationalExpression の ? Evaluation とする。leftValue を ? GetValue (leftRef ) とする。rightRef をShiftExpression の ? Evaluation とする。rightValue を ? GetValue (rightRef ) とする。result を ? IsLessThan (leftValue , rightValue , true ) とする。result がtrue またはundefined のいずれかなら、false を返す。true を返す。
RelationalExpression :
RelationalExpression
instanceof
ShiftExpression
leftRef をRelationalExpression の ? Evaluation とする。leftValue を ? GetValue (leftRef ) とする。rightRef をShiftExpression の ? Evaluation とする。rightValue を ? GetValue (rightRef ) とする。? InstanceofOperator (leftValue , rightValue )を返す。
RelationalExpression :
RelationalExpression
in
ShiftExpression
leftRef をRelationalExpression の ? Evaluation とする。leftValue を ? GetValue (leftRef ) とする。rightRef をShiftExpression の ? Evaluation とする。rightValue を ? GetValue (rightRef ) とする。rightValue がObjectでないなら、TypeError 例外をthrowする。? HasProperty (rightValue , ? ToPropertyKey (leftValue ))を返す。
RelationalExpression :
PrivateIdentifier
in
ShiftExpression
privateIdentifier をPrivateIdentifier のStringValue とする。rightRef をShiftExpression の ? Evaluation とする。rightValue を ? GetValue (rightRef ) とする。rightValue がObjectでないなら、TypeError 例外をthrowする。privateEnv をrunning execution context のPrivateEnvironmentとする。Assert : privateEnv はnull でない。privateName をResolvePrivateIdentifier (privateEnv , privateIdentifier )とする。PrivateElementFind (rightValue , privateName )がempty なら、false を返す。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内に存在するかどうかを判定することによって、value がtarget のinstanceであるかどうかを判定するgeneric algorithmを実装します。 It performs the following steps when called:
target がObjectでないなら、TypeError 例外をthrowする。instOfHandler を ? GetMethod (target , %Symbol.hasInstance% ) とする。instOfHandler がundefined でないなら、ToBoolean (? Call (instOfHandler , target , « value »))を返す。IsCallable (target )がfalse なら、TypeError 例外をthrowする。? 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
leftRef をEqualityExpression の ? Evaluation とする。leftValue を ? GetValue (leftRef ) とする。rightRef をRelationalExpression の ? Evaluation とする。rightValue を ? GetValue (rightRef ) とする。? IsLooselyEqual (rightValue , leftValue )を返す。
EqualityExpression :
EqualityExpression
!=
RelationalExpression
leftRef をEqualityExpression の ? Evaluation とする。leftValue を ? GetValue (leftRef ) とする。rightRef をRelationalExpression の ? Evaluation とする。rightValue を ? GetValue (rightRef ) とする。result を ? IsLooselyEqual (rightValue , leftValue ) とする。result がtrue なら、false を返す。true を返す。
EqualityExpression :
EqualityExpression
===
RelationalExpression
leftRef をEqualityExpression の ? Evaluation とする。leftValue を ? GetValue (leftRef ) とする。rightRef をRelationalExpression の ? Evaluation とする。rightValue を ? GetValue (rightRef ) とする。IsStrictlyEqual (rightValue , leftValue )を返す。
EqualityExpression :
EqualityExpression
!==
RelationalExpression
leftRef をEqualityExpression の ? Evaluation とする。leftValue を ? GetValue (leftRef ) とする。rightRef をRelationalExpression の ? Evaluation とする。rightValue を ? GetValue (rightRef ) とする。result をIsStrictlyEqual (rightValue , leftValue )とする。result がtrue なら、false を返す。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
? EvaluateStringOrNumericBinaryExpression (BitwiseANDExpression , &, EqualityExpression )を返す。
BitwiseXORExpression :
BitwiseXORExpression
^
BitwiseANDExpression
? EvaluateStringOrNumericBinaryExpression (BitwiseXORExpression , ^, BitwiseANDExpression )を返す。
BitwiseORExpression :
BitwiseORExpression
|
BitwiseXORExpression
? 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
leftRef をLogicalANDExpression の ? Evaluation とする。leftValue を ? GetValue (leftRef ) とする。ToBoolean (leftValue )がfalse なら、leftValue を返す。rightRef をBitwiseORExpression の ? Evaluation とする。? GetValue (rightRef )を返す。
LogicalORExpression :
LogicalORExpression
||
LogicalANDExpression
leftRef をLogicalORExpression の ? Evaluation とする。leftValue を ? GetValue (leftRef ) とする。ToBoolean (leftValue )がtrue なら、leftValue を返す。rightRef をLogicalANDExpression の ? Evaluation とする。? GetValue (rightRef )を返す。
CoalesceExpression :
CoalesceExpressionHead
??
BitwiseORExpression
leftRef をCoalesceExpressionHead の ? Evaluation とする。leftValue を ? GetValue (leftRef ) とする。leftValue がundefined でもnull でもないなら、leftValue を返す。rightRef をBitwiseORExpression の ? Evaluation とする。? 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
leftRef をShortCircuitExpression の ? Evaluation とする。leftValue をToBoolean (? GetValue (leftRef ))とする。leftValue がtrue なら、trueRef を最初のAssignmentExpression の ? Evaluation とする。? GetValue (trueRef )を返す。 falseRef を2番目のAssignmentExpression の ? Evaluation とする。? 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
LeftHandSideExpression がObjectLiteral でもArrayLiteral でもないなら、leftRef をLeftHandSideExpression の ? Evaluation とする。LeftHandSideExpression のAssignmentTargetType がweb-compat なら、ReferenceError 例外をthrowする。IsAnonymousFunctionDefinition (AssignmentExpression )がtrue であり、かつLeftHandSideExpression のIsIdentifierRef がtrue なら、lhs をLeftHandSideExpression のStringValue とする。rightValue を、引数lhs を伴うAssignmentExpression の ? NamedEvaluation とする。そうでなければ、rightRef をAssignmentExpression の ? Evaluation とする。rightValue を ? GetValue (rightRef ) とする。 ? PutValue (leftRef , rightValue )を実行する。 rightValue を返す。assignmentPattern をLeftHandSideExpression によってcoverされるAssignmentPattern とする。rightRef をAssignmentExpression の ? Evaluation とする。rightValue を ? GetValue (rightRef ) とする。引数rightValue を伴うassignmentPattern の ? DestructuringAssignmentEvaluation を実行する。 rightValue を返す。
AssignmentExpression :
LeftHandSideExpression
AssignmentOperator
AssignmentExpression
leftRef をLeftHandSideExpression の ? Evaluation とする。LeftHandSideExpression のAssignmentTargetType がweb-compat なら、ReferenceError 例外をthrowする。leftValue を ? GetValue (leftRef ) とする。rightRef をAssignmentExpression の ? Evaluation とする。rightValue を ? GetValue (rightRef ) とする。assignmentOpText をAssignmentOperator によってmatchされたsource textとする。opText を、次のtable内でassignmentOpText に関連付けられたUnicode code pointsのsequenceとする:
assignmentOpText opText
**= **
*= *
/= /
%= %
+= +
-= -
<<= <<
>>= >>
>>>= >>>
&= &
^= ^
|= |
result を ? ApplyStringOrNumericBinaryOperator (leftValue , opText , rightValue ) とする。? PutValue (leftRef , result )を実行する。 result を返す。
AssignmentExpression :
LeftHandSideExpression
&&=
AssignmentExpression
leftRef をLeftHandSideExpression の ? Evaluation とする。leftValue を ? GetValue (leftRef ) とする。ToBoolean (leftValue )がfalse なら、leftValue を返す。IsAnonymousFunctionDefinition (AssignmentExpression )がtrue であり、かつLeftHandSideExpression のIsIdentifierRef がtrue なら、lhs をLeftHandSideExpression のStringValue とする。rightValue を、引数lhs を伴うAssignmentExpression の ? NamedEvaluation とする。そうでなければ、rightRef をAssignmentExpression の ? Evaluation とする。rightValue を ? GetValue (rightRef ) とする。 ? PutValue (leftRef , rightValue )を実行する。 rightValue を返す。
AssignmentExpression :
LeftHandSideExpression
||=
AssignmentExpression
leftRef をLeftHandSideExpression の ? Evaluation とする。leftValue を ? GetValue (leftRef ) とする。ToBoolean (leftValue )がtrue なら、leftValue を返す。IsAnonymousFunctionDefinition (AssignmentExpression )がtrue であり、かつLeftHandSideExpression のIsIdentifierRef がtrue なら、lhs をLeftHandSideExpression のStringValue とする。rightValue を、引数lhs を伴うAssignmentExpression の ? NamedEvaluation とする。そうでなければ、rightRef をAssignmentExpression の ? Evaluation とする。rightValue を ? GetValue (rightRef ) とする。 ? PutValue (leftRef , rightValue )を実行する。 rightValue を返す。
AssignmentExpression :
LeftHandSideExpression
??=
AssignmentExpression
leftRef をLeftHandSideExpression の ? Evaluation とする。leftValue を ? GetValue (leftRef ) とする。leftValue がundefined でもnull でもないなら、leftValue を返す。IsAnonymousFunctionDefinition (AssignmentExpression )がtrue であり、かつLeftHandSideExpression のIsIdentifierRef がtrue なら、lhs をLeftHandSideExpression のStringValue とする。rightValue を、引数lhs を伴うAssignmentExpression の ? NamedEvaluation とする。そうでなければ、rightRef をAssignmentExpression の ? Evaluation とする。rightValue を ? GetValue (rightRef ) とする。 ? PutValue (leftRef , rightValue )を実行する。 rightValue を返す。
Note
このexpressionがstrict mode code 内に出現する場合、step 1.e 、3 、2 、2 、2 におけるleftRef がunresolvable referenceであるなら、それはruntime errorです。そうであれば、ReferenceError 例外がthrowされます。さらに、step 9 、6 、6 、6 における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:
opText が+なら、leftPrimitive を ? ToPrimitive (leftValue ) とする。rightPrimitive を ? ToPrimitive (rightValue ) とする。leftPrimitive がStringまたはrightPrimitive がStringなら、leftString を ? ToString (leftPrimitive ) とする。rightString を ? ToString (rightPrimitive ) とする。leftString とrightString のstring-concatenation を返す。leftValue をleftPrimitive に設定する。rightValue をrightPrimitive に設定する。NOTE : この時点では、numeric operationでなければならない。leftNumber を ? ToNumeric (leftValue ) とする。rightNumber を ? ToNumeric (rightValue ) とする。SameType (leftNumber , rightNumber )がfalse なら、TypeError 例外をthrowする。leftNumber がBigIntなら、opText が**なら、? BigInt::exponentiate (leftNumber , rightNumber )を返す。opText が/なら、? BigInt::divide (leftNumber , rightNumber )を返す。opText が%なら、? BigInt::remainder (leftNumber , rightNumber )を返す。opText が>>>なら、? BigInt::unsignedRightShift (leftNumber , rightNumber )を返す。operation を、次のtable内でopText に関連付けられたabstract operationとする:
そうでなければ、Assert : leftNumber はNumberである。operation を、次のtable内でopText に関連付けられたabstract operationとする:
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:
leftRef をleftOperand の ? Evaluation とする。leftValue を ? GetValue (leftRef ) とする。rightRef をrightOperand の ? Evaluation とする。rightValue を ? GetValue (rightRef ) とする。? 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] :
[
Elision opt
AssignmentRestElement [?Yield, ?Await] opt
]
[
AssignmentElementList [?Yield, ?Await]
]
[
AssignmentElementList [?Yield, ?Await]
,
Elision opt
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] :
Elision opt
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
Initializer opt
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 :
{
}
? RequireObjectCoercible (value )を実行する。 unused を返す。
ObjectAssignmentPattern :
{
AssignmentPropertyList
}
{
AssignmentPropertyList
,
}
? RequireObjectCoercible (value )を実行する。 引数value を伴うAssignmentPropertyList の ? PropertyDestructuringAssignmentEvaluation を実行する。 unused を返す。
ObjectAssignmentPattern :
{
AssignmentRestProperty
}
? RequireObjectCoercible (value )を実行する。 excludedNames を新しい空のList とする。引数value およびexcludedNames を伴うAssignmentRestProperty の ? RestDestructuringAssignmentEvaluation を返す。
ObjectAssignmentPattern :
{
AssignmentPropertyList
,
AssignmentRestProperty
}
? RequireObjectCoercible (value )を実行する。 excludedNames を、引数value を伴うAssignmentPropertyList の ? PropertyDestructuringAssignmentEvaluation とする。引数value およびexcludedNames を伴うAssignmentRestProperty の ? RestDestructuringAssignmentEvaluation を返す。
ArrayAssignmentPattern :
[
]
iteratorRecord を ? GetIterator (value , sync ) とする。? IteratorClose (iteratorRecord , NormalCompletion (unused ))を返す。
ArrayAssignmentPattern :
[
Elision
]
iteratorRecord を ? GetIterator (value , sync ) とする。result を、引数iteratorRecord を伴うElision のIteratorDestructuringAssignmentEvaluation のCompletion とする。iteratorRecord .[[Done]] がfalse なら、? IteratorClose (iteratorRecord , result )を返す。result を返す。
ArrayAssignmentPattern :
[
Elision opt
AssignmentRestElement
]
iteratorRecord を ? GetIterator (value , sync ) とする。Elision が存在するなら、status を、引数iteratorRecord を伴うElision のIteratorDestructuringAssignmentEvaluation のCompletion とする。status がabrupt completion なら、Assert : iteratorRecord .[[Done]] はtrue である。? status を返す。 result を、引数iteratorRecord を伴うAssignmentRestElement のIteratorDestructuringAssignmentEvaluation のCompletion とする。iteratorRecord .[[Done]] がfalse なら、? IteratorClose (iteratorRecord , result )を返す。result を返す。
ArrayAssignmentPattern :
[
AssignmentElementList
]
iteratorRecord を ? GetIterator (value , sync ) とする。result を、引数iteratorRecord を伴うAssignmentElementList のIteratorDestructuringAssignmentEvaluation のCompletion とする。iteratorRecord .[[Done]] がfalse なら、? IteratorClose (iteratorRecord , result )を返す。result を返す。
ArrayAssignmentPattern :
[
AssignmentElementList
,
Elision opt
AssignmentRestElement opt
]
iteratorRecord を ? GetIterator (value , sync ) とする。status を、引数iteratorRecord を伴うAssignmentElementList のIteratorDestructuringAssignmentEvaluation のCompletion とする。status がabrupt completion なら、iteratorRecord .[[Done]] がfalse なら、? IteratorClose (iteratorRecord , status )を返す。? status を返す。 Elision が存在するなら、status を、引数iteratorRecord を伴うElision のIteratorDestructuringAssignmentEvaluation のCompletion に設定する。status がabrupt completion なら、Assert : iteratorRecord .[[Done]] はtrue である。? status を返す。 AssignmentRestElement が存在するなら、status を、引数iteratorRecord を伴うAssignmentRestElement のIteratorDestructuringAssignmentEvaluation のCompletion に設定する。iteratorRecord .[[Done]] がfalse なら、? IteratorClose (iteratorRecord , status )を返す。? 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
propertyNames を、引数value を伴うAssignmentPropertyList の ? PropertyDestructuringAssignmentEvaluation とする。nextNames を、引数value を伴うAssignmentProperty の ? PropertyDestructuringAssignmentEvaluation とする。propertyNames とnextNames のlist-concatenation を返す。
AssignmentProperty :
IdentifierReference
Initializer opt
propertyName をIdentifierReference のStringValue とする。leftRef を ? ResolveBinding (propertyName ) とする。value を ? GetV (value , propertyName ) に設定する。Initializer が存在し、かつvalue がundefined なら、IsAnonymousFunctionDefinition (Initializer )がtrue なら、value を、引数propertyName を伴うInitializer の ? NamedEvaluation に設定する。そうでなければ、defaultValue をInitializer の ? Evaluation とする。value を ? GetValue (defaultValue ) に設定する。 ? PutValue (leftRef , value )を実行する。 « propertyName »を返す。
AssignmentProperty :
PropertyName
:
AssignmentElement
name をPropertyName の ? Evaluation とする。引数value およびname を伴うAssignmentElement の ? KeyedDestructuringAssignmentEvaluation を実行する。 « 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
leftRef をDestructuringAssignmentTarget の ? Evaluation とする。restObj をOrdinaryObjectCreate (%Object.prototype% )とする。? CopyDataProperties (restObj , value , excludedNames )を実行する。 ? 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
引数iteratorRecord を伴うAssignmentElisionElement の ? IteratorDestructuringAssignmentEvaluation を返す。
AssignmentElementList :
AssignmentElementList
,
AssignmentElisionElement
引数iteratorRecord を伴うAssignmentElementList の ? IteratorDestructuringAssignmentEvaluation を実行する。 引数iteratorRecord を伴うAssignmentElisionElement の ? IteratorDestructuringAssignmentEvaluation を返す。
AssignmentElisionElement : AssignmentElement
引数iteratorRecord を伴うAssignmentElement の ? IteratorDestructuringAssignmentEvaluation を返す。
AssignmentElisionElement :
Elision
AssignmentElement
引数iteratorRecord を伴うElision の ? IteratorDestructuringAssignmentEvaluation を実行する。 引数iteratorRecord を伴うAssignmentElement の ? IteratorDestructuringAssignmentEvaluation を返す。
Elision : ,
iteratorRecord .[[Done]] がfalse なら、? IteratorStep (iteratorRecord )を実行する。 unused を返す。
Elision :
Elision
,
引数iteratorRecord を伴うElision の ? IteratorDestructuringAssignmentEvaluation を実行する。 iteratorRecord .[[Done]] がfalse なら、? IteratorStep (iteratorRecord )を実行する。 unused を返す。
AssignmentElement :
DestructuringAssignmentTarget
Initializer opt
DestructuringAssignmentTarget がObjectLiteral でもArrayLiteral でもないなら、leftRef をDestructuringAssignmentTarget の ? Evaluation とする。value をundefined とする。iteratorRecord .[[Done]] がfalse なら、next を ? IteratorStepValue (iteratorRecord ) とする。next がdone でないなら、value をnext に設定する。Initializer が存在し、かつvalue がundefined なら、IsAnonymousFunctionDefinition (Initializer )がtrue であり、かつDestructuringAssignmentTarget のIsIdentifierRef がtrue なら、target をDestructuringAssignmentTarget のStringValue とする。v を、引数target を伴うInitializer の ? NamedEvaluation とする。そうでなければ、defaultValue をInitializer の ? Evaluation とする。v を ? GetValue (defaultValue ) とする。 そうでなければ、v をvalue とする。 DestructuringAssignmentTarget がObjectLiteral またはArrayLiteral のいずれかなら、nestedAssignmentPattern をDestructuringAssignmentTarget によってcoverされるAssignmentPattern とする。引数v を伴うnestedAssignmentPattern の ? DestructuringAssignmentEvaluation を返す。 ? PutValue (leftRef , v )を返す。
Note
left to right evaluation orderは、iterator へaccessする前、またはInitializer を評価する前に、destructuring patternではないDestructuringAssignmentTarget を評価することによって維持されます。
AssignmentRestElement :
...
DestructuringAssignmentTarget
DestructuringAssignmentTarget がObjectLiteral でもArrayLiteral でもないなら、leftRef をDestructuringAssignmentTarget の ? Evaluation とする。array を ! ArrayCreate (0) とする。n を0とする。iteratorRecord .[[Done]] がfalse である間、繰り返すnext を ? IteratorStepValue (iteratorRecord ) とする。next がdone でないなら、! CreateDataPropertyOrThrow (array , ! ToString (𝔽 (n )), next )を実行する。 n をn + 1に設定する。DestructuringAssignmentTarget がObjectLiteral でもArrayLiteral でもないなら、? PutValue (leftRef , array )を返す。 nestedAssignmentPattern をDestructuringAssignmentTarget によってcoverされるAssignmentPattern とする。引数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
Initializer opt
DestructuringAssignmentTarget がObjectLiteral でもArrayLiteral でもないなら、leftRef をDestructuringAssignmentTarget の ? Evaluation とする。value を ? GetV (value , propertyName ) に設定する。Initializer が存在し、かつvalue がundefined なら、IsAnonymousFunctionDefinition (Initializer )がtrue であり、かつDestructuringAssignmentTarget のIsIdentifierRef がtrue なら、target をDestructuringAssignmentTarget のStringValue とする。rhsValue を、引数target を伴うInitializer の ? NamedEvaluation とする。そうでなければ、defaultValue をInitializer の ? Evaluation とする。rhsValue を ? GetValue (defaultValue ) とする。 そうでなければ、rhsValue をvalue とする。 DestructuringAssignmentTarget がObjectLiteral またはArrayLiteral のいずれかなら、assignmentPattern をDestructuringAssignmentTarget によってcoverされるAssignmentPattern とする。引数rhsValue を伴うassignmentPattern の ? DestructuringAssignmentEvaluation を返す。 ? 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
leftRef をExpression の ? Evaluation とする。? GetValue (leftRef )を実行する。 rightRef をAssignmentExpression の ? Evaluation とする。? 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
empty を返す。
HoistableDeclaration : FunctionDeclaration
FunctionDeclaration の ? Evaluation を返す。
BreakableStatement :
IterationStatement
SwitchStatement
newLabelSet を新しい空のList とする。引数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 :
{
}
empty を返す。
Block :
{
StatementList
}
oldEnv を、実行中の実行コンテキストの LexicalEnvironment とする。blockEnv を NewDeclarativeEnvironment (oldEnv ) とする。BlockDeclarationInstantiation (StatementList , blockEnv ) を実行する。実行中の実行コンテキストの LexicalEnvironment を blockEnv に設定する。 blockValue を StatementList の Evaluation の Completion とする。blockValue を Completion (DisposeResources (blockEnv .[[DisposableResourceStack]] , blockValue )) に設定する。実行中の実行コンテキストの LexicalEnvironment を oldEnv に設定する。 Return ? blockValue .
Note 1
controlがどのようにBlock から離れても、LexicalEnvironmentは常に以前のstateへ復元されます。
StatementList :
StatementList
StatementListItem
sl をStatementList の ? Evaluation とする。s をStatementListItem のEvaluation のCompletion とする。? 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を実行します:
code のLexicallyScopedDeclarations をdecls とする。実行中の実行コンテキストのPrivateEnvironmentをprivateEnv とする。 decls の各要素decl について、次を行う。decl のBoundNames の各要素name について、次を行う。decl のIsConstantDeclaration がtrue である場合、! envRecord .CreateImmutableBinding (name , true )を実行する。 そうでなければ、ホスト がWebブラウザである、またはその他の形でBlock-Level Function Declarations Web Legacy Compatibility Semantics をサポートする場合、! envRecord .HasBinding (name )がfalse である場合、! envRecord .CreateMutableBinding (name , false )を実行する。 そうでなければ、! envRecord .CreateMutableBinding (name , false )を実行する。 decl がFunctionDeclaration 、GeneratorDeclaration 、AsyncFunctionDeclaration 、またはAsyncGeneratorDeclaration のいずれかである場合、decl のBoundNames の唯一の要素をfuncName とする。envRecord およびprivateEnv を引数として、decl のInstantiateFunctionObject をfuncObj とする。ホスト がWebブラウザである、またはその他の形でBlock-Level Function Declarations Web Legacy Compatibility Semantics をサポートする場合、envRecord 内のfuncName に対する束縛が未初期化束縛である場合、! envRecord .InitializeBinding (funcName , funcObj )を実行する。 そうでなければ、Assert : decl はFunctionDeclaration である。! envRecord .SetMutableBinding (funcName , funcObj , false )を実行する。 そうでなければ、! envRecord .InitializeBinding (funcName , funcObj )を実行する。 unused を返す。
14.3 Declarations and the Variable Statement
14.3.1 Let、Const、Using、および Await Using 宣言
Note
let、const、using、および await using 宣言は、実行中の実行コンテキストの LexicalEnvironment にスコープされる変数を定義する。変数は、それを含む Environment Record がインスタンス化されるときに作成されるが、その変数の LexicalBinding が評価されるまで、いかなる方法でもアクセスできない。Initializer を持つ LexicalBinding によって定義される変数には、変数が作成されるときではなく、LexicalBinding が評価されるときに、その Initializer の AssignmentExpression の値が代入される。let 宣言内の LexicalBinding が Initializer を持たない場合、その 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
Initializer opt
14.3.1.2 Runtime Semantics: Evaluation
LexicalDeclaration :
LetOrConst
BindingList
;
引数 normal で BindingList の BindingEvaluation を実行する。 empty を返す。
UsingDeclaration :
using
BindingList
;
引数 sync-dispose で BindingList の BindingEvaluation を実行する。 empty を返す。
AwaitUsingDeclaration :
CoverAwaitExpressionAndAwaitUsingDeclarationHead
BindingList
;
引数 async-dispose で BindingList の BindingEvaluation を実行する。 empty を返す。
14.3.1.3 Runtime Semantics: BindingEvaluation
The syntax-directed operation BindingEvaluation takes argument kind (normal 、sync-dispose 、または async-dispose ) and returns unused を含む normal completion または abrupt completion . It is defined piecewise over the following productions:
BindingList :
BindingList
,
LexicalBinding
引数 kind で、派生した BindingList の BindingEvaluation を実行する。 引数 kind で LexicalBinding の BindingEvaluation を返す。
LexicalBinding : BindingIdentifier
Assert : kind は normal である。lhs を ! ResolveBinding (BindingIdentifier の StringValue ) とする。! InitializeReferencedBinding (lhs , undefined ) を実行する。 unused を返す。
Note
静的意味論の規則により、この形式の LexicalBinding は const、using、または await using 宣言では決して発生しないことが保証される。
LexicalBinding :
BindingIdentifier
Initializer
bindingId を BindingIdentifier の StringValue とする。lhs を ! ResolveBinding (bindingId ) とする。IsAnonymousFunctionDefinition (Initializer ) が true である場合、thenvalue を、引数 bindingId で Initializer の NamedEvaluation とする。Else,rhs を Initializer の Evaluation とする。value を ? GetValue (rhs ) とする。 kind が normal でない場合、thenAssert : IsUnresolvableReference (lhs ) は false である。base を lhs .[[Base]] とする。Assert : base は Declarative Environment Record である。? AddDisposableResource (base .[[DisposableResourceStack]] , value , kind ) を実行する。 ? InitializeReferencedBinding (lhs , value ) を実行する。 unused を返す。
LexicalBinding :
BindingPattern
Initializer
Assert : kind は normal である。rhs を Initializer の Evaluation とする。value を ? GetValue (rhs ) とする。envRecord を、実行中の実行コンテキストの LexicalEnvironment とする。引数 value および envRecord で、BindingPattern の BindingInitialization を返す。
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 が実行されるときに、そのInitializer のAssignmentExpression の値が割り当てられます。
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
;
VariableDeclarationList の ? Evaluation を実行する。empty を返す。
VariableDeclarationList :
VariableDeclarationList
,
VariableDeclaration
VariableDeclarationList の ? Evaluation を実行する。VariableDeclaration の ? Evaluation を返す。
VariableDeclaration : BindingIdentifier
empty を返す。
VariableDeclaration :
BindingIdentifier
Initializer
bindingId をBindingIdentifier のStringValue とする。lhs を ? ResolveBinding (bindingId ) とする。IsAnonymousFunctionDefinition (Initializer )がtrue なら、value を、引数bindingId を伴うInitializer の ? NamedEvaluation とする。そうでなければ、rhs をInitializer の ? Evaluation とする。value を ? GetValue (rhs ) とする。 ? PutValue (lhs , value )を実行する。 empty を返す。
Note
VariableDeclaration がwith statement内にnestedされており、VariableDeclaration 内のBindingIdentifier がwith statementのObject Environment Record のbinding objectのproperty name と同じである場合、step 5 はvalue をIdentifier のVariableEnvironment bindingへ割り当てる代わりに、そのpropertyへ割り当てます。
VariableDeclaration :
BindingPattern
Initializer
rhs をInitializer の ? Evaluation とする。rightValue を ? GetValue (rhs ) とする。引数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] :
[
Elision opt
BindingRestElement [?Yield, ?Await] opt
]
[
BindingElementList [?Yield, ?Await]
]
[
BindingElementList [?Yield, ?Await]
,
Elision opt
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] :
Elision opt
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
boundNames を、引数value およびenvRecord を伴うBindingPropertyList の ? PropertyBindingInitialization とする。nextNames を、引数value およびenvRecord を伴うBindingProperty の ? PropertyBindingInitialization とする。boundNames とnextNames のlist-concatenation を返す。
BindingProperty : SingleNameBinding
name をSingleNameBinding のBoundNames の唯一の要素とする。引数value 、envRecord 、およびname を伴うSingleNameBinding の ? KeyedBindingInitialization を実行する。 « name »を返す。
BindingProperty :
PropertyName
:
BindingElement
propertyKey をPropertyName の ? Evaluation とする。引数value 、envRecord 、およびpropertyKey を伴うBindingElement の ? KeyedBindingInitialization を実行する。 « 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
lhs を ? ResolveBinding (BindingIdentifier のStringValue , envRecord ) とする。restObj をOrdinaryObjectCreate (%Object.prototype% )とする。? CopyDataProperties (restObj , value , excludedNames )を実行する。 envRecord がundefined なら、? PutValue (lhs , restObj )を返す。? 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
envRecord にundefined が渡された場合、それは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
Initializer opt
value を ? GetV (value , propertyName ) に設定する。Initializer が存在し、かつvalue がundefined なら、defaultValue をInitializer の ? Evaluation とする。value を ? GetValue (defaultValue ) に設定する。引数value およびenvRecord を伴うBindingPattern の ? BindingInitialization を返す。
SingleNameBinding :
BindingIdentifier
Initializer opt
bindingId をBindingIdentifier のStringValue とする。lhs を ? ResolveBinding (bindingId , envRecord ) とする。value を ? GetV (value , propertyName ) に設定する。Initializer が存在し、かつvalue がundefined なら、IsAnonymousFunctionDefinition (Initializer )がtrue なら、value を、引数bindingId を伴うInitializer の ? NamedEvaluation に設定する。そうでなければ、defaultValue をInitializer の ? Evaluation とする。value を ? GetValue (defaultValue ) に設定する。 envRecord がundefined なら、? PutValue (lhs , value )を返す。? InitializeReferencedBinding (lhs , value )を返す。
14.4 Empty Statement
Syntax
EmptyStatement :
;
14.4.1 Runtime Semantics: Evaluation
EmptyStatement : ;
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を生じさせる可能性があるためです。ExpressionStatement はfunctionまたはclass keywords で開始できません。これはFunctionDeclaration 、GeneratorDeclaration 、またはClassDeclaration とのambiguityを生じさせるためです。ExpressionStatement はasync functionで開始できません。これはAsyncFunctionDeclaration またはAsyncGeneratorDeclaration とのambiguityを生じさせるためです。ExpressionStatement はtwo token sequence let [で開始できません。これは、最初のLexicalBinding がArrayBindingPattern であるlet LexicalDeclaration とのambiguityを生じさせるためです。
14.5.1 Runtime Semantics: Evaluation
ExpressionStatement :
Expression
;
exprRef をExpression の ? Evaluation とする。? 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
exprRef をExpression の ? Evaluation とする。exprValue をToBoolean (? GetValue (exprRef ))とする。exprValue がtrue なら、stmtCompletion を最初のStatement のEvaluation のCompletion とする。そうでなければ、stmtCompletion を2番目のStatement のEvaluation のCompletion とする。 ? UpdateEmpty (stmtCompletion , undefined )を返す。
IfStatement :
if
(
Expression
)
Statement
exprRef をExpression の ? Evaluation とする。exprValue をToBoolean (? GetValue (exprRef ))とする。exprValue がfalse なら、undefined を返す。stmtCompletion をStatement のEvaluation のCompletion とする。? 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:
completion がnormal completion なら、true を返す。completion がcontinue completion でないなら、false を返す。completion .[[Target]] がempty なら、true を返す。labelSet がcompletion .[[Target]] を含むなら、true を返す。false を返す。
Note
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
引数labelSet を伴うDoWhileStatement の ? DoWhileLoopEvaluation を返す。
IterationStatement : WhileStatement
引数labelSet を伴うWhileStatement の ? WhileLoopEvaluation を返す。
IterationStatement : ForStatement
引数labelSet を伴うForStatement の ? ForLoopEvaluation を返す。
IterationStatement : ForInOfStatement
引数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
)
;
iterationResult をundefined とする。繰り返すstmtResult をStatement のEvaluation のCompletion とする。LoopContinues (stmtResult , labelSet )がfalse なら、? UpdateEmpty (stmtResult , iterationResult )を返す。stmtResult .[[Value]] がempty でないなら、iterationResult をstmtResult .[[Value]] に設定する。exprRef をExpression の ? Evaluation とする。exprValue を ? GetValue (exprRef ) とする。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
iterationResult をundefined とする。繰り返すexprRef をExpression の ? Evaluation とする。exprValue を ? GetValue (exprRef ) とする。ToBoolean (exprValue )がfalse なら、iterationResult を返す。stmtResult をStatement のEvaluation のCompletion とする。LoopContinues (stmtResult , labelSet )がfalse なら、? UpdateEmpty (stmtResult , iterationResult )を返す。stmtResult .[[Value]] がempty でないなら、iterationResult をstmtResult .[[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
(
Expression opt
;
Expression opt
;
Expression opt
)
Statement
for
(
var
VariableDeclarationList
;
Expression opt
;
Expression opt
)
Statement
for
(
LexicalDeclaration
Expression opt
;
Expression opt
)
Statement
Note
このruleを適用する必要があるのは、B.3.1 で指定されるextensionが実装されている場合だけです。
ForStatement :
for
(
LexicalDeclaration
Expression opt
;
Expression opt
)
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
(
Expression opt
;
Expression opt
;
Expression opt
)
Statement
最初のExpression が存在するなら、exprRef を最初のExpression の ? Evaluation とする。? GetValue (exprRef )を実行する。 2番目のExpression が存在するなら、test を2番目のExpression とする;そうでなければ、test をempty とする。 3番目のExpression が存在するなら、increment を3番目のExpression とする;そうでなければ、increment をempty とする。 ? ForBodyEvaluation (test , increment , Statement , « », labelSet )を返す。
ForStatement :
for
(
var
VariableDeclarationList
;
Expression opt
;
Expression opt
)
Statement
VariableDeclarationList の ? Evaluation を実行する。最初のExpression が存在するなら、test を最初のExpression とする;そうでなければ、test をempty とする。 2番目のExpression が存在するなら、increment を2番目のExpression とする;そうでなければ、increment をempty とする。 ? ForBodyEvaluation (test , increment , Statement , « », labelSet )を返す。
ForStatement :
for
(
LexicalDeclaration
Expression opt
;
Expression opt
)
Statement
oldEnv を、実行中の実行コンテキストの LexicalEnvironment とする。loopEnv を NewDeclarativeEnvironment (oldEnv ) とする。isConst を LexicalDeclaration の IsConstantDeclaration とする。boundNames を LexicalDeclaration の BoundNames とする。boundNames の各要素 name について、doisConst が true である場合、then! loopEnv .CreateImmutableBinding (name , true ) を実行する。 Else,! loopEnv .CreateMutableBinding (name , false ) を実行する。 実行中の実行コンテキストの LexicalEnvironment を loopEnv に設定する。 forDecl を LexicalDeclaration の Evaluation の Completion とする。forDecl が abrupt completion である場合、thenforDecl を Completion (DisposeResources (loopEnv .[[DisposableResourceStack]] , forDecl )) に設定する。Assert : forDecl は abrupt completion である。実行中の実行コンテキストの LexicalEnvironment を oldEnv に設定する。 Return ? forDecl . isConst が false である場合、perIterationLets を boundNames とする。そうでなければ、perIterationLets を新しい空の List とする。最初の Expression が存在する場合、test を最初の Expression とする。そうでなければ、test を empty とする。 2番目の Expression が存在する場合、increment を2番目の Expression とする。そうでなければ、increment を empty とする。 bodyResult を Completion (ForBodyEvaluation (test , increment , Statement , perIterationLets , labelSet )) とする。bodyResult を Completion (DisposeResources (loopEnv .[[DisposableResourceStack]] , bodyResult )) に設定する。Assert : bodyResult が normal completion である場合、bodyResult .[[Value]] は empty でない。実行中の実行コンテキストの LexicalEnvironment を oldEnv に設定する。 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:
iterationResult をundefined とする。? CreatePerIterationEnvironment (perIterationBindings )を実行する。 繰り返すtest がempty でないなら、testRef をtest の ? Evaluation とする。testValue を ? GetValue (testRef ) とする。ToBoolean (testValue )がfalse なら、iterationResult を返す。result をstmt のEvaluation のCompletion とする。LoopContinues (result , labelSet )がfalse なら、? UpdateEmpty (result , iterationResult )を返す。result .[[Value]] がempty でないなら、iterationResult をresult .[[Value]] に設定する。? CreatePerIterationEnvironment (perIterationBindings )を実行する。 increment がempty でないなら、incRef をincrement の ? Evaluation とする。? 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:
perIterationBindings に要素がある場合、実行中の実行コンテキストのLexicalEnvironmentをlastIterationEnv とする。 lastIterationEnv .[[OuterEnv]] をouter とする。Assert : outer はnull ではない。NewDeclarativeEnvironment (outer )をthisIterationEnv とする。perIterationBindings の各要素name について、次を行う。! thisIterationEnv .CreateMutableBinding (name , false )を実行する。 ? lastIterationEnv .GetBindingValue (name , true )をlastValue とする。 ! thisIterationEnv .InitializeBinding (name , lastValue )を実行する。 実行中の実行コンテキストのLexicalEnvironmentをthisIterationEnv に設定する。 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
PrimaryExpression がObjectLiteral またはArrayLiteral のいずれかなら、true を返す。false を返す。
MemberExpression :
MemberExpression
[
Expression
]
MemberExpression
.
IdentifierName
MemberExpression
TemplateLiteral
SuperProperty
MetaProperty
new
MemberExpression
Arguments
MemberExpression
.
PrivateIdentifier
NewExpression :
new
NewExpression
LeftHandSideExpression :
CallExpression
OptionalExpression
false を返す。
ForDeclaration :
LetOrConst
ForBinding
ForBinding のIsDestructuring を返す。
ForBinding : BindingIdentifier
false を返す。
ForBinding : BindingPattern
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
引数value およびenvRecord を伴うForBinding の ? BindingInitialization を返す。
ForDeclaration :
using
ForBinding
await
using
ForBinding
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
ForBinding のBoundNames の各要素name について、以下を行うLetOrConst のIsConstantDeclaration がtrue なら、! envRecord .CreateImmutableBinding (name , true )を実行する。 そうでなければ、! envRecord .CreateMutableBinding (name , false )を実行する。 unused を返す。
ForDeclaration :
using
ForBinding
await
using
ForBinding
ForBinding の BoundNames の各要素 name について、do! envRecord .CreateImmutableBinding (name , true ) を実行する。 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
keyResult を ? ForIn/OfHeadEvaluation (« », Expression , enumerate ) とする。? ForIn/OfBodyEvaluation (LeftHandSideExpression , Statement , keyResult , enumerate , assignment , labelSet )を返す。
ForInOfStatement :
for
(
var
ForBinding
in
Expression
)
Statement
keyResult を ? ForIn/OfHeadEvaluation (« », Expression , enumerate ) とする。? ForIn/OfBodyEvaluation (ForBinding , Statement , keyResult , enumerate , var-binding , labelSet )を返す。
ForInOfStatement :
for
(
ForDeclaration
in
Expression
)
Statement
keyResult を ? ForIn/OfHeadEvaluation (ForDeclaration のBoundNames , Expression , enumerate ) とする。? ForIn/OfBodyEvaluation (ForDeclaration , Statement , keyResult , enumerate , lexical-binding , labelSet )を返す。
ForInOfStatement :
for
(
LeftHandSideExpression
of
AssignmentExpression
)
Statement
keyResult を ? ForIn/OfHeadEvaluation (« », AssignmentExpression , iterate ) とする。? ForIn/OfBodyEvaluation (LeftHandSideExpression , Statement , keyResult , iterate , assignment , labelSet )を返す。
ForInOfStatement :
for
(
var
ForBinding
of
AssignmentExpression
)
Statement
keyResult を ? ForIn/OfHeadEvaluation (« », AssignmentExpression , iterate ) とする。? ForIn/OfBodyEvaluation (ForBinding , Statement , keyResult , iterate , var-binding , labelSet )を返す。
ForInOfStatement :
for
(
ForDeclaration
of
AssignmentExpression
)
Statement
keyResult を ? ForIn/OfHeadEvaluation (ForDeclaration のBoundNames , AssignmentExpression , iterate ) とする。? ForIn/OfBodyEvaluation (ForDeclaration , Statement , keyResult , iterate , lexical-binding , labelSet )を返す。
ForInOfStatement :
for
await
(
LeftHandSideExpression
of
AssignmentExpression
)
Statement
keyResult を ? ForIn/OfHeadEvaluation (« », AssignmentExpression , async-iterate ) とする。? ForIn/OfBodyEvaluation (LeftHandSideExpression , Statement , keyResult , iterate , assignment , labelSet , async )を返す。
ForInOfStatement :
for
await
(
var
ForBinding
of
AssignmentExpression
)
Statement
keyResult を ? ForIn/OfHeadEvaluation (« », AssignmentExpression , async-iterate ) とする。? ForIn/OfBodyEvaluation (ForBinding , Statement , keyResult , iterate , var-binding , labelSet , async )を返す。
ForInOfStatement :
for
await
(
ForDeclaration
of
AssignmentExpression
)
Statement
keyResult を ? ForIn/OfHeadEvaluation (ForDeclaration のBoundNames , AssignmentExpression , async-iterate ) とする。? 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:
oldEnv をrunning execution context のLexicalEnvironmentとする。uninitializedBoundNames が空でないなら、Assert : uninitializedBoundNames は重複entriesを持たない。newEnv をNewDeclarativeEnvironment (oldEnv )とする。uninitializedBoundNames の各String name について、以下を行う! newEnv .CreateMutableBinding (name , false )を実行する。 running execution context のLexicalEnvironmentをnewEnv に設定する。exprRef をexpr のEvaluation のCompletion とする。running execution context のLexicalEnvironmentをoldEnv に設定する。exprValue を ? GetValue (? exprRef ) とする。iterationKind がenumerate なら、exprValue がundefined またはnull のいずれかなら、Completion Record { [[Type]] : break , [[Value]] : empty , [[Target]] : empty }を返す。obj を ! ToObject (exprValue ) とする。iterator をEnumerateObjectProperties (obj )とする。nextMethod を ! GetV (iterator , "next" ) とする。Iterator Record { [[Iterator]] : iterator , [[NextMethod]] : nextMethod , [[Done]] : false }を返す。Assert : iterationKind はiterate またはasync-iterate のいずれかである。iterationKind がasync-iterate なら、iteratorKind をasync とする。そうでなければ、iteratorKind をsync とする。 ? 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:
iteratorKind が存在しない場合、iteratorKind を sync に設定する。oldEnv を、実行中の実行コンテキストの LexicalEnvironment とする。iterationResult を undefined とする。lhsKind が lexical-binding である場合、thenAssert : lhs は ForDeclaration である。lhs の IsAwaitUsingDeclaration が true である場合、thendeclarationKind を async-dispose とする。Else if lhs の IsUsingDeclaration が true である場合、thendeclarationKind を sync-dispose とする。 Else,declarationKind を normal とする。 Else,declarationKind を normal とする。 destructuring を lhs の IsDestructuring とする。destructuring が true であり、かつ lhsKind が assignment である場合、thenAssert : lhs は LeftHandSideExpression である。assignmentPattern を、lhs によってカバーされる AssignmentPattern とする。Repeat,nextResult を ? Call (iteratorRecord .[[NextMethod]] , iteratorRecord .[[Iterator]] ) とする。iteratorKind が async である場合、nextResult を ? Await (nextResult ) に設定する。nextResult が Object でない場合、TypeError 例外を投げる。done を ? IteratorComplete (nextResult ) とする。done が true である場合、iterationResult を返す。nextValue を ? IteratorValue (nextResult ) とする。lhsKind が assignment または var-binding のいずれかである場合、thendestructuring が true である場合、thenlhsKind が assignment である場合、thenstatus を、引数 nextValue で assignmentPattern の DestructuringAssignmentEvaluation の Completion とする。Else,Assert : lhsKind は var-binding である。Assert : lhs は ForBinding である。status を、引数 nextValue および undefined で lhs の BindingInitialization の Completion とする。 Else,lhsRef を lhs の Evaluation の Completion とする。(これは繰り返し評価されることがある。)lhsKind が assignment であり、かつ lhs の AssignmentTargetType が web-compat である場合、ReferenceError 例外を投げる。lhsRef が abrupt completion である場合、thenstatus を lhsRef とする。Else,status を Completion (PutValue (lhsRef .[[Value]] , nextValue )) とする。 iterationEnv を undefined とする。Else,Assert : lhsKind は lexical-binding である。Assert : lhs は ForDeclaration である。iterationEnv を NewDeclarativeEnvironment (oldEnv ) とする。引数 iterationEnv で lhs の ForDeclarationBindingInstantiation を実行する。 実行中の実行コンテキストの LexicalEnvironment を iterationEnv に設定する。 destructuring が true である場合、thenstatus を、引数 nextValue および iterationEnv で lhs の ForDeclarationBindingInitialization の Completion とする。Else,Assert : lhs は単一の名前を束縛する。lhsName を lhs の BoundNames の唯一の要素とする。lhsRef を ! ResolveBinding (lhsName ) とする。declarationKind が normal でない場合、thenAssert : IsUnresolvableReference (lhsRef ) は false である。base を lhsRef .[[Base]] とする。Assert : base は Declarative Environment Record である。status を Completion (AddDisposableResource (base .[[DisposableResourceStack]] , nextValue , declarationKind )) とする。Else,status を NormalCompletion (unused ) とする。 status が normal completion である場合、thenstatus を Completion (InitializeReferencedBinding (lhsRef , nextValue )) に設定する。 status が abrupt completion である場合、theniterationEnv が undefined でない場合、thenstatus を Completion (DisposeResources (iterationEnv .[[DisposableResourceStack]] , status )) に設定する。Assert : status は abrupt completion である。実行中の実行コンテキストの LexicalEnvironment を oldEnv に設定する。 iterationKind が enumerate である場合、return ? status .Assert : iterationKind は iterate である。iteratorKind が async である場合、return ? AsyncIteratorClose (iteratorRecord , status ).Return ? IteratorClose (iteratorRecord , status ). result を stmt の Evaluation の Completion とする。iterationEnv が undefined でない場合、thenresult を Completion (DisposeResources (iterationEnv .[[DisposableResourceStack]] , result )) に設定する。実行中の実行コンテキストの LexicalEnvironment を oldEnv に設定する。 LoopContinues (result , labelSet ) が false である場合、thenstatus を Completion (UpdateEmpty (result , iterationResult )) に設定する。iterationKind が enumerate である場合、return ? status .Assert : iterationKind は iterate である。iteratorKind が async である場合、return ? AsyncIteratorClose (iteratorRecord , status ).Return ? IteratorClose (iteratorRecord , status ). result .[[Value]] が empty でない場合、iterationResult を result .[[Value]] に設定する。
14.7.5.8 Runtime Semantics: Evaluation
BindingIdentifier :
Identifier
yield
await
bindingId をBindingIdentifier のStringValue とする。? 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:
obj のenumerable propertiesのString値keysすべてを反復するnext methodを持つiterator object を返す。iterator object はECMAScript codeから直接accessできることは決してありません。propertiesをenumeratingするmechanicsおよびorderは指定されませんが、以下で指定されるrulesにconformしなければなりません。
iterator のthrowおよびreturn methodsはnull であり、決して呼び出されません。iterator のnext methodは、property key をiterator valueとして返すべきかどうかを判定するためにobject propertiesを処理します。返されるproperty keys にはSymbolsであるkeysは含まれません。target objectのpropertiesはenumeration中に削除される場合があります。iterator のnext methodによって処理される前に削除されたpropertyは無視されます。enumeration中にtarget objectへ新しいpropertiesが追加された場合、新しく追加されたpropertiesはactive enumerationで処理されることが保証されません。property name は、どのenumerationでもiterator のnext methodによって最大1回だけ返されます。
target objectのpropertiesをenumeratingすることには、そのprototype、そのprototypeのprototype、以下同様にrecursiveにpropertiesをenumeratingすることが含まれます;ただし、prototypeのpropertyは、iterator のnext 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 object 、TypedArray 、module 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:
iterator をOrdinaryObjectCreate (%ForInIteratorPrototype% , « [[Object]] , [[ObjectWasVisited]] , [[VisitedKeys]] , [[RemainingKeys]] »)とする。iterator .[[Object]] をobj に設定する。iterator .[[ObjectWasVisited]] をfalse に設定する。iterator .[[VisitedKeys]] を新しい空のList に設定する。iterator .[[RemainingKeys]] を新しい空のList に設定する。iterator を返す。
14.7.5.10.2 The %ForInIteratorPrototype% Object
%ForInIteratorPrototype% object:
14.7.5.10.2.1 %ForInIteratorPrototype%.next ( )
iterator をthis valueとする。Assert : iterator はObjectである。Assert : iterator はFor-In Iterator instanceのinternal slotsすべてを持つ(14.7.5.10.3 )。obj をiterator .[[Object]] とする。繰り返すiterator .[[ObjectWasVisited]] がfalse なら、keys を ? obj .[[OwnPropertyKeys]] () とする。keys の各要素key について、以下を行うkey がStringなら、key をiterator .[[RemainingKeys]] へappendする。iterator .[[ObjectWasVisited]] をtrue に設定する。iterator .[[RemainingKeys]] が空でない間、繰り返すkey をiterator .[[RemainingKeys]] の最初の要素とする。iterator .[[RemainingKeys]] から最初の要素をremoveする。iterator .[[VisitedKeys]] がkey を含まないなら、propertyDesc を ? obj .[[GetOwnProperty]] (key ) とする。propertyDesc がundefined でないなら、key をiterator .[[VisitedKeys]] へappendする。propertyDesc .[[Enumerable]] がtrue なら、CreateIteratorResultObject (key , false )を返す。obj を ? obj .[[GetPrototypeOf]] () に設定する。iterator .[[Object]] をobj に設定する。iterator .[[ObjectWasVisited]] をfalse に設定する。obj がnull なら、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
;
14.8.2 Runtime Semantics: Evaluation
ContinueStatement :
continue
;
Completion Record { [[Type]] : continue , [[Value]] : empty , [[Target]] : empty }を返す。
ContinueStatement :
continue
LabelIdentifier
;
label をLabelIdentifier のStringValue とする。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
;
14.9.2 Runtime Semantics: Evaluation
BreakStatement :
break
;
Completion Record { [[Type]] : break , [[Value]] : empty , [[Target]] : empty }を返す。
BreakStatement :
break
LabelIdentifier
;
label をLabelIdentifier のStringValue とする。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 Record がfinally blockのevaluation中に別のCompletion Record へ置き換えられる場合があります。
14.10.1 Runtime Semantics: Evaluation
ReturnStatement :
return
;
ReturnCompletion (undefined )を返す。
ReturnStatement :
return
Expression
;
exprRef をExpression の ? Evaluation とする。exprValue を ? GetValue (exprRef ) とする。GetGeneratorKind ()がasync なら、exprValue を ? Await (exprValue ) に設定する。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 Record をrunning 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
value をExpression の ? Evaluation とする。obj を ? ToObject (? GetValue (value )) とする。oldEnv をrunning execution context のLexicalEnvironmentとする。newEnv をNewObjectEnvironment (obj , true , oldEnv )とする。running execution context のLexicalEnvironmentをnewEnv に設定する。stmtCompletion をStatement のEvaluation のCompletion とする。running execution context のLexicalEnvironmentをoldEnv に設定する。? 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 :
{
}
undefined を返す。
CaseBlock :
{
CaseClauses
}
resultValue をundefined とする。caseClauses を、source text orderにおけるCaseClauses 内のCaseClause itemsのList とする。found をfalse とする。caseClauses の各CaseClause clause について、以下を行うfound がfalse なら、found を ? CaseClauseIsSelected (clause , input ) に設定する。found がtrue なら、completion をclause のEvaluation のCompletion とする。completion .[[Value]] がempty でないなら、resultValue をcompletion .[[Value]] に設定する。completion がabrupt completion なら、? UpdateEmpty (completion , resultValue )を返す。resultValue を返す。
CaseBlock :
{
CaseClauses opt
DefaultClause
CaseClauses opt
}
resultValue をundefined とする。最初のCaseClauses が存在するなら、caseClauses を、source text orderにおける最初のCaseClauses 内のCaseClause itemsのList とする。 そうでなければ、caseClauses を新しい空のList とする。 found をfalse とする。caseClauses の各CaseClause clause について、以下を行うfound がfalse なら、found を ? CaseClauseIsSelected (clause , input ) に設定する。found がtrue なら、completion をclause のEvaluation のCompletion とする。completion .[[Value]] がempty でないなら、resultValue をcompletion .[[Value]] に設定する。completion がabrupt completion なら、? UpdateEmpty (completion , resultValue )を返す。foundInB をfalse とする。2番目のCaseClauses が存在するなら、secondCaseClauses を、source text orderにおける2番目のCaseClauses 内のCaseClause itemsのList とする。 そうでなければ、secondCaseClauses を新しい空のList とする。 found がfalse なら、secondCaseClauses の各CaseClause clause について、以下を行うfoundInB がfalse なら、foundInB を ? CaseClauseIsSelected (clause , input ) に設定する。foundInB がtrue なら、completion をCaseClause clause のEvaluation のCompletion とする。completion .[[Value]] がempty でないなら、resultValue をcompletion .[[Value]] に設定する。completion がabrupt completion なら、? UpdateEmpty (completion , resultValue )を返す。foundInB がtrue なら、resultValue を返す。defaultR をDefaultClause のEvaluation のCompletion とする。defaultR .[[Value]] がempty でないなら、resultValue をdefaultR .[[Value]] に設定する。defaultR がabrupt completion なら、? UpdateEmpty (defaultR , resultValue )を返す。NOTE : 以下は2番目のCaseClauses のもう1つの完全なiterationです。secondCaseClauses の各CaseClause clause について、以下を行うcompletion をCaseClause clause のEvaluation のCompletion とする。completion .[[Value]] がempty でないなら、resultValue をcompletion .[[Value]] に設定する。completion がabrupt completion なら、? UpdateEmpty (completion , resultValue )を返す。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 . これはcaseClauseNode がinput にmatchするかどうかを判定します。 It performs the following steps when called:
Assert : caseClauseNode はproduction
CaseClause :
case
Expression
:
StatementList opt
のinstanceである。exprRef をcaseClauseNode のExpression の ? Evaluation とする。clauseSelector を ? GetValue (exprRef ) とする。IsStrictlyEqual (input , clauseSelector )を返す。
Note
このoperationはcaseClauseNode のStatementList (存在する場合)を実行しません。CaseBlock algorithmは、どのStatementList の実行を開始するかを判定するためにそのreturn valueを使用します。
14.12.4 Runtime Semantics: Evaluation
SwitchStatement :
switch
(
Expression
)
CaseBlock
exprRef を Expression の Evaluation とする。switchValue を ? GetValue (exprRef ) とする。oldEnv を、実行中の実行コンテキストの LexicalEnvironment とする。blockEnv を NewDeclarativeEnvironment (oldEnv ) とする。BlockDeclarationInstantiation (CaseBlock , blockEnv ) を実行する。実行中の実行コンテキストの LexicalEnvironment を blockEnv に設定する。 blockResult を、引数 switchValue で CaseBlock の CaseBlockEvaluation の Completion とする。Assert : blockEnv .[[DisposableResourceStack]] は空の List である。実行中の実行コンテキストの LexicalEnvironment を oldEnv に設定する。 Return blockResult .
Note
controlがどのようにSwitchStatement から離れても、LexicalEnvironmentは常に以前のstateへ復元されます。
CaseClause :
case
Expression
:
empty を返す。
CaseClause :
case
Expression
:
StatementList
StatementList の ? Evaluation を返す。
DefaultClause :
default
:
empty を返す。
DefaultClause :
default
:
StatementList
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はありません。Statement はLabelledStatement の一部であり得、それ自体がLabelledStatement の一部であり得、以下同様です。この方法でintroducedされるlabelsは、個々のstatementsのsemanticsを記述するとき、collectivelyに“current label set”と呼ばれます。
14.13.1 Static Semantics: Early Errors
LabelledItem : FunctionDeclaration
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:
stmt がLabelledStatement でないなら、false を返す。item をstmt のLabelledItem とする。item が
LabelledItem : FunctionDeclaration
なら、true を返す。subStmt をitem のStatement とする。IsLabelledFunction (subStmt )を返す。
14.13.3 Runtime Semantics: Evaluation
LabelledStatement :
LabelIdentifier
:
LabelledItem
引数« »を伴う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
stmtResult を、引数labelSet を伴うIterationStatement のLoopEvaluation のCompletion とする。stmtResult がbreak completion なら、stmtResult .[[Target]] がempty なら、stmtResult .[[Value]] がempty なら、stmtResult をNormalCompletion (undefined )に設定する。そうでなければ、stmtResult をNormalCompletion (stmtResult .[[Value]] )に設定する。 ? stmtResult を返す。
BreakableStatement : SwitchStatement
stmtResult をSwitchStatement のEvaluation のCompletion とする。stmtResult がbreak completion なら、stmtResult .[[Target]] がempty なら、stmtResult .[[Value]] がempty なら、stmtResult をNormalCompletion (undefined )に設定する。そうでなければ、stmtResult をNormalCompletion (stmtResult .[[Value]] )に設定する。 ? stmtResult を返す。
Note 1
LabelledStatement :
LabelIdentifier
:
LabelledItem
label をLabelIdentifier のStringValue とする。newLabelSet をlabelSet と« label »のlist-concatenation とする。stmtResult を、引数newLabelSet を伴うLabelledItem のLabelledEvaluation のCompletion とする。stmtResult がbreak completion であり、かつstmtResult .[[Target]] がlabel であるなら、stmtResult をNormalCompletion (stmtResult .[[Value]] )に設定する。? stmtResult を返す。
LabelledItem : FunctionDeclaration
FunctionDeclaration の ? Evaluation を返す。
Statement :
BlockStatement
VariableStatement
EmptyStatement
ExpressionStatement
IfStatement
ContinueStatement
BreakStatement
ReturnStatement
WithStatement
ThrowStatement
TryStatement
DebuggerStatement
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
;
exprRef をExpression の ? Evaluation とする。exprValue を ? GetValue (exprRef ) とする。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
oldEnv をrunning execution context のLexicalEnvironmentとする。catchEnv をNewDeclarativeEnvironment (oldEnv )とする。CatchParameter のBoundNames の各要素argName について、以下を行う! catchEnv .CreateMutableBinding (argName , false )を実行する。 running execution context のLexicalEnvironmentをcatchEnv に設定する。status を、引数thrownValue およびcatchEnv を伴うCatchParameter のBindingInitialization のCompletion とする。status がabrupt completion なら、running execution context のLexicalEnvironmentをoldEnv に設定する。? status を返す。 blockCompletion をBlock のEvaluation のCompletion とする。running execution context のLexicalEnvironmentをoldEnv に設定する。? blockCompletion を返す。
Catch :
catch
Block
Block の ? Evaluation を返す。
Note
controlがどのようにBlock から離れても、LexicalEnvironmentは常に以前のstateへ復元されます。
14.15.3 Runtime Semantics: Evaluation
TryStatement :
try
Block
Catch
blockResult をBlock のEvaluation のCompletion とする。blockResult がthrow completion なら、catchResult を、引数blockResult .[[Value]] を伴うCatch のCatchClauseEvaluation のCompletion とする。そうでなければ、catchResult をblockResult とする。 ? UpdateEmpty (catchResult , undefined )を返す。
TryStatement :
try
Block
Finally
blockResult をBlock のEvaluation のCompletion とする。finallyResult をFinally のEvaluation のCompletion とする。finallyResult がnormal completion なら、finallyResult をblockResult に設定する。? UpdateEmpty (finallyResult , undefined )を返す。
TryStatement :
try
Block
Catch
Finally
blockResult をBlock のEvaluation のCompletion とする。blockResult がthrow completion なら、catchResult を、引数blockResult .[[Value]] を伴うCatch のCatchClauseEvaluation のCompletion とする。そうでなければ、catchResult をblockResult とする。 finallyResult をFinally のEvaluation のCompletion とする。finallyResult がnormal completion なら、finallyResult をcatchResult に設定する。? 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
;
implementation-defined debugging facilityがavailableかつenabledであるなら、implementation-defined debugging actionを実行する。新しいimplementation-defined Completion Record を返す。 empty を返す。
15 ECMAScript Language: Functions and Classes
Note
さまざまなECMAScript language elementsは、ECMAScript function objects (10.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
}
false を返す。
ObjectBindingPattern :
{
BindingPropertyList
,
BindingRestProperty
}
BindingPropertyList のContainsExpression を返す。
ArrayBindingPattern :
[
Elision opt
]
false を返す。
ArrayBindingPattern :
[
Elision opt
BindingRestElement
]
BindingRestElement のContainsExpression を返す。
ArrayBindingPattern :
[
BindingElementList
,
Elision opt
]
BindingElementList のContainsExpression を返す。
ArrayBindingPattern :
[
BindingElementList
,
Elision opt
BindingRestElement
]
has をBindingElementList のContainsExpression とする。has がtrue なら、true を返す。BindingRestElement のContainsExpression を返す。
BindingPropertyList :
BindingPropertyList
,
BindingProperty
has をBindingPropertyList のContainsExpression とする。has がtrue なら、true を返す。BindingProperty のContainsExpression を返す。
BindingElementList :
BindingElementList
,
BindingElisionElement
has をBindingElementList のContainsExpression とする。has がtrue なら、true を返す。BindingElisionElement のContainsExpression を返す。
BindingElisionElement :
Elision opt
BindingElement
BindingElement のContainsExpression を返す。
BindingProperty :
PropertyName
:
BindingElement
has をPropertyName のIsComputedPropertyKey とする。has がtrue なら、true を返す。BindingElement のContainsExpression を返す。
BindingElement :
BindingPattern
Initializer
true を返す。
SingleNameBinding : BindingIdentifier
false を返す。
SingleNameBinding :
BindingIdentifier
Initializer
true を返す。
BindingRestElement :
...
BindingIdentifier
false を返す。
BindingRestElement :
...
BindingPattern
BindingPattern のContainsExpression を返す。
FormalParameters : [empty]
false を返す。
FormalParameters :
FormalParameterList
,
FunctionRestParameter
FormalParameterList のContainsExpression がtrue なら、true を返す。FunctionRestParameter のContainsExpression を返す。
FormalParameterList :
FormalParameterList
,
FormalParameter
FormalParameterList のContainsExpression がtrue なら、true を返す。FormalParameter のContainsExpression を返す。
ArrowParameters : BindingIdentifier
false を返す。
ArrowParameters : CoverParenthesizedExpressionAndArrowParameterList
formals をCoverParenthesizedExpressionAndArrowParameterList によってcoverされるArrowFormalParameters とする。formals のContainsExpression を返す。
AsyncArrowBindingIdentifier : BindingIdentifier
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
false を返す。
BindingElement :
BindingPattern
Initializer
false を返す。
SingleNameBinding : BindingIdentifier
true を返す。
SingleNameBinding :
BindingIdentifier
Initializer
false を返す。
FormalParameters : [empty]
true を返す。
FormalParameters : FunctionRestParameter
false を返す。
FormalParameters :
FormalParameterList
,
FunctionRestParameter
false を返す。
FormalParameterList :
FormalParameterList
,
FormalParameter
FormalParameterList のIsSimpleParameterList がfalse なら、false を返す。FormalParameter のIsSimpleParameterList を返す。
FormalParameter : BindingElement
BindingElement のIsSimpleParameterList を返す。
ArrowParameters : BindingIdentifier
true を返す。
ArrowParameters : CoverParenthesizedExpressionAndArrowParameterList
formals をCoverParenthesizedExpressionAndArrowParameterList によってcoverされるArrowFormalParameters とする。formals のIsSimpleParameterList を返す。
AsyncArrowBindingIdentifier : BindingIdentifier
true を返す。
CoverCallExpressionAndAsyncArrowHead :
MemberExpression
Arguments
head をCoverCallExpressionAndAsyncArrowHead によってcoverされるAsyncArrowHead とする。head のIsSimpleParameterList を返す。
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
false を返す。
BindingElement :
BindingPattern
Initializer
true を返す。
SingleNameBinding : BindingIdentifier
false を返す。
SingleNameBinding :
BindingIdentifier
Initializer
true を返す。
FormalParameterList :
FormalParameterList
,
FormalParameter
FormalParameterList のHasInitializer がtrue なら、true を返す。FormalParameter のHasInitializer を返す。
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
0を返す。
FormalParameters :
FormalParameterList
,
FunctionRestParameter
FormalParameterList のExpectedArgumentCount を返す。
Note
FormalParameterList のExpectedArgumentCountは、rest parameterまたはInitializerを持つ最初のFormalParameter のいずれかの左側にあるFormalParameters の数です。initializerを持たないFormalParameter は、initializerを持つ最初のparameterの後に許可されますが、そのようなparametersはundefined をdefault valueとするoptionalと見なされます。
FormalParameterList : FormalParameter
FormalParameter のHasInitializer がtrue なら、0を返す。1を返す。
FormalParameterList :
FormalParameterList
,
FormalParameter
count をFormalParameterList のExpectedArgumentCount とする。FormalParameterList のHasInitializer がtrue 、またはFormalParameter のHasInitializer がtrue なら、count を返す。count + 1を返す。
ArrowParameters : BindingIdentifier
1を返す。
ArrowParameters : CoverParenthesizedExpressionAndArrowParameterList
formals をCoverParenthesizedExpressionAndArrowParameterList によってcoverされるArrowFormalParameters とする。formals のExpectedArgumentCount を返す。
PropertySetParameterList : FormalParameter
FormalParameter のHasInitializer がtrue なら、0を返す。1を返す。
AsyncArrowBindingIdentifier : BindingIdentifier
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
BindingIdentifier opt
(
FormalParameters
)
{
FunctionBody
}
Note
FunctionBody のLexicallyDeclaredNames には、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
FunctionBody のDirective Prologue がUse Strict Directive を含むなら、true を返す。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
? FunctionDeclarationInstantiation (funcObj , argList )を実行する。 FunctionStatementList の ? Evaluation を実行する。NOTE : previous stepがnormal completion をもたらした場合、evaluationはFunctionStatementList の終端を越えて進むことで終了した。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
}
name をBindingIdentifier のStringValue とする。sourceText をFunctionDeclaration によってmatchされたsource textとする。closure をOrdinaryFunctionCreate (%Function.prototype% , sourceText , FormalParameters , FunctionBody , non-lexical-this , envRecord , privateEnv )とする。SetFunctionName (closure , name )を実行する。MakeConstructor (closure )を実行する。closure を返す。
FunctionDeclaration :
function
(
FormalParameters
)
{
FunctionBody
}
sourceText をFunctionDeclaration によってmatchされたsource textとする。closure をOrdinaryFunctionCreate (%Function.prototype% , sourceText , FormalParameters , FunctionBody , non-lexical-this , envRecord , privateEnv )とする。SetFunctionName (closure , "default" )を実行する。MakeConstructor (closure )を実行する。closure を返す。
Note
anonymous FunctionDeclaration はexport 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
}
name が存在しない場合、name をempty Stringに設定する。envRecord をrunning execution context のLexicalEnvironmentとする。privateEnv をrunning execution context のPrivateEnvironmentとする。sourceText をFunctionExpression によってmatchされたsource textとする。closure をOrdinaryFunctionCreate (%Function.prototype% , sourceText , FormalParameters , FunctionBody , non-lexical-this , envRecord , privateEnv )とする。SetFunctionName (closure , name )を実行する。MakeConstructor (closure )を実行する。closure を返す。
FunctionExpression :
function
BindingIdentifier
(
FormalParameters
)
{
FunctionBody
}
Assert : name は存在しない。name をBindingIdentifier のStringValue に設定する。outerEnv をrunning execution context のLexicalEnvironmentとする。funcEnv をNewDeclarativeEnvironment (outerEnv )とする。! funcEnv .CreateImmutableBinding (name , false )を実行する。 privateEnv をrunning execution context のPrivateEnvironmentとする。sourceText をFunctionExpression によってmatchされたsource textとする。closure をOrdinaryFunctionCreate (%Function.prototype% , sourceText , FormalParameters , FunctionBody , non-lexical-this , funcEnv , privateEnv )とする。SetFunctionName (closure , name )を実行する。MakeConstructor (closure )を実行する。! funcEnv .InitializeBinding (name , closure )を実行する。 closure を返す。
Note
15.2.6 Runtime Semantics: Evaluation
FunctionDeclaration :
function
BindingIdentifier
(
FormalParameters
)
{
FunctionBody
}
empty を返す。
Note 1
FunctionDeclaration :
function
(
FormalParameters
)
{
FunctionBody
}
empty を返す。
FunctionExpression :
function
BindingIdentifier opt
(
FormalParameters
)
{
FunctionBody
}
FunctionExpression のInstantiateOrdinaryFunctionExpression を返す。
Note 2
FunctionDeclaration またはFunctionExpression を使用して定義されたすべてのfunctionには、そのfunctionがconstructor として使用される可能性を許容するために、"prototype" propertyが自動的に作成されます。
FunctionStatementList : [empty]
undefined を返す。
FunctionStatementList : StatementList
result を StatementList の Evaluation の Completion とする。env を、実行中の実行コンテキストの LexicalEnvironment とする。Assert : env は Declarative Environment Record である。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
false を返す。
ConciseBody :
{
FunctionBody
}
FunctionBody のFunctionBodyContainsUseStrict を返す。
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
? FunctionDeclarationInstantiation (funcObj , argList )を実行する。 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
name が存在しない場合、name をempty Stringに設定する。envRecord をrunning execution context のLexicalEnvironmentとする。privateEnv をrunning execution context のPrivateEnvironmentとする。sourceText をArrowFunction によってmatchされたsource textとする。closure をOrdinaryFunctionCreate (%Function.prototype% , sourceText , ArrowParameters , ConciseBody , lexical-this , envRecord , privateEnv )とする。SetFunctionName (closure , name )を実行する。closure を返す。
Note
ArrowFunction はarguments、super、this、またはnew.targetに対するlocal bindingsを定義しません。ArrowFunction 内のarguments、super、this、またはnew.targetへのreferenceはいずれも、lexically enclosing environment内のbindingへresolveされなければなりません。通常、これは直ちに囲むfunctionのFunction Environmentになります。ArrowFunction がsuperへのreferencesを含む場合でも、step 5 で作成されるfunction object はMakeMethod を実行することによってmethodにはされません。superをreferenceするArrowFunction は常にnon-ArrowFunction 内に含まれ、superを実装するために必要なstateは、ArrowFunction のfunction object によってcaptureされるenvRecord を介してaccessできます。
15.3.5 Runtime Semantics: Evaluation
ArrowFunction :
ArrowParameters
=>
ConciseBody
ArrowFunction のInstantiateArrowFunctionExpression を返す。
ExpressionBody : AssignmentExpression
exprRef をAssignmentExpression の ? Evaluation とする。exprValue を ? GetValue (exprRef ) とする。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
}
UniqueFormalParameters Contains SuperCall がtrue なら、true を返す。FunctionBody Contains SuperCall を返す。
MethodDefinition :
get
ClassElementName
(
)
{
FunctionBody
}
FunctionBody Contains SuperCall を返す。
MethodDefinition :
set
ClassElementName
(
PropertySetParameterList
)
{
FunctionBody
}
PropertySetParameterList Contains SuperCall がtrue なら、true を返す。FunctionBody Contains SuperCall を返す。
GeneratorMethod :
*
ClassElementName
(
UniqueFormalParameters
)
{
GeneratorBody
}
UniqueFormalParameters Contains SuperCall がtrue なら、true を返す。GeneratorBody Contains SuperCall を返す。
AsyncGeneratorMethod :
async
*
ClassElementName
(
UniqueFormalParameters
)
{
AsyncGeneratorBody
}
UniqueFormalParameters Contains SuperCall がtrue なら、true を返す。AsyncGeneratorBody Contains SuperCall を返す。
AsyncMethod :
async
ClassElementName
(
UniqueFormalParameters
)
{
AsyncFunctionBody
}
UniqueFormalParameters Contains SuperCall がtrue なら、true を返す。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
}
false を返す。
MethodDefinition :
GeneratorMethod
AsyncMethod
AsyncGeneratorMethod
get
ClassElementName
(
)
{
FunctionBody
}
set
ClassElementName
(
PropertySetParameterList
)
{
FunctionBody
}
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
}
propertyKey をClassElementName の ? Evaluation とする。envRecord をrunning execution context のLexicalEnvironmentとする。privateEnv をrunning execution context のPrivateEnvironmentとする。proto が存在しないなら、proto を%Function.prototype% に設定する。sourceText をMethodDefinition によってmatchされたsource textとする。closure をOrdinaryFunctionCreate (proto , sourceText , UniqueFormalParameters , FunctionBody , non-lexical-this , envRecord , privateEnv )とする。MakeMethod (closure , obj )を実行する。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
}
methodDef を、argument obj を伴うMethodDefinition の ? DefineMethod とする。SetFunctionName (methodDef .[[Closure]] , methodDef .[[Key]] )を実行する。? DefineMethodProperty (obj , methodDef .[[Key]] , methodDef .[[Closure]] , enumerable )を返す。
MethodDefinition :
get
ClassElementName
(
)
{
FunctionBody
}
propertyKey をClassElementName の ? Evaluation とする。envRecord をrunning execution context のLexicalEnvironmentとする。privateEnv をrunning execution context のPrivateEnvironmentとする。sourceText をMethodDefinition によってmatchされたsource textとする。formalParamList をproduction
FormalParameters : [empty]
のinstanceとする。closure をOrdinaryFunctionCreate (%Function.prototype% , sourceText , formalParamList , FunctionBody , non-lexical-this , envRecord , privateEnv )とする。MakeMethod (closure , obj )を実行する。SetFunctionName (closure , propertyKey , "get" )を実行する。propertyKey がPrivate Name なら、PrivateElement { [[Key]] : propertyKey , [[Kind]] : accessor , [[Get]] : closure , [[Set]] : undefined }を返す。propertyDesc をPropertyDescriptor { [[Get]] : closure , [[Enumerable]] : enumerable , [[Configurable]] : true }とする。? DefinePropertyOrThrow (obj , propertyKey , propertyDesc )を実行する。 unused を返す。
MethodDefinition :
set
ClassElementName
(
PropertySetParameterList
)
{
FunctionBody
}
propertyKey をClassElementName の ? Evaluation とする。envRecord をrunning execution context のLexicalEnvironmentとする。privateEnv をrunning execution context のPrivateEnvironmentとする。sourceText をMethodDefinition によってmatchされたsource textとする。closure をOrdinaryFunctionCreate (%Function.prototype% , sourceText , PropertySetParameterList , FunctionBody , non-lexical-this , envRecord , privateEnv )とする。MakeMethod (closure , obj )を実行する。SetFunctionName (closure , propertyKey , "set" )を実行する。propertyKey がPrivate Name なら、PrivateElement { [[Key]] : propertyKey , [[Kind]] : accessor , [[Get]] : undefined , [[Set]] : closure }を返す。propertyDesc をPropertyDescriptor { [[Set]] : closure , [[Enumerable]] : enumerable , [[Configurable]] : true }とする。? DefinePropertyOrThrow (obj , propertyKey , propertyDesc )を実行する。 unused を返す。
GeneratorMethod :
*
ClassElementName
(
UniqueFormalParameters
)
{
GeneratorBody
}
propertyKey をClassElementName の ? Evaluation とする。envRecord をrunning execution context のLexicalEnvironmentとする。privateEnv をrunning execution context のPrivateEnvironmentとする。sourceText をGeneratorMethod によってmatchされたsource textとする。closure をOrdinaryFunctionCreate (%GeneratorFunction.prototype% , sourceText , UniqueFormalParameters , GeneratorBody , non-lexical-this , envRecord , privateEnv )とする。MakeMethod (closure , obj )を実行する。SetFunctionName (closure , propertyKey )を実行する。proto をOrdinaryObjectCreate (%GeneratorPrototype% )とする。! DefinePropertyOrThrow (closure , "prototype" , PropertyDescriptor { [[Value]] : proto , [[Writable]] : true , [[Enumerable]] : false , [[Configurable]] : false })を実行する。 ? DefineMethodProperty (obj , propertyKey , closure , enumerable )を返す。
AsyncGeneratorMethod :
async
*
ClassElementName
(
UniqueFormalParameters
)
{
AsyncGeneratorBody
}
propertyKey をClassElementName の ? Evaluation とする。envRecord をrunning execution context のLexicalEnvironmentとする。privateEnv をrunning execution context のPrivateEnvironmentとする。sourceText をAsyncGeneratorMethod によってmatchされたsource textとする。closure をOrdinaryFunctionCreate (%AsyncGeneratorFunction.prototype% , sourceText , UniqueFormalParameters , AsyncGeneratorBody , non-lexical-this , envRecord , privateEnv )とする。MakeMethod (closure , obj )を実行する。SetFunctionName (closure , propertyKey )を実行する。proto をOrdinaryObjectCreate (%AsyncGeneratorPrototype% )とする。! DefinePropertyOrThrow (closure , "prototype" , PropertyDescriptor { [[Value]] : proto , [[Writable]] : true , [[Enumerable]] : false , [[Configurable]] : false })を実行する。 ? DefineMethodProperty (obj , propertyKey , closure , enumerable )を返す。
AsyncMethod :
async
ClassElementName
(
UniqueFormalParameters
)
{
AsyncFunctionBody
}
propertyKey をClassElementName の ? Evaluation とする。envRecord をrunning execution context のLexicalEnvironmentとする。privateEnv をrunning execution context のPrivateEnvironmentとする。sourceText をAsyncMethod によってmatchされたsource textとする。closure をOrdinaryFunctionCreate (%AsyncFunction.prototype% , sourceText , UniqueFormalParameters , AsyncFunctionBody , non-lexical-this , envRecord , privateEnv )とする。MakeMethod (closure , obj )を実行する。SetFunctionName (closure , propertyKey )を実行する。? 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
15.5.1 Static Semantics: Early Errors
GeneratorMethod :
*
ClassElementName
(
UniqueFormalParameters
)
{
GeneratorBody
}
GeneratorDeclaration :
function
*
BindingIdentifier
(
FormalParameters
)
{
GeneratorBody
}
function
*
(
FormalParameters
)
{
GeneratorBody
}
GeneratorExpression :
function
*
BindingIdentifier opt
(
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
? FunctionDeclarationInstantiation (funcObj , argList )を実行する。 gen を ? OrdinaryCreateFromConstructor (funcObj , "%GeneratorPrototype%" , « [[GeneratorState]] , [[GeneratorContext]] , [[GeneratorBrand]] ») とする。gen .[[GeneratorBrand]] をempty に設定する。gen .[[GeneratorState]] をsuspended-start に設定する。GeneratorStart (gen , FunctionBody )を実行する。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
}
name をBindingIdentifier のStringValue とする。sourceText をGeneratorDeclaration によってmatchされたsource textとする。closure をOrdinaryFunctionCreate (%GeneratorFunction.prototype% , sourceText , FormalParameters , GeneratorBody , non-lexical-this , envRecord , privateEnv )とする。SetFunctionName (closure , name )を実行する。proto をOrdinaryObjectCreate (%GeneratorPrototype% )とする。! DefinePropertyOrThrow (closure , "prototype" , PropertyDescriptor { [[Value]] : proto , [[Writable]] : true , [[Enumerable]] : false , [[Configurable]] : false })を実行する。 closure を返す。
GeneratorDeclaration :
function
*
(
FormalParameters
)
{
GeneratorBody
}
sourceText をGeneratorDeclaration によってmatchされたsource textとする。closure をOrdinaryFunctionCreate (%GeneratorFunction.prototype% , sourceText , FormalParameters , GeneratorBody , non-lexical-this , envRecord , privateEnv )とする。SetFunctionName (closure , "default" )を実行する。proto をOrdinaryObjectCreate (%GeneratorPrototype% )とする。! DefinePropertyOrThrow (closure , "prototype" , PropertyDescriptor { [[Value]] : proto , [[Writable]] : true , [[Enumerable]] : false , [[Configurable]] : false })を実行する。 closure を返す。
Note
anonymous GeneratorDeclaration はexport 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
}
name が存在しない場合、name をempty Stringに設定する。envRecord をrunning execution context のLexicalEnvironmentとする。privateEnv をrunning execution context のPrivateEnvironmentとする。sourceText をGeneratorExpression によってmatchされたsource textとする。closure をOrdinaryFunctionCreate (%GeneratorFunction.prototype% , sourceText , FormalParameters , GeneratorBody , non-lexical-this , envRecord , privateEnv )とする。SetFunctionName (closure , name )を実行する。proto をOrdinaryObjectCreate (%GeneratorPrototype% )とする。! DefinePropertyOrThrow (closure , "prototype" , PropertyDescriptor { [[Value]] : proto , [[Writable]] : true , [[Enumerable]] : false , [[Configurable]] : false })を実行する。 closure を返す。
GeneratorExpression :
function
*
BindingIdentifier
(
FormalParameters
)
{
GeneratorBody
}
Assert : name は存在しない。name をBindingIdentifier のStringValue に設定する。outerEnv をrunning execution context のLexicalEnvironmentとする。funcEnv をNewDeclarativeEnvironment (outerEnv )とする。! funcEnv .CreateImmutableBinding (name , false )を実行する。 privateEnv をrunning execution context のPrivateEnvironmentとする。sourceText をGeneratorExpression によってmatchされたsource textとする。closure をOrdinaryFunctionCreate (%GeneratorFunction.prototype% , sourceText , FormalParameters , GeneratorBody , non-lexical-this , funcEnv , privateEnv )とする。SetFunctionName (closure , name )を実行する。proto をOrdinaryObjectCreate (%GeneratorPrototype% )とする。! DefinePropertyOrThrow (closure , "prototype" , PropertyDescriptor { [[Value]] : proto , [[Writable]] : true , [[Enumerable]] : false , [[Configurable]] : false })を実行する。 ! funcEnv .InitializeBinding (name , closure )を実行する。 closure を返す。
Note
15.5.5 Runtime Semantics: Evaluation
GeneratorExpression :
function
*
BindingIdentifier opt
(
FormalParameters
)
{
GeneratorBody
}
GeneratorExpression のInstantiateGeneratorFunctionExpression を返す。
YieldExpression : yield
? Yield (undefined )を返す。
YieldExpression :
yield
AssignmentExpression
exprRef をAssignmentExpression の ? Evaluation とする。value を ? GetValue (exprRef ) とする。? Yield (value )を返す。
YieldExpression :
yield
*
AssignmentExpression
genKind をGetGeneratorKind ()とする。Assert : genKind はsync またはasync のいずれかである。exprRef をAssignmentExpression の ? Evaluation とする。value を ? GetValue (exprRef ) とする。iteratorRecord を ? GetIterator (value , genKind ) とする。iterator をiteratorRecord .[[Iterator]] とする。received をNormalCompletion (undefined )とする。繰り返すreceived がnormal completion なら、innerResult を ? Call (iteratorRecord .[[NextMethod]] , iteratorRecord .[[Iterator]] , « received .[[Value]] ») とする。genKind がasync なら、innerResult を ? Await (innerResult ) に設定する。innerResult がObjectでないなら、TypeError 例外をthrowする。done を ? IteratorComplete (innerResult ) とする。done がtrue なら、? IteratorValue (innerResult )を返す。 genKind がasync なら、received をCompletion (AsyncGeneratorYield (? IteratorValue (innerResult )))に設定する。そうでなければ、received をCompletion (GeneratorYield (innerResult ))に設定する。 そうでなく、received がthrow completion なら、throw を ? GetMethod (iterator , "throw" ) とする。throw がundefined でないなら、innerResult を ? Call (throw , iterator , « received .[[Value]] ») とする。genKind がasync なら、innerResult を ? Await (innerResult ) に設定する。NOTE : inner iterator のthrow methodからのexceptionsは伝播される。inner throw methodからのnormal completions は、inner nextと同様に処理される。innerResult がObjectでないなら、TypeError 例外をthrowする。done を ? IteratorComplete (innerResult ) とする。done がtrue なら、? IteratorValue (innerResult )を返す。 genKind がasync なら、received をCompletion (AsyncGeneratorYield (? IteratorValue (innerResult )))に設定する。そうでなければ、received をCompletion (GeneratorYield (innerResult ))に設定する。 そうでなければ、NOTE : iterator がthrow methodを持たない場合、このthrowはyield* loopを終了させることになる。しかし、まずiterator にclean upの機会を与える必要がある。closeCompletion をNormalCompletion (empty )とする。genKind がasync なら、? AsyncIteratorClose (iteratorRecord , closeCompletion )を実行する。そうでなければ、? IteratorClose (iteratorRecord , closeCompletion )を実行する。 NOTE : next stepは、yield* protocol violationがあったこと、すなわちiterator がthrow methodを持たないことを示すためにTypeError をthrowする。TypeError 例外をthrowする。 そうでなければ、Assert : received はreturn completion である。return を ? GetMethod (iterator , "return" ) とする。return がundefined なら、receivedValue をreceived .[[Value]] とする。genKind がasync なら、receivedValue を ? Await (receivedValue ) に設定する。ReturnCompletion (receivedValue )を返す。innerReturnResult を ? Call (return , iterator , « received .[[Value]] ») とする。genKind がasync なら、innerReturnResult を ? Await (innerReturnResult ) に設定する。innerReturnResult がObjectでないなら、TypeError 例外をthrowする。done を ? IteratorComplete (innerReturnResult ) とする。done がtrue なら、returnedValue を ? IteratorValue (innerReturnResult ) とする。ReturnCompletion (returnedValue )を返す。genKind がasync なら、received をCompletion (AsyncGeneratorYield (? IteratorValue (innerReturnResult )))に設定する。そうでなければ、received をCompletion (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 operations は27.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
*
BindingIdentifier opt
(
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
? FunctionDeclarationInstantiation (funcObj , argList )を実行する。 gen を ? OrdinaryCreateFromConstructor (funcObj , "%AsyncGeneratorPrototype%" , « [[AsyncGeneratorState]] , [[AsyncGeneratorContext]] , [[AsyncGeneratorQueue]] , [[GeneratorBrand]] ») とする。gen .[[GeneratorBrand]] をempty に設定する。gen .[[AsyncGeneratorState]] をsuspended-start に設定する。AsyncGeneratorStart (gen , FunctionBody )を実行する。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
}
name をBindingIdentifier のStringValue とする。sourceText をAsyncGeneratorDeclaration によってmatchされたsource textとする。closure をOrdinaryFunctionCreate (%AsyncGeneratorFunction.prototype% , sourceText , FormalParameters , AsyncGeneratorBody , non-lexical-this , envRecord , privateEnv )とする。SetFunctionName (closure , name )を実行する。proto をOrdinaryObjectCreate (%AsyncGeneratorPrototype% )とする。! DefinePropertyOrThrow (closure , "prototype" , PropertyDescriptor { [[Value]] : proto , [[Writable]] : true , [[Enumerable]] : false , [[Configurable]] : false })を実行する。 closure を返す。
AsyncGeneratorDeclaration :
async
function
*
(
FormalParameters
)
{
AsyncGeneratorBody
}
sourceText をAsyncGeneratorDeclaration によってmatchされたsource textとする。closure をOrdinaryFunctionCreate (%AsyncGeneratorFunction.prototype% , sourceText , FormalParameters , AsyncGeneratorBody , non-lexical-this , envRecord , privateEnv )とする。SetFunctionName (closure , "default" )を実行する。proto をOrdinaryObjectCreate (%AsyncGeneratorPrototype% )とする。! DefinePropertyOrThrow (closure , "prototype" , PropertyDescriptor { [[Value]] : proto , [[Writable]] : true , [[Enumerable]] : false , [[Configurable]] : false })を実行する。 closure を返す。
Note
anonymous AsyncGeneratorDeclaration はexport 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
}
name が存在しない場合、name をempty Stringに設定する。envRecord をrunning execution context のLexicalEnvironmentとする。privateEnv をrunning execution context のPrivateEnvironmentとする。sourceText をAsyncGeneratorExpression によってmatchされたsource textとする。closure をOrdinaryFunctionCreate (%AsyncGeneratorFunction.prototype% , sourceText , FormalParameters , AsyncGeneratorBody , non-lexical-this , envRecord , privateEnv )とする。SetFunctionName (closure , name )を実行する。proto をOrdinaryObjectCreate (%AsyncGeneratorPrototype% )とする。! DefinePropertyOrThrow (closure , "prototype" , PropertyDescriptor { [[Value]] : proto , [[Writable]] : true , [[Enumerable]] : false , [[Configurable]] : false })を実行する。 closure を返す。
AsyncGeneratorExpression :
async
function
*
BindingIdentifier
(
FormalParameters
)
{
AsyncGeneratorBody
}
Assert : name は存在しない。name をBindingIdentifier のStringValue に設定する。outerEnv をrunning execution context のLexicalEnvironmentとする。funcEnv をNewDeclarativeEnvironment (outerEnv )とする。! funcEnv .CreateImmutableBinding (name , false )を実行する。 privateEnv をrunning execution context のPrivateEnvironmentとする。sourceText をAsyncGeneratorExpression によってmatchされたsource textとする。closure をOrdinaryFunctionCreate (%AsyncGeneratorFunction.prototype% , sourceText , FormalParameters , AsyncGeneratorBody , non-lexical-this , funcEnv , privateEnv )とする。SetFunctionName (closure , name )を実行する。proto をOrdinaryObjectCreate (%AsyncGeneratorPrototype% )とする。! DefinePropertyOrThrow (closure , "prototype" , PropertyDescriptor { [[Value]] : proto , [[Writable]] : true , [[Enumerable]] : false , [[Configurable]] : false })を実行する。 ! funcEnv .InitializeBinding (name , closure )を実行する。 closure を返す。
Note
15.6.5 Runtime Semantics: Evaluation
AsyncGeneratorExpression :
async
function
*
BindingIdentifier opt
(
FormalParameters
)
{
AsyncGeneratorBody
}
AsyncGeneratorExpression のInstantiateAsyncGeneratorFunctionExpression を返す。
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 :
ClassHeritage opt
{
ClassBody
}
ClassBody : ClassElementList
ClassElement : MethodDefinition
ClassElement :
static
MethodDefinition
ClassElement :
FieldDefinition
;
ClassElement :
static
FieldDefinition
;
FieldDefinition :
ClassElementName
Initializer opt
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
MethodDefinition のPropName が"constructor" なら、constructor-method を返す。non-constructor-method を返す。
ClassElement :
static
MethodDefinition
FieldDefinition
;
static
FieldDefinition
;
non-constructor-method を返す。
ClassElement : ClassStaticBlock
non-constructor-method を返す。
ClassElement : ;
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
ClassElement のClassElementKind がconstructor-method なら、ClassElement を返す。empty を返す。
ClassElementList :
ClassElementList
ClassElement
head をClassElementList のConstructorMethod とする。head がempty でないなら、head を返す。ClassElement のClassElementKind がconstructor-method なら、ClassElement を返す。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
false を返す。
ClassElement :
static
MethodDefinition
true を返す。
ClassElement :
FieldDefinition
;
false を返す。
ClassElement :
static
FieldDefinition
;
true を返す。
ClassElement : ClassStaticBlock
true を返す。
ClassElement : ;
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
ClassElement のClassElementKind がnon-constructor-method なら、« ClassElement »を返す。 新しい空のList を返す。
ClassElementList :
ClassElementList
ClassElement
list をClassElementList のNonConstructorElements とする。ClassElement のClassElementKind がnon-constructor-method なら、ClassElement をlist へappendする。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
propertyName をClassElement のPropName とする。propertyName がempty なら、新しい空のList を返す。ClassElement のIsStatic がtrue なら、新しい空のList を返す。« propertyName »を返す。
ClassElementList :
ClassElementList
ClassElement
list をClassElementList のPrototypePropertyNameList とする。propertyName をClassElement のPropName とする。propertyName がempty なら、list を返す。ClassElement のIsStatic がtrue なら、list を返す。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を持ちます:
このParse Node の各child node child について、以下を行うchild がnonterminalのinstanceなら、argument names を伴うchild のAllPrivateIdentifiersValid がfalse なら、false を返す。 true を返す。
MemberExpression :
MemberExpression
.
PrivateIdentifier
names がPrivateIdentifier のStringValue を含むなら、argument names を伴うMemberExpression のAllPrivateIdentifiersValid を返す。 false を返す。
CallExpression :
CallExpression
.
PrivateIdentifier
names がPrivateIdentifier のStringValue を含むなら、argument names を伴うCallExpression のAllPrivateIdentifiersValid を返す。 false を返す。
OptionalChain :
?.
PrivateIdentifier
names がPrivateIdentifier のStringValue を含むなら、true を返す。false を返す。
OptionalChain :
OptionalChain
.
PrivateIdentifier
names がPrivateIdentifier のStringValue を含むなら、argument names を伴うOptionalChain のAllPrivateIdentifiersValid を返す。 false を返す。
ClassBody : ClassElementList
newNames をnames とClassBody のPrivateBoundIdentifiers のlist-concatenation とする。argument newNames を伴うClassElementList のAllPrivateIdentifiersValid を返す。
RelationalExpression :
PrivateIdentifier
in
ShiftExpression
names がPrivateIdentifier のStringValue を含むなら、argument names を伴うShiftExpression のAllPrivateIdentifiersValid を返す。 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
Initializer opt
ClassElementName のPrivateBoundIdentifiers を返す。
ClassElementName : PrivateIdentifier
唯一の要素がPrivateIdentifier のStringValue であるList を返す。
ClassElementName :
PropertyName
ClassElement :
ClassStaticBlock
;
新しい空のList を返す。
ClassElementList :
ClassElementList
ClassElement
names1 をClassElementList のPrivateBoundIdentifiers とする。names2 をClassElement のPrivateBoundIdentifiers とする。names1 とnames2 のlist-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
}
ClassElementName のPrivateBoundIdentifiers を返す。
15.7.9 Static Semantics: ContainsArguments
The syntax-directed operation ContainsArguments takes no arguments and returns a Boolean.
この仕様内で下に列挙されていないすべてのgrammar production alternativeは、暗黙的にContainsArgumentsの次のdefault definitionを持ちます:
このParse Node の各child node child について、以下を行うchild がnonterminalのinstanceなら、child のContainsArguments がtrue なら、true を返す。 false を返す。
IdentifierReference : Identifier
Identifier のStringValue が"arguments" なら、true を返す。false を返す。
FunctionDeclaration :
function
BindingIdentifier
(
FormalParameters
)
{
FunctionBody
}
function
(
FormalParameters
)
{
FunctionBody
}
FunctionExpression :
function
BindingIdentifier opt
(
FormalParameters
)
{
FunctionBody
}
GeneratorDeclaration :
function
*
BindingIdentifier
(
FormalParameters
)
{
GeneratorBody
}
function
*
(
FormalParameters
)
{
GeneratorBody
}
GeneratorExpression :
function
*
BindingIdentifier opt
(
FormalParameters
)
{
GeneratorBody
}
AsyncGeneratorDeclaration :
async
function
*
BindingIdentifier
(
FormalParameters
)
{
AsyncGeneratorBody
}
async
function
*
(
FormalParameters
)
{
AsyncGeneratorBody
}
AsyncGeneratorExpression :
async
function
*
BindingIdentifier opt
(
FormalParameters
)
{
AsyncGeneratorBody
}
AsyncFunctionDeclaration :
async
function
BindingIdentifier
(
FormalParameters
)
{
AsyncFunctionBody
}
async
function
(
FormalParameters
)
{
AsyncFunctionBody
}
AsyncFunctionExpression :
async
function
BindingIdentifier opt
(
FormalParameters
)
{
AsyncFunctionBody
}
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
}
ClassElementName のContainsArguments を返す。
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
Initializer opt
name をClassElementName の ? Evaluation とする。Initializer が存在するなら、formalParamList をproduction
FormalParameters : [empty]
のinstanceとする。envRecord をrunning execution context のLexicalEnvironmentとする。privateEnv をrunning execution context のPrivateEnvironmentとする。sourceText をUnicode code pointsのempty sequenceとする。initializer をOrdinaryFunctionCreate (%Function.prototype% , sourceText , formalParamList , Initializer , non-lexical-this , envRecord , privateEnv )とする。MakeMethod (initializer , homeObj )を実行する。initializer .[[ClassFieldInitializerName]] をname に設定する。そうでなければ、initializer をempty とする。 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
}
実行中の実行コンテキストのLexicalEnvironmentをlexicalEnv とする。 実行中の実行コンテキストのPrivateEnvironmentをprivateEnv とする。 空のUnicode符号点列をsourceText とする。 生成規則
FormalParameters : [empty]
のインスタンスをformalParams とする。 OrdinaryFunctionCreate (%Function.prototype% , sourceText , formalParams , ClassStaticBlockBody , non-lexical-this , lexicalEnv , privateEnv )をbodyFunc とする。MakeMethod (bodyFunc , homeObj )を実行する。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
Assert : funcObj は ClassStaticBlockDefinitionEvaluation ステップ 5 によって作成された合成関数である。! FunctionDeclarationInstantiation (funcObj , « ») を実行する。 result を ClassStaticBlockStatementList の Evaluation の Completion とする。envRecord を、実行中の実行コンテキストの LexicalEnvironment とする。Assert : envRecord は Declarative Environment Record である。? DisposeResources (envRecord .[[DisposableResourceStack]] , result ) を実行する。 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
;
argument obj を伴うFieldDefinition の ? ClassFieldDefinitionEvaluation を返す。
ClassElement :
MethodDefinition
static
MethodDefinition
arguments obj およびfalse を伴うMethodDefinition の ? MethodDefinitionEvaluation を返す。
ClassElement : ClassStaticBlock
argument obj を伴うClassStaticBlock のClassStaticBlockDefinitionEvaluation を返す。
ClassElement : ;
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 :
ClassHeritage opt
{
ClassBody opt
}
envRecord をrunning execution context のLexicalEnvironmentとする。classEnv をNewDeclarativeEnvironment (envRecord )とする。classBinding がundefined でないなら、! classEnv .CreateImmutableBinding (classBinding , true )を実行する。 outerPrivateEnv をrunning execution context のPrivateEnvironmentとする。classPrivateEnv をNewPrivateEnvironment (outerPrivateEnv )とする。ClassBody が存在するなら、ClassBody のPrivateBoundIdentifiers の各String description について、以下を行うclassPrivateEnv .[[Names]] が、[[Description]] がdescription であるPrivate Name privateName を含むなら、Assert : これはgetter/setter pairsの場合にのみ可能である。そうでなければ、name を、その[[Description]] がdescription である新しいPrivate Name とする。name をclassPrivateEnv .[[Names]] へappendする。 ClassHeritage が存在しないなら、protoParent を%Object.prototype% とする。ctorParent を%Function.prototype% とする。そうでなければ、running execution context のLexicalEnvironmentをclassEnv に設定する。NOTE : ClassHeritage を評価するとき、running execution context のPrivateEnvironmentはouterPrivateEnv である。superclassRef をClassHeritage のEvaluation のCompletion とする。running execution context のLexicalEnvironmentをenvRecord に設定する。superclass を ? GetValue (? superclassRef ) とする。superclass がnull なら、protoParent をnull とする。ctorParent を%Function.prototype% とする。そうでなく、IsConstructor (superclass )がfalse なら、TypeError 例外をthrowする。 そうでなければ、protoParent を ? Get (superclass , "prototype" ) とする。protoParent がObjectでなく、かつprotoParent がnull でないなら、TypeError 例外をthrowする。ctorParent をsuperclass とする。 proto をOrdinaryObjectCreate (protoParent )とする。ClassBody が存在しないなら、ctor をempty とする。そうでなければ、ctor をClassBody のConstructorMethod とする。 running execution context のLexicalEnvironmentをclassEnv に設定する。running execution context のPrivateEnvironmentをclassPrivateEnv に設定する。ctor がempty なら、defaultCtor を、parametersを持たず、何もcaptureせず、呼び出されたときに次のstepsを実行する新しいAbstract Closure とする:args を、このfunctionに[[Call]] または[[Construct]] によって渡されたargumentsのList とする。NewTargetがundefined なら、TypeError 例外をthrowする。 ctorFunc をactive function object とする。ctorFunc .[[ConstructorKind]] がderived なら、NOTE : このbranchはconstructor(...args) { super(...args); }と同様に振る舞う。最も注目すべき違いは、前述のECMAScript source text が%Array.prototype%上の%Symbol.iterator% methodをobservablyに呼び出すのに対し、このfunctionはそれを行わないことである。func を ! ctorFunc .[[GetPrototypeOf]] () とする。IsConstructor (func )がfalse なら、TypeError 例外をthrowする。result を ? Construct (func , args , NewTarget) とする。そうでなければ、NOTE : このbranchはconstructor() {}と同様に振る舞う。result を ? OrdinaryCreateFromConstructor (NewTarget, "%Object.prototype%" ) とする。 ? InitializeInstanceElements (result , ctorFunc )を実行する。 NormalCompletion (result )を返す。ctorFunc をCreateBuiltinFunction (defaultCtor , 0, className , « [[ConstructorKind]] , [[SourceText]] , [[PrivateMethods]] , [[Fields]] », the current Realm Record , ctorParent )とする。そうでなければ、ctorInfo を、arguments proto およびctorParent を伴うctor の ! DefineMethod とする。ctorFunc をctorInfo .[[Closure]] とする。MakeClassConstructor (ctorFunc )を実行する。SetFunctionName (ctorFunc , className )を実行する。 ctorFunc .[[SourceText]] をsourceText に設定する。MakeConstructor (ctorFunc , false , proto )を実行する。ClassHeritage が存在するなら、ctorFunc .[[ConstructorKind]] をderived に設定する。! DefineMethodProperty (proto , "constructor" , ctorFunc , false )を実行する。 ClassBody が存在しないなら、classElements を新しい空のList とする。そうでなければ、classElements をClassBody のNonConstructorElements とする。 instancePrivateMethods を新しい空のList とする。staticPrivateMethods を新しい空のList とする。instanceFields を新しい空のList とする。staticElements を新しい空のList とする。classElements の各ClassElement classElement について、以下を行うclassElement のIsStatic がfalse なら、element を、argument proto を伴うclassElement のClassElementEvaluation のCompletion とする。そうでなければ、element を、argument ctorFunc を伴うclassElement のClassElementEvaluation のCompletion とする。 element がabrupt completion なら、running execution context のLexicalEnvironmentをenvRecord に設定する。running execution context のPrivateEnvironmentをouterPrivateEnv に設定する。? element を返す。 element を ! element に設定する。element がPrivateElement なら、Assert : element .[[Kind]] はmethod またはaccessor のいずれかである。classElement のIsStatic がfalse なら、container をinstancePrivateMethods とする。そうでなければ、container をstaticPrivateMethods とする。 container が、その[[Key]] がelement .[[Key]] であるPrivateElement existingElement を含むなら、Assert : element .[[Kind]] とexistingElement .[[Kind]] は両方ともaccessor である。element .[[Get]] がundefined なら、combined をPrivateElement { [[Key]] : element .[[Key]] , [[Kind]] : accessor , [[Get]] : existingElement .[[Get]] , [[Set]] : element .[[Set]] }とする。そうでなければ、combined をPrivateElement { [[Key]] : element .[[Key]] , [[Kind]] : accessor , [[Get]] : element .[[Get]] , [[Set]] : existingElement .[[Set]] }とする。 container 内のexistingElement をcombined で置き換える。そうでなければ、element をcontainer へappendする。 そうでなく、element がClassFieldDefinition Record なら、classElement のIsStatic がfalse なら、element をinstanceFields へappendする。そうでなければ、element をstaticElements へappendする。 そうでなく、element がClassStaticBlockDefinition Record なら、element をstaticElements へappendする。 running execution context のLexicalEnvironmentをenvRecord に設定する。classBinding がundefined でないなら、! classEnv .InitializeBinding (classBinding , ctorFunc )を実行する。 ctorFunc .[[PrivateMethods]] をinstancePrivateMethods に設定する。ctorFunc .[[Fields]] をinstanceFields に設定する。staticPrivateMethods の各PrivateElement method について、以下を行う! PrivateMethodOrAccessorAdd (ctorFunc , method )を実行する。 staticElements の各要素elementRecord について、以下を行うelementRecord がClassFieldDefinition Record なら、result をDefineField (ctorFunc , elementRecord )のCompletion とする。そうでなければ、Assert : elementRecord はClassStaticBlockDefinition Record である。result をCall (elementRecord .[[BodyFunction]] , ctorFunc )のCompletion とする。 result がabrupt completion なら、running execution context のPrivateEnvironmentをouterPrivateEnv に設定する。? result を返す。 running execution context のPrivateEnvironmentをouterPrivateEnv に設定する。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
className をBindingIdentifier のStringValue とする。sourceText をClassDeclaration によってmatchされたsource textとする。value を、arguments className 、className 、およびsourceText を伴うClassTail の ? ClassDefinitionEvaluation とする。envRecord をrunning execution context のLexicalEnvironmentとする。? InitializeBoundName (className , value , envRecord )を実行する。 value を返す。
ClassDeclaration :
class
ClassTail
sourceText をClassDeclaration によってmatchされたsource textとする。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
this ClassDeclaration の ? BindingClassDeclarationEvaluation を実行する。 empty を返す。
Note
ClassDeclaration :
class
ClassTail
はExportDeclaration の一部としてのみ出現し、直接評価されることは決してありません。
ClassExpression :
class
ClassTail
sourceText をClassExpression によってmatchされたsource textとする。arguments undefined 、empty String、およびsourceText を伴うClassTail の ? ClassDefinitionEvaluation を返す。
ClassExpression :
class
BindingIdentifier
ClassTail
className をBindingIdentifier のStringValue とする。sourceText をClassExpression によってmatchされたsource textとする。arguments className 、className 、およびsourceText を伴うClassTail の ? ClassDefinitionEvaluation を返す。
ClassElementName : PrivateIdentifier
privateIdentifier をPrivateIdentifier のStringValue とする。privateEnvRecord をrunning execution context のPrivateEnvironmentとする。names をprivateEnvRecord .[[Names]] とする。Assert : names のちょうど1つの要素が、その[[Description]] がprivateIdentifier であるPrivate Name である。privateName を、names 内の、その[[Description]] がprivateIdentifier であるPrivate Name とする。privateName を返す。
ClassStaticBlockStatementList : [empty]
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が存在するとき、awaitはAwaitExpression のkeyword として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
BindingIdentifier opt
(
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
}
name をBindingIdentifier のStringValue とする。sourceText をAsyncFunctionDeclaration によってmatchされたsource textとする。closure をOrdinaryFunctionCreate (%AsyncFunction.prototype% , sourceText , FormalParameters , AsyncFunctionBody , non-lexical-this , envRecord , privateEnv )とする。SetFunctionName (closure , name )を実行する。closure を返す。
AsyncFunctionDeclaration :
async
function
(
FormalParameters
)
{
AsyncFunctionBody
}
sourceText をAsyncFunctionDeclaration によってmatchされたsource textとする。closure をOrdinaryFunctionCreate (%AsyncFunction.prototype% , sourceText , FormalParameters , AsyncFunctionBody , non-lexical-this , envRecord , privateEnv )とする。SetFunctionName (closure , "default" )を実行する。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
}
name が存在しない場合、name をempty Stringに設定する。envRecord をrunning execution context のLexicalEnvironmentとする。privateEnv をrunning execution context のPrivateEnvironmentとする。sourceText をAsyncFunctionExpression によってmatchされたsource textとする。closure をOrdinaryFunctionCreate (%AsyncFunction.prototype% , sourceText , FormalParameters , AsyncFunctionBody , non-lexical-this , envRecord , privateEnv )とする。SetFunctionName (closure , name )を実行する。closure を返す。
AsyncFunctionExpression :
async
function
BindingIdentifier
(
FormalParameters
)
{
AsyncFunctionBody
}
Assert : name は存在しない。name をBindingIdentifier のStringValue に設定する。outerEnv をrunning execution context のLexicalEnvironmentとする。funcEnv をNewDeclarativeEnvironment (outerEnv )とする。! funcEnv .CreateImmutableBinding (name , false )を実行する。 privateEnv をrunning execution context のPrivateEnvironmentとする。sourceText をAsyncFunctionExpression によってmatchされたsource textとする。closure をOrdinaryFunctionCreate (%AsyncFunction.prototype% , sourceText , FormalParameters , AsyncFunctionBody , non-lexical-this , funcEnv , privateEnv )とする。SetFunctionName (closure , name )を実行する。! funcEnv .InitializeBinding (name , closure )を実行する。 closure を返す。
Note
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
promiseCapability を ! NewPromiseCapability (%Promise% ) とする。completion をCompletion (FunctionDeclarationInstantiation (funcObj , argList ))とする。completion がabrupt completion なら、! Call (promiseCapability .[[Reject]] , undefined , « completion .[[Value]] »)を実行する。 そうでなければ、AsyncFunctionStart (promiseCapability , FunctionBody )を実行する。 ReturnCompletion (promiseCapability .[[Promise]] )を返す。
15.8.5 Runtime Semantics: Evaluation
AsyncFunctionExpression :
async
function
BindingIdentifier opt
(
FormalParameters
)
{
AsyncFunctionBody
}
AsyncFunctionExpression のInstantiateAsyncFunctionExpression を返す。
UnaryExpression : CoverAwaitExpressionAndAwaitUsingDeclarationHead
expr を、CoverAwaitExpressionAndAwaitUsingDeclarationHead によってカバーされる AwaitExpression とする。Return ? Evaluation of expr .
AwaitExpression :
await
UnaryExpression
exprRef をUnaryExpression の ? Evaluation とする。value を ? GetValue (exprRef ) とする。? 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
false を返す。
AsyncConciseBody :
{
AsyncFunctionBody
}
AsyncFunctionBody のFunctionBodyContainsUseStrict を返す。
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
promiseCapability を ! NewPromiseCapability (%Promise% ) とする。completion をCompletion (FunctionDeclarationInstantiation (funcObj , argList ))とする。completion がabrupt completion なら、! Call (promiseCapability .[[Reject]] , undefined , « completion .[[Value]] »)を実行する。 そうでなければ、AsyncFunctionStart (promiseCapability , ExpressionBody )を実行する。 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
name が存在しない場合、name をempty Stringに設定する。envRecord をrunning execution context のLexicalEnvironmentとする。privateEnv をrunning execution context のPrivateEnvironmentとする。sourceText をAsyncArrowFunction によってmatchされたsource textとする。params をAsyncArrowBindingIdentifier とする。closure をOrdinaryFunctionCreate (%AsyncFunction.prototype% , sourceText , params , AsyncConciseBody , lexical-this , envRecord , privateEnv )とする。SetFunctionName (closure , name )を実行する。closure を返す。
AsyncArrowFunction :
CoverCallExpressionAndAsyncArrowHead
=>
AsyncConciseBody
name が存在しない場合、name をempty Stringに設定する。envRecord をrunning execution context のLexicalEnvironmentとする。privateEnv をrunning execution context のPrivateEnvironmentとする。sourceText をAsyncArrowFunction によってmatchされたsource textとする。head をCoverCallExpressionAndAsyncArrowHead によってcoverされるAsyncArrowHead とする。params をhead のArrowFormalParameters とする。closure をOrdinaryFunctionCreate (%AsyncFunction.prototype% , sourceText , params , AsyncConciseBody , lexical-this , envRecord , privateEnv )とする。SetFunctionName (closure , name )を実行する。closure を返す。
15.9.5 Runtime Semantics: Evaluation
AsyncArrowFunction :
async
AsyncArrowBindingIdentifier
=>
AsyncConciseBody
CoverCallExpressionAndAsyncArrowHead
=>
AsyncConciseBody
AsyncArrowFunction のInstantiateAsyncArrowFunctionExpression を返す。
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:
IsStrict (call )がfalse なら、false を返す。call がFunctionBody 、ConciseBody 、またはAsyncConciseBody 内に含まれていないなら、false を返す。body をcall を最も近く含むFunctionBody 、ConciseBody 、またはAsyncConciseBody とする。body がGeneratorBody のFunctionBody なら、false を返す。body がAsyncFunctionBody のFunctionBody なら、false を返す。body がAsyncGeneratorBody のFunctionBody なら、false を返す。body がAsyncConciseBody なら、false を返す。argument call を伴うbody のHasCallInTailPosition の結果を返す。
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
It is defined piecewise over the following productions:
StatementList :
StatementList
StatementListItem
has を、引数 call で派生した StatementList の HasCallInTailPosition とする。has が true である場合、true を返す。派生した StatementList の ContainsUsing が true である場合、false を返す。 引数 call で StatementListItem の HasCallInTailPosition を返す。
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 :
{
}
false を返す。
IfStatement :
if
(
Expression
)
Statement
else
Statement
has を、argument call を伴う最初のStatement のHasCallInTailPosition とする。has がtrue なら、true を返す。argument call を伴う2番目のStatement のHasCallInTailPosition を返す。
IfStatement :
if
(
Expression
)
Statement
DoWhileStatement :
do
Statement
while
(
Expression
)
;
WhileStatement :
while
(
Expression
)
Statement
ForStatement :
for
(
Expression opt
;
Expression opt
;
Expression opt
)
Statement
for
(
var
VariableDeclarationList
;
Expression opt
;
Expression opt
)
Statement
for
(
LexicalDeclaration
Expression opt
;
Expression opt
)
Statement
ForInOfStatement :
for
(
LeftHandSideExpression
in
Expression
)
Statement
for
(
var
ForBinding
in
Expression
)
Statement
for
(
ForDeclaration
in
Expression
)
Statement
WithStatement :
with
(
Expression
)
Statement
argument call を伴うStatement のHasCallInTailPosition を返す。
LabelledStatement :
LabelIdentifier
:
LabelledItem
argument call を伴うLabelledItem のHasCallInTailPosition を返す。
ReturnStatement :
return
Expression
;
argument call を伴うExpression のHasCallInTailPosition を返す。
SwitchStatement :
switch
(
Expression
)
CaseBlock
argument call を伴うCaseBlock のHasCallInTailPosition を返す。
CaseBlock :
{
CaseClauses opt
DefaultClause
CaseClauses opt
}
has をfalse とする。最初のCaseClauses が存在するなら、has を、argument call を伴う最初のCaseClauses のHasCallInTailPosition に設定する。 has がtrue なら、true を返す。has を、argument call を伴うDefaultClause のHasCallInTailPosition に設定する。has がtrue なら、true を返す。2番目のCaseClauses が存在するなら、has を、argument call を伴う2番目のCaseClauses のHasCallInTailPosition に設定する。 has を返す。
CaseClauses :
CaseClauses
CaseClause
has を、argument call を伴うCaseClauses のHasCallInTailPosition とする。has がtrue なら、true を返す。argument call を伴うCaseClause のHasCallInTailPosition を返す。
CaseClause :
case
Expression
:
StatementList opt
DefaultClause :
default
:
StatementList opt
StatementList が存在するなら、argument call を伴うStatementList のHasCallInTailPosition を返す。false を返す。
TryStatement :
try
Block
Catch
argument call を伴うCatch のHasCallInTailPosition を返す。
TryStatement :
try
Block
Finally
try
Block
Catch
Finally
argument call を伴うFinally のHasCallInTailPosition を返す。
Catch :
catch
(
CatchParameter
)
Block
argument call を伴うBlock のHasCallInTailPosition を返す。
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
false を返す。
Expression :
AssignmentExpression
Expression
,
AssignmentExpression
argument call を伴うAssignmentExpression のHasCallInTailPosition を返す。
ConditionalExpression :
ShortCircuitExpression
?
AssignmentExpression
:
AssignmentExpression
has を、argument call を伴う最初のAssignmentExpression のHasCallInTailPosition とする。has がtrue なら、true を返す。argument call を伴う2番目のAssignmentExpression のHasCallInTailPosition を返す。
LogicalANDExpression :
LogicalANDExpression
&&
BitwiseORExpression
argument call を伴うBitwiseORExpression のHasCallInTailPosition を返す。
LogicalORExpression :
LogicalORExpression
||
LogicalANDExpression
argument call を伴うLogicalANDExpression のHasCallInTailPosition を返す。
CoalesceExpression :
CoalesceExpressionHead
??
BitwiseORExpression
argument call を伴うBitwiseORExpression のHasCallInTailPosition を返す。
CallExpression :
CoverCallExpressionAndAsyncArrowHead
CallExpression
Arguments
CallExpression
TemplateLiteral
this CallExpression がcall なら、true を返す。 false を返す。
OptionalExpression :
MemberExpression
OptionalChain
CallExpression
OptionalChain
OptionalExpression
OptionalChain
argument call を伴うOptionalChain のHasCallInTailPosition を返す。
OptionalChain :
?.
[
Expression
]
?.
IdentifierName
?.
PrivateIdentifier
OptionalChain
[
Expression
]
OptionalChain
.
IdentifierName
OptionalChain
.
PrivateIdentifier
false を返す。
OptionalChain :
?.
Arguments
OptionalChain
Arguments
this OptionalChain がcall なら、true を返す。 false を返す。
MemberExpression :
MemberExpression
TemplateLiteral
this MemberExpression がcall なら、true を返す。 false を返す。
PrimaryExpression : CoverParenthesizedExpressionAndArrowParameterList
expr をCoverParenthesizedExpressionAndArrowParameterList によってcoverされるParenthesizedExpression とする。argument call を伴うexpr のHasCallInTailPosition を返す。
ParenthesizedExpression :
(
Expression
)
argument call を伴うExpression のHasCallInTailPosition を返す。
15.10.3 PrepareForTailCall ( )
The abstract operation PrepareForTailCall takes no arguments and returns unused . It performs the following steps when called:
Assert : current execution context は、以後いかなるECMAScript codeまたはbuilt-in functionsのevaluationにも使用されない。このabstract operationの呼び出しに続くCallの呼び出しは、そのようなevaluationを実行する前に新しいexecution context を作成してpushする。current execution context に関連付けられたすべてのresourcesを破棄する。 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 :
ScriptBody opt
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 : ScriptBody opt
ScriptBody が存在し、かつScriptBody のDirective Prologue がUse Strict Directive を含むなら、true を返す。false を返す。
16.1.3 Runtime Semantics: Evaluation
Script : [empty]
undefined を返す。
16.1.4 Script Records
Script Record は、評価されているscriptに関する情報をencapsulateします。各script recordはTable 35 に列挙されたfieldsを含みます。
Table 35: Script Record Fields
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. sourceText をScript としてparseした結果に基づいてScript Record を作成します。 It performs the following steps when called:
script をParseText (sourceText , Script )とする。script がerrorsのList なら、script を返す。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:
globalEnv をscriptRecord .[[Realm]] .[[GlobalEnv]] とする。scriptContext を新しいECMAScript code execution context とする。scriptContext のFunctionをnull に設定する。scriptContext のRealm をscriptRecord .[[Realm]] に設定する。scriptContext のScriptOrModuleをscriptRecord に設定する。scriptContext のVariableEnvironmentをglobalEnv に設定する。scriptContext のLexicalEnvironmentをglobalEnv に設定する。scriptContext のPrivateEnvironmentをnull に設定する。running execution context をsuspendする。scriptContext をexecution context stack へpushする;scriptContext は現在running execution context である。scriptNode をscriptRecord .[[ECMAScriptCode]] とする。result をCompletion (GlobalDeclarationInstantiation (scriptNode , globalEnv ))とする。result がnormal completion なら、result をCompletion (scriptNode のEvaluation )に設定する。result がnormal completion であり、かつresult .[[Value]] がempty なら、result をNormalCompletion (undefined )に設定する。scriptContext をsuspendし、それをexecution context stack からremoveする。Assert : execution context stack は空でない。execution context stack のtopにあるcontextをrunning execution context としてresumeする。? 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 . script はexecution context が確立される対象のScript です。envRecord はbindingsが作成されるglobal environmentです。
Note 1
scriptsを評価するためにexecution context が確立されるとき、declarationsはcurrent global environment内でinstantiatedされます。code内でdeclaredされた各global bindingがinstantiatedされます。
これは呼び出されたとき、次のstepsを実行します:
script のLexicallyDeclaredNames をlexicalNames とする。script のVarDeclaredNames をvariableNames とする。lexicalNames の各要素name について、次を行う。HasLexicalDeclaration (envRecord , name )がtrue である場合、SyntaxError 例外を投げる。? HasRestrictedGlobalProperty (envRecord , name )をhasRestrictedGlobal とする。 NOTE : グローバルvarおよびfunction束縛(非strict direct eval によって導入されるものを除く)は構成不可であり、したがって制限されたグローバルプロパティである。hasRestrictedGlobal がtrue である場合、SyntaxError 例外を投げる。variableNames の各要素name について、次を行う。HasLexicalDeclaration (envRecord , name )がtrue である場合、SyntaxError 例外を投げる。script のVarScopedDeclarations をvariableDecls とする。funcsToInitialize を新しい空のList とする。declaredFuncNames を新しい空のList とする。variableDecls の各要素variableDecl について、List の逆順で、次を行う。variableDecl がVariableDeclaration 、ForBinding 、またはBindingIdentifier のいずれでもない場合、Assert : variableDecl は、FunctionDeclaration 、GeneratorDeclaration 、AsyncFunctionDeclaration 、またはAsyncGeneratorDeclaration のいずれかである。NOTE : 同じ名前に対して複数の関数宣言がある場合、最後の宣言が使用される。variableDecl のBoundNames の唯一の要素をfuncName とする。declaredFuncNames がfuncName を含まない場合、? CanDeclareGlobalFunction (envRecord , funcName )をfuncDefinable とする。 funcDefinable がfalse である場合、TypeError 例外を投げる。funcName をdeclaredFuncNames に追加する。variableDecl をfuncsToInitialize の最初の要素として挿入する。declaredVariableNames を新しい空のList とする。variableDecls の各要素variableDecl について、次を行う。variableDecl がVariableDeclaration 、ForBinding 、またはBindingIdentifier のいずれかである場合、variableDecl のBoundNames の各String name について、次を行う。declaredFuncNames がname を含まない場合、? CanDeclareGlobalVar (envRecord , name )をvariableDefinable とする。 variableDefinable がfalse である場合、TypeError 例外を投げる。declaredVariableNames がname を含まない場合、name をdeclaredVariableNames に追加する。NOTE : グローバルオブジェクトがordinary object である場合、このアルゴリズムステップ以降で異常終了は発生しない。しかし、グローバルオブジェクトがProxy exotic object である場合、以下のステップの一部で異常終了を引き起こす挙動を示すことがある。ホスト がWebブラウザである、またはその他の形でBlock-Level Function Declarations Web Legacy Compatibility Semantics をサポートする場合、script のScriptIsStrict をstrict とする。strict がfalse である場合、declaredFuncNames とdeclaredVariableNames のlist-concatenation をdeclaredFuncOrVariableNames とする。script Contains x がtrue であるような任意のBlock 、CaseClause 、またはDefaultClause x のStatementList に直接含まれる各FunctionDeclaration funcDecl について、次を行う。funcDecl のBindingIdentifier のStringValue をfuncName とする。FunctionDeclaration funcDecl を、funcName をBindingIdentifier として持つVariableStatement に置き換えても、script に対してEarly Errorsが発生しない場合、HasLexicalDeclaration (envRecord , funcName )がfalse である場合、? CanDeclareGlobalVar (envRecord , funcName )をfuncDefinable とする。 funcDefinable がtrue である場合、NOTE : funcName に対するvar束縛は、それがVarDeclaredNameでも別のFunctionDeclaration の名前でもない場合にのみ、ここでインスタンス化される。declaredFuncOrVariableNames がfuncName を含まない場合、? CreateGlobalVarBinding (envRecord , funcName , false )を実行する。 funcName をdeclaredFuncOrVariableNames に追加する。FunctionDeclaration funcDecl が評価されるとき、15.2.6 で提供されるFunctionDeclaration Evaluation アルゴリズムの代わりに、次のステップを実行する。実行中の実行コンテキストのVariableEnvironmentをglobalEnv とする。 実行中の実行コンテキストのLexicalEnvironmentをblockEnv とする。 ! blockEnv .GetBindingValue (funcName , false )をfuncObj とする。 ? globalEnv .SetMutableBinding (funcName , funcObj , false ) を実行する。 unused を返す。script のLexicallyScopedDeclarations をlexicalDecls とする。privateEnv をnull とする。lexicalDecls の各要素lexicalDecl について、次を行う。NOTE : Lexically declared nameは、ここでインスタンス化されるだけで、初期化されない。lexicalDecl のBoundNames の各要素name について、次を行う。lexicalDecl のIsConstantDeclaration がtrue である場合、? envRecord .CreateImmutableBinding (name , true ) を実行する。 そうでなければ、? envRecord .CreateMutableBinding (name , false ) を実行する。 funcsToInitialize の各Parse Node funcDecl について、次を行う。funcDecl のBoundNames の唯一の要素をfuncName とする。envRecord およびprivateEnv を引数として、funcDecl のInstantiateFunctionObject をfuncObj とする。? CreateGlobalFunctionBinding (envRecord , funcName , funcObj , false )を実行する。 declaredVariableNames の各String variableName について、次を行う。? CreateGlobalVarBinding (envRecord , variableName , false )を実行する。 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 object がProxy 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 :
ModuleBody opt
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:
localNames を新しい空のList とする。importEntries の各ImportEntry Record importEntry について、次を行う。importEntry .[[LocalName]] をlocalNames に追加する。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
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:
x .[[Specifier]] がy .[[Specifier]] でないなら、false を返す。xAttrs をx .[[Attributes]] とする。yAttrs をy .[[Attributes]] とする。xAttrsCount をxAttrs 内の要素数とする。yAttrsCount をyAttrs 内の要素数とする。xAttrsCount ≠ yAttrsCount なら、false を返す。xAttrs の各ImportAttribute Record xAttr について、以下を行うyAttrs が、xAttr .[[Key]] がyAttr .[[Key]] であり、かつxAttr .[[Value]] がyAttr .[[Value]] であるようなImportAttribute Record yAttr を含まないなら、false を返す。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]
新しい空のList を返す。
ModuleItemList : ModuleItem
ModuleItem のModuleRequests を返す。
ModuleItemList :
ModuleItemList
ModuleItem
ModuleItemList のModuleRequests をrequests とする。ModuleItem のModuleRequests をadditionalRequests とする。additionalRequests の各ModuleRequest Record moduleRequest について、次を行う。ModuleRequestsEqual (moduleRequest , otherModuleRequest )がtrue であるようなModuleRequest Record otherModuleRequest をrequests が含まない場合、moduleRequest をrequests に追加する。requests を返す。
ModuleItem : StatementListItem
新しい空のList を返す。
ImportDeclaration :
import
ImportClause
FromClause
;
specifier をFromClause のSV とする。唯一の要素がModuleRequest Record { [[Specifier]] : specifier , [[Attributes]] : « » }であるList を返す。
ImportDeclaration :
import
ImportClause
FromClause
WithClause
;
specifier をFromClause のSV とする。attrs をWithClause のWithClauseToAttributes とする。唯一の要素がModuleRequest Record { [[Specifier]] : specifier , [[Attributes]] : attrs }であるList を返す。
ImportDeclaration :
import
ModuleSpecifier
;
specifier をModuleSpecifier のSV とする。唯一の要素がModuleRequest Record { [[Specifier]] : specifier , [[Attributes]] : « » }であるList を返す。
ImportDeclaration :
import
ModuleSpecifier
WithClause
;
specifier をModuleSpecifier のSV とする。attrs をWithClause のWithClauseToAttributes とする。唯一の要素がModuleRequest Record { [[Specifier]] : specifier , [[Attributes]] : attrs }であるList を返す。
ExportDeclaration :
export
ExportFromClause
FromClause
;
specifier をFromClause のSV とする。唯一の要素がModuleRequest Record { [[Specifier]] : specifier , [[Attributes]] : « » }であるList を返す。
ExportDeclaration :
export
ExportFromClause
FromClause
WithClause
;
specifier をFromClause のSV とする。attrs をWithClause のWithClauseToAttributes とする。唯一の要素がModuleRequest Record { [[Specifier]] : specifier , [[Attributes]] : attrs }であるList を返す。
ExportDeclaration :
export
NamedExports
;
export
VariableStatement
export
Declaration
export
default
HoistableDeclaration
export
default
ClassDeclaration
export
default
AssignmentExpression
;
新しい空の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が特定のexportName 、resolveSet pairをargumentsとして呼び出されるたびに、同じresultを返さなければなりません。
このmethodをinvokeする前に、LoadRequestedModules はsuccessfullyに完了していなければなりません。
この仕様内では、これは次のtypes内にdefinitionsを持ちます;hosts は独自のdefinitionsを持つ追加のtypesを提供してもよいです:
Link ( )
The abstract method Link takes no arguments and returns either a normal completion containing unused or a throw completion .
すべてのmodule dependenciesをtransitivelyにresolveし、Module Environment Record を作成することで、evaluationのためにmoduleを準備します。
この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:
Assert : module はCyclic Module Record でない。promise をmodule .Evaluate ()とする。Assert : promise .[[PromiseState]] はfulfilled またはrejected のいずれかである。promise .[[PromiseState]] がrejected なら、promise .[[PromiseIsHandled]] がfalse なら、HostPromiseRejectionTracker (promise , "handle" )を実行する。promise .[[PromiseIsHandled]] をtrue に設定する。promise .[[PromiseResult]] をThrowする。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 Records はTable 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を通じて進むにつれて、unlinked 、linking 、linked 、evaluating 、場合によりevaluating-async 、evaluated へ(この順に)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 Records のList 。この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 Records はTable 42 に列挙された追加のmethodsを持ちます:
Table 42: Additional Abstract Methods of Cyclic Module Records
GraphLoadingState Record は、module graphのloading processに関する情報を含むRecord です。これはHostLoadImportedModule のcall後にloadingをcontinueするために使用されます。各GraphLoadingState Record はTable 43 で定義されるfieldsを持ちます:
Table 43: GraphLoadingState Record Fields
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:
hostDefined が存在しないなら、hostDefined をempty に設定する。promiseCapability を ! NewPromiseCapability (%Promise% ) とする。state をGraphLoadingState Record { [[IsLoading]] : true , [[PendingModulesCount]] : 1, [[Visited]] : « », [[PromiseCapability]] : promiseCapability , [[HostDefined]] : hostDefined }とする。InnerModuleLoading (state , module )を実行する。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:
Assert : state .[[IsLoading]] はtrue である。module がCyclic Module Record であり、module .[[Status]] がnew であり、かつstate .[[Visited]] がmodule を含まないなら、module をstate .[[Visited]] へappendする。requestedModulesCount をmodule .[[RequestedModules]] 内の要素数とする。state .[[PendingModulesCount]] をstate .[[PendingModulesCount]] + requestedModulesCount に設定する。module .[[RequestedModules]] の各ModuleRequest Record request について、以下を行うAllImportAttributesSupported (request .[[Attributes]] )がfalse なら、error をThrowCompletion (a newly created SyntaxError object)とする。ContinueModuleLoading (state , error )を実行する。そうでなく、module .[[LoadedModules]] がModuleRequestsEqual (record , request )がtrue であるようなLoadedModuleRequest Record record を含むなら、InnerModuleLoading (state , record .[[Module]] )を実行する。 そうでなければ、HostLoadImportedModule (module , request , state .[[HostDefined]] , state )を実行する。NOTE : HostLoadImportedModule はFinishLoadingImportedModule をcallし、これはContinueModuleLoading を通じてgraph loading processへre-enterする。 state .[[IsLoading]] がfalse なら、unused を返す。Assert : state .[[PendingModulesCount]] ≥ 1である。state .[[PendingModulesCount]] をstate .[[PendingModulesCount]] - 1に設定する。state .[[PendingModulesCount]] = 0なら、state .[[IsLoading]] をfalse に設定する。state .[[Visited]] の各Cyclic Module Record loaded について、以下を行うloaded .[[Status]] がnew なら、loaded .[[Status]] をunlinked に設定する。! Call (state .[[PromiseCapability]] .[[Resolve]] , undefined , « undefined »)を実行する。 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:
state .[[IsLoading]] がfalse なら、unused を返す。moduleCompletion がnormal completion なら、InnerModuleLoading (state , moduleCompletion .[[Value]] )を実行する。そうでなければ、state .[[IsLoading]] をfalse に設定する。! Call (state .[[PromiseCapability]] .[[Reject]] , undefined , « moduleCompletion .[[Value]] »)を実行する。 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:
Assert : module .[[Status]] はunlinked 、linked 、evaluating-async 、またはevaluated のいずれかである。stack を新しい空のList とする。Completion (InnerModuleLinking (module , stack , 0))をresult とする。result がabrupt completion である場合、stack の各Cyclic Module Record requiredModule について、次を行う。Assert : requiredModule .[[Status]] はlinking である。requiredModule .[[Status]] をunlinked に設定する。Assert : module .[[Status]] はunlinked である。? result を返す。 Assert : module .[[Status]] はlinked 、evaluating-async 、またはevaluated のいずれかである。Assert : stack は空である。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:
module がCyclic Module Record でないなら、? module .Link ()を実行する。 index を返す。module .[[Status]] がlinking 、linked 、evaluating-async 、またはevaluated のいずれかなら、index を返す。Assert : module .[[Status]] はunlinked である。module .[[Status]] をlinking に設定する。moduleIndex をindex とする。module .[[DFSAncestorIndex]] をindex に設定する。index をindex + 1に設定する。module をstack へappendする。module .[[RequestedModules]] の各ModuleRequest Record request について、以下を行うrequiredModule をGetImportedModule (module , request )とする。index を ? InnerModuleLinking (requiredModule , stack , index ) に設定する。requiredModule がCyclic Module Record なら、Assert : requiredModule .[[Status]] はlinking 、linked 、evaluating-async 、またはevaluated のいずれかである。Assert : requiredModule .[[Status]] がlinking であることとstack がrequiredModule を含むことは同値である。requiredModule .[[Status]] がlinking なら、module .[[DFSAncestorIndex]] をmin (module .[[DFSAncestorIndex]] , requiredModule .[[DFSAncestorIndex]] )に設定する。? module .InitializeEnvironment ()を実行する。 Assert : module はstack 内にちょうど1回出現する。Assert : module .[[DFSAncestorIndex]] ≤ moduleIndex である。module .[[DFSAncestorIndex]] = moduleIndex なら、done をfalse とする。done がfalse である間、繰り返すrequiredModule をstack の最後の要素とする。stack の最後の要素をremoveする。Assert : requiredModule はCyclic Module Record である。requiredModule .[[Status]] をlinked に設定する。requiredModule とmodule が同じModule Record なら、done をtrue に設定する。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:
Assert : このEvaluate への呼び出しは、周囲のagent 内の別のEvaluate への呼び出しと同時には発生していない。Assert : module .[[Status]] はlinked 、evaluating-async 、またはevaluated のいずれかである。module .[[Status]] がevaluating-async またはevaluated のいずれかである場合、module .[[CycleRoot]] がempty でない場合、module をmodule .[[CycleRoot]] に設定する。そうでなければ、Assert : module .[[Status]] はevaluated であり、module .[[EvaluationError]] はthrow completion である。 module .[[TopLevelCapability]] がempty でない場合、module .[[TopLevelCapability]] .[[Promise]] を返す。stack を新しい空のList とする。! NewPromiseCapability (%Promise% )をpromiseCapability とする。 module .[[TopLevelCapability]] をpromiseCapability に設定する。Completion (InnerModuleEvaluation (module , stack , 0))をresult とする。result がabrupt completion である場合、stack の各Cyclic Module Record requiredModule について、次を行う。Assert : requiredModule .[[Status]] はevaluating である。requiredModule .[[Status]] をevaluated に設定する。requiredModule .[[EvaluationError]] をresult に設定する。Assert : module .[[Status]] はevaluated である。Assert : module .[[EvaluationError]] とresult は同じCompletion Record である。! Call (promiseCapability .[[Reject]] , undefined , « result .[[Value]] »)を実行する。 そうでなければ、Assert : module .[[Status]] はevaluating-async またはevaluated のいずれかである。Assert : module .[[EvaluationError]] はempty である。module .[[Status]] がevaluated である場合、Assert : module .[[AsyncEvaluationOrder]] はunset またはdone のいずれかである。NOTE : module .[[AsyncEvaluationOrder]] がdone であるのは、module が既に評価済みであり、かつその評価が非同期であった場合に限る。! Call (promiseCapability .[[Resolve]] , undefined , « undefined »)を実行する。 Assert : stack は空である。 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:
module がCyclic Module Record でないなら、? EvaluateModuleSync (module )を実行する。 index を返す。module .[[Status]] がevaluating-async またはevaluated のいずれかなら、module .[[EvaluationError]] がempty なら、index を返す。? module .[[EvaluationError]] を返す。 module .[[Status]] がevaluating なら、index を返す。Assert : module .[[Status]] はlinked である。module .[[Status]] をevaluating に設定する。moduleIndex をindex とする。module .[[DFSAncestorIndex]] をindex に設定する。module .[[PendingAsyncDependencies]] を0に設定する。index をindex + 1に設定する。module をstack へappendする。module .[[RequestedModules]] の各ModuleRequest Record request について、以下を行うrequiredModule をGetImportedModule (module , request )とする。index を ? InnerModuleEvaluation (requiredModule , stack , index ) に設定する。requiredModule がCyclic Module Record なら、Assert : requiredModule .[[Status]] はevaluating 、evaluating-async 、またはevaluated のいずれかである。Assert : requiredModule .[[Status]] がevaluating であることとstack がrequiredModule を含むことは同値である。requiredModule .[[Status]] がevaluating なら、module .[[DFSAncestorIndex]] をmin (module .[[DFSAncestorIndex]] , requiredModule .[[DFSAncestorIndex]] )に設定する。そうでなければ、requiredModule をrequiredModule .[[CycleRoot]] に設定する。Assert : requiredModule .[[Status]] はevaluating-async またはevaluated のいずれかである。requiredModule .[[EvaluationError]] がempty でないなら、? requiredModule .[[EvaluationError]] を返す。 requiredModule .[[AsyncEvaluationOrder]] がinteger なら、module .[[PendingAsyncDependencies]] をmodule .[[PendingAsyncDependencies]] + 1に設定する。module をrequiredModule .[[AsyncParentModules]] へappendする。module .[[PendingAsyncDependencies]] > 0またはmodule .[[HasTLA]] がtrue なら、Assert : module .[[AsyncEvaluationOrder]] はunset である。module .[[AsyncEvaluationOrder]] をIncrementModuleAsyncEvaluationCount ()に設定する。module .[[PendingAsyncDependencies]] = 0なら、ExecuteAsyncModule (module )を実行する。そうでなければ、? module .ExecuteModule () を実行する。 Assert : module はstack 内にちょうど1回出現する。Assert : module .[[DFSAncestorIndex]] ≤ moduleIndex である。module .[[DFSAncestorIndex]] = moduleIndex なら、done をfalse とする。done がfalse である間、繰り返すrequiredModule をstack の最後の要素とする。stack の最後の要素をremoveする。Assert : requiredModule はCyclic Module Record である。Assert : requiredModule .[[AsyncEvaluationOrder]] はinteger またはunset のいずれかである。requiredModule .[[AsyncEvaluationOrder]] がunset なら、requiredModule .[[Status]] をevaluated に設定する。そうでなければ、requiredModule .[[Status]] をevaluating-async に設定する。 requiredModule とmodule が同じModule Record なら、done をtrue に設定する。requiredModule .[[CycleRoot]] をmodule に設定する。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:
Assert : module .[[Status]] はevaluating またはevaluating-async のいずれかである。Assert : module .[[HasTLA]] はtrue である。promiseCapability を ! NewPromiseCapability (%Promise% ) とする。module をcaptureし、呼び出されたとき次のstepsを実行する、parametersを持たない新しいAbstract Closure fulfilledClosure とする:AsyncModuleExecutionFulfilled (module )を実行する。NormalCompletion (undefined )を返す。onFulfilled をCreateBuiltinFunction (fulfilledClosure , 0, "" , « »)とする。module をcaptureし、呼び出されたとき次のstepsを実行する、parameters (error )を持つ新しいAbstract Closure rejectedClosure とする:AsyncModuleExecutionRejected (module , error )を実行する。NormalCompletion (undefined )を返す。onRejected をCreateBuiltinFunction (rejectedClosure , 0, "" , « »)とする。PerformPromiseThen (promiseCapability .[[Promise]] , onFulfilled , onRejected )を実行する。! module .ExecuteModule (promiseCapability ) を実行する。 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:
module .[[AsyncParentModules]] の各Cyclic Module Record ancestorModule について、以下を行うexecList がancestorModule を含まず、かつancestorModule .[[CycleRoot]] .[[EvaluationError]] がempty であるなら、Assert : ancestorModule .[[Status]] はevaluating-async である。Assert : ancestorModule .[[EvaluationError]] はempty である。Assert : ancestorModule .[[AsyncEvaluationOrder]] はinteger である。Assert : ancestorModule .[[PendingAsyncDependencies]] > 0である。ancestorModule .[[PendingAsyncDependencies]] をancestorModule .[[PendingAsyncDependencies]] - 1に設定する。ancestorModule .[[PendingAsyncDependencies]] = 0なら、ancestorModule をexecList へappendする。ancestorModule .[[HasTLA]] がfalse なら、GatherAvailableAncestors (ancestorModule , execList )を実行する。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:
module .[[Status]] がevaluated なら、Assert : module .[[EvaluationError]] はempty でない。unused を返す。Assert : module .[[Status]] はevaluating-async である。Assert : module .[[AsyncEvaluationOrder]] はinteger である。Assert : module .[[EvaluationError]] はempty である。module .[[AsyncEvaluationOrder]] をdone に設定する。module .[[Status]] をevaluated に設定する。module .[[TopLevelCapability]] がempty でないなら、Assert : module .[[CycleRoot]] とmodule は同じModule Record である。! Call (module .[[TopLevelCapability]] .[[Resolve]] , undefined , « undefined »)を実行する。 execList を新しい空のList とする。GatherAvailableAncestors (module , execList )を実行する。Assert : execList のすべての要素は、その[[AsyncEvaluationOrder]] fieldがinteger に、[[PendingAsyncDependencies]] fieldが0に、[[EvaluationError]] fieldがempty に設定されている。sortedExecList を、その要素がexecList の要素であり、それらの[[AsyncEvaluationOrder]] fieldの昇順でsortedされたList とする。sortedExecList の各Cyclic Module Record ancestorModule について、以下を行うancestorModule .[[Status]] がevaluated なら、Assert : ancestorModule .[[EvaluationError]] はempty でない。そうでなく、ancestorModule .[[HasTLA]] がtrue なら、ExecuteAsyncModule (ancestorModule )を実行する。 そうでなければ、result をCompletion (ancestorModule .ExecuteModule () )とする。result がabrupt completion なら、AsyncModuleExecutionRejected (ancestorModule , result .[[Value]] )を実行する。そうでなければ、ancestorModule .[[AsyncEvaluationOrder]] をdone に設定する。ancestorModule .[[Status]] をevaluated に設定する。ancestorModule .[[TopLevelCapability]] がempty でないなら、Assert : ancestorModule .[[CycleRoot]] とancestorModule は同じModule Record である。! Call (ancestorModule .[[TopLevelCapability]] .[[Resolve]] , undefined , « undefined »)を実行する。 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:
module .[[Status]] がevaluated なら、Assert : module .[[EvaluationError]] はempty でない。unused を返す。Assert : module .[[Status]] はevaluating-async である。Assert : module .[[AsyncEvaluationOrder]] はinteger である。Assert : module .[[EvaluationError]] はempty である。module .[[EvaluationError]] をThrowCompletion (error )に設定する。module .[[Status]] をevaluated に設定する。module .[[AsyncEvaluationOrder]] をdone に設定する。NOTE : module .[[AsyncEvaluationOrder]] はAsyncModuleExecutionFulfilled とのsymmetryのためにdone に設定される。InnerModuleEvaluation において、moduleの[[AsyncEvaluationOrder]] internal slotの値は、その[[EvaluationError]] internal slotがempty でない場合には使用されない。module .[[TopLevelCapability]] がempty でないなら、Assert : module .[[CycleRoot]] とmodule は同じModule Record である。! Call (module .[[TopLevelCapability]] .[[Reject]] , undefined , « error »)を実行する。 module .[[AsyncParentModules]] の各Cyclic Module Record ancestorModule について、以下を行うAsyncModuleExecutionRejected (ancestorModule , error )を実行する。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
まず、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を考えます。C のInnerModuleLinking がsucceedsしたが、その後B についてfailsする場合、例えばB がC が提供しないものをimportするためにfailsする場合、original A .Link ()はfailし、A とB の[[Status]] はunlinked のままです。ただしC の[[Status]] はlinked になっています。
最後に、Link ()へのsuccessful call後にevaluation errorsが関係するcaseを考えます。C のInnerModuleEvaluation がsucceedsしたが、その後B についてfailsする場合、例えばB がexceptionをthrowするcodeを含むためにfailsする場合、original A .Evaluate ()はfailし、rejected Promiseを返します。結果として生じるexceptionはA とB の[[EvaluationError]] fieldsの両方にrecordedされ、それらの[[Status]] はevaluated になります。C もevaluated になりますが、A およびB とは対照的に、successfullyにevaluationを完了したため[[EvaluationError]] を持たないままです。exceptionをstoreすることで、hostがA またはB をreuseしようとしてEvaluate () methodをcallするたびに、同じexceptionにencounterすることが保証されます。(Hosts はCyclic Module Records をreuseする必要はありません;同様に、hosts はこれらのmethodsによってthrownされたexception objectsをexposeする必要はありません。ただし、この仕様はそのようなusesを可能にします。)
次に、異なるtypeのerror conditionを考えます:
Figure 3: A module graph with an unresolvable module
この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
ここでは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 になって戻った後、A とB は一緒に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を考えます;例えば、A がC から存在しない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します。したがってA とB の両方がunlinked になります。C はlinked のまま残ることに注意してください。
あるいは、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します。したがってA とB の両方がevaluated になり、exceptionはA とB の[[EvaluationError]] fieldsの両方にrecordedされる一方、C は[[EvaluationError]] なしでevaluated のまま残ります。
最後に、すべてのmodulesがasynchronouslyにcompleteするcycleを持つmodule graphを考えます:
Figure 5: An asynchronous cyclic module graph
Loadingおよびlinkingは以前と同様に発生し、すべてのmodulesは[[Status]] がlinked に設定されて終了します。
A .Evaluate ()をcallすると、A 、B 、D に対して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になり、ExecuteAsyncModule がB に対してcallされ、executingを開始します。C .[[PendingAsyncDependencies]] もdecrementされて0になり、C がexecutingを開始します(B がawaitを含む場合、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
C がC のerrorを伴ってA に対してAsyncModuleExecutionRejected をcallするため、A はC と同じ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 に設定されます。GatherAvailableAncestors がB に対して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 text (11 )から定義された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 Records はTable 53 に列挙された追加のfieldsを持ちます。これらの各fieldはParseModule 内でinitiallyに設定されます。
Table 53: Additional Fields of Source Text Module Records
Field Name
Value Type
Meaning
[[ECMAScriptCode]]
a Parse Node
Module をgoal 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 Record はTable 54 で定義されるfieldsを持ちます:
Table 54: ImportEntry Record Fields
Field Name
Value Type
Meaning
[[ModuleRequest]]
a ModuleRequest Record
ImportDeclaration のModuleSpecifier および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 Record はTable 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
ExportDeclaration のModuleSpecifier およびimport attributesを表すModuleRequest Record 。ExportDeclaration がModuleSpecifier を持たない場合はnull 。
[[ImportName]]
a String, null , namespace , or all-but-default
[[ModuleRequest]] によってidentifiedされるmoduleによってdesired bindingがexportされているname。ExportDeclaration がModuleSpecifier を持たない場合はnull 。namespace はexport * as ns from "mod" declarationsに使用されます。all-but-default はexport * 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. sourceText をModule としてparseした結果に基づいてSource Text Module Record を作成します。 It performs the following steps when called:
body をParseText (sourceText , Module )とする。body がerrorsのList なら、body を返す。requestedModules をbody のModuleRequests とする。importEntries をbody のImportEntries とする。importedBoundNames をImportedLocalNames (importEntries )とする。indirectExportEntries を新しい空のList とする。localExportEntries を新しい空のList とする。starExportEntries を新しい空のList とする。exportEntries をbody のExportEntries とする。exportEntries の各ExportEntry Record exportEntry について、以下を行うexportEntry .[[ModuleRequest]] がnull なら、importedBoundNames がexportEntry .[[LocalName]] を含まないなら、exportEntry をlocalExportEntries へappendする。そうでなければ、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できる。importEntry をimportEntries のうち[[LocalName]] がexportEntry .[[LocalName]] である要素とする。ExportEntry Record { [[ModuleRequest]] : importEntry .[[ModuleRequest]] , [[ImportName]] : importEntry .[[ImportName]] , [[LocalName]] : null , [[ExportName]] : exportEntry .[[ExportName]] }をindirectExportEntries へappendする。 そうでなく、exportEntry .[[ImportName]] がall-but-default なら、Assert : exportEntry .[[ExportName]] はnull である。exportEntry をstarExportEntries へappendする。 そうでなければ、exportEntry をindirectExportEntries へappendする。 async をbody Contains awaitとする。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:
Assert : module .[[Status]] はnew ではない。exportStarSet が存在しない場合、exportStarSet を新しい空のList に設定する。exportStarSet がmodule を含む場合、Assert : export *の循環の開始点に到達している。新しい空のList を返す。 module をexportStarSet に追加する。exportedNames を新しい空のList とする。module .[[LocalExportEntries]] の各ExportEntry Record exportEntry について、次を行う。Assert : module はこのエクスポートに対する直接束縛を提供する。Assert : exportEntry .[[ExportName]] はnull ではない。exportEntry .[[ExportName]] をexportedNames に追加する。module .[[IndirectExportEntries]] の各ExportEntry Record exportEntry について、次を行う。Assert : module はこのエクスポートに対する特定の束縛をインポートしている。Assert : exportEntry .[[ExportName]] はnull ではない。exportEntry .[[ExportName]] をexportedNames に追加する。module .[[StarExportEntries]] の各ExportEntry Record exportEntry について、次を行う。Assert : exportEntry .[[ModuleRequest]] はnull ではない。GetImportedModule (module , exportEntry .[[ModuleRequest]] )をrequestedModule とする。requestedModule .GetExportedNames (exportStarSet )をstarNames とする。starNames の各要素name について、次を行う。name が"default" でない場合、exportedNames がname を含まない場合、name をexportedNames に追加する。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 Record とexportName からなるpairがすでにresolveSet 内にある状態で到達された場合、import circularityにencounterしています。ResolveExport をrecursiveにcallする前に、module とexportName からなる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:
Assert : module .[[Status]] はnew ではない。resolveSet が存在しない場合、resolveSet を新しい空のList に設定する。resolveSet の各Record { [[Module]] , [[ExportName]] } record について、次を行う。module とrecord .[[Module]] が同じModule Record であり、かつexportName がrecord .[[ExportName]] である場合、Assert : これは循環import要求である。null を返す。Record { [[Module]] : module , [[ExportName]] : exportName }をresolveSet に追加する。module .[[LocalExportEntries]] の各ExportEntry Record exportEntry について、次を行う。exportEntry .[[ExportName]] がexportName である場合、Assert : module はこのエクスポートに対する直接束縛を提供する。ResolvedBinding Record { [[Module]] : module , [[BindingName]] : exportEntry .[[LocalName]] }を返す。module .[[IndirectExportEntries]] の各ExportEntry Record exportEntry について、次を行う。exportEntry .[[ExportName]] がexportName である場合、Assert : exportEntry .[[ModuleRequest]] はnull ではない。GetImportedModule (module , exportEntry .[[ModuleRequest]] )をimportedModule とする。exportEntry .[[ImportName]] がnamespace である場合、Assert : module はこのエクスポートに対する直接束縛を提供しない。ResolvedBinding Record { [[Module]] : importedModule , [[BindingName]] : namespace }を返す。Assert : module はこのエクスポートに対する特定の束縛をインポートしている。Assert : exportEntry .[[ImportName]] はStringである。importedModule .ResolveExport (exportEntry .[[ImportName]] , resolveSet )を返す。exportName が"default" である場合、Assert : defaultエクスポートはこのモジュールによって明示的に定義されていなかった。null を返す。NOTE : defaultエクスポートはexport * from "mod"宣言によって提供されることはできない。starResolution をnull とする。module .[[StarExportEntries]] の各ExportEntry Record exportEntry について、次を行う。Assert : exportEntry .[[ModuleRequest]] はnull ではない。GetImportedModule (module , exportEntry .[[ModuleRequest]] )をimportedModule とする。importedModule .ResolveExport (exportName , resolveSet )をresolution とする。resolution がambiguous である場合、ambiguous を返す。resolution がnull でない場合、Assert : resolution はResolvedBinding Record である。starResolution がnull である場合、starResolution をresolution に設定する。そうでなければ、Assert : 要求された名前を含む*エクスポートが複数存在する。resolution .[[Module]] とstarResolution .[[Module]] が同じModule Record でない場合、ambiguous を返す。resolution .[[BindingName]] がstarResolution .[[BindingName]] でない場合、ambiguous を返す。 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:
module .[[IndirectExportEntries]] の各ExportEntry Record exportEntry について、次を行う。Assert : exportEntry .[[ExportName]] はnull ではない。module .ResolveExport (exportEntry .[[ExportName]] )をresolution とする。resolution がnull またはambiguous のいずれかである場合、SyntaxError 例外を投げる。Assert : resolution はResolvedBinding Record である。Assert : module からのすべての名前付きエクスポートは解決可能である。module .[[Realm]] をrealm とする。Assert : realm はundefined ではない。NewModuleEnvironment (realm .[[GlobalEnv]] )をenvRecord とする。module .[[Environment]] をenvRecord に設定する。module .[[ImportEntries]] の各ImportEntry Record importEntry について、次を行う。GetImportedModule (module , importEntry .[[ModuleRequest]] )をimportedModule とする。importEntry .[[ImportName]] がnamespace である場合、GetModuleNamespace (importedModule )をnamespace とする。! envRecord .CreateImmutableBinding (importEntry .[[LocalName]] , true )を実行する。 ! envRecord .InitializeBinding (importEntry .[[LocalName]] , namespace )を実行する。 そうでなければ、Assert : importEntry .[[ImportName]] はStringである。importedModule .ResolveExport (importEntry .[[ImportName]] )をresolution とする。resolution がnull またはambiguous のいずれかである場合、SyntaxError 例外を投げる。resolution .[[BindingName]] がnamespace である場合、GetModuleNamespace (resolution .[[Module]] )をnamespace とする。! envRecord .CreateImmutableBinding (importEntry .[[LocalName]] , true )を実行する。 ! envRecord .InitializeBinding (importEntry .[[LocalName]] , namespace )を実行する。 そうでなければ、CreateImportBinding (envRecord , importEntry .[[LocalName]] , resolution .[[Module]] , resolution .[[BindingName]] )を実行する。 moduleContext を新しいECMAScriptコード実行コンテキストとする。moduleContext のFunctionをnull に設定する。Assert : module .[[Realm]] はundefined ではない。moduleContext のRealm をmodule .[[Realm]] に設定する。moduleContext のScriptOrModuleをmodule に設定する。moduleContext のVariableEnvironmentをmodule .[[Environment]] に設定する。moduleContext のLexicalEnvironmentをmodule .[[Environment]] に設定する。moduleContext のPrivateEnvironmentをnull に設定する。module .[[Context]] をmoduleContext に設定する。moduleContext を実行コンテキストスタックにプッシュする。moduleContext は現在、実行中の実行コンテキストである。module .[[ECMAScriptCode]] をcode とする。code のVarScopedDeclarations をvariableDecls とする。declaredVariableNames を新しい空のList とする。variableDecls の各要素variableDecl について、次を行う。variableDecl のBoundNames の各要素name について、次を行う。declaredVariableNames がname を含まない場合、! envRecord .CreateMutableBinding (name , false )を実行する。 ! envRecord .InitializeBinding (name , undefined )を実行する。 name をdeclaredVariableNames に追加する。code のLexicallyScopedDeclarations をlexicalDecls とする。privateEnv をnull とする。lexicalDecls の各要素lexicalDecl について、次を行う。lexicalDecl のBoundNames の各要素name について、次を行う。lexicalDecl のIsConstantDeclaration がtrue である場合、! envRecord .CreateImmutableBinding (name , true )を実行する。 そうでなければ、! envRecord .CreateMutableBinding (name , false )を実行する。 lexicalDecl がFunctionDeclaration 、GeneratorDeclaration 、AsyncFunctionDeclaration 、またはAsyncGeneratorDeclaration のいずれかである場合、envRecord およびprivateEnv を引数として、lexicalDecl のInstantiateFunctionObject をfuncObj とする。! envRecord .InitializeBinding (name , funcObj )を実行する。 moduleContext を実行コンテキストスタックから取り除く。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:
Assert : module はリンク済みであり、そのモジュール環境内の宣言はインスタンス化済みである。moduleContext を module .[[Context]] とする。module .[[HasTLA]] が false である場合、thenAssert : capability は存在しない。env を module .[[Environment]] とする。実行中の実行コンテキストを一時停止する。 moduleContext を実行コンテキストスタックにプッシュする。moduleContext は今や実行中の実行コンテキストである。result を module .[[ECMAScriptCode]] の Evaluation の Completion とする。result を Completion (DisposeResources (env .[[DisposableResourceStack]] , result )) に設定する。moduleContext を一時停止し、それを実行コンテキストスタックから取り除く。現在実行コンテキストスタックの最上位にあるコンテキストを、実行中の実行コンテキストとして再開する。 result が abrupt completion である場合、thenReturn ? result . Else,Assert : capability は PromiseCapability Record である。AsyncBlockStart (capability , module .[[ECMAScriptCode]] , moduleContext ) を実行する。 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:
realm をcurrent Realm Record とする。defaultExport をcaptureし、呼び出されたとき次のstepsを実行する、parameters (module )を持つ新しいAbstract Closure setDefaultExport とする:SetSyntheticModuleExport (module , "default" , defaultExport )を実行する。NormalCompletion (unused )を返す。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:
parseResult を ? ParseJSON (source ) とする。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:
Assert : module .[[ExportNames]] はexportName を含む。envRecord をmodule .[[Environment]] とする。Assert : envRecord はempty でない。! envRecord .SetMutableBinding (exportName , exportValue , true )を実行する。 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:
NOTE : LoadRequestedModules のこのimplementationはhostDefined を使用しない。! PromiseResolve (%Promise% , undefined )を返す。
Note
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:
NOTE : GetExportedNames のこのimplementationはexportStarSet を使用しない。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:
NOTE : ResolveExport のこのimplementationはresolveSet を使用しない。module .[[ExportNames]] がexportName を含まないなら、null を返す。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:
realm をmodule .[[Realm]] とする。envRecord をNewModuleEnvironment (realm .[[GlobalEnv]] )とする。module .[[Environment]] をenvRecord に設定する。module .[[ExportNames]] の各String exportName について、以下を行う! envRecord .CreateMutableBinding (exportName , false )を実行する。 ! envRecord .InitializeBinding (exportName , undefined )を実行する。 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:
moduleContext を新しいECMAScript code execution context とする。moduleContext のFunctionをnull に設定する。moduleContext のRealm をmodule .[[Realm]] に設定する。moduleContext のScriptOrModuleをmodule に設定する。moduleContext のVariableEnvironmentをmodule .[[Environment]] に設定する。moduleContext のLexicalEnvironmentをmodule .[[Environment]] に設定する。running execution context をsuspendする。moduleContext をexecution context stack へpushする;moduleContext は現在running execution context である。steps をmodule .[[EvaluationSteps]] とする。result をCompletion (steps (module ))とする。moduleContext をsuspendし、それをexecution context stack からremoveする。execution context stack のtopにあるcontextをrunning execution context としてresumeする。promiseCapability を ! NewPromiseCapability (%Promise% ) とする。IfAbruptRejectPromise (result , promiseCapability )。! Call (promiseCapability .[[Resolve]] , undefined , « undefined »)を実行する。 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:
records を、referrer .[[LoadedModules]] の各LoadedModuleRequest Record r のうち、ModuleRequestsEqual (r , request )がtrue であるものから構成されるList とする。Assert : このabstract operationをinvokeする前にLoadRequestedModules がreferrer 上でsuccessfullyに完了しているため、records はちょうど1つの要素を持つ。record をrecords の唯一の要素とする。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
referrer がRealm 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 contexts をexecution 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 である;
かつ、result がnormal 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 )を実行するとき、result はParseJSONModule のinvocationによって返されたCompletion Record またはthrow completion のいずれかでなければなりません。
operationはpayload をFinishLoadingImportedModule へ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:
result がnormal completion なら、referrer .[[LoadedModules]] が、ModuleRequestsEqual (record , moduleRequest )がtrue であるようなLoadedModuleRequest Record record を含むなら、Assert : record .[[Module]] とresult .[[Value]] は同じModule Record である。そうでなければ、LoadedModuleRequest Record { [[Specifier]] : moduleRequest .[[Specifier]] , [[Attributes]] : moduleRequest .[[Attributes]] , [[Module]] : result .[[Value]] }をreferrer .[[LoadedModules]] へappendする。 payload がGraphLoadingState Record なら、ContinueModuleLoading (payload , result )を実行する。そうでなければ、ContinueDynamicImport (payload , result )を実行する。 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:
supported をHostGetSupportedImportAttributes ()とする。attrs の各ImportAttribute Record attr について、以下を行うsupported がattr .[[Key]] を含まないなら、false を返す。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:
Assert : module がCyclic Module Record なら、module .[[Status]] はnew でもunlinked でもない。namespace をmodule .[[Namespace]] とする。namespace がempty なら、exportedNames をmodule .GetExportedNames ()とする。unambiguousNames を新しい空のList とする。exportedNames の各要素name について、以下を行うresolution をmodule .ResolveExport (name )とする。resolution がResolvedBinding Record なら、name をunambiguousNames へappendする。namespace をModuleNamespaceCreate (module , unambiguousNames )に設定する。namespace を返す。
Note
GetModuleNamespaceは決してthrowしません。代わりに、unresolvable namesはこの時点で単にnamespaceから除外されます。それらは、どこでもexplicitly requestedされていないambiguous star exportsだけでない限り、後でreal linking errorにつながります。
16.2.1.14 Runtime Semantics: Evaluation
Module : [empty]
undefined を返す。
ModuleBody : ModuleItemList
result をModuleItemList のEvaluation のCompletion とする。result がnormal completion であり、かつresult .[[Value]] がempty であるなら、undefined を返す。? result を返す。
ModuleItemList :
ModuleItemList
ModuleItem
sl をModuleItemList の ? Evaluation とする。s をModuleItem のEvaluation のCompletion とする。? UpdateEmpty (s , sl )を返す。
Note
ModuleItem : ImportDeclaration
empty を返す。
16.2.2 Imports
Syntax
ImportDeclaration :
import
ImportClause
FromClause
WithClause opt
;
import
ModuleSpecifier
WithClause opt
;
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
}
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]
新しい空のList を返す。
ModuleItemList :
ModuleItemList
ModuleItem
entries1 をModuleItemList のImportEntries とする。entries2 をModuleItem のImportEntries とする。entries1 とentries2 のlist-concatenation を返す。
ModuleItem :
ExportDeclaration
StatementListItem
新しい空のList を返す。
ImportDeclaration :
import
ImportClause
FromClause
WithClause opt
;
module をImportDeclaration のModuleRequests の唯一の要素とする。argument module を伴うImportClause のImportEntriesForModule を返す。
ImportDeclaration :
import
ModuleSpecifier
WithClause opt
;
新しい空の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
entries1 を、argument module を伴うImportedDefaultBinding のImportEntriesForModule とする。entries2 を、argument module を伴うNameSpaceImport のImportEntriesForModule とする。entries1 とentries2 のlist-concatenation を返す。
ImportClause :
ImportedDefaultBinding
,
NamedImports
entries1 を、argument module を伴うImportedDefaultBinding のImportEntriesForModule とする。entries2 を、argument module を伴うNamedImports のImportEntriesForModule とする。entries1 とentries2 のlist-concatenation を返す。
ImportedDefaultBinding : ImportedBinding
localName をImportedBinding のBoundNames の唯一の要素とする。defaultEntry をImportEntry Record { [[ModuleRequest]] : module , [[ImportName]] : "default" , [[LocalName]] : localName }とする。« defaultEntry »を返す。
NameSpaceImport :
*
as
ImportedBinding
localName をImportedBinding のStringValue とする。entry をImportEntry Record { [[ModuleRequest]] : module , [[ImportName]] : namespace , [[LocalName]] : localName }とする。« entry »を返す。
NamedImports :
{
}
新しい空のList を返す。
ImportsList :
ImportsList
,
ImportSpecifier
specs1 を、argument module を伴うImportsList のImportEntriesForModule とする。specs2 を、argument module を伴うImportSpecifier のImportEntriesForModule とする。specs1 とspecs2 のlist-concatenation を返す。
ImportSpecifier : ImportedBinding
localName をImportedBinding のBoundNames の唯一の要素とする。entry をImportEntry Record { [[ModuleRequest]] : module , [[ImportName]] : localName , [[LocalName]] : localName }とする。« entry »を返す。
ImportSpecifier :
ModuleExportName
as
ImportedBinding
importName をModuleExportName のStringValue とする。localName をImportedBinding のStringValue とする。entry をImportEntry Record { [[ModuleRequest]] : module , [[ImportName]] : importName , [[LocalName]] : localName }とする。« 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
{
}
新しい空のList を返す。
WithClause :
with
{
WithEntries
,opt
}
attrs をWithEntries のWithClauseToAttributes とする。attrs を、それらの[[Key]] fieldのlexicographic orderに従ってsortする。このとき各fieldの値をUTF-16 code unit valuesのsequenceとして扱う。NOTE : このsortingは、hosts がattributesがenumeratedされるorderに基づいてbehaviourを変更することをprohibitedされる点でのみobservableである。attrs を返す。
WithEntries :
AttributeKey
:
StringLiteral
key をAttributeKey のPropName とする。entry をImportAttribute Record { [[Key]] : key , [[Value]] : StringLiteral のSV }とする。« entry »を返す。
WithEntries :
AttributeKey
:
StringLiteral
,
WithEntries
key をAttributeKey のPropName とする。entry をImportAttribute Record { [[Key]] : key , [[Value]] : StringLiteral のSV }とする。rest をWithEntries のWithClauseToAttributes とする。« entry »とrest のlist-concatenation を返す。
16.2.3 Exports
Syntax
ExportDeclaration :
export
ExportFromClause
FromClause
WithClause opt
;
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
16.2.3.2 Static Semantics: ExportedBindings
The syntax-directed operation ExportedBindings takes no arguments and returns a List of Strings.
Note
ExportedBindingsは、Module のExportedNames にexplicitlyに関連付けられたlocally bound namesです。
It is defined piecewise over the following productions:
ModuleItemList :
ModuleItemList
ModuleItem
names1 をModuleItemList のExportedBindings とする。names2 をModuleItem のExportedBindings とする。names1 とnames2 のlist-concatenation を返す。
ModuleItem :
ImportDeclaration
StatementListItem
新しい空のList を返す。
ExportDeclaration :
export
ExportFromClause
FromClause
WithClause opt
;
新しい空のList を返す。
ExportDeclaration :
export
NamedExports
;
NamedExports のExportedBindings を返す。
ExportDeclaration :
export
VariableStatement
VariableStatement のBoundNames を返す。
ExportDeclaration :
export
Declaration
Declaration のBoundNames を返す。
ExportDeclaration :
export
default
HoistableDeclaration
export
default
ClassDeclaration
export
default
AssignmentExpression
;
this ExportDeclaration のBoundNames を返す。
NamedExports :
{
}
新しい空のList を返す。
ExportsList :
ExportsList
,
ExportSpecifier
names1 をExportsList のExportedBindings とする。names2 をExportSpecifier のExportedBindings とする。names1 とnames2 のlist-concatenation を返す。
ExportSpecifier : ModuleExportName
唯一の要素がModuleExportName のStringValue であるList を返す。
ExportSpecifier :
ModuleExportName
as
ModuleExportName
唯一の要素が最初のModuleExportName のStringValue である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
names1 をModuleItemList のExportedNames とする。names2 をModuleItem のExportedNames とする。names1 とnames2 のlist-concatenation を返す。
ModuleItem : ExportDeclaration
ExportDeclaration のExportedNames を返す。
ModuleItem :
ImportDeclaration
StatementListItem
新しい空のList を返す。
ExportDeclaration :
export
ExportFromClause
FromClause
WithClause opt
;
ExportFromClause のExportedNames を返す。
ExportFromClause : *
新しい空のList を返す。
ExportFromClause :
*
as
ModuleExportName
唯一の要素がModuleExportName のStringValue であるList を返す。
ExportFromClause : NamedExports
NamedExports のExportedNames を返す。
ExportDeclaration :
export
VariableStatement
VariableStatement のBoundNames を返す。
ExportDeclaration :
export
Declaration
Declaration のBoundNames を返す。
ExportDeclaration :
export
default
HoistableDeclaration
export
default
ClassDeclaration
export
default
AssignmentExpression
;
« "default" »を返す。
NamedExports :
{
}
新しい空のList を返す。
ExportsList :
ExportsList
,
ExportSpecifier
names1 をExportsList のExportedNames とする。names2 をExportSpecifier のExportedNames とする。names1 とnames2 のlist-concatenation を返す。
ExportSpecifier : ModuleExportName
唯一の要素がModuleExportName のStringValue であるList を返す。
ExportSpecifier :
ModuleExportName
as
ModuleExportName
唯一の要素が2番目のModuleExportName のStringValue である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]
新しい空のList を返す。
ModuleItemList :
ModuleItemList
ModuleItem
entries1 をModuleItemList のExportEntries とする。entries2 をModuleItem のExportEntries とする。entries1 とentries2 のlist-concatenation を返す。
ModuleItem :
ImportDeclaration
StatementListItem
新しい空のList を返す。
ExportDeclaration :
export
ExportFromClause
FromClause
WithClause opt
;
module をExportDeclaration のModuleRequests の唯一の要素とする。argument module を伴うExportFromClause のExportEntriesForModule を返す。
ExportDeclaration :
export
NamedExports
;
argument null を伴うNamedExports のExportEntriesForModule を返す。
ExportDeclaration :
export
VariableStatement
entries を新しい空のList とする。names をVariableStatement のBoundNames とする。names の各要素name について、以下を行うExportEntry Record { [[ModuleRequest]] : null , [[ImportName]] : null , [[LocalName]] : name , [[ExportName]] : name }をentries へappendする。entries を返す。
ExportDeclaration :
export
Declaration
entries を新しい空のList とする。names をDeclaration のBoundNames とする。names の各要素name について、以下を行うExportEntry Record { [[ModuleRequest]] : null , [[ImportName]] : null , [[LocalName]] : name , [[ExportName]] : name }をentries へappendする。entries を返す。
ExportDeclaration :
export
default
HoistableDeclaration
names をHoistableDeclaration のBoundNames とする。localName をnames の唯一の要素とする。唯一の要素が新しいExportEntry Record { [[ModuleRequest]] : null , [[ImportName]] : null , [[LocalName]] : localName , [[ExportName]] : "default" }であるList を返す。
ExportDeclaration :
export
default
ClassDeclaration
names をClassDeclaration のBoundNames とする。localName をnames の唯一の要素とする。唯一の要素が新しいExportEntry Record { [[ModuleRequest]] : null , [[ImportName]] : null , [[LocalName]] : localName , [[ExportName]] : "default" }であるList を返す。
ExportDeclaration :
export
default
AssignmentExpression
;
entry をExportEntry Record { [[ModuleRequest]] : null , [[ImportName]] : null , [[LocalName]] : "*default*" , [[ExportName]] : "default" }とする。« 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 : *
entry をExportEntry Record { [[ModuleRequest]] : module , [[ImportName]] : all-but-default , [[LocalName]] : null , [[ExportName]] : null }とする。« entry »を返す。
ExportFromClause :
*
as
ModuleExportName
exportName をModuleExportName のStringValue とする。entry をExportEntry Record { [[ModuleRequest]] : module , [[ImportName]] : namespace , [[LocalName]] : null , [[ExportName]] : exportName }とする。« entry »を返す。
NamedExports :
{
}
新しい空のList を返す。
ExportsList :
ExportsList
,
ExportSpecifier
specs1 を、argument module を伴うExportsList のExportEntriesForModule とする。specs2 を、argument module を伴うExportSpecifier のExportEntriesForModule とする。specs1 とspecs2 のlist-concatenation を返す。
ExportSpecifier : ModuleExportName
sourceName をModuleExportName のStringValue とする。module がnull なら、localName をsourceName とする。importName をnull とする。そうでなければ、localName をnull とする。importName をsourceName とする。 唯一の要素が新しいExportEntry Record { [[ModuleRequest]] : module , [[ImportName]] : importName , [[LocalName]] : localName , [[ExportName]] : sourceName }であるList を返す。
ExportSpecifier :
ModuleExportName
as
ModuleExportName
sourceName を最初のModuleExportName のStringValue とする。exportName を2番目のModuleExportName のStringValue とする。module がnull なら、localName をsourceName とする。importName をnull とする。そうでなければ、localName をnull とする。importName をsourceName とする。 唯一の要素が新しい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 :
{
}
新しい空のList を返す。
ExportsList :
ExportsList
,
ExportSpecifier
names1 をExportsList のReferencedBindings とする。names2 をExportSpecifier のReferencedBindings とする。names1 とnames2 のlist-concatenation を返す。
ExportSpecifier :
ModuleExportName
as
ModuleExportName
最初のModuleExportName のReferencedBindings を返す。
ModuleExportName : IdentifierName
唯一の要素がIdentifierName であるList を返す。
ModuleExportName : StringLiteral
唯一の要素がStringLiteral であるList を返す。
16.2.3.7 Runtime Semantics: Evaluation
ExportDeclaration :
export
ExportFromClause
FromClause
WithClause opt
;
export
NamedExports
;
empty を返す。
ExportDeclaration :
export
VariableStatement
VariableStatement の ? Evaluation を返す。
ExportDeclaration :
export
Declaration
Declaration の ? Evaluation を返す。
ExportDeclaration :
export
default
HoistableDeclaration
HoistableDeclaration の ? Evaluation を返す。
ExportDeclaration :
export
default
ClassDeclaration
value をClassDeclaration の ? BindingClassDeclarationEvaluation とする。className をClassDeclaration のBoundNames の唯一の要素とする。className が"*default*" なら、envRecord をrunning execution context のLexicalEnvironmentとする。? InitializeBoundName ("*default*" , value , envRecord )を実行する。 empty を返す。
ExportDeclaration :
export
default
AssignmentExpression
;
IsAnonymousFunctionDefinition (AssignmentExpression )がtrue なら、value を、argument "default" を伴うAssignmentExpression の ? NamedEvaluation とする。そうでなければ、rhs をAssignmentExpression の ? Evaluation とする。value を ? GetValue (rhs ) とする。 envRecord をrunning execution context のLexicalEnvironmentとする。? InitializeBoundName ("*default*" , value , envRecord )を実行する。 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 で制限されている場合を除き、hostまたはimplementationはScript syntax、Module syntax、およびregular expression patternまたはflag syntaxを拡張してもよいです。これを可能にするため、SyntaxError をthrowすることが許されているすべてのoperations(evalの呼び出し、regular expression literalの使用、またはFunctionもしくはRegExp constructor の使用など)は、script syntaxまたはregular expression patternもしくはflag syntaxへのhost-defined extensionに遭遇したとき、SyntaxError をthrowする代わりにhost-defined behaviourを示すことが許されます。
17.1 で制限されている場合を除き、hostまたはimplementationは、この仕様で記述されるものを超える追加のtypes、values、objects、properties、およびfunctionsを提供してもよいです。これにより、constructs(global scope内でvariableをlookupするなど)は、error(ReferenceError など)をthrowする代わりにhost-defined behaviourを持つ場合があります。
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に作成されたrealm のRealm 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.prototype(20.2.3 )のinitial valueであるFunction prototype object を、その[[Prototype]] internal slotのvalueとして持ちます。
特に指定されない限り、すべてのbuilt-in prototype objectは、Object prototype object 自体を除き、式Object.prototype(20.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 は:
controlが任意のexecution context に入る前に作成されます。
[[Construct]] internal methodを持ちません;new operatorを伴うconstructor として使用できません。
[[Call]] internal methodを持ちません;functionとして呼び出せません。
valueがhost-defined である[[Prototype]] internal slotを持ちます。
この仕様で定義されるpropertiesに加えて、host-defined propertiesを持ってもよいです。これには、そのvalueがglobal object自身であるpropertyが含まれる場合があります。
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はNaN (6.1.6.1 を参照)です。
このpropertyはattributes { [[Writable]] : false , [[Enumerable]] : false , [[Configurable]] : false }を持ちます。
19.1.4 undefined
global object の"undefined" propertyのinitial valueはundefined (6.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を実行します:
? 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:
Assert : direct がfalse なら、strictCaller もfalse である。source がStringでないなら、source を返す。evalRealm をcurrent Realm Record とする。NOTE : direct eval の場合、evalRealm はevalのcallerとeval function自身の両方のrealm である。? HostEnsureCanCompileStrings (evalRealm , « », source , direct )を実行する。 inFunc をfalse とする。inMethod をfalse とする。inDerivedCtor をfalse とする。inClassFieldInitializer をfalse とする。direct がtrue なら、thisEnvRecord をGetThisEnvironment ()とする。thisEnvRecord がFunction Environment Record なら、func をthisEnvRecord .[[FunctionObject]] とする。inFunc をtrue に設定する。inMethod をthisEnvRecord .HasSuperBinding ()に設定する。func .[[ConstructorKind]] がderived なら、inDerivedCtor をtrue に設定する。classFieldInitializerName をfunc .[[ClassFieldInitializerName]] とする。classFieldInitializerName がempty でないなら、inClassFieldInitializer をtrue に設定する。次のsubstepsをimplementation-defined orderで実行し、parsingとerror detectionをinterleaveしてもよい:script をParseText (source , Script )とする。script がerrorsのList なら、SyntaxError 例外をthrowする。script Contains ScriptBody がfalse なら、undefined を返す。body をscript のScriptBody とする。inFunc がfalse であり、body Contains NewTarget であるなら、SyntaxError 例外をthrowする。inMethod がfalse であり、body Contains SuperProperty であるなら、SyntaxError 例外をthrowする。inDerivedCtor がfalse であり、body Contains SuperCall であるなら、SyntaxError 例外をthrowする。inClassFieldInitializer がtrue であり、body のContainsArguments がtrue であるなら、SyntaxError 例外をthrowする。 strictCaller がtrue なら、strictEval をtrue とする。そうでなければ、strictEval をscript のScriptIsStrict とする。 runningContext をrunning execution context とする。NOTE : direct がtrue なら、runningContext はdirect eval を実行したexecution context である。direct がfalse なら、runningContext はeval functionのinvocationに対するexecution context である。direct がtrue なら、lexicalEnv をNewDeclarativeEnvironment (runningContext のLexicalEnvironment)とする。variableEnv をrunningContext のVariableEnvironmentとする。privateEnv をrunningContext のPrivateEnvironmentとする。そうでなければ、lexicalEnv をNewDeclarativeEnvironment (evalRealm .[[GlobalEnv]] )とする。variableEnv をevalRealm .[[GlobalEnv]] とする。privateEnv をnull とする。 strictEval がtrue なら、variableEnv をlexicalEnv に設定する。runningContext がまだsuspendedでないなら、runningContext をsuspendする。evalContext を新しいECMAScript code execution context とする。evalContext のFunctionをnull に設定する。evalContext のRealm をevalRealm に設定する。evalContext のScriptOrModuleをrunningContext のScriptOrModuleに設定する。evalContext のVariableEnvironmentをvariableEnv に設定する。evalContext のLexicalEnvironmentをlexicalEnv に設定する。evalContext のPrivateEnvironmentをprivateEnv に設定する。evalContext をexecution context stack へpushする;evalContext は現在running execution context である。result をCompletion (EvalDeclarationInstantiation (body , variableEnv , lexicalEnv , privateEnv , strictEval ))とする。result がnormal completion なら、result をCompletion (body のEvaluation )に設定する。result がnormal completion であり、result .[[Value]] がempty であるなら、result をNormalCompletion (undefined )に設定する。evalContext をsuspendし、execution context stack からremoveする。execution context stack のtopにあるcontextをrunning execution context としてresumeする。? 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されます。let、const、または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:
body のVarDeclaredNames をvariableNames とする。body のVarScopedDeclarations をvariableDecls とする。strict がfalse である場合、variableEnv がGlobal Environment Record である場合、variableNames の各要素name について、次を行う。HasLexicalDeclaration (variableEnv , name )がtrue である場合、SyntaxError 例外を投げる。NOTE : evalは、グローバルlexical宣言によってシャドーイングされることになるグローバルvar宣言を作成しない。lexicalEnv をthisEnv とする。Assert : 次のループは終了する。thisEnv とvariableEnv が同じEnvironment Record でない間、繰り返す。thisEnv がObject Environment Record でない場合、NOTE : with文の環境はlexical宣言を含むことができないため、var/letの巻き上げの競合を確認する必要はない。variableNames の各要素name について、次を行う。! thisEnv .HasBinding (name )がtrue である場合、ホスト がWebブラウザである、またはその他の形でCatch Blocks内のVariableStatements をサポートする場合、thisEnv がCatch 節のEnvironment Record でない場合、SyntaxError 例外を投げる。そうでなければ、SyntaxError 例外を投げる。 NOTE : direct eval は、同名のlexical宣言を越えてvar宣言を巻き上げない。thisEnv をthisEnv .[[OuterEnv]] に設定する。privateIdentifiers を新しい空のList とする。privateEnv をpointer とする。pointer がnull でない間、繰り返す。pointer .[[Names]] の各Private Name binding について、次を行う。privateIdentifiers がbinding .[[Description]] を含まない場合、binding .[[Description]] をprivateIdentifiers に追加する。pointer をpointer .[[OuterPrivateEnvironment]] に設定する。privateIdentifiers を引数とするbody のAllPrivateIdentifiersValid がfalse である場合、SyntaxError 例外を投げる。funcsToInitialize を新しい空のList とする。declaredFuncNames を新しい空のList とする。variableDecls の各要素variableDecl について、List の逆順で、次を行う。variableDecl がVariableDeclaration 、ForBinding 、またはBindingIdentifier のいずれでもない場合、Assert : variableDecl は、FunctionDeclaration 、GeneratorDeclaration 、AsyncFunctionDeclaration 、またはAsyncGeneratorDeclaration のいずれかである。NOTE : 同じ名前に対して複数の関数宣言がある場合、最後の宣言が使用される。variableDecl のBoundNames の唯一の要素をfuncName とする。declaredFuncNames がfuncName を含まない場合、variableEnv がGlobal Environment Record である場合、? CanDeclareGlobalFunction (variableEnv , funcName )をfuncDefinable とする。 funcDefinable がfalse である場合、TypeError 例外を投げる。funcName をdeclaredFuncNames に追加する。variableDecl をfuncsToInitialize の最初の要素として挿入する。declaredVariableNames を新しい空のList とする。variableDecls の各要素variableDecl について、次を行う。variableDecl がVariableDeclaration 、ForBinding 、またはBindingIdentifier のいずれかである場合、variableDecl のBoundNames の各String name について、次を行う。declaredFuncNames がname を含まない場合、variableEnv がGlobal Environment Record である場合、? CanDeclareGlobalVar (variableEnv , name )をvariableDefinable とする。 variableDefinable がfalse である場合、TypeError 例外を投げる。declaredVariableNames がname を含まない場合、name をdeclaredVariableNames に追加する。strict がfalse であり、かつホスト がWebブラウザである、またはその他の形でBlock-Level Function Declarations Web Legacy Compatibility Semantics をサポートする場合、declaredFuncNames とdeclaredVariableNames のlist-concatenation をdeclaredFuncOrVariableNames とする。body Contains x がtrue であるような任意のBlock 、CaseClause 、またはDefaultClause x のStatementList に直接含まれる各FunctionDeclaration funcDecl について、次を行う。funcDecl のBindingIdentifier のStringValue をfuncName とする。FunctionDeclaration funcDecl を、funcName をBindingIdentifier として持つVariableStatement に置き換えても、body に対してEarly Errorsが発生しない場合、bindingExists をfalse とする。thisEnv をlexicalEnv に設定する。Assert : 次のループは終了する。thisEnv がvariableEnv でない間、繰り返す。thisEnv がObject Environment Record でない場合、! thisEnv .HasBinding (funcName )がtrue である場合、ホスト がWebブラウザである、またはその他の形でCatch Blocks内のVariableStatements をサポートする場合、thisEnv がCatch 節のEnvironment Record でない場合、bindingExists をtrue に設定する。そうでなければ、bindingExists をtrue に設定する。 thisEnv をthisEnv .[[OuterEnv]] に設定する。bindingExists がfalse であり、かつvariableEnv がGlobal Environment Record である場合、HasLexicalDeclaration (variableEnv , funcName )がfalse である場合、? CanDeclareGlobalVar (variableEnv , funcName )をfuncDefinable とする。 そうでなければ、funcDefinable をfalse とする。 そうでなければ、funcDefinable をtrue とする。 bindingExists がfalse であり、かつfuncDefinable がtrue である場合、declaredFuncOrVariableNames がfuncName を含まない場合、variableEnv がGlobal Environment Record である場合、? CreateGlobalVarBinding (variableEnv , funcName , true )を実行する。 そうでなければ、! variableEnv .HasBinding (funcName )をbindingExists に設定する。 bindingExists がfalse である場合、! variableEnv .CreateMutableBinding (funcName , true )を実行する。 ! variableEnv .InitializeBinding (funcName , undefined )を実行する。 funcName をdeclaredFuncOrVariableNames に追加する。FunctionDeclaration funcDecl が評価されるとき、15.2.6 で提供されるFunctionDeclaration Evaluation アルゴリズムの代わりに、次のステップを実行する。実行中の実行コンテキストのVariableEnvironmentをglobalEnv とする。 実行中の実行コンテキストのLexicalEnvironmentをblockEnv とする。 ! blockEnv .GetBindingValue (funcName , false )をfuncObj とする。 ? globalEnv .SetMutableBinding (funcName , funcObj , false ) を実行する。 unused を返す。NOTE : variableEnv がGlobal Environment Record であり、かつグローバルオブジェクトがProxy exotic object である場合を除き、このアルゴリズムステップ以降に異常終了は発生しない。body のLexicallyScopedDeclarations をlexicalDecls とする。lexicalDecls の各要素lexicalDecl について、次を行う。NOTE : Lexically declared nameは、ここでインスタンス化されるだけで、初期化されない。lexicalDecl のBoundNames の各要素name について、次を行う。lexicalDecl のIsConstantDeclaration がtrue である場合、? lexicalEnv .CreateImmutableBinding (name , true )を実行する。 そうでなければ、? lexicalEnv .CreateMutableBinding (name , false )を実行する。 funcsToInitialize の各Parse Node funcDecl について、次を行う。funcDecl のBoundNames の唯一の要素をfuncName とする。lexicalEnv およびprivateEnv を引数として、funcDecl のInstantiateFunctionObject をfuncObj とする。variableEnv がGlobal Environment Record である場合、? CreateGlobalFunctionBinding (variableEnv , funcName , funcObj , true )を実行する。 そうでなければ、! variableEnv .HasBinding (funcName )をbindingExists とする。 bindingExists がfalse である場合、NOTE : 次の呼び出しは、ステップ14 に先立つ検証により、abrupt completion を返すことができない。! variableEnv .CreateMutableBinding (funcName , true )を実行する。 ! variableEnv .InitializeBinding (funcName , funcObj )を実行する。 そうでなければ、! variableEnv .SetMutableBinding (funcName , funcObj , false )を実行する。 declaredVariableNames の各String variableName について、次を行う。variableEnv がGlobal Environment Record である場合、? CreateGlobalVarBinding (variableEnv , variableName , true )を実行する。 そうでなければ、! variableEnv .HasBinding (variableName )をbindingExists とする。 bindingExists がfalse である場合、NOTE : 次の呼び出しは、ステップ14 に先立つ検証により、abrupt completion を返すことができない。! variableEnv .CreateMutableBinding (variableName , true )を実行する。 ! variableEnv .InitializeBinding (variableName , undefined )を実行する。 unused を返す。
19.2.2 isFinite ( value )
このfunctionは%isFinite% intrinsic objectです。
これは呼び出されたとき、次のstepsを実行します:
number を ? ToNumber (value ) とする。number がfinite なら、true を返す。false を返す。
19.2.3 isNaN ( value )
このfunctionは%isNaN% intrinsic objectです。
これは呼び出されたとき、次のstepsを実行します:
number を ? ToNumber (value ) とする。number がNaN なら、true を返す。false を返す。
Note
ECMAScript codeがvalue XがNaN かどうかをtestするreliableな方法は、X !== Xという形式のexpressionです。そのresultは、XがNaN である場合に限りtrue になります。
19.2.4 parseFloat ( string )
このfunctionは、string argumentのcontentsをdecimal literalとしてinterpretすることによってdictatedされるNumber valueをproduceします。
これは%parseFloat% intrinsic objectです。
これは呼び出されたとき、次のstepsを実行します:
inputString を ? ToString (string ) とする。trimmedString を ! TrimString (inputString , start ) とする。trimmed をStringToCodePoints (trimmedString )とする。trimmedPrefix を、StrDecimalLiteral のsyntaxをsatisfiesするtrimmed のlongest prefixとする。これはtrimmed 自身である場合があります。そのようなprefixがない場合、NaN を返す。parsedNumber をParseText (trimmedPrefix , StrDecimalLiteral )とする。Assert : parsedNumber はParse Node である。parsedNumber のStringNumericValue を返す。
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を実行します:
inputString を ? ToString (string ) とする。trimmedString を ! TrimString (inputString , start ) とする。sign を1とする。trimmedString がemptyでなく、trimmedString の最初のcode unitがcode unit 0x002D (HYPHEN-MINUS)であるなら、sign を-1に設定する。trimmedString がemptyでなく、trimmedString の最初のcode unitがcode unit 0x002B (PLUS SIGN)またはcode unit 0x002D (HYPHEN-MINUS)のいずれかであるなら、trimmedString をindex 1からのtrimmedString のsubstring に設定する。radixMV をℝ (? ToInt32 (radix ))とする。stripPrefix をtrue とする。radixMV ≠ 0なら、radixMV < 2またはradixMV > 36なら、NaN を返す。radixMV ≠ 16なら、stripPrefix をfalse に設定する。そうでなければ、radixMV を10に設定する。 stripPrefix がtrue なら、trimmedString のlengthが≥ 2であり、trimmedString の最初の2つのcode unitsが"0x" または"0X" のいずれかであるなら、trimmedString をindex 2からのtrimmedString のsubstring に設定する。radixMV を16に設定する。trimmedString がradix-radixMV digitでないcode unitを含むなら、end をtrimmedString 内の最初のそのようなcode unitのindexとする;そうでなければ、end をtrimmedString のlengthとする。numberString を0からend までのtrimmedString のsubstring とする。numberString がemptyなら、NaN を返す。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 であってもよい。)mathInt = 0なら、sign = -1なら、-0 𝔽 を返す。+0 𝔽 を返す。𝔽 (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を実行します:
uriString を ? ToString (encodedURI ) とする。preserveEscapeSet を";/?:@&=+$,#" とする。? 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を実行します:
componentString を ? ToString (encodedURIComponent ) とする。preserveEscapeSet をempty Stringとする。? 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を実行します:
uriString を ? ToString (uri ) とする。extraUnescaped を";/?:@&=+$,#" とする。? 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を実行します:
componentString を ? ToString (uriComponent ) とする。extraUnescaped をempty Stringとする。? 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を実行し、string を6.1.4 で記述されるUTF-16 encoded code pointsのsequenceとしてinterpretします。characterがRFC 2396でunreservedとしてidentifiedされるか、extraUnescaped 内にappearする場合、それはescapedされません。 It performs the following steps when called:
length をstring のlengthとする。result をempty Stringとする。alwaysUnescaped をASCII word charactersと"-.!~*'()" のstring-concatenation とする。unescapedSet をalwaysUnescaped とextraUnescaped のstring-concatenation とする。k を0とする。k < length の間、繰り返すcodeUnit をstring 内のindex k にあるcode unitとする。unescapedSet がcodeUnit を含むなら、k をk + 1に設定する。result をresult とcodeUnit のstring-concatenation に設定する。そうでなければ、codePoint をCodePointAt (string , k )とする。codePoint .[[IsUnpairedSurrogate]] がtrue なら、URIError 例外をthrowする。k をk + codePoint .[[CodeUnitCount]] に設定する。octets をcodePoint .[[CodePoint]] にUTF-8 transformationをapplyした結果のoctetsのList とする。octets の各要素octet について、以下を行うhex をoctet のString representationとし、uppercase hexadecimal numberとしてformattedする。result をresult 、"%" 、およびStringPad (hex , 2, "0" , start )のstring-concatenation に設定する。 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:
length をstring のlengthとする。result をempty Stringとする。k を0とする。k < length の間、繰り返すcodeUnit をstring 内のindex k にあるcode unitとする。segment をcodeUnit とする。codeUnit がcode unit 0x0025 (PERCENT SIGN)であるなら、k + 3 > length なら、URIError 例外をthrowする。escape をk からk + 3までのstring のsubstring とする。firstOctet をParseHexOctet (string , k + 1)とする。firstOctet がinteger でないなら、URIError 例外をthrowする。k をk + 2に設定する。n をfirstOctet 内のleading 1 bitsの数とする。n = 0なら、asciiChar を、numeric valueがfirstOctet であるcode unitとする。preserveEscapeSet がasciiChar を含むなら、segment をescape に設定する;そうでなければ、segment をasciiChar に設定する。そうでなければ、n = 1またはn > 4なら、URIError 例外をthrowする。octets を« firstOctet »とする。j を1とする。j < n の間、繰り返すk をk + 1に設定する。k + 3 > length なら、URIError 例外をthrowする。string 内のindex k にあるcode unitがcode unit 0x0025 (PERCENT SIGN)でないなら、URIError 例外をthrowする。continuationByte をParseHexOctet (string , k + 1)とする。continuationByte がinteger でないなら、URIError 例外をthrowする。continuationByte をoctets へappendする。k をk + 2に設定する。j をj + 1に設定する。Assert : octets のlengthはn である。octets がUnicode code pointのvalid UTF-8 encodingを含まないなら、URIError 例外をthrowする。codePoint を、UTF-8 transformationをoctets にapplyして得られるcode point、すなわちoctetsのList から21-bit valueへの変換で得られるものとする。segment をUTF16EncodeCodePoint (codePoint )に設定する。 result をresult とsegment のstring-concatenation に設定する。k をk + 1に設定する。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:
length をstring のlengthとする。Assert : position + 2 ≤ length である。hexDigits をposition からposition + 2までのstring のsubstring とする。parseResult をParseText (hexDigits , HexDigits [~Sep] )とする。parseResult がParse Node でないなら、parseResult を返す。n をparseResult のMVとする。Assert : n は0から255までのinclusive interval 内にある。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 は:
20.1.1.1 Object ( value )
このfunctionは呼び出されたとき、次のstepsを実行します:
NewTargetがundefined でもactive function object でもないなら、? OrdinaryCreateFromConstructor (NewTarget, "%Object.prototype%" )を返す。 value がundefined またはnull のいずれかなら、OrdinaryObjectCreate (%Object.prototype% )を返す。! ToObject (value )を返す。
20.1.2 Properties of the Object Constructor
Object constructor は:
20.1.2.1 Object.assign ( target , ...sources )
このfunctionは、1つ以上のsource objectsからすべてのenumerable own propertiesのvaluesをtarget objectへcopyします。
これは呼び出されたとき、次のstepsを実行します:
? ToObject (target )をtargetObj とする。 引数が1個だけ渡された場合、targetObj を返す。 sources の各要素nextSource について、次を行う。nextSource がundefined でもnull でもない場合、! ToObject (nextSource )をfrom とする。 ? from .[[OwnPropertyKeys]] () をkeys とする。 keys の各要素nextKey について、次を行う。? from .[[GetOwnProperty]] (nextKey ) をpropertyDesc とする。 propertyDesc がundefined でなく、かつpropertyDesc .[[Enumerable]] がtrue である場合、? Get (from , nextKey )をpropertyValue とする。 ? Set (targetObj , nextKey , propertyValue , true )を実行する。 targetObj を返す。
このfunctionの"length" propertyは2 𝔽 です。
20.1.2.2 Object.create ( proto , properties )
このfunctionは、指定されたprototypeを持つ新しいobjectを作成します。
これは呼び出されたとき、次のstepsを実行します:
proto がObjectでなく、かつproto がnull でないなら、TypeError 例外をthrowする。obj をOrdinaryObjectCreate (proto )とする。properties がundefined でないなら、? ObjectDefineProperties (obj , properties )を返す。 obj を返す。
20.1.2.3 Object.defineProperties ( obj , properties )
このfunctionは、objectのown propertiesを追加し、かつ/または既存のown propertiesのattributesをupdateします。
これは呼び出されたとき、次のstepsを実行します:
obj がObjectでないなら、TypeError 例外をthrowする。? 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:
properties を ? ToObject (properties ) に設定する。keys を ? properties .[[OwnPropertyKeys]] () とする。propertyDescs を新しい空のList とする。keys の各要素nextKey について、以下を行うcurrentPropertyDesc を ? properties .[[GetOwnProperty]] (nextKey ) とする。currentPropertyDesc がundefined でなく、currentPropertyDesc .[[Enumerable]] がtrue なら、propertyDescObj を ? Get (properties , nextKey ) とする。propertyDesc を ? ToPropertyDescriptor (propertyDescObj ) とする。Record { [[Key]] : nextKey , [[Descriptor]] : propertyDesc }をpropertyDescs へappendする。propertyDescs の各要素property について、以下を行う? DefinePropertyOrThrow (obj , property .[[Key]] , property .[[Descriptor]] )を実行する。 obj を返す。
20.1.2.4 Object.defineProperty ( obj , key , attrs )
このfunctionは、objectのown propertyを追加し、かつ/または既存のown propertyのattributesをupdateします。
これは呼び出されたとき、次のstepsを実行します:
obj がObjectでないなら、TypeError 例外をthrowする。propertyKey を ? ToPropertyKey (key ) とする。propertyDesc を ? ToPropertyDescriptor (attrs ) とする。? DefinePropertyOrThrow (obj , propertyKey , propertyDesc )を実行する。 obj を返す。
20.1.2.5 Object.entries ( obj )
このfunctionは呼び出されたとき、次のstepsを実行します:
coerced を ? ToObject (obj ) とする。entryList を ? EnumerableOwnProperties (coerced , key+value ) とする。CreateArrayFromList (entryList )を返す。
20.1.2.6 Object.freeze ( obj )
このfunctionは呼び出されたとき、次のstepsを実行します:
obj がObjectでないなら、obj を返す。status を ? SetIntegrityLevel (obj , frozen ) とする。status がfalse なら、TypeError 例外をthrowする。obj を返す。
20.1.2.7 Object.fromEntries ( iterable )
このfunctionは呼び出されたとき、次のstepsを実行します:
? RequireObjectCoercible (iterable )を実行する。 obj をOrdinaryObjectCreate (%Object.prototype% )とする。Assert : obj はown propertiesを持たないextensible ordinary object である。obj をcaptureし、呼び出されたとき次のstepsを実行する、parameters (key , value )を持つ新しいAbstract Closure closure とする:propertyKey を ? ToPropertyKey (key ) とする。! CreateDataPropertyOrThrow (obj , propertyKey , value )を実行する。 NormalCompletion (undefined )を返す。adder をCreateBuiltinFunction (closure , 2, "" , « »)とする。? AddEntriesFromIterable (obj , iterable , adder )を返す。
Note
adder のために作成されたfunctionは、ECMAScript codeから直接accessできることはありません。
20.1.2.8 Object.getOwnPropertyDescriptor ( obj , key )
このfunctionは呼び出されたとき、次のstepsを実行します:
coerced を ? ToObject (obj ) とする。propertyKey を ? ToPropertyKey (key ) とする。propertyDesc を ? coerced .[[GetOwnProperty]] (propertyKey ) とする。FromPropertyDescriptor (propertyDesc )を返す。
20.1.2.9 Object.getOwnPropertyDescriptors ( obj )
このfunctionは呼び出されたとき、次のstepsを実行します:
coerced を ? ToObject (obj ) とする。ownKeys を ? coerced .[[OwnPropertyKeys]] () とする。descs をOrdinaryObjectCreate (%Object.prototype% )とする。ownKeys の各要素key について、以下を行うpropertyDesc を ? coerced .[[GetOwnProperty]] (key ) とする。propertyDescObj をFromPropertyDescriptor (propertyDesc )とする。propertyDescObj がundefined でないなら、! CreateDataPropertyOrThrow (descs , key , propertyDescObj )を実行する。descs を返す。
20.1.2.10 Object.getOwnPropertyNames ( obj )
このfunctionは呼び出されたとき、次のstepsを実行します:
CreateArrayFromList (? GetOwnPropertyKeys (obj , string ))を返す。
20.1.2.11 Object.getOwnPropertySymbols ( obj )
このfunctionは呼び出されたとき、次のstepsを実行します:
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:
obj を ? ToObject (value ) とする。keys を ? obj .[[OwnPropertyKeys]] () とする。nameList を新しい空のList とする。keys の各要素nextKey について、以下を行うnextKey がSymbolでありtype がsymbol である、またはnextKey がStringでありtype がstring であるなら、nextKey をnameList へappendする。nameList を返す。
20.1.2.12 Object.getPrototypeOf ( obj )
このfunctionは呼び出されたとき、次のstepsを実行します:
coerced を ? ToObject (obj ) とする。? coerced .[[GetPrototypeOf]] () を返す。
20.1.2.13 Object.groupBy ( items , callback )
Note
callback は2つのargumentsをacceptするfunctionであるべきです。groupByはitems 内の各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を実行します:
? GroupBy (items , callback , property )をgroups とする。 OrdinaryObjectCreate (null )をobj とする。groups の各Record { [[Key]] , [[Elements]] } group について、次を行う。CreateArrayFromList (group .[[Elements]] )をelements とする。! CreateDataPropertyOrThrow (obj , group .[[Key]] , elements )を実行する。 obj を返す。
20.1.2.14 Object.hasOwn ( obj , key )
このfunctionは呼び出されたとき、次のstepsを実行します:
coerced を ? ToObject (obj ) とする。propertyKey を ? ToPropertyKey (key ) とする。? HasOwnProperty (coerced , propertyKey )を返す。
20.1.2.15 Object.is ( value1 , value2 )
このfunctionは呼び出されたとき、次のstepsを実行します:
SameValue (value1 , value2 )を返す。
20.1.2.16 Object.isExtensible ( obj )
このfunctionは呼び出されたとき、次のstepsを実行します:
obj がObjectでないなら、false を返す。? IsExtensible (obj )を返す。
20.1.2.17 Object.isFrozen ( obj )
このfunctionは呼び出されたとき、次のstepsを実行します:
obj がObjectでないなら、true を返す。? TestIntegrityLevel (obj , frozen )を返す。
20.1.2.18 Object.isSealed ( obj )
このfunctionは呼び出されたとき、次のstepsを実行します:
obj がObjectでないなら、true を返す。? TestIntegrityLevel (obj , sealed )を返す。
20.1.2.19 Object.keys ( obj )
このfunctionは呼び出されたとき、次のstepsを実行します:
coerced を ? ToObject (obj ) とする。keyList を ? EnumerableOwnProperties (coerced , key ) とする。CreateArrayFromList (keyList )を返す。
20.1.2.20 Object.preventExtensions ( obj )
このfunctionは呼び出されたとき、次のstepsを実行します:
obj がObjectでないなら、obj を返す。status を ? obj .[[PreventExtensions]] () とする。status がfalse なら、TypeError 例外をthrowする。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を実行します:
obj がObjectでないなら、obj を返す。status を ? SetIntegrityLevel (obj , sealed ) とする。status がfalse なら、TypeError 例外をthrowする。obj を返す。
20.1.2.23 Object.setPrototypeOf ( obj , proto )
このfunctionは呼び出されたとき、次のstepsを実行します:
? RequireObjectCoercible (obj )を実行する。 proto がObjectでなく、かつproto がnull でないなら、TypeError 例外をthrowする。obj がObjectでないなら、obj を返す。status を ? obj .[[SetPrototypeOf]] (proto ) とする。status がfalse なら、TypeError 例外をthrowする。obj を返す。
20.1.2.24 Object.values ( obj )
このfunctionは呼び出されたとき、次のstepsを実行します:
coerced を ? ToObject (obj ) とする。valueList を ? EnumerableOwnProperties (coerced , value ) とする。CreateArrayFromList (valueList )を返す。
20.1.3 Properties of the Object Prototype Object
Object prototype object は:
20.1.3.1 Object.prototype.constructor
Object.prototype.constructorのinitial valueは%Object% です。
20.1.3.2 Object.prototype.hasOwnProperty ( value )
このmethodは呼び出されたとき、次のstepsを実行します:
propertyKey を ? ToPropertyKey (value ) とする。obj を ? ToObject (this value) とする。? 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を実行します:
value がObjectでないなら、false を返す。obj を ? ToObject (this value) とする。繰り返すvalue を ? value .[[GetPrototypeOf]] () に設定する。value がnull なら、false を返す。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を実行します:
propertyKey を ? ToPropertyKey (value ) とする。obj を ? ToObject (this value) とする。propertyDesc を ? obj .[[GetOwnProperty]] (propertyKey ) とする。propertyDesc がundefined なら、false を返す。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を実行します:
thisValue をthis valueとする。? 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を提供します。Array、Number、Date、および%TypedArray% は、それぞれ独自のlocale-sensitiveなtoLocaleString methodsを提供します。
Note 2
ECMA-402は意図的に、このdefault implementationのalternativeを提供していません。
20.1.3.6 Object.prototype.toString ( )
このmethodは呼び出されたとき、次のstepsを実行します:
this valueがundefined なら、"[object Undefined]" を返す。this valueがnull なら、"[object Null]" を返す。obj を ! ToObject (this value) とする。isArray を ? IsArray (obj ) とする。isArray がtrue なら、builtinTag を"Array" とする。そうでなく、obj が[[ParameterMap]] internal slotを持つなら、builtinTag を"Arguments" とする。 そうでなく、obj が[[Call]] internal methodを持つなら、builtinTag を"Function" とする。 そうでなく、obj が[[ErrorData]] internal slotを持つなら、builtinTag を"Error" とする。 そうでなく、obj が[[BooleanData]] internal slotを持つなら、builtinTag を"Boolean" とする。 そうでなく、obj が[[NumberData]] internal slotを持つなら、builtinTag を"Number" とする。 そうでなく、obj が[[StringData]] internal slotを持つなら、builtinTag を"String" とする。 そうでなく、obj が[[DateValue]] internal slotを持つなら、builtinTag を"Date" とする。 そうでなく、obj が[[RegExpMatcher]] internal slotを持つなら、builtinTag を"RegExp" とする。 そうでなければ、builtinTag を"Object" とする。 tag を ? Get (obj , %Symbol.toStringTag% ) とする。tag がStringでないなら、tag をbuiltinTag に設定する。"[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を実行します:
? 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を実行します:
obj を ? ToObject (this value) とする。? obj .[[GetPrototypeOf]] () を返す。
20.1.3.8.2 set Object.prototype.__proto__
[[Set]] attributeのvalueは、argument proto を取るbuilt-in functionです。これは呼び出されたとき、次のstepsを実行します:
thisValue をthis valueとする。? RequireObjectCoercible (thisValue )を実行する。 proto がObjectでなく、かつproto がnull でないなら、undefined を返す。thisValue がObjectでないなら、undefined を返す。status を ? thisValue .[[SetPrototypeOf]] (proto ) とする。status がfalse なら、TypeError 例外をthrowする。undefined を返す。
20.1.3.9 Legacy Object.prototype Accessor Methods
20.1.3.9.1 Object.prototype.__defineGetter__ ( key , getter )
このmethodは呼び出されたとき、次のstepsを実行します:
obj を ? ToObject (this value) とする。IsCallable (getter )がfalse なら、TypeError 例外をthrowする。propertyDesc をPropertyDescriptor { [[Get]] : getter , [[Enumerable]] : true , [[Configurable]] : true }とする。propertyKey を ? ToPropertyKey (key ) とする。? DefinePropertyOrThrow (obj , propertyKey , propertyDesc )を実行する。 undefined を返す。
20.1.3.9.2 Object.prototype.__defineSetter__ ( key , setter )
このmethodは呼び出されたとき、次のstepsを実行します:
obj を ? ToObject (this value) とする。IsCallable (setter )がfalse なら、TypeError 例外をthrowする。propertyDesc をPropertyDescriptor { [[Set]] : setter , [[Enumerable]] : true , [[Configurable]] : true }とする。propertyKey を ? ToPropertyKey (key ) とする。? DefinePropertyOrThrow (obj , propertyKey , propertyDesc )を実行する。 undefined を返す。
20.1.3.9.3 Object.prototype.__lookupGetter__ ( key )
このmethodは呼び出されたとき、次のstepsを実行します:
obj を ? ToObject (this value) とする。propertyKey を ? ToPropertyKey (key ) とする。繰り返すpropertyDesc を ? obj .[[GetOwnProperty]] (propertyKey ) とする。propertyDesc がundefined でないなら、IsAccessorDescriptor (propertyDesc )がtrue なら、propertyDesc .[[Get]] を返す。undefined を返す。obj を ? obj .[[GetPrototypeOf]] () に設定する。obj がnull なら、undefined を返す。
20.1.3.9.4 Object.prototype.__lookupSetter__ ( key )
このmethodは呼び出されたとき、次のstepsを実行します:
obj を ? ToObject (this value) とする。propertyKey を ? ToPropertyKey (key ) とする。繰り返すpropertyDesc を ? obj .[[GetOwnProperty]] (propertyKey ) とする。propertyDesc がundefined でないなら、IsAccessorDescriptor (propertyDesc )がtrue なら、propertyDesc .[[Set]] を返す。undefined を返す。obj を ? obj .[[GetPrototypeOf]] () に設定する。obj がnull なら、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を実行します:
ctor をactive function object とする。bodyArg が存在しないなら、bodyArg をempty Stringに設定する。? 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です。newTarget はnewがinitiallyに適用されたconstructor です。paramArgs およびbodyArg はctor へ渡されたargument valuesをreflectします。 It performs the following steps when called:
newTarget がundefined なら、newTarget をctor に設定する。kind がnormal なら、prefix を"function" とする。exprGrammar をgrammar symbol FunctionExpression とする。bodyGrammar をgrammar symbol FunctionBody [~Yield, ~Await] とする。paramGrammar をgrammar symbol FormalParameters [~Yield, ~Await] とする。fallbackProto を"%Function.prototype%" とする。そうでなく、kind がgenerator なら、prefix を"function*" とする。exprGrammar をgrammar symbol GeneratorExpression とする。bodyGrammar をgrammar symbol GeneratorBody とする。paramGrammar をgrammar symbol FormalParameters [+Yield, ~Await] とする。fallbackProto を"%GeneratorFunction.prototype%" とする。 そうでなく、kind がasync なら、prefix を"async function" とする。exprGrammar をgrammar symbol AsyncFunctionExpression とする。bodyGrammar をgrammar symbol AsyncFunctionBody とする。paramGrammar をgrammar symbol FormalParameters [~Yield, +Await] とする。fallbackProto を"%AsyncFunction.prototype%" とする。 そうでなければ、Assert : kind はasync-generator である。prefix を"async function*" とする。exprGrammar をgrammar symbol AsyncGeneratorExpression とする。bodyGrammar をgrammar symbol AsyncGeneratorBody とする。paramGrammar をgrammar symbol FormalParameters [+Yield, +Await] とする。fallbackProto を"%AsyncGeneratorFunction.prototype%" とする。 argCount をparamArgs 内の要素数とする。paramStrings を新しい空のList とする。paramArgs の各要素arg について、以下を行う? ToString (arg )をparamStrings へappendする。 bodyString を ? ToString (bodyArg ) とする。currentRealm をcurrent Realm Record とする。? HostEnsureCanCompileStrings (currentRealm , paramStrings , bodyString , false )を実行する。 paramString をempty Stringとする。argCount > 0なら、paramString をparamStrings [0]に設定する。k を1とする。k < argCount の間、繰り返すnextArgString をparamStrings [k ]とする。paramString をparamString 、"," (comma)、およびnextArgString のstring-concatenation に設定する。k をk + 1に設定する。bodyParseString を0x000A (LINE FEED)、bodyString 、および0x000A (LINE FEED)のstring-concatenation とする。sourceString をprefix 、" anonymous(" 、paramString 、0x000A (LINE FEED)、") {" 、bodyParseString 、および"}" のstring-concatenation とする。sourceText をStringToCodePoints (sourceString )とする。params をParseText (paramString , paramGrammar )とする。params がerrorsのList なら、SyntaxError 例外をthrowする。body をParseText (bodyParseString , bodyGrammar )とする。body がerrorsのList なら、SyntaxError 例外をthrowする。NOTE : parametersとbodyは、それぞれが単独でvalidであることを保証するためにseparatelyにparsedされる。例えば、new Function("/*", "*/ ) {")はfunctionへevaluateされない。NOTE : このstepに到達した場合、sourceText はexprGrammar のsyntaxを持っていなければならない(ただしそのreverse implicationは成り立たない)。次の2つのstepsの目的は、exprGrammar にdirectlyにapplyされる任意のEarly Error rulesをenforceすることである。expr をParseText (sourceText , exprGrammar )とする。expr がerrorsのList なら、SyntaxError 例外をthrowする。funcProto を ? GetPrototypeFromConstructor (newTarget , fallbackProto ) とする。envRecord をcurrentRealm .[[GlobalEnv]] とする。privateEnv をnull とする。func をOrdinaryFunctionCreate (funcProto , sourceText , params , body , non-lexical-this , envRecord , privateEnv )とする。SetFunctionName (func , "anonymous" )を実行する。kind がgenerator なら、protoProto をOrdinaryObjectCreate (%GeneratorPrototype% )とする。! DefinePropertyOrThrow (func , "prototype" , PropertyDescriptor { [[Value]] : protoProto , [[Writable]] : true , [[Enumerable]] : false , [[Configurable]] : false })を実行する。 そうでなく、kind がasync-generator なら、protoProto をOrdinaryObjectCreate (%AsyncGeneratorPrototype% )とする。! DefinePropertyOrThrow (func , "prototype" , PropertyDescriptor { [[Value]] : protoProto , [[Writable]] : true , [[Enumerable]] : false , [[Configurable]] : false })を実行する。 そうでなく、kind がnormal なら、MakeConstructor (func )を実行する。 NOTE : kind がasync であるfunctionsはconstructableではなく、[[Construct]] internal methodまたは"prototype" propertyを持たない。func を返す。
Note
CreateDynamicFunctionは、そのkind がasync でない、作成する任意のfunctionに対して"prototype" propertyを定義し、そのfunctionがconstructor として使用される可能性に備えます。
20.2.2 Properties of the Function Constructor
Function constructor は:
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を実行します:
func をthis valueとする。IsCallable (func )がfalse なら、TypeError 例外をthrowする。argArray がundefined またはnull のいずれかなら、PrepareForTailCall ()を実行する。? Call (func , thisArg )を返す。 argList を ? CreateListFromArrayLike (argArray ) とする。PrepareForTailCall ()を実行する。? Call (func , thisArg , argList )を返す。
Note 1
thisArg valueは、modificationなしでthis valueとして渡されます。これはEdition 3からのchangeであり、そこではundefined またはnull のthisArg はglobal 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を実行します:
target をthis valueとする。IsCallable (target )がfalse なら、TypeError 例外をthrowする。boundFunc を ? BoundFunctionCreate (target , thisArg , args ) とする。length を0とする。targetHasLength を ? HasOwnProperty (target , "length" ) とする。targetHasLength がtrue なら、targetLength を ? Get (target , "length" ) とする。targetLength がNumberなら、targetLength が+∞ 𝔽 なら、length を+∞に設定する。そうでなく、targetLength が-∞ 𝔽 なら、length を0に設定する。 そうでなければ、targetLengthAsInt を ! ToIntegerOrInfinity (targetLength ) とする。Assert : targetLengthAsInt はfinite である。argCount をargs 内の要素数とする。length をmax (targetLengthAsInt - argCount , 0)に設定する。 SetFunctionLength (boundFunc , length )を実行する。targetName を ? Get (target , "name" ) とする。targetName がStringでないなら、targetName をempty Stringに設定する。SetFunctionName (boundFunc , targetName , "bound" )を実行する。boundFunc を返す。
Note 1
Function.prototype.bindを使用して作成されたFunction objects はexotic objects です。それらはまた"prototype" propertyを持ちません。
Note 2
target がarrow functionまたはbound function exotic object のいずれかである場合、このmethodに渡されたthisArg はfunc へのsubsequent callsによって使用されません。
20.2.3.3 Function.prototype.call ( thisArg , ...args )
このmethodは呼び出されたとき、次のstepsを実行します:
func をthis valueとする。IsCallable (func )がfalse なら、TypeError 例外をthrowする。PrepareForTailCall ()を実行する。? Call (func , thisArg , args )を返す。
Note 1
thisArg valueは、modificationなしでthis valueとして渡されます。これはEdition 3からのchangeであり、そこではundefined またはnull のthisArg はglobal 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を実行します:
func をthis valueとする。func がObjectであり、func が[[SourceText]] internal slotを持ち、func .[[SourceText]] がUnicode code pointsのsequenceであり、かつHostHasSourceTextAvailable (func )がtrue なら、CodePointsToString (func .[[SourceText]] )を返す。func がbuilt-in function object なら、func のimplementation-defined String source code representationを返す。そのrepresentationはNativeFunction のsyntaxを持たなければなりません。加えて、func が[[InitialName]] internal slotを持ち、func .[[InitialName]] がStringである場合、NativeFunctionAccessor opt PropertyName にmatchするreturned Stringのportionはfunc .[[InitialName]] でなければなりません。func がObjectであり、IsCallable (func )がtrue なら、func のimplementation-defined String source code representationを返す。そのrepresentationはNativeFunction のsyntaxを持たなければなりません。TypeError 例外をThrowする。
NativeFunction :
function
NativeFunctionAccessor opt
PropertyName [~Yield, ~Await] opt
(
FormalParameters [~Yield, ~Await]
)
{
[
native
code
]
}
NativeFunctionAccessor :
get
set
20.2.3.6 Function.prototype [ %Symbol.hasInstance% ] ( value )
このmethodは呼び出されたとき、次のstepsを実行します:
thisValue をthis valueとする。? 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 、またはMethodDefinition (GeneratorMethod または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 environments がfunc に対して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を実行します:
bool をToBoolean (value )とする。NewTargetがundefined なら、bool を返す。 obj を ? OrdinaryCreateFromConstructor (NewTarget, "%Boolean.prototype%" , « [[BooleanData]] ») とする。obj .[[BooleanData]] をbool に設定する。obj を返す。
20.3.2 Properties of the Boolean Constructor
Boolean constructor は:
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を実行します:
bool を ? ThisBooleanValue (this value) とする。bool がtrue なら、"true" を返す。"false" を返す。
20.3.3.3 Boolean.prototype.valueOf ( )
このmethodは呼び出されたとき、次のstepsを実行します:
? 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:
arg がBooleanなら、arg を返す。arg がObjectであり、arg が[[BooleanData]] internal slotを持つなら、bool をarg .[[BooleanData]] とする。Assert : bool はBooleanである。bool を返す。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を実行します:
NewTargetがundefined でないなら、TypeError 例外をthrowする。 description がundefined なら、descString をundefined とする。そうでなければ、descString を ? ToString (description ) とする。 ... [[Description]] がdescString である新しいSymbolを返す。
20.4.2 Properties of the Symbol Constructor
Symbol constructor は:
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を実行します:
stringKey を ? ToString (key ) とする。agentRecord を周囲のエージェントの Agent Record とする。globalSymbolRegistry を agentRecord .[[GlobalSymbolRegistry]] とする。globalSymbolRegistry の各要素 element について、次を行う。element .[[Key]] が stringKey である場合、element .[[Symbol]] を返す。Assert : globalSymbolRegistry は現在、stringKey に対するエントリーを含んでいない。newSymbol を、[[Description]] が stringKey である新しい Symbol とする。GlobalSymbolRegistry Record { [[Key]] : stringKey , [[Symbol]] : newSymbol } を globalSymbolRegistry に追加する。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を実行します:
symbol がSymbolでないなら、TypeError 例外をthrowする。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 は:
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を実行します:
symbol を ? ThisSymbolValue (this value) とする。symbol .[[Description]] を返す。
20.4.3.3 Symbol.prototype.toString ( )
このmethodは呼び出されたとき、次のstepsを実行します:
symbol を ? ThisSymbolValue (this value) とする。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:
symbol .[[Description]] をdescription とする。description がundefined である場合、description を空のStringに設定する。Assert : description はStringである。"Symbol(" 、description 、および")" のstring-concatenation を返す。
20.4.3.4 Symbol.prototype.valueOf ( )
このmethodは呼び出されたとき、次のstepsを実行します:
? 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:
arg がSymbolなら、arg を返す。arg がObjectであり、arg が[[SymbolData]] internal slotを持つなら、symbol をarg .[[SymbolData]] とする。Assert : symbol はSymbolである。symbol を返す。TypeError 例外をThrowする。
20.4.3.5 Symbol.prototype [ %Symbol.toPrimitive% ] ( hint )
このmethodは、Symbol objectをprimitive valueへconvertするためにECMAScript language operatorsによって呼び出されます。
これは呼び出されたとき、次のstepsを実行します:
? ThisSymbolValue (this value)を返す。
Note
この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:
agentRecord を周囲のエージェントの Agent Record とする。globalSymbolRegistry を agentRecord .[[GlobalSymbolRegistry]] とする。globalSymbolRegistry の各要素 element について、次を行う。SameValue (element .[[Symbol]] , symbol ) が true である場合、element .[[Key]] を返す。Assert : globalSymbolRegistry は現在、symbol に対するエントリーを含んでいない。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を実行します:
NewTargetがundefined なら、newTarget をactive function object とする;そうでなければ、newTarget をNewTargetとする。 obj を ? OrdinaryCreateFromConstructor (newTarget , "%Error.prototype%" , « [[ErrorData]] ») とする。message がundefined でないなら、messageString を ? ToString (message ) とする。CreateNonEnumerableDataPropertyOrThrow (obj , "message" , messageString )を実行する。? InstallErrorCause (obj , options )を実行する。 obj を返す。
20.5.2 Properties of the Error Constructor
Error constructor は:
20.5.2.1 Error.isError ( arg )
このfunctionは呼び出されたとき、次のstepsを実行します:
arg がObjectでないなら、false を返す。arg が[[ErrorData]] internal slotを持たないなら、false を返す。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 は:
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を実行します:
obj をthis valueとする。obj がObjectでないなら、TypeError 例外をthrowする。name を ? Get (obj , "name" ) とする。name がundefined なら、name を"Error" に設定する;そうでなければ、name を ? ToString (name ) に設定する。message を ? Get (obj , "message" ) とする。message がundefined なら、message をempty Stringに設定する;そうでなければ、message を ? ToString (message ) に設定する。name がempty Stringなら、message を返す。message がempty Stringなら、name を返す。name 、code unit 0x003A (COLON)、code unit 0x0020 (SPACE)、およびmessage のstring-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を実行します:
NewTargetがundefined なら、newTarget をactive function object とする;そうでなければ、newTarget をNewTargetとする。 obj を ? OrdinaryCreateFromConstructor (newTarget , "%NativeError .prototype%" , « [[ErrorData]] ») とする。message がundefined でないなら、messageString を ? ToString (message ) とする。CreateNonEnumerableDataPropertyOrThrow (obj , "message" , messageString )を実行する。? InstallErrorCause (obj , options )を実行する。 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 は:
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.toString(20.1.3.6 )および Error.isError(20.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を実行します:
NewTargetがundefined なら、newTarget をactive function object とする;そうでなければ、newTarget をNewTargetとする。 obj を ? OrdinaryCreateFromConstructor (newTarget , "%AggregateError.prototype%" , « [[ErrorData]] ») とする。message がundefined でないなら、messageString を ? ToString (message ) とする。CreateNonEnumerableDataPropertyOrThrow (obj , "message" , messageString )を実行する。? InstallErrorCause (obj , options )を実行する。 errorsList を ? IteratorToList (? GetIterator (errors , sync )) とする。! DefinePropertyOrThrow (obj , "errors" , PropertyDescriptor { [[Configurable]] : true , [[Enumerable]] : false , [[Writable]] : true , [[Value]] : CreateArrayFromList (errorsList ) })を実行する。 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.toString(20.1.3.6 )および Error.isError(20.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 )
この関数は、呼び出されたときに次のステップを実行する:
NewTarget が undefined である場合、newTarget をアクティブな関数オブジェクトとする。そうでなければ、newTarget を NewTarget とする。 obj を ? OrdinaryCreateFromConstructor (newTarget , "%SuppressedError.prototype%" , « [[ErrorData]] ») とする。message が undefined でない場合、thenmessageString を ? ToString (message ) とする。CreateNonEnumerableDataPropertyOrThrow (obj , "message" , messageString ) を実行する。CreateNonEnumerableDataPropertyOrThrow (obj , "error" , error ) を実行する。CreateNonEnumerableDataPropertyOrThrow (obj , "suppressed" , suppressed ) を実行する。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:
options がObjectであり、? HasProperty (options , "cause" )がtrue なら、cause を ? Get (options , "cause" ) とする。CreateNonEnumerableDataPropertyOrThrow (obj , "cause" , cause )を実行する。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を実行します:
value が存在するなら、primitive を ? ToNumeric (value ) とする。primitive がBigIntなら、n を𝔽 (ℝ (primitive ))とする。そうでなければ、n をprimitive とする。 そうでなければ、n を+0 𝔽 とする。 NewTargetがundefined なら、n を返す。 obj を ? OrdinaryCreateFromConstructor (NewTarget, "%Number.prototype%" , « [[NumberData]] ») とする。obj .[[NumberData]] をn に設定する。obj を返す。
21.1.2 Properties of the Number Constructor
Number constructor は:
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を実行します:
number がNumberでないなら、false を返す。number がfinite でないなら、false を返す。true を返す。
21.1.2.3 Number.isInteger ( number )
このfunctionは呼び出されたとき、次のstepsを実行します:
number がintegral Number なら、true を返す。false を返す。
21.1.2.4 Number.isNaN ( number )
このfunctionは呼び出されたとき、次のstepsを実行します:
number がNumberでないなら、false を返す。number がNaN なら、true を返す。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を実行します:
number がintegral Number なら、abs (ℝ (number )) ≤ 253 - 1なら、true を返す。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 integers はsafe ではなく、Number valuesとして正確にrepresentableであること、または互いにdistinguishableであることすらguaranteeされません。例えば、9007199254740992と9007199254740993はいずれも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 integers はsafe ではなく、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を返します。fractionDigits がundefined なら、Numberを一意に指定するために必要なだけのsignificand digitsを含めます(ToString の場合と同様ですが、この場合Numberは常にexponential notationでoutputされる点が異なります)。
これは呼び出されたとき、次のstepsを実行します:
number を ? ThisNumberValue (this value) とする。fractionCount を ? ToIntegerOrInfinity (fractionDigits ) とする。Assert : fractionDigits がundefined なら、fractionCount は0である。number がfinite でないなら、Number::toString (number , 10)を返す。fractionCount < 0またはfractionCount > 100なら、RangeError 例外をthrowする。number をℝ (number )に設定する。sign をempty Stringとする。number < 0なら、sign を"-" に設定する。number を-number に設定する。number = 0なら、significand を、code unit 0x0030 (DIGIT ZERO)がfractionCount + 1回出現するString valueとする。exponent を0とする。そうでなければ、fractionDigits がundefined でないなら、exponent およびintSignificand を、10fractionCount ≤ intSignificand < 10fractionCount + 1 であり、intSignificand × 10exponent - fractionCount - number が可能な限りzeroに近くなるようなintegers とする。そのようなexponent およびintSignificand のsetsが2つある場合、intSignificand × 10exponent - fractionCount がより大きい方のexponent およびintSignificand を選ぶ。そうでなければ、exponent 、intSignificand 、およびff を、ff ≥ 0、10ff ≤ intSignificand < 10ff + 1 、𝔽 (intSignificand × 10exponent - ff )が𝔽 (number )であり、ff が可能な限りsmallであるようなintegers とする。intSignificand のdecimal representationはff + 1 digitsを持ち、intSignificand は10で割り切れず、intSignificand のleast significant digitはこれらのcriteriaによって必ずしも一意にdeterminedされないことに注意。fractionCount をff に設定する。 significand を、intSignificand のdecimal representationのdigitsからなるString value(order通り、leading zeroesなし)とする。 fractionCount ≠ 0なら、intPart をsignificand の最初のcode unitとする。fractionalPart をsignificand の他のfractionCount 個のcode unitsとする。significand をintPart 、"." 、およびfractionalPart のstring-concatenation に設定する。exponent = 0なら、exponentSign を"+" とする。exponentDigits を"0" とする。そうでなければ、exponent > 0なら、exponentSign を"+" とする。そうでなければ、Assert : exponent < 0である。exponentSign を"-" とする。exponent を-exponent に設定する。 exponentDigits を、exponent のdecimal representationのdigitsからなるString value(order通り、leading zeroesなし)とする。 significand をsignificand 、"e" 、exponentSign 、およびexponentDigits のstring-concatenation に設定する。sign とsignificand のstring-concatenation を返す。
Note
上記のrulesでrequiredされるよりもaccurateなconversionsを提供するimplementationsについては、step 10.b.i の次のalternative versionをguidelineとして使用することがrecommendedされます:
exponent 、intSignificand 、およびff を、ff ≥ 0、10ff ≤ intSignificand < 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を返します。fractionDigits がundefined なら、0がassumedされます。
これは呼び出されたとき、次のstepsを実行します:
number を ? ThisNumberValue (this value) とする。fractionCount を ? ToIntegerOrInfinity (fractionDigits ) とする。Assert : fractionDigits がundefined なら、fractionCount は0である。fractionCount がfinite でないなら、RangeError 例外をthrowする。fractionCount < 0またはfractionCount > 100なら、RangeError 例外をthrowする。number がfinite でないなら、Number::toString (number , 10)を返す。number をℝ (number )に設定する。sign をempty Stringとする。number < 0なら、sign を"-" に設定する。number を-number に設定する。number ≥ 1021 なら、digitString を ! ToString (𝔽 (number )) とする。そうでなければ、intValue を、intValue / 10fractionCount - number が可能な限りzeroに近くなるinteger とする。そのようなintValue が2つある場合、より大きいintValue を選ぶ。intValue = 0なら、digitString を"0" とする;そうでなければ、digitString をintValue のdecimal representationのdigitsからなるString value(order通り、leading zeroesなし)とする。fractionCount ≠ 0なら、digitCount をdigitString のlengthとする。digitCount ≤ fractionCount なら、zeroPad を、code unit 0x0030 (DIGIT ZERO)がfractionCount + 1 - digitCount 回出現するString valueとする。digitString をzeroPad とdigitString のstring-concatenation に設定する。digitCount をfractionCount + 1に設定する。intPart をdigitString の最初のdigitCount - fractionCount 個のcode unitsとする。fractionalPart をdigitString の他のfractionCount 個のcode unitsとする。digitString をintPart 、"." 、およびfractionalPart のstring-concatenation に設定する。 sign とdigitString のstring-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を返します。precision がundefined なら、代わりにToString を呼び出します。
これは呼び出されたとき、次のstepsを実行します:
number を ? ThisNumberValue (this value) とする。precision がundefined なら、! ToString (number )を返す。precisionCount を ? ToIntegerOrInfinity (precision ) とする。number がfinite でないなら、Number::toString (number , 10)を返す。precisionCount < 1またはprecisionCount > 100なら、RangeError 例外をthrowする。number をℝ (number )に設定する。sign をempty Stringとする。number < 0なら、sign をcode unit 0x002D (HYPHEN-MINUS)に設定する。number を-number に設定する。number = 0なら、significand を、code unit 0x0030 (DIGIT ZERO)がprecisionCount 回出現するString valueとする。exponent を0とする。そうでなければ、exponent およびintSignificand を、10precisionCount - 1 ≤ intSignificand < 10precisionCount であり、intSignificand × 10exponent - precisionCount + 1 - number が可能な限りzeroに近くなるようなintegers とする。そのようなexponent およびintSignificand のsetsが2つある場合、intSignificand × 10exponent - precisionCount + 1 がより大きい方のexponent およびintSignificand を選ぶ。significand を、intSignificand のdecimal representationのdigitsからなるString value(order通り、leading zeroesなし)とする。exponent < -6またはexponent ≥ precisionCount なら、Assert : exponent ≠ 0である。precisionCount ≠ 1なら、intPart をsignificand の最初のcode unitとする。fractionalPart をsignificand の他のprecisionCount - 1個のcode unitsとする。significand をintPart 、"." 、およびfractionalPart のstring-concatenation に設定する。exponent > 0なら、exponentSign をcode unit 0x002B (PLUS SIGN)とする。そうでなければ、Assert : exponent < 0である。exponentSign をcode unit 0x002D (HYPHEN-MINUS)とする。exponent を-exponent に設定する。 exponentDigits を、exponent のdecimal representationのdigitsからなるString value(order通り、leading zeroesなし)とする。sign 、significand 、code unit 0x0065 (LATIN SMALL LETTER E)、exponentSign 、およびexponentDigits のstring-concatenation を返す。 exponent = precisionCount - 1なら、sign とsignificand のstring-concatenation を返す。exponent ≥ 0なら、significand を、significand の最初のexponent + 1個のcode units、code unit 0x002E (FULL STOP)、およびsignificand の残りのprecisionCount - (exponent + 1)個のcode unitsのstring-concatenation に設定する。そうでなければ、significand を、code unit 0x0030 (DIGIT ZERO)、code unit 0x002E (FULL STOP)、code unit 0x0030 (DIGIT ZERO)の-(exponent + 1)回のoccurrences、およびString significand のstring-concatenation に設定する。 sign とsignificand のstring-concatenation を返す。
21.1.3.6 Number.prototype.toString ( [ radix ] )
Note
optional radix は、2 𝔽 から36 𝔽 までのinclusive interval 内にあるintegral Number valueであるべきです。radix がundefined なら、10 𝔽 がradix のvalueとして使用されます。
このmethodは呼び出されたとき、次のstepsを実行します:
x を ? ThisNumberValue (this value) とする。radix がundefined なら、radixMV を10とする。そうでなければ、radixMV を ? ToIntegerOrInfinity (radix ) とする。 radixMV が2から36までのinclusive interval 内にないなら、RangeError 例外をthrowする。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 ( )
? 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:
arg がNumberなら、arg を返す。arg がObjectであり、arg が[[NumberData]] internal slotを持つなら、number をarg .[[NumberData]] とする。Assert : number はNumberである。number を返す。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を実行します:
NewTargetがundefined でないなら、TypeError 例外をthrowする。 primitive を ? ToPrimitive (value , number ) とする。primitive がNumberなら、? NumberToBigInt (primitive )を返す。? 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:
number がintegral Number でないなら、RangeError 例外をthrowする。ℤ (ℝ (number ))を返す。
21.2.2 Properties of the BigInt Constructor
BigInt constructor は:
21.2.2.1 BigInt.asIntN ( bits , bigint )
このfunctionは呼び出されたとき、次のstepsを実行します:
bits を? ToIndex (bits )に設定する。bigint を? ToBigInt (bigint )に設定する。ℝ (bigint ) modulo 2bits をremainder とする。remainder ≥ 2bits - 1 である場合、ℤ (remainder - 2bits )を返す。ℤ (remainder )を返す。
21.2.2.2 BigInt.asUintN ( bits , bigint )
このfunctionは呼び出されたとき、次のstepsを実行します:
bits を ? ToIndex (bits ) に設定する。bigint を ? ToBigInt (bigint ) に設定する。ℤ (ℝ (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 は:
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であるべきです。radix がundefined なら、10 𝔽 がradix のvalueとして使用されます。
このmethodは呼び出されたとき、次のstepsを実行します:
x を ? ThisBigIntValue (this value) とする。radix がundefined なら、radixMV を10とする。そうでなければ、radixMV を ? ToIntegerOrInfinity (radix ) とする。 radixMV が2から36までのinclusive interval 内にないなら、RangeError 例外をthrowする。BigInt::toString (x , radixMV )を返す。
このmethodはgenericではありません;そのthis valueがBigIntまたはBigInt objectでない場合、TypeError 例外をthrowします。したがって、methodとして使用するために他の種類のobjectsへtransferすることはできません。
21.2.3.4 BigInt.prototype.valueOf ( )
? 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:
arg がBigIntなら、arg を返す。arg がObjectであり、arg が[[BigIntData]] internal slotを持つなら、Assert : arg .[[BigIntData]] はBigIntである。arg .[[BigIntData]] を返す。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は:
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 acos、acosh、asin、asinh、atan、atanh、atan2、cbrt、cos、cosh、exp、expm1、hypot、log、log1p、log2、log10、pow、random、sin、sinh、tan、および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であるfdlibm(http://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を実行します:
n を ? ToNumber (x ) とする。n がNaN なら、NaN を返す。n が-0 𝔽 なら、+0 𝔽 を返す。n が-∞ 𝔽 なら、+∞ 𝔽 を返す。n < -0 𝔽 なら、-n を返す。n を返す。
21.3.2.2 Math.acos ( x )
このfunctionはx のinverse cosineを返します。resultはradiansで表され、+0 𝔽 から𝔽 (π)までのinclusive interval 内にあります。
これは呼び出されたとき、次のstepsを実行します:
n を ? ToNumber (x ) とする。n がNaN 、n > 1 𝔽 、またはn < -1 𝔽 のいずれかなら、NaN を返す。n が1 𝔽 なら、+0 𝔽 を返す。ℝ (n )のinverse cosineを表すimplementation-approximated Number valueを返す。
21.3.2.3 Math.acosh ( x )
このfunctionはx のinverse hyperbolic cosineを返します。
これは呼び出されたとき、次のstepsを実行します:
n を ? ToNumber (x ) とする。n がNaN または+∞ 𝔽 のいずれかなら、n を返す。n が1 𝔽 なら、+0 𝔽 を返す。n < 1 𝔽 なら、NaN を返す。ℝ (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を実行します:
n を ? ToNumber (x ) とする。n がNaN 、+0 𝔽 、または-0 𝔽 のいずれかなら、n を返す。n > 1 𝔽 またはn < -1 𝔽 なら、NaN を返す。ℝ (n )のinverse sineを表すimplementation-approximated Number valueを返す。
21.3.2.5 Math.asinh ( x )
このfunctionはx のinverse hyperbolic sineを返します。
これは呼び出されたとき、次のstepsを実行します:
n を ? ToNumber (x ) とする。n がfinite でない、またはn が+0 𝔽 または-0 𝔽 のいずれかなら、n を返す。ℝ (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を実行します:
n を ? ToNumber (x ) とする。n がNaN 、+0 𝔽 、または-0 𝔽 のいずれかなら、n を返す。n が+∞ 𝔽 なら、π / 2を表すimplementation-approximated Number valueを返す。n が-∞ 𝔽 なら、-π / 2を表すimplementation-approximated Number valueを返す。ℝ (n )のinverse tangentを表すimplementation-approximated Number valueを返す。
21.3.2.7 Math.atanh ( x )
このfunctionはx のinverse hyperbolic tangentを返します。
これは呼び出されたとき、次のstepsを実行します:
n を ? ToNumber (x ) とする。n がNaN 、+0 𝔽 、または-0 𝔽 のいずれかなら、n を返す。n > 1 𝔽 またはn < -1 𝔽 なら、NaN を返す。n が1 𝔽 なら、+∞ 𝔽 を返す。n が-1 𝔽 なら、-∞ 𝔽 を返す。ℝ (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を実行します:
ny を ? ToNumber (y ) とする。nx を ? ToNumber (x ) とする。ny がNaN またはnx がNaN なら、NaN を返す。ny が+∞ 𝔽 なら、nx が+∞ 𝔽 なら、π / 4を表すimplementation-approximated Number valueを返す。nx が-∞ 𝔽 なら、3π / 4を表すimplementation-approximated Number valueを返す。π / 2を表すimplementation-approximated Number valueを返す。 ny が-∞ 𝔽 なら、nx が+∞ 𝔽 なら、-π / 4を表すimplementation-approximated Number valueを返す。nx が-∞ 𝔽 なら、-3π / 4を表すimplementation-approximated Number valueを返す。-π / 2を表すimplementation-approximated Number valueを返す。 ny が+0 𝔽 なら、nx > +0 𝔽 またはnx が+0 𝔽 なら、+0 𝔽 を返す。πを表すimplementation-approximated Number valueを返す。 ny が-0 𝔽 なら、nx > +0 𝔽 またはnx が+0 𝔽 なら、-0 𝔽 を返す。-πを表すimplementation-approximated Number valueを返す。 Assert : ny はfinite であり、+0 𝔽 でも-0 𝔽 でもない。ny > +0 𝔽 なら、nx が+∞ 𝔽 なら、+0 𝔽 を返す。nx が-∞ 𝔽 なら、πを表すimplementation-approximated Number valueを返す。nx が+0 𝔽 または-0 𝔽 のいずれかなら、π / 2を表すimplementation-approximated Number valueを返す。ny < -0 𝔽 なら、nx が+∞ 𝔽 なら、-0 𝔽 を返す。nx が-∞ 𝔽 なら、-πを表すimplementation-approximated Number valueを返す。nx が+0 𝔽 または-0 𝔽 のいずれかなら、-π / 2を表すimplementation-approximated Number valueを返す。Assert : nx はfinite であり、+0 𝔽 でも-0 𝔽 でもない。result をabs (ℝ (ny ) / ℝ (nx ))のinverse tangentとする。nx < -0 𝔽 なら、ny > +0 𝔽 なら、result をπ - result に設定する。そうでなければ、result を-π + result に設定する。 そうでなければ、ny < -0 𝔽 なら、result を-result に設定する。 result を表すimplementation-approximated Number valueを返す。
21.3.2.9 Math.cbrt ( x )
このfunctionはx のcube rootを返します。
これは呼び出されたとき、次のstepsを実行します:
n を ? ToNumber (x ) とする。n がfinite でない、またはn が+0 𝔽 または-0 𝔽 のいずれかなら、n を返す。ℝ (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を実行します:
n を ? ToNumber (x ) とする。n がfinite でない、またはn が+0 𝔽 または-0 𝔽 のいずれかなら、n を返す。n < -0 𝔽 かつn > -1 𝔽 なら、-0 𝔽 を返す。n がintegral Number なら、n を返す。n 以上であるsmallest(-∞にclosest)integral Number valueを返す。
Note
Math.ceil(x)のvalueは-Math.floor(-x)のvalueと同じです。
21.3.2.11 Math.clz32 ( x )
このfunctionは呼び出されたとき、次のstepsを実行します:
n を ? ToUint32 (x ) とする。p をn のunsigned 32-bit binary representationにおけるleading zero bitsの数とする。𝔽 (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を実行します:
n を ? ToNumber (x ) とする。n がfinite でないなら、NaN を返す。n が+0 𝔽 または-0 𝔽 のいずれかなら、1 𝔽 を返す。ℝ (n )のcosineを表すimplementation-approximated Number valueを返す。
21.3.2.13 Math.cosh ( x )
このfunctionはx のhyperbolic cosineを返します。
これは呼び出されたとき、次のstepsを実行します:
n を ? ToNumber (x ) とする。n がNaN なら、NaN を返す。n が+∞ 𝔽 または-∞ 𝔽 のいずれかなら、+∞ 𝔽 を返す。n が+0 𝔽 または-0 𝔽 のいずれかなら、1 𝔽 を返す。ℝ (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(e をx 乗したもの。ここでe はnatural logarithmsのbase)を返します。
これは呼び出されたとき、次のstepsを実行します:
n を ? ToNumber (x ) とする。n がNaN または+∞ 𝔽 のいずれかなら、n を返す。n が+0 𝔽 または-0 𝔽 のいずれかなら、1 𝔽 を返す。n が-∞ 𝔽 なら、+0 𝔽 を返す。ℝ (n )のexponential functionを表すimplementation-approximated Number valueを返す。
21.3.2.15 Math.expm1 ( x )
このfunctionはx のexponential function(e をx 乗したもの。ここでe はnatural logarithmsのbase)から1をsubtractしたresultを返します。resultは、x のvalueが0に近い場合でもaccurateになるようにcomputedされます。
これは呼び出されたとき、次のstepsを実行します:
n を ? ToNumber (x ) とする。n がNaN 、+0 𝔽 、-0 𝔽 、または+∞ 𝔽 のいずれかなら、n を返す。n が-∞ 𝔽 なら、-1 𝔽 を返す。exp をℝ (n )のexponential functionとする。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を実行します:
n を ? ToNumber (x ) とする。n がfinite でない、またはn が+0 𝔽 または-0 𝔽 のいずれかなら、n を返す。n < 1 𝔽 かつn > +0 𝔽 なら、+0 𝔽 を返す。n がintegral Number なら、n を返す。n 以下であるgreatest(+∞にclosest)integral Number valueを返す。
Note
Math.floor(x)のvalueは-Math.ceil(-x)のvalueと同じです。
21.3.2.17 Math.fround ( x )
このfunctionは呼び出されたとき、次のstepsを実行します:
n を ? ToNumber (x ) とする。n がNaN なら、NaN を返す。n が+0 𝔽 、-0 𝔽 、+∞ 𝔽 、または-∞ 𝔽 のいずれかなら、n を返す。n32 を、roundTiesToEven modeを使用してn をIEEE 754-2019 binary32 formatへconvertしたresultとする。n64 を、n32 をIEEE 754-2019 binary64 formatへconvertしたresultとする。n64 に対応するECMAScript Number valueを返す。
21.3.2.18 Math.f16round ( x )
このfunctionは呼び出されたとき、次のstepsを実行します:
n を ? ToNumber (x ) とする。n がNaN なら、NaN を返す。n が+0 𝔽 、-0 𝔽 、+∞ 𝔽 、または-∞ 𝔽 のいずれかなら、n を返す。n16 を、roundTiesToEven modeを使用してn をIEEE 754-2019 binary16 formatへconvertしたresultとする。n64 を、n16 をIEEE 754-2019 binary64 formatへconvertしたresultとする。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を実行します:
coerced を新しい空のList とする。args の各要素arg について、以下を行うn を ? ToNumber (arg ) とする。n をcoerced へappendする。coerced の各要素number について、以下を行うnumber が+∞ 𝔽 または-∞ 𝔽 のいずれかなら、+∞ 𝔽 を返す。onlyZero をtrue とする。coerced の各要素number について、以下を行うnumber がNaN なら、NaN を返す。number が+0 𝔽 でも-0 𝔽 でもないなら、onlyZero をfalse に設定する。onlyZero がtrue なら、+0 𝔽 を返す。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を実行します:
a をℝ (? ToUint32 (x ))とする。b をℝ (? ToUint32 (y ))とする。product を(a × b ) modulo 232 とする。product ≥ 231 なら、𝔽 (product - 232 )を返す。𝔽 (product )を返す。
21.3.2.21 Math.log ( x )
このfunctionはx のnatural logarithmを返します。
これは呼び出されたとき、次のstepsを実行します:
n を ? ToNumber (x ) とする。n がNaN または+∞ 𝔽 のいずれかなら、n を返す。n が1 𝔽 なら、+0 𝔽 を返す。n が+0 𝔽 または-0 𝔽 のいずれかなら、-∞ 𝔽 を返す。n < -0 𝔽 なら、NaN を返す。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を実行します:
n を ? ToNumber (x ) とする。n がNaN 、+0 𝔽 、-0 𝔽 、または+∞ 𝔽 のいずれかなら、n を返す。n が-1 𝔽 なら、-∞ 𝔽 を返す。n < -1 𝔽 なら、NaN を返す。ln (1 + ℝ (n ))を表すimplementation-approximated Number valueを返す。
21.3.2.23 Math.log10 ( x )
このfunctionはx のbase 10 logarithmを返します。
これは呼び出されたとき、次のstepsを実行します:
n を ? ToNumber (x ) とする。n がNaN または+∞ 𝔽 のいずれかなら、n を返す。n が1 𝔽 なら、+0 𝔽 を返す。n が+0 𝔽 または-0 𝔽 のいずれかなら、-∞ 𝔽 を返す。n < -0 𝔽 なら、NaN を返す。log10 (ℝ (n ))を表すimplementation-approximated Number valueを返す。
21.3.2.24 Math.log2 ( x )
このfunctionはx のbase 2 logarithmを返します。
これは呼び出されたとき、次のstepsを実行します:
n を ? ToNumber (x ) とする。n がNaN または+∞ 𝔽 のいずれかなら、n を返す。n が1 𝔽 なら、+0 𝔽 を返す。n が+0 𝔽 または-0 𝔽 のいずれかなら、-∞ 𝔽 を返す。n < -0 𝔽 なら、NaN を返す。log2 (ℝ (n ))を表すimplementation-approximated Number valueを返す。
21.3.2.25 Math.max ( ...args )
zero以上のargumentsが与えられると、このfunctionはargumentsのそれぞれにToNumber をcallし、得られたvaluesのlargestを返します。
これは呼び出されたとき、次のstepsを実行します:
coerced を新しい空のList とする。args の各要素arg について、以下を行うn を ? ToNumber (arg ) とする。n をcoerced へappendする。highest を-∞ 𝔽 とする。coerced の各要素number について、以下を行うnumber がNaN なら、NaN を返す。number が+0 𝔽 であり、highest が-0 𝔽 なら、highest を+0 𝔽 に設定する。number > highest なら、highest をnumber に設定する。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を実行します:
coerced を新しい空のList とする。args の各要素arg について、以下を行うn を ? ToNumber (arg ) とする。n をcoerced へappendする。lowest を+∞ 𝔽 とする。coerced の各要素number について、以下を行うnumber がNaN なら、NaN を返す。number が-0 𝔽 であり、lowest が+0 𝔽 なら、lowest を-0 𝔽 に設定する。number < lowest なら、lowest をnumber に設定する。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を実行します:
base を ? ToNumber (base ) に設定する。exponent を ? ToNumber (exponent ) に設定する。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 Numbers がx にequally closeである場合、resultは+∞にcloserなNumber valueです。x がすでにintegralである場合、resultはx です。
これは呼び出されたとき、次のstepsを実行します:
n を ? ToNumber (x ) とする。n がfinite でない、またはn がintegral Number なら、n を返す。n < 0.5 𝔽 かつn > +0 𝔽 なら、+0 𝔽 を返す。n < -0 𝔽 かつn ≥ -0.5 𝔽 なら、-0 𝔽 を返す。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を実行します:
n を ? ToNumber (x ) とする。n がNaN 、+0 𝔽 、または-0 𝔽 のいずれかなら、n を返す。n < -0 𝔽 なら、-1 𝔽 を返す。1 𝔽 を返す。
21.3.2.31 Math.sin ( x )
このfunctionはx のsineを返します。argumentはradiansで表されます。
これは呼び出されたとき、次のstepsを実行します:
n を ? ToNumber (x ) とする。n がNaN 、+0 𝔽 、または-0 𝔽 のいずれかなら、n を返す。n が+∞ 𝔽 または-∞ 𝔽 のいずれかなら、NaN を返す。ℝ (n )のsineを表すimplementation-approximated Number valueを返す。
21.3.2.32 Math.sinh ( x )
このfunctionはx のhyperbolic sineを返します。
これは呼び出されたとき、次のstepsを実行します:
n を ? ToNumber (x ) とする。n がfinite でない、またはn が+0 𝔽 または-0 𝔽 のいずれかなら、n を返す。ℝ (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を実行します:
n を ? ToNumber (x ) とする。n がNaN 、+0 𝔽 、-0 𝔽 、または+∞ 𝔽 のいずれかなら、n を返す。n < -0 𝔽 なら、NaN を返す。𝔽 (ℝ (n )のsquare root)を返す。
21.3.2.34 Math.sumPrecise ( items )
Numbersのiterable が与えられると、このfunctionはiterable 内の各valueをsumし、それらのsumを返します。何らかのvalueがNumberでない場合、TypeError 例外をthrowします。
これは呼び出されたとき、次のstepsを実行します:
? RequireObjectCoercible (items )を実行する。 iteratorRecord を ? GetIterator (items , sync ) とする。state をminus-zero とする。sum を0とする。count を0とする。next をnot-started とする。next がdone でない間、繰り返すnext を ? IteratorStepValue (iteratorRecord ) に設定する。next がdone でないなら、count ≥ 253 - 1なら、NOTE : このstepは実際には到達しないことが期待されており、implementationsがこの仕様に違反することなくinputsが“reasonably sized”であることに依存できるようにするためだけに含まれる。error をThrowCompletion (a newly created RangeError object)とする。? IteratorClose (iteratorRecord , error )を返す。 next がNumberでないなら、error をThrowCompletion (a newly created TypeError object)とする。? IteratorClose (iteratorRecord , error )を返す。 n をnext とする。state がnot-a-number でないなら、n がNaN なら、state をnot-a-number に設定する。そうでなく、n が+∞ 𝔽 なら、state がminus-infinity なら、state をnot-a-number に設定する。そうでなければ、state をplus-infinity に設定する。 そうでなく、n が-∞ 𝔽 なら、state がplus-infinity なら、state をnot-a-number に設定する。そうでなければ、state をminus-infinity に設定する。 そうでなく、n が-0 𝔽 でなく、かつstate がminus-zero またはfinite のいずれかなら、state をfinite に設定する。sum をsum + ℝ (n )に設定する。 count をcount + 1に設定する。state がnot-a-number なら、NaN を返す。state がplus-infinity なら、+∞ 𝔽 を返す。state がminus-infinity なら、-∞ 𝔽 を返す。state がminus-zero なら、-0 𝔽 を返す。𝔽 (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を実行します:
n を ? ToNumber (x ) とする。n がNaN 、+0 𝔽 、または-0 𝔽 のいずれかなら、n を返す。n が+∞ 𝔽 または-∞ 𝔽 のいずれかなら、NaN を返す。ℝ (n )のtangentを表すimplementation-approximated Number valueを返す。
21.3.2.36 Math.tanh ( x )
このfunctionはx のhyperbolic tangentを返します。
これは呼び出されたとき、次のstepsを実行します:
n を ? ToNumber (x ) とする。n がNaN 、+0 𝔽 、または-0 𝔽 のいずれかなら、n を返す。n が+∞ 𝔽 なら、1 𝔽 を返す。n が-∞ 𝔽 なら、-1 𝔽 を返す。ℝ (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を実行します:
n を ? ToNumber (x ) とする。n がfinite でない、またはn が+0 𝔽 または-0 𝔽 のいずれかなら、n を返す。n < 1 𝔽 かつn > +0 𝔽 なら、+0 𝔽 を返す。n < -0 𝔽 かつn > -1 𝔽 なら、-0 𝔽 を返す。+0 𝔽 の方向にn にnearestなintegral Number を返す。
21.4 Date Objects
21.4.1 Overview of Date Objects and Definitions of Abstract Operations
以下のabstract operations はtime values (21.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 𝔽
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:
𝔽 (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:
𝔽 (ℝ (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:
ry をℝ (y )とする。(ry modulo 400) = 0なら、366 𝔽 を返す。 (ry modulo 100) = 0なら、365 𝔽 を返す。 (ry modulo 4) = 0なら、366 𝔽 を返す。 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:
ry をℝ (y )とする。NOTE : 以下のstepsでは、numberYears1 、numberYears4 、numberYears100 、およびnumberYears400 は、それぞれepoch とyear y のstartとの間に現れる、1、4、100、および400でdivisibleなyearsの数を表す。y がepoch より前なら、この数はnegativeである。numberYears1 を(ry - 1970)とする。numberYears4 をfloor ((ry - 1969) / 4)とする。numberYears100 をfloor ((ry - 1901) / 100)とする。numberYears400 をfloor ((ry - 1601) / 400)とする。𝔽 (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:
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:
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:
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:
DaysInYear (YearFromTime (tv ))が366 𝔽 なら、1 𝔽 を返す。+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:
inLeapYear をInLeapYear (tv )とする。dayWithinYear をDayWithinYear (tv )とする。dayWithinYear < 31 𝔽 なら、+0 𝔽 を返す。dayWithinYear < 59 𝔽 + inLeapYear なら、1 𝔽 を返す。dayWithinYear < 90 𝔽 + inLeapYear なら、2 𝔽 を返す。dayWithinYear < 120 𝔽 + inLeapYear なら、3 𝔽 を返す。dayWithinYear < 151 𝔽 + inLeapYear なら、4 𝔽 を返す。dayWithinYear < 181 𝔽 + inLeapYear なら、5 𝔽 を返す。dayWithinYear < 212 𝔽 + inLeapYear なら、6 𝔽 を返す。dayWithinYear < 243 𝔽 + inLeapYear なら、7 𝔽 を返す。dayWithinYear < 273 𝔽 + inLeapYear なら、8 𝔽 を返す。dayWithinYear < 304 𝔽 + inLeapYear なら、9 𝔽 を返す。dayWithinYear < 334 𝔽 + inLeapYear なら、10 𝔽 を返す。Assert : dayWithinYear < 365 𝔽 + inLeapYear である。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:
inLeapYear をInLeapYear (tv )とする。dayWithinYear をDayWithinYear (tv )とする。month をMonthFromTime (tv )とする。month が+0 𝔽 なら、dayWithinYear + 1 𝔽 を返す。month が1 𝔽 なら、dayWithinYear - 30 𝔽 を返す。month が2 𝔽 なら、dayWithinYear - 58 𝔽 - inLeapYear を返す。month が3 𝔽 なら、dayWithinYear - 89 𝔽 - inLeapYear を返す。month が4 𝔽 なら、dayWithinYear - 119 𝔽 - inLeapYear を返す。month が5 𝔽 なら、dayWithinYear - 150 𝔽 - inLeapYear を返す。month が6 𝔽 なら、dayWithinYear - 180 𝔽 - inLeapYear を返す。month が7 𝔽 なら、dayWithinYear - 211 𝔽 - inLeapYear を返す。month が8 𝔽 なら、dayWithinYear - 242 𝔽 - inLeapYear を返す。month が9 𝔽 なら、dayWithinYear - 272 𝔽 - inLeapYear を返す。month が10 𝔽 なら、dayWithinYear - 303 𝔽 - inLeapYear を返す。Assert : month は11 𝔽 である。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:
𝔽 (ℝ (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:
𝔽 (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:
𝔽 (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:
𝔽 (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:
𝔽 (ℝ (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:
date をMakeDay (𝔽 (year ), 𝔽 (month - 1), 𝔽 (day ))とする。time をMakeTime (𝔽 (hour ), 𝔽 (minute ), 𝔽 (second ), 𝔽 (millisecond ))とする。ms をMakeDate (date , time )とする。Assert : ms はintegral Number である。ℤ (ℝ (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 、またはIsTimeZoneOffsetString がtrue を返す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を実行します:
Assert : timeZoneIdentifier は"UTC" である。epochNanoseconds をGetUTCEpochNanoseconds (year , month , day , hour , minute , second , millisecond , microsecond , nanosecond )とする。« 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を実行します:
Assert : timeZoneIdentifier は"UTC" である。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
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を実行します:
implementationがtime zonesに関するlocal political rulesをまったく含まないなら、« the Time Zone Identifier Record { [[Identifier]] : "UTC" , [[PrimaryIdentifier]] : "UTC" } »を返す。 identifiers を、lexicographic code unit order に従ってsortedされた、unique available named time zone identifiers のList とする。result を新しい空のList とする。identifiers の各要素identifier について、以下を行うprimary をidentifier とする。identifier がこのimplementation内のnon-primary time zone identifier であり、かつidentifier が"UTC" でないなら、primary をidentifier にassociatedされたprimary time zone identifier に設定する。NOTE : implementationはprimary time zone identifier をobtainするためにidentifier をiterativelyにresolveする必要がある場合がある。record をTime Zone Identifier Record { [[Identifier]] : identifier , [[PrimaryIdentifier]] : primary }とする。record をresult へappendする。Assert : result は、record .[[Identifier]] が"UTC" であり、record .[[PrimaryIdentifier]] が"UTC" であるようなTime Zone Identifier Record record を含む。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を返します。これは、IsTimeZoneOffsetString がtrue を返すUTC offsetを表すString、またはprimary time zone identifier のいずれかです。
It performs the following steps when called:
implementationがUTC time zoneのみをsupportするなら、"UTC" を返す。 systemTimeZoneString を、host environmentのcurrent time zoneを表すString、すなわちprimary time zone identifier またはoffset time zone identifierとする。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:
systemTimeZoneIdentifier をSystemTimeZoneIdentifier ()とする。IsTimeZoneOffsetString (systemTimeZoneIdentifier )がtrue なら、offsetNs をParseTimeZoneOffsetString (systemTimeZoneIdentifier )とする。そうでなければ、offsetNs をGetNamedTimeZoneOffsetNanoseconds (systemTimeZoneIdentifier , ℤ (ℝ (tv ) × 106 ))とする。 offsetMs をtruncate (offsetNs / 106 )とする。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 tv UTC は、repeated timesが存在するnegative time zone transition(例えばdaylight saving timeが終了するとき、またはtime zone adjustmentがdecreasedされるとき)に、同じlocal time tlocal へconvertedされます。
LocalTime(UTC (tv local )) は、必ずしも常にtv local にequalであるとは限りません。対応して、UTC (LocalTime(tv UTC )) も、必ずしも常にtv UTC に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:
t がfinite でないなら、NaN を返す。systemTimeZoneIdentifier をSystemTimeZoneIdentifier ()とする。IsTimeZoneOffsetString (systemTimeZoneIdentifier )がtrue なら、offsetNs をParseTimeZoneOffsetString (systemTimeZoneIdentifier )とする。そうでなければ、possibleInstants をGetNamedTimeZoneEpochNanoseconds (systemTimeZoneIdentifier , ℝ (YearFromTime (t )), ℝ (MonthFromTime (t )) + 1, ℝ (DateFromTime (t )), ℝ (HourFromTime (t )), ℝ (MinFromTime (t )), ℝ (SecFromTime (t )), ℝ (msFromTime (t )), 0, 0)とする。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する。possibleInstants がemptyでないなら、disambiguatedInstant をpossibleInstants [0]とする。そうでなければ、NOTE : t はpositive time zone transitionでskippedされたlocal timeを表す(例えばdaylight saving timeの開始、またはUTC offsetをincreaseするtime zone rule changeによる)。possibleInstantsBefore をGetNamedTimeZoneEpochNanoseconds (systemTimeZoneIdentifier , ℝ (YearFromTime (tBefore )), ℝ (MonthFromTime (tBefore )) + 1, ℝ (DateFromTime (tBefore )), ℝ (HourFromTime (tBefore )), ℝ (MinFromTime (tBefore )), ℝ (SecFromTime (tBefore )), ℝ (msFromTime (tBefore )), 0, 0)とする。ここで、tBefore はpossibleInstantsBefore がemptyでないようなt 未満のlargest integral Number である(すなわち、tBefore はtransition前のlast local timeを表す)。disambiguatedInstant をpossibleInstantsBefore のlast elementとする。 offsetNs をGetNamedTimeZoneOffsetNanoseconds (systemTimeZoneIdentifier , disambiguatedInstant )とする。 offsetMs をtruncate (offsetNs / 106 )とする。t - 𝔽 (offsetMs )を返す。
Input t はnominallyにはtime value ですが、任意のNumber valueであり得ます。
algorithmはt をtime 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 (t UTC )) は、必ずしも常にt UTC にequalであるとは限りません。対応して、LocalTime (UTC(t local )) も、必ずしも常にt local に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:
hour がfinite でない、min がfinite でない、sec がfinite でない、またはms がfinite でないなら、NaN を返す。h を𝔽 (! ToIntegerOrInfinity (hour ))とする。m を𝔽 (! ToIntegerOrInfinity (min ))とする。s を𝔽 (! ToIntegerOrInfinity (sec ))とする。milli を𝔽 (! ToIntegerOrInfinity (ms ))とする。((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:
year がfinite でない、month がfinite でない、またはdate がfinite でないなら、NaN を返す。y を𝔽 (! ToIntegerOrInfinity (year ))とする。m を𝔽 (! ToIntegerOrInfinity (month ))とする。dt を𝔽 (! ToIntegerOrInfinity (date ))とする。ym をy + 𝔽 (floor (ℝ (m ) / 12))とする。ym がfinite でないなら、NaN を返す。mn を𝔽 (ℝ (m ) modulo 12)とする。YearFromTime (tv )がym であり、MonthFromTime (tv )がmn であり、DateFromTime (tv )が1 𝔽 であるようなfinite time value tv を見つける;ただし、これが可能でない場合(あるargumentがout of rangeであるため)、NaN を返す。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:
day がfinite でない、またはtime がfinite でないなら、NaN を返す。tv をday × msPerDay + time とする。tv がfinite でないなら、NaN を返す。tv を返す。
21.4.1.30 MakeFullYear ( year )
The abstract operation MakeFullYear takes argument year (a Number) and returns an integral Number or NaN . year のinteger 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:
year がNaN 、+∞ 𝔽 、または-∞ 𝔽 のいずれかなら、NaN を返す。truncated を ! ToIntegerOrInfinity (year ) とする。truncated が0から99までのinclusive interval 内にあるなら、1900 𝔽 + 𝔽 (truncated )を返す。𝔽 (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:
time がfinite でないなら、NaN を返す。abs (ℝ (time )) > 8.64 × 1015 なら、NaN を返す。𝔽 (! 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
TemporalDecimalFraction opt
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は、offsetString がUTCOffset によって与えられるgrammarにconformするかどうかを示します。 It performs the following steps when called:
parseResult をParseText (offsetString , UTCOffset )とする。parseResult がerrorsのList なら、false を返す。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:
parseResult をParseText (offsetString , UTCOffset )とする。Assert : parseResult はerrorsのList ではない。Assert : parseResult はASCIISign Parse Node を含む。parsedSign をparseResult 内に含まれるASCIISign Parse Node にmatchedするsource textとする。parsedSign がsingle code point U+002D (HYPHEN-MINUS)なら、sign を-1とする。そうでなければ、sign を1とする。 NOTE : 以下のStringToNumber のapplicationsはprecisionを失わない。なぜなら、parsed valuesのそれぞれは十分に短いdecimal digitsのstringであることがguaranteedされるからである。Assert : parseResult はHour Parse Node を含む。parsedHours をparseResult 内に含まれるHour Parse Node にmatchedするsource textとする。hours をℝ (StringToNumber (CodePointsToString (parsedHours )))とする。parseResult がMinuteSecond Parse Node を含まないなら、minutes を0とする。そうでなければ、parsedMinutes をparseResult 内に含まれるfirst MinuteSecond Parse Node にmatchedするsource textとする。minutes をℝ (StringToNumber (CodePointsToString (parsedMinutes )))とする。 parseResult がtwo MinuteSecond Parse Nodes を含まないなら、seconds を0とする。そうでなければ、parsedSeconds をparseResult 内に含まれるsecond MinuteSecond Parse Node にmatchedするsource textとする。seconds をℝ (StringToNumber (CodePointsToString (parsedSeconds )))とする。 parseResult がTemporalDecimalFraction Parse Node を含まないなら、nanoseconds を0とする。そうでなければ、parsedFraction をparseResult 内に含まれるTemporalDecimalFraction Parse Node にmatchedするsource textとする。fraction をCodePointsToString (parsedFraction )と"000000000" のstring-concatenation とする。nanosecondsString をfraction の1から10までのsubstring とする。nanoseconds をℝ (StringToNumber (nanosecondsString ))とする。 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を実行します:
NewTargetがundefined なら、now をcurrent timeをidentifyするtime value (UTC)とする。ToDateString (now )を返す。 numberOfArgs をvalues 内のelementsの数とする。numberOfArgs = 0なら、dv をcurrent timeをidentifyするtime value (UTC)とする。そうでなく、numberOfArgs = 1なら、value をvalues [0]とする。value がObjectであり、value が[[DateValue]] internal slotを持つなら、tv をvalue .[[DateValue]] とする。そうでなければ、v を ? ToPrimitive (value ) とする。v がStringなら、Assert : v はStringであるため、next stepはabrupt completion を返すことはない。tv を、parse method(21.4.3.2 )の場合とexactly same mannerで、v をdateとしてparsingしたresultとする。そうでなければ、tv を ? ToNumber (v ) とする。 dv をTimeClip (tv )とする。 そうでなければ、Assert : numberOfArgs ≥ 2である。y を ? ToNumber (values [0]) とする。m を ? ToNumber (values [1]) とする。numberOfArgs > 2なら、dt を ? ToNumber (values [2]) とする;そうでなければ、dt を1 𝔽 とする。numberOfArgs > 3なら、h を ? ToNumber (values [3]) とする;そうでなければ、h を+0 𝔽 とする。numberOfArgs > 4なら、min を ? ToNumber (values [4]) とする;そうでなければ、min を+0 𝔽 とする。numberOfArgs > 5なら、s を ? ToNumber (values [5]) とする;そうでなければ、s を+0 𝔽 とする。numberOfArgs > 6なら、milli を ? ToNumber (values [6]) とする;そうでなければ、milli を+0 𝔽 とする。yr をMakeFullYear (y )とする。finalDate をMakeDate (MakeDay (yr , m , dt ), MakeTime (h , min , s , milli ))とする。dv をTimeClip (UTC (finalDate ))とする。 obj を ? OrdinaryCreateFromConstructor (NewTarget, "%Date.prototype%" , « [[DateValue]] ») とする。obj .[[DateValue]] をdv に設定する。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します。ToString がabrupt 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" が使用されます。HH、mm、または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を実行します:
y を ? ToNumber (year ) とする。month がpresentなら、m を ? ToNumber (month ) とする;そうでなければ、m を+0 𝔽 とする。date がpresentなら、dt を ? ToNumber (date ) とする;そうでなければ、dt を1 𝔽 とする。hours がpresentなら、h を ? ToNumber (hours ) とする;そうでなければ、h を+0 𝔽 とする。minutes がpresentなら、min を ? ToNumber (minutes ) とする;そうでなければ、min を+0 𝔽 とする。seconds がpresentなら、s を ? ToNumber (seconds ) とする;そうでなければ、s を+0 𝔽 とする。ms がpresentなら、milli を ? ToNumber (ms ) とする;そうでなければ、milli を+0 𝔽 とする。yr をMakeFullYear (y )とする。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 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を実行します:
dateObj をthis valueとする。? RequireInternalSlot (dateObj , [[DateValue]] )を実行する。 tv をdateObj .[[DateValue]] とする。tv がNaN なら、NaN を返す。DateFromTime (LocalTime (tv ))を返す。
21.4.4.3 Date.prototype.getDay ( )
このmethodは呼び出されたとき、次のstepsを実行します:
dateObj をthis valueとする。? RequireInternalSlot (dateObj , [[DateValue]] )を実行する。 tv をdateObj .[[DateValue]] とする。tv がNaN なら、NaN を返す。WeekDay (LocalTime (tv ))を返す。
21.4.4.4 Date.prototype.getFullYear ( )
このmethodは呼び出されたとき、次のstepsを実行します:
dateObj をthis valueとする。? RequireInternalSlot (dateObj , [[DateValue]] )を実行する。 tv をdateObj .[[DateValue]] とする。tv がNaN なら、NaN を返す。YearFromTime (LocalTime (tv ))を返す。
21.4.4.5 Date.prototype.getHours ( )
このmethodは呼び出されたとき、次のstepsを実行します:
dateObj をthis valueとする。? RequireInternalSlot (dateObj , [[DateValue]] )を実行する。 tv をdateObj .[[DateValue]] とする。tv がNaN なら、NaN を返す。HourFromTime (LocalTime (tv ))を返す。
21.4.4.6 Date.prototype.getMilliseconds ( )
このmethodは呼び出されたとき、次のstepsを実行します:
dateObj をthis valueとする。? RequireInternalSlot (dateObj , [[DateValue]] )を実行する。 tv をdateObj .[[DateValue]] とする。tv がNaN なら、NaN を返す。msFromTime (LocalTime (tv ))を返す。
21.4.4.7 Date.prototype.getMinutes ( )
このmethodは呼び出されたとき、次のstepsを実行します:
dateObj をthis valueとする。? RequireInternalSlot (dateObj , [[DateValue]] )を実行する。 tv をdateObj .[[DateValue]] とする。tv がNaN なら、NaN を返す。MinFromTime (LocalTime (tv ))を返す。
21.4.4.8 Date.prototype.getMonth ( )
このmethodは呼び出されたとき、次のstepsを実行します:
dateObj をthis valueとする。? RequireInternalSlot (dateObj , [[DateValue]] )を実行する。 tv をdateObj .[[DateValue]] とする。tv がNaN なら、NaN を返す。MonthFromTime (LocalTime (tv ))を返す。
21.4.4.9 Date.prototype.getSeconds ( )
このmethodは呼び出されたとき、次のstepsを実行します:
dateObj をthis valueとする。? RequireInternalSlot (dateObj , [[DateValue]] )を実行する。 tv をdateObj .[[DateValue]] とする。tv がNaN なら、NaN を返す。SecFromTime (LocalTime (tv ))を返す。
21.4.4.10 Date.prototype.getTime ( )
このmethodは呼び出されたとき、次のstepsを実行します:
dateObj をthis valueとする。? RequireInternalSlot (dateObj , [[DateValue]] )を実行する。 dateObj .[[DateValue]] を返す。
21.4.4.11 Date.prototype.getTimezoneOffset ( )
このmethodは呼び出されたとき、次のstepsを実行します:
dateObj をthis valueとする。? RequireInternalSlot (dateObj , [[DateValue]] )を実行する。 tv をdateObj .[[DateValue]] とする。tv がNaN なら、NaN を返す。(tv - LocalTime (tv )) / msPerMinute を返す。
21.4.4.12 Date.prototype.getUTCDate ( )
このmethodは呼び出されたとき、次のstepsを実行します:
dateObj をthis valueとする。? RequireInternalSlot (dateObj , [[DateValue]] )を実行する。 tv をdateObj .[[DateValue]] とする。tv がNaN なら、NaN を返す。DateFromTime (tv )を返す。
21.4.4.13 Date.prototype.getUTCDay ( )
このmethodは呼び出されたとき、次のstepsを実行します:
dateObj をthis valueとする。? RequireInternalSlot (dateObj , [[DateValue]] )を実行する。 tv をdateObj .[[DateValue]] とする。tv がNaN なら、NaN を返す。WeekDay (tv )を返す。
21.4.4.14 Date.prototype.getUTCFullYear ( )
このmethodは呼び出されたとき、次のstepsを実行します:
dateObj をthis valueとする。? RequireInternalSlot (dateObj , [[DateValue]] )を実行する。 tv をdateObj .[[DateValue]] とする。tv がNaN なら、NaN を返す。YearFromTime (tv )を返す。
21.4.4.15 Date.prototype.getUTCHours ( )
このmethodは呼び出されたとき、次のstepsを実行します:
dateObj をthis valueとする。? RequireInternalSlot (dateObj , [[DateValue]] )を実行する。 tv をdateObj .[[DateValue]] とする。tv がNaN なら、NaN を返す。HourFromTime (tv )を返す。
21.4.4.16 Date.prototype.getUTCMilliseconds ( )
このmethodは呼び出されたとき、次のstepsを実行します:
dateObj をthis valueとする。? RequireInternalSlot (dateObj , [[DateValue]] )を実行する。 tv をdateObj .[[DateValue]] とする。tv がNaN なら、NaN を返す。msFromTime (tv )を返す。
21.4.4.17 Date.prototype.getUTCMinutes ( )
このmethodは呼び出されたとき、次のstepsを実行します:
dateObj をthis valueとする。? RequireInternalSlot (dateObj , [[DateValue]] )を実行する。 tv をdateObj .[[DateValue]] とする。tv がNaN なら、NaN を返す。MinFromTime (tv )を返す。
21.4.4.18 Date.prototype.getUTCMonth ( )
このmethodは呼び出されたとき、次のstepsを実行します:
dateObj をthis valueとする。? RequireInternalSlot (dateObj , [[DateValue]] )を実行する。 tv をdateObj .[[DateValue]] とする。tv がNaN なら、NaN を返す。MonthFromTime (tv )を返す。
21.4.4.19 Date.prototype.getUTCSeconds ( )
このmethodは呼び出されたとき、次のstepsを実行します:
dateObj をthis valueとする。? RequireInternalSlot (dateObj , [[DateValue]] )を実行する。 tv をdateObj .[[DateValue]] とする。tv がNaN なら、NaN を返す。SecFromTime (tv )を返す。
21.4.4.20 Date.prototype.setDate ( date )
このmethodは呼び出されたとき、次のstepsを実行します:
dateObj をthis valueとする。? RequireInternalSlot (dateObj , [[DateValue]] )を実行する。 tv をdateObj .[[DateValue]] とする。dt を ? ToNumber (date ) とする。tv がNaN なら、NaN を返す。tv をLocalTime (tv )に設定する。newDate をMakeDate (MakeDay (YearFromTime (tv ), MonthFromTime (tv ), dt ), TimeWithinDay (tv ))とする。u をTimeClip (UTC (newDate ))とする。dateObj .[[DateValue]] をu に設定する。u を返す。
21.4.4.21 Date.prototype.setFullYear ( year [ , month [ , date ] ] )
このmethodは呼び出されたとき、次のstepsを実行します:
dateObj をthis valueとする。? RequireInternalSlot (dateObj , [[DateValue]] )を実行する。 tv をdateObj .[[DateValue]] とする。y を ? ToNumber (year ) とする。tv がNaN なら、tv を+0 𝔽 に設定する;そうでなければ、tv をLocalTime (tv )に設定する。month がpresentなら、m を ? ToNumber (month ) とする;そうでなければ、m をMonthFromTime (tv )とする。date がpresentなら、dt を ? ToNumber (date ) とする;そうでなければ、dt をDateFromTime (tv )とする。newDate をMakeDate (MakeDay (y , m , dt ), TimeWithinDay (tv ))とする。u をTimeClip (UTC (newDate ))とする。dateObj .[[DateValue]] をu に設定する。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を実行します:
dateObj をthis valueとする。? RequireInternalSlot (dateObj , [[DateValue]] )を実行する。 tv をdateObj .[[DateValue]] とする。h を ? ToNumber (hour ) とする。min がpresentなら、m を ? ToNumber (min ) とする。sec がpresentなら、s を ? ToNumber (sec ) とする。ms がpresentなら、milli を ? ToNumber (ms ) とする。tv がNaN なら、NaN を返す。tv をLocalTime (tv )に設定する。min がpresentでないなら、m をMinFromTime (tv )とする。sec がpresentでないなら、s をSecFromTime (tv )とする。ms がpresentでないなら、milli をmsFromTime (tv )とする。date をMakeDate (Day (tv ), MakeTime (h , m , s , milli ))とする。u をTimeClip (UTC (date ))とする。dateObj .[[DateValue]] をu に設定する。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を実行します:
dateObj をthis valueとする。? RequireInternalSlot (dateObj , [[DateValue]] )を実行する。 tv をdateObj .[[DateValue]] とする。ms を ? ToNumber (ms ) に設定する。tv がNaN なら、NaN を返す。tv をLocalTime (tv )に設定する。time をMakeTime (HourFromTime (tv ), MinFromTime (tv ), SecFromTime (tv ), ms )とする。u をTimeClip (UTC (MakeDate (Day (tv ), time )))とする。dateObj .[[DateValue]] をu に設定する。u を返す。
21.4.4.24 Date.prototype.setMinutes ( min [ , sec [ , ms ] ] )
このmethodは呼び出されたとき、次のstepsを実行します:
dateObj をthis valueとする。? RequireInternalSlot (dateObj , [[DateValue]] )を実行する。 tv をdateObj .[[DateValue]] とする。m を ? ToNumber (min ) とする。sec がpresentなら、s を ? ToNumber (sec ) とする。ms がpresentなら、milli を ? ToNumber (ms ) とする。tv がNaN なら、NaN を返す。tv をLocalTime (tv )に設定する。sec がpresentでないなら、s をSecFromTime (tv )とする。ms がpresentでないなら、milli をmsFromTime (tv )とする。date をMakeDate (Day (tv ), MakeTime (HourFromTime (tv ), m , s , milli ))とする。u をTimeClip (UTC (date ))とする。dateObj .[[DateValue]] をu に設定する。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を実行します:
dateObj をthis valueとする。? RequireInternalSlot (dateObj , [[DateValue]] )を実行する。 tv をdateObj .[[DateValue]] とする。m を ? ToNumber (month ) とする。date がpresentなら、dt を ? ToNumber (date ) とする。tv がNaN なら、NaN を返す。tv をLocalTime (tv )に設定する。date がpresentでないなら、dt をDateFromTime (tv )とする。newDate をMakeDate (MakeDay (YearFromTime (tv ), m , dt ), TimeWithinDay (tv ))とする。u をTimeClip (UTC (newDate ))とする。dateObj .[[DateValue]] をu に設定する。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を実行します:
dateObj をthis valueとする。? RequireInternalSlot (dateObj , [[DateValue]] )を実行する。 tv をdateObj .[[DateValue]] とする。s を ? ToNumber (sec ) とする。ms がpresentなら、milli を ? ToNumber (ms ) とする。tv がNaN なら、NaN を返す。tv をLocalTime (tv )に設定する。ms がpresentでないなら、milli をmsFromTime (tv )とする。date をMakeDate (Day (tv ), MakeTime (HourFromTime (tv ), MinFromTime (tv ), s , milli ))とする。u をTimeClip (UTC (date ))とする。dateObj .[[DateValue]] をu に設定する。u を返す。
このmethodの"length" propertyは2 𝔽 です。
Note
ms がpresentでない場合、このmethodはms がvalue getMilliseconds()でpresentであったかのようにbehaveします。
21.4.4.27 Date.prototype.setTime ( time )
このmethodは呼び出されたとき、次のstepsを実行します:
dateObj をthis valueとする。? RequireInternalSlot (dateObj , [[DateValue]] )を実行する。 t を ? ToNumber (time ) とする。v をTimeClip (t )とする。dateObj .[[DateValue]] をv に設定する。v を返す。
21.4.4.28 Date.prototype.setUTCDate ( date )
このmethodは呼び出されたとき、次のstepsを実行します:
dateObj をthis valueとする。? RequireInternalSlot (dateObj , [[DateValue]] )を実行する。 tv をdateObj .[[DateValue]] とする。dt を ? ToNumber (date ) とする。tv がNaN なら、NaN を返す。newDate をMakeDate (MakeDay (YearFromTime (tv ), MonthFromTime (tv ), dt ), TimeWithinDay (tv ))とする。v をTimeClip (newDate )とする。dateObj .[[DateValue]] をv に設定する。v を返す。
21.4.4.29 Date.prototype.setUTCFullYear ( year [ , month [ , date ] ] )
このmethodは呼び出されたとき、次のstepsを実行します:
dateObj をthis valueとする。? RequireInternalSlot (dateObj , [[DateValue]] )を実行する。 tv をdateObj .[[DateValue]] とする。tv がNaN なら、tv を+0 𝔽 に設定する。y を ? ToNumber (year ) とする。month がpresentなら、m を ? ToNumber (month ) とする;そうでなければ、m をMonthFromTime (tv )とする。date がpresentなら、dt を ? ToNumber (date ) とする;そうでなければ、dt をDateFromTime (tv )とする。newDate をMakeDate (MakeDay (y , m , dt ), TimeWithinDay (tv ))とする。v をTimeClip (newDate )とする。dateObj .[[DateValue]] をv に設定する。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を実行します:
dateObj をthis valueとする。? RequireInternalSlot (dateObj , [[DateValue]] )を実行する。 tv をdateObj .[[DateValue]] とする。h を ? ToNumber (hour ) とする。min がpresentなら、m を ? ToNumber (min ) とする。sec がpresentなら、s を ? ToNumber (sec ) とする。ms がpresentなら、milli を ? ToNumber (ms ) とする。tv がNaN なら、NaN を返す。min がpresentでないなら、m をMinFromTime (tv )とする。sec がpresentでないなら、s をSecFromTime (tv )とする。ms がpresentでないなら、milli をmsFromTime (tv )とする。date をMakeDate (Day (tv ), MakeTime (h , m , s , milli ))とする。v をTimeClip (date )とする。dateObj .[[DateValue]] をv に設定する。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を実行します:
dateObj をthis valueとする。? RequireInternalSlot (dateObj , [[DateValue]] )を実行する。 tv をdateObj .[[DateValue]] とする。ms を ? ToNumber (ms ) に設定する。tv がNaN なら、NaN を返す。time をMakeTime (HourFromTime (tv ), MinFromTime (tv ), SecFromTime (tv ), ms )とする。v をTimeClip (MakeDate (Day (tv ), time ))とする。dateObj .[[DateValue]] をv に設定する。v を返す。
21.4.4.32 Date.prototype.setUTCMinutes ( min [ , sec [ , ms ] ] )
このmethodは呼び出されたとき、次のstepsを実行します:
dateObj をthis valueとする。? RequireInternalSlot (dateObj , [[DateValue]] )を実行する。 tv をdateObj .[[DateValue]] とする。m を ? ToNumber (min ) とする。sec がpresentなら、s を ? ToNumber (sec ) とする。ms がpresentなら、milli を ? ToNumber (ms ) とする。tv がNaN なら、NaN を返す。sec がpresentでないなら、s をSecFromTime (tv )とする。ms がpresentでないなら、milli をmsFromTime (tv )とする。date をMakeDate (Day (tv ), MakeTime (HourFromTime (tv ), m , s , milli ))とする。v をTimeClip (date )とする。dateObj .[[DateValue]] をv に設定する。v を返す。
このmethodの"length" propertyは3 𝔽 です。
Note
sec がpresentでない場合、このmethodはsec がvalue getUTCSeconds()でpresentであったかのようにbehaveします。ms がpresentでない場合、ms がgetUTCMilliseconds()によって返されるvalueでpresentであったかのようにbehaveします。
21.4.4.33 Date.prototype.setUTCMonth ( month [ , date ] )
このmethodは呼び出されたとき、次のstepsを実行します:
dateObj をthis valueとする。? RequireInternalSlot (dateObj , [[DateValue]] )を実行する。 tv をdateObj .[[DateValue]] とする。m を ? ToNumber (month ) とする。date がpresentなら、dt を ? ToNumber (date ) とする。tv がNaN なら、NaN を返す。date がpresentでないなら、dt をDateFromTime (tv )とする。newDate をMakeDate (MakeDay (YearFromTime (tv ), m , dt ), TimeWithinDay (tv ))とする。v をTimeClip (newDate )とする。dateObj .[[DateValue]] をv に設定する。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を実行します:
dateObj をthis valueとする。? RequireInternalSlot (dateObj , [[DateValue]] )を実行する。 tv をdateObj .[[DateValue]] とする。s を ? ToNumber (sec ) とする。ms がpresentなら、milli を ? ToNumber (ms ) とする。tv がNaN なら、NaN を返す。ms がpresentでないなら、milli をmsFromTime (tv )とする。date をMakeDate (Day (tv ), MakeTime (HourFromTime (tv ), MinFromTime (tv ), s , milli ))とする。v をTimeClip (date )とする。dateObj .[[DateValue]] をv に設定する。v を返す。
このmethodの"length" propertyは2 𝔽 です。
Note
ms がpresentでない場合、このmethodはms がvalue getUTCMilliseconds()でpresentであったかのようにbehaveします。
21.4.4.35 Date.prototype.toDateString ( )
このmethodは呼び出されたとき、次のstepsを実行します:
dateObj をthis valueとする。? RequireInternalSlot (dateObj , [[DateValue]] )を実行する。 tv をdateObj .[[DateValue]] とする。tv がNaN なら、"Invalid Date" を返す。t をLocalTime (tv )とする。DateString (t )を返す。
21.4.4.36 Date.prototype.toISOString ( )
このmethodは呼び出されたとき、次のstepsを実行します:
dateObj をthis valueとする。? RequireInternalSlot (dateObj , [[DateValue]] )を実行する。 tv をdateObj .[[DateValue]] とする。tv がNaN なら、RangeError 例外をthrowする。Assert : tv はintegral Number である。tv がDate Time String Format でrepresentできないyearに対応するなら、RangeError 例外をthrowする。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.stringify(25.5.4 )による使用のためにDateのString representationを提供します。
これは呼び出されたとき、次のstepsを実行します:
obj を ? ToObject (this value) とする。tv を ? ToPrimitive (obj , number ) とする。tv がNumberであり、かつtv がfinite でないなら、null を返す。? Invoke (obj , "toISOString" )を返す。
Note 1
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を実行します:
dateObj をthis valueとする。? RequireInternalSlot (dateObj , [[DateValue]] )を実行する。 tv をdateObj .[[DateValue]] とする。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:
hour をToZeroPaddedDecimalString (ℝ (HourFromTime (tv )), 2)とする。minute をToZeroPaddedDecimalString (ℝ (MinFromTime (tv )), 2)とする。second をToZeroPaddedDecimalString (ℝ (SecFromTime (tv )), 2)とする。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:
weekday を、WeekDay (tv )のNumberを持つTable 61 内のentryのNameとする。month を、MonthFromTime (tv )のNumberを持つTable 62 内のentryのNameとする。day をToZeroPaddedDecimalString (ℝ (DateFromTime (tv )), 2)とする。yv をYearFromTime (tv )とする。yv が+0 𝔽 またはyv > +0 𝔽 なら、yearSign をempty Stringとする;そうでなければ、yearSign を"-" とする。paddedYear をToZeroPaddedDecimalString (abs (ℝ (yv )), 4)とする。weekday 、code unit 0x0020 (SPACE)、month 、code unit 0x0020 (SPACE)、day 、code unit 0x0020 (SPACE)、yearSign 、およびpaddedYear のstring-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:
systemTimeZoneIdentifier をSystemTimeZoneIdentifier ()とする。IsTimeZoneOffsetString (systemTimeZoneIdentifier )がtrue なら、offsetNs をParseTimeZoneOffsetString (systemTimeZoneIdentifier )とする。そうでなければ、offsetNs をGetNamedTimeZoneOffsetNanoseconds (systemTimeZoneIdentifier , ℤ (ℝ (tv ) × 106 ))とする。 offset を𝔽 (truncate (offsetNs / 106 ))とする。offset が+0 𝔽 またはoffset > +0 𝔽 なら、offsetSign を"+" とする。absOffset をoffset とする。そうでなければ、offsetSign を"-" とする。absOffset を-offset とする。 offsetMin をToZeroPaddedDecimalString (ℝ (MinFromTime (absOffset )), 2)とする。offsetHour をToZeroPaddedDecimalString (ℝ (HourFromTime (absOffset )), 2)とする。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とする。offsetSign 、offsetHour 、offsetMin 、およびtzName のstring-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:
tv がNaN なら、"Invalid Date" を返す。localTime をLocalTime (tv )とする。DateString (localTime )、code unit 0x0020 (SPACE)、TimeString (localTime )、およびTimeZoneString (tv )のstring-concatenation を返す。
21.4.4.42 Date.prototype.toTimeString ( )
このmethodは呼び出されたとき、次のstepsを実行します:
dateObj をthis valueとする。? RequireInternalSlot (dateObj , [[DateValue]] )を実行する。 tv をdateObj .[[DateValue]] とする。tv がNaN なら、"Invalid Date" を返す。localTime をLocalTime (tv )とする。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を実行します:
dateObj をthis valueとする。? RequireInternalSlot (dateObj , [[DateValue]] )を実行する。 tv をdateObj .[[DateValue]] とする。tv がNaN なら、"Invalid Date" を返す。weekday を、WeekDay (tv )のNumberを持つTable 61 内のentryのNameとする。month を、MonthFromTime (tv )のNumberを持つTable 62 内のentryのNameとする。day をToZeroPaddedDecimalString (ℝ (DateFromTime (tv )), 2)とする。yv をYearFromTime (tv )とする。yv が+0 𝔽 またはyv > +0 𝔽 なら、yearSign をempty Stringとする;そうでなければ、yearSign を"-" とする。paddedYear をToZeroPaddedDecimalString (abs (ℝ (yv )), 4)とする。weekday 、"," 、code unit 0x0020 (SPACE)、day 、code unit 0x0020 (SPACE)、month 、code unit 0x0020 (SPACE)、yearSign 、paddedYear 、code unit 0x0020 (SPACE)、およびTimeString (tv )のstring-concatenation を返す。
21.4.4.44 Date.prototype.valueOf ( )
このmethodは呼び出されたとき、次のstepsを実行します:
dateObj をthis valueとする。? RequireInternalSlot (dateObj , [[DateValue]] )を実行する。 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を実行します:
obj をthis valueとする。obj がObjectでないなら、TypeError 例外をthrowする。hint が"string" または"default" のいずれかなら、tryFirst をstring とする。そうでなく、hint が"number" なら、tryFirst をnumber とする。 そうでなければ、TypeError 例外をThrowする。 ? 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を実行します:
value がpresentでないなら、string をempty Stringとする。そうでなければ、NewTargetがundefined であり、かつvalue がSymbolなら、SymbolDescriptiveString (value )を返す。 string を ? ToString (value ) とする。 NewTargetがundefined なら、string を返す。 StringCreate (string , ? GetPrototypeFromConstructor (NewTarget, "%String.prototype%" ))を返す。
22.1.2 Properties of the String Constructor
String constructor は:
22.1.2.1 String.fromCharCode ( ...codeUnits )
このfunctionは、rest parameter codeUnits を形成する任意の数のargumentsで呼び出すことができます。
これは呼び出されたとき、次のstepsを実行します:
result をempty Stringとする。codeUnits の各要素next について、以下を行うnextCU を、numeric valueがℝ (? ToUint16 (next ))であるcode unitとする。result をresult とnextCU のstring-concatenation に設定する。result を返す。
このfunctionの"length" propertyは1 𝔽 です。
22.1.2.2 String.fromCodePoint ( ...codePoints )
このfunctionは、rest parameter codePoints を形成する任意の数のargumentsで呼び出すことができます。
これは呼び出されたとき、次のstepsを実行します:
result をempty Stringとする。codePoints の各要素next について、以下を行うnextCP を ? ToNumber (next ) とする。nextCP がintegral Number でないなら、RangeError 例外をthrowする。ℝ (nextCP ) < 0またはℝ (nextCP ) > 0x10FFFFなら、RangeError 例外をthrowする。result をresult とUTF16EncodeCodePoint (ℝ (nextCP ))のstring-concatenation に設定する。Assert : codePoints がemptyなら、result はempty Stringである。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を実行します:
substitutionCount をsubstitutions 内のelementsの数とする。cooked を ? ToObject (template ) とする。literals を ? ToObject (? Get (cooked , "raw" )) とする。literalCount を ? LengthOfArrayLike (literals ) とする。literalCount ≤ 0なら、empty Stringを返す。result をempty Stringとする。nextIndex を0とする。繰り返す:nextLiteralValue を ? Get (literals , ! ToString (𝔽 (nextIndex ))) とする。nextLiteral を ? ToString (nextLiteralValue ) とする。result をresult とnextLiteral のstring-concatenation に設定する。nextIndex + 1 = literalCount なら、result を返す。nextIndex < substitutionCount なら、nextSubValue をsubstitutions [nextIndex ]とする。nextSub を ? ToString (nextSubValue ) とする。result をresult とnextSub のstring-concatenation に設定する。nextIndex をnextIndex + 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 )
thisValue をthis valueとする。? RequireObjectCoercible (thisValue )を実行する。 string を ? ToString (thisValue ) とする。length をstring のlengthとする。relativeIndex を ? ToIntegerOrInfinity (index ) とする。relativeIndex ≥ 0なら、k をrelativeIndex とする。そうでなければ、k をlength + relativeIndex とする。 k < 0またはk ≥ length なら、undefined を返す。string のk から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ではありません。
posがintegral Number である場合、x.charAt(pos)のresultはx.substring(pos, pos + 1)のresultとequivalentです。
このmethodは呼び出されたとき、次のstepsを実行します:
thisValue をthis valueとする。? RequireObjectCoercible (thisValue )を実行する。 string を ? ToString (thisValue ) とする。position を ? ToIntegerOrInfinity (position ) に設定する。size をstring のlengthとする。position < 0またはposition ≥ size なら、empty Stringを返す。string のposition から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を実行します:
thisValue をthis valueとする。? RequireObjectCoercible (thisValue )を実行する。 string を ? ToString (thisValue ) とする。position を ? ToIntegerOrInfinity (position ) に設定する。size をstring のlengthとする。position < 0またはposition ≥ size なら、NaN を返す。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 pair がposition でbeginしない場合、resultはposition にあるcode unitです。
このmethodは呼び出されたとき、次のstepsを実行します:
thisValue をthis valueとする。? RequireObjectCoercible (thisValue )を実行する。 string を ? ToString (thisValue ) とする。position を ? ToIntegerOrInfinity (position ) に設定する。size をstring のlengthとする。position < 0またはposition ≥ size なら、undefined を返す。codePoint をCodePointAt (string , position )とする。𝔽 (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を実行します:
thisValue をthis valueとする。? RequireObjectCoercible (thisValue )を実行する。 string を ? ToString (thisValue ) とする。result をstring とする。args の各要素next について、以下を行うnextString を ? ToString (next ) とする。result をresult とnextString のstring-concatenation に設定する。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を実行します:
thisValue をthis valueとする。? RequireObjectCoercible (thisValue )を実行する。 string を ? ToString (thisValue ) とする。isRegexp を ? IsRegExp (searchString ) とする。isRegexp がtrue なら、TypeError 例外をthrowする。searchString を ? ToString (searchString ) に設定する。length をstring のlengthとする。endPosition がundefined なら、position をlength とする;そうでなければ、position を ? ToIntegerOrInfinity (endPosition ) とする。end をposition を0とlength の間にclamping したresultとする。searchLength をsearchString のlengthとする。searchLength = 0なら、true を返す。start をend - searchLength とする。start < 0なら、false を返す。substring をstring のstart からend までのsubstring とする。substring がsearchString なら、true を返す。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を実行します:
thisValue をthis valueとする。? RequireObjectCoercible (thisValue )を実行する。 string を ? ToString (thisValue ) とする。isRegexp を ? IsRegExp (searchString ) とする。isRegexp がtrue なら、TypeError 例外をthrowする。searchString を ? ToString (searchString ) に設定する。positionInt を ? ToIntegerOrInfinity (position ) とする。Assert : position がundefined なら、positionInt は0である。length をstring のlengthとする。start をpositionInt を0とlength の間にclamping したresultとする。index をStringIndexOf (string , searchString , start )とする。index がnot-found なら、false を返す。true を返す。
Note 1
searchString が、このobjectをStringへconvertしたresultのsubstring として、position 以上である1つ以上のindicesにappearsする場合、このfunctionはtrue を返します;そうでなければfalse を返します。position がundefined なら、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 𝔽 が返されます。position がundefined なら、String全体をsearchするために+0 𝔽 がassumedされます。
このmethodは呼び出されたとき、次のstepsを実行します:
thisValue をthis valueとする。? RequireObjectCoercible (thisValue )を実行する。 string を ? ToString (thisValue ) とする。searchString を ? ToString (searchString ) に設定する。positionInt を ? ToIntegerOrInfinity (position ) とする。Assert : position がundefined なら、positionInt は0である。length をstring のlengthとする。start をpositionInt を0とlength の間にclamping したresultとする。result をStringIndexOf (string , searchString , start )とする。result がnot-found なら、-1 𝔽 を返す。𝔽 (result )を返す。
Note 2
このmethodは意図的にgenericです;そのthis valueがString objectであることをrequireしません。したがって、methodとして使用するために他の種類のobjectsへtransferできます。
22.1.3.10 String.prototype.isWellFormed ( )
このmethodは呼び出されたとき、次のstepsを実行します:
thisValue をthis valueとする。? RequireObjectCoercible (thisValue )を実行する。 string を ? ToString (thisValue ) とする。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 𝔽 が返されます。position がundefined なら、String全体をsearchするためにString valueのlengthがassumedされます。
このmethodは呼び出されたとき、次のstepsを実行します:
thisValue をthis valueとする。? RequireObjectCoercible (thisValue )を実行する。 string を ? ToString (thisValue ) とする。searchString を ? ToString (searchString ) に設定する。numberPosition を ? ToNumber (position ) とする。Assert : position がundefined なら、numberPosition はNaN である。numberPosition がNaN なら、position を+∞に設定する;そうでなければ、position を ! ToIntegerOrInfinity (numberPosition ) に設定する。length をstring のlengthとする。searchLength をsearchString のlengthとする。length < searchLength なら、-1 𝔽 を返す。start をposition を0とlength - searchLength の間にclamping したresultとする。result をStringLastIndexOf (string , searchString , start )とする。result がnot-found なら、-1 𝔽 を返す。𝔽 (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 に対応することを意図しており、string がthatValue より前にorderedされるときnegative、string がthatValue より後にorderedされるときpositive、その他すべての場合にはzero(string とthatValue の間にrelative orderingがないことを表す)になります。
comparisonsを実行する前に、このmethodはStringsをprepareするために次のstepsを実行します:
thisValue をthis valueとする。? RequireObjectCoercible (thisValue )を実行する。 string を ? ToString (thisValue ) とする。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 𝔽 を返さなければなりません:
"\u212B" .localeCompare ("A\u030A" )
"\u2126" .localeCompare ("\u03A9" )
"\u1E69" .localeCompare ("s\u0307\u0323" )
"\u1E0B\u0323" .localeCompare ("\u1E0D\u0307" )
"\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を実行します:
thisValue をthis valueとする。? RequireObjectCoercible (thisValue )を実行する。 regexpOrPattern がObjectなら、matcher を ? GetMethod (regexpOrPattern , %Symbol.match% ) とする。matcher がundefined でないなら、? Call (matcher , regexpOrPattern , « thisValue »)を返す。 string を ? ToString (thisValue ) とする。regexp を ? RegExpCreate (regexpOrPattern , undefined ) とする。? 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を実行します:
thisValue をthis valueとする。? RequireObjectCoercible (thisValue )を実行する。 regexpOrPattern がObjectなら、isRegexp を ? IsRegExp (regexpOrPattern ) とする。isRegexp がtrue なら、flags を ? Get (regexpOrPattern , "flags" ) とする。? RequireObjectCoercible (flags )を実行する。 ? ToString (flags )が"g" を含まないなら、TypeError 例外をthrowする。 matcher を ? GetMethod (regexpOrPattern , %Symbol.matchAll% ) とする。matcher がundefined でないなら、? Call (matcher , regexpOrPattern , « thisValue »)を返す。 string を ? ToString (thisValue ) とする。regexp を ? RegExpCreate (regexpOrPattern , "g" ) とする。? 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を実行します:
thisValue をthis valueとする。? RequireObjectCoercible (thisValue )を実行する。 string を ? ToString (thisValue ) とする。form がundefined なら、form を"NFC" に設定する。そうでなければ、form を ? ToString (form ) に設定する。 form が"NFC" 、"NFD" 、"NFKC" 、または"NFKD" のいずれでもないなら、RangeError 例外をthrowする。normal を、the latest Unicode Standard, Normalization Forms で指定される通り、form によってnamedされたnormalization formへstring をnormalizingしたresultであるString valueとする。normal を返す。
Note
このmethodは意図的にgenericです;そのthis valueがString objectであることをrequireしません。したがって、methodとして使用するために他の種類のobjectsへtransferできます。
22.1.3.16 String.prototype.padEnd ( maxLength [ , fillString ] )
このmethodは呼び出されたとき、次のstepsを実行します:
thisValue をthis valueとする。? RequireObjectCoercible (thisValue )を実行する。 ? StringPaddingBuiltinsImpl (thisValue , maxLength , fillString , end )を返す。
22.1.3.17 String.prototype.padStart ( maxLength [ , fillString ] )
このmethodは呼び出されたとき、次のstepsを実行します:
thisValue をthis valueとする。? RequireObjectCoercible (thisValue )を実行する。 ? 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:
string を ? ToString (thisValue ) とする。intMaxLength をℝ (? ToLength (maxLength ))とする。stringLength をstring のlengthとする。intMaxLength ≤ stringLength なら、string を返す。fillString がundefined なら、fillString をcode unit 0x0020 (SPACE)のみからなるString valueに設定する。そうでなければ、fillString を ? ToString (fillString ) に設定する。 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:
stringLength をstring のlengthとする。maxLength ≤ stringLength なら、string を返す。fillString がempty Stringなら、string を返す。fillLength をmaxLength - stringLength とする。truncatedStringFiller を、fillString のrepeated concatenationsからなり、length fillLength にtruncatedされたString valueとする。placement がstart なら、truncatedStringFiller とstring のstring-concatenation を返す。string とtruncatedStringFiller のstring-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:
string をdecimal numberとしてformattedされたn のString representationとする。StringPad (string , minLength , "0" , start )を返す。
22.1.3.18 String.prototype.repeat ( count )
このmethodは呼び出されたとき、次のstepsを実行します:
thisValue をthis valueとする。? RequireObjectCoercible (thisValue )を実行する。 string を ? ToString (thisValue ) とする。n を ? ToIntegerOrInfinity (count ) とする。n < 0またはn = +∞なら、RangeError 例外をthrowする。n = 0なら、empty Stringを返す。string のn 個の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を実行します:
thisValue をthis valueとする。? RequireObjectCoercible (thisValue )を実行する。 searchValue がObjectなら、replacer を ? GetMethod (searchValue , %Symbol.replace% ) とする。replacer がundefined でないなら、? Call (replacer , searchValue , « thisValue , replaceValue »)を返す。 string を ? ToString (thisValue ) とする。searchString を ? ToString (searchValue ) とする。functionalReplace をIsCallable (replaceValue )とする。functionalReplace がfalse なら、replaceValue を ? ToString (replaceValue ) に設定する。searchLength をsearchString のlengthとする。position をStringIndexOf (string , searchString , 0)とする。position がnot-found なら、string を返す。preceding をstring の0からposition までのsubstring とする。following をstring のposition + searchLength からのsubstring とする。functionalReplace がtrue なら、replacement を ? ToString (? Call (replaceValue , undefined , « searchString , 𝔽 (position ), string »)) とする。そうでなければ、Assert : replaceValue はStringである。captures を新しい空のList とする。replacement を ! GetSubstitution (searchString , string , position , captures , undefined , replaceValue ) とする。 preceding 、replacement 、およびfollowing のstring-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:
stringLength をstring のlengthとする。Assert : position ≤ stringLength である。result をempty Stringとする。templateRemainder をreplacementTemplate とする。templateRemainder がempty Stringでない間、繰り返すNOTE : 以下のstepsはref (templateRemainder のprefix)をisolateし、refReplacement (そのreplacement)をdetermineし、そのreplacementをresult へappendする。templateRemainder が"$$" で始まるなら、ref を"$$" とする。refReplacement を"$" とする。そうでなく、templateRemainder が"$`" で始まるなら、ref を"$`" とする。refReplacement をstring の0からposition までのsubstring とする。 そうでなく、templateRemainder が"$&" で始まるなら、ref を"$&" とする。refReplacement をmatched とする。 そうでなく、templateRemainder が"$'" (0x0024 (DOLLAR SIGN) followed by 0x0027 (APOSTROPHE))で始まるなら、ref を"$'" とする。matchLength をmatched のlengthとする。tailPosition をposition + matchLength とする。refReplacement をstring のmin (tailPosition , stringLength )からのsubstring とする。NOTE : このabstract operationが、"exec" propertyがintrinsic %RegExp.prototype.exec%でないobject上の%RegExp.prototype% のintrinsic %Symbol.replace% methodへのcallによってinvokedされた場合にのみ、tailPosition はstringLength を超え得る。 そうでなく、templateRemainder が"$" の後に1つ以上のdecimal digitsが続くもので始まるなら、templateRemainder が"$" の後に2つ以上のdecimal digitsが続くもので始まるなら、digitCount を2とする;そうでなければ、digitCount を1とする。digits をtemplateRemainder の1から1 + digitCount までのsubstring とする。index をℝ (StringToNumber (digits ))とする。Assert : 0 ≤ index ≤ 99である。captureLength をcaptures 内のelementsの数とする。index > captureLength かつdigitCount = 2なら、NOTE : two-digit replacement patternがcapturing groupsのcountを超えるindexをspecifyする場合、それはone-digit replacement patternの後にliteral digitが続くものとして扱われる。digitCount を1に設定する。digits をdigits の0から1までのsubstring に設定する。index をℝ (StringToNumber (digits ))に設定する。ref をtemplateRemainder の0から1 + digitCount までのsubstring とする。1 ≤ index ≤ captureLength なら、capture をcaptures [index - 1]とする。capture がundefined なら、refReplacement をempty Stringとする。そうでなければ、refReplacement をcapture とする。 そうでなければ、refReplacement をref とする。 そうでなく、templateRemainder が"$<" で始まるなら、gtPosition をStringIndexOf (templateRemainder , ">" , 0)とする。gtPosition がnot-found またはnamedCaptures がundefined なら、ref を"$<" とする。refReplacement をref とする。そうでなければ、ref をtemplateRemainder の0からgtPosition + 1までのsubstring とする。groupName をtemplateRemainder の2からgtPosition までのsubstring とする。Assert : namedCaptures はObjectである。capture を ? Get (namedCaptures , groupName ) とする。capture がundefined なら、refReplacement をempty Stringとする。そうでなければ、refReplacement を ? ToString (capture ) とする。 そうでなければ、ref をtemplateRemainder の0から1までのsubstring とする。refReplacement をref とする。 refLength をref のlengthとする。templateRemainder をtemplateRemainder のrefLength からのsubstring に設定する。result をresult とrefReplacement のstring-concatenation に設定する。result を返す。
22.1.3.20 String.prototype.replaceAll ( searchValue , replaceValue )
このmethodは呼び出されたとき、次のstepsを実行します:
thisValue をthis valueとする。? RequireObjectCoercible (thisValue )を実行する。 searchValue がObjectなら、isRegexp を ? IsRegExp (searchValue ) とする。isRegexp がtrue なら、flags を ? Get (searchValue , "flags" ) とする。? RequireObjectCoercible (flags )を実行する。 ? ToString (flags )が"g" を含まないなら、TypeError 例外をthrowする。 replacer を ? GetMethod (searchValue , %Symbol.replace% ) とする。replacer がundefined でないなら、? Call (replacer , searchValue , « thisValue , replaceValue »)を返す。 string を ? ToString (thisValue ) とする。searchString を ? ToString (searchValue ) とする。functionalReplace をIsCallable (replaceValue )とする。functionalReplace がfalse なら、replaceValue を ? ToString (replaceValue ) に設定する。searchLength をsearchString のlengthとする。advanceBy をmax (1, searchLength )とする。matchPositions を新しい空のList とする。position をStringIndexOf (string , searchString , 0)とする。position がnot-found でない間、繰り返すposition をmatchPositions へappendする。position をStringIndexOf (string , searchString , position + advanceBy )に設定する。endOfLastMatch を0とする。result をempty Stringとする。matchPositions の各要素matchPosition について、以下を行うpreserved をstring のendOfLastMatch からmatchPosition までのsubstring とする。functionalReplace がtrue なら、replacement を ? ToString (? Call (replaceValue , undefined , « searchString , 𝔽 (matchPosition ), string »)) とする。そうでなければ、Assert : replaceValue はStringである。captures を新しい空のList とする。replacement を ! GetSubstitution (searchString , string , matchPosition , captures , undefined , replaceValue ) とする。 result をresult 、preserved 、およびreplacement のstring-concatenation に設定する。endOfLastMatch をmatchPosition + searchLength に設定する。endOfLastMatch < string のlengthなら、result をresult とstring のendOfLastMatch からのsubstring のstring-concatenation に設定する。result を返す。
22.1.3.21 String.prototype.search ( regexpOrPattern )
このmethodは呼び出されたとき、次のstepsを実行します:
thisValue をthis valueとする。? RequireObjectCoercible (thisValue )を実行する。 regexpOrPattern がObjectなら、searcher を ? GetMethod (regexpOrPattern , %Symbol.search% ) とする。searcher がundefined でないなら、? Call (searcher , regexpOrPattern , « thisValue »)を返す。 string を ? ToString (thisValue ) とする。regexp を ? RegExpCreate (regexpOrPattern , undefined ) とする。? 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します(またはend がundefined ならStringのendまで)。start がnegativeなら、sourceLength をStringのlengthとして、sourceLength + start として扱われます。end がnegativeなら、sourceLength をStringのlengthとして、sourceLength + end として扱われます。resultはString valueであり、String objectではありません。
これは呼び出されたとき、次のstepsを実行します:
thisValue をthis valueとする。? RequireObjectCoercible (thisValue )を実行する。 string を ? ToString (thisValue ) とする。length をstring のlengthとする。intStart を ? ToIntegerOrInfinity (start ) とする。intStart = -∞なら、from を0とする。そうでなく、intStart < 0なら、from をmax (length + intStart , 0)とする。 そうでなければ、from をmin (intStart , length )とする。 end がundefined なら、intEnd をlength とする;そうでなければ、intEnd を ? ToIntegerOrInfinity (end ) とする。intEnd = -∞なら、to を0とする。そうでなく、intEnd < 0なら、to をmax (length + intEnd , 0)とする。 そうでなければ、to をmin (intEnd , length )とする。 from ≥ to なら、empty Stringを返す。string のfrom から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を実行します:
thisValue をthis valueとする。? RequireObjectCoercible (thisValue )を実行する。 separator がObjectなら、splitter を ? GetMethod (separator , %Symbol.split% ) とする。splitter がundefined でないなら、? Call (splitter , separator , « thisValue , limit »)を返す。 string を ? ToString (thisValue ) とする。limit がundefined なら、lim を232 - 1とする;そうでなければ、lim をℝ (? ToUint32 (limit ))とする。separatorString を ? ToString (separator ) とする。lim = 0なら、CreateArrayFromList (« »)を返す。separator がundefined なら、CreateArrayFromList (« string »)を返す。separatorLength をseparatorString のlengthとする。separatorLength = 0なら、stringLength をstring のlengthとする。outLength をlim を0とstringLength の間にclamping したresultとする。head をstring の0からoutLength までのsubstring とする。codeUnits を、head のelementsであるcode unitsのsequenceからなるList とする。CreateArrayFromList (codeUnits )を返す。string がempty Stringなら、CreateArrayFromList (« string »)を返す。substrings を新しい空のList とする。searchStart を0とする。matchIndex をStringIndexOf (string , separatorString , 0)とする。matchIndex がnot-found でない間、繰り返すsubstring をstring のsearchStart からmatchIndex までのsubstring とする。substring をsubstrings へappendする。substrings 内のelementsの数がlim なら、CreateArrayFromList (substrings )を返す。searchStart をmatchIndex + separatorLength に設定する。matchIndex をStringIndexOf (string , separatorString , searchStart )に設定する。substring をstring のsearchStart からのsubstring とする。substring をsubstrings へappendする。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です。
separator がundefined である場合、result arrayはthis value(Stringへconvertedされる)であるone Stringだけを含みます。limit がundefined でない場合、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を実行します:
thisValue をthis valueとする。? RequireObjectCoercible (thisValue )を実行する。 string を ? ToString (thisValue ) とする。isRegexp を ? IsRegExp (searchString ) とする。isRegexp がtrue なら、TypeError 例外をthrowする。searchString を ? ToString (searchString ) に設定する。length をstring のlengthとする。position がundefined なら、position を0に設定する;そうでなければ、position を ? ToIntegerOrInfinity (position ) に設定する。start をposition を0とlength の間にclamping したresultとする。searchLength をsearchString のlengthとする。searchLength = 0なら、true を返す。end をstart + searchLength とする。end > length なら、false を返す。substring をstring のstart からend までのsubstring とする。substring がsearchString なら、true を返す。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します(またはend がundefined ならStringのendまで)。resultはString valueであり、String objectではありません。
いずれかのargumentがNaN またはnegativeである場合、それはzeroで置き換えられます;いずれかのargumentがStringのlengthよりstrictly greaterである場合、それはStringのlengthで置き換えられます。
start がend よりstrictly greaterである場合、それらはswappedされます。
これは呼び出されたとき、次のstepsを実行します:
thisValue をthis valueとする。? RequireObjectCoercible (thisValue )を実行する。 string を ? ToString (thisValue ) とする。length をstring のlengthとする。intStart を ? ToIntegerOrInfinity (start ) とする。end がundefined なら、intEnd をlength とする;そうでなければ、intEnd を ? ToIntegerOrInfinity (end ) とする。finalStart をintStart を0とlength の間にclamping したresultとする。finalEnd をintEnd を0とlength の間にclamping したresultとする。from をmin (finalStart , finalEnd )とする。to をmax (finalStart , finalEnd )とする。string のfrom から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を実行します:
thisValue をthis valueとする。? RequireObjectCoercible (thisValue )を実行する。 string を ? ToString (thisValue ) とする。sText をStringToCodePoints (string )とする。lowerText を、Unicode Default Case Conversion algorithmに従うtoLowercase(sText )とする。lowercaseString をCodePointsToString (lowerText )とする。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でないことがあります。toUpperCaseとtoLowerCaseの両方が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を実行します:
? 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を実行します:
thisValue をthis valueとする。? RequireObjectCoercible (thisValue )を実行する。 string を ? ToString (thisValue ) とする。stringLength をstring のlengthとする。k を0とする。result をempty Stringとする。k < stringLength の間、繰り返すcodePoint をCodePointAt (string , k )とする。codePoint .[[IsUnpairedSurrogate]] がtrue なら、result をresult と0xFFFD (REPLACEMENT CHARACTER)のstring-concatenation に設定する。そうでなければ、result をresult とUTF16EncodeCodePoint (codePoint .[[CodePoint]] )のstring-concatenation に設定する。 k をk + codePoint .[[CodeUnitCount]] に設定する。result を返す。
22.1.3.32 String.prototype.trim ( )
このmethodは、6.1.4 でdescribedされる通り、String valueをUTF-16 encoded code pointsのsequenceとしてinterpretします。
これは呼び出されたとき、次のstepsを実行します:
thisValue をthis valueとする。? 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:
? RequireObjectCoercible (arg )を実行する。 string を ? ToString (arg ) とする。where がstart なら、trimmedString を、string からleading white spaceがremovedされたcopyであるString valueとする。そうでなく、where がend なら、trimmedString を、string からtrailing white spaceがremovedされたcopyであるString valueとする。 そうでなければ、Assert : where はstart+end である。trimmedString を、string からleadingおよびtrailing white spaceの両方がremovedされたcopyであるString valueとする。 trimmedString を返す。
white spaceのdefinitionはWhiteSpace とLineTerminator の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を実行します:
string をthis valueとする。? 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を実行します:
string をthis valueとする。? TrimString (string , start )を返す。
Note
このmethodは意図的にgenericです;そのthis valueがString objectであることをrequireしません。したがって、methodとして使用するために他の種類のobjectsへtransferできます。
22.1.3.35 String.prototype.valueOf ( )
このmethodは呼び出されたとき、次のstepsを実行します:
? 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:
arg がStringなら、arg を返す。arg がObjectであり、かつarg が[[StringData]] internal slotを持つなら、string をarg .[[StringData]] とする。Assert : string はStringである。string を返す。TypeError 例外をThrowする。
22.1.3.36 String.prototype [ %Symbol.iterator% ] ( )
このmethodは、String valueのcode pointsをiterateし、各code pointをString valueとしてreturnするiterator object を返します。
これは呼び出されたとき、次のstepsを実行します:
string をthis valueとする。? RequireObjectCoercible (string )を実行する。 string を ? ToString (string ) に設定する。closure を、string をcaptureし、呼び出されたとき次のstepsを実行する、parametersを持たない新しいAbstract Closure とする:length をstring のlengthとする。position を0とする。position < length の間、繰り返すcodePoint をCodePointAt (string , position )とする。nextIndex をposition + codePoint .[[CodeUnitCount]] とする。resultString をstring のposition からnextIndex までのsubstring とする。position をnextIndex に設定する。? GeneratorYield (CreateIteratorResultObject (resultString , false ))を実行する。 NormalCompletion (unused )を返す。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 ( )
? 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
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
UnicodePropertyNameCharacters opt
UnicodePropertyValue ::
UnicodePropertyValueCharacters
LoneUnicodePropertyNameOrValue ::
UnicodePropertyValueCharacters
UnicodePropertyValueCharacters ::
UnicodePropertyValueCharacter
UnicodePropertyValueCharacters opt
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
ClassUnion opt
ClassSetOperand
ClassUnion opt
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
NonEmptyClassString opt
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
UnicodePropertyValueExpression :: LoneUnicodePropertyNameOrValue
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 ::
(
GroupSpecifier opt
Disjunction
)
productionの( terminalにmatchedする任意の( pattern characterです。
Note
このsectionはB.1.2.2 でamendedされます。
It performs the following steps when called:
Assert : parseNode はthe RegExp Pattern grammar 内のproductionのinstanceである。parseNode 内にcontainedされる
Atom ::
(
GroupSpecifier opt
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:
Assert : parseNode はthe RegExp Pattern grammar 内のproductionのinstanceである。pattern をparseNode を含むPattern とする。pattern 内にcontainedされる
Atom ::
(
GroupSpecifier opt
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:
Assert : x およびy は同じenclosing Pattern を持つ。enclosing Pattern が、x がAlternative 内にcontainedされy がderived Disjunction 内にcontainedされる、またはx がderived Disjunction 内にcontainedされy がAlternative 内にcontainedされるような
Disjunction ::
Alternative
|
Disjunction
Parse Node を含むなら、false を返す。 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
NonZeroDigit のMVを返す。
DecimalEscape ::
NonZeroDigit
DecimalDigits
n をDecimalDigits 内のcode pointsの数とする。(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
false を返す。
ClassEscape :: CharacterClassEscape
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 :: -
U+002D (HYPHEN-MINUS)のnumeric valueを返す。
ClassAtomNoDash :: SourceCharacter but not one of \ or ] or -
codePoint をSourceCharacter にmatchedするcode pointとする。codePoint のnumeric valueを返す。
ClassEscape :: b
U+0008 (BACKSPACE)のnumeric valueを返す。
ClassEscape ::
U+002D (HYPHEN-MINUS)のnumeric valueを返す。
CharacterEscape :: ControlEscape
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
codePoint をAsciiLetter にmatchedするcode pointとする。i をcodePoint のnumeric valueとする。i を32で割ったremainderを返す。
CharacterEscape ::
0
[lookahead ∉ DecimalDigit ]
U+0000 (NULL)のnumeric valueを返す。
Note 2
\0は<NUL> characterを表し、decimal digitをfollowすることはできません。
CharacterEscape :: HexEscapeSequence
HexEscapeSequence のMVを返す。
RegExpUnicodeEscapeSequence ::
u
HexLeadSurrogate
\u
HexTrailSurrogate
lead をHexLeadSurrogate のCharacterValue とする。trail をHexTrailSurrogate のCharacterValue とする。codePoint をUTF16SurrogatePairToCodePoint (lead , trail )とする。codePoint のnumeric valueを返す。
RegExpUnicodeEscapeSequence ::
u
Hex4Digits
Hex4Digits のMVを返す。
RegExpUnicodeEscapeSequence ::
u{
CodePoint
}
CodePoint のMVを返す。
HexLeadSurrogate :: Hex4Digits
HexTrailSurrogate :: Hex4Digits
HexNonSurrogate :: Hex4Digits
Hex4Digits のMVを返す。
CharacterEscape :: IdentityEscape
codePoint をIdentityEscape にmatchedするcode pointとする。codePoint のnumeric valueを返す。
ClassSetCharacter :: SourceCharacter but not ClassSetSyntaxCharacter
codePoint をSourceCharacter にmatchedするcode pointとする。codePoint のnumeric valueを返す。
ClassSetCharacter ::
\
ClassSetReservedPunctuator
codePoint をClassSetReservedPunctuator にmatchedするcode pointとする。codePoint のnumeric valueを返す。
ClassSetCharacter :: \b
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
false を返す。
UnicodePropertyValueExpression :: LoneUnicodePropertyNameOrValue
LoneUnicodePropertyNameOrValue にmatchedするsource textがTable 67 の“Property name ” columnにlistedされているbinary property of stringsであるなら、true を返す。false を返す。
ClassUnion ::
ClassSetRange
ClassUnion opt
ClassUnion がpresentなら、ClassUnion のMayContainStrings を返す。false を返す。
ClassUnion ::
ClassSetOperand
ClassUnion opt
ClassSetOperand のMayContainStrings がtrue なら、true を返す。ClassUnion がpresentなら、ClassUnion のMayContainStrings を返す。false を返す。
ClassIntersection ::
ClassSetOperand
&&
ClassSetOperand
first ClassSetOperand のMayContainStrings がfalse なら、false を返す。 second ClassSetOperand のMayContainStrings がfalse なら、false を返す。 true を返す。
ClassIntersection ::
ClassIntersection
&&
ClassSetOperand
ClassIntersection のMayContainStrings がfalse なら、false を返す。ClassSetOperand のMayContainStrings がfalse なら、false を返す。true を返す。
ClassSubtraction ::
ClassSetOperand
--
ClassSetOperand
first ClassSetOperand のMayContainStrings を返す。
ClassSubtraction ::
ClassSubtraction
--
ClassSetOperand
ClassSubtraction のMayContainStrings を返す。
ClassStringDisjunctionContents ::
ClassString
|
ClassStringDisjunctionContents
ClassString のMayContainStrings がtrue なら、true を返す。ClassStringDisjunctionContents のMayContainStrings を返す。
ClassString :: [empty]
true を返す。
ClassString :: NonEmptyClassString
NonEmptyClassString のMayContainStrings を返す。
NonEmptyClassString ::
ClassSetCharacter
NonEmptyClassString opt
NonEmptyClassString がpresentなら、true を返す。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:
name をthisGroupName のCapturingGroupName とする。pattern をthisGroupName を含むPattern とする。result を新しい空のList とする。pattern が含む各GroupSpecifier groupSpecifier について、以下を行うgroupSpecifier のCapturingGroupName がname であるなら、groupSpecifier をresult へappendする。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
>
idTextUnescaped をRegExpIdentifierName のRegExpIdentifierCodePoints とする。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
codePoint をRegExpIdentifierStart のRegExpIdentifierCodePoint とする。« codePoint »を返す。
RegExpIdentifierName ::
RegExpIdentifierName
RegExpIdentifierPart
派生したRegExpIdentifierName のRegExpIdentifierCodePoints をcodePoints とする。 RegExpIdentifierPart のRegExpIdentifierCodePoint をcodePoint とする。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
IdentifierStartChar にmatchedするcode pointを返す。
RegExpIdentifierPart :: IdentifierPartChar
IdentifierPartChar にmatchedするcode pointを返す。
RegExpIdentifierStart ::
\
RegExpUnicodeEscapeSequence
RegExpIdentifierPart ::
\
RegExpUnicodeEscapeSequence
numeric valueがRegExpUnicodeEscapeSequence のCharacterValue であるcode pointを返す。
RegExpIdentifierStart ::
UnicodeLeadSurrogate
UnicodeTrailSurrogate
RegExpIdentifierPart ::
UnicodeLeadSurrogate
UnicodeTrailSurrogate
lead を、numeric valueがUnicodeLeadSurrogate にmatchedするcode pointのnumeric valueであるcode unitとする。trail を、numeric valueがUnicodeTrailSurrogate にmatchedするcode pointのnumeric valueであるcode unitとする。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がuもvも含まない場合は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]] のn th elementは、n th set of capturing parenthesesによってcapturedされたcharactersのrangeを表すCaptureRange 、またはn th 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する場合、MatcherContinuation はfailure を返します。
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します。できる場合、Matcher はMatcherContinuation によって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
m を、arguments regexpRecord およびforward を伴うDisjunction のCompileSubpattern とする。regexpRecord およびm をcaptureし、calledされたときに次のstepsをperformする、parameters (input , index )を持つnew Abstract Closure を返す:Assert : input はcharactersのList である。Assert : 0 ≤ index ≤ input 内のelementsの数である。c を、nothingをcaptureし、calledされたときに次のstepsをperformする、parameters (y )を持つnew MatcherContinuation とする:Assert : y はMatchState である。y を返す。capability を、1からregexpRecord .[[CapturingGroupsCount]] までindexedされたregexpRecord .[[CapturingGroupsCount]] 個のundefined valuesのList とする。x をMatchState { [[Input]] : input , [[EndIndex]] : index , [[Captures]] : capability }とする。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
m1 を、arguments regexpRecord およびdirection を伴うAlternative のCompileSubpattern とする。m2 を、arguments regexpRecord およびdirection を伴うDisjunction のCompileSubpattern とする。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]
EmptyMatcher ()を返す。
Alternative ::
Alternative
Term
m1 を、arguments regexpRecord およびdirection を伴うAlternative のCompileSubpattern とする。m2 を、arguments regexpRecord およびdirection を伴うTerm のCompileSubpattern とする。MatchSequence (m1 , m2 , direction )を返す。
Note 3
Consecutive Term sは、input のconsecutive portionsをsimultaneouslyにmatchしようとします。direction がforward であるとき、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されます。direction がbackward であるとき、Alternative およびTerm のevaluation orderはreversedされます。
Term :: Assertion
argument regexpRecord を伴うAssertion のCompileAssertion を返す。
Note 4
resulting Matcher はdirection にindependentです。
Term :: Atom
arguments regexpRecord およびdirection を伴うAtom のCompileAtom を返す。
Term ::
Atom
Quantifier
m を、arguments regexpRecord およびdirection を伴うAtom のCompileAtom とする。q をQuantifier のCompileQuantifier とする。Assert : q .[[Min]] ≤ q .[[Max]] である。parenIndex をCountLeftCapturingParensBefore (Term )とする。parenCount をCountLeftCapturingParensWithin (Atom )とする。m 、q 、parenIndex 、およびparenCount をcaptureし、calledされたときに次のstepsをperformする、parameters (x , c )を持つnew Matcher を返す:Assert : x はMatchState である。Assert : c はMatcherContinuation である。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:
max = 0なら、continue (matchState )を返す。d を、m 、min 、max 、greedy 、matchState 、continue 、parenIndex 、およびparenCount をcaptureし、calledされたときに次のstepsをperformする、parameters (y )を持つnew MatcherContinuation とする:Assert : y はMatchState である。min = 0かつy .[[EndIndex]] = matchState .[[EndIndex]] なら、failure を返す。min = 0なら、min2 を0とする;そうでなければ、min2 をmin - 1とする。max = +∞なら、max2 を+∞とする;そうでなければ、max2 をmax - 1とする。RepeatMatcher (m , min2 , max2 , greedy , y , continue , parenIndex , parenCount )を返す。capability をmatchState .[[Captures]] のcopyとする。parenIndex + 1からparenIndex + parenCount までのinclusive interval 内の各integer k について、capability [k ]をundefined に設定する。input をmatchState .[[Input]] とする。e をmatchState .[[EndIndex]] とする。xr をMatchState { [[Input]] : input , [[EndIndex]] : e , [[Captures]] : capability }とする。min ≠ 0なら、m (xr , d )を返す。greedy がfalse なら、z をcontinue (matchState )とする。z がfailure でないなら、z を返す。m (xr , d )を返す。z をm (xr , d )とする。z がfailure でないなら、z を返す。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:
nothingをcaptureし、calledされたときに次のstepsをperformする、parameters (matchState , continue )を持つnew Matcher を返す:Assert : matchState はMatchState である。Assert : continue はMatcherContinuation である。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:
m1 およびm2 をcaptureし、calledされたときに次のstepsをperformする、parameters (matchState , continue )を持つnew Matcher を返す:Assert : matchState はMatchState である。Assert : continue はMatcherContinuation である。result をm1 (matchState , continue )とする。result がfailure でないなら、result を返す。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:
direction がforward なら、m1 およびm2 をcaptureし、calledされたときに次のstepsをperformする、parameters (matchState , continue )を持つnew Matcher を返す:Assert : matchState はMatchState である。Assert : continue はMatcherContinuation である。d を、continue およびm2 をcaptureし、calledされたときに次のstepsをperformする、parameters (y )を持つnew MatcherContinuation とする:Assert : y はMatchState である。m2 (y , continue )を返す。m1 (matchState , d )を返す。Assert : direction はbackward である。m1 およびm2 をcaptureし、calledされたときに次のstepsをperformする、parameters (matchState , continue )を持つnew Matcher を返す:Assert : matchState はMatchState である。Assert : continue はMatcherContinuation である。d を、continue およびm1 をcaptureし、calledされたときに次のstepsをperformする、parameters (y )を持つnew MatcherContinuation とする:Assert : y はMatchState である。m1 (y , continue )を返す。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 :: ^
regexpRecord をcaptureし、calledされたときに次のstepsをperformする、parameters (matchState , continue )を持つnew Matcher を返す:Assert : matchState はMatchState である。Assert : continue はMatcherContinuation である。input をmatchState .[[Input]] とする。e をmatchState .[[EndIndex]] とする。e = 0である、またはregexpRecord .[[Multiline]] がtrue でありcharacter input [e - 1]がLineTerminator によってmatchedされるなら、continue (matchState )を返す。failure を返す。
Note 2
y flagがpatternとともに使用される場合であっても、^は常にinput のbeginning、または(regexpRecord .[[Multiline]] がtrue なら)lineのbeginningにのみmatchします。
Assertion :: $
regexpRecord をcaptureし、calledされたときに次のstepsをperformする、parameters (matchState , continue )を持つnew Matcher を返す:Assert : matchState はMatchState である。Assert : continue はMatcherContinuation である。input をmatchState .[[Input]] とする。e をmatchState .[[EndIndex]] とする。inputLength をinput 内のelementsの数とする。e = inputLength である、またはregexpRecord .[[Multiline]] がtrue でありcharacter input [e ]がLineTerminator によってmatchedされるなら、continue (matchState )を返す。failure を返す。
Assertion :: \b
regexpRecord をcaptureし、calledされたときに次のstepsをperformする、parameters (matchState , continue )を持つnew Matcher を返す:Assert : matchState はMatchState である。Assert : continue はMatcherContinuation である。input をmatchState .[[Input]] とする。e をmatchState .[[EndIndex]] とする。a をIsWordChar (regexpRecord , input , e - 1)とする。b をIsWordChar (regexpRecord , input , e )とする。a がtrue でありb がfalse である、またはa がfalse でありb がtrue であるなら、continue (matchState )を返す。failure を返す。
Assertion :: \B
regexpRecord をcaptureし、calledされたときに次のstepsをperformする、parameters (matchState , continue )を持つnew Matcher を返す:Assert : matchState はMatchState である。Assert : continue はMatcherContinuation である。input をmatchState .[[Input]] とする。e をmatchState .[[EndIndex]] とする。a をIsWordChar (regexpRecord , input , e - 1)とする。b をIsWordChar (regexpRecord , input , e )とする。a がtrue でありb がtrue である、またはa がfalse でありb がfalse であるなら、continue (matchState )を返す。failure を返す。
Assertion ::
(?=
Disjunction
)
m を、arguments regexpRecord およびforward を伴うDisjunction のCompileSubpattern とする。m をcaptureし、calledされたときに次のstepsをperformする、parameters (matchState , continue )を持つnew Matcher を返す:Assert : matchState はMatchState である。Assert : continue はMatcherContinuation である。d を、nothingをcaptureし、calledされたときに次のstepsをperformする、parameters (y )を持つnew MatcherContinuation とする:Assert : y はMatchState である。y を返す。result をm (matchState , d )とする。result がfailure なら、failure を返す。Assert : result はMatchState である。capability をresult .[[Captures]] とする。input をmatchState .[[Input]] とする。xe をmatchState .[[EndIndex]] とする。z をMatchState { [[Input]] : input , [[EndIndex]] : xe , [[Captures]] : capability }とする。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
)
m を、arguments regexpRecord およびforward を伴うDisjunction のCompileSubpattern とする。m をcaptureし、calledされたときに次のstepsをperformする、parameters (matchState , continue )を持つnew Matcher を返す:Assert : matchState はMatchState である。Assert : continue はMatcherContinuation である。d を、nothingをcaptureし、calledされたときに次のstepsをperformする、parameters (y )を持つnew MatcherContinuation とする:Assert : y はMatchState である。y を返す。result をm (matchState , d )とする。result がfailure でないなら、failure を返す。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
)
m を、arguments regexpRecord およびbackward を伴うDisjunction のCompileSubpattern とする。m をcaptureし、calledされたときに次のstepsをperformする、parameters (matchState , continue )を持つnew Matcher を返す:Assert : matchState はMatchState である。Assert : continue はMatcherContinuation である。d を、nothingをcaptureし、calledされたときに次のstepsをperformする、parameters (y )を持つnew MatcherContinuation とする:Assert : y はMatchState である。y を返す。result をm (matchState , d )とする。result がfailure なら、failure を返す。Assert : result はMatchState である。capability をresult .[[Captures]] とする。input をmatchState .[[Input]] とする。xe をmatchState .[[EndIndex]] とする。z をMatchState { [[Input]] : input , [[EndIndex]] : xe , [[Captures]] : capability }とする。continue (z )を返す。
Assertion ::
(?<!
Disjunction
)
m を、arguments regexpRecord およびbackward を伴うDisjunction のCompileSubpattern とする。m をcaptureし、calledされたときに次のstepsをperformする、parameters (matchState , continue )を持つnew Matcher を返す:Assert : matchState はMatchState である。Assert : continue はMatcherContinuation である。d を、nothingをcaptureし、calledされたときに次のstepsをperformする、parameters (y )を持つnew MatcherContinuation とする:Assert : y はMatchState である。y を返す。result をm (matchState , d )とする。result がfailure でないなら、failure を返す。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:
inputLength をinput 内のelementsの数とする。e = -1またはe = inputLength なら、false を返す。char をcharacter input [e ]とする。WordCharacters (regexpRecord )がchar を含むなら、true を返す。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
qp をQuantifierPrefix のCompileQuantifierPrefix とする。Record { [[Min]] : qp .[[Min]] , [[Max]] : qp .[[Max]] , [[Greedy]] : true }を返す。
Quantifier ::
QuantifierPrefix
?
qp をQuantifierPrefix のCompileQuantifierPrefix とする。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 :: *
Record { [[Min]] : 0, [[Max]] : +∞ }を返す。
QuantifierPrefix :: +
Record { [[Min]] : 1, [[Max]] : +∞ }を返す。
QuantifierPrefix :: ?
Record { [[Min]] : 0, [[Max]] : 1 }を返す。
QuantifierPrefix ::
{
DecimalDigits
}
i をDecimalDigits のMVとする(12.9.3 を参照)。Record { [[Min]] : i , [[Max]] : i }を返す。
QuantifierPrefix ::
{
DecimalDigits
,}
i をDecimalDigits のMVとする。Record { [[Min]] : i , [[Max]] : +∞ }を返す。
QuantifierPrefix ::
{
DecimalDigits
,
DecimalDigits
}
i をfirst DecimalDigits のMVとする。j をsecond DecimalDigits のMVとする。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
char をPatternCharacter にmatchedするcharacterとする。charSet をcharacter char を含むone-element CharSet とする。CharacterSetMatcher (regexpRecord , charSet , false , direction )を返す。
Atom :: .
charSet をAllCharacters (regexpRecord )とする。regexpRecord .[[DotAll]] がtrue でないなら、LineTerminator productionのright-hand side上のcode pointに対応するすべてのcharactersをcharSet からremoveする。CharacterSetMatcher (regexpRecord , charSet , false , direction )を返す。
Atom :: CharacterClass
cc をargument regexpRecord を伴うCharacterClass のCompileCharacterClass とする。cs をcc .[[CharSet]] とする。regexpRecord .[[UnicodeSets]] がfalse である、またはcs のすべてのCharSetElement がsingle characterからなる(cs がemptyの場合を含む)なら、CharacterSetMatcher (regexpRecord , cs , cc .[[Invert]] , direction )を返す。Assert : cc .[[Invert]] はfalse である。listOfMatchers をMatchers のempty List とする。cs 内のmore than 1 characterを含む各CharSetElement s について、lengthのdescending orderでiteratingして、以下を行うcs2 をs のlast code pointを含むone-element CharSet とする。m2 をCharacterSetMatcher (regexpRecord , cs2 , false , direction )とする。s 内の各code point c1 について、そのsecond-to-last code pointからbackwardsにiteratingして、以下を行うcs1 をc1 を含むone-element CharSet とする。m1 をCharacterSetMatcher (regexpRecord , cs1 , false , direction )とする。m2 をMatchSequence (m1 , m2 , direction )に設定する。m2 をlistOfMatchers へappendする。singles を、single characterからなるcs のすべてのCharSetElement を含むCharSet とする。CharacterSetMatcher (regexpRecord , singles , false , direction )をlistOfMatchers へappendする。cs がcharactersのempty sequenceを含むなら、EmptyMatcher ()をlistOfMatchers へappendする。m2 をlistOfMatchers 内のlast Matcher とする。listOfMatchers の各Matcher m1 について、そのsecond-to-last elementからbackwardsにiteratingして、以下を行うm2 をMatchTwoAlternatives (m1 , m2 )に設定する。m2 を返す。
Atom ::
(
GroupSpecifier opt
Disjunction
)
m を、arguments regexpRecord およびdirection を伴うDisjunction のCompileSubpattern とする。parenIndex をCountLeftCapturingParensBefore (Atom )とする。direction 、m 、およびparenIndex をcaptureし、calledされたときに次のstepsをperformする、parameters (x , c )を持つnew Matcher を返す:Assert : x はMatchState である。Assert : c はMatcherContinuation である。d を、x 、c 、direction 、およびparenIndex をcaptureし、calledされたときに次のstepsをperformする、parameters (y )を持つnew MatcherContinuation とする:Assert : y はMatchState である。capability をy .[[Captures]] のcopyとする。input をx .[[Input]] とする。xe をx .[[EndIndex]] とする。ye をy .[[EndIndex]] とする。direction がforward なら、Assert : xe ≤ ye である。r をCaptureRange { [[StartIndex]] : xe , [[EndIndex]] : ye }とする。そうでなければ、Assert : direction はbackward である。Assert : ye ≤ xe である。r をCaptureRange { [[StartIndex]] : ye , [[EndIndex]] : xe }とする。 capability [parenIndex + 1]をr に設定する。z をMatchState { [[Input]] : input , [[EndIndex]] : ye , [[Captures]] : capability }とする。c (z )を返す。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
)
addModifiers をRegularExpressionModifiers にmatchedするsource textとする。removeModifiers をempty Stringとする。modifiedRer をUpdateModifiers (regexpRecord , CodePointsToString (addModifiers ), removeModifiers )とする。arguments modifiedRer およびdirection を伴うDisjunction のCompileSubpattern を返す。
Atom ::
(?
RegularExpressionModifiers
-
RegularExpressionModifiers
:
Disjunction
)
addModifiers をfirst RegularExpressionModifiers にmatchedするsource textとする。removeModifiers をsecond RegularExpressionModifiers にmatchedするsource textとする。modifiedRer をUpdateModifiers (regexpRecord , CodePointsToString (addModifiers ), CodePointsToString (removeModifiers ))とする。arguments modifiedRer およびdirection を伴うDisjunction のCompileSubpattern を返す。
AtomEscape :: DecimalEscape
n をDecimalEscape のCapturingGroupNumber とする。Assert : n ≤ regexpRecord .[[CapturingGroupsCount]] である。BackreferenceMatcher (regexpRecord , « n », direction )を返す。
Note 3
\ followed by a non-zero decimal number n というformのescape sequenceは、n th set of capturing parentheses(22.2.2.1 )のresultにmatchします。regular expressionがn 個未満のcapturing parenthesesを持つ場合、errorになります。regular expressionがn 個以上のcapturing parenthesesを持つが、n th oneが何もcapturedしていないためundefined である場合、backreferenceは常にsucceedsします。
AtomEscape :: CharacterEscape
charValue をCharacterEscape のCharacterValue とする。char をcharacter valueがcharValue であるcharacterとする。charSet をcharacter char を含むone-element CharSet とする。CharacterSetMatcher (regexpRecord , charSet , false , direction )を返す。
AtomEscape :: CharacterClassEscape
cs をargument regexpRecord を伴うCharacterClassEscape のCompileToCharSet とする。regexpRecord .[[UnicodeSets]] がfalse である、またはcs のすべてのCharSetElement がsingle characterからなる(cs がemptyの場合を含む)なら、CharacterSetMatcher (regexpRecord , cs , false , direction )を返す。listOfMatchers をMatchers のempty List とする。cs 内のmore than 1 characterを含む各CharSetElement s について、lengthのdescending orderでiteratingして、以下を行うcs2 をs のlast code pointを含むone-element CharSet とする。m2 をCharacterSetMatcher (regexpRecord , cs2 , false , direction )とする。s 内の各code point c1 について、そのsecond-to-last code pointからbackwardsにiteratingして、以下を行うcs1 をc1 を含むone-element CharSet とする。m1 をCharacterSetMatcher (regexpRecord , cs1 , false , direction )とする。m2 をMatchSequence (m1 , m2 , direction )に設定する。m2 をlistOfMatchers へappendする。singles を、single characterからなるcs のすべてのCharSetElement を含むCharSet とする。CharacterSetMatcher (regexpRecord , singles , false , direction )をlistOfMatchers へappendする。cs がcharactersのempty sequenceを含むなら、EmptyMatcher ()をlistOfMatchers へappendする。m2 をlistOfMatchers 内のlast Matcher とする。listOfMatchers の各Matcher m1 について、そのsecond-to-last elementからbackwardsにiteratingして、以下を行うm2 をMatchTwoAlternatives (m1 , m2 )に設定する。m2 を返す。
AtomEscape ::
k
GroupName
matchingGroupSpecifiers をGroupSpecifiersThatMatch (GroupName )とする。parenIndices を新しい空のList とする。matchingGroupSpecifiers の各GroupSpecifier groupSpecifier について、以下を行うparenIndex をCountLeftCapturingParensBefore (groupSpecifier )とする。parenIndex をparenIndices へappendする。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:
regexpRecord .[[UnicodeSets]] がtrue なら、Assert : invert はfalse である。Assert : charSet のすべてのCharSetElement はsingle characterからなる。regexpRecord 、charSet 、invert 、およびdirection をcaptureし、calledされたときに次のstepsをperformする、parameters (x , c )を持つnew Matcher を返す:Assert : x はMatchState である。Assert : c はMatcherContinuation である。input をx .[[Input]] とする。endIndex をx .[[EndIndex]] とする。direction がforward なら、f をendIndex + 1とする。そうでなければ、f をendIndex - 1とする。 inputLength をinput 内のelementsの数とする。f < 0またはf > inputLength なら、failure を返す。index をmin (endIndex , f )とする。char をcharacter input [index ]とする。cc をCanonicalize (regexpRecord , char )とする。Canonicalize (regexpRecord , a )がcc であるような、exactly one character a を含むCharSetElement がcharSet 内に存在するなら、found をtrue とする;そうでなければ、found をfalse とする。invert がfalse であり、かつfound がfalse なら、failure を返す。invert がtrue であり、かつfound がtrue なら、failure を返す。capability をx .[[Captures]] とする。y をMatchState { [[Input]] : input , [[EndIndex]] : f , [[Captures]] : capability }とする。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:
regexpRecord 、ns 、およびdirection をcaptureし、calledされたときに次のstepsをperformする、parameters (x , c )を持つnew Matcher を返す:Assert : x はMatchState である。Assert : c はMatcherContinuation である。input をx .[[Input]] とする。capability をx .[[Captures]] とする。r をundefined とする。ns の各integer n について、以下を行うcapability [n ]がundefined でないなら、Assert : r はundefined である。r をcapability [n ]に設定する。r がundefined なら、c (x )を返す。endIndex をx .[[EndIndex]] とする。rs をr .[[StartIndex]] とする。re をr .[[EndIndex]] とする。length をre - rs とする。direction がforward なら、f をendIndex + length とする。そうでなければ、f をendIndex - length とする。 inputLength をinput 内のelementsの数とする。f < 0またはf > inputLength なら、failure を返す。g をmin (endIndex , f )とする。0(inclusive)からlength (exclusive)までのinterval 内に、Canonicalize (regexpRecord , input [rs + i ])がCanonicalize (regexpRecord , input [g + i ])でないようなinteger i が存在するなら、failure を返す。 y をMatchState { [[Input]] : input , [[EndIndex]] : f , [[Captures]] : capability }とする。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:
HasEitherUnicodeFlag (regexpRecord )がtrue であり、かつregexpRecord .[[IgnoreCase]] がtrue なら、Unicode Character Databaseのfile CaseFolding.txt がchar に対するsimpleまたはcommon case folding mappingを提供するなら、そのmappingをchar にapplyしたresultを返す。 char を返す。regexpRecord .[[IgnoreCase]] がfalse なら、char を返す。Assert : char はUTF-16 code unitである。codePoint をnumeric valueがchar のnumeric valueであるcode pointとする。u を、Unicode Default Case Conversion algorithmに従ったtoUppercase(« codePoint »)とする。uString をCodePointsToString (u )とする。uString のlength ≠ 1なら、char を返す。codeUnit をuString のsingle code unit elementとする。char のnumeric value ≥ 128であり、かつcodeUnit のnumeric value < 128なら、char を返す。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)をssやSSへ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し、K(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:
Assert : add およびremove はcommon elementsを持たない。ignoreCase をregexpRecord .[[IgnoreCase]] とする。multiline をregexpRecord .[[Multiline]] とする。dotAll をregexpRecord .[[DotAll]] とする。unicode をregexpRecord .[[Unicode]] とする。unicodeSets をregexpRecord .[[UnicodeSets]] とする。capturingGroupsCount をregexpRecord .[[CapturingGroupsCount]] とする。remove が"i" を含むなら、ignoreCase をfalse に設定する。そうでなく、add が"i" を含むなら、ignoreCase をtrue に設定する。 remove が"m" を含むなら、multiline をfalse に設定する。そうでなく、add が"m" を含むなら、multiline をtrue に設定する。 remove が"s" を含むなら、dotAll をfalse に設定する。そうでなく、add が"s" を含むなら、dotAll をtrue に設定する。 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
]
charSet をargument regexpRecord を伴うClassContents のCompileToCharSet とする。Record { [[CharSet]] : charSet , [[Invert]] : false }を返す。
CharacterClass ::
[^
ClassContents
]
charSet をargument regexpRecord を伴うClassContents のCompileToCharSet とする。regexpRecord .[[UnicodeSets]] がtrue なら、Record { [[CharSet]] : CharacterComplement (regexpRecord , charSet ), [[Invert]] : false }を返す。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]
empty CharSet を返す。
NonemptyClassRanges ::
ClassAtom
NonemptyClassRangesNoDash
charSet をargument regexpRecord を伴うClassAtom のCompileToCharSet とする。otherSet をargument regexpRecord を伴うNonemptyClassRangesNoDash のCompileToCharSet とする。CharSets charSet およびotherSet のunionを返す。
NonemptyClassRanges ::
ClassAtom
-
ClassAtom
ClassContents
charSet をargument regexpRecord を伴うfirst ClassAtom のCompileToCharSet とする。otherSet をargument regexpRecord を伴うsecond ClassAtom のCompileToCharSet とする。remainingSet をargument regexpRecord を伴うClassContents のCompileToCharSet とする。rangeSet をCharacterRange (charSet , otherSet )とする。rangeSet およびremainingSet のunionを返す。
NonemptyClassRangesNoDash ::
ClassAtomNoDash
NonemptyClassRangesNoDash
charSet をargument regexpRecord を伴うClassAtomNoDash のCompileToCharSet とする。otherSet をargument regexpRecord を伴うNonemptyClassRangesNoDash のCompileToCharSet とする。CharSets charSet およびotherSet のunionを返す。
NonemptyClassRangesNoDash ::
ClassAtomNoDash
-
ClassAtom
ClassContents
charSet をargument regexpRecord を伴うClassAtomNoDash のCompileToCharSet とする。otherSet をargument regexpRecord を伴うClassAtom のCompileToCharSet とする。remainingSet をargument regexpRecord を伴うClassContents のCompileToCharSet とする。rangeSet をCharacterRange (charSet , otherSet )とする。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 E、F、e、および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 :: -
single character - U+002D (HYPHEN-MINUS)を含むCharSet を返す。
ClassAtomNoDash :: SourceCharacter but not one of \ or ] or -
SourceCharacter にmatchedするcharacterを含むCharSet を返す。
ClassEscape ::
b
-
CharacterEscape
charValue をこのClassEscape のCharacterValue とする。char をcharacter valueがcharValue であるcharacterとする。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
characters 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9を含むten-element CharSet を返す。
CharacterClassEscape :: D
charSet を
CharacterClassEscape :: d
によってreturnedされるCharSet とする。CharacterComplement (regexpRecord , charSet )を返す。
CharacterClassEscape :: s
WhiteSpace またはLineTerminator productionsのright-hand side上のcode pointに対応するすべてのcharactersを含むCharSet を返す。
CharacterClassEscape :: S
charSet を
CharacterClassEscape :: s
によってreturnedされるCharSet とする。CharacterComplement (regexpRecord , charSet )を返す。
CharacterClassEscape :: w
MaybeSimpleCaseFolding (regexpRecord , WordCharacters (regexpRecord ))を返す。
CharacterClassEscape :: W
charSet を
CharacterClassEscape :: w
によってreturnedされるCharSet とする。CharacterComplement (regexpRecord , charSet )を返す。
CharacterClassEscape ::
p{
UnicodePropertyValueExpression
}
argument regexpRecord を伴うUnicodePropertyValueExpression のCompileToCharSet を返す。
CharacterClassEscape ::
P{
UnicodePropertyValueExpression
}
charSet をargument regexpRecord を伴うUnicodePropertyValueExpression のCompileToCharSet とする。Assert : charSet はsingle code pointsのみを含む。CharacterComplement (regexpRecord , charSet )を返す。
UnicodePropertyValueExpression ::
UnicodePropertyName
=
UnicodePropertyValue
ps をUnicodePropertyName にmatchedするsource textとする。p をUnicodeMatchProperty (regexpRecord , ps )とする。Assert : p はTable 65 の“Property name and aliases ” columnにlistedされているUnicode property name またはproperty aliasである。vs をUnicodePropertyValue にmatchedするsource textとする。v をUnicodeMatchPropertyValue (p , vs )とする。charSet を、character database definitionがproperty p with value v を含むすべてのUnicode code pointsを含むCharSet とする。MaybeSimpleCaseFolding (regexpRecord , charSet )を返す。
UnicodePropertyValueExpression :: LoneUnicodePropertyNameOrValue
s をLoneUnicodePropertyNameOrValue にmatchedするsource textとする。UnicodeMatchPropertyValue (General_Category, s )が、PropertyValueAliases.txt にlistedされているGeneral_Category (gc) propertyに対するUnicode property valueまたはproperty value aliasであるなら、“General_Category” property with value s をcharacter database definitionが含むすべてのUnicode code pointsを含むCharSet を返す。 p をUnicodeMatchProperty (regexpRecord , s )とする。Assert : p はTable 66 の“Property name and aliases ” columnにlistedされているbinary Unicode propertyまたはbinary property alias、またはTable 67 の“Property name ” columnにlistedされているbinary Unicode property of stringsである。charSet を、character database definitionがproperty p with value “True”を含むすべてのCharSetElementsを含むCharSet とする。MaybeSimpleCaseFolding (regexpRecord , charSet )を返す。
ClassUnion ::
ClassSetRange
ClassUnion opt
charSet をargument regexpRecord を伴うClassSetRange のCompileToCharSet とする。ClassUnion がpresentなら、otherSet をargument regexpRecord を伴うClassUnion のCompileToCharSet とする。CharSets charSet およびotherSet のunionを返す。charSet を返す。
ClassUnion ::
ClassSetOperand
ClassUnion opt
charSet をargument regexpRecord を伴うClassSetOperand のCompileToCharSet とする。ClassUnion がpresentなら、otherSet をargument regexpRecord を伴うClassUnion のCompileToCharSet とする。CharSets charSet およびotherSet のunionを返す。charSet を返す。
ClassIntersection ::
ClassSetOperand
&&
ClassSetOperand
charSet をargument regexpRecord を伴うfirst ClassSetOperand のCompileToCharSet とする。otherSet をargument regexpRecord を伴うsecond ClassSetOperand のCompileToCharSet とする。CharSets charSet およびotherSet のintersectionを返す。
ClassIntersection ::
ClassIntersection
&&
ClassSetOperand
charSet をargument regexpRecord を伴うClassIntersection のCompileToCharSet とする。otherSet をargument regexpRecord を伴うClassSetOperand のCompileToCharSet とする。CharSets charSet およびotherSet のintersectionを返す。
ClassSubtraction ::
ClassSetOperand
--
ClassSetOperand
charSet をargument regexpRecord を伴うfirst ClassSetOperand のCompileToCharSet とする。otherSet をargument regexpRecord を伴うsecond ClassSetOperand のCompileToCharSet とする。otherSet のCharSetElementsでもあるものを除いた、charSet のCharSetElementsを含むCharSet を返す。
ClassSubtraction ::
ClassSubtraction
--
ClassSetOperand
charSet をargument regexpRecord を伴うClassSubtraction のCompileToCharSet とする。otherSet をargument regexpRecord を伴うClassSetOperand のCompileToCharSet とする。otherSet のCharSetElementsでもあるものを除いた、charSet のCharSetElementsを含むCharSet を返す。
ClassSetRange ::
ClassSetCharacter
-
ClassSetCharacter
charSet をargument regexpRecord を伴うfirst ClassSetCharacter のCompileToCharSet とする。otherSet をargument regexpRecord を伴うsecond ClassSetCharacter のCompileToCharSet とする。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
charSet をargument regexpRecord を伴うClassSetCharacter のCompileToCharSet とする。MaybeSimpleCaseFolding (regexpRecord , charSet )を返す。
ClassSetOperand :: ClassStringDisjunction
charSet をargument regexpRecord を伴うClassStringDisjunction のCompileToCharSet とする。MaybeSimpleCaseFolding (regexpRecord , charSet )を返す。
ClassSetOperand :: NestedClass
argument regexpRecord を伴うNestedClass のCompileToCharSet を返す。
NestedClass ::
[
ClassContents
]
argument regexpRecord を伴うClassContents のCompileToCharSet を返す。
NestedClass ::
[^
ClassContents
]
charSet をargument regexpRecord を伴うClassContents のCompileToCharSet とする。CharacterComplement (regexpRecord , charSet )を返す。
NestedClass ::
\
CharacterClassEscape
argument regexpRecord を伴うCharacterClassEscape のCompileToCharSet を返す。
ClassStringDisjunction ::
\q{
ClassStringDisjunctionContents
}
argument regexpRecord を伴うClassStringDisjunctionContents のCompileToCharSet を返す。
ClassStringDisjunctionContents :: ClassString
s をargument regexpRecord を伴うClassString のCompileClassSetString とする。one string s を含むCharSet を返す。
ClassStringDisjunctionContents ::
ClassString
|
ClassStringDisjunctionContents
s をargument regexpRecord を伴うClassString のCompileClassSetString とする。charSet をone string s を含むCharSet とする。otherSet をargument regexpRecord を伴うClassStringDisjunctionContents のCompileToCharSet とする。CharSets charSet およびotherSet のunionを返す。
ClassSetCharacter ::
SourceCharacter but not ClassSetSyntaxCharacter
\
CharacterEscape
\
ClassSetReservedPunctuator
charValue をこのClassSetCharacter のCharacterValue とする。char をcharacter valueがcharValue であるcharacterとする。single character char を含むCharSet を返す。
ClassSetCharacter :: \b
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:
Assert : charSet およびotherSet はそれぞれexactly one characterを含む。a をCharSet charSet 内のone characterとする。b をCharSet otherSet 内のone characterとする。i をcharacter a のcharacter valueとする。j をcharacter b のcharacter valueとする。Assert : i ≤ j である。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:
regexpRecord .[[Unicode]] がtrue またはregexpRecord .[[UnicodeSets]] がtrue なら、true を返す。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:
basicWordChars をASCII word characters内のすべてのcharacterを含むCharSet とする。extraWordChars を、basicWordChars 内にないがCanonicalize (regexpRecord , c )がbasicWordChars 内にあるようなすべてのcharacters c を含むCharSet とする。Assert : HasEitherUnicodeFlag (regexpRecord )がtrue かつregexpRecord .[[IgnoreCase]] がtrue でない限り、extraWordChars はemptyである。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:
regexpRecord .[[UnicodeSets]] がtrue であり、かつregexpRecord .[[IgnoreCase]] がtrue なら、Simple Case Folding mappingを持たない(すなわち、scf (c )=c である)すべてのUnicode code points c を含むCharSet を返す。HasEitherUnicodeFlag (regexpRecord )がtrue なら、すべてのcode point valuesを含むCharSet を返す。 すべての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 Folding (scf(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:
regexpRecord .[[UnicodeSets]] がfalse またはregexpRecord .[[IgnoreCase]] がfalse なら、charSet を返す。otherSet をnew empty CharSet とする。charSet の各CharSetElement s について、以下を行うt をcharactersのempty sequenceとする。s 内の各single code point codePoint について、以下を行うscf (codePoint )をt へappendする。t をotherSet へaddする。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:
charSet をAllCharacters (regexpRecord )とする。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:
regexpRecord .[[UnicodeSets]] がtrue であり、かつp がTable 67 の“Property name ” columnにlistedされているUnicode property name であるなら、Unicode code points p のList を返す。 Assert : p はTable 65 またはTable 66 の“Property name and aliases ” columnにlistedされているUnicode property name またはproperty aliasである。c を、corresponding rowの“Canonical property name ” columnでgivenされたp のcanonical property name とする。Unicode code points c のList を返す。
Implementationsは、Table 65 、Table 66 、およびTable 67 にlistedされているUnicode property names およびaliasesをsupportしなければなりません。interoperabilityをensureするため、implementationsは他のproperty names またはaliasesをsupportしてはなりません。
Note 1
例えば、Script_Extensions(property name )およびscx(property alias)はvalidですが、script_extensionsやScxは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
Table 66: Binary Unicode property aliases and their canonical property names
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:
Assert : p はTable 65 の“Canonical property name ” columnにlistedされているcanonicalかつunaliasedなUnicode property name である。Assert : v はUnicode property p に対するproperty valueまたはproperty value aliasであり、PropertyValueAliases.txt にlistedされている。value を、corresponding rowの“Canonical property value” columnでgivenされたv のcanonical property valueとする。Unicode code points value のList を返す。
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]
charactersのempty sequenceを返す。
ClassString :: NonEmptyClassString
argument regexpRecord を伴うNonEmptyClassString のCompileClassSetString を返す。
NonEmptyClassString ::
ClassSetCharacter
NonEmptyClassString opt
cs をargument regexpRecord を伴うClassSetCharacter のCompileToCharSet とする。s1 を、cs のsingle CharSetElement であるcharactersのsequenceとする。NonEmptyClassString がpresentなら、s2 をargument regexpRecord を伴うNonEmptyClassString のCompileClassSetString とする。s1 とs2 のconcatenationを返す。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:
obj を ! RegExpAlloc (%RegExp% ) とする。? 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:
obj を ? OrdinaryCreateFromConstructor (newTarget , "%RegExp.prototype%" , « [[OriginalSource]] , [[OriginalFlags]] , [[RegExpRecord]] , [[RegExpMatcher]] ») とする。! DefinePropertyOrThrow (obj , "lastIndex" , PropertyDescriptor { [[Writable]] : true , [[Enumerable]] : false , [[Configurable]] : false })を実行する。 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:
pattern がundefined なら、pattern をempty Stringに設定する。そうでなければ、pattern を ? ToString (pattern ) に設定する。 flags がundefined なら、flags をempty Stringに設定する。そうでなければ、flags を ? ToString (flags ) に設定する。 flags が"d" 、"g" 、"i" 、"m" 、"s" 、"u" 、"v" 、または"y" 以外のcode unitを含むなら、SyntaxError 例外をthrowする。flags が同じcode unitを複数回含むなら、SyntaxError 例外をthrowする。flags が"i" を含むなら、i をtrue とする;そうでなければ、i をfalse とする。flags が"m" を含むなら、m をtrue とする;そうでなければ、m をfalse とする。flags が"s" を含むなら、s をtrue とする;そうでなければ、s をfalse とする。flags が"u" を含むなら、u をtrue とする;そうでなければ、u をfalse とする。flags が"v" を含むなら、v をtrue とする;そうでなければ、v をfalse とする。u がtrue またはv がtrue なら、patternText をStringToCodePoints (pattern )とする。そうでなければ、patternText を、pattern の各16-bit elementをUnicode BMP code pointとしてinterpretingしたresultとする。UTF-16 decodingはelementsにapplyされない。 parseResult をParsePattern (patternText , u , v )とする。parseResult がSyntaxError objectsのnon-empty List なら、SyntaxError 例外をthrowする。Assert : parseResult はPattern Parse Node である。obj .[[OriginalSource]] をpattern に設定する。obj .[[OriginalFlags]] をflags に設定する。capturingGroupsCount をCountLeftCapturingParensWithin (parseResult )とする。regexpRecord をRegExp Record { [[IgnoreCase]] : i , [[Multiline]] : m , [[DotAll]] : s , [[Unicode]] : u , [[UnicodeSets]] : v , [[CapturingGroupsCount]] : capturingGroupsCount }とする。obj .[[RegExpRecord]] をregexpRecord に設定する。obj .[[RegExpMatcher]] を、argument regexpRecord を伴うparseResult のCompilePattern に設定する。? Set (obj , "lastIndex" , +0 𝔽 , true )を実行する。 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:
v がtrue であり、かつu がtrue なら、parseResult を、one or more SyntaxError objectsを含むList とする。そうでなく、v がtrue なら、parseResult をParseText (patternText , Pattern [+UnicodeMode, +UnicodeSetsMode, +NamedCaptureGroups] )とする。 そうでなく、u がtrue なら、parseResult をParseText (patternText , Pattern [+UnicodeMode, ~UnicodeSetsMode, +NamedCaptureGroups] )とする。 そうでなければ、parseResult をParseText (patternText , Pattern [~UnicodeMode, ~UnicodeSetsMode, +NamedCaptureGroups] )とする。 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を実行します:
patternIsRegExp を ? IsRegExp (patternOrRegexp ) とする。NewTargetがundefined なら、newTarget をactive function object とする。patternIsRegExp がtrue であり、かつflags がundefined なら、patternCtor を ? Get (patternOrRegexp , "constructor" ) とする。SameValue (newTarget , patternCtor )がtrue なら、patternOrRegexp を返す。 そうでなければ、newTarget をNewTargetとする。 patternOrRegexp がObjectであり、かつpatternOrRegexp が[[RegExpMatcher]] internal slotを持つなら、patternSource をpatternOrRegexp .[[OriginalSource]] とする。flags がundefined なら、flags をpatternOrRegexp .[[OriginalFlags]] に設定する。そうでなく、patternIsRegExp がtrue なら、patternSource を ? Get (patternOrRegexp , "source" ) とする。flags がundefined なら、flags を ? Get (patternOrRegexp , "flags" ) に設定する。 そうでなければ、patternSource をpatternOrRegexp とする。 obj を ? RegExpAlloc (newTarget ) とする。? 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 は:
22.2.5.1 RegExp.escape ( string )
このfunctionは、regular expression Pattern 内でpotentially specialであるcharactersがequivalent escape sequencesで置き換えられたstring のcopyを返します。
これは呼び出されたとき、次のstepsを実行します:
string がStringでないなら、TypeError 例外をthrowする。escaped をempty Stringとする。codePointList をStringToCodePoints (string )とする。codePointList の各code point codePoint について、以下を行うescaped がempty Stringであり、かつcodePoint がDecimalDigit またはAsciiLetter のいずれかによってmatchedされるなら、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について同じことを行う。numericValue をcodePoint のnumeric valueとする。hex をNumber::toString (𝔽 (numericValue ), 16)とする。Assert : hex のlengthは2である。escaped をcode unit 0x005C (REVERSE SOLIDUS)、"x" 、およびhex のstring-concatenation に設定する。そうでなければ、escaped をescaped とEncodeForRegExpEscape (codePoint )のstring-concatenation に設定する。 escaped を返す。
Note
similar namesを持つにもかかわらず、EscapeRegExpPattern とRegExp.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:
codePoint がSyntaxCharacter によってmatchedされる、またはcodePoint がU+002F (SOLIDUS)であるなら、0x005C (REVERSE SOLIDUS)とUTF16EncodeCodePoint (codePoint )のstring-concatenation を返す。 codePoint がTable 63 の“Code Point” columnにlistedされているcode pointなら、0x005C (REVERSE SOLIDUS)と、“Code Point” columnがcodePoint を含むrowの“ControlEscape” column内のstringのstring-concatenation を返す。 otherPunctuators を",-=<>#&!%:;@~'`" とcode unit 0x0022 (QUOTATION MARK)のstring-concatenation とする。toEscape をStringToCodePoints (otherPunctuators )とする。toEscape がcodePoint を含む、codePoint がWhiteSpace またはLineTerminator のいずれかによってmatchedされる、またはcodePoint がleading surrogate またはtrailing surrogate とsame numeric valueを持つなら、codePointNumber をcodePoint のnumeric valueとする。codePointNumber ≤ 0xFFなら、hex をNumber::toString (𝔽 (codePointNumber ), 16)とする。code unit 0x005C (REVERSE SOLIDUS)、"x" 、およびStringPad (hex , 2, "0" , start )のstring-concatenation を返す。 escaped をempty Stringとする。codeUnits をUTF16EncodeCodePoint (codePoint )とする。codeUnits の各code unit codeUnit について、以下を行うescaped をescaped とUnicodeEscape (codeUnit )のstring-concatenation に設定する。escaped を返す。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を実行します:
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を実行します:
regexp をthis valueとする。? RequireInternalSlot (regexp , [[RegExpMatcher]] )を実行する。 string を ? ToString (string ) に設定する。? RegExpBuiltinExec (regexp , string )を返す。
22.2.6.3 get RegExp.prototype.dotAll
RegExp.prototype.dotAllは、set accessor functionがundefined であるaccessor property です。そのget accessor functionは呼び出されたとき、次のstepsを実行します:
regexp をthis valueとする。codeUnit をcode unit 0x0073 (LATIN SMALL LETTER S)とする。? RegExpHasFlag (regexp , codeUnit )を返す。
22.2.6.4 get RegExp.prototype.flags
RegExp.prototype.flagsは、set accessor functionがundefined であるaccessor property です。そのget accessor functionは呼び出されたとき、次のstepsを実行します:
regexp をthis valueとする。regexp がObjectでないなら、TypeError 例外をthrowする。codeUnits を新しい空のList とする。hasIndices をToBoolean (? Get (regexp , "hasIndices" ))とする。hasIndices がtrue なら、code unit 0x0064 (LATIN SMALL LETTER D)をcodeUnits へappendする。global をToBoolean (? Get (regexp , "global" ))とする。global がtrue なら、code unit 0x0067 (LATIN SMALL LETTER G)をcodeUnits へappendする。ignoreCase をToBoolean (? Get (regexp , "ignoreCase" ))とする。ignoreCase がtrue なら、code unit 0x0069 (LATIN SMALL LETTER I)をcodeUnits へappendする。multiline をToBoolean (? Get (regexp , "multiline" ))とする。multiline がtrue なら、code unit 0x006D (LATIN SMALL LETTER M)をcodeUnits へappendする。dotAll をToBoolean (? Get (regexp , "dotAll" ))とする。dotAll がtrue なら、code unit 0x0073 (LATIN SMALL LETTER S)をcodeUnits へappendする。unicode をToBoolean (? Get (regexp , "unicode" ))とする。unicode がtrue なら、code unit 0x0075 (LATIN SMALL LETTER U)をcodeUnits へappendする。unicodeSets をToBoolean (? Get (regexp , "unicodeSets" ))とする。unicodeSets がtrue なら、code unit 0x0076 (LATIN SMALL LETTER V)をcodeUnits へappendする。sticky をToBoolean (? Get (regexp , "sticky" ))とする。sticky がtrue なら、code unit 0x0079 (LATIN SMALL LETTER Y)をcodeUnits へappendする。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:
regexp がObjectでないなら、TypeError 例外をthrowする。regexp が[[OriginalFlags]] internal slotを持たないなら、SameValue (regexp , %RegExp.prototype% )がtrue なら、undefined を返す。TypeError 例外をThrowする。flags をregexp .[[OriginalFlags]] とする。flags がcodeUnit を含むなら、true を返す。false を返す。
22.2.6.5 get RegExp.prototype.global
RegExp.prototype.globalは、set accessor functionがundefined であるaccessor property です。そのget accessor functionは呼び出されたとき、次のstepsを実行します:
regexp をthis valueとする。codeUnit をcode unit 0x0067 (LATIN SMALL LETTER G)とする。? RegExpHasFlag (regexp , codeUnit )を返す。
22.2.6.6 get RegExp.prototype.hasIndices
RegExp.prototype.hasIndicesは、set accessor functionがundefined であるaccessor property です。そのget accessor functionは呼び出されたとき、次のstepsを実行します:
regexp をthis valueとする。codeUnit をcode unit 0x0064 (LATIN SMALL LETTER D)とする。? RegExpHasFlag (regexp , codeUnit )を返す。
22.2.6.7 get RegExp.prototype.ignoreCase
RegExp.prototype.ignoreCaseは、set accessor functionがundefined であるaccessor property です。そのget accessor functionは呼び出されたとき、次のstepsを実行します:
regexp をthis valueとする。codeUnit をcode unit 0x0069 (LATIN SMALL LETTER I)とする。? RegExpHasFlag (regexp , codeUnit )を返す。
22.2.6.8 RegExp.prototype [ %Symbol.match% ] ( string )
このmethodは呼び出されたとき、次のstepsを実行します:
regexp をthis valueとする。regexp がObjectでないなら、TypeError 例外をthrowする。string を ? ToString (string ) に設定する。flags を ? ToString (? Get (regexp , "flags" )) とする。flags が"g" を含まないなら、? RegExpExec (regexp , string )を返す。flags が"u" を含む、またはflags が"v" を含むなら、fullUnicode をtrue とする;そうでなければ、fullUnicode をfalse とする。? Set (regexp , "lastIndex" , +0 𝔽 , true )を実行する。 array を ! ArrayCreate (0) とする。matchCount を0とする。繰り返す:result を ? RegExpExec (regexp , string ) とする。result がnull なら、matchCount = 0なら、null を返す。array を返す。matchString を ? ToString (? Get (result , "0" )) とする。! CreateDataPropertyOrThrow (array , ! ToString (𝔽 (matchCount )), matchString )を実行する。 matchString がempty Stringなら、thisIndex をℝ (? ToLength (? Get (regexp , "lastIndex" )))とする。nextIndex をAdvanceStringIndex (string , thisIndex , fullUnicode )とする。? Set (regexp , "lastIndex" , 𝔽 (nextIndex ), true )を実行する。 matchCount をmatchCount + 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を実行します:
regexp をthis valueとする。regexp がObjectでないなら、TypeError 例外をthrowする。string を ? ToString (string ) に設定する。speciesCtor を ? SpeciesConstructor (regexp , %RegExp% ) とする。flags を ? ToString (? Get (regexp , "flags" )) とする。matcher を ? Construct (speciesCtor , « regexp , flags ») とする。lastIndex を ? ToLength (? Get (regexp , "lastIndex" )) とする。? Set (matcher , "lastIndex" , lastIndex , true )を実行する。 flags が"g" を含むなら、global をtrue とする。そうでなければ、global をfalse とする。 flags が"u" を含む、またはflags が"v" を含むなら、fullUnicode をtrue とする。そうでなければ、fullUnicode をfalse とする。 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を実行します:
regexp をthis valueとする。codeUnit をcode unit 0x006D (LATIN SMALL LETTER M)とする。? RegExpHasFlag (regexp , codeUnit )を返す。
22.2.6.11 RegExp.prototype [ %Symbol.replace% ] ( string , replaceValue )
このmethodは呼び出されたとき、次のstepsを実行します:
regexp をthis valueとする。regexp がObjectでないなら、TypeError 例外をthrowする。string を ? ToString (string ) に設定する。stringLength をstring のlengthとする。functionalReplace をIsCallable (replaceValue )とする。functionalReplace がfalse なら、replaceValue を ? ToString (replaceValue ) に設定する。flags を ? ToString (? Get (regexp , "flags" )) とする。flags が"g" を含むなら、global をtrue とする;そうでなければ、global をfalse とする。global がtrue なら、? Set (regexp , "lastIndex" , +0 𝔽 , true )を実行する。 results を新しい空のList とする。done をfalse とする。done がfalse である間、繰り返すresult を ? RegExpExec (regexp , string ) とする。result がnull なら、done をtrue に設定する。そうでなければ、result をresults へappendする。global がfalse なら、done をtrue に設定する。そうでなければ、matchString を ? ToString (? Get (result , "0" )) とする。matchString がempty Stringなら、thisIndex をℝ (? ToLength (? Get (regexp , "lastIndex" )))とする。flags が"u" を含む、またはflags が"v" を含むなら、fullUnicode をtrue とする;そうでなければ、fullUnicode をfalse とする。nextIndex をAdvanceStringIndex (string , thisIndex , fullUnicode )とする。? Set (regexp , "lastIndex" , 𝔽 (nextIndex ), true )を実行する。 accumulatedResult をempty Stringとする。nextSourcePosition を0とする。results の各要素result について、以下を行うresultLength を ? LengthOfArrayLike (result ) とする。capturesCount をmax (resultLength - 1, 0)とする。matched を ? ToString (? Get (result , "0" )) とする。matchLength をmatched のlengthとする。position を ? ToIntegerOrInfinity (? Get (result , "index" )) とする。position を、0とstringLength の間にclamping したresultに設定する。captures を新しい空のList とする。captureNumber を1とする。captureNumber ≤ capturesCount の間、繰り返すcapture を ? Get (result , ! ToString (𝔽 (captureNumber ))) とする。capture がundefined でないなら、capture を ? ToString (capture ) に設定する。capture をcaptures へappendする。NOTE : captureNumber = 1のとき、preceding stepはfirst elementをcaptures へputする(index 0に)。より一般に、captureNumber th capture(captureNumber th set of capturing parenthesesによってcapturedされたcharacters)はcaptures [captureNumber - 1]にある。captureNumber をcaptureNumber + 1に設定する。namedCaptures を ? Get (result , "groups" ) とする。functionalReplace がtrue なら、replacerArgs を« matched »、captures 、および« 𝔽 (position ), string »のlist-concatenation とする。namedCaptures がundefined でないなら、namedCaptures をreplacerArgs へappendする。replacementValue を ? Call (replaceValue , undefined , replacerArgs ) とする。replacementString を ? ToString (replacementValue ) とする。そうでなければ、namedCaptures がundefined でないなら、namedCaptures を ? ToObject (namedCaptures ) に設定する。replacementString を ? GetSubstitution (matched , string , position , captures , namedCaptures , replaceValue ) とする。 position ≥ nextSourcePosition なら、NOTE : position は通常backwardsにmoveすべきではない。そうなる場合、それはill-behaving RegExp subclass、またはregexp のglobal flagやその他のcharacteristicsをchangeするためのaccess triggered side-effectの使用を示す。そのようなcasesでは、corresponding substitutionはignoredされる。accumulatedResult を、accumulatedResult 、string のnextSourcePosition からposition までのsubstring 、およびreplacementString のstring-concatenation に設定する。nextSourcePosition をposition + matchLength に設定する。nextSourcePosition ≥ stringLength なら、accumulatedResult を返す。accumulatedResult とstring のnextSourcePosition からのsubstring のstring-concatenation を返す。
このmethodの"name" propertyのvalueは"[Symbol.replace]" です。
22.2.6.12 RegExp.prototype [ %Symbol.search% ] ( string )
このmethodは呼び出されたとき、次のstepsを実行します:
regexp をthis valueとする。regexp がObjectでないなら、TypeError 例外をthrowする。string を ? ToString (string ) に設定する。previousLastIndex を ? Get (regexp , "lastIndex" ) とする。previousLastIndex が+0 𝔽 でないなら、? Set (regexp , "lastIndex" , +0 𝔽 , true )を実行する。 result を ? RegExpExec (regexp , string ) とする。currentLastIndex を ? Get (regexp , "lastIndex" ) とする。SameValue (currentLastIndex , previousLastIndex )がfalse なら、? Set (regexp , "lastIndex" , previousLastIndex , true )を実行する。 result がnull なら、-1 𝔽 を返す。? 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を実行します:
regexp をthis valueとする。regexp がObjectでないなら、TypeError 例外をthrowする。regexp が[[OriginalSource]] internal slotを持たないなら、SameValue (regexp , %RegExp.prototype% )がtrue なら、"(?:)" を返す。TypeError 例外をThrowする。Assert : regexp は[[OriginalFlags]] internal slotを持つ。source をregexp .[[OriginalSource]] とする。flags をregexp .[[OriginalFlags]] とする。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:
flags が"v" を含むなら、patternSymbol をPattern [+UnicodeMode, +UnicodeSetsMode] とする。そうでなく、flags が"u" を含むなら、patternSymbol をPattern [+UnicodeMode, ~UnicodeSetsMode] とする。 そうでなければ、patternSymbol をPattern [~UnicodeMode, ~UnicodeSetsMode] とする。 escapedPattern を、UTF-16 encoded Unicode code points(6.1.4 )としてinterpretedされたpattern にequivalentなpatternSymbol のformのStringとする。この中では、certain code pointsが以下でdescribedされる通りescapedされます。escapedPattern はpattern とdifferしてもよいしdifferしなくてもよい;しかし、escapedPattern をpatternSymbol として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しなければなりません。pattern内にoccurringするcode points /または任意のLineTerminator は、" / " ではなく"/" 、escapedPattern 、"/" 、およびflags のstring-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 を"(?:)" とすることで満たされ得ます。 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" , "" ]
limit がundefined でない場合、output arrayはlimit elements以下を含むようにtruncatedされます。
このmethodは呼び出されたとき、次のstepsを実行します:
regexp をthis valueとする。regexp がObjectでないなら、TypeError 例外をthrowする。string を ? ToString (string ) に設定する。speciesCtor を ? SpeciesConstructor (regexp , %RegExp% ) とする。flags を ? ToString (? Get (regexp , "flags" )) とする。flags が"u" を含む、またはflags が"v" を含むなら、unicodeMatching をtrue とする。そうでなければ、unicodeMatching をfalse とする。 flags が"y" を含むなら、newFlags をflags とする。そうでなければ、newFlags をflags と"y" のstring-concatenation とする。 splitter を ? Construct (speciesCtor , « regexp , newFlags ») とする。array を ! ArrayCreate (0) とする。lengthA を0とする。limit がundefined なら、lim を232 - 1とする;そうでなければ、lim をℝ (? ToUint32 (limit ))とする。lim = 0なら、array を返す。string がempty Stringなら、matchResult を ? RegExpExec (splitter , string ) とする。matchResult がnull でないなら、array を返す。! CreateDataPropertyOrThrow (array , "0" , string )を実行する。 array を返す。size をstring のlengthとする。lastMatchEnd を0とする。searchIndex をlastMatchEnd とする。searchIndex < size の間、繰り返す? Set (splitter , "lastIndex" , 𝔽 (searchIndex ), true )を実行する。 matchResult を ? RegExpExec (splitter , string ) とする。matchResult がnull なら、searchIndex をAdvanceStringIndex (string , searchIndex , unicodeMatching )に設定する。そうでなければ、matchEnd をℝ (? ToLength (? Get (splitter , "lastIndex" )))とする。matchEnd をmin (matchEnd , size )に設定する。matchEnd = lastMatchEnd なら、searchIndex をAdvanceStringIndex (string , searchIndex , unicodeMatching )に設定する。そうでなければ、substring をstring のlastMatchEnd からsearchIndex までのsubstring とする。! CreateDataPropertyOrThrow (array , ! ToString (𝔽 (lengthA )), substring )を実行する。 lengthA をlengthA + 1に設定する。lengthA = lim なら、array を返す。lastMatchEnd をmatchEnd に設定する。numberOfCaptures を ? LengthOfArrayLike (matchResult ) とする。numberOfCaptures をmax (numberOfCaptures - 1, 0)に設定する。captureIndex を1とする。captureIndex ≤ numberOfCaptures の間、繰り返すnextCapture を ? Get (matchResult , ! ToString (𝔽 (captureIndex ))) とする。! CreateDataPropertyOrThrow (array , ! ToString (𝔽 (lengthA )), nextCapture )を実行する。 captureIndex をcaptureIndex + 1に設定する。lengthA をlengthA + 1に設定する。lengthA = lim なら、array を返す。searchIndex をlastMatchEnd に設定する。 substring をstring のlastMatchEnd からsize までのsubstring とする。! CreateDataPropertyOrThrow (array , ! ToString (𝔽 (lengthA )), substring )を実行する。 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を実行します:
regexp をthis valueとする。codeUnit をcode unit 0x0079 (LATIN SMALL LETTER Y)とする。? RegExpHasFlag (regexp , codeUnit )を返す。
22.2.6.16 RegExp.prototype.test ( string )
このmethodは呼び出されたとき、次のstepsを実行します:
regexp をthis valueとする。regexp がObjectでないなら、TypeError 例外をthrowする。string を ? ToString (string ) に設定する。match を ? RegExpExec (regexp , string ) とする。match がnull なら、false を返す。true を返す。
22.2.6.17 RegExp.prototype.toString ( )
regexp をthis valueとする。regexp がObjectでないなら、TypeError 例外をthrowする。pattern を ? ToString (? Get (regexp , "source" )) とする。flags を ? ToString (? Get (regexp , "flags" )) とする。result を"/" 、pattern 、"/" 、およびflags のstring-concatenation とする。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を実行します:
regexp をthis valueとする。codeUnit をcode unit 0x0075 (LATIN SMALL LETTER U)とする。? RegExpHasFlag (regexp , codeUnit )を返す。
22.2.6.19 get RegExp.prototype.unicodeSets
RegExp.prototype.unicodeSetsは、set accessor functionがundefined であるaccessor property です。そのget accessor functionは呼び出されたとき、次のstepsを実行します:
regexp をthis valueとする。codeUnit をcode unit 0x0076 (LATIN SMALL LETTER V)とする。? 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:
exec を ? Get (regexp , "exec" ) とする。IsCallable (exec )がtrue なら、result を ? Call (exec , regexp , « string ») とする。result がObjectでなく、かつresult がnull でないなら、TypeError 例外をthrowする。result を返す。? RequireInternalSlot (regexp , [[RegExpMatcher]] )を実行する。 ? 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:
length をstring のlengthとする。lastIndex をℝ (? ToLength (! Get (regexp , "lastIndex" )))とする。flags をregexp .[[OriginalFlags]] とする。flags が"g" を含むなら、global をtrue とする;そうでなければ、global をfalse とする。flags が"y" を含むなら、sticky をtrue とする;そうでなければ、sticky をfalse とする。flags が"d" を含むなら、hasIndices をtrue とする;そうでなければ、hasIndices をfalse とする。global がfalse であり、かつsticky がfalse なら、lastIndex を0に設定する。matcher をregexp .[[RegExpMatcher]] とする。flags が"u" を含む、またはflags が"v" を含むなら、fullUnicode をtrue とする;そうでなければ、fullUnicode をfalse とする。matchSucceeded をfalse とする。fullUnicode がtrue なら、input をStringToCodePoints (string )とする;そうでなければ、input を、そのelementsがstring のelementsであるcode unitsであるList とする。NOTE : input の各elementはcharacterであるとconsiderされる。matchSucceeded がfalse である間、繰り返すlastIndex > length なら、global がtrue またはsticky がtrue なら、? Set (regexp , "lastIndex" , +0 𝔽 , true )を実行する。 null を返す。inputIndex を、string のelement lastIndex からobtainedされたcharacterのinput 内のindexとする。result をmatcher (input , inputIndex )とする。result がfailure なら、sticky がtrue なら、? Set (regexp , "lastIndex" , +0 𝔽 , true )を実行する。 null を返す。lastIndex をAdvanceStringIndex (string , lastIndex , fullUnicode )に設定する。そうでなければ、Assert : result はMatchState である。matchSucceeded をtrue に設定する。 endIndex をresult .[[EndIndex]] とする。fullUnicode がtrue なら、endIndex をGetStringIndex (string , endIndex )に設定する。global がtrue またはsticky がtrue なら、? Set (regexp , "lastIndex" , 𝔽 (endIndex ), true )を実行する。 capturingGroupsCount をresult .[[Captures]] 内のelementsの数とする。Assert : capturingGroupsCount = regexp .[[RegExpRecord]] .[[CapturingGroupsCount]] である。Assert : capturingGroupsCount < 232 - 1である。array を ! ArrayCreate (capturingGroupsCount + 1) とする。Assert : array の"length" propertyのmathematical value はcapturingGroupsCount + 1である。! CreateDataPropertyOrThrow (array , "index" , 𝔽 (lastIndex ))を実行する。 ! CreateDataPropertyOrThrow (array , "input" , string )を実行する。 match をMatch Record { [[StartIndex]] : lastIndex , [[EndIndex]] : endIndex }とする。indices を新しい空のList とする。groupNames を新しい空のList とする。match をindices へappendする。matchedSubstring をGetMatchString (string , match )とする。! CreateDataPropertyOrThrow (array , "0" , matchedSubstring )を実行する。 regexp が任意のGroupName を含むなら、groups をOrdinaryObjectCreate (null )とする。hasGroups をtrue とする。そうでなければ、groups をundefined とする。hasGroups をfalse とする。 ! CreateDataPropertyOrThrow (array , "groups" , groups )を実行する。 matchedGroupNames を新しい空のList とする。1 ≤ i ≤ capturingGroupsCount である各integer i について、ascending orderで、以下を行うcapture をresult .[[Captures]] のi th elementとする。capture がundefined なら、capturedValue をundefined とする。undefined をindices へappendする。そうでなければ、captureStart をcapture .[[StartIndex]] とする。captureEnd をcapture .[[EndIndex]] とする。fullUnicode がtrue なら、captureStart をGetStringIndex (string , captureStart )に設定する。captureEnd をGetStringIndex (string , captureEnd )に設定する。captureRecord をMatch Record { [[StartIndex]] : captureStart , [[EndIndex]] : captureEnd }とする。capturedValue をGetMatchString (string , captureRecord )とする。captureRecord をindices へappendする。 ! CreateDataPropertyOrThrow (array , ! ToString (𝔽 (i )), capturedValue )を実行する。 regexp のi th captureがGroupName でdefinedされていたなら、groupName をそのGroupName のCapturingGroupName とする。matchedGroupNames がgroupName を含むなら、Assert : capturedValue はundefined である。undefined をgroupNames へappendする。そうでなければ、capturedValue がundefined でないなら、groupName をmatchedGroupNames へappendする。NOTE : groupName とnamedされたmultiple groupsが存在する場合、groups はこの時点ですでにgroupName propertyを持っている可能性がある。しかし、groups は、そのpropertiesがすべてwritable data properties であるordinary object であるため、CreateDataPropertyOrThrow へのcallはそれでもsucceedすることがguaranteedされる。! CreateDataPropertyOrThrow (groups , groupName , capturedValue )を実行する。 groupName をgroupNames へappendする。 そうでなければ、undefined をgroupNames へappendする。 hasIndices がtrue なら、indicesArray をMakeMatchIndicesIndexPairArray (string , indices , groupNames , hasGroups )とする。! CreateDataPropertyOrThrow (array , "indices" , indicesArray )を実行する。 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:
Assert : index ≤ 253 - 1である。unicode がfalse なら、index + 1を返す。length をstring のlengthとする。index + 1 ≥ length なら、index + 1を返す。codePoint をCodePointAt (string , index )とする。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:
string がempty Stringなら、0を返す。length をstring のlengthとする。codeUnitCount を0とする。codePointCount を0とする。codeUnitCount < length の間、繰り返すcodePointCount = codePointIndex なら、codeUnitCount を返す。codePoint をCodePointAt (string , codeUnitCount )とする。codeUnitCount をcodeUnitCount + codePoint .[[CodeUnitCount]] に設定する。codePointCount をcodePointCount + 1に設定する。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:
Assert : match .[[StartIndex]] ≤ match .[[EndIndex]] ≤ string のlengthである。string のmatch .[[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:
Assert : match .[[StartIndex]] ≤ match .[[EndIndex]] ≤ string のlengthである。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:
n をindices 内のelementsの数とする。Assert : n < 232 - 1である。Assert : groupNames はn - 1個のelementsを持つ。NOTE : groupNames List はindices [1]からstartingしてindices List とalignedされたelementsを含む。array を ! ArrayCreate (n ) とする。hasGroups がtrue なら、groups をOrdinaryObjectCreate (null )とする。そうでなければ、groups をundefined とする。 ! CreateDataPropertyOrThrow (array , "groups" , groups )を実行する。 0 ≤ i < n である各integer i について、ascending orderで、以下を行うmatchIndices をindices [i ]とする。matchIndices がundefined でないなら、matchIndexPair をGetMatchIndexPair (string , matchIndices )とする。そうでなければ、matchIndexPair をundefined とする。 ! CreateDataPropertyOrThrow (array , ! ToString (𝔽 (i )), matchIndexPair )を実行する。 i > 0なら、name をgroupNames [i - 1]とする。name がundefined でないなら、Assert : groups はundefined でない。NOTE : name とnamedされたmultiple groupsが存在する場合、groups はこの時点ですでにname propertyを持っている可能性がある。しかし、groups は、そのpropertiesがすべてwritable data properties であるordinary object であるため、CreateDataPropertyOrThrow へのcallはそれでもsucceedすることがguaranteedされる。! CreateDataPropertyOrThrow (groups , name , matchIndexPair )を実行する。 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のPattern のAbstract Closure representationです。
Note
ECMAScript 2015より前は、RegExp instancesはown data properties "source" 、"global" 、"ignoreCase" 、および"multiline" を持つものとしてspecifiedされていました。現在、それらのpropertiesはRegExp.prototypeのaccessor 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:
iterator をOrdinaryObjectCreate (%RegExpStringIteratorPrototype% , « [[IteratingRegExp]] , [[IteratedString]] , [[Global]] , [[Unicode]] , [[Done]] »)とする。iterator .[[IteratingRegExp]] をregexp に設定する。iterator .[[IteratedString]] をstring に設定する。iterator .[[Global]] をglobal に設定する。iterator .[[Unicode]] をfullUnicode に設定する。iterator .[[Done]] をfalse に設定する。iterator を返す。
22.2.9.2 The %RegExpStringIteratorPrototype% Object
%RegExpStringIteratorPrototype% objectは:
22.2.9.2.1 %RegExpStringIteratorPrototype%.next ( )
iteratorObj をthis valueとする。iteratorObj がObjectでないなら、TypeError 例外をthrowする。iteratorObj がRegExp String Iterator Object Instanceのすべてのinternal slotsを持たないなら(22.2.9.3 を参照)、TypeError 例外をthrowする。iteratorObj .[[Done]] がtrue なら、CreateIteratorResultObject (undefined , true )を返す。regexp をiteratorObj .[[IteratingRegExp]] とする。string をiteratorObj .[[IteratedString]] とする。global をiteratorObj .[[Global]] とする。fullUnicode をiteratorObj .[[Unicode]] とする。match を ? RegExpExec (regexp , string ) とする。match がnull なら、iteratorObj .[[Done]] をtrue に設定する。CreateIteratorResultObject (undefined , true )を返す。global がfalse なら、iteratorObj .[[Done]] をtrue に設定する。CreateIteratorResultObject (match , false )を返す。matchString を ? ToString (? Get (match , "0" )) とする。matchString がempty Stringなら、thisIndex をℝ (? ToLength (? Get (regexp , "lastIndex" )))とする。nextIndex をAdvanceStringIndex (string , thisIndex , fullUnicode )とする。? Set (regexp , "lastIndex" , 𝔽 (nextIndex ), true )を実行する。 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を実行します:
NewTargetがundefined なら、newTarget をactive function object とする;そうでなければ、newTarget をNewTargetとする。 proto を ? GetPrototypeFromConstructor (newTarget , "%Array.prototype%" ) とする。numberOfArgs をvalues 内のelementsの数とする。numberOfArgs = 0なら、! ArrayCreate (0, proto )を返す。numberOfArgs = 1なら、length をvalues [0]とする。array を ! ArrayCreate (0, proto ) とする。length がNumberでないなら、! CreateDataPropertyOrThrow (array , "0" , length )を実行する。 intLength を1 𝔽 とする。そうでなければ、intLength を ! ToUint32 (length ) とする。SameValueZero (intLength , length )がfalse なら、RangeError 例外をthrowする。 ! Set (array , "length" , intLength , true )を実行する。 array を返す。Assert : numberOfArgs ≥ 2である。array を ? ArrayCreate (numberOfArgs , proto ) とする。k を0とする。k < numberOfArgs の間、繰り返すpropertyKey を ! ToString (𝔽 (k )) とする。itemK をvalues [k ]とする。! CreateDataPropertyOrThrow (array , propertyKey , itemK )を実行する。 k をk + 1に設定する。Assert : array の"length" propertyのmathematical value はnumberOfArgs である。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を実行します:
ctor をthis valueとする。mapper がundefined なら、mapping をfalse とする。そうでなければ、IsCallable (mapper )がfalse なら、TypeError 例外をthrowする。mapping をtrue とする。 usingIterator を ? GetMethod (items , %Symbol.iterator% ) とする。usingIterator がundefined でないなら、IsConstructor (ctor )がtrue なら、array を ? Construct (ctor ) とする。そうでなければ、array を ! ArrayCreate (0) とする。 iteratorRecord を ? GetIteratorFromMethod (items , usingIterator ) とする。k を0とする。繰り返す:k ≥ 253 - 1なら、error をThrowCompletion (a newly created TypeError object)とする。? IteratorClose (iteratorRecord , error )を返す。 propertyKey を ! ToString (𝔽 (k )) とする。next を ? IteratorStepValue (iteratorRecord ) とする。next がdone なら、? Set (array , "length" , 𝔽 (k ), true )を実行する。 array を返す。mapping がtrue なら、mappedValue をCompletion (Call (mapper , thisArg , « next , 𝔽 (k ) »))とする。IfAbruptCloseIterator (mappedValue , iteratorRecord ).そうでなければ、mappedValue をnext とする。 defineStatus をCompletion (CreateDataPropertyOrThrow (array , propertyKey , mappedValue ))とする。IfAbruptCloseIterator (defineStatus , iteratorRecord ).k をk + 1に設定する。 NOTE : items はiterable でないため、array-like object であるとassumeする。arrayLike を ! ToObject (items ) とする。length を ? LengthOfArrayLike (arrayLike ) とする。IsConstructor (ctor )がtrue なら、array を ? Construct (ctor , « 𝔽 (length ) ») とする。そうでなければ、array を ? ArrayCreate (length ) とする。 k を0とする。k < length の間、繰り返すpropertyKey を ! ToString (𝔽 (k )) とする。kValue を ? Get (arrayLike , propertyKey ) とする。mapping がtrue なら、mappedValue を ? Call (mapper , thisArg , « kValue , 𝔽 (k ) ») とする。そうでなければ、mappedValue をkValue とする。 ? CreateDataPropertyOrThrow (array , propertyKey , mappedValue )を実行する。 k をk + 1に設定する。? Set (array , "length" , 𝔽 (length ), true )を実行する。 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を実行します:
ctor をthis valueとする。mapping をfalse とする。mapper がundefined でないなら、IsCallable (mapper )がfalse なら、TypeError 例外をthrowする。mapping をtrue に設定する。iteratorRecord をundefined とする。usingAsyncIterator を ? GetMethod (items , %Symbol.asyncIterator% ) とする。usingAsyncIterator がundefined なら、usingSyncIterator を ? GetMethod (items , %Symbol.iterator% ) とする。usingSyncIterator がundefined でないなら、iteratorRecord をCreateAsyncFromSyncIterator (? GetIteratorFromMethod (items , usingSyncIterator ))に設定する。そうでなければ、iteratorRecord を ? GetIteratorFromMethod (items , usingAsyncIterator ) に設定する。 iteratorRecord がundefined でないなら、IsConstructor (ctor )がtrue なら、array を ? Construct (ctor ) とする。そうでなければ、array を ! ArrayCreate (0) とする。 k を0とする。繰り返す:k ≥ 253 - 1なら、error をThrowCompletion (a newly created TypeError object)とする。? AsyncIteratorClose (iteratorRecord , error )を返す。 propertyKey を ! ToString (𝔽 (k )) とする。nextResult を ? Call (iteratorRecord .[[NextMethod]] , iteratorRecord .[[Iterator]] ) とする。nextResult を ? Await (nextResult ) に設定する。nextResult がObjectでないなら、TypeError 例外をthrowする。done を ? IteratorComplete (nextResult ) とする。done がtrue なら、? Set (array , "length" , 𝔽 (k ), true )を実行する。 array を返す。nextValue を ? IteratorValue (nextResult ) とする。mapping がtrue なら、mappedValue をCompletion (Call (mapper , thisArg , « nextValue , 𝔽 (k ) »))とする。IfAbruptCloseAsyncIterator (mappedValue , iteratorRecord ).mappedValue をCompletion (Await (mappedValue ))に設定する。IfAbruptCloseAsyncIterator (mappedValue , iteratorRecord ).そうでなければ、mappedValue をnextValue とする。 defineStatus をCompletion (CreateDataPropertyOrThrow (array , propertyKey , mappedValue ))とする。IfAbruptCloseAsyncIterator (defineStatus , iteratorRecord ).k をk + 1に設定する。 そうでなければ、NOTE : items はasync iterable でもiterable でもないため、array-like object であるとassumeする。arrayLike を ! ToObject (items ) とする。length を ? LengthOfArrayLike (arrayLike ) とする。IsConstructor (ctor )がtrue なら、array を ? Construct (ctor , « 𝔽 (length ) ») とする。そうでなければ、array を ? ArrayCreate (length ) とする。 k を0とする。k < length の間、繰り返すpropertyKey を ! ToString (𝔽 (k )) とする。kValue を ? Get (arrayLike , propertyKey ) とする。kValue を ? Await (kValue ) に設定する。mapping がtrue なら、mappedValue を ? Call (mapper , thisArg , « kValue , 𝔽 (k ) ») とする。mappedValue を ? Await (mappedValue ) に設定する。そうでなければ、mappedValue をkValue とする。 ? CreateDataPropertyOrThrow (array , propertyKey , mappedValue )を実行する。 k をk + 1に設定する。? Set (array , "length" , 𝔽 (length ), true )を実行する。 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を実行します:
? IsArray (arg )を返す。
23.1.2.4 Array.of ( ...items )
このmethodは呼び出されたとき、次のstepsを実行します:
length をitems 内のelementsの数とする。lengthNumber を𝔽 (length )とする。ctor をthis valueとする。IsConstructor (ctor )がtrue なら、array を ? Construct (ctor , « lengthNumber ») とする。そうでなければ、array を ? ArrayCreate (length ) とする。 k を0とする。k < length の間、繰り返すkValue をitems [k ]とする。propertyKey を ! ToString (𝔽 (k )) とする。? CreateDataPropertyOrThrow (array , propertyKey , kValue )を実行する。 k をk + 1に設定する。? Set (array , "length" , lengthNumber , true )を実行する。 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を実行します:
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 )
obj を ? ToObject (this value) とする。length を ? LengthOfArrayLike (obj ) とする。relativeIndex を ? ToIntegerOrInfinity (index ) とする。relativeIndex ≥ 0なら、k をrelativeIndex とする。そうでなければ、k をlength + relativeIndex とする。 k < 0またはk ≥ length なら、undefined を返す。? Get (obj , ! ToString (𝔽 (k )))を返す。
23.1.3.2 Array.prototype.concat ( ...items )
このmethodは、objectのarray elementsに各argumentのarray elementsがfollowしたものを含むarrayを返します。
これは呼び出されたとき、次のstepsを実行します:
obj を ? ToObject (this value) とする。array を ? ArraySpeciesCreate (obj , 0) とする。nextIndex を0とする。obj をitems の先頭にprependする。items の各要素item について、以下を行うspreadable を ? IsConcatSpreadable (item ) とする。spreadable がtrue なら、length を ? LengthOfArrayLike (item ) とする。nextIndex + length > 253 - 1なら、TypeError 例外をthrowする。sourceIndex を0とする。sourceIndex < length の間、繰り返すpropertyKey を ! ToString (𝔽 (sourceIndex )) とする。exists を ? HasProperty (item , propertyKey ) とする。exists がtrue なら、subElement を ? Get (item , propertyKey ) とする。? CreateDataPropertyOrThrow (array , ! ToString (𝔽 (nextIndex )), subElement )を実行する。 nextIndex をnextIndex + 1に設定する。sourceIndex をsourceIndex + 1に設定する。そうでなければ、NOTE : item はspreadされるのではなくsingle itemとしてaddedされる。nextIndex ≥ 253 - 1なら、TypeError 例外をthrowする。? CreateDataPropertyOrThrow (array , ! ToString (𝔽 (nextIndex )), item )を実行する。 nextIndex をnextIndex + 1に設定する。 ? Set (array , "length" , 𝔽 (nextIndex ), true )を実行する。 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:
obj がObjectでないなら、false を返す。spreadable を ? Get (obj , %Symbol.isConcatSpreadable% ) とする。spreadable がundefined でないなら、ToBoolean (spreadable )を返す。? 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を実行します:
obj を ? ToObject (this value) とする。length を ? LengthOfArrayLike (obj ) とする。relativeTarget を ? ToIntegerOrInfinity (target ) とする。relativeTarget = -∞なら、to を0とする。そうでなく、relativeTarget < 0なら、to をmax (length + relativeTarget , 0)とする。 そうでなければ、to をmin (relativeTarget , length )とする。 relativeStart を ? ToIntegerOrInfinity (start ) とする。relativeStart = -∞なら、from を0とする。そうでなく、relativeStart < 0なら、from をmax (length + relativeStart , 0)とする。 そうでなければ、from をmin (relativeStart , length )とする。 end がundefined なら、relativeEnd をlength とする;そうでなければ、relativeEnd を ? ToIntegerOrInfinity (end ) とする。relativeEnd = -∞なら、final を0とする。そうでなく、relativeEnd < 0なら、final をmax (length + relativeEnd , 0)とする。 そうでなければ、final をmin (relativeEnd , length )とする。 count をmin (final - from , length - to )とする。from < to かつto < from + count なら、direction を-1とする。from をfrom + count - 1に設定する。to をto + count - 1に設定する。そうでなければ、direction を1とする。 count > 0の間、繰り返すfromKey を ! ToString (𝔽 (from )) とする。toKey を ! ToString (𝔽 (to )) とする。fromPresent を ? HasProperty (obj , fromKey ) とする。fromPresent がtrue なら、fromValue を ? Get (obj , fromKey ) とする。? Set (obj , toKey , fromValue , true )を実行する。 そうでなければ、Assert : fromPresent はfalse である。? DeletePropertyOrThrow (obj , toKey )を実行する。 from をfrom + direction に設定する。to をto + direction に設定する。count をcount - 1に設定する。obj を返す。
Note 3
このmethodは意図的にgenericです;そのthis valueがArrayであることをrequireしません。したがって、methodとして使用するために他の種類のobjectsへtransferできます。
23.1.3.5 Array.prototype.entries ( )
このmethodは呼び出されたとき、次のstepsを実行します:
obj を ? ToObject (this value) とする。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は、callback がfalse を返すoneをfindするまで、array内にpresentな各elementについてascending orderでcallback をonce呼び出します。そのようなelementが見つかると、everyはimmediately false を返します。そうでなければ、everyはtrue を返します。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を実行します:
obj を ? ToObject (this value) とする。length を ? LengthOfArrayLike (obj ) とする。IsCallable (callback )がfalse なら、TypeError 例外をthrowする。k を0とする。k < length の間、繰り返すpropertyKey を ! ToString (𝔽 (k )) とする。kPresent を ? HasProperty (obj , propertyKey ) とする。kPresent がtrue なら、kValue を ? Get (obj , propertyKey ) とする。testResult をToBoolean (? Call (callback , thisArg , « kValue , 𝔽 (k ), obj »))とする。testResult がfalse なら、false を返す。k をk + 1に設定する。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を実行します:
obj を ? ToObject (this value) とする。length を ? LengthOfArrayLike (obj ) とする。relativeStart を ? ToIntegerOrInfinity (start ) とする。relativeStart = -∞なら、k を0とする。そうでなく、relativeStart < 0なら、k をmax (length + relativeStart , 0)とする。 そうでなければ、k をmin (relativeStart , length )とする。 end がundefined なら、relativeEnd をlength とする;そうでなければ、relativeEnd を ? ToIntegerOrInfinity (end ) とする。relativeEnd = -∞なら、final を0とする。そうでなく、relativeEnd < 0なら、final をmax (length + relativeEnd , 0)とする。 そうでなければ、final をmin (relativeEnd , length )とする。 k < final の間、繰り返すpropertyKey を ! ToString (𝔽 (k )) とする。? Set (obj , propertyKey , value , true )を実行する。 k をk + 1に設定する。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呼び出し、callback がtrue を返すすべての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を実行します:
obj を ? ToObject (this value) とする。length を ? LengthOfArrayLike (obj ) とする。IsCallable (callback )がfalse なら、TypeError 例外をthrowする。array を ? ArraySpeciesCreate (obj , 0) とする。k を0とする。to を0とする。k < length の間、繰り返すpropertyKey を ! ToString (𝔽 (k )) とする。kPresent を ? HasProperty (obj , propertyKey ) とする。kPresent がtrue なら、kValue を ? Get (obj , propertyKey ) とする。selected をToBoolean (? Call (callback , thisArg , « kValue , 𝔽 (k ), obj »))とする。selected がtrue なら、? CreateDataPropertyOrThrow (array , ! ToString (𝔽 (to )), kValue )を実行する。 to をto + 1に設定する。k をk + 1に設定する。array を返す。
Note 2
このmethodは意図的にgenericです;そのthis valueがArrayであることをrequireしません。したがって、methodとして使用するために他の種類のobjectsへtransferできます。
23.1.3.9 Array.prototype.find ( predicate [ , thisArg ] )
Note 1
このmethodは、predicate がtrue へcoercesされるvalueを返すoneをfindするまで、arrayの各elementについてascending index orderでpredicate をonce呼び出します。そのようなelementが見つかると、findはimmediatelyそのelement valueを返します。そうでなければ、findはundefined を返します。
additional informationについてはFindViaPredicate を参照してください。
このmethodは呼び出されたとき、次のstepsを実行します:
obj を ? ToObject (this value) とする。length を ? LengthOfArrayLike (obj ) とする。findRecord を ? FindViaPredicate (obj , length , ascending , predicate , thisArg ) とする。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は、predicate がtrue へcoercesされるvalueを返すoneをfindするまで、arrayの各elementについてascending index orderでpredicate をonce呼び出します。そのようなelementが見つかると、findIndexはimmediatelyそのelement valueのindexを返します。そうでなければ、findIndexは-1を返します。
additional informationについてはFindViaPredicate を参照してください。
このmethodは呼び出されたとき、次のstepsを実行します:
obj を ? ToObject (this value) とする。length を ? LengthOfArrayLike (obj ) とする。findRecord を ? FindViaPredicate (obj , length , ascending , predicate , thisArg ) とする。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は、predicate がtrue へcoercesされるvalueを返すoneをfindするまで、arrayの各elementについてdescending index orderでpredicate をonce呼び出します。そのようなelementが見つかると、findLastはimmediatelyそのelement valueを返します。そうでなければ、findLastはundefined を返します。
additional informationについてはFindViaPredicate を参照してください。
このmethodは呼び出されたとき、次のstepsを実行します:
obj を ? ToObject (this value) とする。length を ? LengthOfArrayLike (obj ) とする。findRecord を ? FindViaPredicate (obj , length , descending , predicate , thisArg ) とする。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は、predicate がtrue へcoercesされるvalueを返すoneをfindするまで、arrayの各elementについてdescending index orderでpredicate をonce呼び出します。そのようなelementが見つかると、findLastIndexはimmediatelyそのelement valueのindexを返します。そうでなければ、findLastIndexは-1を返します。
additional informationについてはFindViaPredicate を参照してください。
このmethodは呼び出されたとき、次のstepsを実行します:
obj を ? ToObject (this value) とする。length を ? LengthOfArrayLike (obj ) とする。findRecord を ? FindViaPredicate (obj , length , descending , predicate , thisArg ) とする。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 .
obj はarray-like object またはTypedArray であるべきです。このoperationは、direction によって示される通り、ascending index orderまたはdescending index orderのいずれかで、predicate がtrue へ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:
IsCallable (predicate )がfalse なら、TypeError 例外をthrowする。direction がascending なら、indices を、0(inclusive)からlength (exclusive)までのinterval 内のintegers のList で、ascending orderとする。そうでなければ、indices を、0(inclusive)からlength (exclusive)までのinterval 内のintegers のList で、descending orderとする。 indices の各integer k について、以下を行うpropertyKey を ! ToString (𝔽 (k )) とする。NOTE : obj がTypedArray である場合、以下のGet のinvocationはnormal completion を返す。kValue を ? Get (obj , propertyKey ) とする。testResult を ? Call (predicate , thisArg , « kValue , 𝔽 (k ), obj ») とする。ToBoolean (testResult )がtrue なら、Record { [[Index]] : 𝔽 (k ), [[Value]] : kValue }を返す。Record { [[Index]] : -1 𝔽 , [[Value]] : undefined }を返す。
23.1.3.13 Array.prototype.flat ( [ depth ] )
このmethodは呼び出されたとき、次のstepsを実行します:
obj を ? ToObject (this value) とする。sourceLength を ? LengthOfArrayLike (obj ) とする。depthNumber を1とする。depth がundefined でないなら、depthNumber を ? ToIntegerOrInfinity (depth ) に設定する。depthNumber < 0なら、depthNumber を0に設定する。array を ? ArraySpeciesCreate (obj , 0) とする。? FlattenIntoArray (array , obj , sourceLength , 0, depthNumber )を実行する。 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:
Assert : mapperFunc がpresentなら、IsCallable (mapperFunc )はtrue であり、thisArg はpresentであり、depth は1である。targetIndex をstart とする。sourceIndex を+0 𝔽 とする。ℝ (sourceIndex ) < sourceLength の間、繰り返すpropertyKey を ! ToString (sourceIndex ) とする。exists を ? HasProperty (source , propertyKey ) とする。exists がtrue なら、element を ? Get (source , propertyKey ) とする。mapperFunc がpresentなら、element を ? Call (mapperFunc , thisArg , « element , sourceIndex , source ») に設定する。shouldFlatten をfalse とする。depth > 0なら、shouldFlatten を ? IsArray (element ) に設定する。shouldFlatten がtrue なら、depth = +∞なら、newDepth を+∞とする。そうでなければ、newDepth をdepth - 1とする。 elementLength を ? LengthOfArrayLike (element ) とする。targetIndex を ? FlattenIntoArray (target , element , elementLength , targetIndex , newDepth ) に設定する。そうでなければ、targetIndex ≥ 253 - 1なら、TypeError 例外をthrowする。? CreateDataPropertyOrThrow (target , ! ToString (𝔽 (targetIndex )), element )を実行する。 targetIndex をtargetIndex + 1に設定する。 sourceIndex をsourceIndex + 1 𝔽 に設定する。targetIndex を返す。
23.1.3.14 Array.prototype.flatMap ( mapperFunc [ , thisArg ] )
このmethodは呼び出されたとき、次のstepsを実行します:
obj を ? ToObject (this value) とする。sourceLength を ? LengthOfArrayLike (obj ) とする。IsCallable (mapperFunc )がfalse なら、TypeError 例外をthrowする。array を ? ArraySpeciesCreate (obj , 0) とする。? FlattenIntoArray (array , obj , sourceLength , 0, 1, mapperFunc , thisArg )を実行する。 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を実行します:
obj を ? ToObject (this value) とする。length を ? LengthOfArrayLike (obj ) とする。IsCallable (callback )がfalse なら、TypeError 例外をthrowする。k を0とする。k < length の間、繰り返すpropertyKey を ! ToString (𝔽 (k )) とする。kPresent を ? HasProperty (obj , propertyKey ) とする。kPresent がtrue なら、kValue を ? Get (obj , propertyKey ) とする。? Call (callback , thisArg , « kValue , 𝔽 (k ), obj »)を実行する。 k をk + 1に設定する。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を実行します:
obj を ? ToObject (this value) とする。length を ? LengthOfArrayLike (obj ) とする。length = 0なら、false を返す。startIndex を ? ToIntegerOrInfinity (fromIndex ) とする。Assert : fromIndex がundefined なら、startIndex は0である。startIndex = +∞なら、false を返す。startIndex = -∞なら、startIndex を0に設定する。startIndex ≥ 0なら、k をstartIndex とする。そうでなければ、k をlength + startIndex とする。k < 0なら、k を0に設定する。 k < length の間、繰り返すelementK を ? Get (obj , ! ToString (𝔽 (k ))) とする。SameValueZero (searchElement , elementK )がtrue なら、true を返す。k をk + 1に設定する。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を実行します:
obj を ? ToObject (this value) とする。length を ? LengthOfArrayLike (obj ) とする。length = 0なら、-1 𝔽 を返す。startIndex を ? ToIntegerOrInfinity (fromIndex ) とする。Assert : fromIndex がundefined なら、startIndex は0である。startIndex = +∞なら、-1 𝔽 を返す。startIndex = -∞なら、startIndex を0に設定する。startIndex ≥ 0なら、k をstartIndex とする。そうでなければ、k をlength + startIndex とする。k < 0なら、k を0に設定する。 k < length の間、繰り返すpropertyKey を ! ToString (𝔽 (k )) とする。kPresent を ? HasProperty (obj , propertyKey ) とする。kPresent がtrue なら、elementK を ? Get (obj , propertyKey ) とする。IsStrictlyEqual (searchElement , elementK )がtrue なら、𝔽 (k )を返す。k をk + 1に設定する。-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を実行します:
obj を ? ToObject (this value) とする。length を ? LengthOfArrayLike (obj ) とする。separator がundefined なら、sep を"," とする。そうでなければ、sep を ? ToString (separator ) とする。 result をempty Stringとする。k を0とする。k < length の間、繰り返すk > 0なら、result をresult とsep のstring-concatenation に設定する。element を ? Get (obj , ! ToString (𝔽 (k ))) とする。element がundefined でもnull でもないなら、elementString を ? ToString (element ) とする。result をresult とelementString のstring-concatenation に設定する。k をk + 1に設定する。result を返す。
Note
このmethodは意図的にgenericです;そのthis valueがArrayであることをrequireしません。したがって、methodとして使用するために他の種類のobjectsへtransferできます。
23.1.3.19 Array.prototype.keys ( )
このmethodは呼び出されたとき、次のstepsを実行します:
obj を ? ToObject (this value) とする。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を実行します:
obj を ? ToObject (this value) とする。length を ? LengthOfArrayLike (obj ) とする。length = 0なら、-1 𝔽 を返す。fromIndex がpresentなら、startIndex を ? ToIntegerOrInfinity (fromIndex ) とする;そうでなければ、startIndex をlength - 1とする。startIndex = -∞なら、-1 𝔽 を返す。startIndex ≥ 0なら、k をmin (startIndex , length - 1)とする。そうでなければ、k をlength + startIndex とする。 k ≥ 0の間、繰り返すpropertyKey を ! ToString (𝔽 (k )) とする。kPresent を ? HasProperty (obj , propertyKey ) とする。kPresent がtrue なら、elementK を ? Get (obj , propertyKey ) とする。IsStrictlyEqual (searchElement , elementK )がtrue なら、𝔽 (k )を返す。k をk - 1に設定する。-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を実行します:
obj を ? ToObject (this value) とする。length を ? LengthOfArrayLike (obj ) とする。IsCallable (callback )がfalse なら、TypeError 例外をthrowする。array を ? ArraySpeciesCreate (obj , length ) とする。k を0とする。k < length の間、繰り返すpropertyKey を ! ToString (𝔽 (k )) とする。kPresent を ? HasProperty (obj , propertyKey ) とする。kPresent がtrue なら、kValue を ? Get (obj , propertyKey ) とする。mappedValue を ? Call (callback , thisArg , « kValue , 𝔽 (k ), obj ») とする。? CreateDataPropertyOrThrow (array , propertyKey , mappedValue )を実行する。 k をk + 1に設定する。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を実行します:
obj を ? ToObject (this value) とする。length を ? LengthOfArrayLike (obj ) とする。length = 0なら、? Set (obj , "length" , +0 𝔽 , true )を実行する。 undefined を返す。Assert : length > 0である。newLength を𝔽 (length - 1)とする。index を ! ToString (newLength ) とする。element を ? Get (obj , index ) とする。? DeletePropertyOrThrow (obj , index )を実行する。 ? Set (obj , "length" , newLength , true )を実行する。 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を実行します:
obj を ? ToObject (this value) とする。length を ? LengthOfArrayLike (obj ) とする。argCount をitems 内のelementsの数とする。length + argCount > 253 - 1なら、TypeError 例外をthrowする。items の各要素item について、以下を行う? Set (obj , ! ToString (𝔽 (length )), item , true )を実行する。 length をlength + 1に設定する。? Set (obj , "length" , 𝔽 (length ), true )を実行する。 𝔽 (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で呼び出されます:previousValue (callback へのprevious callからのvalue)、currentValue (current elementのvalue)、currentIndex 、およびtraversedされているobjectです。callbackがfirst time呼び出されるとき、previousValue とcurrentValue はtwo valuesのいずれかになり得ます。reduceへのcallでinitialValue がsuppliedされた場合、previousValue はinitialValue になり、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を実行します:
obj を ? ToObject (this value) とする。length を ? LengthOfArrayLike (obj ) とする。IsCallable (callback )がfalse なら、TypeError 例外をthrowする。length = 0であり、かつinitialValue がpresentでないなら、TypeError 例外をthrowする。k を0とする。accumulator をundefined とする。initialValue がpresentなら、accumulator をinitialValue に設定する。そうでなければ、kPresent をfalse とする。kPresent がfalse であり、かつk < length である間、繰り返すpropertyKey を ! ToString (𝔽 (k )) とする。kPresent を ? HasProperty (obj , propertyKey ) に設定する。kPresent がtrue なら、accumulator を ? Get (obj , propertyKey ) に設定する。k をk + 1に設定する。kPresent がfalse なら、TypeError 例外をthrowする。 k < length の間、繰り返すpropertyKey を ! ToString (𝔽 (k )) とする。kPresent を ? HasProperty (obj , propertyKey ) とする。kPresent がtrue なら、kValue を ? Get (obj , propertyKey ) とする。accumulator を ? Call (callback , undefined , « accumulator , kValue , 𝔽 (k ), obj ») に設定する。k をk + 1に設定する。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で呼び出されます:previousValue (callback へのprevious callからのvalue)、currentValue (current elementのvalue)、currentIndex 、およびtraversedされているobjectです。functionがfirst time呼び出されるとき、previousValue とcurrentValue はtwo valuesのいずれかになり得ます。reduceRightへのcallでinitialValue がsuppliedされた場合、previousValue はinitialValue になり、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を実行します:
obj を ? ToObject (this value) とする。length を ? LengthOfArrayLike (obj ) とする。IsCallable (callback )がfalse なら、TypeError 例外をthrowする。length = 0であり、かつinitialValue がpresentでないなら、TypeError 例外をthrowする。k をlength - 1とする。accumulator をundefined とする。initialValue がpresentなら、accumulator をinitialValue に設定する。そうでなければ、kPresent をfalse とする。kPresent がfalse であり、かつk ≥ 0である間、繰り返すpropertyKey を ! ToString (𝔽 (k )) とする。kPresent を ? HasProperty (obj , propertyKey ) に設定する。kPresent がtrue なら、accumulator を ? Get (obj , propertyKey ) に設定する。k をk - 1に設定する。kPresent がfalse なら、TypeError 例外をthrowする。 k ≥ 0の間、繰り返すpropertyKey を ! ToString (𝔽 (k )) とする。kPresent を ? HasProperty (obj , propertyKey ) とする。kPresent がtrue なら、kValue を ? Get (obj , propertyKey ) とする。accumulator を ? Call (callback , undefined , « accumulator , kValue , 𝔽 (k ), obj ») に設定する。k をk - 1に設定する。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を実行します:
obj を ? ToObject (this value) とする。length を ? LengthOfArrayLike (obj ) とする。middle をfloor (length / 2)とする。lower を0とする。lower ≠ middle の間、繰り返すupper をlength - lower - 1とする。upperP を ! ToString (𝔽 (upper )) とする。lowerP を ! ToString (𝔽 (lower )) とする。lowerExists を ? HasProperty (obj , lowerP ) とする。lowerExists がtrue なら、lowerValue を ? Get (obj , lowerP ) とする。upperExists を ? HasProperty (obj , upperP ) とする。upperExists がtrue なら、upperValue を ? Get (obj , upperP ) とする。lowerExists がtrue であり、かつupperExists がtrue なら、? Set (obj , lowerP , upperValue , true )を実行する。 ? Set (obj , upperP , lowerValue , true )を実行する。 そうでなく、lowerExists がfalse であり、かつupperExists がtrue なら、? Set (obj , lowerP , upperValue , true )を実行する。 ? DeletePropertyOrThrow (obj , upperP )を実行する。 そうでなく、lowerExists がtrue であり、かつupperExists がfalse なら、? DeletePropertyOrThrow (obj , lowerP )を実行する。 ? Set (obj , upperP , lowerValue , true )を実行する。 そうでなければ、Assert : lowerExists およびupperExists はともにfalse である。NOTE : actionはrequiredされない。 lower をlower + 1に設定する。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を実行します:
obj を ? ToObject (this value) とする。length を ? LengthOfArrayLike (obj ) とする。length = 0なら、? Set (obj , "length" , +0 𝔽 , true )を実行する。 undefined を返す。first を ? Get (obj , "0" ) とする。k を1とする。k < length の間、繰り返すfrom を ! ToString (𝔽 (k )) とする。to を ! ToString (𝔽 (k - 1)) とする。fromPresent を ? HasProperty (obj , from ) とする。fromPresent がtrue なら、fromValue を ? Get (obj , from ) とする。? Set (obj , to , fromValue , true )を実行する。 そうでなければ、Assert : fromPresent はfalse である。? DeletePropertyOrThrow (obj , to )を実行する。 k をk + 1に設定する。? DeletePropertyOrThrow (obj , ! ToString (𝔽 (length - 1)))を実行する。 ? Set (obj , "length" , 𝔽 (length - 1), true )を実行する。 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を返します(またはend がundefined ならarrayのendまで)。start がnegativeなら、length をarrayのlengthとしてlength + start として扱われます。end がnegativeなら、length をarrayのlengthとしてlength + end として扱われます。
これは呼び出されたとき、次のstepsを実行します:
obj を ? ToObject (this value) とする。length を ? LengthOfArrayLike (obj ) とする。relativeStart を ? ToIntegerOrInfinity (start ) とする。relativeStart = -∞なら、k を0とする。そうでなく、relativeStart < 0なら、k をmax (length + relativeStart , 0)とする。 そうでなければ、k をmin (relativeStart , length )とする。 end がundefined なら、relativeEnd をlength とする;そうでなければ、relativeEnd を ? ToIntegerOrInfinity (end ) とする。relativeEnd = -∞なら、final を0とする。そうでなく、relativeEnd < 0なら、final をmax (length + relativeEnd , 0)とする。 そうでなければ、final をmin (relativeEnd , length )とする。 count をmax (final - k , 0)とする。array を ? ArraySpeciesCreate (obj , count ) とする。resultIndex を0とする。k < final の間、繰り返すpropertyKey を ! ToString (𝔽 (k )) とする。kPresent を ? HasProperty (obj , propertyKey ) とする。kPresent がtrue なら、kValue を ? Get (obj , propertyKey ) とする。? CreateDataPropertyOrThrow (array , ! ToString (𝔽 (resultIndex )), kValue )を実行する。 k をk + 1に設定する。resultIndex をresultIndex + 1に設定する。? Set (array , "length" , 𝔽 (resultIndex ), true )を実行する。 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は、callback がtrue を返すoneをfindするまで、array内にpresentな各elementについてascending orderでcallback をonce呼び出します。そのようなelementが見つかると、someはimmediately true を返します。そうでなければ、someはfalse を返します。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を実行します:
obj を ? ToObject (this value) とする。length を ? LengthOfArrayLike (obj ) とする。IsCallable (callback )がfalse なら、TypeError 例外をthrowする。k を0とする。k < length の間、繰り返すpropertyKey を ! ToString (𝔽 (k )) とする。kPresent を ? HasProperty (obj , propertyKey ) とする。kPresent がtrue なら、kValue を ? Get (obj , propertyKey ) とする。testResult をToBoolean (? Call (callback , thisArg , « kValue , 𝔽 (k ), obj »))とする。testResult がtrue なら、true を返す。k をk + 1に設定する。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します。comparator がundefined でないなら、それはtwo arguments x およびy をacceptし、x < y ならnegative Number、x > y ならpositive Number、そうでなければzeroを返すfunctionであるべきです。
これは呼び出されたとき、次のstepsを実行します:
comparator がundefined でなく、かつIsCallable (comparator )がfalse なら、TypeError 例外をthrowする。obj を ? ToObject (this value) とする。length を ? LengthOfArrayLike (obj ) とする。sortCompare を、comparator をcaptureし、calledされたときに次のstepsを実行する、parameters (x , y )を持つnew Abstract Closure とする:? CompareArrayElements (x , y , comparator )を返す。 sortedList を ? SortIndexedProperties (obj , length , sortCompare , skip-holes ) とする。itemCount をsortedList 内のelementsの数とする。j を0とする。j < itemCount の間、繰り返す? Set (obj , ! ToString (𝔽 (j )), sortedList [j ], true )を実行する。 j をj + 1に設定する。NOTE : step 5 のSortIndexedProperties へのcallはskip-holes を使用する。remaining indicesは、sortからdetectedおよびexcludedされたholesの数をpreserveするためにdeletedされる。j < length の間、繰り返す? DeletePropertyOrThrow (obj , ! ToString (𝔽 (j )))を実行する。 j をj + 1に設定する。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は、sortCompare がconsistent 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:
items を新しい空のList とする。k を0とする。k < length の間、繰り返すpropertyKey を ! ToString (𝔽 (k )) とする。holes がskip-holes なら、kRead を ? HasProperty (obj , propertyKey ) とする。そうでなければ、Assert : holes はread-through-holes である。kRead をtrue とする。 kRead がtrue なら、kValue を ? Get (obj , propertyKey ) とする。kValue をitems へappendする。k をk + 1に設定する。implementation-defined sequence of calls to sortCompare を使用してitems をSortする。そのようなcallのいずれかがabrupt completion を返す場合、sortCompare へのそれ以上のcallsをperformする前にstopし、そのCompletion Record を返す。items を返す。
sort order は、上記algorithmのstep 4 のcompletion後のitems のorderingです。sortCompare がitems のelementsに対するconsistent comparator でない場合、sort order はimplementation-defined です。SortIndexedPropertiesがArray.prototype.sort またはArray.prototype.toSorted によってinvokedされる場合、comparator がundefined であり、かつsortCompare へのargumentとしてpassedされたany specific valueへのToString のすべてのapplicationsがsame resultをproduceしない場合にも、sort order はimplementation-defined です。
sort order がimplementation-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 a 、b 、および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であり、v はNaN ではありません。これは、given pair of a およびb について、a <C b 、a =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:
x がundefined であり、かつy がundefined なら、+0 𝔽 を返す。x がundefined なら、1 𝔽 を返す。y がundefined なら、-1 𝔽 を返す。comparator がundefined でないなら、result を ? ToNumber (? Call (comparator , undefined , « x , y »)) とする。result がNaN なら、+0 𝔽 を返す。result を返す。xString を ? ToString (x ) とする。yString を ? ToString (y ) とする。xSmaller を ! IsLessThan (xString , yString , true ) とする。xSmaller がtrue なら、-1 𝔽 を返す。ySmaller を ! IsLessThan (yString , xString , true ) とする。ySmaller がtrue なら、1 𝔽 を返す。+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を実行します:
obj を ? ToObject (this value) とする。length を ? LengthOfArrayLike (obj ) とする。relativeStart を ? ToIntegerOrInfinity (start ) とする。relativeStart = -∞なら、actualStart を0とする。そうでなく、relativeStart < 0なら、actualStart をmax (length + relativeStart , 0)とする。 そうでなければ、actualStart をmin (relativeStart , length )とする。 itemCount をitems 内のelementsの数とする。start がpresentでないなら、actualDeleteCount を0とする。そうでなく、deleteCount がpresentでないなら、actualDeleteCount をlength - actualStart とする。 そうでなければ、dc を ? ToIntegerOrInfinity (deleteCount ) とする。actualDeleteCount をdc を0とlength - actualStart の間にclamping したresultとする。 length + itemCount - actualDeleteCount > 253 - 1なら、TypeError 例外をthrowする。deletedArray を ? ArraySpeciesCreate (obj , actualDeleteCount ) とする。k を0とする。k < actualDeleteCount の間、繰り返すfrom を ! ToString (𝔽 (actualStart + k )) とする。? HasProperty (obj , from )がtrue なら、fromValue を ? Get (obj , from ) とする。? CreateDataPropertyOrThrow (deletedArray , ! ToString (𝔽 (k )), fromValue )を実行する。 k をk + 1に設定する。? Set (deletedArray , "length" , 𝔽 (actualDeleteCount ), true )を実行する。 itemCount < actualDeleteCount なら、k をactualStart に設定する。k < (length - actualDeleteCount )の間、繰り返すfrom を ! ToString (𝔽 (k + actualDeleteCount )) とする。to を ! ToString (𝔽 (k + itemCount )) とする。? HasProperty (obj , from )がtrue なら、fromValue を ? Get (obj , from ) とする。? Set (obj , to , fromValue , true )を実行する。 そうでなければ、? DeletePropertyOrThrow (obj , to )を実行する。 k をk + 1に設定する。k をlength に設定する。k > (length - actualDeleteCount + itemCount )の間、繰り返す? DeletePropertyOrThrow (obj , ! ToString (𝔽 (k - 1)))を実行する。 k をk - 1に設定する。そうでなく、itemCount > actualDeleteCount なら、k を(length - actualDeleteCount )に設定する。k > actualStart の間、繰り返すfrom を ! ToString (𝔽 (k + actualDeleteCount - 1)) とする。to を ! ToString (𝔽 (k + itemCount - 1)) とする。? HasProperty (obj , from )がtrue なら、fromValue を ? Get (obj , from ) とする。? Set (obj , to , fromValue , true )を実行する。 そうでなければ、? DeletePropertyOrThrow (obj , to )を実行する。 k をk - 1に設定する。 k をactualStart に設定する。items の各要素item について、以下を行う? Set (obj , ! ToString (𝔽 (k )), item , true )を実行する。 k をk + 1に設定する。? Set (obj , "length" , 𝔽 (length - actualDeleteCount + itemCount ), true )を実行する。 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を実行します:
array を ? ToObject (this value) とする。length を ? LengthOfArrayLike (array ) とする。separator を、host environmentのcurrent localeにappropriateなimplementation-defined list-separator String value(", " など)とする。result をempty Stringとする。k を0とする。k < length の間、繰り返すk > 0なら、result をresult とseparator のstring-concatenation に設定する。element を ? Get (array , ! ToString (𝔽 (k ))) とする。element がundefined でもnull でもないなら、elementString を ? ToString (? Invoke (element , "toLocaleString" )) とする。result をresult とelementString のstring-concatenation に設定する。k をk + 1に設定する。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を実行します:
obj を ? ToObject (this value) とする。length を ? LengthOfArrayLike (obj ) とする。array を ? ArrayCreate (length ) とする。k を0とする。k < length の間、繰り返すfrom を ! ToString (𝔽 (length - k - 1)) とする。propertyKey を ! ToString (𝔽 (k )) とする。fromValue を ? Get (obj , from ) とする。! CreateDataPropertyOrThrow (array , propertyKey , fromValue )を実行する。 k をk + 1に設定する。array を返す。
23.1.3.34 Array.prototype.toSorted ( comparator )
このmethodは呼び出されたとき、次のstepsを実行します:
comparator がundefined でなく、かつIsCallable (comparator )がfalse なら、TypeError 例外をthrowする。obj を ? ToObject (this value) とする。length を ? LengthOfArrayLike (obj ) とする。array を ? ArrayCreate (length ) とする。sortCompare を、comparator をcaptureし、calledされたときに次のstepsを実行する、parameters (x , y )を持つnew Abstract Closure とする:? CompareArrayElements (x , y , comparator )を返す。 sortedList を ? SortIndexedProperties (obj , length , sortCompare , read-through-holes ) とする。j を0とする。j < length の間、繰り返す! CreateDataPropertyOrThrow (array , ! ToString (𝔽 (j )), sortedList [j ])を実行する。 j をj + 1に設定する。array を返す。
23.1.3.35 Array.prototype.toSpliced ( start , skipCount , ...items )
このmethodは呼び出されたとき、次のstepsを実行します:
obj を ? ToObject (this value) とする。length を ? LengthOfArrayLike (obj ) とする。relativeStart を ? ToIntegerOrInfinity (start ) とする。relativeStart = -∞なら、actualStart を0とする。そうでなく、relativeStart < 0なら、actualStart をmax (length + relativeStart , 0)とする。 そうでなければ、actualStart をmin (relativeStart , length )とする。 insertCount をitems 内のelementsの数とする。start がpresentでないなら、actualSkipCount を0とする。そうでなく、skipCount がpresentでないなら、actualSkipCount をlength - actualStart とする。 そうでなければ、sc を ? ToIntegerOrInfinity (skipCount ) とする。actualSkipCount をsc を0とlength - actualStart の間にclamping したresultとする。 newLength をlength + insertCount - actualSkipCount とする。newLength > 253 - 1なら、TypeError 例外をthrowする。newArray を ? ArrayCreate (newLength ) とする。writeIndex を0とする。readIndex をactualStart + actualSkipCount とする。writeIndex < actualStart の間、繰り返すpropertyKey を ! ToString (𝔽 (writeIndex )) とする。iValue を ? Get (obj , propertyKey ) とする。! CreateDataPropertyOrThrow (newArray , propertyKey , iValue )を実行する。 writeIndex をwriteIndex + 1に設定する。items の各要素item について、以下を行うpropertyKey を ! ToString (𝔽 (writeIndex )) とする。! CreateDataPropertyOrThrow (newArray , propertyKey , item )を実行する。 writeIndex をwriteIndex + 1に設定する。writeIndex < newLength の間、繰り返すpropertyKey を ! ToString (𝔽 (writeIndex )) とする。from を ! ToString (𝔽 (readIndex )) とする。fromValue を ? Get (obj , from ) とする。! CreateDataPropertyOrThrow (newArray , propertyKey , fromValue )を実行する。 writeIndex をwriteIndex + 1に設定する。readIndex をreadIndex + 1に設定する。newArray を返す。
23.1.3.36 Array.prototype.toString ( )
このmethodは呼び出されたとき、次のstepsを実行します:
array を ? ToObject (this value) とする。func を ? Get (array , "join" ) とする。IsCallable (func )がfalse なら、func をintrinsic function %Object.prototype.toString%に設定する。? 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を実行します:
obj を ? ToObject (this value) とする。length を ? LengthOfArrayLike (obj ) とする。argCount をitems 内のelementsの数とする。argCount > 0なら、length + argCount > 253 - 1なら、TypeError 例外をthrowする。k をlength とする。k > 0の間、繰り返すfrom を ! ToString (𝔽 (k - 1)) とする。to を ! ToString (𝔽 (k + argCount - 1)) とする。fromPresent を ? HasProperty (obj , from ) とする。fromPresent がtrue なら、fromValue を ? Get (obj , from ) とする。? Set (obj , to , fromValue , true )を実行する。 そうでなければ、Assert : fromPresent はfalse である。? DeletePropertyOrThrow (obj , to )を実行する。 k をk - 1に設定する。j を+0 𝔽 とする。items の各要素item について、以下を行う? Set (obj , ! ToString (j ), item , true )を実行する。 j をj + 1 𝔽 に設定する。? Set (obj , "length" , 𝔽 (length + argCount ), true )を実行する。 𝔽 (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を実行します:
obj を ? ToObject (this value) とする。CreateArrayIterator (obj , value )を返す。
23.1.3.39 Array.prototype.with ( index , value )
このmethodは呼び出されたとき、次のstepsを実行します:
obj を ? ToObject (this value) とする。length を ? LengthOfArrayLike (obj ) とする。relativeIndex を ? ToIntegerOrInfinity (index ) とする。relativeIndex ≥ 0なら、actualIndex をrelativeIndex とする。そうでなければ、actualIndex をlength + relativeIndex とする。 actualIndex ≥ length またはactualIndex < 0なら、RangeError 例外をthrowする。array を ? ArrayCreate (length ) とする。k を0とする。k < length の間、繰り返すpropertyKey を ! ToString (𝔽 (k )) とする。k = actualIndex なら、fromValue をvalue とする。そうでなければ、fromValue を ? Get (obj , propertyKey ) とする。 ! CreateDataPropertyOrThrow (array , propertyKey , fromValue )を実行する。 k をk + 1に設定する。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です:
unscopableList をOrdinaryObjectCreate (null )とする。! CreateDataPropertyOrThrow (unscopableList , "at" , true )を実行する。 ! CreateDataPropertyOrThrow (unscopableList , "copyWithin" , true )を実行する。 ! CreateDataPropertyOrThrow (unscopableList , "entries" , true )を実行する。 ! CreateDataPropertyOrThrow (unscopableList , "fill" , true )を実行する。 ! CreateDataPropertyOrThrow (unscopableList , "find" , true )を実行する。 ! CreateDataPropertyOrThrow (unscopableList , "findIndex" , true )を実行する。 ! CreateDataPropertyOrThrow (unscopableList , "findLast" , true )を実行する。 ! CreateDataPropertyOrThrow (unscopableList , "findLastIndex" , true )を実行する。 ! CreateDataPropertyOrThrow (unscopableList , "flat" , true )を実行する。 ! CreateDataPropertyOrThrow (unscopableList , "flatMap" , true )を実行する。 ! CreateDataPropertyOrThrow (unscopableList , "includes" , true )を実行する。 ! CreateDataPropertyOrThrow (unscopableList , "keys" , true )を実行する。 ! CreateDataPropertyOrThrow (unscopableList , "toReversed" , true )を実行する。 ! CreateDataPropertyOrThrow (unscopableList , "toSorted" , true )を実行する。 ! CreateDataPropertyOrThrow (unscopableList , "toSpliced" , true )を実行する。 ! CreateDataPropertyOrThrow (unscopableList , "values" , true )を実行する。 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:
iterator をOrdinaryObjectCreate (%ArrayIteratorPrototype% , « [[IteratedArrayLike]] , [[ArrayLikeNextIndex]] , [[ArrayLikeIterationKind]] »)とする。iterator .[[IteratedArrayLike]] をarray に設定する。iterator .[[ArrayLikeNextIndex]] を0に設定する。iterator .[[ArrayLikeIterationKind]] をkind に設定する。iterator を返す。
23.1.5.2 The %ArrayIteratorPrototype% Object
%ArrayIteratorPrototype% objectは:
23.1.5.2.1 %ArrayIteratorPrototype%.next ( )
iteratorObj をthis valueとする。iteratorObj がObjectでないなら、TypeError 例外をthrowする。iteratorObj がArray Iterator Instanceのすべてのinternal slots(23.1.5.3 )を持たないなら、TypeError 例外をthrowする。array をiteratorObj .[[IteratedArrayLike]] とする。array がundefined なら、CreateIteratorResultObject (undefined , true )を返す。index をiteratorObj .[[ArrayLikeNextIndex]] とする。kind をiteratorObj .[[ArrayLikeIterationKind]] とする。array が[[TypedArrayName]] internal slotを持つなら、taRecord をMakeTypedArrayWithBufferWitnessRecord (array , seq-cst )とする。IsTypedArrayOutOfBounds (taRecord )がtrue なら、TypeError 例外をthrowする。length をTypedArrayLength (taRecord )とする。そうでなければ、length を ? LengthOfArrayLike (array ) とする。 index ≥ length なら、iteratorObj .[[IteratedArrayLike]] をundefined に設定する。CreateIteratorResultObject (undefined , true )を返す。iteratorObj .[[ArrayLikeNextIndex]] をindex + 1に設定する。indexNumber を𝔽 (index )とする。kind がkey なら、result をindexNumber とする。そうでなければ、elementKey を ! ToString (indexNumber ) とする。elementValue を ? Get (array , elementKey ) とする。kind がvalue なら、result をelementValue とする。そうでなければ、Assert : kind はkey+value である。result をCreateArrayFromList (« indexNumber , elementValue »)とする。 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は:
23.2.1.1 %TypedArray% ( )
このfunctionは呼び出されたとき、次のstepsを実行します:
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を実行します:
ctor をthis valueとする。IsConstructor (ctor )がfalse なら、TypeError 例外をthrowする。mapper がundefined なら、mapping をfalse とする。そうでなければ、IsCallable (mapper )がfalse なら、TypeError 例外をthrowする。mapping をtrue とする。 usingIterator を ? GetMethod (source , %Symbol.iterator% ) とする。usingIterator がundefined でないなら、values を ? IteratorToList (? GetIteratorFromMethod (source , usingIterator )) とする。length をvalues 内のelementsの数とする。targetObj を ? TypedArrayCreateFromConstructor (ctor , « 𝔽 (length ) ») とする。k を0とする。k < length の間、繰り返すpropertyKey を ! ToString (𝔽 (k )) とする。kValue をvalues のfirst elementとする。values からfirst elementをremoveする。mapping がtrue なら、mappedValue を ? Call (mapper , thisArg , « kValue , 𝔽 (k ) ») とする。そうでなければ、mappedValue をkValue とする。 ? Set (targetObj , propertyKey , mappedValue , true )を実行する。 k をk + 1に設定する。Assert : values は現在empty List である。targetObj を返す。NOTE : source はiterable object ではないため、すでにarray-like object であるとassumeする。arrayLike を ! ToObject (source ) とする。length を ? LengthOfArrayLike (arrayLike ) とする。targetObj を ? TypedArrayCreateFromConstructor (ctor , « 𝔽 (length ) ») とする。k を0とする。k < length の間、繰り返すpropertyKey を ! ToString (𝔽 (k )) とする。kValue を ? Get (arrayLike , propertyKey ) とする。mapping がtrue なら、mappedValue を ? Call (mapper , thisArg , « kValue , 𝔽 (k ) ») とする。そうでなければ、mappedValue をkValue とする。 ? Set (targetObj , propertyKey , mappedValue , true )を実行する。 k をk + 1に設定する。targetObj を返す。
23.2.2.2 %TypedArray%.of ( ...items )
このmethodは呼び出されたとき、次のstepsを実行します:
length をitems 内のelementsの数とする。ctor をthis valueとする。IsConstructor (ctor )がfalse なら、TypeError 例外をthrowする。newObj を ? TypedArrayCreateFromConstructor (ctor , « 𝔽 (length ) ») とする。k を0とする。k < length の間、繰り返すkValue をitems [k ]とする。propertyKey を ! ToString (𝔽 (k )) とする。? Set (newObj , propertyKey , kValue , true )を実行する。 k をk + 1に設定する。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を実行します:
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 )
obj をthis valueとする。taRecord を ? ValidateTypedArray (obj , seq-cst ) とする。length をTypedArrayLength (taRecord )とする。relativeIndex を ? ToIntegerOrInfinity (index ) とする。relativeIndex ≥ 0なら、k をrelativeIndex とする。そうでなければ、k をlength + relativeIndex とする。 k < 0またはk ≥ length なら、undefined を返す。! 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を実行します:
obj をthis valueとする。? RequireInternalSlot (obj , [[TypedArrayName]] )を実行する。 Assert : obj は[[ViewedArrayBuffer]] internal slotを持つ。buffer をobj .[[ViewedArrayBuffer]] とする。buffer を返す。
23.2.3.3 get %TypedArray%.prototype.byteLength
%TypedArray% .prototype.byteLengthは、set accessor functionがundefined であるaccessor property です。そのget accessor functionは呼び出されたとき、次のstepsを実行します:
obj をthis valueとする。? RequireInternalSlot (obj , [[TypedArrayName]] )を実行する。 Assert : obj は[[ViewedArrayBuffer]] internal slotを持つ。taRecord をMakeTypedArrayWithBufferWitnessRecord (obj , seq-cst )とする。IsTypedArrayOutOfBounds (taRecord )がtrue なら、+0 𝔽 を返す。size をTypedArrayByteLength (taRecord )とする。𝔽 (size )を返す。
23.2.3.4 get %TypedArray%.prototype.byteOffset
%TypedArray% .prototype.byteOffsetは、set accessor functionがundefined であるaccessor property です。そのget accessor functionは呼び出されたとき、次のstepsを実行します:
obj をthis valueとする。? RequireInternalSlot (obj , [[TypedArrayName]] )を実行する。 Assert : obj は[[ViewedArrayBuffer]] internal slotを持つ。taRecord をMakeTypedArrayWithBufferWitnessRecord (obj , seq-cst )とする。IsTypedArrayOutOfBounds (taRecord )がtrue なら、+0 𝔽 を返す。offset をobj .[[ByteOffset]] とする。𝔽 (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を実行します:
obj をthis valueとする。taRecord を ? ValidateTypedArray (obj , seq-cst ) とする。length をTypedArrayLength (taRecord )とする。relativeTarget を ? ToIntegerOrInfinity (target ) とする。relativeTarget = -∞なら、targetIndex を0とする。そうでなく、relativeTarget < 0なら、targetIndex をmax (length + relativeTarget , 0)とする。 そうでなければ、targetIndex をmin (relativeTarget , length )とする。 relativeStart を ? ToIntegerOrInfinity (start ) とする。relativeStart = -∞なら、startIndex を0とする。そうでなく、relativeStart < 0なら、startIndex をmax (length + relativeStart , 0)とする。 そうでなければ、startIndex をmin (relativeStart , length )とする。 end がundefined なら、relativeEnd をlength とする;そうでなければ、relativeEnd を ? ToIntegerOrInfinity (end ) とする。relativeEnd = -∞なら、endIndex を0とする。そうでなく、relativeEnd < 0なら、endIndex をmax (length + relativeEnd , 0)とする。 そうでなければ、endIndex をmin (relativeEnd , length )とする。 count をmin (endIndex - startIndex , length - targetIndex )とする。count > 0なら、NOTE : copyingはsource dataのbit-level encodingをpreserveするmannerでperformedされなければならない。buffer をobj .[[ViewedArrayBuffer]] とする。taRecord をMakeTypedArrayWithBufferWitnessRecord (obj , seq-cst )に設定する。IsTypedArrayOutOfBounds (taRecord )がtrue なら、TypeError 例外をthrowする。length をTypedArrayLength (taRecord )に設定する。NOTE : 上記stepsのside-effectsによりobj のsizeがreducedされた可能性があり、そのcaseではcopyingはlongest still-applicable prefixでproceedすべきである。count をmin (count , length - startIndex , length - targetIndex )に設定する。elementSize をTypedArrayElementSize (obj )とする。byteOffset をobj .[[ByteOffset]] とする。toByteIndex を(targetIndex × elementSize ) + byteOffset とする。fromByteIndex を(startIndex × elementSize ) + byteOffset とする。countBytes をcount × elementSize とする。fromByteIndex < toByteIndex かつtoByteIndex < fromByteIndex + countBytes なら、direction を-1とする。fromByteIndex をfromByteIndex + countBytes - 1に設定する。toByteIndex をtoByteIndex + countBytes - 1に設定する。そうでなければ、direction を1とする。 countBytes > 0の間、繰り返すvalue をGetValueFromBuffer (buffer , fromByteIndex , uint8 , true , unordered )とする。SetValueInBuffer (buffer , toByteIndex , uint8 , value , true , unordered )を実行する。fromByteIndex をfromByteIndex + direction に設定する。toByteIndex をtoByteIndex + direction に設定する。countBytes をcountBytes - 1に設定する。obj を返す。
23.2.3.7 %TypedArray%.prototype.entries ( )
このmethodは呼び出されたとき、次のstepsを実行します:
obj をthis valueとする。? ValidateTypedArray (obj , seq-cst )を実行する。 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を実行します:
obj をthis valueとする。taRecord を ? ValidateTypedArray (obj , seq-cst ) とする。length をTypedArrayLength (taRecord )とする。IsCallable (callback )がfalse なら、TypeError 例外をthrowする。k を0とする。k < length の間、繰り返すpropertyKey を ! ToString (𝔽 (k )) とする。kValue を ! Get (obj , propertyKey ) とする。testResult をToBoolean (? Call (callback , thisArg , « kValue , 𝔽 (k ), obj »))とする。testResult がfalse なら、false を返す。k をk + 1に設定する。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を実行します:
obj をthis valueとする。taRecord を ? ValidateTypedArray (obj , seq-cst ) とする。length をTypedArrayLength (taRecord )とする。obj .[[ContentType]] がbigint なら、value を ? ToBigInt (value ) に設定する。そうでなければ、value を ? ToNumber (value ) に設定する。 relativeStart を ? ToIntegerOrInfinity (start ) とする。relativeStart = -∞なら、startIndex を0とする。そうでなく、relativeStart < 0なら、startIndex をmax (length + relativeStart , 0)とする。 そうでなければ、startIndex をmin (relativeStart , length )とする。 end がundefined なら、relativeEnd をlength とする;そうでなければ、relativeEnd を ? ToIntegerOrInfinity (end ) とする。relativeEnd = -∞なら、endIndex を0とする。そうでなく、relativeEnd < 0なら、endIndex をmax (length + relativeEnd , 0)とする。 そうでなければ、endIndex をmin (relativeEnd , length )とする。 taRecord をMakeTypedArrayWithBufferWitnessRecord (obj , seq-cst )に設定する。IsTypedArrayOutOfBounds (taRecord )がtrue なら、TypeError 例外をthrowする。length をTypedArrayLength (taRecord )に設定する。endIndex をmin (endIndex , length )に設定する。k をstartIndex とする。k < endIndex の間、繰り返すpropertyKey を ! ToString (𝔽 (k )) とする。! Set (obj , propertyKey , value , true )を実行する。 k をk + 1に設定する。obj を返す。
23.2.3.10 %TypedArray%.prototype.filter ( callback [ , thisArg ] )
このmethodのargumentsのinterpretationおよびuseは、23.1.3.8 で定義されるArray.prototype.filterと同じです。
このmethodは呼び出されたとき、次のstepsを実行します:
obj をthis valueとする。taRecord を ? ValidateTypedArray (obj , seq-cst ) とする。length をTypedArrayLength (taRecord )とする。IsCallable (callback )がfalse なら、TypeError 例外をthrowする。kept を新しい空のList とする。captured を0とする。k を0とする。k < length の間、繰り返すpropertyKey を ! ToString (𝔽 (k )) とする。kValue を ! Get (obj , propertyKey ) とする。selected をToBoolean (? Call (callback , thisArg , « kValue , 𝔽 (k ), obj »))とする。selected がtrue なら、kValue をkept へappendする。captured をcaptured + 1に設定する。k をk + 1に設定する。result を ? TypedArraySpeciesCreate (obj , « 𝔽 (captured ) ») とする。n を0とする。kept の各要素element について、以下を行う! Set (result , ! ToString (𝔽 (n )), element , true )を実行する。 n をn + 1に設定する。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を実行します:
obj をthis valueとする。taRecord を ? ValidateTypedArray (obj , seq-cst ) とする。length をTypedArrayLength (taRecord )とする。findRecord を ? FindViaPredicate (obj , length , ascending , predicate , thisArg ) とする。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を実行します:
obj をthis valueとする。taRecord を ? ValidateTypedArray (obj , seq-cst ) とする。length をTypedArrayLength (taRecord )とする。findRecord を ? FindViaPredicate (obj , length , ascending , predicate , thisArg ) とする。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を実行します:
obj をthis valueとする。taRecord を ? ValidateTypedArray (obj , seq-cst ) とする。length をTypedArrayLength (taRecord )とする。findRecord を ? FindViaPredicate (obj , length , descending , predicate , thisArg ) とする。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を実行します:
obj をthis valueとする。taRecord を ? ValidateTypedArray (obj , seq-cst ) とする。length をTypedArrayLength (taRecord )とする。findRecord を ? FindViaPredicate (obj , length , descending , predicate , thisArg ) とする。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を実行します:
obj をthis valueとする。taRecord を ? ValidateTypedArray (obj , seq-cst ) とする。length をTypedArrayLength (taRecord )とする。IsCallable (callback )がfalse なら、TypeError 例外をthrowする。k を0とする。k < length の間、繰り返すpropertyKey を ! ToString (𝔽 (k )) とする。kValue を ! Get (obj , propertyKey ) とする。? Call (callback , thisArg , « kValue , 𝔽 (k ), obj »)を実行する。 k をk + 1に設定する。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を実行します:
obj をthis valueとする。taRecord を ? ValidateTypedArray (obj , seq-cst ) とする。length をTypedArrayLength (taRecord )とする。length = 0なら、false を返す。n を ? ToIntegerOrInfinity (fromIndex ) とする。Assert : fromIndex がundefined なら、n は0である。n = +∞なら、false を返す。n = -∞なら、n を0に設定する。n ≥ 0なら、k をn とする。そうでなければ、k をlength + n とする。k < 0なら、k を0に設定する。 k < length の間、繰り返すelementK を ! Get (obj , ! ToString (𝔽 (k ))) とする。SameValueZero (searchElement , elementK )がtrue なら、true を返す。k をk + 1に設定する。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を実行します:
obj をthis valueとする。taRecord を ? ValidateTypedArray (obj , seq-cst ) とする。length をTypedArrayLength (taRecord )とする。length = 0なら、-1 𝔽 を返す。n を ? ToIntegerOrInfinity (fromIndex ) とする。Assert : fromIndex がundefined なら、n は0である。n = +∞なら、-1 𝔽 を返す。n = -∞なら、n を0に設定する。n ≥ 0なら、k をn とする。そうでなければ、k をlength + n とする。k < 0なら、k を0に設定する。 k < length の間、繰り返すpropertyKey を ! ToString (𝔽 (k )) とする。kPresent を ! HasProperty (obj , propertyKey ) とする。kPresent がtrue なら、elementK を ! Get (obj , propertyKey ) とする。IsStrictlyEqual (searchElement , elementK )がtrue なら、𝔽 (k )を返す。k をk + 1に設定する。-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を実行します:
obj をthis valueとする。taRecord を ? ValidateTypedArray (obj , seq-cst ) とする。length をTypedArrayLength (taRecord )とする。separator がundefined なら、sep を"," とする。そうでなければ、sep を ? ToString (separator ) とする。 result をempty Stringとする。k を0とする。k < length の間、繰り返すk > 0なら、result をresult とsep のstring-concatenation に設定する。element を ! Get (obj , ! ToString (𝔽 (k ))) とする。element がundefined でないなら、elementString を ! ToString (element ) とする。result をresult とelementString のstring-concatenation に設定する。k をk + 1に設定する。result を返す。
このmethodはgenericではありません。this valueは[[TypedArrayName]] internal slotを持つobjectでなければなりません。
23.2.3.19 %TypedArray%.prototype.keys ( )
このmethodは呼び出されたとき、次のstepsを実行します:
obj をthis valueとする。? ValidateTypedArray (obj , seq-cst )を実行する。 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を実行します:
obj をthis valueとする。taRecord を ? ValidateTypedArray (obj , seq-cst ) とする。length をTypedArrayLength (taRecord )とする。length = 0なら、-1 𝔽 を返す。fromIndex がpresentなら、n を ? ToIntegerOrInfinity (fromIndex ) とする;そうでなければ、n をlength - 1とする。n = -∞なら、-1 𝔽 を返す。n ≥ 0なら、k をmin (n , length - 1)とする。そうでなければ、k をlength + n とする。 k ≥ 0の間、繰り返すpropertyKey を ! ToString (𝔽 (k )) とする。kPresent を ! HasProperty (obj , propertyKey ) とする。kPresent がtrue なら、elementK を ! Get (obj , propertyKey ) とする。IsStrictlyEqual (searchElement , elementK )がtrue なら、𝔽 (k )を返す。k をk - 1に設定する。-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を実行します:
obj をthis valueとする。? RequireInternalSlot (obj , [[TypedArrayName]] )を実行する。 Assert : obj は[[ViewedArrayBuffer]] および[[ArrayLength]] internal slotsを持つ。taRecord をMakeTypedArrayWithBufferWitnessRecord (obj , seq-cst )とする。IsTypedArrayOutOfBounds (taRecord )がtrue なら、+0 𝔽 を返す。length をTypedArrayLength (taRecord )とする。𝔽 (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を実行します:
obj をthis valueとする。taRecord を ? ValidateTypedArray (obj , seq-cst ) とする。length をTypedArrayLength (taRecord )とする。IsCallable (callback )がfalse なら、TypeError 例外をthrowする。result を ? TypedArraySpeciesCreate (obj , « 𝔽 (length ) ») とする。k を0とする。k < length の間、繰り返すpropertyKey を ! ToString (𝔽 (k )) とする。kValue を ! Get (obj , propertyKey ) とする。mappedValue を ? Call (callback , thisArg , « kValue , 𝔽 (k ), obj ») とする。? Set (result , propertyKey , mappedValue , true )を実行する。 k をk + 1に設定する。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を実行します:
obj をthis valueとする。taRecord を ? ValidateTypedArray (obj , seq-cst ) とする。length をTypedArrayLength (taRecord )とする。IsCallable (callback )がfalse なら、TypeError 例外をthrowする。length = 0であり、かつinitialValue がpresentでないなら、TypeError 例外をthrowする。k を0とする。accumulator をundefined とする。initialValue がpresentなら、accumulator をinitialValue に設定する。そうでなければ、propertyKey を ! ToString (𝔽 (k )) とする。accumulator を ! Get (obj , propertyKey ) に設定する。k をk + 1に設定する。 k < length の間、繰り返すpropertyKey を ! ToString (𝔽 (k )) とする。kValue を ! Get (obj , propertyKey ) とする。accumulator を ? Call (callback , undefined , « accumulator , kValue , 𝔽 (k ), obj ») に設定する。k をk + 1に設定する。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を実行します:
obj をthis valueとする。taRecord を ? ValidateTypedArray (obj , seq-cst ) とする。length をTypedArrayLength (taRecord )とする。IsCallable (callback )がfalse なら、TypeError 例外をthrowする。length = 0であり、かつinitialValue がpresentでないなら、TypeError 例外をthrowする。k をlength - 1とする。accumulator をundefined とする。initialValue がpresentなら、accumulator をinitialValue に設定する。そうでなければ、propertyKey を ! ToString (𝔽 (k )) とする。accumulator を ! Get (obj , propertyKey ) に設定する。k をk - 1に設定する。 k ≥ 0の間、繰り返すpropertyKey を ! ToString (𝔽 (k )) とする。kValue を ! Get (obj , propertyKey ) とする。accumulator を ? Call (callback , undefined , « accumulator , kValue , 𝔽 (k ), obj ») に設定する。k をk - 1に設定する。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を実行します:
obj をthis valueとする。taRecord を ? ValidateTypedArray (obj , seq-cst ) とする。length をTypedArrayLength (taRecord )とする。middle をfloor (length / 2)とする。lower を0とする。lower ≠ middle の間、繰り返すupper をlength - lower - 1とする。upperP を ! ToString (𝔽 (upper )) とする。lowerP を ! ToString (𝔽 (lower )) とする。lowerValue を ! Get (obj , lowerP ) とする。upperValue を ! Get (obj , upperP ) とする。! Set (obj , lowerP , upperValue , true )を実行する。 ! Set (obj , upperP , lowerValue , true )を実行する。 lower をlower + 1に設定する。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を実行します:
target をthis valueとする。? RequireInternalSlot (target , [[TypedArrayName]] )を実行する。 Assert : target は[[ViewedArrayBuffer]] internal slotを持つ。targetOffset を ? ToIntegerOrInfinity (offset ) とする。targetOffset < 0なら、RangeError 例外をthrowする。source が[[TypedArrayName]] internal slotを持つObjectなら、? SetTypedArrayFromTypedArray (target , targetOffset , source )を実行する。 そうでなければ、? SetTypedArrayFromArrayLike (target , targetOffset , source )を実行する。 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:
targetRecord をMakeTypedArrayWithBufferWitnessRecord (target , seq-cst )とする。IsTypedArrayOutOfBounds (targetRecord )がtrue なら、TypeError 例外をthrowする。targetLength をTypedArrayLength (targetRecord )とする。source を ? ToObject (source ) に設定する。sourceLength を ? LengthOfArrayLike (source ) とする。targetOffset = +∞なら、RangeError 例外をthrowする。sourceLength + targetOffset > targetLength なら、RangeError 例外をthrowする。k を0とする。k < sourceLength の間、繰り返すpropertyKey を ! ToString (𝔽 (k )) とする。value を ? Get (source , propertyKey ) とする。targetIndex を𝔽 (targetOffset + k )とする。? TypedArraySetElement (target , targetIndex , value )を実行する。 k をk + 1に設定する。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:
targetBuffer をtarget .[[ViewedArrayBuffer]] とする。targetRecord をMakeTypedArrayWithBufferWitnessRecord (target , seq-cst )とする。IsTypedArrayOutOfBounds (targetRecord )がtrue なら、TypeError 例外をthrowする。targetLength をTypedArrayLength (targetRecord )とする。sourceBuffer をsource .[[ViewedArrayBuffer]] とする。sourceRecord をMakeTypedArrayWithBufferWitnessRecord (source , seq-cst )とする。IsTypedArrayOutOfBounds (sourceRecord )がtrue なら、TypeError 例外をthrowする。sourceLength をTypedArrayLength (sourceRecord )とする。targetType をTypedArrayElementType (target )とする。targetElementSize をTypedArrayElementSize (target )とする。targetByteOffset をtarget .[[ByteOffset]] とする。sourceType をTypedArrayElementType (source )とする。sourceElementSize をTypedArrayElementSize (source )とする。sourceByteOffset をsource .[[ByteOffset]] とする。targetOffset = +∞なら、RangeError 例外をthrowする。sourceLength + targetOffset > targetLength なら、RangeError 例外をthrowする。target .[[ContentType]] がsource .[[ContentType]] でないなら、TypeError 例外をthrowする。IsSharedArrayBuffer (sourceBuffer )がtrue であり、IsSharedArrayBuffer (targetBuffer )がtrue であり、かつsourceBuffer .[[ArrayBufferData]] がtargetBuffer .[[ArrayBufferData]] であるなら、sameSharedArrayBuffer をtrue とする;そうでなければ、sameSharedArrayBuffer をfalse とする。SameValue (sourceBuffer , targetBuffer )がtrue またはsameSharedArrayBuffer がtrue なら、sourceByteLength をTypedArrayByteLength (sourceRecord )とする。sourceBuffer を ? CloneArrayBuffer (sourceBuffer , sourceByteOffset , sourceByteLength ) に設定する。sourceByteIndex を0とする。そうでなければ、sourceByteIndex をsourceByteOffset とする。 targetByteIndex を(targetOffset × targetElementSize ) + targetByteOffset とする。limit をtargetByteIndex + (targetElementSize × sourceLength )とする。sourceType がtargetType なら、NOTE : transferはsource dataのbit-level encodingをpreserveするmannerでperformedされなければならない。targetByteIndex < limit の間、繰り返すvalue をGetValueFromBuffer (sourceBuffer , sourceByteIndex , uint8 , true , unordered )とする。SetValueInBuffer (targetBuffer , targetByteIndex , uint8 , value , true , unordered )を実行する。sourceByteIndex をsourceByteIndex + 1に設定する。targetByteIndex をtargetByteIndex + 1に設定する。そうでなければ、targetByteIndex < limit の間、繰り返すvalue をGetValueFromBuffer (sourceBuffer , sourceByteIndex , sourceType , true , unordered )とする。SetValueInBuffer (targetBuffer , targetByteIndex , targetType , value , true , unordered )を実行する。sourceByteIndex をsourceByteIndex + sourceElementSize に設定する。targetByteIndex をtargetByteIndex + targetElementSize に設定する。 unused を返す。
23.2.3.27 %TypedArray%.prototype.slice ( start , end )
このmethodのargumentsのinterpretationおよびuseは、23.1.3.28 で定義されるArray.prototype.sliceと同じです。
このmethodは呼び出されたとき、次のstepsを実行します:
obj をthis valueとする。taRecord を ? ValidateTypedArray (obj , seq-cst ) とする。sourceArrayLength をTypedArrayLength (taRecord )とする。relativeStart を ? ToIntegerOrInfinity (start ) とする。relativeStart = -∞なら、startIndex を0とする。そうでなく、relativeStart < 0なら、startIndex をmax (sourceArrayLength + relativeStart , 0)とする。 そうでなければ、startIndex をmin (relativeStart , sourceArrayLength )とする。 end がundefined なら、relativeEnd をsourceArrayLength とする;そうでなければ、relativeEnd を ? ToIntegerOrInfinity (end ) とする。relativeEnd = -∞なら、endIndex を0とする。そうでなく、relativeEnd < 0なら、endIndex をmax (sourceArrayLength + relativeEnd , 0)とする。 そうでなければ、endIndex をmin (relativeEnd , sourceArrayLength )とする。 countBytes をmax (endIndex - startIndex , 0)とする。resultArray を ? TypedArraySpeciesCreate (obj , « 𝔽 (countBytes ) ») とする。countBytes > 0なら、taRecord をMakeTypedArrayWithBufferWitnessRecord (obj , seq-cst )に設定する。IsTypedArrayOutOfBounds (taRecord )がtrue なら、TypeError 例外をthrowする。endIndex をmin (endIndex , TypedArrayLength (taRecord ))に設定する。countBytes をmax (endIndex - startIndex , 0)に設定する。sourceType をTypedArrayElementType (obj )とする。targetType をTypedArrayElementType (resultArray )とする。sourceType がtargetType なら、NOTE : transferはsource dataのbit-level encodingをpreserveするmannerでperformedされなければならない。sourceBuffer をobj .[[ViewedArrayBuffer]] とする。targetBuffer をresultArray .[[ViewedArrayBuffer]] とする。elementSize をTypedArrayElementSize (obj )とする。sourceByteOffset をobj .[[ByteOffset]] とする。sourceByteIndex を(startIndex × elementSize ) + sourceByteOffset とする。targetByteIndex をresultArray .[[ByteOffset]] とする。endByteIndex をtargetByteIndex + (countBytes × elementSize )とする。targetByteIndex < endByteIndex の間、繰り返すvalue をGetValueFromBuffer (sourceBuffer , sourceByteIndex , uint8 , true , unordered )とする。SetValueInBuffer (targetBuffer , targetByteIndex , uint8 , value , true , unordered )を実行する。sourceByteIndex をsourceByteIndex + 1に設定する。targetByteIndex をtargetByteIndex + 1に設定する。そうでなければ、n を0とする。k をstartIndex とする。k < endIndex の間、繰り返すpropertyKey を ! ToString (𝔽 (k )) とする。kValue を ! Get (obj , propertyKey ) とする。! Set (resultArray , ! ToString (𝔽 (n )), kValue , true )を実行する。 k をk + 1に設定する。n をn + 1に設定する。 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を実行します:
obj をthis valueとする。taRecord を ? ValidateTypedArray (obj , seq-cst ) とする。length をTypedArrayLength (taRecord )とする。IsCallable (callback )がfalse なら、TypeError 例外をthrowする。k を0とする。k < length の間、繰り返すpropertyKey を ! ToString (𝔽 (k )) とする。kValue を ! Get (obj , propertyKey ) とする。testResult をToBoolean (? Call (callback , thisArg , « kValue , 𝔽 (k ), obj »))とする。testResult がtrue なら、true を返す。k をk + 1に設定する。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を実行します:
comparator がundefined でなく、かつIsCallable (comparator )がfalse なら、TypeError 例外をthrowする。obj をthis valueとする。taRecord を ? ValidateTypedArray (obj , seq-cst ) とする。length をTypedArrayLength (taRecord )とする。NOTE : 以下のclosureは、23.1.3.30 で使用されるstring comparisonではなくnumeric comparisonをperformする。sortCompare を、comparator をcaptureし、calledされたときに次のstepsを実行する、parameters (x , y )を持つnew Abstract Closure とする:? CompareTypedArrayElements (x , y , comparator )を返す。 sortedList を ? SortIndexedProperties (obj , length , sortCompare , read-through-holes ) とする。j を0とする。j < length の間、繰り返す! Set (obj , ! ToString (𝔽 (j )), sortedList [j ], true )を実行する。 j をj + 1に設定する。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を実行します:
obj をthis valueとする。? RequireInternalSlot (obj , [[TypedArrayName]] )を実行する。 Assert : obj は[[ViewedArrayBuffer]] internal slotを持つ。buffer をobj .[[ViewedArrayBuffer]] とする。sourceRecord をMakeTypedArrayWithBufferWitnessRecord (obj , seq-cst )とする。IsTypedArrayOutOfBounds (sourceRecord )がtrue なら、sourceLength を0とする。そうでなければ、sourceLength をTypedArrayLength (sourceRecord )とする。 relativeStart を ? ToIntegerOrInfinity (start ) とする。relativeStart = -∞なら、startIndex を0とする。そうでなく、relativeStart < 0なら、startIndex をmax (sourceLength + relativeStart , 0)とする。 そうでなければ、startIndex をmin (relativeStart , sourceLength )とする。 elementSize をTypedArrayElementSize (obj )とする。sourceByteOffset をobj .[[ByteOffset]] とする。beginByteOffset をsourceByteOffset + (startIndex × elementSize )とする。obj .[[ArrayLength]] がauto であり、かつend がundefined なら、argList を« buffer , 𝔽 (beginByteOffset ) »とする。そうでなければ、end がundefined なら、relativeEnd をsourceLength とする;そうでなければ、relativeEnd を ? ToIntegerOrInfinity (end ) とする。relativeEnd = -∞なら、endIndex を0とする。そうでなく、relativeEnd < 0なら、endIndex をmax (sourceLength + relativeEnd , 0)とする。 そうでなければ、endIndex をmin (relativeEnd , sourceLength )とする。 newLength をmax (endIndex - startIndex , 0)とする。argList を« buffer , 𝔽 (beginByteOffset ), 𝔽 (newLength ) »とする。 ? 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を実行します:
obj をthis valueとする。taRecord を ? ValidateTypedArray (obj , seq-cst ) とする。length をTypedArrayLength (taRecord )とする。resultArray を ? TypedArrayCreateSameType (obj , length ) とする。k を0とする。k < length の間、繰り返すfrom を ! ToString (𝔽 (length - k - 1)) とする。propertyKey を ! ToString (𝔽 (k )) とする。fromValue を ! Get (obj , from ) とする。! Set (resultArray , propertyKey , fromValue , true )を実行する。 k をk + 1に設定する。resultArray を返す。
23.2.3.33 %TypedArray%.prototype.toSorted ( comparator )
このmethodは呼び出されたとき、次のstepsを実行します:
comparator がundefined でなく、かつIsCallable (comparator )がfalse なら、TypeError 例外をthrowする。obj をthis valueとする。taRecord を ? ValidateTypedArray (obj , seq-cst ) とする。length をTypedArrayLength (taRecord )とする。resultArray を ? TypedArrayCreateSameType (obj , length ) とする。NOTE : 以下のclosureは、23.1.3.34 で使用されるstring comparisonではなくnumeric comparisonをperformする。sortCompare を、comparator をcaptureし、calledされたときに次のstepsを実行する、parameters (x , y )を持つnew Abstract Closure とする:? CompareTypedArrayElements (x , y , comparator )を返す。 sortedList を ? SortIndexedProperties (obj , length , sortCompare , read-through-holes ) とする。j を0とする。j < length の間、繰り返す! Set (resultArray , ! ToString (𝔽 (j )), sortedList [j ], true )を実行する。 j をj + 1に設定する。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を実行します:
obj をthis valueとする。? ValidateTypedArray (obj , seq-cst )を実行する。 CreateArrayIterator (obj , value )を返す。
23.2.3.36 %TypedArray%.prototype.with ( index , value )
このmethodは呼び出されたとき、次のstepsを実行します:
obj をthis valueとする。taRecord を ? ValidateTypedArray (obj , seq-cst ) とする。length をTypedArrayLength (taRecord )とする。relativeIndex を ? ToIntegerOrInfinity (index ) とする。relativeIndex ≥ 0なら、actualIndex をrelativeIndex とする。そうでなければ、actualIndex をlength + relativeIndex とする。 obj .[[ContentType]] がbigint なら、numericValue を ? ToBigInt (value ) とする。そうでなければ、numericValue を ? ToNumber (value ) とする。 IsValidIntegerIndex (obj , 𝔽 (actualIndex ))がfalse なら、RangeError 例外をthrowする。resultArray を ? TypedArrayCreateSameType (obj , length ) とする。k を0とする。k < length の間、繰り返すpropertyKey を ! ToString (𝔽 (k )) とする。k = actualIndex なら、fromValue をnumericValue とする。そうでなければ、fromValue を ! Get (obj , propertyKey ) とする。 ! Set (resultArray , propertyKey , fromValue , true )を実行する。 k をk + 1に設定する。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を実行します:
obj をthis valueとする。obj がObjectでないなら、undefined を返す。obj が[[TypedArrayName]] internal slotを持たないなら、undefined を返す。name をobj .[[TypedArrayName]] とする。Assert : name はStringである。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:
ta を ? Construct (ctor , argList ) とする。taRecord を ? ValidateTypedArray (ta , seq-cst ) とする。Assert : ta はProperties of TypedArray Instances でmentionedされるすべてのinternal slotsを持つ。argList 内のelementsの数が1であり、かつargList [0]がNumberなら、IsTypedArrayOutOfBounds (taRecord )がtrue なら、TypeError 例外をthrowする。length をTypedArrayLength (taRecord )とする。length < ℝ (argList [0])なら、TypeError 例外をthrowする。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:
ctor を、Table 71 内のconstructor name exemplar .[[TypedArrayName]] にassociatedするintrinsic objectとする。result を ? TypedArrayCreateFromConstructor (ctor , « 𝔽 (length ) ») とする。Assert : result は[[TypedArrayName]] および[[ContentType]] internal slotsを持つ。Assert : result .[[ContentType]] はexemplar .[[ContentType]] である。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:
defaultCtor を、Table 71 内のconstructor name exemplar .[[TypedArrayName]] にassociatedするintrinsic objectとする。ctor を ? SpeciesConstructor (exemplar , defaultCtor ) とする。result を ? TypedArrayCreateFromConstructor (ctor , argList ) とする。result .[[ContentType]] がexemplar .[[ContentType]] でないなら、TypeError 例外をthrowする。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:
? RequireInternalSlot (obj , [[TypedArrayName]] )を実行する。 Assert : obj は[[ViewedArrayBuffer]] internal slotを持つ。taRecord をMakeTypedArrayWithBufferWitnessRecord (obj , order )とする。IsTypedArrayOutOfBounds (taRecord )がtrue なら、TypeError 例外をthrowする。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:
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:
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:
Assert : x はNumberでありy はNumberである、またはx はBigIntでありy はBigIntである。comparator がundefined でないなら、result を ? ToNumber (? Call (comparator , undefined , « x , y »)) とする。result がNaN なら、+0 𝔽 を返す。result を返す。x がNaN であり、かつy がNaN なら、+0 𝔽 を返す。x がNaN なら、1 𝔽 を返す。y がNaN なら、-1 𝔽 を返す。x < y なら、-1 𝔽 を返す。x > y なら、1 𝔽 を返す。x が-0 𝔽 であり、かつy が+0 𝔽 なら、-1 𝔽 を返す。x が+0 𝔽 であり、かつy が-0 𝔽 なら、1 𝔽 を返す。+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を実行します:
NewTargetがundefined なら、TypeError 例外をthrowする。 ctorName を、this TypedArray constructor についてTable 71 でspecifiedされるConstructor Name valueのString valueとする。proto を"%TypedArray .prototype%"とする。numberOfArgs をargs 内のelementsの数とする。numberOfArgs = 0なら、? AllocateTypedArray (ctorName , NewTarget, proto , 0)を返す。firstArg をargs [0]とする。firstArg がObjectなら、obj を ? AllocateTypedArray (ctorName , NewTarget, proto ) とする。firstArg が[[TypedArrayName]] internal slotを持つなら、? InitializeTypedArrayFromTypedArray (obj , firstArg )を実行する。 そうでなく、firstArg が[[ArrayBufferData]] internal slotを持つなら、numberOfArgs > 1なら、byteOffset をargs [1]とする;そうでなければ、byteOffset をundefined とする。numberOfArgs > 2なら、length をargs [2]とする;そうでなければ、length をundefined とする。? InitializeTypedArrayFromArrayBuffer (obj , firstArg , byteOffset , length )を実行する。 そうでなければ、Assert : firstArg はObjectであり、firstArg は[[TypedArrayName]] および[[ArrayBufferData]] internal slotのいずれも持たない。usingIterator を ? GetMethod (firstArg , %Symbol.iterator% ) とする。usingIterator がundefined でないなら、values を ? IteratorToList (? GetIteratorFromMethod (firstArg , usingIterator )) とする。? InitializeTypedArrayFromList (obj , values )を実行する。 そうでなければ、NOTE : firstArg はiterable object ではないため、すでにarray-like object であるとassumeする。? InitializeTypedArrayFromArrayLike (obj , firstArg )を実行する。 obj を返す。Assert : firstArg はObjectではない。elementLength を ? ToIndex (firstArg ) とする。? 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:
proto を ? GetPrototypeFromConstructor (newTarget , defaultProto ) とする。obj をTypedArrayCreate (proto )とする。Assert : obj .[[ViewedArrayBuffer]] はundefined である。obj .[[TypedArrayName]] をctorName に設定する。ctorName が"BigInt64Array" または"BigUint64Array" のいずれかなら、obj .[[ContentType]] をbigint に設定する。そうでなければ、obj .[[ContentType]] をnumber に設定する。 length がpresentでないなら、obj .[[ByteLength]] を0に設定する。obj .[[ByteOffset]] を0に設定する。obj .[[ArrayLength]] を0に設定する。そうでなければ、? AllocateTypedArrayBuffer (obj , length )を実行する。 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:
sourceData をsourceArray .[[ViewedArrayBuffer]] とする。elementType をTypedArrayElementType (obj )とする。elementSize をTypedArrayElementSize (obj )とする。sourceType をTypedArrayElementType (sourceArray )とする。sourceElementSize をTypedArrayElementSize (sourceArray )とする。sourceByteOffset をsourceArray .[[ByteOffset]] とする。sourceRecord をMakeTypedArrayWithBufferWitnessRecord (sourceArray , seq-cst )とする。IsTypedArrayOutOfBounds (sourceRecord )がtrue なら、TypeError 例外をthrowする。elementLength をTypedArrayLength (sourceRecord )とする。byteLength をelementSize × elementLength とする。elementType がsourceType なら、data を ? CloneArrayBuffer (sourceData , sourceByteOffset , byteLength ) とする。そうでなければ、data を ? AllocateArrayBuffer (%ArrayBuffer% , byteLength ) とする。sourceArray .[[ContentType]] がobj .[[ContentType]] でないなら、TypeError 例外をthrowする。sourceByteIndex をsourceByteOffset とする。targetByteIndex を0とする。count をelementLength とする。count > 0の間、繰り返すvalue をGetValueFromBuffer (sourceData , sourceByteIndex , sourceType , true , unordered )とする。SetValueInBuffer (data , targetByteIndex , elementType , value , true , unordered )を実行する。sourceByteIndex をsourceByteIndex + sourceElementSize に設定する。targetByteIndex をtargetByteIndex + elementSize に設定する。count をcount - 1に設定する。 obj .[[ViewedArrayBuffer]] をdata に設定する。obj .[[ByteLength]] をbyteLength に設定する。obj .[[ByteOffset]] を0に設定する。obj .[[ArrayLength]] をelementLength に設定する。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:
elementSize をTypedArrayElementSize (obj )とする。offset を ? ToIndex (byteOffset ) とする。offset modulo elementSize ≠ 0なら、RangeError 例外をthrowする。bufferIsFixedLength をIsFixedLengthArrayBuffer (buffer )とする。length がundefined でないなら、newLength を ? ToIndex (length ) とする。IsDetachedBuffer (buffer )がtrue なら、TypeError 例外をthrowする。bufferByteLength をArrayBufferByteLength (buffer , seq-cst )とする。length がundefined であり、かつbufferIsFixedLength がfalse なら、offset > bufferByteLength なら、RangeError 例外をthrowする。obj .[[ByteLength]] をauto に設定する。obj .[[ArrayLength]] をauto に設定する。そうでなければ、length がundefined なら、bufferByteLength modulo elementSize ≠ 0なら、RangeError 例外をthrowする。newByteLength をbufferByteLength - offset とする。newByteLength < 0なら、RangeError 例外をthrowする。そうでなければ、newByteLength をnewLength × elementSize とする。offset + newByteLength > bufferByteLength なら、RangeError 例外をthrowする。 obj .[[ByteLength]] をnewByteLength に設定する。obj .[[ArrayLength]] をnewByteLength / elementSize に設定する。 obj .[[ViewedArrayBuffer]] をbuffer に設定する。obj .[[ByteOffset]] をoffset に設定する。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:
length をvalues 内のelementsの数とする。? AllocateTypedArrayBuffer (obj , length )を実行する。 k を0とする。k < length の間、繰り返すpropertyKey を ! ToString (𝔽 (k )) とする。kValue をvalues のfirst elementとする。values からfirst elementをremoveする。? Set (obj , propertyKey , kValue , true )を実行する。 k をk + 1に設定する。Assert : values は現在empty List である。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:
length を ? LengthOfArrayLike (arrayLike ) とする。? AllocateTypedArrayBuffer (obj , length )を実行する。 k を0とする。k < length の間、繰り返すpropertyKey を ! ToString (𝔽 (k )) とする。kValue を ? Get (arrayLike , propertyKey ) とする。? Set (obj , propertyKey , kValue , true )を実行する。 k をk + 1に設定する。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:
Assert : obj .[[ViewedArrayBuffer]] はundefined である。elementSize をTypedArrayElementSize (obj )とする。byteLength をelementSize × length とする。data を ? AllocateArrayBuffer (%ArrayBuffer% , byteLength ) とする。obj .[[ViewedArrayBuffer]] をdata に設定する。obj .[[ByteLength]] をbyteLength に設定する。obj .[[ByteOffset]] を0に設定する。obj .[[ArrayLength]] をlength に設定する。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は:
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 constructor (23.3.1 )およびUint8Array prototype object(23.3.2 )にはadditional methodsがあります。
23.3.1 Uint8Array Constructorの追加プロパティ
23.3.1.1 Uint8Array.fromBase64 ( string [ , options ] )
string がStringでないなら、TypeError 例外をthrowする。opts を ? GetOptionsObject (options ) とする。alphabet を ? Get (opts , "alphabet" ) とする。alphabet がundefined なら、alphabet を"base64" に設定する。alphabet が"base64" でも"base64url" でもないなら、TypeError 例外をthrowする。lastChunkHandling を ? Get (opts , "lastChunkHandling" ) とする。lastChunkHandling がundefined なら、lastChunkHandling を"loose" に設定する。lastChunkHandling が"loose" 、"strict" 、または"stop-before-partial" のいずれでもないなら、TypeError 例外をthrowする。result をFromBase64 (string , alphabet , lastChunkHandling )とする。result .[[Error]] がnone でないなら、result .[[Error]] をthrowする。resultLength をresult .[[Bytes]] 内のelementsの数とする。ta を ? AllocateTypedArray ("Uint8Array" , %Uint8Array% , "%Uint8Array.prototype%" , resultLength ) とする。Assert : ta .[[ViewedArrayBuffer]] .[[ArrayBufferByteLength]] はresult .[[Bytes]] 内のelementsの数である。ta .[[ViewedArrayBuffer]] .[[ArrayBufferData]] の各indexのvalueを、result .[[Bytes]] のcorresponding indexのvalueに設定する。ta を返す。
23.3.1.2 Uint8Array.fromHex ( string )
string がStringでないなら、TypeError 例外をthrowする。result をFromHex (string )とする。result .[[Error]] がnone でないなら、result .[[Error]] をthrowする。resultLength をresult .[[Bytes]] 内のelementsの数とする。ta を ? AllocateTypedArray ("Uint8Array" , %Uint8Array% , "%Uint8Array.prototype%" , resultLength ) とする。Assert : ta .[[ViewedArrayBuffer]] .[[ArrayBufferByteLength]] はresult .[[Bytes]] 内のelementsの数である。ta .[[ViewedArrayBuffer]] .[[ArrayBufferData]] の各indexのvalueを、result .[[Bytes]] のcorresponding indexのvalueに設定する。ta を返す。
23.3.2 Uint8Array Prototype Objectの追加プロパティ
23.3.2.1 Uint8Array.prototype.setFromBase64 ( string [ , options ] )
into をthis valueとする。? ValidateUint8Array (into )を実行する。 string がStringでないなら、TypeError 例外をthrowする。opts を ? GetOptionsObject (options ) とする。alphabet を ? Get (opts , "alphabet" ) とする。alphabet がundefined なら、alphabet を"base64" に設定する。alphabet が"base64" でも"base64url" でもないなら、TypeError 例外をthrowする。lastChunkHandling を ? Get (opts , "lastChunkHandling" ) とする。lastChunkHandling がundefined なら、lastChunkHandling を"loose" に設定する。lastChunkHandling が"loose" 、"strict" 、または"stop-before-partial" のいずれでもないなら、TypeError 例外をthrowする。taRecord をMakeTypedArrayWithBufferWitnessRecord (into , seq-cst )とする。IsTypedArrayOutOfBounds (taRecord )がtrue なら、TypeError 例外をthrowする。byteLength をTypedArrayLength (taRecord )とする。result をFromBase64 (string , alphabet , lastChunkHandling , byteLength )とする。bytes をresult .[[Bytes]] とする。written をbytes 内のelementsの数とする。NOTE : FromBase64 はuser codeをinvokeしないため、into をbackingするArrayBufferはdetachedまたはshrunkされていることはない。Assert : written ≤ byteLength 。SetUint8ArrayBytes (into , bytes )を実行する。result .[[Error]] がnone でないなら、result .[[Error]] をthrowする。resultObj をOrdinaryObjectCreate (%Object.prototype% )とする。! CreateDataPropertyOrThrow (resultObj , "read" , 𝔽 (result .[[Read]] ))を実行する。 ! CreateDataPropertyOrThrow (resultObj , "written" , 𝔽 (written ))を実行する。 resultObj を返す。
23.3.2.2 Uint8Array.prototype.setFromHex ( string )
into をthis valueとする。? ValidateUint8Array (into )を実行する。 string がStringでないなら、TypeError 例外をthrowする。taRecord をMakeTypedArrayWithBufferWitnessRecord (into , seq-cst )とする。IsTypedArrayOutOfBounds (taRecord )がtrue なら、TypeError 例外をthrowする。byteLength をTypedArrayLength (taRecord )とする。result をFromHex (string , byteLength )とする。bytes をresult .[[Bytes]] とする。written をbytes 内のelementsの数とする。NOTE : FromHex はuser codeをinvokeしないため、into をbackingするArrayBufferはdetachedまたはshrunkされていることはない。Assert : written ≤ byteLength 。SetUint8ArrayBytes (into , bytes )を実行する。result .[[Error]] がnone でないなら、result .[[Error]] をthrowする。resultObj をOrdinaryObjectCreate (%Object.prototype% )とする。! CreateDataPropertyOrThrow (resultObj , "read" , 𝔽 (result .[[Read]] ))を実行する。 ! CreateDataPropertyOrThrow (resultObj , "written" , 𝔽 (written ))を実行する。 resultObj を返す。
23.3.2.3 Uint8Array.prototype.toBase64 ( [ options ] )
obj をthis valueとする。? ValidateUint8Array (obj )を実行する。 opts を ? GetOptionsObject (options ) とする。alphabet を ? Get (opts , "alphabet" ) とする。alphabet がundefined なら、alphabet を"base64" に設定する。alphabet が"base64" でも"base64url" でもないなら、TypeError 例外をthrowする。omitPadding をToBoolean (? Get (opts , "omitPadding" ))とする。toEncode を ? GetUint8ArrayBytes (obj ) とする。alphabet が"base64" なら、outAscii を、toEncode をRFC 4648 のsection 4でspecifiedされるbase64 encodingに従ってencodingした結果のcode pointsのsequenceとする。Paddingは、omitPadding がfalse である場合に限りincludedされる。そうでなければ、Assert : alphabet は"base64url" である。outAscii を、toEncode をRFC 4648 のsection 5でspecifiedされるbase64url encodingに従ってencodingした結果のcode pointsのsequenceとする。Paddingは、omitPadding がfalse である場合に限りincludedされる。 CodePointsToString (outAscii )を返す。
23.3.2.4 Uint8Array.prototype.toHex ( )
obj をthis valueとする。? ValidateUint8Array (obj )を実行する。 toEncode を ? GetUint8ArrayBytes (obj ) とする。out をempty Stringとする。toEncode の各byte byte について、以下を行うhex をNumber::toString (𝔽 (byte ), 16)とする。hex をStringPad (hex , 2, "0" , start )に設定する。out をout とhex のstring-concatenation に設定する。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:
? RequireInternalSlot (ta , [[TypedArrayName]] )を実行する。 ta .[[TypedArrayName]] が"Uint8Array" でないなら、TypeError 例外をthrowする。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:
buffer をta .[[ViewedArrayBuffer]] とする。taRecord をMakeTypedArrayWithBufferWitnessRecord (ta , seq-cst )とする。IsTypedArrayOutOfBounds (taRecord )がtrue なら、TypeError 例外をthrowする。length をTypedArrayLength (taRecord )とする。byteOffset をta .[[ByteOffset]] とする。bytes を新しい空のList とする。index を0とする。index < length の間、繰り返すbyteIndex をbyteOffset + index とする。byte をℝ (GetValueFromBuffer (buffer , byteIndex , uint8 , true , unordered ))とする。byte をbytes へappendする。index をindex + 1に設定する。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:
offset をinto .[[ByteOffset]] とする。length をbytes 内のelementsの数とする。index を0とする。index < length の間、繰り返すbyte をbytes [index ]とする。byteIndexInBuffer をindex + offset とする。SetValueInBuffer (into .[[ViewedArrayBuffer]] , byteIndexInBuffer , uint8 , 𝔽 (byte ), true , unordered )を実行する。index をindex + 1に設定する。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:
length をstring のlengthとする。index < length の間、繰り返すchar をstring 内のindex index にあるcode unitとする。char が0x0009 (TAB)、0x000A (LF)、0x000C (FF)、0x000D (CR)、または0x0020 (SPACE)のいずれでもないなら、index を返す。index をindex + 1に設定する。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:
chunkLength をchunk のlengthとする。chunkLength = 2なら、chunk をchunk と"AA" のstring-concatenation に設定する。そうでなければ、Assert : chunkLength は3である。chunk をchunk と"A" のstring-concatenation に設定する。 bytes をDecodeFullLengthBase64Chunk (chunk )とする。chunkLength = 2なら、throwOnExtraBits がtrue であり、かつbytes [1] ≠ 0なら、SyntaxError 例外をthrowする。« bytes [0] »を返す。 throwOnExtraBits がtrue であり、かつbytes [2] ≠ 0なら、SyntaxError 例外をthrowする。« 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です。
byteSequence を、chunk をbase64としてdecodingした結果のunique sequence of 3 bytesとする(すなわち、byteSequence にRFC 4648 のsection 4でspecifiedされるbase64 encodingをapplyingするとchunk をproduceするようなsequence)。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:
maxLength がpresentでないなら、maxLength を253 - 1に設定する。NOTE : inputはStringであるため、Stringsのlengthは253 - 1 charactersにlimitedされ、outputはinputが持つcharactersより多くのbytesを必要としないので、このlimitに達することは決してない。しかし、maxLength にfinite valueを使用することはeditorially convenientである。NOTE : 下のalgorithmにおけるvalidationおよびdecodingのorderはobservableではない。Implementationsは、最もefficientなorderでそれらをperformすることがencouragedされ、possibly validationとdecodingをinterleavingしてもよい。maxLength = 0なら、Record { [[Read]] : 0, [[Bytes]] : « », [[Error]] : none }を返す。read を0とする。bytes を新しい空のList とする。chunk をempty Stringとする。chunkLength を0とする。index を0とする。length をstring のlengthとする。繰り返す、Assert : bytes 内のelementsの数は3でevenly divisibleである。index をSkipAsciiWhitespace (string , index )に設定する。index = length なら、chunkLength > 0なら、lastChunkHandling が"stop-before-partial" なら、Record { [[Read]] : read , [[Bytes]] : bytes , [[Error]] : none }を返す。lastChunkHandling が"strict" なら、error をnewly created SyntaxError objectとする。Record { [[Read]] : read , [[Bytes]] : bytes , [[Error]] : error }を返す。Assert : lastChunkHandling は"loose" である。chunkLength = 1なら、error をnewly created SyntaxError objectとする。Record { [[Read]] : read , [[Bytes]] : bytes , [[Error]] : error }を返す。bytes を、bytes と ! DecodeFinalBase64Chunk (chunk , false ) のlist-concatenation に設定する。Record { [[Read]] : length , [[Bytes]] : bytes , [[Error]] : none }を返す。char をstring のindex からindex + 1までのsubstring とする。index をindex + 1に設定する。char が"=" なら、chunkLength < 2なら、error をnewly created SyntaxError objectとする。Record { [[Read]] : read , [[Bytes]] : bytes , [[Error]] : error }を返す。index をSkipAsciiWhitespace (string , index )に設定する。chunkLength = 2なら、index = length なら、lastChunkHandling が"stop-before-partial" なら、Record { [[Read]] : read , [[Bytes]] : bytes , [[Error]] : none }を返す。error をnewly created SyntaxError objectとする。Record { [[Read]] : read , [[Bytes]] : bytes , [[Error]] : error }を返す。char をstring のindex からindex + 1までのsubstring に設定する。char が"=" なら、index をSkipAsciiWhitespace (string , index + 1)に設定する。index < length なら、error をnewly created SyntaxError objectとする。Record { [[Read]] : read , [[Bytes]] : bytes , [[Error]] : error }を返す。lastChunkHandling が"strict" なら、throwOnExtraBits をtrue とする;そうでなければ、throwOnExtraBits をfalse とする。decodeResult をCompletion (DecodeFinalBase64Chunk (chunk , throwOnExtraBits ))とする。decodeResult がabrupt completion なら、error をdecodeResult .[[Value]] とする。Record { [[Read]] : read , [[Bytes]] : bytes , [[Error]] : error }を返す。bytes を、bytes と ! decodeResult のlist-concatenation に設定する。Record { [[Read]] : length , [[Bytes]] : bytes , [[Error]] : none }を返す。alphabet が"base64url" なら、char が"+" または"/" のいずれかなら、error をnewly created SyntaxError objectとする。Record { [[Read]] : read , [[Bytes]] : bytes , [[Error]] : error }を返す。そうでなく、char が"-" なら、char を"+" に設定する。 そうでなく、char が"_" なら、char を"/" に設定する。 char のsole code unitがstandard base64 alphabet のelementでないなら、error をnewly created SyntaxError objectとする。Record { [[Read]] : read , [[Bytes]] : bytes , [[Error]] : error }を返す。remaining をmaxLength - bytes 内のelementsの数とする。remaining = 1かつchunkLength = 2の場合、またはremaining = 2かつchunkLength = 3の場合、Record { [[Read]] : read , [[Bytes]] : bytes , [[Error]] : none }を返す。chunk をchunk とchar のstring-concatenation に設定する。chunkLength をchunk のlengthに設定する。chunkLength = 4なら、bytes を、bytes とDecodeFullLengthBase64Chunk (chunk )のlist-concatenation に設定する。chunk をempty Stringに設定する。chunkLength を0に設定する。read をindex に設定する。bytes 内のelementsの数 = maxLength なら、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:
maxLength がpresentでないなら、maxLength を253 - 1に設定する。length をstring のlengthとする。bytes を新しい空のList とする。read を0とする。length modulo 2 ≠ 0なら、error をnewly created SyntaxError objectとする。Record { [[Read]] : read , [[Bytes]] : bytes , [[Error]] : error }を返す。read < length であり、かつbytes 内のelementsの数 < maxLength である間、繰り返すhexits をstring のread からread + 2までのsubstring とする。hexits が"0123456789abcdefABCDEF" 内にないcode unitsを含むなら、error をnewly created SyntaxError objectとする。Record { [[Read]] : read , [[Bytes]] : bytes , [[Error]] : error }を返す。read をread + 2に設定する。byte を、values 10 through 15のdigitsとしてletters A through F およびa through f を使用するbase-16 notationでhexits によりrepresentedされるinteger valueとする。byte をbytes へappendする。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を実行する:
NewTargetがundefined なら、TypeError 例外をthrowする。 map を ? OrdinaryCreateFromConstructor (NewTarget, "%Map.prototype%" , « [[MapData]] ») とする。map .[[MapData]] を新しい空のList に設定する。iterable がundefined またはnull のどちらかなら、map を返す。adder を ? Get (map , "set" ) とする。IsCallable (adder )がfalse なら、TypeError 例外をthrowする。? 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:
iteratorRecord を ? GetIterator (iterable , sync ) とする。繰り返す、next を ? IteratorStepValue (iteratorRecord ) とする。next がdone なら、target を返す。next がObjectでないなら、error をThrowCompletion (newly created TypeError object)とする。? IteratorClose (iteratorRecord , error )を返す。 key をCompletion (Get (next , "0" ))とする。IfAbruptCloseIterator (key , iteratorRecord )。value をCompletion (Get (next , "1" ))とする。IfAbruptCloseIterator (value , iteratorRecord )。status をCompletion (Call (adder , target , « key , value »))とする。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 は:
24.1.2.1 Map.groupBy ( items , callback )
Note
callback はtwo argumentsをacceptするfunctionであるべきである。groupByはitems 内の各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を実行する:
groups を ? GroupBy (items , callback , collection ) とする。map を ! Construct (%Map% ) とする。groups の各Record { [[Key]] , [[Elements]] } group について、以下を行うelements をCreateArrayFromList (group .[[Elements]] )とする。entry をRecord { [[Key]] : group .[[Key]] , [[Value]] : elements }とする。entry をmap .[[MapData]] へappendする。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を実行する:
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 は:
24.1.3.1 Map.prototype.clear ( )
このmethodは、呼び出されたときに次のstepsを実行する:
map をthis valueとする。? RequireInternalSlot (map , [[MapData]] )を実行する。 map .[[MapData]] の各Record { [[Key]] , [[Value]] } entry について、以下を行うentry .[[Key]] をempty に設定する。entry .[[Value]] をempty に設定する。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を実行する:
map をthis valueとする。? RequireInternalSlot (map , [[MapData]] )を実行する。 key をCanonicalizeKeyedCollectionKey (key )に設定する。map .[[MapData]] の各Record { [[Key]] , [[Value]] } entry について、以下を行うentry .[[Key]] がempty でなく、SameValue (entry .[[Key]] , key )がtrue なら、entry .[[Key]] をempty に設定する。entry .[[Value]] をempty に設定する。true を返す。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を実行する:
map をthis valueとする。? CreateMapIterator (map , key+value )を返す。
24.1.3.5 Map.prototype.forEach ( callback [ , thisArg ] )
このmethodは、呼び出されたときに次のstepsを実行する:
map をthis valueとする。? RequireInternalSlot (map , [[MapData]] )を実行する。 IsCallable (callback )がfalse なら、TypeError 例外をthrowする。entries をmap .[[MapData]] とする。entriesCount をentries 内のelementsの数とする。index を0とする。index < entriesCount の間、繰り返すentry をentries [index ]とする。index をindex + 1に設定する。entry .[[Key]] がempty でないなら、? Call (callback , thisArg , « entry .[[Value]] , entry .[[Key]] , map »)を実行する。 NOTE : entries 内のelementsの数はcallback のexecution中に増加しているかもしれない。entriesCount をentries 内のelementsの数に設定する。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を実行する:
map をthis valueとする。? RequireInternalSlot (map , [[MapData]] )を実行する。 key をCanonicalizeKeyedCollectionKey (key )に設定する。map .[[MapData]] の各Record { [[Key]] , [[Value]] } entry について、以下を行うentry .[[Key]] がempty でなく、SameValue (entry .[[Key]] , key )がtrue なら、entry .[[Value]] を返す。undefined を返す。
24.1.3.7 Map.prototype.getOrInsert ( key , value )
このmethodは、呼び出されたときに次のstepsを実行する:
map をthis valueとする。? RequireInternalSlot (map , [[MapData]] )を実行する。 key をCanonicalizeKeyedCollectionKey (key )に設定する。map .[[MapData]] の各Record { [[Key]] , [[Value]] } entry について、以下を行うentry .[[Key]] がempty でなく、SameValue (entry .[[Key]] , key )がtrue なら、entry .[[Value]] を返す。entry をRecord { [[Key]] : key , [[Value]] : value }とする。entry をmap .[[MapData]] へappendする。value を返す。
24.1.3.8 Map.prototype.getOrInsertComputed ( key , callback )
このmethodは、呼び出されたときに次のstepsを実行する:
map をthis valueとする。? RequireInternalSlot (map , [[MapData]] )を実行する。 IsCallable (callback )がfalse なら、TypeError 例外をthrowする。key をCanonicalizeKeyedCollectionKey (key )に設定する。map .[[MapData]] の各Record { [[Key]] , [[Value]] } entry について、以下を行うentry .[[Key]] がempty でなく、SameValue (entry .[[Key]] , key )がtrue なら、entry .[[Value]] を返す。value を ? Call (callback , undefined , « key ») とする。NOTE : Mapはcallback のexecution中にmodifiedされているかもしれない。map .[[MapData]] の各Record { [[Key]] , [[Value]] } entry について、以下を行うentry .[[Key]] がempty でなく、SameValue (entry .[[Key]] , key )がtrue なら、entry .[[Value]] をvalue に設定する。value を返す。entry をRecord { [[Key]] : key , [[Value]] : value }とする。entry をmap .[[MapData]] へappendする。value を返す。
24.1.3.9 Map.prototype.has ( key )
このmethodは、呼び出されたときに次のstepsを実行する:
map をthis valueとする。? RequireInternalSlot (map , [[MapData]] )を実行する。 key をCanonicalizeKeyedCollectionKey (key )に設定する。map .[[MapData]] の各Record { [[Key]] , [[Value]] } entry について、以下を行うentry .[[Key]] がempty でなく、SameValue (entry .[[Key]] , key )がtrue なら、true を返す。false を返す。
24.1.3.10 Map.prototype.keys ( )
このmethodは、呼び出されたときに次のstepsを実行する:
map をthis valueとする。? CreateMapIterator (map , key )を返す。
24.1.3.11 Map.prototype.set ( key , value )
このmethodは、呼び出されたときに次のstepsを実行する:
map をthis valueとする。? RequireInternalSlot (map , [[MapData]] )を実行する。 key をCanonicalizeKeyedCollectionKey (key )に設定する。map .[[MapData]] の各Record { [[Key]] , [[Value]] } entry について、以下を行うentry .[[Key]] がempty でなく、SameValue (entry .[[Key]] , key )がtrue なら、entry .[[Value]] をvalue に設定する。map を返す。entry をRecord { [[Key]] : key , [[Value]] : value }とする。entry をmap .[[MapData]] へappendする。map を返す。
24.1.3.12 get Map.prototype.size
Map.prototype.sizeは、set accessor functionがundefined であるaccessor property である。そのget accessor functionは、呼び出されたときに次のstepsを実行する:
map をthis valueとする。? RequireInternalSlot (map , [[MapData]] )を実行する。 count を0とする。map .[[MapData]] の各Record { [[Key]] , [[Value]] } entry について、以下を行うentry .[[Key]] がempty でないなら、count をcount + 1に設定する。𝔽 (count )を返す。
24.1.3.13 Map.prototype.values ( )
このmethodは、呼び出されたときに次のstepsを実行する:
map をthis valueとする。? 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するそのようなiterators のiterator objects をcreateするために使用される。 It performs the following steps when called:
? RequireInternalSlot (map , [[MapData]] )を実行する。 closure を、parametersを持たず、map およびkind をcapturesし、呼び出されたときに次のstepsを実行する新しいAbstract Closure とする:entries をmap .[[MapData]] とする。index を0とする。entriesCount をentries 内のelementsの数とする。index < entriesCount の間、繰り返すentry をentries [index ]とする。index をindex + 1に設定する。entry .[[Key]] がempty でないなら、kind がkey なら、result をentry .[[Key]] とする。そうでなく、kind がvalue なら、result をentry .[[Value]] とする。 そうでなければ、Assert : kind はkey+value である。result をCreateArrayFromList (« entry .[[Key]] , entry .[[Value]] »)とする。 ? GeneratorYield (CreateIteratorResultObject (result , false ))を実行する。 NOTE : このabstract operationのexecutionがGeneratorYield によりpausedされている間に、entries 内のelementsの数が増加しているかもしれない。entriesCount をentries 内のelementsの数に設定する。NormalCompletion (unused )を返す。CreateIteratorFromClosure (closure , "%MapIteratorPrototype%" , %MapIteratorPrototype% )を返す。
24.1.5.2 %MapIteratorPrototype% Object
%MapIteratorPrototype% objectは:
24.1.5.2.1 %MapIteratorPrototype%.next ( )
? 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 objects はECMAScript 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:
obj がObjectでないなら、TypeError 例外をthrowする。rawSize を ? Get (obj , "size" ) とする。numberSize を ? ToNumber (rawSize ) とする。NOTE : rawSize がundefined なら、numberSize はNaN になる。numberSize がNaN なら、TypeError 例外をthrowする。intSize を ! ToIntegerOrInfinity (numberSize ) とする。intSize < 0なら、RangeError 例外をthrowする。has を ? Get (obj , "has" ) とする。IsCallable (has )がfalse なら、TypeError 例外をthrowする。keys を ? Get (obj , "keys" ) とする。IsCallable (keys )がfalse なら、TypeError 例外をthrowする。新しい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:
SetDataIndex (setData , value )がnot-found なら、false を返す。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:
value をCanonicalizeKeyedCollectionKey (value )に設定する。size をsetData 内のelementsの数とする。index を0とする。index < size の間、繰り返すelement をsetData [index ]とする。element がempty でなく、element がvalue であるなら、index を返す。index をindex + 1に設定する。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:
count を0とする。setData の各element element について、以下を行うelement がempty でないなら、count をcount + 1に設定する。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を実行する:
NewTargetがundefined なら、TypeError 例外をthrowする。 set を ? OrdinaryCreateFromConstructor (NewTarget, "%Set.prototype%" , « [[SetData]] ») とする。set .[[SetData]] を新しい空のList に設定する。iterable がundefined またはnull のどちらかなら、set を返す。adder を ? Get (set , "add" ) とする。IsCallable (adder )がfalse なら、TypeError 例外をthrowする。iteratorRecord を ? GetIterator (iterable , sync ) とする。繰り返す、next を ? IteratorStepValue (iteratorRecord ) とする。next がdone なら、set を返す。status をCompletion (Call (adder , set , « next »))とする。IfAbruptCloseIterator (status , iteratorRecord )。
24.2.3 Set Constructorのプロパティ
Set constructor は:
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を実行する:
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 は:
24.2.4.1 Set.prototype.add ( value )
このmethodは、呼び出されたときに次のstepsを実行する:
set をthis valueとする。? RequireInternalSlot (set , [[SetData]] )を実行する。 value をCanonicalizeKeyedCollectionKey (value )に設定する。set .[[SetData]] の各element entry について、以下を行うentry がempty でなく、SameValue (entry , value )がtrue なら、set を返す。value をset .[[SetData]] へappendする。set を返す。
24.2.4.2 Set.prototype.clear ( )
このmethodは、呼び出されたときに次のstepsを実行する:
set をthis valueとする。? RequireInternalSlot (set , [[SetData]] )を実行する。 set .[[SetData]] の各element entry について、以下を行うvalueがentry であるset .[[SetData]] のelementを、valueがempty であるelementでreplaceする。 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を実行する:
set をthis valueとする。? RequireInternalSlot (set , [[SetData]] )を実行する。 value をCanonicalizeKeyedCollectionKey (value )に設定する。set .[[SetData]] の各element entry について、以下を行うentry がempty でなく、SameValue (entry , value )がtrue なら、valueがentry であるset .[[SetData]] のelementを、valueがempty であるelementでreplaceする。 true を返す。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を実行する:
set をthis valueとする。? RequireInternalSlot (set , [[SetData]] )を実行する。 otherRecord を ? GetSetRecord (other ) とする。resultSetData をset .[[SetData]] のcopyとする。SetDataSize (set .[[SetData]] ) ≤ otherRecord .[[Size]] なら、thisSize をset .[[SetData]] 内のelementsの数とする。index を0とする。index < thisSize の間、繰り返すentry をresultSetData [index ]とする。entry がempty でないなら、inOther をToBoolean (? Call (otherRecord .[[Has]] , otherRecord .[[SetObject]] , « entry »))とする。inOther がtrue なら、resultSetData [index ]をempty に設定する。index をindex + 1に設定する。そうでなければ、keysIterator を ? GetIteratorFromMethod (otherRecord .[[SetObject]] , otherRecord .[[Keys]] ) とする。next をnot-started とする。next がdone でない間、繰り返すnext を ? IteratorStepValue (keysIterator ) に設定する。next がdone でないなら、next をCanonicalizeKeyedCollectionKey (next )に設定する。valueIndex をSetDataIndex (resultSetData , next )とする。valueIndex がnot-found でないなら、resultSetData [valueIndex ]をempty に設定する。 result をOrdinaryObjectCreate (%Set.prototype% , « [[SetData]] »)とする。result .[[SetData]] をresultSetData に設定する。result を返す。
24.2.4.6 Set.prototype.entries ( )
このmethodは、呼び出されたときに次のstepsを実行する:
set をthis valueとする。? 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を実行する:
set をthis valueとする。? RequireInternalSlot (set , [[SetData]] )を実行する。 IsCallable (callback )がfalse なら、TypeError 例外をthrowする。entries をset .[[SetData]] とする。entriesCount をentries 内のelementsの数とする。index を0とする。index < entriesCount の間、繰り返すentry をentries [index ]とする。index をindex + 1に設定する。entry がempty でないなら、? Call (callback , thisArg , « entry , entry , set »)を実行する。 NOTE : entries 内のelementsの数はcallback のexecution中に増加しているかもしれない。entriesCount をentries 内のelementsの数に設定する。undefined を返す。
Note
callback はthree argumentsをacceptするfunctionであるべきである。forEachはSet 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を実行する:
set をthis valueとする。? RequireInternalSlot (set , [[SetData]] )を実行する。 value をCanonicalizeKeyedCollectionKey (value )に設定する。set .[[SetData]] の各element entry について、以下を行うentry がempty でなく、SameValue (entry , value )がtrue なら、true を返す。false を返す。
24.2.4.9 Set.prototype.intersection ( other )
このmethodは、呼び出されたときに次のstepsを実行する:
set をthis valueとする。? RequireInternalSlot (set , [[SetData]] )を実行する。 otherRecord を ? GetSetRecord (other ) とする。resultSetData を新しい空のList とする。SetDataSize (set .[[SetData]] ) ≤ otherRecord .[[Size]] なら、thisSize をset .[[SetData]] 内のelementsの数とする。index を0とする。index < thisSize の間、繰り返すentry をset .[[SetData]] [index ]とする。index をindex + 1に設定する。entry がempty でないなら、inOther をToBoolean (? Call (otherRecord .[[Has]] , otherRecord .[[SetObject]] , « entry »))とする。inOther がtrue なら、NOTE : otherRecord .[[Has]] へのearlier callsがset .[[SetData]] のelementをremoveしてre-addすることがpossibleであり、それによりこのiteration中に同じelementがtwice visitedされる可能性がある。SetDataHas (resultSetData , entry )がfalse なら、entry をresultSetData へappendする。NOTE : set .[[SetData]] 内のelementsの数はotherRecord .[[Has]] のexecution中に増加しているかもしれない。thisSize をset .[[SetData]] 内のelementsの数に設定する。そうでなければ、keysIterator を ? GetIteratorFromMethod (otherRecord .[[SetObject]] , otherRecord .[[Keys]] ) とする。next をnot-started とする。next がdone でない間、繰り返すnext を ? IteratorStepValue (keysIterator ) に設定する。next がdone でないなら、next をCanonicalizeKeyedCollectionKey (next )に設定する。inThis をSetDataHas (set .[[SetData]] , next )とする。inThis がtrue なら、NOTE : other はarbitrary objectであるため、その"keys" iterator が同じvalueを複数回produceすることがpossibleである。SetDataHas (resultSetData , next )がfalse なら、next をresultSetData へappendする。 result をOrdinaryObjectCreate (%Set.prototype% , « [[SetData]] »)とする。result .[[SetData]] をresultSetData に設定する。result を返す。
24.2.4.10 Set.prototype.isDisjointFrom ( other )
このmethodは、呼び出されたときに次のstepsを実行する:
set をthis valueとする。? RequireInternalSlot (set , [[SetData]] )を実行する。 otherRecord を ? GetSetRecord (other ) とする。SetDataSize (set .[[SetData]] ) ≤ otherRecord .[[Size]] なら、thisSize をset .[[SetData]] 内のelementsの数とする。index を0とする。index < thisSize の間、繰り返すentry をset .[[SetData]] [index ]とする。index をindex + 1に設定する。entry がempty でないなら、inOther をToBoolean (? Call (otherRecord .[[Has]] , otherRecord .[[SetObject]] , « entry »))とする。inOther がtrue なら、false を返す。NOTE : set .[[SetData]] 内のelementsの数はotherRecord .[[Has]] のexecution中に増加しているかもしれない。thisSize をset .[[SetData]] 内のelementsの数に設定する。そうでなければ、keysIterator を ? GetIteratorFromMethod (otherRecord .[[SetObject]] , otherRecord .[[Keys]] ) とする。next をnot-started とする。next がdone でない間、繰り返すnext を ? IteratorStepValue (keysIterator ) に設定する。next がdone でないなら、SetDataHas (set .[[SetData]] , next )がtrue なら、? IteratorClose (keysIterator , NormalCompletion (unused ))を実行する。 false を返す。 true を返す。
24.2.4.11 Set.prototype.isSubsetOf ( other )
このmethodは、呼び出されたときに次のstepsを実行する:
set をthis valueとする。? RequireInternalSlot (set , [[SetData]] )を実行する。 otherRecord を ? GetSetRecord (other ) とする。SetDataSize (set .[[SetData]] ) > otherRecord .[[Size]] なら、false を返す。thisSize をset .[[SetData]] 内のelementsの数とする。index を0とする。index < thisSize の間、繰り返すentry をset .[[SetData]] [index ]とする。index をindex + 1に設定する。entry がempty でないなら、inOther をToBoolean (? Call (otherRecord .[[Has]] , otherRecord .[[SetObject]] , « entry »))とする。inOther がfalse なら、false を返す。NOTE : set .[[SetData]] 内のelementsの数はotherRecord .[[Has]] のexecution中に増加しているかもしれない。thisSize をset .[[SetData]] 内のelementsの数に設定する。true を返す。
24.2.4.12 Set.prototype.isSupersetOf ( other )
このmethodは、呼び出されたときに次のstepsを実行する:
set をthis valueとする。? RequireInternalSlot (set , [[SetData]] )を実行する。 otherRecord を ? GetSetRecord (other ) とする。SetDataSize (set .[[SetData]] ) < otherRecord .[[Size]] なら、false を返す。keysIterator を ? GetIteratorFromMethod (otherRecord .[[SetObject]] , otherRecord .[[Keys]] ) とする。next をnot-started とする。next がdone でない間、繰り返すnext を ? IteratorStepValue (keysIterator ) に設定する。next がdone でないなら、SetDataHas (set .[[SetData]] , next )がfalse なら、? IteratorClose (keysIterator , NormalCompletion (unused ))を実行する。 false を返す。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を実行する:
set をthis valueとする。? RequireInternalSlot (set , [[SetData]] )を実行する。 size をSetDataSize (set .[[SetData]] )とする。𝔽 (size )を返す。
24.2.4.15 Set.prototype.symmetricDifference ( other )
このmethodは、呼び出されたときに次のstepsを実行する:
set をthis valueとする。? RequireInternalSlot (set , [[SetData]] )を実行する。 otherRecord を ? GetSetRecord (other ) とする。keysIterator を ? GetIteratorFromMethod (otherRecord .[[SetObject]] , otherRecord .[[Keys]] ) とする。resultSetData をset .[[SetData]] のcopyとする。next をnot-started とする。next がdone でない間、繰り返すnext を ? IteratorStepValue (keysIterator ) に設定する。next がdone でないなら、next をCanonicalizeKeyedCollectionKey (next )に設定する。resultIndex をSetDataIndex (resultSetData , next )とする。resultIndex がnot-found なら、alreadyInResult をfalse とする;そうでなければ、alreadyInResult をtrue とする。SetDataHas (set .[[SetData]] , next )がtrue なら、alreadyInResult がtrue なら、resultSetData [resultIndex ]をempty に設定する。そうでなければ、alreadyInResult がfalse なら、next をresultSetData へappendする。 result をOrdinaryObjectCreate (%Set.prototype% , « [[SetData]] »)とする。result .[[SetData]] をresultSetData に設定する。result を返す。
24.2.4.16 Set.prototype.union ( other )
このmethodは、呼び出されたときに次のstepsを実行する:
set をthis valueとする。? RequireInternalSlot (set , [[SetData]] )を実行する。 otherRecord を ? GetSetRecord (other ) とする。keysIterator を ? GetIteratorFromMethod (otherRecord .[[SetObject]] , otherRecord .[[Keys]] ) とする。resultSetData をset .[[SetData]] のcopyとする。next をnot-started とする。next がdone でない間、繰り返すnext を ? IteratorStepValue (keysIterator ) に設定する。next がdone でないなら、next をCanonicalizeKeyedCollectionKey (next )に設定する。SetDataHas (resultSetData , next )がfalse なら、next をresultSetData へappendする。result をOrdinaryObjectCreate (%Set.prototype% , « [[SetData]] »)とする。result .[[SetData]] をresultSetData に設定する。result を返す。
24.2.4.17 Set.prototype.values ( )
このmethodは、呼び出されたときに次のstepsを実行する:
set をthis valueとする。? 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するそのようなiterators のiterator objects をcreateするために使用される。 It performs the following steps when called:
? RequireInternalSlot (set , [[SetData]] )を実行する。 closure を、parametersを持たず、set およびkind をcapturesし、呼び出されたときに次のstepsを実行する新しいAbstract Closure とする:index を0とする。entries をset .[[SetData]] とする。entriesCount をentries 内のelementsの数とする。index < entriesCount の間、繰り返すentry をentries [index ]とする。index をindex + 1に設定する。entry がempty でないなら、kind がkey+value なら、result をCreateArrayFromList (« entry , entry »)とする。? GeneratorYield (CreateIteratorResultObject (result , false ))を実行する。 そうでなければ、Assert : kind はvalue である。? GeneratorYield (CreateIteratorResultObject (entry , false ))を実行する。 NOTE : このabstract operationのexecutionがGeneratorYield によりpausedされている間に、entries 内のelementsの数が増加しているかもしれない。entriesCount をentries 内のelementsの数に設定する。NormalCompletion (unused )を返す。CreateIteratorFromClosure (closure , "%SetIteratorPrototype%" , %SetIteratorPrototype% )を返す。
24.2.6.2 %SetIteratorPrototype% Object
%SetIteratorPrototype% objectは:
24.2.6.2.1 %SetIteratorPrototype%.next ( )
? 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を実行する:
NewTargetがundefined なら、TypeError 例外をthrowする。 map を ? OrdinaryCreateFromConstructor (NewTarget, "%WeakMap.prototype%" , « [[WeakMapData]] ») とする。map .[[WeakMapData]] を新しい空のList に設定する。iterable がundefined またはnull のどちらかなら、map を返す。adder を ? Get (map , "set" ) とする。IsCallable (adder )がfalse なら、TypeError 例外をthrowする。? 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 は:
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 は:
24.3.3.1 WeakMap.prototype.constructor
WeakMap.prototype.constructorのinitial valueは%WeakMap% である。
24.3.3.2 WeakMap.prototype.delete ( key )
このmethodは、呼び出されたときに次のstepsを実行する:
weakMap をthis valueとする。? RequireInternalSlot (weakMap , [[WeakMapData]] )を実行する。 CanBeHeldWeakly (key )がfalse なら、false を返す。weakMap .[[WeakMapData]] の各Record { [[Key]] , [[Value]] } entry について、以下を行うentry .[[Key]] がempty でなく、SameValue (entry .[[Key]] , key )がtrue なら、entry .[[Key]] をempty に設定する。entry .[[Value]] をempty に設定する。true を返す。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を実行する:
weakMap をthis valueとする。? RequireInternalSlot (weakMap , [[WeakMapData]] )を実行する。 CanBeHeldWeakly (key )がfalse なら、undefined を返す。weakMap .[[WeakMapData]] の各Record { [[Key]] , [[Value]] } entry について、以下を行うentry .[[Key]] がempty でなく、SameValue (entry .[[Key]] , key )がtrue なら、entry .[[Value]] を返す。undefined を返す。
24.3.3.4 WeakMap.prototype.getOrInsert ( key , value )
このmethodは、呼び出されたときに次のstepsを実行する:
weakMap をthis valueとする。? RequireInternalSlot (weakMap , [[WeakMapData]] )を実行する。 CanBeHeldWeakly (key )がfalse なら、TypeError 例外をthrowする。weakMap .[[WeakMapData]] の各Record { [[Key]] , [[Value]] } entry について、以下を行うentry .[[Key]] がempty でなく、SameValue (entry .[[Key]] , key )がtrue なら、entry .[[Value]] を返す。entry をRecord { [[Key]] : key , [[Value]] : value }とする。entry をweakMap .[[WeakMapData]] へappendする。value を返す。
24.3.3.5 WeakMap.prototype.getOrInsertComputed ( key , callback )
このmethodは、呼び出されたときに次のstepsを実行する:
weakMap をthis valueとする。? RequireInternalSlot (weakMap , [[WeakMapData]] )を実行する。 CanBeHeldWeakly (key )がfalse なら、TypeError 例外をthrowする。IsCallable (callback )がfalse なら、TypeError 例外をthrowする。weakMap .[[WeakMapData]] の各Record { [[Key]] , [[Value]] } entry について、以下を行うentry .[[Key]] がempty でなく、SameValue (entry .[[Key]] , key )がtrue なら、entry .[[Value]] を返す。value を ? Call (callback , undefined , « key ») とする。NOTE : WeakMapはcallback のexecution中にmodifiedされているかもしれない。weakMap .[[WeakMapData]] の各Record { [[Key]] , [[Value]] } entry について、以下を行うentry .[[Key]] がempty でなく、SameValue (entry .[[Key]] , key )がtrue なら、entry .[[Value]] をvalue に設定する。value を返す。entry をRecord { [[Key]] : key , [[Value]] : value }とする。entry をweakMap .[[WeakMapData]] へappendする。value を返す。
24.3.3.6 WeakMap.prototype.has ( key )
このmethodは、呼び出されたときに次のstepsを実行する:
weakMap をthis valueとする。? RequireInternalSlot (weakMap , [[WeakMapData]] )を実行する。 CanBeHeldWeakly (key )がfalse なら、false を返す。weakMap .[[WeakMapData]] の各Record { [[Key]] , [[Value]] } entry について、以下を行うentry .[[Key]] がempty でなく、SameValue (entry .[[Key]] , key )がtrue なら、true を返す。false を返す。
24.3.3.7 WeakMap.prototype.set ( key , value )
このmethodは、呼び出されたときに次のstepsを実行する:
weakMap をthis valueとする。? RequireInternalSlot (weakMap , [[WeakMapData]] )を実行する。 CanBeHeldWeakly (key )がfalse なら、TypeError 例外をthrowする。weakMap .[[WeakMapData]] の各Record { [[Key]] , [[Value]] } entry について、以下を行うentry .[[Key]] がempty でなく、SameValue (entry .[[Key]] , key )がtrue なら、entry .[[Value]] をvalue に設定する。weakMap を返す。entry をRecord { [[Key]] : key , [[Value]] : value }とする。entry をweakMap .[[WeakMapData]] へappendする。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.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を実行する:
NewTargetがundefined なら、TypeError 例外をthrowする。 set を ? OrdinaryCreateFromConstructor (NewTarget, "%WeakSet.prototype%" , « [[WeakSetData]] ») とする。set .[[WeakSetData]] を新しい空のList に設定する。iterable がundefined またはnull のどちらかなら、set を返す。adder を ? Get (set , "add" ) とする。IsCallable (adder )がfalse なら、TypeError 例外をthrowする。iteratorRecord を ? GetIterator (iterable , sync ) とする。繰り返す、next を ? IteratorStepValue (iteratorRecord ) とする。next がdone なら、set を返す。status をCompletion (Call (adder , set , « next »))とする。IfAbruptCloseIterator (status , iteratorRecord )。
24.4.2 WeakSet Constructorのプロパティ
WeakSet constructor は:
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 は:
24.4.3.1 WeakSet.prototype.add ( value )
このmethodは、呼び出されたときに次のstepsを実行する:
weakSet をthis valueとする。? RequireInternalSlot (weakSet , [[WeakSetData]] )を実行する。 CanBeHeldWeakly (value )がfalse なら、TypeError 例外をthrowする。weakSet .[[WeakSetData]] の各element entry について、以下を行うentry がempty でなく、SameValue (entry , value )がtrue なら、weakSet を返す。value をweakSet .[[WeakSetData]] へappendする。weakSet を返す。
24.4.3.2 WeakSet.prototype.constructor
WeakSet.prototype.constructorのinitial valueは%WeakSet% である。
24.4.3.3 WeakSet.prototype.delete ( value )
このmethodは、呼び出されたときに次のstepsを実行する:
weakSet をthis valueとする。? RequireInternalSlot (weakSet , [[WeakSetData]] )を実行する。 CanBeHeldWeakly (value )がfalse なら、false を返す。weakSet .[[WeakSetData]] の各element entry について、以下を行うentry がempty でなく、SameValue (entry , value )がtrue なら、valueがentry であるweakSet .[[WeakSetData]] のelementを、valueがempty であるelementでreplaceする。 true を返す。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を実行する:
weakSet をthis valueとする。? RequireInternalSlot (weakSet , [[WeakSetData]] )を実行する。 CanBeHeldWeakly (value )がfalse なら、false を返す。weakSet .[[WeakSetData]] の各element entry について、以下を行うentry がempty でなく、SameValue (entry , value )がtrue なら、true を返す。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:
key が-0 𝔽 なら、+0 𝔽 を返す。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 values のList を返す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:
Let slots be « [[ArrayBufferData]] , [[ArrayBufferByteLength]] , [[ArrayBufferDetachKey]] ». If maxByteLength is present and maxByteLength is not empty , let allocatingResizableBuffer be true ; else let allocatingResizableBuffer be false . If allocatingResizableBuffer is true , thenIf byteLength > maxByteLength , throw a RangeError exception. Append [[ArrayBufferMaxByteLength]] to slots . Let obj be ? OrdinaryCreateFromConstructor (ctor , "%ArrayBuffer.prototype%" , slots ). Let block be ? CreateByteDataBlock (byteLength ). Set obj .[[ArrayBufferData]] to block . Set obj .[[ArrayBufferByteLength]] to byteLength . If allocatingResizableBuffer is true , thenIf it is not possible to create a Data Block block consisting of maxByteLength bytes, throw a RangeError exception. 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.Set obj .[[ArrayBufferMaxByteLength]] to maxByteLength . 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:
IsGrowableSharedArrayBuffer (arrayBuffer ) が true である場合、bufferByteLengthBlock を arrayBuffer .[[ArrayBufferByteLengthData]] とする。rawLength を GetRawBytesFromSharedBlock (bufferByteLengthBlock , 0, biguint64 , true , order ) とする。agentRecord を周囲のエージェントのAgent Record とする。isLittleEndian を agentRecord .[[LittleEndian]] とする。ℝ (RawBytesToNumeric (biguint64 , rawLength , isLittleEndian )) を返す。アサート: IsDetachedBuffer (arrayBuffer ) は false である。 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:
? RequireInternalSlot (arrayBuffer , [[ArrayBufferData]] ) を実行する。 IsSharedArrayBuffer (arrayBuffer ) が true である場合、TypeError 例外を投げる。newLength が undefined である場合、newByteLength を arrayBuffer .[[ArrayBufferByteLength]] とする。そうでなければ、newByteLength を ? ToIndex (newLength ) とする。 IsDetachedBuffer (arrayBuffer ) が true である場合、TypeError 例外を投げる。preserveResizability が preserve-resizability であり、かつ IsFixedLengthArrayBuffer (arrayBuffer ) が false である場合、newMaxByteLength を arrayBuffer .[[ArrayBufferMaxByteLength]] とする。そうでなければ、newMaxByteLength を empty とする。 arrayBuffer .[[ArrayBufferDetachKey]] が undefined でない場合、TypeError 例外を投げる。newBuffer を ? AllocateArrayBuffer (%ArrayBuffer% , newByteLength , newMaxByteLength ) とする。copyLength を min (newByteLength , arrayBuffer .[[ArrayBufferByteLength]] ) とする。fromBlock を arrayBuffer .[[ArrayBufferData]] とする。toBlock を newBuffer .[[ArrayBufferData]] とする。CopyDataBlockBytes (toBlock , 0, fromBlock , 0, copyLength ) を実行する。注記: 新しいData Block の作成も、古いData Block からのコピーも観測可能ではない。実装はこのメソッドをゼロコピーの移動または realloc として実装してもよい。 ! DetachArrayBuffer (arrayBuffer ) を実行する。 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:
arrayBuffer .[[ArrayBufferData]] が null である場合、true を返す。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:
アサート: IsSharedArrayBuffer (arrayBuffer ) は false である。 key が存在しない場合、key を undefined に設定する。arrayBuffer .[[ArrayBufferDetachKey]] が key でない場合、TypeError 例外を投げる。arrayBuffer .[[ArrayBufferData]] を null に設定する。arrayBuffer .[[ArrayBufferByteLength]] を 0 に設定する。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:
アサート: IsDetachedBuffer (sourceBuffer ) は false である。 targetBuffer を ? AllocateArrayBuffer (%ArrayBuffer% , sourceLength ) とする。sourceBlock を sourceBuffer .[[ArrayBufferData]] とする。targetBlock を targetBuffer .[[ArrayBufferData]] とする。CopyDataBlockBytes (targetBlock , 0, sourceBlock , sourceByteOffset , sourceLength ) を実行する。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:
options がObjectでない場合、empty を返す。maxByteLength を ? Get (options , "maxByteLength" ) とする。maxByteLength が undefined である場合、empty を返す。? 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:
arrayBuffer が [[ArrayBufferMaxByteLength]] 内部スロットを持つ場合、false を返す。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:
type が uint8 , uint8clamped , uint16 , uint32 , または biguint64 のいずれかである場合、true を返す。false を返す。
25.1.3.11 IsUnclampedIntegerElementType ( type )
The abstract operation IsUnclampedIntegerElementType takes argument type (TypedArray 要素型) and returns Boolean. これは、引数 type が uint8clamped を含まないInteger TypedArray 要素型であるかどうかを検証する。 It performs the following steps when called:
type が int8 , uint8 , int16 , uint16 , int32 , または uint32 のいずれかである場合、true を返す。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:
type が biguint64 または bigint64 のいずれかである場合、true を返す。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:
IsUnclampedIntegerElementType (type ) が true である場合、true を返す。IsBigIntElementType (type ) が true であり、かつ order が init でも unordered でもない場合、true を返す。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:
elementSize を、Element Type type に対して Table 71 で指定されるElement Size値とする。isLittleEndian が false である場合、rawBytes の要素の順序を反転する。type が float16 である場合、value を、rawBytes のバイト要素を連結し、IEEE 754-2019 binary16値のリトルエンディアン・ビット列エンコードとして解釈したものとする。value がNaNである場合、NaN を返す。value に対応するNumber値を返す。type が float32 である場合、value を、rawBytes のバイト要素を連結し、IEEE 754-2019 binary32値のリトルエンディアン・ビット列エンコードとして解釈したものとする。value がNaNである場合、NaN を返す。value に対応するNumber値を返す。type が float64 である場合、value を、rawBytes のバイト要素を連結し、IEEE 754-2019 binary64値のリトルエンディアン・ビット列エンコードとして解釈したものとする。value がNaNである場合、NaN を返す。value に対応するNumber値を返す。IsUnsignedElementType (type ) が true である場合、intValue を、rawBytes のバイト要素を連結し、符号なしリトルエンディアン二進数のビット列エンコードとして解釈したものとする。そうでなければ、intValue を、rawBytes のバイト要素を連結し、ビット長 elementSize × 8 の二進リトルエンディアン2の補数のビット列エンコードとして解釈したものとする。 IsBigIntElementType (type ) が true である場合、intValue に対応するBigInt値を返す。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:
elementSize を、Element Type type に対して Table 71 で指定されるElement Size値とする。agentRecord を周囲のエージェントのAgent Record とする。execution を agentRecord .[[CandidateExecution]] とする。eventsRecord を、execution .[[EventsRecords]] のうち [[AgentSignifier]] が AgentSignifier () であるAgent Events Record とする。isTypedArray が true であり、かつ IsNoTearConfiguration (type , order ) が true である場合、noTear を true とする。そうでなければ noTear を false とする。rawValue を、要素が非決定的に選択されたバイト値である、長さ elementSize のList とする。注記: 実装では、rawValue は基礎となるハードウェア上の非アトミックまたはアトミック読み取り命令の結果である。非決定性は、弱い一貫性を持つハードウェアの観測可能な振る舞いを記述するための、メモリモデルの意味論的規定である。 readEvent を ReadSharedMemory { [[Order]] : order , [[NoTear]] : noTear , [[Block]] : block , [[ByteIndex]] : byteIndex , [[ElementSize]] : elementSize } とする。readEvent を eventsRecord .[[EventList]] に追加する。Chosen Value Record { [[Event]] : readEvent , [[ChosenValue]] : rawValue } を execution .[[ChosenValues]] に追加する。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:
アサート: IsDetachedBuffer (arrayBuffer ) は false である。 アサート: arrayBuffer には、byteIndex から始まり type の値を表現するのに十分なバイトがある。 block を arrayBuffer .[[ArrayBufferData]] とする。elementSize を、Element Type type に対して Table 71 で指定されるElement Size値とする。IsSharedArrayBuffer (arrayBuffer ) が true である場合、アサート: block はShared Data Block である。 rawValue を GetRawBytesFromSharedBlock (block , byteIndex , type , isTypedArray , order ) とする。そうでなければ、rawValue を、block 内の byteIndex (含む)から byteIndex + elementSize (含まない)までの区間のインデックスにあるバイトを要素とするList とする。 アサート: rawValue 内の要素数は elementSize である。 isLittleEndian が存在しない場合、agentRecord を周囲のエージェントのAgent Record とする。isLittleEndian を agentRecord .[[LittleEndian]] に設定する。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:
type が float16 である場合、rawBytes を、roundTiesToEvenモードを使用して value をIEEE 754-2019 binary16形式へ変換した結果である2バイトを要素とするList とする。これらのバイトはリトルエンディアン順に配置される。value が NaN である場合、rawBytes は実装が選択する任意のIEEE 754-2019 binary16形式のNaNエンコードに設定されてもよい。実装は、実装上区別可能な各 NaN 値に対して、常に同じエンコードを選択しなければならない。そうでなく type が float32 である場合、rawBytes を、roundTiesToEvenモードを使用して value をIEEE 754-2019 binary32形式へ変換した結果である4バイトを要素とするList とする。これらのバイトはリトルエンディアン順に配置される。value が NaN である場合、rawBytes は実装が選択する任意のIEEE 754-2019 binary32形式のNaNエンコードに設定されてもよい。実装は、実装上区別可能な各 NaN 値に対して、常に同じエンコードを選択しなければならない。 そうでなく type が float64 である場合、rawBytes を、value のIEEE 754-2019 binary64形式エンコードである8バイトを要素とするList とする。これらのバイトはリトルエンディアン順に配置される。value が NaN である場合、rawBytes は実装が選択する任意のIEEE 754-2019 binary64形式のNaNエンコードに設定されてもよい。実装は、実装上区別可能な各 NaN 値に対して、常に同じエンコードを選択しなければならない。 そうでなければ、n を、Element Type type に対して Table 71 で指定されるElement Size値とする。conversionOperation を、Element Type type に対して Table 71 の“Conversion Operation”列にある名前の抽象操作とする。intValue を ℝ (! conversionOperation (value )) とする。intValue ≥ 0 である場合、rawBytes を、intValue の n バイト二進エンコードを要素とするList とする。これらのバイトはリトルエンディアン順に並べられる。そうでなければ、rawBytes を、intValue の n バイト二進2の補数エンコードを要素とするList とする。これらのバイトはリトルエンディアン順に並べられる。 isLittleEndian が false である場合、rawBytes の要素の順序を反転する。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:
アサート: IsDetachedBuffer (arrayBuffer ) は false である。 アサート: arrayBuffer には、byteIndex から始まり type の値を表現するのに十分なバイトがある。 アサート: IsBigIntElementType (type ) が true である場合、value はBigIntであり、そうでなければ value はNumberである。 block を arrayBuffer .[[ArrayBufferData]] とする。elementSize を、Element Type type に対して Table 71 で指定されるElement Size値とする。agentRecord を周囲のエージェントのAgent Record とする。isLittleEndian が存在しない場合、isLittleEndian を agentRecord .[[LittleEndian]] に設定する。rawBytes を NumericToRawBytes (type , value , isLittleEndian ) とする。IsSharedArrayBuffer (arrayBuffer ) が true である場合、execution を agentRecord .[[CandidateExecution]] とする。eventsRecord を、execution .[[EventsRecords]] のうち [[AgentSignifier]] が AgentSignifier () であるAgent Events Record とする。isTypedArray が true であり、かつ IsNoTearConfiguration (type , order ) が true である場合、noTear を true とする。そうでなければ noTear を false とする。WriteSharedMemory { [[Order]] : order , [[NoTear]] : noTear , [[Block]] : block , [[ByteIndex]] : byteIndex , [[ElementSize]] : elementSize , [[Payload]] : rawBytes } を eventsRecord .[[EventList]] に追加する。そうでなければ、rawBytes の個々のバイトを、block [byteIndex ] から始めて block に格納する。 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:
アサート: IsDetachedBuffer (arrayBuffer ) は false である。 アサート: arrayBuffer には、byteIndex から始まり type の値を表現するのに十分なバイトがある。 アサート: IsBigIntElementType (type ) が true である場合、value はBigIntであり、そうでなければ value はNumberである。 block を arrayBuffer .[[ArrayBufferData]] とする。elementSize を、Element Type type に対して Table 71 で指定されるElement Size値とする。agentRecord を周囲のエージェントのAgent Record とする。isLittleEndian を agentRecord .[[LittleEndian]] とする。rawBytes を NumericToRawBytes (type , value , isLittleEndian ) とする。IsSharedArrayBuffer (arrayBuffer ) が true である場合、execution を agentRecord .[[CandidateExecution]] とする。eventsRecord を、execution .[[EventsRecords]] のうち [[AgentSignifier]] が AgentSignifier () であるAgent Events Record とする。rawBytesRead を、要素が非決定的に選択されたバイト値である、長さ elementSize のList とする。注記: 実装では、rawBytesRead は基礎となるハードウェア上のload-link、load-exclusive、または読み取り-変更-書き込み命令のオペランドの結果である。非決定性は、弱い一貫性を持つハードウェアの観測可能な振る舞いを記述するための、メモリモデルの意味論的規定である。 rmwEvent を ReadModifyWriteSharedMemory { [[Order]] : seq-cst , [[NoTear]] : true , [[Block]] : block , [[ByteIndex]] : byteIndex , [[ElementSize]] : elementSize , [[Payload]] : rawBytes , [[ModifyOp]] : op } とする。rmwEvent を eventsRecord .[[EventList]] に追加する。Chosen Value Record { [[Event]] : rmwEvent , [[ChosenValue]] : rawBytesRead } を execution .[[ChosenValues]] に追加する。そうでなければ、rawBytesRead を、block [byteIndex ] から始まる elementSize バイトの並びを要素とする、長さ elementSize のList とする。rawBytesModified を op (rawBytesRead , rawBytes ) とする。rawBytesModified の個々のバイトを、block [byteIndex ] から始めて block に格納する。 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を実行する:
NewTargetがundefined なら、TypeError 例外をthrowする。 byteLength を ? ToIndex (length ) とする。requestedMaxByteLength を ? GetArrayBufferMaxByteLengthOption (options ) とする。? AllocateArrayBuffer (NewTarget, byteLength , requestedMaxByteLength )を返す。
25.1.5 ArrayBuffer Constructorのプロパティ
ArrayBuffer constructor は:
25.1.5.1 ArrayBuffer.isView ( arg )
このfunctionは、呼び出されたときに以下のstepsを実行する:
arg がObjectでないなら、false を返す。arg が[[ViewedArrayBuffer]] internal slotを持つなら、true を返す。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を実行する:
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を実行する:
obj をthis valueとする。? RequireInternalSlot (obj , [[ArrayBufferData]] )を実行する。 IsSharedArrayBuffer (obj )がtrue なら、TypeError 例外をthrowする。IsDetachedBuffer (obj )がtrue なら、+0 𝔽 を返す。length をobj .[[ArrayBufferByteLength]] とする。𝔽 (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を実行する:
obj をthis valueとする。? RequireInternalSlot (obj , [[ArrayBufferData]] )を実行する。 IsSharedArrayBuffer (obj )がtrue なら、TypeError 例外をthrowする。IsDetachedBuffer (obj )を返す。
25.1.6.4 get ArrayBuffer.prototype.maxByteLength
ArrayBuffer.prototype.maxByteLengthは、set accessor functionがundefined であるaccessor property である。そのget accessor functionは、呼び出されたときに以下のstepsを実行する:
obj をthis valueとする。? RequireInternalSlot (obj , [[ArrayBufferData]] )を実行する。 IsSharedArrayBuffer (obj )がtrue なら、TypeError 例外をthrowする。IsDetachedBuffer (obj )がtrue なら、+0 𝔽 を返す。IsFixedLengthArrayBuffer (obj )がtrue なら、length をobj .[[ArrayBufferByteLength]] とする。そうでなければ、length をobj .[[ArrayBufferMaxByteLength]] とする。 𝔽 (length )を返す。
25.1.6.5 get ArrayBuffer.prototype.resizable
ArrayBuffer.prototype.resizableは、set accessor functionがundefined であるaccessor property である。そのget accessor functionは、呼び出されたときに以下のstepsを実行する:
obj をthis valueとする。? RequireInternalSlot (obj , [[ArrayBufferData]] )を実行する。 IsSharedArrayBuffer (obj )がtrue なら、TypeError 例外をthrowする。IsFixedLengthArrayBuffer (obj )がfalse なら、true を返す。false を返す。
25.1.6.6 ArrayBuffer.prototype.resize ( newLength )
このmethodは、呼び出されたときに以下のstepsを実行する:
obj をthis valueとする。? RequireInternalSlot (obj , [[ArrayBufferMaxByteLength]] )を実行する。 IsSharedArrayBuffer (obj )がtrue なら、TypeError 例外をthrowする。newByteLength を ? ToIndex (newLength ) とする。IsDetachedBuffer (obj )がtrue なら、TypeError 例外をthrowする。newByteLength > obj .[[ArrayBufferMaxByteLength]] なら、RangeError 例外をthrowする。hostHandled を ? HostResizeArrayBuffer (obj , newByteLength ) とする。hostHandled がhandled なら、undefined を返す。oldBlock をobj .[[ArrayBufferData]] とする。newBlock を ? CreateByteDataBlock (newByteLength ) とする。copyLength をmin (newByteLength , obj .[[ArrayBufferByteLength]] )とする。CopyDataBlockBytes (newBlock , 0, oldBlock , 0, copyLength )を実行する。NOTE : 新しいData Block のcreationもold Data Block からのcopyingもobservableではない。Implementationsは、このmethodをin-place growthまたはshrinkageとしてimplementしてもよい。obj .[[ArrayBufferData]] をnewBlock に設定する。obj .[[ArrayBufferByteLength]] をnewByteLength に設定する。undefined を返す。
25.1.6.7 ArrayBuffer.prototype.slice ( start , end )
このmethodは、呼び出されたときに以下のstepsを実行する:
obj をthis valueとする。? RequireInternalSlot (obj , [[ArrayBufferData]] )を実行する。 IsSharedArrayBuffer (obj )がtrue なら、TypeError 例外をthrowする。IsDetachedBuffer (obj )がtrue なら、TypeError 例外をthrowする。length をobj .[[ArrayBufferByteLength]] とする。relativeStart を ? ToIntegerOrInfinity (start ) とする。relativeStart = -∞なら、first を0とする。そうでなく、relativeStart < 0なら、first をmax (length + relativeStart , 0)とする。 そうでなければ、first をmin (relativeStart , length )とする。 end がundefined なら、relativeEnd をlength とする;そうでなければ、relativeEnd を ? ToIntegerOrInfinity (end ) とする。relativeEnd = -∞なら、final を0とする。そうでなく、relativeEnd < 0なら、final をmax (length + relativeEnd , 0)とする。 そうでなければ、final をmin (relativeEnd , length )とする。 newLength をmax (final - first , 0)とする。ctor を ? SpeciesConstructor (obj , %ArrayBuffer% ) とする。new を ? Construct (ctor , « 𝔽 (newLength ) ») とする。? RequireInternalSlot (new , [[ArrayBufferData]] )を実行する。 IsSharedArrayBuffer (new )がtrue なら、TypeError 例外をthrowする。IsDetachedBuffer (new )がtrue なら、TypeError 例外をthrowする。SameValue (new , obj )がtrue なら、TypeError 例外をthrowする。new .[[ArrayBufferByteLength]] < newLength なら、TypeError 例外をthrowする。NOTE : 上記stepsのside-effectsにより、obj がdetachedまたはresizedされている可能性がある。IsDetachedBuffer (obj )がtrue なら、TypeError 例外をthrowする。fromBuf をobj .[[ArrayBufferData]] とする。toBuf をnew .[[ArrayBufferData]] とする。currentLength をobj .[[ArrayBufferByteLength]] とする。first < currentLength なら、count をmin (newLength , currentLength - first )とする。CopyDataBlockBytes (toBuf , 0, fromBuf , first , count )を実行する。new を返す。
25.1.6.8 ArrayBuffer.prototype.transfer ( [ newLength ] )
このmethodは、呼び出されたときに以下のstepsを実行する:
obj をthis valueとする。? ArrayBufferCopyAndDetach (obj , newLength , preserve-resizability )を返す。
25.1.6.9 ArrayBuffer.prototype.transferToFixedLength ( [ newLength ] )
このmethodは、呼び出されたときに以下のstepsを実行する:
obj をthis valueとする。? 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:
Let slots be « [[ArrayBufferData]] ». If maxByteLength is present and maxByteLength is not empty , let allocatingGrowableBuffer be true ; else let allocatingGrowableBuffer be false . If allocatingGrowableBuffer is true , thenIf byteLength > maxByteLength , throw a RangeError exception. Append [[ArrayBufferByteLengthData]] and [[ArrayBufferMaxByteLength]] to slots . Else,Append [[ArrayBufferByteLength]] to slots . Let obj be ? OrdinaryCreateFromConstructor (ctor , "%SharedArrayBuffer.prototype%" , slots ). If allocatingGrowableBuffer is true , let allocLength be maxByteLength ; else let allocLength be byteLength . Let block be ? CreateSharedByteDataBlock (allocLength ). Set obj .[[ArrayBufferData]] to block . If allocatingGrowableBuffer is true , thenAssert : byteLength ≤ maxByteLength .Let byteLengthBlock be ? CreateSharedByteDataBlock (8). Perform SetValueInBuffer (byteLengthBlock , 0, biguint64 , ℤ (byteLength ), true , seq-cst ). Set obj .[[ArrayBufferByteLengthData]] to byteLengthBlock . Set obj .[[ArrayBufferMaxByteLength]] to maxByteLength . Else,Set obj .[[ArrayBufferByteLength]] to byteLength . 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:
obj .[[ArrayBufferData]] がShared Data Block なら、true を返す。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:
IsSharedArrayBuffer (obj )がtrue であり、obj が[[ArrayBufferByteLengthData]] internal slotを持つなら、true を返す。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に、buffer のimplementation-defined growingをperformする機会を与える。hostがbuffer のgrowingをhandleしないことをchooseした場合、default behaviourのためにunhandled を返してもよい。
HostGrowSharedArrayBufferのimplementationは、以下のrequirementsにconformしなければならない:
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 ≤ newByteLength ≤ buffer .[[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を実行する:
NewTargetがundefined なら、TypeError 例外をthrowする。 byteLength を ? ToIndex (length ) とする。requestedMaxByteLength を ? GetArrayBufferMaxByteLengthOption (options ) とする。? AllocateSharedArrayBuffer (NewTarget, byteLength , requestedMaxByteLength )を返す。
25.2.4 SharedArrayBuffer Constructorのプロパティ
SharedArrayBuffer constructor は:
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を実行する:
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を実行する:
obj をthis valueとする。? RequireInternalSlot (obj , [[ArrayBufferData]] )を実行する。 IsSharedArrayBuffer (obj )がfalse なら、TypeError 例外をthrowする。length をArrayBufferByteLength (obj , seq-cst )とする。𝔽 (length )を返す。
25.2.5.2 SharedArrayBuffer.prototype.constructor
SharedArrayBuffer.prototype.constructorのinitial valueは%SharedArrayBuffer% である。
25.2.5.3 SharedArrayBuffer.prototype.grow ( newLength )
このmethodは、呼び出されたときに以下のstepsを実行する:
obj をthis valueとする。? RequireInternalSlot (obj , [[ArrayBufferMaxByteLength]] )を実行する。 IsSharedArrayBuffer (obj )がfalse なら、TypeError 例外をthrowする。newByteLength を ? ToIndex (newLength ) とする。hostHandled を ? HostGrowSharedArrayBuffer (obj , newByteLength ) とする。hostHandled がhandled なら、undefined を返す。agentRecord をsurrounding agent のAgent Record とする。isLittleEndian をagentRecord .[[LittleEndian]] とする。byteLengthBlock をobj .[[ArrayBufferByteLengthData]] とする。currentByteLengthRawBytes をGetRawBytesFromSharedBlock (byteLengthBlock , 0, biguint64 , true , seq-cst )とする。newByteLengthRawBytes をNumericToRawBytes (biguint64 , ℤ (newByteLength ), isLittleEndian )とする。Repeat,NOTE : これは、same bufferのparallelかつracingなgrowsがtotally orderedされ、lostされず、silently do nothingしないことをensureするためのcompare-and-exchange loopである。このloopは、uncontendedにgrowをattemptできた場合にexitする。currentByteLength をℝ (RawBytesToNumeric (biguint64 , currentByteLengthRawBytes , isLittleEndian ))とする。newByteLength = currentByteLength なら、undefined を返す。newByteLength < currentByteLength またはnewByteLength > obj .[[ArrayBufferMaxByteLength]] なら、RangeError 例外をthrowする。byteLengthDelta をnewByteLength - currentByteLength とする。byteLengthDelta bytesからなるnew Shared Data Block valueをcreateすることがimpossibleなら、RangeError 例外をthrowする。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する。readByteLengthRawBytes をAtomicCompareExchangeInSharedBlock (byteLengthBlock , 0, 8, currentByteLengthRawBytes , newByteLengthRawBytes )とする。ByteListEqual (readByteLengthRawBytes , currentByteLengthRawBytes )がtrue なら、undefined を返す。currentByteLengthRawBytes をreadByteLengthRawBytes に設定する。
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を実行する:
obj をthis valueとする。? RequireInternalSlot (obj , [[ArrayBufferData]] )を実行する。 IsSharedArrayBuffer (obj )がfalse なら、TypeError 例外をthrowする。IsFixedLengthArrayBuffer (obj )がfalse なら、true を返す。false を返す。
25.2.5.5 get SharedArrayBuffer.prototype.maxByteLength
SharedArrayBuffer.prototype.maxByteLengthは、set accessor functionがundefined であるaccessor property である。そのget accessor functionは、呼び出されたときに以下のstepsを実行する:
obj をthis valueとする。? RequireInternalSlot (obj , [[ArrayBufferData]] )を実行する。 IsSharedArrayBuffer (obj )がfalse なら、TypeError 例外をthrowする。IsFixedLengthArrayBuffer (obj )がtrue なら、length をobj .[[ArrayBufferByteLength]] とする。そうでなければ、length をobj .[[ArrayBufferMaxByteLength]] とする。 𝔽 (length )を返す。
25.2.5.6 SharedArrayBuffer.prototype.slice ( start , end )
このmethodは、呼び出されたときに以下のstepsを実行する:
obj をthis valueとする。? RequireInternalSlot (obj , [[ArrayBufferData]] )を実行する。 IsSharedArrayBuffer (obj )がfalse なら、TypeError 例外をthrowする。length をArrayBufferByteLength (obj , seq-cst )とする。relativeStart を ? ToIntegerOrInfinity (start ) とする。relativeStart = -∞なら、first を0とする。そうでなく、relativeStart < 0なら、first をmax (length + relativeStart , 0)とする。 そうでなければ、first をmin (relativeStart , length )とする。 end がundefined なら、relativeEnd をlength とする;そうでなければ、relativeEnd を ? ToIntegerOrInfinity (end ) とする。relativeEnd = -∞なら、final を0とする。そうでなく、relativeEnd < 0なら、final をmax (length + relativeEnd , 0)とする。 そうでなければ、final をmin (relativeEnd , length )とする。 newLength をmax (final - first , 0)とする。ctor を ? SpeciesConstructor (obj , %SharedArrayBuffer% ) とする。new を ? Construct (ctor , « 𝔽 (newLength ) ») とする。? RequireInternalSlot (new , [[ArrayBufferData]] )を実行する。 IsSharedArrayBuffer (new )がfalse なら、TypeError 例外をthrowする。new .[[ArrayBufferData]] がobj .[[ArrayBufferData]] であるなら、TypeError 例外をthrowする。ArrayBufferByteLength (new , seq-cst ) < newLength なら、TypeError 例外をthrowする。fromBuf をobj .[[ArrayBufferData]] とする。toBuf をnew .[[ArrayBufferData]] とする。CopyDataBlockBytes (toBuf , 0, fromBuf , first , newLength )を実行する。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:
buffer をobj .[[ViewedArrayBuffer]] とする。IsDetachedBuffer (buffer )がtrue なら、byteLength をdetached とする。そうでなければ、byteLength をArrayBufferByteLength (buffer , order )とする。 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:
Assert : IsViewOutOfBounds (viewRecord )はfalse である。view をviewRecord .[[Object]] とする。view .[[ByteLength]] がauto でないなら、view .[[ByteLength]] を返す。Assert : IsFixedLengthArrayBuffer (view .[[ViewedArrayBuffer]] )はfalse である。byteOffset をview .[[ByteOffset]] とする。byteLength をviewRecord .[[CachedBufferByteLength]] とする。Assert : byteLength はdetached でない。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:
view をviewRecord .[[Object]] とする。bufferByteLength をviewRecord .[[CachedBufferByteLength]] とする。IsDetachedBuffer (view .[[ViewedArrayBuffer]] )がtrue なら、Assert : bufferByteLength はdetached である。true を返す。Assert : bufferByteLength はnon-negative integer である。byteOffsetStart をview .[[ByteOffset]] とする。view .[[ByteLength]] がauto なら、byteOffsetEnd をbufferByteLength とする。そうでなければ、byteOffsetEnd をbyteOffsetStart + view .[[ByteLength]] とする。 NOTE : [[ByteOffset]] がbufferByteLength である0-length DataViewはout-of-boundsであるとはconsideredされない。byteOffsetStart > bufferByteLength またはbyteOffsetEnd > bufferByteLength なら、true を返す。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:
? RequireInternalSlot (view , [[DataView]] )を実行する。 Assert : view は[[ViewedArrayBuffer]] internal slotを持つ。getIndex を ? ToIndex (requestIndex ) とする。isLittleEndian をToBoolean (isLittleEndian )に設定する。viewOffset をview .[[ByteOffset]] とする。viewRecord をMakeDataViewWithBufferWitnessRecord (view , unordered )とする。NOTE : view のbacking bufferがgrowable SharedArrayBuffer である場合、Bounds checkingはsynchronizing operationではない。IsViewOutOfBounds (viewRecord )がtrue なら、TypeError 例外をthrowする。viewSize をGetViewByteLength (viewRecord )とする。elementSize を、Element Type type についてTable 71 でspecifiedされるElement Size valueとする。getIndex + elementSize > viewSize なら、RangeError 例外をthrowする。bufferIndex をgetIndex + viewOffset とする。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:
? RequireInternalSlot (view , [[DataView]] )を実行する。 Assert : view は[[ViewedArrayBuffer]] internal slotを持つ。getIndex を ? ToIndex (requestIndex ) とする。IsBigIntElementType (type )がtrue なら、number を ? ToBigInt (value ) とする。そうでなければ、number を ? ToNumber (value ) とする。 isLittleEndian をToBoolean (isLittleEndian )に設定する。viewOffset をview .[[ByteOffset]] とする。viewRecord をMakeDataViewWithBufferWitnessRecord (view , unordered )とする。NOTE : view のbacking bufferがgrowable SharedArrayBuffer である場合、Bounds checkingはsynchronizing operationではない。IsViewOutOfBounds (viewRecord )がtrue なら、TypeError 例外をthrowする。viewSize をGetViewByteLength (viewRecord )とする。elementSize を、Element Type type についてTable 71 でspecifiedされるElement Size valueとする。getIndex + elementSize > viewSize なら、RangeError 例外をthrowする。bufferIndex をgetIndex + viewOffset とする。SetValueInBuffer (view .[[ViewedArrayBuffer]] , bufferIndex , type , number , false , unordered , isLittleEndian )を実行する。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を実行する:
NewTargetがundefined なら、TypeError 例外をthrowする。 ? RequireInternalSlot (buffer , [[ArrayBufferData]] )を実行する。 offset を ? ToIndex (byteOffset ) とする。IsDetachedBuffer (buffer )がtrue なら、TypeError 例外をthrowする。bufferByteLength をArrayBufferByteLength (buffer , seq-cst )とする。offset > bufferByteLength なら、RangeError 例外をthrowする。bufferIsFixedLength をIsFixedLengthArrayBuffer (buffer )とする。byteLength がundefined なら、bufferIsFixedLength がtrue なら、viewByteLength をbufferByteLength - offset とする。そうでなければ、viewByteLength をauto とする。 そうでなければ、viewByteLength を ? ToIndex (byteLength ) とする。offset + viewByteLength > bufferByteLength なら、RangeError 例外をthrowする。 obj を ? OrdinaryCreateFromConstructor (NewTarget, "%DataView.prototype%" , « [[DataView]] , [[ViewedArrayBuffer]] , [[ByteLength]] , [[ByteOffset]] ») とする。IsDetachedBuffer (buffer )がtrue なら、TypeError 例外をthrowする。bufferByteLength をArrayBufferByteLength (buffer , seq-cst )に設定する。offset > bufferByteLength なら、RangeError 例外をthrowする。byteLength がundefined でないなら、offset + viewByteLength > bufferByteLength なら、RangeError 例外をthrowする。obj .[[ViewedArrayBuffer]] をbuffer に設定する。obj .[[ByteLength]] をviewByteLength に設定する。obj .[[ByteOffset]] をoffset に設定する。obj を返す。
25.3.3 DataView Constructorのプロパティ
DataView constructor は:
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を実行する:
obj をthis valueとする。? RequireInternalSlot (obj , [[DataView]] )を実行する。 Assert : obj は[[ViewedArrayBuffer]] internal slotを持つ。buffer をobj .[[ViewedArrayBuffer]] とする。buffer を返す。
25.3.4.2 get DataView.prototype.byteLength
DataView.prototype.byteLengthは、set accessor functionがundefined であるaccessor property である。そのget accessor functionは、呼び出されたときに以下のstepsを実行する:
obj をthis valueとする。? RequireInternalSlot (obj , [[DataView]] )を実行する。 Assert : obj は[[ViewedArrayBuffer]] internal slotを持つ。viewRecord をMakeDataViewWithBufferWitnessRecord (obj , seq-cst )とする。IsViewOutOfBounds (viewRecord )がtrue なら、TypeError 例外をthrowする。size をGetViewByteLength (viewRecord )とする。𝔽 (size )を返す。
25.3.4.3 get DataView.prototype.byteOffset
DataView.prototype.byteOffsetは、set accessor functionがundefined であるaccessor property である。そのget accessor functionは、呼び出されたときに以下のstepsを実行する:
obj をthis valueとする。? RequireInternalSlot (obj , [[DataView]] )を実行する。 Assert : obj は[[ViewedArrayBuffer]] internal slotを持つ。viewRecord をMakeDataViewWithBufferWitnessRecord (obj , seq-cst )とする。IsViewOutOfBounds (viewRecord )がtrue なら、TypeError 例外をthrowする。offset をobj .[[ByteOffset]] とする。𝔽 (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を実行する:
view をthis valueとする。? GetViewValue (view , byteOffset , littleEndian , bigint64 )を返す。
25.3.4.6 DataView.prototype.getBigUint64 ( byteOffset [ , littleEndian ] )
このmethodは、呼び出されたときに以下のstepsを実行する:
view をthis valueとする。? GetViewValue (view , byteOffset , littleEndian , biguint64 )を返す。
25.3.4.7 DataView.prototype.getFloat16 ( byteOffset [ , littleEndian ] )
このmethodは、呼び出されたときに以下のstepsを実行する:
view をthis valueとする。littleEndian がpresentでないなら、littleEndian をfalse に設定する。? GetViewValue (view , byteOffset , littleEndian , float16 )を返す。
25.3.4.8 DataView.prototype.getFloat32 ( byteOffset [ , littleEndian ] )
このmethodは、呼び出されたときに以下のstepsを実行する:
view をthis valueとする。littleEndian がpresentでないなら、littleEndian をfalse に設定する。? GetViewValue (view , byteOffset , littleEndian , float32 )を返す。
25.3.4.9 DataView.prototype.getFloat64 ( byteOffset [ , littleEndian ] )
このmethodは、呼び出されたときに以下のstepsを実行する:
view をthis valueとする。littleEndian がpresentでないなら、littleEndian をfalse に設定する。? GetViewValue (view , byteOffset , littleEndian , float64 )を返す。
25.3.4.10 DataView.prototype.getInt8 ( byteOffset )
このmethodは、呼び出されたときに以下のstepsを実行する:
view をthis valueとする。? GetViewValue (view , byteOffset , true , int8 )を返す。
25.3.4.11 DataView.prototype.getInt16 ( byteOffset [ , littleEndian ] )
このmethodは、呼び出されたときに以下のstepsを実行する:
view をthis valueとする。littleEndian がpresentでないなら、littleEndian をfalse に設定する。? GetViewValue (view , byteOffset , littleEndian , int16 )を返す。
25.3.4.12 DataView.prototype.getInt32 ( byteOffset [ , littleEndian ] )
このmethodは、呼び出されたときに以下のstepsを実行する:
view をthis valueとする。littleEndian がpresentでないなら、littleEndian をfalse に設定する。? GetViewValue (view , byteOffset , littleEndian , int32 )を返す。
25.3.4.13 DataView.prototype.getUint8 ( byteOffset )
このmethodは、呼び出されたときに以下のstepsを実行する:
view をthis valueとする。? GetViewValue (view , byteOffset , true , uint8 )を返す。
25.3.4.14 DataView.prototype.getUint16 ( byteOffset [ , littleEndian ] )
このmethodは、呼び出されたときに以下のstepsを実行する:
view をthis valueとする。littleEndian がpresentでないなら、littleEndian をfalse に設定する。? GetViewValue (view , byteOffset , littleEndian , uint16 )を返す。
25.3.4.15 DataView.prototype.getUint32 ( byteOffset [ , littleEndian ] )
このmethodは、呼び出されたときに以下のstepsを実行する:
view をthis valueとする。littleEndian がpresentでないなら、littleEndian をfalse に設定する。? GetViewValue (view , byteOffset , littleEndian , uint32 )を返す。
25.3.4.16 DataView.prototype.setBigInt64 ( byteOffset , value [ , littleEndian ] )
このmethodは、呼び出されたときに以下のstepsを実行する:
view をthis valueとする。? SetViewValue (view , byteOffset , littleEndian , bigint64 , value )を返す。
25.3.4.17 DataView.prototype.setBigUint64 ( byteOffset , value [ , littleEndian ] )
このmethodは、呼び出されたときに以下のstepsを実行する:
view をthis valueとする。? SetViewValue (view , byteOffset , littleEndian , biguint64 , value )を返す。
25.3.4.18 DataView.prototype.setFloat16 ( byteOffset , value [ , littleEndian ] )
このmethodは、呼び出されたときに以下のstepsを実行する:
view をthis valueとする。littleEndian がpresentでないなら、littleEndian をfalse に設定する。? SetViewValue (view , byteOffset , littleEndian , float16 , value )を返す。
25.3.4.19 DataView.prototype.setFloat32 ( byteOffset , value [ , littleEndian ] )
このmethodは、呼び出されたときに以下のstepsを実行する:
view をthis valueとする。littleEndian がpresentでないなら、littleEndian をfalse に設定する。? SetViewValue (view , byteOffset , littleEndian , float32 , value )を返す。
25.3.4.20 DataView.prototype.setFloat64 ( byteOffset , value [ , littleEndian ] )
このmethodは、呼び出されたときに以下のstepsを実行する:
view をthis valueとする。littleEndian がpresentでないなら、littleEndian をfalse に設定する。? SetViewValue (view , byteOffset , littleEndian , float64 , value )を返す。
25.3.4.21 DataView.prototype.setInt8 ( byteOffset , value )
このmethodは、呼び出されたときに以下のstepsを実行する:
view をthis valueとする。? SetViewValue (view , byteOffset , true , int8 , value )を返す。
25.3.4.22 DataView.prototype.setInt16 ( byteOffset , value [ , littleEndian ] )
このmethodは、呼び出されたときに以下のstepsを実行する:
view をthis valueとする。littleEndian がpresentでないなら、littleEndian をfalse に設定する。? SetViewValue (view , byteOffset , littleEndian , int16 , value )を返す。
25.3.4.23 DataView.prototype.setInt32 ( byteOffset , value [ , littleEndian ] )
このmethodは、呼び出されたときに以下のstepsを実行する:
view をthis valueとする。littleEndian がpresentでないなら、littleEndian をfalse に設定する。? SetViewValue (view , byteOffset , littleEndian , int32 , value )を返す。
25.3.4.24 DataView.prototype.setUint8 ( byteOffset , value )
このmethodは、呼び出されたときに以下のstepsを実行する:
view をthis valueとする。? SetViewValue (view , byteOffset , true , uint8 , value )を返す。
25.3.4.25 DataView.prototype.setUint16 ( byteOffset , value [ , littleEndian ] )
このmethodは、呼び出されたときに以下のstepsを実行する:
view をthis valueとする。littleEndian がpresentでないなら、littleEndian をfalse に設定する。? SetViewValue (view , byteOffset , littleEndian , uint16 , value )を返す。
25.3.4.26 DataView.prototype.setUint32 ( byteOffset , value [ , littleEndian ] )
このmethodは、呼び出されたときに以下のstepsを実行する:
view をthis valueとする。littleEndian がpresentでないなら、littleEndian をfalse に設定する。? 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オブジェクトは、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
25.4.2 WaiterList Records
WaiterList Record は、Atomics.wait、Atomics.waitAsync、およびAtomics.notifyを介するagents のwaitingおよびnotificationをexplainするために使用される。
WaiterList Recordは、Table 75 にlistedされるfieldsを持つ。
Table 75: WaiterList Record Fields
同じagent signifier を持つ複数のWaiter Records がWaiterList内に存在できる。
agent cluster はWaiterList Recordsのstoreを持つ;そのstoreは(block , i )によってindexedされる。ここで、block はShared Data Block であり、i はblock の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:
taRecord を ? ValidateTypedArray (ta , unordered ) とする。NOTE : ta のbacking bufferがgrowable SharedArrayBuffer である場合、Bounds checkingはsynchronizing operationではない。waitable がtrue なら、ta .[[TypedArrayName]] が"Int32Array" でも"BigInt64Array" でもないなら、TypeError 例外をthrowする。そうでなければ、type をTypedArrayElementType (ta )とする。IsUnclampedIntegerElementType (type )がfalse であり、かつIsBigIntElementType (type )がfalse なら、TypeError 例外をthrowする。 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:
length をTypedArrayLength (taRecord )とする。accessIndex を ? ToIndex (requestIndex ) とする。Assert : accessIndex ≥ 0である。accessIndex ≥ length なら、RangeError 例外をthrowする。ta をtaRecord .[[Object]] とする。elementSize をTypedArrayElementSize (ta )とする。offset をta .[[ByteOffset]] とする。(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:
taRecord を ? ValidateIntegerTypedArray (ta , false ) とする。? 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:
taRecord をMakeTypedArrayWithBufferWitnessRecord (ta , unordered )とする。NOTE : ta のbacking bufferがgrowable SharedArrayBuffer である場合、Bounds checkingはsynchronizing operationではない。IsTypedArrayOutOfBounds (taRecord )がtrue なら、TypeError 例外をthrowする。Assert : byteIndexInBuffer ≥ ta .[[ByteOffset]] である。byteIndexInBuffer ≥ taRecord .[[CachedBufferByteLength]] なら、RangeError 例外をthrowする。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:
Assert : i およびi + 3はblock のmemory内のvalid byte offsetsである。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:
Assert : surrounding agent はいかなるWaiterList Record についてもcritical section 内にいない。waiterList のcritical section 内にagent がいなくなるまでwaitし、その後waiterList のcritical section にenterする(他のagent がenterすることをallowせずに)。waiterList .[[MostRecentLeaveEvent]] がempty でないなら、NOTE : 少なくとも一度critical section にenteredされたwaiterList は、LeaveCriticalSection によってsetされたSynchronize event を持つ。agentRecord をsurrounding agent のAgent Record とする。execution をagentRecord .[[CandidateExecution]] とする。eventsRecord を、execution .[[EventsRecords]] のうち[[AgentSignifier]] がAgentSignifier ()であるAgent Events Record とする。enterEvent をnew Synchronize event とする。enterEvent をeventsRecord .[[EventList]] にappendする。(waiterList .[[MostRecentLeaveEvent]] , enterEvent )をeventsRecord .[[AgentSynchronizesWith]] にappendする。 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:
Assert : surrounding agent はwaiterList のcritical section 内にいる。agentRecord をsurrounding agent のAgent Record とする。execution をagentRecord .[[CandidateExecution]] とする。eventsRecord を、execution .[[EventsRecords]] のうち[[AgentSignifier]] がAgentSignifier ()であるAgent Events Record とする。leaveEvent をnew Synchronize event とする。leaveEvent をeventsRecord .[[EventList]] にappendする。waiterList .[[MostRecentLeaveEvent]] をleaveEvent に設定する。waiterList のcritical section をleaveする。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:
Assert : surrounding agent はwaiterList のcritical section 内にいる。Assert : waiterList .[[Waiters]] 内に、[[PromiseCapability]] fieldがwaiterRecord .[[PromiseCapability]] であり、かつ[[AgentSignifier]] fieldがwaiterRecord .[[AgentSignifier]] であるWaiter Record は存在しない。waiterRecord をwaiterList .[[Waiters]] にappendする。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:
Assert : surrounding agent はwaiterList のcritical section 内にいる。Assert : waiterList .[[Waiters]] はwaiterRecord を含む。waiterRecord をwaiterList .[[Waiters]] からremoveする。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:
Assert : surrounding agent はwaiterList のcritical section 内にいる。length をwaiterList .[[Waiters]] 内のelementsのnumberとする。count をmin (count , length )に設定する。waiters を、elementsがwaiterList .[[Waiters]] のfirst count elementsであるList とする。waiterList .[[Waiters]] のfirst count elementsをremoveする。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:
Assert : surrounding agent はwaiterList のcritical section 内にいる。Assert : waiterList .[[Waiters]] はwaiterRecord を含む。thisAgent をAgentSignifier ()とする。Assert : waiterRecord .[[AgentSignifier]] はthisAgent である。Assert : waiterRecord .[[PromiseCapability]] はblocking である。Assert : AgentCanSuspend ()はtrue である。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 およびthisAgent でNotifyWaiter をcallingすること(すなわちAtomics.notifyへのcallを介すること)によってのみ、suspensionからwakeできる。EnterCriticalSection (waiterList )を実行する。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:
Assert : surrounding agent はwaiterList のcritical section 内にいる。waiterRecord .[[PromiseCapability]] がblocking なら、signifierがwaiterRecord .[[AgentSignifier]] であるagent をsuspensionからwakeする。 NOTE : これは、agent がSuspendThisAgent 内でexecutionをresumeすることをcauseする。そうでなく、AgentSignifier ()がwaiterRecord .[[AgentSignifier]] であるなら、promiseCapability をwaiterRecord .[[PromiseCapability]] とする。! Call (promiseCapability .[[Resolve]] , undefined , « waiterRecord .[[Result]] »)を実行する。 そうでなければ、EnqueueResolveInAgentJob (waiterRecord .[[AgentSignifier]] , waiterRecord .[[PromiseCapability]] , waiterRecord .[[Result]] )を実行する。 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:
resolveJob を、parametersを持たず、agentSignifier 、promiseCapability 、およびresolution をcapturesし、calledされたときに以下のstepsを実行するnew Job Abstract Closure とする:Assert : AgentSignifier ()はagentSignifier である。! Call (promiseCapability .[[Resolve]] , undefined , « resolution »)を実行する。 unused を返す。realmInTargetAgent を ! GetFunctionRealm (promiseCapability .[[Resolve]] ) とする。Assert : agentSignifier はrealmInTargetAgent .[[AgentSignifier]] である。HostEnqueueGenericJob (resolveJob , realmInTargetAgent )を実行する。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:
taRecord を ? ValidateIntegerTypedArray (ta , true ) とする。buffer をtaRecord .[[Object]] .[[ViewedArrayBuffer]] とする。IsSharedArrayBuffer (buffer )がfalse なら、TypeError 例外をthrowする。byteIndexInBuffer を ? ValidateAtomicAccess (taRecord , index ) とする。arrayTypeName をta .[[TypedArrayName]] とする。arrayTypeName が"BigInt64Array" なら、expected を ? ToBigInt64 (value ) とする。そうでなければ、expected を ? ToInt32 (value ) とする。 timeoutNumber を ? ToNumber (timeout ) とする。timeoutNumber がNaN または+∞ 𝔽 のいずれかなら、realTimeout を+∞とする。そうでなく、timeoutNumber が-∞ 𝔽 なら、realTimeout を0とする。 そうでなければ、realTimeout をmax (ℝ (timeoutNumber ), 0)とする。 mode がsync であり、AgentCanSuspend ()がfalse なら、TypeError 例外をthrowする。block をbuffer .[[ArrayBufferData]] とする。waiterList をGetWaiterList (block , byteIndexInBuffer )とする。mode がsync なら、promiseCapability をblocking とする。resultObj をundefined とする。そうでなければ、promiseCapability を ! NewPromiseCapability (%Promise% ) とする。resultObj をOrdinaryObjectCreate (%Object.prototype% )とする。 EnterCriticalSection (waiterList )を実行する。elementType をTypedArrayElementType (ta )とする。witness をGetValueFromBuffer (buffer , byteIndexInBuffer , elementType , true , seq-cst )とする。expected ≠ witness なら、LeaveCriticalSection (waiterList )を実行する。mode がsync なら、"not-equal" を返す。! CreateDataPropertyOrThrow (resultObj , "async" , false )を実行する。 ! CreateDataPropertyOrThrow (resultObj , "value" , "not-equal" )を実行する。 resultObj を返す。realTimeout = 0かつmode がasync なら、NOTE : synchronous immediate timeoutsにspecial handlingはない。Asynchronous immediate timeoutsは、fail fastし、unnecessary Promise jobsをavoidするためにspecial handlingを持つ。LeaveCriticalSection (waiterList )を実行する。! CreateDataPropertyOrThrow (resultObj , "async" , false )を実行する。 ! CreateDataPropertyOrThrow (resultObj , "value" , "timed-out" )を実行する。 resultObj を返す。thisAgent をAgentSignifier ()とする。now をcurrent timeをidentifyingするtime value (UTC)とする。additionalTimeout をimplementation-defined non-negative mathematical value とする。timeoutTime をℝ (now ) + realTimeout + additionalTimeout とする。NOTE : realTimeout が+∞である場合、timeoutTime も+∞である。waiterRecord をnew Waiter Record { [[AgentSignifier]] : thisAgent , [[PromiseCapability]] : promiseCapability , [[TimeoutTime]] : timeoutTime , [[Result]] : "ok" }とする。AddWaiter (waiterList , waiterRecord )を実行する。mode がsync なら、SuspendThisAgent (waiterList , waiterRecord )を実行する。そうでなく、timeoutTime がfinite なら、EnqueueAtomicsWaitAsyncTimeoutJob (waiterList , waiterRecord )を実行する。 LeaveCriticalSection (waiterList )を実行する。mode がsync なら、waiterRecord .[[Result]] を返す。! CreateDataPropertyOrThrow (resultObj , "async" , true )を実行する。 ! CreateDataPropertyOrThrow (resultObj , "value" , promiseCapability .[[Promise]] )を実行する。 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:
timeoutJob を、parametersを持たず、waiterList およびwaiterRecord をcapturesし、calledされたときに以下のstepsを実行するnew Job Abstract Closure とする:EnterCriticalSection (waiterList )を実行する。waiterList .[[Waiters]] がwaiterRecord を含むなら、timeOfJobExecution をcurrent timeをidentifyingするtime value (UTC)とする。Assert : ℝ (timeOfJobExecution ) ≥ waiterRecord .[[TimeoutTime]] である(time values のpotential non-monotonicityをignoringする)。waiterRecord .[[Result]] を"timed-out" に設定する。RemoveWaiter (waiterList , waiterRecord )を実行する。NotifyWaiter (waiterList , waiterRecord )を実行する。LeaveCriticalSection (waiterList )を実行する。unused を返す。now をcurrent timeをidentifyingするtime value (UTC)とする。currentRealm をcurrent Realm Record とする。HostEnqueueTimeoutJob (timeoutJob , currentRealm , 𝔽 (waiterRecord .[[TimeoutTime]] ) - now )を実行する。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:
agentRecord をsurrounding agent のAgent Record とする。execution をagentRecord .[[CandidateExecution]] とする。eventsRecord を、execution .[[EventsRecords]] のうち[[AgentSignifier]] がAgentSignifier ()であるAgent Events Record とする。rawBytesRead を、elementsがnondeterministicallyにchosenされたbyte values であるlength elementSize のList とする。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である。NOTE : expected valueとread valueのcomparisonは、expected valueがread valueとequalでない場合にneedlessly strong synchronizationをavoidするため、read-modify-write modification function の外側でperformedされる。ByteListEqual (rawBytesRead , expectedBytes )がtrue なら、second を、parameters (oldBytes , newBytes )を持ち、nothingをcapturesし、calledされたときに以下のstepsをatomicallyに実行するnew read-modify-write modification function とする:newBytes を返す。event をReadModifyWriteSharedMemory { [[Order]] : seq-cst , [[NoTear]] : true , [[Block]] : block , [[ByteIndex]] : byteIndexInBuffer , [[ElementSize]] : elementSize , [[Payload]] : replacementBytes , [[ModifyOp]] : second }とする。そうでなければ、event をReadSharedMemory { [[Order]] : seq-cst , [[NoTear]] : true , [[Block]] : block , [[ByteIndex]] : byteIndexInBuffer , [[ElementSize]] : elementSize }とする。 event をeventsRecord .[[EventList]] にappendする。Chosen Value Record { [[Event]] : event , [[ChosenValue]] : rawBytesRead }をexecution .[[ChosenValues]] にappendする。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:
byteIndexInBuffer を ? ValidateAtomicAccessOnIntegerTypedArray (ta , index ) とする。ta .[[ContentType]] がbigint なら、coerced を ? ToBigInt (value ) とする。そうでなければ、coerced を𝔽 (? ToIntegerOrInfinity (value ))とする。 ? RevalidateAtomicAccess (ta , byteIndexInBuffer )を実行する。 buffer をta .[[ViewedArrayBuffer]] とする。elementType をTypedArrayElementType (ta )とする。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:
Assert : xBytes とyBytes は同じnumberのelementsを持つ。result をnew empty List とする。i を0とする。xBytes の各element xByte について、yByte をyBytes [i ]とする。op が&なら、resultByte を、xByte とyByte にbitwise AND operationをapplyingしたresultとする。そうでなく、op が^なら、resultByte を、xByte とyByte にbitwise exclusive OR (XOR) operationをapplyingしたresultとする。 そうでなければ、Assert : op は|である。resultByte を、xByte とyByte にbitwise inclusive OR operationをapplyingしたresultとする。 i をi + 1に設定する。resultByte をresult にappendする。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:
xBytes とyBytes が同じnumberのelementsを持たないなら、false を返す。i を0とする。xBytes の各element xByte について、yByte をyBytes [i ]とする。xByte ≠ yByte なら、false を返す。i をi + 1に設定する。true を返す。
25.4.4 Atomics.add ( ta , index , value )
このfunctionは、呼び出されたときに以下のstepsを実行する:
add を、parameters (xBytes , yBytes )を持ち、ta をcapturesし、calledされたときに以下のstepsをatomicallyに実行するnew read-modify-write modification function とする:type をTypedArrayElementType (ta )とする。agentRecord をsurrounding agent のAgent Record とする。isLittleEndian をagentRecord .[[LittleEndian]] とする。x をRawBytesToNumeric (type , xBytes , isLittleEndian )とする。y をRawBytesToNumeric (type , yBytes , isLittleEndian )とする。x がNumberなら、sum をNumber::add (x , y )とする。そうでなければ、Assert : x はBigIntである。sum をBigInt::add (x , y )とする。 sumBytes をNumericToRawBytes (type , sum , isLittleEndian )とする。Assert : sumBytes 、xBytes 、およびyBytes は同じnumberのelementsを持つ。sumBytes を返す。? AtomicReadModifyWrite (ta , index , value , add )を返す。
25.4.5 Atomics.and ( ta , index , value )
このfunctionは、呼び出されたときに以下のstepsを実行する:
and を、parameters (xBytes , yBytes )を持ち、nothingをcapturesし、calledされたときに以下のstepsをatomicallyに実行するnew read-modify-write modification function とする:ByteListBitwiseOp (&, xBytes , yBytes )を返す。? AtomicReadModifyWrite (ta , index , value , and )を返す。
25.4.6 Atomics.compareExchange ( ta , index , expectedValue , replacementValue )
このfunctionは、呼び出されたときに以下のstepsを実行する:
byteIndexInBuffer を ? ValidateAtomicAccessOnIntegerTypedArray (ta , index ) とする。buffer をta .[[ViewedArrayBuffer]] とする。block をbuffer .[[ArrayBufferData]] とする。ta .[[ContentType]] がbigint なら、expected を ? ToBigInt (expectedValue ) とする。replacement を ? ToBigInt (replacementValue ) とする。そうでなければ、expected を𝔽 (? ToIntegerOrInfinity (expectedValue ))とする。replacement を𝔽 (? ToIntegerOrInfinity (replacementValue ))とする。 ? RevalidateAtomicAccess (ta , byteIndexInBuffer )を実行する。 elementType をTypedArrayElementType (ta )とする。elementSize をTypedArrayElementSize (ta )とする。agentRecord をsurrounding agent のAgent Record とする。isLittleEndian をagentRecord .[[LittleEndian]] とする。expectedBytes をNumericToRawBytes (elementType , expected , isLittleEndian )とする。replacementBytes をNumericToRawBytes (elementType , replacement , isLittleEndian )とする。IsSharedArrayBuffer (buffer )がtrue なら、rawBytesRead をAtomicCompareExchangeInSharedBlock (block , byteIndexInBuffer , elementSize , expectedBytes , replacementBytes )とする。そうでなければ、rawBytesRead を、elementsがblock [byteIndexInBuffer ]でstartingするelementSize bytesのsequenceであるlength elementSize のList とする。ByteListEqual (rawBytesRead , expectedBytes )がtrue なら、replacementBytes のindividual bytesをblock に、block [byteIndexInBuffer ]からstartingしてstoreする。 RawBytesToNumeric (elementType , rawBytesRead , isLittleEndian )を返す。
25.4.7 Atomics.exchange ( ta , index , value )
このfunctionは、呼び出されたときに以下のstepsを実行する:
second を、parameters (oldBytes , newBytes )を持ち、nothingをcapturesし、calledされたときに以下のstepsをatomicallyに実行するnew read-modify-write modification function とする:newBytes を返す。? AtomicReadModifyWrite (ta , index , value , second )を返す。
25.4.8 Atomics.isLockFree ( size )
このfunctionは、呼び出されたときに以下のstepsを実行する:
n を ? ToIntegerOrInfinity (size ) とする。agentRecord をsurrounding agent のAgent Record とする。n = 1なら、agentRecord .[[IsLockFree1]] を返す。n = 2なら、agentRecord .[[IsLockFree2]] を返す。n = 4なら、true を返す。n = 8なら、agentRecord .[[IsLockFree8]] を返す。false を返す。
Note
このfunctionはoptimization primitiveである。その直観は、size n bytesのdatum上のatomic primitive(compareExchange、load、store、add、sub、and、or、xor、または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を実行する:
byteIndexInBuffer を ? ValidateAtomicAccessOnIntegerTypedArray (ta , index ) とする。? RevalidateAtomicAccess (ta , byteIndexInBuffer )を実行する。 buffer をta .[[ViewedArrayBuffer]] とする。elementType をTypedArrayElementType (ta )とする。GetValueFromBuffer (buffer , byteIndexInBuffer , elementType , true , seq-cst )を返す。
25.4.10 Atomics.notify ( ta , index , count )
この関数は、待機キュー内でスリープしているいくつかのエージェントに通知する。
呼び出されたとき、次の手順を実行する。
taRecord を ? ValidateIntegerTypedArray (ta , true ) とする。byteIndexInBuffer を ? ValidateAtomicAccess (taRecord , index ) とする。count が undefined である場合、count を +∞ に設定する。そうでなければ、intCount を ? ToIntegerOrInfinity (count ) とする。count を max (intCount , 0) に設定する。 buffer を ta .[[ViewedArrayBuffer]] とする。block を buffer .[[ArrayBufferData]] とする。IsSharedArrayBuffer (buffer ) が false である場合、+0 𝔽 を返す。waiterList を GetWaiterList (block , byteIndexInBuffer ) とする。EnterCriticalSection (waiterList ) を実行する。waiters を RemoveWaiters (waiterList , count ) とする。waiters の各要素 waiterRecord について、次を行う。NotifyWaiter (waiterList , waiterRecord ) を実行する。LeaveCriticalSection (waiterList ) を実行する。waitersCount を waiters 内の要素数とする。𝔽 (waitersCount ) を返す。
25.4.11 Atomics.or ( ta , index , value )
この関数は、呼び出されたとき、次の手順を実行する。
or を、パラメーター (xBytes , yBytes ) を持ち、何もキャプチャせず、呼び出されたときに次の手順をアトミックに実行する、新しい読み取り-変更-書き込み変更関数とする。ByteListBitwiseOp (|, xBytes , yBytes ) を返す。? AtomicReadModifyWrite (ta , index , value , or ) を返す。
25.4.12 Atomics.pause ( )
この関数は、値を待機している間プログラムがスピンループしていることを CPU に示すヒントを提供する。
呼び出されたとき、次の手順を実行する。
ECMAScript 実装の実行環境が、現在実行中のコードがスピン待機ループ内にあることをオペレーティングシステムまたは CPU に通知することをサポートしている場合、その信号を送る。 undefined を返す。
Note 1
このメソッドは、mutex 内の spinlock 高速パスなど、スピン待機ループを実装するプログラムが、値を待機している間スピンしていることを CPU に示すヒントを提供するために設計されている。これはタイミング以外に観測可能な動作を持たない。
実装は、基盤となるアーキテクチャのベストプラクティスがスピンループ内でそのような命令を推奨している場合、pause または yield 命令を実装することが期待される。例えば、Intel 最適化マニュアル は pause 命令を推奨している。
実装には、一時停止する最大時間について、数十から数百ナノ秒程度の内部上限を持つことが推奨される。
Note 2
関数呼び出しのオーバーヘッドにより、最適化コンパイラーにおけるこのメソッドへのインライン化された呼び出しが、インライン化されていない呼び出しとは異なる時間だけ待機することは妥当である。
25.4.13 Atomics.store ( ta , index , value )
この関数は、呼び出されたとき、次の手順を実行する。
byteIndexInBuffer を ? ValidateAtomicAccessOnIntegerTypedArray (ta , index ) とする。ta .[[ContentType]] が bigint である場合、coerced を ? ToBigInt (value ) とする。そうでなければ、coerced を 𝔽 (? ToIntegerOrInfinity (value )) とする。 ? RevalidateAtomicAccess (ta , byteIndexInBuffer ) を実行する。 buffer を ta .[[ViewedArrayBuffer]] とする。elementType を TypedArrayElementType (ta ) とする。SetValueInBuffer (buffer , byteIndexInBuffer , elementType , coerced , true , seq-cst ) を実行する。coerced を返す。
25.4.14 Atomics.sub ( ta , index , value )
この関数は、呼び出されたとき、次の手順を実行する。
subtract を、パラメーター (xBytes , yBytes ) を持ち、ta をキャプチャし、呼び出されたときに次の手順をアトミックに実行する、新しい読み取り-変更-書き込み変更関数とする。type を TypedArrayElementType (ta ) とする。agentRecord を周囲のエージェントの Agent Record とする。isLittleEndian を agentRecord .[[LittleEndian]] とする。x を RawBytesToNumeric (type , xBytes , isLittleEndian ) とする。y を RawBytesToNumeric (type , yBytes , isLittleEndian ) とする。x が Number である場合、difference を Number::subtract (x , y ) とする。そうでなければ、Assert : x は BigInt である。difference を BigInt::subtract (x , y ) とする。 differenceBytes を NumericToRawBytes (type , difference , isLittleEndian ) とする。Assert : differenceBytes 、xBytes 、および yBytes は同じ数の要素を持つ。differenceBytes を返す。? AtomicReadModifyWrite (ta , index , value , subtract ) を返す。
25.4.15 Atomics.wait ( ta , index , value , timeout )
この関数は、周囲のエージェントを待機キューに入れ、通知されるか待機がタイムアウトするまでそのエージェントを一時停止し、それらの場合を区別する String を返す。
呼び出されたとき、次の手順を実行する。
? DoWait (sync , ta , index , value , timeout ) を返す。
25.4.16 Atomics.waitAsync ( ta , index , value , timeout )
この関数は、呼び出し元エージェントが通知されるかタイムアウトに達したときに解決される Promise を返す。
呼び出されたとき、次の手順を実行する。
? DoWait (async , ta , index , value , timeout ) を返す。
25.4.17 Atomics.xor ( ta , index , value )
この関数は、呼び出されたとき、次の手順を実行する。
xor を、パラメーター (xBytes , yBytes ) を持ち、何もキャプチャせず、呼び出されたときに次の手順をアトミックに実行する、新しい読み取り-変更-書き込み変更関数とする。ByteListBitwiseOp (^, xBytes , yBytes ) を返す。? 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を実行する:
obj がObjectであり、かつobj が[[IsRawJSON]] internal slotを持つなら、true を返す。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される。
jsonString を ? ToString (text ) とする。parseResult を ? ParseJSON (jsonString ) とする。unfiltered をparseResult .[[Value]] とする。IsCallable (reviver )がfalse なら、unfiltered を返す。root をOrdinaryObjectCreate (%Object.prototype% )とする。rootName をempty Stringとする。! CreateDataPropertyOrThrow (root , rootName , unfiltered )を実行する。 snapshot をCreateJSONParseRecord (parseResult .[[ParseNode]] , rootName , unfiltered )とする。? 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:
StringToCodePoints (text )がECMA-404でspecifiedされるvalid JSON textでないなら、SyntaxError 例外をthrowする。scriptString を"(" 、text 、および");" のstring-concatenation とする。script をParseText (scriptString , Script )とする。NOTE : 13.2.5.1 でdefinedされるearly error rulesは、上記のParseText のinvocationについてspecial handlingを持つ。Assert : script はParse Node である。result を ! Evaluation of script とする。NOTE : 13.2.5.6 でdefinedされるPropertyDefinitionEvaluation semanticsは、上記のevaluationについてspecial handlingを持つ。Assert : result はString、Number、Boolean、ArrayLiteral またはObjectLiteral のいずれかによってdefinedされるObject、またはnull のいずれかである。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
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:
typedValueNode をShallowestContainedJSONValue (parseNode )とする。Assert : typedValueNode はempty でない。elements をnew empty List とする。entries をnew empty List とする。value がObjectなら、isArray を ! IsArray (value ) とする。isArray がtrue なら、Assert : typedValueNode はArrayLiteral Parse Node である。contentNodes をtypedValueNode のJSONArrayLiteralContentNodes とする。length をcontentNodes 内のelementsのnumberとする。valueLength を ! LengthOfArrayLike (value ) とする。Assert : valueLength はlength である。index を0とする。Repeat, while index < length ,propertyName を ! ToString (𝔽 (index )) とする。elementParseRecord をCreateJSONParseRecord (contentNodes [index ], propertyName , ! Get (value , propertyName ))とする。elementParseRecord をelements にappendする。index をindex + 1に設定する。 そうでなければ、Assert : typedValueNode はObjectLiteral Parse Node である。propertyNodes をtypedValueNode のPropertyDefinitionNodes とする。NOTE : value はJSON textからproducedされ、modifiedされていないため、そのproperty keys はすべてStringsであり、exhaustively enumeratedされる。keys を ! EnumerableOwnProperties (value , key ) とする。keys の各String propertyKey について、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される。propertyDefinition をempty とする。propertyNodes の各Parse Node propertyNode について、propertyName をpropertyNode のPropName とする。propertyName がpropertyKey なら、propertyDefinition をpropertyNode に設定する。Assert : propertyDefinition は
PropertyDefinition :
PropertyName
:
AssignmentExpression
である。propertyValueNode をpropertyDefinition のAssignmentExpression とする。entryParseRecord をCreateJSONParseRecord (propertyValueNode , propertyKey , ! Get (value , propertyKey ))とする。entryParseRecord をentries にappendする。 そうでなければ、Assert : typedValueNode はArrayLiteral Parse Node でもObjectLiteral Parse Node でもない。 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を実行する:
value を ? Get (holder , name ) とする。context をOrdinaryObjectCreate (%Object.prototype% )とする。parseRecord がJSON Parse Record であり、SameValue (parseRecord .[[Value]] , value )がtrue なら、value がObjectでないなら、parseNode をparseRecord .[[ParseNode]] とする。Assert : parseNode はArrayLiteral Parse Node でもObjectLiteral Parse Node でもない。sourceText をparseNode によってmatchedされるsource textとする。! CreateDataPropertyOrThrow (context , "source" , CodePointsToString (sourceText ))を実行する。 elementRecords をparseRecord .[[Elements]] とする。entryRecords をparseRecord .[[Entries]] とする。そうでなければ、elementRecords をnew empty List とする。entryRecords をnew empty List とする。 value がObjectなら、isArray を ? IsArray (value ) とする。isArray がtrue なら、elementRecordsLength をelementRecords 内のelementsのnumberとする。length を ? LengthOfArrayLike (value ) とする。index を0とする。Repeat, while index < length ,propertyKey を ! ToString (𝔽 (index )) とする。index < elementRecordsLength なら、elementRecord をelementRecords [index ]とする;そうでなければ、elementRecord をempty とする。newElement を ? InternalizeJSONProperty (value , propertyKey , reviver , elementRecord ) とする。newElement がundefined なら、? value .[[Delete]] (propertyKey ) を実行する。 そうでなければ、? CreateDataProperty (value , propertyKey , newElement )を実行する。 index をindex + 1に設定する。 そうでなければ、keys を ? EnumerableOwnProperties (value , key ) とする。keys の各String propertyKey について、entryRecords のelement entry であってentry .[[Key]] がpropertyKey であるものが存在するなら、entryRecord をentry とする;そうでなければ、entryRecord をempty とする。newElement を ? InternalizeJSONProperty (value , propertyKey , reviver , entryRecord ) とする。newElement がundefined なら、? value .[[Delete]] (propertyKey ) を実行する。 そうでなければ、? CreateDataProperty (value , propertyKey , newElement )を実行する。 ? 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:
activeFunc をactive function object とする。Assert : activeFunc はJSON.parse built-in function object である(JSON.parse を参照)。types を« NullLiteral , BooleanLiteral , NumericLiteral , StringLiteral , ArrayLiteral , ObjectLiteral , UnaryExpression »とする。unaryExpr をempty とする。queue を« root »とする。Repeat, while queue is not empty,candidate をqueue のfirst elementとする。queue からfirst elementをremoveする。queuedChildren をfalse とする。types の各nonterminal type について、candidate がtype のinstanceであるなら、NOTE : JSON grammarにおいて、number tokenはnegative valueをrepresentし得る。ECMAScriptでは、negationは、UnaryExpression が-に続いてderived UnaryExpression へparseするunary operationとしてrepresentedされる。type がUnaryExpression なら、candidate のparentがUnaryExpression Parse Node でないなら、unaryExpr をcandidate に設定する。そうでなく、type がNumericLiteral なら、Assert : candidate はunaryExpr 内にcontainedされる。unaryExpr を返す。 そうでなければ、candidate を返す。 queuedChildren がfalse であり、candidate がnonterminalのinstanceであり、かつcandidate Contains type がtrue なら、children を、candidate の各child nodeをorder通りに含むList とする。queue をqueue とchildren のlist-concatenation に設定する。queuedChildren をtrue に設定する。 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 :
[
Elision opt
]
[
ElementList
]
[
ElementList
,
Elision opt
]
Assert : Elision はpresentでない。ElementList がpresentでないなら、new empty List を返す。ElementList のJSONArrayLiteralContentNodes を返す。
ElementList :
Elision opt
AssignmentExpression
Assert : Elision はpresentでない。« AssignmentExpression »を返す。
ElementList :
ElementList
,
Elision opt
AssignmentExpression
Assert : Elision はpresentでない。elements をderived ElementList のJSONArrayLiteralContentNodes とする。elements と« AssignmentExpression »のlist-concatenation を返す。
ElementList :
Elision opt
SpreadElement
ElementList
,
Elision opt
SpreadElement
NOTE : ECMA-404でspecifiedされるJSON textはSpreadElement をincludeしない。Assert : このstepに到達することはない。
25.5.3 JSON.rawJSON ( text )
このfunctionは、string、number、boolean、またはnull valueのraw JSON textをrepresentするobjectを返す。
jsonString を ? ToString (text ) とする。jsonString がempty Stringなら、SyntaxError 例外をthrowする。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する。jsonString のlast code unitが、ASCII lowercase letter code unit(0x0061から0x007Aまで、inclusive)、ASCII digit code unit(0x0030から0x0039まで、inclusive)、または0x0022 (QUOTATION MARK)のいずれでもないなら、SyntaxError 例外をthrowする。parseResult を ? ParseJSON (jsonString ) とする。Assert : parseResult .[[Value]] はString、Number、Boolean、またはnull のいずれかである。internalSlotsList を« [[IsRawJSON]] »とする。obj をOrdinaryObjectCreate (null , internalSlotsList )とする。! CreateDataPropertyOrThrow (obj , "rawJSON" , jsonString )を実行する。 ! SetIntegrityLevel (obj , frozen )を実行する。 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を実行する:
stack をnew empty List とする。indent をempty Stringとする。propertyList をundefined とする。replacerFunc をundefined とする。replacer がObjectなら、IsCallable (replacer )がtrue なら、replacerFunc をreplacer に設定する。そうでなければ、isArray を ? IsArray (replacer ) とする。isArray がtrue なら、propertyList をnew empty List に設定する。length を ? LengthOfArrayLike (replacer ) とする。k を0とする。Repeat, while k < length ,propertyKey を ! ToString (𝔽 (k )) とする。propertyValue を ? Get (replacer , propertyKey ) とする。item をundefined とする。propertyValue がStringなら、item をpropertyValue に設定する。そうでなく、propertyValue がNumberなら、item を ! ToString (propertyValue ) に設定する。 そうでなく、propertyValue がObjectなら、propertyValue が[[StringData]] または[[NumberData]] internal slotを持つなら、item を ? ToString (propertyValue ) に設定する。 item がundefined でなく、かつpropertyList がitem をcontainしないなら、item をpropertyList にappendする。k をk + 1に設定する。 space がObjectなら、space が[[NumberData]] internal slotを持つなら、space を ? ToNumber (space ) に設定する。そうでなく、space が[[StringData]] internal slotを持つなら、space を ? ToString (space ) に設定する。 space がNumberなら、spaceMV を ! ToIntegerOrInfinity (space ) とする。spaceMV をmin (10, spaceMV )に設定する。spaceMV < 1なら、gap をempty Stringとする;そうでなければ、gap をcode unit 0x0020 (SPACE)のspaceMV occurrencesを含むString valueとする。そうでなく、space がStringなら、space のlengthが10以下なら、gap をspace とする;そうでなければ、gap をspace の0から10までのsubstring とする。 そうでなければ、gap をempty Stringとする。 wrapper をOrdinaryObjectCreate (%Object.prototype% )とする。! CreateDataPropertyOrThrow (wrapper , the empty String, value )を実行する。 state をJSON Serialization Record { [[ReplacerFunction]] : replacerFunc , [[Stack]] : stack , [[Indent]] : indent , [[Gap]] : gap , [[PropertyList]] : propertyList }とする。? 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);
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:
value を ? Get (holder , key ) とする。value がObjectまたはvalue がBigIntなら、toJSON を ? GetV (value , "toJSON" ) とする。IsCallable (toJSON )がtrue なら、value を ? Call (toJSON , value , « key ») に設定する。state .[[ReplacerFunction]] がundefined でないなら、value を ? Call (state .[[ReplacerFunction]] , holder , « key , value ») に設定する。value がObjectなら、value が[[IsRawJSON]] internal slotを持つなら、rawJSON を ! Get (value , "rawJSON" ) とする。Assert : rawJSON はStringである。rawJSON を返す。value が[[NumberData]] internal slotを持つなら、value を ? ToNumber (value ) に設定する。そうでなく、value が[[StringData]] internal slotを持つなら、value を ? ToString (value ) に設定する。 そうでなく、value が[[BooleanData]] internal slotを持つなら、value をvalue .[[BooleanData]] に設定する。 そうでなく、value が[[BigIntData]] internal slotを持つなら、value をvalue .[[BigIntData]] に設定する。 value がnull なら、"null" を返す。value がtrue なら、"true" を返す。value がfalse なら、"false" を返す。value がStringなら、QuoteJSONString (value )を返す。value がNumberなら、value がfinite なら、! ToString (value )を返す。"null" を返す。value がBigIntなら、TypeError 例外をthrowする。value がObjectであり、IsCallable (value )がfalse なら、isArray を ? IsArray (value ) とする。isArray がtrue なら、? SerializeJSONArray (state , value )を返す。 ? SerializeJSONObject (state , value )を返す。 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:
product を、code unit 0x0022 (QUOTATION MARK)のみからなるString valueとする。StringToCodePoints (value )の各code point codePoint について、codePoint がTable 78 の“Code Point” columnにlistedされているなら、product を、product と、corresponding rowの“Escape Sequence” columnでspecifiedされるcodePoint のescape sequenceとのstring-concatenation に設定する。そうでなく、codePoint が0x0020 (SPACE)未満のnumeric valueを持つ、またはcodePoint がleading surrogate またはtrailing surrogate とsame numeric valueを持つなら、unit を、numeric valueがcodePoint のnumeric valueであるcode unitとする。product を、product とUnicodeEscape (unit )のstring-concatenation に設定する。 そうでなければ、product を、product とUTF16EncodeCodePoint (codePoint )のstring-concatenation に設定する。 product を、product とcode unit 0x0022 (QUOTATION MARK)のstring-concatenation に設定する。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:
n をcodeUnit のnumeric valueとする。Assert : n ≤ 0xFFFFである。hex を、lowercase hexadecimal numberとしてformattedされたn のString representationとする。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:
state .[[Stack]] がvalue をcontainするなら、structureがcyclicalであるため、TypeError 例外をthrowする。value をstate .[[Stack]] にappendする。stepBack をstate .[[Indent]] とする。state .[[Indent]] をstate .[[Indent]] とstate .[[Gap]] のstring-concatenation に設定する。state .[[PropertyList]] がundefined でないなら、keys をstate .[[PropertyList]] とする。そうでなければ、keys を ? EnumerableOwnProperties (value , key ) とする。 partial をnew empty List とする。keys の各element propertyKey について、stringP を ? SerializeJSONProperty (state , propertyKey , value ) とする。stringP がundefined でないなら、member をQuoteJSONString (propertyKey )とする。member をmember と":" のstring-concatenation に設定する。state .[[Gap]] がempty Stringでないなら、member をmember とcode unit 0x0020 (SPACE)のstring-concatenation に設定する。member をmember とstringP のstring-concatenation に設定する。member をpartial にappendする。partial がemptyなら、final を"{}" とする。そうでなければ、state .[[Gap]] がempty Stringなら、properties を、partial のすべてのelement Stringsを、adjacent pair of Stringsごとにcode unit 0x002C (COMMA)でseparatedしてconcatenatingすることによってformedされるString valueとする。commaはfirst Stringの前にもlast Stringの後にもinsertedされない。final を"{" 、properties 、および"}" のstring-concatenation とする。そうでなければ、separator をcode unit 0x002C (COMMA)、code unit 0x000A (LINE FEED)、およびstate .[[Indent]] のstring-concatenation とする。properties を、partial のすべてのelement Stringsを、adjacent pair of Stringsごとにseparator でseparatedしてconcatenatingすることによってformedされるString valueとする。separator Stringはfirst Stringの前にもlast Stringの後にもinsertedされない。final を"{" 、code unit 0x000A (LINE FEED)、state .[[Indent]] 、properties 、code unit 0x000A (LINE FEED)、stepBack 、および"}" のstring-concatenation とする。 state .[[Stack]] のlast elementをremoveする。state .[[Indent]] をstepBack に設定する。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:
state .[[Stack]] がvalue をcontainするなら、structureがcyclicalであるため、TypeError 例外をthrowする。value をstate .[[Stack]] にappendする。stepBack をstate .[[Indent]] とする。state .[[Indent]] をstate .[[Indent]] とstate .[[Gap]] のstring-concatenation に設定する。partial をnew empty List とする。length を ? LengthOfArrayLike (value ) とする。index を0とする。Repeat, while index < length ,stringP を ? SerializeJSONProperty (state , ! ToString (𝔽 (index )), value ) とする。stringP がundefined なら、"null" をpartial にappendする。そうでなければ、stringP をpartial にappendする。 index をindex + 1に設定する。 partial がemptyなら、final を"[]" とする。そうでなければ、state .[[Gap]] がempty Stringなら、properties を、partial のすべてのelement Stringsを、adjacent pair of Stringsごとにcode unit 0x002C (COMMA)でseparatedしてconcatenatingすることによってformedされるString valueとする。commaはfirst Stringの前にもlast Stringの後にもinsertedされない。final を"[" 、properties 、および"]" のstring-concatenation とする。そうでなければ、separator をcode unit 0x002C (COMMA)、code unit 0x000A (LINE FEED)、およびstate .[[Indent]] のstring-concatenation とする。properties を、partial のすべてのelement Stringsを、adjacent pair of Stringsごとにseparator でseparatedしてconcatenatingすることによってformedされるString valueとする。separator Stringはfirst Stringの前にもlast Stringの後にもinsertedされない。final を"[" 、code unit 0x000A (LINE FEED)、state .[[Indent]] 、properties 、code unit 0x000A (LINE FEED)、stepBack 、および"]" のstring-concatenation とする。 state .[[Stack]] のlast elementをremoveする。state .[[Indent]] をstepBack に設定する。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を実行する:
NewTargetがundefined なら、TypeError 例外をthrowする。 CanBeHeldWeakly (target )がfalse なら、TypeError 例外をthrowする。weakRef を ? OrdinaryCreateFromConstructor (NewTarget, "%WeakRef.prototype%" , « [[WeakRefTarget]] ») とする。AddToKeptObjects (target )を実行する。weakRef .[[WeakRefTarget]] をtarget に設定する。weakRef を返す。
26.1.2 WeakRefコンストラクタのプロパティ
WeakRef constructor は:
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 は:
26.1.3.1 WeakRef.prototype.constructor
WeakRef.prototype.constructorのinitial valueは%WeakRef% である。
26.1.3.2 WeakRef.prototype.deref ( )
このmethodは、呼び出されたときに以下のstepsを実行する:
weakRef をthis valueとする。? RequireInternalSlot (weakRef , [[WeakRefTarget]] )を実行する。 WeakRefDeref (weakRef )を返す。
Note
WeakRef がundefined でないtarget valueを返す場合、このtarget valueは、ECMAScript codeのcurrent executionがcompletedするまでガベージコレクションされるべきではない。AddToKeptObjects operationは、read consistencyがmaintainedされることを確実にする。
let target = { foo ( ) {} };
let weakRef = new WeakRef (target);
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:
target をweakRef .[[WeakRefTarget]] とする。target がempty でないなら、AddToKeptObjects (target )を実行する。target を返す。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を実行する:
NewTargetがundefined である場合、TypeError 例外を投げる。 IsCallable (cleanupCallback )がfalse である場合、TypeError 例外を投げる。? OrdinaryCreateFromConstructor (NewTarget, "%FinalizationRegistry.prototype%" , « [[Realm]] , [[CleanupCallback]] , [[Cells]] »)をfinalizationRegistry とする。 アクティブな関数オブジェクトをactiveFunc とする。 finalizationRegistry .[[Realm]] をactiveFunc .[[Realm]] に設定する。finalizationRegistry .[[CleanupCallback]] をHostMakeJobCallback (cleanupCallback )に設定する。finalizationRegistry .[[Cells]] を新しい空のList に設定する。finalizationRegistry を返す。
26.2.2 FinalizationRegistryコンストラクタのプロパティ
FinalizationRegistry constructor は:
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を実行する:
finalizationRegistry をthis valueとする。? RequireInternalSlot (finalizationRegistry , [[Cells]] )を実行する。 CanBeHeldWeakly (target )がfalse なら、TypeError 例外をthrowする。SameValue (target , heldValue )がtrue なら、TypeError 例外をthrowする。CanBeHeldWeakly (unregisterToken )がfalse なら、unregisterToken がundefined でないなら、TypeError 例外をthrowする。unregisterToken をempty に設定する。cell をRecord { [[WeakRefTarget]] : target , [[HeldValue]] : heldValue , [[UnregisterToken]] : unregisterToken }とする。cell をfinalizationRegistry .[[Cells]] にappendする。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を実行する:
finalizationRegistry をthis valueとする。? RequireInternalSlot (finalizationRegistry , [[Cells]] )を実行する。 CanBeHeldWeakly (unregisterToken )がfalse なら、TypeError 例外をthrowする。removed をfalse とする。finalizationRegistry .[[Cells]] の各Record { [[WeakRefTarget]] , [[HeldValue]] , [[UnregisterToken]] } cell について、cell .[[UnregisterToken]] がempty でなく、かつSameValue (cell .[[UnregisterToken]] , unregisterToken )がtrue なら、finalizationRegistry .[[Cells]] からcell をremoveする。removed をtrue に設定する。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
27.1.1.2 Iteratorインターフェイス
iterator interface を実装するobjectは、Table 80 内のpropertyを含まなければならない。そのようなobjectsは、Table 81 内のpropertiesを実装してもよい。
Table 80: Iterator Interface Required Properties
Note 1
next functionにargumentsを渡してもよいが、それらの解釈およびvalidityはtarget iteratorに依存する。for-of statementおよびiteratorsの他の一般的な利用者はargumentsを渡さないため、そのような方法で使用されることを期待するiterator objectsは、argumentsなしで呼び出されることに対処できるよう準備されていなければならない。
Table 81: Iterator Interface Optional Properties
Note 2
典型的には、これらのmethodsの呼び出し側は、それらをinvokeする前にそれらの存在をcheckすべきである。for-of、yield*、および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
27.1.1.4 Async Iteratorインターフェイス
async iterator interface を実装するobjectは、Table 83 内のpropertiesを含まなければならない。そのようなobjectsは、Table 84 内のpropertiesを実装してもよい。
Table 83: Async Iterator Interface Required Properties
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 ( )
? GeneratorResume (this value, undefined , "Iterator Helper" )を返す。
27.1.2.1.2 %IteratorHelperPrototype%.return ( )
obj をthis valueとする。? RequireInternalSlot (obj , [[UnderlyingIterators]] )を実行する。 Assert : obj は[[GeneratorState]] internal slotを持つ。obj .[[GeneratorState]] がsuspended-start なら、obj .[[GeneratorState]] をcompleted に設定する。NOTE : generatorがcompleted stateに入ると、そこから離れることはなく、関連付けられたexecution context は再開されない。この時点で、obj に関連付けられた任意のexecution stateは破棄できる。? IteratorCloseAll (obj .[[UnderlyingIterators]] , NormalCompletion (unused ))を実行する。 CreateIteratorResultObject (undefined , true )を返す。completion をReturnCompletion (undefined )とする。? 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を実行する:
NewTargetがundefined またはactive function object なら、TypeError 例外をthrowする。 ? OrdinaryCreateFromConstructor (NewTarget, "%Iterator.prototype%" )を返す。
27.1.3.2 Iteratorコンストラクタのプロパティ
Iterator constructor は:
27.1.3.2.1 Iterator.concat ( ...items )
iterables をnew empty List とする。items の各element item について、item がObjectでないなら、TypeError 例外をthrowする。method を ? GetMethod (item , %Symbol.iterator% ) とする。method がundefined なら、TypeError 例外をthrowする。Record { [[OpenMethod]] : method , [[Iterable]] : item }をiterables にappendする。closure を、iterables をcaptureし、呼び出されたときに以下のstepsを実行する、parametersを持たないnew Abstract Closure とする:iterables の各Record iterable について、iterator を ? Call (iterable .[[OpenMethod]] , iterable .[[Iterable]] ) とする。iterator がObjectでないなら、TypeError 例外をthrowする。iteratorRecord を ? GetIteratorDirect (iterator ) とする。innerAlive をtrue とする。innerAlive がtrue である間、繰り返す:innerValue を ? IteratorStepValue (iteratorRecord ) とする。innerValue がdone なら、innerAlive をfalse に設定する。そうでなければ、completion をCompletion (Yield (innerValue ))とする。completion がabrupt completion なら、? IteratorClose (iteratorRecord , completion )を返す。 ReturnCompletion (undefined )を返す。gen をCreateIteratorFromClosure (closure , "Iterator Helper" , %IteratorHelperPrototype% , « [[UnderlyingIterators]] »)とする。gen .[[UnderlyingIterators]] をnew empty List に設定する。gen を返す。
27.1.3.2.2 Iterator.from ( obj )
iteratorRecord を ? GetIteratorFlattenable (obj , iterate-string-primitives ) とする。hasInstance を ? OrdinaryHasInstance (%Iterator% , iteratorRecord .[[Iterator]] ) とする。hasInstance がtrue なら、iteratorRecord .[[Iterator]] を返す。wrapper をOrdinaryObjectCreate (%WrapForValidIteratorPrototype% , « [[Iterated]] »)とする。wrapper .[[Iterated]] をiteratorRecord に設定する。wrapper を返す。
27.1.3.2.2.1 %WrapForValidIteratorPrototype%オブジェクト
%WrapForValidIteratorPrototype% objectは:
27.1.3.2.2.1.1 %WrapForValidIteratorPrototype%.next ( )
obj をthis valueとする。? RequireInternalSlot (obj , [[Iterated]] )を実行する。 iteratorRecord をobj .[[Iterated]] とする。? Call (iteratorRecord .[[NextMethod]] , iteratorRecord .[[Iterator]] )を返す。
27.1.3.2.2.1.2 %WrapForValidIteratorPrototype%.return ( )
obj をthis valueとする。? RequireInternalSlot (obj , [[Iterated]] )を実行する。 iterator をobj .[[Iterated]] .[[Iterator]] とする。Assert : iterator はObjectである。returnMethod を ? GetMethod (iterator , "return" ) とする。returnMethod がundefined なら、CreateIteratorResultObject (undefined , true )を返す。? 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を実行する:
iterables がObjectでないなら、TypeError 例外をthrowする。options を ? GetOptionsObject (options ) に設定する。mode を ? Get (options , "mode" ) とする。mode がundefined なら、mode を"shortest" に設定する。mode が"shortest" 、"longest" 、または"strict" のいずれでもないなら、TypeError 例外をthrowする。paddingOption をundefined とする。mode が"longest" なら、paddingOption を ? Get (options , "padding" ) に設定する。paddingOption がundefined でなく、かつObjectでないなら、TypeError 例外をthrowする。iters をnew empty List とする。padding をnew empty List とする。inputIter を ? GetIterator (iterables , sync ) とする。next をnot-started とする。next がdone でない間、繰り返す:next をCompletion (IteratorStepValue (inputIter ))に設定する。IfAbruptCloseIterators (next , iters ).next がdone でないなら、iter をCompletion (GetIteratorFlattenable (next , reject-primitives ))とする。needClosing を« inputIter »とiters のlist-concatenation とする。IfAbruptCloseIterators (iter , needClosing ).iter をiters にappendする。iterCount をiters のelements数とする。mode が"longest" なら、paddingOption がundefined なら、iterCount 回繰り返す:undefined をpadding にappendする。そうでなければ、paddingIter をCompletion (GetIterator (paddingOption , sync ))とする。IfAbruptCloseIterators (paddingIter , iters ).usingIterator をtrue とする。iterCount 回繰り返す:usingIterator がtrue なら、next をCompletion (IteratorStepValue (paddingIter ))に設定する。IfAbruptCloseIterators (next , iters ).next がdone なら、usingIterator をfalse に設定する。そうでなければ、next をpadding にappendする。 usingIterator がfalse なら、undefined をpadding にappendする。usingIterator がtrue なら、completion をCompletion (IteratorClose (paddingIter , NormalCompletion (unused )))とする。IfAbruptCloseIterators (completion , iters ). finishResults を、parameters (results )を持ち、何もcaptureせず、呼び出されたときに以下のstepsを実行するnew Abstract Closure とする:CreateArrayFromList (results )を返す。IteratorZip (iters , mode , padding , finishResults )を返す。
27.1.3.2.5 Iterator.zipKeyed ( iterables [ , options ] )
このfunctionは、呼び出されたときに以下のstepsを実行する:
iterables がObjectでないなら、TypeError 例外をthrowする。options を ? GetOptionsObject (options ) に設定する。mode を ? Get (options , "mode" ) とする。mode がundefined なら、mode を"shortest" に設定する。mode が"shortest" 、"longest" 、または"strict" のいずれでもないなら、TypeError 例外をthrowする。paddingOption をundefined とする。mode が"longest" なら、paddingOption を ? Get (options , "padding" ) に設定する。paddingOption がundefined でなく、かつObjectでないなら、TypeError 例外をthrowする。iters をnew empty List とする。padding をnew empty List とする。allKeys を ? iterables .[[OwnPropertyKeys]] () とする。keys をnew empty List とする。allKeys の各element key について、propertyDesc をCompletion (iterables .[[GetOwnProperty]] (key ))とする。IfAbruptCloseIterators (propertyDesc , iters ).propertyDesc がundefined でなく、かつpropertyDesc .[[Enumerable]] がtrue なら、value をCompletion (Get (iterables , key ))とする。IfAbruptCloseIterators (value , iters ).value がundefined でないなら、key をkeys にappendする。iter をCompletion (GetIteratorFlattenable (value , reject-primitives ))とする。IfAbruptCloseIterators (iter , iters ).iter をiters にappendする。iterCount をiters のelements数とする。mode が"longest" なら、paddingOption がundefined なら、iterCount 回繰り返す:undefined をpadding にappendする。そうでなければ、keys の各element key について、value をCompletion (Get (paddingOption , key ))とする。IfAbruptCloseIterators (value , iters ).value をpadding にappendする。 finishResults を、parameters (results )を持ち、keys とiterCount をcaptureし、呼び出されたときに以下のstepsを実行するnew Abstract Closure とする:obj をOrdinaryObjectCreate (null )とする。0 ≤ i < iterCount である各integer i について、昇順で、! CreateDataPropertyOrThrow (obj , keys [i ], results [i ])を実行する。 obj を返す。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を実行する:
%Iterator% を返す。
27.1.3.3.1.2 set Iterator.prototype.constructor
[[Set]] attributeのvalueは、argument v を取るbuilt-in functionである。呼び出されたときに以下のstepsを実行する:
? SetterThatIgnoresPrototypeProperties (this value, %Iterator.prototype% , "constructor" , v )を実行する。 undefined を返す。
Note
ほとんどのbuilt-in prototypes上の"constructor" propertyとは異なり、web-compatibilityの理由により、このpropertyはaccessorでなければならない。
27.1.3.3.2 Iterator.prototype.drop ( limit )
このmethodは、呼び出されたときに以下のstepsを実行する:
obj をthis valueとする。obj がObjectでないなら、TypeError 例外をthrowする。iterated をIterator Record { [[Iterator]] : obj , [[NextMethod]] : undefined , [[Done]] : false }とする。numberLimit をCompletion (ToNumber (limit ))とする。IfAbruptCloseIterator (numberLimit , iterated ).numberLimit がNaN なら、error をThrowCompletion (a newly created RangeError object)とする。? IteratorClose (iterated , error )を返す。 intLimit を ! ToIntegerOrInfinity (numberLimit ) とする。intLimit < 0なら、error をThrowCompletion (a newly created RangeError object)とする。? IteratorClose (iterated , error )を返す。 iterated を ? GetIteratorDirect (obj ) に設定する。closure を、iterated とintLimit をcaptureし、呼び出されたときに以下のstepsを実行する、parametersを持たないnew Abstract Closure とする:remaining をintLimit とする。remaining > 0である間、繰り返す:remaining ≠ +∞なら、remaining をremaining - 1に設定する。next を ? IteratorStep (iterated ) とする。next がdone なら、ReturnCompletion (undefined )を返す。繰り返す:value を ? IteratorStepValue (iterated ) とする。value がdone なら、ReturnCompletion (undefined )を返す。completion をCompletion (Yield (value ))とする。IfAbruptCloseIterator (completion , iterated ). result をCreateIteratorFromClosure (closure , "Iterator Helper" , %IteratorHelperPrototype% , « [[UnderlyingIterators]] »)とする。result .[[UnderlyingIterators]] を« iterated »に設定する。result を返す。
27.1.3.3.3 Iterator.prototype.every ( predicate )
このmethodは、呼び出されたときに以下のstepsを実行する:
obj をthis valueとする。obj がObjectでないなら、TypeError 例外をthrowする。iterated をIterator Record { [[Iterator]] : obj , [[NextMethod]] : undefined , [[Done]] : false }とする。IsCallable (predicate )がfalse なら、error をThrowCompletion (a newly created TypeError object)とする。? IteratorClose (iterated , error )を返す。 iterated を ? GetIteratorDirect (obj ) に設定する。counter を0とする。繰り返す:value を ? IteratorStepValue (iterated ) とする。value がdone なら、true を返す。result をCompletion (Call (predicate , undefined , « value , 𝔽 (counter ) »))とする。IfAbruptCloseIterator (result , iterated ).ToBoolean (result )がfalse なら、? IteratorClose (iterated , NormalCompletion (false ))を返す。counter をcounter + 1に設定する。
27.1.3.3.4 Iterator.prototype.filter ( predicate )
このmethodは、呼び出されたときに以下のstepsを実行する:
obj をthis valueとする。obj がObjectでないなら、TypeError 例外をthrowする。iterated をIterator Record { [[Iterator]] : obj , [[NextMethod]] : undefined , [[Done]] : false }とする。IsCallable (predicate )がfalse なら、error をThrowCompletion (a newly created TypeError object)とする。? IteratorClose (iterated , error )を返す。 iterated を ? GetIteratorDirect (obj ) に設定する。closure を、iterated とpredicate をcaptureし、呼び出されたときに以下のstepsを実行する、parametersを持たないnew Abstract Closure とする:counter を0とする。繰り返す:value を ? IteratorStepValue (iterated ) とする。value がdone なら、ReturnCompletion (undefined )を返す。selected をCompletion (Call (predicate , undefined , « value , 𝔽 (counter ) »))とする。IfAbruptCloseIterator (selected , iterated ).ToBoolean (selected )がtrue なら、completion をCompletion (Yield (value ))とする。IfAbruptCloseIterator (completion , iterated ).counter をcounter + 1に設定する。 result をCreateIteratorFromClosure (closure , "Iterator Helper" , %IteratorHelperPrototype% , « [[UnderlyingIterators]] »)とする。result .[[UnderlyingIterators]] を« iterated »に設定する。result を返す。
27.1.3.3.5 Iterator.prototype.find ( predicate )
このmethodは、呼び出されたときに以下のstepsを実行する:
obj をthis valueとする。obj がObjectでないなら、TypeError 例外をthrowする。iterated をIterator Record { [[Iterator]] : obj , [[NextMethod]] : undefined , [[Done]] : false }とする。IsCallable (predicate )がfalse なら、error をThrowCompletion (a newly created TypeError object)とする。? IteratorClose (iterated , error )を返す。 iterated を ? GetIteratorDirect (obj ) に設定する。counter を0とする。繰り返す:value を ? IteratorStepValue (iterated ) とする。value がdone なら、undefined を返す。result をCompletion (Call (predicate , undefined , « value , 𝔽 (counter ) »))とする。IfAbruptCloseIterator (result , iterated ).ToBoolean (result )がtrue なら、? IteratorClose (iterated , NormalCompletion (value ))を返す。counter をcounter + 1に設定する。
27.1.3.3.6 Iterator.prototype.flatMap ( mapper )
このmethodは、呼び出されたときに以下のstepsを実行する:
obj をthis valueとする。obj がObjectでないなら、TypeError 例外をthrowする。iterated をIterator Record { [[Iterator]] : obj , [[NextMethod]] : undefined , [[Done]] : false }とする。IsCallable (mapper )がfalse なら、error をThrowCompletion (a newly created TypeError object)とする。? IteratorClose (iterated , error )を返す。 iterated を ? GetIteratorDirect (obj ) に設定する。closure を、iterated とmapper をcaptureし、呼び出されたときに以下のstepsを実行する、parametersを持たないnew Abstract Closure とする:counter を0とする。繰り返す:value を ? IteratorStepValue (iterated ) とする。value がdone なら、ReturnCompletion (undefined )を返す。mapped をCompletion (Call (mapper , undefined , « value , 𝔽 (counter ) »))とする。IfAbruptCloseIterator (mapped , iterated ).innerIterator をCompletion (GetIteratorFlattenable (mapped , reject-primitives ))とする。IfAbruptCloseIterator (innerIterator , iterated ).innerAlive をtrue とする。innerAlive がtrue である間、繰り返す:innerValue をCompletion (IteratorStepValue (innerIterator ))とする。IfAbruptCloseIterator (innerValue , iterated ).innerValue がdone なら、innerAlive をfalse に設定する。そうでなければ、completion をCompletion (Yield (innerValue ))とする。completion がabrupt completion なら、backupCompletion をCompletion (IteratorClose (innerIterator , completion ))とする。IfAbruptCloseIterator (backupCompletion , iterated ).? IteratorClose (iterated , completion )を返す。 counter をcounter + 1に設定する。 result をCreateIteratorFromClosure (closure , "Iterator Helper" , %IteratorHelperPrototype% , « [[UnderlyingIterators]] »)とする。result .[[UnderlyingIterators]] を« iterated »に設定する。result を返す。
27.1.3.3.7 Iterator.prototype.forEach ( procedure )
このmethodは、呼び出されたときに以下のstepsを実行する:
obj をthis valueとする。obj がObjectでないなら、TypeError 例外をthrowする。iterated をIterator Record { [[Iterator]] : obj , [[NextMethod]] : undefined , [[Done]] : false }とする。IsCallable (procedure )がfalse なら、error をThrowCompletion (a newly created TypeError object)とする。? IteratorClose (iterated , error )を返す。 iterated を ? GetIteratorDirect (obj ) に設定する。counter を0とする。繰り返す:value を ? IteratorStepValue (iterated ) とする。value がdone なら、undefined を返す。result をCompletion (Call (procedure , undefined , « value , 𝔽 (counter ) »))とする。IfAbruptCloseIterator (result , iterated ).counter をcounter + 1に設定する。
27.1.3.3.8 Iterator.prototype.map ( mapper )
このmethodは、呼び出されたときに以下のstepsを実行する:
obj をthis valueとする。obj がObjectでないなら、TypeError 例外をthrowする。iterated をIterator Record { [[Iterator]] : obj , [[NextMethod]] : undefined , [[Done]] : false }とする。IsCallable (mapper )がfalse なら、error をThrowCompletion (a newly created TypeError object)とする。? IteratorClose (iterated , error )を返す。 iterated を ? GetIteratorDirect (obj ) に設定する。closure を、iterated とmapper をcaptureし、呼び出されたときに以下のstepsを実行する、parametersを持たないnew Abstract Closure とする:counter を0とする。繰り返す:value を ? IteratorStepValue (iterated ) とする。value がdone なら、ReturnCompletion (undefined )を返す。mapped をCompletion (Call (mapper , undefined , « value , 𝔽 (counter ) »))とする。IfAbruptCloseIterator (mapped , iterated ).completion をCompletion (Yield (mapped ))とする。IfAbruptCloseIterator (completion , iterated ).counter をcounter + 1に設定する。 result をCreateIteratorFromClosure (closure , "Iterator Helper" , %IteratorHelperPrototype% , « [[UnderlyingIterators]] »)とする。result .[[UnderlyingIterators]] を« iterated »に設定する。result を返す。
27.1.3.3.9 Iterator.prototype.reduce ( reducer [ , initialValue ] )
このmethodは、呼び出されたときに以下のstepsを実行する:
obj をthis valueとする。obj がObjectでないなら、TypeError 例外をthrowする。iterated をIterator Record { [[Iterator]] : obj , [[NextMethod]] : undefined , [[Done]] : false }とする。IsCallable (reducer )がfalse なら、error をThrowCompletion (a newly created TypeError object)とする。? IteratorClose (iterated , error )を返す。 iterated を ? GetIteratorDirect (obj ) に設定する。initialValue が存在しないなら、accumulator を ? IteratorStepValue (iterated ) とする。accumulator がdone なら、TypeError 例外をthrowする。counter を1とする。そうでなければ、accumulator をinitialValue とする。counter を0とする。 繰り返す:value を ? IteratorStepValue (iterated ) とする。value がdone なら、accumulator を返す。result をCompletion (Call (reducer , undefined , « accumulator , value , 𝔽 (counter ) »))とする。IfAbruptCloseIterator (result , iterated ).accumulator をresult に設定する。counter をcounter + 1に設定する。
27.1.3.3.10 Iterator.prototype.some ( predicate )
このmethodは、呼び出されたときに以下のstepsを実行する:
obj をthis valueとする。obj がObjectでないなら、TypeError 例外をthrowする。iterated をIterator Record { [[Iterator]] : obj , [[NextMethod]] : undefined , [[Done]] : false }とする。IsCallable (predicate )がfalse なら、error をThrowCompletion (a newly created TypeError object)とする。? IteratorClose (iterated , error )を返す。 iterated を ? GetIteratorDirect (obj ) に設定する。counter を0とする。繰り返す:value を ? IteratorStepValue (iterated ) とする。value がdone なら、false を返す。result をCompletion (Call (predicate , undefined , « value , 𝔽 (counter ) »))とする。IfAbruptCloseIterator (result , iterated ).ToBoolean (result )がtrue なら、? IteratorClose (iterated , NormalCompletion (true ))を返す。counter をcounter + 1に設定する。
27.1.3.3.11 Iterator.prototype.take ( limit )
このmethodは、呼び出されたときに以下のstepsを実行する:
obj をthis valueとする。obj がObjectでないなら、TypeError 例外をthrowする。iterated をIterator Record { [[Iterator]] : obj , [[NextMethod]] : undefined , [[Done]] : false }とする。numberLimit をCompletion (ToNumber (limit ))とする。IfAbruptCloseIterator (numberLimit , iterated ).numberLimit がNaN なら、error をThrowCompletion (a newly created RangeError object)とする。? IteratorClose (iterated , error )を返す。 intLimit を ! ToIntegerOrInfinity (numberLimit ) とする。intLimit < 0なら、error をThrowCompletion (a newly created RangeError object)とする。? IteratorClose (iterated , error )を返す。 iterated を ? GetIteratorDirect (obj ) に設定する。closure を、iterated とintLimit をcaptureし、呼び出されたときに以下のstepsを実行する、parametersを持たないnew Abstract Closure とする:remaining をintLimit とする。繰り返す:remaining = 0なら、? IteratorClose (iterated , ReturnCompletion (undefined ))を返す。 remaining ≠ +∞なら、remaining をremaining - 1に設定する。value を ? IteratorStepValue (iterated ) とする。value がdone なら、ReturnCompletion (undefined )を返す。completion をCompletion (Yield (value ))とする。IfAbruptCloseIterator (completion , iterated ). result をCreateIteratorFromClosure (closure , "Iterator Helper" , %IteratorHelperPrototype% , « [[UnderlyingIterators]] »)とする。result .[[UnderlyingIterators]] を« iterated »に設定する。result を返す。
27.1.3.3.12 Iterator.prototype.toArray ( )
このmethodは、呼び出されたときに以下のstepsを実行する:
obj をthis valueとする。obj がObjectでないなら、TypeError 例外をthrowする。iterated を ? GetIteratorDirect (obj ) とする。items をnew empty List とする。繰り返す:value を ? IteratorStepValue (iterated ) とする。value がdone なら、CreateArrayFromList (items )を返す。value をitems にappendする。
27.1.3.3.13 Iterator.prototype [ %Symbol.dispose% ] ( )
このメソッドは、呼び出されたときに次のステップを実行する:
obj を this 値とする。return を ? GetMethod (obj , "return" ) とする。return が undefined でない場合、then? Call (return , obj ) を実行する。 undefined を返す。
このメソッドの "name" プロパティの値は "[Symbol.dispose]" である。
27.1.3.3.14 Iterator.prototype [ %Symbol.iterator% ] ( )
このfunctionは、呼び出されたときに以下のstepsを実行する:
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を実行する:
"Iterator" を返す。
27.1.3.3.15.2 set Iterator.prototype [ %Symbol.toStringTag% ]
[[Set]] attributeのvalueは、argument v を取るbuilt-in functionである。呼び出されたときに以下のstepsを実行する:
? SetterThatIgnoresPrototypeProperties (this value, %Iterator.prototype% , %Symbol.toStringTag% , v )を実行する。 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:
iterCount をiters のelements数とする。openIters をiters のcopyとする。closure を、iters 、iterCount 、openIters 、mode 、padding 、およびfinishResults をcaptureし、呼び出されたときに以下のstepsを実行する、parametersを持たないnew Abstract Closure とする:iterCount = 0なら、ReturnCompletion (undefined )を返す。繰り返す:results をnew empty List とする。Assert : openIters はemptyでない。0 ≤ i < iterCount である各integer i について、昇順で、iter をiters [i ]とする。iter がnull なら、Assert : mode は"longest" である。result をpadding [i ]とする。そうでなければ、result をCompletion (IteratorStepValue (iter ))とする。result がabrupt completion なら、openIters からiter をremoveする。? IteratorCloseAll (openIters , result )を返す。 result を ! result に設定する。result がdone なら、openIters からiter をremoveする。mode が"shortest" なら、? IteratorCloseAll (openIters , ReturnCompletion (undefined ))を返す。 そうでなく、mode が"strict" なら、i ≠ 0なら、? IteratorCloseAll (openIters , ThrowCompletion (a newly created TypeError object))を返す。 1 ≤ k < iterCount である各integer k について、昇順で、Assert : iters [k ]はnull でない。open をCompletion (IteratorStep (iters [k ]))とする。open がabrupt completion なら、openIters からiters [k ]をremoveする。? IteratorCloseAll (openIters , open )を返す。 open を ! open に設定する。open がdone なら、openIters からiters [k ]をremoveする。そうでなければ、? IteratorCloseAll (openIters , ThrowCompletion (a newly created TypeError object))を返す。 ReturnCompletion (undefined )を返す。 そうでなければ、Assert : mode は"longest" である。openIters がemptyなら、ReturnCompletion (undefined )を返す。iters [i ]をnull に設定する。result をpadding [i ]に設定する。 result をresults にappendする。 results をfinishResults (results )に設定する。completion をCompletion (Yield (results ))とする。IfAbruptCloseIterators (completion , openIters ). gen をCreateIteratorFromClosure (closure , "Iterator Helper" , %IteratorHelperPrototype% , « [[UnderlyingIterators]] »)とする。gen .[[UnderlyingIterators]] をopenIters に設定する。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% ] ( )
このメソッドは、呼び出されたときに次のステップを実行する:
obj を this 値とする。promiseCapability を ! NewPromiseCapability (%Promise% ) とする。return を Completion (GetMethod (obj , "return" ))) とする。IfAbruptRejectPromise (return , promiseCapability ).return が undefined である場合、then! Call (promiseCapability .[[Resolve]] , undefined , « undefined ») を実行する。 Else,result を Completion (Call (return , obj , « »)) とする。IfAbruptRejectPromise (result , promiseCapability ).resultWrapper を Completion (PromiseResolve (%Promise% , result )) とする。IfAbruptRejectPromise (resultWrapper , promiseCapability ).unwrap を、何もキャプチャせず、呼び出されたときに次のステップを実行する、パラメータを持たない新しい Abstract Closure とする:undefined を返す。onFulfilled を CreateBuiltinFunction (unwrap , 1, "" , « ») とする。PerformPromiseThen (resultWrapper , onFulfilled , undefined , promiseCapability ) を実行する。 promiseCapability .[[Promise]] を返す。
このメソッドの "name" プロパティの値は "[Symbol.asyncDispose]" である。
27.1.4.2 %AsyncIteratorPrototype% [ %Symbol.asyncIterator% ] ( )
このfunctionは、呼び出されたときに以下のstepsを実行する:
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:
asyncIterator をOrdinaryObjectCreate (%AsyncFromSyncIteratorPrototype% , « [[SyncIteratorRecord]] »)とする。asyncIterator .[[SyncIteratorRecord]] をsyncIteratorRecord に設定する。nextMethod を ! Get (asyncIterator , "next" ) とする。iteratorRecord をIterator Record { [[Iterator]] : asyncIterator , [[NextMethod]] : nextMethod , [[Done]] : false }とする。iteratorRecord を返す。
27.1.5.2 %AsyncFromSyncIteratorPrototype%オブジェクト
%AsyncFromSyncIteratorPrototype% objectは:
27.1.5.2.1 %AsyncFromSyncIteratorPrototype%.next ( [ value ] )
obj をthis valueとする。Assert : obj は[[SyncIteratorRecord]] internal slotを持つObjectである。promiseCapability を ! NewPromiseCapability (%Promise% ) とする。syncIteratorRecord をobj .[[SyncIteratorRecord]] とする。value が存在するなら、result をCompletion (IteratorNext (syncIteratorRecord , value ))とする。そうでなければ、result をCompletion (IteratorNext (syncIteratorRecord ))とする。 IfAbruptRejectPromise (result , promiseCapability ).AsyncFromSyncIteratorContinuation (result , promiseCapability , syncIteratorRecord , true )を返す。
27.1.5.2.2 %AsyncFromSyncIteratorPrototype%.return ( [ value ] )
obj をthis valueとする。Assert : obj は[[SyncIteratorRecord]] internal slotを持つObjectである。promiseCapability を ! NewPromiseCapability (%Promise% ) とする。syncIteratorRecord をobj .[[SyncIteratorRecord]] とする。syncIterator をsyncIteratorRecord .[[Iterator]] とする。return をCompletion (GetMethod (syncIterator , "return" ))とする。IfAbruptRejectPromise (return , promiseCapability ).return がundefined なら、iteratorResult をCreateIteratorResultObject (value , true )とする。! Call (promiseCapability .[[Resolve]] , undefined , « iteratorResult »)を実行する。 promiseCapability .[[Promise]] を返す。value が存在するなら、result をCompletion (Call (return , syncIterator , « value »))とする。そうでなければ、result をCompletion (Call (return , syncIterator ))とする。 IfAbruptRejectPromise (result , promiseCapability ).result がObjectでないなら、! Call (promiseCapability .[[Reject]] , undefined , « a newly created TypeError object »)を実行する。 promiseCapability .[[Promise]] を返す。AsyncFromSyncIteratorContinuation (result , promiseCapability , syncIteratorRecord , false )を返す。
27.1.5.2.3 %AsyncFromSyncIteratorPrototype%.throw ( [ value ] )
Note このspecificationでは、
value は常に提供されるが、
%AsyncFromSyncIteratorPrototype%.return ( [ value ] ) との一貫性のためにoptionalのままにされている。
obj をthis valueとする。Assert : obj は[[SyncIteratorRecord]] internal slotを持つObjectである。promiseCapability を ! NewPromiseCapability (%Promise% ) とする。syncIteratorRecord をobj .[[SyncIteratorRecord]] とする。syncIterator をsyncIteratorRecord .[[Iterator]] とする。throw をCompletion (GetMethod (syncIterator , "throw" ))とする。IfAbruptRejectPromise (throw , promiseCapability ).throw がundefined なら、NOTE : syncIterator にthrow methodがない場合、capabilityをrejectする前にcleanupの機会を与えるためにそれをcloseする。closeCompletion をNormalCompletion (empty )とする。result をCompletion (IteratorClose (syncIteratorRecord , closeCompletion ))とする。IfAbruptRejectPromise (result , promiseCapability ).NOTE : 次のstepは、protocol violationがあったことを示すためにTypeError をthrowする:syncIterator はthrow methodを持たない。NOTE : syncIterator のclosingがthrowしない場合、そのoperationのresultは、それがrejected promiseをyieldする場合であっても無視される。! Call (promiseCapability .[[Reject]] , undefined , « a newly created TypeError object »)を実行する。 promiseCapability .[[Promise]] を返す。value が存在するなら、result をCompletion (Call (throw , syncIterator , « value »))とする。そうでなければ、result をCompletion (Call (throw , syncIterator ))とする。 IfAbruptRejectPromise (result , promiseCapability ).result がObjectでないなら、! Call (promiseCapability .[[Reject]] , undefined , « a newly created TypeError object »)を実行する。 promiseCapability .[[Promise]] を返す。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
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:
NOTE : promiseCapability はintrinsic %Promise% からderivedされるため、下記のIfAbruptRejectPromise の使用によって必要となるpromiseCapability .[[Reject]] へのcallsは、throwしないことがguaranteedされる。done をCompletion (IteratorComplete (result ))とする。IfAbruptRejectPromise (done , promiseCapability ).value をCompletion (IteratorValue (result ))とする。IfAbruptRejectPromise (value , promiseCapability ).valueWrapper をCompletion (PromiseResolve (%Promise% , value ))とする。valueWrapper がabrupt completion で、done がfalse で、closeOnRejection がtrue なら、valueWrapper をCompletion (IteratorClose (syncIteratorRecord , valueWrapper ))に設定する。IfAbruptRejectPromise (valueWrapper , promiseCapability ).unwrap を、parameters (v )を持ち、done をcaptureし、呼び出されたときに以下のstepsを実行するnew Abstract Closure とする:CreateIteratorResultObject (v , done )を返す。onFulfilled をCreateBuiltinFunction (unwrap , 1, "" , « »)とする。NOTE : onFulfilled は、IteratorResult object の"value" propertyを処理するとき、そのvalueがpromiseである場合にそれを待ち、resultを新しい“unwrapped” IteratorResult object に再packageするために使用される。done がtrue またはcloseOnRejection がfalse なら、onRejected をundefined とする。そうでなければ、closeIterator を、parameters (error )を持ち、syncIteratorRecord をcaptureし、呼び出されたときに以下のstepsを実行するnew Abstract Closure とする:? IteratorClose (syncIteratorRecord , ThrowCompletion (error ))を返す。 onRejected をCreateBuiltinFunction (closeIterator , 1, "" , « »)とする。NOTE : onRejected は、Iterator がyieldするIteratorResult object の"value" propertyがrejected promiseである場合に、そのIterator をcloseするために使用される。 PerformPromiseThen (valueWrapper , onFulfilled , onRejected , promiseCapability )を実行する。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 ( )
この関数は、呼び出されたときに次のステップを実行する:
NewTarget が undefined である場合、TypeError 例外を投げる。 disposableStack を ? OrdinaryCreateFromConstructor (NewTarget, "%DisposableStack.prototype%" , « [[DisposableState]] , [[DisposableResourceStack]] ») とする。disposableStack .[[DisposableState]] を pending に設定する。disposableStack .[[DisposableResourceStack]] を新しい空の List に設定する。disposableStack を返す。
27.3.2 DisposableStack コンストラクタのプロパティ
DisposableStack コンストラクタは次のとおりである:
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 )
このメソッドは、呼び出されたときに次のステップを実行する:
disposableStack を this 値とする。? RequireInternalSlot (disposableStack , [[DisposableState]] ) を実行する。 disposableStack .[[DisposableState]] が disposed である場合、ReferenceError 例外を投げる。IsCallable (onDispose ) が false である場合、TypeError 例外を投げる。closure を、value と onDispose をキャプチャし、呼び出されたときに次のステップを実行する、パラメータを持たない新しい Abstract Closure とする:Return ? Call (onDispose , undefined , « value »). func を CreateBuiltinFunction (closure , 0, "" , « ») とする。? AddDisposableResource (disposableStack .[[DisposableResourceStack]] , undefined , sync-dispose , func ) を実行する。 value を返す。
27.3.3.2 DisposableStack.prototype.constructor
DisposableStack.prototype.constructor の初期値は %DisposableStack% である。
27.3.3.3 DisposableStack.prototype.defer ( onDispose )
このメソッドは、呼び出されたときに次のステップを実行する:
disposableStack を this 値とする。? RequireInternalSlot (disposableStack , [[DisposableState]] ) を実行する。 disposableStack .[[DisposableState]] が disposed である場合、ReferenceError 例外を投げる。IsCallable (onDispose ) が false である場合、TypeError 例外を投げる。? AddDisposableResource (disposableStack .[[DisposableResourceStack]] , undefined , sync-dispose , onDispose ) を実行する。 undefined を返す。
27.3.3.4 DisposableStack.prototype.dispose ( )
このメソッドは、呼び出されたときに次のステップを実行する:
disposableStack を this 値とする。? RequireInternalSlot (disposableStack , [[DisposableState]] ) を実行する。 disposableStack .[[DisposableState]] が disposed である場合、undefined を返す。disposableStack .[[DisposableState]] を disposed に設定する。Return ? DisposeResources (disposableStack .[[DisposableResourceStack]] , NormalCompletion (undefined )).
27.3.3.5 get DisposableStack.prototype.disposed
DisposableStack.prototype.disposed は、set アクセサ関数が undefined であるアクセサプロパティである。その get アクセサ関数は、呼び出されたときに次のステップを実行する:
disposableStack を this 値とする。? RequireInternalSlot (disposableStack , [[DisposableState]] ) を実行する。 disposableStack .[[DisposableState]] が disposed である場合、true を返す。false を返す。
27.3.3.6 DisposableStack.prototype.move ( )
このメソッドは、呼び出されたときに次のステップを実行する:
disposableStack を this 値とする。? RequireInternalSlot (disposableStack , [[DisposableState]] ) を実行する。 disposableStack .[[DisposableState]] が disposed である場合、ReferenceError 例外を投げる。newDisposableStack を ? OrdinaryCreateFromConstructor (%DisposableStack% , "%DisposableStack.prototype%" , « [[DisposableState]] , [[DisposableResourceStack]] ») とする。newDisposableStack .[[DisposableState]] を pending に設定する。newDisposableStack .[[DisposableResourceStack]] を disposableStack .[[DisposableResourceStack]] に設定する。disposableStack .[[DisposableResourceStack]] を新しい空の List に設定する。disposableStack .[[DisposableState]] を disposed に設定する。newDisposableStack を返す。
27.3.3.7 DisposableStack.prototype.use ( value )
このメソッドは、呼び出されたときに次のステップを実行する:
disposableStack を this 値とする。? RequireInternalSlot (disposableStack , [[DisposableState]] ) を実行する。 disposableStack .[[DisposableState]] が disposed である場合、ReferenceError 例外を投げる。? AddDisposableResource (disposableStack .[[DisposableResourceStack]] , value , sync-dispose ) を実行する。 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 ( )
この関数は、呼び出されたときに次のステップを実行する:
NewTarget が undefined である場合、TypeError 例外を投げる。 asyncDisposableStack を ? OrdinaryCreateFromConstructor (NewTarget, "%AsyncDisposableStack.prototype%" , « [[AsyncDisposableState]] , [[DisposableResourceStack]] ») とする。asyncDisposableStack .[[AsyncDisposableState]] を pending に設定する。asyncDisposableStack .[[DisposableResourceStack]] を新しい空の List に設定する。asyncDisposableStack を返す。
27.4.2 AsyncDisposableStack コンストラクタのプロパティ
AsyncDisposableStack コンストラクタは次のとおりである:
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 )
このメソッドは、呼び出されたときに次のステップを実行する:
asyncDisposableStack を this 値とする。? RequireInternalSlot (asyncDisposableStack , [[AsyncDisposableState]] ) を実行する。 asyncDisposableStack .[[AsyncDisposableState]] が disposed である場合、ReferenceError 例外を投げる。IsCallable (onDisposeAsync ) が false である場合、TypeError 例外を投げる。closure を、value と onDisposeAsync をキャプチャし、呼び出されたときに次のステップを実行する、パラメータを持たない新しい Abstract Closure とする:Return ? Call (onDisposeAsync , undefined , « value »). func を CreateBuiltinFunction (closure , 0, "" , « ») とする。? AddDisposableResource (asyncDisposableStack .[[DisposableResourceStack]] , undefined , async-dispose , func ) を実行する。 value を返す。
27.4.3.2 AsyncDisposableStack.prototype.constructor
AsyncDisposableStack.prototype.constructor の初期値は %AsyncDisposableStack% である。
27.4.3.3 AsyncDisposableStack.prototype.defer ( onDisposeAsync )
このメソッドは、呼び出されたときに次のステップを実行する:
asyncDisposableStack を this 値とする。? RequireInternalSlot (asyncDisposableStack , [[AsyncDisposableState]] ) を実行する。 asyncDisposableStack .[[AsyncDisposableState]] が disposed である場合、ReferenceError 例外を投げる。IsCallable (onDisposeAsync ) が false である場合、TypeError 例外を投げる。? AddDisposableResource (asyncDisposableStack .[[DisposableResourceStack]] , undefined , async-dispose , onDisposeAsync ) を実行する。 undefined を返す。
27.4.3.4 AsyncDisposableStack.prototype.disposeAsync ( )
この async メソッドは、呼び出されたときに次のステップを実行する:
asyncDisposableStack を this 値とする。? RequireInternalSlot (asyncDisposableStack , [[AsyncDisposableState]] ) を実行する。 asyncDisposableStack .[[AsyncDisposableState]] が disposed である場合、undefined を返す。asyncDisposableStack .[[AsyncDisposableState]] を disposed に設定する。Return ? DisposeResources (asyncDisposableStack .[[DisposableResourceStack]] , NormalCompletion (undefined )).
27.4.3.5 get AsyncDisposableStack.prototype.disposed
AsyncDisposableStack.prototype.disposed は、set アクセサ関数が undefined であるアクセサプロパティである。その get アクセサ関数は、呼び出されたときに次のステップを実行する:
asyncDisposableStack を this 値とする。? RequireInternalSlot (asyncDisposableStack , [[AsyncDisposableState]] ) を実行する。 asyncDisposableStack .[[AsyncDisposableState]] が disposed である場合、true を返す。false を返す。
27.4.3.6 AsyncDisposableStack.prototype.move ( )
このメソッドは、呼び出されたときに次のステップを実行する:
asyncDisposableStack を this 値とする。? RequireInternalSlot (asyncDisposableStack , [[AsyncDisposableState]] ) を実行する。 asyncDisposableStack .[[AsyncDisposableState]] が disposed である場合、ReferenceError 例外を投げる。newAsyncDisposableStack を ? OrdinaryCreateFromConstructor (%AsyncDisposableStack% , "%AsyncDisposableStack.prototype%" , « [[AsyncDisposableState]] , [[DisposableResourceStack]] ») とする。newAsyncDisposableStack .[[AsyncDisposableState]] を pending に設定する。newAsyncDisposableStack .[[DisposableResourceStack]] を asyncDisposableStack .[[DisposableResourceStack]] に設定する。asyncDisposableStack .[[DisposableResourceStack]] を新しい空の List に設定する。asyncDisposableStack .[[AsyncDisposableState]] を disposed に設定する。newAsyncDisposableStack を返す。
27.4.3.7 AsyncDisposableStack.prototype.use ( value )
このメソッドは、呼び出されたときに次のステップを実行する:
asyncDisposableStack を this 値とする。? RequireInternalSlot (asyncDisposableStack , [[AsyncDisposableState]] ) を実行する。 asyncDisposableStack .[[AsyncDisposableState]] が disposed である場合、ReferenceError 例外を投げる。? AddDisposableResource (asyncDisposableStack .[[DisposableResourceStack]] , value , async-dispose ) を実行する。 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、すなわちfulfilled 、rejected 、および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:
IfAbruptRejectPromise (value , capability ).
は、次と同じ意味である:
Assert : value はCompletion Record である。value がabrupt completion なら、? Call (capability .[[Reject]] , undefined , « value .[[Value]] »)を実行する。 capability .[[Promise]] を返す。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:
promiseOrEmpty をRecord { [[Value]] : toResolve }とする。resolveSteps を、parameters (resolution )を持ち、promiseOrEmpty をcaptureし、呼び出されたときに以下のstepsを実行するnew Abstract Closure とする:promiseOrEmpty .[[Value]] がempty なら、undefined を返す。promise をpromiseOrEmpty .[[Value]] とする。promiseOrEmpty .[[Value]] をempty に設定する。SameValue (resolution , promise )がtrue なら、selfResolutionError をnewly created TypeError objectとする。RejectPromise (promise , selfResolutionError )を実行する。undefined を返す。resolution がObjectでないなら、FulfillPromise (promise , resolution )を実行する。undefined を返す。then をCompletion (Get (resolution , "then" ))とする。then がabrupt completion なら、RejectPromise (promise , then .[[Value]] )を実行する。undefined を返す。thenAction をthen .[[Value]] とする。IsCallable (thenAction )がfalse なら、FulfillPromise (promise , resolution )を実行する。undefined を返す。thenJobCallback をHostMakeJobCallback (thenAction )とする。job をNewPromiseResolveThenableJob (promise , resolution , thenJobCallback )とする。HostEnqueuePromiseJob (job .[[Job]] , job .[[Realm]] )を実行する。undefined を返す。resolve をCreateBuiltinFunction (resolveSteps , 1, "" , « »)とする。rejectSteps を、parameters (reason )を持ち、promiseOrEmpty をcaptureし、呼び出されたときに以下のstepsを実行するnew Abstract Closure とする:promiseOrEmpty .[[Value]] がempty なら、undefined を返す。promise をpromiseOrEmpty .[[Value]] とする。promiseOrEmpty .[[Value]] をempty に設定する。RejectPromise (promise , reason )を実行する。undefined を返す。reject をCreateBuiltinFunction (rejectSteps , 1, "" , « »)とする。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:
Assert : promise .[[PromiseState]] はpending である。reactions をpromise .[[PromiseFulfillReactions]] とする。promise .[[PromiseResult]] をvalue に設定する。promise .[[PromiseFulfillReactions]] をundefined に設定する。promise .[[PromiseRejectReactions]] をundefined に設定する。promise .[[PromiseState]] をfulfilled に設定する。TriggerPromiseReactions (reactions , value )を実行する。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 の方式でctor をconstructor として使用し、promiseをcreateしてそのresolveおよびreject functionsをextractしようとする。promiseとresolveおよびreject functionsは、new PromiseCapability Record をinitializeするために使用される。 It performs the following steps when called:
IsConstructor (ctor )がfalse なら、TypeError 例外をthrowする。NOTE : ctor は、Promise constructor のparameter conventionsをsupportするconstructor functionであるとassumedされる(27.5.3.1 を参照)。resolvingFuncs をRecord { [[Resolve]] : undefined , [[Reject]] : undefined }とする。executorClosure を、parameters (resolve , reject )を持ち、resolvingFuncs をcaptureし、呼び出されたときに以下のstepsを実行するnew Abstract Closure とする:resolvingFuncs .[[Resolve]] がundefined でないなら、TypeError 例外をthrowする。resolvingFuncs .[[Reject]] がundefined でないなら、TypeError 例外をthrowする。resolvingFuncs .[[Resolve]] をresolve に設定する。resolvingFuncs .[[Reject]] をreject に設定する。NormalCompletion (undefined )を返す。executor をCreateBuiltinFunction (executorClosure , 2, "" , « »)とする。promise を ? Construct (ctor , « executor ») とする。IsCallable (resolvingFuncs .[[Resolve]] )がfalse なら、TypeError 例外をthrowする。IsCallable (resolvingFuncs .[[Reject]] )がfalse なら、TypeError 例外をthrowする。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:
arg がObjectでないなら、false を返す。arg が[[PromiseState]] internal slotを持たないなら、false を返す。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:
Assert : promise .[[PromiseState]] はpending である。reactions をpromise .[[PromiseRejectReactions]] とする。promise .[[PromiseResult]] をreason に設定する。promise .[[PromiseFulfillReactions]] をundefined に設定する。promise .[[PromiseRejectReactions]] をundefined に設定する。promise .[[PromiseState]] をrejected に設定する。promise .[[PromiseIsHandled]] がfalse なら、HostPromiseRejectionTracker (promise , "reject" )を実行する。TriggerPromiseReactions (reactions , reason )を実行する。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する。そのような各Job はPromiseReaction Record の[[Type]] および[[Handler]] をprocessし、[[Handler]] がempty でない場合、与えられたargumentを渡してそれをcallする。[[Handler]] がempty である場合、behaviourは[[Type]] によってdeterminedされる。 It performs the following steps when called:
reactions の各element reaction について、job をNewPromiseReactionJob (reaction , arg )とする。HostEnqueuePromiseJob (job .[[Job]] , job .[[Realm]] )を実行する。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:
job を、parametersを持たず、reaction およびarg をcaptureし、呼び出されたときに以下のstepsを実行するnew Job Abstract Closure とする:promiseCapability をreaction .[[Capability]] とする。type をreaction .[[Type]] とする。handler をreaction .[[Handler]] とする。handler がempty なら、type がfulfill なら、handlerResult をNormalCompletion (arg )とする。そうでなければ、Assert : type はreject である。handlerResult をThrowCompletion (arg )とする。 そうでなければ、handlerResult をCompletion (HostCallJobCallback (handler , undefined , « arg »))とする。 promiseCapability がundefined なら、Assert : handlerResult はabrupt completion でない。empty を返す。Assert : promiseCapability はPromiseCapability Record である。handlerResult がabrupt completion なら、? Call (promiseCapability .[[Reject]] , undefined , « handlerResult .[[Value]] »)を返す。 ? Call (promiseCapability .[[Resolve]] , undefined , « handlerResult .[[Value]] »)を返す。 handlerRealm をnull とする。reaction .[[Handler]] がempty でないなら、getHandlerRealmResult をCompletion (GetFunctionRealm (reaction .[[Handler]] .[[Callback]] ))とする。getHandlerRealmResult がnormal completion なら、handlerRealm をgetHandlerRealmResult .[[Value]] に設定する。そうでなければ、handlerRealm をcurrent Realm Record に設定する。 NOTE : handlerがundefined でない限り、handlerRealm は決してnull ではない。handlerがrevoked ProxyでありECMAScript codeが実行されない場合、handlerRealm はerror objectsをcreateするために使用される。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:
job を、parametersを持たず、promiseToResolve 、thenable 、およびthen をcaptureし、呼び出されたときに以下のstepsを実行するnew Job Abstract Closure とする:resolvingFuncs をCreateResolvingFunctions (promiseToResolve )とする。thenCallResult をCompletion (HostCallJobCallback (then , thenable , « resolvingFuncs .[[Resolve]] , resolvingFuncs .[[Reject]] »))とする。thenCallResult がabrupt completion なら、? Call (resolvingFuncs .[[Reject]] , undefined , « thenCallResult .[[Value]] »)を返す。 ! thenCallResult を返す。 getThenRealmResult をCompletion (GetFunctionRealm (then .[[Callback]] ))とする。getThenRealmResult がnormal completion なら、thenRealm をgetThenRealmResult .[[Value]] とする。そうでなければ、thenRealm をcurrent Realm Record とする。 NOTE : thenRealm は決してnull ではない。then .[[Callback]] がrevoked Proxyでありcodeが実行されない場合、thenRealm はerror objectsをcreateするために使用される。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を実行する:
NewTargetがundefined なら、TypeError 例外をthrowする。 IsCallable (executor )がfalse なら、TypeError 例外をthrowする。promise を ? OrdinaryCreateFromConstructor (NewTarget, "%Promise.prototype%" , « [[PromiseState]] , [[PromiseResult]] , [[PromiseFulfillReactions]] , [[PromiseRejectReactions]] , [[PromiseIsHandled]] ») とする。promise .[[PromiseState]] をpending に設定する。promise .[[PromiseResult]] をempty に設定する。promise .[[PromiseFulfillReactions]] をnew empty List に設定する。promise .[[PromiseRejectReactions]] をnew empty List に設定する。promise .[[PromiseIsHandled]] をfalse に設定する。resolvingFuncs をCreateResolvingFunctions (promise )とする。completion をCompletion (Call (executor , undefined , « resolvingFuncs .[[Resolve]] , resolvingFuncs .[[Reject]] »))とする。completion がabrupt completion なら、? Call (resolvingFuncs .[[Reject]] , undefined , « completion .[[Value]] »)を実行する。 promise を返す。
Note
executor argumentはfunction object でなければならない。これは、このPromiseによって表される、場合によってはdeferredされたactionの開始および完了報告のためにcallされる。executorは2つのarguments、resolve とreject で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 は:
27.5.4.1 Promise.all ( iterable )
このfunctionは、渡されたpromisesのfulfillment valuesのarrayでfulfilledされる、または最初にrejectする渡されたpromiseのreasonでrejectされるnew promiseを返す。このalgorithmを実行する際、渡されたiterable のすべてのelementsをpromisesにresolveする。
ctor をthis valueとする。promiseCapability を ? NewPromiseCapability (ctor ) とする。promiseResolve をCompletion (GetPromiseResolve (ctor ))とする。IfAbruptRejectPromise (promiseResolve , promiseCapability ).iteratorRecord をCompletion (GetIterator (iterable , sync ))とする。IfAbruptRejectPromise (iteratorRecord , promiseCapability ).result をCompletion (PerformPromiseAll (iteratorRecord , ctor , promiseCapability , promiseResolve ))とする。result がabrupt completion なら、iteratorRecord .[[Done]] がfalse なら、result をCompletion (IteratorClose (iteratorRecord , result ))に設定する。IfAbruptRejectPromise (result , promiseCapability ).! 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:
promiseResolve を ? Get (promiseCtor , "resolve" ) とする。IsCallable (promiseResolve )がfalse なら、TypeError 例外をthrowする。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:
values をnew empty List とする。NOTE : remainingElementsCount は、input iterator がexhaustedされる前に渡されたcallbackをcallするmisbehaving "then" が存在する場合でも、resultCapability .[[Resolve]] が一度だけcallされることをensureするため、0ではなく1から始まる。remainingElementsCount をRecord { [[Value]] : 1 }とする。index を0とする。繰り返す:next を ? IteratorStepValue (iteratorRecord ) とする。next がdone なら、remainingElementsCount .[[Value]] をremainingElementsCount .[[Value]] - 1に設定する。remainingElementsCount .[[Value]] = 0なら、valuesArray をCreateArrayFromList (values )とする。? Call (resultCapability .[[Resolve]] , undefined , « valuesArray »)を実行する。 resultCapability .[[Promise]] を返す。undefined をvalues にappendする。nextPromise を ? Call (promiseResolve , ctor , « next ») とする。fulfilledSteps を、parameters (value )を持ち、values 、resultCapability 、およびremainingElementsCount をcaptureし、呼び出されたときに以下のstepsを実行するnew Abstract Closure とする:activeFunc をactive function object とする。activeFunc .[[AlreadyCalled]] がtrue なら、undefined を返す。activeFunc .[[AlreadyCalled]] をtrue に設定する。thisIndex をactiveFunc .[[Index]] とする。values [thisIndex ]をvalue に設定する。remainingElementsCount .[[Value]] をremainingElementsCount .[[Value]] - 1に設定する。remainingElementsCount .[[Value]] = 0なら、valuesArray をCreateArrayFromList (values )とする。? Call (resultCapability .[[Resolve]] , undefined , « valuesArray »)を返す。 undefined を返す。onFulfilled をCreateBuiltinFunction (fulfilledSteps , 1, "" , « [[AlreadyCalled]] , [[Index]] »)とする。onFulfilled .[[AlreadyCalled]] をfalse に設定する。onFulfilled .[[Index]] をindex に設定する。index をindex + 1に設定する。remainingElementsCount .[[Value]] をremainingElementsCount .[[Value]] + 1に設定する。? 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する。
ctor をthis valueとする。promiseCapability を ? NewPromiseCapability (ctor ) とする。promiseResolve をCompletion (GetPromiseResolve (ctor ))とする。IfAbruptRejectPromise (promiseResolve , promiseCapability ).iteratorRecord をCompletion (GetIterator (iterable , sync ))とする。IfAbruptRejectPromise (iteratorRecord , promiseCapability ).result をCompletion (PerformPromiseAllSettled (iteratorRecord , ctor , promiseCapability , promiseResolve ))とする。result がabrupt completion なら、iteratorRecord .[[Done]] がfalse なら、result をCompletion (IteratorClose (iteratorRecord , result ))に設定する。IfAbruptRejectPromise (result , promiseCapability ).! 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:
values をnew empty List とする。NOTE : remainingElementsCount は、input iterator がexhaustedされる前に渡されたcallbacksの1つをcallするmisbehaving "then" が存在する場合でも、resultCapability .[[Resolve]] が一度だけcallされることをensureするため、0ではなく1から始まる。remainingElementsCount をRecord { [[Value]] : 1 }とする。index を0とする。繰り返す:next を ? IteratorStepValue (iteratorRecord ) とする。next がdone なら、remainingElementsCount .[[Value]] をremainingElementsCount .[[Value]] - 1に設定する。remainingElementsCount .[[Value]] = 0なら、valuesArray をCreateArrayFromList (values )とする。? Call (resultCapability .[[Resolve]] , undefined , « valuesArray »)を実行する。 resultCapability .[[Promise]] を返す。undefined をvalues にappendする。nextPromise を ? Call (promiseResolve , ctor , « next ») とする。alreadyCalled をRecord { [[Value]] : false }とする。fulfilledSteps を、parameters (value )を持ち、values 、resultCapability 、およびremainingElementsCount をcaptureし、呼び出されたときに以下のstepsを実行するnew Abstract Closure とする:activeFunc をactive function object とする。activeFunc .[[AlreadyCalled]] .[[Value]] がtrue なら、undefined を返す。activeFunc .[[AlreadyCalled]] .[[Value]] をtrue に設定する。obj をOrdinaryObjectCreate (%Object.prototype% )とする。! CreateDataPropertyOrThrow (obj , "status" , "fulfilled" )を実行する。 ! CreateDataPropertyOrThrow (obj , "value" , value )を実行する。 thisIndex をactiveFunc .[[Index]] とする。values [thisIndex ]をobj に設定する。remainingElementsCount .[[Value]] をremainingElementsCount .[[Value]] - 1に設定する。remainingElementsCount .[[Value]] = 0なら、valuesArray をCreateArrayFromList (values )とする。? Call (resultCapability .[[Resolve]] , undefined , « valuesArray »)を返す。 undefined を返す。onFulfilled をCreateBuiltinFunction (fulfilledSteps , 1, "" , « [[AlreadyCalled]] , [[Index]] »)とする。onFulfilled .[[AlreadyCalled]] をalreadyCalled に設定する。onFulfilled .[[Index]] をindex に設定する。rejectedSteps を、parameters (error )を持ち、values 、resultCapability 、およびremainingElementsCount をcaptureし、呼び出されたときに以下のstepsを実行するnew Abstract Closure とする:activeFunc をactive function object とする。activeFunc .[[AlreadyCalled]] .[[Value]] がtrue なら、undefined を返す。activeFunc .[[AlreadyCalled]] .[[Value]] をtrue に設定する。obj をOrdinaryObjectCreate (%Object.prototype% )とする。! CreateDataPropertyOrThrow (obj , "status" , "rejected" )を実行する。 ! CreateDataPropertyOrThrow (obj , "reason" , error )を実行する。 thisIndex をactiveFunc .[[Index]] とする。values [thisIndex ]をobj に設定する。remainingElementsCount .[[Value]] をremainingElementsCount .[[Value]] - 1に設定する。remainingElementsCount .[[Value]] = 0なら、valuesArray をCreateArrayFromList (values )とする。? Call (resultCapability .[[Resolve]] , undefined , « valuesArray »)を返す。 undefined を返す。onRejected をCreateBuiltinFunction (rejectedSteps , 1, "" , « [[AlreadyCalled]] , [[Index]] »)とする。onRejected .[[AlreadyCalled]] をalreadyCalled に設定する。onRejected .[[Index]] をindex に設定する。index をindex + 1に設定する。remainingElementsCount .[[Value]] をremainingElementsCount .[[Value]] + 1に設定する。? 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する。
ctor をthis valueとする。promiseCapability を ? NewPromiseCapability (ctor ) とする。promiseResolve をCompletion (GetPromiseResolve (ctor ))とする。IfAbruptRejectPromise (promiseResolve , promiseCapability ).iteratorRecord をCompletion (GetIterator (iterable , sync ))とする。IfAbruptRejectPromise (iteratorRecord , promiseCapability ).result をCompletion (PerformPromiseAny (iteratorRecord , ctor , promiseCapability , promiseResolve ))とする。result がabrupt completion なら、iteratorRecord .[[Done]] がfalse なら、result をCompletion (IteratorClose (iteratorRecord , result ))に設定する。IfAbruptRejectPromise (result , promiseCapability ).! 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:
errors をnew empty List とする。NOTE : remainingElementsCount は、input iterator がexhaustedされる前に渡されたcallbackをcallするmisbehaving "then" が存在する場合でも、resultCapability .[[Reject]] が一度だけcallされることをensureするため、0ではなく1から始まる。remainingElementsCount をRecord { [[Value]] : 1 }とする。index を0とする。繰り返す:next を ? IteratorStepValue (iteratorRecord ) とする。next がdone なら、remainingElementsCount .[[Value]] をremainingElementsCount .[[Value]] - 1に設定する。remainingElementsCount .[[Value]] = 0なら、aggregateError をnewly created AggregateError objectとする。! DefinePropertyOrThrow (aggregateError , "errors" , PropertyDescriptor { [[Configurable]] : true , [[Enumerable]] : false , [[Writable]] : true , [[Value]] : CreateArrayFromList (errors ) })を実行する。 ? Call (resultCapability .[[Reject]] , undefined , « aggregateError »)を実行する。 resultCapability .[[Promise]] を返す。undefined をerrors にappendする。nextPromise を ? Call (promiseResolve , ctor , « next ») とする。rejectedSteps を、parameters (error )を持ち、errors 、resultCapability 、およびremainingElementsCount をcaptureし、呼び出されたときに以下のstepsを実行するnew Abstract Closure とする:activeFunc をactive function object とする。activeFunc .[[AlreadyCalled]] がtrue なら、undefined を返す。activeFunc .[[AlreadyCalled]] をtrue に設定する。thisIndex をactiveFunc .[[Index]] とする。errors [thisIndex ]をerror に設定する。remainingElementsCount .[[Value]] をremainingElementsCount .[[Value]] - 1に設定する。remainingElementsCount .[[Value]] = 0なら、aggregateError をnewly created AggregateError objectとする。! DefinePropertyOrThrow (aggregateError , "errors" , PropertyDescriptor { [[Configurable]] : true , [[Enumerable]] : false , [[Writable]] : true , [[Value]] : CreateArrayFromList (errors ) })を実行する。 ? Call (resultCapability .[[Reject]] , undefined , « aggregateError »)を返す。 undefined を返す。onRejected をCreateBuiltinFunction (rejectedSteps , 1, "" , « [[AlreadyCalled]] , [[Index]] »)とする。onRejected .[[AlreadyCalled]] をfalse に設定する。onRejected .[[Index]] をindex に設定する。index をindex + 1に設定する。remainingElementsCount .[[Value]] をremainingElementsCount .[[Value]] + 1に設定する。? 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する。
ctor をthis valueとする。promiseCapability を ? NewPromiseCapability (ctor ) とする。promiseResolve をCompletion (GetPromiseResolve (ctor ))とする。IfAbruptRejectPromise (promiseResolve , promiseCapability ).iteratorRecord をCompletion (GetIterator (iterable , sync ))とする。IfAbruptRejectPromise (iteratorRecord , promiseCapability ).result をCompletion (PerformPromiseRace (iteratorRecord , ctor , promiseCapability , promiseResolve ))とする。result がabrupt completion なら、iteratorRecord .[[Done]] がfalse なら、result をCompletion (IteratorClose (iteratorRecord , result ))に設定する。IfAbruptRejectPromise (result , promiseCapability ).! 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:
繰り返す:next を ? IteratorStepValue (iteratorRecord ) とする。next がdone なら、resultCapability .[[Promise]] を返す。nextPromise を ? Call (promiseResolve , ctor , « next ») とする。? Invoke (nextPromise , "then" , « resultCapability .[[Resolve]] , resultCapability .[[Reject]] »)を実行する。
27.5.4.6 Promise.reject ( reason )
このfunctionは、渡されたargumentでrejectedされたnew promiseを返す。
ctor をthis valueとする。promiseCapability を ? NewPromiseCapability (ctor ) とする。? Call (promiseCapability .[[Reject]] , undefined , « reason »)を実行する。 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自体を返す。
ctor をthis valueとする。ctor がObjectでないなら、TypeError 例外をthrowする。? 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:
IsPromise (resolution )がtrue なら、resolutionCtor を ? Get (resolution , "constructor" ) とする。SameValue (resolutionCtor , ctor )がtrue なら、resolution を返す。promiseCapability を ? NewPromiseCapability (ctor ) とする。? Call (promiseCapability .[[Resolve]] , undefined , « resolution »)を実行する。 promiseCapability .[[Promise]] を返す。
27.5.4.8 Promise.try ( callback , ...args )
このfunctionは、呼び出されたときに以下のstepsを実行する:
ctor をthis valueとする。ctor がObjectでないなら、TypeError 例外をthrowする。promiseCapability を ? NewPromiseCapability (ctor ) とする。status をCompletion (Call (callback , undefined , args ))とする。status がabrupt completion なら、? Call (promiseCapability .[[Reject]] , undefined , « status .[[Value]] »)を実行する。 そうでなければ、? Call (promiseCapability .[[Resolve]] , undefined , « status .[[Value]] »)を実行する。 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を返す。
ctor をthis valueとする。promiseCapability を ? NewPromiseCapability (ctor ) とする。obj をOrdinaryObjectCreate (%Object.prototype% )とする。! CreateDataPropertyOrThrow (obj , "promise" , promiseCapability .[[Promise]] )を実行する。 ! CreateDataPropertyOrThrow (obj , "resolve" , promiseCapability .[[Resolve]] )を実行する。 ! CreateDataPropertyOrThrow (obj , "reject" , promiseCapability .[[Reject]] )を実行する。 obj を返す。
27.5.4.10 get Promise [ %Symbol.species% ]
Promise[%Symbol.species%]は、set accessor functionがundefined であるaccessor property である。そのget accessor functionは、呼び出されたときに以下のstepsを実行する:
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を実行する:
promise をthis valueとする。? 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を実行する:
promise をthis valueとする。promise がObjectでないなら、TypeError 例外をthrowする。ctor を ? SpeciesConstructor (promise , %Promise% ) とする。Assert : IsConstructor (ctor )はtrue である。IsCallable (onFinally )がfalse なら、thenFinally をonFinally とする。catchFinally をonFinally とする。そうでなければ、thenFinallyClosure を、parameters (value )を持ち、onFinally およびctor をcaptureし、呼び出されたときに以下のstepsを実行するnew Abstract Closure とする:result を ? Call (onFinally , undefined ) とする。p を ? PromiseResolve (ctor , result ) とする。returnValue を、parametersを持たず、value をcaptureし、呼び出されたときに以下のstepsを実行するnew Abstract Closure とする:NormalCompletion (value )を返す。valueThunk をCreateBuiltinFunction (returnValue , 0, "" , « »)とする。? Invoke (p , "then" , « valueThunk »)を返す。 thenFinally をCreateBuiltinFunction (thenFinallyClosure , 1, "" , « »)とする。catchFinallyClosure を、parameters (reason )を持ち、onFinally およびctor をcaptureし、呼び出されたときに以下のstepsを実行するnew Abstract Closure とする:result を ? Call (onFinally , undefined ) とする。p を ? PromiseResolve (ctor , result ) とする。throwReason を、parametersを持たず、reason をcaptureし、呼び出されたときに以下のstepsを実行するnew Abstract Closure とする:reason をThrowする。thrower をCreateBuiltinFunction (throwReason , 0, "" , « »)とする。? Invoke (p , "then" , « thrower »)を返す。 catchFinally をCreateBuiltinFunction (catchFinallyClosure , 1, "" , « »)とする。 ? Invoke (promise , "then" , « thenFinally , catchFinally »)を返す。
27.5.5.4 Promise.prototype.then ( onFulfilled , onRejected )
このmethodは、呼び出されたときに以下のstepsを実行する:
promise をthis valueとする。IsPromise (promise )がfalse なら、TypeError 例外をthrowする。ctor を ? SpeciesConstructor (promise , %Promise% ) とする。resultCapability を ? NewPromiseCapability (ctor ) とする。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:
Assert : IsPromise (promise )はtrue である。resultCapability が存在しないなら、resultCapability をundefined に設定する。IsCallable (onFulfilled )がfalse なら、onFulfilledJobCallback をempty とする。そうでなければ、onFulfilledJobCallback をHostMakeJobCallback (onFulfilled )とする。 IsCallable (onRejected )がfalse なら、onRejectedJobCallback をempty とする。そうでなければ、onRejectedJobCallback をHostMakeJobCallback (onRejected )とする。 fulfillReaction をPromiseReaction Record { [[Capability]] : resultCapability , [[Type]] : fulfill , [[Handler]] : onFulfilledJobCallback }とする。rejectReaction をPromiseReaction Record { [[Capability]] : resultCapability , [[Type]] : reject , [[Handler]] : onRejectedJobCallback }とする。promise .[[PromiseState]] がpending なら、fulfillReaction をpromise .[[PromiseFulfillReactions]] にappendする。rejectReaction をpromise .[[PromiseRejectReactions]] にappendする。そうでなく、promise .[[PromiseState]] がfulfilled なら、value をpromise .[[PromiseResult]] とする。fulfillJob をNewPromiseReactionJob (fulfillReaction , value )とする。HostEnqueuePromiseJob (fulfillJob .[[Job]] , fulfillJob .[[Realm]] )を実行する。 そうでなければ、Assert : promise .[[PromiseState]] はrejected である。reason をpromise .[[PromiseResult]] とする。promise .[[PromiseIsHandled]] がfalse なら、HostPromiseRejectionTracker (promise , "handle" )を実行する。rejectJob をNewPromiseReactionJob (rejectReaction , reason )とする。HostEnqueuePromiseJob (rejectJob .[[Job]] , rejectJob .[[Realm]] )を実行する。 promise .[[PromiseIsHandled]] をtrue に設定する。resultCapability がundefined なら、undefined を返す。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 Records のList
promiseがpending stateからfulfilled stateにtransitionするとき/する場合にprocessedされるRecords 。
[[PromiseRejectReactions]]
PromiseReaction Records のList
promiseがpending stateからrejected stateにtransitionするとき/する場合にprocessedされるRecords 。
[[PromiseIsHandled]]
Boolean
promiseがこれまでにfulfillmentまたはrejection handlerを持ったことがあるかどうかを示す。unhandled rejection trackingで使用される。
27.6 GeneratorFunctionオブジェクト
GeneratorFunctionsは、通常、GeneratorDeclaration 、GeneratorExpression 、およびGeneratorMethod を評価することによって作成されるfunctionsである。これらは%GeneratorFunction% intrinsicをcallすることによって作成されることもある。
Figure 6 (Informative): Generatorオブジェクトの関係
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を実行する:
activeFunc をactive function object とする。bodyArg が存在しないなら、bodyArg をempty Stringに設定する。? CreateDynamicFunction (activeFunc , NewTarget, generator , paramArgs , bodyArg )を返す。
Note
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は、通常、AsyncGeneratorDeclaration 、AsyncGeneratorExpression 、および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を実行する:
activeFunc をactive function object とする。bodyArg が存在しないなら、bodyArg をempty Stringに設定する。? CreateDynamicFunction (activeFunc , NewTarget, async-generator , paramArgs , bodyArg )を返す。
Note
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 interface とiterable 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 )
? GeneratorResume (this value, value , empty )を返す。
27.8.1.3 %GeneratorPrototype%.return ( value )
このmethodは、呼び出されたときに以下のstepsを実行する:
gen をthis valueとする。completion をReturnCompletion (value )とする。? GeneratorResumeAbrupt (gen , completion , empty )を返す。
27.8.1.4 %GeneratorPrototype%.throw ( exception )
このmethodは、呼び出されたときに以下のstepsを実行する:
gen をthis valueとする。completion をThrowCompletion (exception )とする。? 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:
Assert : gen .[[GeneratorState]] はsuspended-start である。genContext をrunning execution context とする。genContext のGenerator componentをgen に設定する。closure を、parametersを持たず、genBody をcaptureし、呼び出されたときに以下のstepsを実行するnew Abstract Closure とする:acGenContext をrunning execution context とする。acGen をacGenContext のGenerator componentとする。genBody がParse Node なら、result をCompletion (Evaluation of genBody )とする。そうでなければ、Assert : genBody はparametersを持たないAbstract Closure である。result をCompletion (genBody ())とする。 Assert : ここにreturnした場合、generatorはexceptionをthrowしたか、implicitまたはexplicit returnのいずれかを実行した。acGenContext をexecution context stack からremoveし、execution context stack のtopにあるexecution context をrunning execution context としてrestoreする。acGen .[[GeneratorState]] をcompleted に設定する。NOTE : generatorがcompleted stateに入ると、決してそこからleaveせず、そのassociated execution context は決してresumedされない。この時点で、acGen にassociatedする任意のexecution stateはdiscardできる。result がnormal completion なら、resultValue をundefined とする。そうでなく、result がreturn completion なら、resultValue をresult .[[Value]] とする。 そうでなければ、Assert : result はthrow completion である。? result を返す。 NormalCompletion (CreateIteratorResultObject (resultValue , true ))を返す。genContext のcode evaluation stateを、そのexecution context についてevaluationがresumedされたときに、closure がargumentsなしでcallされるように設定する。gen .[[GeneratorContext]] をgenContext に設定する。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:
? RequireInternalSlot (gen , [[GeneratorState]] )を実行する。 ? RequireInternalSlot (gen , [[GeneratorBrand]] )を実行する。 gen .[[GeneratorBrand]] がgenBrand でないなら、TypeError 例外をthrowする。Assert : gen は[[GeneratorContext]] internal slotを持つ。state をgen .[[GeneratorState]] とする。state がexecuting なら、TypeError 例外をthrowする。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:
state を ? GeneratorValidate (gen , genBrand ) とする。state がcompleted なら、CreateIteratorResultObject (undefined , true )を返す。Assert : state はsuspended-start またはsuspended-yield のいずれかである。genContext をgen .[[GeneratorContext]] とする。gen .[[GeneratorState]] をexecuting に設定する。? 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:
state を ? GeneratorValidate (gen , genBrand ) とする。state がsuspended-start なら、gen .[[GeneratorState]] をcompleted に設定する。NOTE : generatorがcompleted stateに入ると、決してそこからleaveせず、そのassociated execution context は決してresumedされない。この時点で、gen にassociatedする任意のexecution stateはdiscardできる。state をcompleted に設定する。state がcompleted なら、abruptCompletion がreturn completion なら、CreateIteratorResultObject (abruptCompletion .[[Value]] , true )を返す。? abruptCompletion を返す。 Assert : state はsuspended-yield である。genContext をgen .[[GeneratorContext]] とする。gen .[[GeneratorState]] をexecuting に設定する。? 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:
genContext をrunning execution context とする。genContext がGenerator componentを持たないなら、non-generator を返す。gen をgenContext のGenerator componentとする。gen が[[AsyncGeneratorState]] internal slotを持つなら、async を返す。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:
genContext を、実行中の実行コンテキストとする。Assert : genContext はジェネレータの実行コンテキストである。gen を、genContext のGeneratorコンポーネントの値とする。Assert : GetGeneratorKind ()はsync である。gen .[[GeneratorState]] をsuspended-yield に設定する。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:
genKind をGetGeneratorKind ()とする。genKind がasync なら、? AsyncGeneratorYield (? Await (arg ))を返す。? 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:
NOTE : closure は、IteratorResult object をyieldするためにYield operationのusesを含むことができる。extraSlots が存在しないなら、extraSlots をnew empty List に設定する。internalSlotsList をextraSlots と« [[GeneratorState]] , [[GeneratorContext]] , [[GeneratorBrand]] »のlist-concatenation とする。gen をOrdinaryObjectCreate (genProto , internalSlotsList )とする。gen .[[GeneratorBrand]] をgenBrand に設定する。gen .[[GeneratorState]] をsuspended-start に設定する。callerContext をrunning execution context とする。calleeContext をnew execution context とする。calleeContext のFunctionをnull に設定する。calleeContext のRealm をcurrent Realm Record に設定する。calleeContext のScriptOrModuleをcallerContext のScriptOrModuleに設定する。callerContext がまだsuspendedでないなら、callerContext をsuspendする。calleeContext をexecution context stack にPushする。calleeContext はいまrunning execution context である。GeneratorStart (gen , closure )を実行する。calleeContext をexecution context stack からremoveし、callerContext をrunning execution context としてrestoreする。gen を返す。
27.9 AsyncGeneratorオブジェクト
AsyncGeneratorは、async generator functionをcallすることによって作成され、async iterator interface とasync 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 )
gen をthis valueとする。promiseCapability を ! NewPromiseCapability (%Promise% ) とする。result をCompletion (AsyncGeneratorValidate (gen , empty ))とする。IfAbruptRejectPromise (result , promiseCapability ).state をgen .[[AsyncGeneratorState]] とする。state がcompleted なら、iteratorResult をCreateIteratorResultObject (undefined , true )とする。! Call (promiseCapability .[[Resolve]] , undefined , « iteratorResult »)を実行する。 promiseCapability .[[Promise]] を返す。completion をNormalCompletion (value )とする。AsyncGeneratorEnqueue (gen , completion , promiseCapability )を実行する。state がsuspended-start またはsuspended-yield のいずれかなら、AsyncGeneratorResume (gen , completion )を実行する。そうでなければ、Assert : state はexecuting またはdraining-queue のいずれかである。 promiseCapability .[[Promise]] を返す。
27.9.1.3 %AsyncGeneratorPrototype%.return ( value )
gen をthis valueとする。promiseCapability を ! NewPromiseCapability (%Promise% ) とする。result をCompletion (AsyncGeneratorValidate (gen , empty ))とする。IfAbruptRejectPromise (result , promiseCapability ).completion をReturnCompletion (value )とする。AsyncGeneratorEnqueue (gen , completion , promiseCapability )を実行する。state をgen .[[AsyncGeneratorState]] とする。state がsuspended-start またはcompleted のいずれかなら、gen .[[AsyncGeneratorState]] をdraining-queue に設定する。AsyncGeneratorAwaitReturn (gen )を実行する。そうでなく、state がsuspended-yield なら、AsyncGeneratorResume (gen , completion )を実行する。 そうでなければ、Assert : state はexecuting またはdraining-queue のいずれかである。 promiseCapability .[[Promise]] を返す。
27.9.1.4 %AsyncGeneratorPrototype%.throw ( exception )
gen をthis valueとする。promiseCapability を ! NewPromiseCapability (%Promise% ) とする。result をCompletion (AsyncGeneratorValidate (gen , empty ))とする。IfAbruptRejectPromise (result , promiseCapability ).state をgen .[[AsyncGeneratorState]] とする。state がsuspended-start なら、gen .[[AsyncGeneratorState]] をcompleted に設定する。state をcompleted に設定する。state がcompleted なら、! Call (promiseCapability .[[Reject]] , undefined , « exception »)を実行する。 promiseCapability .[[Promise]] を返す。completion をThrowCompletion (exception )とする。AsyncGeneratorEnqueue (gen , completion , promiseCapability )を実行する。state がsuspended-yield なら、AsyncGeneratorResume (gen , completion )を実行する。そうでなければ、Assert : state はexecuting またはdraining-queue のいずれかである。 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 Records のList
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
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:
Assert : gen .[[AsyncGeneratorState]] はsuspended-start である。genContext をrunning execution context とする。genContext のGenerator componentをgen に設定する。closure を、parametersを持たず、genBody をcaptureし、呼び出されたときに以下のstepsを実行するnew Abstract Closure とする:acGenContext をrunning execution context とする。acGen をacGenContext のGenerator componentとする。genBody がParse Node なら、result をCompletion (Evaluation of genBody )とする。そうでなければ、Assert : genBody はparametersを持たないAbstract Closure である。result をCompletion (genBody ())とする。 Assert : ここにreturnした場合、async generatorはexceptionをthrowしたか、implicitまたはexplicit returnのいずれかを実行した。acGenContext をexecution context stack からremoveし、execution context stack のtopにあるexecution context をrunning execution context としてrestoreする。acGen .[[AsyncGeneratorState]] をdraining-queue に設定する。result がnormal completion なら、result をNormalCompletion (undefined )に設定する。result がreturn completion なら、result をNormalCompletion (result .[[Value]] )に設定する。AsyncGeneratorCompleteStep (acGen , result , true )を実行する。AsyncGeneratorDrainQueue (acGen )を実行する。NormalCompletion (undefined )を返す。genContext のcode evaluation stateを、そのexecution context についてevaluationがresumedされたときに、closure がargumentsなしでcallされるように設定する。gen .[[AsyncGeneratorContext]] をgenContext に設定する。gen .[[AsyncGeneratorQueue]] をnew empty List に設定する。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:
? RequireInternalSlot (gen , [[AsyncGeneratorContext]] )を実行する。 ? RequireInternalSlot (gen , [[AsyncGeneratorState]] )を実行する。 ? RequireInternalSlot (gen , [[AsyncGeneratorQueue]] )を実行する。 gen .[[GeneratorBrand]] がgenBrand でないなら、TypeError 例外をthrowする。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:
request をAsyncGeneratorRequest { [[Completion]] : completion , [[Capability]] : promiseCapability }とする。request をgen .[[AsyncGeneratorQueue]] にappendする。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:
Assert : gen .[[AsyncGeneratorQueue]] はemptyでない。next をgen .[[AsyncGeneratorQueue]] のfirst elementとする。gen .[[AsyncGeneratorQueue]] からfirst elementをremoveする。promiseCapability をnext .[[Capability]] とする。value をcompletion .[[Value]] とする。completion がthrow completion なら、! Call (promiseCapability .[[Reject]] , undefined , « value »)を実行する。 そうでなければ、Assert : completion はnormal completion である。realm が存在するなら、oldRealm をrunning execution context のRealm とする。running execution context のRealm をrealm に設定する。iteratorResult をCreateIteratorResultObject (value , done )とする。running execution context のRealm をoldRealm に設定する。そうでなければ、iteratorResult をCreateIteratorResultObject (value , done )とする。 ! Call (promiseCapability .[[Resolve]] , undefined , « iteratorResult »)を実行する。 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:
Assert : gen .[[AsyncGeneratorState]] はsuspended-start またはsuspended-yield のいずれかである。genContext をgen .[[AsyncGeneratorContext]] とする。gen .[[AsyncGeneratorState]] をexecuting に設定する。! RunSuspendedContext (genContext , completion )を実行する。 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:
resumptionValue がreturn completion でないなら、? resumptionValue を返す。awaited をCompletion (Await (resumptionValue .[[Value]] ))とする。awaited がthrow completion なら、? awaited を返す。Assert : awaited はnormal completion である。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:
genContext を、実行中の実行コンテキストとする。Assert : genContext はジェネレータの実行コンテキストである。gen を、genContext のGeneratorコンポーネントの値とする。Assert : GetGeneratorKind ()はasync である。completion を、NormalCompletion (arg )とする。Assert : 実行コンテキストスタックには少なくとも2つの要素がある。previousContext を、実行コンテキストスタックの先頭から2番目の要素とする。previousRealm を、previousContext のRealm とする。AsyncGeneratorCompleteStep (gen , completion , false , previousRealm )を実行する。queue を、gen .[[AsyncGeneratorQueue]] とする。queue が空でない場合、NOTE : 実行はジェネレータを中断せずに継続する。toYield を、queue の最初の要素とする。resumptionValue を、Completion (toYield .[[Completion]] )とする。Return ? AsyncGeneratorUnwrapYieldResumption (resumptionValue )。 gen .[[AsyncGeneratorState]] をsuspended-yield に設定する。resumptionValue を、Completion (RunCallerContext (undefined ))とする。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:
Assert : gen .[[AsyncGeneratorState]] はdraining-queue である。queue をgen .[[AsyncGeneratorQueue]] とする。Assert : queue はemptyでない。next をqueue のfirst elementとする。completion をCompletion (next .[[Completion]] )とする。Assert : completion はreturn completion である。promiseCompletion をCompletion (PromiseResolve (%Promise% , completion .[[Value]] ))とする。promiseCompletion がabrupt completion なら、AsyncGeneratorCompleteStep (gen , promiseCompletion , true )を実行する。AsyncGeneratorDrainQueue (gen )を実行する。unused を返す。Assert : promiseCompletion はnormal completion である。promise をpromiseCompletion .[[Value]] とする。fulfilledClosure を、parameters (value )を持ち、gen をcaptureし、呼び出されたときに以下のstepsを実行するnew Abstract Closure とする:Assert : gen .[[AsyncGeneratorState]] はdraining-queue である。result をNormalCompletion (value )とする。AsyncGeneratorCompleteStep (gen , result , true )を実行する。AsyncGeneratorDrainQueue (gen )を実行する。NormalCompletion (undefined )を返す。onFulfilled をCreateBuiltinFunction (fulfilledClosure , 1, "" , « »)とする。rejectedClosure を、parameters (reason )を持ち、gen をcaptureし、呼び出されたときに以下のstepsを実行するnew Abstract Closure とする:Assert : gen .[[AsyncGeneratorState]] はdraining-queue である。result をThrowCompletion (reason )とする。AsyncGeneratorCompleteStep (gen , result , true )を実行する。AsyncGeneratorDrainQueue (gen )を実行する。NormalCompletion (undefined )を返す。onRejected をCreateBuiltinFunction (rejectedClosure , 1, "" , « »)とする。PerformPromiseThen (promise , onFulfilled , onRejected )を実行する。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:
Assert : gen .[[AsyncGeneratorState]] はdraining-queue である。queue をgen .[[AsyncGeneratorQueue]] とする。queue がemptyでない間、繰り返す:next をqueue のfirst elementとする。completion をCompletion (next .[[Completion]] )とする。completion がreturn completion なら、AsyncGeneratorAwaitReturn (gen )を実行する。unused を返す。completion がnormal completion なら、completion をNormalCompletion (undefined )に設定する。AsyncGeneratorCompleteStep (gen , completion , true )を実行する。gen .[[AsyncGeneratorState]] をcompleted に設定する。unused を返す。
27.10 AsyncFunctionオブジェクト
AsyncFunctionsは、通常、AsyncFunctionDeclaration 、AsyncFunctionExpression 、AsyncMethod 、および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を実行する:
activeFunc をactive function object とする。bodyArg が存在しないなら、bodyArg をempty Stringに設定する。? CreateDynamicFunction (activeFunc , NewTarget, async , paramArgs , bodyArg )を返す。
Note
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:
runningContext をrunning execution context とする。asyncContext をrunningContext のcopyとする。NOTE : execution stateのcopyingは、AsyncBlockStart がそのexecutionをresumeするためにrequiredである。現在executing中のcontextをresumeすることはill-definedである。AsyncBlockStart (promiseCapability , asyncFuncBody , asyncContext )を実行する。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:
closure を、parametersを持たず、promiseCapability およびasyncBody をcaptureし、呼び出されたときに以下のstepsを実行するnew Abstract Closure とする:acAsyncContext をrunning execution context とする。asyncBody がParse Node なら、result をCompletion (Evaluation of asyncBody )とする。そうでなければ、Assert : asyncBody はparametersを持たないAbstract Closure である。result をCompletion (asyncBody ())とする。 Assert : ここにreturnした場合、async functionはexceptionをthrowしたか、implicitまたはexplicit returnを実行した。すべてのawaitingは完了している。acAsyncContext をexecution context stack からremoveし、execution context stack のtopにあるexecution context をrunning execution context としてrestoreする。result がnormal completion なら、! Call (promiseCapability .[[Resolve]] , undefined , « undefined »)を実行する。 そうでなく、result がreturn completion なら、! Call (promiseCapability .[[Resolve]] , undefined , « result .[[Value]] »)を実行する。 そうでなければ、Assert : result はthrow completion である。! Call (promiseCapability .[[Reject]] , undefined , « result .[[Value]] »)を実行する。 NormalCompletion (unused )を返す。asyncContext のcode evaluation stateを、そのexecution context についてevaluationがresumedされたときに、closure がargumentsなしでcallされるように設定する。result を ! RunSuspendedContext (asyncContext , NormalCompletion (empty )) とする。Assert : result はunused である。NOTE : result valuesのpossible sourcesは、Await 、またはasync functionが何もawaitしない場合は上のstep 1.i である。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:
asyncContext を、実行中の実行コンテキストとする。promise を、? PromiseResolve (%Promise% , arg )とする。fulfilledClosure を、asyncContext をキャプチャし、呼び出されたときに次の手順を実行する、パラメータ(v )を持つ新しいAbstract Closure とする。Completion (RunSuspendedContext (asyncContext , NormalCompletion (v )))を実行する。NOTE : RunSuspendedContext によって返されるCompletion Record は意図的に無視される。NormalCompletion (undefined )を返す。onFulfilled を、CreateBuiltinFunction (fulfilledClosure , 1, "" , « »)とする。rejectedClosure を、asyncContext をキャプチャし、呼び出されたときに次の手順を実行する、パラメータ(reason )を持つ新しいAbstract Closure とする。Completion (RunSuspendedContext (asyncContext , ThrowCompletion (reason )))を実行する。NOTE : RunSuspendedContext によって返されるCompletion Record は意図的に無視される。NormalCompletion (undefined )を返す。onRejected を、CreateBuiltinFunction (rejectedClosure , 1, "" , « »)とする。PerformPromiseThen (promise , onFulfilled , onRejected )を実行する。Return ? RunCallerContext (empty )。
28 Reflection
28.1 Reflectオブジェクト
Reflect objectは:
28.1.1 Reflect.apply ( target , thisArg , args )
このfunctionは、呼び出されたときに以下のstepsを実行する:
IsCallable (target )がfalse なら、TypeError 例外をthrowする。argList を ? CreateListFromArrayLike (args ) とする。PrepareForTailCall ()を実行する。? Call (target , thisArg , argList )を返す。
28.1.2 Reflect.construct ( target , args [ , newTarget ] )
このfunctionは、呼び出されたときに以下のstepsを実行する:
IsConstructor (target )がfalse なら、TypeError 例外をthrowする。newTarget が存在しないなら、newTarget をtarget に設定する。そうでなく、IsConstructor (newTarget )がfalse なら、TypeError 例外をthrowする。 argList を ? CreateListFromArrayLike (args ) とする。? Construct (target , argList , newTarget )を返す。
28.1.3 Reflect.defineProperty ( target , key , attrs )
このfunctionは、呼び出されたときに以下のstepsを実行する:
target がObjectでないなら、TypeError 例外をthrowする。propertyKey を ? ToPropertyKey (key ) とする。propertyDesc を ? ToPropertyDescriptor (attrs ) とする。? target .[[DefineOwnProperty]] (propertyKey , propertyDesc ) を返す。
28.1.4 Reflect.deleteProperty ( target , key )
このfunctionは、呼び出されたときに以下のstepsを実行する:
target がObjectでないなら、TypeError 例外をthrowする。propertyKey を ? ToPropertyKey (key ) とする。? target .[[Delete]] (propertyKey ) を返す。
28.1.5 Reflect.get ( target , key [ , receiver ] )
このfunctionは、呼び出されたときに以下のstepsを実行する:
target がObjectでないなら、TypeError 例外をthrowする。propertyKey を ? ToPropertyKey (key ) とする。receiver が存在しないなら、receiver をtarget に設定する。? target .[[Get]] (propertyKey , receiver ) を返す。
28.1.6 Reflect.getOwnPropertyDescriptor ( target , key )
このfunctionは、呼び出されたときに以下のstepsを実行する:
target がObjectでないなら、TypeError 例外をthrowする。propertyKey を ? ToPropertyKey (key ) とする。propertyDesc を ? target .[[GetOwnProperty]] (propertyKey ) とする。FromPropertyDescriptor (propertyDesc )を返す。
28.1.7 Reflect.getPrototypeOf ( target )
このfunctionは、呼び出されたときに以下のstepsを実行する:
target がObjectでないなら、TypeError 例外をthrowする。? target .[[GetPrototypeOf]] () を返す。
28.1.8 Reflect.has ( target , key )
このfunctionは、呼び出されたときに以下のstepsを実行する:
target がObjectでないなら、TypeError 例外をthrowする。propertyKey を ? ToPropertyKey (key ) とする。? target .[[HasProperty]] (propertyKey ) を返す。
28.1.9 Reflect.isExtensible ( target )
このfunctionは、呼び出されたときに以下のstepsを実行する:
target がObjectでないなら、TypeError 例外をthrowする。? target .[[IsExtensible]] () を返す。
28.1.10 Reflect.ownKeys ( target )
このfunctionは、呼び出されたときに以下のstepsを実行する:
target がObjectでないなら、TypeError 例外をthrowする。keys を ? target .[[OwnPropertyKeys]] () とする。CreateArrayFromList (keys )を返す。
28.1.11 Reflect.preventExtensions ( target )
このfunctionは、呼び出されたときに以下のstepsを実行する:
target がObjectでないなら、TypeError 例外をthrowする。? target .[[PreventExtensions]] () を返す。
28.1.12 Reflect.set ( target , key , value [ , receiver ] )
このfunctionは、呼び出されたときに以下のstepsを実行する:
target がObjectでないなら、TypeError 例外をthrowする。propertyKey を ? ToPropertyKey (key ) とする。receiver が存在しないなら、receiver をtarget に設定する。? target .[[Set]] (propertyKey , value , receiver ) を返す。
28.1.13 Reflect.setPrototypeOf ( target , proto )
このfunctionは、呼び出されたときに以下のstepsを実行する:
target がObjectでないなら、TypeError 例外をthrowする。proto がObjectでなく、かつproto がnull でないなら、TypeError 例外をthrowする。? 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を実行する:
NewTargetがundefined なら、TypeError 例外をthrowする。 ? 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を実行する:
? ProxyCreate (target , handler )をproxy とする。 パラメータを持たず、何も捕捉せず、呼び出されたときに次のステップを実行する新しいAbstract Closure をrevokerClosure とする。アクティブな関数オブジェクトをactiveFunc とする。 activeFunc .[[RevocableProxy]] をrevocableProxy とする。revocableProxy がnull である場合、NormalCompletion (undefined )を返す。activeFunc .[[RevocableProxy]] をnull に設定する。Assert : revocableProxy はProxy exotic object である。revocableProxy .[[ProxyTarget]] をnull に設定する。revocableProxy .[[ProxyHandler]] をnull に設定する。NormalCompletion (undefined )を返す。 CreateBuiltinFunction (revokerClosure , 0, "" , « [[RevocableProxy]] »)をrevoker とする。revoker .[[RevocableProxy]] をproxy に設定する。OrdinaryObjectCreate (%Object.prototype% )をresult とする。! CreateDataPropertyOrThrow (result , "proxy" , proxy )を実行する。 ! CreateDataPropertyOrThrow (result , "revoke" , revoker )を実行する。 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 は、ReadSharedMemory 、WriteSharedMemory 、または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
Table 99: ReadModifyWriteSharedMemory Event Fields
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 e のmemory 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によって提供される。さらに、hosts はis-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
29.3 Chosen Value Records
Chosen Value Record は、以下のfieldsを持つRecord である。
Table 101: Chosen Value Record Fields
29.4 Candidate Executions
agent cluster のevaluationのcandidate execution は、以下のfieldsを持つRecord である。
Table 102: Candidate Execution Record Fields
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:
events をempty Setとする。execution .[[EventsRecords]] の各Agent Events Record eventsRecord について、eventsRecord .[[EventList]] の各Memory event event について、event をevents にaddする。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:
events をempty Setとする。EventSet (execution )の各Memory event event について、event がShared Data Block event なら、event をevents にaddする。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:
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:
byteLocation をbyteIndex とする。bytesRead をnew empty List とする。writes の各element writeEvent について、Assert : writeEvent はそのmemory range 内にbyteLocation を持つ。payloadIndex をbyteLocation - writeEvent .[[ByteIndex]] とする。writeEvent がWriteSharedMemory eventなら、byte をwriteEvent .[[Payload]] [payloadIndex ]とする。そうでなければ、Assert : writeEvent はReadModifyWriteSharedMemory eventである。bytes をValueOfReadEvent (execution , writeEvent )とする。bytesModified をwriteEvent .[[ModifyOp]] (bytes , writeEvent .[[Payload]] )とする。byte をbytesModified [payloadIndex ]とする。 byte をbytesRead にappendする。byteLocation をbyteLocation + 1に設定する。bytesRead を返す。
Note 1
read-modify-write modification [[ModifyOp]] は、ReadModifyWriteSharedMemory eventsを導入するAtomics object上のfunction propertiesによって与えられる。
Note 2
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:
writes をexecution におけるreads-bytes-from (readEvent )とする。Assert : writes は、lengthがreadEvent .[[ElementSize]] にequalなWriteSharedMemory またはReadModifyWriteSharedMemory eventsのList である。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]] 内に、eventA とeventB の両方を含むeventsRecord .[[EventList]] を持つ何らかのAgent Events Record eventsRecord があり、かつeventsRecord .[[EventList]] のList orderにおいてeventA がeventB より前であるなら、eventA はexecution において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 events をSharedDataBlockEventSet (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 )がreadEvent とwriteEvent の両方を含み、かつexecution におけるreads-bytes-from (readEvent )がwriteEvent を含むなら、readEvent はexecution において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 である。
eventA がexecution において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 について、eventA がexecution においてeventB とhost-synchronizes-withであることは、eventA がexecution においてeventB のhappens-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 について、readEvent がexecution においてwriteEvent からreads-from し、readEvent .[[Order]] がseq-cst であり、writeEvent .[[Order]] がseq-cst であり、かつreadEvent とwriteEvent がequal memory ranges を持つなら、writeEvent はexecution においてreadEvent とsynchronizes-withである。
execution .[[EventsRecords]] の各element eventsRecord について、以下がtrueである。
events eventA およびeventB について、eventsRecord .[[AgentSynchronizesWith]] が(eventA , eventB )を含むなら、eventA はexecution においてeventB とsynchronizes-withである。
イベント eventA および eventB について、execution 内で eventA が eventB と host-synchronizes-with する場合、execution 内で eventA は eventB と synchronizes-with する。
Note 1
memory model literatureにおけるconventionにより、candidate execution execution においては、read events がwrite events とsynchronizes-withするのではなく、write events がread 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 について、writeEvent がreadEvent とsynchronizes-withである場合、readEvent はwriteEvent 以外のwritesからreads-from することがある。
29.6.6 happens-before
candidate execution execution について、そのhappens-before Relation は、以下をsatisfyするMemory events 上のleast Relation である。
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を持つ。
SharedDataBlockEventSet (execution )の各ReadSharedMemory またはReadModifyWriteSharedMemory event readEvent について、chosenValueRecord を、[[Event]] fieldがreadEvent であるexecution .[[ChosenValues]] のelementとする。chosenValue をchosenValueRecord .[[ChosenValue]] とする。readValue をValueOfReadEvent (execution , readEvent )とする。chosenLength をchosenValue 内のelementsの数とする。readLength をreadValue 内のelementsの数とする。chosenLength ≠ readLength なら、false を返す。0(inclusive)からchosenLength (exclusive)までのinterval 内の何らかのinteger i について、chosenValue [i ] ≠ readValue [i ]なら、false を返す。 true を返す。
29.7.2 Coherent Reads
candidate execution execution は、以下のalgorithmがtrue を返すならcoherent readsを持つ。
SharedDataBlockEventSet (execution )の各ReadSharedMemory またはReadModifyWriteSharedMemory event readEvent について、writes をexecution におけるreads-bytes-from (readEvent )とする。byteLocation をreadEvent .[[ByteIndex]] とする。writes の各element writeEvent について、readEvent がexecution においてwriteEvent のhappens-before であるなら、false を返す。byteLocation をそのmemory range 内に持つWriteSharedMemory またはReadModifyWriteSharedMemory event value であって、execution においてwriteEvent がvalue のhappens-before であり、かつvalue がreadEvent のhappens-before であるものが存在するなら、false を返す。byteLocation をbyteLocation + 1に設定する。true を返す。
29.7.3 Tear Free Reads
candidate execution execution は、以下のalgorithmがtrue を返すならtear free readsを持つ。
SharedDataBlockEventSet (execution )の各ReadSharedMemory またはReadModifyWriteSharedMemory event readEvent について、readEvent .[[NoTear]] がtrue なら、Assert : readEvent .[[ByteIndex]] をreadEvent .[[ElementSize]] でdivideしたremainderは0である。execution においてreadEvent がwriteEvent からreads-from し、かつwriteEvent .[[NoTear]] がtrue であるような各Memory event writeEvent について、readEvent とwriteEvent がequal memory ranges を持ち、value とwriteEvent がequal memory ranges を持ち、value .[[NoTear]] がtrue であり、writeEvent とvalue が同じShared Data Block event ではなく、かつexecution においてreadEvent がvalue からreads-from するようなMemory event value が存在するなら、false を返す。true を返す。
Note
Shared Data Block event の[[NoTear]] fieldは、そのeventがinteger TypedArray へのaccessを介して導入されたときtrue であり、floating point TypedArray またはDataViewへのaccessを介して導入されたときfalse である。
直観的には、このrequirementは、memory range がinteger 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 events のstrict total order である。
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 を返すなら、eventA とeventB はrace にある。
eventA とeventB が同じShared Data Block event でないなら、execution においてeventA がeventB のhappens-before であり、かつeventB がeventA のhappens-before である、ということが成り立たないなら、eventA がWriteSharedMemory またはReadModifyWriteSharedMemory eventのいずれかであり、eventB がWriteSharedMemory またはReadModifyWriteSharedMemory eventのいずれかであり、かつeventA とeventB がdisjoint memory ranges を持たないなら、true を返す。eventA がexecution においてeventB からreads-from する、またはeventB がexecution においてeventA からreads-from するなら、true を返す。false を返す。
29.9 Data Races
execution execution と、SharedDataBlockEventSet (execution )に含まれるevents eventA およびeventB について、以下のalgorithmがtrue を返すなら、eventA とeventB はdata race にある。
eventA とeventB がexecution においてrace にあるなら、eventA .[[Order]] がseq-cst でない、またはeventB .[[Order]] がseq-cst でないなら、true を返す。eventA とeventB がoverlapping memory ranges を持つなら、true を返す。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 event のpossible 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 events をis-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 ::
/*
MultiLineCommentChars opt
*/
MultiLineCommentChars ::
MultiLineNotAsteriskChar
MultiLineCommentChars opt
*
PostAsteriskCommentChars opt
PostAsteriskCommentChars ::
MultiLineNotForwardSlashOrAsteriskChar
MultiLineCommentChars opt
*
PostAsteriskCommentChars opt
MultiLineNotAsteriskChar ::
SourceCharacter but not *
MultiLineNotForwardSlashOrAsteriskChar ::
SourceCharacter but not one of / or *
SingleLineComment ::
//
SingleLineCommentChars opt
SingleLineCommentChars ::
SingleLineCommentChar
SingleLineCommentChars opt
SingleLineCommentChar ::
SourceCharacter but not LineTerminator
HashbangComment ::
#!
SingleLineCommentChars opt
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
NumericLiteralSeparator opt
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 ::
"
DoubleStringCharacters opt
"
'
SingleStringCharacters opt
'
DoubleStringCharacters ::
DoubleStringCharacter
DoubleStringCharacters opt
SingleStringCharacters ::
SingleStringCharacter
SingleStringCharacters opt
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 ::
`
TemplateCharacters opt
`
TemplateHead ::
`
TemplateCharacters opt
${
TemplateSubstitutionTail ::
TemplateMiddle
TemplateTail
TemplateMiddle ::
}
TemplateCharacters opt
${
TemplateTail ::
}
TemplateCharacters opt
`
TemplateCharacters ::
TemplateCharacter
TemplateCharacters opt
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] :
[
Elision opt
]
[
ElementList [?Yield, ?Await]
]
[
ElementList [?Yield, ?Await]
,
Elision opt
]
ElementList [Yield, Await] :
Elision opt
AssignmentExpression [+In, ?Yield, ?Await]
Elision opt
SpreadElement [?Yield, ?Await]
ElementList [?Yield, ?Await]
,
Elision opt
AssignmentExpression [+In, ?Yield, ?Await]
ElementList [?Yield, ?Await]
,
Elision opt
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] :
[
Elision opt
AssignmentRestElement [?Yield, ?Await] opt
]
[
AssignmentElementList [?Yield, ?Await]
]
[
AssignmentElementList [?Yield, ?Await]
,
Elision opt
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] :
Elision opt
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] :
[
Elision opt
BindingRestElement [?Yield, ?Await] opt
]
[
BindingElementList [?Yield, ?Await]
]
[
BindingElementList [?Yield, ?Await]
,
Elision opt
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] :
Elision opt
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 :
ScriptBody opt
ScriptBody :
StatementList [~Yield, ~Await, ~Return]
Module :
ModuleBody opt
ModuleBody :
ModuleItemList
ModuleItemList :
ModuleItem
ModuleItemList
ModuleItem
ModuleItem :
ImportDeclaration
ExportDeclaration
StatementListItem [~Yield, +Await, ~Return]
ModuleExportName :
IdentifierName
StringLiteral
ImportDeclaration :
import
ImportClause
FromClause
WithClause opt
;
import
ModuleSpecifier
WithClause opt
;
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
WithClause opt
;
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 :::
StrWhiteSpace opt
StrWhiteSpace opt
StrNumericLiteral
StrWhiteSpace opt
StrWhiteSpace :::
StrWhiteSpaceChar
StrWhiteSpace opt
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 :::
StrWhiteSpace opt
StrWhiteSpace opt
StrIntegerLiteral
StrWhiteSpace opt
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
TemporalDecimalFraction opt
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
UnicodePropertyNameCharacters opt
UnicodePropertyValue ::
UnicodePropertyValueCharacters
LoneUnicodePropertyNameOrValue ::
UnicodePropertyValueCharacters
UnicodePropertyValueCharacters ::
UnicodePropertyValueCharacter
UnicodePropertyValueCharacters opt
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
ClassUnion opt
ClassSetOperand
ClassUnion opt
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
NonEmptyClassString opt
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.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 ::
(
GroupSpecifier opt
Disjunction
)
”へのreferencesは、“
Atom ::
(
GroupSpecifier opt
Disjunction
)
”または“
ExtendedAtom ::
(
GroupSpecifier opt
Disjunction
)
”をmeaningするものとしてinterpretedされる。
B.1.2.3 Static Semantics: IsCharacterClass
22.2.1.6 のsemanticsは以下のようにextendedされる:
ClassAtomNoDash ::
\
[lookahead = c ]
false を返す。
B.1.2.4 Static Semantics: CharacterValue
22.2.1.7 のsemanticsは以下のようにextendedされる:
ClassAtomNoDash ::
\
[lookahead = c ]
U+005C (REVERSE SOLIDUS)のnumeric valueを返す。
ClassEscape ::
c
ClassControlLetter
codePoint をClassControlLetter によりmatchedされるcode pointとする。i をcodePoint のnumeric valueとする。i を32で割ったremainderを返す。
CharacterEscape :: LegacyOctalEscapeSequence
LegacyOctalEscapeSequence のMVを返す(12.9.4.3 を参照)。
B.1.2.5 Runtime Semantics: CompileSubpattern
CompileSubpattern のsemanticsは以下のようにextendedされる:
Term ::
QuantifiableAssertion
Quantifier
のruleは、Atom をQuantifiableAssertion でsubstitutedすることを除き、
Term ::
Atom
Quantifier
の場合と同じである。
Term ::
ExtendedAtom
Quantifier
のruleは、Atom をExtendedAtom でsubstitutedすることを除き、
Term ::
Atom
Quantifier
の場合と同じである。
Term :: ExtendedAtom
のruleは、Atom をExtendedAtom でsubstitutedすることを除き、
Term :: Atom
の場合と同じである。
B.1.2.6 Runtime Semantics: CompileAssertion
Assertion ::
(?=
Disjunction
)
および
Assertion ::
(?!
Disjunction
)
productionsのCompileAssertion rulesは、Assertion をQuantifiableAssertion でsubstitutedすることを除き、QuantifiableAssertion productionsにも使用される。
B.1.2.7 Runtime Semantics: CompileAtom
Atom :: PatternCharacter
を除くAtom productionsのCompileAtom rulesは、Atom をExtendedAtom でsubstitutedすることを除き、ExtendedAtom productionsにも使用される。parameter direction を持つ以下のrulesもaddedされる:
ExtendedAtom ::
\
[lookahead = c ]
charSet を、single character \ U+005C (REVERSE SOLIDUS)を含むCharSet とする。CharacterSetMatcher (regexpRecord , charSet , false , direction )を返す。
ExtendedAtom :: ExtendedPatternCharacter
char をExtendedPatternCharacter によりrepresentedされるcharacterとする。charSet をcharacter char を含むone-element CharSet とする。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
charSet をargument regexpRecord を伴うfirst ClassAtom のCompileToCharSet とする。otherSet をargument regexpRecord を伴うsecond ClassAtom のCompileToCharSet とする。remainingSet をargument regexpRecord を伴うClassContents のCompileToCharSet とする。rangeSet をCharacterRangeOrUnion (regexpRecord , charSet , otherSet )とする。rangeSet とremainingSet のunionを返す。
NonemptyClassRangesNoDash ::
ClassAtomNoDash
-
ClassAtom
ClassContents
charSet をargument regexpRecord を伴うClassAtomNoDash のCompileToCharSet とする。otherSet をargument regexpRecord を伴うClassAtom のCompileToCharSet とする。remainingSet をargument regexpRecord を伴うClassContents のCompileToCharSet とする。rangeSet をCharacterRangeOrUnion (regexpRecord , charSet , otherSet )とする。rangeSet とremainingSet のunionを返す。
さらに、以下のrulesがCompileToCharSet にaddedされる。
ClassEscape ::
c
ClassControlLetter
charValue をこのClassEscape のCharacterValue とする。char をcharacter valueがcharValue であるcharacterとする。single character char を含むCharSet を返す。
ClassAtomNoDash ::
\
[lookahead = c ]
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:
HasEitherUnicodeFlag (regexpRecord )がfalse なら、charSet がexactly one characterをcontainしない、またはotherSet がexactly one characterをcontainしないなら、remainingSet をsingle character - U+002D (HYPHEN-MINUS)を含むCharSet とする。CharSets charSet 、otherSet およびremainingSet のunionを返す。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を実行する:
v がtrue でありu がtrue なら、parseResult を1つ以上のSyntaxError objectsを含むList とする。そうでなく、v がtrue なら、parseResult をParseText (patternText , Pattern [+UnicodeMode, +UnicodeSetsMode, +NamedCaptureGroups] )とする。 そうでなく、u がtrue なら、parseResult をParseText (patternText , Pattern [+UnicodeMode, ~UnicodeSetsMode, +NamedCaptureGroups] )とする。 そうでなければ、parseResult をParseText (patternText , Pattern [~UnicodeMode, ~UnicodeSetsMode, ~NamedCaptureGroups] )とする。parseResult がParse Node であり、parseResult がGroupName を含むなら、parseResult をParseText (patternText , Pattern [~UnicodeMode, ~UnicodeSetsMode, +NamedCaptureGroups] )に設定する。 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
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を実行する:
string を ? ToString (string ) に設定する。length をstring のlengthとする。result をempty Stringとする。unescapedSet をASCII word charactersと"@*+-./" のstring-concatenation とする。k を0とする。k < length である間、繰り返す:codeUnit をstring 内のindex k にあるcode unitとする。unescapedSet がcodeUnit をcontainするなら、nextPart をcodeUnit とする。そうでなければ、codeUnitNumber をcodeUnit のnumeric valueとする。codeUnitNumber < 256なら、hex を、uppercase hexadecimal numberとしてformattedされたcodeUnitNumber のString representationとする。nextPart を"%" とStringPad (hex , 2, "0" , start )のstring-concatenation とする。そうでなければ、hex を、uppercase hexadecimal numberとしてformattedされたcodeUnitNumber のString representationとする。nextPart を"%u" とStringPad (hex , 4, "0" , start )のstring-concatenation とする。 result をresult とnextPart のstring-concatenation に設定する。k をk + 1に設定する。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を実行する:
string を ? ToString (string ) に設定する。length をstring のlengthとする。result をempty Stringとする。k を0とする。k < length である間、繰り返す:codeUnit をstring 内のindex k にあるcode unitとする。codeUnit がcode unit 0x0025 (PERCENT SIGN)であるなら、hexDigits をempty Stringとする。optionalAdvance を0とする。k + 5 < length であり、string 内のindex k + 1にあるcode unitがcode unit 0x0075 (LATIN SMALL LETTER U)であるなら、hexDigits をstring のk + 2からk + 6までのsubstring に設定する。optionalAdvance を5に設定する。そうでなく、k + 3 ≤ length なら、hexDigits をstring のk + 1からk + 3までのsubstring に設定する。optionalAdvance を2に設定する。 parseResult をParseText (hexDigits , HexDigits [~Sep] )とする。parseResult がParse Node なら、codeUnitNumber をparseResult のMVとする。codeUnit をnumeric valueがcodeUnitNumber であるcode unitに設定する。k をk + optionalAdvance に設定する。result をresult とcodeUnit のstring-concatenation に設定する。k をk + 1に設定する。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だけ(またはlength がundefined ならStringのendまで)runningする。start がnegativeなら、それはsourceLength + start としてtreatedされる。ここでsourceLength はStringのlengthである。resultはString valueであり、String objectではない。
呼び出されたとき、以下のstepsを実行する:
obj をthis valueとする。? RequireObjectCoercible (obj )を実行する。 string を ? ToString (obj ) とする。size をstring のlengthとする。intStart を ? ToIntegerOrInfinity (start ) とする。intStart = -∞なら、intStart を0に設定する。そうでなく、intStart < 0なら、intStart をmax (size + intStart , 0)に設定する。 そうでなければ、intStart をmin (intStart , size )に設定する。 length がundefined なら、intLength をsize とする;そうでなければ、intLength を ? ToIntegerOrInfinity (length ) とする。intLength を0とsize の間にclamping したresultに設定する。intEnd をmin (intStart + intLength , size )とする。string のintStart から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を実行する:
string をthis valueとする。? 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:
? RequireObjectCoercible (contents )を実行する。 contentsString を ? ToString (contents ) とする。part1 を"<" とtag のstring-concatenation とする。attr がempty Stringでないなら、attrValueString を ? ToString (attrValue ) とする。escapedAttrValue を、attrValueString 内のcode unit 0x0022 (QUOTATION MARK)の各occurrenceがsix code unit sequence """ でreplacedされたことを除きattrValueString と同じString valueとする。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) part2 をpart1 と">" のstring-concatenation とする。part3 をpart2 とcontentsString のstring-concatenation とする。part4 をpart3 、"</" 、tag 、および">" のstring-concatenation とする。part4 を返す。
B.2.2.3 String.prototype.big ( )
このmethodは呼び出されたとき、以下のstepsを実行する:
string をthis valueとする。? CreateHTML (string , "big" , "" , "" )を返す。
B.2.2.4 String.prototype.blink ( )
このmethodは呼び出されたとき、以下のstepsを実行する:
string をthis valueとする。? CreateHTML (string , "blink" , "" , "" )を返す。
B.2.2.5 String.prototype.bold ( )
このmethodは呼び出されたとき、以下のstepsを実行する:
string をthis valueとする。? CreateHTML (string , "b" , "" , "" )を返す。
B.2.2.6 String.prototype.fixed ( )
このmethodは呼び出されたとき、以下のstepsを実行する:
string をthis valueとする。? CreateHTML (string , "tt" , "" , "" )を返す。
B.2.2.7 String.prototype.fontcolor ( colour )
このmethodは呼び出されたとき、以下のstepsを実行する:
string をthis valueとする。? CreateHTML (string , "font" , "color" , colour )を返す。
B.2.2.8 String.prototype.fontsize ( size )
このmethodは呼び出されたとき、以下のstepsを実行する:
string をthis valueとする。? CreateHTML (string , "font" , "size" , size )を返す。
B.2.2.9 String.prototype.italics ( )
このmethodは呼び出されたとき、以下のstepsを実行する:
string をthis valueとする。? CreateHTML (string , "i" , "" , "" )を返す。
B.2.2.10 String.prototype.link ( url )
このmethodは呼び出されたとき、以下のstepsを実行する:
string をthis valueとする。? CreateHTML (string , "a" , "href" , url )を返す。
B.2.2.11 String.prototype.small ( )
このmethodは呼び出されたとき、以下のstepsを実行する:
string をthis valueとする。? CreateHTML (string , "small" , "" , "" )を返す。
B.2.2.12 String.prototype.strike ( )
このmethodは呼び出されたとき、以下のstepsを実行する:
string をthis valueとする。? CreateHTML (string , "strike" , "" , "" )を返す。
B.2.2.13 String.prototype.sub ( )
このmethodは呼び出されたとき、以下のstepsを実行する:
string をthis valueとする。? CreateHTML (string , "sub" , "" , "" )を返す。
B.2.2.14 String.prototype.sup ( )
このmethodは呼び出されたとき、以下のstepsを実行する:
string をthis valueとする。? 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を実行する:
dateObj をthis valueとする。? RequireInternalSlot (dateObj , [[DateValue]] )を実行する。 tv をdateObj .[[DateValue]] とする。tv がNaN なら、NaN を返す。YearFromTime (LocalTime (tv )) - 1900 𝔽 を返す。
B.2.3.2 Date.prototype.setYear ( year )
Note
setFullYear methodは“year 2000 problem”をavoidするため、ほぼすべての目的でpreferredされる。
このmethodは呼び出されたとき、以下のstepsを実行する:
dateObj をthis valueとする。? RequireInternalSlot (dateObj , [[DateValue]] )を実行する。 time をdateObj .[[DateValue]] とする。year を ? ToNumber (year ) とする。time がNaN なら、time を+0 𝔽 に設定する;そうでなければ、time をLocalTime (time )に設定する。fullYear をMakeFullYear (year )とする。day をMakeDay (fullYear , MonthFromTime (time ), DateFromTime (time ))とする。date をMakeDate (day , TimeWithinDay (time ))とする。utcTimestamp をTimeClip (UTC (date ))とする。dateObj .[[DateValue]] をutcTimestamp に設定する。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を実行する:
obj をthis valueとする。? RequireInternalSlot (obj , [[RegExpMatcher]] )を実行する。 pattern がObjectであり、pattern が[[RegExpMatcher]] internal slotを持つなら、flags がundefined でないなら、TypeError 例外をthrowする。flags をpattern .[[OriginalFlags]] に設定する。pattern をpattern .[[OriginalSource]] に設定する。? 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 FunctionDeclaration はnon-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
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である:
functionがdeclaredされ、single block内でのみreferencedされる。
functionがdeclaredされ、single Block 内でpossibly usedされるが、同じBlock 内にcontainedされないinner function definitionによってalso referencedされる。
functionがdeclaredされ、single block内でpossibly usedされるが、subsequent blocks内でもreferencedされる。
first use caseは、ECMAScript 2015によってprovidedされるBlock level function declarationsのsemanticsとinteroperableである。そのuse caseをemployするpre-existing ECMAScript source text は、clauses 10 、14 、および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 内のContainsDuplicateLabels のstatic semantics は以下でaugmentedされる:
ForInOfStatement :
for
(
var
BindingIdentifier
Initializer
in
Expression
)
Statement
argument labelSet を伴うStatement のContainsDuplicateLabels を返す。
8.3.2 内のContainsUndefinedBreakTarget のstatic semantics は以下でaugmentedされる:
ForInOfStatement :
for
(
var
BindingIdentifier
Initializer
in
Expression
)
Statement
argument labelSet を伴うStatement のContainsUndefinedBreakTarget を返す。
8.3.3 内のContainsUndefinedContinueTarget のstatic semantics は以下でaugmentedされる:
ForInOfStatement :
for
(
var
BindingIdentifier
Initializer
in
Expression
)
Statement
arguments iterationSet および « » を伴うStatement のContainsUndefinedContinueTarget を返す。
14.7.5.2 内のIsDestructuring のstatic semantics は以下でaugmentedされる:
BindingIdentifier :
Identifier
yield
await
false を返す。
8.2.8 内のVarDeclaredNames のstatic semantics は以下でaugmentedされる:
ForInOfStatement :
for
(
var
BindingIdentifier
Initializer
in
Expression
)
Statement
names1 をBindingIdentifier のBoundNames とする。names2 をStatement のVarDeclaredNames とする。names1 とnames2 のlist-concatenation を返す。
8.2.9 内のVarScopedDeclarations のstatic semantics は以下でaugmentedされる:
ForInOfStatement :
for
(
var
BindingIdentifier
Initializer
in
Expression
)
Statement
decls1 を « BindingIdentifier » とする。decls2 をStatement のVarScopedDeclarations とする。decls1 とdecls2 のlist-concatenation を返す。
14.7.5.5 内のForInOfLoopEvaluationのruntime semantics は以下でaugmentedされる:
ForInOfStatement :
for
(
var
BindingIdentifier
Initializer
in
Expression
)
Statement
bindingId をBindingIdentifier のStringValue とする。lhs を ? ResolveBinding (bindingId ) とする。IsAnonymousFunctionDefinition (Initializer )がtrue なら、value をargument bindingId を伴うInitializer のNamedEvaluation とする。そうでなければ、rhs を ? Initializer のEvaluation とする。value を ? GetValue (rhs ) とする。 ? PutValue (lhs , value )を実行する。 keyResult を ? ForIn/OfHeadEvaluation (« », Expression , enumerate ) とする。? ForIn/OfBodyEvaluation (BindingIdentifier , Statement , keyResult , enumerate , var-binding , labelSet )を返す。
B.3.6 [[IsHTMLDDA]] Internal Slot
[[IsHTMLDDA]] internal slot はhost-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がAssignmentExpression のLeftHandSideExpression である場合、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.36 :21.4.1.32 でspecifiedされるDate Time String Formatを使用してyearをrepresentedできない場合、RangeError例外がthrownされる。Previous editionsはそのcaseのbehaviourをspecifyしていなかった。
21.4.4.41 :Previous editionsは、time value がNaN であるときに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_Separator(Zs)categoryにあり、したがってwhitespaceとしてtreatedされていたが、(Unicode 6.3.0以降)Format(Cf)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 code はearly error をproduceしない。代わりにruntime errorをproduceする。
14.2 :ECMAScript 2015では、token letで始まり、その後にinput elements LineTerminator 、次にIdentifier が続くStatementList はLexicalDeclaration のstartである。previous editionsでは、automatic semicolon insertionは常にIdentifier input elementの前にsemicolonをinsertしていた。
14.5 :ECMAScript 2015では、token letで始まりtoken [が続くStatementListItem はLexicalDeclaration の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 [が続く場合、そのletはLexicalDeclaration のstartとしてtreatedされる。previous editionsでは、そのようなtoken sequenceはExpression のstartであった。
14.7 :ECMAScript 2015では、for-in statementの( tokenの直後にtoken sequence let [が続く場合、そのletはForDeclaration の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 には決してならない。IterationStatement のStatement 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 には決してならない。WithStatement のStatement 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 には決してならない。SwitchStatement のCaseBlock 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 ではない。TryStatement のBlock partがempty を含むnormal completion へevaluatesする場合、TryStatement のresultはundefined である。TryStatement のBlock 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 objects はconstructor 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でありflags がundefined でない場合、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.wakeはAtomics.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
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の間にない。
The Unicode Standard 、<https://unicode.org/versions/latest >で入手可能
Unicode Technical Note #5: Canonical Equivalence in Applications 、<https://unicode.org/notes/tn5/ >で入手可能
Unicode Technical Standard #10: Unicode Collation Algorithm 、<https://unicode.org/reports/tr10/ >で入手可能
Unicode Standard Annex #15, Unicode Normalization Forms 、<https://unicode.org/reports/tr15/ >で入手可能
Unicode Standard Annex #18: Unicode Regular Expressions 、<https://unicode.org/reports/tr18/ >で入手可能
Unicode Standard Annex #24: Unicode Script Property 、<https://unicode.org/reports/tr24/ >で入手可能
Unicode Standard Annex #31, Unicode Identifiers and Pattern Syntax 、<https://unicode.org/reports/tr31/ >で入手可能
Unicode Standard Annex #44: Unicode Character Database 、<https://unicode.org/reports/tr44/ >で入手可能
Unicode Technical Standard #51: Unicode Emoji 、<https://unicode.org/reports/tr51/ >で入手可能
IANA Time Zone Database 、<https://www.iana.org/time-zones >で入手可能
ISO 8601:2004(E) Data elements and interchange formats — Information interchange — Representation of dates and times
RFC 1738 “Uniform Resource Locators (URL)” 、<https://tools.ietf.org/html/rfc1738 >で入手可能
RFC 2396 “Uniform Resource Identifiers (URI): Generic Syntax” 、<https://tools.ietf.org/html/rfc2396 >で入手可能
RFC 3629 “UTF-8, a transformation format of ISO 10646” 、<https://tools.ietf.org/html/rfc3629 >で入手可能
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/
Copyright Notice
ALTERNATIVE COPYRIGHT NOTICE AND COPYRIGHT LICENSE
© 2026 Ecma International
By obtaining and/or copying this work, you (the licensee) agree that you
have read, understood, and will comply with the following terms and
conditions.
Permission under Ecma’s copyright to copy, modify, prepare derivative works
of, and distribute this work, with or without modification, for any purpose
and without fee or royalty is hereby granted, provided that you include the
following on ALL copies of the work or portions thereof, including
modifications:
(i) The full text of this COPYRIGHT NOTICE AND COPYRIGHT LICENSE in a location
viewable to users of the redistributed or derivative work.
(ii) Any pre-existing intellectual property disclaimers, notices, or terms and
conditions. If none exist, the Ecma alternative copyright notice should be
included.
(iii) Notice of any changes or modifications, through a copyright statement on
the document such as “This document includes material copied from or
derived from ECMAScript® 2027 言語仕様 https://tc39.es/ecma262/.
Copyright © Ecma International.”
Disclaimers
THIS WORK IS PROVIDED “AS IS,” AND COPYRIGHT HOLDERS MAKE NO REPRESENTATIONS
OR WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO, WARRANTIES
OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF
THE DOCUMENT WILL NOT INFRINGE ANY THIRD PARTY PATENTS, COPYRIGHTS,
TRADEMARKS OR OTHER RIGHTS.
COPYRIGHT HOLDERS WILL NOT BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL OR
CONSEQUENTIAL DAMAGES ARISING OUT OF ANY USE OF THE DOCUMENT.
The name and trademarks of copyright holders may NOT be used in advertising
or publicity pertaining to the work without specific, written prior
permission. Title to copyright in this work will at all times remain with
copyright holders.
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:
Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
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.
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.