Draft ECMA-262 / June 25, 2026

ECMAScript® 2027 언어 명세

이 명세에 대하여

https://tc39.es/ecma262/에 있는 문서는 가장 정확하고 최신인 ECMAScript 명세입니다. 여기에는 가장 최근의 연간 스냅샷 내용과 모든 완료된 제안 — 즉 제안 절차에서 Stage 4에 도달하여 여러 구현에서 구현되었고 다음 연간 스냅샷에 포함될 제안 — 이 포함됩니다. 역사적 스냅샷은 https://ecma-international.org/publications-and-standards/standards/ecma-262/에서 사용할 수 있습니다.

이 문서는 단일 페이지여러 페이지로 사용할 수 있습니다.

이 명세에 기여하기

이 명세는 ECMAScript 커뮤니티의 도움으로 GitHub에서 개발됩니다. 이 명세 개발에 기여하는 방법은 여러 가지가 있습니다:

이 문서가 어떻게 만들어지는지에 대한 자세한 내용은 colophon을 참조하십시오.

소개

이 Ecma 표준은 ECMAScript 2027 언어를 정의합니다. 이는 ECMAScript 언어 명세의 제18판입니다. ECMAScript는 여러 기원 기술을 기반으로 하며, 그중 가장 잘 알려진 것은 JavaScript(Netscape)와 JScript(Microsoft)입니다. 이 언어는 Netscape의 Brendan Eich가 발명했으며, 그 회사의 Navigator 2.0 브라우저에 처음 등장했습니다. 웹 브라우저에 내장된 언어로 가장 잘 알려져 있지만, 서버 및 임베디드 애플리케이션을 포함하여 브라우저 밖에서도 널리 채택되었으며, 세계에서 가장 널리 사용되는 범용 프로그래밍 언어 중 하나로 성장했습니다.

ECMAScript 언어 명세의 개발은 1996년 11월에 시작되었습니다. 이 Ecma 표준의 초판은 1997년 6월 Ecma 총회에서 채택되었습니다.

그 Ecma 표준은 fast-track 절차에 따라 ISO/IEC JTC 1에 채택을 위해 제출되었고, 1998년 4월에 국제 표준 ISO/IEC 16262로 승인되었습니다. 1998년 6월 Ecma 총회는 ECMA-262의 제2판을 ISO/IEC 16262와 완전히 일치하도록 승인했습니다. 초판과 제2판 사이의 변경 사항은 편집상 변경입니다.

표준의 제3판은 강력한 정규 표현식, 더 나은 문자열 처리, 새로운 제어문, try/catch 예외 처리, 오류의 더 엄밀한 정의, 숫자 출력 형식화 및 향후 언어 성장을 예상한 소규모 변경을 도입했습니다. ECMAScript 표준 제3판은 1999년 12월 Ecma 총회에서 채택되었고 2002년 6월 ISO/IEC 16262:2002로 공개되었습니다.

제3판 공개 이후, ECMAScript는 World Wide Web과 함께 대규모로 채택되어 사실상 모든 웹 브라우저가 지원하는 프로그래밍 언어가 되었습니다. ECMAScript 제4판 개발을 위한 중요한 작업이 수행되었습니다. 그러나 그 작업은 완료되지 않았고 ECMAScript 제4판으로 공개되지 않았지만, 그 일부는 제6판 개발에 포함되었습니다.

ECMAScript 제5판(ECMA-262 5th edition으로 공개됨)은 브라우저 구현 사이에서 일반화된 언어 명세의 사실상 해석을 성문화하고, 제3판 공개 이후 등장한 새로운 기능에 대한 지원을 추가했습니다. 그러한 기능에는 접근자 속성, 객체의 반사적 생성과 검사, 속성 어트리뷰트의 프로그램 제어, 추가 배열 조작 함수, JSON 객체 인코딩 형식 지원, 그리고 향상된 오류 검사와 프로그램 보안을 제공하는 strict mode가 포함됩니다. 제5판은 2009년 12월 Ecma 총회에서 채택되었습니다.

제5판은 fast-track 절차에 따라 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 사용을 더 잘 지원하는 것이 포함되었습니다. 주요 개선 사항에는 모듈, 클래스 선언, lexical block scoping, 이터레이터와 제너레이터, 비동기 프로그래밍을 위한 promise, 구조 분해 패턴, proper tail calls가 포함되었습니다. ECMAScript 내장 라이브러리는 맵, 세트, 이진 숫자 값의 배열을 포함한 추가 데이터 추상화를 지원하도록 확장되었으며, 문자열과 정규 표현식에서 Unicode supplementary character에 대한 추가 지원도 포함했습니다. 또한 내장 객체는 서브클래싱을 통해 확장 가능하게 만들어졌습니다. 제6판은 정기적이고 점진적인 언어 및 라이브러리 향상의 기반을 제공합니다. 제6판은 2015년 6월 총회에서 채택되었습니다.

ECMAScript 2016은 Ecma TC39의 새로운 연간 릴리스 주기와 개방형 개발 절차에 따라 릴리스된 첫 번째 ECMAScript 판이었습니다. ECMAScript 2015 소스 문서에서 평문 소스 문서를 만들어 GitHub에서 완전히 이어지는 개발의 기반으로 삼았습니다. 이 표준이 개발된 1년 동안 수백 개의 pull request와 issue가 제출되었으며, 이는 수천 건의 버그 수정, 편집상 수정 및 기타 개선을 나타냅니다. 또한 Ecmarkup, Ecmarkdown, Grammarkdown을 포함하여 이 작업을 돕기 위한 수많은 소프트웨어 도구가 개발되었습니다. ES2016은 또한 새로운 지수 연산자 지원을 포함하고, Array.prototypeincludes라는 새 메서드를 추가했습니다.

ECMAScript 2017은 Async Functions, Shared Memory, Atomics를 도입했으며, 이와 함께 더 작은 언어 및 라이브러리 개선, 버그 수정, 편집상 업데이트를 포함했습니다. Async functions는 promise를 반환하는 함수를 위한 구문을 제공하여 비동기 프로그래밍 경험을 개선합니다. Shared Memory와 Atomics는 여러 agent 프로그램이 병렬 CPU에서도 잘 정의된 실행 순서를 보장하는 atomic operation을 사용하여 통신할 수 있게 하는 새로운 메모리 모델을 도입합니다. 또한 Object의 새로운 static method인 Object.values, Object.entries, Object.getOwnPropertyDescriptors도 포함되었습니다.

ECMAScript 2018은 async iterator protocol과 async generator를 통한 비동기 반복 지원을 도입했습니다. 또한 네 가지 새로운 정규 표현식 기능인 dotAll 플래그, named capture group, Unicode property escape, look-behind assertion을 포함했습니다. 마지막으로 object rest 및 spread properties를 포함했습니다.

ECMAScript 2019는 몇 가지 새로운 내장 함수를 도입했습니다: 배열을 평탄화하기 위한 Array.prototypeflatflatMap, Object.entries의 반환값을 직접 새 Object로 바꾸기 위한 Object.fromEntries, 그리고 널리 구현되었지만 비표준인 String.prototype.trimLefttrimRight 내장 함수의 더 나은 이름을 가진 대안으로서 String.prototypetrimStarttrimEnd가 포함됩니다. 또한 구문과 의미에 대한 몇 가지 사소한 업데이트가 포함되었습니다. 업데이트된 구문에는 optional catch binding parameter와 JSON에 맞추기 위해 문자열 리터럴에서 U+2028(LINE SEPARATOR) 및 U+2029(PARAGRAPH SEPARATOR)를 허용하는 것이 포함되었습니다. 다른 업데이트에는 Array.prototype.sort가 stable sort여야 한다는 요구, JSON.stringify가 입력과 관계없이 well-formed UTF-8을 반환해야 한다는 요구, 그리고 Function.prototype.toString이 해당 원본 소스 텍스트 또는 표준 placeholder를 반환해야 한다고 명확히 하는 것이 포함되었습니다.

ECMAScript 2020, 제11판은 전역 정규 표현식이 생성하는 모든 match object에 대한 iterator를 생성하기 위해 String의 matchAll 메서드; 동적 specifier로 Module을 비동기적으로 import하는 구문인 import(); 임의 정밀도 정수 작업을 위한 새로운 number primitive인 BigInt; short-circuit하지 않는 새로운 Promise combinator인 Promise.allSettled; 전역 this 값에 접근하는 보편적 방법인 globalThis; module 내에서 사용하기 위한 전용 export * as ns from 'module' 구문; for-in 열거 순서의 표준화 확대; Module에서 사용할 수 있고 Module에 대한 문맥 정보를 포함할 수 있는 host-populated object인 import.meta; 그리고 “nullish” 값(undefined 또는 null) 작업을 개선하기 위한 두 가지 새로운 구문 기능인 값 선택 연산자 nullish coalescing과, 접근/호출할 값이 nullish이면 short-circuit하는 속성 접근 및 함수 호출 연산자 optional chaining을 도입했습니다.

ECMAScript 2021, 제12판은 String의 replaceAll 메서드; 입력 값이 fulfilled되면 short-circuit하는 Promise combinator인 Promise.any; 여러 오류를 한 번에 표현하는 새로운 Error 타입인 AggregateError; logical assignment operators(??=, &&=, ||=); 대상 객체가 garbage collection되지 않도록 보존하지 않고 참조하기 위한 WeakRef, 그리고 대상 객체가 garbage collection될 때 수행되는 cleanup operation의 등록과 해제를 관리하기 위한 FinalizationRegistry; 숫자 리터럴의 separator(1_000); 그리고 Array.prototype.sort를 더 정밀하게 만들어 구현 정의 정렬 순서가 되는 경우의 수를 줄인 것을 도입했습니다.

ECMAScript 2022, 제13판은 top-level await를 도입하여 module의 top level에서 해당 keyword를 사용할 수 있게 했습니다; 새로운 class element로 public 및 private instance field, public 및 private static field, private instance method와 accessor, private static method와 accessor를 도입했습니다; class 내부에서 per-class evaluation initialization을 수행하기 위한 static block; 객체에 private field가 존재하는지 테스트하기 위한 #x in obj 구문; match된 substring의 start 및 end index를 제공하는 /d 플래그를 통한 regular expression match indices; 오류에서 causation chain을 기록하는 데 사용할 수 있는 Error object의 cause 속성; relative indexing을 허용하는 String, Array, TypedArrayat 메서드; 그리고 Object.prototype.hasOwnProperty의 편리한 대안인 Object.hasOwn을 도입했습니다.

ECMAScript 2023, 제14판은 Array.prototypeTypedArray.prototypetoSorted, toReversed, with, findLast, findLastIndex 메서드와 Array.prototypetoSpliced 메서드를 도입했습니다; 실행 가능한 ECMAScript 파일을 더 잘 지원하기 위해 파일 시작 부분의 #! 주석 지원을 추가했습니다; 그리고 대부분의 Symbol을 weak collection의 key로 사용할 수 있게 했습니다.

ECMAScript 2024, 제15판은 ArrayBuffer와 SharedArrayBuffer의 resizing 및 transferring을 위한 기능을 추가했습니다; string set 작업을 위한 더 고급 기능을 갖춘 RegExp를 만들기 위한 새로운 RegExp /v 플래그를 추가했습니다; 그리고 Promise를 구성하기 위한 편의 메서드 Promise.withResolvers, 데이터를 집계하기 위한 Object.groupByMap.groupBy 메서드, shared memory 변경을 비동기적으로 기다리기 위한 Atomics.waitAsync 메서드, 문자열이 well-formed Unicode만 포함하는지 확인하고 보장하기 위한 String.prototype.isWellFormedString.prototype.toWellFormed 메서드를 도입했습니다.

ECMAScript 2025, 제16판은 iterator 작업을 위한 관련 static 및 prototype method를 가진 새로운 Iterator global을 추가했습니다; Set에 대한 일반적인 operation을 수행하기 위한 메서드를 Set.prototype에 추가했습니다; JSON module import 지원과 imported module의 attribute를 선언하는 구문을 추가했습니다; 문자열을 정규 표현식에서 안전하게 사용할 수 있도록 escape하는 RegExp.escape 메서드를 추가했습니다; 정규 표현식 내에서 modifier flag를 inline으로 활성화하고 비활성화하는 구문을 추가했습니다; Promise를 반환할 수도 있고 반환하지 않을 수도 있는 함수를 호출하고 결과가 항상 Promise가 되도록 보장하기 위한 Promise.try 메서드를 추가했습니다; 그리고 새로운 Float16Array TypedArray kind와 관련된 DataView.prototype.getFloat16, DataView.prototype.setFloat16, Math.f16round 메서드를 추가했습니다.

ECMAScript 2026, 제17판은 precision loss를 최소화하면서 크기가 다양한 Number의 iterable을 합산하기 위한 Math.sumPrecise; iterator를 순서대로 연결하기 위한 Iterator.concat; async iterable과 다른 async source로부터 Array를 구성하기 위한 Array.fromAsync; error object를 식별하기 위한 Error.isError; key가 아직 존재하지 않을 때 retrieval 중 사용할 default value를 제공하기 위한 Map.prototypeWeakMap.prototype의 메서드; 16진수 및 base64로 인코딩된 이진 데이터 String으로 변환하거나 그로부터 변환하기 위한 Uint8Array의 메서드; JSON source의 match된 segment에 접근하기 위한 JSON.parse reviver의 parameter; 그리고 primitive value에 대한 JSON.stringify 출력을 세밀하게 제어하기 위한 JSON.rawJSON을 추가했습니다.

많은 조직을 대표하는 수십 명의 개인이 Ecma TC39 내에서 이 판과 이전 판들의 개발에 매우 중요한 기여를 했습니다. 또한 TC39의 ECMAScript 작업을 지원하는 활발한 커뮤니티가 형성되었습니다. 이 커뮤니티는 수많은 draft를 검토하고, 수천 건의 bug report를 제출하고, implementation experiment를 수행하고, test suite에 기여하고, 전 세계 개발자 커뮤니티에 ECMAScript를 교육했습니다. 안타깝게도 이 노력에 기여한 모든 개인과 조직을 식별하고 감사를 표하는 것은 불가능합니다.

Allen Wirfs-Brock
ECMA-262, 제6판 프로젝트 편집자

Brian Terlson
ECMA-262, 제7판부터 제10판까지 프로젝트 편집자

Jordan Harband
ECMA-262, 제10판부터 제12판까지 프로젝트 편집자

Kevin Gibbons
ECMA-262, 제12판부터 제17판까지 프로젝트 편집자

Shu-yu Guo
ECMA-262, 제12판부터 제18판까지 프로젝트 편집자

Michael Ficarra
ECMA-262, 제12판부터 제18판까지 프로젝트 편집자

Richard Gibson
ECMA-262, 제18판 프로젝트 편집자

Ron Buckton
ECMA-262, 제18판 프로젝트 편집자

Nicolò Ribaudo
ECMA-262, 제18판 프로젝트 편집자

Linus Groh
ECMA-262, 제18판 프로젝트 편집자

1 범위

이 표준은 ECMAScript 2027 범용 프로그래밍 언어를 정의합니다.

2 적합성

ECMAScript의 conforming implementation은 이 명세에 설명된 모든 타입, 값, 객체, 속성, 함수, 그리고 프로그램 구문과 의미를 제공하고 지원해야 합니다.

ECMAScript의 conforming implementation은 최신 버전의 Unicode Standard 및 ISO/IEC 10646에 부합하게 source text input을 해석해야 합니다.

서로 다른 인간 언어와 국가에서 사용되는 언어적·문화적 관례에 적응해야 하는 프로그램을 지원하는 application programming interface(API)를 제공하는 ECMAScript의 conforming implementation은 이 명세와 호환되는 ECMA-402의 가장 최근 판에서 정의한 interface를 구현해야 합니다.

ECMAScript의 conforming implementation은 이 명세에 설명된 것 외에 추가 타입, 값, 객체, 속성 및 함수를 제공할 수 있습니다. 특히, ECMAScript의 conforming implementation은 이 명세에 설명된 객체에 대해 이 명세에 설명되지 않은 속성과 그 속성의 값을 제공할 수 있습니다.

ECMAScript의 conforming implementation은 이 명세에 설명되지 않은 프로그램 및 정규 표현식 구문을 지원할 수 있습니다. 특히, ECMAScript의 conforming implementation은 이 명세의 하위 절 12.7.2에 언급된 모든 “future reserved words”를 사용하는 프로그램 구문을 지원할 수 있습니다.

ECMAScript의 conforming implementation은 하위 절 17.1에서 Forbidden Extension으로 열거된 어떤 확장도 구현해서는 안 됩니다.

ECMAScript의 conforming implementation은 implementation-defined, implementation-approximated, 또는 host-defined가 아닌 어떤 기능도 재정의해서는 안 됩니다.

ECMAScript의 conforming implementation은 달리 명시되지 않는 한 Normative Optional 하위 절을 구현할지 여부를 선택할 수 있습니다. 웹 브라우저는 일반적으로 모든 normative optional 하위 절을 구현해야 합니다. (Annex B 참조.) 어떤 Normative Optional 동작이 구현되면, 이를 포함하는 Normative Optional clause의 모든 동작이 구현되어야 합니다. Normative Optional clause는 아래에 표시된 것처럼 이 명세에서 색이 있는 상자 안의 “Normative Optional”이라는 단어로 표시됩니다.

2.1 예시 Normative Optional 절 제목

예시 절 내용.

ECMAScript의 conforming implementation은 Legacy 하위 절이 Normative Optional로도 표시되어 있지 않은 한 Legacy 하위 절을 구현해야 합니다. Legacy 하위 절 안에 명시된 모든 언어 기능과 동작은 하나 이상의 바람직하지 않은 특성을 가집니다. 그러나 기존 애플리케이션에서 계속 사용되고 있기 때문에 이 명세에서 제거할 수 없습니다. 이러한 기능은 핵심 ECMAScript 언어의 일부로 간주되지 않습니다. 프로그래머는 새로운 ECMAScript 코드를 작성할 때 이러한 기능과 동작의 존재를 사용하거나 가정해서는 안 됩니다.

2.2 예시 Legacy 절 제목

예시 절 내용.

2.3 예시 Legacy Normative Optional 절 제목

예시 절 내용.

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) 및 Amendment 1:2005, Amendment 2:2006, Amendment 3:2008, Amendment 4:2008, 그리고 추가 amendment와 corrigenda, 또는 successor.

ECMA-402, ECMAScript Internationalization API 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는 host environment 안에서 계산을 수행하고 computational object를 조작하기 위한 객체 지향 프로그래밍 언어입니다. 여기서 정의된 ECMAScript는 계산적으로 자급자족하도록 의도되지 않았습니다. 실제로 이 명세에는 외부 데이터 입력이나 계산 결과 출력에 대한 규정이 없습니다. 대신 ECMAScript 프로그램의 computational environment는 이 명세에 설명된 객체와 기타 기능뿐만 아니라, 이 명세의 범위를 벗어나는 설명과 동작을 갖는 특정 environment-specific object도 제공할 것으로 기대됩니다. 다만 그러한 객체가 ECMAScript 프로그램에서 접근할 수 있는 특정 속성과 호출할 수 있는 특정 함수를 제공할 수 있음을 나타내는 경우는 예외입니다.

ECMAScript는 원래 scripting language로 사용되도록 설계되었지만, 현재는 general-purpose programming language로 널리 사용됩니다. scripting language는 기존 시스템의 기능을 조작, 사용자화, 자동화하는 데 사용되는 프로그래밍 언어입니다. 그러한 시스템에서는 유용한 기능이 이미 user interface를 통해 제공되고, scripting language는 그 기능을 프로그램 제어에 노출하는 메커니즘입니다. 이런 방식으로 기존 시스템은 scripting language의 기능을 완성하는 객체와 기능의 host environment를 제공한다고 말합니다. scripting language는 전문 프로그래머와 비전문 프로그래머 모두가 사용하도록 의도됩니다.

ECMAScript는 원래 Web scripting language가 되도록 설계되어, 브라우저에서 Web page에 생동감을 부여하고 Web 기반 client-server architecture의 일부로 server computation을 수행하는 메커니즘을 제공했습니다. ECMAScript는 이제 다양한 host environment에 core scripting capability를 제공하는 데 사용됩니다. 따라서 core language는 특정 host environment와 분리되어 이 문서에 명시됩니다.

ECMAScript 사용은 단순 scripting을 넘어섰으며, 이제 많은 서로 다른 환경과 규모에서 프로그래밍 작업의 전체 범위에 사용됩니다. ECMAScript 사용이 확장됨에 따라, ECMAScript가 제공하는 기능과 시설도 확장되었습니다. ECMAScript는 이제 충분한 기능을 갖춘 general-purpose programming language입니다.

4.1 Web Scripting

웹 브라우저는 client-side computation을 위한 ECMAScript host environment를 제공합니다. 여기에는 예를 들어 windows, menus, pop-ups, dialog boxes, text areas, anchors, frames, history, cookies, 그리고 input/output을 나타내는 객체가 포함됩니다. 또한 host environment는 focus 변경, page와 image loading, unloading, error와 abort, selection, form submission, mouse action과 같은 이벤트에 scripting code를 붙이는 수단을 제공합니다. Scripting code는 HTML 안에 나타나며, 표시되는 page는 user interface element와 고정 및 계산된 text와 image의 조합입니다. Scripting code는 user interaction에 반응하며, main program은 필요하지 않습니다.

웹 서버는 requests, clients, files를 나타내는 객체와 데이터를 잠그고 공유하는 메커니즘을 포함하여 server-side computation을 위한 다른 host environment를 제공합니다. browser-side와 server-side scripting을 함께 사용하면, Web 기반 애플리케이션에 사용자화된 user interface를 제공하면서 client와 server 사이에 computation을 분산할 수 있습니다.

ECMAScript를 지원하는 각 Web browser와 server는 자신만의 host environment를 제공하여 ECMAScript execution environment를 완성합니다.

4.2 Hosts와 Implementations

ECMAScript를 host environment에 통합하는 데 도움을 주기 위해, 이 명세는 특정 기능(예: abstract operations)의 정의를 전체 또는 일부에 대해 이 명세 외부의 source로 위임합니다. 편집상, 이 명세는 다음과 같은 종류의 위임을 구분합니다.

implementation은 Annex D에 열거된 기능 또는 implementation-definedimplementation-approximated로 표시된 기능을 추가로 정의하는 외부 source입니다. 비공식 사용에서 implementation은 특정 웹 브라우저와 같은 concrete artefact를 가리킵니다.

implementation-defined facility는 추가 한정 없이 그 정의를 외부 source로 위임하는 것입니다. 이 명세는 특정 동작에 대해 어떤 권고도 하지 않으며, conforming implementation은 이 명세가 제시한 제약 내에서 어떤 동작이든 자유롭게 선택할 수 있습니다.

implementation-approximated facility는 그 정의를 외부 source로 위임하면서 이상적인 동작을 권고하는 것입니다. conforming implementation은 이 명세가 제시한 제약 내에서 어떤 동작이든 자유롭게 선택할 수 있지만, 그 이상에 가깝게 근사하려고 노력하도록 권장됩니다. Math.exp와 같은 일부 mathematical operation은 implementation-approximated입니다.

host는 Annex D에 나열된 기능을 추가로 정의하지만, 다른 implementation-defined 또는 implementation-approximated facility는 추가로 정의하지 않는 외부 source입니다. 비공식 사용에서 host는 Annex D를 통해 같은 방식으로 이 명세와 interface하는 모든 implementation의 집합, 예를 들어 모든 웹 브라우저의 집합을 가리킵니다. host는 WHATWG HTML(https://html.spec.whatwg.org/)과 같은 외부 명세인 경우가 많습니다. 달리 말하면, host-defined인 facility는 종종 외부 명세에서 추가로 정의됩니다.

host hook은 전체 또는 일부가 외부 source에 의해 정의되는 abstract operation입니다. 모든 host hook은 Annex D에 나열되어야 합니다. host hook은 적어도 다음 요구사항을 준수해야 합니다:

host-defined facility는 추가 한정 없이 그 정의를 외부 source로 위임하며 Annex D에 나열되는 것입니다. host가 아닌 implementation도 host-defined facility에 대한 정의를 제공할 수 있습니다.

host environment는 모든 host-defined facility에 대한 특정 정의 선택입니다. host environment는 보통 global objecthost-defined property로서 input을 얻고 output을 제공할 수 있게 하는 객체나 함수를 포함합니다.

이 명세는 항상 가장 구체적인 용어를 사용하는 편집 관례를 따릅니다. 예를 들어 어떤 facility가 host-defined이면, implementation-defined라고 지칭해서는 안 됩니다.

hosts와 implementations는 모두 여기에 정의된 language type, specification type, abstract operation, grammar production, intrinsic object, intrinsic symbol을 통해 이 명세와 interface할 수 있습니다.

4.3 ECMAScript 개요

다음은 ECMAScript에 대한 비공식 개요입니다. 언어의 모든 부분이 설명되는 것은 아닙니다. 이 개요는 표준 본문 자체의 일부가 아닙니다.

ECMAScript는 object-based입니다. 기본 언어와 host facility는 object에 의해 제공되며, ECMAScript 프로그램은 서로 통신하는 object의 cluster입니다. ECMAScript에서 object는 각각의 property가 어떻게 사용될 수 있는지를 결정하는 attributes를 가진, 0개 이상의 properties의 collection입니다. 예를 들어 property의 Writable attribute가 false로 설정되면, 실행되는 ECMAScript code가 그 property에 다른 값을 할당하려는 모든 시도는 실패합니다. Properties는 다른 object, primitive values, 또는 functions를 담는 container입니다. primitive value는 다음 built-in type 중 하나의 member입니다: Undefined, Null, Boolean, Number, BigInt, String, 그리고 Symbol; object는 built-in type Object의 member입니다; 그리고 function은 callable object입니다. property를 통해 object와 연결된 function을 method라고 합니다.

ECMAScript는 ECMAScript entity의 정의를 완성하는 built-in objects의 collection을 정의합니다. 이러한 built-in object에는 global object; Object, Function, Boolean, Symbol, 그리고 다양한 Error object를 포함하여 언어의 runtime semantics에 근본적인 object; Math, Number, Date를 포함하여 numeric value를 나타내고 조작하는 object; text processing object인 StringRegExp; Array와, element가 모두 특정 numeric data representation을 갖는 아홉 가지 다른 종류의 Typed Array를 포함하여 value의 indexed collection인 object; MapSet object를 포함하는 keyed collection; JSON object, ArrayBuffer, SharedArrayBuffer, DataView를 포함하여 structured data를 지원하는 object; generator function과 Promise object를 포함하여 control abstraction을 지원하는 object; 그리고 ProxyReflect를 포함하는 reflection object가 포함됩니다.

ECMAScript는 또한 built-in operators의 집합을 정의합니다. ECMAScript operator에는 다양한 unary operation, multiplicative operator, additive operator, bitwise shift operator, relational operator, equality operator, binary bitwise operator, binary logical operator, assignment operator, 그리고 comma operator가 포함됩니다.

대규모 ECMAScript 프로그램은 modules에 의해 지원되며, module은 프로그램을 statements와 declarations의 여러 sequence로 나눌 수 있게 합니다. 각 module은 자신이 사용하며 다른 module이 제공해야 하는 declaration과, 다른 module이 사용할 수 있는 자신의 declaration을 명시적으로 식별합니다.

ECMAScript 구문은 의도적으로 Java 구문과 유사합니다. ECMAScript 구문은 사용하기 쉬운 scripting language로 기능할 수 있도록 완화되어 있습니다. 예를 들어 variable은 type을 선언할 필요가 없고, type은 property와 연결되어 있지 않으며, 정의된 function은 호출보다 텍스트상 앞에 declaration이 나타날 필요가 없습니다.

4.3.1 Objects

ECMAScript에는 class definition을 위한 구문이 포함되어 있지만, ECMAScript object는 C++, Smalltalk, Java의 object처럼 근본적으로 class-based가 아닙니다. 대신 object는 literal notation을 통해서나, object를 만들고 그 property에 initial value를 할당하여 그 전부 또는 일부를 초기화하는 code를 실행하는 constructors를 통해서 등 다양한 방식으로 생성될 수 있습니다. 각 constructor"prototype"이라는 이름의 property를 가진 function이며, 이 property는 prototype-based inheritanceshared properties를 구현하는 데 사용됩니다. Object는 new expression에서 constructor를 사용하여 생성됩니다. 예를 들어 new Date(2009, 11)은 새 Date object를 생성합니다. new를 사용하지 않고 constructor를 호출하는 것은 constructor에 따라 다른 결과를 가집니다. 예를 들어 Date()는 object가 아니라 현재 date와 time의 string representation을 생성합니다.

constructor에 의해 생성된 모든 object는 자신의 constructor"prototype" property 값에 대한 암시적 reference(object의 prototype이라고 함)를 가집니다. 또한 prototype은 자신의 prototype에 대한 non-null 암시적 reference를 가질 수 있으며, 이런 식으로 이어질 수 있습니다. 이를 prototype chain이라고 합니다. object의 property를 참조할 때, 그 reference는 해당 이름의 property를 포함하는 prototype chain의 첫 번째 object 안의 그 이름 property를 가리킵니다. 달리 말하면, 먼저 직접 언급된 object가 그러한 property를 갖는지 검사됩니다. 그 object가 named property를 포함하면, 그것이 reference가 가리키는 property입니다. 그 object가 named property를 포함하지 않으면, 그 object의 prototype이 다음으로 검사됩니다. 그리고 이런 식으로 계속됩니다.

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

class-based object-oriented language에서는 일반적으로 state는 instance가 보유하고, method는 class가 보유하며, inheritance는 structure와 behaviour에 대해서만 이루어집니다. ECMAScript에서는 state와 method가 object에 의해 보유되는 반면, structure, behaviour, state가 모두 inherited됩니다.

prototype이 포함하는 특정 property를 직접 포함하지 않는 모든 object는 그 property와 그 값을 공유합니다. Figure 1은 이를 보여줍니다:

CFconstructor이며 object이기도 합니다. new expression을 사용하여 다섯 개의 object가 생성되었습니다: cf1, cf2, cf3, cf4, 그리고 cf5. 이 object들은 각각 "q1""q2"라는 이름의 property를 포함합니다. 점선은 암시적 prototype 관계를 나타냅니다. 따라서 예를 들어 cf3의 prototype은 CFp입니다. constructorCF는 그 자체로 "P1""P2"라는 두 property를 가지며, 이들은 CFp, cf1, cf2, cf3, cf4, 또는 cf5에는 보이지 않습니다. CFp"CFP1"이라는 이름의 property는 cf1, cf2, cf3, cf4, 그리고 cf5가 공유합니다(CF와는 공유하지 않음). CFp의 암시적 prototype chain에서 발견되는 property 중 "q1", "q2", 또는 "CFP1"이라는 이름이 아닌 모든 property도 마찬가지입니다. CFCFp 사이에는 암시적 prototype link가 없다는 점에 유의하십시오.

대부분의 class-based object language와 달리, property는 값 할당을 통해 object에 동적으로 추가될 수 있습니다. 즉 constructor는 constructed object의 property 전부 또는 일부의 이름을 정하거나 값을 할당할 필요가 없습니다. 위 그림에서 CFp의 property에 새 값을 할당함으로써 cf1, cf2, cf3, cf4, 그리고 cf5를 위한 새로운 shared property를 추가할 수 있습니다.

ECMAScript object가 본질적으로 class-based는 아니지만, constructor function, prototype object, method의 공통 pattern에 기반하여 class-like abstraction을 정의하는 것이 편리한 경우가 많습니다. ECMAScript built-in object 자체도 그러한 class-like pattern을 따릅니다. ECMAScript 2015부터 ECMAScript language에는 built-in object가 사용하는 동일한 class-like abstraction pattern을 따르는 object를 프로그래머가 간결하게 정의할 수 있게 하는 syntactic class definition이 포함됩니다.

4.3.2 ECMAScript의 Strict Variant

ECMAScript 언어는 언어에서 사용할 수 있는 일부 기능의 사용을 제한하고자 하는 사용자가 있을 수 있음을 인정합니다. 그들은 security를 위해, 오류가 발생하기 쉽다고 여기는 기능을 피하기 위해, 향상된 error checking을 얻기 위해, 또는 자신이 선택한 다른 이유로 그렇게 할 수 있습니다. 이 가능성을 지원하기 위해 ECMAScript는 언어의 strict variant를 정의합니다. 언어의 strict variant는 일반 ECMAScript 언어의 특정 syntactic 및 semantic feature를 제외하고, 일부 기능의 자세한 semantics를 수정합니다. strict variant는 또한 언어의 non-strict form에서 오류로 명시되지 않은 상황에서 error exception을 throw하여 보고해야 하는 추가 error condition을 명시합니다.

ECMAScript의 strict variant는 일반적으로 언어의 strict mode라고 불립니다. strict mode 선택과 ECMAScript의 strict mode syntax 및 semantics 사용은 11.2.2에 설명된 대로 개별 ECMAScript source text unit 수준에서 명시적으로 이루어집니다. strict mode는 syntactic source text unit 수준에서 선택되므로, strict mode는 그러한 source text unit 안에서 local effect를 갖는 제한만 부과합니다. strict mode는 여러 source text unit에 걸쳐 일관되게 동작해야 하는 ECMAScript semantics의 어떤 측면도 제한하거나 수정하지 않습니다. 완전한 ECMAScript 프로그램은 strict mode와 non-strict mode ECMAScript source text unit 둘 다로 구성될 수 있습니다. 이 경우 strict mode는 strict mode source text unit 안에 정의된 code를 실제로 실행할 때만 적용됩니다.

이 명세에 부합하기 위해, ECMAScript implementation은 이 명세에서 정의한 full unrestricted ECMAScript language와 ECMAScript language의 strict variant를 모두 구현해야 합니다. 또한 implementation은 unrestricted와 strict mode source text unit을 하나의 composite program으로 결합하는 것을 지원해야 합니다.

4.4 용어와 정의

이 문서의 목적상, 다음 용어와 정의가 적용됩니다.

4.4.1 implementation-approximated

implementation-approximated facility는 전체 또는 일부가 외부 source에 의해 정의되지만, 이 명세에서 권장되는 이상적인 behaviour를 가집니다

4.4.2 implementation-defined

implementation-defined facility는 전체 또는 일부가 이 명세 외부의 source에 의해 정의됩니다

4.4.3 host-defined

implementation-defined와 동일합니다

Note

편집상, 절 4.2를 참조하십시오.

4.4.4 type

6에 정의된 data value의 집합

4.4.5 primitive value

6에 정의된 Undefined, Null, Boolean, Number, BigInt, Symbol, 또는 String type 중 하나의 member

Note

primitive value는 language implementation의 가장 낮은 수준에서 직접 표현되는 datum입니다.

4.4.6 object

Object type의 member

Note

object는 property의 collection이며 하나의 prototype object를 가집니다. prototype은 null일 수 있습니다.

4.4.7 constructor

object를 생성하고 초기화하는 function object

Note

constructor"prototype" property 값은 inheritance와 shared property를 구현하는 데 사용되는 prototype object입니다.

4.4.8 prototype

다른 object에 shared property를 제공하는 object

Note

constructor가 object를 생성할 때, 그 object는 property reference를 resolve하기 위해 constructor"prototype" property를 암시적으로 참조합니다. constructor"prototype" property는 프로그램 expression constructor.prototype으로 참조될 수 있으며, object의 prototype에 추가된 property는 inheritance를 통해 그 prototype을 공유하는 모든 object가 공유합니다. 또는 Object.create built-in function을 사용하여 명시적으로 지정된 prototype을 가진 새 object를 생성할 수 있습니다.

4.4.9 ordinary object

모든 object가 지원해야 하는 essential internal method에 대한 default behaviour를 가진 object

4.4.10 exotic object

하나 이상의 essential internal method에 대해 default behaviour를 갖지 않는 object

Note

ordinary object가 아닌 모든 object는 exotic object입니다.

4.4.11 standard object

semantics가 이 명세에 의해 정의되는 object

4.4.12 built-in object

ECMAScript implementation에 의해 명시되고 제공되는 object

Note

standard built-in object는 이 명세에서 정의됩니다. ECMAScript implementation은 추가 종류의 built-in object를 명시하고 제공할 수 있습니다.

4.4.13 undefined value

variable에 값이 할당되지 않았을 때 사용되는 primitive value

4.4.14 Undefined type

sole value가 undefined value인 type

4.4.15 null value

어떤 object value의 의도적인 부재를 나타내는 primitive value

4.4.16 Null type

sole value가 null value인 type

4.4.17 Boolean value

Boolean type의 member

Note

Boolean value는 truefalse 두 개뿐입니다.

4.4.18 Boolean type

primitive value truefalse로 구성된 type

4.4.19 Boolean object

standard built-in Boolean constructor의 instance인 Object type의 member

Note

Boolean object는 Boolean constructornew expression에서 사용하고 Boolean value를 argument로 제공하여 생성됩니다. 결과 object는 그 값이 Boolean value인 internal slot을 가집니다. Boolean object는 Boolean value로 coerced될 수 있습니다.

4.4.20 String value

0개 이상의 16-bit unsigned integer value의 finite ordered sequence인 primitive value

Note

String value는 String type의 member입니다. sequence 안의 각 integer value는 보통 UTF-16 text의 단일 16-bit unit을 나타냅니다. 그러나 ECMAScript는 값이 16-bit unsigned integer여야 한다는 것 외에는 그 값에 어떤 제한이나 요구사항도 두지 않습니다.

4.4.21 String type

가능한 모든 String value의 집합

4.4.22 String object

standard built-in String constructor의 instance인 Object type의 member

Note

String object는 String constructornew expression에서 사용하고 String value를 argument로 제공하여 생성됩니다. 결과 object는 그 값이 String value인 internal slot을 가집니다. String object는 String constructor를 function으로 호출함으로써 String value로 coerced될 수 있습니다(22.1.1.1).

4.4.23 Number value

double-precision 64-bit binary format IEEE 754-2019 value에 대응하는 primitive value

Note

Number value는 Number type의 member이며 number의 direct representation입니다.

4.4.24 Number type

NaN(“not a number”), +∞𝔽(positive infinity), 그리고 -∞𝔽(negative infinity)를 포함하는 가능한 모든 Number value의 집합

4.4.25 Number object

standard built-in Number constructor의 instance인 Object type의 member

Note

Number object는 Number constructornew expression에서 사용하고 Number value를 argument로 제공하여 생성됩니다. 결과 object는 그 값이 Number value인 internal slot을 가집니다. Number object는 Number constructor를 function으로 호출함으로써 Number value로 coerced될 수 있습니다(21.1.1.1).

4.4.26 Infinity

positive infinite Number value인 Number value

4.4.27 NaN

IEEE 754-2019 NaN(“not a number”) value인 Number value

4.4.28 BigInt value

arbitrary-precision integer value에 대응하는 primitive value

4.4.29 BigInt type

가능한 모든 BigInt value의 집합

4.4.30 BigInt object

standard built-in BigInt constructor의 instance인 Object type의 member

4.4.31 Symbol value

unique하고 non-String인 Object property key를 나타내는 primitive value

4.4.32 Symbol type

가능한 모든 Symbol value의 집합

4.4.33 Symbol object

standard built-in Symbol constructor의 instance인 Object type의 member

4.4.34 function

subroutine으로 invoked될 수 있는 Object type의 member

Note

function은 자신의 property 외에도 invoked될 때 어떻게 동작하는지를 결정하는 executable code와 state를 포함합니다. function의 code는 ECMAScript로 작성될 수도 있고 아닐 수도 있습니다.

4.4.35 built-in function

function인 built-in object

Note

built-in function의 예에는 parseIntMath.exp가 포함됩니다. host 또는 implementation은 이 명세에 설명되지 않은 추가 built-in function을 제공할 수 있습니다.

4.4.36 built-in constructor

constructor인 built-in function

Note

built-in constructor의 예에는 ObjectFunction이 포함됩니다. host 또는 implementation은 이 명세에 설명되지 않은 추가 built-in constructor를 제공할 수 있습니다.

4.4.37 property

key(String value 또는 Symbol value)와 value를 연결하는 object의 일부

Note

property의 형식에 따라 value는 data value(primitive value, object, 또는 function object)로 직접 표현되거나 accessor function의 pair로 간접적으로 표현될 수 있습니다.

4.4.38 method

property의 value인 function

Note

function이 object의 method로 호출될 때, object는 그 function에 this value로 전달됩니다.

4.4.39 built-in method

built-in function인 method

Note

standard built-in method는 이 명세에서 정의됩니다. host 또는 implementation은 이 명세에 설명되지 않은 추가 built-in method를 제공할 수 있습니다.

4.4.40 attribute

property의 어떤 characteristic을 정의하는 internal value

4.4.41 own property

그 object에 직접 포함된 property

4.4.42 inherited property

own property는 아니지만 object의 prototype의 property(own 또는 inherited)인 object의 property

4.5 이 명세의 구성

이 명세의 나머지는 다음과 같이 구성됩니다:

Clause 5는 명세 전체에서 사용되는 notational convention을 정의합니다.

Clauses 6 through 10는 ECMAScript 프로그램이 동작하는 execution environment를 정의합니다.

Clauses 11 through 17는 syntactic encoding과 모든 language feature의 execution semantics를 포함하여 실제 ECMAScript programming language를 정의합니다.

Clauses 18 through 28는 ECMAScript standard library를 정의합니다. 여기에는 ECMAScript 프로그램이 실행될 때 사용할 수 있는 모든 standard object의 정의가 포함됩니다.

Clause 29는 SharedArrayBuffer-backed memory에 대한 access와 Atomics object의 method의 memory consistency model을 설명합니다.

5 표기 관례

5.1 Syntactic and Lexical Grammars

5.1.1 Context-Free Grammars

context-free grammar는 여러 production으로 구성됩니다. 각 production은 left-hand side로서 nonterminal이라고 하는 abstract symbol을 가지며, right-hand side로서 0개 이상의 nonterminal 및 terminal symbol의 sequence를 가집니다. 각 grammar에 대해 terminal symbol은 지정된 alphabet에서 가져옵니다.

chain production은 right-hand side에 정확히 하나의 nonterminal symbol과 0개 이상의 terminal symbol을 가진 production입니다.

goal symbol이라고 하는 하나의 distinguished nonterminal로 이루어진 sentence에서 시작하여, 주어진 context-free grammar는 하나의 language, 즉 sequence 안의 nonterminal을 그 nonterminal이 left-hand side인 production의 right-hand side로 반복해서 대체함으로써 얻을 수 있는 가능한 terminal symbol sequence의 (아마도 무한한) 집합을 명시합니다.

5.1.2 Lexical 및 RegExp Grammars

ECMAScript의 lexical grammar는 clause 12에 제시됩니다. 이 grammar는 11.1에 정의된 SourceCharacter 규칙을 따르는 Unicode code point를 terminal symbol로 가집니다. 이는 goal symbol InputElementDiv, InputElementTemplateTail, InputElementRegExp, InputElementRegExpOrTemplateTail, 또는 InputElementHashbangOrRegExp에서 시작하여, 그러한 code point의 sequence가 input element의 sequence로 어떻게 변환되는지를 설명하는 production의 집합을 정의합니다.

white space와 comment 이외의 input element는 ECMAScript의 syntactic grammar를 위한 terminal symbol을 형성하며 ECMAScript tokens라고 불립니다. 이러한 token은 ECMAScript 언어의 reserved word, identifier, literal, punctuator입니다. 또한 line terminator는 token으로 간주되지는 않지만 input element의 stream의 일부가 되어 automatic semicolon insertion 과정(12.10)을 안내합니다. 단순 white space와 single-line comment는 버려지며 syntactic grammar를 위한 input element의 stream에 나타나지 않습니다. MultiLineComment(즉, 여러 줄에 걸치는지와 관계없이 /**/ 형식의 comment)도 line terminator를 포함하지 않으면 마찬가지로 단순히 버려집니다. 그러나 MultiLineComment가 하나 이상의 line terminator를 포함하면, 이는 하나의 line terminator로 대체되어 syntactic grammar를 위한 input element의 stream의 일부가 됩니다.

ECMAScript의 RegExp grammar22.2.1에 제시됩니다. 이 grammar도 SourceCharacter로 정의된 code point를 terminal symbol로 가집니다. 이는 goal symbol Pattern에서 시작하여 code point의 sequence가 regular expression pattern으로 어떻게 변환되는지를 설명하는 production의 집합을 정의합니다.

lexical 및 RegExp grammar의 production은 분리 punctuation으로 두 개의 colon “::”을 가진다는 점으로 구분됩니다. lexical 및 RegExp grammar는 일부 production을 공유합니다.

5.1.3 Numeric String Grammar

numeric string grammar7.1.4.1에 나타납니다. 이는 SourceCharacter를 terminal symbol로 가지며, goal symbol StringNumericLiteral에서 시작하여 String을 numeric value로 변환하는 데 사용됩니다(이는 numeric literal을 위한 lexical grammar와 유사하지만 구별됩니다).

numeric string grammar의 production은 punctuation으로 세 개의 colon “:::”을 가진다는 점으로 구분되며, source text를 parsing하는 데 사용되지 않습니다.

5.1.4 Syntactic Grammar

ECMAScript의 syntactic grammar는 clauses 13 through 16에 제시됩니다. 이 grammar는 lexical grammar에 의해 정의된 ECMAScript token을 terminal symbol로 가집니다(5.1.2). 이는 두 alternative goal symbol ScriptModule에서 시작하여, token의 sequence가 ECMAScript 프로그램의 syntactically correct independent component를 어떻게 형성하는지를 설명하는 production의 집합을 정의합니다.

code point의 stream을 ECMAScript Script 또는 Module로 parsing하려면, 먼저 lexical grammar의 반복 적용에 의해 input element의 stream으로 변환됩니다. 그런 다음 이 input element의 stream은 syntactic grammar를 한 번 적용하여 parsed됩니다. input element의 stream 안의 token이 goal nonterminal(Script 또는 Module)의 단일 instance로, token을 남기지 않고 parsed될 수 없으면 input stream은 syntactically in error입니다.

parse가 성공하면, root가 있는 tree structure인 parse tree를 구성하며, 이 tree의 각 node는 Parse Node입니다. 각 Parse Node는 grammar 안의 symbol의 instance입니다. 이는 그 symbol로부터 derivable한 source text의 span을 나타냅니다. parse tree의 root node는 source text 전체를 나타내며 parse의 goal symbol의 instance입니다. Parse Node가 nonterminal의 instance일 때, 이는 또한 그 nonterminal을 left-hand side로 갖는 어떤 production의 instance입니다. 또한 이는 0개 이상의 children을 가지며, production의 right-hand side에 있는 각 symbol마다 하나씩 존재합니다. 각 child는 해당 symbol의 instance인 Parse Node입니다.

New Parse Node는 parser의 각 invocation마다 instantiated되며, 동일한 source text의 parse 사이에서도 결코 재사용되지 않습니다. Parse Node는 같은 source text span을 나타내고, 같은 grammar symbol의 instance이며, 같은 parser invocation에서 나온 경우에만 the same Parse Node로 간주됩니다.

Note 1

같은 String을 여러 번 parsing하면 서로 다른 Parse Node가 생성됩니다. 예를 들어 다음을 고려하십시오:

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

eval 호출 각각은 str의 값을 ECMAScript source text로 변환하고, 독립적인 parse를 수행하여 자신만의 별도 Parse Node tree를 생성합니다. 각 parse가 같은 String value에서 derived된 source text에 대해 동작하더라도 tree들은 distinct합니다.

Note 2
Parse Node는 specification artefact이며, implementation은 유사한 data structure를 사용할 필요가 없습니다.

syntactic grammar의 production은 punctuation으로 단 하나의 colon “:”을 가진다는 점으로 구분됩니다.

clauses 13 through 16에 제시된 syntactic grammar는 어떤 token sequence가 올바른 ECMAScript Script 또는 Module로 받아들여지는지에 대한 완전한 설명이 아닙니다. 특정 위치(예: line terminator character 앞)에 semicolon을 추가하기만 하면 grammar가 설명할 수 있는 token sequence도 추가로 허용됩니다. 또한 grammar에 의해 설명되는 특정 token sequence라도 line terminator character가 특정 “awkward” 위치에 나타나면 허용 가능한 것으로 간주되지 않습니다.

어떤 경우에는 ambiguity를 피하기 위해 syntactic grammar가 유효한 ECMAScript Script 또는 Module을 형성하지 않는 token sequence를 허용하는 generalized production을 사용합니다. 예를 들어 이 기법은 object literal과 object destructuring pattern에 사용됩니다. 그런 경우 허용 가능한 token sequence를 더 제한하는 보다 제한적인 supplemental grammar가 제공됩니다. 일반적으로 early error rule은 특정 context에서 “p must cover an n”이라고 명시하며, 여기서 p는 Parse Node(generalized production의 instance)이고 n은 supplemental grammar의 nonterminal입니다. 이는 다음을 의미합니다:

  1. 원래 p에 의해 match된 token sequence는 ngoal symbol로 사용하여 다시 parsed됩니다. n이 grammatical parameter를 취하면, 이는 p가 원래 parsed될 때 사용된 값과 같은 값으로 설정됩니다.
  2. token sequence가 token을 남기지 않고 n의 단일 instance로 parsed될 수 있으면, 다음과 같습니다:
    1. n의 instance(주어진 p에 대해 unique한 Parse Node)를 “p에 의해 covered되는 n”이라고 부릅니다.
    2. n과 그 derived production에 대한 모든 Early Error rule도 p에 의해 covered되는 n에 적용됩니다.
  3. 그렇지 않으면(parse가 실패하면) early Syntax Error입니다.

5.1.5 Grammar Notation

5.1.5.1 Terminal Symbols

ECMAScript grammar에서 일부 terminal symbol은 fixed-width font로 표시됩니다. 이들은 source text에 쓰인 그대로 나타나야 합니다. 이런 방식으로 명시된 모든 terminal symbol code point는 다른 Unicode range의 비슷하게 보이는 code point가 아니라 Basic Latin block의 적절한 Unicode code point로 이해되어야 합니다. terminal symbol 안의 code point는 \ UnicodeEscapeSequence로 표현될 수 없습니다.

terminal symbol이 개별 Unicode code point인 grammar(즉 lexical, RegExp, numeric string grammar)에서 production에 나타나는 여러 fixed-width code point의 contiguous run은 standalone terminal symbol로 쓰인 같은 code point sequence에 대한 단순한 shorthand입니다.

예를 들어 production:

HexIntegerLiteral :: 0x HexDigits

은 다음에 대한 shorthand입니다:

HexIntegerLiteral :: 0 x HexDigits

반대로 syntactic grammar에서는 fixed-width code point의 contiguous run이 하나의 terminal symbol입니다.

Terminal symbol은 두 가지 다른 형식으로도 나타납니다:

  • lexical 및 RegExp grammar에서 관례적인 인쇄 표현이 없는 Unicode code point는 대신 “<ABBREV>” 형식으로 표시되며, 여기서 “ABBREV”는 code point 또는 code point 집합에 대한 mnemonic입니다. 이러한 형식은 Unicode Format-Control Characters, White Space, 그리고 Line Terminators에 정의됩니다.
  • syntactic grammar에서 특정 terminal symbol(예: IdentifierNameRegularExpressionLiteral)은 italic으로 표시되며, 이는 lexical grammar의 같은 이름의 nonterminal을 참조하기 때문입니다.

5.1.5.2 Nonterminal Symbols and Productions

Nonterminal symbol은 italic type으로 표시됩니다. nonterminal의 정의(“production”이라고도 함)는 정의되는 nonterminal의 name과 그 뒤에 오는 하나 이상의 colon으로 시작됩니다. (colon의 수는 production이 어떤 grammar에 속하는지를 나타냅니다.) 그런 다음 nonterminal에 대한 하나 이상의 alternative right-hand side가 다음 줄들에 이어집니다. 예를 들어 syntactic definition:

WhileStatement : while ( Expression ) Statement

은 nonterminal WhileStatement가 token while, 그 뒤의 left parenthesis token, 그 뒤의 Expression, 그 뒤의 right parenthesis token, 그 뒤의 Statement를 나타낸다고 명시합니다. ExpressionStatement의 occurrence는 그 자체로 nonterminal입니다. 또 다른 예로, syntactic definition:

ArgumentList : AssignmentExpression ArgumentList , AssignmentExpression

ArgumentList가 하나의 AssignmentExpression을 나타내거나, ArgumentList 뒤에 comma가 오고 그 뒤에 AssignmentExpression이 오는 것을 나타낼 수 있다고 명시합니다. ArgumentList의 이 정의는 recursive합니다. 즉 자신을 기준으로 정의됩니다. 그 결과 ArgumentList는 comma로 구분된 임의의 양수 개수의 argument를 포함할 수 있으며, 각 argument expression은 AssignmentExpression입니다. 이러한 nonterminal의 recursive definition은 흔합니다.

5.1.5.3 Optional Symbols

terminal 또는 nonterminal 뒤에 나타날 수 있는 subscripted suffix “opt”는 optional symbol을 나타냅니다. optional symbol을 포함하는 alternative는 실제로 optional element를 생략한 것과 포함한 것, 두 right-hand side를 명시합니다. 이는 다음을 의미합니다:

VariableDeclaration : BindingIdentifier Initializeropt

은 다음에 대한 편리한 abbreviation입니다:

VariableDeclaration : BindingIdentifier BindingIdentifier Initializer

그리고 다음도:

ForStatement : for ( LexicalDeclaration Expressionopt ; Expressionopt ) Statement

다음에 대한 편리한 abbreviation입니다:

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

이는 다시 다음에 대한 abbreviation입니다:

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

따라서 이 예에서 nonterminal ForStatement는 실제로 네 개의 alternative right-hand side를 가집니다.

5.1.5.4 Grammatical Parameters

production은 정의되는 production의 nonterminal symbol에 suffix로 나타날 수 있는 “[parameters]” 형식의 subscripted annotation으로 parameterized될 수 있습니다. “parameters”는 하나의 name이거나 comma로 구분된 name의 list일 수 있습니다. parameterized production은 parameterized nonterminal symbol에 underscore를 앞에 붙인 parameter name의 모든 조합을 덧붙여 정의하는 production 집합에 대한 shorthand입니다. 이는 다음을 의미합니다:

StatementList[Return] : ReturnStatement ExpressionStatement

은 다음에 대한 편리한 abbreviation입니다:

StatementList : ReturnStatement ExpressionStatement StatementList_Return : ReturnStatement ExpressionStatement

그리고 다음도:

StatementList[Return, In] : ReturnStatement ExpressionStatement

다음에 대한 abbreviation입니다:

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

여러 parameter는 combinatoric number의 production을 생성하며, 그 모두가 완전한 grammar에서 반드시 참조되는 것은 아닙니다.

production의 right-hand side에 있는 nonterminal reference도 parameterized될 수 있습니다. 예를 들어:

StatementList : ReturnStatement ExpressionStatement[+In]

은 다음과 말하는 것과 equivalent합니다:

StatementList : ReturnStatement ExpressionStatement_In

그리고:

StatementList : ReturnStatement ExpressionStatement[~In]

은 다음과 equivalent합니다:

StatementList : ReturnStatement ExpressionStatement

nonterminal reference는 parameter list와 “opt” suffix를 모두 가질 수 있습니다. 예를 들어:

VariableDeclaration : BindingIdentifier Initializer[+In]opt

은 다음에 대한 abbreviation입니다:

VariableDeclaration : BindingIdentifier BindingIdentifier Initializer_In

right-hand side nonterminal reference에서 parameter name 앞에 “?”를 붙이면, 그 parameter value는 현재 production의 left-hand side symbol에 대한 reference에서 parameter name이 occurrence하는지에 따라 달라집니다. 예를 들어:

VariableDeclaration[In] : BindingIdentifier Initializer[?In]

은 다음에 대한 abbreviation입니다:

VariableDeclaration : BindingIdentifier Initializer VariableDeclaration_In : BindingIdentifier Initializer_In

right-hand side alternative 앞에 “[+parameter]”가 붙으면, 그 alternative는 production의 nonterminal symbol을 참조할 때 named parameter가 사용된 경우에만 available합니다. right-hand side alternative 앞에 “[~parameter]”가 붙으면, 그 alternative는 production의 nonterminal symbol을 참조할 때 named parameter가 사용되지 않은 경우에만 available합니다. 이는 다음을 의미합니다:

StatementList[Return] : [+Return] ReturnStatement ExpressionStatement

은 다음에 대한 abbreviation입니다:

StatementList : ExpressionStatement StatementList_Return : ReturnStatement ExpressionStatement

그리고 다음도:

StatementList[Return] : [~Return] ReturnStatement ExpressionStatement

다음에 대한 abbreviation입니다:

StatementList : ReturnStatement ExpressionStatement StatementList_Return : ExpressionStatement

5.1.5.5 one of

grammar definition에서 colon(s) 뒤에 “one of”라는 단어가 오면, 이는 다음 line 또는 lines의 각 terminal symbol이 alternative definition임을 의미합니다. 예를 들어 ECMAScript의 lexical grammar에는 다음 production이 포함됩니다:

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

이는 단지 다음에 대한 편리한 abbreviation입니다:

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

5.1.5.6 [empty]

production의 right-hand side에 “[empty]”라는 phrase가 나타나면, 이는 그 production의 right-hand side가 terminal이나 nonterminal을 포함하지 않음을 나타냅니다.

5.1.5.7 Lookahead Restrictions

production의 right-hand side에 “[lookahead = seq]”라는 phrase가 나타나면, 이는 immediately following input token sequence의 prefix가 token sequence seq인 경우에만 그 production을 사용할 수 있음을 나타냅니다. 마찬가지로 “[lookahead ∈ set]”에서 set이 token sequence의 finite non-empty set이면, immediately following token sequence의 prefix가 set의 어떤 element인 경우에만 그 production을 사용할 수 있음을 나타냅니다. 편의를 위해 set은 nonterminal로도 쓸 수 있으며, 이 경우 그 nonterminal이 expand될 수 있는 모든 token sequence의 집합을 나타냅니다. nonterminal이 무한히 많은 distinct token sequence로 expand될 수 있으면 이는 editorial error로 간주됩니다.

이러한 condition은 negated될 수 있습니다. “[lookahead ≠ seq]”는 containing production이 seq가 immediately following input token sequence의 prefix가 아닌 경우에만 사용될 수 있음을 나타내며, “[lookahead ∉ set]”는 immediately following token sequence의 prefix가 set어떤 element도 아닌 경우에만 production을 사용할 수 있음을 나타냅니다.

예를 들어 다음 정의가 주어졌을 때:

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]

letter n 뒤에 하나 이상의 decimal digit가 오며 그 첫 번째가 even인 경우, 또는 다른 decimal digit가 뒤따르지 않는 decimal digit 중 하나와 match합니다.

이 phrase들이 syntactic grammar에서 사용될 때는, 이후 token을 결정하려면 이후 위치에서 어떤 lexical goal symbol을 사용할지 알아야 하기 때문에 immediately following token sequence를 unambiguously identify할 수 없을 수도 있습니다. 따라서 syntactic grammar에서 이것들이 사용될 때, lexical goal symbol 선택이 resulting token sequence의 prefix가 seq인지 여부를 바꿀 수 있다면 token sequence seq가 lookahead restriction에(시퀀스 집합의 일부로 포함되는 경우도 포함) 나타나는 것은 editorial error로 간주됩니다.

5.1.5.8 [no LineTerminator here]

syntactic grammar의 production의 right-hand side에 “[no LineTerminator here]”라는 phrase가 나타나면, 이는 그 production이 restricted production임을 나타냅니다. 즉 indicated position의 input stream에 LineTerminator가 occurrence하면 사용할 수 없습니다. 예를 들어 production:

ThrowStatement : throw [no LineTerminator here] Expression ;

은 script에서 throw token과 Expression 사이에 LineTerminator가 occurrence하면 그 production을 사용할 수 없음을 나타냅니다.

LineTerminator의 존재가 restricted production에 의해 forbidden되지 않는 한, LineTerminator는 input element의 stream에서 연속된 두 token 사이에 임의의 횟수로 나타날 수 있으며 script의 syntactic acceptability에 영향을 주지 않습니다.

5.1.5.9 but not

production의 right-hand side는 “but not”이라는 phrase를 사용한 다음 excluded될 expansion을 표시하여 특정 expansion이 허용되지 않음을 명시할 수 있습니다. 예를 들어 production:

Identifier :: IdentifierName but not ReservedWord

은 nonterminal IdentifierIdentifierName을 replace할 수 있는 어떤 code point sequence로도 replace될 수 있되, 같은 code point sequence가 ReservedWord를 replace할 수 없는 경우에 한한다는 의미입니다.

5.1.5.10 Descriptive Phrases

마지막으로, 모든 alternative를 나열하는 것이 비실용적인 경우에는 몇몇 nonterminal symbol이 sans-serif type의 descriptive phrase로 설명됩니다:

SourceCharacter :: any Unicode code point

5.2 Algorithm Conventions

이 명세는 algorithm의 step을 명시하기 위해 numbered list를 자주 사용합니다. 이러한 algorithm은 ECMAScript language construct의 요구되는 semantics를 정밀하게 명시하는 데 사용됩니다. algorithm은 특정 implementation technique의 사용을 함의하도록 의도되지 않습니다. 실제로 주어진 feature를 구현하는 데 더 효율적인 algorithm이 있을 수 있습니다.

algorithm은 algorithm step 안에서 해당 위치에 전달된 argument를 참조하는 데 사용할 수 있는 alias name의 ordered, comma-separated sequence로 명시적으로 parameterized될 수 있습니다. optional parameter는 surrounding brackets([ , name ])로 표시되며 algorithm step 안에서는 required parameter와 다르지 않습니다. rest parameter는 parameter list의 끝에 나타날 수 있으며, leading ellipsis(, ...name)로 표시됩니다. rest parameter는 required 및 optional parameter 뒤에 제공된 모든 argument를 List로 capture합니다. 그러한 additional argument가 없으면 그 List는 empty입니다.

algorithm step은 sequential substep으로 세분될 수 있습니다. substep은 indented되며 그 자체가 다시 indented substep으로 더 나뉠 수 있습니다. outline numbering convention은 substep을 식별하는 데 사용되며, 첫 번째 수준의 substep은 lowercase alphabetic character로, 두 번째 수준의 substep은 lowercase roman numeral로 labelled됩니다. 세 수준보다 더 많은 수준이 필요하면 이 규칙이 반복되며 네 번째 수준은 numeric label을 사용합니다. 예를 들어:

  1. Top-level step
    1. Substep.
    2. Substep.
      1. Subsubstep.
        1. Subsubsubstep
          1. Subsubsubsubstep
            1. Subsubsubsubsubstep

step 또는 substep은 그 substep을 condition하는 “if” predicate로 작성될 수 있습니다. 이 경우 substep은 predicate가 true일 때만 적용됩니다. step 또는 substep이 “else”라는 단어로 시작하면, 이는 같은 level의 preceding “if” predicate step의 negation인 predicate입니다.

step은 그 substep의 iterative application을 명시하기 위해 “For each” 또는 “Repeat”로 시작할 수 있습니다.

Assert:”로 시작하는 step은 algorithm의 invariant condition을 assertion합니다. 이러한 assertion은 그렇지 않으면 암시적일 algorithmic invariant를 명시적으로 만들기 위해 사용됩니다. 마찬가지로 “NOTE:”로 시작하는 step은 nearby step에 관련된 context를 제공합니다. Assertion step과 note step은 strictly informative입니다. 이는 추가 semantic requirement를 더하지 않으므로 implementation이 check할 필요가 없습니다.

algorithm step은 “Let x be someValue” 형식을 사용하여 어떤 value에 대해서도 named alias를 선언할 수 있습니다. 이러한 alias는 xsomeValue 모두 같은 underlying data를 참조하고 어느 쪽에 대한 modification도 양쪽에 보인다는 점에서 reference-like입니다. 이 reference-like behaviour를 피하고자 하는 algorithm step은 right-hand side의 copy를 명시적으로 만들어야 합니다. “Let x be a copy of someValue”는 someValue의 shallow copy를 만듭니다.

일단 선언되면, alias는 이후의 어떤 step에서도 참조될 수 있으며 alias의 declaration 이전 step에서 참조되어서는 안 됩니다. alias는 “Set x to someOtherValue” 형식을 사용하여 수정될 수 있습니다.

5.2.1 Evaluation Order

complex expression이 algorithm step에 나타날 때, 이는 left-to-right, inside-to-outside order로 evaluated되는 것으로 이해해야 합니다. 예를 들어 step

  1. Return A(B(), C.[[D]]) + E(F()).

은 다음과 equivalent합니다

  1. Let tmp1 be B().
  2. Let tmp2 be C.[[D]].
  3. Let tmp3 be A(tmp1, tmp2).
  4. Let tmp4 be F().
  5. Let tmp5 be E(tmp4).
  6. Let tmp6 be tmp3 + tmp5.
  7. Return tmp6.

여기서 여러 tmpN alias는 ephemeral하며 이 step들 안에서만 visible합니다.

5.2.2 Abstract Operations

이 명세의 여러 부분에서 사용하기 쉽도록, abstract operations라고 하는 일부 algorithm은 이름을 가지며 parameterized functional form으로 작성되어 다른 algorithm 안에서 이름으로 참조될 수 있습니다. abstract operation은 보통 OperationName(arg1, arg2)와 같은 functional application style을 사용하여 참조됩니다. 일부 abstract operation은 class-like specification abstraction의 polymorphically dispatched method로 취급됩니다. 그러한 method-like abstract operation은 보통 someValue.OperationName(arg1, arg2)와 같은 method application style을 사용하여 참조됩니다.

5.2.3 Syntax-Directed Operations

syntax-directed operation은 named operation이며, 그 정의는 algorithm들로 구성되고, 각 algorithm은 ECMAScript grammar 중 하나의 하나 이상의 production과 associated됩니다. 여러 alternative definition을 가진 production은 보통 각 alternative마다 distinct algorithm을 가집니다. algorithm이 grammar production과 associated될 때, 이는 production alternative의 terminal 및 nonterminal symbol을 algorithm의 parameter인 것처럼 참조할 수 있습니다. 이런 방식으로 사용될 때 nonterminal symbol은 source text를 parsing할 때 match되는 실제 alternative definition을 참조합니다. grammar production 또는 그로부터 derived된 Parse Nodematched by한 source text는 match에 참여한 첫 번째 terminal의 시작에서 시작하여 match에 참여한 마지막 terminal의 끝에서 끝나는 source text 부분입니다.

algorithm이 production alternative와 associated될 때, alternative는 보통 “[ ]” grammar annotation 없이 표시됩니다. 그러한 annotation은 alternative의 syntactic recognition에만 영향을 주어야 하며 alternative에 associated된 semantics에는 영향을 주지 않아야 합니다.

Syntax-directed operation은 다음 algorithm의 steps 1, 3, 그리고 4에 있는 convention을 사용하여 parse node와, 선택적으로, 다른 parameter와 함께 invoked됩니다:

  1. Let status be SyntaxDirectedOperation of SomeNonTerminal.
  2. Let someParseNode be the parse of some source text.
  3. Perform SyntaxDirectedOperation of someParseNode.
  4. Perform SyntaxDirectedOperation of someParseNode with argument "value".

명시적으로 달리 specified되지 않는 한, 모든 chain production은 그 production의 left-hand side nonterminal에 적용될 수 있는 모든 operation에 대해 implicit definition을 가집니다. implicit definition은 같은 operation을 같은 parameter가 있으면 그대로, chain production의 sole right-hand side nonterminal에 다시 적용하고 그 결과를 반환합니다. 예를 들어 어떤 algorithm에 “Return Evaluation of Block” 형식의 step이 있고 다음 production이 있다고 가정합니다:

Block : { StatementList }

그러나 Evaluation operation이 그 production에 algorithm을 associate하지 않는 경우, Evaluation operation은 다음 형식의 association을 implicitly 포함합니다:

Runtime Semantics: Evaluation

Block : { StatementList }
  1. Return Evaluation of StatementList.

5.2.4 Runtime Semantics

runtime에 호출되어야 하는 semantics를 명시하는 algorithm은 runtime semantics라고 합니다. Runtime semantics는 abstract operation 또는 syntax-directed operation에 의해 정의됩니다.

5.2.4.1 Completion ( completionRecord )

The abstract operation Completion takes argument completionRecord (a Completion Record) and returns a Completion Record. Completion Record가 반환되고 있음을 강조하는 데 사용됩니다. It performs the following steps when called:

  1. Assert: completionRecord is a Completion Record.
  2. Return completionRecord.

5.2.4.2 Throw

algorithm step에서 “throw”라는 단어는 ThrowCompletion을 호출한 결과를 반환하는 것에 대한 shorthand입니다. 예를 들어,

  1. If result.[[Error]] is not none, throw result.[[Error]].

은 다음과 equivalent합니다

  1. If result.[[Error]] is not none, return ThrowCompletion(result.[[Error]]).

특정 type의 exception을 throw하라고 말하는 algorithm step은 throw될 그 type의 exception을 construct합니다. 예를 들어,

  1. Throw a TypeError exception.

은 다음과 equivalent합니다

  1. Return ThrowCompletion(a newly created TypeError object).

5.2.4.3 Completion Record를 Unwrap하기 위한 Shorthand

prefix “?”와 “!”는 Completion Record를 unwrap하는 shorthand로 사용됩니다. “?”는 abrupt completion을 caller에게 propagate하거나, 그렇지 않으면 normal completion을 unwrap하는 데 사용됩니다. “!”는 Completion Record가 normal임을 assert하고 unwrap하는 데 사용됩니다. 형식적으로 step

  1. Let result be ? record.

은 다음과 equivalent합니다

  1. Assert: record is a Completion Record.
  2. If record is an abrupt completion, return record.
  3. Let result be record.[[Value]].

마찬가지로 step

  1. Let result be ! record.

은 다음과 equivalent합니다

  1. Assert: record is a normal completion.
  2. Let result be record.[[Value]].

“?” 또는 “!”가 다른 context에서 사용될 때는, 먼저 이 rule이 적용될 수 있을 때까지 Evaluation Order에 주어진 rewrite를 적용한 다음 이 rule을 적용합니다. 예를 들어 step

  1. Perform AO(? Other()).

은 다음으로 rewrite될 수 있습니다

  1. Let tmp1 be Other().
  2. Let tmp2 be ? tmp1.
  3. Perform AO(tmp2).

이는 다시 다음으로 expands됩니다

  1. Let tmp1 be Other().
  2. Assert: tmp1 is a Completion Record.
  3. If tmp1 is an abrupt completion, return tmp1.
  4. Let tmp2 be tmp1.[[Value]].
  5. Perform AO(tmp2).

5.2.4.4 Implicit Normal Completion

Completion Record를 반환하도록 declared된 abstract operation 안의 algorithm과 모든 built-in function 안에서는, 반환된 value가 먼저 NormalCompletion에 전달되고 그 결과가 대신 사용됩니다. 이 rule은 Completion algorithm 안이나 반환되는 value가 그 step에서 명확하게 Completion Record로 표시된 경우에는 적용되지 않습니다. 이러한 경우는 다음과 같습니다:

그러한 abstract operation에서 Completion Record가 다른 수단을 통해 반환되면 editorial error입니다. 예를 들어 이러한 abstract operation 안에서,

  1. Return true.

은 다음 중 어느 것과도 같은 의미입니다

  1. Return NormalCompletion(true).

또는

  1. Let completion be NormalCompletion(true).
  2. Return Completion(completion).

또는

  1. Return Completion Record { [[Type]]: normal, [[Value]]: true, [[Target]]: empty }.

? shorthand expansion을 통해, 다음 예는 허용된다는 점에 유의하십시오. expanded step 안에서 abrupt case에는 Completion을 적용한 결과가 직접 반환되고, normal case에는 unwrapping 후 implicit NormalCompletion application이 발생하기 때문입니다.

  1. Return ? completion.

다음 예는 Completion Record가 그 step에서 annotated되지 않은 채 반환되므로 editorial error입니다.

  1. Let completion be NormalCompletion(true).
  2. Return completion.

5.2.5 Static Semantics

Context-free grammar는 input element의 stream이 evaluated될 수 있는 유효한 ECMAScript Script 또는 Module을 형성하는지 정의하는 모든 rule을 표현할 만큼 충분히 강력하지 않습니다. 어떤 상황에서는 ECMAScript algorithm convention 또는 prose requirement를 사용하여 표현될 수 있는 additional rule이 필요합니다. 그러한 rule은 항상 grammar의 production과 associated되며 production의 static semantics라고 불립니다.

Static Semantic Rule은 name을 가지며 보통 algorithm을 사용하여 정의됩니다. Named Static Semantic Rule은 grammar production과 associated되며, 여러 alternative definition을 가진 production은 보통 각 applicable named static semantic rule에 대해 각 alternative마다 distinct algorithm을 가집니다.

특별한 종류의 static semantic rule은 Early Error Rule입니다. Early error rule은 특정 grammar production과 associated된 early error condition을 정의합니다(절 17 참조). 대부분의 early error rule의 evaluation은 이 명세의 algorithm 안에서 명시적으로 invoked되지 않습니다. conforming implementation은 Script 또는 Module의 첫 evaluation 이전에, 해당 Script 또는 Module을 parse하는 데 사용된 production의 모든 early error rule을 validate해야 합니다. early error rule 중 하나라도 위반되면 Script 또는 Module은 invalid이며 evaluated될 수 없습니다.

5.2.6 Mathematical Operations

이 명세는 다음 종류의 numeric value를 참조합니다:

  • Mathematical values: 기본 numeric type으로 사용되는 arbitrary real number.
  • Extended mathematical values: Mathematical value에 +∞와 -∞를 더한 것.
  • Numbers: IEEE 754-2019 binary64(double-precision floating point) value.
  • BigInts: arbitrary integer를 one-to-one correspondence로 나타내는 ECMAScript language value.

이 명세의 언어에서 numerical value는 subscript suffix를 사용하여 서로 다른 numeric kind 사이에서 구분됩니다. subscript 𝔽는 Number를 가리키고, subscript 는 BigInt를 가리킵니다. subscript suffix가 없는 numeric value는 mathematical value를 가리킵니다. 이 명세는 대부분의 numeric value를 base 10으로 나타내며, 0x 뒤에 digit 0-9 또는 A-F가 오는 형식의 numeric value도 base-16 value로 사용합니다.

일반적으로 이 명세가 “the length of y” 또는 “the integer represented by the four hexadecimal digits ...”와 같은 phrase에서 numeric kind를 명시적으로 지정하지 않고 numerical value를 참조하면, 그 phrase는 mathematical value를 가리킵니다. Number 또는 BigInt value를 가리키는 phrase는 명시적으로 그렇게 annotated됩니다. 예를 들어 “the Number value for the number of code points in …” 또는 “the BigInt value for …”와 같습니다.

이 명세에서 integer라는 term이 사용될 때, 달리 stated되지 않는 한 이는 integer 집합에 속하는 mathematical value를 가리킵니다. 이 명세에서 integral Number라는 term이 사용될 때, 이는 mathematical valueinteger 집합에 속하는 finite Number value를 가리킵니다.

+, ×, =, ≥와 같은 numeric operator는 operand의 type에 따라 결정되는 operation을 가리킵니다. mathematical value에 적용될 때, operator는 일반적인 mathematical operation을 가리킵니다. extended mathematical value에 적용될 때, operator는 extended real number에 대한 일반적인 mathematical operation을 가리킵니다. indeterminate form은 정의되지 않으며, 이 명세에서 그 사용은 editorial error로 간주되어야 합니다. Number에 적용될 때, operator는 IEEE 754-2019 안의 관련 operation을 가리킵니다. BigInt에 적용될 때, operator는 BigInt의 mathematical value에 적용되는 일반적인 mathematical operation을 가리킵니다. mixed-type operand(예: Number와 mathematical value)에 적용된 numeric operator는 정의되지 않으며 이 명세에서 editorial error로 간주되어야 합니다.

mathematical value와 Number 또는 BigInt 사이의 conversion은 이 문서에서 항상 explicit합니다. mathematical value 또는 extended mathematical value x에서 Number로의 conversion은 “the Number value for x” 또는 𝔽(x)로 표시되며 6.1.6.1에 정의됩니다. integer x에서 BigInt로의 conversion은 “the BigInt value for x” 또는 ℤ(x)로 표시됩니다. Number 또는 BigInt x에서 mathematical value로의 conversion은 “the mathematical value of x”, 또는 ℝ(x)로 표시됩니다. +0𝔽-0𝔽mathematical valuemathematical value 0입니다. non-finite value의 mathematical value는 정의되지 않습니다. xextended mathematical value offinite value의 경우 xmathematical value이며, +∞𝔽-∞𝔽의 경우 각각 +∞와 -∞입니다. NaN에 대해서는 정의되지 않습니다.

mathematical function abs(x)x의 absolute value를 생성하며, 이는 x < 0이면 -x, 그렇지 않으면 x 자체입니다.

mathematical function ln(x)x의 natural logarithm을 생성합니다. mathematical function log10(x)x의 base 10 logarithm을 생성합니다. mathematical function log2(x)x의 base 2 logarithm을 생성합니다.

mathematical function min(x1, x2, … , xN)x1부터 xN까지 중 mathematically smallest인 것을 생성합니다. mathematical function max(x1, x2, ..., xN)x1부터 xN까지 중 mathematically largest인 것을 생성합니다. 이러한 mathematical function의 domain과 range는 extended mathematical value입니다.

notation “x modulo y”(yfinite이고 non-zero여야 함)은 abs(k) < abs(y) 그리고 x - k = q × y가 어떤 integer q에 대해 성립하도록, y와 같은 sign(또는 zero)을 가진 값 k를 계산합니다.

phrase “the result of clamping x between lower and upper”(xextended mathematical value이고 lowerupperloweruppermathematical value)는 x < lower이면 lower를 생성하고, x > upper이면 upper를 생성하며, 그렇지 않으면 x를 생성합니다.

mathematical function floor(x)x보다 크지 않은 가장 큰 integer(+∞에 가장 가까운)를 생성합니다.

Note

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

mathematical function truncate(x)x를 zero 쪽으로 rounding하여 fractional part를 제거하며, x < 0이면 -floor(-x)를 생성하고 그렇지 않으면 floor(x)를 생성합니다.

mathematical function min, max, abs, floor, truncate는 Number와 BigInt에 대해 정의되지 않으며, non-mathematical value argument를 가진 이러한 method의 어떤 사용도 이 명세에서 editorial error가 됩니다.

lower bound a에서 upper bound b까지의 interval은 같은 numeric type의 numeric value로 이루어진 possibly-infinite, possibly-empty set입니다. 각 bound는 inclusive 또는 exclusive 중 하나로 설명되며 둘 다일 수는 없습니다. interval에는 다음 네 종류가 있습니다:

  • a(inclusive)에서 b(inclusive)까지의 interval, 또한 a에서 b까지의 inclusive interval이라고도 하며, axb인 같은 numeric type의 모든 value x를 포함하고 그 외에는 포함하지 않습니다.
  • a(inclusive)에서 b(exclusive)까지의 intervalax < b인 같은 numeric type의 모든 value x를 포함하고 그 외에는 포함하지 않습니다.
  • a(exclusive)에서 b(inclusive)까지의 intervala < xb인 같은 numeric type의 모든 value x를 포함하고 그 외에는 포함하지 않습니다.
  • a(exclusive)에서 b(exclusive)까지의 intervala < x < b인 같은 numeric type의 모든 value x를 포함하고 그 외에는 포함하지 않습니다.

예를 들어 1(inclusive)에서 2(exclusive)까지의 interval은 1과 2 사이의 모든 mathematical value로 구성되며, 1을 포함하고 2를 포함하지 않습니다. interval을 정의하는 목적상, -0𝔽 < +0𝔽입니다. 따라서 예를 들어 lower bound가 +0𝔽inclusive interval+0𝔽를 포함하지만 -0𝔽는 포함하지 않습니다. NaNinterval에 결코 포함되지 않습니다.

5.2.7 Value Notation

이 명세에서 ECMAScript language valuebold로 표시됩니다. 예에는 null, true, 또는 "hello"가 포함됩니다. 이는 Function.prototype.apply 또는 let n = 42;와 같은 ECMAScript source text와 구별됩니다.

5.2.8 Identity

이 명세에서는 specification value와 ECMAScript language value 모두가 equality를 위해 비교됩니다. equality를 비교할 때 value는 두 category 중 하나에 속합니다. Values without identityinteger의 magnitude나 sequence의 length와 같은 모든 innate characteristic이 같으면 다른 value without identity와 equal합니다. value without identity는 그 characteristic을 완전히 설명함으로써 prior reference 없이 manifest될 수 있습니다. 반대로 각 value with identity는 unique하므로 자기 자신과만 equal합니다. value with identity는 value without identity와 비슷하지만 identity라고 하는 추가적인 unguessable, unchangeable, universally-unique characteristic을 가집니다. identity 자체는 indescribable이므로 existing value with identity에 대한 reference는 단순히 설명함으로써 manifest될 수 없습니다. 대신 이러한 value에 대한 reference는 한 곳에서 다른 곳으로 명시적으로 전달되어야 합니다. 일부 value with identity는 mutable하므로 그 characteristic(identity 제외)을 in-place로 변경할 수 있으며, 그 value를 보유한 모든 이는 새로운 characteristic을 observe하게 됩니다. value without identity는 value with identity와 결코 equal하지 않습니다.

이 명세의 관점에서, “is”라는 단어는 “If bool is true, then ...”에서처럼 두 value를 equality로 비교하는 데 사용되고, “contains”라는 단어는 “If list contains a Record r such that r.[[Foo]] is true, then ...”에서처럼 equality comparison을 사용하여 list 안에서 value를 search하는 데 사용됩니다. value의 specification identity는 이러한 comparison의 결과를 결정하며 이 명세에서 axiomatic입니다.

ECMAScript 언어의 관점에서, language value는 SameValue abstract operation과 그것이 transitively 호출하는 abstract operation을 사용하여 equality로 비교됩니다. 이러한 comparison abstract operation의 algorithm은 ECMAScript language valuelanguage identity를 결정합니다.

specification value의 경우, specification identity가 없는 value의 예에는 다음이 포함되지만 이에 한정되지 않습니다: mathematical valueextended mathematical value; ECMAScript source text, surrogate pair, Directive Prologue 등; UTF-16 code unit; Unicode code point; enum; syntax-directed operation, host hook 등을 포함한 abstract operation; 그리고 ordered pair. specification identity가 있는 specification value의 예에는 다음이 포함되지만 이에 한정되지 않습니다: Property Descriptor, PrivateElement 등을 포함한 모든 종류의 Record; Parse Node; List; SetRelation; Abstract Closure; Data Block; Private Name; execution contextexecution context stack; agent signifier; 그리고 WaiterList Record.

specification identity는 Symbol.for에 의해 생성된 Symbol value를 제외한 모든 ECMAScript language value에 대해 language identity와 일치합니다. specification identity도 language identity도 없는 ECMAScript language valueundefined, null, Booleans, Strings, Numbers, 그리고 BigInts입니다. specification identity와 language identity를 모두 가진 ECMAScript language valueSymbol.for에 의해 생성되지 않은 SymbolsObjects입니다. Symbol.for에 의해 생성된 Symbol value는 specification identity를 가지지만 language identity는 가지지 않습니다.

6 ECMAScript 데이터 타입과 값

이 명세 안의 알고리즘은 각각 associated type을 가진 값을 조작합니다. 가능한 값 타입은 정확히 이 절에서 정의된 것들입니다. 타입은 다시 ECMAScript language type과 specification type으로 분류됩니다.

6.1 ECMAScript Language Types

ECMAScript language type은 ECMAScript 프로그래머가 ECMAScript 언어를 사용하여 직접 조작하는 값에 대응합니다. ECMAScript language type은 Undefined, Null, Boolean, String, Symbol, Number, BigInt, Object입니다. ECMAScript language value는 ECMAScript language type으로 특징지어지는 값입니다.

6.1.1 Undefined Type

Undefined type은 정확히 하나의 값을 가지며, 이를 undefined라고 합니다. 값이 할당되지 않은 모든 variable은 undefined 값을 가집니다.

6.1.2 Null Type

Null type은 정확히 하나의 값을 가지며, 이를 null이라고 합니다.

6.1.3 Boolean Type

Boolean typetruefalse라고 불리는 두 값을 가진 logical entity를 나타냅니다.

6.1.4 String Type

String type은 0개 이상의 16-bit unsigned integer value(“elements”)의 ordered sequence 전체의 집합이며, 최대 길이는 253 - 1 elements입니다. String type은 일반적으로 실행 중인 ECMAScript 프로그램에서 textual data를 나타내는 데 사용되며, 이 경우 String 안의 각 element는 UTF-16 code unit value로 취급됩니다. 각 element는 sequence 안의 한 position을 차지하는 것으로 간주됩니다. 이러한 position은 non-negative integer로 indexed됩니다. 첫 번째 element가 있으면 index 0에 있고, 다음 element가 있으면 index 1에 있으며, 이런 식으로 계속됩니다. String의 length는 그 안의 element 수(즉, 16-bit value의 수)입니다. empty String은 length가 zero이므로 element를 포함하지 않습니다.

String contents를 interpret하지 않는 ECMAScript operation은 추가 semantics를 적용하지 않습니다. String value를 interpret하는 operation은 각 element를 단일 UTF-16 code unit으로 취급합니다. 그러나 ECMAScript는 이러한 code unit의 값이나 관계에 제한이나 요구사항을 두지 않으므로, String contents를 UTF-16으로 encoded된 Unicode code point의 sequence로 추가 interpret하는 operation은 ill-formed subsequence를 고려해야 합니다. 이러한 operation은 numeric value가 0xD800부터 0xDBFF까지의 inclusive interval에 있는 모든 code unit(Unicode Standard에서 leading surrogate, 더 형식적으로는 high-surrogate code unit으로 정의됨)과 numeric value가 0xDC00부터 0xDFFF까지의 inclusive interval에 있는 모든 code unit(trailing surrogate, 더 형식적으로는 low-surrogate code unit으로 정의됨)에 대해 다음 규칙을 사용하여 특별한 처리를 적용합니다:

String.prototype.normalize 함수(22.1.3.15 참조)는 String value를 명시적으로 normalize하는 데 사용할 수 있습니다. String.prototype.localeCompare(22.1.3.12 참조)는 내부적으로 String value를 normalize하지만, 다른 operation은 자신이 동작하는 string을 implicitly normalize하지 않습니다. 달리 stated되지 않는 한 operation 결과는 language- 및/또는 locale-sensitive하지 않습니다.

Note

이 설계의 rationale은 String 구현을 가능한 한 simple하고 high-performing하게 유지하기 위한 것이었습니다. ECMAScript source text가 Normalized Form C이면, string literal은 Unicode escape sequence를 포함하지 않는 한 normalized되어 있음이 보장됩니다.

이 명세에서 “A, B, ...의 string-concatenation”이라는 phrase(각 argument가 String value, code unit, 또는 code unit sequence인 경우)는 각 argument의 code unit을 (순서대로) concatenation한 code unit sequence를 가진 String value를 나타냅니다.

inclusiveStart부터 exclusiveEnd까지의 stringsubstring”이라는 phrase(string이 String value 또는 code unit sequence이고 inclusiveStartexclusiveEndinteger인 경우)는 string의 index inclusiveStart에서 시작하여 index exclusiveEnd 바로 앞에서 끝나는 consecutive code unit으로 구성된 String value를 나타냅니다(inclusiveStart = exclusiveEnd인 경우 empty String). "to" suffix가 생략되면 string의 length가 exclusiveEnd 값으로 사용됩니다.

ASCII word characters”라는 phrase는 Unicode Basic Latin block의 모든 letter와 number 및 U+005F(LOW LINE)만으로 구성된 다음 String value를 나타냅니다:
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_".
역사적 이유로, 이는 여러 algorithm에서 의미를 가집니다.

6.1.4.1 StringIndexOf ( string, searchValue, fromIndex )

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

  1. lengthstring의 length로 둔다.
  2. searchValue가 empty String이고 fromIndexlength이면, fromIndex를 반환한다.
  3. searchLengthsearchValue의 length로 둔다.
  4. fromIndexilength - searchLength인 각 integer i에 대해, ascending order로, 다음을 수행한다.
    1. candidatestringi부터 i + searchLength까지의 substring으로 둔다.
    2. candidatesearchValue이면, i를 반환한다.
  5. not-found를 반환한다.
Note 1

searchValue가 empty String이고 fromIndexstring의 length이면, 이 알고리즘은 fromIndex를 반환합니다. empty String은 string 안의 모든 position에서, 마지막 code unit 뒤를 포함하여, 사실상 found됩니다.

Note 2

fromIndex + searchValue의 length > string의 length이면, 이 알고리즘은 항상 not-found를 반환합니다.

6.1.4.2 StringLastIndexOf ( string, searchValue, fromIndex )

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

  1. lengthstring의 length로 둔다.
  2. searchLengthsearchValue의 length로 둔다.
  3. Assert: fromIndex + searchLengthlength.
  4. 0 ≤ ifromIndex인 각 integer i에 대해, descending order로, 다음을 수행한다.
    1. candidatestringi부터 i + searchLength까지의 substring으로 둔다.
    2. candidatesearchValue이면, i를 반환한다.
  5. not-found를 반환한다.
Note

searchValue가 empty String이면, 이 알고리즘은 fromIndex를 반환합니다. empty String은 string 안의 모든 position에서, 마지막 code unit 뒤를 포함하여, 사실상 found됩니다.

6.1.5 Symbol Type

Symbol type은 Object property의 key로 사용할 수 있는 모든 non-String value의 집합입니다(6.1.7).

각 Symbol은 unique하고 immutable합니다.

각 Symbol은 값이 String 또는 undefined인 immutable [[Description]] internal slot을 가집니다.

6.1.5.1 Well-Known Symbols

Well-known symbol은 이 명세의 algorithm에서 명시적으로 참조되는 built-in Symbol value입니다. 보통 specification algorithm의 extension point 역할을 하는 value를 가진 property의 key로 사용됩니다. 달리 specified되지 않는 한, well-known symbol value는 모든 realm이 공유합니다(9.3).

이 명세 안에서 well-known symbol은 Table 1에 나열된 값 중 하나인 intrinsic을 사용하는 표준 intrinsic notation으로 지칭됩니다.

Note
이 명세의 이전 판들은 @@name 형식의 notation을 사용했으며, 현재 판에서는 %Symbol.name%을 사용합니다. 특히 다음 이름들이 사용되었습니다: @@asyncIterator, @@hasInstance, @@isConcatSpreadable, @@iterator, @@match, @@matchAll, @@replace, @@search, @@species, @@split, @@toPrimitive, @@toStringTag, and @@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" 생성자 객체가 어떤 객체를 해당 생성자의 인스턴스 중 하나로 인식하는지 결정하는 메서드. 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" 정규 표현식을 문자열과 대조한 일치 항목을 산출하는 반복자를 반환하는 정규 표현식 메서드. 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 Numeric Types

ECMAScript에는 두 built-in numeric type이 있습니다: Number와 BigInt. 다음 abstract operation은 이러한 numeric type 위에서 정의됩니다. “Result” column은 return type을 보여주며, operation의 일부 invocation이 abrupt completion을 반환할 수 있는지도 함께 나타냅니다.

Table 2: Numeric Type Operations
Operation Example source ...의 Evaluation semantics에 의해 Invoked Result
Number::unaryMinus -x Unary - Operator Number
BigInt::unaryMinus BigInt
Number::bitwiseNOT ~x Bitwise NOT Operator ( ~ ) Number
BigInt::bitwiseNOT BigInt
Number::exponentiate x ** y Exponentiation OperatorMath.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, 및 Addition Operator ( + ) Number
BigInt::add BigInt
Number::subtract x --
-- x
x - y
Postfix Decrement Operator, Prefix Decrement Operator, 및 Subtraction Operator ( - ) Number
BigInt::subtract BigInt
Number::leftShift x << y Left Shift Operator ( << ) Number
BigInt::leftShift BigInt
Number::signedRightShift x >> y Signed Right Shift Operator ( >> ) Number
BigInt::signedRightShift BigInt
Number::unsignedRightShift x >>> y Unsigned Right Shift Operator ( >>> ) Number
BigInt::unsignedRightShift throw completion
Number::lessThan x < y
x > y
x <= y
x >= y
Relational Operators, via IsLessThan ( x, y, leftFirst ) Boolean 또는 undefined (unordered input의 경우)
BigInt::lessThan Boolean
Number::equal x == y
x != y
x === y
x !== y
Equality Operators, via IsStrictlyEqual ( x, y ) Boolean
BigInt::equal
Number::sameValue Object.is(x, y) Object internal method, via SameValue ( x, y ), exact value equality를 test하기 위해 Boolean
Number::sameValueZero [x].includes(y) via SameValueZero ( x, y ), Array, Map, Set method에서처럼 +0𝔽-0𝔽의 차이를 무시하고 value equality를 test하기 위해 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) 많은 expression과 built-in function, via ToString ( arg ) String
BigInt::toString

numeric type은 일반적으로 precision loss 또는 truncation 없이 convert될 수 없으므로, ECMAScript 언어는 이러한 type 사이의 implicit conversion을 제공하지 않습니다. 다른 type을 요구하는 function을 호출할 때 type 간 convert를 하려면, 프로그래머는 NumberBigInt function을 명시적으로 호출해야 합니다.

Note

ECMAScript의 초판과 이후 판들은 특정 operator에 대해 precision을 잃거나 truncate될 수 있는 implicit numeric conversion을 제공해 왔습니다. 이러한 legacy implicit conversion은 backward compatibility를 위해 유지되지만, programmer error의 가능성을 최소화하고 향후 판에서 generalized value types의 선택지를 열어두기 위해 BigInt에는 제공되지 않습니다.

6.1.6.1 Number Type

Number type은 정확히 18,437,736,874,454,810,627개(즉, 264 - 253 + 3)의 값을 가지며, IEEE Standard for Binary Floating-Point Arithmetic에 명시된 double-precision floating point IEEE 754-2019 binary64 값을 나타냅니다. 다만 IEEE Standard의 9,007,199,254,740,990개(즉, 253 - 2) distinct NaN 값은 ECMAScript에서 하나의 special NaN value로 표현됩니다. (주의: NaN value는 program expression NaN에 의해 생성됩니다.) 일부 implementation에서는 external code가 여러 NaN value 사이의 차이를 detect할 수 있을 수 있지만, 그러한 behaviour는 implementation-defined입니다. ECMAScript code에서는 모든 NaN value가 서로 indistinguishable합니다.

Note

Number value가 ArrayBuffer(25.1 참조) 또는 SharedArrayBuffer(25.2 참조)에 저장된 뒤 관찰될 수 있는 bit pattern은 ECMAScript implementation이 사용하는 그 Number value의 internal representation과 반드시 같지는 않습니다.

positive Infinitynegative Infinity라고 불리는 두 special value가 더 있습니다. 간결함을 위해, 이 값들은 설명 목적상 각각 +∞𝔽-∞𝔽 symbol로도 지칭됩니다. (주의: 이 두 infinite Number value는 program expression +Infinity(또는 간단히 Infinity)와 -Infinity에 의해 생성됩니다.)

다른 18,437,736,874,454,810,624개(즉, 264 - 253)의 값은 finite number라고 불립니다. 이 중 절반은 positive number이고 절반은 negative number입니다. 모든 finite positive Number value에 대해 같은 magnitude를 가진 대응하는 negative value가 있습니다.

positive zeronegative zero가 모두 있다는 점에 유의하십시오. 간결함을 위해, 이 값들은 설명 목적상 각각 +0𝔽-0𝔽 symbol로도 지칭됩니다. (주의: 이 두 다른 zero Number value는 program expression +0(또는 간단히 0)와 -0에 의해 생성됩니다.)

18,437,736,874,454,810,622개(즉, 264 - 253 - 2)의 finite non-zero value는 두 종류입니다:

그중 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까지의 inclusive interval에 있는 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입니다.

magnitude가 253보다 크지 않은 모든 positive 및 negative integer는 Number type에서 representable하다는 점에 유의하십시오. integer 0은 Number type에서 두 representation을 가집니다: +0𝔽-0𝔽.

finite number가 non-zero이고 위에 표시된 두 형식 중 하나로 표현하는 데 사용된 integer m이 odd이면, 이는 odd significand를 가집니다. 그렇지 않으면 even significand를 가집니다.

이 명세에서 “x에 대한 Number value for”라는 phrase에서 x가 exact real mathematical quantity(π와 같은 irrational number일 수도 있음)를 나타낼 때, 이는 다음 방식으로 선택된 Number value를 의미합니다. Number type의 모든 finite value의 집합에서 -0𝔽를 제거하고, Number type에서 representable하지 않는 두 additional value, 즉 21024(이는 +1 × 253 × 2971)와 -21024(이는 -1 × 253 × 2971)를 추가한 집합을 고려합니다. 이 집합의 member 중 x에 가장 가까운 값을 선택합니다. 집합의 두 값이 equally close이면, even significand를 가진 것을 선택합니다. 이 목적상 두 extra value 21024-21024는 even significand를 가진 것으로 간주됩니다. 마지막으로 21024가 선택되었으면 이를 +∞𝔽로 replace합니다. -21024가 선택되었으면 이를 -∞𝔽로 replace합니다. +0𝔽가 선택되었으면 x < 0인 경우에만 이를 -0𝔽로 replace합니다. 그 밖의 선택된 값은 unchanged로 사용됩니다. 그 결과가 x에 대한 Number value입니다. (이 절차는 IEEE 754-2019 roundTiesToEven mode의 behaviour와 정확히 대응합니다.)

+∞에 대한 Number value는 +∞𝔽이고, -∞에 대한 Number value는 -∞𝔽입니다.

일부 ECMAScript operator는 -231부터 231 - 1까지의 inclusive interval이나 0부터 216 - 1까지의 inclusive interval과 같은 특정 range의 integer만 다룹니다. 이러한 operator는 Number type의 어떤 값이든 accept하지만 먼저 그러한 각 값을 expected range의 integer value로 convert합니다. 7.1의 numeric conversion operation 설명을 참조하십시오.

6.1.6.1.1 Number::unaryMinus ( number )

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

  1. numberNaN이면, NaN을 반환한다.
  2. number의 negation을 반환한다. 즉, 같은 magnitude이지만 opposite sign을 가진 Number를 계산한다.

6.1.6.1.2 Number::bitwiseNOT ( number )

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

  1. oldValue를 ! ToInt32(number)로 둔다.
  2. oldValue의 bitwise complement를 반환한다. 결과의 mathematical value는 32-bit two's complement bit string으로 정확히 representable하다.

6.1.6.1.3 Number::exponentiate ( base, exponent )

The abstract operation Number::exponentiate takes arguments base (a Number) and exponent (a Number) and returns a Number. baseexponent power로 올린 결과를 나타내는 implementation-approximated value를 반환합니다. It performs the following steps when called:

  1. exponentNaN이면, NaN을 반환한다.
  2. exponent+0𝔽 또는 -0𝔽이면, 1𝔽를 반환한다.
  3. baseNaN이면, NaN을 반환한다.
  4. base+∞𝔽이면, 다음을 수행한다.
    1. exponent > +0𝔽이면, +∞𝔽를 반환한다.
    2. +0𝔽를 반환한다.
  5. base-∞𝔽이면, 다음을 수행한다.
    1. exponent > +0𝔽이면, 다음을 수행한다.
      1. exponent가 odd integral Number이면, -∞𝔽를 반환한다.
      2. +∞𝔽를 반환한다.
    2. exponent가 odd integral Number이면, -0𝔽를 반환한다.
    3. +0𝔽를 반환한다.
  6. base+0𝔽이면, 다음을 수행한다.
    1. exponent > +0𝔽이면, +0𝔽를 반환한다.
    2. +∞𝔽를 반환한다.
  7. base-0𝔽이면, 다음을 수행한다.
    1. exponent > +0𝔽이면, 다음을 수행한다.
      1. exponent가 odd integral Number이면, -0𝔽를 반환한다.
      2. +0𝔽를 반환한다.
    2. exponent가 odd integral Number이면, -∞𝔽를 반환한다.
    3. +∞𝔽를 반환한다.
  8. Assert: basefinite이고 +0𝔽-0𝔽도 아니다.
  9. exponent+∞𝔽이면, 다음을 수행한다.
    1. abs((base)) > 1이면, +∞𝔽를 반환한다.
    2. abs((base)) = 1이면, NaN을 반환한다.
    3. +0𝔽를 반환한다.
  10. exponent-∞𝔽이면, 다음을 수행한다.
    1. abs((base)) > 1이면, +0𝔽를 반환한다.
    2. abs((base)) = 1이면, NaN을 반환한다.
    3. +∞𝔽를 반환한다.
  11. Assert: exponentfinite이고 +0𝔽-0𝔽도 아니다.
  12. base < -0𝔽이고 exponentintegral Number가 아니면, NaN을 반환한다.
  13. (base)를 (exponent) power로 올린 결과를 나타내는 implementation-approximated Number value를 반환한다.
Note

base1𝔽 또는 -1𝔽이고 exponent+∞𝔽 또는 -∞𝔽일 때, 또는 base1𝔽이고 exponentNaN일 때의 base ** exponent 결과는 IEEE 754-2019와 다릅니다. ECMAScript 초판은 이 operation의 결과를 NaN으로 명시했지만, 이후 IEEE 754 개정판은 1𝔽를 명시했습니다. 역사적 ECMAScript behaviour는 compatibility 이유로 보존됩니다.

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의 규칙에 따라 multiplication을 수행하여 xy의 product를 생성합니다. It performs the following steps when called:

  1. xNaN이거나 yNaN이면, NaN을 반환한다.
  2. x+∞𝔽 또는 -∞𝔽이면, 다음을 수행한다.
    1. y+0𝔽 또는 -0𝔽이면, NaN을 반환한다.
    2. y > +0𝔽이면, x를 반환한다.
    3. -x를 반환한다.
  3. y+∞𝔽 또는 -∞𝔽이면, 다음을 수행한다.
    1. x+0𝔽 또는 -0𝔽이면, NaN을 반환한다.
    2. x > +0𝔽이면, y를 반환한다.
    3. -y를 반환한다.
  4. x-0𝔽이면, 다음을 수행한다.
    1. y-0𝔽이거나 y < -0𝔽이면, +0𝔽를 반환한다.
    2. -0𝔽를 반환한다.
  5. y-0𝔽이면, 다음을 수행한다.
    1. x < -0𝔽이면, +0𝔽를 반환한다.
    2. -0𝔽를 반환한다.
  6. 𝔽((x) × (y))를 반환한다.
Note

Finite-precision multiplication은 commutative이지만, 항상 associative인 것은 아닙니다.

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의 규칙에 따라 division을 수행하여, x가 dividend이고 y가 divisor인 xy의 quotient를 생성합니다. It performs the following steps when called:

  1. xNaN이거나 yNaN이면, NaN을 반환한다.
  2. x+∞𝔽 또는 -∞𝔽이면, 다음을 수행한다.
    1. y+∞𝔽 또는 -∞𝔽이면, NaN을 반환한다.
    2. y+0𝔽이거나 y > +0𝔽이면, x를 반환한다.
    3. -x를 반환한다.
  3. y+∞𝔽이면, 다음을 수행한다.
    1. x+0𝔽이거나 x > +0𝔽이면, +0𝔽를 반환한다.
    2. -0𝔽를 반환한다.
  4. y-∞𝔽이면, 다음을 수행한다.
    1. x+0𝔽이거나 x > +0𝔽이면, -0𝔽를 반환한다.
    2. +0𝔽를 반환한다.
  5. x+0𝔽 또는 -0𝔽이면, 다음을 수행한다.
    1. y+0𝔽 또는 -0𝔽이면, NaN을 반환한다.
    2. y > +0𝔽이면, x를 반환한다.
    3. -x를 반환한다.
  6. y+0𝔽이면, 다음을 수행한다.
    1. x > +0𝔽이면, +∞𝔽를 반환한다.
    2. -∞𝔽를 반환한다.
  7. y-0𝔽이면, 다음을 수행한다.
    1. x > +0𝔽이면, -∞𝔽를 반환한다.
    2. +∞𝔽를 반환한다.
  8. 𝔽((x) / (y))를 반환한다.

6.1.6.1.6 Number::remainder ( numerator, denominator )

The abstract operation Number::remainder takes arguments numerator (a Number) and denominator (a Number) and returns a Number. numerator가 dividend이고 denominator가 divisor인 operand의 implied division에서 remainder를 산출합니다. It performs the following steps when called:

  1. numeratorNaN이거나 denominatorNaN이면, NaN을 반환한다.
  2. numerator+∞𝔽 또는 -∞𝔽이면, NaN을 반환한다.
  3. denominator+∞𝔽 또는 -∞𝔽이면, numerator를 반환한다.
  4. denominator+0𝔽 또는 -0𝔽이면, NaN을 반환한다.
  5. numerator+0𝔽 또는 -0𝔽이면, numerator를 반환한다.
  6. Assert: numeratordenominatorfinite이고 non-zero이다.
  7. quotient(numerator) / (denominator)로 둔다.
  8. truncatedQuotienttruncate(quotient)로 둔다.
  9. remainder(numerator) - ((denominator) × truncatedQuotient)로 둔다.
  10. remainder = 0이고 numerator < -0𝔽이면, -0𝔽를 반환한다.
  11. 𝔽(remainder)를 반환한다.
Note 1

C와 C++에서 remainder operator는 integral operand만 accept합니다. ECMAScript에서는 floating-point operand도 accept합니다.

Note 2
% operator로 계산되는 floating-point remainder operation의 결과는 IEEE 754-2019가 정의하는 “remainder” operation과 같지 않습니다. IEEE 754-2019 “remainder” operation은 truncating division이 아니라 rounding division에서 remainder를 계산하므로, 그 behaviour는 일반적인 integer remainder operator의 behaviour와 analogous하지 않습니다. 대신 ECMAScript 언어는 floating-point operation에서 %가 Java integer remainder operator와 analogous한 방식으로 behave하도록 정의합니다. 이는 C library function 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의 규칙에 따라 addition을 수행하여 argument의 sum을 생성합니다. It performs the following steps when called:

  1. xNaN이거나 yNaN이면, NaN을 반환한다.
  2. x+∞𝔽이고 y-∞𝔽이면, NaN을 반환한다.
  3. x-∞𝔽이고 y+∞𝔽이면, NaN을 반환한다.
  4. x+∞𝔽 또는 -∞𝔽이면, x를 반환한다.
  5. y+∞𝔽 또는 -∞𝔽이면, y를 반환한다.
  6. Assert: xy는 둘 다 finite이다.
  7. x-0𝔽이고 y-0𝔽이면, -0𝔽를 반환한다.
  8. 𝔽((x) + (y))를 반환한다.
Note

Finite-precision addition은 commutative이지만, 항상 associative인 것은 아닙니다.

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. subtraction을 수행하여 operand의 difference를 생성합니다. x는 minuend이고 y는 subtrahend입니다. It performs the following steps when called:

  1. Number::add(x, Number::unaryMinus(y))를 반환한다.
Note

x - y는 항상 x + (-y)와 같은 결과를 생성합니다.

6.1.6.1.9 Number::leftShift ( x, y )

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

  1. leftNumber를 ! ToInt32(x)로 둔다.
  2. rightNumber를 ! ToUint32(y)로 둔다.
  3. shiftCount(rightNumber) modulo 32로 둔다.
  4. leftNumbershiftCount bit만큼 left shifting한 결과를 반환한다. 결과의 mathematical value는 32-bit two's complement bit string으로 정확히 representable하다.

6.1.6.1.10 Number::signedRightShift ( x, y )

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

  1. leftNumber를 ! ToInt32(x)로 둔다.
  2. rightNumber를 ! ToUint32(y)로 둔다.
  3. shiftCount(rightNumber) modulo 32로 둔다.
  4. leftNumbershiftCount bit만큼 sign-extending right shift한 결과를 반환한다. most significant bit가 propagated된다. 결과의 mathematical value는 32-bit two's complement bit string으로 정확히 representable하다.

6.1.6.1.11 Number::unsignedRightShift ( x, y )

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

  1. leftNumber를 ! ToUint32(x)로 둔다.
  2. rightNumber를 ! ToUint32(y)로 둔다.
  3. shiftCount(rightNumber) modulo 32로 둔다.
  4. leftNumbershiftCount bit만큼 zero-filling right shift한 결과를 반환한다. 비워진 bit는 zero로 채워진다. 결과의 mathematical value는 32-bit unsigned bit string으로 정확히 representable하다.

6.1.6.1.12 Number::lessThan ( x, y )

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

  1. xNaN이면, undefined를 반환한다.
  2. yNaN이면, undefined를 반환한다.
  3. xy이면, false를 반환한다.
  4. x+0𝔽이고 y-0𝔽이면, false를 반환한다.
  5. x-0𝔽이고 y+0𝔽이면, false를 반환한다.
  6. x+∞𝔽이면, false를 반환한다.
  7. y+∞𝔽이면, true를 반환한다.
  8. y-∞𝔽이면, false를 반환한다.
  9. x-∞𝔽이면, true를 반환한다.
  10. Assert: xyfinite이다.
  11. (x) < (y)이면, true를 반환한다.
  12. false를 반환한다.

6.1.6.1.13 Number::equal ( x, y )

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

  1. xNaN이면, false를 반환한다.
  2. yNaN이면, false를 반환한다.
  3. xy이면, true를 반환한다.
  4. x+0𝔽이고 y-0𝔽이면, true를 반환한다.
  5. x-0𝔽이고 y+0𝔽이면, true를 반환한다.
  6. false를 반환한다.

6.1.6.1.14 Number::sameValue ( x, y )

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

  1. xNaN이고 yNaN이면, true를 반환한다.
  2. x+0𝔽이고 y-0𝔽이면, false를 반환한다.
  3. x-0𝔽이고 y+0𝔽이면, false를 반환한다.
  4. xy이면, true를 반환한다.
  5. false를 반환한다.

6.1.6.1.15 Number::sameValueZero ( x, y )

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

  1. xNaN이고 yNaN이면, true를 반환한다.
  2. x+0𝔽이고 y-0𝔽이면, true를 반환한다.
  3. x-0𝔽이고 y+0𝔽이면, true를 반환한다.
  4. xy이면, true를 반환한다.
  5. false를 반환한다.

6.1.6.1.16 NumberBitwiseOp ( op, x, y )

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

  1. leftNumber를 ! ToInt32(x)로 둔다.
  2. rightNumber를 ! ToInt32(y)로 둔다.
  3. leftBits(leftNumber)를 나타내는 32-bit two's complement bit string으로 둔다.
  4. rightBits(rightNumber)를 나타내는 32-bit two's complement bit string으로 둔다.
  5. op&이면, 다음을 수행한다.
    1. resultleftBitsrightBits에 bitwise AND operation을 적용한 결과로 둔다.
  6. 그렇지 않고 op^이면, 다음을 수행한다.
    1. resultleftBitsrightBits에 bitwise exclusive OR (XOR) operation을 적용한 결과로 둔다.
  7. 그렇지 않으면,
    1. Assert: op|이다.
    2. resultleftBitsrightBits에 bitwise inclusive OR operation을 적용한 결과로 둔다.
  8. 32-bit two's complement bit string result가 나타내는 integer에 대한 Number value를 반환한다.

6.1.6.1.17 Number::bitwiseAND ( x, y )

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

  1. NumberBitwiseOp(&, x, y)를 반환한다.

6.1.6.1.18 Number::bitwiseXOR ( x, y )

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

  1. NumberBitwiseOp(^, x, y)를 반환한다.

6.1.6.1.19 Number::bitwiseOR ( x, y )

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

  1. NumberBitwiseOp(|, x, y)를 반환한다.

6.1.6.1.20 Number::toString ( x, radix )

The abstract operation Number::toString takes arguments x (a Number) and radix (an integer in the inclusive interval from 2 to 36) and returns a String. radix를 radix로 하는 positional numeral system을 사용하여 x를 String으로 나타냅니다. radix r을 사용한 number representation에서 사용되는 digit은 "0123456789abcdefghijklmnopqrstuvwxyz"의 처음 r code unit에서 순서대로 가져옵니다. magnitude가 1𝔽 이상인 number의 representation은 leading zero를 결코 포함하지 않습니다. It performs the following steps when called:

  1. xNaN이면, "NaN"을 반환한다.
  2. x+0𝔽 또는 -0𝔽이면, "0"을 반환한다.
  3. x < -0𝔽이면, "-"Number::toString(-x, radix)의 string-concatenation을 반환한다.
  4. x+∞𝔽이면, "Infinity"를 반환한다.
  5. n, k, s를 다음을 만족하는 integer로 둔다: k ≥ 1, radixk - 1s < radixk, 𝔽(s × radixn - k)가 x이고, k는 가능한 한 작다. k는 radix radix를 사용한 s의 representation에서 digit 수이고, sradix로 divisible하지 않으며, s의 least significant digit은 이러한 criteria에 의해 반드시 uniquely determined되는 것은 아니라는 점에 유의한다.
  6. radix ≠ 10이거나 n이 -5부터 21까지의 inclusive interval 안에 있으면, 다음을 수행한다.
    1. nk이면, 다음을 수행한다.
      1. 다음의 string-concatenation을 반환한다:
        • radix radix를 사용한 s의 representation에서 k digit의 code unit
        • code unit 0x0030 (DIGIT ZERO)의 n - k occurrences
    2. n > 0이면, 다음을 수행한다.
      1. 다음의 string-concatenation을 반환한다:
        • radix radix를 사용한 s의 representation에서 most significant n digit의 code unit
        • code unit 0x002E (FULL STOP)
        • radix radix를 사용한 s의 representation에서 remaining k - n digit의 code unit
    3. Assert: n ≤ 0.
    4. 다음의 string-concatenation을 반환한다:
      • code unit 0x0030 (DIGIT ZERO)
      • code unit 0x002E (FULL STOP)
      • code unit 0x0030 (DIGIT ZERO)의 -n occurrences
      • radix radix를 사용한 s의 representation에서 k digit의 code unit
  7. NOTE: 이 경우 input은 1.2e+3과 같은 scientific E notation을 사용하여 represented된다.
  8. Assert: radix는 10이다.
  9. n < 0이면, 다음을 수행한다.
    1. exponentSign을 code unit 0x002D (HYPHEN-MINUS)로 둔다.
  10. 그렇지 않으면,
    1. exponentSign을 code unit 0x002B (PLUS SIGN)로 둔다.
  11. k = 1이면, 다음을 수행한다.
    1. 다음의 string-concatenation을 반환한다:
      • s의 single digit의 code unit
      • code unit 0x0065 (LATIN SMALL LETTER E)
      • exponentSign
      • abs(n - 1)의 decimal representation의 code unit
  12. 다음의 string-concatenation을 반환한다:
    • s의 decimal representation에서 most significant digit의 code unit
    • code unit 0x002E (FULL STOP)
    • s의 decimal representation에서 remaining k - 1 digit의 code unit
    • code unit 0x0065 (LATIN SMALL LETTER E)
    • exponentSign
    • abs(n - 1)의 decimal representation의 code unit
Note 1

다음 observations는 implementation을 위한 guideline으로 유용할 수 있지만, 이 표준의 normative requirement의 일부는 아닙니다:

  • x가 -0𝔽 이외의 어떤 Number value이면, ToNumber(ToString(x))는 x입니다.
  • s의 least significant digit은 step 5에 나열된 requirements에 의해 항상 uniquely determined되는 것은 아닙니다.
Note 2

위 규칙이 요구하는 것보다 더 정확한 conversion을 제공하는 implementation의 경우, step 5의 다음 alternative version을 guideline으로 사용할 것을 권장합니다:

  1. n, k, s를 다음을 만족하는 integer로 둔다: k ≥ 1, radixk - 1s < radixk, 𝔽(s × radixn - k)가 x이고, k는 가능한 한 작다. s에 대해 여러 가능성이 있으면, s × radixn - k(x)에 가장 가까운 s를 선택한다. 그러한 가능한 s 값이 두 개 있으면, even인 것을 선택한다. k는 radix radix를 사용한 s의 representation에서 digit 수이며 sradix로 divisible하지 않는다는 점에 유의한다.
Note 3

ECMAScript implementer는 floating-point number의 binary-to-decimal conversion에 대해 David M. Gay가 작성한 논문과 code가 유용할 수 있습니다:

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 Type

BigInt typeinteger value를 나타냅니다. 값은 어떤 size도 될 수 있으며 특정 bit-width로 제한되지 않습니다. 일반적으로 달리 noted되지 않은 곳에서 operation은 exact mathematically-based answer를 반환하도록 설계됩니다. binary operation의 경우, BigInt는 two's complement binary string처럼 동작하며, negative number는 왼쪽으로 infinite하게 bit가 set된 것으로 취급됩니다.

6.1.6.2.1 BigInt::unaryMinus ( bigint )

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

  1. bigint = 0이면, 0를 반환한다.
  2. -bigint를 반환한다.

6.1.6.2.2 BigInt::bitwiseNOT ( bigint )

The abstract operation BigInt::bitwiseNOT takes argument bigint (a BigInt) and returns a BigInt. bigint의 one's complement를 반환합니다. It performs the following steps when called:

  1. -bigint - 1를 반환한다.

6.1.6.2.3 BigInt::exponentiate ( base, exponent )

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

  1. exponent < 0이면, RangeError exception을 throw한다.
  2. base = 0이고 exponent = 0이면, 1를 반환한다.
  3. base raised to the power 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:

  1. x × y를 반환한다.
Note
결과가 input보다 훨씬 더 큰 bit width를 가지더라도, exact mathematical answer가 제공됩니다.

6.1.6.2.5 BigInt::divide ( x, y )

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

  1. y = 0이면, RangeError exception을 throw한다.
  2. quotient(x) / (y)로 둔다.
  3. (truncate(quotient))를 반환한다.

6.1.6.2.6 BigInt::remainder ( numerator, denominator )

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

  1. denominator = 0이면, RangeError exception을 throw한다.
  2. numerator = 0이면, 0를 반환한다.
  3. quotient(numerator) / (denominator)로 둔다.
  4. truncatedQuotient(truncate(quotient))로 둔다.
  5. numerator - (denominator × truncatedQuotient)를 반환한다.
Note
결과의 sign은 dividend의 sign입니다.

6.1.6.2.7 BigInt::add ( x, y )

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

  1. x + y를 반환한다.

6.1.6.2.8 BigInt::subtract ( x, y )

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

  1. x - y를 반환한다.

6.1.6.2.9 BigInt::leftShift ( x, y )

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

  1. y < 0이면, 다음을 수행한다.
    1. (floor((x) / 2-(y)))를 반환한다.
  2. x × 2y를 반환한다.
Note
여기서 semantics는 BigInt를 infinite length string of binary two's complement digit으로 취급하는 bitwise shift와 equivalent해야 합니다.

6.1.6.2.10 BigInt::signedRightShift ( x, y )

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

  1. BigInt::leftShift(x, -y)를 반환한다.

6.1.6.2.11 BigInt::unsignedRightShift ( x, y )

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

  1. TypeError exception을 throw한다.

6.1.6.2.12 BigInt::lessThan ( x, y )

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

  1. (x) < (y)이면, true를 반환한다.
  2. false를 반환한다.

6.1.6.2.13 BigInt::equal ( x, y )

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

  1. (x) = (y)이면, true를 반환한다.
  2. false를 반환한다.

6.1.6.2.14 BinaryAnd ( x, y )

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

  1. x = 1이고 y = 1이면, 1을 반환한다.
  2. 0을 반환한다.

6.1.6.2.15 BinaryOr ( x, y )

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

  1. x = 1이거나 y = 1이면, 1을 반환한다.
  2. 0을 반환한다.

6.1.6.2.16 BinaryXor ( x, y )

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

  1. x = 1이고 y = 0이면, 1을 반환한다.
  2. x = 0이고 y = 1이면, 1을 반환한다.
  3. 0을 반환한다.

6.1.6.2.17 BigIntBitwiseOp ( op, x, y )

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

  1. x(x)로 설정한다.
  2. y(y)로 설정한다.
  3. result를 0으로 둔다.
  4. shift를 0으로 둔다.
  5. (x = 0 또는 x = -1)이고 (y = 0 또는 y = -1)이 될 때까지 Repeat한다.
    1. xDigitx modulo 2로 둔다.
    2. yDigity modulo 2로 둔다.
    3. op&이면, 다음을 수행한다.
      1. resultresult + 2shift × BinaryAnd(xDigit, yDigit)로 설정한다.
    4. 그렇지 않고 op|이면, 다음을 수행한다.
      1. resultresult + 2shift × BinaryOr(xDigit, yDigit)로 설정한다.
    5. 그렇지 않으면,
      1. Assert: op^이다.
      2. resultresult + 2shift × BinaryXor(xDigit, yDigit)로 설정한다.
    6. shiftshift + 1로 설정한다.
    7. x를 (x - xDigit) / 2로 설정한다.
    8. y를 (y - yDigit) / 2로 설정한다.
  6. op&이면, 다음을 수행한다.
    1. signBitBinaryAnd(x modulo 2, y modulo 2)로 둔다.
  7. 그렇지 않고 op|이면, 다음을 수행한다.
    1. signBitBinaryOr(x modulo 2, y modulo 2)로 둔다.
  8. 그렇지 않으면,
    1. Assert: op^이다.
    2. signBitBinaryXor(x modulo 2, y modulo 2)로 둔다.
  9. signBit ≠ 0이면, 다음을 수행한다.
    1. resultresult - 2shift로 설정한다.
    2. NOTE: 이는 sign을 extends한다.
  10. result에 대한 BigInt value를 반환한다.

6.1.6.2.18 BigInt::bitwiseAND ( x, y )

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

  1. BigIntBitwiseOp(&, x, y)를 반환한다.

6.1.6.2.19 BigInt::bitwiseXOR ( x, y )

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

  1. BigIntBitwiseOp(^, x, y)를 반환한다.

6.1.6.2.20 BigInt::bitwiseOR ( x, y )

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

  1. BigIntBitwiseOp(|, x, y)를 반환한다.

6.1.6.2.21 BigInt::toString ( x, radix )

The abstract operation BigInt::toString takes arguments x (a BigInt) and radix (an integer in the inclusive interval from 2 to 36) and returns a String. radix를 radix로 하는 positional numeral system을 사용하여 x를 String으로 나타냅니다. radix r을 사용한 BigInt representation에서 사용되는 digit은 "0123456789abcdefghijklmnopqrstuvwxyz"의 처음 r code unit에서 순서대로 가져옵니다. 0 이외의 BigInt representation은 leading zero를 결코 포함하지 않습니다. It performs the following steps when called:

  1. x < 0이면, "-"BigInt::toString(-x, radix)의 string-concatenation을 반환한다.
  2. radix radix를 사용한 x의 representation으로 구성된 String value를 반환한다.

6.1.7 Object Type

Object type의 각 instance는 간단히 “an Object”라고도 하며, property의 collection을 나타냅니다. 각 property는 data property 또는 accessor property입니다:

  • data property는 key value를 ECMAScript language value 및 Boolean attribute의 set과 연관시킵니다.
  • accessor property는 key value를 하나 또는 두 개의 accessor function 및 Boolean attribute의 set과 연관시킵니다. accessor function은 property와 연관된 ECMAScript language value를 store하거나 retrieve하는 데 사용됩니다.

object의 property는 property key를 사용하여 unique하게 식별됩니다. property key는 String 또는 Symbol입니다. empty String을 포함한 모든 String과 Symbol은 property key로 valid합니다. property name은 String인 property key입니다.

integer indexCanonicalNumericIndexString(n)이 +0𝔽부터 𝔽(253 - 1)까지의 inclusive interval에 있는 integral Number를 반환하는 property name n입니다. array indexCanonicalNumericIndexString(n)이 +0𝔽부터 𝔽(232 - 2)까지의 inclusive interval에 있는 integral Number를 반환하는 integer index n입니다.

Note

모든 non-negative safe integer에는 대응하는 integer index가 있습니다. 232 - 1을 제외한 모든 32-bit unsigned integer에는 대응하는 array index가 있습니다. "-0"integer indexarray index도 아닙니다.

Property key는 property와 그 value에 access하는 데 사용됩니다. property에 대한 access에는 두 종류가 있습니다: 각각 value retrieval과 assignment에 대응하는 getset입니다. get 및 set access를 통해 accessible한 property에는 object의 직접적인 부분인 own properties와 property inheritance relationship을 통해 다른 associated object가 제공하는 inherited properties가 모두 포함됩니다. Inherited property는 associated object의 own 또는 inherited property일 수 있습니다. object의 각 own property는 그 object의 다른 own property의 key value와 distinct한 key value를 각각 가져야 합니다.

모든 object는 논리적으로 property의 collection이지만, property에 access하고 manipulate하는 semantics가 서로 다른 여러 form의 object가 있습니다. object의 여러 form에 대한 정의는 6.1.7.2를 참조하십시오.

또한 일부 object는 callable합니다. 이러한 object는 function 또는 function object라고 불리며 아래에서 더 자세히 설명됩니다. ECMAScript의 모든 function은 Object type의 member입니다.

6.1.7.1 Property Attributes

Attribute는 Table 3에 설명된 Object property의 state를 정의하고 설명하기 위해 이 명세에서 사용됩니다. 명시적으로 specified되지 않는 한, 각 attribute의 initial value는 그 Default Value입니다.

Table 3: Attributes of an Object property
Attribute Name 그것이 present하는 property의 type Value Domain Default Value Description
[[Value]] data property ECMAScript language value undefined property의 get access에 의해 retrieved되는 value입니다.
[[Writable]] data property Boolean false false이면, ECMAScript code가 [[Set]]을 사용하여 property의 [[Value]] attribute를 변경하려는 시도는 성공하지 않습니다.
[[Get]] accessor property Object 또는 undefined undefined value가 Object이면 function object여야 합니다. property의 get access가 수행될 때마다, property value를 retrieve하기 위해 function의 [[Call]] internal method(Table 5)가 empty arguments list와 함께 호출됩니다.
[[Set]] accessor property Object 또는 undefined undefined value가 Object이면 function object여야 합니다. property의 set access가 수행될 때마다, assigned value를 sole argument로 포함하는 arguments list와 함께 function의 [[Call]] internal method(Table 5)가 호출됩니다. property의 [[Set]] internal method의 effect는 subsequent call에서 property의 [[Get]] internal method가 반환하는 value에 effect를 가질 수 있지만, 반드시 그래야 하는 것은 아닙니다.
[[Enumerable]] data property 또는 accessor property Boolean false true이면, property는 for-in enumeration(14.7.5 참조)에 의해 enumerated됩니다. 그렇지 않으면 property는 non-enumerable이라고 합니다.
[[Configurable]] data property 또는 accessor property Boolean false false이면, property를 delete하거나, data property에서 accessor property로 또는 accessor property에서 data property로 변경하거나, 그 attribute에 변경을 가하려는 시도(기존 [[Value]]를 replacing하거나 [[Writable]]false로 setting하는 것 제외)는 fail합니다.

6.1.7.2 Object Internal Methods and Internal Slots

ECMAScript에서 object의 실제 semantics는 internal methods라고 불리는 algorithm을 통해 specified됩니다. ECMAScript engine의 각 object는 그 runtime behaviour를 정의하는 internal method의 set과 associated됩니다. 이러한 internal method는 ECMAScript language의 일부가 아닙니다. 이들은 순전히 expository purpose를 위해 이 명세에서 정의됩니다. 그러나 ECMAScript implementation 안의 각 object는 자신과 associated된 internal method에 의해 specified된 대로 behave해야 합니다. 이를 달성하는 정확한 방식은 implementation에 의해 결정됩니다.

Internal method name은 polymorphic입니다. 이는 common internal method name이 서로 다른 object value에서 invoked될 때 서로 다른 algorithm을 수행할 수 있음을 의미합니다. internal method가 invoked되는 실제 object는 invocation의 “target”입니다. runtime에 algorithm의 implementation이 object가 support하지 않는 internal method를 사용하려고 하면, TypeError exception이 thrown됩니다.

Internal slot은 object, Symbol 또는 Private Name과 associated되어 다양한 ECMAScript specification algorithm에서 사용되는 internal state에 대응합니다. Internal slot은 object property가 아니며 inherited되지 않습니다. 특정 internal slot specification에 따라, 이러한 state는 어떤 ECMAScript language type의 value나 특정 ECMAScript specification type value로 구성될 수 있습니다. 달리 explicitly specified되지 않는 한, internal slot은 object, Symbol 또는 Private Name을 생성하는 process의 일부로 allocated되며 dynamically added될 수 없습니다. 달리 specified되지 않는 한, internal slot의 initial value는 undefined 값입니다. 이 명세 안의 다양한 algorithm은 internal slot을 가진 value를 생성합니다. 그러나 ECMAScript language는 internal slot을 manipulate하는 직접적인 방법을 제공하지 않습니다.

모든 object는 [[PrivateElements]]라는 internal slot을 가지며, 이는 PrivateElementsList입니다. 이 List는 object에 대한 private field, method 및 accessor의 value를 나타냅니다. Initially, 이는 empty List입니다.

Internal method와 internal slot은 이 명세 안에서 double square bracket [[ ]]으로 둘러싸인 name을 사용하여 식별됩니다.

Table 4는 ECMAScript code에 의해 생성되거나 manipulated되는 모든 object에 applicable한 이 명세에서 사용되는 essential internal methods를 요약합니다. 모든 object는 모든 essential internal method에 대한 algorithm을 가져야 합니다. 그러나 모든 object가 그 method에 대해 반드시 같은 algorithm을 사용하는 것은 아닙니다.

ordinary object는 다음 criteria를 모두 만족하는 object입니다:

  • Table 4에 나열된 internal method에 대해, object는 10.1에 정의된 것들을 사용합니다.
  • object가 [[Call]] internal method를 가지는 경우, 10.2.1에 정의된 것 또는 10.3.1에 정의된 것 중 하나를 사용합니다.
  • object가 [[Construct]] internal method를 가지는 경우, 10.2.2에 정의된 것 또는 10.3.2에 정의된 것 중 하나를 사용합니다.

exotic objectordinary object가 아닌 object입니다.

이 명세는 object의 internal method에 의해 여러 종류의 exotic object를 인식합니다. 특정 종류의 exotic object(예: Array exotic object 또는 bound function exotic object)와 behaviourally equivalent하지만 그 종류에 대해 specified된 동일한 collection of internal method를 가지지 않는 object는 그 종류의 exotic object로 인식되지 않습니다.

Table 4 및 기타 유사한 table의 “Signature” column은 각 internal method의 invocation pattern을 설명합니다. invocation pattern은 항상 descriptive parameter name의 parenthesized list를 포함합니다. parameter name이 ECMAScript type name과 같으면 그 name은 parameter value의 required type을 설명합니다. internal method가 명시적으로 value를 반환하면, parameter list 뒤에 symbol “→”와 returned value의 type name이 옵니다. signature에서 사용되는 type name은 6 절에 정의된 type에 다음 additional name을 보강한 것을 가리킵니다. “any”는 value가 어떤 ECMAScript language type도 될 수 있음을 의미합니다.

parameter 외에도, internal method는 항상 method invocation의 target인 object에 access할 수 있습니다.

internal method는 Completion Record를 implicitly 반환합니다. 이는 invocation pattern에 표시된 return type의 value를 wrap하는 normal completion이거나 throw completion입니다.

Table 4: Essential Internal Methods
Internal Method Signature Description
[[GetPrototypeOf]] ( ) Object | Null 이 object에 대해 inherited property를 제공하는 object를 결정합니다. null value는 inherited property가 없음을 나타냅니다.
[[SetPrototypeOf]] (Object | Null) Boolean inherited property를 제공하는 다른 object와 이 object를 associate합니다. null을 passing하는 것은 inherited property가 없음을 나타냅니다. operation이 successfully completed되었음을 나타내는 true 또는 operation이 successful하지 않았음을 나타내는 false를 반환합니다.
[[IsExtensible]] ( ) Boolean 이 object에 additional property를 add하는 것이 permitted되는지 결정합니다.
[[PreventExtensions]] ( ) Boolean new property가 이 object에 added될 수 있는지 control합니다. operation이 successful이면 true를, unsuccessful이면 false를 반환합니다.
[[GetOwnProperty]] (propertyKey) Undefined | Property Descriptor key가 propertyKey인 이 object의 own property에 대한 Property Descriptor를 반환하거나, 그러한 property가 없으면 undefined를 반환합니다.
[[DefineOwnProperty]] (propertyKey, propertyDesc) Boolean key가 propertyKey인 own property가 propertyDesc가 설명하는 state를 가지도록 create하거나 alter합니다. 해당 property가 successfully created/updated되었으면 true를 반환하고, property를 create하거나 update할 수 없으면 false를 반환합니다.
[[HasProperty]] (propertyKey) Boolean 이 object가 이미 key가 propertyKey인 own 또는 inherited property를 가지고 있는지 나타내는 Boolean value를 반환합니다.
[[Get]] (propertyKey, receiver) any 이 object에서 key가 propertyKey인 property의 value를 반환합니다. property value를 retrieve하기 위해 ECMAScript code가 실행되어야 하는 경우, code를 evaluating할 때 receiverthis value로 사용됩니다.
[[Set]] (propertyKey, value, receiver) Boolean key가 propertyKey인 property의 value를 value로 set합니다. property value를 set하기 위해 ECMAScript code가 실행되어야 하는 경우, code를 evaluating할 때 receiverthis value로 사용됩니다. property value가 set되었으면 true를, set될 수 없으면 false를 반환합니다.
[[Delete]] (propertyKey) Boolean key가 propertyKey인 own property를 이 object에서 remove합니다. property가 deleted되지 않았고 여전히 present하면 false를 반환합니다. property가 deleted되었거나 present하지 않으면 true를 반환합니다.
[[OwnPropertyKeys]] ( ) List of property keys element가 object의 모든 own property keyList를 반환합니다.

Table 5는 function으로 called될 수 있는 object가 support하는 additional essential internal method를 요약합니다. function object[[Call]] internal method를 support하는 object입니다. constructor[[Construct]] internal method를 support하는 object입니다. [[Construct]]를 support하는 모든 object는 [[Call]]을 support해야 합니다. 즉, 모든 constructorfunction object여야 합니다. 따라서 constructorconstructor function 또는 constructor function object라고도 지칭될 수 있습니다.

Table 5: Additional Essential Internal Methods of Function Objects
Internal Method Signature Description
[[Call]] (any, a List of any) any 이 object와 associated된 code를 executes합니다. function call expression을 통해 invoked됩니다. internal method에 대한 argument는 this value와 call expression에 의해 function에 passed된 argument를 element로 하는 List입니다. 이 internal method를 implement하는 object는 callable입니다.
[[Construct]] (a List of any, Object) Object object를 creates합니다. new operator 또는 super call을 통해 invoked됩니다. internal method의 첫 번째 argument는 constructor invocation 또는 super call의 argument를 element로 하는 List입니다. 두 번째 argument는 new operator가 initially applied된 object입니다. 이 internal method를 implement하는 object는 constructors라고 불립니다. function object가 반드시 constructor인 것은 아니며, 그러한 non-constructor function object[[Construct]] internal method를 가지지 않습니다.

ordinary object 및 standard exotic object에 대한 essential internal method의 semantics는 10 절에 specified되어 있습니다. exotic object의 internal method의 specified된 사용이 implementation에서 support되지 않는 경우, 해당 usage를 시도할 때 TypeError exception을 throw해야 합니다.

6.1.7.3 Essential Internal Methods의 Invariants

ECMAScript engine의 Object의 Internal Method는 아래에 specified된 invariant list를 conform해야 합니다. Ordinary ECMAScript Object뿐 아니라 이 명세의 모든 standard exotic object도 이러한 invariant를 유지합니다. ECMAScript Proxy object는 [[ProxyHandler]] object에서 invoked된 trap의 result에 대한 runtime check를 통해 이러한 invariant를 유지합니다.

implementation provided exotic object도 해당 object에 대해 이러한 invariant를 유지해야 합니다. 이러한 invariant를 위반하면 ECMAScript code가 unpredictable behaviour를 보일 수 있고 security issue를 만들 수 있습니다. 그러나 이러한 invariant의 위반은 implementation의 memory safety를 결코 compromise해서는 안 됩니다.

implementation은 essential internal method의 functionality를 implement하면서 invariant를 enforce하지 않는 alternative interface를 제공하는 등의 어떠한 방식으로도 이러한 invariant가 circumvent되도록 허용해서는 안 됩니다.

Definitions:

  • internal method의 target은 internal method가 called되는 object입니다.
  • target은 자신의 [[IsExtensible]] internal method에서 false를 반환하거나, 자신의 [[PreventExtensions]] internal method에서 true를 반환하는 것이 observed되었으면 non-extensible입니다.
  • non-existent property는 non-extensible target에서 own property로 존재하지 않는 property입니다.
  • SameValue에 대한 모든 reference는 SameValue algorithm의 definition을 따릅니다.

Return value:

어떤 internal method가 반환하는 value도 다음 중 하나를 가지는 Completion Record여야 합니다:

  • [[Type]] = normal, [[Target]] = empty, 및 [[Value]] = 해당 internal method에 대해 아래에 표시된 “normal return type”의 value, 또는
  • [[Type]] = throw, [[Target]] = empty, 및 [[Value]] = 어떤 ECMAScript language value.
Note 1

internal method는 continue completion, break completion, 또는 return completion을 반환해서는 안 됩니다.

[[GetPrototypeOf]] ( )

  • normal return type은 Object 또는 Null입니다.
  • target이 non-extensible이고 [[GetPrototypeOf]]가 value proto를 반환하면, 이후 [[GetPrototypeOf]]에 대한 모든 call은 protoSameValue를 반환해야 합니다.
Note 2

object의 prototype chain은 finite length를 가져야 합니다(즉, 어떤 object에서 시작하여 [[GetPrototypeOf]] internal method를 그 result에 recursively applying하면 결국 null value에 도달해야 합니다). 그러나 prototype chain이 [[GetPrototypeOf]]ordinary object definition을 사용하지 않는 exotic object를 포함하는 경우, 이 requirement는 object level invariant로 enforce될 수 없습니다. 그러한 circular prototype chain은 object property에 access할 때 infinite loop를 초래할 수 있습니다.

[[SetPrototypeOf]] ( proto )

  • normal return type은 Boolean입니다.
  • target이 non-extensible이면, proto가 target의 observed [[GetPrototypeOf]] value와 SameValue가 아닌 한 [[SetPrototypeOf]]false를 반환해야 합니다.

[[IsExtensible]] ( )

  • normal return type은 Boolean입니다.
  • [[IsExtensible]]false를 반환하면, target에 대한 [[IsExtensible]]의 모든 future call은 false를 반환해야 합니다.

[[PreventExtensions]] ( )

  • normal return type은 Boolean입니다.
  • [[PreventExtensions]]true를 반환하면, target에 대한 [[IsExtensible]]의 모든 future call은 false를 반환해야 하며 target은 이제 non-extensible로 간주됩니다.

[[GetOwnProperty]] ( propertyKey )

  • normal return type은 Property Descriptor 또는 Undefined입니다.
  • return value가 Property Descriptor이면, 이는 fully populated Property Descriptor여야 합니다.
  • propertyKey가 non-configurable, non-writable own data property로 described되면, [[GetOwnProperty]] ( propertyKey )에 대한 모든 future call은 [[Value]]propertyKey[[Value]] attribute와 SameValueProperty Descriptor를 반환해야 합니다.
  • propertyKey[[Writable]][[Value]] 이외의 attribute가 시간이 지나면서 change될 수 있거나, property가 deleted될 수도 있으면, propertyKey[[Configurable]] attribute는 true여야 합니다.
  • [[Writable]] attribute가 false에서 true로 change될 수 있으면, [[Configurable]] attribute는 true여야 합니다.
  • target이 non-extensible이고 propertyKey가 non-existent이면, target에 대한 [[GetOwnProperty]] (propertyKey)의 모든 future call은 propertyKey를 non-existent로 describe해야 합니다(즉, [[GetOwnProperty]] (propertyKey)는 undefined를 반환해야 합니다).
Note 3

세 번째 invariant의 consequence로, property가 data property로 described되고 시간이 지나면서 다른 value를 반환할 수 있으면, 다른 essential internal method를 통해 value를 change하는 mechanism이 exposed되지 않더라도 [[Writable]][[Configurable]] attribute 중 하나 또는 둘 다 true여야 합니다.

[[DefineOwnProperty]] ( propertyKey, propertyDesc )

  • normal return type은 Boolean입니다.
  • propertyKey가 이전에 target의 non-configurable own property로 observed되었으면, 다음 중 하나가 아닌 한 [[DefineOwnProperty]]false를 반환해야 합니다:
    1. propertyKey가 writable data property인 경우. non-configurable writable data property는 non-configurable non-writable data property로 변경될 수 있습니다.
    2. propertyDesc의 모든 attribute가 propertyKey의 attribute와 SameValue인 경우.
  • target이 non-extensible이고 propertyKey가 non-existent own property이면, [[DefineOwnProperty]] (propertyKey, propertyDesc)는 false를 반환해야 합니다. 즉, non-extensible target object는 new property로 extended될 수 없습니다.

[[HasProperty]] ( propertyKey )

  • normal return type은 Boolean입니다.
  • propertyKey가 이전에 target의 non-configurable own data 또는 accessor property로 observed되었으면, [[HasProperty]]true를 반환해야 합니다.

[[Get]] ( propertyKey, receiver )

  • normal return type은 any ECMAScript language type입니다.
  • propertyKey가 이전에 target의 value value를 가진 non-configurable, non-writable own data property로 observed되었으면, [[Get]]valueSameValue를 반환해야 합니다.
  • propertyKey가 이전에 [[Get]] attribute가 undefined인 target의 non-configurable own accessor property로 observed되었으면, [[Get]] operation은 undefined를 반환해야 합니다.

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

  • normal return type은 Boolean입니다.
  • propertyKey가 이전에 target의 non-configurable, non-writable own data property로 observed되었으면, valuepropertyKey[[Value]] attribute와 SameValue가 아닌 한 [[Set]]false를 반환해야 합니다.
  • propertyKey가 이전에 [[Set]] attribute가 undefined인 target의 non-configurable own accessor property로 observed되었으면, [[Set]] operation은 false를 반환해야 합니다.

[[Delete]] ( propertyKey )

  • normal return type은 Boolean입니다.
  • propertyKey가 이전에 target의 non-configurable own data 또는 accessor property로 observed되었으면, [[Delete]]false를 반환해야 합니다.

[[OwnPropertyKeys]] ( )

  • normal return type은 List입니다.
  • returned List는 duplicate entry를 포함해서는 안 됩니다.
  • returned List의 각 element는 property key여야 합니다.
  • returned List는 이전에 observed된 모든 non-configurable own property의 key를 적어도 포함해야 합니다.
  • target이 non-extensible이면, returned List[[GetOwnProperty]]를 사용하여 observable한 target의 모든 own property의 key만 포함해야 합니다.

[[Call]] ( )

[[Construct]] ( )

  • normal return type은 Object입니다.
  • target은 또한 [[Call]] internal method를 가져야 합니다.

6.1.7.4 Well-Known Intrinsic Objects

Well-known intrinsic은 이 명세의 algorithm에서 명시적으로 referenced되는 built-in object이며, 보통 realm-specific identity를 가집니다. 달리 specified되지 않는 한 각 intrinsic object는 실제로 realm마다 하나씩, 유사한 object의 set에 대응합니다.

이 명세 안에서 %name% 같은 reference는 current realm과 associated되고 해당 name에 대응하는 intrinsic object를 의미합니다. %name.a.b% 같은 reference는, ECMAScript code가 evaluated되기 전에 intrinsic object %name%의 "a" property value의 "b" property가 accessed된 것처럼 의미합니다. current realm과 그 intrinsic의 determination은 9.4에 설명되어 있습니다. well-known intrinsic은 Table 6에 listed되어 있습니다.

Table 6: 잘 알려진 내재 객체
내재 이름 전역 이름 ECMAScript 언어 연관
%AggregateError% "AggregateError" AggregateError 생성자 (20.5.7.1)
%Array% "Array" Array 생성자 (23.1.1)
%ArrayBuffer% "ArrayBuffer" ArrayBuffer 생성자 (25.1.4)
%ArrayIteratorPrototype% Array Iterator 객체의 프로토타입 (23.1.5)
%AsyncDisposableStack% "AsyncDisposableStack" AsyncDisposableStack 생성자 (27.4.1)
%AsyncFromSyncIteratorPrototype% Async-from-Sync Iterator 객체의 프로토타입 (27.1.5)
%AsyncFunction% async 함수 객체의 생성자 (27.10.1)
%AsyncGeneratorFunction% async generator 함수 객체의 생성자 (27.7.1)
%AsyncGeneratorPrototype% async generator 객체의 프로토타입 (27.9)
%AsyncIteratorPrototype% 모든 표준 내장 async iterator 객체가 간접적으로 상속하는 객체
%Atomics% "Atomics" Atomics 객체 (25.4)
%BigInt% "BigInt" BigInt 생성자 (21.2.1)
%BigInt64Array% "BigInt64Array" BigInt64Array 생성자 (23.2)
%BigUint64Array% "BigUint64Array" BigUint64Array 생성자 (23.2)
%Boolean% "Boolean" Boolean 생성자 (20.3.1)
%DataView% "DataView" DataView 생성자 (25.3.2)
%Date% "Date" Date 생성자 (21.4.2)
%decodeURI% "decodeURI" decodeURI 함수 (19.2.6.1)
%decodeURIComponent% "decodeURIComponent" decodeURIComponent 함수 (19.2.6.2)
%DisposableStack% "DisposableStack" DisposableStack 생성자 (27.3.1)
%encodeURI% "encodeURI" encodeURI 함수 (19.2.6.3)
%encodeURIComponent% "encodeURIComponent" encodeURIComponent 함수 (19.2.6.4)
%Error% "Error" Error 생성자 (20.5.1)
%eval% "eval" eval 함수 (19.2.1)
%EvalError% "EvalError" EvalError 생성자 (20.5.5.1)
%FinalizationRegistry% "FinalizationRegistry" FinalizationRegistry 생성자 (26.2.1)
%Float16Array% "Float16Array" Float16Array 생성자 (23.2)
%Float32Array% "Float32Array" Float32Array 생성자 (23.2)
%Float64Array% "Float64Array" Float64Array 생성자 (23.2)
%ForInIteratorPrototype% For-In Iterator 객체의 프로토타입 (14.7.5.10)
%Function% "Function" Function 생성자 (20.2.1)
%GeneratorFunction% generator 함수 객체의 생성자 (27.6.1)
%GeneratorPrototype% generator 객체의 프로토타입 (27.8)
%Int8Array% "Int8Array" Int8Array 생성자 (23.2)
%Int16Array% "Int16Array" Int16Array 생성자 (23.2)
%Int32Array% "Int32Array" Int32Array 생성자 (23.2)
%isFinite% "isFinite" isFinite 함수 (19.2.2)
%isNaN% "isNaN" isNaN 함수 (19.2.3)
%Iterator% "Iterator" Iterator 생성자 (27.1.3.1)
%IteratorHelperPrototype% Iterator Helper 객체의 프로토타입 (27.1.2.1)
%JSON% "JSON" JSON 객체 (25.5)
%Map% "Map" Map 생성자 (24.1.1)
%MapIteratorPrototype% Map Iterator 객체의 프로토타입 (24.1.5)
%Math% "Math" Math 객체 (21.3)
%Number% "Number" Number 생성자 (21.1.1)
%Object% "Object" Object 생성자 (20.1.1)
%parseFloat% "parseFloat" parseFloat 함수 (19.2.4)
%parseInt% "parseInt" parseInt 함수 (19.2.5)
%Promise% "Promise" Promise 생성자 (27.5.3)
%Proxy% "Proxy" Proxy 생성자 (28.2.1)
%RangeError% "RangeError" RangeError 생성자 (20.5.5.2)
%ReferenceError% "ReferenceError" ReferenceError 생성자 (20.5.5.3)
%Reflect% "Reflect" Reflect 객체 (28.1)
%RegExp% "RegExp" RegExp 생성자 (22.2.4)
%RegExpStringIteratorPrototype% RegExp String Iterator 객체의 프로토타입 (22.2.9)
%Set% "Set" Set 생성자 (24.2.2)
%SetIteratorPrototype% Set Iterator 객체의 프로토타입 (24.2.6)
%SharedArrayBuffer% "SharedArrayBuffer" SharedArrayBuffer 생성자 (25.2.3)
%String% "String" String 생성자 (22.1.1)
%StringIteratorPrototype% String Iterator 객체의 프로토타입 (22.1.5)
%SuppressedError% "SuppressedError" SuppressedError 생성자 (20.5.8.1)
%Symbol% "Symbol" Symbol 생성자 (20.4.1)
%SyntaxError% "SyntaxError" SyntaxError 생성자 (20.5.5.4)
%ThrowTypeError% 무조건 %TypeError%의 새 인스턴스를 던지는 함수 객체
%TypedArray% 모든 typed Array 생성자의 슈퍼클래스 (23.2.1)
%TypeError% "TypeError" TypeError 생성자 (20.5.5.5)
%Uint8Array% "Uint8Array" Uint8Array 생성자 (23.2)
%Uint8ClampedArray% "Uint8ClampedArray" Uint8ClampedArray 생성자 (23.2)
%Uint16Array% "Uint16Array" Uint16Array 생성자 (23.2)
%Uint32Array% "Uint32Array" Uint32Array 생성자 (23.2)
%URIError% "URIError" URIError 생성자 (20.5.5.6)
%WeakMap% "WeakMap" WeakMap 생성자 (24.3.1)
%WeakRef% "WeakRef" WeakRef 생성자 (26.1.1)
%WeakSet% "WeakSet" WeakSet 생성자 (24.4.1)
%WrapForValidIteratorPrototype% Iterator.from이 반환하는 감싸진 iterator 객체의 프로토타입 (27.1.3.2.2.1)
Note

Table 103에 additional entry가 있습니다.

6.2 ECMAScript Specification Types

specification type은 ECMAScript language construct와 ECMAScript language type의 semantics를 설명하기 위해 algorithm 안에서 사용되는 meta-value에 대응합니다. specification type에는 Reference Record, List, Completion Record, Property Descriptor, Environment Record, Abstract Closure, Data Block이 포함됩니다. Specification type value는 ECMAScript implementation 안의 특정 entity와 반드시 대응하지는 않는 specification artefact입니다. Specification type value는 ECMAScript expression evaluation의 intermediate result를 설명하는 데 사용될 수 있지만, 그러한 value는 object의 property나 ECMAScript language variable의 value로 저장될 수 없습니다.

6.2.1 Enum Specification Type

Enum은 specification 내부의 value이며 ECMAScript code에서 직접 observable하지 않습니다. Enum은 sans-serif typeface를 사용하여 upper kebab case로 표시됩니다. 예를 들어 Completion Record[[Type]] field는 normal, return, throw와 같은 value를 취합니다. Enum은 name 외의 characteristic을 가지지 않습니다. enum의 name은 다른 enum과 구별하는 것 외의 목적을 가지지 않으며, context에서의 usage나 meaning에 대해 아무것도 imply하지 않습니다.

6.2.2 List and Record Specification Types

List type은 new expression, function call, 그리고 simple ordered list of values가 필요한 다른 algorithm에서 argument list(13.3.8 참조)의 evaluation을 설명하는 데 사용됩니다. List type의 value는 individual value를 포함하는 list element의 ordered sequence일 뿐입니다. 이러한 sequence는 어떤 length도 될 수 있습니다. list의 element는 0-origin index를 사용하여 randomly accessed될 수 있습니다. notation 편의를 위해 array-like syntax를 사용하여 List element에 access할 수 있습니다. 예를 들어 args[2]는 List args의 3rd element를 말하는 shorthand입니다.

algorithm이 order를 지정하지 않고 List의 element를 iterate하면, 사용되는 order는 List 안의 element order입니다.

이 명세 안에서 notation 편의를 위해 literal syntax를 사용하여 새 List value를 표현할 수 있습니다. 예를 들어 « 1, 2 »는 각각 특정 value로 initialized된 두 element를 가진 List value를 정의합니다. 새 empty List는 « »로 표현할 수 있습니다.

이 명세에서 “A, B, ...의 list-concatenation”이라는 phrase(각 argument가 possibly empty List인 경우)는 각 argument의 element를 (순서대로) concatenation한 element를 가진 새 List value를 나타냅니다.

List of Strings에 적용될 때, “lexicographic code unit order에 따라 sorted”라는 phrase는 더 짧은 string의 length까지 각 code unit의 numeric value로 sorting하고, 모두 같으면 더 짧은 string을 더 긴 string보다 앞에 sorting함을 의미하며, 이는 abstract operation IsLessThan에 설명되어 있습니다.

Record type은 이 명세의 algorithm 안에서 data aggregation을 설명하는 데 사용됩니다. Record type value는 하나 이상의 named field로 구성됩니다. 각 field의 value는 ECMAScript language value 또는 specification value입니다. field name은 항상 double bracket으로 둘러싸입니다. 예: [[Value]].

이 명세 안에서 notation 편의를 위해 object literal-like syntax를 사용하여 Record value를 표현할 수 있습니다. 예를 들어 { [[Field1]]: 42, [[Field2]]: false, [[Field3]]: empty }는 세 field를 가지며 각각 특정 value로 initialized된 Record value를 정의합니다. Field name order는 중요하지 않습니다. 명시적으로 listed되지 않은 field는 absent인 것으로 간주됩니다.

specification text와 algorithm에서 dot notation은 Record value의 특정 field를 refer하는 데 사용될 수 있습니다. 예를 들어 R이 이전 paragraph에 표시된 record이면 R.[[Field2]]는 “[[Field2]]라는 name을 가진 R의 field”에 대한 shorthand입니다.

일반적으로 사용되는 Record field combination에 대한 schema에는 name이 붙을 수 있으며, 그 name은 literal Record value의 prefix로 사용되어 설명되는 aggregation의 특정 kind를 identify할 수 있습니다. 예: PropertyDescriptor { [[Value]]: 42, [[Writable]]: false, [[Configurable]]: true }.

6.2.3 Set and Relation Specification Types

Set type은 memory model에서 사용하기 위한 unordered element의 collection을 설명하는 데 사용됩니다. 이는 같은 name의 ECMAScript collection type과 distinct합니다. 구별을 위해, 이 명세 안에서 ECMAScript collection의 instance는 일관되게 “Set objects”라고 지칭됩니다. Set type의 value는 simple collection of elements이며, 어떤 element도 한 번보다 많이 나타나지 않습니다. element는 Set에 added되거나 removed될 수 있습니다. Set은 서로 unioned, intersected, subtracted될 수 있습니다.

Relation type은 Set에 대한 constraint를 설명하는 데 사용됩니다. Relation type의 value는 그 value domain에서 온 ordered pair of values의 Set입니다. 예를 들어 Memory event에 대한 Relation은 Memory event의 ordered pair의 set입니다. Relation RR의 value domain 안의 두 value ab에 대해, a R b는 ordered pair (a, b)가 R의 member임을 말하는 shorthand입니다. 어떤 condition에 관해 least Relation인 Relation은 그 condition을 만족하는 가장 작은 Relation입니다.

strict partial order는 다음을 만족하는 Relation value R입니다.

  • R의 domain 안의 모든 a, b, c에 대해:

    • a R a인 경우는 없고,
    • a R b이고 b R c이면, a R c입니다.
Note 1

위의 두 property는 각각 irreflexivity와 transitivity라고 불립니다.

strict total order는 다음을 만족하는 Relation value R입니다.

  • R의 domain 안의 모든 a, b, c에 대해:

    • ab이거나 a R b이거나 b R a이고,
    • a R a인 경우는 없고,
    • a R b이고 b R c이면, a R c입니다.
Note 2

위의 세 property는 각각 totality, irreflexivity, transitivity라고 불립니다.

6.2.4 Completion Record Specification Type

Completion Record specification type은 nonlocal transfer of control을 수행하는 statement(break, continue, return, throw)의 behaviour와 같은 value 및 control flow의 runtime propagation을 설명하는 데 사용됩니다.

Completion Record는 Table 7에 정의된 field를 가집니다.

Table 7: Completion Record Fields
Field Name Value Meaning
[[Type]] normal, break, continue, return, or throw 발생한 completion의 type입니다.
[[Value]] Completion Record를 제외한 모든 value 생성된 value입니다.
[[Target]] String 또는 empty directed control transfer를 위한 target label입니다.

다음 shorthand term은 때때로 Completion Record를 refer하는 데 사용됩니다.

  • normal completion[[Type]] value가 normal인 모든 Completion Record를 가리킵니다.
  • break completion[[Type]] value가 break인 모든 Completion Record를 가리킵니다.
  • continue completion[[Type]] value가 continue인 모든 Completion Record를 가리킵니다.
  • return completion[[Type]] value가 return인 모든 Completion Record를 가리킵니다.
  • throw completion[[Type]] value가 throw인 모든 Completion Record를 가리킵니다.
  • abrupt completion[[Type]] value가 normal이 아닌 모든 Completion Record를 가리킵니다.
  • 어떤 type의 value를 normal completion containing한다는 것은 [[Value]] field에 그 type의 value를 가진 normal completion을 가리킵니다.

이 명세에서 정의된 callable object는 normal completion 또는 throw completion만 반환합니다. 다른 종류의 Completion Record를 반환하는 것은 editorial error로 간주됩니다.

Implementation-defined callable object는 normal completion 또는 throw completion 중 하나를 반환해야 합니다.

6.2.4.1 NormalCompletion ( value )

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

  1. Completion Record { [[Type]]: normal, [[Value]]: value, [[Target]]: empty }를 반환한다.

6.2.4.2 ThrowCompletion ( value )

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

  1. Completion Record { [[Type]]: throw, [[Value]]: value, [[Target]]: empty }를 반환한다.

6.2.4.3 ReturnCompletion ( value )

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

  1. Completion Record { [[Type]]: return, [[Value]]: value, [[Target]]: empty }를 반환한다.

6.2.4.4 UpdateEmpty ( completionRecord, value )

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

  1. Assert: completionRecordreturn completion 또는 throw completion이면, completionRecord.[[Value]]empty가 아니다.
  2. completionRecord.[[Value]]empty가 아니면, ? completionRecord를 반환한다.
  3. Completion Record { [[Type]]: completionRecord.[[Type]], [[Value]]: value, [[Target]]: completionRecord.[[Target]] }를 반환한다.

6.2.5 Reference Record Specification Type

Reference Record type은 delete, typeof, assignment operator, super keyword 및 기타 language feature와 같은 operator의 behaviour를 설명하는 데 사용됩니다. 예를 들어 assignment의 left-hand operand는 Reference Record를 생성할 것으로 expected됩니다.

Reference Record는 resolved name 또는 (possibly not-yet-resolved) property binding입니다. 그 field는 Table 8에 의해 정의됩니다.

Table 8: Reference Record Fields
Field Name Value Meaning
[[Base]] ECMAScript language value, Environment Record, 또는 unresolvable binding을 hold하는 value 또는 Environment Record입니다. unresolvable[[Base]]는 binding이 resolve될 수 없었음을 나타냅니다.
[[ReferencedName]] ECMAScript language value 또는 Private Name binding의 name입니다. [[Base]] value가 Environment Record이면 항상 String입니다. 그렇지 않으면 ToPropertyKey가 수행될 때까지 String이나 Symbol이 아닌 ECMAScript language value일 수 있습니다.
[[Strict]] Boolean Reference Recordstrict mode code에서 originated되었으면 true, 그렇지 않으면 false입니다.
[[ThisValue]] ECMAScript language value 또는 empty empty가 아니면, Reference Recordsuper keyword를 사용하여 표현된 property binding을 나타냅니다. 이는 Super Reference Record라고 불리며, 그 [[Base]] value는 결코 Environment Record가 아닙니다. 이 경우 [[ThisValue]] field는 Reference Record가 생성된 시점의 this value를 hold합니다.

다음 abstract operation은 Reference Record를 대상으로 operate하기 위해 이 명세에서 사용됩니다:

6.2.5.1 IsPropertyReference ( refRecord )

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

  1. refRecord.[[Base]]unresolvable이면, false를 반환한다.
  2. refRecord.[[Base]]Environment Record이면, false를 반환한다.
  3. true를 반환한다.

6.2.5.2 IsUnresolvableReference ( refRecord )

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

  1. refRecord.[[Base]]unresolvable이면, true를 반환한다.
  2. false를 반환한다.

6.2.5.3 IsSuperReference ( refRecord )

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

  1. refRecord.[[ThisValue]]empty이면, false를 반환한다.
  2. true를 반환한다.

6.2.5.4 IsPrivateReference ( refRecord )

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

  1. refRecord.[[ReferencedName]]Private Name이면, true를 반환한다.
  2. false를 반환한다.

6.2.5.5 GetValue ( refRecord )

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

  1. refRecordReference Record가 아니면, refRecord를 반환한다.
  2. IsUnresolvableReference(refRecord)가 true이면, ReferenceError exception을 throw한다.
  3. IsPropertyReference(refRecord)가 true이면, 다음을 수행한다.
    1. baseObj를 ? ToObject(refRecord.[[Base]])로 둔다.
    2. IsPrivateReference(refRecord)가 true이면, 다음을 수행한다.
      1. PrivateGet(baseObj, refRecord.[[ReferencedName]])을 반환한다.
    3. refRecord.[[ReferencedName]]property key가 아니면, 다음을 수행한다.
      1. refRecord.[[ReferencedName]]을 ? ToPropertyKey(refRecord.[[ReferencedName]])로 설정한다.
    4. baseObj.[[Get]](refRecord.[[ReferencedName]], GetThisValue(refRecord))를 반환한다.
  4. baserefRecord.[[Base]]로 둔다.
  5. Assert: baseEnvironment Record이다.
  6. base.GetBindingValue(refRecord.[[ReferencedName]], refRecord.[[Strict]])를 반환한다(9.1 참조).
Note

step 3.a에서 생성될 수 있는 object는 위 abstract operation 및 ordinary object [[Get]] internal method 밖에서 accessible하지 않습니다. implementation은 object의 실제 생성을 피하도록 선택할 수도 있습니다.

6.2.5.6 PutValue ( refRecord, value )

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

  1. refRecordReference Record가 아니면, ReferenceError exception을 throw한다.
  2. IsUnresolvableReference(refRecord)가 true이면, 다음을 수행한다.
    1. refRecord.[[Strict]]true이면, ReferenceError exception을 throw한다.
    2. globalObjGetGlobalObject()로 둔다.
    3. Set(globalObj, refRecord.[[ReferencedName]], value, false)를 수행한다.
    4. unused를 반환한다.
  3. IsPropertyReference(refRecord)가 true이면, 다음을 수행한다.
    1. baseObj를 ? ToObject(refRecord.[[Base]])로 둔다.
    2. IsPrivateReference(refRecord)가 true이면, 다음을 수행한다.
      1. PrivateSet(baseObj, refRecord.[[ReferencedName]], value)를 반환한다.
    3. refRecord.[[ReferencedName]]property key가 아니면, 다음을 수행한다.
      1. refRecord.[[ReferencedName]]을 ? ToPropertyKey(refRecord.[[ReferencedName]])로 설정한다.
    4. succeeded를 ? baseObj.[[Set]](refRecord.[[ReferencedName]], value, GetThisValue(refRecord))로 둔다.
    5. succeededfalse이고 refRecord.[[Strict]]true이면, TypeError exception을 throw한다.
    6. unused를 반환한다.
  4. baserefRecord.[[Base]]로 둔다.
  5. Assert: baseEnvironment Record이다.
  6. base.SetMutableBinding(refRecord.[[ReferencedName]], value, refRecord.[[Strict]])를 반환한다(9.1 참조).
Note

step 3.a에서 생성될 수 있는 object는 위 abstract operation 및 ordinary object [[Set]] internal method 밖에서 accessible하지 않습니다. implementation은 해당 object의 실제 생성을 피하도록 선택할 수도 있습니다.

6.2.5.7 GetThisValue ( refRecord )

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

  1. Assert: IsPropertyReference(refRecord)는 true이다.
  2. IsSuperReference(refRecord)가 true이면, refRecord.[[ThisValue]]를 반환한다.
  3. refRecord.[[Base]]를 반환한다.

6.2.5.8 InitializeReferencedBinding ( refRecord, value )

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

  1. Assert: IsUnresolvableReference(refRecord)는 false이다.
  2. baserefRecord.[[Base]]로 둔다.
  3. Assert: baseEnvironment Record이다.
  4. base.InitializeBinding(refRecord.[[ReferencedName]], value)를 반환한다.

6.2.5.9 MakePrivateReference ( baseValue, privateIdentifier )

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

  1. privateEnvrunning execution context의 PrivateEnvironment로 둔다.
  2. Assert: privateEnvnull이 아니다.
  3. privateNameResolvePrivateIdentifier(privateEnv, privateIdentifier)로 둔다.
  4. Reference Record { [[Base]]: baseValue, [[ReferencedName]]: privateName, [[Strict]]: true, [[ThisValue]]: empty }를 반환한다.

6.2.6 Property Descriptor Specification Type

Property Descriptor type은 Object property attribute의 manipulation과 reification을 설명하는 데 사용됩니다. Property Descriptor는 zero or more field를 가진 Record이며, 각 field의 name은 attribute name이고 그 value는 6.1.7.1에 specified된 대응하는 attribute value입니다. Property Descriptor record의 literal description에 tag를 붙이기 위해 이 명세 안에서 사용되는 schema name은 “PropertyDescriptor”입니다.

Property Descriptor value는 특정 field의 existence 또는 use에 따라 data Property Descriptor와 accessor Property Descriptor로 further classified될 수 있습니다. data Property Descriptor는 [[Value]] 또는 [[Writable]]이라는 이름의 field 중 하나를 포함하는 것입니다. accessor Property Descriptor는 [[Get]] 또는 [[Set]]이라는 이름의 field 중 하나를 포함하는 것입니다. 어떤 Property Descriptor든 [[Enumerable]][[Configurable]]이라는 이름의 field를 가질 수 있습니다. Property Descriptor value는 data Property Descriptor이면서 동시에 accessor Property Descriptor일 수 없습니다. 그러나 둘 다 아닐 수는 있습니다(이 경우 generic Property Descriptor입니다). fully populated Property Descriptor는 accessor Property Descriptor 또는 data Property Descriptor이며, Table 3에 정의된 대응하는 field를 모두 가진 것입니다.

다음 abstract operation은 Property Descriptor value를 대상으로 operate하기 위해 이 명세에서 사용됩니다:

6.2.6.1 IsAccessorDescriptor ( propertyDesc )

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

  1. propertyDesc[[Get]] field를 가지면, true를 반환한다.
  2. propertyDesc[[Set]] field를 가지면, true를 반환한다.
  3. false를 반환한다.

6.2.6.2 IsDataDescriptor ( propertyDesc )

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

  1. propertyDesc[[Value]] field를 가지면, true를 반환한다.
  2. propertyDesc[[Writable]] field를 가지면, true를 반환한다.
  3. false를 반환한다.

6.2.6.3 IsGenericDescriptor ( propertyDesc )

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

  1. IsAccessorDescriptor(propertyDesc)가 true이면, false를 반환한다.
  2. IsDataDescriptor(propertyDesc)가 true이면, false를 반환한다.
  3. true를 반환한다.

6.2.6.4 FromPropertyDescriptor ( propertyDesc )

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

  1. propertyDescundefined이면, undefined를 반환한다.
  2. objOrdinaryObjectCreate(%Object.prototype%)로 둔다.
  3. Assert: obj는 own property가 없는 extensible ordinary object이다.
  4. propertyDesc[[Value]] field를 가지면, 다음을 수행한다.
    1. CreateDataPropertyOrThrow(obj, "value", propertyDesc.[[Value]])를 수행한다.
  5. propertyDesc[[Writable]] field를 가지면, 다음을 수행한다.
    1. CreateDataPropertyOrThrow(obj, "writable", propertyDesc.[[Writable]])를 수행한다.
  6. propertyDesc[[Get]] field를 가지면, 다음을 수행한다.
    1. CreateDataPropertyOrThrow(obj, "get", propertyDesc.[[Get]])를 수행한다.
  7. propertyDesc[[Set]] field를 가지면, 다음을 수행한다.
    1. CreateDataPropertyOrThrow(obj, "set", propertyDesc.[[Set]])를 수행한다.
  8. propertyDesc[[Enumerable]] field를 가지면, 다음을 수행한다.
    1. CreateDataPropertyOrThrow(obj, "enumerable", propertyDesc.[[Enumerable]])를 수행한다.
  9. propertyDesc[[Configurable]] field를 가지면, 다음을 수행한다.
    1. CreateDataPropertyOrThrow(obj, "configurable", propertyDesc.[[Configurable]])를 수행한다.
  10. obj를 반환한다.

6.2.6.5 ToPropertyDescriptor ( obj )

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

  1. obj가 Object가 아니면, TypeError exception을 throw한다.
  2. propertyDesc를 initially field가 없는 새 Property Descriptor로 둔다.
  3. hasEnumerable을 ? HasProperty(obj, "enumerable")로 둔다.
  4. hasEnumerabletrue이면, 다음을 수행한다.
    1. enumerableToBoolean(? Get(obj, "enumerable"))으로 둔다.
    2. propertyDesc.[[Enumerable]]enumerable로 설정한다.
  5. hasConfigurable을 ? HasProperty(obj, "configurable")로 둔다.
  6. hasConfigurabletrue이면, 다음을 수행한다.
    1. configurableToBoolean(? Get(obj, "configurable"))으로 둔다.
    2. propertyDesc.[[Configurable]]configurable로 설정한다.
  7. hasValue를 ? HasProperty(obj, "value")로 둔다.
  8. hasValuetrue이면, 다음을 수행한다.
    1. value를 ? Get(obj, "value")로 둔다.
    2. propertyDesc.[[Value]]value로 설정한다.
  9. hasWritable을 ? HasProperty(obj, "writable")로 둔다.
  10. hasWritabletrue이면, 다음을 수행한다.
    1. writableToBoolean(? Get(obj, "writable"))으로 둔다.
    2. propertyDesc.[[Writable]]writable로 설정한다.
  11. hasGet을 ? HasProperty(obj, "get")로 둔다.
  12. hasGettrue이면, 다음을 수행한다.
    1. getter를 ? Get(obj, "get")로 둔다.
    2. IsCallable(getter)가 false이고 getterundefined가 아니면, TypeError exception을 throw한다.
    3. propertyDesc.[[Get]]getter로 설정한다.
  13. hasSet을 ? HasProperty(obj, "set")로 둔다.
  14. hasSettrue이면, 다음을 수행한다.
    1. setter를 ? Get(obj, "set")로 둔다.
    2. IsCallable(setter)가 false이고 setterundefined가 아니면, TypeError exception을 throw한다.
    3. propertyDesc.[[Set]]setter로 설정한다.
  15. propertyDesc[[Get]] field를 가지거나 propertyDesc[[Set]] field를 가지면, 다음을 수행한다.
    1. propertyDesc[[Value]] field를 가지거나 propertyDesc[[Writable]] field를 가지면, TypeError exception을 throw한다.
  16. propertyDesc를 반환한다.

6.2.6.6 CompletePropertyDescriptor ( propertyDesc )

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

  1. likeRecord { [[Value]]: undefined, [[Writable]]: false, [[Get]]: undefined, [[Set]]: undefined, [[Enumerable]]: false, [[Configurable]]: false }로 둔다.
  2. IsGenericDescriptor(propertyDesc)가 true이거나 IsDataDescriptor(propertyDesc)가 true이면, 다음을 수행한다.
    1. propertyDesc[[Value]] field를 가지지 않으면, propertyDesc.[[Value]]like.[[Value]]로 설정한다.
    2. propertyDesc[[Writable]] field를 가지지 않으면, propertyDesc.[[Writable]]like.[[Writable]]로 설정한다.
  3. 그렇지 않으면,
    1. propertyDesc[[Get]] field를 가지지 않으면, propertyDesc.[[Get]]like.[[Get]]로 설정한다.
    2. propertyDesc[[Set]] field를 가지지 않으면, propertyDesc.[[Set]]like.[[Set]]로 설정한다.
  4. propertyDesc[[Enumerable]] field를 가지지 않으면, propertyDesc.[[Enumerable]]like.[[Enumerable]]로 설정한다.
  5. propertyDesc[[Configurable]] field를 가지지 않으면, propertyDesc.[[Configurable]]like.[[Configurable]]로 설정한다.
  6. unused를 반환한다.

6.2.7 Environment Record Specification Type

Environment Record type은 nested function 및 block에서 name resolution의 behaviour를 설명하는 데 사용됩니다. 이 type과 그 operation은 9.1에 정의되어 있습니다.

6.2.8 Abstract Closure Specification Type

Abstract Closure specification type은 algorithm step과 value collection을 함께 refer하는 데 사용됩니다. Abstract Closure는 meta-value이며 closure(arg1, arg2)와 같은 function application style을 사용하여 invoked됩니다. abstract operation처럼 invocation은 Abstract Closure가 설명하는 algorithm step을 수행합니다.

Abstract Closure를 생성하는 algorithm step에서 value는 “capture”라는 verb 뒤에 alias list를 사용하여 captured됩니다. Abstract Closure가 생성되면, 그 시점에 각 alias와 associated된 value를 capture합니다. Abstract Closure가 called될 때 수행될 algorithm을 specify하는 step에서 각 captured value는 value를 capture하는 데 사용된 alias로 referred됩니다.

Abstract Closure가 Completion Record를 반환하면, 그 Completion Recordnormal completion 또는 throw completion이어야 합니다.

Abstract Closure는 다른 algorithm의 일부로 inline 생성되며, 다음 example에 표시되어 있습니다.

  1. addend를 41로 둔다.
  2. closure를 parameter (x)를 가지고 addend를 capture하며 called될 때 다음 step을 수행하는 새 Abstract Closure로 둔다:
    1. x + addend를 반환한다.
  3. valueclosure(1)로 둔다.
  4. Assert: value는 42이다.

6.2.9 Data Blocks

Data Block specification type은 byte-sized(8 bit) numeric value의 distinct하고 mutable한 sequence를 설명하는 데 사용됩니다. byte value는 0부터 255까지의 inclusive interval에 있는 integer입니다. Data Block value는 fixed number of byte로 생성되며, 각 byte의 initial value는 0입니다.

이 명세 안에서 notation 편의를 위해 array-like syntax를 사용하여 Data Block value의 individual byte에 access할 수 있습니다. 이 notation은 Data Block value를 byte의 0-based integer-indexed sequence로 나타냅니다. 예를 들어 dataBlock가 5 byte Data Block value이면 dataBlock[2]를 사용하여 그 3rd byte에 access할 수 있습니다.

여러 agent에서 concurrently referenced될 수 있는 memory에 resides하는 data block은 Shared Data Block으로 지정됩니다. Shared Data Block은 (Shared Data Block value의 equality testing 목적상) address-free인 identity를 가집니다. 이는 block이 어떤 process에 mapped되는 virtual address에 묶이는 것이 아니라, block이 나타내는 memory의 location set에 묶입니다. 두 data block은 자신들이 포함하는 location set이 equal할 때만 equal합니다. 그렇지 않으면 equal하지 않으며 자신들이 포함하는 location set의 intersection은 empty입니다. 마지막으로, Shared Data Block은 Data Block과 distinguished될 수 있습니다.

Shared Data Block의 semantics는 memory model에 의해 Shared Data Block event를 사용하여 정의됩니다. 아래 abstract operation은 Shared Data Block event를 도입하며 evaluation semantics와 memory model의 event semantics 사이의 interface로 동작합니다. event는 candidate execution을 형성하고, memory model은 그 위에서 filter로 동작합니다. full semantics는 memory model을 참조하십시오.

Shared Data Block eventmemory model에 정의된 Record로 modelled됩니다.

다음 abstract operation은 Data Block value를 대상으로 operate하기 위해 이 명세에서 사용됩니다:

6.2.9.1 CreateByteDataBlock ( size )

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

  1. size > 253 - 1이면, RangeError exception을 throw한다.
  2. dataBlocksize byte로 구성된 새 Data Block value로 둔다. 그러한 Data Block을 생성하는 것이 impossible하면, RangeError exception을 throw한다.
  3. dataBlock의 모든 byte를 0으로 설정한다.
  4. dataBlock를 반환한다.

6.2.9.2 CreateSharedByteDataBlock ( size )

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

  1. dataBlocksize byte로 구성된 새 Shared Data Block value로 둔다. 그러한 Shared Data Block을 생성하는 것이 impossible하면, RangeError exception을 throw한다.
  2. agentRecordsurrounding agentAgent Record로 둔다.
  3. executionagentRecord.[[CandidateExecution]]으로 둔다.
  4. eventsRecord[[AgentSignifier]]AgentSignifier()인 execution.[[EventsRecords]]Agent Events Record로 둔다.
  5. zero를 « 0 »로 둔다.
  6. dataBlock의 각 index index에 대해, 다음을 수행한다.
    1. WriteSharedMemory { [[Order]]: init, [[NoTear]]: true, [[Block]]: dataBlock, [[ByteIndex]]: index, [[ElementSize]]: 1, [[Payload]]: zero }를 eventsRecord.[[EventList]]에 append한다.
  7. dataBlock를 반환한다.

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

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

  1. Assert: fromBlocktoBlock은 distinct value이다.
  2. fromSizefromBlock 안의 byte 수로 둔다.
  3. Assert: fromIndex + countfromSize.
  4. toSizetoBlock 안의 byte 수로 둔다.
  5. Assert: toIndex + counttoSize.
  6. count > 0인 동안 Repeat한다.
    1. fromBlockShared Data Block이면, 다음을 수행한다.
      1. agentRecordsurrounding agentAgent Record로 둔다.
      2. executionagentRecord.[[CandidateExecution]]으로 둔다.
      3. eventsRecord[[AgentSignifier]]AgentSignifier()인 execution.[[EventsRecords]]Agent Events Record로 둔다.
      4. bytes를 nondeterministically chosen byte value를 sole element로 하는 List로 둔다.
      5. NOTE: implementation에서 bytes는 underlying hardware의 non-atomic read instruction 결과이다. nondeterminism은 weak consistency를 가진 hardware의 observable behaviour를 describe하기 위한 memory model의 semantic prescription이다.
      6. readEventReadSharedMemory { [[Order]]: unordered, [[NoTear]]: true, [[Block]]: fromBlock, [[ByteIndex]]: fromIndex, [[ElementSize]]: 1 }로 둔다.
      7. readEventeventsRecord.[[EventList]]에 append한다.
      8. Chosen Value Record { [[Event]]: readEvent, [[ChosenValue]]: bytes }를 execution.[[ChosenValues]]에 append한다.
      9. toBlockShared Data Block이면, 다음을 수행한다.
        1. WriteSharedMemory { [[Order]]: unordered, [[NoTear]]: true, [[Block]]: toBlock, [[ByteIndex]]: toIndex, [[ElementSize]]: 1, [[Payload]]: bytes }를 eventsRecord.[[EventList]]에 append한다.
      10. 그렇지 않으면,
        1. toBlock[toIndex]를 bytes[0]로 설정한다.
    2. 그렇지 않으면,
      1. Assert: toBlockShared Data Block이 아니다.
      2. toBlock[toIndex]를 fromBlock[fromIndex]로 설정한다.
    3. toIndextoIndex + 1로 설정한다.
    4. fromIndexfromIndex + 1로 설정한다.
    5. countcount - 1로 설정한다.
  7. unused를 반환한다.

6.2.10 PrivateElement Specification Type

PrivateElement 타입은 비공개 클래스 필드, 메서드 및 접근자 명세에서 사용되는 Record이다. Property Descriptor는 비공개 요소에 사용되지 않지만, 비공개 필드는 구성 불가능하고 열거 불가능하며 쓰기 가능한 데이터 프로퍼티와 유사하게 동작하고, 비공개 메서드는 구성 불가능하고 열거 불가능하며 쓰기 불가능한 데이터 프로퍼티와 유사하게 동작하며, 비공개 접근자는 구성 불가능하고 열거 불가능한 접근자 프로퍼티와 유사하게 동작한다.

PrivateElement 타입의 값은 Table 9에 의해 필드가 정의되는 Record 값이다. 이러한 값은 PrivateElements라고 한다.

Table 9: PrivateElement Fields
Field Name 그것이 present하는 [[Kind]] field의 Values Value Meaning
[[Key]] All Private Name field, method, 또는 accessor의 name입니다.
[[Kind]] All field, method, or accessor element의 kind입니다.
[[Value]] field and method ECMAScript language value field의 value입니다.
[[Get]] accessor function object 또는 undefined private accessor의 getter입니다.
[[Set]] accessor function object 또는 undefined private accessor의 setter입니다.

6.2.11 ClassFieldDefinition Record Specification Type

ClassFieldDefinition 타입은 클래스 필드 명세에서 사용되는 Record이다.

ClassFieldDefinition 타입의 값은 Table 10에 의해 필드가 정의되는 Record 값이다. 이러한 값은 ClassFieldDefinition Records라고 한다.

Table 10: ClassFieldDefinition Record Fields
Field Name Value Meaning
[[Name]] Private Name, String, 또는 Symbol field의 name입니다.
[[Initializer]] ECMAScript function object 또는 empty field의 initializer입니다(있다면).

6.2.12 Private Names

Private Name specification type은 private class element(field, method, accessor)의 key를 나타내는 globally unique value(그 밖에는 indistinguishable하더라도 다른 어떤 Private Name과도 다른 value)를 설명하는 데 사용됩니다. 각 Private Name은 String인 immutable [[Description]] internal slot을 가집니다. Private Name은 PrivateFieldAdd 또는 PrivateMethodOrAccessorAdd를 사용하여 어떤 ECMAScript object에도 installed될 수 있으며, 그런 다음 PrivateGetPrivateSet을 사용하여 read 또는 written될 수 있습니다.

6.2.13 ClassStaticBlockDefinition Record Specification Type

ClassStaticBlockDefinition Record는 class static initialization block을 위한 executable code를 encapsulate하는 데 사용되는 Record value입니다.

ClassStaticBlockDefinition Record는 Table 11에 listed된 field를 가집니다.

Table 11: ClassStaticBlockDefinition Record Fields
Field Name Value Meaning
[[BodyFunction]] ECMAScript function object class의 static initialization 중에 called될 function object입니다.

7 Abstract Operations

이 operation들은 ECMAScript language의 일부가 아닙니다. 이들은 ECMAScript language의 semantics specification을 돕기 위해서만 여기에 정의됩니다. 더 specialized된 다른 abstract operation은 이 명세 전반에 걸쳐 정의됩니다.

7.1 Type Conversion

ECMAScript language는 필요에 따라 automatic type conversion을 implicitly 수행합니다. 특정 construct의 semantics를 명확히 하기 위해 conversion abstract operation의 set을 정의하는 것이 유용합니다. conversion abstract operation은 polymorphic합니다. 즉, 어떤 ECMAScript language type의 value도 accept할 수 있습니다. 그러나 이러한 operation에는 다른 specification type이 사용되지 않습니다.

BigInt type은 ECMAScript language에서 implicit conversion을 가지지 않습니다. programmer는 다른 type의 value를 convert하려면 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를 non-Object type으로 convert합니다. object가 둘 이상의 primitive type으로 convert할 수 있으면, optional hint preferredType을 사용하여 그 type을 favour할 수 있습니다. It performs the following steps when called:

  1. input이 Object이면, 다음을 수행한다.
    1. exoticToPrimitive를 ? GetMethod(input, %Symbol.toPrimitive%)로 둔다.
    2. exoticToPrimitiveundefined가 아니면, 다음을 수행한다.
      1. preferredType이 present하지 않으면, 다음을 수행한다.
        1. hint"default"로 둔다.
      2. 그렇지 않고 preferredTypestring이면, 다음을 수행한다.
        1. hint"string"으로 둔다.
      3. 그렇지 않으면,
        1. Assert: preferredTypenumber이다.
        2. hint"number"로 둔다.
      4. result를 ? Call(exoticToPrimitive, input, « hint »)로 둔다.
      5. result가 Object가 아니면, result를 반환한다.
      6. TypeError exception을 throw한다.
    3. preferredType이 present하지 않으면, preferredTypenumber로 설정한다.
    4. OrdinaryToPrimitive(input, preferredType)를 반환한다.
  2. input을 반환한다.
Note

ToPrimitive가 hint 없이 호출되면, 일반적으로 hint가 number인 것처럼 behave합니다. 그러나 object는 %Symbol.toPrimitive% method를 정의하여 이 behaviour를 over-ride할 수 있습니다. 이 명세에서 정의된 object 중 Date(21.4.4.45 참조)와 Symbol object(20.4.3.5 참조)만 default ToPrimitive behaviour를 over-ride합니다. Date는 hint의 absence를 hint가 string인 것처럼 취급합니다.

7.1.1.1 OrdinaryToPrimitive ( obj, hint )

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

  1. hintstring이면, 다음을 수행한다.
    1. methodNames를 « "toString", "valueOf" »로 둔다.
  2. 그렇지 않으면,
    1. methodNames를 « "valueOf", "toString" »로 둔다.
  3. methodNames의 각 element name에 대해, 다음을 수행한다.
    1. method를 ? Get(obj, name)으로 둔다.
    2. IsCallable(method)가 true이면, 다음을 수행한다.
      1. result를 ? Call(method, obj)로 둔다.
      2. result가 Object가 아니면, result를 반환한다.
  4. TypeError exception을 throw한다.

7.1.2 ToBoolean ( arg )

The abstract operation ToBoolean takes argument arg (an ECMAScript language value) and returns a Boolean. argBoolean type의 value로 convert합니다. It performs the following steps when called:

  1. arg가 Boolean이면, arg를 반환한다.
  2. argundefined, null, +0𝔽, -0𝔽, NaN, 0, 또는 empty String 중 하나이면, false를 반환한다.
  3. host가 web browser이거나 그 밖에 [[IsHTMLDDA]] Internal Slot를 support하면, 다음을 수행한다.
    1. arg가 Object이고 arg[[IsHTMLDDA]] internal slot을 가지면, false를 반환한다.
  4. true를 반환한다.

7.1.3 ToNumeric ( arg )

The abstract operation ToNumeric takes argument arg (an ECMAScript language value) and returns either a normal completion containing either a Number or a BigInt, or a throw completion. arg를 Number 또는 BigInt로 convert한 값을 반환합니다. It performs the following steps when called:

  1. primitiveValue를 ? ToPrimitive(arg, number)로 둔다.
  2. primitiveValue가 BigInt이면, primitiveValue를 반환한다.
  3. ToNumber(primitiveValue)를 반환한다.

7.1.4 ToNumber ( arg )

The abstract operation ToNumber takes argument arg (an ECMAScript language value) and returns either a normal completion containing a Number or a throw completion. argNumber type의 value로 convert합니다. It performs the following steps when called:

  1. arg가 Number이면, arg를 반환한다.
  2. arg가 Symbol 또는 BigInt이면, TypeError exception을 throw한다.
  3. argundefined이면, NaN을 반환한다.
  4. argnull 또는 false이면, +0𝔽를 반환한다.
  5. argtrue이면, 1𝔽를 반환한다.
  6. arg가 String이면, StringToNumber(arg)를 반환한다.
  7. Assert: arg는 Object이다.
  8. primitiveValue를 ? ToPrimitive(arg, number)로 둔다.
  9. Assert: primitiveValue는 Object가 아니다.
  10. ToNumber(primitiveValue)를 반환한다.

7.1.4.1 String Type에 적용되는 ToNumber

abstract operation StringToNumber는 다음 grammar를 사용하여 String value를 Number value로 convert하는 방법을 specified합니다.

Syntax

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

위에서 명시적으로 정의되지 않은 모든 grammar symbol은 numeric literal에 대한 Lexical Grammar(12.9.3)에서 사용되는 definition을 가집니다.

Note

StringNumericLiteral의 syntax와 NumericLiteral 사이에는 몇 가지 difference가 있음에 유의해야 합니다:

7.1.4.1.1 StringToNumber ( string )

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

  1. literalParseText(string, StringNumericLiteral)로 둔다.
  2. literal이 error의 List이면, NaN을 반환한다.
  3. literalStringNumericValue를 반환한다.

7.1.4.1.2 Runtime Semantics: StringNumericValue

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

Note

StringNumericLiteral을 Number value로 conversion하는 것은 전체적으로 NumericLiteralNumericValue determination(12.9.3 참조)과 유사하지만, 일부 detail은 다릅니다.

It is defined piecewise over the following productions:

StringNumericLiteral ::: StrWhiteSpaceopt
  1. +0𝔽를 반환한다.
StringNumericLiteral ::: StrWhiteSpaceopt StrNumericLiteral StrWhiteSpaceopt
  1. StrNumericLiteralStringNumericValue를 반환한다.
StrNumericLiteral ::: NonDecimalIntegerLiteral
  1. 𝔽(NonDecimalIntegerLiteral의 MV)를 반환한다.
StrDecimalLiteral ::: - StrUnsignedDecimalLiteral
  1. aStrUnsignedDecimalLiteralStringNumericValue로 둔다.
  2. a+0𝔽이면, -0𝔽를 반환한다.
  3. -a를 반환한다.
StrUnsignedDecimalLiteral ::: Infinity
  1. +∞𝔽를 반환한다.
StrUnsignedDecimalLiteral ::: DecimalDigits . DecimalDigitsopt ExponentPartopt
  1. a를 첫 번째 DecimalDigits의 MV로 둔다.
  2. 두 번째 DecimalDigits가 present하면, 다음을 수행한다.
    1. b를 두 번째 DecimalDigits의 MV로 둔다.
    2. n을 두 번째 DecimalDigits 안의 code point 수로 둔다.
  3. 그렇지 않으면,
    1. b를 0으로 둔다.
    2. n을 0으로 둔다.
  4. ExponentPart가 present하면 eExponentPart의 MV로 둔다. 그렇지 않으면 e를 0으로 둔다.
  5. RoundMVResult((a + (b × 10-n)) × 10e)를 반환한다.
StrUnsignedDecimalLiteral ::: . DecimalDigits ExponentPartopt
  1. bDecimalDigits의 MV로 둔다.
  2. ExponentPart가 present하면 eExponentPart의 MV로 둔다. 그렇지 않으면 e를 0으로 둔다.
  3. nDecimalDigits 안의 code point 수로 둔다.
  4. RoundMVResult(b × 10e - n)를 반환한다.
StrUnsignedDecimalLiteral ::: DecimalDigits ExponentPartopt
  1. aDecimalDigits의 MV로 둔다.
  2. ExponentPart가 present하면 eExponentPart의 MV로 둔다. 그렇지 않으면 e를 0으로 둔다.
  3. RoundMVResult(a × 10e)를 반환한다.

7.1.4.1.3 RoundMVResult ( n )

The abstract operation RoundMVResult takes argument n (a mathematical value) and returns a Number. nimplementation-defined 방식으로 Number로 convert합니다. 이 abstract operation의 목적상, digit은 zero가 아니거나 그 왼쪽에 non-zero digit이 있고 그 오른쪽에 non-zero digit이 있으면 significant합니다. 이 abstract operation의 목적상, mathematical value의 representation이 “denoted by”하는 mathematical valuemathematical value의 “decimal representation of”의 inverse입니다. It performs the following steps when called:

  1. n의 decimal representation이 20개 이하의 significant digit을 가지면, 𝔽(n)을 반환한다.
  2. option1n의 decimal representation에서 20번째 뒤의 각 significant digit을 0 digit으로 replacing한 결과가 denoted by하는 mathematical value로 둔다.
  3. option2n의 decimal representation에서 20번째 뒤의 각 significant digit을 0 digit으로 replacing한 다음 20번째 position에서 incrementing한 결과가 denoted by하는 mathematical value로 둔다(필요에 따라 carrying).
  4. chosenoption1 또는 option2implementation-defined choice로 둔다.
  5. 𝔽(chosen)을 반환한다.

7.1.5 ToIntegerOrInfinity ( arg )

The abstract operation ToIntegerOrInfinity takes argument arg (an ECMAScript language value) and returns either a normal completion containing either an integer, +∞, or -∞, or a throw completion. arg를 fractional part가 truncated된 Number value를 나타내는 integer로 convert하거나, 그 Number value가 infinite이면 +∞ 또는 -∞로 convert합니다. It performs the following steps when called:

  1. number를 ? ToNumber(arg)로 둔다.
  2. numberNaN, +0𝔽, 또는 -0𝔽 중 하나이면, 0을 반환한다.
  3. number+∞𝔽이면, +∞를 반환한다.
  4. number-∞𝔽이면, -∞를 반환한다.
  5. truncate((number))를 반환한다.
Note
𝔽(ToIntegerOrInfinity(x))는 어떤 value x에 대해서도 결코 -0𝔽를 반환하지 않습니다. fractional part의 truncation은 xmathematical value로 converting한 뒤 수행됩니다.

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를 0부터 2bitWidth - 1까지의 inclusive interval(signedunsigned인 경우) 또는 -2bitWidth - 1부터 2bitWidth - 1 - 1까지의 inclusive interval(signedsigned인 경우)에 있는 2bitWidthinteger 중 하나로 map합니다. It performs the following steps when called:

  1. int = +∞ 또는 int = -∞이면, 0을 반환한다.
  2. fixedIntint modulo 2bitWidth로 둔다.
  3. NOTE: 다음 step은 fixedInt의 two's complement representation을 change하지 않는다.
  4. signedsigned이고 fixedInt ≥ 2bitWidth - 1이면, fixedIntfixedInt - 2bitWidth로 설정한다.
  5. fixedInt를 반환한다.
Note

ToFixedSizeInteger는 idempotent입니다. 즉, 어떤 ECMAScript language value x에 대해서도 ToFixedSizeInteger(ToFixedSizeInteger(x, signed, bitWidth), signed, bitWidth)는 ToFixedSizeInteger(x, signed, bitWidth)와 같습니다. 실제로 +∞와 -∞가 0으로 mapped되므로, 이 invariant는 signed의 inversion에서도 유지됩니다(예: 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)까지의 inclusive interval에 있는 232개의 integral Number value 중 하나로 convert하며, -0𝔽는 제외합니다. It performs the following steps when called:

  1. int를 ? ToIntegerOrInfinity(arg)로 둔다.
  2. 𝔽(ToFixedSizeInteger(int, signed, 32))를 반환한다.

7.1.8 ToUint32 ( arg )

The abstract operation ToUint32 takes argument arg (an ECMAScript language value) and returns either a normal completion containing an integral Number or a throw completion. arg+0𝔽부터 𝔽(232 - 1)까지의 inclusive interval에 있는 232개의 integral Number value 중 하나로 convert합니다. It performs the following steps when called:

  1. int를 ? ToIntegerOrInfinity(arg)로 둔다.
  2. 𝔽(ToFixedSizeInteger(int, unsigned, 32))를 반환한다.

7.1.9 ToInt16 ( arg )

The abstract operation ToInt16 takes argument arg (an ECMAScript language value) and returns either a normal completion containing an integral Number or a throw completion. arg𝔽(-215)부터 𝔽(215 - 1)까지의 inclusive interval에 있는 216개의 integral Number value 중 하나로 convert하며, -0𝔽는 제외합니다. It performs the following steps when called:

  1. int를 ? ToIntegerOrInfinity(arg)로 둔다.
  2. 𝔽(ToFixedSizeInteger(int, signed, 16))를 반환한다.

7.1.10 ToUint16 ( arg )

The abstract operation ToUint16 takes argument arg (an ECMAScript language value) and returns either a normal completion containing an integral Number or a throw completion. arg+0𝔽부터 𝔽(216 - 1)까지의 inclusive interval에 있는 216개의 integral Number value 중 하나로 convert합니다. It performs the following steps when called:

  1. int를 ? ToIntegerOrInfinity(arg)로 둔다.
  2. 𝔽(ToFixedSizeInteger(int, unsigned, 16))를 반환한다.

7.1.11 ToInt8 ( arg )

The abstract operation ToInt8 takes argument arg (an ECMAScript language value) and returns either a normal completion containing an integral Number or a throw completion. arg-128𝔽부터 127𝔽까지의 inclusive interval에 있는 28개의 integral Number value 중 하나로 convert하며, -0𝔽는 제외합니다. It performs the following steps when called:

  1. int를 ? ToIntegerOrInfinity(arg)로 둔다.
  2. 𝔽(ToFixedSizeInteger(int, signed, 8))를 반환한다.

7.1.12 ToUint8 ( arg )

The abstract operation ToUint8 takes argument arg (an ECMAScript language value) and returns either a normal completion containing an integral Number or a throw completion. arg+0𝔽부터 255𝔽까지의 inclusive interval에 있는 28개의 integral Number value 중 하나로 convert합니다. It performs the following steps when called:

  1. int를 ? ToIntegerOrInfinity(arg)로 둔다.
  2. 𝔽(ToFixedSizeInteger(int, unsigned, 8))를 반환한다.

7.1.13 ToUint8Clamp ( arg )

The abstract operation ToUint8Clamp takes argument arg (an ECMAScript language value) and returns either a normal completion containing an integral Number or a throw completion. arg+0𝔽부터 255𝔽까지의 inclusive interval에 있는 28개의 integral Number value 중 하나로 clamp하고 round합니다. It performs the following steps when called:

  1. number를 ? ToNumber(arg)로 둔다.
  2. numberNaN이면, +0𝔽를 반환한다.
  3. mvnumberextended mathematical value로 둔다.
  4. clampedmv를 0과 255 사이로 clamping한 결과로 둔다.
  5. ffloor(clamped)로 둔다.
  6. clamped < f + 0.5이면, 𝔽(f)를 반환한다.
  7. clamped > f + 0.5이면, 𝔽(f + 1)를 반환한다.
  8. f가 even이면, 𝔽(f)를 반환한다.
  9. 𝔽(f + 1)를 반환한다.
Note

대부분의 다른 ECMAScript integer conversion operation과 달리, ToUint8Clamp는 non-integral value를 truncate하지 않고 round합니다. 또한 “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 value로 convert하거나, Number로부터의 implicit conversion이 required되면 throw합니다. It performs the following steps when called:

  1. primitive를 ? ToPrimitive(arg, number)로 둔다.
  2. primitiveTable 12에서 대응하는 value를 반환한다.
Table 12: BigInt Conversions
Argument Type Result
Undefined TypeError exception을 throw한다.
Null TypeError exception을 throw한다.
Boolean primitivetrue이면 1n을 반환하고, primitivefalse이면 0n을 반환한다.
BigInt primitive를 반환한다.
Number TypeError exception을 throw한다.
String
  1. nStringToBigInt(primitive)로 둔다.
  2. nundefined이면, SyntaxError exception을 throw한다.
  3. n을 반환한다.
Symbol TypeError exception을 throw한다.

7.1.15 StringToBigInt ( string )

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

  1. literalParseText(string, StringIntegerLiteral)로 둔다.
  2. literal이 error의 List이면, undefined를 반환한다.
  3. mvliteral의 MV로 둔다.
  4. Assert: mvinteger이다.
  5. (mv)를 반환한다.

7.1.15.1 StringIntegerLiteral Grammar

StringToBigInt는 다음 grammar를 사용합니다.

Syntax

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

7.1.15.2 Runtime Semantics: MV

7.1.16 ToBigInt64 ( arg )

The abstract operation ToBigInt64 takes argument arg (an ECMAScript language value) and returns either a normal completion containing a BigInt or a throw completion. arg(-263)부터 (263 - 1)까지의 inclusive interval에 있는 264개의 BigInt value 중 하나로 convert합니다. It performs the following steps when called:

  1. int(? ToBigInt(arg))로 둔다.
  2. (ToFixedSizeInteger(int, signed, 64))를 반환한다.

7.1.17 ToBigUint64 ( arg )

The abstract operation ToBigUint64 takes argument arg (an ECMAScript language value) and returns either a normal completion containing a BigInt or a throw completion. arg0부터 (264 - 1)까지의 inclusive interval에 있는 264개의 BigInt value 중 하나로 convert합니다. It performs the following steps when called:

  1. int(? ToBigInt(arg))로 둔다.
  2. (ToFixedSizeInteger(int, unsigned, 64))를 반환한다.

7.1.18 ToString ( arg )

The abstract operation ToString takes argument arg (an ECMAScript language value) and returns either a normal completion containing a String or a throw completion. argString type의 value로 convert합니다. It performs the following steps when called:

  1. arg가 String이면, arg를 반환한다.
  2. arg가 Symbol이면, TypeError exception을 throw한다.
  3. argundefined이면, "undefined"를 반환한다.
  4. argnull이면, "null"을 반환한다.
  5. argtrue이면, "true"를 반환한다.
  6. argfalse이면, "false"를 반환한다.
  7. arg가 Number이면, Number::toString(arg, 10)을 반환한다.
  8. arg가 BigInt이면, BigInt::toString(arg, 10)을 반환한다.
  9. Assert: arg는 Object이다.
  10. primitiveValue를 ? ToPrimitive(arg, string)로 둔다.
  11. Assert: primitiveValue는 Object가 아니다.
  12. ToString(primitiveValue)를 반환한다.

7.1.19 ToObject ( arg )

The abstract operation ToObject takes argument arg (an ECMAScript language value) and returns either a normal completion containing an Object or a throw completion. argObject type의 value로 convert합니다. It performs the following steps when called:

  1. argundefined 또는 null이면, TypeError exception을 throw한다.
  2. arg가 Boolean이면, [[BooleanData]] internal slot이 arg로 set된 새 Boolean object를 반환한다. Boolean object의 description은 20.3를 참조한다.
  3. arg가 Number이면, [[NumberData]] internal slot이 arg로 set된 새 Number object를 반환한다. Number object의 description은 21.1를 참조한다.
  4. arg가 String이면, [[StringData]] internal slot이 arg로 set된 새 String object를 반환한다. String object의 description은 22.1를 참조한다.
  5. arg가 Symbol이면, [[SymbolData]] internal slot이 arg로 set된 새 Symbol object를 반환한다. Symbol object의 description은 20.4를 참조한다.
  6. arg가 BigInt이면, [[BigIntData]] internal slot이 arg로 set된 새 BigInt object를 반환한다. BigInt object의 description은 21.2를 참조한다.
  7. Assert: arg는 Object이다.
  8. arg를 반환한다.

7.1.20 ToPropertyKey ( arg )

The abstract operation ToPropertyKey takes argument arg (an ECMAScript language value) and returns either a normal completion containing a property key or a throw completion. argproperty key로 사용할 수 있는 value로 convert합니다. It performs the following steps when called:

  1. key를 ? ToPrimitive(arg, string)로 둔다.
  2. key가 Symbol이면, 다음을 수행한다.
    1. key를 반환한다.
  3. ToString(key)를 반환한다.

7.1.21 ToLength ( arg )

The abstract operation ToLength takes argument arg (an ECMAScript language value) and returns either a normal completion containing a non-negative integral Number or a throw completion. argarray-like object의 length로 사용하기에 suitable한 non-negative integral Number로 clamp하고 truncate합니다. It performs the following steps when called:

  1. length를 ? ToIntegerOrInfinity(arg)로 둔다.
  2. length ≤ 0이면, +0𝔽를 반환한다.
  3. 𝔽(min(length, 253 - 1))를 반환한다.

7.1.22 CanonicalNumericIndexString ( arg )

The abstract operation CanonicalNumericIndexString takes argument arg (a String) and returns a Number or undefined. arg"-0"이거나 어떤 Number value n에 대해 정확히 ToString(n)과 match하면, 각각의 Number value를 반환합니다. 그렇지 않으면 undefined를 반환합니다. It performs the following steps when called:

  1. arg"-0"이면, -0𝔽를 반환한다.
  2. n을 ! ToNumber(arg)로 둔다.
  3. ToString(n)이 arg이면, n을 반환한다.
  4. undefined를 반환한다.

canonical numeric string은 CanonicalNumericIndexString abstract operation이 undefined를 반환하지 않는 모든 String입니다.

7.1.23 ToIndex ( arg )

The abstract operation ToIndex takes argument arg (an ECMAScript language value) and returns either a normal completion containing a non-negative integer or a throw completion. arginteger로 convert하고, 그것이 non-negative이며 integer index에 대응하면 그 integer를 반환합니다. 그렇지 않으면 exception을 throw합니다. It performs the following steps when called:

  1. int를 ? ToIntegerOrInfinity(arg)로 둔다.
  2. int가 0부터 253 - 1까지의 inclusive interval 안에 없으면, RangeError exception을 throw한다.
  3. int를 반환한다.

7.2 Testing and Comparison Operations

7.2.1 RequireObjectCoercible ( arg )

The abstract operation RequireObjectCoercible takes argument arg (an ECMAScript language value) and returns either a normal completion containing unused or a throw completion. argToObject를 사용하여 Object로 convert될 수 없는 value이면 error를 throw합니다. It performs the following steps when called:

  1. argundefined 또는 null이면, TypeError exception을 throw한다.
  2. unused를 반환한다.

7.2.2 IsArray ( arg )

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

  1. arg가 Object가 아니면, false를 반환한다.
  2. argArray exotic object이면, true를 반환한다.
  3. argProxy exotic object이면, 다음을 수행한다.
    1. ValidateNonRevokedProxy(arg)를 수행한다.
    2. proxyTargetarg.[[ProxyTarget]]으로 둔다.
    3. IsArray(proxyTarget)를 반환한다.
  4. false를 반환한다.

7.2.3 IsCallable ( arg )

The abstract operation IsCallable takes argument arg (an ECMAScript language value) and returns a Boolean. arg[[Call]] internal method를 가진 callable function인지 determine합니다. It performs the following steps when called:

  1. arg가 Object가 아니면, false를 반환한다.
  2. arg[[Call]] internal method를 가지면, true를 반환한다.
  3. false를 반환한다.

7.2.4 IsConstructor ( arg )

The abstract operation IsConstructor takes argument arg (an ECMAScript language value) and returns a Boolean. arg[[Construct]] internal method를 가진 function object인지 determine합니다. It performs the following steps when called:

  1. arg가 Object가 아니면, false를 반환한다.
  2. arg[[Construct]] internal method를 가지면, true를 반환한다.
  3. false를 반환한다.

7.2.5 IsExtensible ( obj )

The abstract operation IsExtensible takes argument obj (an Object) and returns either a normal completion containing a Boolean or a throw completion. additional property가 obj에 added될 수 있는지 determine하는 데 사용됩니다. It performs the following steps when called:

  1. obj.[[IsExtensible]]()를 반환한다.

7.2.6 IsRegExp ( arg )

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

  1. arg가 Object가 아니면, false를 반환한다.
  2. matcher를 ? Get(arg, %Symbol.match%)로 둔다.
  3. matcherundefined가 아니면, ToBoolean(matcher)를 반환한다.
  4. arg[[RegExpMatcher]] internal slot을 가지면, true를 반환한다.
  5. false를 반환한다.

7.2.7 Static Semantics: IsStringWellFormedUnicode ( string )

The abstract operation IsStringWellFormedUnicode takes argument string (a String) and returns a Boolean. 6.1.4에 설명된 대로 string을 UTF-16으로 encoded된 code point의 sequence로 interpret하고, 이것이 well formed UTF-16 sequence인지 determine합니다. It performs the following steps when called:

  1. lengthstring의 length로 둔다.
  2. k를 0으로 둔다.
  3. k < length인 동안 Repeat한다.
    1. codePointCodePointAt(string, k)로 둔다.
    2. codePoint.[[IsUnpairedSurrogate]]true이면, false를 반환한다.
    3. kk + codePoint.[[CodeUnitCount]]로 설정한다.
  4. true를 반환한다.

7.2.8 SameType ( x, y )

The abstract operation SameType takes arguments x (an ECMAScript language value) and y (an ECMAScript language value) and returns a Boolean. 두 argument가 같은 type인지 여부를 determine합니다. It performs the following steps when called:

  1. xundefined이고 yundefined이면, true를 반환한다.
  2. xnull이고 ynull이면, true를 반환한다.
  3. x가 Boolean이고 y가 Boolean이면, true를 반환한다.
  4. x가 Number이고 y가 Number이면, true를 반환한다.
  5. x가 BigInt이고 y가 BigInt이면, true를 반환한다.
  6. x가 Symbol이고 y가 Symbol이면, true를 반환한다.
  7. x가 String이고 y가 String이면, true를 반환한다.
  8. x가 Object이고 y가 Object이면, true를 반환한다.
  9. false를 반환한다.

7.2.9 SameValue ( x, y )

The abstract operation SameValue takes arguments x (an ECMAScript language value) and y (an ECMAScript language value) and returns a Boolean. 두 argument가 같은 value인지 여부를 determine합니다. It performs the following steps when called:

  1. SameType(x, y)가 false이면, false를 반환한다.
  2. x가 Number이면, 다음을 수행한다.
    1. Number::sameValue(x, y)를 반환한다.
  3. SameValueNonNumber(x, y)를 반환한다.
Note

이 algorithm은 모든 NaN value를 equivalent로 취급하고 +0𝔽-0𝔽를 differentiate한다는 점에서 IsStrictlyEqual Algorithm과 다릅니다.

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. 두 argument가 같은 value인지 여부를 determine합니다(+0𝔽-0𝔽의 차이를 ignoring). It performs the following steps when called:

  1. SameType(x, y)가 false이면, false를 반환한다.
  2. x가 Number이면, 다음을 수행한다.
    1. Number::sameValueZero(x, y)를 반환한다.
  3. SameValueNonNumber(x, y)를 반환한다.
Note

SameValueZero는 +0𝔽-0𝔽를 equivalent로 취급한다는 점에서만 SameValue와 다릅니다.

7.2.11 SameValueNonNumber ( x, y )

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

  1. Assert: SameType(x, y)는 true이다.
  2. xundefined 또는 null이면, true를 반환한다.
  3. x가 BigInt이면, 다음을 수행한다.
    1. BigInt::equal(x, y)를 반환한다.
  4. x가 String이면, 다음을 수행한다.
    1. xy가 같은 length와 같은 position의 같은 code unit을 가지면, true를 반환한다.
    2. false를 반환한다.
  5. x가 Boolean이면, 다음을 수행한다.
    1. xtrue이고 ytrue이면, true를 반환한다.
    2. xfalse이고 yfalse이면, true를 반환한다.
    3. false를 반환한다.
  6. NOTE: 다른 모든 ECMAScript language value는 identity로 비교된다.
  7. xy이면, true를 반환한다.
  8. false를 반환한다.
Note 1
expository purpose상, 일부 case는 불필요하더라도 이 algorithm 안에서 separately handled됩니다.
Note 2
x is y”가 의미하는 바의 detail은 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. comparison x < y에 대한 semantics를 제공하며, true, false, 또는 undefined(operand가 같은 numeric type의 comparable value로 coerced될 수 없음을 나타냄)를 반환합니다. leftFirst flag는 potentially visible side-effect가 있는 operation이 xy에 대해 수행되는 order를 control하는 데 사용됩니다. 이는 ECMAScript가 expression의 left to right evaluation을 specify하기 때문에 필요합니다. leftFirsttrue이면, x parameter는 y parameter에 대응하는 expression의 왼쪽에 나타나는 expression에 대응합니다. leftFirstfalse이면, 그 반대이며 operation은 x보다 y에 먼저 수행되어야 합니다. It performs the following steps when called:

  1. leftFirsttrue이면, 다음을 수행한다.
    1. px를 ? ToPrimitive(x, number)로 둔다.
    2. py를 ? ToPrimitive(y, number)로 둔다.
  2. 그렇지 않으면,
    1. NOTE: left to right evaluation을 preserve하려면 evaluation order가 reversed되어야 한다.
    2. py를 ? ToPrimitive(y, number)로 둔다.
    3. px를 ? ToPrimitive(x, number)로 둔다.
  3. px가 String이고 py가 String이면, 다음을 수행한다.
    1. lxpx의 length로 둔다.
    2. lypy의 length로 둔다.
    3. 0 ≤ i < min(lx, ly)인 각 integer i에 대해, ascending order로 다음을 수행한다.
      1. cxpx 안의 index i에 있는 code unit의 numeric value로 둔다.
      2. cypy 안의 index i에 있는 code unit의 numeric value로 둔다.
      3. cx < cy이면, true를 반환한다.
      4. cx > cy이면, false를 반환한다.
    4. lx < ly이면, true를 반환한다.
    5. false를 반환한다.
  4. px가 BigInt이고 py가 String이면, 다음을 수행한다.
    1. nyStringToBigInt(py)로 둔다.
    2. nyundefined이면, undefined를 반환한다.
    3. BigInt::lessThan(px, ny)를 반환한다.
  5. px가 String이고 py가 BigInt이면, 다음을 수행한다.
    1. nxStringToBigInt(px)로 둔다.
    2. nxundefined이면, undefined를 반환한다.
    3. BigInt::lessThan(nx, py)를 반환한다.
  6. NOTE: pxpy는 primitive value이므로, evaluation order는 중요하지 않다.
  7. nx를 ? ToNumeric(px)로 둔다.
  8. ny를 ? ToNumeric(py)로 둔다.
  9. SameType(nx, ny)가 true이면, 다음을 수행한다.
    1. nx가 Number이면, Number::lessThan(nx, ny)를 반환한다.
    2. Assert: nx는 BigInt이다.
    3. BigInt::lessThan(nx, ny)를 반환한다.
  10. Assert: nx는 BigInt이고 ny는 Number이거나, nx는 Number이고 ny는 BigInt이다.
  11. nxNaN이거나 nyNaN이면, undefined를 반환한다.
  12. nx-∞𝔽이거나 ny+∞𝔽이면, true를 반환한다.
  13. nx+∞𝔽이거나 ny-∞𝔽이면, false를 반환한다.
  14. (nx) < (ny)이면, true를 반환한다.
  15. false를 반환한다.
Note 1

Step 3는 logical-or operation 대신 logical-and operation을 사용한다는 점에서 addition operator +(13.15.3)를 handle하는 algorithm의 step 1.c와 다릅니다.

Note 2

String의 comparison은 UTF-16 code unit value의 sequence에 대한 simple lexicographic ordering을 사용합니다. Unicode specification에 정의된 character 또는 string equality와 collating order의 더 complex하고 semantically oriented definition을 사용하려는 attempt는 없습니다. 따라서 Unicode Standard에 따라 canonically equal하지만 같은 normalization form이 아닌 String value는 unequal로 test될 수 있습니다. 또한 code unit에 의한 lexicographic ordering은 surrogate pair를 포함하는 String에서 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. == operator에 대한 semantics를 제공합니다. It performs the following steps when called:

  1. SameType(x, y)가 true이면, 다음을 수행한다.
    1. IsStrictlyEqual(x, y)를 반환한다.
  2. xnull이고 yundefined이면, true를 반환한다.
  3. xundefined이고 ynull이면, true를 반환한다.
  4. host가 web browser이거나 그 밖에 [[IsHTMLDDA]] Internal Slot를 support하면, 다음을 수행한다.
    1. x가 Object이고 x[[IsHTMLDDA]] internal slot을 가지며 yundefined 또는 null 중 하나이면, true를 반환한다.
    2. xundefined 또는 null 중 하나이고, y가 Object이며 y[[IsHTMLDDA]] internal slot을 가지면, true를 반환한다.
  5. x가 Number이고 y가 String이면, ! IsLooselyEqual(x, ! ToNumber(y))를 반환한다.
  6. x가 String이고 y가 Number이면, ! IsLooselyEqual(! ToNumber(x), y)를 반환한다.
  7. x가 BigInt이고 y가 String이면, 다음을 수행한다.
    1. nStringToBigInt(y)로 둔다.
    2. nundefined이면, false를 반환한다.
    3. IsLooselyEqual(x, n)를 반환한다.
  8. x가 String이고 y가 BigInt이면, ! IsLooselyEqual(y, x)를 반환한다.
  9. x가 Boolean이면, ! IsLooselyEqual(! ToNumber(x), y)를 반환한다.
  10. y가 Boolean이면, ! IsLooselyEqual(x, ! ToNumber(y))를 반환한다.
  11. x가 String, Number, BigInt 또는 Symbol 중 하나이고 y가 Object이면, ! IsLooselyEqual(x, ? ToPrimitive(y))를 반환한다.
  12. x가 Object이고 y가 String, Number, BigInt 또는 Symbol 중 하나이면, ! IsLooselyEqual(? ToPrimitive(x), y)를 반환한다.
  13. x가 BigInt이고 y가 Number이거나, x가 Number이고 y가 BigInt이면, 다음을 수행한다.
    1. xfinite가 아니거나 yfinite가 아니면, false를 반환한다.
    2. (x) = (y)이면, true를 반환한다.
    3. false를 반환한다.
  14. false를 반환한다.

7.2.14 IsStrictlyEqual ( x, y )

The abstract operation IsStrictlyEqual takes arguments x (an ECMAScript language value) and y (an ECMAScript language value) and returns a Boolean. === operator에 대한 semantics를 제공합니다. It performs the following steps when called:

  1. SameType(x, y)가 false이면, false를 반환한다.
  2. x가 Number이면, 다음을 수행한다.
    1. Number::equal(x, y)를 반환한다.
  3. SameValueNonNumber(x, y)를 반환한다.
Note

이 algorithm은 signed zero와 NaN의 treatment에서 SameValue Algorithm과 다릅니다.

7.3 Operations on Objects

7.3.1 MakeBasicObject ( internalSlotsList )

The abstract operation MakeBasicObject takes argument internalSlotsList (a List of internal slot names) and returns an Object. algorithmically 생성되는 모든 ECMAScript object의 source이며, ordinary objectexotic object를 모두 포함합니다. 모든 object를 creating하는 데 사용되는 common step을 factored out하고 object creation을 centralize합니다. It performs the following steps when called:

  1. internalSlotsListinternalSlotsList와 « [[PrivateElements]] »의 list-concatenation으로 설정한다.
  2. internalSlotsList 안의 각 name에 대한 internal slot을 가진 newly created object obj를 둔다.
  3. NOTE: Object Internal Methods and Internal Slots에 설명된 것처럼, 그러한 각 internal slot의 initial value는 달리 specified되지 않는 한 undefined이다.
  4. obj.[[PrivateElements]]를 새 empty List로 설정한다.
  5. obj의 essential internal method를 10.1에 specified된 default ordinary object definition으로 설정한다.
  6. Assert: caller가 obj[[GetPrototypeOf]][[SetPrototypeOf]] essential internal method를 모두 overriding하지 않을 것이라면, internalSlotsList[[Prototype]]을 포함한다.
  7. Assert: caller가 obj[[SetPrototypeOf]], [[IsExtensible]], [[PreventExtensions]] essential internal method를 모두 overriding하지 않을 것이라면, internalSlotsList[[Extensible]]을 포함한다.
  8. internalSlotsList[[Extensible]]을 포함하면, obj.[[Extensible]]true로 설정한다.
  9. obj를 반환한다.
Note

이 명세 안에서 exotic objectArrayCreateBoundFunctionCreate 같은 abstract operation에서 먼저 MakeBasicObject를 호출하여 basic, foundational object를 얻은 다음, 해당 object의 internal method 일부 또는 전부를 overriding하여 생성됩니다. exotic object creation을 encapsulate하기 위해, object의 essential internal method는 이러한 operation 밖에서는 결코 modified되지 않습니다.

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. object의 특정 property의 value를 retrieve하는 데 사용됩니다. It performs the following steps when called:

  1. obj.[[Get]](propertyKey, obj)를 반환한다.

7.3.3 GetV ( value, propertyKey )

The abstract operation GetV takes arguments value (an ECMAScript language value) and propertyKey (a property key) and returns either a normal completion containing an ECMAScript language value or a throw completion. ECMAScript language value의 특정 property의 value를 retrieve하는 데 사용됩니다. value가 object가 아니면, value의 type에 appropriate한 wrapper object를 사용하여 property lookup이 수행됩니다. It performs the following steps when called:

  1. obj를 ? ToObject(value)로 둔다.
  2. obj.[[Get]](propertyKey, value)를 반환한다.

7.3.4 Set ( obj, propertyKey, value, throw )

The abstract operation Set takes arguments obj (an Object), propertyKey (a property key), value (an ECMAScript language value), and throw (a Boolean) and returns either a normal completion containing unused or a throw completion. object의 특정 property의 value를 set하는 데 사용됩니다. value는 property의 new value입니다. It performs the following steps when called:

  1. success를 ? obj.[[Set]](propertyKey, value, obj)로 둔다.
  2. successfalse이고 throwtrue이면, TypeError exception을 throw한다.
  3. unused를 반환한다.

7.3.5 CreateDataProperty ( obj, propertyKey, value )

The abstract operation CreateDataProperty takes arguments obj (an Object), propertyKey (a property key), and value (an ECMAScript language value) and returns either a normal completion containing a Boolean or a throw completion. object의 new own property를 create하는 데 사용됩니다. It performs the following steps when called:

  1. newDesc를 PropertyDescriptor { [[Value]]: value, [[Writable]]: true, [[Enumerable]]: true, [[Configurable]]: true }로 둔다.
  2. obj.[[DefineOwnProperty]](propertyKey, newDesc)를 반환한다.
Note

이 abstract operation은 ECMAScript language assignment operator가 생성하는 property에 사용되는 것과 같은 default로 attribute가 set된 property를 생성합니다. 일반적으로 property는 이미 존재하지 않습니다. 존재하지만 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. object의 new own property를 create하는 데 사용됩니다. requested property update를 수행할 수 없으면 TypeError exception을 throw합니다. It performs the following steps when called:

  1. success를 ? CreateDataProperty(obj, propertyKey, value)로 둔다.
  2. successfalse이면, TypeError exception을 throw한다.
  3. unused를 반환한다.
Note

이 abstract operation은 ECMAScript language assignment operator가 생성하는 property에 사용되는 것과 같은 default로 attribute가 set된 property를 생성합니다. 일반적으로 property는 이미 존재하지 않습니다. 존재하지만 configurable하지 않거나 obj가 extensible하지 않으면, [[DefineOwnProperty]]false를 반환하여 이 operation이 TypeError exception을 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의 new non-enumerable own property를 create하는 데 사용됩니다. It performs the following steps when called:

  1. Assert: obj는 non-configurable property가 없는 ordinary, extensible object이다.
  2. newDesc를 PropertyDescriptor { [[Value]]: value, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: true }로 둔다.
  3. DefinePropertyOrThrow(obj, propertyKey, newDesc)를 수행한다.
  4. unused를 반환한다.
Note

이 abstract operation은 enumerable하지 않다는 점을 제외하고 ECMAScript language assignment operator가 생성하는 property에 사용되는 것과 같은 default로 attribute가 set된 property를 생성합니다. 일반적으로 property는 이미 존재하지 않습니다. 존재하는 경우에도, DefinePropertyOrThrow는 정상적으로 complete함이 guaranteed됩니다.

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. requested property update를 수행할 수 없으면 TypeError exception을 throw하는 방식으로 object의 [[DefineOwnProperty]] internal method를 call하는 데 사용됩니다. It performs the following steps when called:

  1. success를 ? obj.[[DefineOwnProperty]](propertyKey, propertyDesc)로 둔다.
  2. successfalse이면, TypeError exception을 throw한다.
  3. unused를 반환한다.

7.3.9 DeletePropertyOrThrow ( obj, propertyKey )

The abstract operation DeletePropertyOrThrow takes arguments obj (an Object) and propertyKey (a property key) and returns either a normal completion containing unused or a throw completion. object의 특정 own property를 remove하는 데 사용됩니다. property가 configurable하지 않으면 exception을 throw합니다. It performs the following steps when called:

  1. success를 ? obj.[[Delete]](propertyKey)로 둔다.
  2. successfalse이면, TypeError exception을 throw한다.
  3. unused를 반환한다.

7.3.10 GetMethod ( value, propertyKey )

The abstract operation GetMethod takes arguments value (an ECMAScript language value) and propertyKey (a property key) and returns either a normal completion containing either a function object or undefined, or a throw completion. property의 value가 function일 것으로 expected될 때 ECMAScript language value의 특정 property의 value를 get하는 데 사용됩니다. It performs the following steps when called:

  1. func를 ? GetV(value, propertyKey)로 둔다.
  2. funcundefined 또는 null이면, undefined를 반환한다.
  3. IsCallable(func)가 false이면, TypeError exception을 throw한다.
  4. func를 반환한다.

7.3.11 HasProperty ( obj, propertyKey )

The abstract operation HasProperty takes arguments obj (an Object) and propertyKey (a property key) and returns either a normal completion containing a Boolean or a throw completion. object가 specified property key를 가진 property를 가지는지 determine하는 데 사용됩니다. property는 own 또는 inherited일 수 있습니다. It performs the following steps when called:

  1. obj.[[HasProperty]](propertyKey)를 반환한다.

7.3.12 HasOwnProperty ( obj, propertyKey )

The abstract operation HasOwnProperty takes arguments obj (an Object) and propertyKey (a property key) and returns either a normal completion containing a Boolean or a throw completion. object가 specified property key를 가진 own property를 가지는지 determine하는 데 사용됩니다. It performs the following steps when called:

  1. propertyDesc를 ? obj.[[GetOwnProperty]](propertyKey)로 둔다.
  2. propertyDescundefined이면, false를 반환한다.
  3. true를 반환한다.

7.3.13 Call ( func, thisValue [ , argList ] )

The abstract operation Call takes arguments func (an ECMAScript language value) and thisValue (an ECMAScript language value) and optional argument argList (a List of ECMAScript language values) and returns either a normal completion containing an ECMAScript language value or a throw completion. function object[[Call]] internal method를 call하는 데 사용됩니다. funcfunction object이고, thisValue[[Call]]this value인 ECMAScript language value이며, argList는 internal method의 corresponding argument로 passed되는 value입니다. argList가 present하지 않으면, 새 empty List가 그 value로 사용됩니다. It performs the following steps when called:

  1. argList가 present하지 않으면, argList를 새 empty List로 설정한다.
  2. IsCallable(func)가 false이면, TypeError exception을 throw한다.
  3. func.[[Call]](thisValue, argList)를 반환한다.

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

The abstract operation Construct takes argument ctor (a constructor) and optional arguments argList (a List of ECMAScript language values) and newTarget (a constructor) and returns either a normal completion containing an Object or a throw completion. function object[[Construct]] internal method를 call하는 데 사용됩니다. argListnewTarget은 internal method의 corresponding argument로 passed될 value입니다. argList가 present하지 않으면, 새 empty List가 그 value로 사용됩니다. newTarget이 present하지 않으면, ctor가 그 value로 사용됩니다. It performs the following steps when called:

  1. newTarget이 present하지 않으면, newTargetctor로 설정한다.
  2. argList가 present하지 않으면, argList를 새 empty List로 설정한다.
  3. ctor.[[Construct]](argList, newTarget)를 반환한다.
Note

newTarget이 present하지 않으면, 이 operation은 new F(...argumentsList)와 equivalent합니다.

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. object의 own property set을 fix하는 데 사용됩니다. It performs the following steps when called:

  1. status를 ? obj.[[PreventExtensions]]()로 둔다.
  2. statusfalse이면, false를 반환한다.
  3. keys를 ? obj.[[OwnPropertyKeys]]()로 둔다.
  4. levelsealed이면, 다음을 수행한다.
    1. keys의 각 element key에 대해, 다음을 수행한다.
      1. DefinePropertyOrThrow(obj, key, PropertyDescriptor { [[Configurable]]: false })를 수행한다.
  5. 그렇지 않으면,
    1. Assert: levelfrozen이다.
    2. keys의 각 element key에 대해, 다음을 수행한다.
      1. currentDesc를 ? obj.[[GetOwnProperty]](key)로 둔다.
      2. currentDescundefined가 아니면, 다음을 수행한다.
        1. IsAccessorDescriptor(currentDesc)가 true이면, 다음을 수행한다.
          1. propertyDesc를 PropertyDescriptor { [[Configurable]]: false }로 둔다.
        2. 그렇지 않으면,
          1. propertyDesc를 PropertyDescriptor { [[Configurable]]: false, [[Writable]]: false }로 둔다.
        3. DefinePropertyOrThrow(obj, key, propertyDesc)를 수행한다.
  6. true를 반환한다.

7.3.16 TestIntegrityLevel ( obj, level )

The abstract operation TestIntegrityLevel takes arguments obj (an Object) and level (sealed or frozen) and returns either a normal completion containing a Boolean or a throw completion. object의 own property set이 fixed되어 있는지 determine하는 데 사용됩니다. It performs the following steps when called:

  1. extensible을 ? IsExtensible(obj)로 둔다.
  2. extensibletrue이면, false를 반환한다.
  3. NOTE: object가 extensible이면, 그 property는 전혀 examined되지 않는다.
  4. keys를 ? obj.[[OwnPropertyKeys]]()로 둔다.
  5. keys의 각 element key에 대해, 다음을 수행한다.
    1. currentDesc를 ? obj.[[GetOwnProperty]](key)로 둔다.
    2. currentDescundefined가 아니면, 다음을 수행한다.
      1. currentDesc.[[Configurable]]true이면, false를 반환한다.
      2. levelfrozen이고 IsDataDescriptor(currentDesc)가 true이면, 다음을 수행한다.
        1. currentDesc.[[Writable]]true이면, false를 반환한다.
  6. true를 반환한다.

7.3.17 CreateArrayFromList ( elements )

The abstract operation CreateArrayFromList takes argument elements (a List of ECMAScript language values) and returns an Array. elements가 제공하는 element를 가진 Array를 create하는 데 사용됩니다. It performs the following steps when called:

  1. array를 ! ArrayCreate(0)으로 둔다.
  2. n을 0으로 둔다.
  3. elements의 각 element element에 대해, 다음을 수행한다.
    1. CreateDataPropertyOrThrow(array, ! ToString(𝔽(n)), element)를 수행한다.
    2. nn + 1로 설정한다.
  4. array를 반환한다.

7.3.18 LengthOfArrayLike ( obj )

The abstract operation LengthOfArrayLike takes argument obj (an Object) and returns either a normal completion containing a non-negative integer or a throw completion. array-like object의 "length" property value를 반환합니다. It performs the following steps when called:

  1. (? ToLength(? Get(obj, "length")))를 반환한다.

array-like object는 이 operation이 normal completion을 반환하는 모든 object입니다.

Note 1
일반적으로 array-like object는 integer index name을 가진 property도 일부 가집니다. 그러나 이는 이 definition의 requirement는 아닙니다.
Note 2
Array와 String object는 array-like object의 example입니다.

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 property가 제공하는 element를 가진 List value를 create하는 데 사용됩니다. validElementTypes는 element로 allowed되는 value의 type을 나타냅니다. It performs the following steps when called:

  1. validElementTypes가 present하지 않으면, validElementTypesall로 설정한다.
  2. obj가 Object가 아니면, TypeError exception을 throw한다.
  3. length를 ? LengthOfArrayLike(obj)로 둔다.
  4. list를 새 empty List로 둔다.
  5. index를 0으로 둔다.
  6. index < length인 동안 Repeat한다.
    1. indexName을 ! ToString(𝔽(index))으로 둔다.
    2. next를 ? Get(obj, indexName)로 둔다.
    3. validElementTypesproperty-key이고 nextproperty key가 아니면, TypeError exception을 throw한다.
    4. nextlist에 append한다.
    5. indexindex + 1로 설정한다.
  7. list를 반환한다.

7.3.20 Invoke ( value, propertyKey [ , argList ] )

The abstract operation Invoke takes arguments value (an ECMAScript language value) and propertyKey (a property key) and optional argument argList (a List of ECMAScript language values) and returns either a normal completion containing an ECMAScript language value or a throw completion. ECMAScript language value의 method property를 call하는 데 사용됩니다. value는 property의 lookup point와 call의 this value 둘 다로 사용됩니다. argList는 method에 passed되는 argument value의 list입니다. argList가 present하지 않으면, 새 empty List가 그 value로 사용됩니다. It performs the following steps when called:

  1. argList가 present하지 않으면, argList를 새 empty List로 설정한다.
  2. func를 ? GetV(value, propertyKey)로 둔다.
  3. Call(func, value, argList)를 반환한다.

7.3.21 OrdinaryHasInstance ( ctor, instance )

The abstract operation OrdinaryHasInstance takes arguments ctor (an ECMAScript language value) and instance (an ECMAScript language value) and returns either a normal completion containing a Boolean or a throw completion. instancector가 제공하는 instance object inheritance path에서 inherit하는지 determine하기 위한 default algorithm을 implements합니다. It performs the following steps when called:

  1. IsCallable(ctor)가 false이면, false를 반환한다.
  2. ctor[[BoundTargetFunction]] internal slot을 가지면, 다음을 수행한다.
    1. boundCtorctor.[[BoundTargetFunction]]으로 둔다.
    2. InstanceofOperator(instance, boundCtor)를 반환한다.
  3. instance가 Object가 아니면, false를 반환한다.
  4. proto를 ? Get(ctor, "prototype")로 둔다.
  5. proto가 Object가 아니면, TypeError exception을 throw한다.
  6. Repeat,
    1. instance를 ? instance.[[GetPrototypeOf]]()로 설정한다.
    2. instancenull이면, false를 반환한다.
    3. SameValue(proto, instance)가 true이면, true를 반환한다.

7.3.22 SpeciesConstructor ( obj, defaultCtor )

The abstract operation SpeciesConstructor takes arguments obj (an Object) and defaultCtor (a constructor) and returns either a normal completion containing a constructor or a throw completion. obj에서 derived된 new object를 create하는 데 사용해야 하는 constructor를 retrieve하는 데 사용됩니다. defaultCtorobj에서 시작하여 constructor %Symbol.species% property를 찾을 수 없을 때 사용할 constructor입니다. It performs the following steps when called:

  1. ctor를 ? Get(obj, "constructor")로 둔다.
  2. ctorundefined이면, defaultCtor를 반환한다.
  3. ctor가 Object가 아니면, TypeError exception을 throw한다.
  4. species를 ? Get(ctor, %Symbol.species%)로 둔다.
  5. speciesundefined 또는 null이면, defaultCtor를 반환한다.
  6. IsConstructor(species)가 true이면, species를 반환한다.
  7. TypeError exception을 throw한다.

7.3.23 EnumerableOwnProperties ( obj, kind )

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

  1. ownKeys를 ? obj.[[OwnPropertyKeys]]()로 둔다.
  2. results를 새 empty List로 둔다.
  3. ownKeys의 각 element key에 대해, 다음을 수행한다.
    1. key가 String이면, 다음을 수행한다.
      1. propertyDesc를 ? obj.[[GetOwnProperty]](key)로 둔다.
      2. propertyDescundefined가 아니고 propertyDesc.[[Enumerable]]true이면, 다음을 수행한다.
        1. kindkey이면, 다음을 수행한다.
          1. keyresults에 append한다.
        2. 그렇지 않으면,
          1. value를 ? Get(obj, key)로 둔다.
          2. kindvalue이면, 다음을 수행한다.
            1. valueresults에 append한다.
          3. 그렇지 않으면,
            1. Assert: kindkey+value이다.
            2. entryCreateArrayFromListkey, value »)로 둔다.
            3. entryresults에 append한다.
  4. results를 반환한다.

7.3.24 GetFunctionRealm ( func )

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

  1. func[[Realm]] internal slot을 가지면, 다음을 수행한다.
    1. func.[[Realm]]을 반환한다.
  2. funcbound function exotic object이면, 다음을 수행한다.
    1. boundTargetFuncfunc.[[BoundTargetFunction]]으로 둔다.
    2. GetFunctionRealm(boundTargetFunc)를 반환한다.
  3. funcProxy exotic object이면, 다음을 수행한다.
    1. ValidateNonRevokedProxy(func)를 수행한다.
    2. proxyTargetfunc.[[ProxyTarget]]으로 둔다.
    3. Assert: proxyTargetfunction object이다.
    4. GetFunctionRealm(proxyTarget)를 반환한다.
  4. current Realm Record를 반환한다.
Note

Step 4func[[Realm]] internal slot을 가지지 않는 non-standard function exotic object인 경우에만 도달됩니다.

7.3.25 CopyDataProperties ( target, source, excludedItems )

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

  1. sourceundefined 또는 null이면, unused를 반환한다.
  2. from을 ! ToObject(source)로 둔다.
  3. keys를 ? from.[[OwnPropertyKeys]]()로 둔다.
  4. keys의 각 element nextKey에 대해, 다음을 수행한다.
    1. excludedfalse로 둔다.
    2. excludedItems의 각 element element에 대해, 다음을 수행한다.
      1. SameValue(element, nextKey)가 true이면, 다음을 수행한다.
        1. excludedtrue로 설정한다.
    3. excludedfalse이면, 다음을 수행한다.
      1. propertyDesc를 ? from.[[GetOwnProperty]](nextKey)로 둔다.
      2. propertyDescundefined가 아니고 propertyDesc.[[Enumerable]]true이면, 다음을 수행한다.
        1. propertyValue를 ? Get(from, nextKey)로 둔다.
        2. CreateDataPropertyOrThrow(target, nextKey, propertyValue)를 수행한다.
  5. unused를 반환한다.
Note

여기서 passed되는 target은 항상 newly created object이며, error가 thrown되는 경우 직접 accessible하지 않습니다.

7.3.26 PrivateElementFind ( obj, privateName )

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

  1. obj.[[PrivateElements]]entry.[[Key]]privateNamePrivateElement entry를 contain하면, 다음을 수행한다.
    1. entry를 반환한다.
  2. empty를 반환한다.

7.3.27 PrivateFieldAdd ( obj, privateName, value )

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

  1. host가 web browser이면, 다음을 수행한다.
    1. HostEnsureCanAddPrivateElement(obj)를 수행한다.
  2. entryPrivateElementFind(obj, privateName)로 둔다.
  3. entryempty가 아니면, TypeError exception을 throw한다.
  4. PrivateElement { [[Key]]: privateName, [[Kind]]: field, [[Value]]: value }를 obj.[[PrivateElements]]에 append한다.
  5. unused를 반환한다.

7.3.28 PrivateMethodOrAccessorAdd ( obj, method )

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

  1. Assert: method.[[Kind]]method 또는 accessor 중 하나이다.
  2. host가 web browser이면, 다음을 수행한다.
    1. HostEnsureCanAddPrivateElement(obj)를 수행한다.
  3. entryPrivateElementFind(obj, method.[[Key]])로 둔다.
  4. entryempty가 아니면, TypeError exception을 throw한다.
  5. methodobj.[[PrivateElements]]에 append한다.
  6. unused를 반환한다.
Note

private method와 accessor의 value는 instance 간에 shared됩니다. 이 operation은 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 environment가 특정 host-defined exotic object에 private element가 추가되는 것을 prevent할 수 있게 합니다.

HostEnsureCanAddPrivateElement의 implementation은 다음 requirement를 conform해야 합니다:

  • objhost-defined exotic object가 아니면, 이 abstract operation은 NormalCompletion(unused)를 반환하고 다른 step을 수행하지 않아야 합니다.
  • 같은 argument로 이 abstract operation을 두 번 call하면, 같은 kind의 Completion Record를 반환해야 합니다.

HostEnsureCanAddPrivateElement의 default implementation은 NormalCompletion(unused)를 반환하는 것입니다.

이 abstract operation은 web browser인 ECMAScript host에 의해서만 invoked됩니다.

7.3.30 PrivateGet ( obj, privateName )

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

  1. entryPrivateElementFind(obj, privateName)로 둔다.
  2. entryempty이면, TypeError exception을 throw한다.
  3. entry.[[Kind]]field 또는 method 중 하나이면, 다음을 수행한다.
    1. entry.[[Value]]를 반환한다.
  4. Assert: entry.[[Kind]]accessor이다.
  5. entry.[[Get]]undefined이면, TypeError exception을 throw한다.
  6. getterentry.[[Get]]으로 둔다.
  7. Call(getter, obj)를 반환한다.

7.3.31 PrivateSet ( obj, privateName, value )

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

  1. entryPrivateElementFind(obj, privateName)로 둔다.
  2. entryempty이면, TypeError exception을 throw한다.
  3. entry.[[Kind]]method이면, TypeError exception을 throw한다.
  4. entry.[[Kind]]field이면, 다음을 수행한다.
    1. entry.[[Value]]value로 설정한다.
  5. 그렇지 않으면,
    1. Assert: entry.[[Kind]]accessor이다.
    2. entry.[[Set]]undefined이면, TypeError exception을 throw한다.
    3. setterentry.[[Set]]으로 둔다.
    4. Call(setter, obj, « value »)를 수행한다.
  6. unused를 반환한다.

7.3.32 DefineField ( receiver, fieldRecord )

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

  1. fieldNamefieldRecord.[[Name]]으로 둔다.
  2. initializerfieldRecord.[[Initializer]]로 둔다.
  3. initializerempty가 아니면, 다음을 수행한다.
    1. initValue를 ? Call(initializer, receiver)로 둔다.
  4. 그렇지 않으면,
    1. initValueundefined로 둔다.
  5. fieldNamePrivate Name이면, 다음을 수행한다.
    1. PrivateFieldAdd(receiver, fieldName, initValue)를 수행한다.
  6. 그렇지 않으면,
    1. Assert: fieldNameproperty key이다.
    2. CreateDataPropertyOrThrow(receiver, fieldName, initValue)를 수행한다.
  7. unused를 반환한다.

7.3.33 InitializeInstanceElements ( obj, ctor )

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

  1. methodsctor.[[PrivateMethods]]로 둔다.
  2. methods의 각 PrivateElement method에 대해, 다음을 수행한다.
    1. PrivateMethodOrAccessorAdd(obj, method)를 수행한다.
  3. fieldsctor.[[Fields]]로 둔다.
  4. fields의 각 element fieldRecord에 대해, 다음을 수행한다.
    1. DefineField(obj, fieldRecord)를 수행한다.
  5. unused를 반환한다.

7.3.34 AddValueToKeyedGroup ( groups, key, value )

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

  1. groups의 각 Record { [[Key]], [[Elements]] } group에 대해, 다음을 수행한다.
    1. SameValue(group.[[Key]], key)가 true이면, 다음을 수행한다.
      1. Assert: groups의 정확히 한 element가 이 criterion을 만족한다.
      2. valuegroup.[[Elements]]에 append한다.
      3. unused를 반환한다.
  2. groupRecord { [[Key]]: key, [[Elements]]: « value » }로 둔다.
  3. groupgroups에 append한다.
  4. unused를 반환한다.

7.3.35 GroupBy ( items, callback, keyCoercion )

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

  1. RequireObjectCoercible(items)를 수행한다.
  2. IsCallable(callback)가 false이면, TypeError exception을 throw한다.
  3. groups를 새 empty List로 둔다.
  4. iteratorRecord를 ? GetIterator(items, sync)로 둔다.
  5. k를 0으로 둔다.
  6. Repeat,
    1. k ≥ 253 - 1이면, 다음을 수행한다.
      1. errorThrowCompletion(a newly created TypeError object)로 둔다.
      2. IteratorClose(iteratorRecord, error)를 반환한다.
    2. next를 ? IteratorStepValue(iteratorRecord)로 둔다.
    3. nextdone이면, 다음을 수행한다.
      1. groups를 반환한다.
    4. valuenext로 둔다.
    5. keyCompletion(Call(callback, undefined, « value, 𝔽(k) »))로 둔다.
    6. IfAbruptCloseIterator(key, iteratorRecord).
    7. keyCoercionproperty이면, 다음을 수행한다.
      1. keyCompletion(ToPropertyKey(key))로 설정한다.
      2. IfAbruptCloseIterator(key, iteratorRecord).
    8. 그렇지 않으면,
      1. Assert: keyCoercioncollection이다.
      2. keyCanonicalizeKeyedCollectionKey(key)로 설정한다.
    9. AddValueToKeyedGroup(groups, key, value)를 수행한다.
    10. kk + 1로 설정한다.

7.3.36 GetOptionsObject ( options )

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

  1. optionsundefined이면, 다음을 수행한다.
    1. OrdinaryObjectCreate(null)를 반환한다.
  2. options가 Object이면, 다음을 수행한다.
    1. options를 반환한다.
  3. TypeError exception을 throw한다.

7.3.37 SetterThatIgnoresPrototypeProperties ( thisValue, home, propertyKey, value )

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

  1. thisValue가 Object가 아니면, 다음을 수행한다.
    1. TypeError exception을 throw한다.
  2. SameValue(thisValue, home)가 true이면, 다음을 수행한다.
    1. NOTE: 여기서 throw하는 것은 strict mode code에서 home object의 non-writable data property에 assignment하는 것을 emulates한다.
    2. TypeError exception을 throw한다.
  3. propertyDesc를 ? thisValue.[[GetOwnProperty]](propertyKey)로 둔다.
  4. propertyDescundefined이면, 다음을 수행한다.
    1. CreateDataPropertyOrThrow(thisValue, propertyKey, value)를 수행한다.
  5. 그렇지 않으면,
    1. Set(thisValue, propertyKey, value, true)를 수행한다.
  6. unused를 반환한다.

7.4 Iterator Objects에 대한 Operations

Common Iteration Interfaces(27.1)를 참조하십시오.

7.4.1 Iterator Records

Iterator Recordnext method와 함께 iterator 또는 async iterator를 encapsulate하는 데 사용되는 Record value입니다.

Iterator Record는 Table 13에 listed된 field를 가집니다.

Table 13: Iterator Record Fields
Field Name Value Meaning
[[Iterator]] Object iterator interface 또는 async iterator interface를 conform하는 object입니다.
[[NextMethod]] ECMAScript language value [[Iterator]] object의 next method입니다.
[[Done]] Boolean iterator가 completed되었거나 closed되었는지 여부입니다.

7.4.2 GetIteratorDirect ( obj )

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

  1. nextMethod를 ? Get(obj, "next")로 둔다.
  2. iteratorRecordIterator Record { [[Iterator]]: obj, [[NextMethod]]: nextMethod, [[Done]]: false }로 둔다.
  3. iteratorRecord를 반환한다.

7.4.3 GetIteratorFromMethod ( obj, method )

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

  1. iterator를 ? Call(method, obj)로 둔다.
  2. iterator가 Object가 아니면, TypeError exception을 throw한다.
  3. GetIteratorDirect(iterator)를 반환한다.

7.4.4 GetIterator ( obj, kind )

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

  1. kindasync이면, 다음을 수행한다.
    1. method를 ? GetMethod(obj, %Symbol.asyncIterator%)로 둔다.
    2. methodundefined이면, 다음을 수행한다.
      1. syncMethod를 ? GetMethod(obj, %Symbol.iterator%)로 둔다.
      2. syncMethodundefined이면, TypeError exception을 throw한다.
      3. syncIteratorRecord를 ? GetIteratorFromMethod(obj, syncMethod)로 둔다.
      4. CreateAsyncFromSyncIterator(syncIteratorRecord)를 반환한다.
  2. 그렇지 않으면,
    1. method를 ? GetMethod(obj, %Symbol.iterator%)로 둔다.
  3. methodundefined이면, TypeError exception을 throw한다.
  4. GetIteratorFromMethod(obj, method)를 반환한다.

7.4.5 GetIteratorFlattenable ( obj, primitiveHandling )

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

  1. obj가 Object가 아니면, 다음을 수행한다.
    1. primitiveHandlingreject-primitives이면, TypeError exception을 throw한다.
    2. Assert: primitiveHandlingiterate-string-primitives이다.
    3. obj가 String이 아니면, TypeError exception을 throw한다.
  2. method를 ? GetMethod(obj, %Symbol.iterator%)로 둔다.
  3. methodundefined이면, 다음을 수행한다.
    1. iteratorobj로 둔다.
  4. 그렇지 않으면,
    1. iterator를 ? Call(method, obj)로 둔다.
  5. iterator가 Object가 아니면, TypeError exception을 throw한다.
  6. GetIteratorDirect(iterator)를 반환한다.

7.4.6 IteratorNext ( iteratorRecord [ , value ] )

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

  1. value가 present하지 않으면, 다음을 수행한다.
    1. resultCompletion(Call(iteratorRecord.[[NextMethod]], iteratorRecord.[[Iterator]]))로 둔다.
  2. 그렇지 않으면,
    1. resultCompletion(Call(iteratorRecord.[[NextMethod]], iteratorRecord.[[Iterator]], « value »))로 둔다.
  3. resultthrow completion이면, 다음을 수행한다.
    1. iteratorRecord.[[Done]]true로 설정한다.
    2. result를 반환한다.
  4. result를 ! result로 설정한다.
  5. result가 Object가 아니면, 다음을 수행한다.
    1. iteratorRecord.[[Done]]true로 설정한다.
    2. TypeError exception을 throw한다.
  6. result를 반환한다.

7.4.7 IteratorComplete ( iteratorResult )

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

  1. ToBoolean(? Get(iteratorResult, "done"))를 반환한다.

7.4.8 IteratorValue ( iteratorResult )

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

  1. Get(iteratorResult, "value")를 반환한다.

7.4.9 IteratorStep ( iteratorRecord )

The abstract operation IteratorStep takes argument iteratorRecord (an Iterator Record) and returns either a normal completion containing either an Object or done, or a throw completion. iteratorRecord.[[NextMethod]]를 호출하여 iteratorRecord.[[Iterator]]로부터 next value를 request하고, iterator가 끝에 도달했음을 나타내는 done 또는 next value가 available하면 IteratorResult object를 반환합니다. It performs the following steps when called:

  1. result를 ? IteratorNext(iteratorRecord)로 둔다.
  2. doneCompletion(IteratorComplete(result))로 둔다.
  3. donethrow completion이면, 다음을 수행한다.
    1. iteratorRecord.[[Done]]true로 설정한다.
    2. done을 반환한다.
  4. done을 ! done으로 설정한다.
  5. donetrue이면, 다음을 수행한다.
    1. iteratorRecord.[[Done]]true로 설정한다.
    2. done을 반환한다.
  6. result를 반환한다.

7.4.10 IteratorStepValue ( iteratorRecord )

The abstract operation IteratorStepValue takes argument iteratorRecord (an Iterator Record) and returns either a normal completion containing either an ECMAScript language value or done, or a throw completion. iteratorRecord.[[NextMethod]]를 호출하여 iteratorRecord.[[Iterator]]로부터 next value를 request하고, iterator가 끝에 도달했음을 나타내는 done 또는 next value가 available하면 IteratorResult object의 value를 반환합니다. It performs the following steps when called:

  1. result를 ? IteratorStep(iteratorRecord)로 둔다.
  2. resultdone이면, 다음을 수행한다.
    1. done을 반환한다.
  3. valueCompletion(IteratorValue(result))로 둔다.
  4. valuethrow completion이면, 다음을 수행한다.
    1. iteratorRecord.[[Done]]true로 설정한다.
  5. value를 반환한다.

7.4.11 IteratorClose ( iteratorRecord, completion )

The abstract operation IteratorClose takes arguments iteratorRecord (an Iterator Record) and completion (a Completion Record) and returns a Completion Record. iterator가 completed state에 도달했을 때 일반적으로 수행할 action을 수행해야 함을 notify하는 데 사용됩니다. It performs the following steps when called:

  1. Assert: iteratorRecord.[[Iterator]]는 Object이다.
  2. iteratoriteratorRecord.[[Iterator]]로 둔다.
  3. innerResultCompletion(GetMethod(iterator, "return" ))로 둔다.
  4. innerResultnormal completion이면, 다음을 수행한다.
    1. returninnerResult.[[Value]]로 둔다.
    2. returnundefined이면, ? completion을 반환한다.
    3. innerResultCompletion(Call(return, iterator))로 설정한다.
  5. completionthrow completion이면, ? completion을 반환한다.
  6. innerResultthrow completion이면, ? innerResult를 반환한다.
  7. innerResult.[[Value]]가 Object가 아니면, TypeError exception을 throw한다.
  8. completion을 반환한다.

7.4.12 IteratorCloseAll ( iterators, completion )

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

  1. iterators의 각 element iterator에 대해, reverse List order로 다음을 수행한다.
    1. completionCompletion(IteratorClose(iterator, completion))으로 설정한다.
  2. completion을 반환한다.

7.4.13 IfAbruptCloseIterator ( value, iteratorRecord )

IfAbruptCloseIterator는 Iterator Record를 사용하는 algorithm step sequence에 대한 shorthand입니다. 다음 형식의 algorithm step은:

  1. IfAbruptCloseIterator(value, iteratorRecord).

다음과 같은 의미입니다:

  1. Assert: valueCompletion Record이다.
  2. valueabrupt completion이면, ? IteratorClose(iteratorRecord, value)를 반환한다.
  3. value를 ! value로 설정한다.

7.4.14 IfAbruptCloseIterators ( value, iteratorRecords )

IfAbruptCloseIterators는 Iterator Record의 list를 사용하는 algorithm step sequence에 대한 shorthand입니다. 다음 형식의 algorithm step은:

  1. IfAbruptCloseIterators(value, iteratorRecords).

다음과 같은 의미입니다:

  1. Assert: valueCompletion Record이다.
  2. valueabrupt completion이면, ? IteratorCloseAll(iteratorRecords, value)를 반환한다.
  3. value를 ! value로 설정한다.

7.4.15 AsyncIteratorClose ( iteratorRecord, completion )

The abstract operation AsyncIteratorClose takes arguments iteratorRecord (an Iterator Record) and completion (a Completion Record) and returns a Completion Record. async iterator가 completed state에 도달했을 때 일반적으로 수행할 action을 수행해야 함을 notify하는 데 사용됩니다. It performs the following steps when called:

  1. Assert: iteratorRecord.[[Iterator]]는 Object이다.
  2. iteratoriteratorRecord.[[Iterator]]로 둔다.
  3. innerResultCompletion(GetMethod(iterator, "return" ))로 둔다.
  4. innerResultnormal completion이면, 다음을 수행한다.
    1. returninnerResult.[[Value]]로 둔다.
    2. returnundefined이면, ? completion을 반환한다.
    3. innerResultCompletion(Call(return, iterator))로 설정한다.
    4. innerResultnormal completion이면, innerResultCompletion(Await(innerResult.[[Value]]))로 설정한다.
  5. completionthrow completion이면, ? completion을 반환한다.
  6. innerResultthrow completion이면, ? innerResult를 반환한다.
  7. innerResult.[[Value]]가 Object가 아니면, TypeError exception을 throw한다.
  8. completion을 반환한다.

7.4.16 IfAbruptCloseAsyncIterator ( value, iteratorRecord )

IfAbruptCloseAsyncIterator는 Iterator Record를 사용하는 algorithm step sequence에 대한 shorthand입니다. 다음 형식의 algorithm step은:

  1. IfAbruptCloseAsyncIterator(value, iteratorRecord).

다음과 같은 의미입니다:

  1. Assert: valueCompletion Record이다.
  2. valueabrupt completion이면, ? AsyncIteratorClose(iteratorRecord, value)를 반환한다.
  3. value를 ! value로 설정한다.

7.4.17 CreateIteratorResultObject ( value, done )

The abstract operation CreateIteratorResultObject takes arguments value (an ECMAScript language value) and done (a Boolean) and returns an Object that conforms to the IteratorResult interface. IteratorResult interface를 conform하는 object를 생성합니다. It performs the following steps when called:

  1. objOrdinaryObjectCreate(%Object.prototype%)로 둔다.
  2. CreateDataPropertyOrThrow(obj, "value", value)를 수행한다.
  3. CreateDataPropertyOrThrow(obj, "done", done)를 수행한다.
  4. obj를 반환한다.

7.4.18 CreateListIteratorRecord ( list )

The abstract operation CreateListIteratorRecord takes argument list (a List of ECMAScript language values) and returns an Iterator Record. [[NextMethod]]list의 successive element를 반환하는 Iterator Record를 생성합니다. It performs the following steps when called:

  1. closure를 parameter가 없고 list를 capture하며 called될 때 다음 step을 수행하는 새 Abstract Closure로 둔다:
    1. list의 각 element value에 대해, 다음을 수행한다.
      1. GeneratorYield(CreateIteratorResultObject(value, false))를 수행한다.
    2. NormalCompletion(undefined)를 반환한다.
  2. iteratorCreateIteratorFromClosure(closure, empty, %Iterator.prototype%)로 둔다.
  3. Iterator Record { [[Iterator]]: iterator, [[NextMethod]]: %GeneratorPrototype.next%, [[Done]]: false }를 반환한다.
Note

list iterator object는 ECMAScript code에서 직접 accessible하지 않습니다.

7.4.19 IteratorToList ( iteratorRecord )

The abstract operation IteratorToList takes argument iteratorRecord (an Iterator Record) and returns either a normal completion containing a List of ECMAScript language values or a throw completion. It performs the following steps when called:

  1. values를 새 empty List로 둔다.
  2. Repeat,
    1. next를 ? IteratorStepValue(iteratorRecord)로 둔다.
    2. nextdone이면, 다음을 수행한다.
      1. values를 반환한다.
    3. nextvalues에 append한다.

7.5 Disposable 객체에 대한 연산

공통 리소스 관리 인터페이스(27.2.1)를 참조한다.

7.5.1 DisposableResource 레코드

DisposableResource 레코드는 폐기 가능한 객체를 해당 객체를 폐기하는 데 사용되는 메서드와 함께 캡슐화하는 데 사용되는 Record 값이다. DisposableResource 레코드는 CreateDisposableResource 추상 연산에 의해 생성된다.

DisposableResource 레코드에는 Table 14에 나열된 필드가 있다:

Table 14: DisposableResource 레코드 필드
필드 이름 의미
[[ResourceValue]] Object 또는 undefined 폐기될 값.
[[Kind]] sync-dispose 또는 async-dispose 리소스가 using 선언 또는 DisposableStack 객체(sync-dispose)에 의해 추가되었는지, 아니면 await using 선언 또는 AsyncDisposableStack 객체(async-dispose)에 의해 추가되었는지를 나타낸다.
[[DisposeMethod]] 함수 객체 또는 undefined 리소스가 폐기될 때 [[ResourceValue]]this 값으로 하여 호출될 함수 객체.

7.5.2 AddDisposableResource ( disposableResourceStack, value, kind [ , method ] )

The abstract operation AddDisposableResource takes arguments disposableResourceStack (DisposableResource 레코드List), value (ECMAScript 언어 값), and kind (sync-dispose 또는 async-dispose) and optional argument method (함수 객체) and returns unused를 포함하는 정상 완료 또는 throw 완료. It performs the following steps when called:

  1. method가 존재하면,
    1. 단언: valueundefined이다.
    2. resource를 ? CreateDisposableResource(undefined, kind, method)로 둔다.
  2. 그렇지 않으면,
    1. valuenull 또는 undefined이고 kindsync-dispose이면, unused를 반환한다.
    2. NOTE: valuenull 또는 undefined이고 kindasync-dispose인 경우, 나중에 리소스가 폐기될 때 여전히 Await를 수행하도록 보장하기 위해 리소스가 평가되었음을 기록한다.
    3. resource를 ? CreateDisposableResource(value, kind)로 둔다.
  3. resourcedisposableResourceStack에 추가한다.
  4. 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 레코드를 포함하는 정상 완료 또는 throw 완료. It performs the following steps when called:

  1. method가 존재하지 않으면,
    1. valuenull 또는 undefined이면,
      1. valueundefined로 설정한다.
      2. methodundefined로 설정한다.
    2. 그렇지 않으면,
      1. method를 ? GetDisposeMethod(value, kind)로 설정한다.
      2. methodundefined이면, TypeError 예외를 던진다.
  2. DisposableResource 레코드 { [[ResourceValue]]: value, [[Kind]]: kind, [[DisposeMethod]]: method }를 반환한다.

7.5.4 GetDisposeMethod ( value, kind )

The abstract operation GetDisposeMethod takes arguments value (an ECMAScript language value) and kind (sync-dispose or async-dispose) and returns either a normal completion containing either a function object or undefined, or a throw completion. It performs the following steps when called:

  1. value가 Object가 아니면, TypeError 예외를 던진다.
  2. kindsync-dispose이면, ? GetMethod(value, %Symbol.dispose%)를 반환한다.
  3. 단언: kindasync-dispose이다.
  4. asyncMethod를 ? GetMethod(value, %Symbol.asyncDispose%)로 둔다.
  5. asyncMethodundefined가 아니면, asyncMethod를 반환한다.
  6. syncMethod를 ? GetMethod(value, %Symbol.dispose%)로 둔다.
  7. syncMethodundefined이면, undefined를 반환한다.
  8. syncMethod를 캡처하고 호출될 때 다음 단계를 수행하는, 매개변수가 없는 새 Abstract Closureclosure를 둔다:
    1. objthis 값으로 둔다.
    2. promiseCapability를 ! NewPromiseCapability(%Promise%)로 둔다.
    3. resultCompletion(Call(syncMethod, obj))로 둔다.
    4. IfAbruptRejectPromise(result, promiseCapability).
    5. Call(promiseCapability.[[Resolve]], undefined, « undefined »)를 수행한다.
    6. promiseCapability.[[Promise]]를 반환한다.
  9. NOTE: 이 함수는 사용자 코드에 관찰되지 않는다. 이 함수는 동기 %Symbol.dispose% 메서드에서 반환된 Promise가 await되지 않도록 하고, 동기 예외가 거부된 Promise로 변환되도록 보장하는 데 사용된다.
  10. CreateBuiltinFunction(closure, 0, "", « »)를 반환한다.

7.5.5 DisposeResources ( disposableResourceStack, completion )

The abstract operation DisposeResources takes arguments disposableResourceStack (a List of DisposableResource Records) and completion (either a normal completion containing either an ECMAScript language value or empty, or an abrupt completion) and returns either a normal completion containing either an ECMAScript language value or empty, or an abrupt completion. It performs the following steps when called:

  1. needsAwaitfalse로 둔다.
  2. hasAwaitedfalse로 둔다.
  3. outputCompletioncompletion으로 둔다.
  4. disposableResourceStack의 각 요소 resource에 대해, 역 List 순서로 다음을 수행한다.
    1. valueresource.[[ResourceValue]]로 둔다.
    2. kindresource.[[Kind]]로 둔다.
    3. methodresource.[[DisposeMethod]]로 둔다.
    4. kindsync-dispose이고, needsAwaittrue이며, hasAwaitedfalse이면,
      1. Await(undefined)를 수행한다.
      2. needsAwaitfalse로 설정한다.
    5. methodundefined가 아니면,
      1. resultCompletion(Call(method, value))로 둔다.
      2. result가 정상 완료이고 kindasync-dispose이면,
        1. resultCompletion(Await(result.[[Value]]))로 설정한다.
        2. hasAwaitedtrue로 설정한다.
      3. result가 throw 완료이면,
        1. outputCompletion이 throw 완료이면,
          1. resultresult.[[Value]]로 설정한다.
          2. suppressedoutputCompletion.[[Value]]로 둔다.
          3. error를 새로 생성된 SuppressedError 객체로 둔다.
          4. CreateNonEnumerableDataPropertyOrThrow(error, "error", result)를 수행한다.
          5. CreateNonEnumerableDataPropertyOrThrow(error, "suppressed", suppressed)를 수행한다.
          6. outputCompletionThrowCompletion(error)로 설정한다.
        2. 그렇지 않으면,
          1. outputCompletionresult로 설정한다.
    6. 그렇지 않으면,
      1. 단언: kindasync-dispose이다.
      2. needsAwaittrue로 설정한다.
      3. NOTE: 이는 await using 선언의 초기화된 값이 null 또는 undefined였던 경우만 나타낼 수 있다.
  5. needsAwaittrue이고 hasAwaitedfalse이면,
    1. Await(undefined)를 수행한다.
  6. NOTE: 이 시점에서 disposableResourceStack은 다시는 사용되지 않는다. disposableResourceStack의 내용은 가비지 컬렉션과 같은 방식으로 구현에서 폐기될 수 있다.
  7. outputCompletion을 반환한다.

8 Syntax-Directed Operations

이 section에 정의된 것들 외에도, specialized syntax-directed operation은 이 명세 전반에 걸쳐 정의됩니다.

8.1 Runtime Semantics: Evaluation

The syntax-directed operation Evaluation takes no arguments and returns a Completion Record.

Note
이 operation에 대한 definition은 이 명세의 “ECMAScript Language” section 전반에 분산되어 있습니다. 각 definition은 relevant production의 defining occurrence 뒤에 나타납니다.

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가 다른 name을 가지지 않을 때 그 synthetic name으로 사용됩니다. module의 [[Environment]] 안의 entry가 그 name으로 생성되어 corresponding value를 hold하며, module에 대해 ResolveExport ( exportName [ , resolveSet ] )를 호출하여 "default"라는 name의 export를 resolving하면 [[BindingName]]"*default*"ResolvedBinding Record가 반환되고, 이는 module의 [[Environment]] 안에서 위에서 언급한 value로 resolve됩니다. 이는 anonymous default export가 다른 export와 마찬가지로 resolve될 수 있도록 하기 위한 specification 편의를 위해서만 수행됩니다. 이 "*default*" string은 ECMAScript code나 module linking algorithm에서 결코 accessible하지 않습니다.

It is defined piecewise over the following productions:

BindingIdentifier : Identifier
  1. IdentifierStringValue를 sole element로 하는 List를 반환한다.
BindingIdentifier : yield
  1. « "yield" »를 반환한다.
BindingIdentifier : await
  1. « "await" »를 반환한다.
LexicalDeclaration : LetOrConst BindingList ;
  1. BindingListBoundNames를 반환한다.
UsingDeclaration : using BindingList ; AwaitUsingDeclaration : CoverAwaitExpressionAndAwaitUsingDeclarationHead BindingList ;
  1. BindingListBoundNames를 반환한다.
BindingList : BindingList , LexicalBinding
  1. names1BindingListBoundNames로 둔다.
  2. names2LexicalBindingBoundNames로 둔다.
  3. names1names2list-concatenation을 반환한다.
LexicalBinding : BindingIdentifier Initializeropt
  1. BindingIdentifierBoundNames를 반환한다.
LexicalBinding : BindingPattern Initializer
  1. BindingPatternBoundNames를 반환한다.
VariableDeclarationList : VariableDeclarationList , VariableDeclaration
  1. names1VariableDeclarationListBoundNames로 둔다.
  2. names2VariableDeclarationBoundNames로 둔다.
  3. names1names2list-concatenation을 반환한다.
VariableDeclaration : BindingIdentifier Initializeropt
  1. BindingIdentifierBoundNames를 반환한다.
VariableDeclaration : BindingPattern Initializer
  1. BindingPatternBoundNames를 반환한다.
ObjectBindingPattern : { }
  1. 새 empty List를 반환한다.
ObjectBindingPattern : { BindingPropertyList , BindingRestProperty }
  1. names1BindingPropertyListBoundNames로 둔다.
  2. names2BindingRestPropertyBoundNames로 둔다.
  3. names1names2list-concatenation을 반환한다.
ArrayBindingPattern : [ Elisionopt ]
  1. 새 empty List를 반환한다.
ArrayBindingPattern : [ Elisionopt BindingRestElement ]
  1. BindingRestElementBoundNames를 반환한다.
ArrayBindingPattern : [ BindingElementList , Elisionopt ]
  1. BindingElementListBoundNames를 반환한다.
ArrayBindingPattern : [ BindingElementList , Elisionopt BindingRestElement ]
  1. names1BindingElementListBoundNames로 둔다.
  2. names2BindingRestElementBoundNames로 둔다.
  3. names1names2list-concatenation을 반환한다.
BindingPropertyList : BindingPropertyList , BindingProperty
  1. names1BindingPropertyListBoundNames로 둔다.
  2. names2BindingPropertyBoundNames로 둔다.
  3. names1names2list-concatenation을 반환한다.
BindingElementList : BindingElementList , BindingElisionElement
  1. names1BindingElementListBoundNames로 둔다.
  2. names2BindingElisionElementBoundNames로 둔다.
  3. names1names2list-concatenation을 반환한다.
BindingElisionElement : Elisionopt BindingElement
  1. BindingElementBoundNames를 반환한다.
BindingProperty : PropertyName : BindingElement
  1. BindingElementBoundNames를 반환한다.
SingleNameBinding : BindingIdentifier Initializeropt
  1. BindingIdentifierBoundNames를 반환한다.
BindingElement : BindingPattern Initializeropt
  1. BindingPatternBoundNames를 반환한다.
ForDeclaration : LetOrConst ForBinding
  1. ForBindingBoundNames를 반환한다.
FunctionDeclaration : function BindingIdentifier ( FormalParameters ) { FunctionBody }
  1. BindingIdentifierBoundNames를 반환한다.
FunctionDeclaration : function ( FormalParameters ) { FunctionBody }
  1. « "*default*" »를 반환한다.
FormalParameters : [empty]
  1. 새 empty List를 반환한다.
FormalParameters : FormalParameterList , FunctionRestParameter
  1. names1FormalParameterListBoundNames로 둔다.
  2. names2FunctionRestParameterBoundNames로 둔다.
  3. names1names2list-concatenation을 반환한다.
FormalParameterList : FormalParameterList , FormalParameter
  1. names1FormalParameterListBoundNames로 둔다.
  2. names2FormalParameterBoundNames로 둔다.
  3. names1names2list-concatenation을 반환한다.
ArrowParameters : CoverParenthesizedExpressionAndArrowParameterList
  1. formalsCoverParenthesizedExpressionAndArrowParameterList가 cover하는 ArrowFormalParameters로 둔다.
  2. formalsBoundNames를 반환한다.
GeneratorDeclaration : function * BindingIdentifier ( FormalParameters ) { GeneratorBody }
  1. BindingIdentifierBoundNames를 반환한다.
GeneratorDeclaration : function * ( FormalParameters ) { GeneratorBody }
  1. « "*default*" »를 반환한다.
AsyncGeneratorDeclaration : async function * BindingIdentifier ( FormalParameters ) { AsyncGeneratorBody }
  1. BindingIdentifierBoundNames를 반환한다.
AsyncGeneratorDeclaration : async function * ( FormalParameters ) { AsyncGeneratorBody }
  1. « "*default*" »를 반환한다.
ClassDeclaration : class BindingIdentifier ClassTail
  1. BindingIdentifierBoundNames를 반환한다.
ClassDeclaration : class ClassTail
  1. « "*default*" »를 반환한다.
AsyncFunctionDeclaration : async function BindingIdentifier ( FormalParameters ) { AsyncFunctionBody }
  1. BindingIdentifierBoundNames를 반환한다.
AsyncFunctionDeclaration : async function ( FormalParameters ) { AsyncFunctionBody }
  1. « "*default*" »를 반환한다.
CoverCallExpressionAndAsyncArrowHead : MemberExpression Arguments
  1. headCoverCallExpressionAndAsyncArrowHead가 cover하는 AsyncArrowHead로 둔다.
  2. headBoundNames를 반환한다.
ImportDeclaration : import ImportClause FromClause WithClauseopt ;
  1. ImportClauseBoundNames를 반환한다.
ImportDeclaration : import ModuleSpecifier WithClauseopt ;
  1. 새 empty List를 반환한다.
ImportClause : ImportedDefaultBinding , NameSpaceImport
  1. names1ImportedDefaultBindingBoundNames로 둔다.
  2. names2NameSpaceImportBoundNames로 둔다.
  3. names1names2list-concatenation을 반환한다.
ImportClause : ImportedDefaultBinding , NamedImports
  1. names1ImportedDefaultBindingBoundNames로 둔다.
  2. names2NamedImportsBoundNames로 둔다.
  3. names1names2list-concatenation을 반환한다.
NamedImports : { }
  1. 새 empty List를 반환한다.
ImportsList : ImportsList , ImportSpecifier
  1. names1ImportsListBoundNames로 둔다.
  2. names2ImportSpecifierBoundNames로 둔다.
  3. names1names2list-concatenation을 반환한다.
ImportSpecifier : ModuleExportName as ImportedBinding
  1. ImportedBindingBoundNames를 반환한다.
ExportDeclaration : export ExportFromClause FromClause WithClauseopt ; export NamedExports ;
  1. 새 empty List를 반환한다.
ExportDeclaration : export VariableStatement
  1. VariableStatementBoundNames를 반환한다.
ExportDeclaration : export Declaration
  1. DeclarationBoundNames를 반환한다.
ExportDeclaration : export default HoistableDeclaration
  1. declNamesHoistableDeclarationBoundNames로 둔다.
  2. declNames가 element "*default*"를 include하지 않으면, "*default*"declNames에 append한다.
  3. declNames를 반환한다.
ExportDeclaration : export default ClassDeclaration
  1. declNamesClassDeclarationBoundNames로 둔다.
  2. declNames가 element "*default*"를 include하지 않으면, "*default*"declNames에 append한다.
  3. declNames를 반환한다.
ExportDeclaration : export default AssignmentExpression ;
  1. « "*default*" »를 반환한다.

8.2.2 Static Semantics: DeclarationPart

The syntax-directed operation DeclarationPart takes no arguments and returns a Parse Node. It is defined piecewise over the following productions:

HoistableDeclaration : FunctionDeclaration
  1. FunctionDeclaration을 반환한다.
HoistableDeclaration : GeneratorDeclaration
  1. GeneratorDeclaration을 반환한다.
HoistableDeclaration : AsyncFunctionDeclaration
  1. AsyncFunctionDeclaration을 반환한다.
HoistableDeclaration : AsyncGeneratorDeclaration
  1. AsyncGeneratorDeclaration을 반환한다.
Declaration : ClassDeclaration
  1. ClassDeclaration을 반환한다.
Declaration : LexicalDeclaration
  1. LexicalDeclaration을 반환한다.

8.2.3 Static Semantics: IsConstantDeclaration

The syntax-directed operation IsConstantDeclaration takes no arguments and returns a Boolean. It is defined piecewise over the following productions:

LexicalDeclaration : LetOrConst BindingList ;
  1. LetOrConstIsConstantDeclaration을 반환한다.
LetOrConst : let
  1. false를 반환한다.
LetOrConst : const
  1. true를 반환한다.
UsingDeclaration : using BindingList ; AwaitUsingDeclaration : CoverAwaitExpressionAndAwaitUsingDeclarationHead BindingList ;
  1. true를 반환한다.
FunctionDeclaration : function BindingIdentifier ( FormalParameters ) { FunctionBody } function ( FormalParameters ) { FunctionBody } GeneratorDeclaration : function * BindingIdentifier ( FormalParameters ) { GeneratorBody } function * ( FormalParameters ) { GeneratorBody } AsyncGeneratorDeclaration : async function * BindingIdentifier ( FormalParameters ) { AsyncGeneratorBody } async function * ( FormalParameters ) { AsyncGeneratorBody } AsyncFunctionDeclaration : async function BindingIdentifier ( FormalParameters ) { AsyncFunctionBody } async function ( FormalParameters ) { AsyncFunctionBody }
  1. false를 반환한다.
ClassDeclaration : class BindingIdentifier ClassTail class ClassTail
  1. false를 반환한다.
ExportDeclaration : export ExportFromClause FromClause ; export NamedExports ; export default AssignmentExpression ;
  1. false를 반환한다.
Note

export default AssignmentExpression을 constant declaration으로 취급할 필요는 없습니다. module의 default object를 reference하는 데 사용되는 internal bound name에 assignment를 허용하는 syntax가 없기 때문입니다.

8.2.4 Static Semantics: IsUsingDeclaration

The syntax-directed operation IsUsingDeclaration takes no arguments and returns Boolean. It is defined piecewise over the following productions:

LexicalDeclaration : LetOrConst BindingList ;
  1. false를 반환한다.
UsingDeclaration : using BindingList ; AwaitUsingDeclaration : CoverAwaitExpressionAndAwaitUsingDeclarationHead BindingList ;
  1. true를 반환한다.
ForDeclaration : LetOrConst ForBinding
  1. false를 반환한다.
ForDeclaration : using ForBinding await using ForBinding
  1. true를 반환한다.
FunctionDeclaration : function BindingIdentifier ( FormalParameters ) { FunctionBody } function ( FormalParameters ) { FunctionBody } GeneratorDeclaration : function * BindingIdentifier ( FormalParameters ) { GeneratorBody } function * ( FormalParameters ) { GeneratorBody } AsyncGeneratorDeclaration : async function * BindingIdentifier ( FormalParameters ) { AsyncGeneratorBody } async function * ( FormalParameters ) { AsyncGeneratorBody } AsyncFunctionDeclaration : async function BindingIdentifier ( FormalParameters ) { AsyncFunctionBody } async function ( FormalParameters ) { AsyncFunctionBody }
  1. false를 반환한다.
ClassDeclaration : class BindingIdentifier ClassTail class ClassTail
  1. false를 반환한다.

8.2.5 Static Semantics: IsAwaitUsingDeclaration

The syntax-directed operation IsAwaitUsingDeclaration takes no arguments and returns Boolean. It is defined piecewise over the following productions:

LexicalDeclaration : LetOrConst BindingList ;
  1. false를 반환한다.
UsingDeclaration : using BindingList ;
  1. false를 반환한다.
AwaitUsingDeclaration : CoverAwaitExpressionAndAwaitUsingDeclarationHead BindingList ;
  1. true를 반환한다.
ForDeclaration : LetOrConst ForBinding
  1. false를 반환한다.
ForDeclaration : using ForBinding
  1. false를 반환한다.
ForDeclaration : await using ForBinding
  1. true를 반환한다.
FunctionDeclaration : function BindingIdentifier ( FormalParameters ) { FunctionBody } function ( FormalParameters ) { FunctionBody } GeneratorDeclaration : function * BindingIdentifier ( FormalParameters ) { GeneratorBody } function * ( FormalParameters ) { GeneratorBody } AsyncGeneratorDeclaration : async function * BindingIdentifier ( FormalParameters ) { AsyncGeneratorBody } async function * ( FormalParameters ) { AsyncGeneratorBody } AsyncFunctionDeclaration : async function BindingIdentifier ( FormalParameters ) { AsyncFunctionBody } async function ( FormalParameters ) { AsyncFunctionBody }
  1. false를 반환한다.
ClassDeclaration : class BindingIdentifier ClassTail class ClassTail
  1. false를 반환한다.

8.2.6 Static Semantics: LexicallyDeclaredNames

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

Block : { }
  1. 새 empty List를 반환한다.
StatementList : StatementList StatementListItem
  1. names1StatementListLexicallyDeclaredNames로 둔다.
  2. names2StatementListItemLexicallyDeclaredNames로 둔다.
  3. names1names2list-concatenation을 반환한다.
StatementListItem : Statement
  1. Statement Statement : LabelledStatement 이면, LabelledStatementLexicallyDeclaredNames를 반환한다.
  2. 새 empty List를 반환한다.
StatementListItem : Declaration
  1. DeclarationBoundNames를 반환한다.
CaseBlock : { }
  1. 새 empty List를 반환한다.
CaseBlock : { CaseClausesopt DefaultClause CaseClausesopt }
  1. 첫 번째 CaseClauses가 present하면, names1을 첫 번째 CaseClausesLexicallyDeclaredNames로 둔다.
  2. 그렇지 않으면, names1을 새 empty List로 둔다.
  3. names2DefaultClauseLexicallyDeclaredNames로 둔다.
  4. 두 번째 CaseClauses가 present하면, names3을 두 번째 CaseClausesLexicallyDeclaredNames로 둔다.
  5. 그렇지 않으면, names3을 새 empty List로 둔다.
  6. names1, names2, names3list-concatenation을 반환한다.
CaseClauses : CaseClauses CaseClause
  1. names1CaseClausesLexicallyDeclaredNames로 둔다.
  2. names2CaseClauseLexicallyDeclaredNames로 둔다.
  3. names1names2list-concatenation을 반환한다.
CaseClause : case Expression : StatementListopt
  1. StatementList가 present하면, StatementListLexicallyDeclaredNames를 반환한다.
  2. 새 empty List를 반환한다.
DefaultClause : default : StatementListopt
  1. StatementList가 present하면, StatementListLexicallyDeclaredNames를 반환한다.
  2. 새 empty List를 반환한다.
LabelledStatement : LabelIdentifier : LabelledItem
  1. LabelledItemLexicallyDeclaredNames를 반환한다.
LabelledItem : Statement
  1. 새 empty List를 반환한다.
LabelledItem : FunctionDeclaration
  1. FunctionDeclarationBoundNames를 반환한다.
FunctionStatementList : [empty]
  1. 새 empty List를 반환한다.
FunctionStatementList : StatementList
  1. StatementListTopLevelLexicallyDeclaredNames를 반환한다.
ClassStaticBlockStatementList : [empty]
  1. 새 empty List를 반환한다.
ClassStaticBlockStatementList : StatementList
  1. StatementListTopLevelLexicallyDeclaredNames를 반환한다.
ConciseBody : ExpressionBody
  1. 새 empty List를 반환한다.
AsyncConciseBody : ExpressionBody
  1. 새 empty List를 반환한다.
Script : [empty]
  1. 새 empty List를 반환한다.
ScriptBody : StatementList
  1. StatementListTopLevelLexicallyDeclaredNames를 반환한다.
Note 1

Script의 top level에서 function declaration은 lexical declaration처럼이 아니라 var declaration처럼 취급됩니다.

Note 2

Module의 LexicallyDeclaredNames에는 모든 imported binding의 name이 포함됩니다.

ModuleItemList : ModuleItemList ModuleItem
  1. names1ModuleItemListLexicallyDeclaredNames로 둔다.
  2. names2ModuleItemLexicallyDeclaredNames로 둔다.
  3. names1names2list-concatenation을 반환한다.
ModuleItem : ImportDeclaration
  1. ImportDeclarationBoundNames를 반환한다.
ModuleItem : ExportDeclaration
  1. ExportDeclarationexport VariableStatement이면, 새 empty List를 반환한다.
  2. ExportDeclarationBoundNames를 반환한다.
ModuleItem : StatementListItem
  1. StatementListItemLexicallyDeclaredNames를 반환한다.
Note 3

Module의 top level에서 function declaration은 var declaration처럼이 아니라 lexical declaration처럼 취급됩니다.

8.2.7 Static Semantics: LexicallyScopedDeclarations

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

StatementList : StatementList StatementListItem
  1. decls1StatementListLexicallyScopedDeclarations로 둔다.
  2. decls2StatementListItemLexicallyScopedDeclarations로 둔다.
  3. decls1decls2list-concatenation을 반환한다.
StatementListItem : Statement
  1. Statement Statement : LabelledStatement 이면, LabelledStatementLexicallyScopedDeclarations를 반환한다.
  2. 새 empty List를 반환한다.
StatementListItem : Declaration
  1. DeclarationDeclarationPart를 sole element로 하는 List를 반환한다.
CaseBlock : { }
  1. 새 empty List를 반환한다.
CaseBlock : { CaseClausesopt DefaultClause CaseClausesopt }
  1. 첫 번째 CaseClauses가 present하면, decls1을 첫 번째 CaseClausesLexicallyScopedDeclarations로 둔다.
  2. 그렇지 않으면, decls1을 새 empty List로 둔다.
  3. decls2DefaultClauseLexicallyScopedDeclarations로 둔다.
  4. 두 번째 CaseClauses가 present하면, decls3을 두 번째 CaseClausesLexicallyScopedDeclarations로 둔다.
  5. 그렇지 않으면, decls3을 새 empty List로 둔다.
  6. decls1, decls2, decls3list-concatenation을 반환한다.
CaseClauses : CaseClauses CaseClause
  1. decls1CaseClausesLexicallyScopedDeclarations로 둔다.
  2. decls2CaseClauseLexicallyScopedDeclarations로 둔다.
  3. decls1decls2list-concatenation을 반환한다.
CaseClause : case Expression : StatementListopt
  1. StatementList가 present하면, StatementListLexicallyScopedDeclarations를 반환한다.
  2. 새 empty List를 반환한다.
DefaultClause : default : StatementListopt
  1. StatementList가 present하면, StatementListLexicallyScopedDeclarations를 반환한다.
  2. 새 empty List를 반환한다.
LabelledStatement : LabelIdentifier : LabelledItem
  1. LabelledItemLexicallyScopedDeclarations를 반환한다.
LabelledItem : Statement
  1. 새 empty List를 반환한다.
LabelledItem : FunctionDeclaration
  1. « FunctionDeclaration »를 반환한다.
FunctionStatementList : [empty]
  1. 새 empty List를 반환한다.
FunctionStatementList : StatementList
  1. StatementListTopLevelLexicallyScopedDeclarations를 반환한다.
ClassStaticBlockStatementList : [empty]
  1. 새 empty List를 반환한다.
ClassStaticBlockStatementList : StatementList
  1. StatementListTopLevelLexicallyScopedDeclarations를 반환한다.
ConciseBody : ExpressionBody
  1. 새 empty List를 반환한다.
AsyncConciseBody : ExpressionBody
  1. 새 empty List를 반환한다.
Script : [empty]
  1. 새 empty List를 반환한다.
ScriptBody : StatementList
  1. StatementListTopLevelLexicallyScopedDeclarations를 반환한다.
Module : [empty]
  1. 새 empty List를 반환한다.
ModuleItemList : ModuleItemList ModuleItem
  1. decls1ModuleItemListLexicallyScopedDeclarations로 둔다.
  2. decls2ModuleItemLexicallyScopedDeclarations로 둔다.
  3. decls1decls2list-concatenation을 반환한다.
ModuleItem : ImportDeclaration
  1. 새 empty List를 반환한다.
ExportDeclaration : export ExportFromClause FromClause WithClauseopt ; export NamedExports ; export VariableStatement
  1. 새 empty List를 반환한다.
ExportDeclaration : export Declaration
  1. DeclarationDeclarationPart를 sole element로 하는 List를 반환한다.
ExportDeclaration : export default HoistableDeclaration
  1. HoistableDeclarationDeclarationPart를 sole element로 하는 List를 반환한다.
ExportDeclaration : export default ClassDeclaration
  1. ClassDeclaration을 sole element로 하는 List를 반환한다.
ExportDeclaration : export default AssignmentExpression ;
  1. this ExportDeclaration을 sole element로 하는 List를 반환한다.

8.2.8 Static Semantics: VarDeclaredNames

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

Statement : EmptyStatement ExpressionStatement ContinueStatement BreakStatement ReturnStatement ThrowStatement DebuggerStatement
  1. 새 empty List를 반환한다.
Block : { }
  1. 새 empty List를 반환한다.
StatementList : StatementList StatementListItem
  1. names1StatementListVarDeclaredNames로 둔다.
  2. names2StatementListItemVarDeclaredNames로 둔다.
  3. names1names2list-concatenation을 반환한다.
StatementListItem : Declaration
  1. 새 empty List를 반환한다.
VariableStatement : var VariableDeclarationList ;
  1. VariableDeclarationListBoundNames를 반환한다.
IfStatement : if ( Expression ) Statement else Statement
  1. names1을 첫 번째 StatementVarDeclaredNames로 둔다.
  2. names2를 두 번째 StatementVarDeclaredNames로 둔다.
  3. names1names2list-concatenation을 반환한다.
IfStatement : if ( Expression ) Statement
  1. StatementVarDeclaredNames를 반환한다.
DoWhileStatement : do Statement while ( Expression ) ;
  1. StatementVarDeclaredNames를 반환한다.
WhileStatement : while ( Expression ) Statement
  1. StatementVarDeclaredNames를 반환한다.
ForStatement : for ( Expressionopt ; Expressionopt ; Expressionopt ) Statement
  1. StatementVarDeclaredNames를 반환한다.
ForStatement : for ( var VariableDeclarationList ; Expressionopt ; Expressionopt ) Statement
  1. names1VariableDeclarationListBoundNames로 둔다.
  2. names2StatementVarDeclaredNames로 둔다.
  3. names1names2list-concatenation을 반환한다.
ForStatement : for ( LexicalDeclaration Expressionopt ; Expressionopt ) Statement
  1. StatementVarDeclaredNames를 반환한다.
ForInOfStatement : for ( LeftHandSideExpression in Expression ) Statement for ( ForDeclaration in Expression ) Statement for ( LeftHandSideExpression of AssignmentExpression ) Statement for ( ForDeclaration of AssignmentExpression ) Statement for await ( LeftHandSideExpression of AssignmentExpression ) Statement for await ( ForDeclaration of AssignmentExpression ) Statement
  1. StatementVarDeclaredNames를 반환한다.
ForInOfStatement : for ( var ForBinding in Expression ) Statement for ( var ForBinding of AssignmentExpression ) Statement for await ( var ForBinding of AssignmentExpression ) Statement
  1. names1ForBindingBoundNames로 둔다.
  2. names2StatementVarDeclaredNames로 둔다.
  3. names1names2list-concatenation을 반환한다.
Note

이 section은 Annex B.3.5에 의해 extended됩니다.

WithStatement : with ( Expression ) Statement
  1. StatementVarDeclaredNames를 반환한다.
SwitchStatement : switch ( Expression ) CaseBlock
  1. CaseBlockVarDeclaredNames를 반환한다.
CaseBlock : { }
  1. 새 empty List를 반환한다.
CaseBlock : { CaseClausesopt DefaultClause CaseClausesopt }
  1. 첫 번째 CaseClauses가 present하면, names1을 첫 번째 CaseClausesVarDeclaredNames로 둔다.
  2. 그렇지 않으면, names1을 새 empty List로 둔다.
  3. names2DefaultClauseVarDeclaredNames로 둔다.
  4. 두 번째 CaseClauses가 present하면, names3을 두 번째 CaseClausesVarDeclaredNames로 둔다.
  5. 그렇지 않으면, names3을 새 empty List로 둔다.
  6. names1, names2, names3list-concatenation을 반환한다.
CaseClauses : CaseClauses CaseClause
  1. names1CaseClausesVarDeclaredNames로 둔다.
  2. names2CaseClauseVarDeclaredNames로 둔다.
  3. names1names2list-concatenation을 반환한다.
CaseClause : case Expression : StatementListopt
  1. StatementList가 present하면, StatementListVarDeclaredNames를 반환한다.
  2. 새 empty List를 반환한다.
DefaultClause : default : StatementListopt
  1. StatementList가 present하면, StatementListVarDeclaredNames를 반환한다.
  2. 새 empty List를 반환한다.
LabelledStatement : LabelIdentifier : LabelledItem
  1. LabelledItemVarDeclaredNames를 반환한다.
LabelledItem : FunctionDeclaration
  1. 새 empty List를 반환한다.
TryStatement : try Block Catch
  1. names1BlockVarDeclaredNames로 둔다.
  2. names2CatchVarDeclaredNames로 둔다.
  3. names1names2list-concatenation을 반환한다.
TryStatement : try Block Finally
  1. names1BlockVarDeclaredNames로 둔다.
  2. names2FinallyVarDeclaredNames로 둔다.
  3. names1names2list-concatenation을 반환한다.
TryStatement : try Block Catch Finally
  1. names1BlockVarDeclaredNames로 둔다.
  2. names2CatchVarDeclaredNames로 둔다.
  3. names3FinallyVarDeclaredNames로 둔다.
  4. names1, names2, names3list-concatenation을 반환한다.
Catch : catch ( CatchParameter ) Block
  1. BlockVarDeclaredNames를 반환한다.
FunctionStatementList : [empty]
  1. 새 empty List를 반환한다.
FunctionStatementList : StatementList
  1. StatementListTopLevelVarDeclaredNames를 반환한다.
ClassStaticBlockStatementList : [empty]
  1. 새 empty List를 반환한다.
ClassStaticBlockStatementList : StatementList
  1. StatementListTopLevelVarDeclaredNames를 반환한다.
ConciseBody : ExpressionBody
  1. 새 empty List를 반환한다.
AsyncConciseBody : ExpressionBody
  1. 새 empty List를 반환한다.
Script : [empty]
  1. 새 empty List를 반환한다.
ScriptBody : StatementList
  1. StatementListTopLevelVarDeclaredNames를 반환한다.
ModuleItemList : ModuleItemList ModuleItem
  1. names1ModuleItemListVarDeclaredNames로 둔다.
  2. names2ModuleItemVarDeclaredNames로 둔다.
  3. names1names2list-concatenation을 반환한다.
ModuleItem : ImportDeclaration
  1. 새 empty List를 반환한다.
ModuleItem : ExportDeclaration
  1. ExportDeclarationexport VariableStatement이면, ExportDeclarationBoundNames를 반환한다.
  2. 새 empty List를 반환한다.

8.2.9 Static Semantics: VarScopedDeclarations

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

Statement : EmptyStatement ExpressionStatement ContinueStatement BreakStatement ReturnStatement ThrowStatement DebuggerStatement
  1. 새 empty List를 반환한다.
Block : { }
  1. 새 empty List를 반환한다.
StatementList : StatementList StatementListItem
  1. decls1StatementListVarScopedDeclarations로 둔다.
  2. decls2StatementListItemVarScopedDeclarations로 둔다.
  3. decls1decls2list-concatenation을 반환한다.
StatementListItem : Declaration
  1. 새 empty List를 반환한다.
VariableDeclarationList : VariableDeclaration
  1. « VariableDeclaration »를 반환한다.
VariableDeclarationList : VariableDeclarationList , VariableDeclaration
  1. decls1VariableDeclarationListVarScopedDeclarations로 둔다.
  2. decls1과 « VariableDeclaration »의 list-concatenation을 반환한다.
IfStatement : if ( Expression ) Statement else Statement
  1. decls1을 첫 번째 StatementVarScopedDeclarations로 둔다.
  2. decls2를 두 번째 StatementVarScopedDeclarations로 둔다.
  3. decls1decls2list-concatenation을 반환한다.
IfStatement : if ( Expression ) Statement
  1. StatementVarScopedDeclarations를 반환한다.
DoWhileStatement : do Statement while ( Expression ) ;
  1. StatementVarScopedDeclarations를 반환한다.
WhileStatement : while ( Expression ) Statement
  1. StatementVarScopedDeclarations를 반환한다.
ForStatement : for ( Expressionopt ; Expressionopt ; Expressionopt ) Statement
  1. StatementVarScopedDeclarations를 반환한다.
ForStatement : for ( var VariableDeclarationList ; Expressionopt ; Expressionopt ) Statement
  1. decls1VariableDeclarationListVarScopedDeclarations로 둔다.
  2. decls2StatementVarScopedDeclarations로 둔다.
  3. decls1decls2list-concatenation을 반환한다.
ForStatement : for ( LexicalDeclaration Expressionopt ; Expressionopt ) Statement
  1. StatementVarScopedDeclarations를 반환한다.
ForInOfStatement : for ( LeftHandSideExpression in Expression ) Statement for ( ForDeclaration in Expression ) Statement for ( LeftHandSideExpression of AssignmentExpression ) Statement for ( ForDeclaration of AssignmentExpression ) Statement for await ( LeftHandSideExpression of AssignmentExpression ) Statement for await ( ForDeclaration of AssignmentExpression ) Statement
  1. StatementVarScopedDeclarations를 반환한다.
ForInOfStatement : for ( var ForBinding in Expression ) Statement for ( var ForBinding of AssignmentExpression ) Statement for await ( var ForBinding of AssignmentExpression ) Statement
  1. decls1을 « ForBinding »로 둔다.
  2. decls2StatementVarScopedDeclarations로 둔다.
  3. decls1decls2list-concatenation을 반환한다.
Note

이 section은 Annex B.3.5에 의해 extended됩니다.

WithStatement : with ( Expression ) Statement
  1. StatementVarScopedDeclarations를 반환한다.
SwitchStatement : switch ( Expression ) CaseBlock
  1. CaseBlockVarScopedDeclarations를 반환한다.
CaseBlock : { }
  1. 새 empty List를 반환한다.
CaseBlock : { CaseClausesopt DefaultClause CaseClausesopt }
  1. 첫 번째 CaseClauses가 present하면, decls1을 첫 번째 CaseClausesVarScopedDeclarations로 둔다.
  2. 그렇지 않으면, decls1을 새 empty List로 둔다.
  3. decls2DefaultClauseVarScopedDeclarations로 둔다.
  4. 두 번째 CaseClauses가 present하면, decls3을 두 번째 CaseClausesVarScopedDeclarations로 둔다.
  5. 그렇지 않으면, decls3을 새 empty List로 둔다.
  6. decls1, decls2, decls3list-concatenation을 반환한다.
CaseClauses : CaseClauses CaseClause
  1. decls1CaseClausesVarScopedDeclarations로 둔다.
  2. decls2CaseClauseVarScopedDeclarations로 둔다.
  3. decls1decls2list-concatenation을 반환한다.
CaseClause : case Expression : StatementListopt
  1. StatementList가 present하면, StatementListVarScopedDeclarations를 반환한다.
  2. 새 empty List를 반환한다.
DefaultClause : default : StatementListopt
  1. StatementList가 present하면, StatementListVarScopedDeclarations를 반환한다.
  2. 새 empty List를 반환한다.
LabelledStatement : LabelIdentifier : LabelledItem
  1. LabelledItemVarScopedDeclarations를 반환한다.
LabelledItem : FunctionDeclaration
  1. 새 empty List를 반환한다.
TryStatement : try Block Catch
  1. decls1BlockVarScopedDeclarations로 둔다.
  2. decls2CatchVarScopedDeclarations로 둔다.
  3. decls1decls2list-concatenation을 반환한다.
TryStatement : try Block Finally
  1. decls1BlockVarScopedDeclarations로 둔다.
  2. decls2FinallyVarScopedDeclarations로 둔다.
  3. decls1decls2list-concatenation을 반환한다.
TryStatement : try Block Catch Finally
  1. decls1BlockVarScopedDeclarations로 둔다.
  2. decls2CatchVarScopedDeclarations로 둔다.
  3. decls3FinallyVarScopedDeclarations로 둔다.
  4. decls1, decls2, decls3list-concatenation을 반환한다.
Catch : catch ( CatchParameter ) Block
  1. BlockVarScopedDeclarations를 반환한다.
FunctionStatementList : [empty]
  1. 새 empty List를 반환한다.
FunctionStatementList : StatementList
  1. StatementListTopLevelVarScopedDeclarations를 반환한다.
ClassStaticBlockStatementList : [empty]
  1. 새 empty List를 반환한다.
ClassStaticBlockStatementList : StatementList
  1. StatementListTopLevelVarScopedDeclarations를 반환한다.
ConciseBody : ExpressionBody
  1. 새 empty List를 반환한다.
AsyncConciseBody : ExpressionBody
  1. 새 empty List를 반환한다.
Script : [empty]
  1. 새 empty List를 반환한다.
ScriptBody : StatementList
  1. StatementListTopLevelVarScopedDeclarations를 반환한다.
Module : [empty]
  1. 새 empty List를 반환한다.
ModuleItemList : ModuleItemList ModuleItem
  1. decls1ModuleItemListVarScopedDeclarations로 둔다.
  2. decls2ModuleItemVarScopedDeclarations로 둔다.
  3. decls1decls2list-concatenation을 반환한다.
ModuleItem : ImportDeclaration
  1. 새 empty List를 반환한다.
ModuleItem : ExportDeclaration
  1. ExportDeclarationexport VariableStatement이면, VariableStatementVarScopedDeclarations를 반환한다.
  2. 새 empty List를 반환한다.

8.2.10 Static Semantics: TopLevelLexicallyDeclaredNames

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

StatementList : StatementList StatementListItem
  1. names1StatementListTopLevelLexicallyDeclaredNames로 둔다.
  2. names2StatementListItemTopLevelLexicallyDeclaredNames로 둔다.
  3. names1names2list-concatenation을 반환한다.
StatementListItem : Statement
  1. 새 empty List를 반환한다.
StatementListItem : Declaration
  1. Declaration Declaration : HoistableDeclaration 이면, 다음을 수행한다.
    1. 새 empty List를 반환한다.
  2. DeclarationBoundNames를 반환한다.
Note

function 또는 script의 top level에서 function declaration은 lexical declaration처럼이 아니라 var declaration처럼 취급됩니다.

8.2.11 Static Semantics: TopLevelLexicallyScopedDeclarations

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

StatementList : StatementList StatementListItem
  1. decls1StatementListTopLevelLexicallyScopedDeclarations로 둔다.
  2. decls2StatementListItemTopLevelLexicallyScopedDeclarations로 둔다.
  3. decls1decls2list-concatenation을 반환한다.
StatementListItem : Statement
  1. 새 empty List를 반환한다.
StatementListItem : Declaration
  1. Declaration Declaration : HoistableDeclaration 이면, 다음을 수행한다.
    1. 새 empty List를 반환한다.
  2. « Declaration »를 반환한다.

8.2.12 Static Semantics: TopLevelVarDeclaredNames

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

StatementList : StatementList StatementListItem
  1. names1StatementListTopLevelVarDeclaredNames로 둔다.
  2. names2StatementListItemTopLevelVarDeclaredNames로 둔다.
  3. names1names2list-concatenation을 반환한다.
StatementListItem : Declaration
  1. Declaration Declaration : HoistableDeclaration 이면, 다음을 수행한다.
    1. HoistableDeclarationBoundNames를 반환한다.
  2. 새 empty List를 반환한다.
StatementListItem : Statement
  1. Statement Statement : LabelledStatement 이면, StatementTopLevelVarDeclaredNames를 반환한다.
  2. StatementVarDeclaredNames를 반환한다.
Note

function 또는 script의 top level에서 inner function declaration은 var declaration처럼 취급됩니다.

LabelledStatement : LabelIdentifier : LabelledItem
  1. LabelledItemTopLevelVarDeclaredNames를 반환한다.
LabelledItem : Statement
  1. Statement Statement : LabelledStatement 이면, StatementTopLevelVarDeclaredNames를 반환한다.
  2. StatementVarDeclaredNames를 반환한다.
LabelledItem : FunctionDeclaration
  1. FunctionDeclarationBoundNames를 반환한다.

8.2.13 Static Semantics: TopLevelVarScopedDeclarations

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

StatementList : StatementList StatementListItem
  1. decls1StatementListTopLevelVarScopedDeclarations로 둔다.
  2. decls2StatementListItemTopLevelVarScopedDeclarations로 둔다.
  3. decls1decls2list-concatenation을 반환한다.
StatementListItem : Statement
  1. Statement Statement : LabelledStatement 이면, StatementTopLevelVarScopedDeclarations를 반환한다.
  2. StatementVarScopedDeclarations를 반환한다.
StatementListItem : Declaration
  1. Declaration Declaration : HoistableDeclaration 이면, 다음을 수행한다.
    1. declHoistableDeclarationDeclarationPart로 둔다.
    2. « decl »를 반환한다.
  2. 새 empty List를 반환한다.
LabelledStatement : LabelIdentifier : LabelledItem
  1. LabelledItemTopLevelVarScopedDeclarations를 반환한다.
LabelledItem : Statement
  1. Statement Statement : LabelledStatement 이면, StatementTopLevelVarScopedDeclarations를 반환한다.
  2. StatementVarScopedDeclarations를 반환한다.
LabelledItem : FunctionDeclaration
  1. « FunctionDeclaration »를 반환한다.

8.3 Labels

8.3.1 Static Semantics: ContainsDuplicateLabels

The syntax-directed operation ContainsDuplicateLabels takes argument labelSet (a List of Strings) and returns a Boolean. It is defined piecewise over the following productions:

Statement : VariableStatement EmptyStatement ExpressionStatement ContinueStatement BreakStatement ReturnStatement ThrowStatement DebuggerStatement Block : { } StatementListItem : Declaration
  1. false를 반환한다.
StatementList : StatementList StatementListItem
  1. hasDuplicates를 argument labelSet를 가진 StatementListContainsDuplicateLabels로 둔다.
  2. hasDuplicatestrue이면, true를 반환한다.
  3. argument labelSet를 가진 StatementListItemContainsDuplicateLabels를 반환한다.
IfStatement : if ( Expression ) Statement else Statement
  1. hasDuplicate를 argument labelSet를 가진 첫 번째 StatementContainsDuplicateLabels로 둔다.
  2. hasDuplicatetrue이면, true를 반환한다.
  3. argument labelSet를 가진 두 번째 StatementContainsDuplicateLabels를 반환한다.
IfStatement : if ( Expression ) Statement
  1. argument labelSet를 가진 StatementContainsDuplicateLabels를 반환한다.
DoWhileStatement : do Statement while ( Expression ) ;
  1. argument labelSet를 가진 StatementContainsDuplicateLabels를 반환한다.
WhileStatement : while ( Expression ) Statement
  1. argument labelSet를 가진 StatementContainsDuplicateLabels를 반환한다.
ForStatement : for ( Expressionopt ; Expressionopt ; Expressionopt ) Statement for ( var VariableDeclarationList ; Expressionopt ; Expressionopt ) Statement for ( LexicalDeclaration Expressionopt ; Expressionopt ) Statement
  1. argument labelSet를 가진 StatementContainsDuplicateLabels를 반환한다.
ForInOfStatement : for ( LeftHandSideExpression in Expression ) Statement for ( var ForBinding in Expression ) Statement for ( ForDeclaration in Expression ) Statement for ( LeftHandSideExpression of AssignmentExpression ) Statement for ( var ForBinding of AssignmentExpression ) Statement for ( ForDeclaration of AssignmentExpression ) Statement for await ( LeftHandSideExpression of AssignmentExpression ) Statement for await ( var ForBinding of AssignmentExpression ) Statement for await ( ForDeclaration of AssignmentExpression ) Statement
  1. argument labelSet를 가진 StatementContainsDuplicateLabels를 반환한다.
Note

이 section은 Annex B.3.5에 의해 extended됩니다.

WithStatement : with ( Expression ) Statement
  1. argument labelSet를 가진 StatementContainsDuplicateLabels를 반환한다.
SwitchStatement : switch ( Expression ) CaseBlock
  1. argument labelSet를 가진 CaseBlockContainsDuplicateLabels를 반환한다.
CaseBlock : { }
  1. false를 반환한다.
CaseBlock : { CaseClausesopt DefaultClause CaseClausesopt }
  1. 첫 번째 CaseClauses가 present하면, 다음을 수행한다.
    1. argument labelSet를 가진 첫 번째 CaseClausesContainsDuplicateLabelstrue이면, true를 반환한다.
  2. argument labelSet를 가진 DefaultClauseContainsDuplicateLabelstrue이면, true를 반환한다.
  3. 두 번째 CaseClauses가 present하지 않으면, false를 반환한다.
  4. argument labelSet를 가진 두 번째 CaseClausesContainsDuplicateLabels를 반환한다.
CaseClauses : CaseClauses CaseClause
  1. hasDuplicates를 argument labelSet를 가진 CaseClausesContainsDuplicateLabels로 둔다.
  2. hasDuplicatestrue이면, true를 반환한다.
  3. argument labelSet를 가진 CaseClauseContainsDuplicateLabels를 반환한다.
CaseClause : case Expression : StatementListopt
  1. StatementList가 present하면, argument labelSet를 가진 StatementListContainsDuplicateLabels를 반환한다.
  2. false를 반환한다.
DefaultClause : default : StatementListopt
  1. StatementList가 present하면, argument labelSet를 가진 StatementListContainsDuplicateLabels를 반환한다.
  2. false를 반환한다.
LabelledStatement : LabelIdentifier : LabelledItem
  1. labelLabelIdentifierStringValue로 둔다.
  2. labelSetlabel을 contain하면, true를 반환한다.
  3. newLabelSetlabelSet와 « label »의 list-concatenation으로 둔다.
  4. argument newLabelSet를 가진 LabelledItemContainsDuplicateLabels를 반환한다.
LabelledItem : FunctionDeclaration
  1. false를 반환한다.
TryStatement : try Block Catch
  1. hasDuplicates를 argument labelSet를 가진 BlockContainsDuplicateLabels로 둔다.
  2. hasDuplicatestrue이면, true를 반환한다.
  3. argument labelSet를 가진 CatchContainsDuplicateLabels를 반환한다.
TryStatement : try Block Finally
  1. hasDuplicates를 argument labelSet를 가진 BlockContainsDuplicateLabels로 둔다.
  2. hasDuplicatestrue이면, true를 반환한다.
  3. argument labelSet를 가진 FinallyContainsDuplicateLabels를 반환한다.
TryStatement : try Block Catch Finally
  1. argument labelSet를 가진 BlockContainsDuplicateLabelstrue이면, true를 반환한다.
  2. argument labelSet를 가진 CatchContainsDuplicateLabelstrue이면, true를 반환한다.
  3. argument labelSet를 가진 FinallyContainsDuplicateLabels를 반환한다.
Catch : catch ( CatchParameter ) Block
  1. argument labelSet를 가진 BlockContainsDuplicateLabels를 반환한다.
FunctionStatementList : [empty]
  1. false를 반환한다.
ClassStaticBlockStatementList : [empty]
  1. false를 반환한다.
ModuleItemList : ModuleItemList ModuleItem
  1. hasDuplicates를 argument labelSet를 가진 ModuleItemListContainsDuplicateLabels로 둔다.
  2. hasDuplicatestrue이면, true를 반환한다.
  3. argument labelSet를 가진 ModuleItemContainsDuplicateLabels를 반환한다.
ModuleItem : ImportDeclaration ExportDeclaration
  1. false를 반환한다.

8.3.2 Static Semantics: ContainsUndefinedBreakTarget

The syntax-directed operation ContainsUndefinedBreakTarget takes argument labelSet (a List of Strings) and returns a Boolean. It is defined piecewise over the following productions:

Statement : VariableStatement EmptyStatement ExpressionStatement ContinueStatement ReturnStatement ThrowStatement DebuggerStatement Block : { } StatementListItem : Declaration
  1. false를 반환한다.
StatementList : StatementList StatementListItem
  1. hasUndefinedLabels를 argument labelSet를 가진 StatementListContainsUndefinedBreakTarget으로 둔다.
  2. hasUndefinedLabelstrue이면, true를 반환한다.
  3. argument labelSet를 가진 StatementListItemContainsUndefinedBreakTarget을 반환한다.
IfStatement : if ( Expression ) Statement else Statement
  1. hasUndefinedLabels를 argument labelSet를 가진 첫 번째 StatementContainsUndefinedBreakTarget으로 둔다.
  2. hasUndefinedLabelstrue이면, true를 반환한다.
  3. argument labelSet를 가진 두 번째 StatementContainsUndefinedBreakTarget을 반환한다.
IfStatement : if ( Expression ) Statement
  1. argument labelSet를 가진 StatementContainsUndefinedBreakTarget을 반환한다.
DoWhileStatement : do Statement while ( Expression ) ;
  1. argument labelSet를 가진 StatementContainsUndefinedBreakTarget을 반환한다.
WhileStatement : while ( Expression ) Statement
  1. argument labelSet를 가진 StatementContainsUndefinedBreakTarget을 반환한다.
ForStatement : for ( Expressionopt ; Expressionopt ; Expressionopt ) Statement for ( var VariableDeclarationList ; Expressionopt ; Expressionopt ) Statement for ( LexicalDeclaration Expressionopt ; Expressionopt ) Statement
  1. argument labelSet를 가진 StatementContainsUndefinedBreakTarget을 반환한다.
ForInOfStatement : for ( LeftHandSideExpression in Expression ) Statement for ( var ForBinding in Expression ) Statement for ( ForDeclaration in Expression ) Statement for ( LeftHandSideExpression of AssignmentExpression ) Statement for ( var ForBinding of AssignmentExpression ) Statement for ( ForDeclaration of AssignmentExpression ) Statement for await ( LeftHandSideExpression of AssignmentExpression ) Statement for await ( var ForBinding of AssignmentExpression ) Statement for await ( ForDeclaration of AssignmentExpression ) Statement
  1. argument labelSet를 가진 StatementContainsUndefinedBreakTarget을 반환한다.
Note

이 section은 Annex B.3.5에 의해 extended됩니다.

BreakStatement : break ;
  1. false를 반환한다.
BreakStatement : break LabelIdentifier ;
  1. labelSetLabelIdentifierStringValue를 contain하면, false를 반환한다.
  2. true를 반환한다.
WithStatement : with ( Expression ) Statement
  1. argument labelSet를 가진 StatementContainsUndefinedBreakTarget을 반환한다.
SwitchStatement : switch ( Expression ) CaseBlock
  1. argument labelSet를 가진 CaseBlockContainsUndefinedBreakTarget을 반환한다.
CaseBlock : { }
  1. false를 반환한다.
CaseBlock : { CaseClausesopt DefaultClause CaseClausesopt }
  1. 첫 번째 CaseClauses가 present하면, 다음을 수행한다.
    1. argument labelSet를 가진 첫 번째 CaseClausesContainsUndefinedBreakTargettrue이면, true를 반환한다.
  2. argument labelSet를 가진 DefaultClauseContainsUndefinedBreakTargettrue이면, true를 반환한다.
  3. 두 번째 CaseClauses가 present하지 않으면, false를 반환한다.
  4. argument labelSet를 가진 두 번째 CaseClausesContainsUndefinedBreakTarget을 반환한다.
CaseClauses : CaseClauses CaseClause
  1. hasUndefinedLabels를 argument labelSet를 가진 CaseClausesContainsUndefinedBreakTarget으로 둔다.
  2. hasUndefinedLabelstrue이면, true를 반환한다.
  3. argument labelSet를 가진 CaseClauseContainsUndefinedBreakTarget을 반환한다.
CaseClause : case Expression : StatementListopt
  1. StatementList가 present하면, argument labelSet를 가진 StatementListContainsUndefinedBreakTarget을 반환한다.
  2. false를 반환한다.
DefaultClause : default : StatementListopt
  1. StatementList가 present하면, argument labelSet를 가진 StatementListContainsUndefinedBreakTarget을 반환한다.
  2. false를 반환한다.
LabelledStatement : LabelIdentifier : LabelledItem
  1. labelLabelIdentifierStringValue로 둔다.
  2. newLabelSetlabelSet와 « label »의 list-concatenation으로 둔다.
  3. argument newLabelSet를 가진 LabelledItemContainsUndefinedBreakTarget을 반환한다.
LabelledItem : FunctionDeclaration
  1. false를 반환한다.
TryStatement : try Block Catch
  1. hasUndefinedLabels를 argument labelSet를 가진 BlockContainsUndefinedBreakTarget으로 둔다.
  2. hasUndefinedLabelstrue이면, true를 반환한다.
  3. argument labelSet를 가진 CatchContainsUndefinedBreakTarget을 반환한다.
TryStatement : try Block Finally
  1. hasUndefinedLabels를 argument labelSet를 가진 BlockContainsUndefinedBreakTarget으로 둔다.
  2. hasUndefinedLabelstrue이면, true를 반환한다.
  3. argument labelSet를 가진 FinallyContainsUndefinedBreakTarget을 반환한다.
TryStatement : try Block Catch Finally
  1. argument labelSet를 가진 BlockContainsUndefinedBreakTargettrue이면, true를 반환한다.
  2. argument labelSet를 가진 CatchContainsUndefinedBreakTargettrue이면, true를 반환한다.
  3. argument labelSet를 가진 FinallyContainsUndefinedBreakTarget을 반환한다.
Catch : catch ( CatchParameter ) Block
  1. argument labelSet를 가진 BlockContainsUndefinedBreakTarget을 반환한다.
FunctionStatementList : [empty]
  1. false를 반환한다.
ClassStaticBlockStatementList : [empty]
  1. false를 반환한다.
ModuleItemList : ModuleItemList ModuleItem
  1. hasUndefinedLabels를 argument labelSet를 가진 ModuleItemListContainsUndefinedBreakTarget으로 둔다.
  2. hasUndefinedLabelstrue이면, true를 반환한다.
  3. argument labelSet를 가진 ModuleItemContainsUndefinedBreakTarget을 반환한다.
ModuleItem : ImportDeclaration ExportDeclaration
  1. false를 반환한다.

8.3.3 Static Semantics: ContainsUndefinedContinueTarget

The syntax-directed operation ContainsUndefinedContinueTarget takes arguments iterationSet (a List of Strings) and labelSet (a List of Strings) and returns a Boolean. It is defined piecewise over the following productions:

Statement : VariableStatement EmptyStatement ExpressionStatement BreakStatement ReturnStatement ThrowStatement DebuggerStatement Block : { } StatementListItem : Declaration
  1. false를 반환한다.
Statement : BlockStatement
  1. arguments iterationSet와 « »를 가진 BlockStatementContainsUndefinedContinueTarget을 반환한다.
BreakableStatement : IterationStatement
  1. newIterationSetiterationSetlabelSetlist-concatenation으로 둔다.
  2. arguments newIterationSet와 « »를 가진 IterationStatementContainsUndefinedContinueTarget을 반환한다.
StatementList : StatementList StatementListItem
  1. hasUndefinedLabels를 arguments iterationSet와 « »를 가진 StatementListContainsUndefinedContinueTarget으로 둔다.
  2. hasUndefinedLabelstrue이면, true를 반환한다.
  3. arguments iterationSet와 « »를 가진 StatementListItemContainsUndefinedContinueTarget을 반환한다.
IfStatement : if ( Expression ) Statement else Statement
  1. hasUndefinedLabels를 arguments iterationSet와 « »를 가진 첫 번째 StatementContainsUndefinedContinueTarget으로 둔다.
  2. hasUndefinedLabelstrue이면, true를 반환한다.
  3. arguments iterationSet와 « »를 가진 두 번째 StatementContainsUndefinedContinueTarget을 반환한다.
IfStatement : if ( Expression ) Statement
  1. arguments iterationSet와 « »를 가진 StatementContainsUndefinedContinueTarget을 반환한다.
DoWhileStatement : do Statement while ( Expression ) ;
  1. arguments iterationSet와 « »를 가진 StatementContainsUndefinedContinueTarget을 반환한다.
WhileStatement : while ( Expression ) Statement
  1. arguments iterationSet와 « »를 가진 StatementContainsUndefinedContinueTarget을 반환한다.
ForStatement : for ( Expressionopt ; Expressionopt ; Expressionopt ) Statement for ( var VariableDeclarationList ; Expressionopt ; Expressionopt ) Statement for ( LexicalDeclaration Expressionopt ; Expressionopt ) Statement
  1. arguments iterationSet와 « »를 가진 StatementContainsUndefinedContinueTarget을 반환한다.
ForInOfStatement : for ( LeftHandSideExpression in Expression ) Statement for ( var ForBinding in Expression ) Statement for ( ForDeclaration in Expression ) Statement for ( LeftHandSideExpression of AssignmentExpression ) Statement for ( var ForBinding of AssignmentExpression ) Statement for ( ForDeclaration of AssignmentExpression ) Statement for await ( LeftHandSideExpression of AssignmentExpression ) Statement for await ( var ForBinding of AssignmentExpression ) Statement for await ( ForDeclaration of AssignmentExpression ) Statement
  1. arguments iterationSet와 « »를 가진 StatementContainsUndefinedContinueTarget을 반환한다.
Note

이 section은 Annex B.3.5에 의해 extended됩니다.

ContinueStatement : continue ;
  1. false를 반환한다.
ContinueStatement : continue LabelIdentifier ;
  1. iterationSetLabelIdentifierStringValue를 contain하면, false를 반환한다.
  2. true를 반환한다.
WithStatement : with ( Expression ) Statement
  1. arguments iterationSet와 « »를 가진 StatementContainsUndefinedContinueTarget을 반환한다.
SwitchStatement : switch ( Expression ) CaseBlock
  1. arguments iterationSet와 « »를 가진 CaseBlockContainsUndefinedContinueTarget을 반환한다.
CaseBlock : { }
  1. false를 반환한다.
CaseBlock : { CaseClausesopt DefaultClause CaseClausesopt }
  1. 첫 번째 CaseClauses가 present하면, 다음을 수행한다.
    1. arguments iterationSet와 « »를 가진 첫 번째 CaseClausesContainsUndefinedContinueTargettrue이면, true를 반환한다.
  2. arguments iterationSet와 « »를 가진 DefaultClauseContainsUndefinedContinueTargettrue이면, true를 반환한다.
  3. 두 번째 CaseClauses가 present하지 않으면, false를 반환한다.
  4. arguments iterationSet와 « »를 가진 두 번째 CaseClausesContainsUndefinedContinueTarget을 반환한다.
CaseClauses : CaseClauses CaseClause
  1. hasUndefinedLabels를 arguments iterationSet와 « »를 가진 CaseClausesContainsUndefinedContinueTarget으로 둔다.
  2. hasUndefinedLabelstrue이면, true를 반환한다.
  3. arguments iterationSet와 « »를 가진 CaseClauseContainsUndefinedContinueTarget을 반환한다.
CaseClause : case Expression : StatementListopt
  1. StatementList가 present하면, arguments iterationSet와 « »를 가진 StatementListContainsUndefinedContinueTarget을 반환한다.
  2. false를 반환한다.
DefaultClause : default : StatementListopt
  1. StatementList가 present하면, arguments iterationSet와 « »를 가진 StatementListContainsUndefinedContinueTarget을 반환한다.
  2. false를 반환한다.
LabelledStatement : LabelIdentifier : LabelledItem
  1. labelLabelIdentifierStringValue로 둔다.
  2. newLabelSetlabelSet와 « label »의 list-concatenation으로 둔다.
  3. arguments iterationSetnewLabelSet를 가진 LabelledItemContainsUndefinedContinueTarget을 반환한다.
LabelledItem : FunctionDeclaration
  1. false를 반환한다.
TryStatement : try Block Catch
  1. hasUndefinedLabels를 arguments iterationSet와 « »를 가진 BlockContainsUndefinedContinueTarget으로 둔다.
  2. hasUndefinedLabelstrue이면, true를 반환한다.
  3. arguments iterationSet와 « »를 가진 CatchContainsUndefinedContinueTarget을 반환한다.
TryStatement : try Block Finally
  1. hasUndefinedLabels를 arguments iterationSet와 « »를 가진 BlockContainsUndefinedContinueTarget으로 둔다.
  2. hasUndefinedLabelstrue이면, true를 반환한다.
  3. arguments iterationSet와 « »를 가진 FinallyContainsUndefinedContinueTarget을 반환한다.
TryStatement : try Block Catch Finally
  1. arguments iterationSet와 « »를 가진 BlockContainsUndefinedContinueTargettrue이면, true를 반환한다.
  2. arguments iterationSet와 « »를 가진 CatchContainsUndefinedContinueTargettrue이면, true를 반환한다.
  3. arguments iterationSet와 « »를 가진 FinallyContainsUndefinedContinueTarget을 반환한다.
Catch : catch ( CatchParameter ) Block
  1. arguments iterationSet와 « »를 가진 BlockContainsUndefinedContinueTarget을 반환한다.
FunctionStatementList : [empty]
  1. false를 반환한다.
ClassStaticBlockStatementList : [empty]
  1. false를 반환한다.
ModuleItemList : ModuleItemList ModuleItem
  1. hasUndefinedLabels를 arguments iterationSet와 « »를 가진 ModuleItemListContainsUndefinedContinueTarget으로 둔다.
  2. hasUndefinedLabelstrue이면, true를 반환한다.
  3. arguments iterationSet와 « »를 가진 ModuleItemContainsUndefinedContinueTarget을 반환한다.
ModuleItem : ImportDeclaration ExportDeclaration
  1. false를 반환한다.

8.4 Function Name Inference

8.4.1 Static Semantics: HasName

The syntax-directed operation HasName takes no arguments and returns a Boolean. It is defined piecewise over the following productions:

PrimaryExpression : CoverParenthesizedExpressionAndArrowParameterList
  1. exprCoverParenthesizedExpressionAndArrowParameterList가 cover하는 ParenthesizedExpression으로 둔다.
  2. exprIsFunctionDefinitionfalse이면, false를 반환한다.
  3. exprHasName을 반환한다.
FunctionExpression : function ( FormalParameters ) { FunctionBody } GeneratorExpression : function * ( FormalParameters ) { GeneratorBody } AsyncGeneratorExpression : async function * ( FormalParameters ) { AsyncGeneratorBody } AsyncFunctionExpression : async function ( FormalParameters ) { AsyncFunctionBody } ArrowFunction : ArrowParameters => ConciseBody AsyncArrowFunction : async AsyncArrowBindingIdentifier => AsyncConciseBody CoverCallExpressionAndAsyncArrowHead => AsyncConciseBody ClassExpression : class ClassTail
  1. false를 반환한다.
FunctionExpression : function BindingIdentifier ( FormalParameters ) { FunctionBody } GeneratorExpression : function * BindingIdentifier ( FormalParameters ) { GeneratorBody } AsyncGeneratorExpression : async function * BindingIdentifier ( FormalParameters ) { AsyncGeneratorBody } AsyncFunctionExpression : async function BindingIdentifier ( FormalParameters ) { AsyncFunctionBody } ClassExpression : class BindingIdentifier ClassTail
  1. true를 반환한다.

8.4.2 Static Semantics: IsFunctionDefinition

The syntax-directed operation IsFunctionDefinition takes no arguments and returns a Boolean. It is defined piecewise over the following productions:

PrimaryExpression : CoverParenthesizedExpressionAndArrowParameterList
  1. exprCoverParenthesizedExpressionAndArrowParameterList가 cover하는 ParenthesizedExpression으로 둔다.
  2. exprIsFunctionDefinition을 반환한다.
PrimaryExpression : this IdentifierReference Literal ArrayLiteral ObjectLiteral RegularExpressionLiteral TemplateLiteral MemberExpression : MemberExpression [ Expression ] MemberExpression . IdentifierName MemberExpression TemplateLiteral SuperProperty MetaProperty new MemberExpression Arguments MemberExpression . PrivateIdentifier NewExpression : new NewExpression LeftHandSideExpression : CallExpression OptionalExpression UpdateExpression : LeftHandSideExpression ++ LeftHandSideExpression -- ++ UnaryExpression -- UnaryExpression UnaryExpression : delete UnaryExpression void UnaryExpression typeof UnaryExpression + UnaryExpression - UnaryExpression ~ UnaryExpression ! UnaryExpression CoverAwaitExpressionAndAwaitUsingDeclarationHead ExponentiationExpression : UpdateExpression ** ExponentiationExpression MultiplicativeExpression : MultiplicativeExpression MultiplicativeOperator ExponentiationExpression AdditiveExpression : AdditiveExpression + MultiplicativeExpression AdditiveExpression - MultiplicativeExpression ShiftExpression : ShiftExpression << AdditiveExpression ShiftExpression >> AdditiveExpression ShiftExpression >>> AdditiveExpression RelationalExpression : RelationalExpression < ShiftExpression RelationalExpression > ShiftExpression RelationalExpression <= ShiftExpression RelationalExpression >= ShiftExpression RelationalExpression instanceof ShiftExpression RelationalExpression in ShiftExpression PrivateIdentifier in ShiftExpression EqualityExpression : EqualityExpression == RelationalExpression EqualityExpression != RelationalExpression EqualityExpression === RelationalExpression EqualityExpression !== RelationalExpression BitwiseANDExpression : BitwiseANDExpression & EqualityExpression BitwiseXORExpression : BitwiseXORExpression ^ BitwiseANDExpression BitwiseORExpression : BitwiseORExpression | BitwiseXORExpression LogicalANDExpression : LogicalANDExpression && BitwiseORExpression LogicalORExpression : LogicalORExpression || LogicalANDExpression CoalesceExpression : CoalesceExpressionHead ?? BitwiseORExpression ConditionalExpression : ShortCircuitExpression ? AssignmentExpression : AssignmentExpression AssignmentExpression : YieldExpression LeftHandSideExpression = AssignmentExpression LeftHandSideExpression AssignmentOperator AssignmentExpression LeftHandSideExpression &&= AssignmentExpression LeftHandSideExpression ||= AssignmentExpression LeftHandSideExpression ??= AssignmentExpression Expression : Expression , AssignmentExpression
  1. false를 반환한다.
AssignmentExpression : ArrowFunction AsyncArrowFunction FunctionExpression : function BindingIdentifieropt ( FormalParameters ) { FunctionBody } GeneratorExpression : function * BindingIdentifieropt ( FormalParameters ) { GeneratorBody } AsyncGeneratorExpression : async function * BindingIdentifieropt ( FormalParameters ) { AsyncGeneratorBody } AsyncFunctionExpression : async function BindingIdentifieropt ( FormalParameters ) { AsyncFunctionBody } ClassExpression : class BindingIdentifieropt ClassTail
  1. true를 반환한다.

8.4.3 Static Semantics: IsAnonymousFunctionDefinition ( expr )

The abstract operation IsAnonymousFunctionDefinition takes argument expr (an AssignmentExpression Parse Node, an Initializer Parse Node, or an Expression Parse Node) and returns a Boolean. argument가 name을 bind하지 않는 function definition인지 determine합니다. It performs the following steps when called:

  1. exprIsFunctionDefinitionfalse이면, false를 반환한다.
  2. hasNameexprHasName으로 둔다.
  3. hasNametrue이면, false를 반환한다.
  4. true를 반환한다.

8.4.4 Static Semantics: IsIdentifierRef

The syntax-directed operation IsIdentifierRef takes no arguments and returns a Boolean. It is defined piecewise over the following productions:

PrimaryExpression : IdentifierReference
  1. true를 반환한다.
PrimaryExpression : this Literal ArrayLiteral ObjectLiteral FunctionExpression ClassExpression GeneratorExpression AsyncFunctionExpression AsyncGeneratorExpression RegularExpressionLiteral TemplateLiteral CoverParenthesizedExpressionAndArrowParameterList MemberExpression : MemberExpression [ Expression ] MemberExpression . IdentifierName MemberExpression TemplateLiteral SuperProperty MetaProperty new MemberExpression Arguments MemberExpression . PrivateIdentifier NewExpression : new NewExpression LeftHandSideExpression : CallExpression OptionalExpression
  1. false를 반환한다.

8.4.5 Runtime Semantics: NamedEvaluation

The syntax-directed operation NamedEvaluation takes argument name (a property key or a Private Name) and returns either a normal completion containing a function object or an abrupt completion. It is defined piecewise over the following productions:

PrimaryExpression : CoverParenthesizedExpressionAndArrowParameterList
  1. exprCoverParenthesizedExpressionAndArrowParameterList가 cover하는 ParenthesizedExpression으로 둔다.
  2. argument name을 가진 exprNamedEvaluation을 ? 반환한다.
ParenthesizedExpression : ( Expression )
  1. Assert: IsAnonymousFunctionDefinition(Expression)은 true이다.
  2. argument name을 가진 ExpressionNamedEvaluation을 ? 반환한다.
FunctionExpression : function ( FormalParameters ) { FunctionBody }
  1. argument name을 가진 FunctionExpressionInstantiateOrdinaryFunctionExpression을 반환한다.
GeneratorExpression : function * ( FormalParameters ) { GeneratorBody }
  1. argument name을 가진 GeneratorExpressionInstantiateGeneratorFunctionExpression을 반환한다.
AsyncGeneratorExpression : async function * ( FormalParameters ) { AsyncGeneratorBody }
  1. argument name을 가진 AsyncGeneratorExpressionInstantiateAsyncGeneratorFunctionExpression을 반환한다.
AsyncFunctionExpression : async function ( FormalParameters ) { AsyncFunctionBody }
  1. argument name을 가진 AsyncFunctionExpressionInstantiateAsyncFunctionExpression을 반환한다.
ArrowFunction : ArrowParameters => ConciseBody
  1. argument name을 가진 ArrowFunctionInstantiateArrowFunctionExpression을 반환한다.
AsyncArrowFunction : async AsyncArrowBindingIdentifier => AsyncConciseBody CoverCallExpressionAndAsyncArrowHead => AsyncConciseBody
  1. argument name을 가진 AsyncArrowFunctionInstantiateAsyncArrowFunctionExpression을 반환한다.
ClassExpression : class ClassTail
  1. sourceTextClassExpression에 matched된 source text로 둔다.
  2. arguments undefined, name, sourceText를 가진 ClassTailClassDefinitionEvaluation을 ? 반환한다.

8.5 Contains

8.5.1 Static Semantics: Contains

The syntax-directed operation Contains takes argument symbol (a grammar symbol) and returns a Boolean.

아래에 listed되지 않은 이 명세의 모든 grammar production alternative는 implicitly 다음 default definition of Contains를 가집니다:

  1. Parse Node의 각 child node child에 대해, 다음을 수행한다.
    1. childsymbol의 instance이면, true를 반환한다.
    2. child가 nonterminal의 instance이면, 다음을 수행한다.
      1. containedchild Contains symbol의 result로 둔다.
      2. containedtrue이면, true를 반환한다.
  2. false를 반환한다.
FunctionDeclaration : function BindingIdentifier ( FormalParameters ) { FunctionBody } function ( FormalParameters ) { FunctionBody } FunctionExpression : function BindingIdentifieropt ( FormalParameters ) { FunctionBody } GeneratorDeclaration : function * BindingIdentifier ( FormalParameters ) { GeneratorBody } function * ( FormalParameters ) { GeneratorBody } GeneratorExpression : function * BindingIdentifieropt ( FormalParameters ) { GeneratorBody } AsyncGeneratorDeclaration : async function * BindingIdentifier ( FormalParameters ) { AsyncGeneratorBody } async function * ( FormalParameters ) { AsyncGeneratorBody } AsyncGeneratorExpression : async function * BindingIdentifieropt ( FormalParameters ) { AsyncGeneratorBody } AsyncFunctionDeclaration : async function BindingIdentifier ( FormalParameters ) { AsyncFunctionBody } async function ( FormalParameters ) { AsyncFunctionBody } AsyncFunctionExpression : async function BindingIdentifieropt ( FormalParameters ) { AsyncFunctionBody }
  1. false를 반환한다.
Note 1

substructure에 depend하는 static semantic rule은 일반적으로 function definition 내부를 look into하지 않습니다.

ClassTail : ClassHeritageopt { ClassBody }
  1. symbolClassBody이면, true를 반환한다.
  2. symbolClassHeritage이면, 다음을 수행한다.
    1. ClassHeritage가 present하면, true를 반환한다.
    2. false를 반환한다.
  3. ClassHeritage가 present하면, 다음을 수행한다.
    1. ClassHeritage Contains symboltrue이면, true를 반환한다.
  4. argument symbol을 가진 ClassBodyComputedPropertyContains의 result를 반환한다.
Note 2

substructure에 depend하는 static semantic rule은 일반적으로 PropertyName을 제외하고 class body 내부를 look into하지 않습니다.

ClassStaticBlock : static { ClassStaticBlockBody }
  1. false를 반환한다.
Note 3

substructure에 depend하는 static semantic rule은 일반적으로 static initialization block 내부를 look into하지 않습니다.

ArrowFunction : ArrowParameters => ConciseBody
  1. symbolNewTarget, SuperProperty, SuperCall, super, 또는 this 중 하나가 아니면, false를 반환한다.
  2. ArrowParameters Contains symboltrue이면, true를 반환한다.
  3. ConciseBody Contains symbol을 반환한다.
ArrowParameters : CoverParenthesizedExpressionAndArrowParameterList
  1. formalsCoverParenthesizedExpressionAndArrowParameterList가 cover하는 ArrowFormalParameters로 둔다.
  2. formals Contains symbol을 반환한다.
AsyncArrowFunction : async AsyncArrowBindingIdentifier => AsyncConciseBody
  1. symbolNewTarget, SuperProperty, SuperCall, super, 또는 this 중 하나가 아니면, false를 반환한다.
  2. AsyncConciseBody Contains symbol을 반환한다.
AsyncArrowFunction : CoverCallExpressionAndAsyncArrowHead => AsyncConciseBody
  1. symbolNewTarget, SuperProperty, SuperCall, super, 또는 this 중 하나가 아니면, false를 반환한다.
  2. headCoverCallExpressionAndAsyncArrowHead가 cover하는 AsyncArrowHead로 둔다.
  3. head Contains symboltrue이면, true를 반환한다.
  4. AsyncConciseBody Contains symbol을 반환한다.
Note 4

Contains는 ArrowFunction 또는 AsyncArrowFunction 안에서 new.target, this, super usage를 detect하는 데 사용됩니다.

PropertyDefinition : MethodDefinition
  1. symbolMethodDefinition이면, true를 반환한다.
  2. argument symbol을 가진 MethodDefinitionComputedPropertyContains의 result를 반환한다.
LiteralPropertyName : IdentifierName
  1. false를 반환한다.
MemberExpression : MemberExpression . IdentifierName
  1. MemberExpression Contains symboltrue이면, true를 반환한다.
  2. false를 반환한다.
SuperProperty : super . IdentifierName
  1. symbolReservedWord super이면, true를 반환한다.
  2. false를 반환한다.
CallExpression : CallExpression . IdentifierName
  1. CallExpression Contains symboltrue이면, true를 반환한다.
  2. false를 반환한다.
OptionalChain : ?. IdentifierName
  1. false를 반환한다.
OptionalChain : OptionalChain . IdentifierName
  1. OptionalChain Contains symboltrue이면, true를 반환한다.
  2. false를 반환한다.

8.5.2 Static Semantics: ComputedPropertyContains

The syntax-directed operation ComputedPropertyContains takes argument symbol (a grammar symbol) and returns a Boolean. It is defined piecewise over the following productions:

ClassElementName : PrivateIdentifier PropertyName : LiteralPropertyName
  1. false를 반환한다.
PropertyName : ComputedPropertyName
  1. ComputedPropertyName Contains symbol의 result를 반환한다.
MethodDefinition : ClassElementName ( UniqueFormalParameters ) { FunctionBody } get ClassElementName ( ) { FunctionBody } set ClassElementName ( PropertySetParameterList ) { FunctionBody }
  1. argument symbol을 가진 ClassElementNameComputedPropertyContains의 result를 반환한다.
GeneratorMethod : * ClassElementName ( UniqueFormalParameters ) { GeneratorBody }
  1. argument symbol을 가진 ClassElementNameComputedPropertyContains의 result를 반환한다.
AsyncGeneratorMethod : async * ClassElementName ( UniqueFormalParameters ) { AsyncGeneratorBody }
  1. argument symbol을 가진 ClassElementNameComputedPropertyContains의 result를 반환한다.
ClassElementList : ClassElementList ClassElement
  1. inList를 argument symbol을 가진 ClassElementListComputedPropertyContains로 둔다.
  2. inListtrue이면, true를 반환한다.
  3. argument symbol을 가진 ClassElementComputedPropertyContains의 result를 반환한다.
ClassElement : ClassStaticBlock
  1. false를 반환한다.
ClassElement : ;
  1. false를 반환한다.
AsyncMethod : async ClassElementName ( UniqueFormalParameters ) { AsyncFunctionBody }
  1. argument symbol을 가진 ClassElementNameComputedPropertyContains의 result를 반환한다.
FieldDefinition : ClassElementName Initializeropt
  1. argument symbol을 가진 ClassElementNameComputedPropertyContains의 result를 반환한다.

8.6 Miscellaneous

이 operation들은 명세 전반의 여러 곳에서 사용됩니다.

8.6.1 Runtime Semantics: InstantiateFunctionObject

The syntax-directed operation InstantiateFunctionObject takes arguments envRecord (an Environment Record) and privateEnv (a PrivateEnvironment Record or null) and returns an ECMAScript function object. It is defined piecewise over the following productions:

FunctionDeclaration : function BindingIdentifier ( FormalParameters ) { FunctionBody } function ( FormalParameters ) { FunctionBody }
  1. arguments envRecordprivateEnv를 가진 FunctionDeclarationInstantiateOrdinaryFunctionObject를 반환한다.
GeneratorDeclaration : function * BindingIdentifier ( FormalParameters ) { GeneratorBody } function * ( FormalParameters ) { GeneratorBody }
  1. arguments envRecordprivateEnv를 가진 GeneratorDeclarationInstantiateGeneratorFunctionObject를 반환한다.
AsyncGeneratorDeclaration : async function * BindingIdentifier ( FormalParameters ) { AsyncGeneratorBody } async function * ( FormalParameters ) { AsyncGeneratorBody }
  1. arguments envRecordprivateEnv를 가진 AsyncGeneratorDeclarationInstantiateAsyncGeneratorFunctionObject를 반환한다.
AsyncFunctionDeclaration : async function BindingIdentifier ( FormalParameters ) { AsyncFunctionBody } async function ( FormalParameters ) { AsyncFunctionBody }
  1. arguments envRecordprivateEnv를 가진 AsyncFunctionDeclarationInstantiateAsyncFunctionObject를 반환한다.

8.6.2 Runtime Semantics: BindingInitialization

The syntax-directed operation BindingInitialization takes arguments value (an ECMAScript language value) and envRecord (an Environment Record or undefined) and returns either a normal completion containing unused or an abrupt completion.

Note

undefined는 initialization value를 assign하기 위해 PutValue operation을 사용해야 함을 나타내기 위해 envRecord로 passed됩니다. 이는 var statement와 일부 non-strict function의 formal parameter list의 경우입니다(10.2.11 참조). 이러한 경우 lexical binding은 initializer의 evaluation 전에 hoisted되고 preinitialized됩니다.

It is defined piecewise over the following productions:

BindingIdentifier : Identifier
  1. nameIdentifierStringValue로 둔다.
  2. InitializeBoundName(name, value, envRecord)을 ? 반환한다.
BindingIdentifier : yield
  1. InitializeBoundName("yield", value, envRecord)을 ? 반환한다.
BindingIdentifier : await
  1. InitializeBoundName("await", value, envRecord)을 ? 반환한다.
BindingPattern : ObjectBindingPattern
  1. RequireObjectCoercible(value)을 ? 수행한다.
  2. arguments valueenvRecord를 가진 ObjectBindingPatternBindingInitialization을 ? 반환한다.
BindingPattern : ArrayBindingPattern
  1. iteratorRecord를 ? GetIterator(value, sync)로 둔다.
  2. result를 arguments iteratorRecordenvRecord를 가진 ArrayBindingPatternIteratorBindingInitializationCompletion으로 둔다.
  3. iteratorRecord.[[Done]]false이면, IteratorClose(iteratorRecord, result)를 ? 반환한다.
  4. result를 ? 반환한다.
ObjectBindingPattern : { }
  1. unused를 반환한다.
ObjectBindingPattern : { BindingPropertyList } { BindingPropertyList , }
  1. arguments valueenvRecord를 가진 BindingPropertyListPropertyBindingInitialization을 ? 수행한다.
  2. unused를 반환한다.
ObjectBindingPattern : { BindingRestProperty }
  1. excludedNames를 새 empty List로 둔다.
  2. arguments value, envRecord, excludedNames를 가진 BindingRestPropertyRestBindingInitialization을 ? 반환한다.
ObjectBindingPattern : { BindingPropertyList , BindingRestProperty }
  1. excludedNames를 arguments valueenvRecord를 가진 BindingPropertyListPropertyBindingInitialization으로 ? 둔다.
  2. arguments value, envRecord, excludedNames를 가진 BindingRestPropertyRestBindingInitialization을 ? 반환한다.

8.6.2.1 InitializeBoundName ( name, value, envRecord )

The abstract operation InitializeBoundName takes arguments name (a String), value (an ECMAScript language value), and envRecord (an Environment Record or undefined) and returns either a normal completion containing unused or an abrupt completion. It performs the following steps when called:

  1. envRecordundefined가 아니면, 다음을 수행한다.
    1. envRecord.InitializeBinding(name, value)를 수행한다.
    2. unused를 반환한다.
  2. lhs를 ? ResolveBinding(name)으로 둔다.
  3. PutValue(lhs, value)를 ? 반환한다.

8.6.3 Runtime Semantics: IteratorBindingInitialization

The syntax-directed operation IteratorBindingInitialization takes arguments iteratorRecord (an Iterator Record) and envRecord (an Environment Record or undefined) and returns either a normal completion containing unused or an abrupt completion.

Note

undefinedenvRecord로 passed되면 initialization value를 assign하기 위해 PutValue operation을 사용해야 함을 나타냅니다. 이는 non-strict function의 formal parameter list의 경우입니다. 그 경우 formal parameter binding은 같은 name을 가진 multiple parameter의 possibility를 처리하기 위해 preinitialized됩니다.

It is defined piecewise over the following productions:

ArrayBindingPattern : [ ]
  1. unused를 반환한다.
ArrayBindingPattern : [ Elision ]
  1. argument iteratorRecord를 가진 ElisionIteratorDestructuringAssignmentEvaluation을 ? 반환한다.
ArrayBindingPattern : [ Elisionopt BindingRestElement ]
  1. Elision이 present하면, 다음을 수행한다.
    1. argument iteratorRecord를 가진 ElisionIteratorDestructuringAssignmentEvaluation을 ? 수행한다.
  2. arguments iteratorRecordenvRecord를 가진 BindingRestElementIteratorBindingInitialization을 ? 반환한다.
ArrayBindingPattern : [ BindingElementList , Elision ]
  1. arguments iteratorRecordenvRecord를 가진 BindingElementListIteratorBindingInitialization을 ? 수행한다.
  2. argument iteratorRecord를 가진 ElisionIteratorDestructuringAssignmentEvaluation을 ? 반환한다.
ArrayBindingPattern : [ BindingElementList , Elisionopt BindingRestElement ]
  1. arguments iteratorRecordenvRecord를 가진 BindingElementListIteratorBindingInitialization을 ? 수행한다.
  2. Elision이 present하면, 다음을 수행한다.
    1. argument iteratorRecord를 가진 ElisionIteratorDestructuringAssignmentEvaluation을 ? 수행한다.
  3. arguments iteratorRecordenvRecord를 가진 BindingRestElementIteratorBindingInitialization을 ? 반환한다.
BindingElementList : BindingElementList , BindingElisionElement
  1. arguments iteratorRecordenvRecord를 가진 BindingElementListIteratorBindingInitialization을 ? 수행한다.
  2. arguments iteratorRecordenvRecord를 가진 BindingElisionElementIteratorBindingInitialization을 ? 반환한다.
BindingElisionElement : Elision BindingElement
  1. argument iteratorRecord를 가진 ElisionIteratorDestructuringAssignmentEvaluation을 ? 수행한다.
  2. arguments iteratorRecordenvRecord를 가진 BindingElementIteratorBindingInitialization을 ? 반환한다.
SingleNameBinding : BindingIdentifier Initializeropt
  1. bindingIdBindingIdentifierStringValue로 둔다.
  2. lhs를 ? ResolveBinding(bindingId, envRecord)로 둔다.
  3. vundefined로 둔다.
  4. iteratorRecord.[[Done]]false이면, 다음을 수행한다.
    1. next를 ? IteratorStepValue(iteratorRecord)로 둔다.
    2. nextdone이 아니면, 다음을 수행한다.
      1. vnext로 설정한다.
  5. Initializer가 present하고 vundefined이면, 다음을 수행한다.
    1. IsAnonymousFunctionDefinition(Initializer)이 true이면, 다음을 수행한다.
      1. v를 argument bindingId를 가진 InitializerNamedEvaluation으로 ? 설정한다.
    2. 그렇지 않으면,
      1. defaultValueInitializerEvaluation으로 ? 둔다.
      2. v를 ? GetValue(defaultValue)로 설정한다.
  6. envRecordundefined이면, PutValue(lhs, v)를 ? 반환한다.
  7. InitializeReferencedBinding(lhs, v)를 ? 반환한다.
BindingElement : BindingPattern Initializeropt
  1. vundefined로 둔다.
  2. iteratorRecord.[[Done]]false이면, 다음을 수행한다.
    1. next를 ? IteratorStepValue(iteratorRecord)로 둔다.
    2. nextdone이 아니면, 다음을 수행한다.
      1. vnext로 설정한다.
  3. Initializer가 present하고 vundefined이면, 다음을 수행한다.
    1. defaultValueInitializerEvaluation으로 ? 둔다.
    2. v를 ? GetValue(defaultValue)로 설정한다.
  4. arguments venvRecord를 가진 BindingPatternBindingInitialization을 ? 반환한다.
BindingRestElement : ... BindingIdentifier
  1. lhs를 ? ResolveBinding(BindingIdentifierStringValue, envRecord)로 둔다.
  2. array를 ! ArrayCreate(0)으로 둔다.
  3. n을 0으로 둔다.
  4. Repeat,
    1. nextdone으로 둔다.
    2. iteratorRecord.[[Done]]false이면, 다음을 수행한다.
      1. next를 ? IteratorStepValue(iteratorRecord)로 설정한다.
    3. nextdone이면, 다음을 수행한다.
      1. envRecordundefined이면, PutValue(lhs, array)를 ? 반환한다.
      2. InitializeReferencedBinding(lhs, array)를 ? 반환한다.
    4. CreateDataPropertyOrThrow(array, ! ToString(𝔽(n)), next)를 수행한다.
    5. nn + 1로 설정한다.
BindingRestElement : ... BindingPattern
  1. array를 ! ArrayCreate(0)으로 둔다.
  2. n을 0으로 둔다.
  3. Repeat,
    1. nextdone으로 둔다.
    2. iteratorRecord.[[Done]]false이면, 다음을 수행한다.
      1. next를 ? IteratorStepValue(iteratorRecord)로 설정한다.
    3. nextdone이면, 다음을 수행한다.
      1. arguments arrayenvRecord를 가진 BindingPatternBindingInitialization을 ? 반환한다.
    4. CreateDataPropertyOrThrow(array, ! ToString(𝔽(n)), next)를 수행한다.
    5. nn + 1로 설정한다.
FormalParameters : [empty]
  1. unused를 반환한다.
FormalParameters : FormalParameterList , FunctionRestParameter
  1. arguments iteratorRecordenvRecord를 가진 FormalParameterListIteratorBindingInitialization을 ? 수행한다.
  2. arguments iteratorRecordenvRecord를 가진 FunctionRestParameterIteratorBindingInitialization을 ? 반환한다.
FormalParameterList : FormalParameterList , FormalParameter
  1. arguments iteratorRecordenvRecord를 가진 FormalParameterListIteratorBindingInitialization을 ? 수행한다.
  2. arguments iteratorRecordenvRecord를 가진 FormalParameterIteratorBindingInitialization을 ? 반환한다.
ArrowParameters : BindingIdentifier
  1. vundefined로 둔다.
  2. Assert: iteratorRecord.[[Done]]false이다.
  3. next를 ? IteratorStepValue(iteratorRecord)로 둔다.
  4. nextdone이 아니면, 다음을 수행한다.
    1. vnext로 설정한다.
  5. arguments venvRecord를 가진 BindingIdentifierBindingInitialization을 ? 반환한다.
ArrowParameters : CoverParenthesizedExpressionAndArrowParameterList
  1. formalsCoverParenthesizedExpressionAndArrowParameterList가 cover하는 ArrowFormalParameters로 둔다.
  2. arguments iteratorRecordenvRecord를 가진 formalsIteratorBindingInitialization을 ? 반환한다.
AsyncArrowBindingIdentifier : BindingIdentifier
  1. vundefined로 둔다.
  2. Assert: iteratorRecord.[[Done]]false이다.
  3. next를 ? IteratorStepValue(iteratorRecord)로 둔다.
  4. nextdone이 아니면, 다음을 수행한다.
    1. vnext로 설정한다.
  5. arguments venvRecord를 가진 BindingIdentifierBindingInitialization을 ? 반환한다.

8.6.4 Static Semantics: AssignmentTargetType

The syntax-directed operation AssignmentTargetType takes no arguments and returns simple, web-compat, or invalid. It is defined piecewise over the following productions:

IdentifierReference : Identifier
  1. IsStrict(this IdentifierReference)이 true이고 IdentifierStringValue"eval" 또는 "arguments" 중 하나이면, invalid를 반환한다.
  2. simple을 반환한다.
IdentifierReference : yield await CallExpression : CallExpression [ Expression ] CallExpression . IdentifierName CallExpression . PrivateIdentifier MemberExpression : MemberExpression [ Expression ] MemberExpression . IdentifierName SuperProperty MemberExpression . PrivateIdentifier
  1. simple을 반환한다.
PrimaryExpression : CoverParenthesizedExpressionAndArrowParameterList
  1. exprCoverParenthesizedExpressionAndArrowParameterList가 cover하는 ParenthesizedExpression으로 둔다.
  2. exprAssignmentTargetType을 반환한다.
CallExpression : CoverCallExpressionAndAsyncArrowHead CallExpression Arguments
  1. host가 web browser이거나 그 밖에 Function Call Assignment Targets에 대한 Runtime Errors를 support하고 IsStrict(this CallExpression)이 false이면, 다음을 수행한다.
    1. web-compat를 반환한다.
  2. invalid를 반환한다.
PrimaryExpression : this Literal ArrayLiteral ObjectLiteral FunctionExpression ClassExpression GeneratorExpression AsyncFunctionExpression AsyncGeneratorExpression RegularExpressionLiteral TemplateLiteral CallExpression : SuperCall ImportCall CallExpression TemplateLiteral NewExpression : new NewExpression MemberExpression : MemberExpression TemplateLiteral new MemberExpression Arguments NewTarget : new . target ImportMeta : import . meta LeftHandSideExpression : OptionalExpression UpdateExpression : LeftHandSideExpression ++ LeftHandSideExpression -- ++ UnaryExpression -- UnaryExpression UnaryExpression : delete UnaryExpression void UnaryExpression typeof UnaryExpression + UnaryExpression - UnaryExpression ~ UnaryExpression ! UnaryExpression CoverAwaitExpressionAndAwaitUsingDeclarationHead ExponentiationExpression : UpdateExpression ** ExponentiationExpression MultiplicativeExpression : MultiplicativeExpression MultiplicativeOperator ExponentiationExpression AdditiveExpression : AdditiveExpression + MultiplicativeExpression AdditiveExpression - MultiplicativeExpression ShiftExpression : ShiftExpression << AdditiveExpression ShiftExpression >> AdditiveExpression ShiftExpression >>> AdditiveExpression RelationalExpression : RelationalExpression < ShiftExpression RelationalExpression > ShiftExpression RelationalExpression <= ShiftExpression RelationalExpression >= ShiftExpression RelationalExpression instanceof ShiftExpression RelationalExpression in ShiftExpression PrivateIdentifier in ShiftExpression EqualityExpression : EqualityExpression == RelationalExpression EqualityExpression != RelationalExpression EqualityExpression === RelationalExpression EqualityExpression !== RelationalExpression BitwiseANDExpression : BitwiseANDExpression & EqualityExpression BitwiseXORExpression : BitwiseXORExpression ^ BitwiseANDExpression BitwiseORExpression : BitwiseORExpression | BitwiseXORExpression LogicalANDExpression : LogicalANDExpression && BitwiseORExpression LogicalORExpression : LogicalORExpression || LogicalANDExpression CoalesceExpression : CoalesceExpressionHead ?? BitwiseORExpression ConditionalExpression : ShortCircuitExpression ? AssignmentExpression : AssignmentExpression AssignmentExpression : YieldExpression ArrowFunction AsyncArrowFunction LeftHandSideExpression = AssignmentExpression LeftHandSideExpression AssignmentOperator AssignmentExpression LeftHandSideExpression &&= AssignmentExpression LeftHandSideExpression ||= AssignmentExpression LeftHandSideExpression ??= AssignmentExpression Expression : Expression , AssignmentExpression
  1. invalid를 반환한다.

8.6.5 Static Semantics: PropName

The syntax-directed operation PropName takes no arguments and returns a String or empty. It is defined piecewise over the following productions:

PropertyDefinition : IdentifierReference
  1. IdentifierReferenceStringValue를 반환한다.
PropertyDefinition : ... AssignmentExpression
  1. empty를 반환한다.
PropertyDefinition : PropertyName : AssignmentExpression
  1. PropertyNamePropName을 반환한다.
LiteralPropertyName : IdentifierName AttributeKey : IdentifierName
  1. IdentifierNameStringValue를 반환한다.
LiteralPropertyName : StringLiteral AttributeKey : StringLiteral
  1. StringLiteralSV를 반환한다.
LiteralPropertyName : NumericLiteral
  1. numberNumericLiteralNumericValue로 둔다.
  2. ToString(number)를 반환한다.
ComputedPropertyName : [ AssignmentExpression ]
  1. empty를 반환한다.
MethodDefinition : ClassElementName ( UniqueFormalParameters ) { FunctionBody } get ClassElementName ( ) { FunctionBody } set ClassElementName ( PropertySetParameterList ) { FunctionBody }
  1. ClassElementNamePropName을 반환한다.
GeneratorMethod : * ClassElementName ( UniqueFormalParameters ) { GeneratorBody }
  1. ClassElementNamePropName을 반환한다.
AsyncGeneratorMethod : async * ClassElementName ( UniqueFormalParameters ) { AsyncGeneratorBody }
  1. ClassElementNamePropName을 반환한다.
ClassElement : ClassStaticBlock
  1. empty를 반환한다.
ClassElement : ;
  1. empty를 반환한다.
AsyncMethod : async ClassElementName ( UniqueFormalParameters ) { AsyncFunctionBody }
  1. ClassElementNamePropName을 반환한다.
FieldDefinition : ClassElementName Initializeropt
  1. ClassElementNamePropName을 반환한다.
ClassElementName : PrivateIdentifier
  1. empty를 반환한다.

8.6.6 Static Semantics: ContainsUsing

The syntax-directed operation ContainsUsing takes no arguments and returns Boolean. It is defined piecewise over the following productions:

StatementList : StatementList StatementListItem
  1. 파생된 StatementListContainsUsingtrue이면, true를 반환한다.
  2. StatementListItemContainsUsingtrue이면, true를 반환한다.
  3. false를 반환한다.
StatementListItem : Statement
  1. false를 반환한다.
StatementListItem : Declaration
  1. DeclarationIsUsingDeclarationtrue이면, true를 반환한다.
  2. DeclarationIsAwaitUsingDeclarationtrue이면, true를 반환한다.
  3. false를 반환한다.

9 Executable Code and Execution Contexts

9.1 Environment Records

Environment Record는 ECMAScript code의 lexical nesting structure에 기반하여 Identifier를 특정 variable 및 function과 associate하는 것을 define하는 데 사용되는 specification type입니다. 보통 Environment Record는 FunctionDeclaration, BlockStatement 또는 TryStatementCatch clause 같은 ECMAScript code의 특정 syntactic structure와 associated됩니다. 그러한 code가 evaluate될 때마다, 그 code가 생성하는 identifier binding을 record하기 위해 새 Environment Record가 생성됩니다.

모든 Environment Record는 [[OuterEnv]] field를 가지며, 이는 null이거나 outer Environment Record에 대한 reference입니다. 이는 Environment Record value의 logical nesting을 model하는 데 사용됩니다. (inner) Environment Record의 outer reference는 inner Environment Record를 logically surround하는 Environment Record에 대한 reference입니다. 물론 outer Environment Record는 자체 outer Environment Record를 가질 수 있습니다. 하나의 Environment Record가 여러 inner Environment Record의 outer environment 역할을 할 수 있습니다. 예를 들어, FunctionDeclaration이 두 개의 nested FunctionDeclaration을 포함하면, 각 nested function의 Environment Record는 surrounding function의 current evaluation의 Environment Record를 outer Environment Record로 갖게 됩니다.

Environment Record는 순수하게 specification mechanism이며 ECMAScript implementation의 특정 artefact에 대응할 필요가 없습니다. ECMAScript program이 이러한 value에 직접 access하거나 manipulate하는 것은 불가능합니다.

9.1.1 The Environment Record Type Hierarchy

Environment RecordEnvironment Record가 abstract class이고 Declarative Environment Record, Object Environment Record, Global Environment Record라는 세 concrete subclass를 가진 simple object-oriented hierarchy에 존재하는 것으로 생각할 수 있습니다. Function Environment RecordModule Environment RecordDeclarative Environment Record의 subclass입니다.

Environment Record abstract class는 Table 15에 정의된 abstract specification method를 포함합니다. 이러한 abstract method는 각 concrete subclass에 대해 distinct concrete algorithm을 가집니다.

Table 15: Abstract Methods of Environment Records
Method Purpose Definitions
HasBinding ( name )

The abstract method HasBinding takes argument name (a String) and returns either a normal completion containing a Boolean or a throw completion.

Environment Recordname에 대한 binding을 가지는지 determine합니다.
다음 type에 concrete definition이 있습니다:
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 안에 새롭지만 uninitialized인 mutable binding을 생성합니다. name은 bound name의 text입니다. deletabletrue이면 binding은 subsequently deleted될 수 있습니다.
다음 type에 concrete definition이 있습니다:
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 안에 새롭지만 uninitialized인 immutable binding을 생성합니다. name은 bound name의 text입니다. stricttrue이면 initialized된 후 이를 set하려는 attempt는 그 binding을 reference하는 operation의 strict mode setting과 관계없이 항상 exception을 throw합니다.
다음 type에 concrete definition이 있습니다:
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 안에 already existing하지만 uninitialized인 binding의 value를 set합니다. name은 bound name의 text입니다. value는 binding에 대한 value입니다.
다음 type에 concrete definition이 있습니다:
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 안에 already existing인 mutable binding의 value를 set합니다. name은 bound name의 text입니다. value는 binding에 대한 value입니다. stricttrue이고 binding을 set할 수 없으면, 이는 TypeError exception을 throw합니다.
다음 type에 concrete definition이 있습니다:
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에서 already existing인 binding의 value를 반환합니다. name은 bound name의 text입니다. strictstrict mode code에서 originating한 reference 또는 그 밖에 strict mode reference semantics를 require하는 reference를 identify하는 데 사용됩니다. stricttrue이고 binding이 존재하지 않으면, 이는 ReferenceError exception을 throw합니다. binding이 존재하지만 uninitialized이면 strict의 value와 관계없이 ReferenceError가 thrown됩니다.
다음 type에 concrete definition이 있습니다:
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을 delete합니다. name은 bound name의 text입니다. name에 대한 binding이 존재하면, 이는 binding을 remove하고 true를 반환합니다. binding이 존재하지만 remove할 수 없으면, 이는 false를 반환합니다. binding이 존재하지 않으면, 이는 true를 반환합니다.
다음 type에 concrete definition이 있습니다:
HasThisBinding ( )

The abstract method HasThisBinding takes no arguments and returns a Boolean.

Environment Recordthis binding을 establish하는지 determine합니다. establish하면 true를 반환하고 그렇지 않으면 false를 반환합니다.
다음 type에 concrete definition이 있습니다:
GetThisBinding ( )

The abstract method GetThisBinding takes no arguments and returns either a normal completion containing an ECMAScript language value or a throw completion.

Environment Recordthis binding value를 반환합니다. this binding이 initialized되지 않았으면 ReferenceError를 throw합니다.
다음 type에 concrete definition이 있습니다:
HasSuperBinding ( )

The abstract method HasSuperBinding takes no arguments and returns a Boolean.

Environment Recordsuper method binding을 establish하는지 determine합니다. establish하면 true를 반환하고 그렇지 않으면 false를 반환합니다. true를 반환하면 Environment RecordFunction Environment Record임을 imply하지만, reverse implication은 성립하지 않습니다.
다음 type에 concrete definition이 있습니다:
WithBaseObject ( )

The abstract method WithBaseObject takes no arguments and returns an Object or undefined.

Environment Recordwith statement와 associated되면, with object를 반환합니다. 그렇지 않으면 undefined를 반환합니다.
다음 type에 concrete definition이 있습니다:

9.1.1.1 Declarative Environment Records

Declarative Environment Record는 variable, constant, let, class, module, import 및/또는 function declaration을 포함하는 ECMAScript program scope와 associated됩니다. Declarative Environment Record는 그 scope 안에 contained된 declaration이 정의하는 identifier의 set을 bind합니다.

모든 Declarative Environment Record에는 DisposableResource 레코드List를 포함하는 [[DisposableResourceStack]] 필드도 있다. 이 목록의 요소는 Environment Record를 구성한 Evaluation 단계가 완료되었을 때 폐기되어야 하는 using 선언과 await using 선언에 의해 추적된다.

9.1.1.1.1 HasBinding ( name )

The HasBinding concrete method of a Declarative Environment Record envRecord takes argument name (a String) and returns a normal completion containing a Boolean. argument identifier가 record에 의해 bound된 identifier 중 하나인지 determine합니다. It performs the following steps when called:

  1. envRecordname에 대한 binding을 가지면, true를 반환한다.
  2. false를 반환한다.

9.1.1.1.2 CreateMutableBinding ( name, deletable )

The CreateMutableBinding concrete method of a Declarative Environment Record envRecord takes arguments name (a String) and deletable (a Boolean) and returns a normal completion containing unused. uninitialized인 name name에 대한 새 mutable binding을 생성합니다. 이 Environment Record 안에는 name에 대한 binding이 already exist하지 않아야 합니다. deletabletrue이면, 새 binding은 deletion subject로 marked됩니다. It performs the following steps when called:

  1. Assert: envRecordname에 대한 binding을 already have하지 않는다.
  2. envRecord 안에 name에 대한 mutable binding을 생성하고 그것이 uninitialized임을 record한다. deletabletrue이면, newly created binding이 subsequent DeleteBinding call에 의해 deleted될 수 있음을 record한다.
  3. unused를 반환한다.

9.1.1.1.3 CreateImmutableBinding ( name, strict )

The CreateImmutableBinding concrete method of a Declarative Environment Record envRecord takes arguments name (a String) and strict (a Boolean) and returns a normal completion containing unused. uninitialized인 name name에 대한 새 immutable binding을 생성합니다. 이 Environment Record 안에는 name에 대한 binding이 already exist하지 않아야 합니다. stricttrue이면, 새 binding은 strict binding으로 marked됩니다. It performs the following steps when called:

  1. Assert: envRecordname에 대한 binding을 already have하지 않는다.
  2. envRecord 안에 name에 대한 immutable binding을 생성하고 그것이 uninitialized임을 record한다. stricttrue이면, newly created binding이 strict binding임을 record한다.
  3. unused를 반환한다.

9.1.1.1.4 InitializeBinding ( name, value )

The InitializeBinding concrete method of a Declarative Environment Record envRecord takes arguments name (a String) and value (an ECMAScript language value) and returns a normal completion containing unused. name이 name인 identifier의 current binding의 bound value를 value value로 set하는 데 사용됩니다. name에 대한 uninitialized binding이 already exist해야 합니다. It performs the following steps when called:

  1. Assert: envRecordname에 대한 uninitialized binding을 가져야 한다.
  2. envRecord 안의 name에 대한 bound value를 value로 설정한다.
  3. envRecord 안의 name에 대한 binding이 initialized되었음을 Record한다.
  4. unused를 반환한다.

9.1.1.1.5 SetMutableBinding ( name, value, strict )

The SetMutableBinding concrete method of a 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이 name인 identifier의 current binding의 bound value를 value value로 change하려고 attempt합니다. name에 대한 binding은 normally already exist하지만, rare case에는 그렇지 않을 수 있습니다. binding이 immutable binding이면 stricttrue일 때 TypeError가 thrown됩니다. It performs the following steps when called:

  1. envRecordname에 대한 binding을 가지지 않으면, 다음을 수행한다.
    1. stricttrue이면, ReferenceError exception을 throw한다.
    2. envRecord.CreateMutableBinding(name, true)를 수행한다.
    3. envRecord.InitializeBinding(name, value)를 수행한다.
    4. unused를 반환한다.
  2. envRecord 안의 name에 대한 binding이 strict binding이면, stricttrue로 설정한다.
  3. envRecord 안의 name에 대한 binding이 아직 initialized되지 않았으면, 다음을 수행한다.
    1. ReferenceError exception을 throw한다.
  4. 그렇지 않고 envRecord 안의 name에 대한 binding이 mutable binding이면, 다음을 수행한다.
    1. 그 bound value를 value로 change한다.
  5. 그렇지 않으면,
    1. Assert: 이는 immutable binding의 value를 change하려는 attempt이다.
    2. stricttrue이면, TypeError exception을 throw한다.
  6. unused를 반환한다.
Note

step 1에서 missing binding을 result하는 ECMAScript code의 example은 다음과 같습니다:

function f() { eval("var x; x = (delete x, 0);"); }

9.1.1.1.6 GetBindingValue ( name, strict )

The GetBindingValue concrete method of a 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이 name인 bound identifier의 value를 반환합니다. binding이 존재하지만 uninitialized이면 strict의 value와 관계없이 ReferenceError가 thrown됩니다. It performs the following steps when called:

  1. Assert: envRecordname에 대한 binding을 가진다.
  2. envRecord 안의 name에 대한 binding이 uninitialized binding이면, ReferenceError exception을 throw한다.
  3. envRecord 안에서 현재 name에 bound된 value를 반환한다.

9.1.1.1.7 DeleteBinding ( name )

The DeleteBinding concrete method of a Declarative Environment Record envRecord takes argument name (a String) and returns a normal completion containing a Boolean. deletion subject로 명시적으로 designated된 binding만 delete할 수 있습니다. It performs the following steps when called:

  1. Assert: envRecordname에 대한 binding을 가진다.
  2. envRecord 안의 name에 대한 binding을 deleted할 수 없으면, false를 반환한다.
  3. envRecord에서 name에 대한 binding을 remove한다.
  4. true를 반환한다.

9.1.1.1.8 HasThisBinding ( )

The HasThisBinding concrete method of a Declarative Environment Record envRecord takes no arguments and returns false. It performs the following steps when called:

  1. false를 반환한다.
Note

regular Declarative Environment Record(즉, Function Environment RecordModule Environment Record도 아닌 것)는 this binding을 제공하지 않습니다.

9.1.1.1.9 GetThisBinding ( )

Declarative Environment RecordGetThisBinding concrete method는 이 명세 안에서 결코 사용되지 않습니다.

9.1.1.1.10 HasSuperBinding ( )

The HasSuperBinding concrete method of a Declarative Environment Record envRecord takes no arguments and returns false. It performs the following steps when called:

  1. false를 반환한다.
Note

regular Declarative Environment Record(즉, Function Environment RecordModule Environment Record도 아닌 것)는 super binding을 제공하지 않습니다.

9.1.1.1.11 WithBaseObject ( )

The WithBaseObject concrete method of a Declarative Environment Record envRecord takes no arguments and returns undefined. It performs the following steps when called:

  1. undefined를 반환한다.

9.1.1.2 Object Environment Records

Object Environment Record는 그 binding object라고 불리는 object와 associated됩니다. Object Environment Record는 그 binding object의 property name에 직접 corresponding하는 string identifier name의 set을 bind합니다. IdentifierName form의 string이 아닌 property key는 bound identifier의 set에 포함되지 않습니다. own property와 inherited property는 [[Enumerable]] attribute의 setting과 관계없이 set에 포함됩니다. property는 object에서 dynamically added되고 deleted될 수 있으므로, Object Environment Record에 의해 bound된 identifier의 set은 property를 add하거나 delete하는 모든 operation의 side-effect로 potentially change될 수 있습니다. 그러한 side-effect의 결과로 created되는 binding은 corresponding property의 Writable attribute가 false이더라도 mutable binding으로 considered됩니다. Immutable binding은 Object Environment Record에는 존재하지 않습니다.

with statement(14.11)에 대해 created된 Object Environment Record는 function call에서 사용하기 위한 implicit this value로 그 binding object를 제공할 수 있습니다. 이 capability는 Boolean [[IsWithEnvironment]] field에 의해 controlled됩니다.

Object Environment Record는 Table 16에 listed된 additional state field를 가집니다.

Table 16: Additional Fields of Object Environment Records
Field Name Value Meaning
[[BindingObject]] Object Environment Record의 binding object입니다.
[[IsWithEnvironment]] Boolean Environment Recordwith statement에 대해 created되었는지 여부를 나타냅니다.

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. associated binding object가 name이라는 name의 property를 가지는지 determine합니다. It performs the following steps when called:

  1. bindingObjenvRecord.[[BindingObject]]로 둔다.
  2. foundBinding을 ? HasProperty(bindingObj, name)으로 둔다.
  3. foundBindingfalse이면, false를 반환한다.
  4. envRecord.[[IsWithEnvironment]]false이면, true를 반환한다.
  5. unscopables를 ? Get(bindingObj, %Symbol.unscopables%)로 둔다.
  6. unscopables가 Object이면, 다음을 수행한다.
    1. blockedToBoolean(? Get(unscopables, name))으로 둔다.
    2. blockedtrue이면, false를 반환한다.
  7. true를 반환한다.

9.1.1.2.2 CreateMutableBinding ( name, deletable )

The CreateMutableBinding concrete method of an Object Environment Record envRecord takes arguments name (a String) and deletable (a Boolean) and returns either a normal completion containing unused or a throw completion. Environment Record의 associated binding object 안에 name이라는 name의 property를 생성하고 이를 value undefined로 initialize합니다. deletabletrue이면, 새 property의 [[Configurable]] attribute는 true로 set됩니다. 그렇지 않으면 false로 set됩니다. It performs the following steps when called:

  1. bindingObjenvRecord.[[BindingObject]]로 둔다.
  2. DefinePropertyOrThrow(bindingObj, name, PropertyDescriptor { [[Value]]: undefined, [[Writable]]: true, [[Enumerable]]: true, [[Configurable]]: deletable })를 수행한다.
  3. unused를 반환한다.
Note

Normally envRecordname에 대한 binding을 가지지 않지만, 만약 가진다면 DefinePropertyOrThrow의 semantics는 existing binding이 replaced되거나 shadowed되게 하거나 abrupt completion을 returned하게 할 수 있습니다.

9.1.1.2.3 CreateImmutableBinding ( name, strict )

Object Environment RecordCreateImmutableBinding concrete method는 이 명세 안에서 결코 사용되지 않습니다.

9.1.1.2.4 InitializeBinding ( name, value )

The InitializeBinding concrete method of an Object Environment Record envRecord takes arguments name (a String) and value (an ECMAScript language value) and returns either a normal completion containing unused or a throw completion. name이 name인 identifier의 current binding의 bound value를 value value로 set하는 데 사용됩니다. It performs the following steps when called:

  1. envRecord.SetMutableBinding(name, value, false)를 수행한다.
  2. unused를 반환한다.
Note

이 명세에서 Object Environment Record에 대한 CreateMutableBinding의 모든 use는 즉시 같은 name에 대한 InitializeBinding call을 뒤따릅니다. 따라서 이 명세는 Object Environment Record 안의 binding의 initialization state를 명시적으로 track하지 않습니다.

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의 associated binding object's property 중 name이 name인 것의 value를 value value로 set하려고 attempt합니다. name이라는 name의 property는 normally already exist하지만, 존재하지 않거나 현재 writable하지 않으면 error handling은 strict에 의해 determined됩니다. It performs the following steps when called:

  1. bindingObjenvRecord.[[BindingObject]]로 둔다.
  2. stillExists를 ? HasProperty(bindingObj, name)으로 둔다.
  3. stillExistsfalse이고 stricttrue이면, ReferenceError exception을 throw한다.
  4. Set(bindingObj, name, value, strict)를 수행한다.
  5. unused를 반환한다.

9.1.1.2.6 GetBindingValue ( name, strict )

The GetBindingValue concrete method of an Object Environment Record envRecord takes arguments name (a String) and strict (a Boolean) and returns either a normal completion containing an ECMAScript language value or a throw completion. associated binding object's property 중 name이 name인 것의 value를 반환합니다. property는 already exist해야 하지만, 존재하지 않으면 result는 strict에 depend합니다. It performs the following steps when called:

  1. bindingObjenvRecord.[[BindingObject]]로 둔다.
  2. value를 ? HasProperty(bindingObj, name)으로 둔다.
  3. valuefalse이면, 다음을 수행한다.
    1. strictfalse이면, undefined를 반환한다.
    2. ReferenceError exception을 throw한다.
  4. Get(bindingObj, name)을 반환한다.

9.1.1.2.7 DeleteBinding ( name )

The DeleteBinding concrete method of an Object Environment Record envRecord takes argument name (a String) and returns either a normal completion containing a Boolean or a throw completion. environment object의 property에 대응하고 [[Configurable]] attribute의 value가 true인 binding만 delete할 수 있습니다. It performs the following steps when called:

  1. bindingObjenvRecord.[[BindingObject]]로 둔다.
  2. bindingObj.[[Delete]](name)를 반환한다.

9.1.1.2.8 HasThisBinding ( )

The HasThisBinding concrete method of an Object Environment Record envRecord takes no arguments and returns false. It performs the following steps when called:

  1. false를 반환한다.
Note

Object Environment Recordthis binding을 제공하지 않습니다.

9.1.1.2.9 GetThisBinding ( )

Object Environment RecordGetThisBinding concrete method는 이 명세 안에서 결코 사용되지 않습니다.

9.1.1.2.10 HasSuperBinding ( )

The HasSuperBinding concrete method of an Object Environment Record envRecord takes no arguments and returns false. It performs the following steps when called:

  1. false를 반환한다.
Note

Object Environment Recordsuper binding을 제공하지 않습니다.

9.1.1.2.11 WithBaseObject ( )

The WithBaseObject concrete method of an Object Environment Record envRecord takes no arguments and returns an Object or undefined. It performs the following steps when called:

  1. envRecord.[[IsWithEnvironment]]true이면, envRecord.[[BindingObject]]를 반환한다.
  2. undefined를 반환한다.

9.1.1.3 Function Environment Records

Function Environment Record는 function의 top-level scope를 represent하는 데 사용되는 Declarative Environment Record이며, function이 ArrowFunction function이나 AsyncArrowFunction function이 아니면 this binding을 제공합니다. function이 ArrowFunction function이나 AsyncArrowFunction function이 아니고 super를 reference하면, 그 Function Environment Record는 function 내부에서 super method invocation을 수행하는 데 사용되는 state도 포함합니다.

Function Environment Record는 Table 17에 listed된 additional state field를 가집니다.

Table 17: Additional Fields of Function Environment Records
Field Name Value Meaning
[[ThisValue]] ECMAScript language value 이는 function의 이 invocation에 사용되는 this value입니다.
[[ThisBindingStatus]] lexical, initialized, or uninitialized value가 lexical이면, 이는 ArrowFunction 또는 AsyncArrowFunction이며 local this value를 가지지 않습니다.
[[FunctionObject]] ECMAScript function object 그 invocation으로 인해 이 Environment Record가 created된 function object입니다.
[[NewTarget]] a constructor or undefined Environment Record[[Construct]] internal method에 의해 created되었다면, [[NewTarget]][[Construct]] newTarget parameter의 value입니다. 그렇지 않으면 그 value는 undefined입니다.

Function Environment Record는 Table 15에 listed된 모든 Declarative Environment Record method를 support하며, HasThisBinding, GetThisBinding, HasSuperBinding을 제외한 모든 method에 대해 같은 specification을 share합니다.

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]]를 set하고 그것이 initialized되었음을 record합니다. It performs the following steps when called:

  1. Assert: envRecord.[[ThisBindingStatus]]lexical이 아니다.
  2. envRecord.[[ThisBindingStatus]]initialized이면, ReferenceError exception을 throw한다.
  3. envRecord.[[ThisValue]]value로 설정한다.
  4. envRecord.[[ThisBindingStatus]]initialized로 설정한다.
  5. unused를 반환한다.

9.1.1.3.2 HasThisBinding ( )

The HasThisBinding concrete method of a Function Environment Record envRecord takes no arguments and returns a Boolean. It performs the following steps when called:

  1. envRecord.[[ThisBindingStatus]]lexical이면, false를 반환한다.
  2. true를 반환한다.

9.1.1.3.3 GetThisBinding ( )

The GetThisBinding concrete method of a Function Environment Record envRecord takes no arguments and returns either a normal completion containing an ECMAScript language value or a throw completion. It performs the following steps when called:

  1. Assert: envRecord.[[ThisBindingStatus]]lexical이 아니다.
  2. envRecord.[[ThisBindingStatus]]uninitialized이면, ReferenceError exception을 throw한다.
  3. envRecord.[[ThisValue]]를 반환한다.

9.1.1.3.4 HasSuperBinding ( )

The HasSuperBinding concrete method of a Function Environment Record envRecord takes no arguments and returns a Boolean. It performs the following steps when called:

  1. envRecord.[[ThisBindingStatus]]lexical이면, false를 반환한다.
  2. envRecord.[[FunctionObject]].[[HomeObject]]undefined이면, false를 반환한다.
  3. true를 반환한다.

9.1.1.3.5 GetSuperBase ( envRecord )

The abstract operation GetSuperBase takes argument envRecord (a Function Environment Record) and returns an Object, null, or undefined. envRecord에 bound된 super property access의 base인 object를 반환합니다. value undefined는 그러한 access가 runtime error를 produce함을 나타냅니다. It performs the following steps when called:

  1. homeenvRecord.[[FunctionObject]].[[HomeObject]]로 둔다.
  2. homeundefined이면, undefined를 반환한다.
  3. Assert: homeordinary object이다.
  4. home.[[GetPrototypeOf]]()를 반환한다.

9.1.1.4 Global Environment Records

Global Environment Record는 common realm에서 processed되는 모든 ECMAScript Script element가 shared하는 outer most scope를 represent하는 데 사용됩니다. Global Environment Record는 built-in global(clause 19), global object의 property, 그리고 Script 안에서 occur하는 모든 top-level declaration(8.2.11, 8.2.13)에 대한 binding을 제공합니다.

Global Environment Record는 logically single record이지만, Object Environment RecordDeclarative Environment Record를 encapsulate하는 composite로 specified됩니다. Object Environment Record는 associated Realm Recordglobal object를 base object로 가집니다. 이 global object는 Global Environment Record의 GetThisBinding concrete method가 반환하는 value입니다. Global Environment Record의 Object Environment Record component는 모든 built-in global(clause 19) 및 global code 안에 contained된 FunctionDeclaration, GeneratorDeclaration, AsyncFunctionDeclaration, AsyncGeneratorDeclaration 또는 VariableStatement에 의해 introduced된 모든 binding을 포함합니다. global code 안의 다른 모든 ECMAScript declaration에 대한 binding은 Global Environment Record의 Declarative Environment Record component에 포함됩니다.

Property는 global object 위에 직접 created될 수 있습니다. 따라서 Global Environment Record의 Object Environment Record component는 FunctionDeclaration, GeneratorDeclaration, AsyncFunctionDeclaration, AsyncGeneratorDeclaration 또는 VariableDeclaration declaration에 의해 explicitly created된 binding과 global object의 property로 implicitly created된 binding을 모두 포함할 수 있습니다.

Global Environment Record는 Table 18에 listed된 additional field를 가집니다.

Table 18: Additional Fields of Global Environment Records
Field Name Value Meaning
[[ObjectRecord]] Object Environment Record Binding object는 global object입니다. 이는 associated realm에 대한 global code 안의 FunctionDeclaration, GeneratorDeclaration, AsyncFunctionDeclaration, AsyncGeneratorDeclaration, VariableDeclaration binding뿐 아니라 global built-in binding도 포함합니다.
[[GlobalThisValue]] Object global scope에서 this에 의해 returned되는 value입니다. Host는 어떤 ECMAScript Object value든 provide할 수 있습니다.
[[DeclarativeRecord]] Declarative Environment Record associated realm code에 대한 global code 안의 모든 declaration에 대한 binding을 Contains하지만, FunctionDeclaration, GeneratorDeclaration, AsyncFunctionDeclaration, AsyncGeneratorDeclaration, VariableDeclaration binding은 제외합니다.

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에 의해 bound된 identifier 중 하나인지 determine합니다. It performs the following steps when called:

  1. declRecordenvRecord.[[DeclarativeRecord]]로 둔다.
  2. declRecord.HasBinding(name)이 true이면, true를 반환한다.
  3. objRecordenvRecord.[[ObjectRecord]]로 둔다.
  4. objRecord.HasBinding(name)을 반환한다.

9.1.1.4.2 CreateMutableBinding ( name, deletable )

The CreateMutableBinding concrete method of a Global Environment Record envRecord takes arguments name (a String) and deletable (a Boolean) and returns either a normal completion containing unused or a throw completion. uninitialized인 name name에 대한 새 mutable binding을 생성합니다. binding은 associated DeclarativeRecord 안에 created됩니다. name에 대한 binding은 DeclarativeRecord 안에 already exist하지 않아야 합니다. deletabletrue이면, 새 binding은 deletion subject로 marked됩니다. It performs the following steps when called:

  1. declRecordenvRecord.[[DeclarativeRecord]]로 둔다.
  2. declRecord.HasBinding(name)이 true이면, TypeError exception을 throw한다.
  3. declRecord.CreateMutableBinding(name, deletable)를 반환한다.

9.1.1.4.3 CreateImmutableBinding ( name, strict )

The CreateImmutableBinding concrete method of a Global Environment Record envRecord takes arguments name (a String) and strict (a Boolean) and returns either a normal completion containing unused or a throw completion. uninitialized인 name name에 대한 새 immutable binding을 생성합니다. 이 Environment Record 안에는 name에 대한 binding이 already exist하지 않아야 합니다. stricttrue이면, 새 binding은 strict binding으로 marked됩니다. It performs the following steps when called:

  1. declRecordenvRecord.[[DeclarativeRecord]]로 둔다.
  2. declRecord.HasBinding(name)이 true이면, TypeError exception을 throw한다.
  3. declRecord.CreateImmutableBinding(name, strict)를 반환한다.

9.1.1.4.4 InitializeBinding ( name, value )

The InitializeBinding concrete method of a Global Environment Record envRecord takes arguments name (a String) and value (an ECMAScript language value) and returns either a normal completion containing unused or a throw completion. name이 name인 identifier의 current binding의 bound value를 value value로 set하는 데 사용됩니다. name에 대한 uninitialized binding이 already exist해야 합니다. It performs the following steps when called:

  1. declRecordenvRecord.[[DeclarativeRecord]]로 둔다.
  2. declRecord.HasBinding(name)이 true이면, 다음을 수행한다.
    1. declRecord.InitializeBinding(name, value)를 반환한다.
  3. Assert: binding이 존재한다면, 그것은 Object Environment Record 안에 있어야 한다.
  4. objRecordenvRecord.[[ObjectRecord]]로 둔다.
  5. objRecord.InitializeBinding(name, value)를 반환한다.

9.1.1.4.5 SetMutableBinding ( name, value, strict )

The SetMutableBinding concrete method of a Global Environment Record envRecord takes arguments name (a String), value (an ECMAScript language value), and strict (a Boolean) and returns either a normal completion containing unused or a throw completion. name이 name인 identifier의 current binding의 bound value를 value value로 change하려고 attempt합니다. binding이 immutable binding이고 stricttrue이면, TypeError가 thrown됩니다. name이라는 binding은 normally already exist하지만, 존재하지 않거나 currently writable하지 않으면 error handling은 strict에 의해 determined됩니다. It performs the following steps when called:

  1. declRecordenvRecord.[[DeclarativeRecord]]로 둔다.
  2. declRecord.HasBinding(name)이 true이면, 다음을 수행한다.
    1. declRecord.SetMutableBinding(name, value, strict)를 반환한다.
  3. objRecordenvRecord.[[ObjectRecord]]로 둔다.
  4. objRecord.SetMutableBinding(name, value, strict)를 반환한다.

9.1.1.4.6 GetBindingValue ( name, strict )

The GetBindingValue concrete method of a Global Environment Record envRecord takes arguments name (a String) and strict (a Boolean) and returns either a normal completion containing an ECMAScript language value or a throw completion. name이 name인 bound identifier의 value를 반환합니다. binding이 uninitialized binding이면, ReferenceError exception을 throw합니다. name이라는 binding은 normally already exist하지만, 존재하지 않거나 currently writable하지 않으면 error handling은 strict에 의해 determined됩니다. It performs the following steps when called:

  1. declRecordenvRecord.[[DeclarativeRecord]]로 둔다.
  2. declRecord.HasBinding(name)이 true이면, 다음을 수행한다.
    1. declRecord.GetBindingValue(name, strict)를 반환한다.
  3. objRecordenvRecord.[[ObjectRecord]]로 둔다.
  4. objRecord.GetBindingValue(name, strict)를 반환한다.

9.1.1.4.7 DeleteBinding ( name )

The DeleteBinding concrete method of a Global Environment Record envRecord takes argument name (a String) and returns either a normal completion containing a Boolean or a throw completion. deletion subject로 명시적으로 designated된 binding만 delete할 수 있습니다. It performs the following steps when called:

  1. declRecordenvRecord.[[DeclarativeRecord]]로 둔다.
  2. declRecord.HasBinding(name)이 true이면, 다음을 수행한다.
    1. declRecord.DeleteBinding(name)를 반환한다.
  3. objRecordenvRecord.[[ObjectRecord]]로 둔다.
  4. globalObjobjRecord.[[BindingObject]]로 둔다.
  5. existingProperty를 ? HasOwnProperty(globalObj, name)로 둔다.
  6. existingPropertytrue이면, 다음을 수행한다.
    1. objRecord.DeleteBinding(name)를 반환한다.
  7. true를 반환한다.

9.1.1.4.8 HasThisBinding ( )

The HasThisBinding concrete method of a Global Environment Record envRecord takes no arguments and returns true. It performs the following steps when called:

  1. true를 반환한다.
Note

Global Environment Record는 항상 this binding을 제공합니다.

9.1.1.4.9 GetThisBinding ( )

The GetThisBinding concrete method of a Global Environment Record envRecord takes no arguments and returns a normal completion containing an Object. It performs the following steps when called:

  1. envRecord.[[GlobalThisValue]]를 반환한다.

9.1.1.4.10 HasSuperBinding ( )

The HasSuperBinding concrete method of a Global Environment Record envRecord takes no arguments and returns false. It performs the following steps when called:

  1. false를 반환한다.
Note

Global Environment Recordsuper binding을 제공하지 않습니다.

9.1.1.4.11 WithBaseObject ( )

The WithBaseObject concrete method of a Global Environment Record envRecord takes no arguments and returns undefined. It performs the following steps when called:

  1. undefined를 반환한다.

9.1.1.4.12 HasLexicalDeclaration ( envRecord, name )

The abstract operation HasLexicalDeclaration takes arguments envRecord (a Global Environment Record) and name (a String) and returns a Boolean. argument identifier가 LexicalDeclaration 또는 ClassDeclaration 같은 lexical declaration을 사용하여 created된 envRecord 안의 binding을 가지는지 determine합니다. It performs the following steps when called:

  1. declRecordenvRecord.[[DeclarativeRecord]]로 둔다.
  2. declRecord.HasBinding(name)를 반환한다.

9.1.1.4.13 HasRestrictedGlobalProperty ( envRecord, name )

The abstract operation HasRestrictedGlobalProperty takes arguments envRecord (a Global Environment Record) and name (a String) and returns either a normal completion containing a Boolean or a throw completion. argument identifier가 global lexical binding에 의해 shadowed되어서는 안 되는 global objectproperty name인지 determine합니다. It performs the following steps when called:

  1. objRecordenvRecord.[[ObjectRecord]]로 둔다.
  2. globalObjobjRecord.[[BindingObject]]로 둔다.
  3. existingProperty를 ? globalObj.[[GetOwnProperty]](name)로 둔다.
  4. existingPropertyundefined이면, false를 반환한다.
  5. existingProperty.[[Configurable]]true이면, false를 반환한다.
  6. true를 반환한다.
Note

var 또는 function declaration을 사용하여 declared된 것이 아니라 directly created된 property가 global object 위에 존재할 수 있습니다. global lexical binding은 global object의 non-configurable property와 같은 name으로 created될 수 없습니다. global property "undefined"는 그러한 property의 example입니다.

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. same argument name에 대해 corresponding CreateGlobalVarBinding call이 called된다면 succeed할지 determine합니다. Redundant var declaration과 pre-existing global object property에 대한 var declaration은 allowed됩니다. It performs the following steps when called:

  1. objRecordenvRecord.[[ObjectRecord]]로 둔다.
  2. globalObjobjRecord.[[BindingObject]]로 둔다.
  3. hasProperty를 ? HasOwnProperty(globalObj, name)로 둔다.
  4. hasPropertytrue이면, true를 반환한다.
  5. IsExtensible(globalObj)를 반환한다.

9.1.1.4.15 CanDeclareGlobalFunction ( envRecord, name )

The abstract operation CanDeclareGlobalFunction takes arguments envRecord (a Global Environment Record) and name (a String) and returns either a normal completion containing a Boolean or a throw completion. same argument name에 대해 corresponding CreateGlobalFunctionBinding call이 called된다면 succeed할지 determine합니다. It performs the following steps when called:

  1. objRecordenvRecord.[[ObjectRecord]]로 둔다.
  2. globalObjobjRecord.[[BindingObject]]로 둔다.
  3. existingProperty를 ? globalObj.[[GetOwnProperty]](name)로 둔다.
  4. existingPropertyundefined이면, ? IsExtensible(globalObj)를 반환한다.
  5. existingProperty.[[Configurable]]true이면, true를 반환한다.
  6. IsDataDescriptor(existingProperty)가 true이고 existingProperty가 attribute values { [[Writable]]: true, [[Enumerable]]: true }를 가지면, true를 반환한다.
  7. false를 반환한다.

9.1.1.4.16 CreateGlobalVarBinding ( envRecord, name, deletable )

The abstract operation CreateGlobalVarBinding takes arguments envRecord (a Global Environment Record), name (a String), and deletable (a Boolean) and returns either a normal completion containing unused or a throw completion. associated Object Environment Record 안에 mutable binding을 create하고 initialize합니다. binding이 already exist하면, 재사용되며 initialized된 것으로 assumed됩니다. It performs the following steps when called:

  1. objRecordenvRecord.[[ObjectRecord]]로 둔다.
  2. globalObjobjRecord.[[BindingObject]]로 둔다.
  3. hasProperty를 ? HasOwnProperty(globalObj, name)로 둔다.
  4. extensible을 ? IsExtensible(globalObj)로 둔다.
  5. hasPropertyfalse이고 extensibletrue이면, 다음을 수행한다.
    1. objRecord.CreateMutableBinding(name, deletable)를 수행한다.
    2. objRecord.InitializeBinding(name, undefined)를 수행한다.
  6. unused를 반환한다.

9.1.1.4.17 CreateGlobalFunctionBinding ( envRecord, name, value, deletable )

The abstract operation CreateGlobalFunctionBinding takes arguments envRecord (a Global Environment Record), name (a String), value (an ECMAScript function object), and deletable (a Boolean) and returns either a normal completion containing unused or a throw completion. associated Object Environment Record 안에 mutable binding을 create하고 initialize합니다. binding이 already exist하면, replaced됩니다. It performs the following steps when called:

  1. objRecordenvRecord.[[ObjectRecord]]로 둔다.
  2. globalObjobjRecord.[[BindingObject]]로 둔다.
  3. existingProperty를 ? globalObj.[[GetOwnProperty]](name)로 둔다.
  4. existingPropertyundefined이거나 existingProperty.[[Configurable]]true이면, 다음을 수행한다.
    1. propertyDesc를 PropertyDescriptor { [[Value]]: value, [[Writable]]: true, [[Enumerable]]: true, [[Configurable]]: deletable }로 둔다.
  5. 그렇지 않으면,
    1. propertyDesc를 PropertyDescriptor { [[Value]]: value }로 둔다.
  6. DefinePropertyOrThrow(globalObj, name, propertyDesc)를 수행한다.
  7. Set(globalObj, name, value, false)를 수행한다.
  8. unused를 반환한다.
Note

Global function declaration은 항상 global object의 own property로 represented됩니다. 가능하면, existing own property는 standard set of attribute values를 가지도록 reconfigured됩니다. Step 7InitializeBinding concrete method를 calling하는 것이 수행할 것과 equivalent하며 globalObj가 Proxy이면 같은 sequence의 Proxy trap call을 produce합니다.

9.1.1.5 Module Environment Records

Module Environment Record는 ECMAScript Module의 outer scope를 represent하는 데 사용되는 Declarative Environment Record입니다. normal mutable 및 immutable binding에 더해, Module Environment Record는 다른 Environment Record에 존재하는 target binding에 대한 indirect access를 제공하는 binding인 immutable import binding도 제공합니다.

Module Environment Record는 Table 15에 listed된 모든 Declarative Environment Record method를 support하며, GetBindingValue, DeleteBinding, HasThisBinding, GetThisBinding을 제외한 모든 method에 대해 같은 specification을 share합니다.

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이 name인 bound identifier의 value를 반환합니다. 그러나 binding이 indirect binding이면 target binding의 value가 returned됩니다. binding이 존재하지만 uninitialized이면 ReferenceError가 thrown됩니다. It performs the following steps when called:

  1. Assert: stricttrue이다.
  2. Assert: envRecordname에 대한 binding을 가진다.
  3. name에 대한 binding이 indirect binding이면, 다음을 수행한다.
    1. moduletargetNamename에 대한 이 binding이 created될 때 provided된 indirection value로 둔다.
    2. targetEnvmodule.[[Environment]]로 둔다.
    3. targetEnvempty이면, ReferenceError exception을 throw한다.
    4. targetEnv.GetBindingValue(targetName, true)를 반환한다.
  4. envRecord 안의 name에 대한 binding이 uninitialized binding이면, ReferenceError exception을 throw한다.
  5. envRecord 안에서 현재 name에 bound된 value를 반환한다.
Note

Module은 항상 strict mode code이므로 strict는 항상 true입니다.

9.1.1.5.2 DeleteBinding ( name )

Module Environment RecordDeleteBinding concrete method는 이 명세 안에서 결코 사용되지 않습니다.

Note

Module Environment Record는 strict code 안에서만 사용되고, early error rule은 strict code에서 delete operator가 Module Environment Record binding으로 resolve될 Reference Record에 applied되는 것을 prevent합니다. 13.5.1.1를 참조하십시오.

9.1.1.5.3 HasThisBinding ( )

The HasThisBinding concrete method of a Module Environment Record envRecord takes no arguments and returns true. It performs the following steps when called:

  1. true를 반환한다.
Note

Module Environment Record는 항상 this binding을 제공합니다.

9.1.1.5.4 GetThisBinding ( )

The GetThisBinding concrete method of a Module Environment Record envRecord takes no arguments and returns a normal completion containing undefined. It performs the following steps when called:

  1. undefined를 반환한다.

9.1.1.5.5 CreateImportBinding ( envRecord, name, targetModule, targetName )

The abstract operation CreateImportBinding takes arguments envRecord (a Module Environment Record), name (a String), targetModule (a Module Record), and targetName (a String) and returns unused. name name에 대한 새 initialized immutable indirect binding을 생성합니다. envRecord 안에는 name에 대한 binding이 already exist하지 않아야 합니다. targetNametargetModuleModule Environment Record에 존재하는 binding의 name입니다. 새 binding의 value에 대한 access는 target binding의 bound value에 indirectly access합니다. It performs the following steps when called:

  1. Assert: envRecordname에 대한 binding을 already have하지 않는다.
  2. Assert: targetModule.[[Environment]]가 instantiated되면, 이는 targetName에 대한 direct binding을 가질 것이다.
  3. envRecord 안에 targetModuletargetName을 target binding으로 reference하는 name에 대한 immutable indirect binding을 생성하고, 그 binding이 initialized되었음을 record한다.
  4. unused를 반환한다.

9.1.2 Environment Record Operations

다음 abstract operation은 이 명세에서 Environment Record에 대해 operate하는 데 사용됩니다:

9.1.2.1 GetIdentifierReference ( envRecord, name, strict )

The abstract operation GetIdentifierReference takes arguments envRecord (an Environment Record or null), name (a String), and strict (a Boolean) and returns either a normal completion containing a Reference Record or a throw completion. It performs the following steps when called:

  1. envRecordnull이면, 다음을 수행한다.
    1. Reference Record { [[Base]]: unresolvable, [[ReferencedName]]: name, [[Strict]]: strict, [[ThisValue]]: empty }를 반환한다.
  2. exists를 ? envRecord.HasBinding(name)로 둔다.
  3. existstrue이면, 다음을 수행한다.
    1. Reference Record { [[Base]]: envRecord, [[ReferencedName]]: name, [[Strict]]: strict, [[ThisValue]]: empty }를 반환한다.
  4. outerenvRecord.[[OuterEnv]]로 둔다.
  5. GetIdentifierReference(outer, name, strict)를 반환한다.

9.1.2.2 NewDeclarativeEnvironment ( outerEnv )

The abstract operation NewDeclarativeEnvironment takes argument outerEnv (an Environment Record or null) and returns a Declarative Environment Record. It performs the following steps when called:

  1. 바인딩을 포함하지 않는 새 Declarative Environment RecordenvRecord로 둔다.
  2. envRecord.[[OuterEnv]]outerEnv로 설정한다.
  3. envRecord.[[DisposableResourceStack]]을 새 빈 List로 설정한다.
  4. envRecord를 반환한다.

9.1.2.3 NewObjectEnvironment ( obj, isWithEnv, outerEnv )

The abstract operation NewObjectEnvironment takes arguments obj (an Object), isWithEnv (a Boolean), and outerEnv (an Environment Record or null) and returns an Object Environment Record. It performs the following steps when called:

  1. Object Environment Record envRecord를 둔다.
  2. envRecord.[[BindingObject]]obj로 설정한다.
  3. envRecord.[[IsWithEnvironment]]isWithEnv로 설정한다.
  4. envRecord.[[OuterEnv]]outerEnv로 설정한다.
  5. envRecord를 반환한다.

9.1.2.4 NewFunctionEnvironment ( func, newTarget )

The abstract operation NewFunctionEnvironment takes arguments func (an ECMAScript function object) and newTarget (an Object or undefined) and returns a Function Environment Record. It performs the following steps when called:

  1. 바인딩을 포함하지 않는 새 Function Environment RecordenvRecord로 둔다.
  2. envRecord.[[FunctionObject]]func로 설정한다.
  3. func.[[ThisMode]]lexical이면, envRecord.[[ThisBindingStatus]]lexical로 설정한다.
  4. 그렇지 않으면, envRecord.[[ThisBindingStatus]]uninitialized로 설정한다.
  5. envRecord.[[NewTarget]]newTarget으로 설정한다.
  6. envRecord.[[OuterEnv]]func.[[Environment]]로 설정한다.
  7. envRecord.[[DisposableResourceStack]]을 새 빈 List로 설정한다.
  8. envRecord를 반환한다.

9.1.2.5 NewGlobalEnvironment ( obj, thisValue )

The abstract operation NewGlobalEnvironment takes arguments obj (an Object) and thisValue (an Object) and returns a Global Environment Record. It performs the following steps when called:

  1. objRecordNewObjectEnvironment(obj, false, null)로 둔다.
  2. declRecordNewDeclarativeEnvironment(null)로 둔다.
  3. Global Environment Record envRecord를 둔다.
  4. envRecord.[[ObjectRecord]]objRecord로 설정한다.
  5. envRecord.[[GlobalThisValue]]thisValue로 설정한다.
  6. envRecord.[[DeclarativeRecord]]declRecord로 설정한다.
  7. envRecord.[[OuterEnv]]null로 설정한다.
  8. envRecord를 반환한다.

9.1.2.6 NewModuleEnvironment ( outerEnv )

The abstract operation NewModuleEnvironment takes argument outerEnv (a Global Environment Record) and returns a Module Environment Record. It performs the following steps when called:

  1. 바인딩을 포함하지 않는 새 Module Environment RecordenvRecord로 둔다.
  2. envRecord.[[OuterEnv]]outerEnv로 설정한다.
  3. envRecord.[[DisposableResourceStack]]을 새 빈 List로 설정한다.
  4. envRecord를 반환한다.

9.2 PrivateEnvironment Records

PrivateEnvironment Record는 ECMAScript code 안의 ClassDeclarationClassExpression의 lexical nesting structure에 기반하여 Private Name을 track하는 데 사용되는 specification mechanism입니다. 이는 Environment Record와 similar하지만 distinct합니다. 각 PrivateEnvironment RecordClassDeclaration 또는 ClassExpression과 associated됩니다. 그러한 class가 evaluate될 때마다, 그 class가 declared한 Private Name을 record하기 위해 새 PrivateEnvironment Record가 생성됩니다.

PrivateEnvironment RecordTable 19에 정의된 field를 가집니다.

Table 19: PrivateEnvironment Record Fields
Field Name Value Type Meaning
[[OuterPrivateEnvironment]] a PrivateEnvironment Record or null 가장 가까운 containing class의 PrivateEnvironment Record입니다. 이 PrivateEnvironment Record와 associated된 class가 다른 class 안에 contained되어 있지 않으면 null입니다.
[[Names]] a List of Private Names 이 class가 declared한 Private Name입니다.

9.2.1 PrivateEnvironment Record Operations

다음 abstract operation은 이 명세에서 PrivateEnvironment Record에 대해 operate하는 데 사용됩니다:

9.2.1.1 NewPrivateEnvironment ( outerPrivateEnv )

The abstract operation NewPrivateEnvironment takes argument outerPrivateEnv (a PrivateEnvironment Record or null) and returns a PrivateEnvironment Record. It performs the following steps when called:

  1. names를 새 empty List로 둔다.
  2. PrivateEnvironment Record { [[OuterPrivateEnvironment]]: outerPrivateEnv, [[Names]]: names }를 반환한다.

9.2.1.2 ResolvePrivateIdentifier ( privateEnv, identifier )

The abstract operation ResolvePrivateIdentifier takes arguments privateEnv (a PrivateEnvironment Record) and identifier (a String) and returns a Private Name. It performs the following steps when called:

  1. namesprivateEnv.[[Names]]로 둔다.
  2. names의 각 Private Name privateName에 대해, 다음을 수행한다.
    1. privateName.[[Description]]identifier이면, 다음을 수행한다.
      1. privateName을 반환한다.
  3. outerPrivateEnvprivateEnv.[[OuterPrivateEnvironment]]로 둔다.
  4. Assert: outerPrivateEnvnull이 아니다.
  5. ResolvePrivateIdentifier(outerPrivateEnv, identifier)를 반환한다.

9.3 Realms

evaluate되기 전에, 모든 ECMAScript code는 realm과 associated되어야 합니다. Conceptually, realm은 intrinsic object의 set, ECMAScript global environment, 그 global environment의 scope 안에 loaded된 모든 ECMAScript code, 그리고 기타 associated state와 resource로 구성됩니다.

realm은 이 명세에서 Table 20에 specified된 field를 가진 Realm Record로 represented됩니다:

Table 20: Realm Record Fields
Field Name Value Meaning
[[AgentSignifier]] an agent signifier realm을 own하는 agent
[[Intrinsics]] a Record whose field names are intrinsic keys and whose values are objects realm과 associated된 code가 사용하는 intrinsic value
[[GlobalObject]] an Object realmglobal object
[[GlobalEnv]] a Global Environment Record realm의 global environment
[[TemplateMap]] a List of Records with fields [[Site]] (a TemplateLiteral Parse Node) and [[Array]] (an Array)

Template object는 각 realm마다 그 Realm Record[[TemplateMap]]을 사용하여 separately canonicalized됩니다. 각 [[Site]] value는 TemplateLiteralParse Node입니다. associated [[Array]] value는 tag function에 passed되는 corresponding template object입니다.

Note 1
Parse Node가 unreachable이 되면, corresponding [[Array]]도 unreachable이 되며, implementation이 [[TemplateMap]] list에서 그 pair를 removed하더라도 unobservable합니다.
[[LoadedModules]] a List of LoadedModuleRequest Records

realm이 import한 specifier string에서 resolved Module Record로의 map입니다. 이 list는 ModuleRequestsEqual(r1, r2)이 true인 서로 다른 Record r1r2를 contain하지 않습니다.

Note 2
HostLoadImportedModule(16.2.1.10 Note 1)에서 언급한 것처럼, Realm Record 안의 [[LoadedModules]]는 active script나 module이 없는 context에서 import() expression을 running할 때만 사용됩니다.
[[HostDefined]] anything (default value is undefined) Realm Record와 additional information을 associate해야 하는 host가 사용하기 위해 reserved된 field입니다.

9.3.1 InitializeHostDefinedRealm ( )

The abstract operation InitializeHostDefinedRealm takes no arguments and returns either a normal completion containing unused or a throw completion. It performs the following steps when called:

  1. realm을 새 Realm Record로 둔다.
  2. CreateIntrinsics(realm)를 수행한다.
  3. realm.[[AgentSignifier]]AgentSignifier()로 설정한다.
  4. realm.[[TemplateMap]]을 새 empty List로 설정한다.
  5. newContext를 새 execution context로 둔다.
  6. newContext의 Function을 null로 설정한다.
  7. newContextRealmrealm으로 설정한다.
  8. newContext의 ScriptOrModule을 null로 설정한다.
  9. newContextexecution context stack 위로 push한다; newContext는 이제 running execution context이다.
  10. hostrealmglobal object 역할을 할 specific object의 use를 require하면, 다음을 수행한다.
    1. globalhost-defined manner로 created된 그러한 object로 둔다.
  11. 그렇지 않으면,
    1. globalOrdinaryObjectCreate(realm.[[Intrinsics]].[[%Object.prototype%]])로 둔다.
  12. hostrealm의 global scope 안의 this binding이 global object가 아닌 object를 return하도록 require하면, 다음을 수행한다.
    1. thisValuehost-defined manner로 created된 그러한 object로 둔다.
  13. 그렇지 않으면,
    1. thisValueglobal로 둔다.
  14. realm.[[GlobalObject]]global로 설정한다.
  15. realm.[[GlobalEnv]]NewGlobalEnvironment(global, thisValue)로 설정한다.
  16. SetDefaultGlobalBindings(realm)를 수행한다.
  17. host-defined global object property를 global 위에 create한다.
  18. unused를 반환한다.

9.3.2 CreateIntrinsics ( realmRecord )

The abstract operation CreateIntrinsics takes argument realmRecord (a Realm Record) and returns unused. It performs the following steps when called:

  1. realmRecord.[[Intrinsics]]를 새 Record로 설정한다.
  2. realmRecord.[[Intrinsics]]의 field를 Table 6에 listed된 value로 설정한다. field name은 table의 “Intrinsic Name” column에 listed된 name입니다. 각 field의 value는 clause 19부터 28까지의 각 object specification에 의해 정의된 property value로 fully and recursively populated된 새 object value입니다. 모든 object property value는 newly created object value입니다. built-in function object인 모든 value는 CreateBuiltinFunction(steps, length, name, slots, realmRecord, proto, async)를 수행하여 created되며, 여기서 steps는 이 명세가 제공하는 해당 function의 definition, name은 function의 "name" property의 initial value, length는 function의 "length" property의 initial value, slots는 function의 specified internal slot의 name list(있는 경우), proto는 function의 [[Prototype]] internal slot의 specified value, async는 function이 “async”로 described되면 true이고 그렇지 않으면 false입니다. intrinsics와 그 property의 creation은 아직 created되지 않은 object에 대한 dependency를 피하도록 ordered되어야 합니다.
  3. AddRestrictedFunctionProperties(realmRecord.[[Intrinsics]].[[%Function.prototype%]], realmRecord)를 수행한다.
  4. unused를 반환한다.

9.3.3 SetDefaultGlobalBindings ( realmRecord )

The abstract operation SetDefaultGlobalBindings takes argument realmRecord (a Realm Record) and returns either a normal completion containing unused or a throw completion. It performs the following steps when called:

  1. globalrealmRecord.[[GlobalObject]]로 둔다.
  2. clause 19에 specified된 Global Object의 각 property에 대해, 다음을 수행한다.
    1. nameproperty name의 String value로 둔다.
    2. propertyDesc를 property에 대한 specified attribute를 contain하는, property에 대한 fully populated data Property Descriptor로 둔다. 19.2, 19.3 또는 19.4에 listed된 property에 대해서는 [[Value]] attribute의 value가 realmRecord의 corresponding intrinsic object입니다.
    3. DefinePropertyOrThrow(global, name, propertyDesc)를 수행한다.
  3. unused를 반환한다.

9.4 Execution Contexts

execution context는 ECMAScript implementation에 의한 code의 runtime evaluation을 track하는 데 사용되는 specification device입니다. 어느 시점에서든, 실제로 code를 executing하고 있는 execution context는 agent마다 at most one입니다. 이는 agentrunning execution context로 알려져 있습니다. 이 명세에서 running execution context에 대한 모든 reference는 surrounding agentrunning execution context를 denote합니다.

execution context stack은 execution context를 track하는 데 사용됩니다. running execution context는 항상 이 stack의 top element입니다. currently running execution context와 associated된 executable code에서 그 execution context와 associated되지 않은 executable code로 control이 transferred될 때마다 새 execution context가 created됩니다. newly created execution context는 stack 위로 pushed되고 running execution context가 됩니다.

execution context는 associated code의 execution progress를 track하는 데 필요한 implementation specific state를 포함합니다. 각 execution context는 적어도 Table 21에 listed된 state component를 가집니다.

Table 21: State Components for All Execution Contexts
Component Purpose
code evaluation state execution context와 associated된 code의 evaluation을 perform, suspend, resume하는 데 필요한 모든 state입니다.
Function execution contextfunction object의 code를 evaluating하고 있으면, 이 component의 value는 그 function object입니다. context가 Script 또는 Module의 code를 evaluating하고 있으면, value는 null입니다.
Realm associated code가 ECMAScript resource에 access하는 Realm Record입니다.
ScriptOrModule associated code가 originate하는 Module Record 또는 Script Record입니다. InitializeHostDefinedRealm에서 created된 original execution context의 경우처럼 originating script나 module이 없으면, value는 null입니다.

실행 중인 실행 컨텍스트에 의한 코드 평가는 이 명세 안에 정의된 여러 지점에서 중단될 수 있다. 실행 중인 실행 컨텍스트가 일단 중단되면, 다른 실행 컨텍스트가 실행 중인 실행 컨텍스트가 되어 그 코드를 평가하기 시작할 수 있다. 나중의 어느 시점에 중단된 실행 컨텍스트가 다시 실행 중인 실행 컨텍스트가 되어 이전에 중단되었던 지점에서 그 코드 평가를 계속할 수 있다. 실행 컨텍스트들 사이에서 실행 중인 실행 컨텍스트 상태의 전환은 보통 스택과 같은 후입선출 방식으로 일어난다. 그러나 일부 ECMAScript 기능은 실행 중인 실행 컨텍스트의 비-LIFO 전환을 필요로 한다.

실행 중인 실행 컨텍스트의 Realm 구성 요소 값은 현재 Realm Record라고도 한다. 실행 중인 실행 컨텍스트의 Function 구성 요소 값은 활성 함수 객체라고도 한다.

ECMAScript 코드 실행 컨텍스트에는 Table 22에 나열된 추가 상태 구성 요소가 있다.

Table 22: Additional State Components for ECMAScript Code Execution Contexts
Component Purpose
LexicalEnvironment execution context 안의 code가 만든 identifier reference를 resolve하는 데 사용되는 Environment Record를 identify합니다.
VariableEnvironment execution context 안의 VariableStatement에 의해 created된 binding을 hold하는 Environment Record를 identify합니다.
PrivateEnvironment 가장 가까운 containing class 안의 ClassElement에 의해 created된 Private Name을 hold하는 PrivateEnvironment Record를 identify합니다. containing class가 없으면 null입니다.

execution context의 LexicalEnvironment와 VariableEnvironment component는 항상 Environment Record입니다.

Generator의 evaluation을 representing하는 execution context는 Table 23에 listed된 additional state component를 가집니다.

Table 23: Additional State Components for Generator Execution Contexts
Component Purpose
Generator execution context가 evaluating하고 있는 Generator입니다.

대부분의 situation에서는 running execution context(execution context stack의 top)만 이 명세 안의 algorithm에 의해 directly manipulated됩니다. 따라서 “LexicalEnvironment”와 “VariableEnvironment”라는 term이 qualification 없이 사용될 때는 running execution context의 해당 component를 reference합니다.

execution context는 순수하게 specification mechanism이며 ECMAScript implementation의 특정 artefact에 대응할 필요가 없습니다. ECMAScript code가 execution context에 직접 access하거나 observe하는 것은 불가능합니다.

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을 determine하는 데 사용됩니다. It performs the following steps when called:

  1. execution context stack이 empty이면, null을 반환한다.
  2. executionContextexecution context stack 위에서 ScriptOrModule component가 null이 아닌 topmost execution context로 둔다.
  3. 그러한 execution context가 존재하지 않으면, null을 반환한다.
  4. executionContext의 ScriptOrModule을 반환한다.

9.4.2 ResolveBinding ( name [ , envRecord ] )

The abstract operation ResolveBinding takes argument name (a String) and optional argument envRecord (an Environment Record or undefined) and returns either a normal completion containing a Reference Record or a throw completion. name의 binding을 determine하는 데 사용됩니다. envRecord는 binding을 search할 Environment Record를 명시적으로 provide하는 데 사용될 수 있습니다. It performs the following steps when called:

  1. envRecord가 present하지 않거나 envRecordundefined이면, 다음을 수행한다.
    1. envRecordrunning execution context의 LexicalEnvironment로 설정한다.
  2. Assert: envRecordEnvironment Record이다.
  3. strict를 evaluating되고 있는 syntactic production의 IsStrict로 둔다.
  4. GetIdentifierReference(envRecord, name, strict)를 반환한다.
Note

ResolveBinding의 result는 항상 [[ReferencedName]] field가 nameReference Record입니다.

9.4.3 GetThisEnvironment ( )

The abstract operation GetThisEnvironment takes no arguments and returns an Environment Record. keyword this의 binding을 currently supply하는 Environment Record를 찾습니다. It performs the following steps when called:

  1. envRecordrunning execution context의 LexicalEnvironment로 둔다.
  2. Repeat,
    1. existsenvRecord.HasThisBinding()으로 둔다.
    2. existstrue이면, envRecord를 반환한다.
    3. outerenvRecord.[[OuterEnv]]로 둔다.
    4. Assert: outernull이 아니다.
    5. envRecordouter로 설정한다.
Note

step 2의 loop는 environment list가 항상 this binding을 가진 global environment로 끝나기 때문에 항상 terminate합니다.

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을 determine합니다. It performs the following steps when called:

  1. envRecordGetThisEnvironment()로 둔다.
  2. envRecord.GetThisBinding()을 반환한다.

9.4.5 GetNewTarget ( )

The abstract operation GetNewTarget takes no arguments and returns an Object or undefined. running execution context의 LexicalEnvironment를 사용하여 NewTarget value를 determine합니다. It performs the following steps when called:

  1. envRecordGetThisEnvironment()로 둔다.
  2. Assert: envRecord[[NewTarget]] field를 가진다.
  3. envRecord.[[NewTarget]]을 반환한다.

9.4.6 GetGlobalObject ( )

The abstract operation GetGlobalObject takes no arguments and returns an Object. currently running execution context가 사용하는 global object를 반환합니다. It performs the following steps when called:

  1. currentRealm을 current Realm Record로 둔다.
  2. currentRealm.[[GlobalObject]]를 반환한다.

9.4.7 RunSuspendedContext ( context, completionRecord )

The abstract operation RunSuspendedContext takes arguments context (an execution context) and completionRecord (a Completion Record) and returns either a normal completion containing either an ECMAScript language value or unused, or an abrupt completion. context를 resume하고(completionRecord를 resumption value로 sending), result를 기다립니다. It performs the following steps when called:

  1. callerContextrunning execution context로 둔다.
  2. callerContext를 Suspend한다.
  3. contextexecution context stack 위로 push한다; context는 이제 running execution context이다.
  4. suspended시킨 operation의 result로 completionRecord를 사용하여 context의 suspended evaluation을 Resume한다. result를 resumed computation이 반환한 Completion Record로 둔다.
  5. Assert: 이 step에 도달했을 때, context는 이미 execution context stack에서 removed되었고 callerContext가 다시 running execution context이다.
  6. Completion(result)를 반환한다.

9.4.8 RunCallerContext ( value )

The abstract operation RunCallerContext takes argument value (ECMAScript 언어 값 또는 empty) and returns Completion Record. 호출자 컨텍스트를 재개하고(value를 재개 값으로 보냄), 결과가 있으면 그 결과를 기다린다. It performs the following steps when called:

  1. genContext를 실행 중인 실행 컨텍스트라 하자.
  2. 실행 컨텍스트 스택에서 genContext를 제거하고, 실행 컨텍스트 스택의 맨 위에 있는 실행 컨텍스트를 실행 중인 실행 컨텍스트로 복원한다.
  3. callerContext를 실행 중인 실행 컨텍스트라 하자.
  4. callerContext를 재개하며, NormalCompletion(value)를 전달한다.
  5. NOTE: 위 단계는 제어를 callerContext로 이전하고 일시 중지한다. 이것이 일시 중지를 해제하고 이 알고리즘의 이후 단계로 제어가 진행되게 하는 유일한 방법은 genContext가 다시 재개되는 것이며, 이는 결코 일어나지 않을 수도 있다.
  6. Assert: genContext는 실행 중인 실행 컨텍스트이다.
  7. resultgenContext가 방금 재개될 때 함께 전달된 Completion Record라 하자.
  8. Completion(result)를 반환한다.

9.5 Jobs and Host Operations to Enqueue Jobs

Job은 현재 진행 중인 다른 ECMAScript computation이 없을 때 ECMAScript computation을 initiate하는 parameter가 없는 Abstract Closure입니다.

Job은 특정 agent 안에서 ECMAScript host environment에 의해 execution을 위해 scheduled됩니다. 이 명세는 job을 schedule하기 위한 host hook HostEnqueueGenericJob, HostEnqueueFinalizationRegistryCleanupJob, HostEnqueuePromiseJob, HostEnqueueTimeoutJob을 설명합니다. 이 명세의 host hook은 job scheduling에 imposed되는 additional constraint에 의해 organized됩니다. Host는 job을 schedule하는 additional abstract operation을 define할 수 있습니다. 그러한 operation은 Job Abstract Closurerealm(Realm Record 또는 null)을 parameter로 accept합니다. Realm Record가 provided되면, 이러한 operation은 provided realm 안에서, 그 realm을 owns하는 agent 안에서, future time에 job이 performed되도록 schedule합니다. realm으로 null이 대신 provided되면, job은 ECMAScript code를 evaluate하지 않습니다. 그 implementation은 다음 requirement를 conform해야 합니다:

Note 1
Host environment는 scheduling과 관련하여 Job을 uniformly 취급할 필요가 없습니다. 예를 들어, web browser와 Node.js는 Promise-handling Job을 다른 work보다 higher priority로 취급합니다. future feature는 그렇게 high priority로 취급되지 않는 Job을 add할 수 있습니다.

특정 시점에서 scriptOrModule(Script Record, Module Record 또는 null)은 다음 조건이 모두 true이면 active script or module입니다:

특정 시점에서 execution은 다음 조건이 모두 true이면 prepared to evaluate ECMAScript code입니다:

Note 2

Host environmentexecution contextexecution context stack 위로 push함으로써 code를 evaluate할 execution을 prepare할 수 있습니다. specific step은 implementation-defined입니다.

Realm의 specific choice는 host environment에 달려 있습니다. 이 initial execution contextRealm은 callback function이 invoked되기 전까지만 사용됩니다. Promise handler 같은 Job과 관련된 callback function이 invoked되면, invocation은 자체 execution contextRealm을 push합니다.

Particular kind의 Job은 additional conformance requirement를 가집니다.

9.5.1 JobCallback Records

JobCallback Recordfunction objecthost-defined value를 store하는 데 사용되는 Record value입니다. host에 의해 enqueued된 Job을 통해 invoked되는 function object는 additional host-defined context를 가질 수 있습니다. state를 propagate하기 위해 Job Abstract Closurefunction object를 직접 capture하고 call해서는 안 됩니다. 대신 HostMakeJobCallbackHostCallJobCallback을 사용하십시오.

Note

WHATWG HTML specification(https://html.spec.whatwg.org/)은, 예를 들어, host-defined value를 사용하여 Promise callback에 대한 incumbent settings object를 propagate합니다.

JobCallback Record는 Table 24에 listed된 field를 가집니다.

Table 24: JobCallback Record Fields
Field Name Value Meaning
[[Callback]] a function object Job이 invoked될 때 invoke할 function입니다.
[[HostDefined]] anything (default value is empty) host가 사용하기 위해 reserved된 field입니다.

9.5.2 HostMakeJobCallback ( callback )

The host-defined abstract operation HostMakeJobCallback takes argument callback (a function object) and returns a JobCallback Record.

HostMakeJobCallback의 implementation은 다음 requirement를 conform해야 합니다:

HostMakeJobCallback의 default implementation은 called될 때 다음 step을 수행합니다:

  1. JobCallback Record { [[Callback]]: callback, [[HostDefined]]: empty }를 반환한다.

web browser가 아닌 ECMAScript host는 HostMakeJobCallback의 default implementation을 사용해야 합니다.

Note

이는 callback이 eventually scheduled되고 run되는 것을 responsible하는 function에 passed되는 시점에 called됩니다. 예를 들어, promise.then(thenAction)은 reaction Job을 scheduling하는 시점이 아니라 Promise.prototype.then을 invoking하는 시점에 thenAction에 대해 MakeJobCallback을 call합니다.

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의 implementation은 다음 requirement를 conform해야 합니다:

  • Call(jobCallback.[[Callback]], thisValue, argList)의 result를 perform하고 반환해야 합니다.
Note

이 requirement는 host가 이 명세에 정의된 function object[[Call]] behaviour를 change할 수 없음을 의미합니다.

HostCallJobCallback의 default implementation은 called될 때 다음 step을 수행합니다:

  1. Assert: IsCallable(jobCallback.[[Callback]])은 true이다.
  2. Call(jobCallback.[[Callback]], thisValue, argList)를 반환한다.

web browser가 아닌 ECMAScript host는 HostCallJobCallback의 default implementation을 사용해야 합니다.

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]]가 signified하는 agent 안에서, realm realm 안에 job을 future time에 performed되도록 schedule합니다. 이 algorithm과 함께 사용되는 Abstract Closure는 priority와 ordering 같은 additional constraint 없이 scheduled되도록 intended됩니다.

HostEnqueueGenericJob의 implementation은 9.5의 requirement를 conform해야 합니다.

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을 future time에 performed되도록 schedule합니다. 이 algorithm과 함께 사용되는 Abstract Closure는 Promise의 handling과 관련되거나, 그 밖에 Promise handling operation과 equal priority로 scheduled되도록 intended됩니다.

HostEnqueuePromiseJob의 implementation은 9.5의 requirement와 다음 requirement를 conform해야 합니다:

  • realmnull이 아니면, job이 invoked될 때마다 implementation은 job의 invocation 시점에 execution이 ECMAScript code를 evaluate할 준비가 되도록 implementation-defined step을 수행해야 합니다.
  • HostEnqueuePromiseJob이 invoked되는 시점의 GetActiveScriptOrModule()을 scriptOrModule로 둡니다. realmnull이 아니면, job이 invoked될 때마다 implementation은 job의 invocation 시점에 scriptOrModuleactive script or module이 되도록 implementation-defined step을 수행해야 합니다.
  • Job은 그것을 scheduled한 HostEnqueuePromiseJob invocation과 같은 order로 run해야 합니다.
Note

NewPromiseResolveThenableJob이 반환하는 Jobrealm은 보통 then function object에 대해 GetFunctionRealm을 call한 result입니다. NewPromiseReactionJob이 반환하는 Jobrealm은 handler가 undefined가 아니면 보통 handler에 대해 GetFunctionRealm을 call한 result입니다. handler가 undefined이면 realmnull입니다. 두 종류의 Job 모두에 대해, GetFunctionRealm이 abnormally complete하면(즉 revoked Proxy에 called되면), realmGetFunctionRealm call 시점의 current Realm Record입니다. realmnull이면 user ECMAScript code는 evaluate되지 않고 새 ECMAScript object(예: Error object)도 created되지 않습니다. WHATWG HTML specification(https://html.spec.whatwg.org/)은, 예를 들어, realm을 사용하여 script를 run할 capability와 entry concept를 check합니다.

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]]가 signified하는 agent 안에서, realm realm 안에 timeoutJob을 at least milliseconds milliseconds 후에 performed되도록 schedule합니다.

HostEnqueueTimeoutJob의 implementation은 9.5의 requirement를 conform해야 합니다.

9.6 Agents

agent는 ECMAScript execution context의 set, execution context stack, running execution context, Agent Record, 그리고 executing thread로 구성됩니다. executing thread를 제외하면, agent의 구성 요소는 exclusively 그 agent에 belong합니다.

agentexecuting thread는 다른 agent와 independent하게 그 agentexecution context에서 algorithmic step을 execute하지만, thread를 sharing하는 agent[[CanBlock]] field가 trueAgent Record를 가진 agent가 하나도 없다면 executing thread가 여러 agent에 의해 executing thread로 사용될 수 있습니다.

Note 1

예를 들어, 일부 web browser는 browser window의 unrelated tab 여러 개에 걸쳐 single executing thread를 share합니다.

agentexecuting thread가 algorithmic step을 executing하는 동안, 그 agent는 그 step에 대한 surrounding agent입니다. step은 surrounding agent를 사용하여 agent 안에 held된 specification-level execution object, 즉 running execution context, execution context stack, Agent Record의 field에 access합니다.

agent signifierAgent를 identify하는 데 사용되는 globally-unique opaque value입니다.

Table 25: 에이전트 레코드 필드
필드 이름 의미
[[LittleEndian]] Boolean 값 GetValueFromBufferSetValueInBuffer 알고리즘에서 필요할 때 isLittleEndian 매개변수에 대해 계산되는 기본값. 선택은 구현 정의이며, 해당 구현에 가장 효율적인 대안이어야 한다.
[[CanBlock]] Boolean 값 에이전트가 블록될 수 있는지 여부를 결정한다.
[[Signifier]] 에이전트 표시자 에이전트 클러스터 내에서 에이전트를 고유하게 식별한다.
[[IsLockFree1]] Boolean 값 1바이트 값에 대한 원자적 연산이 lock-free이면 true, 그렇지 않으면 false.
[[IsLockFree2]] Boolean 값 2바이트 값에 대한 원자적 연산이 lock-free이면 true, 그렇지 않으면 false.
[[IsLockFree8]] Boolean 값 8바이트 값에 대한 원자적 연산이 lock-free이면 true, 그렇지 않으면 false.
[[CandidateExecution]] candidate execution Record 메모리 모델을 참조하라.
[[KeptAlive]] Object 또는 Symbol의 List 처음에는 새 빈 List이며, 현재 Job의 끝까지 살아 있게 유지할 객체 및/또는 심벌의 목록을 나타낸다
[[ModuleAsyncEvaluationCount]] 정수 처음에는 0이며, 비동기이거나 비동기 의존성을 가진 모듈의 [[AsyncEvaluationOrder]] 필드에 고유하게 증가하는 값을 할당하는 데 사용된다.
[[GlobalSymbolRegistry]] GlobalSymbolRegistry RecordList 처음에는 새 빈 List이며, Symbol.for에 의해 생성된 Symbol 값의 목록을 나타낸다.

[[LittleEndian]], [[Signifier]], [[IsLockFree1]], [[IsLockFree2]], [[IsLockFree8]]의 값은 변경될 수 없다.

[[GlobalSymbolRegistry]] List는 추가만 가능하며 재할당되지 않는다.

Note 2

[[IsLockFree1]], [[IsLockFree2]], [[IsLockFree8]]의 value는 necessarily hardware에 의해 determined되는 것은 아니며, over time 및 ECMAScript implementation 사이에서 vary할 수 있는 implementation choice를 reflect할 수도 있습니다.

[[IsLockFree4]] field는 없습니다: 4-byte atomic operation은 항상 lock-free입니다.

실제로 atomic operation이 어떤 type의 lock으로 implement되면 그 operation은 lock-free가 아닙니다. Lock-free는 wait-free를 imply하지 않습니다: lock-free atomic operation을 complete하는 데 필요한 machine step 수에는 upper bound가 없습니다.

size가 n인 atomic access가 lock-free라는 것이 size가 n인 non-atomic access의 (perceived) atomicity에 대해 어떤 것도 imply하지 않습니다. 특히 non-atomic access는 여전히 여러 separate memory access의 sequence로 performed될 수 있습니다. detail은 ReadSharedMemoryWriteSharedMemory를 참조하십시오.

Note 3

agent는 specification mechanism이며 ECMAScript implementation의 특정 artefact에 대응할 필요가 없습니다.

9.6.1 AgentSignifier ( )

The abstract operation AgentSignifier takes no arguments and returns an agent signifier. It performs the following steps when called:

  1. agentRecordsurrounding agentAgent Record로 둔다.
  2. agentRecord.[[Signifier]]를 반환한다.

9.6.2 AgentCanSuspend ( )

The abstract operation AgentCanSuspend takes no arguments and returns a Boolean. It performs the following steps when called:

  1. agentRecordsurrounding agentAgent Record로 둔다.
  2. agentRecord.[[CanBlock]]을 반환한다.
Note

일부 environment에서는 주어진 agent가 suspend되는 것이 reasonable하지 않을 수 있습니다. 예를 들어, web browser environment에서는 document의 main event handling thread가 suspend되는 것을 disallow하면서 worker의 event handling thread는 suspend하도록 allow하는 것이 reasonable할 수 있습니다.

9.6.3 IncrementModuleAsyncEvaluationCount ( )

The abstract operation IncrementModuleAsyncEvaluationCount takes no arguments and returns a non-negative integer. It performs the following steps when called:

  1. agentRecordsurrounding agentAgent Record로 둔다.
  2. countagentRecord.[[ModuleAsyncEvaluationCount]]로 둔다.
  3. agentRecord.[[ModuleAsyncEvaluationCount]]count + 1로 설정한다.
  4. count를 반환한다.
Note

이 value는 pending module 사이의 relative evaluation order를 keep track하는 데만 사용됩니다. implementation은 pending module이 없을 때마다 unobservably [[ModuleAsyncEvaluationCount]]를 0으로 reset할 수 있습니다.

9.7 Agent Clusters

agent cluster는 shared memory를 operate함으로써 communicate할 수 있는 agent의 maximal set입니다.

Note 1

서로 다른 agent 안의 program은 unspecified means로 memory를 share할 수 있습니다. 최소한 SharedArrayBuffer의 backing memory는 cluster 안의 agent들 사이에서 shared될 수 있습니다.

message passing으로 communicate할 수 있지만 memory를 share할 수 없는 agent가 있을 수 있습니다. 이들은 결코 같은 agent cluster에 있지 않습니다.

모든 agent는 exactly one agent cluster에 belong합니다.

Note 2

cluster 안의 agent가 모두 특정 시점에 alive일 필요는 없습니다. agent A가 다른 agent B를 create한 후 A가 terminate되고 Bagent C를 create하면, AB와 some memory를 share할 수 있었고 BC와 some memory를 share할 수 있었다면 세 agent는 같은 cluster에 있습니다.

cluster 안의 모든 agent는 각각의 Agent Record 안의 [[LittleEndian]] field에 대해 같은 value를 가져야 합니다.

Note 3

agent cluster 안의 서로 다른 agent[[LittleEndian]]의 different value를 가지면 multi-byte data에 shared memory를 use하기 어려워집니다.

cluster 안의 모든 agent는 각각의 Agent Record 안의 [[IsLockFree1]] field에 대해 같은 value를 가져야 합니다; [[IsLockFree2]][[IsLockFree8]] field도 마찬가지입니다.

cluster 안의 모든 agent는 각각의 Agent Record 안의 [[Signifier]] field에 대해 서로 다른 value를 가져야 합니다.

embedding은 agent의 knowledge나 cooperation 없이 agent를 deactivate(forward progress를 stop)하거나 activate(forward progress를 resume)할 수 있습니다. embedding이 그렇게 하는 경우, cluster 안의 일부 agent를 active로 남겨둔 채 다른 agent를 indefinitely deactivated 상태로 두어서는 안 됩니다.

Note 4

preceding restriction의 purpose는 다른 agent가 deactivated되어 agent가 deadlock되거나 starve되는 situation을 avoid하는 것입니다. 예를 들어, 어떤 window의 document와 independent한 lifetime을 가진 HTML shared worker가 그러한 independent document의 dedicated worker와 memory를 share할 수 있도록 allowed되었고, document와 그 dedicated worker가 dedicated worker가 lock을 hold하고 있는 동안 deactivated된다면(예: document가 window의 history에 pushed됨), shared worker가 그 lock을 acquire하려고 할 때 shared worker는 dedicated worker가 다시 activated될 때까지, 혹은 ever, blocked됩니다. Meanwhile 다른 window에서 shared worker에 access하려는 다른 worker는 starve됩니다.

restriction의 implication은 embedding 안에서 같은 suspend/wake collective에 belong하지 않는 agent 사이에서는 memory를 share할 수 없다는 것입니다.

embedding은 agent cluster의 다른 agent가 prior knowledge나 cooperation을 가지지 않아도 agent를 terminate할 수 있습니다. agent가 cluster 안의 자체 programmatic action이나 다른 agent의 programmatic action이 아니라 cluster 외부의 force에 의해 terminated되면, embedding은 두 strategy 중 하나를 choose해야 합니다: cluster 안의 모든 agent를 terminate하거나, cluster 안의 agent가 coordinate하여 cluster의 적어도 하나의 remaining member가 termination을 detect할 수 있게 하는 reliable API를 provide해야 하며, termination data는 terminated된 agent를 identify하기에 충분한 information을 contain해야 합니다.

Note 5

그 type의 termination example은 다음과 같습니다: operating system 또는 user가 separate process에서 running 중인 agent를 terminate하는 경우; per-agent resource accounting이 agent가 runaway임을 indicate할 때 embedding 자체가 다른 agent와 in-process로 running 중인 agent를 terminate하는 경우.

다음 specification value 각각과, 그것들로부터 transitively reachable한 value는 exactly one agent cluster에 belong합니다.

cluster 안의 어떤 agent가 ECMAScript code를 evaluate하기 전에, cluster 안의 모든 agent에 대한 Agent Record[[CandidateExecution]] field는 initial candidate execution으로 set됩니다. initial candidate execution[[EventsRecords]] field가 각 agent에 대해 그 agentagent signifier[[AgentSignifier]] field와 empty List[[EventList]][[AgentSynchronizesWith]] field를 가진 Agent Events Record를 contain하는 Listempty candidate execution입니다.

Note 6

agent cluster 안의 모든 agent는 그 Agent Record[[CandidateExecution]] field 안에서 같은 candidate execution을 share합니다. candidate executionmemory model에서 사용하는 specification mechanism입니다.

Note 7

agent cluster는 specification mechanism이며 ECMAScript implementation의 특정 artefact에 대응할 필요가 없습니다.

9.8 Forward Progress

agentmake forward progress한다는 것은 이 명세에 따라 evaluation step을 perform한다는 것입니다.

agentrunning execution context가 external event를 위해 synchronously and indefinitely wait할 때 agentblocked가 됩니다. Agent Record[[CanBlock]] field가 trueagent만 이러한 의미에서 blocked될 수 있습니다. unblocked agent는 blocked되지 않은 agent입니다.

implementation은 다음을 ensure해야 합니다:

  • dedicated executing thread를 가진 모든 unblocked agent는 eventually forward progress를 make합니다
  • executing thread를 share하는 agent의 set 안에서는 하나의 agent가 eventually forward progress를 make합니다
  • agent는 blocking을 provide하는 explicit API를 통하지 않고는 다른 agent를 blocked되게 cause하지 않습니다.
Note

이는 memory model의 liveness guarantee와 함께, 모든 seq-cst write가 eventually 모든 agent에 observable하게 됨을 ensure합니다.

9.9 Processing Model of WeakRef and FinalizationRegistry Targets

9.9.1 Objectives

이 명세는 어떤 object 또는 symbol도 garbage collected될 것이라는 guarantee를 하지 않습니다. live가 아닌 object 또는 symbol은 long period of time 후에 released될 수도 있고, 전혀 released되지 않을 수도 있습니다. 이러한 이유로, 이 명세는 garbage collection에 의해 triggered되는 behaviour를 describing할 때 “may”라는 term을 사용합니다.

WeakRefFinalizationRegistry의 semantics는 특정 point in time에 발생하는 두 operation에 기반합니다:

  • WeakRef.prototype.deref가 called될 때, referent(undefined가 returned되지 않는 경우)는 subsequent synchronous access도 같은 value를 return하도록 alive로 kept됩니다. 이 list는 ClearKeptObjects abstract operation을 사용하여 synchronous work가 done될 때 reset됩니다.
  • FinalizationRegistry에 registered된 object 또는 symbol이 unreachable이 되면, synchronous ECMAScript execution이 completes된 후 FinalizationRegistry의 cleanup callback call이 eventually made될 수 있습니다. FinalizationRegistry cleanup은 CleanupFinalizationRegistry abstract operation으로 performed됩니다.

이러한 action(ClearKeptObjects 또는 CleanupFinalizationRegistry) 중 어느 것도 synchronous ECMAScript execution을 interrupt할 수 없습니다. host는 더 긴 synchronous ECMAScript execution run을 assemble할 수 있으므로, 이 명세는 ClearKeptObjectsCleanupFinalizationRegistry의 scheduling을 host environment에 defer합니다.

일부 ECMAScript implementation은 ECMAScript가 idle일 때를 포함하여 background에서 run하는 garbage collector implementation을 포함합니다. host environmentCleanupFinalizationRegistry를 schedule하게 하면 finalizer work를 run하기 위해 ECMAScript execution을 resume할 수 있으며, 이는 held value를 free up하여 overall memory usage를 reduce할 수 있습니다.

9.9.2 Liveness

object 및/또는 symbol의 어떤 set objSet에 대해 objSet와 관련한 hypothetical WeakRef-oblivious execution은 referent가 objSet의 element인 WeakRef의 abstract operation WeakRefDeref가 항상 undefined를 반환하는 execution입니다.

Note 1
WeakRef-obliviousness는 liveness와 함께 두 notion을 capture합니다. 첫째, WeakRef 자체는 그 referent를 alive로 keep하지 않습니다. 둘째, liveness의 cycle은 value가 live임을 imply하지 않습니다. 구체적으로, v의 liveness를 determining하는 것이 WeakRef referent r의 liveness를 determining하는 것에 depend한다면, r의 liveness는 v의 liveness를 assume할 수 없습니다. 이는 circular reasoning이기 때문입니다.
Note 2
WeakRef-obliviousness는 cycle을 account하기 위해 individual value 대신 object 또는 symbol의 set에 대해 정의됩니다. individual value에 대해 정의된다면, cycle 안의 WeakRef referent는 그 identity가 cycle 안의 다른 WeakRef referent를 통해서만 observed되더라도 live로 considered될 것입니다.
Note 3
Colloquially, 우리는 individual object 또는 symbol이 그것을 contain하는 모든 set이 live이면 live라고 말합니다.

evaluation 중 어느 point에서든, object 및/또는 symbol의 set objSet는 다음 조건 중 하나가 met되면 live로 considered됩니다:

  • objSet 안의 어떤 element가 어떤 agent[[KeptAlive]] List에 included되어 있습니다.
  • objSet와 관련하여 valid future hypothetical WeakRef-oblivious execution이 존재하며, 이는 objSet 안의 어떤 value의 identity를 observe합니다.
Note 4
위의 두 번째 condition은 value의 identity가 non-WeakRef means를 통해 observable하면 그 value가 live라는 intuition을 capture하려는 의도입니다. value의 identity는 strict equality comparison을 observing하거나 Map의 key로 사용되는 value를 observing함으로써 observed될 수 있습니다.
Note 5

field, internal slot 또는 property 안에 object나 symbol이 존재한다는 것은 그 value가 live임을 imply하지 않습니다. 예를 들어 해당 value가 program에 다시 passed되지 않으면, it cannot be observed.

이는 WeakMap의 key, WeakSet의 member, 그리고 FinalizationRegistry Cell record의 [[WeakRefTarget]][[UnregisterToken]] field의 경우에 해당합니다.

위 definition은, WeakMap 안의 key가 live가 아니면, 그 corresponding value도 necessarily live인 것은 아님을 imply합니다.

Note 6
Liveness는 engine이 반드시 empty하지 않아야 하는 WeakRef를 guarantee하기 위한 lower bound입니다. 여기서 정의된 Liveness는 undecidable입니다. 실제로 engine은 reachability 같은 conservative approximation을 사용합니다. significant implementation leeway가 expected됩니다.

9.9.3 Execution

어느 때든 object 및/또는 symbol의 set objSetlive가 아니면, ECMAScript implementation은 다음 step을 atomically perform할 수 있습니다:

  1. objSet의 각 element value에 대해, 다음을 수행한다.
    1. ref.[[WeakRefTarget]]value인 각 WeakRef ref에 대해, 다음을 수행한다.
      1. ref.[[WeakRefTarget]]empty로 설정한다.
    2. finalizationRegistry.[[Cells]]cell.[[WeakRefTarget]]valueRecord cell을 contain하는 각 FinalizationRegistry finalizationRegistry에 대해, 다음을 수행한다.
      1. cell.[[WeakRefTarget]]empty로 설정한다.
      2. enqueueCleanuptrue 또는 false 중 하나의 implementation-defined choice로 둔다.
      3. enqueueCleanuptrue이면, HostEnqueueFinalizationRegistryCleanupJob(finalizationRegistry)를 수행한다.
    3. map.[[WeakMapData]]entry.[[Key]]valueRecord entry를 contain하는 각 WeakMap map에 대해, 다음을 수행한다.
      1. entry.[[Key]]empty로 설정한다.
      2. entry.[[Value]]empty로 설정한다.
    4. set.[[WeakSetData]]value를 contain하는 각 WeakSet set에 대해, 다음을 수행한다.
      1. set.[[WeakSetData]] 안에서 value가 value인 element를 value가 empty인 element로 replace한다.
Note 1

liveness의 definition과 함께, 이 clause는 implementation이 WeakRef와 관련하여 apply할 수 있는 optimization을 prescribe합니다.

object의 identity를 observing하지 않고 object에 access하는 것이 가능합니다. identity가 observed되지 않는 non-escaping object의 property에 대한 dead variable elimination 및 scalar replacement 같은 optimization은 allowed됩니다. 따라서 이러한 optimization은 그러한 object를 point하는 WeakRef를 observably empty하는 것을 allow합니다.

반면, object의 identity가 observable이고 그 object가 WeakRef[[WeakRefTarget]] internal slot 안에 있으면, WeakRef를 observably empty하는 rematerialization 같은 optimization은 prohibited됩니다.

HostEnqueueFinalizationRegistryCleanupJob을 calling하는 것은 optional이므로, FinalizationRegistry 안의 registered object가 necessarily 그 FinalizationRegistrylive로 hold하지는 않습니다. implementation은 어떤 이유로든 FinalizationRegistry callback을 omit할 수 있습니다. 예를 들어, FinalizationRegistry 자체가 dead가 되거나 application이 shutting down되는 경우입니다.

Note 2

implementation은 non-live object 또는 symbol의 maximal set에 대해 WeakRef를 empty할 의무가 없습니다.

implementation이 WeakRef를 empty할 non-live set objSet을 choose하면, 이 definition은 objSet 안의 모든 value에 대한 WeakRef를 simultaneously empty할 것을 require합니다. 다시 말해, implementation이 value v를 point하는 WeakRef를 empty하면서, empty하지 않으면 v의 value를 observe하는 execution을 result할 수 있는 다른 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을 parameter가 없고 finalizationRegistry를 capture하며 called될 때 다음 step을 수행하는 새 Job Abstract Closure로 둔다:

  1. cleanupResultCompletion(CleanupFinalizationRegistry(finalizationRegistry))로 둔다.
  2. cleanupResultabrupt completion이면, error를 reporting하기 위한 host-defined step을 수행한다.
  3. unused를 반환한다.

HostEnqueueFinalizationRegistryCleanupJob의 implementation은 가능하면 cleanupJob이 future time에 performed되도록 schedule합니다. 또한 9.5의 requirement를 conform해야 합니다.

9.10 ClearKeptObjects ( )

The abstract operation ClearKeptObjects takes no arguments and returns unused. ECMAScript implementation은 synchronous sequence of ECMAScript executions가 completes될 때 ClearKeptObjects를 call할 것으로 expected됩니다. It performs the following steps when called:

  1. agentRecordsurrounding agentAgent Record로 둔다.
  2. agentRecord.[[KeptAlive]]를 새 empty List로 설정한다.
  3. unused를 반환한다.

9.11 AddToKeptObjects ( value )

The abstract operation AddToKeptObjects takes argument value (an Object or a Symbol) and returns unused. It performs the following steps when called:

  1. agentRecordsurrounding agentAgent Record로 둔다.
  2. valueagentRecord.[[KeptAlive]]에 append한다.
  3. unused를 반환한다.
Note
abstract operation AddToKeptObjects가 target object 또는 symbol과 함께 called되면, 이는 ClearKeptObjects가 called될 때까지 target을 strongly point할 list에 target을 add합니다.

9.12 CleanupFinalizationRegistry ( finalizationRegistry )

The abstract operation CleanupFinalizationRegistry takes argument finalizationRegistry (a FinalizationRegistry) and returns either a normal completion containing unused or a throw completion. It performs the following steps when called:

  1. Assert: finalizationRegistry[[Cells]][[CleanupCallback]] internal slot을 가진다.
  2. callbackfinalizationRegistry.[[CleanupCallback]]으로 둔다.
  3. finalizationRegistry.[[Cells]]cell.[[WeakRefTarget]]emptyRecord cell을 contain하는 동안, implementation은 다음 step을 수행할 수 있다:
    1. 그러한 cell 중 아무 것이나 choose한다.
    2. finalizationRegistry.[[Cells]]에서 cell을 remove한다.
    3. HostCallJobCallback(callback, undefined, « cell.[[HeldValue]] »)를 수행한다.
  4. unused를 반환한다.

9.13 CanBeHeldWeakly ( arg )

The abstract operation CanBeHeldWeakly takes argument arg (an ECMAScript language value) and returns a Boolean. arg가 weak reference로 사용하기에 suitable하면 and only if true를 반환합니다. weak reference로 사용하기에 suitable한 value만 WeakMap의 key, WeakSet의 element, WeakRef의 target, 또는 FinalizationRegistry의 target 중 하나일 수 있습니다. It performs the following steps when called:

  1. arg가 Object이면, true를 반환한다.
  2. arg가 Symbol이고 KeyForSymbol(arg)이 undefined이면, true를 반환한다.
  3. false를 반환한다.
Note

language identity가 없는 language value는 prior reference 없이 manifested될 수 있으므로 weak reference로 사용하기에 unsuitable합니다. Symbol.for가 produced한 Symbol value는 다른 Symbol value와 달리 language identity를 가지지 않으며 weak reference로 사용하기에 unsuitable합니다. Well-known symbols는 collected되지 않을 가능성이 높지만, number가 limited되어 다양한 implementation approach로 manageable하기 때문에 nonetheless weak reference로 사용하기에 suitable한 것으로 treated됩니다. 그러나 live WeakMap 안의 well-known symbol에 associated된 value는 collected될 가능성이 낮고 implementation에서 memory resource를 “leak”할 수 있습니다.

10 Ordinary 및 Exotic Objects Behaviours

10.1 Ordinary Object Internal Methods and Internal Slots

모든 ordinary object[[Prototype]]이라는 internal slot을 가집니다. 이 internal slot의 value는 null 또는 object이며 inheritance를 implementing하는 데 사용됩니다. propertyKey라는 property가 ordinary object obj에는 missing이지만 그 [[Prototype]] object에는 존재한다고 가정합니다. propertyKey[[Prototype]] object 위의 data property를 refer하면, obj는 get access에 대해 이를 inherit하여 propertyKeyobj의 property인 것처럼 behave하게 합니다. propertyKey[[Prototype]] object 위의 writable data property를 refer하면, obj 위의 propertyKey의 set access는 obj 위에 propertyKey라는 새 data property를 create합니다. propertyKey[[Prototype]] object 위의 non-writable data property를 refer하면, obj 위의 propertyKey의 set access는 fail합니다. propertyKey[[Prototype]] object 위의 accessor property를 refer하면, accessor는 get access와 set access 모두에 대해 obj에 inherited됩니다.

모든 ordinary object는 Boolean-valued [[Extensible]] internal slot을 가지며, 이는 6.1.7.3에 specified된 extensibility-related internal method invariant를 fulfill하는 데 사용됩니다. 즉, object의 [[Extensible]] internal slot의 value가 일단 false로 set되면, 그 object에 property를 add하거나, object의 [[Prototype]] internal slot의 value를 modify하거나, 이후 [[Extensible]]의 value를 true로 change하는 것은 더 이상 possible하지 않습니다.

다음 algorithm description에서, objordinary object, propertyKeyproperty key value, value는 임의의 ECMAScript language value, propertyDescProperty Descriptor record라고 가정합니다.

ordinary object internal method는 similarly-named abstract operation에 delegate합니다. 그러한 abstract operation이 다른 internal method에 depend하면, similarly-named abstract operation을 직접 calling하는 대신 obj 위에서 internal method가 invoked됩니다. 이러한 semantics는 ordinary object internal method가 exotic object에 applied될 때 그 overridden internal method가 invoked되도록 ensure합니다.

10.1.1 [[GetPrototypeOf]] ( )

The [[GetPrototypeOf]] internal method of an ordinary object obj takes no arguments and returns a normal completion containing either an Object or null. It performs the following steps when called:

  1. OrdinaryGetPrototypeOf(obj)를 반환한다.

10.1.1.1 OrdinaryGetPrototypeOf ( obj )

The abstract operation OrdinaryGetPrototypeOf takes argument obj (an Object) and returns an Object or null. It performs the following steps when called:

  1. obj.[[Prototype]]을 반환한다.

10.1.2 [[SetPrototypeOf]] ( proto )

The [[SetPrototypeOf]] internal method of an ordinary object obj takes argument proto (an Object or null) and returns a normal completion containing a Boolean. It performs the following steps when called:

  1. OrdinarySetPrototypeOf(obj, proto)를 반환한다.

10.1.2.1 OrdinarySetPrototypeOf ( obj, proto )

The abstract operation OrdinarySetPrototypeOf takes arguments obj (an Object) and proto (an Object or null) and returns a Boolean. It performs the following steps when called:

  1. currentobj.[[Prototype]]으로 둔다.
  2. SameValue(proto, current)가 true이면, true를 반환한다.
  3. extensibleobj.[[Extensible]]로 둔다.
  4. extensiblefalse이면, false를 반환한다.
  5. cursorproto로 둔다.
  6. donefalse로 둔다.
  7. donefalse인 동안 Repeat,
    1. cursornull이면, 다음을 수행한다.
      1. donetrue로 설정한다.
    2. 그렇지 않고 SameValue(cursor, obj)가 true이면, 다음을 수행한다.
      1. false를 반환한다.
    3. 그렇지 않으면,
      1. cursor.[[GetPrototypeOf]]10.1.1에 정의된 ordinary object internal method가 아니면, donetrue로 설정한다.
      2. 그렇지 않으면, cursorcursor.[[Prototype]]으로 설정한다.
  8. obj.[[Prototype]]proto로 설정한다.
  9. true를 반환한다.
Note

step 7의 loop는 [[GetPrototypeOf]][[SetPrototypeOf]]에 대해 ordinary object definition을 사용하는 object만 포함하는 prototype chain 안에는 cycle이 없음을 guarantee합니다.

10.1.3 [[IsExtensible]] ( )

The [[IsExtensible]] internal method of an ordinary object obj takes no arguments and returns a normal completion containing a Boolean. It performs the following steps when called:

  1. OrdinaryIsExtensible(obj)를 반환한다.

10.1.3.1 OrdinaryIsExtensible ( obj )

The abstract operation OrdinaryIsExtensible takes argument obj (an Object) and returns a Boolean. It performs the following steps when called:

  1. obj.[[Extensible]]을 반환한다.

10.1.4 [[PreventExtensions]] ( )

The [[PreventExtensions]] internal method of an ordinary object obj takes no arguments and returns a normal completion containing true. It performs the following steps when called:

  1. OrdinaryPreventExtensions(obj)를 반환한다.

10.1.4.1 OrdinaryPreventExtensions ( obj )

The abstract operation OrdinaryPreventExtensions takes argument obj (an Object) and returns true. It performs the following steps when called:

  1. obj.[[Extensible]]false로 설정한다.
  2. true를 반환한다.

10.1.5 [[GetOwnProperty]] ( propertyKey )

The [[GetOwnProperty]] internal method of an ordinary object obj takes argument propertyKey (a property key) and returns a normal completion containing either a Property Descriptor or undefined. It performs the following steps when called:

  1. OrdinaryGetOwnProperty(obj, propertyKey)를 반환한다.

10.1.5.1 OrdinaryGetOwnProperty ( obj, propertyKey )

The abstract operation OrdinaryGetOwnProperty takes arguments obj (an Object) and propertyKey (a property key) and returns a Property Descriptor or undefined. It performs the following steps when called:

  1. obj가 key가 propertyKey인 own property를 가지지 않으면, undefined를 반환한다.
  2. propertyDesc를 field가 없는 newly created Property Descriptor로 둔다.
  3. ownProperty를 key가 propertyKeyobj의 own property로 둔다.
  4. ownPropertydata property이면, 다음을 수행한다.
    1. propertyDesc.[[Value]]ownProperty[[Value]] attribute의 value로 설정한다.
    2. propertyDesc.[[Writable]]ownProperty[[Writable]] attribute의 value로 설정한다.
  5. 그렇지 않으면,
    1. Assert: ownPropertyaccessor property이다.
    2. propertyDesc.[[Get]]ownProperty[[Get]] attribute의 value로 설정한다.
    3. propertyDesc.[[Set]]ownProperty[[Set]] attribute의 value로 설정한다.
  6. propertyDesc.[[Enumerable]]ownProperty[[Enumerable]] attribute의 value로 설정한다.
  7. propertyDesc.[[Configurable]]ownProperty[[Configurable]] attribute의 value로 설정한다.
  8. propertyDesc를 반환한다.

10.1.6 [[DefineOwnProperty]] ( propertyKey, propertyDesc )

The [[DefineOwnProperty]] internal method of an ordinary object obj takes arguments propertyKey (a property key) and propertyDesc (a Property Descriptor) and returns either a normal completion containing a Boolean or a throw completion. It performs the following steps when called:

  1. OrdinaryDefineOwnProperty(obj, propertyKey, propertyDesc)를 반환한다.

10.1.6.1 OrdinaryDefineOwnProperty ( obj, propertyKey, propertyDesc )

The abstract operation OrdinaryDefineOwnProperty takes arguments obj (an Object), propertyKey (a property key), and propertyDesc (a Property Descriptor) and returns either a normal completion containing a Boolean or a throw completion. It performs the following steps when called:

  1. current를 ? obj.[[GetOwnProperty]](propertyKey)로 둔다.
  2. extensible을 ? IsExtensible(obj)로 둔다.
  3. ValidateAndApplyPropertyDescriptor(obj, propertyKey, extensible, propertyDesc, current)를 반환한다.

10.1.6.2 IsCompatiblePropertyDescriptor ( extensible, propertyDesc, current )

The abstract operation IsCompatiblePropertyDescriptor takes arguments extensible (a Boolean), propertyDesc (a Property Descriptor), and current (a Property Descriptor or undefined) and returns a Boolean. It performs the following steps when called:

  1. ValidateAndApplyPropertyDescriptor(undefined, "", extensible, propertyDesc, current)를 반환한다.

10.1.6.3 ValidateAndApplyPropertyDescriptor ( obj, propertyKey, extensible, propertyDesc, current )

The abstract operation ValidateAndApplyPropertyDescriptor takes arguments obj (an Object or undefined), propertyKey (a property key), extensible (a Boolean), propertyDesc (a Property Descriptor), and current (a Property Descriptor or undefined) and returns a Boolean. specified extensibility와 current property current를 가진 object의 property로 propertyDescinvariant를 uphold하면서 apply할 수 있으면 and only if true를 반환합니다. 그러한 application이 possible하고 objundefined가 아니면, propertyKey라는 name의 property에 대해 performed됩니다(필요하면 created됩니다). It performs the following steps when called:

  1. Assert: propertyKeyproperty key이다.
  2. currentundefined이면, 다음을 수행한다.
    1. extensiblefalse이면, false를 반환한다.
    2. objundefined이면, true를 반환한다.
    3. IsAccessorDescriptor(propertyDesc)가 true이면, 다음을 수행한다.
      1. object obj 위에 propertyKey라는 own accessor property를 create하되, 그 [[Get]], [[Set]], [[Enumerable]], [[Configurable]] attribute는 propertyDesc가 해당 field를 가지면 propertyDesc 안의 corresponding field의 value로, 그렇지 않으면 attribute의 default value로 설정한다.
    4. 그렇지 않으면,
      1. object obj 위에 propertyKey라는 own data property를 create하되, 그 [[Value]], [[Writable]], [[Enumerable]], [[Configurable]] attribute는 propertyDesc가 해당 field를 가지면 propertyDesc 안의 corresponding field의 value로, 그렇지 않으면 attribute의 default value로 설정한다.
    5. true를 반환한다.
  3. Assert: currentfully populated Property Descriptor이다.
  4. propertyDesc가 어떤 field도 가지지 않으면, true를 반환한다.
  5. current.[[Configurable]]false이면, 다음을 수행한다.
    1. propertyDesc[[Configurable]] field를 가지고 propertyDesc.[[Configurable]]true이면, false를 반환한다.
    2. propertyDesc[[Enumerable]] field를 가지고 propertyDesc.[[Enumerable]]current.[[Enumerable]]이 아니면, false를 반환한다.
    3. IsGenericDescriptor(propertyDesc)가 false이고 IsAccessorDescriptor(propertyDesc)가 IsAccessorDescriptor(current)가 아니면, false를 반환한다.
    4. IsAccessorDescriptor(current)가 true이면, 다음을 수행한다.
      1. propertyDesc[[Get]] field를 가지고 SameValue(propertyDesc.[[Get]], current.[[Get]])이 false이면, false를 반환한다.
      2. propertyDesc[[Set]] field를 가지고 SameValue(propertyDesc.[[Set]], current.[[Set]])이 false이면, false를 반환한다.
    5. 그렇지 않고 current.[[Writable]]false이면, 다음을 수행한다.
      1. propertyDesc[[Writable]] field를 가지고 propertyDesc.[[Writable]]true이면, false를 반환한다.
      2. NOTE: SameValue는 다른 means로 distinguishable할 수 있는 NaN value에 대해 true를 반환합니다. 여기서 return하면 obj의 existing property가 unmodified로 남도록 ensure합니다.
      3. propertyDesc[[Value]] field를 가지면, SameValue(propertyDesc.[[Value]], current.[[Value]])를 반환한다.
  6. objundefined가 아니면, 다음을 수행한다.
    1. IsDataDescriptor(current)가 true이고 IsAccessorDescriptor(propertyDesc)가 true이면, 다음을 수행한다.
      1. propertyDesc[[Configurable]] field를 가지면, configurablepropertyDesc.[[Configurable]]로 둔다; 그렇지 않으면 configurablecurrent.[[Configurable]]로 둔다.
      2. propertyDesc[[Enumerable]] field를 가지면, enumerablepropertyDesc.[[Enumerable]]로 둔다; 그렇지 않으면 enumerablecurrent.[[Enumerable]]으로 둔다.
      3. object objpropertyKey라는 property를 accessor property로 replace하되, 그 [[Configurable]][[Enumerable]] attribute는 각각 configurableenumerable로 설정하고, [[Get]][[Set]] attribute는 propertyDesc가 해당 field를 가지면 propertyDesc 안의 corresponding field의 value로, 그렇지 않으면 attribute의 default value로 설정한다.
    2. 그렇지 않고 IsAccessorDescriptor(current)가 true이고 IsDataDescriptor(propertyDesc)가 true이면, 다음을 수행한다.
      1. propertyDesc[[Configurable]] field를 가지면, configurablepropertyDesc.[[Configurable]]로 둔다; 그렇지 않으면 configurablecurrent.[[Configurable]]로 둔다.
      2. propertyDesc[[Enumerable]] field를 가지면, enumerablepropertyDesc.[[Enumerable]]로 둔다; 그렇지 않으면 enumerablecurrent.[[Enumerable]]으로 둔다.
      3. object objpropertyKey라는 property를 data property로 replace하되, 그 [[Configurable]][[Enumerable]] attribute는 각각 configurableenumerable로 설정하고, [[Value]][[Writable]] attribute는 propertyDesc가 해당 field를 가지면 propertyDesc 안의 corresponding field의 value로, 그렇지 않으면 attribute의 default value로 설정한다.
    3. 그렇지 않으면,
      1. propertyDesc의 각 field name fieldName에 대해, object objpropertyKey라는 property의 fieldName이라는 attribute를 propertyDescfieldName field의 value로 설정한다.
  7. true를 반환한다.

10.1.7 [[HasProperty]] ( propertyKey )

The [[HasProperty]] internal method of an ordinary object obj takes argument propertyKey (a property key) and returns either a normal completion containing a Boolean or a throw completion. It performs the following steps when called:

  1. OrdinaryHasProperty(obj, propertyKey)를 반환한다.

10.1.7.1 OrdinaryHasProperty ( obj, propertyKey )

The abstract operation OrdinaryHasProperty takes arguments obj (an Object) and propertyKey (a property key) and returns either a normal completion containing a Boolean or a throw completion. It performs the following steps when called:

  1. hasOwn을 ? obj.[[GetOwnProperty]](propertyKey)로 둔다.
  2. hasOwnundefined가 아니면, true를 반환한다.
  3. parent를 ? obj.[[GetPrototypeOf]]()로 둔다.
  4. parentnull이 아니면, 다음을 수행한다.
    1. parent.[[HasProperty]](propertyKey)를 반환한다.
  5. false를 반환한다.

10.1.8 [[Get]] ( propertyKey, receiver )

The [[Get]] internal method of an ordinary object obj takes arguments propertyKey (a property key) and receiver (an ECMAScript language value) and returns either a normal completion containing an ECMAScript language value or a throw completion. It performs the following steps when called:

  1. OrdinaryGet(obj, propertyKey, receiver)를 반환한다.

10.1.8.1 OrdinaryGet ( obj, propertyKey, receiver )

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

  1. propertyDesc를 ? obj.[[GetOwnProperty]](propertyKey)로 둔다.
  2. propertyDescundefined이면, 다음을 수행한다.
    1. parent를 ? obj.[[GetPrototypeOf]]()로 둔다.
    2. parentnull이면, undefined를 반환한다.
    3. parent.[[Get]](propertyKey, receiver)를 반환한다.
  3. IsDataDescriptor(propertyDesc)가 true이면, propertyDesc.[[Value]]를 반환한다.
  4. Assert: IsAccessorDescriptor(propertyDesc)는 true이다.
  5. getterpropertyDesc.[[Get]]으로 둔다.
  6. getterundefined이면, undefined를 반환한다.
  7. Call(getter, receiver)를 반환한다.

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

The [[Set]] internal method of an ordinary object obj takes arguments propertyKey (a property key), value (an ECMAScript language value), and receiver (an ECMAScript language value) and returns either a normal completion containing a Boolean or a throw completion. It performs the following steps when called:

  1. OrdinarySet(obj, propertyKey, value, receiver)를 반환한다.

10.1.9.1 OrdinarySet ( obj, propertyKey, value, receiver )

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

  1. ownDesc를 ? obj.[[GetOwnProperty]](propertyKey)로 둔다.
  2. OrdinarySetWithOwnDescriptor(obj, propertyKey, value, receiver, ownDesc)를 반환한다.

10.1.9.2 OrdinarySetWithOwnDescriptor ( obj, propertyKey, value, receiver, ownDesc )

The abstract operation OrdinarySetWithOwnDescriptor takes arguments obj (an Object), propertyKey (a property key), value (an ECMAScript language value), receiver (an ECMAScript language value), and ownDesc (a Property Descriptor or undefined) and returns either a normal completion containing a Boolean or a throw completion. It performs the following steps when called:

  1. ownDescundefined이면, 다음을 수행한다.
    1. parent를 ? obj.[[GetPrototypeOf]]()로 둔다.
    2. parentnull이 아니면, ? parent.[[Set]](propertyKey, value, receiver)를 반환한다.
    3. ownDesc를 PropertyDescriptor { [[Value]]: undefined, [[Writable]]: true, [[Enumerable]]: true, [[Configurable]]: true }로 설정한다.
  2. IsDataDescriptor(ownDesc)가 true이면, 다음을 수행한다.
    1. ownDesc.[[Writable]]false이면, false를 반환한다.
    2. receiver가 Object가 아니면, false를 반환한다.
    3. existingDesc를 ? receiver.[[GetOwnProperty]](propertyKey)로 둔다.
    4. existingDescundefined이면, 다음을 수행한다.
      1. Assert: receiver는 currently property propertyKey를 가지지 않는다.
      2. CreateDataProperty(receiver, propertyKey, value)를 반환한다.
    5. IsAccessorDescriptor(existingDesc)가 true이면, false를 반환한다.
    6. existingDesc.[[Writable]]false이면, false를 반환한다.
    7. valueDesc를 PropertyDescriptor { [[Value]]: value }로 둔다.
    8. receiver.[[DefineOwnProperty]](propertyKey, valueDesc)를 반환한다.
  3. Assert: IsAccessorDescriptor(ownDesc)는 true이다.
  4. setterownDesc.[[Set]]으로 둔다.
  5. setterundefined이면, false를 반환한다.
  6. Call(setter, receiver, « value »)를 수행한다.
  7. true를 반환한다.

10.1.10 [[Delete]] ( propertyKey )

The [[Delete]] internal method of an ordinary object obj takes argument propertyKey (a property key) and returns either a normal completion containing a Boolean or a throw completion. It performs the following steps when called:

  1. OrdinaryDelete(obj, propertyKey)를 반환한다.

10.1.10.1 OrdinaryDelete ( obj, propertyKey )

The abstract operation OrdinaryDelete takes arguments obj (an Object) and propertyKey (a property key) and returns either a normal completion containing a Boolean or a throw completion. It performs the following steps when called:

  1. propertyDesc를 ? obj.[[GetOwnProperty]](propertyKey)로 둔다.
  2. propertyDescundefined이면, true를 반환한다.
  3. propertyDesc.[[Configurable]]true이면, 다음을 수행한다.
    1. obj에서 name이 propertyKey인 own property를 remove한다.
    2. true를 반환한다.
  4. false를 반환한다.

10.1.11 [[OwnPropertyKeys]] ( )

The [[OwnPropertyKeys]] internal method of an ordinary object obj takes no arguments and returns a normal completion containing a List of property keys. It performs the following steps when called:

  1. OrdinaryOwnPropertyKeys(obj)를 반환한다.

10.1.11.1 OrdinaryOwnPropertyKeys ( obj )

The abstract operation OrdinaryOwnPropertyKeys takes argument obj (an Object) and returns a List of property keys. It performs the following steps when called:

  1. keys를 새 empty List로 둔다.
  2. obj의 각 own property key propertyKeypropertyKeyarray index인 것에 대해, ascending numeric index order로 다음을 수행한다.
    1. propertyKeykeys에 append한다.
  3. obj의 각 own property key propertyKeypropertyKey가 String이고 propertyKeyarray index가 아닌 것에 대해, property creation의 ascending chronological order로 다음을 수행한다.
    1. propertyKeykeys에 append한다.
  4. obj의 각 own property key propertyKeypropertyKey가 Symbol인 것에 대해, property creation의 ascending chronological order로 다음을 수행한다.
    1. propertyKeykeys에 append한다.
  5. keys를 반환한다.

10.1.12 OrdinaryObjectCreate ( proto [ , additionalInternalSlotsList ] )

The abstract operation OrdinaryObjectCreate takes argument proto (an Object or null) and optional argument additionalInternalSlotsList (a List of names of internal slots) and returns an Object. 새 ordinary object의 runtime creation을 specify하는 데 사용됩니다. additionalInternalSlotsList[[Prototype]][[Extensible]]을 넘어 object의 part로 define되어야 하는 additional internal slot의 name을 contain합니다. additionalInternalSlotsList가 provided되지 않으면, 새 empty List가 사용됩니다. It performs the following steps when called:

  1. internalSlotsList를 « [[Prototype]], [[Extensible]] »로 둔다.
  2. additionalInternalSlotsList가 present하면, internalSlotsListinternalSlotsListadditionalInternalSlotsListlist-concatenation으로 설정한다.
  3. objMakeBasicObject(internalSlotsList)로 둔다.
  4. obj.[[Prototype]]proto로 설정한다.
  5. obj를 반환한다.
Note

OrdinaryObjectCreate는 MakeBasicObject를 call하는 것 이상의 일을 거의 하지 않지만, 그 use는 exotic object가 아니라 ordinary object를 create하려는 intention을 communicate합니다. 따라서 이 명세 안에서는 result가 non-ordinary가 되도록 object의 internal method를 subsequently modify하는 algorithm에 의해 called되지 않습니다. exotic object를 create하는 operation은 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가 존재하면 그 property에서 retrieved된 [[Prototype]] value를 가지는 ordinary object를 create합니다. 그렇지 않으면 intrinsicDefaultProto가 naming하는 intrinsic이 [[Prototype]]에 사용됩니다. internalSlotsList는 object의 part로 define되어야 하는 additional internal slot의 name을 contain합니다. internalSlotsList가 provided되지 않으면, 새 empty List가 사용됩니다. It performs the following steps when called:

  1. Assert: intrinsicDefaultProto는 이 명세의 intrinsic object name이다. corresponding object는 object의 [[Prototype]] value로 사용되도록 intended된 intrinsic이어야 한다.
  2. proto를 ? GetPrototypeFromConstructor(ctor, intrinsicDefaultProto)로 둔다.
  3. internalSlotsList가 present하면, slotsinternalSlotsList로 둔다.
  4. 그렇지 않으면, slots를 새 empty List로 둔다.
  5. OrdinaryObjectCreate(proto, slots)를 반환한다.

10.1.14 GetPrototypeFromConstructor ( ctor, intrinsicDefaultProto )

The abstract operation GetPrototypeFromConstructor takes arguments ctor (a function object) and intrinsicDefaultProto (a String) and returns either a normal completion containing an Object or a throw completion. specific constructor에 corresponding하는 object를 create하는 데 사용해야 하는 [[Prototype]] value를 determine합니다. value는 constructor"prototype" property가 존재하면 그 property에서 retrieved됩니다. 그렇지 않으면 intrinsicDefaultProto가 naming하는 intrinsic이 [[Prototype]]에 사용됩니다. It performs the following steps when called:

  1. Assert: intrinsicDefaultProto는 이 명세의 intrinsic object name이다. corresponding object는 object의 [[Prototype]] value로 사용되도록 intended된 intrinsic이어야 한다.
  2. proto를 ? Get(ctor, "prototype")로 둔다.
  3. proto가 Object가 아니면, 다음을 수행한다.
    1. realm을 ? GetFunctionRealm(ctor)으로 둔다.
    2. protorealmintrinsicDefaultProto라는 name의 intrinsic object로 설정한다.
  4. proto를 반환한다.
Note

ctor[[Prototype]] value를 supply하지 않으면, 사용되는 default value는 running execution context가 아니라 ctor function의 realm에서 obtained됩니다.

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이고 given internal slot을 가지지 않는 한 exception을 throw합니다. It performs the following steps when called:

  1. obj가 Object가 아니면, TypeError exception을 throw한다.
  2. objinternalSlot internal slot을 가지지 않으면, TypeError exception을 throw한다.
  3. unused를 반환한다.

10.2 ECMAScript Function Objects

ECMAScript function object는 lexical environment 위에 closed된 parameterized ECMAScript code를 encapsulate하고 그 code의 dynamic evaluation을 support합니다. ECMAScript function objectordinary object이며 다른 ordinary object와 같은 internal slot과 같은 internal method를 가집니다. ECMAScript function object의 code는 strict mode code(11.2.2)이거나 non-strict code일 수 있습니다. code가 strict mode code인 ECMAScript function objectstrict function이라고 합니다. code가 strict mode code가 아닌 것은 non-strict function이라고 합니다.

[[Extensible]][[Prototype]] 외에도, ECMAScript function objectTable 26에 listed된 internal slot도 가집니다.

Table 26: Internal Slots of ECMAScript Function Objects
Internal Slot Type Description
[[Environment]] an Environment Record function이 closed over된 Environment Record입니다. function의 code를 evaluating할 때 outer environment로 사용됩니다.
[[PrivateEnvironment]] a PrivateEnvironment Record or null function이 closed over된 Private Name에 대한 PrivateEnvironment Record입니다. 이 function이 syntactically class 안에 contained되어 있지 않으면 null입니다. function의 code를 evaluating할 때 inner class를 위한 outer PrivateEnvironment로 사용됩니다.
[[FormalParameters]] a Parse Node function의 formal parameter list를 define하는 source text의 root parse node입니다.
[[ECMAScriptCode]] a Parse Node function의 body를 define하는 source text의 root parse node입니다.
[[ConstructorKind]] base or derived function이 derived class constructor인지 여부입니다.
[[Realm]] a Realm Record function이 created된 realm이며, function을 evaluating할 때 accessed되는 intrinsic object를 제공합니다.
[[ScriptOrModule]] a Script Record or a Module Record function이 created된 script 또는 module입니다.
[[ThisMode]] lexical, strict, or global function의 formal parameter와 code body 안에서 this reference가 어떻게 interpreted되는지 define합니다. lexicalthis가 lexically enclosing function의 this value를 refer함을 의미합니다. strictthis value가 function invocation에 의해 provided된 그대로 사용됨을 의미합니다. globalundefined 또는 nullthis value가 global object에 대한 reference로 interpreted되고, 그 밖의 this value는 먼저 ToObject에 passed됨을 의미합니다.
[[Strict]] a Boolean 이것이 strict function이면 true, non-strict function이면 false입니다.
[[HomeObject]] an Object or undefined function이 super를 사용하면, 이는 그 [[GetPrototypeOf]]super property lookup이 시작되는 object를 제공하는 object입니다.
[[SourceText]] a sequence of Unicode code points function을 define하는 source text입니다.
[[Fields]] a List of ClassFieldDefinition Records function이 class이면, 이는 class의 non-static field와 corresponding initializer를 represent하는 Record의 list입니다.
[[PrivateMethods]] a List of PrivateElements function이 class이면, 이는 class의 non-static private method와 accessor를 represent하는 list입니다.
[[ClassFieldInitializerName]] a String, a Symbol, a Private Name, or empty function이 class field의 initializer로 created되면, field의 NamedEvaluation에 사용할 name입니다. 그렇지 않으면 empty입니다.
[[IsClassConstructor]] a Boolean function이 class constructor인지 여부를 나타냅니다. (true이면, function의 [[Call]]을 invoking하는 즉시 TypeError exception을 throw합니다.)

모든 ECMAScript function object는 여기서 정의된 [[Call]] internal method를 가집니다. 또한 constructor이기도 한 ECMAScript function은 [[Construct]] internal method를 가집니다.

10.2.1 [[Call]] ( thisArg, argList )

The [[Call]] internal method of an ECMAScript function object func takes arguments thisArg (an ECMAScript language value) and argList (a List of ECMAScript language values) and returns either a normal completion containing an ECMAScript language value or a throw completion. It performs the following steps when called:

  1. callerContextrunning execution context로 둔다.
  2. calleeContextPrepareForOrdinaryCall(func, undefined)로 둔다.
  3. Assert: calleeContext는 이제 running execution context이다.
  4. func.[[IsClassConstructor]]true이면, 다음을 수행한다.
    1. error를 newly created TypeError object로 둔다.
    2. NOTE: errorfunc의 associated Realm Record를 가진 calleeContext 안에서 created됩니다.
    3. execution context stack에서 calleeContext를 remove하고 callerContextrunning execution context로 restore한다.
    4. error를 throw한다.
  5. OrdinaryCallBindThis(func, calleeContext, thisArg)를 수행한다.
  6. resultCompletion(OrdinaryCallEvaluateBody(func, argList))로 둔다.
  7. execution context stack에서 calleeContext를 remove하고 callerContextrunning execution context로 restore한다.
  8. resultreturn completion이면, result.[[Value]]를 반환한다.
  9. Assert: resultthrow completion이다.
  10. result를 반환한다.
Note

step 7에서 calleeContextexecution context stack에서 removed될 때, accessible Generator에 의해 later resumption을 위해 suspended되고 retained되어 있다면 destroyed되어서는 안 됩니다.

10.2.1.1 PrepareForOrdinaryCall ( func, newTarget )

The abstract operation PrepareForOrdinaryCall takes arguments func (an ECMAScript function object) and newTarget (an Object or undefined) and returns an execution context. It performs the following steps when called:

  1. callerContextrunning execution context로 둔다.
  2. calleeContext를 새 ECMAScript code execution context로 둔다.
  3. calleeContext의 Function을 func로 설정한다.
  4. calleeRealmfunc.[[Realm]]으로 둔다.
  5. calleeContextRealmcalleeRealm으로 설정한다.
  6. calleeContext의 ScriptOrModule을 func.[[ScriptOrModule]]으로 설정한다.
  7. localEnvNewFunctionEnvironment(func, newTarget)으로 둔다.
  8. calleeContext의 LexicalEnvironment를 localEnv로 설정한다.
  9. calleeContext의 VariableEnvironment를 localEnv로 설정한다.
  10. calleeContext의 PrivateEnvironment를 func.[[PrivateEnvironment]]로 설정한다.
  11. callerContext가 already suspended가 아니면, callerContext를 suspend한다.
  12. calleeContextexecution context stack 위로 push한다; calleeContext는 이제 running execution context이다.
  13. NOTE: 이 point 이후 produced되는 모든 exception object는 calleeRealm과 associated됩니다.
  14. calleeContext를 반환한다.

10.2.1.2 OrdinaryCallBindThis ( func, calleeContext, thisArg )

The abstract operation OrdinaryCallBindThis takes arguments func (an ECMAScript function object), calleeContext (an execution context), and thisArg (an ECMAScript language value) and returns unused. It performs the following steps when called:

  1. thisModefunc.[[ThisMode]]로 둔다.
  2. thisModelexical이면, unused를 반환한다.
  3. calleeRealmfunc.[[Realm]]으로 둔다.
  4. localEnvcalleeContext의 LexicalEnvironment로 둔다.
  5. thisModestrict이면, 다음을 수행한다.
    1. thisValuethisArg로 둔다.
  6. 그렇지 않으면,
    1. thisArgundefined 또는 null이면, 다음을 수행한다.
      1. globalEnvcalleeRealm.[[GlobalEnv]]로 둔다.
      2. Assert: globalEnvGlobal Environment Record이다.
      3. thisValueglobalEnv.[[GlobalThisValue]]로 둔다.
    2. 그렇지 않으면,
      1. thisValue를 ! ToObject(thisArg)로 둔다.
      2. NOTE: ToObjectcalleeRealm을 사용하여 wrapper object를 produce합니다.
  7. Assert: localEnvFunction Environment Record이다.
  8. Assert: localEnv.[[ThisBindingStatus]]initialized가 아니므로 다음 step은 결코 abrupt completion을 반환하지 않는다.
  9. BindThisValue(localEnv, thisValue)를 수행한다.
  10. unused를 반환한다.

10.2.1.3 Runtime Semantics: EvaluateBody

The syntax-directed operation EvaluateBody takes arguments func (an ECMAScript function object) and argList (a List of ECMAScript language values) and returns a return completion or a throw completion. It is defined piecewise over the following productions:

FunctionBody : FunctionStatementList
  1. arguments funcargList를 가진 FunctionBodyEvaluateFunctionBody를 ? 반환한다.
ConciseBody : ExpressionBody
  1. arguments funcargList를 가진 ConciseBodyEvaluateConciseBody를 ? 반환한다.
GeneratorBody : FunctionBody
  1. arguments funcargList를 가진 GeneratorBodyEvaluateGeneratorBody를 ? 반환한다.
AsyncGeneratorBody : FunctionBody
  1. arguments funcargList를 가진 AsyncGeneratorBodyEvaluateAsyncGeneratorBody를 ? 반환한다.
AsyncFunctionBody : FunctionBody
  1. arguments funcargList를 가진 AsyncFunctionBodyEvaluateAsyncFunctionBody를 ? 반환한다.
AsyncConciseBody : ExpressionBody
  1. arguments funcargList를 가진 AsyncConciseBodyEvaluateAsyncConciseBody를 ? 반환한다.
Initializer : = AssignmentExpression
  1. Assert: argList는 empty이다.
  2. Assert: func.[[ClassFieldInitializerName]]empty가 아니다.
  3. IsAnonymousFunctionDefinition(AssignmentExpression)이 true이면, 다음을 수행한다.
    1. value를 argument func.[[ClassFieldInitializerName]]을 가진 InitializerNamedEvaluation으로 ? 둔다.
  4. 그렇지 않으면,
    1. rhsAssignmentExpressionEvaluation으로 ? 둔다.
    2. value를 ? GetValue(rhs)로 둔다.
  5. ReturnCompletion(value)를 반환한다.
Note

field initializer가 function boundary를 constitute하더라도, FunctionDeclarationInstantiation을 calling하는 것은 observable effect가 없으므로 omitted됩니다.

ClassStaticBlockBody : ClassStaticBlockStatementList
  1. Assert: argList는 empty이다.
  2. argument func를 가진 ClassStaticBlockBodyEvaluateClassStaticBlockBody를 ? 반환한다.

10.2.1.4 OrdinaryCallEvaluateBody ( func, argList )

The abstract operation OrdinaryCallEvaluateBody takes arguments func (an ECMAScript function object) and argList (a List of ECMAScript language values) and returns a return completion or a throw completion. It performs the following steps when called:

  1. arguments funcargList를 가진 func.[[ECMAScriptCode]]EvaluateBody를 ? 반환한다.

10.2.2 [[Construct]] ( argList, newTarget )

The [[Construct]] internal method of an ECMAScript function object func takes arguments argList (a List of ECMAScript language values) and newTarget (a constructor) and returns either a normal completion containing an Object or a throw completion. It performs the following steps when called:

  1. callerContextrunning execution context로 둔다.
  2. kindfunc.[[ConstructorKind]]로 둔다.
  3. kindbase이면, 다음을 수행한다.
    1. thisArg를 ? OrdinaryCreateFromConstructor(newTarget, "%Object.prototype%")로 둔다.
  4. calleeContextPrepareForOrdinaryCall(func, newTarget)으로 둔다.
  5. Assert: calleeContext는 이제 running execution context이다.
  6. kindbase이면, 다음을 수행한다.
    1. OrdinaryCallBindThis(func, calleeContext, thisArg)를 수행한다.
    2. initializeResultCompletion(InitializeInstanceElements(thisArg, func))로 둔다.
    3. initializeResultabrupt completion이면, 다음을 수행한다.
      1. execution context stack에서 calleeContext를 remove하고 callerContextrunning execution context로 restore한다.
      2. initializeResult를 반환한다.
  7. ctorEnvcalleeContext의 LexicalEnvironment로 둔다.
  8. resultCompletion(OrdinaryCallEvaluateBody(func, argList))로 둔다.
  9. execution context stack에서 calleeContext를 remove하고 callerContextrunning execution context로 restore한다.
  10. resultthrow completion이면, 다음을 수행한다.
    1. result를 반환한다.
  11. Assert: resultreturn completion이다.
  12. result.[[Value]]가 Object이면, result.[[Value]]를 반환한다.
  13. kindbase이면, thisArg를 반환한다.
  14. result.[[Value]]undefined가 아니면, TypeError exception을 throw한다.
  15. thisBinding을 ? ctorEnv.GetThisBinding()으로 둔다.
  16. Assert: thisBinding은 Object이다.
  17. thisBinding을 반환한다.

10.2.3 OrdinaryFunctionCreate ( proto, sourceText, paramList, body, thisMode, envRecord, privateEnv )

The abstract operation OrdinaryFunctionCreate takes arguments proto (an Object), sourceText (a sequence of Unicode code points), paramList (a Parse Node), body (a Parse Node), thisMode (lexical-this or non-lexical-this), envRecord (an Environment Record), and privateEnv (a PrivateEnvironment Record or null) and returns an ECMAScript function object. default [[Call]] internal method를 가지며 [[Construct]] internal method는 없는 새 function의 runtime creation을 specify하는 데 사용됩니다(단, MakeConstructor 같은 operation에 의해 subsequently added될 수 있습니다). sourceText는 created될 function의 syntactic definition의 source text입니다. It performs the following steps when called:

  1. internalSlotsListTable 26에 listed된 internal slot으로 둔다.
  2. funcOrdinaryObjectCreate(proto, internalSlotsList)로 둔다.
  3. func.[[Call]]10.2.1에 specified된 definition으로 설정한다.
  4. func.[[SourceText]]sourceText로 설정한다.
  5. func.[[FormalParameters]]paramList로 설정한다.
  6. func.[[ECMAScriptCode]]body로 설정한다.
  7. strictIsStrict(body)로 둔다.
  8. func.[[Strict]]strict로 설정한다.
  9. thisModelexical-this이면, func.[[ThisMode]]lexical로 설정한다.
  10. 그렇지 않고 stricttrue이면, func.[[ThisMode]]strict로 설정한다.
  11. 그렇지 않으면, func.[[ThisMode]]global로 설정한다.
  12. func.[[IsClassConstructor]]false로 설정한다.
  13. func.[[Environment]]envRecord로 설정한다.
  14. func.[[PrivateEnvironment]]privateEnv로 설정한다.
  15. func.[[ScriptOrModule]]GetActiveScriptOrModule()로 설정한다.
  16. func.[[Realm]]을 current Realm Record로 설정한다.
  17. func.[[HomeObject]]undefined로 설정한다.
  18. func.[[Fields]]를 새 empty List로 설정한다.
  19. func.[[PrivateMethods]]를 새 empty List로 설정한다.
  20. func.[[ClassFieldInitializerName]]empty로 설정한다.
  21. lengthparamListExpectedArgumentCount로 둔다.
  22. SetFunctionLength(func, length)를 수행한다.
  23. func를 반환한다.

10.2.4 AddRestrictedFunctionProperties ( func, realm )

The abstract operation AddRestrictedFunctionProperties takes arguments func (a function object) and realm (a Realm Record) and returns unused. It performs the following steps when called:

  1. Assert: realm.[[Intrinsics]].[[%ThrowTypeError%]]는 존재하고 initialized되어 있다.
  2. throwerrealm.[[Intrinsics]].[[%ThrowTypeError%]]로 둔다.
  3. DefinePropertyOrThrow(func, "caller", PropertyDescriptor { [[Get]]: thrower, [[Set]]: thrower, [[Enumerable]]: false, [[Configurable]]: true })를 수행한다.
  4. DefinePropertyOrThrow(func, "arguments", PropertyDescriptor { [[Get]]: thrower, [[Set]]: thrower, [[Enumerable]]: false, [[Configurable]]: true })를 수행한다.
  5. unused를 반환한다.

10.2.4.1 %ThrowTypeError% ( )

이 function은 %ThrowTypeError% intrinsic object입니다.

이는 각 realm마다 한 번 정의되는 anonymous built-in function object입니다.

called될 때 다음 step을 수행합니다:

  1. TypeError exception을 throw한다.

이 function의 [[Extensible]] internal slot의 value는 false입니다.

이 function의 "length" property는 attribute { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }를 가집니다.

이 function의 "name" property는 attribute { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }를 가집니다.

10.2.5 MakeConstructor ( func [ , writableProto [ , proto ] ] )

The abstract operation MakeConstructor takes argument func (an ECMAScript function object or a built-in function object) and optional arguments writableProto (a Boolean) and proto (an Object) and returns unused. funcconstructor로 convert합니다. It performs the following steps when called:

  1. func가 ECMAScript function object이면, 다음을 수행한다.
    1. Assert: IsConstructor(func)는 false이다.
    2. Assert: func"prototype" own property를 가지지 않는 extensible object이다.
    3. func.[[Construct]]10.2.2에 specified된 definition으로 설정한다.
  2. 그렇지 않으면,
    1. func.[[Construct]]10.3.2에 specified된 definition으로 설정한다.
  3. func.[[ConstructorKind]]base로 설정한다.
  4. writableProto가 present하지 않으면, writablePrototrue로 설정한다.
  5. proto가 present하지 않으면, 다음을 수행한다.
    1. protoOrdinaryObjectCreate(%Object.prototype%)로 설정한다.
    2. DefinePropertyOrThrow(proto, "constructor", PropertyDescriptor { [[Value]]: func, [[Writable]]: writableProto, [[Enumerable]]: false, [[Configurable]]: true })를 수행한다.
  6. DefinePropertyOrThrow(func, "prototype", PropertyDescriptor { [[Value]]: proto, [[Writable]]: writableProto, [[Enumerable]]: false, [[Configurable]]: false })를 수행한다.
  7. unused를 반환한다.

10.2.6 MakeClassConstructor ( func )

The abstract operation MakeClassConstructor takes argument func (an ECMAScript function object) and returns unused. It performs the following steps when called:

  1. Assert: func.[[IsClassConstructor]]false이다.
  2. func.[[IsClassConstructor]]true로 설정한다.
  3. unused를 반환한다.

10.2.7 MakeMethod ( func, homeObj )

The abstract operation MakeMethod takes arguments func (an ECMAScript function object) and homeObj (an Object) and returns unused. func를 method로 configure합니다. It performs the following steps when called:

  1. Assert: homeObjordinary object이다.
  2. func.[[HomeObject]]homeObj로 설정한다.
  3. unused를 반환한다.

10.2.8 DefineMethodProperty ( homeObj, name, closure, enumerable )

The abstract operation DefineMethodProperty takes arguments homeObj (an Object), name (a property key or Private Name), closure (a function object), and enumerable (a Boolean) and returns either a normal completion containing either a PrivateElement or unused, or an abrupt completion. It performs the following steps when called:

  1. Assert: homeObj는 ordinary, extensible object이다.
  2. namePrivate Name이면, PrivateElement { [[Key]]: name, [[Kind]]: method, [[Value]]: closure }를 반환한다.
  3. propertyDesc를 PropertyDescriptor { [[Value]]: closure, [[Writable]]: true, [[Enumerable]]: enumerable, [[Configurable]]: true }로 둔다.
  4. DefinePropertyOrThrow(homeObj, name, propertyDesc)를 수행한다.
  5. NOTE: DefinePropertyOrThrowname"prototype"인 class static method를 define하려고 attempt할 때만 abrupt completion을 반환합니다.
  6. unused를 반환한다.

10.2.9 SetFunctionName ( func, name [ , prefix ] )

The abstract operation SetFunctionName takes arguments func (a function object) and name (a property key or Private Name) and optional argument prefix (a String) and returns unused. func"name" property를 add합니다. It performs the following steps when called:

  1. Assert: func"name" own property를 가지지 않는 extensible object이다.
  2. name이 Symbol이면, 다음을 수행한다.
    1. descriptionname.[[Description]]으로 둔다.
    2. descriptionundefined이면, name을 empty String으로 설정한다.
    3. 그렇지 않으면, name"[", description, "]"string-concatenation으로 설정한다.
  3. 그렇지 않고 namePrivate Name이면, 다음을 수행한다.
    1. namename.[[Description]]으로 설정한다.
  4. func[[InitialName]] internal slot을 가지면, 다음을 수행한다.
    1. func.[[InitialName]]name으로 설정한다.
  5. prefix가 present하면, 다음을 수행한다.
    1. prefixedNameprefix, code unit 0x0020 (SPACE), namestring-concatenation으로 둔다.
    2. func[[InitialName]] internal slot을 가지면, 다음을 수행한다.
      1. NOTE: 다음 step의 choice는 이 Abstract Operation이 invoked될 때마다 independently made됩니다.
      2. func.[[InitialName]]name 또는 prefixedNameimplementation-defined choice로 설정한다.
    3. nameprefixedName으로 설정한다.
  6. DefinePropertyOrThrow(func, "name", PropertyDescriptor { [[Value]]: name, [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true })를 수행한다.
  7. unused를 반환한다.

10.2.10 SetFunctionLength ( func, length )

The abstract operation SetFunctionLength takes arguments func (a function object) and length (a non-negative integer or +∞) and returns unused. func"length" property를 add합니다. It performs the following steps when called:

  1. Assert: func"length" own property를 가지지 않는 extensible object이다.
  2. DefinePropertyOrThrow(func, "length", PropertyDescriptor { [[Value]]: 𝔽(length), [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true })를 수행한다.
  3. unused를 반환한다.

10.2.11 FunctionDeclarationInstantiation ( func, argList )

The abstract operation FunctionDeclarationInstantiation takes arguments func (an ECMAScript function object) and argList (a List of ECMAScript language values) and returns either a normal completion containing unused or a throw completion. funcexecution context가 established되고 있는 대상 function object입니다.

Note

ECMAScript function을 evaluating하기 위해 execution context가 established될 때 새 Function Environment Record가 created되고 각 formal parameter에 대한 binding이 그 Environment Record 안에 instantiated됩니다. function body 안의 각 declaration도 instantiated됩니다. function의 formal parameter가 default value initializer를 포함하지 않으면 body declaration은 parameter와 같은 Environment Record 안에 instantiated됩니다. default value parameter initializer가 존재하면 body declaration을 위해 두 번째 Environment Record가 created됩니다. Formal parameter와 function은 FunctionDeclarationInstantiation의 일부로 initialized됩니다. 다른 모든 binding은 function body의 evaluation 중에 initialized됩니다.

called될 때 다음 step을 수행합니다:

  1. calleeContext를 실행 중인 실행 컨텍스트라고 하자.
  2. codefunc.[[ECMAScriptCode]]라고 하자.
  3. strictfunc.[[Strict]]라고 하자.
  4. formalsfunc.[[FormalParameters]]라고 하자.
  5. paramNamesformalsBoundNames라고 하자.
  6. paramNames에 중복 항목이 있으면 hasDuplicatestrue라고 하고, 그렇지 않으면 hasDuplicatesfalse라고 하자.
  7. simpleParamListformalsIsSimpleParameterList라고 하자.
  8. hasParamExprsformalsContainsExpression이라고 하자.
  9. variableNamescodeVarDeclaredNames라고 하자.
  10. variableDeclscodeVarScopedDeclarations라고 하자.
  11. lexicalNamescodeLexicallyDeclaredNames라고 하자.
  12. funcNames를 새로운 빈 List라고 하자.
  13. funcsToInitialize를 새로운 빈 List라고 하자.
  14. variableDecls의 각 요소 variableDecl에 대해, List의 역순으로 다음을 수행한다.
    1. variableDeclVariableDeclarationForBindingBindingIdentifier도 아니면,
      1. Assert: variableDeclFunctionDeclaration, GeneratorDeclaration, AsyncFunctionDeclaration 또는 AsyncGeneratorDeclaration 중 하나이다.
      2. funcNamevariableDeclBoundNames의 유일한 요소라고 하자.
      3. funcNamesfuncName을 포함하지 않으면,
        1. funcNamefuncNames의 첫 번째 요소로 삽입한다.
        2. NOTE: 같은 이름에 대해 여러 함수 선언이 있으면, 마지막 선언이 사용된다.
        3. variableDeclfuncsToInitialize의 첫 번째 요소로 삽입한다.
  15. argumentsObjNeededtrue라고 하자.
  16. func.[[ThisMode]]lexical이면,
    1. NOTE: 화살표 함수는 arguments 객체를 갖지 않는다.
    2. argumentsObjNeededfalse로 설정한다.
  17. 그렇지 않고 paramNames"arguments"를 포함하면,
    1. argumentsObjNeededfalse로 설정한다.
  18. 그렇지 않고 hasParamExprsfalse이면,
    1. funcNames"arguments"를 포함하거나 lexicalNames"arguments"를 포함하면,
      1. argumentsObjNeededfalse로 설정한다.
  19. stricttrue이거나 hasParamExprsfalse이면,
    1. NOTE: 매개변수에는 단일 Environment Record만 필요하다. strict mode 코드의 eval 호출은 eval 밖에서 보이는 새 바인딩을 만들 수 없기 때문이다.
    2. envRecordcalleeContext의 LexicalEnvironment라고 하자.
  20. 그렇지 않으면,
    1. NOTE: formal parameter list 안의 direct eval 호출로 생성된 바인딩이 매개변수가 선언된 환경 밖에 있도록 보장하기 위해 별도의 Environment Record가 필요하다.
    2. calleeEnvcalleeContext의 LexicalEnvironment라고 하자.
    3. envRecordNewDeclarativeEnvironment(calleeEnv)라고 하자.
    4. Assert: calleeContext의 VariableEnvironment와 calleeEnv는 같은 Environment Record이다.
    5. calleeContext의 LexicalEnvironment를 envRecord로 설정한다.
  21. paramNames의 각 String paramName에 대해 다음을 수행한다.
    1. alreadyDeclared를 ! envRecord.HasBinding(paramName)이라고 하자.
    2. NOTE: Early errors는 중복 매개변수 이름이 기본 매개변수 값이나 rest 매개변수가 없는 non-strict 함수에서만 발생할 수 있음을 보장한다.
    3. alreadyDeclaredfalse이면,
      1. envRecord.CreateMutableBinding(paramName, false)를 수행한다.
      2. hasDuplicatestrue이면,
        1. envRecord.InitializeBinding(paramName, undefined)를 수행한다.
  22. argumentsObjNeededtrue이면,
    1. stricttrue이거나 simpleParamListfalse이면,
      1. argumentsObjCreateUnmappedArgumentsObject(argList)라고 하자.
    2. 그렇지 않으면,
      1. NOTE: mapped argument object는 rest 매개변수, 매개변수 기본값 초기화자, 구조 분해 매개변수가 없는 non-strict 함수에만 제공된다.
      2. argumentsObjCreateMappedArgumentsObject(func, formals, argList, envRecord)라고 하자.
    3. stricttrue이면,
      1. envRecord.CreateImmutableBinding("arguments", false)를 수행한다.
      2. NOTE: strict mode 코드에서는 Early Errors가 이 바인딩에 할당하려는 시도를 방지하므로, 그 가변성은 관찰 가능하지 않다.
    4. 그렇지 않으면,
      1. envRecord.CreateMutableBinding("arguments", false)를 수행한다.
    5. envRecord.InitializeBinding("arguments", argumentsObj)를 수행한다.
    6. paramBindingsparamNames와 « "arguments" »의 list-concatenation이라고 하자.
  23. 그렇지 않으면,
    1. paramBindingsparamNames라고 하자.
  24. iteratorRecordCreateListIteratorRecord(argList)라고 하자.
  25. hasDuplicatestrue이면,
    1. usedEnvundefined라고 하자.
  26. 그렇지 않으면,
    1. usedEnvenvRecord라고 하자.
  27. NOTE: 다음 단계는 ReturnCompletion을 반환할 수 없다. 그러한 completion이 expression 위치에서 발생할 수 있는 유일한 방법은 YieldExpression 사용뿐인데, 이는 15.5.115.6.1의 Early Error 규칙에 의해 parameter list에서 금지되기 때문이다.
  28. formalsIteratorBindingInitialization을 인수 iteratorRecordusedEnv와 함께 수행한다. 완료가 갑작스러운 완료이면 전파한다.
  29. hasParamExprsfalse이면,
    1. NOTE: 매개변수와 최상위 vars에는 단일 Environment Record만 필요하다.
    2. instantiatedVariableNamesList paramBindings의 복사본이라고 하자.
    3. variableNames의 각 요소 name에 대해 다음을 수행한다.
      1. instantiatedVariableNamesname을 포함하지 않으면,
        1. nameinstantiatedVariableNames에 추가한다.
        2. envRecord.CreateMutableBinding(name, false)를 수행한다.
        3. envRecord.InitializeBinding(name, undefined)를 수행한다.
    4. variableEnvenvRecord라고 하자.
  30. 그렇지 않으면,
    1. NOTE: formal parameter list 안의 표현식으로 생성된 클로저가 함수 본문의 선언을 볼 수 없도록 보장하기 위해 별도의 Environment Record가 필요하다.
    2. variableEnvNewDeclarativeEnvironment(envRecord)라고 하자.
    3. calleeContext의 VariableEnvironment를 variableEnv로 설정한다.
    4. instantiatedVariableNames를 새로운 빈 List라고 하자.
    5. variableNames의 각 요소 name에 대해 다음을 수행한다.
      1. instantiatedVariableNamesname을 포함하지 않으면,
        1. nameinstantiatedVariableNames에 추가한다.
        2. variableEnv.CreateMutableBinding(name, false)를 수행한다.
        3. paramBindingsname을 포함하지 않거나 funcNamesname을 포함하면,
          1. initialValueundefined라고 하자.
        4. 그렇지 않으면,
          1. initialValue를 ! envRecord.GetBindingValue(name, false)라고 하자.
        5. variableEnv.InitializeBinding(name, initialValue)를 수행한다.
        6. NOTE: formal parameter와 같은 이름의 var는 처음에 해당 초기화된 매개변수와 같은 값을 갖는다.
  31. stricttrue이면,
    1. lexicalEnvvariableEnv라고 하자.
  32. 그렇지 않으면,
    1. host가 web browser이거나 그 밖에 Block-Level Function Declarations Web Legacy Compatibility Semantics를 지원하면,
      1. code Contains xtrueBlock, CaseClause 또는 DefaultClause xStatementList에 직접 포함된 각 FunctionDeclaration funcDecl에 대해 다음을 수행한다.
        1. funcNamefuncDeclBindingIdentifierStringValue라고 하자.
        2. FunctionDeclaration funcDeclfuncNameBindingIdentifier로 갖는 VariableStatement로 대체해도 func에 대한 Early Errors가 생성되지 않고 paramNamesfuncName을 포함하지 않으면,
          1. NOTE: funcName에 대한 var 바인딩은 그것이 VarDeclaredName, formal parameter의 이름 또는 다른 FunctionDeclaration이 아닐 때에만 여기서 인스턴스화된다.
          2. instantiatedVariableNamesfuncName을 포함하지 않고 funcName"arguments"가 아니면,
            1. variableEnv.CreateMutableBinding(funcName, false)를 수행한다.
            2. variableEnv.InitializeBinding(funcName, undefined)를 수행한다.
            3. funcNameinstantiatedVariableNames에 추가한다.
          3. FunctionDeclaration funcDecl이 평가될 때, 15.2.6에 제공된 FunctionDeclaration Evaluation 알고리즘 대신 다음 단계를 수행한다.
            1. funcEnv를 실행 중인 실행 컨텍스트의 VariableEnvironment라고 하자.
            2. blockEnv를 실행 중인 실행 컨텍스트의 LexicalEnvironment라고 하자.
            3. funcObj를 ! blockEnv.GetBindingValue(funcName, false)라고 하자.
            4. funcEnv.SetMutableBinding(funcName, funcObj, false)를 수행한다.
            5. unused를 반환한다.
    2. lexicalEnvNewDeclarativeEnvironment(variableEnv)라고 하자.
    3. NOTE: non-strict 함수는 최상위 lexical 선언에 대해 별도의 Environment Record를 사용하므로, direct eval은 eval 코드가 도입한 var scoped 선언이 기존의 최상위 lexically scoped 선언과 충돌하는지 판단할 수 있다. strict 함수에는 이것이 필요하지 않다. strict direct eval은 항상 모든 선언을 새로운 Environment Record에 두기 때문이다.
  33. calleeContext의 LexicalEnvironment를 lexicalEnv로 설정한다.
  34. lexicalDeclscodeLexicallyScopedDeclarations라고 하자.
  35. lexicalDecls의 각 요소 lexicalDecl에 대해 다음을 수행한다.
    1. NOTE: lexically declared name은 function/generator 선언, formal parameter 또는 var 이름과 같을 수 없다. Lexically declared name은 여기서 인스턴스화만 되고 초기화되지는 않는다.
    2. lexicalDeclBoundNames의 각 요소 name에 대해 다음을 수행한다.
      1. lexicalDeclIsConstantDeclarationtrue이면,
        1. lexicalEnv.CreateImmutableBinding(name, true)를 수행한다.
      2. 그렇지 않으면,
        1. lexicalEnv.CreateMutableBinding(name, false)를 수행한다.
  36. privateEnvcalleeContext의 PrivateEnvironment라고 하자.
  37. funcsToInitialize의 각 Parse Node funcDecl에 대해 다음을 수행한다.
    1. funcNamefuncDeclBoundNames의 유일한 요소라고 하자.
    2. funcObjfuncDeclInstantiateFunctionObject에 인수 lexicalEnvprivateEnv를 전달한 결과라고 하자.
    3. variableEnv.SetMutableBinding(funcName, funcObj, false)를 수행한다.
  38. unused를 반환한다.

10.3 Built-in Function Objects

built-in function objectordinary object입니다; 이는 10.1에 set out된 ordinary object에 대한 requirement를 satisfy해야 합니다.

모든 ordinary object에 required되는 internal slot(10.1 참조) 외에도, built-in function object는 다음 internal slot도 가져야 합니다:

  • [[Realm]], function이 created된 realm을 represent하는 Realm Record.
  • [[InitialName]], function의 initial name인 String. 이는 20.2.3.5에 의해 사용됩니다.
  • [[Async]], function이 BuiltinCallOrConstruct 안에서 async function call 및 construct behaviour를 가지는지 여부를 나타내는 Boolean.

달리 specified되지 않는 한, built-in function object's [[Prototype]] internal slot의 initial value는 %Function.prototype%입니다.

built-in function object10.3.1의 definition을 conform하는 [[Call]] internal method를 가져야 합니다.

built-in function object는 “constructor”로 described되거나 이 명세의 어떤 algorithm이 그 [[Construct]] internal method를 explicit하게 set하는 경우에 and only if [[Construct]] internal method를 가집니다. 그러한 [[Construct]] internal method는 10.3.2의 definition을 conform해야 합니다.

implementation은 이 명세에 정의되지 않은 additional built-in function object를 provide할 수 있습니다.

10.3.1 [[Call]] ( thisArg, argList )

The [[Call]] internal method of a built-in function object func takes arguments thisArg (an ECMAScript language value) and argList (a List of ECMAScript language values) and returns either a normal completion containing an ECMAScript language value or a throw completion. It performs the following steps when called:

  1. BuiltinCallOrConstruct(func, thisArg, argList, undefined)를 반환한다.

10.3.2 [[Construct]] ( argList, newTarget )

The [[Construct]] internal method of a built-in function object func (when the method is present) takes arguments argList (a List of ECMAScript language values) and newTarget (a constructor) and returns either a normal completion containing an Object or a throw completion. It performs the following steps when called:

  1. result를 ? BuiltinCallOrConstruct(func, uninitialized, argList, newTarget)로 둔다.
  2. Assert: result는 Object이다.
  3. result를 반환한다.

10.3.3 BuiltinCallOrConstruct ( func, thisArg, argList, newTarget )

The abstract operation BuiltinCallOrConstruct takes arguments func (a built-in function object), thisArg (an ECMAScript language value or uninitialized), argList (a List of ECMAScript language values), and newTarget (a constructor or undefined) and returns either a normal completion containing an ECMAScript language value or a throw completion. It performs the following steps when called:

  1. callerContextrunning execution context로 둔다.
  2. callerContext가 already suspended가 아니면, callerContext를 suspend한다.
  3. calleeContext를 새 execution context로 둔다.
  4. calleeContext의 Function을 func로 설정한다.
  5. calleeRealmfunc.[[Realm]]으로 둔다.
  6. calleeContextRealmcalleeRealm으로 설정한다.
  7. calleeContext의 ScriptOrModule을 null로 설정한다.
  8. calleeContext의 necessary implementation-defined initialization을 수행한다.
  9. calleeContextexecution context stack 위로 push한다; calleeContext는 이제 running execution context이다.
  10. func.[[Async]]true이면, 다음을 수행한다.
    1. promiseCapability를 ! NewPromiseCapability(%Promise%)로 둔다.
    2. resultsClosurefunc, thisArg, argList, newTarget을 capture하고 called될 때 다음 step을 수행하는, parameter가 없는 새 Abstract Closure로 둔다:
      1. resultfunc의 specification을 conform하는 manner로 funcevaluating한 resultCompletion Record로 둔다. thisArguninitialized이면, this value는 uninitialized입니다; 그렇지 않으면 thisArgthis value를 제공합니다. argList는 named parameter를 제공합니다. newTarget은 NewTarget value를 제공합니다.
      2. NOTE: func가 이 document에 defined되어 있으면, “func의 specification”은 algorithm step 또는 기타 means를 통해 그것에 대해 specified된 behaviour입니다.
      3. Completion(result)을 반환한다.
    3. AsyncFunctionStart(promiseCapability, resultsClosure)를 수행한다.
    4. execution context stack에서 calleeContext를 remove하고 callerContextrunning execution context로 restore한다.
    5. promiseCapability.[[Promise]]를 반환한다.
  11. resultfunc의 specification을 conform하는 manner로 funcevaluating한 resultCompletion Record로 둔다. thisArguninitialized이면, this value는 uninitialized입니다; 그렇지 않으면 thisArgthis value를 제공합니다. argList는 named parameter를 제공합니다. newTarget은 NewTarget value를 제공합니다.
  12. NOTE: func가 이 document에 defined되어 있으면, “func의 specification”은 algorithm step 또는 기타 means를 통해 그것에 대해 specified된 behaviour입니다.
  13. execution context stack에서 calleeContext를 remove하고 callerContextrunning execution context로 restore한다.
  14. result를 반환한다.
Note

calleeContextexecution context stack에서 removed될 때, accessible Generator에 의해 later resumption을 위해 suspended되고 retained되어 있다면 destroyed되어서는 안 됩니다.

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의 part로 define되어야 하는 additional internal slot의 name을 contain합니다. 이 operation은 built-in function object를 create합니다. It performs the following steps when called:

  1. realm이 present하지 않으면, realm을 current Realm Record로 설정한다.
  2. proto가 present하지 않으면, protorealm.[[Intrinsics]].[[%Function.prototype%]]로 설정한다.
  3. async가 present하지 않으면, asyncfalse로 설정한다.
  4. internalSlotsList를, create하려는 built-in function object에 대해 10.3가 require하는 모든 internal slot의 name을 contain하는 List로 둔다.
  5. additionalInternalSlotsList의 element를 internalSlotsList에 append한다.
  6. func를 called될 때 behaviour에 의해 specified된 corresponding parameter의 value로 provided argument를 사용하여 behaviour가 describe한 action을 수행하는 새 built-in function object로 둔다. 새 function object는 name이 internalSlotsList의 element인 internal slot과 [[InitialName]] internal slot을 가진다.
  7. func.[[Async]]async로 설정한다.
  8. func.[[Prototype]]proto로 설정한다.
  9. func.[[Extensible]]true로 설정한다.
  10. func.[[Realm]]realm으로 설정한다.
  11. func.[[InitialName]]null로 설정한다.
  12. SetFunctionLength(func, length)를 수행한다.
  13. prefix가 present하지 않으면, 다음을 수행한다.
    1. SetFunctionName(func, name)을 수행한다.
  14. 그렇지 않으면,
    1. SetFunctionName(func, name, prefix)를 수행한다.
  15. func를 반환한다.

이 명세에 정의된 각 built-in function은 CreateBuiltinFunction abstract operation을 calling하여 created됩니다.

10.4 Built-in Exotic Object Internal Methods and Slots

이 명세는 여러 종류의 built-in exotic object를 정의합니다. 이러한 object는 일반적으로 몇몇 specific situation을 제외하면 ordinary object와 similar하게 behave합니다. 다음 exotic object는 아래에서 explicit하게 달리 specified된 곳을 제외하고 ordinary object internal method를 사용합니다:

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를 calling하면 일반적으로 그것의 wrapped function의 call이 result됩니다.

object의 [[Call]]과 (applicable하면) [[Construct]] internal method가 다음 implementation을 사용하고, 그 other essential internal method가 10.1에 있는 definition을 사용하면, 그 object는 bound function exotic object입니다. 이러한 method는 BoundFunctionCreate에서 installed됩니다.

Bound function exotic objectTable 26에 listed된 ECMAScript function object의 internal slot을 가지지 않습니다. 대신 [[Prototype]][[Extensible]]에 더해, Table 27에 listed된 internal slot을 가집니다.

Table 27: Internal Slots of Bound Function Exotic Objects
Internal Slot Type Description
[[BoundTargetFunction]] a callable Object wrapped function object입니다.
[[BoundThis]] an ECMAScript language value wrapped function을 calling할 때 항상 this value로 passed되는 value입니다.
[[BoundArguments]] a List of ECMAScript language values wrapped function에 대한 any call의 first arguments로 사용되는 element를 가진 value의 list입니다.

10.4.1.1 [[Call]] ( thisArg, argList )

The [[Call]] internal method of a bound function exotic object func takes arguments thisArg (an ECMAScript language value) and argList (a List of ECMAScript language values) and returns either a normal completion containing an ECMAScript language value or a throw completion. It performs the following steps when called:

  1. targetfunc.[[BoundTargetFunction]]으로 둔다.
  2. boundThisfunc.[[BoundThis]]로 둔다.
  3. boundArgsfunc.[[BoundArguments]]로 둔다.
  4. argsboundArgsargListlist-concatenation으로 둔다.
  5. Call(target, boundThis, args)를 반환한다.

10.4.1.2 [[Construct]] ( argList, newTarget )

The [[Construct]] internal method of a bound function exotic object func takes arguments argList (a List of ECMAScript language values) and newTarget (a constructor) and returns either a normal completion containing an Object or a throw completion. It performs the following steps when called:

  1. targetfunc.[[BoundTargetFunction]]으로 둔다.
  2. Assert: IsConstructor(target)은 true이다.
  3. boundArgsfunc.[[BoundArguments]]로 둔다.
  4. argsboundArgsargListlist-concatenation으로 둔다.
  5. SameValue(func, newTarget)가 true이면, newTargettarget으로 설정한다.
  6. Construct(target, args, newTarget)을 반환한다.

10.4.1.3 BoundFunctionCreate ( targetFunc, boundThis, boundArgs )

The abstract operation BoundFunctionCreate takes arguments targetFunc (a function object), boundThis (an ECMAScript language value), and boundArgs (a List of ECMAScript language values) and returns either a normal completion containing a function object or a throw completion. 새 bound function exotic object의 creation을 specify하는 데 사용됩니다. It performs the following steps when called:

  1. proto를 ? targetFunc.[[GetPrototypeOf]]()로 둔다.
  2. internalSlotsList를 « [[Prototype]], [[Extensible]] »와 Table 27에 listed된 internal slot의 list-concatenation으로 둔다.
  3. objMakeBasicObject(internalSlotsList)로 둔다.
  4. obj.[[Prototype]]proto로 설정한다.
  5. obj.[[Call]]10.4.1.1에 specified된 대로 설정한다.
  6. IsConstructor(targetFunc)가 true이면, 다음을 수행한다.
    1. obj.[[Construct]]10.4.1.2에 specified된 대로 설정한다.
  7. obj.[[BoundTargetFunction]]targetFunc로 설정한다.
  8. obj.[[BoundThis]]boundThis로 설정한다.
  9. obj.[[BoundArguments]]boundArgs로 설정한다.
  10. obj를 반환한다.

10.4.2 Array Exotic Objects

Array는 array index property key(6.1.7 참조)에 special treatment를 제공하는 exotic object입니다. property namearray index인 property는 element라고도 합니다. 모든 Array는 non-configurable "length" property를 가지며, 그 value는 항상 mathematical value가 232보다 strictly less인 non-negative integral Number입니다. "length" property의 value는 name이 array index인 모든 own property의 name보다 numerically greater합니다; Array의 own property가 created되거나 changed될 때마다, 이 invariant를 maintain하기 위해 other property가 necessary하게 adjusted됩니다. Specifically, name이 array index인 own property가 added될 때마다, "length" property의 value는 필요하면 그 array index의 numeric value보다 하나 큰 값으로 changed됩니다; 그리고 "length" property의 value가 changed될 때마다, name이 array index이고 value가 new length보다 작지 않은 모든 own property는 deleted됩니다. 이 constraint는 Array의 own property에만 apply되며, 그 prototype에서 inherited될 수 있는 "length" 또는 array index property의 영향을 받지 않습니다.

object의 [[DefineOwnProperty]] internal method가 다음 implementation을 사용하고, 그 other essential internal method가 10.1에 있는 definition을 사용하면, 그 object는 Array exotic object(또는 simply, Array)입니다. 이러한 method는 ArrayCreate에서 installed됩니다.

10.4.2.1 [[DefineOwnProperty]] ( propertyKey, propertyDesc )

The [[DefineOwnProperty]] internal method of an Array exotic object array takes arguments propertyKey (a property key) and propertyDesc (a Property Descriptor) and returns either a normal completion containing a Boolean or a throw completion. It performs the following steps when called:

  1. propertyKey"length"이면, ? ArraySetLength(array, propertyDesc)를 반환한다.
  2. propertyKeyarray index이면, 다음을 수행한다.
    1. lengthDescOrdinaryGetOwnProperty(array, "length")로 둔다.
    2. Assert: lengthDescundefined가 아니다.
    3. Assert: IsDataDescriptor(lengthDesc)는 true이다.
    4. Assert: lengthDesc.[[Configurable]]false이다.
    5. lengthlengthDesc.[[Value]]로 둔다.
    6. Assert: length는 non-negative integral Number이다.
    7. index를 ! ToUint32(propertyKey)로 둔다.
    8. indexlength이고 lengthDesc.[[Writable]]false이면, false를 반환한다.
    9. succeeded를 ! OrdinaryDefineOwnProperty(array, propertyKey, propertyDesc)로 둔다.
    10. succeededfalse이면, false를 반환한다.
    11. indexlength이면, 다음을 수행한다.
      1. lengthDesc.[[Value]]index + 1𝔽로 설정한다.
      2. succeeded를 ! OrdinaryDefineOwnProperty(array, "length", lengthDesc)로 설정한다.
      3. Assert: succeededtrue이다.
    12. true를 반환한다.
  3. OrdinaryDefineOwnProperty(array, propertyKey, propertyDesc)를 반환한다.

10.4.2.2 ArrayCreate ( length [ , proto ] )

The abstract operation ArrayCreate takes argument length (a non-negative integer) and optional argument proto (an Object) and returns either a normal completion containing an Array exotic object or a throw completion. 새 Array의 creation을 specify하는 데 사용됩니다. It performs the following steps when called:

  1. length > 232 - 1이면, RangeError exception을 throw한다.
  2. proto가 present하지 않으면, proto%Array.prototype%으로 설정한다.
  3. arrayMakeBasicObject[[Prototype]], [[Extensible]] »)로 둔다.
  4. array.[[Prototype]]proto로 설정한다.
  5. array.[[DefineOwnProperty]]10.4.2.1에 specified된 대로 설정한다.
  6. OrdinaryDefineOwnProperty(array, "length", PropertyDescriptor { [[Value]]: 𝔽(length), [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false })를 수행한다.
  7. array를 반환한다.

10.4.2.3 ArraySpeciesCreate ( originalArray, length )

The abstract operation ArraySpeciesCreate takes arguments originalArray (an Object) and length (a non-negative integer) and returns either a normal completion containing an Object or a throw completion. originalArray에서 derived된 constructor function을 사용하여 새 Array 또는 similar object의 creation을 specify하는 데 사용됩니다. constructor function이 Array를 return해야 한다고 enforce하지는 않습니다. It performs the following steps when called:

  1. isArray를 ? IsArray(originalArray)로 둔다.
  2. isArrayfalse이면, ? ArrayCreate(length)를 반환한다.
  3. ctor를 ? Get(originalArray, "constructor")로 둔다.
  4. IsConstructor(ctor)가 true이면, 다음을 수행한다.
    1. thisRealm을 current Realm Record로 둔다.
    2. ctorRealm을 ? GetFunctionRealm(ctor)으로 둔다.
    3. thisRealmctorRealm이 같은 Realm Record가 아니면, 다음을 수행한다.
      1. SameValue(ctor, ctorRealm.[[Intrinsics]].[[%Array%]])가 true이면, ctorundefined로 설정한다.
  5. ctor가 Object이면, 다음을 수행한다.
    1. ctor를 ? Get(ctor, %Symbol.species%)로 설정한다.
    2. ctornull이면, ctorundefined로 설정한다.
  6. ctorundefined이면, ? ArrayCreate(length)를 반환한다.
  7. IsConstructor(ctor)가 false이면, TypeError exception을 throw한다.
  8. Construct(ctor, « 𝔽(length) »)를 반환한다.
Note

originalArrayrunning execution contextrealm이 아닌 realm에 대한 standard built-in Array constructor를 사용하여 created되었다면, running execution contextrealm을 사용하여 새 Array가 created됩니다. 이는 역사적으로 ArraySpeciesCreate를 사용하여 now defined된 Array.prototype method에 대해 해당 behaviour를 가졌던 Web browser와의 compatibility를 maintain합니다.

10.4.2.4 ArraySetLength ( array, propertyDesc )

The abstract operation ArraySetLength takes arguments array (an Array) and propertyDesc (a Property Descriptor) and returns either a normal completion containing a Boolean or a throw completion. It performs the following steps when called:

  1. propertyDesc[[Value]] field를 가지지 않으면, 다음을 수행한다.
    1. OrdinaryDefineOwnProperty(array, "length", propertyDesc)를 반환한다.
  2. newLengthDescpropertyDesc의 copy로 둔다.
  3. newLength를 ? ToUint32(propertyDesc.[[Value]])로 둔다.
  4. numberLength를 ? ToNumber(propertyDesc.[[Value]])로 둔다.
  5. SameValueZero(newLength, numberLength)가 false이면, RangeError exception을 throw한다.
  6. newLengthDesc.[[Value]]newLength로 설정한다.
  7. oldLengthDescOrdinaryGetOwnProperty(array, "length")로 둔다.
  8. Assert: oldLengthDescundefined가 아니다.
  9. Assert: IsDataDescriptor(oldLengthDesc)는 true이다.
  10. Assert: oldLengthDesc.[[Configurable]]false이다.
  11. oldLengtholdLengthDesc.[[Value]]로 둔다.
  12. newLengtholdLength이면, 다음을 수행한다.
    1. OrdinaryDefineOwnProperty(array, "length", newLengthDesc)를 반환한다.
  13. oldLengthDesc.[[Writable]]false이면, false를 반환한다.
  14. newLengthDesc[[Writable]] field를 가지지 않거나 newLengthDesc.[[Writable]]true이면, 다음을 수행한다.
    1. newWritabletrue로 둔다.
  15. 그렇지 않으면,
    1. NOTE: 어떤 element가 deleted될 수 없는 경우를 대비하여 [[Writable]] attribute를 false로 setting하는 것은 deferred됩니다.
    2. newWritablefalse로 둔다.
    3. newLengthDesc.[[Writable]]true로 설정한다.
  16. succeeded를 ! OrdinaryDefineOwnProperty(array, "length", newLengthDesc)로 둔다.
  17. succeededfalse이면, false를 반환한다.
  18. array의 각 own property key propertyKeypropertyKeyarray index이고 ! ToUint32(propertyKey) ≥ newLength인 것에 대해, descending numeric index order로 다음을 수행한다.
    1. deleteSucceeded를 ! array.[[Delete]](propertyKey)로 둔다.
    2. deleteSucceededfalse이면, 다음을 수행한다.
      1. newLengthDesc.[[Value]]를 ! ToUint32(propertyKey) + 1𝔽로 설정한다.
      2. newWritablefalse이면, newLengthDesc.[[Writable]]false로 설정한다.
      3. OrdinaryDefineOwnProperty(array, "length", newLengthDesc)를 수행한다.
      4. false를 반환한다.
  19. newWritablefalse이면, 다음을 수행한다.
    1. succeeded를 ! OrdinaryDefineOwnProperty(array, "length", PropertyDescriptor { [[Writable]]: false })로 설정한다.
    2. Assert: succeededtrue이다.
  20. true를 반환한다.
Note

step 34에서, propertyDesc.[[Value]]가 object이면 그 valueOf method가 두 번 called됩니다. 이는 이 명세의 2nd Edition부터 이 effect로 specified된 legacy behaviour입니다.

10.4.3 String Exotic Objects

String object는 String value를 encapsulate하고 String value의 individual code unit element에 corresponding하는 virtual integer-indexed data property를 expose하는 exotic object입니다. String exotic object는 항상 "length"라는 data property를 가지며, 그 value는 encapsulated String value의 length입니다. code unit data property"length" property는 모두 non-writable 및 non-configurable입니다.

object의 [[GetOwnProperty]], [[DefineOwnProperty]], [[OwnPropertyKeys]] internal method가 다음 implementation을 사용하고, 그 other essential internal method가 10.1에 있는 definition을 사용하면, 그 object는 String exotic object(또는 simply, String object)입니다. 이러한 method는 StringCreate에서 installed됩니다.

String exotic objectordinary object와 같은 internal slot을 가집니다. 또한 [[StringData]] internal slot을 가집니다.

10.4.3.1 [[GetOwnProperty]] ( propertyKey )

The [[GetOwnProperty]] internal method of a String exotic object string takes argument propertyKey (a property key) and returns a normal completion containing either a Property Descriptor or undefined. It performs the following steps when called:

  1. propertyDescOrdinaryGetOwnProperty(string, propertyKey)로 둔다.
  2. propertyDescundefined가 아니면, propertyDesc를 반환한다.
  3. StringGetOwnProperty(string, propertyKey)를 반환한다.

10.4.3.2 [[DefineOwnProperty]] ( propertyKey, propertyDesc )

The [[DefineOwnProperty]] internal method of a String exotic object string takes arguments propertyKey (a property key) and propertyDesc (a Property Descriptor) and returns a normal completion containing a Boolean. It performs the following steps when called:

  1. stringDescStringGetOwnProperty(string, propertyKey)로 둔다.
  2. stringDescundefined가 아니면, 다음을 수행한다.
    1. extensiblestring.[[Extensible]]로 둔다.
    2. IsCompatiblePropertyDescriptor(extensible, propertyDesc, stringDesc)를 반환한다.
  3. OrdinaryDefineOwnProperty(string, propertyKey, propertyDesc)를 반환한다.

10.4.3.3 [[OwnPropertyKeys]] ( )

The [[OwnPropertyKeys]] internal method of a String exotic object obj takes no arguments and returns a normal completion containing a List of property keys. It performs the following steps when called:

  1. keys를 새 empty List로 둔다.
  2. stringobj.[[StringData]]로 둔다.
  3. Assert: string은 String이다.
  4. lengthstring의 length로 둔다.
  5. 0 ≤ i < length인 각 integer i에 대해, ascending order로 다음을 수행한다.
    1. ToString(𝔽(i))를 keys에 append한다.
  6. obj의 각 own property key propertyKeypropertyKeyarray index이고 ! ToIntegerOrInfinity(propertyKey) ≥ length인 것에 대해, ascending numeric index order로 다음을 수행한다.
    1. propertyKeykeys에 append한다.
  7. obj의 각 own property key propertyKeypropertyKey가 String이고 propertyKeyarray index가 아닌 것에 대해, property creation의 ascending chronological order로 다음을 수행한다.
    1. propertyKeykeys에 append한다.
  8. obj의 각 own property key propertyKeypropertyKey가 Symbol인 것에 대해, property creation의 ascending chronological order로 다음을 수행한다.
    1. propertyKeykeys에 append한다.
  9. keys를 반환한다.

10.4.3.4 StringCreate ( value, proto )

The abstract operation StringCreate takes arguments value (a String) and proto (an Object) and returns a String exotic object. 새 String exotic object의 creation을 specify하는 데 사용됩니다. It performs the following steps when called:

  1. stringMakeBasicObject[[Prototype]], [[Extensible]], [[StringData]] »)로 둔다.
  2. string.[[Prototype]]proto로 설정한다.
  3. string.[[StringData]]value로 설정한다.
  4. string.[[GetOwnProperty]]10.4.3.1에 specified된 대로 설정한다.
  5. string.[[DefineOwnProperty]]10.4.3.2에 specified된 대로 설정한다.
  6. string.[[OwnPropertyKeys]]10.4.3.3에 specified된 대로 설정한다.
  7. lengthvalue의 length로 둔다.
  8. DefinePropertyOrThrow(string, "length", PropertyDescriptor { [[Value]]: 𝔽(length), [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false })를 수행한다.
  9. string을 반환한다.

10.4.3.5 StringGetOwnProperty ( string, propertyKey )

The abstract operation StringGetOwnProperty takes arguments string (an Object that has a [[StringData]] internal slot) and propertyKey (a property key) and returns a Property Descriptor or undefined. It performs the following steps when called:

  1. propertyKey가 String이 아니면, undefined를 반환한다.
  2. numericIndexCanonicalNumericIndexString(propertyKey)로 둔다.
  3. numericIndexintegral Number가 아니면, undefined를 반환한다.
  4. numericIndex-0𝔽이거나 numericIndex < -0𝔽이면, undefined를 반환한다.
  5. stringDatastring.[[StringData]]로 둔다.
  6. Assert: stringData는 String이다.
  7. lengthstringData의 length로 둔다.
  8. (numericIndex) ≥ length이면, undefined를 반환한다.
  9. resultString(numericIndex)부터 (numericIndex) + 1까지의 stringData substring으로 둔다.
  10. PropertyDescriptor { [[Value]]: resultString, [[Writable]]: false, [[Enumerable]]: true, [[Configurable]]: false }를 반환한다.

10.4.4 Arguments Exotic Objects

대부분의 ECMAScript function은 그 code에서 arguments object를 available하게 합니다. function definition의 characteristic에 따라, 그 arguments object는 ordinary object이거나 arguments exotic object입니다. arguments exotic objectarray index property가 associated ECMAScript function의 invocation의 formal parameter binding에 map되는 exotic object입니다.

object의 internal method가 다음 implementation을 사용하고, 여기서 specified되지 않은 것은 10.1에 있는 것을 사용하면, 그 object는 arguments exotic object입니다. 이러한 method는 CreateMappedArgumentsObject에서 installed됩니다.

Note 1

CreateUnmappedArgumentsObject는 이 clause 안에 grouped되어 있지만, arguments exotic object가 아니라 ordinary object를 create합니다.

Arguments exotic objectordinary object와 같은 internal slot을 가집니다. 또한 [[ParameterMap]] internal slot을 가집니다. Ordinary arguments object도 value가 항상 undefined[[ParameterMap]] internal slot을 가집니다. ordinary argument object의 경우 [[ParameterMap]] internal slot은 Object.prototype.toString(20.1.3.6)에 의해 그것을 그렇게 identify하는 데만 사용됩니다.

Note 2

numeric name value가 corresponding function object의 formal parameter 수보다 작은 arguments exotic objectinteger-indexed data property는 initially function의 execution context 안의 corresponding argument binding과 그 value를 share합니다. 이는 property를 changing하면 corresponding argument binding의 value가 changed되고 그 반대도 성립함을 의미합니다. 그러한 property가 deleted된 다음 redefined되거나 property가 accessor property로 changed되면 이 correspondence는 broken됩니다. arguments object가 ordinary object이면, 그 property의 value는 단순히 function에 passed된 argument의 copy이며, property value와 formal parameter value 사이에 dynamic linkage는 없습니다.

Note 3

ParameterMap object와 그 property value는 arguments object correspondence to argument binding을 specifying하는 device로 사용됩니다. ParameterMap object와 그 property의 value인 object는 ECMAScript code에서 directly observable하지 않습니다. ECMAScript implementation은 specified semantics를 implement하기 위해 실제로 그러한 object를 create하거나 사용할 필요가 없습니다.

Note 4

Ordinary arguments object는 access 시 TypeError exception을 throw하는 "callee"라는 non-configurable accessor property를 define합니다. "callee" property는 일부 class의 non-strict function에 대해서만 created되는 arguments exotic object에 대해 더 specific한 meaning을 가집니다. ordinary variant에서 이 property의 definition은 conforming ECMAScript implementation이 다른 manner로 define하지 않도록 ensure하기 위해 존재합니다.

Note 5

arguments exotic object의 ECMAScript implementation은 역사적으로 "caller"라는 accessor property를 contained했습니다. ECMAScript 2017 이전에는, 이 명세가 ordinary arguments object 위의 throwing "caller" property의 definition을 포함했습니다. implementation이 더 이상 이 extension을 contain하지 않으므로, ECMAScript 2017은 throwing "caller" accessor에 대한 requirement를 dropped했습니다.

10.4.4.1 [[GetOwnProperty]] ( propertyKey )

The [[GetOwnProperty]] internal method of an arguments exotic object args takes argument propertyKey (a property key) and returns a normal completion containing either a Property Descriptor or undefined. It performs the following steps when called:

  1. propertyDescOrdinaryGetOwnProperty(args, propertyKey)로 둔다.
  2. propertyDescundefined이면, undefined를 반환한다.
  3. mapargs.[[ParameterMap]]으로 둔다.
  4. isMapped를 ! HasOwnProperty(map, propertyKey)로 둔다.
  5. isMappedtrue이면, 다음을 수행한다.
    1. propertyDesc.[[Value]]를 ! Get(map, propertyKey)로 설정한다.
  6. propertyDesc를 반환한다.

10.4.4.2 [[DefineOwnProperty]] ( propertyKey, propertyDesc )

The [[DefineOwnProperty]] internal method of an arguments exotic object args takes arguments propertyKey (a property key) and propertyDesc (a Property Descriptor) and returns a normal completion containing a Boolean. It performs the following steps when called:

  1. mapargs.[[ParameterMap]]으로 둔다.
  2. isMapped를 ! HasOwnProperty(map, propertyKey)로 둔다.
  3. newArgDescpropertyDesc로 둔다.
  4. isMappedtrue이고 IsDataDescriptor(propertyDesc)가 true이면, 다음을 수행한다.
    1. propertyDesc[[Value]] field를 가지지 않고, propertyDesc[[Writable]] field를 가지며, propertyDesc.[[Writable]]false이면, 다음을 수행한다.
      1. newArgDescpropertyDesc의 copy로 설정한다.
      2. newArgDesc.[[Value]]를 ! Get(map, propertyKey)로 설정한다.
  5. allowed를 ! OrdinaryDefineOwnProperty(args, propertyKey, newArgDesc)로 둔다.
  6. allowedfalse이면, false를 반환한다.
  7. isMappedtrue이면, 다음을 수행한다.
    1. IsAccessorDescriptor(propertyDesc)가 true이면, 다음을 수행한다.
      1. map.[[Delete]](propertyKey)를 수행한다.
    2. 그렇지 않으면,
      1. propertyDesc[[Value]] field를 가지면, 다음을 수행한다.
        1. Assert: arguments object가 map한 formal parameter는 항상 writable이므로 다음 Set은 succeed할 것이다.
        2. Set(map, propertyKey, propertyDesc.[[Value]], false)를 수행한다.
      2. propertyDesc[[Writable]] field를 가지고 propertyDesc.[[Writable]]false이면, 다음을 수행한다.
        1. map.[[Delete]](propertyKey)를 수행한다.
  8. true를 반환한다.

10.4.4.3 [[Get]] ( propertyKey, receiver )

The [[Get]] internal method of an arguments exotic object args takes arguments propertyKey (a property key) and receiver (an ECMAScript language value) and returns either a normal completion containing an ECMAScript language value or a throw completion. It performs the following steps when called:

  1. mapargs.[[ParameterMap]]으로 둔다.
  2. isMapped를 ! HasOwnProperty(map, propertyKey)로 둔다.
  3. isMappedfalse이면, ? OrdinaryGet(args, propertyKey, receiver)를 반환한다.
  4. Assert: mappropertyKey에 대한 formal parameter mapping을 contain한다.
  5. Get(map, propertyKey)를 반환한다.

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

The [[Set]] internal method of an arguments exotic object args takes arguments propertyKey (a property key), value (an ECMAScript language value), and receiver (an ECMAScript language value) and returns either a normal completion containing a Boolean or a throw completion. It performs the following steps when called:

  1. SameValue(args, receiver)가 false이면, 다음을 수행한다.
    1. isMappedfalse로 둔다.
  2. 그렇지 않으면,
    1. mapargs.[[ParameterMap]]으로 둔다.
    2. isMapped를 ! HasOwnProperty(map, propertyKey)로 둔다.
  3. isMappedtrue이면, 다음을 수행한다.
    1. Assert: arguments object가 map한 formal parameter는 항상 writable이므로 다음 Set은 succeed할 것이다.
    2. Set(map, propertyKey, value, false)를 수행한다.
  4. OrdinarySet(args, propertyKey, value, receiver)를 반환한다.

10.4.4.5 [[Delete]] ( propertyKey )

The [[Delete]] internal method of an arguments exotic object args takes argument propertyKey (a property key) and returns either a normal completion containing a Boolean or a throw completion. It performs the following steps when called:

  1. mapargs.[[ParameterMap]]으로 둔다.
  2. isMapped를 ! HasOwnProperty(map, propertyKey)로 둔다.
  3. result를 ? OrdinaryDelete(args, propertyKey)로 둔다.
  4. resulttrue이고 isMappedtrue이면, 다음을 수행한다.
    1. map.[[Delete]](propertyKey)를 수행한다.
  5. result를 반환한다.

10.4.4.6 CreateUnmappedArgumentsObject ( argList )

The abstract operation CreateUnmappedArgumentsObject takes argument argList (a List of ECMAScript language values) and returns an ordinary object. It performs the following steps when called:

  1. lengthargList 안의 element 수로 둔다.
  2. objOrdinaryObjectCreate(%Object.prototype%, « [[ParameterMap]] »)로 둔다.
  3. obj.[[ParameterMap]]undefined로 설정한다.
  4. DefinePropertyOrThrow(obj, "length", PropertyDescriptor { [[Value]]: 𝔽(length), [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: true })를 수행한다.
  5. index를 0으로 둔다.
  6. index < length인 동안 Repeat,
    1. valueargList[index]로 둔다.
    2. CreateDataPropertyOrThrow(obj, ! ToString(𝔽(index)), value)를 수행한다.
    3. indexindex + 1로 설정한다.
  7. DefinePropertyOrThrow(obj, %Symbol.iterator%, PropertyDescriptor { [[Value]]: %Array.prototype.values%, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: true })를 수행한다.
  8. DefinePropertyOrThrow(obj, "callee", PropertyDescriptor { [[Get]]: %ThrowTypeError%, [[Set]]: %ThrowTypeError%, [[Enumerable]]: false, [[Configurable]]: false })를 수행한다.
  9. obj를 반환한다.

10.4.4.7 CreateMappedArgumentsObject ( func, formals, argList, envRecord )

The abstract operation CreateMappedArgumentsObject takes arguments func (an ECMAScript function object), formals (a Parse Node), argList (a List of ECMAScript language values), and envRecord (an Environment Record) and returns an arguments exotic object. It performs the following steps when called:

  1. Assert: formals는 rest parameter, binding pattern 또는 initializer를 contain하지 않는다. 이는 duplicate identifier를 contain할 수 있다.
  2. lengthargList 안의 element 수로 둔다.
  3. objMakeBasicObject[[Prototype]], [[Extensible]], [[ParameterMap]] »)로 둔다.
  4. obj.[[GetOwnProperty]]10.4.4.1에 specified된 대로 설정한다.
  5. obj.[[DefineOwnProperty]]10.4.4.2에 specified된 대로 설정한다.
  6. obj.[[Get]]10.4.4.3에 specified된 대로 설정한다.
  7. obj.[[Set]]10.4.4.4에 specified된 대로 설정한다.
  8. obj.[[Delete]]10.4.4.5에 specified된 대로 설정한다.
  9. obj.[[Prototype]]%Object.prototype%으로 설정한다.
  10. mapOrdinaryObjectCreate(null)로 둔다.
  11. obj.[[ParameterMap]]map으로 설정한다.
  12. paramNamesformalsBoundNames로 둔다.
  13. paramCountparamNames 안의 element 수로 둔다.
  14. index를 0으로 둔다.
  15. index < length인 동안 Repeat,
    1. valueargList[index]로 둔다.
    2. CreateDataPropertyOrThrow(obj, ! ToString(𝔽(index)), value)를 수행한다.
    3. indexindex + 1로 설정한다.
  16. DefinePropertyOrThrow(obj, "length", PropertyDescriptor { [[Value]]: 𝔽(length), [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: true })를 수행한다.
  17. mappedNames를 새 empty List로 둔다.
  18. indexparamCount - 1로 설정한다.
  19. index ≥ 0인 동안 Repeat,
    1. nameparamNames[index]로 둔다.
    2. mappedNamesname을 contain하지 않으면, 다음을 수행한다.
      1. namemappedNames에 append한다.
      2. index < length이면, 다음을 수행한다.
        1. getterMakeArgGetter(name, envRecord)로 둔다.
        2. setterMakeArgSetter(name, envRecord)로 둔다.
        3. map.[[DefineOwnProperty]](! ToString(𝔽(index)), PropertyDescriptor { [[Set]]: setter, [[Get]]: getter, [[Enumerable]]: false, [[Configurable]]: true })를 수행한다.
    3. indexindex - 1로 설정한다.
  20. DefinePropertyOrThrow(obj, %Symbol.iterator%, PropertyDescriptor { [[Value]]: %Array.prototype.values%, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: true })를 수행한다.
  21. DefinePropertyOrThrow(obj, "callee", PropertyDescriptor { [[Value]]: func, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: true })를 수행한다.
  22. obj를 반환한다.

10.4.4.7.1 MakeArgGetter ( name, envRecord )

The abstract operation MakeArgGetter takes arguments name (a String) and envRecord (an Environment Record) and returns a function object. executed될 때 envRecord 안에서 name에 bound된 value를 반환하는 built-in function object를 create합니다. It performs the following steps when called:

  1. getterClosurenameenvRecord를 capture하고 called될 때 다음 step을 수행하는, parameter가 없는 새 Abstract Closure로 둔다:
    1. NormalCompletion(! envRecord.GetBindingValue(name, false))를 반환한다.
  2. getterCreateBuiltinFunction(getterClosure, 0, "", « »)로 둔다.
  3. NOTE: getter는 ECMAScript code에서 결코 directly accessible하지 않습니다.
  4. getter를 반환한다.

10.4.4.7.2 MakeArgSetter ( name, envRecord )

The abstract operation MakeArgSetter takes arguments name (a String) and envRecord (an Environment Record) and returns a function object. executed될 때 envRecord 안에서 name에 bound된 value를 set하는 built-in function object를 create합니다. It performs the following steps when called:

  1. setterClosurenameenvRecord를 capture하고 called될 때 다음 step을 수행하는, parameter (value)를 가진 새 Abstract Closure로 둔다:
    1. NormalCompletion(! envRecord.SetMutableBinding(name, value, false))를 반환한다.
  2. setterCreateBuiltinFunction(setterClosure, 1, "", « »)로 둔다.
  3. NOTE: setter는 ECMAScript code에서 결코 directly accessible하지 않습니다.
  4. setter를 반환한다.

10.4.5 TypedArray Exotic Objects

TypedArraycanonical numeric stringproperty key에 대해 special handling을 수행하는 exotic object입니다. uniform type의 element를 index하기 위해 in-bounds integer index인 subset을 사용하고, 나머지는 prototype chain traversal을 incur하지 않고 absent임을 enforce합니다.

Note

어떤 Number n에 대해서도 ToString(n)은 canonical numeric string이므로, implementation은 실제 string conversion을 수행하지 않고도 Number를 TypedArrayproperty key로 treat할 수 있습니다.

TypedArrayordinary object와 같은 internal slot을 가지며, 추가로 [[ViewedArrayBuffer]], [[TypedArrayName]], [[ContentType]], [[ByteLength]], [[ByteOffset]], [[ArrayLength]] internal slot을 가집니다.

object의 [[PreventExtensions]], [[GetOwnProperty]], [[HasProperty]], [[DefineOwnProperty]], [[Get]], [[Set]], [[Delete]], [[OwnPropertyKeys]] internal method가 이 section의 definition을 사용하고, 그 other essential internal method가 10.1에 있는 definition을 사용하면, 그 object는 TypedArray입니다. 이러한 method는 TypedArrayCreate에 의해 installed됩니다.

10.4.5.1 [[PreventExtensions]] ( )

The [[PreventExtensions]] internal method of a TypedArray obj takes no arguments and returns a normal completion containing a Boolean. It performs the following steps when called:

  1. NOTE: 6.1.7.3에 specified된 extensibility-related invariant는 obj가 property를 gain할 수 있을 때(또는 lose한 후 regain할 수 있을 때) 이 method가 true를 return하는 것을 allow하지 않습니다. 이는 underlying buffer가 resized될 때 integer index name을 가진 property에 대해 occur할 수 있습니다.
  2. IsTypedArrayFixedLength(obj)가 false이면, false를 반환한다.
  3. OrdinaryPreventExtensions(obj)를 반환한다.

10.4.5.2 [[GetOwnProperty]] ( propertyKey )

The [[GetOwnProperty]] internal method of a TypedArray obj takes argument propertyKey (a property key) and returns a normal completion containing either a Property Descriptor or undefined. It performs the following steps when called:

  1. propertyKey가 String이면, 다음을 수행한다.
    1. numericIndexCanonicalNumericIndexString(propertyKey)으로 둔다.
    2. numericIndexundefined가 아니면, 다음을 수행한다.
      1. valueTypedArrayGetElement(obj, numericIndex)로 둔다.
      2. valueundefined이면, undefined를 반환한다.
      3. PropertyDescriptor { [[Value]]: value, [[Writable]]: true, [[Enumerable]]: true, [[Configurable]]: true }를 반환한다.
  2. OrdinaryGetOwnProperty(obj, propertyKey)를 반환한다.

10.4.5.3 [[HasProperty]] ( propertyKey )

The [[HasProperty]] internal method of a TypedArray obj takes argument propertyKey (a property key) and returns either a normal completion containing a Boolean or a throw completion. It performs the following steps when called:

  1. propertyKey가 String이면, 다음을 수행한다.
    1. numericIndexCanonicalNumericIndexString(propertyKey)으로 둔다.
    2. numericIndexundefined가 아니면, IsValidIntegerIndex(obj, numericIndex)를 반환한다.
  2. OrdinaryHasProperty(obj, propertyKey)를 반환한다.

10.4.5.4 [[DefineOwnProperty]] ( propertyKey, propertyDesc )

The [[DefineOwnProperty]] internal method of a TypedArray obj takes arguments propertyKey (a property key) and propertyDesc (a Property Descriptor) and returns either a normal completion containing a Boolean or a throw completion. It performs the following steps when called:

  1. propertyKey가 String이면, 다음을 수행한다.
    1. numericIndexCanonicalNumericIndexString(propertyKey)으로 둔다.
    2. numericIndexundefined가 아니면, 다음을 수행한다.
      1. IsValidIntegerIndex(obj, numericIndex)가 false이면, false를 반환한다.
      2. propertyDesc[[Configurable]] field를 가지고 propertyDesc.[[Configurable]]false이면, false를 반환한다.
      3. propertyDesc[[Enumerable]] field를 가지고 propertyDesc.[[Enumerable]]false이면, false를 반환한다.
      4. IsAccessorDescriptor(propertyDesc)가 true이면, false를 반환한다.
      5. propertyDesc[[Writable]] field를 가지고 propertyDesc.[[Writable]]false이면, false를 반환한다.
      6. propertyDesc[[Value]] field를 가지면, ? TypedArraySetElement(obj, numericIndex, propertyDesc.[[Value]])를 수행한다.
      7. true를 반환한다.
  2. OrdinaryDefineOwnProperty(obj, propertyKey, propertyDesc)를 반환한다.

10.4.5.5 [[Get]] ( propertyKey, receiver )

The [[Get]] internal method of a TypedArray obj takes arguments propertyKey (a property key) and receiver (an ECMAScript language value) and returns either a normal completion containing an ECMAScript language value or a throw completion. It performs the following steps when called:

  1. propertyKey가 String이면, 다음을 수행한다.
    1. numericIndexCanonicalNumericIndexString(propertyKey)으로 둔다.
    2. numericIndexundefined가 아니면, 다음을 수행한다.
      1. TypedArrayGetElement(obj, numericIndex)를 반환한다.
  2. OrdinaryGet(obj, propertyKey, receiver)를 반환한다.

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

The [[Set]] internal method of a TypedArray obj takes arguments propertyKey (a property key), value (an ECMAScript language value), and receiver (an ECMAScript language value) and returns either a normal completion containing a Boolean or a throw completion. It performs the following steps when called:

  1. propertyKey가 String이면, 다음을 수행한다.
    1. numericIndexCanonicalNumericIndexString(propertyKey)으로 둔다.
    2. numericIndexundefined가 아니면, 다음을 수행한다.
      1. SameValue(obj, receiver)가 true이면, 다음을 수행한다.
        1. TypedArraySetElement(obj, numericIndex, value)를 수행한다.
        2. true를 반환한다.
      2. IsValidIntegerIndex(obj, numericIndex)가 false이면, true를 반환한다.
  2. OrdinarySet(obj, propertyKey, value, receiver)를 반환한다.

10.4.5.7 [[Delete]] ( propertyKey )

The [[Delete]] internal method of a TypedArray obj takes argument propertyKey (a property key) and returns a normal completion containing a Boolean. It performs the following steps when called:

  1. propertyKey가 String이면, 다음을 수행한다.
    1. numericIndexCanonicalNumericIndexString(propertyKey)으로 둔다.
    2. numericIndexundefined가 아니면, 다음을 수행한다.
      1. IsValidIntegerIndex(obj, numericIndex)가 false이면, true를 반환한다.
      2. false를 반환한다.
  2. OrdinaryDelete(obj, propertyKey)를 반환한다.

10.4.5.8 [[OwnPropertyKeys]] ( )

The [[OwnPropertyKeys]] internal method of a TypedArray obj takes no arguments and returns a normal completion containing a List of property keys. It performs the following steps when called:

  1. taRecordMakeTypedArrayWithBufferWitnessRecord(obj, seq-cst)로 둔다.
  2. keys를 새 empty List로 둔다.
  3. IsTypedArrayOutOfBounds(taRecord)가 false이면, 다음을 수행한다.
    1. lengthTypedArrayLength(taRecord)로 둔다.
    2. 0 ≤ i < length인 각 integer i에 대해, ascending order로 다음을 수행한다.
      1. ToString(𝔽(i))를 keys에 append한다.
  4. obj의 각 own property key propertyKeypropertyKey가 String이고 propertyKeyinteger index가 아닌 것에 대해, property creation의 ascending chronological order로 다음을 수행한다.
    1. propertyKeykeys에 append한다.
  5. obj의 각 own property key propertyKeypropertyKey가 Symbol인 것에 대해, property creation의 ascending chronological order로 다음을 수행한다.
    1. propertyKeykeys에 append한다.
  6. keys를 반환한다.

10.4.5.9 TypedArray With Buffer Witness Records

TypedArray With Buffer Witness Record는 viewed buffer의 cached byte length와 함께 TypedArray를 encapsulate하는 데 사용되는 Record value입니다. 이는 viewed buffer가 growable SharedArrayBuffer일 때 byte length data block의 single ReadSharedMemory event가 있음을 ensure하는 데 help하기 위해 사용됩니다.

TypedArray With Buffer Witness Record는 Table 28에 listed된 field를 가집니다.

Table 28: TypedArray With Buffer Witness Record Fields
Field Name Value Meaning
[[Object]] a TypedArray buffer의 byte length가 loaded되는 TypedArray입니다.
[[CachedBufferByteLength]] a non-negative integer or detached Record가 created되었을 때 object의 [[ViewedArrayBuffer]]의 byte length입니다.

10.4.5.10 MakeTypedArrayWithBufferWitnessRecord ( obj, order )

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

  1. bufferobj.[[ViewedArrayBuffer]]로 둔다.
  2. IsDetachedBuffer(buffer)가 true이면, 다음을 수행한다.
    1. byteLengthdetached로 둔다.
  3. 그렇지 않으면,
    1. byteLengthArrayBufferByteLength(buffer, order)로 둔다.
  4. TypedArray With Buffer Witness Record { [[Object]]: obj, [[CachedBufferByteLength]]: byteLength }를 반환한다.

10.4.5.11 TypedArrayCreate ( proto )

The abstract operation TypedArrayCreate takes argument proto (an Object) and returns a TypedArray. 새 TypedArray의 creation을 specify하는 데 사용됩니다. It performs the following steps when called:

  1. internalSlotsList를 « [[Prototype]], [[Extensible]], [[ViewedArrayBuffer]], [[TypedArrayName]], [[ContentType]], [[ByteLength]], [[ByteOffset]], [[ArrayLength]] »로 둔다.
  2. taMakeBasicObject(internalSlotsList)로 둔다.
  3. ta.[[PreventExtensions]]10.4.5.1에 specified된 대로 설정한다.
  4. ta.[[GetOwnProperty]]10.4.5.2에 specified된 대로 설정한다.
  5. ta.[[HasProperty]]10.4.5.3에 specified된 대로 설정한다.
  6. ta.[[DefineOwnProperty]]10.4.5.4에 specified된 대로 설정한다.
  7. ta.[[Get]]10.4.5.5에 specified된 대로 설정한다.
  8. ta.[[Set]]10.4.5.6에 specified된 대로 설정한다.
  9. ta.[[Delete]]10.4.5.7에 specified된 대로 설정한다.
  10. ta.[[OwnPropertyKeys]]10.4.5.8에 specified된 대로 설정한다.
  11. ta.[[Prototype]]proto로 설정한다.
  12. ta를 반환한다.

10.4.5.12 TypedArrayByteLength ( taRecord )

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

  1. Assert: IsTypedArrayOutOfBounds(taRecord)는 false이다.
  2. objtaRecord.[[Object]]로 둔다.
  3. obj.[[ByteLength]]auto가 아니면, obj.[[ByteLength]]를 반환한다.
  4. lengthTypedArrayLength(taRecord)로 둔다.
  5. elementSizeTypedArrayElementSize(obj)로 둔다.
  6. NOTE: underlying buffer가 non-integer multiple로 resized되었을 때도 returned byte length는 항상 elementSizeinteger multiple입니다.
  7. length × elementSize를 반환한다.

10.4.5.13 TypedArrayLength ( taRecord )

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

  1. Assert: IsTypedArrayOutOfBounds(taRecord)는 false이다.
  2. objtaRecord.[[Object]]로 둔다.
  3. obj.[[ArrayLength]]auto가 아니면, obj.[[ArrayLength]]를 반환한다.
  4. Assert: IsFixedLengthArrayBuffer(obj.[[ViewedArrayBuffer]])는 false이다.
  5. byteOffsetobj.[[ByteOffset]]로 둔다.
  6. elementSizeTypedArrayElementSize(obj)로 둔다.
  7. byteLengthtaRecord.[[CachedBufferByteLength]]로 둔다.
  8. Assert: byteLengthdetached가 아니다.
  9. floor((byteLength - byteOffset) / elementSize)를 반환한다.

10.4.5.14 IsTypedArrayOutOfBounds ( taRecord )

The abstract operation IsTypedArrayOutOfBounds takes argument taRecord (a TypedArray With Buffer Witness Record) and returns a Boolean. object의 numeric property 중 어떤 것이 underlying buffer's bounds 안에 contained되지 않은 index의 value를 reference하는지 check합니다. It performs the following steps when called:

  1. objtaRecord.[[Object]]로 둔다.
  2. bufferByteLengthtaRecord.[[CachedBufferByteLength]]로 둔다.
  3. IsDetachedBuffer(obj.[[ViewedArrayBuffer]])가 true이면, 다음을 수행한다.
    1. Assert: bufferByteLengthdetached이다.
    2. true를 반환한다.
  4. Assert: bufferByteLength는 non-negative integer이다.
  5. byteOffsetStartobj.[[ByteOffset]]로 둔다.
  6. obj.[[ArrayLength]]auto이면, 다음을 수행한다.
    1. byteOffsetEndbufferByteLength로 둔다.
  7. 그렇지 않으면,
    1. elementSizeTypedArrayElementSize(obj)로 둔다.
    2. arrayByteLengthobj.[[ArrayLength]] × elementSize로 둔다.
    3. byteOffsetEndbyteOffsetStart + arrayByteLength로 둔다.
  8. NOTE: [[ByteOffset]]bufferByteLength인 0-length TypedArray는 out-of-bounds로 considered되지 않습니다.
  9. byteOffsetStart > bufferByteLength이거나 byteOffsetEnd > bufferByteLength이면, true를 반환한다.
  10. false를 반환한다.

10.4.5.15 IsTypedArrayFixedLength ( obj )

The abstract operation IsTypedArrayFixedLength takes argument obj (a TypedArray) and returns a Boolean. It performs the following steps when called:

  1. obj.[[ArrayLength]]auto이면, false를 반환한다.
  2. bufferobj.[[ViewedArrayBuffer]]로 둔다.
  3. IsFixedLengthArrayBuffer(buffer)가 false이고 IsSharedArrayBuffer(buffer)가 false이면, false를 반환한다.
  4. true를 반환한다.

10.4.5.16 IsValidIntegerIndex ( obj, index )

The abstract operation IsValidIntegerIndex takes arguments obj (a TypedArray) and index (a Number) and returns a Boolean. It performs the following steps when called:

  1. IsDetachedBuffer(obj.[[ViewedArrayBuffer]])가 true이면, false를 반환한다.
  2. indexintegral Number가 아니면, false를 반환한다.
  3. index-0𝔽이거나 index < -0𝔽이면, false를 반환한다.
  4. taRecordMakeTypedArrayWithBufferWitnessRecord(obj, unordered)로 둔다.
  5. NOTE: obj의 backing buffer가 growable SharedArrayBuffer일 때 bounds checking은 synchronizing operation이 아닙니다.
  6. IsTypedArrayOutOfBounds(taRecord)가 true이면, false를 반환한다.
  7. lengthTypedArrayLength(taRecord)로 둔다.
  8. (index) ≥ length이면, false를 반환한다.
  9. true를 반환한다.

10.4.5.17 TypedArrayGetElement ( obj, index )

The abstract operation TypedArrayGetElement takes arguments obj (a TypedArray) and index (a Number) and returns a Number, a BigInt, or undefined. It performs the following steps when called:

  1. IsValidIntegerIndex(obj, index)가 false이면, undefined를 반환한다.
  2. offsetobj.[[ByteOffset]]로 둔다.
  3. elementSizeTypedArrayElementSize(obj)로 둔다.
  4. byteIndexInBuffer를 ((index) × elementSize) + offset으로 둔다.
  5. elementTypeTypedArrayElementType(obj)으로 둔다.
  6. GetValueFromBuffer(obj.[[ViewedArrayBuffer]], byteIndexInBuffer, elementType, true, unordered)를 반환한다.

10.4.5.18 TypedArraySetElement ( obj, index, value )

The abstract operation TypedArraySetElement takes arguments obj (a TypedArray), index (a Number), and value (an ECMAScript language value) and returns either a normal completion containing unused or a throw completion. It performs the following steps when called:

  1. obj.[[ContentType]]bigint이면, number를 ? ToBigInt(value)로 둔다.
  2. 그렇지 않으면, number를 ? ToNumber(value)로 둔다.
  3. IsValidIntegerIndex(obj, index)가 true이면, 다음을 수행한다.
    1. offsetobj.[[ByteOffset]]로 둔다.
    2. elementSizeTypedArrayElementSize(obj)로 둔다.
    3. byteIndexInBuffer를 ((index) × elementSize) + offset으로 둔다.
    4. elementTypeTypedArrayElementType(obj)로 둔다.
    5. SetValueInBuffer(obj.[[ViewedArrayBuffer]], byteIndexInBuffer, elementType, number, true, unordered)를 수행한다.
  4. unused를 반환한다.
Note

이 operation은 항상 succeed하는 것처럼 보이지만, TypedArray의 end를 지나서 write하려고 하거나 detached ArrayBuffer가 backing하는 TypedArray에 write하려고 할 때는 effect가 없습니다.

10.4.5.19 IsArrayBufferViewOutOfBounds ( obj )

The abstract operation IsArrayBufferViewOutOfBounds takes argument obj (a TypedArray or a DataView) and returns a Boolean. TypedArray의 numeric property 중 어떤 것이나 DataView object의 method가 underlying data block's bounds 안에 contained되지 않은 index의 value를 reference할 수 있는지 check합니다. 이 abstract operation은 upstream specification을 위한 convenience로 존재합니다. It performs the following steps when called:

  1. obj[[DataView]] internal slot을 가지면, 다음을 수행한다.
    1. viewRecordMakeDataViewWithBufferWitnessRecord(obj, seq-cst)로 둔다.
    2. IsViewOutOfBounds(viewRecord)를 반환한다.
  2. taRecordMakeTypedArrayWithBufferWitnessRecord(obj, seq-cst)로 둔다.
  3. IsTypedArrayOutOfBounds(taRecord)를 반환한다.

10.4.6 Module Namespace Exotic Objects

module namespace exotic object는 ECMAScript Module에서 exported된 binding을 expose하는 exotic object입니다(16.2.3 참조). module namespace exotic object의 String-keyed own property와 Module이 exported한 binding name 사이에는 one-to-one correspondence가 있습니다. exported binding에는 export * export item을 사용하여 indirectly exported된 binding도 포함됩니다. 각 String-valued own property key는 corresponding exported binding name의 StringValue입니다. 이들은 module namespace exotic object의 유일한 String-keyed property입니다. 그러한 각 property는 attribute { [[Writable]]: true, [[Enumerable]]: true, [[Configurable]]: false }를 가집니다. Module namespace exotic object는 extensible이 아닙니다.

object의 [[GetPrototypeOf]], [[SetPrototypeOf]], [[IsExtensible]], [[PreventExtensions]], [[GetOwnProperty]], [[DefineOwnProperty]], [[HasProperty]], [[Get]], [[Set]], [[Delete]], [[OwnPropertyKeys]] internal method가 이 section의 definition을 사용하고, 그 other essential internal method가 10.1에 있는 definition을 사용하면, 그 object는 module namespace exotic object입니다. 이러한 method는 ModuleNamespaceCreate에 의해 installed됩니다.

Module namespace exotic objectTable 29에 정의된 internal slot을 가집니다.

Table 29: Internal Slots of Module Namespace Exotic Objects
Internal Slot Type Description
[[Module]] a Module Record 이 namespace가 expose하는 export를 가진 Module Record입니다.
[[Exports]] a List of Strings 이 object의 own property로 exposed되는 exported name의 String value를 element로 가지는 List입니다. list는 lexicographic code unit order에 따라 sorted됩니다.

10.4.6.1 [[GetPrototypeOf]] ( )

The [[GetPrototypeOf]] internal method of a module namespace exotic object takes no arguments and returns a normal completion containing null. It performs the following steps when called:

  1. null을 반환한다.

10.4.6.2 [[SetPrototypeOf]] ( proto )

The [[SetPrototypeOf]] internal method of a module namespace exotic object obj takes argument proto (an Object or null) and returns a normal completion containing a Boolean. It performs the following steps when called:

  1. SetImmutablePrototype(obj, proto)를 반환한다.

10.4.6.3 [[IsExtensible]] ( )

The [[IsExtensible]] internal method of a module namespace exotic object takes no arguments and returns a normal completion containing false. It performs the following steps when called:

  1. false를 반환한다.

10.4.6.4 [[PreventExtensions]] ( )

The [[PreventExtensions]] internal method of a module namespace exotic object takes no arguments and returns a normal completion containing true. It performs the following steps when called:

  1. true를 반환한다.

10.4.6.5 [[GetOwnProperty]] ( propertyKey )

The [[GetOwnProperty]] internal method of a module namespace exotic object obj takes argument propertyKey (a property key) and returns either a normal completion containing either a Property Descriptor or undefined, or a throw completion. It performs the following steps when called:

  1. propertyKey가 Symbol이면, OrdinaryGetOwnProperty(obj, propertyKey)를 반환한다.
  2. exportsobj.[[Exports]]로 둔다.
  3. exportspropertyKey를 contain하지 않으면, undefined를 반환한다.
  4. value를 ? obj.[[Get]](propertyKey, obj)로 둔다.
  5. PropertyDescriptor { [[Value]]: value, [[Writable]]: true, [[Enumerable]]: true, [[Configurable]]: false }를 반환한다.

10.4.6.6 [[DefineOwnProperty]] ( propertyKey, propertyDesc )

The [[DefineOwnProperty]] internal method of a module namespace exotic object obj takes arguments propertyKey (a property key) and propertyDesc (a Property Descriptor) and returns either a normal completion containing a Boolean or a throw completion. It performs the following steps when called:

  1. propertyKey가 Symbol이면, ! OrdinaryDefineOwnProperty(obj, propertyKey, propertyDesc)를 반환한다.
  2. current를 ? obj.[[GetOwnProperty]](propertyKey)로 둔다.
  3. currentundefined이면, false를 반환한다.
  4. propertyDesc[[Configurable]] field를 가지고 propertyDesc.[[Configurable]]true이면, false를 반환한다.
  5. propertyDesc[[Enumerable]] field를 가지고 propertyDesc.[[Enumerable]]false이면, false를 반환한다.
  6. IsAccessorDescriptor(propertyDesc)가 true이면, false를 반환한다.
  7. propertyDesc[[Writable]] field를 가지고 propertyDesc.[[Writable]]false이면, false를 반환한다.
  8. propertyDesc[[Value]] field를 가지면, SameValue(propertyDesc.[[Value]], current.[[Value]])를 반환한다.
  9. true를 반환한다.

10.4.6.7 [[HasProperty]] ( propertyKey )

The [[HasProperty]] internal method of a module namespace exotic object obj takes argument propertyKey (a property key) and returns a normal completion containing a Boolean. It performs the following steps when called:

  1. propertyKey가 Symbol이면, ! OrdinaryHasProperty(obj, propertyKey)를 반환한다.
  2. exportsobj.[[Exports]]로 둔다.
  3. exportspropertyKey를 contain하면, true를 반환한다.
  4. false를 반환한다.

10.4.6.8 [[Get]] ( propertyKey, receiver )

The [[Get]] internal method of a module namespace exotic object obj takes arguments propertyKey (a property key) and receiver (an ECMAScript language value) and returns either a normal completion containing an ECMAScript language value or a throw completion. It performs the following steps when called:

  1. propertyKey가 Symbol이면, 다음을 수행한다.
    1. OrdinaryGet(obj, propertyKey, receiver)를 반환한다.
  2. exportsobj.[[Exports]]로 둔다.
  3. exportspropertyKey를 contain하지 않으면, undefined를 반환한다.
  4. moduleobj.[[Module]]로 둔다.
  5. bindingmodule.ResolveExport(propertyKey)로 둔다.
  6. Assert: bindingResolvedBinding Record이다.
  7. targetModulebinding.[[Module]]로 둔다.
  8. Assert: targetModuleundefined가 아니다.
  9. binding.[[BindingName]]namespace이면, 다음을 수행한다.
    1. GetModuleNamespace(targetModule)를 반환한다.
  10. targetEnvtargetModule.[[Environment]]로 둔다.
  11. targetEnvempty이면, ReferenceError exception을 throw한다.
  12. targetEnv.GetBindingValue(binding.[[BindingName]], true)를 반환한다.
Note

ResolveExport는 side-effect free입니다. 이 operation이 specific exportName, resolveSet pair를 argument로 called될 때마다 같은 result를 반환해야 합니다. implementation은 각 module namespace exotic object[[Exports]]에 대한 ResolveExport result를 pre-compute하거나 cache하도록 choose할 수 있습니다.

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

The [[Set]] internal method of a module namespace exotic object takes arguments propertyKey (a property key), value (an ECMAScript language value), and receiver (an ECMAScript language value) and returns a normal completion containing false. It performs the following steps when called:

  1. false를 반환한다.

10.4.6.10 [[Delete]] ( propertyKey )

The [[Delete]] internal method of a module namespace exotic object obj takes argument propertyKey (a property key) and returns a normal completion containing a Boolean. It performs the following steps when called:

  1. propertyKey가 Symbol이면, 다음을 수행한다.
    1. OrdinaryDelete(obj, propertyKey)를 반환한다.
  2. exportsobj.[[Exports]]로 둔다.
  3. exportspropertyKey를 contain하면, false를 반환한다.
  4. true를 반환한다.

10.4.6.11 [[OwnPropertyKeys]] ( )

The [[OwnPropertyKeys]] internal method of a module namespace exotic object obj takes no arguments and returns a normal completion containing a List of property keys. It performs the following steps when called:

  1. exportsobj.[[Exports]]로 둔다.
  2. symbolKeysOrdinaryOwnPropertyKeys(obj)로 둔다.
  3. exportssymbolKeyslist-concatenation을 반환한다.

10.4.6.12 ModuleNamespaceCreate ( module, exports )

The abstract operation ModuleNamespaceCreate takes arguments module (a Module Record) and exports (a List of Strings) and returns a module namespace exotic object. 새 module namespace exotic object의 creation을 specify하는 데 사용됩니다. It performs the following steps when called:

  1. Assert: module.[[Namespace]]empty이다.
  2. internalSlotsListTable 29에 listed된 internal slot으로 둔다.
  3. namespaceMakeBasicObject(internalSlotsList)로 둔다.
  4. namespace의 essential internal method를 10.4.6에 specified된 definition으로 설정한다.
  5. namespace.[[Module]]module로 설정한다.
  6. sortedExportsexports의 element를 element로 가지고 lexicographic code unit order에 따라 sorted된 List로 둔다.
  7. namespace.[[Exports]]sortedExports로 설정한다.
  8. 28.3의 definition에 corresponding하는 namespace의 own property를 create한다.
  9. module.[[Namespace]]namespace로 설정한다.
  10. namespace를 반환한다.

10.4.7 Immutable Prototype Exotic Objects

immutable prototype exotic object는 initialized된 후 change되지 않는 [[Prototype]] internal slot을 가지는 exotic object입니다.

object의 [[SetPrototypeOf]] internal method가 다음 implementation을 사용하면, 그 object는 immutable prototype exotic object입니다. (그 other essential internal method는 문제의 specific immutable prototype exotic object에 따라 어떤 implementation이든 사용할 수 있습니다.)

Note

다른 exotic object와 달리, immutable prototype exotic object를 위해 provided된 dedicated creation abstract operation은 없습니다. 이는 그것들이 %Object.prototype%host environment에서만 사용되며, host environment에서는 relevant object가 potentially 다른 방식으로도 exotic이므로 자체 dedicated creation operation이 필요하기 때문입니다.

10.4.7.1 [[SetPrototypeOf]] ( proto )

The [[SetPrototypeOf]] internal method of an immutable prototype exotic object obj takes argument proto (an Object or null) and returns either a normal completion containing a Boolean or a throw completion. It performs the following steps when called:

  1. SetImmutablePrototype(obj, proto)를 반환한다.

10.4.7.2 SetImmutablePrototype ( obj, proto )

The abstract operation SetImmutablePrototype takes arguments obj (an Object) and proto (an Object or null) and returns either a normal completion containing a Boolean or a throw completion. It performs the following steps when called:

  1. current를 ? obj.[[GetPrototypeOf]]()로 둔다.
  2. SameValue(proto, current)가 true이면, true를 반환한다.
  3. false를 반환한다.

10.5 Proxy Object Internal Methods and Internal Slots

Proxy object는 essential internal method가 ECMAScript code를 사용하여 partially implemented되는 exotic object입니다. 모든 Proxy object는 [[ProxyHandler]]라는 internal slot을 가집니다. [[ProxyHandler]]의 value는 proxy의 handler object라고 불리는 object 또는 null입니다. handler object의 method(Table 30 참조)는 Proxy object's internal method 중 하나 이상에 대한 implementation을 augment하는 데 사용될 수 있습니다. 모든 Proxy object는 또한 [[ProxyTarget]]이라는 internal slot을 가지며, 그 value는 object 또는 null입니다. 이 object를 proxy의 target object라고 합니다.

object의 essential internal method(applicable하면 [[Call]][[Construct]] 포함)가 이 section의 definition을 사용하면, 그 object는 Proxy exotic object입니다. 이러한 internal method는 ProxyCreate에서 installed됩니다.

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

Proxy object internal method의 implementation을 provide하기 위해 handler method가 called될 때, handler method에는 proxy의 target object가 parameter로 passed됩니다. proxy의 handler object가 모든 essential internal method에 corresponding하는 method를 반드시 가지는 것은 아닙니다. proxy 위에서 internal method를 invoking하면 handler object가 internal trap에 corresponding하는 method를 가지지 않는 경우 proxy의 target object 위의 corresponding internal method가 invoked됩니다.

Proxy object의 [[ProxyHandler]][[ProxyTarget]] internal slot은 object가 created될 때 항상 initialized되며 일반적으로 modified될 수 없습니다. 일부 Proxy object는 subsequently revoked될 수 있도록 허용하는 manner로 created됩니다. proxy가 revoked되면, 그 [[ProxyHandler]][[ProxyTarget]] internal slot은 null로 set되어 이후 그 Proxy object 위의 internal method invocation이 TypeError exception을 throw하게 합니다.

Proxy object는 internal method의 implementation이 arbitrary ECMAScript code에 의해 provided되는 것을 permit하므로, handler method가 6.1.7.3에 정의된 invariant를 violate하는 Proxy object를 define하는 것이 가능합니다. 6.1.7.3에 정의된 internal method invariant 중 일부는 essential integrity invariant입니다. 이러한 invariant는 이 section에 specified된 Proxy object internal method에 의해 explicitly enforced됩니다. ECMAScript implementation은 가능한 모든 invariant violation이 presence하더라도 robust해야 합니다.

다음 algorithm description에서, obj는 ECMAScript Proxy object, propertyKeyproperty key value, value는 임의의 ECMAScript language value, propertyDescProperty Descriptor record라고 가정합니다.

10.5.1 [[GetPrototypeOf]] ( )

The [[GetPrototypeOf]] internal method of a Proxy exotic object obj takes no arguments and returns either a normal completion containing either an Object or null, or a throw completion. It performs the following steps when called:

  1. ValidateNonRevokedProxy(obj)를 수행한다.
  2. targetobj.[[ProxyTarget]]으로 둔다.
  3. handlerobj.[[ProxyHandler]]로 둔다.
  4. Assert: handler는 Object이다.
  5. trap을 ? GetMethod(handler, "getPrototypeOf")로 둔다.
  6. trapundefined이면, 다음을 수행한다.
    1. target.[[GetPrototypeOf]]()를 반환한다.
  7. handlerProto를 ? Call(trap, handler, « target »)로 둔다.
  8. handlerProto가 Object도 아니고 null도 아니면, TypeError exception을 throw한다.
  9. extensibleTarget을 ? IsExtensible(target)으로 둔다.
  10. extensibleTargettrue이면, handlerProto를 반환한다.
  11. targetProto를 ? target.[[GetPrototypeOf]]()로 둔다.
  12. SameValue(handlerProto, targetProto)가 false이면, TypeError exception을 throw한다.
  13. handlerProto를 반환한다.
Note

Proxy object의 [[GetPrototypeOf]]는 다음 invariant를 enforce합니다:

  • [[GetPrototypeOf]]의 result는 Object 또는 null이어야 합니다.
  • target object가 extensible이 아니면, Proxy object에 applied된 [[GetPrototypeOf]]는 Proxy object's target object에 applied된 [[GetPrototypeOf]]와 같은 value를 반환해야 합니다.

10.5.2 [[SetPrototypeOf]] ( proto )

The [[SetPrototypeOf]] internal method of a Proxy exotic object obj takes argument proto (an Object or null) and returns either a normal completion containing a Boolean or a throw completion. It performs the following steps when called:

  1. ValidateNonRevokedProxy(obj)를 수행한다.
  2. targetobj.[[ProxyTarget]]으로 둔다.
  3. handlerobj.[[ProxyHandler]]로 둔다.
  4. Assert: handler는 Object이다.
  5. trap을 ? GetMethod(handler, "setPrototypeOf")로 둔다.
  6. trapundefined이면, 다음을 수행한다.
    1. target.[[SetPrototypeOf]](proto)를 반환한다.
  7. boolTrapResultToBoolean(? Call(trap, handler, « target, proto »))로 둔다.
  8. boolTrapResultfalse이면, false를 반환한다.
  9. extensibleTarget을 ? IsExtensible(target)으로 둔다.
  10. extensibleTargettrue이면, true를 반환한다.
  11. targetProto를 ? target.[[GetPrototypeOf]]()로 둔다.
  12. SameValue(proto, targetProto)가 false이면, TypeError exception을 throw한다.
  13. true를 반환한다.
Note

Proxy object의 [[SetPrototypeOf]]는 다음 invariant를 enforce합니다:

  • [[SetPrototypeOf]]의 result는 Boolean value입니다.
  • target object가 extensible이 아니면, argument value는 target object에 applied된 [[GetPrototypeOf]]의 result와 같아야 합니다.

10.5.3 [[IsExtensible]] ( )

The [[IsExtensible]] internal method of a Proxy exotic object obj takes no arguments and returns either a normal completion containing a Boolean or a throw completion. It performs the following steps when called:

  1. ValidateNonRevokedProxy(obj)를 수행한다.
  2. targetobj.[[ProxyTarget]]으로 둔다.
  3. handlerobj.[[ProxyHandler]]로 둔다.
  4. Assert: handler는 Object이다.
  5. trap을 ? GetMethod(handler, "isExtensible")로 둔다.
  6. trapundefined이면, 다음을 수행한다.
    1. IsExtensible(target)을 반환한다.
  7. boolTrapResultToBoolean(? Call(trap, handler, « target »))로 둔다.
  8. targetResult를 ? IsExtensible(target)으로 둔다.
  9. boolTrapResulttargetResult가 아니면, TypeError exception을 throw한다.
  10. boolTrapResult를 반환한다.
Note

Proxy object의 [[IsExtensible]]는 다음 invariant를 enforce합니다:

  • [[IsExtensible]]의 result는 Boolean value입니다.
  • Proxy object에 applied된 [[IsExtensible]]는 같은 argument로 Proxy object's target object에 applied된 [[IsExtensible]]와 같은 value를 반환해야 합니다.

10.5.4 [[PreventExtensions]] ( )

The [[PreventExtensions]] internal method of a Proxy exotic object obj takes no arguments and returns either a normal completion containing a Boolean or a throw completion. It performs the following steps when called:

  1. ValidateNonRevokedProxy(obj)를 수행한다.
  2. targetobj.[[ProxyTarget]]으로 둔다.
  3. handlerobj.[[ProxyHandler]]로 둔다.
  4. Assert: handler는 Object이다.
  5. trap을 ? GetMethod(handler, "preventExtensions")로 둔다.
  6. trapundefined이면, 다음을 수행한다.
    1. target.[[PreventExtensions]]()를 반환한다.
  7. boolTrapResultToBoolean(? Call(trap, handler, « target »))로 둔다.
  8. boolTrapResulttrue이면, 다음을 수행한다.
    1. extensibleTarget을 ? IsExtensible(target)으로 둔다.
    2. extensibleTargettrue이면, TypeError exception을 throw한다.
  9. boolTrapResult를 반환한다.
Note

Proxy object의 [[PreventExtensions]]는 다음 invariant를 enforce합니다:

  • [[PreventExtensions]]의 result는 Boolean value입니다.
  • Proxy object에 applied된 [[PreventExtensions]]는 Proxy object's target object에 applied된 [[IsExtensible]]false인 경우에만 true를 반환합니다.

10.5.5 [[GetOwnProperty]] ( propertyKey )

The [[GetOwnProperty]] internal method of a Proxy exotic object obj takes argument propertyKey (a property key) and returns either a normal completion containing either a Property Descriptor or undefined, or a throw completion. It performs the following steps when called:

  1. ValidateNonRevokedProxy(obj)를 수행한다.
  2. targetobj.[[ProxyTarget]]으로 둔다.
  3. handlerobj.[[ProxyHandler]]로 둔다.
  4. Assert: handler는 Object이다.
  5. trap을 ? GetMethod(handler, "getOwnPropertyDescriptor")로 둔다.
  6. trapundefined이면, 다음을 수행한다.
    1. target.[[GetOwnProperty]](propertyKey)를 반환한다.
  7. trapResultObj를 ? Call(trap, handler, « target, propertyKey »)로 둔다.
  8. trapResultObj가 Object도 아니고 undefined도 아니면, TypeError exception을 throw한다.
  9. targetDesc를 ? target.[[GetOwnProperty]](propertyKey)로 둔다.
  10. trapResultObjundefined이면, 다음을 수행한다.
    1. targetDescundefined이면, undefined를 반환한다.
    2. targetDesc.[[Configurable]]false이면, TypeError exception을 throw한다.
    3. extensibleTarget을 ? IsExtensible(target)으로 둔다.
    4. extensibleTargetfalse이면, TypeError exception을 throw한다.
    5. undefined를 반환한다.
  11. extensibleTarget을 ? IsExtensible(target)으로 둔다.
  12. resultDesc를 ? ToPropertyDescriptor(trapResultObj)로 둔다.
  13. CompletePropertyDescriptor(resultDesc)를 수행한다.
  14. validIsCompatiblePropertyDescriptor(extensibleTarget, resultDesc, targetDesc)로 둔다.
  15. validfalse이면, TypeError exception을 throw한다.
  16. resultDesc.[[Configurable]]false이면, 다음을 수행한다.
    1. targetDescundefined이거나 targetDesc.[[Configurable]]true이면, 다음을 수행한다.
      1. TypeError exception을 throw한다.
    2. resultDesc[[Writable]] field를 가지고 resultDesc.[[Writable]]false이면, 다음을 수행한다.
      1. Assert: targetDesc[[Writable]] field를 가진다.
      2. targetDesc.[[Writable]]true이면, TypeError exception을 throw한다.
  17. resultDesc를 반환한다.
Note

Proxy object의 [[GetOwnProperty]]는 다음 invariant를 enforce합니다:

  • [[GetOwnProperty]]의 result는 Property Descriptor 또는 undefined여야 합니다.
  • property가 target object의 non-configurable own property로 존재하면, 그 property를 non-existent로 report할 수 없습니다.
  • property가 non-extensible target object의 own property로 존재하면, 그 property를 non-existent로 report할 수 없습니다.
  • property가 target object의 own property로 존재하지 않고 target object가 extensible이 아니면, 그 property를 existent로 report할 수 없습니다.
  • target object의 non-configurable own property로 존재하지 않는 한, property를 non-configurable로 report할 수 없습니다.
  • target object의 non-configurable, non-writable own property로 존재하지 않는 한, property를 non-configurable이면서 non-writable로 report할 수 없습니다.

10.5.6 [[DefineOwnProperty]] ( propertyKey, propertyDesc )

The [[DefineOwnProperty]] internal method of a Proxy exotic object obj takes arguments propertyKey (a property key) and propertyDesc (a Property Descriptor) and returns either a normal completion containing a Boolean or a throw completion. It performs the following steps when called:

  1. ValidateNonRevokedProxy(obj)를 수행한다.
  2. targetobj.[[ProxyTarget]]으로 둔다.
  3. handlerobj.[[ProxyHandler]]로 둔다.
  4. Assert: handler는 Object이다.
  5. trap을 ? GetMethod(handler, "defineProperty")로 둔다.
  6. trapundefined이면, 다음을 수행한다.
    1. target.[[DefineOwnProperty]](propertyKey, propertyDesc)를 반환한다.
  7. propertyDescObjFromPropertyDescriptor(propertyDesc)로 둔다.
  8. boolTrapResultToBoolean(? Call(trap, handler, « target, propertyKey, propertyDescObj »))로 둔다.
  9. boolTrapResultfalse이면, false를 반환한다.
  10. targetDesc를 ? target.[[GetOwnProperty]](propertyKey)로 둔다.
  11. extensibleTarget을 ? IsExtensible(target)으로 둔다.
  12. propertyDesc[[Configurable]] field를 가지고 propertyDesc.[[Configurable]]false이면, 다음을 수행한다.
    1. settingConfigFalsetrue로 둔다.
  13. 그렇지 않으면,
    1. settingConfigFalsefalse로 둔다.
  14. targetDescundefined이면, 다음을 수행한다.
    1. extensibleTargetfalse이면, TypeError exception을 throw한다.
    2. settingConfigFalsetrue이면, TypeError exception을 throw한다.
  15. 그렇지 않으면,
    1. IsCompatiblePropertyDescriptor(extensibleTarget, propertyDesc, targetDesc)가 false이면, TypeError exception을 throw한다.
    2. settingConfigFalsetrue이고 targetDesc.[[Configurable]]true이면, TypeError exception을 throw한다.
    3. IsDataDescriptor(targetDesc)가 true이고, targetDesc.[[Configurable]]false이고, targetDesc.[[Writable]]true이면, 다음을 수행한다.
      1. propertyDesc[[Writable]] field를 가지고 propertyDesc.[[Writable]]false이면, TypeError exception을 throw한다.
  16. true를 반환한다.
Note

Proxy object의 [[DefineOwnProperty]]는 다음 invariant를 enforce합니다:

  • [[DefineOwnProperty]]의 result는 Boolean value입니다.
  • target object가 extensible이 아니면 property를 added할 수 없습니다.
  • target object의 corresponding non-configurable own property가 존재하지 않는 한 property는 non-configurable일 수 없습니다.
  • target object의 corresponding non-configurable, non-writable own property가 존재하지 않는 한 non-configurable property는 non-writable일 수 없습니다.
  • property가 corresponding target object property를 가지면, [[DefineOwnProperty]]를 사용하여 그 property의 Property Descriptor를 target object에 applying해도 exception을 throw하지 않습니다.

10.5.7 [[HasProperty]] ( propertyKey )

The [[HasProperty]] internal method of a Proxy exotic object obj takes argument propertyKey (a property key) and returns either a normal completion containing a Boolean or a throw completion. It performs the following steps when called:

  1. ValidateNonRevokedProxy(obj)를 수행한다.
  2. targetobj.[[ProxyTarget]]으로 둔다.
  3. handlerobj.[[ProxyHandler]]로 둔다.
  4. Assert: handler는 Object이다.
  5. trap을 ? GetMethod(handler, "has")로 둔다.
  6. trapundefined이면, 다음을 수행한다.
    1. target.[[HasProperty]](propertyKey)를 반환한다.
  7. boolTrapResultToBoolean(? Call(trap, handler, « target, propertyKey »))로 둔다.
  8. boolTrapResultfalse이면, 다음을 수행한다.
    1. targetDesc를 ? target.[[GetOwnProperty]](propertyKey)로 둔다.
    2. targetDescundefined가 아니면, 다음을 수행한다.
      1. targetDesc.[[Configurable]]false이면, TypeError exception을 throw한다.
      2. extensibleTarget을 ? IsExtensible(target)으로 둔다.
      3. extensibleTargetfalse이면, TypeError exception을 throw한다.
  9. boolTrapResult를 반환한다.
Note

Proxy object의 [[HasProperty]]는 다음 invariant를 enforce합니다:

  • [[HasProperty]]의 result는 Boolean value입니다.
  • property가 target object의 non-configurable own property로 존재하면, 그 property를 non-existent로 report할 수 없습니다.
  • property가 target object의 own property로 존재하고 target object가 extensible이 아니면, 그 property를 non-existent로 report할 수 없습니다.

10.5.8 [[Get]] ( propertyKey, receiver )

The [[Get]] internal method of a Proxy exotic object obj takes arguments propertyKey (a property key) and receiver (an ECMAScript language value) and returns either a normal completion containing an ECMAScript language value or a throw completion. It performs the following steps when called:

  1. ValidateNonRevokedProxy(obj)를 수행한다.
  2. targetobj.[[ProxyTarget]]으로 둔다.
  3. handlerobj.[[ProxyHandler]]로 둔다.
  4. Assert: handler는 Object이다.
  5. trap을 ? GetMethod(handler, "get")로 둔다.
  6. trapundefined이면, 다음을 수행한다.
    1. target.[[Get]](propertyKey, receiver)를 반환한다.
  7. trapResult를 ? Call(trap, handler, « target, propertyKey, receiver »)로 둔다.
  8. targetDesc를 ? target.[[GetOwnProperty]](propertyKey)로 둔다.
  9. targetDescundefined가 아니고 targetDesc.[[Configurable]]false이면, 다음을 수행한다.
    1. IsDataDescriptor(targetDesc)가 true이고 targetDesc.[[Writable]]false이면, 다음을 수행한다.
      1. SameValue(trapResult, targetDesc.[[Value]])가 false이면, TypeError exception을 throw한다.
    2. IsAccessorDescriptor(targetDesc)가 true이고 targetDesc.[[Get]]undefined이면, 다음을 수행한다.
      1. trapResultundefined가 아니면, TypeError exception을 throw한다.
  10. trapResult를 반환한다.
Note

Proxy object의 [[Get]]은 다음 invariant를 enforce합니다:

  • target object property가 non-writable, non-configurable own data property이면, property에 대해 reported된 value는 corresponding target object property의 value와 같아야 합니다.
  • corresponding target object property가 [[Get]] attribute로 undefined를 가지는 non-configurable own accessor property이면, property에 대해 reported된 value는 undefined여야 합니다.

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

The [[Set]] internal method of a Proxy exotic object obj takes arguments propertyKey (a property key), value (an ECMAScript language value), and receiver (an ECMAScript language value) and returns either a normal completion containing a Boolean or a throw completion. It performs the following steps when called:

  1. ValidateNonRevokedProxy(obj)를 수행한다.
  2. targetobj.[[ProxyTarget]]으로 둔다.
  3. handlerobj.[[ProxyHandler]]로 둔다.
  4. Assert: handler는 Object이다.
  5. trap을 ? GetMethod(handler, "set")로 둔다.
  6. trapundefined이면, 다음을 수행한다.
    1. target.[[Set]](propertyKey, value, receiver)를 반환한다.
  7. boolTrapResultToBoolean(? Call(trap, handler, « target, propertyKey, value, receiver »))로 둔다.
  8. boolTrapResultfalse이면, false를 반환한다.
  9. targetDesc를 ? target.[[GetOwnProperty]](propertyKey)로 둔다.
  10. targetDescundefined가 아니고 targetDesc.[[Configurable]]false이면, 다음을 수행한다.
    1. IsDataDescriptor(targetDesc)가 true이고 targetDesc.[[Writable]]false이면, 다음을 수행한다.
      1. SameValue(value, targetDesc.[[Value]])가 false이면, TypeError exception을 throw한다.
    2. IsAccessorDescriptor(targetDesc)가 true이면, 다음을 수행한다.
      1. targetDesc.[[Set]]undefined이면, TypeError exception을 throw한다.
  11. true를 반환한다.
Note

Proxy object의 [[Set]]은 다음 invariant를 enforce합니다:

  • [[Set]]의 result는 Boolean value입니다.
  • corresponding target object property가 non-writable, non-configurable own data property이면, property의 value를 corresponding target object property의 value와 다르게 change할 수 없습니다.
  • corresponding target object property가 [[Set]] attribute로 undefined를 가지는 non-configurable own accessor property이면, property의 value를 set할 수 없습니다.

10.5.10 [[Delete]] ( propertyKey )

The [[Delete]] internal method of a Proxy exotic object obj takes argument propertyKey (a property key) and returns either a normal completion containing a Boolean or a throw completion. It performs the following steps when called:

  1. ValidateNonRevokedProxy(obj)를 수행한다.
  2. targetobj.[[ProxyTarget]]으로 둔다.
  3. handlerobj.[[ProxyHandler]]로 둔다.
  4. Assert: handler는 Object이다.
  5. trap을 ? GetMethod(handler, "deleteProperty")로 둔다.
  6. trapundefined이면, 다음을 수행한다.
    1. target.[[Delete]](propertyKey)를 반환한다.
  7. boolTrapResultToBoolean(? Call(trap, handler, « target, propertyKey »))로 둔다.
  8. boolTrapResultfalse이면, false를 반환한다.
  9. targetDesc를 ? target.[[GetOwnProperty]](propertyKey)로 둔다.
  10. targetDescundefined이면, true를 반환한다.
  11. targetDesc.[[Configurable]]false이면, TypeError exception을 throw한다.
  12. extensibleTarget을 ? IsExtensible(target)으로 둔다.
  13. extensibleTargetfalse이면, TypeError exception을 throw한다.
  14. true를 반환한다.
Note

Proxy object의 [[Delete]]는 다음 invariant를 enforce합니다:

  • [[Delete]]의 result는 Boolean value입니다.
  • property가 target object의 non-configurable own property로 존재하면, 그 property를 deleted된 것으로 report할 수 없습니다.
  • property가 target object의 own property로 존재하고 target object가 non-extensible이면, 그 property를 deleted된 것으로 report할 수 없습니다.

10.5.11 [[OwnPropertyKeys]] ( )

The [[OwnPropertyKeys]] internal method of a Proxy exotic object obj takes no arguments and returns either a normal completion containing a List of property keys or a throw completion. It performs the following steps when called:

  1. ValidateNonRevokedProxy(obj)를 수행한다.
  2. targetobj.[[ProxyTarget]]으로 둔다.
  3. handlerobj.[[ProxyHandler]]로 둔다.
  4. Assert: handler는 Object이다.
  5. trap을 ? GetMethod(handler, "ownKeys")로 둔다.
  6. trapundefined이면, 다음을 수행한다.
    1. target.[[OwnPropertyKeys]]()를 반환한다.
  7. trapResultArray를 ? Call(trap, handler, « target »)로 둔다.
  8. trapResult를 ? CreateListFromArrayLike(trapResultArray, property-key)로 둔다.
  9. trapResult가 duplicate entry를 contain하면, TypeError exception을 throw한다.
  10. extensibleTarget을 ? IsExtensible(target)으로 둔다.
  11. targetKeys를 ? target.[[OwnPropertyKeys]]()로 둔다.
  12. Assert: targetKeysproperty keyList이다.
  13. Assert: targetKeys는 duplicate entry를 contain하지 않는다.
  14. targetConfigurableKeys를 새 empty List로 둔다.
  15. targetNonconfigurableKeys를 새 empty List로 둔다.
  16. targetKeys의 각 element key에 대해, 다음을 수행한다.
    1. propertyDesc를 ? target.[[GetOwnProperty]](key)로 둔다.
    2. propertyDescundefined가 아니고 propertyDesc.[[Configurable]]false이면, 다음을 수행한다.
      1. keytargetNonconfigurableKeys에 append한다.
    3. 그렇지 않으면,
      1. keytargetConfigurableKeys에 append한다.
  17. extensibleTargettrue이고 targetNonconfigurableKeys가 empty이면, 다음을 수행한다.
    1. trapResult를 반환한다.
  18. uncheckedResultKeys를 element가 trapResult의 element인 List로 둔다.
  19. targetNonconfigurableKeys의 각 element key에 대해, 다음을 수행한다.
    1. uncheckedResultKeyskey를 contain하지 않으면, TypeError exception을 throw한다.
    2. uncheckedResultKeys에서 key를 remove한다.
  20. extensibleTargettrue이면, trapResult를 반환한다.
  21. targetConfigurableKeys의 각 element key에 대해, 다음을 수행한다.
    1. uncheckedResultKeyskey를 contain하지 않으면, TypeError exception을 throw한다.
    2. uncheckedResultKeys에서 key를 remove한다.
  22. uncheckedResultKeys가 empty가 아니면, TypeError exception을 throw한다.
  23. trapResult를 반환한다.
Note

Proxy object의 [[OwnPropertyKeys]]는 다음 invariant를 enforce합니다:

  • [[OwnPropertyKeys]]의 result는 List입니다.
  • returned List는 duplicate entry를 contain하지 않습니다.
  • returned List의 각 element는 property key입니다.
  • result List는 target object의 모든 non-configurable own property의 key를 contain해야 합니다.
  • target object가 extensible이 아니면, result List는 target object의 own property의 모든 key를 contain해야 하며 다른 value는 contain하지 않아야 합니다.

10.5.12 [[Call]] ( thisArg, argList )

The [[Call]] internal method of a Proxy exotic object obj takes arguments thisArg (an ECMAScript language value) and argList (a List of ECMAScript language values) and returns either a normal completion containing an ECMAScript language value or a throw completion. It performs the following steps when called:

  1. ValidateNonRevokedProxy(obj)를 수행한다.
  2. targetobj.[[ProxyTarget]]으로 둔다.
  3. handlerobj.[[ProxyHandler]]로 둔다.
  4. Assert: handler는 Object이다.
  5. trap을 ? GetMethod(handler, "apply")로 둔다.
  6. trapundefined이면, 다음을 수행한다.
    1. Call(target, thisArg, argList)를 반환한다.
  7. argArrayCreateArrayFromList(argList)로 둔다.
  8. Call(trap, handler, « target, thisArg, argArray »)를 반환한다.
Note

Proxy exotic object는 그 [[ProxyTarget]] internal slot의 initial value가 [[Call]] internal method를 가지는 object인 경우에만 [[Call]] internal method를 가집니다.

10.5.13 [[Construct]] ( argList, newTarget )

The [[Construct]] internal method of a Proxy exotic object obj takes arguments argList (a List of ECMAScript language values) and newTarget (a constructor) and returns either a normal completion containing an Object or a throw completion. It performs the following steps when called:

  1. ValidateNonRevokedProxy(obj)를 수행한다.
  2. targetobj.[[ProxyTarget]]으로 둔다.
  3. Assert: IsConstructor(target)은 true이다.
  4. handlerobj.[[ProxyHandler]]로 둔다.
  5. Assert: handler는 Object이다.
  6. trap을 ? GetMethod(handler, "construct")로 둔다.
  7. trapundefined이면, 다음을 수행한다.
    1. Construct(target, argList, newTarget)를 반환한다.
  8. argArrayCreateArrayFromList(argList)로 둔다.
  9. newObj를 ? Call(trap, handler, « target, argArray, newTarget »)로 둔다.
  10. newObj가 Object가 아니면, TypeError exception을 throw한다.
  11. newObj를 반환한다.
Note 1

Proxy exotic object는 그 [[ProxyTarget]] internal slot의 initial value가 [[Construct]] internal method를 가지는 object인 경우에만 [[Construct]] internal method를 가집니다.

Note 2

Proxy object의 [[Construct]]는 다음 invariant를 enforce합니다:

  • [[Construct]]의 result는 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 exception을 throw합니다. It performs the following steps when called:

  1. proxy.[[ProxyTarget]]null이면, TypeError exception을 throw한다.
  2. Assert: proxy.[[ProxyHandler]]null이 아니다.
  3. unused를 반환한다.

10.5.15 ProxyCreate ( target, handler )

The abstract operation ProxyCreate takes arguments target (an ECMAScript language value) and handler (an ECMAScript language value) and returns either a normal completion containing a Proxy exotic object or a throw completion. 새 Proxy object의 creation을 specify하는 데 사용됩니다. It performs the following steps when called:

  1. target이 Object가 아니면, TypeError 예외를 던진다.
  2. handler가 Object가 아니면, TypeError 예외를 던진다.
  3. proxyMakeBasicObject[[ProxyHandler]], [[ProxyTarget]] »)라고 하자.
  4. , [[Call]][[Construct]]를 제외한 proxy의 필수 내부 메서드를 10.5에 명시된 정의로 설정한다.
  5. IsCallable(target)이 true이면,
    1. proxy.[[Call]]10.5.12에 명시된 대로 설정한다.
    2. IsConstructor(target)가 true이면,
      1. proxy.[[Construct]]10.5.13에 명시된 대로 설정한다.
  6. proxy.[[ProxyTarget]]target으로 설정한다.
  7. proxy.[[ProxyHandler]]handler로 설정한다.
  8. proxy를 반환한다.

11 ECMAScript 언어: Source Text

11.1 Source Text

Syntax

SourceCharacter :: any Unicode code point

ECMAScript source text는 Unicode code point의 sequence입니다. surrogate code point를 포함하여 U+0000부터 U+10FFFF까지의 모든 Unicode code point value는 ECMAScript grammar가 허용하는 곳에서 ECMAScript source text에 occur할 수 있습니다. ECMAScript source text를 store하고 interchange하는 데 사용되는 actual encoding은 이 명세와 관련이 없습니다. external source text encoding과 관계없이, conforming ECMAScript implementation은 source text를 equivalent한 SourceCharacter value의 sequence인 것처럼 process하며, 각 SourceCharacter는 Unicode code point입니다. Conforming ECMAScript implementation은 source text의 normalization을 수행하거나, source text의 normalization을 수행하는 것처럼 behave할 필요가 없습니다.

combining character sequence의 component는 user가 전체 sequence를 single character로 생각할 수 있더라도 individual Unicode code point로 treated됩니다.

Note

string literal, regular expression literal, template literal 및 identifier 안에서는 어떤 Unicode code point든 code point의 numeric value를 explicitly express하는 Unicode escape sequence를 사용하여 표현할 수도 있습니다. comment 안에서는 그러한 escape sequence가 comment의 part로 effectively ignored됩니다.

ECMAScript는 Unicode escape sequence의 behaviour에서 Java programming language와 다릅니다. Java program에서는 예를 들어 Unicode escape sequence \u000A가 single-line comment 안에 occur하면, line terminator(Unicode code point U+000A는 LINE FEED (LF))로 interpreted되므로 다음 code point는 comment의 part가 아닙니다. 마찬가지로 Unicode escape sequence \u000A가 Java program의 string literal 안에 occur하면, 역시 line terminator로 interpreted되며, 이는 string literal 안에서 allowed되지 않습니다 — string literal의 value의 part로 LINE FEED (LF)를 cause하려면 \u000A 대신 \n을 써야 합니다. ECMAScript program에서는 comment 안에 occur하는 Unicode escape sequence가 never interpreted되므로 comment의 termination에 contribute할 수 없습니다. 마찬가지로 ECMAScript program의 string literal 안에 occur하는 Unicode escape sequence는 항상 literal에 contribute하며 line terminator로 또는 string literal을 terminate할 수 있는 code point로 never interpreted되지 않습니다.

11.1.1 Static Semantics: UTF16EncodeCodePoint ( codePoint )

The abstract operation UTF16EncodeCodePoint takes argument codePoint (a Unicode code point) and returns a String. It performs the following steps when called:

  1. Assert: 0 ≤ codePoint ≤ 0x10FFFF.
  2. codePoint ≤ 0xFFFF이면, numeric value가 codePoint인 code unit으로 구성된 String value를 반환한다.
  3. cu1을 numeric value가 floor((codePoint - 0x10000) / 0x400) + 0xD800인 code unit으로 둔다.
  4. cu2를 numeric value가 ((codePoint - 0x10000) modulo 0x400) + 0xDC00인 code unit으로 둔다.
  5. cu1cu2string-concatenation을 반환한다.

11.1.2 Static Semantics: CodePointsToString ( text )

The abstract operation CodePointsToString takes argument text (a sequence of Unicode code points) and returns a String. 6.1.4에 described된 대로 text를 String value로 convert합니다. It performs the following steps when called:

  1. result를 empty String으로 둔다.
  2. text의 각 code point codePoint에 대해, 다음을 수행한다.
    1. resultresultUTF16EncodeCodePoint(codePoint)의 string-concatenation으로 설정한다.
  3. result를 반환한다.

11.1.3 Static Semantics: UTF16SurrogatePairToCodePoint ( lead, trail )

The abstract operation UTF16SurrogatePairToCodePoint takes arguments lead (a code unit) and trail (a code unit) and returns a code point. UTF-16 surrogate pair를 form하는 두 code unit이 code point로 converted됩니다. It performs the following steps when called:

  1. Assert: leadleading surrogate이고 trailtrailing surrogate이다.
  2. codePoint를 (lead - 0xD800) × 0x400 + (trail - 0xDC00) + 0x10000으로 둔다.
  3. code point codePoint를 반환한다.

11.1.4 Static Semantics: CodePointAt ( string, position )

The abstract operation CodePointAt takes arguments string (a String) and position (a non-negative integer) and returns a Record with fields [[CodePoint]] (a code point), [[CodeUnitCount]] (a positive integer), and [[IsUnpairedSurrogate]] (a Boolean). 6.1.4에 described된 대로 string을 UTF-16 encoded code point의 sequence로 interpret하고, index position의 code unit부터 시작하여 single code point를 read합니다. It performs the following steps when called:

  1. sizestring의 length로 둔다.
  2. Assert: position ≥ 0이고 position < size이다.
  3. firststring 안의 index position에 있는 code unit으로 둔다.
  4. codePoint를 numeric value가 first의 numeric value인 code point로 둔다.
  5. firstleading surrogatetrailing surrogate도 아니면, 다음을 수행한다.
    1. Record { [[CodePoint]]: codePoint, [[CodeUnitCount]]: 1, [[IsUnpairedSurrogate]]: false }를 반환한다.
  6. firsttrailing surrogate이거나 position + 1 = size이면, 다음을 수행한다.
    1. Record { [[CodePoint]]: codePoint, [[CodeUnitCount]]: 1, [[IsUnpairedSurrogate]]: true }를 반환한다.
  7. secondstring 안의 index position + 1에 있는 code unit으로 둔다.
  8. secondtrailing surrogate가 아니면, 다음을 수행한다.
    1. Record { [[CodePoint]]: codePoint, [[CodeUnitCount]]: 1, [[IsUnpairedSurrogate]]: true }를 반환한다.
  9. codePointUTF16SurrogatePairToCodePoint(first, second)로 설정한다.
  10. Record { [[CodePoint]]: codePoint, [[CodeUnitCount]]: 2, [[IsUnpairedSurrogate]]: false }를 반환한다.

11.1.5 Static Semantics: StringToCodePoints ( string )

The abstract operation StringToCodePoints takes argument string (a String) and returns a List of code points. 6.1.4에 described된 대로 string을 UTF-16 encoded Unicode text로 interpreting한 결과인 Unicode code point의 sequence를 반환합니다. It performs the following steps when called:

  1. codePoints를 새 empty List로 둔다.
  2. sizestring의 length로 둔다.
  3. position을 0으로 둔다.
  4. position < size인 동안 Repeat,
    1. codePointCodePointAt(string, position)으로 둔다.
    2. codePoint.[[CodePoint]]codePoints에 append한다.
    3. positionposition + codePoint.[[CodeUnitCount]]로 설정한다.
  5. codePoints를 반환한다.

11.1.6 Static Semantics: ParseText ( sourceText, goalSymbol )

The abstract operation ParseText takes arguments sourceText (a String or a sequence of Unicode code points) and goalSymbol (a nonterminal in one of the ECMAScript grammars) and returns a Parse Node or a non-empty List of SyntaxError objects. It performs the following steps when called:

  1. sourceText가 String이면, sourceTextStringToCodePoints(sourceText)로 설정한다.
  2. goalSymbolgoal symbol로 사용하여 sourceText를 parse하려고 attempt하고, parse result를 early error condition이 있는지 analyse한다. Parsing과 early error detection은 implementation-defined manner로 interleaved될 수 있다.
  3. parse가 succeeded하고 early error가 발견되지 않았으면, parse의 result로 생긴 parse tree의 root에 있는 Parse Node(goalSymbol의 instance)를 반환한다.
  4. parsing error 및/또는 early error를 represent하는 하나 이상의 SyntaxError object의 List를 반환한다. 둘 이상의 parsing error 또는 early error가 present하면, list 안의 error object의 number와 ordering은 implementation-defined이지만, 적어도 하나는 present해야 한다.
Note 1

particular point에 early error가 있고, later point에도 syntax error가 있는 text를 consider하십시오. parse pass 뒤에 early errors pass를 수행하는 implementation은 syntax error를 report하고 early errors pass로 proceed하지 않을 수 있습니다. 두 activity를 interleave하는 implementation은 early error를 report하고 syntax error를 찾기 위해 proceed하지 않을 수 있습니다. 세 번째 implementation은 두 error를 모두 report할 수 있습니다. 이 모든 behaviour는 conformant입니다.

Note 2

clause 17도 참조하십시오.

11.2 Source Code의 Types

ECMAScript code에는 네 가지 type이 있습니다:

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)의 body로 provided됩니다. 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)에 대한 argument로부터도 derived됩니다.

Note 2

function code에 BindingIdentifier를 포함하는 practical effect는, surrounding code가 strict mode code가 아니더라도, strict mode code의 Early Error가 body가 Use Strict Directive를 contain하는 function의 name인 BindingIdentifier에 applied된다는 것입니다.

11.2.1 Directive Prologues와 Use Strict Directive

Directive PrologueFunctionBody, ScriptBody 또는 ModuleBody의 initial StatementListItem 또는 ModuleItem로 occurring하는 ExpressionStatement의 longest sequence이며, 그 sequence 안의 각 ExpressionStatement는 전적으로 StringLiteral token과 그 뒤의 semicolon으로 구성됩니다. semicolon은 explicitly 나타날 수도 있고 automatic semicolon insertion(12.10)에 의해 inserted될 수도 있습니다. Directive Prologue는 empty sequence일 수 있습니다.

Use Strict DirectiveDirective Prologue 안의 ExpressionStatement 중 그 StringLiteral이 exact code point sequence "use strict" 또는 'use strict'인 것입니다. Use Strict DirectiveEscapeSequence 또는 LineContinuation을 contain할 수 없습니다.

Directive Prologue는 둘 이상의 Use Strict Directive를 contain할 수 있습니다. 그러나 이런 일이 발생하면 implementation은 warning을 issue할 수 있습니다.

Note

Directive PrologueExpressionStatement는 containing production의 evaluation 중에 normally evaluated됩니다. Implementation은 Use Strict Directive가 아니며 Directive Prologue 안에 occur하는 ExpressionStatement에 대해 implementation specific meaning을 define할 수 있습니다. appropriate notification mechanism이 존재하면, implementation은 Directive Prologue 안에서 Use Strict Directive가 아니며 implementation에 의해 정의된 meaning을 가지지 않는 ExpressionStatement를 encounter할 때 warning을 issue해야 합니다.

11.2.2 Strict Mode Code

ECMAScript syntactic unit은 unrestricted 또는 strict mode syntax and semantics(4.3.2)를 사용하여 processed될 수 있습니다. Code는 다음 situation에서 strict mode code로 interpreted됩니다:

strict mode code가 아닌 ECMAScript code를 non-strict code라고 합니다.

11.2.2.1 Static Semantics: IsStrict ( parseNode )

The abstract operation IsStrict takes argument parseNode (a Parse Node) and returns a Boolean. It performs the following steps when called:

  1. parseNode에 matched된 source text가 strict mode code이면, true를 반환한다.
  2. false를 반환한다.

11.2.3 Non-ECMAScript Functions

ECMAScript implementation은 evaluative behaviour가 ECMAScript source text가 아닌 host-defined form의 executable code로 expressed되는 function exotic object의 evaluation을 support할 수 있습니다. function object가 ECMAScript code 안에서 defined되었는지 또는 built-in function인지 여부는 그러한 function object를 call하거나 그러한 function object에 의해 called되는 ECMAScript code의 perspective에서는 observable하지 않습니다.

12 ECMAScript 언어: Lexical Grammar

ECMAScript Script 또는 Module의 source text는 먼저 token, line terminator, comment 또는 white space인 input element의 sequence로 converted됩니다. source text는 left to right로 scanned되며, 가능한 가장 긴 code point sequence를 반복적으로 next input element로 취합니다.

lexical input element의 identification이 input element를 consuming하는 syntactic grammar context에 sensitive한 여러 situation이 있습니다. 이는 lexical grammar에 대해 multiple goal symbol을 require합니다. InputElementHashbangOrRegExp goal은 Script 또는 Module의 start에서 사용됩니다. InputElementRegExpOrTemplateTail goal은 RegularExpressionLiteral, TemplateMiddle 또는 TemplateTail이 permitted되는 syntactic grammar context에서 사용됩니다. InputElementRegExp goal symbolRegularExpressionLiteral은 permitted되지만 TemplateMiddleTemplateTail도 permitted되지 않는 모든 syntactic grammar context에서 사용됩니다. InputElementTemplateTail goal은 TemplateMiddle 또는 TemplateTail은 permitted되지만 RegularExpressionLiteral은 permitted되지 않는 모든 syntactic grammar context에서 사용됩니다. 그 밖의 모든 context에서는 InputElementDiv가 lexical goal symbol로 사용됩니다.

Note

multiple lexical goal의 사용은 automatic semicolon insertion에 영향을 줄 lexical ambiguity가 없음을 ensure합니다. 예를 들어 leading division 또는 division-assignment와 leading RegularExpressionLiteral이 둘 다 permitted되는 syntactic grammar context는 없습니다. 이는 semicolon insertion(12.10 참조)의 영향을 받지 않습니다; 다음과 같은 예에서:

a = b
/hi/g.exec(c).map(d);

LineTerminator 뒤의 first non-whitespace, non-comment code point가 U+002F (SOLIDUS)이고 syntactic context가 division 또는 division-assignment를 allow하면, LineTerminator에서 semicolon은 inserted되지 않습니다. 즉, 위 example은 다음과 같은 방식으로 interpreted됩니다:

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 character(즉, LEFT-TO-RIGHT MARK 또는 RIGHT-TO-LEFT MARK 같은 Unicode Character Database의 category “Cf” 안의 character)는 이를 위한 higher-level protocol(mark-up language 등)이 없을 때 text range의 formatting을 control하는 데 사용되는 control code입니다.

editing과 display를 facilitate하기 위해 source text 안에서 format-control character를 allow하는 것은 useful합니다. 모든 format control character는 comment 안에서, 그리고 string literal, template literal, regular expression literal 안에서 사용될 수 있습니다.

U+FEFF (ZERO WIDTH NO-BREAK SPACE)는 primarily text의 start에서 그것을 Unicode로 mark하고 text의 encoding과 byte order의 detection을 allow하는 데 사용되는 format-control character입니다. 이 purpose로 intended된 <ZWNBSP> character는 때때로 text의 start 뒤에도 나타날 수 있습니다. 예를 들어 file을 concatenating한 result로 그렇습니다. ECMAScript source text에서 <ZWNBSP> code point는 comment, string literal, template literal, regular expression literal 밖에서는 white space character(12.2 참조)로 treated됩니다.

12.2 White Space

White space code point는 source text readability를 improve하고 token(indivisible lexical unit)을 서로 separate하는 데 사용되지만, otherwise insignificant합니다. White space code point는 어떤 두 token 사이에도, input의 start 또는 end에도 occur할 수 있습니다. White space code point는 StringLiteral, RegularExpressionLiteral, Template 또는 TemplateSubstitutionTail 안에서도 occur할 수 있으며, 여기서는 literal value의 part를 forming하는 significant code point로 considered됩니다. 또한 Comment 안에서도 occur할 수 있지만, 그 밖의 어떤 kind의 token 안에는 appear할 수 없습니다.

ECMAScript white space code point는 Table 31에 listed되어 있습니다.

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 point는 <USP>의 part입니다.

Note 2

Table 31에 listed된 code point 외에는, ECMAScript WhiteSpace는 Unicode “White_Space” property를 가지지만 general category “Space_Separator”(“Zs”)로 classified되지 않은 모든 code point를 intentionally excludes합니다.

Syntax

WhiteSpace :: <TAB> <VT> <FF> <ZWNBSP> <USP>

12.3 Line Terminators

white space code point와 마찬가지로, line terminator code point는 source text readability를 improve하고 token(indivisible lexical unit)을 서로 separate하는 데 사용됩니다. 그러나 white space code point와 달리, line terminator는 syntactic grammar의 behaviour에 어느 정도 influence를 가집니다. 일반적으로 line terminator는 어떤 두 token 사이에도 occur할 수 있지만, syntactic grammar에 의해 forbidden되는 몇몇 place가 있습니다. Line terminator는 automatic semicolon insertion(12.10) process에도 affect합니다. line terminator는 StringLiteral, Template 또는 TemplateSubstitutionTail을 제외한 어떤 token 안에도 occur할 수 없습니다. <LF> 및 <CR> line terminator는 LineContinuation의 part인 경우를 제외하고 StringLiteral token 안에 occur할 수 없습니다.

line terminator는 MultiLineComment 안에는 occur할 수 있지만 SingleLineComment 안에는 occur할 수 없습니다.

Line terminator는 regular expression 안의 \s class가 match하는 white space code point의 set에 included됩니다.

ECMAScript line terminator code point는 Table 32에 listed되어 있습니다.

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 point만 line terminator로 treated됩니다. 다른 new line 또는 line breaking Unicode code point는 line terminator로 treated되지 않지만, Table 31에 listed된 requirement를 meet하면 white space로 treated됩니다. sequence <CR><LF>는 commonly line terminator로 사용됩니다. 이는 line number를 reporting하기 위한 purpose에서는 single SourceCharacter로 considered되어야 합니다.

Syntax

LineTerminator :: <LF> <CR> <LS> <PS> LineTerminatorSequence :: <LF> <CR> [lookahead ≠ <LF>] <LS> <PS> <CR> <LF>

12.4 Comments

Comment는 single-line 또는 multi-line일 수 있습니다. Multi-line comment는 nest할 수 없습니다.

single-line comment는 LineTerminator code point를 제외한 어떤 Unicode code point든 contain할 수 있고, token은 항상 가능한 한 길다는 general rule 때문에, single-line comment는 항상 // marker부터 line의 end까지의 모든 code point로 구성됩니다. 그러나 line end의 LineTerminator는 single-line comment의 part로 considered되지 않습니다; 이는 lexical grammar에 의해 separately recognized되고 syntactic grammar를 위한 input element stream의 part가 됩니다. 이 point는 매우 important합니다. 왜냐하면 single-line comment의 presence 또는 absence가 automatic semicolon insertion process에 affect하지 않음을 imply하기 때문입니다(12.10 참조).

Comment는 white space처럼 behave하며 discarded됩니다. 단, MultiLineComment가 line terminator code point를 contain하면, syntactic grammar에 의한 parsing purpose에서 전체 comment가 LineTerminator로 considered됩니다.

Syntax

Comment :: MultiLineComment SingleLineComment MultiLineComment :: /* MultiLineCommentCharsopt */ MultiLineCommentChars :: MultiLineNotAsteriskChar MultiLineCommentCharsopt * PostAsteriskCommentCharsopt PostAsteriskCommentChars :: MultiLineNotForwardSlashOrAsteriskChar MultiLineCommentCharsopt * PostAsteriskCommentCharsopt MultiLineNotAsteriskChar :: SourceCharacter but not * MultiLineNotForwardSlashOrAsteriskChar :: SourceCharacter but not one of / or * SingleLineComment :: // SingleLineCommentCharsopt SingleLineCommentChars :: SingleLineCommentChar SingleLineCommentCharsopt SingleLineCommentChar :: SourceCharacter but not LineTerminator

이 section의 여러 production은 section B.1.1에서 alternative definition이 given됩니다

12.5 Hashbang Comments

Hashbang Comment는 location-sensitive이며 다른 type의 comment처럼 syntactic grammar를 위한 input element stream에서 discarded됩니다.

Syntax

HashbangComment :: #! SingleLineCommentCharsopt

12.6 Tokens

Syntax

CommonToken :: IdentifierName PrivateIdentifier Punctuator NumericLiteral StringLiteral Template Note

DivPunctuator, RegularExpressionLiteral, RightBracePunctuator, TemplateSubstitutionTail production은 CommonToken production에 included되지 않은 additional token을 derive합니다.

12.7 Names and Keywords

IdentifierNameReservedWord는 Unicode Standard Annex #31, Identifier and Pattern Syntax에 given된 Default Identifier Syntax에 따라 interpreted되는 token이며, 약간의 modification이 있습니다. ReservedWordIdentifierName의 enumerated subset입니다. syntactic grammar는 IdentifierReservedWord가 아닌 IdentifierName으로 define합니다. Unicode identifier grammar는 Unicode Standard가 specified한 character property에 기반합니다. Unicode Standard의 latest version에서 specified된 category 안의 Unicode code point는 모든 conforming ECMAScript implementation에 의해 해당 category 안에 있는 것으로 treated되어야 합니다. ECMAScript implementation은 Unicode Standard의 later edition에 defined된 identifier code point를 recognize할 수 있습니다.

Note 1

이 standard는 specific code point addition을 specify합니다: U+0024 (DOLLAR SIGN) 및 U+005F (LOW LINE)는 IdentifierName 안의 어디에서나 permitted됩니다.

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의 definition은 12.9.4에 given됩니다.

Note 2

nonterminal IdentifierPartUnicodeIDContinue를 통해 _를 derive합니다.

Note 3

Unicode property “ID_Start” 및 “ID_Continue”를 가진 code point의 set은 각각 Unicode property “Other_ID_Start” 및 “Other_ID_Continue”를 가진 code point를 포함합니다.

12.7.1 Identifier Names

Unicode escape sequence는 IdentifierName 안에서 permitted되며, 여기서 UnicodeEscapeSequenceIdentifierCodePoint와 equal한 single Unicode code point를 contribute합니다. UnicodeEscapeSequence 앞의 \는 어떤 code point도 contribute하지 않습니다. UnicodeEscapeSequence는 otherwise invalid일 code point를 IdentifierName에 contribute하는 데 사용할 수 없습니다. 다시 말해, \ UnicodeEscapeSequence sequence가 그것이 contribute하는 SourceCharacter로 replaced되면, result는 original IdentifierName과 exact same sequence의 SourceCharacter element를 가지는 valid IdentifierName이어야 합니다. 이 명세 안의 IdentifierName에 대한 모든 interpretation은 특정 code point를 contribute하기 위해 escape sequence가 사용되었는지 여부와 관계없이 actual code point에 based합니다.

Unicode Standard에 따라 canonically equivalent한 두 IdentifierName은, 각 UnicodeEscapeSequence의 replacement 후 exact same sequence의 code point로 represented되지 않는 한 not equal입니다.

12.7.1.1 Static Semantics: Early Errors

IdentifierStart :: \ UnicodeEscapeSequence IdentifierPart :: \ UnicodeEscapeSequence

12.7.1.2 Static Semantics: IdentifierCodePoints

The syntax-directed operation IdentifierCodePoints takes no arguments and returns a List of code points. It is defined piecewise over the following productions:

IdentifierName :: IdentifierStart
  1. codePointIdentifierStartIdentifierCodePoint로 둔다.
  2. « codePoint »를 반환한다.
IdentifierName :: IdentifierName IdentifierPart
  1. codePoints 를 derived IdentifierNameIdentifierCodePoints로 둔다.
  2. codePointIdentifierPartIdentifierCodePoint로 둔다.
  3. codePoints 와 « codePoint »의 list-concatenation을 반환한다.

12.7.1.3 Static Semantics: IdentifierCodePoint

The syntax-directed operation IdentifierCodePoint takes no arguments and returns a code point. It is defined piecewise over the following productions:

IdentifierStart :: IdentifierStartChar
  1. IdentifierStartChar에 matched된 code point를 반환한다.
IdentifierPart :: IdentifierPartChar
  1. IdentifierPartChar에 matched된 code point를 반환한다.
UnicodeEscapeSequence :: u Hex4Digits
  1. numeric value가 Hex4Digits의 MV인 code point를 반환한다.
UnicodeEscapeSequence :: u{ CodePoint }
  1. numeric value가 CodePoint의 MV인 code point를 반환한다.

12.7.2 Keywords and Reserved Words

keywordIdentifierName과 match되지만 syntactic use도 가지는 token입니다; 즉, 어떤 syntactic production 안에서 fixed width font로 literally appear합니다. ECMAScript의 keyword에는 if, while, async, await 및 many others가 포함됩니다.

reserved word는 identifier로 사용할 수 없는 IdentifierName입니다. 많은 keyword는 reserved word이지만, 일부는 그렇지 않으며, 일부는 certain context에서만 reserved됩니다. ifwhile은 reserved word입니다. await는 async function과 module 안에서만 reserved됩니다. async는 reserved되지 않습니다; variable name 또는 statement label로 restriction 없이 사용할 수 있습니다.

이 명세는 어떤 name이 valid identifier이고 어떤 것이 reserved word인지 specify하기 위해 grammatical production과 early error rule의 combination을 사용합니다. 아래 ReservedWord list 안의 모든 token은 awaityield를 제외하고 unconditionally reserved됩니다. awaityield에 대한 exception은 parameterized syntactic production을 사용하여 13.1에 specified되어 있습니다. Lastly, several early error rule이 valid identifier의 set을 restrict합니다. 13.1.1, 14.3.1.1, 14.7.5.1, 15.7.1를 참조하십시오. 요약하면, identifier name에는 다섯 category가 있습니다:

  • Math, window, toString, _처럼 always identifier로 allowed되고 keyword가 아닌 것;

  • identifier로 never allowed되지 않는 것, 즉 awaityield를 제외하고 아래 listed된 ReservedWord;

  • contextually identifier로 allowed되는 것, 즉 awaityield;

  • strict mode code에서 contextually identifier로 disallowed되는 것: let, static, implements, interface, package, private, protected, public;

  • always identifier로 allowed되지만 Identifier가 allowed되지 않는 place에서 certain syntactic production 안의 keyword로도 appear하는 것: as, async, from, get, meta, of, set, target.

conditional keyword 또는 contextual keyword라는 term은 때때로 last three category에 속해 일부 context에서는 identifier로, 다른 context에서는 keyword로 사용될 수 있는 keyword를 refer하는 데 사용됩니다.

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 안의 keyword는 specific SourceCharacter element의 literal sequence와 match합니다. keyword 안의 code point는 \ UnicodeEscapeSequence로 expressed될 수 없습니다.

IdentifierName\ UnicodeEscapeSequence를 contain할 수 있지만, els\u{65}라고 spelling하여 “else”라는 variable을 declare하는 것은 possible하지 않습니다. 13.1.1early error rule은 reserved word와 같은 StringValue를 가진 identifier를 rule out합니다.

Note 2

enum은 이 명세에서 현재 keyword로 사용되지 않습니다. 이는 future language extension에서 keyword로 use하기 위해 set aside된 future reserved word입니다.

마찬가지로, implements, interface, package, private, protected, publicstrict mode code에서 future reserved word입니다.

Note 3

name argumentseval은 keyword가 아니지만, strict mode code에서 일부 restriction의 subject입니다. 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 NumericLiteralSeparatoropt DecimalDigits[+Sep] NonOctalDecimalIntegerLiteral DecimalDigits[Sep] :: DecimalDigit DecimalDigits[?Sep] DecimalDigit [+Sep] DecimalDigits[+Sep] NumericLiteralSeparator DecimalDigit DecimalDigit :: one of 0 1 2 3 4 5 6 7 8 9 NonZeroDigit :: one of 1 2 3 4 5 6 7 8 9 ExponentPart[Sep] :: ExponentIndicator SignedInteger[?Sep] ExponentIndicator :: one of e E SignedInteger[Sep] :: DecimalDigits[?Sep] + DecimalDigits[?Sep] - DecimalDigits[?Sep] BinaryIntegerLiteral[Sep] :: 0b BinaryDigits[?Sep] 0B BinaryDigits[?Sep] BinaryDigits[Sep] :: BinaryDigit BinaryDigits[?Sep] BinaryDigit [+Sep] BinaryDigits[+Sep] NumericLiteralSeparator BinaryDigit BinaryDigit :: one of 0 1 OctalIntegerLiteral[Sep] :: 0o OctalDigits[?Sep] 0O OctalDigits[?Sep] OctalDigits[Sep] :: OctalDigit OctalDigits[?Sep] OctalDigit [+Sep] OctalDigits[+Sep] NumericLiteralSeparator OctalDigit LegacyOctalIntegerLiteral :: 0 OctalDigit LegacyOctalIntegerLiteral OctalDigit NonOctalDecimalIntegerLiteral :: 0 NonOctalDigit LegacyOctalLikeDecimalIntegerLiteral NonOctalDigit NonOctalDecimalIntegerLiteral DecimalDigit LegacyOctalLikeDecimalIntegerLiteral :: 0 OctalDigit LegacyOctalLikeDecimalIntegerLiteral OctalDigit OctalDigit :: one of 0 1 2 3 4 5 6 7 NonOctalDigit :: one of 8 9 HexIntegerLiteral[Sep] :: 0x HexDigits[?Sep] 0X HexDigits[?Sep] HexDigits[Sep] :: HexDigit HexDigits[?Sep] HexDigit [+Sep] HexDigits[+Sep] NumericLiteralSeparator HexDigit HexDigit :: one of 0 1 2 3 4 5 6 7 8 9 a b c d e f A B C D E F

NumericLiteral 바로 뒤의 SourceCharacterIdentifierStart 또는 DecimalDigit이어서는 안 됩니다.

Note

예: 3in은 error이며 두 input element 3in이 아닙니다.

12.9.3.1 Static Semantics: Early Errors

NumericLiteral :: LegacyOctalIntegerLiteral DecimalIntegerLiteral :: NonOctalDecimalIntegerLiteral
  • IsStrict(this production)이 true이면 Syntax Error입니다.
Note
non-strict code에서 이 syntax는 Legacy입니다.

12.9.3.2 Static Semantics: MV

numeric literal은 Number type 또는 BigInt type의 value를 나타냅니다.

12.9.3.3 Static Semantics: NumericValue

The syntax-directed operation NumericValue takes no arguments and returns a Number or a BigInt. It is defined piecewise over the following productions:

NumericLiteral :: DecimalLiteral
  1. RoundMVResult(DecimalLiteral의 MV)를 반환한다.
NumericLiteral :: NonDecimalIntegerLiteral
  1. 𝔽(NonDecimalIntegerLiteral의 MV)를 반환한다.
NumericLiteral :: LegacyOctalIntegerLiteral
  1. 𝔽(LegacyOctalIntegerLiteral의 MV)를 반환한다.
NumericLiteral :: NonDecimalIntegerLiteral BigIntLiteralSuffix
  1. NonDecimalIntegerLiteral의 MV에 대한 BigInt value를 반환한다.
DecimalBigIntegerLiteral :: 0 BigIntLiteralSuffix
  1. 0를 반환한다.
DecimalBigIntegerLiteral :: NonZeroDigit BigIntLiteralSuffix
  1. NonZeroDigit의 MV에 대한 BigInt value를 반환한다.
DecimalBigIntegerLiteral :: NonZeroDigit DecimalDigits BigIntLiteralSuffix NonZeroDigit NumericLiteralSeparator DecimalDigits BigIntLiteralSuffix
  1. nNumericLiteralSeparator의 모든 occurrence를 제외한 DecimalDigits 안의 code point 수로 둔다.
  2. mv를 (NonZeroDigit의 MV × 10n) plus DecimalDigits의 MV로 둔다.
  3. (mv)를 반환한다.

12.9.4 String Literals

Note 1

string literal은 single 또는 double quote로 enclosed된 0개 이상의 Unicode code point입니다. Unicode code point는 escape sequence로 represented될 수도 있습니다. closing quote code point, U+005C (REVERSE SOLIDUS), U+000D (CARRIAGE RETURN), U+000A (LINE FEED)를 제외한 모든 code point는 string literal에 literally appear할 수 있습니다. 어떤 code point든 escape sequence의 form으로 appear할 수 있습니다. String literal은 ECMAScript String value로 evaluate됩니다. 이러한 String value를 generating할 때 Unicode code point는 11.1.1에 defined된 대로 UTF-16 encoded됩니다. Basic Multilingual Plane에 속하는 code point는 string의 single code unit element로 encoded됩니다. 그 밖의 모든 code point는 string의 two code unit element로 encoded됩니다.

Syntax

StringLiteral :: " DoubleStringCharactersopt " ' SingleStringCharactersopt ' DoubleStringCharacters :: DoubleStringCharacter DoubleStringCharactersopt SingleStringCharacters :: SingleStringCharacter SingleStringCharactersopt DoubleStringCharacter :: SourceCharacter but not one of " or \ or LineTerminator <LS> <PS> \ EscapeSequence LineContinuation SingleStringCharacter :: SourceCharacter but not one of ' or \ or LineTerminator <LS> <PS> \ EscapeSequence LineContinuation LineContinuation :: \ LineTerminatorSequence EscapeSequence :: CharacterEscapeSequence 0 [lookahead ∉ DecimalDigit] LegacyOctalEscapeSequence NonOctalDecimalEscapeSequence HexEscapeSequence UnicodeEscapeSequence CharacterEscapeSequence :: SingleEscapeCharacter NonEscapeCharacter SingleEscapeCharacter :: one of ' " \ b f n r t v NonEscapeCharacter :: SourceCharacter but not one of EscapeCharacter or LineTerminator EscapeCharacter :: SingleEscapeCharacter DecimalDigit x u LegacyOctalEscapeSequence :: 0 [lookahead ∈ { 8, 9 }] NonZeroOctalDigit [lookahead ∉ OctalDigit] ZeroToThree OctalDigit [lookahead ∉ OctalDigit] FourToSeven OctalDigit ZeroToThree OctalDigit OctalDigit NonZeroOctalDigit :: OctalDigit but not 0 ZeroToThree :: one of 0 1 2 3 FourToSeven :: one of 4 5 6 7 NonOctalDecimalEscapeSequence :: one of 8 9 HexEscapeSequence :: x HexDigit HexDigit UnicodeEscapeSequence :: u Hex4Digits u{ CodePoint } Hex4Digits :: HexDigit HexDigit HexDigit HexDigit

nonterminal HexDigit의 definition은 12.9.3에 given되어 있습니다. SourceCharacter11.1에 defined되어 있습니다.

Note 2

<LF> 및 <CR>은 empty code point sequence를 produce하는 LineContinuation의 part인 경우를 제외하고 string literal 안에 appear할 수 없습니다. string literal의 String value 안에 둘 중 하나를 include하는 proper way는 \n 또는 \u000A 같은 escape sequence를 사용하는 것입니다.

12.9.4.1 Static Semantics: Early Errors

EscapeSequence :: LegacyOctalEscapeSequence NonOctalDecimalEscapeSequence
  • IsStrict(this production)이 true이면 Syntax Error입니다.
Note 1
non-strict code에서 이 syntax는 Legacy입니다.
Note 2

string literal이 enclosing code를 strict mode로 place하는 Use Strict Directive보다 preceding할 수 있으며, implementation은 그러한 literal에 대해 위 rule을 enforce하도록 care해야 합니다. 예를 들어 다음 source text는 Syntax Error를 contain합니다:

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의 value를 나타냅니다. SV는 string literal의 various part에 대한 recursive application을 통해 string literal에 대한 String value를 produce합니다. 이 process의 part로, string literal 안의 일부 Unicode code point는 아래 또는 12.9.3에 described된 대로 mathematical value를 가지는 것으로 interpreted됩니다.

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이 evaluated될 때마다 RegExp object(22.2 참조)로 converted되는 input element입니다. program 안의 두 regular expression literal은 두 literal의 content가 identical하더라도 서로 ===로 compare되는 regular expression object로 evaluate되지 않습니다. RegExp object는 runtime에 new RegExp에 의해 또는 RegExp constructor를 function으로 calling하여 created될 수도 있습니다(22.2.4 참조).

아래 production은 regular expression literal의 syntax를 describe하며 input element scanner가 regular expression literal의 end를 find하는 데 사용됩니다. RegularExpressionBodyRegularExpressionFlags를 comprising하는 source text는 subsequently 더 stringent한 ECMAScript Regular Expression grammar(22.2.1)를 사용하여 다시 parsed됩니다.

implementation은 22.2.1에 defined된 ECMAScript Regular Expression grammar를 extend할 수 있지만, 아래 defined된 RegularExpressionBodyRegularExpressionFlags production이나 이러한 production이 사용하는 production을 extend해서는 안 됩니다.

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 literal은 empty일 수 없습니다; empty regular expression literal을 represent하는 대신 code unit sequence //는 single-line comment를 start합니다. empty regular expression을 specify하려면 /(?:)/를 사용하십시오.

12.9.5.1 Static Semantics: BodyText

The syntax-directed operation BodyText takes no arguments and returns source text. It is defined piecewise over the following productions:

RegularExpressionLiteral :: / RegularExpressionBody / RegularExpressionFlags
  1. RegularExpressionBody로 recognized된 source text를 반환한다.

12.9.5.2 Static Semantics: FlagText

The syntax-directed operation FlagText takes no arguments and returns source text. It is defined piecewise over the following productions:

RegularExpressionLiteral :: / RegularExpressionBody / RegularExpressionFlags
  1. RegularExpressionFlags로 recognized된 source text를 반환한다.

12.9.6 Template Literal Lexical Components

Syntax

Template :: NoSubstitutionTemplate TemplateHead NoSubstitutionTemplate :: ` TemplateCharactersopt ` TemplateHead :: ` TemplateCharactersopt ${ TemplateSubstitutionTail :: TemplateMiddle TemplateTail TemplateMiddle :: } TemplateCharactersopt ${ TemplateTail :: } TemplateCharactersopt ` TemplateCharacters :: TemplateCharacter TemplateCharactersopt TemplateCharacter :: $ [lookahead ≠ {] \ TemplateEscapeSequence \ NotEscapeSequence LineContinuation LineTerminatorSequence SourceCharacter but not one of ` or \ or $ or LineTerminator TemplateEscapeSequence :: CharacterEscapeSequence 0 [lookahead ∉ DecimalDigit] HexEscapeSequence UnicodeEscapeSequence NotEscapeSequence :: 0 DecimalDigit DecimalDigit but not 0 x [lookahead ∉ HexDigit] x HexDigit [lookahead ∉ HexDigit] u [lookahead ∉ HexDigit] [lookahead ≠ {] u HexDigit [lookahead ∉ HexDigit] u HexDigit HexDigit [lookahead ∉ HexDigit] u HexDigit HexDigit HexDigit [lookahead ∉ HexDigit] u { [lookahead ∉ HexDigit] u { NotCodePoint [lookahead ∉ HexDigit] u { CodePoint [lookahead ∉ HexDigit] [lookahead ≠ }] NotCodePoint :: HexDigits[~Sep] but only if the MV of HexDigits > 0x10FFFF CodePoint :: HexDigits[~Sep] but only if the MV of HexDigits ≤ 0x10FFFF Note

TemplateSubstitutionTailInputElementTemplateTail alternative lexical goal에 의해 사용됩니다.

12.9.6.1 Static Semantics: TV

The syntax-directed operation TV takes no arguments and returns a String or undefined. template literal component는 TV에 의해 String type의 value로 interpreted됩니다. TV는 template object의 indexed component(colloquially, template values)를 construct하는 데 사용됩니다. TV에서 escape sequence는 escape sequence가 represented하는 Unicode code point의 UTF-16 code unit으로 replaced됩니다.

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의 value로 interpreted됩니다. TRV는 template object의 raw component(colloquially, template raw values)를 construct하는 데 사용됩니다. TRV는 TV와 similar하지만 차이점은 TRV에서 escape sequence가 literal에 appear하는 그대로 interpreted된다는 것입니다.

Note

TVLineContinuation의 code unit을 excludes하지만 TRV는 them을 includes합니다. <CR><LF> 및 <CR> LineTerminatorSequenceTV와 TRV 모두에서 <LF>로 normalized됩니다. <CR> 또는 <CR><LF> sequence를 include하려면 explicit TemplateEscapeSequence가 필요합니다.

12.10 Automatic Semicolon Insertion

대부분의 ECMAScript statement와 declaration은 semicolon으로 terminated되어야 합니다. 그러한 semicolon은 source text에 항상 explicitly appear할 수 있습니다. 그러나 convenience를 위해, certain situation에서는 그러한 semicolon을 source text에서 omitted할 수 있습니다. 이러한 situation은 semicolon이 그 situation에서 source code token stream에 automatically inserted된다고 말함으로써 described됩니다.

12.10.1 Rules of Automatic Semicolon Insertion

다음 rule에서 “token”은 clause 12에 described된 대로 current lexical goal symbol을 사용하여 determined된 actual recognized lexical token을 의미합니다.

semicolon insertion에는 세 가지 basic rule이 있습니다:

  1. source text가 left to right로 parsed될 때, grammar의 어떤 production에도 allowed되지 않는 token(offending token이라고 함)이 encountered되면, 다음 condition 중 하나 이상이 true인 경우 semicolon이 offending token 앞에 automatically inserted됩니다:

    • offending token이 previous token과 적어도 하나의 LineTerminator에 의해 separated되어 있습니다.
    • offending token이 }입니다.
    • previous token이 )이고 inserted semicolon이 do-while statement(14.7.2)의 terminating semicolon으로 parsed될 것입니다.
  2. source text가 left to right로 parsed될 때, token의 input stream의 end가 encountered되고 parser가 input token stream을 goal nonterminal의 single instance로 parse할 수 없으면, semicolon이 input stream의 end에 automatically inserted됩니다.
  3. source text가 left to right로 parsed될 때, grammar의 어떤 production에서는 allowed되지만 그 production이 restricted production이고, 그 token이 restricted production 안에서 annotation “[no LineTerminator here]” 바로 뒤의 terminal 또는 nonterminal을 위한 first token이 될 수 있는 token(restricted token이라고 함)이며, restricted token이 previous token과 적어도 하나의 LineTerminator에 의해 separated되어 있으면, semicolon이 restricted token 앞에 automatically inserted됩니다.

그러나 preceding rule에는 additional overriding condition이 있습니다: semicolon이 empty statement로 parsed될 경우 또는 그 semicolon이 for statement(14.7.4 참조)의 header 안의 두 semicolon 중 하나가 될 경우, semicolon은 never automatically inserted되지 않습니다.

Note

다음은 grammar 안의 only restricted production입니다:

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 production의 practical effect는 다음과 같습니다:

  • 파서가 후위 연산자로 처리할 위치에서 ++ 또는 -- 토큰을 만났고, 앞선 토큰과 ++ 또는 -- 토큰 사이에 하나 이상의 LineTerminator가 발생한 경우, ++ 또는 -- 토큰 앞에 세미콜론이 자동으로 삽입된다.
  • using 토큰을 만났고 IdentifierName 토큰 앞에서 LineTerminator를 만난 경우, using 토큰 뒤에 세미콜론이 자동으로 삽입된다.
  • continue, break, return, throw 또는 yield 토큰을 만났고 다음 토큰 앞에서 LineTerminator를 만난 경우, continue, break, return, throw 또는 yield 토큰 뒤에 세미콜론이 자동으로 삽입된다.
  • 화살표 함수 매개변수 뒤에 => 토큰 앞의 LineTerminator가 오는 경우, 세미콜론이 자동으로 삽입되고 해당 punctuator가 구문 오류를 일으킨다.
  • async 토큰 뒤에 function, IdentifierName 또는 ( 토큰 앞의 LineTerminator가 오는 경우, 세미콜론이 자동으로 삽입되고 async 토큰은 뒤따르는 토큰들과 같은 표현식 또는 클래스 요소의 일부로 처리되지 않는다.
  • async 토큰 뒤에 * 토큰 앞의 LineTerminator가 오는 경우, 세미콜론이 자동으로 삽입되고 해당 punctuator가 구문 오류를 일으킨다.

그 결과 ECMAScript 프로그래머에게 주어지는 실질적인 조언은 다음과 같다:

  • 후위 ++ 또는 -- 연산자는 그 피연산자와 같은 줄에 있어야 한다.
  • using 선언의 BindingListusing 토큰과 같은 줄에서 시작해야 한다.
  • return 또는 throw 문에서의 Expression, 또는 yield 표현식에서의 AssignmentExpressionreturn, throw 또는 yield 토큰과 같은 줄에서 시작해야 한다.
  • break 또는 continue 문에서의 LabelIdentifierbreak 또는 continue 토큰과 같은 줄에 있어야 한다.
  • 화살표 함수의 매개변수 끝과 그 =>는 같은 줄에 있어야 한다.
  • 비동기 함수 또는 메서드 앞의 async 토큰은 바로 뒤따르는 토큰과 같은 줄에 있어야 한다.

12.10.2 Examples of Automatic Semicolon Insertion

This section is non-normative.

source

{ 1 2 } 3

는 automatic semicolon insertion rule이 있어도 ECMAScript grammar에서 valid sentence가 아닙니다. 반대로, source

{ 1
2 } 3

역시 valid ECMAScript sentence는 아니지만, automatic semicolon insertion에 의해 다음으로 transformed됩니다:

{ 1
;2 ;} 3;

이는 valid ECMAScript sentence입니다.

source

for (a; b
)

는 valid ECMAScript sentence가 아니며, semicolon이 for statement의 header에 needed되기 때문에 automatic semicolon insertion에 의해 altered되지 않습니다. Automatic semicolon insertion은 for statement의 header 안의 두 semicolon 중 하나를 never inserts하지 않습니다.

source

return
a + b

는 automatic semicolon insertion에 의해 다음으로 transformed됩니다:

return;
a + b;
Note 1

LineTerminator가 token return과 expression a + b를 separate하기 때문에, expression a + breturn statement에 의해 returned될 value로 treated되지 않습니다.

source

a = b
++c

는 automatic semicolon insertion에 의해 다음으로 transformed됩니다:

a = b;
++c;
Note 2

LineTerminatorb++ 사이에 occur하기 때문에, token ++는 variable b에 applying되는 postfix operator로 treated되지 않습니다.

source

if (a > b)
else c = d

는 valid ECMAScript sentence가 아니며, grammar의 어떤 production도 그 point에 apply되지 않더라도, automatically inserted된 semicolon이 empty statement로 parsed될 것이기 때문에 else token 앞에서 automatic semicolon insertion에 의해 altered되지 않습니다.

source

a = b + c
(d + e).print()

not automatic semicolon insertion에 의해 transformed되지 않습니다. second line을 begin하는 parenthesized expression이 function call의 argument list로 interpreted될 수 있기 때문입니다:

a = b + c(d + e).print()

assignment statement가 left parenthesis로 begin해야 하는 circumstance에서는, programmer가 automatic semicolon insertion에 rely하기보다는 preceding statement의 end에 explicit semicolon을 provide하는 것이 good idea입니다.

12.10.3 Interesting Cases of Automatic Semicolon Insertion

This section is non-normative.

ECMAScript program은 automatic semicolon insertion에 relying함으로써 very few semicolon을 가진 style로 written될 수 있습니다. 위에 described된 것처럼, semicolon은 every newline에 inserted되지 않으며, automatic semicolon insertion은 line terminator를 across하는 multiple token에 depend할 수 있습니다.

새 syntactic feature가 ECMAScript에 added됨에 따라, automatic semicolon insertion에 preceding하여 relying하는 line이 parsed될 때 grammar production을 change하게 하는 additional grammar production이 added될 수 있습니다.

이 section의 purpose상, automatic semicolon insertion의 case는 preceding source text에 따라 semicolon이 inserted될 수도 있고 inserted되지 않을 수도 있는 place이면 interesting하다고 considered됩니다. 이 section의 rest는 이 version의 ECMAScript에서 automatic semicolon insertion의 여러 interesting case를 describe합니다.

12.10.3.1 Statement List 안의 Automatic Semicolon Insertion의 Interesting Cases

StatementList에서 많은 StatementListItem은 semicolon으로 end하며, 이는 automatic semicolon insertion을 사용하여 omitted될 수 있습니다. 위 rule의 consequence로, expression을 ending하는 line의 end에서는 following line이 다음 중 하나로 begin하면 semicolon이 required됩니다:

  • opening parenthesis((). semicolon이 없으면 두 line은 together CallExpression으로 treated됩니다.
  • opening square bracket([). semicolon이 없으면 두 line은 ArrayLiteral 또는 ArrayAssignmentPattern이 아니라 property access로 treated됩니다.
  • template literal(`). semicolon이 없으면 두 line은 previous expression을 MemberExpression으로 하는 tagged Template(13.3.11)으로 interpreted됩니다.
  • Unary + 또는 -. semicolon이 없으면 두 line은 corresponding binary operator의 usage로 interpreted됩니다.
  • RegExp literal. semicolon이 없으면 두 line은 instead / MultiplicativeOperator로 parsed될 수 있습니다. 예를 들어 RegExp에 flag가 있는 경우입니다.

12.10.3.2 Automatic Semicolon Insertion 및 “[no LineTerminator here]”의 Cases

This section is non-normative.

ECMAScript는 “[no LineTerminator here]”를 include하는 grammar production을 contain합니다. 이러한 production은 때때로 grammar 안에서 optional operand를 가지기 위한 means입니다. 이러한 location에 LineTerminator를 introducing하면 optional operand가 없는 grammar production을 사용하여 source text의 grammar production을 change하게 됩니다.

이 section의 rest는 이 version의 ECMAScript에서 “[no LineTerminator here]”를 사용하는 여러 production을 describe합니다.

12.10.3.2.1 Optional Operand와 “[no LineTerminator here]”를 가진 Grammar Production의 List

13 ECMAScript 언어: 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

yieldawait는 grammar에서 BindingIdentifier로 permitted되고, 아래 static semantics에 의해 prohibited됩니다. 이는 다음과 같은 case에서 automatic semicolon insertion을 prohibit하기 위한 것입니다.

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
  • this production이 [Yield] parameter를 가지면 Syntax Error입니다.
BindingIdentifier[Yield, Await] : await
  • this production이 [Await] parameter를 가지면 Syntax Error입니다.
IdentifierReference[Yield, Await] : Identifier BindingIdentifier[Yield, Await] : Identifier LabelIdentifier[Yield, Await] : Identifier
  • this production이 [Yield] parameter를 가지고 IdentifierStringValue"yield"이면 Syntax Error입니다.
  • this production이 [Await] parameter를 가지고 IdentifierStringValue"await"이면 Syntax Error입니다.
Identifier : IdentifierName but not ReservedWord Note

IdentifierNameStringValueIdentifierName 안의 모든 Unicode escape sequence를 normalize하므로, 그러한 escape는 code point sequence가 ReservedWord와 같은 Identifier를 write하는 데 사용할 수 없습니다.

13.1.2 Static Semantics: StringValue

The syntax-directed operation StringValue takes no arguments and returns a String. It is defined piecewise over the following productions:

IdentifierName :: IdentifierStart IdentifierName IdentifierPart
  1. idTextUnescapedIdentifierNameIdentifierCodePoints로 둔다.
  2. CodePointsToString(idTextUnescaped)를 반환한다.
IdentifierReference : yield BindingIdentifier : yield LabelIdentifier : yield
  1. "yield"를 반환한다.
IdentifierReference : await BindingIdentifier : await LabelIdentifier : await
  1. "await"를 반환한다.
Identifier : IdentifierName but not ReservedWord
  1. IdentifierNameStringValue를 반환한다.
PrivateIdentifier :: # IdentifierName
  1. 0x0023 (NUMBER SIGN)과 IdentifierNameStringValuestring-concatenation을 반환한다.
ModuleExportName : StringLiteral
  1. StringLiteralSV를 반환한다.

13.1.3 Runtime Semantics: Evaluation

IdentifierReference : Identifier
  1. ResolveBinding(IdentifierStringValue)를 반환한다.
IdentifierReference : yield
  1. ResolveBinding("yield")를 반환한다.
IdentifierReference : await
  1. ResolveBinding("await")를 반환한다.
Note 1

IdentifierReference를 evaluating한 result는 항상 Reference type의 value입니다.

Note 2

non-strict code에서 keyword yield는 identifier로 사용될 수 있습니다. IdentifierReference를 evaluating하면 그것이 Identifier였던 것처럼 yield의 binding을 resolve합니다. Early Error restriction은 그러한 evaluation이 non-strict code에서만 occur할 수 있음을 ensure합니다.

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를 processing할 때, CoverParenthesizedExpressionAndArrowParameterList의 interpretation은 다음 grammar를 사용하여 refined됩니다:

ParenthesizedExpression[Yield, Await] : ( Expression[+In, ?Yield, ?Await] )

13.2.1 this Keyword

13.2.1.1 Runtime Semantics: Evaluation

PrimaryExpression : this
  1. ResolveThisBinding()을 반환한다.

13.2.2 Identifier Reference

IdentifierReference에 대해서는 13.1를 참조하십시오.

13.2.3 Literals

Syntax

Literal : NullLiteral BooleanLiteral NumericLiteral StringLiteral

13.2.3.1 Runtime Semantics: Evaluation

Literal : NullLiteral
  1. null을 반환한다.
Literal : BooleanLiteral
  1. BooleanLiteral이 token false이면, false를 반환한다.
  2. BooleanLiteral이 token true이면, true를 반환한다.
Literal : NumericLiteral
  1. 12.9.3에 defined된 NumericLiteralNumericValue를 반환한다.
Literal : StringLiteral
  1. 12.9.4.2에 defined된 StringLiteralSV를 반환한다.

13.2.4 Array Initializer

Note

ArrayLiteral은 square bracket으로 enclosed된, 각각 array element를 represent하는 0개 이상의 expression list를 사용하여 Array의 initialization을 describe하는 expression입니다. element는 literal일 필요가 없습니다; 이는 array initializer가 evaluated될 때마다 evaluated됩니다.

Array element는 element list의 beginning, middle 또는 end에서 elided될 수 있습니다. element list 안의 comma가 AssignmentExpression에 의해 preceded되지 않을 때마다(즉, beginning의 comma 또는 another comma 뒤의 comma), missing array element는 Array의 length에 contribute하고 subsequent element의 index를 increase합니다. Elided array element는 defined되지 않습니다. array의 end에서 element가 elided되면, 그 element는 Array의 length에 contribute하지 않습니다.

Syntax

ArrayLiteral[Yield, Await] : [ Elisionopt ] [ ElementList[?Yield, ?Await] ] [ ElementList[?Yield, ?Await] , Elisionopt ] ElementList[Yield, Await] : Elisionopt AssignmentExpression[+In, ?Yield, ?Await] Elisionopt SpreadElement[?Yield, ?Await] ElementList[?Yield, ?Await] , Elisionopt AssignmentExpression[+In, ?Yield, ?Await] ElementList[?Yield, ?Await] , Elisionopt SpreadElement[?Yield, ?Await] Elision : , Elision , SpreadElement[Yield, Await] : ... AssignmentExpression[+In, ?Yield, ?Await]

13.2.4.1 Runtime Semantics: ArrayAccumulation

The syntax-directed operation ArrayAccumulation takes arguments array (an Array) and nextIndex (an integer) and returns either a normal completion containing an integer or an abrupt completion. It is defined piecewise over the following productions:

Elision : ,
  1. lengthnextIndex + 1로 둔다.
  2. Set(array, "length", 𝔽(length), true)를 수행한다.
  3. NOTE: 위 step은 length가 232 - 1을 exceeds하면 throw한다.
  4. length를 반환한다.
Elision : Elision ,
  1. arguments array와 (nextIndex + 1)을 가진 ElisionArrayAccumulation을 ? 반환한다.
ElementList : Elisionopt AssignmentExpression
  1. Elision이 present이면, 다음을 수행한다.
    1. nextIndex를 arguments arraynextIndex를 가진 ElisionArrayAccumulation으로 ? 설정한다.
  2. initResultAssignmentExpressionEvaluation으로 ? 둔다.
  3. initValue를 ? GetValue(initResult)로 둔다.
  4. CreateDataPropertyOrThrow(array, ! ToString(𝔽(nextIndex)), initValue)를 수행한다.
  5. nextIndex + 1을 반환한다.
ElementList : Elisionopt SpreadElement
  1. Elision이 present이면, 다음을 수행한다.
    1. nextIndex를 arguments arraynextIndex를 가진 ElisionArrayAccumulation으로 ? 설정한다.
  2. arguments arraynextIndex를 가진 SpreadElementArrayAccumulation을 ? 반환한다.
ElementList : ElementList , Elisionopt AssignmentExpression
  1. nextIndex를 arguments arraynextIndex를 가진 derived ElementListArrayAccumulation으로 ? 설정한다.
  2. Elision이 present이면, 다음을 수행한다.
    1. nextIndex를 arguments arraynextIndex를 가진 ElisionArrayAccumulation으로 ? 설정한다.
  3. initResultAssignmentExpressionEvaluation으로 ? 둔다.
  4. initValue를 ? GetValue(initResult)로 둔다.
  5. CreateDataPropertyOrThrow(array, ! ToString(𝔽(nextIndex)), initValue)를 수행한다.
  6. nextIndex + 1을 반환한다.
ElementList : ElementList , Elisionopt SpreadElement
  1. nextIndex를 arguments arraynextIndex를 가진 derived ElementListArrayAccumulation으로 ? 설정한다.
  2. Elision이 present이면, 다음을 수행한다.
    1. nextIndex를 arguments arraynextIndex를 가진 ElisionArrayAccumulation으로 ? 설정한다.
  3. arguments arraynextIndex를 가진 SpreadElementArrayAccumulation을 ? 반환한다.
SpreadElement : ... AssignmentExpression
  1. spreadRefAssignmentExpressionEvaluation으로 ? 둔다.
  2. spreadObj를 ? GetValue(spreadRef)로 둔다.
  3. iteratorRecord를 ? GetIterator(spreadObj, sync)로 둔다.
  4. Repeat,
    1. next를 ? IteratorStepValue(iteratorRecord)로 둔다.
    2. nextdone이면, nextIndex를 반환한다.
    3. CreateDataPropertyOrThrow(array, ! ToString(𝔽(nextIndex)), next)를 수행한다.
    4. nextIndexnextIndex + 1로 설정한다.
Note

CreateDataPropertyOrThrow는 standard built-in Array prototype object[[Set]]을 사용한 new own property creation을 preclude하는 manner로 modified되었더라도 own property가 array에 defined되도록 ensure하기 위해 사용됩니다.

13.2.4.2 Runtime Semantics: Evaluation

ArrayLiteral : [ Elisionopt ]
  1. array를 ! ArrayCreate(0)으로 둔다.
  2. Elision이 present이면, 다음을 수행한다.
    1. arguments array와 0을 가진 ElisionArrayAccumulation을 ? 수행한다.
  3. array를 반환한다.
ArrayLiteral : [ ElementList ]
  1. array를 ! ArrayCreate(0)으로 둔다.
  2. arguments array와 0을 가진 ElementListArrayAccumulation을 ? 수행한다.
  3. array를 반환한다.
ArrayLiteral : [ ElementList , Elisionopt ]
  1. array를 ! ArrayCreate(0)으로 둔다.
  2. nextIndex를 arguments array와 0을 가진 ElementListArrayAccumulation으로 ? 둔다.
  3. Elision이 present이면, 다음을 수행한다.
    1. arguments arraynextIndex를 가진 ElisionArrayAccumulation을 ? 수행한다.
  4. array를 반환한다.

13.2.5 Object Initializer

Note 1

object initializer는 literal과 resembling한 form으로 written된, Object의 initialization을 describe하는 expression입니다. 이는 curly bracket으로 enclosed된, 0개 이상의 property key와 associated value pair의 list입니다. value는 literal일 필요가 없습니다; 이는 object initializer가 evaluated될 때마다 evaluated됩니다.

Syntax

ObjectLiteral[Yield, Await] : { } { PropertyDefinitionList[?Yield, ?Await] } { PropertyDefinitionList[?Yield, ?Await] , } PropertyDefinitionList[Yield, Await] : PropertyDefinition[?Yield, ?Await] PropertyDefinitionList[?Yield, ?Await] , PropertyDefinition[?Yield, ?Await] PropertyDefinition[Yield, Await] : IdentifierReference[?Yield, ?Await] CoverInitializedName[?Yield, ?Await] PropertyName[?Yield, ?Await] : AssignmentExpression[+In, ?Yield, ?Await] MethodDefinition[?Yield, ?Await] ... AssignmentExpression[+In, ?Yield, ?Await] PropertyName[Yield, Await] : LiteralPropertyName ComputedPropertyName[?Yield, ?Await] LiteralPropertyName : IdentifierName StringLiteral NumericLiteral ComputedPropertyName[Yield, Await] : [ AssignmentExpression[+In, ?Yield, ?Await] ] CoverInitializedName[Yield, Await] : IdentifierReference[?Yield, ?Await] Initializer[+In, ?Yield, ?Await] Initializer[In, Yield, Await] : = AssignmentExpression[?In, ?Yield, ?Await] Note 2

MethodDefinition15.4에 defined되어 있습니다.

Note 3

certain context에서 ObjectLiteral은 더 restricted된 secondary grammar를 위한 cover grammar로 사용됩니다. CoverInitializedName production은 이러한 secondary grammar를 fully cover하기 위해 necessary합니다. 그러나 이 production의 사용은 actual ObjectLiteral이 expected되는 normal context에서 early Syntax Error를 result합니다.

13.2.5.1 Static Semantics: Early Errors

PropertyDefinition : MethodDefinition

actual object initializer를 describing하는 것 외에도 ObjectLiteral production은 ObjectAssignmentPattern을 위한 cover grammar로도 사용되며, CoverParenthesizedExpressionAndArrowParameterList의 part로 recognized될 수 있습니다. ObjectLiteralObjectAssignmentPattern이 required되는 context에 appear하면 다음 Early Error rule은 applied되지 않습니다. 또한 CoverParenthesizedExpressionAndArrowParameterList 또는 CoverCallExpressionAndAsyncArrowHead를 initially parsing할 때도 applied되지 않습니다.

PropertyDefinition : CoverInitializedName
  • 이 production에 의해 source text가 matched되면 Syntax Error입니다.
Note 1

이 production은 ObjectLiteralObjectAssignmentPattern을 위한 cover grammar로 serve할 수 있도록 존재합니다. 이는 actual object initializer 안에 occur할 수 없습니다.

ObjectLiteral : { PropertyDefinitionList } { PropertyDefinitionList , } Note 2

PropertyNameList가 반환하는 ListComputedPropertyName을 사용하여 defined된 property name을 include하지 않습니다.

13.2.5.2 Static Semantics: IsComputedPropertyKey

The syntax-directed operation IsComputedPropertyKey takes no arguments and returns a Boolean. It is defined piecewise over the following productions:

PropertyName : LiteralPropertyName
  1. false를 반환한다.
PropertyName : ComputedPropertyName
  1. true를 반환한다.

13.2.5.3 Static Semantics: PropertyDefinitionNodes

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

ObjectLiteral : { }
  1. 새 empty List를 반환한다.
PropertyDefinitionList : PropertyDefinition
  1. « PropertyDefinition »를 반환한다.
PropertyDefinitionList : PropertyDefinitionList , PropertyDefinition
  1. head를 derived PropertyDefinitionListPropertyDefinitionNodes로 둔다.
  2. head와 « PropertyDefinition »의 list-concatenation을 반환한다.

13.2.5.4 Static Semantics: PropertyNameList

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

PropertyDefinitionList : PropertyDefinition
  1. propertyNamePropertyDefinitionPropName으로 둔다.
  2. propertyNameempty이면, 새 empty List를 반환한다.
  3. « propertyName »를 반환한다.
PropertyDefinitionList : PropertyDefinitionList , PropertyDefinition
  1. listPropertyDefinitionListPropertyNameList로 둔다.
  2. propertyNamePropertyDefinitionPropName으로 둔다.
  3. propertyNameempty이면, list를 반환한다.
  4. list와 « propertyName »의 list-concatenation을 반환한다.

13.2.5.5 Runtime Semantics: Evaluation

ObjectLiteral : { }
  1. OrdinaryObjectCreate(%Object.prototype%)를 반환한다.
ObjectLiteral : { PropertyDefinitionList } { PropertyDefinitionList , }
  1. objOrdinaryObjectCreate(%Object.prototype%)로 둔다.
  2. argument obj를 가진 PropertyDefinitionListPropertyDefinitionEvaluation을 ? 수행한다.
  3. obj를 반환한다.
LiteralPropertyName : IdentifierName
  1. IdentifierNameStringValue를 반환한다.
LiteralPropertyName : StringLiteral
  1. StringLiteralSV를 반환한다.
LiteralPropertyName : NumericLiteral
  1. numberNumericLiteralNumericValue로 둔다.
  2. ToString(number)를 반환한다.
ComputedPropertyName : [ AssignmentExpression ]
  1. exprValueAssignmentExpressionEvaluation으로 ? 둔다.
  2. propertyName을 ? GetValue(exprValue)로 둔다.
  3. ToPropertyKey(propertyName)를 반환한다.

13.2.5.6 Runtime Semantics: PropertyDefinitionEvaluation

The syntax-directed operation PropertyDefinitionEvaluation takes argument obj (an Object) and returns either a normal completion containing unused or an abrupt completion. It is defined piecewise over the following productions:

PropertyDefinitionList : PropertyDefinitionList , PropertyDefinition
  1. argument obj를 가진 PropertyDefinitionListPropertyDefinitionEvaluation을 ? 수행한다.
  2. argument obj를 가진 PropertyDefinitionPropertyDefinitionEvaluation을 ? 수행한다.
  3. unused를 반환한다.
PropertyDefinition : ... AssignmentExpression
  1. exprValueAssignmentExpressionEvaluation으로 ? 둔다.
  2. fromValue를 ? GetValue(exprValue)로 둔다.
  3. excludedNames를 새 empty List로 둔다.
  4. CopyDataProperties(obj, fromValue, excludedNames)를 수행한다.
  5. unused를 반환한다.
PropertyDefinition : IdentifierReference
  1. propertyNameIdentifierReferenceStringValue로 둔다.
  2. exprValueIdentifierReferenceEvaluation으로 ? 둔다.
  3. propertyValue를 ? GetValue(exprValue)로 둔다.
  4. Assert: obj는 non-configurable property가 없는 ordinary, extensible object이다.
  5. CreateDataPropertyOrThrow(obj, propertyName, propertyValue)를 수행한다.
  6. unused를 반환한다.
PropertyDefinition : PropertyName : AssignmentExpression
  1. propertyKeyPropertyNameEvaluation으로 ? 둔다.
  2. PropertyDefinitionParseJSON을 위해 evaluated되는 Script 안에 contained되어 있으면(ParseJSON의 step 6 참조), 다음을 수행한다.
    1. isProtoSetterfalse로 둔다.
  3. 그렇지 않고 propertyKey"__proto__"이고 PropertyNameIsComputedPropertyKeyfalse이면, 다음을 수행한다.
    1. isProtoSettertrue로 둔다.
  4. 그렇지 않으면,
    1. isProtoSetterfalse로 둔다.
  5. IsAnonymousFunctionDefinition(AssignmentExpression)이 true이고 isProtoSetterfalse이면, 다음을 수행한다.
    1. propertyValue를 argument propertyKey를 가진 AssignmentExpressionNamedEvaluation으로 ? 둔다.
  6. 그렇지 않으면,
    1. exprValueRefAssignmentExpressionEvaluation으로 ? 둔다.
    2. propertyValue를 ? GetValue(exprValueRef)로 둔다.
  7. isProtoSettertrue이면, 다음을 수행한다.
    1. propertyValue가 Object이거나 propertyValuenull이면, 다음을 수행한다.
      1. obj.[[SetPrototypeOf]](propertyValue)를 수행한다.
    2. unused를 반환한다.
  8. Assert: obj는 non-configurable property가 없는 ordinary, extensible object이다.
  9. CreateDataPropertyOrThrow(obj, propertyKey, propertyValue)를 수행한다.
  10. unused를 반환한다.
PropertyDefinition : MethodDefinition
  1. arguments objtrue를 가진 MethodDefinitionMethodDefinitionEvaluation을 ? 수행한다.
  2. unused를 반환한다.

13.2.6 Function Defining Expressions

PrimaryExpression : FunctionExpression 에 대해서는 15.2를 참조하십시오.

PrimaryExpression : GeneratorExpression 에 대해서는 15.5를 참조하십시오.

PrimaryExpression : ClassExpression 에 대해서는 15.7를 참조하십시오.

PrimaryExpression : AsyncFunctionExpression 에 대해서는 15.8를 참조하십시오.

PrimaryExpression : AsyncGeneratorExpression 에 대해서는 15.6를 참조하십시오.

13.2.7 Regular Expression Literals

Syntax

12.9.5를 참조하십시오.

13.2.7.1 Static Semantics: Early Errors

PrimaryExpression : RegularExpressionLiteral

13.2.7.2 Static Semantics: IsValidRegularExpressionLiteral ( literal )

The abstract operation IsValidRegularExpressionLiteral takes argument literal (a RegularExpressionLiteral Parse Node) and returns a Boolean. argument가 valid regular expression literal인지 determine합니다. It performs the following steps when called:

  1. flagsliteralFlagText로 둔다.
  2. flagsd, g, i, m, s, u, v, 또는 y 이외의 code point를 contain하면, false를 반환한다.
  3. flags가 어떤 code point를 두 번 이상 contain하면, false를 반환한다.
  4. flagsu를 contain하면, utrue로 둔다; 그렇지 않으면 ufalse로 둔다.
  5. flagsv를 contain하면, vtrue로 둔다; 그렇지 않으면 vfalse로 둔다.
  6. patternTextliteralBodyText로 둔다.
  7. ufalse이고 vfalse이면, 다음을 수행한다.
    1. stringValueCodePointsToString(patternText)로 둔다.
    2. patternTextstringValue의 각 16-bit element를 Unicode BMP code point로 interpreting한 result인 code point sequence로 설정한다. UTF-16 decoding은 element에 applied되지 않는다.
  8. parseResultParsePattern(patternText, u, v)로 둔다.
  9. parseResultParse Node이면, true를 반환한다.
  10. false를 반환한다.

13.2.7.3 Runtime Semantics: Evaluation

PrimaryExpression : RegularExpressionLiteral
  1. patternCodePointsToString(RegularExpressionLiteralBodyText)로 둔다.
  2. flagsCodePointsToString(RegularExpressionLiteralFlagText)로 둔다.
  3. RegExpCreate(pattern, flags)를 반환한다.

13.2.8 Template Literals

Syntax

TemplateLiteral[Yield, Await, Tagged] : NoSubstitutionTemplate SubstitutionTemplate[?Yield, ?Await, ?Tagged] SubstitutionTemplate[Yield, Await, Tagged] : TemplateHead Expression[+In, ?Yield, ?Await] TemplateSpans[?Yield, ?Await, ?Tagged] TemplateSpans[Yield, Await, Tagged] : TemplateTail TemplateMiddleList[?Yield, ?Await, ?Tagged] TemplateTail TemplateMiddleList[Yield, Await, Tagged] : TemplateMiddle Expression[+In, ?Yield, ?Await] TemplateMiddleList[?Yield, ?Await, ?Tagged] TemplateMiddle Expression[+In, ?Yield, ?Await]

13.2.8.1 Static Semantics: Early Errors

TemplateLiteral[Yield, Await, Tagged] : NoSubstitutionTemplate TemplateLiteral[Yield, Await, Tagged] : SubstitutionTemplate[?Yield, ?Await, ?Tagged] SubstitutionTemplate[Yield, Await, Tagged] : TemplateHead Expression[+In, ?Yield, ?Await] TemplateSpans[?Yield, ?Await, ?Tagged] TemplateSpans[Yield, Await, Tagged] : TemplateTail TemplateMiddleList[Yield, Await, Tagged] : TemplateMiddle Expression[+In, ?Yield, ?Await] TemplateMiddleList[?Yield, ?Await, ?Tagged] TemplateMiddle Expression[+In, ?Yield, ?Await]

13.2.8.2 Static Semantics: TemplateStrings

The syntax-directed operation TemplateStrings takes argument raw (a Boolean) and returns a List of either Strings or undefined. It is defined piecewise over the following productions:

TemplateLiteral : NoSubstitutionTemplate
  1. « TemplateString(NoSubstitutionTemplate, raw) »를 반환한다.
SubstitutionTemplate : TemplateHead Expression TemplateSpans
  1. head를 « TemplateString(TemplateHead, raw) »로 둔다.
  2. tail을 argument raw를 가진 TemplateSpansTemplateStrings로 둔다.
  3. headtaillist-concatenation을 반환한다.
TemplateSpans : TemplateTail
  1. « TemplateString(TemplateTail, raw) »를 반환한다.
TemplateSpans : TemplateMiddleList TemplateTail
  1. middle을 argument raw를 가진 TemplateMiddleListTemplateStrings로 둔다.
  2. tail을 « TemplateString(TemplateTail, raw) »로 둔다.
  3. middletaillist-concatenation을 반환한다.
TemplateMiddleList : TemplateMiddle Expression
  1. « TemplateString(TemplateMiddle, raw) »를 반환한다.
TemplateMiddleList : TemplateMiddleList TemplateMiddle Expression
  1. front를 argument raw를 가진 TemplateMiddleListTemplateStrings로 둔다.
  2. last를 « TemplateString(TemplateMiddle, raw) »로 둔다.
  3. frontlastlist-concatenation을 반환한다.

13.2.8.3 Static Semantics: TemplateString ( templateToken, raw )

The abstract operation TemplateString takes arguments templateToken (a NoSubstitutionTemplate Parse Node, a TemplateHead Parse Node, a TemplateMiddle Parse Node, or a TemplateTail Parse Node) and raw (a Boolean) and returns a String or undefined. It performs the following steps when called:

  1. rawtrue이면, 다음을 수행한다.
    1. stringtemplateTokenTRV로 둔다.
  2. 그렇지 않으면,
    1. stringtemplateTokenTV로 둔다.
  3. string을 반환한다.
Note

이 operation은 rawfalse이고 templateTokenNotEscapeSequence를 contain하면 undefined를 반환합니다. 그 밖의 모든 경우에는 String을 반환합니다.

13.2.8.4 GetTemplateObject ( templateLiteral )

The abstract operation GetTemplateObject takes argument templateLiteral (a Parse Node) and returns an Array. It performs the following steps when called:

  1. realm을 current Realm Record로 둔다.
  2. templateRegistryrealm.[[TemplateMap]]으로 둔다.
  3. templateRegistry의 각 element element에 대해, 다음을 수행한다.
    1. element.[[Site]]templateLiteral과 같은 Parse Node이면, 다음을 수행한다.
      1. element.[[Array]]를 반환한다.
  4. rawStrings를 argument true를 가진 templateLiteralTemplateStrings로 둔다.
  5. Assert: rawStrings는 String의 List이다.
  6. cookedStrings를 argument false를 가진 templateLiteralTemplateStrings로 둔다.
  7. countList cookedStrings 안의 element 수로 둔다.
  8. Assert: count ≤ 232 - 1이다.
  9. template을 ! ArrayCreate(count)로 둔다.
  10. rawObj를 ! ArrayCreate(count)로 둔다.
  11. index를 0으로 둔다.
  12. index < count인 동안 Repeat,
    1. propertyKey를 ! ToString(𝔽(index))로 둔다.
    2. cookedValuecookedStrings[index]로 둔다.
    3. DefinePropertyOrThrow(template, propertyKey, PropertyDescriptor { [[Value]]: cookedValue, [[Writable]]: false, [[Enumerable]]: true, [[Configurable]]: false })를 수행한다.
    4. rawValue를 String value rawStrings[index]로 둔다.
    5. DefinePropertyOrThrow(rawObj, propertyKey, PropertyDescriptor { [[Value]]: rawValue, [[Writable]]: false, [[Enumerable]]: true, [[Configurable]]: false })를 수행한다.
    6. indexindex + 1로 설정한다.
  13. SetIntegrityLevel(rawObj, frozen)을 수행한다.
  14. DefinePropertyOrThrow(template, "raw", PropertyDescriptor { [[Value]]: rawObj, [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false })를 수행한다.
  15. SetIntegrityLevel(template, frozen)을 수행한다.
  16. Record { [[Site]]: templateLiteral, [[Array]]: template }를 realm.[[TemplateMap]]에 append한다.
  17. template을 반환한다.
Note 1

template object의 creation은 abrupt completion을 result할 수 없습니다.

Note 2

realm의 program code 안의 각 TemplateLiteral은 tagged Template의 evaluation(13.2.8.6)에 사용되는 unique template object와 associated됩니다. template object는 frozen되며, specific tagged Template이 evaluated될 때마다 같은 template object가 사용됩니다. template object가 TemplateLiteral의 first evaluation 시 lazily created되는지 또는 first evaluation 전에 eagerly created되는지는 ECMAScript code에는 observable하지 않은 implementation choice입니다.

Note 3

이 명세의 future edition은 template object의 additional non-enumerable property를 define할 수 있습니다.

13.2.8.5 Runtime Semantics: SubstitutionEvaluation

The syntax-directed operation SubstitutionEvaluation takes no arguments and returns either a normal completion containing a List of ECMAScript language values or an abrupt completion. It is defined piecewise over the following productions:

TemplateSpans : TemplateTail
  1. 새 empty List를 반환한다.
TemplateSpans : TemplateMiddleList TemplateTail
  1. TemplateMiddleListSubstitutionEvaluation을 ? 반환한다.
TemplateMiddleList : TemplateMiddle Expression
  1. subRefExpressionEvaluation으로 ? 둔다.
  2. sub를 ? GetValue(subRef)로 둔다.
  3. « sub »를 반환한다.
TemplateMiddleList : TemplateMiddleList TemplateMiddle Expression
  1. precedingTemplateMiddleListSubstitutionEvaluation으로 ? 둔다.
  2. nextRefExpressionEvaluation으로 ? 둔다.
  3. next를 ? GetValue(nextRef)로 둔다.
  4. preceding과 « next »의 list-concatenation을 반환한다.

13.2.8.6 Runtime Semantics: Evaluation

TemplateLiteral : NoSubstitutionTemplate
  1. 12.9.6에 defined된 NoSubstitutionTemplateTV를 반환한다.
SubstitutionTemplate : TemplateHead Expression TemplateSpans
  1. head12.9.6에 defined된 TemplateHeadTV로 둔다.
  2. subRefExpressionEvaluation으로 ? 둔다.
  3. sub를 ? GetValue(subRef)로 둔다.
  4. middle을 ? ToString(sub)로 둔다.
  5. tailTemplateSpansEvaluation으로 ? 둔다.
  6. head, middle, tailstring-concatenation을 반환한다.
Note 1

Expression value에 applied되는 string conversion semantics는 + operator가 아니라 String.prototype.concat과 같습니다.

TemplateSpans : TemplateTail
  1. 12.9.6에 defined된 TemplateTailTV를 반환한다.
TemplateSpans : TemplateMiddleList TemplateTail
  1. headTemplateMiddleListEvaluation으로 ? 둔다.
  2. tail12.9.6에 defined된 TemplateTailTV로 둔다.
  3. headtailstring-concatenation을 반환한다.
TemplateMiddleList : TemplateMiddle Expression
  1. head12.9.6에 defined된 TemplateMiddleTV로 둔다.
  2. subRefExpressionEvaluation으로 ? 둔다.
  3. sub를 ? GetValue(subRef)로 둔다.
  4. middle을 ? ToString(sub)로 둔다.
  5. headmiddlestring-concatenation을 반환한다.
Note 2

Expression value에 applied되는 string conversion semantics는 + operator가 아니라 String.prototype.concat과 같습니다.

TemplateMiddleList : TemplateMiddleList TemplateMiddle Expression
  1. restTemplateMiddleListEvaluation으로 ? 둔다.
  2. middle12.9.6에 defined된 TemplateMiddleTV로 둔다.
  3. subRefExpressionEvaluation으로 ? 둔다.
  4. sub를 ? GetValue(subRef)로 둔다.
  5. last를 ? ToString(sub)로 둔다.
  6. rest, middle, laststring-concatenation을 반환한다.
Note 3

Expression value에 applied되는 string conversion semantics는 + operator가 아니라 String.prototype.concat과 같습니다.

13.2.9 Grouping Operator

13.2.9.1 Static Semantics: Early Errors

PrimaryExpression : CoverParenthesizedExpressionAndArrowParameterList

13.2.9.2 Runtime Semantics: Evaluation

PrimaryExpression : CoverParenthesizedExpressionAndArrowParameterList
  1. exprCoverParenthesizedExpressionAndArrowParameterList에 의해 covered되는 ParenthesizedExpression로 둔다.
  2. exprEvaluation을 ? 반환한다.
ParenthesizedExpression : ( Expression )
  1. ExpressionEvaluation을 ? 반환한다. 이는 Reference type일 수 있다.
Note

이 algorithm은 ExpressionEvaluationGetValue를 apply하지 않습니다. 이에 대한 principal motivation은 deletetypeof 같은 operator가 parenthesized expression에 applied될 수 있도록 하기 위한 것입니다.

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를 processing할 때, CoverCallExpressionAndAsyncArrowHead의 interpretation은 다음 grammar를 사용하여 refined됩니다:

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
  • 이 production에 의해 source text가 matched되면 Syntax Error입니다.
Note

이 production은 다음 code에 automatic semicolon insertion rule(12.10)이 applied되는 것을 prevent하기 위해 존재합니다:

a?.b
`c`

따라서 이것이 두 개의 valid statement로 interpreted되지 않도록 합니다. 그 purpose는 optional chaining이 없는 similar code와 consistency를 maintain하는 것입니다:

a.b
`c`

이는 valid statement이며 automatic semicolon insertion이 apply되지 않습니다.

ImportMeta : import . meta

13.3.2 Property Accessors

Note

Property는 dot notation을 사용하여 name으로 accessed됩니다:

또는 bracket notation을 사용합니다:

dot notation은 다음 syntactic conversion에 의해 explained됩니다:

는 그 behaviour가 다음과 identical합니다

MemberExpression [ <identifier-name-string> ]

그리고 similarly

는 그 behaviour가 다음과 identical합니다

CallExpression [ <identifier-name-string> ]

여기서 <identifier-name-string>은 IdentifierNameStringValue입니다.

13.3.2.1 Runtime Semantics: Evaluation

MemberExpression : MemberExpression [ Expression ]
  1. baseRefMemberExpressionEvaluation으로 ? 둔다.
  2. baseValue를 ? GetValue(baseRef)로 둔다.
  3. strictIsStrict(this MemberExpression)로 둔다.
  4. EvaluatePropertyAccessWithExpressionKey(baseValue, Expression, strict)를 반환한다.
MemberExpression : MemberExpression . IdentifierName
  1. baseRefMemberExpressionEvaluation으로 ? 둔다.
  2. baseValue를 ? GetValue(baseRef)로 둔다.
  3. strictIsStrict(this MemberExpression)로 둔다.
  4. EvaluatePropertyAccessWithIdentifierKey(baseValue, IdentifierName, strict)를 반환한다.
MemberExpression : MemberExpression . PrivateIdentifier
  1. baseRefMemberExpressionEvaluation으로 ? 둔다.
  2. baseValue를 ? GetValue(baseRef)로 둔다.
  3. fieldNameStringPrivateIdentifierStringValue로 둔다.
  4. MakePrivateReference(baseValue, fieldNameString)를 반환한다.
CallExpression : CallExpression [ Expression ]
  1. baseRefCallExpressionEvaluation으로 ? 둔다.
  2. baseValue를 ? GetValue(baseRef)로 둔다.
  3. strictIsStrict(this CallExpression)로 둔다.
  4. EvaluatePropertyAccessWithExpressionKey(baseValue, Expression, strict)를 반환한다.
CallExpression : CallExpression . IdentifierName
  1. baseRefCallExpressionEvaluation으로 ? 둔다.
  2. baseValue를 ? GetValue(baseRef)로 둔다.
  3. strictIsStrict(this CallExpression)로 둔다.
  4. EvaluatePropertyAccessWithIdentifierKey(baseValue, IdentifierName, strict)를 반환한다.
CallExpression : CallExpression . PrivateIdentifier
  1. baseRefCallExpressionEvaluation으로 ? 둔다.
  2. baseValue를 ? GetValue(baseRef)로 둔다.
  3. fieldNameStringPrivateIdentifierStringValue로 둔다.
  4. MakePrivateReference(baseValue, fieldNameString)를 반환한다.

13.3.3 EvaluatePropertyAccessWithExpressionKey ( baseValue, expr, strict )

The abstract operation EvaluatePropertyAccessWithExpressionKey takes arguments baseValue (an ECMAScript language value), expr (an Expression Parse Node), and strict (a Boolean) and returns either a normal completion containing a Reference Record or an abrupt completion. It performs the following steps when called:

  1. propertyNameRefexprEvaluation으로 ? 둔다.
  2. propertyNameValue를 ? GetValue(propertyNameRef)로 둔다.
  3. NOTE: 대부분의 경우, ToPropertyKey는 이 step 직후 propertyNameValue에 대해 performed됩니다. 그러나 a[b] = c의 경우에는 c의 evaluation 이후까지 performed되지 않습니다.
  4. Reference Record { [[Base]]: baseValue, [[ReferencedName]]: propertyNameValue, [[Strict]]: strict, [[ThisValue]]: empty }를 반환한다.

13.3.4 EvaluatePropertyAccessWithIdentifierKey ( baseValue, identifierName, strict )

The abstract operation EvaluatePropertyAccessWithIdentifierKey takes arguments baseValue (an ECMAScript language value), identifierName (an IdentifierName Parse Node), and strict (a Boolean) and returns a Reference Record. It performs the following steps when called:

  1. propertyNameStringidentifierNameStringValue로 둔다.
  2. Reference Record { [[Base]]: baseValue, [[ReferencedName]]: propertyNameString, [[Strict]]: strict, [[ThisValue]]: empty }를 반환한다.

13.3.5 new Operator

13.3.5.1 Runtime Semantics: Evaluation

NewExpression : new NewExpression
  1. EvaluateNew(NewExpression, empty)를 반환한다.
MemberExpression : new MemberExpression Arguments
  1. EvaluateNew(MemberExpression, Arguments)를 반환한다.

13.3.5.1.1 EvaluateNew ( constructExpr, argumentsNode )

The abstract operation EvaluateNew takes arguments constructExpr (a NewExpression Parse Node or a MemberExpression Parse Node) and argumentsNode (empty or an Arguments Parse Node) and returns either a normal completion containing an Object or an abrupt completion. It performs the following steps when called:

  1. refconstructExprEvaluation으로 ? 둔다.
  2. ctor를 ? GetValue(ref)로 둔다.
  3. argumentsNodeempty이면, 다음을 수행한다.
    1. argList를 새 empty List로 둔다.
  4. 그렇지 않으면,
    1. argListargumentsNodeArgumentListEvaluation으로 ? 둔다.
  5. IsConstructor(ctor)가 false이면, TypeError exception을 throw한다.
  6. Construct(ctor, argList)를 반환한다.

13.3.6 Function Calls

13.3.6.1 Runtime Semantics: Evaluation

CallExpression : CoverCallExpressionAndAsyncArrowHead
  1. exprCoverCallExpressionAndAsyncArrowHead에 의해 covered되는 CallMemberExpression으로 둔다.
  2. memberExprexprMemberExpression으로 둔다.
  3. argsexprArguments로 둔다.
  4. refmemberExprEvaluation으로 ? 둔다.
  5. func를 ? GetValue(ref)로 둔다.
  6. refReference Record이고, IsPropertyReference(ref)가 false이며, ref.[[ReferencedName]]"eval"이면, 다음을 수행한다.
    1. SameValue(func, %eval%)가 true이면, 다음을 수행한다.
      1. argListargsArgumentListEvaluation으로 ? 둔다.
      2. argList가 element를 가지지 않으면, undefined를 반환한다.
      3. evalArgargList의 first element로 둔다.
      4. IsStrict(this CallExpression)가 true이면, strictCallertrue로 둔다; 그렇지 않으면 strictCallerfalse로 둔다.
      5. PerformEval(evalArg, strictCaller, true)를 반환한다.
  7. thisCall을 this CallExpression로 둔다.
  8. tailCallIsInTailPosition(thisCall)으로 둔다.
  9. EvaluateCall(func, ref, args, tailCall)를 반환한다.

step 6.a.v를 execute하는 CallExpression evaluation은 direct eval입니다.

CallExpression : CallExpression Arguments
  1. refCallExpressionEvaluation으로 ? 둔다.
  2. func를 ? GetValue(ref)로 둔다.
  3. thisCall을 this CallExpression로 둔다.
  4. tailCallIsInTailPosition(thisCall)으로 둔다.
  5. EvaluateCall(func, ref, Arguments, tailCall)를 반환한다.

13.3.6.2 EvaluateCall ( func, thisValueRef, argumentListNode, tailPosition )

The abstract operation EvaluateCall takes arguments func (an ECMAScript language value), thisValueRef (an ECMAScript language value or a Reference Record), argumentListNode (a Parse Node), and tailPosition (a Boolean) and returns either a normal completion containing an ECMAScript language value or an abrupt completion. It performs the following steps when called:

  1. thisValueRefReference Record이면, 다음을 수행한다.
    1. IsPropertyReference(thisValueRef)가 true이면, 다음을 수행한다.
      1. thisValueGetThisValue(thisValueRef)로 둔다.
    2. 그렇지 않으면,
      1. refEnvthisValueRef.[[Base]]로 둔다.
      2. Assert: refEnvEnvironment Record이다.
      3. thisValuerefEnv.WithBaseObject()로 둔다.
  2. 그렇지 않으면,
    1. thisValueundefined로 둔다.
  3. argListargumentListNodeArgumentListEvaluation으로 ? 둔다.
  4. func가 Object가 아니면, TypeError exception을 throw한다.
  5. IsCallable(func)가 false이면, TypeError exception을 throw한다.
  6. tailPositiontrue이면, PrepareForTailCall()을 수행한다.
  7. Call(func, thisValue, argList)를 반환한다.

13.3.7 super Keyword

13.3.7.1 Runtime Semantics: Evaluation

SuperProperty : super [ Expression ]
  1. envRecordGetThisEnvironment()로 둔다.
  2. actualThis를 ? envRecord.GetThisBinding()으로 둔다.
  3. propertyNameRefExpressionEvaluation으로 ? 둔다.
  4. propertyNameValue를 ? GetValue(propertyNameRef)로 둔다.
  5. strictIsStrict(this SuperProperty)로 둔다.
  6. NOTE: 대부분의 경우, ToPropertyKey는 이 step 직후 propertyNameValue에 대해 performed됩니다. 그러나 super[b] = c의 경우에는 c의 evaluation 이후까지 performed되지 않습니다.
  7. MakeSuperPropertyReference(actualThis, propertyNameValue, strict)를 반환한다.
SuperProperty : super . IdentifierName
  1. envRecordGetThisEnvironment()로 둔다.
  2. actualThis를 ? envRecord.GetThisBinding()으로 둔다.
  3. propertyKeyIdentifierNameStringValue로 둔다.
  4. strictIsStrict(this SuperProperty)로 둔다.
  5. MakeSuperPropertyReference(actualThis, propertyKey, strict)를 반환한다.
SuperCall : super Arguments
  1. newTargetGetNewTarget()으로 둔다.
  2. Assert: newTargetconstructor이다.
  3. superCtorGetSuperConstructor()로 둔다.
  4. argListArgumentsArgumentListEvaluation으로 ? 둔다.
  5. IsConstructor(superCtor)가 false이면, TypeError exception을 throw한다.
  6. result를 ? Construct(superCtor, argList, newTarget)로 둔다.
  7. thisERGetThisEnvironment()로 둔다.
  8. Assert: thisERFunction Environment Record이다.
  9. BindThisValue(thisER, result)를 수행한다.
  10. funcObjthisER.[[FunctionObject]]로 둔다.
  11. Assert: funcObj는 ECMAScript function object이다.
  12. InitializeInstanceElements(result, funcObj)를 수행한다.
  13. result를 반환한다.

13.3.7.2 GetSuperConstructor ( )

The abstract operation GetSuperConstructor takes no arguments and returns an Object or null. It performs the following steps when called:

  1. envRecordGetThisEnvironment()로 둔다.
  2. Assert: envRecordFunction Environment Record이다.
  3. activeFuncenvRecord.[[FunctionObject]]로 둔다.
  4. Assert: activeFunc는 ECMAScript function object이다.
  5. superCtor를 ! activeFunc.[[GetPrototypeOf]]()로 둔다.
  6. superCtor를 반환한다.

13.3.7.3 MakeSuperPropertyReference ( actualThis, propertyKey, strict )

The abstract operation MakeSuperPropertyReference takes arguments actualThis (an ECMAScript language value), propertyKey (an ECMAScript language value), and strict (a Boolean) and returns a Super Reference Record. It performs the following steps when called:

  1. envRecordGetThisEnvironment()로 둔다.
  2. Assert: envRecord.HasSuperBinding()은 true이다.
  3. Assert: envRecordFunction Environment Record이다.
  4. baseValueGetSuperBase(envRecord)로 둔다.
  5. Reference Record { [[Base]]: baseValue, [[ReferencedName]]: propertyKey, [[Strict]]: strict, [[ThisValue]]: actualThis }를 반환한다.

13.3.8 Argument Lists

Note

argument list의 evaluation은 value의 List를 produce합니다.

13.3.8.1 Runtime Semantics: ArgumentListEvaluation

The syntax-directed operation ArgumentListEvaluation takes no arguments and returns either a normal completion containing a List of ECMAScript language values or an abrupt completion. It is defined piecewise over the following productions:

Arguments : ( )
  1. 새 empty List를 반환한다.
ArgumentList : AssignmentExpression
  1. refAssignmentExpressionEvaluation으로 ? 둔다.
  2. arg를 ? GetValue(ref)로 둔다.
  3. « arg »를 반환한다.
ArgumentList : ... AssignmentExpression
  1. list를 새 empty List로 둔다.
  2. spreadRefAssignmentExpressionEvaluation으로 ? 둔다.
  3. spreadObj를 ? GetValue(spreadRef)로 둔다.
  4. iteratorRecord를 ? GetIterator(spreadObj, sync)로 둔다.
  5. Repeat,
    1. next를 ? IteratorStepValue(iteratorRecord)로 둔다.
    2. nextdone이면, list를 반환한다.
    3. nextlist에 append한다.
ArgumentList : ArgumentList , AssignmentExpression
  1. precedingArgsArgumentListArgumentListEvaluation으로 ? 둔다.
  2. refAssignmentExpressionEvaluation으로 ? 둔다.
  3. arg를 ? GetValue(ref)로 둔다.
  4. precedingArgs와 « arg »의 list-concatenation을 반환한다.
ArgumentList : ArgumentList , ... AssignmentExpression
  1. precedingArgsArgumentListArgumentListEvaluation으로 ? 둔다.
  2. spreadRefAssignmentExpressionEvaluation으로 ? 둔다.
  3. iteratorRecord를 ? GetIterator(? GetValue(spreadRef), sync)로 둔다.
  4. Repeat,
    1. next를 ? IteratorStepValue(iteratorRecord)로 둔다.
    2. nextdone이면, precedingArgs를 반환한다.
    3. nextprecedingArgs에 append한다.
TemplateLiteral : NoSubstitutionTemplate
  1. templateLiteral을 this TemplateLiteral로 둔다.
  2. siteObjGetTemplateObject(templateLiteral)로 둔다.
  3. « siteObj »를 반환한다.
TemplateLiteral : SubstitutionTemplate
  1. templateLiteral을 this TemplateLiteral로 둔다.
  2. siteObjGetTemplateObject(templateLiteral)로 둔다.
  3. remainingSubstitutionTemplateArgumentListEvaluation으로 ? 둔다.
  4. « siteObj »와 remaininglist-concatenation을 반환한다.
SubstitutionTemplate : TemplateHead Expression TemplateSpans
  1. firstSubRefExpressionEvaluation으로 ? 둔다.
  2. firstSub를 ? GetValue(firstSubRef)로 둔다.
  3. restSubTemplateSpansSubstitutionEvaluation으로 ? 둔다.
  4. Assert: restSub는 possibly empty List이다.
  5. « firstSub »와 restSublist-concatenation을 반환한다.

13.3.9 Optional Chains

Note
optional chain은 하나 이상의 property access와 function call의 chain이며, 그 first는 token ?.로 시작합니다.

13.3.9.1 Runtime Semantics: Evaluation

OptionalExpression : MemberExpression OptionalChain
  1. baseRefMemberExpressionEvaluation으로 ? 둔다.
  2. baseValue를 ? GetValue(baseRef)로 둔다.
  3. baseValueundefined 또는 null이면, 다음을 수행한다.
    1. undefined를 반환한다.
  4. arguments baseValuebaseRef를 가진 OptionalChainChainEvaluation을 ? 반환한다.
OptionalExpression : CallExpression OptionalChain
  1. baseRefCallExpressionEvaluation으로 ? 둔다.
  2. baseValue를 ? GetValue(baseRef)로 둔다.
  3. baseValueundefined 또는 null이면, 다음을 수행한다.
    1. undefined를 반환한다.
  4. arguments baseValuebaseRef를 가진 OptionalChainChainEvaluation을 ? 반환한다.
OptionalExpression : OptionalExpression OptionalChain
  1. baseRefOptionalExpressionEvaluation으로 ? 둔다.
  2. baseValue를 ? GetValue(baseRef)로 둔다.
  3. baseValueundefined 또는 null이면, 다음을 수행한다.
    1. undefined를 반환한다.
  4. arguments baseValuebaseRef를 가진 OptionalChainChainEvaluation을 ? 반환한다.

13.3.9.2 Runtime Semantics: ChainEvaluation

The syntax-directed operation ChainEvaluation takes arguments baseValue (an ECMAScript language value) and baseRef (an ECMAScript language value or a Reference Record) and returns either a normal completion containing either an ECMAScript language value or a Reference Record, or an abrupt completion. It is defined piecewise over the following productions:

OptionalChain : ?. Arguments
  1. thisChain을 this OptionalChain로 둔다.
  2. tailCallIsInTailPosition(thisChain)으로 둔다.
  3. EvaluateCall(baseValue, baseRef, Arguments, tailCall)를 반환한다.
OptionalChain : ?. [ Expression ]
  1. strictIsStrict(this OptionalChain)로 둔다.
  2. EvaluatePropertyAccessWithExpressionKey(baseValue, Expression, strict)를 반환한다.
OptionalChain : ?. IdentifierName
  1. strictIsStrict(this OptionalChain)로 둔다.
  2. EvaluatePropertyAccessWithIdentifierKey(baseValue, IdentifierName, strict)를 반환한다.
OptionalChain : ?. PrivateIdentifier
  1. fieldNameStringPrivateIdentifierStringValue로 둔다.
  2. MakePrivateReference(baseValue, fieldNameString)를 반환한다.
OptionalChain : OptionalChain Arguments
  1. optionalChainOptionalChain로 둔다.
  2. newRef를 arguments baseValuebaseRef를 가진 optionalChainChainEvaluation으로 ? 둔다.
  3. newValue를 ? GetValue(newRef)로 둔다.
  4. thisChain을 this OptionalChain로 둔다.
  5. tailCallIsInTailPosition(thisChain)으로 둔다.
  6. EvaluateCall(newValue, newRef, Arguments, tailCall)를 반환한다.
OptionalChain : OptionalChain [ Expression ]
  1. optionalChainOptionalChain로 둔다.
  2. newRef를 arguments baseValuebaseRef를 가진 optionalChainChainEvaluation으로 ? 둔다.
  3. newValue를 ? GetValue(newRef)로 둔다.
  4. strictIsStrict(this OptionalChain)로 둔다.
  5. EvaluatePropertyAccessWithExpressionKey(newValue, Expression, strict)를 반환한다.
OptionalChain : OptionalChain . IdentifierName
  1. optionalChainOptionalChain로 둔다.
  2. newRef를 arguments baseValuebaseRef를 가진 optionalChainChainEvaluation으로 ? 둔다.
  3. newValue를 ? GetValue(newRef)로 둔다.
  4. strictIsStrict(this OptionalChain)로 둔다.
  5. EvaluatePropertyAccessWithIdentifierKey(newValue, IdentifierName, strict)를 반환한다.
OptionalChain : OptionalChain . PrivateIdentifier
  1. optionalChainOptionalChain로 둔다.
  2. newRef를 arguments baseValuebaseRef를 가진 optionalChainChainEvaluation으로 ? 둔다.
  3. newValue를 ? GetValue(newRef)로 둔다.
  4. fieldNameStringPrivateIdentifierStringValue로 둔다.
  5. MakePrivateReference(newValue, fieldNameString)를 반환한다.

13.3.10 Import Calls

13.3.10.1 Runtime Semantics: Evaluation

ImportCall : import ( AssignmentExpression ,opt )
  1. EvaluateImportCall(AssignmentExpression)를 반환한다.
ImportCall : import ( AssignmentExpression , AssignmentExpression ,opt )
  1. EvaluateImportCall(first AssignmentExpression, second AssignmentExpression)를 반환한다.

13.3.10.2 EvaluateImportCall ( specifierExpr [ , optionsExpr ] )

The abstract operation EvaluateImportCall takes argument specifierExpr (a Parse Node) and optional argument optionsExpr (a Parse Node) and returns either a normal completion containing a Promise or an abrupt completion. It performs the following steps when called:

  1. referrerGetActiveScriptOrModule()로 둔다.
  2. referrernull이면, referrer를 current Realm Record로 설정한다.
  3. specifierRefspecifierExprEvaluation으로 ? 둔다.
  4. specifier를 ? GetValue(specifierRef)로 둔다.
  5. optionsExpr가 present하면, 다음을 수행한다.
    1. optionsRefoptionsExprEvaluation으로 ? 둔다.
    2. options를 ? GetValue(optionsRef)로 둔다.
  6. 그렇지 않으면,
    1. optionsundefined로 둔다.
  7. promiseCapability를 ! NewPromiseCapability(%Promise%)로 둔다.
  8. specifierStringCompletion(ToString(specifier))으로 둔다.
  9. IfAbruptRejectPromise(specifierString, promiseCapability).
  10. attrs를 새 empty List로 둔다.
  11. optionsundefined가 아니면, 다음을 수행한다.
    1. options가 Object가 아니면, 다음을 수행한다.
      1. Call(promiseCapability.[[Reject]], undefined, « newly created TypeError object »)를 수행한다.
      2. promiseCapability.[[Promise]]를 반환한다.
    2. attrsObjCompletion(Get(options, "with"))로 둔다.
    3. IfAbruptRejectPromise(attrsObj, promiseCapability).
    4. attrsObjundefined가 아니면, 다음을 수행한다.
      1. attrsObj가 Object가 아니면, 다음을 수행한다.
        1. Call(promiseCapability.[[Reject]], undefined, « newly created TypeError object »)를 수행한다.
        2. promiseCapability.[[Promise]]를 반환한다.
      2. entriesCompletion(EnumerableOwnProperties(attrsObj, key+value))로 둔다.
      3. IfAbruptRejectPromise(entries, promiseCapability).
      4. entries의 각 element entry에 대해, 다음을 수행한다.
        1. key를 ! Get(entry, "0")로 둔다.
        2. value를 ! Get(entry, "1")로 둔다.
        3. key가 String이면, 다음을 수행한다.
          1. value가 String이 아니면, 다음을 수행한다.
            1. Call(promiseCapability.[[Reject]], undefined, « newly created TypeError object »)를 수행한다.
            2. promiseCapability.[[Promise]]를 반환한다.
          2. ImportAttribute Record { [[Key]]: key, [[Value]]: value }를 attrs에 append한다.
    5. AllImportAttributesSupported(attrs)가 false이면, 다음을 수행한다.
      1. Call(promiseCapability.[[Reject]], undefined, « newly created TypeError object »)를 수행한다.
      2. promiseCapability.[[Promise]]를 반환한다.
    6. [[Key]] field의 value를 UTF-16 code unit value의 sequence로 treating하여, [[Key]] field의 lexicographic order에 따라 attrs를 sort한다. NOTE: 이 sorting은 host가 attribute가 enumerated된 order에 based하여 behaviour를 change하는 것이 prohibited된다는 점에서만 observable합니다.
  12. moduleRequest를 새 ModuleRequest Record { [[Specifier]]: specifierString, [[Attributes]]: attrs }로 둔다.
  13. HostLoadImportedModule(referrer, moduleRequest, empty, promiseCapability)를 수행한다.
  14. promiseCapability.[[Promise]]를 반환한다.

13.3.10.3 ContinueDynamicImport ( promiseCapability, moduleCompletion )

The abstract operation ContinueDynamicImport takes arguments promiseCapability (a PromiseCapability Record) and moduleCompletion (either a normal completion containing a Module Record or a throw completion) and returns unused. import() call에 의해 originally started된 dynamic import process를 complete하여, 해당 call이 반환한 promise를 appropriate하게 resolving하거나 rejecting합니다. It performs the following steps when called:

  1. moduleCompletionabrupt completion이면, 다음을 수행한다.
    1. Call(promiseCapability.[[Reject]], undefined, « moduleCompletion.[[Value]] »)를 수행한다.
    2. unused를 반환한다.
  2. modulemoduleCompletion.[[Value]]로 둔다.
  3. loadPromisemodule.LoadRequestedModules()로 둔다.
  4. rejectedClosurepromiseCapability를 capture하고 called될 때 다음 step을 수행하는, parameter (reason)를 가진 새 Abstract Closure로 둔다:
    1. Call(promiseCapability.[[Reject]], undefined, « reason »)를 수행한다.
    2. NormalCompletion(undefined)를 반환한다.
  5. onRejectedCreateBuiltinFunction(rejectedClosure, 1, "", « »)로 둔다.
  6. linkAndEvaluateClosuremodule, promiseCapability, onRejected를 capture하고 called될 때 다음 step을 수행하는, parameter가 없는 새 Abstract Closure로 둔다:
    1. linkCompletion(module.Link())로 둔다.
    2. linkabrupt completion이면, 다음을 수행한다.
      1. Call(promiseCapability.[[Reject]], undefined, « link.[[Value]] »)를 수행한다.
      2. NormalCompletion(undefined)를 반환한다.
    3. evaluatePromisemodule.Evaluate()로 둔다.
    4. fulfilledClosuremodulepromiseCapability를 capture하고 called될 때 다음 step을 수행하는, parameter가 없는 새 Abstract Closure로 둔다:
      1. namespaceGetModuleNamespace(module)로 둔다.
      2. Call(promiseCapability.[[Resolve]], undefined, « namespace »)를 수행한다.
      3. NormalCompletion(undefined)를 반환한다.
    5. onFulfilledCreateBuiltinFunction(fulfilledClosure, 0, "", « »)로 둔다.
    6. PerformPromiseThen(evaluatePromise, onFulfilled, onRejected)를 수행한다.
    7. unused를 반환한다.
  7. linkAndEvaluateCreateBuiltinFunction(linkAndEvaluateClosure, 0, "", « »)로 둔다.
  8. PerformPromiseThen(loadPromise, linkAndEvaluate, onRejected)를 수행한다.
  9. unused를 반환한다.

13.3.11 Tagged Templates

Note

tagged template은 call의 argument가 TemplateLiteral(13.2.8)에서 derived되는 function call입니다. actual argument에는 template object(13.2.8.4)와 TemplateLiteral 안에 embedded된 expression을 evaluating하여 produced된 value가 포함됩니다.

13.3.11.1 Runtime Semantics: Evaluation

MemberExpression : MemberExpression TemplateLiteral
  1. tagRefMemberExpressionEvaluation으로 ? 둔다.
  2. tagFunc를 ? GetValue(tagRef)로 둔다.
  3. thisCall을 this MemberExpression로 둔다.
  4. tailCallIsInTailPosition(thisCall)으로 둔다.
  5. EvaluateCall(tagFunc, tagRef, TemplateLiteral, tailCall)를 반환한다.
CallExpression : CallExpression TemplateLiteral
  1. tagRefCallExpressionEvaluation으로 ? 둔다.
  2. tagFunc를 ? GetValue(tagRef)로 둔다.
  3. thisCall을 this CallExpression로 둔다.
  4. tailCallIsInTailPosition(thisCall)으로 둔다.
  5. EvaluateCall(tagFunc, tagRef, TemplateLiteral, tailCall)를 반환한다.

13.3.12 Meta Properties

13.3.12.1 Runtime Semantics: Evaluation

NewTarget : new . target
  1. GetNewTarget()을 반환한다.
ImportMeta : import . meta
  1. moduleGetActiveScriptOrModule()로 둔다.
  2. Assert: moduleSource Text Module Record이다.
  3. importMetamodule.[[ImportMeta]]로 둔다.
  4. importMetaempty이면, 다음을 수행한다.
    1. importMetaOrdinaryObjectCreate(null)로 설정한다.
    2. importMetaValuesHostGetImportMetaProperties(module)로 둔다.
    3. importMetaValues의 각 Record { [[Key]], [[Value]] } entry에 대해, 다음을 수행한다.
      1. CreateDataPropertyOrThrow(importMeta, entry.[[Key]], entry.[[Value]])를 수행한다.
    4. HostFinalizeImportMeta(importMeta, module)를 수행한다.
    5. module.[[ImportMeta]]importMeta로 설정한다.
    6. importMeta를 반환한다.
  5. Assert: importMeta는 Object이다.
  6. importMeta를 반환한다.

13.3.12.1.1 HostGetImportMetaProperties ( moduleRecord )

The host-defined abstract operation HostGetImportMetaProperties takes argument moduleRecord (a Module Record) and returns a List of Records with fields [[Key]] (a property key) and [[Value]] (an ECMAScript language value). hostimport.meta에서 반환된 object를 위한 property key와 value를 provide할 수 있게 합니다.

HostGetImportMetaProperties의 default implementation은 새 empty 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. hostimport.meta에서 반환된 object를 prepare하기 위해 extraordinary operation을 perform할 수 있게 합니다.

대부분의 host는 단순히 HostGetImportMetaProperties를 define하고, HostFinalizeImportMeta를 default behaviour로 leave할 수 있습니다. 그러나 HostFinalizeImportMeta는 ECMAScript code에 exposed되기 전에 object를 직접 manipulate해야 하는 host를 위한 “escape hatch”를 제공합니다.

HostFinalizeImportMeta의 default implementation은 unused를 반환하는 것입니다.

13.4 Update Expressions

Syntax

UpdateExpression[Yield, Await] : LeftHandSideExpression[?Yield, ?Await] LeftHandSideExpression[?Yield, ?Await] [no LineTerminator here] ++ LeftHandSideExpression[?Yield, ?Await] [no LineTerminator here] -- ++ UnaryExpression[?Yield, ?Await] -- UnaryExpression[?Yield, ?Await]

13.4.1 Static Semantics: Early Errors

UpdateExpression : LeftHandSideExpression ++ LeftHandSideExpression -- UpdateExpression : ++ UnaryExpression -- UnaryExpression

13.4.2 Postfix Increment Operator

13.4.2.1 Runtime Semantics: Evaluation

UpdateExpression : LeftHandSideExpression ++
  1. lhsLeftHandSideExpressionEvaluation으로 ? 둔다.
  2. LeftHandSideExpressionAssignmentTargetTypeweb-compat이면, ReferenceError exception을 throw한다.
  3. oldValue를 ? ToNumeric(? GetValue(lhs))로 둔다.
  4. oldValue가 Number이면, 다음을 수행한다.
    1. newValueNumber::add(oldValue, 1𝔽)로 둔다.
  5. 그렇지 않으면,
    1. Assert: oldValue는 BigInt이다.
    2. newValueBigInt::add(oldValue, 1)로 둔다.
  6. PutValue(lhs, newValue)를 수행한다.
  7. oldValue를 반환한다.

13.4.3 Postfix Decrement Operator

13.4.3.1 Runtime Semantics: Evaluation

UpdateExpression : LeftHandSideExpression --
  1. lhsLeftHandSideExpressionEvaluation으로 ? 둔다.
  2. LeftHandSideExpressionAssignmentTargetTypeweb-compat이면, ReferenceError exception을 throw한다.
  3. oldValue를 ? ToNumeric(? GetValue(lhs))로 둔다.
  4. oldValue가 Number이면, 다음을 수행한다.
    1. newValueNumber::subtract(oldValue, 1𝔽)로 둔다.
  5. 그렇지 않으면,
    1. Assert: oldValue는 BigInt이다.
    2. newValueBigInt::subtract(oldValue, 1)로 둔다.
  6. PutValue(lhs, newValue)를 수행한다.
  7. oldValue를 반환한다.

13.4.4 Prefix Increment Operator

13.4.4.1 Runtime Semantics: Evaluation

UpdateExpression : ++ UnaryExpression
  1. exprUnaryExpressionEvaluation으로 ? 둔다.
  2. UnaryExpressionAssignmentTargetTypeweb-compat이면, ReferenceError exception을 throw한다.
  3. oldValue를 ? ToNumeric(? GetValue(expr))로 둔다.
  4. oldValue가 Number이면, 다음을 수행한다.
    1. newValueNumber::add(oldValue, 1𝔽)로 둔다.
  5. 그렇지 않으면,
    1. Assert: oldValue는 BigInt이다.
    2. newValueBigInt::add(oldValue, 1)로 둔다.
  6. PutValue(expr, newValue)를 수행한다.
  7. newValue를 반환한다.

13.4.5 Prefix Decrement Operator

13.4.5.1 Runtime Semantics: Evaluation

UpdateExpression : -- UnaryExpression
  1. exprUnaryExpressionEvaluation으로 ? 둔다.
  2. UnaryExpressionAssignmentTargetTypeweb-compat이면, ReferenceError exception을 throw한다.
  3. oldValue를 ? ToNumeric(? GetValue(expr))로 둔다.
  4. oldValue가 Number이면, 다음을 수행한다.
    1. newValueNumber::subtract(oldValue, 1𝔽)로 둔다.
  5. 그렇지 않으면,
    1. Assert: oldValue는 BigInt이다.
    2. newValueBigInt::subtract(oldValue, 1)로 둔다.
  6. PutValue(expr, newValue)를 수행한다.
  7. newValue를 반환한다.

13.5 Unary Operators

Syntax

UnaryExpression[Yield, Await] : UpdateExpression[?Yield, ?Await] delete UnaryExpression[?Yield, ?Await] void UnaryExpression[?Yield, ?Await] typeof UnaryExpression[?Yield, ?Await] + UnaryExpression[?Yield, ?Await] - UnaryExpression[?Yield, ?Await] ~ UnaryExpression[?Yield, ?Await] ! UnaryExpression[?Yield, ?Await] [+Await] CoverAwaitExpressionAndAwaitUsingDeclarationHead[?Yield] CoverAwaitExpressionAndAwaitUsingDeclarationHead[Yield] : await UnaryExpression[?Yield, +Await]

보충 구문

생성식의 인스턴스를 처리할 때
UnaryExpression : CoverAwaitExpressionAndAwaitUsingDeclarationHead
CoverAwaitExpressionAndAwaitUsingDeclarationHead의 해석은 다음 문법을 사용하여 정제된다:

AwaitExpression[Yield] : await UnaryExpression[?Yield, +Await]

13.5.1 delete Operator

13.5.1.1 Static Semantics: Early Errors

UnaryExpression : delete UnaryExpression Note

last rule은 delete (((foo))) 같은 expression이 first rule의 recursive application 때문에 early error를 produce한다는 의미입니다.

13.5.1.2 Runtime Semantics: Evaluation

UnaryExpression : delete UnaryExpression
  1. refUnaryExpressionEvaluation으로 ? 둔다.
  2. refReference Record가 아니면, true를 반환한다.
  3. IsUnresolvableReference(ref)가 true이면, 다음을 수행한다.
    1. Assert: ref.[[Strict]]false이다.
    2. true를 반환한다.
  4. IsPropertyReference(ref)가 true이면, 다음을 수행한다.
    1. Assert: IsPrivateReference(ref)는 false이다.
    2. IsSuperReference(ref)가 true이면, ReferenceError exception을 throw한다.
    3. baseObj를 ? ToObject(ref.[[Base]])로 둔다.
    4. ref.[[ReferencedName]]property key가 아니면, 다음을 수행한다.
      1. ref.[[ReferencedName]]을 ? ToPropertyKey(ref.[[ReferencedName]])로 설정한다.
    5. deleteStatus를 ? baseObj.[[Delete]](ref.[[ReferencedName]])로 둔다.
    6. deleteStatusfalse이고 ref.[[Strict]]true이면, TypeError exception을 throw한다.
    7. deleteStatus를 반환한다.
  5. baseref.[[Base]]로 둔다.
  6. Assert: baseEnvironment Record이다.
  7. base.DeleteBinding(ref.[[ReferencedName]])를 반환한다.
Note 1

delete operator가 strict mode code 안에 occur할 때, 그 UnaryExpression이 variable, function argument 또는 function name에 대한 direct reference이면 SyntaxError exception이 throw됩니다. 또한 delete operator가 strict mode code 안에 occur하고 deleted될 property가 attribute { [[Configurable]]: false }를 가지면(또는 otherwise deleted될 수 없으면), TypeError exception이 throw됩니다.

Note 2

step 4.c에서 created될 수 있는 object는 위 abstract operation과 ordinary object [[Delete]] internal method 밖에서는 accessible하지 않습니다. implementation은 그 object의 actual creation을 avoid하도록 choose할 수 있습니다.

13.5.2 void Operator

13.5.2.1 Runtime Semantics: Evaluation

UnaryExpression : void UnaryExpression
  1. exprUnaryExpressionEvaluation으로 ? 둔다.
  2. GetValue(expr)를 수행한다.
  3. undefined를 반환한다.
Note

value가 사용되지 않더라도 observable side-effect가 있을 수 있으므로 GetValue가 called되어야 합니다.

13.5.3 typeof Operator

13.5.3.1 Runtime Semantics: Evaluation

UnaryExpression : typeof UnaryExpression
  1. valueUnaryExpressionEvaluation으로 ? 둔다.
  2. valueReference Record이면, 다음을 수행한다.
    1. IsUnresolvableReference(value)가 true이면, "undefined"를 반환한다.
  3. value를 ? GetValue(value)로 설정한다.
  4. valueundefined이면, "undefined"를 반환한다.
  5. valuenull이면, "object"를 반환한다.
  6. value가 String이면, "string"을 반환한다.
  7. value가 Symbol이면, "symbol"을 반환한다.
  8. value가 Boolean이면, "boolean"을 반환한다.
  9. value가 Number이면, "number"를 반환한다.
  10. value가 BigInt이면, "bigint"를 반환한다.
  11. Assert: value는 Object이다.
  12. host가 web browser이거나 그 밖에 [[IsHTMLDDA]] Internal Slot를 support하면, 다음을 수행한다.
    1. value[[IsHTMLDDA]] internal slot을 가지면, "undefined"를 반환한다.
  13. value[[Call]] internal method를 가지면, "function"을 반환한다.
  14. "object"를 반환한다.

13.5.4 Unary + Operator

Note

unary + operator는 그 operand를 Number type으로 convert합니다.

13.5.4.1 Runtime Semantics: Evaluation

UnaryExpression : + UnaryExpression
  1. exprUnaryExpressionEvaluation으로 ? 둔다.
  2. ToNumber(? GetValue(expr))를 반환한다.

13.5.5 Unary - Operator

Note

unary - operator는 그 operand를 numeric value로 convert한 다음 negate합니다. +0𝔽를 negating하면 -0𝔽가 produce되고, -0𝔽를 negating하면 +0𝔽가 produce됩니다.

13.5.5.1 Runtime Semantics: Evaluation

UnaryExpression : - UnaryExpression
  1. exprUnaryExpressionEvaluation으로 ? 둔다.
  2. oldValue를 ? ToNumeric(? GetValue(expr))로 둔다.
  3. oldValue가 Number이면, Number::unaryMinus(oldValue)를 반환한다.
  4. Assert: oldValue는 BigInt이다.
  5. BigInt::unaryMinus(oldValue)를 반환한다.

13.5.6 Bitwise NOT Operator ( ~ )

13.5.6.1 Runtime Semantics: Evaluation

UnaryExpression : ~ UnaryExpression
  1. exprUnaryExpressionEvaluation으로 ? 둔다.
  2. oldValue를 ? ToNumeric(? GetValue(expr))로 둔다.
  3. oldValue가 Number이면, Number::bitwiseNOT(oldValue)를 반환한다.
  4. Assert: oldValue는 BigInt이다.
  5. BigInt::bitwiseNOT(oldValue)를 반환한다.

13.5.7 Logical NOT Operator ( ! )

13.5.7.1 Runtime Semantics: Evaluation

UnaryExpression : ! UnaryExpression
  1. exprUnaryExpressionEvaluation으로 ? 둔다.
  2. oldValueToBoolean(? GetValue(expr))로 둔다.
  3. oldValuetrue이면, false를 반환한다.
  4. true를 반환한다.

13.6 Exponentiation Operator

Syntax

ExponentiationExpression[Yield, Await] : UnaryExpression[?Yield, ?Await] UpdateExpression[?Yield, ?Await] ** ExponentiationExpression[?Yield, ?Await]

13.6.1 Runtime Semantics: Evaluation

ExponentiationExpression : UpdateExpression ** ExponentiationExpression
  1. EvaluateStringOrNumericBinaryExpression(UpdateExpression, **, ExponentiationExpression)를 반환한다.

13.7 Multiplicative Operators

Syntax

MultiplicativeExpression[Yield, Await] : ExponentiationExpression[?Yield, ?Await] MultiplicativeExpression[?Yield, ?Await] MultiplicativeOperator ExponentiationExpression[?Yield, ?Await] MultiplicativeOperator : one of * / % Note
  • * operator는 multiplication을 수행하여 operand의 product를 produce합니다.
  • / operator는 division을 수행하여 operand의 quotient를 produce합니다.
  • % operator는 implied division에서 operand의 remainder를 yield합니다.

13.7.1 Runtime Semantics: Evaluation

MultiplicativeExpression : MultiplicativeExpression MultiplicativeOperator ExponentiationExpression
  1. opTextMultiplicativeOperator에 matched된 source text로 둔다.
  2. EvaluateStringOrNumericBinaryExpression(MultiplicativeExpression, opText, ExponentiationExpression)를 반환한다.

13.8 Additive Operators

Syntax

AdditiveExpression[Yield, Await] : MultiplicativeExpression[?Yield, ?Await] AdditiveExpression[?Yield, ?Await] + MultiplicativeExpression[?Yield, ?Await] AdditiveExpression[?Yield, ?Await] - MultiplicativeExpression[?Yield, ?Await]

13.8.1 Addition Operator ( + )

Note

addition operator는 string concatenation 또는 numeric addition을 수행합니다.

13.8.1.1 Runtime Semantics: Evaluation

AdditiveExpression : AdditiveExpression + MultiplicativeExpression
  1. EvaluateStringOrNumericBinaryExpression(AdditiveExpression, +, MultiplicativeExpression)를 반환한다.

13.8.2 Subtraction Operator ( - )

Note

- operator는 subtraction을 수행하여 operand의 difference를 produce합니다.

13.8.2.1 Runtime Semantics: Evaluation

AdditiveExpression : AdditiveExpression - MultiplicativeExpression
  1. EvaluateStringOrNumericBinaryExpression(AdditiveExpression, -, MultiplicativeExpression)를 반환한다.

13.9 Bitwise Shift Operators

Syntax

ShiftExpression[Yield, Await] : AdditiveExpression[?Yield, ?Await] ShiftExpression[?Yield, ?Await] << AdditiveExpression[?Yield, ?Await] ShiftExpression[?Yield, ?Await] >> AdditiveExpression[?Yield, ?Await] ShiftExpression[?Yield, ?Await] >>> AdditiveExpression[?Yield, ?Await]

13.9.1 Left Shift Operator ( << )

Note

left operand에 대해 right operand가 specified하는 amount만큼 bitwise left shift operation을 수행합니다.

13.9.1.1 Runtime Semantics: Evaluation

ShiftExpression : ShiftExpression << AdditiveExpression
  1. EvaluateStringOrNumericBinaryExpression(ShiftExpression, <<, AdditiveExpression)를 반환한다.

13.9.2 Signed Right Shift Operator ( >> )

Note

left operand에 대해 right operand가 specified하는 amount만큼 sign-filling bitwise right shift operation을 수행합니다.

13.9.2.1 Runtime Semantics: Evaluation

ShiftExpression : ShiftExpression >> AdditiveExpression
  1. EvaluateStringOrNumericBinaryExpression(ShiftExpression, >>, AdditiveExpression)를 반환한다.

13.9.3 Unsigned Right Shift Operator ( >>> )

Note

left operand에 대해 right operand가 specified하는 amount만큼 zero-filling bitwise right shift operation을 수행합니다.

13.9.3.1 Runtime Semantics: Evaluation

ShiftExpression : ShiftExpression >>> AdditiveExpression
  1. EvaluateStringOrNumericBinaryExpression(ShiftExpression, >>>, AdditiveExpression)를 반환한다.

13.10 Relational Operators

Note 1

relational operator를 evaluating한 result는 항상 Boolean type이며, operator가 named한 relationship이 두 operand 사이에서 holds하는지를 reflect합니다.

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를 confuse하는 것을 avoid하기 위해 필요합니다.

13.10.1 Runtime Semantics: Evaluation

RelationalExpression : RelationalExpression < ShiftExpression
  1. leftRefRelationalExpressionEvaluation으로 ? 둔다.
  2. leftValue를 ? GetValue(leftRef)로 둔다.
  3. rightRefShiftExpressionEvaluation으로 ? 둔다.
  4. rightValue를 ? GetValue(rightRef)로 둔다.
  5. result를 ? IsLessThan(leftValue, rightValue, true)로 둔다.
  6. resultundefined이면, false를 반환한다.
  7. result를 반환한다.
RelationalExpression : RelationalExpression > ShiftExpression
  1. leftRefRelationalExpressionEvaluation으로 ? 둔다.
  2. leftValue를 ? GetValue(leftRef)로 둔다.
  3. rightRefShiftExpressionEvaluation으로 ? 둔다.
  4. rightValue를 ? GetValue(rightRef)로 둔다.
  5. result를 ? IsLessThan(rightValue, leftValue, false)로 둔다.
  6. resultundefined이면, false를 반환한다.
  7. result를 반환한다.
RelationalExpression : RelationalExpression <= ShiftExpression
  1. leftRefRelationalExpressionEvaluation으로 ? 둔다.
  2. leftValue를 ? GetValue(leftRef)로 둔다.
  3. rightRefShiftExpressionEvaluation으로 ? 둔다.
  4. rightValue를 ? GetValue(rightRef)로 둔다.
  5. result를 ? IsLessThan(rightValue, leftValue, false)로 둔다.
  6. resulttrue 또는 undefined이면, false를 반환한다.
  7. true를 반환한다.
RelationalExpression : RelationalExpression >= ShiftExpression
  1. leftRefRelationalExpressionEvaluation으로 ? 둔다.
  2. leftValue를 ? GetValue(leftRef)로 둔다.
  3. rightRefShiftExpressionEvaluation으로 ? 둔다.
  4. rightValue를 ? GetValue(rightRef)로 둔다.
  5. result를 ? IsLessThan(leftValue, rightValue, true)로 둔다.
  6. resulttrue 또는 undefined이면, false를 반환한다.
  7. true를 반환한다.
RelationalExpression : RelationalExpression instanceof ShiftExpression
  1. leftRefRelationalExpressionEvaluation으로 ? 둔다.
  2. leftValue를 ? GetValue(leftRef)로 둔다.
  3. rightRefShiftExpressionEvaluation으로 ? 둔다.
  4. rightValue를 ? GetValue(rightRef)로 둔다.
  5. InstanceofOperator(leftValue, rightValue)를 반환한다.
RelationalExpression : RelationalExpression in ShiftExpression
  1. leftRefRelationalExpressionEvaluation으로 ? 둔다.
  2. leftValue를 ? GetValue(leftRef)로 둔다.
  3. rightRefShiftExpressionEvaluation으로 ? 둔다.
  4. rightValue를 ? GetValue(rightRef)로 둔다.
  5. rightValue가 Object가 아니면, TypeError exception을 throw한다.
  6. HasProperty(rightValue, ? ToPropertyKey(leftValue))를 반환한다.
RelationalExpression : PrivateIdentifier in ShiftExpression
  1. privateIdentifierPrivateIdentifierStringValue로 둔다.
  2. rightRefShiftExpressionEvaluation으로 ? 둔다.
  3. rightValue를 ? GetValue(rightRef)로 둔다.
  4. rightValue가 Object가 아니면, TypeError exception을 throw한다.
  5. privateEnvrunning execution context의 PrivateEnvironment로 둔다.
  6. Assert: privateEnvnull이 아니다.
  7. privateNameResolvePrivateIdentifier(privateEnv, privateIdentifier)로 둔다.
  8. PrivateElementFind(rightValue, privateName)가 empty이면, false를 반환한다.
  9. true를 반환한다.

13.10.2 InstanceofOperator ( value, target )

The abstract operation InstanceofOperator takes arguments value (an ECMAScript language value) and target (an ECMAScript language value) and returns either a normal completion containing a Boolean or a throw completion. target%Symbol.hasInstance% method를 consult하거나, 그것이 absent하면 target"prototype" property의 value가 value의 prototype chain 안에 present한지를 determine하여, valuetarget의 instance인지 determine하는 generic algorithm을 implements합니다. It performs the following steps when called:

  1. target이 Object가 아니면, TypeError exception을 throw한다.
  2. instOfHandler를 ? GetMethod(target, %Symbol.hasInstance%)로 둔다.
  3. instOfHandlerundefined가 아니면, 다음을 수행한다.
    1. ToBoolean(? Call(instOfHandler, target, « value »))를 반환한다.
  4. IsCallable(target)이 false이면, TypeError exception을 throw한다.
  5. OrdinaryHasInstance(target, value)를 반환한다.
Note

step 45instanceof operator semantics를 define하기 위해 %Symbol.hasInstance% method를 사용하지 않았던 ECMAScript의 previous edition과의 compatibility를 제공합니다. object가 %Symbol.hasInstance%를 define하거나 inherit하지 않으면 default instanceof semantics를 사용합니다.

13.11 Equality Operators

Note

equality operator를 evaluating한 result는 항상 Boolean type이며, operator가 named한 relationship이 두 operand 사이에서 holds하는지를 reflect합니다.

Syntax

EqualityExpression[In, Yield, Await] : RelationalExpression[?In, ?Yield, ?Await] EqualityExpression[?In, ?Yield, ?Await] == RelationalExpression[?In, ?Yield, ?Await] EqualityExpression[?In, ?Yield, ?Await] != RelationalExpression[?In, ?Yield, ?Await] EqualityExpression[?In, ?Yield, ?Await] === RelationalExpression[?In, ?Yield, ?Await] EqualityExpression[?In, ?Yield, ?Await] !== RelationalExpression[?In, ?Yield, ?Await]

13.11.1 Runtime Semantics: Evaluation

EqualityExpression : EqualityExpression == RelationalExpression
  1. leftRefEqualityExpressionEvaluation으로 ? 둔다.
  2. leftValue를 ? GetValue(leftRef)로 둔다.
  3. rightRefRelationalExpressionEvaluation으로 ? 둔다.
  4. rightValue를 ? GetValue(rightRef)로 둔다.
  5. IsLooselyEqual(rightValue, leftValue)를 반환한다.
EqualityExpression : EqualityExpression != RelationalExpression
  1. leftRefEqualityExpressionEvaluation으로 ? 둔다.
  2. leftValue를 ? GetValue(leftRef)로 둔다.
  3. rightRefRelationalExpressionEvaluation으로 ? 둔다.
  4. rightValue를 ? GetValue(rightRef)로 둔다.
  5. result를 ? IsLooselyEqual(rightValue, leftValue)로 둔다.
  6. resulttrue이면, false를 반환한다.
  7. true를 반환한다.
EqualityExpression : EqualityExpression === RelationalExpression
  1. leftRefEqualityExpressionEvaluation으로 ? 둔다.
  2. leftValue를 ? GetValue(leftRef)로 둔다.
  3. rightRefRelationalExpressionEvaluation으로 ? 둔다.
  4. rightValue를 ? GetValue(rightRef)로 둔다.
  5. IsStrictlyEqual(rightValue, leftValue)를 반환한다.
EqualityExpression : EqualityExpression !== RelationalExpression
  1. leftRefEqualityExpressionEvaluation으로 ? 둔다.
  2. leftValue를 ? GetValue(leftRef)로 둔다.
  3. rightRefRelationalExpressionEvaluation으로 ? 둔다.
  4. rightValue를 ? GetValue(rightRef)로 둔다.
  5. resultIsStrictlyEqual(rightValue, leftValue)로 둔다.
  6. resulttrue이면, false를 반환한다.
  7. true를 반환한다.
Note 1

equality operator는 다음 invariant를 maintain합니다:

  • A != B!(A == B)와 equivalent합니다.
  • A == BAB의 evaluation order를 제외하면 B == A와 equivalent합니다.
Note 2

equality operator는 항상 transitive하지는 않습니다. 예를 들어 같은 String value를 각각 representing하는 두 distinct String object가 있을 수 있습니다; 각 String object는 == operator에 의해 String value와 equal하다고 considered되지만, 두 String object는 서로 equal하지 않습니다. 예:

  • new String("a") == "a""a" == new String("a")는 모두 true입니다.
  • new String("a") == new String("a")false입니다.
Note 3

String의 comparison은 code unit value의 sequence에 대한 simple equality test를 사용합니다. Unicode specification에 defined된 character 또는 string equality 및 collating order의 더 complex하고 semantically oriented한 definition을 사용하려는 attempt는 없습니다. 따라서 Unicode Standard에 따라 canonically equal한 String value가 unequal로 test될 수 있습니다. 사실상 이 algorithm은 두 String이 이미 normalized form에 있다고 assume합니다.

13.12 Binary Bitwise Operators

Syntax

BitwiseANDExpression[In, Yield, Await] : EqualityExpression[?In, ?Yield, ?Await] BitwiseANDExpression[?In, ?Yield, ?Await] & EqualityExpression[?In, ?Yield, ?Await] BitwiseXORExpression[In, Yield, Await] : BitwiseANDExpression[?In, ?Yield, ?Await] BitwiseXORExpression[?In, ?Yield, ?Await] ^ BitwiseANDExpression[?In, ?Yield, ?Await] BitwiseORExpression[In, Yield, Await] : BitwiseXORExpression[?In, ?Yield, ?Await] BitwiseORExpression[?In, ?Yield, ?Await] | BitwiseXORExpression[?In, ?Yield, ?Await]

13.12.1 Runtime Semantics: Evaluation

BitwiseANDExpression : BitwiseANDExpression & EqualityExpression
  1. EvaluateStringOrNumericBinaryExpression(BitwiseANDExpression, &, EqualityExpression)를 반환한다.
BitwiseXORExpression : BitwiseXORExpression ^ BitwiseANDExpression
  1. EvaluateStringOrNumericBinaryExpression(BitwiseXORExpression, ^, BitwiseANDExpression)를 반환한다.
BitwiseORExpression : BitwiseORExpression | BitwiseXORExpression
  1. EvaluateStringOrNumericBinaryExpression(BitwiseORExpression, |, BitwiseXORExpression)를 반환한다.

13.13 Binary Logical Operators

Syntax

LogicalANDExpression[In, Yield, Await] : BitwiseORExpression[?In, ?Yield, ?Await] LogicalANDExpression[?In, ?Yield, ?Await] && BitwiseORExpression[?In, ?Yield, ?Await] LogicalORExpression[In, Yield, Await] : LogicalANDExpression[?In, ?Yield, ?Await] LogicalORExpression[?In, ?Yield, ?Await] || LogicalANDExpression[?In, ?Yield, ?Await] CoalesceExpression[In, Yield, Await] : CoalesceExpressionHead[?In, ?Yield, ?Await] ?? BitwiseORExpression[?In, ?Yield, ?Await] CoalesceExpressionHead[In, Yield, Await] : CoalesceExpression[?In, ?Yield, ?Await] BitwiseORExpression[?In, ?Yield, ?Await] ShortCircuitExpression[In, Yield, Await] : LogicalORExpression[?In, ?Yield, ?Await] CoalesceExpression[?In, ?Yield, ?Await] Note

&& 또는 || operator가 produced하는 value는 반드시 Boolean type일 필요는 없습니다. produced되는 value는 항상 두 operand expression 중 하나의 value입니다.

13.13.1 Runtime Semantics: Evaluation

LogicalANDExpression : LogicalANDExpression && BitwiseORExpression
  1. leftRefLogicalANDExpressionEvaluation으로 ? 둔다.
  2. leftValue를 ? GetValue(leftRef)로 둔다.
  3. ToBoolean(leftValue)가 false이면, leftValue를 반환한다.
  4. rightRefBitwiseORExpressionEvaluation으로 ? 둔다.
  5. GetValue(rightRef)를 반환한다.
LogicalORExpression : LogicalORExpression || LogicalANDExpression
  1. leftRefLogicalORExpressionEvaluation으로 ? 둔다.
  2. leftValue를 ? GetValue(leftRef)로 둔다.
  3. ToBoolean(leftValue)가 true이면, leftValue를 반환한다.
  4. rightRefLogicalANDExpressionEvaluation으로 ? 둔다.
  5. GetValue(rightRef)를 반환한다.
CoalesceExpression : CoalesceExpressionHead ?? BitwiseORExpression
  1. leftRefCoalesceExpressionHeadEvaluation으로 ? 둔다.
  2. leftValue를 ? GetValue(leftRef)로 둔다.
  3. leftValueundefinednull도 아니면, leftValue를 반환한다.
  4. rightRefBitwiseORExpressionEvaluation으로 ? 둔다.
  5. GetValue(rightRef)를 반환한다.

13.14 Conditional Operator ( ? : )

Syntax

ConditionalExpression[In, Yield, Await] : ShortCircuitExpression[?In, ?Yield, ?Await] ShortCircuitExpression[?In, ?Yield, ?Await] ? AssignmentExpression[+In, ?Yield, ?Await] : AssignmentExpression[?In, ?Yield, ?Await] Note

ECMAScript에서 ConditionalExpression의 grammar는 C 및 Java의 grammar와 약간 다릅니다. C와 Java는 second subexpression을 Expression으로 allow하지만 third expression은 ConditionalExpression으로 restrict합니다. ECMAScript에서 이 차이의 motivation은 conditional의 어느 arm이든 assignment expression에 의해 governed될 수 있도록 하고, centre expression으로서 comma expression이라는 confusing하고 fairly useless한 case를 eliminate하기 위한 것입니다.

13.14.1 Runtime Semantics: Evaluation

ConditionalExpression : ShortCircuitExpression ? AssignmentExpression : AssignmentExpression
  1. leftRefShortCircuitExpressionEvaluation으로 ? 둔다.
  2. leftValueToBoolean(? GetValue(leftRef))로 둔다.
  3. leftValuetrue이면, 다음을 수행한다.
    1. trueRef를 first AssignmentExpressionEvaluation으로 ? 둔다.
    2. GetValue(trueRef)를 반환한다.
  4. falseRef를 second AssignmentExpressionEvaluation으로 ? 둔다.
  5. GetValue(falseRef)를 반환한다.

13.15 Assignment Operators

Syntax

AssignmentExpression[In, Yield, Await] : ConditionalExpression[?In, ?Yield, ?Await] [+Yield] YieldExpression[?In, ?Await] ArrowFunction[?In, ?Yield, ?Await] AsyncArrowFunction[?In, ?Yield, ?Await] LeftHandSideExpression[?Yield, ?Await] = AssignmentExpression[?In, ?Yield, ?Await] LeftHandSideExpression[?Yield, ?Await] AssignmentOperator AssignmentExpression[?In, ?Yield, ?Await] LeftHandSideExpression[?Yield, ?Await] &&= AssignmentExpression[?In, ?Yield, ?Await] LeftHandSideExpression[?Yield, ?Await] ||= AssignmentExpression[?In, ?Yield, ?Await] LeftHandSideExpression[?Yield, ?Await] ??= AssignmentExpression[?In, ?Yield, ?Await] AssignmentOperator : one of *= /= %= += -= <<= >>= >>>= &= ^= |= **=

13.15.1 Static Semantics: Early Errors

AssignmentExpression : LeftHandSideExpression = AssignmentExpression AssignmentExpression : LeftHandSideExpression AssignmentOperator AssignmentExpression AssignmentExpression : LeftHandSideExpression &&= AssignmentExpression LeftHandSideExpression ||= AssignmentExpression LeftHandSideExpression ??= AssignmentExpression

13.15.2 Runtime Semantics: Evaluation

AssignmentExpression : LeftHandSideExpression = AssignmentExpression
  1. LeftHandSideExpressionObjectLiteralArrayLiteral도 아니면, 다음을 수행한다.
    1. leftRefLeftHandSideExpressionEvaluation으로 ? 둔다.
    2. LeftHandSideExpressionAssignmentTargetTypeweb-compat이면, ReferenceError exception을 throw한다.
    3. IsAnonymousFunctionDefinition(AssignmentExpression)이 true이고 LeftHandSideExpressionIsIdentifierReftrue이면, 다음을 수행한다.
      1. lhsLeftHandSideExpressionStringValue로 둔다.
      2. rightValue를 argument lhs를 가진 AssignmentExpressionNamedEvaluation으로 ? 둔다.
    4. 그렇지 않으면,
      1. rightRefAssignmentExpressionEvaluation으로 ? 둔다.
      2. rightValue를 ? GetValue(rightRef)로 둔다.
    5. PutValue(leftRef, rightValue)를 수행한다.
    6. rightValue를 반환한다.
  2. assignmentPatternLeftHandSideExpressioncovered하는 AssignmentPattern으로 둔다.
  3. rightRefAssignmentExpressionEvaluation으로 ? 둔다.
  4. rightValue를 ? GetValue(rightRef)로 둔다.
  5. argument rightValue를 가진 assignmentPatternDestructuringAssignmentEvaluation을 ? 수행한다.
  6. rightValue를 반환한다.
AssignmentExpression : LeftHandSideExpression AssignmentOperator AssignmentExpression
  1. leftRefLeftHandSideExpressionEvaluation으로 ? 둔다.
  2. LeftHandSideExpressionAssignmentTargetTypeweb-compat이면, ReferenceError exception을 throw한다.
  3. leftValue를 ? GetValue(leftRef)로 둔다.
  4. rightRefAssignmentExpressionEvaluation으로 ? 둔다.
  5. rightValue를 ? GetValue(rightRef)로 둔다.
  6. assignmentOpTextAssignmentOperator에 matched된 source text로 둔다.
  7. opText를 다음 table에서 assignmentOpText와 associated된 Unicode code point의 sequence로 둔다:
    assignmentOpText opText
    **= **
    *= *
    /= /
    %= %
    += +
    -= -
    <<= <<
    >>= >>
    >>>= >>>
    &= &
    ^= ^
    |= |
  8. result를 ? ApplyStringOrNumericBinaryOperator(leftValue, opText, rightValue)로 둔다.
  9. PutValue(leftRef, result)를 수행한다.
  10. result를 반환한다.
AssignmentExpression : LeftHandSideExpression &&= AssignmentExpression
  1. leftRefLeftHandSideExpressionEvaluation으로 ? 둔다.
  2. leftValue를 ? GetValue(leftRef)로 둔다.
  3. ToBoolean(leftValue)가 false이면, leftValue를 반환한다.
  4. IsAnonymousFunctionDefinition(AssignmentExpression)이 true이고 LeftHandSideExpressionIsIdentifierReftrue이면, 다음을 수행한다.
    1. lhsLeftHandSideExpressionStringValue로 둔다.
    2. rightValue를 argument lhs를 가진 AssignmentExpressionNamedEvaluation으로 ? 둔다.
  5. 그렇지 않으면,
    1. rightRefAssignmentExpressionEvaluation으로 ? 둔다.
    2. rightValue를 ? GetValue(rightRef)로 둔다.
  6. PutValue(leftRef, rightValue)를 수행한다.
  7. rightValue를 반환한다.
AssignmentExpression : LeftHandSideExpression ||= AssignmentExpression
  1. leftRefLeftHandSideExpressionEvaluation으로 ? 둔다.
  2. leftValue를 ? GetValue(leftRef)로 둔다.
  3. ToBoolean(leftValue)가 true이면, leftValue를 반환한다.
  4. IsAnonymousFunctionDefinition(AssignmentExpression)이 true이고 LeftHandSideExpressionIsIdentifierReftrue이면, 다음을 수행한다.
    1. lhsLeftHandSideExpressionStringValue로 둔다.
    2. rightValue를 argument lhs를 가진 AssignmentExpressionNamedEvaluation으로 ? 둔다.
  5. 그렇지 않으면,
    1. rightRefAssignmentExpressionEvaluation으로 ? 둔다.
    2. rightValue를 ? GetValue(rightRef)로 둔다.
  6. PutValue(leftRef, rightValue)를 수행한다.
  7. rightValue를 반환한다.
AssignmentExpression : LeftHandSideExpression ??= AssignmentExpression
  1. leftRefLeftHandSideExpressionEvaluation으로 ? 둔다.
  2. leftValue를 ? GetValue(leftRef)로 둔다.
  3. leftValueundefinednull도 아니면, leftValue를 반환한다.
  4. IsAnonymousFunctionDefinition(AssignmentExpression)이 true이고 LeftHandSideExpressionIsIdentifierReftrue이면, 다음을 수행한다.
    1. lhsLeftHandSideExpressionStringValue로 둔다.
    2. rightValue를 argument lhs를 가진 AssignmentExpressionNamedEvaluation으로 ? 둔다.
  5. 그렇지 않으면,
    1. rightRefAssignmentExpressionEvaluation으로 ? 둔다.
    2. rightValue를 ? GetValue(rightRef)로 둔다.
  6. PutValue(leftRef, rightValue)를 수행한다.
  7. rightValue를 반환한다.
Note

이 expression이 strict mode code 안에 occur할 때, step 1.e, 3, 2, 2, 2leftRef가 unresolvable reference이면 runtime error입니다. 그러한 경우 ReferenceError exception이 throw됩니다. 추가로, step 9, 6, 6, 6leftRef가 attribute value { [[Writable]]: false }를 가진 data property에 대한 reference이거나, attribute value { [[Set]]: undefined }를 가진 accessor property에 대한 reference이거나, IsExtensible predicate가 value false를 반환하는 object의 non-existent property에 대한 reference이면 runtime error입니다. 이러한 경우 TypeError exception이 throw됩니다.

13.15.3 ApplyStringOrNumericBinaryOperator ( leftValue, opText, rightValue )

The abstract operation ApplyStringOrNumericBinaryOperator takes arguments leftValue (an ECMAScript language value), opText (**, *, /, %, +, -, <<, >>, >>>, &, ^, or |), and rightValue (an ECMAScript language value) and returns either a normal completion containing either a String, a BigInt, or a Number, or a throw completion. It performs the following steps when called:

  1. opText+이면, 다음을 수행한다.
    1. leftPrimitive를 ? ToPrimitive(leftValue)로 둔다.
    2. rightPrimitive를 ? ToPrimitive(rightValue)로 둔다.
    3. leftPrimitive가 String이거나 rightPrimitive가 String이면, 다음을 수행한다.
      1. leftString을 ? ToString(leftPrimitive)로 둔다.
      2. rightString을 ? ToString(rightPrimitive)로 둔다.
      3. leftStringrightStringstring-concatenation을 반환한다.
    4. leftValueleftPrimitive로 설정한다.
    5. rightValuerightPrimitive로 설정한다.
  2. NOTE: 이 시점에서는 numeric operation이어야 한다.
  3. leftNumber를 ? ToNumeric(leftValue)로 둔다.
  4. rightNumber를 ? ToNumeric(rightValue)로 둔다.
  5. SameType(leftNumber, rightNumber)이 false이면, TypeError exception을 throw한다.
  6. leftNumber가 BigInt이면, 다음을 수행한다.
    1. opText**이면, ? BigInt::exponentiate(leftNumber, rightNumber)를 반환한다.
    2. opText/이면, ? BigInt::divide(leftNumber, rightNumber)를 반환한다.
    3. opText%이면, ? BigInt::remainder(leftNumber, rightNumber)를 반환한다.
    4. opText>>>이면, ? BigInt::unsignedRightShift(leftNumber, rightNumber)를 반환한다.
    5. operation을 다음 table에서 opText와 associated된 abstract operation으로 둔다:
      opText operation
      * BigInt::multiply
      + BigInt::add
      - BigInt::subtract
      << BigInt::leftShift
      >> BigInt::signedRightShift
      & BigInt::bitwiseAND
      ^ BigInt::bitwiseXOR
      | BigInt::bitwiseOR
  7. 그렇지 않으면,
    1. Assert: leftNumber는 Number이다.
    2. operation을 다음 table에서 opText와 associated된 abstract operation으로 둔다:
      opText operation
      ** Number::exponentiate
      * Number::multiply
      / Number::divide
      % Number::remainder
      + Number::add
      - Number::subtract
      << Number::leftShift
      >> Number::signedRightShift
      >>> Number::unsignedRightShift
      & Number::bitwiseAND
      ^ Number::bitwiseXOR
      | Number::bitwiseOR
  8. operation(leftNumber, rightNumber)를 반환한다.
Note 1

step 1.a1.bToPrimitive call에는 hint가 provided되지 않습니다. Date를 제외한 모든 standard object는 hint의 absence를 number가 given된 것처럼 handle합니다; Date는 hint의 absence를 string이 given된 것처럼 handle합니다. Exotic object는 hint의 absence를 다른 manner로 handle할 수 있습니다.

Note 2

step 1.c는 logical-and operation 대신 logical-or operation을 사용한다는 점에서 IsLessThan algorithm의 step 3와 다릅니다.

13.15.4 EvaluateStringOrNumericBinaryExpression ( leftOperand, opText, rightOperand )

The abstract operation EvaluateStringOrNumericBinaryExpression takes arguments leftOperand (a Parse Node), opText (**, *, /, %, +, -, <<, >>, >>>, &, ^, or |), and rightOperand (a Parse Node) and returns either a normal completion containing either a String, a BigInt, or a Number, or an abrupt completion. It performs the following steps when called:

  1. leftRefleftOperandEvaluation으로 ? 둔다.
  2. leftValue를 ? GetValue(leftRef)로 둔다.
  3. rightRefrightOperandEvaluation으로 ? 둔다.
  4. rightValue를 ? GetValue(rightRef)로 둔다.
  5. ApplyStringOrNumericBinaryOperator(leftValue, opText, rightValue)를 반환한다.

13.15.5 Destructuring Assignment

Supplemental Syntax

특정 circumstance에서 production
AssignmentExpression : LeftHandSideExpression = AssignmentExpression
의 instance를 processing할 때, LeftHandSideExpression의 interpretation은 다음 grammar를 사용하여 refined됩니다:

AssignmentPattern[Yield, Await] : ObjectAssignmentPattern[?Yield, ?Await] ArrayAssignmentPattern[?Yield, ?Await] ObjectAssignmentPattern[Yield, Await] : { } { AssignmentRestProperty[?Yield, ?Await] } { AssignmentPropertyList[?Yield, ?Await] } { AssignmentPropertyList[?Yield, ?Await] , AssignmentRestProperty[?Yield, ?Await]opt } ArrayAssignmentPattern[Yield, Await] : [ Elisionopt AssignmentRestElement[?Yield, ?Await]opt ] [ AssignmentElementList[?Yield, ?Await] ] [ AssignmentElementList[?Yield, ?Await] , Elisionopt AssignmentRestElement[?Yield, ?Await]opt ] AssignmentRestProperty[Yield, Await] : ... DestructuringAssignmentTarget[?Yield, ?Await] AssignmentPropertyList[Yield, Await] : AssignmentProperty[?Yield, ?Await] AssignmentPropertyList[?Yield, ?Await] , AssignmentProperty[?Yield, ?Await] AssignmentElementList[Yield, Await] : AssignmentElisionElement[?Yield, ?Await] AssignmentElementList[?Yield, ?Await] , AssignmentElisionElement[?Yield, ?Await] AssignmentElisionElement[Yield, Await] : Elisionopt AssignmentElement[?Yield, ?Await] AssignmentProperty[Yield, Await] : IdentifierReference[?Yield, ?Await] Initializer[+In, ?Yield, ?Await]opt PropertyName[?Yield, ?Await] : AssignmentElement[?Yield, ?Await] AssignmentElement[Yield, Await] : DestructuringAssignmentTarget[?Yield, ?Await] Initializer[+In, ?Yield, ?Await]opt AssignmentRestElement[Yield, Await] : ... DestructuringAssignmentTarget[?Yield, ?Await] DestructuringAssignmentTarget[Yield, Await] : LeftHandSideExpression[?Yield, ?Await]

13.15.5.1 Static Semantics: Early Errors

AssignmentProperty : IdentifierReference Initializeropt AssignmentRestProperty : ... DestructuringAssignmentTarget DestructuringAssignmentTarget : LeftHandSideExpression

13.15.5.2 Runtime Semantics: DestructuringAssignmentEvaluation

The syntax-directed operation DestructuringAssignmentEvaluation takes argument value (an ECMAScript language value) and returns either a normal completion containing unused or an abrupt completion. It is defined piecewise over the following productions:

ObjectAssignmentPattern : { }
  1. RequireObjectCoercible(value)를 수행한다.
  2. unused를 반환한다.
ObjectAssignmentPattern : { AssignmentPropertyList } { AssignmentPropertyList , }
  1. RequireObjectCoercible(value)를 수행한다.
  2. argument value를 가진 AssignmentPropertyListPropertyDestructuringAssignmentEvaluation을 ? 수행한다.
  3. unused를 반환한다.
ObjectAssignmentPattern : { AssignmentRestProperty }
  1. RequireObjectCoercible(value)를 수행한다.
  2. excludedNames를 새 empty List로 둔다.
  3. arguments valueexcludedNames를 가진 AssignmentRestPropertyRestDestructuringAssignmentEvaluation을 ? 반환한다.
ObjectAssignmentPattern : { AssignmentPropertyList , AssignmentRestProperty }
  1. RequireObjectCoercible(value)를 수행한다.
  2. excludedNames를 argument value를 가진 AssignmentPropertyListPropertyDestructuringAssignmentEvaluation으로 ? 둔다.
  3. arguments valueexcludedNames를 가진 AssignmentRestPropertyRestDestructuringAssignmentEvaluation을 ? 반환한다.
ArrayAssignmentPattern : [ ]
  1. iteratorRecord를 ? GetIterator(value, sync)로 둔다.
  2. IteratorClose(iteratorRecord, NormalCompletion(unused))를 반환한다.
ArrayAssignmentPattern : [ Elision ]
  1. iteratorRecord를 ? GetIterator(value, sync)로 둔다.
  2. result를 argument iteratorRecord를 가진 ElisionIteratorDestructuringAssignmentEvaluationCompletion으로 둔다.
  3. iteratorRecord.[[Done]]false이면, ? IteratorClose(iteratorRecord, result)를 반환한다.
  4. result를 반환한다.
ArrayAssignmentPattern : [ Elisionopt AssignmentRestElement ]
  1. iteratorRecord를 ? GetIterator(value, sync)로 둔다.
  2. Elision이 present이면, 다음을 수행한다.
    1. status를 argument iteratorRecord를 가진 ElisionIteratorDestructuringAssignmentEvaluationCompletion으로 둔다.
    2. statusabrupt completion이면, 다음을 수행한다.
      1. Assert: iteratorRecord.[[Done]]true이다.
      2. status를 반환한다.
  3. result를 argument iteratorRecord를 가진 AssignmentRestElementIteratorDestructuringAssignmentEvaluationCompletion으로 둔다.
  4. iteratorRecord.[[Done]]false이면, ? IteratorClose(iteratorRecord, result)를 반환한다.
  5. result를 반환한다.
ArrayAssignmentPattern : [ AssignmentElementList ]
  1. iteratorRecord를 ? GetIterator(value, sync)로 둔다.
  2. result를 argument iteratorRecord를 가진 AssignmentElementListIteratorDestructuringAssignmentEvaluationCompletion으로 둔다.
  3. iteratorRecord.[[Done]]false이면, ? IteratorClose(iteratorRecord, result)를 반환한다.
  4. result를 반환한다.
ArrayAssignmentPattern : [ AssignmentElementList , Elisionopt AssignmentRestElementopt ]
  1. iteratorRecord를 ? GetIterator(value, sync)로 둔다.
  2. status를 argument iteratorRecord를 가진 AssignmentElementListIteratorDestructuringAssignmentEvaluationCompletion으로 둔다.
  3. statusabrupt completion이면, 다음을 수행한다.
    1. iteratorRecord.[[Done]]false이면, ? IteratorClose(iteratorRecord, status)를 반환한다.
    2. status를 반환한다.
  4. Elision이 present이면, 다음을 수행한다.
    1. status를 argument iteratorRecord를 가진 ElisionIteratorDestructuringAssignmentEvaluationCompletion으로 설정한다.
    2. statusabrupt completion이면, 다음을 수행한다.
      1. Assert: iteratorRecord.[[Done]]true이다.
      2. status를 반환한다.
  5. AssignmentRestElement가 present이면, 다음을 수행한다.
    1. status를 argument iteratorRecord를 가진 AssignmentRestElementIteratorDestructuringAssignmentEvaluationCompletion으로 설정한다.
  6. iteratorRecord.[[Done]]false이면, ? IteratorClose(iteratorRecord, status)를 반환한다.
  7. status를 반환한다.

13.15.5.3 Runtime Semantics: PropertyDestructuringAssignmentEvaluation

The syntax-directed operation PropertyDestructuringAssignmentEvaluation takes argument value (an ECMAScript language value) and returns either a normal completion containing a List of property keys or an abrupt completion. destructured property key 전체의 list를 collect합니다. It is defined piecewise over the following productions:

AssignmentPropertyList : AssignmentPropertyList , AssignmentProperty
  1. propertyNames를 argument value를 가진 AssignmentPropertyListPropertyDestructuringAssignmentEvaluation으로 ? 둔다.
  2. nextNames를 argument value를 가진 AssignmentPropertyPropertyDestructuringAssignmentEvaluation으로 ? 둔다.
  3. propertyNamesnextNameslist-concatenation을 반환한다.
AssignmentProperty : IdentifierReference Initializeropt
  1. propertyNameIdentifierReferenceStringValue로 둔다.
  2. leftRef를 ? ResolveBinding(propertyName)으로 둔다.
  3. value를 ? GetV(value, propertyName)로 설정한다.
  4. Initializer가 present이고 valueundefined이면, 다음을 수행한다.
    1. IsAnonymousFunctionDefinition(Initializer)이 true이면, 다음을 수행한다.
      1. value를 argument propertyName을 가진 InitializerNamedEvaluation으로 ? 설정한다.
    2. 그렇지 않으면,
      1. defaultValueInitializerEvaluation으로 ? 둔다.
      2. value를 ? GetValue(defaultValue)로 설정한다.
  5. PutValue(leftRef, value)를 수행한다.
  6. « propertyName »를 반환한다.
AssignmentProperty : PropertyName : AssignmentElement
  1. namePropertyNameEvaluation으로 ? 둔다.
  2. arguments valuename을 가진 AssignmentElementKeyedDestructuringAssignmentEvaluation을 ? 수행한다.
  3. « name »를 반환한다.

13.15.5.4 Runtime Semantics: RestDestructuringAssignmentEvaluation

The syntax-directed operation RestDestructuringAssignmentEvaluation takes arguments value (an ECMAScript language value) and excludedNames (a List of property keys) and returns either a normal completion containing unused or an abrupt completion. It is defined piecewise over the following productions:

AssignmentRestProperty : ... DestructuringAssignmentTarget
  1. leftRefDestructuringAssignmentTargetEvaluation으로 ? 둔다.
  2. restObjOrdinaryObjectCreate(%Object.prototype%)로 둔다.
  3. CopyDataProperties(restObj, value, excludedNames)를 수행한다.
  4. PutValue(leftRef, restObj)를 반환한다.

13.15.5.5 Runtime Semantics: IteratorDestructuringAssignmentEvaluation

The syntax-directed operation IteratorDestructuringAssignmentEvaluation takes argument iteratorRecord (an Iterator Record) and returns either a normal completion containing unused or an abrupt completion. It is defined piecewise over the following productions:

AssignmentElementList : AssignmentElisionElement
  1. argument iteratorRecord를 가진 AssignmentElisionElementIteratorDestructuringAssignmentEvaluation을 ? 반환한다.
AssignmentElementList : AssignmentElementList , AssignmentElisionElement
  1. argument iteratorRecord를 가진 AssignmentElementListIteratorDestructuringAssignmentEvaluation을 ? 수행한다.
  2. argument iteratorRecord를 가진 AssignmentElisionElementIteratorDestructuringAssignmentEvaluation을 ? 반환한다.
AssignmentElisionElement : AssignmentElement
  1. argument iteratorRecord를 가진 AssignmentElementIteratorDestructuringAssignmentEvaluation을 ? 반환한다.
AssignmentElisionElement : Elision AssignmentElement
  1. argument iteratorRecord를 가진 ElisionIteratorDestructuringAssignmentEvaluation을 ? 수행한다.
  2. argument iteratorRecord를 가진 AssignmentElementIteratorDestructuringAssignmentEvaluation을 ? 반환한다.
Elision : ,
  1. iteratorRecord.[[Done]]false이면, 다음을 수행한다.
    1. IteratorStep(iteratorRecord)를 수행한다.
  2. unused를 반환한다.
Elision : Elision ,
  1. argument iteratorRecord를 가진 ElisionIteratorDestructuringAssignmentEvaluation을 ? 수행한다.
  2. iteratorRecord.[[Done]]false이면, 다음을 수행한다.
    1. IteratorStep(iteratorRecord)를 수행한다.
  3. unused를 반환한다.
AssignmentElement : DestructuringAssignmentTarget Initializeropt
  1. DestructuringAssignmentTargetObjectLiteralArrayLiteral도 아니면, 다음을 수행한다.
    1. leftRefDestructuringAssignmentTargetEvaluation으로 ? 둔다.
  2. valueundefined로 둔다.
  3. iteratorRecord.[[Done]]false이면, 다음을 수행한다.
    1. next를 ? IteratorStepValue(iteratorRecord)로 둔다.
    2. nextdone이 아니면, 다음을 수행한다.
      1. valuenext로 설정한다.
  4. Initializer가 present이고 valueundefined이면, 다음을 수행한다.
    1. IsAnonymousFunctionDefinition(Initializer)이 true이고 DestructuringAssignmentTargetIsIdentifierReftrue이면, 다음을 수행한다.
      1. targetDestructuringAssignmentTargetStringValue로 둔다.
      2. v를 argument target을 가진 InitializerNamedEvaluation으로 ? 둔다.
    2. 그렇지 않으면,
      1. defaultValueInitializerEvaluation으로 ? 둔다.
      2. v를 ? GetValue(defaultValue)로 둔다.
  5. 그렇지 않으면,
    1. vvalue로 둔다.
  6. DestructuringAssignmentTargetObjectLiteral 또는 ArrayLiteral 중 하나이면, 다음을 수행한다.
    1. nestedAssignmentPatternDestructuringAssignmentTargetcovered하는 AssignmentPattern으로 둔다.
    2. argument v를 가진 nestedAssignmentPatternDestructuringAssignmentEvaluation을 ? 반환한다.
  7. PutValue(leftRef, v)를 반환한다.
Note

destructuring pattern이 아닌 DestructuringAssignmentTargetiterator에 accessing하거나 Initializer를 evaluating하기 전에 evaluating함으로써 left-to-right evaluation order가 maintained됩니다.

AssignmentRestElement : ... DestructuringAssignmentTarget
  1. DestructuringAssignmentTargetObjectLiteralArrayLiteral도 아니면, 다음을 수행한다.
    1. leftRefDestructuringAssignmentTargetEvaluation으로 ? 둔다.
  2. array를 ! ArrayCreate(0)으로 둔다.
  3. n을 0으로 둔다.
  4. iteratorRecord.[[Done]]false인 동안 Repeat,
    1. next를 ? IteratorStepValue(iteratorRecord)로 둔다.
    2. nextdone이 아니면, 다음을 수행한다.
      1. CreateDataPropertyOrThrow(array, ! ToString(𝔽(n)), next)를 수행한다.
      2. nn + 1로 설정한다.
  5. DestructuringAssignmentTargetObjectLiteralArrayLiteral도 아니면, 다음을 수행한다.
    1. PutValue(leftRef, array)를 반환한다.
  6. nestedAssignmentPatternDestructuringAssignmentTargetcovered하는 AssignmentPattern으로 둔다.
  7. argument array를 가진 nestedAssignmentPatternDestructuringAssignmentEvaluation을 ? 반환한다.

13.15.5.6 Runtime Semantics: KeyedDestructuringAssignmentEvaluation

The syntax-directed operation KeyedDestructuringAssignmentEvaluation takes arguments value (an ECMAScript language value) and propertyName (a property key) and returns either a normal completion containing unused or an abrupt completion. It is defined piecewise over the following productions:

AssignmentElement : DestructuringAssignmentTarget Initializeropt
  1. DestructuringAssignmentTargetObjectLiteralArrayLiteral도 아니면, 다음을 수행한다.
    1. leftRefDestructuringAssignmentTargetEvaluation으로 ? 둔다.
  2. value를 ? GetV(value, propertyName)로 설정한다.
  3. Initializer가 present이고 valueundefined이면, 다음을 수행한다.
    1. IsAnonymousFunctionDefinition(Initializer)이 true이고 DestructuringAssignmentTargetIsIdentifierReftrue이면, 다음을 수행한다.
      1. targetDestructuringAssignmentTargetStringValue로 둔다.
      2. rhsValue를 argument target을 가진 InitializerNamedEvaluation으로 ? 둔다.
    2. 그렇지 않으면,
      1. defaultValueInitializerEvaluation으로 ? 둔다.
      2. rhsValue를 ? GetValue(defaultValue)로 둔다.
  4. 그렇지 않으면,
    1. rhsValuevalue로 둔다.
  5. DestructuringAssignmentTargetObjectLiteral 또는 ArrayLiteral 중 하나이면, 다음을 수행한다.
    1. assignmentPatternDestructuringAssignmentTargetcovered하는 AssignmentPattern으로 둔다.
    2. argument rhsValue를 가진 assignmentPatternDestructuringAssignmentEvaluation을 ? 반환한다.
  6. PutValue(leftRef, rhsValue)를 반환한다.

13.16 Comma Operator ( , )

Syntax

Expression[In, Yield, Await] : AssignmentExpression[?In, ?Yield, ?Await] Expression[?In, ?Yield, ?Await] , AssignmentExpression[?In, ?Yield, ?Await]

13.16.1 Runtime Semantics: Evaluation

Expression : Expression , AssignmentExpression
  1. leftRefExpressionEvaluation으로 ? 둔다.
  2. GetValue(leftRef)를 수행한다.
  3. rightRefAssignmentExpressionEvaluation으로 ? 둔다.
  4. GetValue(rightRef)를 반환한다.
Note

value가 사용되지 않더라도 observable side-effect가 있을 수 있으므로 GetValue가 called되어야 합니다.

14 ECMAScript 언어: Statements and Declarations

Syntax

Statement[Yield, Await, Return] : BlockStatement[?Yield, ?Await, ?Return] VariableStatement[?Yield, ?Await] EmptyStatement ExpressionStatement[?Yield, ?Await] IfStatement[?Yield, ?Await, ?Return] BreakableStatement[?Yield, ?Await, ?Return] ContinueStatement[?Yield, ?Await] BreakStatement[?Yield, ?Await] [+Return] ReturnStatement[?Yield, ?Await] WithStatement[?Yield, ?Await, ?Return] LabelledStatement[?Yield, ?Await, ?Return] ThrowStatement[?Yield, ?Await] TryStatement[?Yield, ?Await, ?Return] DebuggerStatement Declaration[Yield, Await] : HoistableDeclaration[?Yield, ?Await, ~Default] ClassDeclaration[?Yield, ?Await, ~Default] LexicalDeclaration[+In, ?Yield, ?Await] HoistableDeclaration[Yield, Await, Default] : FunctionDeclaration[?Yield, ?Await, ?Default] GeneratorDeclaration[?Yield, ?Await, ?Default] AsyncFunctionDeclaration[?Yield, ?Await, ?Default] AsyncGeneratorDeclaration[?Yield, ?Await, ?Default] BreakableStatement[Yield, Await, Return] : IterationStatement[?Yield, ?Await, ?Return] SwitchStatement[?Yield, ?Await, ?Return]

14.1 Statement Semantics

14.1.1 Runtime Semantics: Evaluation

HoistableDeclaration : GeneratorDeclaration AsyncFunctionDeclaration AsyncGeneratorDeclaration
  1. empty를 반환한다.
HoistableDeclaration : FunctionDeclaration
  1. FunctionDeclarationEvaluation을 ? 반환한다.
BreakableStatement : IterationStatement SwitchStatement
  1. newLabelSet을 새 empty List로 둔다.
  2. argument newLabelSet를 가진 this BreakableStatementLabelledEvaluation을 ? 반환한다.

14.2 Block

Syntax

BlockStatement[Yield, Await, Return] : Block[?Yield, ?Await, ?Return] Block[Yield, Await, Return] : { StatementList[?Yield, ?Await, ?Return]opt } StatementList[Yield, Await, Return] : StatementListItem[?Yield, ?Await, ?Return] StatementList[?Yield, ?Await, ?Return] StatementListItem[?Yield, ?Await, ?Return] StatementListItem[Yield, Await, Return] : Statement[?Yield, ?Await, ?Return] Declaration[?Yield, ?Await]

14.2.1 Static Semantics: Early Errors

Block : { StatementList }

14.2.2 Runtime Semantics: Evaluation

Block : { }
  1. empty를 반환한다.
Block : { StatementList }
  1. oldEnv를 실행 중인 실행 컨텍스트의 LexicalEnvironment로 둔다.
  2. blockEnvNewDeclarativeEnvironment(oldEnv)로 둔다.
  3. BlockDeclarationInstantiation(StatementList, blockEnv)를 수행한다.
  4. 실행 중인 실행 컨텍스트의 LexicalEnvironment를 blockEnv로 설정한다.
  5. blockValueStatementListEvaluationCompletion으로 둔다.
  6. blockValueCompletion(DisposeResources(blockEnv.[[DisposableResourceStack]], blockValue))로 설정한다.
  7. 실행 중인 실행 컨텍스트의 LexicalEnvironment를 oldEnv로 설정한다.
  8. blockValue를 반환한다.
Note 1

control이 Block을 어떻게 leave하든 LexicalEnvironment는 항상 former state로 restored됩니다.

StatementList : StatementList StatementListItem
  1. slStatementListEvaluation으로 ? 둔다.
  2. sStatementListItemEvaluationCompletion으로 둔다.
  3. UpdateEmpty(s, sl)를 반환한다.
Note 2

StatementList의 value는 StatementList 안의 마지막 value-producing item의 value입니다. 예를 들어, 다음 eval function call은 모두 value 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에 corresponding하는 Parse Node입니다. envRecord는 binding이 created될 Environment Record입니다.

Note

Block 또는 CaseBlock이 evaluated될 때 새 Declarative Environment Record가 created되고, block 안에 declared된 각 block scoped variable, constant, function 또는 class에 대한 binding이 Environment Record 안에서 instantiated됩니다.

called될 때 다음 step을 수행합니다:

  1. declscodeLexicallyScopedDeclarations라고 하자.
  2. privateEnv를 실행 중인 실행 컨텍스트의 PrivateEnvironment라고 하자.
  3. decls의 각 요소 decl에 대해 다음을 수행한다.
    1. declBoundNames의 각 요소 name에 대해 다음을 수행한다.
      1. declIsConstantDeclarationtrue이면,
        1. envRecord.CreateImmutableBinding(name, true)를 수행한다.
      2. 그렇지 않으면,
        1. host가 웹 브라우저이거나 그 밖에 Block-Level Function Declarations Web Legacy Compatibility Semantics를 지원하면,
          1. envRecord.HasBinding(name)이 false이면,
            1. envRecord.CreateMutableBinding(name, false)를 수행한다.
        2. 그렇지 않으면,
          1. envRecord.CreateMutableBinding(name, false)를 수행한다.
    2. declFunctionDeclaration, GeneratorDeclaration, AsyncFunctionDeclaration 또는 AsyncGeneratorDeclaration 중 하나이면,
      1. funcNamedeclBoundNames의 유일한 요소라고 하자.
      2. funcObjdeclInstantiateFunctionObject에 인수 envRecordprivateEnv를 전달한 결과라고 하자.
      3. host가 웹 브라우저이거나 그 밖에 Block-Level Function Declarations Web Legacy Compatibility Semantics를 지원하면,
        1. envRecord에서 funcName에 대한 바인딩이 초기화되지 않은 바인딩이면,
          1. envRecord.InitializeBinding(funcName, funcObj)를 수행한다.
        2. 그렇지 않으면,
          1. Assert: declFunctionDeclaration이다.
          2. envRecord.SetMutableBinding(funcName, funcObj, false)를 수행한다.
      4. 그렇지 않으면,
        1. envRecord.InitializeBinding(funcName, funcObj)를 수행한다.
  4. unused를 반환한다.

14.3 Declarations and the Variable Statement

14.3.1 let, const, using 및 await using 선언

Note

let, const, usingawait using 선언은 실행 중인 실행 컨텍스트의 LexicalEnvironment로 스코프가 지정되는 변수를 정의한다. 변수는 이를 포함하는 Environment Record가 인스턴스화될 때 생성되지만, 변수의 LexicalBinding이 평가될 때까지는 어떤 방식으로도 접근할 수 없다. Initializer가 있는 LexicalBinding으로 정의된 변수는 변수가 생성될 때가 아니라 LexicalBinding이 평가될 때 해당 InitializerAssignmentExpression 값이 할당된다. let 선언의 LexicalBindingInitializer가 없으면, LexicalBinding이 평가될 때 변수에는 undefined 값이 할당된다.

구문

LexicalDeclaration[In, Yield, Await] : LetOrConst BindingList[?In, ?Yield, ?Await, +Pattern] ; UsingDeclaration[?In, ?Yield, ?Await] [+Await] AwaitUsingDeclaration[?In, ?Yield] LetOrConst : let const UsingDeclaration[In, Yield, Await] : using [no LineTerminator here] BindingList[?In, ?Yield, ?Await, ~Pattern] ; AwaitUsingDeclaration[In, Yield] : CoverAwaitExpressionAndAwaitUsingDeclarationHead[?Yield] [no LineTerminator here] BindingList[?In, ?Yield, +Await, ~Pattern] ; BindingList[In, Yield, Await, Pattern] : LexicalBinding[?In, ?Yield, ?Await, ?Pattern] BindingList[?In, ?Yield, ?Await, ?Pattern] , LexicalBinding[?In, ?Yield, ?Await, ?Pattern] LexicalBinding[In, Yield, Await, Pattern] : BindingIdentifier[?Yield, ?Await] Initializer[?In, ?Yield, ?Await]opt [+Pattern] BindingPattern[?Yield, ?Await] Initializer[?In, ?Yield, ?Await]

보충 구문

생성식의 인스턴스를 처리할 때
AwaitUsingDeclaration : CoverAwaitExpressionAndAwaitUsingDeclarationHead BindingList ;
CoverAwaitExpressionAndAwaitUsingDeclarationHead의 해석은 다음 문법을 사용하여 정제된다:

AwaitUsingDeclarationHead : await [no LineTerminator here] using

14.3.1.1 Static Semantics: 조기 오류

LexicalDeclaration : LetOrConst BindingList ; UsingDeclaration : using BindingList ; AwaitUsingDeclaration : CoverAwaitExpressionAndAwaitUsingDeclarationHead BindingList ; LexicalBinding : BindingIdentifier Initializeropt

14.3.1.2 Runtime Semantics: Evaluation

LexicalDeclaration : LetOrConst BindingList ;
  1. 인수 normalBindingListBindingEvaluation을 ? 수행한다.
  2. empty를 반환한다.
UsingDeclaration : using BindingList ;
  1. 인수 sync-disposeBindingListBindingEvaluation을 ? 수행한다.
  2. empty를 반환한다.
AwaitUsingDeclaration : CoverAwaitExpressionAndAwaitUsingDeclarationHead BindingList ;
  1. 인수 async-disposeBindingListBindingEvaluation을 ? 수행한다.
  2. empty를 반환한다.

14.3.1.3 Runtime Semantics: BindingEvaluation

The syntax-directed operation BindingEvaluation takes argument kind (normal, sync-dispose, or async-dispose) and returns either a normal completion containing unused or an abrupt completion. It is defined piecewise over the following productions:

BindingList : BindingList , LexicalBinding
  1. 인수 kind로 파생된 BindingListBindingEvaluation을 ? 수행한다.
  2. 인수 kindLexicalBindingBindingEvaluation을 ? 반환한다.
LexicalBinding : BindingIdentifier
  1. 단언: kindnormal이다.
  2. lhs를 ! ResolveBinding(BindingIdentifierStringValue)으로 둔다.
  3. InitializeReferencedBinding(lhs, undefined)를 수행한다.
  4. unused를 반환한다.
Note

정적 의미론 규칙은 이러한 형태의 LexicalBindingconst, using 또는 await using 선언에서 절대 발생하지 않도록 보장한다.

LexicalBinding : BindingIdentifier Initializer
  1. bindingIdBindingIdentifierStringValue로 둔다.
  2. lhs를 ! ResolveBinding(bindingId)로 둔다.
  3. IsAnonymousFunctionDefinition(Initializer)이 true이면,
    1. value를 인수 bindingIdInitializerNamedEvaluation을 ? 수행한 결과로 둔다.
  4. 그렇지 않으면,
    1. rhsInitializerEvaluation을 ? 수행한 결과로 둔다.
    2. value를 ? GetValue(rhs)로 둔다.
  5. kindnormal이 아니면,
    1. 단언: IsUnresolvableReference(lhs)는 false이다.
    2. baselhs.[[Base]]로 둔다.
    3. 단언: baseDeclarative Environment Record이다.
    4. AddDisposableResource(base.[[DisposableResourceStack]], value, kind)를 ? 수행한다.
  6. InitializeReferencedBinding(lhs, value)를 ? 수행한다.
  7. unused를 반환한다.
LexicalBinding : BindingPattern Initializer
  1. 단언: kindnormal이다.
  2. rhsInitializerEvaluation을 ? 수행한 결과로 둔다.
  3. value를 ? GetValue(rhs)로 둔다.
  4. envRecord를 실행 중인 실행 컨텍스트의 LexicalEnvironment로 둔다.
  5. 인수 valueenvRecordBindingPatternBindingInitialization을 ? 반환한다.

14.3.2 Variable Statement

Note

var statement는 running execution context의 VariableEnvironment로 scoped되는 variable을 declare합니다. Var variable은 containing Environment Record가 instantiated될 때 created되고, created될 때 undefined로 initialized됩니다. 어떤 VariableEnvironment의 scope 안에서도 common BindingIdentifier는 둘 이상의 VariableDeclaration에 appear할 수 있지만, 그러한 declaration은 collectively 하나의 variable만 define합니다. Initializer를 가진 VariableDeclaration에 의해 defined된 variable은 variable이 created될 때가 아니라 VariableDeclaration이 executed될 때 그 InitializerAssignmentExpression value가 assigned됩니다.

Syntax

VariableStatement[Yield, Await] : var VariableDeclarationList[+In, ?Yield, ?Await] ; VariableDeclarationList[In, Yield, Await] : VariableDeclaration[?In, ?Yield, ?Await] VariableDeclarationList[?In, ?Yield, ?Await] , VariableDeclaration[?In, ?Yield, ?Await] VariableDeclaration[In, Yield, Await] : BindingIdentifier[?Yield, ?Await] Initializer[?In, ?Yield, ?Await]opt BindingPattern[?Yield, ?Await] Initializer[?In, ?Yield, ?Await]

14.3.2.1 Runtime Semantics: Evaluation

VariableStatement : var VariableDeclarationList ;
  1. VariableDeclarationListEvaluation을 ? 수행한다.
  2. empty를 반환한다.
VariableDeclarationList : VariableDeclarationList , VariableDeclaration
  1. VariableDeclarationListEvaluation을 ? 수행한다.
  2. VariableDeclarationEvaluation을 ? 반환한다.
VariableDeclaration : BindingIdentifier
  1. empty를 반환한다.
VariableDeclaration : BindingIdentifier Initializer
  1. bindingIdBindingIdentifierStringValue로 둔다.
  2. lhs를 ? ResolveBinding(bindingId)로 둔다.
  3. IsAnonymousFunctionDefinition(Initializer)이 true이면, 다음을 수행한다.
    1. value를 argument bindingId를 가진 InitializerNamedEvaluation으로 ? 둔다.
  4. 그렇지 않으면,
    1. rhsInitializerEvaluation으로 ? 둔다.
    2. value를 ? GetValue(rhs)로 둔다.
  5. PutValue(lhs, value)를 수행한다.
  6. empty를 반환한다.
Note

VariableDeclaration이 with statement 안에 nested되어 있고 VariableDeclaration 안의 BindingIdentifier가 with statement의 Object Environment Record의 binding object의 property name과 same하면, step 5valueIdentifier의 VariableEnvironment binding에 assigning하는 대신 property에 assign합니다.

VariableDeclaration : BindingPattern Initializer
  1. rhsInitializerEvaluation으로 ? 둔다.
  2. rightValue를 ? GetValue(rhs)로 둔다.
  3. arguments rightValueundefined를 가진 BindingPatternBindingInitialization을 ? 반환한다.

14.3.3 Destructuring Binding Patterns

Syntax

BindingPattern[Yield, Await] : ObjectBindingPattern[?Yield, ?Await] ArrayBindingPattern[?Yield, ?Await] ObjectBindingPattern[Yield, Await] : { } { BindingRestProperty[?Yield, ?Await] } { BindingPropertyList[?Yield, ?Await] } { BindingPropertyList[?Yield, ?Await] , BindingRestProperty[?Yield, ?Await]opt } ArrayBindingPattern[Yield, Await] : [ Elisionopt BindingRestElement[?Yield, ?Await]opt ] [ BindingElementList[?Yield, ?Await] ] [ BindingElementList[?Yield, ?Await] , Elisionopt BindingRestElement[?Yield, ?Await]opt ] BindingRestProperty[Yield, Await] : ... BindingIdentifier[?Yield, ?Await] BindingPropertyList[Yield, Await] : BindingProperty[?Yield, ?Await] BindingPropertyList[?Yield, ?Await] , BindingProperty[?Yield, ?Await] BindingElementList[Yield, Await] : BindingElisionElement[?Yield, ?Await] BindingElementList[?Yield, ?Await] , BindingElisionElement[?Yield, ?Await] BindingElisionElement[Yield, Await] : Elisionopt BindingElement[?Yield, ?Await] BindingProperty[Yield, Await] : SingleNameBinding[?Yield, ?Await] PropertyName[?Yield, ?Await] : BindingElement[?Yield, ?Await] BindingElement[Yield, Await] : SingleNameBinding[?Yield, ?Await] BindingPattern[?Yield, ?Await] Initializer[+In, ?Yield, ?Await]opt SingleNameBinding[Yield, Await] : BindingIdentifier[?Yield, ?Await] Initializer[+In, ?Yield, ?Await]opt BindingRestElement[Yield, Await] : ... BindingIdentifier[?Yield, ?Await] ... BindingPattern[?Yield, ?Await]

14.3.3.1 Runtime Semantics: PropertyBindingInitialization

The syntax-directed operation PropertyBindingInitialization takes arguments value (an ECMAScript language value) and envRecord (an Environment Record or undefined) and returns either a normal completion containing a List of property keys or an abrupt completion. bound property name 전체의 list를 collect합니다. It is defined piecewise over the following productions:

BindingPropertyList : BindingPropertyList , BindingProperty
  1. boundNames를 arguments valueenvRecord를 가진 BindingPropertyListPropertyBindingInitialization으로 ? 둔다.
  2. nextNames를 arguments valueenvRecord를 가진 BindingPropertyPropertyBindingInitialization으로 ? 둔다.
  3. boundNamesnextNameslist-concatenation을 반환한다.
BindingProperty : SingleNameBinding
  1. nameSingleNameBindingBoundNames의 sole element로 둔다.
  2. arguments value, envRecord, name을 가진 SingleNameBindingKeyedBindingInitialization을 ? 수행한다.
  3. « name »를 반환한다.
BindingProperty : PropertyName : BindingElement
  1. propertyKeyPropertyNameEvaluation으로 ? 둔다.
  2. arguments value, envRecord, propertyKey를 가진 BindingElementKeyedBindingInitialization을 ? 수행한다.
  3. « propertyKey »를 반환한다.

14.3.3.2 Runtime Semantics: RestBindingInitialization

The syntax-directed operation RestBindingInitialization takes arguments value (an ECMAScript language value), envRecord (an Environment Record or undefined), and excludedNames (a List of property keys) and returns either a normal completion containing unused or an abrupt completion. It is defined piecewise over the following productions:

BindingRestProperty : ... BindingIdentifier
  1. lhs를 ? ResolveBinding(BindingIdentifierStringValue, envRecord)로 둔다.
  2. restObjOrdinaryObjectCreate(%Object.prototype%)로 둔다.
  3. CopyDataProperties(restObj, value, excludedNames)를 수행한다.
  4. envRecordundefined이면, ? PutValue(lhs, restObj)를 반환한다.
  5. InitializeReferencedBinding(lhs, restObj)를 반환한다.

14.3.3.3 Runtime Semantics: KeyedBindingInitialization

The syntax-directed operation KeyedBindingInitialization takes arguments value (an ECMAScript language value), envRecord (an Environment Record or undefined), and propertyName (a property key) and returns either a normal completion containing unused or an abrupt completion.

Note

undefinedenvRecord로 passed되면 initialization value를 assign하기 위해 PutValue operation이 사용되어야 함을 indicate합니다. 이는 non-strict function의 formal parameter list의 경우입니다. 그 경우 formal parameter binding은 같은 name을 가진 multiple parameter의 possibility를 deal하기 위해 preinitialized됩니다.

It is defined piecewise over the following productions:

BindingElement : BindingPattern Initializeropt
  1. value를 ? GetV(value, propertyName)로 설정한다.
  2. Initializer가 present이고 valueundefined이면, 다음을 수행한다.
    1. defaultValueInitializerEvaluation으로 ? 둔다.
    2. value를 ? GetValue(defaultValue)로 설정한다.
  3. arguments valueenvRecord를 가진 BindingPatternBindingInitialization을 ? 반환한다.
SingleNameBinding : BindingIdentifier Initializeropt
  1. bindingIdBindingIdentifierStringValue로 둔다.
  2. lhs를 ? ResolveBinding(bindingId, envRecord)로 둔다.
  3. value를 ? GetV(value, propertyName)로 설정한다.
  4. Initializer가 present이고 valueundefined이면, 다음을 수행한다.
    1. IsAnonymousFunctionDefinition(Initializer)이 true이면, 다음을 수행한다.
      1. value를 argument bindingId를 가진 InitializerNamedEvaluation으로 ? 설정한다.
    2. 그렇지 않으면,
      1. defaultValueInitializerEvaluation으로 ? 둔다.
      2. value를 ? GetValue(defaultValue)로 설정한다.
  5. envRecordundefined이면, ? PutValue(lhs, value)를 반환한다.
  6. InitializeReferencedBinding(lhs, value)를 반환한다.

14.4 Empty Statement

Syntax

EmptyStatement : ;

14.4.1 Runtime Semantics: Evaluation

EmptyStatement : ;
  1. empty를 반환한다.

14.5 Expression Statement

Syntax

ExpressionStatement[Yield, Await] : [lookahead ∉ { {, function, async [no LineTerminator here] function, class, let [ }] Expression[+In, ?Yield, ?Await] ; Note

ExpressionStatement는 U+007B (LEFT CURLY BRACKET)로 start할 수 없습니다. 그렇게 하면 Block과 ambiguous할 수 있기 때문입니다. ExpressionStatementfunction 또는 class keyword로 start할 수 없습니다. 그렇게 하면 FunctionDeclaration, GeneratorDeclaration 또는 ClassDeclaration과 ambiguous할 수 있기 때문입니다. ExpressionStatementasync function으로 start할 수 없습니다. 그렇게 하면 AsyncFunctionDeclaration 또는 AsyncGeneratorDeclaration과 ambiguous할 수 있기 때문입니다. ExpressionStatement는 two token sequence let [로 start할 수 없습니다. 그렇게 하면 first LexicalBindingArrayBindingPatternlet LexicalDeclaration과 ambiguous할 수 있기 때문입니다.

14.5.1 Runtime Semantics: Evaluation

ExpressionStatement : Expression ;
  1. exprRefExpressionEvaluation으로 ? 둔다.
  2. GetValue(exprRef)를 반환한다.

14.6 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]는 classic “dangling else” problem을 usual way로 resolve합니다. 즉, associated if의 choice가 otherwise ambiguous할 때, else는 candidate if 중 nearest (innermost)에 associated됩니다

14.6.1 Static Semantics: Early Errors

IfStatement : if ( Expression ) Statement else Statement IfStatement : if ( Expression ) Statement Note

이 rule은 B.3.1에 specified된 extension이 implemented된 경우에만 apply할 필요가 있습니다.

14.6.2 Runtime Semantics: Evaluation

IfStatement : if ( Expression ) Statement else Statement
  1. exprRefExpressionEvaluation으로 ? 둔다.
  2. exprValueToBoolean(? GetValue(exprRef))로 둔다.
  3. exprValuetrue이면, 다음을 수행한다.
    1. stmtCompletion을 first StatementEvaluationCompletion으로 둔다.
  4. 그렇지 않으면,
    1. stmtCompletion을 second StatementEvaluationCompletion으로 둔다.
  5. UpdateEmpty(stmtCompletion, undefined)를 반환한다.
IfStatement : if ( Expression ) Statement
  1. exprRefExpressionEvaluation으로 ? 둔다.
  2. exprValueToBoolean(? GetValue(exprRef))로 둔다.
  3. exprValuefalse이면, undefined를 반환한다.
  4. stmtCompletionStatementEvaluationCompletion으로 둔다.
  5. UpdateEmpty(stmtCompletion, undefined)를 반환한다.

14.7 Iteration Statements

Syntax

IterationStatement[Yield, Await, Return] : DoWhileStatement[?Yield, ?Await, ?Return] WhileStatement[?Yield, ?Await, ?Return] ForStatement[?Yield, ?Await, ?Return] ForInOfStatement[?Yield, ?Await, ?Return]

14.7.1 Semantics

14.7.1.1 LoopContinues ( completion, labelSet )

The abstract operation LoopContinues takes arguments completion (a Completion Record) and labelSet (a List of Strings) and returns a Boolean. It performs the following steps when called:

  1. completionnormal completion이면, true를 반환한다.
  2. completioncontinue completion이 아니면, false를 반환한다.
  3. completion.[[Target]]empty이면, true를 반환한다.
  4. labelSetcompletion.[[Target]]을 contain하면, true를 반환한다.
  5. false를 반환한다.
Note

IterationStatementStatement part 안에서는 ContinueStatement가 new iteration을 begin하는 데 사용될 수 있습니다.

14.7.1.2 Runtime Semantics: LoopEvaluation

The syntax-directed operation LoopEvaluation takes argument labelSet (a List of Strings) and returns either a normal completion containing an ECMAScript language value or an abrupt completion. It is defined piecewise over the following productions:

IterationStatement : DoWhileStatement
  1. argument labelSet를 가진 DoWhileStatementDoWhileLoopEvaluation을 ? 반환한다.
IterationStatement : WhileStatement
  1. argument labelSet를 가진 WhileStatementWhileLoopEvaluation을 ? 반환한다.
IterationStatement : ForStatement
  1. argument labelSet를 가진 ForStatementForLoopEvaluation을 ? 반환한다.
IterationStatement : ForInOfStatement
  1. argument labelSet를 가진 ForInOfStatementForInOfLoopEvaluation을 ? 반환한다.

14.7.2 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에 specified된 extension이 implemented된 경우에만 apply할 필요가 있습니다.

14.7.2.2 Runtime Semantics: DoWhileLoopEvaluation

The syntax-directed operation DoWhileLoopEvaluation takes argument labelSet (a List of Strings) and returns either a normal completion containing an ECMAScript language value or an abrupt completion. It is defined piecewise over the following productions:

DoWhileStatement : do Statement while ( Expression ) ;
  1. iterationResultundefined로 둔다.
  2. Repeat,
    1. stmtResultStatementEvaluationCompletion으로 둔다.
    2. LoopContinues(stmtResult, labelSet)가 false이면, ? UpdateEmpty(stmtResult, iterationResult)를 반환한다.
    3. stmtResult.[[Value]]empty가 아니면, iterationResultstmtResult.[[Value]]로 설정한다.
    4. exprRefExpressionEvaluation으로 ? 둔다.
    5. exprValue를 ? GetValue(exprRef)로 둔다.
    6. ToBoolean(exprValue)가 false이면, iterationResult를 반환한다.

14.7.3 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에 specified된 extension이 implemented된 경우에만 apply할 필요가 있습니다.

14.7.3.2 Runtime Semantics: WhileLoopEvaluation

The syntax-directed operation WhileLoopEvaluation takes argument labelSet (a List of Strings) and returns either a normal completion containing an ECMAScript language value or an abrupt completion. It is defined piecewise over the following productions:

WhileStatement : while ( Expression ) Statement
  1. iterationResultundefined로 둔다.
  2. Repeat,
    1. exprRefExpressionEvaluation으로 ? 둔다.
    2. exprValue를 ? GetValue(exprRef)로 둔다.
    3. ToBoolean(exprValue)가 false이면, iterationResult를 반환한다.
    4. stmtResultStatementEvaluationCompletion으로 둔다.
    5. LoopContinues(stmtResult, labelSet)가 false이면, ? UpdateEmpty(stmtResult, iterationResult)를 반환한다.
    6. stmtResult.[[Value]]empty가 아니면, iterationResultstmtResult.[[Value]]로 설정한다.

14.7.4 for Statement

Syntax

ForStatement[Yield, Await, Return] : for ( [lookahead ≠ let [] Expression[~In, ?Yield, ?Await]opt ; Expression[+In, ?Yield, ?Await]opt ; Expression[+In, ?Yield, ?Await]opt ) Statement[?Yield, ?Await, ?Return] for ( var VariableDeclarationList[~In, ?Yield, ?Await] ; Expression[+In, ?Yield, ?Await]opt ; Expression[+In, ?Yield, ?Await]opt ) Statement[?Yield, ?Await, ?Return] for ( LexicalDeclaration[~In, ?Yield, ?Await] Expression[+In, ?Yield, ?Await]opt ; Expression[+In, ?Yield, ?Await]opt ) Statement[?Yield, ?Await, ?Return]

14.7.4.1 Static Semantics: Early Errors

ForStatement : for ( Expressionopt ; Expressionopt ; Expressionopt ) Statement for ( var VariableDeclarationList ; Expressionopt ; Expressionopt ) Statement for ( LexicalDeclaration Expressionopt ; Expressionopt ) Statement Note

이 rule은 B.3.1에 specified된 extension이 implemented된 경우에만 apply할 필요가 있습니다.

ForStatement : for ( LexicalDeclaration Expressionopt ; Expressionopt ) Statement

14.7.4.2 Runtime Semantics: ForLoopEvaluation

The syntax-directed operation ForLoopEvaluation takes argument labelSet (a List of Strings) and returns either a normal completion containing an ECMAScript language value or an abrupt completion. It is defined piecewise over the following productions:

ForStatement : for ( Expressionopt ; Expressionopt ; Expressionopt ) Statement
  1. first Expression이 present이면, 다음을 수행한다.
    1. exprRef를 first ExpressionEvaluation으로 ? 둔다.
    2. GetValue(exprRef)를 수행한다.
  2. second Expression이 present이면 test를 second Expression으로 둔다; 그렇지 않으면 testempty로 둔다.
  3. third Expression이 present이면 increment를 third Expression으로 둔다; 그렇지 않으면 incrementempty로 둔다.
  4. ForBodyEvaluation(test, increment, Statement, « », labelSet)를 반환한다.
ForStatement : for ( var VariableDeclarationList ; Expressionopt ; Expressionopt ) Statement
  1. VariableDeclarationListEvaluation을 ? 수행한다.
  2. first Expression이 present이면 test를 first Expression으로 둔다; 그렇지 않으면 testempty로 둔다.
  3. second Expression이 present이면 increment를 second Expression으로 둔다; 그렇지 않으면 incrementempty로 둔다.
  4. ForBodyEvaluation(test, increment, Statement, « », labelSet)를 반환한다.
ForStatement : for ( LexicalDeclaration Expressionopt ; Expressionopt ) Statement
  1. oldEnv를 실행 중인 실행 컨텍스트의 LexicalEnvironment로 둔다.
  2. loopEnvNewDeclarativeEnvironment(oldEnv)로 둔다.
  3. isConstLexicalDeclarationIsConstantDeclaration로 둔다.
  4. boundNamesLexicalDeclarationBoundNames로 둔다.
  5. boundNames의 각 요소 name에 대해, 다음을 수행한다.
    1. isConsttrue이면,
      1. loopEnv.CreateImmutableBinding(name, true)를 수행한다.
    2. 그렇지 않으면,
      1. loopEnv.CreateMutableBinding(name, false)를 수행한다.
  6. 실행 중인 실행 컨텍스트의 LexicalEnvironment를 loopEnv로 설정한다.
  7. forDeclLexicalDeclarationEvaluationCompletion으로 둔다.
  8. forDecl이 abrupt 완료이면,
    1. forDeclCompletion(DisposeResources(loopEnv.[[DisposableResourceStack]], forDecl))로 설정한다.
    2. 단언: forDecl은 abrupt 완료이다.
    3. 실행 중인 실행 컨텍스트의 LexicalEnvironment를 oldEnv로 설정한다.
    4. forDecl을 반환한다.
  9. isConstfalse이면, perIterationLetsboundNames로 둔다. 그렇지 않으면 perIterationLets를 새 빈 List로 둔다.
  10. 첫 번째 Expression이 존재하면, test를 첫 번째 Expression으로 둔다. 그렇지 않으면 testempty로 둔다.
  11. 두 번째 Expression이 존재하면, increment를 두 번째 Expression으로 둔다. 그렇지 않으면 incrementempty로 둔다.
  12. bodyResultCompletion(ForBodyEvaluation(test, increment, Statement, perIterationLets, labelSet))으로 둔다.
  13. bodyResultCompletion(DisposeResources(loopEnv.[[DisposableResourceStack]], bodyResult))로 설정한다.
  14. 단언: bodyResult가 정상 완료이면, bodyResult.[[Value]]empty가 아니다.
  15. 실행 중인 실행 컨텍스트의 LexicalEnvironment를 oldEnv로 설정한다.
  16. bodyResult를 반환한다.

14.7.4.3 ForBodyEvaluation ( test, increment, stmt, perIterationBindings, labelSet )

The abstract operation ForBodyEvaluation takes arguments test (an Expression Parse Node or empty), increment (an Expression Parse Node or empty), stmt (a Statement Parse Node), perIterationBindings (a List of Strings), and labelSet (a List of Strings) and returns either a normal completion containing an ECMAScript language value or an abrupt completion. It performs the following steps when called:

  1. iterationResultundefined로 둔다.
  2. CreatePerIterationEnvironment(perIterationBindings)를 수행한다.
  3. Repeat,
    1. testempty가 아니면, 다음을 수행한다.
      1. testReftestEvaluation으로 ? 둔다.
      2. testValue를 ? GetValue(testRef)로 둔다.
      3. ToBoolean(testValue)가 false이면, iterationResult를 반환한다.
    2. resultstmtEvaluationCompletion으로 둔다.
    3. LoopContinues(result, labelSet)가 false이면, ? UpdateEmpty(result, iterationResult)를 반환한다.
    4. result.[[Value]]empty가 아니면, iterationResultresult.[[Value]]로 설정한다.
    5. CreatePerIterationEnvironment(perIterationBindings)를 수행한다.
    6. incrementempty가 아니면, 다음을 수행한다.
      1. incRefincrementEvaluation으로 ? 둔다.
      2. GetValue(incRef)를 수행한다.

14.7.4.4 CreatePerIterationEnvironment ( perIterationBindings )

The abstract operation CreatePerIterationEnvironment takes argument perIterationBindings (a List of Strings) and returns either a normal completion containing unused or a throw completion. It performs the following steps when called:

  1. perIterationBindings에 요소가 있으면,
    1. lastIterationEnv를 실행 중인 실행 컨텍스트의 LexicalEnvironment라고 하자.
    2. outerlastIterationEnv.[[OuterEnv]]라고 하자.
    3. Assert: outernull이 아니다.
    4. thisIterationEnvNewDeclarativeEnvironment(outer)라고 하자.
    5. perIterationBindings의 각 요소 name에 대해 다음을 수행한다.
      1. thisIterationEnv.CreateMutableBinding(name, false)를 수행한다.
      2. lastValue를 ? lastIterationEnv.GetBindingValue(name, true)라고 하자.
      3. thisIterationEnv.InitializeBinding(name, lastValue)를 수행한다.
    6. 실행 중인 실행 컨텍스트의 LexicalEnvironment를 thisIterationEnv로 설정한다.
  2. unused를 반환한다.

14.7.5 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에 의해 extended됩니다.

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에 specified된 extension이 implemented된 경우에만 apply할 필요가 있습니다.

ForInOfStatement : for ( LeftHandSideExpression in Expression ) Statement for ( LeftHandSideExpression of AssignmentExpression ) Statement for await ( LeftHandSideExpression of AssignmentExpression ) Statement ForInOfStatement : for ( ForDeclaration in Expression ) Statement for ( ForDeclaration of AssignmentExpression ) Statement for await ( ForDeclaration of AssignmentExpression ) Statement

14.7.5.2 Static Semantics: IsDestructuring

The syntax-directed operation IsDestructuring takes no arguments and returns a Boolean. It is defined piecewise over the following productions:

MemberExpression : PrimaryExpression
  1. PrimaryExpressionObjectLiteral 또는 ArrayLiteral 중 하나이면, true를 반환한다.
  2. false를 반환한다.
MemberExpression : MemberExpression [ Expression ] MemberExpression . IdentifierName MemberExpression TemplateLiteral SuperProperty MetaProperty new MemberExpression Arguments MemberExpression . PrivateIdentifier NewExpression : new NewExpression LeftHandSideExpression : CallExpression OptionalExpression
  1. false를 반환한다.
ForDeclaration : LetOrConst ForBinding
  1. ForBindingIsDestructuring을 반환한다.
ForBinding : BindingIdentifier
  1. false를 반환한다.
ForBinding : BindingPattern
  1. true를 반환한다.
Note

이 section은 Annex B.3.5에 의해 extended됩니다.

14.7.5.3 Runtime Semantics: ForDeclarationBindingInitialization

The syntax-directed operation ForDeclarationBindingInitialization takes arguments value (an ECMAScript language value) and envRecord (an Environment Record) and returns either a normal completion containing unused or an abrupt completion. It is defined piecewise over the following productions:

ForDeclaration : LetOrConst ForBinding
  1. arguments valueenvRecord를 가진 ForBindingBindingInitialization을 ? 반환한다.
ForDeclaration : using ForBinding await using ForBinding
  1. SyntaxError 예외를 던진다.

14.7.5.4 Runtime Semantics: ForDeclarationBindingInstantiation

The syntax-directed operation ForDeclarationBindingInstantiation takes argument envRecord (a Declarative Environment Record) and returns unused. It is defined piecewise over the following productions:

ForDeclaration : LetOrConst ForBinding
  1. ForBindingBoundNames의 각 element name에 대해, 다음을 수행한다.
    1. LetOrConstIsConstantDeclarationtrue이면, 다음을 수행한다.
      1. envRecord.CreateImmutableBinding(name, true)를 수행한다.
    2. 그렇지 않으면,
      1. envRecord.CreateMutableBinding(name, false)를 수행한다.
  2. unused를 반환한다.
ForDeclaration : using ForBinding await using ForBinding
  1. ForBindingBoundNames의 각 요소 name에 대해, 다음을 수행한다.
    1. envRecord.CreateImmutableBinding(name, true)를 수행한다.
  2. unused를 반환한다.

14.7.5.5 Runtime Semantics: ForInOfLoopEvaluation

The syntax-directed operation ForInOfLoopEvaluation takes argument labelSet (a List of Strings) and returns either a normal completion containing an ECMAScript language value or an abrupt completion. It is defined piecewise over the following productions:

ForInOfStatement : for ( LeftHandSideExpression in Expression ) Statement
  1. keyResult를 ? ForIn/OfHeadEvaluation(« », Expression, enumerate)로 둔다.
  2. ForIn/OfBodyEvaluation(LeftHandSideExpression, Statement, keyResult, enumerate, assignment, labelSet)를 반환한다.
ForInOfStatement : for ( var ForBinding in Expression ) Statement
  1. keyResult를 ? ForIn/OfHeadEvaluation(« », Expression, enumerate)로 둔다.
  2. ForIn/OfBodyEvaluation(ForBinding, Statement, keyResult, enumerate, var-binding, labelSet)를 반환한다.
ForInOfStatement : for ( ForDeclaration in Expression ) Statement
  1. keyResult를 ? ForIn/OfHeadEvaluation(ForDeclarationBoundNames, Expression, enumerate)로 둔다.
  2. ForIn/OfBodyEvaluation(ForDeclaration, Statement, keyResult, enumerate, lexical-binding, labelSet)를 반환한다.
ForInOfStatement : for ( LeftHandSideExpression of AssignmentExpression ) Statement
  1. keyResult를 ? ForIn/OfHeadEvaluation(« », AssignmentExpression, iterate)로 둔다.
  2. ForIn/OfBodyEvaluation(LeftHandSideExpression, Statement, keyResult, iterate, assignment, labelSet)를 반환한다.
ForInOfStatement : for ( var ForBinding of AssignmentExpression ) Statement
  1. keyResult를 ? ForIn/OfHeadEvaluation(« », AssignmentExpression, iterate)로 둔다.
  2. ForIn/OfBodyEvaluation(ForBinding, Statement, keyResult, iterate, var-binding, labelSet)를 반환한다.
ForInOfStatement : for ( ForDeclaration of AssignmentExpression ) Statement
  1. keyResult를 ? ForIn/OfHeadEvaluation(ForDeclarationBoundNames, AssignmentExpression, iterate)로 둔다.
  2. ForIn/OfBodyEvaluation(ForDeclaration, Statement, keyResult, iterate, lexical-binding, labelSet)를 반환한다.
ForInOfStatement : for await ( LeftHandSideExpression of AssignmentExpression ) Statement
  1. keyResult를 ? ForIn/OfHeadEvaluation(« », AssignmentExpression, async-iterate)로 둔다.
  2. ForIn/OfBodyEvaluation(LeftHandSideExpression, Statement, keyResult, iterate, assignment, labelSet, async)를 반환한다.
ForInOfStatement : for await ( var ForBinding of AssignmentExpression ) Statement
  1. keyResult를 ? ForIn/OfHeadEvaluation(« », AssignmentExpression, async-iterate)로 둔다.
  2. ForIn/OfBodyEvaluation(ForBinding, Statement, keyResult, iterate, var-binding, labelSet, async)를 반환한다.
ForInOfStatement : for await ( ForDeclaration of AssignmentExpression ) Statement
  1. keyResult를 ? ForIn/OfHeadEvaluation(ForDeclarationBoundNames, AssignmentExpression, async-iterate)로 둔다.
  2. ForIn/OfBodyEvaluation(ForDeclaration, Statement, keyResult, iterate, lexical-binding, labelSet, async)를 반환한다.
Note

이 section은 Annex B.3.5에 의해 extended됩니다.

14.7.5.6 ForIn/OfHeadEvaluation ( uninitializedBoundNames, expr, iterationKind )

The abstract operation ForIn/OfHeadEvaluation takes arguments uninitializedBoundNames (a List of Strings), expr (an Expression Parse Node or an AssignmentExpression Parse Node), and iterationKind (enumerate, iterate, or async-iterate) and returns either a normal completion containing an Iterator Record or an abrupt completion. It performs the following steps when called:

  1. oldEnvrunning execution context의 LexicalEnvironment로 둔다.
  2. uninitializedBoundNames가 empty가 아니면, 다음을 수행한다.
    1. Assert: uninitializedBoundNames는 duplicate entry를 가지지 않는다.
    2. newEnvNewDeclarativeEnvironment(oldEnv)로 둔다.
    3. uninitializedBoundNames의 각 String name에 대해, 다음을 수행한다.
      1. newEnv.CreateMutableBinding(name, false)를 수행한다.
    4. running execution context의 LexicalEnvironment를 newEnv로 설정한다.
  3. exprRefexprEvaluationCompletion으로 둔다.
  4. running execution context의 LexicalEnvironment를 oldEnv로 설정한다.
  5. exprValue를 ? GetValue(? exprRef)로 둔다.
  6. iterationKindenumerate이면, 다음을 수행한다.
    1. exprValueundefined 또는 null 중 하나이면, 다음을 수행한다.
      1. Completion Record { [[Type]]: break, [[Value]]: empty, [[Target]]: empty }를 반환한다.
    2. obj를 ! ToObject(exprValue)로 둔다.
    3. iteratorEnumerateObjectProperties(obj)로 둔다.
    4. nextMethod를 ! GetV(iterator, "next")로 둔다.
    5. Iterator Record { [[Iterator]]: iterator, [[NextMethod]]: nextMethod, [[Done]]: false }를 반환한다.
  7. Assert: iterationKinditerate 또는 async-iterate 중 하나이다.
  8. iterationKindasync-iterate이면 iteratorKindasync로 둔다.
  9. 그렇지 않으면 iteratorKindsync로 둔다.
  10. GetIterator(exprValue, iteratorKind)를 반환한다.

14.7.5.7 ForIn/OfBodyEvaluation ( lhs, stmt, iteratorRecord, iterationKind, lhsKind, labelSet [ , iteratorKind ] )

The abstract operation ForIn/OfBodyEvaluation takes arguments lhs (a Parse Node), stmt (a Statement Parse Node), iteratorRecord (an Iterator Record), iterationKind (enumerate or iterate), lhsKind (assignment, var-binding, or lexical-binding), and labelSet (a List of Strings) and optional argument iteratorKind (sync or async) and returns either a normal completion containing an ECMAScript language value or an abrupt completion. It performs the following steps when called:

  1. iteratorKind가 존재하지 않으면, iteratorKindsync로 설정한다.
  2. oldEnv를 실행 중인 실행 컨텍스트의 LexicalEnvironment로 둔다.
  3. iterationResultundefined로 둔다.
  4. lhsKindlexical-binding이면,
    1. 단언: lhsForDeclaration이다.
    2. lhsIsAwaitUsingDeclarationtrue이면,
      1. declarationKindasync-dispose로 둔다.
    3. 그렇지 않고 lhsIsUsingDeclarationtrue이면,
      1. declarationKindsync-dispose로 둔다.
    4. 그렇지 않으면,
      1. declarationKindnormal로 둔다.
  5. 그렇지 않으면,
    1. declarationKindnormal로 둔다.
  6. destructuringlhsIsDestructuring으로 둔다.
  7. destructuringtrue이고 lhsKindassignment이면,
    1. 단언: lhsLeftHandSideExpression이다.
    2. assignmentPatternlhs가 cover하는 AssignmentPattern으로 둔다.
  8. 반복한다.
    1. nextResult를 ? Call(iteratorRecord.[[NextMethod]], iteratorRecord.[[Iterator]])로 둔다.
    2. iteratorKindasync이면, nextResult를 ? Await(nextResult)로 설정한다.
    3. nextResult가 Object가 아니면, TypeError 예외를 던진다.
    4. done을 ? IteratorComplete(nextResult)로 둔다.
    5. donetrue이면, iterationResult를 반환한다.
    6. nextValue를 ? IteratorValue(nextResult)로 둔다.
    7. lhsKindassignment 또는 var-binding이면,
      1. destructuringtrue이면,
        1. lhsKindassignment이면,
          1. status를 인수 nextValueassignmentPatternDestructuringAssignmentEvaluationCompletion으로 둔다.
        2. 그렇지 않으면,
          1. 단언: lhsKindvar-binding이다.
          2. 단언: lhsForBinding이다.
          3. status를 인수 nextValueundefinedlhsBindingInitializationCompletion으로 둔다.
      2. 그렇지 않으면,
        1. lhsReflhsEvaluationCompletion으로 둔다. (반복해서 평가될 수 있다.)
        2. lhsKindassignment이고 lhsAssignmentTargetTypeweb-compat이면, ReferenceError 예외를 던진다.
        3. lhsRef가 abrupt 완료이면,
          1. statuslhsRef로 둔다.
        4. 그렇지 않으면,
          1. statusCompletion(PutValue(lhsRef.[[Value]], nextValue))로 둔다.
      3. iterationEnvundefined로 둔다.
    8. 그렇지 않으면,
      1. 단언: lhsKindlexical-binding이다.
      2. 단언: lhsForDeclaration이다.
      3. iterationEnvNewDeclarativeEnvironment(oldEnv)로 둔다.
      4. 인수 iterationEnvlhsForDeclarationBindingInstantiation을 수행한다.
      5. 실행 중인 실행 컨텍스트의 LexicalEnvironment를 iterationEnv로 설정한다.
      6. destructuringtrue이면,
        1. status를 인수 nextValueiterationEnvlhsForDeclarationBindingInitializationCompletion으로 둔다.
      7. 그렇지 않으면,
        1. 단언: lhs는 단일 이름을 바인딩한다.
        2. lhsNamelhsBoundNames의 유일한 요소로 둔다.
        3. lhsRef를 ! ResolveBinding(lhsName)으로 둔다.
        4. declarationKindnormal이 아니면,
          1. 단언: IsUnresolvableReference(lhsRef)는 false이다.
          2. baselhsRef.[[Base]]로 둔다.
          3. 단언: baseDeclarative Environment Record이다.
          4. statusCompletion(AddDisposableResource(base.[[DisposableResourceStack]], nextValue, declarationKind))로 둔다.
        5. 그렇지 않으면,
          1. statusNormalCompletion(unused)로 둔다.
        6. status가 정상 완료이면,
          1. statusCompletion(InitializeReferencedBinding(lhsRef, nextValue))로 설정한다.
    9. status가 abrupt 완료이면,
      1. iterationEnvundefined가 아니면,
        1. statusCompletion(DisposeResources(iterationEnv.[[DisposableResourceStack]], status))로 설정한다.
        2. 단언: status는 abrupt 완료이다.
      2. 실행 중인 실행 컨텍스트의 LexicalEnvironment를 oldEnv로 설정한다.
      3. iterationKindenumerate이면, ? status를 반환한다.
      4. 단언: iterationKinditerate이다.
      5. iteratorKindasync이면, ? AsyncIteratorClose(iteratorRecord, status)를 반환한다.
      6. IteratorClose(iteratorRecord, status)를 반환한다.
    10. resultstmtEvaluationCompletion으로 둔다.
    11. iterationEnvundefined가 아니면,
      1. resultCompletion(DisposeResources(iterationEnv.[[DisposableResourceStack]], result))로 설정한다.
    12. 실행 중인 실행 컨텍스트의 LexicalEnvironment를 oldEnv로 설정한다.
    13. LoopContinues(result, labelSet)가 false이면,
      1. statusCompletion(UpdateEmpty(result, iterationResult))로 설정한다.
      2. iterationKindenumerate이면, ? status를 반환한다.
      3. 단언: iterationKinditerate이다.
      4. iteratorKindasync이면, ? AsyncIteratorClose(iteratorRecord, status)를 반환한다.
      5. IteratorClose(iteratorRecord, status)를 반환한다.
    14. result.[[Value]]empty가 아니면, iterationResultresult.[[Value]]로 설정한다.

14.7.5.8 Runtime Semantics: Evaluation

BindingIdentifier : Identifier yield await
  1. bindingIdBindingIdentifierStringValue로 둔다.
  2. ResolveBinding(bindingId)를 반환한다.

14.7.5.9 EnumerateObjectProperties ( obj )

The abstract operation EnumerateObjectProperties takes argument obj (an Object) and returns an iterator object. It performs the following steps when called:

  1. obj의 enumerable property의 모든 String-valued key를 iterate하는 next method를 가진 iterator object를 반환한다. iterator object는 ECMAScript code에 의해 never directly accessible하지 않다. property를 enumerating하는 mechanics와 order는 specified되어 있지 않지만, 아래 specified된 rule에 conform해야 한다.

iteratorthrowreturn method는 null이며 never invoked되지 않습니다. iteratornext method는 property keyiterator value로 returned되어야 하는지 determine하기 위해 object property를 process합니다. returned property key는 Symbol인 key를 include하지 않습니다. target object의 property는 enumeration 중에 deleted될 수 있습니다. iteratornext method에 의해 processed되기 전에 deleted된 property는 ignored됩니다. enumeration 중에 target object에 새 property가 added되면, newly added property가 active enumeration에서 processed된다는 guarantee는 없습니다. property name은 어떤 enumeration에서든 iteratornext method에 의해 at most once returned됩니다.

target object의 property를 enumerating하는 것은 그 prototype의 property, 그 prototype의 prototype 등을 recursively enumerating하는 것을 include합니다; 그러나 prototype의 property는 같은 name을 가진 property가 iteratornext method에 의해 이미 processed되었으면 processed되지 않습니다. prototype object의 property가 이미 processed되었는지 determine할 때 [[Enumerable]] attribute의 value는 considered되지 않습니다. prototype object의 enumerable property name은 prototype object를 argument로 passing하여 EnumerateObjectProperties를 invoking함으로써 obtained되어야 합니다. EnumerateObjectProperties는 target object의 [[OwnPropertyKeys]] internal method를 calling하여 own property key를 obtain해야 합니다. target object의 Property attribute는 그 [[GetOwnProperty]] internal method를 calling하여 obtained되어야 합니다.

추가로, obj도 그 prototype chain 안의 어떤 object도 Proxy exotic object, TypedArray, module namespace exotic object 또는 implementation provided exotic object가 아니면, iterator는 다음 중 하나가 occur할 때까지 CreateForInIterator(obj)가 given한 iterator처럼 behave해야 합니다:

  • obj 또는 그 prototype chain 안의 object의 [[Prototype]] internal slot의 value가 changes,
  • obj 또는 그 prototype chain 안의 object에서 property가 removed,
  • obj의 prototype chain 안의 object에 property가 added, 또는
  • obj 또는 그 prototype chain 안의 object의 property의 [[Enumerable]] attribute value가 changes.
Note 1

ECMAScript implementation은 14.7.5.10.2.1의 algorithm을 directly implement할 필요가 없습니다. previous paragraph의 constraint 중 하나가 violated되지 않는 한 그 algorithm에서 deviate하지 않을 behaviour를 가진 어떤 implementation이라도 choose할 수 있습니다.

다음은 이러한 rule에 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
implementation이 CreateForInIterator와 match할 필요가 없는 exotic object의 list는, implementation이 historically those case에서 behaviour가 differed했고, all others에서는 agreed했기 때문에 chosen되었습니다.

14.7.5.10 For-In Iterator Objects

For-In Iterator는 어떤 specific object에 대한 specific iteration을 represent하는 object입니다. For-In Iterator object는 ECMAScript code에 의해 never directly accessible하지 않으며, 오직 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 property를 specific order로 iterate하는 For-In Iterator object를 create하는 데 사용됩니다. It performs the following steps when called:

  1. iteratorOrdinaryObjectCreate(%ForInIteratorPrototype%, « [[Object]], [[ObjectWasVisited]], [[VisitedKeys]], [[RemainingKeys]] »)로 둔다.
  2. iterator.[[Object]]obj로 설정한다.
  3. iterator.[[ObjectWasVisited]]false로 설정한다.
  4. iterator.[[VisitedKeys]]를 새 empty List로 설정한다.
  5. iterator.[[RemainingKeys]]를 새 empty List로 설정한다.
  6. iterator를 반환한다.

14.7.5.10.2 %ForInIteratorPrototype% Object

%ForInIteratorPrototype% object:

  • 모든 For-In Iterator object에 의해 inherited되는 property를 가집니다.
  • ordinary object입니다.
  • value가 %Iterator.prototype%[[Prototype]] internal slot을 가집니다.
  • ECMAScript code에 의해 never directly accessible하지 않습니다.
  • 다음 property를 가집니다:

14.7.5.10.2.1 %ForInIteratorPrototype%.next ( )

  1. iteratorthis value로 둔다.
  2. Assert: iterator는 Object이다.
  3. Assert: iteratorFor-In Iterator instance(14.7.5.10.3)의 모든 internal slot을 가진다.
  4. objiterator.[[Object]]로 둔다.
  5. Repeat,
    1. iterator.[[ObjectWasVisited]]false이면, 다음을 수행한다.
      1. keys를 ? obj.[[OwnPropertyKeys]]()로 둔다.
      2. keys의 각 element key에 대해, 다음을 수행한다.
        1. key가 String이면, 다음을 수행한다.
          1. keyiterator.[[RemainingKeys]]에 append한다.
      3. iterator.[[ObjectWasVisited]]true로 설정한다.
    2. iterator.[[RemainingKeys]]가 empty가 아닌 동안 Repeat,
      1. keyiterator.[[RemainingKeys]]의 first element로 둔다.
      2. iterator.[[RemainingKeys]]에서 first element를 remove한다.
      3. iterator.[[VisitedKeys]]key를 contain하지 않으면, 다음을 수행한다.
        1. propertyDesc를 ? obj.[[GetOwnProperty]](key)로 둔다.
        2. propertyDescundefined가 아니면, 다음을 수행한다.
          1. keyiterator.[[VisitedKeys]]에 append한다.
          2. propertyDesc.[[Enumerable]]true이면, CreateIteratorResultObject(key, false)를 반환한다.
    3. obj를 ? obj.[[GetPrototypeOf]]()로 설정한다.
    4. iterator.[[Object]]obj로 설정한다.
    5. iterator.[[ObjectWasVisited]]false로 설정한다.
    6. objnull이면, CreateIteratorResultObject(undefined, true)를 반환한다.

14.7.5.10.3 Properties of For-In Iterator Instances

For-In Iterator instance는 %ForInIteratorPrototype% intrinsic object로부터 property를 inherit하는 ordinary object입니다. For-In Iterator instance는 Table 34에 listed된 internal slot으로 initially created됩니다.

Table 34: Internal Slots of For-In Iterator Instances
Internal Slot Type Description
[[Object]] an Object property가 iterated되고 있는 Object value입니다.
[[ObjectWasVisited]] a Boolean iterator[[Object]]에 대해 [[OwnPropertyKeys]]를 invoked했으면 true, otherwise false입니다.
[[VisitedKeys]] a List of Strings iterator가 thus far emitted한 value입니다.
[[RemainingKeys]] a List of Strings 그 prototype의 property를 iterating하기 전에(그 prototype이 null이 아니면), current object에 대해 emitted될 remaining value입니다.

14.8 continue Statement

Syntax

ContinueStatement[Yield, Await] : continue ; continue [no LineTerminator here] LabelIdentifier[?Yield, ?Await] ;

14.8.1 Static Semantics: Early Errors

ContinueStatement : continue ; continue LabelIdentifier ;
  • ContinueStatement가 직접 또는 간접적으로(function 또는 static initialization block boundary를 crossing하지 않고) IterationStatement 안에 nested되어 있지 않으면 Syntax Error입니다.

14.8.2 Runtime Semantics: Evaluation

ContinueStatement : continue ;
  1. Completion Record { [[Type]]: continue, [[Value]]: empty, [[Target]]: empty }를 반환한다.
ContinueStatement : continue LabelIdentifier ;
  1. labelLabelIdentifierStringValue로 둔다.
  2. Completion Record { [[Type]]: continue, [[Value]]: empty, [[Target]]: label }를 반환한다.

14.9 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 ;
  1. Completion Record { [[Type]]: break, [[Value]]: empty, [[Target]]: empty }를 반환한다.
BreakStatement : break LabelIdentifier ;
  1. labelLabelIdentifierStringValue로 둔다.
  2. Completion Record { [[Type]]: break, [[Value]]: empty, [[Target]]: label }를 반환한다.

14.10 return Statement

Syntax

ReturnStatement[Yield, Await] : return ; return [no LineTerminator here] Expression[+In, ?Yield, ?Await] ; Note

return statement는 function이 execution을 cease하게 하고, 대부분의 경우 caller에게 value를 return합니다. Expression이 omitted되면, return value는 undefined입니다. 그렇지 않으면 return value는 Expression의 value입니다. surrounding context에 따라 return statement가 actually caller에게 value를 return하지 않을 수도 있습니다. 예를 들어 try block 안에서, return statement의 Completion Recordfinally block의 evaluation 중에 another Completion Record로 replaced될 수 있습니다.

14.10.1 Runtime Semantics: Evaluation

ReturnStatement : return ;
  1. ReturnCompletion(undefined)를 반환한다.
ReturnStatement : return Expression ;
  1. exprRefExpressionEvaluation으로 ? 둔다.
  2. exprValue를 ? GetValue(exprRef)로 둔다.
  3. GetGeneratorKind()가 async이면, exprValue를 ? Await(exprValue)로 설정한다.
  4. ReturnCompletion(exprValue)를 반환한다.

14.11 with Statement

Note 1

새 ECMAScript code에서는 Legacy with statement의 use가 discouraged됩니다. strict mode codenon-strict code 모두에서 permitted되는 alternative, 예를 들어 destructuring assignment를 consider하십시오.

Syntax

WithStatement[Yield, Await, Return] : with ( Expression[+In, ?Yield, ?Await] ) Statement[?Yield, ?Await, ?Return] Note 2

with statement는 computed object에 대한 Object Environment Recordrunning execution context의 lexical environment에 adds합니다. 그런 다음 이 augmented lexical environment를 사용하여 statement를 executes합니다. Finally, original lexical environment를 restores합니다.

14.11.1 Static Semantics: Early Errors

WithStatement : with ( Expression ) Statement Note

second rule은 B.3.1에 specified된 extension이 implemented된 경우에만 apply할 필요가 있습니다.

14.11.2 Runtime Semantics: Evaluation

WithStatement : with ( Expression ) Statement
  1. valueExpressionEvaluation으로 ? 둔다.
  2. obj를 ? ToObject(? GetValue(value))로 둔다.
  3. oldEnvrunning execution context의 LexicalEnvironment로 둔다.
  4. newEnvNewObjectEnvironment(obj, true, oldEnv)로 둔다.
  5. running execution context의 LexicalEnvironment를 newEnv로 설정한다.
  6. stmtCompletionStatementEvaluationCompletion으로 둔다.
  7. running execution context의 LexicalEnvironment를 oldEnv로 설정한다.
  8. UpdateEmpty(stmtCompletion, undefined)를 반환한다.
Note

control이 embedded Statement를 어떻게 leave하든, normally든 어떤 form의 abrupt completion 또는 exception에 의해서든, LexicalEnvironment는 항상 former state로 restored됩니다.

14.12 switch Statement

Syntax

SwitchStatement[Yield, Await, Return] : switch ( Expression[+In, ?Yield, ?Await] ) CaseBlock[?Yield, ?Await, ?Return] CaseBlock[Yield, Await, Return] : { CaseClauses[?Yield, ?Await, ?Return]opt } { CaseClauses[?Yield, ?Await, ?Return]opt DefaultClause[?Yield, ?Await, ?Return] CaseClauses[?Yield, ?Await, ?Return]opt } CaseClauses[Yield, Await, Return] : CaseClause[?Yield, ?Await, ?Return] CaseClauses[?Yield, ?Await, ?Return] CaseClause[?Yield, ?Await, ?Return] CaseClause[Yield, Await, Return] : case Expression[+In, ?Yield, ?Await] : StatementList[?Yield, ?Await, ?Return]opt DefaultClause[Yield, Await, Return] : default : StatementList[?Yield, ?Await, ?Return]opt

14.12.1 Static Semantics: Early Errors

SwitchStatement : switch ( Expression ) CaseBlock CaseClause : case Expression : StatementList DefaultClause : default : StatementList

14.12.2 Runtime Semantics: CaseBlockEvaluation

The syntax-directed operation CaseBlockEvaluation takes argument input (an ECMAScript language value) and returns either a normal completion containing an ECMAScript language value or an abrupt completion. It is defined piecewise over the following productions:

CaseBlock : { }
  1. undefined를 반환한다.
CaseBlock : { CaseClauses }
  1. resultValueundefined로 둔다.
  2. caseClauses를 source text order의 CaseClauses 안의 CaseClause item의 List로 둔다.
  3. foundfalse로 둔다.
  4. caseClauses의 각 CaseClause clause에 대해, 다음을 수행한다.
    1. foundfalse이면, 다음을 수행한다.
      1. found를 ? CaseClauseIsSelected(clause, input)로 설정한다.
    2. foundtrue이면, 다음을 수행한다.
      1. completionclauseEvaluationCompletion으로 둔다.
      2. completion.[[Value]]empty가 아니면, resultValuecompletion.[[Value]]로 설정한다.
      3. completionabrupt completion이면, ? UpdateEmpty(completion, resultValue)를 반환한다.
  5. resultValue를 반환한다.
CaseBlock : { CaseClausesopt DefaultClause CaseClausesopt }
  1. resultValueundefined로 둔다.
  2. first CaseClauses가 present이면, 다음을 수행한다.
    1. caseClauses를 source text order의 first CaseClauses 안의 CaseClause item의 List로 둔다.
  3. 그렇지 않으면,
    1. caseClauses를 새 empty List로 둔다.
  4. foundfalse로 둔다.
  5. caseClauses의 각 CaseClause clause에 대해, 다음을 수행한다.
    1. foundfalse이면, 다음을 수행한다.
      1. found를 ? CaseClauseIsSelected(clause, input)로 설정한다.
    2. foundtrue이면, 다음을 수행한다.
      1. completionclauseEvaluationCompletion으로 둔다.
      2. completion.[[Value]]empty가 아니면, resultValuecompletion.[[Value]]로 설정한다.
      3. completionabrupt completion이면, ? UpdateEmpty(completion, resultValue)를 반환한다.
  6. foundInBfalse로 둔다.
  7. second CaseClauses가 present이면, 다음을 수행한다.
    1. secondCaseClauses를 source text order의 second CaseClauses 안의 CaseClause item의 List로 둔다.
  8. 그렇지 않으면,
    1. secondCaseClauses를 새 empty List로 둔다.
  9. foundfalse이면, 다음을 수행한다.
    1. secondCaseClauses의 각 CaseClause clause에 대해, 다음을 수행한다.
      1. foundInBfalse이면, 다음을 수행한다.
        1. foundInB를 ? CaseClauseIsSelected(clause, input)로 설정한다.
      2. foundInBtrue이면, 다음을 수행한다.
        1. completionCaseClause clauseEvaluationCompletion으로 둔다.
        2. completion.[[Value]]empty가 아니면, resultValuecompletion.[[Value]]로 설정한다.
        3. completionabrupt completion이면, ? UpdateEmpty(completion, resultValue)를 반환한다.
  10. foundInBtrue이면, resultValue를 반환한다.
  11. defaultRDefaultClauseEvaluationCompletion으로 둔다.
  12. defaultR.[[Value]]empty가 아니면, resultValuedefaultR.[[Value]]로 설정한다.
  13. defaultRabrupt completion이면, ? UpdateEmpty(defaultR, resultValue)를 반환한다.
  14. NOTE: 다음은 second CaseClauses의 또 다른 complete iteration이다.
  15. secondCaseClauses의 각 CaseClause clause에 대해, 다음을 수행한다.
    1. completionCaseClause clauseEvaluationCompletion으로 둔다.
    2. completion.[[Value]]empty가 아니면, resultValuecompletion.[[Value]]로 설정한다.
    3. completionabrupt completion이면, ? UpdateEmpty(completion, resultValue)를 반환한다.
  16. resultValue를 반환한다.

14.12.3 CaseClauseIsSelected ( caseClauseNode, input )

The abstract operation CaseClauseIsSelected takes arguments caseClauseNode (a CaseClause Parse Node) and input (an ECMAScript language value) and returns either a normal completion containing a Boolean or an abrupt completion. caseClauseNodeinput과 match하는지 determine합니다. It performs the following steps when called:

  1. Assert: caseClauseNode는 production CaseClause : case Expression : StatementListopt 의 instance이다.
  2. exprRefcaseClauseNodeExpressionEvaluation으로 ? 둔다.
  3. clauseSelector를 ? GetValue(exprRef)로 둔다.
  4. IsStrictlyEqual(input, clauseSelector)를 반환한다.
Note

이 operation은 caseClauseNodeStatementList(있는 경우)를 execute하지 않습니다. CaseBlock algorithm은 어떤 StatementList를 executing 시작할지 determine하기 위해 그 return value를 사용합니다.

14.12.4 Runtime Semantics: Evaluation

SwitchStatement : switch ( Expression ) CaseBlock
  1. exprRefExpressionEvaluation을 ? 수행한 결과로 둔다.
  2. switchValue를 ? GetValue(exprRef)로 둔다.
  3. oldEnv를 실행 중인 실행 컨텍스트의 LexicalEnvironment로 둔다.
  4. blockEnvNewDeclarativeEnvironment(oldEnv)로 둔다.
  5. BlockDeclarationInstantiation(CaseBlock, blockEnv)를 수행한다.
  6. 실행 중인 실행 컨텍스트의 LexicalEnvironment를 blockEnv로 설정한다.
  7. blockResult를 인수 switchValueCaseBlockCaseBlockEvaluationCompletion으로 둔다.
  8. 단언: blockEnv.[[DisposableResourceStack]]은 빈 List이다.
  9. 실행 중인 실행 컨텍스트의 LexicalEnvironment를 oldEnv로 설정한다.
  10. blockResult를 반환한다.
Note

control이 SwitchStatement를 어떻게 leave하든 LexicalEnvironment는 항상 former state로 restored됩니다.

CaseClause : case Expression :
  1. empty를 반환한다.
CaseClause : case Expression : StatementList
  1. StatementListEvaluation을 ? 반환한다.
DefaultClause : default :
  1. empty를 반환한다.
DefaultClause : default : StatementList
  1. StatementListEvaluation을 ? 반환한다.

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로 prefixed될 수 있습니다. Labelled statement는 labelled breakcontinue statement와 conjunction에서만 사용됩니다. ECMAScript에는 goto statement가 없습니다. StatementLabelledStatement의 part가 될 수 있고, 그 자체가 LabelledStatement의 part가 될 수 있으며, 이런 식으로 계속될 수 있습니다. 이런 way로 introduced된 label은 individual statement의 semantics를 describing할 때 collectively “current label set”이라고 referred됩니다.

14.13.1 Static Semantics: Early Errors

LabelledItem : FunctionDeclaration
  • 이 production에 의해 어떤 source text든 matched되면 Syntax Error입니다. 단, 그 source text가 non-strict code이고 host가 web browser이거나 그 밖에 Labelled Function Declarations를 support하는 경우는 예외입니다.

14.13.2 Static Semantics: IsLabelledFunction ( stmt )

The abstract operation IsLabelledFunction takes argument stmt (a Statement Parse Node) and returns a Boolean. It performs the following steps when called:

  1. stmtLabelledStatement가 아니면, false를 반환한다.
  2. itemstmtLabelledItem으로 둔다.
  3. item LabelledItem : FunctionDeclaration 이면, true를 반환한다.
  4. subStmtitemStatement로 둔다.
  5. IsLabelledFunction(subStmt)를 반환한다.

14.13.3 Runtime Semantics: Evaluation

LabelledStatement : LabelIdentifier : LabelledItem
  1. argument « »를 가진 this LabelledStatementLabelledEvaluation을 ? 반환한다.

14.13.4 Runtime Semantics: LabelledEvaluation

The syntax-directed operation LabelledEvaluation takes argument labelSet (a List of Strings) and returns either a normal completion containing either an ECMAScript language value or empty, or an abrupt completion. It is defined piecewise over the following productions:

BreakableStatement : IterationStatement
  1. stmtResult를 argument labelSet를 가진 IterationStatementLoopEvaluationCompletion으로 둔다.
  2. stmtResultbreak completion이면, 다음을 수행한다.
    1. stmtResult.[[Target]]empty이면, 다음을 수행한다.
      1. stmtResult.[[Value]]empty이면, stmtResultNormalCompletion(undefined)로 설정한다.
      2. 그렇지 않으면, stmtResultNormalCompletion(stmtResult.[[Value]])로 설정한다.
  3. stmtResult를 반환한다.
BreakableStatement : SwitchStatement
  1. stmtResultSwitchStatementEvaluationCompletion으로 둔다.
  2. stmtResultbreak completion이면, 다음을 수행한다.
    1. stmtResult.[[Target]]empty이면, 다음을 수행한다.
      1. stmtResult.[[Value]]empty이면, stmtResultNormalCompletion(undefined)로 설정한다.
      2. 그렇지 않으면, stmtResultNormalCompletion(stmtResult.[[Value]])로 설정한다.
  3. stmtResult를 반환한다.
Note 1

BreakableStatement는 unlabelled BreakStatement를 통해 exited될 수 있는 것입니다.

LabelledStatement : LabelIdentifier : LabelledItem
  1. labelLabelIdentifierStringValue로 둔다.
  2. newLabelSetlabelSet와 « label »의 list-concatenation으로 둔다.
  3. stmtResult를 argument newLabelSet를 가진 LabelledItemLabelledEvaluationCompletion으로 둔다.
  4. stmtResultbreak completion이고 stmtResult.[[Target]]label이면, 다음을 수행한다.
    1. stmtResultNormalCompletion(stmtResult.[[Value]])로 설정한다.
  5. stmtResult를 반환한다.
LabelledItem : FunctionDeclaration
  1. FunctionDeclarationEvaluation을 ? 반환한다.
Statement : BlockStatement VariableStatement EmptyStatement ExpressionStatement IfStatement ContinueStatement BreakStatement ReturnStatement WithStatement ThrowStatement TryStatement DebuggerStatement
  1. StatementEvaluation을 ? 반환한다.
Note 2

LabelledEvaluation을 위한 special semantics를 가진 Statement의 only two production은 BreakableStatementLabelledStatement입니다.

14.14 throw Statement

Syntax

ThrowStatement[Yield, Await] : throw [no LineTerminator here] Expression[+In, ?Yield, ?Await] ;

14.14.1 Runtime Semantics: Evaluation

ThrowStatement : throw Expression ;
  1. exprRefExpressionEvaluation으로 ? 둔다.
  2. exprValue를 ? GetValue(exprRef)로 둔다.
  3. exprValue를 Throw한다.

14.15 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이 occur할 수 있는 code block을 encloses합니다. catch clause는 exception-handling code를 제공합니다. catch clause가 exception을 catches하면, 그 CatchParameter가 해당 exception에 bound됩니다.

14.15.1 Static Semantics: Early Errors

Catch : catch ( CatchParameter ) Block

14.15.2 Runtime Semantics: CatchClauseEvaluation

The syntax-directed operation CatchClauseEvaluation takes argument thrownValue (an ECMAScript language value) and returns either a normal completion containing either an ECMAScript language value or empty, or an abrupt completion. It is defined piecewise over the following productions:

Catch : catch ( CatchParameter ) Block
  1. oldEnvrunning execution context의 LexicalEnvironment로 둔다.
  2. catchEnvNewDeclarativeEnvironment(oldEnv)로 둔다.
  3. CatchParameterBoundNames의 각 element argName에 대해, 다음을 수행한다.
    1. catchEnv.CreateMutableBinding(argName, false)를 수행한다.
  4. running execution context의 LexicalEnvironment를 catchEnv로 설정한다.
  5. status를 arguments thrownValuecatchEnv를 가진 CatchParameterBindingInitializationCompletion으로 둔다.
  6. statusabrupt completion이면, 다음을 수행한다.
    1. running execution context의 LexicalEnvironment를 oldEnv로 설정한다.
    2. status를 반환한다.
  7. blockCompletionBlockEvaluationCompletion으로 둔다.
  8. running execution context의 LexicalEnvironment를 oldEnv로 설정한다.
  9. blockCompletion을 반환한다.
Catch : catch Block
  1. BlockEvaluation을 ? 반환한다.
Note

control이 Block을 어떻게 leave하든 LexicalEnvironment는 항상 former state로 restored됩니다.

14.15.3 Runtime Semantics: Evaluation

TryStatement : try Block Catch
  1. blockResultBlockEvaluationCompletion으로 둔다.
  2. blockResultthrow completion이면 catchResult를 argument blockResult.[[Value]]를 가진 CatchCatchClauseEvaluationCompletion으로 둔다.
  3. 그렇지 않으면 catchResultblockResult로 둔다.
  4. UpdateEmpty(catchResult, undefined)를 반환한다.
TryStatement : try Block Finally
  1. blockResultBlockEvaluationCompletion으로 둔다.
  2. finallyResultFinallyEvaluationCompletion으로 둔다.
  3. finallyResultnormal completion이면, finallyResultblockResult로 설정한다.
  4. UpdateEmpty(finallyResult, undefined)를 반환한다.
TryStatement : try Block Catch Finally
  1. blockResultBlockEvaluationCompletion으로 둔다.
  2. blockResultthrow completion이면 catchResult를 argument blockResult.[[Value]]를 가진 CatchCatchClauseEvaluationCompletion으로 둔다.
  3. 그렇지 않으면 catchResultblockResult로 둔다.
  4. finallyResultFinallyEvaluationCompletion으로 둔다.
  5. finallyResultnormal completion이면, finallyResultcatchResult로 설정한다.
  6. UpdateEmpty(finallyResult, undefined)를 반환한다.

14.16 debugger Statement

Syntax

DebuggerStatement : debugger ;

14.16.1 Runtime Semantics: Evaluation

Note

DebuggerStatement를 evaluating하면 implementation이 debugger 아래에서 run될 때 breakpoint를 cause할 수 있습니다. debugger가 present하지 않거나 active하지 않으면 이 statement는 observable effect를 가지지 않습니다.

DebuggerStatement : debugger ;
  1. implementation-defined debugging facility가 available하고 enabled이면, 다음을 수행한다.
    1. implementation-defined debugging action을 수행한다.
    2. implementation-defined Completion Record를 반환한다.
  2. empty를 반환한다.

15 ECMAScript 언어: Functions and Classes

Note

다양한 ECMAScript language element는 ECMAScript function object(10.2)의 creation을 cause합니다. 그러한 function의 Evaluation은 그 [[Call]] internal method(10.2.1)의 execution으로 시작됩니다.

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가 multiple occurrence로 나타나는 것은 simple parameter list를 가지고 strict mode code 안에서 defined되지 않은 function에 대해서만 allowed됩니다.

15.1.2 Static Semantics: ContainsExpression

The syntax-directed operation ContainsExpression takes no arguments and returns a Boolean. It is defined piecewise over the following productions:

ObjectBindingPattern : { } { BindingRestProperty }
  1. false를 반환한다.
ObjectBindingPattern : { BindingPropertyList , BindingRestProperty }
  1. BindingPropertyListContainsExpression을 반환한다.
ArrayBindingPattern : [ Elisionopt ]
  1. false를 반환한다.
ArrayBindingPattern : [ Elisionopt BindingRestElement ]
  1. BindingRestElementContainsExpression을 반환한다.
ArrayBindingPattern : [ BindingElementList , Elisionopt ]
  1. BindingElementListContainsExpression을 반환한다.
ArrayBindingPattern : [ BindingElementList , Elisionopt BindingRestElement ]
  1. hasBindingElementListContainsExpression으로 둔다.
  2. hastrue이면, true를 반환한다.
  3. BindingRestElementContainsExpression을 반환한다.
BindingPropertyList : BindingPropertyList , BindingProperty
  1. hasBindingPropertyListContainsExpression으로 둔다.
  2. hastrue이면, true를 반환한다.
  3. BindingPropertyContainsExpression을 반환한다.
BindingElementList : BindingElementList , BindingElisionElement
  1. hasBindingElementListContainsExpression으로 둔다.
  2. hastrue이면, true를 반환한다.
  3. BindingElisionElementContainsExpression을 반환한다.
BindingElisionElement : Elisionopt BindingElement
  1. BindingElementContainsExpression을 반환한다.
BindingProperty : PropertyName : BindingElement
  1. hasPropertyNameIsComputedPropertyKey로 둔다.
  2. hastrue이면, true를 반환한다.
  3. BindingElementContainsExpression을 반환한다.
BindingElement : BindingPattern Initializer
  1. true를 반환한다.
SingleNameBinding : BindingIdentifier
  1. false를 반환한다.
SingleNameBinding : BindingIdentifier Initializer
  1. true를 반환한다.
BindingRestElement : ... BindingIdentifier
  1. false를 반환한다.
BindingRestElement : ... BindingPattern
  1. BindingPatternContainsExpression을 반환한다.
FormalParameters : [empty]
  1. false를 반환한다.
FormalParameters : FormalParameterList , FunctionRestParameter
  1. FormalParameterListContainsExpressiontrue이면, true를 반환한다.
  2. FunctionRestParameterContainsExpression을 반환한다.
FormalParameterList : FormalParameterList , FormalParameter
  1. FormalParameterListContainsExpressiontrue이면, true를 반환한다.
  2. FormalParameterContainsExpression을 반환한다.
ArrowParameters : BindingIdentifier
  1. false를 반환한다.
ArrowParameters : CoverParenthesizedExpressionAndArrowParameterList
  1. formalsCoverParenthesizedExpressionAndArrowParameterListcovered하는 ArrowFormalParameters로 둔다.
  2. formalsContainsExpression을 반환한다.
AsyncArrowBindingIdentifier : BindingIdentifier
  1. false를 반환한다.

15.1.3 Static Semantics: IsSimpleParameterList

The syntax-directed operation IsSimpleParameterList takes no arguments and returns a Boolean. It is defined piecewise over the following productions:

BindingElement : BindingPattern
  1. false를 반환한다.
BindingElement : BindingPattern Initializer
  1. false를 반환한다.
SingleNameBinding : BindingIdentifier
  1. true를 반환한다.
SingleNameBinding : BindingIdentifier Initializer
  1. false를 반환한다.
FormalParameters : [empty]
  1. true를 반환한다.
FormalParameters : FunctionRestParameter
  1. false를 반환한다.
FormalParameters : FormalParameterList , FunctionRestParameter
  1. false를 반환한다.
FormalParameterList : FormalParameterList , FormalParameter
  1. FormalParameterListIsSimpleParameterListfalse이면, false를 반환한다.
  2. FormalParameterIsSimpleParameterList를 반환한다.
FormalParameter : BindingElement
  1. BindingElementIsSimpleParameterList를 반환한다.
ArrowParameters : BindingIdentifier
  1. true를 반환한다.
ArrowParameters : CoverParenthesizedExpressionAndArrowParameterList
  1. formalsCoverParenthesizedExpressionAndArrowParameterListcovered하는 ArrowFormalParameters로 둔다.
  2. formalsIsSimpleParameterList를 반환한다.
AsyncArrowBindingIdentifier : BindingIdentifier
  1. true를 반환한다.
CoverCallExpressionAndAsyncArrowHead : MemberExpression Arguments
  1. headCoverCallExpressionAndAsyncArrowHeadcovered하는 AsyncArrowHead로 둔다.
  2. headIsSimpleParameterList를 반환한다.

15.1.4 Static Semantics: HasInitializer

The syntax-directed operation HasInitializer takes no arguments and returns a Boolean. It is defined piecewise over the following productions:

BindingElement : BindingPattern
  1. false를 반환한다.
BindingElement : BindingPattern Initializer
  1. true를 반환한다.
SingleNameBinding : BindingIdentifier
  1. false를 반환한다.
SingleNameBinding : BindingIdentifier Initializer
  1. true를 반환한다.
FormalParameterList : FormalParameterList , FormalParameter
  1. FormalParameterListHasInitializertrue이면, true를 반환한다.
  2. FormalParameterHasInitializer를 반환한다.

15.1.5 Static Semantics: ExpectedArgumentCount

The syntax-directed operation ExpectedArgumentCount takes no arguments and returns a non-negative integer. It is defined piecewise over the following productions:

FormalParameters : [empty] FunctionRestParameter
  1. 0을 반환한다.
FormalParameters : FormalParameterList , FunctionRestParameter
  1. FormalParameterListExpectedArgumentCount를 반환한다.
Note

FormalParameterList의 ExpectedArgumentCount는 rest parameter 또는 Initializer를 가진 first FormalParameter의 left에 있는 FormalParameters의 수입니다. initializer가 없는 FormalParameter는 initializer를 가진 first parameter 뒤에 allowed되지만, 그러한 parameter는 undefined를 default value로 하는 optional parameter로 considered됩니다.

FormalParameterList : FormalParameter
  1. FormalParameterHasInitializertrue이면, 0을 반환한다.
  2. 1을 반환한다.
FormalParameterList : FormalParameterList , FormalParameter
  1. countFormalParameterListExpectedArgumentCount로 둔다.
  2. FormalParameterListHasInitializertrue이거나 FormalParameterHasInitializertrue이면, count를 반환한다.
  3. count + 1을 반환한다.
ArrowParameters : BindingIdentifier
  1. 1을 반환한다.
ArrowParameters : CoverParenthesizedExpressionAndArrowParameterList
  1. formalsCoverParenthesizedExpressionAndArrowParameterListcovered하는 ArrowFormalParameters로 둔다.
  2. formalsExpectedArgumentCount를 반환한다.
PropertySetParameterList : FormalParameter
  1. FormalParameterHasInitializertrue이면, 0을 반환한다.
  2. 1을 반환한다.
AsyncArrowBindingIdentifier : BindingIdentifier
  1. 1을 반환한다.

15.2 Function Definitions

Syntax

FunctionDeclaration[Yield, Await, Default] : function BindingIdentifier[?Yield, ?Await] ( FormalParameters[~Yield, ~Await] ) { FunctionBody[~Yield, ~Await] } [+Default] function ( FormalParameters[~Yield, ~Await] ) { FunctionBody[~Yield, ~Await] } FunctionExpression : function BindingIdentifier[~Yield, ~Await]opt ( FormalParameters[~Yield, ~Await] ) { FunctionBody[~Yield, ~Await] } FunctionBody[Yield, Await] : FunctionStatementList[?Yield, ?Await] FunctionStatementList[Yield, Await] : StatementList[?Yield, ?Await, +Return]opt

15.2.1 Static Semantics: Early Errors

FunctionDeclaration : function BindingIdentifier ( FormalParameters ) { FunctionBody } function ( FormalParameters ) { FunctionBody } FunctionExpression : function BindingIdentifieropt ( FormalParameters ) { FunctionBody } Note

FunctionBodyLexicallyDeclaredNames는 var 또는 function declaration을 사용하여 bound된 identifier를 include하지 않습니다.

FunctionBody : FunctionStatementList

15.2.2 Static Semantics: FunctionBodyContainsUseStrict

The syntax-directed operation FunctionBodyContainsUseStrict takes no arguments and returns a Boolean. It is defined piecewise over the following productions:

FunctionBody : FunctionStatementList
  1. FunctionBodyDirective PrologueUse Strict Directive를 contain하면, true를 반환한다.
  2. false를 반환한다.

15.2.3 Runtime Semantics: EvaluateFunctionBody

The syntax-directed operation EvaluateFunctionBody takes arguments funcObj (an ECMAScript function object) and argList (a List of ECMAScript language values) and returns a return completion or a throw completion. It is defined piecewise over the following productions:

FunctionBody : FunctionStatementList
  1. FunctionDeclarationInstantiation(funcObj, argList)를 수행한다.
  2. FunctionStatementListEvaluation을 ? 수행한다.
  3. NOTE: previous step이 normal completion을 result했다면, evaluation은 FunctionStatementList의 end를 지나 proceed함으로써 finished된 것이다.
  4. ReturnCompletion(undefined)를 반환한다.

15.2.4 Runtime Semantics: InstantiateOrdinaryFunctionObject

The syntax-directed operation InstantiateOrdinaryFunctionObject takes arguments envRecord (an Environment Record) and privateEnv (a PrivateEnvironment Record or null) and returns an ECMAScript function object. It is defined piecewise over the following productions:

FunctionDeclaration : function BindingIdentifier ( FormalParameters ) { FunctionBody }
  1. nameBindingIdentifierStringValue로 둔다.
  2. sourceTextFunctionDeclaration에 matched된 source text로 둔다.
  3. closureOrdinaryFunctionCreate(%Function.prototype%, sourceText, FormalParameters, FunctionBody, non-lexical-this, envRecord, privateEnv)로 둔다.
  4. SetFunctionName(closure, name)을 수행한다.
  5. MakeConstructor(closure)를 수행한다.
  6. closure를 반환한다.
FunctionDeclaration : function ( FormalParameters ) { FunctionBody }
  1. sourceTextFunctionDeclaration에 matched된 source text로 둔다.
  2. closureOrdinaryFunctionCreate(%Function.prototype%, sourceText, FormalParameters, FunctionBody, non-lexical-this, envRecord, privateEnv)로 둔다.
  3. SetFunctionName(closure, "default")를 수행한다.
  4. MakeConstructor(closure)를 수행한다.
  5. closure를 반환한다.
Note

anonymous FunctionDeclarationexport default declaration의 part로만 occur할 수 있으므로, 그 function code는 따라서 항상 strict mode code입니다.

15.2.5 Runtime Semantics: InstantiateOrdinaryFunctionExpression

The syntax-directed operation InstantiateOrdinaryFunctionExpression takes optional argument name (a property key or a Private Name) and returns an ECMAScript function object. It is defined piecewise over the following productions:

FunctionExpression : function ( FormalParameters ) { FunctionBody }
  1. name이 present하지 않으면, name을 empty String으로 설정한다.
  2. envRecordrunning execution context의 LexicalEnvironment로 둔다.
  3. privateEnvrunning execution context의 PrivateEnvironment로 둔다.
  4. sourceTextFunctionExpression에 matched된 source text로 둔다.
  5. closureOrdinaryFunctionCreate(%Function.prototype%, sourceText, FormalParameters, FunctionBody, non-lexical-this, envRecord, privateEnv)로 둔다.
  6. SetFunctionName(closure, name)을 수행한다.
  7. MakeConstructor(closure)를 수행한다.
  8. closure를 반환한다.
FunctionExpression : function BindingIdentifier ( FormalParameters ) { FunctionBody }
  1. Assert: name은 present하지 않는다.
  2. nameBindingIdentifierStringValue로 설정한다.
  3. outerEnvrunning execution context의 LexicalEnvironment로 둔다.
  4. funcEnvNewDeclarativeEnvironment(outerEnv)로 둔다.
  5. funcEnv.CreateImmutableBinding(name, false)를 수행한다.
  6. privateEnvrunning execution context의 PrivateEnvironment로 둔다.
  7. sourceTextFunctionExpression에 matched된 source text로 둔다.
  8. closureOrdinaryFunctionCreate(%Function.prototype%, sourceText, FormalParameters, FunctionBody, non-lexical-this, funcEnv, privateEnv)로 둔다.
  9. SetFunctionName(closure, name)을 수행한다.
  10. MakeConstructor(closure)를 수행한다.
  11. funcEnv.InitializeBinding(name, closure)를 수행한다.
  12. closure를 반환한다.
Note

FunctionExpression 안의 BindingIdentifier는 function이 recursively 자신을 call할 수 있도록 FunctionExpressionFunctionBody 내부에서 referenced될 수 있습니다. 그러나 FunctionDeclaration과 달리 FunctionExpression 안의 BindingIdentifierFunctionExpression을 enclosing하는 scope에서 referenced될 수 없고 그 scope에 affect하지 않습니다.

15.2.6 Runtime Semantics: Evaluation

FunctionDeclaration : function BindingIdentifier ( FormalParameters ) { FunctionBody }
  1. empty를 반환한다.
Note 1 FunctionDeclaration : function ( FormalParameters ) { FunctionBody }
  1. empty를 반환한다.
FunctionExpression : function BindingIdentifieropt ( FormalParameters ) { FunctionBody }
  1. FunctionExpressionInstantiateOrdinaryFunctionExpression을 반환한다.
Note 2

FunctionDeclaration 또는 FunctionExpression을 사용하여 defined된 모든 function에는, 그 function이 constructor로 사용될 possibility를 allow하기 위해 "prototype" property가 automatically created됩니다.

FunctionStatementList : [empty]
  1. undefined를 반환한다.
FunctionStatementList : StatementList
  1. resultStatementListEvaluationCompletion으로 둔다.
  2. env를 실행 중인 실행 컨텍스트의 LexicalEnvironment로 둔다.
  3. 단언: envDeclarative Environment Record이다.
  4. 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를 processing할 때, CoverParenthesizedExpressionAndArrowParameterList의 interpretation은 다음 grammar를 사용하여 refined됩니다:

ArrowFormalParameters[Yield, Await] : ( UniqueFormalParameters[?Yield, ?Await] )

15.3.1 Static Semantics: Early Errors

ArrowFunction : ArrowParameters => ConciseBody ArrowParameters : CoverParenthesizedExpressionAndArrowParameterList

15.3.2 Static Semantics: ConciseBodyContainsUseStrict

The syntax-directed operation ConciseBodyContainsUseStrict takes no arguments and returns a Boolean. It is defined piecewise over the following productions:

ConciseBody : ExpressionBody
  1. false를 반환한다.
ConciseBody : { FunctionBody }
  1. FunctionBodyFunctionBodyContainsUseStrict를 반환한다.

15.3.3 Runtime Semantics: EvaluateConciseBody

The syntax-directed operation EvaluateConciseBody takes arguments funcObj (an ECMAScript function object) and argList (a List of ECMAScript language values) and returns a return completion or a throw completion. It is defined piecewise over the following productions:

ConciseBody : ExpressionBody
  1. FunctionDeclarationInstantiation(funcObj, argList)를 수행한다.
  2. ExpressionBodyEvaluation을 ? 반환한다.

15.3.4 Runtime Semantics: InstantiateArrowFunctionExpression

The syntax-directed operation InstantiateArrowFunctionExpression takes optional argument name (a property key or a Private Name) and returns an ECMAScript function object. It is defined piecewise over the following productions:

ArrowFunction : ArrowParameters => ConciseBody
  1. name이 present하지 않으면, name을 empty String으로 설정한다.
  2. envRecordrunning execution context의 LexicalEnvironment로 둔다.
  3. privateEnvrunning execution context의 PrivateEnvironment로 둔다.
  4. sourceTextArrowFunction에 matched된 source text로 둔다.
  5. closureOrdinaryFunctionCreate(%Function.prototype%, sourceText, ArrowParameters, ConciseBody, lexical-this, envRecord, privateEnv)로 둔다.
  6. SetFunctionName(closure, name)을 수행한다.
  7. closure를 반환한다.
Note

ArrowFunctionarguments, super, this 또는 new.target을 위한 local binding을 define하지 않습니다. ArrowFunction 안의 arguments, super, this 또는 new.target에 대한 모든 reference는 lexically enclosing environment 안의 binding으로 resolve되어야 합니다. 보통 이는 immediately enclosing function의 Function Environment입니다. ArrowFunctionsuper에 대한 reference를 contain할 수 있더라도, step 5에서 created되는 function objectMakeMethod를 수행하여 method로 만들어지지 않습니다. super를 reference하는 ArrowFunction은 항상 non-ArrowFunction 안에 contained되며, super를 implement하는 데 필요한 state는 ArrowFunctionfunction object가 capture하는 envRecord를 통해 accessible합니다.

15.3.5 Runtime Semantics: Evaluation

ArrowFunction : ArrowParameters => ConciseBody
  1. ArrowFunctionInstantiateArrowFunctionExpression을 반환한다.
ExpressionBody : AssignmentExpression
  1. exprRefAssignmentExpressionEvaluation으로 ? 둔다.
  2. exprValue를 ? GetValue(exprRef)로 둔다.
  3. ReturnCompletion(exprValue)를 반환한다.

15.4 Method Definitions

Syntax

MethodDefinition[Yield, Await] : ClassElementName[?Yield, ?Await] ( UniqueFormalParameters[~Yield, ~Await] ) { FunctionBody[~Yield, ~Await] } GeneratorMethod[?Yield, ?Await] AsyncMethod[?Yield, ?Await] AsyncGeneratorMethod[?Yield, ?Await] get ClassElementName[?Yield, ?Await] ( ) { FunctionBody[~Yield, ~Await] } set ClassElementName[?Yield, ?Await] ( PropertySetParameterList ) { FunctionBody[~Yield, ~Await] } PropertySetParameterList : FormalParameter[~Yield, ~Await]

15.4.1 Static Semantics: Early Errors

MethodDefinition : ClassElementName ( UniqueFormalParameters ) { FunctionBody } MethodDefinition : set ClassElementName ( PropertySetParameterList ) { FunctionBody }

15.4.2 Static Semantics: HasDirectSuper

The syntax-directed operation HasDirectSuper takes no arguments and returns a Boolean. It is defined piecewise over the following productions:

MethodDefinition : ClassElementName ( UniqueFormalParameters ) { FunctionBody }
  1. UniqueFormalParameters Contains SuperCalltrue이면, true를 반환한다.
  2. FunctionBody Contains SuperCall을 반환한다.
MethodDefinition : get ClassElementName ( ) { FunctionBody }
  1. FunctionBody Contains SuperCall을 반환한다.
MethodDefinition : set ClassElementName ( PropertySetParameterList ) { FunctionBody }
  1. PropertySetParameterList Contains SuperCalltrue이면, true를 반환한다.
  2. FunctionBody Contains SuperCall을 반환한다.
GeneratorMethod : * ClassElementName ( UniqueFormalParameters ) { GeneratorBody }
  1. UniqueFormalParameters Contains SuperCalltrue이면, true를 반환한다.
  2. GeneratorBody Contains SuperCall을 반환한다.
AsyncGeneratorMethod : async * ClassElementName ( UniqueFormalParameters ) { AsyncGeneratorBody }
  1. UniqueFormalParameters Contains SuperCalltrue이면, true를 반환한다.
  2. AsyncGeneratorBody Contains SuperCall을 반환한다.
AsyncMethod : async ClassElementName ( UniqueFormalParameters ) { AsyncFunctionBody }
  1. UniqueFormalParameters Contains SuperCalltrue이면, true를 반환한다.
  2. AsyncFunctionBody Contains SuperCall을 반환한다.

15.4.3 Static Semantics: SpecialMethod

The syntax-directed operation SpecialMethod takes no arguments and returns a Boolean. It is defined piecewise over the following productions:

MethodDefinition : ClassElementName ( UniqueFormalParameters ) { FunctionBody }
  1. false를 반환한다.
MethodDefinition : GeneratorMethod AsyncMethod AsyncGeneratorMethod get ClassElementName ( ) { FunctionBody } set ClassElementName ( PropertySetParameterList ) { FunctionBody }
  1. true를 반환한다.

15.4.4 Runtime Semantics: DefineMethod

The syntax-directed operation DefineMethod takes argument obj (an Object) and optional argument proto (an Object) and returns either a normal completion containing a Record with fields [[Key]] (a property key) and [[Closure]] (an ECMAScript function object) or an abrupt completion. It is defined piecewise over the following productions:

MethodDefinition : ClassElementName ( UniqueFormalParameters ) { FunctionBody }
  1. propertyKeyClassElementNameEvaluation으로 ? 둔다.
  2. envRecordrunning execution context의 LexicalEnvironment로 둔다.
  3. privateEnvrunning execution context의 PrivateEnvironment로 둔다.
  4. proto가 present하지 않으면, proto%Function.prototype%으로 설정한다.
  5. sourceTextMethodDefinition에 matched된 source text로 둔다.
  6. closureOrdinaryFunctionCreate(proto, sourceText, UniqueFormalParameters, FunctionBody, non-lexical-this, envRecord, privateEnv)로 둔다.
  7. MakeMethod(closure, obj)를 수행한다.
  8. Record { [[Key]]: propertyKey, [[Closure]]: closure }를 반환한다.

15.4.5 Runtime Semantics: MethodDefinitionEvaluation

The syntax-directed operation MethodDefinitionEvaluation takes arguments obj (an Object) and enumerable (a Boolean) and returns either a normal completion containing either a PrivateElement or unused, or an abrupt completion. It is defined piecewise over the following productions:

MethodDefinition : ClassElementName ( UniqueFormalParameters ) { FunctionBody }
  1. methodDef를 argument obj를 가진 MethodDefinitionDefineMethod로 ? 둔다.
  2. SetFunctionName(methodDef.[[Closure]], methodDef.[[Key]])을 수행한다.
  3. DefineMethodProperty(obj, methodDef.[[Key]], methodDef.[[Closure]], enumerable)를 반환한다.
MethodDefinition : get ClassElementName ( ) { FunctionBody }
  1. propertyKeyClassElementNameEvaluation으로 ? 둔다.
  2. envRecordrunning execution context의 LexicalEnvironment로 둔다.
  3. privateEnvrunning execution context의 PrivateEnvironment로 둔다.
  4. sourceTextMethodDefinition에 matched된 source text로 둔다.
  5. formalParamList를 production FormalParameters : [empty] 의 instance로 둔다.
  6. closureOrdinaryFunctionCreate(%Function.prototype%, sourceText, formalParamList, FunctionBody, non-lexical-this, envRecord, privateEnv)로 둔다.
  7. MakeMethod(closure, obj)를 수행한다.
  8. SetFunctionName(closure, propertyKey, "get")을 수행한다.
  9. propertyKeyPrivate Name이면, 다음을 수행한다.
    1. PrivateElement { [[Key]]: propertyKey, [[Kind]]: accessor, [[Get]]: closure, [[Set]]: undefined }를 반환한다.
  10. propertyDesc를 PropertyDescriptor { [[Get]]: closure, [[Enumerable]]: enumerable, [[Configurable]]: true }로 둔다.
  11. DefinePropertyOrThrow(obj, propertyKey, propertyDesc)를 수행한다.
  12. unused를 반환한다.
MethodDefinition : set ClassElementName ( PropertySetParameterList ) { FunctionBody }
  1. propertyKeyClassElementNameEvaluation으로 ? 둔다.
  2. envRecordrunning execution context의 LexicalEnvironment로 둔다.
  3. privateEnvrunning execution context의 PrivateEnvironment로 둔다.
  4. sourceTextMethodDefinition에 matched된 source text로 둔다.
  5. closureOrdinaryFunctionCreate(%Function.prototype%, sourceText, PropertySetParameterList, FunctionBody, non-lexical-this, envRecord, privateEnv)로 둔다.
  6. MakeMethod(closure, obj)를 수행한다.
  7. SetFunctionName(closure, propertyKey, "set")을 수행한다.
  8. propertyKeyPrivate Name이면, 다음을 수행한다.
    1. PrivateElement { [[Key]]: propertyKey, [[Kind]]: accessor, [[Get]]: undefined, [[Set]]: closure }를 반환한다.
  9. propertyDesc를 PropertyDescriptor { [[Set]]: closure, [[Enumerable]]: enumerable, [[Configurable]]: true }로 둔다.
  10. DefinePropertyOrThrow(obj, propertyKey, propertyDesc)를 수행한다.
  11. unused를 반환한다.
GeneratorMethod : * ClassElementName ( UniqueFormalParameters ) { GeneratorBody }
  1. propertyKeyClassElementNameEvaluation으로 ? 둔다.
  2. envRecordrunning execution context의 LexicalEnvironment로 둔다.
  3. privateEnvrunning execution context의 PrivateEnvironment로 둔다.
  4. sourceTextGeneratorMethod에 matched된 source text로 둔다.
  5. closureOrdinaryFunctionCreate(%GeneratorFunction.prototype%, sourceText, UniqueFormalParameters, GeneratorBody, non-lexical-this, envRecord, privateEnv)로 둔다.
  6. MakeMethod(closure, obj)를 수행한다.
  7. SetFunctionName(closure, propertyKey)을 수행한다.
  8. protoOrdinaryObjectCreate(%GeneratorPrototype%)로 둔다.
  9. DefinePropertyOrThrow(closure, "prototype", PropertyDescriptor { [[Value]]: proto, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false })를 수행한다.
  10. DefineMethodProperty(obj, propertyKey, closure, enumerable)를 반환한다.
AsyncGeneratorMethod : async * ClassElementName ( UniqueFormalParameters ) { AsyncGeneratorBody }
  1. propertyKeyClassElementNameEvaluation으로 ? 둔다.
  2. envRecordrunning execution context의 LexicalEnvironment로 둔다.
  3. privateEnvrunning execution context의 PrivateEnvironment로 둔다.
  4. sourceTextAsyncGeneratorMethod에 matched된 source text로 둔다.
  5. closureOrdinaryFunctionCreate(%AsyncGeneratorFunction.prototype%, sourceText, UniqueFormalParameters, AsyncGeneratorBody, non-lexical-this, envRecord, privateEnv)로 둔다.
  6. MakeMethod(closure, obj)를 수행한다.
  7. SetFunctionName(closure, propertyKey)을 수행한다.
  8. protoOrdinaryObjectCreate(%AsyncGeneratorPrototype%)로 둔다.
  9. DefinePropertyOrThrow(closure, "prototype", PropertyDescriptor { [[Value]]: proto, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false })를 수행한다.
  10. DefineMethodProperty(obj, propertyKey, closure, enumerable)를 반환한다.
AsyncMethod : async ClassElementName ( UniqueFormalParameters ) { AsyncFunctionBody }
  1. propertyKeyClassElementNameEvaluation으로 ? 둔다.
  2. envRecordrunning execution context의 LexicalEnvironment로 둔다.
  3. privateEnvrunning execution context의 PrivateEnvironment로 둔다.
  4. sourceTextAsyncMethod에 matched된 source text로 둔다.
  5. closureOrdinaryFunctionCreate(%AsyncFunction.prototype%, sourceText, UniqueFormalParameters, AsyncFunctionBody, non-lexical-this, envRecord, privateEnv)로 둔다.
  6. MakeMethod(closure, obj)를 수행한다.
  7. SetFunctionName(closure, propertyKey)을 수행한다.
  8. DefineMethodProperty(obj, propertyKey, closure, enumerable)를 반환한다.

15.5 Generator Function Definitions

Syntax

GeneratorDeclaration[Yield, Await, Default] : function * BindingIdentifier[?Yield, ?Await] ( FormalParameters[+Yield, ~Await] ) { GeneratorBody } [+Default] function * ( FormalParameters[+Yield, ~Await] ) { GeneratorBody } GeneratorExpression : function * BindingIdentifier[+Yield, ~Await]opt ( FormalParameters[+Yield, ~Await] ) { GeneratorBody } GeneratorMethod[Yield, Await] : * ClassElementName[?Yield, ?Await] ( UniqueFormalParameters[+Yield, ~Await] ) { GeneratorBody } GeneratorBody : FunctionBody[+Yield, ~Await] YieldExpression[In, Await] : yield yield [no LineTerminator here] AssignmentExpression[?In, +Yield, ?Await] yield [no LineTerminator here] * AssignmentExpression[?In, +Yield, ?Await] Note 1

yield 바로 뒤의 syntactic context는 InputElementRegExpOrTemplateTail lexical goal의 use를 require합니다.

Note 2

YieldExpression은 generator function의 FormalParameters 안에서 사용할 수 없습니다. 왜냐하면 FormalParameters의 part인 모든 expression은 resulting Generator가 resumable state에 있기 전에 evaluated되기 때문입니다.

Note 3

Generator와 관련된 abstract operation은 27.8.3에 defined되어 있습니다.

15.5.1 Static Semantics: Early Errors

GeneratorMethod : * ClassElementName ( UniqueFormalParameters ) { GeneratorBody } GeneratorDeclaration : function * BindingIdentifier ( FormalParameters ) { GeneratorBody } function * ( FormalParameters ) { GeneratorBody } GeneratorExpression : function * BindingIdentifieropt ( FormalParameters ) { GeneratorBody }

15.5.2 Runtime Semantics: EvaluateGeneratorBody

The syntax-directed operation EvaluateGeneratorBody takes arguments funcObj (an ECMAScript function object) and argList (a List of ECMAScript language values) and returns a throw completion or a return completion. It is defined piecewise over the following productions:

GeneratorBody : FunctionBody
  1. FunctionDeclarationInstantiation(funcObj, argList)를 수행한다.
  2. gen을 ? OrdinaryCreateFromConstructor(funcObj, "%GeneratorPrototype%", « [[GeneratorState]], [[GeneratorContext]], [[GeneratorBrand]] »)로 둔다.
  3. gen.[[GeneratorBrand]]empty로 설정한다.
  4. gen.[[GeneratorState]]suspended-start로 설정한다.
  5. GeneratorStart(gen, FunctionBody)를 수행한다.
  6. ReturnCompletion(gen)을 반환한다.

15.5.3 Runtime Semantics: InstantiateGeneratorFunctionObject

The syntax-directed operation InstantiateGeneratorFunctionObject takes arguments envRecord (an Environment Record) and privateEnv (a PrivateEnvironment Record or null) and returns an ECMAScript function object. It is defined piecewise over the following productions:

GeneratorDeclaration : function * BindingIdentifier ( FormalParameters ) { GeneratorBody }
  1. nameBindingIdentifierStringValue로 둔다.
  2. sourceTextGeneratorDeclaration에 matched된 source text로 둔다.
  3. closureOrdinaryFunctionCreate(%GeneratorFunction.prototype%, sourceText, FormalParameters, GeneratorBody, non-lexical-this, envRecord, privateEnv)로 둔다.
  4. SetFunctionName(closure, name)을 수행한다.
  5. protoOrdinaryObjectCreate(%GeneratorPrototype%)로 둔다.
  6. DefinePropertyOrThrow(closure, "prototype", PropertyDescriptor { [[Value]]: proto, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false })를 수행한다.
  7. closure를 반환한다.
GeneratorDeclaration : function * ( FormalParameters ) { GeneratorBody }
  1. sourceTextGeneratorDeclaration에 matched된 source text로 둔다.
  2. closureOrdinaryFunctionCreate(%GeneratorFunction.prototype%, sourceText, FormalParameters, GeneratorBody, non-lexical-this, envRecord, privateEnv)로 둔다.
  3. SetFunctionName(closure, "default")를 수행한다.
  4. protoOrdinaryObjectCreate(%GeneratorPrototype%)로 둔다.
  5. DefinePropertyOrThrow(closure, "prototype", PropertyDescriptor { [[Value]]: proto, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false })를 수행한다.
  6. closure를 반환한다.
Note

anonymous GeneratorDeclarationexport default declaration의 part로만 occur할 수 있으므로, 그 function code는 따라서 항상 strict mode code입니다.

15.5.4 Runtime Semantics: InstantiateGeneratorFunctionExpression

The syntax-directed operation InstantiateGeneratorFunctionExpression takes optional argument name (a property key or a Private Name) and returns an ECMAScript function object. It is defined piecewise over the following productions:

GeneratorExpression : function * ( FormalParameters ) { GeneratorBody }
  1. name이 present하지 않으면, name을 empty String으로 설정한다.
  2. envRecordrunning execution context의 LexicalEnvironment로 둔다.
  3. privateEnvrunning execution context의 PrivateEnvironment로 둔다.
  4. sourceTextGeneratorExpression에 matched된 source text로 둔다.
  5. closureOrdinaryFunctionCreate(%GeneratorFunction.prototype%, sourceText, FormalParameters, GeneratorBody, non-lexical-this, envRecord, privateEnv)로 둔다.
  6. SetFunctionName(closure, name)을 수행한다.
  7. protoOrdinaryObjectCreate(%GeneratorPrototype%)로 둔다.
  8. DefinePropertyOrThrow(closure, "prototype", PropertyDescriptor { [[Value]]: proto, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false })를 수행한다.
  9. closure를 반환한다.
GeneratorExpression : function * BindingIdentifier ( FormalParameters ) { GeneratorBody }
  1. Assert: name은 present하지 않는다.
  2. nameBindingIdentifierStringValue로 설정한다.
  3. outerEnvrunning execution context의 LexicalEnvironment로 둔다.
  4. funcEnvNewDeclarativeEnvironment(outerEnv)로 둔다.
  5. funcEnv.CreateImmutableBinding(name, false)를 수행한다.
  6. privateEnvrunning execution context의 PrivateEnvironment로 둔다.
  7. sourceTextGeneratorExpression에 matched된 source text로 둔다.
  8. closureOrdinaryFunctionCreate(%GeneratorFunction.prototype%, sourceText, FormalParameters, GeneratorBody, non-lexical-this, funcEnv, privateEnv)로 둔다.
  9. SetFunctionName(closure, name)을 수행한다.
  10. protoOrdinaryObjectCreate(%GeneratorPrototype%)로 둔다.
  11. DefinePropertyOrThrow(closure, "prototype", PropertyDescriptor { [[Value]]: proto, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false })를 수행한다.
  12. funcEnv.InitializeBinding(name, closure)를 수행한다.
  13. closure를 반환한다.
Note

GeneratorExpression 안의 BindingIdentifier는 generator code가 recursively 자신을 call할 수 있도록 GeneratorExpressionFunctionBody 내부에서 referenced될 수 있습니다. 그러나 GeneratorDeclaration과 달리 GeneratorExpression 안의 BindingIdentifierGeneratorExpression을 enclosing하는 scope에서 referenced될 수 없고 그 scope에 affect하지 않습니다.

15.5.5 Runtime Semantics: Evaluation

GeneratorExpression : function * BindingIdentifieropt ( FormalParameters ) { GeneratorBody }
  1. GeneratorExpressionInstantiateGeneratorFunctionExpression을 반환한다.
YieldExpression : yield
  1. Yield(undefined)를 반환한다.
YieldExpression : yield AssignmentExpression
  1. exprRefAssignmentExpressionEvaluation으로 ? 둔다.
  2. value를 ? GetValue(exprRef)로 둔다.
  3. Yield(value)를 반환한다.
YieldExpression : yield * AssignmentExpression
  1. genKindGetGeneratorKind()로 둔다.
  2. Assert: genKindsync 또는 async 중 하나이다.
  3. exprRefAssignmentExpressionEvaluation으로 ? 둔다.
  4. value를 ? GetValue(exprRef)로 둔다.
  5. iteratorRecord를 ? GetIterator(value, genKind)로 둔다.
  6. iteratoriteratorRecord.[[Iterator]]로 둔다.
  7. receivedNormalCompletion(undefined)로 둔다.
  8. Repeat,
    1. receivednormal completion이면, 다음을 수행한다.
      1. innerResult를 ? Call(iteratorRecord.[[NextMethod]], iteratorRecord.[[Iterator]], « received.[[Value]] »)로 둔다.
      2. genKindasync이면, innerResult를 ? Await(innerResult)로 설정한다.
      3. innerResult가 Object가 아니면, TypeError exception을 throw한다.
      4. done을 ? IteratorComplete(innerResult)로 둔다.
      5. donetrue이면, 다음을 수행한다.
        1. IteratorValue(innerResult)를 반환한다.
      6. genKindasync이면, receivedCompletion(AsyncGeneratorYield(? IteratorValue(innerResult)))로 설정한다.
      7. 그렇지 않으면, receivedCompletion(GeneratorYield(innerResult))로 설정한다.
    2. 그렇지 않고 receivedthrow completion이면, 다음을 수행한다.
      1. throw를 ? GetMethod(iterator, "throw")로 둔다.
      2. throwundefined가 아니면, 다음을 수행한다.
        1. innerResult를 ? Call(throw, iterator, « received.[[Value]] »)로 둔다.
        2. genKindasync이면, innerResult를 ? Await(innerResult)로 설정한다.
        3. NOTE: inner iterator throw method로부터의 exception은 propagated된다. inner throw method로부터의 normal completion은 inner next와 similar하게 processed된다.
        4. innerResult가 Object가 아니면, TypeError exception을 throw한다.
        5. done을 ? IteratorComplete(innerResult)로 둔다.
        6. donetrue이면, 다음을 수행한다.
          1. IteratorValue(innerResult)를 반환한다.
        7. genKindasync이면, receivedCompletion(AsyncGeneratorYield(? IteratorValue(innerResult)))로 설정한다.
        8. 그렇지 않으면, receivedCompletion(GeneratorYield(innerResult))로 설정한다.
      3. 그렇지 않으면,
        1. NOTE: iteratorthrow method를 가지지 않으면, 이 throw는 yield* loop를 terminate할 것이다. 하지만 먼저 iterator에게 cleanup할 chance를 주어야 한다.
        2. closeCompletionNormalCompletion(empty)로 둔다.
        3. genKindasync이면, ? AsyncIteratorClose(iteratorRecord, closeCompletion)를 수행한다.
        4. 그렇지 않으면, ? IteratorClose(iteratorRecord, closeCompletion)를 수행한다.
        5. NOTE: next step은 yield* protocol violation이 있었음을 indicate하기 위해 TypeError를 throw한다: iteratorthrow method를 가지지 않는다.
        6. TypeError exception을 throw한다.
    3. 그렇지 않으면,
      1. Assert: receivedreturn completion이다.
      2. return을 ? GetMethod(iterator, "return")으로 둔다.
      3. returnundefined이면, 다음을 수행한다.
        1. receivedValuereceived.[[Value]]로 둔다.
        2. genKindasync이면, 다음을 수행한다.
          1. receivedValue를 ? Await(receivedValue)로 설정한다.
        3. ReturnCompletion(receivedValue)를 반환한다.
      4. innerReturnResult를 ? Call(return, iterator, « received.[[Value]] »)로 둔다.
      5. genKindasync이면, innerReturnResult를 ? Await(innerReturnResult)로 설정한다.
      6. innerReturnResult가 Object가 아니면, TypeError exception을 throw한다.
      7. done을 ? IteratorComplete(innerReturnResult)로 둔다.
      8. donetrue이면, 다음을 수행한다.
        1. returnedValue를 ? IteratorValue(innerReturnResult)로 둔다.
        2. ReturnCompletion(returnedValue)를 반환한다.
      9. genKindasync이면, receivedCompletion(AsyncGeneratorYield(? IteratorValue(innerReturnResult)))로 설정한다.
      10. 그렇지 않으면, receivedCompletion(GeneratorYield(innerReturnResult))로 설정한다.

15.6 Async Generator Function Definitions

Syntax

AsyncGeneratorDeclaration[Yield, Await, Default] : async [no LineTerminator here] function * BindingIdentifier[?Yield, ?Await] ( FormalParameters[+Yield, +Await] ) { AsyncGeneratorBody } [+Default] async [no LineTerminator here] function * ( FormalParameters[+Yield, +Await] ) { AsyncGeneratorBody } AsyncGeneratorExpression : async [no LineTerminator here] function * BindingIdentifier[+Yield, +Await]opt ( FormalParameters[+Yield, +Await] ) { AsyncGeneratorBody } AsyncGeneratorMethod[Yield, Await] : async [no LineTerminator here] * ClassElementName[?Yield, ?Await] ( UniqueFormalParameters[+Yield, +Await] ) { AsyncGeneratorBody } AsyncGeneratorBody : FunctionBody[+Yield, +Await] Note 1

YieldExpressionAwaitExpression은 async generator function의 FormalParameters 안에서 사용할 수 없습니다. 왜냐하면 FormalParameters의 part인 모든 expression은 resulting AsyncGenerator가 resumable state에 있기 전에 evaluated되기 때문입니다.

Note 2

AsyncGenerator와 관련된 abstract operation은 27.9.3에 defined되어 있습니다.

15.6.1 Static Semantics: Early Errors

AsyncGeneratorMethod : async * ClassElementName ( UniqueFormalParameters ) { AsyncGeneratorBody } AsyncGeneratorDeclaration : async function * BindingIdentifier ( FormalParameters ) { AsyncGeneratorBody } async function * ( FormalParameters ) { AsyncGeneratorBody } AsyncGeneratorExpression : async function * BindingIdentifieropt ( FormalParameters ) { AsyncGeneratorBody }

15.6.2 Runtime Semantics: EvaluateAsyncGeneratorBody

The syntax-directed operation EvaluateAsyncGeneratorBody takes arguments funcObj (an ECMAScript function object) and argList (a List of ECMAScript language values) and returns a throw completion or a return completion. It is defined piecewise over the following productions:

AsyncGeneratorBody : FunctionBody
  1. FunctionDeclarationInstantiation(funcObj, argList)를 수행한다.
  2. gen을 ? OrdinaryCreateFromConstructor(funcObj, "%AsyncGeneratorPrototype%", « [[AsyncGeneratorState]], [[AsyncGeneratorContext]], [[AsyncGeneratorQueue]], [[GeneratorBrand]] »)로 둔다.
  3. gen.[[GeneratorBrand]]empty로 설정한다.
  4. gen.[[AsyncGeneratorState]]suspended-start로 설정한다.
  5. AsyncGeneratorStart(gen, FunctionBody)를 수행한다.
  6. ReturnCompletion(gen)을 반환한다.

15.6.3 Runtime Semantics: InstantiateAsyncGeneratorFunctionObject

The syntax-directed operation InstantiateAsyncGeneratorFunctionObject takes arguments envRecord (an Environment Record) and privateEnv (a PrivateEnvironment Record or null) and returns an ECMAScript function object. It is defined piecewise over the following productions:

AsyncGeneratorDeclaration : async function * BindingIdentifier ( FormalParameters ) { AsyncGeneratorBody }
  1. nameBindingIdentifierStringValue로 둔다.
  2. sourceTextAsyncGeneratorDeclaration에 matched된 source text로 둔다.
  3. closureOrdinaryFunctionCreate(%AsyncGeneratorFunction.prototype%, sourceText, FormalParameters, AsyncGeneratorBody, non-lexical-this, envRecord, privateEnv)로 둔다.
  4. SetFunctionName(closure, name)을 수행한다.
  5. protoOrdinaryObjectCreate(%AsyncGeneratorPrototype%)로 둔다.
  6. DefinePropertyOrThrow(closure, "prototype", PropertyDescriptor { [[Value]]: proto, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false })를 수행한다.
  7. closure를 반환한다.
AsyncGeneratorDeclaration : async function * ( FormalParameters ) { AsyncGeneratorBody }
  1. sourceTextAsyncGeneratorDeclaration에 matched된 source text로 둔다.
  2. closureOrdinaryFunctionCreate(%AsyncGeneratorFunction.prototype%, sourceText, FormalParameters, AsyncGeneratorBody, non-lexical-this, envRecord, privateEnv)로 둔다.
  3. SetFunctionName(closure, "default")를 수행한다.
  4. protoOrdinaryObjectCreate(%AsyncGeneratorPrototype%)로 둔다.
  5. DefinePropertyOrThrow(closure, "prototype", PropertyDescriptor { [[Value]]: proto, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false })를 수행한다.
  6. closure를 반환한다.
Note

anonymous AsyncGeneratorDeclarationexport default declaration의 part로만 occur할 수 있습니다.

15.6.4 Runtime Semantics: InstantiateAsyncGeneratorFunctionExpression

The syntax-directed operation InstantiateAsyncGeneratorFunctionExpression takes optional argument name (a property key or a Private Name) and returns an ECMAScript function object. It is defined piecewise over the following productions:

AsyncGeneratorExpression : async function * ( FormalParameters ) { AsyncGeneratorBody }
  1. name이 present하지 않으면, name을 empty String으로 설정한다.
  2. envRecordrunning execution context의 LexicalEnvironment로 둔다.
  3. privateEnvrunning execution context의 PrivateEnvironment로 둔다.
  4. sourceTextAsyncGeneratorExpression에 matched된 source text로 둔다.
  5. closureOrdinaryFunctionCreate(%AsyncGeneratorFunction.prototype%, sourceText, FormalParameters, AsyncGeneratorBody, non-lexical-this, envRecord, privateEnv)로 둔다.
  6. SetFunctionName(closure, name)을 수행한다.
  7. protoOrdinaryObjectCreate(%AsyncGeneratorPrototype%)로 둔다.
  8. DefinePropertyOrThrow(closure, "prototype", PropertyDescriptor { [[Value]]: proto, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false })를 수행한다.
  9. closure를 반환한다.
AsyncGeneratorExpression : async function * BindingIdentifier ( FormalParameters ) { AsyncGeneratorBody }
  1. Assert: name은 present하지 않는다.
  2. nameBindingIdentifierStringValue로 설정한다.
  3. outerEnvrunning execution context의 LexicalEnvironment로 둔다.
  4. funcEnvNewDeclarativeEnvironment(outerEnv)로 둔다.
  5. funcEnv.CreateImmutableBinding(name, false)를 수행한다.
  6. privateEnvrunning execution context의 PrivateEnvironment로 둔다.
  7. sourceTextAsyncGeneratorExpression에 matched된 source text로 둔다.
  8. closureOrdinaryFunctionCreate(%AsyncGeneratorFunction.prototype%, sourceText, FormalParameters, AsyncGeneratorBody, non-lexical-this, funcEnv, privateEnv)로 둔다.
  9. SetFunctionName(closure, name)을 수행한다.
  10. protoOrdinaryObjectCreate(%AsyncGeneratorPrototype%)로 둔다.
  11. DefinePropertyOrThrow(closure, "prototype", PropertyDescriptor { [[Value]]: proto, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false })를 수행한다.
  12. funcEnv.InitializeBinding(name, closure)를 수행한다.
  13. closure를 반환한다.
Note

AsyncGeneratorExpression 안의 BindingIdentifier는 generator code가 recursively 자신을 call할 수 있도록 AsyncGeneratorExpressionAsyncGeneratorBody 내부에서 referenced될 수 있습니다. 그러나 AsyncGeneratorDeclaration과 달리 AsyncGeneratorExpression 안의 BindingIdentifierAsyncGeneratorExpression을 enclosing하는 scope에서 referenced될 수 없고 그 scope에 affect하지 않습니다.

15.6.5 Runtime Semantics: Evaluation

AsyncGeneratorExpression : async function * BindingIdentifieropt ( FormalParameters ) { AsyncGeneratorBody }
  1. AsyncGeneratorExpressionInstantiateAsyncGeneratorFunctionExpression을 반환한다.

15.7 Class Definitions

Syntax

ClassDeclaration[Yield, Await, Default] : class BindingIdentifier[?Yield, ?Await] ClassTail[?Yield, ?Await] [+Default] class ClassTail[?Yield, ?Await] ClassExpression[Yield, Await] : class BindingIdentifier[?Yield, ?Await]opt ClassTail[?Yield, ?Await] ClassTail[Yield, Await] : ClassHeritage[?Yield, ?Await]opt { ClassBody[?Yield, ?Await]opt } ClassHeritage[Yield, Await] : extends LeftHandSideExpression[?Yield, ?Await] ClassBody[Yield, Await] : ClassElementList[?Yield, ?Await] ClassElementList[Yield, Await] : ClassElement[?Yield, ?Await] ClassElementList[?Yield, ?Await] ClassElement[?Yield, ?Await] ClassElement[Yield, Await] : MethodDefinition[?Yield, ?Await] static MethodDefinition[?Yield, ?Await] FieldDefinition[?Yield, ?Await] ; static FieldDefinition[?Yield, ?Await] ; ClassStaticBlock ; FieldDefinition[Yield, Await] : ClassElementName[?Yield, ?Await] Initializer[+In, ?Yield, ?Await]opt ClassElementName[Yield, Await] : PropertyName[?Yield, ?Await] PrivateIdentifier ClassStaticBlock : static { ClassStaticBlockBody } ClassStaticBlockBody : ClassStaticBlockStatementList ClassStaticBlockStatementList : StatementList[~Yield, +Await, ~Return]opt Note

class definition은 항상 strict mode code입니다.

15.7.1 Static Semantics: Early Errors

ClassTail : ClassHeritageopt { ClassBody } ClassBody : ClassElementList
  • ClassElementListPrototypePropertyNameList"constructor"의 occurrence를 둘 이상 contain하면 Syntax Error입니다.
  • ClassElementListPrivateBoundIdentifiers가 duplicate entry를 contain하면 Syntax Error입니다. 단, name이 getter에 한 번, setter에 한 번 사용되고 다른 entry에는 사용되지 않으며, getter와 setter가 둘 다 static이거나 둘 다 non-static인 경우는 예외입니다.
ClassElement : MethodDefinition ClassElement : static MethodDefinition ClassElement : FieldDefinition ; ClassElement : static FieldDefinition ; FieldDefinition : ClassElementName Initializeropt ClassElementName : PrivateIdentifier ClassStaticBlockBody : ClassStaticBlockStatementList

15.7.2 Static Semantics: ClassElementKind

The syntax-directed operation ClassElementKind takes no arguments and returns constructor-method, non-constructor-method, or empty. It is defined piecewise over the following productions:

ClassElement : MethodDefinition
  1. MethodDefinitionPropName"constructor"이면, constructor-method를 반환한다.
  2. non-constructor-method를 반환한다.
ClassElement : static MethodDefinition FieldDefinition ; static FieldDefinition ;
  1. non-constructor-method를 반환한다.
ClassElement : ClassStaticBlock
  1. non-constructor-method를 반환한다.
ClassElement : ;
  1. empty를 반환한다.

15.7.3 Static Semantics: ConstructorMethod

The syntax-directed operation ConstructorMethod takes no arguments and returns a ClassElement Parse Node or empty. It is defined piecewise over the following productions:

ClassElementList : ClassElement
  1. ClassElementClassElementKindconstructor-method이면, ClassElement를 반환한다.
  2. empty를 반환한다.
ClassElementList : ClassElementList ClassElement
  1. headClassElementListConstructorMethod로 둔다.
  2. headempty가 아니면, head를 반환한다.
  3. ClassElementClassElementKindconstructor-method이면, ClassElement를 반환한다.
  4. empty를 반환한다.
Note

Early Error rule은 "constructor"라는 name의 method definition이 하나만 있고 그것이 accessor property 또는 generator definition이 아님을 ensure합니다.

15.7.4 Static Semantics: IsStatic

The syntax-directed operation IsStatic takes no arguments and returns a Boolean. It is defined piecewise over the following productions:

ClassElement : MethodDefinition
  1. false를 반환한다.
ClassElement : static MethodDefinition
  1. true를 반환한다.
ClassElement : FieldDefinition ;
  1. false를 반환한다.
ClassElement : static FieldDefinition ;
  1. true를 반환한다.
ClassElement : ClassStaticBlock
  1. true를 반환한다.
ClassElement : ;
  1. false를 반환한다.

15.7.5 Static Semantics: NonConstructorElements

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

ClassElementList : ClassElement
  1. ClassElementClassElementKindnon-constructor-method이면, 다음을 수행한다.
    1. « ClassElement »를 반환한다.
  2. 새 empty List를 반환한다.
ClassElementList : ClassElementList ClassElement
  1. listClassElementListNonConstructorElements로 둔다.
  2. ClassElementClassElementKindnon-constructor-method이면, 다음을 수행한다.
    1. ClassElementlist에 append한다.
  3. list를 반환한다.

15.7.6 Static Semantics: PrototypePropertyNameList

The syntax-directed operation PrototypePropertyNameList takes no arguments and returns a List of property keys. It is defined piecewise over the following productions:

ClassElementList : ClassElement
  1. propertyNameClassElementPropName으로 둔다.
  2. propertyNameempty이면, 새 empty List를 반환한다.
  3. ClassElementIsStatictrue이면, 새 empty List를 반환한다.
  4. « propertyName »를 반환한다.
ClassElementList : ClassElementList ClassElement
  1. listClassElementListPrototypePropertyNameList로 둔다.
  2. propertyNameClassElementPropName으로 둔다.
  3. propertyNameempty이면, list를 반환한다.
  4. ClassElementIsStatictrue이면, list를 반환한다.
  5. list와 « propertyName »의 list-concatenation을 반환한다.

15.7.7 Static Semantics: AllPrivateIdentifiersValid

The syntax-directed operation AllPrivateIdentifiersValid takes argument names (a List of Strings) and returns a Boolean.

이 명세에서 아래에 listed되지 않은 모든 grammar production alternative는 암묵적으로 AllPrivateIdentifiersValid에 대해 다음 default definition을 가집니다:

  1. Parse Node의 각 child node child에 대해, 다음을 수행한다.
    1. child가 nonterminal의 instance이면, 다음을 수행한다.
      1. argument names를 가진 childAllPrivateIdentifiersValidfalse이면, false를 반환한다.
  2. true를 반환한다.
MemberExpression : MemberExpression . PrivateIdentifier
  1. namesPrivateIdentifierStringValue를 contain하면, 다음을 수행한다.
    1. argument names를 가진 MemberExpressionAllPrivateIdentifiersValid를 반환한다.
  2. false를 반환한다.
CallExpression : CallExpression . PrivateIdentifier
  1. namesPrivateIdentifierStringValue를 contain하면, 다음을 수행한다.
    1. argument names를 가진 CallExpressionAllPrivateIdentifiersValid를 반환한다.
  2. false를 반환한다.
OptionalChain : ?. PrivateIdentifier
  1. namesPrivateIdentifierStringValue를 contain하면, true를 반환한다.
  2. false를 반환한다.
OptionalChain : OptionalChain . PrivateIdentifier
  1. namesPrivateIdentifierStringValue를 contain하면, 다음을 수행한다.
    1. argument names를 가진 OptionalChainAllPrivateIdentifiersValid를 반환한다.
  2. false를 반환한다.
ClassBody : ClassElementList
  1. newNamesnamesClassBodyPrivateBoundIdentifierslist-concatenation으로 둔다.
  2. argument newNames를 가진 ClassElementListAllPrivateIdentifiersValid를 반환한다.
RelationalExpression : PrivateIdentifier in ShiftExpression
  1. namesPrivateIdentifierStringValue를 contain하면, 다음을 수행한다.
    1. argument names를 가진 ShiftExpressionAllPrivateIdentifiersValid를 반환한다.
  2. false를 반환한다.

15.7.8 Static Semantics: PrivateBoundIdentifiers

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

FieldDefinition : ClassElementName Initializeropt
  1. ClassElementNamePrivateBoundIdentifiers를 반환한다.
ClassElementName : PrivateIdentifier
  1. sole element가 PrivateIdentifierStringValueList를 반환한다.
ClassElementName : PropertyName ClassElement : ClassStaticBlock ;
  1. 새 empty List를 반환한다.
ClassElementList : ClassElementList ClassElement
  1. names1ClassElementListPrivateBoundIdentifiers로 둔다.
  2. names2ClassElementPrivateBoundIdentifiers로 둔다.
  3. names1names2list-concatenation을 반환한다.
MethodDefinition : ClassElementName ( UniqueFormalParameters ) { FunctionBody } get ClassElementName ( ) { FunctionBody } set ClassElementName ( PropertySetParameterList ) { FunctionBody } GeneratorMethod : * ClassElementName ( UniqueFormalParameters ) { GeneratorBody } AsyncMethod : async ClassElementName ( UniqueFormalParameters ) { AsyncFunctionBody } AsyncGeneratorMethod : async * ClassElementName ( UniqueFormalParameters ) { AsyncGeneratorBody }
  1. ClassElementNamePrivateBoundIdentifiers를 반환한다.

15.7.9 Static Semantics: ContainsArguments

The syntax-directed operation ContainsArguments takes no arguments and returns a Boolean.

이 명세에서 아래에 listed되지 않은 모든 grammar production alternative는 암묵적으로 ContainsArguments에 대해 다음 default definition을 가집니다:

  1. Parse Node의 각 child node child에 대해, 다음을 수행한다.
    1. child가 nonterminal의 instance이면, 다음을 수행한다.
      1. childContainsArgumentstrue이면, true를 반환한다.
  2. false를 반환한다.
IdentifierReference : Identifier
  1. IdentifierStringValue"arguments"이면, true를 반환한다.
  2. false를 반환한다.
FunctionDeclaration : function BindingIdentifier ( FormalParameters ) { FunctionBody } function ( FormalParameters ) { FunctionBody } FunctionExpression : function BindingIdentifieropt ( FormalParameters ) { FunctionBody } GeneratorDeclaration : function * BindingIdentifier ( FormalParameters ) { GeneratorBody } function * ( FormalParameters ) { GeneratorBody } GeneratorExpression : function * BindingIdentifieropt ( FormalParameters ) { GeneratorBody } AsyncGeneratorDeclaration : async function * BindingIdentifier ( FormalParameters ) { AsyncGeneratorBody } async function * ( FormalParameters ) { AsyncGeneratorBody } AsyncGeneratorExpression : async function * BindingIdentifieropt ( FormalParameters ) { AsyncGeneratorBody } AsyncFunctionDeclaration : async function BindingIdentifier ( FormalParameters ) { AsyncFunctionBody } async function ( FormalParameters ) { AsyncFunctionBody } AsyncFunctionExpression : async function BindingIdentifieropt ( FormalParameters ) { AsyncFunctionBody }
  1. false를 반환한다.
MethodDefinition : ClassElementName ( UniqueFormalParameters ) { FunctionBody } get ClassElementName ( ) { FunctionBody } set ClassElementName ( PropertySetParameterList ) { FunctionBody } GeneratorMethod : * ClassElementName ( UniqueFormalParameters ) { GeneratorBody } AsyncGeneratorMethod : async * ClassElementName ( UniqueFormalParameters ) { AsyncGeneratorBody } AsyncMethod : async ClassElementName ( UniqueFormalParameters ) { AsyncFunctionBody }
  1. ClassElementNameContainsArguments를 반환한다.

15.7.10 Runtime Semantics: ClassFieldDefinitionEvaluation

The syntax-directed operation ClassFieldDefinitionEvaluation takes argument homeObj (an Object) and returns either a normal completion containing a ClassFieldDefinition Record or an abrupt completion. It is defined piecewise over the following productions:

FieldDefinition : ClassElementName Initializeropt
  1. nameClassElementNameEvaluation으로 ? 둔다.
  2. Initializer가 present하면, 다음을 수행한다.
    1. formalParamList를 production FormalParameters : [empty] 의 instance로 둔다.
    2. envRecordrunning execution context의 LexicalEnvironment로 둔다.
    3. privateEnvrunning execution context의 PrivateEnvironment로 둔다.
    4. sourceText를 Unicode code point의 empty sequence로 둔다.
    5. initializerOrdinaryFunctionCreate(%Function.prototype%, sourceText, formalParamList, Initializer, non-lexical-this, envRecord, privateEnv)로 둔다.
    6. MakeMethod(initializer, homeObj)를 수행한다.
    7. initializer.[[ClassFieldInitializerName]]name으로 설정한다.
  3. 그렇지 않으면,
    1. initializerempty로 둔다.
  4. ClassFieldDefinition Record { [[Name]]: name, [[Initializer]]: initializer }를 반환한다.
Note
initializer를 위해 created된 function은 ECMAScript code에 의해 never directly accessible하지 않습니다.

15.7.11 Runtime Semantics: ClassStaticBlockDefinitionEvaluation

The syntax-directed operation ClassStaticBlockDefinitionEvaluation takes argument homeObj (an Object) and returns a ClassStaticBlockDefinition Record. It is defined piecewise over the following productions:

ClassStaticBlock : static { ClassStaticBlockBody }
  1. lexicalEnv를 실행 중인 실행 컨텍스트의 LexicalEnvironment라고 하자.
  2. privateEnv를 실행 중인 실행 컨텍스트의 PrivateEnvironment라고 하자.
  3. sourceText를 Unicode 코드 포인트의 빈 시퀀스라고 하자.
  4. formalParams를 생성식 FormalParameters : [empty] 의 인스턴스라고 하자.
  5. bodyFuncOrdinaryFunctionCreate(%Function.prototype%, sourceText, formalParams, ClassStaticBlockBody, non-lexical-this, lexicalEnv, privateEnv)라고 하자.
  6. MakeMethod(bodyFunc, homeObj)를 수행한다.
  7. ClassStaticBlockDefinition Record { [[BodyFunction]]: bodyFunc }를 반환한다.
Note
function bodyFunc는 ECMAScript code에 의해 never directly accessible하지 않습니다.

15.7.12 Runtime Semantics: EvaluateClassStaticBlockBody

The syntax-directed operation EvaluateClassStaticBlockBody takes argument funcObj (an ECMAScript function object) and returns a return completion or a throw completion. It is defined piecewise over the following productions:

ClassStaticBlockBody : ClassStaticBlockStatementList
  1. 단언: funcObjClassStaticBlockDefinitionEvaluation 단계 5에서 생성된 합성 함수이다.
  2. FunctionDeclarationInstantiation(funcObj, « »)를 수행한다.
  3. resultClassStaticBlockStatementListEvaluationCompletion으로 둔다.
  4. envRecord를 실행 중인 실행 컨텍스트의 LexicalEnvironment로 둔다.
  5. 단언: envRecordDeclarative Environment Record이다.
  6. DisposeResources(envRecord.[[DisposableResourceStack]], result)를 수행한다.
  7. ReturnCompletion(undefined)을 반환한다.

15.7.13 Runtime Semantics: ClassElementEvaluation

The syntax-directed operation ClassElementEvaluation takes argument obj (an Object) and returns either a normal completion containing either a ClassFieldDefinition Record, a ClassStaticBlockDefinition Record, a PrivateElement, or unused, or an abrupt completion. It is defined piecewise over the following productions:

ClassElement : FieldDefinition ; static FieldDefinition ;
  1. argument obj를 가진 FieldDefinitionClassFieldDefinitionEvaluation을 ? 반환한다.
ClassElement : MethodDefinition static MethodDefinition
  1. arguments objfalse를 가진 MethodDefinitionMethodDefinitionEvaluation을 ? 반환한다.
ClassElement : ClassStaticBlock
  1. argument obj를 가진 ClassStaticBlockClassStaticBlockDefinitionEvaluation을 반환한다.
ClassElement : ;
  1. unused를 반환한다.

15.7.14 Runtime Semantics: ClassDefinitionEvaluation

The syntax-directed operation ClassDefinitionEvaluation takes arguments classBinding (a String or undefined), className (a property key or a Private Name), and sourceText (ECMAScript source text) and returns either a normal completion containing a function object or an abrupt completion.

Note

specification의 ease를 위해, private method와 accessor는 private field와 함께 class instance의 [[PrivateElements]] slot에 included됩니다. 그러나 given object는 given class에 의해 defined된 private method 및 accessor를 모두 가지거나 전혀 가지지 않습니다. 이 feature는 implementation이 각 method 또는 accessor를 individual하게 tracking할 필요가 없는 strategy를 사용하여 private method와 accessor를 implement하도록 choose할 수 있게 designed되었습니다.

예를 들어, implementation은 instance private method를 그 corresponding Private Name과 직접 associate하고, 각 object에 대해 어느 class constructor가 그 object를 this value로 사용하여 run되었는지를 track할 수 있습니다. 그러면 object에서 instance private method를 looking up하는 것은 method를 define하는 class constructor가 object를 initialize하는 데 사용되었는지 checking한 다음, Private Name과 associated된 method를 returning하는 것으로 구성됩니다.

이는 private field와 다릅니다: field initializer는 class instantiation 중에 throw할 수 있으므로, individual object는 given class의 private field의 proper subset만 가질 수 있고, 따라서 private field는 일반적으로 individual하게 tracked되어야 합니다.

It is defined piecewise over the following productions:

ClassTail : ClassHeritageopt { ClassBodyopt }
  1. envRecord를 실행 중인 실행 컨텍스트의 LexicalEnvironment라고 하자.
  2. classEnvNewDeclarativeEnvironment(envRecord)라고 하자.
  3. classBindingundefined가 아니면,
    1. classEnv.CreateImmutableBinding(classBinding, true)를 수행한다.
  4. outerPrivateEnv를 실행 중인 실행 컨텍스트의 PrivateEnvironment라고 하자.
  5. classPrivateEnvNewPrivateEnvironment(outerPrivateEnv)라고 하자.
  6. ClassBody가 있으면,
    1. ClassBodyPrivateBoundIdentifiers의 각 String description에 대해 다음을 수행한다.
      1. classPrivateEnv.[[Names]][[Description]]descriptionPrivate Name privateName을 포함하면,
        1. Assert: 이것은 getter/setter 쌍에 대해서만 가능하다.
      2. 그렇지 않으면,
        1. name[[Description]]description인 새로운 Private Name이라고 하자.
        2. nameclassPrivateEnv.[[Names]]에 추가한다.
  7. ClassHeritage가 없으면,
    1. protoParent%Object.prototype%이라고 하자.
    2. ctorParent%Function.prototype%이라고 하자.
  8. 그렇지 않으면,
    1. 실행 중인 실행 컨텍스트의 LexicalEnvironment를 classEnv로 설정한다.
    2. NOTE: ClassHeritage를 평가할 때 실행 중인 실행 컨텍스트의 PrivateEnvironment는 outerPrivateEnv이다.
    3. superclassRefClassHeritageEvaluationCompletion이라고 하자.
    4. 실행 중인 실행 컨텍스트의 LexicalEnvironment를 envRecord로 설정한다.
    5. superclass를 ? GetValue(? superclassRef)라고 하자.
    6. superclassnull이면,
      1. protoParentnull이라고 하자.
      2. ctorParent%Function.prototype%이라고 하자.
    7. 그렇지 않고 IsConstructor(superclass)가 false이면,
      1. TypeError 예외를 던진다.
    8. 그렇지 않으면,
      1. protoParent를 ? Get(superclass, "prototype")라고 하자.
      2. protoParent가 Object가 아니고 protoParentnull도 아니면, TypeError 예외를 던진다.
      3. ctorParentsuperclass라고 하자.
  9. protoOrdinaryObjectCreate(protoParent)라고 하자.
  10. ClassBody가 없으면 ctorempty라고 하자.
  11. 그렇지 않으면, ctorClassBodyConstructorMethod라고 하자.
  12. 실행 중인 실행 컨텍스트의 LexicalEnvironment를 classEnv로 설정한다.
  13. 실행 중인 실행 컨텍스트의 PrivateEnvironment를 classPrivateEnv로 설정한다.
  14. ctorempty이면,
    1. defaultCtor를 매개변수가 없고 아무것도 캡처하지 않으며 호출될 때 다음 단계를 수행하는 새로운 Abstract Closure라고 하자.
      1. args[[Call]] 또는 [[Construct]]가 이 함수에 전달한 인수의 List라고 하자.
      2. NewTarget이 undefined이면, TypeError 예외를 던진다.
      3. ctorFunc활성 함수 객체라고 하자.
      4. ctorFunc.[[ConstructorKind]]derived이면,
        1. NOTE: 이 분기는 constructor(...args) { super(...args); }와 유사하게 동작한다. 가장 두드러진 차이점은 앞의 ECMAScript 소스 텍스트는 관찰 가능하게 %Array.prototype%%Symbol.iterator% 메서드를 호출하지만, 이 함수는 그렇지 않다는 점이다.
        2. func를 ! ctorFunc.[[GetPrototypeOf]]()라고 하자.
        3. IsConstructor(func)가 false이면, TypeError 예외를 던진다.
        4. result를 ? Construct(func, args, NewTarget)라고 하자.
      5. 그렇지 않으면,
        1. NOTE: 이 분기는 constructor() {}와 유사하게 동작한다.
        2. result를 ? OrdinaryCreateFromConstructor(NewTarget, "%Object.prototype%")라고 하자.
      6. InitializeInstanceElements(result, ctorFunc)를 수행한다.
      7. NormalCompletion(result)를 반환한다.
    2. ctorFuncCreateBuiltinFunction(defaultCtor, 0, className, « [[ConstructorKind]], [[SourceText]], [[PrivateMethods]], [[Fields]] », the current Realm Record, ctorParent)라고 하자.
  15. 그렇지 않으면,
    1. ctorInfoctorDefineMethod에 인수 protoctorParent를 전달한 결과라고 하자.
    2. ctorFuncctorInfo.[[Closure]]라고 하자.
    3. MakeClassConstructor(ctorFunc)를 수행한다.
    4. SetFunctionName(ctorFunc, className)를 수행한다.
  16. ctorFunc.[[SourceText]]sourceText로 설정한다.
  17. MakeConstructor(ctorFunc, false, proto)를 수행한다.
  18. ClassHeritage가 있으면, ctorFunc.[[ConstructorKind]]derived로 설정한다.
  19. DefineMethodProperty(proto, "constructor", ctorFunc, false)를 수행한다.
  20. ClassBody가 없으면 classElements를 새로운 빈 List라고 하자.
  21. 그렇지 않으면, classElementsClassBodyNonConstructorElements라고 하자.
  22. instancePrivateMethods를 새로운 빈 List라고 하자.
  23. staticPrivateMethods를 새로운 빈 List라고 하자.
  24. instanceFields를 새로운 빈 List라고 하자.
  25. staticElements를 새로운 빈 List라고 하자.
  26. classElements의 각 ClassElement classElement에 대해 다음을 수행한다.
    1. classElementIsStaticfalse이면,
      1. element를 인수 proto를 사용한 classElementClassElementEvaluationCompletion이라고 하자.
    2. 그렇지 않으면,
      1. element를 인수 ctorFunc를 사용한 classElementClassElementEvaluationCompletion이라고 하자.
    3. elementabrupt completion이면,
      1. 실행 중인 실행 컨텍스트의 LexicalEnvironment를 envRecord로 설정한다.
      2. 실행 중인 실행 컨텍스트의 PrivateEnvironment를 outerPrivateEnv로 설정한다.
      3. element를 반환한다.
    4. element를 ! element로 설정한다.
    5. elementPrivateElement이면,
      1. Assert: element.[[Kind]]method 또는 accessor 중 하나이다.
      2. classElementIsStaticfalse이면 containerinstancePrivateMethods라고 하자.
      3. 그렇지 않으면, containerstaticPrivateMethods라고 하자.
      4. container[[Key]]element.[[Key]]PrivateElement existingElement를 포함하면,
        1. Assert: element.[[Kind]]existingElement.[[Kind]]는 둘 다 accessor이다.
        2. element.[[Get]]undefined이면,
          1. combinedPrivateElement { [[Key]]: element.[[Key]], [[Kind]]: accessor, [[Get]]: existingElement.[[Get]], [[Set]]: element.[[Set]] }라고 하자.
        3. 그렇지 않으면,
          1. combinedPrivateElement { [[Key]]: element.[[Key]], [[Kind]]: accessor, [[Get]]: element.[[Get]], [[Set]]: existingElement.[[Set]] }라고 하자.
        4. containerexistingElementcombined로 대체한다.
      5. 그렇지 않으면,
        1. elementcontainer에 추가한다.
    6. 그렇지 않고 elementClassFieldDefinition Record이면,
      1. classElementIsStaticfalse이면, elementinstanceFields에 추가한다.
      2. 그렇지 않으면, elementstaticElements에 추가한다.
    7. 그렇지 않고 elementClassStaticBlockDefinition Record이면,
      1. elementstaticElements에 추가한다.
  27. 실행 중인 실행 컨텍스트의 LexicalEnvironment를 envRecord로 설정한다.
  28. classBindingundefined가 아니면,
    1. classEnv.InitializeBinding(classBinding, ctorFunc)를 수행한다.
  29. ctorFunc.[[PrivateMethods]]instancePrivateMethods로 설정한다.
  30. ctorFunc.[[Fields]]instanceFields로 설정한다.
  31. staticPrivateMethods의 각 PrivateElement method에 대해 다음을 수행한다.
    1. PrivateMethodOrAccessorAdd(ctorFunc, method)를 수행한다.
  32. staticElements의 각 요소 elementRecord에 대해 다음을 수행한다.
    1. elementRecordClassFieldDefinition Record이면,
      1. resultCompletion(DefineField(ctorFunc, elementRecord))라고 하자.
    2. 그렇지 않으면,
      1. Assert: elementRecordClassStaticBlockDefinition Record이다.
      2. resultCompletion(Call(elementRecord.[[BodyFunction]], ctorFunc))라고 하자.
    3. resultabrupt completion이면,
      1. 실행 중인 실행 컨텍스트의 PrivateEnvironment를 outerPrivateEnv로 설정한다.
      2. result를 반환한다.
  33. 실행 중인 실행 컨텍스트의 PrivateEnvironment를 outerPrivateEnv로 설정한다.
  34. ctorFunc를 반환한다.

15.7.15 Runtime Semantics: BindingClassDeclarationEvaluation

The syntax-directed operation BindingClassDeclarationEvaluation takes no arguments and returns either a normal completion containing a function object or an abrupt completion. It is defined piecewise over the following productions:

ClassDeclaration : class BindingIdentifier ClassTail
  1. classNameBindingIdentifierStringValue로 둔다.
  2. sourceTextClassDeclaration에 matched된 source text로 둔다.
  3. value를 arguments className, className, 및 sourceText를 가진 ClassTailClassDefinitionEvaluation으로 ? 둔다.
  4. envRecordrunning execution context의 LexicalEnvironment로 둔다.
  5. InitializeBoundName(className, value, envRecord)를 수행한다.
  6. value를 반환한다.
ClassDeclaration : class ClassTail
  1. sourceTextClassDeclaration에 matched된 source text로 둔다.
  2. arguments undefined, "default", 및 sourceText를 가진 ClassTailClassDefinitionEvaluation을 ? 반환한다.
Note

ClassDeclaration : class ClassTail ExportDeclaration의 part로만 occur하며, 그 binding의 establishment는 해당 production을 위한 evaluation action의 part로 handled됩니다. 16.2.3.7를 참조하십시오.

15.7.16 Runtime Semantics: Evaluation

ClassDeclaration : class BindingIdentifier ClassTail
  1. this ClassDeclarationBindingClassDeclarationEvaluation을 ? 수행한다.
  2. empty를 반환한다.
Note

ClassDeclaration : class ClassTail ExportDeclaration의 part로만 occur하며 never directly evaluated되지 않습니다.

ClassExpression : class ClassTail
  1. sourceTextClassExpression에 matched된 source text로 둔다.
  2. arguments undefined, empty String, 및 sourceText를 가진 ClassTailClassDefinitionEvaluation을 ? 반환한다.
ClassExpression : class BindingIdentifier ClassTail
  1. classNameBindingIdentifierStringValue로 둔다.
  2. sourceTextClassExpression에 matched된 source text로 둔다.
  3. arguments className, className, 및 sourceText를 가진 ClassTailClassDefinitionEvaluation을 ? 반환한다.
ClassElementName : PrivateIdentifier
  1. privateIdentifierPrivateIdentifierStringValue로 둔다.
  2. privateEnvRecordrunning execution context의 PrivateEnvironment로 둔다.
  3. namesprivateEnvRecord.[[Names]]로 둔다.
  4. Assert: names의 exactly one element는 [[Description]]privateIdentifierPrivate Name이다.
  5. privateName[[Description]]privateIdentifiernames 안의 Private Name으로 둔다.
  6. privateName을 반환한다.
ClassStaticBlockStatementList : [empty]
  1. undefined를 반환한다.

15.8 Async Function Definitions

Syntax

AsyncFunctionDeclaration[Yield, Await, Default] : async [no LineTerminator here] function BindingIdentifier[?Yield, ?Await] ( FormalParameters[~Yield, +Await] ) { AsyncFunctionBody } [+Default] async [no LineTerminator here] function ( FormalParameters[~Yield, +Await] ) { AsyncFunctionBody } AsyncFunctionExpression : async [no LineTerminator here] function BindingIdentifier[~Yield, +Await]opt ( FormalParameters[~Yield, +Await] ) { AsyncFunctionBody } AsyncMethod[Yield, Await] : async [no LineTerminator here] ClassElementName[?Yield, ?Await] ( UniqueFormalParameters[~Yield, +Await] ) { AsyncFunctionBody } AsyncFunctionBody : FunctionBody[~Yield, +Await] AwaitExpression[Yield] : await UnaryExpression[?Yield, +Await] Note 1

[Await] parameter가 present할 때 awaitAwaitExpressionkeyword로 parsed됩니다. [Await] parameter는 다음 context의 top level에서 present하지만, FunctionBody와 같은 nonterminal에 따라 일부 context에서는 parameter가 absent할 수 있습니다:

Script가 syntactic goal symbol일 때, [Await] parameter가 absent하면 await는 identifier로 parsed될 수 있습니다. 여기에는 다음 context가 포함됩니다:

Note 2

YieldExpression과 달리, AwaitExpression의 operand를 omit하는 것은 Syntax Error입니다. 반드시 something을 await해야 합니다.

15.8.1 Static Semantics: Early Errors

AsyncMethod : async ClassElementName ( UniqueFormalParameters ) { AsyncFunctionBody } AsyncFunctionDeclaration : async function BindingIdentifier ( FormalParameters ) { AsyncFunctionBody } async function ( FormalParameters ) { AsyncFunctionBody } AsyncFunctionExpression : async function BindingIdentifieropt ( FormalParameters ) { AsyncFunctionBody }

15.8.2 Runtime Semantics: InstantiateAsyncFunctionObject

The syntax-directed operation InstantiateAsyncFunctionObject takes arguments envRecord (an Environment Record) and privateEnv (a PrivateEnvironment Record or null) and returns an ECMAScript function object. It is defined piecewise over the following productions:

AsyncFunctionDeclaration : async function BindingIdentifier ( FormalParameters ) { AsyncFunctionBody }
  1. nameBindingIdentifierStringValue로 둔다.
  2. sourceTextAsyncFunctionDeclaration에 matched된 source text로 둔다.
  3. closureOrdinaryFunctionCreate(%AsyncFunction.prototype%, sourceText, FormalParameters, AsyncFunctionBody, non-lexical-this, envRecord, privateEnv)로 둔다.
  4. SetFunctionName(closure, name)을 수행한다.
  5. closure를 반환한다.
AsyncFunctionDeclaration : async function ( FormalParameters ) { AsyncFunctionBody }
  1. sourceTextAsyncFunctionDeclaration에 matched된 source text로 둔다.
  2. closureOrdinaryFunctionCreate(%AsyncFunction.prototype%, sourceText, FormalParameters, AsyncFunctionBody, non-lexical-this, envRecord, privateEnv)로 둔다.
  3. SetFunctionName(closure, "default")를 수행한다.
  4. closure를 반환한다.

15.8.3 Runtime Semantics: InstantiateAsyncFunctionExpression

The syntax-directed operation InstantiateAsyncFunctionExpression takes optional argument name (a property key or a Private Name) and returns an ECMAScript function object. It is defined piecewise over the following productions:

AsyncFunctionExpression : async function ( FormalParameters ) { AsyncFunctionBody }
  1. name이 present하지 않으면, name을 empty String으로 설정한다.
  2. envRecordrunning execution context의 LexicalEnvironment로 둔다.
  3. privateEnvrunning execution context의 PrivateEnvironment로 둔다.
  4. sourceTextAsyncFunctionExpression에 matched된 source text로 둔다.
  5. closureOrdinaryFunctionCreate(%AsyncFunction.prototype%, sourceText, FormalParameters, AsyncFunctionBody, non-lexical-this, envRecord, privateEnv)로 둔다.
  6. SetFunctionName(closure, name)을 수행한다.
  7. closure를 반환한다.
AsyncFunctionExpression : async function BindingIdentifier ( FormalParameters ) { AsyncFunctionBody }
  1. Assert: name은 present하지 않는다.
  2. nameBindingIdentifierStringValue로 설정한다.
  3. outerEnvrunning execution context의 LexicalEnvironment로 둔다.
  4. funcEnvNewDeclarativeEnvironment(outerEnv)로 둔다.
  5. funcEnv.CreateImmutableBinding(name, false)를 수행한다.
  6. privateEnvrunning execution context의 PrivateEnvironment로 둔다.
  7. sourceTextAsyncFunctionExpression에 matched된 source text로 둔다.
  8. closureOrdinaryFunctionCreate(%AsyncFunction.prototype%, sourceText, FormalParameters, AsyncFunctionBody, non-lexical-this, funcEnv, privateEnv)로 둔다.
  9. SetFunctionName(closure, name)을 수행한다.
  10. funcEnv.InitializeBinding(name, closure)를 수행한다.
  11. closure를 반환한다.
Note

AsyncFunctionExpression 안의 BindingIdentifier는 function이 recursively 자신을 call할 수 있도록 AsyncFunctionExpressionAsyncFunctionBody 내부에서 referenced될 수 있습니다. 그러나 FunctionDeclaration과 달리 AsyncFunctionExpression 안의 BindingIdentifierAsyncFunctionExpression을 enclosing하는 scope에서 referenced될 수 없고 그 scope에 affect하지 않습니다.

15.8.4 Runtime Semantics: EvaluateAsyncFunctionBody

The syntax-directed operation EvaluateAsyncFunctionBody takes arguments funcObj (an ECMAScript function object) and argList (a List of ECMAScript language values) and returns a return completion. It is defined piecewise over the following productions:

AsyncFunctionBody : FunctionBody
  1. promiseCapability를 ! NewPromiseCapability(%Promise%)로 둔다.
  2. completionCompletion(FunctionDeclarationInstantiation(funcObj, argList))로 둔다.
  3. completionabrupt completion이면, 다음을 수행한다.
    1. Call(promiseCapability.[[Reject]], undefined, « completion.[[Value]] »)를 수행한다.
  4. 그렇지 않으면,
    1. AsyncFunctionStart(promiseCapability, FunctionBody)를 수행한다.
  5. ReturnCompletion(promiseCapability.[[Promise]])를 반환한다.

15.8.5 Runtime Semantics: Evaluation

AsyncFunctionExpression : async function BindingIdentifieropt ( FormalParameters ) { AsyncFunctionBody }
  1. AsyncFunctionExpressionInstantiateAsyncFunctionExpression을 반환한다.
UnaryExpression : CoverAwaitExpressionAndAwaitUsingDeclarationHead
  1. exprCoverAwaitExpressionAndAwaitUsingDeclarationHead가 cover하는 AwaitExpression으로 둔다.
  2. exprEvaluation을 ? 반환한다.
AwaitExpression : await UnaryExpression
  1. exprRefUnaryExpressionEvaluation으로 ? 둔다.
  2. value를 ? GetValue(exprRef)로 둔다.
  3. Await(value)를 반환한다.

15.9 Async Arrow Function Definitions

Syntax

AsyncArrowFunction[In, Yield, Await] : async [no LineTerminator here] AsyncArrowBindingIdentifier[?Yield] [no LineTerminator here] => AsyncConciseBody[?In] CoverCallExpressionAndAsyncArrowHead[?Yield, ?Await] [no LineTerminator here] => AsyncConciseBody[?In] AsyncConciseBody[In] : [lookahead ≠ {] ExpressionBody[?In, +Await] { AsyncFunctionBody } AsyncArrowBindingIdentifier[Yield] : BindingIdentifier[?Yield, +Await] CoverCallExpressionAndAsyncArrowHead[Yield, Await] : MemberExpression[?Yield, ?Await] Arguments[?Yield, ?Await]

Supplemental Syntax

production
AsyncArrowFunction : CoverCallExpressionAndAsyncArrowHead => AsyncConciseBody
의 instance를 processing할 때, CoverCallExpressionAndAsyncArrowHead의 interpretation은 다음 grammar를 사용하여 refined됩니다:

AsyncArrowHead : async [no LineTerminator here] ArrowFormalParameters[~Yield, +Await]

15.9.1 Static Semantics: Early Errors

AsyncArrowFunction : async AsyncArrowBindingIdentifier => AsyncConciseBody AsyncArrowFunction : CoverCallExpressionAndAsyncArrowHead => AsyncConciseBody

15.9.2 Static Semantics: AsyncConciseBodyContainsUseStrict

The syntax-directed operation AsyncConciseBodyContainsUseStrict takes no arguments and returns a Boolean. It is defined piecewise over the following productions:

AsyncConciseBody : ExpressionBody
  1. false를 반환한다.
AsyncConciseBody : { AsyncFunctionBody }
  1. AsyncFunctionBodyFunctionBodyContainsUseStrict를 반환한다.

15.9.3 Runtime Semantics: EvaluateAsyncConciseBody

The syntax-directed operation EvaluateAsyncConciseBody takes arguments funcObj (an ECMAScript function object) and argList (a List of ECMAScript language values) and returns a return completion. It is defined piecewise over the following productions:

AsyncConciseBody : ExpressionBody
  1. promiseCapability를 ! NewPromiseCapability(%Promise%)로 둔다.
  2. completionCompletion(FunctionDeclarationInstantiation(funcObj, argList))로 둔다.
  3. completionabrupt completion이면, 다음을 수행한다.
    1. Call(promiseCapability.[[Reject]], undefined, « completion.[[Value]] »)를 수행한다.
  4. 그렇지 않으면,
    1. AsyncFunctionStart(promiseCapability, ExpressionBody)를 수행한다.
  5. ReturnCompletion(promiseCapability.[[Promise]])를 반환한다.

15.9.4 Runtime Semantics: InstantiateAsyncArrowFunctionExpression

The syntax-directed operation InstantiateAsyncArrowFunctionExpression takes optional argument name (a property key or a Private Name) and returns an ECMAScript function object. It is defined piecewise over the following productions:

AsyncArrowFunction : async AsyncArrowBindingIdentifier => AsyncConciseBody
  1. name이 present하지 않으면, name을 empty String으로 설정한다.
  2. envRecordrunning execution context의 LexicalEnvironment로 둔다.
  3. privateEnvrunning execution context의 PrivateEnvironment로 둔다.
  4. sourceTextAsyncArrowFunction에 matched된 source text로 둔다.
  5. paramsAsyncArrowBindingIdentifier로 둔다.
  6. closureOrdinaryFunctionCreate(%AsyncFunction.prototype%, sourceText, params, AsyncConciseBody, lexical-this, envRecord, privateEnv)로 둔다.
  7. SetFunctionName(closure, name)을 수행한다.
  8. closure를 반환한다.
AsyncArrowFunction : CoverCallExpressionAndAsyncArrowHead => AsyncConciseBody
  1. name이 present하지 않으면, name을 empty String으로 설정한다.
  2. envRecordrunning execution context의 LexicalEnvironment로 둔다.
  3. privateEnvrunning execution context의 PrivateEnvironment로 둔다.
  4. sourceTextAsyncArrowFunction에 matched된 source text로 둔다.
  5. headCoverCallExpressionAndAsyncArrowHeadcovered하는 AsyncArrowHead로 둔다.
  6. paramsheadArrowFormalParameters로 둔다.
  7. closureOrdinaryFunctionCreate(%AsyncFunction.prototype%, sourceText, params, AsyncConciseBody, lexical-this, envRecord, privateEnv)로 둔다.
  8. SetFunctionName(closure, name)을 수행한다.
  9. closure를 반환한다.

15.9.5 Runtime Semantics: Evaluation

AsyncArrowFunction : async AsyncArrowBindingIdentifier => AsyncConciseBody CoverCallExpressionAndAsyncArrowHead => AsyncConciseBody
  1. AsyncArrowFunctionInstantiateAsyncArrowFunctionExpression을 반환한다.

15.10 Tail Position Calls

15.10.1 Static Semantics: IsInTailPosition ( call )

The abstract operation IsInTailPosition takes argument call (a CallExpression Parse Node, a MemberExpression Parse Node, or an OptionalChain Parse Node) and returns a Boolean. It performs the following steps when called:

  1. IsStrict(call)가 false이면, false를 반환한다.
  2. callFunctionBody, ConciseBody 또는 AsyncConciseBody 안에 contained되어 있지 않으면, false를 반환한다.
  3. bodycall을 most closely contain하는 FunctionBody, ConciseBody 또는 AsyncConciseBody로 둔다.
  4. bodyGeneratorBodyFunctionBody이면, false를 반환한다.
  5. bodyAsyncFunctionBodyFunctionBody이면, false를 반환한다.
  6. bodyAsyncGeneratorBodyFunctionBody이면, false를 반환한다.
  7. bodyAsyncConciseBody이면, false를 반환한다.
  8. argument call를 가진 bodyHasCallInTailPosition의 result를 반환한다.
Note

Tail Position call은 caller context의 chain을 observation할 수 있게 하는 common non-standard language extension(10.2.4 참조) 때문에 strict mode code에서만 defined됩니다.

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

호출 결과의 GetValue를 반환하는 것이 바로 뒤따르는 잠재적 꼬리 위치 호출도 가능한 꼬리 위치 호출이다. 함수 호출은 Reference Record를 반환할 수 없으므로, 이러한 GetValue 연산은 항상 실제 함수 호출 결과와 동일한 값을 반환한다.

Note 3

같은 Block, ForStatement, ForInOfStatement, FunctionBody, GeneratorBody, AsyncGeneratorBody, AsyncFunctionBody 또는 ClassStaticBlockBody 안에서 호출 앞에 오는 using 선언 또는 await using 선언은 그 호출이 가능한 꼬리 위치 호출이 되는 것을 방지한다.

It is defined piecewise over the following productions:

StatementList : StatementList StatementListItem
  1. has를 인수 call로 파생된 StatementListHasCallInTailPosition으로 둔다.
  2. hastrue이면, true를 반환한다.
  3. 파생된 StatementListContainsUsingtrue이면, false를 반환한다.
  4. 인수 callStatementListItemHasCallInTailPosition을 반환한다.
FunctionStatementList : [empty] StatementListItem : Declaration Statement : VariableStatement EmptyStatement ExpressionStatement ContinueStatement BreakStatement ThrowStatement DebuggerStatement Block : { } ReturnStatement : return ; LabelledItem : FunctionDeclaration ForInOfStatement : for ( LeftHandSideExpression of AssignmentExpression ) Statement for ( var ForBinding of AssignmentExpression ) Statement for ( ForDeclaration of AssignmentExpression ) Statement CaseBlock : { }
  1. false를 반환한다.
IfStatement : if ( Expression ) Statement else Statement
  1. has를 argument call를 가진 first StatementHasCallInTailPosition으로 둔다.
  2. hastrue이면, true를 반환한다.
  3. argument call를 가진 second StatementHasCallInTailPosition을 반환한다.
IfStatement : if ( Expression ) Statement DoWhileStatement : do Statement while ( Expression ) ; WhileStatement : while ( Expression ) Statement ForStatement : for ( Expressionopt ; Expressionopt ; Expressionopt ) Statement for ( var VariableDeclarationList ; Expressionopt ; Expressionopt ) Statement for ( LexicalDeclaration Expressionopt ; Expressionopt ) Statement ForInOfStatement : for ( LeftHandSideExpression in Expression ) Statement for ( var ForBinding in Expression ) Statement for ( ForDeclaration in Expression ) Statement WithStatement : with ( Expression ) Statement
  1. argument call를 가진 StatementHasCallInTailPosition을 반환한다.
LabelledStatement : LabelIdentifier : LabelledItem
  1. argument call를 가진 LabelledItemHasCallInTailPosition을 반환한다.
ReturnStatement : return Expression ;
  1. argument call를 가진 ExpressionHasCallInTailPosition을 반환한다.
SwitchStatement : switch ( Expression ) CaseBlock
  1. argument call를 가진 CaseBlockHasCallInTailPosition을 반환한다.
CaseBlock : { CaseClausesopt DefaultClause CaseClausesopt }
  1. hasfalse로 둔다.
  2. first CaseClauses가 present하면, has를 argument call를 가진 first CaseClausesHasCallInTailPosition으로 설정한다.
  3. hastrue이면, true를 반환한다.
  4. has를 argument call를 가진 DefaultClauseHasCallInTailPosition으로 설정한다.
  5. hastrue이면, true를 반환한다.
  6. second CaseClauses가 present하면, has를 argument call를 가진 second CaseClausesHasCallInTailPosition으로 설정한다.
  7. has를 반환한다.
CaseClauses : CaseClauses CaseClause
  1. has를 argument call를 가진 CaseClausesHasCallInTailPosition으로 둔다.
  2. hastrue이면, true를 반환한다.
  3. argument call를 가진 CaseClauseHasCallInTailPosition을 반환한다.
CaseClause : case Expression : StatementListopt DefaultClause : default : StatementListopt
  1. StatementList가 present하면, argument call를 가진 StatementListHasCallInTailPosition을 반환한다.
  2. false를 반환한다.
TryStatement : try Block Catch
  1. argument call를 가진 CatchHasCallInTailPosition을 반환한다.
TryStatement : try Block Finally try Block Catch Finally
  1. argument call를 가진 FinallyHasCallInTailPosition을 반환한다.
Catch : catch ( CatchParameter ) Block
  1. argument call를 가진 BlockHasCallInTailPosition을 반환한다.
AssignmentExpression : YieldExpression ArrowFunction AsyncArrowFunction LeftHandSideExpression = AssignmentExpression LeftHandSideExpression AssignmentOperator AssignmentExpression LeftHandSideExpression &&= AssignmentExpression LeftHandSideExpression ||= AssignmentExpression LeftHandSideExpression ??= AssignmentExpression BitwiseANDExpression : BitwiseANDExpression & EqualityExpression BitwiseXORExpression : BitwiseXORExpression ^ BitwiseANDExpression BitwiseORExpression : BitwiseORExpression | BitwiseXORExpression EqualityExpression : EqualityExpression == RelationalExpression EqualityExpression != RelationalExpression EqualityExpression === RelationalExpression EqualityExpression !== RelationalExpression RelationalExpression : RelationalExpression < ShiftExpression RelationalExpression > ShiftExpression RelationalExpression <= ShiftExpression RelationalExpression >= ShiftExpression RelationalExpression instanceof ShiftExpression RelationalExpression in ShiftExpression PrivateIdentifier in ShiftExpression ShiftExpression : ShiftExpression << AdditiveExpression ShiftExpression >> AdditiveExpression ShiftExpression >>> AdditiveExpression AdditiveExpression : AdditiveExpression + MultiplicativeExpression AdditiveExpression - MultiplicativeExpression MultiplicativeExpression : MultiplicativeExpression MultiplicativeOperator ExponentiationExpression ExponentiationExpression : UpdateExpression ** ExponentiationExpression UpdateExpression : LeftHandSideExpression ++ LeftHandSideExpression -- ++ UnaryExpression -- UnaryExpression UnaryExpression : delete UnaryExpression void UnaryExpression typeof UnaryExpression + UnaryExpression - UnaryExpression ~ UnaryExpression ! UnaryExpression CoverAwaitExpressionAndAwaitUsingDeclarationHead CallExpression : SuperCall ImportCall CallExpression [ Expression ] CallExpression . IdentifierName CallExpression . PrivateIdentifier NewExpression : new NewExpression MemberExpression : MemberExpression [ Expression ] MemberExpression . IdentifierName SuperProperty MetaProperty new MemberExpression Arguments MemberExpression . PrivateIdentifier PrimaryExpression : this IdentifierReference Literal ArrayLiteral ObjectLiteral FunctionExpression ClassExpression GeneratorExpression AsyncFunctionExpression AsyncGeneratorExpression RegularExpressionLiteral TemplateLiteral
  1. false를 반환한다.
Expression : AssignmentExpression Expression , AssignmentExpression
  1. argument call를 가진 AssignmentExpressionHasCallInTailPosition을 반환한다.
ConditionalExpression : ShortCircuitExpression ? AssignmentExpression : AssignmentExpression
  1. has를 argument call를 가진 first AssignmentExpressionHasCallInTailPosition으로 둔다.
  2. hastrue이면, true를 반환한다.
  3. argument call를 가진 second AssignmentExpressionHasCallInTailPosition을 반환한다.
LogicalANDExpression : LogicalANDExpression && BitwiseORExpression
  1. argument call를 가진 BitwiseORExpressionHasCallInTailPosition을 반환한다.
LogicalORExpression : LogicalORExpression || LogicalANDExpression
  1. argument call를 가진 LogicalANDExpressionHasCallInTailPosition을 반환한다.
CoalesceExpression : CoalesceExpressionHead ?? BitwiseORExpression
  1. argument call를 가진 BitwiseORExpressionHasCallInTailPosition을 반환한다.
CallExpression : CoverCallExpressionAndAsyncArrowHead CallExpression Arguments CallExpression TemplateLiteral
  1. this CallExpressioncall이면, true를 반환한다.
  2. false를 반환한다.
OptionalExpression : MemberExpression OptionalChain CallExpression OptionalChain OptionalExpression OptionalChain
  1. argument call를 가진 OptionalChainHasCallInTailPosition을 반환한다.
OptionalChain : ?. [ Expression ] ?. IdentifierName ?. PrivateIdentifier OptionalChain [ Expression ] OptionalChain . IdentifierName OptionalChain . PrivateIdentifier
  1. false를 반환한다.
OptionalChain : ?. Arguments OptionalChain Arguments
  1. this OptionalChaincall이면, true를 반환한다.
  2. false를 반환한다.
MemberExpression : MemberExpression TemplateLiteral
  1. this MemberExpressioncall이면, true를 반환한다.
  2. false를 반환한다.
PrimaryExpression : CoverParenthesizedExpressionAndArrowParameterList
  1. exprCoverParenthesizedExpressionAndArrowParameterListcovered하는 ParenthesizedExpression으로 둔다.
  2. argument call를 가진 exprHasCallInTailPosition을 반환한다.
ParenthesizedExpression : ( Expression )
  1. argument call를 가진 ExpressionHasCallInTailPosition을 반환한다.

15.10.3 PrepareForTailCall ( )

The abstract operation PrepareForTailCall takes no arguments and returns unused. It performs the following steps when called:

  1. Assert: current execution context는 이후 어떤 ECMAScript code 또는 built-in function의 evaluation에도 사용되지 않는다. 이 abstract operation의 invocation 이후 Call의 invocation은 그러한 evaluation을 수행하기 전에 new execution context를 create하고 push할 것이다.
  2. current execution context와 associated된 모든 resource를 discard한다.
  3. unused를 반환한다.

tail position call은 target function을 invoking하기 전에 currently executing function execution context와 associated된 모든 transient internal resource를 release하거나, target function을 support하기 위해 그러한 resource를 reuse해야 합니다.

Note

예를 들어, tail position call은 target function의 activation record size가 calling function의 activation record size를 초과하는 amount만큼만 implementation의 activation record stack을 grow해야 합니다. target function의 activation record가 더 작으면, stack의 total size는 decrease해야 합니다.

16 ECMAScript 언어: Scripts and Modules

16.1 Scripts

Syntax

Script : ScriptBodyopt ScriptBody : StatementList[~Yield, ~Await, ~Return]

16.1.1 Static Semantics: Early Errors

Script : ScriptBody ScriptBody : StatementList

16.1.2 Static Semantics: ScriptIsStrict

The syntax-directed operation ScriptIsStrict takes no arguments and returns a Boolean. It is defined piecewise over the following productions:

Script : ScriptBodyopt
  1. ScriptBody가 present하고 ScriptBodyDirective PrologueUse Strict Directive를 contain하면, true를 반환한다.
  2. false를 반환한다.

16.1.3 Runtime Semantics: Evaluation

Script : [empty]
  1. undefined를 반환한다.

16.1.4 Script Records

Script Record는 evaluating되고 있는 script에 대한 information을 encapsulate합니다. 각 script record는 Table 35에 listed된 field를 contain합니다.

Table 35: Script Record Fields
Field Name Value Type Meaning
[[Realm]] a Realm Record 이 script가 created된 realm입니다.
[[ECMAScriptCode]] a Script Parse Node 이 script의 source text를 parsing한 result입니다.
[[LoadedModules]] a List of LoadedModuleRequest Records 이 script에 의해 imported된 specifier string에서 resolved Module Record로의 map입니다. list는 ModuleRequestsEqual(r1, r2)이 true인 두 different Record r1r2를 contain하지 않습니다.
[[HostDefined]] anything (default value is empty) script와 additional information을 associate해야 하는 host environment가 use하기 위해 reserved된 field입니다.

16.1.5 ParseScript ( sourceText, realm, hostDefined )

The abstract operation ParseScript takes arguments sourceText (a String or a sequence of Unicode code points), realm (a Realm Record), and hostDefined (anything) and returns a Script Record or a non-empty List of SyntaxError objects. sourceTextScript로 parsing한 result를 기반으로 Script Record를 create합니다. It performs the following steps when called:

  1. scriptParseText(sourceText, Script)로 둔다.
  2. script가 error의 List이면, script를 반환한다.
  3. Script Record { [[Realm]]: realm, [[ECMAScriptCode]]: script, [[LoadedModules]]: « », [[HostDefined]]: hostDefined }를 반환한다.
Note

implementation은 해당 script source text에 대해 ParseScript를 evaluation하기 전에 script source text를 parse하고 Early Error condition에 대해 analyse할 수 있습니다. 그러나 any error의 reporting은 이 specification이 실제로 해당 source text에 대해 ParseScript를 수행하는 point까지 deferred되어야 합니다.

16.1.6 ScriptEvaluation ( scriptRecord )

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

  1. globalEnvscriptRecord.[[Realm]].[[GlobalEnv]]로 둔다.
  2. scriptContext를 새 ECMAScript code execution context로 둔다.
  3. scriptContext의 Function을 null로 설정한다.
  4. scriptContextRealmscriptRecord.[[Realm]]로 설정한다.
  5. scriptContext의 ScriptOrModule을 scriptRecord로 설정한다.
  6. scriptContext의 VariableEnvironment를 globalEnv로 설정한다.
  7. scriptContext의 LexicalEnvironment를 globalEnv로 설정한다.
  8. scriptContext의 PrivateEnvironment를 null로 설정한다.
  9. running execution context를 suspend한다.
  10. scriptContextexecution context stack에 push한다; scriptContext는 이제 running execution context이다.
  11. scriptNodescriptRecord.[[ECMAScriptCode]]로 둔다.
  12. resultCompletion(GlobalDeclarationInstantiation(scriptNode, globalEnv))로 둔다.
  13. resultnormal completion이면, 다음을 수행한다.
    1. resultCompletion(scriptNodeEvaluation)으로 설정한다.
    2. resultnormal completion이고 result.[[Value]]empty이면, 다음을 수행한다.
      1. resultNormalCompletion(undefined)로 설정한다.
  14. scriptContext를 suspend하고 execution context stack에서 remove한다.
  15. Assert: execution context stack은 empty가 아니다.
  16. execution context stack의 top에 now 있는 context를 running execution context로 resume한다.
  17. result를 반환한다.

16.1.7 GlobalDeclarationInstantiation ( script, envRecord )

The abstract operation GlobalDeclarationInstantiation takes arguments script (a Script Parse Node) and envRecord (a Global Environment Record) and returns either a normal completion containing unused or a throw completion. scriptexecution context가 established되고 있는 Script입니다. envRecord는 binding이 created될 global environment입니다.

Note 1

script를 evaluating하기 위해 execution context가 established될 때, declaration은 current global environment 안에서 instantiated됩니다. code 안에 declared된 각 global binding이 instantiated됩니다.

called될 때 다음 step을 수행합니다:

  1. lexicalNamesscriptLexicallyDeclaredNames라고 하자.
  2. variableNamesscriptVarDeclaredNames라고 하자.
  3. lexicalNames의 각 요소 name에 대해 다음을 수행한다.
    1. HasLexicalDeclaration(envRecord, name)이 true이면, SyntaxError 예외를 던진다.
    2. hasRestrictedGlobal을 ? HasRestrictedGlobalProperty(envRecord, name)라고 하자.
    3. NOTE: 전역 varfunction 바인딩은 non-strict direct eval에 의해 도입된 것을 제외하고는 non-configurable이므로 restricted global properties이다.
    4. hasRestrictedGlobaltrue이면, SyntaxError 예외를 던진다.
  4. variableNames의 각 요소 name에 대해 다음을 수행한다.
    1. HasLexicalDeclaration(envRecord, name)이 true이면, SyntaxError 예외를 던진다.
  5. variableDeclsscriptVarScopedDeclarations라고 하자.
  6. funcsToInitialize를 새로운 빈 List라고 하자.
  7. declaredFuncNames를 새로운 빈 List라고 하자.
  8. variableDecls의 각 요소 variableDecl에 대해, List의 역순으로 다음을 수행한다.
    1. variableDeclVariableDeclaration, ForBinding 또는 BindingIdentifier 중 어느 것도 아니면,
      1. Assert: variableDeclFunctionDeclaration, GeneratorDeclaration, AsyncFunctionDeclaration 또는 AsyncGeneratorDeclaration 중 하나이다.
      2. NOTE: 같은 이름에 대해 여러 함수 선언이 있으면, 마지막 선언이 사용된다.
      3. funcNamevariableDeclBoundNames의 유일한 요소라고 하자.
      4. declaredFuncNamesfuncName을 포함하지 않으면,
        1. funcDefinable을 ? CanDeclareGlobalFunction(envRecord, funcName)이라고 하자.
        2. funcDefinablefalse이면, TypeError 예외를 던진다.
        3. funcNamedeclaredFuncNames에 추가한다.
        4. variableDeclfuncsToInitialize의 첫 번째 요소로 삽입한다.
  9. declaredVariableNames를 새로운 빈 List라고 하자.
  10. variableDecls의 각 요소 variableDecl에 대해 다음을 수행한다.
    1. variableDeclVariableDeclaration, ForBinding 또는 BindingIdentifier 중 하나이면,
      1. variableDeclBoundNames의 각 String name에 대해 다음을 수행한다.
        1. declaredFuncNamesname을 포함하지 않으면,
          1. variableDefinable을 ? CanDeclareGlobalVar(envRecord, name)라고 하자.
          2. variableDefinablefalse이면, TypeError 예외를 던진다.
          3. declaredVariableNamesname을 포함하지 않으면,
            1. namedeclaredVariableNames에 추가한다.
  11. NOTE: 전역 객체가 ordinary object이면 이 알고리즘 단계 이후에는 abnormal termination이 발생하지 않는다. 하지만 전역 객체가 Proxy exotic object이면 다음 단계 중 일부에서 abnormal termination을 유발하는 동작을 보일 수 있다.
  12. host가 웹 브라우저이거나 그 밖에 Block-Level Function Declarations Web Legacy Compatibility Semantics를 지원하면,
    1. strictscriptScriptIsStrict라고 하자.
    2. strictfalse이면,
      1. declaredFuncOrVariableNamesdeclaredFuncNamesdeclaredVariableNameslist-concatenation이라고 하자.
      2. script Contains xtrueBlock, CaseClause 또는 DefaultClause xStatementList에 직접 포함된 각 FunctionDeclaration funcDecl에 대해 다음을 수행한다.
        1. funcNamefuncDeclBindingIdentifierStringValue라고 하자.
        2. FunctionDeclaration funcDeclfuncNameBindingIdentifier로 갖는 VariableStatement로 대체해도 script에 대한 Early Errors가 생성되지 않으면,
          1. HasLexicalDeclaration(envRecord, funcName)이 false이면,
            1. funcDefinable을 ? CanDeclareGlobalVar(envRecord, funcName)라고 하자.
            2. funcDefinabletrue이면,
              1. NOTE: funcName에 대한 var 바인딩은 그것이 VarDeclaredName도 아니고 다른 FunctionDeclaration의 이름도 아닐 때에만 여기서 인스턴스화된다.
              2. declaredFuncOrVariableNamesfuncName을 포함하지 않으면,
                1. CreateGlobalVarBinding(envRecord, funcName, false)를 수행한다.
                2. funcNamedeclaredFuncOrVariableNames에 추가한다.
              3. FunctionDeclaration funcDecl이 평가될 때, 15.2.6에 제공된 FunctionDeclaration Evaluation 알고리즘 대신 다음 단계를 수행한다.
                1. globalEnv를 실행 중인 실행 컨텍스트의 VariableEnvironment라고 하자.
                2. blockEnv를 실행 중인 실행 컨텍스트의 LexicalEnvironment라고 하자.
                3. funcObj를 ! blockEnv.GetBindingValue(funcName, false)라고 하자.
                4. globalEnv.SetMutableBinding(funcName, funcObj, false)를 수행한다.
                5. unused를 반환한다.
  13. lexicalDeclsscriptLexicallyScopedDeclarations라고 하자.
  14. privateEnvnull이라고 하자.
  15. lexicalDecls의 각 요소 lexicalDecl에 대해 다음을 수행한다.
    1. NOTE: Lexically declared name은 여기서 인스턴스화만 되고 초기화되지는 않는다.
    2. lexicalDeclBoundNames의 각 요소 name에 대해 다음을 수행한다.
      1. lexicalDeclIsConstantDeclarationtrue이면,
        1. envRecord.CreateImmutableBinding(name, true)를 수행한다.
      2. 그렇지 않으면,
        1. envRecord.CreateMutableBinding(name, false)를 수행한다.
  16. funcsToInitialize의 각 Parse Node funcDecl에 대해 다음을 수행한다.
    1. funcNamefuncDeclBoundNames의 유일한 요소라고 하자.
    2. funcObjfuncDeclInstantiateFunctionObject에 인수 envRecordprivateEnv를 전달한 결과라고 하자.
    3. CreateGlobalFunctionBinding(envRecord, funcName, funcObj, false)를 수행한다.
  17. declaredVariableNames의 각 String variableName에 대해 다음을 수행한다.
    1. CreateGlobalVarBinding(envRecord, variableName, false)를 수행한다.
  18. unused를 반환한다.
Note 2

16.1.1에 specified된 early error는 single Script 안에 contained된 declaration에 대해 function/var declaration과 let/const/class declaration 사이의 name conflict 및 let/const/class binding의 redeclaration을 prevent합니다. 그러나 둘 이상의 Script에 걸친 such conflict와 redeclaration은 GlobalDeclarationInstantiation 동안 runtime error로 detected됩니다. 그러한 error가 detected되면, script에 대해 어떤 binding도 instantiated되지 않습니다. 그러나 global objectProxy exotic object를 사용하여 defined된 경우 conflicting declaration에 대한 runtime test가 unreliable할 수 있으며, 그 결과 abrupt completion과 some global declaration이 instantiated되지 않을 수 있습니다. 이것이 occur하면 Script의 code는 evaluated되지 않습니다.

explicit var 또는 function declaration과 달리, global object에 directly created된 property는 let/const/class declaration에 의해 shadowed될 수 있는 global binding을 result합니다.

16.2 Modules

Syntax

Module : ModuleBodyopt ModuleBody : ModuleItemList ModuleItemList : ModuleItem ModuleItemList ModuleItem ModuleItem : ImportDeclaration ExportDeclaration StatementListItem[~Yield, +Await, ~Return] ModuleExportName : IdentifierName StringLiteral

16.2.1 Module Semantics

16.2.1.1 Static Semantics: Early Errors

ModuleBody : ModuleItemList Note

duplicate ExportedNames rule은 ModuleBody 안의 multiple export default ExportDeclaration item이 Syntax Error임을 imply합니다. conflicting 또는 duplicate declaration과 관련된 additional error condition은 Module의 evaluation 전에 module linking 중에 checked됩니다. 그러한 error가 detected되면 Module은 evaluated되지 않습니다.

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에 의해 defined된 모든 local name binding의 List를 create합니다. It performs the following steps when called:

  1. localNames를 새로운 빈 List라고 하자.
  2. importEntries의 각 ImportEntry Record importEntry에 대해 다음을 수행한다.
    1. importEntry.[[LocalName]]localNames에 추가한다.
  3. localNames를 반환한다.

16.2.1.3 ModuleRequest Records

ModuleRequest Record는 given import attribute와 함께 module을 import하려는 request를 represent합니다. 이는 다음 field로 구성됩니다:

Table 36: ModuleRequest Record Fields
Field Name Value Type Meaning
[[Specifier]] a String module specifier입니다.
[[Attributes]] a List of ImportAttribute Records import attribute입니다.

LoadedModuleRequest Record는 resulting Module Record와 함께 module을 import하려는 request를 represent합니다. 이는 Table 36 table에 defined된 같은 field와 [[Module]]의 addition으로 구성됩니다:

Table 37: LoadedModuleRequest Record Fields
Field Name Value Type Meaning
[[Specifier]] a String module specifier입니다.
[[Attributes]] a List of ImportAttribute Records import attribute입니다.
[[Module]] a Module Record 이 module request에 corresponding하는 loaded module입니다.

ImportAttribute Record는 다음 field로 구성됩니다:

Table 38: ImportAttribute Record Fields
Field Name Value Type Meaning
[[Key]] a String attribute key입니다.
[[Value]] a String attribute value입니다.

16.2.1.3.1 ModuleRequestsEqual ( x, y )

The abstract operation ModuleRequestsEqual takes arguments x (a ModuleRequest Record or a LoadedModuleRequest Record) and y (a ModuleRequest Record or a LoadedModuleRequest Record) and returns a Boolean. It performs the following steps when called:

  1. x.[[Specifier]]y.[[Specifier]]가 아니면, false를 반환한다.
  2. xAttrsx.[[Attributes]]로 둔다.
  3. yAttrsy.[[Attributes]]로 둔다.
  4. xAttrsCountxAttrs 안의 element 수로 둔다.
  5. yAttrsCountyAttrs 안의 element 수로 둔다.
  6. xAttrsCountyAttrsCount이면, false를 반환한다.
  7. xAttrs의 각 ImportAttribute Record xAttr에 대해, 다음을 수행한다.
    1. yAttrsxAttr.[[Key]]yAttr.[[Key]]이고 xAttr.[[Value]]yAttr.[[Value]]ImportAttribute Record yAttr를 contain하지 않으면, false를 반환한다.
  8. true를 반환한다.

16.2.1.4 Static Semantics: ModuleRequests

The syntax-directed operation ModuleRequests takes no arguments and returns a List of ModuleRequest Records. It is defined piecewise over the following productions:

Module : [empty]
  1. 새 empty List를 반환한다.
ModuleItemList : ModuleItem
  1. ModuleItemModuleRequests를 반환한다.
ModuleItemList : ModuleItemList ModuleItem
  1. requestsModuleItemListModuleRequests라고 하자.
  2. additionalRequestsModuleItemModuleRequests라고 하자.
  3. additionalRequests의 각 ModuleRequest Record moduleRequest에 대해 다음을 수행한다.
    1. requestsModuleRequestsEqual(moduleRequest, otherModuleRequest)이 trueModuleRequest Record otherModuleRequest를 포함하지 않으면,
      1. moduleRequestrequests에 추가한다.
  4. requests를 반환한다.
ModuleItem : StatementListItem
  1. 새 empty List를 반환한다.
ImportDeclaration : import ImportClause FromClause ;
  1. specifierFromClauseSV로 둔다.
  2. sole element가 ModuleRequest Record { [[Specifier]]: specifier, [[Attributes]]: « » }인 List를 반환한다.
ImportDeclaration : import ImportClause FromClause WithClause ;
  1. specifierFromClauseSV로 둔다.
  2. attrsWithClauseWithClauseToAttributes로 둔다.
  3. sole element가 ModuleRequest Record { [[Specifier]]: specifier, [[Attributes]]: attrs }인 List를 반환한다.
ImportDeclaration : import ModuleSpecifier ;
  1. specifierModuleSpecifierSV로 둔다.
  2. sole element가 ModuleRequest Record { [[Specifier]]: specifier, [[Attributes]]: « » }인 List를 반환한다.
ImportDeclaration : import ModuleSpecifier WithClause ;
  1. specifierModuleSpecifierSV로 둔다.
  2. attrsWithClauseWithClauseToAttributes로 둔다.
  3. sole element가 ModuleRequest Record { [[Specifier]]: specifier, [[Attributes]]: attrs }인 List를 반환한다.
ExportDeclaration : export ExportFromClause FromClause ;
  1. specifierFromClauseSV로 둔다.
  2. sole element가 ModuleRequest Record { [[Specifier]]: specifier, [[Attributes]]: « » }인 List를 반환한다.
ExportDeclaration : export ExportFromClause FromClause WithClause ;
  1. specifierFromClauseSV로 둔다.
  2. attrsWithClauseWithClauseToAttributes로 둔다.
  3. sole element가 ModuleRequest Record { [[Specifier]]: specifier, [[Attributes]]: attrs }인 List를 반환한다.
ExportDeclaration : export NamedExports ; export VariableStatement export Declaration export default HoistableDeclaration export default ClassDeclaration export default AssignmentExpression ;
  1. 새 empty List를 반환한다.

16.2.1.5 Abstract Module Records

Module Record는 single module의 import와 export에 대한 structural information을 encapsulate합니다. 이 information은 connected module의 set의 import와 export를 link하는 데 사용됩니다. Module Record는 module을 evaluating할 때만 사용되는 네 개의 field를 include합니다.

specification 목적상 Module Record value는 Record specification type의 value이며, Module Record가 abstract 및 concrete subclass를 모두 가진 abstract class인 simple object-oriented hierarchy 안에 existing한다고 생각할 수 있습니다. 이 specification은 Cyclic Module Record라는 abstract subclass와 그 concrete subclass인 Source Text Module Record를 define합니다. 다른 specification 및 implementation은 자신이 defined한 alternative module definition facility에 corresponding하는 additional Module Record subclass를 define할 수 있습니다.

Module Record는 Table 39에 listed된 field를 define합니다. 모든 Module Definition subclass는 적어도 those field를 include합니다. Module Record는 또한 Table 40의 abstract method list를 define합니다. 모든 Module definition subclass는 these abstract method의 concrete implementation을 provide해야 합니다.

Table 39: Module Record Fields
Field Name Value Type Meaning
[[Realm]] a Realm Record 이 module이 created된 Realm입니다.
[[Environment]] a Module Environment Record or empty 이 module의 top level binding을 contain하는 Environment Record입니다. 이 field는 module이 linked될 때 set됩니다.
[[Namespace]] an Object or empty 이 module에 대해 created된 경우의 Module Namespace Object(28.3)입니다.
[[HostDefined]] anything (default value is undefined) module과 additional information을 associate해야 하는 host environment가 use하기 위해 reserved된 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.

모든 dependency를 recursively loading하여 linking을 위해 module을 prepare합니다.

이 specification 안에서는 다음 type에 definition이 있습니다; host는 own definition을 가진 additional type을 provide할 수 있습니다:
GetExportedNames ( [ exportStarSet ] )

The abstract method GetExportedNames takes optional argument exportStarSet (a List of Source Text Module Records) and returns a List of Strings.

이 module에서 directly 또는 indirectly exported되는 모든 name의 list를 반환합니다.

이 method를 invoking하기 전에 LoadRequestedModules는 successfully completed되어야 합니다.

이 specification 안에서는 다음 type에 definition이 있습니다; host는 own definition을 가진 additional type을 provide할 수 있습니다:
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이 exported한 name의 binding을 반환합니다. Binding은 { [[Module]]: Module Record, [[BindingName]]: String | namespace } form의 ResolvedBinding Record로 represented됩니다. export가 any module 안의 direct binding 없이 Module Namespace Object인 경우, [[BindingName]]namespace로 set됩니다. name이 resolved될 수 없으면 null을 반환하고, multiple binding이 found되면 ambiguous를 반환합니다.

이 operation이 specific exportName, resolveSet pair를 argument로 하여 called될 때마다 same result를 반환해야 합니다.

이 method를 invoking하기 전에 LoadRequestedModules는 successfully completed되어야 합니다.

이 specification 안에서는 다음 type에 definition이 있습니다; host는 own definition을 가진 additional type을 provide할 수 있습니다:
Evaluate ( )

The abstract method Evaluate takes no arguments and returns a Promise.

이 module 및 그 dependency의 evaluation을 위한 promise를 반환하며, successful evaluation 또는 이미 successfully evaluated된 경우 resolve하고, evaluation error 또는 이미 unsuccessfully evaluated된 경우 reject합니다. promise가 rejected되면, host는 promise rejection을 handle하고 evaluation error를 rethrow할 것으로 expected됩니다. 이 module이 Cyclic Module Record가 아닌 한, returned promise는 already settled되어야 합니다.

이 method를 invoking하기 전에 Link는 successfully completed되어야 합니다.

이 specification 안에서는 다음 type에 definition이 있습니다; host는 own definition을 가진 additional type을 provide할 수 있습니다:

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이 already settled promise를 return할 것임을 guarantee하는 경우, module을 synchronously evaluate합니다. It performs the following steps when called:

  1. Assert: moduleCyclic Module Record가 아니다.
  2. promisemodule.Evaluate()로 둔다.
  3. Assert: promise.[[PromiseState]]fulfilled 또는 rejected 중 하나이다.
  4. promise.[[PromiseState]]rejected이면, 다음을 수행한다.
    1. promise.[[PromiseIsHandled]]false이면, HostPromiseRejectionTracker(promise, "handle")를 수행한다.
    2. promise.[[PromiseIsHandled]]true로 설정한다.
    3. promise.[[PromiseResult]]를 Throw한다.
  5. unused를 반환한다.

16.2.1.6 Cyclic Module Records

Cyclic Module RecordCyclic Module Record type의 subclass인 다른 module과 dependency cycle에 participate할 수 있는 module에 대한 information을 represent하는 데 사용됩니다. Cyclic Module Record type의 subclass가 아닌 Module RecordSource Text Module Record와의 dependency cycle에 participate해서는 안 됩니다.

Table 39에 defined된 field에 addition하여 Cyclic Module RecordsTable 41에 listed된 additional field를 가집니다

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 전체에서 progress함에 따라 unlinked, linking, linked, evaluating, possibly evaluating-async, evaluated로(in that order) transition합니다. evaluating-async는 이 module이 asynchronous dependency의 completion 시 execute되도록 queued되어 있거나, [[HasTLA]] field가 true이고 executed되었으며 top-level completion을 pending 중인 module임을 indicate합니다.
[[EvaluationError]] a throw completion or empty evaluation 중에 occurred한 exception을 represent하는 throw completion입니다. exception이 occurred하지 않았거나 [[Status]]evaluated가 아니면 empty입니다.
[[DFSAncestorIndex]] an integer or empty LinkEvaluate 중에만 사용되는 auxiliary field입니다. [[Status]]linking 또는 evaluating 중 하나이면, 이것은 module의 depth-first traversal index이거나 same strongly connected component 안의 “earlier” module의 것입니다.
[[RequestedModules]] a List of ModuleRequest Records 이 module 안의 import와 associated된 ModuleRequest RecordList입니다. List는 import의 source text occurrence order입니다.
[[LoadedModules]] a List of LoadedModuleRequest Records 이 record가 represented하는 module이 relative import attribute와 함께 module importation을 request하기 위해 사용한 specifier string에서 resolved Module Record로의 map입니다. list는 ModuleRequestsEqual(r1, r2)이 true인 두 different Record r1r2를 contain하지 않습니다.
[[CycleRoot]] a Cyclic Module Record or empty cycle의 first visited module, strongly connected component의 root DFS ancestor입니다. cycle 안에 있지 않은 module의 경우, 이는 module 자체일 것입니다. Evaluate가 completed되면, module의 [[DFSAncestorIndex]]는 그 [[CycleRoot]]의 depth-first traversal index입니다.
[[HasTLA]] a Boolean 이 module이 individually asynchronous인지 여부입니다(예를 들어 top-level await를 contain하는 Source Text Module Record인 경우). asynchronous dependency를 가진다는 것이 이 field가 true임을 의미하지는 않습니다. 이 field는 module이 parsed된 후 change되어서는 안 됩니다.
[[AsyncEvaluationOrder]] unset, an integer, or done 이 field는 initially unset으로 set되며, fully synchronous module의 경우 unset으로 remain합니다. themselves asynchronous이거나 asynchronous dependency를 가진 module의 경우, 16.2.1.6.1.3.4에 의해 pending module의 execution이 queued되는 order를 determine하는 integer로 set됩니다. pending module이 successfully executed되면, field는 done으로 set됩니다.
[[TopLevelCapability]] a PromiseCapability Record or empty 이 module이 어떤 cycle의 [[CycleRoot]]이고, Evaluate()가 그 cycle 안의 어떤 module에 대해 called된 경우, 이 field는 entire evaluation에 대한 PromiseCapability Record를 contain합니다. 이는 Evaluate() abstract method에서 returned되는 Promise object를 settle하는 데 사용됩니다. 이 field는 그 module의 dependency에 대해서는 empty일 것이며, 단 those dependency 중 일부에 대해 top-level Evaluate()가 initiated된 경우는 제외합니다.
[[AsyncParentModules]] a List of Cyclic Module Records 이 module 또는 dependency가 [[HasTLA]] true를 가지고 execution이 in progress이면, top-level execution job에 대해 이 module의 parent importer를 track합니다. 이러한 parent module은 이 module이 successfully completed execution하기 전에 executing을 start하지 않습니다.
[[PendingAsyncDependencies]] an integer or empty 이 module이 asynchronous dependency를 가진 경우, 이 module을 위해 execute될 remaining asynchronous dependency module의 수를 track합니다. asynchronous dependency를 가진 module은 이 field가 0에 reach하고 execution error가 없을 때 executed됩니다.

Table 40에 defined된 method에 addition하여 Cyclic Module RecordsTable 42에 listed된 additional method를 가집니다:

Table 42: Additional Abstract Methods of Cyclic Module Records
Method Purpose Definitions
InitializeEnvironment ( )

The abstract method InitializeEnvironment takes no arguments and returns either a normal completion containing unused or a throw completion.

all imported binding을 resolving하는 것을 include하여 module의 Environment Record를 initialize하고, module의 execution context를 create합니다.
이 specification 안에서는 다음 type에 definition이 있습니다; host는 own definition을 가진 additional type을 provide할 수 있습니다:
ExecuteModule ( [ capability ] )

The abstract method ExecuteModule takes optional argument capability (a PromiseCapability Record) and returns either a normal completion containing unused or a throw completion.

module의 execution context 안에서 module의 code를 evaluate합니다. 이 module이 [[HasTLA]] 안에 true를 가지면, PromiseCapability Record가 argument로 passed되고, method는 given capability를 resolve하거나 reject할 것으로 expected됩니다. 이 경우 method는 exception을 throw해서는 안 되고, 필요하면 PromiseCapability Record를 reject해야 합니다.
이 specification 안에서는 다음 type에 definition이 있습니다; host는 own definition을 가진 additional type을 provide할 수 있습니다:

GraphLoadingState Record는 module graph의 loading process에 대한 information을 contain하는 Record입니다. HostLoadImportedModule call 이후 loading을 continue하는 데 사용됩니다. 각 GraphLoadingState RecordTable 43에 defined된 field를 가집니다:

Table 43: GraphLoadingState Record Fields
Field Name Value Type Meaning
[[PromiseCapability]] a PromiseCapability Record loading process가 finish될 때 resolve할 promise입니다.
[[IsLoading]] a Boolean loading process가 아직 successfully도 error로도 finish되지 않은 경우 true입니다.
[[PendingModulesCount]] a non-negative integer pending HostLoadImportedModule call의 수를 track합니다.
[[Visited]] a List of Cyclic Module Records circular dependency로 인한 infinite loop를 avoid하기 위해, current loading process에 의해 already loaded된 Cyclic Module Record의 list입니다.
[[HostDefined]] anything (default value is empty) LoadRequestedModules caller에서 HostLoadImportedModule로 pass할 host-defined data를 contain합니다.

16.2.1.6.1 Implementation of Module Record Abstract Methods

다음은 Table 40에 defined된 corresponding Module Record abstract method를 implement하는 Cyclic Module Record의 concrete method입니다.

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 Record[[LoadedModules]]를 populate합니다(work의 대부분은 auxiliary function InnerModuleLoading에 의해 done됩니다). HostLoadImportedModule hook에 passed되는 optional hostDefined parameter를 받습니다. It performs the following steps when called:

  1. hostDefined가 present하지 않으면, hostDefinedempty로 설정한다.
  2. promiseCapability를 ! NewPromiseCapability(%Promise%)로 둔다.
  3. stateGraphLoadingState Record { [[IsLoading]]: true, [[PendingModulesCount]]: 1, [[Visited]]: « », [[PromiseCapability]]: promiseCapability, [[HostDefined]]: hostDefined }로 둔다.
  4. InnerModuleLoading(state, module)을 수행한다.
  5. promiseCapability.[[Promise]]를 반환한다.
Note
hostDefined parameter는 imported module을 fetch하는 데 necessary한 additional information을 pass하는 데 사용될 수 있습니다. 예를 들어 HTML에서는 <link rel="preload" as="..."> tag에 대한 correct fetch destination을 set하는 데 사용됩니다. import() expression은 hostDefined parameter를 never set하지 않습니다.

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. LoadRequestedModulesmodule의 dependency graph에 대한 actual loading process를 recursively 수행하는 데 사용됩니다. It performs the following steps when called:

  1. Assert: state.[[IsLoading]]true이다.
  2. moduleCyclic Module Record이고, module.[[Status]]new이며, state.[[Visited]]module을 contain하지 않으면, 다음을 수행한다.
    1. modulestate.[[Visited]]에 append한다.
    2. requestedModulesCountmodule.[[RequestedModules]] 안의 element 수로 둔다.
    3. state.[[PendingModulesCount]]state.[[PendingModulesCount]] + requestedModulesCount로 설정한다.
    4. module.[[RequestedModules]]의 각 ModuleRequest Record request에 대해, 다음을 수행한다.
      1. AllImportAttributesSupported(request.[[Attributes]])가 false이면, 다음을 수행한다.
        1. errorThrowCompletion(newly created SyntaxError object)로 둔다.
        2. ContinueModuleLoading(state, error)를 수행한다.
      2. 그렇지 않고 module.[[LoadedModules]]ModuleRequestsEqual(record, request)이 trueLoadedModuleRequest Record record를 contain하면, 다음을 수행한다.
        1. InnerModuleLoading(state, record.[[Module]])을 수행한다.
      3. 그렇지 않으면,
        1. HostLoadImportedModule(module, request, state.[[HostDefined]], state)를 수행한다.
        2. NOTE: HostLoadImportedModuleFinishLoadingImportedModule을 call하며, 이는 ContinueModuleLoading을 통해 graph loading process에 re-enter한다.
      4. state.[[IsLoading]]false이면, unused를 반환한다.
  3. Assert: state.[[PendingModulesCount]] ≥ 1이다.
  4. state.[[PendingModulesCount]]state.[[PendingModulesCount]] - 1로 설정한다.
  5. state.[[PendingModulesCount]] = 0이면, 다음을 수행한다.
    1. state.[[IsLoading]]false로 설정한다.
    2. state.[[Visited]]의 각 Cyclic Module Record loaded에 대해, 다음을 수행한다.
      1. loaded.[[Status]]new이면, loaded.[[Status]]unlinked로 설정한다.
    3. Call(state.[[PromiseCapability]].[[Resolve]], undefined, « undefined »)를 수행한다.
  6. unused를 반환한다.

16.2.1.6.1.1.2 ContinueModuleLoading ( state, moduleCompletion )

The abstract operation ContinueModuleLoading takes arguments state (a GraphLoadingState Record) and moduleCompletion (either a normal completion containing a Module Record or a throw completion) and returns unused. HostLoadImportedModule call 이후 loading process에 re-enter하는 데 사용됩니다. It performs the following steps when called:

  1. state.[[IsLoading]]false이면, unused를 반환한다.
  2. moduleCompletionnormal completion이면, 다음을 수행한다.
    1. InnerModuleLoading(state, moduleCompletion.[[Value]])을 수행한다.
  3. 그렇지 않으면,
    1. state.[[IsLoading]]false로 설정한다.
    2. Call(state.[[PromiseCapability]].[[Reject]], undefined, « moduleCompletion.[[Value]] »)를 수행한다.
  4. unused를 반환한다.

16.2.1.6.1.2 Link ( )

The Link concrete method of a Cyclic Module Record module takes no arguments and returns either a normal completion containing unused or a throw completion. success 시, Link는 이 module의 [[Status]]unlinked에서 linked로 transition합니다. failure 시, exception이 thrown되고 이 module의 [[Status]]unlinked로 remain합니다. (work의 대부분은 auxiliary function InnerModuleLinking에 의해 done됩니다.) It performs the following steps when called:

  1. Assert: module.[[Status]]unlinked, linked, evaluating-async 또는 evaluated 중 하나이다.
  2. stack을 새로운 빈 List라고 하자.
  3. resultCompletion(InnerModuleLinking(module, stack, 0))이라고 하자.
  4. resultabrupt completion이면,
    1. stack의 각 Cyclic Module Record requiredModule에 대해 다음을 수행한다.
      1. Assert: requiredModule.[[Status]]linking이다.
      2. requiredModule.[[Status]]unlinked로 설정한다.
    2. Assert: module.[[Status]]unlinked이다.
    3. result를 반환한다.
  5. Assert: module.[[Status]]linked, evaluating-async 또는 evaluated 중 하나이다.
  6. Assert: stack은 비어 있다.
  7. unused를 반환한다.

16.2.1.6.1.2.1 InnerModuleLinking ( module, stack, index )

The abstract operation InnerModuleLinking takes arguments module (a Module Record), stack (a List of Cyclic Module Records), and index (a non-negative integer) and returns either a normal completion containing a non-negative integer or a throw completion. Linkmodule에 대한 actual linking process를 수행하고, dependency graph 안의 모든 다른 module에 대해 recursively 수행하는 데 사용됩니다. stackindex parameter와 module의 [[DFSAncestorIndex]] field는 depth-first search (DFS) traversal을 keep track합니다. 특히 [[DFSAncestorIndex]]는 strongly connected component (SCC)를 discover하는 데 사용되어, SCC 안의 모든 module이 together linked로 transition하도록 합니다. It performs the following steps when called:

  1. moduleCyclic Module Record가 아니면, 다음을 수행한다.
    1. module.Link()를 수행한다.
    2. index를 반환한다.
  2. module.[[Status]]linking, linked, evaluating-async, 또는 evaluated 중 하나이면, 다음을 수행한다.
    1. index를 반환한다.
  3. Assert: module.[[Status]]unlinked이다.
  4. module.[[Status]]linking으로 설정한다.
  5. moduleIndexindex로 둔다.
  6. module.[[DFSAncestorIndex]]index로 설정한다.
  7. indexindex + 1로 설정한다.
  8. modulestack에 append한다.
  9. module.[[RequestedModules]]의 각 ModuleRequest Record request에 대해, 다음을 수행한다.
    1. requiredModuleGetImportedModule(module, request)로 둔다.
    2. index를 ? InnerModuleLinking(requiredModule, stack, index)로 설정한다.
    3. requiredModuleCyclic Module Record이면, 다음을 수행한다.
      1. Assert: requiredModule.[[Status]]linking, linked, evaluating-async, 또는 evaluated 중 하나이다.
      2. Assert: requiredModule.[[Status]]linking인 것은 stackrequiredModule을 contain하는 경우에만, 그리고 그 경우에만 true이다.
      3. requiredModule.[[Status]]linking이면, 다음을 수행한다.
        1. module.[[DFSAncestorIndex]]min(module.[[DFSAncestorIndex]], requiredModule.[[DFSAncestorIndex]])로 설정한다.
  10. module.InitializeEnvironment()를 수행한다.
  11. Assert: modulestack 안에 exactly once occur한다.
  12. Assert: module.[[DFSAncestorIndex]]moduleIndex이다.
  13. module.[[DFSAncestorIndex]] = moduleIndex이면, 다음을 수행한다.
    1. donefalse로 둔다.
    2. Repeat, donefalse인 동안,
      1. requiredModulestack의 last element로 둔다.
      2. stack의 last element를 remove한다.
      3. Assert: requiredModuleCyclic Module Record이다.
      4. requiredModule.[[Status]]linked로 설정한다.
      5. requiredModulemodule이 same Module Record이면, donetrue로 설정한다.
  14. index를 반환한다.

16.2.1.6.1.3 Evaluate ( )

The Evaluate concrete method of a Cyclic Module Record module takes no arguments and returns a Promise. Evaluate는 이 module의 [[Status]]linked에서 evaluating-async 또는 evaluated로 transition합니다. given strongly connected component 안의 module에서 first time called되면, Evaluate는 module이 evaluating을 finished할 때 resolve되는 Promise를 create하고 반환합니다. 이 Promise는 component의 [[CycleRoot]][[TopLevelCapability]] field에 stored됩니다. component 안의 any module에 대한 future invocation of Evaluate는 same Promise를 반환합니다. (work의 대부분은 auxiliary function InnerModuleEvaluation에 의해 done됩니다.) It performs the following steps when called:

  1. Assert: 이 Evaluate 호출은 주변 agent 내의 다른 Evaluate 호출과 동시에 발생하고 있지 않다.
  2. Assert: module.[[Status]]linked, evaluating-async 또는 evaluated 중 하나이다.
  3. module.[[Status]]evaluating-async 또는 evaluated 중 하나이면,
    1. module.[[CycleRoot]]empty가 아니면,
      1. modulemodule.[[CycleRoot]]로 설정한다.
    2. 그렇지 않으면,
      1. Assert: module.[[Status]]evaluated이고 module.[[EvaluationError]]throw completion이다.
  4. module.[[TopLevelCapability]]empty가 아니면,
    1. module.[[TopLevelCapability]].[[Promise]]를 반환한다.
  5. stack을 새로운 빈 List라고 하자.
  6. promiseCapability를 ! NewPromiseCapability(%Promise%)라고 하자.
  7. module.[[TopLevelCapability]]promiseCapability로 설정한다.
  8. resultCompletion(InnerModuleEvaluation(module, stack, 0))이라고 하자.
  9. resultabrupt completion이면,
    1. stack의 각 Cyclic Module Record requiredModule에 대해 다음을 수행한다.
      1. Assert: requiredModule.[[Status]]evaluating이다.
      2. requiredModule.[[Status]]evaluated로 설정한다.
      3. requiredModule.[[EvaluationError]]result로 설정한다.
    2. Assert: module.[[Status]]evaluated이다.
    3. Assert: module.[[EvaluationError]]result는 같은 Completion Record이다.
    4. Call(promiseCapability.[[Reject]], undefined, « result.[[Value]] »)를 수행한다.
  10. 그렇지 않으면,
    1. Assert: module.[[Status]]evaluating-async 또는 evaluated 중 하나이다.
    2. Assert: module.[[EvaluationError]]empty이다.
    3. module.[[Status]]evaluated이면,
      1. Assert: module.[[AsyncEvaluationOrder]]unset 또는 done 중 하나이다.
      2. NOTE: module.[[AsyncEvaluationOrder]]module이 이미 평가되었고 그 평가가 비동기였던 경우에만 done이다.
      3. Call(promiseCapability.[[Resolve]], undefined, « undefined »)를 수행한다.
    4. Assert: stack은 비어 있다.
  11. promiseCapability.[[Promise]]를 반환한다.

16.2.1.6.1.3.1 InnerModuleEvaluation ( module, stack, index )

The abstract operation InnerModuleEvaluation takes arguments module (a Module Record), stack (a List of Cyclic Module Records), and index (a non-negative integer) and returns either a normal completion containing a non-negative integer or a throw completion. Evaluatemodule에 대한 actual evaluation process를 수행하고, dependency graph 안의 모든 다른 module에 대해 recursively 수행하는 데 사용됩니다. stackindex parameter와 module[[DFSAncestorIndex]] field는 InnerModuleLinking에서와 same way로 사용됩니다. It performs the following steps when called:

  1. moduleCyclic Module Record가 아니면, 다음을 수행한다.
    1. EvaluateModuleSync(module)을 수행한다.
    2. index를 반환한다.
  2. module.[[Status]]evaluating-async 또는 evaluated 중 하나이면, 다음을 수행한다.
    1. module.[[EvaluationError]]empty이면, index를 반환한다.
    2. module.[[EvaluationError]]를 반환한다.
  3. module.[[Status]]evaluating이면, index를 반환한다.
  4. Assert: module.[[Status]]linked이다.
  5. module.[[Status]]evaluating으로 설정한다.
  6. moduleIndexindex로 둔다.
  7. module.[[DFSAncestorIndex]]index로 설정한다.
  8. module.[[PendingAsyncDependencies]]를 0으로 설정한다.
  9. indexindex + 1로 설정한다.
  10. modulestack에 append한다.
  11. module.[[RequestedModules]]의 각 ModuleRequest Record request에 대해, 다음을 수행한다.
    1. requiredModuleGetImportedModule(module, request)로 둔다.
    2. index를 ? InnerModuleEvaluation(requiredModule, stack, index)로 설정한다.
    3. requiredModuleCyclic Module Record이면, 다음을 수행한다.
      1. Assert: requiredModule.[[Status]]evaluating, evaluating-async, 또는 evaluated 중 하나이다.
      2. Assert: requiredModule.[[Status]]evaluating인 것은 stackrequiredModule을 contain하는 경우에만, 그리고 그 경우에만 true이다.
      3. requiredModule.[[Status]]evaluating이면, 다음을 수행한다.
        1. module.[[DFSAncestorIndex]]min(module.[[DFSAncestorIndex]], requiredModule.[[DFSAncestorIndex]])로 설정한다.
      4. 그렇지 않으면,
        1. requiredModulerequiredModule.[[CycleRoot]]로 설정한다.
        2. Assert: requiredModule.[[Status]]evaluating-async 또는 evaluated 중 하나이다.
        3. requiredModule.[[EvaluationError]]empty가 아니면, ? requiredModule.[[EvaluationError]]를 반환한다.
      5. requiredModule.[[AsyncEvaluationOrder]]integer이면, 다음을 수행한다.
        1. module.[[PendingAsyncDependencies]]module.[[PendingAsyncDependencies]] + 1로 설정한다.
        2. modulerequiredModule.[[AsyncParentModules]]에 append한다.
  12. module.[[PendingAsyncDependencies]] > 0 또는 module.[[HasTLA]]true이면, 다음을 수행한다.
    1. Assert: module.[[AsyncEvaluationOrder]]unset이다.
    2. module.[[AsyncEvaluationOrder]]IncrementModuleAsyncEvaluationCount()로 설정한다.
    3. module.[[PendingAsyncDependencies]] = 0이면, ExecuteAsyncModule(module)을 수행한다.
  13. 그렇지 않으면,
    1. module.ExecuteModule()를 수행한다.
  14. Assert: modulestack 안에 exactly once occur한다.
  15. Assert: module.[[DFSAncestorIndex]]moduleIndex이다.
  16. module.[[DFSAncestorIndex]] = moduleIndex이면, 다음을 수행한다.
    1. donefalse로 둔다.
    2. Repeat, donefalse인 동안,
      1. requiredModulestack의 last element로 둔다.
      2. stack의 last element를 remove한다.
      3. Assert: requiredModuleCyclic Module Record이다.
      4. Assert: requiredModule.[[AsyncEvaluationOrder]]integer 또는 unset 중 하나이다.
      5. requiredModule.[[AsyncEvaluationOrder]]unset이면, requiredModule.[[Status]]evaluated로 설정한다.
      6. 그렇지 않으면, requiredModule.[[Status]]evaluating-async로 설정한다.
      7. requiredModulemodule이 same Module Record이면, donetrue로 설정한다.
      8. requiredModule.[[CycleRoot]]module로 설정한다.
  17. index를 반환한다.
Note 1

module은 InnerModuleEvaluation에 의해 traversed되는 동안 evaluating입니다. module은 execution completion 시 evaluated가 되거나, [[HasTLA]] field가 true이거나 asynchronous dependency를 가진 경우 execution 중 evaluating-async가 됩니다.

Note 2

asynchronous cycle의 module에 depending하는 any module은 that cycle이 evaluating이 아닐 때, 대신 [[CycleRoot]]를 통해 cycle root의 execution에 depend합니다. 이는 cycle state가 root module state를 통해 single strongly connected component로 treated될 수 있음을 ensure합니다.

16.2.1.6.1.3.2 ExecuteAsyncModule ( module )

The abstract operation ExecuteAsyncModule takes argument module (a Cyclic Module Record) and returns unused. It performs the following steps when called:

  1. Assert: module.[[Status]]evaluating 또는 evaluating-async 중 하나이다.
  2. Assert: module.[[HasTLA]]true이다.
  3. promiseCapability를 ! NewPromiseCapability(%Promise%)로 둔다.
  4. module을 capture하고 called될 때 다음 step을 수행하는 parameter가 없는 새 Abstract Closure fulfilledClosure를 둔다:
    1. AsyncModuleExecutionFulfilled(module)을 수행한다.
    2. NormalCompletion(undefined)를 반환한다.
  5. onFulfilledCreateBuiltinFunction(fulfilledClosure, 0, "", « »)로 둔다.
  6. module을 capture하고 called될 때 다음 step을 수행하는 parameter (error)를 가진 새 Abstract Closure rejectedClosure를 둔다:
    1. AsyncModuleExecutionRejected(module, error)를 수행한다.
    2. NormalCompletion(undefined)를 반환한다.
  7. onRejectedCreateBuiltinFunction(rejectedClosure, 0, "", « »)로 둔다.
  8. PerformPromiseThen(promiseCapability.[[Promise]], onFulfilled, onRejected)를 수행한다.
  9. module.ExecuteModule(promiseCapability)를 수행한다.
  10. unused를 반환한다.

16.2.1.6.1.3.3 GatherAvailableAncestors ( module, execList )

The abstract operation GatherAvailableAncestors takes arguments module (a Cyclic Module Record) and execList (a List of Cyclic Module Records) and returns unused. It performs the following steps when called:

  1. module.[[AsyncParentModules]]의 각 Cyclic Module Record ancestorModule에 대해, 다음을 수행한다.
    1. execListancestorModule을 contain하지 않고 ancestorModule.[[CycleRoot]].[[EvaluationError]]empty이면, 다음을 수행한다.
      1. Assert: ancestorModule.[[Status]]evaluating-async이다.
      2. Assert: ancestorModule.[[EvaluationError]]empty이다.
      3. Assert: ancestorModule.[[AsyncEvaluationOrder]]integer이다.
      4. Assert: ancestorModule.[[PendingAsyncDependencies]] > 0이다.
      5. ancestorModule.[[PendingAsyncDependencies]]ancestorModule.[[PendingAsyncDependencies]] - 1로 설정한다.
      6. ancestorModule.[[PendingAsyncDependencies]] = 0이면, 다음을 수행한다.
        1. ancestorModuleexecList에 append한다.
        2. ancestorModule.[[HasTLA]]false이면, GatherAvailableAncestors(ancestorModule, execList)를 수행한다.
  2. unused를 반환한다.
Note

root module에 대한 asynchronous execution이 fulfilled될 때, 이 function은 이 completion에서 synchronously execute together할 수 있는 module의 list를 determine하여 execList에 populate합니다.

16.2.1.6.1.3.4 AsyncModuleExecutionFulfilled ( module )

The abstract operation AsyncModuleExecutionFulfilled takes argument module (a Cyclic Module Record) and returns unused. It performs the following steps when called:

  1. module.[[Status]]evaluated이면, 다음을 수행한다.
    1. Assert: module.[[EvaluationError]]empty가 아니다.
    2. unused를 반환한다.
  2. Assert: module.[[Status]]evaluating-async이다.
  3. Assert: module.[[AsyncEvaluationOrder]]integer이다.
  4. Assert: module.[[EvaluationError]]empty이다.
  5. module.[[AsyncEvaluationOrder]]done으로 설정한다.
  6. module.[[Status]]evaluated로 설정한다.
  7. module.[[TopLevelCapability]]empty가 아니면, 다음을 수행한다.
    1. Assert: module.[[CycleRoot]]module은 same Module Record이다.
    2. Call(module.[[TopLevelCapability]].[[Resolve]], undefined, « undefined »)를 수행한다.
  8. execList를 새 empty List로 둔다.
  9. GatherAvailableAncestors(module, execList)를 수행한다.
  10. Assert: execList의 모든 element는 [[AsyncEvaluationOrder]] field가 integer로 set되고, [[PendingAsyncDependencies]] field가 0으로 set되며, [[EvaluationError]] field가 empty로 set되어 있다.
  11. sortedExecListexecList의 element를 element로 가지고 그 [[AsyncEvaluationOrder]] field의 ascending order로 sorted된 List로 둔다.
  12. sortedExecList의 각 Cyclic Module Record ancestorModule에 대해, 다음을 수행한다.
    1. ancestorModule.[[Status]]evaluated이면, 다음을 수행한다.
      1. Assert: ancestorModule.[[EvaluationError]]empty가 아니다.
    2. 그렇지 않고 ancestorModule.[[HasTLA]]true이면, 다음을 수행한다.
      1. ExecuteAsyncModule(ancestorModule)을 수행한다.
    3. 그렇지 않으면,
      1. resultCompletion(ancestorModule.ExecuteModule())으로 둔다.
      2. resultabrupt completion이면, 다음을 수행한다.
        1. AsyncModuleExecutionRejected(ancestorModule, result.[[Value]])를 수행한다.
      3. 그렇지 않으면,
        1. ancestorModule.[[AsyncEvaluationOrder]]done으로 설정한다.
        2. ancestorModule.[[Status]]evaluated로 설정한다.
        3. ancestorModule.[[TopLevelCapability]]empty가 아니면, 다음을 수행한다.
          1. Assert: ancestorModule.[[CycleRoot]]ancestorModule은 same Module Record이다.
          2. Call(ancestorModule.[[TopLevelCapability]].[[Resolve]], undefined, « undefined »)를 수행한다.
  13. unused를 반환한다.

16.2.1.6.1.3.5 AsyncModuleExecutionRejected ( module, error )

The abstract operation AsyncModuleExecutionRejected takes arguments module (a Cyclic Module Record) and error (an ECMAScript language value) and returns unused. It performs the following steps when called:

  1. module.[[Status]]evaluated이면, 다음을 수행한다.
    1. Assert: module.[[EvaluationError]]empty가 아니다.
    2. unused를 반환한다.
  2. Assert: module.[[Status]]evaluating-async이다.
  3. Assert: module.[[AsyncEvaluationOrder]]integer이다.
  4. Assert: module.[[EvaluationError]]empty이다.
  5. module.[[EvaluationError]]ThrowCompletion(error)로 설정한다.
  6. module.[[Status]]evaluated로 설정한다.
  7. module.[[AsyncEvaluationOrder]]done으로 설정한다.
  8. NOTE: module.[[AsyncEvaluationOrder]]AsyncModuleExecutionFulfilled와의 symmetry를 위해 done으로 set된다. InnerModuleEvaluation에서 module의 [[AsyncEvaluationOrder]] internal slot의 value는 그 [[EvaluationError]] internal slot이 empty가 아닐 때 unused이다.
  9. module.[[TopLevelCapability]]empty가 아니면, 다음을 수행한다.
    1. Assert: module.[[CycleRoot]]module은 same Module Record이다.
    2. Call(module.[[TopLevelCapability]].[[Reject]], undefined, « error »)를 수행한다.
  10. module.[[AsyncParentModules]]의 각 Cyclic Module Record ancestorModule에 대해, 다음을 수행한다.
    1. AsyncModuleExecutionRejected(ancestorModule, error)를 수행한다.
  11. unused를 반환한다.

16.2.1.6.2 Example Cyclic Module Record Graphs

이 non-normative section은 몇 가지 common module graph의 linking 및 evaluation 예제를, error가 어떻게 occur할 수 있는지에 specific focus를 두고 제공합니다.

먼저 다음 simple module graph를 consider하십시오:

Figure 2: A simple module graph
module A가 module B에 depend하고, module B가 module C에 depend하는 module graph

먼저 error condition이 없다고 assume합시다. host가 first A.LoadRequestedModules()를 call하면, 이는 assumption에 따라 successfully complete하고, BC의 dependency도 respectively recursively load하며(각각 C와 none), 그런 다음 A.[[Status]] = B.[[Status]] = C.[[Status]] = unlinked로 set합니다. 그 다음 hostA.Link()를 call하면, 이는 (again by assumption) successfully complete하여 A.[[Status]] = B.[[Status]] = C.[[Status]] = linked가 됩니다. 이러한 preparatory step은 any time에 performed될 수 있습니다. Later, host가 module의 any possible side effect를 incur할 준비가 되면 A.Evaluate()를 call할 수 있으며, 이는 successfully complete하고 undefined로 resolving되는 Promise를 반환하며(again by assumption), recursively first C then B를 evaluated하게 됩니다. 이 point에서 각 module의 [[Status]]evaluated가 됩니다.

그 다음 A.LoadRequestedModules()의 successful call 이후 linking error가 involving된 case를 consider하십시오. CInnerModuleLinking이 succeeds하지만, thereafter B에 대해 fails하면, 예를 들어 C가 provide하지 않는 something을 import하기 때문이면, original A.Link()는 fail하고 AB[[Status]]unlinked로 remain합니다. 그러나 C[[Status]]linked가 되었습니다.

Finally, Link()의 successful call 이후 evaluation error가 involving된 case를 consider하십시오. CInnerModuleEvaluation이 succeeds하지만, thereafter B에 대해 fails하면, 예를 들어 B가 exception을 throw하는 code를 contain하기 때문이면, original A.Evaluate()는 fail하고 rejected Promise를 return합니다. resulting exception은 AB[[EvaluationError]] field 둘 다에 recorded되고, 그 [[Status]]evaluated가 됩니다. C 역시 evaluated가 되지만, AB와 달리 evaluation을 successfully completed했으므로 [[EvaluationError]] 없이 remain합니다. exception을 storing하면 host가 their Evaluate() method를 calling하여 A 또는 B를 reuse하려 할 때마다 same exception을 encounter하도록 ensure합니다. (HostCyclic Module Record를 reuse할 필요가 없습니다; similarly, host는 이러한 method에 의해 thrown된 exception object를 expose할 필요도 없습니다. 그러나 specification은 such use를 enable합니다.)

이제 다른 type의 error condition을 consider하십시오:

Figure 3: A module graph with an unresolvable module
module A가 missing(unresolvable) module에 depend하고, 그것이 ???로 represented된 module graph

이 scenario에서 module A는 어떤 다른 module에 대한 dependency를 declare하지만, 그 module에 대한 Module Record가 존재하지 않습니다. 즉, HostLoadImportedModule은 그것을 요청받았을 때 exception과 함께 FinishLoadingImportedModule을 call합니다. 이는 corresponding resource가 존재하지 않거나, resource는 존재하지만 resulting source text를 parse하려고 할 때 ParseModule이 some errors를 return하는 등 다양한 reason으로 occur할 수 있습니다. HostFinishLoadingImportedModule에 pass하는 completion을 통해 failure의 cause를 expose하도록 choose할 수 있습니다. 어떤 경우든, 이 exception은 loading failure를 cause하고, 그 결과 A[[Status]]new로 remain합니다.

여기서 loading, linking 및 evaluation error 사이의 difference는 다음 characteristic 때문입니다:

  • Evaluation은 side effect를 cause할 수 있으므로 only once performed되어야 합니다; 따라서 evaluation이 already performed되었는지, even unsuccessfully라도 remember하는 것이 important합니다. (error case에서는 subsequent Evaluate() call이 new one을 synthesize해야 하지 않도록 exception도 remember하는 것이 makes sense합니다.)
  • 반면 Linking은 side-effect-free이므로, fail하더라도 later time에 issue 없이 retried될 수 있습니다.
  • Loading은 host와 closely interact하며, 일부 host는 failed load를 retry하도록 users에게 allow하는 것이 desirable할 수 있습니다(예를 들어 failure가 temporarily bad network condition에 의해 caused된 경우).

이제 cycle을 가진 module graph를 consider하십시오:

Figure 4: A cyclic module graph
module A가 module B와 C에 depend하지만, module B도 module A에 depend하는 module graph

여기서는 entry point가 module A라고 assume하므로, hostA.LoadRequestedModules()를 calling하여 proceed하고, 이는 A에 대해 InnerModuleLoading을 수행합니다. 이것은 다시 BC에 대해 InnerModuleLoading을 call합니다. cycle 때문에, 이는 다시 A에 대해 InnerModuleLoading을 trigger하지만, 이 point에서는 A의 dependency loading이 이 LoadRequestedModules process 중에 already triggered되었으므로 no-op입니다. graph 안의 모든 module이 successfully loaded되면, their [[Status]]는 same time에 new에서 unlinked로 transition합니다.

Then hostA.Link()를 calling하여 proceed하고, 이는 A에 대해 InnerModuleLinking을 수행합니다. 이것은 다시 B에 대해 InnerModuleLinking을 call합니다. cycle 때문에, 이는 다시 A에 대해 InnerModuleLinking을 trigger하지만, 이 point에서는 A.[[Status]]가 already linking이므로 no-op입니다. control이 A로 돌아오고 InnerModuleLinkingC에 대해 triggered될 때 B.[[Status]] 자체는 linking으로 remain합니다. 이것이 return하여 C.[[Status]]linked가 된 후, AB는 together linking에서 linked로 transition합니다; 이것은 by design이며, they form a strongly connected component이기 때문입니다. 이 phase 중에는 module graph가 depth-first search로 traversed되므로 same SCC 안의 module status를 same time에 transition하는 것이 possible합니다.

cyclic module graph의 evaluation phase에 대해서도 success case에서는 analogous story가 occur합니다.

이제 A에 linking error가 있는 case를 consider하십시오; 예를 들어, it tries to import a binding from C that does not exist. 이 경우, above step은 still occur하며, InnerModuleLinking on A의 second call로부터 early return도 include합니다. 그러나 original InnerModuleLinking on A로 unwind back하면, InitializeEnvironment 중에, namely C.ResolveExport() right after에 fail합니다. thrown SyntaxError exception은 A.Link로 propagate되고, 이는 currently its stack에 있는 모든 module을 reset합니다(these are always exactly the modules that are still linking). 따라서 AB 둘 다 unlinked가 됩니다. Clinked로 left됨에 note하십시오.

Alternatively, A에 evaluation error가 있는 case를 consider하십시오; 예를 들어, 그 source code가 exception을 throw합니다. 이 경우, evaluation-time analogue of the above step은 still occur하며, InnerModuleEvaluation on A의 second call로부터 early return도 include합니다. 그러나 original InnerModuleEvaluation on A로 unwind back하면, assumption에 따라 fail합니다. thrown exception은 A.Evaluate()로 propagate되고, 이는 currently its stack에 있는 모든 module(즉, still evaluating인 module)에 error를 record할 뿐 아니라, top-level await를 contain하거나 depend하는 module을 위해 whole dependency graph를 통해 chain을 form하는 [[AsyncParentModules]]를 통해서도 record합니다. 이는 AsyncModuleExecutionRejected algorithm을 통해 이루어집니다. 따라서 AB 둘 다 evaluated가 되고 exception은 AB[[EvaluationError]] field 둘 다에 recorded되며, C[[EvaluationError]] 없이 evaluated로 left됩니다.

마지막으로, 모든 module이 asynchronously complete하는 cycle을 가진 module graph를 consider하십시오:

Figure 5: An asynchronous cyclic module graph
module A가 module B와 C에 depend하고, module B가 module D에 depend하며, module C가 module D와 E에 depend하고, module D가 module A에 depend하는 module graph

Loading 및 linking은 before와 같이 happen하며, 모든 module은 [[Status]]linked로 set되어 end up합니다.

A.Evaluate()를 calling하면 A, B, 및 D에 대해 InnerModuleEvaluation을 call하며, 이들은 모두 evaluating으로 transition합니다. Then InnerModuleEvaluationA에 대해 다시 called되며, it is already evaluating이므로 no-op입니다. 이 point에서 D.[[PendingAsyncDependencies]]는 0이므로 ExecuteAsyncModule(D)가 called되고, D의 asynchronous execution을 tracking하는 new PromiseCapability와 함께 D.ExecuteModule을 call합니다. B에 대한 InnerModuleEvaluation으로 unwind back하여 B.[[PendingAsyncDependencies]]를 1로 set하고 B.[[AsyncEvaluationOrder]]를 1로 set합니다. original InnerModuleEvaluation on A로 unwind back하여 A.[[PendingAsyncDependencies]]를 1로 set합니다. A의 dependency에 대한 loop의 next iteration에서, C 그리고 thus D(again no-op)와 E에 대해 InnerModuleEvaluation을 call합니다. E는 dependency가 없고 cycle의 part가 아니므로, D와 same manner로 ExecuteAsyncModule(E)을 call하고 E는 immediately stack에서 removed됩니다. 다시 한 번 C에 대한 InnerModuleEvaluation으로 unwind하여 C.[[AsyncEvaluationOrder]]를 3으로 set합니다. 이제 A의 dependency에 대한 loop를 finish하고, A.[[AsyncEvaluationOrder]]를 4로 set하며, entire strongly connected component를 stack에서 remove하여 모든 module을 at once evaluating-async로 transition합니다. 이 point에서 module의 field는 Table 44에 given된 것과 같습니다.

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가 first로 executing을 finish한다고 assume합시다. 그것이 happen하면, AsyncModuleExecutionFulfilled가 called되고, E.[[Status]]evaluated로 set되며 C.[[PendingAsyncDependencies]]는 decremented되어 1이 됩니다. updated module의 field는 Table 45에 given된 것과 같습니다.

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

D가 next로 finish합니다(아직 executing 중인 only module이었으므로). 그것이 happen하면, AsyncModuleExecutionFulfilled가 again called되고 D.[[Status]]evaluated로 set됩니다. execution에 available한 its ancestor는 B([[AsyncEvaluationOrder]]가 1)와 C([[AsyncEvaluationOrder]]가 3)이므로, B가 first handled됩니다: B.[[PendingAsyncDependencies]]는 decremented되어 0이 되고, ExecuteAsyncModuleB에 대해 called되며, it starts executing. C.[[PendingAsyncDependencies]]도 decremented되어 0이 되고, C가 executing을 start합니다(Bawait를 contain하면 potentially in parallel to B). updated module의 field는 Table 46에 given된 것과 같습니다.

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가 next로 executing을 finish한다고 assume합시다. 그것이 happen하면, AsyncModuleExecutionFulfilled가 again called되고, C.[[Status]]evaluated로 set되며 A.[[PendingAsyncDependencies]]는 decremented되어 1이 됩니다. updated module의 field는 Table 47에 given된 것과 같습니다.

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

Then, B가 executing을 finish합니다. 그것이 happen하면, AsyncModuleExecutionFulfilled가 again called되고 B.[[Status]]evaluated로 set됩니다. A.[[PendingAsyncDependencies]]는 decremented되어 0이 되므로, ExecuteAsyncModule이 called되고 it starts executing. updated module의 field는 Table 48에 given된 것과 같습니다.

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

Finally, A가 executing을 finish합니다. 그것이 happen하면, AsyncModuleExecutionFulfilled가 again called되고 A.[[Status]]evaluated로 set됩니다. 이 point에서 A.[[TopLevelCapability]] 안의 Promise(A.Evaluate()에서 returned된 것)가 resolved되고, 이것으로 이 module graph의 handling이 conclude됩니다. updated module의 field는 Table 49에 given된 것과 같습니다.

Table 49: Module fields after module A finishes executing
Field
Module
A
[[DFSAncestorIndex]] 0
[[Status]] evaluated
[[AsyncEvaluationOrder]] done
[[AsyncParentModules]] « »
[[PendingAsyncDependencies]] 0

Alternatively, CB가 executing을 finished하기 전에 execution에 fail하고 error를 return하는 failure case를 consider하십시오. 그것이 happen하면, AsyncModuleExecutionRejected가 called되고, 이는 C.[[Status]]evaluated로 set하고 C.[[EvaluationError]]를 error로 set합니다. 그런 다음 각 AsyncParentModules에 대해 AsyncModuleExecutionRejected를 수행하여 이 error를 all AsyncParentModules에 propagate합니다. updated module의 field는 Table 50에 given된 것과 같습니다.

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의 evaluation error

CC의 error와 함께 A에 대해 AsyncModuleExecutionRejected를 call하므로, AC와 same error로 rejected될 것입니다. A.[[Status]]evaluated로 set됩니다. 이 point에서 A.[[TopLevelCapability]] 안의 Promise(A.Evaluate()에서 returned된 것)가 rejected됩니다. updated module의 field는 Table 51에 given된 것과 같습니다.

Table 51: Module fields after module A is rejected
Field
Module
A
[[DFSAncestorIndex]] 0
[[Status]] evaluated
[[AsyncEvaluationOrder]] done
[[AsyncParentModules]] « »
[[PendingAsyncDependencies]] 0
[[EvaluationError]] CEvaluation Error

Then, B가 error 없이 executing을 finish합니다. 그것이 happen하면, AsyncModuleExecutionFulfilled가 again called되고 B.[[Status]]evaluated로 set됩니다. GatherAvailableAncestorsB에 대해 called됩니다. 그러나 A.[[CycleRoot]]는 evaluation error를 가진 A이므로, returned sortedExecList에 added되지 않고 AsyncModuleExecutionFulfilled는 further processing 없이 return합니다. B의 any future importer는 cycle root A에 set된 C의 evaluation error에서 B.[[CycleRoot]].[[EvaluationError]]의 rejection을 resolve할 것입니다. updated module의 field는 Table 52에 given된 것과 같습니다.

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]] CEvaluation Error empty

16.2.1.7 Source Text Module Records

Source Text Module Recordgoal symbol Module을 사용하여 parsed된 ECMAScript source text(11)에서 defined된 module에 대한 information을 represent하는 데 사용됩니다. 그 field는 module에 의해 imported 및 exported되는 name에 대한 digested information을 contain하며, 그 concrete method는 these digest를 사용하여 module을 link하고 evaluate합니다.

Source Text Module Record는 abstract Module Record type의 다른 subclass와 함께 module graph 안에 exist할 수 있고, Cyclic Module Record type의 다른 subclass와 함께 cycle에 participate할 수 있습니다.

Table 41에 defined된 field에 addition하여, Source Text Module RecordsTable 53에 listed된 additional field를 가집니다. 이러한 각 field는 initially ParseModule에서 set됩니다.

Table 53: Additional Fields of Source Text Module Records
Field Name Value Type Meaning
[[ECMAScriptCode]] a Parse Node Modulegoal symbol로 사용하여 이 module의 source text를 parsing한 result입니다.
[[Context]] an ECMAScript code execution context or empty 이 module과 associated된 execution context입니다. module의 environment가 initialized될 때까지 empty입니다.
[[ImportMeta]] an Object or empty import.meta meta property를 통해 exposed되는 object입니다. ECMAScript code에 의해 accessed될 때까지 empty입니다.
[[ImportEntries]] a List of ImportEntry Records 이 module의 code에서 derived된 ImportEntry record의 List입니다.
[[LocalExportEntries]] a List of ExportEntry Records module 안에서 occur하는 declaration에 corresponding하는, 이 module의 code에서 derived된 ExportEntry record의 List입니다.
[[IndirectExportEntries]] a List of ExportEntry Records module 안에서 occur하는 reexported import 또는 export * as namespace declaration에서의 export에 corresponding하는, 이 module의 code에서 derived된 ExportEntry record의 List입니다.
[[StarExportEntries]] a List of ExportEntry Records module 안에서 occur하는 export * declaration에 corresponding하는, 이 module의 code에서 derived된 ExportEntry record의 List이며, export * as namespace declaration은 include하지 않습니다.

ImportEntry Record는 single declarative import에 대한 information을 digest하는 Record입니다. 각 ImportEntry RecordTable 54에 defined된 field를 가집니다:

Table 54: ImportEntry Record Fields
Field Name Value Type Meaning
[[ModuleRequest]] a ModuleRequest Record ImportDeclarationModuleSpecifier와 import attribute를 represent하는 ModuleRequest Record입니다.
[[ImportName]] a String or namespace [[ModuleRequest]]가 identified하는 module에 의해 desired binding이 exported되는 name입니다. value namespace는 import request가 target module의 namespace object에 대한 것임을 indicate합니다.
[[LocalName]] a String importing module 안에서 imported value에 locally access하는 데 사용되는 name입니다.
Note 1

Table 55는 syntactic import form을 represent하는 데 사용되는 ImportEntry record field의 example을 제공합니다:

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는 created되지 않습니다.

ExportEntry Record는 single declarative export에 대한 information을 digest하는 Record입니다. 각 ExportEntry RecordTable 56에 defined된 field를 가집니다:

Table 56: ExportEntry Record Fields
Field Name Value Type Meaning
[[ExportName]] a String or null 이 module이 이 binding을 export하는 데 사용하는 name입니다.
[[ModuleRequest]] a ModuleRequest Record or null ExportDeclarationModuleSpecifier와 import attribute를 represent하는 ModuleRequest Record입니다. ExportDeclarationModuleSpecifier를 가지지 않으면 null입니다.
[[ImportName]] a String, null, namespace, or all-but-default [[ModuleRequest]]가 identified하는 module에 의해 desired binding이 exported되는 name입니다. ExportDeclarationModuleSpecifier를 가지지 않으면 null입니다. namespaceexport * as ns from "mod" declaration에 사용됩니다. all-but-defaultexport * from "mod" declaration에 사용됩니다.
[[LocalName]] a String or null importing module 안에서 exported value에 locally access하는 데 사용되는 name입니다. exported value가 module 안에서 locally accessible하지 않으면 null입니다.
Note 2

Table 57는 syntactic export form을 represent하는 데 사용되는 ExportEntry record field의 example을 제공합니다:

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

다음 definition은 Source Text Module Records에 필요한 concrete method 및 other abstract operation을 specify합니다

16.2.1.7.1 ParseModule ( sourceText, realm, hostDefined )

The abstract operation ParseModule takes arguments sourceText (a String or a sequence of Unicode code points), realm (a Realm Record), and hostDefined (anything) and returns a Source Text Module Record or a non-empty List of SyntaxError objects. sourceTextModule로 parsing한 result를 기반으로 Source Text Module Record를 create합니다. It performs the following steps when called:

  1. bodyParseText(sourceText, Module)라고 하자.
  2. body가 errors의 List이면, body를 반환한다.
  3. requestedModulesbodyModuleRequests라고 하자.
  4. importEntriesbodyImportEntries라고 하자.
  5. importedBoundNamesImportedLocalNames(importEntries)라고 하자.
  6. indirectExportEntries를 새로운 빈 List라고 하자.
  7. localExportEntries를 새로운 빈 List라고 하자.
  8. starExportEntries를 새로운 빈 List라고 하자.
  9. exportEntriesbodyExportEntries라고 하자.
  10. exportEntries의 각 ExportEntry Record exportEntry에 대해 다음을 수행한다.
    1. exportEntry.[[ModuleRequest]]null이면,
      1. importedBoundNamesexportEntry.[[LocalName]]을 포함하지 않으면,
        1. exportEntrylocalExportEntries에 추가한다.
      2. 그렇지 않으면,
        1. NOTE: 원래 다른 모듈에서 가져온 바인딩 또는 namespace 객체를 내보낼 때, ExportEntry Record는 바인딩 또는 namespace 객체가 가져온 뒤 내보내진 것이 아니라 원래 모듈에서 직접 다시 내보내졌다면 가졌을 형식과 일치하도록 다시 작성된다. 이를 통해 export * from을 통해 같은 이름으로 같은 바인딩 또는 namespace를 두 번 내보내면서 발생하는 충돌이 Source Text Module Records의 ResolveExport 구체 메서드9.e.iii 단계에서 모호한 것으로 처리되지 않고 무시될 수 있다.
        2. importEntry[[LocalName]]exportEntry.[[LocalName]]importEntries의 요소라고 하자.
        3. ExportEntry Record { [[ModuleRequest]]: importEntry.[[ModuleRequest]], [[ImportName]]: importEntry.[[ImportName]], [[LocalName]]: null, [[ExportName]]: exportEntry.[[ExportName]] }를 indirectExportEntries에 추가한다.
    2. 그렇지 않고 exportEntry.[[ImportName]]all-but-default이면,
      1. Assert: exportEntry.[[ExportName]]null이다.
      2. exportEntrystarExportEntries에 추가한다.
    3. 그렇지 않으면,
      1. exportEntryindirectExportEntries에 추가한다.
  11. asyncbody Contains await라고 하자.
  12. Source Text Module Record { [[Realm]]: realm, [[Environment]]: empty, [[Namespace]]: empty, [[CycleRoot]]: empty, [[HasTLA]]: async, [[AsyncEvaluationOrder]]: unset, [[TopLevelCapability]]: empty, [[AsyncParentModules]]: « », [[PendingAsyncDependencies]]: empty, [[Status]]: new, [[EvaluationError]]: empty, [[HostDefined]]: hostDefined, [[ECMAScriptCode]]: body, [[Context]]: empty, [[ImportMeta]]: empty, [[RequestedModules]]: requestedModules, [[LoadedModules]]: « », [[ImportEntries]]: importEntries, [[LocalExportEntries]]: localExportEntries, [[IndirectExportEntries]]: indirectExportEntries, [[StarExportEntries]]: starExportEntries, [[DFSAncestorIndex]]: empty }를 반환한다.
Note

implementation은 해당 module source text에 대한 ParseModule의 evaluation 전에 module source text를 parse하고 Early Error condition에 대해 analyse할 수 있습니다. 그러나 any error의 reporting은 이 specification이 실제로 해당 source text에 대해 ParseModule을 수행하는 point까지 deferred되어야 합니다.

16.2.1.7.2 Implementation of Module Record Abstract Methods

다음은 Table 40에 defined된 corresponding Module Record abstract method를 implement하는 Source Text Module Record의 concrete method입니다.

16.2.1.7.2.1 GetExportedNames ( [ exportStarSet ] )

The GetExportedNames concrete method of a Source Text Module Record module takes optional argument exportStarSet (a List of Source Text Module Records) and returns a List of Strings. It performs the following steps when called:

  1. Assert: module.[[Status]]new가 아니다.
  2. exportStarSet이 없으면, exportStarSet을 새로운 빈 List로 설정한다.
  3. exportStarSetmodule을 포함하면,
    1. Assert: export * 순환성의 시작점에 도달했다.
    2. 새로운 빈 List를 반환한다.
  4. moduleexportStarSet에 추가한다.
  5. exportedNames를 새로운 빈 List라고 하자.
  6. module.[[LocalExportEntries]]의 각 ExportEntry Record exportEntry에 대해 다음을 수행한다.
    1. Assert: module은 이 export에 대한 direct binding을 제공한다.
    2. Assert: exportEntry.[[ExportName]]null이 아니다.
    3. exportEntry.[[ExportName]]exportedNames에 추가한다.
  7. module.[[IndirectExportEntries]]의 각 ExportEntry Record exportEntry에 대해 다음을 수행한다.
    1. Assert: module은 이 export에 대한 특정 binding을 가져온다.
    2. Assert: exportEntry.[[ExportName]]null이 아니다.
    3. exportEntry.[[ExportName]]exportedNames에 추가한다.
  8. module.[[StarExportEntries]]의 각 ExportEntry Record exportEntry에 대해 다음을 수행한다.
    1. Assert: exportEntry.[[ModuleRequest]]null이 아니다.
    2. requestedModuleGetImportedModule(module, exportEntry.[[ModuleRequest]])라고 하자.
    3. starNamesrequestedModule.GetExportedNames(exportStarSet)라고 하자.
    4. starNames의 각 요소 name에 대해 다음을 수행한다.
      1. name"default"가 아니면,
        1. exportedNamesname을 포함하지 않으면,
          1. nameexportedNames에 추가한다.
  9. exportedNames를 반환한다.
Note

GetExportedNames는 ambiguous star export binding을 가진 name에 대해 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가 represented하는 module일 수도 있고, 그 module에 의해 imported된 다른 module일 수도 있습니다. parameter resolveSet은 unresolved circular import/export path를 detect하는 데 사용됩니다. specific Module RecordexportName으로 구성된 pair가 resolveSet 안에 already 있으면, import circularity가 encountered된 것입니다. ResolveExport를 recursively calling하기 전에, moduleexportName으로 구성된 pair가 resolveSet에 added됩니다.

defining module이 found되면, ResolvedBinding Record { [[Module]], [[BindingName]] }이 returned됩니다. 이 record는 originally requested export의 resolved binding을 identify합니다. 단, this is the export of a namespace with no local binding인 경우 [[BindingName]]namespace로 set됩니다. definition이 found되지 않았거나 request가 circular로 found되면 null이 returned됩니다. request가 ambiguous로 found되면 ambiguous가 returned됩니다.

It performs the following steps when called:

  1. Assert: module.[[Status]]new가 아니다.
  2. resolveSet이 없으면, resolveSet을 새로운 빈 List로 설정한다.
  3. resolveSet의 각 Record { [[Module]], [[ExportName]] } record에 대해 다음을 수행한다.
    1. modulerecord.[[Module]]이 같은 Module Record이고 exportNamerecord.[[ExportName]]이면,
      1. Assert: 이것은 순환 import 요청이다.
      2. null을 반환한다.
  4. Record { [[Module]]: module, [[ExportName]]: exportName }를 resolveSet에 추가한다.
  5. module.[[LocalExportEntries]]의 각 ExportEntry Record exportEntry에 대해 다음을 수행한다.
    1. exportEntry.[[ExportName]]exportName이면,
      1. Assert: module은 이 export에 대한 direct binding을 제공한다.
      2. ResolvedBinding Record { [[Module]]: module, [[BindingName]]: exportEntry.[[LocalName]] }를 반환한다.
  6. module.[[IndirectExportEntries]]의 각 ExportEntry Record exportEntry에 대해 다음을 수행한다.
    1. exportEntry.[[ExportName]]exportName이면,
      1. Assert: exportEntry.[[ModuleRequest]]null이 아니다.
      2. importedModuleGetImportedModule(module, exportEntry.[[ModuleRequest]])라고 하자.
      3. exportEntry.[[ImportName]]namespace이면,
        1. Assert: module은 이 export에 대한 direct binding을 제공하지 않는다.
        2. ResolvedBinding Record { [[Module]]: importedModule, [[BindingName]]: namespace }를 반환한다.
      4. Assert: module은 이 export에 대한 특정 binding을 가져온다.
      5. Assert: exportEntry.[[ImportName]]은 String이다.
      6. importedModule.ResolveExport(exportEntry.[[ImportName]], resolveSet)를 반환한다.
  7. exportName"default"이면,
    1. Assert: default export는 이 모듈에 의해 명시적으로 정의되지 않았다.
    2. null을 반환한다.
    3. NOTE: default export는 export * from "mod" 선언에 의해 제공될 수 없다.
  8. starResolutionnull이라고 하자.
  9. module.[[StarExportEntries]]의 각 ExportEntry Record exportEntry에 대해 다음을 수행한다.
    1. Assert: exportEntry.[[ModuleRequest]]null이 아니다.
    2. importedModuleGetImportedModule(module, exportEntry.[[ModuleRequest]])라고 하자.
    3. resolutionimportedModule.ResolveExport(exportName, resolveSet)라고 하자.
    4. resolutionambiguous이면, ambiguous를 반환한다.
    5. resolutionnull이 아니면,
      1. Assert: resolutionResolvedBinding Record이다.
      2. starResolutionnull이면,
        1. starResolutionresolution으로 설정한다.
      3. 그렇지 않으면,
        1. Assert: 요청된 이름을 포함하는 * export가 둘 이상 있다.
        2. resolution.[[Module]]starResolution.[[Module]]이 같은 Module Record가 아니면, ambiguous를 반환한다.
        3. resolution.[[BindingName]]starResolution.[[BindingName]]이 아니면, ambiguous를 반환한다.
  10. starResolution을 반환한다.

16.2.1.7.3 Implementation of Cyclic Module Record Abstract Methods

다음은 Table 42에 defined된 corresponding Cyclic Module Record abstract method를 implement하는 Source Text Module Record의 concrete method입니다.

16.2.1.7.3.1 InitializeEnvironment ( )

The InitializeEnvironment concrete method of a Source Text Module Record module takes no arguments and returns either a normal completion containing unused or a throw completion. It performs the following steps when called:

  1. module.[[IndirectExportEntries]]의 각 ExportEntry Record exportEntry에 대해 다음을 수행한다.
    1. Assert: exportEntry.[[ExportName]]null이 아니다.
    2. resolutionmodule.ResolveExport(exportEntry.[[ExportName]])라고 하자.
    3. resolutionnull 또는 ambiguous 중 하나이면, SyntaxError 예외를 던진다.
    4. Assert: resolutionResolvedBinding Record이다.
  2. Assert: module의 모든 named export는 resolve 가능하다.
  3. realmmodule.[[Realm]]이라고 하자.
  4. Assert: realmundefined가 아니다.
  5. envRecordNewModuleEnvironment(realm.[[GlobalEnv]])라고 하자.
  6. module.[[Environment]]envRecord로 설정한다.
  7. module.[[ImportEntries]]의 각 ImportEntry Record importEntry에 대해 다음을 수행한다.
    1. importedModuleGetImportedModule(module, importEntry.[[ModuleRequest]])라고 하자.
    2. importEntry.[[ImportName]]namespace이면,
      1. namespaceGetModuleNamespace(importedModule)라고 하자.
      2. envRecord.CreateImmutableBinding(importEntry.[[LocalName]], true)를 수행한다.
      3. envRecord.InitializeBinding(importEntry.[[LocalName]], namespace)를 수행한다.
    3. 그렇지 않으면,
      1. Assert: importEntry.[[ImportName]]은 String이다.
      2. resolutionimportedModule.ResolveExport(importEntry.[[ImportName]])라고 하자.
      3. resolutionnull 또는 ambiguous 중 하나이면, SyntaxError 예외를 던진다.
      4. resolution.[[BindingName]]namespace이면,
        1. namespaceGetModuleNamespace(resolution.[[Module]])라고 하자.
        2. envRecord.CreateImmutableBinding(importEntry.[[LocalName]], true)를 수행한다.
        3. envRecord.InitializeBinding(importEntry.[[LocalName]], namespace)를 수행한다.
      5. 그렇지 않으면,
        1. CreateImportBinding(envRecord, importEntry.[[LocalName]], resolution.[[Module]], resolution.[[BindingName]])을 수행한다.
  8. moduleContext를 새로운 ECMAScript code execution context라고 하자.
  9. moduleContext의 Function을 null로 설정한다.
  10. Assert: module.[[Realm]]undefined가 아니다.
  11. moduleContextRealmmodule.[[Realm]]으로 설정한다.
  12. moduleContext의 ScriptOrModule을 module로 설정한다.
  13. moduleContext의 VariableEnvironment를 module.[[Environment]]로 설정한다.
  14. moduleContext의 LexicalEnvironment를 module.[[Environment]]로 설정한다.
  15. moduleContext의 PrivateEnvironment를 null로 설정한다.
  16. module.[[Context]]moduleContext로 설정한다.
  17. moduleContextexecution context stack에 push한다. moduleContext는 이제 실행 중인 실행 컨텍스트이다.
  18. codemodule.[[ECMAScriptCode]]라고 하자.
  19. variableDeclscodeVarScopedDeclarations라고 하자.
  20. declaredVariableNames를 새로운 빈 List라고 하자.
  21. variableDecls의 각 요소 variableDecl에 대해 다음을 수행한다.
    1. variableDeclBoundNames의 각 요소 name에 대해 다음을 수행한다.
      1. declaredVariableNamesname을 포함하지 않으면,
        1. envRecord.CreateMutableBinding(name, false)를 수행한다.
        2. envRecord.InitializeBinding(name, undefined)를 수행한다.
        3. namedeclaredVariableNames에 추가한다.
  22. lexicalDeclscodeLexicallyScopedDeclarations라고 하자.
  23. privateEnvnull이라고 하자.
  24. lexicalDecls의 각 요소 lexicalDecl에 대해 다음을 수행한다.
    1. lexicalDeclBoundNames의 각 요소 name에 대해 다음을 수행한다.
      1. lexicalDeclIsConstantDeclarationtrue이면,
        1. envRecord.CreateImmutableBinding(name, true)를 수행한다.
      2. 그렇지 않으면,
        1. envRecord.CreateMutableBinding(name, false)를 수행한다.
      3. lexicalDeclFunctionDeclaration, GeneratorDeclaration, AsyncFunctionDeclaration 또는 AsyncGeneratorDeclaration 중 하나이면,
        1. funcObjlexicalDeclInstantiateFunctionObject에 인수 envRecordprivateEnv를 전달한 결과라고 하자.
        2. envRecord.InitializeBinding(name, funcObj)를 수행한다.
  25. moduleContextexecution context stack에서 제거한다.
  26. unused를 반환한다.

16.2.1.7.3.2 ExecuteModule ( [ capability ] )

The ExecuteModule concrete method of a Source Text Module Record module takes optional argument capability (a PromiseCapability Record) and returns either a normal completion containing unused or a throw completion. It performs the following steps when called:

  1. 단언: module은 링크되었고 그 module environment의 선언들은 인스턴스화되었다.
  2. moduleContextmodule.[[Context]]로 둔다.
  3. module.[[HasTLA]]false이면,
    1. 단언: capability는 존재하지 않는다.
    2. envmodule.[[Environment]]로 둔다.
    3. 실행 중인 실행 컨텍스트를 일시 중단한다.
    4. moduleContext를 실행 컨텍스트 스택에 push한다. moduleContext는 이제 실행 중인 실행 컨텍스트이다.
    5. resultmodule.[[ECMAScriptCode]]EvaluationCompletion으로 둔다.
    6. resultCompletion(DisposeResources(env.[[DisposableResourceStack]], result))로 설정한다.
    7. moduleContext를 일시 중단하고 실행 컨텍스트 스택에서 제거한다.
    8. 이제 실행 컨텍스트 스택의 맨 위에 있는 컨텍스트를 실행 중인 실행 컨텍스트로 재개한다.
    9. result가 abrupt 완료이면,
      1. result를 반환한다.
  4. 그렇지 않으면,
    1. 단언: capabilityPromiseCapability Record이다.
    2. AsyncBlockStart(capability, module.[[ECMAScriptCode]], moduleContext)를 수행한다.
  5. unused를 반환한다.

16.2.1.8 Synthetic Module Records

Synthetic Module Record는 specification에 의해 defined된 module에 대한 information을 represent하는 데 사용됩니다. 그 exported name은 creation 시 statically defined되며, 그 corresponding value는 SetSyntheticModuleExport를 사용하여 시간이 지나며 change될 수 있습니다. import나 dependency는 없습니다.

Note
Synthetic Module Record는 다양한 module type을 defining하는 데 사용될 수 있습니다: 예를 들어 JSON modules 또는 CSS modules.

Table 39에 defined된 field에 addition하여 Synthetic Module Records는 Table 58에 listed된 additional field를 가집니다.

Table 58: Additional Fields of Synthetic Module Records
Field Name Value Type Meaning
[[ExportNames]] a List of Strings module의 export name입니다. 이 list는 duplicate를 contain하지 않습니다.
[[EvaluationSteps]] an Abstract Closure module의 evaluation 시 수행할 initialization logic이며, Synthetic Module Record를 its sole argument로 받습니다. 이는 [[ExportNames]]를 modify해서는 안 됩니다. abrupt completion을 return할 수 있습니다.

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가 defaultExportSynthetic Module Record를 create합니다. It performs the following steps when called:

  1. realm을 current Realm Record로 둔다.
  2. defaultExport를 capture하고 called될 때 다음 step을 수행하는 parameter (module)를 가진 새 Abstract Closure setDefaultExport를 둔다:
    1. SetSyntheticModuleExport(module, "default", defaultExport)를 수행한다.
    2. NormalCompletion(unused)를 반환한다.
  3. Synthetic Module Record { [[Realm]]: realm, [[Environment]]: empty, [[Namespace]]: empty, [[HostDefined]]: undefined, [[ExportNames]]: « "default" », [[EvaluationSteps]]: setDefaultExport }를 반환한다.

16.2.1.8.2 ParseJSONModule ( source )

The abstract operation ParseJSONModule takes argument source (a String) and returns either a normal completion containing a Synthetic Module Record, or a throw completion. It performs the following steps when called:

  1. parseResult를 ? ParseJSON(source)로 둔다.
  2. CreateDefaultExportSyntheticModule(parseResult.[[Value]])를 반환한다.

16.2.1.8.3 SetSyntheticModuleExport ( module, exportName, exportValue )

The abstract operation SetSyntheticModuleExport takes arguments module (a Synthetic Module Record), exportName (a String), and exportValue (an ECMAScript language value) and returns unused. Synthetic Module Record의 existing export에 대한 exported value를 set하거나 change하는 데 사용될 수 있습니다. It performs the following steps when called:

  1. Assert: module.[[ExportNames]]exportName을 contain한다.
  2. envRecordmodule.[[Environment]]로 둔다.
  3. Assert: envRecordempty가 아니다.
  4. envRecord.SetMutableBinding(exportName, exportValue, true)를 수행한다.
  5. unused를 반환한다.

16.2.1.8.4 Implementation of Module Record Abstract Methods

다음은 Table 40에 defined된 corresponding Module Record abstract method를 implement하는 Synthetic Module Record의 concrete method입니다.

16.2.1.8.4.1 LoadRequestedModules ( [ hostDefined ] )

The LoadRequestedModules concrete method of a Synthetic Module Record module takes optional argument hostDefined (anything) and returns a Promise. It performs the following steps when called:

  1. NOTE: LoadRequestedModules의 이 implementation은 hostDefined를 사용하지 않는다.
  2. PromiseResolve(%Promise%, undefined)를 반환한다.
Note
Synthetic Module Records는 dependency를 가지지 않습니다.

16.2.1.8.4.2 GetExportedNames ( [ exportStarSet ] )

The GetExportedNames concrete method of a Synthetic Module Record module takes optional argument exportStarSet (a List of Source Text Module Records) and returns a List of Strings. It performs the following steps when called:

  1. NOTE: GetExportedNames의 이 implementation은 exportStarSet을 사용하지 않는다.
  2. module.[[ExportNames]]를 반환한다.

16.2.1.8.4.3 ResolveExport ( exportName [ , resolveSet ] )

The ResolveExport concrete method of a Synthetic Module Record module takes argument exportName (a String) and optional argument resolveSet (a List of Records with fields [[Module]] (a Module Record) and [[ExportName]] (a String)) and returns a ResolvedBinding Record, null, or ambiguous. It performs the following steps when called:

  1. NOTE: ResolveExport의 이 implementation은 resolveSet을 사용하지 않는다.
  2. module.[[ExportNames]]exportName을 contain하지 않으면, null을 반환한다.
  3. ResolvedBinding Record { [[Module]]: module, [[BindingName]]: exportName }을 반환한다.

16.2.1.8.4.4 Link ( )

The Link concrete method of a Synthetic Module Record module takes no arguments and returns a normal completion containing unused. It performs the following steps when called:

  1. realmmodule.[[Realm]]로 둔다.
  2. envRecordNewModuleEnvironment(realm.[[GlobalEnv]])로 둔다.
  3. module.[[Environment]]envRecord로 설정한다.
  4. module.[[ExportNames]]의 각 String exportName에 대해, 다음을 수행한다.
    1. envRecord.CreateMutableBinding(exportName, false)를 수행한다.
    2. envRecord.InitializeBinding(exportName, undefined)를 수행한다.
  5. NormalCompletion(unused)를 반환한다.

16.2.1.8.4.5 Evaluate ( )

The Evaluate concrete method of a Synthetic Module Record module takes no arguments and returns a Promise. It performs the following steps when called:

  1. moduleContext를 새 ECMAScript code execution context로 둔다.
  2. moduleContext의 Function을 null로 설정한다.
  3. moduleContextRealmmodule.[[Realm]]로 설정한다.
  4. moduleContext의 ScriptOrModule을 module로 설정한다.
  5. moduleContext의 VariableEnvironment를 module.[[Environment]]로 설정한다.
  6. moduleContext의 LexicalEnvironment를 module.[[Environment]]로 설정한다.
  7. running execution context를 suspend한다.
  8. moduleContextexecution context stack에 push한다; moduleContext는 이제 running execution context이다.
  9. stepsmodule.[[EvaluationSteps]]로 둔다.
  10. resultCompletion(steps(module))로 둔다.
  11. moduleContext를 suspend하고 execution context stack에서 remove한다.
  12. execution context stack의 top에 now 있는 context를 running execution context로 resume한다.
  13. promiseCapability를 ! NewPromiseCapability(%Promise%)로 둔다.
  14. IfAbruptRejectPromise(result, promiseCapability)를 수행한다.
  15. Call(promiseCapability.[[Resolve]], undefined, « undefined »)를 수행한다.
  16. promiseCapability.[[Promise]]를 반환한다.

16.2.1.9 GetImportedModule ( referrer, request )

The abstract operation GetImportedModule takes arguments referrer (a Cyclic Module Record) and request (a ModuleRequest Record) and returns a Module Record. It performs the following steps when called:

  1. recordsModuleRequestsEqual(r, request)이 truereferrer.[[LoadedModules]]의 각 LoadedModuleRequest Record r로 구성된 List로 둔다.
  2. Assert: this abstract operation을 invoking하기 전에 LoadRequestedModulesreferrer에서 successfully completed되었으므로, records는 exactly one element를 가진다.
  3. recordrecords의 sole element로 둔다.
  4. record.[[Module]]을 반환한다.

16.2.1.10 HostLoadImportedModule ( referrer, moduleRequest, hostDefined, payload )

The host-defined abstract operation HostLoadImportedModule takes arguments referrer (a Script Record, a Cyclic Module Record, or a Realm Record), moduleRequest (a ModuleRequest Record), hostDefined (anything), and payload (a GraphLoadingState Record or a PromiseCapability Record) and returns unused.

Note 1

referrerRealm Record일 수 있는 경우의 example은 web browser host입니다. 거기서 user가 다음에 의해 given된 control을 click하면

<button type="button" onclick="import('./foo.mjs')">Click me</button>

import() expression이 run되는 time에는 active script 또는 module이 없을 것입니다. More generally, 이는 hostnull ScriptOrModule component를 가진 execution contextexecution context stack에 push하는 any situation에서 happen할 수 있습니다.

HostLoadImportedModule의 implementation은 다음 requirements에 conform해야 합니다:

performed되는 actual process는 host-defined이지만, typically appropriate Module Record를 load하는 데 necessary한 whatever I/O operation을 performing하는 것으로 구성됩니다. Multiple different (referrer, moduleRequest.[[Specifier]], moduleRequest.[[Attributes]]) triple이 same Module Record instance에 map될 수 있습니다. actual mapping semantics는 host-defined이지만 typically normalization process가 mapping process의 part로 specifier에 applied됩니다. typical normalization process는 relative 및 abbreviated path specifier의 expansion과 같은 action을 include할 것입니다.

Note 2

above text는 hosttype: "json"으로 imported된 JSON module을 support할 것을 require하지만(그리고 HostLoadImportedModule이 normally complete하는 경우), type: "json" 없이 imported된 JSON module을 host가 supporting하는 것을 prohibit하지 않습니다.

16.2.1.11 FinishLoadingImportedModule ( referrer, moduleRequest, payload, result )

The abstract operation FinishLoadingImportedModule takes arguments referrer (a Script Record, a Cyclic Module Record, or a Realm Record), moduleRequest (a ModuleRequest Record), payload (a GraphLoadingState Record or a PromiseCapability Record), and result (either a normal completion containing a Module Record or a throw completion) and returns unused. It performs the following steps when called:

  1. resultnormal completion이면, 다음을 수행한다.
    1. referrer.[[LoadedModules]]ModuleRequestsEqual(record, moduleRequest)이 trueLoadedModuleRequest Record record를 contain하면, 다음을 수행한다.
      1. Assert: record.[[Module]]result.[[Value]]는 same Module Record이다.
    2. 그렇지 않으면,
      1. LoadedModuleRequest Record { [[Specifier]]: moduleRequest.[[Specifier]], [[Attributes]]: moduleRequest.[[Attributes]], [[Module]]: result.[[Value]] }를 referrer.[[LoadedModules]]에 append한다.
  2. payloadGraphLoadingState Record이면, 다음을 수행한다.
    1. ContinueModuleLoading(payload, result)를 수행한다.
  3. 그렇지 않으면,
    1. ContinueDynamicImport(payload, result)를 수행한다.
  4. unused를 반환한다.

16.2.1.12 AllImportAttributesSupported ( attrs )

The abstract operation AllImportAttributesSupported takes argument attrs (a List of ImportAttribute Records) and returns a Boolean. It performs the following steps when called:

  1. supportedHostGetSupportedImportAttributes()로 둔다.
  2. attrs의 각 ImportAttribute Record attr에 대해, 다음을 수행한다.
    1. supportedattr.[[Key]]를 contain하지 않으면, false를 반환한다.
  3. true를 반환한다.

16.2.1.12.1 HostGetSupportedImportAttributes ( )

The host-defined abstract operation HostGetSupportedImportAttributes takes no arguments and returns a List of Strings. host environment가 support하는 import attribute를 specify할 수 있게 합니다. supported key를 가진 attribute만 host에 provided됩니다.

HostGetSupportedImportAttributes의 implementation은 다음 requirements에 conform해야 합니다:

  • supported attribute를 각각 indicate하는 String의 List를 반환해야 합니다.
  • 이 operation이 called될 때마다, same contents를 same order로 가진 same List를 반환해야 합니다.

HostGetSupportedImportAttributes의 default implementation은 새 empty List를 반환하는 것입니다.

Note
host가 support하는 import attribute를 specify하도록 require하는 목적은, 모든 attribute를 host에 pass하고 host가 then 처리하려는 것을 choose하게 하는 대신, unsupported attribute가 different host across consistent way로 handled되도록 ensure하기 위한 것입니다.

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의 export를 represent하는 Module Namespace Object를 retrieve하며, first time requested되었을 때 lazily creating하고 future retrieval을 위해 module.[[Namespace]]에 storing합니다. It performs the following steps when called:

  1. Assert: moduleCyclic Module Record이면, module.[[Status]]new 또는 unlinked가 아니다.
  2. namespacemodule.[[Namespace]]로 둔다.
  3. namespaceempty이면, 다음을 수행한다.
    1. exportedNamesmodule.GetExportedNames()로 둔다.
    2. unambiguousNames를 새 empty List로 둔다.
    3. exportedNames의 각 element name에 대해, 다음을 수행한다.
      1. resolutionmodule.ResolveExport(name)으로 둔다.
      2. resolutionResolvedBinding Record이면, nameunambiguousNames에 append한다.
    4. namespaceModuleNamespaceCreate(module, unambiguousNames)로 설정한다.
  4. namespace를 반환한다.
Note

GetModuleNamespace는 never throws. 대신 unresolvable name은 이 point에서 simply namespace에서 excluded됩니다. 그것들이 explicitly requested되지 않는 ambiguous star export뿐인 경우가 아니면, later에 real linking error로 이어질 것입니다.

16.2.1.14 Runtime Semantics: Evaluation

Module : [empty]
  1. undefined를 반환한다.
ModuleBody : ModuleItemList
  1. resultCompletion(ModuleItemListEvaluation)으로 둔다.
  2. resultnormal completion이고 result.[[Value]]empty이면, 다음을 수행한다.
    1. undefined를 반환한다.
  3. result를 반환한다.
ModuleItemList : ModuleItemList ModuleItem
  1. slModuleItemListEvaluation으로 ? 둔다.
  2. sModuleItemEvaluationCompletion으로 둔다.
  3. UpdateEmpty(s, sl)를 반환한다.
Note

ModuleItemList의 value는 ModuleItemList 안의 last value-producing item의 value입니다.

ModuleItem : ImportDeclaration
  1. empty를 반환한다.

16.2.2 Imports

Syntax

ImportDeclaration : import ImportClause FromClause WithClauseopt ; import ModuleSpecifier WithClauseopt ; ImportClause : ImportedDefaultBinding NameSpaceImport NamedImports ImportedDefaultBinding , NameSpaceImport ImportedDefaultBinding , NamedImports ImportedDefaultBinding : ImportedBinding NameSpaceImport : * as ImportedBinding NamedImports : { } { ImportsList } { ImportsList , } FromClause : from ModuleSpecifier ImportsList : ImportSpecifier ImportsList , ImportSpecifier ImportSpecifier : ImportedBinding ModuleExportName as ImportedBinding ModuleSpecifier : StringLiteral ImportedBinding : BindingIdentifier[~Yield, +Await] WithClause : with { } with { WithEntries ,opt } WithEntries : AttributeKey : StringLiteral AttributeKey : StringLiteral , WithEntries AttributeKey : IdentifierName StringLiteral

16.2.2.1 Static Semantics: Early Errors

ModuleItem : ImportDeclaration WithClause : with { WithEntries ,opt }

16.2.2.2 Static Semantics: ImportEntries

The syntax-directed operation ImportEntries takes no arguments and returns a List of ImportEntry Records. It is defined piecewise over the following productions:

Module : [empty]
  1. 새 empty List를 반환한다.
ModuleItemList : ModuleItemList ModuleItem
  1. entries1ModuleItemListImportEntries로 둔다.
  2. entries2ModuleItemImportEntries로 둔다.
  3. entries1entries2list-concatenation을 반환한다.
ModuleItem : ExportDeclaration StatementListItem
  1. 새 empty List를 반환한다.
ImportDeclaration : import ImportClause FromClause WithClauseopt ;
  1. moduleImportDeclarationModuleRequests의 sole element로 둔다.
  2. argument module을 가진 ImportClauseImportEntriesForModule을 반환한다.
ImportDeclaration : import ModuleSpecifier WithClauseopt ;
  1. 새 empty List를 반환한다.

16.2.2.3 Static Semantics: ImportEntriesForModule

The syntax-directed operation ImportEntriesForModule takes argument module (a ModuleRequest Record) and returns a List of ImportEntry Records. It is defined piecewise over the following productions:

ImportClause : ImportedDefaultBinding , NameSpaceImport
  1. entries1을 argument module을 가진 ImportedDefaultBindingImportEntriesForModule로 둔다.
  2. entries2를 argument module을 가진 NameSpaceImportImportEntriesForModule로 둔다.
  3. entries1entries2list-concatenation을 반환한다.
ImportClause : ImportedDefaultBinding , NamedImports
  1. entries1을 argument module을 가진 ImportedDefaultBindingImportEntriesForModule로 둔다.
  2. entries2를 argument module을 가진 NamedImportsImportEntriesForModule로 둔다.
  3. entries1entries2list-concatenation을 반환한다.
ImportedDefaultBinding : ImportedBinding
  1. localNameImportedBindingBoundNames의 sole element로 둔다.
  2. defaultEntryImportEntry Record { [[ModuleRequest]]: module, [[ImportName]]: "default", [[LocalName]]: localName }로 둔다.
  3. « defaultEntry »를 반환한다.
NameSpaceImport : * as ImportedBinding
  1. localNameImportedBindingStringValue로 둔다.
  2. entryImportEntry Record { [[ModuleRequest]]: module, [[ImportName]]: namespace, [[LocalName]]: localName }로 둔다.
  3. « entry »를 반환한다.
NamedImports : { }
  1. 새 empty List를 반환한다.
ImportsList : ImportsList , ImportSpecifier
  1. specs1을 argument module을 가진 ImportsListImportEntriesForModule로 둔다.
  2. specs2를 argument module을 가진 ImportSpecifierImportEntriesForModule로 둔다.
  3. specs1specs2list-concatenation을 반환한다.
ImportSpecifier : ImportedBinding
  1. localNameImportedBindingBoundNames의 sole element로 둔다.
  2. entryImportEntry Record { [[ModuleRequest]]: module, [[ImportName]]: localName, [[LocalName]]: localName }로 둔다.
  3. « entry »를 반환한다.
ImportSpecifier : ModuleExportName as ImportedBinding
  1. importNameModuleExportNameStringValue로 둔다.
  2. localNameImportedBindingStringValue로 둔다.
  3. entryImportEntry Record { [[ModuleRequest]]: module, [[ImportName]]: importName, [[LocalName]]: localName }로 둔다.
  4. « entry »를 반환한다.

16.2.2.4 Static Semantics: WithClauseToAttributes

The syntax-directed operation WithClauseToAttributes takes no arguments and returns a List of ImportAttribute Records. It is defined piecewise over the following productions:

WithClause : with { }
  1. 새 empty List를 반환한다.
WithClause : with { WithEntries ,opt }
  1. attrsWithEntriesWithClauseToAttributes로 둔다.
  2. attrs를 각 such field의 value를 UTF-16 code unit value의 sequence로 treating하여 그 [[Key]] field의 lexicographic order에 따라 sort한다. NOTE: 이 sorting은 host가 attribute가 enumerated되는 order에 따라 behaviour를 changing하는 것이 prohibited된다는 점에서만 observable하다.
  3. attrs를 반환한다.
WithEntries : AttributeKey : StringLiteral
  1. keyAttributeKeyPropName으로 둔다.
  2. entryImportAttribute Record { [[Key]]: key, [[Value]]: StringLiteralSV }로 둔다.
  3. « entry »를 반환한다.
WithEntries : AttributeKey : StringLiteral , WithEntries
  1. keyAttributeKeyPropName으로 둔다.
  2. entryImportAttribute Record { [[Key]]: key, [[Value]]: StringLiteralSV }로 둔다.
  3. restWithEntriesWithClauseToAttributes로 둔다.
  4. « entry »와 restlist-concatenation을 반환한다.

16.2.3 Exports

Syntax

ExportDeclaration : export ExportFromClause FromClause WithClauseopt ; export NamedExports ; export VariableStatement[~Yield, +Await] export [lookahead ∉ { using, await }] Declaration[~Yield, +Await] export default HoistableDeclaration[~Yield, +Await, +Default] export default ClassDeclaration[~Yield, +Await, +Default] export default [lookahead ∉ { function, async [no LineTerminator here] function, class }] AssignmentExpression[+In, ~Yield, +Await] ; ExportFromClause : * * as ModuleExportName NamedExports NamedExports : { } { ExportsList } { ExportsList , } ExportsList : ExportSpecifier ExportsList , ExportSpecifier ExportSpecifier : ModuleExportName ModuleExportName as ModuleExportName

16.2.3.1 Static Semantics: Early Errors

ExportDeclaration : export NamedExports ; Note

above rule은 NamedExports의 각 ReferencedBindingsIdentifierReference로 treated됨을 의미합니다.

16.2.3.2 Static Semantics: ExportedBindings

The syntax-directed operation ExportedBindings takes no arguments and returns a List of Strings.

Note

ExportedBindings는 ModuleExportedNames와 explicitly associated된 locally bound name입니다.

It is defined piecewise over the following productions:

ModuleItemList : ModuleItemList ModuleItem
  1. names1ModuleItemListExportedBindings로 둔다.
  2. names2ModuleItemExportedBindings로 둔다.
  3. names1names2list-concatenation을 반환한다.
ModuleItem : ImportDeclaration StatementListItem
  1. 새 empty List를 반환한다.
ExportDeclaration : export ExportFromClause FromClause WithClauseopt ;
  1. 새 empty List를 반환한다.
ExportDeclaration : export NamedExports ;
  1. NamedExportsExportedBindings를 반환한다.
ExportDeclaration : export VariableStatement
  1. VariableStatementBoundNames를 반환한다.
ExportDeclaration : export Declaration
  1. DeclarationBoundNames를 반환한다.
ExportDeclaration : export default HoistableDeclaration export default ClassDeclaration export default AssignmentExpression ;
  1. this ExportDeclarationBoundNames를 반환한다.
NamedExports : { }
  1. 새 empty List를 반환한다.
ExportsList : ExportsList , ExportSpecifier
  1. names1ExportsListExportedBindings로 둔다.
  2. names2ExportSpecifierExportedBindings로 둔다.
  3. names1names2list-concatenation을 반환한다.
ExportSpecifier : ModuleExportName
  1. sole element가 ModuleExportNameStringValueList를 반환한다.
ExportSpecifier : ModuleExportName as ModuleExportName
  1. sole element가 first ModuleExportNameStringValueList를 반환한다.

16.2.3.3 Static Semantics: ExportedNames

The syntax-directed operation ExportedNames takes no arguments and returns a List of Strings.

Note

ExportedNames는 Module이 explicitly 그 local name binding 중 하나에 map하는 externally visible name입니다.

It is defined piecewise over the following productions:

ModuleItemList : ModuleItemList ModuleItem
  1. names1ModuleItemListExportedNames로 둔다.
  2. names2ModuleItemExportedNames로 둔다.
  3. names1names2list-concatenation을 반환한다.
ModuleItem : ExportDeclaration
  1. ExportDeclarationExportedNames를 반환한다.
ModuleItem : ImportDeclaration StatementListItem
  1. 새 empty List를 반환한다.
ExportDeclaration : export ExportFromClause FromClause WithClauseopt ;
  1. ExportFromClauseExportedNames를 반환한다.
ExportFromClause : *
  1. 새 empty List를 반환한다.
ExportFromClause : * as ModuleExportName
  1. sole element가 ModuleExportNameStringValueList를 반환한다.
ExportFromClause : NamedExports
  1. NamedExportsExportedNames를 반환한다.
ExportDeclaration : export VariableStatement
  1. VariableStatementBoundNames를 반환한다.
ExportDeclaration : export Declaration
  1. DeclarationBoundNames를 반환한다.
ExportDeclaration : export default HoistableDeclaration export default ClassDeclaration export default AssignmentExpression ;
  1. « "default" »를 반환한다.
NamedExports : { }
  1. 새 empty List를 반환한다.
ExportsList : ExportsList , ExportSpecifier
  1. names1ExportsListExportedNames로 둔다.
  2. names2ExportSpecifierExportedNames로 둔다.
  3. names1names2list-concatenation을 반환한다.
ExportSpecifier : ModuleExportName
  1. sole element가 ModuleExportNameStringValueList를 반환한다.
ExportSpecifier : ModuleExportName as ModuleExportName
  1. sole element가 second ModuleExportNameStringValueList를 반환한다.

16.2.3.4 Static Semantics: ExportEntries

The syntax-directed operation ExportEntries takes no arguments and returns a List of ExportEntry Records. It is defined piecewise over the following productions:

Module : [empty]
  1. 새 empty List를 반환한다.
ModuleItemList : ModuleItemList ModuleItem
  1. entries1ModuleItemListExportEntries로 둔다.
  2. entries2ModuleItemExportEntries로 둔다.
  3. entries1entries2list-concatenation을 반환한다.
ModuleItem : ImportDeclaration StatementListItem
  1. 새 empty List를 반환한다.
ExportDeclaration : export ExportFromClause FromClause WithClauseopt ;
  1. moduleExportDeclarationModuleRequests의 sole element로 둔다.
  2. argument module을 가진 ExportFromClauseExportEntriesForModule을 반환한다.
ExportDeclaration : export NamedExports ;
  1. argument null을 가진 NamedExportsExportEntriesForModule을 반환한다.
ExportDeclaration : export VariableStatement
  1. entries를 새 empty List로 둔다.
  2. namesVariableStatementBoundNames로 둔다.
  3. names의 각 element name에 대해, 다음을 수행한다.
    1. ExportEntry Record { [[ModuleRequest]]: null, [[ImportName]]: null, [[LocalName]]: name, [[ExportName]]: name }을 entries에 append한다.
  4. entries를 반환한다.
ExportDeclaration : export Declaration
  1. entries를 새 empty List로 둔다.
  2. namesDeclarationBoundNames로 둔다.
  3. names의 각 element name에 대해, 다음을 수행한다.
    1. ExportEntry Record { [[ModuleRequest]]: null, [[ImportName]]: null, [[LocalName]]: name, [[ExportName]]: name }을 entries에 append한다.
  4. entries를 반환한다.
ExportDeclaration : export default HoistableDeclaration
  1. namesHoistableDeclarationBoundNames로 둔다.
  2. localNamenames의 sole element로 둔다.
  3. sole element가 new ExportEntry Record { [[ModuleRequest]]: null, [[ImportName]]: null, [[LocalName]]: localName, [[ExportName]]: "default" }인 List를 반환한다.
ExportDeclaration : export default ClassDeclaration
  1. namesClassDeclarationBoundNames로 둔다.
  2. localNamenames의 sole element로 둔다.
  3. sole element가 new ExportEntry Record { [[ModuleRequest]]: null, [[ImportName]]: null, [[LocalName]]: localName, [[ExportName]]: "default" }인 List를 반환한다.
ExportDeclaration : export default AssignmentExpression ;
  1. entryExportEntry Record { [[ModuleRequest]]: null, [[ImportName]]: null, [[LocalName]]: "*default*", [[ExportName]]: "default" }로 둔다.
  2. « entry »를 반환한다.
Note

"*default*"는 anonymous default export value를 위한 synthetic name으로 이 specification 안에서 사용됩니다. more details는 this note를 참조하십시오.

16.2.3.5 Static Semantics: ExportEntriesForModule

The syntax-directed operation ExportEntriesForModule takes argument module (a ModuleRequest Record or null) and returns a List of ExportEntry Records. It is defined piecewise over the following productions:

ExportFromClause : *
  1. entryExportEntry Record { [[ModuleRequest]]: module, [[ImportName]]: all-but-default, [[LocalName]]: null, [[ExportName]]: null }로 둔다.
  2. « entry »를 반환한다.
ExportFromClause : * as ModuleExportName
  1. exportNameModuleExportNameStringValue로 둔다.
  2. entryExportEntry Record { [[ModuleRequest]]: module, [[ImportName]]: namespace, [[LocalName]]: null, [[ExportName]]: exportName }로 둔다.
  3. « entry »를 반환한다.
NamedExports : { }
  1. 새 empty List를 반환한다.
ExportsList : ExportsList , ExportSpecifier
  1. specs1을 argument module을 가진 ExportsListExportEntriesForModule로 둔다.
  2. specs2를 argument module을 가진 ExportSpecifierExportEntriesForModule로 둔다.
  3. specs1specs2list-concatenation을 반환한다.
ExportSpecifier : ModuleExportName
  1. sourceNameModuleExportNameStringValue로 둔다.
  2. modulenull이면, 다음을 수행한다.
    1. localNamesourceName으로 둔다.
    2. importNamenull로 둔다.
  3. 그렇지 않으면,
    1. localNamenull로 둔다.
    2. importNamesourceName으로 둔다.
  4. sole element가 new ExportEntry Record { [[ModuleRequest]]: module, [[ImportName]]: importName, [[LocalName]]: localName, [[ExportName]]: sourceName }인 List를 반환한다.
ExportSpecifier : ModuleExportName as ModuleExportName
  1. sourceName을 first ModuleExportNameStringValue로 둔다.
  2. exportName을 second ModuleExportNameStringValue로 둔다.
  3. modulenull이면, 다음을 수행한다.
    1. localNamesourceName으로 둔다.
    2. importNamenull로 둔다.
  4. 그렇지 않으면,
    1. localNamenull로 둔다.
    2. importNamesourceName으로 둔다.
  5. sole element가 new ExportEntry Record { [[ModuleRequest]]: module, [[ImportName]]: importName, [[LocalName]]: localName, [[ExportName]]: exportName }인 List를 반환한다.

16.2.3.6 Static Semantics: ReferencedBindings

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

NamedExports : { }
  1. 새 empty List를 반환한다.
ExportsList : ExportsList , ExportSpecifier
  1. names1ExportsListReferencedBindings로 둔다.
  2. names2ExportSpecifierReferencedBindings로 둔다.
  3. names1names2list-concatenation을 반환한다.
ExportSpecifier : ModuleExportName as ModuleExportName
  1. first ModuleExportNameReferencedBindings를 반환한다.
ModuleExportName : IdentifierName
  1. sole element가 IdentifierNameList를 반환한다.
ModuleExportName : StringLiteral
  1. sole element가 StringLiteralList를 반환한다.

16.2.3.7 Runtime Semantics: Evaluation

ExportDeclaration : export ExportFromClause FromClause WithClauseopt ; export NamedExports ;
  1. empty를 반환한다.
ExportDeclaration : export VariableStatement
  1. VariableStatementEvaluation을 ? 반환한다.
ExportDeclaration : export Declaration
  1. DeclarationEvaluation을 ? 반환한다.
ExportDeclaration : export default HoistableDeclaration
  1. HoistableDeclarationEvaluation을 ? 반환한다.
ExportDeclaration : export default ClassDeclaration
  1. valueClassDeclarationBindingClassDeclarationEvaluation으로 ? 둔다.
  2. classNameClassDeclarationBoundNames의 sole element로 둔다.
  3. className"*default*"이면, 다음을 수행한다.
    1. envRecordrunning execution context의 LexicalEnvironment로 둔다.
    2. InitializeBoundName("*default*", value, envRecord)를 수행한다.
  4. empty를 반환한다.
ExportDeclaration : export default AssignmentExpression ;
  1. IsAnonymousFunctionDefinition(AssignmentExpression)이 true이면, 다음을 수행한다.
    1. value를 argument "default"를 가진 AssignmentExpressionNamedEvaluation으로 ? 둔다.
  2. 그렇지 않으면,
    1. rhsAssignmentExpressionEvaluation으로 ? 둔다.
    2. value를 ? GetValue(rhs)로 둔다.
  3. envRecordrunning execution context의 LexicalEnvironment로 둔다.
  4. InitializeBoundName("*default*", value, envRecord)를 수행한다.
  5. empty를 반환한다.

17 Error Handling and Language Extensions

implementation은 대부분의 error를 relevant ECMAScript language construct가 evaluated되는 time에 report해야 합니다. early error는 error를 contain하는 Script 안의 어떤 construct도 evaluation되기 전에 detect 및 report될 수 있는 error입니다. early error가 존재하면 construct의 evaluation은 prevented됩니다. implementation은 Script 안의 early errorParseScript에서 해당 Script를 parsing하는 part로 report해야 합니다. Module 안의 early errorModule이 evaluated될 point에서 report되며 Module은 never initialized됩니다. eval code 안의 early erroreval이 called되는 time에 report되고 eval code의 evaluation을 prevent합니다. early error가 아닌 모든 error는 runtime error입니다.

implementation은 이 specification의 “Static Semantics: Early Errors” subclause에 listed된 condition의 occurrence를 early error로 report해야 합니다.

compiler가 construct가 어떤 circumstance에서도 error 없이 execute될 수 없음을 prove할 수 있더라도, implementation은 other kinds of errors를 early error로 treat해서는 안 됩니다. implementation은 such case에 early warning을 issue할 수 있지만, relevant construct가 actually executed될 때까지 error를 report해서는 안 됩니다.

implementation은 다음을 제외하고 specified된 대로 모든 error를 report해야 합니다:

17.1 Forbidden Extensions

implementation은 다음 ways로 이 specification을 extend해서는 안 됩니다:

18 ECMAScript Standard Built-in Objects

ECMAScript Script 또는 Module이 execution을 begin할 때마다 사용할 수 있는 certain built-in object가 있습니다. 하나인 global object는 executing program의 global environment의 part입니다. 다른 것들은 global object의 initial property로, 또는 accessible built-in object의 property로 indirect하게 accessible합니다.

달리 specified되지 않는 한, function으로 callable한 built-in object는 10.3에 described된 characteristic을 가진 built-in function object입니다. 달리 specified되지 않는 한, built-in object의 [[Extensible]] internal slot은 initially value true를 가집니다. 모든 built-in function object는 object가 initially created된 realmRealm Record를 value로 가지는 [[Realm]] internal slot을 가집니다.

많은 built-in object는 function입니다: arguments와 함께 invoked될 수 있습니다. 그중 일부는 further constructor입니다: new operator와 함께 사용되도록 intended된 function입니다. 각 built-in function에 대해, 이 specification은 해당 function에 required되는 arguments와 그 function object의 property를 describe합니다. 각 built-in constructor에 대해, 이 specification은 further 해당 constructor의 prototype object의 property와 그 constructor를 invoke하는 new expression에 의해 returned되는 specific object instance의 property를 describe합니다.

particular function의 description에 달리 specified되지 않는 한, built-in function 또는 constructor에 specified된 require 수보다 fewer arguments가 given되면, function 또는 constructor는 sufficient additional arguments가 given된 것과 exactly 같이 behave해야 하며, each such argument는 undefined value입니다. such missing arguments는 “not present”로 considered되고 specification algorithm에서 that manner로 identified될 수 있습니다. particular function의 description에서 “this value” 및 “NewTarget”이라는 term은 10.3에 given된 meaning을 가집니다.

particular function의 description에 달리 specified되지 않는 한, described built-in function 또는 constructor에 function이 allow하도록 specified된 것보다 more arguments가 given되면, extra arguments는 call에 의해 evaluated된 다음 function에 의해 ignored됩니다. 그러나 implementation은 such arguments와 관련한 implementation specific behaviour를 define할 수 있으며, 단 그 behaviour가 단순히 extra argument의 presence에 predicated된 TypeError exception의 throwing이어서는 안 됩니다.

Note 1

built-in function의 set에 additional capability를 add하는 implementation은 existing function에 new parameter를 add하는 것보다 new function을 add하는 방식으로 doing so할 것이 encouraged됩니다.

달리 specified되지 않는 한 모든 built-in function 및 모든 built-in constructorFunction prototype object, 즉 expression Function.prototype(20.2.3)의 initial value를 그 [[Prototype]] internal slot의 value로 가집니다.

달리 specified되지 않는 한 모든 built-in prototype object는 Object prototype object, 즉 expression Object.prototype(20.1.3)의 initial value를 그 [[Prototype]] internal slot의 value로 가집니다. 단 Object prototype object itself는 제외합니다.

이 specification이 algorithm step을 통해 built-in constructor의 behaviour를 define하는 경우, 그것이 [[Call]][[Construct]] 둘 다의 purposes에 대한 behaviour입니다. such algorithm이 두 case를 distinguish할 필요가 있으면, NewTarget이 undefined인지 check하며, 이는 [[Call]] invocation을 indicate합니다.

constructor로 identified되지 않은 built-in function object는 particular function의 description에 달리 specified되지 않는 한 [[Construct]] internal method를 implement하지 않습니다.

constructor가 아닌 built-in function object는 particular function의 description에 달리 specified되지 않는 한 "prototype" property를 가지지 않습니다.

이 specification에 defined된 각 built-in function은 CreateBuiltinFunction abstract operation(10.3.4)을 calling하여 created됩니다. lengthname parameter의 value는 below에서 discussed되는 "length""name" property의 initial value입니다. prefix parameter의 value도 similarly below에서 discussed됩니다.

constructor를 include한 모든 built-in function object는 non-negative integral Number인 value를 가진 "length" property를 가집니다. 달리 specified되지 않는 한, 이 value는 function description의 subclause heading에 shown된 required parameter의 수입니다. Optional parameter와 rest parameter는 parameter count에 included되지 않습니다.

Note 2

예를 들어, Array prototype object"map" property의 initial value인 function object는 subclause heading «Array.prototype.map (callback [ , thisArg])» 아래에 described되며, 여기에는 named argument callback과 thisArg 두 개가 shown되고 latter는 optional입니다; 따라서 그 function object"length" property의 value는 1𝔽입니다.

달리 specified되지 않는 한, built-in function object"length" property는 attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }를 가집니다.

constructor를 include한 모든 built-in function object는 String인 value를 가진 "name" property를 가집니다. 달리 specified되지 않는 한, 이 value는 이 specification에서 function에 given되는 name입니다. anonymous function으로 identified되는 function은 "name" property의 value로 empty String을 사용합니다. object의 property로 specified되는 function의 경우, name value는 function에 access하는 데 사용되는 property name string입니다. built-in property의 get 또는 set accessor function으로 specified되는 function은 CreateBuiltinFunction을 calling할 때 prefix parameter에 "get" 또는 "set"(respectively)이 passed됩니다.

"name" property의 value는 property key가 Symbol value인 각 built-in function에 대해 explicitly specified됩니다. such explicitly specified된 value가 prefix "get " 또는 "set "으로 start하고 그것이 specified되는 function이 built-in property의 get 또는 set accessor function인 경우, prefix 없는 value가 name parameter에 passed되고, value "get" 또는 "set"(respectively)이 CreateBuiltinFunction을 calling할 때 prefix parameter에 passed됩니다.

달리 specified되지 않는 한, built-in function object"name" property는 attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }를 가집니다.

clause 19부터 28까지 및 Annex B.2에 described된 every other data property는 달리 specified되지 않는 한 attributes { [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: true }를 가집니다.

clause 19부터 28까지 및 Annex B.2에 described된 every accessor property는 달리 specified되지 않는 한 attributes { [[Enumerable]]: false, [[Configurable]]: true }를 가집니다. get accessor function만 described된 경우, set accessor function은 default value인 undefined입니다. set accessor만 described된 경우 get accessor는 default value인 undefined입니다.

19 The Global Object

global object는:

19.1 Value Properties of the Global Object

19.1.1 globalThis

Realm Record realm 안의 global object"globalThis" property의 initial value는 realm.[[GlobalEnv]].[[GlobalThisValue]]입니다.

이 property는 attributes { [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: true }를 가집니다.

19.1.2 Infinity

global object"Infinity" property의 initial value는 +∞𝔽입니다(6.1.6.1 참조).

이 property는 attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }를 가집니다.

19.1.3 NaN

global object"NaN" property의 initial value는 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입니다.

called될 때 다음 step을 수행합니다:

  1. PerformEval(source, false, false)를 반환한다.

19.2.1.1 PerformEval ( source, strictCaller, direct )

The abstract operation PerformEval takes arguments source (an ECMAScript language value), strictCaller (a Boolean), and direct (a Boolean) and returns either a normal completion containing an ECMAScript language value or a throw completion. It performs the following steps when called:

  1. Assert: directfalse이면, strictCallerfalse이다.
  2. source가 String이 아니면, source를 반환한다.
  3. evalRealm을 current Realm Record로 둔다.
  4. NOTE: direct eval의 경우, evalRealmeval의 caller와 eval function 자체 둘 다의 realm이다.
  5. HostEnsureCanCompileStrings(evalRealm, « », source, direct)를 수행한다.
  6. inFuncfalse로 둔다.
  7. inMethodfalse로 둔다.
  8. inDerivedCtorfalse로 둔다.
  9. inClassFieldInitializerfalse로 둔다.
  10. directtrue이면, 다음을 수행한다.
    1. thisEnvRecordGetThisEnvironment()로 둔다.
    2. thisEnvRecordFunction Environment Record이면, 다음을 수행한다.
      1. functhisEnvRecord.[[FunctionObject]]로 둔다.
      2. inFunctrue로 설정한다.
      3. inMethodthisEnvRecord.HasSuperBinding()으로 설정한다.
      4. func.[[ConstructorKind]]derived이면, inDerivedCtortrue로 설정한다.
      5. classFieldInitializerNamefunc.[[ClassFieldInitializerName]]로 둔다.
      6. classFieldInitializerNameempty가 아니면, inClassFieldInitializertrue로 설정한다.
  11. implementation-defined order로 다음 substep을 수행하며, parsing과 error detection을 interleave할 수 있다:
    1. scriptParseText(source, Script)로 둔다.
    2. script가 error의 List이면, SyntaxError exception을 throw한다.
    3. script Contains ScriptBodyfalse이면, undefined를 반환한다.
    4. bodyscriptScriptBody로 둔다.
    5. inFuncfalse이고 body Contains NewTarget이면, SyntaxError exception을 throw한다.
    6. inMethodfalse이고 body Contains SuperProperty이면, SyntaxError exception을 throw한다.
    7. inDerivedCtorfalse이고 body Contains SuperCall이면, SyntaxError exception을 throw한다.
    8. inClassFieldInitializertrue이고 bodyContainsArgumentstrue이면, SyntaxError exception을 throw한다.
  12. strictCallertrue이면, strictEvaltrue로 둔다.
  13. 그렇지 않으면, strictEvalscriptScriptIsStrict로 둔다.
  14. runningContextrunning execution context로 둔다.
  15. NOTE: directtrue이면, runningContextdirect eval을 수행한 execution context일 것이다. directfalse이면, runningContexteval function invocation에 대한 execution context일 것이다.
  16. directtrue이면, 다음을 수행한다.
    1. lexicalEnvNewDeclarativeEnvironment(runningContext의 LexicalEnvironment)로 둔다.
    2. variableEnvrunningContext의 VariableEnvironment로 둔다.
    3. privateEnvrunningContext의 PrivateEnvironment로 둔다.
  17. 그렇지 않으면,
    1. lexicalEnvNewDeclarativeEnvironment(evalRealm.[[GlobalEnv]])로 둔다.
    2. variableEnvevalRealm.[[GlobalEnv]]로 둔다.
    3. privateEnvnull로 둔다.
  18. strictEvaltrue이면, variableEnvlexicalEnv로 설정한다.
  19. runningContext가 already suspended가 아니면, runningContext를 suspend한다.
  20. evalContext를 새 ECMAScript code execution context로 둔다.
  21. evalContext의 Function을 null로 설정한다.
  22. evalContextRealmevalRealm으로 설정한다.
  23. evalContext의 ScriptOrModule을 runningContext의 ScriptOrModule로 설정한다.
  24. evalContext의 VariableEnvironment를 variableEnv로 설정한다.
  25. evalContext의 LexicalEnvironment를 lexicalEnv로 설정한다.
  26. evalContext의 PrivateEnvironment를 privateEnv로 설정한다.
  27. evalContextexecution context stack에 push한다; evalContext는 이제 running execution context이다.
  28. resultCompletion(EvalDeclarationInstantiation(body, variableEnv, lexicalEnv, privateEnv, strictEval))으로 둔다.
  29. resultnormal completion이면, 다음을 수행한다.
    1. resultCompletion(bodyEvaluation)으로 설정한다.
  30. resultnormal completion이고 result.[[Value]]empty이면, 다음을 수행한다.
    1. resultNormalCompletion(undefined)로 설정한다.
  31. evalContext를 suspend하고 execution context stack에서 remove한다.
  32. execution context stack의 top에 now 있는 context를 running execution context로 resume한다.
  33. result를 반환한다.
Note

eval code는 calling context의 code나 eval code 중 하나가 strict mode code인 경우 eval을 invoked한 calling context의 variable environment 안에 variable 또는 function binding을 instantiate할 수 없습니다. 대신 such binding은 eval code에만 accessible한 새 VariableEnvironment 안에 instantiated됩니다. let, const, 또는 class declaration에 의해 introduced된 binding은 항상 새 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. 개발자가 string을 ECMAScript code로 interpret하고 evaluate할 수 있게 하는 certain ECMAScript function을 host environment가 block할 수 있게 합니다.

paramStrings는 function constructor 중 하나를 사용할 때 parameters list를 build하기 위해 together concatenated될 string들을 represent합니다. bodyString은 function body 또는 eval call에 passed된 string을 represent합니다. direct는 evaluation이 direct eval인지 여부를 signifies합니다.

HostEnsureCanCompileStrings의 default implementation은 NormalCompletion(unused)를 반환하는 것입니다.

19.2.1.3 EvalDeclarationInstantiation ( body, variableEnv, lexicalEnv, privateEnv, strict )

The abstract operation EvalDeclarationInstantiation takes arguments body (a ScriptBody Parse Node), variableEnv (an Environment Record), lexicalEnv (a Declarative Environment Record), privateEnv (a PrivateEnvironment Record or null), and strict (a Boolean) and returns either a normal completion containing unused or a throw completion. It performs the following steps when called:

  1. variableNamesbodyVarDeclaredNames라고 하자.
  2. variableDeclsbodyVarScopedDeclarations라고 하자.
  3. strictfalse이면,
    1. variableEnvGlobal Environment Record이면,
      1. variableNames의 각 요소 name에 대해 다음을 수행한다.
        1. HasLexicalDeclaration(variableEnv, name)이 true이면, SyntaxError 예외를 던진다.
        2. NOTE: eval은 전역 lexical 선언에 의해 가려질 전역 var 선언을 생성하지 않는다.
    2. thisEnvlexicalEnv라고 하자.
    3. Assert: 다음 루프는 종료된다.
    4. thisEnvvariableEnv가 같은 Environment Record가 아닌 동안 반복한다.
      1. thisEnvObject Environment Record가 아니면,
        1. NOTE: with 문장의 환경은 어떤 lexical 선언도 포함할 수 없으므로 var/let 호이스팅 충돌을 검사할 필요가 없다.
        2. variableNames의 각 요소 name에 대해 다음을 수행한다.
          1. thisEnv.HasBinding(name)이 true이면,
            1. host가 웹 브라우저이거나 그 밖에 Catch Blocks 안의 VariableStatements를 지원하면,
              1. thisEnvCatch 절에 대한 Environment Record가 아니면, SyntaxError 예외를 던진다.
            2. 그렇지 않으면,
              1. SyntaxError 예외를 던진다.
          2. NOTE: direct eval은 var 선언을 같은 이름의 lexical 선언 위로 호이스팅하지 않는다.
      2. thisEnvthisEnv.[[OuterEnv]]로 설정한다.
  4. privateIdentifiers를 새로운 빈 List라고 하자.
  5. pointerprivateEnv라고 하자.
  6. pointernull이 아닌 동안 반복한다.
    1. pointer.[[Names]]의 각 Private Name binding에 대해 다음을 수행한다.
      1. privateIdentifiersbinding.[[Description]]을 포함하지 않으면, binding.[[Description]]privateIdentifiers에 추가한다.
    2. pointerpointer.[[OuterPrivateEnvironment]]로 설정한다.
  7. bodyAllPrivateIdentifiersValid에 인수 privateIdentifiers를 전달한 결과가 false이면, SyntaxError 예외를 던진다.
  8. funcsToInitialize를 새로운 빈 List라고 하자.
  9. declaredFuncNames를 새로운 빈 List라고 하자.
  10. variableDecls의 각 요소 variableDecl에 대해, List의 역순으로 다음을 수행한다.
    1. variableDeclVariableDeclaration, ForBinding 또는 BindingIdentifier 중 어느 것도 아니면,
      1. Assert: variableDeclFunctionDeclaration, GeneratorDeclaration, AsyncFunctionDeclaration 또는 AsyncGeneratorDeclaration 중 하나이다.
      2. NOTE: 같은 이름에 대해 여러 함수 선언이 있으면, 마지막 선언이 사용된다.
      3. funcNamevariableDeclBoundNames의 유일한 요소라고 하자.
      4. declaredFuncNamesfuncName을 포함하지 않으면,
        1. variableEnvGlobal Environment Record이면,
          1. funcDefinable을 ? CanDeclareGlobalFunction(variableEnv, funcName)이라고 하자.
          2. funcDefinablefalse이면, TypeError 예외를 던진다.
        2. funcNamedeclaredFuncNames에 추가한다.
        3. variableDeclfuncsToInitialize의 첫 번째 요소로 삽입한다.
  11. declaredVariableNames를 새로운 빈 List라고 하자.
  12. variableDecls의 각 요소 variableDecl에 대해 다음을 수행한다.
    1. variableDeclVariableDeclaration, ForBinding 또는 BindingIdentifier 중 하나이면,
      1. variableDeclBoundNames의 각 String name에 대해 다음을 수행한다.
        1. declaredFuncNamesname을 포함하지 않으면,
          1. variableEnvGlobal Environment Record이면,
            1. variableDefinable을 ? CanDeclareGlobalVar(variableEnv, name)라고 하자.
            2. variableDefinablefalse이면, TypeError 예외를 던진다.
          2. declaredVariableNamesname을 포함하지 않으면,
            1. namedeclaredVariableNames에 추가한다.
  13. strictfalse이고 host가 웹 브라우저이거나 그 밖에 Block-Level Function Declarations Web Legacy Compatibility Semantics를 지원하면,
    1. declaredFuncOrVariableNamesdeclaredFuncNamesdeclaredVariableNameslist-concatenation이라고 하자.
    2. body Contains xtrueBlock, CaseClause 또는 DefaultClause xStatementList에 직접 포함된 각 FunctionDeclaration funcDecl에 대해 다음을 수행한다.
      1. funcNamefuncDeclBindingIdentifierStringValue라고 하자.
      2. FunctionDeclaration funcDeclfuncNameBindingIdentifier로 갖는 VariableStatement로 대체해도 body에 대한 Early Errors가 생성되지 않으면,
        1. bindingExistsfalse라고 하자.
        2. thisEnvlexicalEnv로 설정한다.
        3. Assert: 다음 루프는 종료된다.
        4. thisEnvvariableEnv가 아닌 동안 반복한다.
          1. thisEnvObject Environment Record가 아니면,
            1. thisEnv.HasBinding(funcName)이 true이면,
              1. host가 웹 브라우저이거나 그 밖에 Catch Blocks 안의 VariableStatements를 지원하면,
                1. thisEnvCatch 절에 대한 Environment Record가 아니면, bindingExiststrue로 설정한다.
              2. 그렇지 않으면,
                1. bindingExiststrue로 설정한다.
          2. thisEnvthisEnv.[[OuterEnv]]로 설정한다.
        5. bindingExistsfalse이고 variableEnvGlobal Environment Record이면,
          1. HasLexicalDeclaration(variableEnv, funcName)이 false이면,
            1. funcDefinable을 ? CanDeclareGlobalVar(variableEnv, funcName)라고 하자.
          2. 그렇지 않으면,
            1. funcDefinablefalse라고 하자.
        6. 그렇지 않으면,
          1. funcDefinabletrue라고 하자.
        7. bindingExistsfalse이고 funcDefinabletrue이면,
          1. declaredFuncOrVariableNamesfuncName을 포함하지 않으면,
            1. variableEnvGlobal Environment Record이면,
              1. CreateGlobalVarBinding(variableEnv, funcName, true)를 수행한다.
            2. 그렇지 않으면,
              1. bindingExists를 ! variableEnv.HasBinding(funcName)으로 설정한다.
              2. bindingExistsfalse이면,
                1. variableEnv.CreateMutableBinding(funcName, true)를 수행한다.
                2. variableEnv.InitializeBinding(funcName, undefined)를 수행한다.
            3. funcNamedeclaredFuncOrVariableNames에 추가한다.
          2. FunctionDeclaration funcDecl이 평가될 때, 15.2.6에 제공된 FunctionDeclaration Evaluation 알고리즘 대신 다음 단계를 수행한다.
            1. globalEnv를 실행 중인 실행 컨텍스트의 VariableEnvironment라고 하자.
            2. blockEnv를 실행 중인 실행 컨텍스트의 LexicalEnvironment라고 하자.
            3. funcObj를 ! blockEnv.GetBindingValue(funcName, false)라고 하자.
            4. globalEnv.SetMutableBinding(funcName, funcObj, false)를 수행한다.
            5. unused를 반환한다.
  14. NOTE: variableEnvGlobal Environment Record이고 전역 객체가 Proxy exotic object인 경우가 아니면, 이 알고리즘 단계 이후에는 abnormal termination이 발생하지 않는다.
  15. lexicalDeclsbodyLexicallyScopedDeclarations라고 하자.
  16. lexicalDecls의 각 요소 lexicalDecl에 대해 다음을 수행한다.
    1. NOTE: Lexically declared name은 여기서 인스턴스화만 되고 초기화되지는 않는다.
    2. lexicalDeclBoundNames의 각 요소 name에 대해 다음을 수행한다.
      1. lexicalDeclIsConstantDeclarationtrue이면,
        1. lexicalEnv.CreateImmutableBinding(name, true)를 수행한다.
      2. 그렇지 않으면,
        1. lexicalEnv.CreateMutableBinding(name, false)를 수행한다.
  17. funcsToInitialize의 각 Parse Node funcDecl에 대해 다음을 수행한다.
    1. funcNamefuncDeclBoundNames의 유일한 요소라고 하자.
    2. funcObjfuncDeclInstantiateFunctionObject에 인수 lexicalEnvprivateEnv를 전달한 결과라고 하자.
    3. variableEnvGlobal Environment Record이면,
      1. CreateGlobalFunctionBinding(variableEnv, funcName, funcObj, true)를 수행한다.
    4. 그렇지 않으면,
      1. bindingExists를 ! variableEnv.HasBinding(funcName)이라고 하자.
      2. bindingExistsfalse이면,
        1. NOTE: 다음 호출은 14 단계 이전의 검증 때문에 abrupt completion을 반환할 수 없다.
        2. variableEnv.CreateMutableBinding(funcName, true)를 수행한다.
        3. variableEnv.InitializeBinding(funcName, funcObj)를 수행한다.
      3. 그렇지 않으면,
        1. variableEnv.SetMutableBinding(funcName, funcObj, false)를 수행한다.
  18. declaredVariableNames의 각 String variableName에 대해 다음을 수행한다.
    1. variableEnvGlobal Environment Record이면,
      1. CreateGlobalVarBinding(variableEnv, variableName, true)를 수행한다.
    2. 그렇지 않으면,
      1. bindingExists를 ! variableEnv.HasBinding(variableName)이라고 하자.
      2. bindingExistsfalse이면,
        1. NOTE: 다음 호출은 14 단계 이전의 검증 때문에 abrupt completion을 반환할 수 없다.
        2. variableEnv.CreateMutableBinding(variableName, true)를 수행한다.
        3. variableEnv.InitializeBinding(variableName, undefined)를 수행한다.
  19. unused를 반환한다.

19.2.2 isFinite ( value )

이 function은 %isFinite% intrinsic object입니다.

called될 때 다음 step을 수행합니다:

  1. number를 ? ToNumber(value)로 둔다.
  2. numberfinite이면, true를 반환한다.
  3. false를 반환한다.

19.2.3 isNaN ( value )

이 function은 %isNaN% intrinsic object입니다.

called될 때 다음 step을 수행합니다:

  1. number를 ? ToNumber(value)로 둔다.
  2. numberNaN이면, true를 반환한다.
  3. false를 반환한다.
Note

ECMAScript code가 value XNaN인지 test하는 reliable way는 form X !== X의 expression입니다. result는 XNaN인 경우에만, 그리고 그 경우에만 true입니다.

19.2.4 parseFloat ( string )

이 function은 string argument의 contents를 decimal literal로 interpretation하여 dictated되는 Number value를 produce합니다.

이는 %parseFloat% intrinsic object입니다.

called될 때 다음 step을 수행합니다:

  1. inputString을 ? ToString(string)으로 둔다.
  2. trimmedString을 ! TrimString(inputString, start)로 둔다.
  3. trimmedStringToCodePoints(trimmedString)로 둔다.
  4. trimmedPrefixStrDecimalLiteral의 syntax를 satisfy하는 trimmed의 longest prefix로 둔다. 이는 trimmed 자체일 수도 있다. such prefix가 없으면, NaN을 반환한다.
  5. parsedNumberParseText(trimmedPrefix, StrDecimalLiteral)로 둔다.
  6. Assert: parsedNumberParse Node이다.
  7. parsedNumberStringNumericValue를 반환한다.
Note

이 function은 string의 leading portion만 Number value로 interpret할 수 있습니다; decimal literal의 notation의 part로 interpret될 수 없는 any code unit은 ignored되며, such code unit이 ignored되었다는 indication은 given되지 않습니다.

19.2.5 parseInt ( string, radix )

이 function은 specified된 radix에 따라 string의 contents를 interpretation하여 dictated되는 integral Number를 produce합니다. string 안의 leading white space는 ignored됩니다. radix가 0으로 coerces되면(undefined인 경우 등), number representation이 "0x" 또는 "0X"로 begins하는 경우를 제외하고 10으로 assumed되며, 그런 경우에는 16으로 assumed됩니다. radix가 16이면, number representation은 optionally "0x" 또는 "0X"로 begin할 수 있습니다.

이는 %parseInt% intrinsic object입니다.

called될 때 다음 step을 수행합니다:

  1. inputString을 ? ToString(string)으로 둔다.
  2. trimmedString을 ! TrimString(inputString, start)로 둔다.
  3. sign을 1로 둔다.
  4. trimmedString이 empty가 아니고 trimmedString의 first code unit이 code unit 0x002D (HYPHEN-MINUS)이면, sign을 -1로 설정한다.
  5. trimmedString이 empty가 아니고 trimmedString의 first code unit이 code unit 0x002B (PLUS SIGN) 또는 code unit 0x002D (HYPHEN-MINUS) 중 하나이면, trimmedString을 index 1부터의 trimmedStringsubstring으로 설정한다.
  6. radixMV(? ToInt32(radix))로 둔다.
  7. stripPrefixtrue로 둔다.
  8. radixMV ≠ 0이면, 다음을 수행한다.
    1. radixMV < 2 또는 radixMV > 36이면, NaN을 반환한다.
    2. radixMV ≠ 16이면, stripPrefixfalse로 설정한다.
  9. 그렇지 않으면,
    1. radixMV를 10으로 설정한다.
  10. stripPrefixtrue이면, 다음을 수행한다.
    1. trimmedString의 length가 ≥ 2이고 trimmedString의 first two code unit이 "0x" 또는 "0X" 중 하나이면, 다음을 수행한다.
      1. trimmedString을 index 2부터의 trimmedStringsubstring으로 설정한다.
      2. radixMV를 16으로 설정한다.
  11. trimmedString이 radix-radixMV digit이 아닌 code unit을 contain하면, endtrimmedString 안에서 first such code unit의 index로 둔다; 그렇지 않으면 endtrimmedString의 length로 둔다.
  12. numberString을 0부터 end까지의 trimmedStringsubstring으로 둔다.
  13. numberString이 empty이면, NaN을 반환한다.
  14. mathInt를 radix-radixMV notation으로 numberString에 의해 represented되는 integer value로 둔다. 여기서 A부터 Z까지와 a부터 z까지의 letters는 values 10 through 35를 가진 digits로 사용된다. (그러나 radixMV = 10이고 numberString이 20개보다 많은 significant digits를 contain하면, 20번째 이후의 every significant digit은 implementation의 option에 따라 0 digit으로 replaced될 수 있다; 그리고 radixMV가 2, 4, 8, 10, 16, 또는 32 중 하나가 아니면, mathInt는 radix-radixMV notation에서 numberString이 denoted하는 integer value를 representing하는 implementation-approximated integer일 수 있다.)
  15. mathInt = 0이면, 다음을 수행한다.
    1. sign = -1이면, -0𝔽를 반환한다.
    2. +0𝔽를 반환한다.
  16. 𝔽(sign × mathInt)를 반환한다.
Note

이 function은 string의 leading portion만 integer value로 interpret할 수 있습니다; integer의 notation의 part로 interpret될 수 없는 any code unit은 ignored되며, such code unit이 ignored되었다는 indication은 given되지 않습니다.

19.2.6 URI Handling Functions

Uniform Resource Identifier, 즉 URI는 Internet에서 resource(예: web page 또는 file)와 그것에 access하기 위한 transport protocol(예: HTTP 또는 FTP)을 identify하는 String입니다. ECMAScript language 자체는 이 section에 described된 것처럼 URI를 encode 및 decode하는 function을 제외하고 URI 사용을 위한 어떤 support도 provide하지 않습니다. encodeURIdecodeURI는 complete URI와 함께 work하도록 intended됩니다; 이들은 any reserved character가 special meaning(예: delimiter)을 가지도록 intended된다고 assume하므로 encoded되지 않습니다. encodeURIComponentdecodeURIComponent는 URI의 individual component와 함께 work하도록 intended됩니다; 이들은 any reserved character가 text를 represent하며 component가 complete URI의 part일 때 special meaning을 avoid하기 위해 encoded되어야 한다고 assume합니다.

Note 1

reserved character의 set은 RFC 2396에 based하며, 더 recent한 RFC 3986에 의해 introduced된 change를 reflect하지 않습니다.

Note 2

ECMAScript의 많은 implementation은 web page를 manipulate하는 additional function 및 method를 provide합니다; 이러한 function은 이 standard의 scope 밖입니다.

19.2.6.1 decodeURI ( encodedURI )

이 function은 encodeURI function에 의해 introduced될 수 있는 sort의 각 escape sequence와 UTF-8 encoding이 그것이 represent하는 code point의 UTF-16 encoding으로 replaced된 URI의 new version을 computes합니다. encodeURI에 의해 introduced될 수 없었던 escape sequence는 replaced되지 않습니다.

이는 %decodeURI% intrinsic object입니다.

called될 때 다음 step을 수행합니다:

  1. uriString을 ? ToString(encodedURI)로 둔다.
  2. preserveEscapeSet";/?:@&=+$,#"로 둔다.
  3. Decode(uriString, preserveEscapeSet)를 반환한다.

19.2.6.2 decodeURIComponent ( encodedURIComponent )

이 function은 encodeURIComponent function에 의해 introduced될 수 있는 sort의 각 escape sequence와 UTF-8 encoding이 그것이 represent하는 code point의 UTF-16 encoding으로 replaced된 URI의 new version을 computes합니다.

이는 %decodeURIComponent% intrinsic object입니다.

called될 때 다음 step을 수행합니다:

  1. componentString을 ? ToString(encodedURIComponent)으로 둔다.
  2. preserveEscapeSet을 empty String으로 둔다.
  3. Decode(componentString, preserveEscapeSet)를 반환한다.

19.2.6.3 encodeURI ( uri )

이 function은 certain code point의 각 instance가 code point의 UTF-8 encoding을 represent하는 one, two, three, or four escape sequence로 replaced된 UTF-16 encoded(6.1.4) URI의 new version을 computes합니다.

이는 %encodeURI% intrinsic object입니다.

called될 때 다음 step을 수행합니다:

  1. uriString을 ? ToString(uri)로 둔다.
  2. extraUnescaped";/?:@&=+$,#"로 둔다.
  3. Encode(uriString, extraUnescaped)를 반환한다.

19.2.6.4 encodeURIComponent ( uriComponent )

이 function은 certain code point의 각 instance가 code point의 UTF-8 encoding을 represent하는 one, two, three, or four escape sequence로 replaced된 UTF-16 encoded(6.1.4) URI의 new version을 computes합니다.

이는 %encodeURIComponent% intrinsic object입니다.

called될 때 다음 step을 수행합니다:

  1. componentString을 ? ToString(uriComponent)로 둔다.
  2. extraUnescaped를 empty String으로 둔다.
  3. Encode(componentString, extraUnescaped)를 반환한다.

19.2.6.5 Encode ( string, extraUnescaped )

The abstract operation Encode takes arguments string (a String) and extraUnescaped (a String) and returns either a normal completion containing a String or a throw completion. 6.1.4에 described된 것처럼 string을 UTF-16 encoded code point의 sequence로 interpreting하여 URI encoding과 escaping을 수행합니다. character가 RFC 2396에서 unreserved로 identified되거나 extraUnescaped 안에 appear하면, escaped되지 않습니다. It performs the following steps when called:

  1. lengthstring의 length로 둔다.
  2. result를 empty String으로 둔다.
  3. alwaysUnescaped를 ASCII word character와 "-.!~*'()"string-concatenation으로 둔다.
  4. unescapedSetalwaysUnescapedextraUnescapedstring-concatenation으로 둔다.
  5. k를 0으로 둔다.
  6. Repeat, k < length인 동안,
    1. codeUnitstring 안의 index k에 있는 code unit으로 둔다.
    2. unescapedSetcodeUnit을 contain하면, 다음을 수행한다.
      1. kk + 1로 설정한다.
      2. resultresultcodeUnitstring-concatenation으로 설정한다.
    3. 그렇지 않으면,
      1. codePointCodePointAt(string, k)로 둔다.
      2. codePoint.[[IsUnpairedSurrogate]]true이면, URIError exception을 throw한다.
      3. kk + codePoint.[[CodeUnitCount]]로 설정한다.
      4. octetscodePoint.[[CodePoint]]에 UTF-8 transformation을 applying하여 resulting되는 octet의 List로 둔다.
      5. octets의 각 element octet에 대해, 다음을 수행한다.
        1. hex를 uppercase hexadecimal number로 formatted된 octet의 String representation으로 둔다.
        2. resultresult, "%", 및 StringPad(hex, 2, "0", start)의 string-concatenation으로 설정한다.
  7. result를 반환한다.
Note

percent-encoding은 individual octet을 represent하는 데 사용되므로, single code point는 multiple consecutive escape sequence(그 8-bit UTF-8 code unit 각각에 대해 하나)로 expressed될 수 있습니다.

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. preserveEscapeSet 안의 Basic Latin character에 corresponding하는 any escape sequence를 preserving하면서 URI unescaping 및 decoding을 수행합니다. It performs the following steps when called:

  1. lengthstring의 length로 둔다.
  2. result를 empty String으로 둔다.
  3. k를 0으로 둔다.
  4. Repeat, k < length인 동안,
    1. codeUnitstring 안의 index k에 있는 code unit으로 둔다.
    2. segmentcodeUnit으로 둔다.
    3. codeUnit이 code unit 0x0025 (PERCENT SIGN)이면, 다음을 수행한다.
      1. k + 3 > length이면, URIError exception을 throw한다.
      2. escapestringk부터 k + 3까지의 substring으로 둔다.
      3. firstOctetParseHexOctet(string, k + 1)로 둔다.
      4. firstOctetinteger가 아니면, URIError exception을 throw한다.
      5. kk + 2로 설정한다.
      6. nfirstOctet 안의 leading 1 bit의 number로 둔다.
      7. n = 0이면, 다음을 수행한다.
        1. asciiChar를 numeric value가 firstOctet인 code unit으로 둔다.
        2. preserveEscapeSetasciiChar를 contain하면, segmentescape로 설정한다; 그렇지 않으면 segmentasciiChar로 설정한다.
      8. 그렇지 않으면,
        1. n = 1 또는 n > 4이면, URIError exception을 throw한다.
        2. octets를 « firstOctet »로 둔다.
        3. j를 1로 둔다.
        4. Repeat, j < n인 동안,
          1. kk + 1로 설정한다.
          2. k + 3 > length이면, URIError exception을 throw한다.
          3. string 안의 index k에 있는 code unit이 code unit 0x0025 (PERCENT SIGN)가 아니면, URIError exception을 throw한다.
          4. continuationByteParseHexOctet(string, k + 1)로 둔다.
          5. continuationByteinteger가 아니면, URIError exception을 throw한다.
          6. continuationByteoctets에 append한다.
          7. kk + 2로 설정한다.
          8. jj + 1로 설정한다.
        5. Assert: octets의 length는 n이다.
        6. octets가 Unicode code point의 valid UTF-8 encoding을 contain하지 않으면, URIError exception을 throw한다.
        7. codePointoctets에 UTF-8 transformation을 applying하여 얻은 code point로 둔다, 즉 octet의 List에서 21-bit value로 변환한 것이다.
        8. segmentUTF16EncodeCodePoint(codePoint)로 설정한다.
    4. resultresultsegmentstring-concatenation으로 설정한다.
    5. kk + 1로 설정한다.
  5. result를 반환한다.
Note

RFC 3629는 invalid UTF-8 octet sequence의 decoding을 prohibit합니다. 예를 들어 invalid sequence 0xC0 0x80은 code unit 0x0000으로 decode되어서는 안 됩니다. Decode algorithm의 implementation은 such invalid sequence를 encounter할 때 URIError를 throw해야 합니다.

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 안의 specified position에서 두 hexadecimal character의 sequence를 unsigned 8-bit integer로 parse합니다. It performs the following steps when called:

  1. lengthstring의 length로 둔다.
  2. Assert: position + 2 ≤ length이다.
  3. hexDigitsstringposition부터 position + 2까지의 substring으로 둔다.
  4. parseResultParseText(hexDigits, HexDigits[~Sep])로 둔다.
  5. parseResultParse Node가 아니면, parseResult를 반환한다.
  6. nparseResult의 MV로 둔다.
  7. Assert: n은 0부터 255까지의 inclusive interval 안에 있다.
  8. n을 반환한다.

19.3 Constructor Properties of the Global Object

19.3.1 AggregateError ( . . . )

20.5.7.1를 참조하십시오.

19.3.2 Array ( . . . )

23.1.1를 참조하십시오.

19.3.3 ArrayBuffer ( . . . )

25.1.4를 참조하십시오.

19.3.4 AsyncDisposableStack ( . . . )

27.4.1를 참조하십시오.

19.3.5 BigInt ( . . . )

21.2.1를 참조하십시오.

19.3.6 BigInt64Array ( . . . )

23.2.5를 참조하십시오.

19.3.7 BigUint64Array ( . . . )

23.2.5를 참조하십시오.

19.3.8 Boolean ( . . . )

20.3.1를 참조하십시오.

19.3.9 DataView ( . . . )

25.3.2를 참조하십시오.

19.3.10 Date ( . . . )

21.4.2를 참조하십시오.

19.3.11 DisposableStack ( . . . )

27.3.1를 참조하십시오.

19.3.12 Error ( . . . )

20.5.1를 참조하십시오.

19.3.13 EvalError ( . . . )

20.5.5.1를 참조하십시오.

19.3.14 FinalizationRegistry ( . . . )

26.2.1를 참조하십시오.

19.3.15 Float16Array ( . . . )

23.2.5를 참조하십시오.

19.3.16 Float32Array ( . . . )

23.2.5를 참조하십시오.

19.3.17 Float64Array ( . . . )

23.2.5를 참조하십시오.

19.3.18 Function ( . . . )

20.2.1를 참조하십시오.

19.3.19 Int8Array ( . . . )

23.2.5를 참조하십시오.

19.3.20 Int16Array ( . . . )

23.2.5를 참조하십시오.

19.3.21 Int32Array ( . . . )

23.2.5를 참조하십시오.

19.3.22 Iterator ( . . . )

27.1.3.1를 참조하십시오.

19.3.23 Map ( . . . )

24.1.1를 참조하십시오.

19.3.24 Number ( . . . )

21.1.1를 참조하십시오.

19.3.25 Object ( . . . )

20.1.1를 참조하십시오.

19.3.26 Promise ( . . . )

27.5.3를 참조하십시오.

19.3.27 Proxy ( . . . )

28.2.1를 참조하십시오.

19.3.28 RangeError ( . . . )

20.5.5.2를 참조하십시오.

19.3.29 ReferenceError ( . . . )

20.5.5.3를 참조하십시오.

19.3.30 RegExp ( . . . )

22.2.4를 참조하십시오.

19.3.31 Set ( . . . )

24.2.2를 참조하십시오.

19.3.32 SharedArrayBuffer ( . . . )

25.2.3를 참조하십시오.

19.3.33 String ( . . . )

22.1.1를 참조하십시오.

19.3.34 SuppressedError ( . . . )

20.5.8.1를 참조하십시오.

19.3.35 Symbol ( . . . )

20.4.1를 참조하십시오.

19.3.36 SyntaxError ( . . . )

20.5.5.4를 참조하십시오.

19.3.37 TypeError ( . . . )

20.5.5.5를 참조하십시오.

19.3.38 Uint8Array ( . . . )

23.2.5를 참조하십시오.

19.3.39 Uint8ClampedArray ( . . . )

23.2.5를 참조하십시오.

19.3.40 Uint16Array ( . . . )

23.2.5를 참조하십시오.

19.3.41 Uint32Array ( . . . )

23.2.5를 참조하십시오.

19.3.42 URIError ( . . . )

20.5.5.6를 참조하십시오.

19.3.43 WeakMap ( . . . )

24.3.1를 참조하십시오.

19.3.44 WeakRef ( . . . )

26.1.1를 참조하십시오.

19.3.45 WeakSet ( . . . )

24.4를 참조하십시오.

19.4 Other Properties of the Global Object

19.4.1 Atomics

25.4를 참조하십시오.

19.4.2 JSON

25.5를 참조하십시오.

19.4.3 Math

21.3를 참조하십시오.

19.4.4 Reflect

28.1를 참조하십시오.

20 Fundamental Objects

20.1 Object Objects

20.1.1 The Object Constructor

Object constructor는:

  • %Object%입니다.
  • global object"Object" property의 initial value입니다.
  • constructor로 called될 때 new ordinary object를 create합니다.
  • constructor가 아니라 function으로 called될 때 type conversion을 수행합니다.
  • class definition의 extends clause의 value로 사용될 수 있습니다.

20.1.1.1 Object ( value )

이 function은 called될 때 다음 step을 수행합니다:

  1. NewTarget이 undefined도 아니고 active function object도 아니면, 다음을 수행한다.
    1. OrdinaryCreateFromConstructor(NewTarget, "%Object.prototype%")를 반환한다.
  2. valueundefined 또는 null 중 하나이면, OrdinaryObjectCreate(%Object.prototype%)를 반환한다.
  3. ToObject(value)를 반환한다.

20.1.2 Properties of the Object Constructor

Object constructor는:

  • value가 %Function.prototype%[[Prototype]] internal slot을 가집니다.
  • 다음 additional property를 가집니다:

20.1.2.1 Object.assign ( target, ...sources )

이 function은 one or more source object에서 target object로 모든 enumerable own property의 value를 copy합니다.

called될 때 다음 step을 수행합니다:

  1. targetObj를 ? ToObject(target)라고 하자.
  2. 인수가 하나만 전달되었으면 targetObj를 반환한다.
  3. sources의 각 요소 nextSource에 대해 다음을 수행한다.
    1. nextSourceundefinednull도 아니면,
      1. from을 ! ToObject(nextSource)라고 하자.
      2. keys를 ? from.[[OwnPropertyKeys]]()라고 하자.
      3. keys의 각 요소 nextKey에 대해 다음을 수행한다.
        1. propertyDesc를 ? from.[[GetOwnProperty]](nextKey)라고 하자.
        2. propertyDescundefined가 아니고 propertyDesc.[[Enumerable]]true이면,
          1. propertyValue를 ? Get(from, nextKey)라고 하자.
          2. Set(targetObj, nextKey, propertyValue, true)를 수행한다.
  4. targetObj를 반환한다.

이 function의 "length" property는 2𝔽입니다.

20.1.2.2 Object.create ( proto, properties )

이 function은 specified prototype을 가진 new object를 create합니다.

called될 때 다음 step을 수행합니다:

  1. proto가 Object가 아니고 protonull도 아니면, TypeError exception을 throw한다.
  2. objOrdinaryObjectCreate(proto)로 둔다.
  3. propertiesundefined가 아니면, 다음을 수행한다.
    1. ObjectDefineProperties(obj, properties)를 반환한다.
  4. obj를 반환한다.

20.1.2.3 Object.defineProperties ( obj, properties )

이 function은 object의 own property를 add하거나 existing own property의 attribute를 update합니다.

called될 때 다음 step을 수행합니다:

  1. obj가 Object가 아니면, TypeError exception을 throw한다.
  2. ObjectDefineProperties(obj, properties)를 반환한다.

20.1.2.3.1 ObjectDefineProperties ( obj, properties )

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

  1. properties를 ? ToObject(properties)로 설정한다.
  2. keys를 ? properties.[[OwnPropertyKeys]]()로 둔다.
  3. propertyDescs를 새 empty List로 둔다.
  4. keys의 각 element nextKey에 대해, 다음을 수행한다.
    1. currentPropertyDesc를 ? properties.[[GetOwnProperty]](nextKey)로 둔다.
    2. currentPropertyDescundefined가 아니고 currentPropertyDesc.[[Enumerable]]true이면, 다음을 수행한다.
      1. propertyDescObj를 ? Get(properties, nextKey)로 둔다.
      2. propertyDesc를 ? ToPropertyDescriptor(propertyDescObj)로 둔다.
      3. Record { [[Key]]: nextKey, [[Descriptor]]: propertyDesc }를 propertyDescs에 append한다.
  5. propertyDescs의 각 element property에 대해, 다음을 수행한다.
    1. DefinePropertyOrThrow(obj, property.[[Key]], property.[[Descriptor]])를 수행한다.
  6. obj를 반환한다.

20.1.2.4 Object.defineProperty ( obj, key, attrs )

이 function은 object의 own property를 add하거나 existing own property의 attribute를 update합니다.

called될 때 다음 step을 수행합니다:

  1. obj가 Object가 아니면, TypeError exception을 throw한다.
  2. propertyKey를 ? ToPropertyKey(key)로 둔다.
  3. propertyDesc를 ? ToPropertyDescriptor(attrs)로 둔다.
  4. DefinePropertyOrThrow(obj, propertyKey, propertyDesc)를 수행한다.
  5. obj를 반환한다.

20.1.2.5 Object.entries ( obj )

이 function은 called될 때 다음 step을 수행합니다:

  1. coerced를 ? ToObject(obj)로 둔다.
  2. entryList를 ? EnumerableOwnProperties(coerced, key+value)로 둔다.
  3. CreateArrayFromList(entryList)를 반환한다.

20.1.2.6 Object.freeze ( obj )

이 function은 called될 때 다음 step을 수행합니다:

  1. obj가 Object가 아니면, obj를 반환한다.
  2. status를 ? SetIntegrityLevel(obj, frozen)로 둔다.
  3. statusfalse이면, TypeError exception을 throw한다.
  4. obj를 반환한다.

20.1.2.7 Object.fromEntries ( iterable )

이 function은 called될 때 다음 step을 수행합니다:

  1. RequireObjectCoercible(iterable)를 수행한다.
  2. objOrdinaryObjectCreate(%Object.prototype%)로 둔다.
  3. Assert: obj는 own property가 없는 extensible ordinary object이다.
  4. obj를 capture하고 called될 때 다음 step을 수행하는 parameters (key, value)를 가진 새 Abstract Closure closure를 둔다:
    1. propertyKey를 ? ToPropertyKey(key)로 둔다.
    2. CreateDataPropertyOrThrow(obj, propertyKey, value)를 수행한다.
    3. NormalCompletion(undefined)를 반환한다.
  5. adderCreateBuiltinFunction(closure, 2, "", « »)로 둔다.
  6. AddEntriesFromIterable(obj, iterable, adder)를 반환한다.
Note
adder를 위해 created된 function은 ECMAScript code에 의해 never directly accessible하지 않습니다.

20.1.2.8 Object.getOwnPropertyDescriptor ( obj, key )

이 function은 called될 때 다음 step을 수행합니다:

  1. coerced를 ? ToObject(obj)로 둔다.
  2. propertyKey를 ? ToPropertyKey(key)로 둔다.
  3. propertyDesc를 ? coerced.[[GetOwnProperty]](propertyKey)로 둔다.
  4. FromPropertyDescriptor(propertyDesc)를 반환한다.

20.1.2.9 Object.getOwnPropertyDescriptors ( obj )

이 function은 called될 때 다음 step을 수행합니다:

  1. coerced를 ? ToObject(obj)로 둔다.
  2. ownKeys를 ? coerced.[[OwnPropertyKeys]]()로 둔다.
  3. descsOrdinaryObjectCreate(%Object.prototype%)로 둔다.
  4. ownKeys의 각 element key에 대해, 다음을 수행한다.
    1. propertyDesc를 ? coerced.[[GetOwnProperty]](key)로 둔다.
    2. propertyDescObjFromPropertyDescriptor(propertyDesc)로 둔다.
    3. propertyDescObjundefined가 아니면, ! CreateDataPropertyOrThrow(descs, key, propertyDescObj)를 수행한다.
  5. descs를 반환한다.

20.1.2.10 Object.getOwnPropertyNames ( obj )

이 function은 called될 때 다음 step을 수행합니다:

  1. CreateArrayFromList(? GetOwnPropertyKeys(obj, string))를 반환한다.

20.1.2.11 Object.getOwnPropertySymbols ( obj )

이 function은 called될 때 다음 step을 수행합니다:

  1. CreateArrayFromList(? GetOwnPropertyKeys(obj, symbol))를 반환한다.

20.1.2.11.1 GetOwnPropertyKeys ( value, type )

The abstract operation GetOwnPropertyKeys takes arguments value (an ECMAScript language value) and type (string or symbol) and returns either a normal completion containing a List of property keys or a throw completion. It performs the following steps when called:

  1. obj를 ? ToObject(value)로 둔다.
  2. keys를 ? obj.[[OwnPropertyKeys]]()로 둔다.
  3. nameList를 새 empty List로 둔다.
  4. keys의 각 element nextKey에 대해, 다음을 수행한다.
    1. nextKey가 Symbol이고 typesymbol이거나, nextKey가 String이고 typestring이면, 다음을 수행한다.
      1. nextKeynameList에 append한다.
  5. nameList를 반환한다.

20.1.2.12 Object.getPrototypeOf ( obj )

이 function은 called될 때 다음 step을 수행합니다:

  1. coerced를 ? ToObject(obj)로 둔다.
  2. coerced.[[GetPrototypeOf]]()를 반환한다.

20.1.2.13 Object.groupBy ( items, callback )

Note

callback은 two arguments를 accept하는 function이어야 합니다. groupByitems의 각 element에 대해 ascending order로 callback을 once call하고, new object를 construct합니다. callback에 의해 returned된 각 value는 property key로 coerced됩니다. such 각 property key에 대해, result object는 key가 해당 property key이고 value가 callback return value가 그 key로 coerced된 모든 element를 contain하는 array인 property를 가집니다.

callback은 two arguments, 즉 element의 value와 element의 index로 called됩니다.

groupBy의 return value는 %Object.prototype%에서 inherit하지 않는 object입니다.

이 function은 called될 때 다음 step을 수행합니다:

  1. groups를 ? GroupBy(items, callback, property)라고 하자.
  2. objOrdinaryObjectCreate(null)라고 하자.
  3. groups의 각 Record { [[Key]], [[Elements]] } group에 대해 다음을 수행한다.
    1. elementsCreateArrayFromList(group.[[Elements]])라고 하자.
    2. CreateDataPropertyOrThrow(obj, group.[[Key]], elements)를 수행한다.
  4. obj를 반환한다.

20.1.2.14 Object.hasOwn ( obj, key )

이 function은 called될 때 다음 step을 수행합니다:

  1. coerced를 ? ToObject(obj)로 둔다.
  2. propertyKey를 ? ToPropertyKey(key)로 둔다.
  3. HasOwnProperty(coerced, propertyKey)를 반환한다.

20.1.2.15 Object.is ( value1, value2 )

이 function은 called될 때 다음 step을 수행합니다:

  1. SameValue(value1, value2)를 반환한다.

20.1.2.16 Object.isExtensible ( obj )

이 function은 called될 때 다음 step을 수행합니다:

  1. obj가 Object가 아니면, false를 반환한다.
  2. IsExtensible(obj)를 반환한다.

20.1.2.17 Object.isFrozen ( obj )

이 function은 called될 때 다음 step을 수행합니다:

  1. obj가 Object가 아니면, true를 반환한다.
  2. TestIntegrityLevel(obj, frozen)를 반환한다.

20.1.2.18 Object.isSealed ( obj )

이 function은 called될 때 다음 step을 수행합니다:

  1. obj가 Object가 아니면, true를 반환한다.
  2. TestIntegrityLevel(obj, sealed)를 반환한다.

20.1.2.19 Object.keys ( obj )

이 function은 called될 때 다음 step을 수행합니다:

  1. coerced를 ? ToObject(obj)로 둔다.
  2. keyList를 ? EnumerableOwnProperties(coerced, key)로 둔다.
  3. CreateArrayFromList(keyList)를 반환한다.

20.1.2.20 Object.preventExtensions ( obj )

이 function은 called될 때 다음 step을 수행합니다:

  1. obj가 Object가 아니면, obj를 반환한다.
  2. status를 ? obj.[[PreventExtensions]]()로 둔다.
  3. statusfalse이면, TypeError exception을 throw한다.
  4. obj를 반환한다.

20.1.2.21 Object.prototype

Object.prototype의 initial value는 Object prototype object입니다.

이 property는 attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }를 가집니다.

20.1.2.22 Object.seal ( obj )

이 function은 called될 때 다음 step을 수행합니다:

  1. obj가 Object가 아니면, obj를 반환한다.
  2. status를 ? SetIntegrityLevel(obj, sealed)로 둔다.
  3. statusfalse이면, TypeError exception을 throw한다.
  4. obj를 반환한다.

20.1.2.23 Object.setPrototypeOf ( obj, proto )

이 function은 called될 때 다음 step을 수행합니다:

  1. RequireObjectCoercible(obj)를 수행한다.
  2. proto가 Object가 아니고 protonull도 아니면, TypeError exception을 throw한다.
  3. obj가 Object가 아니면, obj를 반환한다.
  4. status를 ? obj.[[SetPrototypeOf]](proto)로 둔다.
  5. statusfalse이면, TypeError exception을 throw한다.
  6. obj를 반환한다.

20.1.2.24 Object.values ( obj )

이 function은 called될 때 다음 step을 수행합니다:

  1. coerced를 ? ToObject(obj)로 둔다.
  2. valueList를 ? EnumerableOwnProperties(coerced, value)로 둔다.
  3. CreateArrayFromList(valueList)를 반환한다.

20.1.3 Properties of the Object Prototype Object

Object prototype object는:

  • %Object.prototype%입니다.
  • value가 true[[Extensible]] internal slot을 가집니다.
  • 10.4.7.1에 defined된 것과 같은 [[SetPrototypeOf]] method를 제외하고 ordinary object에 defined된 internal method를 가집니다. (따라서 이는 immutable prototype exotic object입니다.)
  • value가 null[[Prototype]] internal slot을 가집니다.

20.1.3.1 Object.prototype.constructor

Object.prototype.constructor의 initial value는 %Object%입니다.

20.1.3.2 Object.prototype.hasOwnProperty ( value )

이 method는 called될 때 다음 step을 수행합니다:

  1. propertyKey를 ? ToPropertyKey(value)로 둔다.
  2. obj를 ? ToObject(this value)로 둔다.
  3. HasOwnProperty(obj, propertyKey)를 반환한다.
Note

step 12의 ordering은, this value가 undefined 또는 null인 경우에도 이 specification의 previous edition에서 step 1에 의해 thrown되었을 any exception이 계속 thrown되도록 ensure하기 위해 chosen되었습니다.

20.1.3.3 Object.prototype.isPrototypeOf ( value )

이 method는 called될 때 다음 step을 수행합니다:

  1. value가 Object가 아니면, false를 반환한다.
  2. obj를 ? ToObject(this value)로 둔다.
  3. Repeat,
    1. value를 ? value.[[GetPrototypeOf]]()로 설정한다.
    2. valuenull이면, false를 반환한다.
    3. SameValue(obj, value)가 true이면, true를 반환한다.
Note

step 12의 ordering은, value가 object가 아니고 this value가 undefined 또는 null인 경우에 대해 이 specification의 previous edition에서 specified된 behaviour를 preserves합니다.

20.1.3.4 Object.prototype.propertyIsEnumerable ( value )

이 method는 called될 때 다음 step을 수행합니다:

  1. propertyKey를 ? ToPropertyKey(value)로 둔다.
  2. obj를 ? ToObject(this value)로 둔다.
  3. propertyDesc를 ? obj.[[GetOwnProperty]](propertyKey)로 둔다.
  4. propertyDescundefined이면, false를 반환한다.
  5. propertyDesc.[[Enumerable]]을 반환한다.
Note 1

이 method는 prototype chain 안의 object를 consider하지 않습니다.

Note 2

step 12의 ordering은, this value가 undefined 또는 null인 경우에도 이 specification의 previous edition에서 step 1에 의해 thrown되었을 any exception이 계속 thrown되도록 ensure하기 위해 chosen되었습니다.

20.1.3.5 Object.prototype.toLocaleString ( [ reserved1 [ , reserved2 ] ] )

이 method는 called될 때 다음 step을 수행합니다:

  1. thisValuethis value로 둔다.
  2. Invoke(thisValue, "toString")를 반환한다.

이 method의 optional parameter는 사용되지 않지만, ECMA-402 toLocaleString method에서 사용되는 parameter pattern에 correspond하도록 intended됩니다. ECMA-402 support를 include하지 않는 implementation은 those parameter position을 other purpose에 사용해서는 안 됩니다.

Note 1

이 method는 locale-sensitive toString behaviour를 가지지 않는 object를 위한 generic toLocaleString implementation을 제공합니다. Array, Number, Date, 및 %TypedArray%는 own locale-sensitive toLocaleString method를 provide합니다.

Note 2

ECMA-402는 intentionally 이 default implementation에 대한 alternative를 provide하지 않습니다.

20.1.3.6 Object.prototype.toString ( )

이 method는 called될 때 다음 step을 수행합니다:

  1. this value가 undefined이면, "[object Undefined]"를 반환한다.
  2. this value가 null이면, "[object Null]"을 반환한다.
  3. obj를 ! ToObject(this value)로 둔다.
  4. isArray를 ? IsArray(obj)로 둔다.
  5. isArraytrue이면, builtinTag"Array"로 둔다.
  6. 그렇지 않고 obj[[ParameterMap]] internal slot을 가지면, builtinTag"Arguments"로 둔다.
  7. 그렇지 않고 obj[[Call]] internal method를 가지면, builtinTag"Function"으로 둔다.
  8. 그렇지 않고 obj[[ErrorData]] internal slot을 가지면, builtinTag"Error"로 둔다.
  9. 그렇지 않고 obj[[BooleanData]] internal slot을 가지면, builtinTag"Boolean"으로 둔다.
  10. 그렇지 않고 obj[[NumberData]] internal slot을 가지면, builtinTag"Number"로 둔다.
  11. 그렇지 않고 obj[[StringData]] internal slot을 가지면, builtinTag"String"으로 둔다.
  12. 그렇지 않고 obj[[DateValue]] internal slot을 가지면, builtinTag"Date"로 둔다.
  13. 그렇지 않고 obj[[RegExpMatcher]] internal slot을 가지면, builtinTag"RegExp"로 둔다.
  14. 그렇지 않으면, builtinTag"Object"로 둔다.
  15. tag를 ? Get(obj, %Symbol.toStringTag%)로 둔다.
  16. tag가 String이 아니면, tagbuiltinTag로 설정한다.
  17. "[object ", tag, 및 "]"string-concatenation을 반환한다.
Note

Historically, 이 method는 this specification의 previous edition에서 various built-in object를 위한 nominal type tag로 사용되었던 [[Class]] internal slot의 String value에 access하기 위해 occasionally 사용되었습니다. toString의 above definition은 those specific kind of built-in object를 test하기 위해 toString을 사용하는 legacy code에 대한 compatibility를 preserves합니다. 이는 other kind의 built-in 또는 program defined object에 대한 reliable type testing mechanism을 provide하지 않습니다. In addition, program은 such legacy type test의 reliability를 invalidate할 ways로 %Symbol.toStringTag%를 사용할 수 있습니다.

20.1.3.7 Object.prototype.valueOf ( )

이 method는 called될 때 다음 step을 수행합니다:

  1. ToObject(this value)를 반환한다.

20.1.3.8 Object.prototype.__proto__

Object.prototype.__proto__는 attributes { [[Enumerable]]: false, [[Configurable]]: true }를 가진 accessor property입니다. [[Get]][[Set]] attribute는 다음과 같이 defined됩니다:

20.1.3.8.1 get Object.prototype.__proto__

[[Get]] attribute의 value는 argument를 require하지 않는 built-in function입니다. called될 때 다음 step을 수행합니다:

  1. obj를 ? ToObject(this value)로 둔다.
  2. obj.[[GetPrototypeOf]]()를 반환한다.

20.1.3.8.2 set Object.prototype.__proto__

[[Set]] attribute의 value는 argument proto를 take하는 built-in function입니다. called될 때 다음 step을 수행합니다:

  1. thisValuethis value로 둔다.
  2. RequireObjectCoercible(thisValue)를 수행한다.
  3. proto가 Object가 아니고 protonull도 아니면, undefined를 반환한다.
  4. thisValue가 Object가 아니면, undefined를 반환한다.
  5. status를 ? thisValue.[[SetPrototypeOf]](proto)로 둔다.
  6. statusfalse이면, TypeError exception을 throw한다.
  7. undefined를 반환한다.

20.1.3.9 Legacy Object.prototype Accessor Methods

20.1.3.9.1 Object.prototype.__defineGetter__ ( key, getter )

이 method는 called될 때 다음 step을 수행합니다:

  1. obj를 ? ToObject(this value)로 둔다.
  2. IsCallable(getter)가 false이면, TypeError exception을 throw한다.
  3. propertyDesc를 PropertyDescriptor { [[Get]]: getter, [[Enumerable]]: true, [[Configurable]]: true }로 둔다.
  4. propertyKey를 ? ToPropertyKey(key)로 둔다.
  5. DefinePropertyOrThrow(obj, propertyKey, propertyDesc)를 수행한다.
  6. undefined를 반환한다.

20.1.3.9.2 Object.prototype.__defineSetter__ ( key, setter )

이 method는 called될 때 다음 step을 수행합니다:

  1. obj를 ? ToObject(this value)로 둔다.
  2. IsCallable(setter)가 false이면, TypeError exception을 throw한다.
  3. propertyDesc를 PropertyDescriptor { [[Set]]: setter, [[Enumerable]]: true, [[Configurable]]: true }로 둔다.
  4. propertyKey를 ? ToPropertyKey(key)로 둔다.
  5. DefinePropertyOrThrow(obj, propertyKey, propertyDesc)를 수행한다.
  6. undefined를 반환한다.

20.1.3.9.3 Object.prototype.__lookupGetter__ ( key )

이 method는 called될 때 다음 step을 수행합니다:

  1. obj를 ? ToObject(this value)로 둔다.
  2. propertyKey를 ? ToPropertyKey(key)로 둔다.
  3. Repeat,
    1. propertyDesc를 ? obj.[[GetOwnProperty]](propertyKey)로 둔다.
    2. propertyDescundefined가 아니면, 다음을 수행한다.
      1. IsAccessorDescriptor(propertyDesc)가 true이면, propertyDesc.[[Get]]을 반환한다.
      2. undefined를 반환한다.
    3. obj를 ? obj.[[GetPrototypeOf]]()로 설정한다.
    4. objnull이면, undefined를 반환한다.

20.1.3.9.4 Object.prototype.__lookupSetter__ ( key )

이 method는 called될 때 다음 step을 수행합니다:

  1. obj를 ? ToObject(this value)로 둔다.
  2. propertyKey를 ? ToPropertyKey(key)로 둔다.
  3. Repeat,
    1. propertyDesc를 ? obj.[[GetOwnProperty]](propertyKey)로 둔다.
    2. propertyDescundefined가 아니면, 다음을 수행한다.
      1. IsAccessorDescriptor(propertyDesc)가 true이면, propertyDesc.[[Set]]을 반환한다.
      2. undefined를 반환한다.
    3. obj를 ? obj.[[GetPrototypeOf]]()로 설정한다.
    4. objnull이면, undefined를 반환한다.

20.1.4 Properties of Object Instances

Object instance는 Object prototype object에서 inherited되는 property 외에 special property를 가지지 않습니다.

20.2 Function Objects

20.2.1 The Function Constructor

Function constructor는:

  • %Function%입니다.
  • global object"Function" property의 initial value입니다.
  • constructor가 아니라 function으로 called될 때 new function object를 create하고 initialize합니다. 따라서 function call Function(…)은 same arguments를 가진 object creation expression new Function(…)과 equivalent합니다.
  • class definition의 extends clause의 value로 사용될 수 있습니다. specified Function behaviour를 inherit하려는 subclass constructor는 built-in function behaviour에 necessary한 internal slot을 가진 subclass instance를 create하고 initialize하기 위해 Function constructor에 대한 super call을 include해야 합니다. function object를 defining하기 위한 모든 ECMAScript syntactic form은 Function의 instance를 create합니다. built-in GeneratorFunction, AsyncFunction, 및 AsyncGeneratorFunction subclass를 제외하고 Function subclass의 instance를 create하는 syntactic means는 없습니다.

20.2.1.1 Function ( ...paramArgs, bodyArg )

last argument(있으면)는 function의 body(executable code)를 specify합니다; preceding argument는 formal parameter를 specify합니다.

이 function은 called될 때 다음 step을 수행합니다:

  1. ctor를 active function object로 둔다.
  2. bodyArg가 present하지 않으면, bodyArg를 empty String으로 설정한다.
  3. CreateDynamicFunction(ctor, NewTarget, normal, paramArgs, bodyArg)를 반환한다.
Note

specified될 각 formal parameter에 대해 one argument를 가지는 것은 permissible하지만 necessary하지 않습니다. 예를 들어 다음 세 expression은 모두 same 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을 performing하는 constructor function입니다. newTargetnew가 initially applied된 constructor입니다. paramArgsbodyArgctor에 passed된 argument value를 reflect합니다. It performs the following steps when called:

  1. newTargetundefined이면, newTargetctor로 설정한다.
  2. kindnormal이면, 다음을 수행한다.
    1. prefix"function"으로 둔다.
    2. exprGrammar를 grammar symbol FunctionExpression으로 둔다.
    3. bodyGrammar를 grammar symbol FunctionBody[~Yield, ~Await]로 둔다.
    4. paramGrammar를 grammar symbol FormalParameters[~Yield, ~Await]로 둔다.
    5. fallbackProto"%Function.prototype%"로 둔다.
  3. 그렇지 않고 kindgenerator이면, 다음을 수행한다.
    1. prefix"function*"로 둔다.
    2. exprGrammar를 grammar symbol GeneratorExpression으로 둔다.
    3. bodyGrammar를 grammar symbol GeneratorBody로 둔다.
    4. paramGrammar를 grammar symbol FormalParameters[+Yield, ~Await]로 둔다.
    5. fallbackProto"%GeneratorFunction.prototype%"로 둔다.
  4. 그렇지 않고 kindasync이면, 다음을 수행한다.
    1. prefix"async function"으로 둔다.
    2. exprGrammar를 grammar symbol AsyncFunctionExpression으로 둔다.
    3. bodyGrammar를 grammar symbol AsyncFunctionBody로 둔다.
    4. paramGrammar를 grammar symbol FormalParameters[~Yield, +Await]로 둔다.
    5. fallbackProto"%AsyncFunction.prototype%"로 둔다.
  5. 그렇지 않으면,
    1. Assert: kindasync-generator이다.
    2. prefix"async function*"로 둔다.
    3. exprGrammar를 grammar symbol AsyncGeneratorExpression으로 둔다.
    4. bodyGrammar를 grammar symbol AsyncGeneratorBody로 둔다.
    5. paramGrammar를 grammar symbol FormalParameters[+Yield, +Await]로 둔다.
    6. fallbackProto"%AsyncGeneratorFunction.prototype%"로 둔다.
  6. argCountparamArgs 안의 element 수로 둔다.
  7. paramStrings를 새 empty List로 둔다.
  8. paramArgs의 각 element arg에 대해, 다음을 수행한다.
    1. ToString(arg)를 paramStrings에 append한다.
  9. bodyString을 ? ToString(bodyArg)로 둔다.
  10. currentRealm을 current Realm Record로 둔다.
  11. HostEnsureCanCompileStrings(currentRealm, paramStrings, bodyString, false)를 수행한다.
  12. paramString을 empty String으로 둔다.
  13. argCount > 0이면, 다음을 수행한다.
    1. paramStringparamStrings[0]으로 설정한다.
    2. k를 1로 둔다.
    3. Repeat, k < argCount인 동안,
      1. nextArgStringparamStrings[k]로 둔다.
      2. paramStringparamString, "," (comma), 및 nextArgStringstring-concatenation으로 설정한다.
      3. kk + 1로 설정한다.
  14. bodyParseString을 0x000A (LINE FEED), bodyString, 및 0x000A (LINE FEED)의 string-concatenation으로 둔다.
  15. sourceStringprefix, " anonymous(", paramString, 0x000A (LINE FEED), ") {", bodyParseString, 및 "}"string-concatenation으로 둔다.
  16. sourceTextStringToCodePoints(sourceString)로 둔다.
  17. paramsParseText(paramString, paramGrammar)로 둔다.
  18. params가 error의 List이면, SyntaxError exception을 throw한다.
  19. bodyParseText(bodyParseString, bodyGrammar)로 둔다.
  20. body가 error의 List이면, SyntaxError exception을 throw한다.
  21. NOTE: parameter와 body는 각각 alone valid함을 ensure하기 위해 separately parsed된다. 예를 들어 new Function("/*", "*/ ) {")는 function으로 evaluate되지 않는다.
  22. NOTE: 이 step에 reached했다면, sourceTextexprGrammar의 syntax를 가져야 한다(although reverse implication does not hold). 다음 두 step의 purpose는 exprGrammar에 directly apply되는 any Early Error rule을 enforce하는 것이다.
  23. exprParseText(sourceText, exprGrammar)로 둔다.
  24. expr가 error의 List이면, SyntaxError exception을 throw한다.
  25. funcProto를 ? GetPrototypeFromConstructor(newTarget, fallbackProto)로 둔다.
  26. envRecordcurrentRealm.[[GlobalEnv]]로 둔다.
  27. privateEnvnull로 둔다.
  28. funcOrdinaryFunctionCreate(funcProto, sourceText, params, body, non-lexical-this, envRecord, privateEnv)로 둔다.
  29. SetFunctionName(func, "anonymous")를 수행한다.
  30. kindgenerator이면, 다음을 수행한다.
    1. protoProtoOrdinaryObjectCreate(%GeneratorPrototype%)로 둔다.
    2. DefinePropertyOrThrow(func, "prototype", PropertyDescriptor { [[Value]]: protoProto, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false })를 수행한다.
  31. 그렇지 않고 kindasync-generator이면, 다음을 수행한다.
    1. protoProtoOrdinaryObjectCreate(%AsyncGeneratorPrototype%)로 둔다.
    2. DefinePropertyOrThrow(func, "prototype", PropertyDescriptor { [[Value]]: protoProto, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false })를 수행한다.
  32. 그렇지 않고 kindnormal이면, 다음을 수행한다.
    1. MakeConstructor(func)를 수행한다.
  33. NOTE: kindasync인 function은 constructable하지 않으며 [[Construct]] internal method 또는 "prototype" property를 가지지 않는다.
  34. func를 반환한다.
Note

CreateDynamicFunction은 created하는 any function 중 kindasync가 아닌 것에 대해 "prototype" property를 define하여, 해당 function이 constructor로 사용될 가능성에 대비합니다.

20.2.2 Properties of the Function Constructor

Function constructor는:

  • itself가 built-in function object입니다.
  • value가 %Function.prototype%[[Prototype]] internal slot을 가집니다.
  • value가 1𝔽"length" property를 가집니다.
  • 다음 property를 가집니다:

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%입니다.
  • itself가 built-in function object입니다.
  • any argument를 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 이전에 created된 ECMAScript code와의 compatibility를 ensure하기 위해 function object로 specified됩니다.

20.2.3.1 Function.prototype.apply ( thisArg, argArray )

이 method는 called될 때 다음 step을 수행합니다:

  1. functhis value로 둔다.
  2. IsCallable(func)이 false이면, TypeError exception을 throw한다.
  3. argArrayundefined 또는 null 중 하나이면, 다음을 수행한다.
    1. PrepareForTailCall()을 수행한다.
    2. Call(func, thisArg)를 반환한다.
  4. argList를 ? CreateListFromArrayLike(argArray)로 둔다.
  5. PrepareForTailCall()을 수행한다.
  6. Call(func, thisArg, argList)를 반환한다.
Note 1

thisArg value는 modification 없이 this value로 passed됩니다. 이는 Edition 3에서 undefined 또는 null thisArgglobal object로 replaced되고, all other value에 ToObject가 applied되며 그 result가 this value로 passed되었던 것과 달라진 change입니다. thisArg가 modification 없이 passed되더라도, non-strict function은 function entry 시 여전히 these transformation을 수행합니다.

Note 2

func가 arrow function 또는 bound function exotic object 중 하나이면, thisArg는 step 6의 function [[Call]]에 의해 ignored될 것입니다.

20.2.3.2 Function.prototype.bind ( thisArg, ...args )

이 method는 called될 때 다음 step을 수행합니다:

  1. targetthis value로 둔다.
  2. IsCallable(target)이 false이면, TypeError exception을 throw한다.
  3. boundFunc를 ? BoundFunctionCreate(target, thisArg, args)로 둔다.
  4. length를 0으로 둔다.
  5. targetHasLength를 ? HasOwnProperty(target, "length")로 둔다.
  6. targetHasLengthtrue이면, 다음을 수행한다.
    1. targetLength를 ? Get(target, "length")로 둔다.
    2. targetLength가 Number이면, 다음을 수행한다.
      1. targetLength+∞𝔽이면, 다음을 수행한다.
        1. length를 +∞로 설정한다.
      2. 그렇지 않고 targetLength-∞𝔽이면, 다음을 수행한다.
        1. length를 0으로 설정한다.
      3. 그렇지 않으면,
        1. targetLengthAsInt를 ! ToIntegerOrInfinity(targetLength)로 둔다.
        2. Assert: targetLengthAsIntfinite이다.
        3. argCountargs 안의 element 수로 둔다.
        4. lengthmax(targetLengthAsInt - argCount, 0)으로 설정한다.
  7. SetFunctionLength(boundFunc, length)를 수행한다.
  8. targetName을 ? Get(target, "name")로 둔다.
  9. targetName이 String이 아니면, targetName을 empty String으로 설정한다.
  10. SetFunctionName(boundFunc, targetName, "bound")를 수행한다.
  11. boundFunc를 반환한다.
Note 1

Function.prototype.bind를 사용하여 created된 Function objectexotic object입니다. 또한 "prototype" property를 가지지 않습니다.

Note 2

target이 arrow function 또는 bound function exotic object 중 하나이면, 이 method에 passed된 thisArgfunc에 대한 subsequent call에서 사용되지 않을 것입니다.

20.2.3.3 Function.prototype.call ( thisArg, ...args )

이 method는 called될 때 다음 step을 수행합니다:

  1. functhis value로 둔다.
  2. IsCallable(func)이 false이면, TypeError exception을 throw한다.
  3. PrepareForTailCall()을 수행한다.
  4. Call(func, thisArg, args)를 반환한다.
Note 1

thisArg value는 modification 없이 this value로 passed됩니다. 이는 Edition 3에서 undefined 또는 null thisArgglobal object로 replaced되고, all other value에 ToObject가 applied되며 그 result가 this value로 passed되었던 것과 달라진 change입니다. thisArg가 modification 없이 passed되더라도, non-strict function은 function entry 시 여전히 these transformation을 수행합니다.

Note 2

func가 arrow function 또는 bound function exotic object 중 하나이면, thisArg는 step 4의 function [[Call]]에 의해 ignored될 것입니다.

20.2.3.4 Function.prototype.constructor

Function.prototype.constructor의 initial value는 %Function%입니다.

20.2.3.5 Function.prototype.toString ( )

이 method는 called될 때 다음 step을 수행합니다:

  1. functhis value로 둔다.
  2. func가 Object이고, func[[SourceText]] internal slot을 가지며, func.[[SourceText]]가 Unicode code point의 sequence이고, HostHasSourceTextAvailable(func)가 true이면, 다음을 수행한다.
    1. CodePointsToString(func.[[SourceText]])를 반환한다.
  3. funcbuilt-in function object이면, funcimplementation-defined String source code representation을 반환한다. representation은 NativeFunction의 syntax를 가져야 합니다. Additionally, func[[InitialName]] internal slot을 가지고 func.[[InitialName]]이 String이면, returned String 중 NativeFunctionAccessoropt PropertyName에 의해 matched될 portion은 func.[[InitialName]]이어야 합니다.
  4. func가 Object이고 IsCallable(func)가 true이면, funcimplementation-defined String source code representation을 반환한다. representation은 NativeFunction의 syntax를 가져야 한다.
  5. TypeError exception을 throw한다.
NativeFunction : function NativeFunctionAccessoropt PropertyName[~Yield, ~Await]opt ( FormalParameters[~Yield, ~Await] ) { [ native code ] } NativeFunctionAccessor : get set

20.2.3.6 Function.prototype [ %Symbol.hasInstance% ] ( value )

이 method는 called될 때 다음 step을 수행합니다:

  1. thisValuethis value로 둔다.
  2. OrdinaryHasInstance(thisValue, value)를 반환한다.

이 property는 attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }를 가집니다.

Note

이는 대부분의 function이 inherit하는 %Symbol.hasInstance%의 default implementation입니다. %Symbol.hasInstance%는 value가 specific constructor의 instance인지 determine하기 위해 instanceof operator에 의해 called됩니다. 다음과 같은 expression은

v instanceof F

다음처럼 evaluates됩니다

F[%Symbol.hasInstance%](v)

constructor function은 function에 different %Symbol.hasInstance% method를 exposing함으로써 instanceof에 의해 어떤 object가 its instance로 recognized되는지 control할 수 있습니다.

이 property는 bound function의 target function을 globally expose하는 데 used될 수 있는 tampering을 prevent하기 위해 non-writable 및 non-configurable입니다.

이 method의 "name" property의 value는 "[Symbol.hasInstance]"입니다.

20.2.4 Function Instances

Every Function instance는 ECMAScript function object이고 Table 26에 listed된 internal slot을 가집니다. Function.prototype.bind method(20.2.3.2)를 사용하여 created된 Function objectTable 27에 listed된 internal slot을 가집니다.

Function instance는 다음 property를 가집니다:

20.2.4.1 length

"length" property의 value는 function에 expected되는 typical number of arguments를 indicate하는 integral Number입니다. 그러나 language는 function이 some other number of arguments와 함께 invoked되는 것을 permit합니다. "length" property에 의해 specified된 number가 아닌 number of arguments로 invoked될 때의 function behaviour는 function에 depend합니다. 이 property는 attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }를 가집니다.

20.2.4.2 name

"name" property의 value는 function을 descriptive하는 String입니다. name은 semantic significance를 가지지 않지만, typically ECMAScript source text 안에서 definition point에서 function을 refer하기 위해 사용되는 variable 또는 property name입니다. 이 property는 attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }를 가집니다.

이 specification에 의해 contextual name이 associated되지 않은 Anonymous function object"name" property의 value로 empty String을 사용합니다.

20.2.4.3 prototype

constructor로 사용될 수 있는 Function instance는 "prototype" property를 가집니다. such Function instance가 created될 때마다 another ordinary object도 created되고 function의 "prototype" property의 initial value가 됩니다. 달리 specified되지 않는 한, "prototype" property의 value는 해당 function이 constructor로 invoked될 때 created되는 object의 [[Prototype]] internal slot을 initialize하는 데 사용됩니다.

이 property는 attributes { [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false }를 가집니다.

Note

Function.prototype.bind를 사용하여 created되거나, MethodDefinition(GeneratorMethod 또는 AsyncGeneratorMethod가 아닌 것) 또는 ArrowFunction을 evaluating하여 created된 Function object"prototype" property를 가지지 않습니다.

20.2.5 HostHasSourceTextAvailable ( func )

The host-defined abstract operation HostHasSourceTextAvailable takes argument func (a function object) and returns a Boolean. host environmentfunc에 대한 source text가 provided되는 것을 prevent할 수 있게 합니다.

HostHasSourceTextAvailable의 implementation은 다음 requirement에 conform해야 합니다:

  • parameter에 대해 deterministic이어야 합니다. 특정 func를 argument로 하여 called될 때마다, same 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로 called될 때 new Boolean object를 create하고 initialize합니다.
  • constructor가 아니라 function으로 called될 때 type conversion을 수행합니다.
  • class definition의 extends clause의 value로 사용될 수 있습니다. specified Boolean behaviour를 inherit하려는 subclass constructor[[BooleanData]] internal slot을 가진 subclass instance를 create하고 initialize하기 위해 Boolean constructor에 대한 super call을 include해야 합니다.

20.3.1.1 Boolean ( value )

이 function은 called될 때 다음 step을 수행합니다:

  1. boolToBoolean(value)로 둔다.
  2. NewTarget이 undefined이면, bool을 반환한다.
  3. obj를 ? OrdinaryCreateFromConstructor(NewTarget, "%Boolean.prototype%", « [[BooleanData]] »)로 둔다.
  4. obj.[[BooleanData]]bool로 설정한다.
  5. obj를 반환한다.

20.3.2 Properties of the Boolean Constructor

Boolean constructor는:

  • value가 %Function.prototype%[[Prototype]] internal slot을 가집니다.
  • 다음 property를 가집니다:

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입니다.
  • itself가 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는 called될 때 다음 step을 수행합니다:

  1. bool을 ? ThisBooleanValue(this value)로 둔다.
  2. booltrue이면, "true"를 반환한다.
  3. "false"를 반환한다.

20.3.3.3 Boolean.prototype.valueOf ( )

이 method는 called될 때 다음 step을 수행합니다:

  1. ThisBooleanValue(this value)를 반환한다.

20.3.3.3.1 ThisBooleanValue ( arg )

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

  1. arg가 Boolean이면, arg를 반환한다.
  2. arg가 Object이고 arg[[BooleanData]] internal slot을 가지면, 다음을 수행한다.
    1. boolarg.[[BooleanData]]로 둔다.
    2. Assert: bool은 Boolean이다.
    3. bool을 반환한다.
  3. TypeError exception을 throw한다.

20.3.4 Properties of Boolean Instances

Boolean instance는 Boolean prototype object에서 property를 inherit하는 ordinary object입니다. Boolean instance는 [[BooleanData]] internal slot을 가집니다. [[BooleanData]] internal slot은 이 Boolean object가 represented하는 Boolean value입니다.

20.4 Symbol Objects

20.4.1 The Symbol Constructor

Symbol constructor는:

  • %Symbol%입니다.
  • global object"Symbol" property의 initial value입니다.
  • function으로 called될 때 new Symbol value를 반환합니다.
  • new operator와 함께 사용되도록 intended되지 않습니다.
  • subclassed되도록 intended되지 않습니다.
  • class definition의 extends clause의 value로 사용될 수 있지만, 이에 대한 super call은 exception을 cause합니다.

20.4.1.1 Symbol ( [ description ] )

이 function은 called될 때 다음 step을 수행합니다:

  1. NewTarget이 undefined가 아니면, TypeError exception을 throw한다.
  2. descriptionundefined이면, descStringundefined로 둔다.
  3. 그렇지 않으면, descString을 ? ToString(description)으로 둔다.
  4. ... [[Description]]descString인 new Symbol을 반환한다.

20.4.2 Properties of the Symbol Constructor

Symbol constructor는:

  • value가 %Function.prototype%[[Prototype]] internal slot을 가집니다.
  • 다음 property를 가집니다:

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은 called될 때 다음 step을 수행합니다:

  1. stringKey를 ? ToString(key)이라고 하자.
  2. agentRecord를 둘러싸는 에이전트의 Agent Record라고 하자.
  3. globalSymbolRegistryagentRecord.[[GlobalSymbolRegistry]]라고 하자.
  4. globalSymbolRegistry의 각 요소 element에 대해, 다음을 수행한다.
    1. element.[[Key]]stringKey이면, element.[[Symbol]]을 반환한다.
  5. 단언: globalSymbolRegistry는 현재 stringKey에 대한 항목을 포함하지 않는다.
  6. newSymbol[[Description]]stringKey인 새 Symbol이라고 하자.
  7. GlobalSymbolRegistry Record { [[Key]]: stringKey, [[Symbol]]: newSymbol }를 globalSymbolRegistry에 추가한다.
  8. newSymbol을 반환한다.

20.4.2.3 Symbol.hasInstance

Symbol.hasInstance의 initial value는 well-known symbol %Symbol.hasInstance%입니다(Table 1).

이 property는 attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }를 가집니다.

20.4.2.4 Symbol.isConcatSpreadable

Symbol.isConcatSpreadable의 initial value는 well-known symbol %Symbol.isConcatSpreadable%입니다(Table 1).

이 property는 attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }를 가집니다.

20.4.2.5 Symbol.iterator

Symbol.iterator의 initial value는 well-known symbol %Symbol.iterator%입니다(Table 1).

이 property는 attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }를 가집니다.

20.4.2.6 Symbol.keyFor ( symbol )

이 function은 called될 때 다음 step을 수행합니다:

  1. symbol이 Symbol이 아니면, TypeError exception을 throw한다.
  2. KeyForSymbol(symbol)을 반환한다.

20.4.2.7 Symbol.match

Symbol.match의 initial value는 well-known symbol %Symbol.match%입니다(Table 1).

이 property는 attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }를 가집니다.

20.4.2.8 Symbol.matchAll

Symbol.matchAll의 initial value는 well-known symbol %Symbol.matchAll%입니다(Table 1).

이 property는 attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }를 가집니다.

20.4.2.9 Symbol.prototype

Symbol.prototype의 initial value는 Symbol prototype object입니다.

이 property는 attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }를 가집니다.

20.4.2.10 Symbol.replace

Symbol.replace의 initial value는 well-known symbol %Symbol.replace%입니다(Table 1).

이 property는 attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }를 가집니다.

20.4.2.11 Symbol.search

Symbol.search의 initial value는 well-known symbol %Symbol.search%입니다(Table 1).

이 property는 attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }를 가집니다.

20.4.2.12 Symbol.species

Symbol.species의 initial value는 well-known symbol %Symbol.species%입니다(Table 1).

이 property는 attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }를 가집니다.

20.4.2.13 Symbol.split

Symbol.split의 initial value는 well-known symbol %Symbol.split%입니다(Table 1).

이 property는 attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }를 가집니다.

20.4.2.14 Symbol.toPrimitive

Symbol.toPrimitive의 initial value는 well-known symbol %Symbol.toPrimitive%입니다(Table 1).

이 property는 attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }를 가집니다.

20.4.2.15 Symbol.toStringTag

Symbol.toStringTag의 initial value는 well-known symbol %Symbol.toStringTag%입니다(Table 1).

이 property는 attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }를 가집니다.

20.4.2.16 Symbol.unscopables

Symbol.unscopables의 initial value는 well-known symbol %Symbol.unscopables%입니다(Table 1).

이 property는 attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }를 가집니다.

20.4.3 Properties of the Symbol Prototype Object

Symbol prototype object는:

  • %Symbol.prototype%입니다.
  • ordinary object입니다.
  • Symbol instance가 아니며 [[SymbolData]] internal slot을 가지지 않습니다.
  • value가 %Object.prototype%[[Prototype]] internal slot을 가집니다.

20.4.3.1 Symbol.prototype.constructor

Symbol.prototype.constructor의 initial value는 %Symbol%입니다.

20.4.3.2 get Symbol.prototype.description

Symbol.prototype.description은 set accessor function이 undefinedaccessor property입니다. 그 get accessor function은 called될 때 다음 step을 수행합니다:

  1. symbol을 ? ThisSymbolValue(this value)로 둔다.
  2. symbol.[[Description]]을 반환한다.

20.4.3.3 Symbol.prototype.toString ( )

이 method는 called될 때 다음 step을 수행합니다:

  1. symbol을 ? ThisSymbolValue(this value)로 둔다.
  2. SymbolDescriptiveString(symbol)을 반환한다.

20.4.3.3.1 SymbolDescriptiveString ( symbol )

The abstract operation SymbolDescriptiveString takes argument symbol (a Symbol) and returns a String. It performs the following steps when called:

  1. descriptionsymbol.[[Description]]이라고 하자.
  2. descriptionundefined이면, description을 빈 String으로 설정한다.
  3. Assert: description은 String이다.
  4. "Symbol(", description")"string-concatenation을 반환한다.

20.4.3.4 Symbol.prototype.valueOf ( )

이 method는 called될 때 다음 step을 수행합니다:

  1. ThisSymbolValue(this value)를 반환한다.

20.4.3.4.1 ThisSymbolValue ( arg )

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

  1. arg가 Symbol이면, arg를 반환한다.
  2. arg가 Object이고 arg[[SymbolData]] internal slot을 가지면, 다음을 수행한다.
    1. symbolarg.[[SymbolData]]로 둔다.
    2. Assert: symbol은 Symbol이다.
    3. symbol을 반환한다.
  3. TypeError exception을 throw한다.

20.4.3.5 Symbol.prototype [ %Symbol.toPrimitive% ] ( hint )

이 method는 ECMAScript language operator가 Symbol object를 primitive value로 convert하기 위해 called합니다.

called될 때 다음 step을 수행합니다:

  1. ThisSymbolValue(this value)를 반환한다.
Note

argument는 ignored됩니다.

이 property는 attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }를 가집니다.

이 method의 "name" property의 value는 "[Symbol.toPrimitive]"입니다.

20.4.3.6 Symbol.prototype [ %Symbol.toStringTag% ]

%Symbol.toStringTag% property의 initial value는 String value "Symbol"입니다.

이 property는 attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }를 가집니다.

20.4.4 Properties of Symbol Instances

Symbol instance는 Symbol prototype object에서 property를 inherit하는 ordinary object입니다. Symbol instance는 [[SymbolData]] internal slot을 가집니다. [[SymbolData]] internal slot은 이 Symbol object가 represented하는 Symbol value입니다.

20.4.5 Abstract Operations for Symbols

20.4.5.1 GlobalSymbolRegistry 레코드

GlobalSymbolRegistry RecordSymbol.for를 통해 등록된 Symbol 값과 String 키를 연결하는 데 사용되는 Record 값이다.

GlobalSymbolRegistry Records에는 Table 59에 나열된 필드가 있다.

Table 59: GlobalSymbolRegistry Record 필드
필드 이름 사용법
[[Key]] String Symbol을 전역적으로 식별하는 데 사용되는 문자열 키.
[[Symbol]] Symbol 어떤 realm에서도 가져올 수 있는 심벌.

20.4.5.2 KeyForSymbol ( symbol )

The abstract operation KeyForSymbol takes argument symbol (a Symbol) and returns a String or undefined. symbol이 둘러싸는 에이전트의 [[GlobalSymbolRegistry]] List 안에 있으면, symbol을 등록하는 데 사용된 String이 반환된다. It performs the following steps when called:

  1. agentRecord를 둘러싸는 에이전트의 Agent Record라고 하자.
  2. globalSymbolRegistryagentRecord.[[GlobalSymbolRegistry]]라고 하자.
  3. globalSymbolRegistry의 각 요소 element에 대해, 다음을 수행한다.
    1. SameValue(element.[[Symbol]], symbol)가 true이면, element.[[Key]]를 반환한다.
  4. 단언: globalSymbolRegistry는 현재 symbol에 대한 항목을 포함하지 않는다.
  5. undefined를 반환한다.

20.5 Error Objects

Error object의 instance는 runtime error가 occur할 때 exception으로 thrown됩니다. Error object는 user-defined exception class를 위한 base object로도 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으로 called될 때 new Error object를 create하고 initialize합니다. 따라서 function call Error(…)은 same arguments를 가진 object creation expression new Error(…)과 equivalent합니다.
  • class definition의 extends clause의 value로 사용될 수 있습니다. specified Error behaviour를 inherit하려는 subclass constructor[[ErrorData]] internal slot을 가진 subclass instance를 create하고 initialize하기 위해 Error constructor에 대한 super call을 include해야 합니다.

20.5.1.1 Error ( message [ , options ] )

이 function은 called될 때 다음 step을 수행합니다:

  1. NewTarget이 undefined이면, newTarget을 active function object로 둔다; 그렇지 않으면 newTarget을 NewTarget으로 둔다.
  2. obj를 ? OrdinaryCreateFromConstructor(newTarget, "%Error.prototype%", « [[ErrorData]] »)로 둔다.
  3. messageundefined가 아니면, 다음을 수행한다.
    1. messageString을 ? ToString(message)로 둔다.
    2. CreateNonEnumerableDataPropertyOrThrow(obj, "message", messageString)을 수행한다.
  4. InstallErrorCause(obj, options)를 수행한다.
  5. obj를 반환한다.

20.5.2 Properties of the Error Constructor

Error constructor는:

  • value가 %Function.prototype%[[Prototype]] internal slot을 가집니다.
  • 다음 property를 가집니다:

20.5.2.1 Error.isError ( arg )

이 function은 called될 때 다음 step을 수행합니다:

  1. arg가 Object가 아니면, false를 반환한다.
  2. arg[[ErrorData]] internal slot을 가지지 않으면, false를 반환한다.
  3. true를 반환한다.

20.5.2.2 Error.prototype

Error.prototype의 initial value는 Error prototype object입니다.

이 property는 attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }를 가집니다.

20.5.3 Properties of the Error Prototype Object

Error prototype object는:

  • %Error.prototype%입니다.
  • ordinary object입니다.
  • Error instance가 아니며 [[ErrorData]] internal slot을 가지지 않습니다.
  • value가 %Object.prototype%[[Prototype]] internal slot을 가집니다.

20.5.3.1 Error.prototype.constructor

Error.prototype.constructor의 initial value는 %Error%입니다.

20.5.3.2 Error.prototype.message

Error.prototype.message의 initial value는 empty String입니다.

20.5.3.3 Error.prototype.name

Error.prototype.name의 initial value는 "Error"입니다.

20.5.3.4 Error.prototype.toString ( )

이 method는 called될 때 다음 step을 수행합니다:

  1. objthis value로 둔다.
  2. obj가 Object가 아니면, TypeError exception을 throw한다.
  3. name을 ? Get(obj, "name")로 둔다.
  4. nameundefined이면, name"Error"로 설정한다; 그렇지 않으면 name을 ? ToString(name)으로 설정한다.
  5. message를 ? Get(obj, "message")로 둔다.
  6. messageundefined이면, message를 empty String으로 설정한다; 그렇지 않으면 message를 ? ToString(message)로 설정한다.
  7. name이 empty String이면, message를 반환한다.
  8. message가 empty String이면, name을 반환한다.
  9. name, code unit 0x003A (COLON), code unit 0x0020 (SPACE), 및 messagestring-concatenation을 반환한다.

20.5.4 Properties of Error Instances

Error 인스턴스는 Error 프로토타입 객체에서 속성을 상속하고 값이 undefined[[ErrorData]] 내부 슬롯을 갖는 일반 객체이다. [[ErrorData]]의 유일하게 명세된 용도는 Object.prototype.toStringError.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은 currently 이 specification 안에서 used되지 않습니다. 이 object는 이 specification의 previous edition과의 compatibility를 위해 remains합니다.

20.5.5.2 RangeError

RangeError constructor%RangeError%입니다.

allowable value의 set 또는 range 안에 있지 않은 value를 indicates합니다.

20.5.5.3 ReferenceError

ReferenceError constructor%ReferenceError%입니다.

invalid reference가 detected되었음을 indicate합니다.

20.5.5.4 SyntaxError

SyntaxError constructor%SyntaxError%입니다.

parsing error가 occurred했음을 indicates합니다.

20.5.5.5 TypeError

TypeError constructor%TypeError%입니다.

TypeError는 other NativeError object 중 none이 failure cause의 appropriate indication이 아닐 때 unsuccessful operation을 indicate하는 데 사용됩니다.

20.5.5.6 URIError

URIError constructor%URIError%입니다.

global URI handling function 중 하나가 its definition과 incompatible한 way로 사용되었음을 indicates합니다.

20.5.6 NativeError Object Structure

이러한 object 각각은 below에 described된 structure를 가지며, constructor name으로 사용되는 name 및 prototype object의 "name" property만 다릅니다.

각 error object에 대해, definition 안의 NativeError에 대한 reference는 20.5.5의 appropriate error object name으로 replaced되어야 합니다.

20.5.6.1 The NativeError Constructors

NativeError constructor는:

  • constructor가 아니라 function으로 called될 때 new NativeError object를 create하고 initialize합니다. object를 function으로 call하는 것은 same arguments를 가지고 constructor로 call하는 것과 equivalent합니다. 따라서 function call NativeError(…)는 same arguments를 가진 object creation expression new NativeError(…)과 equivalent합니다.
  • class definition의 extends clause의 value로 사용될 수 있습니다. specified NativeError behaviour를 inherit하려는 subclass constructor[[ErrorData]] internal slot을 가진 subclass instance를 create하고 initialize하기 위해 NativeError constructor에 대한 super call을 include해야 합니다.

20.5.6.1.1 NativeError ( message [ , options ] )

NativeError function은 called될 때 다음 step을 수행합니다:

  1. NewTarget이 undefined이면, newTarget을 active function object로 둔다; 그렇지 않으면 newTarget을 NewTarget으로 둔다.
  2. obj를 ? OrdinaryCreateFromConstructor(newTarget, "%NativeError.prototype%", « [[ErrorData]] »)로 둔다.
  3. messageundefined가 아니면, 다음을 수행한다.
    1. messageString을 ? ToString(message)으로 둔다.
    2. CreateNonEnumerableDataPropertyOrThrow(obj, "message", messageString)을 수행한다.
  4. InstallErrorCause(obj, options)를 수행한다.
  5. obj를 반환한다.

step 2에 passed되는 string의 actual value는 which NativeError constructor가 defined되는지에 corresponding하여 "%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을 가집니다.
  • String value "NativeError"인 value를 가진 "name" property를 가집니다.
  • 다음 property를 가집니다:

20.5.6.2.1 NativeError.prototype

NativeError.prototype의 initial value는 NativeError prototype object(20.5.6.3)입니다. 각 NativeError constructor는 distinct prototype object를 가집니다.

이 property는 attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }를 가집니다.

20.5.6.3 Properties of the NativeError Prototype Objects

NativeError prototype object는:

  • ordinary object입니다.
  • Error instance가 아니며 [[ErrorData]] internal slot을 가지지 않습니다.
  • value가 %Error.prototype%[[Prototype]] internal slot을 가집니다.

20.5.6.3.1 NativeError.prototype.constructor

given NativeError constructor에 대한 prototype의 "constructor" property의 initial value는 constructor itself입니다.

20.5.6.3.2 NativeError.prototype.message

given NativeError constructor에 대한 prototype의 "message" property의 initial value는 empty String입니다.

20.5.6.3.3 NativeError.prototype.name

given 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으로 called될 때 new AggregateError object를 create하고 initialize합니다. 따라서 function call AggregateError(…)은 same arguments를 가진 object creation expression new AggregateError(…)과 equivalent합니다.
  • class definition의 extends clause의 value로 사용될 수 있습니다. specified AggregateError behaviour를 inherit하려는 subclass constructor[[ErrorData]] internal slot을 가진 subclass instance를 create하고 initialize하기 위해 AggregateError constructor에 대한 super call을 include해야 합니다.

20.5.7.1.1 AggregateError ( errors, message [ , options ] )

이 function은 called될 때 다음 step을 수행합니다:

  1. NewTarget이 undefined이면, newTarget을 active function object로 둔다; 그렇지 않으면 newTarget을 NewTarget으로 둔다.
  2. obj를 ? OrdinaryCreateFromConstructor(newTarget, "%AggregateError.prototype%", « [[ErrorData]] »)로 둔다.
  3. messageundefined가 아니면, 다음을 수행한다.
    1. messageString을 ? ToString(message)으로 둔다.
    2. CreateNonEnumerableDataPropertyOrThrow(obj, "message", messageString)을 수행한다.
  4. InstallErrorCause(obj, options)를 수행한다.
  5. errorsList를 ? IteratorToList(? GetIterator(errors, sync))로 둔다.
  6. DefinePropertyOrThrow(obj, "errors", PropertyDescriptor { [[Configurable]]: true, [[Enumerable]]: false, [[Writable]]: true, [[Value]]: CreateArrayFromList(errorsList) })를 수행한다.
  7. obj를 반환한다.

20.5.7.2 Properties of the AggregateError Constructor

AggregateError constructor는:

  • value가 %Error%[[Prototype]] internal slot을 가집니다.
  • 다음 property를 가집니다:

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 )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. NewTarget이 undefined이면 newTarget활성 함수 객체로 둔다. 그렇지 않으면 newTarget을 NewTarget으로 둔다.
  2. obj를 ? OrdinaryCreateFromConstructor(newTarget, "%SuppressedError.prototype%", « [[ErrorData]] »)로 둔다.
  3. messageundefined가 아니면,
    1. messageString을 ? ToString(message)로 둔다.
    2. CreateNonEnumerableDataPropertyOrThrow(obj, "message", messageString)를 수행한다.
  4. CreateNonEnumerableDataPropertyOrThrow(obj, "error", error)를 수행한다.
  5. CreateNonEnumerableDataPropertyOrThrow(obj, "suppressed", suppressed)를 수행한다.
  6. obj를 반환한다.

20.5.8.2 SuppressedError 생성자의 속성

SuppressedError 생성자는 다음과 같다:

  • 값이 %Error%[[Prototype]] 내부 슬롯을 갖는다.
  • 다음 속성을 갖는다:

20.5.8.2.1 SuppressedError.prototype

SuppressedError.prototype의 초기값은 SuppressedError 프로토타입 객체이다.

이 속성은 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false } 속성을 갖는다.

20.5.8.3 SuppressedError 프로토타입 객체의 속성

SuppressedError 프로토타입 객체는 다음과 같다:

  • %SuppressedError.prototype%이다.
  • 일반 객체이다.
  • Error 인스턴스 또는 SuppressedError 인스턴스가 아니며 [[ErrorData]] 내부 슬롯을 갖지 않는다.
  • 값이 %Error.prototype%[[Prototype]] 내부 슬롯을 갖는다.

20.5.8.3.1 SuppressedError.prototype.constructor

SuppressedError.prototype.constructor의 초기값은 %SuppressedError%이다.

20.5.8.3.2 SuppressedError.prototype.message

SuppressedError.prototype.message의 초기값은 빈 String이다.

20.5.8.3.3 SuppressedError.prototype.name

SuppressedError.prototype.name의 초기값은 "SuppressedError"이다.

20.5.8.4 SuppressedError 인스턴스의 속성

SuppressedError 인스턴스는 해당 SuppressedError 프로토타입 객체에서 속성을 상속하고 값이 undefined[[ErrorData]] 내부 슬롯을 갖는 일반 객체이다. [[ErrorData]]의 유일하게 명세된 용도는 Object.prototype.toStringError.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가 present할 때 obj"cause" property를 create하는 데 사용됩니다. It performs the following steps when called:

  1. options가 Object이고 ? HasProperty(options, "cause")가 true이면, 다음을 수행한다.
    1. cause를 ? Get(options, "cause")로 둔다.
    2. CreateNonEnumerableDataPropertyOrThrow(obj, "cause", cause)를 수행한다.
  2. unused를 반환한다.

21 Numbers and Dates

21.1 Number Objects

21.1.1 The Number Constructor

Number constructor는:

  • %Number%입니다.
  • global object"Number" property의 initial value입니다.
  • constructor로 called될 때 new Number object를 create하고 initialize합니다.
  • constructor가 아니라 function으로 called될 때 type conversion을 수행합니다.
  • class definition의 extends clause의 value로 사용될 수 있습니다. specified Number behaviour를 inherit하려는 subclass constructor[[NumberData]] internal slot을 가진 subclass instance를 create하고 initialize하기 위해 Number constructor에 대한 super call을 include해야 합니다.

21.1.1.1 Number ( value )

이 function은 called될 때 다음 step을 수행합니다:

  1. value가 present이면, 다음을 수행한다.
    1. primitive를 ? ToNumeric(value)로 둔다.
    2. primitive가 BigInt이면, n𝔽((primitive))로 둔다.
    3. 그렇지 않으면, nprimitive로 둔다.
  2. 그렇지 않으면,
    1. n+0𝔽로 둔다.
  3. NewTarget이 undefined이면, n을 반환한다.
  4. obj를 ? OrdinaryCreateFromConstructor(NewTarget, "%Number.prototype%", « [[NumberData]] »)로 둔다.
  5. obj.[[NumberData]]n으로 설정한다.
  6. obj를 반환한다.

21.1.2 Properties of the Number Constructor

Number constructor는:

  • value가 %Function.prototype%[[Prototype]] internal slot을 가집니다.
  • 다음 property를 가집니다:

21.1.2.1 Number.EPSILON

Number.EPSILON의 value는 Number value로 represent 가능한 1보다 큰 smallest value와 1 사이의 difference의 magnitude에 대한 Number value이며, 이는 approximately 2.2204460492503130808472633361816 × 10-16입니다.

이 property는 attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }를 가집니다.

21.1.2.2 Number.isFinite ( number )

이 function은 called될 때 다음 step을 수행합니다:

  1. number가 Number가 아니면, false를 반환한다.
  2. numberfinite가 아니면, false를 반환한다.
  3. true를 반환한다.

21.1.2.3 Number.isInteger ( number )

이 function은 called될 때 다음 step을 수행합니다:

  1. numberintegral Number이면, true를 반환한다.
  2. false를 반환한다.

21.1.2.4 Number.isNaN ( number )

이 function은 called될 때 다음 step을 수행합니다:

  1. number가 Number가 아니면, false를 반환한다.
  2. numberNaN이면, true를 반환한다.
  3. false를 반환한다.
Note

이 function은 argument가 NaN인지 determine하기 전에 Number로 convert하지 않는다는 점에서 global isNaN function(19.2.3)과 다릅니다.

21.1.2.5 Number.isSafeInteger ( number )

Note

integer nn에 대한 Number value가 any other integer에 대한 Number value가 아닌 경우에만 “safe integer”입니다.

이 function은 called될 때 다음 step을 수행합니다:

  1. numberintegral Number이면, 다음을 수행한다.
    1. abs((number)) ≤ 253 - 1이면, true를 반환한다.
  2. false를 반환한다.

21.1.2.6 Number.MAX_SAFE_INTEGER

Note

IEEE 754-2019의 precision limitation 때문에 necessary한 rounding behaviour로 인해, Number.MAX_SAFE_INTEGER보다 큰 every integer에 대한 Number value는 at least one other integer와 shared됩니다. 따라서 such large-magnitude integersafe하지 않으며, Number value로 exactly represent 가능하거나 서로 distinguish 가능하다고 guaranteed되지 않습니다. 예를 들어, 90071992547409929007199254740993 둘 다 Number value 9007199254740992𝔽로 evaluate됩니다.

Number.MAX_SAFE_INTEGER의 value는 9007199254740991𝔽 (𝔽(253 - 1))입니다.

이 property는 attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }를 가집니다.

21.1.2.7 Number.MAX_VALUE

Number.MAX_VALUE의 value는 Number type의 largest positive finite value이며, 이는 approximately 1.7976931348623157 × 10308입니다.

이 property는 attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }를 가집니다.

21.1.2.8 Number.MIN_SAFE_INTEGER

Note

IEEE 754-2019의 precision limitation 때문에 necessary한 rounding behaviour로 인해, Number.MIN_SAFE_INTEGER보다 작은 every integer에 대한 Number value는 at least one other integer와 shared됩니다. 따라서 such large-magnitude integersafe하지 않으며, Number value로 exactly represent 가능하거나 서로 distinguish 가능하다고 guaranteed되지 않습니다. 예를 들어, -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이며, 이는 approximately 5 × 10-324입니다.

IEEE 754-2019 double precision binary representation에서, smallest possible value는 denormalized number입니다. implementation이 denormalized value를 support하지 않으면, Number.MIN_VALUE의 value는 implementation에 의해 actually represented될 수 있는 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입니다.
  • itself가 Number object입니다; value가 +0𝔽[[NumberData]] internal slot을 가집니다.
  • value가 %Object.prototype%[[Prototype]] internal slot을 가집니다.

explicitly 달리 stated되지 않는 한, 아래에 defined된 Number prototype object의 method는 generic하지 않고, 이들에게 passed되는 this value는 Number value이거나 Number value로 initialized된 [[NumberData]] internal slot을 가진 object여야 합니다.

method specification 안의 phrase “this Number value”는 method invocation의 this value를 argument로 pass하여 abstract operation ThisNumberValue를 calling한 result를 refer합니다.

21.1.3.1 Number.prototype.constructor

Number.prototype.constructor의 initial value는 %Number%입니다.

21.1.3.2 Number.prototype.toExponential ( fractionDigits )

이 method는 significand의 decimal point 앞에 one digit, significand의 decimal point 뒤에 fractionDigits digits를 가진 decimal exponential notation으로 represented된 this Number value를 contain하는 String을 반환합니다. fractionDigitsundefined이면, Number를 uniquely specify하는 데 necessary한 만큼의 significand digit을 include합니다(ToString에서와 같지만, 이 경우 Number는 always exponential notation으로 output됩니다).

called될 때 다음 step을 수행합니다:

  1. number를 ? ThisNumberValue(this value)로 둔다.
  2. fractionCount를 ? ToIntegerOrInfinity(fractionDigits)로 둔다.
  3. Assert: fractionDigitsundefined이면, fractionCount는 0이다.
  4. numberfinite가 아니면, Number::toString(number, 10)을 반환한다.
  5. fractionCount < 0 또는 fractionCount > 100이면, RangeError exception을 throw한다.
  6. number(number)로 설정한다.
  7. sign을 empty String으로 둔다.
  8. number < 0이면, 다음을 수행한다.
    1. sign"-"로 설정한다.
    2. number를 -number로 설정한다.
  9. number = 0이면, 다음을 수행한다.
    1. significand를 code unit 0x0030 (DIGIT ZERO)가 fractionCount + 1번 occurrence하는 것으로 구성된 String value로 둔다.
    2. exponent를 0으로 둔다.
  10. 그렇지 않으면,
    1. fractionDigitsundefined가 아니면, 다음을 수행한다.
      1. exponentintSignificand를 10fractionCountintSignificand < 10fractionCount + 1이고 intSignificand × 10exponent - fractionCount - number가 가능한 한 zero에 close한 integers로 둔다. such exponentintSignificand의 set이 two이면, intSignificand × 10exponent - fractionCount가 larger인 exponentintSignificand를 pick한다.
    2. 그렇지 않으면,
      1. exponent, intSignificand, 및 ffff ≥ 0, 10ffintSignificand < 10ff + 1, 𝔽(intSignificand × 10exponent - ff) is 𝔽(number), 그리고 ff가 가능한 한 small인 integers로 둔다. intSignificand의 decimal representation은 ff + 1 digits를 가지고, intSignificand는 10으로 divisible하지 않으며, intSignificand의 least significant digit이 these criteria에 의해 necessarily uniquely determined되는 것은 아님에 note한다.
      2. fractionCountff로 설정한다.
    3. significandintSignificand의 decimal representation의 digits로 구성된 String value로 둔다(in order, with no leading zeroes).
  11. fractionCount ≠ 0이면, 다음을 수행한다.
    1. intPartsignificand의 first code unit으로 둔다.
    2. fractionalPartsignificand의 other fractionCount code unit으로 둔다.
    3. significandintPart, ".", 및 fractionalPartstring-concatenation으로 설정한다.
  12. exponent = 0이면, 다음을 수행한다.
    1. exponentSign"+"로 둔다.
    2. exponentDigits"0"으로 둔다.
  13. 그렇지 않으면,
    1. exponent > 0이면, 다음을 수행한다.
      1. exponentSign"+"로 둔다.
    2. 그렇지 않으면,
      1. Assert: exponent < 0이다.
      2. exponentSign"-"로 둔다.
      3. exponent를 -exponent로 설정한다.
    3. exponentDigitsexponent의 decimal representation의 digits로 구성된 String value로 둔다(in order, with no leading zeroes).
  14. significandsignificand, "e", exponentSign, 및 exponentDigitsstring-concatenation으로 설정한다.
  15. signsignificandstring-concatenation을 반환한다.
Note

above rules에 의해 required되는 것보다 more accurate conversion을 provide하는 implementation의 경우, step 10.b.i의 다음 alternative version을 guideline으로 사용할 것이 recommended됩니다:

  1. exponent, intSignificand, 및 ffff ≥ 0, 10ffintSignificand < 10ff + 1, 𝔽(intSignificand × 10exponent - ff) is 𝔽(number), 그리고 ff가 가능한 한 small인 integers로 둔다. intSignificand에 대해 multiple possibility가 있으면, 𝔽(intSignificand × 10exponent - ff)가 𝔽(number)에 closest한 intSignificand를 choose한다. such possible value of intSignificand가 two이면, even인 것을 choose한다.

21.1.3.3 Number.prototype.toFixed ( fractionDigits )

Note 1

이 method는 decimal point 뒤에 fractionDigits digits를 가진 decimal fixed-point notation으로 represented된 this Number value를 contain하는 String을 반환합니다. fractionDigitsundefined이면, 0이 assumed됩니다.

called될 때 다음 step을 수행합니다:

  1. number를 ? ThisNumberValue(this value)로 둔다.
  2. fractionCount를 ? ToIntegerOrInfinity(fractionDigits)로 둔다.
  3. Assert: fractionDigitsundefined이면, fractionCount는 0이다.
  4. fractionCountfinite가 아니면, RangeError exception을 throw한다.
  5. fractionCount < 0 또는 fractionCount > 100이면, RangeError exception을 throw한다.
  6. numberfinite가 아니면, Number::toString(number, 10)을 반환한다.
  7. number(number)로 설정한다.
  8. sign을 empty String으로 둔다.
  9. number < 0이면, 다음을 수행한다.
    1. sign"-"로 설정한다.
    2. number를 -number로 설정한다.
  10. number ≥ 1021이면, 다음을 수행한다.
    1. digitString을 ! ToString(𝔽(number))으로 둔다.
  11. 그렇지 않으면,
    1. intValueintValue / 10fractionCount - number가 가능한 한 zero에 close한 integer로 둔다. such intValue가 two이면, larger intValue를 pick한다.
    2. intValue = 0이면, digitString"0"으로 둔다; 그렇지 않으면 digitStringintValue의 decimal representation의 digits로 구성된 String value로 둔다(in order, with no leading zeroes).
    3. fractionCount ≠ 0이면, 다음을 수행한다.
      1. digitCountdigitString의 length로 둔다.
      2. digitCountfractionCount이면, 다음을 수행한다.
        1. zeroPad를 code unit 0x0030 (DIGIT ZERO)가 fractionCount + 1 - digitCount번 occurrence하는 것으로 구성된 String value로 둔다.
        2. digitStringzeroPaddigitStringstring-concatenation으로 설정한다.
        3. digitCountfractionCount + 1로 설정한다.
      3. intPartdigitString의 first digitCount - fractionCount code units로 둔다.
      4. fractionalPartdigitString의 other fractionCount code units로 둔다.
      5. digitStringintPart, ".", 및 fractionalPartstring-concatenation으로 설정한다.
  12. signdigitStringstring-concatenation을 반환한다.
Note 2

toString은 adjacent Number value와 number를 distinguish하기에 enough significant digits만 print하므로, some value에 대해 toFixed의 output은 toString보다 more precise할 수 있습니다. 예를 들어,

(1000000000000000128).toString()"1000000000000000100"을 반환하는 반면,
(1000000000000000128).toFixed(0)"1000000000000000128"을 반환합니다.

21.1.3.4 Number.prototype.toLocaleString ( [ reserved1 [ , reserved2 ] ] )

ECMA-402 Internationalization API를 include하는 ECMAScript implementation은 ECMA-402 specification에 specified된 대로 이 method를 implement해야 합니다. ECMAScript implementation이 ECMA-402 API를 include하지 않으면 이 method의 다음 specification이 사용됩니다:

이 method는 host environment의 current locale의 convention에 따라 formatted된 this Number value를 represent하는 String value를 produce합니다. 이 method는 implementation-defined이며, toString과 same thing을 return하는 것이 permissible하지만 encouraged되지는 않습니다.

이 method의 optional parameter의 meaning은 ECMA-402 specification에 defined되어 있습니다; ECMA-402 support를 include하지 않는 implementation은 those parameter position을 anything else에 사용해서는 안 됩니다.

21.1.3.5 Number.prototype.toPrecision ( precision )

이 method는 significand의 decimal point 앞에 one digit, significand의 decimal point 뒤에 precision - 1 digits를 가진 decimal exponential notation 또는 precision significant digits를 가진 decimal fixed notation 중 하나로 represented된 this Number value를 contain하는 String을 반환합니다. precisionundefined이면, 대신 ToString을 call합니다.

called될 때 다음 step을 수행합니다:

  1. number를 ? ThisNumberValue(this value)로 둔다.
  2. precisionundefined이면, ! ToString(number)을 반환한다.
  3. precisionCount를 ? ToIntegerOrInfinity(precision)로 둔다.
  4. numberfinite가 아니면, Number::toString(number, 10)을 반환한다.
  5. precisionCount < 1 또는 precisionCount > 100이면, RangeError exception을 throw한다.
  6. number(number)로 설정한다.
  7. sign을 empty String으로 둔다.
  8. number < 0이면, 다음을 수행한다.
    1. sign을 code unit 0x002D (HYPHEN-MINUS)로 설정한다.
    2. number를 -number로 설정한다.
  9. number = 0이면, 다음을 수행한다.
    1. significand를 code unit 0x0030 (DIGIT ZERO)가 precisionCount번 occurrence하는 것으로 구성된 String value로 둔다.
    2. exponent를 0으로 둔다.
  10. 그렇지 않으면,
    1. exponentintSignificand를 10precisionCount - 1intSignificand < 10precisionCount이고 intSignificand × 10exponent - precisionCount + 1 - number가 가능한 한 zero에 close한 integers로 둔다. such exponentintSignificand의 set이 two이면, intSignificand × 10exponent - precisionCount + 1이 larger인 exponentintSignificand를 pick한다.
    2. significandintSignificand의 decimal representation의 digits로 구성된 String value로 둔다(in order, with no leading zeroes).
    3. exponent < -6 또는 exponentprecisionCount이면, 다음을 수행한다.
      1. Assert: exponent ≠ 0이다.
      2. precisionCount ≠ 1이면, 다음을 수행한다.
        1. intPartsignificand의 first code unit으로 둔다.
        2. fractionalPartsignificand의 other precisionCount - 1 code units로 둔다.
        3. significandintPart, ".", 및 fractionalPartstring-concatenation으로 설정한다.
      3. exponent > 0이면, 다음을 수행한다.
        1. exponentSign을 code unit 0x002B (PLUS SIGN)로 둔다.
      4. 그렇지 않으면,
        1. Assert: exponent < 0이다.
        2. exponentSign을 code unit 0x002D (HYPHEN-MINUS)로 둔다.
        3. exponent를 -exponent로 설정한다.
      5. exponentDigitsexponent의 decimal representation의 digits로 구성된 String value로 둔다(in order, with no leading zeroes).
      6. sign, significand, code unit 0x0065 (LATIN SMALL LETTER E), exponentSign, 및 exponentDigitsstring-concatenation을 반환한다.
  11. exponent = precisionCount - 1이면, signsignificandstring-concatenation을 반환한다.
  12. exponent ≥ 0이면, 다음을 수행한다.
    1. significandsignificand의 first exponent + 1 code units, code unit 0x002E (FULL STOP), 및 significand의 remaining precisionCount - (exponent + 1) code units의 string-concatenation으로 설정한다.
  13. 그렇지 않으면,
    1. significand를 code unit 0x0030 (DIGIT ZERO), code unit 0x002E (FULL STOP), code unit 0x0030 (DIGIT ZERO)의 -(exponent + 1) occurrences, 및 String significandstring-concatenation으로 설정한다.
  14. signsignificandstring-concatenation을 반환한다.

21.1.3.6 Number.prototype.toString ( [ radix ] )

Note

optional radix2𝔽부터 36𝔽까지의 inclusive interval 안에 있는 integral Number value여야 합니다. radixundefined이면 10𝔽radix의 value로 사용됩니다.

이 method는 called될 때 다음 step을 수행합니다:

  1. x를 ? ThisNumberValue(this value)로 둔다.
  2. radixundefined이면, radixMV를 10으로 둔다.
  3. 그렇지 않으면, radixMV를 ? ToIntegerOrInfinity(radix)로 둔다.
  4. radixMV가 2부터 36까지의 inclusive interval 안에 있지 않으면, RangeError exception을 throw한다.
  5. Number::toString(x, radixMV)를 반환한다.

이 method는 generic하지 않습니다; this value가 Number 또는 Number object가 아니면 TypeError exception을 throw합니다. 따라서 method로 사용하기 위해 다른 kind의 object로 transferred될 수 없습니다.

이 method의 "length" property는 1𝔽입니다.

21.1.3.7 Number.prototype.valueOf ( )

  1. ThisNumberValue(this value)를 반환한다.

21.1.3.7.1 ThisNumberValue ( arg )

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

  1. arg가 Number이면, arg를 반환한다.
  2. arg가 Object이고 arg[[NumberData]] internal slot을 가지면, 다음을 수행한다.
    1. numberarg.[[NumberData]]로 둔다.
    2. Assert: number는 Number이다.
    3. number를 반환한다.
  3. TypeError exception을 throw한다.

21.1.4 Properties of Number Instances

Number instance는 Number prototype object에서 property를 inherit하는 ordinary object입니다. Number instance는 또한 [[NumberData]] internal slot을 가집니다. [[NumberData]] internal slot은 이 Number object가 represented하는 Number value입니다.

21.2 BigInt Objects

21.2.1 The BigInt Constructor

BigInt constructor는:

  • %BigInt%입니다.
  • global object"BigInt" property의 initial value입니다.
  • constructor가 아니라 function으로 called될 때 type conversion을 수행합니다.
  • new operator와 함께 사용되거나 subclassed되도록 intended되지 않습니다. class definition의 extends clause의 value로 사용될 수 있지만 BigInt constructor에 대한 super call은 exception을 cause합니다.

21.2.1.1 BigInt ( value )

이 function은 called될 때 다음 step을 수행합니다:

  1. NewTarget이 undefined가 아니면, TypeError exception을 throw한다.
  2. primitive를 ? ToPrimitive(value, number)로 둔다.
  3. primitive가 Number이면, ? NumberToBigInt(primitive)를 반환한다.
  4. ToBigInt(primitive)를 반환한다.

21.2.1.1.1 NumberToBigInt ( number )

The abstract operation NumberToBigInt takes argument number (a Number) and returns either a normal completion containing a BigInt or a throw completion. It performs the following steps when called:

  1. numberintegral Number가 아니면, RangeError exception을 throw한다.
  2. ((number))를 반환한다.

21.2.2 Properties of the BigInt Constructor

BigInt constructor는:

  • value가 %Function.prototype%[[Prototype]] internal slot을 가집니다.
  • 다음 property를 가집니다:

21.2.2.1 BigInt.asIntN ( bits, bigint )

이 function은 called될 때 다음 step을 수행합니다:

  1. bits를 ? ToIndex(bits)로 설정한다.
  2. bigint를 ? ToBigInt(bigint)로 설정한다.
  3. remainder(bigint) modulo 2bits라고 하자.
  4. remainder ≥ 2bits - 1이면, (remainder - 2bits)를 반환한다.
  5. (remainder)를 반환한다.

21.2.2.2 BigInt.asUintN ( bits, bigint )

이 function은 called될 때 다음 step을 수행합니다:

  1. bits를 ? ToIndex(bits)로 설정한다.
  2. bigint를 ? ToBigInt(bigint)로 설정한다.
  3. ((bigint) modulo 2bits)를 반환한다.

21.2.2.3 BigInt.prototype

BigInt.prototype의 initial value는 BigInt prototype object입니다.

이 property는 attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }를 가집니다.

21.2.3 Properties of the BigInt Prototype Object

BigInt prototype object는:

  • %BigInt.prototype%입니다.
  • ordinary object입니다.
  • BigInt object가 아닙니다; [[BigIntData]] internal slot을 가지지 않습니다.
  • value가 %Object.prototype%[[Prototype]] internal slot을 가집니다.

method specification 안의 phrase “this BigInt value”는 method invocation의 this value를 argument로 pass하여 abstract operation ThisBigIntValue를 calling한 result를 refer합니다.

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를 include하는 ECMAScript implementation은 ECMA-402 specification에 specified된 대로 이 method를 implement해야 합니다. ECMAScript implementation이 ECMA-402 API를 include하지 않으면 이 method의 다음 specification이 사용됩니다:

이 method는 host environment의 current locale의 convention에 따라 formatted된 this BigInt value를 represent하는 String value를 produce합니다. 이 method는 implementation-defined이며, toString과 same thing을 return하는 것이 permissible하지만 encouraged되지는 않습니다.

이 method의 optional parameter의 meaning은 ECMA-402 specification에 defined되어 있습니다; ECMA-402 support를 include하지 않는 implementation은 those parameter position을 anything else에 사용해서는 안 됩니다.

21.2.3.3 BigInt.prototype.toString ( [ radix ] )

Note

optional radix2𝔽부터 36𝔽까지의 inclusive interval 안에 있는 integral Number value여야 합니다. radixundefined이면 10𝔽radix의 value로 사용됩니다.

이 method는 called될 때 다음 step을 수행합니다:

  1. x를 ? ThisBigIntValue(this value)로 둔다.
  2. radixundefined이면, radixMV를 10으로 둔다.
  3. 그렇지 않으면, radixMV를 ? ToIntegerOrInfinity(radix)로 둔다.
  4. radixMV가 2부터 36까지의 inclusive interval 안에 있지 않으면, RangeError exception을 throw한다.
  5. BigInt::toString(x, radixMV)를 반환한다.

이 method는 generic하지 않습니다; this value가 BigInt 또는 BigInt object가 아니면 TypeError exception을 throw합니다. 따라서 method로 사용하기 위해 다른 kind의 object로 transferred될 수 없습니다.

21.2.3.4 BigInt.prototype.valueOf ( )

  1. ThisBigIntValue(this value)를 반환한다.

21.2.3.4.1 ThisBigIntValue ( arg )

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

  1. arg가 BigInt이면, arg를 반환한다.
  2. arg가 Object이고 arg[[BigIntData]] internal slot을 가지면, 다음을 수행한다.
    1. Assert: arg.[[BigIntData]]는 BigInt이다.
    2. arg.[[BigIntData]]를 반환한다.
  3. TypeError exception을 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 instance는 BigInt prototype object에서 property를 inherit하는 ordinary object입니다. BigInt instance는 또한 [[BigIntData]] internal slot을 가집니다. [[BigIntData]] internal slot은 이 BigInt object가 represented하는 BigInt value입니다.

21.3 The Math Object

Math object는:

  • %Math%입니다.
  • global object"Math" property의 initial value입니다.
  • ordinary object입니다.
  • value가 %Object.prototype%[[Prototype]] internal slot을 가집니다.
  • function object가 아닙니다.
  • [[Construct]] internal method를 가지지 않습니다; new operator와 함께 constructor로 사용될 수 없습니다.
  • [[Call]] internal method를 가지지 않습니다; function으로 invoked될 수 없습니다.
Note

이 specification에서 phrase “the Number value for x”는 6.1.6.1에 defined된 technical meaning을 가집니다.

21.3.1 Value Properties of the Math Object

21.3.1.1 Math.E

natural logarithm의 base인 e에 대한 Number value이며, 이는 approximately 2.7182818284590452354입니다.

이 property는 attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }를 가집니다.

21.3.1.2 Math.LN10

10의 natural logarithm에 대한 Number value이며, 이는 approximately 2.302585092994046입니다.

이 property는 attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }를 가집니다.

21.3.1.3 Math.LN2

2의 natural logarithm에 대한 Number value이며, 이는 approximately 0.6931471805599453입니다.

이 property는 attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }를 가집니다.

21.3.1.4 Math.LOG10E

natural logarithm의 base인 e의 base-10 logarithm에 대한 Number value입니다; 이 value는 approximately 0.4342944819032518입니다.

이 property는 attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }를 가집니다.

Note

Math.LOG10E의 value는 Math.LN10의 value의 reciprocal에 approximate합니다.

21.3.1.5 Math.LOG2E

natural logarithm의 base인 e의 base-2 logarithm에 대한 Number value입니다; 이 value는 approximately 1.4426950408889634입니다.

이 property는 attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }를 가집니다.

Note

Math.LOG2E의 value는 Math.LN2의 value의 reciprocal에 approximate합니다.

21.3.1.6 Math.PI

circle의 circumference와 diameter의 ratio인 π에 대한 Number value이며, 이는 approximately 3.1415926535897932입니다.

이 property는 attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }를 가집니다.

21.3.1.7 Math.SQRT1_2

½의 square root에 대한 Number value이며, 이는 approximately 0.7071067811865476입니다.

이 property는 attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }를 가집니다.

Note

Math.SQRT1_2의 value는 Math.SQRT2의 value의 reciprocal에 approximate합니다.

21.3.1.8 Math.SQRT2

2의 square root에 대한 Number value이며, 이는 approximately 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

acos, acosh, asin, asinh, atan, atanh, atan2, cbrt, cos, cosh, exp, expm1, hypot, log, log1p, log2, log10, pow, random, sin, sinh, tan, 및 tanh function의 behaviour는 interest의 boundary case를 represent하는 certain argument value에 대해 specific result를 require하는 것 외에는 여기에서 precisely specified되지 않습니다. other argument value에 대해, these function은 familiar mathematical function의 result에 대한 approximation을 compute하도록 intended되지만, approximation algorithm 선택에는 some latitude가 allowed됩니다. general intent는 implementer가 given hardware platform에서 C programmer에게 available한 same mathematical library를 ECMAScript에 사용할 수 있게 하는 것입니다.

algorithm 선택은 implementation에 left되지만, implementation은 Sun Microsystems의 freely distributable mathematical library인 fdlibm(http://www.netlib.org/fdlibm)에 contained된 IEEE 754-2019 arithmetic을 위한 approximation algorithm을 사용할 것이 recommended됩니다(이 standard에 의해 specified되지는 않음).

21.3.2.1 Math.abs ( x )

이 function은 x의 absolute value를 반환합니다; result는 x와 same magnitude를 가지지만 positive sign을 가집니다.

called될 때 다음 step을 수행합니다:

  1. n을 ? ToNumber(x)로 둔다.
  2. nNaN이면, NaN을 반환한다.
  3. n-0𝔽이면, +0𝔽를 반환한다.
  4. n-∞𝔽이면, +∞𝔽를 반환한다.
  5. n < -0𝔽이면, -n을 반환한다.
  6. n을 반환한다.

21.3.2.2 Math.acos ( x )

이 function은 x의 inverse cosine을 반환합니다. result는 radians로 expressed되며 +0𝔽부터 𝔽(π)까지의 inclusive interval 안에 있습니다.

called될 때 다음 step을 수행합니다:

  1. n을 ? ToNumber(x)로 둔다.
  2. nNaN이거나, n > 1𝔽이거나, n < -1𝔽이면, NaN을 반환한다.
  3. n1𝔽이면, +0𝔽를 반환한다.
  4. (n)의 inverse cosine을 represent하는 implementation-approximated Number value를 반환한다.

21.3.2.3 Math.acosh ( x )

이 function은 x의 inverse hyperbolic cosine을 반환합니다.

called될 때 다음 step을 수행합니다:

  1. n을 ? ToNumber(x)로 둔다.
  2. nNaN 또는 +∞𝔽 중 하나이면, n을 반환한다.
  3. n1𝔽이면, +0𝔽를 반환한다.
  4. n < 1𝔽이면, NaN을 반환한다.
  5. (n)의 inverse hyperbolic cosine을 represent하는 implementation-approximated Number value를 반환한다.

21.3.2.4 Math.asin ( x )

이 function은 x의 inverse sine을 반환합니다. result는 radians로 expressed되며 𝔽(-π / 2)부터 𝔽(π / 2)까지의 inclusive interval 안에 있습니다.

called될 때 다음 step을 수행합니다:

  1. n을 ? ToNumber(x)로 둔다.
  2. nNaN, +0𝔽, 또는 -0𝔽 중 하나이면, n을 반환한다.
  3. n > 1𝔽 또는 n < -1𝔽이면, NaN을 반환한다.
  4. (n)의 inverse sine을 represent하는 implementation-approximated Number value를 반환한다.

21.3.2.5 Math.asinh ( x )

이 function은 x의 inverse hyperbolic sine을 반환합니다.

called될 때 다음 step을 수행합니다:

  1. n을 ? ToNumber(x)로 둔다.
  2. nfinite가 아니거나 n+0𝔽 또는 -0𝔽 중 하나이면, n을 반환한다.
  3. (n)의 inverse hyperbolic sine을 represent하는 implementation-approximated Number value를 반환한다.

21.3.2.6 Math.atan ( x )

이 function은 x의 inverse tangent를 반환합니다. result는 radians로 expressed되며 𝔽(-π / 2)부터 𝔽(π / 2)까지의 inclusive interval 안에 있습니다.

called될 때 다음 step을 수행합니다:

  1. n을 ? ToNumber(x)로 둔다.
  2. nNaN, +0𝔽, 또는 -0𝔽 중 하나이면, n을 반환한다.
  3. n+∞𝔽이면, π / 2를 represent하는 implementation-approximated Number value를 반환한다.
  4. n-∞𝔽이면, -π / 2를 represent하는 implementation-approximated Number value를 반환한다.
  5. (n)의 inverse tangent를 represent하는 implementation-approximated Number value를 반환한다.

21.3.2.7 Math.atanh ( x )

이 function은 x의 inverse hyperbolic tangent를 반환합니다.

called될 때 다음 step을 수행합니다:

  1. n을 ? ToNumber(x)로 둔다.
  2. nNaN, +0𝔽, 또는 -0𝔽 중 하나이면, n을 반환한다.
  3. n > 1𝔽 또는 n < -1𝔽이면, NaN을 반환한다.
  4. n1𝔽이면, +∞𝔽를 반환한다.
  5. n-1𝔽이면, -∞𝔽를 반환한다.
  6. (n)의 inverse hyperbolic tangent를 represent하는 implementation-approximated Number value를 반환한다.

21.3.2.8 Math.atan2 ( y, x )

이 function은 arguments yx의 quotient y / x의 inverse tangent를 반환하며, yx의 sign은 result의 quadrant를 determine하는 데 사용됩니다. two-argument inverse tangent function에서 y라는 argument가 first이고 x라는 argument가 second인 것은 intentional이며 traditional임에 note하십시오. result는 radians로 expressed되며 -π부터 +π까지의 inclusive interval 안에 있습니다.

called될 때 다음 step을 수행합니다:

  1. ny를 ? ToNumber(y)로 둔다.
  2. nx를 ? ToNumber(x)로 둔다.
  3. nyNaN이거나 nxNaN이면, NaN을 반환한다.
  4. ny+∞𝔽이면, 다음을 수행한다.
    1. nx+∞𝔽이면, π / 4를 represent하는 implementation-approximated Number value를 반환한다.
    2. nx-∞𝔽이면, 3π / 4를 represent하는 implementation-approximated Number value를 반환한다.
    3. π / 2를 represent하는 implementation-approximated Number value를 반환한다.
  5. ny-∞𝔽이면, 다음을 수행한다.
    1. nx+∞𝔽이면, -π / 4를 represent하는 implementation-approximated Number value를 반환한다.
    2. nx-∞𝔽이면, -3π / 4를 represent하는 implementation-approximated Number value를 반환한다.
    3. -π / 2를 represent하는 implementation-approximated Number value를 반환한다.
  6. ny+0𝔽이면, 다음을 수행한다.
    1. nx > +0𝔽이거나 nx+0𝔽이면, +0𝔽를 반환한다.
    2. π를 represent하는 implementation-approximated Number value를 반환한다.
  7. ny-0𝔽이면, 다음을 수행한다.
    1. nx > +0𝔽이거나 nx+0𝔽이면, -0𝔽를 반환한다.
    2. -π를 represent하는 implementation-approximated Number value를 반환한다.
  8. Assert: nyfinite이고 +0𝔽-0𝔽도 아니다.
  9. ny > +0𝔽이면, 다음을 수행한다.
    1. nx+∞𝔽이면, +0𝔽를 반환한다.
    2. nx-∞𝔽이면, π를 represent하는 implementation-approximated Number value를 반환한다.
    3. nx+0𝔽 또는 -0𝔽 중 하나이면, π / 2를 represent하는 implementation-approximated Number value를 반환한다.
  10. ny < -0𝔽이면, 다음을 수행한다.
    1. nx+∞𝔽이면, -0𝔽를 반환한다.
    2. nx-∞𝔽이면, -π를 represent하는 implementation-approximated Number value를 반환한다.
    3. nx+0𝔽 또는 -0𝔽 중 하나이면, -π / 2를 represent하는 implementation-approximated Number value를 반환한다.
  11. Assert: nxfinite이고 +0𝔽-0𝔽도 아니다.
  12. resultabs((ny) / (nx))의 inverse tangent로 둔다.
  13. nx < -0𝔽이면, 다음을 수행한다.
    1. ny > +0𝔽이면, result를 π - result로 설정한다.
    2. 그렇지 않으면, result를 -π + result로 설정한다.
  14. 그렇지 않으면,
    1. ny < -0𝔽이면, result를 -result로 설정한다.
  15. result를 represent하는 implementation-approximated Number value를 반환한다.

21.3.2.9 Math.cbrt ( x )

이 function은 x의 cube root를 반환합니다.

called될 때 다음 step을 수행합니다:

  1. n을 ? ToNumber(x)로 둔다.
  2. nfinite가 아니거나 n+0𝔽 또는 -0𝔽 중 하나이면, n을 반환한다.
  3. (n)의 cube root를 represent하는 implementation-approximated Number value를 반환한다.

21.3.2.10 Math.ceil ( x )

이 function은 x보다 less하지 않은 smallest(closest to -∞) integral Number value를 반환합니다. x가 already integral Number이면, result는 x입니다.

called될 때 다음 step을 수행합니다:

  1. n을 ? ToNumber(x)로 둔다.
  2. nfinite가 아니거나 n+0𝔽 또는 -0𝔽 중 하나이면, n을 반환한다.
  3. n < -0𝔽이고 n > -1𝔽이면, -0𝔽를 반환한다.
  4. nintegral Number이면, n을 반환한다.
  5. n보다 less하지 않은 smallest(closest to -∞) integral Number value를 반환한다.
Note

Math.ceil(x)의 value는 -Math.floor(-x)의 value와 same입니다.

21.3.2.11 Math.clz32 ( x )

이 function은 called될 때 다음 step을 수행합니다:

  1. n을 ? ToUint32(x)로 둔다.
  2. pn의 unsigned 32-bit binary representation 안의 leading zero bit 수로 둔다.
  3. 𝔽(p)를 반환한다.
Note

n+0𝔽 또는 -0𝔽 중 하나이면, 이 method는 32𝔽를 반환합니다. n의 32-bit binary encoding의 most significant bit가 1이면, 이 method는 +0𝔽를 반환합니다.

21.3.2.12 Math.cos ( x )

이 function은 x의 cosine을 반환합니다. argument는 radians로 expressed됩니다.

called될 때 다음 step을 수행합니다:

  1. n을 ? ToNumber(x)로 둔다.
  2. nfinite가 아니면, NaN을 반환한다.
  3. n+0𝔽 또는 -0𝔽 중 하나이면, 1𝔽를 반환한다.
  4. (n)의 cosine을 represent하는 implementation-approximated Number value를 반환한다.

21.3.2.13 Math.cosh ( x )

이 function은 x의 hyperbolic cosine을 반환합니다.

called될 때 다음 step을 수행합니다:

  1. n을 ? ToNumber(x)로 둔다.
  2. nNaN이면, NaN을 반환한다.
  3. n+∞𝔽 또는 -∞𝔽 중 하나이면, +∞𝔽를 반환한다.
  4. n+0𝔽 또는 -0𝔽 중 하나이면, 1𝔽를 반환한다.
  5. (n)의 hyperbolic cosine을 represent하는 implementation-approximated Number value를 반환한다.
Note

Math.cosh(x)의 value는 (Math.exp(x) + Math.exp(-x)) / 2의 value와 same입니다.

21.3.2.14 Math.exp ( x )

이 function은 x의 exponential function(e raised to the power of x, 여기서 e는 natural logarithm의 base)을 반환합니다.

called될 때 다음 step을 수행합니다:

  1. n을 ? ToNumber(x)로 둔다.
  2. nNaN 또는 +∞𝔽 중 하나이면, n을 반환한다.
  3. n+0𝔽 또는 -0𝔽 중 하나이면, 1𝔽를 반환한다.
  4. n-∞𝔽이면, +0𝔽를 반환한다.
  5. (n)의 exponential function을 represent하는 implementation-approximated Number value를 반환한다.

21.3.2.15 Math.expm1 ( x )

이 function은 x의 exponential function(e raised to the power of x, 여기서 e는 natural logarithm의 base)에서 1을 subtract한 result를 반환합니다. result는 x의 value가 0에 close한 경우에도 accurate한 way로 computed됩니다.

called될 때 다음 step을 수행합니다:

  1. n을 ? ToNumber(x)로 둔다.
  2. nNaN, +0𝔽, -0𝔽, 또는 +∞𝔽 중 하나이면, n을 반환한다.
  3. n-∞𝔽이면, -1𝔽를 반환한다.
  4. exp(n)의 exponential function으로 둔다.
  5. exp - 1을 represent하는 implementation-approximated Number value를 반환한다.

21.3.2.16 Math.floor ( x )

이 function은 x보다 greater하지 않은 greatest(closest to +∞) integral Number value를 반환합니다. x가 already integral Number이면, result는 x입니다.

called될 때 다음 step을 수행합니다:

  1. n을 ? ToNumber(x)로 둔다.
  2. nfinite가 아니거나 n+0𝔽 또는 -0𝔽 중 하나이면, n을 반환한다.
  3. n < 1𝔽이고 n > +0𝔽이면, +0𝔽를 반환한다.
  4. nintegral Number이면, n을 반환한다.
  5. n보다 greater하지 않은 greatest(closest to +∞) integral Number value를 반환한다.
Note

Math.floor(x)의 value는 -Math.ceil(-x)의 value와 same입니다.

21.3.2.17 Math.fround ( x )

이 function은 called될 때 다음 step을 수행합니다:

  1. n을 ? ToNumber(x)로 둔다.
  2. nNaN이면, NaN을 반환한다.
  3. n+0𝔽, -0𝔽, +∞𝔽, 또는 -∞𝔽 중 하나이면, n을 반환한다.
  4. n32를 roundTiesToEven mode를 사용하여 nIEEE 754-2019 binary32 format으로 converting한 result로 둔다.
  5. n64n32IEEE 754-2019 binary64 format으로 converting한 result로 둔다.
  6. n64에 corresponding하는 ECMAScript Number value를 반환한다.

21.3.2.18 Math.f16round ( x )

이 function은 called될 때 다음 step을 수행합니다:

  1. n을 ? ToNumber(x)로 둔다.
  2. nNaN이면, NaN을 반환한다.
  3. n+0𝔽, -0𝔽, +∞𝔽, 또는 -∞𝔽 중 하나이면, n을 반환한다.
  4. n16을 roundTiesToEven mode를 사용하여 nIEEE 754-2019 binary16 format으로 converting한 result로 둔다.
  5. n64n16IEEE 754-2019 binary64 format으로 converting한 result로 둔다.
  6. n64에 corresponding하는 ECMAScript Number value를 반환한다.
Note

이 operation은 double-rounding 가능성 때문에 binary32로 cast한 다음 binary16으로 cast하는 것과 same하지 않습니다: 예를 들어 number k = 1.00048828125000022204𝔽를 consider하면, Math.f16round(k)는 1.0009765625𝔽이지만, Math.f16round(Math.fround(k))는 1𝔽입니다.

모든 platform이 binary64에서 binary16으로 casting하는 native support를 provide하는 것은 아닙니다. 이를 provide할 수 있는 다양한 library가 있으며, 여기에는 MIT-licensed half library가 include됩니다. Alternatively, roundTiesToEven 하에서 binary64에서 binary32로 first cast한 다음 result가 incorrect double-rounding으로 이어질 수 있는지 check할 수 있습니다. such case는 binary32 value의 mantissa를 initial cast를 roundTiesToOdd 하에서 수행했을 때 produced될 value가 되도록 adjusting함으로써 explicitly handled될 수 있습니다. adjusted value를 roundTiesToEven 하에서 binary16으로 casting하면 correct value가 produced됩니다.

21.3.2.19 Math.hypot ( ...args )

zero or more arguments가 given되면, 이 function은 그 arguments의 squares의 sum의 square root를 반환합니다.

called될 때 다음 step을 수행합니다:

  1. coerced를 새 empty List로 둔다.
  2. args의 각 element arg에 대해, 다음을 수행한다.
    1. n을 ? ToNumber(arg)로 둔다.
    2. ncoerced에 append한다.
  3. coerced의 각 element number에 대해, 다음을 수행한다.
    1. number+∞𝔽 또는 -∞𝔽 중 하나이면, +∞𝔽를 반환한다.
  4. onlyZerotrue로 둔다.
  5. coerced의 각 element number에 대해, 다음을 수행한다.
    1. numberNaN이면, NaN을 반환한다.
    2. number+0𝔽-0𝔽도 아니면, onlyZerofalse로 설정한다.
  6. onlyZerotrue이면, +0𝔽를 반환한다.
  7. coerced의 element의 mathematical value의 squares의 sum의 square root를 represent하는 implementation-approximated Number value를 반환한다.

이 function의 "length" property는 2𝔽입니다.

Note

implementation은 이 function이 two or more arguments와 함께 called될 때 naive implementation에서 발생하기 쉬운 overflow 및 underflow로 인한 precision loss를 avoid하도록 care해야 합니다.

21.3.2.20 Math.imul ( x, y )

이 function은 called될 때 다음 step을 수행합니다:

  1. a(? ToUint32(x))로 둔다.
  2. b(? ToUint32(y))로 둔다.
  3. product를 (a × b) modulo 232로 둔다.
  4. product ≥ 231이면, 𝔽(product - 232)를 반환한다.
  5. 𝔽(product)를 반환한다.

21.3.2.21 Math.log ( x )

이 function은 x의 natural logarithm을 반환합니다.

called될 때 다음 step을 수행합니다:

  1. n을 ? ToNumber(x)로 둔다.
  2. nNaN 또는 +∞𝔽 중 하나이면, n을 반환한다.
  3. n1𝔽이면, +0𝔽를 반환한다.
  4. n+0𝔽 또는 -0𝔽 중 하나이면, -∞𝔽를 반환한다.
  5. n < -0𝔽이면, NaN을 반환한다.
  6. ln((n))을 represent하는 implementation-approximated Number value를 반환한다.

21.3.2.22 Math.log1p ( x )

이 function은 1 + x의 natural logarithm을 반환합니다. result는 x의 value가 zero에 close한 경우에도 accurate한 way로 computed됩니다.

called될 때 다음 step을 수행합니다:

  1. n을 ? ToNumber(x)로 둔다.
  2. nNaN, +0𝔽, -0𝔽, 또는 +∞𝔽 중 하나이면, n을 반환한다.
  3. n-1𝔽이면, -∞𝔽를 반환한다.
  4. n < -1𝔽이면, NaN을 반환한다.
  5. ln(1 + (n))을 represent하는 implementation-approximated Number value를 반환한다.

21.3.2.23 Math.log10 ( x )

이 function은 x의 base 10 logarithm을 반환합니다.

called될 때 다음 step을 수행합니다:

  1. n을 ? ToNumber(x)로 둔다.
  2. nNaN 또는 +∞𝔽 중 하나이면, n을 반환한다.
  3. n1𝔽이면, +0𝔽를 반환한다.
  4. n+0𝔽 또는 -0𝔽 중 하나이면, -∞𝔽를 반환한다.
  5. n < -0𝔽이면, NaN을 반환한다.
  6. log10((n))을 represent하는 implementation-approximated Number value를 반환한다.

21.3.2.24 Math.log2 ( x )

이 function은 x의 base 2 logarithm을 반환합니다.

called될 때 다음 step을 수행합니다:

  1. n을 ? ToNumber(x)로 둔다.
  2. nNaN 또는 +∞𝔽 중 하나이면, n을 반환한다.
  3. n1𝔽이면, +0𝔽를 반환한다.
  4. n+0𝔽 또는 -0𝔽 중 하나이면, -∞𝔽를 반환한다.
  5. n < -0𝔽이면, NaN을 반환한다.
  6. log2((n))를 represent하는 implementation-approximated Number value를 반환한다.

21.3.2.25 Math.max ( ...args )

zero or more arguments가 given되면, 이 function은 각 argument에 ToNumber를 call하고 resulting value 중 largest를 반환합니다.

called될 때 다음 step을 수행합니다:

  1. coerced를 새 empty List로 둔다.
  2. args의 각 element arg에 대해, 다음을 수행한다.
    1. n을 ? ToNumber(arg)로 둔다.
    2. ncoerced에 append한다.
  3. highest-∞𝔽로 둔다.
  4. coerced의 각 element number에 대해, 다음을 수행한다.
    1. numberNaN이면, NaN을 반환한다.
    2. number+0𝔽이고 highest-0𝔽이면, highest+0𝔽로 설정한다.
    3. number > highest이면, highestnumber로 설정한다.
  5. highest를 반환한다.
Note

largest value를 determine하기 위한 value comparison은 +0𝔽-0𝔽보다 larger로 considered된다는 점을 제외하고 IsLessThan algorithm을 사용하여 수행됩니다.

이 function의 "length" property는 2𝔽입니다.

21.3.2.26 Math.min ( ...args )

zero or more arguments가 given되면, 이 function은 각 argument에 ToNumber를 call하고 resulting value 중 smallest를 반환합니다.

called될 때 다음 step을 수행합니다:

  1. coerced를 새 empty List로 둔다.
  2. args의 각 element arg에 대해, 다음을 수행한다.
    1. n을 ? ToNumber(arg)로 둔다.
    2. ncoerced에 append한다.
  3. lowest+∞𝔽로 둔다.
  4. coerced의 각 element number에 대해, 다음을 수행한다.
    1. numberNaN이면, NaN을 반환한다.
    2. number-0𝔽이고 lowest+0𝔽이면, lowest-0𝔽로 설정한다.
    3. number < lowest이면, lowestnumber로 설정한다.
  5. lowest를 반환한다.
Note

smallest value를 determine하기 위한 value comparison은 +0𝔽-0𝔽보다 larger로 considered된다는 점을 제외하고 IsLessThan algorithm을 사용하여 수행됩니다.

이 function의 "length" property는 2𝔽입니다.

21.3.2.27 Math.pow ( base, exponent )

이 function은 called될 때 다음 step을 수행합니다:

  1. base를 ? ToNumber(base)로 설정한다.
  2. exponent를 ? ToNumber(exponent)로 설정한다.
  3. Number::exponentiate(base, exponent)를 반환한다.

21.3.2.28 Math.random ( )

이 function은 positive sign을 가지고, +0𝔽보다 크거나 같지만 1𝔽보다 strictly less한 Number value를 반환하며, 이는 implementation-defined algorithm 또는 strategy를 사용하여 해당 range에서 approximately uniform distribution으로 randomly 또는 pseudo randomly chosen됩니다.

distinct realm을 위해 created된 각 Math.random function은 successive call에서 distinct sequence of values를 produce해야 합니다.

21.3.2.29 Math.round ( x )

이 function은 x에 closest하고 integral인 Number value를 반환합니다. two integral Numbersx에 equally close하면, result는 +∞에 closer한 Number value입니다. x가 already integral이면, result는 x입니다.

called될 때 다음 step을 수행합니다:

  1. n을 ? ToNumber(x)로 둔다.
  2. nfinite가 아니거나 nintegral Number이면, n을 반환한다.
  3. n < 0.5𝔽이고 n > +0𝔽이면, +0𝔽를 반환한다.
  4. n < -0𝔽이고 n-0.5𝔽이면, -0𝔽를 반환한다.
  5. tie의 경우 +∞에 closer한 Number를 preferring하여, n에 closest한 integral Number를 반환한다.
Note 1

Math.round(3.5)는 4를 반환하지만, Math.round(-3.5)는 -3을 반환합니다.

Note 2

Math.round(x)의 value는 always Math.floor(x + 0.5)의 value와 same하지 않습니다. x-0𝔽이거나 x-0𝔽보다 less하지만 -0.5𝔽보다 greater than or equal to인 경우, Math.round(x)-0𝔽를 반환하지만, Math.floor(x + 0.5)+0𝔽를 반환합니다. Math.round(x)x + 0.5를 computing할 때 internal rounding 때문에 Math.floor(x + 0.5)의 value와 differ할 수도 있습니다.

21.3.2.30 Math.sign ( x )

이 function은 x의 sign을 반환하여, x가 positive, negative, 또는 zero인지를 indicate합니다.

called될 때 다음 step을 수행합니다:

  1. n을 ? ToNumber(x)로 둔다.
  2. nNaN, +0𝔽, 또는 -0𝔽 중 하나이면, n을 반환한다.
  3. n < -0𝔽이면, -1𝔽를 반환한다.
  4. 1𝔽를 반환한다.

21.3.2.31 Math.sin ( x )

이 function은 x의 sine을 반환합니다. argument는 radians로 expressed됩니다.

called될 때 다음 step을 수행합니다:

  1. n을 ? ToNumber(x)로 둔다.
  2. nNaN, +0𝔽, 또는 -0𝔽 중 하나이면, n을 반환한다.
  3. n+∞𝔽 또는 -∞𝔽 중 하나이면, NaN을 반환한다.
  4. (n)의 sine을 represent하는 implementation-approximated Number value를 반환한다.

21.3.2.32 Math.sinh ( x )

이 function은 x의 hyperbolic sine을 반환합니다.

called될 때 다음 step을 수행합니다:

  1. n을 ? ToNumber(x)로 둔다.
  2. nfinite가 아니거나 n+0𝔽 또는 -0𝔽 중 하나이면, n을 반환한다.
  3. (n)의 hyperbolic sine을 represent하는 implementation-approximated Number value를 반환한다.
Note

Math.sinh(x)의 value는 (Math.exp(x) - Math.exp(-x)) / 2의 value와 same입니다.

21.3.2.33 Math.sqrt ( x )

이 function은 x의 square root를 반환합니다.

called될 때 다음 step을 수행합니다:

  1. n을 ? ToNumber(x)로 둔다.
  2. nNaN, +0𝔽, -0𝔽, 또는 +∞𝔽 중 하나이면, n을 반환한다.
  3. n < -0𝔽이면, NaN을 반환한다.
  4. 𝔽((n)의 square root)를 반환한다.

21.3.2.34 Math.sumPrecise ( items )

Numbers의 iterable이 given되면, 이 function은 iterable 안의 각 value를 sum하고 그 sum을 반환합니다. any value가 Number가 아니면 TypeError exception을 throw합니다.

called될 때 다음 step을 수행합니다:

  1. RequireObjectCoercible(items)를 수행한다.
  2. iteratorRecord를 ? GetIterator(items, sync)로 둔다.
  3. stateminus-zero로 둔다.
  4. sum을 0으로 둔다.
  5. count를 0으로 둔다.
  6. nextnot-started로 둔다.
  7. Repeat, nextdone이 아닌 동안,
    1. next를 ? IteratorStepValue(iteratorRecord)로 설정한다.
    2. nextdone이 아니면, 다음을 수행한다.
      1. count ≥ 253 - 1이면, 다음을 수행한다.
        1. NOTE: 이 step은 practice에서 reached될 것으로 expected되지 않으며, implementation이 이 specification을 violating하지 않고 input이 “reasonably sized”라고 rely할 수 있도록 하기 위해서만 included된다.
        2. errorThrowCompletion(newly created RangeError object)로 둔다.
        3. IteratorClose(iteratorRecord, error)를 반환한다.
      2. next가 Number가 아니면, 다음을 수행한다.
        1. errorThrowCompletion(newly created TypeError object)로 둔다.
        2. IteratorClose(iteratorRecord, error)를 반환한다.
      3. nnext로 둔다.
      4. statenot-a-number가 아니면, 다음을 수행한다.
        1. nNaN이면, 다음을 수행한다.
          1. statenot-a-number로 설정한다.
        2. 그렇지 않고 n+∞𝔽이면, 다음을 수행한다.
          1. stateminus-infinity이면, statenot-a-number로 설정한다.
          2. 그렇지 않으면, stateplus-infinity로 설정한다.
        3. 그렇지 않고 n-∞𝔽이면, 다음을 수행한다.
          1. stateplus-infinity이면, statenot-a-number로 설정한다.
          2. 그렇지 않으면, stateminus-infinity로 설정한다.
        4. 그렇지 않고 n-0𝔽가 아니며 stateminus-zero 또는 finite 중 하나이면, 다음을 수행한다.
          1. statefinite로 설정한다.
          2. sumsum + (n)으로 설정한다.
      5. countcount + 1로 설정한다.
  8. statenot-a-number이면, NaN을 반환한다.
  9. stateplus-infinity이면, +∞𝔽를 반환한다.
  10. stateminus-infinity이면, -∞𝔽를 반환한다.
  11. stateminus-zero이면, -0𝔽를 반환한다.
  12. 𝔽(sum)을 반환한다.
Note

sum의 value는 다양한 algorithm을 통해 arbitrary-precision arithmetic 없이 computed될 수 있습니다. 그중 하나는 Jonathan Richard Shewchuk의 Adaptive Precision Floating-Point Arithmetic and Fast Robust Geometric Predicates에 given된 “Grow-Expansion” algorithm입니다. 더 recent한 algorithm은 “Fast exact summation using small and large superaccumulators”에 given되어 있으며, 그 code는 https://gitlab.com/radfordneal/xsum에서 available합니다.

21.3.2.35 Math.tan ( x )

이 function은 x의 tangent를 반환합니다. argument는 radians로 expressed됩니다.

called될 때 다음 step을 수행합니다:

  1. n을 ? ToNumber(x)로 둔다.
  2. nNaN, +0𝔽, 또는 -0𝔽 중 하나이면, n을 반환한다.
  3. n+∞𝔽 또는 -∞𝔽 중 하나이면, NaN을 반환한다.
  4. (n)의 tangent를 represent하는 implementation-approximated Number value를 반환한다.

21.3.2.36 Math.tanh ( x )

이 function은 x의 hyperbolic tangent를 반환합니다.

called될 때 다음 step을 수행합니다:

  1. n을 ? ToNumber(x)로 둔다.
  2. nNaN, +0𝔽, 또는 -0𝔽 중 하나이면, n을 반환한다.
  3. n+∞𝔽이면, 1𝔽를 반환한다.
  4. n-∞𝔽이면, -1𝔽를 반환한다.
  5. (n)의 hyperbolic tangent를 represent하는 implementation-approximated Number value를 반환한다.
Note

Math.tanh(x)의 value는 (Math.exp(x) - Math.exp(-x)) / (Math.exp(x) + Math.exp(-x))의 value와 same입니다.

21.3.2.37 Math.trunc ( x )

이 function은 fractional digit을 제거하여 number x의 integral part를 반환합니다. x가 already integral이면, result는 x입니다.

called될 때 다음 step을 수행합니다:

  1. n을 ? ToNumber(x)로 둔다.
  2. nfinite가 아니거나 n+0𝔽 또는 -0𝔽 중 하나이면, n을 반환한다.
  3. n < 1𝔽이고 n > +0𝔽이면, +0𝔽를 반환한다.
  4. n < -0𝔽이고 n > -1𝔽이면, -0𝔽를 반환한다.
  5. +0𝔽의 direction으로 n에 nearest한 integral Number를 반환한다.

21.4 Date Objects

21.4.1 Overview of Date Objects and Definitions of Abstract Operations

다음 abstract operation은 time value(21.4.1.1에서 defined됨)에 대해 operate합니다. 모든 경우에, 이러한 function 중 하나에 대한 any argument가 NaN이면 result는 NaN이 된다는 점에 note하십시오.

21.4.1.1 Time Values and Time Range

ECMAScript의 time measurement는 POSIX의 time measurement와 analogous하며, 특히 proleptic Gregorian calendar, 1970년 1월 1일 UTC 시작 시점의 midnight인 epoch, 그리고 every day가 정확히 86,400초(각각 1000 milliseconds 길이)로 구성된다는 accounting을 공유합니다.

ECMAScript time value는 Number이며, millisecond precision으로 time 안의 instant를 represent하는 finite integral Number이거나 specific instant가 없음을 represent하는 NaN입니다. 24 × 60 × 60 × 1000 = 86,400,000의 multiple인 time value(즉 어떤 integer d에 대해 86,400,000 × d)는 epoch 뒤에 d whole UTC days만큼 따르는 UTC day의 start instant를 represent합니다(negative d의 경우 epoch 앞). every other finite time value tv는 그러한 multiple인 greatest preceding time value s를 기준으로 defined되며, s와 same UTC day 안에서 occur하지만 (tv - s) milliseconds만큼 뒤따르는 instant를 represent합니다.

Time value는 UTC leap second를 account하지 않습니다—positive leap second 안의 instant를 represent하는 time value는 없고, negative leap second에 의해 UTC timeline에서 removed된 instant를 represent하는 time value가 있습니다. 그러나 time value의 definition은 nonetheless UTC와 piecewise alignment를 yield하며, discontinuity는 leap second boundary에서만 존재하고 leap second 밖에서는 zero difference입니다.

Number는 -9,007,199,254,740,992부터 9,007,199,254,740,992까지의 모든 integer를 exactly represent할 수 있습니다(21.1.2.821.1.2.6). time value는 -8,640,000,000,000,000부터 8,640,000,000,000,000 milliseconds까지의 slightly smaller range를 support합니다. 이는 1970년 1월 1일 UTC 시작 시점의 midnight를 기준으로 exactly -100,000,000 days부터 100,000,000 days까지의 supported time value range를 yield합니다.

1970년 1월 1일 UTC 시작 시점의 midnight의 exact moment는 time value +0𝔽로 represented됩니다.

Note

proleptic Gregorian calendar에서 leap year는 4로 divisible하면서 400으로 divisible하거나 100으로 divisible하지 않는 year입니다.

proleptic Gregorian calendar의 400 year cycle은 97 leap years를 contain합니다. 이는 year당 average 365.2425 days를 yield하며, 이는 31,556,952,000 milliseconds입니다. 따라서 Number가 millisecond precision으로 exactly represent할 수 있는 maximum range는 1970을 기준으로 approximately -285,426부터 285,426 years까지입니다. 이 section에 specified된 time value가 support하는 smaller range는 1970을 기준으로 approximately -273,790부터 273,790 years까지입니다.

21.4.1.2 Time-related Constants

이러한 constant는 following sections의 algorithm에서 referenced됩니다.

HoursPerDay = 24
MinutesPerHour = 60
SecondsPerMinute = 60
msPerSecond = 1000𝔽
msPerMinute = 60000𝔽 = msPerSecond × 𝔽(SecondsPerMinute)
msPerHour = 3600000𝔽 = msPerMinute × 𝔽(MinutesPerHour)
msPerDay = 86400000𝔽 = msPerHour × 𝔽(HoursPerDay)

21.4.1.3 Day ( tv )

The abstract operation Day takes argument tv (a finite time value) and returns an integral Number. tv가 fall하는 day의 day number를 반환합니다. It performs the following steps when called:

  1. 𝔽(floor((tv / msPerDay)))를 반환한다.

21.4.1.4 TimeWithinDay ( tv )

The abstract operation TimeWithinDay takes argument tv (a finite time value) and returns an integral Number in the interval from +0𝔽 (inclusive) to msPerDay (exclusive). tv가 fall하는 day의 start 이후 milliseconds 수를 반환합니다. It performs the following steps when called:

  1. 𝔽((tv) modulo (msPerDay))를 반환한다.

21.4.1.5 DaysInYear ( y )

The abstract operation DaysInYear takes argument y (an integral Number) and returns 365𝔽 or 366𝔽. year y 안의 days 수를 반환합니다. Leap year는 366 days를 가지고, all other years는 365를 가집니다. It performs the following steps when called:

  1. ry(y)로 둔다.
  2. (ry modulo 400) = 0이면, 366𝔽를 반환한다.
  3. (ry modulo 100) = 0이면, 365𝔽를 반환한다.
  4. (ry modulo 4) = 0이면, 366𝔽를 반환한다.
  5. 365𝔽를 반환한다.

21.4.1.6 DayFromYear ( y )

The abstract operation DayFromYear takes argument y (an integral Number) and returns an integral Number. year y의 first day의 day number를 반환합니다. It performs the following steps when called:

  1. ry(y)로 둔다.
  2. NOTE: following steps에서 numberYears1, numberYears4, numberYears100, 및 numberYears400은 각각 1, 4, 100, 및 400으로 divisible한 years의 number이며, epoch와 year y의 start 사이에 occur합니다. yepoch보다 before이면 number는 negative입니다.
  3. numberYears1을 (ry - 1970)으로 둔다.
  4. numberYears4floor((ry - 1969) / 4)로 둔다.
  5. numberYears100floor((ry - 1901) / 100)으로 둔다.
  6. numberYears400floor((ry - 1601) / 400)으로 둔다.
  7. 𝔽(365 × numberYears1 + numberYears4 - numberYears100 + numberYears400)를 반환한다.

21.4.1.7 TimeFromYear ( y )

The abstract operation TimeFromYear takes argument y (an integral Number) and returns a time value. year y의 start의 time value를 반환합니다. It performs the following steps when called:

  1. msPerDay × DayFromYear(y)를 반환한다.

21.4.1.8 YearFromTime ( tv )

The abstract operation YearFromTime takes argument tv (a finite time value) and returns an integral Number. tv가 fall하는 year를 반환합니다. It performs the following steps when called:

  1. TimeFromYear(y) ≤ tv인 largest integral Number y (closest to +∞)를 반환한다.

21.4.1.9 DayWithinYear ( tv )

The abstract operation DayWithinYear takes argument tv (a finite time value) and returns an integral Number in the inclusive interval from +0𝔽 to 365𝔽. It performs the following steps when called:

  1. Day(tv) - DayFromYear(YearFromTime(tv))를 반환한다.

21.4.1.10 InLeapYear ( tv )

The abstract operation InLeapYear takes argument tv (a finite time value) and returns +0𝔽 or 1𝔽. tv가 leap year 안에 있으면 1𝔽를 반환하고 otherwise +0𝔽를 반환합니다. It performs the following steps when called:

  1. DaysInYear(YearFromTime(tv))가 366𝔽이면, 1𝔽를 반환한다.
  2. +0𝔽를 반환한다.

21.4.1.11 MonthFromTime ( tv )

The abstract operation MonthFromTime takes argument tv (a finite time value) and returns an integral Number in the inclusive interval from +0𝔽 to 11𝔽. tv가 fall하는 month를 identifying하는 Number를 반환합니다. month value +0𝔽는 January를 specify합니다; 1𝔽는 February를 specify합니다; 2𝔽는 March를 specify합니다; 3𝔽는 April을 specify합니다; 4𝔽는 May를 specify합니다; 5𝔽는 June을 specify합니다; 6𝔽는 July를 specify합니다; 7𝔽는 August를 specify합니다; 8𝔽는 September를 specify합니다; 9𝔽는 October를 specify합니다; 10𝔽는 November를 specify합니다; 그리고 11𝔽는 December를 specify합니다. MonthFromTime(+0𝔽) = +0𝔽이며, 이는 1970년 1월 1일 목요일에 corresponding함에 note하십시오. It performs the following steps when called:

  1. inLeapYearInLeapYear(tv)로 둔다.
  2. dayWithinYearDayWithinYear(tv)로 둔다.
  3. dayWithinYear < 31𝔽이면, +0𝔽를 반환한다.
  4. dayWithinYear < 59𝔽 + inLeapYear이면, 1𝔽를 반환한다.
  5. dayWithinYear < 90𝔽 + inLeapYear이면, 2𝔽를 반환한다.
  6. dayWithinYear < 120𝔽 + inLeapYear이면, 3𝔽를 반환한다.
  7. dayWithinYear < 151𝔽 + inLeapYear이면, 4𝔽를 반환한다.
  8. dayWithinYear < 181𝔽 + inLeapYear이면, 5𝔽를 반환한다.
  9. dayWithinYear < 212𝔽 + inLeapYear이면, 6𝔽를 반환한다.
  10. dayWithinYear < 243𝔽 + inLeapYear이면, 7𝔽를 반환한다.
  11. dayWithinYear < 273𝔽 + inLeapYear이면, 8𝔽를 반환한다.
  12. dayWithinYear < 304𝔽 + inLeapYear이면, 9𝔽를 반환한다.
  13. dayWithinYear < 334𝔽 + inLeapYear이면, 10𝔽를 반환한다.
  14. Assert: dayWithinYear < 365𝔽 + inLeapYear이다.
  15. 11𝔽를 반환한다.

21.4.1.12 DateFromTime ( tv )

The abstract operation DateFromTime takes argument tv (a finite time value) and returns an integral Number in the inclusive interval from 1𝔽 to 31𝔽. tv가 fall하는 month의 day를 반환합니다. It performs the following steps when called:

  1. inLeapYearInLeapYear(tv)로 둔다.
  2. dayWithinYearDayWithinYear(tv)로 둔다.
  3. monthMonthFromTime(tv)로 둔다.
  4. month+0𝔽이면, dayWithinYear + 1𝔽를 반환한다.
  5. month1𝔽이면, dayWithinYear - 30𝔽를 반환한다.
  6. month2𝔽이면, dayWithinYear - 58𝔽 - inLeapYear를 반환한다.
  7. month3𝔽이면, dayWithinYear - 89𝔽 - inLeapYear를 반환한다.
  8. month4𝔽이면, dayWithinYear - 119𝔽 - inLeapYear를 반환한다.
  9. month5𝔽이면, dayWithinYear - 150𝔽 - inLeapYear를 반환한다.
  10. month6𝔽이면, dayWithinYear - 180𝔽 - inLeapYear를 반환한다.
  11. month7𝔽이면, dayWithinYear - 211𝔽 - inLeapYear를 반환한다.
  12. month8𝔽이면, dayWithinYear - 242𝔽 - inLeapYear를 반환한다.
  13. month9𝔽이면, dayWithinYear - 272𝔽 - inLeapYear를 반환한다.
  14. month10𝔽이면, dayWithinYear - 303𝔽 - inLeapYear를 반환한다.
  15. Assert: month11𝔽이다.
  16. dayWithinYear - 333𝔽 - inLeapYear를 반환한다.

21.4.1.13 WeekDay ( tv )

The abstract operation WeekDay takes argument tv (a finite time value) and returns an integral Number in the inclusive interval from +0𝔽 to 6𝔽. tv가 fall하는 week의 day를 identifying하는 Number를 반환합니다. weekday value +0𝔽는 Sunday를 specify합니다; 1𝔽는 Monday를 specify합니다; 2𝔽는 Tuesday를 specify합니다; 3𝔽는 Wednesday를 specify합니다; 4𝔽는 Thursday를 specify합니다; 5𝔽는 Friday를 specify합니다; 그리고 6𝔽는 Saturday를 specify합니다. WeekDay(+0𝔽) = 4𝔽이며, 이는 1970년 1월 1일 목요일에 corresponding함에 note하십시오. It performs the following steps when called:

  1. 𝔽((Day(tv) + 4𝔽) modulo 7)를 반환한다.

21.4.1.14 HourFromTime ( tv )

The abstract operation HourFromTime takes argument tv (a finite time value) and returns an integral Number in the inclusive interval from +0𝔽 to 23𝔽. tv가 fall하는 day의 hour를 반환합니다. It performs the following steps when called:

  1. 𝔽(floor((tv / msPerHour)) modulo HoursPerDay)를 반환한다.

21.4.1.15 MinFromTime ( tv )

The abstract operation MinFromTime takes argument tv (a finite time value) and returns an integral Number in the inclusive interval from +0𝔽 to 59𝔽. tv가 fall하는 hour의 minute를 반환합니다. It performs the following steps when called:

  1. 𝔽(floor((tv / msPerMinute)) modulo MinutesPerHour)를 반환한다.

21.4.1.16 SecFromTime ( tv )

The abstract operation SecFromTime takes argument tv (a finite time value) and returns an integral Number in the inclusive interval from +0𝔽 to 59𝔽. tv가 fall하는 minute의 second를 반환합니다. It performs the following steps when called:

  1. 𝔽(floor((tv / msPerSecond)) modulo SecondsPerMinute)를 반환한다.

21.4.1.17 msFromTime ( tv )

The abstract operation msFromTime takes argument tv (a finite time value) and returns an integral Number in the inclusive interval from +0𝔽 to 999𝔽. tv가 fall하는 second의 millisecond를 반환합니다. It performs the following steps when called:

  1. 𝔽((tv) modulo (msPerSecond))를 반환한다.

21.4.1.18 GetUTCEpochNanoseconds ( year, month, day, hour, minute, second, millisecond, microsecond, nanosecond )

The abstract operation GetUTCEpochNanoseconds takes arguments year (an integer), month (an integer in the inclusive interval from 1 to 12), day (an integer in the inclusive interval from 1 to 31), hour (an integer in the inclusive interval from 0 to 23), minute (an integer in the inclusive interval from 0 to 59), second (an integer in the inclusive interval from 0 to 59), millisecond (an integer in the inclusive interval from 0 to 999), microsecond (an integer in the inclusive interval from 0 to 999), and nanosecond (an integer in the inclusive interval from 0 to 999) and returns a BigInt. returned value는 UTC에서 given ISO 8601 calendar date 및 wall-clock time에 corresponding하는 epoch 이후 nanoseconds 수를 represent합니다. It performs the following steps when called:

  1. dateMakeDay(𝔽(year), 𝔽(month - 1), 𝔽(day))로 둔다.
  2. timeMakeTime(𝔽(hour), 𝔽(minute), 𝔽(second), 𝔽(millisecond))로 둔다.
  3. msMakeDate(date, time)로 둔다.
  4. Assert: msintegral Number이다.
  5. ((ms) × 106 + microsecond × 103 + nanosecond)를 반환한다.

21.4.1.19 시간대 식별자

ECMAScript의 시간대는 시간대 식별자로 표현되며, 이는 0x0000부터 0x007F까지의 닫힌 구간에 있는 코드 유닛으로만 구성된 String이다. ECMAScript 구현체가 지원하는 시간대는 AvailableNamedTimeZoneIdentifiers가 반환하는 시간대 식별자 레코드의 [[Identifier]] 필드로 표현되는 사용 가능한 이름 있는 시간대이거나, IsTimeZoneOffsetStringtrue를 반환하는 String으로 표현되는 오프셋 시간대일 수 있다.

주 시간대 식별자는 사용 가능한 이름 있는 시간대에 대한 선호 식별자이다. 비주 시간대 식별자는 주 시간대 식별자가 아닌, 사용 가능한 이름 있는 시간대에 대한 식별자이다. 사용 가능한 이름 있는 시간대 식별자는 주 시간대 식별자 또는 비주 시간대 식별자 중 하나이다. 각 사용 가능한 이름 있는 시간대 식별자는 정확히 하나의 사용 가능한 이름 있는 시간대와 연관된다. 각 사용 가능한 이름 있는 시간대는 정확히 하나의 주 시간대 식별자와 0개 이상의 비주 시간대 식별자와 연관된다.

ECMAScript 구현체는 식별자 "UTC"를 가지는 사용 가능한 이름 있는 시간대를 지원해야 하며, 이는 UTC 시간대의 주 시간대 식별자여야 한다. 또한, 구현체는 임의 개수의 다른 사용 가능한 이름 있는 시간대를 지원할 수 있다.

ECMA-402 국제화 API 명세에 설명된 시간대 요구사항을 따르는 구현체를 시간대 인식이라고 한다. 시간대 인식 구현체는 IANA Time Zone Database의 Zone 및 Link 이름에 해당하는 사용 가능한 이름 있는 시간대를 지원해야 하며, 그러한 이름만 지원해야 한다. 시간대 인식 구현체에서, ECMA-402 명세에 명시된 AvailableNamedTimeZoneIdentifiers에 의해 특별히 재정의된 경우를 제외하고, 주 시간대 식별자는 IANA Time Zone Database의 Zone 이름이고, 비주 시간대 식별자는 각각 Link 이름이다. 전체 IANA Time Zone Database를 지원하지 않는 구현체도 시간대를 표현하는 식별자로 IANA Time Zone Database 이름을 사용하는 것이 권장된다.

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. returned List 안의 각 value는 timeZoneIdentifier로 identified되는 named time zone에서 given ISO 8601 calendar date 및 wall-clock time에 corresponding하는 epoch 이후 nanoseconds 수를 represent합니다.

input이 negative time zone transition 때문에 more than once occur하는 local time을 represent할 때(예: daylight saving time이 끝나거나 time zone rule change 때문에 time zone offset이 decreased되는 경우), returned List는 more than one element를 가지며 ascending numerical value로 sorted됩니다. input이 positive time zone transition 때문에 skipped된 local time을 represent할 때(예: daylight saving time이 시작되거나 time zone rule change 때문에 time zone offset이 increased되는 경우), returned List는 empty입니다. Otherwise, returned List는 one element를 가집니다.

any time zone에 대한 local political rules를 include하지 않는 ECMAScript implementation에 사용될 GetNamedTimeZoneEpochNanoseconds의 default implementation은 called될 때 following steps를 수행합니다:

  1. Assert: timeZoneIdentifier"UTC"이다.
  2. epochNanosecondsGetUTCEpochNanoseconds(year, month, day, hour, minute, second, millisecond, microsecond, nanosecond)로 둔다.
  3. « epochNanoseconds »를 반환한다.
Note

time zone aware implementation에 대해 required되고(all others에도 recommended됨), IANA Time Zone Database https://www.iana.org/time-zones/의 time zone information을 사용해야 합니다.

America/New_York에서 2017년 11월 5일 1:30 AM은 twice 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에 corresponding)를 represent하고 second element는 06:30 UTC(UTC offset -05:00에서 01:30 US Eastern Standard Time에 corresponding)를 represent합니다.

America/New_York에서 2017년 3월 12일 2:30 AM은 exist하지 않으므로, 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.

returned integerepoch를 기준으로 epochNanoseconds와 corresponding하는 instant에서 timeZoneIdentifier로 identified되는 named time zone의 UTC로부터의 offset을 nanoseconds 단위로 represent합니다.

any time zone에 대한 local political rules를 include하지 않는 ECMAScript implementation에 사용될 GetNamedTimeZoneOffsetNanoseconds의 default implementation은 called될 때 following steps를 수행합니다:

  1. Assert: timeZoneIdentifier"UTC"이다.
  2. 0을 반환한다.
Note

Time zone offset value는 positive 또는 negative일 수 있습니다.

21.4.1.22 Time Zone Identifier Record

Time Zone Identifier Recordavailable named time zone identifier와 그 corresponding primary time zone identifier를 describe하는 데 사용되는 Record입니다.

Time Zone Identifier Record는 Table 60에 listed된 field를 가집니다.

Table 60: Time Zone Identifier Record Fields
Field Name Value Meaning
[[Identifier]] a String implementation이 support하는 available named time zone identifier입니다.
[[PrimaryIdentifier]] a String [[Identifier]]가 resolve되는 primary time zone identifier입니다.
Note

[[Identifier]]가 primary time zone identifier이면, [[Identifier]][[PrimaryIdentifier]]입니다.

21.4.1.23 AvailableNamedTimeZoneIdentifiers ( )

The implementation-defined abstract operation AvailableNamedTimeZoneIdentifiers takes no arguments and returns a List of Time Zone Identifier Records. 그 result는 이 implementation의 모든 available named time zone identifier와 각 available named time zone identifier에 corresponding하는 primary time zone identifier를 describe합니다. List는 각 Time Zone Identifier Record[[Identifier]] field에 따라 ordered됩니다.

ECMA-402 Internationalization API를 implement하는 all implementation을 포함하여 time zone aware implementation은 ECMA-402 specification에 specified된 대로 AvailableNamedTimeZoneIdentifiers abstract operation을 implement해야 합니다. time zone aware가 아닌 implementation의 경우, AvailableNamedTimeZoneIdentifiers는 called될 때 following steps를 수행합니다:

  1. implementation이 any time zone에 대한 local political rules를 include하지 않으면, 다음을 수행한다.
    1. « Time Zone Identifier Record { [[Identifier]]: "UTC", [[PrimaryIdentifier]]: "UTC" } »를 반환한다.
  2. identifierslexicographic code unit order에 따라 sorted된 unique available named time zone identifier의 List로 둔다.
  3. result를 새 empty List로 둔다.
  4. identifiers의 각 element identifier에 대해, 다음을 수행한다.
    1. primaryidentifier로 둔다.
    2. identifier가 이 implementation에서 non-primary time zone identifier이고 identifier"UTC"가 아니면, 다음을 수행한다.
      1. primaryidentifier와 associated된 primary time zone identifier로 설정한다.
      2. NOTE: implementation은 primary time zone identifier를 obtain하기 위해 identifier를 iteratively resolve해야 할 수 있다.
    3. recordTime Zone Identifier Record { [[Identifier]]: identifier, [[PrimaryIdentifier]]: primary }로 둔다.
    4. recordresult에 append한다.
  5. Assert: resultrecord.[[Identifier]]"UTC"이고 record.[[PrimaryIdentifier]]"UTC"Time Zone Identifier Record record를 contain한다.
  6. result를 반환한다.

21.4.1.24 SystemTimeZoneIdentifier ( )

The implementation-defined abstract operation SystemTimeZoneIdentifier takes no arguments and returns a String. host environment의 current time zone을 represent하는 String을 반환합니다. 이는 IsTimeZoneOffsetStringtrue를 반환하는 UTC offset을 represent하는 String이거나 primary time zone identifier입니다. It performs the following steps when called:

  1. implementation이 UTC time zone만 support하면, "UTC"를 반환한다.
  2. systemTimeZoneStringhost environment의 current time zone을 represent하는 String으로 둔다. 이는 primary time zone identifier 또는 offset time zone identifier이다.
  3. systemTimeZoneString을 반환한다.
Note

Date object의 method에서 implementation이 commonly provide하는 functionality level을 ensure하기 위해, such thing이 exist한다면 SystemTimeZoneIdentifier가 host environment의 time zone setting에 corresponding하는 IANA time zone name을 return하는 것이 recommended됩니다. GetNamedTimeZoneEpochNanosecondsGetNamedTimeZoneOffsetNanoseconds는 such rules가 exist한다면 해당 time zone의 standard time 및 daylight saving time에 대한 local political rules를 reflect해야 합니다.

예를 들어 host environment가 user가 time zone으로 US Eastern Time을 chosen한 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에서 effect 중인 standard time 및 daylight saving time에 대한 local political rules를 사용하여 이 section에 specified된 way로 result를 determine해야 합니다. It performs the following steps when called:

  1. systemTimeZoneIdentifierSystemTimeZoneIdentifier()로 둔다.
  2. IsTimeZoneOffsetString(systemTimeZoneIdentifier)이 true이면, 다음을 수행한다.
    1. offsetNsParseTimeZoneOffsetString(systemTimeZoneIdentifier)로 둔다.
  3. 그렇지 않으면,
    1. offsetNsGetNamedTimeZoneOffsetNanoseconds(systemTimeZoneIdentifier, ((tv) × 106))로 둔다.
  4. offsetMstruncate(offsetNs / 106)로 둔다.
  5. tv + 𝔽(offsetMs)를 반환한다.
Note 1

local time tv에 대한 political rules가 implementation 안에서 available하지 않으면, SystemTimeZoneIdentifier"UTC"를 반환하고 GetNamedTimeZoneOffsetNanoseconds가 0을 반환하므로 result는 tv입니다.

Note 2

time zone aware implementation에 대해 required되고(all others에도 recommended됨), IANA Time Zone Database https://www.iana.org/time-zones/의 time zone information을 사용해야 합니다.

Note 3

negative time zone transition에서 repeated time이 있을 때(예: daylight saving time이 끝나거나 time zone adjustment가 decreased되는 경우) two different input time value tvUTC가 same local time tlocal로 converted됩니다.

LocalTime(UTC(tvlocal))는 necessarily always tvlocal와 equal하지 않습니다. Correspondingly, UTC(LocalTime(tvUTC))도 necessarily always tvUTC와 equal하지 않습니다.

21.4.1.26 UTC ( t )

The abstract operation UTC takes argument t (a Number) and returns a time value. t를 local time에서 UTC time value로 convert합니다. t에서 effect 중인 standard time 및 daylight saving time에 대한 local political rules를 사용하여 이 section에 specified된 way로 result를 determine해야 합니다. It performs the following steps when called:

  1. tfinite가 아니면, NaN을 반환한다.
  2. systemTimeZoneIdentifierSystemTimeZoneIdentifier()로 둔다.
  3. IsTimeZoneOffsetString(systemTimeZoneIdentifier)이 true이면, 다음을 수행한다.
    1. offsetNsParseTimeZoneOffsetString(systemTimeZoneIdentifier)로 둔다.
  4. 그렇지 않으면,
    1. possibleInstantsGetNamedTimeZoneEpochNanoseconds(systemTimeZoneIdentifier, (YearFromTime(t)), (MonthFromTime(t)) + 1, (DateFromTime(t)), (HourFromTime(t)), (MinFromTime(t)), (SecFromTime(t)), (msFromTime(t)), 0, 0)로 둔다.
    2. NOTE: 다음 steps는 t가 negative time zone transition에서 multiple times repeating되는 local time(예: daylight saving time이 끝나거나 time zone rule change 때문에 time zone offset이 decreased되는 경우) 또는 positive time zone transition에서 skipped local time(예: daylight saving time이 시작되거나 time zone rule change 때문에 time zone offset이 increased되는 경우)을 represent할 때, t가 transition before의 time zone offset을 사용하여 interpreted되도록 ensure한다.
    3. possibleInstants가 empty가 아니면, 다음을 수행한다.
      1. disambiguatedInstantpossibleInstants[0]으로 둔다.
    4. 그렇지 않으면,
      1. NOTE: t는 positive time zone transition에서 skipped된 local time을 represent한다(예: daylight saving time starting 또는 time zone rule change가 UTC offset을 increasing하기 때문).
      2. possibleInstantsBeforeGetNamedTimeZoneEpochNanoseconds(systemTimeZoneIdentifier, (YearFromTime(tBefore)), (MonthFromTime(tBefore)) + 1, (DateFromTime(tBefore)), (HourFromTime(tBefore)), (MinFromTime(tBefore)), (SecFromTime(tBefore)), (msFromTime(tBefore)), 0, 0)로 둔다. 여기서 tBeforepossibleInstantsBefore가 empty가 아닌 largest integral Number < t이다(즉 tBefore는 transition before의 last local time을 represent한다).
      3. disambiguatedInstantpossibleInstantsBefore의 last element로 둔다.
    5. offsetNsGetNamedTimeZoneOffsetNanoseconds(systemTimeZoneIdentifier, disambiguatedInstant)로 둔다.
  5. offsetMstruncate(offsetNs / 106)로 둔다.
  6. t - 𝔽(offsetMs)를 반환한다.

input t는 nominally time value이지만 any Number value일 수 있습니다. algorithm은 ttime value range로 limit해서는 안 됩니다. 그러면 local UTC offset에 관계없이 time value range의 boundary와 corresponding하는 input이 support될 수 있습니다. 예를 들어 maximum time value는 8.64 × 1015이며, 이는 "+275760-09-13T00:00:00Z"에 corresponding합니다. local time zone offset이 해당 instant에서 UTC보다 1 hour ahead인 environment에서는, 더 큰 input인 8.64 × 1015 + 3.6 × 106로 represented되며, 이는 "+275760-09-13T01:00:00+01:00"에 corresponding합니다.

local time t에 대한 political rules가 implementation 안에서 available하지 않으면, SystemTimeZoneIdentifier"UTC"를 반환하고 GetNamedTimeZoneOffsetNanoseconds가 0을 반환하므로 result는 t입니다.

Note 1

time zone aware implementation에 대해 required되고(all others에도 recommended됨), IANA Time Zone Database https://www.iana.org/time-zones/의 time zone information을 사용해야 합니다.

America/New_York에서 2017년 11월 5일 1:30 AM은 twice 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은 exist하지 않지만, 2:30 AM UTC-05(3:30 AM UTC-04와 equivalent)로 interpreted되어야 합니다. UTC(TimeClip(MakeDate(MakeDay(2017, 2, 12), MakeTime(2, 30, 0, 0))))에서 offsetMs의 value는 -5 × msPerHour입니다.

Note 2

UTC(LocalTime(tUTC))는 necessarily always tUTC와 equal하지 않습니다. Correspondingly, LocalTime(UTC(tlocal))도 necessarily always tlocal와 equal하지 않습니다.

21.4.1.27 MakeTime ( hour, min, sec, ms )

The abstract operation MakeTime takes arguments hour (a Number), min (a Number), sec (a Number), and ms (a Number) and returns a Number. milliseconds 수를 calculate합니다. It performs the following steps when called:

  1. hourfinite가 아니거나, minfinite가 아니거나, secfinite가 아니거나, msfinite가 아니면, NaN을 반환한다.
  2. h𝔽(! ToIntegerOrInfinity(hour))로 둔다.
  3. m𝔽(! ToIntegerOrInfinity(min))로 둔다.
  4. s𝔽(! ToIntegerOrInfinity(sec))로 둔다.
  5. milli𝔽(! ToIntegerOrInfinity(ms))로 둔다.
  6. ((h × msPerHour + m × msPerMinute) + s × msPerSecond) + milli를 반환한다.
Note

MakeTime 안의 arithmetic은 floating-point arithmetic이며 associative하지 않으므로, operation은 correct order로 performed되어야 합니다.

21.4.1.28 MakeDay ( year, month, date )

The abstract operation MakeDay takes arguments year (a Number), month (a Number), and date (a Number) and returns a finite Number or NaN. days 수를 calculate합니다. It performs the following steps when called:

  1. yearfinite가 아니거나, monthfinite가 아니거나, datefinite가 아니면, NaN을 반환한다.
  2. y𝔽(! ToIntegerOrInfinity(year))로 둔다.
  3. m𝔽(! ToIntegerOrInfinity(month))로 둔다.
  4. dt𝔽(! ToIntegerOrInfinity(date))로 둔다.
  5. ymy + 𝔽(floor((m) / 12))로 둔다.
  6. ymfinite가 아니면, NaN을 반환한다.
  7. mn𝔽((m) modulo 12)로 둔다.
  8. YearFromTime(tv)가 ym이고, MonthFromTime(tv)가 mn이며, DateFromTime(tv)가 1𝔽finite time value tv를 find한다; 하지만 이것이 possible하지 않으면(어떤 argument가 out of range이므로), NaN을 반환한다.
  9. Day(tv) + dt - 1𝔽를 반환한다.

21.4.1.29 MakeDate ( day, time )

The abstract operation MakeDate takes arguments day (a Number) and time (a Number) and returns a finite Number or NaN. milliseconds 수를 calculate합니다. It performs the following steps when called:

  1. dayfinite가 아니거나 timefinite가 아니면, NaN을 반환한다.
  2. tvday × msPerDay + time으로 둔다.
  3. tvfinite가 아니면, NaN을 반환한다.
  4. tv를 반환한다.

21.4.1.30 MakeFullYear ( year )

The abstract operation MakeFullYear takes argument year (a Number) and returns an integral Number or NaN. yearinteger part와 associated된 full year를 반환하며, 0부터 99까지의 inclusive interval 안의 any value를 1900 start 이후 years count로 interpret합니다. proleptic Gregorian calendar와 alignment하기 위해, “full year”는 year 0(1 B.C.) start 이후 complete years의 signed count로 defined됩니다. It performs the following steps when called:

  1. yearNaN, +∞𝔽, 또는 -∞𝔽 중 하나이면, NaN을 반환한다.
  2. truncated를 ! ToIntegerOrInfinity(year)로 둔다.
  3. truncated가 0부터 99까지의 inclusive interval 안에 있으면, 1900𝔽 + 𝔽(truncated)를 반환한다.
  4. 𝔽(truncated)를 반환한다.

21.4.1.31 TimeClip ( time )

The abstract operation TimeClip takes argument time (a Number) and returns a time value. milliseconds 수를 calculate합니다. It performs the following steps when called:

  1. timefinite가 아니면, NaN을 반환한다.
  2. abs((time)) > 8.64 × 1015이면, NaN을 반환한다.
  3. 𝔽(! ToIntegerOrInfinity(time))를 반환한다.

21.4.1.32 Date Time String Format

ECMAScript는 ISO 8601 calendar date extended format의 simplification을 기반으로 date-times를 위한 string interchange format을 define합니다. format은 다음과 같습니다: YYYY-MM-DDTHH:mm:ss.sssZ

elements는 다음과 같습니다:

YYYY proleptic Gregorian calendar에서 0000부터 9999까지의 four decimal digits로 된 year이거나, "+" 또는 "-" 뒤에 six decimal digits가 followed되는 expanded year입니다.
- "-" (hyphen)가 string 안에 literally twice appear합니다.
MM 01 (January)부터 12 (December)까지의 two decimal digits로 된 year의 month입니다.
DD 01부터 31까지의 two decimal digits로 된 month의 day입니다.
T time element의 beginning을 indicate하기 위해 "T"가 string 안에 literally appear합니다.
HH midnight 이후 passed한 complete hours 수이며, 00부터 24까지의 two decimal digits입니다.
: ":" (colon)가 string 안에 literally twice appear합니다.
mm hour의 start 이후 complete minutes 수이며, 00부터 59까지의 two decimal digits입니다.
ss minute의 start 이후 complete seconds 수이며, 00부터 59까지의 two decimal digits입니다.
. "." (dot)가 string 안에 literally appear합니다.
sss second의 start 이후 complete milliseconds 수이며, three decimal digits입니다.
Z UTC offset representation이며, "Z" (offset 없는 UTC)로 specified되거나, local time이 UTC보다 ahead 또는 behind임을 indicate하기 위해 "+" 또는 "-" 뒤에 time expression HH:mm가 followed되는 형식(time zone offset string format의 subset)입니다.

이 format은 date-only form을 include합니다:

YYYY
YYYY-MM
YYYY-MM-DD
        

또한 above date-only form 중 하나 바로 뒤에 following time form 중 하나가 followed되고 optional UTC offset representation이 appended되는 “date-time” form도 include합니다:

THH:mm
THH:mm:ss
THH:mm:ss.sss
        

out-of-bounds 또는 nonconforming element를 contain하는 string은 이 format의 valid instance가 아닙니다.

Note 1

every day는 midnight로 start하고 end하므로, two notations 00:0024:00는 one date와 associated될 수 있는 two midnights를 distinguish하기 위해 available합니다. 이는 following two notations가 exactly same point in time을 refer함을 의미합니다: 1995-02-04T24:001995-02-05T00:00. latter form을 “calendar day의 end”로 해석하는 것은 ISO 8601과 consistent합니다. 그 specification이 이를 time interval을 describing하는 데 reserve하고 single point in time의 representation 안에서는 permit하지 않더라도 그렇습니다.

Note 2

CET, EST 등과 같은 civil time zone의 abbreviation을 specify하는 international standard는 존재하지 않으며, sometimes same abbreviation이 even two very different time zones에 사용됩니다. 이러한 이유로 ISO 8601과 이 format 모두 time zone offset의 numeric representation을 specify합니다.

21.4.1.32.1 Expanded Years

1970년 1월 1일을 기준으로 forward 또는 backward approximately 273,790 years의 full time value range를 cover하려면(21.4.1.1), 0 before 또는 9999 after의 years를 represent해야 합니다. ISO 8601은 year representation의 expansion을 permit하지만, information interchange의 partners 간 mutual agreement에 의해서만 permit합니다. simplified ECMAScript format에서 such expanded year representation은 6 digits를 가져야 하며 항상 + 또는 - sign이 prefixed됩니다. year 0은 positive로 considered되며 + sign으로 prefixed되어야 합니다. year 0을 -000000으로 represent하는 것은 invalid입니다. expanded years를 가진 Date Time String Format과 match하는 String이 time value range outside의 instant를 represent하면, Date.parse에 의해 unrecognizable로 treated되고 implementation-specific behaviour 또는 heuristics로 fallback하지 않고 그 function이 NaN을 return하게 합니다.

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을 define합니다. format은 following grammar로 described됩니다.

Syntax

UTCOffset ::: ASCIISign Hour ASCIISign Hour HourSubcomponents[+Extended] ASCIISign Hour HourSubcomponents[~Extended] ASCIISign ::: one of + - Hour ::: 0 DecimalDigit 1 DecimalDigit 20 21 22 23 HourSubcomponents[Extended] ::: TimeSeparator[?Extended] MinuteSecond TimeSeparator[?Extended] MinuteSecond TimeSeparator[?Extended] MinuteSecond TemporalDecimalFractionopt TimeSeparator[Extended] ::: [+Extended] : [~Extended] [empty] MinuteSecond ::: 0 DecimalDigit 1 DecimalDigit 2 DecimalDigit 3 DecimalDigit 4 DecimalDigit 5 DecimalDigit TemporalDecimalFraction ::: TemporalDecimalSeparator DecimalDigit TemporalDecimalSeparator DecimalDigit DecimalDigit TemporalDecimalSeparator DecimalDigit DecimalDigit DecimalDigit TemporalDecimalSeparator DecimalDigit DecimalDigit DecimalDigit DecimalDigit TemporalDecimalSeparator DecimalDigit DecimalDigit DecimalDigit DecimalDigit DecimalDigit TemporalDecimalSeparator DecimalDigit DecimalDigit DecimalDigit DecimalDigit DecimalDigit DecimalDigit TemporalDecimalSeparator DecimalDigit DecimalDigit DecimalDigit DecimalDigit DecimalDigit DecimalDigit DecimalDigit TemporalDecimalSeparator DecimalDigit DecimalDigit DecimalDigit DecimalDigit DecimalDigit DecimalDigit DecimalDigit DecimalDigit TemporalDecimalSeparator DecimalDigit DecimalDigit DecimalDigit DecimalDigit DecimalDigit DecimalDigit DecimalDigit DecimalDigit DecimalDigit TemporalDecimalSeparator ::: one of . ,

21.4.1.33.1 IsTimeZoneOffsetString ( offsetString )

The abstract operation IsTimeZoneOffsetString takes argument offsetString (a String) and returns a Boolean. return value는 offsetStringUTCOffset에 의해 given된 grammar에 conform하는지 여부를 indicate합니다. It performs the following steps when called:

  1. parseResultParseText(offsetString, UTCOffset)로 둔다.
  2. parseResult가 error의 List이면, false를 반환한다.
  3. true를 반환한다.

21.4.1.33.2 ParseTimeZoneOffsetString ( offsetString )

The abstract operation ParseTimeZoneOffsetString takes argument offsetString (a String) and returns an integer. return value는 String offsetString에 corresponding하는 UTC offset이며, nanoseconds 수입니다. It performs the following steps when called:

  1. parseResultParseText(offsetString, UTCOffset)로 둔다.
  2. Assert: parseResult는 error의 List가 아니다.
  3. Assert: parseResultASCIISign Parse Node를 contain한다.
  4. parsedSignparseResult 안에 contained된 ASCIISign Parse Node가 matched한 source text로 둔다.
  5. parsedSign이 single code point U+002D (HYPHEN-MINUS)이면, 다음을 수행한다.
    1. sign을 -1로 둔다.
  6. 그렇지 않으면,
    1. sign을 1로 둔다.
  7. NOTE: 아래 StringToNumber의 application은 precision을 lose하지 않는다. parsed value 각각은 sufficiently short string of decimal digits임이 guaranteed되기 때문이다.
  8. Assert: parseResultHour Parse Node를 contain한다.
  9. parsedHoursparseResult 안에 contained된 Hour Parse Node가 matched한 source text로 둔다.
  10. hours(StringToNumber(CodePointsToString(parsedHours)))로 둔다.
  11. parseResultMinuteSecond Parse Node를 contain하지 않으면, 다음을 수행한다.
    1. minutes를 0으로 둔다.
  12. 그렇지 않으면,
    1. parsedMinutesparseResult 안에 contained된 first MinuteSecond Parse Node가 matched한 source text로 둔다.
    2. minutes(StringToNumber(CodePointsToString(parsedMinutes)))로 둔다.
  13. parseResult가 two MinuteSecond Parse Nodes를 contain하지 않으면, 다음을 수행한다.
    1. seconds를 0으로 둔다.
  14. 그렇지 않으면,
    1. parsedSecondsparseResult 안에 contained된 second MinuteSecond Parse Node가 matched한 source text로 둔다.
    2. seconds(StringToNumber(CodePointsToString(parsedSeconds)))로 둔다.
  15. parseResultTemporalDecimalFraction Parse Node를 contain하지 않으면, 다음을 수행한다.
    1. nanoseconds를 0으로 둔다.
  16. 그렇지 않으면,
    1. parsedFractionparseResult 안에 contained된 TemporalDecimalFraction Parse Node가 matched한 source text로 둔다.
    2. fractionCodePointsToString(parsedFraction)과 "000000000"string-concatenation으로 둔다.
    3. nanosecondsStringfraction의 1부터 10까지의 substring으로 둔다.
    4. nanoseconds(StringToNumber(nanosecondsString))로 둔다.
  17. sign × (((hours × 60 + minutes) × 60 + seconds) × 109 + nanoseconds)를 반환한다.

21.4.2 The Date Constructor

Date constructor는:

  • %Date%입니다.
  • global object"Date" property의 initial value입니다.
  • constructor로 called될 때 new Date를 create하고 initialize합니다.
  • constructor가 아니라 function으로 called될 때 current time(UTC)을 represent하는 String을 반환합니다.
  • argument의 number 및 type에 따라 behaviour가 differ하는 function입니다.
  • class definition의 extends clause의 value로 사용될 수 있습니다. specified Date behaviour를 inherit하려는 subclass constructor[[DateValue]] internal slot을 가진 subclass instance를 create하고 initialize하기 위해 Date constructor에 대한 super call을 include해야 합니다.

21.4.2.1 Date ( ...values )

이 function은 called될 때 following steps를 수행합니다:

  1. NewTarget이 undefined이면, 다음을 수행한다.
    1. now를 current time을 identifying하는 time value (UTC)로 둔다.
    2. ToDateString(now)를 반환한다.
  2. numberOfArgsvalues 안의 elements 수로 둔다.
  3. numberOfArgs = 0이면, 다음을 수행한다.
    1. dv를 current time을 identifying하는 time value (UTC)로 둔다.
  4. 그렇지 않고 numberOfArgs = 1이면, 다음을 수행한다.
    1. valuevalues[0]으로 둔다.
    2. value가 Object이고 value[[DateValue]] internal slot을 가지면, 다음을 수행한다.
      1. tvvalue.[[DateValue]]로 둔다.
    3. 그렇지 않으면,
      1. v를 ? ToPrimitive(value)로 둔다.
      2. v가 String이면, 다음을 수행한다.
        1. Assert: next step은 v가 String이므로 abrupt completion을 never return한다.
        2. tvparse method(21.4.3.2)에서와 exactly same manner로 v를 date로 parsing한 result로 둔다.
      3. 그렇지 않으면,
        1. tv를 ? ToNumber(v)로 둔다.
    4. dvTimeClip(tv)로 둔다.
  5. 그렇지 않으면,
    1. Assert: numberOfArgs ≥ 2이다.
    2. y를 ? ToNumber(values[0])로 둔다.
    3. m을 ? ToNumber(values[1])로 둔다.
    4. numberOfArgs > 2이면 dt를 ? ToNumber(values[2])로 둔다; 그렇지 않으면 dt1𝔽로 둔다.
    5. numberOfArgs > 3이면 h를 ? ToNumber(values[3])로 둔다; 그렇지 않으면 h+0𝔽로 둔다.
    6. numberOfArgs > 4이면 min을 ? ToNumber(values[4])로 둔다; 그렇지 않으면 min+0𝔽로 둔다.
    7. numberOfArgs > 5이면 s를 ? ToNumber(values[5])로 둔다; 그렇지 않으면 s+0𝔽로 둔다.
    8. numberOfArgs > 6이면 milli를 ? ToNumber(values[6])로 둔다; 그렇지 않으면 milli+0𝔽로 둔다.
    9. yrMakeFullYear(y)로 둔다.
    10. finalDateMakeDate(MakeDay(yr, m, dt), MakeTime(h, min, s, milli))로 둔다.
    11. dvTimeClip(UTC(finalDate))로 둔다.
  6. obj를 ? OrdinaryCreateFromConstructor(NewTarget, "%Date.prototype%", « [[DateValue]] »)로 둔다.
  7. obj.[[DateValue]]dv로 설정한다.
  8. obj를 반환한다.

21.4.3 Properties of the Date Constructor

Date constructor는:

  • value가 %Function.prototype%[[Prototype]] internal slot을 가집니다.
  • value가 7𝔽"length" property를 가집니다.
  • 다음 property를 가집니다:

21.4.3.1 Date.now ( )

이 function은 call이 occur한 UTC date 및 time을 designating하는 time value를 반환합니다.

21.4.3.2 Date.parse ( string )

이 function은 argument에 ToString operator를 apply합니다. ToStringabrupt completion을 result하면 Completion Record가 immediately returned됩니다. Otherwise, 이 function은 resulting String을 date 및 time으로 interpret합니다; date 및 time에 corresponding하는 UTC time value인 Number를 반환합니다. String은 contents에 따라 local time, UTC time, 또는 어떤 other time zone의 time으로 interpreted될 수 있습니다. function은 first로 expanded years를 포함하여 Date Time String Format(21.4.1.32)에 described된 format에 따라 String을 parse하려고 attempt합니다. String이 that format에 conform하지 않으면 function은 any implementation-specific heuristics 또는 implementation-specific date format으로 fallback할 수 있습니다. unrecognizable하거나 out-of-bounds format element value를 contain하는 String은 이 function이 NaN을 return하게 해야 합니다.

String이 Date Time String Format에 conform하면, absent format element 대신 substitute value가 take됩니다. MM 또는 DD elements가 absent이면, "01"이 사용됩니다. HH, mm, 또는 ss elements가 absent이면, "00"이 사용됩니다. sss element가 absent이면, "000"이 사용됩니다. UTC offset representation이 absent이면, date-only form은 UTC time으로 interpreted되고 date-time form은 local time으로 interpreted됩니다.

x가 ECMAScript의 particular implementation 안에서 milliseconds amount가 zero인 any Date이면, all referenced properties가 their initial values를 가진다면, following expressions는 that implementation에서 same numeric value를 produce해야 합니다:

x.valueOf()
Date.parse(x.toString())
Date.parse(x.toUTCString())
Date.parse(x.toISOString())

However, expression

Date.parse(x.toLocaleString())

은 preceding three expressions와 same Number value를 produce할 필요가 없으며, general하게 이 function에 Date Time String Format(21.4.1.32)에 conform하지 않고 that implementation에서 toString 또는 toUTCString method에 의해 produced될 수 없는 any String value가 given될 때 produced되는 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은 called될 때 following steps를 수행합니다:

  1. y를 ? ToNumber(year)로 둔다.
  2. month가 present하면, m을 ? ToNumber(month)로 둔다; 그렇지 않으면 m+0𝔽로 둔다.
  3. date가 present하면, dt를 ? ToNumber(date)로 둔다; 그렇지 않으면 dt1𝔽로 둔다.
  4. hours가 present하면, h를 ? ToNumber(hours)로 둔다; 그렇지 않으면 h+0𝔽로 둔다.
  5. minutes가 present하면, min을 ? ToNumber(minutes)로 둔다; 그렇지 않으면 min+0𝔽로 둔다.
  6. seconds가 present하면, s를 ? ToNumber(seconds)로 둔다; 그렇지 않으면 s+0𝔽로 둔다.
  7. ms가 present하면, milli를 ? ToNumber(ms)로 둔다; 그렇지 않으면 milli+0𝔽로 둔다.
  8. yrMakeFullYear(y)로 둔다.
  9. TimeClip(MakeDate(MakeDay(yr, m, dt), MakeTime(h, min, s, milli)))를 반환한다.

이 function의 "length" property는 7𝔽입니다.

Note

이 function은 Date constructor와 two ways에서 differ합니다: Date를 creating하는 대신 time value를 Number로 반환하고, arguments를 local time이 아니라 UTC로 interpret합니다.

21.4.4 Properties of the Date Prototype Object

Date prototype object는:

  • %Date.prototype%입니다.
  • itself가 ordinary object입니다.
  • Date instance가 아니며 [[DateValue]] internal slot을 가지지 않습니다.
  • value가 %Object.prototype%[[Prototype]] internal slot을 가집니다.

explicitly 달리 defined되지 않는 한, 아래에 defined된 Date prototype object의 methods는 generic하지 않으며, 이들에게 passed되는 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는 called될 때 following steps를 수행합니다:

  1. dateObjthis value로 둔다.
  2. RequireInternalSlot(dateObj, [[DateValue]])를 수행한다.
  3. tvdateObj.[[DateValue]]로 둔다.
  4. tvNaN이면, NaN을 반환한다.
  5. DateFromTime(LocalTime(tv))를 반환한다.

21.4.4.3 Date.prototype.getDay ( )

이 method는 called될 때 following steps를 수행합니다:

  1. dateObjthis value로 둔다.
  2. RequireInternalSlot(dateObj, [[DateValue]])를 수행한다.
  3. tvdateObj.[[DateValue]]로 둔다.
  4. tvNaN이면, NaN을 반환한다.
  5. WeekDay(LocalTime(tv))를 반환한다.

21.4.4.4 Date.prototype.getFullYear ( )

이 method는 called될 때 following steps를 수행합니다:

  1. dateObjthis value로 둔다.
  2. RequireInternalSlot(dateObj, [[DateValue]])를 수행한다.
  3. tvdateObj.[[DateValue]]로 둔다.
  4. tvNaN이면, NaN을 반환한다.
  5. YearFromTime(LocalTime(tv))를 반환한다.

21.4.4.5 Date.prototype.getHours ( )

이 method는 called될 때 following steps를 수행합니다:

  1. dateObjthis value로 둔다.
  2. RequireInternalSlot(dateObj, [[DateValue]])를 수행한다.
  3. tvdateObj.[[DateValue]]로 둔다.
  4. tvNaN이면, NaN을 반환한다.
  5. HourFromTime(LocalTime(tv))를 반환한다.

21.4.4.6 Date.prototype.getMilliseconds ( )

이 method는 called될 때 following steps를 수행합니다:

  1. dateObjthis value로 둔다.
  2. RequireInternalSlot(dateObj, [[DateValue]])를 수행한다.
  3. tvdateObj.[[DateValue]]로 둔다.
  4. tvNaN이면, NaN을 반환한다.
  5. msFromTime(LocalTime(tv))를 반환한다.

21.4.4.7 Date.prototype.getMinutes ( )

이 method는 called될 때 following steps를 수행합니다:

  1. dateObjthis value로 둔다.
  2. RequireInternalSlot(dateObj, [[DateValue]])를 수행한다.
  3. tvdateObj.[[DateValue]]로 둔다.
  4. tvNaN이면, NaN을 반환한다.
  5. MinFromTime(LocalTime(tv))를 반환한다.

21.4.4.8 Date.prototype.getMonth ( )

이 method는 called될 때 following steps를 수행합니다:

  1. dateObjthis value로 둔다.
  2. RequireInternalSlot(dateObj, [[DateValue]])를 수행한다.
  3. tvdateObj.[[DateValue]]로 둔다.
  4. tvNaN이면, NaN을 반환한다.
  5. MonthFromTime(LocalTime(tv))를 반환한다.

21.4.4.9 Date.prototype.getSeconds ( )

이 method는 called될 때 following steps를 수행합니다:

  1. dateObjthis value로 둔다.
  2. RequireInternalSlot(dateObj, [[DateValue]])를 수행한다.
  3. tvdateObj.[[DateValue]]로 둔다.
  4. tvNaN이면, NaN을 반환한다.
  5. SecFromTime(LocalTime(tv))를 반환한다.

21.4.4.10 Date.prototype.getTime ( )

이 method는 called될 때 following steps를 수행합니다:

  1. dateObjthis value로 둔다.
  2. RequireInternalSlot(dateObj, [[DateValue]])를 수행한다.
  3. dateObj.[[DateValue]]를 반환한다.

21.4.4.11 Date.prototype.getTimezoneOffset ( )

이 method는 called될 때 following steps를 수행합니다:

  1. dateObjthis value로 둔다.
  2. RequireInternalSlot(dateObj, [[DateValue]])를 수행한다.
  3. tvdateObj.[[DateValue]]로 둔다.
  4. tvNaN이면, NaN을 반환한다.
  5. (tv - LocalTime(tv)) / msPerMinute를 반환한다.

21.4.4.12 Date.prototype.getUTCDate ( )

이 method는 called될 때 following steps를 수행합니다:

  1. dateObjthis value로 둔다.
  2. RequireInternalSlot(dateObj, [[DateValue]])를 수행한다.
  3. tvdateObj.[[DateValue]]로 둔다.
  4. tvNaN이면, NaN을 반환한다.
  5. DateFromTime(tv)를 반환한다.

21.4.4.13 Date.prototype.getUTCDay ( )

이 method는 called될 때 following steps를 수행합니다:

  1. dateObjthis value로 둔다.
  2. RequireInternalSlot(dateObj, [[DateValue]])를 수행한다.
  3. tvdateObj.[[DateValue]]로 둔다.
  4. tvNaN이면, NaN을 반환한다.
  5. WeekDay(tv)를 반환한다.

21.4.4.14 Date.prototype.getUTCFullYear ( )

이 method는 called될 때 following steps를 수행합니다:

  1. dateObjthis value로 둔다.
  2. RequireInternalSlot(dateObj, [[DateValue]])를 수행한다.
  3. tvdateObj.[[DateValue]]로 둔다.
  4. tvNaN이면, NaN을 반환한다.
  5. YearFromTime(tv)를 반환한다.

21.4.4.15 Date.prototype.getUTCHours ( )

이 method는 called될 때 following steps를 수행합니다:

  1. dateObjthis value로 둔다.
  2. RequireInternalSlot(dateObj, [[DateValue]])를 수행한다.
  3. tvdateObj.[[DateValue]]로 둔다.
  4. tvNaN이면, NaN을 반환한다.
  5. HourFromTime(tv)를 반환한다.

21.4.4.16 Date.prototype.getUTCMilliseconds ( )

이 method는 called될 때 following steps를 수행합니다:

  1. dateObjthis value로 둔다.
  2. RequireInternalSlot(dateObj, [[DateValue]])를 수행한다.
  3. tvdateObj.[[DateValue]]로 둔다.
  4. tvNaN이면, NaN을 반환한다.
  5. msFromTime(tv)를 반환한다.

21.4.4.17 Date.prototype.getUTCMinutes ( )

이 method는 called될 때 following steps를 수행합니다:

  1. dateObjthis value로 둔다.
  2. RequireInternalSlot(dateObj, [[DateValue]])를 수행한다.
  3. tvdateObj.[[DateValue]]로 둔다.
  4. tvNaN이면, NaN을 반환한다.
  5. MinFromTime(tv)를 반환한다.

21.4.4.18 Date.prototype.getUTCMonth ( )

이 method는 called될 때 following steps를 수행합니다:

  1. dateObjthis value로 둔다.
  2. RequireInternalSlot(dateObj, [[DateValue]])를 수행한다.
  3. tvdateObj.[[DateValue]]로 둔다.
  4. tvNaN이면, NaN을 반환한다.
  5. MonthFromTime(tv)를 반환한다.

21.4.4.19 Date.prototype.getUTCSeconds ( )

이 method는 called될 때 following steps를 수행합니다:

  1. dateObjthis value로 둔다.
  2. RequireInternalSlot(dateObj, [[DateValue]])를 수행한다.
  3. tvdateObj.[[DateValue]]로 둔다.
  4. tvNaN이면, NaN을 반환한다.
  5. SecFromTime(tv)를 반환한다.

21.4.4.20 Date.prototype.setDate ( date )

이 method는 called될 때 following steps를 수행합니다:

  1. dateObjthis value로 둔다.
  2. RequireInternalSlot(dateObj, [[DateValue]])를 수행한다.
  3. tvdateObj.[[DateValue]]로 둔다.
  4. dt를 ? ToNumber(date)로 둔다.
  5. tvNaN이면, NaN을 반환한다.
  6. tvLocalTime(tv)로 설정한다.
  7. newDateMakeDate(MakeDay(YearFromTime(tv), MonthFromTime(tv), dt), TimeWithinDay(tv))로 둔다.
  8. uTimeClip(UTC(newDate))로 둔다.
  9. dateObj.[[DateValue]]u로 설정한다.
  10. u를 반환한다.

21.4.4.21 Date.prototype.setFullYear ( year [ , month [ , date ] ] )

이 method는 called될 때 following steps를 수행합니다:

  1. dateObjthis value로 둔다.
  2. RequireInternalSlot(dateObj, [[DateValue]])를 수행한다.
  3. tvdateObj.[[DateValue]]로 둔다.
  4. y를 ? ToNumber(year)로 둔다.
  5. tvNaN이면 tv+0𝔽로 설정한다; 그렇지 않으면 tvLocalTime(tv)로 설정한다.
  6. month가 present하면, m을 ? ToNumber(month)로 둔다; 그렇지 않으면 mMonthFromTime(tv)로 둔다.
  7. date가 present하면, dt를 ? ToNumber(date)로 둔다; 그렇지 않으면 dtDateFromTime(tv)로 둔다.
  8. newDateMakeDate(MakeDay(y, m, dt), TimeWithinDay(tv))로 둔다.
  9. uTimeClip(UTC(newDate))로 둔다.
  10. dateObj.[[DateValue]]u로 설정한다.
  11. u를 반환한다.

이 method의 "length" property는 3𝔽입니다.

Note

month가 present하지 않으면, 이 method는 month가 value getMonth()로 present한 것처럼 behave합니다. date가 present하지 않으면, date가 value getDate()로 present한 것처럼 behave합니다.

21.4.4.22 Date.prototype.setHours ( hour [ , min [ , sec [ , ms ] ] ] )

이 method는 called될 때 following steps를 수행합니다:

  1. dateObjthis value로 둔다.
  2. RequireInternalSlot(dateObj, [[DateValue]])를 수행한다.
  3. tvdateObj.[[DateValue]]로 둔다.
  4. h를 ? ToNumber(hour)로 둔다.
  5. min이 present하면, m을 ? ToNumber(min)으로 둔다.
  6. sec가 present하면, s를 ? ToNumber(sec)로 둔다.
  7. ms가 present하면, milli를 ? ToNumber(ms)로 둔다.
  8. tvNaN이면, NaN을 반환한다.
  9. tvLocalTime(tv)로 설정한다.
  10. min이 present하지 않으면, mMinFromTime(tv)로 둔다.
  11. sec가 present하지 않으면, sSecFromTime(tv)로 둔다.
  12. ms가 present하지 않으면, millimsFromTime(tv)로 둔다.
  13. dateMakeDate(Day(tv), MakeTime(h, m, s, milli))로 둔다.
  14. uTimeClip(UTC(date))로 둔다.
  15. dateObj.[[DateValue]]u로 설정한다.
  16. u를 반환한다.

이 method의 "length" property는 4𝔽입니다.

Note

min이 present하지 않으면, 이 method는 min이 value getMinutes()로 present한 것처럼 behave합니다. sec가 present하지 않으면, sec가 value getSeconds()로 present한 것처럼 behave합니다. ms가 present하지 않으면, ms가 value getMilliseconds()로 present한 것처럼 behave합니다.

21.4.4.23 Date.prototype.setMilliseconds ( ms )

이 method는 called될 때 following steps를 수행합니다:

  1. dateObjthis value로 둔다.
  2. RequireInternalSlot(dateObj, [[DateValue]])를 수행한다.
  3. tvdateObj.[[DateValue]]로 둔다.
  4. ms를 ? ToNumber(ms)로 설정한다.
  5. tvNaN이면, NaN을 반환한다.
  6. tvLocalTime(tv)로 설정한다.
  7. timeMakeTime(HourFromTime(tv), MinFromTime(tv), SecFromTime(tv), ms)로 둔다.
  8. uTimeClip(UTC(MakeDate(Day(tv), time)))로 둔다.
  9. dateObj.[[DateValue]]u로 설정한다.
  10. u를 반환한다.

21.4.4.24 Date.prototype.setMinutes ( min [ , sec [ , ms ] ] )

이 method는 called될 때 following steps를 수행합니다:

  1. dateObjthis value로 둔다.
  2. RequireInternalSlot(dateObj, [[DateValue]])를 수행한다.
  3. tvdateObj.[[DateValue]]로 둔다.
  4. m을 ? ToNumber(min)으로 둔다.
  5. sec가 present하면, s를 ? ToNumber(sec)로 둔다.
  6. ms가 present하면, milli를 ? ToNumber(ms)로 둔다.
  7. tvNaN이면, NaN을 반환한다.
  8. tvLocalTime(tv)로 설정한다.
  9. sec가 present하지 않으면, sSecFromTime(tv)로 둔다.
  10. ms가 present하지 않으면, millimsFromTime(tv)로 둔다.
  11. dateMakeDate(Day(tv), MakeTime(HourFromTime(tv), m, s, milli))로 둔다.
  12. uTimeClip(UTC(date))로 둔다.
  13. dateObj.[[DateValue]]u로 설정한다.
  14. u를 반환한다.

이 method의 "length" property는 3𝔽입니다.

Note

sec가 present하지 않으면, 이 method는 sec가 value getSeconds()로 present한 것처럼 behave합니다. ms가 present하지 않으면, 이는 ms가 value getMilliseconds()로 present한 것처럼 behave합니다.

21.4.4.25 Date.prototype.setMonth ( month [ , date ] )

이 method는 called될 때 following steps를 수행합니다:

  1. dateObjthis value로 둔다.
  2. RequireInternalSlot(dateObj, [[DateValue]])를 수행한다.
  3. tvdateObj.[[DateValue]]로 둔다.
  4. m을 ? ToNumber(month)로 둔다.
  5. date가 present하면, dt를 ? ToNumber(date)로 둔다.
  6. tvNaN이면, NaN을 반환한다.
  7. tvLocalTime(tv)로 설정한다.
  8. date가 present하지 않으면, dtDateFromTime(tv)로 둔다.
  9. newDateMakeDate(MakeDay(YearFromTime(tv), m, dt), TimeWithinDay(tv))로 둔다.
  10. uTimeClip(UTC(newDate))로 둔다.
  11. dateObj.[[DateValue]]u로 설정한다.
  12. u를 반환한다.

이 method의 "length" property는 2𝔽입니다.

Note

date가 present하지 않으면, 이 method는 date가 value getDate()로 present한 것처럼 behave합니다.

21.4.4.26 Date.prototype.setSeconds ( sec [ , ms ] )

이 method는 called될 때 following steps를 수행합니다:

  1. dateObjthis value로 둔다.
  2. RequireInternalSlot(dateObj, [[DateValue]])를 수행한다.
  3. tvdateObj.[[DateValue]]로 둔다.
  4. s를 ? ToNumber(sec)로 둔다.
  5. ms가 present하면, milli를 ? ToNumber(ms)로 둔다.
  6. tvNaN이면, NaN을 반환한다.
  7. tvLocalTime(tv)로 설정한다.
  8. ms가 present하지 않으면, millimsFromTime(tv)로 둔다.
  9. dateMakeDate(Day(tv), MakeTime(HourFromTime(tv), MinFromTime(tv), s, milli))로 둔다.
  10. uTimeClip(UTC(date))로 둔다.
  11. dateObj.[[DateValue]]u로 설정한다.
  12. u를 반환한다.

이 method의 "length" property는 2𝔽입니다.

Note

ms가 present하지 않으면, 이 method는 ms가 value getMilliseconds()로 present한 것처럼 behave합니다.

21.4.4.27 Date.prototype.setTime ( time )

이 method는 called될 때 following steps를 수행합니다:

  1. dateObjthis value로 둔다.
  2. RequireInternalSlot(dateObj, [[DateValue]])를 수행한다.
  3. t를 ? ToNumber(time)로 둔다.
  4. vTimeClip(t)로 둔다.
  5. dateObj.[[DateValue]]v로 설정한다.
  6. v를 반환한다.

21.4.4.28 Date.prototype.setUTCDate ( date )

이 method는 called될 때 following steps를 수행합니다:

  1. dateObjthis value로 둔다.
  2. RequireInternalSlot(dateObj, [[DateValue]])를 수행한다.
  3. tvdateObj.[[DateValue]]로 둔다.
  4. dt를 ? ToNumber(date)로 둔다.
  5. tvNaN이면, NaN을 반환한다.
  6. newDateMakeDate(MakeDay(YearFromTime(tv), MonthFromTime(tv), dt), TimeWithinDay(tv))로 둔다.
  7. vTimeClip(newDate)로 둔다.
  8. dateObj.[[DateValue]]v로 설정한다.
  9. v를 반환한다.

21.4.4.29 Date.prototype.setUTCFullYear ( year [ , month [ , date ] ] )

이 method는 called될 때 following steps를 수행합니다:

  1. dateObjthis value로 둔다.
  2. RequireInternalSlot(dateObj, [[DateValue]])를 수행한다.
  3. tvdateObj.[[DateValue]]로 둔다.
  4. tvNaN이면, tv+0𝔽로 설정한다.
  5. y를 ? ToNumber(year)로 둔다.
  6. month가 present하면, m을 ? ToNumber(month)로 둔다; 그렇지 않으면 mMonthFromTime(tv)로 둔다.
  7. date가 present하면, dt를 ? ToNumber(date)로 둔다; 그렇지 않으면 dtDateFromTime(tv)로 둔다.
  8. newDateMakeDate(MakeDay(y, m, dt), TimeWithinDay(tv))로 둔다.
  9. vTimeClip(newDate)로 둔다.
  10. dateObj.[[DateValue]]v로 설정한다.
  11. v를 반환한다.

이 method의 "length" property는 3𝔽입니다.

Note

month가 present하지 않으면, 이 method는 month가 value getUTCMonth()로 present한 것처럼 behave합니다. date가 present하지 않으면, date가 value getUTCDate()로 present한 것처럼 behave합니다.

21.4.4.30 Date.prototype.setUTCHours ( hour [ , min [ , sec [ , ms ] ] ] )

이 method는 called될 때 following steps를 수행합니다:

  1. dateObjthis value로 둔다.
  2. RequireInternalSlot(dateObj, [[DateValue]])를 수행한다.
  3. tvdateObj.[[DateValue]]로 둔다.
  4. h를 ? ToNumber(hour)로 둔다.
  5. min이 present하면, m을 ? ToNumber(min)으로 둔다.
  6. sec가 present하면, s를 ? ToNumber(sec)로 둔다.
  7. ms가 present하면, milli를 ? ToNumber(ms)로 둔다.
  8. tvNaN이면, NaN을 반환한다.
  9. min이 present하지 않으면, mMinFromTime(tv)로 둔다.
  10. sec가 present하지 않으면, sSecFromTime(tv)로 둔다.
  11. ms가 present하지 않으면, millimsFromTime(tv)로 둔다.
  12. dateMakeDate(Day(tv), MakeTime(h, m, s, milli))로 둔다.
  13. vTimeClip(date)로 둔다.
  14. dateObj.[[DateValue]]v로 설정한다.
  15. v를 반환한다.

이 method의 "length" property는 4𝔽입니다.

Note

min이 present하지 않으면, 이 method는 min이 value getUTCMinutes()로 present한 것처럼 behave합니다. sec가 present하지 않으면, sec가 value getUTCSeconds()로 present한 것처럼 behave합니다. ms가 present하지 않으면, ms가 value getUTCMilliseconds()로 present한 것처럼 behave합니다.

21.4.4.31 Date.prototype.setUTCMilliseconds ( ms )

이 method는 called될 때 following steps를 수행합니다:

  1. dateObjthis value로 둔다.
  2. RequireInternalSlot(dateObj, [[DateValue]])를 수행한다.
  3. tvdateObj.[[DateValue]]로 둔다.
  4. ms를 ? ToNumber(ms)로 설정한다.
  5. tvNaN이면, NaN을 반환한다.
  6. timeMakeTime(HourFromTime(tv), MinFromTime(tv), SecFromTime(tv), ms)로 둔다.
  7. vTimeClip(MakeDate(Day(tv), time))로 둔다.
  8. dateObj.[[DateValue]]v로 설정한다.
  9. v를 반환한다.

21.4.4.32 Date.prototype.setUTCMinutes ( min [ , sec [ , ms ] ] )

이 method는 called될 때 following steps를 수행합니다:

  1. dateObjthis value로 둔다.
  2. RequireInternalSlot(dateObj, [[DateValue]])를 수행한다.
  3. tvdateObj.[[DateValue]]로 둔다.
  4. m을 ? ToNumber(min)으로 둔다.
  5. sec가 present하면, s를 ? ToNumber(sec)로 둔다.
  6. ms가 present하면, milli를 ? ToNumber(ms)로 둔다.
  7. tvNaN이면, NaN을 반환한다.
  8. sec가 present하지 않으면, sSecFromTime(tv)로 둔다.
  9. ms가 present하지 않으면, millimsFromTime(tv)로 둔다.
  10. dateMakeDate(Day(tv), MakeTime(HourFromTime(tv), m, s, milli))로 둔다.
  11. vTimeClip(date)로 둔다.
  12. dateObj.[[DateValue]]v로 설정한다.
  13. v를 반환한다.

이 method의 "length" property는 3𝔽입니다.

Note

sec가 present하지 않으면, 이 method는 sec가 value getUTCSeconds()로 present한 것처럼 behave합니다. ms가 present하지 않으면, 이는 msgetUTCMilliseconds()에 의해 returned되는 value로 present한 것처럼 behave합니다.

21.4.4.33 Date.prototype.setUTCMonth ( month [ , date ] )

이 method는 called될 때 following steps를 수행합니다:

  1. dateObjthis value로 둔다.
  2. RequireInternalSlot(dateObj, [[DateValue]])를 수행한다.
  3. tvdateObj.[[DateValue]]로 둔다.
  4. m을 ? ToNumber(month)로 둔다.
  5. date가 present하면, dt를 ? ToNumber(date)로 둔다.
  6. tvNaN이면, NaN을 반환한다.
  7. date가 present하지 않으면, dtDateFromTime(tv)로 둔다.
  8. newDateMakeDate(MakeDay(YearFromTime(tv), m, dt), TimeWithinDay(tv))로 둔다.
  9. vTimeClip(newDate)로 둔다.
  10. dateObj.[[DateValue]]v로 설정한다.
  11. v를 반환한다.

이 method의 "length" property는 2𝔽입니다.

Note

date가 present하지 않으면, 이 method는 date가 value getUTCDate()로 present한 것처럼 behave합니다.

21.4.4.34 Date.prototype.setUTCSeconds ( sec [ , ms ] )

이 method는 called될 때 following steps를 수행합니다:

  1. dateObjthis value로 둔다.
  2. RequireInternalSlot(dateObj, [[DateValue]])를 수행한다.
  3. tvdateObj.[[DateValue]]로 둔다.
  4. s를 ? ToNumber(sec)로 둔다.
  5. ms가 present하면, milli를 ? ToNumber(ms)로 둔다.
  6. tvNaN이면, NaN을 반환한다.
  7. ms가 present하지 않으면, millimsFromTime(tv)로 둔다.
  8. dateMakeDate(Day(tv), MakeTime(HourFromTime(tv), MinFromTime(tv), s, milli))로 둔다.
  9. vTimeClip(date)로 둔다.
  10. dateObj.[[DateValue]]v로 설정한다.
  11. v를 반환한다.

이 method의 "length" property는 2𝔽입니다.

Note

ms가 present하지 않으면, 이 method는 ms가 value getUTCMilliseconds()로 present한 것처럼 behave합니다.

21.4.4.35 Date.prototype.toDateString ( )

이 method는 called될 때 following steps를 수행합니다:

  1. dateObjthis value로 둔다.
  2. RequireInternalSlot(dateObj, [[DateValue]])를 수행한다.
  3. tvdateObj.[[DateValue]]로 둔다.
  4. tvNaN이면, "Invalid Date"를 반환한다.
  5. tLocalTime(tv)로 둔다.
  6. DateString(t)를 반환한다.

21.4.4.36 Date.prototype.toISOString ( )

이 method는 called될 때 following steps를 수행합니다:

  1. dateObjthis value로 둔다.
  2. RequireInternalSlot(dateObj, [[DateValue]])를 수행한다.
  3. tvdateObj.[[DateValue]]로 둔다.
  4. tvNaN이면, RangeError exception을 throw한다.
  5. Assert: tvintegral Number이다.
  6. tvDate Time String Format으로 represent될 수 없는 year와 corresponding하면, RangeError exception을 throw한다.
  7. all format elements 및 UTC offset representation "Z"를 포함하여 UTC time scale 상에서 Date Time String Format으로 된 tv의 String representation을 반환한다.

21.4.4.37 Date.prototype.toJSON ( key )

이 method는 JSON.stringify(25.5.4)가 사용할 Date의 String representation을 제공합니다.

called될 때 following steps를 수행합니다:

  1. obj를 ? ToObject(this value)로 둔다.
  2. tv를 ? ToPrimitive(obj, number)로 둔다.
  3. tv가 Number이고 tvfinite가 아니면, null을 반환한다.
  4. Invoke(obj, "toISOString")를 반환한다.
Note 1

argument는 ignored됩니다.

Note 2

이 method는 intentionally generic입니다; this value가 Date일 것을 require하지 않습니다. 따라서 method로 사용하기 위해 other kinds of objects에 transferred될 수 있습니다. However, any such object가 toISOString method를 가질 것을 require합니다.

21.4.4.38 Date.prototype.toLocaleDateString ( [ reserved1 [ , reserved2 ] ] )

ECMA-402 Internationalization API를 include하는 ECMAScript implementation은 ECMA-402 specification에 specified된 대로 이 method를 implement해야 합니다. ECMAScript implementation이 ECMA-402 API를 include하지 않으면 이 method의 following specification이 사용됩니다:

이 method는 String value를 반환합니다. String의 contents는 implementation-defined이지만, host environment의 current locale의 convention에 corresponding하는 convenient, human-readable form으로 current time zone에서 Date의 “date” portion을 represent하도록 intended됩니다.

이 method에 대한 optional parameter의 meaning은 ECMA-402 specification에 defined되어 있습니다; ECMA-402 support를 include하지 않는 implementation은 those parameter position을 anything else에 사용해서는 안 됩니다.

21.4.4.39 Date.prototype.toLocaleString ( [ reserved1 [ , reserved2 ] ] )

ECMA-402 Internationalization API를 include하는 ECMAScript implementation은 ECMA-402 specification에 specified된 대로 이 method를 implement해야 합니다. ECMAScript implementation이 ECMA-402 API를 include하지 않으면 이 method의 following specification이 사용됩니다:

이 method는 String value를 반환합니다. String의 contents는 implementation-defined이지만, host environment의 current locale의 convention에 corresponding하는 convenient, human-readable form으로 current time zone에서 Date를 represent하도록 intended됩니다.

이 method에 대한 optional parameter의 meaning은 ECMA-402 specification에 defined되어 있습니다; ECMA-402 support를 include하지 않는 implementation은 those parameter position을 anything else에 사용해서는 안 됩니다.

21.4.4.40 Date.prototype.toLocaleTimeString ( [ reserved1 [ , reserved2 ] ] )

ECMA-402 Internationalization API를 include하는 ECMAScript implementation은 ECMA-402 specification에 specified된 대로 이 method를 implement해야 합니다. ECMAScript implementation이 ECMA-402 API를 include하지 않으면 이 method의 following specification이 사용됩니다:

이 method는 String value를 반환합니다. String의 contents는 implementation-defined이지만, host environment의 current locale의 convention에 corresponding하는 convenient, human-readable form으로 current time zone에서 Date의 “time” portion을 represent하도록 intended됩니다.

이 method에 대한 optional parameter의 meaning은 ECMA-402 specification에 defined되어 있습니다; ECMA-402 support를 include하지 않는 implementation은 those parameter position을 anything else에 사용해서는 안 됩니다.

21.4.4.41 Date.prototype.toString ( )

이 method는 called될 때 following steps를 수행합니다:

  1. dateObjthis value로 둔다.
  2. RequireInternalSlot(dateObj, [[DateValue]])를 수행한다.
  3. tvdateObj.[[DateValue]]로 둔다.
  4. ToDateString(tv)를 반환한다.
Note 1

d.[[DateValue]]가 1000으로 evenly divisible한 any Date d에 대해, Date.parse(d.toString())의 result는 d.valueOf()와 =입니다. 21.4.3.2를 참조하십시오.

Note 2

이 method는 generic하지 않습니다; this value가 Date가 아니면 TypeError exception을 throw합니다. 따라서 method로 사용하기 위해 other kinds of objects에 transferred될 수 없습니다.

21.4.4.41.1 TimeString ( tv )

The abstract operation TimeString takes argument tv (a Number, but not NaN) and returns a String. It performs the following steps when called:

  1. hourToZeroPaddedDecimalString((HourFromTime(tv)), 2)로 둔다.
  2. minuteToZeroPaddedDecimalString((MinFromTime(tv)), 2)로 둔다.
  3. secondToZeroPaddedDecimalString((SecFromTime(tv)), 2)로 둔다.
  4. hour, ":", minute, ":", second, code unit 0x0020 (SPACE), 및 "GMT"string-concatenation을 반환한다.

21.4.4.41.2 DateString ( tv )

The abstract operation DateString takes argument tv (a Number, but not NaN) and returns a String. It performs the following steps when called:

  1. weekday를 Number WeekDay(tv)를 가진 Table 61 안의 entry의 Name으로 둔다.
  2. month를 Number MonthFromTime(tv)를 가진 Table 62 안의 entry의 Name으로 둔다.
  3. dayToZeroPaddedDecimalString((DateFromTime(tv)), 2)로 둔다.
  4. yvYearFromTime(tv)로 둔다.
  5. yv+0𝔽이거나 yv > +0𝔽이면, yearSign을 empty String으로 둔다; 그렇지 않으면 yearSign"-"로 둔다.
  6. paddedYearToZeroPaddedDecimalString(abs((yv)), 4)로 둔다.
  7. weekday, code unit 0x0020 (SPACE), month, code unit 0x0020 (SPACE), day, code unit 0x0020 (SPACE), yearSign, 및 paddedYearstring-concatenation을 반환한다.
Table 61: Names of days of the week
Number Name
+0𝔽 "Sun"
1𝔽 "Mon"
2𝔽 "Tue"
3𝔽 "Wed"
4𝔽 "Thu"
5𝔽 "Fri"
6𝔽 "Sat"
Table 62: Names of months of the year
Number Name
+0𝔽 "Jan"
1𝔽 "Feb"
2𝔽 "Mar"
3𝔽 "Apr"
4𝔽 "May"
5𝔽 "Jun"
6𝔽 "Jul"
7𝔽 "Aug"
8𝔽 "Sep"
9𝔽 "Oct"
10𝔽 "Nov"
11𝔽 "Dec"

21.4.4.41.3 TimeZoneString ( tv )

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

  1. systemTimeZoneIdentifierSystemTimeZoneIdentifier()로 둔다.
  2. IsTimeZoneOffsetString(systemTimeZoneIdentifier)이 true이면, 다음을 수행한다.
    1. offsetNsParseTimeZoneOffsetString(systemTimeZoneIdentifier)로 둔다.
  3. 그렇지 않으면,
    1. offsetNsGetNamedTimeZoneOffsetNanoseconds(systemTimeZoneIdentifier, ((tv) × 106))로 둔다.
  4. offset𝔽(truncate(offsetNs / 106))로 둔다.
  5. offset+0𝔽이거나 offset > +0𝔽이면, 다음을 수행한다.
    1. offsetSign"+"로 둔다.
    2. absOffsetoffset으로 둔다.
  6. 그렇지 않으면,
    1. offsetSign"-"로 둔다.
    2. absOffset을 -offset으로 둔다.
  7. offsetMinToZeroPaddedDecimalString((MinFromTime(absOffset)), 2)로 둔다.
  8. offsetHourToZeroPaddedDecimalString((HourFromTime(absOffset)), 2)로 둔다.
  9. tzName을 empty String이거나 code unit 0x0020 (SPACE), code unit 0x0028 (LEFT PARENTHESIS), implementation-defined timezone name, 및 code unit 0x0029 (RIGHT PARENTHESIS)의 string-concatenationimplementation-defined string으로 둔다.
  10. offsetSign, offsetHour, offsetMin, 및 tzNamestring-concatenation을 반환한다.

21.4.4.41.4 ToDateString ( tv )

The abstract operation ToDateString takes argument tv (an integral Number or NaN) and returns a String. It performs the following steps when called:

  1. tvNaN이면, "Invalid Date"를 반환한다.
  2. localTimeLocalTime(tv)로 둔다.
  3. DateString(localTime), code unit 0x0020 (SPACE), TimeString(localTime), 및 TimeZoneString(tv)의 string-concatenation을 반환한다.

21.4.4.42 Date.prototype.toTimeString ( )

이 method는 called될 때 following steps를 수행합니다:

  1. dateObjthis value로 둔다.
  2. RequireInternalSlot(dateObj, [[DateValue]])를 수행한다.
  3. tvdateObj.[[DateValue]]로 둔다.
  4. tvNaN이면, "Invalid Date"를 반환한다.
  5. localTimeLocalTime(tv)로 둔다.
  6. TimeString(localTime)과 TimeZoneString(tv)의 string-concatenation을 반환한다.

21.4.4.43 Date.prototype.toUTCString ( )

이 method는 this value에 corresponding하는 instant in time을 represent하는 String value를 반환합니다. String의 format은 RFC 7231의 HTTP-date를 기반으로 하며, ECMAScript Dates가 support하는 full range of times를 support하도록 generalized됩니다.

called될 때 following steps를 수행합니다:

  1. dateObjthis value로 둔다.
  2. RequireInternalSlot(dateObj, [[DateValue]])를 수행한다.
  3. tvdateObj.[[DateValue]]로 둔다.
  4. tvNaN이면, "Invalid Date"를 반환한다.
  5. weekday를 Number WeekDay(tv)를 가진 Table 61 안의 entry의 Name으로 둔다.
  6. month를 Number MonthFromTime(tv)를 가진 Table 62 안의 entry의 Name으로 둔다.
  7. dayToZeroPaddedDecimalString((DateFromTime(tv)), 2)로 둔다.
  8. yvYearFromTime(tv)로 둔다.
  9. yv+0𝔽이거나 yv > +0𝔽이면, yearSign을 empty String으로 둔다; 그렇지 않으면 yearSign"-"로 둔다.
  10. paddedYearToZeroPaddedDecimalString(abs((yv)), 4)로 둔다.
  11. weekday, ",", code unit 0x0020 (SPACE), day, code unit 0x0020 (SPACE), month, code unit 0x0020 (SPACE), yearSign, paddedYear, code unit 0x0020 (SPACE), 및 TimeString(tv)의 string-concatenation을 반환한다.

21.4.4.44 Date.prototype.valueOf ( )

이 method는 called될 때 following steps를 수행합니다:

  1. dateObjthis value로 둔다.
  2. RequireInternalSlot(dateObj, [[DateValue]])를 수행한다.
  3. dateObj.[[DateValue]]를 반환한다.

21.4.4.45 Date.prototype [ %Symbol.toPrimitive% ] ( hint )

이 method는 ECMAScript language operator가 Date를 primitive value로 convert하기 위해 called합니다. hint에 allowed되는 values는 "default", "number", 및 "string"입니다. Date는 "default""string"과 equivalent하게 treat한다는 점에서 built-in ECMAScript object 중 unique합니다. all other built-in ECMAScript objects는 "default""number"와 equivalent하게 treat합니다.

called될 때 following steps를 수행합니다:

  1. objthis value로 둔다.
  2. obj가 Object가 아니면, TypeError exception을 throw한다.
  3. hint"string" 또는 "default" 중 하나이면, 다음을 수행한다.
    1. tryFirststring으로 둔다.
  4. 그렇지 않고 hint"number"이면, 다음을 수행한다.
    1. tryFirstnumber로 둔다.
  5. 그렇지 않으면,
    1. TypeError exception을 throw한다.
  6. OrdinaryToPrimitive(obj, tryFirst)를 반환한다.

이 property는 attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }를 가집니다.

이 method의 "name" property의 value는 "[Symbol.toPrimitive]"입니다.

21.4.5 Properties of Date Instances

Date instance는 Date prototype object에서 property를 inherit하는 ordinary object입니다. Date instance는 또한 [[DateValue]] internal slot을 가집니다. [[DateValue]] internal slot은 이 Date가 represented하는 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로 called될 때 new String object를 create하고 initialize합니다.
  • constructor가 아니라 function으로 called될 때 type conversion을 수행합니다.
  • class definition의 extends clause의 value로 사용될 수 있습니다. specified String behaviour를 inherit하려는 subclass constructor[[StringData]] internal slot을 가진 subclass instance를 create하고 initialize하기 위해 String constructor에 대한 super call을 include해야 합니다.

22.1.1.1 String ( value )

이 function은 called될 때 following steps를 수행합니다:

  1. value가 present하지 않으면, 다음을 수행한다.
    1. string을 empty String으로 둔다.
  2. 그렇지 않으면,
    1. NewTarget이 undefined이고 value가 Symbol이면, SymbolDescriptiveString(value)를 반환한다.
    2. string을 ? ToString(value)로 둔다.
  3. NewTarget이 undefined이면, string을 반환한다.
  4. StringCreate(string, ? GetPrototypeFromConstructor(NewTarget, "%String.prototype%"))를 반환한다.

22.1.2 Properties of the String Constructor

String constructor는:

  • value가 %Function.prototype%[[Prototype]] internal slot을 가집니다.
  • 다음 property를 가집니다:

22.1.2.1 String.fromCharCode ( ...codeUnits )

이 function은 rest parameter codeUnits를 form하는 any number의 arguments와 함께 called될 수 있습니다.

called될 때 following steps를 수행합니다:

  1. result를 empty String으로 둔다.
  2. codeUnits의 각 element next에 대해, 다음을 수행한다.
    1. nextCU를 numeric value가 (? ToUint16(next))인 code unit으로 둔다.
    2. resultresultnextCUstring-concatenation으로 설정한다.
  3. result를 반환한다.

이 function의 "length" property는 1𝔽입니다.

22.1.2.2 String.fromCodePoint ( ...codePoints )

이 function은 rest parameter codePoints를 form하는 any number의 arguments와 함께 called될 수 있습니다.

called될 때 following steps를 수행합니다:

  1. result를 empty String으로 둔다.
  2. codePoints의 각 element next에 대해, 다음을 수행한다.
    1. nextCP를 ? ToNumber(next)로 둔다.
    2. nextCPintegral Number가 아니면, RangeError exception을 throw한다.
    3. (nextCP) < 0 또는 (nextCP) > 0x10FFFF이면, RangeError exception을 throw한다.
    4. resultresultUTF16EncodeCodePoint((nextCP))의 string-concatenation으로 설정한다.
  3. Assert: codePoints가 empty이면, result는 empty String이다.
  4. result를 반환한다.

이 function의 "length" property는 1𝔽입니다.

22.1.2.3 String.prototype

String.prototype의 initial value는 String prototype object입니다.

이 property는 attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }를 가집니다.

22.1.2.4 String.raw ( template, ...substitutions )

이 function은 variable number of arguments와 함께 called될 수 있습니다. first argument는 template이고 나머지 arguments는 List substitutions를 form합니다.

called될 때 following steps를 수행합니다:

  1. substitutionCountsubstitutions 안의 elements 수로 둔다.
  2. cooked를 ? ToObject(template)로 둔다.
  3. literals를 ? ToObject(? Get(cooked, "raw"))로 둔다.
  4. literalCount를 ? LengthOfArrayLike(literals)로 둔다.
  5. literalCount ≤ 0이면, empty String을 반환한다.
  6. result를 empty String으로 둔다.
  7. nextIndex를 0으로 둔다.
  8. Repeat,
    1. nextLiteralValue를 ? Get(literals, ! ToString(𝔽(nextIndex)))로 둔다.
    2. nextLiteral을 ? ToString(nextLiteralValue)로 둔다.
    3. resultresultnextLiteralstring-concatenation으로 설정한다.
    4. nextIndex + 1 = literalCount이면, result를 반환한다.
    5. nextIndex < substitutionCount이면, 다음을 수행한다.
      1. nextSubValuesubstitutions[nextIndex]로 둔다.
      2. nextSub를 ? ToString(nextSubValue)로 둔다.
      3. resultresultnextSubstring-concatenation으로 설정한다.
    6. nextIndexnextIndex + 1로 설정한다.
Note

이 function은 Tagged Template(13.3.11)의 tag function으로 use되도록 intended됩니다. 그렇게 called될 때, first argument는 well formed template object이고 rest parameter는 substitution values를 contain합니다.

22.1.3 Properties of the String Prototype Object

String prototype object는:

  • %String.prototype%입니다.
  • String exotic object이며 such objects에 대해 specified된 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을 가집니다.

explicitly 달리 stated되지 않는 한, 아래에 defined된 String prototype object의 methods는 generic하지 않으며, 이들에게 passed되는 this value는 String value 또는 String value로 initialized된 [[StringData]] internal slot을 가진 object여야 합니다.

22.1.3.1 String.prototype.at ( index )

  1. thisValuethis value로 둔다.
  2. RequireObjectCoercible(thisValue)를 수행한다.
  3. string을 ? ToString(thisValue)로 둔다.
  4. lengthstring의 length로 둔다.
  5. relativeIndex를 ? ToIntegerOrInfinity(index)로 둔다.
  6. relativeIndex ≥ 0이면, 다음을 수행한다.
    1. krelativeIndex로 둔다.
  7. 그렇지 않으면,
    1. klength + relativeIndex로 둔다.
  8. k < 0 또는 klength이면, undefined를 반환한다.
  9. stringk부터 k + 1까지의 substring을 반환한다.

22.1.3.2 String.prototype.charAt ( position )

Note 1

이 method는 this object를 String으로 converting한 result인 String value 안에서 index position의 code unit을 contain하는 single element String을 반환합니다. 해당 index에 element가 없으면 result는 empty String입니다. result는 String value이며, String object가 아닙니다.

posintegral Number이면, x.charAt(pos)의 result는 x.substring(pos, pos + 1)의 result와 equivalent합니다.

이 method는 called될 때 following steps를 수행합니다:

  1. thisValuethis value로 둔다.
  2. RequireObjectCoercible(thisValue)를 수행한다.
  3. string을 ? ToString(thisValue)로 둔다.
  4. position을 ? ToIntegerOrInfinity(position)로 설정한다.
  5. sizestring의 length로 둔다.
  6. position < 0 또는 positionsize이면, empty String을 반환한다.
  7. stringposition부터 position + 1까지의 substring을 반환한다.
Note 2

이 method는 intentionally generic입니다; this value가 String object일 것을 require하지 않습니다. 따라서 method로 사용하기 위해 other kinds of objects에 transferred될 수 있습니다.

22.1.3.3 String.prototype.charCodeAt ( position )

Note 1

이 method는 this object를 String으로 converting한 result인 String 안에서 index position의 code unit의 numeric value인 Number(216보다 작은 non-negative integral Number)를 반환합니다. 해당 index에 element가 없으면 result는 NaN입니다.

이 method는 called될 때 following steps를 수행합니다:

  1. thisValuethis value로 둔다.
  2. RequireObjectCoercible(thisValue)를 수행한다.
  3. string을 ? ToString(thisValue)로 둔다.
  4. position을 ? ToIntegerOrInfinity(position)로 설정한다.
  5. sizestring의 length로 둔다.
  6. position < 0 또는 positionsize이면, NaN을 반환한다.
  7. String string 안에서 index position의 code unit의 numeric value에 대한 Number value를 반환한다.
Note 2

이 method는 intentionally generic입니다; this value가 String object일 것을 require하지 않습니다. 따라서 method로 사용하기 위해 other kinds of objects에 transferred될 수 있습니다.

22.1.3.4 String.prototype.codePointAt ( position )

Note 1

이 method는 this object를 String으로 converting한 result인 String 안에서 index position의 string element에서 starting하는 UTF-16 encoded code point(6.1.4)의 numeric value인 0x10FFFF𝔽 이하의 non-negative integral Number를 반환합니다. 해당 index에 element가 없으면 result는 undefined입니다. valid UTF-16 surrogate pairposition에서 begin하지 않으면, result는 position의 code unit입니다.

이 method는 called될 때 following steps를 수행합니다:

  1. thisValuethis value로 둔다.
  2. RequireObjectCoercible(thisValue)를 수행한다.
  3. string을 ? ToString(thisValue)로 둔다.
  4. position을 ? ToIntegerOrInfinity(position)로 설정한다.
  5. sizestring의 length로 둔다.
  6. position < 0 또는 positionsize이면, undefined를 반환한다.
  7. codePointCodePointAt(string, position)으로 둔다.
  8. 𝔽(codePoint.[[CodePoint]])를 반환한다.
Note 2

이 method는 intentionally generic입니다; this value가 String object일 것을 require하지 않습니다. 따라서 method로 사용하기 위해 other kinds of objects에 transferred될 수 있습니다.

22.1.3.5 String.prototype.concat ( ...args )

Note 1

이 method가 called되면 this value의 code units(String으로 converted됨) 뒤에 각 argument가 String으로 converted된 code units가 followed되는 String value를 반환합니다. result는 String value이며, String object가 아닙니다.

이 method는 called될 때 following steps를 수행합니다:

  1. thisValuethis value로 둔다.
  2. RequireObjectCoercible(thisValue)를 수행한다.
  3. string을 ? ToString(thisValue)로 둔다.
  4. resultstring으로 둔다.
  5. args의 각 element next에 대해, 다음을 수행한다.
    1. nextString을 ? ToString(next)로 둔다.
    2. resultresultnextStringstring-concatenation으로 설정한다.
  6. result를 반환한다.

이 method의 "length" property는 1𝔽입니다.

Note 2

이 method는 intentionally generic입니다; this value가 String object일 것을 require하지 않습니다. 따라서 method로 사용하기 위해 other kinds of objects에 transferred될 수 있습니다.

22.1.3.6 String.prototype.constructor

String.prototype.constructor의 initial value는 %String%입니다.

22.1.3.7 String.prototype.endsWith ( searchString [ , endPosition ] )

이 method는 called될 때 following steps를 수행합니다:

  1. thisValuethis value로 둔다.
  2. RequireObjectCoercible(thisValue)를 수행한다.
  3. string을 ? ToString(thisValue)로 둔다.
  4. isRegexp를 ? IsRegExp(searchString)로 둔다.
  5. isRegexptrue이면, TypeError exception을 throw한다.
  6. searchString을 ? ToString(searchString)으로 설정한다.
  7. lengthstring의 length로 둔다.
  8. endPositionundefined이면 positionlength로 둔다; 그렇지 않으면 position을 ? ToIntegerOrInfinity(endPosition)로 둔다.
  9. endposition을 0과 length 사이로 clamping한 result로 둔다.
  10. searchLengthsearchString의 length로 둔다.
  11. searchLength = 0이면, true를 반환한다.
  12. startend - searchLength로 둔다.
  13. start < 0이면, false를 반환한다.
  14. substringstringstart부터 end까지의 substring으로 둔다.
  15. substringsearchString이면, true를 반환한다.
  16. false를 반환한다.
Note 1

first argument가 RegExp이면 exception을 throw하는 것은, future editions가 such argument values를 allow하는 extensions를 define할 수 있도록 specified되었습니다.

Note 2

이 method는 intentionally generic입니다; this value가 String object일 것을 require하지 않습니다. 따라서 method로 사용하기 위해 other kinds of objects에 transferred될 수 있습니다.

22.1.3.8 String.prototype.includes ( searchString [ , position ] )

이 method는 called될 때 following steps를 수행합니다:

  1. thisValuethis value로 둔다.
  2. RequireObjectCoercible(thisValue)를 수행한다.
  3. string을 ? ToString(thisValue)로 둔다.
  4. isRegexp를 ? IsRegExp(searchString)로 둔다.
  5. isRegexptrue이면, TypeError exception을 throw한다.
  6. searchString을 ? ToString(searchString)으로 설정한다.
  7. positionInt를 ? ToIntegerOrInfinity(position)로 둔다.
  8. Assert: positionundefined이면, positionInt는 0이다.
  9. lengthstring의 length로 둔다.
  10. startpositionInt를 0과 length 사이로 clamping한 result로 둔다.
  11. indexStringIndexOf(string, searchString, start)로 둔다.
  12. indexnot-found이면, false를 반환한다.
  13. true를 반환한다.
Note 1

searchString이 this object를 String으로 converting한 result의 substring으로, position 이상인 one or more indices에 appear하면 이 function은 true를 반환합니다; otherwise false를 반환합니다. positionundefined이면 String 전체를 search하도록 0이 assumed됩니다.

Note 2

first argument가 RegExp이면 exception을 throw하는 것은, future editions가 such argument values를 allow하는 extensions를 define할 수 있도록 specified되었습니다.

Note 3

이 method는 intentionally generic입니다; this value가 String object일 것을 require하지 않습니다. 따라서 method로 사용하기 위해 other kinds of objects에 transferred될 수 있습니다.

22.1.3.9 String.prototype.indexOf ( searchString [ , position ] )

Note 1

searchString이 this object를 String으로 converting한 result의 substring으로, position 이상인 one or more indices에 appear하면, smallest such index가 returned됩니다; otherwise -1𝔽가 returned됩니다. positionundefined이면 String 전체를 search하도록 +0𝔽가 assumed됩니다.

이 method는 called될 때 following steps를 수행합니다:

  1. thisValuethis value로 둔다.
  2. RequireObjectCoercible(thisValue)를 수행한다.
  3. string을 ? ToString(thisValue)로 둔다.
  4. searchString을 ? ToString(searchString)으로 설정한다.
  5. positionInt를 ? ToIntegerOrInfinity(position)로 둔다.
  6. Assert: positionundefined이면, positionInt는 0이다.
  7. lengthstring의 length로 둔다.
  8. startpositionInt를 0과 length 사이로 clamping한 result로 둔다.
  9. resultStringIndexOf(string, searchString, start)로 둔다.
  10. resultnot-found이면, -1𝔽를 반환한다.
  11. 𝔽(result)를 반환한다.
Note 2

이 method는 intentionally generic입니다; this value가 String object일 것을 require하지 않습니다. 따라서 method로 사용하기 위해 other kinds of objects에 transferred될 수 있습니다.

22.1.3.10 String.prototype.isWellFormed ( )

이 method는 called될 때 following steps를 수행합니다:

  1. thisValuethis value로 둔다.
  2. RequireObjectCoercible(thisValue)를 수행한다.
  3. string을 ? ToString(thisValue)로 둔다.
  4. IsStringWellFormedUnicode(string)을 반환한다.

22.1.3.11 String.prototype.lastIndexOf ( searchString [ , position ] )

Note 1

searchString이 this object를 String으로 converting한 result의 substring으로 position 이하인 one or more indices에 appear하면, greatest such index가 returned됩니다; otherwise -1𝔽가 returned됩니다. positionundefined이면, String value의 length가 assumed되어 String 전체를 search합니다.

이 method는 called될 때 following steps를 수행합니다:

  1. thisValuethis value로 둔다.
  2. RequireObjectCoercible(thisValue)를 수행한다.
  3. string을 ? ToString(thisValue)로 둔다.
  4. searchString을 ? ToString(searchString)으로 설정한다.
  5. numberPosition을 ? ToNumber(position)으로 둔다.
  6. Assert: positionundefined이면, numberPositionNaN이다.
  7. numberPositionNaN이면 position을 +∞로 설정한다; 그렇지 않으면 position을 ! ToIntegerOrInfinity(numberPosition)로 설정한다.
  8. lengthstring의 length로 둔다.
  9. searchLengthsearchString의 length로 둔다.
  10. length < searchLength이면, -1𝔽를 반환한다.
  11. startposition을 0과 length - searchLength 사이로 clamping한 result로 둔다.
  12. resultStringLastIndexOf(string, searchString, start)로 둔다.
  13. resultnot-found이면, -1𝔽를 반환한다.
  14. 𝔽(result)를 반환한다.
Note 2

이 method는 intentionally generic입니다; this value가 String object일 것을 require하지 않습니다. 따라서 method로 사용하기 위해 other kinds of objects에 transferred될 수 있습니다.

22.1.3.12 String.prototype.localeCompare ( that [ , reserved1 [ , reserved2 ] ] )

ECMA-402 Internationalization API를 include하는 ECMAScript implementation은 ECMA-402 specification에 specified된 대로 이 method를 implement해야 합니다. ECMAScript implementation이 ECMA-402 API를 include하지 않으면 이 method의 following specification이 사용됩니다:

이 method는 this value(String string으로 converted됨)를 that(String thatValue로 converted됨)과 implementation-defined locale-sensitive String comparison한 result를 representing하는 NaN이 아닌 Number를 반환합니다. result는 host environment의 current locale의 conventions에 따른 String values의 sort order와 corresponding하도록 intended되며, stringthatValue보다 before로 ordered되면 negative, stringthatValue보다 after로 ordered되면 positive, 그리고 all other cases에서는 zero(stringthatValue 사이에 relative ordering이 없음을 representing)입니다.

comparisons를 수행하기 before, 이 method는 Strings를 prepare하기 위해 following steps를 수행합니다:

  1. thisValuethis value로 둔다.
  2. RequireObjectCoercible(thisValue)를 수행한다.
  3. string을 ? ToString(thisValue)로 둔다.
  4. thatValue를 ? ToString(that)로 둔다.

이 method에 대한 optional second 및 third parameters의 meaning은 ECMA-402 specification에 defined되어 있습니다; ECMA-402 support를 include하지 않는 implementations는 those parameter positions에 any other interpretation을 assign해서는 안 됩니다.

actual return values는 additional information을 encode할 수 있도록 implementation-defined이지만, 이 method는 two arguments의 method로 considered될 때 all Strings의 set에 total ordering을 defining하는 consistent comparator일 것이 required됩니다. 또한 이 method는 Unicode Standard에 따른 canonical equivalence를 recognize하고 honour해야 하며, distinguishable Strings가 canonically equivalent인 경우 comparing할 때 +0𝔽를 return하는 것도 include합니다.

Note 1

이 method 자체는 Array.prototype.sort의 argument로 직접 suitable하지 않습니다. latter는 two arguments의 function을 require하기 때문입니다.

Note 2

이 method는 ECMAScript environment가 host environment로부터 사용할 수 있는 whatever language- and/or locale-sensitive comparison functionality에 rely할 수 있으며, host environment의 current locale의 conventions에 따라 compare하도록 intended됩니다. However, comparison capabilities와 관계없이, 이 method는 Unicode Standard에 따른 canonical equivalence를 recognize하고 honour해야 합니다—예를 들어, following comparisons는 모두 +0𝔽를 반환해야 합니다:

// Å ANGSTROM SIGN vs.
// Å LATIN CAPITAL LETTER A + COMBINING RING ABOVE
"\u212B".localeCompare("A\u030A")

// Ω OHM SIGN vs.
// Ω GREEK CAPITAL LETTER OMEGA
"\u2126".localeCompare("\u03A9")

// ṩ LATIN SMALL LETTER S WITH DOT BELOW AND DOT ABOVE vs.
// ṩ LATIN SMALL LETTER S + COMBINING DOT ABOVE + COMBINING DOT BELOW
"\u1E69".localeCompare("s\u0307\u0323")

// ḍ̇ LATIN SMALL LETTER D WITH DOT ABOVE + COMBINING DOT BELOW vs.
// ḍ̇ LATIN SMALL LETTER D WITH DOT BELOW + COMBINING DOT ABOVE
"\u1E0B\u0323".localeCompare("\u1E0D\u0307")

// 가 HANGUL CHOSEONG KIYEOK + HANGUL JUNGSEONG A vs.
// 가 HANGUL SYLLABLE GA
"\u1100\u1161".localeCompare("\uAC00")

canonical equivalence의 definition 및 discussion은 Unicode Standard의 chapters 2 및 3, 그리고 Unicode Standard Annex #15, Unicode Normalization FormsUnicode Technical Note #5, Canonical Equivalence in Applications를 참조하십시오. 또한 Unicode Technical Standard #10, Unicode Collation Algorithm도 참조하십시오.

이 method는 Unicode Standard chapter 3, section 3.7에 defined된 Unicode compatibility equivalents 또는 compatibility decompositions를 honour하지 않는 것이 recommended됩니다.

Note 3

이 method는 intentionally generic입니다; this value가 String object일 것을 require하지 않습니다. 따라서 method로 사용하기 위해 other kinds of objects에 transferred될 수 있습니다.

22.1.3.13 String.prototype.match ( regexpOrPattern )

이 method는 called될 때 following steps를 수행합니다:

  1. thisValuethis value로 둔다.
  2. RequireObjectCoercible(thisValue)를 수행한다.
  3. regexpOrPattern이 Object이면, 다음을 수행한다.
    1. matcher를 ? GetMethod(regexpOrPattern, %Symbol.match%)로 둔다.
    2. matcherundefined가 아니면, 다음을 수행한다.
      1. Call(matcher, regexpOrPattern, « thisValue »)를 반환한다.
  4. string을 ? ToString(thisValue)로 둔다.
  5. regexp를 ? RegExpCreate(regexpOrPattern, undefined)로 둔다.
  6. Invoke(regexp, %Symbol.match%, « string »)를 반환한다.
Note

이 method는 intentionally generic입니다; this value가 String object일 것을 require하지 않습니다. 따라서 method로 사용하기 위해 other kinds of objects에 transferred될 수 있습니다.

22.1.3.14 String.prototype.matchAll ( regexpOrPattern )

이 method는 this value를 representing하는 String에 대해 regexpOrPattern과 regular expression match를 수행하고 match results를 yield하는 iterator를 반환합니다. 각 match result는 String의 matched portion을 first element로 contain하고, 그 뒤에 any capturing groups에 의해 matched된 portions가 followed되는 Array입니다. regular expression이 never matches하면, returned iterator는 any match results도 yield하지 않습니다.

called될 때 following steps를 수행합니다:

  1. thisValuethis value로 둔다.
  2. RequireObjectCoercible(thisValue)를 수행한다.
  3. regexpOrPattern이 Object이면, 다음을 수행한다.
    1. isRegexp를 ? IsRegExp(regexpOrPattern)로 둔다.
    2. isRegexptrue이면, 다음을 수행한다.
      1. flags를 ? Get(regexpOrPattern, "flags")로 둔다.
      2. RequireObjectCoercible(flags)를 수행한다.
      3. ToString(flags)가 "g"를 contain하지 않으면, TypeError exception을 throw한다.
    3. matcher를 ? GetMethod(regexpOrPattern, %Symbol.matchAll%)로 둔다.
    4. matcherundefined가 아니면, 다음을 수행한다.
      1. Call(matcher, regexpOrPattern, « thisValue »)를 반환한다.
  4. string을 ? ToString(thisValue)로 둔다.
  5. regexp를 ? RegExpCreate(regexpOrPattern, "g")로 둔다.
  6. Invoke(regexp, %Symbol.matchAll%, « string »)를 반환한다.
Note 1
이 method는 intentionally generic입니다. this value가 String object일 것을 require하지 않습니다. 따라서 method로 사용하기 위해 other kinds of objects에 transferred될 수 있습니다.
Note 2
String.prototype.split과 similarly, String.prototype.matchAll은 typically 그 inputs를 mutating하지 않고 act하도록 designed되었습니다.

22.1.3.15 String.prototype.normalize ( [ form ] )

이 method는 called될 때 following steps를 수행합니다:

  1. thisValuethis value로 둔다.
  2. RequireObjectCoercible(thisValue)를 수행한다.
  3. string을 ? ToString(thisValue)로 둔다.
  4. formundefined이면, form"NFC"로 설정한다.
  5. 그렇지 않으면, form을 ? ToString(form)으로 설정한다.
  6. form"NFC", "NFD", "NFKC", 또는 "NFKD" 중 하나가 아니면, RangeError exception을 throw한다.
  7. normalthe latest Unicode Standard, Normalization Forms에 specified된 대로 form에 의해 named된 normalization form으로 string을 normalizing한 result인 String value로 둔다.
  8. normal을 반환한다.
Note

이 method는 intentionally generic입니다; this value가 String object일 것을 require하지 않습니다. 따라서 method로 사용하기 위해 other kinds of objects에 transferred될 수 있습니다.

22.1.3.16 String.prototype.padEnd ( maxLength [ , fillString ] )

이 method는 called될 때 following steps를 수행합니다:

  1. thisValuethis value로 둔다.
  2. RequireObjectCoercible(thisValue)를 수행한다.
  3. StringPaddingBuiltinsImpl(thisValue, maxLength, fillString, end)를 반환한다.

22.1.3.17 String.prototype.padStart ( maxLength [ , fillString ] )

이 method는 called될 때 following steps를 수행합니다:

  1. thisValuethis value로 둔다.
  2. RequireObjectCoercible(thisValue)를 수행한다.
  3. StringPaddingBuiltinsImpl(thisValue, maxLength, fillString, start)를 반환한다.

22.1.3.17.1 StringPaddingBuiltinsImpl ( thisValue, maxLength, fillString, placement )

The abstract operation StringPaddingBuiltinsImpl takes arguments thisValue (an ECMAScript language value), maxLength (an ECMAScript language value), fillString (an ECMAScript language value), and placement (start or end) and returns either a normal completion containing a String or a throw completion. It performs the following steps when called:

  1. string을 ? ToString(thisValue)로 둔다.
  2. intMaxLength(? ToLength(maxLength))로 둔다.
  3. stringLengthstring의 length로 둔다.
  4. intMaxLengthstringLength이면, string을 반환한다.
  5. fillStringundefined이면, fillString을 code unit 0x0020 (SPACE)만으로 구성된 String value로 설정한다.
  6. 그렇지 않으면, fillString을 ? ToString(fillString)으로 설정한다.
  7. StringPad(string, intMaxLength, fillString, placement)를 반환한다.

22.1.3.17.2 StringPad ( string, maxLength, fillString, placement )

The abstract operation StringPad takes arguments string (a String), maxLength (a non-negative integer), fillString (a String), and placement (start or end) and returns a String. It performs the following steps when called:

  1. stringLengthstring의 length로 둔다.
  2. maxLengthstringLength이면, string을 반환한다.
  3. fillString이 empty String이면, string을 반환한다.
  4. fillLengthmaxLength - stringLength로 둔다.
  5. truncatedStringFillerfillString의 repeated concatenations로 구성되고 length fillLength로 truncated된 String value로 둔다.
  6. placementstart이면, truncatedStringFillerstringstring-concatenation을 반환한다.
  7. stringtruncatedStringFillerstring-concatenation을 반환한다.
Note 1

argument maxLengthstring의 length보다 작아질 수 없도록 clamped됩니다.

Note 2

argument fillString" " (code unit 0x0020 SPACE로 구성된 String value)가 default입니다.

22.1.3.17.3 ToZeroPaddedDecimalString ( n, minLength )

The abstract operation ToZeroPaddedDecimalString takes arguments n (a non-negative integer) and minLength (a non-negative integer) and returns a String. It performs the following steps when called:

  1. string을 decimal number로 formatted된 n의 String representation으로 둔다.
  2. StringPad(string, minLength, "0", start)를 반환한다.

22.1.3.18 String.prototype.repeat ( count )

이 method는 called될 때 following steps를 수행합니다:

  1. thisValuethis value로 둔다.
  2. RequireObjectCoercible(thisValue)를 수행한다.
  3. string을 ? ToString(thisValue)로 둔다.
  4. n을 ? ToIntegerOrInfinity(count)로 둔다.
  5. n < 0 또는 n = +∞이면, RangeError exception을 throw한다.
  6. n = 0이면, empty String을 반환한다.
  7. stringn copies가 appended together되어 만들어진 String value를 반환한다.
Note 1

이 method는 this value(String으로 converted됨)의 code units가 count times repeated된 String value를 create합니다.

Note 2

이 method는 intentionally generic입니다; this value가 String object일 것을 require하지 않습니다. 따라서 method로 사용하기 위해 other kinds of objects에 transferred될 수 있습니다.

22.1.3.19 String.prototype.replace ( searchValue, replaceValue )

이 method는 called될 때 following steps를 수행합니다:

  1. thisValuethis value로 둔다.
  2. RequireObjectCoercible(thisValue)를 수행한다.
  3. searchValue가 Object이면, 다음을 수행한다.
    1. replacer를 ? GetMethod(searchValue, %Symbol.replace%)로 둔다.
    2. replacerundefined가 아니면, 다음을 수행한다.
      1. Call(replacer, searchValue, « thisValue, replaceValue »)를 반환한다.
  4. string을 ? ToString(thisValue)로 둔다.
  5. searchString을 ? ToString(searchValue)로 둔다.
  6. functionalReplaceIsCallable(replaceValue)로 둔다.
  7. functionalReplacefalse이면, 다음을 수행한다.
    1. replaceValue를 ? ToString(replaceValue)로 설정한다.
  8. searchLengthsearchString의 length로 둔다.
  9. positionStringIndexOf(string, searchString, 0)으로 둔다.
  10. positionnot-found이면, string을 반환한다.
  11. precedingstring의 0부터 position까지의 substring으로 둔다.
  12. followingstringposition + searchLength부터의 substring으로 둔다.
  13. functionalReplacetrue이면, 다음을 수행한다.
    1. replacement를 ? ToString(? Call(replaceValue, undefined, « searchString, 𝔽(position), string »))로 둔다.
  14. 그렇지 않으면,
    1. Assert: replaceValue는 String이다.
    2. captures를 새 empty List로 둔다.
    3. replacement를 ! GetSubstitution(searchString, string, position, captures, undefined, replaceValue)로 둔다.
  15. preceding, replacement, 및 followingstring-concatenation을 반환한다.
Note

이 method는 intentionally generic입니다; this value가 String object일 것을 require하지 않습니다. 따라서 method로 사용하기 위해 other kinds of objects에 transferred될 수 있습니다.

22.1.3.19.1 GetSubstitution ( matched, string, position, captures, namedCaptures, replacementTemplate )

The abstract operation GetSubstitution takes arguments matched (a String), string (a String), position (a non-negative integer), captures (a List of either Strings or undefined), namedCaptures (an Object or undefined), and replacementTemplate (a String) and returns either a normal completion containing a String or a throw completion. 이 abstract operation의 purposes를 위해, decimal digit은 0x0030 (DIGIT ZERO)부터 0x0039 (DIGIT NINE)까지의 inclusive interval 안의 code unit입니다. It performs the following steps when called:

  1. stringLengthstring의 length로 둔다.
  2. Assert: positionstringLength이다.
  3. result를 empty String으로 둔다.
  4. templateRemainderreplacementTemplate으로 둔다.
  5. Repeat, while templateRemainder is not the empty String,
    1. NOTE: following steps는 ref(templateRemainder의 prefix)를 isolate하고, refReplacement(그 replacement)를 determine한 뒤, 그 replacement를 result에 append한다.
    2. templateRemainder"$$"로 starts하면, 다음을 수행한다.
      1. ref"$$"로 둔다.
      2. refReplacement"$"로 둔다.
    3. 그렇지 않고 templateRemainder"$`"로 starts하면, 다음을 수행한다.
      1. ref"$`"로 둔다.
      2. refReplacementstring의 0부터 position까지의 substring으로 둔다.
    4. 그렇지 않고 templateRemainder"$&"로 starts하면, 다음을 수행한다.
      1. ref"$&"로 둔다.
      2. refReplacementmatched로 둔다.
    5. 그렇지 않고 templateRemainder"$'" (0x0024 (DOLLAR SIGN) followed by 0x0027 (APOSTROPHE))로 starts하면, 다음을 수행한다.
      1. ref"$'"로 둔다.
      2. matchLengthmatched의 length로 둔다.
      3. tailPositionposition + matchLength로 둔다.
      4. refReplacementstringmin(tailPosition, stringLength)부터의 substring으로 둔다.
      5. NOTE: tailPosition은 this abstract operation이 %RegExp.prototype%의 intrinsic %Symbol.replace% method를, "exec" property가 intrinsic %RegExp.prototype.exec%가 아닌 object에서 call하여 invoked된 경우에만 stringLength를 exceed할 수 있다.
    6. 그렇지 않고 templateRemainder"$" followed by 1 or more decimal digits로 starts하면, 다음을 수행한다.
      1. templateRemainder"$" followed by 2 or more decimal digits로 starts하면 digitCount를 2로 둔다; 그렇지 않으면 digitCount를 1로 둔다.
      2. digitstemplateRemainder의 1부터 1 + digitCount까지의 substring으로 둔다.
      3. index(StringToNumber(digits))로 둔다.
      4. Assert: 0 ≤ index ≤ 99이다.
      5. captureLengthcaptures의 elements 수로 둔다.
      6. index > captureLength이고 digitCount = 2이면, 다음을 수행한다.
        1. NOTE: two-digit replacement pattern이 capturing groups의 count를 exceeding하는 index를 specify하면, one-digit replacement pattern followed by a literal digit로 treated된다.
        2. digitCount를 1로 설정한다.
        3. digitsdigits의 0부터 1까지의 substring으로 설정한다.
        4. index(StringToNumber(digits))로 설정한다.
      7. reftemplateRemainder의 0부터 1 + digitCount까지의 substring으로 둔다.
      8. 1 ≤ indexcaptureLength이면, 다음을 수행한다.
        1. capturecaptures[index - 1]로 둔다.
        2. captureundefined이면, 다음을 수행한다.
          1. refReplacement를 empty String으로 둔다.
        3. 그렇지 않으면,
          1. refReplacementcapture로 둔다.
      9. 그렇지 않으면,
        1. refReplacementref로 둔다.
    7. 그렇지 않고 templateRemainder"$<"로 starts하면, 다음을 수행한다.
      1. gtPositionStringIndexOf(templateRemainder, ">", 0)으로 둔다.
      2. gtPositionnot-found이거나 namedCapturesundefined이면, 다음을 수행한다.
        1. ref"$<"로 둔다.
        2. refReplacementref로 둔다.
      3. 그렇지 않으면,
        1. reftemplateRemainder의 0부터 gtPosition + 1까지의 substring으로 둔다.
        2. groupNametemplateRemainder의 2부터 gtPosition까지의 substring으로 둔다.
        3. Assert: namedCaptures는 Object이다.
        4. capture를 ? Get(namedCaptures, groupName)으로 둔다.
        5. captureundefined이면, 다음을 수행한다.
          1. refReplacement를 empty String으로 둔다.
        6. 그렇지 않으면,
          1. refReplacement를 ? ToString(capture)로 둔다.
    8. 그렇지 않으면,
      1. reftemplateRemainder의 0부터 1까지의 substring으로 둔다.
      2. refReplacementref로 둔다.
    9. refLengthref의 length로 둔다.
    10. templateRemaindertemplateRemainderrefLength부터의 substring으로 설정한다.
    11. resultresultrefReplacementstring-concatenation으로 설정한다.
  6. result를 반환한다.

22.1.3.20 String.prototype.replaceAll ( searchValue, replaceValue )

이 method는 called될 때 following steps를 수행합니다:

  1. thisValuethis value로 둔다.
  2. RequireObjectCoercible(thisValue)를 수행한다.
  3. searchValue가 Object이면, 다음을 수행한다.
    1. isRegexp를 ? IsRegExp(searchValue)로 둔다.
    2. isRegexptrue이면, 다음을 수행한다.
      1. flags를 ? Get(searchValue, "flags")로 둔다.
      2. RequireObjectCoercible(flags)를 수행한다.
      3. ToString(flags)가 "g"를 contain하지 않으면, TypeError exception을 throw한다.
    3. replacer를 ? GetMethod(searchValue, %Symbol.replace%)로 둔다.
    4. replacerundefined가 아니면, 다음을 수행한다.
      1. Call(replacer, searchValue, « thisValue, replaceValue »)를 반환한다.
  4. string을 ? ToString(thisValue)로 둔다.
  5. searchString을 ? ToString(searchValue)로 둔다.
  6. functionalReplaceIsCallable(replaceValue)로 둔다.
  7. functionalReplacefalse이면, 다음을 수행한다.
    1. replaceValue를 ? ToString(replaceValue)로 설정한다.
  8. searchLengthsearchString의 length로 둔다.
  9. advanceBymax(1, searchLength)로 둔다.
  10. matchPositions를 새 empty List로 둔다.
  11. positionStringIndexOf(string, searchString, 0)으로 둔다.
  12. Repeat, while position is not not-found,
    1. positionmatchPositions에 append한다.
    2. positionStringIndexOf(string, searchString, position + advanceBy)로 설정한다.
  13. endOfLastMatch를 0으로 둔다.
  14. result를 empty String으로 둔다.
  15. matchPositions의 각 element matchPosition에 대해, 다음을 수행한다.
    1. preservedstringendOfLastMatch부터 matchPosition까지의 substring으로 둔다.
    2. functionalReplacetrue이면, 다음을 수행한다.
      1. replacement를 ? ToString(? Call(replaceValue, undefined, « searchString, 𝔽(matchPosition), string »))로 둔다.
    3. 그렇지 않으면,
      1. Assert: replaceValue는 String이다.
      2. captures를 새 empty List로 둔다.
      3. replacement를 ! GetSubstitution(searchString, string, matchPosition, captures, undefined, replaceValue)로 둔다.
    4. resultresult, preserved, 및 replacementstring-concatenation으로 설정한다.
    5. endOfLastMatchmatchPosition + searchLength로 설정한다.
  16. endOfLastMatch < string의 length이면, 다음을 수행한다.
    1. resultresultstringendOfLastMatch부터의 substringstring-concatenation으로 설정한다.
  17. result를 반환한다.

22.1.3.21 String.prototype.search ( regexpOrPattern )

이 method는 called될 때 following steps를 수행합니다:

  1. thisValuethis value로 둔다.
  2. RequireObjectCoercible(thisValue)를 수행한다.
  3. regexpOrPattern이 Object이면, 다음을 수행한다.
    1. searcher를 ? GetMethod(regexpOrPattern, %Symbol.search%)로 둔다.
    2. searcherundefined가 아니면, 다음을 수행한다.
      1. Call(searcher, regexpOrPattern, « thisValue »)를 반환한다.
  4. string을 ? ToString(thisValue)로 둔다.
  5. regexp를 ? RegExpCreate(regexpOrPattern, undefined)로 둔다.
  6. Invoke(regexp, %Symbol.search%, « string »)를 반환한다.
Note

이 method는 intentionally generic입니다; this value가 String object일 것을 require하지 않습니다. 따라서 method로 사용하기 위해 other kinds of objects에 transferred될 수 있습니다.

22.1.3.22 String.prototype.slice ( start, end )

이 method는 this object를 String으로 converting한 result의 substring을 반환하며, index start에서 start하여 index end 전까지(or endundefined이면 String의 end까지) running합니다. start가 negative이면, 이는 sourceLength + start로 treated되며 여기서 sourceLength는 String의 length입니다. end가 negative이면, 이는 sourceLength + end로 treated되며 여기서 sourceLength는 String의 length입니다. result는 String value이며, String object가 아닙니다.

called될 때 following steps를 수행합니다:

  1. thisValuethis value로 둔다.
  2. RequireObjectCoercible(thisValue)를 수행한다.
  3. string을 ? ToString(thisValue)로 둔다.
  4. lengthstring의 length로 둔다.
  5. intStart를 ? ToIntegerOrInfinity(start)로 둔다.
  6. intStart = -∞이면, from을 0으로 둔다.
  7. 그렇지 않고 intStart < 0이면, frommax(length + intStart, 0)으로 둔다.
  8. 그렇지 않으면, frommin(intStart, length)로 둔다.
  9. endundefined이면 intEndlength로 둔다; 그렇지 않으면 intEnd를 ? ToIntegerOrInfinity(end)로 둔다.
  10. intEnd = -∞이면, to를 0으로 둔다.
  11. 그렇지 않고 intEnd < 0이면, tomax(length + intEnd, 0)으로 둔다.
  12. 그렇지 않으면, tomin(intEnd, length)로 둔다.
  13. fromto이면, empty String을 반환한다.
  14. stringfrom부터 to까지의 substring을 반환한다.
Note

이 method는 intentionally generic입니다; this value가 String object일 것을 require하지 않습니다. 따라서 method로 사용하기 위해 other kinds of objects에 transferred될 수 있습니다.

22.1.3.23 String.prototype.split ( separator, limit )

이 method는 this object를 String으로 converting한 result의 substrings가 stored된 Array를 반환합니다. substrings는 separator의 occurrences를 left to right로 searching하여 determined됩니다; 이러한 occurrences는 returned array 안의 any String의 part가 아니지만, String value를 divide up하는 역할을 합니다. separator의 value는 any length의 String일 수 있고, %Symbol.split% method를 가진 object(예: RegExp)일 수도 있습니다.

called될 때 following steps를 수행합니다:

  1. thisValuethis value로 둔다.
  2. RequireObjectCoercible(thisValue)를 수행한다.
  3. separator가 Object이면, 다음을 수행한다.
    1. splitter를 ? GetMethod(separator, %Symbol.split%)로 둔다.
    2. splitterundefined가 아니면, 다음을 수행한다.
      1. Call(splitter, separator, « thisValue, limit »)를 반환한다.
  4. string을 ? ToString(thisValue)로 둔다.
  5. limitundefined이면 lim을 232 - 1로 둔다; 그렇지 않으면 lim(? ToUint32(limit))로 둔다.
  6. separatorString을 ? ToString(separator)로 둔다.
  7. lim = 0이면, 다음을 수행한다.
    1. CreateArrayFromList(« »)를 반환한다.
  8. separatorundefined이면, 다음을 수행한다.
    1. CreateArrayFromListstring »)를 반환한다.
  9. separatorLengthseparatorString의 length로 둔다.
  10. separatorLength = 0이면, 다음을 수행한다.
    1. stringLengthstring의 length로 둔다.
    2. outLengthlim을 0과 stringLength 사이로 clamping한 result로 둔다.
    3. headstring의 0부터 outLength까지의 substring으로 둔다.
    4. codeUnitshead의 elements인 code units의 sequence로 구성된 List로 둔다.
    5. CreateArrayFromList(codeUnits)를 반환한다.
  11. string이 empty String이면, CreateArrayFromListstring »)를 반환한다.
  12. substrings를 새 empty List로 둔다.
  13. searchStart를 0으로 둔다.
  14. matchIndexStringIndexOf(string, separatorString, 0)으로 둔다.
  15. Repeat, while matchIndex is not not-found,
    1. substringstringsearchStart부터 matchIndex까지의 substring으로 둔다.
    2. substringsubstrings에 append한다.
    3. substrings 안의 elements 수가 lim이면, CreateArrayFromList(substrings)를 반환한다.
    4. searchStartmatchIndex + separatorLength로 설정한다.
    5. matchIndexStringIndexOf(string, separatorString, searchStart)로 설정한다.
  16. substringstringsearchStart부터의 substring으로 둔다.
  17. substringsubstrings에 append한다.
  18. CreateArrayFromList(substrings)를 반환한다.
Note 1

separator의 value는 empty String일 수 있습니다. 이 경우, separator는 input String의 beginning 또는 end에 있는 empty substring과 match하지 않으며, previous separator match의 end에 있는 empty substring과도 match하지 않습니다. separator가 empty String이면, String은 individual code unit elements로 split up됩니다; result array의 length는 String의 length와 equal하고, 각 substring은 one code unit을 contain합니다.

this value가 empty String이거나 empty String으로 converts되면, result는 separator가 empty String과 match할 수 있는지 여부에 depends합니다. match할 수 있으면, result array는 no elements를 contain합니다. Otherwise, result array는 one element를 contain하며, 이는 empty String입니다.

separatorundefined이면, result array는 just one String을 contain하며, 이는 this value(String으로 converted됨)입니다. limitundefined가 아니면, output array는 no more than limit elements를 contain하도록 truncated됩니다.

Note 2

이 method는 intentionally generic입니다; this value가 String object일 것을 require하지 않습니다. 따라서 method로 사용하기 위해 other kinds of objects에 transferred될 수 있습니다.

22.1.3.24 String.prototype.startsWith ( searchString [ , position ] )

이 method는 called될 때 following steps를 수행합니다:

  1. thisValuethis value로 둔다.
  2. RequireObjectCoercible(thisValue)를 수행한다.
  3. string을 ? ToString(thisValue)로 둔다.
  4. isRegexp를 ? IsRegExp(searchString)로 둔다.
  5. isRegexptrue이면, TypeError exception을 throw한다.
  6. searchString을 ? ToString(searchString)으로 설정한다.
  7. lengthstring의 length로 둔다.
  8. positionundefined이면 position을 0으로 설정한다; 그렇지 않으면 position을 ? ToIntegerOrInfinity(position)로 설정한다.
  9. startposition을 0과 length 사이로 clamping한 result로 둔다.
  10. searchLengthsearchString의 length로 둔다.
  11. searchLength = 0이면, true를 반환한다.
  12. endstart + searchLength로 둔다.
  13. end > length이면, false를 반환한다.
  14. substringstringstart부터 end까지의 substring으로 둔다.
  15. substringsearchString이면, true를 반환한다.
  16. false를 반환한다.
Note 1

first argument가 RegExp이면 exception을 throw하는 것은, future editions가 such argument values를 allow하는 extensions를 define할 수 있도록 specified되었습니다.

Note 2

이 method는 intentionally generic입니다; this value가 String object일 것을 require하지 않습니다. 따라서 method로 사용하기 위해 other kinds of objects에 transferred될 수 있습니다.

22.1.3.25 String.prototype.substring ( start, end )

이 method는 this object를 String으로 converting한 result의 substring을 반환하며, String의 index start에서 start하여 index end 전까지(or endundefined이면 String의 end까지) running합니다. result는 String value이며, String object가 아닙니다.

either argument가 NaN이거나 negative이면, zero로 replaced됩니다; either argument가 String의 length보다 strictly greater이면, String의 length로 replaced됩니다.

startend보다 strictly greater이면, 둘은 swapped됩니다.

called될 때 following steps를 수행합니다:

  1. thisValuethis value로 둔다.
  2. RequireObjectCoercible(thisValue)를 수행한다.
  3. string을 ? ToString(thisValue)로 둔다.
  4. lengthstring의 length로 둔다.
  5. intStart를 ? ToIntegerOrInfinity(start)로 둔다.
  6. endundefined이면 intEndlength로 둔다; 그렇지 않으면 intEnd를 ? ToIntegerOrInfinity(end)로 둔다.
  7. finalStartintStart를 0과 length 사이로 clamping한 result로 둔다.
  8. finalEndintEnd를 0과 length 사이로 clamping한 result로 둔다.
  9. frommin(finalStart, finalEnd)로 둔다.
  10. tomax(finalStart, finalEnd)로 둔다.
  11. stringfrom부터 to까지의 substring을 반환한다.
Note

이 method는 intentionally generic입니다; this value가 String object일 것을 require하지 않습니다. 따라서 method로 사용하기 위해 other kinds of objects에 transferred될 수 있습니다.

22.1.3.26 String.prototype.toLocaleLowerCase ( [ reserved1 [ , reserved2 ] ] )

ECMA-402 Internationalization API를 include하는 ECMAScript implementation은 ECMA-402 specification에 specified된 대로 이 method를 implement해야 합니다. ECMAScript implementation이 ECMA-402 API를 include하지 않으면 이 method의 following specification이 사용됩니다:

이 method는 6.1.4에 described된 대로 String value를 UTF-16 encoded code points의 sequence로 interpret합니다.

toLowerCase와 exactly same하게 works하지만, host environment의 current locale의 conventions와 corresponding하는 locale-sensitive result를 yield하도록 intended된다는 점이 다릅니다. regular Unicode case mappings와 해당 language의 rules가 conflict하는 few cases(예: Turkish)에서만 difference가 있을 것입니다.

이 method에 대한 optional parameters의 meaning은 ECMA-402 specification에 defined되어 있습니다; ECMA-402 support를 include하지 않는 implementations는 those parameter positions를 anything else에 사용해서는 안 됩니다.

Note

이 method는 intentionally generic입니다; this value가 String object일 것을 require하지 않습니다. 따라서 method로 사용하기 위해 other kinds of objects에 transferred될 수 있습니다.

22.1.3.27 String.prototype.toLocaleUpperCase ( [ reserved1 [ , reserved2 ] ] )

ECMA-402 Internationalization API를 include하는 ECMAScript implementation은 ECMA-402 specification에 specified된 대로 이 method를 implement해야 합니다. ECMAScript implementation이 ECMA-402 API를 include하지 않으면 이 method의 following specification이 사용됩니다:

이 method는 6.1.4에 described된 대로 String value를 UTF-16 encoded code points의 sequence로 interpret합니다.

toUpperCase와 exactly same하게 works하지만, host environment의 current locale의 conventions와 corresponding하는 locale-sensitive result를 yield하도록 intended된다는 점이 다릅니다. regular Unicode case mappings와 해당 language의 rules가 conflict하는 few cases(예: Turkish)에서만 difference가 있을 것입니다.

이 method에 대한 optional parameters의 meaning은 ECMA-402 specification에 defined되어 있습니다; ECMA-402 support를 include하지 않는 implementations는 those parameter positions를 anything else에 사용해서는 안 됩니다.

Note

이 method는 intentionally generic입니다; this value가 String object일 것을 require하지 않습니다. 따라서 method로 사용하기 위해 other kinds of objects에 transferred될 수 있습니다.

22.1.3.28 String.prototype.toLowerCase ( )

이 method는 6.1.4에 described된 대로 String value를 UTF-16 encoded code points의 sequence로 interpret합니다.

called될 때 following steps를 수행합니다:

  1. thisValuethis value로 둔다.
  2. RequireObjectCoercible(thisValue)를 수행한다.
  3. string을 ? ToString(thisValue)로 둔다.
  4. sTextStringToCodePoints(string)로 둔다.
  5. lowerText를 Unicode Default Case Conversion algorithm에 따라 toLowercase(sText)로 둔다.
  6. lowercaseStringCodePointsToString(lowerText)로 둔다.
  7. lowercaseString을 반환한다.

result는 Unicode Character Database의 locale-insensitive case mappings에 따라 derived되어야 합니다(이는 file UnicodeData.txt뿐만 아니라 accompanying file SpecialCasing.txt 안의 모든 locale-insensitive mappings도 explicitly include합니다).

Note 1

some code points의 case mapping은 multiple code points를 produce할 수 있습니다. 이 경우 result String은 source String과 same length가 아닐 수 있습니다. toUpperCasetoLowerCase 모두 context-sensitive behaviour를 가지므로, methods는 symmetrical하지 않습니다. In other words, s.toUpperCase().toLowerCase()는 necessarily s.toLowerCase()와 equal하지 않습니다.

Note 2

이 method는 intentionally generic입니다; this value가 String object일 것을 require하지 않습니다. 따라서 method로 사용하기 위해 other kinds of objects에 transferred될 수 있습니다.

22.1.3.29 String.prototype.toString ( )

이 method는 called될 때 following steps를 수행합니다:

  1. ThisStringValue(this value)를 반환한다.
Note

String object의 경우, 이 method는 valueOf method와 same thing을 return합니다.

22.1.3.30 String.prototype.toUpperCase ( )

이 method는 6.1.4에 described된 대로 String value를 UTF-16 encoded code points의 sequence로 interpret합니다.

String.prototype.toLowerCase와 exactly same way로 behave하지만, String이 Unicode Default Case Conversion의 toUppercase algorithm을 사용하여 mapped된다는 점이 다릅니다.

Note

이 method는 intentionally generic입니다; this value가 String object일 것을 require하지 않습니다. 따라서 method로 사용하기 위해 other kinds of objects에 transferred될 수 있습니다.

22.1.3.31 String.prototype.toWellFormed ( )

이 method는 surrogate pair의 part가 아닌 모든 leading surrogatestrailing surrogates가 U+FFFD (REPLACEMENT CHARACTER)로 replaced된 이 object의 String representation을 반환합니다.

called될 때 following steps를 수행합니다:

  1. thisValuethis value로 둔다.
  2. RequireObjectCoercible(thisValue)를 수행한다.
  3. string을 ? ToString(thisValue)로 둔다.
  4. stringLengthstring의 length로 둔다.
  5. k를 0으로 둔다.
  6. result를 empty String으로 둔다.
  7. Repeat, while k < stringLength,
    1. codePointCodePointAt(string, k)로 둔다.
    2. codePoint.[[IsUnpairedSurrogate]]true이면, 다음을 수행한다.
      1. resultresult와 0xFFFD (REPLACEMENT CHARACTER)의 string-concatenation으로 설정한다.
    3. 그렇지 않으면,
      1. resultresultUTF16EncodeCodePoint(codePoint.[[CodePoint]])의 string-concatenation으로 설정한다.
    4. kk + codePoint.[[CodeUnitCount]]로 설정한다.
  8. result를 반환한다.

22.1.3.32 String.prototype.trim ( )

이 method는 6.1.4에 described된 대로 String value를 UTF-16 encoded code points의 sequence로 interpret합니다.

called될 때 following steps를 수행합니다:

  1. thisValuethis value로 둔다.
  2. TrimString(thisValue, start+end)를 반환한다.
Note

이 method는 intentionally generic입니다; this value가 String object일 것을 require하지 않습니다. 따라서 method로 사용하기 위해 other kinds of objects에 transferred될 수 있습니다.

22.1.3.32.1 TrimString ( arg, where )

The abstract operation TrimString takes arguments arg (an ECMAScript language value) and where (start, end, or start+end) and returns either a normal completion containing a String or a throw completion. 6.1.4에 described된 대로 arg를 UTF-16 encoded code points의 sequence로 interpret합니다. It performs the following steps when called:

  1. RequireObjectCoercible(arg)를 수행한다.
  2. string을 ? ToString(arg)로 둔다.
  3. wherestart이면, 다음을 수행한다.
    1. trimmedString을 leading white space가 removed된 string의 copy인 String value로 둔다.
  4. 그렇지 않고 whereend이면, 다음을 수행한다.
    1. trimmedString을 trailing white space가 removed된 string의 copy인 String value로 둔다.
  5. 그렇지 않으면,
    1. Assert: wherestart+end이다.
    2. trimmedString을 leading 및 trailing white space가 모두 removed된 string의 copy인 String value로 둔다.
  6. trimmedString을 반환한다.

white space의 definition은 WhiteSpaceLineTerminator의 union입니다. Unicode code point가 Unicode general category “Space_Separator” (“Zs”) 안에 있는지 determining할 때, code unit sequences는 6.1.4에 specified된 대로 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합니다.

called될 때 following steps를 수행합니다:

  1. stringthis value로 둔다.
  2. TrimString(string, end)를 반환한다.
Note

이 method는 intentionally generic입니다; this value가 String object일 것을 require하지 않습니다. 따라서 method로 사용하기 위해 other kinds of objects에 transferred될 수 있습니다.

22.1.3.34 String.prototype.trimStart ( )

이 method는 6.1.4에 described된 대로 String value를 UTF-16 encoded code points의 sequence로 interpret합니다.

called될 때 following steps를 수행합니다:

  1. stringthis value로 둔다.
  2. TrimString(string, start)를 반환한다.
Note

이 method는 intentionally generic입니다; this value가 String object일 것을 require하지 않습니다. 따라서 method로 사용하기 위해 other kinds of objects에 transferred될 수 있습니다.

22.1.3.35 String.prototype.valueOf ( )

이 method는 called될 때 following steps를 수행합니다:

  1. ThisStringValue(this value)를 반환한다.

22.1.3.35.1 ThisStringValue ( arg )

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

  1. arg가 String이면, arg를 반환한다.
  2. arg가 Object이고 arg[[StringData]] internal slot을 가지면, 다음을 수행한다.
    1. stringarg.[[StringData]]로 둔다.
    2. Assert: string은 String이다.
    3. string을 반환한다.
  3. TypeError exception을 throw한다.

22.1.3.36 String.prototype [ %Symbol.iterator% ] ( )

이 method는 String value의 code points를 iterate하고, 각 code point를 String value로 반환하는 iterator object를 반환합니다.

called될 때 following steps를 수행합니다:

  1. stringthis value로 둔다.
  2. RequireObjectCoercible(string)를 수행한다.
  3. string을 ? ToString(string)으로 설정한다.
  4. string을 capture하고 called될 때 following steps를 수행하는, parameters가 없는 새 Abstract Closure closure를 둔다:
    1. lengthstring의 length로 둔다.
    2. position을 0으로 둔다.
    3. Repeat, while position < length,
      1. codePointCodePointAt(string, position)로 둔다.
      2. nextIndexposition + codePoint.[[CodeUnitCount]]로 둔다.
      3. resultStringstringposition부터 nextIndex까지의 substring으로 둔다.
      4. positionnextIndex로 설정한다.
      5. GeneratorYield(CreateIteratorResultObject(resultString, false))를 수행한다.
    4. NormalCompletion(unused)를 반환한다.
  5. CreateIteratorFromClosure(closure, "%StringIteratorPrototype%", %StringIteratorPrototype%)를 반환한다.

이 method의 "name" property의 value는 "[Symbol.iterator]"입니다.

22.1.4 Properties of String Instances

String instances는 String exotic objects이며 such objects에 대해 specified된 internal methods를 가집니다. String instances는 String prototype object에서 properties를 inherit합니다. String instances는 또한 [[StringData]] internal slot을 가집니다. [[StringData]] internal slot은 이 String object가 represented하는 String value입니다.

String instances는 "length" property와 integer-indexed names를 가진 enumerable properties의 set을 가집니다.

22.1.4.1 length

이 String object가 represented하는 String value 안의 elements 수입니다.

String object가 initialized되면, 이 property는 unchanging입니다. 이는 attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }를 가집니다.

22.1.5 String Iterator Objects

String Iterator는 some specific String instance object에 대한 specific iteration을 represent하는 object입니다. String Iterator objects를 위한 named constructor는 없습니다. 대신, String Iterator objects는 String instance objects의 certain methods를 calling하여 created됩니다.

22.1.5.1 The %StringIteratorPrototype% Object

%StringIteratorPrototype% object는:

22.1.5.1.1 %StringIteratorPrototype%.next ( )

  1. GeneratorResume(this value, empty, "%StringIteratorPrototype%")를 반환한다.

22.1.5.1.2 %StringIteratorPrototype% [ %Symbol.toStringTag% ]

%Symbol.toStringTag% property의 initial value는 String value "String Iterator"입니다.

이 property는 attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }를 가집니다.

22.2 RegExp (Regular Expression) Objects

RegExp object는 regular expression과 associated flags를 contain합니다.

Note

regular expressions의 form과 functionality는 Perl 5 programming language의 regular expression facility를 model로 합니다.

22.2.1 Patterns

RegExp constructor는 input pattern String에 following grammar를 apply합니다. 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는 otherwise corresponding \u HexTrailSurrogate가 없게 될 nearest possible u HexLeadSurrogate와 associated되어야 합니다.

HexLeadSurrogate :: Hex4Digits but only if the MV of Hex4Digits is in the inclusive interval from 0xD800 to 0xDBFF HexTrailSurrogate :: Hex4Digits but only if the MV of Hex4Digits is in the inclusive interval from 0xDC00 to 0xDFFF HexNonSurrogate :: Hex4Digits but only if the MV of Hex4Digits is not in the inclusive interval from 0xD800 to 0xDFFF IdentityEscape[UnicodeMode] :: [+UnicodeMode] SyntaxCharacter [+UnicodeMode] / [~UnicodeMode] SourceCharacter but not UnicodeIDContinue DecimalEscape :: NonZeroDigit DecimalDigits[~Sep]opt [lookahead ∉ DecimalDigit] CharacterClassEscape[UnicodeMode] :: d D s S w W [+UnicodeMode] p{ UnicodePropertyValueExpression } [+UnicodeMode] P{ UnicodePropertyValueExpression } UnicodePropertyValueExpression :: UnicodePropertyName = UnicodePropertyValue LoneUnicodePropertyNameOrValue UnicodePropertyName :: UnicodePropertyNameCharacters UnicodePropertyNameCharacters :: UnicodePropertyNameCharacter UnicodePropertyNameCharactersopt UnicodePropertyValue :: UnicodePropertyValueCharacters LoneUnicodePropertyNameOrValue :: UnicodePropertyValueCharacters UnicodePropertyValueCharacters :: UnicodePropertyValueCharacter UnicodePropertyValueCharactersopt UnicodePropertyValueCharacter :: UnicodePropertyNameCharacter DecimalDigit UnicodePropertyNameCharacter :: AsciiLetter _ CharacterClass[UnicodeMode, UnicodeSetsMode] :: [ [lookahead ≠ ^] ClassContents[?UnicodeMode, ?UnicodeSetsMode] ] [^ ClassContents[?UnicodeMode, ?UnicodeSetsMode] ] ClassContents[UnicodeMode, UnicodeSetsMode] :: [empty] [~UnicodeSetsMode] NonemptyClassRanges[?UnicodeMode] [+UnicodeSetsMode] ClassSetExpression NonemptyClassRanges[UnicodeMode] :: ClassAtom[?UnicodeMode] ClassAtom[?UnicodeMode] NonemptyClassRangesNoDash[?UnicodeMode] ClassAtom[?UnicodeMode] - ClassAtom[?UnicodeMode] ClassContents[?UnicodeMode, ~UnicodeSetsMode] NonemptyClassRangesNoDash[UnicodeMode] :: ClassAtom[?UnicodeMode] ClassAtomNoDash[?UnicodeMode] NonemptyClassRangesNoDash[?UnicodeMode] ClassAtomNoDash[?UnicodeMode] - ClassAtom[?UnicodeMode] ClassContents[?UnicodeMode, ~UnicodeSetsMode] ClassAtom[UnicodeMode] :: - ClassAtomNoDash[?UnicodeMode] ClassAtomNoDash[UnicodeMode] :: SourceCharacter but not one of \ or ] or - \ ClassEscape[?UnicodeMode] ClassEscape[UnicodeMode] :: b [+UnicodeMode] - CharacterClassEscape[?UnicodeMode] CharacterEscape[?UnicodeMode] ClassSetExpression :: ClassUnion ClassIntersection ClassSubtraction ClassUnion :: ClassSetRange ClassUnionopt ClassSetOperand ClassUnionopt ClassIntersection :: ClassSetOperand && [lookahead ≠ &] ClassSetOperand ClassIntersection && [lookahead ≠ &] ClassSetOperand ClassSubtraction :: ClassSetOperand -- ClassSetOperand ClassSubtraction -- ClassSetOperand ClassSetRange :: ClassSetCharacter - ClassSetCharacter ClassSetOperand :: NestedClass ClassStringDisjunction ClassSetCharacter NestedClass :: [ [lookahead ≠ ^] ClassContents[+UnicodeMode, +UnicodeSetsMode] ] [^ ClassContents[+UnicodeMode, +UnicodeSetsMode] ] \ CharacterClassEscape[+UnicodeMode] Note 1

여기서 first two lines는 CharacterClass와 equivalent합니다.

ClassStringDisjunction :: \q{ ClassStringDisjunctionContents } ClassStringDisjunctionContents :: ClassString ClassString | ClassStringDisjunctionContents ClassString :: [empty] NonEmptyClassString NonEmptyClassString :: ClassSetCharacter NonEmptyClassStringopt ClassSetCharacter :: [lookahead ∉ ClassSetReservedDoublePunctuator] SourceCharacter but not ClassSetSyntaxCharacter \ CharacterEscape[+UnicodeMode] \ ClassSetReservedPunctuator \b ClassSetReservedDoublePunctuator :: one of && !! ## $$ %% ** ++ ,, .. :: ;; << == >> ?? @@ ^^ `` ~~ ClassSetSyntaxCharacter :: one of ( ) [ ] { } / - \ | ClassSetReservedPunctuator :: one of & - ! # % , : ; < = > @ ` ~ Note 2

이 section의 number of productions는 B.1.2 section에서 alternative definitions로 given됩니다.

22.2.1.1 Static Semantics: Early Errors

Note

이 section은 B.1.2.1에서 amended됩니다.

Pattern :: Disjunction QuantifierPrefix :: { DecimalDigits , DecimalDigits } Atom :: (? RegularExpressionModifiers : Disjunction ) Atom :: (? RegularExpressionModifiers - RegularExpressionModifiers : Disjunction ) AtomEscape :: k GroupName AtomEscape :: DecimalEscape NonemptyClassRanges :: ClassAtom - ClassAtom ClassContents NonemptyClassRangesNoDash :: ClassAtomNoDash - ClassAtom ClassContents RegExpIdentifierStart :: \ RegExpUnicodeEscapeSequence RegExpIdentifierStart :: UnicodeLeadSurrogate UnicodeTrailSurrogate RegExpIdentifierPart :: \ RegExpUnicodeEscapeSequence RegExpIdentifierPart :: UnicodeLeadSurrogate UnicodeTrailSurrogate UnicodePropertyValueExpression :: UnicodePropertyName = UnicodePropertyValue
  • UnicodePropertyName이 match한 source text가 Table 65의 “Property name and aliases” column에 listed된 Unicode property name 또는 property alias가 아니면 Syntax Error입니다.
  • UnicodePropertyValue가 match한 source text가 UnicodePropertyName이 match한 source text가 given하는 Unicode property 또는 property alias에 대한 property value 또는 property value alias로 PropertyValueAliases.txt에 listed되어 있지 않으면 Syntax Error입니다.
UnicodePropertyValueExpression :: LoneUnicodePropertyNameOrValue
  • LoneUnicodePropertyNameOrValue가 match한 source text가 PropertyValueAliases.txt에 listed된 General_Category (gc) property의 Unicode property value 또는 property value alias가 아니고, Table 66의 “Property name and aliases” column에 listed된 binary property 또는 binary property alias도 아니며, Table 67의 “Property name” column에 listed된 binary property of strings도 아니면 Syntax Error입니다.
  • enclosing Pattern[UnicodeSetsMode] parameter를 가지지 않고 LoneUnicodePropertyNameOrValue가 match한 source text가 Table 67의 “Property name” column에 listed된 binary property of strings이면 Syntax Error입니다.
CharacterClassEscape :: P{ UnicodePropertyValueExpression } CharacterClass :: [^ ClassContents ] NestedClass :: [^ ClassContents ] ClassSetRange :: ClassSetCharacter - ClassSetCharacter

22.2.1.2 Static Semantics: CountLeftCapturingParensWithin ( parseNode )

The abstract operation CountLeftCapturingParensWithin takes argument parseNode (a Parse Node) and returns a non-negative integer. parseNode 안의 left-capturing parentheses 수를 반환합니다. left-capturing parenthesis Atom :: ( GroupSpecifieropt Disjunction ) production의 ( terminal에 의해 matched되는 any ( pattern character입니다.

Note

이 section은 B.1.2.2에서 amended됩니다.

It performs the following steps when called:

  1. Assert: parseNodethe RegExp Pattern grammar 안의 production의 instance이다.
  2. parseNode 안에 contained된 Atom :: ( GroupSpecifieropt Disjunction ) Parse Nodes의 수를 반환한다.

22.2.1.3 Static Semantics: CountLeftCapturingParensBefore ( parseNode )

The abstract operation CountLeftCapturingParensBefore takes argument parseNode (a Parse Node) and returns a non-negative integer. enclosing pattern 안에서 parseNode의 left에 occur하는 left-capturing parentheses 수를 반환합니다.

Note

이 section은 B.1.2.2에서 amended됩니다.

It performs the following steps when called:

  1. Assert: parseNodethe RegExp Pattern grammar 안의 production의 instance이다.
  2. patternparseNode를 containing하는 Pattern으로 둔다.
  3. pattern 안에 contained된 Atom :: ( GroupSpecifieropt Disjunction ) Parse NodesparseNode before에 occur하거나 parseNode를 contain하는 것들의 수를 반환한다.

22.2.1.4 Static Semantics: MightBothParticipate ( x, y )

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

  1. Assert: xy는 same enclosing Pattern을 가진다.
  2. enclosing Pattern Disjunction :: Alternative | Disjunction Parse Node를 contain하고, xAlternative 안에 contained되고 y가 derived Disjunction 안에 contained되거나, x가 derived Disjunction 안에 contained되고 yAlternative 안에 contained되면, false를 반환한다.
  3. true를 반환한다.

22.2.1.5 Static Semantics: CapturingGroupNumber

The syntax-directed operation CapturingGroupNumber takes no arguments and returns a positive integer.

Note

이 section은 B.1.2.1에서 amended됩니다.

It is defined piecewise over the following productions:

DecimalEscape :: NonZeroDigit
  1. NonZeroDigit의 MV를 반환한다.
DecimalEscape :: NonZeroDigit DecimalDigits
  1. nDecimalDigits 안의 code points 수로 둔다.
  2. (NonZeroDigit의 MV × 10n plus DecimalDigits의 MV)를 반환한다.

NonZeroDigit의 MV” 및 “DecimalDigits의 MV”의 definitions는 12.9.3에 있습니다.

22.2.1.6 Static Semantics: IsCharacterClass

The syntax-directed operation IsCharacterClass takes no arguments and returns a Boolean.

Note

이 section은 B.1.2.3에서 amended됩니다.

It is defined piecewise over the following productions:

ClassAtom :: - ClassAtomNoDash :: SourceCharacter but not one of \ or ] or - ClassEscape :: b - CharacterEscape
  1. false를 반환한다.
ClassEscape :: CharacterClassEscape
  1. true를 반환한다.

22.2.1.7 Static Semantics: CharacterValue

The syntax-directed operation CharacterValue takes no arguments and returns a non-negative integer.

Note 1

이 section은 B.1.2.4에서 amended됩니다.

It is defined piecewise over the following productions:

ClassAtom :: -
  1. U+002D (HYPHEN-MINUS)의 numeric value를 반환한다.
ClassAtomNoDash :: SourceCharacter but not one of \ or ] or -
  1. codePointSourceCharacter가 matched한 code point로 둔다.
  2. codePoint의 numeric value를 반환한다.
ClassEscape :: b
  1. U+0008 (BACKSPACE)의 numeric value를 반환한다.
ClassEscape :: -
  1. U+002D (HYPHEN-MINUS)의 numeric value를 반환한다.
CharacterEscape :: ControlEscape
  1. Table 63에 따라 numeric value를 반환한다.
Table 63: ControlEscape Code Point Values
ControlEscape Numeric Value Code Point Unicode Name Symbol
t 9 U+0009 CHARACTER TABULATION <HT>
n 10 U+000A LINE FEED (LF) <LF>
v 11 U+000B LINE TABULATION <VT>
f 12 U+000C FORM FEED (FF) <FF>
r 13 U+000D CARRIAGE RETURN (CR) <CR>
CharacterEscape :: c AsciiLetter
  1. codePointAsciiLetter가 matched한 code point로 둔다.
  2. icodePoint의 numeric value로 둔다.
  3. i를 32로 dividing한 remainder를 반환한다.
CharacterEscape :: 0 [lookahead ∉ DecimalDigit]
  1. U+0000 (NULL)의 numeric value를 반환한다.
Note 2

\0은 <NUL> character를 represent하며 decimal digit이 follow될 수 없습니다.

CharacterEscape :: HexEscapeSequence
  1. HexEscapeSequence의 MV를 반환한다.
RegExpUnicodeEscapeSequence :: u HexLeadSurrogate \u HexTrailSurrogate
  1. leadHexLeadSurrogateCharacterValue로 둔다.
  2. trailHexTrailSurrogateCharacterValue로 둔다.
  3. codePointUTF16SurrogatePairToCodePoint(lead, trail)로 둔다.
  4. codePoint의 numeric value를 반환한다.
RegExpUnicodeEscapeSequence :: u Hex4Digits
  1. Hex4Digits의 MV를 반환한다.
RegExpUnicodeEscapeSequence :: u{ CodePoint }
  1. CodePoint의 MV를 반환한다.
HexLeadSurrogate :: Hex4Digits HexTrailSurrogate :: Hex4Digits HexNonSurrogate :: Hex4Digits
  1. Hex4Digits의 MV를 반환한다.
CharacterEscape :: IdentityEscape
  1. codePointIdentityEscape가 matched한 code point로 둔다.
  2. codePoint의 numeric value를 반환한다.
ClassSetCharacter :: SourceCharacter but not ClassSetSyntaxCharacter
  1. codePointSourceCharacter가 matched한 code point로 둔다.
  2. codePoint의 numeric value를 반환한다.
ClassSetCharacter :: \ ClassSetReservedPunctuator
  1. codePointClassSetReservedPunctuator가 matched한 code point로 둔다.
  2. codePoint의 numeric value를 반환한다.
ClassSetCharacter :: \b
  1. U+0008 (BACKSPACE)의 numeric value를 반환한다.

22.2.1.8 Static Semantics: MayContainStrings

The syntax-directed operation MayContainStrings takes no arguments and returns a Boolean. It is defined piecewise over the following productions:

CharacterClassEscape :: d D s S w W P{ UnicodePropertyValueExpression } UnicodePropertyValueExpression :: UnicodePropertyName = UnicodePropertyValue NestedClass :: [^ ClassContents ] ClassContents :: [empty] NonemptyClassRanges ClassSetOperand :: ClassSetCharacter
  1. false를 반환한다.
UnicodePropertyValueExpression :: LoneUnicodePropertyNameOrValue
  1. LoneUnicodePropertyNameOrValue가 match한 source text가 Table 67의 “Property name” column에 listed된 binary property of strings이면, true를 반환한다.
  2. false를 반환한다.
ClassUnion :: ClassSetRange ClassUnionopt
  1. ClassUnion이 present하면, ClassUnionMayContainStrings를 반환한다.
  2. false를 반환한다.
ClassUnion :: ClassSetOperand ClassUnionopt
  1. ClassSetOperandMayContainStringstrue이면, true를 반환한다.
  2. ClassUnion이 present하면, ClassUnionMayContainStrings를 반환한다.
  3. false를 반환한다.
ClassIntersection :: ClassSetOperand && ClassSetOperand
  1. first ClassSetOperandMayContainStringsfalse이면, false를 반환한다.
  2. second ClassSetOperandMayContainStringsfalse이면, false를 반환한다.
  3. true를 반환한다.
ClassIntersection :: ClassIntersection && ClassSetOperand
  1. ClassIntersectionMayContainStringsfalse이면, false를 반환한다.
  2. ClassSetOperandMayContainStringsfalse이면, false를 반환한다.
  3. true를 반환한다.
ClassSubtraction :: ClassSetOperand -- ClassSetOperand
  1. first ClassSetOperandMayContainStrings를 반환한다.
ClassSubtraction :: ClassSubtraction -- ClassSetOperand
  1. ClassSubtractionMayContainStrings를 반환한다.
ClassStringDisjunctionContents :: ClassString | ClassStringDisjunctionContents
  1. ClassStringMayContainStringstrue이면, true를 반환한다.
  2. ClassStringDisjunctionContentsMayContainStrings를 반환한다.
ClassString :: [empty]
  1. true를 반환한다.
ClassString :: NonEmptyClassString
  1. NonEmptyClassStringMayContainStrings를 반환한다.
NonEmptyClassString :: ClassSetCharacter NonEmptyClassStringopt
  1. NonEmptyClassString이 present하면, true를 반환한다.
  2. false를 반환한다.

22.2.1.9 Static Semantics: GroupSpecifiersThatMatch ( thisGroupName )

The abstract operation GroupSpecifiersThatMatch takes argument thisGroupName (a GroupName Parse Node) and returns a List of GroupSpecifier Parse Nodes. It performs the following steps when called:

  1. namethisGroupNameCapturingGroupName으로 둔다.
  2. patternthisGroupName을 containing하는 Pattern으로 둔다.
  3. result를 새 empty List로 둔다.
  4. pattern이 contain하는 각 GroupSpecifier groupSpecifier에 대해, 다음을 수행한다.
    1. groupSpecifierCapturingGroupNamename이면, 다음을 수행한다.
      1. groupSpecifierresult에 append한다.
  5. result를 반환한다.

22.2.1.10 Static Semantics: CapturingGroupName

The syntax-directed operation CapturingGroupName takes no arguments and returns a String. It is defined piecewise over the following productions:

GroupName :: < RegExpIdentifierName >
  1. idTextUnescapedRegExpIdentifierNameRegExpIdentifierCodePoints로 둔다.
  2. CodePointsToString(idTextUnescaped)을 반환한다.

22.2.1.11 Static Semantics: RegExpIdentifierCodePoints

The syntax-directed operation RegExpIdentifierCodePoints takes no arguments and returns a List of code points. It is defined piecewise over the following productions:

RegExpIdentifierName :: RegExpIdentifierStart
  1. codePointRegExpIdentifierStartRegExpIdentifierCodePoint로 둔다.
  2. « codePoint »를 반환한다.
RegExpIdentifierName :: RegExpIdentifierName RegExpIdentifierPart
  1. codePoints를 파생된 RegExpIdentifierNameRegExpIdentifierCodePoints라고 하자.
  2. codePointRegExpIdentifierPartRegExpIdentifierCodePoint라고 하자.
  3. codePoints와 « codePoint »의 list-concatenation을 반환한다.

22.2.1.12 Static Semantics: RegExpIdentifierCodePoint

The syntax-directed operation RegExpIdentifierCodePoint takes no arguments and returns a code point. It is defined piecewise over the following productions:

RegExpIdentifierStart :: IdentifierStartChar
  1. IdentifierStartChar가 matched한 code point를 반환한다.
RegExpIdentifierPart :: IdentifierPartChar
  1. IdentifierPartChar가 matched한 code point를 반환한다.
RegExpIdentifierStart :: \ RegExpUnicodeEscapeSequence RegExpIdentifierPart :: \ RegExpUnicodeEscapeSequence
  1. numeric value가 RegExpUnicodeEscapeSequenceCharacterValue인 code point를 반환한다.
RegExpIdentifierStart :: UnicodeLeadSurrogate UnicodeTrailSurrogate RegExpIdentifierPart :: UnicodeLeadSurrogate UnicodeTrailSurrogate
  1. lead를 numeric value가 UnicodeLeadSurrogate가 matched한 code point의 numeric value인 code unit으로 둔다.
  2. trail을 numeric value가 UnicodeTrailSurrogate가 matched한 code point의 numeric value인 code unit으로 둔다.
  3. UTF16SurrogatePairToCodePoint(lead, trail)을 반환한다.

22.2.2 Pattern Semantics

regular expression pattern은 아래에 described된 process를 사용하여 Abstract Closure로 converted됩니다. implementation은 results가 same인 한, below에 listed된 것보다 more efficient algorithms를 use할 것이 encouraged됩니다. Abstract Closure는 RegExp object의 [[RegExpMatcher]] internal slot의 value로 사용됩니다.

Pattern은 its associated flags가 uv도 contain하지 않으면 BMP pattern입니다. Otherwise, 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를 describing하는 context에서 “character”는 single 16-bit Unicode BMP code point를 의미합니다. Unicode pattern의 behaviour를 describing하는 context에서 “character”는 UTF-16 encoded code point(6.1.4)를 의미합니다. 어느 context에서든, “character value”는 corresponding non-encoded code point의 numeric value를 의미합니다.

Pattern의 syntax 및 semantics는 Pattern의 source text가 SourceCharacter values의 List였던 것처럼 defined되며, 각 SourceCharacter는 Unicode code point에 corresponding합니다. BMP pattern이 non-BMP SourceCharacter를 contain하면 전체 pattern은 UTF-16을 사용하여 encoded되고, 그 encoding의 individual code units가 List의 elements로 사용됩니다.

Note

예를 들어, source text에서 single non-BMP character U+1D11E (MUSICAL SYMBOL G CLEF)로 expressed된 pattern을 consider하십시오. Unicode pattern으로 interpreted되면, 이는 single code point U+1D11E로 구성된 single element(character) List가 됩니다. However, BMP pattern으로 interpreted되면, 먼저 UTF-16 encoded되어 code units 0xD834 및 0xDD1E로 구성된 two element List를 produce합니다.

Patterns는 ECMAScript String values로 RegExp constructor에 passed되며, 그 안에서 non-BMP characters는 UTF-16 encoded됩니다. 예를 들어, String value로 expressed된 single character MUSICAL SYMBOL G CLEF pattern은 elements가 code units 0xD834 및 0xDD1E인 length 2의 String입니다. 따라서 이를 two pattern characters로 구성된 BMP pattern으로 process하기 위해서는 string의 further translation이 필요하지 않습니다. However, Unicode pattern으로 process하기 위해서는 sole element가 single pattern character, 즉 code point U+1D11E인 List를 producing하는 데 UTF16SurrogatePairToCodePoint를 사용해야 합니다.

implementation은 such translations를 실제로 UTF-16으로 또는 UTF-16으로부터 perform하지 않을 수 있지만, 이 specification의 semantics는 pattern matching의 result가 such translations가 performed된 것과 같아야 함을 require합니다.

22.2.2.1 Notation

아래 descriptions는 다음 internal data structures를 사용합니다:

  • CharSetElement는 following two entities 중 하나입니다:
    • regexpRecord.[[UnicodeSets]]false이면, CharSetElement는 위 Pattern Semantics의 sense에서 character입니다.
    • regexpRecord.[[UnicodeSets]]true이면, CharSetElement는 elements가 위 Pattern Semantics의 sense에서 characters인 sequence입니다. 이는 empty sequence, one character의 sequences, 및 more than one character의 sequences를 include합니다. convenience를 위해, 이러한 kind의 CharSetElements로 작업할 때 individual character는 one character의 sequence와 interchangeably treated됩니다.
  • CharSet은 CharSetElements의 mathematical set입니다.
  • CaptureRange는 capture에 included된 characters의 range를 represent하는 Record { [[StartIndex]], [[EndIndex]] }이며, 여기서 [[StartIndex]]input 안의 range의 start index(inclusive)를 representing하는 integer이고, [[EndIndex]]input 안의 range의 end index(exclusive)를 representing하는 integer입니다. any CaptureRange에 대해, these indices는 [[StartIndex]][[EndIndex]]라는 invariant를 satisfy해야 합니다.
  • MatchStateRecord { [[Input]], [[EndIndex]], [[Captures]] }이며, 여기서 [[Input]]은 matched되는 String을 representing하는 characters의 List이고, [[EndIndex]]integer이며, [[Captures]]는 pattern 안의 각 left-capturing parenthesis에 대해 하나씩 values의 List입니다. MatchStates는 regular expression matching algorithms에서 partial match states를 represent하는 데 사용됩니다. [[EndIndex]]는 지금까지 pattern에 의해 matched된 last input character의 index plus one이며, [[Captures]]는 capturing parentheses의 results를 hold합니다. [[Captures]]nth element는 nth set of capturing parentheses에 의해 captured된 characters의 range를 representing하는 CaptureRange이거나, nth set of capturing parentheses가 아직 reached되지 않은 경우 undefined입니다. backtracking 때문에, matching process 동안 many MatchStates가 언제든 use 중일 수 있습니다.
  • MatcherContinuation은 one MatchState argument를 take하고 MatchState 또는 failure를 return하는 Abstract Closure입니다. MatcherContinuation은 its MatchState argument가 given하는 intermediate state에서 starting하여 pattern의 remaining portion(closure의 captured values로 specified됨)을 input에 대해 match하려고 attempts합니다. match가 succeeds하면, MatcherContinuation은 reached한 final MatchState를 return합니다; match가 fails하면, MatcherContinuationfailure를 return합니다.
  • Matcher는 two arguments — MatchStateMatcherContinuation — 를 take하고 MatchState 또는 failure를 return하는 Abstract Closure입니다. Matcher는 pattern의 middle subpattern(closure의 captured values로 specified됨)을 MatchState[[Input]]에 대해, its MatchState argument가 given하는 intermediate state에서 starting하여 match하려고 attempts합니다. MatcherContinuation argument는 pattern의 rest를 match하는 closure이어야 합니다. pattern의 subpattern을 match하여 new MatchState를 obtain한 뒤, Matcher는 then that new MatchState에 대해 MatcherContinuation을 calls하여 pattern의 rest도 match할 수 있는지 test합니다. 가능하면, MatcherMatcherContinuation이 returned한 MatchState를 return합니다; 그렇지 않으면, Matcher는 its choice points에서 different choices를 try할 수 있으며, success하거나 all possibilities가 exhausted될 때까지 MatcherContinuation을 repeatedly calling합니다.

22.2.2.1.1 RegExp Records

RegExp Record는 compilation 중 및 possibly matching 중에 needed되는 RegExp에 대한 information을 store하는 데 사용되는 Record value입니다.

다음 fields를 가집니다:

Table 64: RegExp Record Fields
Field Name Value Meaning
[[IgnoreCase]] a Boolean "i"가 RegExp의 flags 안에 appear하는지 여부를 indicate합니다
[[Multiline]] a Boolean "m"가 RegExp의 flags 안에 appear하는지 여부를 indicate합니다
[[DotAll]] a Boolean "s"가 RegExp의 flags 안에 appear하는지 여부를 indicate합니다
[[Unicode]] a Boolean "u"가 RegExp의 flags 안에 appear하는지 여부를 indicate합니다
[[UnicodeSets]] a Boolean "v"가 RegExp의 flags 안에 appear하는지 여부를 indicate합니다
[[CapturingGroupsCount]] a non-negative integer RegExp pattern 안의 left-capturing parentheses의 수

22.2.2.2 Runtime Semantics: CompilePattern

The syntax-directed operation CompilePattern takes argument regexpRecord (a RegExp Record) and returns an Abstract Closure that takes a List of characters and a non-negative integer and returns either a MatchState or failure. It is defined piecewise over the following productions:

Pattern :: Disjunction
  1. m을 arguments regexpRecordforward와 함께 DisjunctionCompileSubpattern으로 둔다.
  2. regexpRecordm을 capture하고 called될 때 following steps를 수행하는, parameters (input, index)를 가진 새 Abstract Closure를 반환한다:
    1. Assert: input은 characters의 List이다.
    2. Assert: 0 ≤ indexinput 안의 elements 수이다.
    3. 아무것도 capture하지 않고 called될 때 following steps를 수행하는, parameters (y)를 가진 새 MatcherContinuation c를 둔다:
      1. Assert: yMatchState이다.
      2. y를 반환한다.
    4. capabilityregexpRecord.[[CapturingGroupsCount]]개의 undefined values의 List로 두며, 1부터 regexpRecord.[[CapturingGroupsCount]]까지 indexed된다.
    5. xMatchState { [[Input]]: input, [[EndIndex]]: index, [[Captures]]: capability }로 둔다.
    6. m(x, c)를 반환한다.
Note

Pattern은 Abstract Closure value로 compiles됩니다. RegExpBuiltinExec는 then 이 procedure를 characters의 List와 그 List 안의 offset에 apply하여 pattern이 그 List 안의 exactly that offset에서 starting하여 match할지, 그리고 match한다면 capturing parentheses의 values가 무엇인지 determine할 수 있습니다. 22.2.2의 algorithms는 pattern을 compiling하는 것이 SyntaxError exception을 throw할 수 있도록 designed되어 있습니다; 반면 pattern이 successfully compiled된 후, resulting Abstract Closure를 apply하여 characters의 List에서 match를 find하는 것은 exception을 throw할 수 없습니다(out-of-memory처럼 anywhere에서 occur할 수 있는 any implementation-defined exceptions는 제외).

22.2.2.3 Runtime Semantics: CompileSubpattern

The syntax-directed operation CompileSubpattern takes arguments regexpRecord (a RegExp Record) and direction (forward or backward) and returns a Matcher.

Note 1

이 section은 B.1.2.5에서 amended됩니다.

It is defined piecewise over the following productions:

Disjunction :: Alternative | Disjunction
  1. m1을 arguments regexpRecorddirection과 함께 AlternativeCompileSubpattern으로 둔다.
  2. m2를 arguments regexpRecorddirection과 함께 DisjunctionCompileSubpattern으로 둔다.
  3. MatchTwoAlternatives(m1, m2)를 반환한다.
Note 2

| regular expression operator는 two alternatives를 separates합니다. pattern은 first left Alternative를 match하려고 tries합니다(regular expression의 sequel이 followed됨); if it fails, right Disjunction을 match하려고 tries합니다(regular expression의 sequel이 followed됨). left Alternative, right Disjunction, 그리고 sequel이 모두 choice points를 가지면, left Alternative의 next choice로 moving하기 전에 sequel 안의 all choices가 tried됩니다. left Alternative의 choices가 exhausted되면, left Alternative 대신 right Disjunction이 tried됩니다. |에 의해 skipped된 pattern portion 안의 any capturing parentheses는 Strings 대신 undefined values를 produce합니다. 따라서, 예를 들어,

/a|ab/.exec("abc")

"ab"가 아니라 result "a"를 반환합니다. Moreover,

/((a)|(ab))((c)|(bc))/.exec("abc")

는 array

["abc", "a", "a", undefined, "bc", undefined, "bc"]

를 반환하고, 다음을 반환하지 않습니다

["abc", "ab", undefined, "ab", "c", "c", undefined]

two alternatives가 tried되는 order는 direction의 value와 independent합니다.

Alternative :: [empty]
  1. EmptyMatcher()를 반환한다.
Alternative :: Alternative Term
  1. m1을 arguments regexpRecorddirection과 함께 AlternativeCompileSubpattern으로 둔다.
  2. m2를 arguments regexpRecorddirection과 함께 TermCompileSubpattern으로 둔다.
  3. MatchSequence(m1, m2, direction)을 반환한다.
Note 3

Consecutive Terms는 input의 consecutive portions를 simultaneously match하려고 try합니다. directionforward이면, left Alternative, right Term, 그리고 regular expression의 sequel이 모두 choice points를 가지는 경우, right Term의 next choice로 moving하기 전에 sequel 안의 all choices가 tried되고, left Alternative의 next choice로 moving하기 전에 right Term 안의 all choices가 tried됩니다. directionbackward이면, AlternativeTerm의 evaluation order가 reversed됩니다.

Term :: Assertion
  1. argument regexpRecord와 함께 AssertionCompileAssertion을 반환한다.
Note 4

resulting Matcherdirection과 independent합니다.

Term :: Atom
  1. arguments regexpRecorddirection과 함께 AtomCompileAtom을 반환한다.
Term :: Atom Quantifier
  1. m을 arguments regexpRecorddirection과 함께 AtomCompileAtom으로 둔다.
  2. qQuantifierCompileQuantifier로 둔다.
  3. Assert: q.[[Min]]q.[[Max]]이다.
  4. parenIndexCountLeftCapturingParensBefore(Term)로 둔다.
  5. parenCountCountLeftCapturingParensWithin(Atom)으로 둔다.
  6. m, q, parenIndex, 및 parenCount를 capture하고 called될 때 following steps를 수행하는, parameters (x, c)를 가진 새 Matcher를 반환한다:
    1. Assert: xMatchState이다.
    2. Assert: cMatcherContinuation이다.
    3. RepeatMatcher(m, q.[[Min]], q.[[Max]], q.[[Greedy]], x, c, parenIndex, parenCount)를 반환한다.

22.2.2.3.1 RepeatMatcher ( m, min, max, greedy, matchState, continue, parenIndex, parenCount )

The abstract operation RepeatMatcher takes arguments m (a Matcher), min (a non-negative integer), max (a non-negative integer or +∞), greedy (a Boolean), matchState (a MatchState), continue (a MatcherContinuation), parenIndex (a non-negative integer), and parenCount (a non-negative integer) and returns either a MatchState or failure. It performs the following steps when called:

  1. max = 0이면, continue(matchState)를 반환한다.
  2. m, min, max, greedy, matchState, continue, parenIndex, 및 parenCount를 capture하고 called될 때 following steps를 수행하는, parameters (y)를 가진 새 MatcherContinuation d를 둔다:
    1. Assert: yMatchState이다.
    2. min = 0이고 y.[[EndIndex]] = matchState.[[EndIndex]]이면, failure를 반환한다.
    3. min = 0이면 min2를 0으로 둔다; else min2min - 1로 둔다.
    4. max = +∞이면 max2를 +∞로 둔다; else max2max - 1로 둔다.
    5. RepeatMatcher(m, min2, max2, greedy, y, continue, parenIndex, parenCount)를 반환한다.
  3. capabilitymatchState.[[Captures]]의 copy로 둔다.
  4. parenIndex + 1부터 parenIndex + parenCount까지의 inclusive interval 안의 각 integer k에 대해, capability[k]를 undefined로 설정한다.
  5. inputmatchState.[[Input]]으로 둔다.
  6. ematchState.[[EndIndex]]로 둔다.
  7. xrMatchState { [[Input]]: input, [[EndIndex]]: e, [[Captures]]: capability }로 둔다.
  8. min ≠ 0이면, m(xr, d)를 반환한다.
  9. greedyfalse이면, 다음을 수행한다.
    1. zcontinue(matchState)로 둔다.
    2. zfailure가 아니면, z를 반환한다.
    3. m(xr, d)를 반환한다.
  10. zm(xr, d)로 둔다.
  11. zfailure가 아니면, z를 반환한다.
  12. continue(matchState)를 반환한다.
Note 1

Atom 뒤에 Quantifier가 followed되면 Quantifier가 specified한 number of times만큼 repeated됩니다. Quantifier는 non-greedy일 수 있으며, 이 경우 Atom pattern은 sequel을 still matching하면서 possible한 few times만 repeated됩니다. 또는 greedy일 수 있으며, 이 경우 Atom pattern은 sequel을 still matching하면서 possible한 many times만 repeated됩니다. Atom pattern은 그것이 match하는 input character sequence가 아니라 pattern itself가 repeated되므로, Atom의 different repetitions는 different input substrings를 match할 수 있습니다.

Note 2

Atom과 regular expression의 sequel이 모두 choice points를 가지면, Atom은 first possible한 many times(or non-greedy이면 possible한 few times)만큼 matched됩니다. last repetition of Atom의 next choice로 moving하기 전에 sequel 안의 all choices가 tried됩니다. Atom의 last (nth) repetition 안의 all choices는 Atom의 next-to-last (n - 1)st repetition 안의 next choice로 moving하기 전에 tried됩니다; at which point Atom의 more or fewer repetitions가 now possible한 것으로 turn out될 수 있습니다; these are exhausted됩니다(again, 가능한 few 또는 many 것으로 starting) before moving on to the next choice in the (n - 1)st repetition of Atom and so on.

Compare

/a[a-z]{2,4}/.exec("abcdefghi")

which returns "abcde" with

/a[a-z]{2,4}?/.exec("abcdefghi")

which returns "abc".

Consider also

/(aa|aabaac|ba|b|c)*/.exec("aabaac")

which, by the choice point ordering above, returns the array

["aaba", "ba"]

and not any of:

["aabaac", "aabaac"]
["aabaac", "c"]

위 choice points의 ordering은 two numbers(unary notation으로 represented됨)의 greatest common divisor를 calculate하는 regular expression을 writing하는 데 사용될 수 있습니다. following example은 10과 15의 gcd를 calculates합니다:

"aaaaaaaaaa,aaaaaaaaaaaaaaa".replace(/^(a+)\1*,\1+$/, "$1")

which returns the gcd in unary notation "aaaaa".

Note 3

RepeatMatcher의 step 4Atom이 repeated될 때마다 Atom의 captures를 clears합니다. 우리는 regular expression

/(z)((a+)?(b+)?(c))*/.exec("zaacbbbcac")

에서 its behaviour를 볼 수 있으며, 이는 array

["zaacbbbcac", "z", "ac", "a", undefined, "c"]

를 반환하고, 다음을 반환하지 않습니다

["zaacbbbcac", "z", "ac", "a", "bbb", "c"]

because outermost *의 each iteration은 quantified Atom 안에 contained된 all captured Strings를 clears하고, 이 case에서는 capture Strings numbered 2, 3, 4, 및 5를 include하기 때문입니다.

Note 4

RepeatMatcher의 step 2.b는 minimum number of repetitions가 satisfied되면, empty character sequence를 match하는 Atom의 any more expansions는 further repetitions에 considered되지 않는다고 states합니다. 이는 regular expression engine이 다음과 같은 patterns에서 infinite loop에 빠지는 것을 prevents합니다:

/(a*)*/.exec("b")

or the slightly more complicated:

/(a*)b\1+/.exec("baaaac")

which returns the array

["b", ""]

22.2.2.3.2 EmptyMatcher ( )

The abstract operation EmptyMatcher takes no arguments and returns a Matcher. It performs the following steps when called:

  1. 아무것도 capture하지 않고 called될 때 following steps를 수행하는, parameters (matchState, continue)를 가진 새 Matcher를 반환한다:
    1. Assert: matchStateMatchState이다.
    2. Assert: continueMatcherContinuation이다.
    3. continue(matchState)를 반환한다.

22.2.2.3.3 MatchTwoAlternatives ( m1, m2 )

The abstract operation MatchTwoAlternatives takes arguments m1 (a Matcher) and m2 (a Matcher) and returns a Matcher. It performs the following steps when called:

  1. m1m2를 capture하고 called될 때 following steps를 수행하는, parameters (matchState, continue)를 가진 새 Matcher를 반환한다:
    1. Assert: matchStateMatchState이다.
    2. Assert: continueMatcherContinuation이다.
    3. resultm1(matchState, continue)로 둔다.
    4. resultfailure가 아니면, result를 반환한다.
    5. m2(matchState, continue)를 반환한다.

22.2.2.3.4 MatchSequence ( m1, m2, direction )

The abstract operation MatchSequence takes arguments m1 (a Matcher), m2 (a Matcher), and direction (forward or backward) and returns a Matcher. It performs the following steps when called:

  1. directionforward이면, 다음을 수행한다.
    1. m1m2를 capture하고 called될 때 following steps를 수행하는, parameters (matchState, continue)를 가진 새 Matcher를 반환한다:
      1. Assert: matchStateMatchState이다.
      2. Assert: continueMatcherContinuation이다.
      3. continuem2를 capture하고 called될 때 following steps를 수행하는, parameters (y)를 가진 새 MatcherContinuation d를 둔다:
        1. Assert: yMatchState이다.
        2. m2(y, continue)를 반환한다.
      4. m1(matchState, d)를 반환한다.
  2. Assert: directionbackward이다.
  3. m1m2를 capture하고 called될 때 following steps를 수행하는, parameters (matchState, continue)를 가진 새 Matcher를 반환한다:
    1. Assert: matchStateMatchState이다.
    2. Assert: continueMatcherContinuation이다.
    3. continuem1을 capture하고 called될 때 following steps를 수행하는, parameters (y)를 가진 새 MatcherContinuation d를 둔다:
      1. Assert: yMatchState이다.
      2. m1(y, continue)를 반환한다.
    4. m2(matchState, d)를 반환한다.

22.2.2.4 Runtime Semantics: CompileAssertion

The syntax-directed operation CompileAssertion takes argument regexpRecord (a RegExp Record) and returns a Matcher.

Note 1

이 section은 B.1.2.6에서 amended됩니다.

It is defined piecewise over the following productions:

Assertion :: ^
  1. regexpRecord를 capture하고 called될 때 following steps를 수행하는, parameters (matchState, continue)를 가진 새 Matcher를 반환한다:
    1. Assert: matchStateMatchState이다.
    2. Assert: continueMatcherContinuation이다.
    3. inputmatchState.[[Input]]으로 둔다.
    4. ematchState.[[EndIndex]]로 둔다.
    5. e = 0이거나, regexpRecord.[[Multiline]]true이고 character input[e - 1]가 LineTerminator에 의해 matched되면, 다음을 수행한다.
      1. continue(matchState)를 반환한다.
    6. failure를 반환한다.
Note 2

y flag가 pattern과 함께 used될 때조차, ^는 always input의 beginning에서만, 또는(regexpRecord.[[Multiline]]true이면) line의 beginning에서만 matches합니다.

Assertion :: $
  1. regexpRecord를 capture하고 called될 때 following steps를 수행하는, parameters (matchState, continue)를 가진 새 Matcher를 반환한다:
    1. Assert: matchStateMatchState이다.
    2. Assert: continueMatcherContinuation이다.
    3. inputmatchState.[[Input]]으로 둔다.
    4. ematchState.[[EndIndex]]로 둔다.
    5. inputLengthinput 안의 elements 수로 둔다.
    6. e = inputLength이거나, regexpRecord.[[Multiline]]true이고 character input[e]가 LineTerminator에 의해 matched되면, 다음을 수행한다.
      1. continue(matchState)를 반환한다.
    7. failure를 반환한다.
Assertion :: \b
  1. regexpRecord를 capture하고 called될 때 following steps를 수행하는, parameters (matchState, continue)를 가진 새 Matcher를 반환한다:
    1. Assert: matchStateMatchState이다.
    2. Assert: continueMatcherContinuation이다.
    3. inputmatchState.[[Input]]으로 둔다.
    4. ematchState.[[EndIndex]]로 둔다.
    5. aIsWordChar(regexpRecord, input, e - 1)로 둔다.
    6. bIsWordChar(regexpRecord, input, e)로 둔다.
    7. atrue이고 bfalse이거나, afalse이고 btrue이면, continue(matchState)를 반환한다.
    8. failure를 반환한다.
Assertion :: \B
  1. regexpRecord를 capture하고 called될 때 following steps를 수행하는, parameters (matchState, continue)를 가진 새 Matcher를 반환한다:
    1. Assert: matchStateMatchState이다.
    2. Assert: continueMatcherContinuation이다.
    3. inputmatchState.[[Input]]으로 둔다.
    4. ematchState.[[EndIndex]]로 둔다.
    5. aIsWordChar(regexpRecord, input, e - 1)로 둔다.
    6. bIsWordChar(regexpRecord, input, e)로 둔다.
    7. atrue이고 btrue이거나, afalse이고 bfalse이면, continue(matchState)를 반환한다.
    8. failure를 반환한다.
Assertion :: (?= Disjunction )
  1. m을 arguments regexpRecordforward와 함께 DisjunctionCompileSubpattern으로 둔다.
  2. m을 capture하고 called될 때 following steps를 수행하는, parameters (matchState, continue)를 가진 새 Matcher를 반환한다:
    1. Assert: matchStateMatchState이다.
    2. Assert: continueMatcherContinuation이다.
    3. 아무것도 capture하지 않고 called될 때 following steps를 수행하는, parameters (y)를 가진 새 MatcherContinuation d를 둔다:
      1. Assert: yMatchState이다.
      2. y를 반환한다.
    4. resultm(matchState, d)로 둔다.
    5. resultfailure이면, failure를 반환한다.
    6. Assert: resultMatchState이다.
    7. capabilityresult.[[Captures]]로 둔다.
    8. inputmatchState.[[Input]]으로 둔다.
    9. xematchState.[[EndIndex]]로 둔다.
    10. zMatchState { [[Input]]: input, [[EndIndex]]: xe, [[Captures]]: capability }로 둔다.
    11. continue(z)를 반환한다.
Note 3

form (?= Disjunction )는 zero-width positive lookahead를 specifies합니다. 이것이 succeed하려면, Disjunction 안의 pattern이 current position에서 match해야 하지만, sequel을 matching하기 전에 current position은 advanced되지 않습니다. Disjunction이 current position에서 several ways로 match할 수 있으면, only first one이 tried됩니다. other regular expression operators와 달리, (?= form 안으로의 backtracking은 없습니다(this unusual behaviour는 Perl로부터 inherited되었습니다). 이는 Disjunction이 capturing parentheses를 contain하고 pattern의 sequel이 those captures에 대한 backreferences를 contain할 때만 matters합니다.

예를 들어,

/(?=(a+))/.exec("baaabac")

는 first b 바로 뒤의 empty String을 matches하므로 array를 반환합니다:

["", "aaa"]

lookahead 안으로 backtracking이 없는 것을 illustrate하기 위해 다음을 consider하십시오:

/(?=(a+))a*b\1/.exec("baaabac")

이 expression은 다음을 반환합니다

["aba", "a"]

그리고 다음을 반환하지 않습니다:

["aaaba", "a"]
Assertion :: (?! Disjunction )
  1. m을 arguments regexpRecordforward와 함께 DisjunctionCompileSubpattern으로 둔다.
  2. m을 capture하고 called될 때 following steps를 수행하는, parameters (matchState, continue)를 가진 새 Matcher를 반환한다:
    1. Assert: matchStateMatchState이다.
    2. Assert: continueMatcherContinuation이다.
    3. 아무것도 capture하지 않고 called될 때 following steps를 수행하는, parameters (y)를 가진 새 MatcherContinuation d를 둔다:
      1. Assert: yMatchState이다.
      2. y를 반환한다.
    4. resultm(matchState, d)로 둔다.
    5. resultfailure가 아니면, failure를 반환한다.
    6. continue(matchState)를 반환한다.
Note 4

form (?! Disjunction )는 zero-width negative lookahead를 specifies합니다. 이것이 succeed하려면, Disjunction 안의 pattern이 current position에서 match하지 못해야 합니다. sequel을 matching하기 전에 current position은 advanced되지 않습니다. Disjunction은 capturing parentheses를 contain할 수 있지만, them에 대한 backreferences는 Disjunction itself 안에서만 sense를 가집니다. pattern의 elsewhere에서 these capturing parentheses에 대한 Backreferences는 negative lookahead가 pattern이 succeed하기 위해 fail해야 하므로 always undefined를 return합니다. 예를 들어,

/(.*?)a(?!(a+)b\2c)\2(.*)/.exec("baaabaac")

는 positive number n of a's, b, another n a's(first \2로 specified됨), 그리고 c가 immediately followed하지 않는 a를 looks for합니다. second \2는 negative lookahead outside에 있으므로, undefined에 대해 matches하고 따라서 always succeeds합니다. whole expression은 array를 반환합니다:

["baaabaac", "ba", undefined, "abaac"]
Assertion :: (?<= Disjunction )
  1. m을 arguments regexpRecordbackward와 함께 DisjunctionCompileSubpattern으로 둔다.
  2. m을 capture하고 called될 때 following steps를 수행하는, parameters (matchState, continue)를 가진 새 Matcher를 반환한다:
    1. Assert: matchStateMatchState이다.
    2. Assert: continueMatcherContinuation이다.
    3. 아무것도 capture하지 않고 called될 때 following steps를 수행하는, parameters (y)를 가진 새 MatcherContinuation d를 둔다:
      1. Assert: yMatchState이다.
      2. y를 반환한다.
    4. resultm(matchState, d)로 둔다.
    5. resultfailure이면, failure를 반환한다.
    6. Assert: resultMatchState이다.
    7. capabilityresult.[[Captures]]로 둔다.
    8. inputmatchState.[[Input]]으로 둔다.
    9. xematchState.[[EndIndex]]로 둔다.
    10. zMatchState { [[Input]]: input, [[EndIndex]]: xe, [[Captures]]: capability }로 둔다.
    11. continue(z)를 반환한다.
Assertion :: (?<! Disjunction )
  1. m을 arguments regexpRecordbackward와 함께 DisjunctionCompileSubpattern으로 둔다.
  2. m을 capture하고 called될 때 following steps를 수행하는, parameters (matchState, continue)를 가진 새 Matcher를 반환한다:
    1. Assert: matchStateMatchState이다.
    2. Assert: continueMatcherContinuation이다.
    3. 아무것도 capture하지 않고 called될 때 following steps를 수행하는, parameters (y)를 가진 새 MatcherContinuation d를 둔다:
      1. Assert: yMatchState이다.
      2. y를 반환한다.
    4. resultm(matchState, d)로 둔다.
    5. resultfailure가 아니면, failure를 반환한다.
    6. continue(matchState)를 반환한다.

22.2.2.4.1 IsWordChar ( regexpRecord, input, e )

The abstract operation IsWordChar takes arguments regexpRecord (a RegExp Record), input (a List of characters), and e (an integer) and returns a Boolean. It performs the following steps when called:

  1. inputLengthinput 안의 elements 수로 둔다.
  2. e = -1 또는 e = inputLength이면, false를 반환한다.
  3. char를 character input[e]로 둔다.
  4. WordCharacters(regexpRecord)가 char를 contain하면, true를 반환한다.
  5. false를 반환한다.

22.2.2.5 Runtime Semantics: CompileQuantifier

The syntax-directed operation CompileQuantifier takes no arguments and returns a Record with fields [[Min]] (a non-negative integer), [[Max]] (a non-negative integer or +∞), and [[Greedy]] (a Boolean). It is defined piecewise over the following productions:

Quantifier :: QuantifierPrefix
  1. qpQuantifierPrefixCompileQuantifierPrefix로 둔다.
  2. Record { [[Min]]: qp.[[Min]], [[Max]]: qp.[[Max]], [[Greedy]]: true }를 반환한다.
Quantifier :: QuantifierPrefix ?
  1. qpQuantifierPrefixCompileQuantifierPrefix로 둔다.
  2. Record { [[Min]]: qp.[[Min]], [[Max]]: qp.[[Max]], [[Greedy]]: false }를 반환한다.

22.2.2.6 Runtime Semantics: CompileQuantifierPrefix

The syntax-directed operation CompileQuantifierPrefix takes no arguments and returns a Record with fields [[Min]] (a non-negative integer) and [[Max]] (a non-negative integer or +∞). It is defined piecewise over the following productions:

QuantifierPrefix :: *
  1. Record { [[Min]]: 0, [[Max]]: +∞ }를 반환한다.
QuantifierPrefix :: +
  1. Record { [[Min]]: 1, [[Max]]: +∞ }를 반환한다.
QuantifierPrefix :: ?
  1. Record { [[Min]]: 0, [[Max]]: 1 }를 반환한다.
QuantifierPrefix :: { DecimalDigits }
  1. iDecimalDigits의 MV로 둔다(12.9.3 참조).
  2. Record { [[Min]]: i, [[Max]]: i }를 반환한다.
QuantifierPrefix :: { DecimalDigits ,}
  1. iDecimalDigits의 MV로 둔다.
  2. Record { [[Min]]: i, [[Max]]: +∞ }를 반환한다.
QuantifierPrefix :: { DecimalDigits , DecimalDigits }
  1. i를 first DecimalDigits의 MV로 둔다.
  2. j를 second DecimalDigits의 MV로 둔다.
  3. Record { [[Min]]: i, [[Max]]: j }를 반환한다.

22.2.2.7 Runtime Semantics: CompileAtom

The syntax-directed operation CompileAtom takes arguments regexpRecord (a RegExp Record) and direction (forward or backward) and returns a Matcher.

Note 1

이 section은 B.1.2.7에서 amended됩니다.

It is defined piecewise over the following productions:

Atom :: PatternCharacter
  1. charPatternCharacter가 matched한 character로 둔다.
  2. charSet을 character char를 contain하는 one-element CharSet으로 둔다.
  3. CharacterSetMatcher(regexpRecord, charSet, false, direction)를 반환한다.
Atom :: .
  1. charSetAllCharacters(regexpRecord)로 둔다.
  2. regexpRecord.[[DotAll]]true가 아니면, 다음을 수행한다.
    1. LineTerminator production의 right-hand side에 있는 code point에 corresponding하는 all characters를 charSet에서 remove한다.
  3. CharacterSetMatcher(regexpRecord, charSet, false, direction)를 반환한다.
Atom :: CharacterClass
  1. cc를 argument regexpRecord와 함께 CharacterClassCompileCharacterClass로 둔다.
  2. cscc.[[CharSet]]으로 둔다.
  3. regexpRecord.[[UnicodeSets]]false이거나 cs의 every CharSetElement가 single character로 구성되면(cs가 empty인 경우 포함), CharacterSetMatcher(regexpRecord, cs, cc.[[Invert]], direction)를 반환한다.
  4. Assert: cc.[[Invert]]false이다.
  5. listOfMatchers를 empty List of Matchers로 둔다.
  6. cs 안의 more than 1 character를 contain하는 각 CharSetElement s에 대해, length의 descending order로 iterating하며 다음을 수행한다.
    1. cs2s의 last code point를 contain하는 one-element CharSet으로 둔다.
    2. m2CharacterSetMatcher(regexpRecord, cs2, false, direction)로 둔다.
    3. s 안의 각 code point c1에 대해, its second-to-last code point부터 backwards로 iterating하며 다음을 수행한다.
      1. cs1c1을 contain하는 one-element CharSet으로 둔다.
      2. m1CharacterSetMatcher(regexpRecord, cs1, false, direction)로 둔다.
      3. m2MatchSequence(m1, m2, direction)으로 설정한다.
    4. m2listOfMatchers에 append한다.
  7. singles를 single character로 구성된 cs의 every CharSetElement를 contain하는 CharSet으로 둔다.
  8. CharacterSetMatcher(regexpRecord, singles, false, direction)를 listOfMatchers에 append한다.
  9. cs가 characters의 empty sequence를 contain하면, EmptyMatcher()를 listOfMatchers에 append한다.
  10. m2listOfMatchers 안의 last Matcher로 둔다.
  11. listOfMatchers의 각 Matcher m1에 대해, its second-to-last element부터 backwards로 iterating하며 다음을 수행한다.
    1. m2MatchTwoAlternatives(m1, m2)로 설정한다.
  12. m2를 반환한다.
Atom :: ( GroupSpecifieropt Disjunction )
  1. m을 arguments regexpRecorddirection과 함께 DisjunctionCompileSubpattern으로 둔다.
  2. parenIndexCountLeftCapturingParensBefore(Atom)로 둔다.
  3. direction, m, 및 parenIndex를 capture하고 called될 때 following steps를 수행하는, parameters (x, c)를 가진 새 Matcher를 반환한다:
    1. Assert: xMatchState이다.
    2. Assert: cMatcherContinuation이다.
    3. x, c, direction, 및 parenIndex를 capture하고 called될 때 following steps를 수행하는, parameters (y)를 가진 새 MatcherContinuation d를 둔다:
      1. Assert: yMatchState이다.
      2. capabilityy.[[Captures]]의 copy로 둔다.
      3. inputx.[[Input]]으로 둔다.
      4. xex.[[EndIndex]]로 둔다.
      5. yey.[[EndIndex]]로 둔다.
      6. directionforward이면, 다음을 수행한다.
        1. Assert: xeye이다.
        2. rCaptureRange { [[StartIndex]]: xe, [[EndIndex]]: ye }로 둔다.
      7. Else,
        1. Assert: directionbackward이다.
        2. Assert: yexe이다.
        3. rCaptureRange { [[StartIndex]]: ye, [[EndIndex]]: xe }로 둔다.
      8. capability[parenIndex + 1]을 r로 설정한다.
      9. zMatchState { [[Input]]: input, [[EndIndex]]: ye, [[Captures]]: capability }로 둔다.
      10. c(z)를 반환한다.
    4. m(x, d)를 반환한다.
Note 2

form ( Disjunction )의 Parentheses는 Disjunction pattern의 components를 together group하고 match result를 save하는 two roles를 serve합니다. result는 backreference(\ followed by a non-zero decimal number), replace String 안에서 referenced, 또는 regular expression matching Abstract Closure로부터 array의 part로 returned되는 데 사용될 수 있습니다. parentheses의 capturing behaviour를 inhibit하려면 form (?: Disjunction )를 사용하십시오.

Atom :: (? RegularExpressionModifiers : Disjunction )
  1. addModifiersRegularExpressionModifiers가 matched한 source text로 둔다.
  2. removeModifiers를 empty String으로 둔다.
  3. modifiedRerUpdateModifiers(regexpRecord, CodePointsToString(addModifiers), removeModifiers)로 둔다.
  4. arguments modifiedRerdirection과 함께 DisjunctionCompileSubpattern을 반환한다.
Atom :: (? RegularExpressionModifiers - RegularExpressionModifiers : Disjunction )
  1. addModifiers를 first RegularExpressionModifiers가 matched한 source text로 둔다.
  2. removeModifiers를 second RegularExpressionModifiers가 matched한 source text로 둔다.
  3. modifiedRerUpdateModifiers(regexpRecord, CodePointsToString(addModifiers), CodePointsToString(removeModifiers))로 둔다.
  4. arguments modifiedRerdirection과 함께 DisjunctionCompileSubpattern을 반환한다.
AtomEscape :: DecimalEscape
  1. nDecimalEscapeCapturingGroupNumber로 둔다.
  2. Assert: nregexpRecord.[[CapturingGroupsCount]]이다.
  3. BackreferenceMatcher(regexpRecord, « n », direction)를 반환한다.
Note 3

form \ followed by a non-zero decimal number n의 escape sequence는 nth set of capturing parentheses의 result(22.2.2.1)를 matches합니다. regular expression이 n보다 fewer capturing parentheses를 가지면 error입니다. regular expression이 n 또는 more capturing parentheses를 가지지만 nth one이 아무것도 capture하지 않았기 때문에 undefined이면, backreference는 always succeeds합니다.

AtomEscape :: CharacterEscape
  1. charValueCharacterEscapeCharacterValue로 둔다.
  2. char를 character value가 charValue인 character로 둔다.
  3. charSet을 character char를 contain하는 one-element CharSet으로 둔다.
  4. CharacterSetMatcher(regexpRecord, charSet, false, direction)를 반환한다.
AtomEscape :: CharacterClassEscape
  1. cs를 argument regexpRecord와 함께 CharacterClassEscapeCompileToCharSet으로 둔다.
  2. regexpRecord.[[UnicodeSets]]false이거나 cs의 every CharSetElement가 single character로 구성되면(cs가 empty인 경우 포함), CharacterSetMatcher(regexpRecord, cs, false, direction)를 반환한다.
  3. listOfMatchers를 empty List of Matchers로 둔다.
  4. cs 안의 more than 1 character를 contain하는 각 CharSetElement s에 대해, length의 descending order로 iterating하며 다음을 수행한다.
    1. cs2s의 last code point를 contain하는 one-element CharSet으로 둔다.
    2. m2CharacterSetMatcher(regexpRecord, cs2, false, direction)로 둔다.
    3. s 안의 각 code point c1에 대해, its second-to-last code point부터 backwards로 iterating하며 다음을 수행한다.
      1. cs1c1을 contain하는 one-element CharSet으로 둔다.
      2. m1CharacterSetMatcher(regexpRecord, cs1, false, direction)로 둔다.
      3. m2MatchSequence(m1, m2, direction)으로 설정한다.
    4. m2listOfMatchers에 append한다.
  5. singles를 single character로 구성된 cs의 every CharSetElement를 contain하는 CharSet으로 둔다.
  6. CharacterSetMatcher(regexpRecord, singles, false, direction)를 listOfMatchers에 append한다.
  7. cs가 characters의 empty sequence를 contain하면, EmptyMatcher()를 listOfMatchers에 append한다.
  8. m2listOfMatchers 안의 last Matcher로 둔다.
  9. listOfMatchers의 각 Matcher m1에 대해, its second-to-last element부터 backwards로 iterating하며 다음을 수행한다.
    1. m2MatchTwoAlternatives(m1, m2)로 설정한다.
  10. m2를 반환한다.
AtomEscape :: k GroupName
  1. matchingGroupSpecifiersGroupSpecifiersThatMatch(GroupName)으로 둔다.
  2. parenIndices를 새 empty List로 둔다.
  3. matchingGroupSpecifiers의 각 GroupSpecifier groupSpecifier에 대해, 다음을 수행한다.
    1. parenIndexCountLeftCapturingParensBefore(groupSpecifier)로 둔다.
    2. parenIndexparenIndices에 append한다.
  4. BackreferenceMatcher(regexpRecord, parenIndices, direction)를 반환한다.

22.2.2.7.1 CharacterSetMatcher ( regexpRecord, charSet, invert, direction )

The abstract operation CharacterSetMatcher takes arguments regexpRecord (a RegExp Record), charSet (a CharSet), invert (a Boolean), and direction (forward or backward) and returns a Matcher. It performs the following steps when called:

  1. regexpRecord.[[UnicodeSets]]true이면, 다음을 수행한다.
    1. Assert: invertfalse이다.
    2. Assert: charSet의 Every CharSetElement는 single character로 구성된다.
  2. regexpRecord, charSet, invert, 및 direction을 capture하고 called될 때 following steps를 수행하는, parameters (x, c)를 가진 새 Matcher를 반환한다:
    1. Assert: xMatchState이다.
    2. Assert: cMatcherContinuation이다.
    3. inputx.[[Input]]으로 둔다.
    4. endIndexx.[[EndIndex]]로 둔다.
    5. directionforward이면, fendIndex + 1로 둔다.
    6. Else, fendIndex - 1로 둔다.
    7. inputLengthinput 안의 elements 수로 둔다.
    8. f < 0 또는 f > inputLength이면, failure를 반환한다.
    9. indexmin(endIndex, f)로 둔다.
    10. char를 character input[index]로 둔다.
    11. ccCanonicalize(regexpRecord, char)로 둔다.
    12. Canonicalize(regexpRecord, a)가 cc인 exactly one character a를 containing하는 CharSetElementcharSet 안에 존재하면 foundtrue로 둔다; else foundfalse로 둔다.
    13. invertfalse이고 foundfalse이면, failure를 반환한다.
    14. inverttrue이고 foundtrue이면, failure를 반환한다.
    15. capabilityx.[[Captures]]로 둔다.
    16. yMatchState { [[Input]]: input, [[EndIndex]]: f, [[Captures]]: capability }로 둔다.
    17. c(y)를 반환한다.

22.2.2.7.2 BackreferenceMatcher ( regexpRecord, ns, direction )

The abstract operation BackreferenceMatcher takes arguments regexpRecord (a RegExp Record), ns (a List of positive integers), and direction (forward or backward) and returns a Matcher. It performs the following steps when called:

  1. regexpRecord, ns, 및 direction을 capture하고 called될 때 following steps를 수행하는, parameters (x, c)를 가진 새 Matcher를 반환한다:
    1. Assert: xMatchState이다.
    2. Assert: cMatcherContinuation이다.
    3. inputx.[[Input]]으로 둔다.
    4. capabilityx.[[Captures]]로 둔다.
    5. rundefined로 둔다.
    6. ns의 각 integer n에 대해, 다음을 수행한다.
      1. capability[n]이 undefined가 아니면, 다음을 수행한다.
        1. Assert: rundefined이다.
        2. rcapability[n]으로 설정한다.
    7. rundefined이면, c(x)를 반환한다.
    8. endIndexx.[[EndIndex]]로 둔다.
    9. rsr.[[StartIndex]]로 둔다.
    10. rer.[[EndIndex]]로 둔다.
    11. lengthre - rs로 둔다.
    12. directionforward이면, fendIndex + length로 둔다.
    13. Else, fendIndex - length로 둔다.
    14. inputLengthinput 안의 elements 수로 둔다.
    15. f < 0 또는 f > inputLength이면, failure를 반환한다.
    16. gmin(endIndex, f)로 둔다.
    17. 0(inclusive)부터 length(exclusive)까지의 interval 안에, Canonicalize(regexpRecord, input[rs + i])가 Canonicalize(regexpRecord, input[g + i])가 아닌 integer i가 존재하면, failure를 반환한다.
    18. yMatchState { [[Input]]: input, [[EndIndex]]: f, [[Captures]]: capability }로 둔다.
    19. c(y)를 반환한다.

22.2.2.7.3 Canonicalize ( regexpRecord, char )

The abstract operation Canonicalize takes arguments regexpRecord (a RegExp Record) and char (a character) and returns a character. It performs the following steps when called:

  1. HasEitherUnicodeFlag(regexpRecord)가 true이고 regexpRecord.[[IgnoreCase]]true이면, 다음을 수행한다.
    1. Unicode Character Database의 file CaseFolding.txtchar에 대한 simple 또는 common case folding mapping을 provide하면, 그 mapping을 char에 apply한 result를 반환한다.
    2. char를 반환한다.
  2. regexpRecord.[[IgnoreCase]]false이면, char를 반환한다.
  3. Assert: char는 UTF-16 code unit이다.
  4. codePoint를 numeric value가 char의 numeric value인 code point로 둔다.
  5. u를 Unicode Default Case Conversion algorithm에 따른 toUppercase(« codePoint »)로 둔다.
  6. uStringCodePointsToString(u)으로 둔다.
  7. uString의 length ≠ 1이면, char를 반환한다.
  8. codeUnituString의 single code unit element로 둔다.
  9. char의 numeric value ≥ 128이고 codeUnit의 numeric value < 128이면, char를 반환한다.
  10. codeUnit을 반환한다.
Note

HasEitherUnicodeFlag(regexpRecord)가 true인 case-insignificant matches에서, all characters는 compared되기 immediately before Unicode Standard가 provided하는 simple mapping을 사용하여 implicitly case-folded됩니다. simple mapping은 always single code point로 maps하므로, 예를 들어 ß (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되고 (U+212A KELVIN SIGN)는 k (U+006B LATIN SMALL LETTER K)로 case-fold됩니다. those code points를 contain하는 Strings는 /[a-z]/ui와 같은 regular expressions에 의해 matched됩니다.

HasEitherUnicodeFlag(regexpRecord)가 false인 case-insignificant matches에서, mapping은 toCasefold가 아니라 Unicode Default Case Conversion algorithm toUppercase에 based하며, 이는 some subtle differences를 result합니다. 예를 들어, (U+2126 OHM SIGN)는 toUppercase에 의해 itself로 mapped되지만 toCasefold에 의해 Ω (U+03A9 GREEK CAPITAL LETTER OMEGA)와 함께 ω (U+03C9 GREEK SMALL LETTER OMEGA)로 mapped되므로, "\u2126"/[ω]/ui/[\u03A9]/ui에 의해 matched되지만 /[ω]/i 또는 /[\u03A9]/i에 의해 matched되지 않습니다. 또한 Basic Latin block 밖의 code point는 그 안의 code point로 mapped되지 않으므로, "\u017F ſ""\u212A K"와 같은 strings는 /[a-z]/i에 의해 matched되지 않습니다.

22.2.2.7.4 UpdateModifiers ( regexpRecord, add, remove )

The abstract operation UpdateModifiers takes arguments regexpRecord (a RegExp Record), add (a String), and remove (a String) and returns a RegExp Record. It performs the following steps when called:

  1. Assert: addremove는 common elements를 가지지 않는다.
  2. ignoreCaseregexpRecord.[[IgnoreCase]]로 둔다.
  3. multilineregexpRecord.[[Multiline]]로 둔다.
  4. dotAllregexpRecord.[[DotAll]]로 둔다.
  5. unicoderegexpRecord.[[Unicode]]로 둔다.
  6. unicodeSetsregexpRecord.[[UnicodeSets]]로 둔다.
  7. capturingGroupsCountregexpRecord.[[CapturingGroupsCount]]로 둔다.
  8. remove"i"를 contain하면, ignoreCasefalse로 설정한다.
  9. Else if add"i"를 contain하면, ignoreCasetrue로 설정한다.
  10. remove"m"를 contain하면, multilinefalse로 설정한다.
  11. Else if add"m"를 contain하면, multilinetrue로 설정한다.
  12. remove"s"를 contain하면, dotAllfalse로 설정한다.
  13. Else if add"s"를 contain하면, dotAlltrue로 설정한다.
  14. RegExp Record { [[IgnoreCase]]: ignoreCase, [[Multiline]]: multiline, [[DotAll]]: dotAll, [[Unicode]]: unicode, [[UnicodeSets]]: unicodeSets, [[CapturingGroupsCount]]: capturingGroupsCount }를 반환한다.

22.2.2.8 Runtime Semantics: CompileCharacterClass

The syntax-directed operation CompileCharacterClass takes argument regexpRecord (a RegExp Record) and returns a Record with fields [[CharSet]] (a CharSet) and [[Invert]] (a Boolean). It is defined piecewise over the following productions:

CharacterClass :: [ ClassContents ]
  1. charSet을 argument regexpRecord와 함께 ClassContentsCompileToCharSet으로 둔다.
  2. Record { [[CharSet]]: charSet, [[Invert]]: false }를 반환한다.
CharacterClass :: [^ ClassContents ]
  1. charSet을 argument regexpRecord와 함께 ClassContentsCompileToCharSet으로 둔다.
  2. regexpRecord.[[UnicodeSets]]true이면, 다음을 수행한다.
    1. Record { [[CharSet]]: CharacterComplement(regexpRecord, charSet), [[Invert]]: false }를 반환한다.
  3. Record { [[CharSet]]: charSet, [[Invert]]: true }를 반환한다.

22.2.2.9 Runtime Semantics: CompileToCharSet

The syntax-directed operation CompileToCharSet takes argument regexpRecord (a RegExp Record) and returns a CharSet.

Note 1

이 section은 B.1.2.8에서 amended됩니다.

It is defined piecewise over the following productions:

ClassContents :: [empty]
  1. empty CharSet을 반환한다.
NonemptyClassRanges :: ClassAtom NonemptyClassRangesNoDash
  1. charSet을 argument regexpRecord와 함께 ClassAtomCompileToCharSet으로 둔다.
  2. otherSet을 argument regexpRecord와 함께 NonemptyClassRangesNoDashCompileToCharSet으로 둔다.
  3. CharSets charSetotherSet의 union을 반환한다.
NonemptyClassRanges :: ClassAtom - ClassAtom ClassContents
  1. charSet을 argument regexpRecord와 함께 first ClassAtomCompileToCharSet으로 둔다.
  2. otherSet을 argument regexpRecord와 함께 second ClassAtomCompileToCharSet으로 둔다.
  3. remainingSet을 argument regexpRecord와 함께 ClassContentsCompileToCharSet으로 둔다.
  4. rangeSetCharacterRange(charSet, otherSet)로 둔다.
  5. rangeSetremainingSet의 union을 반환한다.
NonemptyClassRangesNoDash :: ClassAtomNoDash NonemptyClassRangesNoDash
  1. charSet을 argument regexpRecord와 함께 ClassAtomNoDashCompileToCharSet으로 둔다.
  2. otherSet을 argument regexpRecord와 함께 NonemptyClassRangesNoDashCompileToCharSet으로 둔다.
  3. CharSets charSetotherSet의 union을 반환한다.
NonemptyClassRangesNoDash :: ClassAtomNoDash - ClassAtom ClassContents
  1. charSet을 argument regexpRecord와 함께 ClassAtomNoDashCompileToCharSet으로 둔다.
  2. otherSet을 argument regexpRecord와 함께 ClassAtomCompileToCharSet으로 둔다.
  3. remainingSet을 argument regexpRecord와 함께 ClassContentsCompileToCharSet으로 둔다.
  4. rangeSetCharacterRange(charSet, otherSet)로 둔다.
  5. rangeSetremainingSet의 union을 반환한다.
Note 2

ClassContents는 single ClassAtom 및/또는 dashes로 separated된 two ClassAtom의 ranges로 expand될 수 있습니다. latter case에서 ClassContents는 first ClassAtom과 second ClassAtom 사이의 all characters를 inclusive로 include합니다; either ClassAtom이 single character를 represent하지 않으면(예: one이 \w인 경우) 또는 first ClassAtom의 character value가 second ClassAtom의 character value보다 strictly greater이면 error가 occurs합니다.

Note 3

pattern이 case를 ignores하더라도, range의 two ends의 case는 어떤 characters가 range에 belong하는지 determining하는 데 significant합니다. 따라서 예를 들어, pattern /[E-F]/i는 letters E, F, e, 및 f만 matches하는 반면, pattern /[E-f]/i는 Unicode Basic Latin block 안의 all uppercase and lowercase letters 및 symbols [, \, ], ^, _, 그리고 `를 matches합니다.

Note 4

- character는 literally treated될 수 있고 range를 denote할 수도 있습니다. It is treated literally if it is the first or last character of ClassContents, the beginning or end limit of a range specification, or immediately follows a range specification.

ClassAtom :: -
  1. single character - U+002D (HYPHEN-MINUS)를 contain하는 CharSet을 반환한다.
ClassAtomNoDash :: SourceCharacter but not one of \ or ] or -
  1. SourceCharacter가 matched한 character를 contain하는 CharSet을 반환한다.
ClassEscape :: b - CharacterEscape
  1. charValue를 this ClassEscapeCharacterValue로 둔다.
  2. char를 character value가 charValue인 character로 둔다.
  3. single character char를 contain하는 CharSet을 반환한다.
Note 5

ClassAtom은 regular expression의 rest에서 allowed되는 any escape sequences를 사용할 수 있지만, \b, \B, 및 backreferences는 제외합니다. CharacterClass 안에서 \b는 backspace character를 의미하는 반면, \B 및 backreferences는 errors를 raise합니다. ClassAtom 안에서 backreference를 사용하면 error가 causes됩니다.

CharacterClassEscape :: d
  1. characters 0, 1, 2, 3, 4, 5, 6, 7, 8, 및 9를 contain하는 ten-element CharSet을 반환한다.
CharacterClassEscape :: D
  1. charSet CharacterClassEscape :: d 가 returned한 CharSet으로 둔다.
  2. CharacterComplement(regexpRecord, charSet)를 반환한다.
CharacterClassEscape :: s
  1. WhiteSpace 또는 LineTerminator productions의 right-hand side에 있는 code point에 corresponding하는 all characters를 contain하는 CharSet을 반환한다.
CharacterClassEscape :: S
  1. charSet CharacterClassEscape :: s 가 returned한 CharSet으로 둔다.
  2. CharacterComplement(regexpRecord, charSet)를 반환한다.
CharacterClassEscape :: w
  1. MaybeSimpleCaseFolding(regexpRecord, WordCharacters(regexpRecord))를 반환한다.
CharacterClassEscape :: W
  1. charSet CharacterClassEscape :: w 가 returned한 CharSet으로 둔다.
  2. CharacterComplement(regexpRecord, charSet)를 반환한다.
CharacterClassEscape :: p{ UnicodePropertyValueExpression }
  1. argument regexpRecord와 함께 UnicodePropertyValueExpressionCompileToCharSet을 반환한다.
CharacterClassEscape :: P{ UnicodePropertyValueExpression }
  1. charSet을 argument regexpRecord와 함께 UnicodePropertyValueExpressionCompileToCharSet으로 둔다.
  2. Assert: charSet은 only single code points를 contain한다.
  3. CharacterComplement(regexpRecord, charSet)를 반환한다.
UnicodePropertyValueExpression :: UnicodePropertyName = UnicodePropertyValue
  1. psUnicodePropertyName이 matched한 source text로 둔다.
  2. pUnicodeMatchProperty(regexpRecord, ps)로 둔다.
  3. Assert: pTable 65의 “Property name and aliases” column에 listed된 Unicode property name 또는 property alias이다.
  4. vsUnicodePropertyValue가 matched한 source text로 둔다.
  5. vUnicodeMatchPropertyValue(p, vs)로 둔다.
  6. charSet을 character database definition이 property p with value v를 include하는 all Unicode code points를 contain하는 CharSet으로 둔다.
  7. MaybeSimpleCaseFolding(regexpRecord, charSet)를 반환한다.
UnicodePropertyValueExpression :: LoneUnicodePropertyNameOrValue
  1. sLoneUnicodePropertyNameOrValue가 matched한 source text로 둔다.
  2. UnicodeMatchPropertyValue(General_Category, s)가 PropertyValueAliases.txt에 listed된 General_Category (gc) property의 Unicode property value 또는 property value alias이면, 다음을 수행한다.
    1. character database definition이 property “General_Category” with value s를 include하는 all Unicode code points를 contain하는 CharSet을 반환한다.
  3. pUnicodeMatchProperty(regexpRecord, s)로 둔다.
  4. Assert: pTable 66의 “Property name and aliases” column에 listed된 binary Unicode property 또는 binary property alias이거나, Table 67의 “Property name” column에 listed된 binary Unicode property of strings이다.
  5. charSet을 character database definition이 property p with value “True”를 include하는 all CharSetElements를 contain하는 CharSet으로 둔다.
  6. MaybeSimpleCaseFolding(regexpRecord, charSet)를 반환한다.
ClassUnion :: ClassSetRange ClassUnionopt
  1. charSet을 argument regexpRecord와 함께 ClassSetRangeCompileToCharSet으로 둔다.
  2. ClassUnion이 present하면, 다음을 수행한다.
    1. otherSet을 argument regexpRecord와 함께 ClassUnionCompileToCharSet으로 둔다.
    2. CharSets charSetotherSet의 union을 반환한다.
  3. charSet을 반환한다.
ClassUnion :: ClassSetOperand ClassUnionopt
  1. charSet을 argument regexpRecord와 함께 ClassSetOperandCompileToCharSet으로 둔다.
  2. ClassUnion이 present하면, 다음을 수행한다.
    1. otherSet을 argument regexpRecord와 함께 ClassUnionCompileToCharSet으로 둔다.
    2. CharSets charSetotherSet의 union을 반환한다.
  3. charSet을 반환한다.
ClassIntersection :: ClassSetOperand && ClassSetOperand
  1. charSet을 argument regexpRecord와 함께 first ClassSetOperandCompileToCharSet으로 둔다.
  2. otherSet을 argument regexpRecord와 함께 second ClassSetOperandCompileToCharSet으로 둔다.
  3. CharSets charSetotherSet의 intersection을 반환한다.
ClassIntersection :: ClassIntersection && ClassSetOperand
  1. charSet을 argument regexpRecord와 함께 ClassIntersectionCompileToCharSet으로 둔다.
  2. otherSet을 argument regexpRecord와 함께 ClassSetOperandCompileToCharSet으로 둔다.
  3. CharSets charSetotherSet의 intersection을 반환한다.
ClassSubtraction :: ClassSetOperand -- ClassSetOperand
  1. charSet을 argument regexpRecord와 함께 first ClassSetOperandCompileToCharSet으로 둔다.
  2. otherSet을 argument regexpRecord와 함께 second ClassSetOperandCompileToCharSet으로 둔다.
  3. otherSet의 CharSetElements도 아닌 charSet의 CharSetElements를 contain하는 CharSet을 반환한다.
ClassSubtraction :: ClassSubtraction -- ClassSetOperand
  1. charSet을 argument regexpRecord와 함께 ClassSubtractionCompileToCharSet으로 둔다.
  2. otherSet을 argument regexpRecord와 함께 ClassSetOperandCompileToCharSet으로 둔다.
  3. otherSet의 CharSetElements도 아닌 charSet의 CharSetElements를 contain하는 CharSet을 반환한다.
ClassSetRange :: ClassSetCharacter - ClassSetCharacter
  1. charSet을 argument regexpRecord와 함께 first ClassSetCharacterCompileToCharSet으로 둔다.
  2. otherSet을 argument regexpRecord와 함께 second ClassSetCharacterCompileToCharSet으로 둔다.
  3. MaybeSimpleCaseFolding(regexpRecord, CharacterRange(charSet, otherSet))를 반환한다.
Note 6

result는 often two or more ranges로 구성됩니다. UnicodeSets가 true이고 IgnoreCase가 true이면, MaybeSimpleCaseFolding(regexpRecord, [Ā-č])는 그 range의 odd-numbered code points만 include합니다.

ClassSetOperand :: ClassSetCharacter
  1. charSet을 argument regexpRecord와 함께 ClassSetCharacterCompileToCharSet으로 둔다.
  2. MaybeSimpleCaseFolding(regexpRecord, charSet)를 반환한다.
ClassSetOperand :: ClassStringDisjunction
  1. charSet을 argument regexpRecord와 함께 ClassStringDisjunctionCompileToCharSet으로 둔다.
  2. MaybeSimpleCaseFolding(regexpRecord, charSet)를 반환한다.
ClassSetOperand :: NestedClass
  1. argument regexpRecord와 함께 NestedClassCompileToCharSet을 반환한다.
NestedClass :: [ ClassContents ]
  1. argument regexpRecord와 함께 ClassContentsCompileToCharSet을 반환한다.
NestedClass :: [^ ClassContents ]
  1. charSet을 argument regexpRecord와 함께 ClassContentsCompileToCharSet으로 둔다.
  2. CharacterComplement(regexpRecord, charSet)를 반환한다.
NestedClass :: \ CharacterClassEscape
  1. argument regexpRecord와 함께 CharacterClassEscapeCompileToCharSet을 반환한다.
ClassStringDisjunction :: \q{ ClassStringDisjunctionContents }
  1. argument regexpRecord와 함께 ClassStringDisjunctionContentsCompileToCharSet을 반환한다.
ClassStringDisjunctionContents :: ClassString
  1. s를 argument regexpRecord와 함께 ClassStringCompileClassSetString으로 둔다.
  2. one string s를 contain하는 CharSet을 반환한다.
ClassStringDisjunctionContents :: ClassString | ClassStringDisjunctionContents
  1. s를 argument regexpRecord와 함께 ClassStringCompileClassSetString으로 둔다.
  2. charSet을 one string s를 contain하는 CharSet으로 둔다.
  3. otherSet을 argument regexpRecord와 함께 ClassStringDisjunctionContentsCompileToCharSet으로 둔다.
  4. CharSets charSetotherSet의 union을 반환한다.
ClassSetCharacter :: SourceCharacter but not ClassSetSyntaxCharacter \ CharacterEscape \ ClassSetReservedPunctuator
  1. charValue를 this ClassSetCharacterCharacterValue로 둔다.
  2. char를 character value가 charValue인 character로 둔다.
  3. single character char를 contain하는 CharSet을 반환한다.
ClassSetCharacter :: \b
  1. single character U+0008 (BACKSPACE)를 contain하는 CharSet을 반환한다.

22.2.2.9.1 CharacterRange ( charSet, otherSet )

The abstract operation CharacterRange takes arguments charSet (a CharSet) and otherSet (a CharSet) and returns a CharSet. It performs the following steps when called:

  1. Assert: charSetotherSet은 각각 exactly one character를 contain한다.
  2. aCharSet charSet 안의 one character로 둔다.
  3. bCharSet otherSet 안의 one character로 둔다.
  4. i를 character a의 character value로 둔다.
  5. j를 character b의 character value로 둔다.
  6. Assert: ij이다.
  7. i부터 j까지의 inclusive interval 안의 character value를 가진 all characters를 contain하는 CharSet을 반환한다.

22.2.2.9.2 HasEitherUnicodeFlag ( regexpRecord )

The abstract operation HasEitherUnicodeFlag takes argument regexpRecord (a RegExp Record) and returns a Boolean. It performs the following steps when called:

  1. regexpRecord.[[Unicode]]true이거나 regexpRecord.[[UnicodeSets]]true이면, true를 반환한다.
  2. false를 반환한다.

22.2.2.9.3 WordCharacters ( regexpRecord )

The abstract operation WordCharacters takes argument regexpRecord (a RegExp Record) and returns a CharSet. \b, \B, \w, 및 \W의 purposes를 위해 “word characters”로 considered되는 characters를 contain하는 CharSet을 반환합니다. It performs the following steps when called:

  1. basicWordCharsASCII word characters 안의 every character를 contain하는 CharSet으로 둔다.
  2. extraWordCharscbasicWordChars 안에 없지만 Canonicalize(regexpRecord, c)가 basicWordChars 안에 있는 all characters c를 contain하는 CharSet으로 둔다.
  3. Assert: HasEitherUnicodeFlag(regexpRecord)가 true이고 regexpRecord.[[IgnoreCase]]true인 경우가 아니면 extraWordChars는 empty이다.
  4. basicWordCharsextraWordChars의 union을 반환한다.

22.2.2.9.4 AllCharacters ( regexpRecord )

The abstract operation AllCharacters takes argument regexpRecord (a RegExp Record) and returns a CharSet. regular expression flags에 따른 “all characters”의 set을 반환합니다. It performs the following steps when called:

  1. regexpRecord.[[UnicodeSets]]true이고 regexpRecord.[[IgnoreCase]]true이면, 다음을 수행한다.
    1. Simple Case Folding mapping을 가지지 않는 all Unicode code points c를 contain하는 CharSet을 반환한다(즉, scf(c)=c).
  2. HasEitherUnicodeFlag(regexpRecord)가 true이면, 다음을 수행한다.
    1. all code point values를 contain하는 CharSet을 반환한다.
  3. all code unit values를 contain하는 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을 반환합니다. Otherwise, Unicode Character Database의 file CaseFolding.txt 안의 Simple Case Folding (scf(codePoint)) definitions(each maps a single code point to another single code point)를 사용하여 charSet의 각 CharSetElement를 character-by-character로 canonical form에 map하고 resulting CharSet을 반환합니다. It performs the following steps when called:

  1. regexpRecord.[[UnicodeSets]]false이거나 regexpRecord.[[IgnoreCase]]false이면, charSet을 반환한다.
  2. otherSet을 새 empty CharSet으로 둔다.
  3. charSet의 각 CharSetElement s에 대해, 다음을 수행한다.
    1. t를 characters의 empty sequence로 둔다.
    2. s 안의 각 single code point codePoint에 대해, 다음을 수행한다.
      1. scf(codePoint)를 t에 append한다.
    3. totherSet에 add한다.
  4. otherSet을 반환한다.

22.2.2.9.6 CharacterComplement ( regexpRecord, complement )

The abstract operation CharacterComplement takes arguments regexpRecord (a RegExp Record) and complement (a CharSet) and returns a CharSet. It performs the following steps when called:

  1. charSetAllCharacters(regexpRecord)로 둔다.
  2. complement의 CharSetElements도 아닌 charSet의 CharSetElements를 contain하는 CharSet을 반환한다.

22.2.2.9.7 UnicodeMatchProperty ( regexpRecord, p )

The abstract operation UnicodeMatchProperty takes arguments regexpRecord (a RegExp Record) and p (ECMAScript source text) and returns a Unicode property name. It performs the following steps when called:

  1. regexpRecord.[[UnicodeSets]]true이고 pTable 67의 “Property name” column에 listed된 Unicode property name이면, 다음을 수행한다.
    1. Unicode code points pList를 반환한다.
  2. Assert: pTable 65 또는 Table 66의 “Property name and aliases” column에 listed된 Unicode property name 또는 property alias이다.
  3. c를 corresponding row의 “Canonical property name” column에 given된 p의 canonical property name으로 둔다.
  4. Unicode code points cList를 반환한다.

Implementations는 Table 65, Table 66, 및 Table 67에 listed된 Unicode property names 및 aliases를 support해야 합니다. interoperability를 ensure하기 위해, implementations는 any other property names 또는 aliases를 support해서는 안 됩니다.

Note 1

예를 들어, Script_Extensions(property name) 및 scx(property alias)는 valid이지만, script_extensions 또는 Scx는 그렇지 않습니다.

Note 2

listed properties는 UTS18 RL1.2가 require하는 것의 superset을 form합니다.

Note 3

these tables의 entries의 spellings(casing 포함)는 Unicode Character Database의 file PropertyAliases.txt에서 used되는 spellings와 match합니다. that file의 precise spellings는 stable하다고 guaranteed됩니다.

Table 65: Non-binary Unicode property aliases and their canonical property names
Property name and aliases Canonical property name
General_Category General_Category
gc
Script Script
sc
Script_Extensions Script_Extensions
scx
Table 66: Binary Unicode property aliases and their canonical property names
Property name and aliases Canonical property name
ASCII ASCII
ASCII_Hex_Digit ASCII_Hex_Digit
AHex
Alphabetic Alphabetic
Alpha
Any Any
Assigned Assigned
Bidi_Control Bidi_Control
Bidi_C
Bidi_Mirrored Bidi_Mirrored
Bidi_M
Case_Ignorable Case_Ignorable
CI
Cased Cased
Changes_When_Casefolded Changes_When_Casefolded
CWCF
Changes_When_Casemapped Changes_When_Casemapped
CWCM
Changes_When_Lowercased Changes_When_Lowercased
CWL
Changes_When_NFKC_Casefolded Changes_When_NFKC_Casefolded
CWKCF
Changes_When_Titlecased Changes_When_Titlecased
CWT
Changes_When_Uppercased Changes_When_Uppercased
CWU
Dash Dash
Default_Ignorable_Code_Point Default_Ignorable_Code_Point
DI
Deprecated Deprecated
Dep
Diacritic Diacritic
Dia
Emoji Emoji
Emoji_Component Emoji_Component
EComp
Emoji_Modifier Emoji_Modifier
EMod
Emoji_Modifier_Base Emoji_Modifier_Base
EBase
Emoji_Presentation Emoji_Presentation
EPres
Extended_Pictographic Extended_Pictographic
ExtPict
Extender Extender
Ext
Grapheme_Base Grapheme_Base
Gr_Base
Grapheme_Extend Grapheme_Extend
Gr_Ext
Hex_Digit Hex_Digit
Hex
IDS_Binary_Operator IDS_Binary_Operator
IDSB
IDS_Trinary_Operator IDS_Trinary_Operator
IDST
ID_Continue ID_Continue
IDC
ID_Start ID_Start
IDS
Ideographic Ideographic
Ideo
Join_Control Join_Control
Join_C
Logical_Order_Exception Logical_Order_Exception
LOE
Lowercase Lowercase
Lower
Math Math
Noncharacter_Code_Point Noncharacter_Code_Point
NChar
Pattern_Syntax Pattern_Syntax
Pat_Syn
Pattern_White_Space Pattern_White_Space
Pat_WS
Quotation_Mark Quotation_Mark
QMark
Radical Radical
Regional_Indicator Regional_Indicator
RI
Sentence_Terminal Sentence_Terminal
STerm
Soft_Dotted Soft_Dotted
SD
Terminal_Punctuation Terminal_Punctuation
Term
Unified_Ideograph Unified_Ideograph
UIdeo
Uppercase Uppercase
Upper
Variation_Selector Variation_Selector
VS
White_Space White_Space
space
XID_Continue XID_Continue
XIDC
XID_Start XID_Start
XIDS
Table 67: Binary Unicode properties of strings
Property name
Basic_Emoji
Emoji_Keycap_Sequence
RGI_Emoji_Modifier_Sequence
RGI_Emoji_Flag_Sequence
RGI_Emoji_Tag_Sequence
RGI_Emoji_ZWJ_Sequence
RGI_Emoji

22.2.2.9.8 UnicodeMatchPropertyValue ( p, v )

The abstract operation UnicodeMatchPropertyValue takes arguments p (ECMAScript source text) and v (ECMAScript source text) and returns a Unicode property value. It performs the following steps when called:

  1. Assert: pTable 65의 “Canonical property name” column에 listed된 canonical, unaliased Unicode property name이다.
  2. Assert: v는 Unicode property p에 대한 property value 또는 property value alias이며, PropertyValueAliases.txt에 listed되어 있다.
  3. value를 corresponding row의 “Canonical property value” column에 given된 v의 canonical property value로 둔다.
  4. Unicode code points valueList를 반환한다.

Implementations는 Table 65에 listed된 properties에 대해 PropertyValueAliases.txt에 listed된 Unicode property values 및 property value aliases를 support해야 합니다. interoperability를 ensure하기 위해, implementations는 any other property values 또는 property value aliases를 support해서는 안 됩니다.

Note 1

예를 들어, XpeoOld_Persian은 valid Script_Extensions values이지만, xpeoOld Persian은 그렇지 않습니다.

Note 2

이 algorithm은 UAX44에 listed된 symbolic values에 대한 matching rules와 다릅니다: case, white space, U+002D (HYPHEN-MINUS), 및 U+005F (LOW LINE)는 ignored되지 않고, Is prefix는 supported되지 않습니다.

22.2.2.10 Runtime Semantics: CompileClassSetString

The syntax-directed operation CompileClassSetString takes argument regexpRecord (a RegExp Record) and returns a sequence of characters. It is defined piecewise over the following productions:

ClassString :: [empty]
  1. characters의 empty sequence를 반환한다.
ClassString :: NonEmptyClassString
  1. argument regexpRecord와 함께 NonEmptyClassStringCompileClassSetString을 반환한다.
NonEmptyClassString :: ClassSetCharacter NonEmptyClassStringopt
  1. cs를 argument regexpRecord와 함께 ClassSetCharacterCompileToCharSet으로 둔다.
  2. s1cs의 single CharSetElement인 characters의 sequence로 둔다.
  3. NonEmptyClassString이 present하면, 다음을 수행한다.
    1. s2를 argument regexpRecord와 함께 NonEmptyClassStringCompileClassSetString으로 둔다.
    2. s1s2의 concatenation을 반환한다.
  4. s1을 반환한다.

22.2.3 RegExp 생성용 Abstract Operations

22.2.3.1 RegExpCreate ( pattern, flags )

The abstract operation RegExpCreate takes arguments pattern (an ECMAScript language value) and flags (a String or undefined) and returns either a normal completion containing an Object or a throw completion. It performs the following steps when called:

  1. obj를 ! RegExpAlloc(%RegExp%)로 둔다.
  2. RegExpInitialize(obj, pattern, flags)를 반환한다.

22.2.3.2 RegExpAlloc ( newTarget )

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

  1. obj를 ? OrdinaryCreateFromConstructor(newTarget, "%RegExp.prototype%", « [[OriginalSource]], [[OriginalFlags]], [[RegExpRecord]], [[RegExpMatcher]] »)로 둔다.
  2. DefinePropertyOrThrow(obj, "lastIndex", PropertyDescriptor { [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false })를 수행한다.
  3. obj를 반환한다.

22.2.3.3 RegExpInitialize ( obj, pattern, flags )

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

  1. patternundefined이면, pattern을 empty String으로 설정한다.
  2. Else, pattern을 ? ToString(pattern)으로 설정한다.
  3. flagsundefined이면, flags를 empty String으로 설정한다.
  4. Else, flags를 ? ToString(flags)로 설정한다.
  5. flags"d", "g", "i", "m", "s", "u", "v", 또는 "y" 이외의 any code unit을 contain하면, SyntaxError exception을 throw한다.
  6. flags가 any code unit을 more than once contain하면, SyntaxError exception을 throw한다.
  7. flags"i"를 contain하면, itrue로 둔다; else ifalse로 둔다.
  8. flags"m"를 contain하면, mtrue로 둔다; else mfalse로 둔다.
  9. flags"s"를 contain하면, strue로 둔다; else sfalse로 둔다.
  10. flags"u"를 contain하면, utrue로 둔다; else ufalse로 둔다.
  11. flags"v"를 contain하면, vtrue로 둔다; else vfalse로 둔다.
  12. utrue이거나 vtrue이면, 다음을 수행한다.
    1. patternTextStringToCodePoints(pattern)로 둔다.
  13. Else,
    1. patternTextpattern의 각 16-bit element를 Unicode BMP code point로 interpreting한 result로 둔다. UTF-16 decoding은 elements에 applied되지 않는다.
  14. parseResultParsePattern(patternText, u, v)로 둔다.
  15. parseResultSyntaxError objects의 non-empty List이면, SyntaxError exception을 throw한다.
  16. Assert: parseResultPattern Parse Node이다.
  17. obj.[[OriginalSource]]pattern으로 설정한다.
  18. obj.[[OriginalFlags]]flags로 설정한다.
  19. capturingGroupsCountCountLeftCapturingParensWithin(parseResult)로 둔다.
  20. regexpRecordRegExp Record { [[IgnoreCase]]: i, [[Multiline]]: m, [[DotAll]]: s, [[Unicode]]: u, [[UnicodeSets]]: v, [[CapturingGroupsCount]]: capturingGroupsCount }로 둔다.
  21. obj.[[RegExpRecord]]regexpRecord로 설정한다.
  22. obj.[[RegExpMatcher]]를 argument regexpRecord와 함께 parseResultCompilePattern으로 설정한다.
  23. Set(obj, "lastIndex", +0𝔽, true)를 수행한다.
  24. obj를 반환한다.

22.2.3.4 Static Semantics: ParsePattern ( patternText, u, v )

The abstract operation ParsePattern takes arguments patternText (a sequence of Unicode code points), u (a Boolean), and v (a Boolean) and returns a Parse Node or a non-empty List of SyntaxError objects.

Note

이 section은 B.1.2.9에서 amended됩니다.

It performs the following steps when called:

  1. vtrue이고 utrue이면, 다음을 수행한다.
    1. parseResult를 one or more SyntaxError objects를 contain하는 List로 둔다.
  2. Else if vtrue이면, 다음을 수행한다.
    1. parseResultParseText(patternText, Pattern[+UnicodeMode, +UnicodeSetsMode, +NamedCaptureGroups])로 둔다.
  3. Else if utrue이면, 다음을 수행한다.
    1. parseResultParseText(patternText, Pattern[+UnicodeMode, ~UnicodeSetsMode, +NamedCaptureGroups])로 둔다.
  4. Else,
    1. parseResultParseText(patternText, Pattern[~UnicodeMode, ~UnicodeSetsMode, +NamedCaptureGroups])로 둔다.
  5. parseResult를 반환한다.

22.2.4 The RegExp Constructor

RegExp constructor는:

  • %RegExp%입니다.
  • global object"RegExp" property의 initial value입니다.
  • constructor로 called될 때 new RegExp object를 create하고 initialize합니다.
  • constructor가 아니라 function으로 called될 때, new RegExp object 또는 only argument가 RegExp object인 경우 argument itself를 반환합니다.
  • class definition의 extends clause의 value로 사용될 수 있습니다. specified RegExp behaviour를 inherit하려는 subclass constructors는 necessary internal slots를 가진 subclass instances를 create하고 initialize하기 위해 RegExp constructor에 대한 super call을 include해야 합니다.

22.2.4.1 RegExp ( patternOrRegexp, flags )

이 function은 called될 때 다음 steps를 수행합니다:

  1. patternIsRegExp를 ? IsRegExp(patternOrRegexp)로 둔다.
  2. NewTarget이 undefined이면, 다음을 수행한다.
    1. newTarget을 active function object로 둔다.
    2. patternIsRegExptrue이고 flagsundefined이면, 다음을 수행한다.
      1. patternCtor를 ? Get(patternOrRegexp, "constructor")로 둔다.
      2. SameValue(newTarget, patternCtor)가 true이면, patternOrRegexp를 반환한다.
  3. Else,
    1. newTarget을 NewTarget으로 둔다.
  4. patternOrRegexp가 Object이고 patternOrRegexp[[RegExpMatcher]] internal slot을 가지면, 다음을 수행한다.
    1. patternSourcepatternOrRegexp.[[OriginalSource]]로 둔다.
    2. flagsundefined이면, flagspatternOrRegexp.[[OriginalFlags]]로 설정한다.
  5. Else if patternIsRegExptrue이면, 다음을 수행한다.
    1. patternSource를 ? Get(patternOrRegexp, "source")로 둔다.
    2. flagsundefined이면, 다음을 수행한다.
      1. flags를 ? Get(patternOrRegexp, "flags")로 설정한다.
  6. Else,
    1. patternSourcepatternOrRegexp로 둔다.
  7. obj를 ? RegExpAlloc(newTarget)으로 둔다.
  8. RegExpInitialize(obj, patternSource, flags)를 반환한다.
Note

pattern이 StringLiteral을 사용하여 supplied되면, String이 이 function에 의해 processed되기 전에 usual escape sequence substitutions가 performed됩니다. pattern이 이 function에 의해 recognized되기 위해 escape sequence를 contain해야 한다면, any U+005C (REVERSE SOLIDUS) code points는 StringLiteral의 contents가 formed될 때 removed되는 것을 prevent하기 위해 StringLiteral 안에서 escaped되어야 합니다.

22.2.5 Properties of the RegExp Constructor

RegExp constructor는:

  • value가 %Function.prototype%[[Prototype]] internal slot을 가집니다.
  • 다음 properties를 가집니다:

22.2.5.1 RegExp.escape ( string )

이 function은 regular expression Pattern에서 potentially special한 characters가 equivalent escape sequences로 replaced된 string의 copy를 반환합니다.

called될 때 다음 steps를 수행합니다:

  1. string이 String이 아니면, TypeError exception을 throw한다.
  2. escaped를 empty String으로 둔다.
  3. codePointListStringToCodePoints(string)로 둔다.
  4. codePointList의 각 code point codePoint에 대해, 다음을 수행한다.
    1. escaped가 empty String이고 codePointDecimalDigit 또는 AsciiLetter에 의해 matched되면, 다음을 수행한다.
      1. NOTE: leading digit를 escaping하면 output이 \0 character escape 또는 \1 같은 DecimalEscape 뒤에서 사용될 수 있는 pattern text와 correspond하고, preceding escape sequence의 extension으로 interpreted되는 대신 still string을 match하게 된다. leading ASCII letter를 escaping하는 것도 \c 뒤의 context에 대해 같은 일을 한다.
      2. numericValuecodePoint의 numeric value로 둔다.
      3. hexNumber::toString(𝔽(numericValue), 16)으로 둔다.
      4. Assert: hex의 length는 2이다.
      5. escaped를 code unit 0x005C (REVERSE SOLIDUS), "x", 및 hexstring-concatenation으로 설정한다.
    2. Else,
      1. escapedescapedEncodeForRegExpEscape(codePoint)의 string-concatenation으로 설정한다.
  5. escaped를 반환한다.
Note

similar names를 가지고 있음에도, EscapeRegExpPatternRegExp.escape는 similar actions를 수행하지 않습니다. former는 string으로 representation하기 위해 pattern을 escapes하는 반면, 이 function은 pattern 안에서 representation하기 위해 string을 escapes합니다.

22.2.5.1.1 EncodeForRegExpEscape ( codePoint )

The abstract operation EncodeForRegExpEscape takes argument codePoint (a code point) and returns a String. codePoint를 matching하기 위한 Pattern을 representing하는 String을 반환합니다. codePoint가 white space 또는 ASCII punctuator이면, returned value는 escape sequence입니다. Otherwise, returned value는 codePoint itself의 String representation입니다. It performs the following steps when called:

  1. codePointSyntaxCharacter에 의해 matched되거나 codePoint가 U+002F (SOLIDUS)이면, 다음을 수행한다.
    1. 0x005C (REVERSE SOLIDUS)와 UTF16EncodeCodePoint(codePoint)의 string-concatenation을 반환한다.
  2. codePointTable 63의 “Code Point” column에 listed된 code point이면, 다음을 수행한다.
    1. 0x005C (REVERSE SOLIDUS)와 “Code Point” column이 codePoint를 contain하는 row의 “ControlEscape” column 안의 string의 string-concatenation을 반환한다.
  3. otherPunctuators",-=<>#&!%:;@~'`"와 code unit 0x0022 (QUOTATION MARK)의 string-concatenation으로 둔다.
  4. toEscapeStringToCodePoints(otherPunctuators)로 둔다.
  5. toEscapecodePoint를 contain하거나, codePointWhiteSpace 또는 LineTerminator에 의해 matched되거나, codePointleading surrogate 또는 trailing surrogate와 same numeric value를 가지면, 다음을 수행한다.
    1. codePointNumbercodePoint의 numeric value로 둔다.
    2. codePointNumber ≤ 0xFF이면, 다음을 수행한다.
      1. hexNumber::toString(𝔽(codePointNumber), 16)으로 둔다.
      2. code unit 0x005C (REVERSE SOLIDUS), "x", 및 StringPad(hex, 2, "0", start)의 string-concatenation을 반환한다.
    3. escaped를 empty String으로 둔다.
    4. codeUnitsUTF16EncodeCodePoint(codePoint)로 둔다.
    5. codeUnits의 각 code unit codeUnit에 대해, 다음을 수행한다.
      1. escapedescapedUnicodeEscape(codeUnit)의 string-concatenation으로 설정한다.
    6. escaped를 반환한다.
  6. UTF16EncodeCodePoint(codePoint)를 반환한다.

22.2.5.2 RegExp.prototype

RegExp.prototype의 initial value는 RegExp prototype object입니다.

이 property는 attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }를 가집니다.

22.2.5.3 get RegExp [ %Symbol.species% ]

RegExp[%Symbol.species%]는 set accessor function이 undefinedaccessor property입니다. Its get accessor function은 called될 때 다음 steps를 수행합니다:

  1. this value를 반환한다.

이 function의 "name" property의 value는 "get [Symbol.species]"입니다.

Note

RegExp prototype methods는 normally their this value의 constructor를 사용하여 derived object를 create합니다. However, subclass constructor는 its %Symbol.species% property를 redefining하여 that 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의 any other internal slots를 가지지 않습니다.
  • value가 %Object.prototype%[[Prototype]] internal slot을 가집니다.
Note

RegExp prototype object는 its own "valueOf" property를 가지지 않습니다; however, Object prototype object로부터 "valueOf" property를 inherits합니다.

22.2.6.1 RegExp.prototype.constructor

RegExp.prototype.constructor의 initial value는 %RegExp%입니다.

22.2.6.2 RegExp.prototype.exec ( string )

이 method는 regular expression pattern의 occurrence를 string에서 searches하고 match의 results를 contain하는 Array 또는 string이 match하지 않은 경우 null을 반환합니다.

called될 때 다음 steps를 수행합니다:

  1. regexpthis value로 둔다.
  2. RequireInternalSlot(regexp, [[RegExpMatcher]])를 수행한다.
  3. string을 ? ToString(string)으로 설정한다.
  4. RegExpBuiltinExec(regexp, string)를 반환한다.

22.2.6.3 get RegExp.prototype.dotAll

RegExp.prototype.dotAll은 set accessor function이 undefinedaccessor property입니다. Its get accessor function은 called될 때 다음 steps를 수행합니다:

  1. regexpthis value로 둔다.
  2. codeUnit을 code unit 0x0073 (LATIN SMALL LETTER S)로 둔다.
  3. RegExpHasFlag(regexp, codeUnit)를 반환한다.

22.2.6.4 get RegExp.prototype.flags

RegExp.prototype.flags는 set accessor function이 undefinedaccessor property입니다. Its get accessor function은 called될 때 다음 steps를 수행합니다:

  1. regexpthis value로 둔다.
  2. regexp가 Object가 아니면, TypeError exception을 throw한다.
  3. codeUnits를 새 empty List로 둔다.
  4. hasIndicesToBoolean(? Get(regexp, "hasIndices"))로 둔다.
  5. hasIndicestrue이면, code unit 0x0064 (LATIN SMALL LETTER D)를 codeUnits에 append한다.
  6. globalToBoolean(? Get(regexp, "global"))로 둔다.
  7. globaltrue이면, code unit 0x0067 (LATIN SMALL LETTER G)를 codeUnits에 append한다.
  8. ignoreCaseToBoolean(? Get(regexp, "ignoreCase"))로 둔다.
  9. ignoreCasetrue이면, code unit 0x0069 (LATIN SMALL LETTER I)를 codeUnits에 append한다.
  10. multilineToBoolean(? Get(regexp, "multiline"))로 둔다.
  11. multilinetrue이면, code unit 0x006D (LATIN SMALL LETTER M)를 codeUnits에 append한다.
  12. dotAllToBoolean(? Get(regexp, "dotAll"))로 둔다.
  13. dotAlltrue이면, code unit 0x0073 (LATIN SMALL LETTER S)를 codeUnits에 append한다.
  14. unicodeToBoolean(? Get(regexp, "unicode"))로 둔다.
  15. unicodetrue이면, code unit 0x0075 (LATIN SMALL LETTER U)를 codeUnits에 append한다.
  16. unicodeSetsToBoolean(? Get(regexp, "unicodeSets"))로 둔다.
  17. unicodeSetstrue이면, code unit 0x0076 (LATIN SMALL LETTER V)를 codeUnits에 append한다.
  18. stickyToBoolean(? Get(regexp, "sticky"))로 둔다.
  19. stickytrue이면, code unit 0x0079 (LATIN SMALL LETTER Y)를 codeUnits에 append한다.
  20. code units가 List codeUnits의 elements인 String value를 반환한다. codeUnits가 elements를 가지지 않으면, empty String이 returned된다.

22.2.6.4.1 RegExpHasFlag ( regexp, codeUnit )

The abstract operation RegExpHasFlag takes arguments regexp (an ECMAScript language value) and codeUnit (a code unit) and returns either a normal completion containing either a Boolean or undefined, or a throw completion. It performs the following steps when called:

  1. regexp가 Object가 아니면, TypeError exception을 throw한다.
  2. regexp[[OriginalFlags]] internal slot을 가지지 않으면, 다음을 수행한다.
    1. SameValue(regexp, %RegExp.prototype%)가 true이면, undefined를 반환한다.
    2. TypeError exception을 throw한다.
  3. flagsregexp.[[OriginalFlags]]로 둔다.
  4. flagscodeUnit을 contain하면, true를 반환한다.
  5. false를 반환한다.

22.2.6.5 get RegExp.prototype.global

RegExp.prototype.global은 set accessor function이 undefinedaccessor property입니다. Its get accessor function은 called될 때 다음 steps를 수행합니다:

  1. regexpthis value로 둔다.
  2. codeUnit을 code unit 0x0067 (LATIN SMALL LETTER G)로 둔다.
  3. RegExpHasFlag(regexp, codeUnit)를 반환한다.

22.2.6.6 get RegExp.prototype.hasIndices

RegExp.prototype.hasIndices는 set accessor function이 undefinedaccessor property입니다. Its get accessor function은 called될 때 다음 steps를 수행합니다:

  1. regexpthis value로 둔다.
  2. codeUnit을 code unit 0x0064 (LATIN SMALL LETTER D)로 둔다.
  3. RegExpHasFlag(regexp, codeUnit)를 반환한다.

22.2.6.7 get RegExp.prototype.ignoreCase

RegExp.prototype.ignoreCase는 set accessor function이 undefinedaccessor property입니다. Its get accessor function은 called될 때 다음 steps를 수행합니다:

  1. regexpthis value로 둔다.
  2. codeUnit을 code unit 0x0069 (LATIN SMALL LETTER I)로 둔다.
  3. RegExpHasFlag(regexp, codeUnit)를 반환한다.

22.2.6.8 RegExp.prototype [ %Symbol.match% ] ( string )

이 method는 called될 때 다음 steps를 수행합니다:

  1. regexpthis value로 둔다.
  2. regexp가 Object가 아니면, TypeError exception을 throw한다.
  3. string을 ? ToString(string)으로 설정한다.
  4. flags를 ? ToString(? Get(regexp, "flags"))로 둔다.
  5. flags"g"를 contain하지 않으면, ? RegExpExec(regexp, string)를 반환한다.
  6. flags"u"를 contain하거나 flags"v"를 contain하면 fullUnicodetrue로 둔다; else fullUnicodefalse로 둔다.
  7. Set(regexp, "lastIndex", +0𝔽, true)를 수행한다.
  8. array를 ! ArrayCreate(0)으로 둔다.
  9. matchCount를 0으로 둔다.
  10. Repeat,
    1. result를 ? RegExpExec(regexp, string)로 둔다.
    2. resultnull이면, 다음을 수행한다.
      1. matchCount = 0이면, null을 반환한다.
      2. array를 반환한다.
    3. matchString을 ? ToString(? Get(result, "0"))으로 둔다.
    4. CreateDataPropertyOrThrow(array, ! ToString(𝔽(matchCount)), matchString)를 수행한다.
    5. matchString이 empty String이면, 다음을 수행한다.
      1. thisIndex(? ToLength(? Get(regexp, "lastIndex")))로 둔다.
      2. nextIndexAdvanceStringIndex(string, thisIndex, fullUnicode)로 둔다.
      3. Set(regexp, "lastIndex", 𝔽(nextIndex), true)를 수행한다.
    6. matchCountmatchCount + 1로 설정한다.

이 method의 "name" property의 value는 "[Symbol.match]"입니다.

Note

%Symbol.match% property는 regular expressions의 basic behaviour를 가진 objects를 identify하기 위해 IsRegExp abstract operation에 의해 사용됩니다. %Symbol.match% property의 absence 또는 Boolean coerce to true하지 않는 value를 가진 such property의 existence는 object가 regular expression object로 used될 intended가 아님을 indicates합니다.

22.2.6.9 RegExp.prototype [ %Symbol.matchAll% ] ( string )

이 method는 called될 때 다음 steps를 수행합니다:

  1. regexpthis value로 둔다.
  2. regexp가 Object가 아니면, TypeError exception을 throw한다.
  3. string을 ? ToString(string)으로 설정한다.
  4. speciesCtor를 ? SpeciesConstructor(regexp, %RegExp%)로 둔다.
  5. flags를 ? ToString(? Get(regexp, "flags"))로 둔다.
  6. matcher를 ? Construct(speciesCtor, « regexp, flags »)로 둔다.
  7. lastIndex를 ? ToLength(? Get(regexp, "lastIndex"))로 둔다.
  8. Set(matcher, "lastIndex", lastIndex, true)를 수행한다.
  9. flags"g"를 contain하면, globaltrue로 둔다.
  10. Else, globalfalse로 둔다.
  11. flags"u"를 contain하거나 flags"v"를 contain하면, fullUnicodetrue로 둔다.
  12. Else, fullUnicodefalse로 둔다.
  13. CreateRegExpStringIterator(matcher, string, global, fullUnicode)를 반환한다.

이 method의 "name" property의 value는 "[Symbol.matchAll]"입니다.

22.2.6.10 get RegExp.prototype.multiline

RegExp.prototype.multiline은 set accessor function이 undefinedaccessor property입니다. Its get accessor function은 called될 때 다음 steps를 수행합니다:

  1. regexpthis value로 둔다.
  2. codeUnit을 code unit 0x006D (LATIN SMALL LETTER M)로 둔다.
  3. RegExpHasFlag(regexp, codeUnit)를 반환한다.

22.2.6.11 RegExp.prototype [ %Symbol.replace% ] ( string, replaceValue )

이 method는 called될 때 다음 steps를 수행합니다:

  1. regexpthis value로 둔다.
  2. regexp가 Object가 아니면, TypeError exception을 throw한다.
  3. string을 ? ToString(string)으로 설정한다.
  4. stringLengthstring의 length로 둔다.
  5. functionalReplaceIsCallable(replaceValue)로 둔다.
  6. functionalReplacefalse이면, 다음을 수행한다.
    1. replaceValue를 ? ToString(replaceValue)로 설정한다.
  7. flags를 ? ToString(? Get(regexp, "flags"))로 둔다.
  8. flags"g"를 contain하면 globaltrue로 둔다; else globalfalse로 둔다.
  9. globaltrue이면, 다음을 수행한다.
    1. Set(regexp, "lastIndex", +0𝔽, true)를 수행한다.
  10. results를 새 empty List로 둔다.
  11. donefalse로 둔다.
  12. Repeat, while done is false,
    1. result를 ? RegExpExec(regexp, string)로 둔다.
    2. resultnull이면, 다음을 수행한다.
      1. donetrue로 설정한다.
    3. Else,
      1. resultresults에 append한다.
      2. globalfalse이면, 다음을 수행한다.
        1. donetrue로 설정한다.
      3. Else,
        1. matchString을 ? ToString(? Get(result, "0"))으로 둔다.
        2. matchString이 empty String이면, 다음을 수행한다.
          1. thisIndex(? ToLength(? Get(regexp, "lastIndex")))로 둔다.
          2. flags"u"를 contain하거나 flags"v"를 contain하면 fullUnicodetrue로 둔다; else fullUnicodefalse로 둔다.
          3. nextIndexAdvanceStringIndex(string, thisIndex, fullUnicode)로 둔다.
          4. Set(regexp, "lastIndex", 𝔽(nextIndex), true)를 수행한다.
  13. accumulatedResult를 empty String으로 둔다.
  14. nextSourcePosition을 0으로 둔다.
  15. results의 각 element result에 대해, 다음을 수행한다.
    1. resultLength를 ? LengthOfArrayLike(result)로 둔다.
    2. capturesCountmax(resultLength - 1, 0)으로 둔다.
    3. matched를 ? ToString(? Get(result, "0"))으로 둔다.
    4. matchLengthmatched의 length로 둔다.
    5. position을 ? ToIntegerOrInfinity(? Get(result, "index"))로 둔다.
    6. position을 0과 stringLength 사이로 clamping한 result로 설정한다.
    7. captures를 새 empty List로 둔다.
    8. captureNumber를 1로 둔다.
    9. Repeat, while captureNumbercapturesCount,
      1. capture를 ? Get(result, ! ToString(𝔽(captureNumber)))로 둔다.
      2. captureundefined가 아니면, 다음을 수행한다.
        1. capture를 ? ToString(capture)로 설정한다.
      3. capturecaptures에 append한다.
      4. NOTE: captureNumber = 1일 때, preceding step은 first element를 captures 안에 넣는다(index 0에). More generally, captureNumberth capture(captureNumberth set of capturing parentheses에 의해 captured된 characters)는 captures[captureNumber - 1]에 있다.
      5. captureNumbercaptureNumber + 1로 설정한다.
    10. namedCaptures를 ? Get(result, "groups")로 둔다.
    11. functionalReplacetrue이면, 다음을 수행한다.
      1. replacerArgs를 « matched », captures, 및 « 𝔽(position), string »의 list-concatenation으로 둔다.
      2. namedCapturesundefined가 아니면, 다음을 수행한다.
        1. namedCapturesreplacerArgs에 append한다.
      3. replacementValue를 ? Call(replaceValue, undefined, replacerArgs)로 둔다.
      4. replacementString을 ? ToString(replacementValue)로 둔다.
    12. Else,
      1. namedCapturesundefined가 아니면, 다음을 수행한다.
        1. namedCaptures를 ? ToObject(namedCaptures)로 설정한다.
      2. replacementString을 ? GetSubstitution(matched, string, position, captures, namedCaptures, replaceValue)로 둔다.
    13. positionnextSourcePosition이면, 다음을 수행한다.
      1. NOTE: position은 normally backwards로 move해서는 안 된다. 그렇게 된다면, ill-behaving RegExp subclass 또는 global flag나 regexp의 other characteristics를 change하는 access triggered side-effect의 사용을 indication한다. such cases에서, corresponding substitution은 ignored된다.
      2. accumulatedResultaccumulatedResult, stringnextSourcePosition부터 position까지의 substring, 및 replacementStringstring-concatenation으로 설정한다.
      3. nextSourcePositionposition + matchLength로 설정한다.
  16. nextSourcePositionstringLength이면, accumulatedResult를 반환한다.
  17. accumulatedResultstringnextSourcePosition부터의 substringstring-concatenation을 반환한다.

이 method의 "name" property의 value는 "[Symbol.replace]"입니다.

22.2.6.12 RegExp.prototype [ %Symbol.search% ] ( string )

이 method는 called될 때 다음 steps를 수행합니다:

  1. regexpthis value로 둔다.
  2. regexp가 Object가 아니면, TypeError exception을 throw한다.
  3. string을 ? ToString(string)으로 설정한다.
  4. previousLastIndex를 ? Get(regexp, "lastIndex")로 둔다.
  5. previousLastIndex+0𝔽가 아니면, 다음을 수행한다.
    1. Set(regexp, "lastIndex", +0𝔽, true)를 수행한다.
  6. result를 ? RegExpExec(regexp, string)로 둔다.
  7. currentLastIndex를 ? Get(regexp, "lastIndex")로 둔다.
  8. SameValue(currentLastIndex, previousLastIndex)가 false이면, 다음을 수행한다.
    1. Set(regexp, "lastIndex", previousLastIndex, true)를 수행한다.
  9. resultnull이면, -1𝔽를 반환한다.
  10. Get(result, "index")를 반환한다.

이 method의 "name" property의 value는 "[Symbol.search]"입니다.

Note

이 RegExp object의 "lastIndex""global" properties의 value는 search를 performing할 때 ignored됩니다. "lastIndex" property는 unchanged로 남습니다.

22.2.6.13 get RegExp.prototype.source

RegExp.prototype.source는 set accessor function이 undefinedaccessor property입니다. Its get accessor function은 called될 때 다음 steps를 수행합니다:

  1. regexpthis value로 둔다.
  2. regexp가 Object가 아니면, TypeError exception을 throw한다.
  3. regexp[[OriginalSource]] internal slot을 가지지 않으면, 다음을 수행한다.
    1. SameValue(regexp, %RegExp.prototype%)가 true이면, "(?:)"를 반환한다.
    2. TypeError exception을 throw한다.
  4. Assert: regexp[[OriginalFlags]] internal slot을 가진다.
  5. sourceregexp.[[OriginalSource]]로 둔다.
  6. flagsregexp.[[OriginalFlags]]로 둔다.
  7. EscapeRegExpPattern(source, flags)를 반환한다.

22.2.6.13.1 EscapeRegExpPattern ( pattern, flags )

The abstract operation EscapeRegExpPattern takes arguments pattern (a String) and flags (a String) and returns a String. It performs the following steps when called:

  1. flags"v"를 contain하면, 다음을 수행한다.
    1. patternSymbolPattern[+UnicodeMode, +UnicodeSetsMode]로 둔다.
  2. Else if flags"u"를 contain하면, 다음을 수행한다.
    1. patternSymbolPattern[+UnicodeMode, ~UnicodeSetsMode]로 둔다.
  3. Else,
    1. patternSymbolPattern[~UnicodeMode, ~UnicodeSetsMode]로 둔다.
  4. escapedPattern을 UTF-16 encoded Unicode code points(6.1.4)로 interpreted된 pattern과 equivalent한 patternSymbol의 form인 String으로 두며, 그 안에서 certain code points는 below에 described된 대로 escaped된다. escapedPatternpattern과 differ할 수도 있고 differ하지 않을 수도 있다; however, escapedPatternpatternSymbol로 evaluating하여 result하는 Abstract Closure는 constructed object의 [[RegExpMatcher]] internal slot이 given하는 Abstract Closure와 identically behave해야 한다. same values for pattern and flags를 사용하여 이 abstract operation을 multiple calls하면 identical results를 produce해야 한다.
  5. pattern 안에 occurring하는 code points / 또는 any LineTerminatorescapedPattern 안에서, "/", escapedPattern, "/", 및 flagsstring-concatenation이 constructed regular expression과 identically behave하는 RegularExpressionLiteral로(in an appropriate lexical context) parsed될 수 있도록 necessary하게 escaped되어야 한다. 예를 들어, pattern"/"이면 escapedPattern은 among other possibilities "\/" 또는 "\u002F"일 수 있지만, "/"일 수는 없다. 왜냐하면 flags가 followed되는 ///RegularExpressionLiteral이 아니라 SingleLineComment로 parsed될 것이기 때문이다. pattern이 empty String이면, 이 specification은 escapedPattern"(?:)"로 두어 met될 수 있다.
  6. escapedPattern을 반환한다.
Note

similar names를 가지고 있음에도, RegExp.escape와 EscapeRegExpPattern은 similar actions를 수행하지 않습니다. former는 pattern 안에서 representation하기 위해 string을 escapes하는 반면, 이 function은 string으로 representation하기 위해 pattern을 escapes합니다.

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로 searching하여 determined됩니다; 이러한 occurrences는 returned array 안의 any String의 part가 아니지만, String value를 divide up하는 역할을 합니다.

this value는 empty regular expression 또는 empty String을 match할 수 있는 regular expression일 수 있습니다. 이 경우, 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와 equal하고, 각 substring은 one code unit을 contain합니다.) backtracking이 해당 index에서 non-empty substring match를 yield할 수 있더라도, String의 given index에서 first match만 considered됩니다. (예를 들어, /a*?/[Symbol.split]("ab")는 array ["a", "b"]로 evaluates되는 반면, /a*/[Symbol.split]("ab")는 array ["","b"]로 evaluates됩니다.)

string이 empty String이거나 empty String으로 converts되면, result는 regular expression이 empty String을 match할 수 있는지 여부에 depends합니다. match할 수 있으면, result array는 no elements를 contain합니다. Otherwise, result array는 one element를 contain하며, 이는 empty String입니다.

regular expression이 capturing parentheses를 contain하면, separator가 matched될 때마다 capturing parentheses의 results(any undefined results 포함)가 output array에 spliced됩니다. 예를 들어,

/<(\/)?([^<>]+)>/[Symbol.split]("A<B>bold</B>and<CODE>coded</CODE>")

는 array로 evaluates됩니다

["A", undefined, "B", "bold", "/", "B", "and", undefined, "CODE", "coded", "/", "CODE", ""]

limitundefined가 아니면, output array는 no more than limit elements를 contain하도록 truncated됩니다.

이 method는 called될 때 다음 steps를 수행합니다:

  1. regexpthis value로 둔다.
  2. regexp가 Object가 아니면, TypeError exception을 throw한다.
  3. string을 ? ToString(string)으로 설정한다.
  4. speciesCtor를 ? SpeciesConstructor(regexp, %RegExp%)로 둔다.
  5. flags를 ? ToString(? Get(regexp, "flags"))로 둔다.
  6. flags"u"를 contain하거나 flags"v"를 contain하면, unicodeMatchingtrue로 둔다.
  7. Else, unicodeMatchingfalse로 둔다.
  8. flags"y"를 contain하면, newFlagsflags로 둔다.
  9. Else, newFlagsflags"y"string-concatenation으로 둔다.
  10. splitter를 ? Construct(speciesCtor, « regexp, newFlags »)로 둔다.
  11. array를 ! ArrayCreate(0)으로 둔다.
  12. lengthA를 0으로 둔다.
  13. limitundefined이면 lim을 232 - 1로 둔다; else lim(? ToUint32(limit))로 둔다.
  14. lim = 0이면, array를 반환한다.
  15. string이 empty String이면, 다음을 수행한다.
    1. matchResult를 ? RegExpExec(splitter, string)로 둔다.
    2. matchResultnull이 아니면, array를 반환한다.
    3. CreateDataPropertyOrThrow(array, "0", string)를 수행한다.
    4. array를 반환한다.
  16. sizestring의 length로 둔다.
  17. lastMatchEnd를 0으로 둔다.
  18. searchIndexlastMatchEnd로 둔다.
  19. Repeat, while searchIndex < size,
    1. Set(splitter, "lastIndex", 𝔽(searchIndex), true)를 수행한다.
    2. matchResult를 ? RegExpExec(splitter, string)로 둔다.
    3. matchResultnull이면, 다음을 수행한다.
      1. searchIndexAdvanceStringIndex(string, searchIndex, unicodeMatching)로 설정한다.
    4. Else,
      1. matchEnd(? ToLength(? Get(splitter, "lastIndex")))로 둔다.
      2. matchEndmin(matchEnd, size)로 설정한다.
      3. matchEnd = lastMatchEnd이면, 다음을 수행한다.
        1. searchIndexAdvanceStringIndex(string, searchIndex, unicodeMatching)로 설정한다.
      4. Else,
        1. substringstringlastMatchEnd부터 searchIndex까지의 substring으로 둔다.
        2. CreateDataPropertyOrThrow(array, ! ToString(𝔽(lengthA)), substring)를 수행한다.
        3. lengthAlengthA + 1로 설정한다.
        4. lengthA = lim이면, array를 반환한다.
        5. lastMatchEndmatchEnd로 설정한다.
        6. numberOfCaptures를 ? LengthOfArrayLike(matchResult)로 둔다.
        7. numberOfCapturesmax(numberOfCaptures - 1, 0)으로 설정한다.
        8. captureIndex를 1로 둔다.
        9. Repeat, while captureIndexnumberOfCaptures,
          1. nextCapture를 ? Get(matchResult, ! ToString(𝔽(captureIndex)))로 둔다.
          2. CreateDataPropertyOrThrow(array, ! ToString(𝔽(lengthA)), nextCapture)를 수행한다.
          3. captureIndexcaptureIndex + 1로 설정한다.
          4. lengthAlengthA + 1로 설정한다.
          5. lengthA = lim이면, array를 반환한다.
        10. searchIndexlastMatchEnd로 설정한다.
  20. substringstringlastMatchEnd부터 size까지의 substring으로 둔다.
  21. CreateDataPropertyOrThrow(array, ! ToString(𝔽(lengthA)), substring)를 수행한다.
  22. array를 반환한다.

이 method의 "name" property의 value는 "[Symbol.split]"입니다.

Note 2

이 method는 이 RegExp object의 "global""sticky" properties의 value를 ignores합니다.

22.2.6.15 get RegExp.prototype.sticky

RegExp.prototype.sticky는 set accessor function이 undefinedaccessor property입니다. Its get accessor function은 called될 때 다음 steps를 수행합니다:

  1. regexpthis value로 둔다.
  2. codeUnit을 code unit 0x0079 (LATIN SMALL LETTER Y)로 둔다.
  3. RegExpHasFlag(regexp, codeUnit)를 반환한다.

22.2.6.16 RegExp.prototype.test ( string )

이 method는 called될 때 다음 steps를 수행합니다:

  1. regexpthis value로 둔다.
  2. regexp가 Object가 아니면, TypeError exception을 throw한다.
  3. string을 ? ToString(string)으로 설정한다.
  4. match를 ? RegExpExec(regexp, string)로 둔다.
  5. matchnull이면, false를 반환한다.
  6. true를 반환한다.

22.2.6.17 RegExp.prototype.toString ( )

  1. regexpthis value로 둔다.
  2. regexp가 Object가 아니면, TypeError exception을 throw한다.
  3. pattern을 ? ToString(? Get(regexp, "source"))으로 둔다.
  4. flags를 ? ToString(? Get(regexp, "flags"))로 둔다.
  5. result"/", pattern, "/", 및 flagsstring-concatenation으로 둔다.
  6. result를 반환한다.
Note

returned String은 this object와 same behaviour를 가진 another RegExp object로 evaluates되는 RegularExpressionLiteral의 form을 가집니다.

22.2.6.18 get RegExp.prototype.unicode

RegExp.prototype.unicode는 set accessor function이 undefinedaccessor property입니다. Its get accessor function은 called될 때 다음 steps를 수행합니다:

  1. regexpthis value로 둔다.
  2. codeUnit을 code unit 0x0075 (LATIN SMALL LETTER U)로 둔다.
  3. RegExpHasFlag(regexp, codeUnit)를 반환한다.

22.2.6.19 get RegExp.prototype.unicodeSets

RegExp.prototype.unicodeSets는 set accessor function이 undefinedaccessor property입니다. Its get accessor function은 called될 때 다음 steps를 수행합니다:

  1. regexpthis value로 둔다.
  2. codeUnit을 code unit 0x0076 (LATIN SMALL LETTER V)로 둔다.
  3. RegExpHasFlag(regexp, codeUnit)를 반환한다.

22.2.7 RegExp Matching용 Abstract Operations

22.2.7.1 RegExpExec ( regexp, string )

The abstract operation RegExpExec takes arguments regexp (an Object) and string (a String) and returns either a normal completion containing either an Object or null, or a throw completion. It performs the following steps when called:

  1. exec를 ? Get(regexp, "exec")로 둔다.
  2. IsCallable(exec)이 true이면, 다음을 수행한다.
    1. result를 ? Call(exec, regexp, « string »)로 둔다.
    2. result가 Object가 아니고 resultnull도 아니면, TypeError exception을 throw한다.
    3. result를 반환한다.
  3. RequireInternalSlot(regexp, [[RegExpMatcher]])를 수행한다.
  4. RegExpBuiltinExec(regexp, string)를 반환한다.
Note

callable "exec" property가 found되지 않으면 이 algorithm은 built-in RegExp matching algorithm 사용을 attempt하는 것으로 fallback합니다. 이는 regular expressions를 사용하는 most built-in algorithms가 "exec"의 dynamic property lookup을 수행하지 않았던 prior editions용으로 written된 code에 대해 compatible behaviour를 제공합니다.

22.2.7.2 RegExpBuiltinExec ( regexp, string )

The abstract operation RegExpBuiltinExec takes arguments regexp (an initialized RegExp instance) and string (a String) and returns either a normal completion containing either an Array exotic object or null, or a throw completion. It performs the following steps when called:

  1. lengthstring의 length로 둔다.
  2. lastIndex(? ToLength(! Get(regexp, "lastIndex")))로 둔다.
  3. flagsregexp.[[OriginalFlags]]로 둔다.
  4. flags"g"를 contain하면 globaltrue로 둔다; else globalfalse로 둔다.
  5. flags"y"를 contain하면 stickytrue로 둔다; else stickyfalse로 둔다.
  6. flags"d"를 contain하면 hasIndicestrue로 둔다; else hasIndicesfalse로 둔다.
  7. globalfalse이고 stickyfalse이면, lastIndex를 0으로 설정한다.
  8. matcherregexp.[[RegExpMatcher]]로 둔다.
  9. flags"u"를 contain하거나 flags"v"를 contain하면 fullUnicodetrue로 둔다; else fullUnicodefalse로 둔다.
  10. matchSucceededfalse로 둔다.
  11. fullUnicodetrue이면 inputStringToCodePoints(string)로 둔다; else input을 elements가 string의 elements인 code units인 List로 둔다.
  12. NOTE: input의 각 element는 character로 considered된다.
  13. Repeat, while matchSucceeded is false,
    1. lastIndex > length이면, 다음을 수행한다.
      1. globaltrue이거나 stickytrue이면, 다음을 수행한다.
        1. Set(regexp, "lastIndex", +0𝔽, true)를 수행한다.
      2. null을 반환한다.
    2. inputIndexstring의 element lastIndex로부터 obtained된 character의 input 안 index로 둔다.
    3. resultmatcher(input, inputIndex)로 둔다.
    4. resultfailure이면, 다음을 수행한다.
      1. stickytrue이면, 다음을 수행한다.
        1. Set(regexp, "lastIndex", +0𝔽, true)를 수행한다.
        2. null을 반환한다.
      2. lastIndexAdvanceStringIndex(string, lastIndex, fullUnicode)로 설정한다.
    5. Else,
      1. Assert: resultMatchState이다.
      2. matchSucceededtrue로 설정한다.
  14. endIndexresult.[[EndIndex]]로 둔다.
  15. fullUnicodetrue이면, endIndexGetStringIndex(string, endIndex)로 설정한다.
  16. globaltrue이거나 stickytrue이면, 다음을 수행한다.
    1. Set(regexp, "lastIndex", 𝔽(endIndex), true)를 수행한다.
  17. capturingGroupsCountresult.[[Captures]] 안의 elements 수로 둔다.
  18. Assert: capturingGroupsCount = regexp.[[RegExpRecord]].[[CapturingGroupsCount]]이다.
  19. Assert: capturingGroupsCount < 232 - 1이다.
  20. array를 ! ArrayCreate(capturingGroupsCount + 1)로 둔다.
  21. Assert: array"length" property의 mathematical valuecapturingGroupsCount + 1이다.
  22. CreateDataPropertyOrThrow(array, "index", 𝔽(lastIndex))를 수행한다.
  23. CreateDataPropertyOrThrow(array, "input", string)를 수행한다.
  24. matchMatch Record { [[StartIndex]]: lastIndex, [[EndIndex]]: endIndex }로 둔다.
  25. indices를 새 empty List로 둔다.
  26. groupNames를 새 empty List로 둔다.
  27. matchindices에 append한다.
  28. matchedSubstringGetMatchString(string, match)로 둔다.
  29. CreateDataPropertyOrThrow(array, "0", matchedSubstring)를 수행한다.
  30. regexp가 any GroupName을 contain하면, 다음을 수행한다.
    1. groupsOrdinaryObjectCreate(null)로 둔다.
    2. hasGroupstrue로 둔다.
  31. Else,
    1. groupsundefined로 둔다.
    2. hasGroupsfalse로 둔다.
  32. CreateDataPropertyOrThrow(array, "groups", groups)를 수행한다.
  33. matchedGroupNames를 새 empty List로 둔다.
  34. 1 ≤ icapturingGroupsCount를 만족하는 각 integer i에 대해, ascending order로, 다음을 수행한다.
    1. captureresult.[[Captures]]ith element로 둔다.
    2. captureundefined이면, 다음을 수행한다.
      1. capturedValueundefined로 둔다.
      2. undefinedindices에 append한다.
    3. Else,
      1. captureStartcapture.[[StartIndex]]로 둔다.
      2. captureEndcapture.[[EndIndex]]로 둔다.
      3. fullUnicodetrue이면, 다음을 수행한다.
        1. captureStartGetStringIndex(string, captureStart)로 설정한다.
        2. captureEndGetStringIndex(string, captureEnd)로 설정한다.
      4. captureRecordMatch Record { [[StartIndex]]: captureStart, [[EndIndex]]: captureEnd }로 둔다.
      5. capturedValueGetMatchString(string, captureRecord)로 둔다.
      6. captureRecordindices에 append한다.
    4. CreateDataPropertyOrThrow(array, ! ToString(𝔽(i)), capturedValue)를 수행한다.
    5. regexpith capture가 GroupName으로 defined되었으면, 다음을 수행한다.
      1. groupName을 that GroupNameCapturingGroupName으로 둔다.
      2. matchedGroupNamesgroupName을 contain하면, 다음을 수행한다.
        1. Assert: capturedValueundefined이다.
        2. undefinedgroupNames에 append한다.
      3. Else,
        1. capturedValueundefined가 아니면, groupNamematchedGroupNames에 append한다.
        2. NOTE: groupName이라고 named된 multiple groups가 있으면, groups는 이 point에서 이미 groupName property를 가지고 있을 수 있다. However, groups가 properties가 모두 writable data propertiesordinary object이므로, CreateDataPropertyOrThrow call은 nevertheless succeed하는 것이 guaranteed된다.
        3. CreateDataPropertyOrThrow(groups, groupName, capturedValue)를 수행한다.
        4. groupNamegroupNames에 append한다.
    6. Else,
      1. undefinedgroupNames에 append한다.
  35. hasIndicestrue이면, 다음을 수행한다.
    1. indicesArrayMakeMatchIndicesIndexPairArray(string, indices, groupNames, hasGroups)로 둔다.
    2. CreateDataPropertyOrThrow(array, "indices", indicesArray)를 수행한다.
  36. array를 반환한다.

22.2.7.3 AdvanceStringIndex ( string, index, unicode )

The abstract operation AdvanceStringIndex takes arguments string (a String), index (a non-negative integer), and unicode (a Boolean) and returns a non-negative integer. It performs the following steps when called:

  1. Assert: index ≤ 253 - 1이다.
  2. unicodefalse이면, index + 1을 반환한다.
  3. lengthstring의 length로 둔다.
  4. index + 1 ≥ length이면, index + 1을 반환한다.
  5. codePointCodePointAt(string, index)로 둔다.
  6. index + codePoint.[[CodeUnitCount]]를 반환한다.

22.2.7.4 GetStringIndex ( string, codePointIndex )

The abstract operation GetStringIndex takes arguments string (a String) and codePointIndex (a non-negative integer) and returns a non-negative integer. 6.1.4에 described된 대로 string을 UTF-16 encoded code points의 sequence로 interpret하고, such index가 exist할 때 code point index codePointIndex에 corresponding하는 code unit index를 반환합니다. Otherwise, string의 length를 반환합니다. It performs the following steps when called:

  1. string이 empty String이면, 0을 반환한다.
  2. lengthstring의 length로 둔다.
  3. codeUnitCount를 0으로 둔다.
  4. codePointCount를 0으로 둔다.
  5. Repeat, while codeUnitCount < length,
    1. codePointCount = codePointIndex이면, codeUnitCount를 반환한다.
    2. codePointCodePointAt(string, codeUnitCount)로 둔다.
    3. codeUnitCountcodeUnitCount + codePoint.[[CodeUnitCount]]로 설정한다.
    4. codePointCountcodePointCount + 1로 설정한다.
  6. length를 반환한다.

22.2.7.5 Match Records

Match Record는 regular expression match 또는 capture의 start 및 end indices를 encapsulate하는 데 사용되는 Record value입니다.

Match Records는 Table 68에 listed된 fields를 가집니다.

Table 68: Match Record Fields
Field Name Value Meaning
[[StartIndex]] a non-negative integer match가 begin하는(inclusive) string의 start부터의 code units 수입니다.
[[EndIndex]] an integer[[StartIndex]] match가 end하는(exclusive) string의 start부터의 code units 수입니다.

22.2.7.6 GetMatchString ( string, match )

The abstract operation GetMatchString takes arguments string (a String) and match (a Match Record) and returns a String. It performs the following steps when called:

  1. Assert: match.[[StartIndex]]match.[[EndIndex]]string의 length이다.
  2. stringmatch.[[StartIndex]]부터 match.[[EndIndex]]까지의 substring을 반환한다.

22.2.7.7 GetMatchIndexPair ( string, match )

The abstract operation GetMatchIndexPair takes arguments string (a String) and match (a Match Record) and returns an Array. It performs the following steps when called:

  1. Assert: match.[[StartIndex]]match.[[EndIndex]]string의 length이다.
  2. CreateArrayFromList𝔽(match.[[StartIndex]]), 𝔽(match.[[EndIndex]]) »)를 반환한다.

22.2.7.8 MakeMatchIndicesIndexPairArray ( string, indices, groupNames, hasGroups )

The abstract operation MakeMatchIndicesIndexPairArray takes arguments string (a String), indices (a List of either Match Records or undefined), groupNames (a List of either Strings or undefined), and hasGroups (a Boolean) and returns an Array. It performs the following steps when called:

  1. nindices 안의 elements 수로 둔다.
  2. Assert: n < 232 - 1이다.
  3. Assert: groupNamesn - 1 elements를 가진다.
  4. NOTE: groupNames Listindices[1]에서 starting하여 indices List와 aligned된 elements를 contain한다.
  5. array를 ! ArrayCreate(n)로 둔다.
  6. hasGroupstrue이면, 다음을 수행한다.
    1. groupsOrdinaryObjectCreate(null)로 둔다.
  7. Else,
    1. groupsundefined로 둔다.
  8. CreateDataPropertyOrThrow(array, "groups", groups)를 수행한다.
  9. 0 ≤ i < n인 각 integer i에 대해, ascending order로, 다음을 수행한다.
    1. matchIndicesindices[i]로 둔다.
    2. matchIndicesundefined가 아니면, 다음을 수행한다.
      1. matchIndexPairGetMatchIndexPair(string, matchIndices)로 둔다.
    3. Else,
      1. matchIndexPairundefined로 둔다.
    4. CreateDataPropertyOrThrow(array, ! ToString(𝔽(i)), matchIndexPair)를 수행한다.
    5. i > 0이면, 다음을 수행한다.
      1. namegroupNames[i - 1]로 둔다.
      2. nameundefined가 아니면, 다음을 수행한다.
        1. Assert: groupsundefined가 아니다.
        2. NOTE: name이라고 named된 multiple groups가 있으면, groups는 이 point에서 이미 name property를 가지고 있을 수 있다. However, groups가 properties가 모두 writable data propertiesordinary object이므로, CreateDataPropertyOrThrow call은 nevertheless succeed하는 것이 guaranteed된다.
        3. CreateDataPropertyOrThrow(groups, name, matchIndexPair)를 수행한다.
  10. array를 반환한다.

22.2.8 RegExp Instances의 Properties

RegExp instances는 RegExp prototype object로부터 properties를 inherit하는 ordinary objects입니다. RegExp instances는 internal slots [[OriginalSource]], [[OriginalFlags]], [[RegExpRecord]], 및 [[RegExpMatcher]]를 가집니다. [[RegExpMatcher]] internal slot의 value는 RegExp object의 PatternAbstract Closure representation입니다.

Note

ECMAScript 2015 이전에는 RegExp instances가 own data properties "source", "global", "ignoreCase", 및 "multiline"을 가지는 것으로 specified되었습니다. Those properties는 now RegExp.prototypeaccessor properties로 specified됩니다.

RegExp instances는 또한 다음 property를 가집니다:

22.2.8.1 lastIndex

"lastIndex" property의 value는 next match를 start할 String index를 specifies합니다. 사용될 때 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 String instance object에 대한 specific iteration을 represent하고, some specific RegExp instance object에 대해 matching하는 object입니다. RegExp String Iterator objects를 위한 named constructor는 없습니다. 대신, RegExp String Iterator objects는 RegExp instance objects의 certain methods를 calling하여 created됩니다.

22.2.9.1 CreateRegExpStringIterator ( regexp, string, global, fullUnicode )

The abstract operation CreateRegExpStringIterator takes arguments regexp (an Object), string (a String), global (a Boolean), and fullUnicode (a Boolean) and returns an Object. It performs the following steps when called:

  1. iteratorOrdinaryObjectCreate(%RegExpStringIteratorPrototype%, « [[IteratingRegExp]], [[IteratedString]], [[Global]], [[Unicode]], [[Done]] »)로 둔다.
  2. iterator.[[IteratingRegExp]]regexp로 설정한다.
  3. iterator.[[IteratedString]]string으로 설정한다.
  4. iterator.[[Global]]global로 설정한다.
  5. iterator.[[Unicode]]fullUnicode로 설정한다.
  6. iterator.[[Done]]false로 설정한다.
  7. iterator를 반환한다.

22.2.9.2 The %RegExpStringIteratorPrototype% Object

%RegExpStringIteratorPrototype% object는:

22.2.9.2.1 %RegExpStringIteratorPrototype%.next ( )

  1. iteratorObjthis value로 둔다.
  2. iteratorObj가 Object가 아니면, TypeError exception을 throw한다.
  3. iteratorObjRegExp String Iterator Object Instance의 all internal slots(22.2.9.3 참조)를 가지지 않으면, TypeError exception을 throw한다.
  4. iteratorObj.[[Done]]true이면, 다음을 수행한다.
    1. CreateIteratorResultObject(undefined, true)를 반환한다.
  5. regexpiteratorObj.[[IteratingRegExp]]로 둔다.
  6. stringiteratorObj.[[IteratedString]]으로 둔다.
  7. globaliteratorObj.[[Global]]로 둔다.
  8. fullUnicodeiteratorObj.[[Unicode]]로 둔다.
  9. match를 ? RegExpExec(regexp, string)로 둔다.
  10. matchnull이면, 다음을 수행한다.
    1. iteratorObj.[[Done]]true로 설정한다.
    2. CreateIteratorResultObject(undefined, true)를 반환한다.
  11. globalfalse이면, 다음을 수행한다.
    1. iteratorObj.[[Done]]true로 설정한다.
    2. CreateIteratorResultObject(match, false)를 반환한다.
  12. matchString을 ? ToString(? Get(match, "0"))으로 둔다.
  13. matchString이 empty String이면, 다음을 수행한다.
    1. thisIndex(? ToLength(? Get(regexp, "lastIndex")))로 둔다.
    2. nextIndexAdvanceStringIndex(string, thisIndex, fullUnicode)로 둔다.
    3. Set(regexp, "lastIndex", 𝔽(nextIndex), true)를 수행한다.
  14. CreateIteratorResultObject(match, false)를 반환한다.

22.2.9.2.2 %RegExpStringIteratorPrototype% [ %Symbol.toStringTag% ]

%Symbol.toStringTag% property의 initial value는 String value "RegExp String Iterator"입니다.

이 property는 attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }를 가집니다.

22.2.9.3 RegExp String Iterator Instances의 Properties

RegExp String Iterator instances는 %RegExpStringIteratorPrototype% intrinsic object로부터 properties를 inherit하는 ordinary objects입니다. RegExp String Iterator instances는 Table 69에 listed된 internal slots로 initially created됩니다.

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 iterated upon되고 있는 String value입니다.
[[Global]] a Boolean [[IteratingRegExp]]가 global인지 여부를 indicate합니다.
[[Unicode]] a Boolean [[IteratingRegExp]]가 Unicode mode인지 여부를 indicate합니다.
[[Done]] a Boolean iteration이 complete되었는지 여부를 indicate합니다.

23 Indexed Collections

23.1 Array Objects

Array는 certain 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로 called될 때 new Array를 create하고 initialize합니다.
  • constructor가 아니라 function으로 called될 때도 new Array를 create하고 initialize합니다. 따라서 function call Array(…)는 same arguments를 가진 object creation expression new Array(…)와 equivalent합니다.
  • arguments의 number 및 types에 따라 behaviour가 달라지는 function입니다.
  • class definition의 extends clause의 value로 사용될 수 있습니다. exotic Array behaviour를 inherit하려는 subclass constructorsArray exotic objects인 subclass instances를 initialize하기 위해 Array constructor에 대한 super call을 include해야 합니다. 그러나 Array.prototype methods의 대부분은 this value가 Array exotic object인지에 dependent하지 않은 generic methods입니다.

23.1.1.1 Array ( ...values )

이 function은 called될 때 다음 steps를 수행합니다:

  1. NewTarget이 undefined이면 newTarget을 active function object로 둔다; else newTarget을 NewTarget으로 둔다.
  2. proto를 ? GetPrototypeFromConstructor(newTarget, "%Array.prototype%")로 둔다.
  3. numberOfArgsvalues 안의 elements 수로 둔다.
  4. numberOfArgs = 0이면, ! ArrayCreate(0, proto)를 반환한다.
  5. numberOfArgs = 1이면, 다음을 수행한다.
    1. lengthvalues[0]로 둔다.
    2. array를 ! ArrayCreate(0, proto)로 둔다.
    3. length가 Number가 아니면, 다음을 수행한다.
      1. CreateDataPropertyOrThrow(array, "0", length)를 수행한다.
      2. intLength1𝔽로 둔다.
    4. Else,
      1. intLength를 ! ToUint32(length)로 둔다.
      2. SameValueZero(intLength, length)가 false이면, RangeError exception을 throw한다.
    5. Set(array, "length", intLength, true)를 수행한다.
    6. array를 반환한다.
  6. Assert: numberOfArgs ≥ 2이다.
  7. array를 ? ArrayCreate(numberOfArgs, proto)로 둔다.
  8. k를 0으로 둔다.
  9. Repeat, while k < numberOfArgs,
    1. propertyKey를 ! ToString(𝔽(k))로 둔다.
    2. itemKvalues[k]로 둔다.
    3. CreateDataPropertyOrThrow(array, propertyKey, itemK)를 수행한다.
    4. kk + 1로 설정한다.
  10. Assert: array"length" property의 mathematical valuenumberOfArgs이다.
  11. array를 반환한다.

23.1.2 Properties of the Array Constructor

Array constructor는:

  • value가 %Function.prototype%[[Prototype]] internal slot을 가집니다.
  • value가 1𝔽"length" property를 가집니다.
  • 다음 properties를 가집니다:

23.1.2.1 Array.from ( items [ , mapper [ , thisArg ] ] )

이 function은 called될 때 다음 steps를 수행합니다:

  1. ctorthis value로 둔다.
  2. mapperundefined이면, 다음을 수행한다.
    1. mappingfalse로 둔다.
  3. Else,
    1. IsCallable(mapper)가 false이면, TypeError exception을 throw한다.
    2. mappingtrue로 둔다.
  4. usingIterator를 ? GetMethod(items, %Symbol.iterator%)로 둔다.
  5. usingIteratorundefined가 아니면, 다음을 수행한다.
    1. IsConstructor(ctor)가 true이면, 다음을 수행한다.
      1. array를 ? Construct(ctor)로 둔다.
    2. Else,
      1. array를 ! ArrayCreate(0)로 둔다.
    3. iteratorRecord를 ? GetIteratorFromMethod(items, usingIterator)로 둔다.
    4. k를 0으로 둔다.
    5. Repeat,
      1. k ≥ 253 - 1이면, 다음을 수행한다.
        1. errorThrowCompletion(newly created TypeError object)로 둔다.
        2. IteratorClose(iteratorRecord, error)를 반환한다.
      2. propertyKey를 ! ToString(𝔽(k))로 둔다.
      3. next를 ? IteratorStepValue(iteratorRecord)로 둔다.
      4. nextdone이면, 다음을 수행한다.
        1. Set(array, "length", 𝔽(k), true)를 수행한다.
        2. array를 반환한다.
      5. mappingtrue이면, 다음을 수행한다.
        1. mappedValueCompletion(Call(mapper, thisArg, « next, 𝔽(k) »))로 둔다.
        2. IfAbruptCloseIterator(mappedValue, iteratorRecord).
      6. Else,
        1. mappedValuenext로 둔다.
      7. defineStatusCompletion(CreateDataPropertyOrThrow(array, propertyKey, mappedValue))로 둔다.
      8. IfAbruptCloseIterator(defineStatus, iteratorRecord).
      9. kk + 1로 설정한다.
  6. NOTE: itemsiterable이 아니므로 array-like object라고 assume한다.
  7. arrayLike를 ! ToObject(items)로 둔다.
  8. length를 ? LengthOfArrayLike(arrayLike)로 둔다.
  9. IsConstructor(ctor)가 true이면, 다음을 수행한다.
    1. array를 ? Construct(ctor, « 𝔽(length) »)로 둔다.
  10. Else,
    1. array를 ? ArrayCreate(length)로 둔다.
  11. k를 0으로 둔다.
  12. Repeat, while k < length,
    1. propertyKey를 ! ToString(𝔽(k))로 둔다.
    2. kValue를 ? Get(arrayLike, propertyKey)로 둔다.
    3. mappingtrue이면, 다음을 수행한다.
      1. mappedValue를 ? Call(mapper, thisArg, « kValue, 𝔽(k) »)로 둔다.
    4. Else,
      1. mappedValuekValue로 둔다.
    5. CreateDataPropertyOrThrow(array, propertyKey, mappedValue)를 수행한다.
    6. kk + 1로 설정한다.
  13. Set(array, "length", 𝔽(length), true)를 수행한다.
  14. array를 반환한다.
Note

이 method는 intentionally generic factory method입니다; its this value가 Array constructor일 것을 require하지 않습니다. 따라서 single numeric argument와 함께 called될 수 있는 any other constructors로 transferred되거나 inherited될 수 있습니다.

23.1.2.2 Array.fromAsync ( items [ , mapper [ , thisArg ] ] )

이 async function은 called될 때 다음 steps를 수행합니다:

  1. ctorthis value로 둔다.
  2. mappingfalse로 둔다.
  3. mapperundefined가 아니면, 다음을 수행한다.
    1. IsCallable(mapper)가 false이면, TypeError exception을 throw한다.
    2. mappingtrue로 설정한다.
  4. iteratorRecordundefined로 둔다.
  5. usingAsyncIterator를 ? GetMethod(items, %Symbol.asyncIterator%)로 둔다.
  6. usingAsyncIteratorundefined이면, 다음을 수행한다.
    1. usingSyncIterator를 ? GetMethod(items, %Symbol.iterator%)로 둔다.
    2. usingSyncIteratorundefined가 아니면, 다음을 수행한다.
      1. iteratorRecordCreateAsyncFromSyncIterator(? GetIteratorFromMethod(items, usingSyncIterator))로 설정한다.
  7. Else,
    1. iteratorRecord를 ? GetIteratorFromMethod(items, usingAsyncIterator)로 설정한다.
  8. iteratorRecordundefined가 아니면, 다음을 수행한다.
    1. IsConstructor(ctor)가 true이면, 다음을 수행한다.
      1. array를 ? Construct(ctor)로 둔다.
    2. Else,
      1. array를 ! ArrayCreate(0)로 둔다.
    3. k를 0으로 둔다.
    4. Repeat,
      1. k ≥ 253 - 1이면, 다음을 수행한다.
        1. errorThrowCompletion(newly created TypeError object)로 둔다.
        2. AsyncIteratorClose(iteratorRecord, error)를 반환한다.
      2. propertyKey를 ! ToString(𝔽(k))로 둔다.
      3. nextResult를 ? Call(iteratorRecord.[[NextMethod]], iteratorRecord.[[Iterator]])로 둔다.
      4. nextResult를 ? Await(nextResult)로 설정한다.
      5. nextResult가 Object가 아니면, TypeError exception을 throw한다.
      6. done을 ? IteratorComplete(nextResult)로 둔다.
      7. donetrue이면, 다음을 수행한다.
        1. Set(array, "length", 𝔽(k), true)를 수행한다.
        2. array를 반환한다.
      8. nextValue를 ? IteratorValue(nextResult)로 둔다.
      9. mappingtrue이면, 다음을 수행한다.
        1. mappedValueCompletion(Call(mapper, thisArg, « nextValue, 𝔽(k) »))로 둔다.
        2. IfAbruptCloseAsyncIterator(mappedValue, iteratorRecord).
        3. mappedValueCompletion(Await(mappedValue))로 설정한다.
        4. IfAbruptCloseAsyncIterator(mappedValue, iteratorRecord).
      10. Else,
        1. mappedValuenextValue로 둔다.
      11. defineStatusCompletion(CreateDataPropertyOrThrow(array, propertyKey, mappedValue))로 둔다.
      12. IfAbruptCloseAsyncIterator(defineStatus, iteratorRecord).
      13. kk + 1로 설정한다.
  9. Else,
    1. NOTE: itemsasync iterableiterable도 아니므로 array-like object라고 assume한다.
    2. arrayLike를 ! ToObject(items)로 둔다.
    3. length를 ? LengthOfArrayLike(arrayLike)로 둔다.
    4. IsConstructor(ctor)가 true이면, 다음을 수행한다.
      1. array를 ? Construct(ctor, « 𝔽(length) »)로 둔다.
    5. Else,
      1. array를 ? ArrayCreate(length)로 둔다.
    6. k를 0으로 둔다.
    7. Repeat, while k < length,
      1. propertyKey를 ! ToString(𝔽(k))로 둔다.
      2. kValue를 ? Get(arrayLike, propertyKey)로 둔다.
      3. kValue를 ? Await(kValue)로 설정한다.
      4. mappingtrue이면, 다음을 수행한다.
        1. mappedValue를 ? Call(mapper, thisArg, « kValue, 𝔽(k) »)로 둔다.
        2. mappedValue를 ? Await(mappedValue)로 설정한다.
      5. Else,
        1. mappedValuekValue로 둔다.
      6. CreateDataPropertyOrThrow(array, propertyKey, mappedValue)를 수행한다.
      7. kk + 1로 설정한다.
    8. Set(array, "length", 𝔽(length), true)를 수행한다.
    9. array를 반환한다.
Note

이 method는 intentionally generic factory method입니다; its this value가 Array constructor일 것을 require하지 않습니다. 따라서 single numeric argument와 함께 called될 수 있는 any other constructors로 transferred되거나 inherited될 수 있습니다.

23.1.2.3 Array.isArray ( arg )

이 function은 called될 때 다음 steps를 수행합니다:

  1. IsArray(arg)를 반환한다.

23.1.2.4 Array.of ( ...items )

이 method는 called될 때 다음 steps를 수행합니다:

  1. lengthitems 안의 elements 수로 둔다.
  2. lengthNumber𝔽(length)로 둔다.
  3. ctorthis value로 둔다.
  4. IsConstructor(ctor)가 true이면, 다음을 수행한다.
    1. array를 ? Construct(ctor, « lengthNumber »)로 둔다.
  5. Else,
    1. array를 ? ArrayCreate(length)로 둔다.
  6. k를 0으로 둔다.
  7. Repeat, while k < length,
    1. kValueitems[k]로 둔다.
    2. propertyKey를 ! ToString(𝔽(k))로 둔다.
    3. CreateDataPropertyOrThrow(array, propertyKey, kValue)를 수행한다.
    4. kk + 1로 설정한다.
  8. Set(array, "length", lengthNumber, true)를 수행한다.
  9. array를 반환한다.
Note

이 method는 intentionally generic factory method입니다; its this value가 Array constructor일 것을 require하지 않습니다. 따라서 single numeric argument와 함께 called될 수 있는 other constructors로 transferred되거나 inherited될 수 있습니다.

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이 undefinedaccessor property입니다. Its get accessor function은 called될 때 다음 steps를 수행합니다:

  1. this value를 반환한다.

이 function의 "name" property의 value는 "get [Symbol.species]"입니다.

Note

Array prototype methods는 normally their this value의 constructor를 사용하여 derived object를 create합니다. However, subclass constructor는 its %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이며 such objects에 대해 specified된 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 이전에 created된 ECMAScript code와의 compatibility를 ensure하기 위해 Array exotic object로 specified됩니다.

23.1.3.1 Array.prototype.at ( index )

  1. obj를 ? ToObject(this value)로 둔다.
  2. length를 ? LengthOfArrayLike(obj)로 둔다.
  3. relativeIndex를 ? ToIntegerOrInfinity(index)로 둔다.
  4. relativeIndex ≥ 0이면, 다음을 수행한다.
    1. krelativeIndex로 둔다.
  5. Else,
    1. klength + relativeIndex로 둔다.
  6. k < 0 또는 klength이면, undefined를 반환한다.
  7. Get(obj, ! ToString(𝔽(k)))를 반환한다.

23.1.3.2 Array.prototype.concat ( ...items )

이 method는 object의 array elements 뒤에 each argument의 array elements가 followed되는 array를 반환합니다.

called될 때 다음 steps를 수행합니다:

  1. obj를 ? ToObject(this value)로 둔다.
  2. array를 ? ArraySpeciesCreate(obj, 0)로 둔다.
  3. nextIndex를 0으로 둔다.
  4. objitems 앞에 prepend한다.
  5. items의 각 element item에 대해, 다음을 수행한다.
    1. spreadable을 ? IsConcatSpreadable(item)로 둔다.
    2. spreadabletrue이면, 다음을 수행한다.
      1. length를 ? LengthOfArrayLike(item)로 둔다.
      2. nextIndex + length > 253 - 1이면, TypeError exception을 throw한다.
      3. sourceIndex를 0으로 둔다.
      4. Repeat, while sourceIndex < length,
        1. propertyKey를 ! ToString(𝔽(sourceIndex))로 둔다.
        2. exists를 ? HasProperty(item, propertyKey)로 둔다.
        3. existstrue이면, 다음을 수행한다.
          1. subElement를 ? Get(item, propertyKey)로 둔다.
          2. CreateDataPropertyOrThrow(array, ! ToString(𝔽(nextIndex)), subElement)를 수행한다.
        4. nextIndexnextIndex + 1로 설정한다.
        5. sourceIndexsourceIndex + 1로 설정한다.
    3. Else,
      1. NOTE: item은 spread되지 않고 single item으로 added된다.
      2. nextIndex ≥ 253 - 1이면, TypeError exception을 throw한다.
      3. CreateDataPropertyOrThrow(array, ! ToString(𝔽(nextIndex)), item)를 수행한다.
      4. nextIndexnextIndex + 1로 설정한다.
  6. Set(array, "length", 𝔽(nextIndex), true)를 수행한다.
  7. array를 반환한다.

이 method의 "length" property는 1𝔽입니다.

Note 1

step 6에서 "length" property를 explicitly setting하는 것은 items의 final non-empty element가 trailing holes를 가지거나 array가 built-in Array가 아닌 경우에도 length가 correct함을 ensure하기 위한 것입니다.

Note 2

이 method는 intentionally generic입니다; its this value가 Array일 것을 require하지 않습니다. 따라서 method로 사용하기 위해 other kinds of objects에 transferred될 수 있습니다.

23.1.3.2.1 IsConcatSpreadable ( obj )

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

  1. obj가 Object가 아니면, false를 반환한다.
  2. spreadable을 ? Get(obj, %Symbol.isConcatSpreadable%)로 둔다.
  3. spreadableundefined가 아니면, ToBoolean(spreadable)를 반환한다.
  4. IsArray(obj)를 반환한다.

23.1.3.3 Array.prototype.constructor

Array.prototype.constructor의 initial value는 %Array%입니다.

23.1.3.4 Array.prototype.copyWithin ( target, start [ , end ] )

Note 1

end argument는 optional입니다. 제공되지 않으면, this value의 length가 사용됩니다.

Note 2

target이 negative이면, array의 length인 length에 대해 length + target로 treated됩니다. start가 negative이면, length + start로 treated됩니다. end가 negative이면, length + end로 treated됩니다.

이 method는 called될 때 다음 steps를 수행합니다:

  1. obj를 ? ToObject(this value)로 둔다.
  2. length를 ? LengthOfArrayLike(obj)로 둔다.
  3. relativeTarget을 ? ToIntegerOrInfinity(target)로 둔다.
  4. relativeTarget = -∞이면, to를 0으로 둔다.
  5. Else if relativeTarget < 0이면, tomax(length + relativeTarget, 0)으로 둔다.
  6. Else, tomin(relativeTarget, length)로 둔다.
  7. relativeStart를 ? ToIntegerOrInfinity(start)로 둔다.
  8. relativeStart = -∞이면, from을 0으로 둔다.
  9. Else if relativeStart < 0이면, frommax(length + relativeStart, 0)으로 둔다.
  10. Else, frommin(relativeStart, length)로 둔다.
  11. endundefined이면 relativeEndlength로 둔다; else relativeEnd를 ? ToIntegerOrInfinity(end)로 둔다.
  12. relativeEnd = -∞이면, final을 0으로 둔다.
  13. Else if relativeEnd < 0이면, finalmax(length + relativeEnd, 0)으로 둔다.
  14. Else, finalmin(relativeEnd, length)로 둔다.
  15. countmin(final - from, length - to)로 둔다.
  16. from < to이고 to < from + count이면, 다음을 수행한다.
    1. direction을 -1로 둔다.
    2. fromfrom + count - 1로 설정한다.
    3. toto + count - 1로 설정한다.
  17. Else,
    1. direction을 1로 둔다.
  18. Repeat, while count > 0,
    1. fromKey를 ! ToString(𝔽(from))로 둔다.
    2. toKey를 ! ToString(𝔽(to))로 둔다.
    3. fromPresent를 ? HasProperty(obj, fromKey)로 둔다.
    4. fromPresenttrue이면, 다음을 수행한다.
      1. fromValue를 ? Get(obj, fromKey)로 둔다.
      2. Set(obj, toKey, fromValue, true)를 수행한다.
    5. Else,
      1. Assert: fromPresentfalse이다.
      2. DeletePropertyOrThrow(obj, toKey)를 수행한다.
    6. fromfrom + direction으로 설정한다.
    7. toto + direction으로 설정한다.
    8. countcount - 1로 설정한다.
  19. obj를 반환한다.
Note 3

이 method는 intentionally generic입니다; its this value가 Array일 것을 require하지 않습니다. 따라서 method로 사용하기 위해 other kinds of objects에 transferred될 수 있습니다.

23.1.3.5 Array.prototype.entries ( )

이 method는 called될 때 다음 steps를 수행합니다:

  1. obj를 ? ToObject(this value)로 둔다.
  2. CreateArrayIterator(obj, key+value)를 반환한다.

23.1.3.6 Array.prototype.every ( callback [ , thisArg ] )

Note 1

callback은 three arguments를 accept하고 Boolean value로 coercible한 value를 return하는 function이어야 합니다. everycallbackfalse를 return하는 element를 find할 때까지 array에 present한 each element마다 ascending order로 callback을 once call합니다. such element가 found되면, every는 immediately false를 반환합니다. Otherwise, everytrue를 반환합니다. callback은 actually exist하는 array의 elements에 대해서만 called됩니다; array의 missing elements에 대해서는 called되지 않습니다.

thisArg parameter가 provided되면, callback의 each invocation에 대한 this value로 사용됩니다. provided되지 않으면, 대신 undefined가 사용됩니다.

callback은 three arguments와 함께 called됩니다: element의 value, element의 index, 그리고 traversed되는 object입니다.

every는 called된 object를 directly mutate하지 않지만, object는 callback calls에 의해 mutated될 수 있습니다.

every에 의해 processed되는 elements의 range는 callback에 대한 first call 전에 set됩니다. every call이 begin된 뒤 array에 appended되는 elements는 callback에 의해 visited되지 않습니다. array의 existing elements가 changed되면, callback에 passed되는 그 value는 every가 them을 visit하는 time의 value입니다; every call이 begin된 뒤 그리고 visited되기 전에 deleted되는 elements는 visited되지 않습니다. every는 mathematics의 “for all” quantifier처럼 acts합니다. 특히 empty array에 대해서는 true를 반환합니다.

이 method는 called될 때 다음 steps를 수행합니다:

  1. obj를 ? ToObject(this value)로 둔다.
  2. length를 ? LengthOfArrayLike(obj)로 둔다.
  3. IsCallable(callback)가 false이면, TypeError exception을 throw한다.
  4. k를 0으로 둔다.
  5. Repeat, while k < length,
    1. propertyKey를 ! ToString(𝔽(k))로 둔다.
    2. kPresent를 ? HasProperty(obj, propertyKey)로 둔다.
    3. kPresenttrue이면, 다음을 수행한다.
      1. kValue를 ? Get(obj, propertyKey)로 둔다.
      2. testResultToBoolean(? Call(callback, thisArg, « kValue, 𝔽(k), obj »))로 둔다.
      3. testResultfalse이면, false를 반환한다.
    4. kk + 1로 설정한다.
  6. true를 반환한다.
Note 2

이 method는 intentionally generic입니다; its this value가 Array일 것을 require하지 않습니다. 따라서 method로 사용하기 위해 other kinds of objects에 transferred될 수 있습니다.

23.1.3.7 Array.prototype.fill ( value [ , start [ , end ] ] )

Note 1

start argument는 optional입니다. 제공되지 않으면, +0𝔽이 사용됩니다.

end argument는 optional입니다. 제공되지 않으면, this value의 length가 사용됩니다.

Note 2

start가 negative이면, array의 length인 length에 대해 length + start로 treated됩니다. end가 negative이면, length + end로 treated됩니다.

이 method는 called될 때 다음 steps를 수행합니다:

  1. obj를 ? ToObject(this value)로 둔다.
  2. length를 ? LengthOfArrayLike(obj)로 둔다.
  3. relativeStart를 ? ToIntegerOrInfinity(start)로 둔다.
  4. relativeStart = -∞이면, k를 0으로 둔다.
  5. Else if relativeStart < 0이면, kmax(length + relativeStart, 0)으로 둔다.
  6. Else, kmin(relativeStart, length)로 둔다.
  7. endundefined이면 relativeEndlength로 둔다; else relativeEnd를 ? ToIntegerOrInfinity(end)로 둔다.
  8. relativeEnd = -∞이면, final을 0으로 둔다.
  9. Else if relativeEnd < 0이면, finalmax(length + relativeEnd, 0)으로 둔다.
  10. Else, finalmin(relativeEnd, length)로 둔다.
  11. Repeat, while k < final,
    1. propertyKey를 ! ToString(𝔽(k))로 둔다.
    2. Set(obj, propertyKey, value, true)를 수행한다.
    3. kk + 1로 설정한다.
  12. obj를 반환한다.
Note 3

이 method는 intentionally generic입니다; its this value가 Array일 것을 require하지 않습니다. 따라서 method로 사용하기 위해 other kinds of objects에 transferred될 수 있습니다.

23.1.3.8 Array.prototype.filter ( callback [ , thisArg ] )

Note 1

callback은 three arguments를 accept하고 Boolean value로 coercible한 value를 return하는 function이어야 합니다. filter는 array의 each element에 대해 ascending order로 callback을 once call하고, callbacktrue를 return하는 all values의 new array를 constructs합니다. callback은 actually exist하는 array의 elements에 대해서만 called됩니다; array의 missing elements에 대해서는 called되지 않습니다.

thisArg parameter가 provided되면, callback의 each invocation에 대한 this value로 사용됩니다. provided되지 않으면, 대신 undefined가 사용됩니다.

callback은 three arguments와 함께 called됩니다: element의 value, element의 index, 그리고 traversed되는 object입니다.

filter는 called된 object를 directly mutate하지 않지만, object는 callback calls에 의해 mutated될 수 있습니다.

filter에 의해 processed되는 elements의 range는 callback에 대한 first call 전에 set됩니다. filter call이 begin된 뒤 array에 appended되는 elements는 callback에 의해 visited되지 않습니다. array의 existing elements가 changed되면 callback에 passed되는 그 value는 filter가 them을 visit하는 time의 value입니다; filter call이 begin된 뒤 그리고 visited되기 전에 deleted되는 elements는 visited되지 않습니다.

이 method는 called될 때 다음 steps를 수행합니다:

  1. obj를 ? ToObject(this value)로 둔다.
  2. length를 ? LengthOfArrayLike(obj)로 둔다.
  3. IsCallable(callback)가 false이면, TypeError exception을 throw한다.
  4. array를 ? ArraySpeciesCreate(obj, 0)로 둔다.
  5. k를 0으로 둔다.
  6. to를 0으로 둔다.
  7. Repeat, while k < length,
    1. propertyKey를 ! ToString(𝔽(k))로 둔다.
    2. kPresent를 ? HasProperty(obj, propertyKey)로 둔다.
    3. kPresenttrue이면, 다음을 수행한다.
      1. kValue를 ? Get(obj, propertyKey)로 둔다.
      2. selectedToBoolean(? Call(callback, thisArg, « kValue, 𝔽(k), obj »))로 둔다.
      3. selectedtrue이면, 다음을 수행한다.
        1. CreateDataPropertyOrThrow(array, ! ToString(𝔽(to)), kValue)를 수행한다.
        2. toto + 1로 설정한다.
    4. kk + 1로 설정한다.
  8. array를 반환한다.
Note 2

이 method는 intentionally generic입니다; its this value가 Array일 것을 require하지 않습니다. 따라서 method로 사용하기 위해 other kinds of objects에 transferred될 수 있습니다.

23.1.3.9 Array.prototype.find ( predicate [ , thisArg ] )

Note 1

이 method는 predicatetrue로 coerce되는 value를 return하는 one을 find할 때까지 array의 each element에 대해 ascending index order로 predicate를 once call합니다. such element가 found되면, find는 immediately that element value를 반환합니다. Otherwise, findundefined를 반환합니다.

additional information은 FindViaPredicate를 참조하십시오.

이 method는 called될 때 다음 steps를 수행합니다:

  1. obj를 ? ToObject(this value)로 둔다.
  2. length를 ? LengthOfArrayLike(obj)로 둔다.
  3. findRecord를 ? FindViaPredicate(obj, length, ascending, predicate, thisArg)로 둔다.
  4. findRecord.[[Value]]를 반환한다.
Note 2

이 method는 intentionally generic입니다; its this value가 Array일 것을 require하지 않습니다. 따라서 method로 사용하기 위해 other kinds of objects에 transferred될 수 있습니다.

23.1.3.10 Array.prototype.findIndex ( predicate [ , thisArg ] )

Note 1

이 method는 predicatetrue로 coerce되는 value를 return하는 one을 find할 때까지 array의 each element에 대해 ascending index order로 predicate를 once call합니다. such element가 found되면, findIndex는 immediately that element value의 index를 반환합니다. Otherwise, findIndex는 -1을 반환합니다.

additional information은 FindViaPredicate를 참조하십시오.

이 method는 called될 때 다음 steps를 수행합니다:

  1. obj를 ? ToObject(this value)로 둔다.
  2. length를 ? LengthOfArrayLike(obj)로 둔다.
  3. findRecord를 ? FindViaPredicate(obj, length, ascending, predicate, thisArg)로 둔다.
  4. findRecord.[[Index]]를 반환한다.
Note 2

이 method는 intentionally generic입니다; its this value가 Array일 것을 require하지 않습니다. 따라서 method로 사용하기 위해 other kinds of objects에 transferred될 수 있습니다.

23.1.3.11 Array.prototype.findLast ( predicate [ , thisArg ] )

Note 1

이 method는 predicatetrue로 coerce되는 value를 return하는 one을 find할 때까지 array의 each element에 대해 descending index order로 predicate를 once call합니다. such element가 found되면, findLast는 immediately that element value를 반환합니다. Otherwise, findLastundefined를 반환합니다.

additional information은 FindViaPredicate를 참조하십시오.

이 method는 called될 때 다음 steps를 수행합니다:

  1. obj를 ? ToObject(this value)로 둔다.
  2. length를 ? LengthOfArrayLike(obj)로 둔다.
  3. findRecord를 ? FindViaPredicate(obj, length, descending, predicate, thisArg)로 둔다.
  4. findRecord.[[Value]]를 반환한다.
Note 2

이 method는 intentionally generic입니다; its this value가 Array object일 것을 require하지 않습니다. 따라서 method로 사용하기 위해 other kinds of objects에 transferred될 수 있습니다.

23.1.3.12 Array.prototype.findLastIndex ( predicate [ , thisArg ] )

Note 1

이 method는 predicatetrue로 coerce되는 value를 return하는 one을 find할 때까지 array의 each element에 대해 descending index order로 predicate를 once call합니다. such element가 found되면, findLastIndex는 immediately that element value의 index를 반환합니다. Otherwise, findLastIndex는 -1을 반환합니다.

additional information은 FindViaPredicate를 참조하십시오.

이 method는 called될 때 다음 steps를 수행합니다:

  1. obj를 ? ToObject(this value)로 둔다.
  2. length를 ? LengthOfArrayLike(obj)로 둔다.
  3. findRecord를 ? FindViaPredicate(obj, length, descending, predicate, thisArg)로 둔다.
  4. findRecord.[[Index]]를 반환한다.
Note 2

이 method는 intentionally generic입니다; its this value가 Array object일 것을 require하지 않습니다. 따라서 method로 사용하기 위해 other kinds of objects에 transferred될 수 있습니다.

23.1.3.12.1 FindViaPredicate ( obj, length, direction, predicate, thisArg )

The abstract operation FindViaPredicate takes arguments obj (an Object), length (a non-negative integer), direction (ascending or descending), predicate (an ECMAScript language value), and thisArg (an ECMAScript language value) and returns either a normal completion containing a Record with fields [[Index]] (an integral Number) and [[Value]] (an ECMAScript language value) or a throw completion.

objarray-like object 또는 TypedArray이어야 합니다. 이 operation은 predicatetrue로 coerce되는 value를 return하는 one을 find할 때까지 obj의 each element에 대해 ascending index order 또는 descending index order(direction에 의해 indicated됨)로 predicate를 once call합니다. 그 point에서, 이 operation은 found된 element의 index 및 value를 giving하는 Record를 반환합니다. such element가 found되지 않으면, 이 operation은 index에 -1𝔽을, value에 undefined를 specify하는 Record를 반환합니다.

predicate는 function이어야 합니다. array의 element에 대해 called될 때, three arguments가 passed됩니다: element의 value, element의 index, 그리고 traversed되는 object입니다. Its return value는 Boolean value로 coerced됩니다.

thisArgpredicate의 each invocation에 대한 this value로 사용됩니다.

이 operation은 called된 object를 directly mutate하지 않지만, object는 predicate calls에 의해 mutated될 수 있습니다.

processed되는 elements의 range는 predicate에 대한 first call 전에, traversal이 begin되기 직전에 set됩니다. 이 뒤 array에 appended되는 elements는 predicate에 의해 visited되지 않습니다. array의 existing elements가 changed되면, predicate에 passed되는 그 value는 이 operation이 them을 visit하는 time의 value입니다. traversal이 begin된 뒤 그리고 visited되기 전에 deleted되는 elements도 still visited되며, prototype에서 looked up되거나 undefined입니다.

It performs the following steps when called:

  1. IsCallable(predicate)가 false이면, TypeError exception을 throw한다.
  2. directionascending이면, 다음을 수행한다.
    1. indices를 0(inclusive)부터 length(exclusive)까지의 interval 안의 integers를 ascending order로 가진 List로 둔다.
  3. Else,
    1. indices를 0(inclusive)부터 length(exclusive)까지의 interval 안의 integers를 descending order로 가진 List로 둔다.
  4. indices의 각 integer k에 대해, 다음을 수행한다.
    1. propertyKey를 ! ToString(𝔽(k))로 둔다.
    2. NOTE: objTypedArray이면, following invocation of Getnormal completion을 반환한다.
    3. kValue를 ? Get(obj, propertyKey)로 둔다.
    4. testResult를 ? Call(predicate, thisArg, « kValue, 𝔽(k), obj »)로 둔다.
    5. ToBoolean(testResult)가 true이면, Record { [[Index]]: 𝔽(k), [[Value]]: kValue }를 반환한다.
  5. Record { [[Index]]: -1𝔽, [[Value]]: undefined }를 반환한다.

23.1.3.13 Array.prototype.flat ( [ depth ] )

이 method는 called될 때 다음 steps를 수행합니다:

  1. obj를 ? ToObject(this value)로 둔다.
  2. sourceLength를 ? LengthOfArrayLike(obj)로 둔다.
  3. depthNumber를 1로 둔다.
  4. depthundefined가 아니면, 다음을 수행한다.
    1. depthNumber를 ? ToIntegerOrInfinity(depth)로 설정한다.
    2. depthNumber < 0이면, depthNumber를 0으로 설정한다.
  5. array를 ? ArraySpeciesCreate(obj, 0)로 둔다.
  6. FlattenIntoArray(array, obj, sourceLength, 0, depthNumber)를 수행한다.
  7. array를 반환한다.

23.1.3.13.1 FlattenIntoArray ( target, source, sourceLength, start, depth [ , mapperFunc [ , thisArg ] ] )

The abstract operation FlattenIntoArray takes arguments target (an Object), source (an Object), sourceLength (a non-negative integer), start (a non-negative integer), and depth (a non-negative integer or +∞) and optional arguments mapperFunc (a function object) and thisArg (an ECMAScript language value) and returns either a normal completion containing a non-negative integer or a throw completion. It performs the following steps when called:

  1. Assert: mapperFunc가 present이면, IsCallable(mapperFunc)는 true이고, thisArg는 present이며, depth는 1이다.
  2. targetIndexstart로 둔다.
  3. sourceIndex+0𝔽로 둔다.
  4. Repeat, while (sourceIndex) < sourceLength,
    1. propertyKey를 ! ToString(sourceIndex)로 둔다.
    2. exists를 ? HasProperty(source, propertyKey)로 둔다.
    3. existstrue이면, 다음을 수행한다.
      1. element를 ? Get(source, propertyKey)로 둔다.
      2. mapperFunc가 present이면, 다음을 수행한다.
        1. element를 ? Call(mapperFunc, thisArg, « element, sourceIndex, source »)로 설정한다.
      3. shouldFlattenfalse로 둔다.
      4. depth > 0이면, 다음을 수행한다.
        1. shouldFlatten을 ? IsArray(element)로 설정한다.
      5. shouldFlattentrue이면, 다음을 수행한다.
        1. depth = +∞이면 newDepth를 +∞로 둔다.
        2. Else, newDepthdepth - 1로 둔다.
        3. elementLength를 ? LengthOfArrayLike(element)로 둔다.
        4. targetIndex를 ? FlattenIntoArray(target, element, elementLength, targetIndex, newDepth)로 설정한다.
      6. Else,
        1. targetIndex ≥ 253 - 1이면, TypeError exception을 throw한다.
        2. CreateDataPropertyOrThrow(target, ! ToString(𝔽(targetIndex)), element)를 수행한다.
        3. targetIndextargetIndex + 1로 설정한다.
    4. sourceIndexsourceIndex + 1𝔽로 설정한다.
  5. targetIndex를 반환한다.

23.1.3.14 Array.prototype.flatMap ( mapperFunc [ , thisArg ] )

이 method는 called될 때 다음 steps를 수행합니다:

  1. obj를 ? ToObject(this value)로 둔다.
  2. sourceLength를 ? LengthOfArrayLike(obj)로 둔다.
  3. IsCallable(mapperFunc)가 false이면, TypeError exception을 throw한다.
  4. array를 ? ArraySpeciesCreate(obj, 0)로 둔다.
  5. FlattenIntoArray(array, obj, sourceLength, 0, 1, mapperFunc, thisArg)를 수행한다.
  6. array를 반환한다.

23.1.3.15 Array.prototype.forEach ( callback [ , thisArg ] )

Note 1

callback은 three arguments를 accept하는 function이어야 합니다. forEach는 array에 present한 each element마다 ascending order로 callback을 once call합니다. callback은 actually exist하는 array의 elements에 대해서만 called됩니다; array의 missing elements에 대해서는 called되지 않습니다.

thisArg parameter가 provided되면, callback의 each invocation에 대한 this value로 사용됩니다. provided되지 않으면, 대신 undefined가 사용됩니다.

callback은 three arguments와 함께 called됩니다: element의 value, element의 index, 그리고 traversed되는 object입니다.

forEach는 called된 object를 directly mutate하지 않지만, object는 callback calls에 의해 mutated될 수 있습니다.

forEach에 의해 processed되는 elements의 range는 callback에 대한 first call 전에 set됩니다. forEach call이 begin된 뒤 array에 appended되는 elements는 callback에 의해 visited되지 않습니다. array의 existing elements가 changed되면, callback에 passed되는 그 value는 forEach가 them을 visit하는 time의 value입니다; forEach call이 begin된 뒤 그리고 visited되기 전에 deleted되는 elements는 visited되지 않습니다.

이 method는 called될 때 다음 steps를 수행합니다:

  1. obj를 ? ToObject(this value)로 둔다.
  2. length를 ? LengthOfArrayLike(obj)로 둔다.
  3. IsCallable(callback)가 false이면, TypeError exception을 throw한다.
  4. k를 0으로 둔다.
  5. Repeat, while k < length,
    1. propertyKey를 ! ToString(𝔽(k))로 둔다.
    2. kPresent를 ? HasProperty(obj, propertyKey)로 둔다.
    3. kPresenttrue이면, 다음을 수행한다.
      1. kValue를 ? Get(obj, propertyKey)로 둔다.
      2. Call(callback, thisArg, « kValue, 𝔽(k), obj »)를 수행한다.
    4. kk + 1로 설정한다.
  6. undefined를 반환한다.
Note 2

이 method는 intentionally generic입니다; its this value가 Array일 것을 require하지 않습니다. 따라서 method로 사용하기 위해 other kinds of objects에 transferred될 수 있습니다.

23.1.3.16 Array.prototype.includes ( searchElement [ , fromIndex ] )

Note 1

이 method는 SameValueZero algorithm을 사용하여 searchElement를 array의 elements와 ascending order로 compare하고, any position에서 found되면 true를 반환합니다; otherwise, false를 반환합니다.

optional second argument fromIndex의 default는 +0𝔽입니다(즉, whole array가 searched됩니다). 그것이 array의 length보다 크거나 같으면, false가 returned됩니다, 즉 array는 searched되지 않습니다. 그것이 -0𝔽보다 작으면, fromIndex를 compute하기 위해 array의 end로부터의 offset으로 사용됩니다. computed index가 +0𝔽보다 작거나 같으면, whole array가 searched됩니다.

이 method는 called될 때 다음 steps를 수행합니다:

  1. obj를 ? ToObject(this value)로 둔다.
  2. length를 ? LengthOfArrayLike(obj)로 둔다.
  3. length = 0이면, false를 반환한다.
  4. startIndex를 ? ToIntegerOrInfinity(fromIndex)로 둔다.
  5. Assert: fromIndexundefined이면, startIndex는 0이다.
  6. startIndex = +∞이면, false를 반환한다.
  7. startIndex = -∞이면, startIndex를 0으로 설정한다.
  8. startIndex ≥ 0이면, 다음을 수행한다.
    1. kstartIndex로 둔다.
  9. Else,
    1. klength + startIndex로 둔다.
    2. k < 0이면, k를 0으로 설정한다.
  10. Repeat, while k < length,
    1. elementK를 ? Get(obj, ! ToString(𝔽(k)))로 둔다.
    2. SameValueZero(searchElement, elementK)가 true이면, true를 반환한다.
    3. kk + 1로 설정한다.
  11. false를 반환한다.
Note 2

이 method는 intentionally generic입니다; its this value가 Array일 것을 require하지 않습니다. 따라서 method로 사용하기 위해 other kinds of objects에 transferred될 수 있습니다.

Note 3

이 method는 similar indexOf method와 intentionally two ways에서 다릅니다. First, IsStrictlyEqual 대신 SameValueZero algorithm을 사용하여 NaN array elements를 detect할 수 있습니다. Second, missing array elements를 skip하지 않고, 대신 them을 undefined로 treating합니다.

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를 반환합니다; otherwise, -1𝔽를 반환합니다.

Note 1

optional second argument fromIndex의 default는 +0𝔽입니다(즉, whole array가 searched됩니다). 그것이 array의 length보다 크거나 같으면, -1𝔽가 returned됩니다, 즉 array는 searched되지 않습니다. 그것이 -0𝔽보다 작으면, array의 end로부터 offset을 compute하는 데 사용됩니다. computed index가 +0𝔽보다 작거나 같으면, whole array가 searched됩니다.

이 method는 called될 때 다음 steps를 수행합니다:

  1. obj를 ? ToObject(this value)로 둔다.
  2. length를 ? LengthOfArrayLike(obj)로 둔다.
  3. length = 0이면, -1𝔽를 반환한다.
  4. startIndex를 ? ToIntegerOrInfinity(fromIndex)로 둔다.
  5. Assert: fromIndexundefined이면, startIndex는 0이다.
  6. startIndex = +∞이면, -1𝔽를 반환한다.
  7. startIndex = -∞이면, startIndex를 0으로 설정한다.
  8. startIndex ≥ 0이면, 다음을 수행한다.
    1. kstartIndex로 둔다.
  9. Else,
    1. klength + startIndex로 둔다.
    2. k < 0이면, k를 0으로 설정한다.
  10. Repeat, while k < length,
    1. propertyKey를 ! ToString(𝔽(k))로 둔다.
    2. kPresent를 ? HasProperty(obj, propertyKey)로 둔다.
    3. kPresenttrue이면, 다음을 수행한다.
      1. elementK를 ? Get(obj, propertyKey)로 둔다.
      2. IsStrictlyEqual(searchElement, elementK)가 true이면, 𝔽(k)를 반환한다.
    4. kk + 1로 설정한다.
  11. -1𝔽를 반환한다.
Note 2

이 method는 intentionally generic입니다; its this value가 Array일 것을 require하지 않습니다. 따라서 method로 사용하기 위해 other kinds of objects에 transferred될 수 있습니다.

23.1.3.18 Array.prototype.join ( separator )

이 method는 array의 elements를 Strings로 convert한 뒤, separator의 occurrences로 separated하여 these Strings를 concatenates합니다. separator가 provided되지 않으면, single comma가 separator로 사용됩니다.

called될 때 다음 steps를 수행합니다:

  1. obj를 ? ToObject(this value)로 둔다.
  2. length를 ? LengthOfArrayLike(obj)로 둔다.
  3. separatorundefined이면, sep","로 둔다.
  4. Else, sep를 ? ToString(separator)로 둔다.
  5. result를 empty String으로 둔다.
  6. k를 0으로 둔다.
  7. Repeat, while k < length,
    1. k > 0이면, resultresultsepstring-concatenation으로 설정한다.
    2. element를 ? Get(obj, ! ToString(𝔽(k)))로 둔다.
    3. elementundefinednull도 아니면, 다음을 수행한다.
      1. elementString을 ? ToString(element)로 둔다.
      2. resultresultelementStringstring-concatenation으로 설정한다.
    4. kk + 1로 설정한다.
  8. result를 반환한다.
Note

이 method는 intentionally generic입니다; its this value가 Array일 것을 require하지 않습니다. 따라서 method로 사용하기 위해 other kinds of objects에 transferred될 수 있습니다.

23.1.3.19 Array.prototype.keys ( )

이 method는 called될 때 다음 steps를 수행합니다:

  1. obj를 ? ToObject(this value)로 둔다.
  2. CreateArrayIterator(obj, key)를 반환한다.

23.1.3.20 Array.prototype.lastIndexOf ( searchElement [ , fromIndex ] )

Note 1

이 method는 IsStrictlyEqual algorithm을 사용하여 searchElement를 array의 elements와 descending order로 compare하고, one or more indices에서 found되면 largest such index를 반환합니다; otherwise, -1𝔽를 반환합니다.

optional second argument fromIndex의 default는 array의 length minus one입니다(즉, whole array가 searched됩니다). 그것이 array의 length보다 크거나 같으면, whole array가 searched됩니다. 그것이 -0𝔽보다 작으면, array의 end로부터 offset을 compute하는 데 사용됩니다. computed index가 -0𝔽보다 작으면, -1𝔽가 returned됩니다.

이 method는 called될 때 다음 steps를 수행합니다:

  1. obj를 ? ToObject(this value)로 둔다.
  2. length를 ? LengthOfArrayLike(obj)로 둔다.
  3. length = 0이면, -1𝔽를 반환한다.
  4. fromIndex가 present이면 startIndex를 ? ToIntegerOrInfinity(fromIndex)로 둔다; else startIndexlength - 1로 둔다.
  5. startIndex = -∞이면, -1𝔽를 반환한다.
  6. startIndex ≥ 0이면, 다음을 수행한다.
    1. kmin(startIndex, length - 1)로 둔다.
  7. Else,
    1. klength + startIndex로 둔다.
  8. Repeat, while k ≥ 0,
    1. propertyKey를 ! ToString(𝔽(k))로 둔다.
    2. kPresent를 ? HasProperty(obj, propertyKey)로 둔다.
    3. kPresenttrue이면, 다음을 수행한다.
      1. elementK를 ? Get(obj, propertyKey)로 둔다.
      2. IsStrictlyEqual(searchElement, elementK)가 true이면, 𝔽(k)를 반환한다.
    4. kk - 1로 설정한다.
  9. -1𝔽를 반환한다.
Note 2

이 method는 intentionally generic입니다; its this value가 Array일 것을 require하지 않습니다. 따라서 method로 사용하기 위해 other kinds of objects에 transferred될 수 있습니다.

23.1.3.21 Array.prototype.map ( callback [ , thisArg ] )

Note 1

callback은 three arguments를 accept하는 function이어야 합니다. map은 array의 each element에 대해 ascending order로 callback을 once call하고, results로부터 new Array를 constructs합니다. callback은 actually exist하는 array의 elements에 대해서만 called됩니다; array의 missing elements에 대해서는 called되지 않습니다.

thisArg parameter가 provided되면, callback의 each invocation에 대한 this value로 사용됩니다. provided되지 않으면, 대신 undefined가 사용됩니다.

callback은 three arguments와 함께 called됩니다: element의 value, element의 index, 그리고 traversed되는 object입니다.

map은 called된 object를 directly mutate하지 않지만, object는 callback calls에 의해 mutated될 수 있습니다.

map에 의해 processed되는 elements의 range는 callback에 대한 first call 전에 set됩니다. map call이 begin된 뒤 array에 appended되는 elements는 callback에 의해 visited되지 않습니다. array의 existing elements가 changed되면, callback에 passed되는 그 value는 map이 them을 visit하는 time의 value입니다; map call이 begin된 뒤 그리고 visited되기 전에 deleted되는 elements는 visited되지 않습니다.

이 method는 called될 때 다음 steps를 수행합니다:

  1. obj를 ? ToObject(this value)로 둔다.
  2. length를 ? LengthOfArrayLike(obj)로 둔다.
  3. IsCallable(callback)가 false이면, TypeError exception을 throw한다.
  4. array를 ? ArraySpeciesCreate(obj, length)로 둔다.
  5. k를 0으로 둔다.
  6. Repeat, while k < length,
    1. propertyKey를 ! ToString(𝔽(k))로 둔다.
    2. kPresent를 ? HasProperty(obj, propertyKey)로 둔다.
    3. kPresenttrue이면, 다음을 수행한다.
      1. kValue를 ? Get(obj, propertyKey)로 둔다.
      2. mappedValue를 ? Call(callback, thisArg, « kValue, 𝔽(k), obj »)로 둔다.
      3. CreateDataPropertyOrThrow(array, propertyKey, mappedValue)를 수행한다.
    4. kk + 1로 설정한다.
  7. array를 반환한다.
Note 2

이 method는 intentionally generic입니다; its this value가 Array일 것을 require하지 않습니다. 따라서 method로 사용하기 위해 other kinds of objects에 transferred될 수 있습니다.

23.1.3.22 Array.prototype.pop ( )

Note 1

이 method는 array의 last element를 removes하고 그것을 반환합니다.

이 method는 called될 때 다음 steps를 수행합니다:

  1. obj를 ? ToObject(this value)로 둔다.
  2. length를 ? LengthOfArrayLike(obj)로 둔다.
  3. length = 0이면, 다음을 수행한다.
    1. Set(obj, "length", +0𝔽, true)를 수행한다.
    2. undefined를 반환한다.
  4. Assert: length > 0이다.
  5. newLength𝔽(length - 1)로 둔다.
  6. index를 ! ToString(newLength)로 둔다.
  7. element를 ? Get(obj, index)로 둔다.
  8. DeletePropertyOrThrow(obj, index)를 수행한다.
  9. Set(obj, "length", newLength, true)를 수행한다.
  10. element를 반환한다.
Note 2

이 method는 intentionally generic입니다; its this value가 Array일 것을 require하지 않습니다. 따라서 method로 사용하기 위해 other kinds of objects에 transferred될 수 있습니다.

23.1.3.23 Array.prototype.push ( ...items )

Note 1

이 method는 arguments를 그들이 appear하는 order로 array의 end에 appends합니다. 이는 array의 new length를 반환합니다.

이 method는 called될 때 다음 steps를 수행합니다:

  1. obj를 ? ToObject(this value)로 둔다.
  2. length를 ? LengthOfArrayLike(obj)로 둔다.
  3. argCountitems 안의 elements 수로 둔다.
  4. length + argCount > 253 - 1이면, TypeError exception을 throw한다.
  5. items의 각 element item에 대해, 다음을 수행한다.
    1. Set(obj, ! ToString(𝔽(length)), item, true)를 수행한다.
    2. lengthlength + 1로 설정한다.
  6. Set(obj, "length", 𝔽(length), true)를 수행한다.
  7. 𝔽(length)를 반환한다.

이 method의 "length" property는 1𝔽입니다.

Note 2

이 method는 intentionally generic입니다; its this value가 Array일 것을 require하지 않습니다. 따라서 method로 사용하기 위해 other kinds of objects에 transferred될 수 있습니다.

23.1.3.24 Array.prototype.reduce ( callback [ , initialValue ] )

Note 1

callback은 four arguments를 take하는 function이어야 합니다. reduceinitialValue가 provided되지 않는 한 first element를 skipping하면서, array에 present한 each element에 대해 ascending order로 callback을 once call합니다.

callback은 four arguments와 함께 called됩니다: previousValue(callback에 대한 previous call로부터의 value), currentValue(current element의 value), currentIndex, 그리고 traversed되는 object입니다. callback이 처음 called될 때, previousValuecurrentValue는 two values 중 하나일 수 있습니다. reduce call에 initialValue가 supplied되었으면, previousValueinitialValue가 되고 currentValue는 array의 first value가 됩니다. initialValue가 supplied되지 않았으면, previousValue는 array의 first value가 되고 currentValue는 second가 됩니다. array가 no elements를 contain하고 initialValue가 provided되지 않으면 TypeError입니다.

reduce는 called된 object를 directly mutate하지 않지만, object는 callback calls에 의해 mutated될 수 있습니다.

reduce에 의해 processed되는 elements의 range는 callback에 대한 first call 전에 set됩니다. reduce call이 begin된 뒤 array에 appended되는 elements는 callback에 의해 visited되지 않습니다. array의 existing elements가 changed되면, callback에 passed되는 그 value는 reduce가 them을 visit하는 time의 value입니다; reduce call이 begin된 뒤 그리고 visited되기 전에 deleted되는 elements는 visited되지 않습니다.

이 method는 called될 때 다음 steps를 수행합니다:

  1. obj를 ? ToObject(this value)로 둔다.
  2. length를 ? LengthOfArrayLike(obj)로 둔다.
  3. IsCallable(callback)가 false이면, TypeError exception을 throw한다.
  4. length = 0이고 initialValue가 present하지 않으면, TypeError exception을 throw한다.
  5. k를 0으로 둔다.
  6. accumulatorundefined로 둔다.
  7. initialValue가 present이면, 다음을 수행한다.
    1. accumulatorinitialValue로 설정한다.
  8. Else,
    1. kPresentfalse로 둔다.
    2. Repeat, while kPresent is false and k < length,
      1. propertyKey를 ! ToString(𝔽(k))로 둔다.
      2. kPresent를 ? HasProperty(obj, propertyKey)로 설정한다.
      3. kPresenttrue이면, 다음을 수행한다.
        1. accumulator를 ? Get(obj, propertyKey)로 설정한다.
      4. kk + 1로 설정한다.
    3. kPresentfalse이면, TypeError exception을 throw한다.
  9. Repeat, while k < length,
    1. propertyKey를 ! ToString(𝔽(k))로 둔다.
    2. kPresent를 ? HasProperty(obj, propertyKey)로 둔다.
    3. kPresenttrue이면, 다음을 수행한다.
      1. kValue를 ? Get(obj, propertyKey)로 둔다.
      2. accumulator를 ? Call(callback, undefined, « accumulator, kValue, 𝔽(k), obj »)로 설정한다.
    4. kk + 1로 설정한다.
  10. accumulator를 반환한다.
Note 2

이 method는 intentionally generic입니다; its this value가 Array일 것을 require하지 않습니다. 따라서 method로 사용하기 위해 other kinds of objects에 transferred될 수 있습니다.

23.1.3.25 Array.prototype.reduceRight ( callback [ , initialValue ] )

Note 1

callback은 four arguments를 take하는 function이어야 합니다. reduceRightinitialValue가 provided되지 않는 한 first call을 skipping하면서, array에 present한 each element에 대해 descending order로 callback을 once call합니다.

callback은 four arguments와 함께 called됩니다: previousValue(callback에 대한 previous call로부터의 value), currentValue(current element의 value), currentIndex, 그리고 traversed되는 object입니다. function이 처음 called될 때, previousValuecurrentValue는 two values 중 하나일 수 있습니다. reduceRight call에 initialValue가 supplied되었으면, previousValueinitialValue가 되고 currentValue는 array의 last value가 됩니다. initialValue가 supplied되지 않았으면, previousValue는 array의 last value가 되고 currentValue는 second-to-last value가 됩니다. array가 no elements를 contain하고 initialValue가 provided되지 않으면 TypeError입니다.

reduceRight는 called된 object를 directly mutate하지 않지만, object는 callback calls에 의해 mutated될 수 있습니다.

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가 them을 visit하는 time의 value입니다; reduceRight call이 begin된 뒤 그리고 visited되기 전에 deleted되는 elements는 visited되지 않습니다.

이 method는 called될 때 다음 steps를 수행합니다:

  1. obj를 ? ToObject(this value)로 둔다.
  2. length를 ? LengthOfArrayLike(obj)로 둔다.
  3. IsCallable(callback)가 false이면, TypeError exception을 throw한다.
  4. length = 0이고 initialValue가 present하지 않으면, TypeError exception을 throw한다.
  5. klength - 1로 둔다.
  6. accumulatorundefined로 둔다.
  7. initialValue가 present이면, 다음을 수행한다.
    1. accumulatorinitialValue로 설정한다.
  8. Else,
    1. kPresentfalse로 둔다.
    2. Repeat, while kPresent is false and k ≥ 0,
      1. propertyKey를 ! ToString(𝔽(k))로 둔다.
      2. kPresent를 ? HasProperty(obj, propertyKey)로 설정한다.
      3. kPresenttrue이면, 다음을 수행한다.
        1. accumulator를 ? Get(obj, propertyKey)로 설정한다.
      4. kk - 1로 설정한다.
    3. kPresentfalse이면, TypeError exception을 throw한다.
  9. Repeat, while k ≥ 0,
    1. propertyKey를 ! ToString(𝔽(k))로 둔다.
    2. kPresent를 ? HasProperty(obj, propertyKey)로 둔다.
    3. kPresenttrue이면, 다음을 수행한다.
      1. kValue를 ? Get(obj, propertyKey)로 둔다.
      2. accumulator를 ? Call(callback, undefined, « accumulator, kValue, 𝔽(k), obj »)로 설정한다.
    4. kk - 1로 설정한다.
  10. accumulator를 반환한다.
Note 2

이 method는 intentionally generic입니다; its this value가 Array일 것을 require하지 않습니다. 따라서 method로 사용하기 위해 other kinds of objects에 transferred될 수 있습니다.

23.1.3.26 Array.prototype.reverse ( )

Note 1

이 method는 array의 elements를 rearrange하여 their order를 reverse합니다. 이는 reversed array를 반환합니다.

이 method는 called될 때 다음 steps를 수행합니다:

  1. obj를 ? ToObject(this value)로 둔다.
  2. length를 ? LengthOfArrayLike(obj)로 둔다.
  3. middlefloor(length / 2)로 둔다.
  4. lower를 0으로 둔다.
  5. Repeat, while lowermiddle,
    1. upperlength - lower - 1로 둔다.
    2. upperP를 ! ToString(𝔽(upper))로 둔다.
    3. lowerP를 ! ToString(𝔽(lower))로 둔다.
    4. lowerExists를 ? HasProperty(obj, lowerP)로 둔다.
    5. lowerExiststrue이면, 다음을 수행한다.
      1. lowerValue를 ? Get(obj, lowerP)로 둔다.
    6. upperExists를 ? HasProperty(obj, upperP)로 둔다.
    7. upperExiststrue이면, 다음을 수행한다.
      1. upperValue를 ? Get(obj, upperP)로 둔다.
    8. lowerExiststrue이고 upperExiststrue이면, 다음을 수행한다.
      1. Set(obj, lowerP, upperValue, true)를 수행한다.
      2. Set(obj, upperP, lowerValue, true)를 수행한다.
    9. Else if lowerExistsfalse이고 upperExiststrue이면, 다음을 수행한다.
      1. Set(obj, lowerP, upperValue, true)를 수행한다.
      2. DeletePropertyOrThrow(obj, upperP)를 수행한다.
    10. Else if lowerExiststrue이고 upperExistsfalse이면, 다음을 수행한다.
      1. DeletePropertyOrThrow(obj, lowerP)를 수행한다.
      2. Set(obj, upperP, lowerValue, true)를 수행한다.
    11. Else,
      1. Assert: lowerExistsupperExists는 모두 false이다.
      2. NOTE: action은 required되지 않는다.
    12. lowerlower + 1로 설정한다.
  6. obj를 반환한다.
Note 2

이 method는 intentionally generic입니다; its this value가 Array일 것을 require하지 않습니다. 따라서 method로 사용하기 위해 other kinds of objects에 transferred될 수 있습니다.

23.1.3.27 Array.prototype.shift ( )

이 method는 array의 first element를 removes하고 그것을 반환합니다.

called될 때 다음 steps를 수행합니다:

  1. obj를 ? ToObject(this value)로 둔다.
  2. length를 ? LengthOfArrayLike(obj)로 둔다.
  3. length = 0이면, 다음을 수행한다.
    1. Set(obj, "length", +0𝔽, true)를 수행한다.
    2. undefined를 반환한다.
  4. first를 ? Get(obj, "0")로 둔다.
  5. k를 1로 둔다.
  6. Repeat, while k < length,
    1. from을 ! ToString(𝔽(k))로 둔다.
    2. to를 ! ToString(𝔽(k - 1))로 둔다.
    3. fromPresent를 ? HasProperty(obj, from)로 둔다.
    4. fromPresenttrue이면, 다음을 수행한다.
      1. fromValue를 ? Get(obj, from)로 둔다.
      2. Set(obj, to, fromValue, true)를 수행한다.
    5. Else,
      1. Assert: fromPresentfalse이다.
      2. DeletePropertyOrThrow(obj, to)를 수행한다.
    6. kk + 1로 설정한다.
  7. DeletePropertyOrThrow(obj, ! ToString(𝔽(length - 1)))를 수행한다.
  8. Set(obj, "length", 𝔽(length - 1), true)를 수행한다.
  9. first를 반환한다.
Note

이 method는 intentionally generic입니다; its this value가 Array일 것을 require하지 않습니다. 따라서 method로 사용하기 위해 other kinds of objects에 transferred될 수 있습니다.

23.1.3.28 Array.prototype.slice ( start, end )

이 method는 element start부터 element end 전까지(or endundefined이면 array의 end까지) array의 elements를 contain하는 array를 반환합니다. start가 negative이면, array의 length인 length에 대해 length + start로 treated됩니다. end가 negative이면, array의 length인 length에 대해 length + end로 treated됩니다.

called될 때 다음 steps를 수행합니다:

  1. obj를 ? ToObject(this value)로 둔다.
  2. length를 ? LengthOfArrayLike(obj)로 둔다.
  3. relativeStart를 ? ToIntegerOrInfinity(start)로 둔다.
  4. relativeStart = -∞이면, k를 0으로 둔다.
  5. Else if relativeStart < 0이면, kmax(length + relativeStart, 0)으로 둔다.
  6. Else, kmin(relativeStart, length)로 둔다.
  7. endundefined이면 relativeEndlength로 둔다; else relativeEnd를 ? ToIntegerOrInfinity(end)로 둔다.
  8. relativeEnd = -∞이면, final을 0으로 둔다.
  9. Else if relativeEnd < 0이면, finalmax(length + relativeEnd, 0)으로 둔다.
  10. Else, finalmin(relativeEnd, length)로 둔다.
  11. countmax(final - k, 0)으로 둔다.
  12. array를 ? ArraySpeciesCreate(obj, count)로 둔다.
  13. resultIndex를 0으로 둔다.
  14. Repeat, while k < final,
    1. propertyKey를 ! ToString(𝔽(k))로 둔다.
    2. kPresent를 ? HasProperty(obj, propertyKey)로 둔다.
    3. kPresenttrue이면, 다음을 수행한다.
      1. kValue를 ? Get(obj, propertyKey)로 둔다.
      2. CreateDataPropertyOrThrow(array, ! ToString(𝔽(resultIndex)), kValue)를 수행한다.
    4. kk + 1로 설정한다.
    5. resultIndexresultIndex + 1로 설정한다.
  15. Set(array, "length", 𝔽(resultIndex), true)를 수행한다.
  16. array를 반환한다.
Note 1

step 15에서 "length" property를 explicitly setting하는 것은 array가 built-in Array가 아닌 경우에도 length가 correct함을 ensure하기 위한 것입니다.

Note 2

이 method는 intentionally generic입니다; its this value가 Array일 것을 require하지 않습니다. 따라서 method로 사용하기 위해 other kinds of objects에 transferred될 수 있습니다.

23.1.3.29 Array.prototype.some ( callback [ , thisArg ] )

Note 1

callback은 three arguments를 accept하고 Boolean value로 coercible한 value를 return하는 function이어야 합니다. somecallbacktrue를 return하는 one을 find할 때까지 array에 present한 each element에 대해 ascending order로 callback을 once call합니다. such element가 found되면, some은 immediately true를 반환합니다. Otherwise, somefalse를 반환합니다. callback은 actually exist하는 array의 elements에 대해서만 called됩니다; array의 missing elements에 대해서는 called되지 않습니다.

thisArg parameter가 provided되면, callback의 each invocation에 대한 this value로 사용됩니다. provided되지 않으면, 대신 undefined가 사용됩니다.

callback은 three arguments와 함께 called됩니다: element의 value, element의 index, 그리고 traversed되는 object입니다.

some은 called된 object를 directly mutate하지 않지만, object는 callback calls에 의해 mutated될 수 있습니다.

some에 의해 processed되는 elements의 range는 callback에 대한 first call 전에 set됩니다. some call이 begin된 뒤 array에 appended되는 elements는 callback에 의해 visited되지 않습니다. array의 existing elements가 changed되면, callback에 passed되는 그 value는 some이 them을 visit하는 time의 value입니다; some call이 begin된 뒤 그리고 visited되기 전에 deleted되는 elements는 visited되지 않습니다. some은 mathematics의 “exists” quantifier처럼 acts합니다. 특히 empty array에 대해서는 false를 반환합니다.

이 method는 called될 때 다음 steps를 수행합니다:

  1. obj를 ? ToObject(this value)로 둔다.
  2. length를 ? LengthOfArrayLike(obj)로 둔다.
  3. IsCallable(callback)가 false이면, TypeError exception을 throw한다.
  4. k를 0으로 둔다.
  5. Repeat, while k < length,
    1. propertyKey를 ! ToString(𝔽(k))로 둔다.
    2. kPresent를 ? HasProperty(obj, propertyKey)로 둔다.
    3. kPresenttrue이면, 다음을 수행한다.
      1. kValue를 ? Get(obj, propertyKey)로 둔다.
      2. testResultToBoolean(? Call(callback, thisArg, « kValue, 𝔽(k), obj »))로 둔다.
      3. testResulttrue이면, true를 반환한다.
    4. kk + 1로 설정한다.
  6. false를 반환한다.
Note 2

이 method는 intentionally generic입니다; its this value가 Array일 것을 require하지 않습니다. 따라서 method로 사용하기 위해 other kinds of objects에 transferred될 수 있습니다.

23.1.3.30 Array.prototype.sort ( comparator )

이 method는 this array의 elements를 sorts합니다. comparatorundefined가 아니면, arguments xy two를 accept하고 x < y이면 negative Number, x > y이면 positive Number, otherwise zero를 return하는 function이어야 합니다.

called될 때 다음 steps를 수행합니다:

  1. comparatorundefined가 아니고 IsCallable(comparator)가 false이면, TypeError exception을 throw한다.
  2. obj를 ? ToObject(this value)로 둔다.
  3. length를 ? LengthOfArrayLike(obj)로 둔다.
  4. comparator를 capture하고 called될 때 다음 steps를 수행하는, parameters (x, y)를 가진 새 Abstract Closure sortCompare를 둔다:
    1. CompareArrayElements(x, y, comparator)를 반환한다.
  5. sortedList를 ? SortIndexedProperties(obj, length, sortCompare, skip-holes)로 둔다.
  6. itemCountsortedList 안의 elements 수로 둔다.
  7. j를 0으로 둔다.
  8. Repeat, while j < itemCount,
    1. Set(obj, ! ToString(𝔽(j)), sortedList[j], true)를 수행한다.
    2. jj + 1로 설정한다.
  9. NOTE: step 5SortIndexedProperties call은 skip-holes를 사용한다. remaining indices는 detected되어 sort에서 excluded된 holes 수를 preserve하기 위해 deleted된다.
  10. Repeat, while j < length,
    1. DeletePropertyOrThrow(obj, ! ToString(𝔽(j)))를 수행한다.
    2. jj + 1로 설정한다.
  11. obj를 반환한다.
Note 1

non-existent property values는 always undefined property values보다 greater로 compare되고, undefined는 always any other value보다 greater로 compare되므로(CompareArrayElements 참조), undefined property values는 always result의 end로 sort되고, 그 뒤에 non-existent property values가 followed됩니다.

Note 2

steps 56ToString abstract operations에 의해 performed되는 method calls는 sortCompareconsistent comparator로 behave하지 않게 할 potential을 가집니다.

Note 3

이 method는 intentionally generic입니다; its this value가 Array일 것을 require하지 않습니다. 따라서 method로 사용하기 위해 other kinds of objects에 transferred될 수 있습니다.

23.1.3.30.1 SortIndexedProperties ( obj, length, sortCompare, holes )

The abstract operation SortIndexedProperties takes arguments obj (an Object), length (a non-negative integer), sortCompare (an Abstract Closure with two parameters), and holes (skip-holes or read-through-holes) and returns either a normal completion containing a List of ECMAScript language values or a throw completion. It performs the following steps when called:

  1. items를 새 empty List로 둔다.
  2. k를 0으로 둔다.
  3. Repeat, while k < length,
    1. propertyKey를 ! ToString(𝔽(k))로 둔다.
    2. holesskip-holes이면, 다음을 수행한다.
      1. kRead를 ? HasProperty(obj, propertyKey)로 둔다.
    3. Else,
      1. Assert: holesread-through-holes이다.
      2. kReadtrue로 둔다.
    4. kReadtrue이면, 다음을 수행한다.
      1. kValue를 ? Get(obj, propertyKey)로 둔다.
      2. kValueitems에 append한다.
    5. kk + 1로 설정한다.
  4. implementation-defined sequence of calls to sortCompare를 사용하여 items를 Sort한다. such call이 abrupt completion을 return하면, sortCompare에 대한 any further calls를 수행하기 전에 stop하고 that Completion Record를 반환한다.
  5. items를 반환한다.

sort order는 위 algorithm의 step 4 completion 후 items의 ordering입니다. sortCompareitems의 elements에 대한 consistent comparator가 아니면 sort orderimplementation-defined입니다. SortIndexedProperties가 Array.prototype.sort 또는 Array.prototype.toSorted에 의해 invoked될 때, comparatorundefined이고 sortCompare에 argument로 passed되는 any specific value에 대한 ToString의 all applications가 same result를 produce하지 않으면 sort orderimplementation-defined입니다.

sort orderimplementation-defined로 specified되지 않는 한, 다음 conditions를 모두 satisfy해야 합니다:

  • itemCount보다 작은 non-negative integers의 어떤 mathematical permutation π가 존재하여, itemCount보다 작은 every non-negative integer j에 대해 element old[j]가 exactly new[π(j)]와 same해야 합니다.
  • 그런 다음 itemCount보다 작은 all non-negative integers jk에 대해, (sortCompare(old[j], old[k])) < 0이면, π(j) < π(k)입니다.
  • 그리고 j < k < itemCount인 all non-negative integers jk에 대해, (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 same value)에 대해 below requirements가 모두 met되면 values values의 set에 대한 consistent comparator입니다: notation a <C b(comparator(a, b)) < 0를 의미합니다; a =C b(comparator(a, b)) = 0를 의미합니다; 그리고 a >C b(comparator(a, b)) > 0를 의미합니다.

  • specific pair of values ab가 two arguments로 given될 때 comparator(a, b)를 calling하면 always same value v를 return합니다. Furthermore, v는 Number이고, vNaN이 아닙니다. 이는 given pair of a and b에 대해 a <C b, a =C b, 및 a >C b 중 exactly one이 true일 것을 imply함에 note하십시오.
  • comparator(a, b)를 calling해도 obj 또는 obj의 prototype chain에 있는 any object를 modify하지 않습니다.
  • a =C a (reflexivity)
  • a =C b이면, b =C a입니다 (symmetry)
  • a =C b이고 b =C c이면, a =C c입니다 (transitivity of =C)
  • a <C b이고 b <C c이면, a <C c입니다 (transitivity of <C)
  • a >C b이고 b >C c이면, a >C c입니다 (transitivity of >C)
Note

위 conditions는 comparator가 set values를 equivalence classes로 divide하고, 이러한 equivalence classes가 totally ordered되도록 ensure하는 데 necessary and sufficient합니다.

23.1.3.30.2 CompareArrayElements ( x, y, comparator )

The abstract operation CompareArrayElements takes arguments x (an ECMAScript language value), y (an ECMAScript language value), and comparator (a function object or undefined) and returns either a normal completion containing a Number or an abrupt completion. It performs the following steps when called:

  1. xundefined이고 yundefined이면, +0𝔽를 반환한다.
  2. xundefined이면, 1𝔽를 반환한다.
  3. yundefined이면, -1𝔽를 반환한다.
  4. comparatorundefined가 아니면, 다음을 수행한다.
    1. result를 ? ToNumber(? Call(comparator, undefined, « x, y »))로 둔다.
    2. resultNaN이면, +0𝔽를 반환한다.
    3. result를 반환한다.
  5. xString을 ? ToString(x)로 둔다.
  6. yString을 ? ToString(y)로 둔다.
  7. xSmaller를 ! IsLessThan(xString, yString, true)로 둔다.
  8. xSmallertrue이면, -1𝔽를 반환한다.
  9. ySmaller를 ! IsLessThan(yString, xString, true)로 둔다.
  10. ySmallertrue이면, 1𝔽를 반환한다.
  11. +0𝔽를 반환한다.

23.1.3.31 Array.prototype.splice ( start, deleteCount, ...items )

Note 1

이 method는 integer index start에서 starting하는 array의 deleteCount elements를 deletes하고, them을 items의 elements로 replaces합니다. 이는 deleted elements(if any)를 contain하는 Array를 반환합니다.

이 method는 called될 때 다음 steps를 수행합니다:

  1. obj를 ? ToObject(this value)로 둔다.
  2. length를 ? LengthOfArrayLike(obj)로 둔다.
  3. relativeStart를 ? ToIntegerOrInfinity(start)로 둔다.
  4. relativeStart = -∞이면, actualStart를 0으로 둔다.
  5. Else if relativeStart < 0이면, actualStartmax(length + relativeStart, 0)으로 둔다.
  6. Else, actualStartmin(relativeStart, length)로 둔다.
  7. itemCountitems 안의 elements 수로 둔다.
  8. start가 present하지 않으면, 다음을 수행한다.
    1. actualDeleteCount를 0으로 둔다.
  9. Else if deleteCount가 present하지 않으면, 다음을 수행한다.
    1. actualDeleteCountlength - actualStart로 둔다.
  10. Else,
    1. dc를 ? ToIntegerOrInfinity(deleteCount)로 둔다.
    2. actualDeleteCountdc를 0과 length - actualStart 사이로 clamping한 result로 둔다.
  11. length + itemCount - actualDeleteCount > 253 - 1이면, TypeError exception을 throw한다.
  12. deletedArray를 ? ArraySpeciesCreate(obj, actualDeleteCount)로 둔다.
  13. k를 0으로 둔다.
  14. Repeat, while k < actualDeleteCount,
    1. from을 ! ToString(𝔽(actualStart + k))로 둔다.
    2. HasProperty(obj, from)가 true이면, 다음을 수행한다.
      1. fromValue를 ? Get(obj, from)로 둔다.
      2. CreateDataPropertyOrThrow(deletedArray, ! ToString(𝔽(k)), fromValue)를 수행한다.
    3. kk + 1로 설정한다.
  15. Set(deletedArray, "length", 𝔽(actualDeleteCount), true)를 수행한다.
  16. itemCount < actualDeleteCount이면, 다음을 수행한다.
    1. kactualStart로 설정한다.
    2. Repeat, while k < (length - actualDeleteCount),
      1. from을 ! ToString(𝔽(k + actualDeleteCount))로 둔다.
      2. to를 ! ToString(𝔽(k + itemCount))로 둔다.
      3. HasProperty(obj, from)가 true이면, 다음을 수행한다.
        1. fromValue를 ? Get(obj, from)로 둔다.
        2. Set(obj, to, fromValue, true)를 수행한다.
      4. Else,
        1. DeletePropertyOrThrow(obj, to)를 수행한다.
      5. kk + 1로 설정한다.
    3. klength로 설정한다.
    4. Repeat, while k > (length - actualDeleteCount + itemCount),
      1. DeletePropertyOrThrow(obj, ! ToString(𝔽(k - 1)))를 수행한다.
      2. kk - 1로 설정한다.
  17. Else if itemCount > actualDeleteCount이면, 다음을 수행한다.
    1. k를 (length - actualDeleteCount)로 설정한다.
    2. Repeat, while k > actualStart,
      1. from을 ! ToString(𝔽(k + actualDeleteCount - 1))로 둔다.
      2. to를 ! ToString(𝔽(k + itemCount - 1))로 둔다.
      3. HasProperty(obj, from)가 true이면, 다음을 수행한다.
        1. fromValue를 ? Get(obj, from)로 둔다.
        2. Set(obj, to, fromValue, true)를 수행한다.
      4. Else,
        1. DeletePropertyOrThrow(obj, to)를 수행한다.
      5. kk - 1로 설정한다.
  18. kactualStart로 설정한다.
  19. items의 각 element item에 대해, 다음을 수행한다.
    1. Set(obj, ! ToString(𝔽(k)), item, true)를 수행한다.
    2. kk + 1로 설정한다.
  20. Set(obj, "length", 𝔽(length - actualDeleteCount + itemCount), true)를 수행한다.
  21. deletedArray를 반환한다.
Note 2

steps 1520에서 "length" property를 explicitly setting하는 것은 objects가 built-in Arrays가 아닌 경우에도 lengths가 correct함을 ensure하기 위한 것입니다.

Note 3

이 method는 intentionally generic입니다; its this value가 Array일 것을 require하지 않습니다. 따라서 method로 사용하기 위해 other kinds of objects에 transferred될 수 있습니다.

23.1.3.32 Array.prototype.toLocaleString ( [ reserved1 [ , reserved2 ] ] )

ECMA-402 Internationalization API를 include하는 ECMAScript implementation은 ECMA-402 specification에 specified된 대로 이 method를 implement해야 합니다. ECMAScript implementation이 ECMA-402 API를 include하지 않으면 이 method의 다음 specification이 사용됩니다.

Note 1

ECMA-402의 first edition은 이 method에 대한 replacement specification을 include하지 않았습니다.

이 method의 optional parameters의 meanings는 ECMA-402 specification에 defined되어 있습니다; ECMA-402 support를 include하지 않는 implementations는 those parameter positions를 anything else에 사용해서는 안 됩니다.

이 method는 called될 때 다음 steps를 수행합니다:

  1. array를 ? ToObject(this value)로 둔다.
  2. length를 ? LengthOfArrayLike(array)로 둔다.
  3. separatorhost environment의 current locale에 appropriate한 implementation-defined list-separator String value(such as ", ")로 둔다.
  4. result를 empty String으로 둔다.
  5. k를 0으로 둔다.
  6. Repeat, while k < length,
    1. k > 0이면, resultresultseparatorstring-concatenation으로 설정한다.
    2. element를 ? Get(array, ! ToString(𝔽(k)))로 둔다.
    3. elementundefinednull도 아니면, 다음을 수행한다.
      1. elementString을 ? ToString(? Invoke(element, "toLocaleString"))로 둔다.
      2. resultresultelementStringstring-concatenation으로 설정한다.
    4. kk + 1로 설정한다.
  7. result를 반환한다.
Note 2

이 method는 array의 elements를 their toLocaleString methods를 사용하여 Strings로 convert한 뒤, implementation-defined locale-sensitive separator String의 occurrences로 separated하여 these Strings를 concatenates합니다. 이 method는 host environment의 current locale의 conventions와 corresponding하는 locale-sensitive result를 yield하도록 intended된다는 점을 제외하면 toString과 analogous합니다.

Note 3

이 method는 intentionally generic입니다; its this value가 Array일 것을 require하지 않습니다. 따라서 method로 사용하기 위해 other kinds of objects에 transferred될 수 있습니다.

23.1.3.33 Array.prototype.toReversed ( )

이 method는 called될 때 다음 steps를 수행합니다:

  1. obj를 ? ToObject(this value)로 둔다.
  2. length를 ? LengthOfArrayLike(obj)로 둔다.
  3. array를 ? ArrayCreate(length)로 둔다.
  4. k를 0으로 둔다.
  5. Repeat, while k < length,
    1. from을 ! ToString(𝔽(length - k - 1))로 둔다.
    2. propertyKey를 ! ToString(𝔽(k))로 둔다.
    3. fromValue를 ? Get(obj, from)로 둔다.
    4. CreateDataPropertyOrThrow(array, propertyKey, fromValue)를 수행한다.
    5. kk + 1로 설정한다.
  6. array를 반환한다.

23.1.3.34 Array.prototype.toSorted ( comparator )

이 method는 called될 때 다음 steps를 수행합니다:

  1. comparatorundefined가 아니고 IsCallable(comparator)가 false이면, TypeError exception을 throw한다.
  2. obj를 ? ToObject(this value)로 둔다.
  3. length를 ? LengthOfArrayLike(obj)로 둔다.
  4. array를 ? ArrayCreate(length)로 둔다.
  5. comparator를 capture하고 called될 때 다음 steps를 수행하는, parameters (x, y)를 가진 새 Abstract Closure sortCompare를 둔다:
    1. CompareArrayElements(x, y, comparator)를 반환한다.
  6. sortedList를 ? SortIndexedProperties(obj, length, sortCompare, read-through-holes)로 둔다.
  7. j를 0으로 둔다.
  8. Repeat, while j < length,
    1. CreateDataPropertyOrThrow(array, ! ToString(𝔽(j)), sortedList[j])를 수행한다.
    2. jj + 1로 설정한다.
  9. array를 반환한다.

23.1.3.35 Array.prototype.toSpliced ( start, skipCount, ...items )

이 method는 called될 때 다음 steps를 수행합니다:

  1. obj를 ? ToObject(this value)로 둔다.
  2. length를 ? LengthOfArrayLike(obj)로 둔다.
  3. relativeStart를 ? ToIntegerOrInfinity(start)로 둔다.
  4. relativeStart = -∞이면, actualStart를 0으로 둔다.
  5. Else if relativeStart < 0이면, actualStartmax(length + relativeStart, 0)으로 둔다.
  6. Else, actualStartmin(relativeStart, length)로 둔다.
  7. insertCountitems 안의 elements 수로 둔다.
  8. start가 present하지 않으면, 다음을 수행한다.
    1. actualSkipCount를 0으로 둔다.
  9. Else if skipCount가 present하지 않으면, 다음을 수행한다.
    1. actualSkipCountlength - actualStart로 둔다.
  10. Else,
    1. sc를 ? ToIntegerOrInfinity(skipCount)로 둔다.
    2. actualSkipCountsc를 0과 length - actualStart 사이로 clamping한 result로 둔다.
  11. newLengthlength + insertCount - actualSkipCount로 둔다.
  12. newLength > 253 - 1이면, TypeError exception을 throw한다.
  13. newArray를 ? ArrayCreate(newLength)로 둔다.
  14. writeIndex를 0으로 둔다.
  15. readIndexactualStart + actualSkipCount로 둔다.
  16. Repeat, while writeIndex < actualStart,
    1. propertyKey를 ! ToString(𝔽(writeIndex))로 둔다.
    2. iValue를 ? Get(obj, propertyKey)로 둔다.
    3. CreateDataPropertyOrThrow(newArray, propertyKey, iValue)를 수행한다.
    4. writeIndexwriteIndex + 1로 설정한다.
  17. items의 각 element item에 대해, 다음을 수행한다.
    1. propertyKey를 ! ToString(𝔽(writeIndex))로 둔다.
    2. CreateDataPropertyOrThrow(newArray, propertyKey, item)를 수행한다.
    3. writeIndexwriteIndex + 1로 설정한다.
  18. Repeat, while writeIndex < newLength,
    1. propertyKey를 ! ToString(𝔽(writeIndex))로 둔다.
    2. from을 ! ToString(𝔽(readIndex))로 둔다.
    3. fromValue를 ? Get(obj, from)로 둔다.
    4. CreateDataPropertyOrThrow(newArray, propertyKey, fromValue)를 수행한다.
    5. writeIndexwriteIndex + 1로 설정한다.
    6. readIndexreadIndex + 1로 설정한다.
  19. newArray를 반환한다.

23.1.3.36 Array.prototype.toString ( )

이 method는 called될 때 다음 steps를 수행합니다:

  1. array를 ? ToObject(this value)로 둔다.
  2. func를 ? Get(array, "join")로 둔다.
  3. IsCallable(func)가 false이면, func를 intrinsic function %Object.prototype.toString%으로 설정한다.
  4. Call(func, array)를 반환한다.
Note

이 method는 intentionally generic입니다; its this value가 Array일 것을 require하지 않습니다. 따라서 method로 사용하기 위해 other kinds of objects에 transferred될 수 있습니다.

23.1.3.37 Array.prototype.unshift ( ...items )

이 method는 arguments를 array의 start에 prepends하여, array 안에서 their order가 argument list에 appear하는 order와 same이 되도록 합니다.

called될 때 다음 steps를 수행합니다:

  1. obj를 ? ToObject(this value)로 둔다.
  2. length를 ? LengthOfArrayLike(obj)로 둔다.
  3. argCountitems 안의 elements 수로 둔다.
  4. argCount > 0이면, 다음을 수행한다.
    1. length + argCount > 253 - 1이면, TypeError exception을 throw한다.
    2. klength로 둔다.
    3. Repeat, while k > 0,
      1. from을 ! ToString(𝔽(k - 1))로 둔다.
      2. to를 ! ToString(𝔽(k + argCount - 1))로 둔다.
      3. fromPresent를 ? HasProperty(obj, from)로 둔다.
      4. fromPresenttrue이면, 다음을 수행한다.
        1. fromValue를 ? Get(obj, from)로 둔다.
        2. Set(obj, to, fromValue, true)를 수행한다.
      5. Else,
        1. Assert: fromPresentfalse이다.
        2. DeletePropertyOrThrow(obj, to)를 수행한다.
      6. kk - 1로 설정한다.
    4. j+0𝔽로 둔다.
    5. items의 각 element item에 대해, 다음을 수행한다.
      1. Set(obj, ! ToString(j), item, true)를 수행한다.
      2. jj + 1𝔽로 설정한다.
  5. Set(obj, "length", 𝔽(length + argCount), true)를 수행한다.
  6. 𝔽(length + argCount)를 반환한다.

이 method의 "length" property는 1𝔽입니다.

Note

이 method는 intentionally generic입니다; its this value가 Array일 것을 require하지 않습니다. 따라서 method로 사용하기 위해 other kinds of objects에 transferred될 수 있습니다.

23.1.3.38 Array.prototype.values ( )

이 method는 called될 때 다음 steps를 수행합니다:

  1. obj를 ? ToObject(this value)로 둔다.
  2. CreateArrayIterator(obj, value)를 반환한다.

23.1.3.39 Array.prototype.with ( index, value )

이 method는 called될 때 다음 steps를 수행합니다:

  1. obj를 ? ToObject(this value)로 둔다.
  2. length를 ? LengthOfArrayLike(obj)로 둔다.
  3. relativeIndex를 ? ToIntegerOrInfinity(index)로 둔다.
  4. relativeIndex ≥ 0이면 actualIndexrelativeIndex로 둔다.
  5. Else, actualIndexlength + relativeIndex로 둔다.
  6. actualIndexlength 또는 actualIndex < 0이면, RangeError exception을 throw한다.
  7. array를 ? ArrayCreate(length)로 둔다.
  8. k를 0으로 둔다.
  9. Repeat, while k < length,
    1. propertyKey를 ! ToString(𝔽(k))로 둔다.
    2. k = actualIndex이면 fromValuevalue로 둔다.
    3. Else, fromValue를 ? Get(obj, propertyKey)로 둔다.
    4. CreateDataPropertyOrThrow(array, propertyKey, fromValue)를 수행한다.
    5. kk + 1로 설정한다.
  10. array를 반환한다.

23.1.3.40 Array.prototype [ %Symbol.iterator% ] ( )

%Symbol.iterator% property의 initial value는 23.1.3.38에 defined된 %Array.prototype.values%입니다.

23.1.3.41 Array.prototype [ %Symbol.unscopables% ]

%Symbol.unscopables% data property의 initial value는 다음 steps로 created된 object입니다:

  1. unscopableListOrdinaryObjectCreate(null)로 둔다.
  2. CreateDataPropertyOrThrow(unscopableList, "at", true)를 수행한다.
  3. CreateDataPropertyOrThrow(unscopableList, "copyWithin", true)를 수행한다.
  4. CreateDataPropertyOrThrow(unscopableList, "entries", true)를 수행한다.
  5. CreateDataPropertyOrThrow(unscopableList, "fill", true)를 수행한다.
  6. CreateDataPropertyOrThrow(unscopableList, "find", true)를 수행한다.
  7. CreateDataPropertyOrThrow(unscopableList, "findIndex", true)를 수행한다.
  8. CreateDataPropertyOrThrow(unscopableList, "findLast", true)를 수행한다.
  9. CreateDataPropertyOrThrow(unscopableList, "findLastIndex", true)를 수행한다.
  10. CreateDataPropertyOrThrow(unscopableList, "flat", true)를 수행한다.
  11. CreateDataPropertyOrThrow(unscopableList, "flatMap", true)를 수행한다.
  12. CreateDataPropertyOrThrow(unscopableList, "includes", true)를 수행한다.
  13. CreateDataPropertyOrThrow(unscopableList, "keys", true)를 수행한다.
  14. CreateDataPropertyOrThrow(unscopableList, "toReversed", true)를 수행한다.
  15. CreateDataPropertyOrThrow(unscopableList, "toSorted", true)를 수행한다.
  16. CreateDataPropertyOrThrow(unscopableList, "toSpliced", true)를 수행한다.
  17. CreateDataPropertyOrThrow(unscopableList, "values", true)를 수행한다.
  18. unscopableList를 반환한다.

이 property는 attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }를 가집니다.

Note

이 object의 own property names는 ECMAScript 2015 specification 이전에는 Array.prototype의 standard properties로 included되지 않았던 property names입니다. 이러한 names는 with statement binding purposes에서 ignored되어, outer scope의 binding으로 these names 중 하나를 사용하고, 그 binding이 binding object가 Array인 with statement에 의해 shadowed될 수 있는 existing code의 behaviour를 preserve합니다.

"with"unscopableList에 included되지 않는 reason은 그것이 이미 reserved word이기 때문입니다.

23.1.4 Properties of Array Instances

Array instances는 Array exotic objects이며 such objects에 대해 specified된 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인 every configurable own property의 name보다 always 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를 가집니다. However, non-configurable properties는 deleted될 수 없습니다. Array의 "length" property를 array의 existing non-configurable array-indexed property의 largest numeric own property name보다 numerically less than or equal인 value로 set하려고 attempt하면, length는 that non-configurable numeric own property name보다 one greater인 numeric value로 set됩니다. 10.4.2.1를 참조하십시오.

23.1.5 Array Iterator Objects

Array Iterator는 some specific Array instance object에 대한 specific iteration을 represent하는 object입니다. Array Iterator objects를 위한 named constructor는 없습니다. 대신, Array Iterator objects는 Array instance objects의 certain methods를 calling하여 created됩니다.

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. such iterators를 return하는 Array methods를 위한 iterator objects를 create하는 데 사용됩니다. It performs the following steps when called:

  1. iteratorOrdinaryObjectCreate(%ArrayIteratorPrototype%, « [[IteratedArrayLike]], [[ArrayLikeNextIndex]], [[ArrayLikeIterationKind]] »)로 둔다.
  2. iterator.[[IteratedArrayLike]]array로 설정한다.
  3. iterator.[[ArrayLikeNextIndex]]를 0으로 설정한다.
  4. iterator.[[ArrayLikeIterationKind]]kind로 설정한다.
  5. iterator를 반환한다.

23.1.5.2 The %ArrayIteratorPrototype% Object

%ArrayIteratorPrototype% object는:

23.1.5.2.1 %ArrayIteratorPrototype%.next ( )

  1. iteratorObjthis value로 둔다.
  2. iteratorObj가 Object가 아니면, TypeError exception을 throw한다.
  3. iteratorObjArray Iterator Instance의 all internal slots(23.1.5.3)를 가지지 않으면, TypeError exception을 throw한다.
  4. arrayiteratorObj.[[IteratedArrayLike]]로 둔다.
  5. arrayundefined이면, CreateIteratorResultObject(undefined, true)를 반환한다.
  6. indexiteratorObj.[[ArrayLikeNextIndex]]로 둔다.
  7. kinditeratorObj.[[ArrayLikeIterationKind]]로 둔다.
  8. array[[TypedArrayName]] internal slot을 가지면, 다음을 수행한다.
    1. taRecordMakeTypedArrayWithBufferWitnessRecord(array, seq-cst)로 둔다.
    2. IsTypedArrayOutOfBounds(taRecord)가 true이면, TypeError exception을 throw한다.
    3. lengthTypedArrayLength(taRecord)로 둔다.
  9. Else,
    1. length를 ? LengthOfArrayLike(array)로 둔다.
  10. indexlength이면, 다음을 수행한다.
    1. iteratorObj.[[IteratedArrayLike]]undefined로 설정한다.
    2. CreateIteratorResultObject(undefined, true)를 반환한다.
  11. iteratorObj.[[ArrayLikeNextIndex]]index + 1로 설정한다.
  12. indexNumber𝔽(index)로 둔다.
  13. kindkey이면, 다음을 수행한다.
    1. resultindexNumber로 둔다.
  14. Else,
    1. elementKey를 ! ToString(indexNumber)로 둔다.
    2. elementValue를 ? Get(array, elementKey)로 둔다.
    3. kindvalue이면, 다음을 수행한다.
      1. resultelementValue로 둔다.
    4. Else,
      1. Assert: kindkey+value이다.
      2. resultCreateArrayFromListindexNumber, elementValue »)로 둔다.
  15. CreateIteratorResultObject(result, false)를 반환한다.

23.1.5.2.2 %ArrayIteratorPrototype% [ %Symbol.toStringTag% ]

%Symbol.toStringTag% property의 initial value는 String value "Array Iterator"입니다.

이 property는 attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }를 가집니다.

23.1.5.3 Properties of Array Iterator Instances

Array Iterator instances는 %ArrayIteratorPrototype% intrinsic object로부터 properties를 inherit하는 ordinary objects입니다. Array Iterator instances는 Table 70에 listed된 internal slots로 initially created됩니다.

Table 70: Internal Slots of Array Iterator Instances
Internal Slot Type Description
[[IteratedArrayLike]] an Object or undefined iterated되고 있는 array-like object입니다.
[[ArrayLikeNextIndex]] a non-negative integer iterator가 examine할 next element의 integer index입니다.
[[ArrayLikeIterationKind]] key+value, key, or value iteration의 each element에 대해 return되는 것이 무엇인지 identify하는 value입니다.

23.2 TypedArray Objects

TypedArray는 underlying binary data buffer(25.1)의 array-like view를 제공합니다. TypedArray element typeTypedArray instance의 all elements가 가지는 underlying binary scalar data type입니다. supported element types 각각에 대해 Table 71에 listed된 distinct TypedArray constructor가 있습니다. Table 71의 each 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으로 replaced되어야 합니다.

23.2.1 The %TypedArray% Intrinsic Object

%TypedArray% intrinsic object는:

  • all TypedArray constructor objects가 inherit하는 constructor function object입니다.
  • its corresponding prototype object와 함께, all TypedArray constructors 및 their instances가 inherit하는 common properties를 제공합니다.
  • global name을 가지지 않으며 global object의 property로 appear하지 않습니다.
  • various TypedArray constructors의 abstract superclass처럼 acts합니다.
  • abstract class constructor이므로 invoked될 때 error를 throw합니다. TypedArray constructors는 이에 대한 super call을 수행하지 않습니다.

23.2.1.1 %TypedArray% ( )

이 function은 called될 때 다음 steps를 수행합니다:

  1. TypeError exception을 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는 called될 때 다음 steps를 수행합니다:

  1. ctorthis value로 둔다.
  2. IsConstructor(ctor)가 false이면, TypeError exception을 throw한다.
  3. mapperundefined이면, 다음을 수행한다.
    1. mappingfalse로 둔다.
  4. Else,
    1. IsCallable(mapper)가 false이면, TypeError exception을 throw한다.
    2. mappingtrue로 둔다.
  5. usingIterator를 ? GetMethod(source, %Symbol.iterator%)로 둔다.
  6. usingIteratorundefined가 아니면, 다음을 수행한다.
    1. values를 ? IteratorToList(? GetIteratorFromMethod(source, usingIterator))로 둔다.
    2. lengthvalues 안의 elements 수로 둔다.
    3. targetObj를 ? TypedArrayCreateFromConstructor(ctor, « 𝔽(length) »)로 둔다.
    4. k를 0으로 둔다.
    5. Repeat, while k < length,
      1. propertyKey를 ! ToString(𝔽(k))로 둔다.
      2. kValuevalues의 first element로 둔다.
      3. values에서 first element를 remove한다.
      4. mappingtrue이면, 다음을 수행한다.
        1. mappedValue를 ? Call(mapper, thisArg, « kValue, 𝔽(k) »)로 둔다.
      5. Else,
        1. mappedValuekValue로 둔다.
      6. Set(targetObj, propertyKey, mappedValue, true)를 수행한다.
      7. kk + 1로 설정한다.
    6. Assert: values는 now empty List이다.
    7. targetObj를 반환한다.
  7. NOTE: sourceiterable object가 아니므로, already array-like object라고 assume한다.
  8. arrayLike를 ! ToObject(source)로 둔다.
  9. length를 ? LengthOfArrayLike(arrayLike)로 둔다.
  10. targetObj를 ? TypedArrayCreateFromConstructor(ctor, « 𝔽(length) »)로 둔다.
  11. k를 0으로 둔다.
  12. Repeat, while k < length,
    1. propertyKey를 ! ToString(𝔽(k))로 둔다.
    2. kValue를 ? Get(arrayLike, propertyKey)로 둔다.
    3. mappingtrue이면, 다음을 수행한다.
      1. mappedValue를 ? Call(mapper, thisArg, « kValue, 𝔽(k) »)로 둔다.
    4. Else,
      1. mappedValuekValue로 둔다.
    5. Set(targetObj, propertyKey, mappedValue, true)를 수행한다.
    6. kk + 1로 설정한다.
  13. targetObj를 반환한다.

23.2.2.2 %TypedArray%.of ( ...items )

이 method는 called될 때 다음 steps를 수행합니다:

  1. lengthitems 안의 elements 수로 둔다.
  2. ctorthis value로 둔다.
  3. IsConstructor(ctor)가 false이면, TypeError exception을 throw한다.
  4. newObj를 ? TypedArrayCreateFromConstructor(ctor, « 𝔽(length) »)로 둔다.
  5. k를 0으로 둔다.
  6. Repeat, while k < length,
    1. kValueitems[k]로 둔다.
    2. propertyKey를 ! ToString(𝔽(k))로 둔다.
    3. Set(newObj, propertyKey, kValue, true)를 수행한다.
    4. kk + 1로 설정한다.
  7. newObj를 반환한다.

23.2.2.3 %TypedArray%.prototype

%TypedArray%.prototype의 initial value는 %TypedArray% prototype object입니다.

이 property는 attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }를 가집니다.

23.2.2.4 get %TypedArray% [ %Symbol.species% ]

%TypedArray%[%Symbol.species%]는 set accessor function이 undefinedaccessor property입니다. Its get accessor function은 called될 때 다음 steps를 수행합니다:

  1. this value를 반환한다.

이 function의 "name" property의 value는 "get [Symbol.species]"입니다.

Note

%TypedArray.prototype% methods는 normally their this value의 constructor를 사용하여 derived object를 create합니다. However, subclass constructor는 its %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한 any other internal slots를 가지지 않습니다.

23.2.3.1 %TypedArray%.prototype.at ( index )

  1. objthis value로 둔다.
  2. taRecord를 ? ValidateTypedArray(obj, seq-cst)로 둔다.
  3. lengthTypedArrayLength(taRecord)로 둔다.
  4. relativeIndex를 ? ToIntegerOrInfinity(index)로 둔다.
  5. relativeIndex ≥ 0이면, 다음을 수행한다.
    1. krelativeIndex로 둔다.
  6. Else,
    1. klength + relativeIndex로 둔다.
  7. k < 0 또는 klength이면, undefined를 반환한다.
  8. Get(obj, ! ToString(𝔽(k)))를 반환한다.

23.2.3.2 get %TypedArray%.prototype.buffer

%TypedArray%.prototype.buffer는 set accessor function이 undefinedaccessor property입니다. Its get accessor function은 called될 때 다음 steps를 수행합니다:

  1. objthis value로 둔다.
  2. RequireInternalSlot(obj, [[TypedArrayName]])를 수행한다.
  3. Assert: obj[[ViewedArrayBuffer]] internal slot을 가진다.
  4. bufferobj.[[ViewedArrayBuffer]]로 둔다.
  5. buffer를 반환한다.

23.2.3.3 get %TypedArray%.prototype.byteLength

%TypedArray%.prototype.byteLength는 set accessor function이 undefinedaccessor property입니다. Its get accessor function은 called될 때 다음 steps를 수행합니다:

  1. objthis value로 둔다.
  2. RequireInternalSlot(obj, [[TypedArrayName]])를 수행한다.
  3. Assert: obj[[ViewedArrayBuffer]] internal slot을 가진다.
  4. taRecordMakeTypedArrayWithBufferWitnessRecord(obj, seq-cst)로 둔다.
  5. IsTypedArrayOutOfBounds(taRecord)가 true이면, +0𝔽를 반환한다.
  6. sizeTypedArrayByteLength(taRecord)로 둔다.
  7. 𝔽(size)를 반환한다.

23.2.3.4 get %TypedArray%.prototype.byteOffset

%TypedArray%.prototype.byteOffset는 set accessor function이 undefinedaccessor property입니다. Its get accessor function은 called될 때 다음 steps를 수행합니다:

  1. objthis value로 둔다.
  2. RequireInternalSlot(obj, [[TypedArrayName]])를 수행한다.
  3. Assert: obj[[ViewedArrayBuffer]] internal slot을 가진다.
  4. taRecordMakeTypedArrayWithBufferWitnessRecord(obj, seq-cst)로 둔다.
  5. IsTypedArrayOutOfBounds(taRecord)가 true이면, +0𝔽를 반환한다.
  6. offsetobj.[[ByteOffset]]으로 둔다.
  7. 𝔽(offset)을 반환한다.

23.2.3.5 %TypedArray%.prototype.constructor

%TypedArray%.prototype.constructor의 initial value는 %TypedArray%입니다.

23.2.3.6 %TypedArray%.prototype.copyWithin ( target, start [ , end ] )

이 method의 arguments에 대한 interpretation 및 use는 23.1.3.4에 defined된 Array.prototype.copyWithin의 경우와 같습니다.

이 method는 called될 때 다음 steps를 수행합니다:

  1. objthis value로 둔다.
  2. taRecord를 ? ValidateTypedArray(obj, seq-cst)로 둔다.
  3. lengthTypedArrayLength(taRecord)로 둔다.
  4. relativeTarget을 ? ToIntegerOrInfinity(target)로 둔다.
  5. relativeTarget = -∞이면, targetIndex를 0으로 둔다.
  6. Else if relativeTarget < 0이면, targetIndexmax(length + relativeTarget, 0)으로 둔다.
  7. Else, targetIndexmin(relativeTarget, length)로 둔다.
  8. relativeStart를 ? ToIntegerOrInfinity(start)로 둔다.
  9. relativeStart = -∞이면, startIndex를 0으로 둔다.
  10. Else if relativeStart < 0이면, startIndexmax(length + relativeStart, 0)으로 둔다.
  11. Else, startIndexmin(relativeStart, length)로 둔다.
  12. endundefined이면 relativeEndlength로 둔다; else relativeEnd를 ? ToIntegerOrInfinity(end)로 둔다.
  13. relativeEnd = -∞이면, endIndex를 0으로 둔다.
  14. Else if relativeEnd < 0이면, endIndexmax(length + relativeEnd, 0)으로 둔다.
  15. Else, endIndexmin(relativeEnd, length)로 둔다.
  16. countmin(endIndex - startIndex, length - targetIndex)로 둔다.
  17. count > 0이면, 다음을 수행한다.
    1. NOTE: copying은 source data의 bit-level encoding을 preserve하는 manner로 performed되어야 한다.
    2. bufferobj.[[ViewedArrayBuffer]]로 둔다.
    3. taRecordMakeTypedArrayWithBufferWitnessRecord(obj, seq-cst)로 설정한다.
    4. IsTypedArrayOutOfBounds(taRecord)가 true이면, TypeError exception을 throw한다.
    5. lengthTypedArrayLength(taRecord)로 설정한다.
    6. NOTE: above steps의 side-effects가 obj의 size를 reduced했을 수 있으며, 이 경우 copying은 still-applicable longest prefix로 proceed해야 한다.
    7. countmin(count, length - startIndex, length - targetIndex)로 설정한다.
    8. elementSizeTypedArrayElementSize(obj)로 둔다.
    9. byteOffsetobj.[[ByteOffset]]으로 둔다.
    10. toByteIndex를 (targetIndex × elementSize) + byteOffset으로 둔다.
    11. fromByteIndex를 (startIndex × elementSize) + byteOffset으로 둔다.
    12. countBytescount × elementSize로 둔다.
    13. fromByteIndex < toByteIndex이고 toByteIndex < fromByteIndex + countBytes이면, 다음을 수행한다.
      1. direction을 -1로 둔다.
      2. fromByteIndexfromByteIndex + countBytes - 1로 설정한다.
      3. toByteIndextoByteIndex + countBytes - 1로 설정한다.
    14. Else,
      1. direction을 1로 둔다.
    15. Repeat, while countBytes > 0,
      1. valueGetValueFromBuffer(buffer, fromByteIndex, uint8, true, unordered)로 둔다.
      2. SetValueInBuffer(buffer, toByteIndex, uint8, value, true, unordered)를 수행한다.
      3. fromByteIndexfromByteIndex + direction으로 설정한다.
      4. toByteIndextoByteIndex + direction으로 설정한다.
      5. countBytescountBytes - 1로 설정한다.
  18. obj를 반환한다.

23.2.3.7 %TypedArray%.prototype.entries ( )

이 method는 called될 때 다음 steps를 수행합니다:

  1. objthis value로 둔다.
  2. ValidateTypedArray(obj, seq-cst)를 수행한다.
  3. CreateArrayIterator(obj, key+value)를 반환한다.

23.2.3.8 %TypedArray%.prototype.every ( callback [ , thisArg ] )

이 method의 arguments에 대한 interpretation 및 use는 23.1.3.6에 defined된 Array.prototype.every의 경우와 같습니다.

이 method는 called될 때 다음 steps를 수행합니다:

  1. objthis value로 둔다.
  2. taRecord를 ? ValidateTypedArray(obj, seq-cst)로 둔다.
  3. lengthTypedArrayLength(taRecord)로 둔다.
  4. IsCallable(callback)가 false이면, TypeError exception을 throw한다.
  5. k를 0으로 둔다.
  6. Repeat, while k < length,
    1. propertyKey를 ! ToString(𝔽(k))로 둔다.
    2. kValue를 ! Get(obj, propertyKey)로 둔다.
    3. testResultToBoolean(? Call(callback, thisArg, « kValue, 𝔽(k), obj »))로 둔다.
    4. testResultfalse이면, false를 반환한다.
    5. kk + 1로 설정한다.
  7. true를 반환한다.

이 method는 generic하지 않습니다. this value는 [[TypedArrayName]] internal slot을 가진 object여야 합니다.

23.2.3.9 %TypedArray%.prototype.fill ( value [ , start [ , end ] ] )

이 method의 arguments에 대한 interpretation 및 use는 23.1.3.7에 defined된 Array.prototype.fill의 경우와 같습니다.

이 method는 called될 때 다음 steps를 수행합니다:

  1. objthis value로 둔다.
  2. taRecord를 ? ValidateTypedArray(obj, seq-cst)로 둔다.
  3. lengthTypedArrayLength(taRecord)로 둔다.
  4. obj.[[ContentType]]bigint이면, value를 ? ToBigInt(value)로 설정한다.
  5. Else, value를 ? ToNumber(value)로 설정한다.
  6. relativeStart를 ? ToIntegerOrInfinity(start)로 둔다.
  7. relativeStart = -∞이면, startIndex를 0으로 둔다.
  8. Else if relativeStart < 0이면, startIndexmax(length + relativeStart, 0)으로 둔다.
  9. Else, startIndexmin(relativeStart, length)로 둔다.
  10. endundefined이면 relativeEndlength로 둔다; else relativeEnd를 ? ToIntegerOrInfinity(end)로 둔다.
  11. relativeEnd = -∞이면, endIndex를 0으로 둔다.
  12. Else if relativeEnd < 0이면, endIndexmax(length + relativeEnd, 0)으로 둔다.
  13. Else, endIndexmin(relativeEnd, length)로 둔다.
  14. taRecordMakeTypedArrayWithBufferWitnessRecord(obj, seq-cst)로 설정한다.
  15. IsTypedArrayOutOfBounds(taRecord)가 true이면, TypeError exception을 throw한다.
  16. lengthTypedArrayLength(taRecord)로 설정한다.
  17. endIndexmin(endIndex, length)로 설정한다.
  18. kstartIndex로 둔다.
  19. Repeat, while k < endIndex,
    1. propertyKey를 ! ToString(𝔽(k))로 둔다.
    2. Set(obj, propertyKey, value, true)를 수행한다.
    3. kk + 1로 설정한다.
  20. obj를 반환한다.

23.2.3.10 %TypedArray%.prototype.filter ( callback [ , thisArg ] )

이 method의 arguments에 대한 interpretation 및 use는 23.1.3.8에 defined된 Array.prototype.filter의 경우와 같습니다.

이 method는 called될 때 다음 steps를 수행합니다:

  1. objthis value로 둔다.
  2. taRecord를 ? ValidateTypedArray(obj, seq-cst)로 둔다.
  3. lengthTypedArrayLength(taRecord)로 둔다.
  4. IsCallable(callback)가 false이면, TypeError exception을 throw한다.
  5. kept를 새 empty List로 둔다.
  6. captured를 0으로 둔다.
  7. k를 0으로 둔다.
  8. Repeat, while k < length,
    1. propertyKey를 ! ToString(𝔽(k))로 둔다.
    2. kValue를 ! Get(obj, propertyKey)로 둔다.
    3. selectedToBoolean(? Call(callback, thisArg, « kValue, 𝔽(k), obj »))로 둔다.
    4. selectedtrue이면, 다음을 수행한다.
      1. kValuekept에 append한다.
      2. capturedcaptured + 1로 설정한다.
    5. kk + 1로 설정한다.
  9. result를 ? TypedArraySpeciesCreate(obj, « 𝔽(captured) »)로 둔다.
  10. n을 0으로 둔다.
  11. kept의 각 element element에 대해, 다음을 수행한다.
    1. Set(result, ! ToString(𝔽(n)), element, true)를 수행한다.
    2. nn + 1로 설정한다.
  12. result를 반환한다.

이 method는 generic하지 않습니다. this value는 [[TypedArrayName]] internal slot을 가진 object여야 합니다.

23.2.3.11 %TypedArray%.prototype.find ( predicate [ , thisArg ] )

이 method의 arguments에 대한 interpretation 및 use는 23.1.3.9에 defined된 Array.prototype.find의 경우와 같습니다.

이 method는 called될 때 다음 steps를 수행합니다:

  1. objthis value로 둔다.
  2. taRecord를 ? ValidateTypedArray(obj, seq-cst)로 둔다.
  3. lengthTypedArrayLength(taRecord)로 둔다.
  4. findRecord를 ? FindViaPredicate(obj, length, ascending, predicate, thisArg)로 둔다.
  5. findRecord.[[Value]]를 반환한다.

이 method는 generic하지 않습니다. this value는 [[TypedArrayName]] internal slot을 가진 object여야 합니다.

23.2.3.12 %TypedArray%.prototype.findIndex ( predicate [ , thisArg ] )

이 method의 arguments에 대한 interpretation 및 use는 23.1.3.10에 defined된 Array.prototype.findIndex의 경우와 같습니다.

이 method는 called될 때 다음 steps를 수행합니다:

  1. objthis value로 둔다.
  2. taRecord를 ? ValidateTypedArray(obj, seq-cst)로 둔다.
  3. lengthTypedArrayLength(taRecord)로 둔다.
  4. findRecord를 ? FindViaPredicate(obj, length, ascending, predicate, thisArg)로 둔다.
  5. findRecord.[[Index]]를 반환한다.

이 method는 generic하지 않습니다. this value는 [[TypedArrayName]] internal slot을 가진 object여야 합니다.

23.2.3.13 %TypedArray%.prototype.findLast ( predicate [ , thisArg ] )

이 method의 arguments에 대한 interpretation 및 use는 23.1.3.11에 defined된 Array.prototype.findLast의 경우와 같습니다.

이 method는 called될 때 다음 steps를 수행합니다:

  1. objthis value로 둔다.
  2. taRecord를 ? ValidateTypedArray(obj, seq-cst)로 둔다.
  3. lengthTypedArrayLength(taRecord)로 둔다.
  4. findRecord를 ? FindViaPredicate(obj, length, descending, predicate, thisArg)로 둔다.
  5. findRecord.[[Value]]를 반환한다.

이 method는 generic하지 않습니다. this value는 [[TypedArrayName]] internal slot을 가진 object여야 합니다.

23.2.3.14 %TypedArray%.prototype.findLastIndex ( predicate [ , thisArg ] )

이 method의 arguments에 대한 interpretation 및 use는 23.1.3.12에 defined된 Array.prototype.findLastIndex의 경우와 같습니다.

이 method는 called될 때 다음 steps를 수행합니다:

  1. objthis value로 둔다.
  2. taRecord를 ? ValidateTypedArray(obj, seq-cst)로 둔다.
  3. lengthTypedArrayLength(taRecord)로 둔다.
  4. findRecord를 ? FindViaPredicate(obj, length, descending, predicate, thisArg)로 둔다.
  5. findRecord.[[Index]]를 반환한다.

이 method는 generic하지 않습니다. this value는 [[TypedArrayName]] internal slot을 가진 object여야 합니다.

23.2.3.15 %TypedArray%.prototype.forEach ( callback [ , thisArg ] )

이 method의 arguments에 대한 interpretation 및 use는 23.1.3.15에 defined된 Array.prototype.forEach의 경우와 같습니다.

이 method는 called될 때 다음 steps를 수행합니다:

  1. objthis value로 둔다.
  2. taRecord를 ? ValidateTypedArray(obj, seq-cst)로 둔다.
  3. lengthTypedArrayLength(taRecord)로 둔다.
  4. IsCallable(callback)가 false이면, TypeError exception을 throw한다.
  5. k를 0으로 둔다.
  6. Repeat, while k < length,
    1. propertyKey를 ! ToString(𝔽(k))로 둔다.
    2. kValue를 ! Get(obj, propertyKey)로 둔다.
    3. Call(callback, thisArg, « kValue, 𝔽(k), obj »)를 수행한다.
    4. kk + 1로 설정한다.
  7. undefined를 반환한다.

이 method는 generic하지 않습니다. this value는 [[TypedArrayName]] internal slot을 가진 object여야 합니다.

23.2.3.16 %TypedArray%.prototype.includes ( searchElement [ , fromIndex ] )

이 method의 arguments에 대한 interpretation 및 use는 23.1.3.16에 defined된 Array.prototype.includes의 경우와 같습니다.

이 method는 called될 때 다음 steps를 수행합니다:

  1. objthis value로 둔다.
  2. taRecord를 ? ValidateTypedArray(obj, seq-cst)로 둔다.
  3. lengthTypedArrayLength(taRecord)로 둔다.
  4. length = 0이면, false를 반환한다.
  5. n을 ? ToIntegerOrInfinity(fromIndex)로 둔다.
  6. Assert: fromIndexundefined이면, n은 0이다.
  7. n = +∞이면, false를 반환한다.
  8. n = -∞이면, n을 0으로 설정한다.
  9. n ≥ 0이면, 다음을 수행한다.
    1. kn으로 둔다.
  10. Else,
    1. klength + n으로 둔다.
    2. k < 0이면, k를 0으로 설정한다.
  11. Repeat, while k < length,
    1. elementK를 ! Get(obj, ! ToString(𝔽(k)))로 둔다.
    2. SameValueZero(searchElement, elementK)가 true이면, true를 반환한다.
    3. kk + 1로 설정한다.
  12. false를 반환한다.

이 method는 generic하지 않습니다. this value는 [[TypedArrayName]] internal slot을 가진 object여야 합니다.

23.2.3.17 %TypedArray%.prototype.indexOf ( searchElement [ , fromIndex ] )

이 method의 arguments에 대한 interpretation 및 use는 23.1.3.17에 defined된 Array.prototype.indexOf의 경우와 같습니다.

이 method는 called될 때 다음 steps를 수행합니다:

  1. objthis value로 둔다.
  2. taRecord를 ? ValidateTypedArray(obj, seq-cst)로 둔다.
  3. lengthTypedArrayLength(taRecord)로 둔다.
  4. length = 0이면, -1𝔽를 반환한다.
  5. n을 ? ToIntegerOrInfinity(fromIndex)로 둔다.
  6. Assert: fromIndexundefined이면, n은 0이다.
  7. n = +∞이면, -1𝔽를 반환한다.
  8. n = -∞이면, n을 0으로 설정한다.
  9. n ≥ 0이면, 다음을 수행한다.
    1. kn으로 둔다.
  10. Else,
    1. klength + n으로 둔다.
    2. k < 0이면, k를 0으로 설정한다.
  11. Repeat, while k < length,
    1. propertyKey를 ! ToString(𝔽(k))로 둔다.
    2. kPresent를 ! HasProperty(obj, propertyKey)로 둔다.
    3. kPresenttrue이면, 다음을 수행한다.
      1. elementK를 ! Get(obj, propertyKey)로 둔다.
      2. IsStrictlyEqual(searchElement, elementK)가 true이면, 𝔽(k)를 반환한다.
    4. kk + 1로 설정한다.
  12. -1𝔽를 반환한다.

이 method는 generic하지 않습니다. this value는 [[TypedArrayName]] internal slot을 가진 object여야 합니다.

23.2.3.18 %TypedArray%.prototype.join ( separator )

이 method의 arguments에 대한 interpretation 및 use는 23.1.3.18에 defined된 Array.prototype.join의 경우와 같습니다.

이 method는 called될 때 다음 steps를 수행합니다:

  1. objthis value로 둔다.
  2. taRecord를 ? ValidateTypedArray(obj, seq-cst)로 둔다.
  3. lengthTypedArrayLength(taRecord)로 둔다.
  4. separatorundefined이면, sep","로 둔다.
  5. Else, sep를 ? ToString(separator)로 둔다.
  6. result를 empty String으로 둔다.
  7. k를 0으로 둔다.
  8. Repeat, while k < length,
    1. k > 0이면, resultresultsepstring-concatenation으로 설정한다.
    2. element를 ! Get(obj, ! ToString(𝔽(k)))로 둔다.
    3. elementundefined가 아니면, 다음을 수행한다.
      1. elementString을 ! ToString(element)로 둔다.
      2. resultresultelementStringstring-concatenation으로 설정한다.
    4. kk + 1로 설정한다.
  9. result를 반환한다.

이 method는 generic하지 않습니다. this value는 [[TypedArrayName]] internal slot을 가진 object여야 합니다.

23.2.3.19 %TypedArray%.prototype.keys ( )

이 method는 called될 때 다음 steps를 수행합니다:

  1. objthis value로 둔다.
  2. ValidateTypedArray(obj, seq-cst)를 수행한다.
  3. CreateArrayIterator(obj, key)를 반환한다.

23.2.3.20 %TypedArray%.prototype.lastIndexOf ( searchElement [ , fromIndex ] )

이 method의 arguments에 대한 interpretation 및 use는 23.1.3.20에 defined된 Array.prototype.lastIndexOf의 경우와 같습니다.

이 method는 called될 때 다음 steps를 수행합니다:

  1. objthis value로 둔다.
  2. taRecord를 ? ValidateTypedArray(obj, seq-cst)로 둔다.
  3. lengthTypedArrayLength(taRecord)로 둔다.
  4. length = 0이면, -1𝔽를 반환한다.
  5. fromIndex가 present이면 n을 ? ToIntegerOrInfinity(fromIndex)로 둔다; else nlength - 1로 둔다.
  6. n = -∞이면, -1𝔽를 반환한다.
  7. n ≥ 0이면, 다음을 수행한다.
    1. kmin(n, length - 1)로 둔다.
  8. Else,
    1. klength + n으로 둔다.
  9. Repeat, while k ≥ 0,
    1. propertyKey를 ! ToString(𝔽(k))로 둔다.
    2. kPresent를 ! HasProperty(obj, propertyKey)로 둔다.
    3. kPresenttrue이면, 다음을 수행한다.
      1. elementK를 ! Get(obj, propertyKey)로 둔다.
      2. IsStrictlyEqual(searchElement, elementK)가 true이면, 𝔽(k)를 반환한다.
    4. kk - 1로 설정한다.
  10. -1𝔽를 반환한다.

이 method는 generic하지 않습니다. this value는 [[TypedArrayName]] internal slot을 가진 object여야 합니다.

23.2.3.21 get %TypedArray%.prototype.length

%TypedArray%.prototype.length는 set accessor function이 undefinedaccessor property입니다. Its get accessor function은 called될 때 다음 steps를 수행합니다:

  1. objthis value로 둔다.
  2. RequireInternalSlot(obj, [[TypedArrayName]])를 수행한다.
  3. Assert: obj[[ViewedArrayBuffer]][[ArrayLength]] internal slots를 가진다.
  4. taRecordMakeTypedArrayWithBufferWitnessRecord(obj, seq-cst)로 둔다.
  5. IsTypedArrayOutOfBounds(taRecord)가 true이면, +0𝔽를 반환한다.
  6. lengthTypedArrayLength(taRecord)로 둔다.
  7. 𝔽(length)를 반환한다.

이 function은 generic하지 않습니다. this value는 [[TypedArrayName]] internal slot을 가진 object여야 합니다.

23.2.3.22 %TypedArray%.prototype.map ( callback [ , thisArg ] )

이 method의 arguments에 대한 interpretation 및 use는 23.1.3.21에 defined된 Array.prototype.map의 경우와 같습니다.

이 method는 called될 때 다음 steps를 수행합니다:

  1. objthis value로 둔다.
  2. taRecord를 ? ValidateTypedArray(obj, seq-cst)로 둔다.
  3. lengthTypedArrayLength(taRecord)로 둔다.
  4. IsCallable(callback)가 false이면, TypeError exception을 throw한다.
  5. result를 ? TypedArraySpeciesCreate(obj, « 𝔽(length) »)로 둔다.
  6. k를 0으로 둔다.
  7. Repeat, while k < length,
    1. propertyKey를 ! ToString(𝔽(k))로 둔다.
    2. kValue를 ! Get(obj, propertyKey)로 둔다.
    3. mappedValue를 ? Call(callback, thisArg, « kValue, 𝔽(k), obj »)로 둔다.
    4. Set(result, propertyKey, mappedValue, true)를 수행한다.
    5. kk + 1로 설정한다.
  8. result를 반환한다.

이 method는 generic하지 않습니다. this value는 [[TypedArrayName]] internal slot을 가진 object여야 합니다.

23.2.3.23 %TypedArray%.prototype.reduce ( callback [ , initialValue ] )

이 method의 arguments에 대한 interpretation 및 use는 23.1.3.24에 defined된 Array.prototype.reduce의 경우와 같습니다.

이 method는 called될 때 다음 steps를 수행합니다:

  1. objthis value로 둔다.
  2. taRecord를 ? ValidateTypedArray(obj, seq-cst)로 둔다.
  3. lengthTypedArrayLength(taRecord)로 둔다.
  4. IsCallable(callback)가 false이면, TypeError exception을 throw한다.
  5. length = 0이고 initialValue가 present하지 않으면, TypeError exception을 throw한다.
  6. k를 0으로 둔다.
  7. accumulatorundefined로 둔다.
  8. initialValue가 present이면, 다음을 수행한다.
    1. accumulatorinitialValue로 설정한다.
  9. Else,
    1. propertyKey를 ! ToString(𝔽(k))로 둔다.
    2. accumulator를 ! Get(obj, propertyKey)로 설정한다.
    3. kk + 1로 설정한다.
  10. Repeat, while k < length,
    1. propertyKey를 ! ToString(𝔽(k))로 둔다.
    2. kValue를 ! Get(obj, propertyKey)로 둔다.
    3. accumulator를 ? Call(callback, undefined, « accumulator, kValue, 𝔽(k), obj »)로 설정한다.
    4. kk + 1로 설정한다.
  11. accumulator를 반환한다.

이 method는 generic하지 않습니다. this value는 [[TypedArrayName]] internal slot을 가진 object여야 합니다.

23.2.3.24 %TypedArray%.prototype.reduceRight ( callback [ , initialValue ] )

이 method의 arguments에 대한 interpretation 및 use는 23.1.3.25에 defined된 Array.prototype.reduceRight의 경우와 같습니다.

이 method는 called될 때 다음 steps를 수행합니다:

  1. objthis value로 둔다.
  2. taRecord를 ? ValidateTypedArray(obj, seq-cst)로 둔다.
  3. lengthTypedArrayLength(taRecord)로 둔다.
  4. IsCallable(callback)가 false이면, TypeError exception을 throw한다.
  5. length = 0이고 initialValue가 present하지 않으면, TypeError exception을 throw한다.
  6. klength - 1로 둔다.
  7. accumulatorundefined로 둔다.
  8. initialValue가 present이면, 다음을 수행한다.
    1. accumulatorinitialValue로 설정한다.
  9. Else,
    1. propertyKey를 ! ToString(𝔽(k))로 둔다.
    2. accumulator를 ! Get(obj, propertyKey)로 설정한다.
    3. kk - 1로 설정한다.
  10. Repeat, while k ≥ 0,
    1. propertyKey를 ! ToString(𝔽(k))로 둔다.
    2. kValue를 ! Get(obj, propertyKey)로 둔다.
    3. accumulator를 ? Call(callback, undefined, « accumulator, kValue, 𝔽(k), obj »)로 설정한다.
    4. kk - 1로 설정한다.
  11. accumulator를 반환한다.

이 method는 generic하지 않습니다. this value는 [[TypedArrayName]] internal slot을 가진 object여야 합니다.

23.2.3.25 %TypedArray%.prototype.reverse ( )

이 method의 arguments에 대한 interpretation 및 use는 23.1.3.26에 defined된 Array.prototype.reverse의 경우와 같습니다.

이 method는 called될 때 다음 steps를 수행합니다:

  1. objthis value로 둔다.
  2. taRecord를 ? ValidateTypedArray(obj, seq-cst)로 둔다.
  3. lengthTypedArrayLength(taRecord)로 둔다.
  4. middlefloor(length / 2)로 둔다.
  5. lower를 0으로 둔다.
  6. Repeat, while lowermiddle,
    1. upperlength - lower - 1로 둔다.
    2. upperP를 ! ToString(𝔽(upper))로 둔다.
    3. lowerP를 ! ToString(𝔽(lower))로 둔다.
    4. lowerValue를 ! Get(obj, lowerP)로 둔다.
    5. upperValue를 ! Get(obj, upperP)로 둔다.
    6. Set(obj, lowerP, upperValue, true)를 수행한다.
    7. Set(obj, upperP, lowerValue, true)를 수행한다.
    8. lowerlower + 1로 설정한다.
  7. obj를 반환한다.

이 method는 generic하지 않습니다. this value는 [[TypedArrayName]] internal slot을 가진 object여야 합니다.

23.2.3.26 %TypedArray%.prototype.set ( source [ , offset ] )

이 method는 source에서 values를 reading하여 이 TypedArray 안에 multiple values를 sets합니다. details는 source의 type에 따라 differ합니다. optional offset value는 values가 written되는 이 TypedArray 안의 first element index를 indicates합니다. omitted되면, 0으로 assumed됩니다.

called될 때 다음 steps를 수행합니다:

  1. targetthis value로 둔다.
  2. RequireInternalSlot(target, [[TypedArrayName]])를 수행한다.
  3. Assert: target[[ViewedArrayBuffer]] internal slot을 가진다.
  4. targetOffset을 ? ToIntegerOrInfinity(offset)으로 둔다.
  5. targetOffset < 0이면, RangeError exception을 throw한다.
  6. source[[TypedArrayName]] internal slot을 가진 Object이면, 다음을 수행한다.
    1. SetTypedArrayFromTypedArray(target, targetOffset, source)를 수행한다.
  7. Else,
    1. SetTypedArrayFromArrayLike(target, targetOffset, source)를 수행한다.
  8. undefined를 반환한다.

이 method는 generic하지 않습니다. this value는 [[TypedArrayName]] internal slot을 가진 object여야 합니다.

23.2.3.26.1 SetTypedArrayFromArrayLike ( target, targetOffset, source )

The abstract operation SetTypedArrayFromArrayLike takes arguments target (a TypedArray), targetOffset (a non-negative integer or +∞), and source (an ECMAScript language value, but not a TypedArray) and returns either a normal completion containing unused or a throw completion. source에서 values를 reading하여, index targetOffset에서 starting하여 target 안에 multiple values를 sets합니다. It performs the following steps when called:

  1. targetRecordMakeTypedArrayWithBufferWitnessRecord(target, seq-cst)로 둔다.
  2. IsTypedArrayOutOfBounds(targetRecord)가 true이면, TypeError exception을 throw한다.
  3. targetLengthTypedArrayLength(targetRecord)로 둔다.
  4. source를 ? ToObject(source)로 설정한다.
  5. sourceLength를 ? LengthOfArrayLike(source)로 둔다.
  6. targetOffset = +∞이면, RangeError exception을 throw한다.
  7. sourceLength + targetOffset > targetLength이면, RangeError exception을 throw한다.
  8. k를 0으로 둔다.
  9. Repeat, while k < sourceLength,
    1. propertyKey를 ! ToString(𝔽(k))로 둔다.
    2. value를 ? Get(source, propertyKey)로 둔다.
    3. targetIndex𝔽(targetOffset + k)로 둔다.
    4. TypedArraySetElement(target, targetIndex, value)를 수행한다.
    5. kk + 1로 설정한다.
  10. unused를 반환한다.

23.2.3.26.2 SetTypedArrayFromTypedArray ( target, targetOffset, source )

The abstract operation SetTypedArrayFromTypedArray takes arguments target (a TypedArray), targetOffset (a non-negative integer or +∞), and source (a TypedArray) and returns either a normal completion containing unused or a throw completion. source에서 values를 reading하여, index targetOffset에서 starting하여 target 안에 multiple values를 sets합니다. It performs the following steps when called:

  1. targetBuffertarget.[[ViewedArrayBuffer]]로 둔다.
  2. targetRecordMakeTypedArrayWithBufferWitnessRecord(target, seq-cst)로 둔다.
  3. IsTypedArrayOutOfBounds(targetRecord)가 true이면, TypeError exception을 throw한다.
  4. targetLengthTypedArrayLength(targetRecord)로 둔다.
  5. sourceBuffersource.[[ViewedArrayBuffer]]로 둔다.
  6. sourceRecordMakeTypedArrayWithBufferWitnessRecord(source, seq-cst)로 둔다.
  7. IsTypedArrayOutOfBounds(sourceRecord)가 true이면, TypeError exception을 throw한다.
  8. sourceLengthTypedArrayLength(sourceRecord)로 둔다.
  9. targetTypeTypedArrayElementType(target)으로 둔다.
  10. targetElementSizeTypedArrayElementSize(target)로 둔다.
  11. targetByteOffsettarget.[[ByteOffset]]으로 둔다.
  12. sourceTypeTypedArrayElementType(source)로 둔다.
  13. sourceElementSizeTypedArrayElementSize(source)로 둔다.
  14. sourceByteOffsetsource.[[ByteOffset]]으로 둔다.
  15. targetOffset = +∞이면, RangeError exception을 throw한다.
  16. sourceLength + targetOffset > targetLength이면, RangeError exception을 throw한다.
  17. target.[[ContentType]]source.[[ContentType]]이 아니면, TypeError exception을 throw한다.
  18. IsSharedArrayBuffer(sourceBuffer)가 true이고, IsSharedArrayBuffer(targetBuffer)가 true이며, sourceBuffer.[[ArrayBufferData]]targetBuffer.[[ArrayBufferData]]이면 sameSharedArrayBuffertrue로 둔다; else sameSharedArrayBufferfalse로 둔다.
  19. SameValue(sourceBuffer, targetBuffer)가 true이거나 sameSharedArrayBuffertrue이면, 다음을 수행한다.
    1. sourceByteLengthTypedArrayByteLength(sourceRecord)로 둔다.
    2. sourceBuffer를 ? CloneArrayBuffer(sourceBuffer, sourceByteOffset, sourceByteLength)로 설정한다.
    3. sourceByteIndex를 0으로 둔다.
  20. Else,
    1. sourceByteIndexsourceByteOffset으로 둔다.
  21. targetByteIndex를 (targetOffset × targetElementSize) + targetByteOffset으로 둔다.
  22. limittargetByteIndex + (targetElementSize × sourceLength)로 둔다.
  23. sourceTypetargetType이면, 다음을 수행한다.
    1. NOTE: transfer는 source data의 bit-level encoding을 preserve하는 manner로 performed되어야 한다.
    2. Repeat, while targetByteIndex < limit,
      1. valueGetValueFromBuffer(sourceBuffer, sourceByteIndex, uint8, true, unordered)로 둔다.
      2. SetValueInBuffer(targetBuffer, targetByteIndex, uint8, value, true, unordered)를 수행한다.
      3. sourceByteIndexsourceByteIndex + 1로 설정한다.
      4. targetByteIndextargetByteIndex + 1로 설정한다.
  24. Else,
    1. Repeat, while targetByteIndex < limit,
      1. valueGetValueFromBuffer(sourceBuffer, sourceByteIndex, sourceType, true, unordered)로 둔다.
      2. SetValueInBuffer(targetBuffer, targetByteIndex, targetType, value, true, unordered)를 수행한다.
      3. sourceByteIndexsourceByteIndex + sourceElementSize로 설정한다.
      4. targetByteIndextargetByteIndex + targetElementSize로 설정한다.
  25. unused를 반환한다.

23.2.3.27 %TypedArray%.prototype.slice ( start, end )

이 method의 arguments에 대한 interpretation 및 use는 23.1.3.28에 defined된 Array.prototype.slice의 경우와 같습니다.

이 method는 called될 때 다음 steps를 수행합니다:

  1. objthis value로 둔다.
  2. taRecord를 ? ValidateTypedArray(obj, seq-cst)로 둔다.
  3. sourceArrayLengthTypedArrayLength(taRecord)로 둔다.
  4. relativeStart를 ? ToIntegerOrInfinity(start)로 둔다.
  5. relativeStart = -∞이면, startIndex를 0으로 둔다.
  6. Else if relativeStart < 0이면, startIndexmax(sourceArrayLength + relativeStart, 0)으로 둔다.
  7. Else, startIndexmin(relativeStart, sourceArrayLength)로 둔다.
  8. endundefined이면 relativeEndsourceArrayLength로 둔다; else relativeEnd를 ? ToIntegerOrInfinity(end)로 둔다.
  9. relativeEnd = -∞이면, endIndex를 0으로 둔다.
  10. Else if relativeEnd < 0이면, endIndexmax(sourceArrayLength + relativeEnd, 0)으로 둔다.
  11. Else, endIndexmin(relativeEnd, sourceArrayLength)로 둔다.
  12. countBytesmax(endIndex - startIndex, 0)으로 둔다.
  13. resultArray를 ? TypedArraySpeciesCreate(obj, « 𝔽(countBytes) »)로 둔다.
  14. countBytes > 0이면, 다음을 수행한다.
    1. taRecordMakeTypedArrayWithBufferWitnessRecord(obj, seq-cst)로 설정한다.
    2. IsTypedArrayOutOfBounds(taRecord)가 true이면, TypeError exception을 throw한다.
    3. endIndexmin(endIndex, TypedArrayLength(taRecord))로 설정한다.
    4. countBytesmax(endIndex - startIndex, 0)으로 설정한다.
    5. sourceTypeTypedArrayElementType(obj)로 둔다.
    6. targetTypeTypedArrayElementType(resultArray)로 둔다.
    7. sourceTypetargetType이면, 다음을 수행한다.
      1. NOTE: transfer는 source data의 bit-level encoding을 preserve하는 manner로 performed되어야 한다.
      2. sourceBufferobj.[[ViewedArrayBuffer]]로 둔다.
      3. targetBufferresultArray.[[ViewedArrayBuffer]]로 둔다.
      4. elementSizeTypedArrayElementSize(obj)로 둔다.
      5. sourceByteOffsetobj.[[ByteOffset]]으로 둔다.
      6. sourceByteIndex를 (startIndex × elementSize) + sourceByteOffset으로 둔다.
      7. targetByteIndexresultArray.[[ByteOffset]]으로 둔다.
      8. endByteIndextargetByteIndex + (countBytes × elementSize)로 둔다.
      9. Repeat, while targetByteIndex < endByteIndex,
        1. valueGetValueFromBuffer(sourceBuffer, sourceByteIndex, uint8, true, unordered)로 둔다.
        2. SetValueInBuffer(targetBuffer, targetByteIndex, uint8, value, true, unordered)를 수행한다.
        3. sourceByteIndexsourceByteIndex + 1로 설정한다.
        4. targetByteIndextargetByteIndex + 1로 설정한다.
    8. Else,
      1. n을 0으로 둔다.
      2. kstartIndex로 둔다.
      3. Repeat, while k < endIndex,
        1. propertyKey를 ! ToString(𝔽(k))로 둔다.
        2. kValue를 ! Get(obj, propertyKey)로 둔다.
        3. Set(resultArray, ! ToString(𝔽(n)), kValue, true)를 수행한다.
        4. kk + 1로 설정한다.
        5. nn + 1로 설정한다.
  15. resultArray를 반환한다.

이 method는 generic하지 않습니다. this value는 [[TypedArrayName]] internal slot을 가진 object여야 합니다.

23.2.3.28 %TypedArray%.prototype.some ( callback [ , thisArg ] )

이 method의 arguments에 대한 interpretation 및 use는 23.1.3.29에 defined된 Array.prototype.some의 경우와 같습니다.

이 method는 called될 때 다음 steps를 수행합니다:

  1. objthis value로 둔다.
  2. taRecord를 ? ValidateTypedArray(obj, seq-cst)로 둔다.
  3. lengthTypedArrayLength(taRecord)로 둔다.
  4. IsCallable(callback)가 false이면, TypeError exception을 throw한다.
  5. k를 0으로 둔다.
  6. Repeat, while k < length,
    1. propertyKey를 ! ToString(𝔽(k))로 둔다.
    2. kValue를 ! Get(obj, propertyKey)로 둔다.
    3. testResultToBoolean(? Call(callback, thisArg, « kValue, 𝔽(k), obj »))로 둔다.
    4. testResulttrue이면, true를 반환한다.
    5. kk + 1로 설정한다.
  7. false를 반환한다.

이 method는 generic하지 않습니다. this value는 [[TypedArrayName]] internal slot을 가진 object여야 합니다.

23.2.3.29 %TypedArray%.prototype.sort ( comparator )

이는 below에 described된 경우를 제외하고 23.1.3.30에 defined된 Array.prototype.sort의 requirements와 same requirements를 implements하는 distinct method입니다. 이 method의 implementation은 this value가 fixed length를 가지며 integer-indexed properties가 sparse하지 않은 object라는 knowledge로 optimized될 수 있습니다.

이 method는 generic하지 않습니다. this value는 [[TypedArrayName]] internal slot을 가진 object여야 합니다.

called될 때 다음 steps를 수행합니다:

  1. comparatorundefined가 아니고 IsCallable(comparator)가 false이면, TypeError exception을 throw한다.
  2. objthis value로 둔다.
  3. taRecord를 ? ValidateTypedArray(obj, seq-cst)로 둔다.
  4. lengthTypedArrayLength(taRecord)로 둔다.
  5. NOTE: following closure는 23.1.3.30에서 사용되는 string comparison이 아니라 numeric comparison을 수행한다.
  6. comparator를 capture하고 called될 때 다음 steps를 수행하는, parameters (x, y)를 가진 새 Abstract Closure sortCompare를 둔다:
    1. CompareTypedArrayElements(x, y, comparator)를 반환한다.
  7. sortedList를 ? SortIndexedProperties(obj, length, sortCompare, read-through-holes)로 둔다.
  8. j를 0으로 둔다.
  9. Repeat, while j < length,
    1. Set(obj, ! ToString(𝔽(j)), sortedList[j], true)를 수행한다.
    2. jj + 1로 설정한다.
  10. obj를 반환한다.
Note

NaN은 always any other value보다 greater로 compare되므로(CompareTypedArrayElements 참조), comparator가 provided되지 않을 때 NaN property values는 always result의 end로 sort됩니다.

23.2.3.30 %TypedArray%.prototype.subarray ( start, end )

이 method는 element type이 this TypedArray의 element type이고 ArrayBuffer가 this TypedArray의 ArrayBuffer인 new TypedArray를 반환하며, start(inclusive)부터 end(exclusive)까지의 interval 안의 elements를 referencing합니다. start 또는 end 중 어느 하나가 negative이면, beginning에서가 아니라 array의 end로부터의 index를 refer합니다.

called될 때 다음 steps를 수행합니다:

  1. objthis value로 둔다.
  2. RequireInternalSlot(obj, [[TypedArrayName]])를 수행한다.
  3. Assert: obj[[ViewedArrayBuffer]] internal slot을 가진다.
  4. bufferobj.[[ViewedArrayBuffer]]로 둔다.
  5. sourceRecordMakeTypedArrayWithBufferWitnessRecord(obj, seq-cst)로 둔다.
  6. IsTypedArrayOutOfBounds(sourceRecord)가 true이면, 다음을 수행한다.
    1. sourceLength를 0으로 둔다.
  7. Else,
    1. sourceLengthTypedArrayLength(sourceRecord)로 둔다.
  8. relativeStart를 ? ToIntegerOrInfinity(start)로 둔다.
  9. relativeStart = -∞이면, startIndex를 0으로 둔다.
  10. Else if relativeStart < 0이면, startIndexmax(sourceLength + relativeStart, 0)으로 둔다.
  11. Else, startIndexmin(relativeStart, sourceLength)로 둔다.
  12. elementSizeTypedArrayElementSize(obj)로 둔다.
  13. sourceByteOffsetobj.[[ByteOffset]]으로 둔다.
  14. beginByteOffsetsourceByteOffset + (startIndex × elementSize)로 둔다.
  15. obj.[[ArrayLength]]auto이고 endundefined이면, 다음을 수행한다.
    1. argList를 « buffer, 𝔽(beginByteOffset) »로 둔다.
  16. Else,
    1. endundefined이면 relativeEndsourceLength로 둔다; else relativeEnd를 ? ToIntegerOrInfinity(end)로 둔다.
    2. relativeEnd = -∞이면, endIndex를 0으로 둔다.
    3. Else if relativeEnd < 0이면, endIndexmax(sourceLength + relativeEnd, 0)으로 둔다.
    4. Else, endIndexmin(relativeEnd, sourceLength)로 둔다.
    5. newLengthmax(endIndex - startIndex, 0)으로 둔다.
    6. argList를 « buffer, 𝔽(beginByteOffset), 𝔽(newLength) »로 둔다.
  17. TypedArraySpeciesCreate(obj, argList)를 반환한다.

이 method는 generic하지 않습니다. this value는 [[TypedArrayName]] internal slot을 가진 object여야 합니다.

23.2.3.31 %TypedArray%.prototype.toLocaleString ( [ reserved1 [ , reserved2 ] ] )

이는 TypedArrayLength"length"[[Get]]을 performing하는 대신 called된다는 점을 제외하고 23.1.3.32에 defined된 Array.prototype.toLocaleString과 same algorithm을 implements하는 distinct method입니다. underlying buffer가 resizable하지 않을 때 this value가 fixed length를 가지며 integer-indexed properties가 sparse하지 않다는 knowledge로 algorithm의 implementation이 optimized될 수 있습니다. However, such optimization은 algorithm의 specified behaviour에 any observable changes를 introduce해서는 안 됩니다.

이 method는 generic하지 않습니다. algorithm을 evaluating하기 전에 ValidateTypedArraythis value와 seq-cst를 arguments로 하여 called됩니다. 그 result가 abrupt completion이면, algorithm을 evaluating하는 대신 that exception이 thrown됩니다.

Note

ECMAScript implementation이 ECMA-402 Internationalization API를 include하면, 이 method는 ECMA-402 specification 안의 Array.prototype.toLocaleString용 algorithm에 based됩니다.

23.2.3.32 %TypedArray%.prototype.toReversed ( )

이 method는 called될 때 다음 steps를 수행합니다:

  1. objthis value로 둔다.
  2. taRecord를 ? ValidateTypedArray(obj, seq-cst)로 둔다.
  3. lengthTypedArrayLength(taRecord)로 둔다.
  4. resultArray를 ? TypedArrayCreateSameType(obj, length)로 둔다.
  5. k를 0으로 둔다.
  6. Repeat, while k < length,
    1. from을 ! ToString(𝔽(length - k - 1))로 둔다.
    2. propertyKey를 ! ToString(𝔽(k))로 둔다.
    3. fromValue를 ! Get(obj, from)로 둔다.
    4. Set(resultArray, propertyKey, fromValue, true)를 수행한다.
    5. kk + 1로 설정한다.
  7. resultArray를 반환한다.

23.2.3.33 %TypedArray%.prototype.toSorted ( comparator )

이 method는 called될 때 다음 steps를 수행합니다:

  1. comparatorundefined가 아니고 IsCallable(comparator)가 false이면, TypeError exception을 throw한다.
  2. objthis value로 둔다.
  3. taRecord를 ? ValidateTypedArray(obj, seq-cst)로 둔다.
  4. lengthTypedArrayLength(taRecord)로 둔다.
  5. resultArray를 ? TypedArrayCreateSameType(obj, length)로 둔다.
  6. NOTE: following closure는 23.1.3.34에서 사용되는 string comparison이 아니라 numeric comparison을 수행한다.
  7. comparator를 capture하고 called될 때 다음 steps를 수행하는, parameters (x, y)를 가진 새 Abstract Closure sortCompare를 둔다:
    1. CompareTypedArrayElements(x, y, comparator)를 반환한다.
  8. sortedList를 ? SortIndexedProperties(obj, length, sortCompare, read-through-holes)로 둔다.
  9. j를 0으로 둔다.
  10. Repeat, while j < length,
    1. Set(resultArray, ! ToString(𝔽(j)), sortedList[j], true)를 수행한다.
    2. jj + 1로 설정한다.
  11. resultArray를 반환한다.

23.2.3.34 %TypedArray%.prototype.toString ( )

"toString" property의 initial value는 23.1.3.36에 defined된 %Array.prototype.toString%입니다.

23.2.3.35 %TypedArray%.prototype.values ( )

이 method는 called될 때 다음 steps를 수행합니다:

  1. objthis value로 둔다.
  2. ValidateTypedArray(obj, seq-cst)를 수행한다.
  3. CreateArrayIterator(obj, value)를 반환한다.

23.2.3.36 %TypedArray%.prototype.with ( index, value )

이 method는 called될 때 다음 steps를 수행합니다:

  1. objthis value로 둔다.
  2. taRecord를 ? ValidateTypedArray(obj, seq-cst)로 둔다.
  3. lengthTypedArrayLength(taRecord)로 둔다.
  4. relativeIndex를 ? ToIntegerOrInfinity(index)로 둔다.
  5. relativeIndex ≥ 0이면 actualIndexrelativeIndex로 둔다.
  6. Else, actualIndexlength + relativeIndex로 둔다.
  7. obj.[[ContentType]]bigint이면, numericValue를 ? ToBigInt(value)로 둔다.
  8. Else, numericValue를 ? ToNumber(value)로 둔다.
  9. IsValidIntegerIndex(obj, 𝔽(actualIndex))가 false이면, RangeError exception을 throw한다.
  10. resultArray를 ? TypedArrayCreateSameType(obj, length)로 둔다.
  11. k를 0으로 둔다.
  12. Repeat, while k < length,
    1. propertyKey를 ! ToString(𝔽(k))로 둔다.
    2. k = actualIndex이면 fromValuenumericValue로 둔다.
    3. Else, fromValue를 ! Get(obj, propertyKey)로 둔다.
    4. Set(resultArray, propertyKey, fromValue, true)를 수행한다.
    5. kk + 1로 설정한다.
  13. resultArray를 반환한다.

23.2.3.37 %TypedArray%.prototype [ %Symbol.iterator% ] ( )

%Symbol.iterator% property의 initial value는 23.2.3.35에 defined된 %TypedArray.prototype.values%입니다.

23.2.3.38 get %TypedArray%.prototype [ %Symbol.toStringTag% ]

%TypedArray%.prototype[%Symbol.toStringTag%]는 set accessor function이 undefinedaccessor property입니다. Its get accessor function은 called될 때 다음 steps를 수행합니다:

  1. objthis value로 둔다.
  2. obj가 Object가 아니면, undefined를 반환한다.
  3. obj[[TypedArrayName]] internal slot을 가지지 않으면, undefined를 반환한다.
  4. nameobj.[[TypedArrayName]]으로 둔다.
  5. Assert: name은 String이다.
  6. name을 반환한다.

이 property는 attributes { [[Enumerable]]: false, [[Configurable]]: true }를 가집니다.

이 function의 "name" property의 initial value는 "get [Symbol.toStringTag]"입니다.

23.2.4 TypedArray Objects용 Abstract Operations

23.2.4.1 TypedArrayCreateFromConstructor ( ctor, argList )

The abstract operation TypedArrayCreateFromConstructor takes arguments ctor (a constructor) and argList (a List of ECMAScript language values) and returns either a normal completion containing a TypedArray or a throw completion. constructor function을 사용한 new TypedArray의 creation을 specify하는 데 사용됩니다. It performs the following steps when called:

  1. ta를 ? Construct(ctor, argList)로 둔다.
  2. taRecord를 ? ValidateTypedArray(ta, seq-cst)로 둔다.
  3. Assert: taProperties of TypedArray Instances에 mentioned된 all internal slots를 가진다.
  4. argList 안의 elements 수가 1이고 argList[0]이 Number이면, 다음을 수행한다.
    1. IsTypedArrayOutOfBounds(taRecord)가 true이면, TypeError exception을 throw한다.
    2. lengthTypedArrayLength(taRecord)로 둔다.
    3. length < (argList[0])이면, TypeError exception을 throw한다.
  5. ta를 반환한다.

23.2.4.2 TypedArrayCreateSameType ( exemplar, length )

The abstract operation TypedArrayCreateSameType takes arguments exemplar (a TypedArray) and length (a non-negative integer) and returns either a normal completion containing a TypedArray or a throw completion. exemplar에서 derived된 constructor function을 사용한 new TypedArray의 creation을 specify하는 데 사용됩니다. %Symbol.species% 사용을 통해 custom TypedArray subclasses를 construct할 수 있는 TypedArraySpeciesCreate와 달리, 이 operation은 항상 built-in TypedArray constructors 중 하나를 사용합니다. It performs the following steps when called:

  1. ctorTable 71에서 constructor name exemplar.[[TypedArrayName]]과 associated된 intrinsic object로 둔다.
  2. result를 ? TypedArrayCreateFromConstructor(ctor, « 𝔽(length) »)로 둔다.
  3. Assert: result[[TypedArrayName]][[ContentType]] internal slots를 가진다.
  4. Assert: result.[[ContentType]]exemplar.[[ContentType]]이다.
  5. result를 반환한다.

23.2.4.3 TypedArraySpeciesCreate ( exemplar, argList )

The abstract operation TypedArraySpeciesCreate takes arguments exemplar (a TypedArray) and argList (a List of ECMAScript language values) and returns either a normal completion containing a TypedArray or a throw completion. exemplar에서 derived된 constructor function을 사용한 new TypedArray의 creation을 specify하는 데 사용됩니다. %Symbol.species% 사용을 통해 non-Array objects를 create할 수 있는 ArraySpeciesCreate와 달리, 이 operation은 constructor function이 actual TypedArray를 create하도록 enforces합니다. It performs the following steps when called:

  1. defaultCtorTable 71에서 constructor name exemplar.[[TypedArrayName]]과 associated된 intrinsic object로 둔다.
  2. ctor를 ? SpeciesConstructor(exemplar, defaultCtor)로 둔다.
  3. result를 ? TypedArrayCreateFromConstructor(ctor, argList)로 둔다.
  4. result.[[ContentType]]exemplar.[[ContentType]]이 아니면, TypeError exception을 throw한다.
  5. result를 반환한다.

23.2.4.4 ValidateTypedArray ( obj, order )

The abstract operation ValidateTypedArray takes arguments obj (an ECMAScript language value) and order (seq-cst or unordered) and returns either a normal completion containing a TypedArray With Buffer Witness Record or a throw completion. It performs the following steps when called:

  1. RequireInternalSlot(obj, [[TypedArrayName]])를 수행한다.
  2. Assert: obj[[ViewedArrayBuffer]] internal slot을 가진다.
  3. taRecordMakeTypedArrayWithBufferWitnessRecord(obj, order)로 둔다.
  4. IsTypedArrayOutOfBounds(taRecord)가 true이면, TypeError exception을 throw한다.
  5. taRecord를 반환한다.

23.2.4.5 TypedArrayElementSize ( obj )

The abstract operation TypedArrayElementSize takes argument obj (a TypedArray) and returns a non-negative integer. It performs the following steps when called:

  1. obj.[[TypedArrayName]]에 대해 Table 71에 specified된 Element Size value를 반환한다.

23.2.4.6 TypedArrayElementType ( obj )

The abstract operation TypedArrayElementType takes argument obj (a TypedArray) and returns a TypedArray element type. It performs the following steps when called:

  1. obj.[[TypedArrayName]]에 대해 Table 71에 specified된 Element Type value를 반환한다.

23.2.4.7 CompareTypedArrayElements ( x, y, comparator )

The abstract operation CompareTypedArrayElements takes arguments x (a Number or a BigInt), y (a Number or a BigInt), and comparator (a function object or undefined) and returns either a normal completion containing a Number or an abrupt completion. It performs the following steps when called:

  1. Assert: xy는 모두 Number이거나, xy는 모두 BigInt이다.
  2. comparatorundefined가 아니면, 다음을 수행한다.
    1. result를 ? ToNumber(? Call(comparator, undefined, « x, y »))로 둔다.
    2. resultNaN이면, +0𝔽를 반환한다.
    3. result를 반환한다.
  3. xNaN이고 yNaN이면, +0𝔽를 반환한다.
  4. xNaN이면, 1𝔽를 반환한다.
  5. yNaN이면, -1𝔽를 반환한다.
  6. x < y이면, -1𝔽를 반환한다.
  7. x > y이면, 1𝔽를 반환한다.
  8. x-0𝔽이고 y+0𝔽이면, -1𝔽를 반환한다.
  9. x+0𝔽이고 y-0𝔽이면, 1𝔽를 반환한다.
  10. +0𝔽를 반환한다.
Note
이는 23.1.3.30.2에서 사용되는 string comparison이 아니라 numeric comparison을 수행합니다.

23.2.5 The TypedArray Constructors

TypedArray constructor는:

  • otherwise noted된 경우를 제외하고, Table 71에서 TypedArray 대신 constructor name으로 사용되는 name만 differing하며 below에 described된 structure를 가지는 intrinsic object입니다.
  • arguments의 number 및 types에 따라 behaviour가 달라지는 function입니다. TypedArray call의 actual behaviour는 pass된 arguments의 number 및 kind에 depends합니다.
  • function으로 called되도록 intended되지 않으며, such manner로 called될 때 exception을 throw합니다.
  • 클래스 정의의 extends 절의 값으로 사용될 수 있다. 지정된 TypedArray 동작을 상속하려는 서브클래스 생성자는 %TypedArray%.prototype의 내장 메서드를 지원하는 데 필요한 내부 상태로 서브클래스 인스턴스를 생성하고 초기화하기 위해 TypedArray 생성자에 대한 super 호출을 포함해야 한다.

23.2.5.1 TypedArray ( ...args )

TypedArray constructor는 called될 때 다음 steps를 수행합니다:

  1. NewTarget이 undefined이면, TypeError exception을 throw한다.
  2. ctorName을 이 TypedArray constructor에 대해 Table 71에 specified된 Constructor Name value의 String value로 둔다.
  3. proto"%TypedArray.prototype%"로 둔다.
  4. numberOfArgsargs 안의 elements 수로 둔다.
  5. numberOfArgs = 0이면, ? AllocateTypedArray(ctorName, NewTarget, proto, 0)를 반환한다.
  6. firstArgargs[0]으로 둔다.
  7. firstArg가 Object이면, 다음을 수행한다.
    1. obj를 ? AllocateTypedArray(ctorName, NewTarget, proto)로 둔다.
    2. firstArg[[TypedArrayName]] internal slot을 가지면, 다음을 수행한다.
      1. InitializeTypedArrayFromTypedArray(obj, firstArg)를 수행한다.
    3. Else if firstArg[[ArrayBufferData]] internal slot을 가지면, 다음을 수행한다.
      1. numberOfArgs > 1이면 byteOffsetargs[1]로 둔다; else byteOffsetundefined로 둔다.
      2. numberOfArgs > 2이면 lengthargs[2]로 둔다; else lengthundefined로 둔다.
      3. InitializeTypedArrayFromArrayBuffer(obj, firstArg, byteOffset, length)를 수행한다.
    4. Else,
      1. Assert: firstArg는 Object이고 firstArg[[TypedArrayName]] 또는 [[ArrayBufferData]] internal slot 어느 것도 가지지 않는다.
      2. usingIterator를 ? GetMethod(firstArg, %Symbol.iterator%)로 둔다.
      3. usingIteratorundefined가 아니면, 다음을 수행한다.
        1. values를 ? IteratorToList(? GetIteratorFromMethod(firstArg, usingIterator))로 둔다.
        2. InitializeTypedArrayFromList(obj, values)를 수행한다.
      4. Else,
        1. NOTE: firstArgiterable object가 아니므로, already array-like object라고 assume한다.
        2. InitializeTypedArrayFromArrayLike(obj, firstArg)를 수행한다.
    5. obj를 반환한다.
  8. Assert: firstArg는 Object가 아니다.
  9. elementLength를 ? ToIndex(firstArg)로 둔다.
  10. AllocateTypedArray(ctorName, NewTarget, proto, elementLength)를 반환한다.

23.2.5.1.1 AllocateTypedArray ( ctorName, newTarget, defaultProto [ , length ] )

The abstract operation AllocateTypedArray takes arguments ctorName (a String which is the name of a TypedArray constructor in Table 71), newTarget (a constructor), and defaultProto (a String) and optional argument length (a non-negative integer) and returns either a normal completion containing a TypedArray or a throw completion. TypedArray constructor의 instance를 validate하고 create하는 데 사용됩니다. length argument가 passed되면, that length의 ArrayBuffer도 allocated되고 new TypedArray instance와 associated됩니다. AllocateTypedArray는 TypedArray에 의해 사용되는 common semantics를 제공합니다. It performs the following steps when called:

  1. proto를 ? GetPrototypeFromConstructor(newTarget, defaultProto)로 둔다.
  2. objTypedArrayCreate(proto)로 둔다.
  3. Assert: obj.[[ViewedArrayBuffer]]undefined이다.
  4. obj.[[TypedArrayName]]ctorName으로 설정한다.
  5. ctorName"BigInt64Array" 또는 "BigUint64Array" 중 하나이면, obj.[[ContentType]]bigint로 설정한다.
  6. Else, obj.[[ContentType]]number로 설정한다.
  7. length가 present하지 않으면, 다음을 수행한다.
    1. obj.[[ByteLength]]를 0으로 설정한다.
    2. obj.[[ByteOffset]]을 0으로 설정한다.
    3. obj.[[ArrayLength]]를 0으로 설정한다.
  8. Else,
    1. AllocateTypedArrayBuffer(obj, length)를 수행한다.
  9. obj를 반환한다.

23.2.5.1.2 InitializeTypedArrayFromTypedArray ( obj, sourceArray )

The abstract operation InitializeTypedArrayFromTypedArray takes arguments obj (a TypedArray) and sourceArray (a TypedArray) and returns either a normal completion containing unused or a throw completion. It performs the following steps when called:

  1. sourceDatasourceArray.[[ViewedArrayBuffer]]로 둔다.
  2. elementTypeTypedArrayElementType(obj)로 둔다.
  3. elementSizeTypedArrayElementSize(obj)로 둔다.
  4. sourceTypeTypedArrayElementType(sourceArray)로 둔다.
  5. sourceElementSizeTypedArrayElementSize(sourceArray)로 둔다.
  6. sourceByteOffsetsourceArray.[[ByteOffset]]으로 둔다.
  7. sourceRecordMakeTypedArrayWithBufferWitnessRecord(sourceArray, seq-cst)로 둔다.
  8. IsTypedArrayOutOfBounds(sourceRecord)가 true이면, TypeError exception을 throw한다.
  9. elementLengthTypedArrayLength(sourceRecord)로 둔다.
  10. byteLengthelementSize × elementLength로 둔다.
  11. elementTypesourceType이면, 다음을 수행한다.
    1. data를 ? CloneArrayBuffer(sourceData, sourceByteOffset, byteLength)로 둔다.
  12. Else,
    1. data를 ? AllocateArrayBuffer(%ArrayBuffer%, byteLength)로 둔다.
    2. sourceArray.[[ContentType]]obj.[[ContentType]]이 아니면, TypeError exception을 throw한다.
    3. sourceByteIndexsourceByteOffset으로 둔다.
    4. targetByteIndex를 0으로 둔다.
    5. countelementLength로 둔다.
    6. Repeat, while count > 0,
      1. valueGetValueFromBuffer(sourceData, sourceByteIndex, sourceType, true, unordered)로 둔다.
      2. SetValueInBuffer(data, targetByteIndex, elementType, value, true, unordered)를 수행한다.
      3. sourceByteIndexsourceByteIndex + sourceElementSize로 설정한다.
      4. targetByteIndextargetByteIndex + elementSize로 설정한다.
      5. countcount - 1로 설정한다.
  13. obj.[[ViewedArrayBuffer]]data로 설정한다.
  14. obj.[[ByteLength]]byteLength로 설정한다.
  15. obj.[[ByteOffset]]을 0으로 설정한다.
  16. obj.[[ArrayLength]]elementLength로 설정한다.
  17. unused를 반환한다.

23.2.5.1.3 InitializeTypedArrayFromArrayBuffer ( obj, buffer, byteOffset, length )

The abstract operation InitializeTypedArrayFromArrayBuffer takes arguments obj (a TypedArray), buffer (an ArrayBuffer or a SharedArrayBuffer), byteOffset (an ECMAScript language value), and length (an ECMAScript language value) and returns either a normal completion containing unused or a throw completion. It performs the following steps when called:

  1. elementSizeTypedArrayElementSize(obj)로 둔다.
  2. offset을 ? ToIndex(byteOffset)으로 둔다.
  3. offset modulo elementSize ≠ 0이면, RangeError exception을 throw한다.
  4. bufferIsFixedLengthIsFixedLengthArrayBuffer(buffer)로 둔다.
  5. lengthundefined가 아니면, 다음을 수행한다.
    1. newLength를 ? ToIndex(length)로 둔다.
  6. IsDetachedBuffer(buffer)가 true이면, TypeError exception을 throw한다.
  7. bufferByteLengthArrayBufferByteLength(buffer, seq-cst)로 둔다.
  8. lengthundefined이고 bufferIsFixedLengthfalse이면, 다음을 수행한다.
    1. offset > bufferByteLength이면, RangeError exception을 throw한다.
    2. obj.[[ByteLength]]auto로 설정한다.
    3. obj.[[ArrayLength]]auto로 설정한다.
  9. Else,
    1. lengthundefined이면, 다음을 수행한다.
      1. bufferByteLength modulo elementSize ≠ 0이면, RangeError exception을 throw한다.
      2. newByteLengthbufferByteLength - offset으로 둔다.
      3. newByteLength < 0이면, RangeError exception을 throw한다.
    2. Else,
      1. newByteLengthnewLength × elementSize로 둔다.
      2. offset + newByteLength > bufferByteLength이면, RangeError exception을 throw한다.
    3. obj.[[ByteLength]]newByteLength로 설정한다.
    4. obj.[[ArrayLength]]newByteLength / elementSize로 설정한다.
  10. obj.[[ViewedArrayBuffer]]buffer로 설정한다.
  11. obj.[[ByteOffset]]offset으로 설정한다.
  12. unused를 반환한다.

23.2.5.1.4 InitializeTypedArrayFromList ( obj, values )

The abstract operation InitializeTypedArrayFromList takes arguments obj (a TypedArray) and values (a List of ECMAScript language values) and returns either a normal completion containing unused or a throw completion. It performs the following steps when called:

  1. lengthvalues 안의 elements 수로 둔다.
  2. AllocateTypedArrayBuffer(obj, length)를 수행한다.
  3. k를 0으로 둔다.
  4. Repeat, while k < length,
    1. propertyKey를 ! ToString(𝔽(k))로 둔다.
    2. kValuevalues의 first element로 둔다.
    3. values에서 first element를 remove한다.
    4. Set(obj, propertyKey, kValue, true)를 수행한다.
    5. kk + 1로 설정한다.
  5. Assert: values는 now empty List이다.
  6. unused를 반환한다.

23.2.5.1.5 InitializeTypedArrayFromArrayLike ( obj, arrayLike )

The abstract operation InitializeTypedArrayFromArrayLike takes arguments obj (a TypedArray) and arrayLike (an Object, but not a TypedArray or an ArrayBuffer) and returns either a normal completion containing unused or a throw completion. It performs the following steps when called:

  1. length를 ? LengthOfArrayLike(arrayLike)로 둔다.
  2. AllocateTypedArrayBuffer(obj, length)를 수행한다.
  3. k를 0으로 둔다.
  4. Repeat, while k < length,
    1. propertyKey를 ! ToString(𝔽(k))로 둔다.
    2. kValue를 ? Get(arrayLike, propertyKey)로 둔다.
    3. Set(obj, propertyKey, kValue, true)를 수행한다.
    4. kk + 1로 설정한다.
  5. unused를 반환한다.

23.2.5.1.6 AllocateTypedArrayBuffer ( obj, length )

The abstract operation AllocateTypedArrayBuffer takes arguments obj (a TypedArray) and length (a non-negative integer) and returns either a normal completion containing unused or a throw completion. ArrayBuffer를 allocate하고 obj와 associate합니다. It performs the following steps when called:

  1. Assert: obj.[[ViewedArrayBuffer]]undefined이다.
  2. elementSizeTypedArrayElementSize(obj)로 둔다.
  3. byteLengthelementSize × length로 둔다.
  4. data를 ? AllocateArrayBuffer(%ArrayBuffer%, byteLength)로 둔다.
  5. obj.[[ViewedArrayBuffer]]data로 설정한다.
  6. obj.[[ByteLength]]byteLength로 설정한다.
  7. obj.[[ByteOffset]]을 0으로 설정한다.
  8. obj.[[ArrayLength]]length로 설정한다.
  9. unused를 반환한다.

23.2.6 Properties of the TypedArray Constructors

TypedArray constructor는:

  • value가 %TypedArray%[[Prototype]] internal slot을 가집니다.
  • value가 3𝔽"length" property를 가집니다.
  • Table 71에서 그것에 대해 specified된 constructor name의 String value인 "name" property를 가집니다.
  • 다음 properties를 가집니다:

23.2.6.1 TypedArray.BYTES_PER_ELEMENT

TypedArray.BYTES_PER_ELEMENT의 value는 TypedArray에 대해 Table 71에 specified된 Element Size value입니다.

이 property는 attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }를 가집니다.

23.2.6.2 TypedArray.prototype

TypedArray.prototype의 initial value는 corresponding TypedArray prototype intrinsic object(23.2.7)입니다.

이 property는 attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }를 가집니다.

23.2.7 Properties of the TypedArray Prototype Objects

TypedArray prototype object는:

  • value가 %TypedArray.prototype%[[Prototype]] internal slot을 가집니다.
  • ordinary object입니다.
  • [[ViewedArrayBuffer]] 또는 TypedArray instance objects에 specific한 any other internal slots를 가지지 않습니다.

23.2.7.1 TypedArray.prototype.BYTES_PER_ELEMENT

TypedArray.prototype.BYTES_PER_ELEMENT의 value는 TypedArray에 대해 Table 71에 specified된 Element Size value입니다.

이 property는 attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }를 가집니다.

23.2.7.2 TypedArray.prototype.constructor

given TypedArray constructor에 대한 prototype의 "constructor" property의 initial value는 constructor itself입니다.

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 Objects

Uint8Array는 위에 described된 TypedArray의 particular kind입니다. 또한 Uint8Array constructor(23.3.1)와 Uint8Array prototype object(23.3.2)에 additional methods가 있습니다.

23.3.1 Additional Properties of the Uint8Array Constructor

23.3.1.1 Uint8Array.fromBase64 ( string [ , options ] )

  1. string이 String이 아니면, TypeError exception을 throw한다.
  2. opts를 ? GetOptionsObject(options)로 둔다.
  3. alphabet을 ? Get(opts, "alphabet")으로 둔다.
  4. alphabetundefined이면, alphabet"base64"로 설정한다.
  5. alphabet"base64""base64url"도 아니면, TypeError exception을 throw한다.
  6. lastChunkHandling을 ? Get(opts, "lastChunkHandling")으로 둔다.
  7. lastChunkHandlingundefined이면, lastChunkHandling"loose"로 설정한다.
  8. lastChunkHandling"loose", "strict", 또는 "stop-before-partial" 중 하나가 아니면, TypeError exception을 throw한다.
  9. resultFromBase64(string, alphabet, lastChunkHandling)로 둔다.
  10. result.[[Error]]none이 아니면, 다음을 수행한다.
    1. result.[[Error]]를 Throw한다.
  11. resultLengthresult.[[Bytes]] 안의 elements 수로 둔다.
  12. ta를 ? AllocateTypedArray("Uint8Array", %Uint8Array%, "%Uint8Array.prototype%", resultLength)로 둔다.
  13. Assert: ta.[[ViewedArrayBuffer]].[[ArrayBufferByteLength]]result.[[Bytes]] 안의 elements 수이다.
  14. ta.[[ViewedArrayBuffer]].[[ArrayBufferData]]의 each index의 value를 result.[[Bytes]]의 corresponding index의 value로 설정한다.
  15. ta를 반환한다.

23.3.1.2 Uint8Array.fromHex ( string )

  1. string이 String이 아니면, TypeError exception을 throw한다.
  2. resultFromHex(string)로 둔다.
  3. result.[[Error]]none이 아니면, 다음을 수행한다.
    1. result.[[Error]]를 Throw한다.
  4. resultLengthresult.[[Bytes]] 안의 elements 수로 둔다.
  5. ta를 ? AllocateTypedArray("Uint8Array", %Uint8Array%, "%Uint8Array.prototype%", resultLength)로 둔다.
  6. Assert: ta.[[ViewedArrayBuffer]].[[ArrayBufferByteLength]]result.[[Bytes]] 안의 elements 수이다.
  7. ta.[[ViewedArrayBuffer]].[[ArrayBufferData]]의 each index의 value를 result.[[Bytes]]의 corresponding index의 value로 설정한다.
  8. ta를 반환한다.

23.3.2 Additional Properties of the Uint8Array Prototype Object

23.3.2.1 Uint8Array.prototype.setFromBase64 ( string [ , options ] )

  1. intothis value로 둔다.
  2. ValidateUint8Array(into)를 수행한다.
  3. string이 String이 아니면, TypeError exception을 throw한다.
  4. opts를 ? GetOptionsObject(options)로 둔다.
  5. alphabet을 ? Get(opts, "alphabet")으로 둔다.
  6. alphabetundefined이면, alphabet"base64"로 설정한다.
  7. alphabet"base64""base64url"도 아니면, TypeError exception을 throw한다.
  8. lastChunkHandling을 ? Get(opts, "lastChunkHandling")으로 둔다.
  9. lastChunkHandlingundefined이면, lastChunkHandling"loose"로 설정한다.
  10. lastChunkHandling"loose", "strict", 또는 "stop-before-partial" 중 하나가 아니면, TypeError exception을 throw한다.
  11. taRecordMakeTypedArrayWithBufferWitnessRecord(into, seq-cst)로 둔다.
  12. IsTypedArrayOutOfBounds(taRecord)가 true이면, TypeError exception을 throw한다.
  13. byteLengthTypedArrayLength(taRecord)로 둔다.
  14. resultFromBase64(string, alphabet, lastChunkHandling, byteLength)로 둔다.
  15. bytesresult.[[Bytes]]로 둔다.
  16. writtenbytes 안의 elements 수로 둔다.
  17. NOTE: FromBase64는 any user code를 invoke하지 않으므로, into를 backing하는 ArrayBuffer는 detached되거나 shrunk되었을 수 없다.
  18. Assert: writtenbyteLength이다.
  19. SetUint8ArrayBytes(into, bytes)를 수행한다.
  20. result.[[Error]]none이 아니면, 다음을 수행한다.
    1. result.[[Error]]를 Throw한다.
  21. resultObjOrdinaryObjectCreate(%Object.prototype%)로 둔다.
  22. CreateDataPropertyOrThrow(resultObj, "read", 𝔽(result.[[Read]]))를 수행한다.
  23. CreateDataPropertyOrThrow(resultObj, "written", 𝔽(written))를 수행한다.
  24. resultObj를 반환한다.

23.3.2.2 Uint8Array.prototype.setFromHex ( string )

  1. intothis value로 둔다.
  2. ValidateUint8Array(into)를 수행한다.
  3. string이 String이 아니면, TypeError exception을 throw한다.
  4. taRecordMakeTypedArrayWithBufferWitnessRecord(into, seq-cst)로 둔다.
  5. IsTypedArrayOutOfBounds(taRecord)가 true이면, TypeError exception을 throw한다.
  6. byteLengthTypedArrayLength(taRecord)로 둔다.
  7. resultFromHex(string, byteLength)로 둔다.
  8. bytesresult.[[Bytes]]로 둔다.
  9. writtenbytes 안의 elements 수로 둔다.
  10. NOTE: FromHex는 any user code를 invoke하지 않으므로, into를 backing하는 ArrayBuffer는 detached되거나 shrunk되었을 수 없다.
  11. Assert: writtenbyteLength이다.
  12. SetUint8ArrayBytes(into, bytes)를 수행한다.
  13. result.[[Error]]none이 아니면, 다음을 수행한다.
    1. result.[[Error]]를 Throw한다.
  14. resultObjOrdinaryObjectCreate(%Object.prototype%)로 둔다.
  15. CreateDataPropertyOrThrow(resultObj, "read", 𝔽(result.[[Read]]))를 수행한다.
  16. CreateDataPropertyOrThrow(resultObj, "written", 𝔽(written))를 수행한다.
  17. resultObj를 반환한다.

23.3.2.3 Uint8Array.prototype.toBase64 ( [ options ] )

  1. objthis value로 둔다.
  2. ValidateUint8Array(obj)를 수행한다.
  3. opts를 ? GetOptionsObject(options)로 둔다.
  4. alphabet을 ? Get(opts, "alphabet")으로 둔다.
  5. alphabetundefined이면, alphabet"base64"로 설정한다.
  6. alphabet"base64""base64url"도 아니면, TypeError exception을 throw한다.
  7. omitPaddingToBoolean(? Get(opts, "omitPadding")))으로 둔다.
  8. toEncode를 ? GetUint8ArrayBytes(obj)로 둔다.
  9. alphabet"base64"이면, 다음을 수행한다.
    1. outAsciiRFC 4648의 section 4에 specified된 base64 encoding에 따라 toEncode를 encoding한 결과인 code points의 sequence로 둔다. Padding은 omitPaddingfalse인 경우에만 included된다.
  10. Else,
    1. Assert: alphabet"base64url"이다.
    2. outAsciiRFC 4648의 section 5에 specified된 base64url encoding에 따라 toEncode를 encoding한 결과인 code points의 sequence로 둔다. Padding은 omitPaddingfalse인 경우에만 included된다.
  11. CodePointsToString(outAscii)를 반환한다.

23.3.2.4 Uint8Array.prototype.toHex ( )

  1. objthis value로 둔다.
  2. ValidateUint8Array(obj)를 수행한다.
  3. toEncode를 ? GetUint8ArrayBytes(obj)로 둔다.
  4. out을 empty String으로 둔다.
  5. toEncode의 각 byte byte에 대해, 다음을 수행한다.
    1. hexNumber::toString(𝔽(byte), 16)으로 둔다.
    2. hexStringPad(hex, 2, "0", start)로 설정한다.
    3. outouthexstring-concatenation으로 설정한다.
  6. out을 반환한다.

23.3.3 Uint8Array Objects용 Abstract Operations

23.3.3.1 ValidateUint8Array ( ta )

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

  1. RequireInternalSlot(ta, [[TypedArrayName]])를 수행한다.
  2. ta.[[TypedArrayName]]"Uint8Array"가 아니면, TypeError exception을 throw한다.
  3. unused를 반환한다.

23.3.3.2 GetUint8ArrayBytes ( ta )

The abstract operation GetUint8ArrayBytes takes argument ta (a Uint8Array) and returns either a normal completion containing a List of byte values or a throw completion. It performs the following steps when called:

  1. bufferta.[[ViewedArrayBuffer]]로 둔다.
  2. taRecordMakeTypedArrayWithBufferWitnessRecord(ta, seq-cst)로 둔다.
  3. IsTypedArrayOutOfBounds(taRecord)가 true이면, TypeError exception을 throw한다.
  4. lengthTypedArrayLength(taRecord)로 둔다.
  5. byteOffsetta.[[ByteOffset]]으로 둔다.
  6. bytes를 새 empty List로 둔다.
  7. index를 0으로 둔다.
  8. Repeat, while index < length,
    1. byteIndexbyteOffset + index로 둔다.
    2. byte(GetValueFromBuffer(buffer, byteIndex, uint8, true, unordered))로 둔다.
    3. bytebytes에 append한다.
    4. indexindex + 1로 설정한다.
  9. bytes를 반환한다.

23.3.3.3 SetUint8ArrayBytes ( into, bytes )

The abstract operation SetUint8ArrayBytes takes arguments into (a Uint8Array) and bytes (a List of byte values) and returns unused. It performs the following steps when called:

  1. offsetinto.[[ByteOffset]]으로 둔다.
  2. lengthbytes 안의 elements 수로 둔다.
  3. index를 0으로 둔다.
  4. Repeat, while index < length,
    1. bytebytes[index]로 둔다.
    2. byteIndexInBufferindex + offset으로 둔다.
    3. SetValueInBuffer(into.[[ViewedArrayBuffer]], byteIndexInBuffer, uint8, 𝔽(byte), true, unordered)를 수행한다.
    4. indexindex + 1로 설정한다.
  5. unused를 반환한다.

23.3.3.4 SkipAsciiWhitespace ( string, index )

The abstract operation SkipAsciiWhitespace takes arguments string (a String) and index (a non-negative integer) and returns a non-negative integer. It performs the following steps when called:

  1. lengthstring의 length로 둔다.
  2. Repeat, while index < length,
    1. charstring 내 index index의 code unit으로 둔다.
    2. char가 0x0009 (TAB), 0x000A (LF), 0x000C (FF), 0x000D (CR), 또는 0x0020 (SPACE) 중 하나가 아니면, 다음을 수행한다.
      1. index를 반환한다.
    3. indexindex + 1로 설정한다.
  3. index를 반환한다.

23.3.3.5 DecodeFinalBase64Chunk ( chunk, throwOnExtraBits )

The abstract operation DecodeFinalBase64Chunk takes arguments chunk (a String of length 2 or 3) and throwOnExtraBits (a Boolean) and returns either a normal completion containing a List of byte values, or a throw completion. It performs the following steps when called:

  1. chunkLengthchunk의 length로 둔다.
  2. chunkLength = 2이면, 다음을 수행한다.
    1. chunkchunk"AA"string-concatenation으로 설정한다.
  3. Else,
    1. Assert: chunkLength는 3이다.
    2. chunkchunk"A"string-concatenation으로 설정한다.
  4. bytesDecodeFullLengthBase64Chunk(chunk)로 둔다.
  5. chunkLength = 2이면, 다음을 수행한다.
    1. throwOnExtraBitstrue이고 bytes[1] ≠ 0이면, SyntaxError exception을 throw한다.
    2. « bytes[0] »를 반환한다.
  6. throwOnExtraBitstrue이고 bytes[2] ≠ 0이면, SyntaxError exception을 throw한다.
  7. « bytes[0], bytes[1] »를 반환한다.

23.3.3.6 DecodeFullLengthBase64Chunk ( chunk )

The abstract operation DecodeFullLengthBase64Chunk takes argument chunk (a String of length 4) and returns a List of byte values of length 3.

standard base64 alphabet"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"입니다. 즉, Unicode Basic Latin block 안의 every letter 및 number에 corresponding하는 code units와 "+""/"를 elements로 가지는 String입니다.

  1. byteSequencechunk를 base64로 decoding하여 resulting되는 unique sequence of 3 bytes로 둔다(즉, byteSequenceRFC 4648의 section 4에 specified된 base64 encoding을 applying하면 chunk를 produce하게 되는 sequence).
  2. elements가 byteSequence의 elements인 List를 order대로 반환한다.

23.3.3.7 FromBase64 ( string, alphabet, lastChunkHandling [ , maxLength ] )

The abstract operation FromBase64 takes arguments string (a String), alphabet ("base64" or "base64url"), and lastChunkHandling ("loose", "strict", or "stop-before-partial") and optional argument maxLength (a non-negative integer) and returns a Record with fields [[Read]] (an integer), [[Bytes]] (a List of byte values), and [[Error]] (a SyntaxError object or none). It performs the following steps when called:

  1. maxLength가 present하지 않으면, 다음을 수행한다.
    1. maxLength를 253 - 1로 설정한다.
    2. NOTE: input이 String이므로, Strings의 length는 253 - 1 characters로 limited되고, output은 input이 가진 characters보다 more bytes를 require하지 않으므로, 이 limit에는 never reached될 수 없다. However, maxLengthfinite value를 사용하는 것이 editorially convenient하다.
  2. NOTE: 아래 algorithm에서 validation 및 decoding의 order는 observable하지 않다. Implementations는 validation을 decoding과 interleaving할 수도 있으며, 가장 efficient한 any order로 them을 수행하도록 encouraged된다.
  3. maxLength = 0이면, 다음을 수행한다.
    1. Record { [[Read]]: 0, [[Bytes]]: « », [[Error]]: none }를 반환한다.
  4. read를 0으로 둔다.
  5. bytes를 새 empty List로 둔다.
  6. chunk를 empty String으로 둔다.
  7. chunkLength를 0으로 둔다.
  8. index를 0으로 둔다.
  9. lengthstring의 length로 둔다.
  10. Repeat,
    1. Assert: bytes 안의 elements 수는 3으로 evenly divisible된다.
    2. indexSkipAsciiWhitespace(string, index)로 설정한다.
    3. index = length이면, 다음을 수행한다.
      1. chunkLength > 0이면, 다음을 수행한다.
        1. lastChunkHandling"stop-before-partial"이면, 다음을 수행한다.
          1. Record { [[Read]]: read, [[Bytes]]: bytes, [[Error]]: none }를 반환한다.
        2. lastChunkHandling"strict"이면, 다음을 수행한다.
          1. error를 newly created SyntaxError object로 둔다.
          2. Record { [[Read]]: read, [[Bytes]]: bytes, [[Error]]: error }를 반환한다.
        3. Assert: lastChunkHandling"loose"이다.
        4. chunkLength = 1이면, 다음을 수행한다.
          1. error를 newly created SyntaxError object로 둔다.
          2. Record { [[Read]]: read, [[Bytes]]: bytes, [[Error]]: error }를 반환한다.
        5. bytesbytes와 ! DecodeFinalBase64Chunk(chunk, false)의 list-concatenation으로 설정한다.
      2. Record { [[Read]]: length, [[Bytes]]: bytes, [[Error]]: none }를 반환한다.
    4. charstringindex부터 index + 1까지의 substring으로 둔다.
    5. indexindex + 1로 설정한다.
    6. char"="이면, 다음을 수행한다.
      1. chunkLength < 2이면, 다음을 수행한다.
        1. error를 newly created SyntaxError object로 둔다.
        2. Record { [[Read]]: read, [[Bytes]]: bytes, [[Error]]: error }를 반환한다.
      2. indexSkipAsciiWhitespace(string, index)로 설정한다.
      3. chunkLength = 2이면, 다음을 수행한다.
        1. index = length이면, 다음을 수행한다.
          1. lastChunkHandling"stop-before-partial"이면, 다음을 수행한다.
            1. Record { [[Read]]: read, [[Bytes]]: bytes, [[Error]]: none }를 반환한다.
          2. error를 newly created SyntaxError object로 둔다.
          3. Record { [[Read]]: read, [[Bytes]]: bytes, [[Error]]: error }를 반환한다.
        2. charstringindex부터 index + 1까지의 substring으로 설정한다.
        3. char"="이면, 다음을 수행한다.
          1. indexSkipAsciiWhitespace(string, index + 1)로 설정한다.
      4. index < length이면, 다음을 수행한다.
        1. error를 newly created SyntaxError object로 둔다.
        2. Record { [[Read]]: read, [[Bytes]]: bytes, [[Error]]: error }를 반환한다.
      5. lastChunkHandling"strict"이면 throwOnExtraBitstrue로 둔다; else throwOnExtraBitsfalse로 둔다.
      6. decodeResultCompletion(DecodeFinalBase64Chunk(chunk, throwOnExtraBits))로 둔다.
      7. decodeResultabrupt completion이면, 다음을 수행한다.
        1. errordecodeResult.[[Value]]로 둔다.
        2. Record { [[Read]]: read, [[Bytes]]: bytes, [[Error]]: error }를 반환한다.
      8. bytesbytes와 ! decodeResultlist-concatenation으로 설정한다.
      9. Record { [[Read]]: length, [[Bytes]]: bytes, [[Error]]: none }를 반환한다.
    7. alphabet"base64url"이면, 다음을 수행한다.
      1. char"+" 또는 "/" 중 하나이면, 다음을 수행한다.
        1. error를 newly created SyntaxError object로 둔다.
        2. Record { [[Read]]: read, [[Bytes]]: bytes, [[Error]]: error }를 반환한다.
      2. Else if char"-"이면, 다음을 수행한다.
        1. char"+"로 설정한다.
      3. Else if char"_"이면, 다음을 수행한다.
        1. char"/"로 설정한다.
    8. char의 sole code unit이 standard base64 alphabet의 element가 아니면, 다음을 수행한다.
      1. error를 newly created SyntaxError object로 둔다.
      2. Record { [[Read]]: read, [[Bytes]]: bytes, [[Error]]: error }를 반환한다.
    9. remainingmaxLength - bytes 안의 elements 수로 둔다.
    10. remaining = 1이고 chunkLength = 2이면, 또는 remaining = 2이고 chunkLength = 3이면, 다음을 수행한다.
      1. Record { [[Read]]: read, [[Bytes]]: bytes, [[Error]]: none }를 반환한다.
    11. chunkchunkcharstring-concatenation으로 설정한다.
    12. chunkLengthchunk의 length로 설정한다.
    13. chunkLength = 4이면, 다음을 수행한다.
      1. bytesbytesDecodeFullLengthBase64Chunk(chunk)의 list-concatenation으로 설정한다.
      2. chunk를 empty String으로 설정한다.
      3. chunkLength를 0으로 설정한다.
      4. readindex로 설정한다.
      5. bytes 안의 elements 수 = maxLength이면, 다음을 수행한다.
        1. Record { [[Read]]: read, [[Bytes]]: bytes, [[Error]]: none }를 반환한다.

23.3.3.8 FromHex ( string [ , maxLength ] )

The abstract operation FromHex takes argument string (a String) and optional argument maxLength (a non-negative integer) and returns a Record with fields [[Read]] (an integer), [[Bytes]] (a List of byte values), and [[Error]] (a SyntaxError object or none). It performs the following steps when called:

  1. maxLength가 present하지 않으면, maxLength를 253 - 1로 설정한다.
  2. lengthstring의 length로 둔다.
  3. bytes를 새 empty List로 둔다.
  4. read를 0으로 둔다.
  5. length modulo 2 ≠ 0이면, 다음을 수행한다.
    1. error를 newly created SyntaxError object로 둔다.
    2. Record { [[Read]]: read, [[Bytes]]: bytes, [[Error]]: error }를 반환한다.
  6. Repeat, while read < length and the number of elements in bytes < maxLength,
    1. hexitsstringread부터 read + 2까지의 substring으로 둔다.
    2. hexits"0123456789abcdefABCDEF" 안에 있지 않은 any code units를 contain하면, 다음을 수행한다.
      1. error를 newly created SyntaxError object로 둔다.
      2. Record { [[Read]]: read, [[Bytes]]: bytes, [[Error]]: error }를 반환한다.
    3. readread + 2로 설정한다.
    4. byte를 values 10부터 15까지의 digits에 대해 letters A through Fa through f를 사용하여, base-16 notation에서 hexits가 represented하는 integer value로 둔다.
    5. bytebytes에 append한다.
  7. Record { [[Read]]: read, [[Bytes]]: bytes, [[Error]]: none }를 반환한다.

24 Keyed Collections

24.1 Map Objects

Maps는 keys와 values 모두 arbitrary ECMAScript language values일 수 있는 key/value pairs의 collections입니다. distinct key value는 Map의 collection 안에서 하나의 key/value pair에만 occur할 수 있습니다. Distinct key values는 SameValueZero comparison algorithm의 semantics를 사용하여 discriminated됩니다.

Maps는 collection 안의 elements 수에 대해 average로 sublinear인 access times를 제공하는 hash tables 또는 other mechanisms를 사용하여 implemented되어야 합니다. 이 specification에서 사용되는 data structure는 Maps의 required observable semantics를 describe하기 위한 것일 뿐입니다. viable implementation model로 intended되지 않습니다.

24.1.1 The Map Constructor

Map constructor는:

  • %Map%입니다.
  • global object"Map" property의 initial value입니다.
  • constructor로 called될 때 new Map을 create하고 initialize합니다.
  • function으로 called되도록 intended되지 않으며, such manner로 called될 때 exception을 throw합니다.
  • 클래스 정의의 extends 절의 값으로 사용될 수 있다. 지정된 Map 동작을 상속하려는 서브클래스 생성자는 Map.prototype의 내장 메서드를 지원하는 데 필요한 내부 상태로 서브클래스 인스턴스를 생성하고 초기화하기 위해 Map 생성자에 대한 super 호출을 포함해야 한다.

24.1.1.1 Map ( [ iterable ] )

이 function은 called될 때 다음 steps를 수행합니다:

  1. NewTarget이 undefined이면, TypeError exception을 throw한다.
  2. map을 ? OrdinaryCreateFromConstructor(NewTarget, "%Map.prototype%", « [[MapData]] »)로 둔다.
  3. map.[[MapData]]를 새 empty List로 설정한다.
  4. iterableundefined 또는 null 중 하나이면, map을 반환한다.
  5. adder를 ? Get(map, "set")로 둔다.
  6. IsCallable(adder)가 false이면, TypeError exception을 throw한다.
  7. AddEntriesFromIterable(map, iterable, adder)를 반환한다.
Note

parameter iterable이 present하면, 이는 two element array-like object를 produce하는 iterator object를 반환하는 %Symbol.iterator% method를 implement하는 object일 것으로 expected됩니다. 그 first element는 Map key로 사용될 value이고 second element는 그 key와 associate할 value입니다.

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. addertarget을 receiver로 하여 invoked됩니다. It performs the following steps when called:

  1. iteratorRecord를 ? GetIterator(iterable, sync)로 둔다.
  2. Repeat,
    1. next를 ? IteratorStepValue(iteratorRecord)로 둔다.
    2. nextdone이면, target을 반환한다.
    3. next가 Object가 아니면, 다음을 수행한다.
      1. errorThrowCompletion(a newly created TypeError object)로 둔다.
      2. IteratorClose(iteratorRecord, error)를 반환한다.
    4. keyCompletion(Get(next, "0")))로 둔다.
    5. IfAbruptCloseIterator(key, iteratorRecord).
    6. valueCompletion(Get(next, "1")))로 둔다.
    7. IfAbruptCloseIterator(value, iteratorRecord).
    8. statusCompletion(Call(adder, target, « key, value »))로 둔다.
    9. IfAbruptCloseIterator(status, iteratorRecord).
Note

parameter iterable은 two element array-like object를 produce하는 iterator object를 반환하는 %Symbol.iterator% method를 implement하는 object일 것으로 expected됩니다. 그 first element는 Map key로 사용될 value이고 second element는 그 key와 associate할 value입니다.

24.1.2 Properties of the Map Constructor

Map constructor는:

  • value가 %Function.prototype%[[Prototype]] internal slot을 가집니다.
  • 다음 properties를 가집니다:

24.1.2.1 Map.groupBy ( items, callback )

Note

callback은 two arguments를 accept하는 function이어야 합니다. groupByitems 안의 각 element에 대해 ascending order로 callback을 한 번씩 calls하고, new Map을 constructs합니다. callback에 의해 returned되는 each value는 Map 안의 key로 사용됩니다. such key마다, result Map은 key가 that key이고 value가 callback이 that key를 returned한 all elements를 containing하는 array인 entry를 가집니다.

callback은 two arguments, 즉 element의 value와 element의 index로 called됩니다.

groupBy의 return value는 Map입니다.

이 function은 called될 때 다음 steps를 수행합니다:

  1. groups를 ? GroupBy(items, callback, collection)로 둔다.
  2. map을 ! Construct(%Map%)로 둔다.
  3. groups의 각 Record { [[Key]], [[Elements]] } group에 대해, 다음을 수행한다.
    1. elementsCreateArrayFromList(group.[[Elements]])로 둔다.
    2. entryRecord { [[Key]]: group.[[Key]], [[Value]]: elements }로 둔다.
    3. entrymap.[[MapData]]에 append한다.
  4. map을 반환한다.

24.1.2.2 Map.prototype

Map.prototype의 initial value는 Map prototype object입니다.

이 property는 attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }를 가집니다.

24.1.2.3 get Map [ %Symbol.species% ]

Map[%Symbol.species%]는 set accessor function이 undefinedaccessor property입니다. Its get accessor function은 called될 때 다음 steps를 수행합니다:

  1. this value를 반환한다.

이 function의 "name" property의 value는 "get [Symbol.species]"입니다.

Note

derived collection objects를 create하는 methods는 derived objects를 create하는 데 사용할 constructor를 determine하기 위해 %Symbol.species%를 call해야 합니다. Subclass constructor는 default constructor assignment를 change하기 위해 %Symbol.species%를 over-ride할 수 있습니다.

24.1.3 Properties of the Map Prototype Object

Map prototype object는:

  • %Map.prototype%입니다.
  • value가 %Object.prototype%[[Prototype]] internal slot을 가집니다.
  • ordinary object입니다.
  • [[MapData]] internal slot을 가지지 않습니다.

24.1.3.1 Map.prototype.clear ( )

이 method는 called될 때 다음 steps를 수행합니다:

  1. mapthis value로 둔다.
  2. RequireInternalSlot(map, [[MapData]])를 수행한다.
  3. map.[[MapData]]의 각 Record { [[Key]], [[Value]] } entry에 대해, 다음을 수행한다.
    1. entry.[[Key]]empty로 설정한다.
    2. entry.[[Value]]empty로 설정한다.
  4. undefined를 반환한다.
Note

that List를 iterating하는 중간에 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는 called될 때 다음 steps를 수행합니다:

  1. mapthis value로 둔다.
  2. RequireInternalSlot(map, [[MapData]])를 수행한다.
  3. keyCanonicalizeKeyedCollectionKey(key)로 설정한다.
  4. map.[[MapData]]의 각 Record { [[Key]], [[Value]] } entry에 대해, 다음을 수행한다.
    1. entry.[[Key]]empty가 아니고 SameValue(entry.[[Key]], key)가 true이면, 다음을 수행한다.
      1. entry.[[Key]]empty로 설정한다.
      2. entry.[[Value]]empty로 설정한다.
      3. true를 반환한다.
  5. false를 반환한다.
Note

value empty는 entry가 deleted되었음을 indicate하기 위한 specification device로 사용됩니다. Actual implementations는 internal data structures에서 entry를 physically removing하는 것과 같은 other actions를 취할 수 있습니다.

24.1.3.4 Map.prototype.entries ( )

이 method는 called될 때 다음 steps를 수행합니다:

  1. mapthis value로 둔다.
  2. CreateMapIterator(map, key+value)를 반환한다.

24.1.3.5 Map.prototype.forEach ( callback [ , thisArg ] )

이 method는 called될 때 다음 steps를 수행합니다:

  1. mapthis value로 둔다.
  2. RequireInternalSlot(map, [[MapData]])를 수행한다.
  3. IsCallable(callback)가 false이면, TypeError exception을 throw한다.
  4. entriesmap.[[MapData]]로 둔다.
  5. entriesCountentries 안의 elements 수로 둔다.
  6. index를 0으로 둔다.
  7. Repeat, while index < entriesCount,
    1. entryentries[index]로 둔다.
    2. indexindex + 1로 설정한다.
    3. entry.[[Key]]empty가 아니면, 다음을 수행한다.
      1. Call(callback, thisArg, « entry.[[Value]], entry.[[Key]], map »)를 수행한다.
      2. NOTE: entries 안의 elements 수는 callback의 execution 동안 increased되었을 수 있다.
      3. entriesCountentries 안의 elements 수로 설정한다.
  8. undefined를 반환한다.
Note

callback은 three arguments를 accept하는 function이어야 합니다. forEach는 Map 안에 present한 each key/value pair에 대해 key insertion order로 callback을 한 번씩 calls합니다. callback은 actually exist하는 Map의 keys에 대해서만 called되며, Map에서 deleted된 keys에 대해서는 called되지 않습니다.

thisArg parameter가 provided되면, callback의 each invocation에서 this value로 사용됩니다. provided되지 않으면, 대신 undefined가 사용됩니다.

callback은 three arguments, 즉 item의 value, item의 key, 그리고 traversed되는 Map으로 called됩니다.

forEach는 called된 object를 directly mutate하지 않지만, object는 callback calls에 의해 mutated될 수 있습니다. map의 [[MapData]]의 each entry는 한 번만 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가 again added되지 않는 한 visited되지 않습니다.

24.1.3.6 Map.prototype.get ( key )

이 method는 called될 때 다음 steps를 수행합니다:

  1. mapthis value로 둔다.
  2. RequireInternalSlot(map, [[MapData]])를 수행한다.
  3. keyCanonicalizeKeyedCollectionKey(key)로 설정한다.
  4. map.[[MapData]]의 각 Record { [[Key]], [[Value]] } entry에 대해, 다음을 수행한다.
    1. entry.[[Key]]empty가 아니고 SameValue(entry.[[Key]], key)가 true이면, entry.[[Value]]를 반환한다.
  5. undefined를 반환한다.

24.1.3.7 Map.prototype.getOrInsert ( key, value )

이 method는 called될 때 다음 steps를 수행합니다:

  1. mapthis value로 둔다.
  2. RequireInternalSlot(map, [[MapData]])를 수행한다.
  3. keyCanonicalizeKeyedCollectionKey(key)로 설정한다.
  4. map.[[MapData]]의 각 Record { [[Key]], [[Value]] } entry에 대해, 다음을 수행한다.
    1. entry.[[Key]]empty가 아니고 SameValue(entry.[[Key]], key)가 true이면, entry.[[Value]]를 반환한다.
  5. entryRecord { [[Key]]: key, [[Value]]: value }로 둔다.
  6. entrymap.[[MapData]]에 append한다.
  7. value를 반환한다.

24.1.3.8 Map.prototype.getOrInsertComputed ( key, callback )

이 method는 called될 때 다음 steps를 수행합니다:

  1. mapthis value로 둔다.
  2. RequireInternalSlot(map, [[MapData]])를 수행한다.
  3. IsCallable(callback)가 false이면, TypeError exception을 throw한다.
  4. keyCanonicalizeKeyedCollectionKey(key)로 설정한다.
  5. map.[[MapData]]의 각 Record { [[Key]], [[Value]] } entry에 대해, 다음을 수행한다.
    1. entry.[[Key]]empty가 아니고 SameValue(entry.[[Key]], key)가 true이면, entry.[[Value]]를 반환한다.
  6. value를 ? Call(callback, undefined, « key »)로 둔다.
  7. NOTE: Map은 callback의 execution 동안 modified되었을 수 있다.
  8. map.[[MapData]]의 각 Record { [[Key]], [[Value]] } entry에 대해, 다음을 수행한다.
    1. entry.[[Key]]empty가 아니고 SameValue(entry.[[Key]], key)가 true이면, 다음을 수행한다.
      1. entry.[[Value]]value로 설정한다.
      2. value를 반환한다.
  9. entryRecord { [[Key]]: key, [[Value]]: value }로 둔다.
  10. entrymap.[[MapData]]에 append한다.
  11. value를 반환한다.

24.1.3.9 Map.prototype.has ( key )

이 method는 called될 때 다음 steps를 수행합니다:

  1. mapthis value로 둔다.
  2. RequireInternalSlot(map, [[MapData]])를 수행한다.
  3. keyCanonicalizeKeyedCollectionKey(key)로 설정한다.
  4. map.[[MapData]]의 각 Record { [[Key]], [[Value]] } entry에 대해, 다음을 수행한다.
    1. entry.[[Key]]empty가 아니고 SameValue(entry.[[Key]], key)가 true이면, true를 반환한다.
  5. false를 반환한다.

24.1.3.10 Map.prototype.keys ( )

이 method는 called될 때 다음 steps를 수행합니다:

  1. mapthis value로 둔다.
  2. CreateMapIterator(map, key)를 반환한다.

24.1.3.11 Map.prototype.set ( key, value )

이 method는 called될 때 다음 steps를 수행합니다:

  1. mapthis value로 둔다.
  2. RequireInternalSlot(map, [[MapData]])를 수행한다.
  3. keyCanonicalizeKeyedCollectionKey(key)로 설정한다.
  4. map.[[MapData]]의 각 Record { [[Key]], [[Value]] } entry에 대해, 다음을 수행한다.
    1. entry.[[Key]]empty가 아니고 SameValue(entry.[[Key]], key)가 true이면, 다음을 수행한다.
      1. entry.[[Value]]value로 설정한다.
      2. map을 반환한다.
  5. entryRecord { [[Key]]: key, [[Value]]: value }로 둔다.
  6. entrymap.[[MapData]]에 append한다.
  7. map을 반환한다.

24.1.3.12 get Map.prototype.size

Map.prototype.size는 set accessor function이 undefinedaccessor property입니다. Its get accessor function은 called될 때 다음 steps를 수행합니다:

  1. mapthis value로 둔다.
  2. RequireInternalSlot(map, [[MapData]])를 수행한다.
  3. count를 0으로 둔다.
  4. map.[[MapData]]의 각 Record { [[Key]], [[Value]] } entry에 대해, 다음을 수행한다.
    1. entry.[[Key]]empty가 아니면, countcount + 1로 설정한다.
  5. 𝔽(count)를 반환한다.

24.1.3.13 Map.prototype.values ( )

이 method는 called될 때 다음 steps를 수행합니다:

  1. mapthis value로 둔다.
  2. CreateMapIterator(map, value)를 반환한다.

24.1.3.14 Map.prototype [ %Symbol.iterator% ] ( )

%Symbol.iterator% property의 initial value는 24.1.3.4에 defined된 %Map.prototype.entries%입니다.

24.1.3.15 Map.prototype [ %Symbol.toStringTag% ]

%Symbol.toStringTag% property의 initial value는 String value "Map"입니다.

이 property는 attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }를 가집니다.

24.1.4 Properties of Map Instances

Map instances는 Map prototype object로부터 properties를 inherit하는 ordinary objects입니다. Map instances는 또한 [[MapData]] internal slot을 가집니다.

24.1.5 Map Iterator Objects

Map Iterator는 some specific Map instance object에 대한 specific iteration을 represents하는 object입니다. Map Iterator objects에 대한 named constructor는 없습니다. Instead, 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. such iterators를 return하는 Map methods용 iterator objects를 create하는 데 사용됩니다. It performs the following steps when called:

  1. RequireInternalSlot(map, [[MapData]])를 수행한다.
  2. mapkind를 capture하고 called될 때 다음 steps를 수행하는, parameters가 없는 새 Abstract Closure closure를 둔다:
    1. entriesmap.[[MapData]]로 둔다.
    2. index를 0으로 둔다.
    3. entriesCountentries 안의 elements 수로 둔다.
    4. Repeat, while index < entriesCount,
      1. entryentries[index]로 둔다.
      2. indexindex + 1로 설정한다.
      3. entry.[[Key]]empty가 아니면, 다음을 수행한다.
        1. kindkey이면, 다음을 수행한다.
          1. resultentry.[[Key]]로 둔다.
        2. Else if kindvalue이면, 다음을 수행한다.
          1. resultentry.[[Value]]로 둔다.
        3. Else,
          1. Assert: kindkey+value이다.
          2. resultCreateArrayFromListentry.[[Key]], entry.[[Value]] »)로 둔다.
        4. GeneratorYield(CreateIteratorResultObject(result, false))를 수행한다.
        5. NOTE: 이 abstract operation의 execution이 GeneratorYield에 의해 paused된 동안 entries 안의 elements 수가 increased되었을 수 있다.
        6. entriesCountentries 안의 elements 수로 설정한다.
    5. NormalCompletion(unused)을 반환한다.
  3. CreateIteratorFromClosure(closure, "%MapIteratorPrototype%", %MapIteratorPrototype%)를 반환한다.

24.1.5.2 The %MapIteratorPrototype% Object

%MapIteratorPrototype% object는:

24.1.5.2.1 %MapIteratorPrototype%.next ( )

  1. GeneratorResume(this value, empty, "%MapIteratorPrototype%")를 반환한다.

24.1.5.2.2 %MapIteratorPrototype% [ %Symbol.toStringTag% ]

%Symbol.toStringTag% property의 initial value는 String value "Map Iterator"입니다.

이 property는 attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }를 가집니다.

24.2 Set Objects

Set objectsECMAScript language values의 collections입니다. Set은 each distinct value를 at most once contain할 수 있습니다. Distinct values는 SameValueZero comparison algorithm의 semantics를 사용하여 discriminated됩니다.

Set objects는 collection 안의 elements 수에 대해 average로 sublinear인 access times를 제공하는 hash tables 또는 other mechanisms를 사용하여 implemented되어야 합니다. 이 specification에서 사용되는 data structure는 Set objects의 required observable semantics를 describe하기 위한 것일 뿐입니다. viable implementation model로 intended되지 않습니다.

24.2.1 Abstract Operations For Set Objects

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]] an Object Set 또는 similar object입니다.
[[Size]] a non-negative integer or +∞ object의 reported size입니다.
[[Has]] a function object object의 has method입니다.
[[Keys]] a function object object의 keys method입니다.

24.2.1.2 GetSetRecord ( obj )

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

  1. obj가 Object가 아니면, TypeError exception을 throw한다.
  2. rawSize를 ? Get(obj, "size")로 둔다.
  3. numberSize를 ? ToNumber(rawSize)로 둔다.
  4. NOTE: rawSizeundefined이면, numberSizeNaN이 된다.
  5. numberSizeNaN이면, TypeError exception을 throw한다.
  6. intSize를 ! ToIntegerOrInfinity(numberSize)로 둔다.
  7. intSize < 0이면, RangeError exception을 throw한다.
  8. has를 ? Get(obj, "has")로 둔다.
  9. IsCallable(has)가 false이면, TypeError exception을 throw한다.
  10. keys를 ? Get(obj, "keys")로 둔다.
  11. IsCallable(keys)가 false이면, TypeError exception을 throw한다.
  12. new Set Record { [[SetObject]]: obj, [[Size]]: intSize, [[Has]]: has, [[Keys]]: keys }를 반환한다.

24.2.1.3 SetDataHas ( setData, value )

The abstract operation SetDataHas takes arguments setData (a List of either ECMAScript language values or empty) and value (an ECMAScript language value) and returns a Boolean. It performs the following steps when called:

  1. SetDataIndex(setData, value)가 not-found이면, false를 반환한다.
  2. true를 반환한다.

24.2.1.4 SetDataIndex ( setData, value )

The abstract operation SetDataIndex takes arguments setData (a List of either ECMAScript language values or empty) and value (an ECMAScript language value) and returns a non-negative integer or not-found. It performs the following steps when called:

  1. valueCanonicalizeKeyedCollectionKey(value)로 설정한다.
  2. sizesetData 안의 elements 수로 둔다.
  3. index를 0으로 둔다.
  4. Repeat, while index < size,
    1. elementsetData[index]로 둔다.
    2. elementempty가 아니고 elementvalue이면, 다음을 수행한다.
      1. index를 반환한다.
    3. indexindex + 1로 설정한다.
  5. not-found를 반환한다.

24.2.1.5 SetDataSize ( setData )

The abstract operation SetDataSize takes argument setData (a List of either ECMAScript language values or empty) and returns a non-negative integer. It performs the following steps when called:

  1. count를 0으로 둔다.
  2. setData의 각 element element에 대해, 다음을 수행한다.
    1. elementempty가 아니면, countcount + 1로 설정한다.
  3. count를 반환한다.

24.2.2 The Set Constructor

Set constructor는:

  • %Set%입니다.
  • global object"Set" property의 initial value입니다.
  • constructor로 called될 때 new Set object를 create하고 initialize합니다.
  • function으로 called되도록 intended되지 않으며, such manner로 called될 때 exception을 throw합니다.
  • 클래스 정의의 extends 절의 값으로 사용될 수 있다. 지정된 Set 동작을 상속하려는 서브클래스 생성자는 Set.prototype의 내장 메서드를 지원하는 데 필요한 내부 상태로 서브클래스 인스턴스를 생성하고 초기화하기 위해 Set 생성자에 대한 super 호출을 포함해야 한다.

24.2.2.1 Set ( [ iterable ] )

이 function은 called될 때 다음 steps를 수행합니다:

  1. NewTarget이 undefined이면, TypeError exception을 throw한다.
  2. set을 ? OrdinaryCreateFromConstructor(NewTarget, "%Set.prototype%", « [[SetData]] »)로 둔다.
  3. set.[[SetData]]를 새 empty List로 설정한다.
  4. iterableundefined 또는 null 중 하나이면, set을 반환한다.
  5. adder를 ? Get(set, "add")로 둔다.
  6. IsCallable(adder)가 false이면, TypeError exception을 throw한다.
  7. iteratorRecord를 ? GetIterator(iterable, sync)로 둔다.
  8. Repeat,
    1. next를 ? IteratorStepValue(iteratorRecord)로 둔다.
    2. nextdone이면, set을 반환한다.
    3. statusCompletion(Call(adder, set, « next »))로 둔다.
    4. IfAbruptCloseIterator(status, iteratorRecord).

24.2.3 Properties of the Set Constructor

Set constructor는:

  • value가 %Function.prototype%[[Prototype]] internal slot을 가집니다.
  • 다음 properties를 가집니다:

24.2.3.1 Set.prototype

Set.prototype의 initial value는 Set prototype object입니다.

이 property는 attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }를 가집니다.

24.2.3.2 get Set [ %Symbol.species% ]

Set[%Symbol.species%]는 set accessor function이 undefinedaccessor property입니다. Its get accessor function은 called될 때 다음 steps를 수행합니다:

  1. this value를 반환한다.

이 function의 "name" property의 value는 "get [Symbol.species]"입니다.

Note

derived collection objects를 create하는 methods는 derived objects를 create하는 데 사용할 constructor를 determine하기 위해 %Symbol.species%를 call해야 합니다. Subclass constructor는 default constructor assignment를 change하기 위해 %Symbol.species%를 over-ride할 수 있습니다.

24.2.4 Properties of the Set Prototype Object

Set prototype object는:

  • %Set.prototype%입니다.
  • value가 %Object.prototype%[[Prototype]] internal slot을 가집니다.
  • ordinary object입니다.
  • [[SetData]] internal slot을 가지지 않습니다.

24.2.4.1 Set.prototype.add ( value )

이 method는 called될 때 다음 steps를 수행합니다:

  1. setthis value로 둔다.
  2. RequireInternalSlot(set, [[SetData]])를 수행한다.
  3. valueCanonicalizeKeyedCollectionKey(value)로 설정한다.
  4. set.[[SetData]]의 각 element entry에 대해, 다음을 수행한다.
    1. entryempty가 아니고 SameValue(entry, value)가 true이면, 다음을 수행한다.
      1. set을 반환한다.
  5. valueset.[[SetData]]에 append한다.
  6. set을 반환한다.

24.2.4.2 Set.prototype.clear ( )

이 method는 called될 때 다음 steps를 수행합니다:

  1. setthis value로 둔다.
  2. RequireInternalSlot(set, [[SetData]])를 수행한다.
  3. set.[[SetData]]의 각 element entry에 대해, 다음을 수행한다.
    1. value가 entryset.[[SetData]]의 element를 value가 empty인 element로 replace한다.
  4. undefined를 반환한다.
Note

that List를 iterating하는 중간에 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는 called될 때 다음 steps를 수행합니다:

  1. setthis value로 둔다.
  2. RequireInternalSlot(set, [[SetData]])를 수행한다.
  3. valueCanonicalizeKeyedCollectionKey(value)로 설정한다.
  4. set.[[SetData]]의 각 element entry에 대해, 다음을 수행한다.
    1. entryempty가 아니고 SameValue(entry, value)가 true이면, 다음을 수행한다.
      1. value가 entryset.[[SetData]]의 element를 value가 empty인 element로 replace한다.
      2. true를 반환한다.
  5. false를 반환한다.
Note

value empty는 entry가 deleted되었음을 indicate하기 위한 specification device로 사용됩니다. Actual implementations는 internal data structures에서 entry를 physically removing하는 것과 같은 other actions를 취할 수 있습니다.

24.2.4.5 Set.prototype.difference ( other )

이 method는 called될 때 다음 steps를 수행합니다:

  1. setthis value로 둔다.
  2. RequireInternalSlot(set, [[SetData]])를 수행한다.
  3. otherRecord를 ? GetSetRecord(other)로 둔다.
  4. resultSetDataset.[[SetData]]의 copy로 둔다.
  5. SetDataSize(set.[[SetData]]) ≤ otherRecord.[[Size]]이면, 다음을 수행한다.
    1. thisSizeset.[[SetData]] 안의 elements 수로 둔다.
    2. index를 0으로 둔다.
    3. Repeat, while index < thisSize,
      1. entryresultSetData[index]로 둔다.
      2. entryempty가 아니면, 다음을 수행한다.
        1. inOtherToBoolean(? Call(otherRecord.[[Has]], otherRecord.[[SetObject]], « entry »))로 둔다.
        2. inOthertrue이면, 다음을 수행한다.
          1. resultSetData[index]를 empty로 설정한다.
      3. indexindex + 1로 설정한다.
  6. Else,
    1. keysIterator를 ? GetIteratorFromMethod(otherRecord.[[SetObject]], otherRecord.[[Keys]])로 둔다.
    2. nextnot-started로 둔다.
    3. Repeat, while nextdone이 아니면,
      1. next를 ? IteratorStepValue(keysIterator)로 설정한다.
      2. nextdone이 아니면, 다음을 수행한다.
        1. nextCanonicalizeKeyedCollectionKey(next)로 설정한다.
        2. valueIndexSetDataIndex(resultSetData, next)로 둔다.
        3. valueIndexnot-found가 아니면, 다음을 수행한다.
          1. resultSetData[valueIndex]를 empty로 설정한다.
  7. resultOrdinaryObjectCreate(%Set.prototype%, « [[SetData]] »)로 둔다.
  8. result.[[SetData]]resultSetData로 설정한다.
  9. result를 반환한다.

24.2.4.6 Set.prototype.entries ( )

이 method는 called될 때 다음 steps를 수행합니다:

  1. setthis value로 둔다.
  2. CreateSetIterator(set, key+value)를 반환한다.
Note

iteration purposes에서는, Set은 each entry가 its key와 value에 대해 same value를 가지는 Map과 similar하게 appears합니다.

24.2.4.7 Set.prototype.forEach ( callback [ , thisArg ] )

이 method는 called될 때 다음 steps를 수행합니다:

  1. setthis value로 둔다.
  2. RequireInternalSlot(set, [[SetData]])를 수행한다.
  3. IsCallable(callback)가 false이면, TypeError exception을 throw한다.
  4. entriesset.[[SetData]]로 둔다.
  5. entriesCountentries 안의 elements 수로 둔다.
  6. index를 0으로 둔다.
  7. Repeat, while index < entriesCount,
    1. entryentries[index]로 둔다.
    2. indexindex + 1로 설정한다.
    3. entryempty가 아니면, 다음을 수행한다.
      1. Call(callback, thisArg, « entry, entry, set »)를 수행한다.
      2. NOTE: entries 안의 elements 수는 callback의 execution 동안 increased되었을 수 있다.
      3. entriesCountentries 안의 elements 수로 설정한다.
  8. undefined를 반환한다.
Note

callback은 three arguments를 accept하는 function이어야 합니다. forEachSet object 안에 present한 each value에 대해 value insertion order로 callback을 한 번씩 calls합니다. callback은 actually exist하는 Set의 values에 대해서만 called되며, set에서 deleted된 keys에 대해서는 called되지 않습니다.

thisArg parameter가 provided되면, callback의 each invocation에서 this value로 사용됩니다. provided되지 않으면, 대신 undefined가 사용됩니다.

callback은 three arguments로 called됩니다: first two arguments는 Set 안에 contained된 value입니다. same value가 both arguments로 passed됩니다. traversed되는 Set object는 third argument로 passed됩니다.

callback은 Map 및 Array용 forEach methods가 사용하는 call back functions와 consistent하기 위해 three arguments로 called됩니다. Sets에서는 each item value가 key이자 value인 것으로 considered됩니다.

forEach는 called된 object를 directly mutate하지 않지만, object는 callback calls에 의해 mutated될 수 있습니다.

Each value는 normally 한 번만 visited됩니다. However, value가 visited된 후 deleted되고 forEach call이 completes되기 전에 re-added되면 value는 revisited됩니다. forEach call이 begins된 후 visited되기 전에 deleted된 values는, forEach call이 completes되기 전에 value가 again added되지 않는 한 visited되지 않습니다. forEach call이 begins된 후 added된 new values는 visited됩니다.

24.2.4.8 Set.prototype.has ( value )

이 method는 called될 때 다음 steps를 수행합니다:

  1. setthis value로 둔다.
  2. RequireInternalSlot(set, [[SetData]])를 수행한다.
  3. valueCanonicalizeKeyedCollectionKey(value)로 설정한다.
  4. set.[[SetData]]의 각 element entry에 대해, 다음을 수행한다.
    1. entryempty가 아니고 SameValue(entry, value)가 true이면, true를 반환한다.
  5. false를 반환한다.

24.2.4.9 Set.prototype.intersection ( other )

이 method는 called될 때 다음 steps를 수행합니다:

  1. setthis value로 둔다.
  2. RequireInternalSlot(set, [[SetData]])를 수행한다.
  3. otherRecord를 ? GetSetRecord(other)로 둔다.
  4. resultSetData를 새 empty List로 둔다.
  5. SetDataSize(set.[[SetData]]) ≤ otherRecord.[[Size]]이면, 다음을 수행한다.
    1. thisSizeset.[[SetData]] 안의 elements 수로 둔다.
    2. index를 0으로 둔다.
    3. Repeat, while index < thisSize,
      1. entryset.[[SetData]][index]로 둔다.
      2. indexindex + 1로 설정한다.
      3. entryempty가 아니면, 다음을 수행한다.
        1. inOtherToBoolean(? Call(otherRecord.[[Has]], otherRecord.[[SetObject]], « entry »))로 둔다.
        2. inOthertrue이면, 다음을 수행한다.
          1. NOTE: otherRecord.[[Has]]에 대한 earlier calls가 set.[[SetData]]의 element를 remove하고 re-add할 수 있으며, 이로 인해 same element가 이 iteration 동안 twice visited될 수 있다.
          2. SetDataHas(resultSetData, entry)가 false이면, 다음을 수행한다.
            1. entryresultSetData에 append한다.
        3. NOTE: set.[[SetData]] 안의 elements 수는 otherRecord.[[Has]]의 execution 동안 increased되었을 수 있다.
        4. thisSizeset.[[SetData]] 안의 elements 수로 설정한다.
  6. Else,
    1. keysIterator를 ? GetIteratorFromMethod(otherRecord.[[SetObject]], otherRecord.[[Keys]])로 둔다.
    2. nextnot-started로 둔다.
    3. Repeat, while nextdone이 아니면,
      1. next를 ? IteratorStepValue(keysIterator)로 설정한다.
      2. nextdone이 아니면, 다음을 수행한다.
        1. nextCanonicalizeKeyedCollectionKey(next)로 설정한다.
        2. inThisSetDataHas(set.[[SetData]], next)로 둔다.
        3. inThistrue이면, 다음을 수행한다.
          1. NOTE: other는 arbitrary object이므로, its "keys" iterator가 same value를 more than once produce할 수 있다.
          2. SetDataHas(resultSetData, next)가 false이면, 다음을 수행한다.
            1. nextresultSetData에 append한다.
  7. resultOrdinaryObjectCreate(%Set.prototype%, « [[SetData]] »)로 둔다.
  8. result.[[SetData]]resultSetData로 설정한다.
  9. result를 반환한다.

24.2.4.10 Set.prototype.isDisjointFrom ( other )

이 method는 called될 때 다음 steps를 수행합니다:

  1. setthis value로 둔다.
  2. RequireInternalSlot(set, [[SetData]])를 수행한다.
  3. otherRecord를 ? GetSetRecord(other)로 둔다.
  4. SetDataSize(set.[[SetData]]) ≤ otherRecord.[[Size]]이면, 다음을 수행한다.
    1. thisSizeset.[[SetData]] 안의 elements 수로 둔다.
    2. index를 0으로 둔다.
    3. Repeat, while index < thisSize,
      1. entryset.[[SetData]][index]로 둔다.
      2. indexindex + 1로 설정한다.
      3. entryempty가 아니면, 다음을 수행한다.
        1. inOtherToBoolean(? Call(otherRecord.[[Has]], otherRecord.[[SetObject]], « entry »))로 둔다.
        2. inOthertrue이면, false를 반환한다.
        3. NOTE: set.[[SetData]] 안의 elements 수는 otherRecord.[[Has]]의 execution 동안 increased되었을 수 있다.
        4. thisSizeset.[[SetData]] 안의 elements 수로 설정한다.
  5. Else,
    1. keysIterator를 ? GetIteratorFromMethod(otherRecord.[[SetObject]], otherRecord.[[Keys]])로 둔다.
    2. nextnot-started로 둔다.
    3. Repeat, while nextdone이 아니면,
      1. next를 ? IteratorStepValue(keysIterator)로 설정한다.
      2. nextdone이 아니면, 다음을 수행한다.
        1. SetDataHas(set.[[SetData]], next)가 true이면, 다음을 수행한다.
          1. IteratorClose(keysIterator, NormalCompletion(unused))를 수행한다.
          2. false를 반환한다.
  6. true를 반환한다.

24.2.4.11 Set.prototype.isSubsetOf ( other )

이 method는 called될 때 다음 steps를 수행합니다:

  1. setthis value로 둔다.
  2. RequireInternalSlot(set, [[SetData]])를 수행한다.
  3. otherRecord를 ? GetSetRecord(other)로 둔다.
  4. SetDataSize(set.[[SetData]]) > otherRecord.[[Size]]이면, false를 반환한다.
  5. thisSizeset.[[SetData]] 안의 elements 수로 둔다.
  6. index를 0으로 둔다.
  7. Repeat, while index < thisSize,
    1. entryset.[[SetData]][index]로 둔다.
    2. indexindex + 1로 설정한다.
    3. entryempty가 아니면, 다음을 수행한다.
      1. inOtherToBoolean(? Call(otherRecord.[[Has]], otherRecord.[[SetObject]], « entry »))로 둔다.
      2. inOtherfalse이면, false를 반환한다.
      3. NOTE: set.[[SetData]] 안의 elements 수는 otherRecord.[[Has]]의 execution 동안 increased되었을 수 있다.
      4. thisSizeset.[[SetData]] 안의 elements 수로 설정한다.
  8. true를 반환한다.

24.2.4.12 Set.prototype.isSupersetOf ( other )

이 method는 called될 때 다음 steps를 수행합니다:

  1. setthis value로 둔다.
  2. RequireInternalSlot(set, [[SetData]])를 수행한다.
  3. otherRecord를 ? GetSetRecord(other)로 둔다.
  4. SetDataSize(set.[[SetData]]) < otherRecord.[[Size]]이면, false를 반환한다.
  5. keysIterator를 ? GetIteratorFromMethod(otherRecord.[[SetObject]], otherRecord.[[Keys]])로 둔다.
  6. nextnot-started로 둔다.
  7. Repeat, while nextdone이 아니면,
    1. next를 ? IteratorStepValue(keysIterator)로 설정한다.
    2. nextdone이 아니면, 다음을 수행한다.
      1. SetDataHas(set.[[SetData]], next)가 false이면, 다음을 수행한다.
        1. IteratorClose(keysIterator, NormalCompletion(unused))를 수행한다.
        2. false를 반환한다.
  8. true를 반환한다.

24.2.4.13 Set.prototype.keys ( )

"keys" property의 initial value는 24.2.4.17에 defined된 %Set.prototype.values%입니다.

Note

iteration purposes에서는, Set은 each entry가 its key와 value에 대해 same value를 가지는 Map과 similar하게 appears합니다.

24.2.4.14 get Set.prototype.size

Set.prototype.size는 set accessor function이 undefinedaccessor property입니다. Its get accessor function은 called될 때 다음 steps를 수행합니다:

  1. setthis value로 둔다.
  2. RequireInternalSlot(set, [[SetData]])를 수행한다.
  3. sizeSetDataSize(set.[[SetData]])로 둔다.
  4. 𝔽(size)를 반환한다.

24.2.4.15 Set.prototype.symmetricDifference ( other )

이 method는 called될 때 다음 steps를 수행합니다:

  1. setthis value로 둔다.
  2. RequireInternalSlot(set, [[SetData]])를 수행한다.
  3. otherRecord를 ? GetSetRecord(other)로 둔다.
  4. keysIterator를 ? GetIteratorFromMethod(otherRecord.[[SetObject]], otherRecord.[[Keys]])로 둔다.
  5. resultSetDataset.[[SetData]]의 copy로 둔다.
  6. nextnot-started로 둔다.
  7. Repeat, while nextdone이 아니면,
    1. next를 ? IteratorStepValue(keysIterator)로 설정한다.
    2. nextdone이 아니면, 다음을 수행한다.
      1. nextCanonicalizeKeyedCollectionKey(next)로 설정한다.
      2. resultIndexSetDataIndex(resultSetData, next)로 둔다.
      3. resultIndexnot-found이면 alreadyInResultfalse로 둔다; else alreadyInResulttrue로 둔다.
      4. SetDataHas(set.[[SetData]], next)가 true이면, 다음을 수행한다.
        1. alreadyInResulttrue이면, resultSetData[resultIndex]를 empty로 설정한다.
      5. Else,
        1. alreadyInResultfalse이면, nextresultSetData에 append한다.
  8. resultOrdinaryObjectCreate(%Set.prototype%, « [[SetData]] »)로 둔다.
  9. result.[[SetData]]resultSetData로 설정한다.
  10. result를 반환한다.

24.2.4.16 Set.prototype.union ( other )

이 method는 called될 때 다음 steps를 수행합니다:

  1. setthis value로 둔다.
  2. RequireInternalSlot(set, [[SetData]])를 수행한다.
  3. otherRecord를 ? GetSetRecord(other)로 둔다.
  4. keysIterator를 ? GetIteratorFromMethod(otherRecord.[[SetObject]], otherRecord.[[Keys]])로 둔다.
  5. resultSetDataset.[[SetData]]의 copy로 둔다.
  6. nextnot-started로 둔다.
  7. Repeat, while nextdone이 아니면,
    1. next를 ? IteratorStepValue(keysIterator)로 설정한다.
    2. nextdone이 아니면, 다음을 수행한다.
      1. nextCanonicalizeKeyedCollectionKey(next)로 설정한다.
      2. SetDataHas(resultSetData, next)가 false이면, 다음을 수행한다.
        1. nextresultSetData에 append한다.
  8. resultOrdinaryObjectCreate(%Set.prototype%, « [[SetData]] »)로 둔다.
  9. result.[[SetData]]resultSetData로 설정한다.
  10. result를 반환한다.

24.2.4.17 Set.prototype.values ( )

이 method는 called될 때 다음 steps를 수행합니다:

  1. setthis value로 둔다.
  2. CreateSetIterator(set, value)를 반환한다.

24.2.4.18 Set.prototype [ %Symbol.iterator% ] ( )

%Symbol.iterator% property의 initial value는 24.2.4.17에 defined된 %Set.prototype.values%입니다.

24.2.4.19 Set.prototype [ %Symbol.toStringTag% ]

%Symbol.toStringTag% property의 initial value는 String value "Set"입니다.

이 property는 attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }를 가집니다.

24.2.5 Properties of Set Instances

Set instances는 Set prototype object로부터 properties를 inherit하는 ordinary objects입니다. Set instances는 또한 [[SetData]] internal slot을 가집니다.

24.2.6 Set Iterator Objects

Set Iterator는 below에 defined된 structure를 가진 ordinary object이며, some specific Set instance object에 대한 specific iteration을 represents합니다. Set Iterator objects에 대한 named constructor는 없습니다. Instead, 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. such iterators를 return하는 Set methods용 iterator objects를 create하는 데 사용됩니다. It performs the following steps when called:

  1. RequireInternalSlot(set, [[SetData]])를 수행한다.
  2. setkind를 capture하고 called될 때 다음 steps를 수행하는, parameters가 없는 새 Abstract Closure closure를 둔다:
    1. index를 0으로 둔다.
    2. entriesset.[[SetData]]로 둔다.
    3. entriesCountentries 안의 elements 수로 둔다.
    4. Repeat, while index < entriesCount,
      1. entryentries[index]로 둔다.
      2. indexindex + 1로 설정한다.
      3. entryempty가 아니면, 다음을 수행한다.
        1. kindkey+value이면, 다음을 수행한다.
          1. resultCreateArrayFromListentry, entry »)로 둔다.
          2. GeneratorYield(CreateIteratorResultObject(result, false))를 수행한다.
        2. Else,
          1. Assert: kindvalue이다.
          2. GeneratorYield(CreateIteratorResultObject(entry, false))를 수행한다.
        3. NOTE: 이 abstract operation의 execution이 GeneratorYield에 의해 paused된 동안 entries 안의 elements 수가 increased되었을 수 있다.
        4. entriesCountentries 안의 elements 수로 설정한다.
    5. NormalCompletion(unused)을 반환한다.
  3. CreateIteratorFromClosure(closure, "%SetIteratorPrototype%", %SetIteratorPrototype%)를 반환한다.

24.2.6.2 The %SetIteratorPrototype% Object

%SetIteratorPrototype% object는:

24.2.6.2.1 %SetIteratorPrototype%.next ( )

  1. GeneratorResume(this value, empty, "%SetIteratorPrototype%")를 반환한다.

24.2.6.2.2 %SetIteratorPrototype% [ %Symbol.toStringTag% ]

%Symbol.toStringTag% property의 initial value는 String value "Set Iterator"입니다.

이 property는 attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }를 가집니다.

24.3 WeakMap Objects

WeakMaps는 keys가 objects 및/또는 symbols이고 values는 arbitrary ECMAScript language values일 수 있는 key/value pairs의 collections입니다. WeakMap은 specific key를 가진 key/value pair를 contain하는지 보기 위해 queried될 수 있지만, keys로 holding하는 values를 enumerating하기 위한 mechanism은 provided되지 않습니다. Certain conditions에서, live가 아닌 values는 9.9.3에 described된 것처럼 WeakMap keys로부터 removed됩니다.

implementation은 WeakMap의 key/value pair가 inaccessible하게 되는 time과 key/value pair가 WeakMap에서 removed되는 time 사이에 arbitrarily determined latency를 impose할 수 있습니다. 이 latency가 ECMAScript program에 observable하다면, program execution에 impact할 수 있는 indeterminacy의 source가 될 것입니다. 그 reason으로, ECMAScript implementation은 observer가 observed key를 present하도록 require하지 않는 WeakMap의 key를 observe하는 any means를 provide해서는 안 됩니다.

WeakMaps는 collection 안의 key/value pairs 수에 대해 average로 sublinear인 access times를 제공하는 hash tables 또는 other mechanisms를 사용하여 implemented되어야 합니다. 이 specification에서 사용되는 data structure는 WeakMaps의 required observable semantics를 describe하기 위한 것일 뿐입니다. viable implementation model로 intended되지 않습니다.

Note

WeakMap 및 WeakSet은 WeakMap 또는 WeakSet instance가 없었다면 object 또는 symbol이 otherwise inaccessible해지고 implementation의 garbage collection mechanisms에 의한 resource reclamation의 대상이 되었을 경우 memory resources를 “leak”하지 않는 manner로 object 또는 symbol과 state를 dynamically associating하기 위한 mechanisms를 provide하도록 intended됩니다. 이 characteristic은 WeakMap 또는 WeakSet instances에서 keys로의 inverted per-object/symbol mapping을 사용하여 achieved될 수 있습니다. Alternatively, each WeakMap 또는 WeakSet instance는 internally its key 및 value data를 store할 수 있지만, 이 approach는 WeakMap 또는 WeakSet implementation과 garbage collector 사이의 coordination을 requires합니다. following 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 The WeakMap Constructor

WeakMap constructor는:

  • %WeakMap%입니다.
  • global object"WeakMap" property의 initial value입니다.
  • constructor로 called될 때 new WeakMap을 create하고 initialize합니다.
  • function으로 called되도록 intended되지 않으며, such manner로 called될 때 exception을 throw합니다.
  • 클래스 정의의 extends 절의 값으로 사용될 수 있다. 지정된 WeakMap 동작을 상속하려는 서브클래스 생성자는 WeakMap.prototype의 내장 메서드를 지원하는 데 필요한 내부 상태로 서브클래스 인스턴스를 생성하고 초기화하기 위해 WeakMap 생성자에 대한 super 호출을 포함해야 한다.

24.3.1.1 WeakMap ( [ iterable ] )

이 function은 called될 때 다음 steps를 수행합니다:

  1. NewTarget이 undefined이면, TypeError exception을 throw한다.
  2. map을 ? OrdinaryCreateFromConstructor(NewTarget, "%WeakMap.prototype%", « [[WeakMapData]] »)로 둔다.
  3. map.[[WeakMapData]]를 새 empty List로 설정한다.
  4. iterableundefined 또는 null 중 하나이면, map을 반환한다.
  5. adder를 ? Get(map, "set")로 둔다.
  6. IsCallable(adder)가 false이면, TypeError exception을 throw한다.
  7. AddEntriesFromIterable(map, iterable, adder)를 반환한다.
Note

parameter iterable이 present하면, 이는 two element array-like object를 produce하는 iterator object를 반환하는 %Symbol.iterator% method를 implement하는 object일 것으로 expected됩니다. 그 first element는 WeakMap key로 사용될 value이고 second element는 그 key와 associate할 value입니다.

24.3.2 Properties of the WeakMap Constructor

WeakMap constructor는:

  • value가 %Function.prototype%[[Prototype]] internal slot을 가집니다.
  • 다음 properties를 가집니다:

24.3.2.1 WeakMap.prototype

WeakMap.prototype의 initial value는 WeakMap prototype object입니다.

이 property는 attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }를 가집니다.

24.3.3 Properties of the WeakMap Prototype Object

WeakMap prototype object는:

  • %WeakMap.prototype%입니다.
  • value가 %Object.prototype%[[Prototype]] internal slot을 가집니다.
  • ordinary object입니다.
  • [[WeakMapData]] internal slot을 가지지 않습니다.

24.3.3.1 WeakMap.prototype.constructor

WeakMap.prototype.constructor의 initial value는 %WeakMap%입니다.

24.3.3.2 WeakMap.prototype.delete ( key )

이 method는 called될 때 다음 steps를 수행합니다:

  1. weakMapthis value로 둔다.
  2. RequireInternalSlot(weakMap, [[WeakMapData]])를 수행한다.
  3. CanBeHeldWeakly(key)가 false이면, false를 반환한다.
  4. weakMap.[[WeakMapData]]의 각 Record { [[Key]], [[Value]] } entry에 대해, 다음을 수행한다.
    1. entry.[[Key]]empty가 아니고 SameValue(entry.[[Key]], key)가 true이면, 다음을 수행한다.
      1. entry.[[Key]]empty로 설정한다.
      2. entry.[[Value]]empty로 설정한다.
      3. true를 반환한다.
  5. false를 반환한다.
Note

value empty는 entry가 deleted되었음을 indicate하기 위한 specification device로 사용됩니다. Actual implementations는 internal data structures에서 entry를 physically removing하는 것과 같은 other actions를 취할 수 있습니다.

24.3.3.3 WeakMap.prototype.get ( key )

이 method는 called될 때 다음 steps를 수행합니다:

  1. weakMapthis value로 둔다.
  2. RequireInternalSlot(weakMap, [[WeakMapData]])를 수행한다.
  3. CanBeHeldWeakly(key)가 false이면, undefined를 반환한다.
  4. weakMap.[[WeakMapData]]의 각 Record { [[Key]], [[Value]] } entry에 대해, 다음을 수행한다.
    1. entry.[[Key]]empty가 아니고 SameValue(entry.[[Key]], key)가 true이면, entry.[[Value]]를 반환한다.
  5. undefined를 반환한다.

24.3.3.4 WeakMap.prototype.getOrInsert ( key, value )

이 method는 called될 때 다음 steps를 수행합니다:

  1. weakMapthis value로 둔다.
  2. RequireInternalSlot(weakMap, [[WeakMapData]])를 수행한다.
  3. CanBeHeldWeakly(key)가 false이면, TypeError exception을 throw한다.
  4. weakMap.[[WeakMapData]]의 각 Record { [[Key]], [[Value]] } entry에 대해, 다음을 수행한다.
    1. entry.[[Key]]empty가 아니고 SameValue(entry.[[Key]], key)가 true이면, entry.[[Value]]를 반환한다.
  5. entryRecord { [[Key]]: key, [[Value]]: value }로 둔다.
  6. entryweakMap.[[WeakMapData]]에 append한다.
  7. value를 반환한다.

24.3.3.5 WeakMap.prototype.getOrInsertComputed ( key, callback )

이 method는 called될 때 다음 steps를 수행합니다:

  1. weakMapthis value로 둔다.
  2. RequireInternalSlot(weakMap, [[WeakMapData]])를 수행한다.
  3. CanBeHeldWeakly(key)가 false이면, TypeError exception을 throw한다.
  4. IsCallable(callback)가 false이면, TypeError exception을 throw한다.
  5. weakMap.[[WeakMapData]]의 각 Record { [[Key]], [[Value]] } entry에 대해, 다음을 수행한다.
    1. entry.[[Key]]empty가 아니고 SameValue(entry.[[Key]], key)가 true이면, entry.[[Value]]를 반환한다.
  6. value를 ? Call(callback, undefined, « key »)로 둔다.
  7. NOTE: WeakMap은 callback의 execution 동안 modified되었을 수 있다.
  8. weakMap.[[WeakMapData]]의 각 Record { [[Key]], [[Value]] } entry에 대해, 다음을 수행한다.
    1. entry.[[Key]]empty가 아니고 SameValue(entry.[[Key]], key)가 true이면, 다음을 수행한다.
      1. entry.[[Value]]value로 설정한다.
      2. value를 반환한다.
  9. entryRecord { [[Key]]: key, [[Value]]: value }로 둔다.
  10. entryweakMap.[[WeakMapData]]에 append한다.
  11. value를 반환한다.

24.3.3.6 WeakMap.prototype.has ( key )

이 method는 called될 때 다음 steps를 수행합니다:

  1. weakMapthis value로 둔다.
  2. RequireInternalSlot(weakMap, [[WeakMapData]])를 수행한다.
  3. CanBeHeldWeakly(key)가 false이면, false를 반환한다.
  4. weakMap.[[WeakMapData]]의 각 Record { [[Key]], [[Value]] } entry에 대해, 다음을 수행한다.
    1. entry.[[Key]]empty가 아니고 SameValue(entry.[[Key]], key)가 true이면, true를 반환한다.
  5. false를 반환한다.

24.3.3.7 WeakMap.prototype.set ( key, value )

이 method는 called될 때 다음 steps를 수행합니다:

  1. weakMapthis value로 둔다.
  2. RequireInternalSlot(weakMap, [[WeakMapData]])를 수행한다.
  3. CanBeHeldWeakly(key)가 false이면, TypeError exception을 throw한다.
  4. weakMap.[[WeakMapData]]의 각 Record { [[Key]], [[Value]] } entry에 대해, 다음을 수행한다.
    1. entry.[[Key]]empty가 아니고 SameValue(entry.[[Key]], key)가 true이면, 다음을 수행한다.
      1. entry.[[Value]]value로 설정한다.
      2. weakMap을 반환한다.
  5. entryRecord { [[Key]]: key, [[Value]]: value }로 둔다.
  6. entryweakMap.[[WeakMapData]]에 append한다.
  7. weakMap을 반환한다.

24.3.3.8 WeakMap.prototype [ %Symbol.toStringTag% ]

%Symbol.toStringTag% property의 initial value는 String value "WeakMap"입니다.

이 property는 attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }를 가집니다.

24.3.4 Properties of WeakMap Instances

WeakMap instances는 WeakMap prototype object로부터 properties를 inherit하는 ordinary objects입니다. WeakMap instances는 또한 [[WeakMapData]] internal slot을 가집니다.

24.4 WeakSet Objects

WeakSets는 objects 및/또는 symbols의 collections입니다. distinct object 또는 symbol은 WeakSet의 collection의 element로서 한 번만 occur할 수 있습니다. WeakSet은 specific value를 contain하는지 보기 위해 queried될 수 있지만, holding하는 values를 enumerating하기 위한 mechanism은 provided되지 않습니다. Certain conditions에서, live가 아닌 values는 9.9.3에 described된 것처럼 WeakSet elements로부터 removed됩니다.

implementation은 WeakSet 안에 contained된 value가 inaccessible하게 되는 time과 value가 WeakSet에서 removed되는 time 사이에 arbitrarily determined latency를 impose할 수 있습니다. 이 latency가 ECMAScript program에 observable하다면, program execution에 impact할 수 있는 indeterminacy의 source가 될 것입니다. 그 reason으로, ECMAScript implementation은 observer가 observed value를 present하도록 require하지 않는 particular value를 WeakSet이 contains하는지 determine하는 any means를 provide해서는 안 됩니다.

WeakSets는 collection 안의 elements 수에 대해 average로 sublinear인 access times를 제공하는 hash tables 또는 other mechanisms를 사용하여 implemented되어야 합니다. 이 specification에서 사용되는 data structure는 WeakSets의 required observable semantics를 describe하기 위한 것일 뿐입니다. viable implementation model로 intended되지 않습니다.

Note

24.3NOTE를 참조하십시오.

24.4.1 The WeakSet Constructor

WeakSet constructor는:

  • %WeakSet%입니다.
  • global object"WeakSet" property의 initial value입니다.
  • constructor로 called될 때 new WeakSet을 create하고 initialize합니다.
  • function으로 called되도록 intended되지 않으며, such manner로 called될 때 exception을 throw합니다.
  • 클래스 정의의 extends 절의 값으로 사용될 수 있다. 지정된 WeakSet 동작을 상속하려는 서브클래스 생성자는 WeakSet.prototype의 내장 메서드를 지원하는 데 필요한 내부 상태로 서브클래스 인스턴스를 생성하고 초기화하기 위해 WeakSet 생성자에 대한 super 호출을 포함해야 한다.

24.4.1.1 WeakSet ( [ iterable ] )

이 function은 called될 때 다음 steps를 수행합니다:

  1. NewTarget이 undefined이면, TypeError exception을 throw한다.
  2. set을 ? OrdinaryCreateFromConstructor(NewTarget, "%WeakSet.prototype%", « [[WeakSetData]] »)로 둔다.
  3. set.[[WeakSetData]]를 새 empty List로 설정한다.
  4. iterableundefined 또는 null 중 하나이면, set을 반환한다.
  5. adder를 ? Get(set, "add")로 둔다.
  6. IsCallable(adder)가 false이면, TypeError exception을 throw한다.
  7. iteratorRecord를 ? GetIterator(iterable, sync)로 둔다.
  8. Repeat,
    1. next를 ? IteratorStepValue(iteratorRecord)로 둔다.
    2. nextdone이면, set을 반환한다.
    3. statusCompletion(Call(adder, set, « next »))로 둔다.
    4. IfAbruptCloseIterator(status, iteratorRecord).

24.4.2 Properties of the WeakSet Constructor

WeakSet constructor는:

  • value가 %Function.prototype%[[Prototype]] internal slot을 가집니다.
  • 다음 properties를 가집니다:

24.4.2.1 WeakSet.prototype

WeakSet.prototype의 initial value는 WeakSet prototype object입니다.

이 property는 attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }를 가집니다.

24.4.3 Properties of the WeakSet Prototype Object

WeakSet prototype object는:

  • %WeakSet.prototype%입니다.
  • value가 %Object.prototype%[[Prototype]] internal slot을 가집니다.
  • ordinary object입니다.
  • [[WeakSetData]] internal slot을 가지지 않습니다.

24.4.3.1 WeakSet.prototype.add ( value )

이 method는 called될 때 다음 steps를 수행합니다:

  1. weakSetthis value로 둔다.
  2. RequireInternalSlot(weakSet, [[WeakSetData]])를 수행한다.
  3. CanBeHeldWeakly(value)가 false이면, TypeError exception을 throw한다.
  4. weakSet.[[WeakSetData]]의 각 element entry에 대해, 다음을 수행한다.
    1. entryempty가 아니고 SameValue(entry, value)가 true이면, 다음을 수행한다.
      1. weakSet을 반환한다.
  5. valueweakSet.[[WeakSetData]]에 append한다.
  6. weakSet을 반환한다.

24.4.3.2 WeakSet.prototype.constructor

WeakSet.prototype.constructor의 initial value는 %WeakSet%입니다.

24.4.3.3 WeakSet.prototype.delete ( value )

이 method는 called될 때 다음 steps를 수행합니다:

  1. weakSetthis value로 둔다.
  2. RequireInternalSlot(weakSet, [[WeakSetData]])를 수행한다.
  3. CanBeHeldWeakly(value)가 false이면, false를 반환한다.
  4. weakSet.[[WeakSetData]]의 각 element entry에 대해, 다음을 수행한다.
    1. entryempty가 아니고 SameValue(entry, value)가 true이면, 다음을 수행한다.
      1. value가 entryweakSet.[[WeakSetData]]의 element를 value가 empty인 element로 replace한다.
      2. true를 반환한다.
  5. false를 반환한다.
Note

value empty는 entry가 deleted되었음을 indicate하기 위한 specification device로 사용됩니다. Actual implementations는 internal data structures에서 entry를 physically removing하는 것과 같은 other actions를 취할 수 있습니다.

24.4.3.4 WeakSet.prototype.has ( value )

이 method는 called될 때 다음 steps를 수행합니다:

  1. weakSetthis value로 둔다.
  2. RequireInternalSlot(weakSet, [[WeakSetData]])를 수행한다.
  3. CanBeHeldWeakly(value)가 false이면, false를 반환한다.
  4. weakSet.[[WeakSetData]]의 각 element entry에 대해, 다음을 수행한다.
    1. entryempty가 아니고 SameValue(entry, value)가 true이면, true를 반환한다.
  5. false를 반환한다.

24.4.3.5 WeakSet.prototype [ %Symbol.toStringTag% ]

%Symbol.toStringTag% property의 initial value는 String value "WeakSet"입니다.

이 property는 attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }를 가집니다.

24.4.4 Properties of WeakSet Instances

WeakSet instances는 WeakSet prototype object로부터 properties를 inherit하는 ordinary objects입니다. WeakSet instances는 또한 [[WeakSetData]] internal slot을 가집니다.

24.5 Abstract Operations for Keyed Collections

24.5.1 CanonicalizeKeyedCollectionKey ( key )

The abstract operation CanonicalizeKeyedCollectionKey takes argument key (an ECMAScript language value) and returns an ECMAScript language value. It performs the following steps when called:

  1. key-0𝔽이면, +0𝔽를 반환한다.
  2. key를 반환한다.

25 구조화된 데이터

25.1 ArrayBuffer 객체

25.1.1 표기법

이 section, 25.4, 및 29 안의 아래 descriptions는 read-modify-write modification function internal data structure를 사용합니다.

read-modify-write modification function은 two Lists of byte values를 arguments로 받아 List of byte values를 반환하는 Abstract Closure로 represented되는 mathematical function입니다. 이러한 Abstract Closures는 다음 properties를 모두 satisfy합니다:

  • 그들의 모든 algorithm steps를 atomically 수행합니다.
  • 그들의 individual algorithm steps는 observable하지 않습니다.
Note

read-modify-write modification function의 algorithm steps가 pure, mathematical function을 constitute하는지 verifying하는 데 도움을 주기 위해, 다음 editorial conventions가 recommended됩니다:

25.1.2 Fixed-length 및 Resizable ArrayBuffer 객체

fixed-length ArrayBuffer는 creation 후 byte length가 change될 수 없는 ArrayBuffer입니다.

resizable ArrayBufferArrayBuffer.prototype.resize ( newLength )에 대한 calls를 통해 creation 후 byte length가 change될 수 있는 ArrayBuffer입니다.

created되는 ArrayBuffer object의 kind는 ArrayBuffer ( length [ , options ] )에 passed된 arguments에 따라 달라집니다.

25.1.3 ArrayBuffer 객체를 위한 추상 연산

25.1.3.1 AllocateArrayBuffer ( ctor, byteLength [ , maxByteLength ] )

The abstract operation AllocateArrayBuffer takes arguments ctor (생성자) and byteLength (음이 아닌 정수) and optional argument maxByteLength (음이 아닌 정수 또는 empty) and returns ArrayBuffer를 포함하는 정상 완료 또는 throw 완료. ArrayBuffer를 만드는 데 사용된다. It performs the following steps when called:

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

25.1.3.2 ArrayBufferByteLength ( arrayBuffer, order )

The abstract operation ArrayBufferByteLength takes arguments arrayBuffer (ArrayBuffer 또는 SharedArrayBuffer) and order (seq-cst 또는 unordered) and returns 음이 아닌 정수. It performs the following steps when called:

  1. IsGrowableSharedArrayBuffer(arrayBuffer)가 true이면,
    1. bufferByteLengthBlockarrayBuffer.[[ArrayBufferByteLengthData]]로 하라.
    2. rawLengthGetRawBytesFromSharedBlock(bufferByteLengthBlock, 0, biguint64, true, order)로 하라.
    3. agentRecordsurrounding agentAgent Record로 하라.
    4. isLittleEndianagentRecord.[[LittleEndian]]으로 하라.
    5. (RawBytesToNumeric(biguint64, rawLength, isLittleEndian))를 반환하라.
  2. Assert: IsDetachedBuffer(arrayBuffer)는 false이다.
  3. arrayBuffer.[[ArrayBufferByteLength]]를 반환하라.

25.1.3.3 ArrayBufferCopyAndDetach ( arrayBuffer, newLength, preserveResizability )

The abstract operation ArrayBufferCopyAndDetach takes arguments arrayBuffer (ECMAScript 언어 값), newLength (ECMAScript 언어 값), and preserveResizability (preserve-resizability 또는 fixed-length) and returns ArrayBuffer를 포함하는 정상 완료 또는 throw 완료. It performs the following steps when called:

  1. RequireInternalSlot(arrayBuffer, [[ArrayBufferData]])를 수행하라.
  2. IsSharedArrayBuffer(arrayBuffer)가 true이면, TypeError 예외를 던진다.
  3. newLengthundefined이면,
    1. newByteLengtharrayBuffer.[[ArrayBufferByteLength]]로 하라.
  4. 그렇지 않으면,
    1. newByteLength를 ? ToIndex(newLength)로 하라.
  5. IsDetachedBuffer(arrayBuffer)가 true이면, TypeError 예외를 던진다.
  6. preserveResizabilitypreserve-resizability이고 IsFixedLengthArrayBuffer(arrayBuffer)가 false이면,
    1. newMaxByteLengtharrayBuffer.[[ArrayBufferMaxByteLength]]로 하라.
  7. 그렇지 않으면,
    1. newMaxByteLengthempty로 하라.
  8. arrayBuffer.[[ArrayBufferDetachKey]]undefined가 아니면, TypeError 예외를 던진다.
  9. newBuffer를 ? AllocateArrayBuffer(%ArrayBuffer%, newByteLength, newMaxByteLength)로 하라.
  10. copyLengthmin(newByteLength, arrayBuffer.[[ArrayBufferByteLength]])로 하라.
  11. fromBlockarrayBuffer.[[ArrayBufferData]]로 하라.
  12. toBlocknewBuffer.[[ArrayBufferData]]로 하라.
  13. CopyDataBlockBytes(toBlock, 0, fromBlock, 0, copyLength)를 수행하라.
  14. NOTE: 새 Data Block의 생성도, 이전 Data Block에서의 복사도 관찰 가능하지 않다. 구현체는 이 메서드를 무복사 이동 또는 realloc으로 구현할 수 있다.
  15. DetachArrayBuffer(arrayBuffer)를 수행하라.
  16. newBuffer를 반환하라.

25.1.3.4 IsDetachedBuffer ( arrayBuffer )

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

  1. arrayBuffer.[[ArrayBufferData]]null이면, true를 반환하라.
  2. false를 반환하라.

25.1.3.5 DetachArrayBuffer ( arrayBuffer [ , key ] )

The abstract operation DetachArrayBuffer takes argument arrayBuffer (ArrayBuffer) and optional argument key (아무것) and returns unused를 포함하는 정상 완료 또는 throw 완료. It performs the following steps when called:

  1. Assert: IsSharedArrayBuffer(arrayBuffer)는 false이다.
  2. key가 존재하지 않으면, keyundefined로 설정하라.
  3. arrayBuffer.[[ArrayBufferDetachKey]]key가 아니면, TypeError 예외를 던진다.
  4. arrayBuffer.[[ArrayBufferData]]null로 설정하라.
  5. arrayBuffer.[[ArrayBufferByteLength]]를 0으로 설정하라.
  6. unused를 반환하라.
Note

ArrayBuffer 인스턴스를 detach하면 backing store로 사용되는 Data Block을 해당 인스턴스에서 분리하고 버퍼의 바이트 길이를 0으로 설정한다.

25.1.3.6 CloneArrayBuffer ( sourceBuffer, sourceByteOffset, sourceLength )

The abstract operation CloneArrayBuffer takes arguments sourceBuffer (ArrayBuffer 또는 SharedArrayBuffer), sourceByteOffset (음이 아닌 정수), and sourceLength (음이 아닌 정수) and returns ArrayBuffer를 포함하는 정상 완료 또는 throw 완료. sourceByteOffset에서 시작하여 sourceLength 바이트 동안 이어지는 범위에 걸친 sourceBuffer의 데이터 복사본을 데이터로 가지는 새 ArrayBuffer를 만든다. It performs the following steps when called:

  1. Assert: IsDetachedBuffer(sourceBuffer)는 false이다.
  2. targetBuffer를 ? AllocateArrayBuffer(%ArrayBuffer%, sourceLength)로 하라.
  3. sourceBlocksourceBuffer.[[ArrayBufferData]]로 하라.
  4. targetBlocktargetBuffer.[[ArrayBufferData]]로 하라.
  5. CopyDataBlockBytes(targetBlock, 0, sourceBlock, sourceByteOffset, sourceLength)를 수행하라.
  6. targetBuffer를 반환하라.

25.1.3.7 GetArrayBufferMaxByteLengthOption ( options )

The abstract operation GetArrayBufferMaxByteLengthOption takes argument options (an ECMAScript language value) and returns either a normal completion containing either a non-negative integer or empty, or a throw completion. It performs the following steps when called:

  1. options가 Object가 아니면, empty를 반환하라.
  2. maxByteLength를 ? Get(options, "maxByteLength")로 하라.
  3. maxByteLengthundefined이면, empty를 반환하라.
  4. ToIndex(maxByteLength)를 반환하라.

25.1.3.8 HostResizeArrayBuffer ( buffer, newByteLength )

The host-defined abstract operation HostResizeArrayBuffer takes arguments buffer (an ArrayBuffer) and newByteLength (a non-negative integer) and returns either a normal completion containing either handled or unhandled, or a throw completion. 호스트가 buffer의 구현 정의 크기 조정을 수행할 기회를 제공한다. 호스트가 buffer의 크기 조정을 처리하지 않기로 선택하면, 기본 동작을 위해 unhandled를 반환할 수 있다.

HostResizeArrayBuffer의 구현은 다음 요구사항을 준수해야 한다:

  • 이 추상 연산은 buffer를 detach하지 않는다.
  • 이 추상 연산이 handled로 정상 완료되면, buffer.[[ArrayBufferByteLength]]newByteLength이다.

HostResizeArrayBuffer의 기본 구현은 NormalCompletion(unhandled)를 반환하는 것이다.

25.1.3.9 IsFixedLengthArrayBuffer ( arrayBuffer )

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

  1. arrayBuffer[[ArrayBufferMaxByteLength]] 내부 슬롯을 가지면, false를 반환하라.
  2. true를 반환하라.

25.1.3.10 IsUnsignedElementType ( type )

The abstract operation IsUnsignedElementType takes argument type (TypedArray 요소 타입) and returns Boolean. 인수 type이 부호 없는 TypedArray 요소 타입인지 검증한다. It performs the following steps when called:

  1. typeuint8, uint8clamped, uint16, uint32, 또는 biguint64 중 하나이면, true를 반환하라.
  2. false를 반환하라.

25.1.3.11 IsUnclampedIntegerElementType ( type )

The abstract operation IsUnclampedIntegerElementType takes argument type (TypedArray 요소 타입) and returns Boolean. 인수 typeuint8clamped를 포함하지 않는 Integer TypedArray 요소 타입인지 검증한다. It performs the following steps when called:

  1. typeint8, uint8, int16, uint16, int32, 또는 uint32 중 하나이면, true를 반환하라.
  2. false를 반환하라.

25.1.3.12 IsBigIntElementType ( type )

The abstract operation IsBigIntElementType takes argument type (TypedArray 요소 타입) and returns Boolean. 인수 type이 BigInt TypedArray 요소 타입인지 검증한다. It performs the following steps when called:

  1. typebiguint64 또는 bigint64이면, true를 반환하라.
  2. false를 반환하라.

25.1.3.13 IsNoTearConfiguration ( type, order )

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

  1. IsUnclampedIntegerElementType(type)가 true이면, true를 반환하라.
  2. IsBigIntElementType(type)가 true이고 orderinitunordered도 아니면, true를 반환하라.
  3. false를 반환하라.

25.1.3.14 RawBytesToNumeric ( type, rawBytes, isLittleEndian )

The abstract operation RawBytesToNumeric takes arguments type (TypedArray 요소 타입), rawBytes (바이트 값의 List), and isLittleEndian (Boolean) and returns Number 또는 BigInt. It performs the following steps when called:

  1. elementSize를 Element Type type에 대해 Table 71에 명시된 Element Size 값으로 하라.
  2. isLittleEndianfalse이면, rawBytes의 요소 순서를 뒤집어라.
  3. typefloat16이면,
    1. valuerawBytes의 바이트 요소들을 연결하고 IEEE 754-2019 binary16 값의 리틀 엔디언 비트 문자열 인코딩으로 해석한 것으로 하라.
    2. value가 NaN이면, NaN을 반환하라.
    3. value에 해당하는 Number 값을 반환하라.
  4. typefloat32이면,
    1. valuerawBytes의 바이트 요소들을 연결하고 IEEE 754-2019 binary32 값의 리틀 엔디언 비트 문자열 인코딩으로 해석한 것으로 하라.
    2. value가 NaN이면, NaN을 반환하라.
    3. value에 해당하는 Number 값을 반환하라.
  5. typefloat64이면,
    1. valuerawBytes의 바이트 요소들을 연결하고 IEEE 754-2019 binary64 값의 리틀 엔디언 비트 문자열 인코딩으로 해석한 것으로 하라.
    2. value가 NaN이면, NaN을 반환하라.
    3. value에 해당하는 Number 값을 반환하라.
  6. IsUnsignedElementType(type)가 true이면,
    1. intValuerawBytes의 바이트 요소들을 연결하고 부호 없는 리틀 엔디언 이진수의 비트 문자열 인코딩으로 해석한 것으로 하라.
  7. 그렇지 않으면,
    1. intValuerawBytes의 바이트 요소들을 연결하고 비트 길이가 elementSize × 8인 이진 리틀 엔디언 2의 보수 수의 비트 문자열 인코딩으로 해석한 것으로 하라.
  8. IsBigIntElementType(type)가 true이면, intValue에 해당하는 BigInt 값을 반환하라.
  9. intValue에 해당하는 Number 값을 반환하라.

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

The abstract operation GetRawBytesFromSharedBlock takes arguments block (Shared Data Block), byteIndex (음이 아닌 정수), type (TypedArray 요소 타입), isTypedArray (Boolean), and order (seq-cst 또는 unordered) and returns 바이트 값의 List. It performs the following steps when called:

  1. elementSize를 Element Type type에 대해 Table 71에 명시된 Element Size 값으로 하라.
  2. agentRecordsurrounding agentAgent Record로 하라.
  3. executionagentRecord.[[CandidateExecution]]으로 하라.
  4. eventsRecord[[AgentSignifier]]AgentSignifier()인 execution.[[EventsRecords]]Agent Events Record로 하라.
  5. isTypedArraytrue이고 IsNoTearConfiguration(type, order)가 true이면, noTeartrue로 하라; 그렇지 않으면 noTearfalse로 하라.
  6. rawValue를 요소가 비결정적으로 선택된 바이트 값인 길이 elementSizeList로 하라.
  7. NOTE: 구현에서 rawValue는 기반 하드웨어의 비원자적 또는 원자적 읽기 명령의 결과이다. 비결정성은 약한 일관성을 가진 하드웨어의 관찰 가능한 동작을 설명하기 위한 메모리 모델의 의미론적 규정이다.
  8. readEventReadSharedMemory { [[Order]]: order, [[NoTear]]: noTear, [[Block]]: block, [[ByteIndex]]: byteIndex, [[ElementSize]]: elementSize }로 하라.
  9. readEventeventsRecord.[[EventList]]에 추가하라.
  10. Chosen Value Record { [[Event]]: readEvent, [[ChosenValue]]: rawValue }를 execution.[[ChosenValues]]에 추가하라.
  11. rawValue를 반환하라.

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

The abstract operation GetValueFromBuffer takes arguments arrayBuffer (ArrayBuffer 또는 SharedArrayBuffer), byteIndex (음이 아닌 정수), type (TypedArray 요소 타입), isTypedArray (Boolean), and order (seq-cst 또는 unordered) and optional argument isLittleEndian (Boolean) and returns Number 또는 BigInt. It performs the following steps when called:

  1. Assert: IsDetachedBuffer(arrayBuffer)는 false이다.
  2. Assert: byteIndex에서 시작하여 type의 값을 나타내기에 충분한 바이트가 arrayBuffer에 있다.
  3. blockarrayBuffer.[[ArrayBufferData]]로 하라.
  4. elementSize를 Element Type type에 대해 Table 71에 명시된 Element Size 값으로 하라.
  5. IsSharedArrayBuffer(arrayBuffer)가 true이면,
    1. Assert: blockShared Data Block이다.
    2. rawValueGetRawBytesFromSharedBlock(block, byteIndex, type, isTypedArray, order)로 하라.
  6. 그렇지 않으면,
    1. rawValuebyteIndex 이상 byteIndex + elementSize 미만의 구간에 있는 block의 인덱스들에서 온 바이트를 요소로 하는 List로 하라.
  7. Assert: rawValue의 요소 수는 elementSize이다.
  8. isLittleEndian이 존재하지 않으면,
    1. agentRecordsurrounding agentAgent Record로 하라.
    2. isLittleEndianagentRecord.[[LittleEndian]]으로 설정하라.
  9. RawBytesToNumeric(type, rawValue, isLittleEndian)를 반환하라.

25.1.3.17 NumericToRawBytes ( type, value, isLittleEndian )

The abstract operation NumericToRawBytes takes arguments type (TypedArray 요소 타입), value (Number 또는 BigInt), and isLittleEndian (Boolean) and returns 바이트 값의 List. It performs the following steps when called:

  1. typefloat16이면,
    1. rawBytes를 roundTiesToEven 모드를 사용하여 valueIEEE 754-2019 binary16 형식으로 변환한 결과인 2개의 바이트를 요소로 하는 List로 하라. 바이트는 리틀 엔디언 순서로 배열된다. valueNaN이면, rawBytes는 구현체가 선택한 IEEE 754-2019 binary16 형식 NaN 인코딩 중 하나로 설정될 수 있다. 구현체는 구현체가 구별할 수 있는 각 NaN 값에 대해 항상 동일한 인코딩을 선택해야 한다.
  2. 그렇지 않고 typefloat32이면,
    1. rawBytes를 roundTiesToEven 모드를 사용하여 valueIEEE 754-2019 binary32 형식으로 변환한 결과인 4개의 바이트를 요소로 하는 List로 하라. 바이트는 리틀 엔디언 순서로 배열된다. valueNaN이면, rawBytes는 구현체가 선택한 IEEE 754-2019 binary32 형식 NaN 인코딩 중 하나로 설정될 수 있다. 구현체는 구현체가 구별할 수 있는 각 NaN 값에 대해 항상 동일한 인코딩을 선택해야 한다.
  3. 그렇지 않고 typefloat64이면,
    1. rawBytesvalueIEEE 754-2019 binary64 형식 인코딩인 8개의 바이트를 요소로 하는 List로 하라. 바이트는 리틀 엔디언 순서로 배열된다. valueNaN이면, rawBytes는 구현체가 선택한 IEEE 754-2019 binary64 형식 NaN 인코딩 중 하나로 설정될 수 있다. 구현체는 구현체가 구별할 수 있는 각 NaN 값에 대해 항상 동일한 인코딩을 선택해야 한다.
  4. 그렇지 않으면,
    1. n을 Element Type type에 대해 Table 71에 명시된 Element Size 값으로 하라.
    2. conversionOperation을 Element Type type에 대해 Table 71의 “Conversion Operation” 열에 이름이 지정된 추상 연산으로 하라.
    3. intValue(! conversionOperation(value))로 하라.
    4. intValue ≥ 0이면,
      1. rawBytesintValuen-바이트 이진 인코딩을 요소로 하는 List로 하라. 바이트는 리틀 엔디언 순서로 정렬된다.
    5. 그렇지 않으면,
      1. rawBytesintValuen-바이트 이진 2의 보수 인코딩을 요소로 하는 List로 하라. 바이트는 리틀 엔디언 순서로 정렬된다.
  5. isLittleEndianfalse이면, rawBytes의 요소 순서를 뒤집어라.
  6. rawBytes를 반환하라.

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

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

  1. Assert: IsDetachedBuffer(arrayBuffer)는 false이다.
  2. Assert: byteIndex에서 시작하여 type의 값을 나타내기에 충분한 바이트가 arrayBuffer에 있다.
  3. Assert: IsBigIntElementType(type)가 true이면 value는 BigInt이고, 그렇지 않으면 value는 Number이다.
  4. blockarrayBuffer.[[ArrayBufferData]]로 하라.
  5. elementSize를 Element Type type에 대해 Table 71에 명시된 Element Size 값으로 하라.
  6. agentRecordsurrounding agentAgent Record로 하라.
  7. isLittleEndian이 존재하지 않으면,
    1. isLittleEndianagentRecord.[[LittleEndian]]으로 설정하라.
  8. rawBytesNumericToRawBytes(type, value, isLittleEndian)로 하라.
  9. IsSharedArrayBuffer(arrayBuffer)가 true이면,
    1. executionagentRecord.[[CandidateExecution]]으로 하라.
    2. eventsRecord[[AgentSignifier]]AgentSignifier()인 execution.[[EventsRecords]]Agent Events Record로 하라.
    3. isTypedArraytrue이고 IsNoTearConfiguration(type, order)가 true이면, noTeartrue로 하라; 그렇지 않으면 noTearfalse로 하라.
    4. WriteSharedMemory { [[Order]]: order, [[NoTear]]: noTear, [[Block]]: block, [[ByteIndex]]: byteIndex, [[ElementSize]]: elementSize, [[Payload]]: rawBytes }를 eventsRecord.[[EventList]]에 추가하라.
  10. 그렇지 않으면,
    1. rawBytes의 개별 바이트를 block[byteIndex]에서 시작하여 block에 저장하라.
  11. unused를 반환하라.

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

The abstract operation GetModifySetValueInBuffer takes arguments arrayBuffer (ArrayBuffer 또는 SharedArrayBuffer), byteIndex (음이 아닌 정수), type (TypedArray 요소 타입), value (Number 또는 BigInt), and op (읽기-수정-쓰기 수정 함수) and returns Number 또는 BigInt. It performs the following steps when called:

  1. Assert: IsDetachedBuffer(arrayBuffer)는 false이다.
  2. Assert: byteIndex에서 시작하여 type의 값을 나타내기에 충분한 바이트가 arrayBuffer에 있다.
  3. Assert: IsBigIntElementType(type)가 true이면 value는 BigInt이고, 그렇지 않으면 value는 Number이다.
  4. blockarrayBuffer.[[ArrayBufferData]]로 하라.
  5. elementSize를 Element Type type에 대해 Table 71에 명시된 Element Size 값으로 하라.
  6. agentRecordsurrounding agentAgent Record로 하라.
  7. isLittleEndianagentRecord.[[LittleEndian]]으로 하라.
  8. rawBytesNumericToRawBytes(type, value, isLittleEndian)로 하라.
  9. IsSharedArrayBuffer(arrayBuffer)가 true이면,
    1. executionagentRecord.[[CandidateExecution]]으로 하라.
    2. eventsRecord[[AgentSignifier]]AgentSignifier()인 execution.[[EventsRecords]]Agent Events Record로 하라.
    3. rawBytesRead를 요소가 비결정적으로 선택된 바이트 값인 길이 elementSizeList로 하라.
    4. NOTE: 구현에서 rawBytesRead는 기반 하드웨어의 load-link, load-exclusive, 또는 읽기-수정-쓰기 명령의 피연산자 결과이다. 비결정성은 약한 일관성을 가진 하드웨어의 관찰 가능한 동작을 설명하기 위한 메모리 모델의 의미론적 규정이다.
    5. rmwEventReadModifyWriteSharedMemory { [[Order]]: seq-cst, [[NoTear]]: true, [[Block]]: block, [[ByteIndex]]: byteIndex, [[ElementSize]]: elementSize, [[Payload]]: rawBytes, [[ModifyOp]]: op }로 하라.
    6. rmwEventeventsRecord.[[EventList]]에 추가하라.
    7. Chosen Value Record { [[Event]]: rmwEvent, [[ChosenValue]]: rawBytesRead }를 execution.[[ChosenValues]]에 추가하라.
  10. 그렇지 않으면,
    1. rawBytesReadblock[byteIndex]로 시작하는 elementSize 바이트의 시퀀스를 요소로 하는 길이 elementSizeList로 하라.
    2. rawBytesModifiedop(rawBytesRead, rawBytes)로 하라.
    3. rawBytesModified의 개별 바이트를 block[byteIndex]에서 시작하여 block에 저장하라.
  11. RawBytesToNumeric(type, rawBytesRead, isLittleEndian)를 반환하라.

25.1.4 ArrayBuffer Constructor

ArrayBuffer constructor는:

  • %ArrayBuffer%입니다.
  • global object"ArrayBuffer" property의 initial value입니다.
  • constructor로 called될 때 new ArrayBuffer를 create하고 initialize합니다.
  • function으로 called되도록 intended되지 않으며, such manner로 called될 때 exception을 throw합니다.
  • 클래스 정의의 extends 절의 값으로 사용될 수 있다. 지정된 ArrayBuffer 동작을 상속하려는 서브클래스 생성자는 ArrayBuffer.prototype의 내장 메서드를 지원하는 데 필요한 내부 상태로 서브클래스 인스턴스를 생성하고 초기화하기 위해 ArrayBuffer 생성자에 대한 super 호출을 포함해야 한다.

25.1.4.1 ArrayBuffer ( length [ , options ] )

이 function은 called될 때 다음 steps를 수행합니다:

  1. NewTarget이 undefined이면, TypeError exception을 throw한다.
  2. byteLength를 ? ToIndex(length)로 둔다.
  3. requestedMaxByteLength를 ? GetArrayBufferMaxByteLengthOption(options)로 둔다.
  4. AllocateArrayBuffer(NewTarget, byteLength, requestedMaxByteLength)를 반환한다.

25.1.5 ArrayBuffer Constructor의 Properties

ArrayBuffer constructor는:

  • value가 %Function.prototype%[[Prototype]] internal slot을 가집니다.
  • 다음 properties를 가집니다:

25.1.5.1 ArrayBuffer.isView ( arg )

이 function은 called될 때 다음 steps를 수행합니다:

  1. arg가 Object가 아니면, false를 반환한다.
  2. arg[[ViewedArrayBuffer]] internal slot을 가지면, true를 반환한다.
  3. false를 반환한다.

25.1.5.2 ArrayBuffer.prototype

ArrayBuffer.prototype의 initial value는 ArrayBuffer prototype object입니다.

이 property는 attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }를 가집니다.

25.1.5.3 get ArrayBuffer [ %Symbol.species% ]

ArrayBuffer[%Symbol.species%]는 set accessor function이 undefinedaccessor property입니다. Its get accessor function은 called될 때 다음 steps를 수행합니다:

  1. this value를 반환한다.

이 function의 "name" property의 value는 "get [Symbol.species]"입니다.

Note

ArrayBuffer.prototype.slice ( start, end )는 normally its this value의 constructor를 사용하여 derived object를 create합니다. However, subclass constructor는 its %Symbol.species% property를 redefining하여 ArrayBuffer.prototype.slice ( start, end ) method에 대한 that default behaviour를 over-ride할 수 있습니다.

25.1.6 ArrayBuffer Prototype Object의 Properties

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이 undefinedaccessor property입니다. Its get accessor function은 called될 때 다음 steps를 수행합니다:

  1. objthis value로 둔다.
  2. RequireInternalSlot(obj, [[ArrayBufferData]])를 수행한다.
  3. IsSharedArrayBuffer(obj)가 true이면, TypeError exception을 throw한다.
  4. IsDetachedBuffer(obj)가 true이면, +0𝔽를 반환한다.
  5. lengthobj.[[ArrayBufferByteLength]]로 둔다.
  6. 𝔽(length)를 반환한다.

25.1.6.2 ArrayBuffer.prototype.constructor

ArrayBuffer.prototype.constructor의 initial value는 %ArrayBuffer%입니다.

25.1.6.3 get ArrayBuffer.prototype.detached

ArrayBuffer.prototype.detached는 set accessor function이 undefinedaccessor property입니다. Its get accessor function은 called될 때 다음 steps를 수행합니다:

  1. objthis value로 둔다.
  2. RequireInternalSlot(obj, [[ArrayBufferData]])를 수행한다.
  3. IsSharedArrayBuffer(obj)가 true이면, TypeError exception을 throw한다.
  4. IsDetachedBuffer(obj)를 반환한다.

25.1.6.4 get ArrayBuffer.prototype.maxByteLength

ArrayBuffer.prototype.maxByteLength는 set accessor function이 undefinedaccessor property입니다. Its get accessor function은 called될 때 다음 steps를 수행합니다:

  1. objthis value로 둔다.
  2. RequireInternalSlot(obj, [[ArrayBufferData]])를 수행한다.
  3. IsSharedArrayBuffer(obj)가 true이면, TypeError exception을 throw한다.
  4. IsDetachedBuffer(obj)가 true이면, +0𝔽를 반환한다.
  5. IsFixedLengthArrayBuffer(obj)가 true이면, 다음을 수행한다.
    1. lengthobj.[[ArrayBufferByteLength]]로 둔다.
  6. 그렇지 않으면,
    1. lengthobj.[[ArrayBufferMaxByteLength]]로 둔다.
  7. 𝔽(length)를 반환한다.

25.1.6.5 get ArrayBuffer.prototype.resizable

ArrayBuffer.prototype.resizable는 set accessor function이 undefinedaccessor property입니다. Its get accessor function은 called될 때 다음 steps를 수행합니다:

  1. objthis value로 둔다.
  2. RequireInternalSlot(obj, [[ArrayBufferData]])를 수행한다.
  3. IsSharedArrayBuffer(obj)가 true이면, TypeError exception을 throw한다.
  4. IsFixedLengthArrayBuffer(obj)가 false이면, true를 반환한다.
  5. false를 반환한다.

25.1.6.6 ArrayBuffer.prototype.resize ( newLength )

이 method는 called될 때 다음 steps를 수행합니다:

  1. objthis value로 둔다.
  2. RequireInternalSlot(obj, [[ArrayBufferMaxByteLength]])를 수행한다.
  3. IsSharedArrayBuffer(obj)가 true이면, TypeError exception을 throw한다.
  4. newByteLength를 ? ToIndex(newLength)로 둔다.
  5. IsDetachedBuffer(obj)가 true이면, TypeError exception을 throw한다.
  6. newByteLength > obj.[[ArrayBufferMaxByteLength]]이면, RangeError exception을 throw한다.
  7. hostHandled를 ? HostResizeArrayBuffer(obj, newByteLength)로 둔다.
  8. hostHandledhandled이면, undefined를 반환한다.
  9. oldBlockobj.[[ArrayBufferData]]로 둔다.
  10. newBlock을 ? CreateByteDataBlock(newByteLength)로 둔다.
  11. copyLengthmin(newByteLength, obj.[[ArrayBufferByteLength]])로 둔다.
  12. CopyDataBlockBytes(newBlock, 0, oldBlock, 0, copyLength)를 수행한다.
  13. NOTE: new Data Block의 creation도 old Data Block으로부터의 copying도 observable하지 않습니다. Implementations는 이 method를 in-place growth 또는 shrinkage로 implement할 수 있습니다.
  14. obj.[[ArrayBufferData]]newBlock으로 설정한다.
  15. obj.[[ArrayBufferByteLength]]newByteLength로 설정한다.
  16. undefined를 반환한다.

25.1.6.7 ArrayBuffer.prototype.slice ( start, end )

이 method는 called될 때 다음 steps를 수행합니다:

  1. objthis value로 둔다.
  2. RequireInternalSlot(obj, [[ArrayBufferData]])를 수행한다.
  3. IsSharedArrayBuffer(obj)가 true이면, TypeError exception을 throw한다.
  4. IsDetachedBuffer(obj)가 true이면, TypeError exception을 throw한다.
  5. lengthobj.[[ArrayBufferByteLength]]로 둔다.
  6. relativeStart를 ? ToIntegerOrInfinity(start)로 둔다.
  7. relativeStart = -∞이면, first를 0으로 둔다.
  8. 그렇지 않고 relativeStart < 0이면, firstmax(length + relativeStart, 0)으로 둔다.
  9. 그렇지 않으면, firstmin(relativeStart, length)로 둔다.
  10. endundefined이면 relativeEndlength로 둔다; 그렇지 않으면 relativeEnd를 ? ToIntegerOrInfinity(end)로 둔다.
  11. relativeEnd = -∞이면, final을 0으로 둔다.
  12. 그렇지 않고 relativeEnd < 0이면, finalmax(length + relativeEnd, 0)으로 둔다.
  13. 그렇지 않으면, finalmin(relativeEnd, length)로 둔다.
  14. newLengthmax(final - first, 0)으로 둔다.
  15. ctor를 ? SpeciesConstructor(obj, %ArrayBuffer%)로 둔다.
  16. new를 ? Construct(ctor, « 𝔽(newLength) »)로 둔다.
  17. RequireInternalSlot(new, [[ArrayBufferData]])를 수행한다.
  18. IsSharedArrayBuffer(new)가 true이면, TypeError exception을 throw한다.
  19. IsDetachedBuffer(new)가 true이면, TypeError exception을 throw한다.
  20. SameValue(new, obj)가 true이면, TypeError exception을 throw한다.
  21. new.[[ArrayBufferByteLength]] < newLength이면, TypeError exception을 throw한다.
  22. NOTE: above steps의 side-effects가 obj를 detached 또는 resized했을 수 있다.
  23. IsDetachedBuffer(obj)가 true이면, TypeError exception을 throw한다.
  24. fromBufobj.[[ArrayBufferData]]로 둔다.
  25. toBufnew.[[ArrayBufferData]]로 둔다.
  26. currentLengthobj.[[ArrayBufferByteLength]]로 둔다.
  27. first < currentLength이면, 다음을 수행한다.
    1. countmin(newLength, currentLength - first)로 둔다.
    2. CopyDataBlockBytes(toBuf, 0, fromBuf, first, count)를 수행한다.
  28. new를 반환한다.

25.1.6.8 ArrayBuffer.prototype.transfer ( [ newLength ] )

이 method는 called될 때 다음 steps를 수행합니다:

  1. objthis value로 둔다.
  2. ArrayBufferCopyAndDetach(obj, newLength, preserve-resizability)를 반환한다.

25.1.6.9 ArrayBuffer.prototype.transferToFixedLength ( [ newLength ] )

이 method는 called될 때 다음 steps를 수행합니다:

  1. objthis value로 둔다.
  2. ArrayBufferCopyAndDetach(obj, newLength, fixed-length)를 반환한다.

25.1.6.10 ArrayBuffer.prototype [ %Symbol.toStringTag% ]

%Symbol.toStringTag% property의 initial value는 String value "ArrayBuffer"입니다.

이 property는 attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }를 가집니다.

25.1.7 ArrayBuffer Instances의 Properties

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로 set된 ArrayBuffer instances는 all DetachArrayBuffer calls가 same “detach key”를 argument로 passing해야 하며, 그렇지 않으면 TypeError가 result됩니다. 이 internal slot은 only certain embedding environments에 의해 set되며, 이 specification의 algorithms에 의해 set되지 않습니다.

25.1.8 Resizable ArrayBuffer Guidelines

Note 1

다음은 resizable ArrayBuffer로 작업하는 ECMAScript programmers를 위한 guidelines입니다.

가능한 경우 programs를 그 deployment environments에서 test할 것을 recommend합니다. available physical memory의 amount는 hardware devices 사이에서 크게 differs합니다. Similarly, virtual memory subsystems 또한 hardware devices 및 operating systems 사이에서 크게 differs합니다. 64-bit desktop web browser에서 out-of-memory errors 없이 runs하는 application이 32-bit mobile web browser에서는 memory가 부족해질 수 있습니다.

resizable ArrayBuffer에 대한 "maxByteLength" option의 value를 choosing할 때, application에 대해 가능한 smallest size를 choose할 것을 recommend합니다. "maxByteLength"가 1,073,741,824 (230 bytes 또는 1GiB)를 exceed하지 않을 것을 recommend합니다.

particular maximum size에 대해 resizable ArrayBuffer를 successfully constructing하는 것이 future resizes가 succeed할 것을 guarantee하지 않는다는 점에 note하십시오.

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에 대해 both의 combination으로 implemented될 수 있습니다.

host가 web browser처럼 multi-tenanted(즉, many ECMAScript applications를 simultaneously runs)이고, its implementations가 virtual memory를 reserving하여 in-place growth를 implement하기로 choose하는 경우, 32-bit와 64-bit implementations 모두 "maxByteLength" ≥ 1GiB to 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가 resizing을 copying으로만 implements하는 경우, "maxByteLength" option에 대한 any Number value for을 accept할 수 있습니다. However, requested size의 memory block이 never allocated될 수 없는 경우 RangeError가 thrown될 것을 recommend합니다. 예를 들어, requested size가 device에서 usable한 maximum memory amount보다 greater한 경우입니다.

25.2 SharedArrayBuffer 객체

25.2.1 Fixed-length 및 Growable SharedArrayBuffer 객체

fixed-length SharedArrayBuffer는 creation 후 byte length가 change될 수 없는 SharedArrayBuffer입니다.

growable SharedArrayBufferSharedArrayBuffer.prototype.grow ( newLength )에 대한 calls를 통해 creation 후 byte length가 increase될 수 있는 SharedArrayBuffer입니다.

created되는 SharedArrayBuffer object의 kind는 SharedArrayBuffer ( length [ , options ] )에 passed된 arguments에 따라 달라집니다.

25.2.2 SharedArrayBuffer 객체를 위한 Abstract Operations

25.2.2.1 AllocateSharedArrayBuffer ( ctor, byteLength [ , maxByteLength ] )

The abstract operation AllocateSharedArrayBuffer takes arguments ctor (a constructor) and byteLength (a non-negative integer) and optional argument maxByteLength (a non-negative integer or empty) and returns either a normal completion containing a SharedArrayBuffer or a throw completion. SharedArrayBuffer를 create하는 데 사용됩니다. It performs the following steps when called:

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

25.2.2.2 IsSharedArrayBuffer ( obj )

The abstract operation IsSharedArrayBuffer takes argument obj (an ArrayBuffer or a SharedArrayBuffer) and returns a Boolean. object가 SharedArrayBuffer인지 tests합니다. It performs the following steps when called:

  1. obj.[[ArrayBufferData]]Shared Data Block이면, true를 반환한다.
  2. false를 반환한다.

25.2.2.3 IsGrowableSharedArrayBuffer ( obj )

The abstract operation IsGrowableSharedArrayBuffer takes argument obj (an ArrayBuffer or a SharedArrayBuffer) and returns a Boolean. object가 growable SharedArrayBuffer인지 tests합니다. It performs the following steps when called:

  1. IsSharedArrayBuffer(obj)가 true이고 obj[[ArrayBufferByteLengthData]] internal slot을 가지면, true를 반환한다.
  2. false를 반환한다.

25.2.2.4 HostGrowSharedArrayBuffer ( buffer, newByteLength )

The host-defined abstract operation HostGrowSharedArrayBuffer takes arguments buffer (a SharedArrayBuffer) and newByteLength (a non-negative integer) and returns either a normal completion containing either handled or unhandled, or a throw completion. host에게 bufferimplementation-defined growing을 수행할 opportunity를 제공합니다. hostbuffer의 growing을 handle하지 않기로 choose하면, default behaviour를 위해 unhandled를 반환할 수 있습니다.

HostGrowSharedArrayBuffer의 implementation은 다음 requirements를 conform해야 합니다:

  • abstract operation이 unhandled로 normally complete하지 않고, newByteLength < buffer의 current byte length이거나 newByteLength > buffer.[[ArrayBufferMaxByteLength]]이면, RangeError exception을 throw합니다.
  • agentRecordsurrounding agentAgent Record로 둡니다. isLittleEndianagentRecord.[[LittleEndian]]으로 둡니다. abstract operation이 handled로 normally completes하면, [[Order]]seq-cst, [[Payload]]NumericToRawBytes(biguint64, newByteLength, isLittleEndian), [[Block]]buffer.[[ArrayBufferByteLengthData]], [[ByteIndex]]가 0, [[ElementSize]]가 8인 WriteSharedMemory 또는 ReadModifyWriteSharedMemory event가 surrounding agentcandidate execution에 added되어 SharedArrayBuffer.prototype.grow ( newLength )에 대한 racing calls가 “lost”되지 않도록, 즉 silently do nothing하지 않도록 합니다.
Note

위의 second requirement는 buffer의 current byte length가 how 또는 when 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을 수행하지 않으며, current byte length가 언제 read되는지에 대한 requirement도 없습니다.

이는 0 ≤ newByteLengthbuffer.[[ArrayBufferMaxByteLength]]가 guaranteed되는 HostResizeArrayBuffer와 대비됩니다.

HostGrowSharedArrayBuffer의 default implementation은 NormalCompletion(unhandled)를 반환하는 것입니다.

25.2.3 SharedArrayBuffer Constructor

SharedArrayBuffer constructor는:

  • %SharedArrayBuffer%입니다.
  • 그 property가 present한 경우, global object"SharedArrayBuffer" property의 initial value입니다(아래 참조).
  • constructor로 called될 때 new SharedArrayBuffer를 create하고 initialize합니다.
  • function으로 called되도록 intended되지 않으며, such manner로 called될 때 exception을 throw합니다.
  • 클래스 정의의 extends 절의 값으로 사용될 수 있다. 지정된 SharedArrayBuffer 동작을 상속하려는 서브클래스 생성자는 SharedArrayBuffer.prototype의 내장 메서드를 지원하는 데 필요한 내부 상태로 서브클래스 인스턴스를 생성하고 초기화하기 위해 SharedArrayBuffer 생성자에 대한 super 호출을 포함해야 한다.

host가 SharedArrayBuffers에 대한 concurrent access를 provide하지 않을 때마다, global object"SharedArrayBuffer" property를 omit할 수 있습니다.

Note

ArrayBuffer와 달리, SharedArrayBuffer는 detached될 수 없고, its internal [[ArrayBufferData]] slot은 never null입니다.

25.2.3.1 SharedArrayBuffer ( length [ , options ] )

이 function은 called될 때 다음 steps를 수행합니다:

  1. NewTarget이 undefined이면, TypeError exception을 throw한다.
  2. byteLength를 ? ToIndex(length)로 둔다.
  3. requestedMaxByteLength를 ? GetArrayBufferMaxByteLengthOption(options)로 둔다.
  4. AllocateSharedArrayBuffer(NewTarget, byteLength, requestedMaxByteLength)를 반환한다.

25.2.4 SharedArrayBuffer Constructor의 Properties

SharedArrayBuffer constructor는:

  • value가 %Function.prototype%[[Prototype]] internal slot을 가집니다.
  • 다음 properties를 가집니다:

25.2.4.1 SharedArrayBuffer.prototype

SharedArrayBuffer.prototype의 initial value는 SharedArrayBuffer prototype object입니다.

이 property는 attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }를 가집니다.

25.2.4.2 get SharedArrayBuffer [ %Symbol.species% ]

SharedArrayBuffer[%Symbol.species%]는 set accessor function이 undefinedaccessor property입니다. Its get accessor function은 called될 때 다음 steps를 수행합니다:

  1. this value를 반환한다.

이 function의 "name" property의 value는 "get [Symbol.species]"입니다.

25.2.5 SharedArrayBuffer Prototype Object의 Properties

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이 undefinedaccessor property입니다. Its get accessor function은 called될 때 다음 steps를 수행합니다:

  1. objthis value로 둔다.
  2. RequireInternalSlot(obj, [[ArrayBufferData]])를 수행한다.
  3. IsSharedArrayBuffer(obj)가 false이면, TypeError exception을 throw한다.
  4. lengthArrayBufferByteLength(obj, seq-cst)로 둔다.
  5. 𝔽(length)를 반환한다.

25.2.5.2 SharedArrayBuffer.prototype.constructor

SharedArrayBuffer.prototype.constructor의 initial value는 %SharedArrayBuffer%입니다.

25.2.5.3 SharedArrayBuffer.prototype.grow ( newLength )

이 method는 called될 때 다음 steps를 수행합니다:

  1. objthis value로 둔다.
  2. RequireInternalSlot(obj, [[ArrayBufferMaxByteLength]])를 수행한다.
  3. IsSharedArrayBuffer(obj)가 false이면, TypeError exception을 throw한다.
  4. newByteLength를 ? ToIndex(newLength)로 둔다.
  5. hostHandled를 ? HostGrowSharedArrayBuffer(obj, newByteLength)로 둔다.
  6. hostHandledhandled이면, undefined를 반환한다.
  7. agentRecordsurrounding agentAgent Record로 둔다.
  8. isLittleEndianagentRecord.[[LittleEndian]]으로 둔다.
  9. byteLengthBlockobj.[[ArrayBufferByteLengthData]]로 둔다.
  10. currentByteLengthRawBytesGetRawBytesFromSharedBlock(byteLengthBlock, 0, biguint64, true, seq-cst)로 둔다.
  11. newByteLengthRawBytesNumericToRawBytes(biguint64, (newByteLength), isLittleEndian)로 둔다.
  12. 반복한다.
    1. NOTE: 이것은 same buffer의 parallel, racing grows가 totally ordered되고, lost되지 않으며, silently do nothing하지 않도록 보장하기 위한 compare-and-exchange loop입니다. loop는 uncontended로 grow를 attempt할 수 있었을 때 exits합니다.
    2. currentByteLength(RawBytesToNumeric(biguint64, currentByteLengthRawBytes, isLittleEndian))로 둔다.
    3. newByteLength = currentByteLength이면, undefined를 반환한다.
    4. newByteLength < currentByteLength이거나 newByteLength > obj.[[ArrayBufferMaxByteLength]]이면, RangeError exception을 throw한다.
    5. byteLengthDeltanewByteLength - currentByteLength로 둔다.
    6. byteLengthDelta bytes로 구성된 new Shared Data Block value를 create하는 것이 impossible하면, RangeError exception을 throw한다.
    7. NOTE: 여기서는 new Shared Data Block이 constructed되고 used되지 않습니다. growable SharedArrayBuffers의 observable behaviour는 construction time에 max-sized Shared Data Block을 allocating하는 것으로 specified되며, 이 step은 memory가 부족해진 implementations가 RangeError를 throw해야 한다는 requirement를 captures합니다.
    8. readByteLengthRawBytesAtomicCompareExchangeInSharedBlock(byteLengthBlock, 0, 8, currentByteLengthRawBytes, newByteLengthRawBytes)로 둔다.
    9. ByteListEqual(readByteLengthRawBytes, currentByteLengthRawBytes)가 true이면, undefined를 반환한다.
    10. currentByteLengthRawBytesreadByteLengthRawBytes로 설정한다.
Note

length를 update하는 compare-exchange의 spurious failures는 prohibited됩니다. new length에 대한 bounds checking이 passes하고 implementation이 out of memory가 아니면, ReadModifyWriteSharedMemory event(즉 successful compare-exchange)는 always candidate execution 안에 added됩니다.

SharedArrayBuffer.prototype.grow에 대한 parallel calls는 totally ordered됩니다. 예를 들어, 두 racing calls sab.grow(10)sab.grow(20)을 consider하십시오. 두 calls 중 하나는 race에서 win하는 것이 guaranteed됩니다. sab.grow(20)이 먼저 happened하더라도 sab.grow(10)에 대한 call은 never sab를 shrink하지 않습니다; 그 경우 대신 RangeError를 throw합니다.

25.2.5.4 get SharedArrayBuffer.prototype.growable

SharedArrayBuffer.prototype.growable은 set accessor function이 undefinedaccessor property입니다. Its get accessor function은 called될 때 다음 steps를 수행합니다:

  1. objthis value로 둔다.
  2. RequireInternalSlot(obj, [[ArrayBufferData]])를 수행한다.
  3. IsSharedArrayBuffer(obj)가 false이면, TypeError exception을 throw한다.
  4. IsFixedLengthArrayBuffer(obj)가 false이면, true를 반환한다.
  5. false를 반환한다.

25.2.5.5 get SharedArrayBuffer.prototype.maxByteLength

SharedArrayBuffer.prototype.maxByteLength는 set accessor function이 undefinedaccessor property입니다. Its get accessor function은 called될 때 다음 steps를 수행합니다:

  1. objthis value로 둔다.
  2. RequireInternalSlot(obj, [[ArrayBufferData]])를 수행한다.
  3. IsSharedArrayBuffer(obj)가 false이면, TypeError exception을 throw한다.
  4. IsFixedLengthArrayBuffer(obj)가 true이면, 다음을 수행한다.
    1. lengthobj.[[ArrayBufferByteLength]]로 둔다.
  5. 그렇지 않으면,
    1. lengthobj.[[ArrayBufferMaxByteLength]]로 둔다.
  6. 𝔽(length)를 반환한다.

25.2.5.6 SharedArrayBuffer.prototype.slice ( start, end )

이 method는 called될 때 다음 steps를 수행합니다:

  1. objthis value로 둔다.
  2. RequireInternalSlot(obj, [[ArrayBufferData]])를 수행한다.
  3. IsSharedArrayBuffer(obj)가 false이면, TypeError exception을 throw한다.
  4. lengthArrayBufferByteLength(obj, seq-cst)로 둔다.
  5. relativeStart를 ? ToIntegerOrInfinity(start)로 둔다.
  6. relativeStart = -∞이면, first를 0으로 둔다.
  7. 그렇지 않고 relativeStart < 0이면, firstmax(length + relativeStart, 0)으로 둔다.
  8. 그렇지 않으면, firstmin(relativeStart, length)로 둔다.
  9. endundefined이면 relativeEndlength로 둔다; 그렇지 않으면 relativeEnd를 ? ToIntegerOrInfinity(end)로 둔다.
  10. relativeEnd = -∞이면, final을 0으로 둔다.
  11. 그렇지 않고 relativeEnd < 0이면, finalmax(length + relativeEnd, 0)으로 둔다.
  12. 그렇지 않으면, finalmin(relativeEnd, length)로 둔다.
  13. newLengthmax(final - first, 0)으로 둔다.
  14. ctor를 ? SpeciesConstructor(obj, %SharedArrayBuffer%)로 둔다.
  15. new를 ? Construct(ctor, « 𝔽(newLength) »)로 둔다.
  16. RequireInternalSlot(new, [[ArrayBufferData]])를 수행한다.
  17. IsSharedArrayBuffer(new)가 false이면, TypeError exception을 throw한다.
  18. new.[[ArrayBufferData]]obj.[[ArrayBufferData]]이면, TypeError exception을 throw한다.
  19. ArrayBufferByteLength(new, seq-cst) < newLength이면, TypeError exception을 throw한다.
  20. fromBufobj.[[ArrayBufferData]]로 둔다.
  21. toBufnew.[[ArrayBufferData]]로 둔다.
  22. CopyDataBlockBytes(toBuf, 0, fromBuf, first, newLength)를 수행한다.
  23. new를 반환한다.

25.2.5.7 SharedArrayBuffer.prototype [ %Symbol.toStringTag% ]

%Symbol.toStringTag% property의 initial value는 String value "SharedArrayBuffer"입니다.

이 property는 attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }를 가집니다.

25.2.6 SharedArrayBuffer Instances의 Properties

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와 달리 never detached됩니다.

25.2.7 Growable SharedArrayBuffer Guidelines

Note 1

다음은 growable SharedArrayBuffer로 작업하는 ECMAScript programmers를 위한 guidelines입니다.

가능한 경우 programs를 그 deployment environments에서 test할 것을 recommend합니다. available physical memory의 amount는 hardware devices 사이에서 greatly differ합니다. Similarly, virtual memory subsystems 또한 hardware devices 및 operating systems 사이에서 greatly differ합니다. 64-bit desktop web browser에서 out-of-memory errors 없이 runs하는 application이 32-bit mobile web browser에서는 memory가 부족해질 수 있습니다.

growable SharedArrayBuffer에 대한 "maxByteLength" option의 value를 choosing할 때, application에 대해 가능한 smallest size를 choose할 것을 recommend합니다. "maxByteLength"가 1073741824, 또는 1GiB를 exceed하지 않을 것을 recommend합니다.

particular maximum size에 대해 growable SharedArrayBuffer를 successfully constructing하는 것이 future grows가 succeed할 것을 guarantee하지 않는다는 점에 note하십시오.

growable SharedArrayBuffer's length의 모든 loads가 synchronizing seq-cst loads인 것은 아닙니다. integer-indexed property access의 bounds-checking을 위한 length의 loads, 예를 들어 u8[idx],는 synchronizing하지 않습니다. 일반적으로 explicit synchronization이 없을 때, one property access가 in-bound라는 것이 same agent 안의 subsequent property access도 in-bound라는 것을 imply하지 않습니다. 이와 contrast하여, SharedArrayBuffer, %TypedArray%.prototype, 및 DataView.prototype의 lengthbyteLength 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합니다. In practice, 이는 growable SharedArrayBuffer의 underlying data block이 stopping the world 없이 copied되어 grown될 수 없음을 의미합니다. 우리는 stopping the world를 implementation strategy로 recommend하지 않습니다. 이는 serialization point를 introduce하고 느리기 때문입니다.

Grown memory는 creation 순간부터 zeroed된 것으로 appear해야 하며, parallel한 any racy accesses에도 포함됩니다. 이는 zero-filled-on-demand virtual memory pages를 통해 또는 manually zeroing memory하는 경우 careful synchronization을 통해 accomplished될 수 있습니다.

growable SharedArrayBuffers의 TypedArray views에 대한 Integer-indexed property access는 non-growable SharedArrayBuffers의 TypedArray views에 대한 access와 similarly optimizable되도록 intended됩니다. 이는 integer-indexed property loads가 underlying buffer's length에 대해 synchronizing하지 않기 때문입니다(위 programmer guidelines 참조). 예를 들어, property accesses를 위한 bounds checks는 still loops 밖으로 hoisted될 수 있습니다.

In practice, virtual memory가 없는 hosts, 예를 들어 MMU 없이 embedded devices에서 running하는 hosts에서 growable SharedArrayBuffer를 copying으로 implement하는 것은 어렵습니다. 이러한 hosts에서 growable SharedArrayBuffers의 memory usage behaviour는 virtual memory가 있는 hosts와 significantly differ할 수 있습니다. Such hosts는 memory usage expectations를 users에게 clearly communicate해야 합니다.

25.3 DataView 객체

25.3.1 DataView 객체를 위한 Abstract Operations

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의 single ReadSharedMemory event가 있음을 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's byte length가 loaded되는 DataView object입니다.
[[CachedBufferByteLength]] a non-negative integer or detached Record가 created되었을 때 object's [[ViewedArrayBuffer]]의 byte length입니다.

25.3.1.2 MakeDataViewWithBufferWitnessRecord ( obj, order )

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

  1. bufferobj.[[ViewedArrayBuffer]]로 둔다.
  2. IsDetachedBuffer(buffer)가 true이면, 다음을 수행한다.
    1. byteLengthdetached로 둔다.
  3. 그렇지 않으면,
    1. byteLengthArrayBufferByteLength(buffer, order)로 둔다.
  4. DataView With Buffer Witness Record { [[Object]]: obj, [[CachedBufferByteLength]]: byteLength }를 반환한다.

25.3.1.3 GetViewByteLength ( viewRecord )

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

  1. Assert: IsViewOutOfBounds(viewRecord)는 false이다.
  2. viewviewRecord.[[Object]]로 둔다.
  3. view.[[ByteLength]]auto가 아니면, view.[[ByteLength]]를 반환한다.
  4. Assert: IsFixedLengthArrayBuffer(view.[[ViewedArrayBuffer]])는 false이다.
  5. byteOffsetview.[[ByteOffset]]으로 둔다.
  6. byteLengthviewRecord.[[CachedBufferByteLength]]로 둔다.
  7. Assert: byteLengthdetached가 아니다.
  8. byteLength - byteOffset을 반환한다.

25.3.1.4 IsViewOutOfBounds ( viewRecord )

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

  1. viewviewRecord.[[Object]]로 둔다.
  2. bufferByteLengthviewRecord.[[CachedBufferByteLength]]로 둔다.
  3. IsDetachedBuffer(view.[[ViewedArrayBuffer]])가 true이면, 다음을 수행한다.
    1. Assert: bufferByteLengthdetached이다.
    2. true를 반환한다.
  4. Assert: bufferByteLength는 non-negative integer이다.
  5. byteOffsetStartview.[[ByteOffset]]으로 둔다.
  6. view.[[ByteLength]]auto이면, 다음을 수행한다.
    1. byteOffsetEndbufferByteLength로 둔다.
  7. 그렇지 않으면,
    1. byteOffsetEndbyteOffsetStart + view.[[ByteLength]]로 둔다.
  8. NOTE: [[ByteOffset]]bufferByteLength인 0-length DataView는 out-of-bounds로 considered되지 않습니다.
  9. byteOffsetStart > bufferByteLength이거나 byteOffsetEnd > bufferByteLength이면, true를 반환한다.
  10. false를 반환한다.

25.3.1.5 GetViewValue ( view, requestIndex, isLittleEndian, type )

The abstract operation GetViewValue takes arguments view (an ECMAScript language value), requestIndex (an ECMAScript language value), isLittleEndian (an ECMAScript language value), and type (a TypedArray element type) and returns either a normal completion containing either a Number or a BigInt, or a throw completion. DataView instances의 functions에 의해 view's buffer로부터 values를 retrieve하는 데 사용됩니다. It performs the following steps when called:

  1. RequireInternalSlot(view, [[DataView]])를 수행한다.
  2. Assert: view[[ViewedArrayBuffer]] internal slot을 가진다.
  3. getIndex를 ? ToIndex(requestIndex)로 둔다.
  4. isLittleEndianToBoolean(isLittleEndian)으로 설정한다.
  5. viewOffsetview.[[ByteOffset]]으로 둔다.
  6. viewRecordMakeDataViewWithBufferWitnessRecord(view, unordered)로 둔다.
  7. NOTE: view's backing buffer가 growable SharedArrayBuffer일 때 bounds checking은 synchronizing operation이 아닙니다.
  8. IsViewOutOfBounds(viewRecord)가 true이면, TypeError exception을 throw한다.
  9. viewSizeGetViewByteLength(viewRecord)로 둔다.
  10. elementSize를 Element Type type에 대해 Table 71에 specified된 Element Size value로 둔다.
  11. getIndex + elementSize > viewSize이면, RangeError exception을 throw한다.
  12. bufferIndexgetIndex + viewOffset으로 둔다.
  13. GetValueFromBuffer(view.[[ViewedArrayBuffer]], bufferIndex, type, false, unordered, isLittleEndian)을 반환한다.

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

The abstract operation SetViewValue takes arguments view (an ECMAScript language value), requestIndex (an ECMAScript language value), isLittleEndian (an ECMAScript language value), type (a TypedArray element type), and value (an ECMAScript language value) and returns either a normal completion containing undefined or a throw completion. DataView instances의 functions에 의해 values를 view's buffer 안으로 store하는 데 사용됩니다. It performs the following steps when called:

  1. RequireInternalSlot(view, [[DataView]])를 수행한다.
  2. Assert: view[[ViewedArrayBuffer]] internal slot을 가진다.
  3. getIndex를 ? ToIndex(requestIndex)로 둔다.
  4. IsBigIntElementType(type)이 true이면, number를 ? ToBigInt(value)로 둔다.
  5. 그렇지 않으면, number를 ? ToNumber(value)로 둔다.
  6. isLittleEndianToBoolean(isLittleEndian)으로 설정한다.
  7. viewOffsetview.[[ByteOffset]]으로 둔다.
  8. viewRecordMakeDataViewWithBufferWitnessRecord(view, unordered)로 둔다.
  9. NOTE: view's backing buffer가 growable SharedArrayBuffer일 때 bounds checking은 synchronizing operation이 아닙니다.
  10. IsViewOutOfBounds(viewRecord)가 true이면, TypeError exception을 throw한다.
  11. viewSizeGetViewByteLength(viewRecord)로 둔다.
  12. elementSize를 Element Type type에 대해 Table 71에 specified된 Element Size value로 둔다.
  13. getIndex + elementSize > viewSize이면, RangeError exception을 throw한다.
  14. bufferIndexgetIndex + viewOffset으로 둔다.
  15. SetValueInBuffer(view.[[ViewedArrayBuffer]], bufferIndex, type, number, false, unordered, isLittleEndian)를 수행한다.
  16. undefined를 반환한다.

25.3.2 DataView Constructor

DataView constructor는:

  • %DataView%입니다.
  • global object"DataView" property의 initial value입니다.
  • constructor로 called될 때 new DataView를 create하고 initialize합니다.
  • function으로 called되도록 intended되지 않으며, such manner로 called될 때 exception을 throw합니다.
  • 클래스 정의의 extends 절의 값으로 사용될 수 있다. 지정된 DataView 동작을 상속하려는 서브클래스 생성자는 DataView.prototype의 내장 메서드를 지원하는 데 필요한 내부 상태로 서브클래스 인스턴스를 생성하고 초기화하기 위해 DataView 생성자에 대한 super 호출을 포함해야 한다.

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

이 function은 called될 때 다음 steps를 수행합니다:

  1. NewTarget이 undefined이면, TypeError exception을 throw한다.
  2. RequireInternalSlot(buffer, [[ArrayBufferData]])를 수행한다.
  3. offset을 ? ToIndex(byteOffset)로 둔다.
  4. IsDetachedBuffer(buffer)가 true이면, TypeError exception을 throw한다.
  5. bufferByteLengthArrayBufferByteLength(buffer, seq-cst)로 둔다.
  6. offset > bufferByteLength이면, RangeError exception을 throw한다.
  7. bufferIsFixedLengthIsFixedLengthArrayBuffer(buffer)로 둔다.
  8. byteLengthundefined이면, 다음을 수행한다.
    1. bufferIsFixedLengthtrue이면, 다음을 수행한다.
      1. viewByteLengthbufferByteLength - offset으로 둔다.
    2. 그렇지 않으면,
      1. viewByteLengthauto로 둔다.
  9. 그렇지 않으면,
    1. viewByteLength를 ? ToIndex(byteLength)로 둔다.
    2. offset + viewByteLength > bufferByteLength이면, RangeError exception을 throw한다.
  10. obj를 ? OrdinaryCreateFromConstructor(NewTarget, "%DataView.prototype%", « [[DataView]], [[ViewedArrayBuffer]], [[ByteLength]], [[ByteOffset]] »)로 둔다.
  11. IsDetachedBuffer(buffer)가 true이면, TypeError exception을 throw한다.
  12. bufferByteLengthArrayBufferByteLength(buffer, seq-cst)로 설정한다.
  13. offset > bufferByteLength이면, RangeError exception을 throw한다.
  14. byteLengthundefined가 아니면, 다음을 수행한다.
    1. offset + viewByteLength > bufferByteLength이면, RangeError exception을 throw한다.
  15. obj.[[ViewedArrayBuffer]]buffer로 설정한다.
  16. obj.[[ByteLength]]viewByteLength로 설정한다.
  17. obj.[[ByteOffset]]offset으로 설정한다.
  18. obj를 반환한다.

25.3.3 DataView Constructor의 Properties

DataView constructor는:

  • value가 %Function.prototype%[[Prototype]] internal slot을 가집니다.
  • 다음 properties를 가집니다:

25.3.3.1 DataView.prototype

DataView.prototype의 initial value는 DataView prototype object입니다.

이 property는 attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }를 가집니다.

25.3.4 DataView Prototype Object의 Properties

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이 undefinedaccessor property입니다. Its get accessor function은 called될 때 다음 steps를 수행합니다:

  1. objthis value로 둔다.
  2. RequireInternalSlot(obj, [[DataView]])를 수행한다.
  3. Assert: obj[[ViewedArrayBuffer]] internal slot을 가진다.
  4. bufferobj.[[ViewedArrayBuffer]]로 둔다.
  5. buffer를 반환한다.

25.3.4.2 get DataView.prototype.byteLength

DataView.prototype.byteLength는 set accessor function이 undefinedaccessor property입니다. Its get accessor function은 called될 때 다음 steps를 수행합니다:

  1. objthis value로 둔다.
  2. RequireInternalSlot(obj, [[DataView]])를 수행한다.
  3. Assert: obj[[ViewedArrayBuffer]] internal slot을 가진다.
  4. viewRecordMakeDataViewWithBufferWitnessRecord(obj, seq-cst)로 둔다.
  5. IsViewOutOfBounds(viewRecord)가 true이면, TypeError exception을 throw한다.
  6. sizeGetViewByteLength(viewRecord)로 둔다.
  7. 𝔽(size)를 반환한다.

25.3.4.3 get DataView.prototype.byteOffset

DataView.prototype.byteOffset는 set accessor function이 undefinedaccessor property입니다. Its get accessor function은 called될 때 다음 steps를 수행합니다:

  1. objthis value로 둔다.
  2. RequireInternalSlot(obj, [[DataView]])를 수행한다.
  3. Assert: obj[[ViewedArrayBuffer]] internal slot을 가진다.
  4. viewRecordMakeDataViewWithBufferWitnessRecord(obj, seq-cst)로 둔다.
  5. IsViewOutOfBounds(viewRecord)가 true이면, TypeError exception을 throw한다.
  6. offsetobj.[[ByteOffset]]으로 둔다.
  7. 𝔽(offset)를 반환한다.

25.3.4.4 DataView.prototype.constructor

DataView.prototype.constructor의 initial value는 %DataView%입니다.

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

이 method는 called될 때 다음 steps를 수행합니다:

  1. viewthis value로 둔다.
  2. GetViewValue(view, byteOffset, littleEndian, bigint64)를 반환한다.

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

이 method는 called될 때 다음 steps를 수행합니다:

  1. viewthis value로 둔다.
  2. GetViewValue(view, byteOffset, littleEndian, biguint64)를 반환한다.

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

이 method는 called될 때 다음 steps를 수행합니다:

  1. viewthis value로 둔다.
  2. littleEndian이 present하지 않으면, littleEndianfalse로 설정한다.
  3. GetViewValue(view, byteOffset, littleEndian, float16)를 반환한다.

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

이 method는 called될 때 다음 steps를 수행합니다:

  1. viewthis value로 둔다.
  2. littleEndian이 present하지 않으면, littleEndianfalse로 설정한다.
  3. GetViewValue(view, byteOffset, littleEndian, float32)를 반환한다.

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

이 method는 called될 때 다음 steps를 수행합니다:

  1. viewthis value로 둔다.
  2. littleEndian이 present하지 않으면, littleEndianfalse로 설정한다.
  3. GetViewValue(view, byteOffset, littleEndian, float64)를 반환한다.

25.3.4.10 DataView.prototype.getInt8 ( byteOffset )

이 method는 called될 때 다음 steps를 수행합니다:

  1. viewthis value로 둔다.
  2. GetViewValue(view, byteOffset, true, int8)를 반환한다.

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

이 method는 called될 때 다음 steps를 수행합니다:

  1. viewthis value로 둔다.
  2. littleEndian이 present하지 않으면, littleEndianfalse로 설정한다.
  3. GetViewValue(view, byteOffset, littleEndian, int16)를 반환한다.

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

이 method는 called될 때 다음 steps를 수행합니다:

  1. viewthis value로 둔다.
  2. littleEndian이 present하지 않으면, littleEndianfalse로 설정한다.
  3. GetViewValue(view, byteOffset, littleEndian, int32)를 반환한다.

25.3.4.13 DataView.prototype.getUint8 ( byteOffset )

이 method는 called될 때 다음 steps를 수행합니다:

  1. viewthis value로 둔다.
  2. GetViewValue(view, byteOffset, true, uint8)를 반환한다.

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

이 method는 called될 때 다음 steps를 수행합니다:

  1. viewthis value로 둔다.
  2. littleEndian이 present하지 않으면, littleEndianfalse로 설정한다.
  3. GetViewValue(view, byteOffset, littleEndian, uint16)를 반환한다.

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

이 method는 called될 때 다음 steps를 수행합니다:

  1. viewthis value로 둔다.
  2. littleEndian이 present하지 않으면, littleEndianfalse로 설정한다.
  3. GetViewValue(view, byteOffset, littleEndian, uint32)를 반환한다.

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

이 method는 called될 때 다음 steps를 수행합니다:

  1. viewthis value로 둔다.
  2. SetViewValue(view, byteOffset, littleEndian, bigint64, value)를 반환한다.

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

이 method는 called될 때 다음 steps를 수행합니다:

  1. viewthis value로 둔다.
  2. SetViewValue(view, byteOffset, littleEndian, biguint64, value)를 반환한다.

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

이 method는 called될 때 다음 steps를 수행합니다:

  1. viewthis value로 둔다.
  2. littleEndian이 present하지 않으면, littleEndianfalse로 설정한다.
  3. SetViewValue(view, byteOffset, littleEndian, float16, value)를 반환한다.

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

이 method는 called될 때 다음 steps를 수행합니다:

  1. viewthis value로 둔다.
  2. littleEndian이 present하지 않으면, littleEndianfalse로 설정한다.
  3. SetViewValue(view, byteOffset, littleEndian, float32, value)를 반환한다.

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

이 method는 called될 때 다음 steps를 수행합니다:

  1. viewthis value로 둔다.
  2. littleEndian이 present하지 않으면, littleEndianfalse로 설정한다.
  3. SetViewValue(view, byteOffset, littleEndian, float64, value)를 반환한다.

25.3.4.21 DataView.prototype.setInt8 ( byteOffset, value )

이 method는 called될 때 다음 steps를 수행합니다:

  1. viewthis value로 둔다.
  2. SetViewValue(view, byteOffset, true, int8, value)를 반환한다.

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

이 method는 called될 때 다음 steps를 수행합니다:

  1. viewthis value로 둔다.
  2. littleEndian이 present하지 않으면, littleEndianfalse로 설정한다.
  3. SetViewValue(view, byteOffset, littleEndian, int16, value)를 반환한다.

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

이 method는 called될 때 다음 steps를 수행합니다:

  1. viewthis value로 둔다.
  2. littleEndian이 present하지 않으면, littleEndianfalse로 설정한다.
  3. SetViewValue(view, byteOffset, littleEndian, int32, value)를 반환한다.

25.3.4.24 DataView.prototype.setUint8 ( byteOffset, value )

이 method는 called될 때 다음 steps를 수행합니다:

  1. viewthis value로 둔다.
  2. SetViewValue(view, byteOffset, true, uint8, value)를 반환한다.

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

이 method는 called될 때 다음 steps를 수행합니다:

  1. viewthis value로 둔다.
  2. littleEndian이 present하지 않으면, littleEndianfalse로 설정한다.
  3. SetViewValue(view, byteOffset, littleEndian, uint16, value)를 반환한다.

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

이 method는 called될 때 다음 steps를 수행합니다:

  1. viewthis value로 둔다.
  2. littleEndian이 present하지 않으면, littleEndianfalse로 설정한다.
  3. SetViewValue(view, byteOffset, littleEndian, uint32, value)를 반환한다.

25.3.4.27 DataView.prototype [ %Symbol.toStringTag% ]

%Symbol.toStringTag% property의 initial value는 String value "DataView"입니다.

이 property는 attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }를 가집니다.

25.3.5 DataView Instances의 Properties

DataView instances는 DataView prototype object로부터 properties를 inherit하는 ordinary objects입니다. DataView instances는 각각 [[DataView]], [[ViewedArrayBuffer]], [[ByteLength]], 및 [[ByteOffset]] internal slots를 가집니다.

Note

[[DataView]] internal slot의 value는 이 specification 안에서 사용되지 않습니다. 그 internal slot의 simple presence는 DataView constructor를 사용하여 created된 objects를 identify하기 위해 specification 안에서 사용됩니다.

25.4 Atomics 객체

Atomics object는:

  • %Atomics%입니다.
  • global object"Atomics" property의 initial value입니다.
  • ordinary object입니다.
  • value가 %Object.prototype%[[Prototype]] internal slot을 가집니다.
  • [[Construct]] internal method를 가지지 않습니다; new operator와 함께 constructor로 사용될 수 없습니다.
  • [[Call]] internal method를 가지지 않습니다; function으로 invoked될 수 없습니다.

Atomics object는 shared memory array cells에 대해 indivisibly(atomically) operate하는 functions뿐 아니라 agents가 primitive events를 wait하고 dispatch할 수 있게 하는 functions를 제공합니다. disciplined하게 사용될 때, Atomics functions는 shared memory를 통해 communicate하는 multi-agent programs가 parallel CPUs에서도 well-understood order로 execute되도록 합니다. shared-memory communication을 govern하는 rules는 아래에 defined된 memory model에 의해 제공됩니다.

Note

ECMAScript에서 shared memory를 programming하고 implementing하기 위한 informative guidelines는 memory model section의 끝에 있는 notes를 참조하십시오.

25.4.1 Waiter Record

Waiter RecordAtomics.wait 또는 Atomics.waitAsync에 대한 particular call을 denote하는 데 사용되는 Record value입니다.

Waiter Record는 Table 74에 listed된 fields를 가집니다.

Table 74: Waiter Record Fields
Field Name Value Meaning
[[AgentSignifier]] an agent signifier Atomics.wait 또는 Atomics.waitAsync를 called한 agent입니다.
[[PromiseCapability]] a PromiseCapability Record or blocking Atomics.waitAsync에 대한 call을 denoting하는 경우 resulting promise이고, 그렇지 않으면 blocking입니다.
[[TimeoutTime]] a non-negative extended mathematical value timeout이 trigger될 수 있는 earliest time입니다; time values를 사용하여 computed됩니다.
[[Result]] "ok" or "timed-out" call의 return value입니다.

25.4.2 WaiterList Records

WaiterList RecordAtomics.wait, Atomics.waitAsync, 및 Atomics.notify를 통한 agents의 waiting과 notification을 explain하는 데 사용됩니다.

WaiterList Record는 Table 75에 listed된 fields를 가집니다.

Table 75: WaiterList Record Fields
Field Name Value Meaning
[[Waiters]] a List of Waiter Records 이 WaiterList가 associated된 location에서 waiting하고 있는 Atomics.wait 또는 Atomics.waitAsync에 대한 calls입니다.
[[MostRecentLeaveEvent]] a Synchronize event or empty its critical section의 most recent leaving event이거나, its critical section이 never entered된 경우 empty입니다.

same agent signifier를 가진 multiple Waiter Records가 WaiterList 안에 있을 수 있습니다.

agent cluster는 WaiterList Records의 store를 가집니다; store는 (block, i)로 indexed되며, 여기서 blockShared Data Block이고 iblock의 memory 안으로의 byte offset입니다. WaiterList Records는 agent-independent입니다: any agent in the agent cluster에서 (block, i)로 WaiterList Records의 store를 lookup하면 same WaiterList Record가 result됩니다.

Each WaiterList Record는 evaluation 동안 that WaiterList Record에 대한 exclusive access를 control하는 critical section을 가집니다. 한 번에 단일 agent만 WaiterList Record's critical section에 enter할 수 있습니다. WaiterList Record's critical section에 entering하고 leaving하는 것은 EnterCriticalSectionLeaveCriticalSection abstract operations에 의해 controlled됩니다. WaiterList Record에 대한 operations—waiting agents를 adding 및 removing하기, agents의 list를 traversing하기, list의 agents를 suspending 및 notifying하기, Synchronize event를 setting 및 retrieving하기—는 WaiterList Record's critical section에 entered한 agents에 의해서만 performed될 수 있습니다.

25.4.3 Atomics를 위한 Abstract Operations

25.4.3.1 ValidateIntegerTypedArray ( ta, waitable )

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

  1. taRecord를 ? ValidateTypedArray(ta, unordered)로 둔다.
  2. NOTE: ta's backing buffer가 growable SharedArrayBuffer일 때 bounds checking은 synchronizing operation이 아닙니다.
  3. waitabletrue이면, 다음을 수행한다.
    1. ta.[[TypedArrayName]]"Int32Array""BigInt64Array"도 아니면, TypeError exception을 throw한다.
  4. 그렇지 않으면,
    1. typeTypedArrayElementType(ta)로 둔다.
    2. IsUnclampedIntegerElementType(type)이 false이고 IsBigIntElementType(type)이 false이면, TypeError exception을 throw한다.
  5. taRecord를 반환한다.

25.4.3.2 ValidateAtomicAccess ( taRecord, requestIndex )

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

  1. lengthTypedArrayLength(taRecord)로 둔다.
  2. accessIndex를 ? ToIndex(requestIndex)로 둔다.
  3. Assert: accessIndex ≥ 0.
  4. accessIndexlength이면, RangeError exception을 throw한다.
  5. tataRecord.[[Object]]로 둔다.
  6. elementSizeTypedArrayElementSize(ta)로 둔다.
  7. offsetta.[[ByteOffset]]으로 둔다.
  8. (accessIndex × elementSize) + offset을 반환한다.

25.4.3.3 ValidateAtomicAccessOnIntegerTypedArray ( ta, requestIndex )

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

  1. taRecord를 ? ValidateIntegerTypedArray(ta, false)로 둔다.
  2. ValidateAtomicAccess(taRecord, requestIndex)를 반환한다.

25.4.3.4 RevalidateAtomicAccess ( ta, byteIndexInBuffer )

The abstract operation RevalidateAtomicAccess takes arguments ta (a TypedArray) and byteIndexInBuffer (a non-negative integer) and returns either a normal completion containing unused or a throw completion. 이 operation은 Atomics methods에서 모든 argument coercions가 performed된 후 atomic operations를 위한 backing buffer 안의 index를 revalidates합니다. argument coercions는 arbitrary side effects를 가질 수 있고, 이는 buffer가 out of bounds가 되도록 cause할 수 있기 때문입니다. 이 operation은 ta's backing buffer가 SharedArrayBuffer일 때 throw하지 않습니다. It performs the following steps when called:

  1. taRecordMakeTypedArrayWithBufferWitnessRecord(ta, unordered)로 둔다.
  2. NOTE: ta's backing buffer가 growable SharedArrayBuffer일 때 bounds checking은 synchronizing operation이 아닙니다.
  3. IsTypedArrayOutOfBounds(taRecord)가 true이면, TypeError exception을 throw한다.
  4. Assert: byteIndexInBufferta.[[ByteOffset]].
  5. byteIndexInBuffertaRecord.[[CachedBufferByteLength]]이면, RangeError exception을 throw한다.
  6. unused를 반환한다.

25.4.3.5 GetWaiterList ( block, i )

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

  1. Assert: ii + 3은 block의 memory 안에서 valid byte offsets이다.
  2. pair (block, i)에 의해 referenced되는 WaiterList Record를 반환한다.

25.4.3.6 EnterCriticalSection ( waiterList )

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

  1. Assert: surrounding agent는 any WaiterList Record에 대한 critical section 안에 있지 않다.
  2. no agentwaiterList에 대한 critical section 안에 있을 때까지 wait한 다음, waiterList에 대한 critical section에 enter한다(any other agent가 enter하는 것을 allow하지 않고).
  3. waiterList.[[MostRecentLeaveEvent]]empty가 아니면, 다음을 수행한다.
    1. NOTE: critical section이 at least once entered된 waiterListLeaveCriticalSection에 의해 set된 Synchronize event를 가집니다.
    2. agentRecordsurrounding agentAgent Record로 둔다.
    3. executionagentRecord.[[CandidateExecution]]으로 둔다.
    4. eventsRecordAgentSignifier()인 [[AgentSignifier]]를 가진 execution.[[EventsRecords]]Agent Events Record로 둔다.
    5. enterEvent를 new Synchronize event로 둔다.
    6. enterEventeventsRecord.[[EventList]]에 append한다.
    7. (waiterList.[[MostRecentLeaveEvent]], enterEvent)를 eventsRecord.[[AgentSynchronizesWith]]에 append한다.
  4. unused를 반환한다.

EnterCriticalSection은 critical section에 enter하려는 agent가 another agent가 leave할 때까지 wait해야 할 때 contention을 가집니다. contention이 없을 때, EnterCriticalSection calls의 FIFO order는 observable입니다. contention이 있을 때, implementation은 arbitrary order를 choose할 수 있지만 agent가 indefinitely wait하도록 cause해서는 안 됩니다.

25.4.3.7 LeaveCriticalSection ( waiterList )

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

  1. Assert: surrounding agentwaiterList에 대한 critical section 안에 있다.
  2. agentRecordsurrounding agentAgent Record로 둔다.
  3. executionagentRecord.[[CandidateExecution]]으로 둔다.
  4. eventsRecordAgentSignifier()인 [[AgentSignifier]]를 가진 execution.[[EventsRecords]]Agent Events Record로 둔다.
  5. leaveEvent를 new Synchronize event로 둔다.
  6. leaveEventeventsRecord.[[EventList]]에 append한다.
  7. waiterList.[[MostRecentLeaveEvent]]leaveEvent로 설정한다.
  8. waiterList에 대한 critical section을 leave한다.
  9. unused를 반환한다.

25.4.3.8 AddWaiter ( waiterList, waiterRecord )

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

  1. Assert: surrounding agentwaiterList에 대한 critical section 안에 있다.
  2. Assert: waiterList.[[Waiters]] 안에는 [[PromiseCapability]] field가 waiterRecord.[[PromiseCapability]]이고 [[AgentSignifier]] field가 waiterRecord.[[AgentSignifier]]Waiter Record가 없다.
  3. waiterRecordwaiterList.[[Waiters]]에 append한다.
  4. unused를 반환한다.

25.4.3.9 RemoveWaiter ( waiterList, waiterRecord )

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

  1. Assert: surrounding agentwaiterList에 대한 critical section 안에 있다.
  2. Assert: waiterList.[[Waiters]]waiterRecord를 contain한다.
  3. waiterRecordwaiterList.[[Waiters]]에서 remove한다.
  4. unused를 반환한다.

25.4.3.10 RemoveWaiters ( waiterList, count )

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

  1. Assert: surrounding agentwaiterList에 대한 critical section 안에 있다.
  2. lengthwaiterList.[[Waiters]] 안의 elements 수로 둔다.
  3. countmin(count, length)로 설정한다.
  4. waiters를 elements가 waiterList.[[Waiters]]의 first count elements인 List로 둔다.
  5. waiterList.[[Waiters]]의 first count elements를 remove한다.
  6. waiters를 반환한다.

25.4.3.11 SuspendThisAgent ( waiterList, waiterRecord )

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

  1. Assert: surrounding agentwaiterList에 대한 critical section 안에 있다.
  2. Assert: waiterList.[[Waiters]]waiterRecord를 contain한다.
  3. thisAgentAgentSignifier()로 둔다.
  4. Assert: waiterRecord.[[AgentSignifier]]thisAgent이다.
  5. Assert: waiterRecord.[[PromiseCapability]]blocking이다.
  6. Assert: AgentCanSuspend()는 true이다.
  7. LeaveCriticalSection(waiterList)를 수행하고 time이 waiterRecord.[[TimeoutTime]]이 될 때까지 surrounding agent를 suspend하되, critical section이 exited된 후 suspension이 effect를 가지기 전에 arriving하는 notification이 lost되지 않는 방식으로 combined operation을 수행한다. surrounding agent는 timeout 때문이거나 another agent가 arguments waiterListthisAgentNotifyWaiter를 calling하는 것(즉 Atomics.notify에 대한 call을 통해) 때문에만 suspension에서 wake할 수 있다.
  8. EnterCriticalSection(waiterList)를 수행한다.
  9. unused를 반환한다.

25.4.3.12 NotifyWaiter ( waiterList, waiterRecord )

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

  1. Assert: surrounding agentwaiterList에 대한 critical section 안에 있다.
  2. waiterRecord.[[PromiseCapability]]blocking이면, 다음을 수행한다.
    1. signifier가 waiterRecord.[[AgentSignifier]]agent를 suspension에서 wake한다.
    2. NOTE: 이는 agentSuspendThisAgent 안에서 execution을 resume하도록 causes합니다.
  3. 그렇지 않고 AgentSignifier()가 waiterRecord.[[AgentSignifier]]이면, 다음을 수행한다.
    1. promiseCapabilitywaiterRecord.[[PromiseCapability]]로 둔다.
    2. Call(promiseCapability.[[Resolve]], undefined, « waiterRecord.[[Result]] »)를 수행한다.
  4. 그렇지 않으면,
    1. EnqueueResolveInAgentJob(waiterRecord.[[AgentSignifier]], waiterRecord.[[PromiseCapability]], waiterRecord.[[Result]])를 수행한다.
  5. unused를 반환한다.
Note

agent는 another agent's promise capability를 host에 passing하는 것 beyond any capacity로 access해서는 안 됩니다.

25.4.3.13 EnqueueResolveInAgentJob ( agentSignifier, promiseCapability, resolution )

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

  1. resolveJob을 parameters가 없고 agentSignifier, promiseCapability, 및 resolution을 captures하며 called될 때 다음 steps를 수행하는 new Job Abstract Closure로 둔다:
    1. Assert: AgentSignifier()는 agentSignifier이다.
    2. Call(promiseCapability.[[Resolve]], undefined, « resolution »)를 수행한다.
    3. unused를 반환한다.
  2. realmInTargetAgent를 ! GetFunctionRealm(promiseCapability.[[Resolve]])로 둔다.
  3. Assert: agentSignifierrealmInTargetAgent.[[AgentSignifier]]이다.
  4. HostEnqueueGenericJob(resolveJob, realmInTargetAgent)를 수행한다.
  5. unused를 반환한다.

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

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

  1. taRecord를 ? ValidateIntegerTypedArray(ta, true)로 둔다.
  2. buffertaRecord.[[Object]].[[ViewedArrayBuffer]]로 둔다.
  3. IsSharedArrayBuffer(buffer)가 false이면, TypeError exception을 throw한다.
  4. byteIndexInBuffer를 ? ValidateAtomicAccess(taRecord, index)로 둔다.
  5. arrayTypeNameta.[[TypedArrayName]]으로 둔다.
  6. arrayTypeName"BigInt64Array"이면, expected를 ? ToBigInt64(value)로 둔다.
  7. 그렇지 않으면, expected를 ? ToInt32(value)로 둔다.
  8. timeoutNumber를 ? ToNumber(timeout)로 둔다.
  9. timeoutNumberNaN 또는 +∞𝔽 중 하나이면, realTimeout을 +∞로 둔다.
  10. 그렇지 않고 timeoutNumber-∞𝔽이면, realTimeout을 0으로 둔다.
  11. 그렇지 않으면, realTimeoutmax((timeoutNumber), 0)으로 둔다.
  12. modesync이고 AgentCanSuspend()가 false이면, TypeError exception을 throw한다.
  13. blockbuffer.[[ArrayBufferData]]로 둔다.
  14. waiterListGetWaiterList(block, byteIndexInBuffer)로 둔다.
  15. modesync이면, 다음을 수행한다.
    1. promiseCapabilityblocking으로 둔다.
    2. resultObjundefined로 둔다.
  16. 그렇지 않으면,
    1. promiseCapability를 ! NewPromiseCapability(%Promise%)로 둔다.
    2. resultObjOrdinaryObjectCreate(%Object.prototype%)로 둔다.
  17. EnterCriticalSection(waiterList)를 수행한다.
  18. elementTypeTypedArrayElementType(ta)로 둔다.
  19. witnessGetValueFromBuffer(buffer, byteIndexInBuffer, elementType, true, seq-cst)로 둔다.
  20. expectedwitness이면, 다음을 수행한다.
    1. LeaveCriticalSection(waiterList)를 수행한다.
    2. modesync이면, "not-equal"을 반환한다.
    3. CreateDataPropertyOrThrow(resultObj, "async", false)를 수행한다.
    4. CreateDataPropertyOrThrow(resultObj, "value", "not-equal")를 수행한다.
    5. resultObj를 반환한다.
  21. realTimeout = 0이고 modeasync이면, 다음을 수행한다.
    1. NOTE: synchronous immediate timeouts에 대한 special handling은 없습니다. Asynchronous immediate timeouts는 fail fast하고 unnecessary Promise jobs를 avoid하기 위해 special handling을 가집니다.
    2. LeaveCriticalSection(waiterList)를 수행한다.
    3. CreateDataPropertyOrThrow(resultObj, "async", false)를 수행한다.
    4. CreateDataPropertyOrThrow(resultObj, "value", "timed-out")를 수행한다.
    5. resultObj를 반환한다.
  22. thisAgentAgentSignifier()로 둔다.
  23. now를 current time을 identifying하는 time value (UTC)로 둔다.
  24. additionalTimeoutimplementation-defined non-negative mathematical value로 둔다.
  25. timeoutTime(now) + realTimeout + additionalTimeout으로 둔다.
  26. NOTE: realTimeout이 +∞일 때, timeoutTime도 +∞입니다.
  27. waiterRecord를 new Waiter Record { [[AgentSignifier]]: thisAgent, [[PromiseCapability]]: promiseCapability, [[TimeoutTime]]: timeoutTime, [[Result]]: "ok" }로 둔다.
  28. AddWaiter(waiterList, waiterRecord)를 수행한다.
  29. modesync이면, 다음을 수행한다.
    1. SuspendThisAgent(waiterList, waiterRecord)를 수행한다.
  30. 그렇지 않고 timeoutTimefinite이면, 다음을 수행한다.
    1. EnqueueAtomicsWaitAsyncTimeoutJob(waiterList, waiterRecord)를 수행한다.
  31. LeaveCriticalSection(waiterList)를 수행한다.
  32. modesync이면, waiterRecord.[[Result]]를 반환한다.
  33. CreateDataPropertyOrThrow(resultObj, "async", true)를 수행한다.
  34. CreateDataPropertyOrThrow(resultObj, "value", promiseCapability.[[Promise]])를 수행한다.
  35. resultObj를 반환한다.
Note

additionalTimeout은 power consumption을 reducing하거나 timing attacks를 mitigate하기 위해 timer resolution을 coarsening하는 것처럼, implementations가 necessary하게 timeouts를 pad할 수 있게 합니다. 이 value는 DoWait의 call마다 differ할 수 있습니다.

25.4.3.15 EnqueueAtomicsWaitAsyncTimeoutJob ( waiterList, waiterRecord )

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

  1. timeoutJob을 parameters가 없고 waiterListwaiterRecord를 captures하며 called될 때 다음 steps를 수행하는 new Job Abstract Closure로 둔다:
    1. EnterCriticalSection(waiterList)를 수행한다.
    2. waiterList.[[Waiters]]waiterRecord를 contain하면, 다음을 수행한다.
      1. timeOfJobExecution을 current time을 identifying하는 time value (UTC)로 둔다.
      2. Assert: (timeOfJobExecution) ≥ waiterRecord.[[TimeoutTime]] (time values의 potential non-monotonicity를 ignoring함).
      3. waiterRecord.[[Result]]"timed-out"으로 설정한다.
      4. RemoveWaiter(waiterList, waiterRecord)를 수행한다.
      5. NotifyWaiter(waiterList, waiterRecord)를 수행한다.
    3. LeaveCriticalSection(waiterList)를 수행한다.
    4. unused를 반환한다.
  2. now를 current time을 identifying하는 time value (UTC)로 둔다.
  3. currentRealm을 current Realm Record로 둔다.
  4. HostEnqueueTimeoutJob(timeoutJob, currentRealm, 𝔽(waiterRecord.[[TimeoutTime]]) - now)를 수행한다.
  5. unused를 반환한다.

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

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

  1. agentRecordsurrounding agentAgent Record로 둔다.
  2. executionagentRecord.[[CandidateExecution]]으로 둔다.
  3. eventsRecordAgentSignifier()인 [[AgentSignifier]]를 가진 execution.[[EventsRecords]]Agent Events Record로 둔다.
  4. rawBytesRead를 elements가 nondeterministically chosen byte values인 length elementSizeList로 둔다.
  5. NOTE: implementations에서 rawBytesRead는 underlying hardware의 load-link, load-exclusive, 또는 read-modify-write instruction의 operand의 result입니다. nondeterminism은 weak consistency를 가진 hardware의 observable behaviour를 describe하기 위한 memory model의 semantic prescription입니다.
  6. NOTE: expected value와 read value의 comparison은 expected value가 read value와 equal하지 않을 때 needlessly strong synchronization을 avoid하기 위해 read-modify-write modification function 밖에서 performed됩니다.
  7. ByteListEqual(rawBytesRead, expectedBytes)가 true이면, 다음을 수행한다.
    1. second를 parameters (oldBytes, newBytes)를 가지고 nothing을 captures하며 called될 때 atomically 다음 steps를 수행하는 new read-modify-write modification function으로 둔다:
      1. newBytes를 반환한다.
    2. eventReadModifyWriteSharedMemory { [[Order]]: seq-cst, [[NoTear]]: true, [[Block]]: block, [[ByteIndex]]: byteIndexInBuffer, [[ElementSize]]: elementSize, [[Payload]]: replacementBytes, [[ModifyOp]]: second }로 둔다.
  8. 그렇지 않으면,
    1. eventReadSharedMemory { [[Order]]: seq-cst, [[NoTear]]: true, [[Block]]: block, [[ByteIndex]]: byteIndexInBuffer, [[ElementSize]]: elementSize }로 둔다.
  9. eventeventsRecord.[[EventList]]에 append한다.
  10. Chosen Value Record { [[Event]]: event, [[ChosenValue]]: rawBytesRead }를 execution.[[ChosenValues]]에 append한다.
  11. rawBytesRead를 반환한다.

25.4.3.17 AtomicReadModifyWrite ( ta, index, value, op )

The abstract operation AtomicReadModifyWrite takes arguments ta (an ECMAScript language value), index (an ECMAScript language value), value (an ECMAScript language value), and op (a read-modify-write modification function) and returns either a normal completion containing either a Number or a BigInt, or a throw completion. opbyte values의 두 List arguments를 takes하고 byte valuesList를 returns합니다. 이 operation은 atomically value를 loads하고, 이를 another value와 combines하며, combination을 stores합니다. It returns the loaded value. It performs the following steps when called:

  1. byteIndexInBuffer를 ? ValidateAtomicAccessOnIntegerTypedArray(ta, index)로 둔다.
  2. ta.[[ContentType]]bigint이면, coerced를 ? ToBigInt(value)로 둔다.
  3. 그렇지 않으면, coerced𝔽(? ToIntegerOrInfinity(value))로 둔다.
  4. RevalidateAtomicAccess(ta, byteIndexInBuffer)를 수행한다.
  5. bufferta.[[ViewedArrayBuffer]]로 둔다.
  6. elementTypeTypedArrayElementType(ta)로 둔다.
  7. GetModifySetValueInBuffer(buffer, byteIndexInBuffer, elementType, coerced, op)를 반환한다.

25.4.3.18 ByteListBitwiseOp ( op, xBytes, yBytes )

The abstract operation ByteListBitwiseOp takes arguments op (&, ^, or |), xBytes (a List of byte values), and yBytes (a List of byte values) and returns a List of byte values. 이 operation은 arguments의 모든 byte values에 대해 bitwise operation을 atomically performs하고 byte valuesList를 returns합니다. It performs the following steps when called:

  1. Assert: xBytesyBytes는 same number of elements를 가진다.
  2. result를 new empty List로 둔다.
  3. i를 0으로 둔다.
  4. xBytes의 each element xByte에 대해, 다음을 수행한다.
    1. yByteyBytes[i]로 둔다.
    2. op&이면, 다음을 수행한다.
      1. resultBytexByteyByte에 bitwise AND operation을 applying한 result로 둔다.
    3. 그렇지 않고 op^이면, 다음을 수행한다.
      1. resultBytexByteyByte에 bitwise exclusive OR (XOR) operation을 applying한 result로 둔다.
    4. 그렇지 않으면,
      1. Assert: op|이다.
      2. resultBytexByteyByte에 bitwise inclusive OR operation을 applying한 result로 둔다.
    5. ii + 1로 설정한다.
    6. resultByteresult에 append한다.
  5. result를 반환한다.

25.4.3.19 ByteListEqual ( xBytes, yBytes )

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

  1. xBytesyBytes가 same number of elements를 가지지 않으면, false를 반환한다.
  2. i를 0으로 둔다.
  3. xBytes의 each element xByte에 대해, 다음을 수행한다.
    1. yByteyBytes[i]로 둔다.
    2. xByteyByte이면, false를 반환한다.
    3. ii + 1로 설정한다.
  4. true를 반환한다.

25.4.4 Atomics.add ( ta, index, value )

이 function은 called될 때 다음 steps를 수행합니다:

  1. add를 parameters (xBytes, yBytes)를 가지고 ta를 captures하며 called될 때 atomically 다음 steps를 수행하는 new read-modify-write modification function으로 둔다:
    1. typeTypedArrayElementType(ta)로 둔다.
    2. agentRecordsurrounding agentAgent Record로 둔다.
    3. isLittleEndianagentRecord.[[LittleEndian]]으로 둔다.
    4. xRawBytesToNumeric(type, xBytes, isLittleEndian)으로 둔다.
    5. yRawBytesToNumeric(type, yBytes, isLittleEndian)으로 둔다.
    6. x가 Number이면, 다음을 수행한다.
      1. sumNumber::add(x, y)로 둔다.
    7. 그렇지 않으면,
      1. Assert: x는 BigInt이다.
      2. sumBigInt::add(x, y)로 둔다.
    8. sumBytesNumericToRawBytes(type, sum, isLittleEndian)로 둔다.
    9. Assert: sumBytes, xBytes, 및 yBytes는 same number of elements를 가진다.
    10. sumBytes를 반환한다.
  2. AtomicReadModifyWrite(ta, index, value, add)를 반환한다.

25.4.5 Atomics.and ( ta, index, value )

이 function은 called될 때 다음 steps를 수행합니다:

  1. and를 parameters (xBytes, yBytes)를 가지고 nothing을 captures하며 called될 때 atomically 다음 steps를 수행하는 new read-modify-write modification function으로 둔다:
    1. ByteListBitwiseOp(&, xBytes, yBytes)를 반환한다.
  2. AtomicReadModifyWrite(ta, index, value, and)를 반환한다.

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

이 function은 called될 때 다음 steps를 수행합니다:

  1. byteIndexInBuffer를 ? ValidateAtomicAccessOnIntegerTypedArray(ta, index)로 둔다.
  2. bufferta.[[ViewedArrayBuffer]]로 둔다.
  3. blockbuffer.[[ArrayBufferData]]로 둔다.
  4. ta.[[ContentType]]bigint이면, 다음을 수행한다.
    1. expected를 ? ToBigInt(expectedValue)로 둔다.
    2. replacement를 ? ToBigInt(replacementValue)로 둔다.
  5. 그렇지 않으면,
    1. expected𝔽(? ToIntegerOrInfinity(expectedValue))로 둔다.
    2. replacement𝔽(? ToIntegerOrInfinity(replacementValue))로 둔다.
  6. RevalidateAtomicAccess(ta, byteIndexInBuffer)를 수행한다.
  7. elementTypeTypedArrayElementType(ta)로 둔다.
  8. elementSizeTypedArrayElementSize(ta)로 둔다.
  9. agentRecordsurrounding agentAgent Record로 둔다.
  10. isLittleEndianagentRecord.[[LittleEndian]]으로 둔다.
  11. expectedBytesNumericToRawBytes(elementType, expected, isLittleEndian)로 둔다.
  12. replacementBytesNumericToRawBytes(elementType, replacement, isLittleEndian)로 둔다.
  13. IsSharedArrayBuffer(buffer)가 true이면, 다음을 수행한다.
    1. rawBytesReadAtomicCompareExchangeInSharedBlock(block, byteIndexInBuffer, elementSize, expectedBytes, replacementBytes)로 둔다.
  14. 그렇지 않으면,
    1. rawBytesRead를 elements가 block[byteIndexInBuffer]로 starting하는 elementSize bytes의 sequence인 length elementSizeList로 둔다.
    2. ByteListEqual(rawBytesRead, expectedBytes)가 true이면, 다음을 수행한다.
      1. replacementBytes의 individual bytes를 block 안에, block[byteIndexInBuffer]에서 starting하여 store한다.
  15. RawBytesToNumeric(elementType, rawBytesRead, isLittleEndian)을 반환한다.

25.4.7 Atomics.exchange ( ta, index, value )

이 function은 called될 때 다음 steps를 수행합니다:

  1. second를 parameters (oldBytes, newBytes)를 가지고 nothing을 captures하며 called될 때 atomically 다음 steps를 수행하는 new read-modify-write modification function으로 둔다:
    1. newBytes를 반환한다.
  2. AtomicReadModifyWrite(ta, index, value, second)를 반환한다.

25.4.8 Atomics.isLockFree ( size )

이 function은 called될 때 다음 steps를 수행합니다:

  1. n을 ? ToIntegerOrInfinity(size)로 둔다.
  2. agentRecordsurrounding agentAgent Record로 둔다.
  3. n = 1이면, agentRecord.[[IsLockFree1]]을 반환한다.
  4. n = 2이면, agentRecord.[[IsLockFree2]]를 반환한다.
  5. n = 4이면, true를 반환한다.
  6. n = 8이면, agentRecord.[[IsLockFree8]]을 반환한다.
  7. false를 반환한다.
Note

이 function은 optimization primitive입니다. intuition은 size n bytes인 datum에 대한 atomic primitive(compareExchange, load, store, add, sub, and, or, xor, 또는 exchange)의 atomic step이 datum을 comprising하는 n bytes outside의 lock을 surrounding agent가 acquiring하지 않고 performed될 것이라면, Atomics.isLockFree(n)가 true를 반환한다는 것입니다. High-performance algorithms는 critical sections에서 locks를 사용할지 atomic operations를 사용할지 determine하기 위해 이 function을 사용할 것입니다. atomic primitive가 lock-free가 아니면 algorithm이 its own locking을 provide하는 것이 often more efficient합니다.

Atomics.isLockFree(4)는 all known relevant hardware에서 supported될 수 있으므로 always true를 반환합니다. 이를 assume할 수 있음은 generally programs를 simplify할 것입니다.

이 function이 반환하는 value와 관계없이, all atomic operations는 atomic하다고 guaranteed됩니다. 예를 들어, operation 중간에 visible operation이 take place하는 일은 never 없습니다(예: “tearing”).

25.4.9 Atomics.load ( ta, index )

이 function은 called될 때 다음 steps를 수행합니다:

  1. byteIndexInBuffer를 ? ValidateAtomicAccessOnIntegerTypedArray(ta, index)로 둔다.
  2. RevalidateAtomicAccess(ta, byteIndexInBuffer)를 수행한다.
  3. bufferta.[[ViewedArrayBuffer]]로 둔다.
  4. elementTypeTypedArrayElementType(ta)로 둔다.
  5. GetValueFromBuffer(buffer, byteIndexInBuffer, elementType, true, seq-cst)를 반환한다.

25.4.10 Atomics.notify ( ta, index, count )

이 함수는 대기 큐에서 잠자고 있는 일부 에이전트에게 알린다.

호출될 때 다음 단계를 수행한다:

  1. taRecord를 ? ValidateIntegerTypedArray(ta, true)라고 하자.
  2. byteIndexInBuffer를 ? ValidateAtomicAccess(taRecord, index)라고 하자.
  3. countundefined이면,
    1. count를 +∞로 설정한다.
  4. 그렇지 않으면,
    1. intCount를 ? ToIntegerOrInfinity(count)라고 하자.
    2. countmax(intCount, 0)으로 설정한다.
  5. bufferta.[[ViewedArrayBuffer]]라고 하자.
  6. blockbuffer.[[ArrayBufferData]]라고 하자.
  7. IsSharedArrayBuffer(buffer)가 false이면, +0𝔽를 반환한다.
  8. waiterListGetWaiterList(block, byteIndexInBuffer)라고 하자.
  9. EnterCriticalSection(waiterList)를 수행한다.
  10. waitersRemoveWaiters(waiterList, count)라고 하자.
  11. waiters의 각 요소 waiterRecord에 대해, 다음을 수행한다.
    1. NotifyWaiter(waiterList, waiterRecord)를 수행한다.
  12. LeaveCriticalSection(waiterList)를 수행한다.
  13. waitersCountwaiters 안의 요소 수라고 하자.
  14. 𝔽(waitersCount)를 반환한다.

25.4.11 Atomics.or ( ta, index, value )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. or를 매개변수 (xBytes, yBytes)를 가지고 아무것도 캡처하지 않으며 호출될 때 다음 단계를 원자적으로 수행하는 새 read-modify-write 수정 함수라고 하자:
    1. ByteListBitwiseOp(|, xBytes, yBytes)를 반환한다.
  2. AtomicReadModifyWrite(ta, index, value, or)를 반환한다.

25.4.12 Atomics.pause ( )

이 함수는 프로그램이 어떤 값을 기다리면서 스핀 루프 중이라는 힌트를 CPU에 제공한다.

호출될 때 다음 단계를 수행한다:

  1. ECMAScript 구현의 실행 환경이 현재 실행 중인 코드가 spin-wait 루프 안에 있음을 운영체제나 CPU에 신호로 알리는 것을 지원하면, 그 신호를 보낸다.
  2. undefined를 반환한다.
Note 1

이 메서드는 뮤텍스 내부의 spinlock fast path와 같이 spin-wait 루프를 구현하는 프로그램이, 어떤 값을 기다리는 동안 스핀 중이라는 힌트를 CPU에 제공하도록 설계되었다. 이 메서드는 타이밍 외에는 관찰 가능한 동작이 없다.

기반 아키텍처의 모범 사례가 스핀 루프에서 그러한 명령어를 권장하는 경우, 구현은 pause 또는 yield 명령어를 구현할 것으로 기대된다. 예를 들어, Intel 최적화 매뉴얼pause 명령어를 권장한다.

구현은 일시 정지되는 최대 시간에 대해 수십에서 수백 나노초 정도의 내부 상한을 두는 것이 권장된다.

Note 2

함수 호출의 오버헤드 때문에, 최적화 컴파일러에서 이 메서드에 대한 인라인 호출이 인라인되지 않은 호출과 다른 시간 동안 기다리는 것은 합리적이다.

25.4.13 Atomics.store ( ta, index, value )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. byteIndexInBuffer를 ? ValidateAtomicAccessOnIntegerTypedArray(ta, index)라고 하자.
  2. ta.[[ContentType]]bigint이면, coerced를 ? ToBigInt(value)라고 하자.
  3. 그렇지 않으면, coerced𝔽(? ToIntegerOrInfinity(value))라고 하자.
  4. RevalidateAtomicAccess(ta, byteIndexInBuffer)를 수행한다.
  5. bufferta.[[ViewedArrayBuffer]]라고 하자.
  6. elementTypeTypedArrayElementType(ta)이라고 하자.
  7. SetValueInBuffer(buffer, byteIndexInBuffer, elementType, coerced, true, seq-cst)를 수행한다.
  8. coerced를 반환한다.

25.4.14 Atomics.sub ( ta, index, value )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. subtract를 매개변수 (xBytes, yBytes)를 가지고 ta를 캡처하며 호출될 때 다음 단계를 원자적으로 수행하는 새 read-modify-write 수정 함수라고 하자:
    1. typeTypedArrayElementType(ta)이라고 하자.
    2. agentRecord를 둘러싸는 에이전트의 Agent Record라고 하자.
    3. isLittleEndianagentRecord.[[LittleEndian]]이라고 하자.
    4. xRawBytesToNumeric(type, xBytes, isLittleEndian)이라고 하자.
    5. yRawBytesToNumeric(type, yBytes, isLittleEndian)이라고 하자.
    6. x가 Number이면,
      1. differenceNumber::subtract(x, y)라고 하자.
    7. 그렇지 않으면,
      1. 단언: x는 BigInt이다.
      2. differenceBigInt::subtract(x, y)라고 하자.
    8. differenceBytesNumericToRawBytes(type, difference, isLittleEndian)라고 하자.
    9. 단언: differenceBytes, xBytes, yBytes는 같은 수의 요소를 가진다.
    10. differenceBytes를 반환한다.
  2. AtomicReadModifyWrite(ta, index, value, subtract)를 반환한다.

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

이 함수는 둘러싸는 에이전트를 대기 큐에 넣고 알림을 받거나 대기 시간이 초과될 때까지 이를 일시 중단하며, 이러한 경우를 구분하는 String을 반환한다.

호출될 때 다음 단계를 수행한다:

  1. DoWait(sync, ta, index, value, timeout)를 반환한다.

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

이 함수는 호출한 에이전트가 알림을 받거나 timeout에 도달했을 때 해결되는 Promise를 반환한다.

호출될 때 다음 단계를 수행한다:

  1. DoWait(async, ta, index, value, timeout)를 반환한다.

25.4.17 Atomics.xor ( ta, index, value )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. xor를 매개변수 (xBytes, yBytes)를 가지고 아무것도 캡처하지 않으며 호출될 때 다음 단계를 원자적으로 수행하는 새 read-modify-write 수정 함수라고 하자:
    1. ByteListBitwiseOp(^, xBytes, yBytes)를 반환한다.
  2. AtomicReadModifyWrite(ta, index, value, xor)를 반환한다.

25.4.18 Atomics [ %Symbol.toStringTag% ]

%Symbol.toStringTag% 속성의 초기값은 String 값 "Atomics"이다.

이 속성은 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true } 속성을 가진다.

25.5 JSON 객체

JSON object는:

  • %JSON%입니다.
  • global object"JSON" property의 initial value입니다.
  • ordinary object입니다.
  • JSON texts를 parse하고 construct하는 데 사용되는 두 functions, parsestringify를 contains합니다.
  • value가 %Object.prototype%[[Prototype]] internal slot을 가집니다.
  • [[Construct]] internal method를 가지지 않습니다; new operator와 함께 constructor로 사용될 수 없습니다.
  • [[Call]] internal method를 가지지 않습니다; function으로 invoked될 수 없습니다.

JSON Data Interchange Format은 ECMA-404에 defined되어 있습니다. 이 specification에서 사용되는 JSON interchange format은 ECMA-404에 의해 described된 것과 exactly 같습니다. JSON.parseJSON.stringify의 conforming implementations는 ECMA-404 specification에 described된 exact interchange format을, format에 대한 deletions나 extensions 없이 support해야 합니다.

25.5.1 JSON.isRawJSON ( obj )

이 function은 called될 때 다음 steps를 수행합니다:

  1. obj가 Object이고 obj[[IsRawJSON]] internal slot을 가지면, true를 반환한다.
  2. false를 반환한다.

25.5.2 JSON.parse ( text [ , reviver ] )

이 function은 JSON text(JSON-formatted String)를 parses하고 ECMAScript language value를 produces합니다. JSON format은 literals, arrays, 및 objects를 ECMAScript literals, Array Initializers, 및 Object Initializers에 대한 syntax와 similar한 syntax로 represents합니다. 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된 each value에 대해, reviver는 three arguments(associated property key, value, 및 context object)와 함께 called됩니다. property가 unmodified이고 그 value가 primitive이면, provided context object는 corresponding Parse Node의 source text를 containing하는 "source" property를 가집니다. call이 undefined를 반환하면 property는 deleted됩니다. 그렇지 않으면 property는 return value를 사용하도록 redefined됩니다.

  1. jsonString을 ? ToString(text)로 둔다.
  2. parseResult를 ? ParseJSON(jsonString)으로 둔다.
  3. unfilteredparseResult.[[Value]]로 둔다.
  4. IsCallable(reviver)가 false이면, unfiltered를 반환한다.
  5. rootOrdinaryObjectCreate(%Object.prototype%)로 둔다.
  6. rootName을 empty String으로 둔다.
  7. CreateDataPropertyOrThrow(root, rootName, unfiltered)를 수행한다.
  8. snapshotCreateJSONParseRecord(parseResult.[[ParseNode]], rootName, unfiltered)로 둔다.
  9. InternalizeJSONProperty(root, rootName, reviver, snapshot)를 반환한다.

이 function의 "length" property는 2𝔽입니다.

25.5.2.1 ParseJSON ( text )

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

  1. StringToCodePoints(text)가 ECMA-404에 specified된 valid JSON text가 아니면, SyntaxError exception을 throw한다.
  2. scriptString"(", text, 및 ");"string-concatenation으로 둔다.
  3. scriptParseText(scriptString, Script)로 둔다.
  4. NOTE: 13.2.5.1에 defined된 early error rules는 위 ParseText invocation에 대해 special handling을 가집니다.
  5. Assert: scriptParse Node이다.
  6. result를 ! Evaluation of script로 둔다.
  7. NOTE: 13.2.5.6에 defined된 PropertyDefinitionEvaluation semantics는 위 evaluation에 대해 special handling을 가집니다.
  8. Assert: result는 String, Number, Boolean, ArrayLiteral 또는 ObjectLiteral 중 하나에 의해 defined된 Object, 또는 null 중 하나이다.
  9. Record { [[ParseNode]]: script, [[Value]]: result }를 반환한다.

JSON.parse의 conforming implementation이 JSON grammars를 extend하는 것은 permitted되지 않습니다. implementation이 modified 또는 extended JSON interchange format을 support하려면, different parse function을 defining하여 그렇게 해야 합니다.

Note 1

Valid JSON text는 ECMAScript PrimaryExpression syntax의 subset입니다. Step 1jsonString이 that subset에 conforms함을 verifies하고, step 8는 evaluation이 appropriate type의 value를 returns함을 asserts합니다.

그러나 13.2.5.6가 ParseJSON 동안 differently behaves하기 때문에, same source text는 JSON이 아니라 PrimaryExpression으로 evaluated될 때 different results를 produce할 수 있습니다. Furthermore, object literals 안의 duplicate "__proto__" properties에 대한 Early Error도 likewise 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
Field Name Value Meaning
[[ParseNode]] a Parse Node context Parse Node입니다.
[[Key]] a property name [[Value]]가 associated된 property name입니다.
[[Value]] an ECMAScript language value [[ParseNode]]의 evaluation에 의해 produced된 value입니다.
[[Elements]] a List of JSON Parse Records [[Value]]가 Array이면, 이는 [[Value]]의 elements에 corresponding하는 JSON Parse Records를 contains합니다. 그렇지 않으면, 이는 empty List입니다.
[[Entries]] a List of JSON Parse Records [[Value]]가 non-Array Object이면, 이는 [[Value]]의 entries에 corresponding하는 JSON Parse Records를 contains합니다. 그렇지 않으면, 이는 empty List입니다.

25.5.2.3 CreateJSONParseRecord ( parseNode, key, value )

The abstract operation CreateJSONParseRecord takes arguments parseNode (a Parse Node), key (a property name), and value (an ECMAScript language value) and returns a JSON Parse Record. JSON text에서 parsed된 parseNode와 그 evaluation에 의해 produced된 value를 recursively combines합니다. It performs the following steps when called:

  1. typedValueNodeShallowestContainedJSONValue(parseNode)로 둔다.
  2. Assert: typedValueNodeempty가 아니다.
  3. elements를 new empty List로 둔다.
  4. entries를 new empty List로 둔다.
  5. value가 Object이면, 다음을 수행한다.
    1. isArray를 ! IsArray(value)로 둔다.
    2. isArraytrue이면, 다음을 수행한다.
      1. Assert: typedValueNodeArrayLiteral Parse Node이다.
      2. contentNodestypedValueNodeJSONArrayLiteralContentNodes로 둔다.
      3. lengthcontentNodes 안의 elements 수로 둔다.
      4. valueLength를 ! LengthOfArrayLike(value)로 둔다.
      5. Assert: valueLengthlength이다.
      6. index를 0으로 둔다.
      7. Repeat, while index < length,
        1. propertyName을 ! ToString(𝔽(index))로 둔다.
        2. elementParseRecordCreateJSONParseRecord(contentNodes[index], propertyName, ! Get(value, propertyName))로 둔다.
        3. elementParseRecordelements에 append한다.
        4. indexindex + 1로 설정한다.
    3. 그렇지 않으면,
      1. Assert: typedValueNodeObjectLiteral Parse Node이다.
      2. propertyNodestypedValueNodePropertyDefinitionNodes로 둔다.
      3. NOTE: value가 JSON text에서 produced되었고 modified되지 않았기 때문에, its property keys는 모두 Strings이고 exhaustively enumerated될 것입니다.
      4. keys를 ! EnumerableOwnProperties(value, key)로 둔다.
      5. keys의 each String propertyKey에 대해, 다음을 수행한다.
        1. NOTE: single object에 대해 same name을 가진 multiple name/value pairs를 specifying하는 JSON text의 경우(예: {"a":"lost","a":"kept"}), resulting ECMAScript object의 corresponding property에 대한 value는 that name을 가진 last pair로 specified됩니다.
        2. propertyDefinitionempty로 둔다.
        3. propertyNodes의 each Parse Node propertyNode에 대해, 다음을 수행한다.
          1. propertyNamepropertyNodePropName으로 둔다.
          2. propertyNamepropertyKey이면, propertyDefinitionpropertyNode로 설정한다.
        4. Assert: propertyDefinition PropertyDefinition : PropertyName : AssignmentExpression 이다.
        5. propertyValueNodepropertyDefinitionAssignmentExpression으로 둔다.
        6. entryParseRecordCreateJSONParseRecord(propertyValueNode, propertyKey, ! Get(value, propertyKey))로 둔다.
        7. entryParseRecordentries에 append한다.
  6. 그렇지 않으면,
    1. Assert: typedValueNodeArrayLiteral Parse NodeObjectLiteral Parse Node도 아니다.
  7. JSON Parse Record { [[ParseNode]]: typedValueNode, [[Key]]: key, [[Value]]: value, [[Elements]]: elements, [[Entries]]: entries }를 반환한다.

25.5.2.4 InternalizeJSONProperty ( holder, name, reviver, parseRecord )

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

Note

이 algorithm은 [[Delete]] 또는 CreateDataProperty 중 하나가 false를 반환해도 intentionally exception을 throw하지 않습니다.

called될 때 다음 steps를 수행합니다:

  1. value를 ? Get(holder, name)로 둔다.
  2. contextOrdinaryObjectCreate(%Object.prototype%)로 둔다.
  3. parseRecordJSON Parse Record이고 SameValue(parseRecord.[[Value]], value)가 true이면, 다음을 수행한다.
    1. value가 Object가 아니면, 다음을 수행한다.
      1. parseNodeparseRecord.[[ParseNode]]로 둔다.
      2. Assert: parseNodeArrayLiteral Parse NodeObjectLiteral Parse Node도 아니다.
      3. sourceTextparseNode에 의해 matched된 source text로 둔다.
      4. CreateDataPropertyOrThrow(context, "source", CodePointsToString(sourceText))를 수행한다.
    2. elementRecordsparseRecord.[[Elements]]로 둔다.
    3. entryRecordsparseRecord.[[Entries]]로 둔다.
  4. 그렇지 않으면,
    1. elementRecords를 new empty List로 둔다.
    2. entryRecords를 new empty List로 둔다.
  5. value가 Object이면, 다음을 수행한다.
    1. isArray를 ? IsArray(value)로 둔다.
    2. isArraytrue이면, 다음을 수행한다.
      1. elementRecordsLengthelementRecords 안의 elements 수로 둔다.
      2. length를 ? LengthOfArrayLike(value)로 둔다.
      3. index를 0으로 둔다.
      4. Repeat, while index < length,
        1. propertyKey를 ! ToString(𝔽(index))로 둔다.
        2. index < elementRecordsLength이면, elementRecordelementRecords[index]로 둔다; 그렇지 않으면 elementRecordempty로 둔다.
        3. newElement를 ? InternalizeJSONProperty(value, propertyKey, reviver, elementRecord)로 둔다.
        4. newElementundefined이면, 다음을 수행한다.
          1. value.[[Delete]](propertyKey)를 수행한다.
        5. 그렇지 않으면,
          1. CreateDataProperty(value, propertyKey, newElement)를 수행한다.
        6. indexindex + 1로 설정한다.
    3. 그렇지 않으면,
      1. keys를 ? EnumerableOwnProperties(value, key)로 둔다.
      2. keys의 each String propertyKey에 대해, 다음을 수행한다.
        1. entryRecords의 element entryentry.[[Key]]propertyKey인 것이 존재하면, entryRecordentry로 둔다; 그렇지 않으면 entryRecordempty로 둔다.
        2. newElement를 ? InternalizeJSONProperty(value, propertyKey, reviver, entryRecord)로 둔다.
        3. newElementundefined이면, 다음을 수행한다.
          1. value.[[Delete]](propertyKey)를 수행한다.
        4. 그렇지 않으면,
          1. CreateDataProperty(value, propertyKey, newElement)를 수행한다.
  6. Call(reviver, holder, « name, value, context »)를 반환한다.

25.5.2.5 Static Semantics: ShallowestContainedJSONValue ( root )

The abstract operation ShallowestContainedJSONValue takes argument root (a Parse Node) and returns a Parse Node or empty. root에 rooted된 parse tree의 breadth-first search를 performs하고, JSON value에 corresponding하는 nonterminal의 instance인 first node를 returns하거나, such node가 없으면 empty를 returns합니다. It performs the following steps when called:

  1. activeFunc를 active function object로 둔다.
  2. Assert: activeFuncJSON.parse built-in function object이다(JSON.parse 참조).
  3. types를 « NullLiteral, BooleanLiteral, NumericLiteral, StringLiteral, ArrayLiteral, ObjectLiteral, UnaryExpression »로 둔다.
  4. unaryExprempty로 둔다.
  5. queue를 « root »로 둔다.
  6. Repeat, while queue is not empty,
    1. candidatequeue의 first element로 둔다.
    2. queue에서 first element를 remove한다.
    3. queuedChildrenfalse로 둔다.
    4. types의 each nonterminal type에 대해, 다음을 수행한다.
      1. candidatetype의 instance이면, 다음을 수행한다.
        1. NOTE: JSON grammar에서 number token은 negative value를 represent할 수 있습니다. ECMAScript에서 negation은 UnaryExpression- 뒤에 derived UnaryExpression이 오는 것으로 parses되는 unary operation으로 represented됩니다.
        2. typeUnaryExpression이면, 다음을 수행한다.
          1. candidate의 parent가 UnaryExpression Parse Node가 아니면, unaryExprcandidate로 설정한다.
        3. 그렇지 않고 typeNumericLiteral이면, 다음을 수행한다.
          1. Assert: candidateunaryExpr 안에 contained된다.
          2. unaryExpr를 반환한다.
        4. 그렇지 않으면,
          1. candidate를 반환한다.
      2. queuedChildrenfalse이고, candidate가 nonterminal의 instance이며, candidate Contains typetrue이면, 다음을 수행한다.
        1. childrencandidate의 each child node를 in order로 containing하는 List로 둔다.
        2. queuequeuechildrenlist-concatenation으로 설정한다.
        3. queuedChildrentrue로 설정한다.
  7. empty를 반환한다.

25.5.2.6 Static Semantics: JSONArrayLiteralContentNodes

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

ArrayLiteral : [ Elisionopt ] [ ElementList ] [ ElementList , Elisionopt ]
  1. Assert: Elision은 present하지 않는다.
  2. ElementList가 present하지 않으면, new empty List를 반환한다.
  3. ElementListJSONArrayLiteralContentNodes를 반환한다.
ElementList : Elisionopt AssignmentExpression
  1. Assert: Elision은 present하지 않는다.
  2. « AssignmentExpression »를 반환한다.
ElementList : ElementList , Elisionopt AssignmentExpression
  1. Assert: Elision은 present하지 않는다.
  2. elements를 derived ElementListJSONArrayLiteralContentNodes로 둔다.
  3. elements와 « AssignmentExpression »의 list-concatenation을 반환한다.
ElementList : Elisionopt SpreadElement ElementList , Elisionopt SpreadElement
  1. NOTE: ECMA-404에 specified된 JSON text는 SpreadElement를 include하지 않습니다.
  2. Assert: 이 step은 never reached된다.

25.5.3 JSON.rawJSON ( text )

이 function은 string, number, boolean, 또는 null value의 raw JSON text를 representing하는 object를 반환합니다.

  1. jsonString을 ? ToString(text)로 둔다.
  2. jsonString이 empty String이면, SyntaxError exception을 throw한다.
  3. jsonString의 first code unit이 ASCII lowercase letter code unit(0x0061부터 0x007A까지, inclusive), ASCII digit code unit(0x0030부터 0x0039까지, inclusive), 0x0022 (QUOTATION MARK), 또는 0x002D (HYPHEN-MINUS) 중 어느 것도 아니면, SyntaxError exception을 throw한다.
  4. jsonString의 last code unit이 ASCII lowercase letter code unit(0x0061부터 0x007A까지, inclusive), ASCII digit code unit(0x0030부터 0x0039까지, inclusive), 또는 0x0022 (QUOTATION MARK) 중 어느 것도 아니면, SyntaxError exception을 throw한다.
  5. parseResult를 ? ParseJSON(jsonString)으로 둔다.
  6. Assert: parseResult.[[Value]]는 String, Number, Boolean, 또는 null 중 하나이다.
  7. internalSlotsList를 « [[IsRawJSON]] »로 둔다.
  8. objOrdinaryObjectCreate(null, internalSlotsList)로 둔다.
  9. CreateDataPropertyOrThrow(obj, "rawJSON", jsonString)를 수행한다.
  10. SetIntegrityLevel(obj, frozen)을 수행한다.
  11. obj를 반환한다.

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

이 function은 ECMAScript language value를 representing하는 UTF-16 encoded JSON format의 String 또는 undefined를 반환합니다. 세 parameters를 받을 수 있습니다. value parameter는 ECMAScript language value로, usually object 또는 array이지만 String, Boolean, Number 또는 null일 수도 있습니다. optional replacer parameter는 objects와 arrays가 stringified되는 방식을 alters하는 function이거나, stringified될 object properties를 selecting하기 위한 inclusion list로 acts하는 Strings 및 Numbers의 array입니다. optional space parameter는 result에 human readability를 improve하기 위한 white space가 injected되도록 하는 String 또는 Number입니다.

called될 때 다음 steps를 수행합니다:

  1. stack을 new empty List로 둔다.
  2. indent를 empty String으로 둔다.
  3. propertyListundefined로 둔다.
  4. replacerFuncundefined로 둔다.
  5. replacer가 Object이면, 다음을 수행한다.
    1. IsCallable(replacer)가 true이면, 다음을 수행한다.
      1. replacerFuncreplacer로 설정한다.
    2. 그렇지 않으면,
      1. isArray를 ? IsArray(replacer)로 둔다.
      2. isArraytrue이면, 다음을 수행한다.
        1. propertyList를 new empty List로 설정한다.
        2. length를 ? LengthOfArrayLike(replacer)로 둔다.
        3. k를 0으로 둔다.
        4. Repeat, while k < length,
          1. propertyKey를 ! ToString(𝔽(k))로 둔다.
          2. propertyValue를 ? Get(replacer, propertyKey)로 둔다.
          3. itemundefined로 둔다.
          4. propertyValue가 String이면, 다음을 수행한다.
            1. itempropertyValue로 설정한다.
          5. 그렇지 않고 propertyValue가 Number이면, 다음을 수행한다.
            1. item을 ! ToString(propertyValue)로 설정한다.
          6. 그렇지 않고 propertyValue가 Object이면, 다음을 수행한다.
            1. propertyValue[[StringData]] 또는 [[NumberData]] internal slot을 가지면, item을 ? ToString(propertyValue)로 설정한다.
          7. itemundefined가 아니고 propertyListitem을 contain하지 않으면, 다음을 수행한다.
            1. itempropertyList에 append한다.
          8. kk + 1로 설정한다.
  6. space가 Object이면, 다음을 수행한다.
    1. space[[NumberData]] internal slot을 가지면, 다음을 수행한다.
      1. space를 ? ToNumber(space)로 설정한다.
    2. 그렇지 않고 space[[StringData]] internal slot을 가지면, 다음을 수행한다.
      1. space를 ? ToString(space)로 설정한다.
  7. space가 Number이면, 다음을 수행한다.
    1. spaceMV를 ! ToIntegerOrInfinity(space)로 둔다.
    2. spaceMVmin(10, spaceMV)로 설정한다.
    3. spaceMV < 1이면, gap을 empty String으로 둔다; 그렇지 않으면 gap을 code unit 0x0020 (SPACE)의 spaceMV occurrences를 containing하는 String value로 둔다.
  8. 그렇지 않고 space가 String이면, 다음을 수행한다.
    1. space의 length가 ≤ 10이면, gapspace로 둔다; 그렇지 않으면 gap을 0부터 10까지의 spacesubstring으로 둔다.
  9. 그렇지 않으면,
    1. gap을 empty String으로 둔다.
  10. wrapperOrdinaryObjectCreate(%Object.prototype%)로 둔다.
  11. CreateDataPropertyOrThrow(wrapper, the empty String, value)를 수행한다.
  12. stateJSON Serialization Record { [[ReplacerFunction]]: replacerFunc, [[Stack]]: stack, [[Indent]]: indent, [[Gap]]: gap, [[PropertyList]]: propertyList }로 둔다.
  13. SerializeJSONProperty(state, the empty String, wrapper)를 반환한다.

이 function의 "length" property는 3𝔽입니다.

Note 1

JSON structures는 any depth로 nested될 수 있지만, acyclic이어야 합니다. value가 cyclic structure이거나 cyclic structure를 contains하면, 이 function은 TypeError exception을 throw해야 합니다. 다음은 stringified될 수 없는 value의 예입니다:

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

Symbolic primitive values는 다음과 같이 rendered됩니다:

  • null value는 JSON text에서 String value "null"로 rendered됩니다.
  • undefined value는 rendered되지 않습니다.
  • true value는 JSON text에서 String value "true"로 rendered됩니다.
  • false value는 JSON text에서 String value "false"로 rendered됩니다.
Note 3

String values는 QUOTATION MARK (") code units로 wrapped됩니다. code units "\\ prefixes로 escaped됩니다. Control characters code units는 escape sequences \uHHHH 또는 shorter forms인 \b (BACKSPACE), \f (FORM FEED), \n (LINE FEED), \r (CARRIAGE RETURN), \t (CHARACTER TABULATION)로 replaced됩니다.

Note 4

Finite numbers는 ToString(number)를 calling한 것처럼 stringified됩니다. sign과 관계없이 NaNInfinity는 String value "null"로 represented됩니다.

Note 5

JSON representation을 가지지 않는 values(예: undefined 및 functions)는 String을 produce하지 않습니다. 대신 undefined value를 produce합니다. arrays 안에서 these values는 String value "null"로 represented됩니다. objects 안에서는 unrepresentable value가 property를 stringification에서 excluded되도록 causes합니다.

Note 6

object는 U+007B (LEFT CURLY BRACKET) 뒤에 zero or more properties가 오고, U+002C (COMMA)로 separated되며, U+007D (RIGHT CURLY BRACKET)로 closed되는 것으로 rendered됩니다. property는 property name을 representing하는 quoted String, U+003A (COLON), 그리고 stringified property value입니다. array는 opening U+005B (LEFT SQUARE BRACKET) 뒤에 zero or more values가 오고, U+002C (COMMA)로 separated되며, 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
Field Name Value Meaning
[[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 serializing되는 과정에 있는 nested objects의 set입니다. cyclic structures를 detect하는 데 사용됩니다.
[[Indent]] a String current indentation입니다.

25.5.4.2 SerializeJSONProperty ( state, key, holder )

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

  1. value를 ? Get(holder, key)로 둔다.
  2. value가 Object이거나 value가 BigInt이면, 다음을 수행한다.
    1. toJSON을 ? GetV(value, "toJSON")로 둔다.
    2. IsCallable(toJSON)가 true이면, 다음을 수행한다.
      1. value를 ? Call(toJSON, value, « key »)로 설정한다.
  3. state.[[ReplacerFunction]]undefined가 아니면, 다음을 수행한다.
    1. value를 ? Call(state.[[ReplacerFunction]], holder, « key, value »)로 설정한다.
  4. value가 Object이면, 다음을 수행한다.
    1. value[[IsRawJSON]] internal slot을 가지면, 다음을 수행한다.
      1. rawJSON을 ! Get(value, "rawJSON")로 둔다.
      2. Assert: rawJSON은 String이다.
      3. rawJSON을 반환한다.
    2. value[[NumberData]] internal slot을 가지면, 다음을 수행한다.
      1. value를 ? ToNumber(value)로 설정한다.
    3. 그렇지 않고 value[[StringData]] internal slot을 가지면, 다음을 수행한다.
      1. value를 ? ToString(value)로 설정한다.
    4. 그렇지 않고 value[[BooleanData]] internal slot을 가지면, 다음을 수행한다.
      1. valuevalue.[[BooleanData]]로 설정한다.
    5. 그렇지 않고 value[[BigIntData]] internal slot을 가지면, 다음을 수행한다.
      1. valuevalue.[[BigIntData]]로 설정한다.
  5. valuenull이면, "null"을 반환한다.
  6. valuetrue이면, "true"를 반환한다.
  7. valuefalse이면, "false"를 반환한다.
  8. value가 String이면, QuoteJSONString(value)를 반환한다.
  9. value가 Number이면, 다음을 수행한다.
    1. valuefinite이면, ! ToString(value)를 반환한다.
    2. "null"을 반환한다.
  10. value가 BigInt이면, TypeError exception을 throw한다.
  11. value가 Object이고 IsCallable(value)가 false이면, 다음을 수행한다.
    1. isArray를 ? IsArray(value)로 둔다.
    2. isArraytrue이면, 다음을 수행한다.
      1. SerializeJSONArray(state, value)를 반환한다.
    3. SerializeJSONObject(state, value)를 반환한다.
  12. undefined를 반환한다.

25.5.4.3 QuoteJSONString ( value )

The abstract operation QuoteJSONString takes argument value (a String) and returns a String. value를 0x0022 (QUOTATION MARK) code units로 wraps하고, 그 안의 certain other code units를 escapes합니다. 이 operation은 6.1.4에 described된 것처럼 value를 UTF-16 encoded code points의 sequence로 interprets합니다. It performs the following steps when called:

  1. product를 code unit 0x0022 (QUOTATION MARK) solely로 consisting하는 String value로 둔다.
  2. StringToCodePoints(value)의 each code point codePoint에 대해, 다음을 수행한다.
    1. codePointTable 78의 “Code Point” column에 listed되어 있으면, 다음을 수행한다.
      1. productproduct와 corresponding row의 “Escape Sequence” column에 specified된 codePoint에 대한 escape sequence의 string-concatenation으로 설정한다.
    2. 그렇지 않고 codePoint가 0x0020 (SPACE)보다 less than인 numeric value를 가지거나 codePointleading surrogate 또는 trailing surrogate와 same numeric value를 가지면, 다음을 수행한다.
      1. unit을 numeric value가 codePoint의 numeric value인 code unit으로 둔다.
      2. productproductUnicodeEscape(unit)의 string-concatenation으로 설정한다.
    3. 그렇지 않으면,
      1. productproductUTF16EncodeCodePoint(codePoint)의 string-concatenation으로 설정한다.
  3. productproduct와 code unit 0x0022 (QUOTATION MARK)의 string-concatenation으로 설정한다.
  4. product를 반환한다.
Table 78: JSON Single Character Escape Sequences
Code Point Unicode Character Name Escape Sequence
U+0008 BACKSPACE \b
U+0009 CHARACTER TABULATION \t
U+000A LINE FEED (LF) \n
U+000C FORM FEED (FF) \f
U+000D CARRIAGE RETURN (CR) \r
U+0022 QUOTATION MARK \"
U+005C REVERSE SOLIDUS \\

25.5.4.4 UnicodeEscape ( codeUnit )

The abstract operation UnicodeEscape takes argument codeUnit (a code unit) and returns a String. codeUnit을 Unicode escape sequence로 represents합니다. It performs the following steps when called:

  1. ncodeUnit의 numeric value로 둔다.
  2. Assert: n ≤ 0xFFFF.
  3. hex를 lowercase hexadecimal number로 formatted된 n의 String representation으로 둔다.
  4. code unit 0x005C (REVERSE SOLIDUS), "u", 및 StringPad(hex, 4, "0", start)의 string-concatenation을 반환한다.

25.5.4.5 SerializeJSONObject ( state, value )

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

  1. state.[[Stack]]value를 contain하면, structure가 cyclical이므로 TypeError exception을 throw한다.
  2. valuestate.[[Stack]]에 append한다.
  3. stepBackstate.[[Indent]]로 둔다.
  4. state.[[Indent]]state.[[Indent]]state.[[Gap]]string-concatenation으로 설정한다.
  5. state.[[PropertyList]]undefined가 아니면, 다음을 수행한다.
    1. keysstate.[[PropertyList]]로 둔다.
  6. 그렇지 않으면,
    1. keys를 ? EnumerableOwnProperties(value, key)로 둔다.
  7. partial을 new empty List로 둔다.
  8. keys의 each element propertyKey에 대해, 다음을 수행한다.
    1. stringP를 ? SerializeJSONProperty(state, propertyKey, value)로 둔다.
    2. stringPundefined가 아니면, 다음을 수행한다.
      1. memberQuoteJSONString(propertyKey)로 둔다.
      2. membermember":"string-concatenation으로 설정한다.
      3. state.[[Gap]]이 empty String이 아니면, 다음을 수행한다.
        1. membermember와 code unit 0x0020 (SPACE)의 string-concatenation으로 설정한다.
      4. membermemberstringPstring-concatenation으로 설정한다.
      5. memberpartial에 append한다.
  9. partial이 empty이면, 다음을 수행한다.
    1. final"{}"로 둔다.
  10. 그렇지 않으면,
    1. state.[[Gap]]이 empty String이면, 다음을 수행한다.
      1. propertiespartial의 모든 element Strings를 code unit 0x002C (COMMA)로 separated된 each adjacent pair of Strings와 함께 concatenating하여 formed된 String value로 둔다. comma는 first String before나 last String after에 inserted되지 않는다.
      2. final"{", properties, 및 "}"string-concatenation으로 둔다.
    2. 그렇지 않으면,
      1. separator를 code unit 0x002C (COMMA), code unit 0x000A (LINE FEED), 및 state.[[Indent]]string-concatenation으로 둔다.
      2. propertiespartial의 모든 element Strings를 separator로 separated된 each adjacent pair of Strings와 함께 concatenating하여 formed된 String value로 둔다. separator String은 first String before나 last String after에 inserted되지 않는다.
      3. final"{", code unit 0x000A (LINE FEED), state.[[Indent]], properties, code unit 0x000A (LINE FEED), stepBack, 및 "}"string-concatenation으로 둔다.
  11. state.[[Stack]]의 last element를 remove한다.
  12. state.[[Indent]]stepBack으로 설정한다.
  13. final을 반환한다.

25.5.4.6 SerializeJSONArray ( state, value )

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

  1. state.[[Stack]]value를 contain하면, structure가 cyclical이므로 TypeError exception을 throw한다.
  2. valuestate.[[Stack]]에 append한다.
  3. stepBackstate.[[Indent]]로 둔다.
  4. state.[[Indent]]state.[[Indent]]state.[[Gap]]string-concatenation으로 설정한다.
  5. partial을 new empty List로 둔다.
  6. length를 ? LengthOfArrayLike(value)로 둔다.
  7. index를 0으로 둔다.
  8. Repeat, while index < length,
    1. stringP를 ? SerializeJSONProperty(state, ! ToString(𝔽(index)), value)로 둔다.
    2. stringPundefined이면, 다음을 수행한다.
      1. "null"partial에 append한다.
    3. 그렇지 않으면,
      1. stringPpartial에 append한다.
    4. indexindex + 1로 설정한다.
  9. partial이 empty이면, 다음을 수행한다.
    1. final"[]"로 둔다.
  10. 그렇지 않으면,
    1. state.[[Gap]]이 empty String이면, 다음을 수행한다.
      1. propertiespartial의 모든 element Strings를 code unit 0x002C (COMMA)로 separated된 each adjacent pair of Strings와 함께 concatenating하여 formed된 String value로 둔다. comma는 first String before나 last String after에 inserted되지 않는다.
      2. final"[", properties, 및 "]"string-concatenation으로 둔다.
    2. 그렇지 않으면,
      1. separator를 code unit 0x002C (COMMA), code unit 0x000A (LINE FEED), 및 state.[[Indent]]string-concatenation으로 둔다.
      2. propertiespartial의 모든 element Strings를 separator로 separated된 each adjacent pair of Strings와 함께 concatenating하여 formed된 String value로 둔다. separator String은 first String before나 last String after에 inserted되지 않는다.
      3. final"[", code unit 0x000A (LINE FEED), state.[[Indent]], properties, code unit 0x000A (LINE FEED), stepBack, 및 "]"string-concatenation으로 둔다.
  11. state.[[Stack]]의 last element를 remove한다.
  12. state.[[Indent]]stepBack으로 설정한다.
  13. final을 반환한다.
Note

arrays의 representation은 +0𝔽 (inclusive)부터 array.length (exclusive)까지의 interval 안의 elements만 includes합니다. 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는 garbage collection으로부터 target object 또는 symbol을 preserving하지 않고 그것을 refer하는 데 사용되는 object입니다. target이 garbage collection에 의해 reclaimed되지 않았다면, target value에 대한 access를 allow하기 위해 WeakRefs는 dereferenced될 수 있습니다.

26.1.1 WeakRef 생성자

WeakRef constructor는:

  • %WeakRef%입니다.
  • global object"WeakRef" property의 initial value입니다.
  • constructor로 called될 때 new WeakRef를 create하고 initialize합니다.
  • function으로 called되도록 intended되지 않았으며, 그러한 방식으로 called되면 exception을 throw합니다.
  • 클래스 정의의 extends 절의 값으로 사용될 수 있다. 지정된 WeakRef 동작을 상속하려는 서브클래스 생성자는 WeakRef.prototype의 내장 메서드를 지원하는 데 필요한 내부 상태로 서브클래스 인스턴스를 생성하고 초기화하기 위해 WeakRef 생성자에 대한 super 호출을 포함해야 한다.

26.1.1.1 WeakRef ( target )

이 function은 called될 때 다음 steps를 수행합니다:

  1. NewTarget이 undefined이면, TypeError exception을 throw한다.
  2. CanBeHeldWeakly(target)가 false이면, TypeError exception을 throw한다.
  3. weakRef를 ? OrdinaryCreateFromConstructor(NewTarget, "%WeakRef.prototype%", « [[WeakRefTarget]] »)로 둔다.
  4. AddToKeptObjects(target)를 수행한다.
  5. weakRef.[[WeakRefTarget]]target으로 설정한다.
  6. weakRef를 반환한다.

26.1.2 WeakRef 생성자의 속성

WeakRef constructor는:

  • value가 %Function.prototype%[[Prototype]] internal slot을 가집니다.
  • 다음 properties를 가집니다:

26.1.2.1 WeakRef.prototype

WeakRef.prototype의 initial value는 WeakRef prototype object입니다.

이 property는 attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }를 가집니다.

26.1.3 WeakRef 프로토타입 객체의 속성

WeakRef prototype object는:

  • %WeakRef.prototype%입니다.
  • value가 %Object.prototype%[[Prototype]] internal slot을 가집니다.
  • ordinary object입니다.
  • [[WeakRefTarget]] internal slot을 가지지 않습니다.

26.1.3.1 WeakRef.prototype.constructor

WeakRef.prototype.constructor의 initial value는 %WeakRef%입니다.

26.1.3.2 WeakRef.prototype.deref ( )

이 method는 called될 때 다음 steps를 수행합니다:

  1. weakRefthis value로 둔다.
  2. RequireInternalSlot(weakRef, [[WeakRefTarget]])를 수행한다.
  3. WeakRefDeref(weakRef)를 반환한다.
Note

WeakRefundefined가 아닌 target value를 반환하면, 이 target value는 ECMAScript code의 current execution이 completed될 때까지 garbage collected되어서는 안 됩니다. AddToKeptObjects operation은 read consistency가 maintained되도록 보장합니다.

let target = { foo() {} };
let weakRef = new WeakRef(target);

// ... later ...

if (weakRef.deref()) {
  weakRef.deref().foo();
}

위 example에서 first deref가 undefined로 evaluate되지 않으면 second deref도 그럴 수 없습니다.

26.1.3.3 WeakRef.prototype [ %Symbol.toStringTag% ]

%Symbol.toStringTag% property의 initial value는 String value "WeakRef"입니다.

이 property는 attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }를 가집니다.

26.1.4 WeakRef Abstract Operations

26.1.4.1 WeakRefDeref ( weakRef )

The abstract operation WeakRefDeref takes argument weakRef (a WeakRef) and returns an ECMAScript language value. It performs the following steps when called:

  1. targetweakRef.[[WeakRefTarget]]으로 둔다.
  2. targetempty가 아니면, 다음을 수행한다.
    1. AddToKeptObjects(target)를 수행한다.
    2. target을 반환한다.
  3. undefined를 반환한다.
Note

이 abstract operation은 liveness를 succinctly define할 수 있도록 strictly 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가 garbage collected될 때 performed되는 cleanup operations의 registration과 unregistration을 manages하는 object입니다.

26.2.1 FinalizationRegistry 생성자

FinalizationRegistry constructor는:

  • %FinalizationRegistry%입니다.
  • global object"FinalizationRegistry" property의 initial value입니다.
  • constructor로 called될 때 new FinalizationRegistry를 create하고 initialize합니다.
  • function으로 called되도록 intended되지 않았으며, 그러한 방식으로 called되면 exception을 throw합니다.
  • 클래스 정의의 extends 절의 값으로 사용될 수 있다. 지정된 FinalizationRegistry 동작을 상속하려는 서브클래스 생성자는 FinalizationRegistry.prototype의 내장 메서드를 지원하는 데 필요한 내부 상태로 서브클래스 인스턴스를 생성하고 초기화하기 위해 FinalizationRegistry 생성자에 대한 super 호출을 포함해야 한다.

26.2.1.1 FinalizationRegistry ( cleanupCallback )

이 function은 called될 때 다음 steps를 수행합니다:

  1. NewTarget이 undefined이면, TypeError 예외를 던진다.
  2. IsCallable(cleanupCallback)이 false이면, TypeError 예외를 던진다.
  3. finalizationRegistry를 ? OrdinaryCreateFromConstructor(NewTarget, "%FinalizationRegistry.prototype%", « [[Realm]], [[CleanupCallback]], [[Cells]] »)라고 하자.
  4. activeFunc활성 함수 객체라고 하자.
  5. finalizationRegistry.[[Realm]]activeFunc.[[Realm]]으로 설정한다.
  6. finalizationRegistry.[[CleanupCallback]]HostMakeJobCallback(cleanupCallback)으로 설정한다.
  7. finalizationRegistry.[[Cells]]를 새로운 빈 List로 설정한다.
  8. finalizationRegistry를 반환한다.

26.2.2 FinalizationRegistry 생성자의 속성

FinalizationRegistry constructor는:

  • value가 %Function.prototype%[[Prototype]] internal slot을 가집니다.
  • 다음 properties를 가집니다:

26.2.2.1 FinalizationRegistry.prototype

FinalizationRegistry.prototype의 initial value는 FinalizationRegistry prototype object입니다.

이 property는 attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }를 가집니다.

26.2.3 FinalizationRegistry 프로토타입 객체의 속성

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는 called될 때 다음 steps를 수행합니다:

  1. finalizationRegistrythis value로 둔다.
  2. RequireInternalSlot(finalizationRegistry, [[Cells]])를 수행한다.
  3. CanBeHeldWeakly(target)가 false이면, TypeError exception을 throw한다.
  4. SameValue(target, heldValue)가 true이면, TypeError exception을 throw한다.
  5. CanBeHeldWeakly(unregisterToken)가 false이면, 다음을 수행한다.
    1. unregisterTokenundefined가 아니면, TypeError exception을 throw한다.
    2. unregisterTokenempty로 설정한다.
  6. cellRecord { [[WeakRefTarget]]: target, [[HeldValue]]: heldValue, [[UnregisterToken]]: unregisterToken }로 둔다.
  7. cellfinalizationRegistry.[[Cells]]에 append한다.
  8. undefined를 반환한다.
Note

이 specification의 algorithms와 definitions에 기반하면, finalizationRegistry.[[Cells]]cell을 contains할 때 cell.[[HeldValue]]live입니다; 그러나 이는 반드시 cell.[[UnregisterToken]] 또는 cell.[[Target]]live임을 의미하지는 않습니다. 예를 들어, object를 itself를 unregister token으로 하여 registering해도 그 object가 forever alive로 유지되지는 않습니다.

26.2.3.3 FinalizationRegistry.prototype.unregister ( unregisterToken )

이 method는 called될 때 다음 steps를 수행합니다:

  1. finalizationRegistrythis value로 둔다.
  2. RequireInternalSlot(finalizationRegistry, [[Cells]])를 수행한다.
  3. CanBeHeldWeakly(unregisterToken)가 false이면, TypeError exception을 throw한다.
  4. removedfalse로 둔다.
  5. finalizationRegistry.[[Cells]]의 each Record { [[WeakRefTarget]], [[HeldValue]], [[UnregisterToken]] } cell에 대해, 다음을 수행한다.
    1. cell.[[UnregisterToken]]empty가 아니고 SameValue(cell.[[UnregisterToken]], unregisterToken)가 true이면, 다음을 수행한다.
      1. cellfinalizationRegistry.[[Cells]]에서 remove한다.
      2. removedtrue로 설정한다.
  6. removed를 반환한다.

26.2.3.4 FinalizationRegistry.prototype [ %Symbol.toStringTag% ]

%Symbol.toStringTag% property의 initial value는 String value "FinalizationRegistry"입니다.

이 property는 attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }를 가집니다.

26.2.4 FinalizationRegistry 인스턴스의 속성

FinalizationRegistry instances는 FinalizationRegistry prototype object로부터 properties를 inherit하는 ordinary objects입니다. FinalizationRegistry instances는 또한 [[Cells]][[CleanupCallback]] internal slots를 가집니다.

27 제어 추상화 객체

27.1 반복

27.1.1 공통 반복 인터페이스

interface는 associated values가 specific specification과 match하는 property keys의 set입니다. interface의 specification에 의해 described된 모든 properties를 제공하는 any object는 그 interface에 conform합니다. interface는 distinct object로 represented되지 않습니다. 어떤 interface에도 conform하는 separately implemented objects가 많이 있을 수 있습니다. individual object는 multiple interfaces에 conform할 수 있습니다.

27.1.1.1 Iterable Interface

iterable interfaceTable 79에 described된 properties를 포함합니다:

Table 79: Iterable Interface Required Properties
Property Value Requirements
%Symbol.iterator% iterator object를 반환하는 function 반환된 object는 iterator interface에 conform해야 합니다.

27.1.1.2 Iterator Interface

iterator interface를 implement하는 object는 Table 80의 property를 include해야 합니다. Such objects는 또한 Table 81의 properties를 implement할 수 있습니다.

Table 80: Iterator Interface Required Properties
Property Value Requirements
"next" IteratorResult object를 반환하는 function 반환된 object는 IteratorResult interface에 conform해야 합니다. iteratornext method에 대한 previous call이 "done" property가 trueIteratorResult object를 반환했다면, 그 object의 next method에 대한 모든 subsequent calls도 "done" property가 trueIteratorResult object를 반환해야 합니다. 그러나 이 requirement는 enforced되지 않습니다.
Note 1

arguments는 next function에 passed될 수 있지만, 그 interpretation과 validity는 target iterator에 dependent합니다. for-of statement와 iterators의 other common users는 어떤 arguments도 pass하지 않으므로, 그러한 방식으로 사용될 것으로 expect되는 iterator objects는 arguments 없이 called되는 것을 deal할 준비가 되어 있어야 합니다.

Table 81: Iterator Interface Optional Properties
Property Value Requirements
"return" IteratorResult object를 반환하는 function 반환된 object는 IteratorResult interface에 conform해야 합니다. 이 method를 invoking하면 caller가 iterator에 대해 더 이상 next method calls를 make할 intention이 없음을 iterator object에 notifies합니다. 반환된 IteratorResult object는 typically value가 true"done" property와 return method의 argument로 passed된 value를 가진 "value" property를 가집니다. 그러나 이 requirement는 enforced되지 않습니다.
"throw" IteratorResult object를 반환하는 function 반환된 object는 IteratorResult interface에 conform해야 합니다. 이 method를 invoking하면 caller가 error condition을 detected했음을 iterator object에 notifies합니다. argument는 error condition을 identify하는 데 사용될 수 있으며 typically exception object입니다. typical response는 argument로 passed된 value를 throw하는 것입니다. method가 throw하지 않으면, 반환된 IteratorResult object는 typically value가 true"done" property를 가집니다.
Note 2

Typically 이 methods의 callers는 invoking하기 전에 their existence를 check해야 합니다. for-of, yield*, 및 array destructuring을 포함한 certain ECMAScript language features는 existence check를 수행한 후 이 methods를 call합니다. iterable objects를 arguments로 accept하는 most ECMAScript library functions도 conditionally 이들을 call합니다.

27.1.1.3 Async Iterable Interface

async iterable interfaceTable 82에 described된 properties를 포함합니다:

Table 82: Async Iterable Interface Required Properties
Property Value Requirements
%Symbol.asyncIterator% async iterator object를 반환하는 function 반환된 object는 async iterator interface에 conform해야 합니다.

27.1.1.4 Async Iterator Interface

async iterator interface를 implement하는 object는 Table 83의 properties를 include해야 합니다. Such objects는 또한 Table 84의 properties를 implement할 수 있습니다.

Table 83: Async Iterator Interface Required Properties
Property Value Requirements
"next" IteratorResult object에 대한 promise를 반환하는 function

반환된 promise는 fulfilled될 때 IteratorResult interface에 conform하는 object로 fulfill해야 합니다. async iteratornext method에 대한 previous call이 "done" property가 trueIteratorResult object에 대한 promise를 반환했다면, 그 object의 next method에 대한 모든 subsequent calls도 "done" property가 trueIteratorResult object에 대한 promise를 반환해야 합니다. 그러나 이 requirement는 enforced되지 않습니다.

Additionally, fulfillment value로 serves하는 IteratorResult object는 value가 promise(또는 “thenable”)가 아닌 "value" property를 가져야 합니다. 그러나 이 requirement도 enforced되지 않습니다.

Note 1

arguments는 next function에 passed될 수 있지만, 그 interpretation과 validity는 target async iterator에 dependent합니다. for-await-of statement와 async iterators의 other common users는 어떤 arguments도 pass하지 않으므로, 그러한 방식으로 사용될 것으로 expect되는 async iterator objects는 arguments 없이 called되는 것을 deal할 준비가 되어 있어야 합니다.

Table 84: Async Iterator Interface Optional Properties
Property Value Requirements
"return" IteratorResult object에 대한 promise를 반환하는 function

반환된 promise는 fulfilled될 때 IteratorResult interface에 conform하는 object로 fulfill해야 합니다. 이 method를 invoking하면 caller가 async iterator에 대해 더 이상 next method calls를 make할 intention이 없음을 async iterator object에 notifies합니다. 반환된 promise는 typically value가 true"done" property와 return method의 argument로 passed된 value를 가진 "value" property를 가지는 IteratorResult object로 fulfill합니다. 그러나 이 requirement는 enforced되지 않습니다.

Additionally, fulfillment value로 serves하는 IteratorResult object는 value가 promise(또는 “thenable”)가 아닌 "value" property를 가져야 합니다. argument value가 typical manner로 used되면, 그것이 rejected promise인 경우 same reason으로 rejected된 promise가 returned되어야 합니다; fulfilled promise인 경우 그 fulfillment value가 returned promise의 IteratorResult object fulfillment value의 "value" property로 used되어야 합니다. 그러나 이러한 requirements도 enforced되지 않습니다.

"throw" IteratorResult object에 대한 promise를 반환하는 function

반환된 promise는 fulfilled될 때 IteratorResult interface에 conform하는 object로 fulfill해야 합니다. 이 method를 invoking하면 caller가 error condition을 detected했음을 async iterator object에 notifies합니다. argument는 error condition을 identify하는 데 사용될 수 있으며 typically exception object입니다. typical response는 argument로 passed된 value로 reject하는 rejected promise를 반환하는 것입니다.

반환된 promise가 fulfilled되면, IteratorResult object fulfillment value는 typically value가 true"done" property를 가집니다. Additionally, value가 promise(또는 “thenable”)가 아닌 "value" property를 가져야 하지만, 이 requirement는 enforced되지 않습니다.

Note 2

Typically 이 methods의 callers는 invoking하기 전에 their existence를 check해야 합니다. for-await-ofyield*를 포함한 certain ECMAScript language features는 existence check를 수행한 후 이 methods를 call합니다.

27.1.1.5 IteratorResult Interface

IteratorResult interfaceTable 85에 listed된 properties를 포함합니다:

Table 85: IteratorResult Interface Properties
Property Value Requirements
"done" Boolean 이는 iterator next method call의 result status입니다. iterator의 end에 reached했다면 "done"true입니다. end에 reached하지 않았다면 "done"false이고 value가 available합니다. "done" property(own 또는 inherited)가 exist하지 않으면, value false를 가지는 것으로 considered됩니다.
"value" ECMAScript language value done이 false이면, 이는 current iteration element value입니다. done이 true이면, 이는 iterator의 return value입니다(제공한 경우). iterator가 return value를 가지지 않으면, "value"undefined입니다. 그 경우 conforming object가 explicit "value" property를 inherit하지 않는다면 "value" property는 absent일 수 있습니다.

27.1.2 Iterator Helper 객체

Iterator Helper object는 some specific source iterator object의 lazy transformation을 represent하는 ordinary object입니다. Iterator Helper objects를 위한 named constructor는 없습니다. 대신, Iterator Helper objects는 Iterator instance objects의 certain methods를 calling하여 created됩니다.

27.1.2.1 The %IteratorHelperPrototype% Object

%IteratorHelperPrototype% object는:

27.1.2.1.1 %IteratorHelperPrototype%.next ( )

  1. GeneratorResume(this value, undefined, "Iterator Helper")를 반환한다.

27.1.2.1.2 %IteratorHelperPrototype%.return ( )

  1. objthis value로 둔다.
  2. RequireInternalSlot(obj, [[UnderlyingIterators]])를 수행한다.
  3. Assert: obj[[GeneratorState]] internal slot을 가진다.
  4. obj.[[GeneratorState]]suspended-start이면, 다음을 수행한다.
    1. obj.[[GeneratorState]]completed로 설정한다.
    2. NOTE: generator가 completed state에 들어가면 결코 그 state를 떠나지 않으며 its associated execution context는 결코 resumed되지 않는다. obj와 associated된 any execution state는 이 point에서 discarded될 수 있다.
    3. IteratorCloseAll(obj.[[UnderlyingIterators]], NormalCompletion(unused))를 수행한다.
    4. CreateIteratorResultObject(undefined, true)를 반환한다.
  5. completionReturnCompletion(undefined)으로 둔다.
  6. GeneratorResumeAbrupt(obj, completion, "Iterator Helper")를 반환한다.

27.1.2.1.3 %IteratorHelperPrototype% [ %Symbol.toStringTag% ]

%Symbol.toStringTag% property의 initial value는 String value "Iterator Helper"입니다.

이 property는 attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }를 가집니다.

27.1.3 Iterator 객체

27.1.3.1 Iterator 생성자

Iterator constructor는:

  • %Iterator%입니다.
  • global object"Iterator" property의 initial value입니다.
  • subclassable하도록 designed되었습니다. class definition의 extends clause의 value로 사용될 수 있습니다.

27.1.3.1.1 Iterator ( )

이 function은 called될 때 다음 steps를 수행합니다:

  1. NewTarget이 undefined이거나 active function object이면, TypeError exception을 throw한다.
  2. OrdinaryCreateFromConstructor(NewTarget, "%Iterator.prototype%")를 반환한다.

27.1.3.2 Iterator 생성자의 속성

Iterator constructor는:

  • value가 %Function.prototype%[[Prototype]] internal slot을 가집니다.
  • 다음 properties를 가집니다:

27.1.3.2.1 Iterator.concat ( ...items )

  1. iterables를 new empty List로 둔다.
  2. items의 각 element item에 대해, 다음을 수행한다.
    1. item이 Object가 아니면, TypeError exception을 throw한다.
    2. method를 ? GetMethod(item, %Symbol.iterator%)로 둔다.
    3. methodundefined이면, TypeError exception을 throw한다.
    4. Record { [[OpenMethod]]: method, [[Iterable]]: item }를 iterables에 append한다.
  3. closureiterables를 captures하고 called될 때 다음 steps를 수행하는, parameters가 없는 new Abstract Closure로 둔다:
    1. iterables의 각 Record iterable에 대해, 다음을 수행한다.
      1. iterator를 ? Call(iterable.[[OpenMethod]], iterable.[[Iterable]])로 둔다.
      2. iterator가 Object가 아니면, TypeError exception을 throw한다.
      3. iteratorRecord를 ? GetIteratorDirect(iterator)로 둔다.
      4. innerAlivetrue로 둔다.
      5. Repeat, while innerAlive is true,
        1. innerValue를 ? IteratorStepValue(iteratorRecord)로 둔다.
        2. innerValuedone이면, 다음을 수행한다.
          1. innerAlivefalse로 설정한다.
        3. Else,
          1. completionCompletion(Yield(innerValue))로 둔다.
          2. completionabrupt completion이면, 다음을 수행한다.
            1. IteratorClose(iteratorRecord, completion)를 반환한다.
    2. ReturnCompletion(undefined)을 반환한다.
  4. genCreateIteratorFromClosure(closure, "Iterator Helper", %IteratorHelperPrototype%, « [[UnderlyingIterators]] »)로 둔다.
  5. gen.[[UnderlyingIterators]]를 new empty List로 설정한다.
  6. gen을 반환한다.

27.1.3.2.2 Iterator.from ( obj )

  1. iteratorRecord를 ? GetIteratorFlattenable(obj, iterate-string-primitives)로 둔다.
  2. hasInstance를 ? OrdinaryHasInstance(%Iterator%, iteratorRecord.[[Iterator]])로 둔다.
  3. hasInstancetrue이면, 다음을 수행한다.
    1. iteratorRecord.[[Iterator]]를 반환한다.
  4. wrapperOrdinaryObjectCreate(%WrapForValidIteratorPrototype%, « [[Iterated]] »)로 둔다.
  5. wrapper.[[Iterated]]iteratorRecord로 설정한다.
  6. wrapper를 반환한다.

27.1.3.2.2.1 The %WrapForValidIteratorPrototype% Object

%WrapForValidIteratorPrototype% object는:

27.1.3.2.2.1.1 %WrapForValidIteratorPrototype%.next ( )

  1. objthis value로 둔다.
  2. RequireInternalSlot(obj, [[Iterated]])를 수행한다.
  3. iteratorRecordobj.[[Iterated]]로 둔다.
  4. Call(iteratorRecord.[[NextMethod]], iteratorRecord.[[Iterator]])를 반환한다.

27.1.3.2.2.1.2 %WrapForValidIteratorPrototype%.return ( )

  1. objthis value로 둔다.
  2. RequireInternalSlot(obj, [[Iterated]])를 수행한다.
  3. iteratorobj.[[Iterated]].[[Iterator]]로 둔다.
  4. Assert: iterator는 Object이다.
  5. returnMethod를 ? GetMethod(iterator, "return")로 둔다.
  6. returnMethodundefined이면, 다음을 수행한다.
    1. CreateIteratorResultObject(undefined, true)를 반환한다.
  7. Call(returnMethod, iterator)를 반환한다.

27.1.3.2.3 Iterator.prototype

Iterator.prototype의 initial value는 Iterator prototype object입니다.

이 property는 attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }를 가집니다.

27.1.3.2.4 Iterator.zip ( iterables [ , options ] )

이 function은 called될 때 다음 steps를 수행합니다:

  1. iterables가 Object가 아니면, TypeError exception을 throw한다.
  2. options를 ? GetOptionsObject(options)로 설정한다.
  3. mode를 ? Get(options, "mode")로 둔다.
  4. modeundefined이면, mode"shortest"로 설정한다.
  5. mode"shortest", "longest", 또는 "strict" 중 하나가 아니면, TypeError exception을 throw한다.
  6. paddingOptionundefined로 둔다.
  7. mode"longest"이면, 다음을 수행한다.
    1. paddingOption을 ? Get(options, "padding")으로 설정한다.
    2. paddingOptionundefined가 아니고 Object도 아니면, TypeError exception을 throw한다.
  8. iters를 new empty List로 둔다.
  9. padding을 new empty List로 둔다.
  10. inputIter를 ? GetIterator(iterables, sync)로 둔다.
  11. nextnot-started로 둔다.
  12. Repeat, while next is not done,
    1. nextCompletion(IteratorStepValue(inputIter))로 설정한다.
    2. IfAbruptCloseIterators(next, iters).
    3. nextdone이 아니면, 다음을 수행한다.
      1. iterCompletion(GetIteratorFlattenable(next, reject-primitives))로 둔다.
      2. needClosing을 « inputIter »와 iterslist-concatenation으로 둔다.
      3. IfAbruptCloseIterators(iter, needClosing).
      4. iteriters에 append한다.
  13. iterCountiters 안의 elements 수로 둔다.
  14. mode"longest"이면, 다음을 수행한다.
    1. paddingOptionundefined이면, 다음을 수행한다.
      1. Repeat iterCount times:
        1. undefinedpadding에 append한다.
    2. Else,
      1. paddingIterCompletion(GetIterator(paddingOption, sync))로 둔다.
      2. IfAbruptCloseIterators(paddingIter, iters).
      3. usingIteratortrue로 둔다.
      4. Repeat iterCount times:
        1. usingIteratortrue이면, 다음을 수행한다.
          1. nextCompletion(IteratorStepValue(paddingIter))로 설정한다.
          2. IfAbruptCloseIterators(next, iters).
          3. nextdone이면, 다음을 수행한다.
            1. usingIteratorfalse로 설정한다.
          4. Else,
            1. nextpadding에 append한다.
        2. usingIteratorfalse이면, undefinedpadding에 append한다.
      5. usingIteratortrue이면, 다음을 수행한다.
        1. completionCompletion(IteratorClose(paddingIter, NormalCompletion(unused)))로 둔다.
        2. IfAbruptCloseIterators(completion, iters).
  15. finishResults를 parameters (results)를 가지고 captures nothing하며 called될 때 다음 steps를 수행하는 new Abstract Closure로 둔다:
    1. CreateArrayFromList(results)를 반환한다.
  16. IteratorZip(iters, mode, padding, finishResults)를 반환한다.

27.1.3.2.5 Iterator.zipKeyed ( iterables [ , options ] )

이 function은 called될 때 다음 steps를 수행합니다:

  1. iterables가 Object가 아니면, TypeError exception을 throw한다.
  2. options를 ? GetOptionsObject(options)로 설정한다.
  3. mode를 ? Get(options, "mode")로 둔다.
  4. modeundefined이면, mode"shortest"로 설정한다.
  5. mode"shortest", "longest", 또는 "strict" 중 하나가 아니면, TypeError exception을 throw한다.
  6. paddingOptionundefined로 둔다.
  7. mode"longest"이면, 다음을 수행한다.
    1. paddingOption을 ? Get(options, "padding")으로 설정한다.
    2. paddingOptionundefined가 아니고 Object도 아니면, TypeError exception을 throw한다.
  8. iters를 new empty List로 둔다.
  9. padding을 new empty List로 둔다.
  10. allKeys를 ? iterables.[[OwnPropertyKeys]]()로 둔다.
  11. keys를 new empty List로 둔다.
  12. allKeys의 각 element key에 대해, 다음을 수행한다.
    1. propertyDescCompletion(iterables.[[GetOwnProperty]](key))로 둔다.
    2. IfAbruptCloseIterators(propertyDesc, iters).
    3. propertyDescundefined가 아니고 propertyDesc.[[Enumerable]]true이면, 다음을 수행한다.
      1. valueCompletion(Get(iterables, key))로 둔다.
      2. IfAbruptCloseIterators(value, iters).
      3. valueundefined가 아니면, 다음을 수행한다.
        1. keykeys에 append한다.
        2. iterCompletion(GetIteratorFlattenable(value, reject-primitives))로 둔다.
        3. IfAbruptCloseIterators(iter, iters).
        4. iteriters에 append한다.
  13. iterCountiters 안의 elements 수로 둔다.
  14. mode"longest"이면, 다음을 수행한다.
    1. paddingOptionundefined이면, 다음을 수행한다.
      1. Repeat iterCount times:
        1. undefinedpadding에 append한다.
    2. Else,
      1. keys의 각 element key에 대해, 다음을 수행한다.
        1. valueCompletion(Get(paddingOption, key))로 둔다.
        2. IfAbruptCloseIterators(value, iters).
        3. valuepadding에 append한다.
  15. finishResults를 parameters (results)를 가지고 keysiterCount를 captures하며 called될 때 다음 steps를 수행하는 new Abstract Closure로 둔다:
    1. objOrdinaryObjectCreate(null)로 둔다.
    2. 0 ≤ i < iterCount인 각 integer i에 대해, ascending order로, 다음을 수행한다.
      1. CreateDataPropertyOrThrow(obj, keys[i], results[i])를 수행한다.
    3. obj를 반환한다.
  16. IteratorZip(iters, mode, padding, finishResults)를 반환한다.

27.1.3.3 Iterator Prototype Object의 Properties

Iterator prototype object는:

Note

이 specification에서 iterator interface를 implement하도록 defined된 모든 objects는 또한 %Iterator.prototype%으로부터 inherit합니다. ECMAScript code도 %Iterator.prototype%으로부터 inherit하는 objects를 define할 수 있습니다. %Iterator.prototype%은 all iterator objects에 applicable한 additional methods가 added될 수 있는 place를 제공합니다.

다음 expression은 ECMAScript code가 %Iterator.prototype% object에 access할 수 있는 one way입니다:

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를 require하지 않는 built-in function입니다. called될 때 다음 steps를 수행합니다:

  1. %Iterator%를 반환한다.

27.1.3.3.1.2 set Iterator.prototype.constructor

[[Set]] attribute의 value는 argument v를 takes하는 built-in function입니다. called될 때 다음 steps를 수행합니다:

  1. SetterThatIgnoresPrototypeProperties(this value, %Iterator.prototype%, "constructor", v)를 수행한다.
  2. undefined를 반환한다.
Note

most built-in prototypes의 "constructor" property와 unlike, web-compatibility reasons 때문에 이 property는 accessor여야 합니다.

27.1.3.3.2 Iterator.prototype.drop ( limit )

이 method는 called될 때 다음 steps를 수행합니다:

  1. objthis value로 둔다.
  2. obj가 Object가 아니면, TypeError exception을 throw한다.
  3. iteratedIterator Record { [[Iterator]]: obj, [[NextMethod]]: undefined, [[Done]]: false }로 둔다.
  4. numberLimitCompletion(ToNumber(limit))으로 둔다.
  5. IfAbruptCloseIterator(numberLimit, iterated).
  6. numberLimitNaN이면, 다음을 수행한다.
    1. errorThrowCompletion(a newly created RangeError object)로 둔다.
    2. IteratorClose(iterated, error)를 반환한다.
  7. intLimit을 ! ToIntegerOrInfinity(numberLimit)로 둔다.
  8. intLimit < 0이면, 다음을 수행한다.
    1. errorThrowCompletion(a newly created RangeError object)로 둔다.
    2. IteratorClose(iterated, error)를 반환한다.
  9. iterated를 ? GetIteratorDirect(obj)로 설정한다.
  10. closureiteratedintLimit를 captures하고 called될 때 다음 steps를 수행하는, parameters가 없는 new Abstract Closure로 둔다:
    1. remainingintLimit로 둔다.
    2. Repeat, while remaining > 0,
      1. remaining ≠ +∞이면, 다음을 수행한다.
        1. remainingremaining - 1로 설정한다.
      2. next를 ? IteratorStep(iterated)로 둔다.
      3. nextdone이면, ReturnCompletion(undefined)을 반환한다.
    3. Repeat,
      1. value를 ? IteratorStepValue(iterated)로 둔다.
      2. valuedone이면, ReturnCompletion(undefined)을 반환한다.
      3. completionCompletion(Yield(value))로 둔다.
      4. IfAbruptCloseIterator(completion, iterated).
  11. resultCreateIteratorFromClosure(closure, "Iterator Helper", %IteratorHelperPrototype%, « [[UnderlyingIterators]] »)로 둔다.
  12. result.[[UnderlyingIterators]]를 « iterated »로 설정한다.
  13. result를 반환한다.

27.1.3.3.3 Iterator.prototype.every ( predicate )

이 method는 called될 때 다음 steps를 수행합니다:

  1. objthis value로 둔다.
  2. obj가 Object가 아니면, TypeError exception을 throw한다.
  3. iteratedIterator Record { [[Iterator]]: obj, [[NextMethod]]: undefined, [[Done]]: false }로 둔다.
  4. IsCallable(predicate)가 false이면, 다음을 수행한다.
    1. errorThrowCompletion(a newly created TypeError object)로 둔다.
    2. IteratorClose(iterated, error)를 반환한다.
  5. iterated를 ? GetIteratorDirect(obj)로 설정한다.
  6. counter를 0으로 둔다.
  7. Repeat,
    1. value를 ? IteratorStepValue(iterated)로 둔다.
    2. valuedone이면, true를 반환한다.
    3. resultCompletion(Call(predicate, undefined, « value, 𝔽(counter) »))로 둔다.
    4. IfAbruptCloseIterator(result, iterated).
    5. ToBoolean(result)가 false이면, ? IteratorClose(iterated, NormalCompletion(false))를 반환한다.
    6. countercounter + 1로 설정한다.

27.1.3.3.4 Iterator.prototype.filter ( predicate )

이 method는 called될 때 다음 steps를 수행합니다:

  1. objthis value로 둔다.
  2. obj가 Object가 아니면, TypeError exception을 throw한다.
  3. iteratedIterator Record { [[Iterator]]: obj, [[NextMethod]]: undefined, [[Done]]: false }로 둔다.
  4. IsCallable(predicate)가 false이면, 다음을 수행한다.
    1. errorThrowCompletion(a newly created TypeError object)로 둔다.
    2. IteratorClose(iterated, error)를 반환한다.
  5. iterated를 ? GetIteratorDirect(obj)로 설정한다.
  6. closureiteratedpredicate를 captures하고 called될 때 다음 steps를 수행하는, parameters가 없는 new Abstract Closure로 둔다:
    1. counter를 0으로 둔다.
    2. Repeat,
      1. value를 ? IteratorStepValue(iterated)로 둔다.
      2. valuedone이면, ReturnCompletion(undefined)을 반환한다.
      3. selectedCompletion(Call(predicate, undefined, « value, 𝔽(counter) »))로 둔다.
      4. IfAbruptCloseIterator(selected, iterated).
      5. ToBoolean(selected)가 true이면, 다음을 수행한다.
        1. completionCompletion(Yield(value))로 둔다.
        2. IfAbruptCloseIterator(completion, iterated).
      6. countercounter + 1로 설정한다.
  7. resultCreateIteratorFromClosure(closure, "Iterator Helper", %IteratorHelperPrototype%, « [[UnderlyingIterators]] »)로 둔다.
  8. result.[[UnderlyingIterators]]를 « iterated »로 설정한다.
  9. result를 반환한다.

27.1.3.3.5 Iterator.prototype.find ( predicate )

이 method는 called될 때 다음 steps를 수행합니다:

  1. objthis value로 둔다.
  2. obj가 Object가 아니면, TypeError exception을 throw한다.
  3. iteratedIterator Record { [[Iterator]]: obj, [[NextMethod]]: undefined, [[Done]]: false }로 둔다.
  4. IsCallable(predicate)가 false이면, 다음을 수행한다.
    1. errorThrowCompletion(a newly created TypeError object)로 둔다.
    2. IteratorClose(iterated, error)를 반환한다.
  5. iterated를 ? GetIteratorDirect(obj)로 설정한다.
  6. counter를 0으로 둔다.
  7. Repeat,
    1. value를 ? IteratorStepValue(iterated)로 둔다.
    2. valuedone이면, undefined를 반환한다.
    3. resultCompletion(Call(predicate, undefined, « value, 𝔽(counter) »))로 둔다.
    4. IfAbruptCloseIterator(result, iterated).
    5. ToBoolean(result)가 true이면, ? IteratorClose(iterated, NormalCompletion(value))를 반환한다.
    6. countercounter + 1로 설정한다.

27.1.3.3.6 Iterator.prototype.flatMap ( mapper )

이 method는 called될 때 다음 steps를 수행합니다:

  1. objthis value로 둔다.
  2. obj가 Object가 아니면, TypeError exception을 throw한다.
  3. iteratedIterator Record { [[Iterator]]: obj, [[NextMethod]]: undefined, [[Done]]: false }로 둔다.
  4. IsCallable(mapper)가 false이면, 다음을 수행한다.
    1. errorThrowCompletion(a newly created TypeError object)로 둔다.
    2. IteratorClose(iterated, error)를 반환한다.
  5. iterated를 ? GetIteratorDirect(obj)로 설정한다.
  6. closureiteratedmapper를 captures하고 called될 때 다음 steps를 수행하는, parameters가 없는 new Abstract Closure로 둔다:
    1. counter를 0으로 둔다.
    2. Repeat,
      1. value를 ? IteratorStepValue(iterated)로 둔다.
      2. valuedone이면, ReturnCompletion(undefined)을 반환한다.
      3. mappedCompletion(Call(mapper, undefined, « value, 𝔽(counter) »))로 둔다.
      4. IfAbruptCloseIterator(mapped, iterated).
      5. innerIteratorCompletion(GetIteratorFlattenable(mapped, reject-primitives))로 둔다.
      6. IfAbruptCloseIterator(innerIterator, iterated).
      7. innerAlivetrue로 둔다.
      8. Repeat, while innerAlive is true,
        1. innerValueCompletion(IteratorStepValue(innerIterator))로 둔다.
        2. IfAbruptCloseIterator(innerValue, iterated).
        3. innerValuedone이면, 다음을 수행한다.
          1. innerAlivefalse로 설정한다.
        4. Else,
          1. completionCompletion(Yield(innerValue))로 둔다.
          2. completionabrupt completion이면, 다음을 수행한다.
            1. backupCompletionCompletion(IteratorClose(innerIterator, completion))로 둔다.
            2. IfAbruptCloseIterator(backupCompletion, iterated).
            3. IteratorClose(iterated, completion)를 반환한다.
      9. countercounter + 1로 설정한다.
  7. resultCreateIteratorFromClosure(closure, "Iterator Helper", %IteratorHelperPrototype%, « [[UnderlyingIterators]] »)로 둔다.
  8. result.[[UnderlyingIterators]]를 « iterated »로 설정한다.
  9. result를 반환한다.

27.1.3.3.7 Iterator.prototype.forEach ( procedure )

이 method는 called될 때 다음 steps를 수행합니다:

  1. objthis value로 둔다.
  2. obj가 Object가 아니면, TypeError exception을 throw한다.
  3. iteratedIterator Record { [[Iterator]]: obj, [[NextMethod]]: undefined, [[Done]]: false }로 둔다.
  4. IsCallable(procedure)가 false이면, 다음을 수행한다.
    1. errorThrowCompletion(a newly created TypeError object)로 둔다.
    2. IteratorClose(iterated, error)를 반환한다.
  5. iterated를 ? GetIteratorDirect(obj)로 설정한다.
  6. counter를 0으로 둔다.
  7. Repeat,
    1. value를 ? IteratorStepValue(iterated)로 둔다.
    2. valuedone이면, undefined를 반환한다.
    3. resultCompletion(Call(procedure, undefined, « value, 𝔽(counter) »))로 둔다.
    4. IfAbruptCloseIterator(result, iterated).
    5. countercounter + 1로 설정한다.

27.1.3.3.8 Iterator.prototype.map ( mapper )

이 method는 called될 때 다음 steps를 수행합니다:

  1. objthis value로 둔다.
  2. obj가 Object가 아니면, TypeError exception을 throw한다.
  3. iteratedIterator Record { [[Iterator]]: obj, [[NextMethod]]: undefined, [[Done]]: false }로 둔다.
  4. IsCallable(mapper)가 false이면, 다음을 수행한다.
    1. errorThrowCompletion(a newly created TypeError object)로 둔다.
    2. IteratorClose(iterated, error)를 반환한다.
  5. iterated를 ? GetIteratorDirect(obj)로 설정한다.
  6. closureiteratedmapper를 captures하고 called될 때 다음 steps를 수행하는, parameters가 없는 new Abstract Closure로 둔다:
    1. counter를 0으로 둔다.
    2. Repeat,
      1. value를 ? IteratorStepValue(iterated)로 둔다.
      2. valuedone이면, ReturnCompletion(undefined)을 반환한다.
      3. mappedCompletion(Call(mapper, undefined, « value, 𝔽(counter) »))로 둔다.
      4. IfAbruptCloseIterator(mapped, iterated).
      5. completionCompletion(Yield(mapped))로 둔다.
      6. IfAbruptCloseIterator(completion, iterated).
      7. countercounter + 1로 설정한다.
  7. resultCreateIteratorFromClosure(closure, "Iterator Helper", %IteratorHelperPrototype%, « [[UnderlyingIterators]] »)로 둔다.
  8. result.[[UnderlyingIterators]]를 « iterated »로 설정한다.
  9. result를 반환한다.

27.1.3.3.9 Iterator.prototype.reduce ( reducer [ , initialValue ] )

이 method는 called될 때 다음 steps를 수행합니다:

  1. objthis value로 둔다.
  2. obj가 Object가 아니면, TypeError exception을 throw한다.
  3. iteratedIterator Record { [[Iterator]]: obj, [[NextMethod]]: undefined, [[Done]]: false }로 둔다.
  4. IsCallable(reducer)가 false이면, 다음을 수행한다.
    1. errorThrowCompletion(a newly created TypeError object)로 둔다.
    2. IteratorClose(iterated, error)를 반환한다.
  5. iterated를 ? GetIteratorDirect(obj)로 설정한다.
  6. initialValue가 present하지 않으면, 다음을 수행한다.
    1. accumulator를 ? IteratorStepValue(iterated)로 둔다.
    2. accumulatordone이면, TypeError exception을 throw한다.
    3. counter를 1로 둔다.
  7. Else,
    1. accumulatorinitialValue로 둔다.
    2. counter를 0으로 둔다.
  8. Repeat,
    1. value를 ? IteratorStepValue(iterated)로 둔다.
    2. valuedone이면, accumulator를 반환한다.
    3. resultCompletion(Call(reducer, undefined, « accumulator, value, 𝔽(counter) »))로 둔다.
    4. IfAbruptCloseIterator(result, iterated).
    5. accumulatorresult로 설정한다.
    6. countercounter + 1로 설정한다.

27.1.3.3.10 Iterator.prototype.some ( predicate )

이 method는 called될 때 다음 steps를 수행합니다:

  1. objthis value로 둔다.
  2. obj가 Object가 아니면, TypeError exception을 throw한다.
  3. iteratedIterator Record { [[Iterator]]: obj, [[NextMethod]]: undefined, [[Done]]: false }로 둔다.
  4. IsCallable(predicate)가 false이면, 다음을 수행한다.
    1. errorThrowCompletion(a newly created TypeError object)로 둔다.
    2. IteratorClose(iterated, error)를 반환한다.
  5. iterated를 ? GetIteratorDirect(obj)로 설정한다.
  6. counter를 0으로 둔다.
  7. Repeat,
    1. value를 ? IteratorStepValue(iterated)로 둔다.
    2. valuedone이면, false를 반환한다.
    3. resultCompletion(Call(predicate, undefined, « value, 𝔽(counter) »))로 둔다.
    4. IfAbruptCloseIterator(result, iterated).
    5. ToBoolean(result)가 true이면, ? IteratorClose(iterated, NormalCompletion(true))를 반환한다.
    6. countercounter + 1로 설정한다.

27.1.3.3.11 Iterator.prototype.take ( limit )

이 method는 called될 때 다음 steps를 수행합니다:

  1. objthis value로 둔다.
  2. obj가 Object가 아니면, TypeError exception을 throw한다.
  3. iteratedIterator Record { [[Iterator]]: obj, [[NextMethod]]: undefined, [[Done]]: false }로 둔다.
  4. numberLimitCompletion(ToNumber(limit))으로 둔다.
  5. IfAbruptCloseIterator(numberLimit, iterated).
  6. numberLimitNaN이면, 다음을 수행한다.
    1. errorThrowCompletion(a newly created RangeError object)로 둔다.
    2. IteratorClose(iterated, error)를 반환한다.
  7. intLimit을 ! ToIntegerOrInfinity(numberLimit)로 둔다.
  8. intLimit < 0이면, 다음을 수행한다.
    1. errorThrowCompletion(a newly created RangeError object)로 둔다.
    2. IteratorClose(iterated, error)를 반환한다.
  9. iterated를 ? GetIteratorDirect(obj)로 설정한다.
  10. closureiteratedintLimit를 captures하고 called될 때 다음 steps를 수행하는, parameters가 없는 new Abstract Closure로 둔다:
    1. remainingintLimit로 둔다.
    2. Repeat,
      1. remaining = 0이면, 다음을 수행한다.
        1. IteratorClose(iterated, ReturnCompletion(undefined))를 반환한다.
      2. remaining ≠ +∞이면, 다음을 수행한다.
        1. remainingremaining - 1로 설정한다.
      3. value를 ? IteratorStepValue(iterated)로 둔다.
      4. valuedone이면, ReturnCompletion(undefined)을 반환한다.
      5. completionCompletion(Yield(value))로 둔다.
      6. IfAbruptCloseIterator(completion, iterated).
  11. resultCreateIteratorFromClosure(closure, "Iterator Helper", %IteratorHelperPrototype%, « [[UnderlyingIterators]] »)로 둔다.
  12. result.[[UnderlyingIterators]]를 « iterated »로 설정한다.
  13. result를 반환한다.

27.1.3.3.12 Iterator.prototype.toArray ( )

이 method는 called될 때 다음 steps를 수행합니다:

  1. objthis value로 둔다.
  2. obj가 Object가 아니면, TypeError exception을 throw한다.
  3. iterated를 ? GetIteratorDirect(obj)로 둔다.
  4. items를 new empty List로 둔다.
  5. Repeat,
    1. value를 ? IteratorStepValue(iterated)로 둔다.
    2. valuedone이면, CreateArrayFromList(items)를 반환한다.
    3. valueitems에 append한다.

27.1.3.3.13 Iterator.prototype [ %Symbol.dispose% ] ( )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. objthis 값으로 둔다.
  2. return을 ? GetMethod(obj, "return")으로 둔다.
  3. returnundefined가 아니면,
    1. Call(return, obj)를 수행한다.
  4. undefined를 반환한다.

이 메서드의 "name" 속성 값은 "[Symbol.dispose]"이다.

27.1.3.3.14 Iterator.prototype [ %Symbol.iterator% ] ( )

이 function은 called될 때 다음 steps를 수행합니다:

  1. this value를 반환한다.

이 function의 "name" property의 value는 "[Symbol.iterator]"입니다.

27.1.3.3.15 Iterator.prototype [ %Symbol.toStringTag% ]

Iterator.prototype[%Symbol.toStringTag%]는 attributes { [[Enumerable]]: false, [[Configurable]]: true }를 가진 accessor property입니다. [[Get]][[Set]] attributes는 다음과 같이 defined됩니다:

27.1.3.3.15.1 get Iterator.prototype [ %Symbol.toStringTag% ]

[[Get]] attribute의 value는 arguments를 require하지 않는 built-in function입니다. called될 때 다음 steps를 수행합니다:

  1. "Iterator"를 반환한다.

27.1.3.3.15.2 set Iterator.prototype [ %Symbol.toStringTag% ]

[[Set]] attribute의 value는 argument v를 takes하는 built-in function입니다. called될 때 다음 steps를 수행합니다:

  1. SetterThatIgnoresPrototypeProperties(this value, %Iterator.prototype%, %Symbol.toStringTag%, v)를 수행한다.
  2. undefined를 반환한다.
Note

most built-in prototypes의 %Symbol.toStringTag% property와 unlike, web-compatibility reasons 때문에 이 property는 accessor여야 합니다.

27.1.3.4 Iterators용 Abstract Operations

27.1.3.4.1 IteratorZip ( iters, mode, padding, finishResults )

The abstract operation IteratorZip takes arguments iters (a List of Iterator Records), mode ("shortest", "longest", or "strict"), padding (a List of ECMAScript language values), and finishResults (an Abstract Closure that takes a List of ECMAScript language values and returns an ECMAScript language value) and returns a Generator. It performs the following steps when called:

  1. iterCountiters 안의 elements 수로 둔다.
  2. openItersiters의 copy로 둔다.
  3. closureiters, iterCount, openIters, mode, padding, 및 finishResults를 captures하고 called될 때 다음 steps를 수행하는, parameters가 없는 new Abstract Closure로 둔다:
    1. iterCount = 0이면, ReturnCompletion(undefined)을 반환한다.
    2. Repeat,
      1. results를 new empty List로 둔다.
      2. Assert: openIters는 empty가 아니다.
      3. 0 ≤ i < iterCount인 각 integer i에 대해, ascending order로, 다음을 수행한다.
        1. iteriters[i]로 둔다.
        2. iternull이면, 다음을 수행한다.
          1. Assert: mode"longest"이다.
          2. resultpadding[i]로 둔다.
        3. Else,
          1. resultCompletion(IteratorStepValue(iter))로 둔다.
          2. resultabrupt completion이면, 다음을 수행한다.
            1. iteropenIters에서 remove한다.
            2. IteratorCloseAll(openIters, result)를 반환한다.
          3. result를 ! result로 설정한다.
          4. resultdone이면, 다음을 수행한다.
            1. iteropenIters에서 remove한다.
            2. mode"shortest"이면, 다음을 수행한다.
              1. IteratorCloseAll(openIters, ReturnCompletion(undefined))를 반환한다.
            3. Else if mode is "strict", then
              1. i ≠ 0이면, 다음을 수행한다.
                1. IteratorCloseAll(openIters, ThrowCompletion(a newly created TypeError object))를 반환한다.
              2. 1 ≤ k < iterCount인 각 integer k에 대해, ascending order로, 다음을 수행한다.
                1. Assert: iters[k]는 null이 아니다.
                2. openCompletion(IteratorStep(iters[k]))으로 둔다.
                3. openabrupt completion이면, 다음을 수행한다.
                  1. iters[k]를 openIters에서 remove한다.
                  2. IteratorCloseAll(openIters, open)를 반환한다.
                4. open을 ! open으로 설정한다.
                5. opendone이면, 다음을 수행한다.
                  1. iters[k]를 openIters에서 remove한다.
                6. Else,
                  1. IteratorCloseAll(openIters, ThrowCompletion(a newly created TypeError object))를 반환한다.
              3. ReturnCompletion(undefined)을 반환한다.
            4. Else,
              1. Assert: mode"longest"이다.
              2. openIters가 empty이면, ReturnCompletion(undefined)을 반환한다.
              3. iters[i]를 null로 설정한다.
              4. resultpadding[i]로 설정한다.
        4. resultresults에 append한다.
      4. resultsfinishResults(results)로 설정한다.
      5. completionCompletion(Yield(results))로 둔다.
      6. IfAbruptCloseIterators(completion, openIters).
  4. genCreateIteratorFromClosure(closure, "Iterator Helper", %IteratorHelperPrototype%, « [[UnderlyingIterators]] »)로 둔다.
  5. gen.[[UnderlyingIterators]]openIters로 설정한다.
  6. gen을 반환한다.

27.1.4 The %AsyncIteratorPrototype% Object

%AsyncIteratorPrototype% object는:

Note

이 specification에서 async iterator interface를 implement하도록 defined된 모든 objects는 또한 %AsyncIteratorPrototype%으로부터 inherit합니다. ECMAScript code도 %AsyncIteratorPrototype%으로부터 inherit하는 objects를 define할 수 있습니다. %AsyncIteratorPrototype% object는 all async iterator objects에 applicable한 additional methods가 added될 수 있는 place를 제공합니다.

27.1.4.1 %AsyncIteratorPrototype% [ %Symbol.asyncDispose% ] ( )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. objthis 값으로 둔다.
  2. promiseCapability를 ! NewPromiseCapability(%Promise%)로 둔다.
  3. returnCompletion(GetMethod(obj, "return"))으로 둔다.
  4. IfAbruptRejectPromise(return, promiseCapability).
  5. returnundefined이면,
    1. Call(promiseCapability.[[Resolve]], undefined, « undefined »)를 수행한다.
  6. 그렇지 않으면,
    1. resultCompletion(Call(return, obj, « »))으로 둔다.
    2. IfAbruptRejectPromise(result, promiseCapability).
    3. resultWrapperCompletion(PromiseResolve(%Promise%, result))로 둔다.
    4. IfAbruptRejectPromise(resultWrapper, promiseCapability).
    5. 아무것도 캡처하지 않고 호출될 때 다음 단계를 수행하는, 매개변수가 없는 새 Abstract Closureunwrap을 둔다:
      1. undefined를 반환한다.
    6. onFulfilledCreateBuiltinFunction(unwrap, 1, "", « »)로 둔다.
    7. PerformPromiseThen(resultWrapper, onFulfilled, undefined, promiseCapability)를 수행한다.
  7. promiseCapability.[[Promise]]를 반환한다.

이 메서드의 "name" 속성 값은 "[Symbol.asyncDispose]"이다.

27.1.4.2 %AsyncIteratorPrototype% [ %Symbol.asyncIterator% ] ( )

이 function은 called될 때 다음 steps를 수행합니다:

  1. this value를 반환한다.

이 function의 "name" property의 value는 "[Symbol.asyncIterator]"입니다.

27.1.5 Async-from-Sync Iterator 객체

Async-from-Sync Iterator object는 specific synchronous iterator를 adapts하는 async iterator입니다. Async-from-Sync Iterator objects는 ECMAScript code에 직접 accessible하지 않습니다. Async-from-Sync Iterator objects를 위한 named constructor는 없습니다. 대신, Async-from-Sync Iterator objects는 needed에 따라 CreateAsyncFromSyncIterator abstract operation에 의해 created됩니다.

27.1.5.1 CreateAsyncFromSyncIterator ( syncIteratorRecord )

The abstract operation CreateAsyncFromSyncIterator takes argument syncIteratorRecord (an Iterator Record) and returns an Iterator Record. synchronous Iterator Record로부터 async Iterator Record를 create하는 데 사용됩니다. It performs the following steps when called:

  1. asyncIteratorOrdinaryObjectCreate(%AsyncFromSyncIteratorPrototype%, « [[SyncIteratorRecord]] »)로 둔다.
  2. asyncIterator.[[SyncIteratorRecord]]syncIteratorRecord로 설정한다.
  3. nextMethod를 ! Get(asyncIterator, "next")로 둔다.
  4. iteratorRecordIterator Record { [[Iterator]]: asyncIterator, [[NextMethod]]: nextMethod, [[Done]]: false }로 둔다.
  5. iteratorRecord를 반환한다.

27.1.5.2 The %AsyncFromSyncIteratorPrototype% Object

%AsyncFromSyncIteratorPrototype% object는:

27.1.5.2.1 %AsyncFromSyncIteratorPrototype%.next ( [ value ] )

  1. objthis value로 둔다.
  2. Assert: obj[[SyncIteratorRecord]] internal slot을 가진 Object이다.
  3. promiseCapability를 ! NewPromiseCapability(%Promise%)로 둔다.
  4. syncIteratorRecordobj.[[SyncIteratorRecord]]로 둔다.
  5. value가 present하면, 다음을 수행한다.
    1. resultCompletion(IteratorNext(syncIteratorRecord, value))로 둔다.
  6. Else,
    1. resultCompletion(IteratorNext(syncIteratorRecord))로 둔다.
  7. IfAbruptRejectPromise(result, promiseCapability).
  8. AsyncFromSyncIteratorContinuation(result, promiseCapability, syncIteratorRecord, true)를 반환한다.

27.1.5.2.2 %AsyncFromSyncIteratorPrototype%.return ( [ value ] )

  1. objthis value로 둔다.
  2. Assert: obj[[SyncIteratorRecord]] internal slot을 가진 Object이다.
  3. promiseCapability를 ! NewPromiseCapability(%Promise%)로 둔다.
  4. syncIteratorRecordobj.[[SyncIteratorRecord]]로 둔다.
  5. syncIteratorsyncIteratorRecord.[[Iterator]]로 둔다.
  6. returnCompletion(GetMethod(syncIterator, "return"))으로 둔다.
  7. IfAbruptRejectPromise(return, promiseCapability).
  8. returnundefined이면, 다음을 수행한다.
    1. iteratorResultCreateIteratorResultObject(value, true)로 둔다.
    2. Call(promiseCapability.[[Resolve]], undefined, « iteratorResult »)를 수행한다.
    3. promiseCapability.[[Promise]]를 반환한다.
  9. value가 present하면, 다음을 수행한다.
    1. resultCompletion(Call(return, syncIterator, « value »))로 둔다.
  10. Else,
    1. resultCompletion(Call(return, syncIterator))로 둔다.
  11. IfAbruptRejectPromise(result, promiseCapability).
  12. result가 Object가 아니면, 다음을 수행한다.
    1. Call(promiseCapability.[[Reject]], undefined, « a newly created TypeError object »)를 수행한다.
    2. promiseCapability.[[Promise]]를 반환한다.
  13. AsyncFromSyncIteratorContinuation(result, promiseCapability, syncIteratorRecord, false)를 반환한다.

27.1.5.2.3 %AsyncFromSyncIteratorPrototype%.throw ( [ value ] )

Note
이 specification에서 value는 always provided되지만, %AsyncFromSyncIteratorPrototype%.return ( [ value ] )와의 consistency를 위해 optional로 left됩니다.
  1. objthis value로 둔다.
  2. Assert: obj[[SyncIteratorRecord]] internal slot을 가진 Object이다.
  3. promiseCapability를 ! NewPromiseCapability(%Promise%)로 둔다.
  4. syncIteratorRecordobj.[[SyncIteratorRecord]]로 둔다.
  5. syncIteratorsyncIteratorRecord.[[Iterator]]로 둔다.
  6. throwCompletion(GetMethod(syncIterator, "throw"))으로 둔다.
  7. IfAbruptRejectPromise(throw, promiseCapability).
  8. throwundefined이면, 다음을 수행한다.
    1. NOTE: syncIteratorthrow method를 가지지 않으면, capability를 reject하기 전에 cleanup할 chance를 주기 위해 it을 close한다.
    2. closeCompletionNormalCompletion(empty)으로 둔다.
    3. resultCompletion(IteratorClose(syncIteratorRecord, closeCompletion))로 둔다.
    4. IfAbruptRejectPromise(result, promiseCapability).
    5. NOTE: next step은 protocol violation이 있었다는 것을 indicate하기 위해 TypeError를 throw한다: syncIteratorthrow method를 가지지 않는다.
    6. NOTE: syncIterator를 closing하는 것이 throw하지 않으면 그 operation의 result는 ignored된다, rejected promise를 yields하더라도 마찬가지이다.
    7. Call(promiseCapability.[[Reject]], undefined, « a newly created TypeError object »)를 수행한다.
    8. promiseCapability.[[Promise]]를 반환한다.
  9. value가 present하면, 다음을 수행한다.
    1. resultCompletion(Call(throw, syncIterator, « value »))로 둔다.
  10. Else,
    1. resultCompletion(Call(throw, syncIterator))로 둔다.
  11. IfAbruptRejectPromise(result, promiseCapability).
  12. result가 Object가 아니면, 다음을 수행한다.
    1. Call(promiseCapability.[[Reject]], undefined, « a newly created TypeError object »)를 수행한다.
    2. promiseCapability.[[Promise]]를 반환한다.
  13. AsyncFromSyncIteratorContinuation(result, promiseCapability, syncIteratorRecord, true)를 반환한다.

27.1.5.3 Async-from-Sync Iterator Instances의 Properties

Async-from-Sync Iterator instances는 %AsyncFromSyncIteratorPrototype% intrinsic object로부터 properties를 inherit하는 ordinary objects입니다. Async-from-Sync Iterator instances는 Table 86에 listed된 internal slots로 initially created됩니다.

Table 86: Internal Slots of Async-from-Sync Iterator Instances
Internal Slot Type Description
[[SyncIteratorRecord]] Iterator Record adapted되고 있는 original synchronous iterator를 represents합니다.

27.1.5.4 AsyncFromSyncIteratorContinuation ( result, promiseCapability, syncIteratorRecord, closeOnRejection )

The abstract operation AsyncFromSyncIteratorContinuation takes arguments result (an Object), promiseCapability (a PromiseCapability Record for an intrinsic %Promise%), syncIteratorRecord (an Iterator Record), and closeOnRejection (a Boolean) and returns a Promise. It performs the following steps when called:

  1. NOTE: promiseCapability가 intrinsic %Promise%에서 derived되므로, 아래 IfAbruptRejectPromise의 use에 entailed되는 promiseCapability.[[Reject]]에 대한 calls는 throw하지 않음이 guaranteed된다.
  2. doneCompletion(IteratorComplete(result))로 둔다.
  3. IfAbruptRejectPromise(done, promiseCapability).
  4. valueCompletion(IteratorValue(result))로 둔다.
  5. IfAbruptRejectPromise(value, promiseCapability).
  6. valueWrapperCompletion(PromiseResolve(%Promise%, value))로 둔다.
  7. valueWrapperabrupt completion이고, donefalse이며, closeOnRejectiontrue이면, 다음을 수행한다.
    1. valueWrapperCompletion(IteratorClose(syncIteratorRecord, valueWrapper))로 설정한다.
  8. IfAbruptRejectPromise(valueWrapper, promiseCapability).
  9. unwrap을 parameters (v)를 가지고 done을 captures하며 called될 때 다음 steps를 수행하는 new Abstract Closure로 둔다:
    1. CreateIteratorResultObject(v, done)를 반환한다.
  10. onFulfilledCreateBuiltinFunction(unwrap, 1, "", « »)로 둔다.
  11. NOTE: onFulfilledIteratorResult object"value" property를 processing할 때, 그 value가 promise이면 it을 wait하고 new “unwrapped” IteratorResult object로 result를 re-package하기 위해 used된다.
  12. donetrue이거나 closeOnRejectionfalse이면, 다음을 수행한다.
    1. onRejectedundefined로 둔다.
  13. Else,
    1. closeIterator를 parameters (error)를 가지고 syncIteratorRecord를 captures하며 called될 때 다음 steps를 수행하는 new Abstract Closure로 둔다:
      1. IteratorClose(syncIteratorRecord, ThrowCompletion(error))를 반환한다.
    2. onRejectedCreateBuiltinFunction(closeIterator, 1, "", « »)로 둔다.
    3. NOTE: onRejected는 yields하는 IteratorResult object"value" property가 rejected promise일 때 Iterator를 close하는 데 used된다.
  14. PerformPromiseThen(valueWrapper, onFulfilled, onRejected, promiseCapability)를 수행한다.
  15. promiseCapability.[[Promise]]를 반환한다.

27.2 리소스 관리

27.2.1 공통 리소스 관리 인터페이스

27.2.1.1 Disposable 인터페이스

Disposable 인터페이스에는 Table 87에 설명된 속성이 포함된다:

Table 87: Disposable 인터페이스 필수 속성
속성 요구사항
%Symbol.dispose% 함수 객체

이 메서드를 호출하면 호출자가 이 객체를 계속 사용할 의도가 없음을 Disposable 객체에 알린다. 이 메서드는 파일 시스템 핸들, 스트림, 호스트 객체 등을 포함하되 이에 국한되지 않는 리소스의 명시적 정리를 수행하는 데 필요한 모든 로직을 수행해야 한다. 이 메서드에서 예외가 던져지면, 일반적으로 리소스를 명시적으로 해제할 수 없었음을 의미한다.

같은 객체에 대해 이 메서드를 두 번 이상 호출하는 경우, 이미 폐기된 리소스에 대해 정리 로직을 반복하지 않아야 하며, 첫 번째 호출에서 예외가 던져졌더라도 예외를 던지지 않아야 한다. 그러나 이 요구사항은 강제되지 않는다.

Disposable 객체를 using 또는 await using 선언과 함께 사용할 때, 리소스는 해당 선언을 바로 포함하는 Block 또는 Module이 평가된 후 자동으로 폐기된다.

27.2.1.2 AsyncDisposable 인터페이스

AsyncDisposable 인터페이스에는 Table 88에 설명된 속성이 포함된다:

Table 88: AsyncDisposable 인터페이스 필수 속성
속성 요구사항
%Symbol.asyncDispose% promise를 반환하는 함수 객체

이 메서드를 호출하면 호출자가 이 객체를 계속 사용할 의도가 없음을 AsyncDisposable 객체에 알린다. 이 메서드는 파일 시스템 핸들, 스트림, 호스트 객체 등을 포함하되 이에 국한되지 않는 리소스의 명시적 정리를 수행하는 데 필요한 모든 로직을 수행해야 한다. 이 메서드가 반환한 promise가 거부되면, 일반적으로 리소스를 명시적으로 해제할 수 없었음을 의미한다. AsyncDisposable 객체는 결과 Promise가 이행될 때까지 "disposed"된 것으로 간주되지 않는다.

같은 객체에 대해 이 메서드를 두 번 이상 호출하는 경우, 이미 폐기된 리소스에 대해 정리 로직을 반복하지 않아야 하며, 첫 번째 호출에서 예외가 던져졌거나 거부된 promise가 반환되었더라도 예외를 던지거나 거부된 promise를 반환하지 않아야 한다. 그러나 이 요구사항은 강제되지 않는다.

AsyncDisposable 객체를 await using 선언과 함께 사용할 때, 리소스는 해당 선언을 바로 포함하는 Block 또는 Module이 평가된 후 자동으로 폐기된다.

27.3 DisposableStack 객체

DisposableStack은 함께 폐기되어야 하는 하나 이상의 리소스를 담는 데 사용할 수 있는 객체이다.

모든 DisposableStack 객체는 서로 배타적인 두 상태 중 하나, 즉 disposed 또는 pending 상태에 있다. disposable stack d에 대해 d.dispose()d.move()가 모두 호출되지 않은 경우에만 d는 pending이다.

27.3.1 DisposableStack 생성자

DisposableStack 생성자는 다음과 같다:

  • %DisposableStack%이다.
  • 전역 객체의 "DisposableStack" 속성의 초기값이다.
  • 생성자로 호출될 때 새 DisposableStack을 생성하고 초기화한다.
  • 함수로 호출되도록 의도되지 않았으며, 그런 방식으로 호출되면 예외를 던진다.
  • 클래스 정의의 extends 절에서 값으로 사용할 수 있다. 지정된 DisposableStack 동작을 상속하려는 하위 클래스 생성자는 DisposableStack.prototype의 내장 메서드를 지원하는 데 필요한 내부 상태로 하위 클래스 인스턴스를 생성하고 초기화하기 위해 DisposableStack 생성자에 대한 super 호출을 포함해야 한다.

27.3.1.1 DisposableStack ( )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. NewTarget이 undefined이면, TypeError 예외를 던진다.
  2. disposableStack을 ? OrdinaryCreateFromConstructor(NewTarget, "%DisposableStack.prototype%", « [[DisposableState]], [[DisposableResourceStack]] »)로 둔다.
  3. disposableStack.[[DisposableState]]pending으로 설정한다.
  4. disposableStack.[[DisposableResourceStack]]을 새 빈 List로 설정한다.
  5. disposableStack을 반환한다.

27.3.2 DisposableStack 생성자의 속성

DisposableStack 생성자는 다음과 같다:

  • 값이 %Function.prototype%[[Prototype]] 내부 슬롯을 갖는다.
  • 다음 속성을 갖는다:

27.3.2.1 DisposableStack.prototype

DisposableStack.prototype의 초기값은 DisposableStack 프로토타입 객체이다.

이 속성은 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false } 속성을 갖는다.

27.3.3 DisposableStack 프로토타입 객체의 속성

DisposableStack 프로토타입 객체는 다음과 같다:

  • %DisposableStack.prototype%이다.
  • 값이 %Object.prototype%[[Prototype]] 내부 슬롯을 갖는다.
  • 일반 객체이다.
  • [[DisposableState]] 내부 슬롯 또는 DisposableStack 인스턴스의 다른 내부 슬롯을 갖지 않는다.

27.3.3.1 DisposableStack.prototype.adopt ( value, onDispose )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. disposableStackthis 값으로 둔다.
  2. RequireInternalSlot(disposableStack, [[DisposableState]])를 수행한다.
  3. disposableStack.[[DisposableState]]disposed이면, ReferenceError 예외를 던진다.
  4. IsCallable(onDispose)가 false이면, TypeError 예외를 던진다.
  5. valueonDispose를 캡처하고 호출될 때 다음 단계를 수행하는, 매개변수가 없는 새 Abstract Closureclosure를 둔다:
    1. Call(onDispose, undefined, « value »)를 반환한다.
  6. funcCreateBuiltinFunction(closure, 0, "", « »)로 둔다.
  7. AddDisposableResource(disposableStack.[[DisposableResourceStack]], undefined, sync-dispose, func)를 수행한다.
  8. value를 반환한다.

27.3.3.2 DisposableStack.prototype.constructor

DisposableStack.prototype.constructor의 초기값은 %DisposableStack%이다.

27.3.3.3 DisposableStack.prototype.defer ( onDispose )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. disposableStackthis 값으로 둔다.
  2. RequireInternalSlot(disposableStack, [[DisposableState]])를 수행한다.
  3. disposableStack.[[DisposableState]]disposed이면, ReferenceError 예외를 던진다.
  4. IsCallable(onDispose)가 false이면, TypeError 예외를 던진다.
  5. AddDisposableResource(disposableStack.[[DisposableResourceStack]], undefined, sync-dispose, onDispose)를 수행한다.
  6. undefined를 반환한다.

27.3.3.4 DisposableStack.prototype.dispose ( )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. disposableStackthis 값으로 둔다.
  2. RequireInternalSlot(disposableStack, [[DisposableState]])를 수행한다.
  3. disposableStack.[[DisposableState]]disposed이면, undefined를 반환한다.
  4. disposableStack.[[DisposableState]]disposed로 설정한다.
  5. DisposeResources(disposableStack.[[DisposableResourceStack]], NormalCompletion(undefined))를 반환한다.

27.3.3.5 get DisposableStack.prototype.disposed

DisposableStack.prototype.disposed는 set 접근자 함수가 undefined인 접근자 속성이다. 그 get 접근자 함수는 호출될 때 다음 단계를 수행한다:

  1. disposableStackthis 값으로 둔다.
  2. RequireInternalSlot(disposableStack, [[DisposableState]])를 수행한다.
  3. disposableStack.[[DisposableState]]disposed이면, true를 반환한다.
  4. false를 반환한다.

27.3.3.6 DisposableStack.prototype.move ( )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. disposableStackthis 값으로 둔다.
  2. RequireInternalSlot(disposableStack, [[DisposableState]])를 수행한다.
  3. disposableStack.[[DisposableState]]disposed이면, ReferenceError 예외를 던진다.
  4. newDisposableStack을 ? OrdinaryCreateFromConstructor(%DisposableStack%, "%DisposableStack.prototype%", « [[DisposableState]], [[DisposableResourceStack]] »)로 둔다.
  5. newDisposableStack.[[DisposableState]]pending으로 설정한다.
  6. newDisposableStack.[[DisposableResourceStack]]disposableStack.[[DisposableResourceStack]]로 설정한다.
  7. disposableStack.[[DisposableResourceStack]]을 새 빈 List로 설정한다.
  8. disposableStack.[[DisposableState]]disposed로 설정한다.
  9. newDisposableStack을 반환한다.

27.3.3.7 DisposableStack.prototype.use ( value )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. disposableStackthis 값으로 둔다.
  2. RequireInternalSlot(disposableStack, [[DisposableState]])를 수행한다.
  3. disposableStack.[[DisposableState]]disposed이면, ReferenceError 예외를 던진다.
  4. AddDisposableResource(disposableStack.[[DisposableResourceStack]], value, sync-dispose)를 수행한다.
  5. value를 반환한다.

27.3.3.8 DisposableStack.prototype [ %Symbol.dispose% ] ( )

%Symbol.dispose% 속성의 초기값은 27.3.3.4에 정의된 %DisposableStack.prototype.dispose%이다.

27.3.3.9 DisposableStack.prototype [ %Symbol.toStringTag% ]

%Symbol.toStringTag% 속성의 초기값은 String 값 "DisposableStack"이다.

이 속성은 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true } 속성을 갖는다.

27.3.4 DisposableStack 인스턴스의 속성

DisposableStack 인스턴스는 DisposableStack 프로토타입 객체(내재 객체 %DisposableStack.prototype%)에서 속성을 상속하는 일반 객체이다. DisposableStack 인스턴스는 처음에 Table 89에 설명된 내부 슬롯과 함께 생성된다.

Table 89: DisposableStack 인스턴스의 내부 슬롯
내부 슬롯 타입 설명
[[DisposableState]] pending 또는 disposed disposable stack이 자신의 %Symbol.dispose% 메서드에 대한 들어오는 호출에 어떻게 반응할지를 지배한다.
[[DisposableResourceStack]] DisposableResource 레코드List disposable stack이 폐기될 때 폐기될 리소스. 리소스는 초기화된 순서대로 추가되고, 역순으로 폐기된다.

27.4 AsyncDisposableStack 객체

AsyncDisposableStack은 함께 비동기적으로 폐기되어야 하는 하나 이상의 리소스를 담는 데 사용할 수 있는 객체이다.

모든 AsyncDisposableStack 객체는 서로 배타적인 두 상태 중 하나, 즉 disposed 또는 pending 상태에 있다. async-disposable stack d에 대해 d.disposeAsync()d.move()가 모두 호출되지 않은 경우에만 d는 pending이다.

27.4.1 AsyncDisposableStack 생성자

AsyncDisposableStack 생성자는 다음과 같다:

  • %AsyncDisposableStack%이다.
  • 전역 객체의 "AsyncDisposableStack" 속성의 초기값이다.
  • 생성자로 호출될 때 새 AsyncDisposableStack을 생성하고 초기화한다.
  • 함수로 호출되도록 의도되지 않았으며, 그런 방식으로 호출되면 예외를 던진다.
  • 클래스 정의의 extends 절에서 값으로 사용할 수 있다. 지정된 AsyncDisposableStack 동작을 상속하려는 하위 클래스 생성자는 AsyncDisposableStack.prototype의 내장 메서드를 지원하는 데 필요한 내부 상태로 하위 클래스 인스턴스를 생성하고 초기화하기 위해 AsyncDisposableStack 생성자에 대한 super 호출을 포함해야 한다.

27.4.1.1 AsyncDisposableStack ( )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. NewTarget이 undefined이면, TypeError 예외를 던진다.
  2. asyncDisposableStack을 ? OrdinaryCreateFromConstructor(NewTarget, "%AsyncDisposableStack.prototype%", « [[AsyncDisposableState]], [[DisposableResourceStack]] »)로 둔다.
  3. asyncDisposableStack.[[AsyncDisposableState]]pending으로 설정한다.
  4. asyncDisposableStack.[[DisposableResourceStack]]을 새 빈 List로 설정한다.
  5. asyncDisposableStack을 반환한다.

27.4.2 AsyncDisposableStack 생성자의 속성

AsyncDisposableStack 생성자는 다음과 같다:

  • 값이 %Function.prototype%[[Prototype]] 내부 슬롯을 갖는다.
  • 다음 속성을 갖는다:

27.4.2.1 AsyncDisposableStack.prototype

AsyncDisposableStack.prototype의 초기값은 AsyncDisposableStack 프로토타입 객체이다.

이 속성은 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false } 속성을 갖는다.

27.4.3 AsyncDisposableStack 프로토타입 객체의 속성

AsyncDisposableStack 프로토타입 객체는 다음과 같다:

  • %AsyncDisposableStack.prototype%이다.
  • 값이 %Object.prototype%[[Prototype]] 내부 슬롯을 갖는다.
  • 일반 객체이다.
  • [[AsyncDisposableState]] 내부 슬롯 또는 AsyncDisposableStack 인스턴스의 다른 내부 슬롯을 갖지 않는다.

27.4.3.1 AsyncDisposableStack.prototype.adopt ( value, onDisposeAsync )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. asyncDisposableStackthis 값으로 둔다.
  2. RequireInternalSlot(asyncDisposableStack, [[AsyncDisposableState]])를 수행한다.
  3. asyncDisposableStack.[[AsyncDisposableState]]disposed이면, ReferenceError 예외를 던진다.
  4. IsCallable(onDisposeAsync)가 false이면, TypeError 예외를 던진다.
  5. valueonDisposeAsync를 캡처하고 호출될 때 다음 단계를 수행하는, 매개변수가 없는 새 Abstract Closureclosure를 둔다:
    1. Call(onDisposeAsync, undefined, « value »)를 반환한다.
  6. funcCreateBuiltinFunction(closure, 0, "", « »)로 둔다.
  7. AddDisposableResource(asyncDisposableStack.[[DisposableResourceStack]], undefined, async-dispose, func)를 수행한다.
  8. value를 반환한다.

27.4.3.2 AsyncDisposableStack.prototype.constructor

AsyncDisposableStack.prototype.constructor의 초기값은 %AsyncDisposableStack%이다.

27.4.3.3 AsyncDisposableStack.prototype.defer ( onDisposeAsync )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. asyncDisposableStackthis 값으로 둔다.
  2. RequireInternalSlot(asyncDisposableStack, [[AsyncDisposableState]])를 수행한다.
  3. asyncDisposableStack.[[AsyncDisposableState]]disposed이면, ReferenceError 예외를 던진다.
  4. IsCallable(onDisposeAsync)가 false이면, TypeError 예외를 던진다.
  5. AddDisposableResource(asyncDisposableStack.[[DisposableResourceStack]], undefined, async-dispose, onDisposeAsync)를 수행한다.
  6. undefined를 반환한다.

27.4.3.4 AsyncDisposableStack.prototype.disposeAsync ( )

이 async 메서드는 호출될 때 다음 단계를 수행한다:

  1. asyncDisposableStackthis 값으로 둔다.
  2. RequireInternalSlot(asyncDisposableStack, [[AsyncDisposableState]])를 수행한다.
  3. asyncDisposableStack.[[AsyncDisposableState]]disposed이면, undefined를 반환한다.
  4. asyncDisposableStack.[[AsyncDisposableState]]disposed로 설정한다.
  5. DisposeResources(asyncDisposableStack.[[DisposableResourceStack]], NormalCompletion(undefined))를 반환한다.

27.4.3.5 get AsyncDisposableStack.prototype.disposed

AsyncDisposableStack.prototype.disposed는 set 접근자 함수가 undefined인 접근자 속성이다. 그 get 접근자 함수는 호출될 때 다음 단계를 수행한다:

  1. asyncDisposableStackthis 값으로 둔다.
  2. RequireInternalSlot(asyncDisposableStack, [[AsyncDisposableState]])를 수행한다.
  3. asyncDisposableStack.[[AsyncDisposableState]]disposed이면, true를 반환한다.
  4. false를 반환한다.

27.4.3.6 AsyncDisposableStack.prototype.move ( )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. asyncDisposableStackthis 값으로 둔다.
  2. RequireInternalSlot(asyncDisposableStack, [[AsyncDisposableState]])를 수행한다.
  3. asyncDisposableStack.[[AsyncDisposableState]]disposed이면, ReferenceError 예외를 던진다.
  4. newAsyncDisposableStack을 ? OrdinaryCreateFromConstructor(%AsyncDisposableStack%, "%AsyncDisposableStack.prototype%", « [[AsyncDisposableState]], [[DisposableResourceStack]] »)로 둔다.
  5. newAsyncDisposableStack.[[AsyncDisposableState]]pending으로 설정한다.
  6. newAsyncDisposableStack.[[DisposableResourceStack]]asyncDisposableStack.[[DisposableResourceStack]]로 설정한다.
  7. asyncDisposableStack.[[DisposableResourceStack]]을 새 빈 List로 설정한다.
  8. asyncDisposableStack.[[AsyncDisposableState]]disposed로 설정한다.
  9. newAsyncDisposableStack을 반환한다.

27.4.3.7 AsyncDisposableStack.prototype.use ( value )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. asyncDisposableStackthis 값으로 둔다.
  2. RequireInternalSlot(asyncDisposableStack, [[AsyncDisposableState]])를 수행한다.
  3. asyncDisposableStack.[[AsyncDisposableState]]disposed이면, ReferenceError 예외를 던진다.
  4. AddDisposableResource(asyncDisposableStack.[[DisposableResourceStack]], value, async-dispose)를 수행한다.
  5. value를 반환한다.

27.4.3.8 AsyncDisposableStack.prototype [ %Symbol.asyncDispose% ] ( )

%Symbol.asyncDispose% 속성의 초기값은 27.4.3.4에 정의된 %AsyncDisposableStack.prototype.disposeAsync%이다.

27.4.3.9 AsyncDisposableStack.prototype [ %Symbol.toStringTag% ]

%Symbol.toStringTag% 속성의 초기값은 String 값 "AsyncDisposableStack"이다.

이 속성은 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true } 속성을 갖는다.

27.4.4 AsyncDisposableStack 인스턴스의 속성

AsyncDisposableStack 인스턴스는 AsyncDisposableStack 프로토타입 객체(내재 객체 %AsyncDisposableStack.prototype%)에서 속성을 상속하는 일반 객체이다. AsyncDisposableStack 인스턴스는 처음에 Table 90에 설명된 내부 슬롯과 함께 생성된다.

Table 90: AsyncDisposableStack 인스턴스의 내부 슬롯
내부 슬롯 타입 설명
[[AsyncDisposableState]] pending 또는 disposed disposable stack이 자신의 %Symbol.asyncDispose% 메서드에 대한 들어오는 호출에 어떻게 반응할지를 지배한다.
[[DisposableResourceStack]] DisposableResource 레코드List disposable stack이 폐기될 때 폐기될 리소스. 리소스는 초기화된 순서대로 추가되고, 역순으로 폐기된다.

27.5 Promise 객체

Promise는 deferred된(그리고 possibly asynchronous인) computation의 eventual results에 대한 placeholder로 사용되는 object입니다.

모든 Promise는 mutually exclusive한 세 states 중 하나입니다: fulfilled, rejected, 그리고 pending:

  • promise pp.then(f, r)가 function f를 call하는 Job을 immediately enqueue할 경우 fulfilled입니다.
  • promise pp.then(f, r)가 function r를 call하는 Job을 immediately enqueue할 경우 rejected입니다.
  • promise는 fulfilled도 rejected도 아니면 pending입니다.

promise는 pending이 아니면, 즉 fulfilled 또는 rejected이면 settled라고 합니다.

promise는 settled되었거나 다른 promise의 state와 match하도록 “locked in”된 경우 resolved입니다. resolved promise를 resolve 또는 reject하려는 시도는 effect가 없습니다. 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에 의해 produced됩니다.

PromiseCapability Records는 Table 91에 listed된 fields를 가집니다.

Table 91: PromiseCapability Record Fields
Field Name Value Meaning
[[Promise]] Object promise로 usable한 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입니다. 다음 form의 algorithm step:

  1. IfAbruptRejectPromise(value, capability).

는 다음과 same thing을 의미합니다:

  1. Assert: valueCompletion Record이다.
  2. valueabrupt completion이면, 다음을 수행한다.
    1. Call(capability.[[Reject]], undefined, « value.[[Value]] »)를 수행한다.
    2. capability.[[Promise]]를 반환한다.
  3. value를 ! value로 설정한다.

27.5.1.2 PromiseReaction Records

PromiseReaction Record는 promise가 주어진 value로 resolved 또는 rejected될 때 어떻게 react해야 하는지에 대한 information을 store하는 데 사용되는 Record value입니다. PromiseReaction Records는 PerformPromiseThen abstract operation에 의해 created되며, NewPromiseReactionJob이 반환하는 Abstract Closure에 의해 used됩니다.

PromiseReaction Records는 Table 92에 listed된 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에 specific한 behaviour를 allow하기 위해 사용됩니다.
[[Handler]] JobCallback Record 또는 empty incoming value에 applied되어야 하는 function이며, 그 return value가 derived promise에 무슨 일이 일어나는지를 govern합니다. [[Handler]]empty이면, [[Type]]의 value에 dependent한 function이 대신 사용됩니다.

27.5.1.3 CreateResolvingFunctions ( toResolve )

The abstract operation CreateResolvingFunctions takes argument toResolve (a Promise) and returns a Record with fields [[Resolve]] (a function object) and [[Reject]] (a function object). It performs the following steps when called:

  1. promiseOrEmptyRecord { [[Value]]: toResolve }로 둔다.
  2. resolveSteps를 parameters (resolution)를 가지고 promiseOrEmpty를 captures하며 called될 때 다음 steps를 수행하는 new Abstract Closure로 둔다:
    1. promiseOrEmpty.[[Value]]empty이면, undefined를 반환한다.
    2. promisepromiseOrEmpty.[[Value]]로 둔다.
    3. promiseOrEmpty.[[Value]]empty로 설정한다.
    4. SameValue(resolution, promise)가 true이면, 다음을 수행한다.
      1. selfResolutionError를 newly created TypeError object로 둔다.
      2. RejectPromise(promise, selfResolutionError)를 수행한다.
      3. undefined를 반환한다.
    5. resolution이 Object가 아니면, 다음을 수행한다.
      1. FulfillPromise(promise, resolution)를 수행한다.
      2. undefined를 반환한다.
    6. thenCompletion(Get(resolution, "then")))로 둔다.
    7. thenabrupt completion이면, 다음을 수행한다.
      1. RejectPromise(promise, then.[[Value]])를 수행한다.
      2. undefined를 반환한다.
    8. thenActionthen.[[Value]]로 둔다.
    9. IsCallable(thenAction)가 false이면, 다음을 수행한다.
      1. FulfillPromise(promise, resolution)를 수행한다.
      2. undefined를 반환한다.
    10. thenJobCallbackHostMakeJobCallback(thenAction)로 둔다.
    11. jobNewPromiseResolveThenableJob(promise, resolution, thenJobCallback)으로 둔다.
    12. HostEnqueuePromiseJob(job.[[Job]], job.[[Realm]])을 수행한다.
    13. undefined를 반환한다.
  3. resolveCreateBuiltinFunction(resolveSteps, 1, "", « »)로 둔다.
  4. rejectSteps를 parameters (reason)를 가지고 promiseOrEmpty를 captures하며 called될 때 다음 steps를 수행하는 new Abstract Closure로 둔다:
    1. promiseOrEmpty.[[Value]]empty이면, undefined를 반환한다.
    2. promisepromiseOrEmpty.[[Value]]로 둔다.
    3. promiseOrEmpty.[[Value]]empty로 설정한다.
    4. RejectPromise(promise, reason)를 수행한다.
    5. undefined를 반환한다.
  5. rejectCreateBuiltinFunction(rejectSteps, 1, "", « »)로 둔다.
  6. Record { [[Resolve]]: resolve, [[Reject]]: reject }를 반환한다.

27.5.1.4 FulfillPromise ( promise, value )

The abstract operation FulfillPromise takes arguments promise (a Promise) and value (an ECMAScript language value) and returns unused. It performs the following steps when called:

  1. Assert: promise.[[PromiseState]]pending이다.
  2. reactionspromise.[[PromiseFulfillReactions]]로 둔다.
  3. promise.[[PromiseResult]]value로 설정한다.
  4. promise.[[PromiseFulfillReactions]]undefined로 설정한다.
  5. promise.[[PromiseRejectReactions]]undefined로 설정한다.
  6. promise.[[PromiseState]]fulfilled로 설정한다.
  7. TriggerPromiseReactions(reactions, value)를 수행한다.
  8. unused를 반환한다.

27.5.1.5 NewPromiseCapability ( ctor )

The abstract operation NewPromiseCapability takes argument ctor (an ECMAScript language value) and returns either a normal completion containing a PromiseCapability Record or a throw completion. built-in Promise constructor의 방식으로 ctorconstructor로 사용하여 promise를 create하고 그 resolvereject functions를 extract하려고 attempts합니다. promise와 resolvereject functions는 new PromiseCapability Record를 initialize하는 데 사용됩니다. It performs the following steps when called:

  1. IsConstructor(ctor)가 false이면, TypeError exception을 throw한다.
  2. NOTE: ctor는 Promise constructor의 parameter conventions를 support하는 constructor function으로 assumed된다(27.5.3.1 참조).
  3. resolvingFuncsRecord { [[Resolve]]: undefined, [[Reject]]: undefined }로 둔다.
  4. executorClosure를 parameters (resolve, reject)를 가지고 resolvingFuncs를 captures하며 called될 때 다음 steps를 수행하는 new Abstract Closure로 둔다:
    1. resolvingFuncs.[[Resolve]]undefined가 아니면, TypeError exception을 throw한다.
    2. resolvingFuncs.[[Reject]]undefined가 아니면, TypeError exception을 throw한다.
    3. resolvingFuncs.[[Resolve]]resolve로 설정한다.
    4. resolvingFuncs.[[Reject]]reject로 설정한다.
    5. NormalCompletion(undefined)을 반환한다.
  5. executorCreateBuiltinFunction(executorClosure, 2, "", « »)로 둔다.
  6. promise를 ? Construct(ctor, « executor »)로 둔다.
  7. IsCallable(resolvingFuncs.[[Resolve]])가 false이면, TypeError exception을 throw한다.
  8. IsCallable(resolvingFuncs.[[Reject]])가 false이면, TypeError exception을 throw한다.
  9. PromiseCapability Record { [[Promise]]: promise, [[Resolve]]: resolvingFuncs.[[Resolve]], [[Reject]]: resolvingFuncs.[[Reject]] }를 반환한다.
Note

이 abstract operation은 Promise subclassing을 support합니다. 이는 Promise constructor와 same way로 passed executor function argument를 call하는 any constructor에 대해 generic하기 때문입니다. Promise constructor의 static methods를 any 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를 checks합니다. It performs the following steps when called:

  1. arg가 Object가 아니면, false를 반환한다.
  2. arg[[PromiseState]] internal slot을 가지지 않으면, false를 반환한다.
  3. true를 반환한다.

27.5.1.7 RejectPromise ( promise, reason )

The abstract operation RejectPromise takes arguments promise (a Promise) and reason (an ECMAScript language value) and returns unused. It performs the following steps when called:

  1. Assert: promise.[[PromiseState]]pending이다.
  2. reactionspromise.[[PromiseRejectReactions]]로 둔다.
  3. promise.[[PromiseResult]]reason으로 설정한다.
  4. promise.[[PromiseFulfillReactions]]undefined로 설정한다.
  5. promise.[[PromiseRejectReactions]]undefined로 설정한다.
  6. promise.[[PromiseState]]rejected로 설정한다.
  7. promise.[[PromiseIsHandled]]false이면, HostPromiseRejectionTracker(promise, "reject")를 수행한다.
  8. TriggerPromiseReactions(reactions, reason)를 수행한다.
  9. unused를 반환한다.

27.5.1.8 TriggerPromiseReactions ( reactions, arg )

The abstract operation TriggerPromiseReactions takes arguments reactions (a List of PromiseReaction Records) and arg (an ECMAScript language value) and returns unused. reactions 안의 각 record에 대해 new Job을 enqueue합니다. Such Job 각각은 PromiseReaction Record[[Type]][[Handler]]를 process하며, [[Handler]]empty가 아니면 주어진 argument를 passing하여 it을 calls합니다. [[Handler]]empty이면, behaviour는 [[Type]]에 의해 determined됩니다. It performs the following steps when called:

  1. reactions의 각 element reaction에 대해, 다음을 수행한다.
    1. jobNewPromiseReactionJob(reaction, arg)로 둔다.
    2. HostEnqueuePromiseJob(job.[[Job]], job.[[Realm]])을 수행한다.
  2. unused를 반환한다.

27.5.1.9 HostPromiseRejectionTracker ( promise, operation )

The host-defined abstract operation HostPromiseRejectionTracker takes arguments promise (a Promise) and operation ("reject" or "handle") and returns unused. host environments가 promise rejections를 track할 수 있게 합니다.

HostPromiseRejectionTracker의 default implementation은 unused를 반환하는 것입니다.

Note 1

HostPromiseRejectionTracker는 두 scenarios에서 called됩니다:

  • promise가 any handlers 없이 rejected될 때, operation argument가 "reject"로 set되어 called됩니다.
  • rejected promise에 handler가 first time added될 때, operation argument가 "handle"로 set되어 called됩니다.

HostPromiseRejectionTracker의 typical implementation은 unhandled rejections를 developers에게 notify하려고 시도할 수 있으며, 그러한 previous notifications가 later new handlers being attached에 의해 invalidated되면 also notify하도록 careful할 수 있습니다.

Note 2

operation"handle"이면, implementation은 garbage collection을 interfere하는 way로 promise에 대한 reference를 hold해서는 안 됩니다. operation"reject"이면, rejections는 rare하고 hot code paths에 있지 않을 것으로 expected되므로 implementation은 promise에 대한 reference를 hold할 수 있습니다.

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에 appropriate handler를 apply하고, handler의 return value를 사용하여 that handler와 associated된 derived promise를 resolve 또는 reject하는 new Job Abstract Closure를 반환합니다. It performs the following steps when called:

  1. jobreactionarg를 captures하며 called될 때 다음 steps를 수행하는, parameters가 없는 new Job Abstract Closure로 둔다:
    1. promiseCapabilityreaction.[[Capability]]로 둔다.
    2. typereaction.[[Type]]으로 둔다.
    3. handlerreaction.[[Handler]]로 둔다.
    4. handlerempty이면, 다음을 수행한다.
      1. typefulfill이면, 다음을 수행한다.
        1. handlerResultNormalCompletion(arg)로 둔다.
      2. Else,
        1. Assert: typereject이다.
        2. handlerResultThrowCompletion(arg)로 둔다.
    5. Else,
      1. handlerResultCompletion(HostCallJobCallback(handler, undefined, « arg »))로 둔다.
    6. promiseCapabilityundefined이면, 다음을 수행한다.
      1. Assert: handlerResultabrupt completion이 아니다.
      2. empty를 반환한다.
    7. Assert: promiseCapabilityPromiseCapability Record이다.
    8. handlerResultabrupt completion이면, 다음을 수행한다.
      1. Call(promiseCapability.[[Reject]], undefined, « handlerResult.[[Value]] »)를 반환한다.
    9. Call(promiseCapability.[[Resolve]], undefined, « handlerResult.[[Value]] »)를 반환한다.
  2. handlerRealmnull로 둔다.
  3. reaction.[[Handler]]empty가 아니면, 다음을 수행한다.
    1. getHandlerRealmResultCompletion(GetFunctionRealm(reaction.[[Handler]].[[Callback]]))으로 둔다.
    2. getHandlerRealmResultnormal completion이면, handlerRealmgetHandlerRealmResult.[[Value]]로 설정한다.
    3. Else, handlerRealm을 current Realm Record로 설정한다.
    4. NOTE: handler가 undefined가 아닌 한 handlerRealm은 never null이다. handler가 revoked Proxy이고 ECMAScript code가 실행되지 않을 때, handlerRealm은 error objects를 create하는 데 사용된다.
  4. Record { [[Job]]: job, [[Realm]]: handlerRealm }를 반환한다.

27.5.2.2 NewPromiseResolveThenableJob ( promiseToResolve, thenable, then )

The abstract operation NewPromiseResolveThenableJob takes arguments promiseToResolve (a Promise), thenable (an Object), and then (a JobCallback Record) and returns a Record with fields [[Job]] (a Job Abstract Closure) and [[Realm]] (a Realm Record). It performs the following steps when called:

  1. jobpromiseToResolve, thenable, 및 then을 captures하며 called될 때 다음 steps를 수행하는, parameters가 없는 new Job Abstract Closure로 둔다:
    1. resolvingFuncsCreateResolvingFunctions(promiseToResolve)로 둔다.
    2. thenCallResultCompletion(HostCallJobCallback(then, thenable, « resolvingFuncs.[[Resolve]], resolvingFuncs.[[Reject]] »))로 둔다.
    3. thenCallResultabrupt completion이면, 다음을 수행한다.
      1. Call(resolvingFuncs.[[Reject]], undefined, « thenCallResult.[[Value]] »)를 반환한다.
    4. thenCallResult를 반환한다.
  2. getThenRealmResultCompletion(GetFunctionRealm(then.[[Callback]]))으로 둔다.
  3. getThenRealmResultnormal completion이면, thenRealmgetThenRealmResult.[[Value]]로 둔다.
  4. Else, thenRealm을 current Realm Record로 둔다.
  5. NOTE: thenRealm은 never null이다. then.[[Callback]]이 revoked Proxy이고 code가 실행되지 않을 때, thenRealm은 error objects를 create하는 데 사용된다.
  6. Record { [[Job]]: job, [[Realm]]: thenRealm }를 반환한다.
Note

Job은 supplied thenable과 its then method를 사용하여 given promise를 resolve합니다. 이 process는 then method의 evaluation이 any surrounding code의 evaluation이 completed된 후 occur하도록 보장하기 위해 Job으로 일어나야 합니다.

27.5.3 Promise Constructor

Promise constructor는:

  • %Promise%입니다.
  • global object"Promise" property의 initial value입니다.
  • constructor로 called될 때 new Promise를 create하고 initialize합니다.
  • function으로 called되도록 intended되지 않으며, 그런 방식으로 called되면 exception을 throw합니다.
  • 클래스 정의의 extends 절의 값으로 사용될 수 있다. 지정된 Promise 동작을 상속하려는 서브클래스 생성자는 PromisePromise.prototype의 내장 메서드를 지원하는 데 필요한 내부 상태로 서브클래스 인스턴스를 생성하고 초기화하기 위해 Promise 생성자에 대한 super 호출을 포함해야 한다.

27.5.3.1 Promise ( executor )

이 function은 called될 때 다음 steps를 수행합니다:

  1. NewTarget이 undefined이면, TypeError exception을 throw한다.
  2. IsCallable(executor)가 false이면, TypeError exception을 throw한다.
  3. promise를 ? OrdinaryCreateFromConstructor(NewTarget, "%Promise.prototype%", « [[PromiseState]], [[PromiseResult]], [[PromiseFulfillReactions]], [[PromiseRejectReactions]], [[PromiseIsHandled]] »)로 둔다.
  4. promise.[[PromiseState]]pending으로 설정한다.
  5. promise.[[PromiseResult]]empty로 설정한다.
  6. promise.[[PromiseFulfillReactions]]를 new empty List로 설정한다.
  7. promise.[[PromiseRejectReactions]]를 new empty List로 설정한다.
  8. promise.[[PromiseIsHandled]]false로 설정한다.
  9. resolvingFuncsCreateResolvingFunctions(promise)로 둔다.
  10. completionCompletion(Call(executor, undefined, « resolvingFuncs.[[Resolve]], resolvingFuncs.[[Reject]] »))로 둔다.
  11. completionabrupt completion이면, 다음을 수행한다.
    1. Call(resolvingFuncs.[[Reject]], undefined, « completion.[[Value]] »)를 수행한다.
  12. promise를 반환한다.
Note

executor argument는 function object여야 합니다. 이는 이 Promise에 의해 represented되는 possibly deferred action의 initiating 및 reporting completion을 위해 called됩니다. executor는 두 arguments, resolvereject로 called됩니다. 이들은 executor function이 deferred computation의 eventual completion 또는 failure를 report하는 데 사용할 수 있는 functions입니다. executor function에서 returning하는 것은 deferred action이 completed되었음을 의미하지 않고, eventual deferred action 수행 request가 accepted되었음을 의미할 뿐입니다.

executor function에 passed되는 resolve function은 single argument를 accepts합니다. executor code는 eventually associated Promise를 resolve하기 원함을 indicate하기 위해 resolve function을 call할 수 있습니다. resolve function에 passed되는 argument는 deferred action의 eventual value를 represent하며, actual fulfillment value 또는 fulfilled될 경우 value를 provide할 another promise일 수 있습니다.

executor function에 passed되는 reject function은 single argument를 accepts합니다. executor code는 associated Promise가 rejected되며 결코 fulfilled되지 않음을 indicate하기 위해 reject function을 eventually call할 수 있습니다. reject function에 passed되는 argument는 promise의 rejection value로 used됩니다. Typically Error object입니다.

Promise constructorexecutor function에 passed하는 resolve 및 reject functions는 associated promise를 actually resolve하고 reject할 capability를 가집니다. Subclasses는 resolve와 reject에 대해 customized values를 pass하는 different constructor behaviour를 가질 수 있습니다.

27.5.4 Promise Constructor의 Properties

Promise constructor는:

  • value가 %Function.prototype%[[Prototype]] internal slot을 가집니다.
  • 다음 properties를 가집니다:

27.5.4.1 Promise.all ( iterable )

이 function은 passed promises의 fulfillment values array로 fulfilled되는 new promise를 반환하거나, rejects하는 first passed promise의 reason으로 rejects합니다. 이 algorithm을 run하면서 passed iterable의 모든 elements를 promises로 resolves합니다.

  1. ctorthis value로 둔다.
  2. promiseCapability를 ? NewPromiseCapability(ctor)로 둔다.
  3. promiseResolveCompletion(GetPromiseResolve(ctor))로 둔다.
  4. IfAbruptRejectPromise(promiseResolve, promiseCapability).
  5. iteratorRecordCompletion(GetIterator(iterable, sync))로 둔다.
  6. IfAbruptRejectPromise(iteratorRecord, promiseCapability).
  7. resultCompletion(PerformPromiseAll(iteratorRecord, ctor, promiseCapability, promiseResolve))로 둔다.
  8. resultabrupt completion이면, 다음을 수행한다.
    1. iteratorRecord.[[Done]]false이면, resultCompletion(IteratorClose(iteratorRecord, result))로 설정한다.
    2. IfAbruptRejectPromise(result, promiseCapability).
  9. result를 반환한다.
Note

이 function은 its this value가 Promise constructor의 parameter conventions를 support하는 constructor function일 것을 require합니다.

27.5.4.1.1 GetPromiseResolve ( promiseCtor )

The abstract operation GetPromiseResolve takes argument promiseCtor (a constructor) and returns either a normal completion containing a function object or a throw completion. It performs the following steps when called:

  1. promiseResolve를 ? Get(promiseCtor, "resolve")로 둔다.
  2. IsCallable(promiseResolve)가 false이면, TypeError exception을 throw한다.
  3. promiseResolve를 반환한다.

27.5.4.1.2 PerformPromiseAll ( iteratorRecord, ctor, resultCapability, promiseResolve )

The abstract operation PerformPromiseAll takes arguments iteratorRecord (an Iterator Record), ctor (a constructor), resultCapability (a PromiseCapability Record), and promiseResolve (a function object) and returns either a normal completion containing an Object or a throw completion. It performs the following steps when called:

  1. values를 new empty List로 둔다.
  2. NOTE: remainingElementsCount는 0 대신 1에서 시작하여, passed callback이 input iterator가 exhausted되기 전에 misbehaving "then"에 의해 called되는 경우에도 resultCapability.[[Resolve]]가 only once called되도록 ensure한다.
  3. remainingElementsCountRecord { [[Value]]: 1 }로 둔다.
  4. index를 0으로 둔다.
  5. Repeat,
    1. next를 ? IteratorStepValue(iteratorRecord)로 둔다.
    2. nextdone이면, 다음을 수행한다.
      1. remainingElementsCount.[[Value]]remainingElementsCount.[[Value]] - 1로 설정한다.
      2. remainingElementsCount.[[Value]] = 0이면, 다음을 수행한다.
        1. valuesArrayCreateArrayFromList(values)로 둔다.
        2. Call(resultCapability.[[Resolve]], undefined, « valuesArray »)를 수행한다.
      3. resultCapability.[[Promise]]를 반환한다.
    3. undefinedvalues에 append한다.
    4. nextPromise를 ? Call(promiseResolve, ctor, « next »)로 둔다.
    5. fulfilledSteps를 parameters (value)를 가지고 values, resultCapability, 및 remainingElementsCount를 captures하며 called될 때 다음 steps를 수행하는 new Abstract Closure로 둔다:
      1. activeFunc를 active function object로 둔다.
      2. activeFunc.[[AlreadyCalled]]true이면, undefined를 반환한다.
      3. activeFunc.[[AlreadyCalled]]true로 설정한다.
      4. thisIndexactiveFunc.[[Index]]로 둔다.
      5. values[thisIndex]를 value로 설정한다.
      6. remainingElementsCount.[[Value]]remainingElementsCount.[[Value]] - 1로 설정한다.
      7. remainingElementsCount.[[Value]] = 0이면, 다음을 수행한다.
        1. valuesArrayCreateArrayFromList(values)로 둔다.
        2. Call(resultCapability.[[Resolve]], undefined, « valuesArray »)를 반환한다.
      8. undefined를 반환한다.
    6. onFulfilledCreateBuiltinFunction(fulfilledSteps, 1, "", « [[AlreadyCalled]], [[Index]] »)로 둔다.
    7. onFulfilled.[[AlreadyCalled]]false로 설정한다.
    8. onFulfilled.[[Index]]index로 설정한다.
    9. indexindex + 1로 설정한다.
    10. remainingElementsCount.[[Value]]remainingElementsCount.[[Value]] + 1로 설정한다.
    11. Invoke(nextPromise, "then", « onFulfilled, resultCapability.[[Reject]] »)를 수행한다.

27.5.4.2 Promise.allSettled ( iterable )

이 function은 original promises가 모두 settled될 때, 즉 fulfilled 또는 rejected 중 하나가 될 때만 promise state snapshots의 array로 fulfilled되는 promise를 반환합니다. 이 algorithm을 run하면서 passed iterable의 모든 elements를 promises로 resolves합니다.

  1. ctorthis value로 둔다.
  2. promiseCapability를 ? NewPromiseCapability(ctor)로 둔다.
  3. promiseResolveCompletion(GetPromiseResolve(ctor))로 둔다.
  4. IfAbruptRejectPromise(promiseResolve, promiseCapability).
  5. iteratorRecordCompletion(GetIterator(iterable, sync))로 둔다.
  6. IfAbruptRejectPromise(iteratorRecord, promiseCapability).
  7. resultCompletion(PerformPromiseAllSettled(iteratorRecord, ctor, promiseCapability, promiseResolve))로 둔다.
  8. resultabrupt completion이면, 다음을 수행한다.
    1. iteratorRecord.[[Done]]false이면, resultCompletion(IteratorClose(iteratorRecord, result))로 설정한다.
    2. IfAbruptRejectPromise(result, promiseCapability).
  9. result를 반환한다.
Note

이 function은 its this value가 Promise constructor의 parameter conventions를 support하는 constructor function일 것을 require합니다.

27.5.4.2.1 PerformPromiseAllSettled ( iteratorRecord, ctor, resultCapability, promiseResolve )

The abstract operation PerformPromiseAllSettled takes arguments iteratorRecord (an Iterator Record), ctor (a constructor), resultCapability (a PromiseCapability Record), and promiseResolve (a function object) and returns either a normal completion containing an Object or a throw completion. It performs the following steps when called:

  1. values를 new empty List로 둔다.
  2. NOTE: remainingElementsCount는 0 대신 1에서 시작하여, passed callbacks 중 하나가 input iterator가 exhausted되기 전에 misbehaving "then"에 의해 called되는 경우에도 resultCapability.[[Resolve]]가 only once called되도록 ensure한다.
  3. remainingElementsCountRecord { [[Value]]: 1 }로 둔다.
  4. index를 0으로 둔다.
  5. Repeat,
    1. next를 ? IteratorStepValue(iteratorRecord)로 둔다.
    2. nextdone이면, 다음을 수행한다.
      1. remainingElementsCount.[[Value]]remainingElementsCount.[[Value]] - 1로 설정한다.
      2. remainingElementsCount.[[Value]] = 0이면, 다음을 수행한다.
        1. valuesArrayCreateArrayFromList(values)로 둔다.
        2. Call(resultCapability.[[Resolve]], undefined, « valuesArray »)를 수행한다.
      3. resultCapability.[[Promise]]를 반환한다.
    3. undefinedvalues에 append한다.
    4. nextPromise를 ? Call(promiseResolve, ctor, « next »)로 둔다.
    5. alreadyCalledRecord { [[Value]]: false }로 둔다.
    6. fulfilledSteps를 parameters (value)를 가지고 values, resultCapability, 및 remainingElementsCount를 captures하며 called될 때 다음 steps를 수행하는 new Abstract Closure로 둔다:
      1. activeFunc를 active function object로 둔다.
      2. activeFunc.[[AlreadyCalled]].[[Value]]true이면, undefined를 반환한다.
      3. activeFunc.[[AlreadyCalled]].[[Value]]true로 설정한다.
      4. objOrdinaryObjectCreate(%Object.prototype%)로 둔다.
      5. CreateDataPropertyOrThrow(obj, "status", "fulfilled")를 수행한다.
      6. CreateDataPropertyOrThrow(obj, "value", value)를 수행한다.
      7. thisIndexactiveFunc.[[Index]]로 둔다.
      8. values[thisIndex]를 obj로 설정한다.
      9. remainingElementsCount.[[Value]]remainingElementsCount.[[Value]] - 1로 설정한다.
      10. remainingElementsCount.[[Value]] = 0이면, 다음을 수행한다.
        1. valuesArrayCreateArrayFromList(values)로 둔다.
        2. Call(resultCapability.[[Resolve]], undefined, « valuesArray »)를 반환한다.
      11. undefined를 반환한다.
    7. onFulfilledCreateBuiltinFunction(fulfilledSteps, 1, "", « [[AlreadyCalled]], [[Index]] »)로 둔다.
    8. onFulfilled.[[AlreadyCalled]]alreadyCalled로 설정한다.
    9. onFulfilled.[[Index]]index로 설정한다.
    10. rejectedSteps를 parameters (error)를 가지고 values, resultCapability, 및 remainingElementsCount를 captures하며 called될 때 다음 steps를 수행하는 new Abstract Closure로 둔다:
      1. activeFunc를 active function object로 둔다.
      2. activeFunc.[[AlreadyCalled]].[[Value]]true이면, undefined를 반환한다.
      3. activeFunc.[[AlreadyCalled]].[[Value]]true로 설정한다.
      4. objOrdinaryObjectCreate(%Object.prototype%)로 둔다.
      5. CreateDataPropertyOrThrow(obj, "status", "rejected")를 수행한다.
      6. CreateDataPropertyOrThrow(obj, "reason", error)를 수행한다.
      7. thisIndexactiveFunc.[[Index]]로 둔다.
      8. values[thisIndex]를 obj로 설정한다.
      9. remainingElementsCount.[[Value]]remainingElementsCount.[[Value]] - 1로 설정한다.
      10. remainingElementsCount.[[Value]] = 0이면, 다음을 수행한다.
        1. valuesArrayCreateArrayFromList(values)로 둔다.
        2. Call(resultCapability.[[Resolve]], undefined, « valuesArray »)를 반환한다.
      11. undefined를 반환한다.
    11. onRejectedCreateBuiltinFunction(rejectedSteps, 1, "", « [[AlreadyCalled]], [[Index]] »)로 둔다.
    12. onRejected.[[AlreadyCalled]]alreadyCalled로 설정한다.
    13. onRejected.[[Index]]index로 설정한다.
    14. indexindex + 1로 설정한다.
    15. remainingElementsCount.[[Value]]remainingElementsCount.[[Value]] + 1로 설정한다.
    16. Invoke(nextPromise, "then", « onFulfilled, onRejected »)를 수행한다.

27.5.4.3 Promise.any ( iterable )

이 function은 fulfilled되는 first given promise에 의해 fulfilled되거나, given promises가 모두 rejected되면 rejection reasons를 holding하는 AggregateError로 rejected되는 promise를 반환합니다. 이 algorithm을 run하면서 passed iterable의 모든 elements를 promises로 resolves합니다.

  1. ctorthis value로 둔다.
  2. promiseCapability를 ? NewPromiseCapability(ctor)로 둔다.
  3. promiseResolveCompletion(GetPromiseResolve(ctor))로 둔다.
  4. IfAbruptRejectPromise(promiseResolve, promiseCapability).
  5. iteratorRecordCompletion(GetIterator(iterable, sync))로 둔다.
  6. IfAbruptRejectPromise(iteratorRecord, promiseCapability).
  7. resultCompletion(PerformPromiseAny(iteratorRecord, ctor, promiseCapability, promiseResolve))로 둔다.
  8. resultabrupt completion이면, 다음을 수행한다.
    1. iteratorRecord.[[Done]]false이면, resultCompletion(IteratorClose(iteratorRecord, result))로 설정한다.
    2. IfAbruptRejectPromise(result, promiseCapability).
  9. result를 반환한다.
Note

이 function은 its this value가 Promise constructor의 parameter conventions를 support하는 constructor function일 것을 require합니다.

27.5.4.3.1 PerformPromiseAny ( iteratorRecord, ctor, resultCapability, promiseResolve )

The abstract operation PerformPromiseAny takes arguments iteratorRecord (an Iterator Record), ctor (a constructor), resultCapability (a PromiseCapability Record), and promiseResolve (a function object) and returns either a normal completion containing an Object or a throw completion. It performs the following steps when called:

  1. errors를 new empty List로 둔다.
  2. NOTE: remainingElementsCount는 0 대신 1에서 시작하여, passed callback이 input iterator가 exhausted되기 전에 misbehaving "then"에 의해 called되는 경우에도 resultCapability.[[Reject]]가 only once called되도록 ensure한다.
  3. remainingElementsCountRecord { [[Value]]: 1 }로 둔다.
  4. index를 0으로 둔다.
  5. Repeat,
    1. next를 ? IteratorStepValue(iteratorRecord)로 둔다.
    2. nextdone이면, 다음을 수행한다.
      1. remainingElementsCount.[[Value]]remainingElementsCount.[[Value]] - 1로 설정한다.
      2. remainingElementsCount.[[Value]] = 0이면, 다음을 수행한다.
        1. aggregateError를 newly created AggregateError object로 둔다.
        2. DefinePropertyOrThrow(aggregateError, "errors", PropertyDescriptor { [[Configurable]]: true, [[Enumerable]]: false, [[Writable]]: true, [[Value]]: CreateArrayFromList(errors) })를 수행한다.
        3. Call(resultCapability.[[Reject]], undefined, « aggregateError »)를 수행한다.
      3. resultCapability.[[Promise]]를 반환한다.
    3. undefinederrors에 append한다.
    4. nextPromise를 ? Call(promiseResolve, ctor, « next »)로 둔다.
    5. rejectedSteps를 parameters (error)를 가지고 errors, resultCapability, 및 remainingElementsCount를 captures하며 called될 때 다음 steps를 수행하는 new Abstract Closure로 둔다:
      1. activeFunc를 active function object로 둔다.
      2. activeFunc.[[AlreadyCalled]]true이면, undefined를 반환한다.
      3. activeFunc.[[AlreadyCalled]]true로 설정한다.
      4. thisIndexactiveFunc.[[Index]]로 둔다.
      5. errors[thisIndex]를 error로 설정한다.
      6. remainingElementsCount.[[Value]]remainingElementsCount.[[Value]] - 1로 설정한다.
      7. remainingElementsCount.[[Value]] = 0이면, 다음을 수행한다.
        1. aggregateError를 newly created AggregateError object로 둔다.
        2. DefinePropertyOrThrow(aggregateError, "errors", PropertyDescriptor { [[Configurable]]: true, [[Enumerable]]: false, [[Writable]]: true, [[Value]]: CreateArrayFromList(errors) })를 수행한다.
        3. Call(resultCapability.[[Reject]], undefined, « aggregateError »)를 반환한다.
      8. undefined를 반환한다.
    6. onRejectedCreateBuiltinFunction(rejectedSteps, 1, "", « [[AlreadyCalled]], [[Index]] »)로 둔다.
    7. onRejected.[[AlreadyCalled]]false로 설정한다.
    8. onRejected.[[Index]]index로 설정한다.
    9. indexindex + 1로 설정한다.
    10. remainingElementsCount.[[Value]]remainingElementsCount.[[Value]] + 1로 설정한다.
    11. Invoke(nextPromise, "then", « resultCapability.[[Resolve]], onRejected »)를 수행한다.

27.5.4.4 Promise.prototype

Promise.prototype의 initial value는 Promise prototype object입니다.

이 property는 attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }를 가집니다.

27.5.4.5 Promise.race ( iterable )

이 function은 settle되는 first passed promise와 same way로 settled되는 new promise를 반환합니다. 이 algorithm을 run하면서 passed iterable의 모든 elements를 promises로 resolves합니다.

  1. ctorthis value로 둔다.
  2. promiseCapability를 ? NewPromiseCapability(ctor)로 둔다.
  3. promiseResolveCompletion(GetPromiseResolve(ctor))로 둔다.
  4. IfAbruptRejectPromise(promiseResolve, promiseCapability).
  5. iteratorRecordCompletion(GetIterator(iterable, sync))로 둔다.
  6. IfAbruptRejectPromise(iteratorRecord, promiseCapability).
  7. resultCompletion(PerformPromiseRace(iteratorRecord, ctor, promiseCapability, promiseResolve))로 둔다.
  8. resultabrupt completion이면, 다음을 수행한다.
    1. iteratorRecord.[[Done]]false이면, resultCompletion(IteratorClose(iteratorRecord, result))로 설정한다.
    2. IfAbruptRejectPromise(result, promiseCapability).
  9. result를 반환한다.
Note 1

iterable argument가 no values를 yield하거나 iterable에 의해 yielded된 promises 중 none이 ever settle하지 않으면, 이 method가 반환하는 pending promise는 never settled됩니다.

Note 2

이 function은 its this value가 Promise constructor의 parameter conventions를 support하는 constructor function일 것을 expects합니다. 또한 its this value가 resolve method를 provide할 것을 expects합니다.

27.5.4.5.1 PerformPromiseRace ( iteratorRecord, ctor, resultCapability, promiseResolve )

The abstract operation PerformPromiseRace takes arguments iteratorRecord (an Iterator Record), ctor (a constructor), resultCapability (a PromiseCapability Record), and promiseResolve (a function object) and returns either a normal completion containing an Object or a throw completion. It performs the following steps when called:

  1. Repeat,
    1. next를 ? IteratorStepValue(iteratorRecord)로 둔다.
    2. nextdone이면, 다음을 수행한다.
      1. resultCapability.[[Promise]]를 반환한다.
    3. nextPromise를 ? Call(promiseResolve, ctor, « next »)로 둔다.
    4. Invoke(nextPromise, "then", « resultCapability.[[Resolve]], resultCapability.[[Reject]] »)를 수행한다.

27.5.4.6 Promise.reject ( reason )

이 function은 passed argument로 rejected된 new promise를 반환합니다.

  1. ctorthis value로 둔다.
  2. promiseCapability를 ? NewPromiseCapability(ctor)로 둔다.
  3. Call(promiseCapability.[[Reject]], undefined, « reason »)를 수행한다.
  4. promiseCapability.[[Promise]]를 반환한다.
Note

이 function은 its this value가 Promise constructor의 parameter conventions를 support하는 constructor function일 것을 expects합니다.

27.5.4.7 Promise.resolve ( resolution )

이 function은 passed argument로 resolved된 new promise를 반환하거나, argument가 this constructor에 의해 produced된 promise이면 argument 자체를 반환합니다.

  1. ctorthis value로 둔다.
  2. ctor가 Object가 아니면, TypeError exception을 throw한다.
  3. PromiseResolve(ctor, resolution)를 반환한다.
Note

이 function은 its this value가 Promise constructor의 parameter conventions를 support하는 constructor function일 것을 expects합니다.

27.5.4.7.1 PromiseResolve ( ctor, resolution )

The abstract operation PromiseResolve takes arguments ctor (an Object) and resolution (an ECMAScript language value) and returns either a normal completion containing an Object or a throw completion. resolution으로 resolved된 new promise를 반환합니다. It performs the following steps when called:

  1. IsPromise(resolution)가 true이면, 다음을 수행한다.
    1. resolutionCtor를 ? Get(resolution, "constructor")로 둔다.
    2. SameValue(resolutionCtor, ctor)가 true이면, resolution을 반환한다.
  2. promiseCapability를 ? NewPromiseCapability(ctor)로 둔다.
  3. Call(promiseCapability.[[Resolve]], undefined, « resolution »)를 수행한다.
  4. promiseCapability.[[Promise]]를 반환한다.

27.5.4.8 Promise.try ( callback, ...args )

이 function은 called될 때 다음 steps를 수행합니다:

  1. ctorthis value로 둔다.
  2. ctor가 Object가 아니면, TypeError exception을 throw한다.
  3. promiseCapability를 ? NewPromiseCapability(ctor)로 둔다.
  4. statusCompletion(Call(callback, undefined, args))로 둔다.
  5. statusabrupt completion이면, 다음을 수행한다.
    1. Call(promiseCapability.[[Reject]], undefined, « status.[[Value]] »)를 수행한다.
  6. Else,
    1. Call(promiseCapability.[[Resolve]], undefined, « status.[[Value]] »)를 수행한다.
  7. promiseCapability.[[Promise]]를 반환한다.
Note

이 function은 its this value가 Promise constructor의 parameter conventions를 support하는 constructor function일 것을 expects합니다.

27.5.4.9 Promise.withResolvers ( )

이 function은 세 properties를 가진 object를 반환합니다: new promise와 그에 associated된 resolvereject functions.

  1. ctorthis value로 둔다.
  2. promiseCapability를 ? NewPromiseCapability(ctor)로 둔다.
  3. objOrdinaryObjectCreate(%Object.prototype%)로 둔다.
  4. CreateDataPropertyOrThrow(obj, "promise", promiseCapability.[[Promise]])를 수행한다.
  5. CreateDataPropertyOrThrow(obj, "resolve", promiseCapability.[[Resolve]])를 수행한다.
  6. CreateDataPropertyOrThrow(obj, "reject", promiseCapability.[[Reject]])를 수행한다.
  7. obj를 반환한다.

27.5.4.10 get Promise [ %Symbol.species% ]

Promise[%Symbol.species%]는 set accessor function이 undefinedaccessor property입니다. Its get accessor function은 called될 때 다음 steps를 수행합니다:

  1. this value를 반환한다.

이 function의 "name" property의 value는 "get [Symbol.species]"입니다.

Note

Promise prototype methods는 normally derived object를 create하기 위해 their this value's constructor를 사용합니다. 그러나 subclass constructor는 its %Symbol.species% property를 redefining하여 that default behaviour를 over-ride할 수 있습니다.

27.5.5 Promise Prototype Object의 Properties

Promise prototype object는:

  • %Promise.prototype%입니다.
  • value가 %Object.prototype%[[Prototype]] internal slot을 가집니다.
  • ordinary object입니다.
  • [[PromiseState]] internal slot 또는 Promise instances의 other internal slots 중 any를 가지지 않습니다.

27.5.5.1 Promise.prototype.catch ( onRejected )

이 method는 called될 때 다음 steps를 수행합니다:

  1. promisethis value로 둔다.
  2. Invoke(promise, "then", « undefined, onRejected »)를 반환한다.

27.5.5.2 Promise.prototype.constructor

Promise.prototype.constructor의 initial value는 %Promise%입니다.

27.5.5.3 Promise.prototype.finally ( onFinally )

이 method는 called될 때 다음 steps를 수행합니다:

  1. promisethis value로 둔다.
  2. promise가 Object가 아니면, TypeError exception을 throw한다.
  3. ctor를 ? SpeciesConstructor(promise, %Promise%)로 둔다.
  4. Assert: IsConstructor(ctor)는 true이다.
  5. IsCallable(onFinally)가 false이면, 다음을 수행한다.
    1. thenFinallyonFinally로 둔다.
    2. catchFinallyonFinally로 둔다.
  6. Else,
    1. thenFinallyClosure를 parameters (value)를 가지고 onFinallyctor를 captures하며 called될 때 다음 steps를 수행하는 new Abstract Closure로 둔다:
      1. result를 ? Call(onFinally, undefined)로 둔다.
      2. p를 ? PromiseResolve(ctor, result)로 둔다.
      3. returnValue를 parameters가 없고 value를 captures하며 called될 때 다음 steps를 수행하는 new Abstract Closure로 둔다:
        1. NormalCompletion(value)를 반환한다.
      4. valueThunkCreateBuiltinFunction(returnValue, 0, "", « »)로 둔다.
      5. Invoke(p, "then", « valueThunk »)를 반환한다.
    2. thenFinallyCreateBuiltinFunction(thenFinallyClosure, 1, "", « »)로 둔다.
    3. catchFinallyClosure를 parameters (reason)를 가지고 onFinallyctor를 captures하며 called될 때 다음 steps를 수행하는 new Abstract Closure로 둔다:
      1. result를 ? Call(onFinally, undefined)로 둔다.
      2. p를 ? PromiseResolve(ctor, result)로 둔다.
      3. throwReason을 parameters가 없고 reason을 captures하며 called될 때 다음 steps를 수행하는 new Abstract Closure로 둔다:
        1. Throw reason.
      4. throwerCreateBuiltinFunction(throwReason, 0, "", « »)로 둔다.
      5. Invoke(p, "then", « thrower »)를 반환한다.
    4. catchFinallyCreateBuiltinFunction(catchFinallyClosure, 1, "", « »)로 둔다.
  7. Invoke(promise, "then", « thenFinally, catchFinally »)를 반환한다.

27.5.5.4 Promise.prototype.then ( onFulfilled, onRejected )

이 method는 called될 때 다음 steps를 수행합니다:

  1. promisethis value로 둔다.
  2. IsPromise(promise)가 false이면, TypeError exception을 throw한다.
  3. ctor를 ? SpeciesConstructor(promise, %Promise%)로 둔다.
  4. resultCapability를 ? NewPromiseCapability(ctor)로 둔다.
  5. PerformPromiseThen(promise, onFulfilled, onRejected, resultCapability)를 반환한다.

27.5.5.4.1 PerformPromiseThen ( promise, onFulfilled, onRejected [ , resultCapability ] )

The abstract operation PerformPromiseThen takes arguments promise (a Promise), onFulfilled (an ECMAScript language value), and onRejected (an ECMAScript language value) and optional argument resultCapability (a PromiseCapability Record) and returns an Object or undefined. onFulfilledonRejected를 settlement actions로 사용하여 promise에 “then” operation을 수행합니다. resultCapability가 passed되면, result는 resultCapability의 promise를 updating하여 stored됩니다. passed되지 않으면, PerformPromiseThen은 result가 matter하지 않는 specification-internal operation에 의해 called되고 있는 것입니다. It performs the following steps when called:

  1. Assert: IsPromise(promise)는 true이다.
  2. resultCapability가 present하지 않으면, 다음을 수행한다.
    1. resultCapabilityundefined로 설정한다.
  3. IsCallable(onFulfilled)가 false이면, 다음을 수행한다.
    1. onFulfilledJobCallbackempty로 둔다.
  4. Else,
    1. onFulfilledJobCallbackHostMakeJobCallback(onFulfilled)로 둔다.
  5. IsCallable(onRejected)가 false이면, 다음을 수행한다.
    1. onRejectedJobCallbackempty로 둔다.
  6. Else,
    1. onRejectedJobCallbackHostMakeJobCallback(onRejected)로 둔다.
  7. fulfillReactionPromiseReaction Record { [[Capability]]: resultCapability, [[Type]]: fulfill, [[Handler]]: onFulfilledJobCallback }로 둔다.
  8. rejectReactionPromiseReaction Record { [[Capability]]: resultCapability, [[Type]]: reject, [[Handler]]: onRejectedJobCallback }로 둔다.
  9. promise.[[PromiseState]]pending이면, 다음을 수행한다.
    1. fulfillReactionpromise.[[PromiseFulfillReactions]]에 append한다.
    2. rejectReactionpromise.[[PromiseRejectReactions]]에 append한다.
  10. Else if promise.[[PromiseState]] is fulfilled, then
    1. valuepromise.[[PromiseResult]]로 둔다.
    2. fulfillJobNewPromiseReactionJob(fulfillReaction, value)로 둔다.
    3. HostEnqueuePromiseJob(fulfillJob.[[Job]], fulfillJob.[[Realm]])을 수행한다.
  11. Else,
    1. Assert: promise.[[PromiseState]]rejected이다.
    2. reasonpromise.[[PromiseResult]]로 둔다.
    3. promise.[[PromiseIsHandled]]false이면, HostPromiseRejectionTracker(promise, "handle")를 수행한다.
    4. rejectJobNewPromiseReactionJob(rejectReaction, reason)로 둔다.
    5. HostEnqueuePromiseJob(rejectJob.[[Job]], rejectJob.[[Realm]])을 수행한다.
  12. promise.[[PromiseIsHandled]]true로 설정한다.
  13. resultCapabilityundefined이면, undefined를 반환한다.
  14. resultCapability.[[Promise]]를 반환한다.

27.5.5.5 Promise.prototype [ %Symbol.toStringTag% ]

%Symbol.toStringTag% property의 initial value는 String value "Promise"입니다.

이 property는 attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }를 가집니다.

27.5.6 Promise Instances의 Properties

Promise instances는 Promise prototype object(intrinsic, %Promise.prototype%)로부터 properties를 inherit하는 ordinary objects입니다. Promise instances는 Table 93에 described된 internal slots로 initially created됩니다.

Table 93: Internal Slots of Promise Instances
Internal Slot Type Description
[[PromiseState]] pending, fulfilled, 또는 rejected promise가 its then method에 대한 incoming calls에 어떻게 react할지를 governs합니다.
[[PromiseResult]] ECMAScript language value 또는 empty promise가 fulfilled 또는 rejected된 value, if any. [[PromiseState]]pending인 경우에만 empty입니다.
[[PromiseFulfillReactions]] PromiseReaction RecordsList promise가 pending state에서 fulfilled state로 transitions할 때/한다면 processed될 Records.
[[PromiseRejectReactions]] PromiseReaction RecordsList promise가 pending state에서 rejected state로 transitions할 때/한다면 processed될 Records.
[[PromiseIsHandled]] Boolean promise가 fulfillment 또는 rejection handler를 ever had했는지를 indicates합니다; unhandled rejection tracking에 used됩니다.

27.6 GeneratorFunction 객체

GeneratorFunctions는 보통 GeneratorDeclaration, GeneratorExpression, 및 GeneratorMethod를 평가하여 생성되는 functions입니다. 또한 %GeneratorFunction% intrinsic을 호출하여 생성될 수도 있습니다.

Figure 6 (Informative): Generator 객체 관계
다양한 boxes와 arrows.

27.6.1 GeneratorFunction Constructor

GeneratorFunction constructor는:

  • %GeneratorFunction%입니다.
  • Function의 subclass입니다.
  • constructor가 아니라 function으로 호출될 때 새 GeneratorFunction을 생성하고 초기화합니다. 따라서 function call GeneratorFunction (…)은 같은 arguments를 가진 object creation expression new GeneratorFunction (…)과 동등합니다.
  • class definition의 extends clause의 value로 사용될 수 있습니다. 지정된 GeneratorFunction behaviour를 상속하려는 subclass constructors는 built-in GeneratorFunction behaviour에 필요한 internal slots를 가진 subclass instances를 생성하고 초기화하기 위해 GeneratorFunction constructor에 대한 super call을 포함해야 합니다. generator function objects를 정의하는 모든 ECMAScript syntactic forms는 GeneratorFunction의 direct instances를 생성합니다. GeneratorFunction subclasses의 instances를 생성하는 syntactic means는 없습니다.

27.6.1.1 GeneratorFunction ( ...paramArgs, bodyArg )

마지막 argument(있다면)는 generator function의 body(executable code)를 지정하고, preceding arguments는 formal parameters를 지정합니다.

이 function은 호출될 때 다음 steps를 수행합니다:

  1. activeFunc를 active function object로 둔다.
  2. bodyArg가 present하지 않으면, bodyArg를 empty String으로 설정한다.
  3. CreateDynamicFunction(activeFunc, NewTarget, generator, paramArgs, bodyArg)를 반환한다.
Note

20.2.1.1NOTE를 참조하십시오.

27.6.2 GeneratorFunction Constructor의 Properties

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의 Properties

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 Instances

모든 GeneratorFunction instance는 ECMAScript function object이며 Table 26에 listed된 internal slots를 가집니다. 그러한 모든 instances의 [[IsClassConstructor]] internal slot의 value는 false입니다.

각 GeneratorFunction instance는 다음 own properties를 가집니다:

27.6.4.1 length

20.2.4.1에 given된 Function instances의 "length" property에 대한 specification은 GeneratorFunction instances에도 적용됩니다.

27.6.4.2 name

20.2.4.2에 given된 Function instances의 "name" property에 대한 specification은 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될 때 newly created 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을 호출하여 생성될 수도 있습니다.

27.7.1 AsyncGeneratorFunction Constructor

AsyncGeneratorFunction constructor는:

  • %AsyncGeneratorFunction%입니다.
  • Function의 subclass입니다.
  • constructor가 아니라 function으로 호출될 때 새 AsyncGeneratorFunction을 생성하고 초기화합니다. 따라서 function call AsyncGeneratorFunction (...)은 같은 arguments를 가진 object creation expression new AsyncGeneratorFunction (...)과 동등합니다.
  • class definition의 extends clause의 value로 사용될 수 있습니다. 지정된 AsyncGeneratorFunction behaviour를 상속하려는 subclass constructors는 built-in AsyncGeneratorFunction behaviour에 필요한 internal slots를 가진 subclass instances를 생성하고 초기화하기 위해 AsyncGeneratorFunction constructor에 대한 super call을 포함해야 합니다. async generator function objects를 정의하는 모든 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)를 지정하고, preceding arguments는 formal parameters를 지정합니다.

이 function은 호출될 때 다음 steps를 수행합니다:

  1. activeFunc를 active function object로 둔다.
  2. bodyArg가 present하지 않으면, bodyArg를 empty String으로 설정한다.
  3. CreateDynamicFunction(activeFunc, NewTarget, async-generator, paramArgs, bodyArg)를 반환한다.
Note

20.2.1.1NOTE를 참조하십시오.

27.7.2 AsyncGeneratorFunction Constructor의 Properties

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의 Properties

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 Instances

모든 AsyncGeneratorFunction instance는 ECMAScript function object이며 Table 26에 listed된 internal slots를 가집니다. 그러한 모든 instances의 [[IsClassConstructor]] internal slot의 value는 false입니다.

각 AsyncGeneratorFunction instance는 다음 own properties를 가집니다:

27.7.4.1 length

"length" property의 value는 AsyncGeneratorFunction이 expected하는 typical number of arguments를 나타내는 integral Number입니다. 그러나 language는 function이 다른 number of arguments로 invoked되는 것을 permits합니다. "length" property가 specified한 number가 아닌 number of arguments로 invoked될 때 AsyncGeneratorFunction의 behaviour는 function에 depends합니다.

이 property는 attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }를 가집니다.

27.7.4.2 name

20.2.4.2에 given된 Function instances의 "name" property에 대한 specification은 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될 때 newly created 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을 호출하여 생성되며 iterator interfaceiterable interface 둘 다에 conforms합니다.

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가 indirectly inherit하는 properties를 가집니다.

27.8.1.1 %GeneratorPrototype%.constructor

%GeneratorPrototype%.constructor의 initial value는 %GeneratorFunction.prototype%입니다.

이 property는 attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }를 가집니다.

27.8.1.2 %GeneratorPrototype%.next ( value )

  1. GeneratorResume(this value, value, empty)를 반환한다.

27.8.1.3 %GeneratorPrototype%.return ( value )

이 method는 호출될 때 다음 steps를 수행합니다:

  1. genthis value로 둔다.
  2. completionReturnCompletion(value)로 둔다.
  3. GeneratorResumeAbrupt(gen, completion, empty)를 반환한다.

27.8.1.4 %GeneratorPrototype%.throw ( exception )

이 method는 호출될 때 다음 steps를 수행합니다:

  1. genthis value로 둔다.
  2. completionThrowCompletion(exception)으로 둔다.
  3. GeneratorResumeAbrupt(gen, completion, empty)를 반환한다.

27.8.1.5 %GeneratorPrototype% [ %Symbol.toStringTag% ]

%Symbol.toStringTag% property의 initial value는 String value "Generator"입니다.

이 property는 attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }를 가집니다.

27.8.2 Generator Instances의 Properties

Generator instances는 Table 94에 described된 internal slots로 initially created됩니다.

Table 94: Generator Instances의 Internal Slots
Internal Slot Type Description
[[GeneratorState]] suspended-start, suspended-yield, executing, 또는 completed generator의 current execution state.
[[GeneratorContext]] execution context 이 generator의 code를 executing할 때 사용되는 execution context.
[[GeneratorBrand]] String 또는 empty different kinds of generators를 distinguish하기 위해 사용되는 brand. ECMAScript source text로 declared된 generators의 [[GeneratorBrand]]는 항상 empty입니다.

27.8.3 Generator Abstract Operations

27.8.3.1 GeneratorStart ( gen, genBody )

The abstract operation GeneratorStart takes arguments gen (a Generator) and genBody (a FunctionBody Parse Node or an Abstract Closure with no parameters) and returns unused. It performs the following steps when called:

  1. Assert: gen.[[GeneratorState]]suspended-start이다.
  2. genContextrunning execution context로 둔다.
  3. genContext의 Generator component를 gen으로 설정한다.
  4. closure를 parameters가 없고 genBody를 captures하며 호출될 때 다음 steps를 수행하는 new Abstract Closure로 둔다:
    1. acGenContextrunning execution context로 둔다.
    2. acGenacGenContext의 Generator component로 둔다.
    3. genBodyParse Node이면, 다음을 수행한다.
      1. resultCompletion(Evaluation of genBody)로 둔다.
    4. Else,
      1. Assert: genBody는 parameters가 없는 Abstract Closure이다.
      2. resultCompletion(genBody())로 둔다.
    5. Assert: 여기로 return한다면, generator는 exception을 throw했거나 implicit 또는 explicit return 중 하나를 수행했다.
    6. execution context stack에서 acGenContext를 remove하고, execution context stack의 top에 있는 execution contextrunning execution context로 restore한다.
    7. acGen.[[GeneratorState]]completed로 설정한다.
    8. NOTE: generator가 completed state에 들어가면 결코 이를 떠나지 않으며, its associated execution context는 결코 resumed되지 않는다. acGen과 associated된 any execution state는 이 시점에서 discarded될 수 있다.
    9. resultnormal completion이면, 다음을 수행한다.
      1. resultValueundefined로 둔다.
    10. Else if resultreturn completion이면, 다음을 수행한다.
      1. resultValueresult.[[Value]]로 둔다.
    11. Else,
      1. Assert: resultthrow completion이다.
      2. result를 반환한다.
    12. NormalCompletion(CreateIteratorResultObject(resultValue, true))를 반환한다.
  5. genContext의 code evaluation state를, 그 execution context에 대해 evaluation이 resumed될 때 closure가 no arguments로 called되도록 설정한다.
  6. gen.[[GeneratorContext]]genContext로 설정한다.
  7. unused를 반환한다.

27.8.3.2 GeneratorValidate ( gen, genBrand )

The abstract operation GeneratorValidate takes arguments gen (an ECMAScript language value) and genBrand (a String or empty) and returns either a normal completion containing one of suspended-start, suspended-yield, or completed, or a throw completion. It performs the following steps when called:

  1. RequireInternalSlot(gen, [[GeneratorState]])를 수행한다.
  2. RequireInternalSlot(gen, [[GeneratorBrand]])를 수행한다.
  3. gen.[[GeneratorBrand]]genBrand가 아니면, TypeError exception을 throw한다.
  4. Assert: gen[[GeneratorContext]] internal slot을 가진다.
  5. stategen.[[GeneratorState]]로 둔다.
  6. stateexecuting이면, TypeError exception을 throw한다.
  7. state를 반환한다.

27.8.3.3 GeneratorResume ( gen, value, genBrand )

The abstract operation GeneratorResume takes arguments gen (an ECMAScript language value), value (an ECMAScript language value or empty), and genBrand (a String or empty) and returns either a normal completion containing an ECMAScript language value or a throw completion. It performs the following steps when called:

  1. state를 ? GeneratorValidate(gen, genBrand)로 둔다.
  2. statecompleted이면, CreateIteratorResultObject(undefined, true)를 반환한다.
  3. Assert: statesuspended-start 또는 suspended-yield 중 하나이다.
  4. genContextgen.[[GeneratorContext]]로 둔다.
  5. gen.[[GeneratorState]]executing으로 설정한다.
  6. RunSuspendedContext(genContext, NormalCompletion(value))를 반환한다.

27.8.3.4 GeneratorResumeAbrupt ( gen, abruptCompletion, genBrand )

The abstract operation GeneratorResumeAbrupt takes arguments gen (an ECMAScript language value), abruptCompletion (a return completion or a throw completion), and genBrand (a String or empty) and returns either a normal completion containing an ECMAScript language value or a throw completion. It performs the following steps when called:

  1. state를 ? GeneratorValidate(gen, genBrand)로 둔다.
  2. statesuspended-start이면, 다음을 수행한다.
    1. gen.[[GeneratorState]]completed로 설정한다.
    2. NOTE: generator가 completed state에 들어가면 결코 이를 떠나지 않으며, its associated execution context는 결코 resumed되지 않는다. gen과 associated된 any execution state는 이 시점에서 discarded될 수 있다.
    3. statecompleted로 설정한다.
  3. statecompleted이면, 다음을 수행한다.
    1. abruptCompletionreturn completion이면, 다음을 수행한다.
      1. CreateIteratorResultObject(abruptCompletion.[[Value]], true)를 반환한다.
    2. abruptCompletion을 반환한다.
  4. Assert: statesuspended-yield이다.
  5. genContextgen.[[GeneratorContext]]로 둔다.
  6. gen.[[GeneratorState]]executing으로 설정한다.
  7. RunSuspendedContext(genContext, abruptCompletion)를 반환한다.

27.8.3.5 GetGeneratorKind ( )

The abstract operation GetGeneratorKind takes no arguments and returns non-generator, sync, or async. It performs the following steps when called:

  1. genContextrunning execution context로 둔다.
  2. genContext가 Generator component를 가지지 않으면, non-generator를 반환한다.
  3. gengenContext의 Generator component로 둔다.
  4. gen[[AsyncGeneratorState]] internal slot을 가지면, async를 반환한다.
  5. sync를 반환한다.

27.8.3.6 GeneratorYield ( iteratorResult )

The abstract operation GeneratorYield takes argument iteratorResult (an Object that conforms to the IteratorResult interface) and returns either a normal completion containing an ECMAScript language value or an abrupt completion. It performs the following steps when called:

  1. genContext를 실행 중인 실행 컨텍스트라 하자.
  2. Assert: genContext는 제너레이터의 실행 컨텍스트이다.
  3. gengenContext의 Generator 컴포넌트 값이라 하자.
  4. Assert: GetGeneratorKind()는 sync이다.
  5. gen.[[GeneratorState]]suspended-yield로 설정한다.
  6. RunCallerContext(iteratorResult)를 반환한다.

27.8.3.7 Yield ( arg )

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

  1. genKindGetGeneratorKind()로 둔다.
  2. genKindasync이면, ? AsyncGeneratorYield(? Await(arg))를 반환한다.
  3. GeneratorYield(CreateIteratorResultObject(arg, false))를 반환한다.

27.8.3.8 CreateIteratorFromClosure ( closure, genBrand, genProto [ , extraSlots ] )

The abstract operation CreateIteratorFromClosure takes arguments closure (an Abstract Closure with no parameters), genBrand (a String or empty), and genProto (an Object) and optional argument extraSlots (a List of names of internal slots) and returns a Generator. It performs the following steps when called:

  1. NOTE: closureIteratorResult object를 yield하기 위해 Yield operation의 uses를 contain할 수 있다.
  2. extraSlots가 present하지 않으면, extraSlots를 new empty List로 설정한다.
  3. internalSlotsListextraSlots와 « [[GeneratorState]], [[GeneratorContext]], [[GeneratorBrand]] »의 list-concatenation으로 둔다.
  4. genOrdinaryObjectCreate(genProto, internalSlotsList)로 둔다.
  5. gen.[[GeneratorBrand]]genBrand로 설정한다.
  6. gen.[[GeneratorState]]suspended-start로 설정한다.
  7. callerContextrunning execution context로 둔다.
  8. calleeContext를 new execution context로 둔다.
  9. calleeContext의 Function을 null로 설정한다.
  10. calleeContextRealm을 current Realm Record로 설정한다.
  11. calleeContext의 ScriptOrModule을 callerContext의 ScriptOrModule로 설정한다.
  12. callerContext가 already suspended가 아니면, callerContext를 suspend한다.
  13. calleeContextexecution context stack에 Push한다; calleeContext는 이제 running execution context이다.
  14. GeneratorStart(gen, closure)를 수행한다.
  15. execution context stack에서 calleeContext를 remove하고 callerContextrunning execution context로 restore한다.
  16. gen을 반환한다.

27.9 AsyncGenerator 객체

AsyncGenerator는 async generator function을 호출하여 생성되며 async iterator interfaceasync iterable interface 둘 다에 conforms합니다.

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가 indirectly inherit하는 properties를 가집니다.

27.9.1.1 %AsyncGeneratorPrototype%.constructor

%AsyncGeneratorPrototype%.constructor의 initial value는 %AsyncGeneratorFunction.prototype%입니다.

이 property는 attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }를 가집니다.

27.9.1.2 %AsyncGeneratorPrototype%.next ( value )

  1. genthis value로 둔다.
  2. promiseCapability를 ! NewPromiseCapability(%Promise%)로 둔다.
  3. resultCompletion(AsyncGeneratorValidate(gen, empty))로 둔다.
  4. IfAbruptRejectPromise(result, promiseCapability).
  5. stategen.[[AsyncGeneratorState]]로 둔다.
  6. statecompleted이면, 다음을 수행한다.
    1. iteratorResultCreateIteratorResultObject(undefined, true)로 둔다.
    2. Call(promiseCapability.[[Resolve]], undefined, « iteratorResult »)를 수행한다.
    3. promiseCapability.[[Promise]]를 반환한다.
  7. completionNormalCompletion(value)로 둔다.
  8. AsyncGeneratorEnqueue(gen, completion, promiseCapability)를 수행한다.
  9. statesuspended-start 또는 suspended-yield 중 하나이면, 다음을 수행한다.
    1. AsyncGeneratorResume(gen, completion)을 수행한다.
  10. Else,
    1. Assert: stateexecuting 또는 draining-queue 중 하나이다.
  11. promiseCapability.[[Promise]]를 반환한다.

27.9.1.3 %AsyncGeneratorPrototype%.return ( value )

  1. genthis value로 둔다.
  2. promiseCapability를 ! NewPromiseCapability(%Promise%)로 둔다.
  3. resultCompletion(AsyncGeneratorValidate(gen, empty))로 둔다.
  4. IfAbruptRejectPromise(result, promiseCapability).
  5. completionReturnCompletion(value)로 둔다.
  6. AsyncGeneratorEnqueue(gen, completion, promiseCapability)를 수행한다.
  7. stategen.[[AsyncGeneratorState]]로 둔다.
  8. statesuspended-start 또는 completed 중 하나이면, 다음을 수행한다.
    1. gen.[[AsyncGeneratorState]]draining-queue로 설정한다.
    2. AsyncGeneratorAwaitReturn(gen)을 수행한다.
  9. Else if statesuspended-yield이면, 다음을 수행한다.
    1. AsyncGeneratorResume(gen, completion)을 수행한다.
  10. Else,
    1. Assert: stateexecuting 또는 draining-queue 중 하나이다.
  11. promiseCapability.[[Promise]]를 반환한다.

27.9.1.4 %AsyncGeneratorPrototype%.throw ( exception )

  1. genthis value로 둔다.
  2. promiseCapability를 ! NewPromiseCapability(%Promise%)로 둔다.
  3. resultCompletion(AsyncGeneratorValidate(gen, empty))로 둔다.
  4. IfAbruptRejectPromise(result, promiseCapability).
  5. stategen.[[AsyncGeneratorState]]로 둔다.
  6. statesuspended-start이면, 다음을 수행한다.
    1. gen.[[AsyncGeneratorState]]completed로 설정한다.
    2. statecompleted로 설정한다.
  7. statecompleted이면, 다음을 수행한다.
    1. Call(promiseCapability.[[Reject]], undefined, « exception »)를 수행한다.
    2. promiseCapability.[[Promise]]를 반환한다.
  8. completionThrowCompletion(exception)으로 둔다.
  9. AsyncGeneratorEnqueue(gen, completion, promiseCapability)를 수행한다.
  10. statesuspended-yield이면, 다음을 수행한다.
    1. AsyncGeneratorResume(gen, completion)을 수행한다.
  11. Else,
    1. Assert: stateexecuting 또는 draining-queue 중 하나이다.
  12. promiseCapability.[[Promise]]를 반환한다.

27.9.1.5 %AsyncGeneratorPrototype% [ %Symbol.toStringTag% ]

%Symbol.toStringTag% property의 initial value는 String value "AsyncGenerator"입니다.

이 property는 attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }를 가집니다.

27.9.2 AsyncGenerator Instances의 Properties

AsyncGenerator instances는 아래에 described된 internal slots로 initially created됩니다:

Table 95: AsyncGenerator Instances의 Internal Slots
Internal Slot Type Description
[[AsyncGeneratorState]] suspended-start, suspended-yield, executing, draining-queue, 또는 completed async generator의 current execution state.
[[AsyncGeneratorContext]] execution context 이 async generator의 code를 executing할 때 사용되는 execution context.
[[AsyncGeneratorQueue]] AsyncGeneratorRequest RecordsList async generator를 resume하기 위한 requests를 represent하는 Records. state transitions 동안을 제외하고, [[AsyncGeneratorState]]executing 또는 draining-queue 중 하나인 경우에만 non-empty입니다.
[[GeneratorBrand]] String 또는 empty different kinds of 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되어야 하는지에 대한 information을 store하고, corresponding promise를 fulfilling하거나 rejecting하기 위한 capabilities를 contain하는 데 사용되는 Record value입니다.

이는 다음 fields를 가집니다:

Table 96: AsyncGeneratorRequest Record Fields
Field Name Value Meaning
[[Completion]] Completion Record async generator를 resume하기 위해 사용되어야 하는 Completion Record.
[[Capability]] PromiseCapability Record 이 request와 associated된 promise capabilities.

27.9.3.2 AsyncGeneratorStart ( gen, genBody )

The abstract operation AsyncGeneratorStart takes arguments gen (an AsyncGenerator) and genBody (a FunctionBody Parse Node or an Abstract Closure with no parameters) and returns unused. It performs the following steps when called:

  1. Assert: gen.[[AsyncGeneratorState]]suspended-start이다.
  2. genContextrunning execution context로 둔다.
  3. genContext의 Generator component를 gen으로 설정한다.
  4. closure를 parameters가 없고 genBody를 captures하며 호출될 때 다음 steps를 수행하는 new Abstract Closure로 둔다:
    1. acGenContextrunning execution context로 둔다.
    2. acGenacGenContext의 Generator component로 둔다.
    3. genBodyParse Node이면, 다음을 수행한다.
      1. resultCompletion(Evaluation of genBody)로 둔다.
    4. Else,
      1. Assert: genBody는 parameters가 없는 Abstract Closure이다.
      2. resultCompletion(genBody())로 둔다.
    5. Assert: 여기로 return한다면, async generator는 exception을 throw했거나 implicit 또는 explicit return 중 하나를 수행했다.
    6. execution context stack에서 acGenContext를 remove하고, execution context stack의 top에 있는 execution contextrunning execution context로 restore한다.
    7. acGen.[[AsyncGeneratorState]]draining-queue로 설정한다.
    8. resultnormal completion이면, resultNormalCompletion(undefined)로 설정한다.
    9. resultreturn completion이면, resultNormalCompletion(result.[[Value]])로 설정한다.
    10. AsyncGeneratorCompleteStep(acGen, result, true)를 수행한다.
    11. AsyncGeneratorDrainQueue(acGen)를 수행한다.
    12. NormalCompletion(undefined)를 반환한다.
  5. genContext의 code evaluation state를, 그 execution context에 대해 evaluation이 resumed될 때 closure가 no arguments로 called되도록 설정한다.
  6. gen.[[AsyncGeneratorContext]]genContext로 설정한다.
  7. gen.[[AsyncGeneratorQueue]]를 new empty List로 설정한다.
  8. unused를 반환한다.

27.9.3.3 AsyncGeneratorValidate ( gen, genBrand )

The abstract operation AsyncGeneratorValidate takes arguments gen (an ECMAScript language value) and genBrand (a String or empty) and returns either a normal completion containing unused or a throw completion. It performs the following steps when called:

  1. RequireInternalSlot(gen, [[AsyncGeneratorContext]])를 수행한다.
  2. RequireInternalSlot(gen, [[AsyncGeneratorState]])를 수행한다.
  3. RequireInternalSlot(gen, [[AsyncGeneratorQueue]])를 수행한다.
  4. gen.[[GeneratorBrand]]genBrand가 아니면, TypeError exception을 throw한다.
  5. unused를 반환한다.

27.9.3.4 AsyncGeneratorEnqueue ( gen, completion, promiseCapability )

The abstract operation AsyncGeneratorEnqueue takes arguments gen (an AsyncGenerator), completion (a Completion Record), and promiseCapability (a PromiseCapability Record) and returns unused. It performs the following steps when called:

  1. requestAsyncGeneratorRequest { [[Completion]]: completion, [[Capability]]: promiseCapability }로 둔다.
  2. requestgen.[[AsyncGeneratorQueue]]에 append한다.
  3. unused를 반환한다.

27.9.3.5 AsyncGeneratorCompleteStep ( gen, completion, done [ , realm ] )

The abstract operation AsyncGeneratorCompleteStep takes arguments gen (an AsyncGenerator), completion (a Completion Record), and done (a Boolean) and optional argument realm (a Realm Record) and returns unused. It performs the following steps when called:

  1. Assert: gen.[[AsyncGeneratorQueue]]는 empty가 아니다.
  2. nextgen.[[AsyncGeneratorQueue]]의 first element로 둔다.
  3. gen.[[AsyncGeneratorQueue]]에서 first element를 remove한다.
  4. promiseCapabilitynext.[[Capability]]로 둔다.
  5. valuecompletion.[[Value]]로 둔다.
  6. completionthrow completion이면, 다음을 수행한다.
    1. Call(promiseCapability.[[Reject]], undefined, « value »)를 수행한다.
  7. Else,
    1. Assert: completionnormal completion이다.
    2. realm이 present하면, 다음을 수행한다.
      1. oldRealmrunning execution contextRealm으로 둔다.
      2. running execution contextRealmrealm으로 설정한다.
      3. iteratorResultCreateIteratorResultObject(value, done)로 둔다.
      4. running execution contextRealmoldRealm으로 설정한다.
    3. Else,
      1. iteratorResultCreateIteratorResultObject(value, done)로 둔다.
    4. Call(promiseCapability.[[Resolve]], undefined, « iteratorResult »)를 수행한다.
  8. unused를 반환한다.

27.9.3.6 AsyncGeneratorResume ( gen, completion )

The abstract operation AsyncGeneratorResume takes arguments gen (an AsyncGenerator) and completion (a Completion Record) and returns unused. It performs the following steps when called:

  1. Assert: gen.[[AsyncGeneratorState]]suspended-start 또는 suspended-yield 중 하나이다.
  2. genContextgen.[[AsyncGeneratorContext]]로 둔다.
  3. gen.[[AsyncGeneratorState]]executing으로 설정한다.
  4. RunSuspendedContext(genContext, completion)을 수행한다.
  5. unused를 반환한다.

27.9.3.7 AsyncGeneratorUnwrapYieldResumption ( resumptionValue )

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

  1. resumptionValuereturn completion이 아니면, ? resumptionValue를 반환한다.
  2. awaitedCompletion(Await(resumptionValue.[[Value]]))로 둔다.
  3. awaitedthrow completion이면, ? awaited를 반환한다.
  4. Assert: awaitednormal completion이다.
  5. ReturnCompletion(awaited.[[Value]])를 반환한다.

27.9.3.8 AsyncGeneratorYield ( arg )

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

  1. genContext를 실행 중인 실행 컨텍스트라 하자.
  2. Assert: genContext는 제너레이터의 실행 컨텍스트이다.
  3. gengenContext의 Generator 컴포넌트 값이라 하자.
  4. Assert: GetGeneratorKind()는 async이다.
  5. completionNormalCompletion(arg)이라 하자.
  6. Assert: 실행 컨텍스트 스택에는 최소 두 개의 요소가 있다.
  7. previousContext를 실행 컨텍스트 스택의 위에서 두 번째 요소라 하자.
  8. previousRealmpreviousContextRealm이라 하자.
  9. AsyncGeneratorCompleteStep(gen, completion, false, previousRealm)을 수행한다.
  10. queuegen.[[AsyncGeneratorQueue]]라 하자.
  11. queue가 비어 있지 않으면,
    1. NOTE: 실행은 제너레이터를 일시 중단하지 않고 계속된다.
    2. toYieldqueue의 첫 번째 요소라 하자.
    3. resumptionValueCompletion(toYield.[[Completion]])이라 하자.
    4. AsyncGeneratorUnwrapYieldResumption(resumptionValue)를 반환한다.
  12. gen.[[AsyncGeneratorState]]suspended-yield로 설정한다.
  13. resumptionValueCompletion(RunCallerContext(undefined))이라 하자.
  14. AsyncGeneratorUnwrapYieldResumption(resumptionValue)를 반환한다.

27.9.3.9 AsyncGeneratorAwaitReturn ( gen )

The abstract operation AsyncGeneratorAwaitReturn takes argument gen (an AsyncGenerator) and returns unused. It performs the following steps when called:

  1. Assert: gen.[[AsyncGeneratorState]]draining-queue이다.
  2. queuegen.[[AsyncGeneratorQueue]]로 둔다.
  3. Assert: queue는 empty가 아니다.
  4. nextqueue의 first element로 둔다.
  5. completionCompletion(next.[[Completion]])으로 둔다.
  6. Assert: completionreturn completion이다.
  7. promiseCompletionCompletion(PromiseResolve(%Promise%, completion.[[Value]]))로 둔다.
  8. promiseCompletionabrupt completion이면, 다음을 수행한다.
    1. AsyncGeneratorCompleteStep(gen, promiseCompletion, true)를 수행한다.
    2. AsyncGeneratorDrainQueue(gen)를 수행한다.
    3. unused를 반환한다.
  9. Assert: promiseCompletionnormal completion이다.
  10. promisepromiseCompletion.[[Value]]로 둔다.
  11. fulfilledClosure를 parameters (value)를 가지고 gen을 captures하며 호출될 때 다음 steps를 수행하는 new Abstract Closure로 둔다:
    1. Assert: gen.[[AsyncGeneratorState]]draining-queue이다.
    2. resultNormalCompletion(value)로 둔다.
    3. AsyncGeneratorCompleteStep(gen, result, true)를 수행한다.
    4. AsyncGeneratorDrainQueue(gen)를 수행한다.
    5. NormalCompletion(undefined)를 반환한다.
  12. onFulfilledCreateBuiltinFunction(fulfilledClosure, 1, "", « »)로 둔다.
  13. rejectedClosure를 parameters (reason)를 가지고 gen을 captures하며 호출될 때 다음 steps를 수행하는 new Abstract Closure로 둔다:
    1. Assert: gen.[[AsyncGeneratorState]]draining-queue이다.
    2. resultThrowCompletion(reason)으로 둔다.
    3. AsyncGeneratorCompleteStep(gen, result, true)를 수행한다.
    4. AsyncGeneratorDrainQueue(gen)를 수행한다.
    5. NormalCompletion(undefined)를 반환한다.
  14. onRejectedCreateBuiltinFunction(rejectedClosure, 1, "", « »)로 둔다.
  15. PerformPromiseThen(promise, onFulfilled, onRejected)를 수행한다.
  16. unused를 반환한다.

27.9.3.10 AsyncGeneratorDrainQueue ( gen )

The abstract operation AsyncGeneratorDrainQueue takes argument gen (an AsyncGenerator) and returns unused. generator의 AsyncGeneratorQueue를 return completion을 holding하는 AsyncGeneratorRequest를 encounters할 때까지 drains합니다. It performs the following steps when called:

  1. Assert: gen.[[AsyncGeneratorState]]draining-queue이다.
  2. queuegen.[[AsyncGeneratorQueue]]로 둔다.
  3. Repeat, while queue is not empty,
    1. nextqueue의 first element로 둔다.
    2. completionCompletion(next.[[Completion]])으로 둔다.
    3. completionreturn completion이면, 다음을 수행한다.
      1. AsyncGeneratorAwaitReturn(gen)을 수행한다.
      2. unused를 반환한다.
    4. completionnormal completion이면, 다음을 수행한다.
      1. completionNormalCompletion(undefined)로 설정한다.
    5. AsyncGeneratorCompleteStep(gen, completion, true)를 수행한다.
  4. gen.[[AsyncGeneratorState]]completed로 설정한다.
  5. unused를 반환한다.

27.10 AsyncFunction 객체

AsyncFunctions는 보통 AsyncFunctionDeclaration, AsyncFunctionExpression, AsyncMethod, 및 AsyncArrowFunction을 평가하여 생성되는 functions입니다. 또한 %AsyncFunction% intrinsic을 호출하여 생성될 수도 있습니다.

27.10.1 AsyncFunction Constructor

AsyncFunction constructor는:

  • %AsyncFunction%입니다.
  • Function의 subclass입니다.
  • constructor가 아니라 function으로 호출될 때 새 AsyncFunction을 생성하고 초기화합니다. 따라서 function call AsyncFunction(…)은 같은 arguments를 가진 object creation expression new AsyncFunction(…)과 동등합니다.
  • class definition의 extends clause의 value로 사용될 수 있습니다. 지정된 AsyncFunction behaviour를 상속하려는 subclass constructors는 built-in async function behaviour에 필요한 internal slots를 가진 subclass instance를 생성하고 초기화하기 위해 AsyncFunction constructor에 대한 super call을 포함해야 합니다. async function objects를 정의하는 모든 ECMAScript syntactic forms는 AsyncFunction의 direct instances를 생성합니다. AsyncFunction subclasses의 instances를 생성하는 syntactic means는 없습니다.

27.10.1.1 AsyncFunction ( ...paramArgs, bodyArg )

마지막 argument(있다면)는 async function의 body(executable code)를 지정합니다. preceding arguments는 formal parameters를 지정합니다.

이 function은 호출될 때 다음 steps를 수행합니다:

  1. activeFunc를 active function object로 둔다.
  2. bodyArg가 present하지 않으면, bodyArg를 empty String으로 설정한다.
  3. CreateDynamicFunction(activeFunc, NewTarget, async, paramArgs, bodyArg)를 반환한다.
Note
20.2.1.1NOTE를 참조하십시오.

27.10.2 AsyncFunction Constructor의 Properties

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의 Properties

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 Instances

모든 AsyncFunction instance는 ECMAScript function object이며 Table 26에 listed된 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에 given된 Function instances의 "length" property에 대한 specification은 AsyncFunction instances에도 적용됩니다.

27.10.4.2 name

20.2.4.2에 given된 Function instances의 "name" property에 대한 specification은 AsyncFunction instances에도 적용됩니다.

27.10.5 Async Functions Abstract Operations

27.10.5.1 AsyncFunctionStart ( promiseCapability, asyncFuncBody )

The abstract operation AsyncFunctionStart takes arguments promiseCapability (a PromiseCapability Record) and asyncFuncBody (a FunctionBody Parse Node, an ExpressionBody Parse Node, or an Abstract Closure with no parameters) and returns unused. It performs the following steps when called:

  1. runningContextrunning execution context로 둔다.
  2. asyncContextrunningContext의 copy로 둔다.
  3. NOTE: execution state를 copy하는 것은 AsyncBlockStart가 its execution을 resume하기 위해 required된다. currently executing context를 resume하는 것은 ill-defined이다.
  4. AsyncBlockStart(promiseCapability, asyncFuncBody, asyncContext)를 수행한다.
  5. unused를 반환한다.

27.10.5.2 AsyncBlockStart ( promiseCapability, asyncBody, asyncContext )

The abstract operation AsyncBlockStart takes arguments promiseCapability (a PromiseCapability Record), asyncBody (a Parse Node or an Abstract Closure with no parameters), and asyncContext (an execution context) and returns unused. It performs the following steps when called:

  1. closure를 parameters가 없고 promiseCapabilityasyncBody를 captures하며 호출될 때 다음 steps를 수행하는 new Abstract Closure로 둔다:
    1. acAsyncContextrunning execution context로 둔다.
    2. asyncBodyParse Node이면, 다음을 수행한다.
      1. resultCompletion(Evaluation of asyncBody)로 둔다.
    3. Else,
      1. Assert: asyncBody는 parameters가 없는 Abstract Closure이다.
      2. resultCompletion(asyncBody())로 둔다.
    4. Assert: 여기로 return한다면, async function은 exception을 throw했거나 implicit 또는 explicit return을 수행했다; all awaiting is done.
    5. execution context stack에서 acAsyncContext를 remove하고, execution context stack의 top에 있는 execution contextrunning execution context로 restore한다.
    6. resultnormal completion이면, 다음을 수행한다.
      1. Call(promiseCapability.[[Resolve]], undefined, « undefined »)를 수행한다.
    7. Else if resultreturn completion이면, 다음을 수행한다.
      1. Call(promiseCapability.[[Resolve]], undefined, « result.[[Value]] »)를 수행한다.
    8. Else,
      1. Assert: resultthrow completion이다.
      2. Call(promiseCapability.[[Reject]], undefined, « result.[[Value]] »)를 수행한다.
    9. NormalCompletion(unused)를 반환한다.
  2. asyncContext의 code evaluation state를, 그 execution context에 대해 evaluation이 resumed될 때 closure가 no arguments로 called되도록 설정한다.
  3. result를 ! RunSuspendedContext(asyncContext, NormalCompletion(empty))로 둔다.
  4. Assert: resultunused이다.
  5. NOTE: result values의 possible sources는 Await이거나, async function이 anything을 await하지 않는 경우 위의 step 1.i이다.
  6. unused를 반환한다.

27.10.5.3 Await ( arg )

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

  1. asyncContext를 실행 중인 실행 컨텍스트라 하자.
  2. promise를 ? PromiseResolve(%Promise%, arg)라 하자.
  3. fulfilledClosureasyncContext를 캡처하고 호출될 때 다음 단계를 수행하는, 매개변수 (v)를 갖는 새로운 Abstract Closure라 하자.
    1. Completion(RunSuspendedContext(asyncContext, NormalCompletion(v)))을 수행한다.
    2. NOTE: RunSuspendedContext가 반환한 Completion Record는 의도적으로 무시된다.
    3. NormalCompletion(undefined)을 반환한다.
  4. onFulfilledCreateBuiltinFunction(fulfilledClosure, 1, "", « »)라 하자.
  5. rejectedClosureasyncContext를 캡처하고 호출될 때 다음 단계를 수행하는, 매개변수 (reason)를 갖는 새로운 Abstract Closure라 하자.
    1. Completion(RunSuspendedContext(asyncContext, ThrowCompletion(reason)))을 수행한다.
    2. NOTE: RunSuspendedContext가 반환한 Completion Record는 의도적으로 무시된다.
    3. NormalCompletion(undefined)을 반환한다.
  6. onRejectedCreateBuiltinFunction(rejectedClosure, 1, "", « »)라 하자.
  7. PerformPromiseThen(promise, onFulfilled, onRejected)을 수행한다.
  8. RunCallerContext(empty)를 반환한다.

28 Reflection

28.1 Reflect 객체

Reflect object는:

  • %Reflect%입니다.
  • global object"Reflect" property의 initial value입니다.
  • ordinary object입니다.
  • value가 %Object.prototype%[[Prototype]] internal slot을 가집니다.
  • function object가 아닙니다.
  • [[Construct]] internal method를 가지지 않습니다; new operator와 함께 constructor로 사용될 수 없습니다.
  • [[Call]] internal method를 가지지 않습니다; function으로 invoked될 수 없습니다.

28.1.1 Reflect.apply ( target, thisArg, args )

이 function은 호출될 때 다음 steps를 수행합니다:

  1. IsCallable(target)이 false이면, TypeError exception을 throw한다.
  2. argList를 ? CreateListFromArrayLike(args)로 둔다.
  3. PrepareForTailCall()을 수행한다.
  4. Call(target, thisArg, argList)를 반환한다.

28.1.2 Reflect.construct ( target, args [ , newTarget ] )

이 function은 호출될 때 다음 steps를 수행합니다:

  1. IsConstructor(target)가 false이면, TypeError exception을 throw한다.
  2. newTarget이 present하지 않으면, newTargettarget으로 설정한다.
  3. Else if IsConstructor(newTarget)가 false이면, TypeError exception을 throw한다.
  4. argList를 ? CreateListFromArrayLike(args)로 둔다.
  5. Construct(target, argList, newTarget)를 반환한다.

28.1.3 Reflect.defineProperty ( target, key, attrs )

이 function은 호출될 때 다음 steps를 수행합니다:

  1. target이 Object가 아니면, TypeError exception을 throw한다.
  2. propertyKey를 ? ToPropertyKey(key)로 둔다.
  3. propertyDesc를 ? ToPropertyDescriptor(attrs)로 둔다.
  4. target.[[DefineOwnProperty]](propertyKey, propertyDesc)를 반환한다.

28.1.4 Reflect.deleteProperty ( target, key )

이 function은 호출될 때 다음 steps를 수행합니다:

  1. target이 Object가 아니면, TypeError exception을 throw한다.
  2. propertyKey를 ? ToPropertyKey(key)로 둔다.
  3. target.[[Delete]](propertyKey)를 반환한다.

28.1.5 Reflect.get ( target, key [ , receiver ] )

이 function은 호출될 때 다음 steps를 수행합니다:

  1. target이 Object가 아니면, TypeError exception을 throw한다.
  2. propertyKey를 ? ToPropertyKey(key)로 둔다.
  3. receiver가 present하지 않으면, 다음을 수행한다.
    1. receivertarget으로 설정한다.
  4. target.[[Get]](propertyKey, receiver)를 반환한다.

28.1.6 Reflect.getOwnPropertyDescriptor ( target, key )

이 function은 호출될 때 다음 steps를 수행합니다:

  1. target이 Object가 아니면, TypeError exception을 throw한다.
  2. propertyKey를 ? ToPropertyKey(key)로 둔다.
  3. propertyDesc를 ? target.[[GetOwnProperty]](propertyKey)로 둔다.
  4. FromPropertyDescriptor(propertyDesc)를 반환한다.

28.1.7 Reflect.getPrototypeOf ( target )

이 function은 호출될 때 다음 steps를 수행합니다:

  1. target이 Object가 아니면, TypeError exception을 throw한다.
  2. target.[[GetPrototypeOf]]()를 반환한다.

28.1.8 Reflect.has ( target, key )

이 function은 호출될 때 다음 steps를 수행합니다:

  1. target이 Object가 아니면, TypeError exception을 throw한다.
  2. propertyKey를 ? ToPropertyKey(key)로 둔다.
  3. target.[[HasProperty]](propertyKey)를 반환한다.

28.1.9 Reflect.isExtensible ( target )

이 function은 호출될 때 다음 steps를 수행합니다:

  1. target이 Object가 아니면, TypeError exception을 throw한다.
  2. target.[[IsExtensible]]()를 반환한다.

28.1.10 Reflect.ownKeys ( target )

이 function은 호출될 때 다음 steps를 수행합니다:

  1. target이 Object가 아니면, TypeError exception을 throw한다.
  2. keys를 ? target.[[OwnPropertyKeys]]()로 둔다.
  3. CreateArrayFromList(keys)를 반환한다.

28.1.11 Reflect.preventExtensions ( target )

이 function은 호출될 때 다음 steps를 수행합니다:

  1. target이 Object가 아니면, TypeError exception을 throw한다.
  2. target.[[PreventExtensions]]()를 반환한다.

28.1.12 Reflect.set ( target, key, value [ , receiver ] )

이 function은 호출될 때 다음 steps를 수행합니다:

  1. target이 Object가 아니면, TypeError exception을 throw한다.
  2. propertyKey를 ? ToPropertyKey(key)로 둔다.
  3. receiver가 present하지 않으면, 다음을 수행한다.
    1. receivertarget으로 설정한다.
  4. target.[[Set]](propertyKey, value, receiver)를 반환한다.

28.1.13 Reflect.setPrototypeOf ( target, proto )

이 function은 호출될 때 다음 steps를 수행합니다:

  1. target이 Object가 아니면, TypeError exception을 throw한다.
  2. proto가 Object가 아니고 protonull도 아니면, TypeError exception을 throw한다.
  3. target.[[SetPrototypeOf]](proto)를 반환한다.

28.1.14 Reflect [ %Symbol.toStringTag% ]

%Symbol.toStringTag% property의 initial value는 String value "Reflect"입니다.

이 property는 attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }를 가집니다.

28.2 Proxy 객체

28.2.1 Proxy Constructor

Proxy constructor는:

  • %Proxy%입니다.
  • global object"Proxy" property의 initial value입니다.
  • constructor로 호출될 때 새 Proxy object를 생성하고 초기화합니다.
  • function으로 호출되도록 intended되지 않았으며 그런 방식으로 호출되면 exception을 throw합니다.

28.2.1.1 Proxy ( target, handler )

이 function은 호출될 때 다음 steps를 수행합니다:

  1. NewTarget이 undefined이면, TypeError exception을 throw한다.
  2. ProxyCreate(target, handler)를 반환한다.

28.2.2 Proxy Constructor의 Properties

Proxy constructor는:

  • value가 %Function.prototype%[[Prototype]] internal slot을 가집니다.
  • Proxy objects는 initialization이 required되는 [[Prototype]] internal slot을 가지지 않으므로 "prototype" property를 가지지 않습니다.
  • 다음 properties를 가집니다:

28.2.2.1 Proxy.revocable ( target, handler )

이 function은 revocable Proxy object를 생성합니다.

호출될 때 다음 steps를 수행합니다:

  1. proxy를 ? ProxyCreate(target, handler)라고 하자.
  2. revokerClosure를 매개변수가 없고 아무것도 캡처하지 않으며 호출될 때 다음 단계를 수행하는 새로운 Abstract Closure라고 하자.
    1. activeFunc활성 함수 객체라고 하자.
    2. revocableProxyactiveFunc.[[RevocableProxy]]라고 하자.
    3. revocableProxynull이면, NormalCompletion(undefined)을 반환한다.
    4. activeFunc.[[RevocableProxy]]null로 설정한다.
    5. Assert: revocableProxyProxy exotic object이다.
    6. revocableProxy.[[ProxyTarget]]null로 설정한다.
    7. revocableProxy.[[ProxyHandler]]null로 설정한다.
    8. NormalCompletion(undefined)을 반환한다.
  3. revokerCreateBuiltinFunction(revokerClosure, 0, "", « [[RevocableProxy]] »)라고 하자.
  4. revoker.[[RevocableProxy]]proxy로 설정한다.
  5. resultOrdinaryObjectCreate(%Object.prototype%)라고 하자.
  6. CreateDataPropertyOrThrow(result, "proxy", proxy)를 수행한다.
  7. CreateDataPropertyOrThrow(result, "revoke", revoker)를 수행한다.
  8. result를 반환한다.

28.3 Module Namespace 객체

Module Namespace Object는 module의 exported bindings에 runtime property-based access를 제공하는 module namespace exotic object입니다. Module Namespace Objects에 대한 constructor function은 없습니다. 대신 그러한 object는 NameSpaceImport를 포함하는 ImportDeclaration에 의해 imported되는 각 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로 backed된 TypedArray instances에 accessing하여, 그리고 Atomics object의 methods를 통해 발생하는 Shared Data Block events의 possible orderings를 specifies합니다. program에 data races(아래에 defined됨)가 없을 때, 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 둘 다를 정의합니다. 즉, undefined behaviour는 없습니다.

memory model은 SharedArrayBuffer에 대한 abstract operations 또는 evaluation 중 Atomics object의 methods에 의해 introduced되는 Memory events에 대한 relational constraints로 defined됩니다.

Note

이 section은 SharedArrayBuffers에 대한 abstract operations가 introduced하는 Memory events에 관한 axiomatic model을 제공합니다. 이 model은 이 specification의 나머지와 달리 algorithmically expressible하지 않다는 점을 강조할 필요가 있습니다. abstract operations에 의한 events의 nondeterministic introduction은 ECMAScript evaluation의 operational semantics와 memory model의 axiomatic semantics 사이의 interface입니다. 이러한 events의 semantics는 evaluation의 모든 events graphs를 considering하여 defined됩니다. 이것들은 Static Semantics도 Runtime Semantics도 아닙니다. demonstrated algorithmic implementation은 없고, 대신 particular event graph가 allowed 또는 disallowed되는지를 determine하는 constraints의 set이 있습니다.

29.1 Memory Model Fundamentals

Shared memory accesses(reads와 writes)는 아래에 defined된 atomic accesses와 data accesses라는 두 groups로 divided됩니다. Atomic accesses는 sequentially consistent합니다. 즉, agent cluster의 모든 agents가 agreed upon하는 events의 strict total ordering이 있습니다. Non-atomic accesses에는 모든 agents가 agreed upon하는 strict total ordering이 없습니다. 즉, unordered입니다.

Note 1

release-acquire와 같이 sequentially consistent보다 약하고 unordered보다 강한 orderings는 supported되지 않습니다.

Shared Data Block eventReadSharedMemory, WriteSharedMemory, 또는 ReadModifyWriteSharedMemory Record 중 하나입니다. read event는 ReadSharedMemory 또는 ReadModifyWriteSharedMemory입니다. write event는 WriteSharedMemory 또는 ReadModifyWriteSharedMemory입니다.

Table 97: ReadSharedMemory Event Fields
Field Name Value Meaning
[[Order]] seq-cst 또는 unordered memory model이 event에 대해 guarantee하는 weakest ordering.
[[NoTear]] Boolean 이 event가 이 event와 equal memory range를 가진 multiple write events로부터 read하는 것이 allowed되는지 여부.
[[Block]] Shared Data Block event가 operate하는 block.
[[ByteIndex]] non-negative integer [[Block]]에서 read의 byte address.
[[ElementSize]] non-negative integer read의 size.
Table 98: WriteSharedMemory Event Fields
Field Name Value Meaning
[[Order]] seq-cst, unordered, 또는 init memory model이 event에 대해 guarantee하는 weakest ordering.
[[NoTear]] Boolean 이 event가 이 event와 equal memory range를 가진 multiple read events에 의해 read되는 것이 allowed되는지 여부.
[[Block]] Shared Data Block event가 operate하는 block.
[[ByteIndex]] non-negative integer [[Block]]에서 write의 byte address.
[[ElementSize]] non-negative integer write의 size.
[[Payload]] byte valuesList 다른 events가 read할 byte valuesList.
Table 99: ReadModifyWriteSharedMemory Event Fields
Field Name Value Meaning
[[Order]] seq-cst Read-modify-write events는 항상 sequentially consistent합니다.
[[NoTear]] true Read-modify-write events는 tear될 수 없습니다.
[[Block]] Shared Data Block event가 operate하는 block.
[[ByteIndex]] non-negative integer [[Block]]에서 read-modify-write의 byte address.
[[ElementSize]] non-negative integer read-modify-write의 size.
[[Payload]] byte valuesList [[ModifyOp]]에 passed될 byte valuesList.
[[ModifyOp]] read-modify-write modification function read byte valuesList[[Payload]]로부터 modified byte valuesList를 반환하는 Abstract Closure.

Shared Data Block events는 abstract operations 또는 Atomics object의 methods에 의해 candidate execution Agent Events Records에 introduced됩니다. 일부 operations는 또한 fields가 없고 other events의 permitted orderings를 직접 constrain하기 위해서만 존재하는 Synchronize events를 introduce합니다. 그리고 마지막으로 host-specific events가 있습니다. Memory event는 Shared Data Block event, Synchronize event, 또는 그러한 host-specific event 중 하나입니다.

Shared Data Block event ememory rangee.[[ByteIndex]](inclusive)에서 e.[[ByteIndex]] + e.[[ElementSize]](exclusive)까지 interval의 all integers의 Set으로 둔다. 두 events가 같은 [[Block]], [[ByteIndex]], 및 [[ElementSize]]를 가질 때 두 events의 memory ranges는 equal입니다. 두 events가 같은 [[Block]]을 가지고, ranges가 equal이 아니며, 그 intersection이 non-empty일 때 두 events의 memory ranges는 overlapping합니다. 두 events가 같은 [[Block]]을 가지지 않거나 그 ranges가 equal도 overlapping도 아닐 때 두 events의 memory ranges는 disjoint입니다.

Note 2

accounted for되어야 하는 host-specific synchronizing events의 examples는 다음과 같습니다: 한 agent에서 다른 agent로 SharedArrayBuffer를 sending하는 것(예: browser에서 postMessage), agents를 starting 및 stopping하는 것, 그리고 shared memory 이외의 channels를 통해 agent cluster 내에서 communicating하는 것. particular execution execution에 대해, 이러한 events는 hosthost-synchronizes-with strict partial order를 통해 제공합니다. 또한 hostsis-agent-order-before Relation에 participate하기 위해 host-specific synchronizing events를 execution.[[EventList]]에 add할 수 있습니다.

Events는 아래에 defined된 relations에 의해 candidate executions 내에서 ordered됩니다.

29.2 Agent Events Records

Agent Events Record는 다음 fields를 가진 Record입니다.

Table 100: Agent Events Record Fields
Field Name Value Meaning
[[AgentSignifier]] agent signifier evaluation이 이 ordering을 result한 agent.
[[EventList]] Memory eventsList Events는 evaluation 중 list에 appended됩니다.
[[AgentSynchronizesWith]] Synchronize events의 pairs의 List operational semantics에 의해 introduced된 Synchronize relationships.

29.3 Chosen Value Records

Chosen Value Record는 다음 fields를 가진 Record입니다.

Table 101: Chosen Value Record Fields
Field Name Value Meaning
[[Event]] Shared Data Block event 이 chosen value에 대해 introduced된 ReadSharedMemory 또는 ReadModifyWriteSharedMemory event.
[[ChosenValue]] byte valuesList evaluation 중 nondeterministically chosen된 bytes.

29.4 Candidate Executions

agent cluster의 evaluation의 candidate execution은 다음 fields를 가진 Record입니다.

Table 102: Candidate Execution Record Fields
Field Name Value Meaning
[[EventsRecords]] Agent Events RecordsList agent를 evaluation 중 appended된 Memory eventsLists에 maps합니다.
[[ChosenValues]] Chosen Value RecordsList ReadSharedMemory 또는 ReadModifyWriteSharedMemory events를 evaluation 중 chosen된 byte valuesList에 maps합니다.

empty candidate execution은 fields가 empty Lists인 candidate execution Record입니다.

29.5 Memory Model의 Abstract Operations

29.5.1 EventSet ( execution )

The abstract operation EventSet takes argument execution (a candidate execution) and returns a Set of Memory events. It performs the following steps when called:

  1. events를 empty Set으로 둔다.
  2. execution.[[EventsRecords]]의 각 Agent Events Record eventsRecord에 대해, 다음을 수행한다.
    1. eventsRecord.[[EventList]]의 각 Memory event event에 대해, 다음을 수행한다.
      1. eventevents에 Add한다.
  3. events를 반환한다.

29.5.2 SharedDataBlockEventSet ( execution )

The abstract operation SharedDataBlockEventSet takes argument execution (a candidate execution) and returns a Set of Shared Data Block events. It performs the following steps when called:

  1. events를 empty Set으로 둔다.
  2. EventSet(execution)의 각 Memory event event에 대해, 다음을 수행한다.
    1. eventShared Data Block event이면, eventevents에 add한다.
  3. events를 반환한다.

29.5.3 HostEventSet ( execution )

The abstract operation HostEventSet takes argument execution (a candidate execution) and returns a Set of Memory events. It performs the following steps when called:

  1. EventSet(execution)의 elements 중 SharedDataBlockEventSet(execution)에 있지 않은 모든 elements를 포함하는 new Set을 반환한다.

29.5.4 ComposeWriteEventBytes ( execution, byteIndex, writes )

The abstract operation ComposeWriteEventBytes takes arguments execution (a candidate execution), byteIndex (a non-negative integer), and writes (a List of either WriteSharedMemory or ReadModifyWriteSharedMemory events) and returns a List of byte values. It performs the following steps when called:

  1. byteLocationbyteIndex로 둔다.
  2. bytesRead를 new empty List로 둔다.
  3. writes의 각 element writeEvent에 대해, 다음을 수행한다.
    1. Assert: writeEvent는 its memory range 안에 byteLocation을 가진다.
    2. payloadIndexbyteLocation - writeEvent.[[ByteIndex]]로 둔다.
    3. writeEventWriteSharedMemory event이면, 다음을 수행한다.
      1. bytewriteEvent.[[Payload]][payloadIndex]로 둔다.
    4. Else,
      1. Assert: writeEventReadModifyWriteSharedMemory event이다.
      2. bytesValueOfReadEvent(execution, writeEvent)로 둔다.
      3. bytesModifiedwriteEvent.[[ModifyOp]](bytes, writeEvent.[[Payload]])로 둔다.
      4. bytebytesModified[payloadIndex]로 둔다.
    5. bytebytesRead에 Append한다.
    6. byteLocationbyteLocation + 1로 설정한다.
  4. bytesRead를 반환한다.
Note 1

read-modify-write modification [[ModifyOp]]ReadModifyWriteSharedMemory events를 introduce하는 Atomics object의 function properties에 의해 given됩니다.

Note 2

이 abstract operation은 write eventsListbyte valuesList로 composes합니다. 이는 ReadSharedMemoryReadModifyWriteSharedMemory events의 event semantics에서 사용됩니다.

29.5.5 ValueOfReadEvent ( execution, readEvent )

The abstract operation ValueOfReadEvent takes arguments execution (a candidate execution) and readEvent (a ReadSharedMemory or ReadModifyWriteSharedMemory event) and returns a List of byte values. It performs the following steps when called:

  1. writesexecution 안의 reads-bytes-from(readEvent)으로 둔다.
  2. Assert: writesreadEvent.[[ElementSize]]와 같은 length를 가진 WriteSharedMemory 또는 ReadModifyWriteSharedMemory events의 List이다.
  3. ComposeWriteEventBytes(execution, readEvent.[[ByteIndex]], writes)를 반환한다.

29.6 Candidate Executions의 Relations

다음 relations와 mathematical functions는 particular candidate execution에 대해 parameterized되고 its Memory events를 order합니다.

29.6.1 is-agent-order-before

candidate execution execution에 대해, 그 is-agent-order-before Relation은 다음을 satisfies하는 Memory events에 대한 least Relation입니다.

  • 이벤트 eventAeventB에 대해, execution.[[EventsRecords]] 안에 어떤 Agent Events Record eventsRecord가 있어서 eventsRecord.[[EventList]]eventAeventB를 모두 포함하고, eventAeventsRecord.[[EventList]]List 순서에서 eventB보다 앞에 있으면, eventAexecution에서 eventB보다 is-agent-order-before이다.
Note

agent는 evaluation 중 per-agent strict total order로 events를 introduce합니다. 이것은 그러한 strict total orders의 union입니다.

29.6.2 reads-bytes-from

candidate execution execution에 대해, 그 reads-bytes-from function은 SharedDataBlockEventSet(execution)의 Memory eventsSharedDataBlockEventSet(execution) 안의 events의 Lists에 mapping하는 mathematical function이며 다음 conditions를 satisfies합니다.

candidate execution은 항상 reads-bytes-from function을 admits합니다.

29.6.3 reads-from

candidate execution execution에 대해, 그 reads-from Relation은 다음을 satisfies하는 Memory events에 대한 least Relation입니다.

  • events readEventwriteEvent에 대해, SharedDataBlockEventSet(execution)이 readEventwriteEvent 둘 다를 contain하고 execution 안의 reads-bytes-from(readEvent)이 writeEvent를 contain하면, readEventexecution에서 writeEvent로부터 reads-from합니다.

29.6.4 host-synchronizes-with

candidate execution execution에 대해, 그 host-synchronizes-with Relation은 적어도 다음을 satisfies하는 host-specific Memory events에 대한 host-provided strict partial order입니다.

  • eventAexecution에서 eventB와 host-synchronizes-with이면, HostEventSet(execution)은 eventAeventB를 contain합니다.
  • execution에서 host-synchronizes-with와 is-agent-order-before의 union에는 cycle이 없습니다.
Note 1

candidate execution execution 안의 두 host-specific events eventAeventB에 대해, eventAexecution에서 eventB와 host-synchronizes-with이면 eventAexecution에서 eventB보다 happens-before임을 implies합니다.

Note 2

Relationhost가 HTML workers 사이의 postMessage와 같은 additional synchronization mechanisms를 제공할 수 있게 합니다.

29.6.5 synchronizes-with

candidate execution execution에 대해, 그 synchronizes-with Relation은 다음을 satisfies하는 Memory events에 대한 least Relation입니다.

  • events readEventwriteEvent에 대해, readEventexecution에서 writeEvent로부터 reads-from하고, readEvent.[[Order]]seq-cst이고, writeEvent.[[Order]]seq-cst이고, readEventwriteEvent가 equal memory ranges를 가지면, writeEventexecution에서 readEvent와 synchronizes-with합니다.
  • execution.[[EventsRecords]]의 각 element eventsRecord에 대해, 다음은 true입니다.
    • events eventAeventB에 대해, eventsRecord.[[AgentSynchronizesWith]]가 (eventA, eventB)를 contain하면, eventAexecution에서 eventB와 synchronizes-with합니다.
  • 이벤트 eventAeventB에 대해, execution에서 eventAeventBhost-synchronizes-with이면, execution에서 eventAeventB와 synchronizes-with이다.
Note 1

memory model literature의 convention으로 인해, candidate execution execution에서 read eventswrite events와 synchronizes-with하는 대신 write eventsread events와 synchronizes-with합니다.

Note 2

candidate execution execution에서 init events는 이 Relation에 participate하지 않고 대신 happens-before에 의해 directly 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 readEventwriteEvent에 대해, writeEventreadEvent와 synchronizes-with하면, readEventwriteEvent 이외의 other writes로부터 reads-from할 수 있습니다.

29.6.6 happens-before

candidate execution execution에 대해, 그 happens-before Relation은 다음을 satisfies하는 Memory events에 대한 least Relation입니다.

  • events eventAeventB에 대해, 다음 conditions 중 any가 true이면 eventAexecution에서 eventB보다 happens-before입니다.

    • eventAexecution에서 eventB보다 is-agent-order-before이다.
    • eventAexecution에서 eventBsynchronizes-with한다.
    • SharedDataBlockEventSet(execution)이 eventAeventB 둘 다를 contain하고, eventA.[[Order]]init이며, eventAeventB가 overlapping memory ranges를 가진다.
    • eventAexecution에서 eventC보다 happens-before이고 eventCeventB보다 happens-before인 event eventC가 있다.
Note

happens-before는 agent-order의 superset이므로, candidate execution은 ECMAScript의 single-thread evaluation semantics와 consistent합니다.

29.7 Valid Executions의 Properties

29.7.1 Valid Chosen Reads

candidate execution execution은 다음 algorithm이 true를 반환하면 valid chosen reads를 가집니다.

  1. SharedDataBlockEventSet(execution)의 각 ReadSharedMemory 또는 ReadModifyWriteSharedMemory event readEvent에 대해, 다음을 수행한다.
    1. chosenValueRecord[[Event]] field가 readEventexecution.[[ChosenValues]]의 element로 둔다.
    2. chosenValuechosenValueRecord.[[ChosenValue]]로 둔다.
    3. readValueValueOfReadEvent(execution, readEvent)로 둔다.
    4. chosenLengthchosenValue 안의 elements의 number로 둔다.
    5. readLengthreadValue 안의 elements의 number로 둔다.
    6. chosenLengthreadLength이면, 다음을 수행한다.
      1. false를 반환한다.
    7. 0(inclusive)에서 chosenLength(exclusive)까지의 interval 안의 some integer i에 대해 chosenValue[i] ≠ readValue[i]이면, 다음을 수행한다.
      1. false를 반환한다.
  2. true를 반환한다.

29.7.2 Coherent Reads

candidate execution execution은 다음 algorithm이 true를 반환하면 coherent reads를 가집니다.

  1. SharedDataBlockEventSet(execution)의 각 ReadSharedMemory 또는 ReadModifyWriteSharedMemory event readEvent에 대해, 다음을 수행한다.
    1. writesexecution 안의 reads-bytes-from(readEvent)으로 둔다.
    2. byteLocationreadEvent.[[ByteIndex]]로 둔다.
    3. writes의 각 element writeEvent에 대해, 다음을 수행한다.
      1. readEventexecution에서 writeEvent보다 happens-before이면, 다음을 수행한다.
        1. false를 반환한다.
      2. byteLocation을 its memory range 안에 가지는 WriteSharedMemory 또는 ReadModifyWriteSharedMemory event value가 존재하고, writeEventexecution에서 value보다 happens-before이며 valueexecution에서 readEvent보다 happens-before이면, 다음을 수행한다.
        1. false를 반환한다.
      3. byteLocationbyteLocation + 1로 설정한다.
  2. true를 반환한다.

29.7.3 Tear Free Reads

candidate execution execution은 다음 algorithm이 true를 반환하면 tear free reads를 가집니다.

  1. SharedDataBlockEventSet(execution)의 각 ReadSharedMemory 또는 ReadModifyWriteSharedMemory event readEvent에 대해, 다음을 수행한다.
    1. readEvent.[[NoTear]]true이면, 다음을 수행한다.
      1. Assert: readEvent.[[ByteIndex]]readEvent.[[ElementSize]]로 나눈 remainder는 0이다.
      2. readEventexecution에서 writeEvent로부터 reads-from하고 writeEvent.[[NoTear]]true인 각 Memory event writeEvent에 대해, 다음을 수행한다.
        1. readEventwriteEvent가 equal memory ranges를 가지고, valuewriteEvent가 equal memory ranges를 가지고, value.[[NoTear]]true이고, writeEventvalue가 같은 Shared Data Block event가 아니며, readEventexecution에서 value로부터 reads-from하는 Memory event value가 존재하면, 다음을 수행한다.
          1. false를 반환한다.
  2. true를 반환한다.
Note

Shared Data Block event[[NoTear]] field는 integer TypedArray에 accessing하여 introduced된 경우 true이고, floating point TypedArray 또는 DataView에 accessing하여 introduced된 경우 false입니다.

직관적으로, 이 requirement는 memory rangeinteger TypedArray를 통해 aligned fashion으로 accessed될 때, 그 range에 대한 single write event가 equal ranges를 가진 other write eventsdata race에서 “win”해야 한다는 뜻입니다. 더 정확히는, 이 requirement는 aligned read event가 equal ranges를 모두 가진 multiple different write events의 bytes로 composed된 value를 read할 수 없다는 뜻입니다. 그러나 aligned read event가 overlapping ranges를 가진 multiple write events로부터 read하는 것은 가능합니다.

29.7.4 Sequentially Consistent Atomics

candidate execution execution에 대해, is-memory-order-beforeEventSet(execution) 안의 모든 Memory eventsstrict total order이며 다음을 satisfies합니다.

candidate execution이 is-memory-order-before Relation을 admits하면 sequentially consistent atomics를 가집니다.

Note 3

is-memory-order-before가 EventSet(execution) 안의 모든 events를 포함하지만, execution에서 happens-before 또는 synchronizes-with에 의해 constrained되지 않는 것들은 order 안의 anywhere에서 occur하는 것이 allowed됩니다.

29.7.5 Valid Executions

candidate execution execution은 다음 모두가 true이면 valid execution(또는 simply execution)입니다.

모든 programs는 적어도 하나의 valid execution을 가집니다.

29.8 Races

execution executionSharedDataBlockEventSet(execution)에 contained된 events eventAeventB에 대해, 다음 algorithm이 true를 반환하면 eventAeventBrace 안에 있습니다.

  1. eventAeventB가 같은 Shared Data Block event가 아니면, 다음을 수행한다.
    1. eventAexecution에서 eventB보다 happens-before이고 eventBexecution에서 eventA보다 happens-before라는 것이 둘 다 true인 경우가 아니면, 다음을 수행한다.
      1. eventAWriteSharedMemory 또는 ReadModifyWriteSharedMemory event 중 하나이고, eventBWriteSharedMemory 또는 ReadModifyWriteSharedMemory event 중 하나이며, eventAeventB가 disjoint memory ranges를 가지지 않으면, 다음을 수행한다.
        1. true를 반환한다.
      2. eventAexecution에서 eventB로부터 reads-from하거나 eventBexecution에서 eventA로부터 reads-from하면, 다음을 수행한다.
        1. true를 반환한다.
  2. false를 반환한다.

29.9 Data Races

execution executionSharedDataBlockEventSet(execution)에 contained된 events eventAeventB에 대해, 다음 algorithm이 true를 반환하면 eventAeventBdata race 안에 있습니다.

  1. eventAeventBexecution에서 race 안에 있으면, 다음을 수행한다.
    1. eventA.[[Order]]seq-cst가 아니거나 eventB.[[Order]]seq-cst가 아니면, 다음을 수행한다.
      1. true를 반환한다.
    2. eventAeventB가 overlapping memory ranges를 가지면, 다음을 수행한다.
      1. true를 반환한다.
  2. false를 반환한다.

29.10 Data Race Freedom

execution executionSharedDataBlockEventSet(execution) 안에 data race 안에 있는 두 events가 없으면 data race free입니다.

program은 all its executions가 data race free이면 data race free입니다.

memory model은 data race free programs에 대해 all events의 sequential consistency를 guarantee합니다.

29.11 Shared Memory Guidelines

Note 1

다음은 shared memory로 작업하는 ECMAScript programmers를 위한 guidelines입니다.

programs는 data race free로 유지하는 것을 recommend합니다. 즉, 같은 memory location에 concurrent non-atomic operations가 존재할 수 없도록 만듭니다. Data race free programs는 각 agent의 evaluation semantics 안의 각 step이 서로 interleaved되는 interleaving semantics를 가집니다. data race free programs에 대해서는 memory model의 details를 이해할 필요가 없습니다. details는 ECMAScript를 더 잘 작성하는 데 도움이 되는 intuition을 build할 가능성이 낮습니다.

더 일반적으로, program이 data race free가 아니더라도 atomic operations가 any data races에 involved되지 않고 race하는 operations가 모두 같은 access size를 가지는 한 predictable behaviour를 가질 수 있습니다. atomics가 races에 involved되지 않도록 arrange하는 simplest way는 atomic 및 non-atomic operations에 different memory cells가 사용되도록 ensure하고, different sizes의 atomic accesses가 동시에 같은 cells에 access하는 데 사용되지 않도록 하는 것입니다. Effectively, program은 shared memory를 가능한 한 strongly typed로 treat해야 합니다. 여전히 race하는 non-atomic accesses의 ordering과 timing에 depend할 수는 없지만, memory가 strongly typed로 treated되면 racing accesses는 “tear”되지 않습니다(bits of their values will not be mixed).

Note 2

다음은 shared memory를 사용하는 programs에 대한 compiler transformations를 작성하는 ECMAScript implementers를 위한 guidelines입니다.

multi-agent setting에서 각 agent의 performance가 single-agent setting에서와 as good as it would be 되도록, single-agent setting에서 valid한 대부분의 program transformations를 multi-agent setting에서도 allow하는 것이 desirable합니다. 이러한 transformations는 often judge하기 어렵습니다. 우리는 normative로 taken되도록 intended된(즉 memory model에 의해 implied되거나 memory model이 implies하는 것보다 stronger인) program transformations에 관한 몇 가지 rules를 outline하지만, 이는 exhaustive하지 않을 가능성이 큽니다. 이러한 rules는 is-agent-order-before Relation을 구성하는 Memory events의 introductions에 precede하는 program transformations에 apply되도록 intended됩니다.

agent-order slice를 single agent에 pertaining하는 is-agent-order-before Relation의 subset으로 둔다.

read eventpossible read values를 모든 valid executions 전반에서 그 event에 대한 ValueOfReadEvent의 모든 values의 set으로 둔다.

shared memory가 없는 경우 valid한 agent-order slice의 any transformation은 shared memory가 있는 경우에도 valid하며, 다음 exceptions가 있습니다.

  • Atomics are carved in stone: Program transformations는 [[Order]]seq-cst인 any Shared Data Block eventsis-agent-order-before Relation에서 removed되게 하거나, 서로에 대해 reordered되게 하거나, [[Order]]unordered인 events에 대해 agent-order slice 안에서 reordered되게 해서는 안 됩니다.

    (In practice, reorderings에 대한 prohibition은 compiler가 inter-agent program analysis가 없는 경우 어차피 보통 assume해야 하는 것처럼, every seq-cst operation이 synchronization이고 final is-memory-order-before Relation에 included된다고 assume하도록 force합니다. 또한 memory-order에 대한 callee의 effects가 unknown인 every call이 seq-cst operations를 contain할 수 있다고 compiler가 assume하도록 force합니다.)

  • Reads must be stable: Any given shared memory read는 execution 안에서 single value만 observe해야 합니다.

    (예를 들어, program에서 semantically single read인 것이 multiple times executed되면, program은 subsequently read된 values 중 하나만 observe하도록 allowed됩니다. rematerialization으로 known된 transformation은 이 rule을 violate할 수 있습니다.)

  • Writes must be stable: shared memory에 대한 모든 observable writes는 execution 안의 program semantics로부터 follow해야 합니다.

    (예를 들어, transformation은 larger location에 대한 read-modify-write operations를 사용해 smaller datum을 write하거나, program이 write할 수 없었던 value를 memory에 write하거나, read한 location이 read 후 다른 agent에 의해 overwritten될 수 있었다면 그 just-read value를 그 location에 다시 write하는 것과 같은 certain observable writes를 introduce해서는 안 됩니다.)

  • Possible read values must be non-empty: Program transformations는 shared memory read의 possible read values가 empty가 되도록 할 수 없습니다.

    (Counterintuitively, 이 rule은 effect적으로 writes에 대한 transformations를 restrict합니다. 왜냐하면 writes는 read events에 의해 read되는 한에서 memory model 안에서 force를 가지기 때문입니다. 예를 들어, writes는 두 seq-cst operations 사이에서 moved 및 coalesced되고 sometimes reordered될 수 있지만, transformation은 location을 updates하는 모든 write를 remove해서는 안 됩니다; some write는 preserved되어야 합니다.)

valid로 remain하는 transformations의 examples는 다음과 같습니다: 같은 location으로부터 multiple non-atomic reads를 merging하는 것, non-atomic reads를 reordering하는 것, speculative non-atomic reads를 introducing하는 것, 같은 location에 대한 multiple non-atomic writes를 merging하는 것, different locations에 대한 non-atomic writes를 reordering하는 것, 그리고 termination에 영향을 미치더라도 non-atomic reads를 loops 밖으로 hoisting하는 것. 일반적으로 aliased TypedArrays는 locations가 different임을 prove하기 어렵게 만든다는 점에 유의하십시오.

Note 3

다음은 shared memory accesses에 대한 machine code를 generating하는 ECMAScript implementers를 위한 guidelines입니다.

ARM 또는 Power의 memory models보다 no weaker인 memory models를 가진 architectures에서는, non-atomic stores와 loads가 target architecture의 bare stores와 loads로 compiled될 수 있습니다. Atomic stores와 loads는 sequential consistency를 guarantee하는 instructions로 compiled down될 수 있습니다. such instructions가 없으면, bare store 또는 load의 양쪽에 barriers를 placing하는 것과 같은 memory barriers가 employed되어야 합니다. 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로 compiled될 수 있습니다.

Specifically, memory model은 다음과 같은 code generation을 allow하도록 intended됩니다.

  • program 안의 every atomic operation은 necessary하다고 assumed됩니다.
  • Atomic operations는 서로 또는 non-atomic operations와 never 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됩니다. (우리는 already every 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합니다. 그러나 그것이 all we need입니다: memory model은 race에 involved된 atomic operations를 effect적으로 non-atomic status로 demotes합니다. 반면 naive mapping은 꽤 strong합니다: 이는 atomic operations가 sequentially consistent fences로 사용되는 것을 allow하지만, memory model은 실제로 이를 guarantee하지 않습니다.

those basic patterns에 대한 local improvements도 memory model의 constraints에 subject하여 allowed됩니다. 예를 들어:

  • redundant fences를 remove하는 obvious platform-dependent improvements가 있습니다. 예를 들어, x86에서는 lock-free atomic loads와 stores 주변의 fences를 store 뒤에 following하는 fence를 제외하고 항상 omitted할 수 있으며, lock-free read-modify-write instructions에는 fence가 필요하지 않습니다. 이것들은 모두 LOCK-prefixed instructions를 사용하기 때문입니다. many platforms에는 several strengths의 fences가 있고, certain contexts에서는 sequential consistency를 destroying하지 않고 weaker fences가 사용될 수 있습니다.
  • 대부분의 modern platforms는 ECMAScript atomics가 required하는 모든 data sizes에 대해 lock-free atomics를 support합니다. Non-lock-free atomics가 needed되면, atomic operation의 body를 surrounding하는 fences는 보통 lock 및 unlock steps에 folded될 수 있습니다. non-lock-free atomics에 대한 simplest solution은 SharedArrayBuffer마다 single lock word를 가지는 것입니다.
  • 또한 더 complicated platform-dependent local improvements가 있으며, 이는 some code analysis를 require합니다. 예를 들어, two back-to-back fences는 often single fence와 같은 effect를 가지므로, code가 two atomic operations in sequence에 대해 generated되면 single fence만 them 사이를 separate하면 됩니다. x86에서는 atomic stores를 separating하는 single fence조차 omitted될 수 있습니다. store 뒤에 following하는 fence는 store를 subsequent load와 separate하는 데만 needed되기 때문입니다.

Annex A (informative) 문법 요약

A.1 어휘 문법

SourceCharacter :: any Unicode code point InputElementDiv :: WhiteSpace LineTerminator Comment CommonToken DivPunctuator RightBracePunctuator InputElementRegExp :: WhiteSpace LineTerminator Comment CommonToken RightBracePunctuator RegularExpressionLiteral InputElementRegExpOrTemplateTail :: WhiteSpace LineTerminator Comment CommonToken RegularExpressionLiteral TemplateSubstitutionTail InputElementTemplateTail :: WhiteSpace LineTerminator Comment CommonToken DivPunctuator TemplateSubstitutionTail InputElementHashbangOrRegExp :: WhiteSpace LineTerminator Comment CommonToken HashbangComment RegularExpressionLiteral WhiteSpace :: <TAB> <VT> <FF> <ZWNBSP> <USP> LineTerminator :: <LF> <CR> <LS> <PS> LineTerminatorSequence :: <LF> <CR> [lookahead ≠ <LF>] <LS> <PS> <CR> <LF> Comment :: MultiLineComment SingleLineComment MultiLineComment :: /* MultiLineCommentCharsopt */ MultiLineCommentChars :: MultiLineNotAsteriskChar MultiLineCommentCharsopt * PostAsteriskCommentCharsopt PostAsteriskCommentChars :: MultiLineNotForwardSlashOrAsteriskChar MultiLineCommentCharsopt * PostAsteriskCommentCharsopt MultiLineNotAsteriskChar :: SourceCharacter but not * MultiLineNotForwardSlashOrAsteriskChar :: SourceCharacter but not one of / or * SingleLineComment :: // SingleLineCommentCharsopt SingleLineCommentChars :: SingleLineCommentChar SingleLineCommentCharsopt SingleLineCommentChar :: SourceCharacter but not LineTerminator HashbangComment :: #! SingleLineCommentCharsopt CommonToken :: IdentifierName PrivateIdentifier Punctuator NumericLiteral StringLiteral Template PrivateIdentifier :: # IdentifierName IdentifierName :: IdentifierStart IdentifierName IdentifierPart IdentifierStart :: IdentifierStartChar \ UnicodeEscapeSequence IdentifierPart :: IdentifierPartChar \ UnicodeEscapeSequence IdentifierStartChar :: UnicodeIDStart $ _ IdentifierPartChar :: UnicodeIDContinue $ AsciiLetter :: one of a b c d e f g h i j k l m n o p q r s t u v w x y z A B C D E F G H I J K L M N O P Q R S T U V W X Y Z UnicodeIDStart :: any Unicode code point with the Unicode property “ID_Start” UnicodeIDContinue :: any Unicode code point with the Unicode property “ID_Continue” ReservedWord :: one of await break case catch class const continue debugger default delete do else enum export extends false finally for function if import in instanceof new null return super switch this throw true try typeof var void while with yield Punctuator :: OptionalChainingPunctuator OtherPunctuator OptionalChainingPunctuator :: ?. [lookahead ∉ DecimalDigit] OtherPunctuator :: one of { ( ) [ ] . ... ; , < > <= >= == != === !== + - * % ** ++ -- << >> >>> & | ^ ! ~ && || ?? ? : = += -= *= %= **= <<= >>= >>>= &= |= ^= &&= ||= ??= => DivPunctuator :: / /= RightBracePunctuator :: } NullLiteral :: null BooleanLiteral :: true false NumericLiteralSeparator :: _ NumericLiteral :: DecimalLiteral DecimalBigIntegerLiteral NonDecimalIntegerLiteral[+Sep] NonDecimalIntegerLiteral[+Sep] BigIntLiteralSuffix LegacyOctalIntegerLiteral DecimalBigIntegerLiteral :: 0 BigIntLiteralSuffix NonZeroDigit DecimalDigits[+Sep]opt BigIntLiteralSuffix NonZeroDigit NumericLiteralSeparator DecimalDigits[+Sep] BigIntLiteralSuffix NonDecimalIntegerLiteral[Sep] :: BinaryIntegerLiteral[?Sep] OctalIntegerLiteral[?Sep] HexIntegerLiteral[?Sep] BigIntLiteralSuffix :: n DecimalLiteral :: DecimalIntegerLiteral . DecimalDigits[+Sep]opt ExponentPart[+Sep]opt . DecimalDigits[+Sep] ExponentPart[+Sep]opt DecimalIntegerLiteral ExponentPart[+Sep]opt DecimalIntegerLiteral :: 0 NonZeroDigit NonZeroDigit NumericLiteralSeparatoropt DecimalDigits[+Sep] NonOctalDecimalIntegerLiteral DecimalDigits[Sep] :: DecimalDigit DecimalDigits[?Sep] DecimalDigit [+Sep] DecimalDigits[+Sep] NumericLiteralSeparator DecimalDigit DecimalDigit :: one of 0 1 2 3 4 5 6 7 8 9 NonZeroDigit :: one of 1 2 3 4 5 6 7 8 9 ExponentPart[Sep] :: ExponentIndicator SignedInteger[?Sep] ExponentIndicator :: one of e E SignedInteger[Sep] :: DecimalDigits[?Sep] + DecimalDigits[?Sep] - DecimalDigits[?Sep] BinaryIntegerLiteral[Sep] :: 0b BinaryDigits[?Sep] 0B BinaryDigits[?Sep] BinaryDigits[Sep] :: BinaryDigit BinaryDigits[?Sep] BinaryDigit [+Sep] BinaryDigits[+Sep] NumericLiteralSeparator BinaryDigit BinaryDigit :: one of 0 1 OctalIntegerLiteral[Sep] :: 0o OctalDigits[?Sep] 0O OctalDigits[?Sep] OctalDigits[Sep] :: OctalDigit OctalDigits[?Sep] OctalDigit [+Sep] OctalDigits[+Sep] NumericLiteralSeparator OctalDigit LegacyOctalIntegerLiteral :: 0 OctalDigit LegacyOctalIntegerLiteral OctalDigit NonOctalDecimalIntegerLiteral :: 0 NonOctalDigit LegacyOctalLikeDecimalIntegerLiteral NonOctalDigit NonOctalDecimalIntegerLiteral DecimalDigit LegacyOctalLikeDecimalIntegerLiteral :: 0 OctalDigit LegacyOctalLikeDecimalIntegerLiteral OctalDigit OctalDigit :: one of 0 1 2 3 4 5 6 7 NonOctalDigit :: one of 8 9 HexIntegerLiteral[Sep] :: 0x HexDigits[?Sep] 0X HexDigits[?Sep] HexDigits[Sep] :: HexDigit HexDigits[?Sep] HexDigit [+Sep] HexDigits[+Sep] NumericLiteralSeparator HexDigit HexDigit :: one of 0 1 2 3 4 5 6 7 8 9 a b c d e f A B C D E F StringLiteral :: " DoubleStringCharactersopt " ' SingleStringCharactersopt ' DoubleStringCharacters :: DoubleStringCharacter DoubleStringCharactersopt SingleStringCharacters :: SingleStringCharacter SingleStringCharactersopt DoubleStringCharacter :: SourceCharacter but not one of " or \ or LineTerminator <LS> <PS> \ EscapeSequence LineContinuation SingleStringCharacter :: SourceCharacter but not one of ' or \ or LineTerminator <LS> <PS> \ EscapeSequence LineContinuation LineContinuation :: \ LineTerminatorSequence EscapeSequence :: CharacterEscapeSequence 0 [lookahead ∉ DecimalDigit] LegacyOctalEscapeSequence NonOctalDecimalEscapeSequence HexEscapeSequence UnicodeEscapeSequence CharacterEscapeSequence :: SingleEscapeCharacter NonEscapeCharacter SingleEscapeCharacter :: one of ' " \ b f n r t v NonEscapeCharacter :: SourceCharacter but not one of EscapeCharacter or LineTerminator EscapeCharacter :: SingleEscapeCharacter DecimalDigit x u LegacyOctalEscapeSequence :: 0 [lookahead ∈ { 8, 9 }] NonZeroOctalDigit [lookahead ∉ OctalDigit] ZeroToThree OctalDigit [lookahead ∉ OctalDigit] FourToSeven OctalDigit ZeroToThree OctalDigit OctalDigit NonZeroOctalDigit :: OctalDigit but not 0 ZeroToThree :: one of 0 1 2 3 FourToSeven :: one of 4 5 6 7 NonOctalDecimalEscapeSequence :: one of 8 9 HexEscapeSequence :: x HexDigit HexDigit UnicodeEscapeSequence :: u Hex4Digits u{ CodePoint } Hex4Digits :: HexDigit HexDigit HexDigit HexDigit RegularExpressionLiteral :: / RegularExpressionBody / RegularExpressionFlags RegularExpressionBody :: RegularExpressionFirstChar RegularExpressionChars RegularExpressionChars :: [empty] RegularExpressionChars RegularExpressionChar RegularExpressionFirstChar :: RegularExpressionNonTerminator but not one of * or \ or / or [ RegularExpressionBackslashSequence RegularExpressionClass RegularExpressionChar :: RegularExpressionNonTerminator but not one of \ or / or [ RegularExpressionBackslashSequence RegularExpressionClass RegularExpressionBackslashSequence :: \ RegularExpressionNonTerminator RegularExpressionNonTerminator :: SourceCharacter but not LineTerminator RegularExpressionClass :: [ RegularExpressionClassChars ] RegularExpressionClassChars :: [empty] RegularExpressionClassChars RegularExpressionClassChar RegularExpressionClassChar :: RegularExpressionNonTerminator but not one of ] or \ RegularExpressionBackslashSequence RegularExpressionFlags :: [empty] RegularExpressionFlags IdentifierPartChar Template :: NoSubstitutionTemplate TemplateHead NoSubstitutionTemplate :: ` TemplateCharactersopt ` TemplateHead :: ` TemplateCharactersopt ${ TemplateSubstitutionTail :: TemplateMiddle TemplateTail TemplateMiddle :: } TemplateCharactersopt ${ TemplateTail :: } TemplateCharactersopt ` TemplateCharacters :: TemplateCharacter TemplateCharactersopt TemplateCharacter :: $ [lookahead ≠ {] \ TemplateEscapeSequence \ NotEscapeSequence LineContinuation LineTerminatorSequence SourceCharacter but not one of ` or \ or $ or LineTerminator TemplateEscapeSequence :: CharacterEscapeSequence 0 [lookahead ∉ DecimalDigit] HexEscapeSequence UnicodeEscapeSequence NotEscapeSequence :: 0 DecimalDigit DecimalDigit but not 0 x [lookahead ∉ HexDigit] x HexDigit [lookahead ∉ HexDigit] u [lookahead ∉ HexDigit] [lookahead ≠ {] u HexDigit [lookahead ∉ HexDigit] u HexDigit HexDigit [lookahead ∉ HexDigit] u HexDigit HexDigit HexDigit [lookahead ∉ HexDigit] u { [lookahead ∉ HexDigit] u { NotCodePoint [lookahead ∉ HexDigit] u { CodePoint [lookahead ∉ HexDigit] [lookahead ≠ }] NotCodePoint :: HexDigits[~Sep] but only if the MV of HexDigits > 0x10FFFF CodePoint :: HexDigits[~Sep] but only if the MV of HexDigits ≤ 0x10FFFF

A.2 표현식

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의 interpretation은 다음 grammar를 사용하여 refined됩니다:

ParenthesizedExpression[Yield, Await] : ( Expression[+In, ?Yield, ?Await] )

 

Literal : NullLiteral BooleanLiteral NumericLiteral StringLiteral ArrayLiteral[Yield, Await] : [ Elisionopt ] [ ElementList[?Yield, ?Await] ] [ ElementList[?Yield, ?Await] , Elisionopt ] ElementList[Yield, Await] : Elisionopt AssignmentExpression[+In, ?Yield, ?Await] Elisionopt SpreadElement[?Yield, ?Await] ElementList[?Yield, ?Await] , Elisionopt AssignmentExpression[+In, ?Yield, ?Await] ElementList[?Yield, ?Await] , Elisionopt SpreadElement[?Yield, ?Await] Elision : , Elision , SpreadElement[Yield, Await] : ... AssignmentExpression[+In, ?Yield, ?Await] ObjectLiteral[Yield, Await] : { } { PropertyDefinitionList[?Yield, ?Await] } { PropertyDefinitionList[?Yield, ?Await] , } PropertyDefinitionList[Yield, Await] : PropertyDefinition[?Yield, ?Await] PropertyDefinitionList[?Yield, ?Await] , PropertyDefinition[?Yield, ?Await] PropertyDefinition[Yield, Await] : IdentifierReference[?Yield, ?Await] CoverInitializedName[?Yield, ?Await] PropertyName[?Yield, ?Await] : AssignmentExpression[+In, ?Yield, ?Await] MethodDefinition[?Yield, ?Await] ... AssignmentExpression[+In, ?Yield, ?Await] PropertyName[Yield, Await] : LiteralPropertyName ComputedPropertyName[?Yield, ?Await] LiteralPropertyName : IdentifierName StringLiteral NumericLiteral ComputedPropertyName[Yield, Await] : [ AssignmentExpression[+In, ?Yield, ?Await] ] CoverInitializedName[Yield, Await] : IdentifierReference[?Yield, ?Await] Initializer[+In, ?Yield, ?Await] Initializer[In, Yield, Await] : = AssignmentExpression[?In, ?Yield, ?Await] TemplateLiteral[Yield, Await, Tagged] : NoSubstitutionTemplate SubstitutionTemplate[?Yield, ?Await, ?Tagged] SubstitutionTemplate[Yield, Await, Tagged] : TemplateHead Expression[+In, ?Yield, ?Await] TemplateSpans[?Yield, ?Await, ?Tagged] TemplateSpans[Yield, Await, Tagged] : TemplateTail TemplateMiddleList[?Yield, ?Await, ?Tagged] TemplateTail TemplateMiddleList[Yield, Await, Tagged] : TemplateMiddle Expression[+In, ?Yield, ?Await] TemplateMiddleList[?Yield, ?Await, ?Tagged] TemplateMiddle Expression[+In, ?Yield, ?Await] MemberExpression[Yield, Await] : PrimaryExpression[?Yield, ?Await] MemberExpression[?Yield, ?Await] [ Expression[+In, ?Yield, ?Await] ] MemberExpression[?Yield, ?Await] . IdentifierName MemberExpression[?Yield, ?Await] TemplateLiteral[?Yield, ?Await, +Tagged] SuperProperty[?Yield, ?Await] MetaProperty new MemberExpression[?Yield, ?Await] Arguments[?Yield, ?Await] MemberExpression[?Yield, ?Await] . PrivateIdentifier SuperProperty[Yield, Await] : super [ Expression[+In, ?Yield, ?Await] ] super . IdentifierName MetaProperty : NewTarget ImportMeta NewTarget : new . target ImportMeta : import . meta NewExpression[Yield, Await] : MemberExpression[?Yield, ?Await] new NewExpression[?Yield, ?Await] CallExpression[Yield, Await] : CoverCallExpressionAndAsyncArrowHead[?Yield, ?Await] SuperCall[?Yield, ?Await] ImportCall[?Yield, ?Await] CallExpression[?Yield, ?Await] Arguments[?Yield, ?Await] CallExpression[?Yield, ?Await] [ Expression[+In, ?Yield, ?Await] ] CallExpression[?Yield, ?Await] . IdentifierName CallExpression[?Yield, ?Await] TemplateLiteral[?Yield, ?Await, +Tagged] CallExpression[?Yield, ?Await] . PrivateIdentifier

다음 production의 instance를 처리할 때
CallExpression[Yield, Await] : CoverCallExpressionAndAsyncArrowHead[?Yield, ?Await]
CoverCallExpressionAndAsyncArrowHead의 interpretation은 다음 grammar를 사용하여 refined됩니다:

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 *= /= %= += -= <<= >>= >>>= &= ^= |= **=

특정 circumstances에서 다음 production의 instance를 처리할 때
AssignmentExpression[In, Yield, Await] : LeftHandSideExpression[?Yield, ?Await] = AssignmentExpression[?In, ?Yield, ?Await]
LeftHandSideExpression의 interpretation은 다음 grammar를 사용하여 refined됩니다:

AssignmentPattern[Yield, Await] : ObjectAssignmentPattern[?Yield, ?Await] ArrayAssignmentPattern[?Yield, ?Await] ObjectAssignmentPattern[Yield, Await] : { } { AssignmentRestProperty[?Yield, ?Await] } { AssignmentPropertyList[?Yield, ?Await] } { AssignmentPropertyList[?Yield, ?Await] , AssignmentRestProperty[?Yield, ?Await]opt } ArrayAssignmentPattern[Yield, Await] : [ Elisionopt AssignmentRestElement[?Yield, ?Await]opt ] [ AssignmentElementList[?Yield, ?Await] ] [ AssignmentElementList[?Yield, ?Await] , Elisionopt AssignmentRestElement[?Yield, ?Await]opt ] AssignmentRestProperty[Yield, Await] : ... DestructuringAssignmentTarget[?Yield, ?Await] AssignmentPropertyList[Yield, Await] : AssignmentProperty[?Yield, ?Await] AssignmentPropertyList[?Yield, ?Await] , AssignmentProperty[?Yield, ?Await] AssignmentElementList[Yield, Await] : AssignmentElisionElement[?Yield, ?Await] AssignmentElementList[?Yield, ?Await] , AssignmentElisionElement[?Yield, ?Await] AssignmentElisionElement[Yield, Await] : Elisionopt AssignmentElement[?Yield, ?Await] AssignmentProperty[Yield, Await] : IdentifierReference[?Yield, ?Await] Initializer[+In, ?Yield, ?Await]opt PropertyName[?Yield, ?Await] : AssignmentElement[?Yield, ?Await] AssignmentElement[Yield, Await] : DestructuringAssignmentTarget[?Yield, ?Await] Initializer[+In, ?Yield, ?Await]opt AssignmentRestElement[Yield, Await] : ... DestructuringAssignmentTarget[?Yield, ?Await] DestructuringAssignmentTarget[Yield, Await] : LeftHandSideExpression[?Yield, ?Await]

 

Expression[In, Yield, Await] : AssignmentExpression[?In, ?Yield, ?Await] Expression[?In, ?Yield, ?Await] , AssignmentExpression[?In, ?Yield, ?Await]

A.3

Statement[Yield, Await, Return] : BlockStatement[?Yield, ?Await, ?Return] VariableStatement[?Yield, ?Await] EmptyStatement ExpressionStatement[?Yield, ?Await] IfStatement[?Yield, ?Await, ?Return] BreakableStatement[?Yield, ?Await, ?Return] ContinueStatement[?Yield, ?Await] BreakStatement[?Yield, ?Await] [+Return] ReturnStatement[?Yield, ?Await] WithStatement[?Yield, ?Await, ?Return] LabelledStatement[?Yield, ?Await, ?Return] ThrowStatement[?Yield, ?Await] TryStatement[?Yield, ?Await, ?Return] DebuggerStatement Declaration[Yield, Await] : HoistableDeclaration[?Yield, ?Await, ~Default] ClassDeclaration[?Yield, ?Await, ~Default] LexicalDeclaration[+In, ?Yield, ?Await] HoistableDeclaration[Yield, Await, Default] : FunctionDeclaration[?Yield, ?Await, ?Default] GeneratorDeclaration[?Yield, ?Await, ?Default] AsyncFunctionDeclaration[?Yield, ?Await, ?Default] AsyncGeneratorDeclaration[?Yield, ?Await, ?Default] BreakableStatement[Yield, Await, Return] : IterationStatement[?Yield, ?Await, ?Return] SwitchStatement[?Yield, ?Await, ?Return] BlockStatement[Yield, Await, Return] : Block[?Yield, ?Await, ?Return] Block[Yield, Await, Return] : { StatementList[?Yield, ?Await, ?Return]opt } StatementList[Yield, Await, Return] : StatementListItem[?Yield, ?Await, ?Return] StatementList[?Yield, ?Await, ?Return] StatementListItem[?Yield, ?Await, ?Return] StatementListItem[Yield, Await, Return] : Statement[?Yield, ?Await, ?Return] Declaration[?Yield, ?Await] LexicalDeclaration[In, Yield, Await] : LetOrConst BindingList[?In, ?Yield, ?Await, +Pattern] ; UsingDeclaration[?In, ?Yield, ?Await] [+Await] AwaitUsingDeclaration[?In, ?Yield] LetOrConst : let const UsingDeclaration[In, Yield, Await] : using [no LineTerminator here] BindingList[?In, ?Yield, ?Await, ~Pattern] ; AwaitUsingDeclaration[In, Yield] : CoverAwaitExpressionAndAwaitUsingDeclarationHead[?Yield] [no LineTerminator here] BindingList[?In, ?Yield, +Await, ~Pattern] ; BindingList[In, Yield, Await, Pattern] : LexicalBinding[?In, ?Yield, ?Await, ?Pattern] BindingList[?In, ?Yield, ?Await, ?Pattern] , LexicalBinding[?In, ?Yield, ?Await, ?Pattern] LexicalBinding[In, Yield, Await, Pattern] : BindingIdentifier[?Yield, ?Await] Initializer[?In, ?Yield, ?Await]opt [+Pattern] BindingPattern[?Yield, ?Await] Initializer[?In, ?Yield, ?Await]

생성식의 인스턴스를 처리할 때
AwaitUsingDeclaration[In, Yield] : CoverAwaitExpressionAndAwaitUsingDeclarationHead[?Yield] [no LineTerminator here] BindingList[?In, ?Yield, +Await, ~Pattern] ;
CoverAwaitExpressionAndAwaitUsingDeclarationHead의 해석은 다음 문법을 사용하여 정제된다:

AwaitUsingDeclarationHead : await [no LineTerminator here] using

 

VariableStatement[Yield, Await] : var VariableDeclarationList[+In, ?Yield, ?Await] ; VariableDeclarationList[In, Yield, Await] : VariableDeclaration[?In, ?Yield, ?Await] VariableDeclarationList[?In, ?Yield, ?Await] , VariableDeclaration[?In, ?Yield, ?Await] VariableDeclaration[In, Yield, Await] : BindingIdentifier[?Yield, ?Await] Initializer[?In, ?Yield, ?Await]opt BindingPattern[?Yield, ?Await] Initializer[?In, ?Yield, ?Await] BindingPattern[Yield, Await] : ObjectBindingPattern[?Yield, ?Await] ArrayBindingPattern[?Yield, ?Await] ObjectBindingPattern[Yield, Await] : { } { BindingRestProperty[?Yield, ?Await] } { BindingPropertyList[?Yield, ?Await] } { BindingPropertyList[?Yield, ?Await] , BindingRestProperty[?Yield, ?Await]opt } ArrayBindingPattern[Yield, Await] : [ Elisionopt BindingRestElement[?Yield, ?Await]opt ] [ BindingElementList[?Yield, ?Await] ] [ BindingElementList[?Yield, ?Await] , Elisionopt BindingRestElement[?Yield, ?Await]opt ] BindingRestProperty[Yield, Await] : ... BindingIdentifier[?Yield, ?Await] BindingPropertyList[Yield, Await] : BindingProperty[?Yield, ?Await] BindingPropertyList[?Yield, ?Await] , BindingProperty[?Yield, ?Await] BindingElementList[Yield, Await] : BindingElisionElement[?Yield, ?Await] BindingElementList[?Yield, ?Await] , BindingElisionElement[?Yield, ?Await] BindingElisionElement[Yield, Await] : Elisionopt BindingElement[?Yield, ?Await] BindingProperty[Yield, Await] : SingleNameBinding[?Yield, ?Await] PropertyName[?Yield, ?Await] : BindingElement[?Yield, ?Await] BindingElement[Yield, Await] : SingleNameBinding[?Yield, ?Await] BindingPattern[?Yield, ?Await] Initializer[+In, ?Yield, ?Await]opt SingleNameBinding[Yield, Await] : BindingIdentifier[?Yield, ?Await] Initializer[+In, ?Yield, ?Await]opt BindingRestElement[Yield, Await] : ... BindingIdentifier[?Yield, ?Await] ... BindingPattern[?Yield, ?Await] EmptyStatement : ; ExpressionStatement[Yield, Await] : [lookahead ∉ { {, function, async [no LineTerminator here] function, class, let [ }] Expression[+In, ?Yield, ?Await] ; IfStatement[Yield, Await, Return] : if ( Expression[+In, ?Yield, ?Await] ) Statement[?Yield, ?Await, ?Return] else Statement[?Yield, ?Await, ?Return] if ( Expression[+In, ?Yield, ?Await] ) Statement[?Yield, ?Await, ?Return] [lookahead ≠ else] IterationStatement[Yield, Await, Return] : DoWhileStatement[?Yield, ?Await, ?Return] WhileStatement[?Yield, ?Await, ?Return] ForStatement[?Yield, ?Await, ?Return] ForInOfStatement[?Yield, ?Await, ?Return] DoWhileStatement[Yield, Await, Return] : do Statement[?Yield, ?Await, ?Return] while ( Expression[+In, ?Yield, ?Await] ) ; WhileStatement[Yield, Await, Return] : while ( Expression[+In, ?Yield, ?Await] ) Statement[?Yield, ?Await, ?Return] ForStatement[Yield, Await, Return] : for ( [lookahead ≠ let [] Expression[~In, ?Yield, ?Await]opt ; Expression[+In, ?Yield, ?Await]opt ; Expression[+In, ?Yield, ?Await]opt ) Statement[?Yield, ?Await, ?Return] for ( var VariableDeclarationList[~In, ?Yield, ?Await] ; Expression[+In, ?Yield, ?Await]opt ; Expression[+In, ?Yield, ?Await]opt ) Statement[?Yield, ?Await, ?Return] for ( LexicalDeclaration[~In, ?Yield, ?Await] Expression[+In, ?Yield, ?Await]opt ; Expression[+In, ?Yield, ?Await]opt ) Statement[?Yield, ?Await, ?Return] ForInOfStatement[Yield, Await, Return] : for ( [lookahead ≠ let [] LeftHandSideExpression[?Yield, ?Await] in Expression[+In, ?Yield, ?Await] ) Statement[?Yield, ?Await, ?Return] for ( var ForBinding[?Yield, ?Await, +Pattern] in Expression[+In, ?Yield, ?Await] ) Statement[?Yield, ?Await, ?Return] for ( ForDeclaration[?Yield, ?Await, ~Using] in Expression[+In, ?Yield, ?Await] ) Statement[?Yield, ?Await, ?Return] for ( [lookahead ∉ { let, async of }] LeftHandSideExpression[?Yield, ?Await] of AssignmentExpression[+In, ?Yield, ?Await] ) Statement[?Yield, ?Await, ?Return] for ( var ForBinding[?Yield, ?Await, +Pattern] of AssignmentExpression[+In, ?Yield, ?Await] ) Statement[?Yield, ?Await, ?Return] for ( [lookahead ≠ using of] ForDeclaration[?Yield, ?Await, +Using] of AssignmentExpression[+In, ?Yield, ?Await] ) Statement[?Yield, ?Await, ?Return] [+Await] for await ( [lookahead ≠ let] LeftHandSideExpression[?Yield, ?Await] of AssignmentExpression[+In, ?Yield, ?Await] ) Statement[?Yield, ?Await, ?Return] [+Await] for await ( var ForBinding[?Yield, ?Await, +Pattern] of AssignmentExpression[+In, ?Yield, ?Await] ) Statement[?Yield, ?Await, ?Return] [+Await] for await ( [lookahead ≠ using of] ForDeclaration[?Yield, ?Await, +Using] of AssignmentExpression[+In, ?Yield, ?Await] ) Statement[?Yield, ?Await, ?Return] ForDeclaration[Yield, Await, Using] : LetOrConst ForBinding[?Yield, ?Await, +Pattern] [+Using] using [no LineTerminator here] ForBinding[?Yield, ?Await, ~Pattern] [+Using, +Await] await [no LineTerminator here] using [no LineTerminator here] ForBinding[?Yield, +Await, ~Pattern] ForBinding[Yield, Await, Pattern] : BindingIdentifier[?Yield, ?Await] [+Pattern] BindingPattern[?Yield, ?Await] ContinueStatement[Yield, Await] : continue ; continue [no LineTerminator here] LabelIdentifier[?Yield, ?Await] ; BreakStatement[Yield, Await] : break ; break [no LineTerminator here] LabelIdentifier[?Yield, ?Await] ; ReturnStatement[Yield, Await] : return ; return [no LineTerminator here] Expression[+In, ?Yield, ?Await] ; WithStatement[Yield, Await, Return] : with ( Expression[+In, ?Yield, ?Await] ) Statement[?Yield, ?Await, ?Return] SwitchStatement[Yield, Await, Return] : switch ( Expression[+In, ?Yield, ?Await] ) CaseBlock[?Yield, ?Await, ?Return] CaseBlock[Yield, Await, Return] : { CaseClauses[?Yield, ?Await, ?Return]opt } { CaseClauses[?Yield, ?Await, ?Return]opt DefaultClause[?Yield, ?Await, ?Return] CaseClauses[?Yield, ?Await, ?Return]opt } CaseClauses[Yield, Await, Return] : CaseClause[?Yield, ?Await, ?Return] CaseClauses[?Yield, ?Await, ?Return] CaseClause[?Yield, ?Await, ?Return] CaseClause[Yield, Await, Return] : case Expression[+In, ?Yield, ?Await] : StatementList[?Yield, ?Await, ?Return]opt DefaultClause[Yield, Await, Return] : default : StatementList[?Yield, ?Await, ?Return]opt LabelledStatement[Yield, Await, Return] : LabelIdentifier[?Yield, ?Await] : LabelledItem[?Yield, ?Await, ?Return] LabelledItem[Yield, Await, Return] : Statement[?Yield, ?Await, ?Return] FunctionDeclaration[?Yield, ?Await, ~Default] ThrowStatement[Yield, Await] : throw [no LineTerminator here] Expression[+In, ?Yield, ?Await] ; TryStatement[Yield, Await, Return] : try Block[?Yield, ?Await, ?Return] Catch[?Yield, ?Await, ?Return] try Block[?Yield, ?Await, ?Return] Finally[?Yield, ?Await, ?Return] try Block[?Yield, ?Await, ?Return] Catch[?Yield, ?Await, ?Return] Finally[?Yield, ?Await, ?Return] Catch[Yield, Await, Return] : catch ( CatchParameter[?Yield, ?Await] ) Block[?Yield, ?Await, ?Return] catch Block[?Yield, ?Await, ?Return] Finally[Yield, Await, Return] : finally Block[?Yield, ?Await, ?Return] CatchParameter[Yield, Await] : BindingIdentifier[?Yield, ?Await] BindingPattern[?Yield, ?Await] DebuggerStatement : debugger ;

A.4 함수와 클래스

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의 interpretation은 다음 grammar를 사용하여 refined됩니다:

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의 interpretation은 다음 grammar를 사용하여 refined됩니다:

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 스크립트와 모듈

Script : ScriptBodyopt ScriptBody : StatementList[~Yield, ~Await, ~Return] Module : ModuleBodyopt ModuleBody : ModuleItemList ModuleItemList : ModuleItem ModuleItemList ModuleItem ModuleItem : ImportDeclaration ExportDeclaration StatementListItem[~Yield, +Await, ~Return] ModuleExportName : IdentifierName StringLiteral ImportDeclaration : import ImportClause FromClause WithClauseopt ; import ModuleSpecifier WithClauseopt ; ImportClause : ImportedDefaultBinding NameSpaceImport NamedImports ImportedDefaultBinding , NameSpaceImport ImportedDefaultBinding , NamedImports ImportedDefaultBinding : ImportedBinding NameSpaceImport : * as ImportedBinding NamedImports : { } { ImportsList } { ImportsList , } FromClause : from ModuleSpecifier ImportsList : ImportSpecifier ImportsList , ImportSpecifier ImportSpecifier : ImportedBinding ModuleExportName as ImportedBinding ModuleSpecifier : StringLiteral ImportedBinding : BindingIdentifier[~Yield, +Await] WithClause : with { } with { WithEntries ,opt } WithEntries : AttributeKey : StringLiteral AttributeKey : StringLiteral , WithEntries AttributeKey : IdentifierName StringLiteral ExportDeclaration : export ExportFromClause FromClause WithClauseopt ; export NamedExports ; export VariableStatement[~Yield, +Await] export [lookahead ∉ { using, await }] Declaration[~Yield, +Await] export default HoistableDeclaration[~Yield, +Await, +Default] export default ClassDeclaration[~Yield, +Await, +Default] export default [lookahead ∉ { function, async [no LineTerminator here] function, class }] AssignmentExpression[+In, ~Yield, +Await] ; ExportFromClause : * * as ModuleExportName NamedExports NamedExports : { } { ExportsList } { ExportsList , } ExportsList : ExportSpecifier ExportsList , ExportSpecifier ExportSpecifier : ModuleExportName ModuleExportName as ModuleExportName

A.6 Number 변환

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

StringNumericLiteral grammar에 의해 explicitly defined되지 않은 모든 grammar symbols는 numeric literals에 대한 Lexical Grammar에서 사용되는 definitions를 가집니다.

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

A.7 Time Zone Offset String 형식

UTCOffset ::: ASCIISign Hour ASCIISign Hour HourSubcomponents[+Extended] ASCIISign Hour HourSubcomponents[~Extended] ASCIISign ::: one of + - Hour ::: 0 DecimalDigit 1 DecimalDigit 20 21 22 23 HourSubcomponents[Extended] ::: TimeSeparator[?Extended] MinuteSecond TimeSeparator[?Extended] MinuteSecond TimeSeparator[?Extended] MinuteSecond TemporalDecimalFractionopt TimeSeparator[Extended] ::: [+Extended] : [~Extended] [empty] MinuteSecond ::: 0 DecimalDigit 1 DecimalDigit 2 DecimalDigit 3 DecimalDigit 4 DecimalDigit 5 DecimalDigit TemporalDecimalFraction ::: TemporalDecimalSeparator DecimalDigit TemporalDecimalSeparator DecimalDigit DecimalDigit TemporalDecimalSeparator DecimalDigit DecimalDigit DecimalDigit TemporalDecimalSeparator DecimalDigit DecimalDigit DecimalDigit DecimalDigit TemporalDecimalSeparator DecimalDigit DecimalDigit DecimalDigit DecimalDigit DecimalDigit TemporalDecimalSeparator DecimalDigit DecimalDigit DecimalDigit DecimalDigit DecimalDigit DecimalDigit TemporalDecimalSeparator DecimalDigit DecimalDigit DecimalDigit DecimalDigit DecimalDigit DecimalDigit DecimalDigit TemporalDecimalSeparator DecimalDigit DecimalDigit DecimalDigit DecimalDigit DecimalDigit DecimalDigit DecimalDigit DecimalDigit TemporalDecimalSeparator DecimalDigit DecimalDigit DecimalDigit DecimalDigit DecimalDigit DecimalDigit DecimalDigit DecimalDigit DecimalDigit TemporalDecimalSeparator ::: one of . ,

A.8 정규 표현식

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는, otherwise corresponding \u HexTrailSurrogate를 가지지 않을 nearest possible u HexLeadSurrogate와 associated되어야 합니다.

 

HexLeadSurrogate :: Hex4Digits but only if the MV of Hex4Digits is in the inclusive interval from 0xD800 to 0xDBFF HexTrailSurrogate :: Hex4Digits but only if the MV of Hex4Digits is in the inclusive interval from 0xDC00 to 0xDFFF HexNonSurrogate :: Hex4Digits but only if the MV of Hex4Digits is not in the inclusive interval from 0xD800 to 0xDFFF IdentityEscape[UnicodeMode] :: [+UnicodeMode] SyntaxCharacter [+UnicodeMode] / [~UnicodeMode] SourceCharacter but not UnicodeIDContinue DecimalEscape :: NonZeroDigit DecimalDigits[~Sep]opt [lookahead ∉ DecimalDigit] CharacterClassEscape[UnicodeMode] :: d D s S w W [+UnicodeMode] p{ UnicodePropertyValueExpression } [+UnicodeMode] P{ UnicodePropertyValueExpression } UnicodePropertyValueExpression :: UnicodePropertyName = UnicodePropertyValue LoneUnicodePropertyNameOrValue UnicodePropertyName :: UnicodePropertyNameCharacters UnicodePropertyNameCharacters :: UnicodePropertyNameCharacter UnicodePropertyNameCharactersopt UnicodePropertyValue :: UnicodePropertyValueCharacters LoneUnicodePropertyNameOrValue :: UnicodePropertyValueCharacters UnicodePropertyValueCharacters :: UnicodePropertyValueCharacter UnicodePropertyValueCharactersopt UnicodePropertyValueCharacter :: UnicodePropertyNameCharacter DecimalDigit UnicodePropertyNameCharacter :: AsciiLetter _ CharacterClass[UnicodeMode, UnicodeSetsMode] :: [ [lookahead ≠ ^] ClassContents[?UnicodeMode, ?UnicodeSetsMode] ] [^ ClassContents[?UnicodeMode, ?UnicodeSetsMode] ] ClassContents[UnicodeMode, UnicodeSetsMode] :: [empty] [~UnicodeSetsMode] NonemptyClassRanges[?UnicodeMode] [+UnicodeSetsMode] ClassSetExpression NonemptyClassRanges[UnicodeMode] :: ClassAtom[?UnicodeMode] ClassAtom[?UnicodeMode] NonemptyClassRangesNoDash[?UnicodeMode] ClassAtom[?UnicodeMode] - ClassAtom[?UnicodeMode] ClassContents[?UnicodeMode, ~UnicodeSetsMode] NonemptyClassRangesNoDash[UnicodeMode] :: ClassAtom[?UnicodeMode] ClassAtomNoDash[?UnicodeMode] NonemptyClassRangesNoDash[?UnicodeMode] ClassAtomNoDash[?UnicodeMode] - ClassAtom[?UnicodeMode] ClassContents[?UnicodeMode, ~UnicodeSetsMode] ClassAtom[UnicodeMode] :: - ClassAtomNoDash[?UnicodeMode] ClassAtomNoDash[UnicodeMode] :: SourceCharacter but not one of \ or ] or - \ ClassEscape[?UnicodeMode] ClassEscape[UnicodeMode] :: b [+UnicodeMode] - CharacterClassEscape[?UnicodeMode] CharacterEscape[?UnicodeMode] ClassSetExpression :: ClassUnion ClassIntersection ClassSubtraction ClassUnion :: ClassSetRange ClassUnionopt ClassSetOperand ClassUnionopt ClassIntersection :: ClassSetOperand && [lookahead ≠ &] ClassSetOperand ClassIntersection && [lookahead ≠ &] ClassSetOperand ClassSubtraction :: ClassSetOperand -- ClassSetOperand ClassSubtraction -- ClassSetOperand ClassSetRange :: ClassSetCharacter - ClassSetCharacter ClassSetOperand :: NestedClass ClassStringDisjunction ClassSetCharacter NestedClass :: [ [lookahead ≠ ^] ClassContents[+UnicodeMode, +UnicodeSetsMode] ] [^ ClassContents[+UnicodeMode, +UnicodeSetsMode] ] \ CharacterClassEscape[+UnicodeMode] ClassStringDisjunction :: \q{ ClassStringDisjunctionContents } ClassStringDisjunctionContents :: ClassString ClassString | ClassStringDisjunctionContents ClassString :: [empty] NonEmptyClassString NonEmptyClassString :: ClassSetCharacter NonEmptyClassStringopt ClassSetCharacter :: [lookahead ∉ ClassSetReservedDoublePunctuator] SourceCharacter but not ClassSetSyntaxCharacter \ CharacterEscape[+UnicodeMode] \ ClassSetReservedPunctuator \b ClassSetReservedDoublePunctuator :: one of && !! ## $$ %% ** ++ ,, .. :: ;; << == >> ?? @@ ^^ `` ~~ ClassSetSyntaxCharacter :: one of ( ) [ ] { } / - \ | ClassSetReservedPunctuator :: one of & - ! # % , : ; < = > @ ` ~

Annex B (normative) 웹 브라우저를 위한 추가 ECMAScript 기능

이 annex에서 정의되는 ECMAScript language syntax와 semantics는 ECMAScript host가 web browser일 때 요구됩니다. 이 annex의 내용은 normative이지만 ECMAScript host가 web browser가 아닌 경우 optional입니다.

이 annex에서 정의되는 일부 기능은 이 annex에 specified되며, 일부는 이 문서의 main body에 specified됩니다.

기능이 main body에 specified되는 경우, 그것이 문서에 영향을 주는 각 지점은 coloured box 안의 “Normative Optional”이라는 단어로 표시됩니다. 또한 그 기능이 algorithm이나 early error rule에서 특정 wording을 수반하는 경우, 이는 relevant feature를 “the host supports”한다는 condition으로 guarded됩니다. Web browsers는 이러한 모든 기능을 support해야 합니다.

Note

이 annex는 web browser ECMAScript hosts의 다양한 legacy features와 기타 characteristics를 설명합니다. 이 annex에 specified된 모든 language features와 behaviours는 하나 이상의 바람직하지 않은 characteristics를 가지고 있으며 legacy usage가 없다면 이 specification에서 제거될 것입니다. 그러나 많은 기존 web pages가 이러한 features를 사용하기 때문에 web browsers는 계속 이를 support해야 합니다. 이 annex의 specifications는 이러한 legacy features의 interoperable implementations에 대한 requirements를 정의합니다.

이러한 features는 core ECMAScript language의 일부로 간주되지 않습니다. Programmers는 새로운 ECMAScript code를 작성할 때 이러한 features와 behaviours의 존재를 사용하거나 가정해서는 안 됩니다. ECMAScript implementations는 implementation이 web browser의 일부이거나 web browsers가 마주치는 동일한 legacy ECMAScript code를 실행해야 하는 경우가 아니면 이러한 features를 implement하지 않는 것이 권장됩니다.

B.1 추가 구문

B.1.1 HTML-like Comments

12.4의 syntax와 semantics는 다음과 같이 extended됩니다. 단, 이 extension은 goal symbol Module을 사용하여 source text를 parsing할 때는 allowed되지 않습니다:

Syntax

InputElementHashbangOrRegExp :: WhiteSpace LineTerminator Comment CommonToken HashbangComment RegularExpressionLiteral HTMLCloseComment Comment :: MultiLineComment SingleLineComment SingleLineHTMLOpenComment SingleLineHTMLCloseComment SingleLineDelimitedComment MultiLineComment :: /* FirstCommentLineopt LineTerminator MultiLineCommentCharsopt */ HTMLCloseCommentopt FirstCommentLine :: SingleLineDelimitedCommentChars SingleLineHTMLOpenComment :: <!-- SingleLineCommentCharsopt SingleLineHTMLCloseComment :: LineTerminatorSequence HTMLCloseComment SingleLineDelimitedComment :: /* SingleLineDelimitedCommentCharsopt */ HTMLCloseComment :: WhiteSpaceSequenceopt SingleLineDelimitedCommentSequenceopt --> SingleLineCommentCharsopt SingleLineDelimitedCommentChars :: SingleLineNotAsteriskChar SingleLineDelimitedCommentCharsopt * SingleLinePostAsteriskCommentCharsopt SingleLineNotAsteriskChar :: SourceCharacter but not one of * or LineTerminator SingleLinePostAsteriskCommentChars :: SingleLineNotForwardSlashOrAsteriskChar SingleLineDelimitedCommentCharsopt * SingleLinePostAsteriskCommentCharsopt SingleLineNotForwardSlashOrAsteriskChar :: SourceCharacter but not one of / or * or LineTerminator WhiteSpaceSequence :: WhiteSpace WhiteSpaceSequenceopt SingleLineDelimitedCommentSequence :: SingleLineDelimitedComment WhiteSpaceSequenceopt SingleLineDelimitedCommentSequenceopt

line terminator code point를 포함하는 MultiLineComment와 유사하게, SingleLineHTMLCloseComment는 syntactic grammar에 의한 parsing purposes에서 LineTerminator로 간주됩니다.

B.1.2 Regular Expressions Patterns

22.2.1의 syntax는 다음과 같이 modified되고 extended됩니다. 이러한 changes는 grammar productions의 ordering과 contextual information에 의해 resolved되는 ambiguities를 도입합니다. 다음 grammar를 사용하여 parsing할 때, 각 alternative는 previous production alternatives가 match하지 않는 경우에만 considered됩니다.

이 alternative pattern grammar와 semantics는 BMP patterns의 syntax와 semantics만 변경합니다. 다음 grammar extensions는 [UnicodeMode] parameter로 parameterized된 productions를 포함합니다. 그러나 이러한 extensions 중 어느 것도 [UnicodeMode] parameter가 goal symbol에 present한 상태로 parsing할 때 recognized되는 Unicode patterns의 syntax를 변경하지 않습니다.

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 모두와 함께 발생하는 경우 이는 disambiguation priority를 control하기 위한 것입니다.

B.1.2.1 Static Semantics: Early Errors

22.2.1.1의 semantics는 다음과 같이 extended됩니다:

ExtendedAtom :: InvalidBracedQuantifier
  • 이 production에 의해 match되는 source text가 있으면 Syntax Error입니다.

Additionally, 다음 productions에 대한 rules는 highlighted text의 addition으로 modified됩니다:

NonemptyClassRanges :: ClassAtom - ClassAtom ClassContents NonemptyClassRangesNoDash :: ClassAtomNoDash - ClassAtom ClassContents

B.1.2.2 Static Semantics: CountLeftCapturingParensWithin and CountLeftCapturingParensBefore

CountLeftCapturingParensWithinCountLeftCapturingParensBefore의 definitions에서, “ Atom :: ( GroupSpecifieropt Disjunction ) ”에 대한 references는 “ Atom :: ( GroupSpecifieropt Disjunction ) ” 또는 “ ExtendedAtom :: ( GroupSpecifieropt Disjunction ) ”를 의미하는 것으로 interpreted되어야 합니다.

B.1.2.3 Static Semantics: IsCharacterClass

22.2.1.6의 semantics는 다음과 같이 extended됩니다:

ClassAtomNoDash :: \ [lookahead = c]
  1. false를 반환한다.

B.1.2.4 Static Semantics: CharacterValue

22.2.1.7의 semantics는 다음과 같이 extended됩니다:

ClassAtomNoDash :: \ [lookahead = c]
  1. U+005C (REVERSE SOLIDUS)의 numeric value를 반환한다.
ClassEscape :: c ClassControlLetter
  1. codePointClassControlLetter와 match된 code point로 둔다.
  2. icodePoint의 numeric value로 둔다.
  3. i를 32로 나눈 remainder를 반환한다.
CharacterEscape :: LegacyOctalEscapeSequence
  1. LegacyOctalEscapeSequence의 MV를 반환한다(12.9.4.3 참조).

B.1.2.5 Runtime Semantics: CompileSubpattern

CompileSubpattern의 semantics는 다음과 같이 extended됩니다:

Term :: QuantifiableAssertion Quantifier 에 대한 rule은 Term :: Atom Quantifier 와 동일하지만 Atom 대신 QuantifiableAssertion이 substituted됩니다.

Term :: ExtendedAtom Quantifier 에 대한 rule은 Term :: Atom Quantifier 와 동일하지만 Atom 대신 ExtendedAtom이 substituted됩니다.

Term :: ExtendedAtom 에 대한 rule은 Term :: Atom 와 동일하지만 Atom 대신 ExtendedAtom이 substituted됩니다.

B.1.2.6 Runtime Semantics: CompileAssertion

Assertion :: (?= Disjunction ) Assertion :: (?! Disjunction ) productions에 대한 CompileAssertion rules는 QuantifiableAssertion productions에도 사용되지만, Assertion 대신 QuantifiableAssertion이 substituted됩니다.

B.1.2.7 Runtime Semantics: CompileAtom

Atom :: PatternCharacter 를 제외한 Atom productions에 대한 CompileAtom rules는 ExtendedAtom productions에도 사용되지만, Atom 대신 ExtendedAtom이 substituted됩니다. parameter direction을 가지는 다음 rules도 added됩니다:

ExtendedAtom :: \ [lookahead = c]
  1. charSet를 single character \ U+005C (REVERSE SOLIDUS)를 포함하는 CharSet으로 둔다.
  2. CharacterSetMatcher(regexpRecord, charSet, false, direction)를 반환한다.
ExtendedAtom :: ExtendedPatternCharacter
  1. charExtendedPatternCharacter가 represented하는 character로 둔다.
  2. charSet를 character char를 포함하는 one-element CharSet으로 둔다.
  3. CharacterSetMatcher(regexpRecord, charSet, false, direction)를 반환한다.

B.1.2.8 Runtime Semantics: CompileToCharSet

22.2.2.9의 semantics는 다음과 같이 extended됩니다:

다음 두 rules는 CompileToCharSet의 corresponding rules를 replace합니다.

NonemptyClassRanges :: ClassAtom - ClassAtom ClassContents
  1. charSet를 argument regexpRecord를 사용한 첫 번째 ClassAtomCompileToCharSet으로 둔다.
  2. otherSet를 argument regexpRecord를 사용한 두 번째 ClassAtomCompileToCharSet으로 둔다.
  3. remainingSet를 argument regexpRecord를 사용한 ClassContentsCompileToCharSet으로 둔다.
  4. rangeSetCharacterRangeOrUnion(regexpRecord, charSet, otherSet)로 둔다.
  5. rangeSetremainingSet의 union을 반환한다.
NonemptyClassRangesNoDash :: ClassAtomNoDash - ClassAtom ClassContents
  1. charSet를 argument regexpRecord를 사용한 ClassAtomNoDashCompileToCharSet으로 둔다.
  2. otherSet를 argument regexpRecord를 사용한 ClassAtomCompileToCharSet으로 둔다.
  3. remainingSet를 argument regexpRecord를 사용한 ClassContentsCompileToCharSet으로 둔다.
  4. rangeSetCharacterRangeOrUnion(regexpRecord, charSet, otherSet)로 둔다.
  5. rangeSetremainingSet의 union을 반환한다.

또한 다음 rules가 CompileToCharSet에 added됩니다.

ClassEscape :: c ClassControlLetter
  1. charValue를 이 ClassEscapeCharacterValue로 둔다.
  2. char를 character value가 charValue인 character로 둔다.
  3. single character char를 포함하는 CharSet을 반환한다.
ClassAtomNoDash :: \ [lookahead = c]
  1. single character \ U+005C (REVERSE SOLIDUS)를 포함하는 CharSet을 반환한다.
Note
이 production은 character class 내에서 sequence \c 뒤에 acceptable control character가 따르지 않는 경우에만 reached될 수 있습니다.

B.1.2.8.1 CharacterRangeOrUnion ( regexpRecord, charSet, otherSet )

The abstract operation CharacterRangeOrUnion takes arguments regexpRecord (a RegExp Record), charSet (a CharSet), and otherSet (a CharSet) and returns a CharSet. It performs the following steps when called:

  1. HasEitherUnicodeFlag(regexpRecord)가 false이면, 다음을 수행한다.
    1. charSet이 정확히 one character를 포함하지 않거나 otherSet이 정확히 one character를 포함하지 않으면, 다음을 수행한다.
      1. remainingSet를 single character - U+002D (HYPHEN-MINUS)를 포함하는 CharSet으로 둔다.
      2. CharSets charSet, otherSetremainingSet의 union을 반환한다.
  2. CharacterRange(charSet, otherSet)를 반환한다.

B.1.2.9 Static Semantics: ParsePattern ( patternText, u, v )

22.2.3.4의 semantics는 다음과 같이 extended됩니다:

abstract operation ParsePattern은 arguments patternText (Unicode code points의 sequence), u (a Boolean), 및 v (a Boolean)를 받습니다. called될 때 다음 steps를 수행합니다:

  1. vtrue이고 utrue이면, 다음을 수행한다.
    1. parseResult를 하나 이상의 SyntaxError objects를 포함하는 List로 둔다.
  2. Else if vtrue이면, 다음을 수행한다.
    1. parseResultParseText(patternText, Pattern[+UnicodeMode, +UnicodeSetsMode, +NamedCaptureGroups])로 둔다.
  3. Else if utrue이면, 다음을 수행한다.
    1. parseResultParseText(patternText, Pattern[+UnicodeMode, ~UnicodeSetsMode, +NamedCaptureGroups])로 둔다.
  4. Else,
    1. parseResultParseText(patternText, Pattern[~UnicodeMode, ~UnicodeSetsMode, ~NamedCaptureGroups])로 둔다.
    2. parseResultParse Node이고 parseResultGroupName을 포함하면, 다음을 수행한다.
      1. parseResultParseText(patternText, Pattern[~UnicodeMode, ~UnicodeSetsMode, +NamedCaptureGroups])로 설정한다.
  5. parseResult를 반환한다.

B.2 추가 Built-in Properties

ECMAScript host가 web browser일 때 standard built-in objects의 다음 additional properties가 defined됩니다.

B.2.1 Global Object의 추가 Properties

Table 103의 entries가 Table 6에 added됩니다.

Table 103: 추가 Well-known Intrinsic Objects
Intrinsic Name Global Name ECMAScript Language Association
%escape% "escape" escape function (B.2.1.1)
%unescape% "unescape" unescape function (B.2.1.2)

B.2.1.1 escape ( string )

이 function은 global object의 property입니다. 특정 code units가 hexadecimal escape sequence로 replaced된 String value의 새 version을 computes합니다.

numeric value가 0x00FF 이하인 code unit을 replacing할 때는 %xx form의 two-digit escape sequence가 사용됩니다. numeric value가 0x00FF보다 strictly greater한 code unit을 replacing할 때는 %uxxxx form의 four-digit escape sequence가 사용됩니다.

이는 %escape% intrinsic object입니다.

called될 때 다음 steps를 수행합니다:

  1. string을 ? ToString(string)으로 설정한다.
  2. lengthstring의 length로 둔다.
  3. result를 empty String으로 둔다.
  4. unescapedSetASCII word characters"@*+-./"string-concatenation으로 둔다.
  5. k를 0으로 둔다.
  6. k < length인 동안 반복한다.
    1. codeUnitstring 내 index k에 있는 code unit으로 둔다.
    2. unescapedSetcodeUnit을 포함하면, 다음을 수행한다.
      1. nextPartcodeUnit으로 둔다.
    3. Else,
      1. codeUnitNumbercodeUnit의 numeric value로 둔다.
      2. codeUnitNumber < 256이면, 다음을 수행한다.
        1. hex를 uppercase hexadecimal number로 formatted된 codeUnitNumber의 String representation으로 둔다.
        2. nextPart"%"StringPad(hex, 2, "0", start)의 string-concatenation으로 둔다.
      3. Else,
        1. hex를 uppercase hexadecimal number로 formatted된 codeUnitNumber의 String representation으로 둔다.
        2. nextPart"%u"StringPad(hex, 4, "0", start)의 string-concatenation으로 둔다.
    4. resultresultnextPartstring-concatenation으로 설정한다.
    5. kk + 1로 설정한다.
  7. result를 반환한다.
Note

encoding은 RFC 1738에 described된 encoding에 부분적으로 based되지만, 이 standard에 specified된 전체 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의 새 version을 computes합니다.

이는 %unescape% intrinsic object입니다.

called될 때 다음 steps를 수행합니다:

  1. string을 ? ToString(string)으로 설정한다.
  2. lengthstring의 length로 둔다.
  3. result를 empty String으로 둔다.
  4. k를 0으로 둔다.
  5. k < length인 동안 반복한다.
    1. codeUnitstring 내 index k에 있는 code unit으로 둔다.
    2. codeUnit이 code unit 0x0025 (PERCENT SIGN)이면, 다음을 수행한다.
      1. hexDigits를 empty String으로 둔다.
      2. optionalAdvance를 0으로 둔다.
      3. k + 5 < length이고 string 내 index k + 1에 있는 code unit이 code unit 0x0075 (LATIN SMALL LETTER U)이면, 다음을 수행한다.
        1. hexDigitsstringsubstring from k + 2 to k + 6으로 설정한다.
        2. optionalAdvance를 5로 설정한다.
      4. Else if k + 3 ≤ length이면, 다음을 수행한다.
        1. hexDigitsstringsubstring from k + 1 to k + 3으로 설정한다.
        2. optionalAdvance를 2로 설정한다.
      5. parseResultParseText(hexDigits, HexDigits[~Sep])로 둔다.
      6. parseResultParse Node이면, 다음을 수행한다.
        1. codeUnitNumberparseResult의 MV로 둔다.
        2. codeUnit을 numeric value가 codeUnitNumber인 code unit으로 설정한다.
        3. kk + optionalAdvance로 설정한다.
    3. resultresultcodeUnitstring-concatenation으로 설정한다.
    4. kk + 1로 설정한다.
  6. result를 반환한다.

B.2.2 String.prototype Object의 추가 Properties

B.2.2.1 String.prototype.substr ( start, length )

이 method는 this value를 String으로 converting한 결과의 substring을 반환하며, index start에서 시작하여 length code units만큼 이어집니다(lengthundefined이면 String의 end까지). start가 negative이면, sourceLength가 String의 length일 때 sourceLength + start로 treated됩니다. 결과는 String object가 아니라 String value입니다.

called될 때 다음 steps를 수행합니다:

  1. objthis value로 둔다.
  2. RequireObjectCoercible(obj)를 수행한다.
  3. string을 ? ToString(obj)로 둔다.
  4. sizestring의 length로 둔다.
  5. intStart를 ? ToIntegerOrInfinity(start)로 둔다.
  6. intStart = -∞이면, intStart를 0으로 설정한다.
  7. Else if intStart < 0이면, intStartmax(size + intStart, 0)으로 설정한다.
  8. Else, intStartmin(intStart, size)로 설정한다.
  9. lengthundefined이면 intLengthsize로 둔다; 그렇지 않으면 intLength를 ? ToIntegerOrInfinity(length)로 둔다.
  10. intLength를 0과 size 사이로 clamping한 result로 설정한다.
  11. intEndmin(intStart + intLength, size)로 둔다.
  12. stringsubstring from intStart to intEnd를 반환한다.
Note

이 method는 intentionally generic합니다; this value가 String object일 것을 require하지 않습니다. 따라서 method로 사용하기 위해 다른 kinds of objects로 transferred될 수 있습니다.

B.2.2.2 String.prototype.anchor ( name )

이 method는 called될 때 다음 steps를 수행합니다:

  1. stringthis value로 둔다.
  2. CreateHTML(string, "a", "name", name)를 반환한다.

B.2.2.2.1 CreateHTML ( contents, tag, attr, attrValue )

The abstract operation CreateHTML takes arguments contents (an ECMAScript language value), tag (a String), attr (a String), and attrValue (an ECMAScript language value) and returns either a normal completion containing a String or a throw completion. It performs the following steps when called:

  1. RequireObjectCoercible(contents)를 수행한다.
  2. contentsString을 ? ToString(contents)으로 둔다.
  3. part1"<"tagstring-concatenation으로 둔다.
  4. attr이 empty String이 아니면, 다음을 수행한다.
    1. attrValueString을 ? ToString(attrValue)로 둔다.
    2. escapedAttrValueattrValueString과 같지만 attrValueString 내 code unit 0x0022 (QUOTATION MARK)의 각 occurrence가 six code unit sequence "&quot;"로 replaced된 String value로 둔다.
    3. part1을 다음의 string-concatenation으로 설정한다:
      • part1
      • code unit 0x0020 (SPACE)
      • attr
      • code unit 0x003D (EQUALS SIGN)
      • code unit 0x0022 (QUOTATION MARK)
      • escapedAttrValue
      • code unit 0x0022 (QUOTATION MARK)
  5. part2part1">"string-concatenation으로 둔다.
  6. part3part2contentsStringstring-concatenation으로 둔다.
  7. part4part3, "</", tag, 및 ">"string-concatenation으로 둔다.
  8. part4를 반환한다.

B.2.2.3 String.prototype.big ( )

이 method는 called될 때 다음 steps를 수행합니다:

  1. stringthis value로 둔다.
  2. CreateHTML(string, "big", "", "")를 반환한다.

B.2.2.4 String.prototype.blink ( )

이 method는 called될 때 다음 steps를 수행합니다:

  1. stringthis value로 둔다.
  2. CreateHTML(string, "blink", "", "")를 반환한다.

B.2.2.5 String.prototype.bold ( )

이 method는 called될 때 다음 steps를 수행합니다:

  1. stringthis value로 둔다.
  2. CreateHTML(string, "b", "", "")를 반환한다.

B.2.2.6 String.prototype.fixed ( )

이 method는 called될 때 다음 steps를 수행합니다:

  1. stringthis value로 둔다.
  2. CreateHTML(string, "tt", "", "")를 반환한다.

B.2.2.7 String.prototype.fontcolor ( colour )

이 method는 called될 때 다음 steps를 수행합니다:

  1. stringthis value로 둔다.
  2. CreateHTML(string, "font", "color", colour)를 반환한다.

B.2.2.8 String.prototype.fontsize ( size )

이 method는 called될 때 다음 steps를 수행합니다:

  1. stringthis value로 둔다.
  2. CreateHTML(string, "font", "size", size)를 반환한다.

B.2.2.9 String.prototype.italics ( )

이 method는 called될 때 다음 steps를 수행합니다:

  1. stringthis value로 둔다.
  2. CreateHTML(string, "i", "", "")를 반환한다.

B.2.2.10 String.prototype.link ( url )

이 method는 called될 때 다음 steps를 수행합니다:

  1. stringthis value로 둔다.
  2. CreateHTML(string, "a", "href", url)를 반환한다.

B.2.2.11 String.prototype.small ( )

이 method는 called될 때 다음 steps를 수행합니다:

  1. stringthis value로 둔다.
  2. CreateHTML(string, "small", "", "")를 반환한다.

B.2.2.12 String.prototype.strike ( )

이 method는 called될 때 다음 steps를 수행합니다:

  1. stringthis value로 둔다.
  2. CreateHTML(string, "strike", "", "")를 반환한다.

B.2.2.13 String.prototype.sub ( )

이 method는 called될 때 다음 steps를 수행합니다:

  1. stringthis value로 둔다.
  2. CreateHTML(string, "sub", "", "")를 반환한다.

B.2.2.14 String.prototype.sup ( )

이 method는 called될 때 다음 steps를 수행합니다:

  1. stringthis value로 둔다.
  2. CreateHTML(string, "sup", "", "")를 반환한다.

B.2.2.15 String.prototype.trimLeft ( )

Note

property "trimStart"가 preferred됩니다. "trimLeft" property는 principally 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

property "trimEnd"가 preferred됩니다. "trimRight" property는 principally 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하기 때문에 거의 모든 purposes에서 preferred됩니다.

이 method는 called될 때 다음 steps를 수행합니다:

  1. dateObjthis value로 둔다.
  2. RequireInternalSlot(dateObj, [[DateValue]])를 수행한다.
  3. tvdateObj.[[DateValue]]로 둔다.
  4. tvNaN이면, NaN을 반환한다.
  5. YearFromTime(LocalTime(tv)) - 1900𝔽을 반환한다.

B.2.3.2 Date.prototype.setYear ( year )

Note

setFullYear method는 “year 2000 problem”을 avoid하기 때문에 거의 모든 purposes에서 preferred됩니다.

이 method는 called될 때 다음 steps를 수행합니다:

  1. dateObjthis value로 둔다.
  2. RequireInternalSlot(dateObj, [[DateValue]])를 수행한다.
  3. timedateObj.[[DateValue]]로 둔다.
  4. year를 ? ToNumber(year)로 둔다.
  5. timeNaN이면 time+0𝔽으로 설정한다; 그렇지 않으면 timeLocalTime(time)으로 설정한다.
  6. fullYearMakeFullYear(year)로 둔다.
  7. dayMakeDay(fullYear, MonthFromTime(time), DateFromTime(time))로 둔다.
  8. dateMakeDate(day, TimeWithinDay(time))로 둔다.
  9. utcTimestampTimeClip(UTC(date))로 둔다.
  10. dateObj.[[DateValue]]utcTimestamp로 설정한다.
  11. utcTimestamp를 반환한다.

B.2.3.3 Date.prototype.toGMTString ( )

Note

toUTCString method가 preferred됩니다. 이 method는 principally 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는 called될 때 다음 steps를 수행합니다:

  1. objthis value로 둔다.
  2. RequireInternalSlot(obj, [[RegExpMatcher]])를 수행한다.
  3. pattern이 Object이고 pattern[[RegExpMatcher]] internal slot을 가지면, 다음을 수행한다.
    1. flagsundefined가 아니면, TypeError exception을 throw한다.
    2. flagspattern.[[OriginalFlags]]로 설정한다.
    3. patternpattern.[[OriginalSource]]로 설정한다.
  4. RegExpInitialize(obj, pattern, flags)를 반환한다.
Note

이 method는 this value RegExp를 새로운 pattern과 flags로 완전히 reinitializes합니다. implementation은 이 method의 use를 resulting RegExp object가 multiple times 사용될 것이며 따라서 extra optimization의 candidate라는 assertion으로 interpret할 수 있습니다.

B.3 기타 추가 기능

B.3.1 Labelled Function Declarations

ECMAScript 2015 이전에는 LabelledStatement의 specification이 statement label과 FunctionDeclaration의 association을 allow하지 않았습니다. 그러나 labelled FunctionDeclarationnon-strict code에 대한 allowable extension이었고 대부분의 browser-hosted ECMAScript implementations가 그 extension을 supported했습니다. ECMAScript 2015 이후에는 LabelledStatement에 대한 grammar production이 FunctionDeclarationLabelledItem으로 사용하는 것을 permits하지만, 14.13.1에는 그것이 발생하면 Syntax Error를 producing하는 Early Error rule이 포함됩니다. 그런 다음 host가 이 feature를 support하는 경우 non-strict code에서 Syntax Error를 suppress하도록 그 rule이 modified됩니다.

Note

WithStatement, IfStatement, 및 IterationStatement에 대한 early error rules는 이러한 statements가 non-strict code에서 labelled FunctionDeclaration을 containing하는 것을 prevent합니다.

B.3.2 Block-Level Function Declarations Web Legacy Compatibility Semantics

ECMAScript 2015 이전에는 ECMAScript specification이 Block statement의 StatementList의 element로서 FunctionDeclaration의 occurrence를 define하지 않았습니다. 그러나 그러한 form의 FunctionDeclaration에 대한 support는 allowable extension이었고 대부분의 browser-hosted ECMAScript implementations가 이를 permitted했습니다. 불행히도 그러한 declarations의 semantics는 implementations마다 다릅니다. 이러한 semantic differences 때문에 Block level function declarations를 사용하는 기존 web ECMAScript source text는 그 usage가 그러한 declarations에 대한 모든 browser implementations의 semantic intersection에만 depends하는 경우에만 browser implementations 간에 portable합니다. 다음은 그 intersection semantics에 속하는 use cases입니다:

  1. function이 declared되고 single block 내에서만 referenced됩니다.

    • BindingIdentifier가 이름 f인 하나 이상의 FunctionDeclarations가 enclosing function g의 function code 내에서 occur하고 그 declaration은 Block 내에 nested됩니다.
    • var declaration이 아닌 f의 다른 declaration은 g의 function code 내에서 occur하지 않습니다.
    • IdentifierReference로서의 f의 모든 occurrences는 f의 declaration을 containing하는 BlockStatementList 내에 있습니다.
  2. function이 single Block 내에서 declared되고 possibly used되지만, 동일한 Block 내에 contained되지 않은 inner function definition에 의해 also referenced됩니다.

    • BindingIdentifier가 이름 f인 하나 이상의 FunctionDeclarations가 enclosing function g의 function code 내에서 occur하고 그 declaration은 Block 내에 nested됩니다.
    • var declaration이 아닌 f의 다른 declaration은 g의 function code 내에서 occur하지 않습니다.
    • f의 declaration을 containing하는 BlockStatementList 내에 IdentifierReference로서 f의 occurrences가 있을 수 있습니다.
    • g 내에 nested된 또 다른 function h 내에 IdentifierReference로서 f의 occurrence가 적어도 하나 있으며, h 내에서 f에 대한 references를 shadow하는 f의 다른 declaration은 없습니다.
    • h의 모든 invocations는 f의 declaration이 evaluated된 후 occur합니다.
  3. function이 single block 내에서 declared되고 possibly used되지만, subsequent blocks 내에서도 referenced됩니다.

    • BindingIdentifier가 이름 f인 하나 이상의 FunctionDeclaration이 enclosing function g의 function code 내에서 occur하고 그 declaration은 Block 내에 nested됩니다.
    • var declaration이 아닌 f의 다른 declaration은 g의 function code 내에서 occur하지 않습니다.
    • f의 declaration을 containing하는 BlockStatementList 내에 IdentifierReference로서 f의 occurrences가 있을 수 있습니다.
    • f의 declaration을 containing하는 Block을 lexically follows하는 g의 function code 내에 IdentifierReference로서 f의 occurrence가 적어도 하나 있습니다.

첫 번째 use case는 ECMAScript 2015가 provided하는 Block level function declarations의 semantics와 interoperable합니다. 그 use case를 employing하는 pre-existing ECMAScript source text는 clauses 10, 14, 및 15에 의해 defined된 Block level function declarations semantics를 사용하여 operate할 것입니다.

두 번째 및 세 번째 use cases에 대한 ECMAScript 2015 interoperability는 clause 10, clause 15, clause 19.2.1 및 clause 16.1.7 semantics에 대한 다음 extensions를 requires합니다.

ECMAScript implementation이 diagnostic warning messages를 reporting하는 mechanism을 가지고 있으면, code가 이러한 compatibility semantics가 applied되고 non-compatibility semantics와 observable differences를 introduce하는 FunctionDeclaration을 contains할 때 warning이 produced되어야 합니다. 예를 들어 var binding이 early error를 create하기 때문에 introduced되지 않는 경우 warning message는 produced되지 않아야 합니다.

이 feature는 다음 points에서 special semantics를 involves합니다:

B.3.3 IfStatement Statement Clauses 안의 FunctionDeclarations

다음은 14.6IfStatement 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의 BlockCatchParameter에 의해 also bound되는 name을 bind하는 var declarations를 contain할 수 있습니다. 이는 14.15.1 Catch : catch ( CatchParameter ) Block 에 대한 early error rule을 modifying함으로써 accomplished됩니다.

Note

At runtime, 그러한 bindings는 VariableDeclarationEnvironment에서 instantiated됩니다. 그것들은 CatchParameter에 의해 introduced된 same-named bindings를 shadow하지 않으므로, 그러한 var declarations에 대한 Initializervar binding이 아니라 corresponding catch parameter에 assign됩니다.

이 modified behaviour는 Catch clause의 Block 내에 contained된 direct eval calls에 의해 introduced되는 varfunction declarations에도 applies됩니다. 이 change는 EvalDeclarationInstantiation의 steps 3.d.i.2.a.i13.b.ii.4.a.i.i를 modifying함으로써 accomplished됩니다.

B.3.5 ForIn Statement Heads 안의 Initializers

다음은 14.7.5ForInOfStatement 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.1ContainsDuplicateLabels static semantics는 다음으로 augmented됩니다:

ForInOfStatement : for ( var BindingIdentifier Initializer in Expression ) Statement
  1. argument labelSet를 사용한 StatementContainsDuplicateLabels를 반환한다.

8.3.2ContainsUndefinedBreakTarget static semantics는 다음으로 augmented됩니다:

ForInOfStatement : for ( var BindingIdentifier Initializer in Expression ) Statement
  1. argument labelSet를 사용한 StatementContainsUndefinedBreakTarget을 반환한다.

8.3.3ContainsUndefinedContinueTarget static semantics는 다음으로 augmented됩니다:

ForInOfStatement : for ( var BindingIdentifier Initializer in Expression ) Statement
  1. arguments iterationSet 및 « »를 사용한 StatementContainsUndefinedContinueTarget을 반환한다.

14.7.5.2IsDestructuring static semantics는 다음으로 augmented됩니다:

BindingIdentifier : Identifier yield await
  1. false를 반환한다.

8.2.8VarDeclaredNames static semantics는 다음으로 augmented됩니다:

ForInOfStatement : for ( var BindingIdentifier Initializer in Expression ) Statement
  1. names1BindingIdentifierBoundNames로 둔다.
  2. names2StatementVarDeclaredNames로 둔다.
  3. names1names2list-concatenation을 반환한다.

8.2.9VarScopedDeclarations static semantics는 다음으로 augmented됩니다:

ForInOfStatement : for ( var BindingIdentifier Initializer in Expression ) Statement
  1. decls1을 « BindingIdentifier »로 둔다.
  2. decls2StatementVarScopedDeclarations로 둔다.
  3. decls1decls2list-concatenation을 반환한다.

14.7.5.5ForInOfLoopEvaluation runtime semantics는 다음으로 augmented됩니다:

ForInOfStatement : for ( var BindingIdentifier Initializer in Expression ) Statement
  1. bindingIdBindingIdentifierStringValue로 둔다.
  2. lhs를 ? ResolveBinding(bindingId)로 둔다.
  3. IsAnonymousFunctionDefinition(Initializer)가 true이면, 다음을 수행한다.
    1. value를 argument bindingId를 사용한 InitializerNamedEvaluation으로 둔다.
  4. Else,
    1. rhs를 ? Evaluation of Initializer로 둔다.
    2. value를 ? GetValue(rhs)로 둔다.
  5. PutValue(lhs, value)를 수행한다.
  6. keyResult를 ? ForIn/OfHeadEvaluation(« », Expression, enumerate)로 둔다.
  7. ForIn/OfBodyEvaluation(BindingIdentifier, Statement, keyResult, enumerate, var-binding, labelSet)를 반환한다.

B.3.6 [[IsHTMLDDA]] Internal Slot

[[IsHTMLDDA]] internal slothost-defined objects에 존재할 수 있습니다. [[IsHTMLDDA]] internal slot을 가진 objects는 ToBooleanIsLooselyEqual 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을 제외하고 이를 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를 producing하는 대신 assignment의 evaluation 중에 ReferenceError exception이 thrown됩니다.

Note

assignment target이 AssignmentExpressionLeftHandSideExpression인 경우, assignment operator는 = 또는 AssignmentOperator여야 합니다. 특히 여기의 allowance는 logical assignment operators (??=, &&=, ||=)에는 apply되지 않습니다.

CallExpression : CoverCallExpressionAndAsyncArrowHead CallExpression : CallExpression Arguments 에 대한 AssignmentTargetType의 step 1을 참조하세요.

Annex C (informative) ECMAScript의 Strict Mode

strict mode restriction과 exceptions

Annex D (informative) Host Layering Points

host의 definition은 4.2를 참조하세요.

D.1 Host Hooks

HostCallJobCallback(...)

HostEnqueueFinalizationRegistryCleanupJob(...)

HostEnqueueGenericJob(...)

HostEnqueuePromiseJob(...)

HostEnqueueTimeoutJob(...)

HostEnsureCanCompileStrings(...)

HostFinalizeImportMeta(...)

HostGetImportMetaProperties(...)

HostGrowSharedArrayBuffer(...)

HostHasSourceTextAvailable(...)

HostLoadImportedModule(...)

HostGetSupportedImportAttributes(...)

HostMakeJobCallback(...)

HostPromiseRejectionTracker(...)

HostResizeArrayBuffer(...)

InitializeHostDefinedRealm(...)

D.2 Host-defined Fields

Realm Records[[HostDefined]]: Table 20 참조.

Script Records[[HostDefined]]: Table 35 참조.

Module Records[[HostDefined]]: Table 39 참조.

JobCallback Records[[HostDefined]]: Table 24 참조.

[[IsHTMLDDA]]: B.3.6 참조.

D.3 Host-defined Objects

global object: clause 19 참조.

D.4 Running Jobs

Job Abstract Closures의 invocation 전 preparation steps와 invocation 후 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) Possible Compatibility Impact가 있는 ECMAScript 2015의 Corrections and Clarifications

9.1.1.4.14-9.1.1.4.17 Edition 5 및 5.1은 new global declaration에 corresponding하는 global object property가 already existed하는지를 determine하기 위해 property existence test를 사용했습니다. ECMAScript 2015는 own property existence test를 사용합니다. 이는 web browsers에서 가장 commonly implemented된 것과 corresponds합니다.

10.4.2.1: 5th Edition은 array index 또는 new length value의 integer conversion보다 current array length의 capture를 prior로 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𝔽를 반환하는 것을 permitted했습니다. ECMAScript 2015는 +0𝔽가 always returned된다고 specifies합니다. 이는 ECMAScript 2015에서 Date의 time value가 never observably -0𝔽이고 time values를 반환하는 methods가 never -0𝔽를 반환하지 않음을 의미합니다.

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: year가 21.4.1.32에 specified된 Date Time String Format을 사용해 represented될 수 없으면 RangeError exception이 thrown됩니다. Previous editions는 그 case에 대한 behaviour를 specify하지 않았습니다.

21.4.4.41: Previous editions는 time valueNaN일 때 Date.prototype.toString이 returned하는 value를 specify하지 않았습니다. ECMAScript 2015는 result를 String value "Invalid Date"로 specifies합니다.

22.2.4.1, 22.2.6.13.1: RegExp instance의 "source" property의 value 내 모든 LineTerminator code points는 escape sequence를 사용하여 expressed되어야 합니다. Edition 5.1은 /의 escaping만 required했습니다.

22.2.6.8, 22.2.6.11: previous editions에서 String.prototype.matchString.prototype.replace에 대한 specifications는 pattern argument가 global flag가 set된 RegExp value인 cases에 대해 incorrect했습니다. previous specifications는 pattern을 match하려는 각 attempt에서 lastIndex가 change하지 않으면 1만큼 increment되어야 한다고 stated했습니다. correct behaviour는 pattern이 empty String을 matched한 경우에만 lastIndex가 1만큼 increment되어야 한다는 것입니다.

23.1.3.30: Previous editions는 comparator가 returned한 NaN value가 Array.prototype.sort에 의해 어떻게 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) Prior 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는 이제 BinaryIntegerLiteralOctalIntegerLiteral 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됩니다. 특히 이는 ECMAScript 2015에서 Space_Separator (Zs) category에 있어 whitespace로 treated되었던 U+180E MONGOLIAN VOWEL SEPARATOR가 Unicode 6.3.0부터 Format (Cf) category로 moved되도록 했습니다. 이는 whitespace-sensitive methods가 differently behave하게 합니다. 예를 들어, "\u180E".trim().length는 previous editions에서는 0이었지만 ECMAScript 2016 이후에는 1입니다. Additionally, 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에서 Automatic Semicolon Insertion은 do-while statement의 semicolon이 missing이면 그 end에 semicolon을 adds합니다. 이 change는 specification을 대부분의 existing implementations의 actual behaviour와 aligns합니다.

13.2.5.1: ECMAScript 2015에서 Object Initializers에 duplicate property names가 있는 것은 더 이상 early error가 아닙니다.

13.15.1: ECMAScript 2015에서 FunctionExpression의 function name과 같은 immutable binding에 대한 assignment를 containing하는 strict mode codeearly error를 produce하지 않습니다. 대신 runtime error를 produces합니다.

14.2: ECMAScript 2015에서 token let 다음에 input elements LineTerminator, then Identifier가 followed되는 StatementListLexicalDeclaration의 start입니다. previous editions에서는 automatic semicolon insertion이 always Identifier input element 앞에 semicolon을 insert했을 것입니다.

14.5: ECMAScript 2015에서 token let 다음에 token [가 followed되는 StatementListItemLexicalDeclaration의 start입니다. previous editions에서 그러한 sequence는 ExpressionStatement의 start였을 것입니다.

14.6.2: ECMAScript 2015에서 IfStatement의 normal result는 never value empty입니다. Statement part가 evaluated되지 않았거나 evaluated된 Statement part가 empty를 containing하는 normal completion을 produces하면, IfStatement의 result는 undefined입니다.

14.7: ECMAScript 2015에서 for statement의 ( token이 immediately token sequence let [로 followed되면 letLexicalDeclaration의 start로 treated됩니다. previous editions에서 그러한 token sequence는 Expression의 start였을 것입니다.

14.7: ECMAScript 2015에서 for-in statement의 ( token이 immediately token sequence let [로 followed되면 letForDeclaration의 start로 treated됩니다. previous editions에서 그러한 token sequence는 LeftHandSideExpression의 start였을 것입니다.

14.7: ECMAScript 2015 이전에는 initialization expression이 in keyword를 precedes하는 VariableDeclaration의 일부로 appear할 수 있었습니다. ECMAScript 2015에서 같은 position의 ForBinding은 그러한 initializer의 occurrence를 allow하지 않습니다. ECMAScript 2017에서는 그러한 initializer가 non-strict code에서만 permitted됩니다.

14.7: ECMAScript 2015에서 IterationStatement를 evaluating한 result는 never [[Value]]emptynormal completion입니다. IterationStatementStatement part가 evaluated되지 않았거나 Statement part의 final evaluation이 [[Value]]emptynormal completion을 produces하면, IterationStatement를 evaluating한 result는 [[Value]]undefinednormal completion입니다.

14.11.2: ECMAScript 2015에서 WithStatement를 evaluating한 result는 never [[Value]]emptynormal completion입니다. WithStatementStatement part의 evaluation이 [[Value]]emptynormal completion을 produces하면, WithStatement를 evaluating한 result는 [[Value]]undefinednormal completion입니다.

14.12.4: ECMAScript 2015에서 SwitchStatement를 evaluating한 result는 never [[Value]]emptynormal completion입니다. SwitchStatementCaseBlock part의 evaluation이 [[Value]]emptynormal completion을 produces하면, SwitchStatement를 evaluating한 result는 [[Value]]undefinednormal completion입니다.

14.15: ECMAScript 2015에서 Catch clause가 Catch clause parameter로 appears하는 동일한 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가 Catch clause parameter로 appears하는 동일한 Identifier를 binds하는 var 또는 FunctionDeclaration declaration을 포함하는 eval code를 가진 non-strict direct eval을 evaluates하면 runtime SyntaxError가 thrown됩니다.

14.15.3: ECMAScript 2015에서 TryStatement의 result는 never value empty입니다. TryStatementBlock part가 empty를 containing하는 normal completion으로 evaluates되면 TryStatement의 result는 undefined입니다. TryStatementBlock part가 throw completion으로 evaluates되고, normal completion containing empty로 evaluates되는 Catch part를 가지며, Finally clause가 없거나 its Finally clause가 empty normal completion으로 evaluates되면 TryStatement의 result는 undefined입니다.

15.4.5 ECMAScript 2015에서 ObjectLiteral 안의 accessor properties[[Get]] 또는 [[Set]] attribute의 values로 created되는 function objectsconstructor functions가 아니며 "prototype" own property를 가지지 않습니다. previous edition에서는 이들이 constructors였고 "prototype" property를 가졌습니다.

20.1.2.6: ECMAScript 2015에서 Object.freeze의 argument가 object가 아니면 own properties가 없는 non-extensible ordinary object인 것처럼 treated됩니다. previous edition에서는 non-object argument가 always TypeError를 thrown하게 했습니다.

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가 always TypeError를 thrown하게 했습니다.

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가 always TypeError를 thrown하게 했습니다.

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가 always TypeError를 thrown하게 했습니다.

20.1.2.16: ECMAScript 2015에서 Object.isExtensible의 argument가 object가 아니면 own properties가 없는 non-extensible ordinary object인 것처럼 treated됩니다. previous edition에서는 non-object argument가 always TypeError를 thrown하게 했습니다.

20.1.2.17: ECMAScript 2015에서 Object.isFrozen의 argument가 object가 아니면 own properties가 없는 non-extensible ordinary object인 것처럼 treated됩니다. previous edition에서는 non-object argument가 always TypeError를 thrown하게 했습니다.

20.1.2.18: ECMAScript 2015에서 Object.isSealed의 argument가 object가 아니면 own properties가 없는 non-extensible ordinary object인 것처럼 treated됩니다. previous edition에서는 non-object argument가 always TypeError를 thrown하게 했습니다.

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가 always TypeError를 thrown하게 했습니다.

20.1.2.20: ECMAScript 2015에서 Object.preventExtensions의 argument가 object가 아니면 own properties가 없는 non-extensible ordinary object인 것처럼 treated됩니다. previous edition에서는 non-object argument가 always TypeError를 thrown하게 했습니다.

20.1.2.22: ECMAScript 2015에서 Object.seal의 argument가 object가 아니면 own properties가 없는 non-extensible ordinary object인 것처럼 treated됩니다. previous edition에서는 non-object argument가 always TypeError를 thrown하게 했습니다.

20.2.3.2: ECMAScript 2015에서 bound function의 [[Prototype]] internal slot은 target function의 [[GetPrototypeOf]] value로 set됩니다. previous edition에서 [[Prototype]]은 always %Function.prototype%으로 set되었습니다.

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을 사용할 수 있었습니다.

22.1.3.2822.1.3.30 ECMAScript 2015에서 lowercase/upper conversion processing은 code points에 대해 operates합니다. previous editions에서는 such conversion processing이 individual code units에만 applied되었습니다. affected되는 유일한 code points는 Unicode의 Deseret block에 있는 것들입니다.

22.1.3.32 ECMAScript 2015에서 String.prototype.trim method는 Unicode BMP 밖에 존재할 수 있는 white space code points를 recognize하도록 defined됩니다. 그러나 Unicode 7 기준으로 그러한 code points는 defined되어 있지 않습니다. previous editions에서는 그러한 code points가 white space로 recognized되지 않았을 것입니다.

22.2.4.1 ECMAScript 2015에서 pattern argument가 RegExp instance이고 flags argument가 undefined가 아니면, pattern과 같지만 pattern의 flags가 argument flags로 replaced된 new RegExp instance가 created됩니다. previous editions에서는 pattern이 RegExp instance이고 flagsundefined가 아니면 TypeError exception이 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.wakeAtomics.wait와의 confusion을 prevent하기 위해 Atomics.notify로 renamed되었습니다.

27.1.5.4, 27.9.3.6: ECMAScript 2019에서 await에 의해 enqueued되는 Jobs의 수가 reduced되었으며, 이는 then() call과 await expression 사이의 resolution order에 observable difference를 create할 수 있었습니다.

Bibliography

  1. IEEE 754-2019: IEEE Standard for Floating-Point Arithmetic. Institute of Electrical and Electronic Engineers, New York (2019) Note

    ECMA-262 specification에 affect하는 IEEE 754-2008과 IEEE 754-2019 사이의 normative changes는 없습니다.

  2. The Unicode Standard, available at <https://unicode.org/versions/latest>
  3. Unicode Technical Note #5: Canonical Equivalence in Applications, available at <https://unicode.org/notes/tn5/>
  4. Unicode Technical Standard #10: Unicode Collation Algorithm, available at <https://unicode.org/reports/tr10/>
  5. Unicode Standard Annex #15, Unicode Normalization Forms, available at <https://unicode.org/reports/tr15/>
  6. Unicode Standard Annex #18: Unicode Regular Expressions, available at <https://unicode.org/reports/tr18/>
  7. Unicode Standard Annex #24: Unicode Script Property, available at <https://unicode.org/reports/tr24/>
  8. Unicode Standard Annex #31, Unicode Identifiers and Pattern Syntax, available at <https://unicode.org/reports/tr31/>
  9. Unicode Standard Annex #44: Unicode Character Database, available at <https://unicode.org/reports/tr44/>
  10. Unicode Technical Standard #51: Unicode Emoji, available at <https://unicode.org/reports/tr51/>
  11. IANA Time Zone Database, available at <https://www.iana.org/time-zones>
  12. ISO 8601:2004(E) Data elements and interchange formats — Information interchange — Representation of dates and times
  13. RFC 1738 “Uniform Resource Locators (URL)”, available at <https://tools.ietf.org/html/rfc1738>
  14. RFC 2396 “Uniform Resource Identifiers (URI): Generic Syntax”, available at <https://tools.ietf.org/html/rfc2396>
  15. RFC 3629 “UTF-8, a transformation format of ISO 10646”, available at <https://tools.ietf.org/html/rfc3629>
  16. RFC 7231 “Hypertext Transfer Protocol (HTTP/1.1): Semantics and Content”, available at <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 및 Markdown dialect입니다. Ecmarkup은 syntax를 defining하기 위한 Grammarkdown 및 algorithm steps를 authoring하기 위한 Ecmarkdown을 포함한 여러 다른 formats와 technologies를 builds on하고 integrates합니다. 이 specification의 PDF renderings는 CSS Paged Media specification을 활용하는 print stylesheet를 사용하여 produced되며 PrinceXML을 사용해 converted됩니다.

이 specification의 prior editions는 Word를 사용하여 authored되었습니다. 이 edition의 basis를 formed한 Ecmarkup source text는 automated conversion tool을 사용하여 ECMAScript 2015 Word document를 Ecmarkup으로 converting하여 produced되었습니다.

Copyright & Software License

Ecma International

Rue du Rhone 114

CH-1204 Geneva

Tel: +41 22 849 6000

Fax: +41 22 849 6001

Web: https://ecma-international.org/

Software License

All Software contained in this document ("Software") is protected by copyright and is being made available under the "BSD License", included below. This Software may be subject to third party rights (rights from parties other than Ecma International), including patent rights, and no licenses under such third party rights are granted under this license even if the third party concerned is a member of Ecma International. SEE THE ECMA CODE OF CONDUCT IN PATENT MATTERS AVAILABLE AT https://ecma-international.org/memento/codeofconduct.htm FOR INFORMATION REGARDING THE LICENSING OF PATENT CLAIMS THAT ARE REQUIRED TO IMPLEMENT ECMA INTERNATIONAL STANDARDS.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

  1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
  2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
  3. Neither the name of the authors nor Ecma International may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE ECMA INTERNATIONAL "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL ECMA INTERNATIONAL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.