Draft ECMA-262 / September 16, 2025

ECMAScript® 2026 언어 명세서

이 명세서에 대하여

https://tc39.es/ecma262/에 있는 문서는 가장 정확하고 최신의 ECMAScript 명세서입니다. 이 문서에는 가장 최근 연간 스냅샷의 내용과, 그 스냅샷 이후의 완료된 제안(제안 절차에서 Stage 4에 도달하여 여러 구현에 적용되었고 다음 실질적인 개정에 포함될 제안)이 함께 담겨 있습니다.

이 문서는 단일 페이지여러 페이지로 제공됩니다.

이 명세서에 기여하기

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

이 문서가 어떻게 작성되는지 더 자세한 내용은 colophon을 참고하세요.

소개

이 Ecma 표준은 ECMAScript 2026 언어를 정의합니다. 이는 ECMAScript 언어 명세서의 열일곱 번째 판입니다. 1997년 첫 판이 발표된 이후 ECMAScript는 세계에서 가장 널리 사용되는 범용 프로그래밍 언어 중 하나로 성장했습니다. 웹 브라우저에 내장된 언어로 가장 잘 알려져 있지만, 서버 및 임베디드 애플리케이션에서도 널리 채택되었습니다.

ECMAScript는 여러 기술에서 유래했으며, 그 중 가장 잘 알려진 것은 JavaScript(Netscape)와 JScript(Microsoft)입니다. 이 언어는 Netscape의 Brendan Eich가 발명하였으며, 최초로 해당 회사의 Navigator 2.0 브라우저에 등장했습니다. 이후 Netscape의 모든 브라우저와 Microsoft의 Internet Explorer 3.0부터 모든 브라우저에 포함되었습니다.

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

그 Ecma 표준은 ISO/IEC JTC 1에 신속 채택 절차(fast-track procedure)를 통해 제출되었고, 1998년 4월 국제 표준 ISO/IEC 16262로 승인되었습니다. 1998년 6월 Ecma 총회에서 ECMA-262 두 번째 판이 승인되어 ISO/IEC 16262와 완전히 일치하게 되었습니다. 첫 번째 판과 두 번째 판의 변경 사항은 편집상의 변화입니다.

표준의 세 번째 판에서는 강력한 정규 표현식, 향상된 문자열 처리, 새로운 제어문, try/catch 예외 처리, 오류 정의 강화, 숫자 출력 형식 지정, 그리고 향후 언어 성장을 대비한 소규모 변경 사항이 도입되었습니다. ECMAScript 표준의 세 번째 판은 1999년 12월 Ecma 총회에서 채택되었고, 2002년 6월 ISO/IEC 16262:2002로 출판되었습니다.

세 번째 판이 출판된 이후 ECMAScript는 월드 와이드 웹과 결합되어 거의 모든 웹 브라우저에서 지원되는 프로그래밍 언어로 대규모로 채택되기에 이르렀습니다. ECMAScript의 네 번째 판 개발을 위한 많은 작업이 이루어졌지만 완전히 완료되지 않았고, ECMAScript의 네 번째 판으로 출판되지 않았습니다. 하지만 그 중 일부는 여섯 번째 판 개발에 통합되었습니다.

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

다섯 번째 판은 ISO/IEC JTC 1에 신속 채택 절차로 제출되어 국제 표준 ISO/IEC 16262:2011로 승인되었습니다. ECMAScript 표준의 5.1 판은 소규모 수정이 통합되었고, ISO/IEC 16262:2011과 동일한 텍스트입니다. 5.1 판은 2011년 6월 Ecma 총회에서 채택되었습니다.

여섯 번째 판의 집중적인 개발은 2009년에 시작되었으며, 다섯 번째 판이 출판 준비 중이던 시점입니다. 하지만 이는 1999년 세 번째 판 출판 이후 진행된 상당한 실험과 언어 개선 설계 노력에 선행되었습니다. 실제로 여섯 번째 판 완성은 15년의 노력의 결실이라 할 수 있습니다. 이 판의 목표에는 대규모 애플리케이션 지원 강화, 라이브러리 제작, 그리고 ECMAScript를 다른 언어의 컴파일 대상로 사용하는 데의 지원 강화가 포함되었습니다. 주요 개선 사항으로는 모듈, 클래스 선언, 렉시컬 블록 스코핑, 이터레이터와 제너레이터, 비동기 프로그래밍을 위한 프로미스, 구조 분해 패턴, proper tail call 등이 있습니다. ECMAScript 내장 라이브러리는 맵, 셋, 바이너리 숫자값 배열과 같은 추가 데이터 추상화를 지원하도록 확장되었고, 문자열과 정규 표현식에서 유니코드 보조 문자 지원이 강화되었습니다. 내장 객체는 서브클래싱을 통해 확장 가능해졌습니다. 여섯 번째 판은 정기적이고 점진적인 언어 및 라이브러리 개선의 기반을 제공합니다. 여섯 번째 판은 2015년 6월 총회에서 채택되었습니다.

ECMAScript 2016은 Ecma TC39의 새로운 연간 릴리스 주기 및 공개 개발 프로세스 하에 발표된 최초의 ECMAScript 판입니다. 평문 소스 문서가 ECMAScript 2015 소스 문서에서 구축되어 GitHub에서의 추가 개발의 기반이 되었습니다. 이 표준의 개발 기간 동안 수백 건의 풀 리퀘스트와 이슈가 제출되었으며, 이는 수천 건의 버그 수정, 편집적 수정, 기타 개선사항을 대표합니다. 또한 Ecmarkup, Ecmarkdown, Grammarkdown 등 개발을 지원하는 다양한 소프트웨어 도구가 개발되었습니다. ES2016에는 새로운 거듭제곱 연산자와 Array.prototypeincludes라는 새로운 메소드가 추가되었습니다.

ECMAScript 2017에서는 Async 함수, Shared Memory, Atomics가 도입되었고, 소규모 언어 및 라이브러리 개선, 버그 수정, 편집적 업데이트가 이루어졌습니다. Async 함수는 프로미스를 반환하는 함수에 대한 문법을 제공하여 비동기 프로그래밍 경험을 향상합니다. Shared Memory와 Atomics는 멀티 에이전트 프로그램이 병렬 CPU 환경에서도 잘 정의된 실행 순서를 보장하는 원자적 연산을 사용하여 통신할 수 있는 새로운 메모리 모델을 도입합니다. 또한 Object에 새로운 정적 메소드인 Object.values, Object.entries, Object.getOwnPropertyDescriptors가 추가되었습니다.

ECMAScript 2018에서는 async 이터레이터 프로토콜과 async 제너레이터를 통한 비동기 이터레이션 지원이 도입되었습니다. 또한 네 가지 새로운 정규 표현식 기능(dotAll 플래그, 명명된 캡처 그룹, 유니코드 속성 이스케이프, 후행 어설션)을 추가하였고, 객체의 rest 및 spread 속성도 포함되었습니다.

ECMAScript 2019에서는 몇 가지 새로운 내장 함수가 도입되었습니다: 배열 평탄화를 위한 Array.prototypeflatflatMap, Object.entries의 반환값을 바로 새 객체로 변환하는 Object.fromEntries, 더 적절한 이름의 String.prototype.trimStarttrimEnd(비표준 내장인 String.prototype.trimLefttrimRight의 대안). 또한 구문 및 의미론에 일부 소규모 업데이트가 있었습니다. 업데이트된 구문에는 catch 바인딩 매개변수 선택적 사용, JSON에 맞추어 문자열 리터럴에서 U+2028(줄 구분자) 및 U+2029(단락 구분자) 허용 등이 있습니다. 기타 업데이트로는 Array.prototype.sort의 안정 정렬 요구, JSON.stringify의 입력과 관계없이 올바른 UTF-8 반환 요구, Function.prototype.toString의 명확화(원본 소스 텍스트 또는 표준 플레이스홀더 반환 요구) 등이 있습니다.

ECMAScript 2020, 11에서는 문자열의 모든 매치 객체를 반복자로 반환하는 matchAll 메소드, 동적 지정자를 통해 모듈을 비동기적으로 import할 수 있는 import() 구문, 임의 정밀도의 정수 작업을 위한 새로운 숫자 원시 타입인 BigInt, 단락 회로 없이 동작하는 새로운 Promise 결합자인 Promise.allSettled, 전역 this 값을 보편적으로 접근하는 방법인 globalThis, 모듈 내에서 사용할 수 있는 export * as ns from 'module' 구문, for-in 열거 순서의 표준화 강화, 모듈 내에서 컨텍스트 정보를 담을 수 있는 호스트가 채워주는 객체인 import.meta, 그리고 nullish 값(undefined 또는 null)을 다루기 위한 두 가지 구문(nullish 병합 연산자와 옵셔널 체이닝)이 추가되었습니다.

ECMAScript 2021, 12에서는 문자열의 replaceAll 메소드, 입력 값이 이행될 때 단락 회로가 발생하는 Promise 결합자인 Promise.any, 여러 오류를 한 번에 표현하는 새로운 오류 타입인 AggregateError, 논리 할당 연산자(??=, &&=, ||=), 객체를 가비지 컬렉션에서 보호하지 않고 참조할 수 있는 WeakRef와 가비지 컬렉션 시 정리 작업 등록 및 해제를 관리하는 FinalizationRegistry, 숫자 리터럴 구분자(1_000), 그리고 Array.prototype.sort의 동작을 더 정확하게 하여 구현 정의 정렬 순서 발생을 줄였습니다.

ECMAScript 2022, 13에서는 모듈 최상위에서 await 키워드를 사용할 수 있게 되었고, 클래스 내에 새로운 요소(공개 및 비공개 인스턴스 필드, 공개 및 비공개 정적 필드, 비공개 인스턴스 메소드 및 접근자, 비공개 정적 메소드 및 접근자), 클래스 내부에서 평가 초기화를 위한 정적 블록, 객체의 비공개 필드 존재를 테스트하는 #x in obj 구문, 정규 표현식의 매치 인덱스를 제공하는 /d 플래그, 오류의 인과 관계를 기록하는 Error 객체의 cause 속성, 상대 인덱싱을 가능하게 하는 문자열/배열/TypedArrayat 메소드, 그리고 Object.hasOwn(기존 Object.prototype.hasOwnProperty의 간편 대안)이 도입되었습니다.

ECMAScript 2023, 14에서는 Array.prototypeTypedArray.prototypetoSorted, toReversed, with, findLast, findLastIndex 메소드, 그리고 Array.prototypetoSpliced 메소드가 도입되었습니다. 파일 시작 부분에 #! 주석을 허용하여 실행 가능한 ECMAScript 파일 지원이 강화되었고, 대부분의 Symbol을 weak collection의 키로 사용할 수 있게 되었습니다.

ECMAScript 2024, 15에서는 ArrayBuffer와 SharedArrayBuffer의 크기 조정 및 전송 기능, 문자열 집합 작업을 위한 고급 기능을 가진 RegExp /v 플래그, Promise를 쉽게 생성하기 위한 Promise.withResolvers 메소드, 데이터 집계용 Object.groupByMap.groupBy 메소드, 공유 메모리 변경을 비동기적으로 기다리는 Atomics.waitAsync 메소드, 문자열이 올바른 유니코드만 포함하는지 확인/보장하는 String.prototype.isWellFormedString.prototype.toWellFormed 메소드가 도입되었습니다.

ECMAScript 2025, 16에서는 이터레이터 작업을 위한 새로운 전역 Iterator와 관련 정적 및 프로토타입 메소드, Set.prototype의 셋 작업용 메소드, JSON 모듈 import 및 import된 모듈의 속성 선언 구문, 정규 표현식 안전 문자열 이스케이프를 위한 RegExp.escape 메소드, 정규 표현식 내에서 인라인 플래그 활성/비활성화 구문, 함수가 Promise를 반환하든 아니든 항상 Promise를 반환하게 하는 Promise.try 메소드, 새로운 TypedArray 종류인 Float16Array와 관련된 DataView.prototype.getFloat16, DataView.prototype.setFloat16, Math.f16round 메소드가 추가되었습니다.

Ecma TC39 내에서 많은 단체를 대표하는 수십 명의 개인이 이번 판뿐만 아니라 이전 판의 개발에도 매우 중요한 기여를 했습니다. 또한 TC39의 ECMAScript 활동을 지원하는 활발한 커뮤니티가 성장했습니다. 이 커뮤니티는 수많은 초안 검토, 수천 건의 버그 리포트 제출, 구현 실험, 테스트 슈트 기여, ECMAScript에 대해 전 세계 개발자 커뮤니티를 교육하는 역할을 했습니다. 유감스럽게도 이 노력에 기여한 모든 개인과 단체를 식별하고 인정하는 것은 불가능합니다.

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

Brian Terlson
ECMA-262, 프로젝트 편집자, 7 ~ 10

Jordan Harband
ECMA-262, 프로젝트 편집자, 10 ~ 12

Shu-yu Guo
ECMA-262, 프로젝트 편집자, 12 ~ 16

Michael Ficarra
ECMA-262, 프로젝트 편집자, 12 ~ 16

Kevin Gibbons
ECMA-262, 프로젝트 편집자, 12 ~ 16

1 범위

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

2 적합성

ECMAScript의 적합한 구현은 이 명세서에 기술된 모든 타입, 값, 객체, 프로퍼티, 함수, 프로그램 문법과 의미를 제공하고 지원해야 합니다.

ECMAScript의 적합한 구현은 최신 버전의 유니코드 표준과 ISO/IEC 10646에 따라 소스 텍스트 입력을 해석해야 합니다.

여러 인간 언어와 국가에서 사용되는 언어적, 문화적 관습에 적응해야 하는 프로그램을 지원하는 응용 프로그램 프로그래밍 인터페이스(API)를 제공하는 ECMAScript의 적합한 구현은, 이 명세서와 호환되는 가장 최근 판의 ECMA-402에서 정의된 인터페이스를 구현해야 합니다.

ECMAScript의 적합한 구현은 이 명세서에 기술된 것 외에도 추가적인 타입, 값, 객체, 프로퍼티, 함수 등을 제공할 수 있습니다. 특히, 이 명세서에 기술된 객체에 대해 명세서에 기술되지 않은 프로퍼티와 해당 프로퍼티의 값을 제공할 수 있습니다.

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

ECMAScript의 적합한 구현은 17.1 하위절에 금지 확장(Forbidden Extension)으로 명시된 어떤 확장도 구현해서는 안 됩니다.

ECMAScript의 적합한 구현은 구현 정의(implementation-defined), 구현 근사(implementation-approximated), 또는 호스트 정의(host-defined)가 아닌 어떠한 기능도 재정의해서는 안 됩니다.

ECMAScript의 적합한 구현은, 별도의 지시가 없는 한 정규적 선택 사항(Normative Optional) 하위절을 구현하거나 구현하지 않을 수 있습니다. 웹 브라우저는 일반적으로 모든 정규적 선택 사항 하위절을 구현해야 합니다. (부록 B 참조.) 만약 어떤 정규적 선택 사항 동작이 구현된다면, 해당 정규적 선택 사항 절에 포함된 모든 동작이 구현되어야 합니다. 정규적 선택 사항 절은 본 명세서에서 아래와 같이 색상 상자에 "Normative Optional"이라는 문구로 표시됩니다.

Normative Optional

2.1 정규적 선택 사항 예시 절 제목

예시 절 내용.

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

Legacy

2.2 레거시 예시 절 제목

예시 절 내용.

Normative Optional, Legacy

2.3 레거시 정규적 선택 사항 예시 절 제목

예시 절 내용.

3 정규 참조

아래에 참조된 문서는 이 문서의 적용에 필수적입니다. 날짜가 명시된 참조는 해당 판만을 적용합니다. 날짜가 명시되지 않은 참조는 해당 문서의 최신 판(수정 포함)을 적용합니다.

IEEE 754-2019, IEEE 부동소수점 산술 표준.

유니코드 표준.
https://unicode.org/versions/latest

ISO/IEC 10646, 정보 기술 — 범용 다중 바이트 문자 집합(UCS) 및 Amendment 1:2005, Amendment 2:2006, Amendment 3:2008, Amendment 4:2008, 그리고 추가 개정 및 정정 또는 후속 문서.

ECMA-402, ECMAScript 국제화 API 명세서, 본 명세서와 대응되는 연간 판.
https://www.ecma-international.org/publications-and-standards/standards/ecma-402/

ECMA-404, JSON 데이터 교환 형식.
https://www.ecma-international.org/publications-and-standards/standards/ecma-404/

4 개요

이 절은 ECMAScript 언어에 대한 비정규적 개요를 포함합니다.

ECMAScript는 객체 지향 프로그래밍 언어로, 호스트 환경 내에서 계산을 수행하고 계산 객체를 조작합니다. 여기 정의된 ECMAScript는 계산적으로 자급자족하도록 설계된 것이 아니며, 외부 데이터 입력이나 계산 결과 출력에 대한 규정이 없습니다. 대신 ECMAScript 프로그램의 계산 환경은 이 명세서에 기술된 객체와 기타 기능뿐만 아니라 환경 특화 객체도 제공하는 것이 기대되며, 이들의 설명 및 동작은 이 명세서 범위를 벗어나지만 ECMAScript 프로그램에서 접근 가능한 프로퍼티와 호출 가능한 함수가 있을 수 있음을 나타냅니다.

ECMAScript는 원래 스크립트 언어로 설계되었지만, 현재는 범용 프로그래밍 언어로 널리 사용됩니다. 스크립트 언어란 기존 시스템의 기능을 조작, 맞춤화, 자동화하는 데 사용하는 프로그래밍 언어입니다. 이러한 시스템에서는 이미 사용자 인터페이스를 통해 유용한 기능이 제공되며, 스크립트 언어는 해당 기능을 프로그램 제어로 노출하는 역할을 합니다. 이처럼 기존 시스템은 객체와 기능을 제공하는 호스트 환경을 구성하며, 이는 스크립트 언어의 기능을 완성합니다. 스크립트 언어는 전문 프로그래머와 비전문 프로그래머 모두 사용할 수 있도록 설계되었습니다.

ECMAScript는 원래 웹 스크립트 언어로 설계되어, 브라우저에서 웹 페이지에 생동감을 더하고 웹 기반 클라이언트-서버 아키텍처의 일부로 서버 계산을 수행하는 메커니즘을 제공했습니다. ECMAScript는 현재 다양한 호스트 환경에서 핵심 스크립트 기능을 제공합니다. 따라서 핵심 언어는 특정 호스트 환경과 분리되어 이 문서에서 정의됩니다.

ECMAScript 사용은 단순한 스크립팅을 넘어 다양한 환경과 규모에서 전체 프로그래밍 작업 영역으로 확장되었습니다. 사용이 늘어남에 따라 ECMAScript가 제공하는 기능과 시설도 확대되었습니다. ECMAScript는 이제 완전한 기능의 범용 프로그래밍 언어입니다.

4.1 웹 스크립팅

웹 브라우저는 클라이언트 측 계산을 위한 ECMAScript 호스트 환경을 제공합니다. 예를 들어, 창, 메뉴, 팝업, 대화 상자, 텍스트 영역, 앵커, 프레임, 히스토리, 쿠키, 입출력 등을 나타내는 객체를 포함합니다. 또한 호스트 환경은 포커스 변경, 페이지/이미지 로딩 및 언로드, 오류 및 중단, 선택, 폼 제출, 마우스 동작과 같은 이벤트에 스크립트 코드를 연결할 수 있는 수단을 제공합니다. 스크립트 코드는 HTML 내에 나타나며, 표시되는 페이지는 UI 요소와 고정 및 계산된 텍스트/이미지의 조합입니다. 스크립트 코드는 사용자 상호작용에 반응하며, 메인 프로그램이 필요하지 않습니다.

웹 서버는 서버 측 계산을 위한 다른 호스트 환경을 제공하며, 요청, 클라이언트, 파일을 나타내는 객체와 데이터 잠금/공유 메커니즘을 포함합니다. 브라우저 측과 서버 측 스크립팅을 함께 사용하면, 클라이언트와 서버 간에 계산을 분산시키면서 웹 기반 애플리케이션에 맞춤화된 사용자 인터페이스를 제공할 수 있습니다.

ECMAScript를 지원하는 각 웹 브라우저와 서버는 자체 호스트 환경을 제공하며, 이것이 ECMAScript 실행 환경을 완성합니다.

4.2 호스트와 구현체

ECMAScript를 호스트 환경에 통합하기 위해, 이 명세서는 일부 기능(예: 추상 연산)의 정의를 전적으로 또는 부분적으로 명세서 외부 소스에 위임합니다. 편집상, 이 명세서는 다음과 같은 위임 종류를 구분합니다.

구현체란 부록 D에 나열된 시설이나 구현 정의 또는 구현 근사로 표시된 시설을 추가적으로 정의하는 외부 소스를 의미합니다. 비공식적으로 구현체는 특정 웹 브라우저와 같은 구체적인 산출물을 가리킵니다.

구현 정의 시설은 외부 소스에 정의를 위임하며 추가적인 자격을 두지 않습니다. 이 명세서는 특정 동작에 대해 권고하지 않으며, 적합한 구현은 명세서가 제시한 제한 내에서 자유롭게 동작을 선택할 수 있습니다.

구현 근사 시설은 외부 소스에 정의를 위임하면서 이상적인 동작을 권장합니다. 적합한 구현은 명세서의 제한 내에서 자유롭게 동작을 선택할 수 있지만, 이상적인 동작을 최대한 근사하도록 권장됩니다. 예를 들어 Math.exp와 같은 수학 연산이 구현 근사입니다.

호스트는 부록 D에 나열된 시설을 추가적으로 정의하지만, 기타 구현 정의 또는 구현 근사 시설은 추가적으로 정의하지 않는 외부 소스입니다. 비공식적으로 호스트는 이 명세서와 부록 D를 통해 동일하게 인터페이스하는 모든 웹 브라우저 집합 등, 모든 구현체 집합을 의미합니다. 호스트는 종종 WHATWG HTML(https://html.spec.whatwg.org/)과 같은 외부 명세서입니다. 즉, 호스트 정의 시설은 종종 외부 명세서에서 추가적으로 정의됩니다.

호스트 후크는 전적으로 또는 부분적으로 외부 소스에 의해 정의되는 추상 연산입니다. 모든 호스트 후크는 부록 D에 나열되어야 합니다. 호스트 후크는 최소한 다음 요구 사항을 충족해야 합니다:

  • 정상 완료 또는 throw 완료 중 하나를 반환해야 합니다.

호스트 정의 시설은 추가적인 자격 없이 외부 소스에 정의를 위임하며, 부록 D에 나열되어 있습니다. 호스트가 아닌 구현체도 호스트 정의 시설에 대한 정의를 제공할 수 있습니다.

호스트 환경은 모든 호스트 정의 시설에 대한 선택적 정의입니다. 호스트 환경에는 일반적으로 입력을 얻거나 출력을 제공하는 객체나 함수가 포함되어 있으며, 전역 객체호스트 정의 프로퍼티로 제공됩니다.

이 명세서는 항상 가장 구체적인 용어를 사용하는 편집 관례를 따릅니다. 예를 들어, 어떤 시설이 호스트 정의인 경우 구현 정의로 지칭하지 않습니다.

호스트와 구현체 모두 이 명세서에서 정의된 언어 타입, 명세 타입, 추상 연산, 문법 생성, 내장 객체, 내장 심볼을 통해 이 명세서와 인터페이스할 수 있습니다.

4.3 ECMAScript 개요

아래는 ECMAScript에 대한 비공식 개요이며, 언어의 모든 부분이 기술된 것은 아닙니다. 이 개요는 표준의 일부가 아닙니다.

ECMAScript는 객체 기반입니다. 기본 언어와 호스트 기능은 객체로 제공되며, ECMAScript 프로그램은 상호 통신하는 객체 집합입니다. ECMAScript에서 객체란 0개 이상의 프로퍼티로 구성되어 있으며, 각 프로퍼티에는 프로퍼티의 사용 방법을 결정하는 특성이 있습니다. 예를 들어, 어떤 프로퍼티의 Writable 특성이 false로 설정된 경우, ECMAScript 코드가 해당 프로퍼티에 다른 값을 할당하려고 하면 실패합니다. 프로퍼티는 다른 객체, 원시값 또는 함수를 담는 컨테이너입니다. 원시값은 내장 타입 Undefined, Null, Boolean, Number, BigInt, String, Symbol; 중 하나의 멤버입니다. 객체는 내장 타입 Object의 멤버이며, 함수는 호출 가능한 객체입니다. 객체의 프로퍼티에 연결된 함수는 메서드라고 부릅니다.

ECMAScript는 ECMAScript 엔티티 정의를 완성하는 내장 객체 집합을 정의합니다. 내장 객체에는 전역 객체, 언어의 런타임 의미에 필수적인 Object, Function, Boolean, Symbol 및 다양한 Error 객체, 숫자값을 나타내고 조작하는 Math, Number, Date 객체, 텍스트 처리를 위한 StringRegExp 객체, 값을 인덱싱하는 컬렉션인 Array와 9가지 Typed Array, 키 기반 컬렉션인 MapSet 객체, 구조화 데이터를 지원하는 JSON 객체, ArrayBuffer, SharedArrayBuffer, DataView, 제어 추상화를 지원하는 제너레이터 함수와 Promise 객체, 그리고 리플렉션을 위한 ProxyReflect 객체가 포함됩니다.

ECMAScript는 내장 연산자 집합도 정의합니다. ECMAScript 연산자에는 다양한 단항 연산, 곱셈 연산자, 덧셈 연산자, 비트 이동 연산자, 관계 연산자, 동등 연산자, 이진 비트 연산자, 이진 논리 연산자, 할당 연산자, 쉼표 연산자가 포함됩니다.

대규모 ECMAScript 프로그램은 모듈을 통해 여러 문/선언 시퀀스로 분할될 수 있습니다. 각 모듈은 다른 모듈에서 제공해야 하는 선언과 다른 모듈에서 사용할 수 있는 자신의 선언을 명확히 식별합니다.

ECMAScript 문법은 의도적으로 Java 문법과 유사하게 설계되었습니다. ECMAScript 문법은 스크립트 언어로 쉽게 사용할 수 있도록 완화되어 있습니다. 예를 들어, 변수에 타입 선언이 필요하지 않으며, 프로퍼티에 타입이 연결되지 않고, 함수 선언이 호출보다 먼저 나타나야 할 필요도 없습니다.

4.3.1 객체

ECMAScript는 클래스 정의 문법을 포함하지만, ECMAScript 객체는 C++, Smalltalk, Java와 같은 클래스 기반 언어처럼 근본적으로 클래스 기반이 아닙니다. 객체는 리터럴 표기 또는 객체를 생성하고 프로퍼티의 초기값을 할당하는 생성자를 통해 여러 방식으로 생성될 수 있습니다. 각 생성자"prototype"이라는 프로퍼티를 가진 함수로, 프로토타입 기반 상속공유 프로퍼티를 구현하는 데 사용됩니다. new 표현식으로 생성자를 사용하면 객체가 생성됩니다. 예를 들어, new Date(2009, 11)은 새로운 Date 객체를 만듭니다. 생성자new 없이 호출하면 생성자마다 다른 결과가 발생합니다. 예를 들어, Date()는 객체가 아닌 현재 날짜와 시간의 문자열 표현을 반환합니다.

생성자로 생성된 모든 객체는 암시적으로 자신이 속한 생성자"prototype" 프로퍼티 값에 대한 참조(객체의 프로토타입이라 부름)를 갖습니다. 또한 프로토타입은 자신만의 non-null 암시적 참조를 가질 수 있으며, 이를 프로토타입 체인이라 부릅니다. 객체에서 프로퍼티에 대한 참조가 발생하면, 해당 이름의 프로퍼티를 가진 프로토타입 체인에서 첫 번째 객체의 프로퍼티가 참조됩니다. 즉, 먼저 직접 지정된 객체에서 해당 프로퍼티가 있는지 확인하고, 있으면 그 프로퍼티가 참조 대상이 됩니다. 없으면 해당 객체의 프로토타입을 다음으로 검사하고, 계속 반복합니다.

Figure 1: 객체/프로토타입 관계
박스와 화살표가 많은 이미지.

클래스 기반 객체 지향 언어에서는 일반적으로 상태는 인스턴스가, 메서드는 클래스가 담당하며, 상속은 구조와 동작에만 적용됩니다. ECMAScript에서는 상태와 메서드가 객체에 담기며, 구조, 동작, 상태 모두가 상속됩니다.

프로토타입에 특정 프로퍼티가 있고, 객체에 직접 해당 프로퍼티가 포함되지 않은 모든 객체는 그 프로퍼티와 값을 공유합니다. 그림 1은 이를 보여줍니다:

CF생성자(동시에 객체)입니다. cf1, cf2, cf3, cf4, cf5 등 5개의 객체가 new 표현식으로 생성되었습니다. 각 객체에는 "q1", "q2" 프로퍼티가 있습니다. 점선은 암시적 프로토타입 관계를 나타냅니다. 예를 들어, cf3의 프로토타입은 CFp입니다. 생성자CF"P1", "P2"라는 두 개의 프로퍼티를 갖지만, CFp, cf1, cf2, cf3, cf4, cf5에서는 보이지 않습니다. CFp"CFP1" 프로퍼티는 cf1, cf2, cf3, cf4, cf5에서 공유됩니다(CF에서는 공유되지 않음). CFp의 암시적 프로토타입 체인에 있는 다른 프로퍼티도 "q1", "q2", "CFP1"이 아닌 경우 공유됩니다. CFCFp 사이에는 암시적 프로토타입 링크가 없습니다.

대부분의 클래스 기반 객체 언어와 달리, 객체에는 값을 할당함으로써 동적으로 프로퍼티를 추가할 수 있습니다. 즉, 생성자는 생성된 객체의 모든 프로퍼티를 반드시 명명하거나 값을 할당할 필요가 없습니다. 위 그림에서 cf1, cf2, cf3, cf4, cf5에 대해 CFp에 새 값을 할당함으로써 새로운 공유 프로퍼티를 추가할 수 있습니다.

ECMAScript 객체는 본질적으로 클래스 기반이 아니지만, 생성자 함수, 프로토타입 객체, 메서드의 공통 패턴에 기반하여 클래스 유사 추상을 정의하는 것이 편리할 때가 많습니다. ECMAScript 내장 객체도 이런 클래스 유사 패턴을 따릅니다. ECMAScript 2015부터는 내장 객체가 사용하는 동일한 클래스 유사 추상 패턴에 맞는 객체를 간결하게 정의할 수 있는 문법적 클래스 정의가 도입되었습니다.

4.3.2 ECMAScript의 엄격 변종

ECMAScript 언어는 일부 사용자가 언어에서 제공되는 특정 기능 사용을 제한하고자 할 수 있음을 인식합니다. 이는 보안, 오류 발생 가능성이 높은 기능 회피, 오류 검사 강화 또는 기타 사용자의 목적을 위해서일 수 있습니다. 이런 가능성을 지원하기 위해 ECMAScript는 언어의 엄격 변종을 정의합니다. 엄격 변종은 일반 ECMAScript 언어의 일부 구문 및 의미론적 기능을 제외하고, 일부 기능의 상세 의미론을 수정합니다. 엄격 변종은 비엄격 언어 형식에서는 오류로 지정되지 않은 상황에서도 오류 예외를 반드시 던져야 하는 추가 오류 조건을 명시합니다.

ECMAScript의 엄격 변종은 언어의 엄격 모드로 일반적으로 불립니다. 엄격 모드의 선택과 엄격 모드 구문 및 의미론 사용은 개별 ECMAScript 소스 텍스트 단위 수준에서 명시적으로 결정됩니다(11.2.2 참조). 엄격 모드는 구문적 소스 텍스트 단위 수준에서 선택되므로, 제한은 해당 소스 텍스트 단위 내에서만 국지적으로 적용됩니다. 엄격 모드는 여러 소스 텍스트 단위에 걸쳐 일관되게 동작해야 하는 ECMAScript 의미론의 어떤 측면도 제한하거나 수정하지 않습니다. 전체 ECMAScript 프로그램은 엄격 모드와 비엄격 모드 소스 텍스트 단위로 구성될 수 있으며, 이 경우 엄격 모드는 실제로 엄격 모드 소스 텍스트 단위 내에서 정의된 코드를 실행할 때만 적용됩니다.

이 명세서에 적합하려면 ECMAScript 구현은 이 명세서에서 정의한 완전한 비제한 ECMAScript 언어와 엄격 변종을 모두 구현해야 합니다. 또한, 구현체는 비제한 모드와 엄격 모드 소스 텍스트 단위를 단일 복합 프로그램으로 조합하는 기능을 지원해야 합니다.

4.4 용어와 정의

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

4.4.1 구현 근사

구현 근사 시설은 전체 또는 일부가 외부 소스에 의해 정의되지만, 이 명세서에서 권장되는 이상적 동작을 갖습니다.

4.4.2 구현 정의

구현 정의 시설은 전체 또는 일부가 이 명세서 외부 소스에 의해 정의됩니다.

4.4.3 호스트 정의

구현 정의와 동일함

Note

편집상, 4.2 절 참조.

4.4.4 타입

6 절에서 정의된 데이터 값 집합

4.4.5 원시값

6 절에서 정의된 Undefined, Null, Boolean, Number, BigInt, Symbol, String 타입 중 하나의 멤버

Note

원시값은 언어 구현의 가장 낮은 수준에서 직접 표현되는 데이터입니다.

4.4.6 객체

Object 타입의 멤버

Note

객체는 프로퍼티 집합이며, 하나의 프로토타입 객체를 가집니다. 프로토타입은 null일 수 있습니다.

4.4.7 생성자

객체를 생성하고 초기화하는 함수 객체

Note

생성자"prototype" 프로퍼티 값은 상속 및 공유 프로퍼티 구현에 사용되는 프로토타입 객체입니다.

4.4.8 프로토타입

다른 객체를 위한 공유 프로퍼티를 제공하는 객체

Note

생성자가 객체를 생성할 때, 해당 객체는 프로퍼티 참조 해결을 위해 생성자"prototype" 프로퍼티를 암시적으로 참조합니다. 생성자"prototype" 프로퍼티는 constructor.prototype 표현식으로 참조할 수 있으며, 프로토타입에 추가된 프로퍼티는 프로토타입을 공유하는 모든 객체에 상속을 통해 공유됩니다. 또는 Object.create 내장 함수를 사용하여 명시적으로 지정된 프로토타입으로 새 객체를 만들 수 있습니다.

4.4.9 일반 객체

모든 객체가 반드시 지원해야 하는 기본 내부 메서드에 대한 기본 동작을 갖는 객체

4.4.10 특수 객체

하나 이상의 필수 내부 메서드에 대해 기본 동작을 갖지 않는 객체

Note

일반 객체가 아닌 모든 객체는 특수 객체입니다.

4.4.11 표준 객체

이 명세서에서 의미가 정의된 객체

4.4.12 내장 객체

ECMAScript 구현체에 의해 지정되고 제공되는 객체

Note

표준 내장 객체는 이 명세서에서 정의됩니다. ECMAScript 구현체는 추가적인 내장 객체 종류를 지정하고 제공할 수 있습니다.

4.4.13 undefined 값

변수에 값이 할당되지 않았을 때 사용되는 원시값

4.4.14 Undefined 타입

유일한 값이 undefined인 타입

4.4.15 null 값

어떠한 객체 값도 의도적으로 없음을 나타내는 원시값

4.4.16 Null 타입

유일한 값이 null인 타입

4.4.17 Boolean 값

Boolean 타입의 멤버

Note

Boolean 값은 true, false 두 가지 뿐입니다.

4.4.18 Boolean 타입

원시값 truefalse로 구성된 타입

4.4.19 Boolean 객체

표준 내장 Boolean 생성자의 인스턴스인 Object 타입의 멤버

Note

Boolean 객체는 Boolean 생성자new 표현식으로 사용할 때 생성되며, Boolean 값을 인자로 제공합니다. 결과 객체는 내부 슬롯에 Boolean 값이 저장됩니다. Boolean 객체는 Boolean 값으로 강제 변환될 수 있습니다.

4.4.20 String 값

0개 이상의 16비트 부호 없는 정수값으로 이루어진 유한 순서의 원시값

Note

String 값은 String 타입의 멤버입니다. 시퀀스 내 각 정수값은 일반적으로 UTF-16 텍스트의 16비트 단위를 나타냅니다. 단, ECMAScript는 값에 대해 16비트 부호 없는 정수라는 점 외에 제한이나 요구 사항을 두지 않습니다.

4.4.21 String 타입

모든 가능한 String 값의 집합

4.4.22 String 객체

표준 내장 String 생성자의 인스턴스인 Object 타입의 멤버

Note

String 객체는 String 생성자new 표현식으로 사용할 때 생성되며, String 값을 인자로 제공합니다. 결과 객체는 내부 슬롯에 String 값이 저장됩니다. String 객체는 String 생성자를 함수처럼 호출하면 String 값으로 강제 변환될 수 있습니다(22.1.1.1).

4.4.23 Number 값

배정밀도 64비트 이진 형식 IEEE 754-2019 값에 해당하는 원시값

Note

Number 값은 Number 타입의 멤버이며, 숫자를 직접 나타냅니다.

4.4.24 Number 타입

NaN (“not a number”), +∞𝔽 (양의 무한대), -∞𝔽 (음의 무한대)를 포함한 모든 가능한 Number 값의 집합

4.4.25 Number 객체

표준 내장 Number 생성자의 인스턴스인 Object 타입의 멤버

Note

Number 객체는 Number 생성자new 표현식으로 사용할 때 생성되며, Number 값을 인자로 제공합니다. 결과 객체는 내부 슬롯에 Number 값이 저장됩니다. Number 객체는 Number 생성자를 함수처럼 호출하면 Number 값으로 강제 변환될 수 있습니다(21.1.1.1).

4.4.26 Infinity

양의 무한대 Number 값

4.4.27 NaN

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

4.4.28 BigInt 값

임의 정밀도의 정수값에 해당하는 원시값

4.4.29 BigInt 타입

모든 가능한 BigInt 값의 집합

4.4.30 BigInt 객체

표준 내장 BigInt 생성자의 인스턴스인 Object 타입의 멤버

4.4.31 Symbol 값

유한, 문자열이 아닌 Object 프로퍼티 키를 나타내는 원시값

4.4.32 Symbol 타입

모든 가능한 Symbol 값의 집합

4.4.33 Symbol 객체

표준 내장 Symbol 생성자의 인스턴스인 Object 타입의 멤버

4.4.34 함수

서브루틴으로 호출될 수 있는 Object 타입의 멤버

Note

함수는 프로퍼티 외에도 코드와 상태를 포함하며, 호출 시 동작을 결정합니다. 함수의 코드는 ECMAScript로 작성되었을 수도, 아닐 수도 있습니다.

4.4.35 내장 함수

함수인 내장 객체

Note

내장 함수의 예로 parseInt, Math.exp 등이 있습니다. 호스트나 구현체는 이 명세서에 기술되지 않은 추가 내장 함수를 제공할 수 있습니다.

4.4.36 내장 생성자

생성자인 내장 함수

Note

내장 생성자의 예로 Object, Function 등이 있습니다. 호스트나 구현체는 이 명세서에 기술되지 않은 추가 내장 생성자를 제공할 수 있습니다.

4.4.37 프로퍼티

키(문자열 값 또는 Symbol 값)와 값을 연결하는 객체의 일부

Note

프로퍼티 형태에 따라 값은 데이터 값(원시값, 객체, 함수 객체)으로 직접 표현되거나, 접근자 함수 쌍으로 간접적으로 표현될 수 있습니다.

4.4.38 메서드

프로퍼티 값인 함수

Note

함수가 객체의 메서드로 호출될 때, 해당 객체가 this 값으로 함수에 전달됩니다.

4.4.39 내장 메서드

내장 함수인 메서드

Note

표준 내장 메서드는 이 명세서에서 정의됩니다. 호스트나 구현체는 이 명세서에 기술되지 않은 추가 내장 메서드를 제공할 수 있습니다.

4.4.40 특성

프로퍼티의 특성을 정의하는 내부 값

4.4.41 자체 프로퍼티

객체에 직접 포함된 프로퍼티

4.4.42 상속 프로퍼티

객체의 자체 프로퍼티가 아니지만, 객체의 프로토타입(자체 또는 상속 프로퍼티)의 프로퍼티인 프로퍼티

4.5 이 명세서의 구성

이후 명세서는 아래와 같이 구성됩니다:

5 절은 명세서 전반에서 사용되는 표기 관례를 정의합니다.

6 ~ 10 절은 ECMAScript 프로그램이 동작하는 실행 환경을 정의합니다.

11 ~ 17 절은 ECMAScript 프로그래밍 언어의 실제 문법 인코딩과 모든 언어 기능의 실행 의미를 정의합니다.

18 ~ 28 절은 ECMAScript 표준 라이브러리를 정의하며, 실행 중 ECMAScript 프로그램에서 사용할 수 있는 모든 표준 객체의 정의를 포함합니다.

29 절은 SharedArrayBuffer 기반 메모리 접근 및 Atomics 객체의 메서드에 대한 메모리 일관성 모델을 설명합니다.

5 표기 관례

5.1 구문 및 렉시컬 문법

5.1.1 문맥 자유 문법

문맥 자유 문법은 여러 개의 생산식으로 구성됩니다. 각 생산식에는 비단말기라 불리는 추상 기호가 좌변에, 0개 이상의 비단말기와 단말기 기호가 우변에 나열됩니다. 각 문법에서 단말기 기호는 지정된 알파벳에서 선택됩니다.

체인 생산식은 우변에 단 하나의 비단말기 기호와 0개 이상의 단말기 기호가 있는 생산식입니다.

단일 특수 비단말기로 구성된 문장에서 시작하여, 주어진 문맥 자유 문법은 언어를 정의합니다. 즉, 비단말기를 해당 비단말기가 좌변인 생산식의 우변으로 반복적으로 치환함으로써 생성될 수 있는 단말기 기호의 (아마도 무한한) 가능한 시퀀스 집합입니다.

5.1.2 렉시컬 및 정규식 문법

ECMAScript의 렉시컬 문법12 절에 있습니다. 이 문법의 단말기 기호는 11.1에서 정의된 SourceCharacter 규칙을 따르는 유니코드 코드 포인트입니다. 목표 기호 InputElementDiv, InputElementTemplateTail, InputElementRegExp, InputElementRegExpOrTemplateTail, 또는 InputElementHashbangOrRegExp에서 시작하여, 이러한 코드 포인트 시퀀스를 입력 요소 시퀀스로 변환하는 방법을 설명하는 생산식 집합을 정의합니다.

공백과 주석을 제외한 입력 요소는 ECMAScript의 구문 문법의 단말기 기호를 구성하며, ECMAScript 토큰이라고 합니다. 이 토큰은 ECMAScript 언어의 예약어, 식별자, 리터럴, 구두점입니다. 또한 줄 종결자는 토큰으로 간주되지 않지만 입력 요소 스트림의 일부가 되어 자동 세미콜론 삽입 과정(12.10)을 안내합니다. 단순 공백과 한 줄 주석은 버려져서 구문 문법의 입력 요소 스트림에 나타나지 않습니다. MultiLineComment(/**/ 형태의 주석, 줄을 넘나들든 아니든 관계 없음)도 줄 종결자가 포함되지 않았다면 단순히 버려집니다. 하지만 줄 종결자가 하나 이상 포함된 경우, 단일 줄 종결자로 대체되어 구문 문법의 입력 요소 스트림에 포함됩니다.

ECMAScript의 정규식 문법22.2.1에 있습니다. 이 문법 역시 단말기 기호로 SourceCharacter에서 정의된 코드 포인트를 사용합니다. 목표 기호 Pattern에서 시작하여, 코드 포인트 시퀀스를 정규 표현식 패턴으로 변환하는 생산식 집합을 정의합니다.

렉시컬 및 정규식 문법의 생산식은 구분 기호로 두 개의 콜론 “::”을 사용해 구분됩니다. 렉시컬 문법과 정규식 문법은 일부 생산식을 공유합니다.

5.1.3 숫자 문자열 문법

숫자 문자열 문법7.1.4.1에 나옵니다. 단말기 기호로 SourceCharacter를 가지며, 목표 기호 StringNumericLiteral에서 시작하여 문자열을 숫자 값으로 변환하는 데 사용됩니다(이는 숫자 리터럴의 렉시컬 문법과 유사하지만 다릅니다).

숫자 문자열 문법의 생산식은 세 개의 콜론 “:::”을 구분 기호로 가지며, 소스 텍스트 파싱에는 사용되지 않습니다.

5.1.4 구문 문법

ECMAScript의 구문 문법13 절부터 16 절까지 제시되어 있습니다. 이 문법의 단말기 기호는 렉시컬 문법에서 정의된 ECMAScript 토큰입니다(5.1.2). 목표 기호 ScriptModule 두 가지에서 시작하여, 토큰 시퀀스가 ECMAScript 프로그램의 구문적으로 올바른 독립된 구성 요소를 형성하는 방법을 설명하는 생산식 집합을 정의합니다.

코드 포인트 스트림을 ECMAScript Script 또는 Module로 파싱하려면, 먼저 렉시컬 문법을 반복적으로 적용하여 입력 요소 스트림으로 변환합니다. 그 후 입력 요소 스트림을 구문 문법을 단일 적용으로 파싱합니다. 입력 스트림의 토큰이 목표 비단말기(Script 또는 Module)의 단일 인스턴스로 파싱될 수 없거나 토큰이 남는다면 구문 오류입니다.

파싱이 성공하면 파스 트리가 구성되며, 트리의 각 노드는 파스 노드입니다. 각 파스 노드는 문법 기호의 인스턴스이며, 해당 기호에서 유도할 수 있는 소스 텍스트의 범위를 나타냅니다. 파스 트리의 루트 노드는 전체 소스 텍스트를 나타내며, 파싱의 목표 기호의 인스턴스입니다. 파스 노드가 비단말기의 인스턴스라면, 해당 비단말기를 좌변으로 하는 생산식 인스턴스이기도 합니다. 그리고 우변의 각 기호마다 자식을 하나씩 가집니다. 각 자식은 해당 기호의 인스턴스인 파스 노드입니다.

새로운 파스 노드는 파서가 호출될 때마다 인스턴스화되며, 동일한 소스 텍스트를 파싱하더라도 파싱 간에 재사용되지 않습니다. 파스 노드는 동일한 소스 텍스트 범위를 나타내고, 동일한 문법 기호의 인스턴스이며, 동일한 파서 호출에서 생성된 경우에만 동일한 파스 노드로 간주됩니다.

Note 1

같은 문자열을 여러 번 파싱하면 서로 다른 파스 노드가 생성됩니다. 예를 들어:

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

eval을 호출할 때마다 str의 값을 ECMAScript 소스 텍스트로 변환하고, 각각 독립적으로 자신만의 파스 노드 트리를 생성합니다. 이 트리들은 각각의 파싱이 동일한 문자열 값에서 유도된 소스 텍스트를 대상으로 하더라도 서로 다릅니다.

Note 2
파스 노드는 명세상의 산출물이며, 실제 구현에서는 유사한 데이터 구조를 사용할 필요가 없습니다.

구문 문법의 생산식은 구분 기호로 한 개의 콜론 “:”만을 사용합니다.

13부터 16까지 제시된 구문 문법은 ECMAScript Script 또는 Module로서 올바르게 받아들여지는 토큰 시퀀스를 완전히 설명한 것은 아닙니다. 추가적인 토큰 시퀀스도 허용되며, 예를 들어 일부 위치(줄 종결자 앞 등)에 세미콜론만 추가하면 문법에서 기술될 토큰 시퀀스가 허용됩니다. 또한, 일부 위치에 줄 종결자가 나타나면 문법에서 기술된 토큰 시퀀스라 해도 허용되지 않을 수 있습니다.

일부 경우, 모호성을 피하기 위해 구문 문법은 유효한 ECMAScript Script 또는 Module을 형성하지 않는 토큰 시퀀스를 허용하는 일반화된 생산식을 사용합니다. 예를 들어, 객체 리터럴 및 객체 구조 분해 패턴에 이 기법이 사용됩니다. 이런 경우, 더 제한적인 보조 문법이 제공되어 허용되는 토큰 시퀀스를 추가로 제한합니다. 일반적으로, 초기 오류 규칙은 특정 문맥에서 "P 는 반드시 N을 커버해야 한다"고 명시합니다. 여기서 P는 파스 노드(일반화된 생산식의 인스턴스), N은 보조 문법의 비단말기입니다. 이는 다음을 의미합니다:

  1. P가 원래 일치시킨 토큰 시퀀스를 N을 목표 기호로 하여 다시 파싱합니다. N에 문법적 매개변수가 있다면, P가 처음 파싱될 때 사용된 값으로 설정합니다.
  2. 토큰 시퀀스를 토큰 남김 없이 N의 단일 인스턴스로 파싱할 수 있다면:
    1. 해당 N 인스턴스(특정 P에 대해 유일한 파스 노드)를 "P가 커버하는 N"이라고 합니다.
    2. N 및 그 파생 생산식에 대한 모든 Early Error 규칙은 P가 커버하는 N에도 적용됩니다.
  3. 그렇지 않으면(파싱이 실패하면), 이는 초기 구문 오류입니다.

5.1.5 문법 표기법

5.1.5.1 단말기 기호

ECMAScript 문법에서 일부 단말기 기호는 고정폭 글꼴로 표시됩니다. 이는 소스 텍스트에 정확히 표시된 대로 나타나야 함을 의미합니다. 이렇게 지정된 모든 단말기 기호 코드 포인트는 다른 유사한 유니코드 범위가 아니라 기본 라틴 블록의 적절한 유니코드 코드 포인트로 이해해야 합니다. 단말기 기호의 코드 포인트는 \ UnicodeEscapeSequence로 표현할 수 없습니다.

단말기 기호가 개별 유니코드 코드 포인트인 문법(즉, 렉시컬, 정규식, 숫자 문자열 문법)에서는 생산식에 여러 개의 고정폭 코드 포인트가 연속해서 나타날 때, 이는 동일한 시퀀스를 독립된 단말기 기호로 쓴 것과 같습니다.

예를 들어, 다음과 같은 생산식이 있습니다:

HexIntegerLiteral :: 0x HexDigits

이는 사실 다음과 같은 약어입니다:

HexIntegerLiteral :: 0 x HexDigits

반면, 구문 문법에서는 고정폭 코드 포인트가 연속해서 나타날 경우 단일 단말기 기호로 취급됩니다.

단말기 기호는 두 가지 다른 형태도 있습니다:

5.1.5.2 비단말기 기호와 생산식

비단말기 기호는 이탤릭체로 표시됩니다. 비단말기 정의(생산식이라고도 함)는 정의되는 비단말기 이름 다음에 하나 이상의 콜론이 옵니다. (콜론의 개수는 생산식이 속한 문법을 나타냅니다.) 이어서 비단말기의 하나 이상의 대체 우변이 각각의 줄에 나옵니다. 예를 들어, 다음과 같은 구문 정의가 있습니다:

WhileStatement : while ( Expression ) Statement

이는 비단말기 WhileStatement가 토큰 while 다음에 왼쪽 괄호 토큰, Expression, 오른쪽 괄호 토큰, Statement가 차례로 오는 것을 의미합니다. ExpressionStatement도 각각 비단말기입니다. 또 다른 예로, 다음과 같은 구문 정의가 있습니다:

ArgumentList : AssignmentExpression ArgumentList , AssignmentExpression

이는 ArgumentList가 단일 AssignmentExpression 또는 ArgumentList, 쉼표, AssignmentExpression로 나타날 수 있음을 의미합니다. 이 ArgumentList 정의는 자기 참조적(재귀적)이며, 자신에 대한 정의로 이루어져 있습니다. 결과적으로 ArgumentList는 콤마로 구분된 모든 양의 개수의 인자, 각 인자 표현식은 AssignmentExpression이 될 수 있습니다. 이러한 비단말기의 재귀적 정의는 흔합니다.

5.1.5.3 선택적 기호

단말기 또는 비단말기 뒤에 첨자 “opt”가 붙으면 선택적 기호임을 나타냅니다. 선택적 기호가 포함된 대안은 실제로 두 가지 우변을 명시합니다. 하나는 선택적 요소를 생략한 것이고, 하나는 포함한 것입니다. 즉,

VariableDeclaration : BindingIdentifier Initializeropt

는 다음의 편리한 약어입니다:

VariableDeclaration : BindingIdentifier BindingIdentifier Initializer

그리고:

ForStatement : for ( LexicalDeclaration Expressionopt ; Expressionopt ) Statement

는 다음의 편리한 약어입니다:

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

이는 다시 다음의 약어입니다:

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

따라서 이 예시에서 비단말기 ForStatement는 실제로 네 가지 대체 우변을 갖습니다.

5.1.5.4 문법적 매개변수

생산식은 첨자 형태의 “[parameters]” 주석으로 매개변수화될 수 있으며, 이는 생산식이 정의하는 비단말기 기호 뒤에 접미사로 나타납니다. “parameters”는 단일 이름 또는 컴마로 구분된 이름 목록일 수 있습니다. 매개변수화된 생산식은 매개변수 이름 조합마다 해당 비단말기 기호에 언더스코어를 붙여서 정의하는 생산식 집합의 약어입니다. 즉,

StatementList[Return] : ReturnStatement ExpressionStatement

는 다음의 편리한 약어입니다:

StatementList : ReturnStatement ExpressionStatement StatementList_Return : ReturnStatement ExpressionStatement

그리고:

StatementList[Return, In] : ReturnStatement ExpressionStatement

는 다음의 약어입니다:

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

여러 매개변수가 있으면 조합 수만큼 생산식이 생성되며, 모든 경우가 완전한 문법에서 참조되는 것은 아닙니다.

생산식의 우변에 있는 비단말기 참조 역시 매개변수화될 수 있습니다. 예를 들어:

StatementList : ReturnStatement ExpressionStatement[+In]

는 다음과 동일합니다:

StatementList : ReturnStatement ExpressionStatement_In

그리고:

StatementList : ReturnStatement ExpressionStatement[~In]

는 다음과 동일합니다:

StatementList : ReturnStatement ExpressionStatement

비단말기 참조에는 매개변수 목록과 “opt” 첨자가 모두 있을 수 있습니다. 예를 들어:

VariableDeclaration : BindingIdentifier Initializer[+In]opt

는 다음의 약어입니다:

VariableDeclaration : BindingIdentifier BindingIdentifier Initializer_In

우변 비단말기 참조에 매개변수 이름 앞에 “?”가 있으면, 그 매개변수 값은 현재 생산식 좌변의 비단말기 참조에 해당 매개변수 이름이 나타나는지에 따라 결정됩니다. 예를 들어:

VariableDeclaration[In] : BindingIdentifier Initializer[?In]

는 다음의 약어입니다:

VariableDeclaration : BindingIdentifier Initializer VariableDeclaration_In : BindingIdentifier Initializer_In

우변 대안 앞에 “[+parameter]”가 있으면, 해당 대안은 생산식의 비단말기 기호 참조에 지정된 매개변수가 있을 때만 사용 가능합니다. “[~parameter]”가 있으면, 해당 대안은 지정된 매개변수가 없을 때만 사용 가능합니다. 즉,

StatementList[Return] : [+Return] ReturnStatement ExpressionStatement

는 다음의 약어입니다:

StatementList : ExpressionStatement StatementList_Return : ReturnStatement ExpressionStatement

그리고:

StatementList[Return] : [~Return] ReturnStatement ExpressionStatement

는 다음의 약어입니다:

StatementList : ReturnStatement ExpressionStatement StatementList_Return : ExpressionStatement

5.1.5.5 one of

문법 정의에서 콜론 다음에 “one of”가 나오면, 다음 줄 또는 여러 줄에 있는 각 단말기 기호가 대체 정의임을 의미합니다. 예를 들어 ECMAScript의 렉시컬 문법에는 다음과 같은 생산식이 있습니다:

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

이는 다음과 같은 약어일 뿐입니다:

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

5.1.5.6 [empty]

생산식의 우변에 “[empty]”가 나타나면, 해당 생산식의 우변이 단말기나 비단말기 기호를 전혀 포함하지 않음을 의미합니다.

5.1.5.7 앞보기 제한

생산식의 우변에 “[lookahead = seq]”가 나타나면, 해당 생산식은 토큰 시퀀스 seq가 바로 뒤따르는 입력 토큰 시퀀스의 접두사일 때만 사용될 수 있음을 의미합니다. 마찬가지로 “[lookahead ∈ set]”에서 set유한하고 비어 있지 않은 토큰 시퀀스 집합일 때, 집합의 어떤 요소가 바로 뒤따르는 토큰 시퀀스의 접두사일 때만 사용될 수 있음을 의미합니다. 편의상 집합을 비단말기로 쓸 수도 있는데, 이 경우 해당 비단말기가 확장할 수 있는 모든 토큰 시퀀스 집합을 나타냅니다. 비단말기가 무한히 많은 서로 다른 토큰 시퀀스로 확장될 수 있다면 이는 편집 오류로 간주합니다.

이 조건들은 부정될 수도 있습니다. “[lookahead ≠ seq]”는 해당 생산식이 seq가 바로 뒤따르는 입력 토큰 시퀀스의 접두사가 아니어야만 사용할 수 있음을 의미하고, “[lookahead ∉ set]”는 집합의 어떤 요소도 바로 뒤따르는 토큰 시퀀스의 접두사가 되어서는 안 될 때만 사용될 수 있음을 의미합니다.

예시로, 다음과 같은 정의를 보면:

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

다음과 같은 정의가 있습니다:

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

이는 문자 n 다음에 첫 번째가 짝수인 하나 이상의 십진수 숫자가 오거나, 십진수 숫자 다음에 또 다른 십진수 숫자가 오지 않는 경우를 일치시킵니다.

이러한 문구가 구문 문법에서 사용될 때, 바로 뒤따르는 토큰 시퀀스를 명확히 식별하는 것이 불가능할 수 있습니다. 이는 이후 토큰을 결정하려면 이후 위치에서 사용할 렉시컬 목표 기호를 알아야 하기 때문입니다. 그러므로 구문 문법에서 이러한 제한이 사용될 때, 토큰 시퀀스 seq가 접두사 제한에 나타나면(집합의 일부로 포함된 경우도 포함), 이후 사용할 렉시컬 목표 기호 선택에 따라 seq가 실제로 접두사가 되는지 여부가 바뀔 수 있다면, 이는 편집 오류로 간주합니다.

5.1.5.8 [여기 LineTerminator 없음]

구문 문법의 생산식 우변에 “[no LineTerminator here]”가 나타나면, 해당 생산식은 제한 생산식이며, 해당 위치에 입력 스트림에서 LineTerminator가 나타나면 사용할 수 없습니다. 예를 들어 다음과 같은 생산식이 있습니다:

ThrowStatement : throw [no LineTerminator here] Expression ;

이는 스크립트에서 throw 토큰과 Expression 사이에 LineTerminator가 있으면 해당 생산식을 사용할 수 없음을 의미합니다.

제한 생산식에서 LineTerminator의 존재가 금지되지 않는 한, 입력 요소 스트림의 연속된 두 토큰 사이에는 LineTerminator가 아무리 많이 있어도 스크립트의 구문적 허용성에 영향을 주지 않습니다.

5.1.5.9 but not

생산식의 우변에 “but not” 문구가 오면, 뒤이어 제외할 확장을 명시하여 특정 확장이 허용되지 않음을 나타냅니다. 예를 들어 다음과 같은 생산식이 있습니다:

Identifier :: IdentifierName but not ReservedWord

이는 비단말기 IdentifierIdentifierName을 대체할 수 있는 코드 포인트 시퀀스 중, 동일한 시퀀스가 ReservedWord를 대체할 수 없는 경우에만 사용할 수 있음을 의미합니다.

5.1.5.10 서술적 구문

마지막으로 일부 비단말기 기호는 모든 대안을 나열하는 것이 비현실적인 경우 산세리프체로 서술적 문구로 설명됩니다:

SourceCharacter :: any Unicode code point

5.2 알고리즘 관례

이 명세서는 알고리즘 단계 지정을 위해 주로 번호가 매겨진 목록을 사용합니다. 이러한 알고리즘은 ECMAScript 언어 구성 요소의 요구 의미론을 정확하게 명시하는 데 사용됩니다. 알고리즘이 특정 구현 기법의 사용을 암시하는 것은 아닙니다. 실제로, 주어진 기능을 더 효율적으로 구현할 수 있는 알고리즘이 있을 수 있습니다.

알고리즘은 명시적으로 순서가 있는 쉼표로 구분된 별칭 이름 시퀀스로 매개변수화될 수 있으며, 알고리즘 단계 내에서 해당 위치에 전달된 인자를 참조하는 데 사용할 수 있습니다. 선택적 매개변수는 대괄호([ , name ])로 나타내며, 알고리즘 단계 내에서는 필수 매개변수와 차이가 없습니다. 나머지 매개변수(rest parameter)는 매개변수 리스트 끝에 ...name 형태로 나타내며, 필수 및 선택적 매개변수 뒤에 전달된 모든 인자를 List로 수집합니다. 추가 인자가 없는 경우 해당 List는 비어 있습니다.

알고리즘 단계는 순차적 하위 단계로 세분화될 수 있습니다. 하위 단계는 들여쓰기되며, 그 자체로 더 들여쓰기된 하위 단계로 나뉠 수 있습니다. 개요 번호 매기기 규칙은 첫 번째 하위 단계는 소문자 알파벳, 두 번째 하위 단계는 소문자 로마 숫자를 사용합니다. 세 단계보다 더 깊은 단계가 필요할 경우, 네 번째 단계부터는 숫자를 사용합니다. 예시:

  1. 최상위 단계
    1. 하위 단계.
    2. 하위 단계.
      1. 하위 하위 단계.
        1. 하위 하위 하위 단계
          1. 하위 하위 하위 하위 단계
            1. 하위 하위 하위 하위 하위 단계

단계나 하위 단계는 "if" 조건문으로 작성될 수 있으며, 이 경우 조건이 true일 때만 하위 단계를 적용합니다. 단계나 하위 단계가 "else"로 시작하면, 해당 단계는 같은 수준의 직전 “if” 조건문의 부정이 됩니다.

단계는 하위 단계의 반복적 적용을 지정할 수 있습니다.

"Assert:"로 시작하는 단계는 알고리즘의 불변 조건을 단언합니다. 이러한 단언은 암묵적일 수 있는 알고리즘 불변 조건을 명시적으로 만듭니다. 이러한 단언은 추가적인 의미 요구사항을 더하지 않으므로 구현에서는 검사할 필요가 없습니다. 단순히 알고리즘을 명확히 하기 위해 사용됩니다.

알고리즘 단계에서는 "Let x be someValue" 형식으로 어떤 값에 대한 별칭을 선언할 수 있습니다. 이 별칭은 참조와 유사하여 xsomeValue가 동일한 데이터에 연결되며, 둘 중 하나를 수정하면 모두에 반영됩니다. 참조와 유사한 동작을 피하고 싶으면, 오른쪽 값을 명시적으로 복사하도록 "Let x be a copy of someValue"를 사용합니다. 이는 someValue의 얕은 복사를 만듭니다.

별칭이 선언된 이후에는 모든 이후 단계에서 참조할 수 있으며, 선언 이전 단계에서 참조해서는 안 됩니다. 별칭은 "Set x to someOtherValue" 형태로 수정할 수 있습니다.

5.2.1 추상 연산

이 명세서의 여러 부분에서 사용할 수 있도록, 일부 알고리즘(추상 연산)은 이름을 붙이고 매개변수화된 함수 형태로 작성되며, 다른 알고리즘 내에서 이름으로 참조될 수 있습니다. 추상 연산은 일반적으로 함수 호출 형태(OperationName(arg1, arg2))로 참조됩니다. 일부 추상 연산은 클래스와 유사한 명세 추상화의 다형적 메서드로 취급됩니다. 이러한 메서드형 추상 연산은 someValue.OperationName(arg1, arg2)와 같은 메서드 호출 형태로 참조됩니다.

5.2.2 구문 지향 연산

구문 지향 연산은 이름이 붙은 연산으로, 각 연산은 ECMAScript 문법의 하나 이상의 생산식과 연결된 알고리즘으로 정의됩니다. 여러 대안 정의가 있는 생산식은 일반적으로 각 대안마다 별도의 알고리즘을 가집니다. 알고리즘이 문법 생산식과 연결되어 있을 때, 해당 생산식의 단말기와 비단말기 기호를 알고리즘의 매개변수처럼 참조할 수 있습니다. 이때 비단말기 기호는 소스 텍스트를 파싱할 때 실제로 일치된 대안 정의를 참조합니다. 문법 생산식 또는 그로부터 파생된 파스 노드가 일치시킨 소스 텍스트는 일치에 참여한 첫 번째 단말기에서 시작하여 마지막 단말기에서 끝나는 소스 텍스트의 부분입니다.

알고리즘이 생산식 대안과 연결될 때, 대안은 일반적으로 “[ ]” 문법 주석 없이 표시됩니다. 이러한 주석은 대안의 구문 인식에만 영향을 주며, 연결된 의미에는 영향을 주지 않습니다.

구문 지향 연산은 파스 노드와 필요에 따라 추가 매개변수를 넘겨 호출합니다. 다음 알고리즘의 1, 3, 4 단계를 참고하세요:

  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".

별도로 명시되지 않는 한, 모든 체인 생산식은 해당 좌변 비단말기에 적용될 수 있는 모든 연산에 대해 암시적 정의를 가집니다. 암시적 정의는 동일한 연산을 동일한 매개변수로 체인 생산식의 유일한 우변 비단말기에 다시 적용한 다음 그 결과를 반환합니다. 예를 들어, 어떤 알고리즘에 “Return Evaluation of Block”이라는 단계가 있고, 다음과 같은 생산식이 있다고 가정합니다:

Block : { StatementList }

Evaluation 연산이 해당 생산식과 연결된 알고리즘을 갖지 않는 경우, Evaluation 연산은 다음과 같은 연결을 암시적으로 포함합니다:

런타임 의미론: Evaluation

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

5.2.3 런타임 의미론

런타임에 호출되어야 하는 의미론을 명시하는 알고리즘을 런타임 의미론이라고 합니다. 런타임 의미론은 추상 연산 또는 구문 지향 연산으로 정의됩니다.

5.2.3.1 Completion ( completionRecord )

The abstract operation Completion takes argument completionRecord (a Completion Record) and returns a Completion Record. It performs the following steps when called:

  1. Assert: completionRecordCompletion Record이다.
  2. completionRecord를 반환한다.

5.2.3.2 예외 던지기

알고리즘 단계에서 예외를 던지라고 명시된 경우(예:

  1. TypeError 예외를 던진다.

)는 다음과 동일한 의미입니다:

  1. Return ThrowCompletion(새로 생성된 TypeError 객체).

5.2.3.3 ReturnIfAbrupt

다음과 같이 명시된 알고리즘 단계:

  1. ReturnIfAbrupt(argument).

는 다음과 동일합니다:

  1. Assert: argumentCompletion Record이다.
  2. argumentabrupt completion이면 Completion(argument)를 반환한다.
  3. 그렇지 않으면, argumentargument.[[Value]]로 설정한다.

다음과 같이 명시된 알고리즘 단계:

  1. ReturnIfAbrupt(AbstractOperation()).

는 다음과 동일합니다:

  1. Let hygienicTemp be AbstractOperation().
  2. Assert: hygienicTempCompletion Record이다.
  3. hygienicTempabrupt completion이면 Completion(hygienicTemp)를 반환한다.
  4. 그렇지 않으면, hygienicTemphygienicTemp.[[Value]]로 설정한다.

여기서 hygienicTemp는 일시적이며, ReturnIfAbrupt 관련 단계에서만 보입니다.

다음과 같이 명시된 알고리즘 단계:

  1. Let result be AbstractOperation(ReturnIfAbrupt(argument)).

는 다음과 동일합니다:

  1. Assert: argumentCompletion Record이다.
  2. argumentabrupt completion이면 Completion(argument)를 반환한다.
  3. 그렇지 않으면, argumentargument.[[Value]]로 설정한다.
  4. Let result be AbstractOperation(argument).

5.2.3.4 ReturnIfAbrupt 축약 표기

추상 연산 및 구문 지향 연산의 호출 앞에 ?가 붙으면, 결과 Completion RecordReturnIfAbrupt를 적용해야 함을 나타냅니다. 예를 들어:

  1. ? OperationName().

는 다음 단계와 같습니다:

  1. ReturnIfAbrupt(OperationName()).

메서드 호출 형태에서도 마찬가지로 다음 단계:

  1. someValue.OperationName().

는 다음과 같습니다:

  1. ReturnIfAbrupt(someValue.OperationName()).

마찬가지로, !를 앞에 붙이면, 해당 추상 또는 구문 지향 연산abrupt completion을 반환하지 않음을 의미하며, 결과 Completion Record[[Value]] 필드를 연산의 반환값으로 사용함을 나타냅니다. 예를 들어:

  1. Let val be ! OperationName().

는 다음 단계와 같습니다:

  1. Let val be OperationName().
  2. Assert: val은 정상 completion이다.
  3. valval.[[Value]]로 설정한다.

런타임 의미론구문 지향 연산에서는 이 축약 표기를 사용하여 연산 호출 앞에 ! 또는 ?를 둡니다:

  1. Perform ! SyntaxDirectedOperation of NonTerminal.

5.2.3.5 암시적 정상 Completion

Completion Record를 반환하도록 선언된 추상 연산 내부 알고리즘과 모든 내장 함수에서는 반환값이 먼저 NormalCompletion에 전달되고, 그 결과가 대신 사용됩니다. 이 규칙은 Completion 알고리즘 내부 또는 반환되는 값이 해당 단계에서 Completion Record로 명확히 표시된 경우에는 적용되지 않습니다. 적용 예시는 다음과 같습니다:

이러한 추상 연산에서 다른 방식으로 Completion Record를 반환하면 편집 오류입니다. 예를 들어, 다음과 같은 경우,

  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 }.

ReturnIfAbrupt 확장에 따라, 다음 예시는 허용됩니다. 확장된 단계 내에서는 Completion 적용 결과가 abrupt인 경우 바로 반환되고, normal인 경우 unwrapping 후 암시적 NormalCompletion이 적용됩니다.

  1. Return ? completion.

다음 예시는 Completion Record가 해당 단계에서 명시되지 않은 채 반환되므로 편집 오류입니다.

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

5.2.4 정적 의미론

문맥 자유 문법만으로는 입력 요소 스트림이 평가 가능한 ECMAScript Script 또는 Module로서 유효한지를 정의하는 모든 규칙을 표현할 수 없습니다. 일부 상황에서는 ECMAScript 알고리즘 관례나 산문 요구사항을 활용해서 추가 규칙을 명시해야 하며, 이러한 규칙은 항상 문법의 생산식과 연결되어 해당 생산식의 정적 의미론이라 불립니다.

정적 의미론 규칙에는 이름이 있으며, 일반적으로 알고리즘으로 정의됩니다. 이름이 붙은 정적 의미론 규칙은 문법 생산식과 연결되며, 여러 대안 정의가 있는 생산식은 각 대안마다 해당 규칙에 대해 별도의 알고리즘을 가집니다.

정적 의미론 규칙의 특별한 종류가 초기 오류 규칙(Early Error Rule)입니다. 초기 오류 규칙은 특정 문법 생산식과 연결된 초기 오류 조건을 정의하며(17 참조), 대부분의 초기 오류 규칙은 이 명세서 알고리즘에서 명시적으로 호출되지 않습니다. 적합한 구현체는 Script 또는 Module을 최초로 평가하기 전에, 해당 Script 또는 Module을 파싱하는 데 사용된 모든 생산식의 초기 오류 규칙을 반드시 검증해야 합니다. 초기 오류 규칙이 하나라도 위반되면 Script 또는 Module은 유효하지 않으며 평가될 수 없습니다.

5.2.5 수학 연산

이 명세서에서 참조하는 숫자값 종류는 다음과 같습니다:

  • 수학적 값: 임의의 실수. 기본 숫자 타입으로 사용됨.
  • 확장 수학적 값: 수학적 값과 +∞, -∞ 포함.
  • Numbers: IEEE 754-2019 binary64(배정밀도 부동소수점) 값.
  • BigInts: ECMAScript 언어값으로, 임의의 정수와 일대일 대응됨.

이 명세서에서 숫자값은 첨자 표기로 종류를 구분합니다. 첨자 𝔽는 Numbers를, 는 BigInts를 나타냅니다. 첨자 없는 숫자값은 수학적 값을 의미합니다. 대부분의 숫자값은 10진수로 표기되며, 0x로 시작하고 0-9 또는 A-F로 이어지는 값은 16진수로 사용됩니다.

명세서에서 "the length of y"나 "the integer represented by the four hexadecimal digits ..."와 같이 명시적 숫자 종류 없이 숫자값을 언급하면, 이는 수학적 값을 의미합니다. Number나 BigInt 값을 명시할 경우, "the Number value for ..." 또는 "the BigInt value for ..."와 같이 명시적으로 구분합니다.

integer라는 용어는 별도 명시가 없는 한, 정수 집합에 속하는 수학적 값을 의미합니다. integral Number라는 용어는 수학적으로 정수 집합에 속하는 유한한 Number 값을 의미합니다.

+, ×, =, ≥ 등 숫자 연산자는 피연산자의 타입에 따라 연산이 결정됩니다. 수학적 값에 적용하면 일반 수학 연산을, 확장 수학적 값에 적용하면 확장 실수에 대한 연산을 의미합니다. 정의되지 않은 형태는 사용해서는 안 되며, 명세서에 사용되면 편집 오류입니다. Numbers에 적용하면 IEEE 754-2019에 따른 연산을, BigInts에 적용하면 BigInt의 수학적 값에 대한 연산을 의미합니다. 타입이 혼합된(예: Number와 수학적 값) 피연산자에 대한 숫자 연산은 정의되지 않으며, 명세서에서 사용되면 편집 오류입니다.

수학적 값과 Number 또는 BigInt 간의 변환은 항상 명시적으로 나타납니다. 수학적 값 또는 확장 수학적 값 x를 Number로 변환하면 "the Number value for x" 또는 𝔽(x)로 표기하며, 6.1.6.1에서 정의됩니다. 정수 x를 BigInt로 변환하면 "the BigInt value for x" 또는 ℤ(x)로 표기합니다. Number 또는 BigInt x수학적 값으로 변환하면 "the mathematical value of x" 또는 ℝ(x)로 표기합니다. +0𝔽-0𝔽수학적 값은 0입니다. 비유한 값의 수학적 값은 정의되지 않습니다. extended mathematical value of x유한 값에는 수학적 값, +∞𝔽-∞𝔽에는 각각 +∞, -∞가 되며, NaN에는 정의되지 않습니다.

수학 함수 abs(x)x의 절댓값을 반환하며, x < 0이면 -x, 그렇지 않으면 x 자체입니다.

수학 함수 min(x1, x2, … , xN)x1 ~ xN 중 가장 작은 값을 반환합니다. max(x1, x2, ..., xN)은 가장 큰 값을 반환합니다. 이 수학 함수의 정의역과 값의 범위는 확장 수학적 값입니다.

x modulo y”(y유한하고 0이 아니어야 함)은 y와 같은 부호(또는 0)를 가진 값 k를 계산하며, abs(k) < abs(y) and x - k = q × y를 만족하는 정수 q가 존재합니다.

"the result of clamping x between lower and upper"(x확장 수학적 값, lower, upperlowerupper수학적 값)란, x < lowerlower, x > upperupper, 아니면 x를 반환합니다.

수학 함수 floor(x)x보다 크지 않은 가장 큰 정수(가장 +∞에 가까운)를 반환합니다.

Note

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

수학 함수 truncate(x)x의 소수 부분을 제거하며, x < 0이면 -floor(-x), 아니면 floor(x)를 반환합니다.

min, max, abs, floor, truncate 함수는 Numbers와 BigInts에는 정의되지 않으며, 수학적 값이 아닌 인자를 사용하는 경우 명세서에서 편집 오류입니다.

하한 a ~ 상한 b구간은 동일 숫자 타입의 값 집합이며, 무한 혹은 빈 집합일 수 있습니다. 각 구간의 경계는 포함 또는 제외로 표시되나, 둘 다는 아닙니다. 구간 종류는 다음 네 가지입니다:

  • a (포함) ~ b (포함) 구간(inclusive interval)은 axb인 값만 포함합니다.
  • a (포함) ~ b (제외) 구간ax < b인 값만 포함합니다.
  • a (제외) ~ b (포함) 구간a < xb인 값만 포함합니다.
  • a (제외) ~ b (제외) 구간a < x < b인 값만 포함합니다.

예를 들어 1(포함) ~ 2(제외) 구간은 1 이상 2 미만의 모든 수학적 값을 포함하며, 1은 포함, 2는 포함하지 않습니다. 구간 정의에서 -0𝔽 < +0𝔽이므로, 하한이 +0𝔽인 포함 구간+0𝔽는 포함하나 -0𝔽는 포함하지 않습니다. NaN은 절대 구간에 포함되지 않습니다.

5.2.6 값 표기법

이 명세서에서 ECMAScript 언어값은 굵게 표시됩니다. 예시로 null, true, "hello" 등이 있으며, Function.prototype.applylet n = 42;처럼 ECMAScript 소스 텍스트와 구분됩니다.

5.2.7 동일성

이 명세서에서는 명세 값과 ECMAScript 언어값 모두 동등성 비교를 합니다. 동등성 비교 시 값은 두 가지 범주로 나뉩니다. 동일성 없는 값은 모든 고유 특성이 동일하면 서로 동등합니다(예: 정수 크기나 시퀀스 길이). 이러한 값은 특성만으로 참조 없이 나타낼 수 있습니다. 반면 동일성 있는 값은 유일하며 자기 자신과만 동등합니다. 동일성 있는 값은 동일성 없는 값과 같으나, 동일성이라는 추정 불가, 변경 불가, 전역적으로 유일한 특성을 추가로 가집니다. 기존 동일성 있는 값 참조는 특성 설명만으로 나타낼 수 없으며, 반드시 값을 명시적으로 전달해야 합니다. 일부 동일성 있는 값은 변경 가능하여, 동일성 외 특성이 변하면 모든 참조자가 변경을 관찰합니다. 동일성 없는 값은 동일성 있는 값과 결코 동등하지 않습니다.

명세 관점에서 “is”는 두 값을 동등 비교하는 데 사용되며(예: “If bool is true, then ...”), “contains”는 리스트 내 값을 동등 비교로 찾는 데 사용됩니다(예: "If list contains a Record r such that r.[[Foo]] is true, then ..."). 값의 명세 동일성이 비교 결과를 결정하며, 이는 명세적으로 자명합니다.

ECMAScript 언어 관점에서는 언어값을 SameValue 추상 연산 및 그 하위 추상 연산으로 비교합니다. 이 비교 추상 연산 알고리즘이 ECMAScript 언어값의 언어 동일성을 결정합니다.

명세 값 중 동일성 없는 예시는: 수학적 값확장 수학적 값, ECMAScript 소스 텍스트, surrogate pair, Directive Prologue 등, UTF-16 코드 유닛, 유니코드 코드 포인트, enum, 추상 연산(구문 지향 연산, host hook 등), 정렬된 쌍 등이 있습니다. 동일성 있는 예시는: Property Descriptor, PrivateElement 등 다양한 Record, Parse Node, List, SetRelation, Abstract Closure, Data Block, Private Name, 실행 컨텍스트 및 스택, agent signifier, WaiterList Record 등이 있습니다.

명세 동일성은 ECMAScript 언어값 중 Symbol.for로 생성된 Symbol을 제외하고 언어 동일성과 일치합니다. 명세 동일성 및 언어 동일성 모두 없는 ECMAScript 언어값은 undefined, null, Boolean, String, Number, BigInt입니다. 명세 동일성과 언어 동일성을 모두 가지는 ECMAScript 언어값은 Symbol(단, Symbol.for 생성이 아닌 경우) 및 Object입니다. Symbol.for로 생성된 Symbol은 명세 동일성은 있으나 언어 동일성은 없습니다.

6 ECMAScript 데이터 타입과 값

이 명세서의 알고리즘은 각각 타입이 연관된 값을 다룹니다. 가능한 값의 타입은 이 절에서 정의된 것들만 해당합니다. 타입은 ECMAScript 언어 타입과 명세 타입으로 분류됩니다.

6.1 ECMAScript 언어 타입

ECMAScript 언어 타입은 ECMAScript 프로그래머가 ECMAScript 언어를 통해 직접 다루는 값에 해당합니다. ECMAScript 언어 타입에는 Undefined, Null, Boolean, String, Symbol, Number, BigInt, Object가 있습니다. ECMAScript 언어 값은 ECMAScript 언어 타입에 의해 특징지어지는 값입니다.

6.1.1 Undefined 타입

Undefined 타입은 undefined라는 단 하나의 값만을 가집니다. 값이 할당되지 않은 변수는 undefined 값을 가집니다.

6.1.2 Null 타입

Null 타입은 null이라는 단 하나의 값만을 가집니다.

6.1.3 Boolean 타입

Boolean 타입truefalse라는 두 값을 가지는 논리적 개체를 나타냅니다.

6.1.4 String 타입

String 타입은 0개 이상의 16비트 부호 없는 정수값(“요소”)으로 이루어진 모든 순서 있는 시퀀스의 집합이며, 최대 길이는 253 - 1 요소까지입니다. String 타입은 일반적으로 ECMAScript 프로그램에서 텍스트 데이터를 표현하는 데 사용되며, 이 경우 String의 각 요소는 UTF-16 코드 유닛 값으로 간주됩니다. 각 요소는 시퀀스 내에서 위치를 가지며, 이 위치는 0 이상의 정수 인덱스로 지정됩니다. 첫 번째 요소(존재한다면)는 인덱스 0, 그 다음 요소는 인덱스 1 등입니다. String의 길이는 그 안에 포함된 요소(즉, 16비트 값)의 개수입니다. 빈 문자열은 길이가 0이며, 요소가 존재하지 않습니다.

String 내용을 해석하지 않는 ECMAScript 연산은 추가 의미를 적용하지 않습니다. String 값을 해석하는 연산은 각 요소를 단일 UTF-16 코드 유닛으로 취급합니다. 그러나 ECMAScript는 이 코드 유닛의 값이나 관계를 제한하지 않으므로, 추가적으로 String 내용을 UTF-16로 인코딩된 유니코드 코드 포인트 시퀀스로 해석하는 연산은 잘못된 하위 시퀀스를 고려해야 합니다. 이러한 연산은 다음 규칙에 따라 0xD800~0xDBFF(유니코드 표준에서 선행 서러게이트, 또는 high-surrogate 코드 유닛)와 0xDC00~0xDFFF(후행 서러게이트, 또는 low-surrogate 코드 유닛) 값을 특별 처리합니다:

String.prototype.normalize 함수(22.1.3.15)는 String 값을 명시적으로 정규화하는 데 사용할 수 있습니다. String.prototype.localeCompare(22.1.3.12)는 내부적으로 String 값을 정규화하지만, 다른 연산은 암묵적으로 문자열을 정규화하지 않습니다. 연산 결과가 언어 또는 로케일에 민감하지 않음이 별도로 명시되지 않는 한 적용됩니다.

Note

이 설계의 취지는 문자열 구현을 최대한 단순하고 고성능으로 유지하는 것이었습니다. ECMAScript 소스 텍스트가 Normalized Form C인 경우, 문자열 리터럴은 유니코드 이스케이프 시퀀스를 포함하지 않는 한 정규화가 보장됩니다.

이 명세서에서 "the string-concatenation of A, B, ..."라는 구문(각 인자가 String 값, 코드 유닛, 또는 코드 유닛 시퀀스임)은 인자 각각의 코드 유닛을 차례로 이어붙인 시퀀스로 구성된 String 값을 의미합니다.

"the substring of S from inclusiveStart to exclusiveEnd"(여기서 S는 String 값 또는 코드 유닛 시퀀스, inclusiveStartexclusiveEnd는 정수)라는 구문은 inclusiveStart 인덱스에서 시작하여 exclusiveEnd 바로 앞까지 연속된 코드 유닛으로 구성된 String 값을 의미합니다(inclusiveStart = exclusiveEnd이면 빈 문자열). "to" 접미사가 생략된 경우, S의 길이가 exclusiveEnd로 사용됩니다.

"ASCII word characters"라는 구문은 다음 String 값을 의미하며, 이는 유니코드 Basic Latin 블록 내 모든 문자와 숫자, U+005F(LOW LINE)만으로 구성됩니다:
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_".
역사적 이유로 여러 알고리즘에서 의미를 가집니다.

6.1.4.1 StringIndexOf ( string, searchValue, fromIndex )

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

  1. string의 길이를 len으로 한다.
  2. searchValue가 빈 문자열이고 fromIndexlen이면 fromIndex를 반환한다.
  3. searchValue의 길이를 searchLen으로 한다.
  4. fromIndexilen - searchLen인 각 정수 i에 대해 오름차순으로,
    1. stringi에서 i + searchLen까지의 substringcandidate로 한다.
    2. candidatesearchValue와 같다면 i를 반환한다.
  5. not-found를 반환한다.
Note 1

searchValue가 빈 문자열이고 fromIndexstring의 길이면 이 알고리즘은 fromIndex를 반환합니다. 빈 문자열은 문자열 내 모든 위치(마지막 코드 유닛 뒤 포함)에서 발견된 것으로 간주됩니다.

Note 2

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

6.1.4.2 StringLastIndexOf ( string, searchValue, fromIndex )

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

  1. string의 길이를 len으로 한다.
  2. searchValue의 길이를 searchLen으로 한다.
  3. Assert: fromIndex + searchLenlen.
  4. 0 ≤ ifromIndex인 각 정수 i에 대해 내림차순으로,
    1. stringi에서 i + searchLen까지의 substringcandidate로 한다.
    2. candidatesearchValue와 같다면 i를 반환한다.
  5. not-found를 반환한다.
Note

searchValue가 빈 문자열이면 이 알고리즘은 fromIndex를 반환합니다. 빈 문자열은 문자열 내 모든 위치(마지막 코드 유닛 뒤 포함)에서 발견된 것으로 간주됩니다.

6.1.5 Symbol 타입

Symbol 타입은 Object 프로퍼티의 키로 사용될 수 있는 모든 String이 아닌 값의 집합입니다(6.1.7 참고).

각 Symbol은 고유하며 변하지 않습니다.

각 Symbol에는 불변의 [[Description]] 내부 슬롯이 있으며, 그 값은 String 또는 undefined입니다.

6.1.5.1 잘 알려진 심볼들

잘 알려진 심볼은 이 명세서 알고리즘에서 명시적으로 참조되는 내장 Symbol 값입니다. 일반적으로 이 값들은 명세 알고리즘의 확장 지점 역할을 하는 프로퍼티의 키로 사용됩니다. 별도 명시가 없는 한, 잘 알려진 심볼 값은 모든 realm에서 공유됩니다(9.3 참고).

이 명세서에서는 잘 알려진 심볼을 intrinsic 표기법으로 표기하며, intrinsic은 Table 1에 나열된 값 중 하나입니다.

Note
이전 명세 판에서는 @@name 형식의 표기를 사용하였으며, 현재 판에서는 %Symbol.name%을 사용합니다. 특히 다음 이름들이 사용되었습니다: @@asyncIterator, @@hasInstance, @@isConcatSpreadable, @@iterator, @@match, @@matchAll, @@replace, @@search, @@species, @@split, @@toPrimitive, @@toStringTag, @@unscopables.
Table 1: 잘 알려진 심볼
명세 이름 [[Description]] 값 및 용도
%Symbol.asyncIterator% "Symbol.asyncIterator" 객체의 기본 비동기 이터레이터를 반환하는 메서드. for-await-of 구문의 의미론에 의해 호출됨.
%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 숫자 타입

ECMAScript에는 두 가지 내장 숫자 타입(Number와 BigInt)이 있습니다. 아래 추상 연산들은 이 숫자 타입에 대해 정의되어 있습니다. "결과(Result)" 열은 반환 타입과, 일부 연산 호출이 abrupt completion을 반환할 수 있는지 여부를 나타냅니다.

Table 2: 숫자 타입 연산
연산 예시 소스 평가 의미론에서 호출되는 위치 결과
Number::unaryMinus -x 단항 - 연산자(Unary - Operator) Number
BigInt::unaryMinus BigInt
Number::bitwiseNOT ~x 비트 NOT 연산자(Bitwise NOT Operator) ( ~ ) Number
BigInt::bitwiseNOT BigInt
Number::exponentiate x ** y 거듭제곱 연산자(Exponentiation Operator)Math.pow ( base, exponent ) Number
BigInt::exponentiate 정상 완료(BigInt) 또는 throw completion
Number::multiply x * y 곱셈 연산자(Multiplicative Operators) Number
BigInt::multiply BigInt
Number::divide x / y 곱셈 연산자(Multiplicative Operators) Number
BigInt::divide 정상 완료(BigInt) 또는 throw completion
Number::remainder x % y 곱셈 연산자(Multiplicative Operators) Number
BigInt::remainder 정상 완료(BigInt) 또는 throw completion
Number::add x ++
++ x
x + y
후위 증가 연산자(Postfix Increment Operator), 전위 증가 연산자(Prefix Increment Operator), 덧셈 연산자 ( + ) (The Addition Operator) Number
BigInt::add BigInt
Number::subtract x --
-- x
x - y
후위 감소 연산자(Postfix Decrement Operator), 전위 감소 연산자(Prefix Decrement Operator), 뺄셈 연산자 ( - ) (The Subtraction Operator) Number
BigInt::subtract BigInt
Number::leftShift x << y 왼쪽 시프트 연산자 ( << ) (The Left Shift Operator) Number
BigInt::leftShift BigInt
Number::signedRightShift x >> y 부호 있는 오른쪽 시프트 연산자 ( >> ) (The Signed Right Shift Operator) Number
BigInt::signedRightShift BigInt
Number::unsignedRightShift x >>> y 부호 없는 오른쪽 시프트 연산자 ( >>> ) (The Unsigned Right Shift Operator) Number
BigInt::unsignedRightShift throw completion
Number::lessThan x < y
x > y
x <= y
x >= y
관계 연산자(Relational Operators), IsLessThan ( x, y, LeftFirst ) Boolean 또는 undefined (비정렬 입력)
BigInt::lessThan Boolean
Number::equal x == y
x != y
x === y
x !== y
동등 연산자(Equality Operators), IsStrictlyEqual ( x, y ) Boolean
BigInt::equal
Number::sameValue Object.is(x, y) 객체 내부 메서드, SameValue ( x, y )를 통해, 정확한 값 동등성 검사 Boolean
Number::sameValueZero [x].includes(y) SameValueZero ( x, y )를 통해, 값 동등성 검사, Array, Map, Set 메서드에서 +0𝔽-0𝔽 차이 무시 Boolean
Number::bitwiseAND x & y 이진 비트 연산자(Binary Bitwise Operators) Number
BigInt::bitwiseAND BigInt
Number::bitwiseXOR x ^ y Number
BigInt::bitwiseXOR BigInt
Number::bitwiseOR x | y Number
BigInt::bitwiseOR BigInt
Number::toString String(x) 다양한 표현식 및 내장 함수, ToString ( argument )를 통해 String
BigInt::toString

숫자 타입들은 일반적으로 정밀도 손실이나 절단 없이 변환될 수 없으므로, ECMAScript 언어는 이러한 타입들 간의 암시적 변환을 제공하지 않습니다. 프로그래머는 다른 타입이 필요한 함수를 호출할 때 타입 간 변환을 위해 반드시 NumberBigInt 함수를 명시적으로 호출해야 합니다.

Note

ECMAScript의 최초 및 이후 판들은 일부 연산자에 대해 정밀도 손실이나 절단이 발생할 수 있는 암시적 숫자 변환을 제공해왔습니다. 이러한 기존 암시적 변환은 하위 호환성을 위해 유지되지만, BigInt에는 제공되지 않아 프로그래머의 오류 가능성을 최소화하고, 미래 판에서 일반화된 값 타입 옵션을 열어두기 위함입니다.

6.1.6.1 Number 타입

Number 타입은 정확히 18,437,736,874,454,810,627개(즉, 264 - 253 + 3)의 값을 가지며, 이는 IEEE 이진 부동소수점 산술 표준(IEEE 754-2019)의 binary64의 배정밀도 부동소수점 값을 나타냅니다. 단, IEEE 표준의 9,007,199,254,740,990개(즉, 253 - 2)의 NaN 값들은 ECMAScript에서 하나의 특별한 NaN 값으로 표현됩니다. (NaN 값은 프로그램 표현식 NaN에 의해 생성됩니다.) 일부 구현에서는 외부 코드가 다양한 NaN 값을 구분할 수 있지만, 그러한 동작은 구현 정의입니다. ECMAScript 코드에서는 모든 NaN 값이 서로 구분되지 않습니다.

Note

Number 값이 ArrayBuffer(25.1) 또는 SharedArrayBuffer(25.2)에 저장된 후 관찰될 수 있는 비트 패턴은 ECMAScript 구현이 내부적으로 사용하는 Number 값의 표현과 반드시 같지는 않습니다.

또 다른 두 개의 특별한 값, 양의 무한대음의 무한대가 있습니다. 간결하게 하기 위해, 이 값들은 설명상 각각 +∞𝔽-∞𝔽 기호로도 불립니다. (이 두 무한대 Number 값은 프로그램 표현식 +Infinity(또는 단순히 Infinity) 및 -Infinity에 의해 생성됩니다.)

나머지 18,437,736,874,454,810,624개(즉, 264 - 253)의 값들은 유한 숫자라고 불립니다. 이 중 절반은 양수이고, 절반은 음수입니다. 모든 유한 양의 Number 값에는 같은 크기를 가진 음수 값이 대응됩니다.

양의 0과 음의 0이 모두 존재함을 유의하세요. 설명상 이 값들은 각각 +0𝔽-0𝔽 기호로도 불립니다. (이 두 다른 0 Number 값은 프로그램 표현식 +0(또는 단순히 0) 및 -0에 의해 생성됩니다.)

18,437,736,874,454,810,622개(즉, 264 - 253 - 2)의 유한 0이 아닌 값들은 두 종류로 나뉩니다:

18,428,729,675,200,069,632개(즉, 264 - 254)는 정규화된 형태로, 다음과 같습니다

s × m × 2e

여기서 s는 1 또는 -1, m은 252(포함)에서 253(제외) 사이의 정수, e는 -1074에서 971(포함) 사이의 정수입니다.

나머지 9,007,199,254,740,990개(즉, 253 - 2) 값은 비정규화된 형태로, 다음과 같습니다

s × m × 2e

여기서 s는 1 또는 -1, m은 0(제외)에서 252(제외) 사이의 정수, e는 -1074입니다.

크기가 253 이하인 모든 양의 및 음의 정수가 Number 타입으로 표현 가능합니다. 정수 0은 Number 타입에서 +0𝔽-0𝔽 두 가지 표현을 가집니다.

유한 숫자는 0이 아니며 위에 나타난 두 가지 방식 중 한 가지로 표현될 때 정수 m이 홀수이면 홀수 시그니피컨드를 가집니다. 그렇지 않으면 짝수 시그니피컨드 입니다.

본 명세에서 “x의 Number 값”이라는 구절은 x가 정확한 실수 수량(π와 같은 무리수일 수도 있음)을 나타내는 경우, 다음 방식으로 선택된 Number 값을 의미합니다. Number 타입의 모든 유한 값 집합을 고려하고, -0𝔽를 제거하며, Number 타입으로 표현할 수 없는 두 값을 추가합니다: 21024(즉, +1 × 253 × 2971) 및 -21024(즉, -1 × 253 × 2971). 이 집합에서 x와 가장 가까운 값을 선택합니다. 두 값이 동일하게 가까우면 짝수 시그니피컨드를 가진 값을 선택합니다; 이때 두 추가 값 21024-21024은 짝수 시그니피컨드를 가진 것으로 간주합니다. 마지막으로, 선택된 값이 21024이면 +∞𝔽로, -21024이면 -∞𝔽로, +0𝔽이면 x < 0일 때만 -0𝔽로 바꿉니다; 그 밖의 값은 그대로 사용합니다. 결과가 x의 Number 값입니다. (이 절차는 IEEE 754-2019의 roundTiesToEven 모드와 정확히 일치합니다.)

+∞의 Number 값은 +∞𝔽, -∞의 Number 값은 -∞𝔽입니다.

일부 ECMAScript 연산자는 -231에서 231 - 1까지와 같이 특정 범위의 정수만 처리합니다. 이러한 연산자는 Number 타입의 임의 값을 받아들이지만, 먼저 해당 값을 예상 범위의 정수 값으로 변환합니다. 숫자 변환 연산에 대한 설명은 7.1에서 확인하세요.

6.1.6.1.1 Number::unaryMinus ( x )

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

  1. xNaN이면, NaN을 반환한다.
  2. x의 부호를 반전시킨 Number를 반환한다. 즉, 같은 크기이지만 부호가 반대인 Number를 계산한다.

6.1.6.1.2 Number::bitwiseNOT ( x )

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

  1. oldValue를 ! ToInt32(x)로 한다.
  2. oldValue의 비트 보수를 반환한다. 결과의 수학적 값은 32비트 2의 보수 비트 문자열로 정확히 표현된다.

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 제곱을 한 결과를 구현에 따라 근사한 값을 반환한다. It performs the following steps when called:

  1. exponentNaN이면, NaN을 반환한다.
  2. exponent+0𝔽 또는 -0𝔽이면, 1𝔽을 반환한다.
  3. baseNaN이면, NaN을 반환한다.
  4. base+∞𝔽이면,
    1. exponent > +0𝔽이면 +∞𝔽 반환; 그렇지 않으면 +0𝔽 반환.
  5. base-∞𝔽이면,
    1. exponent > +0𝔽이면,
      1. exponent가 홀수 정수 Number이면 -∞𝔽 반환; 아니면 +∞𝔽 반환.
    2. 그렇지 않으면,
      1. exponent가 홀수 정수 Number이면 -0𝔽 반환; 아니면 +0𝔽 반환.
  6. base+0𝔽이면,
    1. exponent > +0𝔽이면 +0𝔽 반환; 아니면 +∞𝔽 반환.
  7. base-0𝔽이면,
    1. exponent > +0𝔽이면,
      1. exponent가 홀수 정수 Number이면 -0𝔽 반환; 아니면 +0𝔽 반환.
    2. 그렇지 않으면,
      1. exponent가 홀수 정수 Number이면 -∞𝔽 반환; 아니면 +∞𝔽 반환.
  8. 단언: base유한하며 +0𝔽 또는 -0𝔽가 아니다.
  9. exponent+∞𝔽이면,
    1. abs((base)) > 1이면 +∞𝔽 반환.
    2. abs((base)) = 1이면 NaN 반환.
    3. abs((base)) < 1이면 +0𝔽 반환.
  10. exponent-∞𝔽이면,
    1. abs((base)) > 1이면 +0𝔽 반환.
    2. abs((base)) = 1이면 NaN 반환.
    3. abs((base)) < 1이면 +∞𝔽 반환.
  11. 단언: exponent유한하며 +0𝔽 또는 -0𝔽가 아니다.
  12. base < -0𝔽이고 exponent가 정수 Number가 아니면 NaN 반환.
  13. (base)의 (exponent) 제곱을 구현에 따라 근사한 Number 값으로 반환.
Note

base1𝔽 또는 -1𝔽이고 exponent+∞𝔽 또는 -∞𝔽일 때, 혹은 base1𝔽이고 exponentNaN일 때, base ** exponent의 결과는 IEEE 754-2019와 다릅니다. ECMAScript 1판은 이 연산에 대해 NaN 결과를 명시했으나, 이후 IEEE 754 개정판은 1𝔽을 명시했습니다. 호환성을 위해 기존 ECMAScript 동작을 유지합니다.

6.1.6.1.4 Number::multiply ( x, y )

The abstract operation Number::multiply takes arguments x (a Number) and y (a Number) and returns a Number. IEEE 754-2019 배정밀도 이진 산술 규칙에 따라 곱셈을 수행하며, xy의 곱을 생성합니다. It performs the following steps when called:

  1. x 또는 yNaN이면 NaN 반환.
  2. x+∞𝔽 또는 -∞𝔽이면,
    1. y+0𝔽 또는 -0𝔽이면 NaN 반환.
    2. y > +0𝔽이면 x 반환.
    3. -x 반환.
  3. y+∞𝔽 또는 -∞𝔽이면,
    1. x+0𝔽 또는 -0𝔽이면 NaN 반환.
    2. x > +0𝔽이면 y 반환.
    3. -y 반환.
  4. x-0𝔽이면,
    1. y-0𝔽 또는 y < -0𝔽이면 +0𝔽 반환.
    2. 아니면 -0𝔽 반환.
  5. y-0𝔽이면,
    1. x < -0𝔽이면 +0𝔽 반환.
    2. 아니면 -0𝔽 반환.
  6. 𝔽((x) × (y)) 반환.
Note

유한 정밀 곱셈은 교환법칙은 성립하지만 항상 결합법칙이 성립하지는 않습니다.

6.1.6.1.5 Number::divide ( x, y )

The abstract operation Number::divide takes arguments x (a Number) and y (a Number) and returns a Number. IEEE 754-2019 배정밀도 이진 산술 규칙에 따라 나눗셈을 수행하며, x는 피제수, y는 제수로써 몫을 생성합니다. It performs the following steps when called:

  1. x 또는 yNaN이면 NaN 반환.
  2. x+∞𝔽 또는 -∞𝔽이면,
    1. y+∞𝔽 또는 -∞𝔽이면 NaN 반환.
    2. y+0𝔽 또는 y > +0𝔽이면 x 반환.
    3. -x 반환.
  3. y+∞𝔽이면,
    1. x+0𝔽 또는 x > +0𝔽이면 +0𝔽 반환; 아니면 -0𝔽 반환.
  4. y-∞𝔽이면,
    1. x+0𝔽 또는 x > +0𝔽이면 -0𝔽 반환; 아니면 +0𝔽 반환.
  5. x+0𝔽 또는 -0𝔽이면,
    1. y+0𝔽 또는 -0𝔽이면 NaN 반환.
    2. y > +0𝔽이면 x 반환.
    3. -x 반환.
  6. y+0𝔽이면,
    1. x > +0𝔽이면 +∞𝔽 반환; 아니면 -∞𝔽 반환.
  7. y-0𝔽이면,
    1. x > +0𝔽이면 -∞𝔽 반환; 아니면 +∞𝔽 반환.
  8. 𝔽((x) / (y)) 반환.

6.1.6.1.6 Number::remainder ( n, d )

The abstract operation Number::remainder takes arguments n (a Number) and d (a Number) and returns a Number. 피제수 n과 제수 d의 암시적 나눗셈에서 나머지를 반환합니다. It performs the following steps when called:

  1. n 또는 dNaN이면 NaN 반환.
  2. n+∞𝔽 또는 -∞𝔽이면 NaN 반환.
  3. d+∞𝔽 또는 -∞𝔽이면 n 반환.
  4. d+0𝔽 또는 -0𝔽이면 NaN 반환.
  5. n+0𝔽 또는 -0𝔽이면 n 반환.
  6. 단언: nd유한하며 0이 아니다.
  7. quotient(n) / (d)로 한다.
  8. qtruncate(quotient)로 한다.
  9. r(n) - ((d) × q)로 한다.
  10. r = 0이고 n < -0𝔽이면 -0𝔽 반환.
  11. 𝔽(r) 반환.
Note 1

C 및 C++에서 나머지 연산자는 정수 피연산자만 허용하지만, ECMAScript에서는 부동소수점 피연산자도 허용합니다.

Note 2
부동소수점 나머지 연산의 결과는 IEEE 754-2019의 “remainder” 연산과 다릅니다. IEEE 754-2019 “remainder” 연산은 반올림 나눗셈에서 나머지를 계산하며, 일반적인 정수 나머지 연산자와는 유사하지 않습니다. ECMAScript는 부동소수점 연산에서 %가 Java의 정수 나머지 연산자와 유사하게 동작하도록 정의합니다; 이는 C 라이브러리 함수 fmod와 비교할 수 있습니다.

6.1.6.1.7 Number::add ( x, y )

The abstract operation Number::add takes arguments x (a Number) and y (a Number) and returns a Number. IEEE 754-2019 배정밀도 이진 산술 규칙에 따라 덧셈을 수행하며, 두 인자의 합을 생성합니다. It performs the following steps when called:

  1. x 또는 yNaN이면 NaN 반환.
  2. x+∞𝔽이고 y-∞𝔽이면 NaN 반환.
  3. x-∞𝔽이고 y+∞𝔽이면 NaN 반환.
  4. x+∞𝔽 또는 -∞𝔽이면 x 반환.
  5. y+∞𝔽 또는 -∞𝔽이면 y 반환.
  6. 단언: xy는 모두 유한하다.
  7. x-0𝔽이고 y-0𝔽이면 -0𝔽 반환.
  8. 𝔽((x) + (y)) 반환.
Note

유한 정밀 덧셈은 교환법칙은 성립하지만 항상 결합법칙이 성립하지는 않습니다.

6.1.6.1.8 Number::subtract ( x, y )

The abstract operation Number::subtract takes arguments x (a Number) and y (a Number) and returns a Number. 뺄셈을 수행하며, x는 피감수, y는 감수로써 차를 생성합니다. 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. lNum을 ! ToInt32(x)로 한다.
  2. rNum을 ! ToUint32(y)로 한다.
  3. shiftCount(rNum) mod 32로 한다.
  4. lNumshiftCount 비트만큼 왼쪽으로 시프트한 결과를 반환한다. 결과의 수학적 값은 32비트 2의 보수 비트 문자열로 정확히 표현된다.

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. lNum을 ! ToInt32(x)로 한다.
  2. rNum을 ! ToUint32(y)로 한다.
  3. shiftCount(rNum) mod 32로 한다.
  4. lNumshiftCount 비트만큼 부호 확장 우측 시프트한 결과를 반환한다. 최상위 비트가 전파된다. 결과의 수학적 값은 32비트 2의 보수 비트 문자열로 정확히 표현된다.

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. lNum을 ! ToUint32(x)로 한다.
  2. rNum을 ! ToUint32(y)로 한다.
  3. shiftCount(rNum) mod 32로 한다.
  4. lNumshiftCount 비트만큼 0으로 채우며 우측 시프트한 결과를 반환한다. 비워진 비트는 0으로 채워진다. 결과의 수학적 값은 32비트 부호 없는 비트 문자열로 정확히 표현된다.

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. 단언: xy유한하다.
  11. (x) < (y)이면 true 반환; 아니면 false 반환.

6.1.6.1.13 Number::equal ( x, y )

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

  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. xy가 모두 NaN이면 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. xy가 모두 NaN이면 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 (&, ^, 또는 |), x (a Number), and y (a Number) and returns an integral Number. It performs the following steps when called:

  1. lNum을 ! ToInt32(x)로 한다.
  2. rNum을 ! ToInt32(y)로 한다.
  3. lBits(lNum)을 표현하는 32비트 2의 보수 비트 문자열로 한다.
  4. rBits(rNum)을 표현하는 32비트 2의 보수 비트 문자열로 한다.
  5. op&이면,
    1. resultlBitsrBits에 대해 비트 AND 연산한 결과로 한다.
  6. 아니고 op^이면,
    1. resultlBitsrBits에 대해 비트 XOR 연산한 결과로 한다.
  7. 그렇지 않으면,
    1. 단언: op|이다.
    2. resultlBitsrBits에 대해 비트 OR 연산한 결과로 한다.
  8. result가 표현하는 32비트 2의 보수 비트 문자열의 정수에 대한 Number 값을 반환한다.

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. x를 진법 radix를 사용한 위치 기수 체계로 문자열로 표현합니다. 진법 r을 사용할 때 사용되는 숫자들은 "0123456789abcdefghijklmnopqrstuvwxyz"의 앞에서 r개 코드 유닛을 차례로 사용합니다. 크기가 1𝔽 이상인 숫자의 표현에는 결코 앞에 0이 포함되지 않습니다. It performs the following steps when called:

  1. xNaN이면 "NaN" 반환.
  2. x+0𝔽 또는 -0𝔽이면 "0" 반환.
  3. x < -0𝔽이면 "-"Number::toString(-x, radix)를 연결한 문자열 반환.
  4. x+∞𝔽이면 "Infinity" 반환.
  5. n, k, s를 다음 조건을 만족하는 정수로 한다: k ≥ 1, radixk - 1s < radixk, 𝔽(s × radixn - k)가 x이고, k가 가능한 한 작다. ksradix 표현에서 자릿수이고, sradix로 나누어떨어지지 않으며, 최소 자리수가 반드시 결정되는 것은 아니다.
  6. radix ≠ 10이거나 n이 -5에서 21 사이이면,
    1. nk이면,
      1. 다음을 연결한 문자열 반환:
        • sradix 표현에서 k개의 자릿수
        • n - k번 반복된 코드 유닛 0x0030(DIGIT ZERO)
    2. n > 0이면,
      1. 다음을 연결한 문자열 반환:
        • sradix 표현에서 가장 높은 n개의 자릿수
        • 코드 유닛 0x002E(FULL STOP)
        • 남은 k - n개의 자릿수
    3. 그렇지 않으면,
      1. 단언: n ≤ 0이다.
      2. 다음을 연결한 문자열 반환:
        • 코드 유닛 0x0030(DIGIT ZERO)
        • 코드 유닛 0x002E(FULL STOP)
        • -n번 반복된 코드 유닛 0x0030(DIGIT ZERO)
        • sradix 표현에서 k개의 자릿수
  7. 참고: 이 경우 입력은 과학적 E 표기법으로 표현됩니다(예: 1.2e+3).
  8. 단언: radix는 10이다.
  9. n < 0이면,
    1. exponentSign을 코드 유닛 0x002D(HYPHEN-MINUS)로 한다.
  10. 그렇지 않으면,
    1. exponentSign을 코드 유닛 0x002B(PLUS SIGN)로 한다.
  11. k = 1이면,
    1. 다음을 연결한 문자열 반환:
      • s의 한 자릿수 코드 유닛
      • 코드 유닛 0x0065(LATIN SMALL LETTER E)
      • exponentSign
      • abs(n - 1)의 10진수 표현 코드 유닛
  12. 다음을 연결한 문자열 반환:
    • s의 10진수 표현에서 가장 높은 자릿수 코드 유닛
    • 코드 유닛 0x002E(FULL STOP)
    • 남은 k - 1개의 10진수 표현 코드 유닛
    • 코드 유닛 0x0065(LATIN SMALL LETTER E)
    • exponentSign
    • abs(n - 1)의 10진수 표현 코드 유닛
Note 1

다음 관찰은 구현 지침으로 유용할 수 있으나, 본 표준의 규범적 요구 사항은 아닙니다:

  • x가 -0𝔽을 제외한 모든 Number 값이면 ToNumber(ToString(x))는 x이다.
  • s의 최소 자리수는 항상 명시된 요구 조건에 따라 고유하게 결정되는 것은 아니다(위 5 참조).
Note 2

더 정확한 변환을 제공하는 구현의 경우, 아래 대안 버전의 5 단계를 구현 지침으로 사용하는 것을 권장합니다:

  1. n, k, s를 다음 조건을 만족하는 정수로 한다: k ≥ 1, radixk - 1s < radixk, 𝔽(s × radixn - k)가 x이고, k가 가능한 한 작다. 여러 가능성이 있으면, (x)에 근접한 값을 가지는 s를 선택한다. 두 가지 가능성이 있으면 짝수 값을 선택한다. ksradix 표현에서 자릿수이며, sradix로 나누어떨어지지 않는다.
Note 3

ECMAScript 구현자는 David M. Gay가 작성한 부동소수점 숫자의 이진-10진 변환 관련 논문과 코드를 참고할 수 있습니다:

Gay, David M. Correctly Rounded Binary-Decimal and Decimal-Binary Conversions. Numerical Analysis, Manuscript 90-10. AT&T Bell Laboratories (Murray Hill, New Jersey). 1990년 11월 30일.
https://ampl.com/_archive/first-website/REFS/rounding.pdf. 관련 코드:
http://netlib.sandia.gov/fp/dtoa.c
http://netlib.sandia.gov/fp/g_fmt.c 그리고 여러 netlib 미러 사이트에서 확인 가능.

6.1.6.2 BigInt 타입

BigInt 타입은 정수 값을 나타냅니다. 값의 크기는 제한이 없으며 특정 비트 폭에 제한되지 않습니다. 별도 언급이 없는 한, 연산들은 일반적으로 정확한 수학적 결과를 반환하도록 설계되었습니다. 이항 연산에서 BigInt는 2의 보수 이진 문자열처럼 동작하며, 음수는 비트가 왼쪽으로 무한히 설정된 것으로 취급됩니다.

6.1.6.2.1 BigInt::unaryMinus ( x )

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

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

6.1.6.2.2 BigInt::bitwiseNOT ( x )

The abstract operation BigInt::bitwiseNOT takes argument x (a BigInt) and returns a BigInt. x의 1의 보수를 반환합니다. It performs the following steps when called:

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

6.1.6.2.3 BigInt::exponentiate ( base, exponent )

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

  1. exponent < 0이면, RangeError 예외를 throw한다.
  2. base = 0이고 exponent = 0이면, 1를 반환한다.
  3. baseexponent 제곱을 반환한다.

6.1.6.2.4 BigInt::multiply ( x, y )

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

  1. x × y를 반환한다.
Note
결과가 입력보다 훨씬 큰 비트 폭을 갖더라도, 정확한 수학적 결과가 반환됩니다.

6.1.6.2.5 BigInt::divide ( x, y )

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

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

6.1.6.2.6 BigInt::remainder ( n, d )

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

  1. d = 0이면, RangeError 예외를 throw한다.
  2. n = 0이면, 0를 반환한다.
  3. quotient(n) / (d)로 한다.
  4. q(truncate(quotient))로 한다.
  5. n - (d × q)를 반환한다.
Note
결과의 부호는 피제수의 부호와 같습니다.

6.1.6.2.7 BigInt::add ( x, y )

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

  1. x + y를 반환한다.

6.1.6.2.8 BigInt::subtract ( x, y )

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

  1. x - y를 반환한다.

6.1.6.2.9 BigInt::leftShift ( x, y )

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

  1. y < 0이면,
    1. (floor((x) / 2-(y)))를 반환한다.
  2. x × 2y를 반환한다.
Note
이 의미는 BigInt를 무한 길이 2의 보수 이진 숫자열로 취급하여 비트 시프트와 동등해야 합니다.

6.1.6.2.10 BigInt::signedRightShift ( x, y )

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

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

6.1.6.2.11 BigInt::unsignedRightShift ( x, y )

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

  1. TypeError 예외를 throw한다.

6.1.6.2.12 BigInt::lessThan ( x, y )

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

  1. (x) < (y)이면 true 반환; 아니면 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 반환; 아니면 false 반환.

6.1.6.2.14 BinaryAnd ( x, y )

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

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

6.1.6.2.15 BinaryOr ( x, y )

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

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

6.1.6.2.16 BinaryXor ( x, y )

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

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

6.1.6.2.17 BigIntBitwiseOp ( op, x, y )

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

  1. x(x)로 설정한다.
  2. y(y)로 설정한다.
  3. result를 0으로 설정한다.
  4. shift를 0으로 설정한다.
  5. (x = 0 또는 x = -1)이고 (y = 0 또는 y = -1)일 때까지 반복한다.
    1. xDigitx mod 2로 한다.
    2. yDigity mod 2로 한다.
    3. op&이면,
      1. resultresult + 2shift × BinaryAnd(xDigit, yDigit)로 설정한다.
    4. 아니고 op|이면,
      1. resultresult + 2shift × BinaryOr(xDigit, yDigit)로 설정한다.
    5. 그렇지 않으면,
      1. 단언: op^이다.
      2. resultresult + 2shift × BinaryXor(xDigit, yDigit)로 설정한다.
    6. shiftshift + 1로 설정한다.
    7. x를 (x - xDigit) / 2로 설정한다.
    8. y를 (y - yDigit) / 2로 설정한다.
  6. op&이면,
    1. tmpBinaryAnd(x mod 2, y mod 2)로 한다.
  7. 아니고 op|이면,
    1. tmpBinaryOr(x mod 2, y mod 2)로 한다.
  8. 그렇지 않으면,
    1. 단언: op^이다.
    2. tmpBinaryXor(x mod 2, y mod 2)로 한다.
  9. tmp ≠ 0이면,
    1. resultresult - 2shift로 설정한다.
    2. 참고: 이는 부호 확장입니다.
  10. result에 대한 BigInt 값을 반환한다.

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. x를 진법 radix를 사용한 위치 기수 체계로 문자열로 표현합니다. 진법 r을 사용할 때 사용되는 숫자들은 "0123456789abcdefghijklmnopqrstuvwxyz"의 앞에서 r개 코드 유닛을 차례로 사용합니다. 0을 제외한 BigInt의 표현에는 결코 앞에 0이 포함되지 않습니다. It performs the following steps when called:

  1. x < 0이면 "-"BigInt::toString(-x, radix)를 연결한 문자열을 반환한다.
  2. xradix로 표현한 문자열 값을 반환한다.

6.1.7 Object 타입

Object 타입의 각 인스턴스(간단히 “객체”라고도 함)는 프로퍼티들의 집합을 나타냅니다. 각 프로퍼티는 데이터 프로퍼티 또는 접근자 프로퍼티입니다:

  • 데이터 프로퍼티는 키 값과 ECMAScript 언어 값, 그리고 불리언 속성 집합을 연관시킵니다.
  • 접근자 프로퍼티는 키 값과 하나 또는 두 개의 접근자 함수, 그리고 불리언 속성 집합을 연관시킵니다. 접근자 함수는 해당 프로퍼티에 연관된 ECMAScript 언어 값을 저장하거나 가져오는 데 사용됩니다.

객체의 프로퍼티는 프로퍼티 키를 사용하여 고유하게 식별됩니다. 프로퍼티 키는 문자열 또는 심볼입니다. 모든 문자열과 심볼(빈 문자열 포함)은 프로퍼티 키로 유효합니다. 프로퍼티 이름은 문자열인 프로퍼티 키입니다.

정수 인덱스CanonicalNumericIndexString(n)이 +0𝔽에서 𝔽(253 - 1)까지(포함)의 정수 Number를 반환하는 프로퍼티 이름 n입니다. 배열 인덱스CanonicalNumericIndexString(n)이 +0𝔽에서 𝔽(232 - 2)까지(포함)의 정수 Number를 반환하는 정수 인덱스 n입니다.

Note

모든 음수가 아닌 안전한 정수는 해당하는 정수 인덱스를 가집니다. 32비트 부호 없는 정수 중 232 - 1을 제외한 모든 값은 해당하는 배열 인덱스를 가집니다. "-0"정수 인덱스배열 인덱스도 아닙니다.

프로퍼티 키는 프로퍼티와 그 값을 접근하는 데 사용됩니다. 프로퍼티 접근 방식에는 값을 가져오는 get과 값을 할당하는 set 두 가지가 있습니다. get과 set 접근으로 접근 가능한 프로퍼티에는 객체의 직접적인 일부인 자체 프로퍼티와 프로퍼티 상속 관계를 통해 다른 연관 객체로부터 제공받는 상속 프로퍼티가 포함됩니다. 상속 프로퍼티는 연관 객체의 자체 프로퍼티 또는 상속 프로퍼티일 수 있습니다. 각 객체의 자체 프로퍼티는 해당 객체의 다른 자체 프로퍼티의 키 값과 구별되는 키 값을 가져야 합니다.

모든 객체는 논리적으로 프로퍼티의 집합이지만, 프로퍼티 접근과 조작의 의미론이 다른 여러 형태의 객체가 존재합니다. 여러 형태의 객체 정의는 6.1.7.2를 참고하세요.

또한 일부 객체는 호출 가능하며, 이러한 객체를 함수 또는 함수 객체라고 하며 아래에서 추가로 설명합니다. ECMAScript의 모든 함수는 Object 타입의 멤버입니다.

6.1.7.1 프로퍼티 속성

속성은 Table 3에 설명된 Object 프로퍼티의 상태를 정의하고 설명하는 데 사용됩니다. 명시적으로 지정되지 않는 한, 각 속성의 초기값은 기본값입니다.

Table 3: Object 프로퍼티의 속성
속성 이름 해당되는 프로퍼티 종류 값 도메인 기본값 설명
[[Value]] 데이터 프로퍼티 ECMAScript 언어 값 undefined get 접근으로 프로퍼티에서 가져오는 값입니다.
[[Writable]] 데이터 프로퍼티 불리언 false false인 경우, ECMAScript 코드가 [[Set]]을 사용하여 [[Value]] 속성을 변경하려고 해도 성공하지 않습니다.
[[Get]] 접근자 프로퍼티 Object 또는 undefined undefined 값이 Object인 경우, 반드시 함수 객체여야 합니다. get 접근 시마다 해당 함수의 [[Call]] 내부 메소드(Table 5)가 빈 인자 리스트로 호출되어 프로퍼티 값을 가져옵니다.
[[Set]] 접근자 프로퍼티 Object 또는 undefined undefined 값이 Object인 경우, 반드시 함수 객체여야 합니다. set 접근 시마다 해당 함수의 [[Call]] 내부 메소드(Table 5)가 할당 값을 유일한 인자로 포함하는 인자 리스트로 호출됩니다. 프로퍼티의 [[Set]] 내부 메소드 효과는, 반드시 그런 것은 아니지만, 이후 [[Get]] 내부 메소드 호출에서 반환되는 값에 영향을 줄 수 있습니다.
[[Enumerable]] 데이터 프로퍼티 또는 접근자 프로퍼티 불리언 false true인 경우, for-in 열거(see 14.7.5)에 의해 프로퍼티가 열거됩니다. 그렇지 않으면 비열거 프로퍼티라고 합니다.
[[Configurable]] 데이터 프로퍼티 또는 접근자 프로퍼티 불리언 false false인 경우, 프로퍼티 삭제, 데이터 프로퍼티에서 접근자 프로퍼티로의 변경 또는 그 반대, 속성 변경(기존 [[Value]] 교체 또는 [[Writable]]false로 설정하는 경우 제외)은 모두 실패합니다.

6.1.7.2 Object 내부 메소드와 내부 슬롯

ECMAScript에서 객체의 실제 의미론은 내부 메소드라 불리는 알고리즘을 통해 지정됩니다. ECMAScript 엔진의 각 객체는 런타임 행동을 정의하는 내부 메소드 집합과 연결되어 있습니다. 이러한 내부 메소드는 ECMAScript 언어의 일부가 아닙니다. 이 명세에서는 순전히 설명 목적으로 정의됩니다. 하지만 ECMAScript 구현 내의 각 객체는 해당 객체에 연결된 내부 메소드로 지정된 대로 동작해야 합니다. 이를 구현하는 정확한 방법은 구현에 따라 결정됩니다.

내부 메소드 이름은 다형적입니다. 즉, 서로 다른 객체 값이 동일한 내부 메소드 이름이 호출될 때 서로 다른 알고리즘을 실행할 수 있습니다. 내부 메소드가 호출되는 실제 객체는 호출의 “대상”입니다. 런타임에 알고리즘 구현이 객체가 지원하지 않는 내부 메소드를 사용하려 하면 TypeError 예외가 발생합니다.

내부 슬롯은 객체, 심볼, 또는 Private Name에 연결된 내부 상태로, 여러 ECMAScript 명세 알고리즘에서 사용됩니다. 내부 슬롯은 객체 프로퍼티가 아니며 상속되지 않습니다. 내부 슬롯 명세에 따라 해당 상태는 ECMAScript 언어의 모든 타입 값이나 특정 ECMAScript 명세 타입 값일 수 있습니다. 명시적으로 달리 지정되지 않는 한, 내부 슬롯은 객체, 심볼, 또는 Private Name 생성 과정에서 할당되며 동적으로 추가할 수 없습니다. 별도 지정이 없는 한, 내부 슬롯의 초기값은 undefined입니다. 이 명세의 여러 알고리즘은 내부 슬롯을 가진 값을 생성합니다. 하지만 ECMAScript 언어는 내부 슬롯을 직접 조작할 방법을 제공하지 않습니다.

모든 객체는 [[PrivateElements]]라는 내부 슬롯을 가지며, 이는 PrivateElements의 리스트입니다. 이 리스트는 객체의 private 필드, 메소드, 접근자의 값을 나타냅니다. 초기에는 빈 리스트입니다.

내부 메소드와 내부 슬롯은 이 명세에서 [[ ]]로 둘러싼 이름으로 식별됩니다.

Table 4는 ECMAScript 코드로 생성하거나 조작하는 모든 객체에 적용되는 필수 내부 메소드를 요약합니다. 모든 객체는 모든 필수 내부 메소드에 대한 알고리즘을 가져야 합니다. 하지만 모든 객체가 반드시 동일한 알고리즘을 사용하는 것은 아닙니다.

일반 객체는 다음 기준을 모두 만족하는 객체입니다:

  • Table 4에 나열된 내부 메소드에 대해 10.1에 정의된 메소드를 사용합니다.
  • 객체에 [[Call]] 내부 메소드가 있으면, 10.2.1 또는 10.3.1에 정의된 것 중 하나를 사용합니다.
  • 객체에 [[Construct]] 내부 메소드가 있으면, 10.2.2 또는 10.3.2에 정의된 것 중 하나를 사용합니다.

이국 객체일반 객체가 아닌 객체입니다.

이 명세는 내부 메소드에 따라 여러 종류의 이국 객체를 인식합니다. 특정 종류의 이국 객체(Array 이국 객체, 바운드 함수 이국 객체 등)와 행동적으로 동등하지만 해당 종류에 대해 명세된 내부 메소드 집합이 동일하지 않은 객체는 해당 종류의 이국 객체로 인식되지 않습니다.

Table 4 및 유사한 표의 “서명(Signature)” 열은 각 내부 메소드의 호출 패턴을 설명합니다. 호출 패턴에는 항상 괄호로 둘러싼 설명적 매개변수 이름 목록이 포함됩니다. 매개변수 이름이 ECMAScript 타입 이름과 같다면 해당 타입의 값이어야 함을 의미합니다. 내부 메소드가 명시적으로 값을 반환하면, 매개변수 목록 뒤에 “→”와 반환 타입 이름이 따라옵니다. 서명에서 사용된 타입 이름은 6에서 정의된 타입에, 아래 추가 이름이 보강된 것입니다. “any”는 값이 ECMAScript 언어 타입 중 아무거나 될 수 있음을 의미합니다.

내부 메소드는 매개변수 외에도 항상 해당 메소드 호출의 대상 객체에 접근할 수 있습니다.

내부 메소드는 암시적으로 Completion Record를 반환하며, 반환 타입에 표시된 값을 감싼 정상 완료 또는 throw 완료입니다.

Table 4: 필수 내부 메소드
내부 메소드 서명(Signature) 설명
[[GetPrototypeOf]] ( ) Object | Null 이 객체의 상속 프로퍼티를 제공하는 객체를 결정합니다. null 값이면 상속 프로퍼티가 없음을 의미합니다.
[[SetPrototypeOf]] (Object | Null) Boolean 이 객체를 상속 프로퍼티를 제공하는 다른 객체와 연결합니다. null을 전달하면 상속 프로퍼티가 없음을 의미합니다. 연산이 성공적으로 완료되면 true, 실패하면 false를 반환합니다.
[[IsExtensible]] ( ) Boolean 이 객체에 추가 프로퍼티를 추가할 수 있는지 결정합니다.
[[PreventExtensions]] ( ) Boolean 객체에 새 프로퍼티를 추가할 수 있는지 제어합니다. 연산이 성공하면 true, 실패하면 false를 반환합니다.
[[GetOwnProperty]] (propertyKey) Undefined | Property Descriptor 이 객체의 키가 propertyKey인 자체 프로퍼티에 대한 프로퍼티 설명자를 반환하거나, 해당 프로퍼티가 없으면 undefined를 반환합니다.
[[DefineOwnProperty]] (propertyKey, PropertyDescriptor) Boolean 키가 propertyKey인 자체 프로퍼티를 생성하거나 상태를 PropertyDescriptor로 변경합니다. 프로퍼티가 성공적으로 생성/업데이트되면 true, 생성/업데이트할 수 없으면 false를 반환합니다.
[[HasProperty]] (propertyKey) Boolean 이 객체에 propertyKey인 자체 또는 상속 프로퍼티가 이미 있는지 불리언 값으로 반환합니다.
[[Get]] (propertyKey, Receiver) any 이 객체에서 키가 propertyKey인 프로퍼티의 값을 반환합니다. 프로퍼티 값을 가져오려면 ECMAScript 코드 실행이 필요할 수 있으며, 그 경우 Receiver가 코드 평가 시 this 값으로 사용됩니다.
[[Set]] (propertyKey, value, Receiver) Boolean 키가 propertyKey인 프로퍼티 값을 value로 설정합니다. ECMAScript 코드 실행이 필요하면, Receiverthis 값으로 사용됩니다. 값이 설정되면 true, 설정할 수 없으면 false를 반환합니다.
[[Delete]] (propertyKey) Boolean 키가 propertyKey인 자체 프로퍼티를 객체에서 제거합니다. 프로퍼티가 삭제되지 않고 여전히 존재하면 false, 삭제되었거나 존재하지 않으면 true를 반환합니다.
[[OwnPropertyKeys]] ( ) 프로퍼티 키 리스트 객체에 대한 모든 자체 프로퍼티 키를 요소로 하는 리스트를 반환합니다.

Table 5는 함수로 호출 가능한 객체가 지원하는 추가 필수 내부 메소드를 요약합니다. 함수 객체[[Call]] 내부 메소드를 지원하는 객체입니다. 생성자[[Construct]] 내부 메소드를 지원하는 객체입니다. [[Construct]]를 지원하는 모든 객체는 [[Call]]도 지원해야 하며, 즉 생성자는 항상 함수 객체입니다. 따라서 생성자생성자 함수 또는 생성자 함수 객체라고도 부를 수 있습니다.

Table 5: 함수 객체의 추가 필수 내부 메소드
내부 메소드 서명(Signature) 설명
[[Call]] (any, any의 리스트) any 이 객체와 연관된 코드를 실행합니다. 함수 호출 표현식으로 호출됩니다. 내부 메소드의 인자는 this 값과 함수 호출 표현식에서 전달된 인자를 요소로 하는 리스트입니다. 이 내부 메소드를 구현한 객체는 호출 가능합니다.
[[Construct]] (any의 리스트, Object) Object 객체를 생성합니다. new 연산자나 super 호출로 호출됩니다. 내부 메소드의 첫 번째 인자는 생성자 호출 또는 super 호출의 인자 리스트이고, 두 번째 인자는 new 연산자가 최초로 적용된 객체입니다. 이 내부 메소드를 구현한 객체는 생성자입니다. 함수 객체가 반드시 생성자인 것은 아니며, 생성자가 아닌 함수 객체[[Construct]] 내부 메소드가 없습니다.

일반 객체 및 표준 이국 객체의 필수 내부 메소드 의미론은 10에서 지정됩니다. 구현에서 이국 객체의 내부 메소드 사용이 지원되지 않는 경우, 해당 사용 시 TypeError 예외를 throw해야 합니다.

6.1.7.3 필수 내부 메소드의 불변성

ECMAScript 엔진의 객체 내부 메소드는 아래에 명시된 불변성 목록을 준수해야 합니다. 일반 ECMAScript 객체와 이 명세의 모든 표준 이국 객체는 이 불변성을 유지합니다. ECMAScript Proxy 객체는 [[ProxyHandler]] 객체의 트랩 결과에 대한 런타임 검사를 통해 이 불변성을 유지합니다.

구현에서 제공하는 이국 객체도 해당 객체에 대해 이 불변성을 유지해야 합니다. 이 불변성을 위반하면 ECMAScript 코드의 예측 불가능한 동작이나 보안 문제를 일으킬 수 있습니다. 그러나 이 불변성 위반으로 구현의 메모리 안전성이 훼손되어서는 안 됩니다.

이 불변성을 필수 내부 메소드의 기능을 대체하는 대체 인터페이스를 제공하는 등 어떤 방식으로든 우회하도록 허용해서는 안 됩니다.

정의:

  • 내부 메소드의 대상(target)은 내부 메소드가 호출되는 객체입니다.
  • 대상이 [[IsExtensible]] 내부 메소드에서 false를 반환하거나 [[PreventExtensions]] 내부 메소드에서 true를 반환한 것으로 관찰되면, 비확장 대상입니다.
  • 존재하지 않는(non-existent) 프로퍼티는 비확장 대상에 자체 프로퍼티로 존재하지 않는 프로퍼티입니다.
  • SameValue에 대한 모든 참조는 SameValue 알고리즘 정의를 따릅니다.

반환값:

모든 내부 메소드가 반환하는 값은 다음 중 하나인 Completion Record여야 합니다:

  • [[Type]] = normal, [[Target]] = empty, 그리고 [[Value]]가 해당 내부 메소드의 “정상 반환 타입”에 표시된 값
  • [[Type]] = throw, [[Target]] = empty, 그리고 [[Value]]ECMAScript 언어 값
Note 1

내부 메소드는 continue, break, return 완료를 반환하면 안 됩니다.

[[GetPrototypeOf]] ( )

  • 정상 반환 타입은 Object 또는 Null입니다.
  • 대상이 비확장 상태이고 [[GetPrototypeOf]]가 값 V를 반환하면, 이후 [[GetPrototypeOf]] 호출은 항상 VSameValue여야 합니다.
Note 2

객체의 프로토타입 체인은 유한 길이를 가져야 합니다(즉, 어떤 객체에서 시작해서 [[GetPrototypeOf]] 내부 메소드를 재귀적으로 적용하면 결국 null에 도달해야 함). 하지만 프로토타입 체인에 일반 객체 정의를 사용하지 않는 이국 객체가 포함되면, 이 요구사항은 객체 수준 불변성으로 강제할 수 없습니다. 이런 순환 프로토타입 체인은 객체 프로퍼티 접근 시 무한 루프를 유발할 수 있습니다.

[[SetPrototypeOf]] ( V )

  • 정상 반환 타입은 Boolean입니다.
  • 대상이 비확장 상태면, [[SetPrototypeOf]]V가 대상의 [[GetPrototypeOf]]로 관찰된 값과 SameValue가 아니면 반드시 false를 반환해야 합니다.

[[IsExtensible]] ( )

  • 정상 반환 타입은 Boolean입니다.
  • [[IsExtensible]]false를 반환하면, 이후 해당 대상에서 [[IsExtensible]]은 반드시 false를 반환해야 합니다.

[[PreventExtensions]] ( )

  • 정상 반환 타입은 Boolean입니다.
  • [[PreventExtensions]]true를 반환하면, 이후 해당 대상에서 [[IsExtensible]]은 반드시 false를 반환해야 하며, 이제 대상은 비확장 상태로 간주됩니다.

[[GetOwnProperty]] ( P )

  • 정상 반환 타입은 Property Descriptor 또는 Undefined입니다.
  • 반환값이 프로퍼티 설명자이면, 반드시 완전히 채워진 설명자여야 합니다.
  • P가 비구성, 비쓰기 자체 데이터 프로퍼티로 기술된 경우, 이후 [[GetOwnProperty]] ( P ) 호출은 반드시 P[[Value]]SameValue[[Value]] 속성을 가진 설명자를 반환해야 합니다.
  • P[[Writable]], [[Value]] 외의 속성이 시간에 따라 변경될 수 있거나 프로퍼티가 삭제될 수 있으면, P[[Configurable]] 속성은 반드시 true여야 합니다.
  • [[Writable]] 속성이 false에서 true로 변할 수 있다면, [[Configurable]] 속성은 반드시 true여야 합니다.
  • 대상이 비확장 상태이고 P가 존재하지 않는 프로퍼티면, 이후 해당 대상에서 [[GetOwnProperty]] (P)는 반드시 P를 존재하지 않는 것으로 기술해야 합니다(즉, [[GetOwnProperty]] (P)는 undefined를 반환해야 함).
Note 3

세 번째 불변성의 결과로, 데이터 프로퍼티로 기술된 프로퍼티가 시간에 따라 다른 값을 반환할 수 있으면, 다른 메소드에서 값을 변경하는 메커니즘이 노출되지 않아도 [[Writable]][[Configurable]] 중 하나 또는 둘 다 반드시 true여야 합니다.

[[DefineOwnProperty]] ( P, Desc )

  • 정상 반환 타입은 Boolean입니다.
  • [[DefineOwnProperty]]P가 이전에 대상의 비구성 자체 프로퍼티로 관찰된 경우, 다음 중 하나가 아니면 반드시 false를 반환해야 합니다:
    1. P가 쓰기 가능한 데이터 프로퍼티이다. 비구성 쓰기 가능 데이터 프로퍼티는 비구성 비쓰기 데이터 프로퍼티로 변경될 수 있다.
    2. Desc의 모든 속성이 P의 속성과 SameValue이다.
  • [[DefineOwnProperty]] (P, Desc)는 대상이 비확장 상태이고 P가 존재하지 않는 자체 프로퍼티이면 반드시 false를 반환해야 합니다. 즉, 비확장 대상 객체는 새 프로퍼티로 확장될 수 없습니다.

[[HasProperty]] ( P )

  • 정상 반환 타입은 Boolean입니다.
  • P가 이전에 대상의 비구성 자체 데이터 또는 접근자 프로퍼티로 관찰된 경우, [[HasProperty]]는 반드시 true를 반환해야 합니다.

[[Get]] ( P, Receiver )

  • 정상 반환 타입은 ECMAScript 언어의 어떤 타입이든 가능합니다.
  • P가 대상의 비구성, 비쓰기 자체 데이터 프로퍼티로 관찰된 값 V이면, [[Get]]은 반드시 VSameValue를 반환해야 합니다.
  • P가 대상의 비구성 자체 접근자 프로퍼티로 관찰되고 [[Get]] 속성이 undefined이면, [[Get]] 연산은 반드시 undefined를 반환해야 합니다.

[[Set]] ( P, V, Receiver )

  • 정상 반환 타입은 Boolean입니다.
  • P가 대상의 비구성, 비쓰기 자체 데이터 프로퍼티로 관찰된 경우, [[Set]]VP[[Value]] 속성과 SameValue가 아니면 반드시 false를 반환해야 합니다.
  • P가 대상의 비구성 자체 접근자 프로퍼티로 관찰되고 [[Set]] 속성이 undefined이면, [[Set]] 연산은 반드시 false를 반환해야 합니다.

[[Delete]] ( P )

  • 정상 반환 타입은 Boolean입니다.
  • P가 대상의 비구성 자체 데이터 또는 접근자 프로퍼티로 관찰된 경우, [[Delete]]는 반드시 false를 반환해야 합니다.

[[OwnPropertyKeys]] ( )

  • 정상 반환 타입은 리스트입니다.
  • 반환된 리스트에는 중복 항목이 포함되면 안 됩니다.
  • 반환된 리스트의 각 요소는 프로퍼티 키여야 합니다.
  • 반환된 리스트에는 이전에 관찰된 모든 비구성 자체 프로퍼티의 키가 반드시 포함되어야 합니다.
  • 대상이 비확장 상태면, 반환된 리스트에는 [[GetOwnProperty]]로 관찰 가능한 대상의 모든 자체 프로퍼티 키만 포함되어야 합니다.

[[Call]] ( )

  • 정상 반환 타입은 ECMAScript 언어의 어떤 타입이든 가능합니다.

[[Construct]] ( )

  • 정상 반환 타입은 Object입니다.
  • 대상은 반드시 [[Call]] 내부 메소드도 가져야 합니다.

6.1.7.4 잘 알려진 내장 객체

잘 알려진 내장 객체는 이 명세의 알고리즘에서 명시적으로 참조되는 내장 객체이며, 일반적으로 realm별로 별도의 정체성을 가집니다. 별도 지정이 없는 한, 각 내장 객체는 실제로 realm별로 하나씩 유사한 객체 집합에 해당합니다.

이 명세 내에서 %name%과 같은 참조는 현재 realm과 연결된 해당 이름의 내장 객체를 의미합니다. %name.a.b%와 같은 참조는, 어떤 ECMAScript 코드가 평가되기 전에 내장 객체 %name%의 "a" 프로퍼티 값의 "b" 프로퍼티 값에 접근한 것과 같습니다. 현재 realm 및 그 내장 객체 결정 방법은 9.4에 설명되어 있습니다. 잘 알려진 내장 객체 목록은 Table 6에 나와 있습니다.

Table 6: 잘 알려진 내장 객체
내장 객체 이름 글로벌 이름 ECMAScript 언어 연관
%AggregateError% AggregateError AggregateError 생성자 (20.5.7.1)
%Array% Array Array 생성자 (23.1.1)
%ArrayBuffer% ArrayBuffer ArrayBuffer 생성자 (25.1.4)
%ArrayIteratorPrototype% Array Iterator 객체의 프로토타입 (23.1.5)
%AsyncFromSyncIteratorPrototype% Async-from-Sync Iterator 객체의 프로토타입 (27.1.6)
%AsyncFunction% async 함수 객체생성자 (27.7.1)
%AsyncGeneratorFunction% async generator 함수 객체생성자 (27.4.1)
%AsyncGeneratorPrototype% async generator 객체의 프로토타입 (27.6)
%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)
%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.3.1)
%GeneratorPrototype% generator 객체의 프로토타입 (27.5)
%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.2.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)
%Symbol% Symbol Symbol 생성자 (20.4.1)
%SyntaxError% SyntaxError SyntaxError 생성자 (20.5.5.4)
%ThrowTypeError% 무조건 새로운 %TypeError% 인스턴스를 throw하는 함수 객체
%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.1.1)
Note

Table 100에 추가 항목이 있습니다.

6.2 ECMAScript 명세 타입

명세 타입은 ECMAScript 언어 구조와 ECMAScript 언어 타입의 의미론을 설명하기 위해 알고리즘 내에서 사용되는 메타 값에 해당합니다. 명세 타입에는 Reference Record, List, Completion Record, Property Descriptor, Environment Record, Abstract Closure, Data Block이 포함됩니다. 명세 타입 값은 ECMAScript 구현 내의 특정 엔티티에 반드시 대응하지는 않는 명세 산출물입니다. 명세 타입 값은 ECMAScript 표현식 평가의 중간 결과를 설명하는 데 사용할 수 있지만, 이러한 값은 객체의 프로퍼티나 ECMAScript 언어 변수의 값으로 저장될 수 없습니다.

6.2.1 Enum 명세 타입

Enum은 명세 내부에서만 사용되며 ECMAScript 코드에서는 직접적으로 관찰할 수 없는 값입니다. Enum은 sans-serif 서체로 표시됩니다. 예를 들어, Completion Record[[Type]] 필드는 normal, return, throw와 같은 값을 가집니다. Enum은 이름 이외의 특징을 가지지 않습니다. Enum의 이름은 다른 Enum과 구별하기 위함이며, 그 사용이나 의미를 암시하지 않습니다.

6.2.2 List와 Record 명세 타입

List 타입은 new 표현식, 함수 호출, 그 외 값의 단순 순서 리스트가 필요한 알고리즘에서 인자 리스트 평가를 설명하는 데 사용됩니다(13.3.8 참조). List 타입의 값은 각 개별 값을 담고 있는 리스트 요소들의 순서 있는 시퀀스입니다. 이 시퀀스는 길이에 제한이 없습니다. 리스트의 요소는 0부터 시작하는 인덱스로 임의 접근할 수 있습니다. 표기상의 편의를 위해 배열과 유사한 문법으로 List 요소에 접근할 수 있습니다. 예를 들어, arguments[2]는 List arguments의 3번째 요소를 의미합니다.

알고리즘이 List의 요소를 반복할 때 순서를 지정하지 않으면 List 요소의 순서대로 사용됩니다.

이 명세에서는 리터럴 문법을 사용해 새로운 List 값을 표현할 수 있습니다. 예를 들어, « 1, 2 »는 두 개의 요소를 특정 값으로 초기화한 List 값을 정의합니다. 새로운 빈 List는 « »로 표현할 수 있습니다.

이 명세에서 “the list-concatenation of A, B, ...”(각 인자가 비어 있을 수도 있는 List)라는 표현은 각 인자(순서대로)의 요소를 이어붙인(순서대로) 새로운 List 값을 의미합니다.

List가 String 요소로 구성된 경우 “sorted according to lexicographic code unit order”란, IsLessThan 추상 연산에서 설명한 대로, 짧은 문자열 길이까지 각 코드 유닛의 숫자값으로 정렬하며, 모든 코드 유닛이 같으면 짧은 문자열이 긴 문자열보다 먼저 오도록 정렬한다는 뜻입니다.

Record 타입은 이 명세의 알고리즘 내에서 데이터 집합을 설명하는 데 사용됩니다. Record 타입 값은 하나 이상의 이름 있는 필드로 구성됩니다. 각 필드의 값은 ECMAScript 언어 값 또는 명세 값입니다. 필드 이름은 항상 [[ ]]로 둘러싸입니다(예: [[Value]]).

이 명세에서는 객체 리터럴과 유사한 문법으로 Record 값을 표현할 수 있습니다. 예를 들어, { [[Field1]]: 42, [[Field2]]: false, [[Field3]]: empty }는 세 개의 필드가 각각 특정 값으로 초기화된 Record 값을 정의합니다. 필드 이름의 순서는 중요하지 않습니다. 명시적으로 나열되지 않은 필드는 없는 것으로 간주합니다.

명세 텍스트와 알고리즘에서 점 표기법으로 Record 값의 특정 필드를 참조할 수 있습니다. 예를 들어, 위의 예시 Record R에 대해 R.[[Field2]]는 “R의 [[Field2]] 필드”를 의미합니다.

자주 사용되는 Record 필드 조합에 대해 스키마 이름을 붙일 수 있으며, 그 이름을 리터럴 Record 값에 접두어로 사용해 특정 집합의 집계임을 명시할 수 있습니다. 예: PropertyDescriptor { [[Value]]: 42, [[Writable]]: false, [[Configurable]]: true }.

6.2.3 Set과 Relation 명세 타입

Set 타입은 메모리 모델에서 사용될 무순서 요소 집합을 설명하는 데 사용됩니다. ECMAScript 컬렉션 타입 Set과는 다릅니다. 혼동을 피하기 위해, 명세에서는 ECMAScript 컬렉션 인스턴스를 “Set 객체”라고 일관되게 부릅니다. Set 타입 값은 중복 없는 간단한 요소 집합입니다. 요소는 추가·제거할 수 있으며, Set끼리 합집합·교집합·차집합 연산이 가능합니다.

Relation 타입은 Set에 대한 제약을 설명하는 데 사용됩니다. Relation 타입 값은 값 도메인에서 가져온 순서쌍의 Set입니다. 예를 들어, 이벤트에 대한 Relation은 이벤트들의 순서쌍 집합입니다. Relation R과 값 도메인 내 두 값 a, b에 대해 a R b는 (a, b)가 R의 원소임을 뜻합니다. Relation이 어떤 조건에 대해 최소 Relation임은 그 조건을 만족하는 가장 작은 Relation임을 의미합니다.

엄격 부분 순서(strict partial order)는 다음을 만족하는 Relation 값 R입니다.

  • 모든 R의 도메인 내 a, b, c에 대해:

    • a R a는 성립하지 않으며,
    • a R bb R c이면, a R c이다.
Note 1

위 두 속성은 각각 반사 불가성(irreflexivity)과 추이성(transitivity)이라 부릅니다.

엄격 전순서(strict total order)는 다음을 만족하는 Relation 값 R입니다.

  • 모든 R의 도메인 내 a, b, c에 대해:

    • ab이거나, a R b이거나, b R a이다.
    • a R a는 성립하지 않는다.
    • a R b 그리고 b R c이면, a R c이다.
Note 2

위 세 속성은 각각 전체성(totality), 반사 불가성(irreflexivity), 추이성(transitivity)이라 부릅니다.

6.2.4 Completion Record 명세 타입

Completion Record 명세 타입은 실행 중 값의 전달과 제어 흐름(비지역적 제어 이동을 수행하는 문장인 break, continue, return, throw의 동작 등)을 설명하는 데 사용됩니다.

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

Table 7: Completion Record 필드
필드 이름 의미
[[Type]] normal, break, continue, return, throw 발생한 completion의 타입
[[Value]] Completion Record가 아닌 임의 값 생성된 값
[[Target]] 문자열 또는 empty 지시된 제어 이동의 대상 레이블

다음과 같은 용어들이 Completion Record를 참조할 때 종종 사용됩니다.

  • normal completion[[Type]] 값이 normal인 Completion Record를 의미합니다.
  • break completion[[Type]] 값이 break인 Completion Record를 의미합니다.
  • continue completion[[Type]] 값이 continue인 Completion Record를 의미합니다.
  • return completion[[Type]] 값이 return인 Completion Record를 의미합니다.
  • throw completion[[Type]] 값이 throw인 Completion Record를 의미합니다.
  • abrupt completion[[Type]] 값이 normal이 아닌 Completion Record를 의미합니다.
  • normal completion containing[[Value]] 필드에 해당 타입의 값이 포함된 normal completion을 의미합니다.

이 명세에서 정의된 호출 가능한 객체는 항상 normal completion이나 throw completion만 반환합니다. 그 외 Completion Record를 반환하는 것은 편집 오류로 간주합니다.

구현 정의 호출 가능 객체도 normal completion 또는 throw completion만 반환해야 합니다.

6.2.4.1 NormalCompletion ( value )

The abstract operation NormalCompletion takes argument value (Completion Record가 아닌 임의 값) and returns 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 (ECMAScript 언어 값) and returns 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 (ECMAScript 언어 값) and returns 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 (Completion Record) and value (Completion Record가 아닌 임의 값) and returns Completion Record. It performs the following steps when called:

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

6.2.5 Reference Record 명세 타입

Reference Record 타입은 delete, typeof, 대입 연산자, super 키워드 및 기타 언어 기능의 동작을 설명하는 데 사용됩니다. 예를 들어, 대입의 왼쪽 피연산자는 Reference Record를 생성해야 합니다.

Reference Record는 해석된 이름 또는(아직 해석되지 않았을 수도 있는) 프로퍼티 바인딩이며, 필드는 Table 8에 정의되어 있습니다.

Table 8: Reference Record 필드
필드 이름 의미
[[Base]] ECMAScript 언어 값, Environment Record, unresolvable 바인딩을 담고 있는 값 또는 Environment Record. [[Base]]unresolvable이면 바인딩을 해석할 수 없음을 의미합니다.
[[ReferencedName]] ECMAScript 언어 값 또는 Private Name 바인딩의 이름. [[Base]] 값이 Environment Record면 항상 문자열입니다. 그렇지 않으면, ToPropertyKey가 수행되기 전까지 문자열이나 심볼이 아닌 ECMAScript 언어 값일 수 있습니다.
[[Strict]] 불리언 Reference Record가 strict 모드 코드에서 생성되었으면 true, 아니면 false입니다.
[[ThisValue]] ECMAScript 언어 값 또는 empty empty가 아니면, Reference Recordsuper 키워드로 표현된 프로퍼티 바인딩을 나타냅니다. 이를 Super Reference Record라 하며, [[Base]] 값은 Environment Record가 될 수 없습니다. 이 경우 [[ThisValue]] 필드는 Reference Record가 생성된 시점의 this 값을 담습니다.

Reference Record를 다루기 위해 명세에서 다음과 같은 추상 연산을 사용합니다:

6.2.5.1 IsPropertyReference ( V )

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

  1. V.[[Base]]unresolvable이면 false 반환.
  2. V.[[Base]]Environment Record이면 false 반환; 아니면 true 반환.

6.2.5.2 IsUnresolvableReference ( V )

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

  1. V.[[Base]]unresolvable이면 true 반환; 아니면 false 반환.

6.2.5.3 IsSuperReference ( V )

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

  1. V.[[ThisValue]]empty가 아니면 true 반환; 아니면 false 반환.

6.2.5.4 IsPrivateReference ( V )

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

  1. V.[[ReferencedName]]Private Name이면 true 반환; 아니면 false 반환.

6.2.5.5 GetValue ( V )

The abstract operation GetValue takes argument V (Reference Record 또는 ECMAScript 언어 값) and returns ECMAScript 언어 값을 담는 normal completion 또는 abrupt completion. It performs the following steps when called:

  1. VReference Record가 아니면 V를 반환한다.
  2. IsUnresolvableReference(V)가 true이면 ReferenceError 예외를 throw한다.
  3. IsPropertyReference(V)가 true이면,
    1. baseObj를 ? ToObject(V.[[Base]])로 한다.
    2. IsPrivateReference(V)가 true이면,
      1. PrivateGet(baseObj, V.[[ReferencedName]])를 반환한다.
    3. V.[[ReferencedName]]프로퍼티 키가 아니면,
      1. V.[[ReferencedName]]을 ? ToPropertyKey(V.[[ReferencedName]])로 설정한다.
    4. baseObj.[[Get]](V.[[ReferencedName]], GetThisValue(V))를 반환한다.
  4. 아니면,
    1. baseV.[[Base]]로 한다.
    2. 단언: baseEnvironment Record이다.
    3. base.GetBindingValue(V.[[ReferencedName]], V.[[Strict]])를 반환한다(9.1 참조).
Note

3.a 단계에서 생성되는 객체는 위 추상 연산과 ordinary object [[Get]] 내부 메소드 외부에서는 접근할 수 없습니다. 구현에서는 실제 객체 생성을 생략할 수 있습니다.

6.2.5.6 PutValue ( V, W )

The abstract operation PutValue takes arguments V (Reference Record 또는 ECMAScript 언어 값) and W (ECMAScript 언어 값) and returns unused을 담는 normal completion 또는 abrupt completion. It performs the following steps when called:

  1. VReference Record가 아니면 ReferenceError 예외를 throw한다.
  2. IsUnresolvableReference(V)가 true이면,
    1. V.[[Strict]]true이면 ReferenceError 예외를 throw한다.
    2. globalObjGetGlobalObject()로 한다.
    3. Set(globalObj, V.[[ReferencedName]], W, false)를 수행한다.
    4. unused를 반환한다.
  3. IsPropertyReference(V)가 true이면,
    1. baseObj를 ? ToObject(V.[[Base]])로 한다.
    2. IsPrivateReference(V)가 true이면,
      1. PrivateSet(baseObj, V.[[ReferencedName]], W)를 반환한다.
    3. V.[[ReferencedName]]프로퍼티 키가 아니면,
      1. V.[[ReferencedName]]을 ? ToPropertyKey(V.[[ReferencedName]])로 설정한다.
    4. succeeded를 ? baseObj.[[Set]](V.[[ReferencedName]], W, GetThisValue(V))로 한다.
    5. succeededfalse이고 V.[[Strict]]true이면 TypeError 예외를 throw한다.
    6. unused를 반환한다.
  4. 아니면,
    1. baseV.[[Base]]로 한다.
    2. 단언: baseEnvironment Record이다.
    3. base.SetMutableBinding(V.[[ReferencedName]], W, V.[[Strict]])를 반환한다(9.1 참조).
Note

3.a 단계에서 생성되는 객체는 위 추상 연산과 ordinary object [[Set]] 내부 메소드 외부에서는 접근할 수 없습니다. 구현에서는 실제 객체 생성을 생략할 수 있습니다.

6.2.5.7 GetThisValue ( V )

The abstract operation GetThisValue takes argument V (Reference Record) and returns ECMAScript 언어 값. It performs the following steps when called:

  1. 단언: IsPropertyReference(V)는 true이다.
  2. IsSuperReference(V)가 true이면 V.[[ThisValue]] 반환; 아니면 V.[[Base]] 반환.

6.2.5.8 InitializeReferencedBinding ( V, W )

The abstract operation InitializeReferencedBinding takes arguments V (Reference Record) and W (ECMAScript 언어 값) and returns unused을 담는 normal completion 또는 abrupt completion. It performs the following steps when called:

  1. 단언: IsUnresolvableReference(V)는 false이다.
  2. baseV.[[Base]]로 한다.
  3. 단언: baseEnvironment Record이다.
  4. base.InitializeBinding(V.[[ReferencedName]], W)를 반환한다.

6.2.5.9 MakePrivateReference ( baseValue, privateIdentifier )

The abstract operation MakePrivateReference takes arguments baseValue (ECMAScript 언어 값) and privateIdentifier (문자열) and returns Reference Record. It performs the following steps when called:

  1. privateEnv를 실행 중인 실행 컨텍스트의 PrivateEnvironment로 한다.
  2. 단언: privateEnvnull이 아니다.
  3. privateNameResolvePrivateIdentifier(privateEnv, privateIdentifier)로 한다.
  4. Reference Record { [[Base]]: baseValue, [[ReferencedName]]: privateName, [[Strict]]: true, [[ThisValue]]: empty }를 반환한다.

6.2.6 Property Descriptor 명세 타입

Property Descriptor 타입은 Object 프로퍼티 속성의 조작과 구체화를 설명하는 데 사용됩니다. Property Descriptor는 0개 이상의 필드를 갖는 Record이며, 각 필드 이름은 속성 이름이고 값은 6.1.7.1에 지정된 속성 값입니다. 명세에서 Property Descriptor 레코드의 리터럴 설명을 태그하는 스키마 이름은 “PropertyDescriptor”입니다.

Property Descriptor 값은 특정 필드의 존재나 사용에 따라 데이터 Property Descriptor와 접근자 Property Descriptor로 더 분류할 수 있습니다. [[Value]] 또는 [[Writable]] 필드가 있으면 데이터 Property Descriptor, [[Get]] 또는 [[Set]] 필드가 있으면 접근자 Property Descriptor입니다. 모든 Property Descriptor에는 [[Enumerable]][[Configurable]] 필드가 있을 수 있습니다. 한 Property Descriptor 값은 데이터 Property Descriptor와 접근자 Property Descriptor를 동시에 가질 수 없지만, 둘 다 아닐 수도 있습니다(이 경우 generic Property Descriptor). 완전한 Property Descriptor는 접근자 또는 데이터 Property Descriptor이면서 Table 3의 해당 필드를 모두 가지고 있는 것입니다.

이 명세에서 Property Descriptor 값을 다루기 위해 다음 추상 연산을 사용합니다:

6.2.6.1 IsAccessorDescriptor ( Desc )

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

  1. Desc[[Get]] 필드가 있으면 true 반환.
  2. Desc[[Set]] 필드가 있으면 true 반환.
  3. false 반환.

6.2.6.2 IsDataDescriptor ( Desc )

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

  1. Desc[[Value]] 필드가 있으면 true 반환.
  2. Desc[[Writable]] 필드가 있으면 true 반환.
  3. false 반환.

6.2.6.3 IsGenericDescriptor ( Desc )

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

  1. IsAccessorDescriptor(Desc)가 truefalse 반환.
  2. IsDataDescriptor(Desc)가 truefalse 반환.
  3. true 반환.

6.2.6.4 FromPropertyDescriptor ( Desc )

The abstract operation FromPropertyDescriptor takes argument Desc (Property Descriptor 또는 undefined) and returns Object 또는 undefined. It performs the following steps when called:

  1. Descundefinedundefined 반환.
  2. objOrdinaryObjectCreate(%Object.prototype%)로 한다.
  3. 단언: obj는 확장 가능한 ordinary object이며 자체 프로퍼티가 없다.
  4. Desc[[Value]] 필드가 있으면,
    1. CreateDataPropertyOrThrow(obj, "value", Desc.[[Value]])를 수행한다.
  5. Desc[[Writable]] 필드가 있으면,
    1. CreateDataPropertyOrThrow(obj, "writable", Desc.[[Writable]])를 수행한다.
  6. Desc[[Get]] 필드가 있으면,
    1. CreateDataPropertyOrThrow(obj, "get", Desc.[[Get]])를 수행한다.
  7. Desc[[Set]] 필드가 있으면,
    1. CreateDataPropertyOrThrow(obj, "set", Desc.[[Set]])를 수행한다.
  8. Desc[[Enumerable]] 필드가 있으면,
    1. CreateDataPropertyOrThrow(obj, "enumerable", Desc.[[Enumerable]])를 수행한다.
  9. Desc[[Configurable]] 필드가 있으면,
    1. CreateDataPropertyOrThrow(obj, "configurable", Desc.[[Configurable]])를 수행한다.
  10. obj를 반환한다.

6.2.6.5 ToPropertyDescriptor ( Obj )

The abstract operation ToPropertyDescriptor takes argument Obj (ECMAScript 언어 값) and returns Property Descriptor를 담는 normal completion 또는 throw completion. It performs the following steps when called:

  1. Obj가 Object가 아니면 TypeError 예외를 throw한다.
  2. desc를 초기에는 필드가 없는 새로운 Property Descriptor로 한다.
  3. hasEnumerable을 ? HasProperty(Obj, "enumerable")로 한다.
  4. hasEnumerabletrue면,
    1. enumerableToBoolean(? Get(Obj, "enumerable"))로 한다.
    2. desc.[[Enumerable]]enumerable을 할당한다.
  5. hasConfigurable을 ? HasProperty(Obj, "configurable")로 한다.
  6. hasConfigurabletrue면,
    1. configurableToBoolean(? Get(Obj, "configurable"))로 한다.
    2. desc.[[Configurable]]configurable을 할당한다.
  7. hasValue를 ? HasProperty(Obj, "value")로 한다.
  8. hasValuetrue면,
    1. value를 ? Get(Obj, "value")로 한다.
    2. desc.[[Value]]value를 할당한다.
  9. hasWritable을 ? HasProperty(Obj, "writable")로 한다.
  10. hasWritabletrue면,
    1. writableToBoolean(? Get(Obj, "writable"))로 한다.
    2. desc.[[Writable]]writable을 할당한다.
  11. hasGet을 ? HasProperty(Obj, "get")로 한다.
  12. hasGettrue면,
    1. getter를 ? Get(Obj, "get")로 한다.
    2. IsCallable(getter)가 false이고 getterundefined가 아니면 TypeError 예외를 throw한다.
    3. desc.[[Get]]getter를 할당한다.
  13. hasSet을 ? HasProperty(Obj, "set")로 한다.
  14. hasSettrue면,
    1. setter를 ? Get(Obj, "set")로 한다.
    2. IsCallable(setter)가 false이고 setterundefined가 아니면 TypeError 예외를 throw한다.
    3. desc.[[Set]]setter를 할당한다.
  15. desc[[Get]] 또는 [[Set]] 필드가 있으면,
    1. desc[[Value]] 또는 [[Writable]] 필드가 있으면 TypeError 예외를 throw한다.
  16. desc를 반환한다.

6.2.6.6 CompletePropertyDescriptor ( Desc )

The abstract operation CompletePropertyDescriptor takes argument Desc (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(Desc)가 true이거나 IsDataDescriptor(Desc)가 true이면,
    1. Desc[[Value]] 필드가 없으면 Desc.[[Value]]like.[[Value]]를 할당한다.
    2. Desc[[Writable]] 필드가 없으면 Desc.[[Writable]]like.[[Writable]]를 할당한다.
  3. 아니면,
    1. Desc[[Get]] 필드가 없으면 Desc.[[Get]]like.[[Get]]를 할당한다.
    2. Desc[[Set]] 필드가 없으면 Desc.[[Set]]like.[[Set]]를 할당한다.
  4. Desc[[Enumerable]] 필드가 없으면 Desc.[[Enumerable]]like.[[Enumerable]]를 할당한다.
  5. Desc[[Configurable]] 필드가 없으면 Desc.[[Configurable]]like.[[Configurable]]를 할당한다.
  6. unused를 반환한다.

6.2.7 Environment Record 명세 타입

Environment Record 타입은 중첩 함수와 블록에서 이름 해석 동작을 설명하는 데 사용됩니다. 이 타입과 관련 연산은 9.1에 정의되어 있습니다.

6.2.8 Abstract Closure 명세 타입

Abstract Closure 명세 타입은 알고리즘 단계와 값 집합을 함께 참조하는 데 사용됩니다. Abstract Closure는 메타 값이며 함수 호출 방식(closure(arg1, arg2))으로 호출됩니다. 추상 연산과 마찬가지로, 호출 시 Abstract Closure에 기술된 알고리즘 단계를 수행합니다.

Abstract Closure를 생성하는 알고리즘 단계에서는 "capture" 뒤에 별칭 목록으로 값을 캡처합니다. Abstract Closure가 생성될 때 각 별칭에 연관된 값을 캡처합니다. Abstract Closure가 호출될 때 수행할 알고리즘 단계에서는 캡처된 값을 캡처 당시 사용된 별칭으로 참조합니다.

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

Abstract Closure는 다른 알고리즘의 일부로 인라인 생성됩니다. 예시는 다음과 같습니다.

  1. addend를 41로 한다.
  2. closure를 매개변수(x)를 가지며, addend를 캡처하고 호출 시 다음 단계를 수행하는 새로운 Abstract Closure로 한다:
    1. x + addend를 반환한다.
  3. valclosure(1)로 한다.
  4. 단언: val은 42이다.

6.2.9 Data Block

Data Block 명세 타입은 개별적이고 변경 가능한 바이트 크기(8비트)의 숫자값 시퀀스를 설명하는 데 사용됩니다. byte value는 0부터 255(포함) 사이의 정수입니다. Data Block 값은 고정된 바이트 수로 생성되며 각 바이트의 초기값은 0입니다.

이 명세에서는 배열과 유사한 문법으로 Data Block 값의 개별 바이트에 접근할 수 있습니다. 이 표기법은 Data Block 값을 0 기반 integer-indexed 바이트 시퀀스로 표현합니다. 예를 들어, db가 5바이트 Data Block 값이면 db[2]는 3번째 바이트에 접근할 수 있습니다.

메모리 내에서 여러 agent가 동시에 참조할 수 있는 data block은 Shared Data Block이라 부릅니다. Shared Data Block은 주소 자유(address-free)의 정체성을 갖습니다(Shared Data Block 값의 동등성 검사 목적). 이는 해당 블록이 어떤 프로세스의 가상 주소에 매핑되어 있든 상관없이, 그 블록이 나타내는 메모리 위치 집합에 따라 정체성이 결정됨을 뜻합니다. 두 data block은 그 위치 집합이 같을 때만 같고, 그렇지 않으면 다르며, 위치 집합의 교집합은 비어 있습니다. 마지막으로, Shared Data Block과 Data Block은 구별할 수 있습니다.

Shared Data Block의 의미론은 메모리 모델에서 Shared Data Block 이벤트를 사용해 정의됩니다. 아래 추상 연산들은 Shared Data Block 이벤트를 도입하며, 평가 의미론과 메모리 모델의 이벤트 의미론 사이의 인터페이스 역할을 합니다. 이벤트들은 후보 실행(candidate execution)을 구성하며, 메모리 모델은 후보 실행에 필터로 작동합니다. 전체 의미론은 메모리 모델을 참고하세요.

Shared Data Block 이벤트는 메모리 모델에서 정의된 Record로 모델링됩니다.

이 명세에서 Data Block 값을 다루기 위해 다음과 같은 추상 연산을 사용합니다:

6.2.9.1 CreateByteDataBlock ( size )

The abstract operation CreateByteDataBlock takes argument size (0 이상 정수) and returns Data Block을 담는 normal completion 또는 throw completion. It performs the following steps when called:

  1. size > 253 - 1이면 RangeError 예외를 throw한다.
  2. dbsize 바이트로 구성된 새로운 Data Block 값으로 한다. 생성이 불가능하면 RangeError 예외를 throw한다.
  3. db의 모든 바이트를 0으로 설정한다.
  4. db를 반환한다.

6.2.9.2 CreateSharedByteDataBlock ( size )

The abstract operation CreateSharedByteDataBlock takes argument size (0 이상 정수) and returns Shared Data Block을 담는 normal completion 또는 throw completion. It performs the following steps when called:

  1. dbsize 바이트로 구성된 새로운 Shared Data Block 값으로 한다. 생성이 불가능하면 RangeError 예외를 throw한다.
  2. execution을 주위 agentAgent Record[[CandidateExecution]] 필드로 한다.
  3. eventsRecordexecution.[[EventsRecords]][[AgentSignifier]]AgentSignifier()인 Agent Events Record로 한다.
  4. zero를 « 0 »으로 한다.
  5. db의 각 인덱스 i에 대해,
    1. WriteSharedMemory { [[Order]]: init, [[NoTear]]: true, [[Block]]: db, [[ByteIndex]]: i, [[ElementSize]]: 1, [[Payload]]: zero }를 eventsRecord.[[EventList]]에 추가한다.
  6. db를 반환한다.

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

The abstract operation CopyDataBlockBytes takes arguments toBlock (Data Block 또는 Shared Data Block), toIndex (0 이상 정수), fromBlock (Data Block 또는 Shared Data Block), fromIndex (0 이상 정수), and count (0 이상 정수) and returns unused. It performs the following steps when called:

  1. 단언: fromBlocktoBlock은 서로 다른 값이다.
  2. fromSizefromBlock의 바이트 수로 한다.
  3. 단언: fromIndex + countfromSize이다.
  4. toSizetoBlock의 바이트 수로 한다.
  5. 단언: toIndex + counttoSize이다.
  6. count > 0 동안 반복한다,
    1. fromBlockShared Data Block이면,
      1. execution을 주위 agentAgent Record[[CandidateExecution]] 필드로 한다.
      2. eventsRecordexecution.[[EventsRecords]][[AgentSignifier]]AgentSignifier()인 Agent Events Record로 한다.
      3. bytes를 nondeterministically 선택된 byte value 1개만 담은 List로 한다.
      4. 참고: 구현에서 bytes는 기저 하드웨어에서 비원자적 읽기 명령 결과입니다. 이 nondeterminism은 하드웨어의 약한 일관성에서 관찰 가능한 행동을 설명하기 위한 메모리 모델의 의미론적 처방입니다.
      5. readEventReadSharedMemory { [[Order]]: unordered, [[NoTear]]: true, [[Block]]: fromBlock, [[ByteIndex]]: fromIndex, [[ElementSize]]: 1 }로 한다.
      6. readEventeventsRecord.[[EventList]]에 추가한다.
      7. Chosen Value Record { [[Event]]: readEvent, [[ChosenValue]]: bytes }를 execution.[[ChosenValues]]에 추가한다.
      8. toBlockShared Data Block이면,
        1. WriteSharedMemory { [[Order]]: unordered, [[NoTear]]: true, [[Block]]: toBlock, [[ByteIndex]]: toIndex, [[ElementSize]]: 1, [[Payload]]: bytes }를 eventsRecord.[[EventList]]에 추가한다.
      9. 아니면,
        1. toBlock[toIndex]를 bytes[0]로 설정한다.
    2. 아니면,
      1. 단언: toBlockShared Data Block이 아니다.
      2. toBlock[toIndex]를 fromBlock[fromIndex]로 설정한다.
    3. toIndextoIndex + 1로 한다.
    4. fromIndexfromIndex + 1로 한다.
    5. countcount - 1로 한다.
  7. unused를 반환한다.

6.2.10 PrivateElement 명세 타입

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

PrivateElement 타입의 값은 Table 9에 정의된 필드를 갖는 Record 값입니다. 이러한 값을 PrivateElement라 합니다.

Table 9: PrivateElement 필드
필드 이름 [[Kind]] 필드 값이 있을 때 의미
[[Key]] 전체 Private Name 필드, 메소드, 접근자의 이름
[[Kind]] 전체 field, method, accessor element의 종류
[[Value]] field, method ECMAScript 언어 값 필드의 값
[[Get]] accessor 함수 객체 또는 undefined private 접근자의 getter
[[Set]] accessor 함수 객체 또는 undefined private 접근자의 setter

6.2.11 ClassFieldDefinition Record 명세 타입

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

ClassFieldDefinition 타입의 값은 Table 10에 정의된 필드를 갖는 Record 값입니다. 이러한 값을 ClassFieldDefinition Record라 합니다.

Table 10: ClassFieldDefinition Record 필드
필드 이름 의미
[[Name]] Private Name, 문자열, 심볼 필드의 이름
[[Initializer]] ECMAScript 함수 객체 또는 empty 필드의 초기화 함수(있으면)

6.2.12 Private Name

Private Name 명세 타입은 전역적으로 고유한 값(다른 Private Name과 구별됨, 설령 구별 불가해 보여도)을 설명하는 데 사용됩니다. 이 값은 private 클래스 요소(필드, 메소드, 접근자)의 키를 나타냅니다. 각 Private Name은 불변의 [[Description]] 내부 슬롯을 가지며, 이는 문자열입니다. Private Name은 ECMAScript 객체에 PrivateFieldAdd 또는 PrivateMethodOrAccessorAdd로 설치할 수 있으며, PrivateGetPrivateSet을 통해 읽거나 쓸 수 있습니다.

6.2.13 ClassStaticBlockDefinition Record 명세 타입

ClassStaticBlockDefinition Record는 클래스 static 초기화 블록의 실행 코드를 캡슐화하는 데 사용되는 Record 값입니다.

ClassStaticBlockDefinition Record는 Table 11에 나열된 필드를 가집니다.

Table 11: ClassStaticBlockDefinition Record 필드
필드 이름 의미
[[BodyFunction]] ECMAScript 함수 객체 클래스 static 초기화 시 호출되는 함수 객체

7 추상 연산(Abstract Operations)

이 연산들은 ECMAScript 언어의 일부가 아니며; ECMAScript 언어의 의미론을 명세하기 쉽게 하기 위해 여기에서만 정의됩니다. 이 명세 전반에 걸쳐 보다 특수화된 다른 추상 연산들이 정의됩니다.

7.1 타입 변환(Type Conversion)

ECMAScript 언어는 필요에 따라 자동으로 암시적 타입 변환을 수행합니다. 특정 구성의 의미론을 명확히 하기 위해 일련의 변환 추상 연산을 정의하는 것이 유용합니다. 변환 추상 연산은 다형적이며; 어떤 ECMAScript 언어 타입의 값이든 받을 수 있습니다. 그러나 다른 명세 타입은 이러한 연산과 함께 사용되지 않습니다.

BigInt 타입은 ECMAScript 언어에서 암시적 변환이 없습니다; 프로그래머는 다른 타입에서 값을 변환하기 위해 반드시 BigInt를 명시적으로 호출해야 합니다.

7.1.1 ToPrimitive ( input [ , preferredType ] )

The abstract operation ToPrimitive takes argument input (ECMAScript 언어 값) and optional argument preferredType (string 또는 number) and returns ECMAScript 언어 값을 담는 normal completion 또는 throw completion. input 인수를 비-Object 타입으로 변환합니다. 객체가 둘 이상의 원시 타입으로 변환 가능하다면 선택적 힌트 preferredType을 사용하여 그 타입을 우선할 수 있습니다. It performs the following steps when called:

  1. input이 Object이면,
    1. exoticToPrim을 ? GetMethod(input, %Symbol.toPrimitive%)로 둔다.
    2. exoticToPrimundefined가 아니면,
      1. preferredType이 존재하지 않으면,
        1. hint"default"로 둔다.
      2. Else if preferredTypestring이면,
        1. hint"string"으로 둔다.
      3. Else,
        1. 단언: preferredTypenumber이다.
        2. hint"number"로 둔다.
      4. result를 ? Call(exoticToPrim, input, « hint »)로 둔다.
      5. result가 Object가 아니면 result를 반환한다.
      6. TypeError 예외를 던진다.
    3. preferredType이 존재하지 않으면 preferredTypenumber로 둔다.
    4. OrdinaryToPrimitive(input, preferredType)을 반환한다.
  2. input을 반환한다.
Note

ToPrimitive가 힌트 없이 호출되면 일반적으로 힌트가 number인 것처럼 동작합니다. 그러나 객체는 %Symbol.toPrimitive% 메서드를 정의하여 이 동작을 재정의할 수 있습니다. 이 명세에 정의된 객체 중 Date( 21.4.4.45 참조 )와 Symbol 객체( 20.4.3.5 참조 )만이 기본 ToPrimitive 동작을 재정의합니다. Date는 힌스가 없는 경우 힌트가 string인 것처럼 취급합니다.

7.1.1.1 OrdinaryToPrimitive ( O, hint )

The abstract operation OrdinaryToPrimitive takes arguments O (Object) and hint (string 또는 number) and returns ECMAScript 언어 값을 담는 normal completion 또는 throw completion. It performs the following steps when called:

  1. hintstring이면,
    1. methodNames를 « "toString", "valueOf" »로 둔다.
  2. Else,
    1. methodNames를 « "valueOf", "toString" »으로 둔다.
  3. methodNames의 각 요소 name에 대해,
    1. method를 ? Get(O, name)으로 둔다.
    2. IsCallable(method)가 true이면,
      1. result를 ? Call(method, O)로 둔다.
      2. result가 Object가 아니면 result를 반환한다.
  4. TypeError 예외를 던진다.

7.1.2 ToBoolean ( argument )

The abstract operation ToBoolean takes argument argument (ECMAScript 언어 값) and returns Boolean. argumentBoolean 타입 값으로 변환합니다. It performs the following steps when called:

  1. argument가 Boolean이면 argument를 반환한다.
  2. argumentundefined, null, +0𝔽, -0𝔽, NaN, 0, 또는 빈 String 중 하나이면 false를 반환한다.
  3. Normative Optional
    호스트가 웹 브라우저이거나 [[IsHTMLDDA]] 내부 슬롯를 지원하면,
    1. argument가 Object이고 [[IsHTMLDDA]] 내부 슬롯을 갖고 있으면 false를 반환한다.
  4. true를 반환한다.

7.1.3 ToNumeric ( value )

The abstract operation ToNumeric takes argument value (ECMAScript 언어 값) and returns Number 또는 BigInt를 담는 normal completion 또는 throw completion. value를 Number 또는 BigInt로 변환하여 반환합니다. It performs the following steps when called:

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

7.1.4 ToNumber ( argument )

The abstract operation ToNumber takes argument argument (ECMAScript 언어 값) and returns Number를 담는 normal completion 또는 throw completion. argumentNumber 타입 값으로 변환합니다. It performs the following steps when called:

  1. argument가 Number이면 argument를 반환한다.
  2. argument가 Symbol 또는 BigInt이면 TypeError 예외를 던진다.
  3. argumentundefined이면 NaN을 반환한다.
  4. argumentnull 또는 false이면 +0𝔽을 반환한다.
  5. argumenttrue이면 1𝔽을 반환한다.
  6. argument가 String이면 StringToNumber(argument)를 반환한다.
  7. 단언: argument는 Object이다.
  8. primValue를 ? ToPrimitive(argument, number)로 둔다.
  9. 단언: primValue는 Object가 아니다.
  10. ToNumber(primValue)를 반환한다.

7.1.4.1 String 타입에 적용된 ToNumber

추상 연산 StringToNumber는 다음 문법을 사용하여 String 값을 Number 값으로 변환하는 방법을 지정합니다.

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

위에서 명시적으로 정의되지 않은 모든 문법 기호는 숫자 리터럴에 대한 어휘 문법(12.9.3)에서 사용된 정의를 갖습니다.

Note

StringNumericLiteralNumericLiteral의 문법에는 다음과 같은 차이가 있습니다:

7.1.4.1.1 StringToNumber ( str )

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

  1. literal을 ParseText(str, StringNumericLiteral)로 둔다.
  2. literal이 오류들의 List이면 NaN을 반환한다.
  3. literal의 StringNumericValue를 반환한다.

7.1.4.1.2 런타임 의미론: StringNumericValue : Number

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS.

Note

StringNumericLiteral을 Number 값으로 변환하는 과정은 전반적으로 NumericLiteral의 NumericValue 결정(12.9.3)과 유사하지만 일부 세부 사항은 다릅니다.

It is defined piecewise over the following productions:

StringNumericLiteral ::: StrWhiteSpaceopt
  1. +0𝔽을 반환한다.
StringNumericLiteral ::: StrWhiteSpaceopt StrNumericLiteral StrWhiteSpaceopt
  1. StrNumericLiteral의 StringNumericValue를 반환한다.
StrNumericLiteral ::: NonDecimalIntegerLiteral
  1. 𝔽(MV of NonDecimalIntegerLiteral)을 반환한다.
StrDecimalLiteral ::: - StrUnsignedDecimalLiteral
  1. aStrUnsignedDecimalLiteral의 StringNumericValue로 둔다.
  2. a+0𝔽이면 -0𝔽을 반환한다.
  3. -a를 반환한다.
StrUnsignedDecimalLiteral ::: Infinity
  1. +∞𝔽를 반환한다.
StrUnsignedDecimalLiteral ::: DecimalDigits . DecimalDigitsopt ExponentPartopt
  1. a를 첫 번째 DecimalDigits의 MV로 둔다.
  2. 두 번째 DecimalDigits가 존재하면,
    1. b를 두 번째 DecimalDigits의 MV로 둔다.
    2. n을 두 번째 DecimalDigits의 코드 포인트 수로 둔다.
  3. Else,
    1. b를 0으로 둔다.
    2. n을 0으로 둔다.
  4. ExponentPart가 존재하면 eExponentPart의 MV로, 아니면 e를 0으로 둔다.
  5. RoundMVResult((a + (b × 10-n)) × 10e)를 반환한다.
StrUnsignedDecimalLiteral ::: . DecimalDigits ExponentPartopt
  1. bDecimalDigits의 MV로 둔다.
  2. ExponentPart가 존재하면 eExponentPart의 MV로, 아니면 e를 0으로 둔다.
  3. nDecimalDigits의 코드 포인트 수로 둔다.
  4. RoundMVResult(b × 10e - n)를 반환한다.
StrUnsignedDecimalLiteral ::: DecimalDigits ExponentPartopt
  1. aDecimalDigits의 MV로 둔다.
  2. ExponentPart가 존재하면 eExponentPart의 MV로, 아니면 e를 0으로 둔다.
  3. RoundMVResult(a × 10e)를 반환한다.

7.1.4.1.3 RoundMVResult ( n )

The abstract operation RoundMVResult takes argument n (수학적 값) and returns Number. 구현 정의 방식으로 n을 Number로 변환합니다. 이 추상 연산의 목적상, 어떤 자릿수가 0이 아니거나 그 왼쪽에 0이 아닌 자릿수가 있고 오른쪽에 0이 아닌 자릿수가 있는 경우 유효 자릿수입니다. 또한 “수학적 값을 나타내는 표현”의 수학적 값은 “수학적 값의 10진 표현”의 역입니다. It performs the following steps when called:

  1. n의 10진 표현이 20개 이하의 유효 자릿수를 가지면 𝔽(n)을 반환한다.
  2. option1을: n의 10진 표현에서 20번째 이후 모든 유효 자릿수를 0으로 대체한 결과가 나타내는 수학적 값으로 둔다.
  3. option2를: n의 10진 표현에서 20번째 이후 모든 유효 자릿수를 0으로 대체한 다음 20번째 위치를 (필요한 자리 올림과 함께) 1 증가시킨 결과가 나타내는 수학적 값으로 둔다.
  4. chosen구현 정의option1 또는 option2 중 하나로 둔다.
  5. 𝔽(chosen)을 반환한다.

7.1.5 ToIntegerOrInfinity ( argument )

The abstract operation ToIntegerOrInfinity takes argument argument (ECMAScript 언어 값) and returns 정수, +∞ 또는 -∞ 중 하나를 담는 normal completion 또는 throw completion. argument를 그 Number 값에서 소수 부분을 절단한 정수로, 혹은 그 Number 값이 무한대일 경우 +∞ 또는 -∞로 변환합니다. It performs the following steps when called:

  1. number를 ? ToNumber(argument)로 둔다.
  2. numberNaN, +0𝔽, -0𝔽 중 하나이면 0을 반환한다.
  3. number+∞𝔽이면 +∞를 반환한다.
  4. number-∞𝔽이면 -∞를 반환한다.
  5. truncate((number))를 반환한다.
Note
𝔽(ToIntegerOrInfinity(x))는 어떤 x에 대해서도 -0𝔽을 반환하지 않습니다. 소수 부분 절단은 x수학적 값으로 변환한 후 수행됩니다.

7.1.6 ToInt32 ( argument )

The abstract operation ToInt32 takes argument argument (ECMAScript 언어 값) and returns 적분 Number를 담는 normal completion 또는 throw completion. argument𝔽(-231)부터 𝔽(231 - 1)까지(포함) 232개의 적분 Number 값 중 하나로 변환합니다. It performs the following steps when called:

  1. number를 ? ToNumber(argument)로 둔다.
  2. number유한이 아니거나 +0𝔽 또는 -0𝔽이면 +0𝔽을 반환한다.
  3. inttruncate((number))로 둔다.
  4. int32bitint modulo 232로 둔다.
  5. int32bit ≥ 231이면 𝔽(int32bit - 232)을, 아니면 𝔽(int32bit)을 반환한다.
Note

위 정의에 따른 ToInt32의 성질:

  • ToInt32 추상 연산은 멱등성: 자신의 결과에 다시 적용해도 값은 변하지 않습니다.
  • 모든 x에 대해 ToInt32(ToUint32(x))는 ToInt32(x)와 동일한 값입니다. (이 후속 성질을 보존하기 위해 +∞𝔽-∞𝔽+0𝔽으로 매핑됩니다.)
  • ToInt32는 -0𝔽+0𝔽으로 매핑합니다.

7.1.7 ToUint32 ( argument )

The abstract operation ToUint32 takes argument argument (ECMAScript 언어 값) and returns 적분 Number를 담는 normal completion 또는 throw completion. argument+0𝔽에서 𝔽(232 - 1)까지(포함) 232개의 적분 Number 값 중 하나로 변환합니다. It performs the following steps when called:

  1. number를 ? ToNumber(argument)로 둔다.
  2. number유한이 아니거나 +0𝔽 또는 -0𝔽이면 +0𝔽을 반환한다.
  3. inttruncate((number))로 둔다.
  4. int32bitint modulo 232로 둔다.
  5. 𝔽(int32bit)를 반환한다.
Note

위 정의에 따른 ToUint32의 성질:

  • 5 단계가 ToUint32와 ToInt32의 유일한 차이점입니다.
  • ToUint32 추상 연산은 멱등성입니다.
  • 모든 x에 대해 ToUint32(ToInt32(x))는 ToUint32(x)와 동일합니다. (+∞𝔽, -∞𝔽+0𝔽으로 매핑되는 이유.)
  • ToUint32는 -0𝔽+0𝔽으로 매핑합니다.

7.1.8 ToInt16 ( argument )

The abstract operation ToInt16 takes argument argument (ECMAScript 언어 값) and returns 적분 Number를 담는 normal completion 또는 throw completion. argument𝔽(-215)부터 𝔽(215 - 1)까지(포함) 216개의 적분 Number 값 중 하나로 변환합니다. It performs the following steps when called:

  1. number를 ? ToNumber(argument)로 둔다.
  2. number유한이 아니거나 +0𝔽 또는 -0𝔽이면 +0𝔽을 반환한다.
  3. inttruncate((number))로 둔다.
  4. int16bitint modulo 216으로 둔다.
  5. int16bit ≥ 215이면 𝔽(int16bit - 216)을, 아니면 𝔽(int16bit)을 반환한다.

7.1.9 ToUint16 ( argument )

The abstract operation ToUint16 takes argument argument (ECMAScript 언어 값) and returns 적분 Number를 담는 normal completion 또는 throw completion. argument+0𝔽에서 𝔽(216 - 1)까지(포함) 216개의 적분 Number 값 중 하나로 변환합니다. It performs the following steps when called:

  1. number를 ? ToNumber(argument)로 둔다.
  2. number유한이 아니거나 +0𝔽 또는 -0𝔽이면 +0𝔽을 반환한다.
  3. inttruncate((number))로 둔다.
  4. int16bitint modulo 216으로 둔다.
  5. 𝔽(int16bit)를 반환한다.
Note

위 정의에 따른 ToUint16의 성질:

  • 4 단계에서 216을 232 대신 사용하는 점이 ToUint32와 ToUint16의 유일한 차이입니다.
  • ToUint16은 -0𝔽+0𝔽으로 매핑합니다.

7.1.10 ToInt8 ( argument )

The abstract operation ToInt8 takes argument argument (ECMAScript 언어 값) and returns 적분 Number를 담는 normal completion 또는 throw completion. argument-128𝔽에서 127𝔽까지(포함) 28개의 적분 Number 값 중 하나로 변환합니다. It performs the following steps when called:

  1. number를 ? ToNumber(argument)로 둔다.
  2. number유한이 아니거나 +0𝔽 또는 -0𝔽이면 +0𝔽을 반환한다.
  3. inttruncate((number))로 둔다.
  4. int8bitint modulo 28로 둔다.
  5. int8bit ≥ 27이면 𝔽(int8bit - 28)을, 아니면 𝔽(int8bit)을 반환한다.

7.1.11 ToUint8 ( argument )

The abstract operation ToUint8 takes argument argument (ECMAScript 언어 값) and returns 적분 Number를 담는 normal completion 또는 throw completion. argument+0𝔽에서 255𝔽까지(포함) 28개의 적분 Number 값 중 하나로 변환합니다. It performs the following steps when called:

  1. number를 ? ToNumber(argument)로 둔다.
  2. number유한이 아니거나 +0𝔽 또는 -0𝔽이면 +0𝔽을 반환한다.
  3. inttruncate((number))로 둔다.
  4. int8bitint modulo 28로 둔다.
  5. 𝔽(int8bit)를 반환한다.

7.1.12 ToUint8Clamp ( argument )

The abstract operation ToUint8Clamp takes argument argument (ECMAScript 언어 값) and returns 적분 Number를 담는 normal completion 또는 throw completion. argument+0𝔽에서 255𝔽까지(포함) 28개의 적분 Number 값 중 하나로 클램프(clamp)하고 반올림합니다. It performs the following steps when called:

  1. number를 ? ToNumber(argument)로 둔다.
  2. numberNaN이면 +0𝔽을 반환한다.
  3. mvnumber의 확장된 수학적 값으로 둔다.
  4. clampedmv를 0과 255 사이로 클램프한 결과로 둔다.
  5. ffloor(clamped)로 둔다.
  6. clamped < f + 0.5이면 𝔽(f)를 반환한다.
  7. clamped > f + 0.5이면 𝔽(f + 1)을 반환한다.
  8. f가 짝수이면 𝔽(f)를; 아니면 𝔽(f + 1)을 반환한다.
Note

대부분 다른 ECMAScript 정수 변환 연산과 달리 ToUint8Clamp는 비정수 값을 절단(truncate)하지 않고 반올림합니다. 또한 “round half up”을 사용하는 Math.round와 달리 “round half to even” 절충 규칙을 사용합니다.

7.1.13 ToBigInt ( argument )

The abstract operation ToBigInt takes argument argument (ECMAScript 언어 값) and returns BigInt를 담는 normal completion 또는 throw completion. argument를 BigInt 값으로 변환하며, Number에서의 암시적 변환이 필요하다면 예외를 던집니다. It performs the following steps when called:

  1. prim을 ? ToPrimitive(argument, number)로 둔다.
  2. Table 12prim이 대응하는 값을 반환한다.
Table 12: BigInt 변환
Argument 타입 결과
Undefined TypeError 예외를 던진다.
Null TypeError 예외를 던진다.
Boolean primtrue이면 1n, false이면 0n을 반환한다.
BigInt prim을 반환한다.
Number TypeError 예외를 던진다.
String
  1. nStringToBigInt(prim)로 둔다.
  2. nundefined이면 SyntaxError 예외를 던진다.
  3. n을 반환한다.
Symbol TypeError 예외를 던진다.

7.1.14 StringToBigInt ( str )

The abstract operation StringToBigInt takes argument str (String) and returns BigInt 또는 undefined. It performs the following steps when called:

  1. literal을 ParseText(str, StringIntegerLiteral)로 둔다.
  2. literal이 오류들의 List이면 undefined를 반환한다.
  3. mvliteral의 MV로 둔다.
  4. 단언: mv는 정수이다.
  5. (mv)를 반환한다.

7.1.14.1 StringIntegerLiteral 문법

StringToBigInt는 다음 문법을 사용합니다.

Syntax

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

7.1.14.2 런타임 의미론: MV

7.1.15 ToBigInt64 ( argument )

The abstract operation ToBigInt64 takes argument argument (ECMAScript 언어 값) and returns BigInt를 담는 normal completion 또는 throw completion. argument(-263)부터 (263 - 1)까지(포함) 264개의 BigInt 값 중 하나로 변환합니다. It performs the following steps when called:

  1. n을 ? ToBigInt(argument)로 둔다.
  2. int64bit(n) modulo 264로 둔다.
  3. int64bit ≥ 263이면 (int64bit - 264)을, 아니면 (int64bit)을 반환한다.

7.1.16 ToBigUint64 ( argument )

The abstract operation ToBigUint64 takes argument argument (ECMAScript 언어 값) and returns BigInt를 담는 normal completion 또는 throw completion. argument0에서 (264 - 1)까지(포함) 264개의 BigInt 값 중 하나로 변환합니다. It performs the following steps when called:

  1. n을 ? ToBigInt(argument)로 둔다.
  2. int64bit(n) modulo 264로 둔다.
  3. (int64bit)를 반환한다.

7.1.17 ToString ( argument )

The abstract operation ToString takes argument argument (ECMAScript 언어 값) and returns String을 담는 normal completion 또는 throw completion. argumentString 타입 값으로 변환합니다. It performs the following steps when called:

  1. argument가 String이면 argument를 반환한다.
  2. argument가 Symbol이면 TypeError 예외를 던진다.
  3. argumentundefined이면 "undefined"를 반환한다.
  4. argumentnull이면 "null"을 반환한다.
  5. argumenttrue이면 "true"를 반환한다.
  6. argumentfalse이면 "false"를 반환한다.
  7. argument가 Number이면 Number::toString(argument, 10)을 반환한다.
  8. argument가 BigInt이면 BigInt::toString(argument, 10)을 반환한다.
  9. 단언: argument는 Object이다.
  10. primValue를 ? ToPrimitive(argument, string)으로 둔다.
  11. 단언: primValue는 Object가 아니다.
  12. ToString(primValue)를 반환한다.

7.1.18 ToObject ( argument )

The abstract operation ToObject takes argument argument (ECMAScript 언어 값) and returns Object를 담는 normal completion 또는 throw completion. argumentObject 타입 값으로 변환합니다. It performs the following steps when called:

  1. argumentundefined 또는 null이면 TypeError 예외를 던진다.
  2. argument가 Boolean이면 [[BooleanData]] 내부 슬롯이 argument로 설정된 새 Boolean 객체를 반환한다. Boolean 객체 설명은 20.3 참조.
  3. argument가 Number이면 [[NumberData]] 내부 슬롯이 argument로 설정된 새 Number 객체를 반환한다. Number 객체 설명은 21.1 참조.
  4. argument가 String이면 [[StringData]] 내부 슬롯이 argument로 설정된 새 String 객체를 반환한다. String 객체 설명은 22.1 참조.
  5. argument가 Symbol이면 [[SymbolData]] 내부 슬롯이 argument로 설정된 새 Symbol 객체를 반환한다. Symbol 객체 설명은 20.4 참조.
  6. argument가 BigInt이면 [[BigIntData]] 내부 슬롯이 argument로 설정된 새 BigInt 객체를 반환한다. BigInt 객체 설명은 21.2 참조.
  7. 단언: argument는 Object이다.
  8. argument를 반환한다.

7.1.19 ToPropertyKey ( argument )

The abstract operation ToPropertyKey takes argument argument (ECMAScript 언어 값) and returns 프로퍼티 키를 담는 normal completion 또는 throw completion. argument프로퍼티 키로 사용할 수 있는 값으로 변환합니다. It performs the following steps when called:

  1. key를 ? ToPrimitive(argument, string)으로 둔다.
  2. key가 Symbol이면
    1. key를 반환한다.
  3. ToString(key)를 반환한다.

7.1.20 ToLength ( argument )

The abstract operation ToLength takes argument argument (ECMAScript 언어 값) and returns 음이 아닌 적분 Number를 담는 normal completion 또는 throw completion. argument를 배열 유사 객체의 length로 사용 가능하도록 음이 아닌 적분 Number로 클램프(clamp) 및 절단(truncate)합니다. It performs the following steps when called:

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

7.1.21 CanonicalNumericIndexString ( argument )

The abstract operation CanonicalNumericIndexString takes argument argument (String) and returns Number 또는 undefined. argument"-0"이거나 어떤 Number 값 n에 대해 ToString(n)과 정확히 일치하면 해당 Number 값을 반환합니다. 그렇지 않으면 undefined를 반환합니다. It performs the following steps when called:

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

canonical numeric string은 CanonicalNumericIndexString 추상 연산이 undefined를 반환하지 않는 모든 String입니다.

7.1.22 ToIndex ( value )

The abstract operation ToIndex takes argument value (ECMAScript 언어 값) and returns 음이 아닌 정수를 담는 normal completion 또는 throw completion. value를 정수로 변환하고, 그 정수가 음이 아니며 정수 인덱스에 대응되면 그 정수를 반환합니다. 그렇지 않으면 예외를 던집니다. It performs the following steps when called:

  1. integer를 ? ToIntegerOrInfinity(value)로 둔다.
  2. integer가 0에서 253 - 1 (포함) 사이에 없으면 RangeError 예외를 던진다.
  3. integer를 반환한다.

7.2 테스트 및 비교 연산(Testing and Comparison Operations)

7.2.1 RequireObjectCoercible ( argument )

The abstract operation RequireObjectCoercible takes argument argument (ECMAScript 언어 값) and returns unused을 담는 normal completion 또는 throw completion. argumentToObject로 Object로 변환될 수 없는 값이면 에러를 던집니다. It performs the following steps when called:

  1. argumentundefined 또는 null이면 TypeError 예외를 던진다.
  2. unused를 반환한다.

7.2.2 IsArray ( argument )

The abstract operation IsArray takes argument argument (ECMAScript 언어 값) and returns Boolean을 담는 normal completion 또는 throw completion. It performs the following steps when called:

  1. argument가 Object가 아니면 false를 반환한다.
  2. argument가 Array 이국 객체이면 true를 반환한다.
  3. argument가 Proxy 이국 객체이면,
    1. ValidateNonRevokedProxy(argument)를 수행한다.
    2. proxyTargetargument.[[ProxyTarget]]으로 둔다.
    3. IsArray(proxyTarget)을 반환한다.
  4. false를 반환한다.

7.2.3 IsCallable ( argument )

The abstract operation IsCallable takes argument argument (ECMAScript 언어 값) and returns Boolean. argument[[Call]] 내부 메소드를 가진 호출 가능 함수인지 결정합니다. It performs the following steps when called:

  1. argument가 Object가 아니면 false를 반환한다.
  2. argument[[Call]] 내부 메소드를 가지면 true를 반환한다.
  3. false를 반환한다.

7.2.4 IsConstructor ( argument )

The abstract operation IsConstructor takes argument argument (ECMAScript 언어 값) and returns Boolean. argument[[Construct]] 내부 메소드를 가진 함수 객체인지 결정합니다. It performs the following steps when called:

  1. argument가 Object가 아니면 false를 반환한다.
  2. argument[[Construct]] 내부 메소드를 가지면 true를 반환한다.
  3. false를 반환한다.

7.2.5 IsExtensible ( O )

The abstract operation IsExtensible takes argument O (Object) and returns Boolean을 담는 normal completion 또는 throw completion. O에 추가 프로퍼티를 더할 수 있는지 결정하는 데 사용됩니다. It performs the following steps when called:

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

7.2.6 IsRegExp ( argument )

The abstract operation IsRegExp takes argument argument (ECMAScript 언어 값) and returns Boolean을 담는 normal completion 또는 throw completion. It performs the following steps when called:

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

7.2.7 Static Semantics: IsStringWellFormedUnicode ( string )

The abstract operation IsStringWellFormedUnicode takes argument string (String) and returns Boolean. 6.1.4에 설명된 대로 string을 UTF-16 인코딩된 코드 포인트 시퀀스로 해석하고 이것이 well formed UTF-16 시퀀스인지 판정합니다. It performs the following steps when called:

  1. lenstring의 길이로 둔다.
  2. k를 0으로 둔다.
  3. k < len 동안 반복,
    1. cp를 CodePointAt(string, k)로 둔다.
    2. cp.[[IsUnpairedSurrogate]]true이면 false를 반환한다.
    3. kk + cp.[[CodeUnitCount]]로 둔다.
  4. true를 반환한다.

7.2.8 SameType ( x, y )

The abstract operation SameType takes arguments x (ECMAScript 언어 값) and y (ECMAScript 언어 값) and returns Boolean. 두 인수가 같은 타입인지 판정합니다. 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 (ECMAScript 언어 값) and y (ECMAScript 언어 값) and returns Boolean. 두 인수가 같은 값인지 판정합니다. It performs the following steps when called:

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

이 알고리즘은 모든 NaN 값을 동등하게 취급하고 +0𝔽-0𝔽을 구분한다는 점에서 IsStrictlyEqual 알고리즘과 다릅니다.

7.2.10 SameValueZero ( x, y )

The abstract operation SameValueZero takes arguments x (ECMAScript 언어 값) and y (ECMAScript 언어 값) and returns Boolean. 두 인수가 같은 값인지 ( +0𝔽-0𝔽의 차이를 무시하고 ) 판정합니다. It performs the following steps when called:

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

SameValueZero는 +0𝔽-0𝔽을 동일하게 취급한다는 점만 SameValue와 다릅니다.

7.2.11 SameValueNonNumber ( x, y )

The abstract operation SameValueNonNumber takes arguments x (Number가 아닌 ECMAScript 언어 값) and y (Number가 아닌 ECMAScript 언어 값) and returns Boolean. It performs the following steps when called:

  1. 단언: SameType(x, y)는 true이다.
  2. xundefined 또는 null이면 true를 반환한다.
  3. x가 BigInt이면
    1. BigInt::equal(x, y)를 반환한다.
  4. x가 String이면
    1. xy가 동일 길이이며 같은 위치에 동일 코드 유닛을 가지면 true, 아니면 false를 반환한다.
  5. x가 Boolean이면
    1. xy가 모두 true 또는 모두 false이면 true, 아니면 false를 반환한다.
  6. 주: 다른 모든 ECMAScript 언어 값은 동일성(identity)으로 비교된다.
  7. xy이면 true, 아니면 false를 반환한다.
Note 1
설명을 위해 일부 경우는 필요 없더라도 별도로 다룹니다.
Note 2
"x is y"의 구체적 의미는 5.2.7에 자세히 있습니다.

7.2.12 IsLessThan ( x, y, LeftFirst )

The abstract operation IsLessThan takes arguments x (ECMAScript 언어 값), y (ECMAScript 언어 값), and LeftFirst (Boolean) and returns Boolean 또는 undefined를 담는 normal completion 또는 throw completion. x < y 비교의 의미론을 제공하며, true, false, 또는 (적어도 한 피연산자가 NaN임을 나타내는) undefined를 반환합니다. LeftFirst 플래그는 x, y에 잠재적으로 부작용 있는 연산의 순서를 제어합니다. 이는 ECMAScript가 표현식을 좌→우로 평가하도록 규정하기 때문에 필요합니다. LeftFirsttrue이면 x 매개변수는 y 매개변수 표현식의 왼쪽에 오는 표현식에 해당합니다. false이면 반대이며 연산은 x 이전에 y에 수행되어야 합니다. It performs the following steps when called:

  1. LeftFirsttrue이면,
    1. px를 ? ToPrimitive(x, number)로 둔다.
    2. py를 ? ToPrimitive(y, number)로 둔다.
  2. Else,
    1. 주: 좌→우 평가를 보존하기 위해 평가 순서를 반전해야 한다.
    2. py를 ? ToPrimitive(y, number)로 둔다.
    3. px를 ? ToPrimitive(x, number)로 둔다.
  3. px가 String이고 py가 String이면,
    1. lxpx의 길이로 둔다.
    2. lypy의 길이로 둔다.
    3. 0 ≤ i < min(lx, ly)인 각 정수 i에 대해 오름차순으로,
      1. cxpx의 인덱스 i 위치 코드 유닛의 숫자 값으로 둔다.
      2. cypy의 인덱스 i 위치 코드 유닛의 숫자 값으로 둔다.
      3. cx < cy이면 true를 반환한다.
      4. cx > cy이면 false를 반환한다.
    4. lx < ly이면 true, 아니면 false를 반환한다.
  4. Else,
    1. px가 BigInt이고 py가 String이면,
      1. nyStringToBigInt(py)로 둔다.
      2. nyundefined이면 undefined를 반환한다.
      3. BigInt::lessThan(px, ny)를 반환한다.
    2. px가 String이고 py가 BigInt이면,
      1. nxStringToBigInt(px)로 둔다.
      2. nxundefined이면 undefined를 반환한다.
      3. BigInt::lessThan(nx, py)를 반환한다.
    3. 주: px, py는 원시 값이므로 평가 순서는 중요하지 않다.
    4. nx를 ? ToNumeric(px)로 둔다.
    5. ny를 ? ToNumeric(py)로 둔다.
    6. SameType(nx, ny)가 true이면,
      1. nx가 Number이면
        1. Number::lessThan(nx, ny)를 반환한다.
      2. Else,
        1. 단언: nx는 BigInt이다.
        2. BigInt::lessThan(nx, ny)를 반환한다.
    7. 단언: nx는 BigInt이고 ny는 Number, 또는 nx는 Number이고 ny는 BigInt.
    8. nx 또는 nyNaN이면 undefined를 반환한다.
    9. nx-∞𝔽이거나 ny+∞𝔽이면 true를 반환한다.
    10. nx+∞𝔽이거나 ny-∞𝔽이면 false를 반환한다.
    11. (nx) < (ny)이면 true, 아니면 false를 반환한다.
Note 1

3 단계는 덧셈 연산자 +를 처리하는 알고리즘(13.15.3)의 1.c 단계와 논리 OR 대신 논리 AND를 사용하는 점에서 다릅니다.

Note 2

String 비교는 UTF-16 코드 유닛 값 시퀀스에 대한 단순한 사전식(lexicographic) 순서를 사용합니다. Unicode 명세에서 정의한 더 복잡하고 의미론 지향적인 문자/문자열 동등성이나 정렬 순서를 사용하려 하지 않습니다. 따라서 Unicode 표준에 따라 정규적으로 동등하지만 정규화 형태가 다른 String 값은 불일치로 판정될 수 있습니다. 또한 surrogate pair를 포함한 String의 경우 코드 유닛 기반 사전식 순서는 코드 포인트 기반 순서와 다를 수 있습니다.

7.2.13 IsLooselyEqual ( x, y )

The abstract operation IsLooselyEqual takes arguments x (ECMAScript 언어 값) and y (ECMAScript 언어 값) and returns Boolean을 담는 normal completion 또는 throw completion. == 연산자의 의미론을 제공합니다. It performs the following steps when called:

  1. SameType(x, y)가 true이면,
    1. IsStrictlyEqual(x, y)를 반환한다.
  2. xnull이고 yundefined이면 true를 반환한다.
  3. xundefined이고 ynull이면 true를 반환한다.
  4. Normative Optional
    호스트가 웹 브라우저이거나 [[IsHTMLDDA]] 내부 슬롯를 지원하면,
    1. x가 Object이고 x[[IsHTMLDDA]] 내부 슬롯을 가지며 yundefined 또는 null이면 true를 반환한다.
    2. xundefined 또는 null이고 y가 Object이며 y[[IsHTMLDDA]] 내부 슬롯을 가지면 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. x 또는 y유한이 아니면 false를 반환한다.
    2. (x) = (y)이면 true, 아니면 false를 반환한다.
  14. false를 반환한다.

7.2.14 IsStrictlyEqual ( x, y )

The abstract operation IsStrictlyEqual takes arguments x (ECMAScript 언어 값) and y (ECMAScript 언어 값) and returns Boolean. === 연산자의 의미론을 제공합니다. It performs the following steps when called:

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

이 알고리즘은 부호 있는 0 및 NaN 처리에서 SameValue 알고리즘과 다릅니다.

7.3 객체에 대한 연산(Operations on Objects)

7.3.1 MakeBasicObject ( internalSlotsList )

The abstract operation MakeBasicObject takes argument internalSlotsList (내부 슬롯 이름들의 List) and returns Object. 알고리즘적으로 생성되는 모든 ECMAScript 객체(ordinary 및 exotic 포함)의 근원입니다. 모든 객체 생성에서 사용되는 공통 단계를 분리하고 객체 생성을 중앙화합니다. It performs the following steps when called:

  1. internalSlotsListinternalSlotsList와 « [[PrivateElements]] »의 list-concatenation으로 설정한다.
  2. internalSlotsList의 각 이름에 대한 내부 슬롯을 가진 새로 생성된 객체 obj를 둔다.
  3. 주: Object 내부 메소드와 내부 슬롯에 설명된 대로 달리 지정되지 않으면 각 내부 슬롯의 초기값은 undefined이다.
  4. obj.[[PrivateElements]]를 새 빈 List로 둔다.
  5. obj의 essential 내부 메소드를 10.1에 지정된 기본 ordinary object 정의로 설정한다.
  6. 단언: 호출자가 obj[[GetPrototypeOf]][[SetPrototypeOf]] essential 내부 메소드를 모두 재정의하지 않을 경우 internalSlotsList[[Prototype]]을 포함한다.
  7. 단언: 호출자가 obj[[SetPrototypeOf]], [[IsExtensible]], [[PreventExtensions]] essential 내부 메소드를 모두 재정의하지 않을 경우 internalSlotsList[[Extensible]]을 포함한다.
  8. internalSlotsList[[Extensible]]을 포함하면 obj.[[Extensible]]true로 둔다.
  9. obj를 반환한다.
Note

이 명세 내에서 exotic 객체는 ArrayCreate, BoundFunctionCreate 같은 추상 연산에서 먼저 MakeBasicObject를 호출하여 기본 객체를 얻고 그 후 그 객체의 일부 또는 모든 내부 메소드를 재정의하여 생성됩니다. exotic 객체 생성을 캡슐화하기 위해 객체의 essential 내부 메소드는 그러한 연산 외부에서는 수정되지 않습니다.

7.3.2 Get ( O, P )

The abstract operation Get takes arguments O (Object) and P (프로퍼티 키) and returns ECMAScript 언어 값을 담는 normal completion 또는 throw completion. 객체의 특정 프로퍼티 값을 가져오는 데 사용됩니다. It performs the following steps when called:

  1. O.[[Get]](P, O)를 반환한다.

7.3.3 GetV ( V, P )

The abstract operation GetV takes arguments V (ECMAScript 언어 값) and P (프로퍼티 키) and returns ECMAScript 언어 값을 담는 normal completion 또는 throw completion. ECMAScript 언어 값의 특정 프로퍼티 값을 가져오는 데 사용됩니다. 값이 객체가 아니면 해당 타입에 적합한 래퍼 객체를 사용하여 프로퍼티 조회가 수행됩니다. It performs the following steps when called:

  1. O를 ? ToObject(V)로 둔다.
  2. O.[[Get]](P, V)를 반환한다.

7.3.4 Set ( O, P, V, Throw )

The abstract operation Set takes arguments O (Object), P (프로퍼티 키), V (ECMAScript 언어 값), and Throw (Boolean) and returns unused을 담는 normal completion 또는 throw completion. 객체의 특정 프로퍼티 값을 설정하는 데 사용됩니다. V는 프로퍼티의 새 값입니다. It performs the following steps when called:

  1. success를 ? O.[[Set]](P, V, O)로 둔다.
  2. successfalse이고 Throwtrue이면 TypeError 예외를 던진다.
  3. unused를 반환한다.

7.3.5 CreateDataProperty ( O, P, V )

The abstract operation CreateDataProperty takes arguments O (Object), P (프로퍼티 키), and V (ECMAScript 언어 값) and returns Boolean을 담는 normal completion 또는 throw completion. 객체의 새로운 own 프로퍼티를 생성하는 데 사용됩니다. It performs the following steps when called:

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

이 추상 연산은 ECMAScript 대입 연산자가 생성하는 프로퍼티와 동일 기본 속성 값을 가진 프로퍼티를 생성합니다. 일반적으로 프로퍼티는 미존재 상태입니다. 존재하고 비구성이거나 O가 비확장 가능이면 [[DefineOwnProperty]]false를 반환합니다.

7.3.6 CreateDataPropertyOrThrow ( O, P, V )

The abstract operation CreateDataPropertyOrThrow takes arguments O (Object), P (프로퍼티 키), and V (ECMAScript 언어 값) and returns unused을 담는 normal completion 또는 throw completion. 객체의 새로운 own 프로퍼티를 생성하는 데 사용되며, 요청된 프로퍼티 갱신이 수행될 수 없으면 TypeError 예외를 던집니다. It performs the following steps when called:

  1. success를 ? CreateDataProperty(O, P, V)로 둔다.
  2. successfalse이면 TypeError 예외를 던진다.
  3. unused를 반환한다.
Note

이 추상 연산은 ECMAScript 대입 연산자가 생성하는 프로퍼티와 동일 기본 속성을 가지는 프로퍼티를 생성합니다. 일반적으로 프로퍼티는 미존재 상태입니다. 존재하고 비구성이거나 O가 비확장 가능이면 [[DefineOwnProperty]]false를 반환하여 이 연산이 TypeError를 던지게 됩니다.

7.3.7 CreateNonEnumerableDataPropertyOrThrow ( O, P, V )

The abstract operation CreateNonEnumerableDataPropertyOrThrow takes arguments O (Object), P (프로퍼티 키), and V (ECMAScript 언어 값) and returns unused. ordinary 객체의 새 비열거 own 프로퍼티를 생성하는 데 사용됩니다. It performs the following steps when called:

  1. 단언: O는 비구성 프로퍼티가 없는 ordinary, 확장 가능한 객체이다.
  2. newDesc를 PropertyDescriptor { [[Value]]: V, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: true }로 둔다.
  3. DefinePropertyOrThrow(O, P, newDesc)를 수행한다.
  4. unused를 반환한다.
Note

이 추상 연산은 ECMAScript 대입 연산자가 생성하는 프로퍼티와 동일 기본 속성을 가지되 열거 가능하지 않은 프로퍼티를 생성합니다. 일반적으로 프로퍼티는 미존재 상태입니다. 존재하는 경우 DefinePropertyOrThrow는 정상적으로 완료됨이 보장됩니다.

7.3.8 DefinePropertyOrThrow ( O, P, desc )

The abstract operation DefinePropertyOrThrow takes arguments O (Object), P (프로퍼티 키), and desc (Property Descriptor) and returns unused을 담는 normal completion 또는 throw completion. 객체의 [[DefineOwnProperty]] 내부 메소드를 호출하되, 요청된 프로퍼티 갱신이 수행될 수 없으면 TypeError 예외를 던집니다. It performs the following steps when called:

  1. success를 ? O.[[DefineOwnProperty]](P, desc)로 둔다.
  2. successfalse이면 TypeError 예외를 던진다.
  3. unused를 반환한다.

7.3.9 DeletePropertyOrThrow ( O, P )

The abstract operation DeletePropertyOrThrow takes arguments O (Object) and P (프로퍼티 키) and returns unused을 담는 normal completion 또는 throw completion. 객체의 특정 own 프로퍼티를 제거하는 데 사용됩니다. 프로퍼티가 비구성이면 예외를 던집니다. It performs the following steps when called:

  1. success를 ? O.[[Delete]](P)로 둔다.
  2. successfalse이면 TypeError 예외를 던진다.
  3. unused를 반환한다.

7.3.10 GetMethod ( V, P )

The abstract operation GetMethod takes arguments V (ECMAScript 언어 값) and P (프로퍼티 키) and returns 함수 객체 또는 undefined를 담는 normal completion 또는 throw completion. 프로퍼티 값이 함수일 것으로 기대되는 ECMAScript 언어 값의 특정 프로퍼티 값을 얻는 데 사용됩니다. It performs the following steps when called:

  1. func을 ? GetV(V, P)로 둔다.
  2. funcundefined 또는 null이면 undefined를 반환한다.
  3. IsCallable(func)가 false이면 TypeError 예외를 던진다.
  4. func를 반환한다.

7.3.11 HasProperty ( O, P )

The abstract operation HasProperty takes arguments O (Object) and P (프로퍼티 키) and returns Boolean을 담는 normal completion 또는 throw completion. 객체가 지정된 프로퍼티 키를 가진 프로퍼티(own 또는 상속)를 갖는지 판정합니다. It performs the following steps when called:

  1. O.[[HasProperty]](P)를 반환한다.

7.3.12 HasOwnProperty ( O, P )

The abstract operation HasOwnProperty takes arguments O (Object) and P (프로퍼티 키) and returns Boolean을 담는 normal completion 또는 throw completion. 객체가 지정된 프로퍼티 키를 가진 own 프로퍼티를 갖는지 판정합니다. It performs the following steps when called:

  1. desc를 ? O.[[GetOwnProperty]](P)로 둔다.
  2. descundefined이면 false를 반환한다.
  3. true를 반환한다.

7.3.13 Call ( F, V [ , argumentsList ] )

The abstract operation Call takes arguments F (ECMAScript 언어 값) and V (ECMAScript 언어 값) and optional argument argumentsList (ECMAScript 언어 값들의 List) and returns ECMAScript 언어 값을 담는 normal completion 또는 throw completion. 함수 객체[[Call]] 내부 메소드를 호출하는 데 사용됩니다. F함수 객체, V[[Call]]this 값, argumentsList는 내부 메소드의 해당 인자에 전달되는 값입니다. argumentsList가 없으면 새 빈 List가 사용됩니다. It performs the following steps when called:

  1. argumentsList가 존재하지 않으면 새 빈 List로 설정한다.
  2. IsCallable(F)가 false이면 TypeError 예외를 던진다.
  3. F.[[Call]](V, argumentsList)를 반환한다.

7.3.14 Construct ( F [ , argumentsList [ , newTarget ] ] )

The abstract operation Construct takes argument F (생성자) and optional arguments argumentsList (ECMAScript 언어 값들의 List) and newTarget (생성자) and returns Object를 담는 normal completion 또는 throw completion. 함수 객체[[Construct]] 내부 메소드를 호출하는 데 사용됩니다. argumentsList, newTarget은 내부 메소드에 전달될 해당 인자 값입니다. argumentsList가 없으면 새 빈 List가, newTarget이 없으면 F가 사용됩니다. It performs the following steps when called:

  1. newTarget이 존재하지 않으면 newTargetF로 둔다.
  2. argumentsList가 존재하지 않으면 새 빈 List로 둔다.
  3. F.[[Construct]](argumentsList, newTarget)를 반환한다.
Note

newTarget이 없으면 이 연산은 new F(...argumentsList)와 동일합니다.

7.3.15 SetIntegrityLevel ( O, level )

The abstract operation SetIntegrityLevel takes arguments O (Object) and level (sealed 또는 frozen) and returns Boolean을 담는 normal completion 또는 throw completion. 객체의 own 프로퍼티 집합을 고정(fix)하는 데 사용됩니다. It performs the following steps when called:

  1. status를 ? O.[[PreventExtensions]]()로 둔다.
  2. statusfalse이면 false를 반환한다.
  3. keys를 ? O.[[OwnPropertyKeys]]()로 둔다.
  4. levelsealed이면,
    1. keys의 각 요소 k에 대해
      1. DefinePropertyOrThrow(O, k, PropertyDescriptor { [[Configurable]]: false })를 수행한다.
  5. Else,
    1. 단언: levelfrozen.
    2. keys의 각 요소 k에 대해
      1. currentDesc를 ? O.[[GetOwnProperty]](k)로 둔다.
      2. currentDescundefined가 아니면,
        1. IsAccessorDescriptor(currentDesc)가 true이면
          1. desc를 PropertyDescriptor { [[Configurable]]: false }로 둔다.
        2. Else,
          1. desc를 PropertyDescriptor { [[Configurable]]: false, [[Writable]]: false }로 둔다.
        3. DefinePropertyOrThrow(O, k, desc)를 수행한다.
  6. true를 반환한다.

7.3.16 TestIntegrityLevel ( O, level )

The abstract operation TestIntegrityLevel takes arguments O (Object) and level (sealed 또는 frozen) and returns Boolean을 담는 normal completion 또는 throw completion. 객체의 own 프로퍼티 집합이 고정되어 있는지 판정하는 데 사용됩니다. It performs the following steps when called:

  1. extensible을 ? IsExtensible(O)로 둔다.
  2. extensibletrue이면 false를 반환한다.
  3. 주: 객체가 확장이 가능하면 프로퍼티를 검사하지 않는다.
  4. keys를 ? O.[[OwnPropertyKeys]]()로 둔다.
  5. keys의 각 요소 k에 대해
    1. currentDesc를 ? O.[[GetOwnProperty]](k)로 둔다.
    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 (ECMAScript 언어 값들의 List) and returns Array. 요소가 elements로 제공되는 Array를 생성하는 데 사용됩니다. It performs the following steps when called:

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

7.3.18 LengthOfArrayLike ( obj )

The abstract operation LengthOfArrayLike takes argument obj (Object) and returns 음이 아닌 정수를 담는 normal completion 또는 throw completion. 배열 유사 객체의 "length" 프로퍼티 값을 반환합니다. It performs the following steps when called:

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

array-like object는 이 연산이 normal completion을 반환하는 모든 객체입니다.

Note 1
일반적으로 array-like object는 정수 인덱스 이름을 가진 몇몇 프로퍼티도 가집니다. 그러나 이것은 필수 조건이 아닙니다.
Note 2
Array와 String 객체가 array-like object의 예입니다.

7.3.19 CreateListFromArrayLike ( obj [ , validElementTypes ] )

The abstract operation CreateListFromArrayLike takes argument obj (ECMAScript 언어 값) and optional argument validElementTypes (all 또는 property-key) and returns ECMAScript 언어 값들의 List를 담는 normal completion 또는 throw completion. obj의 인덱스된 프로퍼티가 제공하는 요소로 이루어진 List 값을 생성하는 데 사용됩니다. validElementTypes는 요소로 허용되는 값 타입을 지정합니다. It performs the following steps when called:

  1. validElementTypes가 존재하지 않으면 all로 설정한다.
  2. obj가 Object가 아니면 TypeError 예외를 던진다.
  3. len을 ? LengthOfArrayLike(obj)로 둔다.
  4. list를 새 빈 List로 둔다.
  5. index를 0으로 둔다.
  6. index < len 동안 반복,
    1. indexName을 ! ToString(𝔽(index))로 둔다.
    2. next를 ? Get(obj, indexName)로 둔다.
    3. validElementTypesproperty-key이고 next프로퍼티 키가 아니면 TypeError 예외를 던진다.
    4. nextlist에 추가한다.
    5. indexindex + 1로 둔다.
  7. list를 반환한다.

7.3.20 Invoke ( V, P [ , argumentsList ] )

The abstract operation Invoke takes arguments V (ECMAScript 언어 값) and P (프로퍼티 키) and optional argument argumentsList (ECMAScript 언어 값들의 List) and returns ECMAScript 언어 값을 담는 normal completion 또는 throw completion. ECMAScript 언어 값의 메서드 프로퍼티를 호출하는 데 사용됩니다. V는 프로퍼티 조회 지점이자 호출의 this 값입니다. argumentsList는 메서드에 전달되는 인자 값 리스트입니다. argumentsList가 없으면 새 빈 List가 사용됩니다. It performs the following steps when called:

  1. argumentsList가 존재하지 않으면 새 빈 List로 둔다.
  2. func을 ? GetV(V, P)로 둔다.
  3. Call(func, V, argumentsList)를 반환한다.

7.3.21 OrdinaryHasInstance ( C, O )

The abstract operation OrdinaryHasInstance takes arguments C (ECMAScript 언어 값) and O (ECMAScript 언어 값) and returns Boolean을 담는 normal completion 또는 throw completion. OC가 제공한 인스턴스 객체 상속 경로를 상속하는지 여부를 결정하는 기본 알고리즘을 구현합니다. It performs the following steps when called:

  1. IsCallable(C)가 false이면 false를 반환한다.
  2. C[[BoundTargetFunction]] 내부 슬롯을 가지면,
    1. BCC.[[BoundTargetFunction]]으로 둔다.
    2. InstanceofOperator(O, BC)를 반환한다.
  3. O가 Object가 아니면 false를 반환한다.
  4. P를 ? Get(C, "prototype")으로 둔다.
  5. P가 Object가 아니면 TypeError 예외를 던진다.
  6. 반복,
    1. O를 ? O.[[GetPrototypeOf]]()로 둔다.
    2. Onull이면 false를 반환한다.
    3. SameValue(P, O)가 true이면 true를 반환한다.

7.3.22 SpeciesConstructor ( O, defaultConstructor )

The abstract operation SpeciesConstructor takes arguments O (Object) and defaultConstructor (생성자) and returns 생성자를 담는 normal completion 또는 throw completion. O로부터 파생된 새 객체를 생성할 때 사용해야 하는 생성자를 가져오는 데 사용됩니다. defaultConstructorO부터 시작하여 %Symbol.species% 프로퍼티 생성자를 찾을 수 없을 때 사용할 생성자입니다. It performs the following steps when called:

  1. C를 ? Get(O, "constructor")로 둔다.
  2. Cundefined이면 defaultConstructor를 반환한다.
  3. C가 Object가 아니면 TypeError 예외를 던진다.
  4. S를 ? Get(C, %Symbol.species%)로 둔다.
  5. Sundefined 또는 null이면 defaultConstructor를 반환한다.
  6. IsConstructor(S)가 true이면 S를 반환한다.
  7. TypeError 예외를 던진다.

7.3.23 EnumerableOwnProperties ( O, kind )

The abstract operation EnumerableOwnProperties takes arguments O (Object) and kind (key, value, 또는 key+value) and returns ECMAScript 언어 값들의 List를 담는 normal completion 또는 throw completion. It performs the following steps when called:

  1. ownKeys를 ? O.[[OwnPropertyKeys]]()로 둔다.
  2. results를 새 빈 List로 둔다.
  3. ownKeys의 각 요소 key에 대해
    1. key가 String이면,
      1. desc를 ? O.[[GetOwnProperty]](key)로 둔다.
      2. descundefined가 아니고 desc.[[Enumerable]]true이면,
        1. kindkey이면
          1. keyresults에 추가한다.
        2. Else,
          1. value를 ? Get(O, key)로 둔다.
          2. kindvalue이면
            1. valueresults에 추가한다.
          3. Else,
            1. 단언: kindkey+value.
            2. entryCreateArrayFromListkey, value »)로 둔다.
            3. entryresults에 추가한다.
  4. results를 반환한다.

7.3.24 GetFunctionRealm ( obj )

The abstract operation GetFunctionRealm takes argument obj (함수 객체) and returns Realm Record를 담는 normal completion 또는 throw completion. It performs the following steps when called:

  1. obj[[Realm]] 내부 슬롯을 가지면
    1. obj.[[Realm]]을 반환한다.
  2. obj가 bound function exotic 객체이면
    1. boundTargetFunctionobj.[[BoundTargetFunction]]으로 둔다.
    2. GetFunctionRealm(boundTargetFunction)을 반환한다.
  3. obj가 Proxy 이국 객체이면
    1. ValidateNonRevokedProxy(obj)를 수행한다.
    2. proxyTargetobj.[[ProxyTarget]]으로 둔다.
    3. 단언: proxyTarget함수 객체이다.
    4. GetFunctionRealm(proxyTarget)을 반환한다.
  4. 현재 Realm Record를 반환한다.
Note

4 단계는 obj[[Realm]] 내부 슬롯이 없는 비표준 함수 이국 객체인 경우에만 도달합니다.

7.3.25 CopyDataProperties ( target, source, excludedItems )

The abstract operation CopyDataProperties takes arguments target (Object), source (ECMAScript 언어 값), and excludedItems (프로퍼티 키들의 List) and returns unused을 담는 normal completion 또는 throw completion. It performs the following steps when called:

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

여기에 전달되는 target은 항상 새로 생성된 객체이며, 오류 발생 시 직접 접근할 수 없습니다.

7.3.26 PrivateElementFind ( O, P )

The abstract operation PrivateElementFind takes arguments O (Object) and P (Private Name) and returns PrivateElement 또는 empty. It performs the following steps when called:

  1. O.[[PrivateElements]]pe.[[Key]]PPrivateElement pe를 포함하면
    1. pe를 반환한다.
  2. empty를 반환한다.

7.3.27 PrivateFieldAdd ( O, P, value )

The abstract operation PrivateFieldAdd takes arguments O (Object), P (Private Name), and value (ECMAScript 언어 값) and returns unused을 담는 normal completion 또는 throw completion. It performs the following steps when called:

  1. 호스트가 웹 브라우저이면
    1. HostEnsureCanAddPrivateElement(O)를 수행한다.
  2. entryPrivateElementFind(O, P)로 둔다.
  3. entryempty가 아니면 TypeError 예외를 던진다.
  4. PrivateElement { [[Key]]: P, [[Kind]]: field, [[Value]]: value }를 O.[[PrivateElements]]에 추가한다.
  5. unused를 반환한다.

7.3.28 PrivateMethodOrAccessorAdd ( O, method )

The abstract operation PrivateMethodOrAccessorAdd takes arguments O (Object) and method (PrivateElement) and returns unused을 담는 normal completion 또는 throw completion. It performs the following steps when called:

  1. 단언: method.[[Kind]]method 또는 accessor이다.
  2. 호스트가 웹 브라우저이면
    1. HostEnsureCanAddPrivateElement(O)를 수행한다.
  3. entryPrivateElementFind(O, method.[[Key]])로 둔다.
  4. entryempty가 아니면 TypeError 예외를 던진다.
  5. methodO.[[PrivateElements]]에 추가한다.
  6. unused를 반환한다.
Note

private 메서드와 접근자의 값은 인스턴스 간에 공유됩니다. 이 연산은 메서드나 접근자의 새 복사본을 만들지 않습니다.

7.3.29 HostEnsureCanAddPrivateElement ( O )

The host-defined abstract operation HostEnsureCanAddPrivateElement takes argument O (Object) and returns unused을 담는 normal completion 또는 throw completion. 호스트 환경이 특정 호스트 정의 exotic 객체에 private element 추가를 방지할 수 있도록 합니다.

HostEnsureCanAddPrivateElement 구현은 다음 요구사항을 따라야 합니다:

  • O호스트 정의 exotic 객체가 아니면 이 추상 연산은 NormalCompletion(unused)을 반환하고 다른 단계를 수행하지 않아야 합니다.
  • 같은 인수로 이 추상 연산을 두 번 호출하면 동일한 종류의 Completion Record를 반환해야 합니다.

HostEnsureCanAddPrivateElement의 기본 구현은 NormalCompletion(unused)을 반환하는 것입니다.

이 추상 연산은 ECMAScript 호스트가 웹 브라우저인 경우에만 호출됩니다.

7.3.30 PrivateGet ( O, P )

The abstract operation PrivateGet takes arguments O (Object) and P (Private Name) and returns ECMAScript 언어 값을 담는 normal completion 또는 throw completion. It performs the following steps when called:

  1. entryPrivateElementFind(O, P)로 둔다.
  2. entryempty이면 TypeError 예외를 던진다.
  3. entry.[[Kind]]field 또는 method이면
    1. entry.[[Value]]를 반환한다.
  4. 단언: entry.[[Kind]]accessor이다.
  5. entry.[[Get]]undefined이면 TypeError 예외를 던진다.
  6. getterentry.[[Get]]으로 둔다.
  7. Call(getter, O)를 반환한다.

7.3.31 PrivateSet ( O, P, value )

The abstract operation PrivateSet takes arguments O (Object), P (Private Name), and value (ECMAScript 언어 값) and returns unused을 담는 normal completion 또는 throw completion. It performs the following steps when called:

  1. entryPrivateElementFind(O, P)로 둔다.
  2. entryempty이면 TypeError 예외를 던진다.
  3. entry.[[Kind]]field이면
    1. entry.[[Value]]value로 설정한다.
  4. Else if entry.[[Kind]]method이면
    1. TypeError 예외를 던진다.
  5. Else,
    1. 단언: entry.[[Kind]]accessor.
    2. entry.[[Set]]undefined이면 TypeError 예외를 던진다.
    3. setterentry.[[Set]]으로 둔다.
    4. Call(setter, O, « value »)를 수행한다.
  6. unused를 반환한다.

7.3.32 DefineField ( receiver, fieldRecord )

The abstract operation DefineField takes arguments receiver (Object) and fieldRecord (ClassFieldDefinition Record) and returns unused을 담는 normal completion 또는 throw completion. It performs the following steps when called:

  1. fieldNamefieldRecord.[[Name]]으로 둔다.
  2. initializerfieldRecord.[[Initializer]]로 둔다.
  3. initializerempty가 아니면
    1. initValue를 ? Call(initializer, receiver)로 둔다.
  4. Else,
    1. initValueundefined로 둔다.
  5. fieldNamePrivate Name이면
    1. PrivateFieldAdd(receiver, fieldName, initValue)를 수행한다.
  6. Else,
    1. 단언: fieldName프로퍼티 키이다.
    2. CreateDataPropertyOrThrow(receiver, fieldName, initValue)를 수행한다.
  7. unused를 반환한다.

7.3.33 InitializeInstanceElements ( O, constructor )

The abstract operation InitializeInstanceElements takes arguments O (Object) and constructor (ECMAScript 함수 객체) and returns unused을 담는 normal completion 또는 throw completion. It performs the following steps when called:

  1. methodsconstructor.[[PrivateMethods]]로 둔다.
  2. methods의 각 PrivateElement method에 대해
    1. PrivateMethodOrAccessorAdd(O, method)를 수행한다.
  3. fieldsconstructor.[[Fields]]로 둔다.
  4. fields의 각 요소 fieldRecord에 대해
    1. DefineField(O, fieldRecord)를 수행한다.
  5. unused를 반환한다.

7.3.34 AddValueToKeyedGroup ( groups, key, value )

The abstract operation AddValueToKeyedGroup takes arguments groups (필드 [[Key]](ECMAScript 언어 값)와 [[Elements]](ECMAScript 언어 값들의 List)를 가진 Record들의 List), key (ECMAScript 언어 값), and value (ECMAScript 언어 값) and returns unused. It performs the following steps when called:

  1. groups의 각 Record { [[Key]], [[Elements]] } g에 대해
    1. SameValue(g.[[Key]], key)가 true이면
      1. 단언: 정확히 한 요소만 이 조건을 만족한다.
      2. valueg.[[Elements]]에 추가한다.
      3. unused를 반환한다.
  2. groupRecord { [[Key]]: key, [[Elements]]: « value » }로 둔다.
  3. groupgroups에 추가한다.
  4. unused를 반환한다.

7.3.35 GroupBy ( items, callback, keyCoercion )

The abstract operation GroupBy takes arguments items (ECMAScript 언어 값), callback (ECMAScript 언어 값), and keyCoercion (property 또는 collection) and returns 필드 [[Key]](ECMAScript 언어 값) 및 [[Elements]](ECMAScript 언어 값들의 List)를 가진 Record들의 List를 담는 normal completion 또는 throw completion. It performs the following steps when called:

  1. RequireObjectCoercible(items)를 수행한다.
  2. IsCallable(callback)이 false이면 TypeError 예외를 던진다.
  3. groups를 새 빈 List로 둔다.
  4. iteratorRecord를 ? GetIterator(items, sync)로 둔다.
  5. k를 0으로 둔다.
  6. 반복,
    1. k ≥ 253 - 1이면
      1. errorThrowCompletion(새로 생성된 TypeError 객체)로 둔다.
      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. Else,
      1. 단언: keyCoercioncollection.
      2. keyCanonicalizeKeyedCollectionKey(key)로 둔다.
    9. AddValueToKeyedGroup(groups, key, value)를 수행한다.
    10. kk + 1로 둔다.

7.3.36 SetterThatIgnoresPrototypeProperties ( thisValue, home, p, v )

The abstract operation SetterThatIgnoresPrototypeProperties takes arguments thisValue (ECMAScript 언어 값), home (Object), p (프로퍼티 키), and v (ECMAScript 언어 값) and returns unused을 담는 normal completion 또는 throw completion. It performs the following steps when called:

  1. thisValue가 Object가 아니면
    1. TypeError 예외를 던진다.
  2. SameValue(thisValue, home)가 true이면
    1. 주: 여기서 던지는 것은 strict mode 코드에서 home 객체의 쓰기 불가능 데이터 프로퍼티에 대입하는 것과 유사하다.
    2. TypeError 예외를 던진다.
  3. desc를 ? thisValue.[[GetOwnProperty]](p)로 둔다.
  4. descundefined이면
    1. CreateDataPropertyOrThrow(thisValue, p, v)를 수행한다.
  5. Else,
    1. Set(thisValue, p, v, true)를 수행한다.
  6. unused를 반환한다.

7.4 이터레이터 객체에 대한 연산(Operations on Iterator Objects)

공통 반복 인터페이스는 27.1 참조.

7.4.1 Iterator Record

Iterator Record는 이터레이터 또는 async 이터레이터와 그 next 메서드를 캡슐화하는 데 사용되는 Record 값입니다.

Iterator Record는 Table 13에 나열된 필드를 가집니다.

Table 13: Iterator Record 필드
필드 이름 의미
[[Iterator]] Object 이터레이터 인터페이스 또는 async 이터레이터 인터페이스를 준수하는 객체.
[[NextMethod]] ECMAScript 언어 값 [[Iterator]] 객체의 next 메서드.
[[Done]] Boolean 이터레이터가 완료되었거나 닫혔는지 여부.

7.4.2 GetIteratorDirect ( obj )

The abstract operation GetIteratorDirect takes argument obj (Object) and returns Iterator Record를 담는 normal completion 또는 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 (ECMAScript 언어 값) and method (함수 객체) and returns Iterator Record를 담는 normal completion 또는 throw completion. It performs the following steps when called:

  1. iterator를 ? Call(method, obj)로 둔다.
  2. iterator가 Object가 아니면 TypeError 예외를 던진다.
  3. GetIteratorDirect(iterator)를 반환한다.

7.4.4 GetIterator ( obj, kind )

The abstract operation GetIterator takes arguments obj (ECMAScript 언어 값) and kind (sync 또는 async) and returns Iterator Record를 담는 normal completion 또는 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 예외를 던진다.
      3. syncIteratorRecord를 ? GetIteratorFromMethod(obj, syncMethod)로 둔다.
      4. CreateAsyncFromSyncIterator(syncIteratorRecord)를 반환한다.
  2. Else,
    1. method를 ? GetMethod(obj, %Symbol.iterator%)로 둔다.
  3. methodundefined이면 TypeError 예외를 던진다.
  4. GetIteratorFromMethod(obj, method)를 반환한다.

7.4.5 GetIteratorFlattenable ( obj, primitiveHandling )

The abstract operation GetIteratorFlattenable takes arguments obj (ECMAScript 언어 값) and primitiveHandling (iterate-string-primitives 또는 reject-primitives) and returns Iterator Record를 담는 normal completion 또는 throw completion. It performs the following steps when called:

  1. obj가 Object가 아니면,
    1. primitiveHandlingreject-primitives이면 TypeError 예외를 던진다.
    2. 단언: primitiveHandlingiterate-string-primitives.
    3. obj가 String이 아니면 TypeError 예외를 던진다.
  2. method를 ? GetMethod(obj, %Symbol.iterator%)로 둔다.
  3. methodundefined이면
    1. iteratorobj로 둔다.
  4. Else,
    1. iterator를 ? Call(method, obj)로 둔다.
  5. iterator가 Object가 아니면 TypeError 예외를 던진다.
  6. GetIteratorDirect(iterator)를 반환한다.

7.4.6 IteratorNext ( iteratorRecord [ , value ] )

The abstract operation IteratorNext takes argument iteratorRecord (Iterator Record) and optional argument value (ECMAScript 언어 값) and returns Object를 담는 normal completion 또는 throw completion. It performs the following steps when called:

  1. value가 존재하지 않으면
    1. resultCompletion(Call(iteratorRecord.[[NextMethod]], iteratorRecord.[[Iterator]]))로 둔다.
  2. Else,
    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 예외를 던진다.
  6. result를 반환한다.

7.4.7 IteratorComplete ( iteratorResult )

The abstract operation IteratorComplete takes argument iteratorResult (Object) and returns Boolean을 담는 normal completion 또는 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 (Object) and returns ECMAScript 언어 값을 담는 normal completion 또는 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 (Iterator Record) and returns Object 또는 done을 담는 normal completion 또는 throw completion. iteratorRecord.[[Iterator]]에서 iteratorRecord.[[NextMethod]]를 호출해 다음 값을 요청하고, 이터레이터가 끝에 도달했음을 나타내는 done 또는 다음 값을 사용할 수 있다면 IteratorResult 객체를 반환합니다. It performs the following steps when called:

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

7.4.10 IteratorStepValue ( iteratorRecord )

The abstract operation IteratorStepValue takes argument iteratorRecord (Iterator Record) and returns ECMAScript 언어 값 또는 done을 담는 normal completion 또는 throw completion. iteratorRecord.[[Iterator]]에서 iteratorRecord.[[NextMethod]]를 호출해 다음 값을 요청하고, 끝에 도달했으면 done을, 다음 값이 있으면 IteratorResult 객체의 값을 반환합니다. It performs the following steps when called:

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

7.4.11 IteratorClose ( iteratorRecord, completion )

The abstract operation IteratorClose takes arguments iteratorRecord (Iterator Record) and completion (Completion Record) and returns Completion Record. 이터레이터가 완료 상태에 도달했을 때 일반적으로 수행할 동작을 실행하도록 알리는 데 사용됩니다. It performs the following steps when called:

  1. 단언: 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 예외를 던진다.
  8. completion을 반환한다.

7.4.12 IfAbruptCloseIterator ( value, iteratorRecord )

IfAbruptCloseIterator는 Iterator Record를 사용하는 알고리즘 단계의 축약 표현입니다. 다음 형태의 알고리즘 단계:

  1. IfAbruptCloseIterator(value, iteratorRecord).

는 다음과 동일한 의미입니다:

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

7.4.13 AsyncIteratorClose ( iteratorRecord, completion )

The abstract operation AsyncIteratorClose takes arguments iteratorRecord (Iterator Record) and completion (Completion Record) and returns Completion Record. async 이터레이터가 완료 상태에 도달했을 때 일반적으로 수행할 동작을 실행하도록 알리는 데 사용됩니다. It performs the following steps when called:

  1. 단언: 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 예외를 던진다.
  8. completion을 반환한다.

7.4.14 CreateIteratorResultObject ( value, done )

The abstract operation CreateIteratorResultObject takes arguments value (ECMAScript 언어 값) and done (Boolean) and returns IteratorResult 인터페이스를 준수하는 Object. IteratorResult 인터페이스를 준수하는 객체를 생성합니다. 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.15 CreateListIteratorRecord ( list )

The abstract operation CreateListIteratorRecord takes argument list (ECMAScript 언어 값들의 List) and returns Iterator Record. [[NextMethod]]list의 연속 요소를 반환하는 Iterator Record를 생성합니다. It performs the following steps when called:

  1. closure를 매개변수 없고 list를 캡처하며 호출 시 다음 단계를 수행하는 새 Abstract Closure로 둔다:
    1. list의 각 요소 E에 대해
      1. GeneratorYield(CreateIteratorResultObject(E, false))를 수행한다.
    2. NormalCompletion(undefined)를 반환한다.
  2. iteratorCreateIteratorFromClosure(closure, empty, %Iterator.prototype%)로 둔다.
  3. Iterator Record { [[Iterator]]: iterator, [[NextMethod]]: %GeneratorPrototype.next%, [[Done]]: false }를 반환한다.
Note

list 이터레이터 객체는 ECMAScript 코드에서 직접 접근할 수 없습니다.

7.4.16 IteratorToList ( iteratorRecord )

The abstract operation IteratorToList takes argument iteratorRecord (Iterator Record) and returns ECMAScript 언어 값들의 List를 담는 normal completion 또는 throw completion. It performs the following steps when called:

  1. values를 새 빈 List로 둔다.
  2. 반복,
    1. next를 ? IteratorStepValue(iteratorRecord)로 둔다.
    2. nextdone이면
      1. values를 반환한다.
    3. nextvalues에 추가한다.

8 구문 지향 연산(Syntax-Directed Operations)

이 절에서 정의된 것들 외에도, 특수화된 구문 지향 연산들이 이 명세 전반에 걸쳐 정의된다.

8.1 런타임 의미론: Evaluation : Completion Record

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS.

Note
이 연산의 정의는 이 명세의 "ECMAScript Language" 절들에 분산되어 있다. 각 정의는 관련 생성규칙(production)이 정의적으로 등장한 직후에 나타난다.

8.2 스코프 분석(Scope Analysis)

8.2.1 정적 의미론: BoundNames : 문자열들의 List

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS.

Note

"*default*" 문자열은 모듈의 기본(default) export가 다른 이름을 가지지 않을 때 그 모듈의 기본 export를 위한 합성된 이름으로 이 명세 내부에서 사용된다. 모듈의 [[Environment]] 내에 그 이름으로 항목이 생성되어 해당 값을 보유하고, 모듈에 대해 ResolveExport ( exportName [ , resolveSet ] )를 호출하여 "default"라는 export를 해석하면 [[BindingName]]"*default*"ResolvedBinding Record를 반환하며, 이는 모듈 [[Environment]]에서 상술한 값으로 다시 해석된다. 이는 명세 편의를 위한 것이며, 익명 기본 export도 다른 export와 동일하게 해석될 수 있도록 한다. 이 "*default*" 문자열은 ECMAScript 코드나 모듈 링크 알고리즘에서 접근될 수 없다.

It is defined piecewise over the following productions:

BindingIdentifier : Identifier
  1. Identifier의 StringValue만을 요소로 갖는 List를 반환한다.
BindingIdentifier : yield
  1. « "yield" » 를 반환한다.
BindingIdentifier : await
  1. « "await" » 를 반환한다.
LexicalDeclaration : LetOrConst BindingList ;
  1. BindingList의 BoundNames를 반환한다.
BindingList : BindingList , LexicalBinding
  1. names1BindingList의 BoundNames로 둔다.
  2. names2LexicalBinding의 BoundNames로 둔다.
  3. names1names2list-concatenation을 반환한다.
LexicalBinding : BindingIdentifier Initializeropt
  1. BindingIdentifier의 BoundNames를 반환한다.
LexicalBinding : BindingPattern Initializer
  1. BindingPattern의 BoundNames를 반환한다.
VariableDeclarationList : VariableDeclarationList , VariableDeclaration
  1. names1VariableDeclarationList의 BoundNames로 둔다.
  2. names2VariableDeclaration의 BoundNames로 둔다.
  3. names1names2list-concatenation을 반환한다.
VariableDeclaration : BindingIdentifier Initializeropt
  1. BindingIdentifier의 BoundNames를 반환한다.
VariableDeclaration : BindingPattern Initializer
  1. BindingPattern의 BoundNames를 반환한다.
ObjectBindingPattern : { }
  1. 새 빈 List를 반환한다.
ObjectBindingPattern : { BindingPropertyList , BindingRestProperty }
  1. names1BindingPropertyList의 BoundNames로 둔다.
  2. names2BindingRestProperty의 BoundNames로 둔다.
  3. names1names2list-concatenation을 반환한다.
ArrayBindingPattern : [ Elisionopt ]
  1. 새 빈 List를 반환한다.
ArrayBindingPattern : [ Elisionopt BindingRestElement ]
  1. BindingRestElement의 BoundNames를 반환한다.
ArrayBindingPattern : [ BindingElementList , Elisionopt ]
  1. BindingElementList의 BoundNames를 반환한다.
ArrayBindingPattern : [ BindingElementList , Elisionopt BindingRestElement ]
  1. names1BindingElementList의 BoundNames로 둔다.
  2. names2BindingRestElement의 BoundNames로 둔다.
  3. names1names2list-concatenation을 반환한다.
BindingPropertyList : BindingPropertyList , BindingProperty
  1. names1BindingPropertyList의 BoundNames로 둔다.
  2. names2BindingProperty의 BoundNames로 둔다.
  3. names1names2list-concatenation을 반환한다.
BindingElementList : BindingElementList , BindingElisionElement
  1. names1BindingElementList의 BoundNames로 둔다.
  2. names2BindingElisionElement의 BoundNames로 둔다.
  3. names1names2list-concatenation을 반환한다.
BindingElisionElement : Elisionopt BindingElement
  1. BindingElement의 BoundNames를 반환한다.
BindingProperty : PropertyName : BindingElement
  1. BindingElement의 BoundNames를 반환한다.
SingleNameBinding : BindingIdentifier Initializeropt
  1. BindingIdentifier의 BoundNames를 반환한다.
BindingElement : BindingPattern Initializeropt
  1. BindingPattern의 BoundNames를 반환한다.
ForDeclaration : LetOrConst ForBinding
  1. ForBinding의 BoundNames를 반환한다.
FunctionDeclaration : function BindingIdentifier ( FormalParameters ) { FunctionBody }
  1. BindingIdentifier의 BoundNames를 반환한다.
FunctionDeclaration : function ( FormalParameters ) { FunctionBody }
  1. « "*default*" » 를 반환한다.
FormalParameters : [empty]
  1. 새 빈 List를 반환한다.
FormalParameters : FormalParameterList , FunctionRestParameter
  1. names1FormalParameterList의 BoundNames로 둔다.
  2. names2FunctionRestParameter의 BoundNames로 둔다.
  3. names1names2list-concatenation을 반환한다.
FormalParameterList : FormalParameterList , FormalParameter
  1. names1FormalParameterList의 BoundNames로 둔다.
  2. names2FormalParameter의 BoundNames로 둔다.
  3. names1names2list-concatenation을 반환한다.
ArrowParameters : CoverParenthesizedExpressionAndArrowParameterList
  1. formalsCoverParenthesizedExpressionAndArrowParameterList가 커버하는 ArrowFormalParameters로 둔다.
  2. formals의 BoundNames를 반환한다.
GeneratorDeclaration : function * BindingIdentifier ( FormalParameters ) { GeneratorBody }
  1. BindingIdentifier의 BoundNames를 반환한다.
GeneratorDeclaration : function * ( FormalParameters ) { GeneratorBody }
  1. « "*default*" » 를 반환한다.
AsyncGeneratorDeclaration : async function * BindingIdentifier ( FormalParameters ) { AsyncGeneratorBody }
  1. BindingIdentifier의 BoundNames를 반환한다.
AsyncGeneratorDeclaration : async function * ( FormalParameters ) { AsyncGeneratorBody }
  1. « "*default*" » 를 반환한다.
ClassDeclaration : class BindingIdentifier ClassTail
  1. BindingIdentifier의 BoundNames를 반환한다.
ClassDeclaration : class ClassTail
  1. « "*default*" » 를 반환한다.
AsyncFunctionDeclaration : async function BindingIdentifier ( FormalParameters ) { AsyncFunctionBody }
  1. BindingIdentifier의 BoundNames를 반환한다.
AsyncFunctionDeclaration : async function ( FormalParameters ) { AsyncFunctionBody }
  1. « "*default*" » 를 반환한다.
CoverCallExpressionAndAsyncArrowHead : MemberExpression Arguments
  1. headCoverCallExpressionAndAsyncArrowHead가 커버하는 AsyncArrowHead로 둔다.
  2. head의 BoundNames를 반환한다.
ImportDeclaration : import ImportClause FromClause WithClauseopt ;
  1. ImportClause의 BoundNames를 반환한다.
ImportDeclaration : import ModuleSpecifier WithClauseopt ;
  1. 새 빈 List를 반환한다.
ImportClause : ImportedDefaultBinding , NameSpaceImport
  1. names1ImportedDefaultBinding의 BoundNames로 둔다.
  2. names2NameSpaceImport의 BoundNames로 둔다.
  3. names1names2list-concatenation을 반환한다.
ImportClause : ImportedDefaultBinding , NamedImports
  1. names1ImportedDefaultBinding의 BoundNames로 둔다.
  2. names2NamedImports의 BoundNames로 둔다.
  3. names1names2list-concatenation을 반환한다.
NamedImports : { }
  1. 새 빈 List를 반환한다.
ImportsList : ImportsList , ImportSpecifier
  1. names1ImportsList의 BoundNames로 둔다.
  2. names2ImportSpecifier의 BoundNames로 둔다.
  3. names1names2list-concatenation을 반환한다.
ImportSpecifier : ModuleExportName as ImportedBinding
  1. ImportedBinding의 BoundNames를 반환한다.
ExportDeclaration : export ExportFromClause FromClause WithClauseopt ; export NamedExports ;
  1. 새 빈 List를 반환한다.
ExportDeclaration : export VariableStatement
  1. VariableStatement의 BoundNames를 반환한다.
ExportDeclaration : export Declaration
  1. Declaration의 BoundNames를 반환한다.
ExportDeclaration : export default HoistableDeclaration
  1. declarationNamesHoistableDeclaration의 BoundNames로 둔다.
  2. declarationNames"*default*" 요소가 없으면 "*default*"declarationNames에 추가한다.
  3. declarationNames를 반환한다.
ExportDeclaration : export default ClassDeclaration
  1. declarationNamesClassDeclaration의 BoundNames로 둔다.
  2. declarationNames"*default*" 요소가 없으면 "*default*"declarationNames에 추가한다.
  3. declarationNames를 반환한다.
ExportDeclaration : export default AssignmentExpression ;
  1. « "*default*" » 를 반환한다.

8.2.2 정적 의미론: DeclarationPart : Parse Node

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. 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 정적 의미론: IsConstantDeclaration : Boolean

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. It is defined piecewise over the following productions:

LexicalDeclaration : LetOrConst BindingList ;
  1. LetOrConst의 IsConstantDeclaration을 반환한다.
LetOrConst : let
  1. false를 반환한다.
LetOrConst : const
  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을 상수 선언으로 다룰 필요는 없다. 이는 모듈의 기본 객체를 참조하는 내부 바운드 이름에 대입을 허용하는 구문이 존재하지 않기 때문이다.

8.2.4 정적 의미론: LexicallyDeclaredNames : 문자열들의 List

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. It is defined piecewise over the following productions:

Block : { }
  1. 새 빈 List를 반환한다.
StatementList : StatementList StatementListItem
  1. names1StatementList의 LexicallyDeclaredNames로 둔다.
  2. names2StatementListItem의 LexicallyDeclaredNames로 둔다.
  3. names1names2list-concatenation을 반환한다.
StatementListItem : Statement
  1. Statement Statement : LabelledStatement 이면 LabelledStatement의 LexicallyDeclaredNames를 반환한다.
  2. 새 빈 List를 반환한다.
StatementListItem : Declaration
  1. Declaration의 BoundNames를 반환한다.
CaseBlock : { }
  1. 새 빈 List를 반환한다.
CaseBlock : { CaseClausesopt DefaultClause CaseClausesopt }
  1. 첫 번째 CaseClauses가 존재하면 names1을 그 LexicallyDeclaredNames로 둔다.
  2. 아니면 names1을 새 빈 List로 둔다.
  3. names2DefaultClause의 LexicallyDeclaredNames로 둔다.
  4. 두 번째 CaseClauses가 존재하면 names3을 그 LexicallyDeclaredNames로 둔다.
  5. 아니면 names3을 새 빈 List로 둔다.
  6. names1, names2, names3list-concatenation을 반환한다.
CaseClauses : CaseClauses CaseClause
  1. names1CaseClauses의 LexicallyDeclaredNames로 둔다.
  2. names2CaseClause의 LexicallyDeclaredNames로 둔다.
  3. names1names2list-concatenation을 반환한다.
CaseClause : case Expression : StatementListopt
  1. StatementList가 존재하면 StatementList의 LexicallyDeclaredNames를 반환한다.
  2. 새 빈 List를 반환한다.
DefaultClause : default : StatementListopt
  1. StatementList가 존재하면 StatementList의 LexicallyDeclaredNames를 반환한다.
  2. 새 빈 List를 반환한다.
LabelledStatement : LabelIdentifier : LabelledItem
  1. LabelledItem의 LexicallyDeclaredNames를 반환한다.
LabelledItem : Statement
  1. 새 빈 List를 반환한다.
LabelledItem : FunctionDeclaration
  1. FunctionDeclaration의 BoundNames를 반환한다.
FunctionStatementList : [empty]
  1. 새 빈 List를 반환한다.
FunctionStatementList : StatementList
  1. StatementList의 TopLevelLexicallyDeclaredNames를 반환한다.
ClassStaticBlockStatementList : [empty]
  1. 새 빈 List를 반환한다.
ClassStaticBlockStatementList : StatementList
  1. StatementList의 TopLevelLexicallyDeclaredNames를 반환한다.
ConciseBody : ExpressionBody
  1. 새 빈 List를 반환한다.
AsyncConciseBody : ExpressionBody
  1. 새 빈 List를 반환한다.
Script : [empty]
  1. 새 빈 List를 반환한다.
ScriptBody : StatementList
  1. StatementList의 TopLevelLexicallyDeclaredNames를 반환한다.
Note 1

Script의 최상위(top level)에서 함수 선언은 lexical 선언이 아닌 var 선언처럼 다루어진다.

Note 2

Module의 LexicallyDeclaredNames에는 모든 import된 바인딩의 이름이 포함된다.

ModuleItemList : ModuleItemList ModuleItem
  1. names1ModuleItemList의 LexicallyDeclaredNames로 둔다.
  2. names2ModuleItem의 LexicallyDeclaredNames로 둔다.
  3. names1names2list-concatenation을 반환한다.
ModuleItem : ImportDeclaration
  1. ImportDeclaration의 BoundNames를 반환한다.
ModuleItem : ExportDeclaration
  1. ExportDeclarationexport VariableStatement이면 새 빈 List를 반환한다.
  2. ExportDeclaration의 BoundNames를 반환한다.
ModuleItem : StatementListItem
  1. StatementListItem의 LexicallyDeclaredNames를 반환한다.
Note 3

Module의 최상위에서는 함수 선언이 var 선언이 아닌 lexical 선언처럼 다루어진다.

8.2.5 정적 의미론: LexicallyScopedDeclarations : Parse Node들의 List

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. It is defined piecewise over the following productions:

StatementList : StatementList StatementListItem
  1. declarations1StatementList의 LexicallyScopedDeclarations로 둔다.
  2. declarations2StatementListItem의 LexicallyScopedDeclarations로 둔다.
  3. declarations1declarations2list-concatenation을 반환한다.
StatementListItem : Statement
  1. Statement Statement : LabelledStatement 이면 LabelledStatement의 LexicallyScopedDeclarations를 반환한다.
  2. 새 빈 List를 반환한다.
StatementListItem : Declaration
  1. Declaration의 DeclarationPart만을 요소로 갖는 List를 반환한다.
CaseBlock : { }
  1. 새 빈 List를 반환한다.
CaseBlock : { CaseClausesopt DefaultClause CaseClausesopt }
  1. 첫 번째 CaseClauses가 존재하면 declarations1을 그 LexicallyScopedDeclarations로 둔다.
  2. 아니면 declarations1을 새 빈 List로 둔다.
  3. declarations2DefaultClause의 LexicallyScopedDeclarations로 둔다.
  4. 두 번째 CaseClauses가 존재하면 declarations3을 그 LexicallyScopedDeclarations로 둔다.
  5. 아니면 declarations3을 새 빈 List로 둔다.
  6. declarations1, declarations2, declarations3list-concatenation을 반환한다.
CaseClauses : CaseClauses CaseClause
  1. declarations1CaseClauses의 LexicallyScopedDeclarations로 둔다.
  2. declarations2CaseClause의 LexicallyScopedDeclarations로 둔다.
  3. declarations1declarations2list-concatenation을 반환한다.
CaseClause : case Expression : StatementListopt
  1. StatementList가 존재하면 StatementList의 LexicallyScopedDeclarations를 반환한다.
  2. 새 빈 List를 반환한다.
DefaultClause : default : StatementListopt
  1. StatementList가 존재하면 StatementList의 LexicallyScopedDeclarations를 반환한다.
  2. 새 빈 List를 반환한다.
LabelledStatement : LabelIdentifier : LabelledItem
  1. LabelledItem의 LexicallyScopedDeclarations를 반환한다.
LabelledItem : Statement
  1. 새 빈 List를 반환한다.
LabelledItem : FunctionDeclaration
  1. « FunctionDeclaration » 를 반환한다.
FunctionStatementList : [empty]
  1. 새 빈 List를 반환한다.
FunctionStatementList : StatementList
  1. StatementList의 TopLevelLexicallyScopedDeclarations를 반환한다.
ClassStaticBlockStatementList : [empty]
  1. 새 빈 List를 반환한다.
ClassStaticBlockStatementList : StatementList
  1. StatementList의 TopLevelLexicallyScopedDeclarations를 반환한다.
ConciseBody : ExpressionBody
  1. 새 빈 List를 반환한다.
AsyncConciseBody : ExpressionBody
  1. 새 빈 List를 반환한다.
Script : [empty]
  1. 새 빈 List를 반환한다.
ScriptBody : StatementList
  1. StatementList의 TopLevelLexicallyScopedDeclarations를 반환한다.
Module : [empty]
  1. 새 빈 List를 반환한다.
ModuleItemList : ModuleItemList ModuleItem
  1. declarations1ModuleItemList의 LexicallyScopedDeclarations로 둔다.
  2. declarations2ModuleItem의 LexicallyScopedDeclarations로 둔다.
  3. declarations1declarations2list-concatenation을 반환한다.
ModuleItem : ImportDeclaration
  1. 새 빈 List를 반환한다.
ExportDeclaration : export ExportFromClause FromClause WithClauseopt ; export NamedExports ; export VariableStatement
  1. 새 빈 List를 반환한다.
ExportDeclaration : export Declaration
  1. Declaration의 DeclarationPart만을 요소로 갖는 List를 반환한다.
ExportDeclaration : export default HoistableDeclaration
  1. HoistableDeclaration의 DeclarationPart만을 요소로 갖는 List를 반환한다.
ExportDeclaration : export default ClassDeclaration
  1. ClassDeclaration만을 요소로 갖는 List를 반환한다.
ExportDeclaration : export default AssignmentExpression ;
  1. ExportDeclaration만을 요소로 갖는 List를 반환한다.

8.2.6 정적 의미론: VarDeclaredNames : 문자열들의 List

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. It is defined piecewise over the following productions:

Statement : EmptyStatement ExpressionStatement ContinueStatement BreakStatement ReturnStatement ThrowStatement DebuggerStatement
  1. 새 빈 List를 반환한다.
Block : { }
  1. 새 빈 List를 반환한다.
StatementList : StatementList StatementListItem
  1. names1StatementList의 VarDeclaredNames로 둔다.
  2. names2StatementListItem의 VarDeclaredNames로 둔다.
  3. names1names2list-concatenation을 반환한다.
StatementListItem : Declaration
  1. 새 빈 List를 반환한다.
VariableStatement : var VariableDeclarationList ;
  1. VariableDeclarationList의 BoundNames를 반환한다.
IfStatement : if ( Expression ) Statement else Statement
  1. names1을 첫 번째 Statement의 VarDeclaredNames로 둔다.
  2. names2를 두 번째 Statement의 VarDeclaredNames로 둔다.
  3. names1names2list-concatenation을 반환한다.
IfStatement : if ( Expression ) Statement
  1. Statement의 VarDeclaredNames를 반환한다.
DoWhileStatement : do Statement while ( Expression ) ;
  1. Statement의 VarDeclaredNames를 반환한다.
WhileStatement : while ( Expression ) Statement
  1. Statement의 VarDeclaredNames를 반환한다.
ForStatement : for ( Expressionopt ; Expressionopt ; Expressionopt ) Statement
  1. Statement의 VarDeclaredNames를 반환한다.
ForStatement : for ( var VariableDeclarationList ; Expressionopt ; Expressionopt ) Statement
  1. names1VariableDeclarationList의 BoundNames로 둔다.
  2. names2Statement의 VarDeclaredNames로 둔다.
  3. names1names2list-concatenation을 반환한다.
ForStatement : for ( LexicalDeclaration Expressionopt ; Expressionopt ) Statement
  1. Statement의 VarDeclaredNames를 반환한다.
ForInOfStatement : for ( LeftHandSideExpression in Expression ) Statement for ( ForDeclaration in Expression ) Statement for ( LeftHandSideExpression of AssignmentExpression ) Statement for ( ForDeclaration of AssignmentExpression ) Statement for await ( LeftHandSideExpression of AssignmentExpression ) Statement for await ( ForDeclaration of AssignmentExpression ) Statement
  1. Statement의 VarDeclaredNames를 반환한다.
ForInOfStatement : for ( var ForBinding in Expression ) Statement for ( var ForBinding of AssignmentExpression ) Statement for await ( var ForBinding of AssignmentExpression ) Statement
  1. names1을 « ForBinding »으로 둔다.
  2. names2Statement의 VarDeclaredNames로 둔다.
  3. names1names2list-concatenation을 반환한다.
Note

이 절은 부록(Annex) B.3.5에 의해 확장된다.

WithStatement : with ( Expression ) Statement
  1. Statement의 VarDeclaredNames를 반환한다.
SwitchStatement : switch ( Expression ) CaseBlock
  1. CaseBlock의 VarDeclaredNames를 반환한다.
CaseBlock : { }
  1. 새 빈 List를 반환한다.
CaseBlock : { CaseClausesopt DefaultClause CaseClausesopt }
  1. 첫 번째 CaseClauses가 존재하면 names1을 그 VarDeclaredNames로 둔다.
  2. 아니면 names1을 새 빈 List로 둔다.
  3. names2DefaultClause의 VarDeclaredNames로 둔다.
  4. 두 번째 CaseClauses가 존재하면 names3을 그 VarDeclaredNames로 둔다.
  5. 아니면 names3을 새 빈 List로 둔다.
  6. names1, names2, names3list-concatenation을 반환한다.
CaseClauses : CaseClauses CaseClause
  1. names1CaseClauses의 VarDeclaredNames로 둔다.
  2. names2CaseClause의 VarDeclaredNames로 둔다.
  3. names1names2list-concatenation을 반환한다.
CaseClause : case Expression : StatementListopt
  1. StatementList가 존재하면 StatementList의 VarDeclaredNames를 반환한다.
  2. 새 빈 List를 반환한다.
DefaultClause : default : StatementListopt
  1. StatementList가 존재하면 StatementList의 VarDeclaredNames를 반환한다.
  2. 새 빈 List를 반환한다.
LabelledStatement : LabelIdentifier : LabelledItem
  1. LabelledItem의 VarDeclaredNames를 반환한다.
LabelledItem : FunctionDeclaration
  1. 새 빈 List를 반환한다.
TryStatement : try Block Catch
  1. names1Block의 VarDeclaredNames로 둔다.
  2. names2Catch의 VarDeclaredNames로 둔다.
  3. names1names2list-concatenation을 반환한다.
TryStatement : try Block Finally
  1. names1Block의 VarDeclaredNames로 둔다.
  2. names2Finally의 VarDeclaredNames로 둔다.
  3. names1names2list-concatenation을 반환한다.
TryStatement : try Block Catch Finally
  1. names1Block의 VarDeclaredNames로 둔다.
  2. names2Catch의 VarDeclaredNames로 둔다.
  3. names3Finally의 VarDeclaredNames로 둔다.
  4. names1, names2, names3list-concatenation을 반환한다.
Catch : catch ( CatchParameter ) Block
  1. Block의 VarDeclaredNames를 반환한다.
FunctionStatementList : [empty]
  1. 새 빈 List를 반환한다.
FunctionStatementList : StatementList
  1. StatementList의 TopLevelVarDeclaredNames를 반환한다.
ClassStaticBlockStatementList : [empty]
  1. 새 빈 List를 반환한다.
ClassStaticBlockStatementList : StatementList
  1. StatementList의 TopLevelVarDeclaredNames를 반환한다.
ConciseBody : ExpressionBody
  1. 새 빈 List를 반환한다.
AsyncConciseBody : ExpressionBody
  1. 새 빈 List를 반환한다.
Script : [empty]
  1. 새 빈 List를 반환한다.
ScriptBody : StatementList
  1. StatementList의 TopLevelVarDeclaredNames를 반환한다.
ModuleItemList : ModuleItemList ModuleItem
  1. names1ModuleItemList의 VarDeclaredNames로 둔다.
  2. names2ModuleItem의 VarDeclaredNames로 둔다.
  3. names1names2list-concatenation을 반환한다.
ModuleItem : ImportDeclaration
  1. 새 빈 List를 반환한다.
ModuleItem : ExportDeclaration
  1. ExportDeclarationexport VariableStatement이면 ExportDeclaration의 BoundNames를 반환한다.
  2. 새 빈 List를 반환한다.

8.2.7 정적 의미론: VarScopedDeclarations : Parse Node들의 List

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. It is defined piecewise over the following productions:

Statement : EmptyStatement ExpressionStatement ContinueStatement BreakStatement ReturnStatement ThrowStatement DebuggerStatement
  1. 새 빈 List를 반환한다.
Block : { }
  1. 새 빈 List를 반환한다.
StatementList : StatementList StatementListItem
  1. declarations1StatementList의 VarScopedDeclarations로 둔다.
  2. declarations2StatementListItem의 VarScopedDeclarations로 둔다.
  3. declarations1declarations2list-concatenation을 반환한다.
StatementListItem : Declaration
  1. 새 빈 List를 반환한다.
VariableDeclarationList : VariableDeclaration
  1. « VariableDeclaration » 를 반환한다.
VariableDeclarationList : VariableDeclarationList , VariableDeclaration
  1. declarations1VariableDeclarationList의 VarScopedDeclarations로 둔다.
  2. declarations1과 « VariableDeclaration »의 list-concatenation을 반환한다.
IfStatement : if ( Expression ) Statement else Statement
  1. declarations1을 첫 번째 Statement의 VarScopedDeclarations로 둔다.
  2. declarations2를 두 번째 Statement의 VarScopedDeclarations로 둔다.
  3. declarations1declarations2list-concatenation을 반환한다.
IfStatement : if ( Expression ) Statement
  1. Statement의 VarScopedDeclarations를 반환한다.
DoWhileStatement : do Statement while ( Expression ) ;
  1. Statement의 VarScopedDeclarations를 반환한다.
WhileStatement : while ( Expression ) Statement
  1. Statement의 VarScopedDeclarations를 반환한다.
ForStatement : for ( Expressionopt ; Expressionopt ; Expressionopt ) Statement
  1. Statement의 VarScopedDeclarations를 반환한다.
ForStatement : for ( var VariableDeclarationList ; Expressionopt ; Expressionopt ) Statement
  1. declarations1VariableDeclarationList의 VarScopedDeclarations로 둔다.
  2. declarations2Statement의 VarScopedDeclarations로 둔다.
  3. declarations1declarations2list-concatenation을 반환한다.
ForStatement : for ( LexicalDeclaration Expressionopt ; Expressionopt ) Statement
  1. Statement의 VarScopedDeclarations를 반환한다.
ForInOfStatement : for ( LeftHandSideExpression in Expression ) Statement for ( ForDeclaration in Expression ) Statement for ( LeftHandSideExpression of AssignmentExpression ) Statement for ( ForDeclaration of AssignmentExpression ) Statement for await ( LeftHandSideExpression of AssignmentExpression ) Statement for await ( ForDeclaration of AssignmentExpression ) Statement
  1. Statement의 VarScopedDeclarations를 반환한다.
ForInOfStatement : for ( var ForBinding in Expression ) Statement for ( var ForBinding of AssignmentExpression ) Statement for await ( var ForBinding of AssignmentExpression ) Statement
  1. declarations1을 « ForBinding »으로 둔다.
  2. declarations2Statement의 VarScopedDeclarations로 둔다.
  3. declarations1declarations2list-concatenation을 반환한다.
Note

이 절은 부록(Annex) B.3.5에 의해 확장된다.

WithStatement : with ( Expression ) Statement
  1. Statement의 VarScopedDeclarations를 반환한다.
SwitchStatement : switch ( Expression ) CaseBlock
  1. CaseBlock의 VarScopedDeclarations를 반환한다.
CaseBlock : { }
  1. 새 빈 List를 반환한다.
CaseBlock : { CaseClausesopt DefaultClause CaseClausesopt }
  1. 첫 번째 CaseClauses가 존재하면 declarations1을 그 VarScopedDeclarations로 둔다.
  2. 아니면 declarations1을 새 빈 List로 둔다.
  3. declarations2DefaultClause의 VarScopedDeclarations로 둔다.
  4. 두 번째 CaseClauses가 존재하면 declarations3을 그 VarScopedDeclarations로 둔다.
  5. 아니면 declarations3을 새 빈 List로 둔다.
  6. declarations1, declarations2, declarations3list-concatenation을 반환한다.
CaseClauses : CaseClauses CaseClause
  1. declarations1CaseClauses의 VarScopedDeclarations로 둔다.
  2. declarations2CaseClause의 VarScopedDeclarations로 둔다.
  3. declarations1declarations2list-concatenation을 반환한다.
CaseClause : case Expression : StatementListopt
  1. StatementList가 존재하면 StatementList의 VarScopedDeclarations를 반환한다.
  2. 새 빈 List를 반환한다.
DefaultClause : default : StatementListopt
  1. StatementList가 존재하면 StatementList의 VarScopedDeclarations를 반환한다.
  2. 새 빈 List를 반환한다.
LabelledStatement : LabelIdentifier : LabelledItem
  1. LabelledItem의 VarScopedDeclarations를 반환한다.
LabelledItem : Statement
  1. 새 빈 List를 반환한다.
TryStatement : try Block Catch
  1. declarations1Block의 VarScopedDeclarations로 둔다.
  2. declarations2Catch의 VarScopedDeclarations로 둔다.
  3. declarations1declarations2list-concatenation을 반환한다.
TryStatement : try Block Finally
  1. declarations1Block의 VarScopedDeclarations로 둔다.
  2. declarations2Finally의 VarScopedDeclarations로 둔다.
  3. declarations1declarations2list-concatenation을 반환한다.
TryStatement : try Block Catch Finally
  1. declarations1Block의 VarScopedDeclarations로 둔다.
  2. declarations2Catch의 VarScopedDeclarations로 둔다.
  3. declarations3Finally의 VarScopedDeclarations로 둔다.
  4. declarations1, declarations2, declarations3list-concatenation을 반환한다.
Catch : catch ( CatchParameter ) Block
  1. Block의 VarScopedDeclarations를 반환한다.
FunctionStatementList : [empty]
  1. 새 빈 List를 반환한다.
FunctionStatementList : StatementList
  1. StatementList의 TopLevelVarScopedDeclarations를 반환한다.
ClassStaticBlockStatementList : [empty]
  1. 새 빈 List를 반환한다.
ClassStaticBlockStatementList : StatementList
  1. StatementList의 TopLevelVarScopedDeclarations를 반환한다.
ConciseBody : ExpressionBody
  1. 새 빈 List를 반환한다.
AsyncConciseBody : ExpressionBody
  1. 새 빈 List를 반환한다.
Script : [empty]
  1. 새 빈 List를 반환한다.
ScriptBody : StatementList
  1. StatementList의 TopLevelVarScopedDeclarations를 반환한다.
Module : [empty]
  1. 새 빈 List를 반환한다.
ModuleItemList : ModuleItemList ModuleItem
  1. declarations1ModuleItemList의 VarScopedDeclarations로 둔다.
  2. declarations2ModuleItem의 VarScopedDeclarations로 둔다.
  3. declarations1declarations2list-concatenation을 반환한다.
ModuleItem : ImportDeclaration
  1. 새 빈 List를 반환한다.
ModuleItem : ExportDeclaration
  1. ExportDeclarationexport VariableStatement이면 VariableStatement의 VarScopedDeclarations를 반환한다.
  2. 새 빈 List를 반환한다.

8.2.8 정적 의미론: TopLevelLexicallyDeclaredNames : 문자열들의 List

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. It is defined piecewise over the following productions:

StatementList : StatementList StatementListItem
  1. names1StatementList의 TopLevelLexicallyDeclaredNames로 둔다.
  2. names2StatementListItem의 TopLevelLexicallyDeclaredNames로 둔다.
  3. names1names2list-concatenation을 반환한다.
StatementListItem : Statement
  1. 새 빈 List를 반환한다.
StatementListItem : Declaration
  1. Declaration Declaration : HoistableDeclaration 이면
    1. 새 빈 List를 반환한다.
  2. Declaration의 BoundNames를 반환한다.
Note

함수나 스크립트의 최상위에서는 함수 선언이 lexical 선언이 아닌 var 선언처럼 취급된다.

8.2.9 정적 의미론: TopLevelLexicallyScopedDeclarations : Parse Node들의 List

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. It is defined piecewise over the following productions:

StatementList : StatementList StatementListItem
  1. declarations1StatementList의 TopLevelLexicallyScopedDeclarations로 둔다.
  2. declarations2StatementListItem의 TopLevelLexicallyScopedDeclarations로 둔다.
  3. declarations1declarations2list-concatenation을 반환한다.
StatementListItem : Statement
  1. 새 빈 List를 반환한다.
StatementListItem : Declaration
  1. Declaration Declaration : HoistableDeclaration 이면
    1. 새 빈 List를 반환한다.
  2. « Declaration » 를 반환한다.

8.2.10 정적 의미론: TopLevelVarDeclaredNames : 문자열들의 List

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. It is defined piecewise over the following productions:

StatementList : StatementList StatementListItem
  1. names1StatementList의 TopLevelVarDeclaredNames로 둔다.
  2. names2StatementListItem의 TopLevelVarDeclaredNames로 둔다.
  3. names1names2list-concatenation을 반환한다.
StatementListItem : Declaration
  1. Declaration Declaration : HoistableDeclaration 이면
    1. HoistableDeclaration의 BoundNames를 반환한다.
  2. 새 빈 List를 반환한다.
StatementListItem : Statement
  1. Statement Statement : LabelledStatement 이면 Statement의 TopLevelVarDeclaredNames를 반환한다.
  2. Statement의 VarDeclaredNames를 반환한다.
Note

함수나 스크립트의 최상위에서 내부 함수 선언은 var 선언처럼 다루어진다.

LabelledStatement : LabelIdentifier : LabelledItem
  1. LabelledItem의 TopLevelVarDeclaredNames를 반환한다.
LabelledItem : Statement
  1. Statement Statement : LabelledStatement 이면 Statement의 TopLevelVarDeclaredNames를 반환한다.
  2. Statement의 VarDeclaredNames를 반환한다.
LabelledItem : FunctionDeclaration
  1. FunctionDeclaration의 BoundNames를 반환한다.

8.2.11 정적 의미론: TopLevelVarScopedDeclarations : Parse Node들의 List

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. It is defined piecewise over the following productions:

StatementList : StatementList StatementListItem
  1. declarations1StatementList의 TopLevelVarScopedDeclarations로 둔다.
  2. declarations2StatementListItem의 TopLevelVarScopedDeclarations로 둔다.
  3. declarations1declarations2list-concatenation을 반환한다.
StatementListItem : Statement
  1. Statement Statement : LabelledStatement 이면 Statement의 TopLevelVarScopedDeclarations를 반환한다.
  2. Statement의 VarScopedDeclarations를 반환한다.
StatementListItem : Declaration
  1. Declaration Declaration : HoistableDeclaration 이면
    1. declarationHoistableDeclaration의 DeclarationPart로 둔다.
    2. « declaration » 를 반환한다.
  2. 새 빈 List를 반환한다.
LabelledStatement : LabelIdentifier : LabelledItem
  1. LabelledItem의 TopLevelVarScopedDeclarations를 반환한다.
LabelledItem : Statement
  1. Statement Statement : LabelledStatement 이면 Statement의 TopLevelVarScopedDeclarations를 반환한다.
  2. Statement의 VarScopedDeclarations를 반환한다.
LabelledItem : FunctionDeclaration
  1. « FunctionDeclaration » 를 반환한다.

8.3 레이블(Labels)

8.3.1 정적 의미론: ContainsDuplicateLabels : Boolean

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. 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. hasDuplicatesStatementList의 ContainsDuplicateLabels(labelSet)로 둔다.
  2. hasDuplicatestrue이면 true를 반환한다.
  3. StatementListItem의 ContainsDuplicateLabels(labelSet)를 반환한다.
IfStatement : if ( Expression ) Statement else Statement
  1. hasDuplicate를 첫 번째 Statement의 ContainsDuplicateLabels(labelSet)로 둔다.
  2. hasDuplicatetrue이면 true를 반환한다.
  3. 두 번째 Statement의 ContainsDuplicateLabels(labelSet)를 반환한다.
IfStatement : if ( Expression ) Statement
  1. Statement의 ContainsDuplicateLabels(labelSet)를 반환한다.
DoWhileStatement : do Statement while ( Expression ) ;
  1. Statement의 ContainsDuplicateLabels(labelSet)를 반환한다.
WhileStatement : while ( Expression ) Statement
  1. Statement의 ContainsDuplicateLabels(labelSet)를 반환한다.
ForStatement : for ( Expressionopt ; Expressionopt ; Expressionopt ) Statement for ( var VariableDeclarationList ; Expressionopt ; Expressionopt ) Statement for ( LexicalDeclaration Expressionopt ; Expressionopt ) Statement
  1. Statement의 ContainsDuplicateLabels(labelSet)를 반환한다.
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. Statement의 ContainsDuplicateLabels(labelSet)를 반환한다.
Note

이 절은 부록(Annex) B.3.5에 의해 확장된다.

WithStatement : with ( Expression ) Statement
  1. Statement의 ContainsDuplicateLabels(labelSet)를 반환한다.
SwitchStatement : switch ( Expression ) CaseBlock
  1. CaseBlock의 ContainsDuplicateLabels(labelSet)를 반환한다.
CaseBlock : { }
  1. false를 반환한다.
CaseBlock : { CaseClausesopt DefaultClause CaseClausesopt }
  1. 첫 번째 CaseClauses가 존재하면
    1. 첫 번째 CaseClauses의 ContainsDuplicateLabels(labelSet)가 true이면 true를 반환한다.
  2. DefaultClause의 ContainsDuplicateLabels(labelSet)가 true이면 true를 반환한다.
  3. 두 번째 CaseClauses가 존재하지 않으면 false를 반환한다.
  4. 두 번째 CaseClauses의 ContainsDuplicateLabels(labelSet)를 반환한다.
CaseClauses : CaseClauses CaseClause
  1. hasDuplicatesCaseClauses의 ContainsDuplicateLabels(labelSet)로 둔다.
  2. hasDuplicatestrue이면 true를 반환한다.
  3. CaseClause의 ContainsDuplicateLabels(labelSet)를 반환한다.
CaseClause : case Expression : StatementListopt
  1. StatementList가 존재하면 StatementList의 ContainsDuplicateLabels(labelSet)를 반환한다.
  2. false를 반환한다.
DefaultClause : default : StatementListopt
  1. StatementList가 존재하면 StatementList의 ContainsDuplicateLabels(labelSet)를 반환한다.
  2. false를 반환한다.
LabelledStatement : LabelIdentifier : LabelledItem
  1. labelLabelIdentifier의 StringValue로 둔다.
  2. labelSetlabel을 포함하면 true를 반환한다.
  3. newLabelSetlabelSet과 « label »의 list-concatenation으로 둔다.
  4. LabelledItem의 ContainsDuplicateLabels(newLabelSet)를 반환한다.
LabelledItem : FunctionDeclaration
  1. false를 반환한다.
TryStatement : try Block Catch
  1. hasDuplicatesBlock의 ContainsDuplicateLabels(labelSet)로 둔다.
  2. hasDuplicatestrue이면 true를 반환한다.
  3. Catch의 ContainsDuplicateLabels(labelSet)를 반환한다.
TryStatement : try Block Finally
  1. hasDuplicatesBlock의 ContainsDuplicateLabels(labelSet)로 둔다.
  2. hasDuplicatestrue이면 true를 반환한다.
  3. Finally의 ContainsDuplicateLabels(labelSet)를 반환한다.
TryStatement : try Block Catch Finally
  1. Block의 ContainsDuplicateLabels(labelSet)가 true이면 true를 반환한다.
  2. Catch의 ContainsDuplicateLabels(labelSet)가 true이면 true를 반환한다.
  3. Finally의 ContainsDuplicateLabels(labelSet)를 반환한다.
Catch : catch ( CatchParameter ) Block
  1. Block의 ContainsDuplicateLabels(labelSet)를 반환한다.
FunctionStatementList : [empty]
  1. false를 반환한다.
ClassStaticBlockStatementList : [empty]
  1. false를 반환한다.
ModuleItemList : ModuleItemList ModuleItem
  1. hasDuplicatesModuleItemList의 ContainsDuplicateLabels(labelSet)로 둔다.
  2. hasDuplicatestrue이면 true를 반환한다.
  3. ModuleItem의 ContainsDuplicateLabels(labelSet)를 반환한다.
ModuleItem : ImportDeclaration ExportDeclaration
  1. false를 반환한다.

8.3.2 정적 의미론: ContainsUndefinedBreakTarget : Boolean

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. 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. hasUndefinedLabelsStatementList의 ContainsUndefinedBreakTarget(labelSet)로 둔다.
  2. hasUndefinedLabelstrue이면 true를 반환한다.
  3. StatementListItem의 ContainsUndefinedBreakTarget(labelSet)를 반환한다.
IfStatement : if ( Expression ) Statement else Statement
  1. hasUndefinedLabels를 첫 번째 Statement의 ContainsUndefinedBreakTarget(labelSet)로 둔다.
  2. hasUndefinedLabelstrue이면 true를 반환한다.
  3. 두 번째 Statement의 ContainsUndefinedBreakTarget(labelSet)를 반환한다.
IfStatement : if ( Expression ) Statement
  1. Statement의 ContainsUndefinedBreakTarget(labelSet)를 반환한다.
DoWhileStatement : do Statement while ( Expression ) ;
  1. Statement의 ContainsUndefinedBreakTarget(labelSet)를 반환한다.
WhileStatement : while ( Expression ) Statement
  1. Statement의 ContainsUndefinedBreakTarget(labelSet)를 반환한다.
ForStatement : for ( Expressionopt ; Expressionopt ; Expressionopt ) Statement for ( var VariableDeclarationList ; Expressionopt ; Expressionopt ) Statement for ( LexicalDeclaration Expressionopt ; Expressionopt ) Statement
  1. Statement의 ContainsUndefinedBreakTarget(labelSet)를 반환한다.
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. Statement의 ContainsUndefinedBreakTarget(labelSet)를 반환한다.
Note

이 절은 부록(Annex) B.3.5에 의해 확장된다.

BreakStatement : break ;
  1. false를 반환한다.
BreakStatement : break LabelIdentifier ;
  1. labelSetLabelIdentifier의 StringValue를 포함하지 않으면 true를 반환한다.
  2. false를 반환한다.
WithStatement : with ( Expression ) Statement
  1. Statement의 ContainsUndefinedBreakTarget(labelSet)를 반환한다.
SwitchStatement : switch ( Expression ) CaseBlock
  1. CaseBlock의 ContainsUndefinedBreakTarget(labelSet)를 반환한다.
CaseBlock : { }
  1. false를 반환한다.
CaseBlock : { CaseClausesopt DefaultClause CaseClausesopt }
  1. 첫 번째 CaseClauses가 존재하면
    1. 첫 번째 CaseClauses의 ContainsUndefinedBreakTarget(labelSet)가 true이면 true를 반환한다.
  2. DefaultClause의 ContainsUndefinedBreakTarget(labelSet)가 true이면 true를 반환한다.
  3. 두 번째 CaseClauses가 존재하지 않으면 false를 반환한다.
  4. 두 번째 CaseClauses의 ContainsUndefinedBreakTarget(labelSet)를 반환한다.
CaseClauses : CaseClauses CaseClause
  1. hasUndefinedLabelsCaseClauses의 ContainsUndefinedBreakTarget(labelSet)로 둔다.
  2. hasUndefinedLabelstrue이면 true를 반환한다.
  3. CaseClause의 ContainsUndefinedBreakTarget(labelSet)를 반환한다.
CaseClause : case Expression : StatementListopt
  1. StatementList가 존재하면 StatementList의 ContainsUndefinedBreakTarget(labelSet)를 반환한다.
  2. false를 반환한다.
DefaultClause : default : StatementListopt
  1. StatementList가 존재하면 StatementList의 ContainsUndefinedBreakTarget(labelSet)를 반환한다.
  2. false를 반환한다.
LabelledStatement : LabelIdentifier : LabelledItem
  1. labelLabelIdentifier의 StringValue로 둔다.
  2. newLabelSetlabelSet과 « label »의 list-concatenation으로 둔다.
  3. LabelledItem의 ContainsUndefinedBreakTarget(newLabelSet)를 반환한다.
LabelledItem : FunctionDeclaration
  1. false를 반환한다.
TryStatement : try Block Catch
  1. hasUndefinedLabelsBlock의 ContainsUndefinedBreakTarget(labelSet)로 둔다.
  2. hasUndefinedLabelstrue이면 true를 반환한다.
  3. Catch의 ContainsUndefinedBreakTarget(labelSet)를 반환한다.
TryStatement : try Block Finally
  1. hasUndefinedLabelsBlock의 ContainsUndefinedBreakTarget(labelSet)로 둔다.
  2. hasUndefinedLabelstrue이면 true를 반환한다.
  3. Finally의 ContainsUndefinedBreakTarget(labelSet)를 반환한다.
TryStatement : try Block Catch Finally
  1. Block의 ContainsUndefinedBreakTarget(labelSet)가 true이면 true를 반환한다.
  2. Catch의 ContainsUndefinedBreakTarget(labelSet)가 true이면 true를 반환한다.
  3. Finally의 ContainsUndefinedBreakTarget(labelSet)를 반환한다.
Catch : catch ( CatchParameter ) Block
  1. Block의 ContainsUndefinedBreakTarget(labelSet)를 반환한다.
FunctionStatementList : [empty]
  1. false를 반환한다.
ClassStaticBlockStatementList : [empty]
  1. false를 반환한다.
ModuleItemList : ModuleItemList ModuleItem
  1. hasUndefinedLabelsModuleItemList의 ContainsUndefinedBreakTarget(labelSet)로 둔다.
  2. hasUndefinedLabelstrue이면 true를 반환한다.
  3. ModuleItem의 ContainsUndefinedBreakTarget(labelSet)를 반환한다.
ModuleItem : ImportDeclaration ExportDeclaration
  1. false를 반환한다.

8.3.3 정적 의미론: ContainsUndefinedContinueTarget : Boolean

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. It is defined piecewise over the following productions:

Statement : VariableStatement EmptyStatement ExpressionStatement BreakStatement ReturnStatement ThrowStatement DebuggerStatement Block : { } StatementListItem : Declaration
  1. false를 반환한다.
Statement : BlockStatement
  1. BlockStatement의 ContainsUndefinedContinueTarget(iterationSet, « »)을 반환한다.
BreakableStatement : IterationStatement
  1. newIterationSetiterationSetlabelSetlist-concatenation으로 둔다.
  2. IterationStatement의 ContainsUndefinedContinueTarget(newIterationSet, « »)을 반환한다.
StatementList : StatementList StatementListItem
  1. hasUndefinedLabelsStatementList의 ContainsUndefinedContinueTarget(iterationSet, « »)로 둔다.
  2. hasUndefinedLabelstrue이면 true를 반환한다.
  3. StatementListItem의 ContainsUndefinedContinueTarget(iterationSet, « »)을 반환한다.
IfStatement : if ( Expression ) Statement else Statement
  1. hasUndefinedLabels를 첫 번째 Statement의 ContainsUndefinedContinueTarget(iterationSet, « »)로 둔다.
  2. hasUndefinedLabelstrue이면 true를 반환한다.
  3. 두 번째 Statement의 ContainsUndefinedContinueTarget(iterationSet, « »)을 반환한다.
IfStatement : if ( Expression ) Statement
  1. Statement의 ContainsUndefinedContinueTarget(iterationSet, « »)을 반환한다.
DoWhileStatement : do Statement while ( Expression ) ;
  1. Statement의 ContainsUndefinedContinueTarget(iterationSet, « »)을 반환한다.
WhileStatement : while ( Expression ) Statement
  1. Statement의 ContainsUndefinedContinueTarget(iterationSet, « »)을 반환한다.
ForStatement : for ( Expressionopt ; Expressionopt ; Expressionopt ) Statement for ( var VariableDeclarationList ; Expressionopt ; Expressionopt ) Statement for ( LexicalDeclaration Expressionopt ; Expressionopt ) Statement
  1. Statement의 ContainsUndefinedContinueTarget(iterationSet, « »)을 반환한다.
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. Statement의 ContainsUndefinedContinueTarget(iterationSet, « »)을 반환한다.
Note

이 절은 부록(Annex) B.3.5에 의해 확장된다.

ContinueStatement : continue ;
  1. false를 반환한다.
ContinueStatement : continue LabelIdentifier ;
  1. iterationSetLabelIdentifier의 StringValue를 포함하지 않으면 true를 반환한다.
  2. false를 반환한다.
WithStatement : with ( Expression ) Statement
  1. Statement의 ContainsUndefinedContinueTarget(iterationSet, « »)을 반환한다.
SwitchStatement : switch ( Expression ) CaseBlock
  1. CaseBlock의 ContainsUndefinedContinueTarget(iterationSet, « »)을 반환한다.
CaseBlock : { }
  1. false를 반환한다.
CaseBlock : { CaseClausesopt DefaultClause CaseClausesopt }
  1. 첫 번째 CaseClauses가 존재하면
    1. 첫 번째 CaseClauses의 ContainsUndefinedContinueTarget(iterationSet, « »)이 true이면 true를 반환한다.
  2. DefaultClause의 ContainsUndefinedContinueTarget(iterationSet, « »)이 true이면 true를 반환한다.
  3. 두 번째 CaseClauses가 존재하지 않으면 false를 반환한다.
  4. 두 번째 CaseClauses의 ContainsUndefinedContinueTarget(iterationSet, « »)을 반환한다.
CaseClauses : CaseClauses CaseClause
  1. hasUndefinedLabelsCaseClauses의 ContainsUndefinedContinueTarget(iterationSet, « »)로 둔다.
  2. hasUndefinedLabelstrue이면 true를 반환한다.
  3. CaseClause의 ContainsUndefinedContinueTarget(iterationSet, « »)을 반환한다.
CaseClause : case Expression : StatementListopt
  1. StatementList가 존재하면 StatementList의 ContainsUndefinedContinueTarget(iterationSet, « »)을 반환한다.
  2. false를 반환한다.
DefaultClause : default : StatementListopt
  1. StatementList가 존재하면 StatementList의 ContainsUndefinedContinueTarget(iterationSet, « »)을 반환한다.
  2. false를 반환한다.
LabelledStatement : LabelIdentifier : LabelledItem
  1. labelLabelIdentifier의 StringValue로 둔다.
  2. newLabelSetlabelSet과 « label »의 list-concatenation으로 둔다.
  3. LabelledItem의 ContainsUndefinedContinueTarget(iterationSet, newLabelSet)을 반환한다.
LabelledItem : FunctionDeclaration
  1. false를 반환한다.
TryStatement : try Block Catch
  1. hasUndefinedLabelsBlock의 ContainsUndefinedContinueTarget(iterationSet, « »)로 둔다.
  2. hasUndefinedLabelstrue이면 true를 반환한다.
  3. Catch의 ContainsUndefinedContinueTarget(iterationSet, « »)을 반환한다.
TryStatement : try Block Finally
  1. hasUndefinedLabelsBlock의 ContainsUndefinedContinueTarget(iterationSet, « »)로 둔다.
  2. hasUndefinedLabelstrue이면 true를 반환한다.
  3. Finally의 ContainsUndefinedContinueTarget(iterationSet, « »)을 반환한다.
TryStatement : try Block Catch Finally
  1. Block의 ContainsUndefinedContinueTarget(iterationSet, « »)이 true이면 true를 반환한다.
  2. Catch의 ContainsUndefinedContinueTarget(iterationSet, « »)이 true이면 true를 반환한다.
  3. Finally의 ContainsUndefinedContinueTarget(iterationSet, « »)을 반환한다.
Catch : catch ( CatchParameter ) Block
  1. Block의 ContainsUndefinedContinueTarget(iterationSet, « »)을 반환한다.
FunctionStatementList : [empty]
  1. false를 반환한다.
ClassStaticBlockStatementList : [empty]
  1. false를 반환한다.
ModuleItemList : ModuleItemList ModuleItem
  1. hasUndefinedLabelsModuleItemList의 ContainsUndefinedContinueTarget(iterationSet, « »)로 둔다.
  2. hasUndefinedLabelstrue이면 true를 반환한다.
  3. ModuleItem의 ContainsUndefinedContinueTarget(iterationSet, « »)을 반환한다.
ModuleItem : ImportDeclaration ExportDeclaration
  1. false를 반환한다.

8.4 함수 이름 추론(Function Name Inference)

8.4.1 정적 의미론: HasName : Boolean

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. It is defined piecewise over the following productions:

PrimaryExpression : CoverParenthesizedExpressionAndArrowParameterList
  1. exprCoverParenthesizedExpressionAndArrowParameterList가 커버하는 ParenthesizedExpression으로 둔다.
  2. IsFunctionDefinition of exprfalse이면 false를 반환한다.
  3. HasName of expr을 반환한다.
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 정적 의미론: IsFunctionDefinition : Boolean

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. It is defined piecewise over the following productions:

PrimaryExpression : CoverParenthesizedExpressionAndArrowParameterList
  1. exprCoverParenthesizedExpressionAndArrowParameterList가 커버하는 ParenthesizedExpression으로 둔다.
  2. IsFunctionDefinition of expr을 반환한다.
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 AwaitExpression 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 정적 의미론: IsAnonymousFunctionDefinition ( expr: AssignmentExpression Parse Node, Initializer Parse Node, 또는 Expression Parse Node, ): Boolean

The abstract operation UNKNOWN takes UNPARSEABLE ARGUMENTS. 인수가 이름을 바인딩하지 않는 함수 정의인지 판정한다. It performs the following steps when called:

  1. IsFunctionDefinition of exprfalse이면 false를 반환한다.
  2. hasName을 HasName of expr으로 둔다.
  3. hasNametrue이면 false를 반환한다.
  4. true를 반환한다.

8.4.4 정적 의미론: IsIdentifierRef : Boolean

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. 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 런타임 의미론: NamedEvaluation : 함수 객체를 담는 normal completion 또는 abrupt completion

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. It is defined piecewise over the following productions:

PrimaryExpression : CoverParenthesizedExpressionAndArrowParameterList
  1. exprCoverParenthesizedExpressionAndArrowParameterList가 커버하는 ParenthesizedExpression으로 둔다.
  2. name 인수를 사용하여 expr의 NamedEvaluation을 ?로 반환한다.
ParenthesizedExpression : ( Expression )
  1. 단언: IsAnonymousFunctionDefinition(Expression)은 true이다.
  2. name 인수를 사용하여 Expression의 NamedEvaluation을 ?로 반환한다.
FunctionExpression : function ( FormalParameters ) { FunctionBody }
  1. name 인수를 사용하여 FunctionExpression의 InstantiateOrdinaryFunctionExpression을 반환한다.
GeneratorExpression : function * ( FormalParameters ) { GeneratorBody }
  1. name 인수를 사용하여 GeneratorExpression의 InstantiateGeneratorFunctionExpression을 반환한다.
AsyncGeneratorExpression : async function * ( FormalParameters ) { AsyncGeneratorBody }
  1. name 인수를 사용하여 AsyncGeneratorExpression의 InstantiateAsyncGeneratorFunctionExpression을 반환한다.
AsyncFunctionExpression : async function ( FormalParameters ) { AsyncFunctionBody }
  1. name 인수를 사용하여 AsyncFunctionExpression의 InstantiateAsyncFunctionExpression을 반환한다.
ArrowFunction : ArrowParameters => ConciseBody
  1. name 인수를 사용하여 ArrowFunction의 InstantiateArrowFunctionExpression을 반환한다.
AsyncArrowFunction : async AsyncArrowBindingIdentifier => AsyncConciseBody CoverCallExpressionAndAsyncArrowHead => AsyncConciseBody
  1. name 인수를 사용하여 AsyncArrowFunction의 InstantiateAsyncArrowFunctionExpression을 반환한다.
ClassExpression : class ClassTail
  1. sourceTextClassExpression이 매치한 소스 텍스트로 둔다.
  2. undefined, name, sourceText 인수로 ClassTail의 ClassDefinitionEvaluation을 ?로 반환한다.

8.5 Contains

8.5.1 정적 의미론: Contains : Boolean

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS.

아래에 나열되지 않은 명세의 모든 문법 생성 규칙 대안은 암묵적으로 다음 기본 Contains 정의를 갖는다:

  1. 이 Parse Node의 각 자식 노드 child에 대해
    1. childsymbol의 인스턴스이면 true를 반환한다.
    2. child가 비종결(nonterminal) 인스턴스이면
      1. containedchild Contains symbol의 결과로 둔다.
      2. containedtrue이면 true를 반환한다.
  2. false를 반환한다.
FunctionDeclaration : function BindingIdentifier ( FormalParameters ) { FunctionBody } function ( FormalParameters ) { FunctionBody } FunctionExpression : function BindingIdentifieropt ( FormalParameters ) { FunctionBody } GeneratorDeclaration : function * BindingIdentifier ( FormalParameters ) { GeneratorBody } function * ( FormalParameters ) { GeneratorBody } GeneratorExpression : function * BindingIdentifieropt ( FormalParameters ) { GeneratorBody } AsyncGeneratorDeclaration : async function * BindingIdentifier ( FormalParameters ) { AsyncGeneratorBody } async function * ( FormalParameters ) { AsyncGeneratorBody } AsyncGeneratorExpression : async function * BindingIdentifieropt ( FormalParameters ) { AsyncGeneratorBody } AsyncFunctionDeclaration : async function BindingIdentifier ( FormalParameters ) { AsyncFunctionBody } async function ( FormalParameters ) { AsyncFunctionBody } AsyncFunctionExpression : async function BindingIdentifieropt ( FormalParameters ) { AsyncFunctionBody }
  1. false를 반환한다.
Note 1

부분 구조에 의존하는 정적 의미 규칙은 일반적으로 함수 정의 내부를 들여다보지 않는다.

ClassTail : ClassHeritageopt { ClassBody }
  1. symbolClassBody이면 true를 반환한다.
  2. symbolClassHeritage이면
    1. ClassHeritage가 존재하면 true, 아니면 false를 반환한다.
  3. ClassHeritage가 존재하면
    1. ClassHeritage Contains symboltrue이면 true를 반환한다.
  4. ClassBody에 대해 symbol 인수를 사용한 ComputedPropertyContains 결과를 반환한다.
Note 2

부분 구조에 의존하는 정적 의미 규칙은 일반적으로 PropertyName을 제외하고 클래스 본문 내부를 들여다보지 않는다.

ClassStaticBlock : static { ClassStaticBlockBody }
  1. false를 반환한다.
Note 3

부분 구조에 의존하는 정적 의미 규칙은 일반적으로 static 초기화 블록 내부를 들여다보지 않는다.

ArrowFunction : ArrowParameters => ConciseBody
  1. symbolNewTarget, SuperProperty, SuperCall, super, this 중 하나가 아니면 false를 반환한다.
  2. ArrowParameters Contains symboltrue이면 true를 반환한다.
  3. ConciseBody Contains symbol을 반환한다.
ArrowParameters : CoverParenthesizedExpressionAndArrowParameterList
  1. formalsCoverParenthesizedExpressionAndArrowParameterList가 커버하는 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가 커버하는 AsyncArrowHead로 둔다.
  3. head Contains symboltrue이면 true를 반환한다.
  4. AsyncConciseBody Contains symbol을 반환한다.
Note 4

Contains는 ArrowFunction 또는 AsyncArrowFunction 내에서 new.target, this, super 사용을 탐지하는 데 사용된다.

PropertyDefinition : MethodDefinition
  1. symbolMethodDefinition이면 true를 반환한다.
  2. MethodDefinition에 대해 symbol 인수를 사용한 ComputedPropertyContains 결과를 반환한다.
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 정적 의미론: ComputedPropertyContains : Boolean

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. It is defined piecewise over the following productions:

ClassElementName : PrivateIdentifier PropertyName : LiteralPropertyName
  1. false를 반환한다.
PropertyName : ComputedPropertyName
  1. ComputedPropertyName Contains symbol의 결과를 반환한다.
MethodDefinition : ClassElementName ( UniqueFormalParameters ) { FunctionBody } get ClassElementName ( ) { FunctionBody } set ClassElementName ( PropertySetParameterList ) { FunctionBody }
  1. ClassElementName에 대해 symbol 인수를 사용한 ComputedPropertyContains 결과를 반환한다.
GeneratorMethod : * ClassElementName ( UniqueFormalParameters ) { GeneratorBody }
  1. ClassElementName에 대해 symbol 인수를 사용한 ComputedPropertyContains 결과를 반환한다.
AsyncGeneratorMethod : async * ClassElementName ( UniqueFormalParameters ) { AsyncGeneratorBody }
  1. ClassElementName에 대해 symbol 인수를 사용한 ComputedPropertyContains 결과를 반환한다.
ClassElementList : ClassElementList ClassElement
  1. inListClassElementList에 대해 symbol 인수를 사용한 ComputedPropertyContains 결과로 둔다.
  2. inListtrue이면 true를 반환한다.
  3. ClassElement에 대해 symbol 인수를 사용한 ComputedPropertyContains 결과를 반환한다.
ClassElement : ClassStaticBlock
  1. false를 반환한다.
ClassElement : ;
  1. false를 반환한다.
AsyncMethod : async ClassElementName ( UniqueFormalParameters ) { AsyncFunctionBody }
  1. ClassElementName에 대해 symbol 인수를 사용한 ComputedPropertyContains 결과를 반환한다.
FieldDefinition : ClassElementName Initializeropt
  1. ClassElementName에 대해 symbol 인수를 사용한 ComputedPropertyContains 결과를 반환한다.

8.6 기타(Miscellaneous)

이 연산들은 명세 전반 여러 위치에서 사용된다.

8.6.1 런타임 의미론: InstantiateFunctionObject : ECMAScript 함수 객체

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. It is defined piecewise over the following productions:

FunctionDeclaration : function BindingIdentifier ( FormalParameters ) { FunctionBody } function ( FormalParameters ) { FunctionBody }
  1. env, privateEnv 인수로 FunctionDeclaration의 InstantiateOrdinaryFunctionObject를 반환한다.
GeneratorDeclaration : function * BindingIdentifier ( FormalParameters ) { GeneratorBody } function * ( FormalParameters ) { GeneratorBody }
  1. env, privateEnv 인수로 GeneratorDeclaration의 InstantiateGeneratorFunctionObject를 반환한다.
AsyncGeneratorDeclaration : async function * BindingIdentifier ( FormalParameters ) { AsyncGeneratorBody } async function * ( FormalParameters ) { AsyncGeneratorBody }
  1. env, privateEnv 인수로 AsyncGeneratorDeclaration의 InstantiateAsyncGeneratorFunctionObject를 반환한다.
AsyncFunctionDeclaration : async function BindingIdentifier ( FormalParameters ) { AsyncFunctionBody } async function ( FormalParameters ) { AsyncFunctionBody }
  1. env, privateEnv 인수로 AsyncFunctionDeclaration의 InstantiateAsyncFunctionObject를 반환한다.

8.6.2 런타임 의미론: BindingInitialization : unused를 담는 normal completion 또는 abrupt completion

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS.

Note

environmentundefined가 전달되면 초기화 값을 할당하는 데 PutValue 연산을 사용해야 함을 나타낸다. 이는 var 문 및 일부 non-strict 함수의 매개변수 목록( 10.2.11 참조)에 해당한다. 이 경우 렉시컬 바인딩은 초기화자 평가 전에 호이스팅되어 사전 초기화된다.

It is defined piecewise over the following productions:

BindingIdentifier : Identifier
  1. nameIdentifier의 StringValue로 둔다.
  2. InitializeBoundName(name, value, environment)를 반환한다.
BindingIdentifier : yield
  1. InitializeBoundName("yield", value, environment)를 반환한다.
BindingIdentifier : await
  1. InitializeBoundName("await", value, environment)를 반환한다.
BindingPattern : ObjectBindingPattern
  1. RequireObjectCoercible(value)를 수행한다.
  2. value, environment 인수로 ObjectBindingPattern의 BindingInitialization을 ?로 반환한다.
BindingPattern : ArrayBindingPattern
  1. iteratorRecord를 ? GetIterator(value, sync)로 둔다.
  2. result를 (ArrayBindingPattern의 IteratorBindingInitialization(iteratorRecord, environment))의 Completion으로 둔다.
  3. iteratorRecord.[[Done]]false이면 ? IteratorClose(iteratorRecord, result)를 반환한다.
  4. result를 반환한다.
ObjectBindingPattern : { }
  1. unused를 반환한다.
ObjectBindingPattern : { BindingPropertyList } { BindingPropertyList , }
  1. value, environment 인수로 BindingPropertyList의 PropertyBindingInitialization을 ? 수행한다.
  2. unused를 반환한다.
ObjectBindingPattern : { BindingRestProperty }
  1. excludedNames를 새 빈 List로 둔다.
  2. value, environment, excludedNames 인수로 BindingRestProperty의 RestBindingInitialization을 ?로 반환한다.
ObjectBindingPattern : { BindingPropertyList , BindingRestProperty }
  1. excludedNamesvalue, environment 인수로 BindingPropertyList의 PropertyBindingInitialization 결과로 둔다.
  2. value, environment, excludedNames 인수로 BindingRestProperty의 RestBindingInitialization을 ?로 반환한다.

8.6.2.1 InitializeBoundName ( name, value, environment )

The abstract operation InitializeBoundName takes arguments name (String), value (ECMAScript 언어 값), and environment (Environment Record 또는 undefined) and returns unused를 담는 normal completion 또는 abrupt completion. It performs the following steps when called:

  1. environmentundefined가 아니면
    1. environment.InitializeBinding(name, value)를 수행한다.
    2. unused를 반환한다.
  2. Else,
    1. lhs를 ? ResolveBinding(name)으로 둔다.
    2. PutValue(lhs, value)를 반환한다.

8.6.3 런타임 의미론: IteratorBindingInitialization : unused를 담는 normal completion 또는 abrupt completion

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS.

Note

environmentundefined가 전달되면 초기화 값 할당에 PutValue 연산을 사용해야 함을 나타낸다. 이는 non-strict 함수의 매개변수 목록에 해당한다. 그 경우 동일 이름 매개변수 가능성 때문에 사전 초기화된다.

It is defined piecewise over the following productions:

ArrayBindingPattern : [ ]
  1. unused를 반환한다.
ArrayBindingPattern : [ Elision ]
  1. Elision의 IteratorDestructuringAssignmentEvaluation(iteratorRecord)을 ?로 반환한다.
ArrayBindingPattern : [ Elisionopt BindingRestElement ]
  1. Elision이 존재하면
    1. Elision의 IteratorDestructuringAssignmentEvaluation(iteratorRecord)을 ? 수행한다.
  2. BindingRestElement의 IteratorBindingInitialization(iteratorRecord, environment)을 ?로 반환한다.
ArrayBindingPattern : [ BindingElementList , Elision ]
  1. BindingElementList의 IteratorBindingInitialization(iteratorRecord, environment)을 ? 수행한다.
  2. Elision의 IteratorDestructuringAssignmentEvaluation(iteratorRecord)을 ?로 반환한다.
ArrayBindingPattern : [ BindingElementList , Elisionopt BindingRestElement ]
  1. BindingElementList의 IteratorBindingInitialization(iteratorRecord, environment)을 ? 수행한다.
  2. Elision이 존재하면
    1. Elision의 IteratorDestructuringAssignmentEvaluation(iteratorRecord)을 ? 수행한다.
  3. BindingRestElement의 IteratorBindingInitialization(iteratorRecord, environment)을 ?로 반환한다.
BindingElementList : BindingElementList , BindingElisionElement
  1. BindingElementList의 IteratorBindingInitialization(iteratorRecord, environment)을 ? 수행한다.
  2. BindingElisionElement의 IteratorBindingInitialization(iteratorRecord, environment)을 ?로 반환한다.
BindingElisionElement : Elision BindingElement
  1. Elision의 IteratorDestructuringAssignmentEvaluation(iteratorRecord)을 ? 수행한다.
  2. BindingElement의 IteratorBindingInitialization(iteratorRecord, environment)을 ?로 반환한다.
SingleNameBinding : BindingIdentifier Initializeropt
  1. bindingIdBindingIdentifier의 StringValue로 둔다.
  2. lhs를 ? ResolveBinding(bindingId, environment)로 둔다.
  3. vundefined로 둔다.
  4. iteratorRecord.[[Done]]false이면
    1. next를 ? IteratorStepValue(iteratorRecord)로 둔다.
    2. nextdone이 아니면 vnext로 둔다.
  5. Initializer가 존재하고 vundefined이면
    1. IsAnonymousFunctionDefinition(Initializer)이 true이면
      1. v를 ? NamedEvaluation(Initializer, bindingId)로 둔다.
    2. Else
      1. defaultValue를 ? Evaluation(Initializer)로 둔다.
      2. v를 ? GetValue(defaultValue)로 둔다.
  6. environmentundefined이면 ? PutValue(lhs, v)를 반환한다.
  7. InitializeReferencedBinding(lhs, v)를 반환한다.
BindingElement : BindingPattern Initializeropt
  1. vundefined로 둔다.
  2. iteratorRecord.[[Done]]false이면
    1. next를 ? IteratorStepValue(iteratorRecord)로 둔다.
    2. nextdone이 아니면 vnext로 둔다.
  3. Initializer가 존재하고 vundefined이면
    1. defaultValue를 ? Evaluation(Initializer)로 둔다.
    2. v를 ? GetValue(defaultValue)로 둔다.
  4. BindingPattern의 BindingInitialization(v, environment)을 ?로 반환한다.
BindingRestElement : ... BindingIdentifier
  1. lhs를 ? ResolveBinding(StringValue of BindingIdentifier, environment)로 둔다.
  2. A를 ! ArrayCreate(0)로 둔다.
  3. n을 0으로 둔다.
  4. 반복,
    1. nextdone으로 둔다.
    2. iteratorRecord.[[Done]]false이면
      1. next를 ? IteratorStepValue(iteratorRecord)로 둔다.
    3. nextdone이면
      1. environmentundefined이면 ? PutValue(lhs, A)를 반환한다.
      2. InitializeReferencedBinding(lhs, A)를 반환한다.
    4. CreateDataPropertyOrThrow(A, ! ToString(𝔽(n)), next)를 수행한다.
    5. nn + 1로 둔다.
BindingRestElement : ... BindingPattern
  1. A를 ! ArrayCreate(0)로 둔다.
  2. n을 0으로 둔다.
  3. 반복,
    1. nextdone으로 둔다.
    2. iteratorRecord.[[Done]]false이면
      1. next를 ? IteratorStepValue(iteratorRecord)로 둔다.
    3. nextdone이면
      1. BindingPattern의 BindingInitialization(A, environment)을 ?로 반환한다.
    4. CreateDataPropertyOrThrow(A, ! ToString(𝔽(n)), next)를 수행한다.
    5. nn + 1로 둔다.
FormalParameters : [empty]
  1. unused를 반환한다.
FormalParameters : FormalParameterList , FunctionRestParameter
  1. FormalParameterList의 IteratorBindingInitialization(iteratorRecord, environment)을 ? 수행한다.
  2. FunctionRestParameter의 IteratorBindingInitialization(iteratorRecord, environment)을 ?로 반환한다.
FormalParameterList : FormalParameterList , FormalParameter
  1. FormalParameterList의 IteratorBindingInitialization(iteratorRecord, environment)을 ? 수행한다.
  2. FormalParameter의 IteratorBindingInitialization(iteratorRecord, environment)을 ?로 반환한다.
ArrowParameters : BindingIdentifier
  1. vundefined로 둔다.
  2. 단언: iteratorRecord.[[Done]]false이다.
  3. next를 ? IteratorStepValue(iteratorRecord)로 둔다.
  4. nextdone이 아니면 vnext로 둔다.
  5. BindingIdentifier의 BindingInitialization(v, environment)을 ?로 반환한다.
ArrowParameters : CoverParenthesizedExpressionAndArrowParameterList
  1. formalsCoverParenthesizedExpressionAndArrowParameterList가 커버하는 ArrowFormalParameters로 둔다.
  2. formals의 IteratorBindingInitialization(iteratorRecord, environment)을 ?로 반환한다.
AsyncArrowBindingIdentifier : BindingIdentifier
  1. vundefined로 둔다.
  2. 단언: iteratorRecord.[[Done]]false이다.
  3. next를 ? IteratorStepValue(iteratorRecord)로 둔다.
  4. nextdone이 아니면 vnext로 둔다.
  5. BindingIdentifier의 BindingInitialization(v, environment)을 ?로 반환한다.

8.6.4 정적 의미론: AssignmentTargetType : simple, web-compat, 또는 invalid

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. It is defined piecewise over the following productions:

IdentifierReference : Identifier
  1. IsStrict(this IdentifierReference)가 true이고 Identifier의 StringValue가 "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가 커버하는 ParenthesizedExpression으로 둔다.
  2. expr의 AssignmentTargetType을 반환한다.
CallExpression : CoverCallExpressionAndAsyncArrowHead CallExpression Arguments
  1. Normative Optional
    호스트가 웹 브라우저이거나 함수 호출 대입 대상으로 인한 런타임 에러를 지원하고 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 AwaitExpression 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 정적 의미론: PropName : String 또는 empty

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. It is defined piecewise over the following productions:

PropertyDefinition : IdentifierReference
  1. IdentifierReference의 StringValue를 반환한다.
PropertyDefinition : ... AssignmentExpression
  1. empty를 반환한다.
PropertyDefinition : PropertyName : AssignmentExpression
  1. PropertyName의 PropName을 반환한다.
LiteralPropertyName : IdentifierName AttributeKey : IdentifierName
  1. IdentifierName의 StringValue를 반환한다.
LiteralPropertyName : StringLiteral AttributeKey : StringLiteral
  1. StringLiteral의 SV를 반환한다.
LiteralPropertyName : NumericLiteral
  1. nbrNumericLiteral의 NumericValue로 둔다.
  2. ToString(nbr)을 반환한다.
ComputedPropertyName : [ AssignmentExpression ]
  1. empty를 반환한다.
MethodDefinition : ClassElementName ( UniqueFormalParameters ) { FunctionBody } get ClassElementName ( ) { FunctionBody } set ClassElementName ( PropertySetParameterList ) { FunctionBody }
  1. ClassElementName의 PropName을 반환한다.
GeneratorMethod : * ClassElementName ( UniqueFormalParameters ) { GeneratorBody }
  1. ClassElementName의 PropName을 반환한다.
AsyncGeneratorMethod : async * ClassElementName ( UniqueFormalParameters ) { AsyncGeneratorBody }
  1. ClassElementName의 PropName을 반환한다.
ClassElement : ClassStaticBlock
  1. empty를 반환한다.
ClassElement : ;
  1. empty를 반환한다.
AsyncMethod : async ClassElementName ( UniqueFormalParameters ) { AsyncFunctionBody }
  1. ClassElementName의 PropName을 반환한다.
FieldDefinition : ClassElementName Initializeropt
  1. ClassElementName의 PropName을 반환한다.
ClassElementName : PrivateIdentifier
  1. empty를 반환한다.

9 실행 가능한 코드와 실행 컨텍스트(Executable Code and Execution Contexts)

9.1 Environment Record

Environment Record는 ECMAScript 코드의 렉시컬 중첩 구조를 기반으로 Identifier들을 특정 변수와 함수에 연계(association)하기 위해 사용되는 명세 타입이다. 보통 Environment Record는 FunctionDeclaration, BlockStatement, TryStatementCatch 절과 같은 ECMAScript 코드의 특정 구문 구조와 연관된다. 그러한 코드가 실행될 때마다 그 코드가 생성하는 식별자 바인딩을 기록하기 위해 새로운 Environment Record가 생성된다.

모든 Environment Record는 [[OuterEnv]] 필드를 가지며, 이는 null이거나 바깥(Environment Record) 환경 레코드에 대한 참조이다. 이는 Environment Record 값들의 논리적 중첩을 모델링하는 데 사용된다. (내부) Environment Record의 바깥 참조는 논리적으로 그 내부 Environment Record를 둘러싸는 Environment Record에 대한 참조이다. 바깥 Environment Record 역시 자체의 바깥 Environment Record를 가질 수 있다. 하나의 Environment Record는 여러 내부 Environment Record의 바깥 환경으로 사용될 수 있다. 예를 들어, 어떤 FunctionDeclaration이 두 개의 중첩된 FunctionDeclaration을 포함한다면 각각의 중첩 함수 Environment Record의 바깥 Environment Record는 둘러싼 함수의 현재 평가에 대한 Environment Record가 된다.

Environment Record는 순수히 명세 메커니즘이며 ECMAScript 구현의 특정한 실체(artefact)에 대응할 필요는 없다. ECMAScript 프로그램이 그러한 값을 직접 접근하거나 조작하는 것은 불가능하다.

9.1.1 Environment Record 타입 계층(The Environment Record Type Hierarchy)

Environment Record는 단순한 객체 지향 계층에 존재한다고 생각할 수 있는데, Environment Record 자체가 추상 클래스이고 세 개의 구체 하위 클래스(Declarative Environment Record, Object Environment Record, Global Environment Record)가 있다. Function Environment RecordModule Environment RecordDeclarative Environment Record의 하위 클래스이다.

Environment Record 추상 클래스는 Table 14에 정의된 추상 명세 메서드를 포함한다. 이 추상 메서드들은 각 구체 하위 클래스마다 구별되는 구체 알고리즘을 가진다.

Table 14: Environment Record의 추상 메서드(Abstract Methods of Environment Records)
메서드(Method) 목적(Purpose)
HasBinding(N) Environment Record가 문자열 값 N에 대한 바인딩을 가지는지 결정한다. 있다면 true, 없으면 false를 반환.
CreateMutableBinding(N, D) Environment Record에 새이지만 아직 초기화되지 않은 변경 가능(mutable) 바인딩을 생성한다. 문자열 값 N은 바운드 이름 텍스트다. Boolean 인자 Dtrue이면 해당 바인딩은 이후 삭제될 수 있다.
CreateImmutableBinding(N, S) Environment Record에 새이지만 아직 초기화되지 않은 변경 불가능(immutable) 바인딩을 생성한다. 문자열 값 N은 바운드 이름 텍스트다. Strue이면 초기화 후 설정하려는 모든 시도는 (참조하는 연산의 strict 모드 설정과 무관하게) 항상 예외를 던진다.
InitializeBinding(N, V) Environment Record 내 이미 존재하지만 초기화되지 않은 바인딩의 값을 설정한다. 문자열 값 N은 바운드 이름 텍스트. V는 바인딩에 대한 값이며 임의의 ECMAScript 언어 타입 값이다.
SetMutableBinding(N, V, S) 이미 존재하는 mutable 바인딩의 값을 설정한다. 문자열 값 N은 바운드 이름 텍스트, V는 값, S는 Boolean 플래그. Strue이고 바인딩을 설정할 수 없다면 TypeError 예외를 던진다.
GetBindingValue(N, S) 이미 존재하는 바인딩의 값을 반환한다. 문자열 값 N은 바운드 이름 텍스트. S는 strict 모드 코드에서 기원했거나 strict 모드 참조语 의미를 요구하는지 식별하는 데 사용된다. Strue이고 바인딩이 존재하지 않으면 ReferenceError를 던진다. 바인딩이 존재하지만 초기화되지 않았다면 S 값과 무관하게 ReferenceError를 던진다.
DeleteBinding(N) 바인딩을 삭제한다. 문자열 값 N은 바운드 이름 텍스트. N에 대한 바인딩이 존재하면 제거하고 true 반환. 존재하지만 제거 불가하면 false 반환. 존재하지 않으면 true 반환.
HasThisBinding() Environment Recordthis 바인딩을 설정하는지 결정. 그렇다면 true, 아니면 false.
HasSuperBinding() Environment Recordsuper 메서드 바인딩을 설정하는지 결정. 그렇다면 true, 아니면 false. true이면 해당 Environment RecordFunction Environment Record임을 시사하지만, 그 역은 성립하지 않는다.
WithBaseObject() Environment Recordwith 문과 연관되면 with 객체를 반환. 아니면 undefined 반환.

9.1.1.1 Declarative Environment Record

Declarative Environment Record는 변수, constant, let, class, module, import 그리고/또는 function 선언을 포함하는 ECMAScript 프로그램 스코프와 연관된다. Declarative Environment Record는 그 스코프에 포함된 선언들이 정의한 식별자 집합을 바인딩한다.

9.1.1.1.1 HasBinding ( N )

The HasBinding concrete method of Declarative Environment Record envRec takes argument N (String) and returns Boolean을 담는 normal completion. 인수 식별자가 이 레코드에 의해 바인딩된 식별자 중 하나인지 판정한다. It performs the following steps when called:

  1. envRecN에 대한 바인딩을 가지고 있으면 true 반환.
  2. false 반환.

9.1.1.1.2 CreateMutableBinding ( N, D )

The CreateMutableBinding concrete method of Declarative Environment Record envRec takes arguments N (String) and D (Boolean) and returns unused를 담는 normal completion. 초기화되지 않은 이름 N에 대한 새로운 mutable 바인딩을 생성한다. 이미 존재해서는 안 된다. Dtrue이면 삭제 대상 표시. It performs the following steps when called:

  1. 단언: envRec은 이미 N 바인딩을 갖지 않는다.
  2. envRec 안에 N에 대한 초기화되지 않은 mutable 바인딩을 생성하고 Dtrue이면 이후 DeleteBinding 호출로 삭제 가능함을 기록.
  3. unused 반환.

9.1.1.1.3 CreateImmutableBinding ( N, S )

The CreateImmutableBinding concrete method of Declarative Environment Record envRec takes arguments N (String) and S (Boolean) and returns unused를 담는 normal completion. 초기화되지 않은 이름 N에 대한 immutable 바인딩을 생성. 이미 존재해서는 안 된다. Strue이면 strict 바인딩으로 표시. It performs the following steps when called:

  1. 단언: envRec은 이미 N 바인딩을 갖지 않는다.
  2. envRecN immutable 바인딩을 생성하고 초기화되지 않았음을 기록. Strue이면 strict 바인딩임을 기록.
  3. unused 반환.

9.1.1.1.4 InitializeBinding ( N, V )

The InitializeBinding concrete method of Declarative Environment Record envRec takes arguments N (String) and V (ECMAScript 언어 값) and returns unused를 담는 normal completion. 이미 존재하는 식별자 N의 현재 바인딩 값(bound value)을 V로 설정한다. N에 대한 초기화되지 않은 바인딩이 이미 있어야 한다. It performs the following steps when called:

  1. 단언: envRecN에 대한 초기화되지 않은 바인딩을 가져야 한다.
  2. envRec에서 N의 바운드 값을 V로 설정.
  3. Record envRecN 바인딩이 초기화되었음을 기록.
  4. unused 반환.

9.1.1.1.5 SetMutableBinding ( N, V, S )

The SetMutableBinding concrete method of Declarative Environment Record envRec takes arguments N (String), V (ECMAScript 언어 값), and S (Boolean) and returns unused 또는 throw completion. 식별자 N의 현재 바인딩 값을 V로 변경 시도. 보통 바인딩은 이미 존재하지만 드물게 없을 수도 있다. 바인딩이 immutable이고 Strue이면 TypeError. It performs the following steps when called:

  1. envRecN 바인딩이 없다면
    1. Strue이면 ReferenceError 예외.
    2. envRec.CreateMutableBinding(N, true) 수행.
    3. envRec.InitializeBinding(N, V) 수행.
    4. unused 반환.
  2. envRec에서 N 바인딩이 strict 바인딩이면 Strue로 설정.
  3. envRec에서 N 바인딩이 아직 초기화되지 않았다면 ReferenceError 예외.
  4. Else if envRec에서 N 바인딩이 mutable이면
    1. 그 값을 V로 변경.
  5. Else
    1. 단언: immutable 바인딩 값을 변경하려는 시도.
    2. Strue이면 TypeError 예외.
  6. unused 반환.
Note

단계 1에서 바인딩이 누락되는 ECMAScript 코드 예:

function f() { eval("var x; x = (delete x, 0);"); }

9.1.1.1.6 GetBindingValue ( N, S )

The GetBindingValue concrete method of Declarative Environment Record envRec takes arguments N (String) and S (Boolean) and returns ECMAScript 언어 값 또는 throw completion. 이름이 N인 바인딩된 식별자의 값을 반환. 바인딩이 존재하지만 초기화되지 않았으면 S와 무관하게 ReferenceError. It performs the following steps when called:

  1. 단언: envRecN 바인딩을 가진다.
  2. envRecN 바인딩이 초기화되지 않았다면 ReferenceError 예외.
  3. 현재 envRecN으로 바인딩된 값을 반환.

9.1.1.1.7 DeleteBinding ( N )

The DeleteBinding concrete method of Declarative Environment Record envRec takes argument N (String) and returns Boolean을 담는 normal completion. 삭제 대상으로 명시적으로 지정된 바인딩만 삭제할 수 있다. It performs the following steps when called:

  1. 단언: envRecN 바인딩을 가진다.
  2. envRecN 바인딩이 삭제 불가라면 false 반환.
  3. envRec에서 N 바인딩 제거.
  4. true 반환.

9.1.1.1.8 HasThisBinding ( )

The HasThisBinding concrete method of Declarative Environment Record envRec takes no arguments and returns false. It performs the following steps when called:

  1. false 반환.
Note

일반 Declarative Environment Record(즉 Function Environment RecordModule Environment Record가 아닌 것)는 this 바인딩을 제공하지 않는다.

9.1.1.1.9 HasSuperBinding ( )

The HasSuperBinding concrete method of Declarative Environment Record envRec takes no arguments and returns false. It performs the following steps when called:

  1. false 반환.
Note

일반 Declarative Environment Recordsuper 바인딩을 제공하지 않는다.

9.1.1.1.10 WithBaseObject ( )

The WithBaseObject concrete method of Declarative Environment Record envRec takes no arguments and returns undefined. It performs the following steps when called:

  1. undefined 반환.

9.1.1.2 Object Environment Record

Object Environment Recordbinding object라 불리는 객체와 연관된다. Object Environment Record는 그 binding object의 프로퍼티 이름과 직접 대응하는 문자열 식별자 이름 집합을 바인딩한다. IdentifierName 형태가 아닌 프로퍼티 키는 포함되지 않는다. own 및 상속 프로퍼티 모두 [[Enumerable]] 속성과 무관하게 포함된다. 객체에 프로퍼티가 동적으로 추가/삭제될 수 있으므로 Object Environment Record가 바인딩하는 식별자 집합은 프로퍼티를 추가/삭제하는 어떤 연산의 부수 효과로 잠재적으로 변화할 수 있다. 그러한 부수 효과로 생성된 바인딩은 대응 프로퍼티의 Writable 속성이 false일지라도 mutable 바인딩으로 간주된다. Object Environment Record에는 immutable 바인딩이 존재하지 않는다.

with 문(14.11)에 대해 생성된 Object Environment Record는 함수 호출에서 사용할 암묵적 this 값을 그 binding object로 제공할 수 있다. 이 기능은 Boolean [[IsWithEnvironment]] 필드로 제어된다.

Object Environment Record는 Table 15에 나열된 추가 상태 필드를 가진다.

Table 15: Object Environment Record의 추가 필드(Additional Fields of Object Environment Records)
필드 이름(Field Name) 값(Value) 의미(Meaning)
[[BindingObject]] 객체(Object) Environment Record의 바인딩 객체.
[[IsWithEnvironment]] Boolean Environment Recordwith 문을 위해 생성되었는지 여부.

9.1.1.2.1 HasBinding ( N )

The HasBinding concrete method of Object Environment Record envRec takes argument N (String) and returns Boolean 또는 throw completion. 연관된 binding object가 이름 N인 프로퍼티를 가지는지 판정한다. It performs the following steps when called:

  1. bindingObjectenvRec.[[BindingObject]]로 둔다.
  2. foundBinding을 ? HasProperty(bindingObject, N)로 둔다.
  3. foundBindingfalse이면 false 반환.
  4. envRec.[[IsWithEnvironment]]false이면 true 반환.
  5. unscopables를 ? Get(bindingObject, %Symbol.unscopables%)로 둔다.
  6. unscopables가 Object이면
    1. blockedToBoolean(? Get(unscopables, N))로 둔다.
    2. blockedtrue이면 false 반환.
  7. true 반환.

9.1.1.2.2 CreateMutableBinding ( N, D )

The CreateMutableBinding concrete method of Object Environment Record envRec takes arguments N (String) and D (Boolean) and returns unused 또는 throw completion. Environment Record의 binding object에 이름 N 프로퍼티를 생성하고 값을 undefined로 초기화. Dtrue이면 새 프로퍼티 [[Configurable]]true, 아니면 false. It performs the following steps when called:

  1. bindingObjectenvRec.[[BindingObject]]로 둔다.
  2. DefinePropertyOrThrow(bindingObject, N, PropertyDescriptor { [[Value]]: undefined, [[Writable]]: true, [[Enumerable]]: true, [[Configurable]]: D }) 수행.
  3. unused 반환.
Note

보통 envRecN 바인딩을 갖지 않지만 갖고 있다면 DefinePropertyOrThrow 의미론이 기존 바인딩을 교체/섀도우하거나 abrupt completion을 유발할 수 있다.

9.1.1.2.3 CreateImmutableBinding ( N, S )

Object Environment Record의 CreateImmutableBinding 구체 메서드는 이 명세 내에서 사용되지 않는다.

9.1.1.2.4 InitializeBinding ( N, V )

The InitializeBinding concrete method of Object Environment Record envRec takes arguments N (String) and V (ECMAScript 언어 값) and returns unused 또는 throw completion. 이름 N인 바인딩 객체 프로퍼티의 값을 V로 설정. It performs the following steps when called:

  1. envRec.SetMutableBinding(N, V, false) 수행.
  2. unused 반환.
Note

이 명세에서 Object Environment Record에 대한 모든 CreateMutableBinding 사용은 같은 이름에 대한 InitializeBinding 호출로 즉시 이어지므로, 초기화 상태를 명시적으로 추적하지 않는다.

9.1.1.2.5 SetMutableBinding ( N, V, S )

The SetMutableBinding concrete method of Object Environment Record envRec takes arguments N (String), V (ECMAScript 언어 값), and S (Boolean) and returns unused 또는 throw completion. 연관된 binding object의 프로퍼티 N 값을 V로 설정 시도. 보통 존재하지만 없거나 쓰기 불가능이면 S에 따라 오류 처리. It performs the following steps when called:

  1. bindingObjectenvRec.[[BindingObject]]로 둔다.
  2. stillExists를 ? HasProperty(bindingObject, N)로 둔다.
  3. stillExistsfalse이고 Strue이면 ReferenceError 예외.
  4. Set(bindingObject, N, V, S) 수행.
  5. unused 반환.

9.1.1.2.6 GetBindingValue ( N, S )

The GetBindingValue concrete method of Object Environment Record envRec takes arguments N (String) and S (Boolean) and returns ECMAScript 언어 값 또는 throw completion. binding object의 이름 N 프로퍼티 값을 반환. 존재하지 않을 경우 S에 따라 결과 결정. It performs the following steps when called:

  1. bindingObjectenvRec.[[BindingObject]]로 둔다.
  2. value를 ? HasProperty(bindingObject, N)로 둔다.
  3. valuefalse이면
    1. Sfalse이면 undefined 반환; 아니면 ReferenceError 예외.
  4. Get(bindingObject, N) 반환.

9.1.1.2.7 DeleteBinding ( N )

The DeleteBinding concrete method of Object Environment Record envRec takes argument N (String) and returns Boolean 또는 throw completion. [[Configurable]]true인 환경 객체 프로퍼티에 대응되는 바인딩만 삭제 가능. It performs the following steps when called:

  1. bindingObjectenvRec.[[BindingObject]]로 둔다.
  2. bindingObject.[[Delete]](N) 반환.

9.1.1.2.8 HasThisBinding ( )

The HasThisBinding concrete method of Object Environment Record envRec takes no arguments and returns false. It performs the following steps when called:

  1. false 반환.
Note

Object Environment Recordthis 바인딩을 제공하지 않는다.

9.1.1.2.9 HasSuperBinding ( )

The HasSuperBinding concrete method of Object Environment Record envRec takes no arguments and returns false. It performs the following steps when called:

  1. false 반환.
Note

Object Environment Recordsuper 바인딩을 제공하지 않는다.

9.1.1.2.10 WithBaseObject ( )

The WithBaseObject concrete method of Object Environment Record envRec takes no arguments and returns Object 또는 undefined. It performs the following steps when called:

  1. envRec.[[IsWithEnvironment]]true이면 envRec.[[BindingObject]] 반환.
  2. 아니면 undefined 반환.

9.1.1.3 Function Environment Record

Function Environment Record는 함수의 최상위 스코프를 나타내는 Declarative Environment Record이며 함수가 ArrowFunction이 아니면 this 바인딩을 제공한다. 함수가 ArrowFunction이 아니고 super를 참조하는 경우 그 Function Environment Record는 함수 내에서 super 메서드 호출을 수행하는 데 사용되는 상태도 포함한다.

Function Environment Record는 Table 16에 나열된 추가 상태 필드를 가진다.

Table 16: Function Environment Record의 추가 필드(Additional Fields of Function Environment Records)
필드 이름 의미
[[ThisValue]] ECMAScript 언어 값 이 함수 호출에 사용되는 this 값.
[[ThisBindingStatus]] lexical, initialized, 또는 uninitialized 값이 lexical이면 이는 ArrowFunction이며 로컬 this 값이 없다.
[[FunctionObject]] ECMAScript 함수 객체 Environment Record를 생성한 호출의 대상 함수 객체.
[[NewTarget]] 생성자 또는 undefined [[Construct]] 내부 메서드로 생성되었다면 [[Construct]] newTarget 매개변수의 값; 아니면 undefined.

Function Environment Record는 Table 14에 나열된 모든 Declarative Environment Record 메서드를 지원하고 HasThisBinding 및 HasSuperBinding을 제외한 명세는 동일하다. 추가로 Table 17에 나열된 메서드를 지원한다:

Table 17: Function Environment Record의 추가 메서드(Additional Methods of Function Environment Records)
메서드 목적
GetThisBinding() Environment Recordthis 바인딩 값을 반환. 초기화되지 않았으면 ReferenceError.

9.1.1.3.1 BindThisValue ( envRec, V )

The abstract operation BindThisValue takes arguments envRec (Function Environment Record) and V (ECMAScript 언어 값) and returns unused 또는 throw completion. envRec.[[ThisValue]]를 설정하고 초기화되었음을 기록한다. It performs the following steps when called:

  1. 단언: envRec.[[ThisBindingStatus]]lexical이 아니다.
  2. envRec.[[ThisBindingStatus]]initialized이면 ReferenceError 예외.
  3. envRec.[[ThisValue]]V로 설정.
  4. envRec.[[ThisBindingStatus]]initialized로 설정.
  5. unused 반환.

9.1.1.3.2 HasThisBinding ( )

The HasThisBinding concrete method of Function Environment Record envRec takes no arguments and returns Boolean. It performs the following steps when called:

  1. envRec.[[ThisBindingStatus]]lexical이면 false, 아니면 true 반환.

9.1.1.3.3 HasSuperBinding ( )

The HasSuperBinding concrete method of Function Environment Record envRec takes no arguments and returns Boolean. It performs the following steps when called:

  1. envRec.[[ThisBindingStatus]]lexical이면 false 반환.
  2. envRec.[[FunctionObject]].[[HomeObject]]undefined이면 false, 아니면 true 반환.

9.1.1.3.4 GetThisBinding ( )

The GetThisBinding concrete method of Function Environment Record envRec takes no arguments and returns ECMAScript 언어 값 또는 throw completion. It performs the following steps when called:

  1. 단언: envRec.[[ThisBindingStatus]]lexical이 아니다.
  2. envRec.[[ThisBindingStatus]]uninitialized이면 ReferenceError 예외.
  3. envRec.[[ThisValue]] 반환.

9.1.1.3.5 GetSuperBase ( envRec )

The abstract operation GetSuperBase takes argument envRec (Function Environment Record) and returns Object, null, 또는 undefined. envRec에 바인딩된 super 프로퍼티 접근의 기반 객체를 반환한다. undefined 값은 그러한 접근이 런타임 오류를 낼 것임을 나타낸다. It performs the following steps when called:

  1. homeenvRec.[[FunctionObject]].[[HomeObject]]로 둔다.
  2. homeundefined이면 undefined 반환.
  3. 단언: home은 ordinary object.
  4. home.[[GetPrototypeOf]]() 반환.

9.1.1.4 Global Environment Record

Global Environment Record는 공통 realm에서 처리되는 모든 ECMAScript Script 요소가 공유하는 가장 바깥 스코프를 나타낸다. Global Environment Record는 내장(global) 전역(19 절), 전역 객체의 프로퍼티 및 Script 내 모든 최상위 선언(8.2.9, 8.2.11)의 바인딩을 제공한다.

Global Environment Record는 논리적으로 단일 레코드이지만 Object Environment RecordDeclarative Environment Record를 캡슐화한 합성체로 명세된다. Object Environment Record는 관련 Realm Record전역 객체를 기본 객체로 가진다. 이 전역 객체는 Global Environment Record의 GetThisBinding 구체 메서드가 반환하는 값이다. Global Environment Record의 Object Environment Record 구성 요소는 모든 내장 전역(19)과 전역 코드에 포함된 FunctionDeclaration, GeneratorDeclaration, AsyncFunctionDeclaration, AsyncGeneratorDeclaration, VariableStatement이 도입한 바인딩을 포함한다. 전역 코드의 다른 ECMAScript 선언에 대한 바인딩은 Global Environment Record의 Declarative Environment Record 구성 요소에 들어 있다.

프로퍼티는 전역 객체에 직접 생성될 수 있다. 따라서 Global Environment Record의 Object Environment Record 구성 요소는 선언에 의해 명시적으로 생성된 바인딩과 전역 객체의 프로퍼티로 암묵적으로 생성된 바인딩을 모두 포함할 수 있다. 어느 바인딩이 선언을 통해 명시적으로 생성되었는지 식별하기 위해 Global Environment Record는 CreateGlobalVarBindingCreateGlobalFunctionBinding 추상 연산을 사용해 바인딩된 이름 목록을 유지한다.

Global Environment Record는 Table 18에 나열된 추가 필드와 Table 19에 나열된 추가 메서드를 가진다.

Table 18: Global Environment Record의 추가 필드(Additional Fields of Global Environment Records)
필드 이름 의미
[[ObjectRecord]] Object Environment Record 바인딩 객체는 전역 객체. 관련 realm의 전역 코드 내 FunctionDeclaration, GeneratorDeclaration, AsyncFunctionDeclaration, AsyncGeneratorDeclaration, VariableDeclaration 바인딩과 전역 내장 바인딩을 포함.
[[GlobalThisValue]] Object 전역 스코프에서 this가 반환하는 값. 호스트는 임의의 ECMAScript Object 값을 제공할 수 있다.
[[DeclarativeRecord]] Declarative Environment Record Contains 전역 코드 선언 중 FunctionDeclaration, GeneratorDeclaration, AsyncFunctionDeclaration, AsyncGeneratorDeclaration, VariableDeclaration을 제외한 모든 선언 바인딩.
Table 19: Global Environment Record의 추가 메서드(Additional Methods of Global Environment Records)
메서드 목적
GetThisBinding() Environment Recordthis 바인딩 값을 반환.

9.1.1.4.1 HasBinding ( N )

The HasBinding concrete method of Global Environment Record envRec takes argument N (String) and returns Boolean 또는 throw completion. 인수 식별자가 레코드에 의해 바인딩된 식별자 중 하나인지 판정. It performs the following steps when called:

  1. DclRecenvRec.[[DeclarativeRecord]]로 둔다.
  2. DclRec.HasBinding(N)이 true이면 true 반환.
  3. ObjRecenvRec.[[ObjectRecord]]로 둔다.
  4. ObjRec.HasBinding(N) 반환.

9.1.1.4.2 CreateMutableBinding ( N, D )

The CreateMutableBinding concrete method of Global Environment Record envRec takes arguments N (String) and D (Boolean) and returns unused 또는 throw completion. 초기화되지 않은 N mutable 바인딩을 새로 생성. 관련 DeclarativeRecord에 생성. 이미 존재하면 안 됨. Dtrue면 삭제 가능 표시. It performs the following steps when called:

  1. DclRecenvRec.[[DeclarativeRecord]]로 둔다.
  2. DclRec.HasBinding(N)이 true이면 TypeError 예외.
  3. DclRec.CreateMutableBinding(N, D) 반환.

9.1.1.4.3 CreateImmutableBinding ( N, S )

The CreateImmutableBinding concrete method of Global Environment Record envRec takes arguments N (String) and S (Boolean) and returns unused 또는 throw completion. 초기화되지 않은 N immutable 바인딩 생성. 이미 존재하면 안 됨. Strue이면 strict 바인딩. It performs the following steps when called:

  1. DclRecenvRec.[[DeclarativeRecord]]로 둔다.
  2. DclRec.HasBinding(N)이 true이면 TypeError 예외.
  3. DclRec.CreateImmutableBinding(N, S) 반환.

9.1.1.4.4 InitializeBinding ( N, V )

The InitializeBinding concrete method of Global Environment Record envRec takes arguments N (String) and V (ECMAScript 언어 값) and returns unused 또는 throw completion. 식별자 N의 현재 바인딩 값을 V로 설정. N에 대한 초기화되지 않은 바인딩이 이미 존재해야 한다. It performs the following steps when called:

  1. DclRecenvRec.[[DeclarativeRecord]]로 둔다.
  2. DclRec.HasBinding(N)이 true이면
    1. DclRec.InitializeBinding(N, V) 반환.
  3. 단언: 바인딩이 존재한다면 Object Environment Record에 있다.
  4. ObjRecenvRec.[[ObjectRecord]]로 둔다.
  5. ObjRec.InitializeBinding(N, V) 반환.

9.1.1.4.5 SetMutableBinding ( N, V, S )

The SetMutableBinding concrete method of Global Environment Record envRec takes arguments N (String), V (ECMAScript 언어 값), and S (Boolean) and returns unused 또는 throw completion. 식별자 N의 현재 바인딩 값을 V로 변경 시도. immutable 바인딩이고 Strue이면 TypeError. 프로퍼티 N은 보통 존재하지만 없거나 현재 writable이 아닐 수도 있으며 이는 S에 따라 처리. It performs the following steps when called:

  1. DclRecenvRec.[[DeclarativeRecord]]로 둔다.
  2. DclRec.HasBinding(N)이 true이면
    1. DclRec.SetMutableBinding(N, V, S) 반환.
  3. ObjRecenvRec.[[ObjectRecord]]로 둔다.
  4. ObjRec.SetMutableBinding(N, V, S) 반환.

9.1.1.4.6 GetBindingValue ( N, S )

The GetBindingValue concrete method of Global Environment Record envRec takes arguments N (String) and S (Boolean) and returns ECMAScript 언어 값 또는 throw completion. 식별자 N의 값을 반환. 바인딩이 초기화되지 않았으면 ReferenceError. 프로퍼티 N은 보통 존재하지만 없거나 writable이 아닐 수도 있는데 이는 S에 따라 처리. It performs the following steps when called:

  1. DclRecenvRec.[[DeclarativeRecord]]로 둔다.
  2. DclRec.HasBinding(N)이 true이면
    1. DclRec.GetBindingValue(N, S) 반환.
  3. ObjRecenvRec.[[ObjectRecord]]로 둔다.
  4. ObjRec.GetBindingValue(N, S) 반환.

9.1.1.4.7 DeleteBinding ( N )

The DeleteBinding concrete method of Global Environment Record envRec takes argument N (String) and returns Boolean 또는 throw completion. 삭제 대상으로 명시된 바인딩만 삭제 가능. It performs the following steps when called:

  1. DclRecenvRec.[[DeclarativeRecord]]로 둔다.
  2. DclRec.HasBinding(N)이 true이면
    1. DclRec.DeleteBinding(N) 반환.
  3. ObjRecenvRec.[[ObjectRecord]]로 둔다.
  4. globalObjectObjRec.[[BindingObject]]로 둔다.
  5. existingProp을 ? HasOwnProperty(globalObject, N)로 둔다.
  6. existingProptrue이면
    1. ObjRec.DeleteBinding(N) 반환.
  7. true 반환.

9.1.1.4.8 HasThisBinding ( )

The HasThisBinding concrete method of Global Environment Record envRec takes no arguments and returns true. It performs the following steps when called:

  1. true 반환.
Note

Global Environment Record는 항상 this 바인딩을 제공한다.

9.1.1.4.9 HasSuperBinding ( )

The HasSuperBinding concrete method of Global Environment Record envRec takes no arguments and returns false. It performs the following steps when called:

  1. false 반환.
Note

Global Environment Recordsuper 바인딩을 제공하지 않는다.

9.1.1.4.10 WithBaseObject ( )

The WithBaseObject concrete method of Global Environment Record envRec takes no arguments and returns undefined. It performs the following steps when called:

  1. undefined 반환.

9.1.1.4.11 GetThisBinding ( )

The GetThisBinding concrete method of Global Environment Record envRec takes no arguments and returns Object를 담는 normal completion. It performs the following steps when called:

  1. envRec.[[GlobalThisValue]] 반환.

9.1.1.4.12 HasLexicalDeclaration ( envRec, N )

The abstract operation HasLexicalDeclaration takes arguments envRec (Global Environment Record) and N (String) and returns Boolean. 인수 식별자가 envRec에서 LexicalDeclaration 또는 ClassDeclaration 같은 렉시컬 선언을 사용해 생성된 바인딩을 가지는지 판정. It performs the following steps when called:

  1. DclRecenvRec.[[DeclarativeRecord]]로 둔다.
  2. DclRec.HasBinding(N) 반환.

9.1.1.4.13 HasRestrictedGlobalProperty ( envRec, N )

The abstract operation HasRestrictedGlobalProperty takes arguments envRec (Global Environment Record) and N (String) and returns Boolean 또는 throw completion. 인수 식별자가 전역 객체의, 전역 렉시컬 바인딩으로 섀도우 되어서는 안 되는 프로퍼티 이름인지 판정. It performs the following steps when called:

  1. ObjRecenvRec.[[ObjectRecord]]로 둔다.
  2. globalObjectObjRec.[[BindingObject]]로 둔다.
  3. existingProp을 ? globalObject.[[GetOwnProperty]](N)로 둔다.
  4. existingPropundefined이면 false 반환.
  5. existingProp.[[Configurable]]true이면 false 반환.
  6. true 반환.
Note

프로퍼티는 var나 function 선언 대신 직접 전역 객체에 존재할 수도 있다. 글로벌 렉시컬 바인딩은 전역 객체의 non-configurable 프로퍼티와 같은 이름으로 생성될 수 없다. "undefined" 전역 프로퍼티가 예.

9.1.1.4.14 CanDeclareGlobalVar ( envRec, N )

The abstract operation CanDeclareGlobalVar takes arguments envRec (Global Environment Record) and N (String) and returns Boolean 또는 throw completion. 같은 N으로 CreateGlobalVarBinding 호출이 성공할지 여부 결정. 중복 var 선언 및 기존 전역 객체 프로퍼티에 대한 var 선언 허용. It performs the following steps when called:

  1. ObjRecenvRec.[[ObjectRecord]]로 둔다.
  2. globalObjectObjRec.[[BindingObject]]로 둔다.
  3. hasProperty를 ? HasOwnProperty(globalObject, N)로 둔다.
  4. hasPropertytrue이면 true 반환.
  5. IsExtensible(globalObject) 반환.

9.1.1.4.15 CanDeclareGlobalFunction ( envRec, N )

The abstract operation CanDeclareGlobalFunction takes arguments envRec (Global Environment Record) and N (String) and returns Boolean 또는 throw completion. 같은 N으로 CreateGlobalFunctionBinding 호출이 성공할지 여부 결정. It performs the following steps when called:

  1. ObjRecenvRec.[[ObjectRecord]]로 둔다.
  2. globalObjectObjRec.[[BindingObject]]로 둔다.
  3. existingProp을 ? globalObject.[[GetOwnProperty]](N)로 둔다.
  4. existingPropundefined이면 ? IsExtensible(globalObject) 반환.
  5. existingProp.[[Configurable]]true이면 true 반환.
  6. IsDataDescriptor(existingProp)가 true이고 existingProp 속성 값이 { [[Writable]]: true, [[Enumerable]]: true }이면 true 반환.
  7. false 반환.

9.1.1.4.16 CreateGlobalVarBinding ( envRec, N, D )

The abstract operation CreateGlobalVarBinding takes arguments envRec (Global Environment Record), N (String), and D (Boolean) and returns unused 또는 throw completion. 연관된 Object Environment Record에 mutable 바인딩을 생성·초기화. 이미 존재하면 재사용되고 초기화된 것으로 간주. It performs the following steps when called:

  1. ObjRecenvRec.[[ObjectRecord]]로 둔다.
  2. globalObjectObjRec.[[BindingObject]]로 둔다.
  3. hasProperty를 ? HasOwnProperty(globalObject, N)로 둔다.
  4. extensible을 ? IsExtensible(globalObject)로 둔다.
  5. hasPropertyfalse이고 extensibletrue이면
    1. ObjRec.CreateMutableBinding(N, D) 수행.
    2. ObjRec.InitializeBinding(N, undefined) 수행.
  6. unused 반환.

9.1.1.4.17 CreateGlobalFunctionBinding ( envRec, N, V, D )

The abstract operation CreateGlobalFunctionBinding takes arguments envRec (Global Environment Record), N (String), V (ECMAScript 언어 값), and D (Boolean) and returns unused 또는 throw completion. 연관된 Object Environment Record에 mutable 바인딩을 생성·초기화. 이미 존재하면 대체. It performs the following steps when called:

  1. ObjRecenvRec.[[ObjectRecord]]로 둔다.
  2. globalObjectObjRec.[[BindingObject]]로 둔다.
  3. existingProp을 ? globalObject.[[GetOwnProperty]](N)로 둔다.
  4. existingPropundefined이거나 existingProp.[[Configurable]]true이면
    1. desc를 PropertyDescriptor { [[Value]]: V, [[Writable]]: true, [[Enumerable]]: true, [[Configurable]]: D }로 둔다.
  5. Else
    1. desc를 PropertyDescriptor { [[Value]]: V }로 둔다.
  6. DefinePropertyOrThrow(globalObject, N, desc) 수행.
  7. Set(globalObject, N, V, false) 수행.
  8. unused 반환.
Note

전역 함수 선언은 항상 전역 객체의 own 프로퍼티로 표현된다. 가능하면 기존 own 프로퍼티가 표준 속성 집합으로 재구성된다. 단계 7은 InitializeBinding 구체 메서드 호출과 동등하며 globalObject가 Proxy이면 동일한 Proxy 트랩 호출 순서를 만든다.

9.1.1.5 Module Environment Record

Module Environment Record는 ECMAScript Module의 바깥 스코프를 나타내는 Declarative Environment Record이며, 일반 mutable/immutable 바인딩 외에 다른 Environment Record에 존재하는 대상 바인딩에 간접 접근을 제공하는 immutable import 바인딩도 제공한다.

Module Environment Record는 Table 14에 나열된 모든 Declarative Environment Record 메서드를 지원하며 GetBindingValue, DeleteBinding, HasThisBinding, GetThisBinding을 제외하고 동일한 명세를 공유한다. 추가로 Table 20에 나열된 메서드를 지원한다:

Table 20: Module Environment Record의 추가 메서드(Additional Methods of Module Environment Records)
메서드 목적
GetThisBinding() Environment Recordthis 바인딩 값을 반환.

9.1.1.5.1 GetBindingValue ( N, S )

The GetBindingValue concrete method of Module Environment Record envRec takes arguments N (String) and S (Boolean) and returns ECMAScript 언어 값 또는 throw completion. 이름 N인 바인딩된 식별자 값을 반환. 간접 바인딩이면 대상 바인딩 값을 반환. 바인딩이 존재하지만 초기화되지 않았으면 ReferenceError. It performs the following steps when called:

  1. 단언: Strue.
  2. 단언: envRecN 바인딩을 가진다.
  3. N에 대한 바인딩이 간접 바인딩이면
    1. N 바인딩 생성 시 제공된 간접 값 M, N2를 둔다.
    2. targetEnvM.[[Environment]]로 둔다.
    3. targetEnvempty이면 ReferenceError 예외.
    4. targetEnv.GetBindingValue(N2, true) 반환.
  4. envRecN 바인딩이 초기화되지 않았으면 ReferenceError 예외.
  5. 현재 envRecN으로 바인딩된 값을 반환.
Note

S는 항상 true인데 Module은 항상 strict 모드 코드이기 때문이다.

9.1.1.5.2 DeleteBinding ( N )

Module Environment Record의 DeleteBinding 구체 메서드는 이 명세 내에서 사용되지 않는다.

Note

Module Environment Record는 strict 코드 내에서만 사용되고 초기 에러 규칙이 strict 코드에서 delete 연산자가 Module Environment Record 바인딩으로 해석될 Reference Record에 적용되는 것을 방지한다. 13.5.1.1 참조.

9.1.1.5.3 HasThisBinding ( )

The HasThisBinding concrete method of Module Environment Record envRec takes no arguments and returns true. It performs the following steps when called:

  1. true 반환.
Note

Module Environment Record는 항상 this 바인딩을 제공한다.

9.1.1.5.4 GetThisBinding ( )

The GetThisBinding concrete method of Module Environment Record envRec takes no arguments and returns undefined를 담는 normal completion. It performs the following steps when called:

  1. undefined 반환.

9.1.1.5.5 CreateImportBinding ( envRec, N, M, N2 )

The abstract operation CreateImportBinding takes arguments envRec (Module Environment Record), N (String), M (Module Record), and N2 (String) and returns unused. 이름 N에 대한 새로 초기화된 immutable 간접 바인딩을 생성. envRecN 바인딩이 이미 존재해서는 안 됨. N2MModule Environment Record에 존재하는 바인딩 이름. 새 바인딩의 값 접근은 대상 바인딩 값을 간접적으로 접근. It performs the following steps when called:

  1. 단언: envRec은 이미 N 바인딩을 갖지 않는다.
  2. 단언: M.[[Environment]]가 인스턴스화될 때 N2에 대한 direct 바인딩을 가진다.
  3. envRecN immutable 간접 바인딩을 생성하여 M, N2를 대상 바인딩으로 참조하고 초기화되었음을 기록.
  4. unused 반환.

9.1.2 Environment Record 연산(Environment Record Operations)

다음 추상 연산들은 명세에서 Environment Record를 조작하기 위해 사용된다:

9.1.2.1 GetIdentifierReference ( env, name, strict )

The abstract operation GetIdentifierReference takes arguments env (Environment Record 또는 null), name (String), and strict (Boolean) and returns Reference Record 또는 throw completion. It performs the following steps when called:

  1. envnull이면
    1. Reference Record { [[Base]]: unresolvable, [[ReferencedName]]: name, [[Strict]]: strict, [[ThisValue]]: empty } 반환.
  2. exists를 ? env.HasBinding(name)로 둔다.
  3. existstrue이면
    1. Reference Record { [[Base]]: env, [[ReferencedName]]: name, [[Strict]]: strict, [[ThisValue]]: empty } 반환.
  4. Else
    1. outerenv.[[OuterEnv]]로 둔다.
    2. GetIdentifierReference(outer, name, strict) 반환.

9.1.2.2 NewDeclarativeEnvironment ( E )

The abstract operation NewDeclarativeEnvironment takes argument E (Environment Record 또는 null) and returns Declarative Environment Record. It performs the following steps when called:

  1. 바인딩이 없는 새 Declarative Environment Record env를 만든다.
  2. env.[[OuterEnv]]E로 설정.
  3. env 반환.

9.1.2.3 NewObjectEnvironment ( O, W, E )

The abstract operation NewObjectEnvironment takes arguments O (Object), W (Boolean), and E (Environment Record 또는 null) and returns Object Environment Record. It performs the following steps when called:

  1. Object Environment Record env 생성.
  2. env.[[BindingObject]]O로 설정.
  3. env.[[IsWithEnvironment]]W로 설정.
  4. env.[[OuterEnv]]E로 설정.
  5. env 반환.

9.1.2.4 NewFunctionEnvironment ( F, newTarget )

The abstract operation NewFunctionEnvironment takes arguments F (ECMAScript 함수 객체) and newTarget (Object 또는 undefined) and returns Function Environment Record. It performs the following steps when called:

  1. 바인딩이 없는 새 Function Environment Record env 생성.
  2. env.[[FunctionObject]]F로 설정.
  3. F.[[ThisMode]]lexical이면 env.[[ThisBindingStatus]]lexical로 설정.
  4. Else env.[[ThisBindingStatus]]uninitialized로 설정.
  5. env.[[NewTarget]]newTarget으로 설정.
  6. env.[[OuterEnv]]F.[[Environment]]로 설정.
  7. env 반환.

9.1.2.5 NewGlobalEnvironment ( G, thisValue )

The abstract operation NewGlobalEnvironment takes arguments G (Object) and thisValue (Object) and returns Global Environment Record. It performs the following steps when called:

  1. objRecNewObjectEnvironment(G, false, null)로 둔다.
  2. dclRecNewDeclarativeEnvironment(null)로 둔다.
  3. Global Environment Record env 생성.
  4. env.[[ObjectRecord]]objRec로 설정.
  5. env.[[GlobalThisValue]]thisValue로 설정.
  6. env.[[DeclarativeRecord]]dclRec로 설정.
  7. env.[[OuterEnv]]null로 설정.
  8. env 반환.

9.1.2.6 NewModuleEnvironment ( E )

The abstract operation NewModuleEnvironment takes argument E (Environment Record) and returns Module Environment Record. It performs the following steps when called:

  1. 바인딩이 없는 새 Module Environment Record env 생성.
  2. env.[[OuterEnv]]E로 설정.
  3. env 반환.

9.2 PrivateEnvironment 레코드(PrivateEnvironment Records)

PrivateEnvironment Record는 ECMAScript 코드에서 ClassDeclarationClassExpression의 렉시컬 중첩 구조를 기반으로 Private Name들을 추적하기 위해 사용되는 명세 메커니즘이다. 이는 Environment Record와 유사하지만 별개의 것이다. 각 PrivateEnvironment Record는 하나의 ClassDeclaration 또는 ClassExpression에 연결된다. 그러한 클래스가 평가될 때마다, 그 클래스가 선언한 Private Name들을 기록하기 위해 새로운 PrivateEnvironment Record가 생성된다.

PrivateEnvironment RecordTable 21에 정의된 필드들을 가진다.

Table 21: PrivateEnvironment Record 필드(PrivateEnvironment Record Fields)
필드 이름(Field Name) 값 타입(Value Type) 의미(Meaning)
[[OuterPrivateEnvironment]] PrivateEnvironment Record 또는 null 가장 가까운 둘러싸는 클래스의 PrivateEnvironment Record. 이 PrivateEnvironment Record가 연결된 클래스가 다른 어떤 클래스에도 포함되지 않았다면 null.
[[Names]] Private Name들의 List 이 클래스가 선언한 Private Name들.

9.2.1 PrivateEnvironment Record 연산(PrivateEnvironment Record Operations)

다음 추상 연산들은 이 명세에서 PrivateEnvironment Record에 대해 동작하기 위해 사용된다:

9.2.1.1 NewPrivateEnvironment ( outerPrivateEnv )

The abstract operation NewPrivateEnvironment takes argument outerPrivateEnv (PrivateEnvironment Record 또는 null) and returns PrivateEnvironment Record. It performs the following steps when called:

  1. names를 새 빈 List로 둔다.
  2. PrivateEnvironment Record { [[OuterPrivateEnvironment]]: outerPrivateEnv, [[Names]]: names } 를 반환한다.

9.2.1.2 ResolvePrivateIdentifier ( privateEnv, identifier )

The abstract operation ResolvePrivateIdentifier takes arguments privateEnv (PrivateEnvironment Record) and identifier (String) and returns Private Name. It performs the following steps when called:

  1. namesprivateEnv.[[Names]]로 둔다.
  2. names의 각 Private Name pn에 대해
    1. pn.[[Description]]identifier이면
      1. pn을 반환한다.
  3. outerPrivateEnvprivateEnv.[[OuterPrivateEnvironment]]로 둔다.
  4. 단언: outerPrivateEnvnull이 아니다.
  5. ResolvePrivateIdentifier(outerPrivateEnv, identifier)를 반환한다.

9.3 Realm들(Realms)

평가되기 전에 모든 ECMAScript 코드는 하나의 realm과 연계되어야 한다. 개념적으로 realm은 일련의 intrinsic 객체, ECMAScript 전역 환경, 그 전역 환경의 범위 내에서 로드된 모든 ECMAScript 코드, 그리고 기타 관련 상태 및 자원으로 구성된다.

realm은 이 명세에서 Table 22에 지정된 필드를 가진 Realm Record로 표현된다:

Table 22: Realm Record 필드(Realm Record Fields)
필드 이름(Field Name) 값(Value) 의미(Meaning)
[[AgentSignifier]] 에이전트 식별자(agent signifier) realm을 소유하는 에이전트
[[Intrinsics]] 필드 이름이 intrinsic key이고 값이 객체인 Record realm에 연계된 코드가 사용하는 intrinsic 값들
[[GlobalObject]] Object realm전역 객체
[[GlobalEnv]] Global Environment Record realm의 전역 환경
[[TemplateMap]] 필드 [[Site]] (TemplateLiteral Parse Node) 및 [[Array]] (Array)를 갖는 Record들의 List

템플릿 객체들은 각 realm별로 그 Realm Record[[TemplateMap]]을 사용하여 정규화(canonicalize)된다. 각 [[Site]] 값은 TemplateLiteral 인 Parse Node이다. 연계된 [[Array]] 값은 태그 함수에 전달되는 해당 템플릿 객체이다.

Note 1
어떤 Parse Node가 도달 불가능(unreachable)이 되면, 대응하는 [[Array]] 또한 도달 불가능해지며, 구현이 그 쌍을 [[TemplateMap]] 리스트에서 제거하더라도 관측 불가능하다.
[[LoadedModules]] LoadedModuleRequest Record들의 List

realm이 import한 명세자(specifier) 문자열에서 해석된 Module Record로의 매핑. 리스트에는 ModuleRequestsEqual(r1, r2)가 true인 서로 다른 Record r1, r2 두 개가 존재하지 않는다.

Note 2
HostLoadImportedModule (16.2.1.10 Note 1)에서 언급했듯이, Realm Record[[LoadedModules]]는 활성 스크립트나 모듈이 없는 문맥에서 import() 표현식을 실행할 때만 사용된다.
[[HostDefined]] 임의(anything) (undefined가 기본값) 호스트Realm Record와 추가 정보를 연계할 필요가 있을 때 사용하기 위한 예약 필드.

9.3.1 InitializeHostDefinedRealm ( )

The abstract operation InitializeHostDefinedRealm takes no arguments and returns unused를 담는 normal completion 또는 throw completion. It performs the following steps when called:

  1. realm을 새로운 Realm Record로 둔다.
  2. CreateIntrinsics(realm)를 수행한다.
  3. realm.[[AgentSignifier]]AgentSignifier()로 설정한다.
  4. realm.[[TemplateMap]]을 새 빈 List로 설정한다.
  5. newContext를 새 실행 컨텍스트로 둔다.
  6. newContext의 Function을 null로 설정한다.
  7. newContextRealmrealm으로 설정한다.
  8. newContext의 ScriptOrModule을 null로 설정한다.
  9. 실행 컨텍스트 스택에 newContext를 push한다; 이제 newContext가 실행 중(running) 실행 컨텍스트다.
  10. 호스트realm전역 객체로서 익조틱(exotic) 객체 사용을 요구한다면
    1. global호스트 정의 방식으로 생성된 그러한 객체로 둔다.
  11. Else,
    1. globalOrdinaryObjectCreate(realm.[[Intrinsics]].[[%Object.prototype%]])로 둔다.
  12. 호스트realm 전역 스코프의 this 바인딩이 전역 객체와 다른 객체를 반환하도록 요구한다면
    1. thisValue호스트 정의 방식으로 생성된 그러한 객체로 둔다.
  13. Else,
    1. thisValueglobal로 둔다.
  14. realm.[[GlobalObject]]global로 설정한다.
  15. realm.[[GlobalEnv]]NewGlobalEnvironment(global, thisValue)로 설정한다.
  16. SetDefaultGlobalBindings(realm)를 수행한다.
  17. 호스트 정의 전역 객체 프로퍼티들을 global에 생성한다.
  18. unused를 반환한다.

9.3.2 CreateIntrinsics ( realmRec )

The abstract operation CreateIntrinsics takes argument realmRec (Realm Record) and returns unused. It performs the following steps when called:

  1. realmRec.[[Intrinsics]]를 새 Record로 설정한다.
  2. realmRec.[[Intrinsics]]의 필드들을 Table 6에 나열된 값으로 설정한다. 필드 이름은 테이블 첫 번째 열의 이름들이다. 각 필드 값은 19부터 28까지의 각 객체 명세에 따라 그 프로퍼티 값으로 완전하고 재귀적으로 채워진 새 객체 값이다. 모든 객체 프로퍼티 값은 새로 생성된 객체 값이다. 내장 함수 객체인 모든 값은 CreateBuiltinFunction(steps, length, name, slots, realmRec, prototype)을 수행하여 생성되는데, 여기서 steps는 이 명세가 제공하는 그 함수의 정의, name은 함수의 초기 "name" 프로퍼티 값, length는 함수의 초기 "length" 프로퍼티 값, slots는 (있다면) 함수의 지정된 내부 슬롯 이름들의 리스트, prototype은 함수 [[Prototype]] 내부 슬롯의 지정된 값이다. intrinsic과 그 프로퍼티 생성은 아직 생성되지 않은 객체에 대한 의존성이 없도록 순서가 정해져야 한다.
  3. AddRestrictedFunctionProperties(realmRec.[[Intrinsics]].[[%Function.prototype%]], realmRec)를 수행한다.
  4. unused를 반환한다.

9.3.3 SetDefaultGlobalBindings ( realmRec )

The abstract operation SetDefaultGlobalBindings takes argument realmRec (Realm Record) and returns unused를 담는 normal completion 또는 throw completion. It performs the following steps when called:

  1. globalrealmRec.[[GlobalObject]]로 둔다.
  2. 19 절에 지정된 전역 객체의 각 프로퍼티에 대해
    1. name을 그 프로퍼티 이름의 String 값으로 둔다.
    2. desc를 그 프로퍼티에 대해 지정된 속성들을 포함하는 완전히 채워진 데이터 프로퍼티 디스크립터로 둔다. 19.2, 19.3, 또는 19.4에 나열된 프로퍼티의 경우 [[Value]] 속성 값은 realmRec의 해당 intrinsic 객체이다.
    3. DefinePropertyOrThrow(global, name, desc)를 수행한다.
  3. unused를 반환한다.

9.4 실행 컨텍스트들(Execution Contexts)

execution context는 ECMAScript 구현이 코드의 런타임 평가를 추적하기 위해 사용하는 명세 장치이다. 어느 시점에도 코드 실행 중인 에이전트당 실제로 코드를 실행하는 실행 컨텍스트는 최대 하나이다. 이는 그 에이전트의 running execution context로 알려져 있다. 이 명세에서 running execution context에 대한 모든 언급은 둘러싼 에이전트의 running execution context를 가리킨다.

execution context stack은 실행 컨텍스트들을 추적하는 데 사용된다. running execution context는 항상 이 스택의 최상단 요소이다. 현재 running execution context에 연계된 실행 가능한 코드로부터 그 실행 컨텍스트와 연계되지 않은 실행 가능한 코드로 제어가 이전될 때마다 새로운 실행 컨텍스트가 생성된다. 새로 생성된 실행 컨텍스트는 스택에 push되며 running execution context가 된다.

실행 컨텍스트는 그 연계된 코드의 실행 진행을 추적하는 데 필요한 구현별 상태를 포함한다. 각 실행 컨텍스트는 최소한 Table 23에 나열된 상태 구성 요소들을 가진다.

Table 23: 모든 실행 컨텍스트의 상태 구성 요소(State Components for All Execution Contexts)
구성 요소(Component) 목적(Purpose)
code evaluation state 이 실행 컨텍스트와 연계된 코드의 평가 수행, 일시중단, 재개에 필요한 모든 상태.
Function 이 실행 컨텍스트가 함수 객체의 코드를 평가 중이면 이 구성 요소 값은 그 함수 객체이고, Script 또는 Module의 코드를 평가 중이면 값은 null.
Realm 연계된 코드가 ECMAScript 자원에 접근하는 데 사용하는 Realm Record.
ScriptOrModule 연계된 코드가 기원한 Module Record 또는 Script Record. 원래 실행 컨텍스트(InitializeHostDefinedRealm에서 생성된)처럼 기원 스크립트나 모듈이 없는 경우 값은 null.

running execution context에 의한 코드 평가는 이 명세에 정의된 여러 지점에서 일시중단(suspend)될 수 있다. 한 번 running execution context가 일시중단되면, 다른 실행 컨텍스트가 running execution context가 되어 자신의 코드를 평가하기 시작할 수 있다. 이후 어느 시점에 일시중단된 실행 컨텍스트가 다시 running execution context가 되어 이전에 일시중단된 지점부터 자신의 코드를 계속 평가할 수 있다. running execution context 상태의 전환은 보통 스택과 같은 후입선출(LIFO) 방식으로 발생하지만, 일부 ECMAScript 기능은 비 LIFO 전환을 요구한다.

running execution contextRealm 구성 요소 값은 current Realm Record라고도 한다. running execution context의 Function 구성 요소 값은 active function object라고도 한다.

ECMAScript 코드 실행 컨텍스트Table 24에 나열된 추가 상태 구성 요소를 가진다.

Table 24: ECMAScript 코드 실행 컨텍스트의 추가 상태 구성 요소(Additional State Components for ECMAScript Code Execution Contexts)
구성 요소(Component) 목적(Purpose)
LexicalEnvironment 이 실행 컨텍스트 내 코드가 수행하는 식별자 참조를 해석하는 데 사용되는 Environment Record를 식별.
VariableEnvironment 이 실행 컨텍스트 내 VariableStatement에 의해 생성된 바인딩을 보유하는 Environment Record를 식별.
PrivateEnvironment 가장 가까운 둘러싸는 클래스의 ClassElement들이 생성한 Private Name들을 보유하는 PrivateEnvironment Record를 식별. 둘러싸는 클래스가 없으면 null.

실행 컨텍스트의 LexicalEnvironment 및 VariableEnvironment 구성 요소는 항상 Environment Record이다.

Generator 평가를 나타내는 실행 컨텍스트는 Table 25에 나열된 추가 상태 구성 요소를 가진다.

Table 25: Generator 실행 컨텍스트의 추가 상태 구성 요소(Additional State Components for Generator Execution Contexts)
구성 요소(Component) 목적(Purpose)
Generator 이 실행 컨텍스트가 평가 중인 Generator.

대부분의 상황에서 이 명세의 알고리즘이 직접 조작하는 것은 running execution context(실행 컨텍스트 스택의 최상단)이다. 따라서 “LexicalEnvironment”, “VariableEnvironment”라는 용어가 한정 없이 사용될 때 그것들은 running execution context의 해당 구성 요소를 의미한다.

실행 컨텍스트는 순수한 명세 메커니즘이며 ECMAScript 구현의 특정한 실체에 대응할 필요가 없다. ECMAScript 코드는 실행 컨텍스트를 직접 접근하거나 관찰할 수 없다.

9.4.1 GetActiveScriptOrModule ( )

The abstract operation GetActiveScriptOrModule takes no arguments and returns Script Record, Module Record, 또는 null. running execution context를 기반으로 실행 중인 스크립트 또는 모듈을 결정하는 데 사용된다. It performs the following steps when called:

  1. 실행 컨텍스트 스택이 비어 있으면 null을 반환한다.
  2. ec를 실행 컨텍스트 스택의 최상단에서 ScriptOrModule 구성 요소가 null이 아닌 실행 컨텍스트로 둔다.
  3. 그러한 실행 컨텍스트가 없으면 null을 반환하고; 그렇지 않으면 ec의 ScriptOrModule을 반환한다.

9.4.2 ResolveBinding ( name [ , env ] )

The abstract operation ResolveBinding takes argument name (String) and optional argument env (Environment Record 또는 undefined) and returns Reference Record를 담는 normal completion 또는 throw completion. name의 바인딩을 결정하는 데 사용된다. env는 검색할 Environment Record를 명시적으로 제공하는 데 사용할 수 있다. It performs the following steps when called:

  1. env가 제공되지 않았거나 envundefined이면
    1. envrunning execution context의 LexicalEnvironment로 설정한다.
  2. 단언: envEnvironment Record이다.
  3. strict를 (평가 중인) 구문 생성 규칙에 대한 IsStrict의 결과로 둔다.
  4. GetIdentifierReference(env, name, strict)를 반환한다.
Note

ResolveBinding의 결과는 항상 [[ReferencedName]] 필드가 nameReference Record이다.

9.4.3 GetThisEnvironment ( )

The abstract operation GetThisEnvironment takes no arguments and returns Environment Record. 현재 this 키워드의 바인딩을 제공하는 Environment Record를 찾는다. It performs the following steps when called:

  1. envrunning execution context의 LexicalEnvironment로 둔다.
  2. 반복,
    1. existsenv.HasThisBinding()으로 둔다.
    2. existstrue이면 env를 반환한다.
    3. outerenv.[[OuterEnv]]로 둔다.
    4. 단언: outernull이 아니다.
    5. envouter로 설정한다.
Note

2 단계의 루프는 환경들의 리스트가 항상 this 바인딩을 가진 전역 환경으로 끝나므로 반드시 종료된다.

9.4.4 ResolveThisBinding ( )

The abstract operation ResolveThisBinding takes no arguments and returns ECMAScript 언어 값을 담는 normal completion 또는 throw completion. running execution context의 LexicalEnvironment를 사용하여 this 키워드의 바인딩을 결정한다. It performs the following steps when called:

  1. envRecGetThisEnvironment()로 둔다.
  2. envRec.GetThisBinding()을 반환한다.

9.4.5 GetNewTarget ( )

The abstract operation GetNewTarget takes no arguments and returns Object 또는 undefined. running execution context의 LexicalEnvironment를 사용하여 NewTarget 값을 결정한다. It performs the following steps when called:

  1. envRecGetThisEnvironment()로 둔다.
  2. 단언: envRec[[NewTarget]] 필드를 가진다.
  3. envRec.[[NewTarget]]을 반환한다.

9.4.6 GetGlobalObject ( )

The abstract operation GetGlobalObject takes no arguments and returns Object. 현재 running execution context가 사용하는 전역 객체를 반환한다. It performs the following steps when called:

  1. currentRealmcurrent Realm Record로 둔다.
  2. currentRealm.[[GlobalObject]]를 반환한다.

9.5 잡과 잡을 대기열에 넣기 위한 호스트 연산(Jobs and Host Operations to Enqueue Jobs)

Job은 파라미터가 없는 추상 클로저(Abstract Closure)로, 다른 ECMAScript 계산이 현재 진행 중이지 않을 때 ECMAScript 계산을 개시한다.

잡은 특정 에이전트 내에서 ECMAScript 호스트 환경에 의해 실행이 스케줄된다. 이 명세는 잡을 스케줄하기 위해 HostEnqueueGenericJob, HostEnqueueFinalizationRegistryCleanupJob, HostEnqueuePromiseJob, HostEnqueueTimeoutJob 호스트 훅을 기술한다. 이 명세의 호스트 훅들은 잡 스케줄링에 추가로 부과되는 제약들에 따라 조직되어 있다. 호스트는 잡을 스케줄하는 추가적인 추상 연산을 정의할 수 있다. 그러한 연산은 Job 추상 클로저와 realm(Realm Record 또는 null)을 인자로 받는다. Realm Record가 제공되면, 그 연산들은 해당 realm을 소유한 에이전트에서 미래의 어느 시점에 그 realm 안에서 잡이 수행되도록 스케줄한다. realm이 대신 null로 제공되면, 그 잡은 ECMAScript 코드를 평가하지 않는다. 구현은 다음 요구 사항을 따라야 한다:

  • 미래의 어떤 시점에, 그 잡이 스케줄된 에이전트에 실행 중인 컨텍스트가 없고 그 에이전트의 실행 컨텍스트 스택이 비어 있을 때, 구현은 반드시:
    1. 호스트 정의 준비 단계를 수행한다.
    2. Invoke Job 추상 클로저를 호출한다.
    3. 호스트 정의 정리 단계를 수행하며, 그 후 실행 컨텍스트 스택은 비어 있어야 한다.
  • 어느 시점에도 하나의 에이전트에서 동시에 평가 중인 Job은 하나만 존재할 수 있다.
  • Job의 평가가 시작되면, 그 에이전트에서 다른 어떤 Job의 평가가 시작되기 전에 완료까지 실행되어야 한다(run to completion).
  • 추상 클로저는 오류 처리를 자체적으로 구현하여 정상 완료(normal completion)를 반환해야 한다.
Note 1
호스트 환경은 스케줄링 측면에서 모든 Job을 동일하게 취급할 필요가 없다. 예를 들어, 웹 브라우저와 Node.js는 Promise 처리 잡을 다른 작업보다 더 높은 우선순위로 다룬다; 향후 기능은 그렇게 높은 우선순위로 다루어지지 않는 잡을 추가할 수 있다.

어떤 특정 시점에, 다음 모든 조건이 참이라면 scriptOrModule(Script Record, Module Record, 또는 null)은 active script or module(활성 스크립트 또는 모듈)이다:

  • GetActiveScriptOrModule() 결과가 scriptOrModule이다.
  • scriptOrModule이 Script Record 또는 Module Record라면, ec를 실행 컨텍스트 스택의 최상단에서 ScriptOrModule 구성 요소가 scriptOrModule인 실행 컨텍스트로 둔다. ecRealm 구성 요소는 scriptOrModule.[[Realm]]이다.

어떤 특정 시점에, 다음 모든 조건이 참이면 실행은 ECMAScript 코드를 평가할 준비가 되었다(prepared to evaluate ECMAScript code)고 한다:

  • 실행 컨텍스트 스택이 비어 있지 않다.
  • 실행 컨텍스트 스택 최상단 실행 컨텍스트의 Realm 구성 요소가 Realm Record이다.
Note 2

호스트 환경은 실행 컨텍스트들을 실행 컨텍스트 스택에 push하여 코드를 평가할 준비를 시킬 수 있다. 구체적인 단계는 구현 정의이다.

Realm의 구체적 선택은 호스트 환경에 달려 있다. 이 초기 실행 컨텍스트와 Realm은 어떤 콜백 함수가 호출되기 전까지만 사용된다. Promise 핸들러 같은 잡 관련 콜백 함수가 호출되면, 그 호출은 자체 실행 컨텍스트와 Realm을 push한다.

특정 종류의 Job은 추가적인 적합성 요구 사항을 가진다.

9.5.1 JobCallback 레코드(JobCallback Records)

JobCallback Record함수 객체호스트 정의 값을 저장하기 위해 사용되는 Record 값이다. 호스트가 대기열에 넣은 Job을 통해 호출되는 함수 객체는 추가적인 호스트 정의 컨텍스트를 가질 수 있다. 이 상태를 전파하기 위해, Job 추상 클로저는 함수 객체를 직접 캡처하고 호출하지 않아야 한다. 대신 HostMakeJobCallbackHostCallJobCallback을 사용한다.

Note

예를 들어 WHATWG HTML 명세(https://html.spec.whatwg.org/)는 Promise 콜백에 대해 incumbent settings object를 전파하기 위해 호스트 정의 값을 사용한다.

JobCallback Record는 Table 26에 나열된 필드를 가진다.

Table 26: JobCallback Record 필드(JobCallback Record Fields)
필드 이름(Field Name) 값(Value) 의미(Meaning)
[[Callback]] 함수 객체 Job이 호출될 때 호출할 함수.
[[HostDefined]] anything (기본값은 empty) 호스트 사용을 위한 예약 필드.

9.5.2 HostMakeJobCallback ( callback )

The host-defined abstract operation HostMakeJobCallback takes argument callback (함수 객체) and returns JobCallback Record.

HostMakeJobCallback 구현은 다음 요구 사항을 따라야 한다:

HostMakeJobCallback의 기본 구현은 호출될 때 다음 단계를 수행한다:

  1. JobCallback Record { [[Callback]]: callback, [[HostDefined]]: empty }를 반환한다.

웹 브라우저가 아닌 ECMAScript 호스트는 HostMakeJobCallback의 기본 구현을 사용해야 한다.

Note

이는 콜백이 궁극적으로 스케줄되고 실행되도록 책임지는 함수에 콜백이 전달되는 시점에 호출된다. 예를 들어, promise.then(thenAction)은 반응 Job이 스케줄되는 시점이 아니라 Promise.prototype.then을 호출하는 시점에 thenAction에 대해 MakeJobCallback을 호출한다.

9.5.3 HostCallJobCallback ( jobCallback, V, argumentsList )

The host-defined abstract operation HostCallJobCallback takes arguments jobCallback (JobCallback Record), V (ECMAScript 언어 값), and argumentsList (ECMAScript 언어 값들의 List) and returns ECMAScript 언어 값을 담는 normal completion 또는 throw completion.

HostCallJobCallback 구현은 다음 요구 사항을 따라야 한다:

  • Call(jobCallback.[[Callback]], V, argumentsList)의 결과를 수행하고 반환해야 한다.
Note

이 요구 사항은 호스트가 이 명세에서 정의된 함수 객체[[Call]] 동작을 변경할 수 없음을 의미한다.

HostCallJobCallback의 기본 구현은 호출될 때 다음 단계를 수행한다:

  1. 단언: IsCallable(jobCallback.[[Callback]])가 true이다.
  2. Call(jobCallback.[[Callback]], V, argumentsList)를 반환한다.

웹 브라우저가 아닌 ECMAScript 호스트는 HostCallJobCallback의 기본 구현을 사용해야 한다.

9.5.4 HostEnqueueGenericJob ( job, realm )

The host-defined abstract operation HostEnqueueGenericJob takes arguments job (Job 추상 클로저) and realm (Realm Record) and returns unused. realm.[[AgentSignifier]]로 표시된 에이전트에서 realm 내에 job을 미래의 어느 시점에 수행하도록 스케줄한다. 이 알고리즘과 함께 사용되는 추상 클로저는 우선순위나 순서 같은 추가 제약 없이 스케줄되는 것을 의도한다.

HostEnqueueGenericJob 구현은 9.5의 요구 사항을 따라야 한다.

9.5.5 HostEnqueuePromiseJob ( job, realm )

The host-defined abstract operation HostEnqueuePromiseJob takes arguments job (Job 추상 클로저) and realm (Realm Record 또는 null) and returns unused. job을 미래의 어느 시점에 수행하도록 스케줄한다. 이 알고리즘과 함께 사용되는 추상 클로저는 Promise 처리와 관련이 있거나 그렇지 않더라도 Promise 처리 연산과 동일한 우선순위로 스케줄되는 것을 의도한다.

HostEnqueuePromiseJob 구현은 9.5의 요구 사항과 아래 사항을 따라야 한다:

  • realmnull이 아니면, job이 호출될 때마다 구현은 job 호출 시점에 실행이 ECMAScript 코드를 평가할 준비가 되도록 구현 정의 단계를 수행해야 한다.
  • HostEnqueuePromiseJob이 호출되는 시점에 scriptOrModuleGetActiveScriptOrModule()으로 둔다. realmnull이 아니면, job이 호출될 때마다 구현은 scriptOrModulejob 호출 시점에 활성 스크립트 또는 모듈이 되도록 구현 정의 단계를 수행해야 한다.
  • 잡은 그들을 스케줄한 HostEnqueuePromiseJob 호출과 동일한 순서로 실행되어야 한다.
Note

NewPromiseResolveThenableJob이 반환한 잡의 realm은 보통 then 함수 객체에 대해 GetFunctionRealm을 호출한 결과이다. NewPromiseReactionJob이 반환한 잡의 realm은 핸들러가 undefined가 아니면 보통 핸들러에 대해 GetFunctionRealm을 호출한 결과이다. 핸들러가 undefined이면 realmnull이다. 두 종류의 잡 모두에서 GetFunctionRealm이 비정상적으로 완료(예: 철회된 Proxy에 대해 호출)되면 realmGetFunctionRealm 호출 시점의 현재 Realm Record이다. realmnull이면 어떤 사용자 ECMAScript 코드도 평가되지 않고 새로운 ECMAScript 객체(예: Error 객체)도 생성되지 않는다. WHATWG HTML 명세(https://html.spec.whatwg.org/)는 예를 들어 realm을 사용하여 스크립트 실행 가능 여부와 entry 개념을 확인한다.

9.5.6 HostEnqueueTimeoutJob ( timeoutJob, realm, milliseconds )

The host-defined abstract operation HostEnqueueTimeoutJob takes arguments timeoutJob (Job 추상 클로저), realm (Realm Record), and milliseconds (음이 아닌 유한 Number) and returns unused. realm.[[AgentSignifier]]로 표시된 에이전트에서 realm 내에 timeoutJob을 최소 milliseconds 밀리초 후에 수행되도록 스케줄한다.

HostEnqueueTimeoutJob 구현은 9.5의 요구 사항을 따라야 한다.

9.6 에이전트(Agents)

agent는 ECMAScript 실행 컨텍스트 집합, 실행 컨텍스트 스택, 실행 중 실행 컨텍스트(running execution context), Agent Record, 그리고 executing thread로 구성된다. executing thread를 제외한 구성 요소들은 오직 그 에이전트에만 속한다.

에이전트의 executing thread는 다른 에이전트와 독립적으로 그 에이전트의 실행 컨텍스트들에 대해 알고리즘 단계를 실행한다. 단, 여러 에이전트가 하나의 executing thread를 공유할 수 있는데, 그 공유하는 에이전트 중 어느 것도 Agent Record[[CanBlock]] 필드가 true이면 안 된다.

Note 1

예를 들어 일부 웹 브라우저는 서로 관계없는 여러 탭이 단일 executing thread를 공유한다.

에이전트의 executing thread가 알고리즘 단계를 실행하는 동안, 그 에이전트는 그 단계들의 surrounding agent(둘러싼 에이전트)이다. 그 단계들은 둘러싼 에이전트를 사용하여 에이전트가 보유한 명세 수준 실행 객체—실행 중 실행 컨텍스트, 실행 컨텍스트 스택, Agent Record의 필드—에 접근한다.

agent signifier(에이전트 식별자)는 에이전트를 식별하기 위해 사용되는 전역적으로 고유한 불투명 값이다.

Table 27: Agent Record 필드(Agent Record Fields)
필드 이름(Field Name) 값(Value) 의미(Meaning)
[[LittleEndian]] Boolean 알고리즘 GetValueFromBufferSetValueInBuffer가 필요할 때 isLittleEndian 파라미터에 대해 계산되는 기본 값. 선택은 구현 정의이며 구현에 가장 효율적인 대안을 사용해야 한다. 한 번 관측된 후에는 변경될 수 없다.
[[CanBlock]] Boolean 에이전트가 블록(block)될 수 있는지 여부를 결정.
[[Signifier]] agent signifier 에이전트를 그 에이전트 클러스터 내에서 고유하게 식별.
[[IsLockFree1]] Boolean 1-byte 값에 대한 원자적 연산이 lock-free이면 true, 아니면 false.
[[IsLockFree2]] Boolean 2-byte 값에 대한 원자적 연산이 lock-free이면 true, 아니면 false.
[[IsLockFree8]] Boolean 8-byte 값에 대한 원자적 연산이 lock-free이면 true, 아니면 false.
[[CandidateExecution]] candidate execution Record 메모리 모델 참조.
[[KeptAlive]] Objects 또는 Symbols 중 하나의 List 초기에는 새 빈 List로, 현재 Job 끝까지 유지(kept alive)되어야 하는 객체 및/또는 심볼들의 목록.
[[ModuleAsyncEvaluationCount]] 정수 초기값 0. 비동기 또는 비동기 의존성을 가진 모듈들의 [[AsyncEvaluationOrder]] 필드에 고유 증가값을 할당하는 데 사용.

[[Signifier]], [[IsLockFree1]], [[IsLockFree2]]의 값은 에이전트 클러스터의 어떤 에이전트에 의해 관측된 후에는 변경될 수 없다.

Note 2

[[IsLockFree1]][[IsLockFree2]]의 값은 반드시 하드웨어에 의해 결정되는 것은 아니며, 시간에 따라 또는 ECMAScript 구현 간에 달라질 수 있는 구현 선택을 반영할 수도 있다.

[[IsLockFree4]] 필드는 없다: 4-byte 원자 연산은 항상 lock-free이다.

실제로 어떤 종류의 락을 사용해 원자 연산이 구현된다면 그 연산은 lock-free가 아니다. Lock-free는 wait-free를 의미하지 않는다: lock-free 원자 연산을 완료하는 데 필요한 기계 단계 수에 상한은 없다.

크기 n의 원자 접근이 lock-free라고 해서 크기 n의 비원자(non-atomic) 접근의 (인지된) 원자성에 대해 아무것도 의미하지 않는다. 특히 비원자 접근은 여전히 여러 개의 별도 메모리 접근 시퀀스로 수행될 수 있다. 세부 사항은 ReadSharedMemoryWriteSharedMemory 참조.

Note 3

에이전트는 명세 메커니즘이며 ECMAScript 구현의 특정 실체에 대응할 필요가 없다.

9.6.1 AgentSignifier ( )

The abstract operation AgentSignifier takes no arguments and returns agent signifier. It performs the following steps when called:

  1. AR를 둘러싼 에이전트의 Agent Record로 둔다.
  2. AR.[[Signifier]]를 반환한다.

9.6.2 AgentCanSuspend ( )

The abstract operation AgentCanSuspend takes no arguments and returns Boolean. It performs the following steps when called:

  1. AR를 둘러싼 에이전트의 Agent Record로 둔다.
  2. AR.[[CanBlock]]를 반환한다.
Note

일부 환경에서는 특정 에이전트가 일시중단(suspend)되는 것이 타당하지 않을 수 있다. 예를 들어 웹 브라우저 환경에서는 문서의 메인 이벤트 처리 스레드를 일시중단하지 않는 것이 합리적일 수 있지만 워커의 이벤트 처리 스레드는 가능하게 할 수 있다.

9.6.3 IncrementModuleAsyncEvaluationCount ( )

The abstract operation IncrementModuleAsyncEvaluationCount takes no arguments and returns 정수. It performs the following steps when called:

  1. AR를 둘러싼 에이전트의 Agent Record로 둔다.
  2. countAR.[[ModuleAsyncEvaluationCount]]로 둔다.
  3. AR.[[ModuleAsyncEvaluationCount]]count + 1로 설정한다.
  4. count를 반환한다.
Note

이 값은 보류 중(pending) 모듈 사이의 상대적 평가 순서를 추적하기 위해서만 사용된다. 보류 중인 모듈이 없다면 구현은 관측 불가능하게 [[ModuleAsyncEvaluationCount]]를 0으로 재설정할 수 있다.

9.7 에이전트 클러스터(Agent Clusters)

agent cluster는 공유 메모리를 조작함으로써 통신할 수 있는 에이전트들의 최대 집합이다.

Note 1

서로 다른 에이전트 내의 프로그램들은 명시되지 않은 수단으로 메모리를 공유할 수 있다. 최소한 SharedArrayBuffers의 백업 메모리는 클러스터의 에이전트들 간에 공유될 수 있다.

메시지 전달로 통신할 수 있지만 메모리를 공유할 수 없는 에이전트들도 있을 수 있으며, 그들은 절대 같은 에이전트 클러스터에 속하지 않는다.

모든 에이전트는 정확히 하나의 에이전트 클러스터에 속한다.

Note 2

클러스터의 에이전트들이 어떤 특정 시점에 모두 살아 있을 필요는 없다. 에이전트 A가 다른 에이전트 B를 생성하고, 그 후 A가 종료되고 B가 에이전트 C를 생성한다면, AB와 일부 메모리를 공유할 수 있었고 BC와 일부 메모리를 공유할 수 있었다면 세 에이전트는 같은 클러스터에 속한다.

클러스터 내 모든 에이전트는 각각의 Agent Record에서 [[LittleEndian]] 필드에 대해 동일한 값을 가져야 한다.

Note 3

에이전트 클러스터 내의 에이전트들이 [[LittleEndian]] 값이 서로 다르다면, 다중 바이트 데이터에 대해 공유 메모리를 사용하는 것이 어려워진다.

클러스터 내 모든 에이전트는 [[IsLockFree1]] 필드에 대해 동일한 값을 가져야 하며 [[IsLockFree2]] 필드도 마찬가지이다.

클러스터 내 모든 에이전트는 각각의 Agent Record에서 [[Signifier]] 필드에 대해 서로 다른 값을 가져야 한다.

임베딩은 에이전트의 지식이나 협력 없이 에이전트를 비활성화(진행 중단)하거나 활성화(진행 재개)할 수 있다. 임베딩이 그렇게 한다면, 클러스터 내 일부 에이전트만 활성 상태로 남기고 다른 에이전트들을 무기한 비활성화된 상태로 두어서는 안 된다.

Note 4

위 제한의 목적은 어떤 에이전트가 다른 에이전트가 비활성화되었기 때문에 데드락 또는 기아(starvation)에 빠지는 상황을 피하기 위함이다. 예를 들어, 창 윈도우의 어떤 문서에도 독립적인 수명(lifetime)을 가진 HTML 공유 워커가 그런 독립 문서의 전용(dedicated) 워커와 메모리를 공유할 수 있고, 그 후 문서와 전용 워커가 (예: 문서가 히스토리에 들어가면서) 비활성화되었으며 전용 워커가 락을 보유한 상태이고, 공유 워커가 락을 획득하려 하면 공유 워커는 전용 워커가 다시 활성화될 때까지(혹은 영원히) 블록된다. 그동안 다른 윈도우에서 공유 워커에 접근하려는 다른 워커들은 기아 상태에 빠진다.

이 제한의 함의는 임베딩 내에서 동일한 suspend/wake 집합에 속하지 않는 에이전트들 사이에서는 메모리를 공유할 수 없다는 것이다.

임베딩은 에이전트 클러스터의 다른 에이전트의 사전 지식이나 협력 없이 에이전트를 종료할 수 있다. 에이전트가 자체 또는 클러스터 내 다른 에이전트의 프로그래밍 동작이 아니라 클러스터 외부의 힘에 의해 종료된다면, 임베딩은 두 전략 중 하나를 선택해야 한다: 클러스터의 모든 에이전트를 종료하거나, 클러스터의 에이전트들이 협력하여 종료를 감지할 수 있도록 신뢰 가능한 API를 제공하되, 종료 데이터는 종료된 에이전트를 식별하기에 충분한 정보를 포함해야 한다.

Note 5

그러한 종료 유형의 예로는: 별도 프로세스에서 실행 중인 에이전트를 운영체제나 사용자가 종료하는 경우; per-agent 자원 계정이 에이전트가 runaway임을 나타낼 때 같은 프로세스에서 다른 에이전트와 함께 실행 중인 에이전트를 임베딩 자체가 종료하는 경우 등이 있다.

다음 명세 값 각각과 그들로부터 추이적으로 도달 가능한 값들은 정확히 하나의 에이전트 클러스터에 속한다.

클러스터 내 어떤 에이전트가 ECMAScript 코드를 평가하기 이전에, 클러스터의 모든 에이전트에 대한 Agent Record[[CandidateExecution]] 필드는 초기 candidate execution으로 설정된다. 초기 candidate execution은 비어 있는 candidate execution으로, 그 [[EventsRecords]] 필드는 각 에이전트에 대해 [[AgentSignifier]] 필드가 그 에이전트의 agent signifier이고 [[EventList]][[AgentSynchronizesWith]] 필드가 빈 ListAgent Events Record를 포함하는 List이다.

Note 6

에이전트 클러스터의 모든 에이전트는 Agent Record[[CandidateExecution]] 필드에서 동일한 candidate execution을 공유한다. candidate execution은 메모리 모델에서 사용되는 명세 메커니즘이다.

Note 7

에이전트 클러스터는 명세 메커니즘이며 ECMAScript 구현의 특정 실체에 대응할 필요가 없다.

9.8 Forward Progress

에이전트가 forward progress를 만든다(make forward progress)는 것은 이 명세에 따라 평가 단계(evaluation step)를 수행하는 것이다.

에이전트의 실행 중 실행 컨텍스트가 외부 이벤트를 동기적으로 무기한 기다릴 때, 그 에이전트는 blocked가 된다. Agent Record[[CanBlock]] 필드가 true인 에이전트만 이런 의미에서 blocked 상태가 될 수 있다. unblocked 에이전트는 blocked가 아닌 에이전트이다.

구현은 다음을 보장해야 한다:

  • 전용 executing thread를 가진 모든 unblocked 에이전트는 결국 forward progress를 만든다.
  • executing thread를 공유하는 에이전트 집합에서는 하나의 에이전트가 결국 forward progress를 만든다.
  • 에이전트는 차단(blocking)을 제공하는 명시적 API를 통한 경우를 제외하고 다른 에이전트를 blocked 상태로 만들지 않는다.
Note

이는 메모리 모델의 liveness 보장과 함께 모든 seq-cst 쓰기가 결국 모든 에이전트에 관측 가능해짐을 보장한다.

9.9 WeakRef 및 FinalizationRegistry 대상 처리 모델(Processing Model of WeakRef and FinalizationRegistry Targets)

9.9.1 목표(Objectives)

이 명세는 어떤 객체나 심볼이 가비지 컬렉션될 것이라는 보장을 제공하지 않는다. live가 아닌 객체나 심볼은 긴 시간이 지난 후 해제되거나 전혀 해제되지 않을 수 있다. 이런 이유로 본 명세는 가비지 컬렉션에 의해 트리거되는 동작을 설명할 때 "may"라는 용어를 사용한다.

WeakRefFinalizationRegistry의 의미론은 특정 시점에 발생하는 두 연산에 기반한다:

  • WeakRef.prototype.deref가 호출될 때, ( undefined 가 반환되지 않는 경우) 참조 대상(referent)은 이후의 동기적 접근에서 동일한 값을 반환할 수 있도록 살아 있게 유지된다. 이 목록(list)은 ClearKeptObjects 추상 연산을 사용해 동기 작업이 완료될 때 리셋된다.
  • FinalizationRegistry에 등록된 객체나 심볼이 도달 불가능(unreachable)이 되면, FinalizationRegistry의 cleanup 콜백 호출이 동기 ECMAScript 실행이 완료된 후 언젠가 수행될 수 있다. FinalizationRegistry 정리는 CleanupFinalizationRegistry 추상 연산으로 수행된다.

이 두 동작(ClearKeptObjects 또는 CleanupFinalizationRegistry)은 동기 ECMAScript 실행을 중단(interrupt)해서는 안 된다. 호스트는 더 긴 동기 ECMAScript 실행 구간을 구성할 수 있으므로, 이 명세는 ClearKeptObjectsCleanupFinalizationRegistry의 스케줄링을 호스트 환경에 위임한다.

일부 ECMAScript 구현에는 ECMAScript가 유휴(idle) 상태일 때를 포함해 백그라운드로 실행되는 가비지 컬렉터 구현이 포함되어 있다. 호스트 환경CleanupFinalizationRegistry를 스케줄하도록 하면, 구현이 파이널라이저 작업을 실행하기 위해 ECMAScript 실행을 재개하여 유지 중인 값을 해제함으로써 전체 메모리 사용량을 줄일 수 있다.

9.9.2 Liveness

객체 및/또는 심볼의 집합 S에 대해 hypothetical WeakRef-oblivious(가설적 WeakRef-무관) 실행이란, S의 요소인 참조 대상을 가진 WeakRefWeakRefDeref 추상 연산이 항상 undefined를 반환하는 실행을 말한다.

Note 1
WeakRef-obliviousness와 liveness는 두 개념을 함께 포착한다. 첫째, WeakRef 자체는 그 참조 대상을 살아 있게 유지하지 않는다. 둘째, liveness에서의 사이클이 값이 live임을 의미하지는 않는다. 구체적으로, v의 liveness 결정이 WeakRef referent r의 liveness 결정에 의존한다면, r의 liveness는 v의 liveness를 가정할 수 없는데, 이는 순환 논리이기 때문이다.
Note 2
WeakRef-obliviousness는 사이클을 고려하기 위해 개별 값이 아닌 객체 또는 심볼 집합에 대해 정의된다. 개별 값에 대해 정의된다면, 사이클 내 WeakRef referent는 사이클 내 다른 WeakRef referent를 통해서만 그 정체성이 관측되더라도 live로 간주될 것이다.
Note 3
구어적으로는, 어떤 개별 객체나 심볼이 속한 모든 집합이 live이면 그 객체나 심볼을 live라고 말한다.

평가 도중 어느 시점에서든, 객체 및/또는 심볼 집합 S가 아래 조건 중 하나를 만족하면 live로 간주한다:

  • S의 어떤 요소라도 어떤 에이전트의 [[KeptAlive]] List에 포함된다.
  • S에 대한 어떤 유효한 미래의 가설적 WeakRef-oblivious 실행이 S 내 값의 정체성을 관측한다.
Note 4
두 번째 조건은 값의 정체성이 WeakRef 이외의 수단으로 관측 가능하다면 그 값이 live라는 직관을 포착하려는 것이다. 값의 정체성은 엄격 동등성 비교를 관측하거나 Map의 키로 사용되는 값을 관측함으로써 관측될 수 있다.
Note 5

필드, 내부 슬롯, 프로퍼티 내 객체 또는 심볼의 존재는 그 값이 live임을 의미하지 않는다. 예를 들어 해당 값이 프로그램에 다시 전달되지 않는다면 관측될 수 없다.

이는 WeakMap의 키, WeakSet의 멤버, 그리고 FinalizationRegistry Cell record의 [[WeakRefTarget]][[UnregisterToken]] 필드에 해당한다.

위 정의는 WeakMap에서 어떤 키가 live가 아니면 그에 대응하는 값도 반드시 live일 필요는 없음을 의미한다.

Note 6
Liveness는 엔진이 비워서는 안 되는 WeakRef에 대해 보장해야 하는 하한(lower bound)이다. 여기 정의된 Liveness는 결정 불가능(undecidable)하다. 실제로 엔진은 도달 가능성 같은 보수적 근사(approximation)를 사용한다. 구현 재량의 폭이 크다.

9.9.3 Execution

어느 시점에서든 객체 및/또는 심볼 집합 Slive가 아니라면, ECMAScript 구현은 다음 단계를 원자적으로 수행할 수 있다:

  1. S의 각 요소 value에 대해
    1. ref.[[WeakRefTarget]]value인 각 WeakRef ref에 대해
      1. ref.[[WeakRefTarget]]empty로 설정한다.
    2. fg.[[Cells]][[WeakRefTarget]]valueRecord cell을 포함하는 각 FinalizationRegistry fg에 대해
      1. cell.[[WeakRefTarget]]empty로 설정한다.
      2. 선택적으로 HostEnqueueFinalizationRegistryCleanupJob(fg)를 수행한다.
    3. map.[[WeakMapData]][[Key]]valueRecord r을 포함하는 각 WeakMap map에 대해
      1. r.[[Key]]empty로 설정한다.
      2. r.[[Value]]empty로 설정한다.
    4. set.[[WeakSetData]]value를 포함하는 각 WeakSet set에 대해
      1. 값이 valueset.[[WeakSetData]]의 요소를 값이 empty인 요소로 교체한다.
Note 1

Liveness 정의와 함께, 본 절은 구현이 WeakRef에 관해 적용할 수 있는 최적화들을 규정한다.

객체의 정체성을 관측하지 않고 객체에 접근하는 것이 가능하다. 정체성이 관측되지 않는, escape하지 않는 객체의 프로퍼티에 대해 dead variable elimination, scalar replacement 같은 최적화는 허용된다. 그러한 최적화는 해당 객체를 가리키는 WeakRef들을 관측 가능하게 비울 수 있다.

반면 객체의 정체성이 관측 가능하고 그 객체가 WeakRef[[WeakRefTarget]] 내부 슬롯에 있다면, WeakRef를 관측 가능하게 비워 버리는 rematerialization 같은 최적화는 금지된다.

HostEnqueueFinalizationRegistryCleanupJob 호출이 선택적이므로, FinalizationRegistry에 등록된 객체는 반드시 그 FinalizationRegistrylive로 유지하지 않는다. 구현은 FinalizationRegistry 자체가 dead가 되었거나 애플리케이션이 종료 중인 경우 등 어떤 이유로든 FinalizationRegistry 콜백을 생략할 수 있다.

Note 2

구현은 live가 아닌 객체나 심볼의 최대 집합에 대해 WeakRef를 반드시 비울 필요는 없다.

구현이 WeakRef를 비울 live가 아닌 집합 S를 선택한다면, 이 정의는 S 내 모든 값에 대한 WeakRef를 동시에 비우도록 요구한다. 즉, 값 v를 가리키는 WeakRef 하나를 비우면서, 비워지지 않았다면 v의 값을 관측할 수도 있는 다른 WeakRef를 비우지 않은 채 두는 것은 적합(conformant)하지 않다.

9.9.4 호스트 훅(Host Hooks)

9.9.4.1 HostEnqueueFinalizationRegistryCleanupJob ( finalizationRegistry )

The host-defined abstract operation HostEnqueueFinalizationRegistryCleanupJob takes argument finalizationRegistry (FinalizationRegistry) and returns unused.

finalizationRegistry를 캡처하고 호출 시 다음 단계를 수행하는, 파라미터 없는 새 Job 추상 클로저 cleanupJob을 둔다:

  1. cleanupResultCompletion(CleanupFinalizationRegistry(finalizationRegistry))로 둔다.
  2. cleanupResultabrupt completion이면 오류 보고를 위한 호스트 정의 단계를 수행한다.
  3. unused를 반환한다.

HostEnqueueFinalizationRegistryCleanupJob 구현은 가능하다면 미래의 어느 시점에 cleanupJob이 수행되도록 스케줄한다. 또한 9.5의 요구 사항을 따라야 한다.

9.10 ClearKeptObjects ( )

The abstract operation ClearKeptObjects takes no arguments and returns unused. ECMAScript 구현은 동기적인 ECMAScript 실행 시퀀스가 완료될 때 ClearKeptObjects를 호출하는 것이 기대된다. It performs the following steps when called:

  1. agentRecord를 둘러싼 에이전트의 Agent Record로 둔다.
  2. agentRecord.[[KeptAlive]]를 새 빈 List로 설정한다.
  3. unused를 반환한다.

9.11 AddToKeptObjects ( value )

The abstract operation AddToKeptObjects takes argument value (an Object or a Symbol) and returns unused. It performs the following steps when called:

  1. agentRecord를 둘러싼 에이전트의 Agent Record로 둔다.
  2. agentRecord.[[KeptAlive]]value를 추가(Append)한다.
  3. unused를 반환한다.
Note
추상 연산 AddToKeptObjects가 어떤 대상 객체나 심볼과 함께 호출되면, ClearKeptObjects가 호출될 때까지 그 대상을 강하게 참조하는 목록에 대상을 추가한다.

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. 단언: finalizationRegistry[[Cells]][[CleanupCallback]] 내부 슬롯을 가진다.
  2. callbackfinalizationRegistry.[[CleanupCallback]]로 둔다.
  3. finalizationRegistry.[[Cells]][[WeakRefTarget]]emptyRecord cell을 포함하는 동안, 구현은 다음 단계를 수행할 수 있다:
    1. 그러한 cell 중 임의의 하나를 선택한다.
    2. finalizationRegistry.[[Cells]]에서 cell을 제거한다.
    3. HostCallJobCallback(callback, undefined, « cell.[[HeldValue]] »)를 수행한다.
  4. unused를 반환한다.

9.13 CanBeHeldWeakly ( v )

The abstract operation CanBeHeldWeakly takes argument v (an ECMAScript language value) and returns a Boolean. v가 약한 참조(weak reference)에 사용하기에 적합한 경우에만 true를 반환한다. 약한 참조에 사용하기에 적합한 값만이 WeakMap의 키, WeakSet의 요소, WeakRef의 target, 또는 FinalizationRegistry의 target들 중 하나가 될 수 있다. It performs the following steps when called:

  1. v가 Object이면 true를 반환한다.
  2. v가 Symbol이고 KeyForSymbol(v)이 undefined이면 true를 반환한다.
  3. false를 반환한다.
Note

언어 정체성(language identity)이 없는 언어 값은 사전 참조 없이도 나타날 수 있으며 약한 참조로 사용하기에 부적합하다. Symbol.for로 생성된 Symbol 값은 다른 Symbol 값과 달리 언어 정체성이 없으므로 약한 참조로 사용하기에 부적합하다. Well-known symbols는 수집되지 않을 가능성이 높지만, 그 수가 제한되어 있고 다양한 구현 방식으로 관리 가능하므로 약한 참조로 사용하기에 적합한 것으로 간주된다. 그러나 live한 WeakMap 안의 well-known symbol에 연관된 어떤 값도 수집되지 않아 메모리 자원이 “누수”될 가능성이 있다.

10 일반(Ordinary) 및 이그조틱(Exotic) 객체 동작

10.1 일반 객체의 내부 메서드와 내부 슬롯(Ordinary Object Internal Methods and Internal Slots)

모든 일반 객체[[Prototype]]이라 불리는 내부 슬롯을 가진다. 이 내부 슬롯의 값은 null 혹은 객체이며 상속을 구현하는 데 사용된다. 일반 객체 O 에 속성 P 가 없지만 그 객체의 [[Prototype]] 객체에는 존재한다고 가정하자. P[[Prototype]] 객체의 데이터 프로퍼티를 가리키면 O 는 get 접근에 대해 그것을 상속하여 P 가 마치 O 의 자체 프로퍼티인 것처럼 동작한다. P[[Prototype]] 객체의 쓰기 가능한(writable) 데이터 프로퍼티를 가리키면 O 에서 P 에 대한 set 접근은 O 에 이름이 P 인 새로운 데이터 프로퍼티를 생성한다. P[[Prototype]] 객체의 쓰기 불가능한(non-writable) 데이터 프로퍼티를 가리키면 O 에서 P 에 대한 set 접근은 실패한다. P[[Prototype]] 객체의 접근자(accessor) 프로퍼티를 가리키면 그 접근자는 get 과 set 둘 다에 대해 O 에 상속된다.

모든 일반 객체는 Boolean 값을 갖는 [[Extensible]] 내부 슬롯을 가지며 이는 6.1.7.3 에 명시된 확장성 관련 내부 메서드 불변식을 충족하는 데 사용된다. 즉, 객체의 [[Extensible]] 내부 슬롯 값이 false 로 설정되면 더 이상 그 객체에 새로운 프로퍼티를 추가하거나 객체의 [[Prototype]] 내부 슬롯 값을 수정하거나 이후 [[Extensible]] 값을 true 로 되돌릴 수 없다.

이하의 알고리즘 설명에서 O일반 객체, P프로퍼티 키 값, V 는 임의의 ECMAScript 언어 값, Desc 는 프로퍼티 디스크립터(Property Descriptor) 레코드라고 가정한다.

일반 객체 내부 메서드는 동일하거나 유사한 이름의 추상 연산에 위임한다. 그러한 추상 연산이 또 다른 내부 메서드에 의존하는 경우, 동일 이름의 추상 연산을 직접 호출하지 않고 O 에 그 내부 메서드를 호출한다. 이러한 의미론은 일반 객체 내부 메서드가 이그조틱 객체에 적용될 때 해당 이그조틱 객체가 재정의한 내부 메서드가 호출되도록 보장한다.

10.1.1 [[GetPrototypeOf]] ( )

The [[GetPrototypeOf]] internal method of 일반 객체 O takes no arguments and returns 객체 또는 null 을 담는 normal completion. It performs the following steps when called:

  1. OrdinaryGetPrototypeOf(O) 를 반환한다.

10.1.1.1 OrdinaryGetPrototypeOf ( O )

The abstract operation OrdinaryGetPrototypeOf takes argument O (an Object) and returns an Object or null. It performs the following steps when called:

  1. O.[[Prototype]] 을 반환한다.

10.1.2 [[SetPrototypeOf]] ( V )

The [[SetPrototypeOf]] internal method of 일반 객체 O takes argument V (an Object or null) and returns Boolean 을 담는 normal completion. It performs the following steps when called:

  1. OrdinarySetPrototypeOf(O, V) 를 반환한다.

10.1.2.1 OrdinarySetPrototypeOf ( O, V )

The abstract operation OrdinarySetPrototypeOf takes arguments O (an Object) and V (an Object or null) and returns a Boolean. It performs the following steps when called:

  1. currentO.[[Prototype]] 로 둔다.
  2. SameValue(V, current) 가 true 이면 true 를 반환한다.
  3. extensibleO.[[Extensible]] 로 둔다.
  4. extensiblefalse 이면 false 를 반환한다.
  5. pV 로 둔다.
  6. donefalse 로 둔다.
  7. donefalse 인 동안 반복한다,
    1. pnull 이면
      1. donetrue 로 설정한다.
    2. 아니고 SameValue(p, O) 가 true 이면
      1. false 를 반환한다.
    3. 그 밖의 경우,
      1. p.[[GetPrototypeOf]]10.1.1 에 정의된 일반 객체 내부 메서드가 아니면 donetrue 로 설정한다.
      2. 아니면 pp.[[Prototype]] 로 설정한다.
  8. O.[[Prototype]]V 로 설정한다.
  9. true 를 반환한다.
Note

7 단계의 루프는 [[GetPrototypeOf]][[SetPrototypeOf]] 에 대한 일반 객체 정의만 사용하는 객체들로 이루어진 어떤 프로토타입 체인에도 순환이 생기지 않도록 보장한다.

10.1.3 [[IsExtensible]] ( )

The [[IsExtensible]] internal method of 일반 객체 O takes no arguments and returns Boolean 을 담는 normal completion. It performs the following steps when called:

  1. OrdinaryIsExtensible(O) 를 반환한다.

10.1.3.1 OrdinaryIsExtensible ( O )

The abstract operation OrdinaryIsExtensible takes argument O (an Object) and returns a Boolean. It performs the following steps when called:

  1. O.[[Extensible]] 를 반환한다.

10.1.4 [[PreventExtensions]] ( )

The [[PreventExtensions]] internal method of 일반 객체 O takes no arguments and returns true 를 담는 normal completion. It performs the following steps when called:

  1. OrdinaryPreventExtensions(O) 를 반환한다.

10.1.4.1 OrdinaryPreventExtensions ( O )

The abstract operation OrdinaryPreventExtensions takes argument O (an Object) and returns true. It performs the following steps when called:

  1. O.[[Extensible]]false 로 설정한다.
  2. true 를 반환한다.

10.1.5 [[GetOwnProperty]] ( P )

The [[GetOwnProperty]] internal method of 일반 객체 O takes argument P (a property key) and returns Property Descriptor 또는 undefined 를 담는 normal completion. It performs the following steps when called:

  1. OrdinaryGetOwnProperty(O, P) 를 반환한다.

10.1.5.1 OrdinaryGetOwnProperty ( O, P )

The abstract operation OrdinaryGetOwnProperty takes arguments O (an Object) and P (a property key) and returns a Property Descriptor or undefined. It performs the following steps when called:

  1. O 가 키 P 인 자체 프로퍼티를 갖지 않으면 undefined 를 반환한다.
  2. 필드가 없는 새 프로퍼티 디스크립터 D 를 생성한다.
  3. X 를 키 PO 의 자체 프로퍼티로 둔다.
  4. X데이터 프로퍼티라면
    1. D.[[Value]]X[[Value]] 속성 값으로 설정한다.
    2. D.[[Writable]]X[[Writable]] 속성 값으로 설정한다.
  5. 그렇지 않으면
    1. 단언: X접근자 프로퍼티이다.
    2. D.[[Get]]X[[Get]] 속성 값으로 설정한다.
    3. D.[[Set]]X[[Set]] 속성 값으로 설정한다.
  6. D.[[Enumerable]]X[[Enumerable]] 속성 값으로 설정한다.
  7. D.[[Configurable]]X[[Configurable]] 속성 값으로 설정한다.
  8. D 를 반환한다.

10.1.6 [[DefineOwnProperty]] ( P, Desc )

The [[DefineOwnProperty]] internal method of 일반 객체 O takes arguments P (a property key) and Desc (a Property Descriptor) and returns Boolean 또는 throw completion 을 담는 normal completion. It performs the following steps when called:

  1. OrdinaryDefineOwnProperty(O, P, Desc) 를 반환한다.

10.1.6.1 OrdinaryDefineOwnProperty ( O, P, Desc )

The abstract operation OrdinaryDefineOwnProperty takes arguments O (an Object), P (a property key), and Desc (a Property Descriptor) and returns Boolean 또는 throw completion 을 담는 normal completion. It performs the following steps when called:

  1. current 를 ? O.[[GetOwnProperty]](P) 로 둔다.
  2. extensible 을 ? IsExtensible(O) 로 둔다.
  3. ValidateAndApplyPropertyDescriptor(O, P, extensible, Desc, current) 를 반환한다.

10.1.6.2 IsCompatiblePropertyDescriptor ( Extensible, Desc, Current )

The abstract operation IsCompatiblePropertyDescriptor takes arguments Extensible (a Boolean), Desc (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, Desc, Current) 를 반환한다.

10.1.6.3 ValidateAndApplyPropertyDescriptor ( O, P, extensible, Desc, current )

The abstract operation ValidateAndApplyPropertyDescriptor takes arguments O (an Object or undefined), P (a property key), extensible (a Boolean), Desc (a Property Descriptor), and current (a Property Descriptor or undefined) and returns a Boolean. Desc 가 지정된 extensibility 와 현재 프로퍼티 current 를 가진 객체의 프로퍼티로 ( 불변식 을 유지하면서) 적용될 수 있을 때에만 true 를 반환한다. 적용 가능하고 Oundefined 가 아니면 이름이 P 인 프로퍼티(필요 시 생성됨)에 대해 실제로 적용한다. It performs the following steps when called:

  1. 단언: P프로퍼티 키이다.
  2. currentundefined 이면
    1. extensiblefalse 이면 false 반환.
    2. Oundefined 이면 true 반환.
    3. IsAccessorDescriptor(Desc) 가 true 이면
      1. 객체 O 에 이름 P 인 자체 접근자 프로퍼티를 생성하되 [[Get]], [[Set]], [[Enumerable]], [[Configurable]]Desc 에 해당 필드가 있으면 그 값, 아니면 그 속성의 기본값 으로 설정.
    4. 그렇지 않으면
      1. 객체 O 에 이름 P 인 자체 데이터 프로퍼티를 생성하되 [[Value]], [[Writable]], [[Enumerable]], [[Configurable]]Desc 에 해당 필드가 있으면 그 값, 아니면 그 속성의 기본값 으로 설정.
    5. true 반환.
  3. 단언: current 는 완전히 채워진(Property Descriptor 모든 필드 보유) 프로퍼티 디스크립터이다.
  4. Desc 가 어떤 필드도 갖지 않으면 true 반환.
  5. current.[[Configurable]]false 이면
    1. Desc[[Configurable]] 필드가 있고 Desc.[[Configurable]]true 이면 false 반환.
    2. Desc[[Enumerable]] 필드가 있고 Desc.[[Enumerable]]current.[[Enumerable]] 와 다르면 false 반환.
    3. IsGenericDescriptor(Desc) 가 false 이고 IsAccessorDescriptor(Desc) 가 IsAccessorDescriptor(current) 와 다르면 false 반환.
    4. IsAccessorDescriptor(current) 가 true 이면
      1. Desc[[Get]] 필드가 있고 SameValue(Desc.[[Get]], current.[[Get]]) 가 false 이면 false 반환.
      2. Desc[[Set]] 필드가 있고 SameValue(Desc.[[Set]], current.[[Set]]) 가 false 이면 false 반환.
    5. Else if current.[[Writable]]false 이면
      1. Desc[[Writable]] 필드가 있고 Desc.[[Writable]]true 이면 false 반환.
      2. NOTE: SameValueNaN 에 대해 true 를 반환한다. 여기서 반환하면 기존 프로퍼티가 수정되지 않음을 보장한다.
      3. Desc[[Value]] 필드가 있으면 SameValue(Desc.[[Value]], current.[[Value]]) 를 반환.
  6. Oundefined 가 아니면
    1. IsDataDescriptor(current) 가 true 이고 IsAccessorDescriptor(Desc) 가 true 이면
      1. Desc[[Configurable]] 필드가 있으면 configurable 을 그 값으로, 아니면 current.[[Configurable]] 로 둔다.
      2. Desc[[Enumerable]] 필드가 있으면 enumerable 을 그 값으로, 아니면 current.[[Enumerable]] 로 둔다.
      3. 객체 O 의 이름 P 인 프로퍼티를 접근자 프로퍼티로 교체하되 [[Configurable]][[Enumerable]] 은 각각 configurable, enumerable 로, [[Get]], [[Set]]Desc 에 해당 필드가 있으면 그 값, 아니면 기본값 로 설정.
    2. Else if IsAccessorDescriptor(current) 가 true 이고 IsDataDescriptor(Desc) 가 true 이면
      1. Desc[[Configurable]] 필드가 있으면 configurable 을 그 값으로, 아니면 current.[[Configurable]] 로 둔다.
      2. Desc[[Enumerable]] 필드가 있으면 enumerable 을 그 값으로, 아니면 current.[[Enumerable]] 로 둔다.
      3. 객체 O 의 이름 P 인 프로퍼티를 데이터 프로퍼티로 교체하되 [[Configurable]][[Enumerable]] 은 각각 configurable, enumerable 로, [[Value]], [[Writable]]Desc 에 해당 필드가 있으면 그 값, 아니면 기본값 로 설정.
    3. Else
      1. Desc 의 각 필드에 대해 객체 O 의 이름 P 인 프로퍼티의 대응 속성을 그 필드 값으로 설정.
  7. true 반환.

10.1.7 [[HasProperty]] ( P )

The [[HasProperty]] internal method of 일반 객체 O takes argument P (a property key) and returns Boolean 또는 throw completion 을 담는 normal completion. It performs the following steps when called:

  1. OrdinaryHasProperty(O, P) 를 반환한다.

10.1.7.1 OrdinaryHasProperty ( O, P )

The abstract operation OrdinaryHasProperty takes arguments O (an Object) and P (a property key) and returns Boolean 또는 throw completion 을 담는 normal completion. It performs the following steps when called:

  1. hasOwn 을 ? O.[[GetOwnProperty]](P) 로 둔다.
  2. hasOwnundefined 가 아니면 true 반환.
  3. parent 를 ? O.[[GetPrototypeOf]]() 로 둔다.
  4. parentnull 이 아니면
    1. parent.[[HasProperty]](P) 를 반환한다.
  5. false 반환.

10.1.8 [[Get]] ( P, Receiver )

The [[Get]] internal method of 일반 객체 O takes arguments P (a property key) and Receiver (an ECMAScript language value) and returns ECMAScript 언어 값 또는 throw completion 을 담는 normal completion. It performs the following steps when called:

  1. OrdinaryGet(O, P, Receiver) 를 반환한다.

10.1.8.1 OrdinaryGet ( O, P, Receiver )

The abstract operation OrdinaryGet takes arguments O (an Object), P (a property key), and Receiver (an ECMAScript language value) and returns ECMAScript 언어 값 또는 throw completion 을 담는 normal completion. It performs the following steps when called:

  1. desc 를 ? O.[[GetOwnProperty]](P) 로 둔다.
  2. descundefined 이면
    1. parent 를 ? O.[[GetPrototypeOf]]() 로 둔다.
    2. parentnull 이면 undefined 반환.
    3. parent.[[Get]](P, Receiver) 를 반환한다.
  3. IsDataDescriptor(desc) 가 true 이면 desc.[[Value]] 를 반환한다.
  4. 단언: IsAccessorDescriptor(desc) 는 true 이다.
  5. getterdesc.[[Get]] 로 둔다.
  6. getterundefined 이면 undefined 반환.
  7. Call(getter, Receiver) 를 반환한다.

10.1.9 [[Set]] ( P, V, Receiver )

The [[Set]] internal method of 일반 객체 O takes arguments P (a property key), V (an ECMAScript language value), and Receiver (an ECMAScript language value) and returns Boolean 또는 throw completion 을 담는 normal completion. It performs the following steps when called:

  1. OrdinarySet(O, P, V, Receiver) 를 반환한다.

10.1.9.1 OrdinarySet ( O, P, V, Receiver )

The abstract operation OrdinarySet takes arguments O (an Object), P (a property key), V (an ECMAScript language value), and Receiver (an ECMAScript language value) and returns Boolean 또는 throw completion 을 담는 normal completion. It performs the following steps when called:

  1. ownDesc 를 ? O.[[GetOwnProperty]](P) 로 둔다.
  2. OrdinarySetWithOwnDescriptor(O, P, V, Receiver, ownDesc) 를 반환한다.

10.1.9.2 OrdinarySetWithOwnDescriptor ( O, P, V, Receiver, ownDesc )

The abstract operation OrdinarySetWithOwnDescriptor takes arguments O (an Object), P (a property key), V (an ECMAScript language value), Receiver (an ECMAScript language value), and ownDesc (a Property Descriptor or undefined) and returns Boolean 또는 throw completion 을 담는 normal completion. It performs the following steps when called:

  1. ownDescundefined 이면
    1. parent 를 ? O.[[GetPrototypeOf]]() 로 둔다.
    2. parentnull 이 아니면
      1. parent.[[Set]](P, V, Receiver) 를 반환한다.
    3. 그렇지 않으면
      1. ownDesc 를 PropertyDescriptor { [[Value]]: undefined, [[Writable]]: true, [[Enumerable]]: true, [[Configurable]]: true } 로 설정한다.
  2. IsDataDescriptor(ownDesc) 가 true 이면
    1. ownDesc.[[Writable]]false 이면 false 반환.
    2. Receiver 가 객체가 아니면 false 반환.
    3. existingDescriptor 를 ? Receiver.[[GetOwnProperty]](P) 로 둔다.
    4. existingDescriptorundefined 가 아니면
      1. IsAccessorDescriptor(existingDescriptor) 가 true 이면 false 반환.
      2. existingDescriptor.[[Writable]]false 이면 false 반환.
      3. valueDesc 를 PropertyDescriptor { [[Value]]: V } 로 둔다.
      4. Receiver.[[DefineOwnProperty]](P, valueDesc) 를 반환한다.
    5. 그렇지 않으면
      1. 단언: Receiver 는 현재 프로퍼티 P 를 갖지 않는다.
      2. CreateDataProperty(Receiver, P, V) 를 반환한다.
  3. 단언: IsAccessorDescriptor(ownDesc) 는 true 이다.
  4. setterownDesc.[[Set]] 로 둔다.
  5. setterundefined 이면 false 반환.
  6. Call(setter, Receiver, « V ») 를 수행한다.
  7. true 반환.

10.1.10 [[Delete]] ( P )

The [[Delete]] internal method of 일반 객체 O takes argument P (a property key) and returns Boolean 또는 throw completion 을 담는 normal completion. It performs the following steps when called:

  1. OrdinaryDelete(O, P) 를 반환한다.

10.1.10.1 OrdinaryDelete ( O, P )

The abstract operation OrdinaryDelete takes arguments O (an Object) and P (a property key) and returns Boolean 또는 throw completion 을 담는 normal completion. It performs the following steps when called:

  1. desc 를 ? O.[[GetOwnProperty]](P) 로 둔다.
  2. descundefined 이면 true 반환.
  3. desc.[[Configurable]]true 이면
    1. 이름 P 인 자체 프로퍼티를 O 에서 제거한다.
    2. true 반환.
  4. false 반환.

10.1.11 [[OwnPropertyKeys]] ( )

The [[OwnPropertyKeys]] internal method of 일반 객체 O takes no arguments and returns 프로퍼티 키 List 를 담는 normal completion. It performs the following steps when called:

  1. OrdinaryOwnPropertyKeys(O) 를 반환한다.

10.1.11.1 OrdinaryOwnPropertyKeys ( O )

The abstract operation OrdinaryOwnPropertyKeys takes argument O (an Object) and returns a List of property keys. It performs the following steps when called:

  1. keys 를 새 빈 List 로 둔다.
  2. O 의 각 자체 프로퍼티 키 PP배열 인덱스인 것들을 숫자 인덱스 오름차순으로 순회하며
    1. keysP 를 추가한다.
  3. O 의 각 자체 프로퍼티 키 PP 가 String 이고 배열 인덱스가 아닌 것들을 생성 시점의 시간 순(chronological order) 오름차순으로 순회하며
    1. keysP 를 추가한다.
  4. O 의 각 자체 프로퍼티 키 PP 가 Symbol 인 것들을 생성 시점의 시간 순 오름차순으로 순회하며
    1. keysP 를 추가한다.
  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. 새 일반 객체를 런타임에 생성하는 과정을 명세하는 데 사용된다. additionalInternalSlotsList[[Prototype]][[Extensible]] 외에 객체 일부로 정의되어야 하는 추가 내부 슬롯 이름을 담는다. additionalInternalSlotsList 가 제공되지 않으면 새 빈 List 를 사용한다. It performs the following steps when called:

  1. internalSlotsList 를 « [[Prototype]], [[Extensible]] » 로 둔다.
  2. additionalInternalSlotsList 가 주어지면 internalSlotsList 를 그 뒤에 additionalInternalSlotsList 를 이어붙인(list-concatenation) 리스트로 갱신한다.
  3. OMakeBasicObject(internalSlotsList) 로 둔다.
  4. O.[[Prototype]]proto 로 설정한다.
  5. O 를 반환한다.
Note

OrdinaryObjectCreate 는 MakeBasicObject 호출 외에 많은 일을 하지 않지만, 이를 사용함으로써 이그조틱이 아닌 “일반 객체” 를 만들고자 함을 전달한다. 따라서 이 명세에서 결과 객체의 내부 메서드를 비일반적으로 만들 방식으로 이후 수정하는 어떤 알고리즘도 이를 호출하지 않는다. 이그조틱 객체를 생성하는 연산은 MakeBasicObject 를 직접 호출한다.

10.1.13 OrdinaryCreateFromConstructor ( constructor, intrinsicDefaultProto [ , internalSlotsList ] )

The abstract operation OrdinaryCreateFromConstructor takes arguments constructor (a function object) and intrinsicDefaultProto (a String) and optional argument internalSlotsList (a List of names of internal slots) and returns 객체 또는 throw completion 을 담는 normal completion. 생성자"prototype" 프로퍼티가 존재하면 거기서 가져온 값을 [[Prototype]] 으로 하는 일반 객체를 생성한다. 그렇지 않으면 intrinsicDefaultProto 로 명명된 intrinsic 이 [[Prototype]] 으로 사용된다. internalSlotsList 는 객체 일부로 정의되어야 하는 추가 내부 슬롯 이름을 담으며 제공되지 않으면 새 빈 List 를 사용한다. It performs the following steps when called:

  1. 단언: intrinsicDefaultProto 는 이 명세에서 정의한 intrinsic 객체의 이름이다. 해당 객체는 다른 객체의 [[Prototype]] 값으로 사용되도록 의도된 intrinsic 이어야 한다.
  2. proto 를 ? GetPrototypeFromConstructor(constructor, intrinsicDefaultProto) 로 둔다.
  3. internalSlotsList 가 존재하면 slotsListinternalSlotsList 로 둔다.
  4. 아니면 slotsList 를 새 빈 List 로 둔다.
  5. OrdinaryObjectCreate(proto, slotsList) 를 반환한다.

10.1.14 GetPrototypeFromConstructor ( constructor, intrinsicDefaultProto )

The abstract operation GetPrototypeFromConstructor takes arguments constructor (a function object) and intrinsicDefaultProto (a String) and returns 객체 또는 throw completion 을 담는 normal completion. 특정 생성자에 대응하는 객체를 만들 때 사용할 [[Prototype]] 값을 결정한다. 생성자"prototype" 프로퍼티가 존재하면 그 값이 사용되고, 그렇지 않으면 intrinsicDefaultProto 로 명명된 intrinsic 이 [[Prototype]] 으로 사용된다. It performs the following steps when called:

  1. 단언: intrinsicDefaultProto 는 이 명세에서 정의한 intrinsic 객체의 이름이다. 해당 객체는 객체의 [[Prototype]] 값으로 사용되도록 의도된 intrinsic 이어야 한다.
  2. proto 를 ? Get(constructor, "prototype") 로 둔다.
  3. proto 가 객체가 아니면
    1. realm 을 ? GetFunctionRealm(constructor) 로 둔다.
    2. protorealmintrinsicDefaultProto 라는 이름의 intrinsic 객체로 설정한다.
  4. proto 를 반환한다.
Note

constructor[[Prototype]] 값을 제공하지 않으면 사용되는 기본값은 실행 중인 실행 컨텍스트가 아니라 constructor 함수의 realm 에서 얻는다.

10.1.15 RequireInternalSlot ( O, internalSlot )

The abstract operation RequireInternalSlot takes arguments O (an ECMAScript language value) and internalSlot (an internal slot name) and returns unused 또는 throw completion 을 담는 normal completion. O 가 객체가 아니거나 지정된 내부 슬롯을 가지지 않으면 예외를 던진다. It performs the following steps when called:

  1. O 가 객체가 아니면 TypeError 예외를 던진다.
  2. OinternalSlot 내부 슬롯이 없으면 TypeError 예외를 던진다.
  3. unused 를 반환한다.

10.2 ECMAScript 함수 객체(ECMAScript Function Objects)

ECMAScript 함수 객체는 렉시컬 환경을 클로즈(over)한 매개변수화된 ECMAScript 코드를 캡슐화하며 그 코드를 동적으로 평가할 수 있게 해준다. ECMAScript 함수 객체일반 객체(ordinary object)이며 다른 일반 객체와 동일한 내부 슬롯과 내부 메서드를 가진다. ECMAScript 함수 객체의 코드는 strict 모드 코드(11.2.2) 또는 비 strict 코드일 수 있다. 코드가 strict 모드 코드인 ECMAScript 함수 객체strict 함수라 한다. 코드가 strict 모드 코드가 아닌 것을 non‑strict 함수라 한다.

[[Extensible]][[Prototype]] 외에도, ECMAScript 함수 객체Table 28에 나열된 내부 슬롯을 추가로 가진다.

Table 28: ECMAScript 함수 객체의 내부 슬롯(Internal Slots of ECMAScript Function Objects)
Internal Slot Type Description
[[Environment]] an Environment Record 함수가 클로즈한 Environment Record. 함수 코드 평가 시 외부 환경(outer environment)으로 사용.
[[PrivateEnvironment]] a PrivateEnvironment Record or null 함수가 클로즈한 Private NamePrivateEnvironment Record. 함수가 문법적으로 어떤 클래스 내부에도 포함되지 않았다면 null. 함수 코드 평가 시 내부 클래스들의 외부 PrivateEnvironment로 사용.
[[FormalParameters]] a Parse Node 함수의 형식 매개변수 목록을 정의하는 소스 텍스트의 루트 Parse Node.
[[ECMAScriptCode]] a Parse Node 함수 본문을 정의하는 소스 텍스트의 루트 Parse Node.
[[ConstructorKind]] base or derived 함수가 파생 클래스 생성자인지 여부.
[[Realm]] a Realm Record 함수가 생성된 realm이며 함수 평가 시 접근되는 intrinsic 객체들을 제공.
[[ScriptOrModule]] a Script Record or a Module Record 함수가 생성된 스크립트 또는 모듈.
[[ThisMode]] lexical, strict, or global this 참조가 형식 매개변수 및 함수 본문 내에서 어떻게 해석되는지 정의. lexicalthis 가 렉시컬로 둘러싼 함수의 this 값을 가리킴. strictthis 값이 호출 시 제공된 그대로 사용됨. globalundefined 또는 nullthis 값을 전역 객체 참조로 해석하고, 다른 this 값은 먼저 ToObject 적용.
[[Strict]] a Boolean true 이면 strict 함수, false 이면 non‑strict 함수.
[[HomeObject]] an Object 함수가 super를 사용한다면, super 프로퍼티 조회의 시작점을 제공하는 [[GetPrototypeOf]] 대상 객체.
[[SourceText]] a sequence of Unicode code points 함수를 정의하는 소스 텍스트.
[[Fields]] a List of ClassFieldDefinition Records 함수가 클래스라면, 비정적 필드 및 그 초기화자를 나타내는 Record들의 목록.
[[PrivateMethods]] a List of PrivateElements 함수가 클래스라면, 비정적 private 메서드 및 접근자들을 나타내는 목록.
[[ClassFieldInitializerName]] a String, a Symbol, a Private Name, or empty 함수가 클래스 필드 초기화자로 생성된 경우, 필드의 NamedEvaluation에 사용할 이름; 그렇지 않으면 empty.
[[IsClassConstructor]] a Boolean 함수가 클래스 생성자인지 나타냄. (true 이면 함수의 [[Call]] 호출은 즉시 TypeError 예외 throw).

모든 ECMAScript 함수 객체는 여기 정의된 [[Call]] 내부 메서드를 가진다. 동시에 생성자인 ECMAScript 함수는 추가로 [[Construct]] 내부 메서드를 가진다.

10.2.1 [[Call]] ( thisArgument, argumentsList )

The [[Call]] internal method of ECMAScript 함수 객체 F takes arguments thisArgument (an ECMAScript language value) and argumentsList (a List of ECMAScript language values) and returns ECMAScript 언어 값 또는 throw completion 을 담는 normal completion. It performs the following steps when called:

  1. callerContext 를 실행 중 실행 컨텍스트로 둔다.
  2. calleeContextPrepareForOrdinaryCall(F, undefined) 로 둔다.
  3. 단언: calleeContext 가 이제 실행 중 실행 컨텍스트.
  4. F.[[IsClassConstructor]]true 이면
    1. TypeError 객체 error 를 생성한다.
    2. NOTE: errorcalleeContext 에서 FRealm Record 로 생성된다.
    3. 실행 컨텍스트 스택에서 calleeContext 를 제거하고 callerContext 를 실행 중 실행 컨텍스트로 복원한다.
    4. ThrowCompletion(error) 를 반환한다.
  5. OrdinaryCallBindThis(F, calleeContext, thisArgument) 를 수행한다.
  6. resultCompletion(OrdinaryCallEvaluateBody(F, argumentsList)) 로 둔다.
  7. 실행 컨텍스트 스택에서 calleeContext 를 제거하고 callerContext 를 실행 중 실행 컨텍스트로 복원한다.
  8. resultreturn completion 이면 result.[[Value]] 반환.
  9. 단언: resultthrow completion.
  10. result 를 반환한다.
Note

단계 7 에서 calleeContext 가 스택에서 제거될 때 접근 가능한 Generator 에 의해 나중 재개를 위해 suspend 및 보존된 경우 파괴되면 안 된다.

10.2.1.1 PrepareForOrdinaryCall ( F, newTarget )

The abstract operation PrepareForOrdinaryCall takes arguments F (an ECMAScript function object) and newTarget (an Object or undefined) and returns an execution context. It performs the following steps when called:

  1. callerContext 를 실행 중 실행 컨텍스트로 둔다.
  2. calleeContext 를 새 ECMAScript 코드 실행 컨텍스트로 둔다.
  3. calleeContext 의 Function 을 F 로 설정.
  4. calleeRealmF.[[Realm]] 로 둔다.
  5. calleeContextRealmcalleeRealm 으로 설정.
  6. calleeContext 의 ScriptOrModule 을 F.[[ScriptOrModule]] 로 설정.
  7. localEnvNewFunctionEnvironment(F, newTarget) 로 둔다.
  8. calleeContext 의 LexicalEnvironment 를 localEnv 로 설정.
  9. calleeContext 의 VariableEnvironment 를 localEnv 로 설정.
  10. calleeContext 의 PrivateEnvironment 를 F.[[PrivateEnvironment]] 로 설정.
  11. callerContext 가 아직 suspend 되어 있지 않다면 suspend 한다.
  12. calleeContext 를 실행 컨텍스트 스택에 push; calleeContext 가 이제 실행 중 실행 컨텍스트.
  13. NOTE: 이 지점 이후 생성되는 모든 예외 객체는 calleeRealm 과 연관됨.
  14. calleeContext 반환.

10.2.1.2 OrdinaryCallBindThis ( F, calleeContext, thisArgument )

The abstract operation OrdinaryCallBindThis takes arguments F (an ECMAScript function object), calleeContext (an execution context), and thisArgument (an ECMAScript language value) and returns unused. It performs the following steps when called:

  1. thisModeF.[[ThisMode]] 로 둔다.
  2. thisModelexical 이면 unused 반환.
  3. calleeRealmF.[[Realm]] 로 둔다.
  4. localEnvcalleeContext 의 LexicalEnvironment 로 둔다.
  5. thisModestrict 이면
    1. thisValuethisArgument 로 둔다.
  6. 그렇지 않으면
    1. thisArgumentundefined 또는 null 이면
      1. globalEnvcalleeRealm.[[GlobalEnv]] 로 둔다.
      2. 단언: globalEnvGlobal Environment Record.
      3. thisValueglobalEnv.[[GlobalThisValue]] 로 둔다.
    2. 아니면
      1. thisValue 를 ! ToObject(thisArgument) 로 둔다.
      2. NOTE: ToObjectcalleeRealm 을 사용하여 wrapper 객체를 생성.
  7. 단언: localEnvFunction Environment Record.
  8. 단언: 다음 단계는 localEnv.[[ThisBindingStatus]]initialized 가 아니므로 abrupt completion 을 반환하지 않는다.
  9. BindThisValue(localEnv, thisValue) 수행.
  10. unused 반환.

10.2.1.3 Runtime Semantics: EvaluateBody

The syntax-directed operation EvaluateBody takes arguments functionObject (an ECMAScript function object) and argumentsList (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. FunctionBody 의 EvaluateFunctionBody (인수 functionObject, argumentsList) ? 를 반환.
ConciseBody : ExpressionBody
  1. ConciseBody 의 EvaluateConciseBody (인수 functionObject, argumentsList) ? 를 반환.
GeneratorBody : FunctionBody
  1. GeneratorBody 의 EvaluateGeneratorBody (인수 functionObject, argumentsList) ? 를 반환.
AsyncGeneratorBody : FunctionBody
  1. AsyncGeneratorBody 의 EvaluateAsyncGeneratorBody (인수 functionObject, argumentsList) ? 를 반환.
AsyncFunctionBody : FunctionBody
  1. AsyncFunctionBody 의 EvaluateAsyncFunctionBody (인수 functionObject, argumentsList) ? 를 반환.
AsyncConciseBody : ExpressionBody
  1. AsyncConciseBody 의 EvaluateAsyncConciseBody (인수 functionObject, argumentsList) ? 를 반환.
Initializer : = AssignmentExpression
  1. 단언: argumentsList 는 비어 있다.
  2. 단언: functionObject.[[ClassFieldInitializerName]]empty 가 아니다.
    1. IsAnonymousFunctionDefinition(AssignmentExpression) 이 true 이면
      1. valueInitializer 의 NamedEvaluation (인수 functionObject.[[ClassFieldInitializerName]]) ? 로 둔다.
    2. 그렇지 않으면
      1. rhsAssignmentExpression 의 Evaluation ? 로 둔다.
      2. value 를 ? GetValue(rhs) 로 둔다.
  3. ReturnCompletion(value) 를 반환.
Note

필드 초기화자는 함수 경계를 형성하지만 FunctionDeclarationInstantiation 호출은 관측 가능한 효과가 없으므로 생략된다.

ClassStaticBlockBody : ClassStaticBlockStatementList
  1. 단언: argumentsList 는 비어 있다.
  2. ClassStaticBlockBody 의 EvaluateClassStaticBlockBody (인수 functionObject) ? 를 반환.

10.2.1.4 OrdinaryCallEvaluateBody ( F, argumentsList )

The abstract operation OrdinaryCallEvaluateBody takes arguments F (an ECMAScript function object) and argumentsList (a List of ECMAScript language values) and returns a return completion or a throw completion. It performs the following steps when called:

  1. F.[[ECMAScriptCode]]EvaluateBody (인수 F, argumentsList) ? 를 반환.

10.2.2 [[Construct]] ( argumentsList, newTarget )

The [[Construct]] internal method of ECMAScript 함수 객체 F takes arguments argumentsList (a List of ECMAScript language values) and newTarget (a constructor) and returns 객체 또는 throw completion 을 담는 normal completion. It performs the following steps when called:

  1. callerContext 를 실행 중 실행 컨텍스트로 둔다.
  2. kindF.[[ConstructorKind]] 로 둔다.
  3. kindbase 이면
    1. thisArgument 를 ? OrdinaryCreateFromConstructor(newTarget, "%Object.prototype%") 로 둔다.
  4. calleeContextPrepareForOrdinaryCall(F, newTarget) 로 둔다.
  5. 단언: calleeContext 가 이제 실행 중 실행 컨텍스트.
  6. kindbase 이면
    1. OrdinaryCallBindThis(F, calleeContext, thisArgument) 수행.
    2. initializeResultCompletion(InitializeInstanceElements(thisArgument, F)) 로 둔다.
    3. initializeResultabrupt completion 이면
      1. 실행 컨텍스트 스택에서 calleeContext 제거 후 callerContext 복원.
      2. initializeResult 반환.
  7. constructorEnvcalleeContext 의 LexicalEnvironment 로 둔다.
  8. resultCompletion(OrdinaryCallEvaluateBody(F, argumentsList)) 로 둔다.
  9. 실행 컨텍스트 스택에서 calleeContext 제거 후 callerContext 복원.
  10. resultthrow completion 이면
    1. result 반환.
  11. 단언: resultreturn completion.
  12. result.[[Value]] 가 객체이면 그 값 반환.
  13. kindbase 이면 thisArgument 반환.
  14. result.[[Value]]undefined 가 아니면 TypeError 예외 throw.
  15. thisBinding 을 ? constructorEnv.GetThisBinding() 로 둔다.
  16. 단언: thisBinding 은 객체.
  17. thisBinding 반환.

10.2.3 OrdinaryFunctionCreate ( functionPrototype, sourceText, ParameterList, Body, thisMode, env, privateEnv )

The abstract operation OrdinaryFunctionCreate takes arguments functionPrototype (an Object), sourceText (a sequence of Unicode code points), ParameterList (a Parse Node), Body (a Parse Node), thisMode (lexical-this or non-lexical-this), env (an Environment Record), and privateEnv (a PrivateEnvironment Record or null) and returns an ECMAScript function object. 기본 [[Call]] 내부 메서드만 있고 [[Construct]] 내부 메서드는 없는(단, 이후 MakeConstructor 같은 연산으로 추가될 수 있음) 새 함수를 런타임에 생성하는 과정을 명세한다. sourceText 는 생성할 함수 문법 정의의 소스 텍스트. It performs the following steps when called:

  1. internalSlotsListTable 28 에 나열된 내부 슬롯으로 둔다.
  2. FOrdinaryObjectCreate(functionPrototype, internalSlotsList) 로 둔다.
  3. F.[[Call]]10.2.1 에 명시된 정의로 설정.
  4. F.[[SourceText]]sourceText 로 설정.
  5. F.[[FormalParameters]]ParameterList 로 설정.
  6. F.[[ECMAScriptCode]]Body 로 설정.
  7. Strict 를 IsStrict(Body) 로 둔다.
  8. F.[[Strict]]Strict 로 설정.
  9. thisModelexical-this 이면 F.[[ThisMode]]lexical 로 설정.
  10. Else if Stricttrue 이면 F.[[ThisMode]]strict 로 설정.
  11. Else F.[[ThisMode]]global 로 설정.
  12. F.[[IsClassConstructor]]false 로 설정.
  13. F.[[Environment]]env 로 설정.
  14. F.[[PrivateEnvironment]]privateEnv 로 설정.
  15. F.[[ScriptOrModule]]GetActiveScriptOrModule() 로 설정.
  16. F.[[Realm]]current Realm Record 로 설정.
  17. F.[[HomeObject]]undefined 로 설정.
  18. F.[[Fields]] 를 새 빈 List 로 설정.
  19. F.[[PrivateMethods]] 를 새 빈 List 로 설정.
  20. F.[[ClassFieldInitializerName]]empty 로 설정.
  21. lenParameterList 의 ExpectedArgumentCount 로 둔다.
  22. SetFunctionLength(F, len) 수행.
  23. F 반환.

10.2.4 AddRestrictedFunctionProperties ( F, realm )

The abstract operation AddRestrictedFunctionProperties takes arguments F (a function object) and realm (a Realm Record) and returns unused. It performs the following steps when called:

  1. 단언: realm.[[Intrinsics]].[[%ThrowTypeError%]] 가 존재하며 초기화됨.
  2. throwerrealm.[[Intrinsics]].[[%ThrowTypeError%]] 로 둔다.
  3. DefinePropertyOrThrow(F, "caller", PropertyDescriptor { [[Get]]: thrower, [[Set]]: thrower, [[Enumerable]]: false, [[Configurable]]: true }) 수행.
  4. DefinePropertyOrThrow(F, "arguments", PropertyDescriptor { [[Get]]: thrower, [[Set]]: thrower, [[Enumerable]]: false, [[Configurable]]: true }) 수행.
  5. unused 반환.

10.2.4.1 %ThrowTypeError% ( )

이 함수는 %ThrowTypeError% intrinsic 객체이다.

realm 마다 한 번 정의되는 익명 내장 함수 객체이다.

호출 시 다음 단계를 수행한다:

  1. TypeError 예외를 throw 한다.

이 함수의 [[Extensible]] 내부 슬롯 값은 false 이다.

이 함수의 "length" 프로퍼티 속성은 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }.

이 함수의 "name" 프로퍼티 속성은 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }.

10.2.5 MakeConstructor ( F [ , writablePrototype [ , prototype ] ] )

The abstract operation MakeConstructor takes argument F (an ECMAScript function object or a built-in function object) and optional arguments writablePrototype (a Boolean) and prototype (an Object) and returns unused. F생성자로 변환한다. It performs the following steps when called:

  1. F 가 ECMAScript 함수 객체이면
    1. 단언: IsConstructor(F) 는 false.
    2. 단언: F"prototype" 자체 프로퍼티가 없는 extensible 객체.
    3. F.[[Construct]]10.2.2 에 명시된 정의로 설정.
  2. 그렇지 않으면
    1. F.[[Construct]]10.3.2 에 명시된 정의로 설정.
  3. F.[[ConstructorKind]]base 로 설정.
  4. writablePrototype 이 제공되지 않았다면 true 로 설정.
  5. prototype 이 제공되지 않았다면
    1. prototypeOrdinaryObjectCreate(%Object.prototype%) 로 둔다.
    2. DefinePropertyOrThrow(prototype, "constructor", PropertyDescriptor { [[Value]]: F, [[Writable]]: writablePrototype, [[Enumerable]]: false, [[Configurable]]: true }) 수행.
  6. DefinePropertyOrThrow(F, "prototype", PropertyDescriptor { [[Value]]: prototype, [[Writable]]: writablePrototype, [[Enumerable]]: false, [[Configurable]]: false }) 수행.
  7. unused 반환.

10.2.6 MakeClassConstructor ( F )

The abstract operation MakeClassConstructor takes argument F (an ECMAScript function object) and returns unused. It performs the following steps when called:

  1. 단언: F.[[IsClassConstructor]]false.
  2. F.[[IsClassConstructor]]true 로 설정.
  3. unused 반환.

10.2.7 MakeMethod ( F, homeObject )

The abstract operation MakeMethod takes arguments F (an ECMAScript function object) and homeObject (an Object) and returns unused. F 를 메서드로 구성한다. It performs the following steps when called:

  1. 단언: homeObject일반 객체.
  2. F.[[HomeObject]]homeObject 로 설정.
  3. unused 반환.

10.2.8 DefineMethodProperty ( homeObject, key, closure, enumerable )

The abstract operation DefineMethodProperty takes arguments homeObject (an Object), key (a property key or Private Name), closure (a function object), and enumerable (a Boolean) and returns PrivateElement 또는 unused 를 담는 normal completion 또는 abrupt completion. It performs the following steps when called:

  1. 단언: homeObject 는 ordinary 이며 extensible 한 객체.
  2. keyPrivate Name 이면
    1. PrivateElement { [[Key]]: key, [[Kind]]: method, [[Value]]: closure } 를 반환.
  3. 그렇지 않으면
    1. desc 를 PropertyDescriptor { [[Value]]: closure, [[Writable]]: true, [[Enumerable]]: enumerable, [[Configurable]]: true } 로 둔다.
    2. DefinePropertyOrThrow(homeObject, key, desc) 수행.
    3. NOTE: key"prototype" 인 class static method 정의 시에만 abrupt completion 반환 가능.
    4. unused 반환.

10.2.9 SetFunctionName ( F, name [ , prefix ] )

The abstract operation SetFunctionName takes arguments F (a function object) and name (a property key or Private Name) and optional argument prefix (a String) and returns unused. F"name" 프로퍼티를 추가한다. It performs the following steps when called:

  1. 단언: F"name" 자체 프로퍼티가 없는 extensible 객체.
  2. name 이 Symbol 이면
    1. descriptionname.[[Description]] 로 둔다.
    2. descriptionundefined 이면 name 을 빈 문자열로 설정.
    3. 그렇지 않으면 name"[", description, "]" 의 문자열 연결로 설정.
  3. Else if namePrivate Name 이면
    1. namename.[[Description]] 로 설정.
  4. F[[InitialName]] 내부 슬롯을 가진다면
    1. F.[[InitialName]]name 으로 설정.
  5. prefix 가 존재하면
    1. name 을 (prefix + 0x0020(SPACE) + name) 문자열 연결로 설정.
    2. F[[InitialName]] 내부 슬롯을 가진다면
      1. NOTE: 다음 선택은 이 Abstract Operation 이 호출될 때마다 독립적으로 이루어짐.
      2. 선택적으로 F.[[InitialName]]name 으로 설정.
  6. DefinePropertyOrThrow(F, "name", PropertyDescriptor { [[Value]]: name, [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }) 수행.
  7. unused 반환.

10.2.10 SetFunctionLength ( F, length )

The abstract operation SetFunctionLength takes arguments F (a function object) and length (a non-negative integer or +∞) and returns unused. F"length" 프로퍼티를 추가한다. It performs the following steps when called:

  1. 단언: F"length" 자체 프로퍼티가 없는 extensible 객체.
  2. DefinePropertyOrThrow(F, "length", PropertyDescriptor { [[Value]]: 𝔽(length), [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }) 수행.
  3. unused 반환.

10.2.11 FunctionDeclarationInstantiation ( func, argumentsList )

The abstract operation FunctionDeclarationInstantiation takes arguments func (an ECMAScript function object) and argumentsList (a List of ECMAScript language values) and returns unused 를 담는 normal completion 또는 throw completion. func 는 실행 컨텍스트를 설정 중인 함수 객체이다.

Note

ECMAScript 함수를 평가하기 위한 실행 컨텍스트가 설정될 때 새로운 Function Environment Record 가 생성되고 각 형식 매개변수에 대한 바인딩이 그 Environment Record 에서 인스턴스화된다. 함수 본문 내 모든 선언도 인스턴스화된다. 함수의 형식 매개변수에 기본값 초기화자가 없으면 본문 선언들은 매개변수와 동일한 Environment Record 에서 인스턴스화된다. 기본값 매개변수 초기화자가 있으면 본문 선언을 위한 두 번째 Environment Record 가 생성된다. 형식 매개변수와 함수들은 FunctionDeclarationInstantiation 의 일부로 초기화된다. 다른 모든 바인딩은 함수 본문 평가 중 초기화된다.

호출 시 다음 단계를 수행한다:

  1. calleeContext 를 실행 중 실행 컨텍스트로 둔다.
  2. codefunc.[[ECMAScriptCode]] 로 둔다.
  3. strictfunc.[[Strict]] 로 둔다.
  4. formalsfunc.[[FormalParameters]] 로 둔다.
  5. parameterNamesformals 의 BoundNames 로 둔다.
  6. parameterNames 가 중복 항목을 가지면 hasDuplicatestrue, 아니면 false 로 둔다.
  7. simpleParameterList 를 IsSimpleParameterList of formals 로 둔다.
  8. hasParameterExpressions 를 ContainsExpression of formals 로 둔다.
  9. varNamescode 의 VarDeclaredNames 로 둔다.
  10. varDeclarationscode 의 VarScopedDeclarations 로 둔다.
  11. lexicalNamescode 의 LexicallyDeclaredNames 로 둔다.
  12. functionNames 를 새 빈 List 로 둔다.
  13. functionsToInitialize 를 새 빈 List 로 둔다.
  14. varDeclarations 의 각 요소 d 에 대해 (역순으로):
    1. dVariableDeclaration, ForBinding, BindingIdentifier 가 아니면
      1. 단언: dFunctionDeclaration, GeneratorDeclaration, AsyncFunctionDeclaration, AsyncGeneratorDeclaration 중 하나.
      2. fnd 의 BoundNames 의 유일한 요소로 둔다.
      3. functionNamesfn 을 포함하지 않으면
        1. fnfunctionNames 의 첫 요소로 삽입.
        2. NOTE: 동일 이름 함수 선언이 여러 개면 마지막 선언 사용.
        3. dfunctionsToInitialize 의 첫 요소로 삽입.
  15. argumentsObjectNeededtrue 로 둔다.
  16. func.[[ThisMode]]lexical 이면
    1. NOTE: 화살표 함수는 arguments 객체를 갖지 않는다.
    2. argumentsObjectNeededfalse 로 설정.
  17. Else if parameterNames"arguments" 를 포함하면
    1. argumentsObjectNeededfalse 로.
  18. Else if hasParameterExpressionsfalse 이면
    1. functionNames"arguments" 를 포함하거나 lexicalNames"arguments" 를 포함하면
      1. argumentsObjectNeededfalse 로.
  19. stricttrue 이거나 hasParameterExpressionsfalse 이면
    1. NOTE: strict 모드 eval 은 외부에서 보이는 새 바인딩을 만들 수 없으므로 매개변수에 단일 Environment Record 만 필요.
    2. envcalleeContext 의 LexicalEnvironment 로 둔다.
  20. Else
    1. NOTE: 형식 매개변수 리스트 내 direct eval 이 만든 바인딩이 매개변수 선언 환경 밖에 위치하도록 분리된 Environment Record 필요.
    2. calleeEnvcalleeContext 의 LexicalEnvironment 로 둔다.
    3. envNewDeclarativeEnvironment(calleeEnv) 로 둔다.
    4. 단언: calleeContext 의 VariableEnvironment 와 calleeEnv 는 동일한 Environment Record.
    5. calleeContext 의 LexicalEnvironment 를 env 로 설정.
  21. parameterNames 의 각 String paramName 에 대해
    1. alreadyDeclared 를 ! env.HasBinding(paramName) 로 둔다.
    2. NOTE: 중복 매개변수 이름은 기본값/나머지 매개변수 없는 non‑strict 함수에만 가능(초기 에러 규칙).
    3. alreadyDeclaredfalse 이면
      1. env.CreateMutableBinding(paramName, false) 수행.
      2. hasDuplicatestrue 이면
        1. env.InitializeBinding(paramName, undefined) 수행.
  22. argumentsObjectNeededtrue 이면
    1. stricttrue 이거나 simpleParameterListfalse 이면
      1. aoCreateUnmappedArgumentsObject(argumentsList) 로 둔다.
    2. Else
      1. NOTE: mapped arguments 객체는 rest, 기본값, 구조분해 매개변수 없는 non‑strict 함수에만 제공.
      2. aoCreateMappedArgumentsObject(func, formals, argumentsList, env) 로 둔다.
    3. stricttrue 이면
      1. env.CreateImmutableBinding("arguments", false) 수행.
      2. NOTE: strict 코드에서는 이 바인딩에 할당 시도 자체가 조기 에러로 금지되어 불변성 관측 불가.
    4. Else
      1. env.CreateMutableBinding("arguments", false) 수행.
    5. env.InitializeBinding("arguments", ao) 수행.
    6. parameterBindingsparameterNames 와 « "arguments" » 의 리스트 연결로 둔다.
  23. Else
    1. parameterBindingsparameterNames 로 둔다.
  24. iteratorRecordCreateListIteratorRecord(argumentsList) 로 둔다.
  25. hasDuplicatestrue 이면
    1. usedEnvundefined 로 둔다.
  26. Else
    1. usedEnvenv 로 둔다.
  27. NOTE: 다음 단계는 표현식 위치에서 YieldExpression 사용으로만 ReturnCompletion 이 가능하나 파라미터 리스트에서 조기 에러로 금지됨.
  28. ? IteratorBindingInitialization of formals (인수 iteratorRecord, usedEnv) 수행.
  29. hasParameterExpressionsfalse 이면
    1. NOTE: 매개변수와 최상위 var 에 단일 Environment Record 사용.
    2. instantiatedVarNamesparameterBindings 복사본으로 둔다.
    3. varNames 의 각 n 에 대해
      1. instantiatedVarNamesn 을 포함하지 않으면
        1. instantiatedVarNamesn 추가.
        2. env.CreateMutableBinding(n, false) 수행.
        3. env.InitializeBinding(n, undefined) 수행.
    4. varEnvenv 로 둔다.
  30. Else
    1. NOTE: 형식 매개변수 표현식이 만든 클로저가 함수 본문 선언을 보지 못하도록 별도 Environment Record 필요.
    2. varEnvNewDeclarativeEnvironment(env) 로 둔다.
    3. calleeContext 의 VariableEnvironment 를 varEnv 로 설정.
    4. instantiatedVarNames 를 새 빈 List 로 둔다.
    5. varNames 의 각 n 에 대해
      1. instantiatedVarNamesn 을 포함하지 않으면
        1. instantiatedVarNamesn 추가.
        2. varEnv.CreateMutableBinding(n, false) 수행.
        3. (parameterBindingsn 을 포함하지 않거나 functionNamesn 을 포함하면)
          1. initialValueundefined 로 둔다.
        4. Else
          1. initialValue 를 ! env.GetBindingValue(n, false) 로 둔다.
        5. varEnv.InitializeBinding(n, initialValue) 수행.
        6. NOTE: 형식 매개변수와 같은 이름의 var 는 초기에는 해당 매개변수 초기화 값과 동일.
  31. stricttrue 이면
    1. lexEnvvarEnv 로 둔다.
  32. Else
    1. Normative Optional
      호스트가 웹 브라우저이거나 블록 수준 함수 선언 웹 레거시 호환 의미 를 지원하면
      1. code Contains xtrue 인 어떤 Block, CaseClause, DefaultClause xStatementList 에 직접 포함된 각 FunctionDeclaration f 에 대해
        1. FfBindingIdentifier 의 StringValue 로 둔다.
        2. FunctionDeclaration fFBindingIdentifier 로 갖는 VariableStatement 로 대체해도 func 에 대해 Early Errors 가 발생하지 않고 parameterNamesF 를 포함하지 않으면
          1. NOTE: F 에 대한 var 바인딩은 VarDeclaredName 이 아니고 형식 매개변수 이름도 아니며 다른 FunctionDeclaration 도 아닐 때만 여기서 인스턴스화.
          2. instantiatedVarNamesF 를 포함하지 않고 F"arguments" 가 아니면
            1. varEnv.CreateMutableBinding(F, false) 수행.
            2. varEnv.InitializeBinding(F, undefined) 수행.
            3. instantiatedVarNamesF 추가.
          3. FunctionDeclaration f 평가 시 15.2.6 의 Evaluation 알고리즘 대신 다음 수행:
            1. fEnv 를 실행 중 실행 컨텍스트의 VariableEnvironment 로 둔다.
            2. bEnv 를 실행 중 실행 컨텍스트의 LexicalEnvironment 로 둔다.
            3. fObj 를 ! bEnv.GetBindingValue(F, false) 로 둔다.
            4. fEnv.SetMutableBinding(F, fObj, false) 수행.
            5. unused 반환.
    2. lexEnvNewDeclarativeEnvironment(varEnv) 로 둔다.
    3. NOTE: non‑strict 함수는 direct eval 이 생성한 var 스코프 선언과 기존 최상위 lexical 선언 충돌 여부를 판단할 수 있도록 top-level lexical 선언에 별도의 Environment Record 사용. strict 함수는 항상 새 Environment Record 사용하므로 불필요.
  33. calleeContext 의 LexicalEnvironment 를 lexEnv 로 설정.
  34. lexDeclarationscode 의 LexicallyScopedDeclarations 로 둔다.
  35. lexDeclarations 의 각 d 에 대해
    1. NOTE: lexical 선언 이름은 함수/제너레이터 선언, 형식 매개변수, var 이름과 같을 수 없으며 여기서 인스턴스화만 되고 초기화는 안 됨.
    2. d 의 BoundNames 각 dn 에 대해
      1. IsConstantDeclaration of dtrue 이면
        1. lexEnv.CreateImmutableBinding(dn, true) 수행.
      2. Else
        1. lexEnv.CreateMutableBinding(dn, false) 수행.
  36. privateEnvcalleeContext 의 PrivateEnvironment 로 둔다.
  37. functionsToInitialize 의 각 Parse Node f 에 대해
    1. fnf 의 BoundNames 유일 요소로 둔다.
    2. fo 를 InstantiateFunctionObject of f (인수 lexEnv, privateEnv) 로 둔다.
    3. varEnv.SetMutableBinding(fn, fo, false) 수행.
  38. unused 반환.

10.3 내장 함수 객체(Built-in Function Objects)

내장 함수 객체일반 객체이며; 10.1에 규정된 일반 객체 요건을 만족해야 한다.

모든 일반 객체에 요구되는 내부 슬롯(10.1 참조)에 더해, 내장 함수 객체는 다음 내부 슬롯도 가져야 한다:

  • [[Realm]]: 함수가 생성된 realm 을 나타내는 Realm Record.
  • [[InitialName]]: 함수의 초기 이름인 String. 20.2.3.5에서 사용된다.

명시적으로 달리 지정되지 않은 한, 내장 함수 객체[[Prototype]] 내부 슬롯 초기 값은 %Function.prototype% 이다.

내장 함수 객체10.3.1의 정의에 부합하는 [[Call]] 내부 메서드를 가져야 한다.

내장 함수 객체는 “constructor”로 기술되었거나 이 명세의 어떤 알고리즘이 그 [[Construct]] 내부 메서드를 명시적으로 설정한 경우에만 [[Construct]] 내부 메서드를 가진다. 그러한 [[Construct]] 내부 메서드는 10.3.2의 정의를 준수해야 한다.

구현은 이 명세에 정의되지 않은 추가 내장 함수 객체를 제공할 수 있다.

10.3.1 [[Call]] ( thisArgument, argumentsList )

The [[Call]] internal method of 내장 함수 객체 F takes arguments thisArgument (an ECMAScript language value) and argumentsList (a List of ECMAScript language values) and returns ECMAScript 언어 값 또는 throw completion 을 담는 normal completion. It performs the following steps when called:

  1. BuiltinCallOrConstruct(F, thisArgument, argumentsList, undefined) 를 반환한다.

10.3.2 [[Construct]] ( argumentsList, newTarget )

The [[Construct]] internal method of 내장 함수 객체 F (이 메서드가 존재할 때) takes arguments argumentsList (a List of ECMAScript language values) and newTarget (a constructor) and returns 객체 또는 throw completion 을 담는 normal completion. It performs the following steps when called:

  1. result 를 ? BuiltinCallOrConstruct(F, uninitialized, argumentsList, newTarget) 로 둔다.
  2. 단언: result 는 Object.
  3. result 를 반환한다.

10.3.3 BuiltinCallOrConstruct ( F, thisArgument, argumentsList, newTarget )

The abstract operation BuiltinCallOrConstruct takes arguments F (a built-in function object), thisArgument (an ECMAScript language value or uninitialized), argumentsList (a List of ECMAScript language values), and newTarget (a constructor or undefined) and returns ECMAScript 언어 값 또는 throw completion 을 담는 normal completion. It performs the following steps when called:

  1. callerContext 를 실행 중 실행 컨텍스트로 둔다.
  2. callerContext 가 아직 suspend 되어 있지 않다면 suspend 한다.
  3. calleeContext 를 새 실행 컨텍스트로 둔다.
  4. calleeContext 의 Function 을 F 로 설정한다.
  5. calleeRealmF.[[Realm]] 로 둔다.
  6. calleeContextRealmcalleeRealm 로 설정한다.
  7. calleeContext 의 ScriptOrModule 을 null 로 설정한다.
  8. 구현 정의된 필요 초기화를 calleeContext 에 수행한다.
  9. calleeContext 를 실행 컨텍스트 스택에 push; 이제 calleeContext 가 실행 중 실행 컨텍스트이다.
  10. resultF 의 명세에 부합하는 방식으로 F 를 평가하여 얻은 Completion Record 로 둔다. thisArgumentuninitialized 이면 this 값은 초기화되지 않은 상태이며; 그렇지 않으면 thisArgumentthis 값을 제공한다. argumentsList 는 명명된 매개변수들을 제공한다. newTarget 은 NewTarget 값을 제공한다.
  11. NOTE: F 가 이 문서에서 정의된 경우 “the specification of F” 는 알고리즘 단계 등으로 기술된 그 동작을 의미한다.
  12. 실행 컨텍스트 스택에서 calleeContext 를 제거하고 callerContext 를 실행 중 실행 컨텍스트로 복원한다.
  13. result 를 반환한다.
Note

calleeContext 가 실행 컨텍스트 스택에서 제거될 때 접근 가능한 Generator 에 의해 suspend 및 보존되어 후속 재개가 예정된 경우 파괴되어서는 안 된다.

10.3.4 CreateBuiltinFunction ( behaviour, length, name, additionalInternalSlotsList [ , realm [ , prototype [ , prefix ] ] ] )

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), prototype (an Object or null), and prefix (a String) and returns a built-in function object. additionalInternalSlotsList 는 객체 일부로 정의되어야 하는 추가 내부 슬롯 이름을 담는다. 이 연산은 내장 함수 객체를 생성한다. It performs the following steps when called:

  1. realm 이 제공되지 않았다면 current Realm Record 로 설정한다.
  2. prototype 이 제공되지 않았다면 prototyperealm.[[Intrinsics]].[[%Function.prototype%]] 로 설정한다.
  3. internalSlotsList 를 곧 생성할 내장 함수 객체에 대해 10.3가 요구하는 모든 내부 슬롯 이름을 담는 List 로 둔다.
  4. additionalInternalSlotsList 의 요소들을 internalSlotsList 에 추가(Append)한다.
  5. func 를 새 내장 함수 객체로 두되, 호출 시 behaviour 가 지정한 매개변수에 제공 인수를 값으로 하여 behaviour 에 기술된 동작을 수행한다. 새 함수 객체internalSlotsList 요소 이름의 내부 슬롯과 [[InitialName]] 내부 슬롯을 가진다.
  6. func.[[Prototype]]prototype 으로 설정한다.
  7. func.[[Extensible]]true 로 설정한다.
  8. func.[[Realm]]realm 으로 설정한다.
  9. func.[[InitialName]]null 로 설정한다.
  10. SetFunctionLength(func, length) 를 수행한다.
  11. prefix 가 제공되지 않았다면
    1. SetFunctionName(func, name) 를 수행한다.
  12. 그렇지 않으면
    1. SetFunctionName(func, name, prefix) 를 수행한다.
  13. func 를 반환한다.

이 명세에 정의된 각 내장 함수는 CreateBuiltinFunction 추상 연산을 호출하여 생성된다.

10.4 내장 이그조틱 객체의 내부 메서드와 슬롯(Built-in Exotic Object Internal Methods and Slots)

이 명세는 여러 종류의 내장 이그조틱 객체를 정의한다. 이 객체들은 특정한 몇몇 상황을 제외하면 일반 객체와 유사하게 동작한다. 다음 이그조틱 객체들은 아래에서 명시적으로 달리 지정된 경우를 제외하고 일반 객체 내부 메서드를 사용한다:

10.4.1 바운드 함수 이그조틱 객체(Bound Function Exotic Objects)

바운드 함수 이그조틱 객체는 다른 함수 객체를 감싸는 이그조틱 객체이다. 바운드 함수 이그조틱 객체는 호출 가능(callable)하며([[Call]] 내부 메서드를 가지며 필요 시 [[Construct]] 내부 메서드도 가질 수 있음), 호출하면 보통 감싼 함수가 호출된다.

객체의 [[Call]] 및 (해당하는 경우) [[Construct]] 내부 메서드가 아래 구현을 사용하고, 그 외 핵심 내부 메서드가 10.1의 정의를 사용한다면 그 객체는 바운드 함수 이그조틱 객체이다. 이러한 메서드는 BoundFunctionCreate 에서 설치된다.

바운드 함수 이그조틱 객체Table 28에 나열된 ECMAScript 함수 객체의 내부 슬롯을 가지지 않는다. 대신 Table 29에 나열된 내부 슬롯을 [[Prototype]], [[Extensible]]와 더불어 가진다.

Table 29: 바운드 함수 이그조틱 객체의 내부 슬롯(Internal Slots of Bound Function Exotic Objects)
Internal Slot Type Description
[[BoundTargetFunction]] a callable Object 감싸진(wrapped) 함수 객체.
[[BoundThis]] an ECMAScript language value 감싸진 함수를 호출할 때 항상 this 값으로 전달되는 값.
[[BoundArguments]] a List of ECMAScript language values 감싸진 함수 호출 시 선행 인수로 사용되는 값들의 리스트.

10.4.1.1 [[Call]] ( thisArgument, argumentsList )

The [[Call]] internal method of 바운드 함수 이그조틱 객체 F takes arguments thisArgument (an ECMAScript language value) and argumentsList (a List of ECMAScript language values) and returns ECMAScript 언어 값 또는 throw completion 을 담는 normal completion. It performs the following steps when called:

  1. targetF.[[BoundTargetFunction]] 로 둔다.
  2. boundThisF.[[BoundThis]] 로 둔다.
  3. boundArgsF.[[BoundArguments]] 로 둔다.
  4. argsboundArgsargumentsList 의 리스트 연결(list-concatenation)으로 둔다.
  5. Call(target, boundThis, args) 를 반환한다.

10.4.1.2 [[Construct]] ( argumentsList, newTarget )

The [[Construct]] internal method of 바운드 함수 이그조틱 객체 F takes arguments argumentsList (a List of ECMAScript language values) and newTarget (a constructor) and returns 객체 또는 throw completion 을 담는 normal completion. It performs the following steps when called:

  1. targetF.[[BoundTargetFunction]] 로 둔다.
  2. 단언: IsConstructor(target) 는 true.
  3. boundArgsF.[[BoundArguments]] 로 둔다.
  4. argsboundArgsargumentsList 의 리스트 연결로 둔다.
  5. SameValue(F, newTarget) 가 true 이면 newTargettarget 으로 설정한다.
  6. Construct(target, args, newTarget) 를 반환한다.

10.4.1.3 BoundFunctionCreate ( targetFunction, boundThis, boundArgs )

The abstract operation BoundFunctionCreate takes arguments targetFunction (a function object), boundThis (an ECMAScript language value), and boundArgs (a List of ECMAScript language values) and returns 함수 객체 또는 throw completion 을 담는 normal completion. 새 바운드 함수 이그조틱 객체 생성을 명세하는 데 사용된다. It performs the following steps when called:

  1. proto 를 ? targetFunction.[[GetPrototypeOf]]() 로 둔다.
  2. internalSlotsList 를 « [[Prototype]], [[Extensible]] » 와 Table 29에 나열된 내부 슬롯의 리스트 연결로 둔다.
  3. objMakeBasicObject(internalSlotsList) 로 둔다.
  4. obj.[[Prototype]]proto 로 설정한다.
  5. obj.[[Call]]10.4.1.1에 기술된 대로 설정한다.
  6. IsConstructor(targetFunction) 가 true 이면
    1. obj.[[Construct]]10.4.1.2에 기술된 대로 설정한다.
  7. obj.[[BoundTargetFunction]]targetFunction 으로 설정한다.
  8. obj.[[BoundThis]]boundThis 로 설정한다.
  9. obj.[[BoundArguments]]boundArgs 로 설정한다.
  10. obj 를 반환한다.

10.4.2 배열(Array) 이그조틱 객체(Array Exotic Objects)

Array 는 배열 인덱스 프로퍼티 키(6.1.7 참조)에 특별 취급을 제공하는 이그조틱 객체이다. 프로퍼티 이름배열 인덱스인 프로퍼티를 element 라고도 부른다. 모든 Array 는 재정의 불가(non-configurable) "length" 프로퍼티를 가지며 그 값은 232 보다 작은 0 이상 정수 Number 이다. "length" 프로퍼티 값은 이름이 배열 인덱스인 모든 자체 프로퍼티 이름보다 수치적으로 크다; Array 의 자체 프로퍼티가 생성되거나 변경될 때마다 이 불변식을 유지하도록 다른 프로퍼티들이 필요 시 조정된다. 구체적으로 배열 인덱스 이름의 자체 프로퍼티가 추가되면 "length" 값은 필요 시 그 인덱스의 수치 값보다 1 큰 값으로 변경되고; "length" 값이 변경되면 새 length 보다 크거나 같았던 배열 인덱스 이름의 모든 자체 프로퍼티는 삭제된다. 이 제약은 Array 의 자체 프로퍼티에만 적용되며 프로토타입에서 상속될 수 있는 "length" 또는 배열 인덱스 프로퍼티에는 영향받지 않는다.

객체의 [[DefineOwnProperty]] 내부 메서드가 아래 구현을 사용하고 그 외 핵심 내부 메서드가 10.1의 정의를 사용하면 그 객체는 Array 이그조틱 객체(간단히 Array)이다. 이러한 메서드는 ArrayCreate 에서 설치된다.

10.4.2.1 [[DefineOwnProperty]] ( P, Desc )

The [[DefineOwnProperty]] internal method of Array 이그조틱 객체 A takes arguments P (a property key) and Desc (a Property Descriptor) and returns Boolean 또는 throw completion 을 담는 normal completion. It performs the following steps when called:

  1. P"length" 이면
    1. ArraySetLength(A, Desc) 를 반환한다.
  2. Else if P배열 인덱스이면
    1. lengthDescOrdinaryGetOwnProperty(A, "length") 로 둔다.
    2. 단언: lengthDescundefined 가 아님.
    3. 단언: IsDataDescriptor(lengthDesc) 는 true.
    4. 단언: lengthDesc.[[Configurable]]false.
    5. lengthlengthDesc.[[Value]] 로 둔다.
    6. 단언: length 는 0 이상 정수 Number.
    7. index 를 ! ToUint32(P) 로 둔다.
    8. indexlength 이고 lengthDesc.[[Writable]]false 이면 false 반환.
    9. succeeded 를 ! OrdinaryDefineOwnProperty(A, P, Desc) 로 둔다.
    10. succeededfalse 이면 false 반환.
    11. indexlength 이면
      1. lengthDesc.[[Value]]index + 1𝔽 로 설정.
      2. succeeded 를 ! OrdinaryDefineOwnProperty(A, "length", lengthDesc) 로 설정.
      3. 단언: succeededtrue.
    12. true 반환.
  3. OrdinaryDefineOwnProperty(A, P, Desc) 를 반환한다.

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 Array 이그조틱 객체 또는 throw completion 을 담는 normal completion. 새 Array 생성 명세에 사용된다. It performs the following steps when called:

  1. length > 232 - 1 이면 RangeError 예외 throw.
  2. proto 가 제공되지 않았다면 proto%Array.prototype% 으로 설정.
  3. AMakeBasicObject[[Prototype]], [[Extensible]] ») 로 둔다.
  4. A.[[Prototype]]proto 로 설정.
  5. A.[[DefineOwnProperty]]10.4.2.1에 지정된 대로 설정.
  6. OrdinaryDefineOwnProperty(A, "length", PropertyDescriptor { [[Value]]: 𝔽(length), [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false }) 수행.
  7. A 반환.

10.4.2.3 ArraySpeciesCreate ( originalArray, length )

The abstract operation ArraySpeciesCreate takes arguments originalArray (an Object) and length (a non-negative integer) and returns 객체 또는 throw completion 을 담는 normal completion. originalArray 에서 파생된 constructor 함수를 사용하여 새 Array 또는 유사 객체를 생성하는 과정을 명세한다. constructor 가 반드시 Array 를 반환하도록 강제하지 않는다. It performs the following steps when called:

  1. isArray 를 ? IsArray(originalArray) 로 둔다.
  2. isArrayfalse 이면 ? ArrayCreate(length) 반환.
  3. C 를 ? Get(originalArray, "constructor") 로 둔다.
  4. IsConstructor(C) 가 true 이면
    1. thisRealmcurrent Realm Record 로 둔다.
    2. realmC 를 ? GetFunctionRealm(C) 로 둔다.
    3. thisRealmrealmC 가 동일 Realm Record 가 아니면
      1. SameValue(C, realmC.[[Intrinsics]].[[%Array%]]) 가 true 이면 Cundefined 로 설정.
  5. C 가 Object 이면
    1. C 를 ? Get(C, %Symbol.species%) 로 설정.
    2. Cnull 이면 Cundefined 로 설정.
  6. Cundefined 이면 ? ArrayCreate(length) 반환.
  7. IsConstructor(C) 가 false 이면 TypeError 예외 throw.
  8. Construct(C, « 𝔽(length) ») 반환.
Note

originalArray 가 실행 중 실행 컨텍스트의 realm 이 아닌 realm 의 표준 내장 Array 생성자로 생성되었다면, 실행 중 실행 컨텍스트 realm 을 사용하여 새 Array 가 생성된다. 이는 ArraySpeciesCreate 로 정의된 Array.prototype 메서드들에 대해 역사적으로 그러한 동작을 가진 웹 브라우저와의 호환성을 유지한다.

10.4.2.4 ArraySetLength ( A, Desc )

The abstract operation ArraySetLength takes arguments A (an Array) and Desc (a Property Descriptor) and returns Boolean 또는 throw completion 을 담는 normal completion. It performs the following steps when called:

  1. Desc[[Value]] 필드를 가지지 않으면
    1. OrdinaryDefineOwnProperty(A, "length", Desc) 반환.
  2. newLenDescDesc 의 복사본으로 둔다.
  3. newLen 을 ? ToUint32(Desc.[[Value]]) 로 둔다.
  4. numberLen 을 ? ToNumber(Desc.[[Value]]) 로 둔다.
  5. SameValueZero(newLen, numberLen) 가 false 이면 RangeError 예외 throw.
  6. newLenDesc.[[Value]]newLen 으로 설정.
  7. oldLenDescOrdinaryGetOwnProperty(A, "length") 로 둔다.
  8. 단언: oldLenDescundefined 아님.
  9. 단언: IsDataDescriptor(oldLenDesc) 는 true.
  10. 단언: oldLenDesc.[[Configurable]]false.
  11. oldLenoldLenDesc.[[Value]] 로 둔다.
  12. newLenoldLen 이면
    1. OrdinaryDefineOwnProperty(A, "length", newLenDesc) 반환.
  13. oldLenDesc.[[Writable]]false 이면 false 반환.
  14. newLenDesc[[Writable]] 필드를 가지지 않거나 newLenDesc.[[Writable]]true 이면
    1. newWritabletrue 로 둔다.
  15. Else
    1. NOTE: 어떤 element 를 삭제할 수 없는 경우를 대비하여 [[Writable]]false 로 설정하는 것을 지연.
    2. newWritablefalse 로 둔다.
    3. newLenDesc.[[Writable]]true 로 설정.
  16. succeeded 를 ! OrdinaryDefineOwnProperty(A, "length", newLenDesc) 로 둔다.
  17. succeededfalse 이면 false 반환.
  18. A 의 각 자체 프로퍼티 키 PP배열 인덱스이고 ! ToUint32(P) ≥ newLen 인 것들을 내림차순 숫자 인덱스 순으로 순회하며
    1. deleteSucceeded 를 ! A.[[Delete]](P) 로 둔다.
    2. deleteSucceededfalse 이면
      1. newLenDesc.[[Value]] 를 ! ToUint32(P) + 1𝔽 로 설정.
      2. newWritablefalse 이면 newLenDesc.[[Writable]]false 로 설정.
      3. OrdinaryDefineOwnProperty(A, "length", newLenDesc) 수행.
      4. false 반환.
  19. newWritablefalse 이면
    1. succeeded 를 ! OrdinaryDefineOwnProperty(A, "length", PropertyDescriptor { [[Writable]]: false }) 로 설정.
    2. 단언: succeededtrue.
  20. true 반환.
Note

34 단계에서 Desc.[[Value]] 가 객체이면 그 valueOf 메서드는 두 번 호출된다. 이는 명세 2부터 이런 효과로 규정된 레거시 동작이다.

10.4.3 문자열(String) 이그조틱 객체(String Exotic Objects)

String 객체는 String 값을 캡슐화하고 그 String 값의 개별 코드 유닛 요소에 해당하는 가상 정수 인덱스 데이터 프로퍼티를 노출하는 이그조틱 객체이다. String 이그조틱 객체는 캡슐화된 String 값 길이를 값으로 갖는 "length" 데이터 프로퍼티를 항상 가진다. 코드 유닛 데이터 프로퍼티"length" 프로퍼티 모두 쓰기 불가능 및 재정의 불가이다.

객체의 [[GetOwnProperty]], [[DefineOwnProperty]], [[OwnPropertyKeys]] 내부 메서드가 아래 구현을 사용하고 그 외 핵심 내부 메서드가 10.1 정의를 사용하면 그 객체는 String 이그조틱 객체(간단히 String 객체)이다. 이러한 메서드는 StringCreate 에서 설치된다.

String 이그조틱 객체일반 객체와 동일한 내부 슬롯을 갖는다. 추가로 [[StringData]] 내부 슬롯을 가진다.

10.4.3.1 [[GetOwnProperty]] ( P )

The [[GetOwnProperty]] internal method of String 이그조틱 객체 S takes argument P (a property key) and returns Property Descriptor 또는 undefined 를 담는 normal completion. It performs the following steps when called:

  1. descOrdinaryGetOwnProperty(S, P) 로 둔다.
  2. descundefined 가 아니면 desc 반환.
  3. StringGetOwnProperty(S, P) 반환.

10.4.3.2 [[DefineOwnProperty]] ( P, Desc )

The [[DefineOwnProperty]] internal method of String 이그조틱 객체 S takes arguments P (a property key) and Desc (a Property Descriptor) and returns Boolean 을 담는 normal completion. It performs the following steps when called:

  1. stringDescStringGetOwnProperty(S, P) 로 둔다.
  2. stringDescundefined 가 아니면
    1. extensibleS.[[Extensible]] 로 둔다.
    2. IsCompatiblePropertyDescriptor(extensible, Desc, stringDesc) 반환.
  3. OrdinaryDefineOwnProperty(S, P, Desc) 반환.

10.4.3.3 [[OwnPropertyKeys]] ( )

The [[OwnPropertyKeys]] internal method of String 이그조틱 객체 O takes no arguments and returns 프로퍼티 키 List 를 담는 normal completion. It performs the following steps when called:

  1. keys 를 새 빈 List 로 둔다.
  2. strO.[[StringData]] 로 둔다.
  3. 단언: str 은 String.
  4. lenstr 의 길이로 둔다.
  5. 0 ≤ i < len 인 각 정수 i 에 대해 오름차순으로
    1. ToString(𝔽(i)) 를 keys 에 추가.
  6. O 의 각 자체 프로퍼티 키 PP배열 인덱스이며 ! ToIntegerOrInfinity(P) ≥ len 인 것들을 숫자 인덱스 오름차순으로
    1. Pkeys 에 추가.
  7. O 의 각 자체 프로퍼티 키 PP 가 String 이고 배열 인덱스가 아닌 것들을 생성 시점 시간 순으로
    1. Pkeys 에 추가.
  8. O 의 각 자체 프로퍼티 키 PP 가 Symbol 인 것들을 생성 시점 시간 순으로
    1. Pkeys 에 추가.
  9. keys 반환.

10.4.3.4 StringCreate ( value, prototype )

The abstract operation StringCreate takes arguments value (a String) and prototype (an Object) and returns String 이그조틱 객체. 새 String 이그조틱 객체 생성 명세에 사용된다. It performs the following steps when called:

  1. SMakeBasicObject[[Prototype]], [[Extensible]], [[StringData]] ») 로 둔다.
  2. S.[[Prototype]]prototype 으로 설정.
  3. S.[[StringData]]value 로 설정.
  4. S.[[GetOwnProperty]]10.4.3.1에 지정된 대로 설정.
  5. S.[[DefineOwnProperty]]10.4.3.2에 지정된 대로 설정.
  6. S.[[OwnPropertyKeys]]10.4.3.3에 지정된 대로 설정.
  7. lengthvalue 길이로 둔다.
  8. DefinePropertyOrThrow(S, "length", PropertyDescriptor { [[Value]]: 𝔽(length), [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }) 수행.
  9. S 반환.

10.4.3.5 StringGetOwnProperty ( S, P )

The abstract operation StringGetOwnProperty takes arguments S (an Object that has a [[StringData]] internal slot) and P (a property key) and returns a Property Descriptor or undefined. It performs the following steps when called:

  1. P 가 String 이 아니면 undefined 반환.
  2. indexCanonicalNumericIndexString(P) 로 둔다.
  3. index 가 정수 Number 가 아니면 undefined 반환.
  4. index-0𝔽 이거나 index < -0𝔽 이면 undefined 반환.
  5. strS.[[StringData]] 로 둔다.
  6. 단언: str 은 String.
  7. lenstr 길이로 둔다.
  8. (index) ≥ len 이면 undefined 반환.
  9. resultStrstr(index) 부터 (index) + 1 까지 부분 문자열로 둔다.
  10. PropertyDescriptor { [[Value]]: resultStr, [[Writable]]: false, [[Enumerable]]: true, [[Configurable]]: false } 반환.

10.4.4 Arguments 이그조틱 객체(Arguments Exotic Objects)

대부분의 ECMAScript 함수는 코드에서 사용할 수 있는 arguments 객체를 제공한다. 함수 정의 특성에 따라 그 arguments 객체는 일반 객체이거나 arguments 이그조틱 객체가 된다. arguments 이그조틱 객체배열 인덱스 프로퍼티들이 관련 ECMAScript 함수 호출의 형식 매개변수 바인딩에 매핑되는 이그조틱 객체이다.

객체의 내부 메서드가 아래 구현을 사용하고 여기 명시되지 않은 메서드는 10.1의 정의를 사용하면 그 객체는 arguments 이그조틱 객체이다. 이러한 메서드는 CreateMappedArgumentsObject 에서 설치된다.

Note 1

CreateUnmappedArgumentsObject 는 이 절에 묶여 있지만, 이그조틱이 아닌 일반 객체를 생성한다.

Arguments 이그조틱 객체일반 객체와 동일한 내부 슬롯을 가지며 추가로 [[ParameterMap]] 내부 슬롯을 가진다. 일반 arguments 객체 또한 값이 항상 undefined[[ParameterMap]] 내부 슬롯을 갖는다. 일반 arguments 객체의 [[ParameterMap]] 내부 슬롯은 Object.prototype.toString (20.1.3.6)이 그것을 식별하는 데만 사용된다.

Note 2

arguments 이그조틱 객체 중 숫자 이름 값이 대응 함수 객체의 형식 매개변수 수보다 작은 정수 인덱스 데이터 프로퍼티는 초기에는 함수 실행 컨텍스트의 해당 인자 바인딩과 값을 공유한다. 즉 프로퍼티를 바꾸면 매개변수 바인딩 값도 바뀌며 그 반대도 같다. 이 대응 관계는 그러한 프로퍼티가 삭제 후 재정의되거나 접근자 프로퍼티로 바뀌면 끊어진다. arguments 객체가 일반 객체인 경우 그 프로퍼티 값은 단지 전달된 인자의 복사이며 동적 연결은 없다.

Note 3

ParameterMap 객체와 그 프로퍼티 값들은 arguments 객체와 인자 바인딩 간의 대응 관계를 명세하기 위한 장치이다. ParameterMap 객체와 그 프로퍼티 값 객체들은 ECMAScript 코드에서 직접 관측될 수 없다. 구현은 명세된 의미론을 위해 실제로 이러한 객체를 생성하거나 사용할 필요가 없다.

Note 4

일반 arguments 객체는 접근 시 TypeError 예외를 throw 하는 재정의 불가 accessor 프로퍼티 "callee" 를 정의한다. "callee" 프로퍼티는 non‑strict 함수 일부에 대해서만 생성되는 arguments 이그조틱 객체에서 더 구체적 의미를 가진다. 일반 변형에서의 정의는 적합한 구현이 다른 방식으로 정의하지 못하도록 하기 위함이다.

Note 5

역사적으로 arguments 이그조틱 객체 구현은 "caller" 라는 accessor 프로퍼티를 포함했다. ECMAScript 2017 이전 명세는 일반 arguments 객체에 throwing "caller" 프로퍼티 정의를 포함했다. 구현이 더 이상 이 확장을 포함하지 않으므로 ECMAScript 2017 은 throwing "caller" accessor 요구를 제거했다.

10.4.4.1 [[GetOwnProperty]] ( P )

The [[GetOwnProperty]] internal method of arguments 이그조틱 객체 args takes argument P (a property key) and returns Property Descriptor 또는 undefined 를 담는 normal completion. It performs the following steps when called:

  1. descOrdinaryGetOwnProperty(args, P) 로 둔다.
  2. descundefined 이면 undefined 반환.
  3. mapargs.[[ParameterMap]] 로 둔다.
  4. isMapped 를 ! HasOwnProperty(map, P) 로 둔다.
  5. isMappedtrue 이면
    1. desc.[[Value]] 를 ! Get(map, P) 로 설정.
  6. desc 반환.

10.4.4.2 [[DefineOwnProperty]] ( P, Desc )

The [[DefineOwnProperty]] internal method of arguments 이그조틱 객체 args takes arguments P (a property key) and Desc (a Property Descriptor) and returns Boolean 을 담는 normal completion. It performs the following steps when called:

  1. mapargs.[[ParameterMap]] 로 둔다.
  2. isMapped 를 ! HasOwnProperty(map, P) 로 둔다.
  3. newArgDescDesc 로 둔다.
  4. isMappedtrue 이고 IsDataDescriptor(Desc) 가 true 이면
    1. Desc[[Value]] 필드를 갖지 않고 [[Writable]] 필드를 가지며 그 값이 false 이면
      1. newArgDescDesc 복사본으로 둔다.
      2. newArgDesc.[[Value]] 를 ! Get(map, P) 로 설정.
  5. allowed 를 ! OrdinaryDefineOwnProperty(args, P, newArgDesc) 로 둔다.
  6. allowedfalse 이면 false 반환.
  7. isMappedtrue 이면
    1. IsAccessorDescriptor(Desc) 가 true 이면
      1. map.[[Delete]](P) 수행.
    2. Else
      1. Desc[[Value]] 필드를 가지면
        1. 단언: arguments 객체가 매핑한 형식 매개변수는 항상 writable 이므로 Set 성공.
        2. Set(map, P, Desc.[[Value]], false) 수행.
      2. Desc[[Writable]] 필드를 가지고 그 값이 false 이면
        1. map.[[Delete]](P) 수행.
  8. true 반환.

10.4.4.3 [[Get]] ( P, Receiver )

The [[Get]] internal method of arguments 이그조틱 객체 args takes arguments P (a property key) and Receiver (an ECMAScript language value) and returns ECMAScript 언어 값 또는 throw completion 을 담는 normal completion. It performs the following steps when called:

  1. mapargs.[[ParameterMap]] 로 둔다.
  2. isMapped 를 ! HasOwnProperty(map, P) 로 둔다.
  3. isMappedfalse 이면
    1. OrdinaryGet(args, P, Receiver) 반환.
  4. Else
    1. 단언: mapP 에 대한 형식 매개변수 매핑을 포함.
    2. Get(map, P) 반환.

10.4.4.4 [[Set]] ( P, V, Receiver )

The [[Set]] internal method of arguments 이그조틱 객체 args takes arguments P (a property key), V (an ECMAScript language value), and Receiver (an ECMAScript language value) and returns Boolean 또는 throw completion 을 담는 normal completion. It performs the following steps when called:

  1. SameValue(args, Receiver) 가 false 이면
    1. isMappedfalse 로 둔다.
  2. Else
    1. mapargs.[[ParameterMap]] 로 둔다.
    2. isMapped 를 ! HasOwnProperty(map, P) 로 둔다.
  3. isMappedtrue 이면
    1. 단언: 아래 Set 은 성공 (매핑된 형식 매개변수는 항상 writable).
    2. Set(map, P, V, false) 수행.
  4. OrdinarySet(args, P, V, Receiver) 반환.

10.4.4.5 [[Delete]] ( P )

The [[Delete]] internal method of arguments 이그조틱 객체 args takes argument P (a property key) and returns Boolean 또는 throw completion 을 담는 normal completion. It performs the following steps when called:

  1. mapargs.[[ParameterMap]] 로 둔다.
  2. isMapped 를 ! HasOwnProperty(map, P) 로 둔다.
  3. result 를 ? OrdinaryDelete(args, P) 로 둔다.
  4. resulttrue 이고 isMappedtrue 이면
    1. map.[[Delete]](P) 수행.
  5. result 반환.

10.4.4.6 CreateUnmappedArgumentsObject ( argumentsList )

The abstract operation CreateUnmappedArgumentsObject takes argument argumentsList (a List of ECMAScript language values) and returns an ordinary object. It performs the following steps when called:

  1. lenargumentsList 요소 개수로 둔다.
  2. objOrdinaryObjectCreate(%Object.prototype%, « [[ParameterMap]] ») 로 둔다.
  3. obj.[[ParameterMap]]undefined 로 설정.
  4. DefinePropertyOrThrow(obj, "length", PropertyDescriptor { [[Value]]: 𝔽(len), [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: true }) 수행.
  5. index 를 0 으로 둔다.
  6. index < len 인 동안 반복
    1. valargumentsList[index] 로 둔다.
    2. CreateDataPropertyOrThrow(obj, ! ToString(𝔽(index)), val) 수행.
    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, argumentsList, env )

The abstract operation CreateMappedArgumentsObject takes arguments func (an Object), formals (a Parse Node), argumentsList (a List of ECMAScript language values), and env (an Environment Record) and returns an arguments exotic object. It performs the following steps when called:

  1. 단언: formals 는 rest 매개변수, 바인딩 패턴, 초기화자를 포함하지 않는다. 중복 식별자는 있을 수 있다.
  2. lenargumentsList 요소 개수로 둔다.
  3. objMakeBasicObject[[Prototype]], [[Extensible]], [[ParameterMap]] ») 로 둔다.
  4. obj.[[GetOwnProperty]]10.4.4.1에 지정된 대로 설정.
  5. obj.[[DefineOwnProperty]]10.4.4.2에 지정된 대로 설정.
  6. obj.[[Get]]10.4.4.3에 지정된 대로 설정.
  7. obj.[[Set]]10.4.4.4에 지정된 대로 설정.
  8. obj.[[Delete]]10.4.4.5에 지정된 대로 설정.
  9. obj.[[Prototype]]%Object.prototype% 으로 설정.
  10. mapOrdinaryObjectCreate(null) 로 둔다.
  11. obj.[[ParameterMap]]map 으로 설정.
  12. parameterNamesformals 의 BoundNames 로 둔다.
  13. numberOfParametersparameterNames 요소 개수로 둔다.
  14. index 를 0 으로 둔다.
  15. index < len 인 동안 반복
    1. valargumentsList[index] 로 둔다.
    2. CreateDataPropertyOrThrow(obj, ! ToString(𝔽(index)), val) 수행.
    3. indexindex + 1 로 설정.
  16. DefinePropertyOrThrow(obj, "length", PropertyDescriptor { [[Value]]: 𝔽(len), [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: true }) 수행.
  17. mappedNames 를 새 빈 List 로 둔다.
  18. indexnumberOfParameters - 1 로 설정.
  19. index ≥ 0 인 동안 반복
    1. nameparameterNames[index] 로 둔다.
    2. mappedNamesname 을 포함하지 않으면
      1. mappedNamesname 추가.
      2. index < len 이면
        1. gMakeArgGetter(name, env) 로 둔다.
        2. pMakeArgSetter(name, env) 로 둔다.
        3. map.[[DefineOwnProperty]](! ToString(𝔽(index)), PropertyDescriptor { [[Set]]: p, [[Get]]: g, [[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, env )

The abstract operation MakeArgGetter takes arguments name (a String) and env (an Environment Record) and returns a function object. 실행 시 env 에서 name 에 바인딩된 값을 반환하는 내장 함수 객체를 생성한다. It performs the following steps when called:

  1. getterClosure 를 매개변수 없고 name, env 를 캡처하며 호출 시 다음 단계를 수행하는 새 Abstract Closure 로 둔다:
    1. NormalCompletion(! env.GetBindingValue(name, false)) 반환.
  2. getterCreateBuiltinFunction(getterClosure, 0, "", « ») 로 둔다.
  3. NOTE: getter 는 ECMAScript 코드에서 직접 접근 불가.
  4. getter 반환.

10.4.4.7.2 MakeArgSetter ( name, env )

The abstract operation MakeArgSetter takes arguments name (a String) and env (an Environment Record) and returns a function object. 실행 시 env 에서 name 에 바인딩된 값을 설정하는 내장 함수 객체를 생성한다. It performs the following steps when called:

  1. setterClosure 를 매개변수 (value) 를 가지며 name, env 를 캡처하고 호출 시 다음을 수행하는 새 Abstract Closure 로 둔다:
    1. NormalCompletion(! env.SetMutableBinding(name, value, false)) 반환.
  2. setterCreateBuiltinFunction(setterClosure, 1, "", « ») 로 둔다.
  3. NOTE: setter 는 ECMAScript 코드에서 직접 접근 불가.
  4. setter 반환.

10.4.5 TypedArray 이그조틱 객체(TypedArray Exotic Objects)

TypedArray 는 정규화 수치 문자열(canonical numeric string) 프로퍼티 키를 특별 처리하고 그 중 경계 내(in-bounds) 정수 인덱스를 균일 타입 요소에 매핑하며 나머지는 프로토타입 체인 탐색 없이 부재로 유지하는 이그조틱 객체이다.

Note

임의의 Number n 에 대해 ToString(n)이 정규화 수치 문자열이므로, 구현은 실제 문자열 변환 없이 Number 를 TypedArray 프로퍼티 키로 다룰 수 있다.

TypedArray일반 객체와 동일한 내부 슬롯을 가지며 추가로 [[ViewedArrayBuffer]], [[TypedArrayName]], [[ContentType]], [[ByteLength]], [[ByteOffset]], [[ArrayLength]] 내부 슬롯을 가진다.

객체의 [[PreventExtensions]], [[GetOwnProperty]], [[HasProperty]], [[DefineOwnProperty]], [[Get]], [[Set]], [[Delete]], [[OwnPropertyKeys]] 내부 메서드가 이 절의 정의를 사용하고 그 외 핵심 내부 메서드가 10.1 정의를 사용하면 그 객체는 TypedArray 이다. 이러한 메서드는 TypedArrayCreate 에 의해 설치된다.

10.4.5.1 [[PreventExtensions]] ( )

The [[PreventExtensions]] internal method of TypedArray O takes no arguments and returns Boolean 을 담는 normal completion. It performs the following steps when called:

  1. NOTE: 6.1.7.3에 규정된 확장성 관련 불변식은 O 가 프로퍼티를 얻거나(또는 잃고 다시 얻을) 수 있는 경우 true 를 반환하지 못하게 한다; 이는 underlying buffer 가 resize 될 때 정수 인덱스 이름 프로퍼티에서 발생할 수 있다.
  2. IsTypedArrayFixedLength(O) 가 false 이면 false 반환.
  3. OrdinaryPreventExtensions(O) 반환.

10.4.5.2 [[GetOwnProperty]] ( P )

The [[GetOwnProperty]] internal method of TypedArray O takes argument P (a property key) and returns Property Descriptor 또는 undefined 를 담는 normal completion. It performs the following steps when called:

  1. P 가 String 이면
    1. numericIndexCanonicalNumericIndexString(P) 로 둔다.
    2. numericIndexundefined 가 아니면
      1. valueTypedArrayGetElement(O, numericIndex) 로 둔다.
      2. valueundefined 이면 undefined 반환.
      3. PropertyDescriptor { [[Value]]: value, [[Writable]]: true, [[Enumerable]]: true, [[Configurable]]: true } 반환.
  2. OrdinaryGetOwnProperty(O, P) 반환.

10.4.5.3 [[HasProperty]] ( P )

The [[HasProperty]] internal method of TypedArray O takes argument P (a property key) and returns Boolean 또는 throw completion 을 담는 normal completion. It performs the following steps when called:

  1. P 가 String 이면
    1. numericIndexCanonicalNumericIndexString(P) 로 둔다.
    2. numericIndexundefined 가 아니면 IsValidIntegerIndex(O, numericIndex) 반환.
  2. OrdinaryHasProperty(O, P) 반환.

10.4.5.4 [[DefineOwnProperty]] ( P, Desc )

The [[DefineOwnProperty]] internal method of TypedArray O takes arguments P (a property key) and Desc (a Property Descriptor) and returns Boolean 또는 throw completion 을 담는 normal completion. It performs the following steps when called:

  1. P 가 String 이면
    1. numericIndexCanonicalNumericIndexString(P) 로 둔다.
    2. numericIndexundefined 가 아니면
      1. IsValidIntegerIndex(O, numericIndex) 가 false 이면 false 반환.
      2. Desc[[Configurable]] 필드가 있고 그 값이 false 이면 false 반환.
      3. Desc[[Enumerable]] 필드가 있고 그 값이 false 이면 false 반환.
      4. IsAccessorDescriptor(Desc) 가 true 이면 false 반환.
      5. Desc[[Writable]] 필드가 있고 그 값이 false 이면 false 반환.
      6. Desc[[Value]] 필드가 있으면 ? TypedArraySetElement(O, numericIndex, Desc.[[Value]]) 수행.
      7. true 반환.
  2. OrdinaryDefineOwnProperty(O, P, Desc) 반환.

10.4.5.5 [[Get]] ( P, Receiver )

The [[Get]] internal method of TypedArray O takes arguments P (a property key) and Receiver (an ECMAScript language value) and returns ECMAScript 언어 값 또는 throw completion 을 담는 normal completion. It performs the following steps when called:

  1. P 가 String 이면
    1. numericIndexCanonicalNumericIndexString(P) 로 둔다.
    2. numericIndexundefined 가 아니면
      1. TypedArrayGetElement(O, numericIndex) 반환.
  2. OrdinaryGet(O, P, Receiver) 반환.

10.4.5.6 [[Set]] ( P, V, Receiver )

The [[Set]] internal method of TypedArray O takes arguments P (a property key), V (an ECMAScript language value), and Receiver (an ECMAScript language value) and returns Boolean 또는 throw completion 을 담는 normal completion. It performs the following steps when called:

  1. P 가 String 이면
    1. numericIndexCanonicalNumericIndexString(P) 로 둔다.
    2. numericIndexundefined 가 아니면
      1. SameValue(O, Receiver) 가 true 이면
        1. TypedArraySetElement(O, numericIndex, V) 수행.
        2. true 반환.
      2. IsValidIntegerIndex(O, numericIndex) 가 false 이면 true 반환.
  2. OrdinarySet(O, P, V, Receiver) 반환.

10.4.5.7 [[Delete]] ( P )

The [[Delete]] internal method of TypedArray O takes argument P (a property key) and returns Boolean 을 담는 normal completion. It performs the following steps when called:

  1. P 가 String 이면
    1. numericIndexCanonicalNumericIndexString(P) 로 둔다.
    2. numericIndexundefined 가 아니면
      1. IsValidIntegerIndex(O, numericIndex) 가 false 이면 true 반환; else false 반환.
  2. OrdinaryDelete(O, P) 반환.

10.4.5.8 [[OwnPropertyKeys]] ( )

The [[OwnPropertyKeys]] internal method of TypedArray O takes no arguments and returns 프로퍼티 키 List 를 담는 normal completion. It performs the following steps when called:

  1. taRecordMakeTypedArrayWithBufferWitnessRecord(O, seq-cst) 로 둔다.
  2. keys 를 새 빈 List 로 둔다.
  3. IsTypedArrayOutOfBounds(taRecord) 가 false 이면
    1. lengthTypedArrayLength(taRecord) 로 둔다.
    2. 0 ≤ i < length 인 각 정수 i 에 대해 오름차순으로
      1. ToString(𝔽(i)) 를 keys 에 추가.
  4. O 의 각 자체 프로퍼티 키 PP 가 String 이고 정수 인덱스가 아닌 것들을 생성 시점 시간 순으로
    1. Pkeys 에 추가.
  5. O 의 각 자체 프로퍼티 키 PP 가 Symbol 인 것들을 생성 시점 시간 순으로
    1. Pkeys 에 추가.
  6. keys 반환.

10.4.5.9 버퍼 증인 레코드가 있는 TypedArray (TypedArray With Buffer Witness Records)

TypedArray With Buffer Witness RecordTypedArray 와, 보기 버퍼(viewed buffer)의 캐시된 byte length 를 함께 캡슐화하는 Record 값이다. growable SharedArrayBuffer 를 보는 경우 byte length 데이터 블록에 대한 단일 공유 메모리 읽기 이벤트를 보장하는 데 사용된다.

TypedArray With Buffer Witness Record 는 Table 30에 나온 필드를 가진다.

Table 30: TypedArray With Buffer Witness Record Fields
Field Name Value Meaning
[[Object]] a TypedArray 버퍼 byte length 가 로드된 TypedArray.
[[CachedBufferByteLength]] a non-negative integer or detached Record 생성 시 객체의 [[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. Else
    1. byteLengthArrayBufferByteLength(buffer, order) 로 둔다.
  4. TypedArray With Buffer Witness Record { [[Object]]: obj, [[CachedBufferByteLength]]: byteLength } 를 반환.

10.4.5.11 TypedArrayCreate ( prototype )

The abstract operation TypedArrayCreate takes argument prototype (an Object) and returns a TypedArray. 새 TypedArray 생성 명세에 사용된다. It performs the following steps when called:

  1. internalSlotsList 를 « [[Prototype]], [[Extensible]], [[ViewedArrayBuffer]], [[TypedArrayName]], [[ContentType]], [[ByteLength]], [[ByteOffset]], [[ArrayLength]] » 로 둔다.
  2. AMakeBasicObject(internalSlotsList) 로 둔다.
  3. A.[[PreventExtensions]]10.4.5.1에 지정된 대로 설정.
  4. A.[[GetOwnProperty]]10.4.5.2에 지정된 대로 설정.
  5. A.[[HasProperty]]10.4.5.3에 지정된 대로 설정.
  6. A.[[DefineOwnProperty]]10.4.5.4에 지정된 대로 설정.
  7. A.[[Get]]10.4.5.5에 지정된 대로 설정.
  8. A.[[Set]]10.4.5.6에 지정된 대로 설정.
  9. A.[[Delete]]10.4.5.7에 지정된 대로 설정.
  10. A.[[OwnPropertyKeys]]10.4.5.8에 지정된 대로 설정.
  11. A.[[Prototype]]prototype 으로 설정.
  12. A 반환.

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. IsTypedArrayOutOfBounds(taRecord) 가 true 이면 0 반환.
  2. lengthTypedArrayLength(taRecord) 로 둔다.
  3. length = 0 이면 0 반환.
  4. OtaRecord.[[Object]] 로 둔다.
  5. O.[[ByteLength]]auto 가 아니면 O.[[ByteLength]] 반환.
  6. elementSizeTypedArrayElementSize(O) 로 둔다.
  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. 단언: IsTypedArrayOutOfBounds(taRecord) 는 false.
  2. OtaRecord.[[Object]] 로 둔다.
  3. O.[[ArrayLength]]auto 가 아니면 O.[[ArrayLength]] 반환.
  4. 단언: IsFixedLengthArrayBuffer(O.[[ViewedArrayBuffer]]) 는 false.
  5. byteOffsetO.[[ByteOffset]] 로 둔다.
  6. elementSizeTypedArrayElementSize(O) 로 둔다.
  7. byteLengthtaRecord.[[CachedBufferByteLength]] 로 둔다.
  8. 단언: 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. 객체의 어떤 수치 프로퍼티라도 underlying buffer 범위를 벗어난 인덱스 값을 참조하는지 검사한다. It performs the following steps when called:

  1. OtaRecord.[[Object]] 로 둔다.
  2. bufferByteLengthtaRecord.[[CachedBufferByteLength]] 로 둔다.
  3. 단언: IsDetachedBuffer(O.[[ViewedArrayBuffer]]) 는 bufferByteLengthdetached 일 때 그리고 그럴 때에만 true.
  4. bufferByteLengthdetached 이면 true 반환.
  5. byteOffsetStartO.[[ByteOffset]] 로 둔다.
  6. O.[[ArrayLength]]auto 이면
    1. byteOffsetEndbufferByteLength 로 둔다.
  7. Else
    1. elementSizeTypedArrayElementSize(O) 로 둔다.
    2. byteOffsetEndbyteOffsetStart + O.[[ArrayLength]] × elementSize 로 둔다.
  8. byteOffsetStart > bufferByteLength 또는 byteOffsetEnd > bufferByteLength 이면 true 반환.
  9. NOTE: 길이 0 TypedArray 는 out-of-bounds 로 간주되지 않는다.
  10. false 반환.

10.4.5.15 IsTypedArrayFixedLength ( O )

The abstract operation IsTypedArrayFixedLength takes argument O (a TypedArray) and returns a Boolean. It performs the following steps when called:

  1. O.[[ArrayLength]]auto 이면 false 반환.
  2. bufferO.[[ViewedArrayBuffer]] 로 둔다.
  3. IsFixedLengthArrayBuffer(buffer) 가 false 이고 IsSharedArrayBuffer(buffer) 가 false 이면 false 반환.
  4. true 반환.

10.4.5.16 IsValidIntegerIndex ( O, index )

The abstract operation IsValidIntegerIndex takes arguments O (a TypedArray) and index (a Number) and returns a Boolean. It performs the following steps when called:

  1. IsDetachedBuffer(O.[[ViewedArrayBuffer]]) 가 true 이면 false 반환.
  2. index 가 정수 Number 가 아니면 false 반환.
  3. index-0𝔽 이거나 index < -0𝔽 이면 false 반환.
  4. taRecordMakeTypedArrayWithBufferWitnessRecord(O, unordered) 로 둔다.
  5. NOTE: O 의 버퍼가 growable SharedArrayBuffer 일 때 경계 검사(bound check)는 동기화 연산이 아니다.
  6. IsTypedArrayOutOfBounds(taRecord) 가 true 이면 false 반환.
  7. lengthTypedArrayLength(taRecord) 로 둔다.
  8. (index) ≥ length 이면 false 반환.
  9. true 반환.

10.4.5.17 TypedArrayGetElement ( O, index )

The abstract operation TypedArrayGetElement takes arguments O (a TypedArray) and index (a Number) and returns a Number, a BigInt, or undefined. It performs the following steps when called:

  1. IsValidIntegerIndex(O, index) 가 false 이면 undefined 반환.
  2. offsetO.[[ByteOffset]] 로 둔다.
  3. elementSizeTypedArrayElementSize(O) 로 둔다.
  4. byteIndexInBuffer 를 ((index) × elementSize) + offset 으로 둔다.
  5. elementTypeTypedArrayElementType(O) 로 둔다.
  6. GetValueFromBuffer(O.[[ViewedArrayBuffer]], byteIndexInBuffer, elementType, true, unordered) 반환.

10.4.5.18 TypedArraySetElement ( O, index, value )

The abstract operation TypedArraySetElement takes arguments O (a TypedArray), index (a Number), and value (an ECMAScript language value) and returns unused 또는 throw completion 을 담는 normal completion. It performs the following steps when called:

  1. O.[[ContentType]]bigint 이면 numValue 를 ? ToBigInt(value) 로 둔다.
  2. 아니면 numValue 를 ? ToNumber(value) 로 둔다.
  3. IsValidIntegerIndex(O, index) 가 true 이면
    1. offsetO.[[ByteOffset]] 로 둔다.
    2. elementSizeTypedArrayElementSize(O) 로 둔다.
    3. byteIndexInBuffer 를 ((index) × elementSize) + offset 으로 둔다.
    4. elementTypeTypedArrayElementType(O) 로 둔다.
    5. SetValueInBuffer(O.[[ViewedArrayBuffer]], byteIndexInBuffer, elementType, numValue, true, unordered) 수행.
  4. unused 반환.
Note

이 연산은 항상 성공하는 것처럼 보이나, TypedArray 끝을 넘어 쓰거나 분리(detached)된 ArrayBuffer 기반 TypedArray 에 쓰려 할 때는 효과가 없다.

10.4.5.19 IsArrayBufferViewOutOfBounds ( O )

The abstract operation IsArrayBufferViewOutOfBounds takes argument O (a TypedArray or a DataView) and returns a Boolean. TypedArray 의 수치 프로퍼티 또는 DataView 메서드가 underlying data block 범위를 벗어난 인덱스 값을 참조할 수 있는지 검사한다. 상위(spec) 명세 편의를 위해 존재. It performs the following steps when called:

  1. O[[DataView]] 내부 슬롯을 가지면
    1. viewRecordMakeDataViewWithBufferWitnessRecord(O, seq-cst) 로 둔다.
    2. IsViewOutOfBounds(viewRecord) 반환.
  2. taRecordMakeTypedArrayWithBufferWitnessRecord(O, seq-cst) 로 둔다.
  3. IsTypedArrayOutOfBounds(taRecord) 반환.

10.4.6 모듈 네임스페이스 이그조틱 객체(Module Namespace Exotic Objects)

모듈 네임스페이스 이그조틱 객체는 ECMAScript Module에서 export 된 바인딩을 노출하는 이그조틱 객체이다(16.2.3 참조). 모듈 네임스페이스 이그조틱 객체의 String-keyed 자체 프로퍼티와 Module 이 export 한 바인딩 이름 사이엔 1:1 대응이 있다. export 된 바인딩에는 export * 로 간접 export 된 바인딩도 포함된다. 각 String 값인 자체 프로퍼티 키는 해당 export 바인딩 이름의 StringValue 이다. 이들이 모듈 네임스페이스 이그조틱 객체의 유일한 String-keyed 프로퍼티이다. 각 프로퍼티는 { [[Writable]]: true, [[Enumerable]]: true, [[Configurable]]: false } 속성을 가진다. 모듈 네임스페이스 이그조틱 객체는 비확장(extensible 아님)이다.

객체의 [[GetPrototypeOf]], [[SetPrototypeOf]], [[IsExtensible]], [[PreventExtensions]], [[GetOwnProperty]], [[DefineOwnProperty]], [[HasProperty]], [[Get]], [[Set]], [[Delete]], [[OwnPropertyKeys]] 내부 메서드가 이 절의 정의를 사용하고 그 외 핵심 내부 메서드가 10.1 정의를 사용하면 그 객체는 모듈 네임스페이스 이그조틱 객체이다. 이러한 메서드는 ModuleNamespaceCreate 에 의해 설치된다.

모듈 네임스페이스 이그조틱 객체Table 31에 정의된 내부 슬롯을 가진다.

Table 31: 모듈 네임스페이스 이그조틱 객체의 내부 슬롯(Internal Slots of Module Namespace Exotic Objects)
Internal Slot Type Description
[[Module]] a Module Record 이 네임스페이스가 export 를 노출하는 Module Record.
[[Exports]] a List of Strings 이 객체의 자체 프로퍼티로 노출되는 export 이름들의 String 값 요소를 가진 List. 코드 유닛 사전식 순서로 정렬됨.

10.4.6.1 [[GetPrototypeOf]] ( )

The [[GetPrototypeOf]] internal method of 모듈 네임스페이스 이그조틱 객체 takes no arguments and returns null 을 담는 normal completion. It performs the following steps when called:

  1. null 반환.

10.4.6.2 [[SetPrototypeOf]] ( V )

The [[SetPrototypeOf]] internal method of 모듈 네임스페이스 이그조틱 객체 O takes argument V (an Object or null) and returns Boolean 을 담는 normal completion. It performs the following steps when called:

  1. SetImmutablePrototype(O, V) 반환.

10.4.6.3 [[IsExtensible]] ( )

The [[IsExtensible]] internal method of 모듈 네임스페이스 이그조틱 객체 takes no arguments and returns false 를 담는 normal completion. It performs the following steps when called:

  1. false 반환.

10.4.6.4 [[PreventExtensions]] ( )

The [[PreventExtensions]] internal method of 모듈 네임스페이스 이그조틱 객체 takes no arguments and returns true 를 담는 normal completion. It performs the following steps when called:

  1. true 반환.

10.4.6.5 [[GetOwnProperty]] ( P )

The [[GetOwnProperty]] internal method of 모듈 네임스페이스 이그조틱 객체 O takes argument P (a property key) and returns Property Descriptor 또는 undefined 를 담는 normal completion 또는 throw completion. It performs the following steps when called:

  1. P 가 Symbol 이면 OrdinaryGetOwnProperty(O, P) 반환.
  2. exportsO.[[Exports]] 로 둔다.
  3. exportsP 를 포함하지 않으면 undefined 반환.
  4. value 를 ? O.[[Get]](P, O) 로 둔다.
  5. PropertyDescriptor { [[Value]]: value, [[Writable]]: true, [[Enumerable]]: true, [[Configurable]]: false } 반환.

10.4.6.6 [[DefineOwnProperty]] ( P, Desc )

The [[DefineOwnProperty]] internal method of 모듈 네임스페이스 이그조틱 객체 O takes arguments P (a property key) and Desc (a Property Descriptor) and returns Boolean 또는 throw completion 을 담는 normal completion. It performs the following steps when called:

  1. P 가 Symbol 이면 ! OrdinaryDefineOwnProperty(O, P, Desc) 반환.
  2. current 를 ? O.[[GetOwnProperty]](P) 로 둔다.
  3. currentundefined 이면 false 반환.
  4. Desc[[Configurable]] 필드가 있고 그 값이 true 이면 false 반환.
  5. Desc[[Enumerable]] 필드가 있고 그 값이 false 이면 false 반환.
  6. IsAccessorDescriptor(Desc) 가 true 이면 false 반환.
  7. Desc[[Writable]] 필드가 있고 그 값이 false 이면 false 반환.
  8. Desc[[Value]] 필드가 있으면 SameValue(Desc.[[Value]], current.[[Value]]) 반환.
  9. true 반환.

10.4.6.7 [[HasProperty]] ( P )

The [[HasProperty]] internal method of 모듈 네임스페이스 이그조틱 객체 O takes argument P (a property key) and returns Boolean 을 담는 normal completion. It performs the following steps when called:

  1. P 가 Symbol 이면 ! OrdinaryHasProperty(O, P) 반환.
  2. exportsO.[[Exports]] 로 둔다.
  3. exportsP 를 포함하면 true 반환.
  4. false 반환.

10.4.6.8 [[Get]] ( P, Receiver )

The [[Get]] internal method of 모듈 네임스페이스 이그조틱 객체 O takes arguments P (a property key) and Receiver (an ECMAScript language value) and returns ECMAScript 언어 값 또는 throw completion 을 담는 normal completion. It performs the following steps when called:

  1. P 가 Symbol 이면
    1. OrdinaryGet(O, P, Receiver) 반환.
  2. exportsO.[[Exports]] 로 둔다.
  3. exportsP 를 포함하지 않으면 undefined 반환.
  4. mO.[[Module]] 로 둔다.
  5. bindingm.ResolveExport(P) 로 둔다.
  6. 단언: bindingResolvedBinding Record.
  7. targetModulebinding.[[Module]] 로 둔다.
  8. 단언: targetModuleundefined 가 아님.
  9. binding.[[BindingName]]namespace 이면
    1. GetModuleNamespace(targetModule) 반환.
  10. targetEnvtargetModule.[[Environment]] 로 둔다.
  11. targetEnvempty 이면 ReferenceError 예외 throw.
  12. targetEnv.GetBindingValue(binding.[[BindingName]], true) 반환.
Note

ResolveExport 는 부작용이 없다. 특정 exportName, resolveSet 인수 쌍으로 이 연산을 호출할 때마다 동일 결과를 반환해야 한다. 구현은 각 모듈 네임스페이스 이그조틱 객체[[Exports]] 에 대한 ResolveExport 결과를 미리 계산하거나 캐시할 수 있다.

10.4.6.9 [[Set]] ( P, V, Receiver )

The [[Set]] internal method of 모듈 네임스페이스 이그조틱 객체 takes arguments P (a property key), V (an ECMAScript language value), and Receiver (an ECMAScript language value) and returns false 를 담는 normal completion. It performs the following steps when called:

  1. false 반환.

10.4.6.10 [[Delete]] ( P )

The [[Delete]] internal method of 모듈 네임스페이스 이그조틱 객체 O takes argument P (a property key) and returns Boolean 을 담는 normal completion. It performs the following steps when called:

  1. P 가 Symbol 이면
    1. OrdinaryDelete(O, P) 반환.
  2. exportsO.[[Exports]] 로 둔다.
  3. exportsP 를 포함하면 false 반환.
  4. true 반환.

10.4.6.11 [[OwnPropertyKeys]] ( )

The [[OwnPropertyKeys]] internal method of 모듈 네임스페이스 이그조틱 객체 O takes no arguments and returns 프로퍼티 키 List 를 담는 normal completion. It performs the following steps when called:

  1. exportsO.[[Exports]] 로 둔다.
  2. symbolKeysOrdinaryOwnPropertyKeys(O) 로 둔다.
  3. exportssymbolKeys 의 리스트 연결(list-concatenation) 반환.

10.4.6.12 ModuleNamespaceCreate ( module, exports )

The abstract operation ModuleNamespaceCreate takes arguments module (a Module Record) and exports (a List of Strings) and returns a module namespace exotic object. 새 모듈 네임스페이스 이그조틱 객체 생성 명세에 사용된다. It performs the following steps when called:

  1. 단언: module.[[Namespace]]empty.
  2. internalSlotsListTable 31에 나열된 내부 슬롯으로 둔다.
  3. MMakeBasicObject(internalSlotsList) 로 둔다.
  4. M 의 핵심 내부 메서드를 10.4.6에 지정된 정의로 설정.
  5. M.[[Module]]module 로 설정.
  6. sortedExportsexports 요소를 코드 유닛 사전식 순서로 정렬한 List 로 둔다.
  7. M.[[Exports]]sortedExports 로 설정.
  8. 28.3에 정의된 대로 M 의 자체 프로퍼티를 생성.
  9. module.[[Namespace]]M 으로 설정.
  10. M 반환.

10.4.7 불변 프로토타입 이그조틱 객체(Immutable Prototype Exotic Objects)

불변 프로토타입 이그조틱 객체는 초기화 이후 변경되지 않는 [[Prototype]] 내부 슬롯을 가진 이그조틱 객체이다.

객체의 [[SetPrototypeOf]] 내부 메서드가 아래 구현을 사용한다면 그 객체는 불변 프로토타입 이그조틱 객체이다. (그 외 핵심 내부 메서드는 구체적 객체에 따라 임의 구현을 사용할 수 있다.)

Note

다른 이그조틱 객체와 달리 불변 프로토타입 이그조틱 객체를 위한 전용 생성 추상 연산은 제공되지 않는다. 이는 %Object.prototype%호스트 환경에서만 사용되고, 호스트 환경에서는 관련 객체들이 다른 방식으로도 이그조틱일 수 있어 자체 전용 생성 연산이 필요하기 때문이다.

10.4.7.1 [[SetPrototypeOf]] ( V )

The [[SetPrototypeOf]] internal method of 불변 프로토타입 이그조틱 객체 O takes argument V (an Object or null) and returns Boolean 또는 throw completion 을 담는 normal completion. It performs the following steps when called:

  1. SetImmutablePrototype(O, V) 반환.

10.4.7.2 SetImmutablePrototype ( O, V )

The abstract operation SetImmutablePrototype takes arguments O (an Object) and V (an Object or null) and returns Boolean 또는 throw completion 을 담는 normal completion. It performs the following steps when called:

  1. current 를 ? O.[[GetPrototypeOf]]() 로 둔다.
  2. SameValue(V, current) 가 true 이면 true 반환.
  3. false 반환.

10.5 Proxy 객체의 내부 메서드와 내부 슬롯(Proxy Object Internal Methods and Internal Slots)

Proxy 객체는 필수 내부 메서드가 ECMAScript 코드로 일부 구현된 이그조틱 객체이다. 모든 Proxy 객체는 [[ProxyHandler]] 라는 내부 슬롯을 가진다. [[ProxyHandler]] 의 값은 프록시의 handler object 라 불리는 객체이거나 null 이다. 핸들러 객체의 메서드들(Table 32 참조)은 하나 이상 Proxy 객체 내부 메서드 구현을 확장(augment)하는 데 사용될 수 있다. 모든 Proxy 객체는 또한 [[ProxyTarget]] 이라 불리는 내부 슬롯을 가지며 그 값은 객체 또는 null 이다. 이 객체를 프록시의 target object 라고 한다.

객체의 (해당한다면 [[Call]][[Construct]] 포함) 필수 내부 메서드가 이 절의 정의를 사용한다면 그 객체는 Proxy 이그조틱 객체이다. 이러한 내부 메서드는 ProxyCreate 에서 설치된다.

Table 32: 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

프록시 객체 내부 메서드 구현을 제공하기 위해 핸들러 메서드가 호출될 때 핸들러 메서드에는 프록시의 target 객체가 매개변수로 전달된다. 프록시의 핸들러 객체가 모든 필수 내부 메서드에 대응하는 메서드를 반드시 가질 필요는 없다. 프록시에서 내부 메서드를 호출했을 때 핸들러 객체가 해당 내부 트랩에 대응하는 메서드를 가지지 않으면 프록시 target 객체의 대응 내부 메서드가 호출된다.

Proxy 객체의 [[ProxyHandler]][[ProxyTarget]] 내부 슬롯은 객체 생성 시 항상 초기화되며 일반적으로 수정될 수 없다. 일부 Proxy 객체는 이후 revoked 될 수 있는 방식으로 생성된다. 프록시가 철회(revoke)되면 그 [[ProxyHandler]][[ProxyTarget]] 내부 슬롯이 null 로 설정되어 이후 그 Proxy 객체의 내부 메서드 호출은 TypeError 예외를 던진다.

Proxy 객체는 내부 메서드 구현을 임의의 ECMAScript 코드로 제공할 수 있게 하므로, 6.1.7.3 에 정의된 불변식을 위반하는 핸들러 메서드를 가진 Proxy 객체를 정의할 가능성이 있다. 6.1.7.3 에 정의된 내부 메서드 불변식 중 일부는 필수 무결성 불변식이며, 이들은 이 절에 명시된 Proxy 객체 내부 메서드에 의해 명시적으로 강제된다. ECMAScript 구현은 모든 가능한 불변식 위반 존재 시에도 견고해야 한다.

이하 알고리즘 설명에서 O 는 ECMAScript Proxy 객체, P프로퍼티 키 값, V 는 임의의 ECMAScript 언어 값, DescProperty Descriptor 레코드라고 가정한다.

10.5.1 [[GetPrototypeOf]] ( )

The [[GetPrototypeOf]] internal method of a Proxy exotic object O takes no arguments and returns Object 또는 null 을 담는 normal completion 또는 throw completion. It performs the following steps when called:

  1. ValidateNonRevokedProxy(O) 를 수행한다.
  2. targetO.[[ProxyTarget]] 로 둔다.
  3. handlerO.[[ProxyHandler]] 로 둔다.
  4. 단언: handler 는 Object.
  5. trap 을 ? GetMethod(handler, "getPrototypeOf") 로 둔다.
  6. trapundefined 이면
    1. target.[[GetPrototypeOf]]() 를 반환한다.
  7. handlerProto 를 ? Call(trap, handler, « target ») 로 둔다.
  8. handlerProto 가 Object 도 아니고 null 도 아니면 TypeError 예외 throw.
  9. extensibleTarget 을 ? IsExtensible(target) 로 둔다.
  10. extensibleTargettrue 이면 handlerProto 반환.
  11. targetProto 를 ? target.[[GetPrototypeOf]]() 로 둔다.
  12. SameValue(handlerProto, targetProto) 가 false 이면 TypeError 예외 throw.
  13. handlerProto 반환.
Note

Proxy 객체의 [[GetPrototypeOf]] 는 다음 불변식을 강제한다:

  • [[GetPrototypeOf]] 결과는 Object 또는 null 이어야 한다.
  • target 객체가 비확장(non-extensible) 이면 Proxy 객체에 적용한 [[GetPrototypeOf]] 는 target 객체에 적용한 [[GetPrototypeOf]] 와 동일 값을 반환해야 한다.

10.5.2 [[SetPrototypeOf]] ( V )

The [[SetPrototypeOf]] internal method of a Proxy exotic object O takes argument V (an Object or null) and returns Boolean 을 담는 normal completion 또는 throw completion. It performs the following steps when called:

  1. ValidateNonRevokedProxy(O) 수행.
  2. targetO.[[ProxyTarget]] 로 둔다.
  3. handlerO.[[ProxyHandler]] 로 둔다.
  4. 단언: handler 는 Object.
  5. trap 을 ? GetMethod(handler, "setPrototypeOf") 로 둔다.
  6. trapundefined 이면
    1. target.[[SetPrototypeOf]](V) 반환.
  7. booleanTrapResultToBoolean(? Call(trap, handler, « target, V »)) 로 둔다.
  8. booleanTrapResultfalse 이면 false 반환.
  9. extensibleTarget 을 ? IsExtensible(target) 로 둔다.
  10. extensibleTargettrue 이면 true 반환.
  11. targetProto 를 ? target.[[GetPrototypeOf]]() 로 둔다.
  12. SameValue(V, targetProto) 가 false 이면 TypeError 예외 throw.
  13. true 반환.
Note

Proxy 객체의 [[SetPrototypeOf]] 는 다음 불변식을 강제한다:

  • [[SetPrototypeOf]] 의 결과는 Boolean 값이다.
  • target 객체가 비확장이라면 인수 값은 target 객체에 적용한 [[GetPrototypeOf]] 결과와 동일해야 한다.

10.5.3 [[IsExtensible]] ( )

The [[IsExtensible]] internal method of a Proxy exotic object O takes no arguments and returns Boolean 을 담는 normal completion 또는 throw completion. It performs the following steps when called:

  1. ValidateNonRevokedProxy(O) 수행.
  2. targetO.[[ProxyTarget]] 로 둔다.
  3. handlerO.[[ProxyHandler]] 로 둔다.
  4. 단언: handler 는 Object.
  5. trap 을 ? GetMethod(handler, "isExtensible") 로 둔다.
  6. trapundefined 이면
    1. IsExtensible(target) 반환.
  7. booleanTrapResultToBoolean(? Call(trap, handler, « target »)) 로 둔다.
  8. targetResult 를 ? IsExtensible(target) 로 둔다.
  9. booleanTrapResulttargetResult 와 다르면 TypeError 예외 throw.
  10. booleanTrapResult 반환.
Note

Proxy 객체의 [[IsExtensible]] 는 다음 불변식을 강제한다:

  • [[IsExtensible]] 결과는 Boolean 값이다.
  • Proxy 객체에 적용한 [[IsExtensible]] 결과는 동일 인수로 target 객체에 적용한 [[IsExtensible]] 결과와 동일해야 한다.

10.5.4 [[PreventExtensions]] ( )

The [[PreventExtensions]] internal method of a Proxy exotic object O takes no arguments and returns Boolean 을 담는 normal completion 또는 throw completion. It performs the following steps when called:

  1. ValidateNonRevokedProxy(O) 수행.
  2. targetO.[[ProxyTarget]] 로 둔다.
  3. handlerO.[[ProxyHandler]] 로 둔다.
  4. 단언: handler 는 Object.
  5. trap 을 ? GetMethod(handler, "preventExtensions") 로 둔다.
  6. trapundefined 이면
    1. target.[[PreventExtensions]]() 반환.
  7. booleanTrapResultToBoolean(? Call(trap, handler, « target »)) 로 둔다.
  8. booleanTrapResulttrue 이면
    1. extensibleTarget 을 ? IsExtensible(target) 로 둔다.
    2. extensibleTargettrue 이면 TypeError 예외 throw.
  9. booleanTrapResult 반환.
Note

Proxy 객체의 [[PreventExtensions]] 는 다음 불변식을 강제한다:

  • [[PreventExtensions]] 결과는 Boolean 값이다.
  • Proxy 객체에 적용한 [[PreventExtensions]]true 를 반환하는 경우는 target 객체에 적용한 [[IsExtensible]]false 일 때뿐이다.

10.5.5 [[GetOwnProperty]] ( P )

The [[GetOwnProperty]] internal method of a Proxy exotic object O takes argument P (a property key) and returns Property Descriptor 또는 undefined 를 담는 normal completion 또는 throw completion. It performs the following steps when called:

  1. ValidateNonRevokedProxy(O) 수행.
  2. targetO.[[ProxyTarget]] 로 둔다.
  3. handlerO.[[ProxyHandler]] 로 둔다.
  4. 단언: handler 는 Object.
  5. trap 을 ? GetMethod(handler, "getOwnPropertyDescriptor") 로 둔다.
  6. trapundefined 이면
    1. target.[[GetOwnProperty]](P) 반환.
  7. trapResultObj 를 ? Call(trap, handler, « target, P ») 로 둔다.
  8. trapResultObj 가 Object 도 아니고 undefined 도 아니면 TypeError 예외 throw.
  9. targetDesc 를 ? target.[[GetOwnProperty]](P) 로 둔다.
  10. trapResultObjundefined 이면
    1. targetDescundefined 이면 undefined 반환.
    2. targetDesc.[[Configurable]]false 이면 TypeError 예외 throw.
    3. extensibleTarget 을 ? IsExtensible(target) 로 둔다.
    4. extensibleTargetfalse 이면 TypeError 예외 throw.
    5. undefined 반환.
  11. extensibleTarget 을 ? IsExtensible(target) 로 둔다.
  12. resultDesc 를 ? ToPropertyDescriptor(trapResultObj) 로 둔다.
  13. CompletePropertyDescriptor(resultDesc) 수행.
  14. validIsCompatiblePropertyDescriptor(extensibleTarget, resultDesc, targetDesc) 로 둔다.
  15. validfalse 이면 TypeError 예외 throw.
  16. resultDesc.[[Configurable]]false 이면
    1. targetDescundefined 이거나 targetDesc.[[Configurable]]true 이면
      1. TypeError 예외 throw.
    2. resultDesc[[Writable]] 필드가 있고 resultDesc.[[Writable]]false 이면
      1. 단언: targetDesc[[Writable]] 필드를 가진다.
      2. targetDesc.[[Writable]]true 이면 TypeError 예외 throw.
  17. resultDesc 반환.
Note

Proxy 객체의 [[GetOwnProperty]] 는 다음 불변식을 강제한다:

  • [[GetOwnProperty]] 결과는 Object 또는 undefined 여야 한다.
  • target 객체에 비구성 가능(non-configurable) 자체 프로퍼티로 존재하면 그 프로퍼티를 비존재로 보고할 수 없다.
  • target 객체가 비확장이고 해당 프로퍼티가 자체 프로퍼티로 존재하면 비존재로 보고할 수 없다.
  • target 객체가 비확장이고 해당 프로퍼티가 target 에 자체 프로퍼티로 존재하지 않으면 존재한다고 보고할 수 없다.
  • target 객체에 대응 비구성 가능 자체 프로퍼티가 없으면 프로퍼티를 비구성 가능으로 보고할 수 없다.
  • target 객체에 대응 비구성 가능·비쓰기(non-writable) 자체 프로퍼티가 없으면 프로퍼티를 동시에 비구성 가능 & 비쓰기라고 보고할 수 없다.

10.5.6 [[DefineOwnProperty]] ( P, Desc )

The [[DefineOwnProperty]] internal method of a Proxy exotic object O takes arguments P (a property key) and Desc (a Property Descriptor) and returns Boolean 을 담는 normal completion 또는 throw completion. It performs the following steps when called:

  1. ValidateNonRevokedProxy(O) 수행.
  2. targetO.[[ProxyTarget]] 로 둔다.
  3. handlerO.[[ProxyHandler]] 로 둔다.
  4. 단언: handler 는 Object.
  5. trap 을 ? GetMethod(handler, "defineProperty") 로 둔다.
  6. trapundefined 이면
    1. target.[[DefineOwnProperty]](P, Desc) 반환.
  7. descObjFromPropertyDescriptor(Desc) 로 둔다.
  8. booleanTrapResultToBoolean(? Call(trap, handler, « target, P, descObj »)) 로 둔다.
  9. booleanTrapResultfalse 이면 false 반환.
  10. targetDesc 를 ? target.[[GetOwnProperty]](P) 로 둔다.
  11. extensibleTarget 을 ? IsExtensible(target) 로 둔다.
  12. Desc[[Configurable]] 필드가 있고 Desc.[[Configurable]]false 이면
    1. settingConfigFalsetrue 로 둔다.
  13. Else
    1. settingConfigFalsefalse 로 둔다.
  14. targetDescundefined 이면
    1. extensibleTargetfalse 이면 TypeError 예외 throw.
    2. settingConfigFalsetrue 이면 TypeError 예외 throw.
  15. Else
    1. IsCompatiblePropertyDescriptor(extensibleTarget, Desc, targetDesc) 가 false 이면 TypeError 예외 throw.
    2. settingConfigFalsetrue 이고 targetDesc.[[Configurable]]true 이면 TypeError 예외 throw.
    3. IsDataDescriptor(targetDesc) 가 true 이고 targetDesc.[[Configurable]]false 이며 targetDesc.[[Writable]]true 이면
      1. Desc[[Writable]] 필드가 있고 Desc.[[Writable]]false 이면 TypeError 예외 throw.
  16. true 반환.
Note

Proxy 객체의 [[DefineOwnProperty]] 는 다음 불변식을 강제한다:

  • [[DefineOwnProperty]] 결과는 Boolean 값이다.
  • target 객체가 비확장이라면 프로퍼티를 추가할 수 없다.
  • target 객체에 대응 비구성 가능 자체 프로퍼티가 없으면 프로퍼티를 비구성 가능으로 만들 수 없다.
  • 대응 비구성 가능·비쓰기 자체 프로퍼티가 없으면 비구성 가능 프로퍼티를 비쓰기 상태로 만들 수 없다.
  • 프로퍼티에 대응하는 target 프로퍼티가 존재한다면 그 프로퍼티의 Descriptor 를 target 에 [[DefineOwnProperty]] 로 적용해도 예외가 발생하지 않아야 한다.

10.5.7 [[HasProperty]] ( P )

The [[HasProperty]] internal method of a Proxy exotic object O takes argument P (a property key) and returns Boolean 을 담는 normal completion 또는 throw completion. It performs the following steps when called:

  1. ValidateNonRevokedProxy(O) 수행.
  2. targetO.[[ProxyTarget]] 로 둔다.
  3. handlerO.[[ProxyHandler]] 로 둔다.
  4. 단언: handler 는 Object.
  5. trap 을 ? GetMethod(handler, "has") 로 둔다.
  6. trapundefined 이면
    1. target.[[HasProperty]](P) 반환.
  7. booleanTrapResultToBoolean(? Call(trap, handler, « target, P »)) 로 둔다.
  8. booleanTrapResultfalse 이면
    1. targetDesc 를 ? target.[[GetOwnProperty]](P) 로 둔다.
    2. targetDescundefined 가 아니면
      1. targetDesc.[[Configurable]]false 이면 TypeError 예외 throw.
      2. extensibleTarget 을 ? IsExtensible(target) 로 둔다.
      3. extensibleTargetfalse 이면 TypeError 예외 throw.
  9. booleanTrapResult 반환.
Note

Proxy 객체의 [[HasProperty]] 는 다음 불변식을 강제한다:

  • [[HasProperty]] 결과는 Boolean 값이다.
  • target 객체에 비구성 가능 자체 프로퍼티로 존재하면 비존재로 보고할 수 없다.
  • target 객체가 비확장이고 해당 프로퍼티가 자체 프로퍼티로 존재하면 비존재로 보고할 수 없다.

10.5.8 [[Get]] ( P, Receiver )

The [[Get]] internal method of a Proxy exotic object O takes arguments P (a property key) and Receiver (an ECMAScript language value) and returns ECMAScript 언어 값 또는 throw completion 을 담는 normal completion. It performs the following steps when called:

  1. ValidateNonRevokedProxy(O) 수행.
  2. targetO.[[ProxyTarget]] 로 둔다.
  3. handlerO.[[ProxyHandler]] 로 둔다.
  4. 단언: handler 는 Object.
  5. trap 을 ? GetMethod(handler, "get") 로 둔다.
  6. trapundefined 이면
    1. target.[[Get]](P, Receiver) 반환.
  7. trapResult 를 ? Call(trap, handler, « target, P, Receiver ») 로 둔다.
  8. targetDesc 를 ? target.[[GetOwnProperty]](P) 로 둔다.
  9. targetDescundefined 가 아니고 targetDesc.[[Configurable]]false 이면
    1. IsDataDescriptor(targetDesc) 가 true 이고 targetDesc.[[Writable]]false 이면
      1. SameValue(trapResult, targetDesc.[[Value]]) 가 false 이면 TypeError 예외 throw.
    2. IsAccessorDescriptor(targetDesc) 가 true 이고 targetDesc.[[Get]]undefined 이면
      1. trapResultundefined 가 아니면 TypeError 예외 throw.
  10. trapResult 반환.
Note

Proxy 객체의 [[Get]] 는 다음 불변식을 강제한다:

  • target 객체 프로퍼티가 비쓰기·비구성 가능 자체 데이터 프로퍼티라면 보고되는 값은 target 프로퍼티 값과 동일해야 한다.
  • target 객체 프로퍼티가 [[Get]]undefined 인 비구성 가능 자체 접근자 프로퍼티라면 보고되는 값은 undefined 이어야 한다.

10.5.9 [[Set]] ( P, V, Receiver )

The [[Set]] internal method of a Proxy exotic object O takes arguments P (a property key), V (an ECMAScript language value), and Receiver (an ECMAScript language value) and returns Boolean 을 담는 normal completion 또는 throw completion. It performs the following steps when called:

  1. ValidateNonRevokedProxy(O) 수행.
  2. targetO.[[ProxyTarget]] 로 둔다.
  3. handlerO.[[ProxyHandler]] 로 둔다.
  4. 단언: handler 는 Object.
  5. trap 을 ? GetMethod(handler, "set") 로 둔다.
  6. trapundefined 이면
    1. target.[[Set]](P, V, Receiver) 반환.
  7. booleanTrapResultToBoolean(? Call(trap, handler, « target, P, V, Receiver »)) 로 둔다.
  8. booleanTrapResultfalse 이면 false 반환.
  9. targetDesc 를 ? target.[[GetOwnProperty]](P) 로 둔다.
  10. targetDescundefined 가 아니고 targetDesc.[[Configurable]]false 이면
    1. IsDataDescriptor(targetDesc) 가 true 이고 targetDesc.[[Writable]]false 이면
      1. SameValue(V, targetDesc.[[Value]]) 가 false 이면 TypeError 예외 throw.
    2. IsAccessorDescriptor(targetDesc) 가 true 이면
      1. targetDesc.[[Set]]undefined 이면 TypeError 예외 throw.
  11. true 반환.
Note

Proxy 객체의 [[Set]] 는 다음 불변식을 강제한다:

  • [[Set]] 결과는 Boolean 값이다.
  • 대응 target 프로퍼티가 비쓰기·비구성 가능 자체 데이터 프로퍼티라면 그 값을 다른 값으로 바꿀 수 없다.
  • 대응 target 프로퍼티가 [[Set]]undefined 인 비구성 가능 자체 접근자 프로퍼티라면 값을 설정할 수 없다.

10.5.10 [[Delete]] ( P )

The [[Delete]] internal method of a Proxy exotic object O takes argument P (a property key) and returns Boolean 을 담는 normal completion 또는 throw completion. It performs the following steps when called:

  1. ValidateNonRevokedProxy(O) 수행.
  2. targetO.[[ProxyTarget]] 로 둔다.
  3. handlerO.[[ProxyHandler]] 로 둔다.
  4. 단언: handler 는 Object.
  5. trap 을 ? GetMethod(handler, "deleteProperty") 로 둔다.
  6. trapundefined 이면
    1. target.[[Delete]](P) 반환.
  7. booleanTrapResultToBoolean(? Call(trap, handler, « target, P »)) 로 둔다.
  8. booleanTrapResultfalse 이면 false 반환.
  9. targetDesc 를 ? target.[[GetOwnProperty]](P) 로 둔다.
  10. targetDescundefined 이면 true 반환.
  11. targetDesc.[[Configurable]]false 이면 TypeError 예외 throw.
  12. extensibleTarget 을 ? IsExtensible(target) 로 둔다.
  13. extensibleTargetfalse 이면 TypeError 예외 throw.
  14. true 반환.
Note

Proxy 객체의 [[Delete]] 는 다음 불변식을 강제한다:

  • [[Delete]] 결과는 Boolean 값이다.
  • target 객체에 비구성 가능 자체 프로퍼티로 존재하면 삭제되었다고 보고할 수 없다.
  • target 객체가 비확장이고 해당 프로퍼티가 자체 프로퍼티로 존재하면 삭제되었다고 보고할 수 없다.

10.5.11 [[OwnPropertyKeys]] ( )

The [[OwnPropertyKeys]] internal method of a Proxy exotic object O takes no arguments and returns 프로퍼티 키 List 를 담는 normal completion 또는 throw completion. It performs the following steps when called:

  1. ValidateNonRevokedProxy(O) 수행.
  2. targetO.[[ProxyTarget]] 로 둔다.
  3. handlerO.[[ProxyHandler]] 로 둔다.
  4. 단언: 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 가 중복 항목을 포함하면 TypeError 예외 throw.
  10. extensibleTarget 을 ? IsExtensible(target) 로 둔다.
  11. targetKeys 를 ? target.[[OwnPropertyKeys]]() 로 둔다.
  12. 단언: targetKeys프로퍼티 키들의 List.
  13. 단언: targetKeys 는 중복 항목이 없다.
  14. targetConfigurableKeys 를 새 빈 List 로 둔다.
  15. targetNonconfigurableKeys 를 새 빈 List 로 둔다.
  16. targetKeys 의 각 요소 key 에 대해
    1. desc 를 ? target.[[GetOwnProperty]](key) 로 둔다.
    2. descundefined 가 아니고 desc.[[Configurable]]false 이면
      1. targetNonconfigurableKeyskey 추가.
    3. Else
      1. targetConfigurableKeyskey 추가.
  17. extensibleTargettrue 이고 targetNonconfigurableKeys 가 비어 있으면
    1. trapResult 반환.
  18. uncheckedResultKeystrapResult 요소들로 구성된 List 로 둔다.
  19. targetNonconfigurableKeys 의 각 key 에 대해
    1. uncheckedResultKeyskey 를 포함하지 않으면 TypeError 예외 throw.
    2. uncheckedResultKeys 에서 key 제거.
  20. extensibleTargettrue 이면 trapResult 반환.
  21. targetConfigurableKeys 의 각 key 에 대해
    1. uncheckedResultKeyskey 를 포함하지 않으면 TypeError 예외 throw.
    2. uncheckedResultKeys 에서 key 제거.
  22. uncheckedResultKeys 가 비어 있지 않으면 TypeError 예외 throw.
  23. trapResult 반환.
Note

Proxy 객체의 [[OwnPropertyKeys]] 는 다음 불변식을 강제한다:

  • [[OwnPropertyKeys]] 결과는 List 이다.
  • 반환된 List 에는 중복 항목이 없다.
  • 반환 List 의 각 요소는 프로퍼티 키이다.
  • 결과 List 는 target 객체의 모든 비구성 가능 자체 프로퍼티의 키를 포함해야 한다.
  • target 객체가 비확장이라면 결과 List 는 target 객체 자체 프로퍼티의 모든 키만 포함해야 한다.

10.5.12 [[Call]] ( thisArgument, argumentsList )

The [[Call]] internal method of a Proxy exotic object O takes arguments thisArgument (an ECMAScript language value) and argumentsList (a List of ECMAScript language values) and returns ECMAScript 언어 값 또는 throw completion 을 담는 normal completion. It performs the following steps when called:

  1. ValidateNonRevokedProxy(O) 수행.
  2. targetO.[[ProxyTarget]] 로 둔다.
  3. handlerO.[[ProxyHandler]] 로 둔다.
  4. 단언: handler 는 Object.
  5. trap 을 ? GetMethod(handler, "apply") 로 둔다.
  6. trapundefined 이면
    1. Call(target, thisArgument, argumentsList) 반환.
  7. argArrayCreateArrayFromList(argumentsList) 로 둔다.
  8. Call(trap, handler, « target, thisArgument, argArray ») 반환.
Note

Proxy 이그조틱 객체[[ProxyTarget]] 내부 슬롯 초기 값이 [[Call]] 내부 메서드를 가진 객체인 경우에만 [[Call]] 내부 메서드를 가진다.

10.5.13 [[Construct]] ( argumentsList, newTarget )

The [[Construct]] internal method of a Proxy exotic object O takes arguments argumentsList (a List of ECMAScript language values) and newTarget (a constructor) and returns Object 를 담는 normal completion 또는 throw completion. It performs the following steps when called:

  1. ValidateNonRevokedProxy(O) 수행.
  2. targetO.[[ProxyTarget]] 로 둔다.
  3. 단언: IsConstructor(target) 는 true.
  4. handlerO.[[ProxyHandler]] 로 둔다.
  5. 단언: handler 는 Object.
  6. trap 을 ? GetMethod(handler, "construct") 로 둔다.
  7. trapundefined 이면
    1. Construct(target, argumentsList, newTarget) 반환.
  8. argArrayCreateArrayFromList(argumentsList) 로 둔다.
  9. newObj 를 ? Call(trap, handler, « target, argArray, newTarget ») 로 둔다.
  10. newObj 가 Object 가 아니면 TypeError 예외 throw.
  11. newObj 반환.
Note 1

Proxy 이그조틱 객체[[ProxyTarget]] 내부 슬롯 초기 값이 [[Construct]] 내부 메서드를 가진 객체인 경우에만 [[Construct]] 내부 메서드를 가진다.

Note 2

Proxy 객체의 [[Construct]] 는 다음 불변식을 강제한다:

  • [[Construct]] 결과는 Object 이어야 한다.

10.5.14 ValidateNonRevokedProxy ( proxy )

The abstract operation ValidateNonRevokedProxy takes argument proxy (a Proxy exotic object) and returns unused 를 담는 normal completion 또는 throw completion. proxy 가 revoke 되었다면 TypeError 예외를 던진다. It performs the following steps when called:

  1. proxy.[[ProxyTarget]]null 이면 TypeError 예외 throw.
  2. 단언: 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 Proxy 이그조틱 객체를 담는 normal completion 또는 throw completion. 새 Proxy 객체 생성 과정을 명세하는 데 사용된다. It performs the following steps when called:

  1. target 이 Object 가 아니면 TypeError 예외 throw.
  2. handler 가 Object 가 아니면 TypeError 예외 throw.
  3. PMakeBasicObject[[ProxyHandler]], [[ProxyTarget]] ») 로 둔다.
  4. P 의 핵심 내부 메서드( [[Call]], [[Construct]] 제외)를 10.5 에 지정된 정의로 설정.
  5. IsCallable(target) 이 true 이면
    1. P.[[Call]]10.5.12 에서 지정된 대로 설정.
    2. IsConstructor(target) 이 true 이면
      1. P.[[Construct]]10.5.13 에서 지정된 대로 설정.
  6. P.[[ProxyTarget]]target 으로 설정.
  7. P.[[ProxyHandler]]handler 로 설정.
  8. P 반환.

11 ECMAScript 언어: 소스 텍스트(ECMAScript Language: Source Text)

11.1 소스 텍스트(Source Text)

Syntax

SourceCharacter :: any Unicode code point

ECMAScript source text는 유니코드 코드 포인트들의 시퀀스이다. ECMAScript 문법이 허용하는 위치에서는 U+0000 부터 U+10FFFF 까지의 모든 유니코드 코드 포인트 값(서러게이트 코드 포인트 포함)이 ECMAScript 소스 텍스트에 나타날 수 있다. ECMAScript 소스 텍스트를 저장·교환하는 실제 인코딩은 이 명세와 무관하다. 외부 소스 텍스트 인코딩이 무엇이든, 적합한 ECMAScript 구현은 소스 텍스트를 동등한 SourceCharacter 값들의 시퀀스로 처리하며, 각 SourceCharacter 는 하나의 유니코드 코드 포인트이다. 적합한 ECMAScript 구현은 소스 텍스트에 대해 어떤 정규화(normalization)를 수행할 필요도 없으며 정규화를 수행하는 것처럼 동작할 필요도 없다.

결합 문자 시퀀스(combining character sequence)의 구성 요소들은 사용자가 전체를 단일 문자로 생각할지라도 개별 유니코드 코드 포인트로 취급된다.

Note

문자열 리터럴, 정규 표현식 리터럴, 템플릿 리터럴 및 식별자에서 모든 유니코드 코드 포인트는 해당 코드 포인트의 수치 값을 명시적으로 표현하는 유니코드 이스케이프 시퀀스로도 표현할 수 있다. 주석 안에서는 그러한 이스케이프 시퀀스는 주석 일부로서 사실상 무시된다.

ECMAScript 는 유니코드 이스케이프 시퀀스 동작에서 Java 프로그래밍 언어와 다르다. 예를 들어 Java 프로그램에서 유니코드 이스케이프 시퀀스 \u000A 가 단일 행 주석 내에 나타나면 그것은 행 종결자(유니코드 코드 포인트 U+000A 는 LINE FEED (LF))로 해석되어 다음 코드 포인트는 더 이상 주석의 일부가 아니다. 마찬가지로 Java 프로그램의 문자열 리터럴에 \u000A 가 나타나면 그것 역시 행 종결자로 해석되며 문자열 리터럴 내부에는 허용되지 않는다—문자열 값에 LINE FEED (LF)를 포함하려면 \u000A 대신 \n 을 써야 한다. ECMAScript 프로그램에서는 주석 내부에 나타나는 유니코드 이스케이프 시퀀스가 절대 해석되지 않으며 따라서 주석 종료에 기여할 수 없다. 유사하게 ECMAScript 프로그램의 문자열 리터럴 내부에 나타나는 유니코드 이스케이프 시퀀스는 항상 리터럴의 일부로 기여하고 결코 행 종결자나 문자열 리터럴을 종료시킬 수 있는 코드 포인트로 해석되지 않는다.

11.1.1 정적 의미론(Static Semantics): UTF16EncodeCodePoint ( cp: a Unicode code point, ): a String

The abstract operation UNKNOWN takes UNPARSEABLE ARGUMENTS. It performs the following steps when called:

  1. 단언: 0 ≤ cp ≤ 0x10FFFF.
  2. cp ≤ 0xFFFF 이면, 수치 값이 cp 인 코드 유닛으로 구성된 String 값을 반환한다.
  3. cu1 를 수치 값이 floor((cp - 0x10000) / 0x400) + 0xD800 인 코드 유닛으로 둔다.
  4. cu2 를 수치 값이 ((cp - 0x10000) modulo 0x400) + 0xDC00 인 코드 유닛으로 둔다.
  5. cu1cu2 의 문자열 연결(string-concatenation)을 반환한다.

11.1.2 정적 의미론(Static Semantics): CodePointsToString ( text: a sequence of Unicode code points, ): a String

The abstract operation UNKNOWN takes UNPARSEABLE ARGUMENTS. 이는 6.1.4 에 설명된 대로 text 를 String 값으로 변환한다. It performs the following steps when called:

  1. result 를 빈 문자열로 둔다.
  2. text 의 각 코드 포인트 cp 에 대해
    1. resultresult 와 UTF16EncodeCodePoint(cp) 의 문자열 연결로 설정한다.
  3. result 를 반환한다.

11.1.3 정적 의미론(Static Semantics): UTF16SurrogatePairToCodePoint ( lead: a code unit, trail: a code unit, ): a code point

The abstract operation UNKNOWN takes UNPARSEABLE ARGUMENTS. UTF-16 서로게이트 쌍을 이루는 두 코드 유닛을 코드 포인트로 변환한다. It performs the following steps when called:

  1. 단언: lead 는 선행 서로게이트이고 trail 은 후행 서로게이트이다.
  2. cp 를 (lead - 0xD800) × 0x400 + (trail - 0xDC00) + 0x10000 으로 둔다.
  3. 코드 포인트 cp 를 반환한다.

11.1.4 정적 의미론(Static Semantics): CodePointAt ( string: a String, position: a non-negative integer, ): a Record with fields [[CodePoint]] (a code point), [[CodeUnitCount]] (a positive integer), and [[IsUnpairedSurrogate]] (a Boolean)

The abstract operation UNKNOWN takes UNPARSEABLE ARGUMENTS. 6.1.4 에 설명된 대로 string 을 UTF-16 인코딩된 코드 포인트 시퀀스로 해석하고, 인덱스 position 에 있는 코드 유닛에서 시작하는 단일 코드 포인트를 읽는다. It performs the following steps when called:

  1. sizestring 길이로 둔다.
  2. 단언: position ≥ 0 그리고 position < size.
  3. firststring 내 인덱스 position 의 코드 유닛으로 둔다.
  4. cp 를 수치 값이 first 의 수치 값인 코드 포인트로 둔다.
  5. first 가 선행 서로게이트도 후행 서로게이트도 아니면
    1. Record { [[CodePoint]]: cp, [[CodeUnitCount]]: 1, [[IsUnpairedSurrogate]]: false } 를 반환한다.
  6. first 가 후행 서로게이트이거나 position + 1 = size 이면
    1. Record { [[CodePoint]]: cp, [[CodeUnitCount]]: 1, [[IsUnpairedSurrogate]]: true } 를 반환한다.
  7. secondstring 내 인덱스 position + 1 의 코드 유닛으로 둔다.
  8. second 가 후행 서로게이트가 아니면
    1. Record { [[CodePoint]]: cp, [[CodeUnitCount]]: 1, [[IsUnpairedSurrogate]]: true } 를 반환한다.
  9. cp 를 UTF16SurrogatePairToCodePoint(first, second) 로 설정한다.
  10. Record { [[CodePoint]]: cp, [[CodeUnitCount]]: 2, [[IsUnpairedSurrogate]]: false } 를 반환한다.

11.1.5 정적 의미론(Static Semantics): StringToCodePoints ( string: a String, ): a List of code points

The abstract operation UNKNOWN takes UNPARSEABLE ARGUMENTS. 6.1.4 에 설명된 대로 string 을 UTF-16 인코딩된 유니코드 텍스트로 해석하여 얻어지는 유니코드 코드 포인트 시퀀스를 반환한다. It performs the following steps when called:

  1. codePoints 를 새 빈 List 로 둔다.
  2. sizestring 길이로 둔다.
  3. position 을 0 으로 둔다.
  4. position < size 인 동안 반복,
    1. cp 를 CodePointAt(string, position) 로 둔다.
    2. cp.[[CodePoint]]codePoints 에 추가한다.
    3. positionposition + cp.[[CodeUnitCount]] 로 설정한다.
  5. codePoints 를 반환한다.

11.1.6 정적 의미론(Static Semantics): ParseText ( sourceText: a String or a sequence of Unicode code points, goalSymbol: a nonterminal in one of the ECMAScript grammars, ): a Parse Node or a non-empty List of SyntaxError objects

The abstract operation UNKNOWN takes UNPARSEABLE ARGUMENTS. It performs the following steps when called:

  1. sourceText 가 String 이면 sourceText 를 StringToCodePoints(sourceText) 로 설정한다.
  2. goalSymbol 을 목표 심볼(goal symbol)로 사용하여 sourceText 를 파싱하고, 파싱 결과를 조기 오류(early error) 조건이 있는지 분석한다. 파싱과 조기 오류 검출은 구현 정의 방식으로 상호 교차(interleaved)될 수 있다.
  3. 파싱이 성공했고 조기 오류가 발견되지 않았다면, 파싱에서 생성된 파스 트리의 루트에 있는 Parse Node ( goalSymbol 의 인스턴스) 를 반환한다.
  4. 그렇지 않으면, 파싱 오류 및/또는 조기 오류를 나타내는 하나 이상의 SyntaxError 객체들의 List 를 반환한다. 둘 이상의 파싱 오류 또는 조기 오류가 있을 경우, 리스트 내 오류 객체의 수와 순서는 구현 정의이지만 최소 하나는 있어야 한다.
Note 1

특정 지점에 조기 오류가 있고 이후 지점에 구문 오류가 있는 텍스트를 생각해보자. 파싱 후 조기 오류 패스를 수행하는 구현은 구문 오류를 보고하고 조기 오류 패스로 진행하지 않을 수 있다. 두 활동을 교차 수행하는 구현은 조기 오류를 보고하고 구문 오류 탐지를 진행하지 않을 수 있다. 세 번째 구현은 두 오류를 모두 보고할 수 있다. 이 모든 동작은 적합하다.

Note 2

17 절도 참조.

11.2 소스 코드의 유형(Types of Source Code)

ECMAScript 코드는 네 가지 유형이 있다:

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) 의 본문으로 제공된다. Function code 는 또한 Function 생성자 (20.2.1.1), GeneratorFunction 생성자 (27.3.1.1), AsyncFunction 생성자 (27.7.1.1), AsyncGeneratorFunction 생성자 (27.4.1.1) 의 인자에서 파생된다.

Note 2

function code 에 BindingIdentifier 를 포함하는 실질적 효과는 주변 코드가 strict 모드 코드가 아니더라도 함수 본문에 "use strict" 지시문을 포함하는 함수 이름인 BindingIdentifier 에 strict 모드 코드의 Early Errors 가 적용되게 한다.

11.2.1 지시문 프로로그와 Use Strict 지시문(Directive Prologues and the Use Strict Directive)

Directive PrologueFunctionBody, ScriptBody, 또는 ModuleBody 의 처음 StatementListItem 들 또는 ModuleItem 들로 발생하는 ExpressionStatement 들의 가장 긴 시퀀스로서, 그 시퀀스의 각 ExpressionStatement 가 완전히 StringLiteral 토큰 뒤에 세미콜론이 따라오는 형태로만 구성된다. 세미콜론은 명시적으로 나타나거나 자동 세미콜론 삽입(12.10)에 의해 삽입될 수 있다. Directive Prologue 는 빈 시퀀스일 수 있다.

Use Strict DirectiveStringLiteral 이 정확히 "use strict" 또는 'use strict' 코드 포인트 시퀀스인 Directive Prologue 내의 ExpressionStatement 이다. Use Strict DirectiveEscapeSequence 또는 LineContinuation 을 포함할 수 없다.

Directive Prologue 는 둘 이상의 Use Strict Directive 를 포함할 수 있다. 단, 구현은 이 경우 경고를 발행할 수 있다.

Note

Directive PrologueExpressionStatement 들은 포함하는 생성물(production)을 평가하는 동안 정상적으로 평가된다. 구현은 Use Strict Directive 가 아니면서 Directive Prologue 에 등장하는 ExpressionStatement 에 대해 구현별 의미를 정의할 수 있다. 적절한 통지 메커니즘이 존재한다면, 구현은 Directive Prologue 에서 Use Strict Directive 가 아니고 구현이 정의한 의미도 가지지 않는 ExpressionStatement 를 발견할 경우 경고를 발행해야 한다.

11.2.2 Strict 모드 코드(Strict Mode Code)

ECMAScript 구문 단위는 비제한(unrestricted) 또는 strict 모드 문법과 의미론(4.3.2)을 사용하여 처리될 수 있다. 다음 상황에서 코드는 strict mode code 로 해석된다:

strict mode code 가 아닌 ECMAScript 코드는 non-strict code 라고 한다.

11.2.2.1 정적 의미론(Static Semantics): IsStrict ( node: a Parse Node, ): a Boolean

The abstract operation UNKNOWN takes UNPARSEABLE ARGUMENTS. It performs the following steps when called:

  1. node 가 매치한 소스 텍스트가 strict mode code 이면 true 반환; 그렇지 않으면 false 반환.

11.2.3 비 ECMAScript 함수(Non-ECMAScript Functions)

ECMAScript 구현은 평가 동작이 ECMAScript 소스 텍스트가 아닌 호스트 정의 실행 가능 코드 형태로 표현된 함수 이그조틱 객체의 평가를 지원할 수 있다. 함수 객체가 ECMAScript 코드 내에서 정의되었는지 또는 내장 함수인지 여부는 그러한 함수 객체를 호출하거나 그에 의해 호출되는 ECMAScript 코드의 관점에서는 관측할 수 없다.

12 ECMAScript 언어: 어휘 문법( Lexical Grammar )

ECMAScript Script 또는 Module 의 소스 텍스트는 먼저 입력 요소들의 시퀀스로 변환되는데, 이는 토큰(token), 줄 종결자(line terminator), 주석(comment), 또는 공백(white space)이다. 소스 텍스트는 왼쪽에서 오른쪽으로 스캔되며, 매번 가능한 한 가장 긴 코드 포인트 시퀀스를 다음 입력 요소로 선택한다.

입력 요소를 소비하는 구문 문법(syntactic grammar) 문맥에 따라 어휘 입력 요소 식별이 민감하게 달라지는 여러 상황이 있다. 이는 어휘 문법에 여러 목표 심볼(lexical goal symbol)이 필요한 이유이다. InputElementHashbangOrRegExp 목표는 Script 또는 Module 의 시작에서 사용된다. InputElementRegExpOrTemplateTail 목표는 RegularExpressionLiteral, TemplateMiddle 또는 TemplateTail 이 허용되는 구문 문맥에서 사용된다. InputElementRegExp 목표 심볼은 RegularExpressionLiteral 이 허용되지만 TemplateMiddleTemplateTail 은 허용되지 않는 모든 구문 문맥에서 사용된다. InputElementTemplateTail 목표는 TemplateMiddle 또는 TemplateTail 이 허용되지만 RegularExpressionLiteral 은 허용되지 않는 모든 구문 문맥에서 사용된다. 그 외 모든 문맥에서는 InputElementDiv 가 어휘 목표 심볼로 사용된다.

Note

여러 어휘 목표를 사용하는 것은 자동 세미콜론 삽입에 영향을 주는 어휘적 모호성이 없도록 보장한다. 예를 들어 선행 division 또는 division-assignment 와 선행 RegularExpressionLiteral 이 동시에 허용되는 구문 문맥은 존재하지 않는다. 이는 세미콜론 삽입 (12.10) 에 의해 영향을 받지 않는다. 다음 예와 같이:

a = b
/hi/g.exec(c).map(d);

LineTerminator 뒤의 첫 공백·주석이 아닌 코드 포인트가 U+002F (SOLIDUS) 이고, 구문 문맥이 division 또는 division-assignment 를 허용한다면, 해당 LineTerminator 위치에는 세미콜론이 삽입되지 않는다. 즉, 위 예는 다음과 동일하게 해석된다:

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)

유니코드 서식 제어 문자(즉, 유니코드 문자 데이터베이스 범주 “Cf” 에 속하는 LEFT-TO-RIGHT MARK, RIGHT-TO-LEFT MARK 등)는 상위 수준 프로토콜(예: 마크업 언어)이 없는 상황에서 텍스트 범위 서식을 제어하는 데 사용하는 제어 코드이다.

소스 텍스트에서 편집 및 표시를 용이하게 하기 위해 서식 제어 문자를 허용하는 것이 유용하다. 모든 서식 제어 문자는 주석 내부, 그리고 문자열 리터럴, 템플릿 리터럴, 정규 표현식 리터럴 내부에 사용할 수 있다.

U+FEFF (ZERO WIDTH NO-BREAK SPACE)는 주로 텍스트 시작 부분에서 해당 텍스트가 유니코드임을 표시하고 인코딩과 바이트 순서를 감지할 수 있도록 하는 서식 제어 문자이다. 이 목적을 위한 <ZWNBSP> 문자가 파일을 연결(concatenate)한 결과 등으로 텍스트 시작 이후에 나타나는 경우도 있다. ECMAScript 소스 텍스트에서 <ZWNBSP> 코드 포인트는 주석, 문자열 리터럴, 템플릿 리터럴, 정규 표현식 리터럴 밖에서는 공백 문자(12.2 참조)로 취급된다.

12.2 공백(White Space)

공백 코드 포인트는 소스 텍스트 가독성을 높이고 토큰(분할 불가능한 어휘 단위)들을 분리하기 위해 사용되며, 그 외에는 의미가 없다. 공백 코드 포인트는 임의의 두 토큰 사이 및 입력 시작과 끝에 나타날 수 있다. 공백 코드 포인트는 StringLiteral, RegularExpressionLiteral, Template, TemplateSubstitutionTail 내부에 나타날 수 있으며 그 경우 리터럴 값의 일부를 구성하는 의미 있는(code point)로 간주된다. Comment 내부에도 나타날 수 있지만 그 밖의 다른 종류의 토큰 내부에는 나타날 수 없다.

ECMAScript 공백 코드 포인트는 Table 33에 나열되어 있다.

Table 33: 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>
any code point in general category “Space_Separator” <USP>
Note 1

U+0020 (SPACE) 과 U+00A0 (NO-BREAK SPACE) 코드 포인트는 <USP> 에 속한다.

Note 2

Table 33 에 나열된 코드 포인트를 제외하고 ECMAScript WhiteSpace 는 “White_Space” 유니코드 속성을 가지지만 일반 범주 “Space_Separator”(“Zs”) 에 속하지 않는 모든 코드 포인트를 의도적으로 제외한다.

Syntax

WhiteSpace :: <TAB> <VT> <FF> <ZWNBSP> <USP>

12.3 줄 종결자(Line Terminators)

공백 코드 포인트와 마찬가지로 줄 종결자 코드 포인트는 소스 텍스트 가독성을 높이고 토큰을 서로 분리한다. 그러나 공백 코드 포인트와 달리 줄 종결자는 구문 문법 동작에 일부 영향을 준다. 일반적으로 줄 종결자는 임의의 두 토큰 사이에 나타날 수 있지만, 구문 문법이 금지하는 몇몇 위치에는 나타날 수 없다. 줄 종결자는 자동 세미콜론 삽입 과정(12.10)에도 영향을 준다. 줄 종결자는 StringLiteral, Template, TemplateSubstitutionTail 을 제외한 어떤 토큰 내부에도 나타날 수 없다. <LF> 및 <CR> 줄 종결자는 LineContinuation 의 일부가 아닌 한 StringLiteral 토큰 내부에 나타날 수 없다.

줄 종결자는 MultiLineComment 내부에 나타날 수 있지만 SingleLineComment 내부에는 나타날 수 없다.

줄 종결자는 정규 표현식에서 \s 클래스가 매칭하는 공백 코드 포인트 집합에 포함된다.

ECMAScript 줄 종결자 코드 포인트는 Table 34에 나열되어 있다.

Table 34: 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 34 의 유니코드 코드 포인트만 줄 종결자로 취급된다. 다른 개행(new line) 또는 줄 분리(line breaking) 유니코드 코드 포인트는 줄 종결자로 취급되지 않지만 Table 33 에 명시된 요구를 만족하면 공백으로 취급된다. 시퀀스 <CR><LF> 는 일반적으로 하나의 줄 종결자로 사용된다. 행 번호 보고 목적으로는 단일 SourceCharacter 로 간주해야 한다.

Syntax

LineTerminator :: <LF> <CR> <LS> <PS> LineTerminatorSequence :: <LF> <CR> [lookahead ≠ <LF>] <LS> <PS> <CR> <LF>

12.4 주석(Comments)

주석은 단일 행 또는 다중 행일 수 있다. 다중 행 주석은 중첩될 수 없다.

단일 행 주석은 LineTerminator 코드 포인트를 제외한 임의의 유니코드 코드 포인트를 포함할 수 있고, 토큰은 항상 가능한 한 가장 길게 인식된다는 일반 규칙 때문에, 단일 행 주석은 // 마커로부터 그 줄 끝까지의 모든 코드 포인트로 구성된다. 단, 줄 끝의 LineTerminator 는 단일 행 주석의 일부로 간주되지 않으며 어휘 문법에 의해 별도로 인식되어 구문 문법을 위한 입력 요소 스트림의 일부가 된다. 이 점은 단일 행 주석의 존재 여부가 자동 세미콜론 삽입 과정 (12.10) 에 영향을 주지 않음을 의미하므로 매우 중요하다.

주석은 공백처럼 동작하며 폐기되지만, MultiLineComment 가 줄 종결자 코드 포인트를 포함하면 구문 문법이 파싱할 때 전체 주석이 LineTerminator 로 간주된다.

Syntax

Comment :: MultiLineComment SingleLineComment MultiLineComment :: /* MultiLineCommentCharsopt */ MultiLineCommentChars :: MultiLineNotAsteriskChar MultiLineCommentCharsopt * PostAsteriskCommentCharsopt PostAsteriskCommentChars :: MultiLineNotForwardSlashOrAsteriskChar MultiLineCommentCharsopt * PostAsteriskCommentCharsopt MultiLineNotAsteriskChar :: SourceCharacter but not * MultiLineNotForwardSlashOrAsteriskChar :: SourceCharacter but not one of / or * SingleLineComment :: // SingleLineCommentCharsopt SingleLineCommentChars :: SingleLineCommentChar SingleLineCommentCharsopt SingleLineCommentChar :: SourceCharacter but not LineTerminator

이 절의 다수 생성물은 B.1.1 절에서 대체 정의를 가진다.

12.5 Hashbang 주석(Hashbang Comments)

Hashbang 주석은 위치에 민감하며 다른 종류의 주석처럼 구문 문법 입력 요소 스트림에서 제거(discard)된다.

Syntax

HashbangComment :: #! SingleLineCommentCharsopt

12.6 토큰(Tokens)

Syntax

CommonToken :: IdentifierName PrivateIdentifier Punctuator NumericLiteral StringLiteral Template Note

DivPunctuator, RegularExpressionLiteral, RightBracePunctuator, TemplateSubstitutionTail 생성물은 CommonToken 생성물에 포함되지 않는 추가 토큰을 도출한다.

12.7 이름과 키워드(Names and Keywords)

IdentifierNameReservedWord 는 Unicode Standard Annex #31 (Identifier and Pattern Syntax)에 규정된 기본 식별자 문법(Default Identifier Syntax)을 (소규모 수정과 함께) 따른 토큰이다. ReservedWordIdentifierName 의 열거된 부분집합이다. 구문 문법은 IdentifierIdentifierName 이면서 ReservedWord 가 아닌 것으로 정의한다. 유니코드 식별자 문법은 유니코드 표준이 규정한 문자 속성에 기반한다. 최신 유니코드 표준 버전에 지정된 범주의 유니코드 코드 포인트는 모든 적합 ECMAScript 구현에서 그 범주에 속한 것으로 취급되어야 한다. ECMAScript 구현은 추후판 유니코드 표준에서 정의된 식별자 코드 포인트를 추가로 인식할 수 있다.

Note 1

본 표준은 특정 코드 포인트 추가를 지정한다: U+0024 (DOLLAR SIGN) 과 U+005F (LOW LINE)는 IdentifierName 내 어디서든 허용된다.

Syntax

PrivateIdentifier :: # IdentifierName IdentifierName :: IdentifierStart IdentifierName IdentifierPart IdentifierStart :: IdentifierStartChar \ UnicodeEscapeSequence IdentifierPart :: IdentifierPartChar \ UnicodeEscapeSequence IdentifierStartChar :: UnicodeIDStart $ _ IdentifierPartChar :: UnicodeIDContinue $ AsciiLetter :: one of a b c d e f g h i j k l m n o p q r s t u v w x y z A B C D E F G H I J K L M N O P Q R S T U V W X Y Z UnicodeIDStart :: any Unicode code point with the Unicode property “ID_Start” UnicodeIDContinue :: any Unicode code point with the Unicode property “ID_Continue”

비단말 UnicodeEscapeSequence 의 정의는 12.9.4에 있다.

Note 2

비단말 IdentifierPartUnicodeIDContinue 를 통해 _ 를 도출한다.

Note 3

유니코드 속성 “ID_Start” 와 “ID_Continue” 를 가진 코드 포인트 집합은 각각 “Other_ID_Start” 및 “Other_ID_Continue” 속성의 코드 포인트를 포함한다.

12.7.1 식별자 이름(Identifier Names)

유니코드 이스케이프 시퀀스는 IdentifierName 내에서 허용되며 해당 UnicodeEscapeSequence 의 IdentifierCodePoint 와 동일한 단일 유니코드 코드 포인트를 기여한다. UnicodeEscapeSequence 앞의 \ 는 어떠한 코드 포인트도 기여하지 않는다. UnicodeEscapeSequence 는 원래라면 무효인 코드 포인트를 IdentifierName 에 기여하는 데 사용할 수 없다. 즉 \ UnicodeEscapeSequence 시퀀스를 그것이 기여하는 SourceCharacter 로 치환해도 결과는 동일한 SourceCharacter 시퀀스를 가지는 여전히 유효한 IdentifierName 이어야 한다. 본 명세에서 IdentifierName 의 해석은 특정 코드 포인트가 이스케이프로 입력되었는지 여부와 관계없이 실제 코드 포인트에 기반한다.

유니코드 표준에 따라 정규적으로 등가(canonically equivalent)인 두 IdentifierName 은 각 UnicodeEscapeSequence 를 치환한 뒤 정확히 동일한 코드 포인트 시퀀스로 표현되지 않는 한 동일하지 않다.

12.7.1.1 정적 의미론: 조기 오류(Early Errors)

IdentifierStart :: \ UnicodeEscapeSequence IdentifierPart :: \ UnicodeEscapeSequence

12.7.1.2 정적 의미론: IdentifierCodePoints : 코드 포인트 List

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. It is defined piecewise over the following productions:

IdentifierName :: IdentifierStart
  1. cpIdentifierStart 의 IdentifierCodePoint 로 둔다.
  2. « cp » 반환.
IdentifierName :: IdentifierName IdentifierPart
  1. cps 를 파생된 IdentifierName 의 IdentifierCodePoints 로 둔다.
  2. cpIdentifierPart 의 IdentifierCodePoint 로 둔다.
  3. cps 와 « cp » 의 리스트 연결을 반환한다.

12.7.1.3 정적 의미론: IdentifierCodePoint : 코드 포인트

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. It is defined piecewise over the following productions:

IdentifierStart :: IdentifierStartChar
  1. IdentifierStartChar 가 매칭한 코드 포인트 반환.
IdentifierPart :: IdentifierPartChar
  1. IdentifierPartChar 가 매칭한 코드 포인트 반환.
UnicodeEscapeSequence :: u Hex4Digits
  1. Hex4Digits 의 MV 인 수치 값을 가진 코드 포인트 반환.
UnicodeEscapeSequence :: u{ CodePoint }
  1. CodePoint 의 MV 인 수치 값을 가진 코드 포인트 반환.

12.7.2 키워드와 예약어(Keywords and Reserved Words)

키워드(keyword)IdentifierName 에 매칭되면서 구문적 용도를 가지는 토큰, 즉 어떤 구문 생성물에 고정폭(fixed width) 글꼴로 문자 그대로 등장하는 토큰이다. ECMAScript 키워드에는 if, while, async, await 등 다수가 포함된다.

예약어(reserved word) 는 식별자로 사용할 수 없는 IdentifierName 이다. 다수 키워드는 예약어이지만 아닌 것도 있으며 어떤 것은 특정 문맥에서만 예약된다. if, while 은 항상 예약어이다. await 는 async 함수 및 모듈 내부에서만 예약된다. async 는 예약되지 않으며 제한 없이 변수 이름이나 레이블로 사용할 수 있다.

이 명세는 문법 생성물과 조기 오류 규칙을 조합하여 어떤 이름이 유효한 식별자이고 어떤 것이 예약어인지 지정한다. 아래 ReservedWord 목록의 모든 토큰( await, yield 제외)은 무조건 예약된다. await, yield 예외는 매개변수화된 구문 생성물을 사용하는 13.1 에서 지정된다. 마지막으로 여러 조기 오류 규칙이 유효한 식별자 집합을 제한한다. 13.1.1, 14.3.1.1, 14.7.5.1, 15.7.1 참조. 요약하면 식별자 이름은 다섯 범주로 나뉜다:

  • Math, window, toString, _ 처럼 항상 식별자로 허용되고 키워드가 아닌 것;

  • await, yield 를 제외한 아래 ReservedWord 들처럼 결코 식별자로 허용되지 않는 것;

  • await, yield 처럼 문맥적으로 식별자로 허용되는 것;

  • strict 모드 코드에서 문맥적으로 식별자로 허용되지 않는 것: let, static, implements, interface, package, private, protected, public;

  • as, async, from, get, meta, of, set, target 처럼 항상 식별자로 허용되지만 특정 구문 생성물 안에서 Identifier 가 허용되지 않는 위치에 키워드로 나타나기도 하는 것.

조건부 키워드 또는 문맥적 키워드(contextual keyword) 라는 용어는 마지막 세 범주에 속해 어떤 문맥에서는 식별자, 다른 문맥에서는 키워드로 쓰일 수 있는 키워드를 가리킬 때 사용되기도 한다.

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 에 따라 문법의 키워드는 특정 SourceCharacter 요소들의 리터럴 시퀀스에 매칭된다. 키워드 내 코드 포인트는 \ UnicodeEscapeSequence 로 표현될 수 없다.

IdentifierName\ UnicodeEscapeSequence 를 포함할 수 있지만 els\u{65} 처럼 작성하여 이름이 "else" 인 변수를 선언할 수는 없다. 13.1.1 의 조기 오류 규칙이 예약어와 StringValue 가 동일한 식별자를 배제한다.

Note 2

enum 은 현재 본 명세에서 키워드로 사용되지 않는다. 이는 향후 언어 확장을 위해 예약된 미래 예약어 (future reserved word)이다.

마찬가지로 implements, interface, package, private, protected, public 는 strict 모드 코드에서 미래 예약어이다.

Note 3

argumentseval 은 키워드는 아니지만 strict 모드 코드에서 몇 가지 제약을 받는다. 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 리터럴(Null Literals)

Syntax

NullLiteral :: null

12.9.2 Boolean 리터럴(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 은 오류이며 3in 두 입력 요소가 아니다.

12.9.3.1 정적 의미론: 조기 오류(Early Errors)

NumericLiteral :: LegacyOctalIntegerLiteral DecimalIntegerLiteral :: NonOctalDecimalIntegerLiteral
  • IsStrict(this production) 이 true 이면 Syntax Error.
Note
비 strict 코드에서 이 문법은 레거시이다.

12.9.3.2 정적 의미론: MV

숫자 리터럴은 Number 타입 또는 BigInt 타입의 값을 나타낸다.

12.9.3.3 정적 의미론: NumericValue : Number 또는 BigInt

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. It is defined piecewise over the following productions:

NumericLiteral :: DecimalLiteral
  1. RoundMVResult(DecimalLiteral MV) 반환.
NumericLiteral :: NonDecimalIntegerLiteral
  1. 𝔽(NonDecimalIntegerLiteral MV) 반환.
NumericLiteral :: LegacyOctalIntegerLiteral
  1. 𝔽(LegacyOctalIntegerLiteral MV) 반환.
NumericLiteral :: NonDecimalIntegerLiteral BigIntLiteralSuffix
  1. NonDecimalIntegerLiteral MV 에 대한 BigInt 값 반환.
DecimalBigIntegerLiteral :: 0 BigIntLiteralSuffix
  1. 0 반환.
DecimalBigIntegerLiteral :: NonZeroDigit BigIntLiteralSuffix
  1. NonZeroDigit MV 에 대한 BigInt 값 반환.
DecimalBigIntegerLiteral :: NonZeroDigit DecimalDigits BigIntLiteralSuffix NonZeroDigit NumericLiteralSeparator DecimalDigits BigIntLiteralSuffix
  1. n = DecimalDigits 에서 NumericLiteralSeparator 제외한 코드 포인트 수.
  2. mv = (NonZeroDigit MV × 10n) + DecimalDigits MV.
  3. (mv) 반환.

12.9.4 문자열 리터럴(String Literals)

Note 1

문자열 리터럴은 작은따옴표 또는 큰따옴표로 둘러싸인 0개 이상의 유니코드 코드 포인트이다. 유니코드 코드 포인트는 이스케이프 시퀀스로도 표현할 수 있다. 닫는 따옴표 코드 포인트, U+005C (REVERSE SOLIDUS), U+000D (CR), U+000A (LF)를 제외한 모든 코드 포인트는 문자열 리터럴 안에 그대로 나타날 수 있다. 어떤 코드 포인트든 이스케이프 시퀀스 형태로 나타날 수 있다. 문자열 리터럴은 ECMAScript String 값을 평가 결과로 가진다. 이러한 String 값을 생성할 때 유니코드 코드 포인트는 11.1.1 에 정의된 대로 UTF-16 으로 인코딩된다. 기본 다국어 평면(BMP)의 코드 포인트는 하나의 코드 유닛으로, 그 밖의 코드 포인트는 두 코드 유닛으로 인코딩된다.

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

비단말 HexDigit 정의는 12.9.3, SourceCharacter11.1 에 있다.

Note 2

<LF>, <CR> 은 LineContinuation 일부가 아닌 한 문자열 리터럴 내에 나타날 수 없다(빈 코드 포인트 시퀀스 생성). 문자열 값에 포함하려면 \n 또는 \u000A 같은 이스케이프를 사용해야 한다.

12.9.4.1 정적 의미론: 조기 오류(Early Errors)

EscapeSequence :: LegacyOctalEscapeSequence NonOctalDecimalEscapeSequence
  • IsStrict(this production) 이 true 이면 Syntax Error.
Note 1
비 strict 코드에서 이 문법은 레거시.
Note 2

문자열 리터럴이 뒤따르는 Use Strict Directive 를 통해 strict 모드가 되는 경우가 있으므로 구현은 위 규칙을 철저히 적용해야 한다. 예:

function invalid() { "\7"; "use strict"; }

12.9.4.2 정적 의미론: SV : String

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS.

문자열 리터럴은 String 타입 값에 해당한다. SV 는 문자열 리터럴의 여러 부분에 재귀 적용되어 String 값을 생성한다. 이 과정에서 문자열 리터럴 내 일부 유니코드 코드 포인트는 아래 또는 12.9.3 에 설명된 대로 수학적 값을 가진 것으로 해석된다.

Table 35: 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 정적 의미론: MV

12.9.5 정규 표현식 리터럴(Regular Expression Literals)

Note 1

정규 표현식 리터럴은 평가될 때마다 RegExp 객체 (22.2) 로 변환되는 입력 요소이다. 동일한 내용을 가진 두 리터럴이라도 서로 === 비교에서 같지 않다. 런타임에 new RegExp 또는 RegExp 생성자 호출 (22.2.4) 로도 생성할 수 있다.

아래 생성물은 정규 표현식 리터럴의 구문을 기술하며 입력 요소 스캐너가 리터럴 끝을 찾는 데 사용된다. RegularExpressionBodyRegularExpressionFlags 를 이루는 소스 텍스트는 이후 더 엄격한 ECMAScript 정규식 문법 (22.2.1) 으로 다시 파싱된다.

구현은 22.2.1 의 ECMAScript 정규식 문법을 확장할 수 있으나 아래 RegularExpressionBody, RegularExpressionFlags 생성물 및 그 종속 생성물은 확장할 수 없다.

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

정규 표현식 리터럴은 비어 있을 수 없다. // 는 빈 정규식이 아니라 단일 행 주석 시작이다. 빈 정규식을 지정하려면 /(?:)/ 사용.

12.9.5.1 정적 의미론: BodyText : 소스 텍스트

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. It is defined piecewise over the following productions:

RegularExpressionLiteral :: / RegularExpressionBody / RegularExpressionFlags
  1. RegularExpressionBody 로 인식된 소스 텍스트 반환.

12.9.5.2 정적 의미론: FlagText : 소스 텍스트

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. It is defined piecewise over the following productions:

RegularExpressionLiteral :: / RegularExpressionBody / RegularExpressionFlags
  1. RegularExpressionFlags 로 인식된 소스 텍스트 반환.

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 대안 어휘 목표에서 사용된다.

12.9.6.1 정적 의미론: TV : String 또는 undefined

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. 템플릿 리터럴 구성 요소는 TV 에 의해 String 타입 값으로 해석된다(TV 는 템플릿 객체의 인덱스된 값 목록—template values—구성에 사용). TV 에서는 이스케이프 시퀀스가 해당 유니코드 코드 포인트의 UTF-16 코드 유닛(들)로 치환된다.

12.9.6.2 정적 의미론: TRV : String

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. 템플릿 리터럴 구성 요소는 TRV 에 의해 String 값으로 해석(템플릿 raw 값 구성). TRV 는 TV 와 유사하지만 이스케이프 시퀀스를 그대로(문자열 상 표기 그대로) 반영한다.

Note

TV 는 LineContinuation 의 코드 유닛을 제외하지만 TRV 는 포함한다. <CR><LF>, <CR> 줄 종결 시퀀스는 TV 와 TRV 모두에서 <LF> 로 정규화된다. <CR> 또는 <CR><LF> 를 원형(raw) 그대로 포함하려면 명시적 TemplateEscapeSequence 가 필요하다.

12.10 자동 세미콜론 삽입(Automatic Semicolon Insertion)

대부분의 ECMAScript 문과 선언은 세미콜론으로 종료되어야 하며, 그 세미콜론은 항상 소스에 명시적으로 쓸 수 있다. 편의를 위해 특정 상황에서는 세미콜론을 생략할 수 있으며, 이 상황에서는 세미콜론이 소스 코드 토큰 스트림에 자동 삽입된다고 기술한다.

12.10.1 자동 세미콜론 삽입 규칙(Rules of Automatic Semicolon Insertion)

다음 규칙에서 “토큰(token)” 은 12 에 설명된 현재 어휘 목표 심볼을 사용해 실제로 인식된 어휘 토큰을 뜻한다.

세 가지 기본 규칙은 다음과 같다:

  1. 왼쪽에서 오른쪽으로 파싱 중 문법의 어떤 생성물에도 허용되지 않는 토큰(“오류 토큰(offending token)”)을 만났을 때, 아래 조건 중 하나 이상이 참이면 그 토큰 앞에 세미콜론을 자동 삽입한다:

    • 오류 토큰이 이전 토큰과 하나 이상의 LineTerminator 로 분리되어 있음.
    • 오류 토큰이 } 임.
    • 이전 토큰이 ) 이고 삽입된 세미콜론이 do-while 문(14.7.2) 종료 세미콜론으로 파싱될 수 있음.
  2. 입력 토큰 스트림 끝에 도달했고 파서가 목표 비단말의 단일 인스턴스로 파싱할 수 없다면 입력 스트림 끝에 세미콜론을 자동 삽입.
  3. 문법 생성물 중 제한 생성물(restricted production) 에 허용되는 토큰이지만 생성물 내 “[no LineTerminator here]” 주석 바로 뒤 등장할 수 있는 첫 토큰(제한 토큰)이며 그 제한 토큰이 이전 토큰과 하나 이상의 LineTerminator 로 분리되어 있다면 제한 토큰 앞에 세미콜론 자동 삽입.

그러나 추가 최우선 조건이 있다: 세미콜론이 빈 문(empty statement)으로 파싱되거나 for 문의 두 세미콜론 중 하나가 되게 하는 경우에는 자동 삽입되지 않는다 (14.7.4 참조).

Note

문법 내 유일한 제한 생성물은 다음과 같다:

UpdateExpression[Yield, Await] : LeftHandSideExpression[?Yield, ?Await] [no LineTerminator here] ++ LeftHandSideExpression[?Yield, ?Await] [no LineTerminator here] -- 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]

실질적 효과:

  • ++ / -- 가 후위(postfix)로 해석될 위치에서 그 앞에 LineTerminator 가 있으면 앞에 세미콜론 삽입.
  • continue, break, return, throw, yield 뒤에 LineTerminator 있으면 해당 토큰 뒤에 세미콜론 삽입.
  • 화살표 함수 매개변수 끝과 => 사이에 LineTerminator 있으면 세미콜론 삽입 후 구문 오류.
  • asyncfunction / 식별자 / ( 전에 LineTerminator 있으면 세미콜론 삽입, 이후 토큰과 같은 구성요소로 간주되지 않음.
  • async* 전에 LineTerminator 있으면 세미콜론 삽입 후 구문 오류.

프로그래머를 위한 요약:

  • 후위 ++ / -- 는 피연산자와 같은 줄에 둔다.
  • return, throw, yield 뒤 표현식은 같은 줄에서 시작.
  • break, continueLabelIdentifier 는 같은 줄.
  • 화살표 함수 매개변수와 => 는 같은 줄.
  • 비동기 함수/메서드 앞 async 는 바로 뒤 토큰과 같은 줄.

12.10.2 자동 세미콜론 삽입 예(Examples of Automatic Semicolon Insertion)

본 절은 비규범적이다.

다음 소스

{ 1 2 } 3

는 자동 삽입 규칙이 있어도 유효한 ECMAScript 문장이 아니다. 반면:

{ 1
2 } 3

역시 유효하지 않지만 자동 삽입으로 다음으로 변환된다:

{ 1
;2 ;} 3;

이는 유효한 문장이다.

다음 소스

for (a; b
)

는 유효하지 않으며 for 문 헤더 세미콜론은 자동 삽입되지 않으므로 변경되지 않는다.

다음 소스

return
a + b

는 다음으로 변환된다:

return;
a + b;
Note 1

a + bLineTerminator 로 인해 return 반환 값이 아니다.

다음 소스

a = b
++c

는 다음으로 변환된다:

a = b;
++c;
Note 2

++b 의 후위 연산자가 아니다 (줄 종결자 존재).

다음 소스

if (a > b)
else c = d

는 유효하지 않으며 else 앞에 자동 삽입되지 않는다 (그 위치 삽입 시 빈 문 생성).

다음 소스

a = b + c
(d + e).print()

는 변환되지 않는다. 괄호로 시작하는 두 번째 줄은 함수 호출 인수 목록으로 해석될 수 있기 때문이다:

a = b + c(d + e).print()

할당문이 왼쪽 괄호로 시작해야 한다면 이전 문 끝에 명시적으로 세미콜론을 쓰는 것이 좋다.

12.10.3 흥미로운 자동 세미콜론 삽입 사례(Interesting Cases of Automatic Semicolon Insertion)

본 절은 비규범적이다.

프로그래머는 자동 세미콜론 삽입에 의존하여 매우 적은 세미콜론으로 프로그램을 작성할 수 있다. 위에서 설명했듯 세미콜론은 모든 줄바꿈마다 삽입되지 않으며 줄 종결자를 넘어 여러 토큰에 의존할 수 있다.

새 구문 기능이 추가되면서 기존 자동 삽입에 의존하던 줄이 다른 방식으로 파싱될 수 있는 추가 생성물이 도입될 수 있다.

이 절에서는 앞선 소스 텍스트에 따라 세미콜론이 삽입될 수도/안 될 수도 있는 위치를 ‘흥미로운’ 사례로 본다. 이하에서는 이 ECMAScript 버전의 그러한 사례들을 기술한다.

12.10.3.1 문 목록에서의 흥미로운 사례(Statement Lists)

StatementList 에서 다수 StatementListItem 은 세미콜론으로 끝나며 자동 삽입으로 생략 가능하다. 그 결과 표현식이 끝나는 줄의 다음 줄이 아래 중 하나로 시작하면 끝에 세미콜론이 필요하다:

  • 여는 괄호 ((): 없으면 두 줄이 CallExpression 으로 결합.
  • 여는 대괄호 ([): 없으면 속성 접근으로 간주 (ArrayLiteral 또는 ArrayAssignmentPattern 아님).
  • 템플릿 리터럴 (`): 없으면 태그드 템플릿으로 해석(앞 표현식이 MemberExpression).
  • 단항 + 또는 -: 없으면 이항 연산 조합으로 해석될 수 있음.
  • 정규 표현식 리터럴: 없으면 /MultiplicativeOperator 로 해석될 여지.

12.10.3.2 “[no LineTerminator here]” 관련 사례

본 절은 비규범적이다.

ECMAScript 는 “[no LineTerminator here]” 를 포함하는 문법 생성물을 가진다. 이는 종종 문법에서 선택적 피연산자를 두기 위한 수단이다. 해당 위치에 LineTerminator 를 넣으면 선택적 피연산자가 없는 다른 생성물로 해석이 바뀐다.

이 절의 나머지 부분은 본 ECMAScript 버전의 이러한 생성물 사례들을 나열한다.

12.10.3.2.1 선택적 피연산자와 “[no LineTerminator here]” 를 가진 생성물 목록

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 는 문법상 BindingIdentifier 로 허용되며, 아래 정적 의미론에서 금지되어 다음과 같은 경우의 자동 세미콜론 삽입을 막는다:

let
await 0;

13.1.1 정적 의미론: 조기 오류(Early Errors)

BindingIdentifier : Identifier
  • IsStrict(this production) 가 true 이고 Identifier 의 StringValue 가 "arguments" 또는 "eval" 이면 Syntax Error.
IdentifierReference : yield BindingIdentifier : yield LabelIdentifier : yield
  • IsStrict(this production) 가 true 이면 Syntax Error.
IdentifierReference : await BindingIdentifier : await LabelIdentifier : await
  • 구문 문법의 목표 심볼이 Module 이면 Syntax Error.
BindingIdentifier[Yield, Await] : yield
  • 이 생성물이 [Yield] 매개변수를 가지면 Syntax Error.
BindingIdentifier[Yield, Await] : await
  • 이 생성물이 [Await] 매개변수를 가지면 Syntax Error.
IdentifierReference[Yield, Await] : Identifier BindingIdentifier[Yield, Await] : Identifier LabelIdentifier[Yield, Await] : Identifier
  • 이 생성물이 [Yield] 매개변수를 가지고 Identifier 의 StringValue 가 "yield" 이면 Syntax Error.
  • 이 생성물이 [Await] 매개변수를 가지고 Identifier 의 StringValue 가 "await" 이면 Syntax Error.
Identifier : IdentifierName but not ReservedWord
  • IsStrict(this phrase) 가 true 이고 IdentifierName 의 StringValue 가 "implements", "interface", "let", "package", "private", "protected", "public", "static", "yield" 중 하나이면 Syntax Error.
  • 구문 문법의 목표 심볼이 Module 이고 IdentifierName 의 StringValue 가 "await" 이면 Syntax Error.
  • IdentifierName 의 StringValue 가 yield, await 를 제외한 어느 ReservedWord 의 StringValue 와 같으면 Syntax Error.
Note

IdentifierName 의 StringValue 는 IdentifierName 내 유니코드 escape 시퀀스를 정규화하므로, 그러한 escape 로 ReservedWord 와 동일한 코드 포인트 시퀀스를 가진 Identifier 를 작성할 수 없다.

13.1.2 정적 의미론: StringValue : String

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. It is defined piecewise over the following productions:

IdentifierName :: IdentifierStart IdentifierName IdentifierPart
  1. idTextUnescapedIdentifierName 의 IdentifierCodePoints 로 둔다.
  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. IdentifierName 의 StringValue 를 반환한다.
PrivateIdentifier :: # IdentifierName
  1. 0x0023 (NUMBER SIGN) 과 IdentifierName 의 StringValue 의 문자열 연결을 반환한다.
ModuleExportName : StringLiteral
  1. StringLiteral 의 SV 를 반환한다.

13.1.3 런타임 의미론: 평가(Evaluation)

IdentifierReference : Identifier
  1. ResolveBinding(StringValue of Identifier) 를 반환한다.
IdentifierReference : yield
  1. ResolveBinding("yield") 를 반환한다.
IdentifierReference : await
  1. ResolveBinding("await") 를 반환한다.
Note 1

IdentifierReference 평가 결과는 항상 Reference 타입 값이다.

Note 2

비 strict 코드에서 키워드 yield 는 식별자로 사용할 수 있다. IdentifierReference 평가 시 yield 바인딩을 Identifier 처럼 해석한다. 조기 오류 제한이 그러한 평가가 비 strict 코드에서만 일어날 수 있게 보장한다.

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)

다음 생성물 인스턴스를 처리할 때
PrimaryExpression[Yield, Await] : CoverParenthesizedExpressionAndArrowParameterList[?Yield, ?Await]
CoverParenthesizedExpressionAndArrowParameterList 의 해석은 아래 문법을 사용해 정밀화된다:

ParenthesizedExpression[Yield, Await] : ( Expression[+In, ?Yield, ?Await] )

13.2.1 this 키워드(The this Keyword)

13.2.1.1 런타임 의미론: 평가(Evaluation)

PrimaryExpression : this
  1. ResolveThisBinding() 을 반환한다.

13.2.2 식별자 참조(Identifier Reference)

IdentifierReference13.1 를 참조.

13.2.3 리터럴(Literals)

Syntax

Literal : NullLiteral BooleanLiteral NumericLiteral StringLiteral

13.2.3.1 런타임 의미론: 평가(Evaluation)

Literal : NullLiteral
  1. null 을 반환한다.
Literal : BooleanLiteral
  1. BooleanLiteral 이 토큰 false 이면 false 반환.
  2. BooleanLiteral 이 토큰 true 이면 true 반환.
Literal : NumericLiteral
  1. 12.9.3 에 정의된 NumericLiteral 의 NumericValue 를 반환한다.
Literal : StringLiteral
  1. 12.9.4.2 에 정의된 StringLiteral 의 SV 를 반환한다.

13.2.4 배열 이니셜라이저(Array Initializer)

Note

ArrayLiteral 은 0 개 이상 표현식(각각 배열 요소를 나타냄) 리스트를 대괄호로 둘러 배열 초기화를 기술하는 표현식이다. 요소는 리터럴일 필요가 없으며 배열 이니셜라이저가 평가될 때마다 평가된다.

배열 요소는 목록의 시작·중간·끝에서 생략(elide)될 수 있다. 요소 목록에서 쉼표 앞에 AssignmentExpression 이 없을 때(즉, 시작의 쉼표나 또 다른 쉼표 뒤) 빠진 요소는 배열 length 에 기여하며 이후 요소의 인덱스를 증가시킨다. 생략된 요소는 정의되지 않는다. 배열 끝에서 생략된 요소는 length 에 기여하지 않는다.

Syntax

ArrayLiteral[Yield, Await] : [ Elisionopt ] [ ElementList[?Yield, ?Await] ] [ ElementList[?Yield, ?Await] , Elisionopt ] ElementList[Yield, Await] : Elisionopt AssignmentExpression[+In, ?Yield, ?Await] Elisionopt SpreadElement[?Yield, ?Await] ElementList[?Yield, ?Await] , Elisionopt AssignmentExpression[+In, ?Yield, ?Await] ElementList[?Yield, ?Await] , Elisionopt SpreadElement[?Yield, ?Await] Elision : , Elision , SpreadElement[Yield, Await] : ... AssignmentExpression[+In, ?Yield, ?Await]

13.2.4.1 런타임 의미론: ArrayAccumulation : 정상 완료 시 정수 또는 abrupt completion

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. It is defined piecewise over the following productions:

Elision : ,
  1. lennextIndex + 1 로 둔다.
  2. Set(array, "length", 𝔽(len), true) 수행.
  3. NOTE: len 이 232 - 1 을 초과하면 위 단계는 throw.
  4. len 을 반환한다.
Elision : Elision ,
  1. Elision 의 ArrayAccumulation 을 (array, (nextIndex + 1)) 인수로 호출한 결과를 ? 로 반환한다.
ElementList : Elisionopt AssignmentExpression
  1. Elision 이 존재하면
    1. nextIndexElision 의 ArrayAccumulation(array, nextIndex) 결과로 설정 (?).
  2. initResultAssignmentExpression 의 Evaluation 결과 (?) 로 둔다.
  3. initValue 를 ? GetValue(initResult) 로 둔다.
  4. CreateDataPropertyOrThrow(array, ! ToString(𝔽(nextIndex)), initValue) 수행.
  5. nextIndex + 1 반환.
ElementList : Elisionopt SpreadElement
  1. Elision 이 존재하면
    1. nextIndexElision 의 ArrayAccumulation(array, nextIndex) 결과로 설정 (?).
  2. SpreadElement 의 ArrayAccumulation(array, nextIndex) 결과를 ? 로 반환한다.
ElementList : ElementList , Elisionopt AssignmentExpression
  1. nextIndexElementList 의 ArrayAccumulation(array, nextIndex) 결과로 설정 (?).
  2. Elision 이 존재하면
    1. nextIndexElision 의 ArrayAccumulation(array, nextIndex) 결과로 설정 (?).
  3. initResultAssignmentExpression Evaluation 결과 (?) 로 둔다.
  4. initValue 를 ? GetValue(initResult) 로 둔다.
  5. CreateDataPropertyOrThrow(array, ! ToString(𝔽(nextIndex)), initValue) 수행.
  6. nextIndex + 1 반환.
ElementList : ElementList , Elisionopt SpreadElement
  1. nextIndexElementList 의 ArrayAccumulation(array, nextIndex) 결과로 설정 (?).
  2. Elision 이 존재하면
    1. nextIndexElision 의 ArrayAccumulation(array, nextIndex) 결과로 설정 (?).
  3. SpreadElement 의 ArrayAccumulation(array, nextIndex) 결과를 ? 로 반환.
SpreadElement : ... AssignmentExpression
  1. spreadRefAssignmentExpression Evaluation 결과 (?) 로 둔다.
  2. spreadObj 를 ? GetValue(spreadRef) 로 둔다.
  3. iteratorRecord 를 ? GetIterator(spreadObj, sync) 로 둔다.
  4. 반복,
    1. next 를 ? IteratorStepValue(iteratorRecord) 로 둔다.
    2. nextdone 이면 nextIndex 반환.
    3. CreateDataPropertyOrThrow(array, ! ToString(𝔽(nextIndex)), next) 수행.
    4. nextIndexnextIndex + 1 로 설정.
Note

CreateDataPropertyOrThrow 는 표준 내장 Array 프로토타입이 [[Set]] 으로 새로운 자체 프로퍼티 생성을 막도록 수정된 경우에도 자체 프로퍼티 정의를 보장하기 위해 사용된다.

13.2.4.2 런타임 의미론: 평가(Evaluation)

ArrayLiteral : [ Elisionopt ]
  1. array 를 ! ArrayCreate(0) 로 둔다.
  2. Elision 이 존재하면
    1. Elision 의 ArrayAccumulation(array, 0) 를 ? 로 수행.
  3. array 반환.
ArrayLiteral : [ ElementList ]
  1. array 를 ! ArrayCreate(0) 로 둔다.
  2. ElementList 의 ArrayAccumulation(array, 0) 를 ? 로 수행.
  3. array 반환.
ArrayLiteral : [ ElementList , Elisionopt ]
  1. array 를 ! ArrayCreate(0) 로 둔다.
  2. nextIndexElementList 의 ArrayAccumulation(array, 0) 결과 (?) 로 둔다.
  3. Elision 이 존재하면
    1. Elision 의 ArrayAccumulation(array, nextIndex) 를 ? 로 수행.
  4. array 반환.

13.2.5 객체 이니셜라이저(Object Initializer)

Note 1

객체 이니셜라이저는 리터럴과 유사한 형태로 객체 초기화를 기술하는 표현식이다. 중괄호로 둘러싸인 0 개 이상 (프로퍼티 키, 값) 쌍 목록이며 값은 리터럴일 필요가 없고 이니셜라이저 평가 시마다 평가된다.

Syntax

ObjectLiteral[Yield, Await] : { } { PropertyDefinitionList[?Yield, ?Await] } { PropertyDefinitionList[?Yield, ?Await] , } PropertyDefinitionList[Yield, Await] : PropertyDefinition[?Yield, ?Await] PropertyDefinitionList[?Yield, ?Await] , PropertyDefinition[?Yield, ?Await] PropertyDefinition[Yield, Await] : IdentifierReference[?Yield, ?Await] CoverInitializedName[?Yield, ?Await] PropertyName[?Yield, ?Await] : AssignmentExpression[+In, ?Yield, ?Await] MethodDefinition[?Yield, ?Await] ... AssignmentExpression[+In, ?Yield, ?Await] PropertyName[Yield, Await] : LiteralPropertyName ComputedPropertyName[?Yield, ?Await] LiteralPropertyName : IdentifierName StringLiteral NumericLiteral ComputedPropertyName[Yield, Await] : [ AssignmentExpression[+In, ?Yield, ?Await] ] CoverInitializedName[Yield, Await] : IdentifierReference[?Yield, ?Await] Initializer[+In, ?Yield, ?Await] Initializer[In, Yield, Await] : = AssignmentExpression[?In, ?Yield, ?Await] Note 2

MethodDefinition15.4 에 정의되어 있다.

Note 3

특정 문맥에서 ObjectLiteral 은 더 제한된 2차 문법을 덮는 cover 문법으로 사용된다. CoverInitializedName 생성물은 이러한 2차 문법을 완전히 덮기 위해 필요하다. 그러나 이 생성물 사용은 실제 ObjectLiteral 이 기대되는 일반 문맥에서 조기 Syntax Error 를 발생시킨다.

13.2.5.1 정적 의미론: 조기 오류(Early Errors)

PropertyDefinition : MethodDefinition

실제 객체 이니셜라이저를 기술하는 것 외에도 ObjectLiteral 생성물은 ObjectAssignmentPattern 의 cover 문법으로 사용될 수 있으며 CoverParenthesizedExpressionAndArrowParameterList 의 일부로 인식될 수 있다. ObjectLiteralObjectAssignmentPattern 이 필요한 문맥에 나타나면 아래 Early Error 규칙은 적용되지 않는다. 또한 초기 CoverParenthesizedExpressionAndArrowParameterList 또는 CoverCallExpressionAndAsyncArrowHead 파싱 시에도 적용되지 않는다.

PropertyDefinition : CoverInitializedName
  • 이 생성물이 어떤 소스 텍스트를 매칭하면 Syntax Error.
Note 1

이 생성물은 ObjectLiteralObjectAssignmentPattern 의 cover 문법이 되도록 존재한다. 실제 객체 이니셜라이저에는 나타날 수 없다.

ObjectLiteral : { PropertyDefinitionList } { PropertyDefinitionList , } Note 2

PropertyNameList 가 반환한 ListComputedPropertyName 으로 정의된 프로퍼티 이름을 포함하지 않는다.

13.2.5.2 정적 의미론: IsComputedPropertyKey : Boolean

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. It is defined piecewise over the following productions:

PropertyName : LiteralPropertyName
  1. false 반환.
PropertyName : ComputedPropertyName
  1. true 반환.

13.2.5.3 정적 의미론: PropertyNameList : String 들의 List

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. It is defined piecewise over the following productions:

PropertyDefinitionList : PropertyDefinition
  1. propNamePropertyDefinition 의 PropName 으로 둔다.
  2. propNameempty 이면 새 빈 List 반환.
  3. « propName » 반환.
PropertyDefinitionList : PropertyDefinitionList , PropertyDefinition
  1. listPropertyDefinitionList 의 PropertyNameList 로 둔다.
  2. propNamePropertyDefinition 의 PropName 으로 둔다.
  3. propNameempty 이면 list 반환.
  4. list 와 « propName » 의 리스트 연결 반환.

13.2.5.4 런타임 의미론: 평가(Evaluation)

ObjectLiteral : { }
  1. OrdinaryObjectCreate(%Object.prototype%) 반환.
ObjectLiteral : { PropertyDefinitionList } { PropertyDefinitionList , }
  1. objOrdinaryObjectCreate(%Object.prototype%) 로 둔다.
  2. PropertyDefinitionList 의 PropertyDefinitionEvaluation(obj) 를 ? 로 수행.
  3. obj 반환.
LiteralPropertyName : IdentifierName
  1. IdentifierName 의 StringValue 반환.
LiteralPropertyName : StringLiteral
  1. StringLiteral 의 SV 반환.
LiteralPropertyName : NumericLiteral
  1. nbrNumericLiteral 의 NumericValue 로 둔다.
  2. ToString(nbr) 반환.
ComputedPropertyName : [ AssignmentExpression ]
  1. exprValueAssignmentExpression Evaluation 결과 (?) 로 둔다.
  2. propName 을 ? GetValue(exprValue) 로 둔다.
  3. ToPropertyKey(propName) 반환.

13.2.5.5 런타임 의미론: PropertyDefinitionEvaluation : unused 를 담는 정상 완료 또는 abrupt completion

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. It is defined piecewise over the following productions:

PropertyDefinitionList : PropertyDefinitionList , PropertyDefinition
  1. PropertyDefinitionList 의 PropertyDefinitionEvaluation(object) 를 ? 로 수행.
  2. PropertyDefinition 의 PropertyDefinitionEvaluation(object) 를 ? 로 수행.
  3. unused 반환.
PropertyDefinition : ... AssignmentExpression
  1. exprValueAssignmentExpression Evaluation 결과 (?) 로 둔다.
  2. fromValue 를 ? GetValue(exprValue) 로 둔다.
  3. excludedNames 를 새 빈 List 로 둔다.
  4. CopyDataProperties(object, fromValue, excludedNames) 수행.
  5. unused 반환.
PropertyDefinition : IdentifierReference
  1. propNameIdentifierReference 의 StringValue 로 둔다.
  2. exprValueIdentifierReference Evaluation 결과 (?) 로 둔다.
  3. propValue 를 ? GetValue(exprValue) 로 둔다.
  4. 단언: object 는 비구성 불가능한 프로퍼티가 없는 보통의(extensible) 객체.
  5. CreateDataPropertyOrThrow(object, propName, propValue) 수행.
  6. unused 반환.
PropertyDefinition : PropertyName : AssignmentExpression
  1. propKeyPropertyName Evaluation 결과 (?) 로 둔다.
  2. PropertyDefinitionParseJSON 평가 중인 Script 에 포함 (ParseJSON 단계 6) 이면
    1. isProtoSetterfalse 로 둔다.
  3. Else if propKey"__proto__" 이고 PropertyName 의 IsComputedPropertyKey 가 false 이면
    1. isProtoSettertrue 로 둔다.
  4. Else,
    1. isProtoSetterfalse 로 둔다.
  5. IsAnonymousFunctionDefinition(AssignmentExpression) 이 true 이고 isProtoSetterfalse 이면
    1. propValueAssignmentExpression 의 NamedEvaluation(propKey) 결과 (?) 로 둔다.
  6. Else,
    1. exprValueRefAssignmentExpression Evaluation 결과 (?) 로 둔다.
    2. propValue 를 ? GetValue(exprValueRef) 로 둔다.
  7. isProtoSettertrue 이면
    1. propValue 가 Object 이거나 null 이면
      1. object.[[SetPrototypeOf]](propValue) 수행.
    2. unused 반환.
  8. 단언: object 는 비구성 불가능한 프로퍼티가 없는 보통의 확장 가능한 객체.
  9. CreateDataPropertyOrThrow(object, propKey, propValue) 수행.
  10. unused 반환.
PropertyDefinition : MethodDefinition
  1. MethodDefinition 의 MethodDefinitionEvaluation(object, true) 를 ? 로 수행.
  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 정적 의미론: 조기 오류(Early Errors)

PrimaryExpression : RegularExpressionLiteral

13.2.7.2 정적 의미론: IsValidRegularExpressionLiteral ( literal: a RegularExpressionLiteral Parse Node, ): Boolean

The abstract operation UNKNOWN takes UNPARSEABLE ARGUMENTS. 인수가 유효한 정규 표현식 리터럴인지 판정한다. It performs the following steps when called:

  1. flagsliteral 의 FlagText 로 둔다.
  2. flagsd, g, i, m, s, u, v, y 이외 코드 포인트를 포함하거나 동일 코드 포인트를 중복 포함하면 false 반환.
  3. flagsu 포함하면 u = true, 아니면 false.
  4. flagsv 포함하면 v = true, 아니면 false.
  5. patternTextliteral 의 BodyText 로 둔다.
  6. ufalse 이고 vfalse 이면
    1. stringValue 를 CodePointsToString(patternText) 로 둔다.
    2. stringValue 의 16비트 요소 각각을 유니코드 BMP 코드 포인트로 해석한 코드 포인트 시퀀스로 patternText 재설정 (UTF-16 디코딩 미적용).
  7. parseResult 를 ParsePattern(patternText, u, v) 로 둔다.
  8. parseResult 가 Parse Node 이면 true 반환; 아니면 false 반환.

13.2.7.3 런타임 의미론: 평가(Evaluation)

PrimaryExpression : RegularExpressionLiteral
  1. pattern 을 CodePointsToString(BodyText of RegularExpressionLiteral) 로 둔다.
  2. flags 를 CodePointsToString(FlagText of RegularExpressionLiteral) 로 둔다.
  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 정적 의미론: 조기 오류(Early Errors)

TemplateLiteral[Yield, Await, Tagged] : NoSubstitutionTemplate TemplateLiteral[Yield, Await, Tagged] : SubstitutionTemplate[?Yield, ?Await, ?Tagged]
  • 인수 false 로 한 TemplateLiteral 의 TemplateStrings 요소 수가 232 이상이면 Syntax Error.
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 정적 의미론: TemplateStrings : String 또는 undefined 요소들의 List

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. It is defined piecewise over the following productions:

TemplateLiteral : NoSubstitutionTemplate
  1. « TemplateString(NoSubstitutionTemplate, raw) » 반환.
SubstitutionTemplate : TemplateHead Expression TemplateSpans
  1. head 를 « TemplateString(TemplateHead, raw) » 로 둔다.
  2. tailTemplateSpans 의 TemplateStrings(raw) 로 둔다.
  3. headtail 의 리스트 연결 반환.
TemplateSpans : TemplateTail
  1. « TemplateString(TemplateTail, raw) » 반환.
TemplateSpans : TemplateMiddleList TemplateTail
  1. middleTemplateMiddleList 의 TemplateStrings(raw) 로 둔다.
  2. tail 을 « TemplateString(TemplateTail, raw) » 로 둔다.
  3. 리스트 연결 반환.
TemplateMiddleList : TemplateMiddle Expression
  1. « TemplateString(TemplateMiddle, raw) » 반환.
TemplateMiddleList : TemplateMiddleList TemplateMiddle Expression
  1. frontTemplateMiddleList 의 TemplateStrings(raw) 로 둔다.
  2. last 를 « TemplateString(TemplateMiddle, raw) » 로 둔다.
  3. frontlast 리스트 연결 반환.

13.2.8.3 정적 의미론: TemplateString ( templateToken: NoSubstitutionTemplate / TemplateHead / TemplateMiddle / TemplateTail Parse Node, raw: Boolean, ): String 또는 undefined

The abstract operation UNKNOWN takes UNPARSEABLE ARGUMENTS. It performs the following steps when called:

  1. rawtrue 이면
    1. stringtemplateToken 의 TRV 로 둔다.
  2. Else
    1. stringtemplateToken 의 TV 로 둔다.
  3. string 반환.
Note

rawfalse 이고 templateTokenNotEscapeSequence 포함 시 undefined 반환. 그 외에는 String 반환.

13.2.8.4 GetTemplateObject ( templateLiteral )

The abstract operation GetTemplateObject takes argument templateLiteral (Parse Node) and returns Array. It performs the following steps when called:

  1. realm 을 현재 Realm Record 로 둔다.
  2. templateRegistryrealm.[[TemplateMap]] 로 둔다.
  3. templateRegistry 의 각 요소 e 에 대해
    1. e.[[Site]]templateLiteral 과 같은 Parse Node 이면
      1. e.[[Array]] 반환.
  4. rawStringstemplateLiteral 의 TemplateStrings(true) 로 둔다.
  5. 단언: rawStrings 는 String 들의 List.
  6. cookedStringstemplateLiteral 의 TemplateStrings(false) 로 둔다.
  7. countcookedStrings 요소 수로 둔다.
  8. 단언: count ≤ 232 - 1.
  9. template 를 ! ArrayCreate(count) 로 둔다.
  10. rawObj 를 ! ArrayCreate(count) 로 둔다.
  11. index 를 0 으로 둔다.
  12. index < count 동안 반복,
    1. prop 를 ! ToString(𝔽(index)) 로 둔다.
    2. cookedValuecookedStrings[index] 로 둔다.
    3. DefinePropertyOrThrow(template, prop, PropertyDescriptor { [[Value]]: cookedValue, [[Writable]]: false, [[Enumerable]]: true, [[Configurable]]: false }) 수행.
    4. rawValuerawStrings[index] 의 String 값으로 둔다.
    5. DefinePropertyOrThrow(rawObj, prop, 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]] 에 추가.
  17. template 반환.
Note 1

템플릿 객체 생성은 abrupt completion 을 일으킬 수 없다.

Note 2

realm 의 프로그램 코드 내 각 TemplateLiteral 은 태그드 템플릿 (13.2.8.6) 평가에 사용되는 고유한 템플릿 객체와 연관된다. 템플릿 객체는 freeze 되고 동일 템플릿이 평가될 때마다 같은 객체가 재사용된다. 지연 생성 또는 사전 생성 여부는 구현 선택이며 관측 불가.

Note 3

향후 판에서 템플릿 객체의 비열거(non-enumerable) 프로퍼티가 추가로 정의될 수 있다.

13.2.8.5 런타임 의미론: SubstitutionEvaluation : ECMAScript 값 List 를 담는 정상 완료 또는 abrupt completion

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. It is defined piecewise over the following productions:

TemplateSpans : TemplateTail
  1. 새 빈 List 반환.
TemplateSpans : TemplateMiddleList TemplateTail
  1. TemplateMiddleList 의 SubstitutionEvaluation 결과를 ? 로 반환.
TemplateMiddleList : TemplateMiddle Expression
  1. subRefExpression Evaluation 결과 (?) 로 둔다.
  2. sub 를 ? GetValue(subRef) 로 둔다.
  3. « sub » 반환.
TemplateMiddleList : TemplateMiddleList TemplateMiddle Expression
  1. precedingTemplateMiddleList 의 SubstitutionEvaluation 결과 (?) 로 둔다.
  2. nextRefExpression Evaluation 결과 (?) 로 둔다.
  3. next 를 ? GetValue(nextRef) 로 둔다.
  4. preceding 과 « next » 리스트 연결 반환.

13.2.8.6 런타임 의미론: 평가(Evaluation)

TemplateLiteral : NoSubstitutionTemplate
  1. 12.9.6 에 정의된 NoSubstitutionTemplate 의 TV 반환.
SubstitutionTemplate : TemplateHead Expression TemplateSpans
  1. head12.9.6 에 정의된 TemplateHead 의 TV 로 둔다.
  2. subRefExpression Evaluation 결과 (?) 로 둔다.
  3. sub 를 ? GetValue(subRef) 로 둔다.
  4. middle 를 ? ToString(sub) 로 둔다.
  5. tailTemplateSpans Evaluation 결과 (?) 로 둔다.
  6. head, middle, tail 의 문자열 연결 반환.
Note 1

Expression 값에 적용되는 문자열 변환 의미론은 + 연산자보다 String.prototype.concat 과 유사하다.

TemplateSpans : TemplateTail
  1. 12.9.6 에 정의된 TemplateTail 의 TV 반환.
TemplateSpans : TemplateMiddleList TemplateTail
  1. headTemplateMiddleList Evaluation 결과 (?) 로 둔다.
  2. tail12.9.6 에 정의된 TemplateTail 의 TV 로 둔다.
  3. headtail 문자열 연결 반환.
TemplateMiddleList : TemplateMiddle Expression
  1. head12.9.6 에 정의된 TemplateMiddle 의 TV 로 둔다.
  2. subRefExpression Evaluation 결과 (?) 로 둔다.
  3. sub 를 ? GetValue(subRef) 로 둔다.
  4. middle 를 ? ToString(sub) 로 둔다.
  5. headmiddle 문자열 연결 반환.
Note 2

Expression 값의 문자열 변환은 String.prototype.concat 과 유사.

TemplateMiddleList : TemplateMiddleList TemplateMiddle Expression
  1. restTemplateMiddleList Evaluation 결과 (?) 로 둔다.
  2. middle12.9.6 에 정의된 TemplateMiddle 의 TV 로 둔다.
  3. subRefExpression Evaluation 결과 (?) 로 둔다.
  4. sub 를 ? GetValue(subRef) 로 둔다.
  5. last 를 ? ToString(sub) 로 둔다.
  6. rest, middle, last 문자열 연결 반환.
Note 3

Expression 값의 문자열 변환은 String.prototype.concat 과 유사.

13.2.9 그룹 연산자(The Grouping Operator)

13.2.9.1 정적 의미론: 조기 오류(Early Errors)

PrimaryExpression : CoverParenthesizedExpressionAndArrowParameterList

13.2.9.2 런타임 의미론: 평가(Evaluation)

PrimaryExpression : CoverParenthesizedExpressionAndArrowParameterList
  1. exprCoverParenthesizedExpressionAndArrowParameterList 가 커버하는 ParenthesizedExpression 으로 둔다.
  2. expr 의 Evaluation 결과를 ? 로 반환.
ParenthesizedExpression : ( Expression )
  1. Expression 의 Evaluation 결과를 ? 로 반환. 이는 Reference 일 수 있다.
Note

이 알고리즘은 Expression 평가에 GetValue 를 적용하지 않는다. 이는 delete, typeof 같은 연산자가 괄호 친 표현식에 적용될 수 있도록 하는 주된 동기다.

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)

다음 생성물 인스턴스를 처리할 때
CallExpression : CoverCallExpressionAndAsyncArrowHead
CoverCallExpressionAndAsyncArrowHead 의 해석은 아래 문법을 사용해 정밀화된다:

CallMemberExpression[Yield, Await] : MemberExpression[?Yield, ?Await] Arguments[?Yield, ?Await]

13.3.1 정적 의미론(Static Semantics)

13.3.1.1 정적 의미론: 조기 오류(Early Errors)

OptionalChain : ?. TemplateLiteral OptionalChain TemplateLiteral
  • 이 생성물이 어떤 소스 텍스트와 매칭되면 Syntax Error이다.
Note

이 생성물은 아래 코드에 대해 자동 세미콜론 삽입 규칙(12.10)이 적용되어 두 개의 유효한 문장으로 해석되는 것을 방지하기 위해 존재한다:

a?.b
`c`

이는 선택적 체이닝이 없는 유사 코드와의 일관성을 유지하려는 목적이다:

a.b
`c`

위 코드는 유효한 문장이며 자동 세미콜론 삽입이 적용되지 않는다.

ImportMeta : import . meta
  • 구문 목표 심볼이 Module 이 아니면 Syntax Error이다.

13.3.2 프로퍼티 접근자(Property Accessors)

Note

프로퍼티는 이름으로 접근하며, 점 표기법(dot notation)을 사용할 수 있다:

또는 대괄호 표기법(bracket notation)을 사용할 수 있다:

점 표기법은 다음 구문 변환으로 설명된다:

는 동작상 다음과 동일하다:

MemberExpression [ <identifier-name-string> ]

비슷하게

도 동작상 다음과 동일하다:

CallExpression [ <identifier-name-string> ]

여기서 <identifier-name-string> 는 IdentifierName 의 StringValue 이다.

13.3.2.1 런타임 의미론: 평가(Evaluation)

MemberExpression : MemberExpression [ Expression ]
  1. baseReferenceMemberExpression 의 Evaluation 결과 (?) 로 둔다.
  2. baseValue 를 ? GetValue(baseReference) 로 둔다.
  3. strict 를 IsStrict(this MemberExpression) 로 둔다.
  4. EvaluatePropertyAccessWithExpressionKey(baseValue, Expression, strict) 를 반환한다.
MemberExpression : MemberExpression . IdentifierName
  1. baseReferenceMemberExpression 의 Evaluation 결과 (?) 로 둔다.
  2. baseValue 를 ? GetValue(baseReference) 로 둔다.
  3. strict 를 IsStrict(this MemberExpression) 로 둔다.
  4. EvaluatePropertyAccessWithIdentifierKey(baseValue, IdentifierName, strict) 를 반환한다.
MemberExpression : MemberExpression . PrivateIdentifier
  1. baseReferenceMemberExpression 의 Evaluation 결과 (?) 로 둔다.
  2. baseValue 를 ? GetValue(baseReference) 로 둔다.
  3. fieldNameStringPrivateIdentifier 의 StringValue 로 둔다.
  4. MakePrivateReference(baseValue, fieldNameString) 를 반환한다.
CallExpression : CallExpression [ Expression ]
  1. baseReferenceCallExpression 의 Evaluation 결과 (?) 로 둔다.
  2. baseValue 를 ? GetValue(baseReference) 로 둔다.
  3. strict 를 IsStrict(this CallExpression) 로 둔다.
  4. EvaluatePropertyAccessWithExpressionKey(baseValue, Expression, strict) 를 반환한다.
CallExpression : CallExpression . IdentifierName
  1. baseReferenceCallExpression 의 Evaluation 결과 (?) 로 둔다.
  2. baseValue 를 ? GetValue(baseReference) 로 둔다.
  3. strict 를 IsStrict(this CallExpression) 로 둔다.
  4. EvaluatePropertyAccessWithIdentifierKey(baseValue, IdentifierName, strict) 를 반환한다.
CallExpression : CallExpression . PrivateIdentifier
  1. baseReferenceCallExpression 의 Evaluation 결과 (?) 로 둔다.
  2. baseValue 를 ? GetValue(baseReference) 로 둔다.
  3. fieldNameStringPrivateIdentifier 의 StringValue 로 둔다.
  4. MakePrivateReference(baseValue, fieldNameString) 를 반환한다.

13.3.3 EvaluatePropertyAccessWithExpressionKey ( baseValue, expression, strict )

The abstract operation EvaluatePropertyAccessWithExpressionKey takes arguments baseValue (an ECMAScript language value), expression (an Expression Parse Node), and strict (a Boolean) and returns 정상 완료 시 Reference Record 또는 abrupt completion. It performs the following steps when called:

  1. propertyNameReferenceexpression 의 Evaluation 결과 (?) 로 둔다.
  2. propertyNameValue 를 ? GetValue(propertyNameReference) 로 둔다.
  3. NOTE: 대부분 경우 이 단계 직후 propertyNameValue 에 대해 ToPropertyKey 가 수행된다. 그러나 a[b] = c 의 경우 c 평가 이후에 수행된다.
  4. Reference Record { [[Base]]: baseValue, [[ReferencedName]]: propertyNameValue, [[Strict]]: strict, [[ThisValue]]: empty } 를 반환한다.

13.3.4 EvaluatePropertyAccessWithIdentifierKey ( baseValue, identifierName, strict )

The abstract operation EvaluatePropertyAccessWithIdentifierKey takes arguments baseValue (an ECMAScript language value), identifierName (an IdentifierName Parse Node), and strict (a Boolean) and returns Reference Record. It performs the following steps when called:

  1. propertyNameStringidentifierName 의 StringValue 로 둔다.
  2. Reference Record { [[Base]]: baseValue, [[ReferencedName]]: propertyNameString, [[Strict]]: strict, [[ThisValue]]: empty } 를 반환한다.

13.3.5 new 연산자(The new Operator)

13.3.5.1 런타임 의미론: 평가(Evaluation)

NewExpression : new NewExpression
  1. EvaluateNew(NewExpression, empty) 를 반환한다.
MemberExpression : new MemberExpression Arguments
  1. EvaluateNew(MemberExpression, Arguments) 를 반환한다.

13.3.5.1.1 EvaluateNew ( constructExpr, arguments )

The abstract operation EvaluateNew takes arguments constructExpr (a NewExpression Parse Node or a MemberExpression Parse Node) and arguments (empty or an Arguments Parse Node) and returns 정상 완료 시 ECMAScript 언어 값 또는 abrupt completion. It performs the following steps when called:

  1. refconstructExpr 의 Evaluation 결과 (?) 로 둔다.
  2. constructor 를 ? GetValue(ref) 로 둔다.
  3. argumentsempty 이면
    1. argList 를 새 빈 List 로 둔다.
  4. Else,
    1. argList 를 ? ArgumentListEvaluation(arguments) 로 둔다.
  5. IsConstructor(constructor) 가 false 이면 TypeError 예외를 throw.
  6. Construct(constructor, argList) 를 반환한다.

13.3.6 함수 호출(Function Calls)

13.3.6.1 런타임 의미론: 평가(Evaluation)

CallExpression : CoverCallExpressionAndAsyncArrowHead
  1. exprCoverCallExpressionAndAsyncArrowHead 가 커버하는 CallMemberExpression 으로 둔다.
  2. memberExprexprMemberExpression 으로 둔다.
  3. argumentsexprArguments 로 둔다.
  4. ref 를 ? Evaluation(memberExpr) 로 둔다.
  5. func 을 ? GetValue(ref) 로 둔다.
  6. refReference Record 이고 IsPropertyReference(ref) 가 false 이며 ref.[[ReferencedName]]"eval" 이면
    1. SameValue(func, %eval%) 이 true 이면
      1. argList 를 ? ArgumentListEvaluation(arguments) 로 둔다.
      2. argList 에 요소가 없으면 undefined 반환.
      3. evalArgargList 의 첫 요소로 둔다.
      4. IsStrict(this CallExpression) 이 true 이면 strictCaller = true, 아니면 false.
      5. PerformEval(evalArg, strictCaller, true) 를 반환한다.
  7. thisCall 을 this CallExpression 으로 둔다.
  8. tailCall 을 IsInTailPosition(thisCall) 로 둔다.
  9. EvaluateCall(func, ref, arguments, tailCall) 를 반환한다.

단계 6.a.v 를 수행한 CallExpression 평가는 직접 eval(direct eval) 이다.

CallExpression : CallExpression Arguments
  1. ref 를 ? Evaluation(CallExpression) 로 둔다.
  2. func 를 ? GetValue(ref) 로 둔다.
  3. thisCall 을 this CallExpression 으로 둔다.
  4. tailCall 을 IsInTailPosition(thisCall) 로 둔다.
  5. EvaluateCall(func, ref, Arguments, tailCall) 를 반환한다.

13.3.6.2 EvaluateCall ( func, ref, arguments, tailPosition )

The abstract operation EvaluateCall takes arguments func (an ECMAScript language value), ref (an ECMAScript language value or a Reference Record), arguments (a Parse Node), and tailPosition (a Boolean) and returns 정상 완료 시 ECMAScript 언어 값 또는 abrupt completion. It performs the following steps when called:

  1. refReference Record 이면
    1. IsPropertyReference(ref) 가 true 이면
      1. thisValueGetThisValue(ref) 로 둔다.
    2. Else,
      1. refEnvref.[[Base]] 로 둔다.
      2. 단언: refEnvEnvironment Record.
      3. thisValuerefEnv.WithBaseObject() 로 둔다.
  2. Else,
    1. thisValueundefined 로 둔다.
  3. argList 를 ? ArgumentListEvaluation(arguments) 로 둔다.
  4. func 가 Object 가 아니면 TypeError 예외 throw.
  5. IsCallable(func) 이 false 이면 TypeError 예외 throw.
  6. tailPositiontrue 이면 PrepareForTailCall() 수행.
  7. Call(func, thisValue, argList) 를 반환한다.

13.3.7 super 키워드(The super Keyword)

13.3.7.1 런타임 의미론: 평가(Evaluation)

SuperProperty : super [ Expression ]
  1. envGetThisEnvironment() 로 둔다.
  2. actualThis 를 ? env.GetThisBinding() 로 둔다.
  3. propertyNameReference 를 ? Evaluation(Expression) 로 둔다.
  4. propertyNameValue 를 ? GetValue(propertyNameReference) 로 둔다.
  5. strict 를 IsStrict(this SuperProperty) 로 둔다.
  6. NOTE: 대부분 경우 이 단계 직후 propertyNameValue 에 대해 ToPropertyKey 가 수행된다. 하지만 super[b] = c 의 경우 c 평가 이후 수행된다.
  7. MakeSuperPropertyReference(actualThis, propertyNameValue, strict) 를 반환한다.
SuperProperty : super . IdentifierName
  1. envGetThisEnvironment() 로 둔다.
  2. actualThis 를 ? env.GetThisBinding() 로 둔다.
  3. propertyKeyIdentifierName 의 StringValue 로 둔다.
  4. strict 를 IsStrict(this SuperProperty) 로 둔다.
  5. MakeSuperPropertyReference(actualThis, propertyKey, strict) 를 반환한다.
SuperCall : super Arguments
  1. newTargetGetNewTarget() 로 둔다.
  2. 단언: newTarget 은 constructor.
  3. funcGetSuperConstructor() 로 둔다.
  4. argList 를 ? ArgumentListEvaluation(Arguments) 로 둔다.
  5. IsConstructor(func) 이 false 이면 TypeError 예외 throw.
  6. result 를 ? Construct(func, argList, newTarget) 로 둔다.
  7. thisERGetThisEnvironment() 로 둔다.
  8. 단언: thisERFunction Environment Record.
  9. BindThisValue(thisER, result) 수행.
  10. FthisER.[[FunctionObject]] 로 둔다.
  11. 단언: F 는 ECMAScript 함수 객체.
  12. InitializeInstanceElements(result, F) 수행.
  13. result 반환.

13.3.7.2 GetSuperConstructor ( )

The abstract operation GetSuperConstructor takes no arguments and returns ECMAScript 언어 값. It performs the following steps when called:

  1. envRecGetThisEnvironment() 로 둔다.
  2. 단언: envRecFunction Environment Record.
  3. activeFunctionenvRec.[[FunctionObject]] 로 둔다.
  4. 단언: activeFunction 은 ECMAScript 함수 객체.
  5. superConstructor 를 ! activeFunction.[[GetPrototypeOf]]() 로 둔다.
  6. superConstructor 반환.

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 Super Reference Record. It performs the following steps when called:

  1. envGetThisEnvironment() 로 둔다.
  2. 단언: env.HasSuperBinding() 은 true.
  3. 단언: envFunction Environment Record.
  4. baseValueGetSuperBase(env) 로 둔다.
  5. Reference Record { [[Base]]: baseValue, [[ReferencedName]]: propertyKey, [[Strict]]: strict, [[ThisValue]]: actualThis } 반환.

13.3.8 인자 목록(Argument Lists)

Note

인자 목록의 평가 결과는 값들의 List 를 생성한다.

13.3.8.1 런타임 의미론: ArgumentListEvaluation : 정상 완료 시 ECMAScript 언어 값들의 List 또는 abrupt completion

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. It is defined piecewise over the following productions:

Arguments : ( )
  1. 새 빈 List 반환.
ArgumentList : AssignmentExpression
  1. refAssignmentExpression Evaluation 결과 (?) 로 둔다.
  2. arg 를 ? GetValue(ref) 로 둔다.
  3. « arg » 반환.
ArgumentList : ... AssignmentExpression
  1. list 를 새 빈 List 로 둔다.
  2. spreadRefAssignmentExpression Evaluation 결과 (?) 로 둔다.
  3. spreadObj 를 ? GetValue(spreadRef) 로 둔다.
  4. iteratorRecord 를 ? GetIterator(spreadObj, sync) 로 둔다.
  5. 반복,
    1. next 를 ? IteratorStepValue(iteratorRecord) 로 둔다.
    2. nextdone 이면 list 반환.
    3. listnext 추가.
ArgumentList : ArgumentList , AssignmentExpression
  1. precedingArgs 를 ? ArgumentListEvaluation(ArgumentList) 로 둔다.
  2. refAssignmentExpression Evaluation 결과 (?) 로 둔다.
  3. arg 를 ? GetValue(ref) 로 둔다.
  4. precedingArgs 와 « arg » 의 리스트 연결 반환.
ArgumentList : ArgumentList , ... AssignmentExpression
  1. precedingArgs 를 ? ArgumentListEvaluation(ArgumentList) 로 둔다.
  2. spreadRefAssignmentExpression Evaluation 결과 (?) 로 둔다.
  3. iteratorRecord 를 ? GetIterator(? GetValue(spreadRef), sync) 로 둔다.
  4. 반복,
    1. next 를 ? IteratorStepValue(iteratorRecord) 로 둔다.
    2. nextdone 이면 precedingArgs 반환.
    3. precedingArgsnext 추가.
TemplateLiteral : NoSubstitutionTemplate
  1. templateLiteral 을 this TemplateLiteral 로 둔다.
  2. siteObjGetTemplateObject(templateLiteral) 로 둔다.
  3. « siteObj » 반환.
TemplateLiteral : SubstitutionTemplate
  1. templateLiteral 을 this TemplateLiteral 로 둔다.
  2. siteObjGetTemplateObject(templateLiteral) 로 둔다.
  3. remaining 을 ? ArgumentListEvaluation(SubstitutionTemplate) 로 둔다.
  4. « siteObj » 와 remaining 의 리스트 연결 반환.
SubstitutionTemplate : TemplateHead Expression TemplateSpans
  1. firstSubRef 를 ? Evaluation(Expression) 로 둔다.
  2. firstSub 를 ? GetValue(firstSubRef) 로 둔다.
  3. restSub 를 ? SubstitutionEvaluation(TemplateSpans) 로 둔다.
  4. 단언: restSub 는 (비어있을 수도 있는) List.
  5. « firstSub » 와 restSub 의 리스트 연결 반환.

13.3.9 옵셔널 체인(Optional Chains)

Note
옵셔널 체인은 하나 이상의 프로퍼티 접근과 함수 호출이 연속된 것으로, 첫 부분이 ?. 토큰으로 시작한다.

13.3.9.1 런타임 의미론: 평가(Evaluation)

OptionalExpression : MemberExpression OptionalChain
  1. baseReference 를 ? Evaluation(MemberExpression) 로 둔다.
  2. baseValue 를 ? GetValue(baseReference) 로 둔다.
  3. baseValueundefined 또는 null 이면
    1. undefined 반환.
  4. ? ChainEvaluation(OptionalChain, 인수 baseValue, baseReference) 를 반환.
OptionalExpression : CallExpression OptionalChain
  1. baseReference 를 ? Evaluation(CallExpression) 로 둔다.
  2. baseValue 를 ? GetValue(baseReference) 로 둔다.
  3. baseValueundefined 또는 null 이면
    1. undefined 반환.
  4. ? ChainEvaluation(OptionalChain, 인수 baseValue, baseReference) 반환.
OptionalExpression : OptionalExpression OptionalChain
  1. baseReference 를 ? Evaluation(OptionalExpression) 로 둔다.
  2. baseValue 를 ? GetValue(baseReference) 로 둔다.
  3. baseValueundefined 또는 null 이면
    1. undefined 반환.
  4. ? ChainEvaluation(OptionalChain, 인수 baseValue, baseReference) 반환.

13.3.9.2 런타임 의미론: ChainEvaluation : 정상 완료 시 ECMAScript 언어 값 또는 Reference Record, 또는 abrupt completion

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. It is defined piecewise over the following productions:

OptionalChain : ?. Arguments
  1. thisChain 을 this OptionalChain 으로 둔다.
  2. tailCall 을 IsInTailPosition(thisChain) 로 둔다.
  3. EvaluateCall(baseValue, baseReference, Arguments, tailCall) 반환.
OptionalChain : ?. [ Expression ]
  1. strict 를 IsStrict(this OptionalChain) 로 둔다.
  2. EvaluatePropertyAccessWithExpressionKey(baseValue, Expression, strict) 반환.
OptionalChain : ?. IdentifierName
  1. strict 를 IsStrict(this OptionalChain) 로 둔다.
  2. EvaluatePropertyAccessWithIdentifierKey(baseValue, IdentifierName, strict) 반환.
OptionalChain : ?. PrivateIdentifier
  1. fieldNameStringPrivateIdentifier 의 StringValue 로 둔다.
  2. MakePrivateReference(baseValue, fieldNameString) 반환.
OptionalChain : OptionalChain Arguments
  1. optionalChainOptionalChain 으로 둔다.
  2. newReference 를 ? ChainEvaluation(optionalChain, 인수 baseValue, baseReference) 로 둔다.
  3. newValue 를 ? GetValue(newReference) 로 둔다.
  4. thisChain 을 this OptionalChain 으로 둔다.
  5. tailCall 을 IsInTailPosition(thisChain) 로 둔다.
  6. EvaluateCall(newValue, newReference, Arguments, tailCall) 반환.
OptionalChain : OptionalChain [ Expression ]
  1. optionalChainOptionalChain 으로 둔다.
  2. newReference 를 ? ChainEvaluation(optionalChain, 인수 baseValue, baseReference) 로 둔다.
  3. newValue 를 ? GetValue(newReference) 로 둔다.
  4. strict 를 IsStrict(this OptionalChain) 로 둔다.
  5. EvaluatePropertyAccessWithExpressionKey(newValue, Expression, strict) 반환.
OptionalChain : OptionalChain . IdentifierName
  1. optionalChainOptionalChain 으로 둔다.
  2. newReference 를 ? ChainEvaluation(optionalChain, 인수 baseValue, baseReference) 로 둔다.
  3. newValue 를 ? GetValue(newReference) 로 둔다.
  4. strict 를 IsStrict(this OptionalChain) 로 둔다.
  5. EvaluatePropertyAccessWithIdentifierKey(newValue, IdentifierName, strict) 반환.
OptionalChain : OptionalChain . PrivateIdentifier
  1. optionalChainOptionalChain 으로 둔다.
  2. newReference 를 ? ChainEvaluation(optionalChain, 인수 baseValue, baseReference) 로 둔다.
  3. newValue 를 ? GetValue(newReference) 로 둔다.
  4. fieldNameStringPrivateIdentifier 의 StringValue 로 둔다.
  5. MakePrivateReference(newValue, fieldNameString) 반환.

13.3.10 import 호출(Import Calls)

13.3.10.1 런타임 의미론: 평가(Evaluation)

ImportCall : import ( AssignmentExpression ,opt )
  1. EvaluateImportCall(AssignmentExpression) 반환.
ImportCall : import ( AssignmentExpression , AssignmentExpression ,opt )
  1. EvaluateImportCall(첫 번째 AssignmentExpression, 두 번째 AssignmentExpression) 반환.

13.3.10.2 EvaluateImportCall ( specifierExpression [ , optionsExpression ] )

The abstract operation EvaluateImportCall takes argument specifierExpression (a Parse Node) and optional argument optionsExpression (a Parse Node) and returns 정상 완료 시 Promise 또는 abrupt completion. It performs the following steps when called:

  1. referrerGetActiveScriptOrModule() 로 둔다.
  2. referrernull 이면 현재 Realm Record 로 설정.
  3. specifierRef 를 ? Evaluation(specifierExpression) 로 둔다.
  4. specifier 를 ? GetValue(specifierRef) 로 둔다.
  5. optionsExpression 이 존재하면
    1. optionsRef 를 ? Evaluation(optionsExpression) 로 둔다.
    2. options 를 ? GetValue(optionsRef) 로 둔다.
  6. Else,
    1. options = undefined.
  7. promiseCapability 를 ! NewPromiseCapability(%Promise%) 로 둔다.
  8. specifierStringCompletion(ToString(specifier)) 로 둔다.
  9. IfAbruptRejectPromise(specifierString, promiseCapability).
  10. attributes 를 새 빈 List 로 둔다.
  11. optionsundefined 가 아니면
    1. options 가 Object 가 아니면
      1. Call(promiseCapability.[[Reject]], undefined, « 새로 생성된 TypeError 객체 ») 수행.
      2. promiseCapability.[[Promise]] 반환.
    2. attributesObjCompletion(Get(options, "with")).
    3. IfAbruptRejectPromise(attributesObj, promiseCapability).
    4. attributesObjundefined 가 아니면
      1. attributesObj 가 Object 가 아니면
        1. Call(promiseCapability.[[Reject]], undefined, « 새로 생성된 TypeError 객체 ») 수행.
        2. promiseCapability.[[Promise]] 반환.
      2. entriesCompletion(EnumerableOwnProperties(attributesObj, key+value)).
      3. IfAbruptRejectPromise(entries, promiseCapability).
      4. entries 의 각 entry 에 대해
        1. key = ! Get(entry, "0").
        2. value = ! Get(entry, "1").
        3. key 가 String 이면
          1. value 가 String 이 아니면
            1. Call(promiseCapability.[[Reject]], undefined, « 새로 생성된 TypeError 객체 ») 수행.
            2. promiseCapability.[[Promise]] 반환.
          2. ImportAttribute Record { [[Key]]: key, [[Value]]: value } 를 attributes 에 추가.
    5. AllImportAttributesSupported(attributes) 가 false 이면
      1. Call(promiseCapability.[[Reject]], undefined, « 새로 생성된 TypeError 객체 ») 수행.
      2. promiseCapability.[[Promise]] 반환.
    6. attributes 를 각 [[Key]] 필드의 UTF-16 코드 유닛 시퀀스 사전식 순서로 정렬. (NOTE: 정렬은 호스트가 열거 순서를 기반으로 동작을 바꾸는 것을 금지하는 방식으로만 관찰 가능)
  12. moduleRequest 를 새 ModuleRequest Record { [[Specifier]]: specifierString, [[Attributes]]: attributes } 로 둔다.
  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 (Module Record 를 담는 정상 completion 또는 throw completion) and returns unused. import() 호출로 시작된 동적 import 과정을 마무리하여, 해당 호출이 반환한 promise 를 적절히 이행(resolve) 또는 거부(reject)한다. It performs the following steps when called:

  1. moduleCompletionabrupt completion 이면
    1. Call(promiseCapability.[[Reject]], undefined, « moduleCompletion.[[Value]] ») 수행.
    2. unused 반환.
  2. modulemoduleCompletion.[[Value]] 로 둔다.
    1. loadPromisemodule.LoadRequestedModules() 로 둔다.
  3. rejectedClosure 를 (reason) 매개변수를 가지며 promiseCapability 를 캡처하고 호출 시:
    1. Call(promiseCapability.[[Reject]], undefined, « reason ») 수행.
    2. NormalCompletion(undefined) 반환.
  4. onRejectedCreateBuiltinFunction(rejectedClosure, 1, "", « ») 로 둔다.
  5. linkAndEvaluateClosure 를 매개변수 없고 module, promiseCapability, onRejected 를 캡처하며 호출 시:
    1. link = Completion(module.Link()).
    2. linkabrupt completion 이면
      1. Call(promiseCapability.[[Reject]], undefined, « link.[[Value]] ») 수행.
      2. NormalCompletion(undefined) 반환.
    3. evaluatePromisemodule.Evaluate() 로 둔다.
    4. fulfilledClosure 를 매개변수 없고 module, promiseCapability 캡처하며 호출 시:
      1. namespace = GetModuleNamespace(module).
      2. Call(promiseCapability.[[Resolve]], undefined, « namespace ») 수행.
      3. NormalCompletion(undefined) 반환.
    5. onFulfilled = CreateBuiltinFunction(fulfilledClosure, 0, "", « »).
    6. PerformPromiseThen(evaluatePromise, onFulfilled, onRejected) 수행.
    7. unused 반환.
  6. linkAndEvaluate = CreateBuiltinFunction(linkAndEvaluateClosure, 0, "", « »).
  7. PerformPromiseThen(loadPromise, linkAndEvaluate, onRejected) 수행.
  8. unused 반환.

13.3.11 태그드 템플릿(Tagged Templates)

Note

태그드 템플릿은 호출 인자가 TemplateLiteral (13.2.8) 로부터 파생되는 함수 호출이다. 실제 인자에는 템플릿 객체(13.2.8.4)와 TemplateLiteral 안에 포함된 표현식들을 평가하여 얻은 값들이 포함된다.

13.3.11.1 런타임 의미론: 평가(Evaluation)

MemberExpression : MemberExpression TemplateLiteral
  1. tagRef 를 ? Evaluation(MemberExpression) 로 둔다.
  2. tagFunc 를 ? GetValue(tagRef) 로 둔다.
  3. thisCall 을 this MemberExpression 으로 둔다.
  4. tailCall 을 IsInTailPosition(thisCall) 로 둔다.
  5. EvaluateCall(tagFunc, tagRef, TemplateLiteral, tailCall) 반환.
CallExpression : CallExpression TemplateLiteral
  1. tagRef 를 ? Evaluation(CallExpression) 로 둔다.
  2. tagFunc 를 ? GetValue(tagRef) 로 둔다.
  3. thisCall 을 this CallExpression 으로 둔다.
  4. tailCall 을 IsInTailPosition(thisCall) 로 둔다.
  5. EvaluateCall(tagFunc, tagRef, TemplateLiteral, tailCall) 반환.

13.3.12 메타 프로퍼티(Meta Properties)

13.3.12.1 런타임 의미론: 평가(Evaluation)

NewTarget : new . target
  1. GetNewTarget() 반환.
ImportMeta : import . meta
  1. moduleGetActiveScriptOrModule() 로 둔다.
  2. 단언: moduleSource Text Module Record.
  3. importMetamodule.[[ImportMeta]] 로 둔다.
  4. importMetaempty 이면
    1. importMetaOrdinaryObjectCreate(null) 로 설정.
    2. importMetaValuesHostGetImportMetaProperties(module) 로 둔다.
    3. Record { [[Key]], [[Value]] } p 에 대해
      1. CreateDataPropertyOrThrow(importMeta, p.[[Key]], p.[[Value]]) 수행.
    4. HostFinalizeImportMeta(importMeta, module) 수행.
    5. module.[[ImportMeta]]importMeta 설정.
    6. importMeta 반환.
  5. Else,
    1. 단언: importMeta 는 Object.
    2. importMeta 반환.

13.3.12.1.1 HostGetImportMetaProperties ( moduleRecord )

The host-defined abstract operation HostGetImportMetaProperties takes argument moduleRecord (a Module Record) and returns [[Key]] (property key), [[Value]] (ECMAScript 언어 값) 필드를 가진 Record 들의 List. 호스트import.meta 로부터 반환되는 객체에 대한 프로퍼티 키와 값을 제공할 수 있게 한다.

HostGetImportMetaProperties 의 기본 구현은 새 빈 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. 호스트import.meta 로부터 반환되는 객체를 ECMAScript 코드에 노출하기 전에 추가 작업을 수행할 수 있게 한다.

대부분 호스트HostGetImportMetaProperties 를 정의하고 HostFinalizeImportMeta 는 기본 동작을 그대로 둘 수 있다. 그러나 HostFinalizeImportMeta 는 노출 전에 객체를 직접 조작해야 하는 호스트를 위한 “escape hatch” 를 제공한다.

HostFinalizeImportMeta 의 기본 구현은 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
  • UnaryExpression 의 AssignmentTargetType 이 invalid 이면 초기(early) Syntax Error 이다.

13.4.2 후위 증가 연산자(Postfix Increment Operator)

13.4.2.1 런타임 의미론: 평가(Runtime Semantics: Evaluation)

UpdateExpression : LeftHandSideExpression ++
  1. lhsLeftHandSideExpression 의 Evaluation 결과 (?) 로 둔다.
  2. LeftHandSideExpression 의 AssignmentTargetType 이 web-compat 이면 ReferenceError 예외를 throw 한다.
  3. oldValue 를 ? ToNumeric(? GetValue(lhs)) 로 둔다.
  4. oldValue 가 Number 이면
    1. newValueNumber::add(oldValue, 1𝔽) 로 둔다.
  5. 그렇지 않으면
    1. 단언: oldValue 는 BigInt.
    2. newValueBigInt::add(oldValue, 1) 로 둔다.
  6. PutValue(lhs, newValue) 수행.
  7. oldValue 반환.

13.4.3 후위 감소 연산자(Postfix Decrement Operator)

13.4.3.1 런타임 의미론: 평가(Runtime Semantics: Evaluation)

UpdateExpression : LeftHandSideExpression --
  1. lhsLeftHandSideExpression 의 Evaluation 결과 (?) 로 둔다.
  2. LeftHandSideExpression 의 AssignmentTargetType 이 web-compat 이면 ReferenceError 예외를 throw 한다.
  3. oldValue 를 ? ToNumeric(? GetValue(lhs)) 로 둔다.
  4. oldValue 가 Number 이면
    1. newValueNumber::subtract(oldValue, 1𝔽) 로 둔다.
  5. 그렇지 않으면
    1. 단언: oldValue 는 BigInt.
    2. newValueBigInt::subtract(oldValue, 1) 로 둔다.
  6. PutValue(lhs, newValue) 수행.
  7. oldValue 반환.

13.4.4 전위 증가 연산자(Prefix Increment Operator)

13.4.4.1 런타임 의미론: 평가(Runtime Semantics: Evaluation)

UpdateExpression : ++ UnaryExpression
  1. exprUnaryExpression 의 Evaluation 결과 (?) 로 둔다.
  2. UnaryExpression 의 AssignmentTargetType 이 web-compat 이면 ReferenceError 예외를 throw 한다.
  3. oldValue 를 ? ToNumeric(? GetValue(expr)) 로 둔다.
  4. oldValue 가 Number 이면
    1. newValueNumber::add(oldValue, 1𝔽) 로 둔다.
  5. 그렇지 않으면
    1. 단언: oldValue 는 BigInt.
    2. newValueBigInt::add(oldValue, 1) 로 둔다.
  6. PutValue(expr, newValue) 수행.
  7. newValue 반환.

13.4.5 전위 감소 연산자(Prefix Decrement Operator)

13.4.5.1 런타임 의미론: 평가(Runtime Semantics: Evaluation)

UpdateExpression : -- UnaryExpression
  1. exprUnaryExpression 의 Evaluation 결과 (?) 로 둔다.
  2. UnaryExpression 의 AssignmentTargetType 이 web-compat 이면 ReferenceError 예외를 throw 한다.
  3. oldValue 를 ? ToNumeric(? GetValue(expr)) 로 둔다.
  4. oldValue 가 Number 이면
    1. newValueNumber::subtract(oldValue, 1𝔽) 로 둔다.
  5. 그렇지 않으면
    1. 단언: 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] AwaitExpression[?Yield]

13.5.1 delete 연산자(The delete Operator)

13.5.1.1 정적 의미론: 조기 오류(Static Semantics: Early Errors)

UnaryExpression : delete UnaryExpression Note

마지막 규칙은 delete (((foo))) 같은 표현식이 첫 번째 규칙의 재귀 적용으로 인해 조기 오류를 발생함을 의미한다.

13.5.1.2 런타임 의미론: 평가(Runtime Semantics: Evaluation)

UnaryExpression : delete UnaryExpression
  1. refUnaryExpression 의 Evaluation 결과 (?) 로 둔다.
  2. refReference Record 가 아니면 true 반환.
  3. IsUnresolvableReference(ref) 가 true 이면
    1. 단언: ref.[[Strict]]false.
    2. true 반환.
  4. IsPropertyReference(ref) 가 true 이면
    1. 단언: IsPrivateReference(ref) 는 false.
    2. IsSuperReference(ref) 가 true 이면 ReferenceError 예외 throw.
    3. baseObj 를 ? ToObject(ref.[[Base]]) 로 둔다.
    4. ref.[[ReferencedName]] 가 property key 가 아니면
      1. ref.[[ReferencedName]] 를 ? ToPropertyKey(ref.[[ReferencedName]]) 로 설정.
    5. deleteStatus 를 ? baseObj.[[Delete]](ref.[[ReferencedName]]) 로 둔다.
    6. deleteStatusfalse 이고 ref.[[Strict]]true 이면 TypeError 예외 throw.
    7. deleteStatus 반환.
  5. 그렇지 않으면
    1. baseref.[[Base]] 로 둔다.
    2. 단언: baseEnvironment Record.
    3. base.DeleteBinding(ref.[[ReferencedName]]) 반환.
Note 1

delete 연산자가 strict 모드 코드 안에 나타나고 그 UnaryExpression 이 변수, 함수 인자, 함수 이름에 대한 직접 참조이면 SyntaxError 예외가 발생한다. 또한 strict 모드 코드에서 delete 가 발생하고 삭제하려는 프로퍼티가 { [[Configurable]]: false } 속성을 가지거나(또는 삭제 불가) 하면 TypeError 예외가 발생한다.

Note 2

4.c 단계에서 생성될 수 있는 객체는 위 추상 연산 및 보통 객체 [[Delete]] 내부 메서드 외부에서는 접근할 수 없다. 구현은 실제 객체 생성을 회피할 수도 있다.

13.5.2 void 연산자(The void Operator)

13.5.2.1 런타임 의미론: 평가(Runtime Semantics: Evaluation)

UnaryExpression : void UnaryExpression
  1. exprUnaryExpression 의 Evaluation 결과 (?) 로 둔다.
  2. GetValue(expr) 수행.
  3. undefined 반환.
Note

값을 사용하지 않더라도 관찰 가능한 부수효과가 있을 수 있으므로 GetValue 는 호출되어야 한다.

13.5.3 typeof 연산자(The typeof Operator)

13.5.3.1 런타임 의미론: 평가(Runtime Semantics: Evaluation)

UnaryExpression : typeof UnaryExpression
  1. valUnaryExpression 의 Evaluation 결과 (?) 로 둔다.
  2. valReference Record 이면
    1. IsUnresolvableReference(val) 가 true 이면 "undefined" 반환.
  3. val 을 ? GetValue(val) 로 설정.
  4. valundefined 이면 "undefined" 반환.
  5. valnull 이면 "object" 반환.
  6. val 이 String 이면 "string" 반환.
  7. val 이 Symbol 이면 "symbol" 반환.
  8. val 이 Boolean 이면 "boolean" 반환.
  9. val 이 Number 이면 "number" 반환.
  10. val 이 BigInt 이면 "bigint" 반환.
  11. 단언: val 은 Object.
  12. Normative Optional
    호스트가 웹 브라우저이거나 [[IsHTMLDDA]] 내부 슬롯 를 지원한다면
    1. val[[IsHTMLDDA]] 내부 슬롯을 가지면 "undefined" 반환.
  13. val[[Call]] 내부 메서드를 가지면 "function" 반환.
  14. "object" 반환.

13.5.4 단항 + 연산자(Unary + Operator)

Note

단항 + 연산자는 피연산자를 Number 타입으로 변환한다.

13.5.4.1 런타임 의미론: 평가(Runtime Semantics: Evaluation)

UnaryExpression : + UnaryExpression
  1. exprUnaryExpression 의 Evaluation 결과 (?) 로 둔다.
  2. ToNumber(? GetValue(expr)) 반환.

13.5.5 단항 - 연산자(Unary - Operator)

Note

단항 - 연산자는 피연산자를 수치 값으로 변환한 뒤 부호를 반전한다. +0𝔽 을 부정하면 -0𝔽, -0𝔽 을 부정하면 +0𝔽 이 된다.

13.5.5.1 런타임 의미론: 평가(Runtime Semantics: Evaluation)

UnaryExpression : - UnaryExpression
  1. exprUnaryExpression 의 Evaluation 결과 (?) 로 둔다.
  2. oldValue 를 ? ToNumeric(? GetValue(expr)) 로 둔다.
  3. oldValue 가 Number 이면
    1. Number::unaryMinus(oldValue) 반환.
  4. 그렇지 않으면
    1. 단언: oldValue 는 BigInt.
    2. BigInt::unaryMinus(oldValue) 반환.

13.5.6 비트 NOT 연산자(Bitwise NOT Operator) ( ~ )

13.5.6.1 런타임 의미론: 평가(Runtime Semantics: Evaluation)

UnaryExpression : ~ UnaryExpression
  1. exprUnaryExpression 의 Evaluation 결과 (?) 로 둔다.
  2. oldValue 를 ? ToNumeric(? GetValue(expr)) 로 둔다.
  3. oldValue 가 Number 이면
    1. Number::bitwiseNOT(oldValue) 반환.
  4. 그렇지 않으면
    1. 단언: oldValue 는 BigInt.
    2. BigInt::bitwiseNOT(oldValue) 반환.

13.5.7 논리 NOT 연산자(Logical NOT Operator) ( ! )

13.5.7.1 런타임 의미론: 평가(Runtime Semantics: Evaluation)

UnaryExpression : ! UnaryExpression
  1. exprUnaryExpression 의 Evaluation 결과 (?) 로 둔다.
  2. oldValueToBoolean(? GetValue(expr)) 로 둔다.
  3. oldValuetrue 이면 false 반환.
  4. true 반환.

13.6 거듭제곱 연산자(Exponentiation Operator)

Syntax

ExponentiationExpression[Yield, Await] : UnaryExpression[?Yield, ?Await] UpdateExpression[?Yield, ?Await] ** ExponentiationExpression[?Yield, ?Await]

13.6.1 런타임 의미론: 평가(Runtime Semantics: Evaluation)

ExponentiationExpression : UpdateExpression ** ExponentiationExpression
  1. EvaluateStringOrNumericBinaryExpression(UpdateExpression, **, ExponentiationExpression) 반환.

13.7 곱셈 연산자(Multiplicative Operators)

Syntax

MultiplicativeExpression[Yield, Await] : ExponentiationExpression[?Yield, ?Await] MultiplicativeExpression[?Yield, ?Await] MultiplicativeOperator ExponentiationExpression[?Yield, ?Await] MultiplicativeOperator : one of * / % Note
  • * 연산자는 피연산자의 곱(product)을 생성하는 곱셈을 수행한다.
  • / 연산자는 피연산자의 몫(quotient)을 생성하는 나눗셈을 수행한다.
  • % 연산자는 암묵적 나눗셈에서 피연산자의 나머지(remainder)를 구한다.

13.7.1 런타임 의미론: 평가(Runtime Semantics: Evaluation)

MultiplicativeExpression : MultiplicativeExpression MultiplicativeOperator ExponentiationExpression
  1. opTextMultiplicativeOperator 가 매칭한 source text 로 둔다.
  2. EvaluateStringOrNumericBinaryExpression(MultiplicativeExpression, opText, ExponentiationExpression) 반환.

13.8 덧셈/뺄셈 연산자(Additive Operators)

Syntax

AdditiveExpression[Yield, Await] : MultiplicativeExpression[?Yield, ?Await] AdditiveExpression[?Yield, ?Await] + MultiplicativeExpression[?Yield, ?Await] AdditiveExpression[?Yield, ?Await] - MultiplicativeExpression[?Yield, ?Await]

13.8.1 덧셈 연산자 ( + ) (The Addition Operator)

Note

덧셈 연산자는 문자열 결합 또는 수치 덧셈을 수행한다.

13.8.1.1 런타임 의미론: 평가(Runtime Semantics: Evaluation)

AdditiveExpression : AdditiveExpression + MultiplicativeExpression
  1. EvaluateStringOrNumericBinaryExpression(AdditiveExpression, +, MultiplicativeExpression) 반환.

13.8.2 뺄셈 연산자 ( - ) (The Subtraction Operator)

Note

- 연산자는 피연산자의 차(difference)를 생성하는 뺄셈을 수행한다.

13.8.2.1 런타임 의미론: 평가(Runtime Semantics: Evaluation)

AdditiveExpression : AdditiveExpression - MultiplicativeExpression
  1. EvaluateStringOrNumericBinaryExpression(AdditiveExpression, -, MultiplicativeExpression) 반환.

13.9 비트 시프트 연산자(Bitwise Shift Operators)

Syntax

ShiftExpression[Yield, Await] : AdditiveExpression[?Yield, ?Await] ShiftExpression[?Yield, ?Await] << AdditiveExpression[?Yield, ?Await] ShiftExpression[?Yield, ?Await] >> AdditiveExpression[?Yield, ?Await] ShiftExpression[?Yield, ?Await] >>> AdditiveExpression[?Yield, ?Await]

13.9.1 왼쪽 시프트 연산자 ( << ) (The Left Shift Operator)

Note

왼쪽 피연산자를 오른쪽 피연산자가 지정한 비트 수만큼 비트 왼쪽 시프트한다.

13.9.1.1 런타임 의미론: 평가(Runtime Semantics: Evaluation)

ShiftExpression : ShiftExpression << AdditiveExpression
  1. EvaluateStringOrNumericBinaryExpression(ShiftExpression, <<, AdditiveExpression) 반환.

13.9.2 부호 있는 오른쪽 시프트 연산자 ( >> ) (The Signed Right Shift Operator)

Note

왼쪽 피연산자를 오른쪽 피연산자가 지정한 비트 수만큼 부호 확장(bit sign-filling)하며 오른쪽 시프트한다.

13.9.2.1 런타임 의미론: 평가(Runtime Semantics: Evaluation)

ShiftExpression : ShiftExpression >> AdditiveExpression
  1. EvaluateStringOrNumericBinaryExpression(ShiftExpression, >>, AdditiveExpression) 반환.

13.9.3 부호 없는 오른쪽 시프트 연산자 ( >>> ) (The Unsigned Right Shift Operator)

Note

왼쪽 피연산자를 오른쪽 피연산자가 지정한 비트 수만큼 0 으로 채우며 오른쪽 시프트한다.

13.9.3.1 런타임 의미론: 평가(Runtime Semantics: Evaluation)

ShiftExpression : ShiftExpression >>> AdditiveExpression
  1. EvaluateStringOrNumericBinaryExpression(ShiftExpression, >>>, AdditiveExpression) 반환.

13.10 관계 연산자(Relational Operators)

Note 1

관계 연산자 평가 결과는 항상 Boolean 타입이며, 연산자가 명명한 관계가 두 피연산자 사이에서 성립하는지를 반영한다.

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] 문법 매개변수는 관계 표현식에서의 in 연산자를 for 문의 in 연산자와 혼동하지 않도록 필요하다.

13.10.1 런타임 의미론: 평가(Runtime Semantics: Evaluation)

RelationalExpression : RelationalExpression < ShiftExpression
  1. lRefRelationalExpression 의 Evaluation 결과 (?) 로 둔다.
  2. lVal 를 ? GetValue(lRef) 로 둔다.
  3. rRefShiftExpression 의 Evaluation 결과 (?) 로 둔다.
  4. rVal 를 ? GetValue(rRef) 로 둔다.
  5. r 를 ? IsLessThan(lVal, rVal, true) 로 둔다.
  6. rundefined 이면 false 반환; 그렇지 않으면 r 반환.
RelationalExpression : RelationalExpression > ShiftExpression
  1. lRef, lVal, rRef, rVal 를 위와 같이 얻는다.
  2. r 를 ? IsLessThan(rVal, lVal, false) 로 둔다.
  3. rundefined 이면 false 반환; 그렇지 않으면 r 반환.
RelationalExpression : RelationalExpression <= ShiftExpression
  1. lRef, lVal, rRef, rVal 를 얻는다.
  2. r 를 ? IsLessThan(rVal, lVal, false) 로 둔다.
  3. rtrue 또는 undefined 이면 false 반환; 그렇지 않으면 true 반환.
RelationalExpression : RelationalExpression >= ShiftExpression
  1. lRef, lVal, rRef, rVal 를 얻는다.
  2. r 를 ? IsLessThan(lVal, rVal, true) 로 둔다.
  3. rtrue 또는 undefined 이면 false 반환; 그렇지 않으면 true 반환.
RelationalExpression : RelationalExpression instanceof ShiftExpression
  1. lRef, lVal, rRef, rVal 를 얻는다.
  2. InstanceofOperator(lVal, rVal) 반환.
RelationalExpression : RelationalExpression in ShiftExpression
  1. lRef, lVal, rRef, rVal 를 얻는다.
  2. rVal 가 Object 가 아니면 TypeError 예외 throw.
  3. HasProperty(rVal, ? ToPropertyKey(lVal)) 반환.
RelationalExpression : PrivateIdentifier in ShiftExpression
  1. privateIdentifierPrivateIdentifier 의 StringValue 로 둔다.
  2. rRefShiftExpression 의 Evaluation 결과 (?) 로 둔다.
  3. rVal 를 ? GetValue(rRef) 로 둔다.
  4. rVal 가 Object 가 아니면 TypeError 예외 throw.
  5. privateEnv 를 실행 중인 실행 컨텍스트의 PrivateEnvironment 로 둔다.
  6. 단언: privateEnvnull 이 아님.
  7. privateNameResolvePrivateIdentifier(privateEnv, privateIdentifier) 로 둔다.
  8. PrivateElementFind(rVal, privateName) 이 empty 가 아니면 true 반환.
  9. false 반환.

13.10.2 InstanceofOperator ( V, target )

The abstract operation InstanceofOperator takes arguments V (an ECMAScript language value) and target (an ECMAScript language value) and returns Boolean 을 담는 정상 완료 또는 throw completion. target%Symbol.hasInstance% 메서드를 조회하거나, 없다면 target"prototype" 프로퍼티 값이 V 의 프로토타입 체인에 존재하는지 확인하여 Vtarget 의 인스턴스인지 결정하는 일반 알고리즘을 구현한다. It performs the following steps when called:

  1. target 이 Object 가 아니면 TypeError 예외 throw.
  2. instOfHandler 를 ? GetMethod(target, %Symbol.hasInstance%) 로 둔다.
  3. instOfHandlerundefined 가 아니면
    1. ToBoolean(? Call(instOfHandler, target, « V »)) 반환.
  4. IsCallable(target) 이 false 이면 TypeError 예외 throw.
  5. OrdinaryHasInstance(target, V) 반환.
Note

45 단계는 %Symbol.hasInstance% 를 사용하지 않던 이전 ECMAScript 판과의 호환성을 제공한다. 객체가 %Symbol.hasInstance% 를 정의하거나 상속하지 않으면 기본 instanceof 의미론을 사용한다.

13.11 동등 연산자(Equality Operators)

Note

동등 연산자 평가 결과는 항상 Boolean 타입이며, 연산자가 명명한 관계가 두 피연산자 사이에서 성립하는지를 반영한다.

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. lRefEqualityExpression 의 Evaluation 결과 (?) 로 둔다.
  2. lVal 를 ? GetValue(lRef) 로 둔다.
  3. rRefRelationalExpression 의 Evaluation 결과 (?) 로 둔다.
  4. rVal 를 ? GetValue(rRef) 로 둔다.
  5. IsLooselyEqual(rVal, lVal) 반환.
EqualityExpression : EqualityExpression != RelationalExpression
  1. lRef, lVal, rRef, rVal 를 얻는다.
  2. r 를 ? IsLooselyEqual(rVal, lVal) 로 둔다.
  3. rtrue 이면 false 반환; 그렇지 않으면 true 반환.
EqualityExpression : EqualityExpression === RelationalExpression
  1. lRef, lVal, rRef, rVal 를 얻는다.
  2. IsStrictlyEqual(rVal, lVal) 반환.
EqualityExpression : EqualityExpression !== RelationalExpression
  1. lRef, lVal, rRef, rVal 를 얻는다.
  2. rIsStrictlyEqual(rVal, lVal) 로 둔다.
  3. rtrue 이면 false 반환; 그렇지 않으면 true 반환.
Note 1

위 동등성 정의에 따라:

  • 문자열 비교를 강제하려면: \`${a}\` == \`${b}\`.
  • 수치 비교를 강제하려면: +a == +b.
  • Boolean 비교를 강제하려면: !a == !b.
Note 2

동등 연산자는 다음 불변식을 유지한다:

  • A != B!(A == B) 와 동등하다.
  • A == B 는 (평가 순서 제외) B == A 와 동등하다.
Note 3

동등 연산자는 항상 추이적(transitive)이지는 않다. 예를 들어 동일한 String 값을 나타내는 서로 다른 두 String 객체가 있을 수 있고, 각 객체는 == 연산자에 의해 그 String 값과는 같지만 서로는 같지 않을 수 있다. 예:

  • new String("a") == "a""a" == new String("a") 는 둘 다 true.
  • new String("a") == new String("a")false.
Note 4

문자열 비교는 코드 유닛 값 시퀀스의 단순 동등성 검사만을 사용한다. 유니코드 명세에 정의된 더 복잡하고 의미 지향적인 문자/문자열 동등성 또는 정렬 순서를 사용하지 않는다. 따라서 유니코드 표준에 따라 정규적으로 동등한 String 값이라도 서로 다르다고 나올 수 있다. 사실상 이 알고리즘은 두 String 이 이미 정규화(normalized)되어 있다고 가정한다.

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

&& 또는 || 연산자가 생성하는 값은 반드시 Boolean 타입일 필요가 없다. 결과 값은 항상 두 피연산자 표현식 중 하나의 값이다.

13.13.1 런타임 의미론: 평가(Runtime Semantics: Evaluation)

LogicalANDExpression : LogicalANDExpression && BitwiseORExpression
  1. lRefLogicalANDExpression 의 Evaluation 결과 (?) 로 둔다.
  2. lVal 를 ? GetValue(lRef) 로 둔다.
  3. ToBoolean(lVal) 이 false 이면 lVal 반환.
  4. rRefBitwiseORExpression 의 Evaluation 결과 (?) 로 둔다.
  5. GetValue(rRef) 반환.
LogicalORExpression : LogicalORExpression || LogicalANDExpression
  1. lRefLogicalORExpression 의 Evaluation 결과 (?) 로 둔다.
  2. lVal 를 ? GetValue(lRef) 로 둔다.
  3. ToBoolean(lVal) 이 true 이면 lVal 반환.
  4. rRefLogicalANDExpression 의 Evaluation 결과 (?) 로 둔다.
  5. GetValue(rRef) 반환.
CoalesceExpression : CoalesceExpressionHead ?? BitwiseORExpression
  1. lRefCoalesceExpressionHead 의 Evaluation 결과 (?) 로 둔다.
  2. lVal 를 ? GetValue(lRef) 로 둔다.
  3. lValundefined 또는 null 이면
    1. rRefBitwiseORExpression 의 Evaluation 결과 (?) 로 둔다.
    2. GetValue(rRef) 반환.
  4. 그렇지 않으면
    1. lVal 반환.

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 문법은 C 및 Java 와 약간 다르다. C 와 Java 는 두 번째 부분식을 Expression 으로 허용하지만 세 번째 부분식을 ConditionalExpression 으로 제한한다. ECMAScript 에서 이러한 차이를 둔 동기는 (1) 조건부의 어느 한 쪽 (arm) 에서도 할당 표현식을 다룰 수 있게 하고 (2) 가운데 표현식이 쉼표 표현식인 혼란스럽고 거의 쓸모없는 경우를 제거하기 위함이다.

13.14.1 런타임 의미론: 평가(Runtime Semantics: Evaluation)

ConditionalExpression : ShortCircuitExpression ? AssignmentExpression : AssignmentExpression
  1. lRefShortCircuitExpression 의 Evaluation 결과 (?) 로 둔다.
  2. lValToBoolean(? GetValue(lRef)) 로 둔다.
  3. lValtrue 이면
    1. trueRef 를 첫 번째 AssignmentExpression 의 Evaluation 결과 (?) 로 둔다.
    2. GetValue(trueRef) 반환.
  4. 그렇지 않으면
    1. falseRef 를 두 번째 AssignmentExpression 의 Evaluation 결과 (?) 로 둔다.
    2. 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. lRefLeftHandSideExpression 의 Evaluation 결과 (?) 로 둔다.
    2. LeftHandSideExpression 의 AssignmentTargetType 이 web-compat 이면 ReferenceError 예외를 throw.
    3. IsAnonymousFunctionDefinition(AssignmentExpression) 이 true 이고 IsIdentifierRef(LeftHandSideExpression) 가 true 이면
      1. lhsLeftHandSideExpression 의 StringValue 로 둔다.
      2. rValAssignmentExpression 의 NamedEvaluation(lhs) 결과 (?) 로 둔다.
    4. 그렇지 않으면
      1. rRefAssignmentExpression 의 Evaluation 결과 (?) 로 둔다.
      2. rVal 를 ? GetValue(rRef) 로 둔다.
    5. PutValue(lRef, rVal) 수행.
    6. rVal 반환.
  2. assignmentPatternLeftHandSideExpression 이 커버하는 AssignmentPattern 으로 둔다.
  3. rRefAssignmentExpression 의 Evaluation 결과 (?) 로 둔다.
  4. rVal 를 ? GetValue(rRef) 로 둔다.
  5. assignmentPattern 의 DestructuringAssignmentEvaluation(rVal) 를 ? 로 수행.
  6. rVal 반환.
AssignmentExpression : LeftHandSideExpression AssignmentOperator AssignmentExpression
  1. lRefLeftHandSideExpression 의 Evaluation 결과 (?) 로 둔다.
  2. LeftHandSideExpression 의 AssignmentTargetType 이 web-compat 이면 ReferenceError 예외 throw.
  3. lVal 를 ? GetValue(lRef) 로 둔다.
  4. rRefAssignmentExpression 의 Evaluation 결과 (?) 로 둔다.
  5. rVal 를 ? GetValue(rRef) 로 둔다.
  6. assignmentOpTextAssignmentOperator 가 매칭한 소스 텍스트로 둔다.
  7. opText 를 아래 표에서 assignmentOpText 에 연관된 유니코드 코드 포인트 시퀀스로 둔다.
    assignmentOpText opText
    **= **
    *= *
    /= /
    %= %
    += +
    -= -
    <<= <<
    >>= >>
    >>>= >>>
    &= &
    ^= ^
    |= |
  8. r 를 ? ApplyStringOrNumericBinaryOperator(lVal, opText, rVal) 로 둔다.
  9. PutValue(lRef, r) 수행.
  10. r 반환.
AssignmentExpression : LeftHandSideExpression &&= AssignmentExpression
  1. lRefLeftHandSideExpression 의 Evaluation 결과 (?) 로 둔다.
  2. lVal 를 ? GetValue(lRef) 로 둔다.
  3. ToBoolean(lVal) 가 false 이면 lVal 반환.
  4. IsAnonymousFunctionDefinition(AssignmentExpression) 이 true 이고 IsIdentifierRef(LeftHandSideExpression) 가 true 이면
    1. lhsLeftHandSideExpression 의 StringValue 로 둔다.
    2. rValAssignmentExpression 의 NamedEvaluation(lhs) 결과 (?) 로 둔다.
  5. 그렇지 않으면
    1. rRefAssignmentExpression 의 Evaluation 결과 (?) 로 둔다.
    2. rVal 를 ? GetValue(rRef) 로 둔다.
  6. PutValue(lRef, rVal) 수행.
  7. rVal 반환.
AssignmentExpression : LeftHandSideExpression ||= AssignmentExpression
  1. lRefLeftHandSideExpression 의 Evaluation 결과 (?) 로 둔다.
  2. lVal 를 ? GetValue(lRef) 로 둔다.
  3. ToBoolean(lVal) 가 true 이면 lVal 반환.
  4. IsAnonymousFunctionDefinition(AssignmentExpression) 이 true 이고 IsIdentifierRef(LeftHandSideExpression) 가 true 이면
    1. lhsLeftHandSideExpression 의 StringValue 로 둔다.
    2. rValAssignmentExpression 의 NamedEvaluation(lhs) 결과 (?) 로 둔다.
  5. 그렇지 않으면
    1. rRefAssignmentExpression 의 Evaluation 결과 (?) 로 둔다.
    2. rVal 를 ? GetValue(rRef) 로 둔다.
  6. PutValue(lRef, rVal) 수행.
  7. rVal 반환.
AssignmentExpression : LeftHandSideExpression ??= AssignmentExpression
  1. lRefLeftHandSideExpression 의 Evaluation 결과 (?) 로 둔다.
  2. lVal 를 ? GetValue(lRef) 로 둔다.
  3. lValundefinednull 도 아니면 lVal 반환.
  4. IsAnonymousFunctionDefinition(AssignmentExpression) 이 true 이고 IsIdentifierRef(LeftHandSideExpression) 가 true 이면
    1. lhsLeftHandSideExpression 의 StringValue 로 둔다.
    2. rValAssignmentExpression 의 NamedEvaluation(lhs) 결과 (?) 로 둔다.
  5. 그렇지 않으면
    1. rRefAssignmentExpression 의 Evaluation 결과 (?) 로 둔다.
    2. rVal 를 ? GetValue(rRef) 로 둔다.
  6. PutValue(lRef, rVal) 수행.
  7. rVal 반환.
Note

이 표현식이 strict 모드 코드 내에 나타날 때 단계 1.e, 3, 2, 2, 2lRef 가 해석 불가능한(unresolvable) reference 이면 런타임 오류이며 ReferenceError 예외가 발생한다. 또한 단계 9, 6, 6, 6lRef 가 { [[Writable]]: false } 특성을 가진 데이터 프로퍼티, { [[Set]]: undefined } 특성을 가진 접근자 프로퍼티, 또는 IsExtensiblefalse 를 반환하는 객체의 존재하지 않는 프로퍼티라면 TypeError 예외가 발생한다.

13.15.3 ApplyStringOrNumericBinaryOperator ( lVal, opText, rVal )

The abstract operation ApplyStringOrNumericBinaryOperator takes arguments lVal (an ECMAScript language value), opText (**, *, /, %, +, -, <<, >>, >>>, &, ^, or |), and rVal (an ECMAScript language value) and returns 정상 완료 시 String, BigInt 또는 Number 중 하나 또는 throw completion. It performs the following steps when called:

  1. opText+ 이면
    1. lPrim 을 ? ToPrimitive(lVal) 로 둔다.
    2. rPrim 을 ? ToPrimitive(rVal) 로 둔다.
    3. lPrim 이 String 이거나 rPrim 이 String 이면
      1. lStr 을 ? ToString(lPrim) 로 둔다.
      2. rStr 을 ? ToString(rPrim) 로 둔다.
      3. lStrrStr 의 문자열 연결을 반환.
    4. lVallPrim 으로 설정.
    5. rValrPrim 으로 설정.
  2. NOTE: 이 시점부터는 수치 연산이어야 한다.
  3. lNum 을 ? ToNumeric(lVal) 로 둔다.
  4. rNum 을 ? ToNumeric(rVal) 로 둔다.
  5. SameType(lNum, rNum) 이 false 이면 TypeError 예외 throw.
  6. lNum 이 BigInt 이면
    1. opText** 이면 ? BigInt::exponentiate(lNum, rNum) 반환.
    2. opText/ 이면 ? BigInt::divide(lNum, rNum) 반환.
    3. opText% 이면 ? BigInt::remainder(lNum, rNum) 반환.
    4. opText>>> 이면 ? BigInt::unsignedRightShift(lNum, rNum) 반환.
    5. operation 을 아래 표에서 opText 에 연관된 추상 연산으로 둔다.
      opText operation
      * BigInt::multiply
      + BigInt::add
      - BigInt::subtract
      << BigInt::leftShift
      >> BigInt::signedRightShift
      & BigInt::bitwiseAND
      ^ BigInt::bitwiseXOR
      | BigInt::bitwiseOR
  7. 그렇지 않으면
    1. 단언: lNum 은 Number.
    2. operation 을 아래 표에서 opText 에 연관된 추상 연산으로 둔다.
      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(lNum, rNum) 반환.
Note 1

단계 1.a, 1.bToPrimitive 호출에는 hint 가 제공되지 않는다. 표준 객체 중 Date 를 제외한 모든 객체는 hint 부재를 number 가 주어진 것처럼 처리하고 Date 는 string 처럼 처리한다. 특수(exotic) 객체는 다른 방식으로 처리할 수 있다.

Note 2

단계 1.cIsLessThan 알고리즘의 단계 3 와 달리 논리 AND 대신 논리 OR 를 사용한다.

13.15.4 EvaluateStringOrNumericBinaryExpression ( leftOperand, opText, rightOperand )

The abstract operation EvaluateStringOrNumericBinaryExpression takes arguments leftOperand (a Parse Node), opText (a sequence of Unicode code points), and rightOperand (a Parse Node) and returns 정상 완료 시 String, BigInt 또는 Number 중 하나 또는 abrupt completion. It performs the following steps when called:

  1. lRefleftOperand 의 Evaluation 결과 (?) 로 둔다.
  2. lVal 를 ? GetValue(lRef) 로 둔다.
  3. rRefrightOperand 의 Evaluation 결과 (?) 로 둔다.
  4. rVal 를 ? GetValue(rRef) 로 둔다.
  5. ApplyStringOrNumericBinaryOperator(lVal, opText, rVal) 반환.

13.15.5 구조 분해 할당(Destructuring Assignment)

보충 문법(Supplemental Syntax)

특정 상황에서 다음 생성물 인스턴스를 처리할 때
AssignmentExpression : LeftHandSideExpression = AssignmentExpression
LeftHandSideExpression 의 해석은 아래 문법을 사용해 정밀화된다:

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 런타임 의미론: DestructuringAssignmentEvaluation : 정상 완료 시 unused 또는 abrupt completion

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. It is defined piecewise over the following productions:

ObjectAssignmentPattern : { }
  1. RequireObjectCoercible(value) 수행.
  2. unused 반환.
ObjectAssignmentPattern : { AssignmentPropertyList } { AssignmentPropertyList , }
  1. RequireObjectCoercible(value) 수행.
  2. AssignmentPropertyList 의 PropertyDestructuringAssignmentEvaluation(value) 를 ? 로 수행.
  3. unused 반환.
ObjectAssignmentPattern : { AssignmentRestProperty }
  1. RequireObjectCoercible(value) 수행.
  2. excludedNames 를 새 빈 List 로 둔다.
  3. AssignmentRestProperty 의 RestDestructuringAssignmentEvaluation(value, excludedNames) 를 ? 로 반환.
ObjectAssignmentPattern : { AssignmentPropertyList , AssignmentRestProperty }
  1. RequireObjectCoercible(value) 수행.
  2. excludedNamesAssignmentPropertyList 의 PropertyDestructuringAssignmentEvaluation(value) 결과 (?) 로 둔다.
  3. AssignmentRestProperty 의 RestDestructuringAssignmentEvaluation(value, excludedNames) 를 ? 로 반환.
ArrayAssignmentPattern : [ ]
  1. iteratorRecord 를 ? GetIterator(value, sync) 로 둔다.
  2. IteratorClose(iteratorRecord, NormalCompletion(unused)) 반환.
ArrayAssignmentPattern : [ Elision ]
  1. iteratorRecord 를 ? GetIterator(value, sync) 로 둔다.
  2. resultCompletion(IteratorDestructuringAssignmentEvaluation(Elision, iteratorRecord)) 로 둔다.
  3. iteratorRecord.[[Done]]false 이면 ? IteratorClose(iteratorRecord, result) 반환.
  4. result 반환.
ArrayAssignmentPattern : [ Elisionopt AssignmentRestElement ]
  1. iteratorRecord 를 ? GetIterator(value, sync) 로 둔다.
  2. Elision 이 존재하면
    1. statusCompletion(IteratorDestructuringAssignmentEvaluation(Elision, iteratorRecord)) 로 둔다.
    2. statusabrupt completion 이면
      1. 단언: iteratorRecord.[[Done]]true.
      2. status 반환.
  3. resultCompletion(IteratorDestructuringAssignmentEvaluation(AssignmentRestElement, iteratorRecord)) 로 둔다.
  4. iteratorRecord.[[Done]]false 이면 ? IteratorClose(iteratorRecord, result) 반환.
  5. result 반환.
ArrayAssignmentPattern : [ AssignmentElementList ]
  1. iteratorRecord 를 ? GetIterator(value, sync) 로 둔다.
  2. resultCompletion(IteratorDestructuringAssignmentEvaluation(AssignmentElementList, iteratorRecord)) 로 둔다.
  3. iteratorRecord.[[Done]]false 이면 ? IteratorClose(iteratorRecord, result) 반환.
  4. result 반환.
ArrayAssignmentPattern : [ AssignmentElementList , Elisionopt AssignmentRestElementopt ]
  1. iteratorRecord 를 ? GetIterator(value, sync) 로 둔다.
  2. statusCompletion(IteratorDestructuringAssignmentEvaluation(AssignmentElementList, iteratorRecord)) 로 둔다.
  3. statusabrupt completion 이면
    1. iteratorRecord.[[Done]]false 이면 ? IteratorClose(iteratorRecord, status) 반환.
    2. status 반환.
  4. Elision 이 존재하면
    1. statusCompletion(IteratorDestructuringAssignmentEvaluation(Elision, iteratorRecord)) 로 설정.
    2. statusabrupt completion 이면
      1. 단언: iteratorRecord.[[Done]]true.
      2. status 반환.
  5. AssignmentRestElement 가 존재하면
    1. statusCompletion(IteratorDestructuringAssignmentEvaluation(AssignmentRestElement, iteratorRecord)) 로 설정.
  6. iteratorRecord.[[Done]]false 이면 ? IteratorClose(iteratorRecord, status) 반환.
  7. status 반환.

13.15.5.3 런타임 의미론: PropertyDestructuringAssignmentEvaluation : 정상 완료 시 프로퍼티 키 List 또는 abrupt completion

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. 모든 구조 분해된 프로퍼티 키의 목록을 수집한다. It is defined piecewise over the following productions:

AssignmentPropertyList : AssignmentPropertyList , AssignmentProperty
  1. propertyNamesAssignmentPropertyList 의 PropertyDestructuringAssignmentEvaluation(value) 결과 (?) 로 둔다.
  2. nextNamesAssignmentProperty 의 PropertyDestructuringAssignmentEvaluation(value) 결과 (?) 로 둔다.
  3. propertyNamesnextNames 의 리스트 연결 반환.
AssignmentProperty : IdentifierReference Initializeropt
  1. PIdentifierReference 의 StringValue 로 둔다.
  2. lRef 를 ? ResolveBinding(P) 로 둔다.
  3. v 를 ? GetV(value, P) 로 둔다.
  4. Initializer 가 존재하고 vundefined 이면
    1. IsAnonymousFunctionDefinition(Initializer) 이 true 이면
      1. vInitializer 의 NamedEvaluation(P) 결과 (?) 로 설정.
    2. 그렇지 않으면
      1. defaultValueInitializer 의 Evaluation 결과 (?) 로 둔다.
      2. v 를 ? GetValue(defaultValue) 로 둔다.
  5. PutValue(lRef, v) 수행.
  6. « P » 반환.
AssignmentProperty : PropertyName : AssignmentElement
  1. namePropertyName 의 Evaluation 결과 (?) 로 둔다.
  2. AssignmentElement 의 KeyedDestructuringAssignmentEvaluation(value, name) 를 ? 로 수행.
  3. « name » 반환.

13.15.5.4 런타임 의미론: RestDestructuringAssignmentEvaluation : 정상 완료 시 unused 또는 abrupt completion

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. It is defined piecewise over the following productions:

AssignmentRestProperty : ... DestructuringAssignmentTarget
  1. lRefDestructuringAssignmentTarget 의 Evaluation 결과 (?) 로 둔다.
  2. restObjOrdinaryObjectCreate(%Object.prototype%) 로 둔다.
  3. CopyDataProperties(restObj, value, excludedNames) 수행.
  4. PutValue(lRef, restObj) 반환.

13.15.5.5 런타임 의미론: IteratorDestructuringAssignmentEvaluation : 정상 완료 시 unused 또는 abrupt completion

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. It is defined piecewise over the following productions:

AssignmentElementList : AssignmentElisionElement
  1. ? IteratorDestructuringAssignmentEvaluation(AssignmentElisionElement, iteratorRecord) 반환.
AssignmentElementList : AssignmentElementList , AssignmentElisionElement
  1. ? IteratorDestructuringAssignmentEvaluation(AssignmentElementList, iteratorRecord) 수행.
  2. ? IteratorDestructuringAssignmentEvaluation(AssignmentElisionElement, iteratorRecord) 반환.
AssignmentElisionElement : AssignmentElement
  1. ? IteratorDestructuringAssignmentEvaluation(AssignmentElement, iteratorRecord) 반환.
AssignmentElisionElement : Elision AssignmentElement
  1. ? IteratorDestructuringAssignmentEvaluation(Elision, iteratorRecord) 수행.
  2. ? IteratorDestructuringAssignmentEvaluation(AssignmentElement, iteratorRecord) 반환.
Elision : ,
  1. iteratorRecord.[[Done]]false 이면
    1. IteratorStep(iteratorRecord) 수행.
  2. unused 반환.
Elision : Elision ,
  1. ? IteratorDestructuringAssignmentEvaluation(Elision, iteratorRecord) 수행.
  2. iteratorRecord.[[Done]]false 이면
    1. IteratorStep(iteratorRecord) 수행.
  3. unused 반환.
AssignmentElement : DestructuringAssignmentTarget Initializeropt
  1. DestructuringAssignmentTargetObjectLiteralArrayLiteral 도 아니면
    1. lRefDestructuringAssignmentTarget 의 Evaluation 결과 (?) 로 둔다.
  2. valueundefined 로 둔다.
  3. iteratorRecord.[[Done]]false 이면
    1. next 를 ? IteratorStepValue(iteratorRecord) 로 둔다.
    2. nextdone 이 아니면
      1. valuenext 로 설정.
  4. Initializer 가 존재하고 valueundefined 이면
    1. IsAnonymousFunctionDefinition(Initializer) 이 true 이고 IsIdentifierRef(DestructuringAssignmentTarget) 가 true 이면
      1. targetDestructuringAssignmentTarget 의 StringValue 로 둔다.
      2. vInitializer 의 NamedEvaluation(target) 결과 (?) 로 둔다.
    2. 그렇지 않으면
      1. defaultValueInitializer 의 Evaluation 결과 (?) 로 둔다.
      2. v 를 ? GetValue(defaultValue) 로 둔다.
  5. 그렇지 않으면
    1. vvalue 로 둔다.
  6. DestructuringAssignmentTargetObjectLiteral 이거나 ArrayLiteral 이면
    1. nestedAssignmentPatternDestructuringAssignmentTarget 이 커버하는 AssignmentPattern 으로 둔다.
    2. ? DestructuringAssignmentEvaluation(nestedAssignmentPattern, v) 반환.
  7. PutValue(lRef, v) 반환.
Note

DestructuringAssignmentTarget 이 구조 분해 패턴이 아닌 경우 그것을 먼저 평가한 뒤 iterator 접근이나 Initializer 평가가 수행되어 좌→우 평가 순서가 유지된다.

AssignmentRestElement : ... DestructuringAssignmentTarget
  1. DestructuringAssignmentTargetObjectLiteralArrayLiteral 도 아니면
    1. lRefDestructuringAssignmentTarget 의 Evaluation 결과 (?) 로 둔다.
  2. A 를 ! ArrayCreate(0) 로 둔다.
  3. n = 0.
  4. iteratorRecord.[[Done]]false 인 동안 반복
    1. next 를 ? IteratorStepValue(iteratorRecord) 로 둔다.
    2. nextdone 이 아니면
      1. CreateDataPropertyOrThrow(A, ! ToString(𝔽(n)), next) 수행.
      2. n = n + 1.
  5. DestructuringAssignmentTargetObjectLiteralArrayLiteral 도 아니면
    1. PutValue(lRef, A) 반환.
  6. nestedAssignmentPatternDestructuringAssignmentTarget 이 커버하는 AssignmentPattern 으로 둔다.
  7. ? DestructuringAssignmentEvaluation(nestedAssignmentPattern, A) 반환.

13.15.5.6 런타임 의미론: KeyedDestructuringAssignmentEvaluation : 정상 완료 시 unused 또는 abrupt completion

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. It is defined piecewise over the following productions:

AssignmentElement : DestructuringAssignmentTarget Initializeropt
  1. DestructuringAssignmentTargetObjectLiteralArrayLiteral 도 아니면
    1. lRefDestructuringAssignmentTarget 의 Evaluation 결과 (?) 로 둔다.
  2. v 를 ? GetV(value, propertyName) 로 둔다.
  3. Initializer 가 존재하고 vundefined 이면
    1. IsAnonymousFunctionDefinition(Initializer) 이 true 이고 IsIdentifierRef(DestructuringAssignmentTarget) 가 true 이면
      1. targetDestructuringAssignmentTarget 의 StringValue 로 둔다.
      2. rhsValueInitializer 의 NamedEvaluation(target) 결과 (?) 로 둔다.
    2. 그렇지 않으면
      1. defaultValueInitializer 의 Evaluation 결과 (?) 로 둔다.
      2. rhsValue 를 ? GetValue(defaultValue) 로 둔다.
  4. 그렇지 않으면
    1. rhsValuev 로 둔다.
  5. DestructuringAssignmentTargetObjectLiteral 이거나 ArrayLiteral 이면
    1. assignmentPatternDestructuringAssignmentTarget 이 커버하는 AssignmentPattern 으로 둔다.
    2. ? DestructuringAssignmentEvaluation(assignmentPattern, rhsValue) 반환.
  6. PutValue(lRef, 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. lRefExpression 의 Evaluation 결과 (?) 로 둔다.
  2. GetValue(lRef) 수행.
  3. rRefAssignmentExpression 의 Evaluation 결과 (?) 로 둔다.
  4. GetValue(rRef) 반환.
Note

값을 사용하지 않더라도 관찰 가능한 부수 효과가 있을 수 있으므로 GetValue 는 호출되어야 한다.

14 ECMAScript 언어: 문(Statements)과 선언(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 의미론

14.1.1 런타임 의미론: 평가

HoistableDeclaration : GeneratorDeclaration AsyncFunctionDeclaration AsyncGeneratorDeclaration
  1. empty 를 반환한다.
HoistableDeclaration : FunctionDeclaration
  1. FunctionDeclaration 의 Evaluation 결과를 ? 로 반환한다.
BreakableStatement : IterationStatement SwitchStatement
  1. newLabelSet 을 새 빈 List 로 둔다.
  2. BreakableStatement 의 LabelledEvaluation(newLabelSet) 결과를 ? 로 반환한다.

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 정적 의미론: 조기 오류

Block : { StatementList }

14.2.2 런타임 의미론: 평가

Block : { }
  1. empty 를 반환한다.
Block : { StatementList }
  1. oldEnv 를 실행 중인 실행 컨텍스트의 LexicalEnvironment 로 둔다.
  2. blockEnvNewDeclarativeEnvironment(oldEnv) 로 둔다.
  3. BlockDeclarationInstantiation(StatementList, blockEnv) 수행.
  4. 실행 컨텍스트의 LexicalEnvironment 를 blockEnv 로 설정.
  5. blockValueCompletion(StatementList 평가) 로 둔다.
  6. 실행 컨텍스트의 LexicalEnvironment 를 oldEnv 로 되돌린다.
  7. blockValue 를 반환한다.
Note 1

Block 을 어떻게 빠져나오든 LexicalEnvironment 는 항상 이전 상태로 복구된다.

StatementList : StatementList StatementListItem
  1. slStatementList 의 Evaluation 결과 (?) 로 둔다.
  2. sStatementListItem 평가의 Completion 으로 둔다.
  3. UpdateEmpty(s, sl) 를 반환한다.
Note 2

StatementList 의 값은 그 안에서 마지막으로 값을 생산한 항목의 값이다. 예를 들어 아래 eval 호출은 모두 1을 반환한다:

eval("1;;;;;")
eval("1;{}")
eval("1;var a;")

14.2.3 BlockDeclarationInstantiation ( code, env )

The abstract operation BlockDeclarationInstantiation takes arguments code (a Parse Node) and env (a Declarative Environment Record) and returns unused. code 는 블록 본문에 대응하는 Parse Node 이며, env 는 바인딩이 생성될 Environment Record 이다.

Note

Block 또는 CaseBlock 이 평가될 때 새 Declarative Environment Record 가 생성되고 블록 안에 선언된 블록 스코프 변수/상수/함수/클래스에 대한 바인딩이 그 Environment Record 안에서 생성된다.

호출 시 다음 단계를 수행한다:

  1. declarationscode 의 LexicallyScopedDeclarations 로 둔다.
  2. privateEnv 를 실행 중인 실행 컨텍스트의 PrivateEnvironment 로 둔다.
  3. declarations 의 각 요소 d 에 대해
    1. d 의 BoundNames 각 요소 dn 에 대해
      1. IsConstantDeclaration(d) 가 true 이면
        1. env.CreateImmutableBinding(dn, true) 수행.
      2. 그렇지 않으면
        1. Normative Optional
          호스트가 웹 브라우저이거나 블록 수준 함수 선언 웹 레거시 호환 의미 를 지원하면
          1. env.HasBinding(dn) 이 false 이면
            1. env.CreateMutableBinding(dn, false) 수행.
        2. 그렇지 않으면
          1. env.CreateMutableBinding(dn, false) 수행.
    2. dFunctionDeclaration, GeneratorDeclaration, AsyncFunctionDeclaration, AsyncGeneratorDeclaration 중 하나라면
      1. fnd 의 BoundNames 의 유일한 요소로 둔다.
      2. fo 를 InstantiateFunctionObject(d, 인수 env, privateEnv) 로 둔다.
      3. Normative Optional
        호스트가 웹 브라우저이거나 블록 수준 함수 선언 웹 레거시 호환 의미 를 지원하면
        1. env 에서 fn 바인딩이 초기화되지 않았다면
          1. env.InitializeBinding(fn, fo) 수행.
        2. 그렇지 않으면
          1. 단언: dFunctionDeclaration.
          2. env.SetMutableBinding(fn, fo, false) 수행.
      4. 그렇지 않으면
        1. env.InitializeBinding(fn, fo) 수행.
  4. unused 반환.

14.3 선언과 변수 문(Variable Statement)

14.3.1 Let 및 Const 선언

Note

letconst 선언은 실행 중인 실행 컨텍스트의 LexicalEnvironment 에 스코프를 가지는 변수를 정의한다. 변수는 포함 Environment Record 가 초기화될 때 생성되지만 해당 변수의 LexicalBinding 이 평가되기 전에는 어떤 방식으로도 접근할 수 없다. Initializer 를 가진 LexicalBinding 으로 정의된 변수는 그 LexicalBinding 이 평가될 때 InitializerAssignmentExpression 결과 값이 할당되며, 생성 시점이 아니다. let 선언에서 Initializer 가 없는 LexicalBinding 은 평가 시 undefined 가 할당된다.

Syntax

LexicalDeclaration[In, Yield, Await] : LetOrConst BindingList[?In, ?Yield, ?Await] ; LetOrConst : let const BindingList[In, Yield, Await] : LexicalBinding[?In, ?Yield, ?Await] BindingList[?In, ?Yield, ?Await] , LexicalBinding[?In, ?Yield, ?Await] LexicalBinding[In, Yield, Await] : BindingIdentifier[?Yield, ?Await] Initializer[?In, ?Yield, ?Await]opt BindingPattern[?Yield, ?Await] Initializer[?In, ?Yield, ?Await]

14.3.1.1 정적 의미론: 조기 오류

LexicalDeclaration : LetOrConst BindingList ;
  • BindingList 의 BoundNames 목록에 "let" 이 포함되면 Syntax Error.
  • BindingList 의 BoundNames 목록에 중복 항목이 있으면 Syntax Error.
LexicalBinding : BindingIdentifier Initializeropt

14.3.1.2 런타임 의미론: 평가

LexicalDeclaration : LetOrConst BindingList ;
  1. BindingList 평가를 ? 로 수행.
  2. empty 반환.
BindingList : BindingList , LexicalBinding
  1. BindingList 평가를 ? 로 수행.
  2. LexicalBinding 평가 결과를 ? 로 반환.
LexicalBinding : BindingIdentifier
  1. lhs 를 ! ResolveBinding(StringValue of BindingIdentifier) 로 둔다.
  2. InitializeReferencedBinding(lhs, undefined) 수행.
  3. empty 반환.
Note

정적 의미론 규칙은 이 형태의 LexicalBindingconst 선언에서는 발생하지 않음을 보장한다.

LexicalBinding : BindingIdentifier Initializer
  1. bindingIdBindingIdentifier 의 StringValue 로 둔다.
  2. lhs 를 ! ResolveBinding(bindingId) 로 둔다.
  3. IsAnonymousFunctionDefinition(Initializer) 이 true 이면
    1. valueInitializer 의 NamedEvaluation(bindingId) 결과 (?) 로 둔다.
  4. 그렇지 않으면
    1. rhsInitializer 평가 결과 (?) 로 둔다.
    2. value 를 ? GetValue(rhs) 로 둔다.
  5. InitializeReferencedBinding(lhs, value) 수행.
  6. empty 반환.
LexicalBinding : BindingPattern Initializer
  1. rhsInitializer 평가 결과 (?) 로 둔다.
  2. value 를 ? GetValue(rhs) 로 둔다.
  3. env 를 실행 중 실행 컨텍스트의 LexicalEnvironment 로 둔다.
  4. BindingPattern 의 BindingInitialization(value, env) 결과를 ? 로 반환.

14.3.2 Variable Statement

Note

var 문은 실행 중인 실행 컨텍스트의 VariableEnvironment 에 스코프를 가지는 변수를 선언한다. Var 변수는 Environment Record 가 인스턴스화될 때 생성되며 생성과 동시에 undefined 로 초기화된다. 하나의 VariableEnvironment 스코프 내에서는 동일 BindingIdentifier 가 여러 VariableDeclaration 에 나타날 수 있으나 그것들은 하나의 변수만을 정의한다. Initializer 를 가진 VariableDeclaration 으로 정의된 변수는 선언이 실행될 때 InitializerAssignmentExpression 결과 값이 할당되며, 생성 시점이 아니다.

Syntax

VariableStatement[Yield, Await] : var VariableDeclarationList[+In, ?Yield, ?Await] ; VariableDeclarationList[In, Yield, Await] : VariableDeclaration[?In, ?Yield, ?Await] VariableDeclarationList[?In, ?Yield, ?Await] , VariableDeclaration[?In, ?Yield, ?Await] VariableDeclaration[In, Yield, Await] : BindingIdentifier[?Yield, ?Await] Initializer[?In, ?Yield, ?Await]opt BindingPattern[?Yield, ?Await] Initializer[?In, ?Yield, ?Await]

14.3.2.1 런타임 의미론: 평가

VariableStatement : var VariableDeclarationList ;
  1. VariableDeclarationList 평가를 ? 로 수행.
  2. empty 반환.
VariableDeclarationList : VariableDeclarationList , VariableDeclaration
  1. VariableDeclarationList 평가를 ? 로 수행.
  2. VariableDeclaration 평가 결과를 ? 로 반환.
VariableDeclaration : BindingIdentifier
  1. empty 반환.
VariableDeclaration : BindingIdentifier Initializer
  1. bindingIdBindingIdentifier 의 StringValue 로 둔다.
  2. lhs 를 ? ResolveBinding(bindingId) 로 둔다.
  3. IsAnonymousFunctionDefinition(Initializer) 이 true 이면
    1. valueInitializer 의 NamedEvaluation(bindingId) 결과 (?) 로 둔다.
  4. 그렇지 않으면
    1. rhsInitializer 평가 결과 (?) 로 둔다.
    2. value 를 ? GetValue(rhs) 로 둔다.
  5. PutValue(lhs, value) 수행.
  6. empty 반환.
Note

VariableDeclaration 이 with 문 내부에 중첩되어 있고 그 BindingIdentifier 가 with 문 Object Environment Record 의 바인딩 객체의 프로퍼티 이름과 같다면, 단계 5 는 식별자의 VariableEnvironment 바인딩 대신 그 프로퍼티에 value 를 할당한다.

VariableDeclaration : BindingPattern Initializer
  1. rhsInitializer 평가 결과 (?) 로 둔다.
  2. rVal 를 ? GetValue(rhs) 로 둔다.
  3. BindingPattern 의 BindingInitialization(rVal, undefined) 결과를 ? 로 반환.

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 런타임 의미론: PropertyBindingInitialization : 정상 완료 시 프로퍼티 키 List 또는 abrupt completion

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. 바인딩된 모든 프로퍼티 이름 목록을 수집한다. It is defined piecewise over the following productions:

BindingPropertyList : BindingPropertyList , BindingProperty
  1. boundNamesBindingPropertyList 의 PropertyBindingInitialization(value, environment) 결과 (?) 로 둔다.
  2. nextNamesBindingProperty 의 PropertyBindingInitialization(value, environment) 결과 (?) 로 둔다.
  3. boundNamesnextNames 의 리스트 연결을 반환.
BindingProperty : SingleNameBinding
  1. nameSingleNameBinding 의 BoundNames 유일 요소로 둔다.
  2. SingleNameBinding 의 KeyedBindingInitialization(value, environment, name) 를 ? 로 수행.
  3. « name » 반환.
BindingProperty : PropertyName : BindingElement
  1. PPropertyName 평가 결과 (?) 로 둔다.
  2. BindingElement 의 KeyedBindingInitialization(value, environment, P) 를 ? 로 수행.
  3. « P » 반환.

14.3.3.2 런타임 의미론: RestBindingInitialization : 정상 완료 시 unused 또는 abrupt completion

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. It is defined piecewise over the following productions:

BindingRestProperty : ... BindingIdentifier
  1. lhs 를 ? ResolveBinding(StringValue of BindingIdentifier, environment) 로 둔다.
  2. restObjOrdinaryObjectCreate(%Object.prototype%) 로 둔다.
  3. CopyDataProperties(restObj, value, excludedNames) 수행.
  4. environmentundefined 이면 ? PutValue(lhs, restObj) 반환.
  5. InitializeReferencedBinding(lhs, restObj) 반환.

14.3.3.3 런타임 의미론: KeyedBindingInitialization : 정상 완료 시 unused 또는 abrupt completion

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS.

Note

environmentundefined 를 전달하면 값 할당에 PutValue 연산을 사용해야 함을 의미한다. 이는 비엄격 함수의 형식 매개변수 리스트 등의 경우이며, 그때는 동일 이름 매개변수 가능성 때문에 사전 초기화된다.

It is defined piecewise over the following productions:

BindingElement : BindingPattern Initializeropt
  1. v 를 ? GetV(value, propertyName) 로 둔다.
  2. Initializer 존재하고 vundefined 이면
    1. defaultValueInitializer 평가 결과 (?) 로 둔다.
    2. v 를 ? GetValue(defaultValue) 로 설정.
  3. BindingPattern 의 BindingInitialization(v, environment) 결과를 ? 로 반환.
SingleNameBinding : BindingIdentifier Initializeropt
  1. bindingIdBindingIdentifier 의 StringValue 로 둔다.
  2. lhs 를 ? ResolveBinding(bindingId, environment) 로 둔다.
  3. v 를 ? GetV(value, propertyName) 로 둔다.
  4. Initializer 존재하고 vundefined 이면
    1. IsAnonymousFunctionDefinition(Initializer) true 이면
      1. vInitializer 의 NamedEvaluation(bindingId) 결과 (?) 로 둔다.
    2. 아니면
      1. defaultValueInitializer 평가 결과 (?) 로 둔다.
      2. v 를 ? GetValue(defaultValue) 로 둔다.
  5. environmentundefined 이면 ? PutValue(lhs, v) 반환.
  6. InitializeReferencedBinding(lhs, v) 반환.

14.4 Empty Statement

Syntax

EmptyStatement : ;

14.4.1 런타임 의미론: 평가

EmptyStatement : ;
  1. empty 반환.

14.5 Expression Statement

Syntax

ExpressionStatement[Yield, Await] : [lookahead ∉ { {, function, async [no LineTerminator here] function, class, let [ }] Expression[+In, ?Yield, ?Await] ; Note

ExpressionStatement 는 U+007B (LEFT CURLY BRACKET) 으로 시작할 수 없는데, 이는 Block 과의 모호성을 피하기 위해서이다. 또한 function 또는 class 로 시작할 수 없는데 그러면 FunctionDeclaration, GeneratorDeclaration, ClassDeclaration 과 모호하기 때문이다. async function 으로 시작할 수 없는 이유는 AsyncFunctionDeclaration 또는 AsyncGeneratorDeclaration 과 모호하기 때문이다. let [ 두 토큰 시퀀스로 시작할 수 없는 이유는 첫 LexicalBindingArrayBindingPatternlet LexicalDeclaration 과 모호하기 때문이다.

14.5.1 Runtime Semantics: Evaluation

ExpressionStatement : Expression ;
  1. exprRefExpression 평가 결과 (?) 로 둔다.
  2. GetValue(exprRef) 반환.

14.6 if

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 제한 [lookahead ≠ else] 는 고전적인 “dangling else” 문제를 통상 방식으로 해결한다. 즉 어떤 else 가 어느 if 와 연관될지 모호할 때 가장 안쪽(가장 가까운)의 if 와 결합된다.

14.6.1 정적 의미론: 조기 오류

IfStatement : if ( Expression ) Statement else Statement
  • 첫 번째 Statement 에 대해 IsLabelledFunction(...) 이 true 이면 Syntax Error.
  • 두 번째 Statement 에 대해 IsLabelledFunction(...) 이 true 이면 Syntax Error.
IfStatement : if ( Expression ) Statement
  • Statement 에 대해 IsLabelledFunction(...) 이 true 이면 Syntax Error.
Note

B.3.1 에 명시된 확장이 구현된 경우에만 이 규칙을 적용하면 된다.

14.6.2 런타임 의미론: 평가

IfStatement : if ( Expression ) Statement else Statement
  1. exprRefExpression 평가 결과 (?) 로 둔다.
  2. exprValueToBoolean(? GetValue(exprRef)) 로 둔다.
  3. exprValuetrue 이면
    1. stmtCompletion 를 첫 번째 Statement 평가의 Completion 으로 둔다.
  4. 그렇지 않으면
    1. stmtCompletion 를 두 번째 Statement 평가의 Completion 으로 둔다.
  5. UpdateEmpty(stmtCompletion, undefined) 반환.
IfStatement : if ( Expression ) Statement
  1. exprRefExpression 평가 결과 (?) 로 둔다.
  2. exprValueToBoolean(? GetValue(exprRef)) 로 둔다.
  3. exprValuefalse 이면
    1. undefined 반환.
  4. 그렇지 않으면
    1. stmtCompletionStatement 평가의 Completion 으로 둔다.
    2. 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 의미론

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. completion 이 정상 completion 이면 true 반환.
  2. completioncontinue completion 이 아니면 false 반환.
  3. completion.[[Target]]empty 이면 true 반환.
  4. labelSetcompletion.[[Target]] 을 포함하면 true 반환.
  5. false 반환.
Note

IterationStatementStatement 부분 내부에서는 ContinueStatement 로 새 반복을 시작할 수 있다.

14.7.1.2 런타임 의미론: LoopEvaluation : 정상 완료 시 ECMAScript 언어 값 또는 abrupt completion

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. It is defined piecewise over the following productions:

IterationStatement : DoWhileStatement
  1. DoWhileStatement 의 DoWhileLoopEvaluation(labelSet) 결과를 ? 로 반환.
IterationStatement : WhileStatement
  1. WhileStatement 의 WhileLoopEvaluation(labelSet) 결과를 ? 로 반환.
IterationStatement : ForStatement
  1. ForStatement 의 ForLoopEvaluation(labelSet) 결과를 ? 로 반환.
IterationStatement : ForInOfStatement
  1. ForInOfStatement 의 ForIn/OfLoopEvaluation(labelSet) 결과를 ? 로 반환.

14.7.2 do-while

Syntax

DoWhileStatement[Yield, Await, Return] : do Statement[?Yield, ?Await, ?Return] while ( Expression[+In, ?Yield, ?Await] ) ;

14.7.2.1 정적 의미론: 조기 오류

DoWhileStatement : do Statement while ( Expression ) ;
  • IsLabelledFunction(Statement) 이 true 이면 Syntax Error.
Note

B.3.1 확장이 구현된 경우에만 적용.

14.7.2.2 런타임 의미론: DoWhileLoopEvaluation : 정상 완료 시 ECMAScript 값 또는 abrupt completion

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. It is defined piecewise over the following productions:

DoWhileStatement : do Statement while ( Expression ) ;
  1. Vundefined 로 둔다.
  2. 반복,
    1. stmtResultStatement 평가 Completion 으로 둔다.
    2. LoopContinues(stmtResult, labelSet) 가 false 이면 ? UpdateEmpty(stmtResult, V) 반환.
    3. stmtResult.[[Value]]empty 가 아니면 V 를 그 값으로 설정.
    4. exprRefExpression 평가 결과 (?) 로 둔다.
    5. exprValue 를 ? GetValue(exprRef) 로 둔다.
    6. ToBoolean(exprValue) 가 false 이면 V 반환.

14.7.3 while

Syntax

WhileStatement[Yield, Await, Return] : while ( Expression[+In, ?Yield, ?Await] ) Statement[?Yield, ?Await, ?Return]

14.7.3.1 정적 의미론: 조기 오류

WhileStatement : while ( Expression ) Statement
  • IsLabelledFunction(Statement) 이 true 이면 Syntax Error.
Note

B.3.1 확장이 구현된 경우에만 적용.

14.7.3.2 런타임 의미론: WhileLoopEvaluation : 정상 완료 시 ECMAScript 값 또는 abrupt completion

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. It is defined piecewise over the following productions:

WhileStatement : while ( Expression ) Statement
  1. Vundefined 로 둔다.
  2. 반복,
    1. exprRefExpression 평가 결과 (?) 로 둔다.
    2. exprValue 를 ? GetValue(exprRef) 로 둔다.
    3. ToBoolean(exprValue) 가 false 이면 V 반환.
    4. stmtResultStatement 평가 Completion 으로 둔다.
    5. LoopContinues(stmtResult, labelSet) 가 false 이면 ? UpdateEmpty(stmtResult, V) 반환.
    6. stmtResult.[[Value]]empty 가 아니면 V 갱신.

14.7.4 for

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 정적 의미론: 조기 오류

ForStatement : for ( Expressionopt ; Expressionopt ; Expressionopt ) Statement for ( var VariableDeclarationList ; Expressionopt ; Expressionopt ) Statement for ( LexicalDeclaration Expressionopt ; Expressionopt ) Statement
  • IsLabelledFunction(Statement) 이 true 이면 Syntax Error.
Note

B.3.1 확장이 구현된 경우에만 적용.

ForStatement : for ( LexicalDeclaration Expressionopt ; Expressionopt ) Statement

14.7.4.2 런타임 의미론: ForLoopEvaluation : 정상 완료 시 ECMAScript 값 또는 abrupt completion

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. It is defined piecewise over the following productions:

ForStatement : for ( Expressionopt ; Expressionopt ; Expressionopt ) Statement
  1. 첫 번째 Expression 존재하면
    1. exprRef 를 그 평가 결과 (?) 로 둔다.
    2. GetValue(exprRef) 수행.
  2. 두 번째 Expression 존재하면 test 를 그 Expression 으로, 아니면 empty.
  3. 세 번째 Expression 존재하면 increment 를 그 Expression 으로, 아니면 empty.
  4. ForBodyEvaluation(test, increment, Statement, « », labelSet) 결과를 ? 로 반환.
ForStatement : for ( var VariableDeclarationList ; Expressionopt ; Expressionopt ) Statement
  1. VariableDeclarationList 평가를 ? 로 수행.
  2. 첫 번째 Expression 존재하면 test 를 그 Expression, 아니면 empty.
  3. 두 번째 Expression 존재하면 increment 를 그 Expression, 아니면 empty.
  4. ForBodyEvaluation(test, increment, Statement, « », labelSet) 결과를 ? 로 반환.
ForStatement : for ( LexicalDeclaration Expressionopt ; Expressionopt ) Statement
  1. oldEnv 를 실행 컨텍스트 LexicalEnvironment 로 둔다.
  2. loopEnvNewDeclarativeEnvironment(oldEnv) 로 둔다.
  3. isConstLexicalDeclaration 의 IsConstantDeclaration 으로 둔다.
  4. boundNamesLexicalDeclaration 의 BoundNames 로 둔다.
  5. dnboundNames 에 대해
    1. isConsttrue 이면 ! loopEnv.CreateImmutableBinding(dn, true)
    2. 아니면 ! loopEnv.CreateMutableBinding(dn, false)
  6. 실행 컨텍스트 LexicalEnvironment 를 loopEnv 로 설정.
  7. forDclLexicalDeclaration 평가 Completion 으로 둔다.
  8. forDcl 이 abrupt 면
    1. LexicalEnvironment 를 oldEnv 로 복구.
    2. forDcl 반환.
  9. isConstfalse 이면 perIterationLets = boundNames; 아니면 새 빈 List.
  10. 첫 번째 Expression 존재하면 testExpression; 아니면 empty.
  11. 두 번째 Expression 존재하면 incrementExpression; 아니면 empty.
  12. bodyResultCompletion(ForBodyEvaluation(test, increment, Statement, perIterationLets, labelSet)) 로 둔다.
  13. LexicalEnvironment 를 oldEnv 로 복구.
  14. 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 정상 완료 시 ECMAScript 값 또는 abrupt completion. It performs the following steps when called:

  1. V = undefined.
  2. CreatePerIterationEnvironment(perIterationBindings) 수행.
  3. 반복,
    1. testempty 이 아니면
      1. testRef = ? test 평가
      2. testValue = ? GetValue(testRef)
      3. ToBoolean(testValue) 가 falseV 반환.
    2. result = stmt 평가 Completion
    3. LoopContinues(result, labelSet) 가 false 면 ? UpdateEmpty(result, V) 반환.
    4. result.[[Value]]empty 아니면 V 갱신.
    5. CreatePerIterationEnvironment(perIterationBindings) 수행.
    6. incrementempty 아니면
      1. incRef = ? increment 평가
      2. GetValue(incRef) 수행.

14.7.4.4 CreatePerIterationEnvironment ( perIterationBindings )

The abstract operation CreatePerIterationEnvironment takes argument perIterationBindings (a List of Strings) and returns 정상 완료 시 unused 또는 throw completion. It performs the following steps when called:

  1. perIterationBindings 에 요소가 있으면
    1. lastIterationEnv = 실행 컨텍스트 LexicalEnvironment
    2. outer = lastIterationEnv.[[OuterEnv]]
    3. 단언: outer != null
    4. thisIterationEnv = NewDeclarativeEnvironment(outer)
    5. bnperIterationBindings 에 대해
      1. thisIterationEnv.CreateMutableBinding(bn, false)
      2. lastValue = ? lastIterationEnv.GetBindingValue(bn, true)
      3. thisIterationEnv.InitializeBinding(bn, lastValue)
    6. 실행 컨텍스트 LexicalEnvironment = thisIterationEnv
  2. unused 반환.

14.7.5 for-in, for-of, for-await-of

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] in Expression[+In, ?Yield, ?Await] ) Statement[?Yield, ?Await, ?Return] for ( ForDeclaration[?Yield, ?Await] 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] of AssignmentExpression[+In, ?Yield, ?Await] ) Statement[?Yield, ?Await, ?Return] for ( ForDeclaration[?Yield, ?Await] 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] of AssignmentExpression[+In, ?Yield, ?Await] ) Statement[?Yield, ?Await, ?Return] [+Await] for await ( ForDeclaration[?Yield, ?Await] of AssignmentExpression[+In, ?Yield, ?Await] ) Statement[?Yield, ?Await, ?Return] ForDeclaration[Yield, Await] : LetOrConst ForBinding[?Yield, ?Await] ForBinding[Yield, Await] : BindingIdentifier[?Yield, ?Await] BindingPattern[?Yield, ?Await] Note

이 절은 부록 B.3.5 에 의해 확장된다.

14.7.5.1 정적 의미론: 조기 오류

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
  • IsLabelledFunction(Statement) 이 true 이면 Syntax Error.
Note

B.3.1 확장이 구현된 경우에만 적용.

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 정적 의미론: IsDestructuring : Boolean

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. 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. ForBinding 의 IsDestructuring 반환.
ForBinding : BindingIdentifier
  1. false 반환.
ForBinding : BindingPattern
  1. true 반환.
Note

이 절은 부록 B.3.5 에 의해 확장된다.

14.7.5.3 런타임 의미론: ForDeclarationBindingInitialization : 정상 완료 시 unused 또는 abrupt completion

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS.

Note

environmentundefined 가 전달되면 PutValue 로 초기화해야 함을 의미한다. 이는 var 문 및 일부 비엄격 함수의 매개변수 리스트 경우 ( 10.2.11 참조 )에 해당한다. 그 경우 렉시컬 바인딩이 초기화자 평가 전 호이스팅·사전 초기화된다.

It is defined piecewise over the following productions:

ForDeclaration : LetOrConst ForBinding
  1. ForBinding 의 BindingInitialization(value, environment) 결과를 ? 로 반환.

14.7.5.4 런타임 의미론: ForDeclarationBindingInstantiation : unused

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. It is defined piecewise over the following productions:

ForDeclaration : LetOrConst ForBinding
  1. ForBinding 의 BoundNames 각 name 에 대해
    1. IsConstantDeclaration(LetOrConst) 이 true 이면 ! environment.CreateImmutableBinding(name, true)
    2. 아니면 ! environment.CreateMutableBinding(name, false)
  2. unused 반환.

14.7.5.5 런타임 의미론: ForInOfLoopEvaluation : 정상 완료 시 ECMAScript 값 또는 abrupt completion

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. 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(BoundNames of ForDeclaration, 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(BoundNames of ForDeclaration, 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(BoundNames of ForDeclaration, AssignmentExpression, async-iterate)
  2. ForIn/OfBodyEvaluation(ForDeclaration, Statement, keyResult, iterate, lexical-binding, labelSet, async) 반환.
Note

이 절은 부록 B.3.5 에 의해 확장된다.

14.7.5.6 ForIn/OfHeadEvaluation ( uninitializedBoundNames, expr, iterationKind )

The abstract operation ForIn/OfHeadEvaluation takes arguments uninitializedBoundNames (a List of Strings), expr (an Expression Parse Node or an AssignmentExpression Parse Node), and iterationKind (enumerate, iterate, or async-iterate) and returns 정상 완료 시 Iterator Record 또는 abrupt completion. It performs the following steps when called:

  1. oldEnv = 실행 컨텍스트 LexicalEnvironment
  2. uninitializedBoundNames 가 비어있지 않다면
    1. 단언: 중복 없음
    2. newEnv = NewDeclarativeEnvironment(oldEnv)
    3. nameuninitializedBoundNames 에 대해
      1. newEnv.CreateMutableBinding(name, false)
    4. LexicalEnvironment = newEnv
  3. exprRef = expr 평가 Completion
  4. 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. iterator = EnumerateObjectProperties(obj)
    4. nextMethod = ! GetV(iterator, "next")
    5. Iterator Record { [[Iterator]]: iterator, [[NextMethod]]: nextMethod, [[Done]]: false } 반환.
  7. 그렇지 않으면
    1. 단언: iterate 또는 async-iterate
    2. iteratorKind = (iterationKindasync-iterate 이면 async 아니면 sync)
    3. 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 정상 완료 시 ECMAScript 값 또는 abrupt completion. It performs the following steps when called:

  1. iteratorKind 가 없으면 sync 로 설정.
  2. oldEnv = 실행 컨텍스트 LexicalEnvironment
  3. V = undefined
  4. destructuring = IsDestructuring(lhs)
  5. destructuring true 그리고 lhsKind = assignment 이면
    1. 단언: lhsLeftHandSideExpression
    2. assignmentPattern = lhs 가 커버하는 AssignmentPattern
  6. 반복,
    1. nextResult = ? Call(iteratorRecord.[[NextMethod]], iteratorRecord.[[Iterator]])
    2. iteratorKind = async 이면 nextResult = ? Await(nextResult)
    3. nextResult 가 Object 아니면 TypeError throw
    4. done = ? IteratorComplete(nextResult)
    5. done true 이면 V 반환
    6. nextValue = ? IteratorValue(nextResult)
    7. lhsKind ∈ {assignment, var-binding} 이면
      1. destructuring true 이면
        1. lhsKind = assignment 이면
          1. status = Completion(DestructuringAssignmentEvaluation(assignmentPattern, nextValue))
        2. 아니면 (var-binding)
          1. 단언: lhsForBinding
          2. status = Completion(BindingInitialization(lhs, nextValue, undefined))
      2. destructuring false 이면
        1. lhsRef = Completion(Evaluation(lhs))
        2. lhsKind = assignment 이고 AssignmentTargetType(lhs) = web-compat 이면 ReferenceError throw
        3. lhsRef 가 abrupt 이면 status = lhsRef
        4. 아니면 status = Completion(PutValue(lhsRef.[[Value]], nextValue))
    8. 그렇지 않으면
      1. 단언: lhsKind = lexical-binding
      2. 단언: lhsForDeclaration
      3. iterationEnv = NewDeclarativeEnvironment(oldEnv)
      4. ForDeclarationBindingInstantiation(lhs, iterationEnv) 수행
      5. LexicalEnvironment = iterationEnv
      6. destructuring true 이면
        1. status = Completion(ForDeclarationBindingInitialization(lhs, nextValue, iterationEnv))
      7. 아니면
        1. 단언: 단일 이름 바인딩
        2. lhsName = BoundNames(lhs) 의 유일 요소
        3. lhsRef = ! ResolveBinding(lhsName)
        4. status = Completion(InitializeReferencedBinding(lhsRef, nextValue))
    9. status abrupt 이면
      1. LexicalEnvironment = oldEnv
      2. iteratorKind = async 이면 ? AsyncIteratorClose(iteratorRecord, status) 반환
      3. iterationKind = enumerate 이면 ? status 반환
      4. 아니면 (iterate)
        1. IteratorClose(iteratorRecord, status) 반환
    10. result = Completion(Evaluation(stmt))
    11. LexicalEnvironment = oldEnv
    12. LoopContinues(result, labelSet) false 이면
      1. iterationKind = enumerate 이면 ? UpdateEmpty(result, V) 반환
      2. 아니면 (iterate)
        1. status = Completion(UpdateEmpty(result, V))
        2. iteratorKind = async 이면 ? AsyncIteratorClose(iteratorRecord, status) 반환
        3. IteratorClose(iteratorRecord, status) 반환
    13. result.[[Value]]empty 아니면 V 갱신

14.7.5.8 런타임 의미론: 평가

BindingIdentifier : Identifier yield await
  1. bindingIdBindingIdentifier 의 StringValue 로 둔다.
  2. ResolveBinding(bindingId) 반환.

14.7.5.9 EnumerateObjectProperties ( O )

The abstract operation EnumerateObjectProperties takes argument O (an Object) and returns iterator 객체. It performs the following steps when called:

  1. O 의 열거 가능한 프로퍼티 중 String 키를 순회하는 next 메서드를 가진 iterator 객체를 반환한다. 이 객체는 ECMAScript 코드에서 직접 접근 불가하다. 순서 및 메커니즘은 아래 규칙을 준수해야 한다.

iteratorthrow, return 메서드는 null 이며 호출되지 않는다. next 메서드는 프로퍼티 키 반환 여부를 결정한다. 반환 키에는 Symbol 키 미포함. 대상 객체의 프로퍼티는 열거 중 삭제될 수 있으며 삭제된 프로퍼티는 무시된다. 열거 중 추가된 프로퍼티는 반드시 처리된다고 보장되지 않는다. 한 프로퍼티 이름은 하나의 열거에서 최대 한 번만 반환된다.

대상 객체 프로퍼티 열거에는 프로토타입 사슬의 프로퍼티도 재귀적으로 포함되지만, 이미 반환된 이름과 동일한 프로토타입 프로퍼티는 무시된다. [[Enumerable]] 값 비교는 중복 판단에 사용되지 않는다. 프로토타입 객체의 열거 가능한 이름은 그 프로토타입을 인수로 EnumerateObjectProperties 를 호출하여 얻어야 한다. 대상 객체의 own keys 는 [[OwnPropertyKeys]] 내부 메서드, 속성 서술자는 [[GetOwnProperty]] 내부 메서드를 통해 얻는다.

또한 O 나 그 프로토타입 체인 어느 객체도 Proxy/TypedArray/module namespace/exotic (구현 정의) 객체가 아니라면, 다음 사건 중 하나가 발생할 때까지 iteratorCreateForInIterator(O) 가 준 iterator 처럼 동작해야 한다:

  • O 또는 프로토타입 체인 객체의 [[Prototype]] 값 변경
  • O 또는 프로토타입 체인 객체에서 프로퍼티 제거
  • 프로토타입 체인 객체에 프로퍼티 추가
  • O 또는 체인 객체 프로퍼티의 [[Enumerable]] 값 변경
Note 1

구현은 14.7.5.10.2.1 알고리즘을 직접 구현할 필요는 없다. 위 제약 위반 전까지 동등 동작을 유지하는 임의 구현 가능.

다음은 이러한 규칙을 만족하는 ECMAScript generator 함수의 예시(정보적):

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
구현이 CreateForInIterator 와 일치할 필요가 없는 exotic 객체 목록은 역사적으로 구현별 차이가 있었던 경우이며 그 외에는 합의된 경우이다.

14.7.5.10 For-In Iterator 객체

For-In Iterator 는 특정 객체에 대한 특정 반복을 나타내는 객체이다. ECMAScript 코드에서 직접 접근할 수 없으며 EnumerateObjectProperties 동작 설명용이다.

14.7.5.10.1 CreateForInIterator ( object )

The abstract operation CreateForInIterator takes argument object (an Object) and returns For-In Iterator. object 의 own 및 상속된 열거 가능한 문자열 프로퍼티를 특정 순서로 순회하는 For-In Iterator 를 생성한다. It performs the following steps when called:

  1. iterator = OrdinaryObjectCreate(%ForInIteratorPrototype%, « [[Object]], [[ObjectWasVisited]], [[VisitedKeys]], [[RemainingKeys]] »)
  2. iterator.[[Object]] = object
  3. iterator.[[ObjectWasVisited]] = false
  4. iterator.[[VisitedKeys]] = 새 빈 List
  5. iterator.[[RemainingKeys]] = 새 빈 List
  6. iterator 반환

14.7.5.10.2 %ForInIteratorPrototype% 객체

%ForInIteratorPrototype% 객체:

  • 모든 For-In Iterator 객체가 상속하는 프로퍼티를 가진다.
  • ordinary object 이다.
  • [[Prototype]] 슬롯 값은 %Iterator.prototype%.
  • ECMAScript 코드에서 직접 접근할 수 없다.
  • 다음 프로퍼티를 가진다:

14.7.5.10.2.1 %ForInIteratorPrototype%.next ( )

  1. Othis 값으로 둔다.
  2. 단언: O 는 Object.
  3. 단언: OFor-In Iterator 인스턴스 내부 슬롯을 모두 가진다 (14.7.5.10.3).
  4. object = O.[[Object]]
  5. 반복,
    1. O.[[ObjectWasVisited]] false 이면
      1. keys = ? object.[[OwnPropertyKeys]]()
      2. keykeys 에 대해
        1. key 가 String 이면 O.[[RemainingKeys]] 에 추가
      3. O.[[ObjectWasVisited]] = true
    2. O.[[RemainingKeys]] 비어있지 않은 동안 반복
      1. r = 첫 요소
      2. 첫 요소 제거
      3. O.[[VisitedKeys]]r 없으면
        1. desc = ? object.[[GetOwnProperty]](r)
        2. desc != undefined 이면
          1. rO.[[VisitedKeys]] 에 추가
          2. desc.[[Enumerable]] true 이면 CreateIteratorResultObject(r, false) 반환
    3. object = ? object.[[GetPrototypeOf]]()
    4. O.[[Object]] = object
    5. O.[[ObjectWasVisited]] = false
    6. objectnull 이면 CreateIteratorResultObject(undefined, true) 반환

14.7.5.10.3 For-In Iterator 인스턴스의 프로퍼티

For-In Iterator 인스턴스는 %ForInIteratorPrototype% 을 상속하는 ordinary 객체이다. 인스턴스는 Table 36 의 내부 슬롯을 가진다.

Table 36: For-In Iterator 인스턴스의 내부 슬롯
Internal Slot Type 설명
[[Object]] an Object 현재 프로퍼티를 열거 중인 객체.
[[ObjectWasVisited]] a Boolean iterator[[OwnPropertyKeys]] 를 호출했으면 true, 아니면 false.
[[VisitedKeys]] a List of Strings 지금까지 방출된 값들.
[[RemainingKeys]] a List of Strings 현재 객체에서 아직 방출되지 않은 값들 (프로토타입 열거 전).

14.8 continue

Syntax

ContinueStatement[Yield, Await] : continue ; continue [no LineTerminator here] LabelIdentifier[?Yield, ?Await] ;

14.8.1 정적 의미론: 조기 오류

ContinueStatement : continue ; continue LabelIdentifier ;
  • ContinueStatement 가 (함수나 static 초기화 블록 경계를 넘지 않고) 직접 또는 간접적으로 IterationStatement 내에 중첩되지 않았다면 Syntax Error.

14.8.2 런타임 의미론: 평가

ContinueStatement : continue ;
  1. Completion Record { [[Type]]: continue, [[Value]]: empty, [[Target]]: empty } 반환.
ContinueStatement : continue LabelIdentifier ;
  1. label = LabelIdentifier 의 StringValue
  2. Completion Record { [[Type]]: continue, [[Value]]: empty, [[Target]]: label } 반환.

14.9 break

Syntax

BreakStatement[Yield, Await] : break ; break [no LineTerminator here] LabelIdentifier[?Yield, ?Await] ;

14.9.1 정적 의미론: 조기 오류

BreakStatement : break ;

14.9.2 런타임 의미론: 평가

BreakStatement : break ;
  1. Completion Record { [[Type]]: break, [[Value]]: empty, [[Target]]: empty } 반환.
BreakStatement : break LabelIdentifier ;
  1. label = LabelIdentifier 의 StringValue
  2. Completion Record { [[Type]]: break, [[Value]]: empty, [[Target]]: label } 반환.

14.10 return

Syntax

ReturnStatement[Yield, Await] : return ; return [no LineTerminator here] Expression[+In, ?Yield, ?Await] ; Note

return 문은 함수를 종료하고(대부분 경우) 호출자에게 값을 반환한다. Expression 이 없으면 반환 값은 undefined. 있으면 그 표현식의 값. return 문이 주변 컨텍스트에 따라 실제로 호출자에게 값을 반환하지 않을 수도 있다. 예: try 블록 내 returnCompletion Recordfinally 블록 평가 중 다른 Completion Record 로 대체될 수 있다.

14.10.1 런타임 의미론: 평가

ReturnStatement : return ;
  1. ReturnCompletion(undefined) 반환.
ReturnStatement : return Expression ;
  1. exprRef = Expression 평가 결과 (?)
  2. exprValue = ? GetValue(exprRef)
  3. GetGeneratorKind() 가 async 이면 exprValue = ? Await(exprValue)
  4. ReturnCompletion(exprValue) 반환.
Legacy

14.11 with

Note 1

레거시 with 문 사용은 새로운 ECMAScript 코드에서 권장되지 않는다. 엄격/비엄격 모두 허용되는 구조 분해 할당 등의 대안을 고려하라.

Syntax

WithStatement[Yield, Await, Return] : with ( Expression[+In, ?Yield, ?Await] ) Statement[?Yield, ?Await, ?Return] Note 2

with 문은 계산된 객체에 대한 Object Environment Record 를 실행 컨텍스트의 렉시컬 환경에 추가한 후 그 확장된 환경으로 문을 실행하고 마지막에 원래 환경을 복구한다.

14.11.1 정적 의미론: 조기 오류

WithStatement : with ( Expression ) Statement
  • IsStrict(this production) true 이면 Syntax Error.
  • IsLabelledFunction(Statement) true 이면 Syntax Error.
Note

두 번째 규칙은 B.3.1 확장이 구현된 경우에만 적용.

14.11.2 런타임 의미론: 평가

WithStatement : with ( Expression ) Statement
  1. val = Expression 평가 결과 (?)
  2. obj = ? ToObject(? GetValue(val))
  3. oldEnv = 현재 LexicalEnvironment
  4. newEnv = NewObjectEnvironment(obj, true, oldEnv)
  5. LexicalEnvironment = newEnv
  6. C = Statement 평가 Completion
  7. LexicalEnvironment = oldEnv
  8. UpdateEmpty(C, undefined) 반환
Note

임의의 경로로 embedded Statement 를 빠져나와도(정상/abrupt) LexicalEnvironment 는 항상 복원된다.

14.12 switch

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 정적 의미론: 조기 오류

SwitchStatement : switch ( Expression ) CaseBlock

14.12.2 런타임 의미론: CaseBlockEvaluation : 정상 완료 시 ECMAScript 값 또는 abrupt completion

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. It is defined piecewise over the following productions:

CaseBlock : { }
  1. undefined 반환.
CaseBlock : { CaseClauses }
  1. V = undefined
  2. A = CaseClausesCaseClause 리스트 (소스 순서)
  3. found = false
  4. CA 에 대해
    1. found false 이면 found = ? CaseClauseIsSelected(C, input)
    2. found true 이면
      1. R = C 평가 Completion
      2. R.[[Value]]empty 아니면 V 갱신
      3. R abrupt 이면 ? UpdateEmpty(R, V) 반환
  5. V 반환.
CaseBlock : { CaseClausesopt DefaultClause CaseClausesopt }
  1. V = undefined
  2. CaseClauses 존재하면 A = 그 CaseClause 리스트; 아니면 새 빈 List
  3. found = false
  4. CA 에 대해
    1. found false 이면 found = ? CaseClauseIsSelected(C, input)
    2. found true 이면
      1. R = C 평가 Completion
      2. R.[[Value]] empty 아니면 V 갱신
      3. R abrupt 이면 ? UpdateEmpty(R, V) 반환
  5. foundInB = false
  6. 두 번째 CaseClauses 존재하면 B = 그 리스트; 아니면 빈 List
  7. found false 이면
    1. CB 에 대해
      1. foundInB false 이면 foundInB = ? CaseClauseIsSelected(C, input)
      2. foundInB true 이면
        1. R = C 평가 Completion
        2. R.[[Value]] empty 아니면 V 갱신
        3. R abrupt 이면 ? UpdateEmpty(R, V) 반환
  8. foundInB true 이면 V 반환
  9. defaultR = DefaultClause 평가 Completion
  10. defaultR.[[Value]] empty 아니면 V 갱신
  11. defaultR abrupt 이면 ? UpdateEmpty(defaultR, V) 반환
  12. (두 번째 CaseClauses 전체 재순회)
  13. CB 에 대해
    1. R = C 평가 Completion
    2. R.[[Value]] empty 아니면 V 갱신
    3. R abrupt 이면 ? UpdateEmpty(R, V) 반환
  14. V 반환

14.12.3 CaseClauseIsSelected ( C, input )

The abstract operation CaseClauseIsSelected takes arguments C (a CaseClause Parse Node) and input (an ECMAScript language value) and returns 정상 완료 시 Boolean 또는 abrupt completion. Cinput 과 일치하는지 결정한다. It performs the following steps when called:

  1. 단언: C CaseClause : case Expression : StatementListopt 인스턴스.
  2. exprRef = CExpression 평가 결과 (?)
  3. clauseSelector = ? GetValue(exprRef)
  4. IsStrictlyEqual(input, clauseSelector) 반환.
Note

이 연산은 CStatementList (있다면)를 실행하지 않는다. CaseBlock 알고리즘은 반환값을 사용해 어느 StatementList 부터 실행할지 결정한다.

14.12.4 런타임 의미론: 평가

SwitchStatement : switch ( Expression ) CaseBlock
  1. exprRef = Expression 평가 결과 (?)
  2. switchValue = ? GetValue(exprRef)
  3. oldEnv = 현재 LexicalEnvironment
  4. blockEnv = NewDeclarativeEnvironment(oldEnv)
  5. BlockDeclarationInstantiation(CaseBlock, blockEnv) 수행
  6. LexicalEnvironment = blockEnv
  7. R = CaseBlockEvaluation(CaseBlock, switchValue) 의 Completion
  8. LexicalEnvironment = oldEnv
  9. R 반환
Note

SwitchStatement 를 어떻게 빠져나오든 LexicalEnvironment 는 복구된다.

CaseClause : case Expression :
  1. empty 반환.
CaseClause : case Expression : StatementList
  1. StatementList 평가 결과를 ? 로 반환.
DefaultClause : default :
  1. empty 반환.
DefaultClause : default : StatementList
  1. StatementList 평가 결과를 ? 로 반환.

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 는 레이블로 접두될 수 있다. 레이블 문은 레이블된 break/continue 와 함께 사용된다. ECMAScript 에는 goto 가 없다. StatementLabelledStatement 의 일부가 될 수 있고 이것이 또 다른 LabelledStatement 의 일부가 되는 식으로 중첩될 수 있다. 이렇게 도입된 레이블 집합을 개별 문 의미론에서 “current label set” 이라 부른다.

14.13.1 정적 의미론: 조기 오류

LabelledItem : FunctionDeclaration
  • 이 생성물에 매칭되는 소스 텍스트가 있다면 Syntax Error — 단, 그 소스가 비엄격 코드이고 호스트레이블된 함수 선언 를 지원하면 예외.

14.13.2 정적 의미론: IsLabelledFunction ( stmt: a Statement Parse Node, ): Boolean

The abstract operation UNKNOWN takes UNPARSEABLE ARGUMENTS. It performs the following steps when called:

  1. stmtLabelledStatement 아니면 false 반환.
  2. item = stmtLabelledItem
  3. item LabelledItem : FunctionDeclaration 이면 true 반환.
  4. subStmt = itemStatement
  5. IsLabelledFunction(subStmt) 반환.

14.13.3 런타임 의미론: 평가

LabelledStatement : LabelIdentifier : LabelledItem
  1. LabelledStatement 의 LabelledEvaluation(« ») 결과를 ? 로 반환.

14.13.4 런타임 의미론: LabelledEvaluation : 정상 완료 시 ECMAScript 값 또는 empty, 또는 abrupt completion

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. It is defined piecewise over the following productions:

BreakableStatement : IterationStatement
  1. stmtResult = Completion(LoopEvaluation(IterationStatement, labelSet))
  2. stmtResultbreak completion 이고 stmtResult.[[Target]]empty 이면
    1. stmtResult.[[Value]]empty 이면 stmtResult = NormalCompletion(undefined)
    2. 아니면 stmtResult = NormalCompletion(stmtResult.[[Value]])
  3. stmtResult 반환
BreakableStatement : SwitchStatement
  1. stmtResult = Completion(Evaluation(SwitchStatement))
  2. stmtResultbreak completion 이고 stmtResult.[[Target]]empty 이면
    1. stmtResult.[[Value]] empty 이면 stmtResult = NormalCompletion(undefined) 아니면 NormalCompletion(stmtResult.[[Value]])
  3. stmtResult 반환
Note 1

BreakableStatement 는 레이블 없는 BreakStatement 로 빠져나올 수 있는 문이다.

LabelledStatement : LabelIdentifier : LabelledItem
  1. label = LabelIdentifier 의 StringValue
  2. newLabelSet = labelSet ⧺ « label »
  3. stmtResult = Completion(LabelledEvaluation(LabelledItem, newLabelSet))
  4. stmtResultbreak completion 이고 stmtResult.[[Target]] = label 이면
    1. stmtResult = NormalCompletion(stmtResult.[[Value]])
  5. stmtResult 반환
LabelledItem : FunctionDeclaration
  1. FunctionDeclaration 평가 결과를 ? 로 반환.
Statement : BlockStatement VariableStatement EmptyStatement ExpressionStatement IfStatement ContinueStatement BreakStatement ReturnStatement WithStatement ThrowStatement TryStatement DebuggerStatement
  1. Statement 평가 결과를 ? 로 반환.
Note 2

Statement 의 production 중 LabelledEvaluation 에 특별한 의미론을 갖는 것은 BreakableStatementLabelledStatement 두 가지뿐이다.

14.14 throw

Syntax

ThrowStatement[Yield, Await] : throw [no LineTerminator here] Expression[+In, ?Yield, ?Await] ;

14.14.1 런타임 의미론: 평가

ThrowStatement : throw Expression ;
  1. exprRef = Expression 평가 결과 (?)
  2. exprValue = ? GetValue(exprRef)
  3. ThrowCompletion(exprValue) 반환.

14.15 try

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 문은 런타임 오류나 throw 등 예외 상황이 발생할 수 있는 코드 블록을 감싼다. catch 절은 예외 처리 코드를 제공한다. catch 절이 예외를 잡으면 CatchParameter 에 그 예외 값이 바인딩된다.

14.15.1 정적 의미론: 조기 오류

Catch : catch ( CatchParameter ) Block

14.15.2 런타임 의미론: CatchClauseEvaluation : 정상 완료 시 ECMAScript 값 또는 empty, 또는 abrupt completion

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. It is defined piecewise over the following productions:

Catch : catch ( CatchParameter ) Block
  1. oldEnv = 현재 LexicalEnvironment
  2. catchEnv = NewDeclarativeEnvironment(oldEnv)
  3. CatchParameter 의 BoundNames 각 argName 에 대해
    1. catchEnv.CreateMutableBinding(argName, false)
  4. LexicalEnvironment = catchEnv
  5. status = Completion(BindingInitialization(CatchParameter, thrownValue, catchEnv))
  6. status abrupt 이면
    1. LexicalEnvironment = oldEnv
    2. status 반환
  7. B = Block 평가 Completion
  8. LexicalEnvironment = oldEnv
  9. B 반환
Catch : catch Block
  1. Block 평가 결과를 ? 로 반환.
Note

Block 을 어떻게 빠져나오든 LexicalEnvironment 는 복구된다.

14.15.3 런타임 의미론: 평가

TryStatement : try Block Catch
  1. B = Block 평가 Completion
  2. Bthrow completion 이면 C = Completion(CatchClauseEvaluation(Catch, B.[[Value]])); 아니면 C = B
  3. UpdateEmpty(C, undefined) 반환
TryStatement : try Block Finally
  1. B = Block 평가 Completion
  2. F = Finally 평가 Completion
  3. Fnormal completion 이면 F = B
  4. UpdateEmpty(F, undefined) 반환
TryStatement : try Block Catch Finally
  1. B = Block 평가 Completion
  2. Bthrow completion 이면 C = Completion(CatchClauseEvaluation(Catch, B.[[Value]])); 아니면 C = B
  3. F = Finally 평가 Completion
  4. Fnormal completion 이면 F = C
  5. UpdateEmpty(F, undefined) 반환

14.16 debugger

Syntax

DebuggerStatement : debugger ;

14.16.1 런타임 의미론: 평가

Note

DebuggerStatement 를 평가하면 구현이 디버거 실행 시 중단점을 걸 수 있게 할 수 있다. 디버거가 없거나 비활성화된 경우 관찰 가능한 효과가 없다.

DebuggerStatement : debugger ;
  1. 구현 정의 디버깅 기능이 활성화되어 있으면
    1. 구현 정의 디버깅 동작 수행.
    2. 구현 정의 Completion Record 반환.
  2. 그렇지 않으면
    1. empty 반환.

15 ECMAScript 언어: 함수와 클래스(Functions and Classes)

Note

다양한 ECMAScript 언어 요소는 ECMAScript 함수 객체(10.2)를 생성한다. 그러한 함수들의 평가(evaluation)는 그들의 [[Call]] 내부 메서드(10.2.1) 실행으로 시작한다.

15.1 매개변수 목록(Parameter Lists)

Syntax

UniqueFormalParameters[Yield, Await] : FormalParameters[?Yield, ?Await] FormalParameters[Yield, Await] : [empty] FunctionRestParameter[?Yield, ?Await] FormalParameterList[?Yield, ?Await] FormalParameterList[?Yield, ?Await] , FormalParameterList[?Yield, ?Await] , FunctionRestParameter[?Yield, ?Await] FormalParameterList[Yield, Await] : FormalParameter[?Yield, ?Await] FormalParameterList[?Yield, ?Await] , FormalParameter[?Yield, ?Await] FunctionRestParameter[Yield, Await] : BindingRestElement[?Yield, ?Await] FormalParameter[Yield, Await] : BindingElement[?Yield, ?Await]

15.1.1 정적 의미론: 조기 오류(Static Semantics: Early Errors)

UniqueFormalParameters : FormalParameters
  • FormalParameters 의 BoundNames 에 중복 요소가 있으면 Syntax Error 이다.
FormalParameters : FormalParameterList Note

같은 BindingIdentifier 의 다중 출현은 간단한(simple) 매개변수 리스트를 가지며 엄격 모드 코드에서 정의되지 않은 함수에 대해서만 허용된다.

15.1.2 정적 의미론: ContainsExpression : Boolean

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. It is defined piecewise over the following productions:

ObjectBindingPattern : { } { BindingRestProperty }
  1. false 반환.
ObjectBindingPattern : { BindingPropertyList , BindingRestProperty }
  1. BindingPropertyList 의 ContainsExpression 결과 반환.
ArrayBindingPattern : [ Elisionopt ]
  1. false 반환.
ArrayBindingPattern : [ Elisionopt BindingRestElement ]
  1. BindingRestElement 의 ContainsExpression 결과 반환.
ArrayBindingPattern : [ BindingElementList , Elisionopt ]
  1. BindingElementList 의 ContainsExpression 결과 반환.
ArrayBindingPattern : [ BindingElementList , Elisionopt BindingRestElement ]
  1. hasBindingElementList 의 ContainsExpression 결과로 둔다.
  2. hastrue 이면 true 반환.
  3. BindingRestElement 의 ContainsExpression 결과 반환.
BindingPropertyList : BindingPropertyList , BindingProperty
  1. hasBindingPropertyList 의 ContainsExpression 결과로 둔다.
  2. hastrue 이면 true 반환.
  3. BindingProperty 의 ContainsExpression 결과 반환.
BindingElementList : BindingElementList , BindingElisionElement
  1. hasBindingElementList 의 ContainsExpression 결과로 둔다.
  2. hastrue 이면 true 반환.
  3. BindingElisionElement 의 ContainsExpression 결과 반환.
BindingElisionElement : Elisionopt BindingElement
  1. BindingElement 의 ContainsExpression 결과 반환.
BindingProperty : PropertyName : BindingElement
  1. has 를 IsComputedPropertyKey(PropertyName) 로 둔다.
  2. hastrue 이면 true 반환.
  3. BindingElement 의 ContainsExpression 결과 반환.
BindingElement : BindingPattern Initializer
  1. true 반환.
SingleNameBinding : BindingIdentifier
  1. false 반환.
SingleNameBinding : BindingIdentifier Initializer
  1. true 반환.
BindingRestElement : ... BindingIdentifier
  1. false 반환.
BindingRestElement : ... BindingPattern
  1. BindingPattern 의 ContainsExpression 결과 반환.
FormalParameters : [empty]
  1. false 반환.
FormalParameters : FormalParameterList , FunctionRestParameter
  1. FormalParameterList 의 ContainsExpression 이 true 이면 true 반환.
  2. FunctionRestParameter 의 ContainsExpression 결과 반환.
FormalParameterList : FormalParameterList , FormalParameter
  1. FormalParameterList 의 ContainsExpression 이 true 이면 true 반환.
  2. FormalParameter 의 ContainsExpression 결과 반환.
ArrowParameters : BindingIdentifier
  1. false 반환.
ArrowParameters : CoverParenthesizedExpressionAndArrowParameterList
  1. formalsCoverParenthesizedExpressionAndArrowParameterList 가 커버하는 ArrowFormalParameters 로 둔다.
  2. formals 의 ContainsExpression 결과 반환.
AsyncArrowBindingIdentifier : BindingIdentifier
  1. false 반환.

15.1.3 정적 의미론: IsSimpleParameterList : Boolean

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. 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. IsSimpleParameterList(FormalParameterList) 가 false 이면 false 반환.
  2. IsSimpleParameterList(FormalParameter) 반환.
FormalParameter : BindingElement
  1. IsSimpleParameterList(BindingElement) 반환.
ArrowParameters : BindingIdentifier
  1. true 반환.
ArrowParameters : CoverParenthesizedExpressionAndArrowParameterList
  1. formalsCoverParenthesizedExpressionAndArrowParameterList 가 커버하는 ArrowFormalParameters 로 둔다.
  2. IsSimpleParameterList(formals) 반환.
AsyncArrowBindingIdentifier : BindingIdentifier
  1. true 반환.
CoverCallExpressionAndAsyncArrowHead : MemberExpression Arguments
  1. headCoverCallExpressionAndAsyncArrowHead 가 커버하는 AsyncArrowHead 로 둔다.
  2. IsSimpleParameterList(head) 반환.

15.1.4 정적 의미론: HasInitializer : Boolean

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. 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. HasInitializer(FormalParameterList) 가 true 이면 true 반환.
  2. HasInitializer(FormalParameter) 반환.

15.1.5 정적 의미론: ExpectedArgumentCount : 음이 아닌 정수

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. It is defined piecewise over the following productions:

FormalParameters : [empty] FunctionRestParameter
  1. 0 반환.
FormalParameters : FormalParameterList , FunctionRestParameter
  1. FormalParameterList 의 ExpectedArgumentCount 반환.
Note

FormalParameterList 의 ExpectedArgumentCount 는 나머지(rest) 매개변수 또는 Initializer 를 가진 첫 번째 FormalParameter 의 왼쪽에 있는 FormalParameters 의 개수이다. 초기화자가 있는 첫 매개변수 뒤에 초기화자 없는 매개변수가 올 수 있지만 그러한 매개변수들은 undefined 를 기본값으로 갖는 선택(optional) 매개변수로 간주된다.

FormalParameterList : FormalParameter
  1. HasInitializer(FormalParameter) 가 true 이면 0 반환.
  2. 1 반환.
FormalParameterList : FormalParameterList , FormalParameter
  1. countFormalParameterList 의 ExpectedArgumentCount 로 둔다.
  2. HasInitializer(FormalParameterList) 가 true 이거나 HasInitializer(FormalParameter) 가 true 이면 count 반환.
  3. count + 1 반환.
ArrowParameters : BindingIdentifier
  1. 1 반환.
ArrowParameters : CoverParenthesizedExpressionAndArrowParameterList
  1. formalsCoverParenthesizedExpressionAndArrowParameterList 가 커버하는 ArrowFormalParameters 로 둔다.
  2. formals 의 ExpectedArgumentCount 반환.
PropertySetParameterList : FormalParameter
  1. HasInitializer(FormalParameter) 가 true 이면 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

FunctionBody 의 LexicallyDeclaredNames 는 var 혹은 function 선언으로 바인딩된 식별자를 포함하지 않는다.

FunctionBody : FunctionStatementList

15.2.2 정적 의미론: FunctionBodyContainsUseStrict : Boolean

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. It is defined piecewise over the following productions:

FunctionBody : FunctionStatementList
  1. FunctionBodyDirective PrologueUse Strict Directive 가 포함되어 있으면 true 반환; 그렇지 않으면 false 반환.

15.2.3 런타임 의미론: EvaluateFunctionBody : return completion 또는 throw completion

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. It is defined piecewise over the following productions:

FunctionBody : FunctionStatementList
  1. FunctionDeclarationInstantiation(functionObject, argumentsList) 수행.
  2. FunctionStatementList 의 Evaluation 수행.
  3. NOTE: 이전 단계가 정상 completion 을 반환했다면 FunctionStatementList 끝을 통과하여 평가가 종료된 것이다.
  4. ReturnCompletion(undefined) 반환.

15.2.4 런타임 의미론: InstantiateOrdinaryFunctionObject : ECMAScript function object

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. It is defined piecewise over the following productions:

FunctionDeclaration : function BindingIdentifier ( FormalParameters ) { FunctionBody }
  1. nameBindingIdentifier 의 StringValue 로 둔다.
  2. sourceTextFunctionDeclaration 이 매칭한 소스 텍스트로 둔다.
  3. FOrdinaryFunctionCreate(%Function.prototype%, sourceText, FormalParameters, FunctionBody, non-lexical-this, env, privateEnv) 로 둔다.
  4. SetFunctionName(F, name) 수행.
  5. MakeConstructor(F) 수행.
  6. F 반환.
FunctionDeclaration : function ( FormalParameters ) { FunctionBody }
  1. sourceTextFunctionDeclaration 이 매칭한 소스 텍스트로 둔다.
  2. FOrdinaryFunctionCreate(%Function.prototype%, sourceText, FormalParameters, FunctionBody, non-lexical-this, env, privateEnv) 로 둔다.
  3. SetFunctionName(F, "default") 수행.
  4. MakeConstructor(F) 수행.
  5. F 반환.
Note

익명 FunctionDeclaration 은 오직 export default 선언의 일부로만 나타날 수 있으며 그 함수 코드는 항상 strict mode 코드이다.

15.2.5 런타임 의미론: InstantiateOrdinaryFunctionExpression : ECMAScript function object

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. It is defined piecewise over the following productions:

FunctionExpression : function ( FormalParameters ) { FunctionBody }
  1. name 이 존재하지 않으면 name = "".
  2. env 를 실행 중 실행 컨텍스트의 LexicalEnvironment 로 둔다.
  3. privateEnv 를 실행 중 실행 컨텍스트의 PrivateEnvironment 로 둔다.
  4. sourceTextFunctionExpression 이 매칭한 소스 텍스트로 둔다.
  5. closureOrdinaryFunctionCreate(%Function.prototype%, sourceText, FormalParameters, FunctionBody, non-lexical-this, env, privateEnv) 로 둔다.
  6. SetFunctionName(closure, name) 수행.
  7. MakeConstructor(closure) 수행.
  8. closure 반환.
FunctionExpression : function BindingIdentifier ( FormalParameters ) { FunctionBody }
  1. 단언: name 은 존재하지 않는다.
  2. nameBindingIdentifier 의 StringValue 로 둔다.
  3. outerEnv 를 실행 중 실행 컨텍스트의 LexicalEnvironment 로 둔다.
  4. funcEnvNewDeclarativeEnvironment(outerEnv) 로 둔다.
  5. funcEnv.CreateImmutableBinding(name, false) 수행.
  6. privateEnv 를 실행 중 실행 컨텍스트의 PrivateEnvironment 로 둔다.
  7. sourceTextFunctionExpression 이 매칭한 소스 텍스트로 둔다.
  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

FunctionExpressionBindingIdentifier 는 그 FunctionExpressionFunctionBody 내부에서 참조되어 재귀 호출을 가능하게 한다. 그러나 FunctionDeclaration 과 달리 FunctionExpressionBindingIdentifierFunctionExpression 을 둘러싼 외부 스코프에서 참조할 수 없고 영향을 주지 않는다.

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. FunctionExpression 의 InstantiateOrdinaryFunctionExpression 반환.
Note 2

FunctionDeclaration 또는 FunctionExpression 으로 정의된 모든 함수에 대해 "prototype" 프로퍼티가 자동으로 생성되어 그 함수가 생성자로 사용될 가능성을 허용한다.

FunctionStatementList : [empty]
  1. undefined 반환.

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

생성물 인스턴스
ArrowParameters[Yield, Await] : CoverParenthesizedExpressionAndArrowParameterList[?Yield, ?Await]
를 처리할 때 CoverParenthesizedExpressionAndArrowParameterList 의 해석은 다음 문법을 사용해 정밀화된다:

ArrowFormalParameters[Yield, Await] : ( UniqueFormalParameters[?Yield, ?Await] )

15.3.1 정적 의미론: 조기 오류(Static Semantics: Early Errors)

ArrowFunction : ArrowParameters => ConciseBody ArrowParameters : CoverParenthesizedExpressionAndArrowParameterList

15.3.2 정적 의미론: ConciseBodyContainsUseStrict : Boolean

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. It is defined piecewise over the following productions:

ConciseBody : ExpressionBody
  1. false 반환.
ConciseBody : { FunctionBody }
  1. FunctionBodyContainsUseStrict(FunctionBody) 반환.

15.3.3 런타임 의미론: EvaluateConciseBody : return completion 또는 throw completion

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. It is defined piecewise over the following productions:

ConciseBody : ExpressionBody
  1. FunctionDeclarationInstantiation(functionObject, argumentsList) 수행.
  2. ExpressionBody 의 Evaluation 결과를 ? 로 반환.

15.3.4 런타임 의미론: InstantiateArrowFunctionExpression : ECMAScript function object

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. It is defined piecewise over the following productions:

ArrowFunction : ArrowParameters => ConciseBody
  1. name 이 존재하지 않으면 name = "".
  2. env 를 실행 중 실행 컨텍스트의 LexicalEnvironment 로 둔다.
  3. privateEnv 를 실행 중 실행 컨텍스트의 PrivateEnvironment 로 둔다.
  4. sourceTextArrowFunction 이 매칭한 소스 텍스트로 둔다.
  5. closureOrdinaryFunctionCreate(%Function.prototype%, sourceText, ArrowParameters, ConciseBody, lexical-this, env, privateEnv) 로 둔다.
  6. SetFunctionName(closure, name) 수행.
  7. closure 반환.
Note

ArrowFunctionarguments, super, this, new.target 에 대한 지역 바인딩을 정의하지 않는다. ArrowFunction 내부의 이러한 식별자 참조는 렉시컬 외부 환경의 바인딩으로 해석되어야 한다. 일반적으로 이는 바로 둘러싼 함수의 Function Environment 가 된다. 비록 ArrowFunctionsuper 를 포함할 수 있지만 단계 5 에서 생성된 함수 객체MakeMethod 를 수행하여 메서드로 만들지 않는다. super 를 참조하는 ArrowFunction 은 항상 비-ArrowFunction 안에 포함되며, super 구현에 필요한 상태는 캡처된 env 를 통해 접근 가능하다.

15.3.5 런타임 의미론: 평가(Runtime Semantics: Evaluation)

ArrowFunction : ArrowParameters => ConciseBody
  1. ArrowFunction 의 InstantiateArrowFunctionExpression 반환.
ExpressionBody : AssignmentExpression
  1. exprRefAssignmentExpression 평가 결과 (?) 로 둔다.
  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 정적 의미론: HasDirectSuper : Boolean

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. 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 정적 의미론: SpecialMethod : Boolean

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. 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 런타임 의미론: DefineMethod 또는 abrupt completion

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. It is defined piecewise over the following productions:

MethodDefinition : ClassElementName ( UniqueFormalParameters ) { FunctionBody }
  1. propKeyClassElementName 평가 결과 (?) 로 둔다.
  2. env 를 실행 중 실행 컨텍스트의 LexicalEnvironment 로 둔다.
  3. privateEnv 를 실행 중 실행 컨텍스트의 PrivateEnvironment 로 둔다.
  4. functionPrototype 이 존재하면
    1. prototype = functionPrototype
  5. 그렇지 않으면
    1. prototype = %Function.prototype%
  6. sourceTextMethodDefinition 이 매칭한 소스 텍스트로 둔다.
  7. closureOrdinaryFunctionCreate(prototype, sourceText, UniqueFormalParameters, FunctionBody, non-lexical-this, env, privateEnv) 로 둔다.
  8. MakeMethod(closure, object) 수행.
  9. Record { [[Key]]: propKey, [[Closure]]: closure } 반환.

15.4.5 런타임 의미론: MethodDefinitionEvaluation 또는 abrupt completion

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. It is defined piecewise over the following productions:

MethodDefinition : ClassElementName ( UniqueFormalParameters ) { FunctionBody }
  1. methodDefMethodDefinition 의 DefineMethod(object) 결과 (?) 로 둔다.
  2. SetFunctionName(methodDef.[[Closure]], methodDef.[[Key]]) 수행.
  3. DefineMethodProperty(object, methodDef.[[Key]], methodDef.[[Closure]], enumerable) 반환.
MethodDefinition : get ClassElementName ( ) { FunctionBody }
  1. propKeyClassElementName 평가 결과 (?) 로 둔다.
  2. env 를 실행 중 실행 컨텍스트의 LexicalEnvironment 로 둔다.
  3. privateEnv 를 실행 중 실행 컨텍스트의 PrivateEnvironment 로 둔다.
  4. sourceTextMethodDefinition 이 매칭한 소스 텍스트로 둔다.
  5. formalParameterList FormalParameters : [empty] 생성물 인스턴스로 둔다.
  6. closureOrdinaryFunctionCreate(%Function.prototype%, sourceText, formalParameterList, FunctionBody, non-lexical-this, env, privateEnv) 로 둔다.
  7. MakeMethod(closure, object) 수행.
  8. SetFunctionName(closure, propKey, "get") 수행.
  9. propKeyPrivate Name 이면
    1. PrivateElement { [[Key]]: propKey, [[Kind]]: accessor, [[Get]]: closure, [[Set]]: undefined } 반환.
  10. 그렇지 않으면
    1. desc = PropertyDescriptor { [[Get]]: closure, [[Enumerable]]: enumerable, [[Configurable]]: true }.
    2. DefinePropertyOrThrow(object, propKey, desc) 수행.
    3. unused 반환.
MethodDefinition : set ClassElementName ( PropertySetParameterList ) { FunctionBody }
  1. propKeyClassElementName 평가 결과 (?) 로 둔다.
  2. env 를 실행 중 실행 컨텍스트의 LexicalEnvironment 로 둔다.
  3. privateEnv 를 실행 중 실행 컨텍스트의 PrivateEnvironment 로 둔다.
  4. sourceTextMethodDefinition 이 매칭한 소스 텍스트로 둔다.
  5. closureOrdinaryFunctionCreate(%Function.prototype%, sourceText, PropertySetParameterList, FunctionBody, non-lexical-this, env, privateEnv) 로 둔다.
  6. MakeMethod(closure, object) 수행.
  7. SetFunctionName(closure, propKey, "set") 수행.
  8. propKeyPrivate Name 이면
    1. PrivateElement { [[Key]]: propKey, [[Kind]]: accessor, [[Get]]: undefined, [[Set]]: closure } 반환.
  9. 그렇지 않으면
    1. desc = PropertyDescriptor { [[Set]]: closure, [[Enumerable]]: enumerable, [[Configurable]]: true }.
    2. DefinePropertyOrThrow(object, propKey, desc) 수행.
    3. unused 반환.
GeneratorMethod : * ClassElementName ( UniqueFormalParameters ) { GeneratorBody }
  1. propKeyClassElementName 평가 결과 (?) 로 둔다.
  2. env 를 실행 중 실행 컨텍스트의 LexicalEnvironment 로 둔다.
  3. privateEnv 를 실행 중 실행 컨텍스트의 PrivateEnvironment 로 둔다.
  4. sourceTextGeneratorMethod 이 매칭한 소스 텍스트로 둔다.
  5. closureOrdinaryFunctionCreate(%GeneratorFunction.prototype%, sourceText, UniqueFormalParameters, GeneratorBody, non-lexical-this, env, privateEnv) 로 둔다.
  6. MakeMethod(closure, object) 수행.
  7. SetFunctionName(closure, propKey) 수행.
  8. prototypeOrdinaryObjectCreate(%GeneratorPrototype%) 로 둔다.
  9. DefinePropertyOrThrow(closure, "prototype", PropertyDescriptor { [[Value]]: prototype, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false }) 수행.
  10. DefineMethodProperty(object, propKey, closure, enumerable) 반환.
AsyncGeneratorMethod : async * ClassElementName ( UniqueFormalParameters ) { AsyncGeneratorBody }
  1. propKeyClassElementName 평가 결과 (?) 로 둔다.
  2. env 를 실행 중 실행 컨텍스트의 LexicalEnvironment 로 둔다.
  3. privateEnv 를 실행 중 실행 컨텍스트의 PrivateEnvironment 로 둔다.
  4. sourceTextAsyncGeneratorMethod 이 매칭한 소스 텍스트로 둔다.
  5. closureOrdinaryFunctionCreate(%AsyncGeneratorFunction.prototype%, sourceText, UniqueFormalParameters, AsyncGeneratorBody, non-lexical-this, env, privateEnv) 로 둔다.
  6. MakeMethod(closure, object) 수행.
  7. SetFunctionName(closure, propKey) 수행.
  8. prototypeOrdinaryObjectCreate(%AsyncGeneratorPrototype%) 로 둔다.
  9. DefinePropertyOrThrow(closure, "prototype", PropertyDescriptor { [[Value]]: prototype, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false }) 수행.
  10. DefineMethodProperty(object, propKey, closure, enumerable) 반환.
AsyncMethod : async ClassElementName ( UniqueFormalParameters ) { AsyncFunctionBody }
  1. propKeyClassElementName 평가 결과 (?) 로 둔다.
  2. env 를 실행 중 실행 컨텍스트의 LexicalEnvironment 로 둔다.
  3. privateEnv 를 실행 중 실행 컨텍스트의 PrivateEnvironment 로 둔다.
  4. sourceTextAsyncMethod 이 매칭한 소스 텍스트로 둔다.
  5. closureOrdinaryFunctionCreate(%AsyncFunction.prototype%, sourceText, UniqueFormalParameters, AsyncFunctionBody, non-lexical-this, env, privateEnv) 로 둔다.
  6. MakeMethod(closure, object) 수행.
  7. SetFunctionName(closure, propKey) 수행.
  8. DefineMethodProperty(object, propKey, 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 바로 뒤의 문맥은 InputElementRegExpOrTemplateTail 어휘 목표(lexical goal)를 사용해야 한다.

Note 2

YieldExpression 은 제너레이터 함수의 FormalParameters 안에서 사용할 수 없다. 그 이유는 FormalParameters 에 속하는 모든 표현식이, 생성된 Generator 가 재개(resumable) 가능한 상태가 되기 이전에 평가되기 때문이다.

Note 3

Generator 와 관련된 추상 연산은 27.5.3 에 정의되어 있다.

15.5.1 정적 의미론: 조기 오류 (Static Semantics: Early Errors)

GeneratorMethod : * ClassElementName ( UniqueFormalParameters ) { GeneratorBody } GeneratorDeclaration : function * BindingIdentifier ( FormalParameters ) { GeneratorBody } function * ( FormalParameters ) { GeneratorBody } GeneratorExpression : function * BindingIdentifieropt ( FormalParameters ) { GeneratorBody }

15.5.2 런타임 의미론: EvaluateGeneratorBody : throw completion 또는 return completion

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. It is defined piecewise over the following productions:

GeneratorBody : FunctionBody
  1. FunctionDeclarationInstantiation(functionObject, argumentsList) 수행.
  2. G 를 ? OrdinaryCreateFromConstructor(functionObject, "%GeneratorPrototype%", « [[GeneratorState]], [[GeneratorContext]], [[GeneratorBrand]] ») 로 둔다.
  3. G.[[GeneratorBrand]]empty 로 설정한다.
  4. G.[[GeneratorState]]suspended-start 로 설정한다.
  5. GeneratorStart(G, FunctionBody) 수행.
  6. ReturnCompletion(G) 반환.

15.5.3 런타임 의미론: InstantiateGeneratorFunctionObject : ECMAScript 함수 객체

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. It is defined piecewise over the following productions:

GeneratorDeclaration : function * BindingIdentifier ( FormalParameters ) { GeneratorBody }
  1. nameBindingIdentifier 의 StringValue 로 둔다.
  2. sourceTextGeneratorDeclaration 이 매칭한 소스 텍스트로 둔다.
  3. FOrdinaryFunctionCreate(%GeneratorFunction.prototype%, sourceText, FormalParameters, GeneratorBody, non-lexical-this, env, privateEnv) 로 둔다.
  4. SetFunctionName(F, name) 수행.
  5. prototypeOrdinaryObjectCreate(%GeneratorPrototype%) 로 둔다.
  6. DefinePropertyOrThrow(F, "prototype", PropertyDescriptor { [[Value]]: prototype, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false }) 수행.
  7. F 반환.
GeneratorDeclaration : function * ( FormalParameters ) { GeneratorBody }
  1. sourceTextGeneratorDeclaration 이 매칭한 소스 텍스트로 둔다.
  2. FOrdinaryFunctionCreate(%GeneratorFunction.prototype%, sourceText, FormalParameters, GeneratorBody, non-lexical-this, env, privateEnv) 로 둔다.
  3. SetFunctionName(F, "default") 수행.
  4. prototypeOrdinaryObjectCreate(%GeneratorPrototype%) 로 둔다.
  5. DefinePropertyOrThrow(F, "prototype", PropertyDescriptor { [[Value]]: prototype, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false }) 수행.
  6. F 반환.
Note

익명 GeneratorDeclarationexport default 선언의 일부로만 등장할 수 있으며 그 함수 코드는 항상 strict mode 코드이다.

15.5.4 런타임 의미론: InstantiateGeneratorFunctionExpression : ECMAScript 함수 객체

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. It is defined piecewise over the following productions:

GeneratorExpression : function * ( FormalParameters ) { GeneratorBody }
  1. name 이 존재하지 않으면 name = "" 로 설정한다.
  2. env 를 실행 중 실행 컨텍스트의 LexicalEnvironment 로 둔다.
  3. privateEnv 를 실행 중 실행 컨텍스트의 PrivateEnvironment 로 둔다.
  4. sourceTextGeneratorExpression 이 매칭한 소스 텍스트로 둔다.
  5. closureOrdinaryFunctionCreate(%GeneratorFunction.prototype%, sourceText, FormalParameters, GeneratorBody, non-lexical-this, env, privateEnv) 로 둔다.
  6. SetFunctionName(closure, name) 수행.
  7. prototypeOrdinaryObjectCreate(%GeneratorPrototype%) 로 둔다.
  8. DefinePropertyOrThrow(closure, "prototype", PropertyDescriptor { [[Value]]: prototype, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false }) 수행.
  9. closure 반환.
GeneratorExpression : function * BindingIdentifier ( FormalParameters ) { GeneratorBody }
  1. 단언: name 은 존재하지 않는다.
  2. nameBindingIdentifier 의 StringValue 로 설정한다.
  3. outerEnv 를 실행 중 실행 컨텍스트의 LexicalEnvironment 로 둔다.
  4. funcEnvNewDeclarativeEnvironment(outerEnv) 로 둔다.
  5. funcEnv.CreateImmutableBinding(name, false) 수행.
  6. privateEnv 를 실행 중 실행 컨텍스트의 PrivateEnvironment 로 둔다.
  7. sourceTextGeneratorExpression 이 매칭한 소스 텍스트로 둔다.
  8. closureOrdinaryFunctionCreate(%GeneratorFunction.prototype%, sourceText, FormalParameters, GeneratorBody, non-lexical-this, funcEnv, privateEnv) 로 둔다.
  9. SetFunctionName(closure, name) 수행.
  10. prototypeOrdinaryObjectCreate(%GeneratorPrototype%) 로 둔다.
  11. DefinePropertyOrThrow(closure, "prototype", PropertyDescriptor { [[Value]]: prototype, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false }) 수행.
  12. funcEnv.InitializeBinding(name, closure) 수행.
  13. closure 반환.
Note

GeneratorExpressionBindingIdentifier 는 그 FunctionBody 내부에서 참조되어 제너레이터 코드가 재귀 호출될 수 있게 한다. 그러나 GeneratorDeclaration 과 달리, 해당 BindingIdentifier 는 둘러싼 스코프에서 참조할 수 없고 영향을 주지 않는다.

15.5.5 런타임 의미론: 평가 (Runtime Semantics: Evaluation)

GeneratorExpression : function * BindingIdentifieropt ( FormalParameters ) { GeneratorBody }
  1. GeneratorExpression 의 InstantiateGeneratorFunctionExpression 결과를 반환한다.
YieldExpression : yield
  1. Yield(undefined) 를 반환한다.
YieldExpression : yield AssignmentExpression
  1. exprRefAssignmentExpression 평가 결과 (?) 로 둔다.
  2. value 를 ? GetValue(exprRef) 로 둔다.
  3. Yield(value) 반환.
YieldExpression : yield * AssignmentExpression
  1. generatorKindGetGeneratorKind() 로 둔다.
  2. 단언: generatorKindsync 또는 async 이어야 한다.
  3. exprRefAssignmentExpression 평가 결과 (?) 로 둔다.
  4. value 를 ? GetValue(exprRef) 로 둔다.
  5. iteratorRecord 를 ? GetIterator(value, generatorKind) 로 둔다.
  6. iteratoriteratorRecord.[[Iterator]] 로 둔다.
  7. receivedNormalCompletion(undefined) 로 둔다.
  8. 반복,
    1. receivednormal completion 이라면
      1. innerResult 를 ? Call(iteratorRecord.[[NextMethod]], iteratorRecord.[[Iterator]], « received.[[Value]] ») 로 둔다.
      2. generatorKindasync 이면 innerResult 를 ? Await(innerResult) 로 둔다.
      3. innerResult 가 Object 가 아니면 TypeError 예외를 던진다.
      4. done 을 ? IteratorComplete(innerResult) 로 둔다.
      5. donetrue 이면
        1. IteratorValue(innerResult) 반환.
      6. generatorKindasync 이면 received = Completion(AsyncGeneratorYield(? IteratorValue(innerResult))).
      7. 아니면 received = Completion(GeneratorYield(innerResult)).
    2. 아니고 receivedthrow completion 이라면
      1. throw 를 ? GetMethod(iterator, "throw") 로 둔다.
      2. throwundefined 가 아니면
        1. innerResult 를 ? Call(throw, iterator, « received.[[Value]] ») 로 둔다.
        2. generatorKindasync 이면 innerResult 를 ? Await(innerResult) 로 둔다.
        3. NOTE: 내부 iterator throw 메서드에서 발생한 예외는 전파되고, 정상 completion 은 내부 next 와 유사하게 처리된다.
        4. innerResult 가 Object 가 아니면 TypeError 예외를 던진다.
        5. done = ? IteratorComplete(innerResult).
        6. donetrue 이면
          1. IteratorValue(innerResult) 반환.
        7. generatorKindasync 이면 received = Completion(AsyncGeneratorYield(? IteratorValue(innerResult))).
        8. 아니면 received = Completion(GeneratorYield(innerResult)).
      3. 그렇지 않으면
        1. NOTE: iteratorthrow 메서드가 없으면 본 throw 로 yield* 루프가 종료되며, 먼저 정리 기회를 준다.
        2. closeCompletion = NormalCompletion(empty) 로 둔다.
        3. generatorKindasync 이면 ? AsyncIteratorClose(iteratorRecord, closeCompletion) 수행.
        4. 아니면 ? IteratorClose(iteratorRecord, closeCompletion) 수행.
        5. NOTE: 다음 단계에서 TypeErroryield* 프로토콜 위반(throw 메서드 부재)을 나타낸다.
        6. TypeError 예외를 던진다.
    3. 그 밖의 경우
      1. 단언: receivedreturn completion 이다.
      2. return 을 ? GetMethod(iterator, "return") 로 둔다.
      3. returnundefined 이면
        1. value = received.[[Value]].
        2. generatorKindasync 이면 value = ? Await(value).
        3. ReturnCompletion(value) 반환.
      4. innerReturnResult = ? Call(return, iterator, « received.[[Value]] »).
      5. generatorKindasync 이면 innerReturnResult = ? Await(innerReturnResult).
      6. innerReturnResult 가 Object 가 아니면 TypeError 예외를 던진다.
      7. done = ? IteratorComplete(innerReturnResult).
      8. donetrue 이면
        1. value = ? IteratorValue(innerReturnResult).
        2. ReturnCompletion(value) 반환.
      9. generatorKindasync 이면 received = Completion(AsyncGeneratorYield(? IteratorValue(innerReturnResult))).
      10. 아니면 received = Completion(GeneratorYield(innerReturnResult)).

15.6 비동기 제너레이터 함수 정의 (Async Generator Function Definitions)

구문 (Syntax)

AsyncGeneratorDeclaration[Yield, Await, Default] : async [no LineTerminator here] function * BindingIdentifier[?Yield, ?Await] ( FormalParameters[+Yield, +Await] ) { AsyncGeneratorBody } [+Default] async [no LineTerminator here] function * ( FormalParameters[+Yield, +Await] ) { AsyncGeneratorBody } AsyncGeneratorExpression : async [no LineTerminator here] function * BindingIdentifier[+Yield, +Await]opt ( FormalParameters[+Yield, +Await] ) { AsyncGeneratorBody } AsyncGeneratorMethod[Yield, Await] : async [no LineTerminator here] * ClassElementName[?Yield, ?Await] ( UniqueFormalParameters[+Yield, +Await] ) { AsyncGeneratorBody } AsyncGeneratorBody : FunctionBody[+Yield, +Await] Note 1

YieldExpressionAwaitExpression 은 async generator 함수의 FormalParameters 내부에서 사용할 수 없다. 이는 해당 표현식들이 AsyncGenerator 가 재개 가능한 상태가 되기 전에 평가되기 때문이다.

Note 2

AsyncGenerator 관련 추상 연산은 27.6.3 에 정의되어 있다.

15.6.1 정적 의미론: 조기 오류 (Static Semantics: Early Errors)

AsyncGeneratorMethod : async * ClassElementName ( UniqueFormalParameters ) { AsyncGeneratorBody } AsyncGeneratorDeclaration : async function * BindingIdentifier ( FormalParameters ) { AsyncGeneratorBody } async function * ( FormalParameters ) { AsyncGeneratorBody } AsyncGeneratorExpression : async function * BindingIdentifieropt ( FormalParameters ) { AsyncGeneratorBody }

15.6.2 런타임 의미론: EvaluateAsyncGeneratorBody : throw completion 또는 return completion

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. It is defined piecewise over the following productions:

AsyncGeneratorBody : FunctionBody
  1. FunctionDeclarationInstantiation(functionObject, argumentsList) 수행.
  2. generator 를 ? OrdinaryCreateFromConstructor(functionObject, "%AsyncGeneratorPrototype%", « [[AsyncGeneratorState]], [[AsyncGeneratorContext]], [[AsyncGeneratorQueue]], [[GeneratorBrand]] ») 로 둔다.
  3. generator.[[GeneratorBrand]]empty 로 설정한다.
  4. generator.[[AsyncGeneratorState]]suspended-start 로 설정한다.
  5. AsyncGeneratorStart(generator, FunctionBody) 수행.
  6. ReturnCompletion(generator) 반환.

15.6.3 런타임 의미론: InstantiateAsyncGeneratorFunctionObject : ECMAScript 함수 객체

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. It is defined piecewise over the following productions:

AsyncGeneratorDeclaration : async function * BindingIdentifier ( FormalParameters ) { AsyncGeneratorBody }
  1. nameBindingIdentifier 의 StringValue 로 둔다.
  2. sourceTextAsyncGeneratorDeclaration 이 매칭한 소스 텍스트로 둔다.
  3. FOrdinaryFunctionCreate(%AsyncGeneratorFunction.prototype%, sourceText, FormalParameters, AsyncGeneratorBody, non-lexical-this, env, privateEnv) 로 둔다.
  4. SetFunctionName(F, name) 수행.
  5. prototypeOrdinaryObjectCreate(%AsyncGeneratorPrototype%) 로 둔다.
  6. DefinePropertyOrThrow(F, "prototype", PropertyDescriptor { [[Value]]: prototype, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false }) 수행.
  7. F 반환.
AsyncGeneratorDeclaration : async function * ( FormalParameters ) { AsyncGeneratorBody }
  1. sourceTextAsyncGeneratorDeclaration 이 매칭한 소스 텍스트로 둔다.
  2. FOrdinaryFunctionCreate(%AsyncGeneratorFunction.prototype%, sourceText, FormalParameters, AsyncGeneratorBody, non-lexical-this, env, privateEnv) 로 둔다.
  3. SetFunctionName(F, "default") 수행.
  4. prototypeOrdinaryObjectCreate(%AsyncGeneratorPrototype%) 로 둔다.
  5. DefinePropertyOrThrow(F, "prototype", PropertyDescriptor { [[Value]]: prototype, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false }) 수행.
  6. F 반환.
Note

익명 AsyncGeneratorDeclarationexport default 선언에서만 나타날 수 있다.

15.6.4 런타임 의미론: InstantiateAsyncGeneratorFunctionExpression : ECMAScript 함수 객체

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. It is defined piecewise over the following productions:

AsyncGeneratorExpression : async function * ( FormalParameters ) { AsyncGeneratorBody }
  1. name 이 존재하지 않으면 name = "" 로 설정한다.
  2. env 를 실행 중 실행 컨텍스트의 LexicalEnvironment 로 둔다.
  3. privateEnv 를 실행 중 실행 컨텍스트의 PrivateEnvironment 로 둔다.
  4. sourceTextAsyncGeneratorExpression 이 매칭한 소스 텍스트로 둔다.
  5. closureOrdinaryFunctionCreate(%AsyncGeneratorFunction.prototype%, sourceText, FormalParameters, AsyncGeneratorBody, non-lexical-this, env, privateEnv) 로 둔다.
  6. SetFunctionName(closure, name) 수행.
  7. prototypeOrdinaryObjectCreate(%AsyncGeneratorPrototype%) 로 둔다.
  8. DefinePropertyOrThrow(closure, "prototype", PropertyDescriptor { [[Value]]: prototype, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false }) 수행.
  9. closure 반환.
AsyncGeneratorExpression : async function * BindingIdentifier ( FormalParameters ) { AsyncGeneratorBody }
  1. 단언: name 은 존재하지 않는다.
  2. name = BindingIdentifier 의 StringValue.
  3. outerEnv = 실행 중 실행 컨텍스트의 LexicalEnvironment.
  4. funcEnv = NewDeclarativeEnvironment(outerEnv).
  5. funcEnv.CreateImmutableBinding(name, false) 수행.
  6. privateEnv = 실행 중 실행 컨텍스트의 PrivateEnvironment.
  7. sourceText = AsyncGeneratorExpression 이 매칭한 소스 텍스트.
  8. closure = OrdinaryFunctionCreate(%AsyncGeneratorFunction.prototype%, sourceText, FormalParameters, AsyncGeneratorBody, non-lexical-this, funcEnv, privateEnv).
  9. SetFunctionName(closure, name) 수행.
  10. prototype = OrdinaryObjectCreate(%AsyncGeneratorPrototype%).
  11. DefinePropertyOrThrow(closure, "prototype", PropertyDescriptor { [[Value]]: prototype, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false }) 수행.
  12. funcEnv.InitializeBinding(name, closure) 수행.
  13. closure 반환.
Note

AsyncGeneratorExpressionBindingIdentifier 는 해당 AsyncGeneratorBody 내부에서 재귀 호출을 위해 참조될 수 있으나 AsyncGeneratorDeclaration 과 달리 둘러싼 스코프에는 영향을 주지 않는다.

15.6.5 런타임 의미론: 평가 (Runtime Semantics: Evaluation)

AsyncGeneratorExpression : async function * BindingIdentifieropt ( FormalParameters ) { AsyncGeneratorBody }
  1. AsyncGeneratorExpression 의 InstantiateAsyncGeneratorFunctionExpression 결과를 반환한다.

15.7 클래스 정의 (Class Definitions)

구문 (Syntax)

ClassDeclaration[Yield, Await, Default] : class BindingIdentifier[?Yield, ?Await] ClassTail[?Yield, ?Await] [+Default] class ClassTail[?Yield, ?Await] ClassExpression[Yield, Await] : class BindingIdentifier[?Yield, ?Await]opt ClassTail[?Yield, ?Await] ClassTail[Yield, Await] : ClassHeritage[?Yield, ?Await]opt { ClassBody[?Yield, ?Await]opt } ClassHeritage[Yield, Await] : extends LeftHandSideExpression[?Yield, ?Await] ClassBody[Yield, Await] : ClassElementList[?Yield, ?Await] ClassElementList[Yield, Await] : ClassElement[?Yield, ?Await] ClassElementList[?Yield, ?Await] ClassElement[?Yield, ?Await] ClassElement[Yield, Await] : MethodDefinition[?Yield, ?Await] static MethodDefinition[?Yield, ?Await] FieldDefinition[?Yield, ?Await] ; static FieldDefinition[?Yield, ?Await] ; ClassStaticBlock ; FieldDefinition[Yield, Await] : ClassElementName[?Yield, ?Await] Initializer[+In, ?Yield, ?Await]opt ClassElementName[Yield, Await] : PropertyName[?Yield, ?Await] PrivateIdentifier ClassStaticBlock : static { ClassStaticBlockBody } ClassStaticBlockBody : ClassStaticBlockStatementList ClassStaticBlockStatementList : StatementList[~Yield, +Await, ~Return]opt Note

클래스 정의는 항상 strict mode 코드이다.

15.7.1 정적 의미론: 조기 오류 (Static Semantics: Early Errors)

ClassTail : ClassHeritageopt { ClassBody }
  • ClassHeritage 가 존재하지 않고 아래 알고리즘이 true 를 반환하면 Syntax Error 이다:

    1. constructorClassBody 의 ConstructorMethod 로 둔다.
    2. constructorempty 이면 false 반환.
    3. HasDirectSuper(constructor) 반환.
ClassBody : ClassElementList
  • ClassElementList 의 PrototypePropertyNameList 에 "constructor" 가 두 번 이상 나타나면 Syntax Error 이다.
  • ClassElementList 의 PrivateBoundIdentifiers 에 중복 항목이 있으면 (단, 동일 이름이 getter 1회와 setter 1회만, 그리고 둘 다 static 이거나 둘 다 non-static 인 경우를 제외) Syntax Error 이다.
ClassElement : MethodDefinition ClassElement : static MethodDefinition ClassElement : FieldDefinition ; ClassElement : static FieldDefinition ;
  • PropName(FieldDefinition) 이 "prototype" 또는 "constructor" 이면 Syntax Error 이다.
FieldDefinition : ClassElementName Initializeropt ClassElementName : PrivateIdentifier ClassStaticBlockBody : ClassStaticBlockStatementList

15.7.2 정적 의미론: ClassElementKind : constructor-method, non-constructor-method, 또는 empty

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. It is defined piecewise over the following productions:

ClassElement : MethodDefinition
  1. MethodDefinition 의 PropName 이 "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 정적 의미론: ConstructorMethod : ClassElement Parse Node 또는 empty

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. It is defined piecewise over the following productions:

ClassElementList : ClassElement
  1. ClassElement 의 ClassElementKind 가 constructor-method 이면 ClassElement 반환.
  2. empty 반환.
ClassElementList : ClassElementList ClassElement
  1. headClassElementList 의 ConstructorMethod 로 둔다.
  2. headempty 이면 head 반환.
  3. ClassElement 의 ClassElementKind 가 constructor-method 이면 ClassElement 반환.
  4. empty 반환.
Note

조기 오류 규칙은 이름이 "constructor" 인 메서드 정의가 하나뿐이며 accessor 나 generator 정의가 아님을 보장한다.

15.7.4 정적 의미론: IsStatic : Boolean

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. 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 정적 의미론: NonConstructorElements : ClassElement Parse Node 들의 List

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. It is defined piecewise over the following productions:

ClassElementList : ClassElement
  1. ClassElement 의 ClassElementKind 가 non-constructor-method 이면
    1. « ClassElement » 반환.
  2. 새 빈 List 반환.
ClassElementList : ClassElementList ClassElement
  1. listClassElementList 의 NonConstructorElements 로 둔다.
  2. ClassElement 의 ClassElementKind 가 non-constructor-method 이면
    1. list 끝에 ClassElement 추가.
  3. list 반환.

15.7.6 정적 의미론: PrototypePropertyNameList : property key 들의 List

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. It is defined piecewise over the following productions:

ClassElementList : ClassElement
  1. propNameClassElement 의 PropName 으로 둔다.
  2. propNameempty 이면 새 빈 List 반환.
  3. IsStatic(ClassElement) 가 true 이면 새 빈 List 반환.
  4. « propName » 반환.
ClassElementList : ClassElementList ClassElement
  1. listClassElementList 의 PrototypePropertyNameList 로 둔다.
  2. propNameClassElement 의 PropName 으로 둔다.
  3. propNameempty 이면 list 반환.
  4. IsStatic(ClassElement) 가 true 이면 list 반환.
  5. list 와 « propName » 의 리스트 연결을 반환.

15.7.7 정적 의미론: AllPrivateIdentifiersValid : Boolean

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS.

아래에 명시되지 않은 모든 생성물 대안은 다음 기본 정의를 암묵적으로 갖는다:

  1. 이 Parse Node 의 각 자식 노드 child 에 대해
    1. child 가 비단말(nonterminal) 인스턴스이면
      1. AllPrivateIdentifiersValid(child, names) 가 false 이면 false 반환.
  2. true 반환.
MemberExpression : MemberExpression . PrivateIdentifier
  1. namesPrivateIdentifier 의 StringValue 를 포함하면
    1. AllPrivateIdentifiersValid(MemberExpression, names) 반환.
  2. false 반환.
CallExpression : CallExpression . PrivateIdentifier
  1. namesPrivateIdentifier 의 StringValue 를 포함하면
    1. AllPrivateIdentifiersValid(CallExpression, names) 반환.
  2. false 반환.
OptionalChain : ?. PrivateIdentifier
  1. namesPrivateIdentifier 의 StringValue 를 포함하면 true 반환.
  2. false 반환.
OptionalChain : OptionalChain . PrivateIdentifier
  1. namesPrivateIdentifier 의 StringValue 를 포함하면
    1. AllPrivateIdentifiersValid(OptionalChain, names) 반환.
  2. false 반환.
ClassBody : ClassElementList
  1. newNamesnamesClassBody 의 PrivateBoundIdentifiers 의 리스트 연결로 둔다.
  2. AllPrivateIdentifiersValid(ClassElementList, newNames) 반환.
RelationalExpression : PrivateIdentifier in ShiftExpression
  1. namesPrivateIdentifier 의 StringValue 를 포함하면
    1. AllPrivateIdentifiersValid(ShiftExpression, names) 반환.
  2. false 반환.

15.7.8 정적 의미론: PrivateBoundIdentifiers : String 들의 List

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. It is defined piecewise over the following productions:

FieldDefinition : ClassElementName Initializeropt
  1. PrivateBoundIdentifiers(ClassElementName) 반환.
ClassElementName : PrivateIdentifier
  1. PrivateIdentifier 의 StringValue 하나만을 요소로 갖는 List 반환.
ClassElementName : PropertyName ClassElement : ClassStaticBlock ;
  1. 새 빈 List 반환.
ClassElementList : ClassElementList ClassElement
  1. names1 = PrivateBoundIdentifiers(ClassElementList).
  2. names2 = PrivateBoundIdentifiers(ClassElement).
  3. 리스트 연결(names1, names2) 반환.
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. PrivateBoundIdentifiers(ClassElementName) 반환.

15.7.9 정적 의미론: ContainsArguments : Boolean

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS.

아래에 나열되지 않은 모든 생성물 대안은 다음 기본 정의를 갖는다:

  1. 이 Parse Node 의 각 자식 child 에 대해
    1. child 가 비단말 인스턴스이면
      1. ContainsArguments(child) 가 true 이면 true 반환.
  2. false 반환.
IdentifierReference : Identifier
  1. Identifier 의 StringValue 가 "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. ContainsArguments(ClassElementName) 반환.

15.7.10 런타임 의미론: ClassFieldDefinitionEvaluation : ClassFieldDefinition Record 를 담은 정상 completion 또는 abrupt completion

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. It is defined piecewise over the following productions:

FieldDefinition : ClassElementName Initializeropt
  1. name 을 ? Evaluation(ClassElementName) 로 둔다.
  2. Initializer 가 존재하면
    1. formalParameterList FormalParameters : [empty] 의 인스턴스로 둔다.
    2. env 를 실행 중 실행 컨텍스트의 LexicalEnvironment 로 둔다.
    3. privateEnv 를 실행 중 실행 컨텍스트의 PrivateEnvironment 로 둔다.
    4. sourceText 를 빈 Unicode 코드 포인트 시퀀스로 둔다.
    5. initializerOrdinaryFunctionCreate(%Function.prototype%, sourceText, formalParameterList, Initializer, non-lexical-this, env, privateEnv) 로 둔다.
    6. MakeMethod(initializer, homeObject) 수행.
    7. initializer.[[ClassFieldInitializerName]] = name 으로 설정.
  3. 그렇지 않으면
    1. initializer = empty.
  4. ClassFieldDefinition Record { [[Name]]: name, [[Initializer]]: initializer } 반환.
Note
initializer 를 위해 생성된 함수는 ECMAScript 코드에서 직접 접근할 수 없다.

15.7.11 런타임 의미론: ClassStaticBlockDefinitionEvaluation : ClassStaticBlockDefinition Record

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. It is defined piecewise over the following productions:

ClassStaticBlock : static { ClassStaticBlockBody }
  1. lex 를 실행 중 실행 컨텍스트의 LexicalEnvironment 로 둔다.
  2. privateEnv 를 실행 중 실행 컨텍스트의 PrivateEnvironment 로 둔다.
  3. sourceText 를 빈 Unicode 코드 포인트 시퀀스로 둔다.
  4. formalParameters FormalParameters : [empty] 인스턴스로 둔다.
  5. bodyFunctionOrdinaryFunctionCreate(%Function.prototype%, sourceText, formalParameters, ClassStaticBlockBody, non-lexical-this, lex, privateEnv) 로 둔다.
  6. MakeMethod(bodyFunction, homeObject) 수행.
  7. ClassStaticBlockDefinition Record { [[BodyFunction]]: bodyFunction } 반환.
Note
bodyFunction 함수는 ECMAScript 코드에서 직접 접근할 수 없다.

15.7.12 런타임 의미론: EvaluateClassStaticBlockBody : return completion 또는 throw completion

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. It is defined piecewise over the following productions:

ClassStaticBlockBody : ClassStaticBlockStatementList
  1. 단언: functionObject 는 ClassStaticBlockDefinitionEvaluation 단계 5 에서 생성된 합성(synthetic) 함수이다.
  2. FunctionDeclarationInstantiation(functionObject, « ») 수행.
  3. ? Evaluation(ClassStaticBlockStatementList) 수행.
  4. ReturnCompletion(undefined) 반환.

15.7.13 런타임 의미론: ClassElementEvaluation 또는 abrupt completion

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. It is defined piecewise over the following productions:

ClassElement : FieldDefinition ; static FieldDefinition ;
  1. FieldDefinition에 대해 object를 인수로 하여 ClassFieldDefinitionEvaluation을 ? 반환한다.
ClassElement : MethodDefinition static MethodDefinition
  1. MethodDefinition에 대해 objectfalse를 인수로 하여 MethodDefinitionEvaluation을 ? 반환한다.
ClassElement : ClassStaticBlock
  1. ClassStaticBlock에 대해 object를 인수로 하여 ClassStaticBlockDefinitionEvaluation을 반환한다.
ClassElement : ;
  1. unused을 반환한다.

15.7.14 런타임 의미론: ClassDefinitionEvaluation: 함수 객체를 포함하는 정상 완료 또는 abrupt completion

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS.

Note

명세를 쉽게 하기 위해 private 메서드와 접근자는 클래스 인스턴스의 [[PrivateElements]] 슬롯에 private 필드와 함께 포함된다. 그러나 어떤 객체든 특정 클래스가 정의한 private 메서드와 접근자를 모두 가지거나 전혀 가지지 않는다. 이 기능은 구현에서 각 메서드나 접근자를 개별적으로 추적하지 않는 전략을 선택할 수 있도록 설계되었다.

예를 들어, 구현은 인스턴스 private 메서드를 해당 Private Name과 직접 연결하고, 각 객체에 대해 어떤 클래스 생성자가 그 객체를 this 값으로 실행했는지 추적할 수 있다. 객체에서 인스턴스 private 메서드를 조회하는 것은 해당 클래스 생성자가 객체 초기화에 사용되었는지 확인한 다음, Private Name에 연결된 메서드를 반환하는 것으로 구성된다.

이는 private 필드와는 다르다. 필드 초기화자가 클래스 인스턴스화 중에 throw될 수 있으므로, 개별 객체는 해당 클래스의 일부 private 필드만을 가질 수 있으며, private 필드는 일반적으로 개별적으로 추적되어야 한다.

It is defined piecewise over the following productions:

ClassTail : ClassHeritageopt { ClassBodyopt }
  1. env를 실행 중인 실행 컨텍스트의 LexicalEnvironment로 둔다.
  2. classEnvNewDeclarativeEnvironment(env)로 둔다.
  3. classBindingundefined가 아니면,
    1. classEnv.CreateImmutableBinding(classBinding, true)를 수행한다.
  4. outerPrivateEnvironment를 실행 중인 실행 컨텍스트의 PrivateEnvironment로 둔다.
  5. classPrivateEnvironmentNewPrivateEnvironment(outerPrivateEnvironment)로 둔다.
  6. ClassBody가 존재하면,
    1. ClassBody의 PrivateBoundIdentifiers의 각 String dn에 대해 다음을 수행한다:
      1. classPrivateEnvironment.[[Names]][[Description]]dnPrivate Name pn을 포함하면,
        1. 단언: 이는 getter/setter 쌍에 대해서만 가능하다.
      2. 그렇지 않으면,
        1. name[[Description]]dn인 새 Private Name으로 둔다.
        2. nameclassPrivateEnvironment.[[Names]]에 추가한다.
  7. ClassHeritage가 존재하지 않으면,
    1. protoParent%Object.prototype%로 둔다.
    2. constructorParent%Function.prototype%로 둔다.
  8. 그렇지 않으면,
    1. 실행 중인 실행 컨텍스트의 LexicalEnvironment를 classEnv로 설정한다.
    2. 참고: ClassHeritage를 평가할 때 실행 중인 실행 컨텍스트의 PrivateEnvironment는 outerPrivateEnvironment이다.
    3. superclassRefCompletion(Evaluation of ClassHeritage)로 둔다.
    4. 실행 중인 실행 컨텍스트의 LexicalEnvironment를 env로 설정한다.
    5. superclass를 ? GetValue(? superclassRef)로 둔다.
    6. superclassnull이면,
      1. protoParentnull로 둔다.
      2. constructorParent%Function.prototype%로 둔다.
    7. 그렇지 않고 IsConstructor(superclass)가 false이면,
      1. TypeError 예외를 던진다.
    8. 그렇지 않으면,
      1. protoParent를 ? Get(superclass, "prototype")로 둔다.
      2. protoParent가 Object가 아니고 null도 아니면, TypeError 예외를 던진다.
      3. constructorParentsuperclass로 둔다.
  9. protoOrdinaryObjectCreate(protoParent)로 둔다.
  10. ClassBody가 존재하지 않으면, constructorempty로 둔다.
  11. 그렇지 않으면, constructorClassBody의 ConstructorMethod로 둔다.
  12. 실행 중인 실행 컨텍스트의 LexicalEnvironment를 classEnv로 설정한다.
  13. 실행 중인 실행 컨텍스트의 PrivateEnvironment를 classPrivateEnvironment로 설정한다.
  14. constructorempty이면,
    1. defaultConstructor를 매개변수가 없고 아무것도 캡처하지 않는 새 Abstract Closure로 두고, 호출될 때 다음 단계를 수행하도록 한다:
      1. args[[Call]] 또는 [[Construct]]에 의해 이 함수에 전달된 인수의 List로 둔다.
      2. NewTarget이 undefined이면, TypeError 예외를 던진다.
      3. F를 활성 함수 객체로 둔다.
      4. F.[[ConstructorKind]]derived이면,
        1. 참고: 이 분기는 constructor(...args) { super(...args); }와 유사하게 동작한다. 가장 주목할 만한 차이점은 앞서 언급한 ECMAScript 소스 텍스트가 %Array.prototype%%Symbol.iterator% 메서드를 관찰 가능하게 호출하는 반면, 이 함수는 그렇지 않는다는 것이다.
        2. func를 ! F.[[GetPrototypeOf]]()로 둔다.
        3. IsConstructor(func)가 false이면, TypeError 예외를 던진다.
        4. result를 ? Construct(func, args, NewTarget)로 둔다.
      5. 그렇지 않으면,
        1. 참고: 이 분기는 constructor() {}와 유사하게 동작한다.
        2. result를 ? OrdinaryCreateFromConstructor(NewTarget, "%Object.prototype%")로 둔다.
      6. InitializeInstanceElements(result, F)를 수행한다.
      7. NormalCompletion(result)를 반환한다.
    2. FCreateBuiltinFunction(defaultConstructor, 0, className, « [[ConstructorKind]], [[SourceText]] », the current Realm Record, constructorParent)로 둔다.
  15. 그렇지 않으면,
    1. constructorInfo를 ! DefineMethod of constructor with arguments proto and constructorParent로 둔다.
    2. FconstructorInfo.[[Closure]]로 둔다.
    3. MakeClassConstructor(F)를 수행한다.
    4. SetFunctionName(F, className)을 수행한다.
  16. F.[[SourceText]]sourceText로 설정한다.
  17. MakeConstructor(F, false, proto)를 수행한다.
  18. ClassHeritage가 존재하면, F.[[ConstructorKind]]derived로 설정한다.
  19. DefineMethodProperty(proto, "constructor", F, false)를 수행한다.
  20. ClassBody가 존재하지 않으면, elements를 새 빈 List로 둔다.
  21. 그렇지 않으면, elementsClassBody의 NonConstructorElements로 둔다.
  22. instancePrivateMethods를 새 빈 List로 둔다.
  23. staticPrivateMethods를 새 빈 List로 둔다.
  24. instanceFields를 새 빈 List로 둔다.
  25. staticElements를 새 빈 List로 둔다.
  26. elements의 각 ClassElement e에 대해 다음을 수행한다:
    1. e의 IsStatic이 false이면,
      1. elementCompletion(ClassElementEvaluation of e with argument proto)로 둔다.
    2. 그렇지 않으면,
      1. elementCompletion(ClassElementEvaluation of e with argument F)로 둔다.
    3. elementabrupt completion이면,
      1. 실행 중인 실행 컨텍스트의 LexicalEnvironment를 env로 설정한다.
      2. 실행 중인 실행 컨텍스트의 PrivateEnvironment를 outerPrivateEnvironment로 설정한다.
      3. element를 반환한다.
    4. element를 ! element로 설정한다.
    5. elementPrivateElement이면,
      1. 단언: element.[[Kind]]method 또는 accessor 중 하나이다.
      2. e의 IsStatic이 false이면, containerinstancePrivateMethods로 둔다; 그렇지 않으면, containerstaticPrivateMethods로 둔다.
      3. container[[Key]]element.[[Key]]PrivateElement pe를 포함하면,
        1. 단언: element.[[Kind]]pe.[[Kind]]는 모두 accessor이다.
        2. element.[[Get]]undefined이면,
          1. combinedPrivateElement { [[Key]]: element.[[Key]], [[Kind]]: accessor, [[Get]]: pe.[[Get]], [[Set]]: element.[[Set]] }로 둔다.
        3. 그렇지 않으면,
          1. combinedPrivateElement { [[Key]]: element.[[Key]], [[Kind]]: accessor, [[Get]]: element.[[Get]], [[Set]]: pe.[[Set]] }로 둔다.
        4. container에서 pecombined로 대체한다.
      4. 그렇지 않으면,
        1. elementcontainer에 추가한다.
    6. 그렇지 않고 elementClassFieldDefinition Record이면,
      1. e의 IsStatic이 false이면, elementinstanceFields에 추가한다.
      2. 그렇지 않으면, elementstaticElements에 추가한다.
    7. 그렇지 않고 elementClassStaticBlockDefinition Record이면,
      1. elementstaticElements에 추가한다.
  27. 실행 중인 실행 컨텍스트의 LexicalEnvironment를 env로 설정한다.
  28. classBindingundefined가 아니면,
    1. classEnv.InitializeBinding(classBinding, F)를 수행한다.
  29. F.[[PrivateMethods]]instancePrivateMethods로 설정한다.
  30. F.[[Fields]]instanceFields로 설정한다.
  31. staticPrivateMethods의 각 PrivateElement method에 대해,
    1. PrivateMethodOrAccessorAdd(F, method)를 수행한다.
  32. staticElements의 각 요소 elementRecord에 대해,
    1. elementRecordClassFieldDefinition Record이면,
      1. resultCompletion(DefineField(F, elementRecord))로 둔다.
    2. 그렇지 않으면,
      1. 단언: elementRecordClassStaticBlockDefinition Record이다.
      2. resultCompletion(Call(elementRecord.[[BodyFunction]], F))로 둔다.
    3. resultabrupt completion이면,
      1. 실행 중인 실행 컨텍스트의 PrivateEnvironment를 outerPrivateEnvironment로 설정한다.
      2. result를 반환한다.
  33. 실행 중인 실행 컨텍스트의 PrivateEnvironment를 outerPrivateEnvironment로 설정한다.
  34. F를 반환한다.

15.7.15 런타임 의미론: BindingClassDeclarationEvaluation : 함수 객체를 포함하는 정상 완료 또는 abrupt completion

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. It is defined piecewise over the following productions:

ClassDeclaration : class BindingIdentifier ClassTail
  1. BindingIdentifier의 StringValue를 className으로 둔다.
  2. ClassDeclaration이 매칭한 소스 텍스트를 sourceText로 둔다.
  3. ClassTail에 대해 className, className, sourceText를 인수로 하여 ClassDefinitionEvaluation의 결과를 value로 둔다.
  4. 실행 컨텍스트의 LexicalEnvironment를 env로 둔다.
  5. InitializeBoundName(className, value, env)를 수행한다.
  6. value를 반환한다.
ClassDeclaration : class ClassTail
  1. ClassDeclaration이 매칭한 소스 텍스트를 sourceText로 둔다.
  2. ClassTail에 대해 undefined, "default", sourceText를 인수로 하여 ClassDefinitionEvaluation의 결과를 반환한다.
Note

ClassDeclaration : class ClassTail ExportDeclaration의 일부로만 나타나며, 바인딩 생성은 해당 생성물의 평가 동작에서 처리된다. 16.2.3.7 참고.

15.7.16 런타임 의미론: Evaluation

ClassDeclaration : class BindingIdentifier ClassTail
  1. ClassDeclaration에 대해 ? BindingClassDeclarationEvaluation을 수행한다.
  2. empty를 반환한다.
Note

ClassDeclaration : class ClassTail ExportDeclaration의 일부로만 나타나며 직접 평가되지 않는다.

ClassExpression : class ClassTail
  1. ClassExpression이 매칭한 소스 텍스트를 sourceText로 둔다.
  2. ClassTail에 대해 undefined, "", sourceText를 인수로 하여 ClassDefinitionEvaluation의 결과를 반환한다.
ClassExpression : class BindingIdentifier ClassTail
  1. BindingIdentifier의 StringValue를 className으로 둔다.
  2. ClassExpression이 매칭한 소스 텍스트를 sourceText로 둔다.
  3. ClassTail에 대해 className, className, sourceText를 인수로 하여 ClassDefinitionEvaluation의 결과를 반환한다.
ClassElementName : PrivateIdentifier
  1. PrivateIdentifier의 StringValue를 privateIdentifier로 둔다.
  2. 실행 컨텍스트의 PrivateEnvironment를 privateEnvRec로 둔다.
  3. privateEnvRec.[[Names]]names로 둔다.
  4. 단언: names의 정확히 하나의 요소가 [[Description]]privateIdentifierPrivate Name임.
  5. privateNamenames[[Description]]privateIdentifierPrivate Name으로 둔다.
  6. privateName을 반환한다.
ClassStaticBlockStatementList : [empty]
  1. undefined를 반환한다.

15.8 Async 함수 정의

구문

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[Await] 파라미터가 있을 때 AwaitExpression의 키워드로 파싱된다. [Await] 파라미터는 아래 문맥의 최상위에 있지만, FunctionBody 같은 비단말에 따라 부재할 수 있다:

Script가 구문 목표 기호일 때, [Await] 파라미터가 없으면 await는 식별자로 파싱될 수 있다. 해당 문맥은 다음과 같다:

Note 2

YieldExpression과 달리 AwaitExpression의 피연산자를 생략하면 문법 오류이다. 반드시 await할 대상이 있어야 한다.

15.8.1 정적 의미론: 조기 오류

AsyncMethod : async ClassElementName ( UniqueFormalParameters ) { AsyncFunctionBody } AsyncFunctionDeclaration : async function BindingIdentifier ( FormalParameters ) { AsyncFunctionBody } async function ( FormalParameters ) { AsyncFunctionBody } AsyncFunctionExpression : async function BindingIdentifieropt ( FormalParameters ) { AsyncFunctionBody }

15.8.2 런타임 의미론: InstantiateAsyncFunctionObject: ECMAScript 함수 객체

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. It is defined piecewise over the following productions:

AsyncFunctionDeclaration : async function BindingIdentifier ( FormalParameters ) { AsyncFunctionBody }
  1. nameBindingIdentifier의 StringValue로 둔다.
  2. sourceTextAsyncFunctionDeclaration이 매칭한 소스 텍스트로 둔다.
  3. FOrdinaryFunctionCreate(%AsyncFunction.prototype%, sourceText, FormalParameters, AsyncFunctionBody, non-lexical-this, env, privateEnv)로 둔다.
  4. SetFunctionName(F, name)을 수행한다.
  5. F를 반환한다.
AsyncFunctionDeclaration : async function ( FormalParameters ) { AsyncFunctionBody }
  1. sourceTextAsyncFunctionDeclaration이 매칭한 소스 텍스트로 둔다.
  2. FOrdinaryFunctionCreate(%AsyncFunction.prototype%, sourceText, FormalParameters, AsyncFunctionBody, non-lexical-this, env, privateEnv)로 둔다.
  3. SetFunctionName(F, "default")를 수행한다.
  4. F를 반환한다.

15.8.3 런타임 의미론: InstantiateAsyncFunctionExpression: ECMAScript 함수 객체

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. It is defined piecewise over the following productions:

AsyncFunctionExpression : async function ( FormalParameters ) { AsyncFunctionBody }
  1. name이 없다면 name = ""로 설정한다.
  2. env를 실행 중 실행 컨텍스트의 LexicalEnvironment로 둔다.
  3. privateEnv를 실행 중 실행 컨텍스트의 PrivateEnvironment로 둔다.
  4. sourceTextAsyncFunctionExpression이 매칭한 소스 텍스트로 둔다.
  5. closureOrdinaryFunctionCreate(%AsyncFunction.prototype%, sourceText, FormalParameters, AsyncFunctionBody, non-lexical-this, env, privateEnv)로 둔다.
  6. SetFunctionName(closure, name)을 수행한다.
  7. closure를 반환한다.
AsyncFunctionExpression : async function BindingIdentifier ( FormalParameters ) { AsyncFunctionBody }
  1. 단언: name은 없다.
  2. nameBindingIdentifier의 StringValue로 둔다.
  3. outerEnv를 실행 중 실행 컨텍스트의 LexicalEnvironment로 둔다.
  4. funcEnvNewDeclarativeEnvironment(outerEnv)로 둔다.
  5. funcEnv.CreateImmutableBinding(name, false)를 수행한다.
  6. privateEnv를 실행 중 실행 컨텍스트의 PrivateEnvironment로 둔다.
  7. sourceTextAsyncFunctionExpression이 매칭한 소스 텍스트로 둔다.
  8. closureOrdinaryFunctionCreate(%AsyncFunction.prototype%, sourceText, FormalParameters, AsyncFunctionBody, non-lexical-this, funcEnv, privateEnv)로 둔다.
  9. SetFunctionName(closure, name)을 수행한다.
  10. funcEnv.InitializeBinding(name, closure)를 수행한다.
  11. closure를 반환한다.
Note

AsyncFunctionExpressionBindingIdentifier는 그 AsyncFunctionBody 내부에서 참조되어 함수가 재귀적으로 자신을 호출할 수 있게 한다. 하지만 FunctionDeclaration과 달리 AsyncFunctionExpressionBindingIdentifier는 외부 스코프에서 참조할 수 없고 영향을 주지 않는다.

15.8.4 런타임 의미론: EvaluateAsyncFunctionBody: return completion

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. It is defined piecewise over the following productions:

AsyncFunctionBody : FunctionBody
  1. promiseCapability를 ! NewPromiseCapability(%Promise%)로 둔다.
  2. completionCompletion(FunctionDeclarationInstantiation(functionObject, argumentsList))로 둔다.
  3. completionabrupt completion이면
    1. Call(promiseCapability.[[Reject]], undefined, « completion.[[Value]] »)를 수행한다.
  4. 그렇지 않으면
    1. AsyncFunctionStart(promiseCapability, FunctionBody)를 수행한다.
  5. ReturnCompletion(promiseCapability.[[Promise]])를 반환한다.

15.8.5 런타임 의미론: 평가

AsyncFunctionExpression : async function BindingIdentifieropt ( FormalParameters ) { AsyncFunctionBody }
  1. AsyncFunctionExpression의 InstantiateAsyncFunctionExpression을 반환한다.
AwaitExpression : await UnaryExpression
  1. exprRefUnaryExpression 평가 결과(?)로 둔다.
  2. value를 ? GetValue(exprRef)로 둔다.
  3. Await(value)를 반환한다.

15.9 Async 화살표 함수 정의

구문

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]

보충 구문

생성물 인스턴스
AsyncArrowFunction : CoverCallExpressionAndAsyncArrowHead => AsyncConciseBody
를 처리할 때 CoverCallExpressionAndAsyncArrowHead의 해석은 다음 구문을 사용해 정밀화된다:

AsyncArrowHead : async [no LineTerminator here] ArrowFormalParameters[~Yield, +Await]

15.9.1 정적 의미론: 조기 오류

AsyncArrowFunction : async AsyncArrowBindingIdentifier => AsyncConciseBody AsyncArrowFunction : CoverCallExpressionAndAsyncArrowHead => AsyncConciseBody

15.9.2 정적 의미론: AsyncConciseBodyContainsUseStrict: Boolean

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. It is defined piecewise over the following productions:

AsyncConciseBody : ExpressionBody
  1. false를 반환한다.
AsyncConciseBody : { AsyncFunctionBody }
  1. FunctionBodyContainsUseStrict(AsyncFunctionBody)를 반환한다.

15.9.3 런타임 의미론: EvaluateAsyncConciseBody: return completion

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. It is defined piecewise over the following productions:

AsyncConciseBody : ExpressionBody
  1. promiseCapability를 ! NewPromiseCapability(%Promise%)로 둔다.
  2. completionCompletion(FunctionDeclarationInstantiation(functionObject, argumentsList))로 둔다.
  3. completionabrupt completion이면
    1. Call(promiseCapability.[[Reject]], undefined, « completion.[[Value]] »)를 수행한다.
  4. 그렇지 않으면
    1. AsyncFunctionStart(promiseCapability, ExpressionBody)를 수행한다.
  5. ReturnCompletion(promiseCapability.[[Promise]])를 반환한다.

15.9.4 런타임 의미론: InstantiateAsyncArrowFunctionExpression: ECMAScript 함수 객체

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. It is defined piecewise over the following productions:

AsyncArrowFunction : async AsyncArrowBindingIdentifier => AsyncConciseBody
  1. name이 없으면 name = ""로 설정한다.
  2. env를 실행 중 실행 컨텍스트의 LexicalEnvironment로 둔다.
  3. privateEnv를 실행 중 실행 컨텍스트의 PrivateEnvironment로 둔다.
  4. sourceTextAsyncArrowFunction이 매칭한 소스 텍스트로 둔다.
  5. parametersAsyncArrowBindingIdentifier로 둔다.
  6. closureOrdinaryFunctionCreate(%AsyncFunction.prototype%, sourceText, parameters, AsyncConciseBody, lexical-this, env, privateEnv)로 둔다.
  7. SetFunctionName(closure, name)을 수행한다.
  8. closure를 반환한다.
AsyncArrowFunction : CoverCallExpressionAndAsyncArrowHead => AsyncConciseBody
  1. name이 없으면 name = ""로 설정한다.
  2. env를 실행 중 실행 컨텍스트의 LexicalEnvironment로 둔다.
  3. privateEnv를 실행 중 실행 컨텍스트의 PrivateEnvironment로 둔다.
  4. sourceTextAsyncArrowFunction이 매칭한 소스 텍스트로 둔다.
  5. headCoverCallExpressionAndAsyncArrowHead가 커버하는 AsyncArrowHead로 둔다.
  6. parametersheadArrowFormalParameters로 둔다.
  7. closureOrdinaryFunctionCreate(%AsyncFunction.prototype%, sourceText, parameters, AsyncConciseBody, lexical-this, env, privateEnv)로 둔다.
  8. SetFunctionName(closure, name)을 수행한다.
  9. closure를 반환한다.

15.9.5 런타임 의미론: 평가

AsyncArrowFunction : async AsyncArrowBindingIdentifier => AsyncConciseBody CoverCallExpressionAndAsyncArrowHead => AsyncConciseBody
  1. AsyncArrowFunction의 InstantiateAsyncArrowFunctionExpression을 반환한다.

15.10 꼬리 위치 호출

15.10.1 정적 의미론: IsInTailPosition( call: CallExpression Parse Node 또는 MemberExpression Parse Node 또는 OptionalChain Parse Node, ): Boolean

The abstract operation UNKNOWN takes UNPARSEABLE ARGUMENTS. It performs the following steps when called:

  1. IsStrict(call)이 false이면 false를 반환한다.
  2. callFunctionBody, ConciseBody, AsyncConciseBody 중 어느 것에도 포함되어 있지 않으면 false를 반환한다.
  3. bodycall을 가장 가까이 포함하는 FunctionBody, ConciseBody, AsyncConciseBody로 둔다.
  4. bodyGeneratorBodyFunctionBody이면 false를 반환한다.
  5. bodyAsyncFunctionBodyFunctionBody이면 false를 반환한다.
  6. bodyAsyncGeneratorBodyFunctionBody이면 false를 반환한다.
  7. bodyAsyncConciseBody이면 false를 반환한다.
  8. body의 HasCallInTailPosition 결과를 call 인수로 반환한다.
Note

꼬리 위치 호출은 엄격 모드 코드에서만 정의된다. 이는 비표준 언어 확장( 10.2.4 참조 )으로 인해 호출자 컨텍스트 체인을 관찰할 수 있게 되기 때문이다.

15.10.2 정적 의미론: HasCallInTailPosition: Boolean

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS.

Note 1

call은 소스 텍스트의 특정 범위를 나타내는 Parse Node이다. 아래 알고리즘에서 call을 다른 Parse Node와 비교할 때는 둘이 동일한 소스 텍스트를 나타내는지 여부를 검사한다.

Note 2

return GetValue로 바로 이어지는 잠재적 꼬리 위치 호출도 꼬리 위치 호출이 될 수 있다. 함수 호출은 Reference Record를 반환할 수 없으므로, 이런 GetValue 연산은 항상 실제 함수 호출 결과와 동일한 값을 반환한다.

It is defined piecewise over the following productions:

StatementList : StatementList StatementListItem
  1. StatementList의 HasCallInTailPosition 결과를 call 인수로 has로 둔다.
  2. hastrue이면 true를 반환한다.
  3. StatementListItem의 HasCallInTailPosition 결과를 call 인수로 반환한다.
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. 첫 번째 Statement의 HasCallInTailPosition 결과를 call 인수로 has로 둔다.
  2. hastrue이면 true를 반환한다.
  3. 두 번째 Statement의 HasCallInTailPosition 결과를 call 인수로 반환한다.
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. Statement의 HasCallInTailPosition 결과를 call 인수로 반환한다.
LabelledStatement : LabelIdentifier : LabelledItem
  1. LabelledItem의 HasCallInTailPosition 결과를 call 인수로 반환한다.
ReturnStatement : return Expression ;
  1. Expression의 HasCallInTailPosition 결과를 call 인수로 반환한다.
SwitchStatement : switch ( Expression ) CaseBlock
  1. CaseBlock의 HasCallInTailPosition 결과를 call 인수로 반환한다.
CaseBlock : { CaseClausesopt DefaultClause CaseClausesopt }
  1. hasfalse로 둔다.
  2. 첫 번째 CaseClauses가 있으면, 그 HasCallInTailPosition 결과를 call 인수로 has로 둔다.
  3. hastrue이면 true를 반환한다.
  4. DefaultClause의 HasCallInTailPosition 결과를 call 인수로 has로 둔다.
  5. hastrue이면 true를 반환한다.
  6. 두 번째 CaseClauses가 있으면, 그 HasCallInTailPosition 결과를 call 인수로 has로 둔다.
  7. has를 반환한다.
CaseClauses : CaseClauses CaseClause
  1. CaseClauses의 HasCallInTailPosition 결과를 call 인수로 has로 둔다.
  2. hastrue이면 true를 반환한다.
  3. CaseClause의 HasCallInTailPosition 결과를 call 인수로 반환한다.
CaseClause : case Expression : StatementListopt DefaultClause : default : StatementListopt
  1. StatementList가 있으면 그 HasCallInTailPosition 결과를 call 인수로 반환한다.
  2. false를 반환한다.
TryStatement : try Block Catch
  1. Catch의 HasCallInTailPosition 결과를 call 인수로 반환한다.
TryStatement : try Block Finally try Block Catch Finally
  1. Finally의 HasCallInTailPosition 결과를 call 인수로 반환한다.
Catch : catch ( CatchParameter ) Block
  1. Block의 HasCallInTailPosition 결과를 call 인수로 반환한다.
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 AwaitExpression 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. AssignmentExpression의 HasCallInTailPosition 결과를 call 인수로 반환한다.
ConditionalExpression : ShortCircuitExpression ? AssignmentExpression : AssignmentExpression
  1. 첫 번째 AssignmentExpression의 HasCallInTailPosition 결과를 call 인수로 has로 둔다.
  2. hastrue이면 true를 반환한다.
  3. 두 번째 AssignmentExpression의 HasCallInTailPosition 결과를 call 인수로 반환한다.
LogicalANDExpression : LogicalANDExpression && BitwiseORExpression
  1. BitwiseORExpression의 HasCallInTailPosition 결과를 call 인수로 반환한다.
LogicalORExpression : LogicalORExpression || LogicalANDExpression
  1. LogicalANDExpression의 HasCallInTailPosition 결과를 call 인수로 반환한다.
CoalesceExpression : CoalesceExpressionHead ?? BitwiseORExpression
  1. BitwiseORExpression의 HasCallInTailPosition 결과를 call 인수로 반환한다.
CallExpression : CoverCallExpressionAndAsyncArrowHead CallExpression Arguments CallExpression TemplateLiteral
  1. CallExpressioncall이면 true를 반환한다.
  2. false를 반환한다.
OptionalExpression : MemberExpression OptionalChain CallExpression OptionalChain OptionalExpression OptionalChain
  1. OptionalChain의 HasCallInTailPosition 결과를 call 인수로 반환한다.
OptionalChain : ?. [ Expression ] ?. IdentifierName ?. PrivateIdentifier OptionalChain [ Expression ] OptionalChain . IdentifierName OptionalChain . PrivateIdentifier
  1. false를 반환한다.
OptionalChain : ?. Arguments OptionalChain Arguments
  1. OptionalChaincall이면 true를 반환한다.
  2. false를 반환한다.
MemberExpression : MemberExpression TemplateLiteral
  1. MemberExpressioncall이면 true를 반환한다.
  2. false를 반환한다.
PrimaryExpression : CoverParenthesizedExpressionAndArrowParameterList
  1. exprCoverParenthesizedExpressionAndArrowParameterList가 커버하는 ParenthesizedExpression으로 둔다.
  2. expr의 HasCallInTailPosition 결과를 call 인수로 반환한다.
ParenthesizedExpression : ( Expression )
  1. Expression의 HasCallInTailPosition 결과를 call 인수로 반환한다.

15.10.3 PrepareForTailCall ( )

The abstract operation PrepareForTailCall takes no arguments and returns unused. It performs the following steps when called:

  1. 현재 실행 컨텍스트는 이후 ECMAScript 코드 또는 내장 함수의 평가에 사용되지 않을 것임을 단언한다. 이 추상 연산 이후 Call을 호출하면 해당 평가 전에 새 실행 컨텍스트가 생성되고 push된다.
  2. 현재 실행 컨텍스트와 관련된 모든 리소스를 폐기한다.
  3. unused를 반환한다.

꼬리 위치 호출은 현재 실행 중인 함수 실행 컨텍스트와 관련된 임시 내부 리소스를 호출 대상 함수 전에 해제하거나, 해당 함수에 재사용해야 한다.

Note

예를 들어, 꼬리 위치 호출은 대상 함수의 activation record가 호출 함수의 activation record보다 커지는 만큼만 스택 크기를 증가시켜야 한다. 대상 함수의 activation record가 더 작다면, 전체 스택 크기는 줄어들어야 한다.

16 ECMAScript 언어: 스크립트와 모듈

16.1 스크립트

구문

Script : ScriptBodyopt ScriptBody : StatementList[~Yield, ~Await, ~Return]

16.1.1 정적 의미론: 조기 오류

Script : ScriptBody
  • ScriptBody의 LexicallyDeclaredNames가 중복 항목을 포함하면 구문 오류이다.
  • ScriptBody의 LexicallyDeclaredNames의 어떤 요소가 ScriptBody의 VarDeclaredNames에도 나타나면 구문 오류이다.
ScriptBody : StatementList
  • super를 포함한 소스 텍스트가 직접 eval에 의해 처리되는 eval 코드가 아닌 한, StatementListsuper를 포함하면 구문 오류이다. 직접 eval 내의 super에 대한 추가 조기 오류 규칙은 19.2.1.1에 정의되어 있다.
  • NewTarget을 포함한 소스 텍스트가 직접 eval에 의해 처리되는 eval 코드가 아닌 한, StatementListNewTarget을 포함하면 구문 오류이다. 직접 eval에서 NewTarget에 대한 추가 조기 오류 규칙은 19.2.1.1에 정의되어 있다.
  • 인수 « »를 사용한 StatementList의 ContainsDuplicateLabels가 true이면 구문 오류이다.
  • 인수 « »를 사용한 StatementList의 ContainsUndefinedBreakTarget이 true이면 구문 오류이다.
  • 인수 « »와 « »를 사용한 StatementList의 ContainsUndefinedContinueTarget이 true이면 구문 오류이다.
  • ScriptBody를 포함한 소스 텍스트가 직접 eval에 의해 처리되는 eval 코드가 아닌 한, 인수 « »를 사용한 StatementList의 AllPrivateIdentifiersValid가 false이면 구문 오류이다.

16.1.2 정적 의미론: ScriptIsStrict : Boolean

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. It is defined piecewise over the following productions:

Script : ScriptBodyopt
  1. ScriptBody가 존재하고 ScriptBodyDirective PrologueUse Strict Directive를 포함하면 true를 반환하고, 그렇지 않으면 false를 반환한다.

16.1.3 런타임 의미론: 평가

Script : [empty]
  1. undefined를 반환한다.

16.1.4 스크립트 레코드

스크립트 레코드는 평가되는 스크립트에 대한 정보를 캡슐화한다. 각 스크립트 레코드Table 37에 나열된 필드를 포함한다.

Table 37: 스크립트 레코드 필드
필드 이름 값 타입 의미
[[Realm]] Realm Record 이 스크립트가 생성된 영역.
[[ECMAScriptCode]] Script Parse Node 이 스크립트의 소스 텍스트를 파싱한 결과.
[[LoadedModules]] LoadedModuleRequest Records의 리스트 이 스크립트가 가져온 지정자 문자열에서 해결된 Module Record로의 맵. 리스트는 ModuleRequestsEqual(r1, r2)이 true인 서로 다른 Records r1r2를 두 개 포함하지 않는다.
[[HostDefined]] anything (기본값은 empty) 스크립트와 추가 정보를 연결해야 하는 호스트 환경에서 사용하기 위해 예약된 필드.

16.1.5 ParseScript ( sourceText, realm, hostDefined )

The abstract operation ParseScript takes arguments sourceText (ECMAScript 소스 텍스트), realm (Realm Record), and hostDefined (anything) and returns Script Record 또는 SyntaxError 객체의 비어있지 않은 리스트. It performs the following steps when called:

  1. script를 ParseText(sourceText, Script)로 둔다.
  2. script가 오류의 리스트이면 script를 반환한다.
  3. Script Record { [[Realm]]: realm, [[ECMAScriptCode]]: script, [[LoadedModules]]: « », [[HostDefined]]: hostDefined }를 반환한다.
Note

구현은 해당 스크립트 소스 텍스트에 대해 ParseScript를 평가하기 전에 스크립트 소스 텍스트를 파싱하고 조기 오류 조건을 분석할 수 있다. 그러나 오류 보고는 이 명세가 실제로 해당 소스 텍스트에 대해 ParseScript를 수행하는 시점까지 연기되어야 한다.

16.1.6 ScriptEvaluation ( scriptRecord )

The abstract operation ScriptEvaluation takes argument scriptRecord (Script Record) and returns ECMAScript 언어 값을 포함하는 정상 완료 또는 abrupt completion. It performs the following steps when called:

  1. globalEnvscriptRecord.[[Realm]].[[GlobalEnv]]로 둔다.
  2. scriptContext를 새로운 ECMAScript 코드 실행 컨텍스트로 둔다.
  3. scriptContext의 Function을 null로 설정한다.
  4. scriptContextRealmscriptRecord.[[Realm]]으로 설정한다.
  5. scriptContext의 ScriptOrModule을 scriptRecord로 설정한다.
  6. scriptContext의 VariableEnvironment를 globalEnv로 설정한다.
  7. scriptContext의 LexicalEnvironment를 globalEnv로 설정한다.
  8. scriptContext의 PrivateEnvironment를 null로 설정한다.
  9. 실행 중인 실행 컨텍스트를 일시 중단한다.
  10. scriptContext를 실행 컨텍스트 스택에 푸시한다; scriptContext가 이제 실행 중인 실행 컨텍스트이다.
  11. scriptscriptRecord.[[ECMAScriptCode]]로 둔다.
  12. resultCompletion(GlobalDeclarationInstantiation(script, globalEnv))로 둔다.
  13. result가 정상 완료이면
    1. resultCompletion(Evaluation of script)로 설정한다.
    2. result가 정상 완료이고 result.[[Value]]empty이면
      1. resultNormalCompletion(undefined)로 설정한다.
  14. scriptContext를 일시 중단하고 실행 컨텍스트 스택에서 제거한다.
  15. 단언: 실행 컨텍스트 스택이 비어있지 않다.
  16. 이제 실행 컨텍스트 스택의 맨 위에 있는 컨텍스트를 실행 중인 실행 컨텍스트로 재개한다.
  17. result를 반환한다.

16.1.7 GlobalDeclarationInstantiation ( script, env )

The abstract operation GlobalDeclarationInstantiation takes arguments script (Script Parse Node) and env (Global Environment Record) and returns unused를 포함하는 정상 완료 또는 throw completion.

Note 1

스크립트 평가를 위한 실행 컨텍스트가 설정될 때, 선언은 현재 전역 환경에서 인스턴스화된다. 코드에서 선언된 각 전역 바인딩이 인스턴스화된다.

호출될 때 다음 단계를 수행한다:

  1. lexNamesscript의 LexicallyDeclaredNames로 둔다.
  2. varNamesscript의 VarDeclaredNames로 둔다.
  3. lexNames의 각 요소 name에 대해
    1. HasLexicalDeclaration(env, name)이 true이면 SyntaxError 예외를 던진다.
    2. hasRestrictedGlobal을 ? HasRestrictedGlobalProperty(env, name)로 둔다.
    3. 참고: 전역 varfunction 바인딩(비-strict 직접 eval에 의해 도입된 것들을 제외하고)은 non-configurable이므로 제한된 전역 속성이다.
    4. hasRestrictedGlobaltrue이면 SyntaxError 예외를 던진다.
  4. varNames의 각 요소 name에 대해
    1. HasLexicalDeclaration(env, name)이 true이면 SyntaxError 예외를 던진다.
  5. varDeclarationsscript의 VarScopedDeclarations로 둔다.
  6. functionsToInitialize를 새로운 빈 리스트로 둔다.
  7. declaredFunctionNames를 새로운 빈 리스트로 둔다.
  8. varDeclarations의 각 요소 d에 대해 역순으로
    1. dVariableDeclaration, ForBinding, 또는 BindingIdentifier가 아니면
      1. 단언: dFunctionDeclaration, GeneratorDeclaration, AsyncFunctionDeclaration, 또는 AsyncGeneratorDeclaration 중 하나이다.
      2. 참고: 같은 이름에 대해 여러 함수 선언이 있으면 마지막 선언이 사용된다.
      3. fnd의 BoundNames의 유일한 요소로 둔다.
      4. declaredFunctionNamesfn을 포함하지 않으면
        1. fnDefinable을 ? CanDeclareGlobalFunction(env, fn)로 둔다.
        2. fnDefinablefalse이면 TypeError 예외를 던진다.
        3. fndeclaredFunctionNames에 추가한다.
        4. dfunctionsToInitialize의 첫 번째 요소로 삽입한다.
  9. declaredVarNames를 새로운 빈 리스트로 둔다.
  10. varDeclarations의 각 요소 d에 대해
    1. dVariableDeclaration, ForBinding, 또는 BindingIdentifier이면
      1. d의 BoundNames의 각 String vn에 대해
        1. declaredFunctionNamesvn을 포함하지 않으면
          1. vnDefinable을 ? CanDeclareGlobalVar(env, vn)로 둔다.
          2. vnDefinablefalse이면 TypeError 예외를 던진다.
          3. declaredVarNamesvn을 포함하지 않으면
            1. vndeclaredVarNames에 추가한다.
  11. 참고: 전역 객체일반 객체인 경우 이 알고리즘 단계 이후에는 비정상적인 종료가 발생하지 않는다. 그러나 전역 객체가 Proxy exotic 객체인 경우 다음 단계 중 일부에서 비정상적인 종료를 유발하는 동작을 보일 수 있다.
  12. Normative Optional
    호스트가 웹 브라우저이거나 그렇지 않으면 블록 수준 함수 선언 웹 레거시 호환 의미를 지원하면
    1. strictscript의 ScriptIsStrict로 둔다.
    2. strictfalse이면
      1. declaredFunctionOrVarNamesdeclaredFunctionNamesdeclaredVarNames의 리스트 연결로 둔다.
      2. scriptx를 포함하는 것이 trueBlock, CaseClause, 또는 DefaultClause xStatementList에 직접 포함된 각 FunctionDeclaration f에 대해
        1. FfBindingIdentifier의 StringValue로 둔다.
        2. FunctionDeclaration fFBindingIdentifier로 가진 VariableStatement로 대체하는 것이 script에 대해 조기 오류를 생성하지 않으면
          1. HasLexicalDeclaration(env, F)가 false이면
            1. fnDefinable을 ? CanDeclareGlobalVar(env, F)로 둔다.
            2. fnDefinabletrue이면
              1. 참고: F에 대한 var 바인딩은 VarDeclaredName도 아니고 다른 FunctionDeclaration의 이름도 아닌 경우에만 여기서 인스턴스화된다.
              2. declaredFunctionOrVarNamesF를 포함하지 않으면
                1. CreateGlobalVarBinding(env, F, false)를 수행한다.
                2. FdeclaredFunctionOrVarNames에 추가한다.
              3. FunctionDeclaration f가 평가될 때, 15.2.6에서 제공하는 FunctionDeclaration Evaluation 알고리즘 대신 다음 단계를 수행한다:
                1. gEnv를 실행 중인 실행 컨텍스트의 VariableEnvironment로 둔다.
                2. bEnv를 실행 중인 실행 컨텍스트의 LexicalEnvironment로 둔다.
                3. fObj를 ! bEnv.GetBindingValue(F, false)로 둔다.
                4. gEnv.SetMutableBinding(F, fObj, false)를 수행한다.
                5. unused를 반환한다.
  13. lexDeclarationsscript의 LexicallyScopedDeclarations로 둔다.
  14. privateEnvnull로 둔다.
  15. lexDeclarations의 각 요소 d에 대해
    1. 참고: 어휘적으로 선언된 이름은 여기서만 인스턴스화되고 초기화되지 않는다.
    2. d의 BoundNames의 각 요소 dn에 대해
      1. d의 IsConstantDeclaration이 true이면
        1. env.CreateImmutableBinding(dn, true)를 수행한다.
      2. 그렇지 않으면
        1. env.CreateMutableBinding(dn, false)를 수행한다.
  16. functionsToInitialize의 각 Parse Node f에 대해
    1. fnf의 BoundNames의 유일한 요소로 둔다.
    2. fo를 인수 envprivateEnv를 사용한 f의 InstantiateFunctionObject로 둔다.
    3. CreateGlobalFunctionBinding(env, fn, fo, false)를 수행한다.
  17. declaredVarNames의 각 String vn에 대해
    1. CreateGlobalVarBinding(env, vn, false)를 수행한다.
  18. unused를 반환한다.
Note 2

16.1.1에 명시된 조기 오류는 function/var 선언과 let/const/class 선언 간의 이름 충돌뿐만 아니라 단일 Script 내에 포함된 선언에 대한 let/const/class 바인딩의 재선언을 방지한다. 그러나 둘 이상의 Script에 걸친 이러한 충돌과 재선언은 GlobalDeclarationInstantiation 중에 런타임 오류로 감지된다. 이러한 오류가 감지되면 스크립트에 대해 바인딩이 인스턴스화되지 않는다. 그러나 전역 객체가 Proxy exotic 객체를 사용하여 정의된 경우 충돌하는 선언에 대한 런타임 테스트가 신뢰할 수 없어 abrupt completion과 일부 전역 선언이 인스턴스화되지 않을 수 있다. 이런 경우 Script의 코드는 평가되지 않는다.

명시적인 var 또는 function 선언과 달리, 전역 객체에서 직접 생성된 속성은 let/const/class 선언에 의해 가려질 수 있는 전역 바인딩을 만든다.

16.2 모듈

구문

Module : ModuleBodyopt ModuleBody : ModuleItemList ModuleItemList : ModuleItem ModuleItemList ModuleItem ModuleItem : ImportDeclaration ExportDeclaration StatementListItem[~Yield, +Await, ~Return] ModuleExportName : IdentifierName StringLiteral

16.2.1 모듈 의미론

16.2.1.1 정적 의미론: 조기 오류

ModuleBody : ModuleItemList
  • ModuleItemList의 LexicallyDeclaredNames가 중복 항목을 포함하면 구문 오류이다.
  • ModuleItemList의 LexicallyDeclaredNames의 어떤 요소가 ModuleItemList의 VarDeclaredNames에도 나타나면 구문 오류이다.
  • ModuleItemList의 ExportedNames가 중복 항목을 포함하면 구문 오류이다.
  • ModuleItemList의 ExportedBindings의 어떤 요소가 ModuleItemList의 VarDeclaredNames 또는 LexicallyDeclaredNames에 나타나지 않으면 구문 오류이다.
  • ModuleItemListsuper를 포함하면 구문 오류이다.
  • ModuleItemListNewTarget을 포함하면 구문 오류이다.
  • 인수 « »를 사용한 ModuleItemList의 ContainsDuplicateLabels가 true이면 구문 오류이다.
  • 인수 « »를 사용한 ModuleItemList의 ContainsUndefinedBreakTarget이 true이면 구문 오류이다.
  • 인수 « »와 « »를 사용한 ModuleItemList의 ContainsUndefinedContinueTarget이 true이면 구문 오류이다.
  • 인수 « »를 사용한 ModuleItemList의 AllPrivateIdentifiersValid가 false이면 구문 오류이다.
Note

중복된 ExportedNames 규칙은 ModuleBody 내에서 여러 export default ExportDeclaration 항목이 구문 오류임을 의미한다. 충돌하거나 중복된 선언과 관련된 추가 오류 조건은 Module 평가 전에 모듈 링킹 중에 확인된다. 이러한 오류가 감지되면 Module은 평가되지 않는다.

ModuleExportName : StringLiteral

16.2.1.2 정적 의미론: ImportedLocalNames ( importEntries: ImportEntry Records의 리스트, ): 문자열의 리스트

The abstract operation UNKNOWN takes UNPARSEABLE ARGUMENTS. It performs the following steps when called:

  1. localNames를 새로운 빈 리스트로 둔다.
  2. importEntries의 각 ImportEntry Record i에 대해
    1. i.[[LocalName]]localNames에 추가한다.
  3. localNames를 반환한다.

16.2.1.3 ModuleRequest 레코드

ModuleRequest 레코드는 주어진 가져오기 속성을 가진 모듈을 가져오는 요청을 나타낸다. 다음 필드들로 구성된다:

Table 38: ModuleRequest 레코드 필드
필드 이름 값 타입 의미
[[Specifier]] 문자열 모듈 지정자
[[Attributes]] ImportAttribute Records의 리스트 가져오기 속성

LoadedModuleRequest 레코드는 모듈을 가져오는 요청과 결과 Module Record를 함께 나타낸다. 표 Table 38에 정의된 동일한 필드들과 [[Module]] 필드의 추가로 구성된다:

Table 39: LoadedModuleRequest 레코드 필드
필드 이름 값 타입 의미
[[Specifier]] 문자열 모듈 지정자
[[Attributes]] ImportAttribute Records의 리스트 가져오기 속성
[[Module]] Module Record 이 모듈 요청에 해당하는 로드된 모듈

ImportAttribute 레코드는 다음 필드들로 구성된다:

Table 40: ImportAttribute 레코드 필드
필드 이름 값 타입 의미
[[Key]] 문자열 속성 키
[[Value]] 문자열 속성 값

16.2.1.3.1 ModuleRequestsEqual ( left, right )

The abstract operation ModuleRequestsEqual takes arguments left (ModuleRequest Record 또는 LoadedModuleRequest Record) and right (ModuleRequest Record 또는 LoadedModuleRequest Record) and returns Boolean. It performs the following steps when called:

  1. left.[[Specifier]]right.[[Specifier]]와 같지 않으면 false를 반환한다.
  2. leftAttrsleft.[[Attributes]]로 둔다.
  3. rightAttrsright.[[Attributes]]로 둔다.
  4. leftAttrsCountleftAttrs의 요소 개수로 둔다.
  5. rightAttrsCountrightAttrs의 요소 개수로 둔다.
  6. leftAttrsCountrightAttrsCount이면 false를 반환한다.
  7. leftAttrs의 각 ImportAttribute Record l에 대해
    1. rightAttrsl.[[Key]]r.[[Key]]이고 l.[[Value]]r.[[Value]]인 ImportAttribute Record r을 포함하지 않으면 false를 반환한다.
  8. true를 반환한다.

16.2.1.4 정적 의미론: ModuleRequests : ModuleRequest Records의 리스트

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. It is defined piecewise over the following productions:

Module : [empty]
  1. 새로운 빈 리스트를 반환한다.
ModuleItemList : ModuleItem
  1. ModuleItem의 ModuleRequests를 반환한다.
ModuleItemList : ModuleItemList ModuleItem
  1. requestsModuleItemList의 ModuleRequests로 둔다.
  2. additionalRequestsModuleItem의 ModuleRequests로 둔다.
  3. additionalRequests의 각 ModuleRequest Record mr에 대해
    1. requestsModuleRequestsEqual(mr, mr2)이 true인 ModuleRequest Record mr2를 포함하지 않으면
      1. mrrequests에 추가한다.
  4. requests를 반환한다.
ModuleItem : StatementListItem
  1. 새로운 빈 리스트를 반환한다.
ImportDeclaration : import ImportClause FromClause ;
  1. specifierFromClause의 SV로 둔다.
  2. ModuleRequest Record { [[Specifier]]: specifier, [[Attributes]]: « » }가 유일한 요소인 리스트를 반환한다.
ImportDeclaration : import ImportClause FromClause WithClause ;
  1. specifierFromClause의 SV로 둔다.
  2. attributesWithClause의 WithClauseToAttributes로 둔다.
  3. ModuleRequest Record { [[Specifier]]: specifier, [[Attributes]]: attributes }가 유일한 요소인 리스트를 반환한다.
ImportDeclaration : import ModuleSpecifier ;
  1. specifierModuleSpecifier의 SV로 둔다.
  2. ModuleRequest Record { [[Specifier]]: specifier, [[Attributes]]: « » }가 유일한 요소인 리스트를 반환한다.
ImportDeclaration : import ModuleSpecifier WithClause ;
  1. specifierModuleSpecifier의 SV로 둔다.
  2. attributesWithClause의 WithClauseToAttributes로 둔다.
  3. ModuleRequest Record { [[Specifier]]: specifier, [[Attributes]]: attributes }가 유일한 요소인 리스트를 반환한다.
ExportDeclaration : export ExportFromClause FromClause ;
  1. specifierFromClause의 SV로 둔다.
  2. ModuleRequest Record { [[Specifier]]: specifier, [[Attributes]]: « » }가 유일한 요소인 리스트를 반환한다.
ExportDeclaration : export ExportFromClause FromClause WithClause ;
  1. specifierFromClause의 SV로 둔다.
  2. attributesWithClause의 WithClauseToAttributes로 둔다.
  3. ModuleRequest Record { [[Specifier]]: specifier, [[Attributes]]: attributes }가 유일한 요소인 리스트를 반환한다.
ExportDeclaration : export NamedExports ; export VariableStatement export Declaration export default HoistableDeclaration export default ClassDeclaration export default AssignmentExpression ;
  1. 새로운 빈 리스트를 반환한다.

16.2.1.5 추상 모듈 레코드

모듈 레코드는 단일 모듈의 가져오기와 내보내기에 대한 구조적 정보를 캡슐화한다. 이 정보는 연결된 모듈 집합의 가져오기와 내보내기를 링크하는 데 사용된다. 모듈 레코드는 모듈을 평가할 때만 사용되는 네 개의 필드를 포함한다.

명세 목적상 Module Record 값은 Record 명세 타입의 값이며, Module Record가 추상 클래스이고 추상 및 구체적 하위 클래스를 모두 가진 간단한 객체 지향 계층 구조에 존재하는 것으로 생각할 수 있다. 이 명세는 Cyclic Module Record라는 추상 하위 클래스와 그 구체적 하위 클래스인 Source Text Module Record를 정의한다. 다른 명세와 구현은 그들이 정의한 대안적인 모듈 정의 기능에 해당하는 추가적인 Module Record 하위 클래스를 정의할 수 있다.

Module RecordTable 41에 나열된 필드들을 정의한다. 모든 Module Definition 하위 클래스는 적어도 이러한 필드들을 포함한다. Module Record는 또한 Table 42의 추상 메서드 리스트를 정의한다. 모든 Module definition 하위 클래스는 이러한 추상 메서드들의 구체적인 구현을 제공해야 한다.

Table 41: 모듈 레코드 필드
필드 이름 값 타입 의미
[[Realm]] Realm Record 이 모듈이 생성된 Realm.
[[Environment]] Module Environment Record 또는 empty 이 모듈의 최상위 바인딩을 포함하는 Environment Record. 이 필드는 모듈이 링크될 때 설정된다.
[[Namespace]] Object 또는 empty 이 모듈에 대해 생성된 Module Namespace Object (28.3).
[[HostDefined]] anything (기본값은 undefined) 모듈과 추가 정보를 연결해야 하는 호스트 환경에서 사용하기 위해 예약된 필드.
Table 42: 모듈 레코드의 추상 메서드
메서드 목적
LoadRequestedModules([hostDefined])

모든 의존성을 재귀적으로 로드하여 모듈을 링킹을 위해 준비하고 프로미스를 반환한다.

GetExportedNames([exportStarSet])

이 모듈에서 직접 또는 간접적으로 내보내지는 모든 이름의 리스트를 반환한다.

이 메서드를 호출하기 전에 LoadRequestedModules가 성공적으로 완료되어야 한다.

ResolveExport(exportName [, resolveSet])

이 모듈에서 내보낸 이름의 바인딩을 반환한다. 바인딩은 { [[Module]]: Module Record, [[BindingName]]: String | namespace } 형태의 ResolvedBinding Record로 표현된다. 내보내기가 어떤 모듈에서도 직접 바인딩이 없는 Module Namespace Object인 경우 [[BindingName]]namespace로 설정된다. 이름을 해결할 수 없으면 null을, 여러 바인딩이 발견되면 ambiguous를 반환한다.

특정 exportName, resolveSet 쌍을 인수로 이 연산을 호출할 때마다 동일한 결과를 반환해야 한다.

이 메서드를 호출하기 전에 LoadRequestedModules가 성공적으로 완료되어야 한다.

Link()

모든 모듈 의존성을 전이적으로 해결하고 Module Environment Record를 생성하여 모듈을 평가를 위해 준비한다.

이 메서드를 호출하기 전에 LoadRequestedModules가 성공적으로 완료되어야 한다.

Evaluate()

이 모듈과 그 의존성의 평가에 대한 프로미스를 반환하며, 성공적인 평가 시 또는 이미 성공적으로 평가된 경우 해결되고, 평가 오류 시 또는 이미 성공적이지 않게 평가된 경우 거부된다. 프로미스가 거부되면 호스트는 프로미스 거부를 처리하고 평가 오류를 다시 던질 것으로 예상된다.

이 메서드를 호출하기 전에 Link가 성공적으로 완료되어야 한다.

16.2.1.5.1 EvaluateModuleSync ( module )

The abstract operation EvaluateModuleSync takes argument module (Module Record) and returns unused를 포함하는 정상 완료 또는 throw completion. It performs the following steps when called:

  1. 단언: moduleCyclic Module Record가 아니다.
  2. promisemodule.Evaluate()로 둔다.
  3. 단언: promise.[[PromiseState]]fulfilled 또는 rejected 중 하나이다.
  4. promise.[[PromiseState]]rejected이면
    1. promise.[[PromiseIsHandled]]false이면 HostPromiseRejectionTracker(promise, "handle")를 수행한다.
    2. promise.[[PromiseIsHandled]]true로 설정한다.
    3. ThrowCompletion(promise.[[PromiseResult]])를 반환한다.
  5. unused를 반환한다.

16.2.1.6 순환 모듈 레코드

Cyclic Module RecordCyclic Module Record 타입의 하위 클래스인 다른 모듈들과 의존성 순환(dependency cycle)에 참여할 수 있는 모듈에 대한 정보를 표현하는 데 사용된다. Cyclic Module Record 타입의 하위 클래스가 아닌 Module RecordSource Text Module Record 와의 의존성 순환에 참여해서는 안 된다.

Table 41에 정의된 필드들에 더해, Cyclic Module RecordTable 43에 나열된 추가 필드를 가진다.

Table 43: Cyclic Module Record 의 추가 필드
필드 이름 값 타입 의미
[[Status]] new, unlinked, linking, linked, evaluating, evaluating-async, 또는 evaluated 초기 값은 new. 모듈 생명주기 진행에 따라 순서대로 unlinked, linking, linked, evaluating, 필요 시 evaluating-async, evaluated 로 전이한다. evaluating-async 는 이 모듈이 비동기 의존성 완료 후 실행 대기열에 들어 있거나, [[HasTLA]] 필드가 true 이어서 실행되었고 최상위 완료를 대기 중임을 나타낸다.
[[EvaluationError]] throw completion 또는 empty 평가 중 발생한 예외를 나타내는 throw completion. 예외가 없었거나 [[Status]]evaluated 가 아니면 undefined.
[[DFSAncestorIndex]] 정수 또는 empty Link 및 Evaluate 동안에만 사용하는 보조 필드. [[Status]]linking 또는 evaluating 이면, 모듈 자신의 DFS(깊이 우선 탐색) 인덱스이거나 동일 SCC(강한 연결 요소) 내 “더 이른” 모듈의 인덱스이다.
[[RequestedModules]] ModuleRequest Record 리스트 이 모듈의 import 들에 연관된 ModuleRequest Record 리스트. 소스 텍스트상의 등장 순서를 따른다.
[[LoadedModules]] LoadedModuleRequest Record 리스트 Record가 표현하는 모듈이 사용한 지정자 문자열을 (상대 import 속성 집합과 함께) 해석된 Module Record 로 매핑하는 맵. ModuleRequestsEqual(r1, r2)가 true 인 서로 다른 Record r1, r2 를 두 개 포함하지 않는다.
[[CycleRoot]] Cyclic Module Record 또는 empty 순환의 최초 방문 모듈, 즉 SCC 의 루트 DFS 선조. 순환에 속하지 않는 모듈이면 자기 자신. Evaluate 완료 후 모듈의 [[DFSAncestorIndex]] 는 그 [[CycleRoot]] 의 DFS 인덱스가 된다.
[[HasTLA]] Boolean 이 모듈이 개별적으로 비동기인지 여부(예: top-level await 를 포함하는 Source Text Module Record). 비동기 의존성이 있다는 사실만으로 true 는 아니다. 파싱 후 이 필드는 변하지 않는다.
[[AsyncEvaluationOrder]] unset, 정수, 또는 done 초기 unset 이며 완전 동기 모듈은 계속 unset. 자체가 비동기이거나 비동기 의존성을 가지는 모듈은 16.2.1.6.1.3.4 에 의해 대기 모듈 실행이 큐잉되는 순서를 결정하는 정수로 설정된다. 대기 모듈이 실행되면 done 으로 설정.
[[TopLevelCapability]] PromiseCapability Record 또는 empty 이 모듈이 어떤 순환의 [[CycleRoot]] 이고 그 순환 내 어떤 모듈에 Evaluate() 가 호출되었다면, 그 전체 평가에 대한 PromiseCapability Record. Evaluate() 추상 메서드가 반환한 Promise 객체 해결에 사용된다. 해당 순환의 의존 모듈들은 최상위 Evaluate() 가 그들에 대해 개시되지 않았다면 empty.
[[AsyncParentModules]] Cyclic Module Record 리스트 이 모듈 또는 그 의존성이 [[HasTLA]] true 인 상태로 실행 진행 중이면, 최상위 실행 작업에 대해 이 모듈의 상위 importer 들을 추적한다. 이 부모 모듈들은 이 모듈이 성공적으로 실행 완료하기 전에는 실행을 시작하지 않는다.
[[PendingAsyncDependencies]] 정수 또는 empty 비동기 의존성이 하나라도 있으면 남은 비동기 의존 모듈 수를 추적한다. 이 값이 0 이고 실행 오류가 없을 때 모듈이 실행된다.

Table 42 에 정의된 메서드들에 더해 Cyclic Module RecordTable 44 에 나열된 추가 메서드를 가진다.

Table 44: Cyclic Module Record 의 추가 추상 메서드
메서드 목적
InitializeEnvironment() 모든 import 된 바인딩을 해석하고 모듈의 Environment Record 를 초기화하며 실행 컨텍스트를 생성한다.
ExecuteModule([promiseCapability]) 모듈의 실행 컨텍스트 내에서 코드 평가. 이 모듈이 [[HasTLA]]true 이면 PromiseCapability Record 가 인수로 전달되며 메서드는 해당 capability 를 resolve 또는 reject 해야 한다. 이 경우 예외를 throw 하지 말고 필요 시 PromiseCapability Record 를 reject 해야 한다.

GraphLoadingState Record 는 모듈 그래프 로딩 과정에 대한 정보를 담는 Record 이다. HostLoadImportedModule 호출 이후 로딩을 계속하기 위해 사용된다. 각 GraphLoadingState RecordTable 45 에 정의된 필드를 가진다:

Table 45: GraphLoadingState Record 필드
필드 이름 값 타입 의미
[[PromiseCapability]] PromiseCapability Record 로딩 프로세스 완료 시 resolve 해야 하는 Promise.
[[IsLoading]] Boolean 로딩이 아직 성공/오류 어떤 형태로도 완료되지 않았으면 true.
[[PendingModulesCount]] 음이 아닌 정수 대기 중인 HostLoadImportedModule 호출 수를 추적.
[[Visited]] Cyclic Module Record 리스트 현재 로딩 과정에서 이미 로드된 Cyclic Module Record 리스트(순환 의존 무한 루프 방지).
[[HostDefined]] anything (기본값 empty) LoadRequestedModules 호출자에서 HostLoadImportedModule 로 전달할 호스트 정의 데이터.

16.2.1.6.1 Module Record 추상 메서드 구현

다음은 Table 42 에 정의된 Module Record 추상 메서드를 구현하는 Cyclic Module Record 의 구체 메서드이다.

16.2.1.6.1.1 LoadRequestedModules ( [ hostDefined ] )

The LoadRequestedModules concrete method of Cyclic Module Record module takes optional argument hostDefined (anything) and returns Promise. module 의 의존성 그래프 내 모든 Module Record[[LoadedModules]] 를 채운다(주요 작업은 보조 함수 InnerModuleLoading 이 수행). 선택적 hostDefinedHostLoadImportedModule 훅에 전달된다. It performs the following steps when called:

  1. hostDefined 가 없으면 hostDefinedempty 로 둔다.
  2. pc 를 ! NewPromiseCapability(%Promise%) 로 둔다.
  3. stateGraphLoadingState Record { [[IsLoading]]: true, [[PendingModulesCount]]: 1, [[Visited]]: « », [[PromiseCapability]]: pc, [[HostDefined]]: hostDefined } 로 둔다.
  4. InnerModuleLoading(state, module) 를 수행한다.
  5. pc.[[Promise]] 를 반환한다.
Note
hostDefined 매개변수는 import 된 모듈을 가져오는 데 필요한 추가 정보를 전달하는 데 사용할 수 있다. 예를 들어 HTML 은 <link rel="preload" as="..."> 태그에 대한 올바른 fetch destination 설정에 사용한다. import() 표현식은 hostDefined 를 설정하지 않는다.

16.2.1.6.1.1.1 InnerModuleLoading ( state, module )

The abstract operation InnerModuleLoading takes arguments state (GraphLoadingState Record) and module (Module Record) and returns unused. LoadRequestedModules 가 module 의 의존성 그래프에 대해 실제 로딩을 재귀적으로 수행할 때 사용된다. It performs the following steps when called:

  1. 단언: state.[[IsLoading]]true.
  2. moduleCyclic Module Record 이고, module.[[Status]]new, 그리고 state.[[Visited]]module 을 포함하지 않으면
    1. modulestate.[[Visited]] 에 추가한다.
    2. requestedModulesCountmodule.[[RequestedModules]] 요소 수로 둔다.
    3. state.[[PendingModulesCount]]state.[[PendingModulesCount]] + requestedModulesCount 로 설정.
    4. module.[[RequestedModules]] 의 각 ModuleRequest Record request 에 대해
      1. AllImportAttributesSupported(request.[[Attributes]]) 가 false 이면
        1. errorThrowCompletion(새로 생성된 SyntaxError 객체) 로 둔다.
        2. ContinueModuleLoading(state, error) 수행.
      2. Else if module.[[LoadedModules]]ModuleRequestsEqual(record, request) 가 true 인 LoadedModuleRequest Record record 를 포함하면
        1. InnerModuleLoading(state, record.[[Module]]) 수행.
      3. Else,
        1. HostLoadImportedModule(module, request, state.[[HostDefined]], state) 수행.
        2. 참고: HostLoadImportedModuleFinishLoadingImportedModule 를 호출하고 이는 ContinueModuleLoading 을 통해 그래프 로딩 과정에 재진입한다.
      4. state.[[IsLoading]]false 이면 unused 반환.
  3. 단언: 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 이면 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 (GraphLoadingState Record) and moduleCompletion (Module Record 를 담은 정상 completion 또는 throw completion) and returns unused. HostLoadImportedModule 호출 후 로딩 과정에 재진입할 때 사용된다. It performs the following steps when called:

  1. state.[[IsLoading]]false 이면 unused 반환.
  2. moduleCompletion 이 정상 completion 이면
    1. InnerModuleLoading(state, moduleCompletion.[[Value]]) 수행.
  3. Else,
    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 Cyclic Module Record module takes no arguments and returns unused 를 담은 정상 completion 또는 throw completion. 성공 시 이 모듈의 [[Status]]unlinked 에서 linked 로 전이. 실패 시 예외를 던지고 [[Status]]unlinked 유지. (주요 작업은 보조 함수 InnerModuleLinking 수행) It performs the following steps when called:

  1. 단언: module.[[Status]]unlinked, linked, evaluating-async, evaluated 중 하나.
  2. stack 을 새 빈 리스트로 둔다.
  3. resultCompletion(InnerModuleLinking(module, stack, 0)) 로 둔다.
  4. resultabrupt completion 이면
    1. stack 의 각 Cyclic Module Record m 에 대해
      1. 단언: m.[[Status]]linking.
      2. m.[[Status]]unlinked 로 설정.
    2. 단언: module.[[Status]]unlinked.
    3. result 반환.
  5. 단언: module.[[Status]]linked, evaluating-async, 또는 evaluated 중 하나.
  6. 단언: stack 은 비어 있음.
  7. unused 반환.

16.2.1.6.1.2.1 InnerModuleLinking ( module, stack, index )

The abstract operation InnerModuleLinking takes arguments module (Module Record), stack (Cyclic Module Record 리스트), and index (음이 아닌 정수) and returns 음이 아닌 정수를 담은 정상 completion 또는 throw completion. Link 가 module 및 의존성 그래프의 다른 모듈들에 대해 실제 링크 과정을 수행. stackindex, 그리고 모듈의 [[DFSAncestorIndex]] 는 DFS 탐색 추적에 사용. 특히 [[DFSAncestorIndex]] 로 SCC 를 발견하여 SCC 내 모든 모듈이 함께 linked 로 전이되도록 한다. 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. 단언: module.[[Status]]unlinked.
  4. module.[[Status]]linking 으로 둔다.
  5. moduleIndexindex 로 둔다.
  6. module.[[DFSAncestorIndex]]index 로 둔다.
  7. indexindex + 1 로 설정.
  8. modulestack 에 추가.
  9. module.[[RequestedModules]] 의 각 ModuleRequest Record request 에 대해
    1. requiredModuleGetImportedModule(module, request) 로 둔다.
    2. index 를 ? InnerModuleLinking(requiredModule, stack, index) 로 설정.
    3. requiredModuleCyclic Module Record 이면
      1. 단언: requiredModule.[[Status]]linking, linked, evaluating-async, evaluated 중 하나.
      2. 단언: requiredModule.[[Status]]linking 인 것은 stackrequiredModule 을 포함함과 동치.
      3. requiredModule.[[Status]]linking 이면
        1. module.[[DFSAncestorIndex]]min(module.[[DFSAncestorIndex]], requiredModule.[[DFSAncestorIndex]]) 로 설정.
  10. module.InitializeEnvironment() 수행.
  11. 단언: modulestack 에 정확히 한 번 등장.
  12. 단언: module.[[DFSAncestorIndex]]moduleIndex.
  13. module.[[DFSAncestorIndex]] = moduleIndex 이면
    1. donefalse 로 둔다.
    2. 반복: donefalse 인 동안
      1. requiredModulestack 마지막 요소로 둔다.
      2. 마지막 요소 제거.
      3. 단언: requiredModuleCyclic Module Record.
      4. requiredModule.[[Status]]linked 로 설정.
      5. requiredModulemodule 이 동일 Module Record 이면 done = true.
  14. index 반환.

16.2.1.6.1.3 Evaluate ( )

The Evaluate concrete method of Cyclic Module Record module takes no arguments and returns Promise. Evaluate 는 이 모듈의 [[Status]]linked 에서 evaluating-async 또는 evaluated 로 전이. 동일 SCC 내에서 처음 호출될 때 Promise 를 생성해 모듈 평가 완료 시 resolve. 이 Promise 는 구성 요소 [[CycleRoot]][[TopLevelCapability]] 에 저장. 이후 SCC 내 어떤 모듈에 대한 Evaluate 호출도 동일 Promise 반환. (주요 작업은 보조 함수 InnerModuleEvaluation 수행) It performs the following steps when called:

  1. 단언: 이 Evaluate 호출은 동일 agent 내 다른 Evaluate 호출과 동시에 일어나지 않음.
  2. 단언: module.[[Status]]linked, evaluating-async, evaluated 중 하나.
  3. module.[[Status]]evaluating-async 또는 evaluated 이면 module = module.[[CycleRoot]].
  4. module.[[TopLevelCapability]]empty 가 아니면
    1. module.[[TopLevelCapability]].[[Promise]] 반환.
  5. stack 을 새 빈 리스트로 둔다.
  6. capability 를 ! NewPromiseCapability(%Promise%) 로 둔다.
  7. module.[[TopLevelCapability]]capability 로 둔다.
  8. resultCompletion(InnerModuleEvaluation(module, stack, 0)) 로 둔다.
  9. resultabrupt completion 이면
    1. stack 의 각 Cyclic Module Record m 에 대해
      1. 단언: m.[[Status]]evaluating.
      2. 단언: m.[[AsyncEvaluationOrder]]unset.
      3. m.[[Status]]evaluated 로.
      4. m.[[EvaluationError]]result 로.
    2. 단언: module.[[Status]]evaluated.
    3. 단언: module.[[EvaluationError]]result 는 동일 Completion Record.
    4. Call(capability.[[Reject]], undefined, « result.[[Value]] ») 수행.
  10. Else,
    1. 단언: module.[[Status]]evaluating-async 또는 evaluated.
    2. 단언: module.[[EvaluationError]]empty.
    3. module.[[Status]]evaluated 이면
      1. 참고: module 평가가 동기적으로 완료되었음을 의미.
      2. 단언: module.[[AsyncEvaluationOrder]]unset.
      3. Call(capability.[[Resolve]], undefined, « undefined ») 수행.
    4. 단언: stack 은 비어 있음.
  11. capability.[[Promise]] 반환.

16.2.1.6.1.3.1 InnerModuleEvaluation ( module, stack, index )

The abstract operation InnerModuleEvaluation takes arguments module (Module Record), stack (Cyclic Module Record 리스트), and index (음이 아닌 정수) and returns 음이 아닌 정수를 담은 정상 completion 또는 throw completion. Evaluate 가 module 및 의존성 그래프의 다른 모듈에 대해 실제 평가 과정을 수행. stack, index, 그리고 module[[DFSAncestorIndex]] 사용 방식은 InnerModuleLinking 과 동일. It performs the following steps when called:

  1. moduleCyclic Module Record 가 아니면
    1. EvaluateModuleSync(module) 수행.
    2. index 반환.
  2. module.[[Status]]evaluating-async 또는 evaluated 이면
    1. module.[[EvaluationError]]empty 이면 index 반환.
    2. 아니면 ? module.[[EvaluationError]] 반환.
  3. module.[[Status]]evaluating 이면 index 반환.
  4. 단언: module.[[Status]]linked.
  5. module.[[Status]]evaluating 으로.
  6. moduleIndex = index.
  7. module.[[DFSAncestorIndex]] = index.
  8. module.[[PendingAsyncDependencies]] = 0.
  9. index = index + 1.
  10. modulestack 에 추가.
  11. module.[[RequestedModules]] 의 각 ModuleRequest Record request 에 대해
    1. requiredModule = GetImportedModule(module, request).
    2. index = ? InnerModuleEvaluation(requiredModule, stack, index).
    3. requiredModuleCyclic Module Record 이면
      1. 단언: requiredModule.[[Status]]evaluating, evaluating-async, evaluated 중 하나.
      2. 단언: requiredModule.[[Status]]evaluating 인 것은 stackrequiredModule 포함과 동치.
      3. requiredModule.[[Status]]evaluating 이면
        1. module.[[DFSAncestorIndex]] = min(module.[[DFSAncestorIndex]], requiredModule.[[DFSAncestorIndex]]).
      4. Else,
        1. requiredModule = requiredModule.[[CycleRoot]].
        2. 단언: requiredModule.[[Status]]evaluating-async 또는 evaluated.
        3. requiredModule.[[EvaluationError]]empty 가 아니면 ? requiredModule.[[EvaluationError]] 반환.
      5. requiredModule.[[AsyncEvaluationOrder]] 가 정수이면
        1. module.[[PendingAsyncDependencies]] += 1.
        2. modulerequiredModule.[[AsyncParentModules]] 에 추가.
  12. module.[[PendingAsyncDependencies]] > 0 또는 module.[[HasTLA]]true 이면
    1. 단언: module.[[AsyncEvaluationOrder]]unset.
    2. module.[[AsyncEvaluationOrder]] = IncrementModuleAsyncEvaluationCount().
    3. module.[[PendingAsyncDependencies]] = 0 이면 ExecuteAsyncModule(module) 수행.
  13. Else,
    1. module.ExecuteModule() 수행.
  14. 단언: modulestack 에 정확히 한 번 등장.
  15. 단언: module.[[DFSAncestorIndex]]moduleIndex.
  16. module.[[DFSAncestorIndex]] = moduleIndex 이면
    1. done = false.
    2. 반복 (donefalse 인 동안)
      1. requiredModule = stack 마지막 요소.
      2. 마지막 요소 제거.
      3. 단언: requiredModuleCyclic Module Record.
      4. 단언: requiredModule.[[AsyncEvaluationOrder]] 는 정수 또는 unset.
      5. requiredModule.[[AsyncEvaluationOrder]]unset 이면 requiredModule.[[Status]] = evaluated.
      6. 아니면 requiredModule.[[Status]] = evaluating-async.
      7. requiredModulemodule 이 같으면 done = true.
      8. requiredModule.[[CycleRoot]] = module.
  17. index 반환.
Note 1

모듈은 InnerModuleEvaluation 이 순회 중이면 evaluating 상태. [[HasTLA]]true 이거나 비동기 의존성이 있으면 실행 중 evaluating-async, 완료 시 evaluated.

Note 2

비동기 순환의 모듈에 의존하는 모듈은 순환이 evaluating 이 아닐 때 [[CycleRoot]] 를 통해 루트 실행에 의존하도록 하여 순환 상태를 단일 SCC 로 취급 가능하게 한다.

16.2.1.6.1.3.2 ExecuteAsyncModule ( module )

The abstract operation ExecuteAsyncModule takes argument module (Cyclic Module Record) and returns unused. It performs the following steps when called:

  1. 단언: module.[[Status]]evaluating 또는 evaluating-async.
  2. 단언: module.[[HasTLA]]true.
  3. capability = ! NewPromiseCapability(%Promise%).
  4. fulfilledClosuremodule 을 캡처하고 호출 시:
    1. AsyncModuleExecutionFulfilled(module) 수행.
    2. NormalCompletion(undefined) 반환.
  5. onFulfilled = CreateBuiltinFunction(fulfilledClosure, 0, "", « »).
  6. rejectedClosure 를 (error) 매개변수, module 캡처하고 호출 시:
    1. AsyncModuleExecutionRejected(module, error) 수행.
    2. NormalCompletion(undefined) 반환.
  7. onRejected = CreateBuiltinFunction(rejectedClosure, 0, "", « »).
  8. PerformPromiseThen(capability.[[Promise]], onFulfilled, onRejected) 수행.
  9. module.ExecuteModule(capability) 수행.
  10. unused 반환.

16.2.1.6.1.3.3 GatherAvailableAncestors ( module, execList )

The abstract operation GatherAvailableAncestors takes arguments module (Cyclic Module Record) and execList (Cyclic Module Record 리스트) and returns unused. It performs the following steps when called:

  1. module.[[AsyncParentModules]] 의 각 Cyclic Module Record m 에 대해
    1. execListm 을 포함하지 않고 m.[[CycleRoot]].[[EvaluationError]]empty 이면
      1. 단언: m.[[Status]]evaluating-async.
      2. 단언: m.[[EvaluationError]]empty.
      3. 단언: m.[[AsyncEvaluationOrder]] 는 정수.
      4. 단언: m.[[PendingAsyncDependencies]] > 0.
      5. m.[[PendingAsyncDependencies]] -= 1.
      6. m.[[PendingAsyncDependencies]] = 0 이면
        1. mexecList 에 추가.
        2. m.[[HasTLA]]false 이면 GatherAvailableAncestors(m, execList) 수행.
  2. unused 반환.
Note

루트 module 의 비동기 실행이 fulfill 될 때, 이 함수는 동시에 동기 실행 가능한 모듈 목록을 결정하여 execList 에 채운다.

16.2.1.6.1.3.4 AsyncModuleExecutionFulfilled ( module )

The abstract operation AsyncModuleExecutionFulfilled takes argument module (Cyclic Module Record) and returns unused. It performs the following steps when called:

  1. module.[[Status]]evaluated 이면
    1. 단언: module.[[EvaluationError]]empty 가 아님.
    2. unused 반환.
  2. 단언: module.[[Status]]evaluating-async.
  3. 단언: module.[[AsyncEvaluationOrder]] 는 정수.
  4. 단언: module.[[EvaluationError]]empty.
  5. module.[[AsyncEvaluationOrder]]done 으로.
  6. module.[[Status]]evaluated 로.
  7. module.[[TopLevelCapability]]empty 가 아니면
    1. 단언: module.[[CycleRoot]]module 은 동일.
    2. Call(module.[[TopLevelCapability]].[[Resolve]], undefined, « undefined ») 수행.
  8. execList 를 새 빈 리스트로 둔다.
  9. GatherAvailableAncestors(module, execList) 수행.
  10. 단언: execList 모든 요소는 [[AsyncEvaluationOrder]] 가 정수, [[PendingAsyncDependencies]] = 0, [[EvaluationError]] = empty.
  11. sortedExecList[[AsyncEvaluationOrder]] 오름차순으로 정렬한 리스트로 둔다.
  12. sortedExecList 의 각 Cyclic Module Record m 에 대해
    1. m.[[Status]]evaluated 이면
      1. 단언: m.[[EvaluationError]]empty 아님.
    2. Else if m.[[HasTLA]]true 이면
      1. ExecuteAsyncModule(m) 수행.
    3. Else
      1. result = m.ExecuteModule().
      2. resultabrupt completion 이면
        1. AsyncModuleExecutionRejected(m, result.[[Value]]) 수행.
      3. Else
        1. m.[[AsyncEvaluationOrder]] = done.
        2. m.[[Status]] = evaluated.
        3. m.[[TopLevelCapability]]empty 아니면
          1. 단언: m.[[CycleRoot]]m 동일.
          2. Call(m.[[TopLevelCapability]].[[Resolve]], undefined, « undefined ») 수행.
  13. unused 반환.

16.2.1.6.1.3.5 AsyncModuleExecutionRejected ( module, error )

The abstract operation AsyncModuleExecutionRejected takes arguments module (Cyclic Module Record) and error (ECMAScript 언어 값) and returns unused. It performs the following steps when called:

  1. module.[[Status]]evaluated 이면
    1. 단언: module.[[EvaluationError]]empty 가 아님.
    2. unused 반환.
  2. 단언: module.[[Status]]evaluating-async.
  3. 단언: module.[[AsyncEvaluationOrder]] 는 정수.
  4. 단언: module.[[EvaluationError]]empty.
  5. module.[[EvaluationError]] = ThrowCompletion(error).
  6. module.[[Status]] = evaluated.
  7. module.[[AsyncEvaluationOrder]] = done.
  8. 참고: module.[[EvaluationError]]empty 가 아닐 때 InnerModuleEvaluation 에서 [[AsyncEvaluationOrder]] 값은 사용되지 않는다.
  9. module.[[AsyncParentModules]] 의 각 Cyclic Module Record m 에 대해
    1. AsyncModuleExecutionRejected(m, error) 수행.
  10. module.[[TopLevelCapability]]empty 아니면
    1. 단언: module.[[CycleRoot]]module 동일.
    2. Call(module.[[TopLevelCapability]].[[Reject]], undefined, « error ») 수행.
  11. unused 반환.

16.2.1.6.2 순환 모듈 레코드 그래프 예시

비규범 섹션: 몇 가지 공통 모듈 그래프의 링크 및 평가 예시와 오류 발생 양상에 초점을 둔다.

먼저 다음 단순 모듈 그래프를 보자:

Figure 2: 단순 모듈 그래프
모듈 A 가 모듈 B 에 의존하고, 모듈 B 가 모듈 C 에 의존하는 그래프

우선 오류 조건이 없다고 가정. 호스트가 처음 A.LoadRequestedModules() 를 호출하면 (가정에 따라) 성공적으로 완료하면서 B, C 의 의존성도 재귀적으로 로드(각각 C 와 없음)하고 A.[[Status]] = B.[[Status]] = C.[[Status]] = unlinked 로 설정. 이후 A.Link() 호출도 성공(가정)하여 세 모듈 모두 linked. 이러한 준비 단계는 언제든 수행 가능. 나중에 호스트가 모듈의 부작용 실행 시점이 되면 A.Evaluate() 호출 → 성공적으로 완료, undefined 로 resolve 되는 Promise 반환(가정), 먼저 C 그다음 B 를 평가. 이 시점에 각 모듈 [[Status]]evaluated.

다음으로 링크 오류 사례: A.LoadRequestedModules() 성공 후 InnerModuleLinking(C) 는 성공하지만 그 뒤 B 에서 실패(예: C 가 제공하지 않는 것을 import). 그러면 원래 A.Link() 가 실패하고 AB[[Status]]unlinked 유지. Clinked 로 전이되어 있음.

마지막으로 링크 성공 후 평가 오류: InnerModuleEvaluation(C) 는 성공하지만 그 뒤 B 가 실패(예: B 코드에서 예외). 원래 A.Evaluate() 는 reject 된 Promise 반환으로 실패. 예외는 A, B[[EvaluationError]] 에 기록되고 두 모듈 [[Status]]evaluated. Cevaluated 되지만 예외 없이 성공 평가. 예외 저장을 통해 이후 Evaluate() 재호출 시 동일 예외 일관 제공. (호스트Cyclic Module Record 재사용 의무 없음; 예외 객체 노출 의무도 없음. 명세는 가능성만 제공.)

이제 다른 오류 조건 유형:

Figure 3: 해결 불가 모듈을 가진 그래프
모듈 A 가 ??? 로 표시된 존재하지 않는 모듈에 의존

이 시나리오에서 A 는 다른 모듈을 선언적 의존하지만 해당 Module Record 가 없음 (HostLoadImportedModuleFinishLoadingImportedModule 호출 시 예외 전달). 리소스 부재, 혹은 존재하지만 ParseModule 이 오류 반환 등 다양한 이유. 호스트는 실패 원인을 FinishLoadingImportedModule 에 전달하는 completion 을 통해 노출 선택 가능. 이 예외로 로딩 실패 → A.[[Status]]new 유지.

로딩 / 링크 / 평가 오류 차이는 다음 특징 때문:

  • 평가는 부작용이 있을 수 있어 한 번만 수행해야 하므로(비성공 포함) 이미 수행 여부 기억 필요. (오류 시에도 이후 Evaluate() 마다 새로운 예외 합성 대신 기존 예외 기억이 합리적)
  • 링크는 부작용이 없으므로 실패해도 나중에 재시도 가능
  • 로딩은 호스트와 긴밀히 상호작용하므로 일부 호스트는 실패한 로드 재시도 허용이 바람직(예: 일시적 네트워크 문제)

이제 순환이 있는 그래프:

Figure 4: 순환 모듈 그래프
모듈 A 가 B, C 에 의존하고 B 가 A 에도 의존

엔트리 포인트가 A 라 가정하고 호스트A.LoadRequestedModules() 호출 → A 에 대해 InnerModuleLoading 수행. 이는 B, C 에 대해 InnerModuleLoading 호출. 순환 때문에 다시 A 에 대해 InnerModuleLoading 트리거되지만 이미 로딩 트리거 되었으므로 no-op. 그래프 모든 모듈 로딩 성공 시 [[Status]] 는 동시에 newunlinked.

그 후 A.Link() → A 에 대해 InnerModuleLinkingB → 순환으로 다시 A (이미 linking 이므로 no-op). B 는 여전히 linking 상태에서 제어가 A 로 돌아와 C 에 대해 InnerModuleLinking. ClinkedA, B 가 함께 linkinglinked 전이; 이는 SCC 단위 동시 전이를 설계한 것. DFS 로 그래프 순회하므로 가능.

성공 사례에서 평가 단계도 유사.

A 에 링크 오류(예: C 에 존재하지 않는 바인딩 import) 인 경우 위 단계 진행 중 두 번째 InnerModuleLinking(A) 조기 반환 포함. 하지만 원래 InnerModuleLinking(A) 로 되돌아왔을 때 InitializeEnvironment 중 (C.ResolveExport() 직후) 실패, SyntaxError 전파 → A.Link 에서 현재 stack 에 있는(linking) 모듈 상태를 재설정. 따라서 A, Bunlinked, Clinked 유지.

유사하게 A 평가 오류(예: 코드 예외) 인 경우에도 평가 시퀀스는 비슷. 두 번째 InnerModuleEvaluation(A) 조기 반환 후 원래 InnerModuleEvaluation(A) 로 돌아와 실패. 예외가 A.Evaluate() 로 전파되어 현재 stack (여전히 evaluating) 및 [[AsyncParentModules]] 체인을 따라(상위 top-level await 를 가진 모듈 경유) AsyncModuleExecutionRejected 알고리즘으로 전파. 결과로 A, Bevaluated & 예외 기록, C 는 예외 없이 evaluated.

마지막으로 모든 모듈이 비동기 완료하는 순환 그래프:

Figure 5: 비동기 순환 모듈 그래프
모듈 A 가 B, C 에 의존, B 는 D, C 는 D, E 에 의존, D 는 A 에 의존

로딩과 링크는 이전과 같고 모두 [[Status]] = linked.

A.Evaluate() 는 A, B, D 에 대해 InnerModuleEvaluation 수행 → 모두 evaluating. 다시 A 호출은 no-op. 이때 D.[[PendingAsyncDependencies]] = 0 → ExecuteAsyncModule(D) 호출 → D.ExecuteModule 새 PromiseCapability. B 로 unwind: B.[[PendingAsyncDependencies]] = 1, [[AsyncEvaluationOrder]] = 1. 다시 A 로: A.[[PendingAsyncDependencies]] = 1. 다음 A 의 의존 반복에서 C 평가 → D(no-op), E. E 는 의존 없고 순환 아님 → ExecuteAsyncModule(E) 즉시 호출 & stack 에서 제거. 다시 C 로 unwind: C.[[AsyncEvaluationOrder]] = 3. A 의 의존 루프 종료 후 A.[[AsyncEvaluationOrder]] = 4, SCC 전체 stack 제거하며 모두 evaluating-async. 이 시점 필드는 Table 46 참조.

Table 46: 초기 Evaluate() 후 모듈 필드
필드
모듈
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, C) 1 (D) 2 (D, E) 0 0

E 가 먼저 실행 완료한다고 가정. AsyncModuleExecutionFulfilled 호출 → E.[[Status]] = evaluated, C.[[PendingAsyncDependencies]] = 1. 업데이트 필드는 Table 47.

Table 47: E 실행 완료 후 필드
필드
모듈
C E
[[DFSAncestorIndex]] 0 4
[[Status]] evaluating-async evaluated
[[AsyncEvaluationOrder]] 3 done
[[AsyncParentModules]] « A » « C »
[[PendingAsyncDependencies]] 1 (D) 0

다음으로 D 완료. AsyncModuleExecutionFulfilled 호출 → D.[[Status]] = evaluated. 실행 가능한 조상은 [[AsyncEvaluationOrder]] 1 의 B, 3 의 C → 순서상 B 먼저 처리: B.[[PendingAsyncDependencies]] = 0 → ExecuteAsyncModule(B) → 실행 시작. C.[[PendingAsyncDependencies]] 도 0 → C 실행 시작( B 에 await 있다면 병렬 가능). 업데이트 필드는 Table 48.

Table 48: D 실행 완료 후 필드
필드
모듈
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 가 다음으로 완료. AsyncModuleExecutionFulfilledC.[[Status]] = evaluated, A.[[PendingAsyncDependencies]] = 1. 필드는 Table 49.

Table 49: C 실행 완료 후 필드
필드
모듈
A C
[[DFSAncestorIndex]] 0 0
[[Status]] evaluating-async evaluated
[[AsyncEvaluationOrder]] 4 done
[[AsyncParentModules]] « » « A »
[[PendingAsyncDependencies]] 1 (B) 0

그 후 B 완료. AsyncModuleExecutionFulfilledB.[[Status]] = evaluated, A.[[PendingAsyncDependencies]] = 0 → ExecuteAsyncModule 호출 → 실행 시작. 필드는 Table 50.

Table 50: B 실행 완료 후 필드
필드
모듈
A B
[[DFSAncestorIndex]] 0 0
[[Status]] evaluating-async evaluated
[[AsyncEvaluationOrder]] 4 done
[[AsyncParentModules]] « » « A »
[[PendingAsyncDependencies]] 0 0

마지막으로 A 완료. AsyncModuleExecutionFulfilledA.[[Status]] = evaluated, A.[[TopLevelCapability]] 의 Promise(resolve) → 그래프 처리 종료. 필드는 Table 51.

Table 51: A 실행 완료 후 필드
필드
모듈
A
[[DFSAncestorIndex]] 0
[[Status]] evaluated
[[AsyncEvaluationOrder]] done
[[AsyncParentModules]] « »
[[PendingAsyncDependencies]] 0

대안: CB 완료 전 오류로 실패. AsyncModuleExecutionRejected 호출 → C.[[Status]] = evaluated, C.[[EvaluationError]] = 오류. 그런 다음 AsyncParentModules 전파. 필드는 Table 52.

Table 52: C 오류 완료 후 필드
필드
모듈
A C
[[DFSAncestorIndex]] 0 0
[[Status]] evaluated evaluated
[[AsyncEvaluationOrder]] done done
[[AsyncParentModules]] « » « A »
[[PendingAsyncDependencies]] 1 (B) 0
[[EvaluationError]] empty C 의 평가 오류

CA 에 대해 AsyncModuleExecutionRejected 호출하므로 A 는 동일 오류로 reject. A.[[Status]] = evaluated. A.[[TopLevelCapability]] Promise 는 reject. 필드는 Table 53.

Table 53: A 가 reject 된 후 필드
필드
모듈
A
[[DFSAncestorIndex]] 0
[[Status]] evaluated
[[AsyncEvaluationOrder]] done
[[AsyncParentModules]] « »
[[PendingAsyncDependencies]] 0
[[EvaluationError]] C 의 Evaluation Error

이후 B 가 오류 없이 완료. AsyncModuleExecutionFulfilledB.[[Status]] = evaluated. GatherAvailableAncestors(B) 호출. 그러나 A.[[CycleRoot]] = A, 그리고 평가 오류 존재 → sortedExecList 에 추가되지 않고 추가 처리 없이 반환. 이후 B 의 importer 는 cycle root A[[EvaluationError]] 를 통해 reject 를 해석. 필드는 Table 54.

Table 54: 오류 그래프에서 B 완료 후 필드
필드
모듈
A B
[[DFSAncestorIndex]] 0 0
[[Status]] evaluated evaluated
[[AsyncEvaluationOrder]] 4 1
[[AsyncParentModules]] « » « A »
[[PendingAsyncDependencies]] 0 0
[[EvaluationError]] C 의 Evaluation Error empty

16.2.1.7 소스 텍스트 모듈 레코드

Source Text Module RecordModule 목표 기호로 파싱된 ECMAScript 소스 텍스트 (11) 로 정의된 모듈 정보를 나타내는 데 사용된다. 필드는 모듈이 import/export 하는 이름에 대한 요약 정보를 포함하고, 구체 메서드는 이 요약을 사용해 링크 및 평가를 수행한다.

Source Text Module Record 는 추상 Module Record 타입의 다른 하위 클래스들과 같은 그래프에 존재할 수 있으며 Cyclic Module Record 타입의 다른 하위 클래스들과 순환에 참여할 수 있다.

Table 43 에 정의된 필드들 외에, Source Text Module RecordTable 55 에 있는 추가 필드를 가진다. 각 필드는 ParseModule 에서 초기화된다.

Table 55: Source Text Module Record 의 추가 필드
필드 이름 값 타입 의미
[[ECMAScriptCode]] Parse Node Module 을 목표 기호로 사용해 이 모듈 소스 텍스트를 파싱한 결과.
[[Context]] ECMAScript 코드 실행 컨텍스트 또는 empty 이 모듈에 연결된 실행 컨텍스트. 환경 초기화 전까지 empty.
[[ImportMeta]] Object 또는 empty import.meta 메타 프로퍼티로 노출되는 객체. ECMAScript 코드에서 접근 전까지 empty.
[[ImportEntries]] ImportEntry Record 리스트 이 모듈 코드에서 도출된 ImportEntry 리스트.
[[LocalExportEntries]] ExportEntry Record 리스트 모듈 내 선언에 해당하는 export 에 대한 ExportEntry 리스트.
[[IndirectExportEntries]] ExportEntry Record 리스트 모듈 내 재export(import 재export 또는 export * as namespace) 에 해당하는 ExportEntry 리스트.
[[StarExportEntries]] ExportEntry Record 리스트 모듈 내 export * 선언(단, export * as namespace 제외)에 해당하는 ExportEntry 리스트.

ImportEntry Record 는 단일 선언적 import 에 대한 정보를 요약한 Record. 각 ImportEntry RecordTable 56 필드를 가진다:

Table 56: ImportEntry Record 필드
필드 이름 값 타입 의미
[[ModuleRequest]] ModuleRequest Record ImportDeclarationModuleSpecifier 및 import 속성.
[[ImportName]] String 또는 namespace-object [[ModuleRequest]] 로 식별된 모듈이 해당 바인딩을 export 하는 이름. namespace-object 는 대상 모듈 네임스페이스 객체 import 요청을 의미.
[[LocalName]] String import 하는 모듈 내부에서 값에 접근할 때 사용하는 로컬 이름.
Note 1

Table 57 는 구문 import 형태를 표현하는 ImportEntry 필드 예시:

Table 57 (Informative): Import 문 형태와 ImportEntry 매핑
Import 문 형태 [[ModuleRequest]] [[ImportName]] [[LocalName]]
import v from "mod"; "mod" "default" "v"
import * as ns from "mod"; "mod" namespace-object "ns"
import {x} from "mod"; "mod" "x" "x"
import {x as v} from "mod"; "mod" "x" "v"
import "mod"; ImportEntry Record 생성 안 됨.

ExportEntry Record 는 단일 선언적 export 정보를 요약한 Record. 각 ExportEntry RecordTable 58 필드 보유:

Table 58: ExportEntry Record 필드
필드 이름 값 타입 의미
[[ExportName]] String 또는 null 모듈이 이 바인딩을 export 하는 이름.
[[ModuleRequest]] ModuleRequest Record 또는 null ExportDeclarationModuleSpecifier 및 import 속성을 나타내는 ModuleRequest Record. ModuleSpecifier 없으면 null.
[[ImportName]] String, null, all, 또는 all-but-default [[ModuleRequest]] 로 식별된 모듈이 해당 바인딩을 export 하는 이름. ModuleSpecifier 없으면 null. export * as ns from "mod"all, export * from "mod"all-but-default 사용.
[[LocalName]] String 또는 null importer 모듈 내부에서 export 값 접근 시 사용 로컬 이름. 로컬 접근 불가면 null.
Note 2

Table 59 는 구문 export 형태를 표현하는 ExportEntry 필드 예시:

Table 59 (Informative): Export 문 형태와 ExportEntry 매핑
Export 문 형태 [[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" all null

다음 정의는 Source Text Module Record 에 필요한 구체 메서드와 기타 추상 연산을 명세한다.

16.2.1.7.1 ParseModule ( sourceText, realm, hostDefined )

The abstract operation ParseModule takes arguments sourceText (ECMAScript 소스 텍스트), realm (Realm Record), and hostDefined (anything) and returns Source Text Module Record 또는 SyntaxError 객체 비어있지 않은 리스트. sourceTextModule 로 파싱한 결과에 기반하여 Source Text Module Record 생성. It performs the following steps when called:

  1. body = ParseText(sourceText, Module).
  2. body 가 오류 리스트이면 body 반환.
  3. requestedModules = ModuleRequests(body).
  4. importEntries = ImportEntries(body).
  5. importedBoundNames = ImportedLocalNames(importEntries).
  6. indirectExportEntries = 새 빈 리스트.
  7. localExportEntries = 새 빈 리스트.
  8. starExportEntries = 새 빈 리스트.
  9. exportEntries = ExportEntries(body).
  10. ExportEntry Record eeexportEntries 에 대해
    1. ee.[[ModuleRequest]]null 이면
      1. importedBoundNamesee.[[LocalName]] 포함하지 않으면
        1. eelocalExportEntries 에 추가.
      2. Else
        1. ie = [[LocalName]]ee.[[LocalName]]importEntries 요소.
        2. ie.[[ImportName]]namespace-object 이면
          1. 참고: import 된 모듈 네임스페이스 객체 재export.
          2. eelocalExportEntries 에 추가.
        3. Else
          1. 참고: 단일 이름 재export.
          2. ExportEntry Record { [[ModuleRequest]]: ie.[[ModuleRequest]], [[ImportName]]: ie.[[ImportName]], [[LocalName]]: null, [[ExportName]]: ee.[[ExportName]] } 를 indirectExportEntries 에 추가.
    2. Else if ee.[[ImportName]]all-but-default 이면
      1. 단언: ee.[[ExportName]]null.
      2. eestarExportEntries 에 추가.
    3. Else
      1. eeindirectExportEntries 에 추가.
  11. async = body 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

구현은 ParseModule 평가 이전에 소스 텍스트를 파싱하고 Early Error 분석을 수행할 수 있으나 오류 보고는 실제 ParseModule 수행 시점까지 지연해야 한다.

16.2.1.7.2 Module Record 추상 메서드 구현

Table 42 에 정의된 Module Record 추상 메서드 구현을 위한 Source Text Module Record 의 구체 메서드.

16.2.1.7.2.1 GetExportedNames ( [ exportStarSet ] )

The GetExportedNames concrete method of Source Text Module Record module takes optional argument exportStarSet (Source Text Module Record 리스트) and returns 문자열 리스트. It performs the following steps when called:

  1. 단언: module.[[Status]]new 아님.
  2. exportStarSet 없으면 새 빈 리스트로 설정.
  3. exportStarSetmodule 포함하면
    1. 단언: export * 순환의 시작점 도달.
    2. 새 빈 리스트 반환.
  4. moduleexportStarSet 에 추가.
  5. exportedNames = 새 빈 리스트.
  6. module.[[LocalExportEntries]]ExportEntry Record e 에 대해
    1. 단언: module 이 직접 바인딩 제공.
    2. 단언: e.[[ExportName]]null 아님.
    3. e.[[ExportName]]exportedNames 에 추가.
  7. module.[[IndirectExportEntries]]e 에 대해
    1. 단언: module 이 특정 바인딩 import 후 재export.
    2. 단언: e.[[ExportName]]null 아님.
    3. e.[[ExportName]]exportedNames 에 추가.
  8. module.[[StarExportEntries]]e 에 대해
    1. 단언: e.[[ModuleRequest]]null 아님.
    2. requestedModule = GetImportedModule(module, e.[[ModuleRequest]]).
    3. starNames = requestedModule.GetExportedNames(exportStarSet).
    4. nstarNames 에 대해
      1. n"default" 이면
        1. exportedNamesn 포함하지 않으면 추가.
  9. exportedNames 반환.
Note

GetExportedNames 는 모호한 star export 바인딩 이름을 필터링하거나 예외를 던지지 않는다.

16.2.1.7.2.2 ResolveExport ( exportName [ , resolveSet ] )

The ResolveExport concrete method of Source Text Module Record module takes argument exportName (String) and optional argument resolveSet (Record 리스트 (필드 [[Module]]: Module Record, [[ExportName]]: String)) and returns ResolvedBinding Record, null, 또는 ambiguous.

ResolveExport 는 import 된 바인딩을 실제 정의 모듈과 로컬 바인딩 이름으로 해석. 정의 모듈은 자신 또는 import 된 다른 모듈일 수 있음. resolveSet 은 순환 import/export 경로 탐지를 위해 사용. 동일 Module RecordexportName 쌍이 이미 resolveSet 에 있으면 순환. 재귀 호출 전 { module, exportName } 쌍을 추가.

정의 모듈 발견 시 ResolvedBinding Record { [[Module]], [[BindingName]] } 반환(네임스페이스 export 만 있는 경우 [[BindingName]] = namespace). 정의 없거나 순환이면 null, 모호하면 ambiguous.

It performs the following steps when called:

  1. 단언: module.[[Status]]new 아님.
  2. resolveSet 없으면 새 빈 리스트.
  3. resolveSet 의 각 Record { [[Module]], [[ExportName]] } r 에 대해
    1. moduler.[[Module]] 동일이고 exportName = r.[[ExportName]] 이면
      1. 단언: 순환 import 요청.
      2. null 반환.
  4. Record { [[Module]]: module, [[ExportName]]: exportName } 를 resolveSet 에 추가.
  5. module.[[LocalExportEntries]]ExportEntry Record e 에 대해
    1. e.[[ExportName]] = exportName 이면
      1. 단언: 직접 바인딩 제공.
      2. ResolvedBinding Record { [[Module]]: module, [[BindingName]]: e.[[LocalName]] } 반환.
  6. module.[[IndirectExportEntries]]e 에 대해
    1. e.[[ExportName]] = exportName 이면
      1. 단언: e.[[ModuleRequest]]null.
      2. importedModule = GetImportedModule(module, e.[[ModuleRequest]]).
      3. e.[[ImportName]]all 이면
        1. 단언: 직접 바인딩 제공 안 함.
        2. ResolvedBinding Record { [[Module]]: importedModule, [[BindingName]]: namespace } 반환.
      4. Else
        1. 단언: 특정 바인딩 import 후 재export.
        2. 단언: e.[[ImportName]] 는 String.
        3. importedModule.ResolveExport(e.[[ImportName]], resolveSet) 반환.
  7. exportName = "default" 이면
    1. 단언: 명시적 default export 없음.
    2. null 반환.
    3. NOTE: export * from "mod"default export 제공 불가.
  8. starResolution = null.
  9. module.[[StarExportEntries]]e 에 대해
    1. 단언: e.[[ModuleRequest]]null.
    2. importedModule = GetImportedModule(module, e.[[ModuleRequest]]).
    3. resolution = importedModule.ResolveExport(exportName, resolveSet).
    4. resolution = ambiguous 이면 ambiguous 반환.
    5. resolutionnull 이면
      1. 단언: resolutionResolvedBinding Record.
      2. starResolutionnull 이면
        1. starResolution = resolution.
      3. Else
        1. 단언: 요청 이름을 포함하는 * import 가 하나 이상.
        2. resolution.[[Module]]starResolution.[[Module]] 이면 ambiguous 반환.
        3. resolution.[[BindingName]]starResolution.[[BindingName]] 이고 둘 중 하나가 namespace 이면 ambiguous.
        4. [[BindingName]] 이 모두 String 이고 다르면 ambiguous.
  10. starResolution 반환.

16.2.1.7.3 Cyclic Module Record 추상 메서드 구현

Table 44 에 정의된 Cyclic Module Record 추상 메서드를 구현하는 Source Text Module Record 의 구체 메서드.

16.2.1.7.3.1 InitializeEnvironment ( )

The InitializeEnvironment concrete method of Source Text Module Record module takes no arguments and returns unused 를 담은 정상 completion 또는 throw completion. It performs the following steps when called:

  1. module.[[IndirectExportEntries]] 의 각 ExportEntry Record e 에 대해
    1. 단언: e.[[ExportName]]null.
    2. resolution = module.ResolveExport(e.[[ExportName]]).
    3. resolutionnull 또는 ambiguous 이면 SyntaxError throw.
    4. 단언: resolutionResolvedBinding Record.
  2. 단언: module 의 모든 named export 는 해석 가능.
  3. realm = module.[[Realm]].
  4. 단언: realmundefined.
  5. env = NewModuleEnvironment(realm.[[GlobalEnv]]).
  6. module.[[Environment]] = env.
  7. module.[[ImportEntries]]ImportEntry Record in 에 대해
    1. importedModule = GetImportedModule(module, in.[[ModuleRequest]]).
    2. in.[[ImportName]]namespace-object 이면
      1. namespace = GetModuleNamespace(importedModule).
      2. env.CreateImmutableBinding(in.[[LocalName]], true) 수행.
      3. env.InitializeBinding(in.[[LocalName]], namespace) 수행.
    3. Else
      1. resolution = importedModule.ResolveExport(in.[[ImportName]]).
      2. resolutionnull 또는 ambiguous 이면 SyntaxError throw.
      3. resolution.[[BindingName]] = namespace 이면
        1. namespace = GetModuleNamespace(resolution.[[Module]]).
        2. env.CreateImmutableBinding(in.[[LocalName]], true).
        3. env.InitializeBinding(in.[[LocalName]], namespace).
      4. Else
        1. CreateImportBinding(env, in.[[LocalName]], resolution.[[Module]], resolution.[[BindingName]]) 수행.
  8. moduleContext = 새 ECMAScript 코드 실행 컨텍스트.
  9. moduleContext.Function = null.
  10. 단언: module.[[Realm]]undefined.
  11. moduleContext.Realm = module.[[Realm]].
  12. moduleContext.ScriptOrModule = module.
  13. moduleContext.VariableEnvironment = module.[[Environment]].
  14. moduleContext.LexicalEnvironment = module.[[Environment]].
  15. moduleContext.PrivateEnvironment = null.
  16. module.[[Context]] = moduleContext.
  17. moduleContext 를 실행 컨텍스트 스택에 push; 실행 중 컨텍스트.
  18. code = module.[[ECMAScriptCode]].
  19. varDeclarations = VarScopedDeclarations(code).
  20. declaredVarNames = 새 빈 리스트.
  21. dvarDeclarations 에 대해
    1. BoundNames(d) 의 각 dn 에 대해
      1. declaredVarNamesdn 포함하지 않으면
        1. env.CreateMutableBinding(dn, false).
        2. env.InitializeBinding(dn, undefined).
        3. dndeclaredVarNames 에 추가.
  22. lexDeclarations = LexicallyScopedDeclarations(code).
  23. privateEnv = null.
  24. dlexDeclarations 에 대해
    1. BoundNames(d) 의 각 dn 에 대해
      1. IsConstantDeclaration(d) 가 true 이면
        1. env.CreateImmutableBinding(dn, true).
      2. Else
        1. env.CreateMutableBinding(dn, false).
      3. dFunctionDeclaration, GeneratorDeclaration, AsyncFunctionDeclaration, AsyncGeneratorDeclaration 중 하나이면
        1. fo = InstantiateFunctionObject(d, env, privateEnv).
        2. env.InitializeBinding(dn, fo).
  25. moduleContext 를 실행 컨텍스트 스택에서 제거.
  26. unused 반환.

16.2.1.7.3.2 ExecuteModule ( [ capability ] )

The ExecuteModule concrete method of Source Text Module Record module takes optional argument capability (PromiseCapability Record) and returns unused 를 담은 정상 completion 또는 throw completion. It performs the following steps when called:

  1. moduleContext = 새 ECMAScript 코드 실행 컨텍스트.
  2. moduleContext.Function = null.
  3. moduleContext.Realm = module.[[Realm]].
  4. moduleContext.ScriptOrModule = module.
  5. 단언: 모듈이 링크되었고 환경 선언 인스턴스화 완료.
  6. moduleContext.VariableEnvironment = module.[[Environment]].
  7. moduleContext.LexicalEnvironment = module.[[Environment]].
  8. 실행 중 컨텍스트 suspend.
  9. module.[[HasTLA]] = false 이면
    1. 단언: capability 없음.
    2. moduleContext push → 실행 중 컨텍스트.
    3. result = Completion(Evaluation(module.[[ECMAScriptCode]]) ).
    4. moduleContext suspend 및 스택에서 제거.
    5. 최상위 컨텍스트 resume.
    6. resultabrupt completion 이면
      1. result 반환.
  10. Else
    1. 단언: capabilityPromiseCapability Record.
    2. AsyncBlockStart(capability, module.[[ECMAScriptCode]], moduleContext) 수행.
  11. unused 반환.

16.2.1.8 합성(Synthetic) 모듈 레코드

Synthetic Module Record 는 명세가 정의하는 모듈 정보를 나타내며 export 이름은 생성 시 정적으로 정의되고 값은 SetSyntheticModuleExport 로 시간에 따라 변경될 수 있다. import 또는 의존성이 없다.

Note
Synthetic Module Record 는 JSON 모듈, CSS 모듈 등 다양한 모듈 타입 정의에 사용 가능.

Table 41 의 필드 외에 Synthetic Module Record 는 Table 60 의 추가 필드를 가진다.

Table 60: Synthetic Module Record 의 추가 필드
필드 이름 값 타입 의미
[[ExportNames]] 문자열 리스트 모듈의 export 이름. 중복 없음.
[[EvaluationSteps]] Abstract Closure 모듈 평가 시 수행할 초기화 로직 (Synthetic Module Record 를 단일 인수). [[ExportNames]] 수정 금지. abrupt completion 반환 가능.

16.2.1.8.1 CreateDefaultExportSyntheticModule ( defaultExport )

The abstract operation CreateDefaultExportSyntheticModule takes argument defaultExport (ECMAScript 언어 값) and returns Synthetic Module Record. defaultExport 를 기본 export 로 하는 Synthetic Module Record 생성. It performs the following steps when called:

  1. realm = 현재 Realm Record.
  2. setDefaultExport = (module) 매개변수, defaultExport 캡처하는 Abstract Closure:
    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 (String) and returns Synthetic Module Record 를 담은 정상 completion 또는 throw completion. It performs the following steps when called:

  1. json = ? ParseJSON(source).
  2. CreateDefaultExportSyntheticModule(json) 반환.

16.2.1.8.3 SetSyntheticModuleExport ( module, exportName, exportValue )

The abstract operation SetSyntheticModuleExport takes arguments module (Synthetic Module Record), exportName (String), and exportValue (ECMAScript 언어 값) and returns unused. Synthetic Module Record 의 기존 export 값 설정/변경. It performs the following steps when called:

  1. 단언: module.[[ExportNames]]exportName 포함.
  2. envRec = module.[[Environment]].
  3. 단언: envRecempty.
  4. envRec.SetMutableBinding(exportName, exportValue, true) 수행.
  5. unused 반환.

16.2.1.8.4 Module Record 추상 메서드 구현

Table 42 에 정의된 Module Record 추상 메서드를 구현하는 Synthetic Module Record 의 구체 메서드.

16.2.1.8.4.1 LoadRequestedModules ( )

The LoadRequestedModules concrete method of Synthetic Module Record module takes no arguments and returns Promise. It performs the following steps when called:

  1. PromiseResolve(%Promise%, undefined) 반환.
Note
Synthetic Module Record 는 의존성이 없다.

16.2.1.8.4.2 GetExportedNames ( )

The GetExportedNames concrete method of Synthetic Module Record module takes no arguments and returns 문자열 리스트. It performs the following steps when called:

  1. module.[[ExportNames]] 반환.

16.2.1.8.4.3 ResolveExport ( exportName )

The ResolveExport concrete method of Synthetic Module Record module takes argument exportName (String) and returns ResolvedBinding Record 또는 null. It performs the following steps when called:

  1. module.[[ExportNames]]exportName 포함하지 않으면 null 반환.
  2. ResolvedBinding Record { [[Module]]: module, [[BindingName]]: exportName } 반환.

16.2.1.8.4.4 Link ( )

The Link concrete method of Synthetic Module Record module takes no arguments and returns unused 를 담은 정상 completion. It performs the following steps when called:

  1. realm = module.[[Realm]].
  2. env = NewModuleEnvironment(realm.[[GlobalEnv]]).
  3. module.[[Environment]] = env.
  4. module.[[ExportNames]] 의 각 String exportName 에 대해
    1. env.CreateMutableBinding(exportName, false).
    2. env.InitializeBinding(exportName, undefined).
  5. NormalCompletion(unused) 반환.

16.2.1.8.4.5 Evaluate ( )

The Evaluate concrete method of Synthetic Module Record module takes no arguments and returns Promise. It performs the following steps when called:

  1. moduleContext = 새 ECMAScript 코드 실행 컨텍스트.
  2. moduleContext.Function = null.
  3. moduleContext.Realm = module.[[Realm]].
  4. moduleContext.ScriptOrModule = module.
  5. moduleContext.VariableEnvironment = module.[[Environment]].
  6. moduleContext.LexicalEnvironment = module.[[Environment]].
  7. 실행 중 컨텍스트 suspend.
  8. moduleContext push → 실행 중 컨텍스트.
  9. steps = module.[[EvaluationSteps]].
  10. result = Completion(steps(module)).
  11. moduleContext suspend 및 스택에서 제거.
  12. 최상위 컨텍스트 resume.
  13. pc = ! NewPromiseCapability(%Promise%).
  14. IfAbruptRejectPromise(result, pc).
  15. Call(pc.[[Resolve]], undefined, « undefined ») 수행.
  16. pc.[[Promise]] 반환.

16.2.1.9 GetImportedModule ( referrer, request )

The abstract operation GetImportedModule takes arguments referrer (Cyclic Module Record) and request (ModuleRequest Record) and returns Module Record. It performs the following steps when called:

  1. recordsreferrer.[[LoadedModules]] 의 각 LoadedModuleRequest Record rModuleRequestsEqual(r, request) 이 true 인 것들의 리스트로 둔다.
  2. 단언: LoadRequestedModules 가 사전에 성공했으므로 records 는 정확히 한 요소.
  3. record = records 의 유일 요소.
  4. record.[[Module]] 반환.

16.2.1.10 HostLoadImportedModule ( referrer, moduleRequest, hostDefined, payload )

The host-defined abstract operation HostLoadImportedModule takes arguments referrer (Script Record, Cyclic Module Record, 또는 Realm Record), moduleRequest (ModuleRequest Record), hostDefined (anything), and payload (GraphLoadingState Record 또는 PromiseCapability Record) and returns unused.

Note 1

웹 브라우저 호스트 예: 사용자가 아래 컨트롤을 클릭할 때

<button type="button" onclick="import('./foo.mjs')">Click me</button>

import() 표현식 실행 시 활성 스크립트나 모듈이 없을 수 있다. 더 일반적으로 호스트가 ScriptOrModule 이 null 인 실행 컨텍스트를 스택에 푸시하는 상황이면 Realm Recordreferrer 가 될 수 있다.

HostLoadImportedModule 구현은 다음 요구사항을 따른다:

실제 과정은 호스트 정의이며 보통 적절한 Module Record 로드에 필요한 I/O 수행. 서로 다른 여러 (referrer, moduleRequest.[[Specifier]], moduleRequest.[[Attributes]]) 삼중 조합이 동일 Module Record 인스턴스에 매핑될 수 있음. 매핑 의미론은 호스트 정의이나 일반적으로 specifier 정규화 포함 (상대/축약 경로 확장 등).

Note 2

위 텍스트는 type: "json" 으로 import 하면 (그리고 HostLoadImportedModule 이 정상 완료) 호스트가 JSON 모듈 지원을 요구하지만 type: "json" 없이 import 할 때 JSON 모듈 지원을 금지하지 않는다.

16.2.1.11 FinishLoadingImportedModule ( referrer, moduleRequest, payload, result )

The abstract operation FinishLoadingImportedModule takes arguments referrer (Script Record, Cyclic Module Record, 또는 Realm Record), moduleRequest (ModuleRequest Record), payload (GraphLoadingState Record 또는 PromiseCapability Record), and result (Module Record 를 담은 정상 completion 또는 throw completion) and returns unused. It performs the following steps when called:

  1. result가 정상 completion이면
    1. referrer.[[LoadedModules]]ModuleRequestsEqual(record, moduleRequest)가 true인 LoadedModuleRequest Record record가 있으면
      1. 단언: record.[[Module]]result.[[Value]]는 동일한 Module Record이다.
    2. 그렇지 않으면
      1. LoadedModuleRequest Record { [[Specifier]]: moduleRequest.[[Specifier]], [[Attributes]]: moduleRequest.[[Attributes]], [[Module]]: result.[[Value]] }를 referrer.[[LoadedModules]]에 추가한다.
  2. payloadGraphLoadingState Record이면
    1. ContinueModuleLoading(payload, result)를 수행한다.
  3. 그렇지 않으면
    1. ContinueDynamicImport(payload, result)를 수행한다.
  4. unused를 반환한다.

16.2.1.12 AllImportAttributesSupported ( attributes )

The abstract operation AllImportAttributesSupported takes argument attributes (ImportAttribute Records 리스트) and returns Boolean. It performs the following steps when called:

  1. supportedHostGetSupportedImportAttributes()로 둔다.
  2. attributes의 각 ImportAttribute Record attribute에 대해
    1. supportedattribute.[[Key]]를 포함하지 않으면 false를 반환한다.
  3. true를 반환한다.

16.2.1.12.1 HostGetSupportedImportAttributes ( )

The host-defined abstract operation HostGetSupportedImportAttributes takes no arguments and returns 문자열 리스트. 호스트 환경이 지원하는 import attribute를 지정할 수 있게 한다. 지원되는 키를 가진 attribute만 호스트에 제공된다.

HostGetSupportedImportAttributes의 구현은 다음 요구사항을 따라야 한다:

  • 지원되는 각 attribute를 나타내는 문자열의 리스트를 반환해야 한다.
  • 이 연산이 호출될 때마다 동일한 순서와 내용의 동일한 리스트를 반환해야 한다.

HostGetSupportedImportAttributes의 기본 구현은 새 빈 리스트를 반환하는 것이다.

Note
호스트가 처리할 attribute를 선택하도록 모든 attribute를 전달하는 대신 지원되는 attribute만 명시하게 하는 목적은 지원되지 않는 attribute가 서로 다른 호스트 간에도 일관되게 처리되도록 하기 위함이다.

16.2.1.13 GetModuleNamespace ( module )

The abstract operation GetModuleNamespace takes argument module (Module Record의 구체 하위 클래스 인스턴스) and returns Module Namespace Object. module의 export를 나타내는 Module Namespace Object를 가져온다. 처음 요청될 때 지연 생성하여 module.[[Namespace]]에 저장하고 이후 재사용한다. It performs the following steps when called:

  1. 단언: moduleCyclic Module Record라면 module.[[Status]]new 또는 unlinked가 아니다.
  2. namespacemodule.[[Namespace]]로 둔다.
  3. namespaceempty이면
    1. exportedNamesmodule.GetExportedNames()로 둔다.
    2. unambiguousNames를 새 빈 리스트로 둔다.
    3. exportedNames의 각 요소 name에 대해
      1. resolutionmodule.ResolveExport(name)로 둔다.
      2. resolutionResolvedBinding Record이면 nameunambiguousNames에 추가한다.
    4. namespaceModuleNamespaceCreate(module, unambiguousNames)로 설정한다.
  4. namespace를 반환한다.
Note

GetModuleNamespace는 예외를 던지지 않는다. 대신 이 시점에서 해결할 수 없는 이름은 네임스페이스에서 제외된다. 그러한 이름들은 어딘가에서 명시적으로 요청되지 않은 모호한 star export 전부가 아닌 한 이후 실제 링크 오류로 이어진다.

16.2.1.14 런타임 의미론: 평가

Module : [empty]
  1. undefined를 반환한다.
ModuleBody : ModuleItemList
  1. resultCompletion(Evaluation of ModuleItemList)로 둔다.
  2. result가 정상 completion이고 result.[[Value]]empty이면
    1. undefined를 반환한다.
  3. result를 반환한다.
ModuleItemList : ModuleItemList ModuleItem
  1. sl을 ? Evaluation of ModuleItemList로 둔다.
  2. sCompletion(Evaluation of ModuleItem)로 둔다.
  3. UpdateEmpty(s, sl)를 반환한다.
Note

ModuleItemList의 값은 그 ModuleItemList 안에서 마지막으로 값을 생성한 항목의 값이다.

ModuleItem : ImportDeclaration
  1. empty를 반환한다.

16.2.2 가져오기(Imports)

구문

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 정적 의미론: 조기 오류

ModuleItem : ImportDeclaration
  • ImportDeclaration 의 BoundNames 에 중복 항목이 있으면 문법 오류이다.
WithClause : with { WithEntries ,opt }
  • WithClause 의 WithClauseToAttributes 결과에 a.[[Key]]b.[[Key]] 와 같은 서로 다른 항목 a, b 두 개가 있으면 문법 오류이다.

16.2.2.2 정적 의미론: ImportEntries : ImportEntry Record 리스트

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. It is defined piecewise over the following productions:

Module : [empty]
  1. 새 빈 리스트를 반환한다.
ModuleItemList : ModuleItemList ModuleItem
  1. entries1ModuleItemList 의 ImportEntries 로 둔다.
  2. entries2ModuleItem 의 ImportEntries 로 둔다.
  3. entries1entries2 의 리스트 연결을 반환한다.
ModuleItem : ExportDeclaration StatementListItem
  1. 새 빈 리스트를 반환한다.
ImportDeclaration : import ImportClause FromClause WithClauseopt ;
  1. moduleImportDeclaration 의 ModuleRequests 의 유일한 요소로 둔다.
  2. ImportClause 의 ImportEntriesForModule(module) 를 반환한다.
ImportDeclaration : import ModuleSpecifier WithClauseopt ;
  1. 새 빈 리스트를 반환한다.

16.2.2.3 정적 의미론: ImportEntriesForModule : ImportEntry Record 리스트

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. It is defined piecewise over the following productions:

ImportClause : ImportedDefaultBinding , NameSpaceImport
  1. entries1ImportedDefaultBinding 의 ImportEntriesForModule(module) 로 둔다.
  2. entries2NameSpaceImport 의 ImportEntriesForModule(module) 로 둔다.
  3. entries1entries2 의 리스트 연결을 반환한다.
ImportClause : ImportedDefaultBinding , NamedImports
  1. entries1ImportedDefaultBinding 의 ImportEntriesForModule(module) 로 둔다.
  2. entries2NamedImports 의 ImportEntriesForModule(module) 로 둔다.
  3. entries1entries2 의 리스트 연결을 반환한다.
ImportedDefaultBinding : ImportedBinding
  1. localNameImportedBinding 의 BoundNames 의 유일한 요소로 둔다.
  2. defaultEntryImportEntry Record { [[ModuleRequest]]: module, [[ImportName]]: "default", [[LocalName]]: localName } 로 둔다.
  3. « defaultEntry » 를 반환한다.
NameSpaceImport : * as ImportedBinding
  1. localNameImportedBinding 의 StringValue 로 둔다.
  2. entryImportEntry Record { [[ModuleRequest]]: module, [[ImportName]]: namespace-object, [[LocalName]]: localName } 로 둔다.
  3. « entry » 를 반환한다.
NamedImports : { }
  1. 새 빈 리스트를 반환한다.
ImportsList : ImportsList , ImportSpecifier
  1. specs1ImportsList 의 ImportEntriesForModule(module) 로 둔다.
  2. specs2ImportSpecifier 의 ImportEntriesForModule(module) 로 둔다.
  3. specs1specs2 의 리스트 연결을 반환한다.
ImportSpecifier : ImportedBinding
  1. localNameImportedBinding 의 BoundNames 의 유일한 요소로 둔다.
  2. entryImportEntry Record { [[ModuleRequest]]: module, [[ImportName]]: localName, [[LocalName]]: localName } 로 둔다.
  3. « entry » 를 반환한다.
ImportSpecifier : ModuleExportName as ImportedBinding
  1. importNameModuleExportName 의 StringValue 로 둔다.
  2. localNameImportedBinding 의 StringValue 로 둔다.
  3. entryImportEntry Record { [[ModuleRequest]]: module, [[ImportName]]: importName, [[LocalName]]: localName } 로 둔다.
  4. « entry » 를 반환한다.

16.2.2.4 정적 의미론: WithClauseToAttributes : ImportAttribute Record 리스트

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. It is defined piecewise over the following productions:

WithClause : with { }
  1. 새 빈 리스트를 반환한다.
WithClause : with { WithEntries ,opt }
  1. attributesWithEntries 의 WithClauseToAttributes 로 둔다.
  2. attributes[[Key]] 필드 값을 UTF-16 코드 유닛 시퀀스로 간주한 사전식 순서에 따라 정렬한다. 참고: 이 정렬은 호스트가 열거 순서에 따라 동작을 바꾸지 못하도록 강제한다는 점에서만 관측 가능하다.
  3. attributes 를 반환한다.
WithEntries : AttributeKey : StringLiteral
  1. keyAttributeKey 의 PropName 으로 둔다.
  2. entry 를 ImportAttribute Record { [[Key]]: key, [[Value]]: StringLiteral 의 SV } 로 둔다.
  3. « entry » 를 반환한다.
WithEntries : AttributeKey : StringLiteral , WithEntries
  1. keyAttributeKey 의 PropName 으로 둔다.
  2. entry 를 ImportAttribute Record { [[Key]]: key, [[Value]]: StringLiteral 의 SV } 로 둔다.
  3. restWithEntries 의 WithClauseToAttributes 로 둔다.
  4. « entry » 와 rest 의 리스트 연결을 반환한다.

16.2.3 내보내기(Exports)

구문

ExportDeclaration : export ExportFromClause FromClause WithClauseopt ; export NamedExports ; export VariableStatement[~Yield, +Await] export 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 정적 의미론: 조기 오류

ExportDeclaration : export NamedExports ;
  • NamedExports 의 ReferencedBindings 에 StringLiteral 이 있으면 문법 오류이다.
  • NamedExports 의 ReferencedBindings 에 있는 각 IdentifierName n 에 대해: n 의 StringValue 가 ReservedWord 이거나 "implements", "interface", "let", "package", "private", "protected", "public", "static" 중 하나이면 문법 오류이다.
Note

위 규칙은 NamedExports 의 ReferencedBindings 각각이 IdentifierReference 로 취급됨을 의미한다.

16.2.3.2 정적 의미론: ExportedBindings : 문자열 리스트

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS.

Note

ExportedBindings 는 Module 의 ExportedNames 와 명시적으로 연결된 로컬 바인딩 이름들이다.

It is defined piecewise over the following productions:

ModuleItemList : ModuleItemList ModuleItem
  1. names1ModuleItemList 의 ExportedBindings 로 둔다.
  2. names2ModuleItem 의 ExportedBindings 로 둔다.
  3. names1names2 의 리스트 연결을 반환한다.
ModuleItem : ImportDeclaration StatementListItem
  1. 새 빈 리스트를 반환한다.
ExportDeclaration : export ExportFromClause FromClause WithClauseopt ;
  1. 새 빈 리스트를 반환한다.
ExportDeclaration : export NamedExports ;
  1. NamedExports 의 ExportedBindings 를 반환한다.
ExportDeclaration : export VariableStatement
  1. VariableStatement 의 BoundNames 를 반환한다.
ExportDeclaration : export Declaration
  1. Declaration 의 BoundNames 를 반환한다.
ExportDeclaration : export default HoistableDeclaration export default ClassDeclaration export default AssignmentExpression ;
  1. ExportDeclaration 의 BoundNames 를 반환한다.
NamedExports : { }
  1. 새 빈 리스트를 반환한다.
ExportsList : ExportsList , ExportSpecifier
  1. names1ExportsList 의 ExportedBindings 로 둔다.
  2. names2ExportSpecifier 의 ExportedBindings 로 둔다.
  3. names1names2 의 리스트 연결을 반환한다.
ExportSpecifier : ModuleExportName
  1. ModuleExportName 의 StringValue 한 요소만 갖는 리스트를 반환한다.
ExportSpecifier : ModuleExportName as ModuleExportName
  1. 첫 번째 ModuleExportName 의 StringValue 한 요소만 갖는 리스트를 반환한다.

16.2.3.3 정적 의미론: ExportedNames : 문자열 리스트

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS.

Note

ExportedNames 는 Module 이 로컬 바인딩 이름 중 하나에 명시적으로 매핑하는 외부로 보이는 이름들이다.

It is defined piecewise over the following productions:

ModuleItemList : ModuleItemList ModuleItem
  1. names1ModuleItemList 의 ExportedNames 로 둔다.
  2. names2ModuleItem 의 ExportedNames 로 둔다.
  3. names1names2 의 리스트 연결을 반환한다.
ModuleItem : ExportDeclaration
  1. ExportDeclaration 의 ExportedNames 를 반환한다.
ModuleItem : ImportDeclaration StatementListItem
  1. 새 빈 리스트를 반환한다.
ExportDeclaration : export ExportFromClause FromClause WithClauseopt ;
  1. ExportFromClause 의 ExportedNames 를 반환한다.
ExportFromClause : *
  1. 새 빈 리스트를 반환한다.
ExportFromClause : * as ModuleExportName
  1. ModuleExportName 의 StringValue 한 요소만 갖는 리스트를 반환한다.
ExportFromClause : NamedExports
  1. NamedExports 의 ExportedNames 를 반환한다.
ExportDeclaration : export VariableStatement
  1. VariableStatement 의 BoundNames 를 반환한다.
ExportDeclaration : export Declaration
  1. Declaration 의 BoundNames 를 반환한다.
ExportDeclaration : export default HoistableDeclaration export default ClassDeclaration export default AssignmentExpression ;
  1. « "default" » 를 반환한다.
NamedExports : { }
  1. 새 빈 리스트를 반환한다.
ExportsList : ExportsList , ExportSpecifier
  1. names1ExportsList 의 ExportedNames 로 둔다.
  2. names2ExportSpecifier 의 ExportedNames 로 둔다.
  3. names1names2 의 리스트 연결을 반환한다.
ExportSpecifier : ModuleExportName
  1. ModuleExportName 의 StringValue 한 요소만 갖는 리스트를 반환한다.
ExportSpecifier : ModuleExportName as ModuleExportName
  1. 두 번째 ModuleExportName 의 StringValue 한 요소만 갖는 리스트를 반환한다.

16.2.3.4 정적 의미론: ExportEntries : ExportEntry Record 리스트

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. It is defined piecewise over the following productions:

Module : [empty]
  1. 새 빈 리스트를 반환한다.
ModuleItemList : ModuleItemList ModuleItem
  1. entries1ModuleItemList 의 ExportEntries 로 둔다.
  2. entries2ModuleItem 의 ExportEntries 로 둔다.
  3. entries1entries2 의 리스트 연결을 반환한다.
ModuleItem : ImportDeclaration StatementListItem
  1. 새 빈 리스트를 반환한다.
ExportDeclaration : export ExportFromClause FromClause WithClauseopt ;
  1. moduleExportDeclaration 의 ModuleRequests 의 유일한 요소로 둔다.
  2. ExportFromClause 의 ExportEntriesForModule(module) 를 반환한다.
ExportDeclaration : export NamedExports ;
  1. NamedExports 의 ExportEntriesForModule(null) 를 반환한다.
ExportDeclaration : export VariableStatement
  1. entries 를 새 빈 리스트로 둔다.
  2. namesVariableStatement 의 BoundNames 로 둔다.
  3. namenames 에 대해
    1. ExportEntry Record { [[ModuleRequest]]: null, [[ImportName]]: null, [[LocalName]]: name, [[ExportName]]: name } 를 entries 에 추가한다.
  4. entries 를 반환한다.
ExportDeclaration : export Declaration
  1. entries 를 새 빈 리스트로 둔다.
  2. namesDeclaration 의 BoundNames 로 둔다.
  3. namenames 에 대해
    1. ExportEntry Record { [[ModuleRequest]]: null, [[ImportName]]: null, [[LocalName]]: name, [[ExportName]]: name } 를 entries 에 추가한다.
  4. entries 를 반환한다.
ExportDeclaration : export default HoistableDeclaration
  1. namesHoistableDeclaration 의 BoundNames 로 둔다.
  2. localNamenames 의 유일한 요소로 둔다.
  3. 유일 요소가 새 ExportEntry Record { [[ModuleRequest]]: null, [[ImportName]]: null, [[LocalName]]: localName, [[ExportName]]: "default" } 인 리스트를 반환한다.
ExportDeclaration : export default ClassDeclaration
  1. namesClassDeclaration 의 BoundNames 로 둔다.
  2. localName 을 그 유일한 요소로 둔다.
  3. 유일 요소가 새 ExportEntry Record { [[ModuleRequest]]: null, [[ImportName]]: null, [[LocalName]]: localName, [[ExportName]]: "default" } 인 리스트를 반환한다.
ExportDeclaration : export default AssignmentExpression ;
  1. entryExportEntry Record { [[ModuleRequest]]: null, [[ImportName]]: null, [[LocalName]]: "*default*", [[ExportName]]: "default" } 로 둔다.
  2. « entry » 를 반환한다.
Note

"*default*" 는 익명 default export 값을 위한 명세 내부의 합성 이름이다. 더 자세한 내용은 이 노트 를 참조.

16.2.3.5 정적 의미론: ExportEntriesForModule : ExportEntry Record 리스트

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. 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. exportNameModuleExportName 의 StringValue 로 둔다.
  2. entryExportEntry Record { [[ModuleRequest]]: module, [[ImportName]]: all, [[LocalName]]: null, [[ExportName]]: exportName } 로 둔다.
  3. « entry » 를 반환한다.
NamedExports : { }
  1. 새 빈 리스트를 반환한다.
ExportsList : ExportsList , ExportSpecifier
  1. specs1ExportsList 의 ExportEntriesForModule(module) 로 둔다.
  2. specs2ExportSpecifier 의 ExportEntriesForModule(module) 로 둔다.
  3. specs1specs2 의 리스트 연결을 반환한다.
ExportSpecifier : ModuleExportName
  1. sourceNameModuleExportName 의 StringValue 로 둔다.
  2. modulenull 이면
    1. localName = sourceName.
    2. importName = null.
  3. 그렇지 않으면
    1. localName = null.
    2. importName = sourceName.
  4. 유일 요소가 새 ExportEntry Record { [[ModuleRequest]]: module, [[ImportName]]: importName, [[LocalName]]: localName, [[ExportName]]: sourceName } 인 리스트를 반환한다.
ExportSpecifier : ModuleExportName as ModuleExportName
  1. sourceName 을 첫 번째 ModuleExportName 의 StringValue 로 둔다.
  2. exportName 을 두 번째 ModuleExportName 의 StringValue 로 둔다.
  3. modulenull 이면
    1. localName = sourceName.
    2. importName = null.
  4. 그렇지 않으면
    1. localName = null.
    2. importName = sourceName.
  5. 유일 요소가 새 ExportEntry Record { [[ModuleRequest]]: module, [[ImportName]]: importName, [[LocalName]]: localName, [[ExportName]]: exportName } 인 리스트를 반환한다.

16.2.3.6 정적 의미론: ReferencedBindings : Parse Node 리스트

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. It is defined piecewise over the following productions:

NamedExports : { }
  1. 새 빈 리스트를 반환한다.
ExportsList : ExportsList , ExportSpecifier
  1. names1ExportsList 의 ReferencedBindings 로 둔다.
  2. names2ExportSpecifier 의 ReferencedBindings 로 둔다.
  3. names1names2 의 리스트 연결을 반환한다.
ExportSpecifier : ModuleExportName as ModuleExportName
  1. 첫 번째 ModuleExportName 의 ReferencedBindings 를 반환한다.
ModuleExportName : IdentifierName
  1. 유일한 요소가 그 IdentifierName 인 리스트를 반환한다.
ModuleExportName : StringLiteral
  1. 유일한 요소가 그 StringLiteral 인 리스트를 반환한다.

16.2.3.7 런타임 의미론: 평가

ExportDeclaration : export ExportFromClause FromClause WithClauseopt ; export NamedExports ;
  1. empty 를 반환한다.
ExportDeclaration : export VariableStatement
  1. VariableStatement 의 Evaluation 결과를 ? 로 반환한다.
ExportDeclaration : export Declaration
  1. Declaration 의 Evaluation 결과를 ? 로 반환한다.
ExportDeclaration : export default HoistableDeclaration
  1. HoistableDeclaration 의 Evaluation 결과를 ? 로 반환한다.
ExportDeclaration : export default ClassDeclaration
  1. valueClassDeclaration 의 BindingClassDeclarationEvaluation 결과(? )로 둔다.
  2. classNameClassDeclaration 의 BoundNames 의 유일한 요소로 둔다.
  3. className"*default*" 이면
    1. env 를 실행 중 실행 컨텍스트의 LexicalEnvironment 로 둔다.
    2. InitializeBoundName("*default*", value, env) 를 수행한다.
  4. empty 를 반환한다.
ExportDeclaration : export default AssignmentExpression ;
  1. IsAnonymousFunctionDefinition(AssignmentExpression) 이 true 이면
    1. value 를 ? NamedEvaluation(AssignmentExpression, "default") 로 둔다.
  2. 그렇지 않으면
    1. rhs 를 ? Evaluation(AssignmentExpression) 로 둔다.
    2. value 를 ? GetValue(rhs) 로 둔다.
  3. env 를 실행 중 실행 컨텍스트의 LexicalEnvironment 로 둔다.
  4. InitializeBoundName("*default*", value, env) 를 수행한다.
  5. empty 를 반환한다.

17 오류 처리 및 언어 확장

구현은 관련 ECMAScript 언어 구성요소가 평가될 때 대부분의 오류를 보고해야 한다. early error(조기 오류) 는 그 오류를 포함하는 Script 안의 어떤 구성요소도 평가되기 전에 검출·보고될 수 있는 오류이다. 조기 오류가 존재하면 그 구성요소의 평가가 차단된다. 구현은 ParseScript 과정에서 해당 Script 를 파싱하는 일부로 Script 의 조기 오류를 보고해야 한다. Module 의 조기 오류는 그 Module 이 평가될 지점에서 보고되며 그 Module 은 결코 초기화되지 않는다. eval 코드의 조기 오류는 eval 이 호출되는 시점에 보고되며 해당 eval 코드의 평가를 막는다. 조기 오류가 아닌 모든 오류는 런타임 오류이다.

구현은 이 명세의 “Static Semantics: Early Errors” 하위 절에 열거된 조건이 발생하면 반드시 그것을 조기 오류로 보고해야 한다.

구현은 (컴파일러가 어떤 구성요소가 어떤 상황에서도 오류 없이 실행될 수 없음을 입증할 수 있더라도) 다른 종류의 오류를 조기 오류로 취급해서는 안 된다. 그런 경우 구현이 조기 경고를 낼 수는 있지만, 관련 구성요소가 실제로 실행될 때까지 오류를 보고해서는 안 된다.

구현은 다음과 같은 경우를 제외하고 명세된 대로 모든 오류를 보고해야 한다:

17.1 금지된 확장

구현은 다음과 같은 방식으로 이 명세를 확장해서는 안 된다:

18 ECMAScript 표준 내장 객체

ECMAScript Script 또는 Module 이 실행을 시작할 때 항상 이용 가능한 특정 내장 객체들이 있다. 그중 전역 객체는 실행 중인 프로그램의 전역 환경 일부이다. 다른 것들은 전역 객체의 초기 프로퍼티로서 또는 접근 가능한 내장 객체의 프로퍼티를 통해 간접적으로 접근할 수 있다.

별도로 명시되지 않는 한 함수로 호출 가능한 내장 객체는 10.3 에 기술된 특성을 가진 내장 함수 객체이다. 별도로 명시되지 않는 한 내장 객체의 [[Extensible]] 내부 슬롯의 초기 값은 true 이다. 모든 내장 함수 객체는 자신이 처음 생성된 RealmRealm Record 값을 가지는 [[Realm]] 내부 슬롯을 가진다.

많은 내장 객체는 함수이며, 인수를 전달받아 호출될 수 있다. 그중 일부는 생성자이기도 하여 new 연산자와 함께 사용하도록 의도된 함수이다. 각 내장 함수에 대해 이 명세는 그 함수가 요구하는 인수와 함수 객체의 프로퍼티를 기술한다. 각 내장 생성자에 대해서는 추가로 그 생성자의 프로토타입 객체 프로퍼티 및 그 생성자를 호출하는 new 표현식이 반환하는 특정 객체 인스턴스의 프로퍼티를 기술한다.

특정 함수의 설명에서 달리 명시되지 않는 한, 내장 함수나 생성자가 지정된 것보다 적은 인수를 받으면, 부족한 인수들을 undefined 값으로 채워 받은 것과 정확히 동일하게 동작해야 한다. 이러한 누락된 인수들은 “존재하지 않음” 으로 간주되며 명세 알고리즘에서 그렇게 식별될 수 있다. 특정 함수 설명에서 “this value” 와 “NewTarget” 용어는 10.3 에서 부여된 의미를 가진다.

특정 함수 설명에서 달리 명시되지 않는 한, 내장 함수나 생성자가 허용된 것보다 많은 인수를 받으면 추가 인수는 평가되지만 함수는 이를 무시한다. 단, 구현은 그러한 인수에 대해 TypeError 예외를 단지 “추가 인수가 존재한다” 는 이유만으로 던지지 않는 한 구현 정의 동작을 규정할 수 있다.

Note 1

내장 함수 집합에 추가 기능을 덧붙이는 구현은 기존 함수에 새 매개변수를 추가하기보다 새 함수를 추가하는 방식으로 하는 것이 권장된다.

별도로 명시되지 않는 한 모든 내장 함수 및 내장 생성자는 자신의 [[Prototype]] 내부 슬롯 값으로 Function 프로토타입 객체(표현식 Function.prototype 의 초기 값, 20.2.3) 를 가진다.

별도로 명시되지 않는 한 모든 내장 프로토타입 객체는 (자기 자신인 Object 프로토타입 객체를 제외하고) 자신의 [[Prototype]] 내부 슬롯 값으로 Object 프로토타입 객체(표현식 Object.prototype 의 초기 값, 20.1.3) 를 가진다.

이 명세가 내장 생성자의 동작을 알고리즘 단계로 정의했다면, 그것이 [[Call]][[Construct]] 양쪽 목적의 동작이다. 해당 알고리즘이 두 경우를 구분할 필요가 있으면 NewTarget 이 undefined 인지 검사하는데, 이는 [[Call]] 호출을 의미한다.

생성자로 식별되지 않은 내장 함수 객체는 특정 함수 설명에서 별도로 명시되지 않는 한 [[Construct]] 내부 메서드를 구현하지 않는다.

생성자가 아닌 내장 함수 객체는 특정 함수 설명에서 별도로 명시되지 않는 한 "prototype" 프로퍼티를 갖지 않는다.

이 명세에 정의된 각 내장 함수는 CreateBuiltinFunction 추상 연산(10.3.4) 호출로 생성된다. lengthname 매개변수의 값은 아래에서 논의되는 "length""name" 프로퍼티의 초기 값이다. prefix 매개변수의 값도 유사하게 아래에서 논의된다.

생성자를 포함한 모든 내장 함수 객체"length" 프로퍼티를 가지며 그 값은 0 이상의 정수 Number 이다. 별도로 명시되지 않는 한 이 값은 함수 설명 하위 절 제목에 나타난 필수 매개변수의 수이다. 선택적 매개변수와 rest 매개변수는 개수에 포함되지 않는다.

Note 2

예: Array 프로토타입 객체"map" 프로퍼티 초기 값인 함수 객체는 «Array.prototype.map (callback [ , thisArg])» 라는 제목 아래에 기술되며, 이름 있는 두 인수 callback 과 선택적인 thisArg 를 보여준다. 따라서 그 함수 객체"length" 프로퍼티 값은 1𝔽 이다.

별도로 명시되지 않는 한 내장 함수 객체"length" 프로퍼티는 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true } 특성을 가진다.

생성자를 포함한 모든 내장 함수 객체"name" 프로퍼티를 가지며 그 값은 String 이다. 별도로 명시되지 않는 한 이 값은 명세에서 그 함수에 부여된 이름이다. 익명 함수로 식별된 함수들은 빈 문자열을 "name" 프로퍼티 값으로 사용한다. 객체의 프로퍼티로 명세된 함수의 경우 이름 값은 그 함수를 접근하는 데 쓰이는 프로퍼티 이름 문자열이다. 내장 프로퍼티의 get 또는 set 접근자 함수로 명세된 함수는 CreateBuiltinFunction 을 호출할 때 prefix 매개변수로 각각 "get" 또는 "set" 을 전달한다.

프로퍼티 키가 Symbol 값인 각 내장 함수에 대해 "name" 프로퍼티 값은 명시적으로 지정된다. 그러한 명시적 값이 접두사 "get " 또는 "set " 로 시작하고 그 함수가 내장 프로퍼티의 get 또는 set 접근자 함수라면, 접두사를 제거한 값이 name 매개변수로 전달되고 "get" 또는 "set" 값이 prefix 매개변수로 전달된다.

별도로 명시되지 않는 한 내장 함수 객체"name" 프로퍼티는 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true } 특성을 가진다.

19 부터 28 절 및 부록 B.2 에 기술된 다른 모든 데이터 프로퍼티는 명시적으로 달리 지정되지 않는 한 { [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: true } 특성을 갖는다.

19 부터 28 절 및 부록 B.2 에 기술된 모든 접근자 프로퍼티는 명시적으로 달리 지정되지 않는 한 { [[Enumerable]]: false, [[Configurable]]: true } 특성을 갖는다. get 접근자 함수만 기술된 경우 set 접근자 함수의 기본값은 undefined 이다. set 접근자만 기술된 경우 get 접근자의 기본값은 undefined 이다.

19 전역 객체(The Global Object)

전역 객체:

19.1 전역 객체의 값(Value) 프로퍼티

19.1.1 globalThis

Realm Record realm 에서 전역 객체"globalThis" 프로퍼티 초기 값은 realm.[[GlobalEnv]].[[GlobalThisValue]] 이다.

이 프로퍼티는 { [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: true } 특성을 갖는다.

19.1.2 Infinity

Infinity 의 값은 +∞𝔽 이다(6.1.6.1 참조). 이 프로퍼티는 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false } 특성을 갖는다.

19.1.3 NaN

NaN 의 값은 NaN 이다(6.1.6.1 참조). 이 프로퍼티는 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false } 특성을 갖는다.

19.1.4 undefined

undefined 의 값은 undefined 이다(6.1.1 참조). 이 프로퍼티는 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false } 특성을 갖는다.

19.2 전역 객체의 함수(Function) 프로퍼티

19.2.1 eval ( x )

이 함수는 %eval% 고유(intrinsic) 객체이다.

호출 시 다음 단계를 수행한다:

  1. Return ? PerformEval(x, false, false).

19.2.1.1 PerformEval ( x, strictCaller, direct )

The abstract operation PerformEval takes arguments x (ECMAScript 언어 값), strictCaller (Boolean), and direct (Boolean) and returns ECMAScript 언어 값을 담은 정상 completion 또는 throw completion. It performs the following steps when called:

  1. 단언: directfalse 이면 strictCallerfalse.
  2. x 가 String 이 아니면 x 를 반환.
  3. evalRealm 을 현재 Realm Record 로 둔다.
  4. 참고: direct eval 의 경우 evalRealmeval 호출자와 eval 함수 자체의 realm 이다.
  5. HostEnsureCanCompileStrings(evalRealm, « », x, direct) 수행.
  6. inFunction = false.
  7. inMethod = false.
  8. inDerivedConstructor = false.
  9. inClassFieldInitializer = false.
  10. directtrue 이면
    1. thisEnvRec = GetThisEnvironment().
    2. thisEnvRecFunction Environment Record 이면
      1. F = thisEnvRec.[[FunctionObject]].
      2. inFunction = true 로.
      3. inMethod = thisEnvRec.HasSuperBinding().
      4. F.[[ConstructorKind]]derived 이면 inDerivedConstructor = true.
      5. classFieldInitializerName = F.[[ClassFieldInitializerName]].
      6. classFieldInitializerNameempty 가 아니면 inClassFieldInitializer = true.
  11. 구현 정의 순서(파싱과 오류 검출을 교차 실행 가능)로 다음 하위 단계 수행:
    1. script = ParseText(x, Script).
    2. script 가 오류 리스트면 SyntaxError 예외 throw.
    3. script Contains ScriptBodyfalse 이면 undefined 반환.
    4. body = scriptScriptBody.
    5. inFunctionfalse 이고 body Contains NewTarget 이면 SyntaxError throw.
    6. inMethodfalse 이고 body Contains SuperProperty 이면 SyntaxError throw.
    7. inDerivedConstructorfalse 이고 body Contains SuperCall 이면 SyntaxError throw.
    8. inClassFieldInitializertrue 이고 ContainsArguments(body) 가 true 이면 SyntaxError throw.
  12. strictCallertrue 이면 strictEval = true.
  13. Else strictEval = ScriptIsStrict(script).
  14. runningContext = 실행 중 실행 컨텍스트.
  15. 참고: direct true 이면 호출한 컨텍스트; false 이면 eval 호출 실행 컨텍스트.
  16. directtrue 이면
    1. lexEnv = NewDeclarativeEnvironment(runningContext.LexicalEnvironment).
    2. varEnv = runningContext.VariableEnvironment.
    3. privateEnv = runningContext.PrivateEnvironment.
  17. Else
    1. lexEnv = NewDeclarativeEnvironment(evalRealm.[[GlobalEnv]]).
    2. varEnv = evalRealm.[[GlobalEnv]].
    3. privateEnv = null.
  18. strictEvaltrue 이면 varEnv = lexEnv.
  19. runningContext 가 아직 suspend 상태가 아니면 suspend.
  20. evalContext = 새 ECMAScript 코드 실행 컨텍스트.
  21. evalContext.Function = null.
  22. evalContext.Realm = evalRealm.
  23. evalContext.ScriptOrModule = runningContext.ScriptOrModule.
  24. evalContext.VariableEnvironment = varEnv.
  25. evalContext.LexicalEnvironment = lexEnv.
  26. evalContext.PrivateEnvironment = privateEnv.
  27. evalContext 를 실행 컨텍스트 스택에 push; 현재 실행 컨텍스트.
  28. result = Completion(EvalDeclarationInstantiation(body, varEnv, lexEnv, privateEnv, strictEval)).
  29. result 가 normal 이면
    1. result = Completion(Evaluation(body)).
  30. result 가 normal 이고 result.[[Value]]empty 이면
    1. result = NormalCompletion(undefined).
  31. evalContext suspend 후 스택에서 제거.
  32. 스택 맨 위 컨텍스트 resume.
  33. Return ? result.
Note

eval 코드는 호출 컨텍스트나 eval 코드 둘 중 하나라도 strict 모드이면 호출자 변수 환경에 var/function 바인딩을 인스턴스화할 수 없다. 대신 새 VariableEnvironment 에 인스턴스화된다. let, const, class 선언이 도입하는 바인딩은 항상 새 LexicalEnvironment 에 인스턴스화된다.

19.2.1.2 HostEnsureCanCompileStrings ( calleeRealm, parameterStrings, bodyString, direct )

The host-defined abstract operation HostEnsureCanCompileStrings takes arguments calleeRealm (Realm Record), parameterStrings (문자열 리스트), bodyString (String), and direct (Boolean) and returns unused 를 담은 정상 completion 또는 throw completion. 문자열을 ECMAScript 코드로 해석·평가할 수 있게 하는 특정 ECMAScript 함수를 호스트 환경이 차단할 수 있도록 한다.

parameterStrings 는 함수 생성자 중 하나를 사용할 때 파라미터 목록을 구성하기 위해 연결될 문자열들을 나타낸다. bodyString 은 함수 본문 또는 eval 에 전달된 문자열을 나타낸다. direct 는 평가가 direct eval 인지 여부를 나타낸다.

기본 구현은 NormalCompletion(unused) 을 반환한다.

19.2.1.3 EvalDeclarationInstantiation ( body, varEnv, lexEnv, privateEnv, strict )

The abstract operation EvalDeclarationInstantiation takes arguments body (ScriptBody Parse Node), varEnv (Environment Record), lexEnv (Declarative Environment Record), privateEnv (PrivateEnvironment Record 또는 null), and strict (Boolean) and returns unused 를 담은 정상 completion 또는 throw completion. It performs the following steps when called:

  1. varNames = VarDeclaredNames(body).
  2. varDeclarations = VarScopedDeclarations(body).
  3. strictfalse 이면
    1. varEnvGlobal Environment Record 이면
      1. namevarNames 에 대해
        1. HasLexicalDeclaration(varEnv, name) 가 true 이면 SyntaxError throw.
        2. 참고: eval 은 전역 lexical 선언에 의해 shadow 되는 전역 var 선언을 만들지 않는다.
    2. thisEnv = lexEnv.
    3. 단언: 다음 루프는 종료한다.
    4. 반복 (thisEnvvarEnv 가 동일 Environment Record 가 아닐 동안)
      1. thisEnvObject Environment Record 가 아니면
        1. 참고: with 문의 환경은 lexical 선언을 포함할 수 없으므로 var/let hoisting 충돌 점검 불필요.
        2. namevarNames 에 대해
          1. thisEnv.HasBinding(name) 가 true 이면
            1. Normative Optional
              호스트가 웹 브라우저이거나 Catch 블록 내 VariableStatement 를 지원하면
              1. thisEnvCatch 절의 Environment Record 가 아니면 SyntaxError throw.
            2. Else
              1. SyntaxError throw.
          2. 참고: direct eval 은 같은 이름의 lexical 선언 위로 var 를 hoist 하지 않는다.
      2. thisEnv = thisEnv.[[OuterEnv]].
  4. privateIdentifiers = 새 빈 리스트.
  5. pointer = privateEnv.
  6. 반복 (pointernull)
    1. pointer.[[Names]] 의 각 Private Name binding 에 대해
      1. privateIdentifiersbinding.[[Description]] 포함하지 않으면 append.
    2. pointer = pointer.[[OuterPrivateEnvironment]].
  7. AllPrivateIdentifiersValid(body, privateIdentifiers) 가 false 이면 SyntaxError throw.
  8. functionsToInitialize = 새 빈 리스트.
  9. declaredFunctionNames = 새 빈 리스트.
  10. varDeclarations 을 역순으로 순회하며 각 d 에 대해
    1. dVariableDeclaration, ForBinding, BindingIdentifier 가 아니면
      1. 단언: dFunctionDeclaration, GeneratorDeclaration, AsyncFunctionDeclaration, AsyncGeneratorDeclaration.
      2. 참고: 같은 이름의 다수 함수 선언이 있으면 마지막 것이 사용됨.
      3. fn = BoundNames(d) 의 유일한 요소.
      4. declaredFunctionNamesfn 포함하지 않으면
        1. varEnvGlobal Environment Record 이면
          1. fnDefinable = ? CanDeclareGlobalFunction(varEnv, fn).
          2. fnDefinablefalse 이면 TypeError throw.
        2. fndeclaredFunctionNames 에 추가.
        3. dfunctionsToInitialize 의 첫 요소로 삽입.
  11. declaredVarNames = 새 빈 리스트.
  12. varDeclarations 의 각 d 에 대해
    1. dVariableDeclaration, ForBinding, BindingIdentifier 이면
      1. BoundNames(d) 의 각 String vn 에 대해
        1. declaredFunctionNamesvn 포함하지 않으면
          1. varEnvGlobal Environment Record 이면
            1. vnDefinable = ? CanDeclareGlobalVar(varEnv, vn).
            2. vnDefinable false 이면 TypeError throw.
          2. declaredVarNamesvn 포함하지 않으면 append.
  13. Normative Optional
    strictfalse 이고 호스트가 웹 브라우저이거나 블록 수준 함수 선언 웹 레거시 호환 의미 를 지원하면
    1. declaredFunctionOrVarNames = declaredFunctionNamesdeclaredVarNames (리스트 연결).
    2. body Contains xtrue 인 모든 Block, CaseClause, DefaultClause xStatementList 에 직접 포함된 각 FunctionDeclaration f 에 대해
      1. F = fBindingIdentifier StringValue.
      2. fFBindingIdentifier 로 하는 VariableStatement 로 치환해도 body 에 Early Error 가 발생하지 않으면
        1. bindingExists = false.
        2. thisEnv = lexEnv.
        3. 단언: 루프 종료 보장.
        4. 반복 (thisEnvvarEnv)
          1. thisEnvObject Environment Record 가 아니면
            1. thisEnv.HasBinding(F) 가 true 이면
              1. Normative Optional
                호스트가 웹 브라우저이거나 Catch 블록 내 VariableStatement 를 지원하면
                1. thisEnvCatchEnvironment Record 가 아니면 bindingExists = true.
              2. Else
                1. bindingExists = true.
          2. thisEnv = thisEnv.[[OuterEnv]].
        5. bindingExistsfalse 이고 varEnvGlobal Environment Record 이면
          1. HasLexicalDeclaration(varEnv, F) 가 false 이면
            1. fnDefinable = ? CanDeclareGlobalVar(varEnv, F).
          2. Else
            1. fnDefinable = false.
        6. Else
          1. fnDefinable = true.
        7. bindingExists false 이고 fnDefinable true 이면
          1. declaredFunctionOrVarNamesF 포함하지 않으면
            1. varEnvGlobal Environment Record 이면
              1. CreateGlobalVarBinding(varEnv, F, true).
            2. Else
              1. bindingExists = ! varEnv.HasBinding(F).
              2. bindingExists false 이면
                1. varEnv.CreateMutableBinding(F, true).
                2. varEnv.InitializeBinding(F, undefined).
            3. FdeclaredFunctionOrVarNames 에 추가.
          2. FunctionDeclaration f 평가 시 15.2.6 의 기본 알고리즘 대신:
            1. gEnv = 실행 중 컨텍스트 VariableEnvironment.
            2. bEnv = 실행 중 컨텍스트 LexicalEnvironment.
            3. fObj = ! bEnv.GetBindingValue(F, false).
            4. gEnv.SetMutableBinding(F, fObj, false).
            5. unused 반환.
  14. 참고: varEnvGlobal Environment Record 이고 전역 객체가 Proxy exotic object 인 경우가 아니면 이 단계 이후 비정상 종료 없음.
  15. lexDeclarations = LexicallyScopedDeclarations(body).
  16. dlexDeclarations 에 대해
    1. 참고: 어휘 선언된 이름은 여기서 인스턴스화만 하고 초기화하지 않음.
    2. BoundNames(d) 의 각 dn 에 대해
      1. IsConstantDeclaration(d) true 이면
        1. lexEnv.CreateImmutableBinding(dn, true).
      2. Else
        1. lexEnv.CreateMutableBinding(dn, false).
  17. functionsToInitialize 의 각 Parse Node f 에 대해
    1. fn = BoundNames(f) 의 유일한 요소.
    2. fo = InstantiateFunctionObject(f, lexEnv, privateEnv).
    3. varEnvGlobal Environment Record 이면
      1. CreateGlobalFunctionBinding(varEnv, fn, fo, true).
    4. Else
      1. bindingExists = ! varEnv.HasBinding(fn).
      2. bindingExists false 이면
        1. 참고: 앞선 검증 때문에 abrupt 발생 불가.
        2. varEnv.CreateMutableBinding(fn, true).
        3. varEnv.InitializeBinding(fn, fo).
      3. Else
        1. varEnv.SetMutableBinding(fn, fo, false).
  18. 각 String vndeclaredVarNames 에 대해
    1. varEnvGlobal Environment Record 이면
      1. CreateGlobalVarBinding(varEnv, vn, true).
    2. Else
      1. bindingExists = ! varEnv.HasBinding(vn).
      2. bindingExists false 이면
        1. 참고: 앞선 검증으로 abrupt 불가.
        2. varEnv.CreateMutableBinding(vn, true).
        3. varEnv.InitializeBinding(vn, undefined).
  19. unused 반환.

19.2.2 isFinite ( number )

이 함수는 %isFinite% 고유 객체이다.

호출 시 다음 단계를 수행한다:

  1. num = ? ToNumber(number).
  2. num 이 finite 가 아니면 false 반환.
  3. 그렇지 않으면 true 반환.

19.2.3 isNaN ( number )

이 함수는 %isNaN% 고유 객체이다.

호출 시 다음 단계를 수행한다:

  1. num = ? ToNumber(number).
  2. numNaN 이면 true 반환.
  3. 그렇지 않으면 false 반환.
Note

XNaN 인지 신뢰성 있게 시험하는 ECMAScript 표현은 X !== X 형태이다. 결과가 true 이면 그리고 오직 그때만 XNaN 이다.

19.2.4 parseFloat ( string )

이 함수는 string 인수를 10진 리터럴로 해석한 결과에 따라 Number 값을 생성한다.

%parseFloat% 고유 객체이다.

호출 시 다음 단계를 수행한다:

  1. inputString = ? ToString(string).
  2. trimmedString = ! TrimString(inputString, start).
  3. trimmed = StringToCodePoints(trimmedString).
  4. trimmedPrefix = StrDecimalLiteral 문법을 만족하는(없으면 없음) 가장 긴 접두사. 없다면 NaN 반환.
  5. parsedNumber = ParseText(trimmedPrefix, StrDecimalLiteral).
  6. 단언: parsedNumber 는 Parse Node.
  7. parsedNumber 의 StringNumericValue 반환.
Note

이 함수는 string 의 선두 일부만 Number 로 해석할 수 있고, 10진 표기 일부가 될 수 없는 코드 유닛은 무시하며 무시되었다는 표시를 제공하지 않는다.

19.2.5 parseInt ( string, radix )

이 함수는 radix 에 따라 string 내용을 해석하여 정수 Number 값을 생성한다. string 의 선행 공백은 무시된다. radix 가 0 으로 강제될 경우(예: undefined) 표현이 "0x" 또는 "0X" 로 시작하지 않으면 10, 그렇다면 16 으로 간주한다. radix 가 16 이면 표현은 "0x" / "0X" 로 시작할 수도 있다.

%parseInt% 고유 객체이다.

호출 시 다음 단계를 수행한다:

  1. inputString = ? ToString(string).
  2. S = ! TrimString(inputString, start).
  3. sign = 1.
  4. S 가 비어 있지 않고 첫 코드 유닛이 0x002D 이면 sign = -1.
  5. S 가 비어 있지 않고 첫 코드 유닛이 0x002B 또는 0x002D 이면 S = 인덱스 1 부터.
  6. R = (? ToInt32(radix)).
  7. stripPrefix = true.
  8. R ≠ 0 이면
    1. R < 2 또는 R > 36 이면 NaN 반환.
    2. R ≠ 16 이면 stripPrefix = false.
  9. Else
    1. R = 10.
  10. stripPrefix true 이면
    1. S 길이 ≥ 2 이고 첫 두 코드 유닛이 "0x" 또는 "0X" 이면
      1. S = 인덱스 2 부터.
      2. R = 16.
  11. S 가 radix-R 숫자가 아닌 코드 유닛을 포함하면 end = 그 첫 위치, 아니면 길이.
  12. Z = S[0..end).
  13. Z 가 비어 있으면 NaN 반환.
  14. mathInt = Z 가 radix-R 표기에서 나타내는 정수 (규정된 근사 허용).
  15. mathInt = 0 이면
    1. sign = -1 이면 -0𝔽 반환.
    2. +0𝔽 반환.
  16. 𝔽(sign × mathInt) 반환.
Note

이 함수는 string 의 선두 일부만 정수로 해석할 수 있으며 나머지는 무시되고 무시 사실은 표시되지 않는다.

19.2.6 URI 처리 함수

Uniform Resource Identifier(URI)는 자원(웹 페이지, 파일 등)과 Internet 상에서 그것에 접근할 전송 프로토콜(HTTP, FTP 등)을 식별하는 String 이다. ECMAScript 자체는 이 절에 기술된 URI 인코딩·디코딩 함수 외에는 URI 사용 지원을 제공하지 않는다. encodeURI, decodeURI 는 전체 URI 에 사용하도록 의도되며 예약 문자는 특별한 의미(구분자 등)를 가정하므로 인코딩하지 않는다. encodeURIComponent, decodeURIComponent 는 URI 개별 구성 요소에 사용하도록 의도되며, 예약 문자가 텍스트를 나타낸다고 가정하고 전체 URI 의 일부가 될 때 특별한 의미를 피하기 위해 인코딩해야 한다.

Note 1

예약 문자 집합은 RFC 2396 에 기반하며 최신 RFC 3986 의 변경을 반영하지 않는다.

Note 2

많은 ECMAScript 구현은 웹 페이지를 조작하는 추가 함수·메서드를 제공하는데, 이는 표준 범위를 벗어난다.

19.2.6.1 decodeURI ( encodedURI )

이 함수는 encodeURI 가 도입할 수 있는 종류의 각 escape 시퀀스 및 UTF-8 인코딩을 해당 코드 포인트의 UTF-16 인코딩으로 치환한 URI 새 버전을 계산한다. encodeURI 가 도입할 수 없었던 escape 시퀀스는 치환하지 않는다.

%decodeURI% 고유 객체이다.

호출 시 다음 단계를 수행한다:

  1. uriString = ? ToString(encodedURI).
  2. preserveEscapeSet = ";/?:@&=+$,#".
  3. Return ? Decode(uriString, preserveEscapeSet).

19.2.6.2 decodeURIComponent ( encodedURIComponent )

이 함수는 encodeURIComponent 가 도입할 수 있는 종류의 각 escape 시퀀스 및 UTF-8 인코딩을 해당 코드 포인트의 UTF-16 인코딩으로 치환한 새 버전을 계산한다.

%decodeURIComponent% 고유 객체이다.

호출 시 다음 단계를 수행한다:

  1. componentString = ? ToString(encodedURIComponent).
  2. preserveEscapeSet = 빈 문자열.
  3. Return ? Decode(componentString, preserveEscapeSet).

19.2.6.3 encodeURI ( uri )

이 함수는 UTF-16 인코딩(6.1.4) 된 URI 에서 특정 코드 포인트의 각 출현을 그 코드 포인트의 UTF-8 인코딩을 나타내는 1~4개의 escape 시퀀스로 대체한 새 버전을 계산한다.

%encodeURI% 고유 객체이다.

호출 시 다음 단계를 수행한다:

  1. uriString = ? ToString(uri).
  2. extraUnescaped = ";/?:@&=+$,#".
  3. Return ? Encode(uriString, extraUnescaped).

19.2.6.4 encodeURIComponent ( uriComponent )

이 함수는 UTF-16 인코딩된 URI 구성 요소에서 특정 코드 포인트의 각 출현을 그 코드 포인트의 UTF-8 인코딩을 나타내는 1~4개의 escape 시퀀스로 대체한 새 버전을 계산한다.

%encodeURIComponent% 고유 객체이다.

호출 시 다음 단계를 수행한다:

  1. componentString = ? ToString(uriComponent).
  2. extraUnescaped = 빈 문자열.
  3. Return ? Encode(componentString, extraUnescaped).

19.2.6.5 Encode ( string, extraUnescaped )

The abstract operation Encode takes arguments string (String) and extraUnescaped (String) and returns String 을 담은 정상 completion 또는 throw completion. string6.1.4 에 기술된 대로 UTF-16 인코딩된 코드 포인트 시퀀스로 해석하여 URI 인코딩·escape 를 수행한다. RFC 2396 에서 unreserved 로 식별되었거나 extraUnescaped 에 등장하는 문자는 escape 하지 않는다. It performs the following steps when called:

  1. len = string 길이.
  2. R = 빈 문자열.
  3. alwaysUnescaped = ASCII 단어 문자들과 "-.!~*'()" 의 문자열 연결.
  4. unescapedSet = alwaysUnescaped + extraUnescaped.
  5. k = 0.
  6. 반복 (k < len)
    1. C = string[k] 코드 유닛.
    2. unescapedSetC 포함하면
      1. k = k + 1.
      2. R = R + C.
    3. Else
      1. cp = CodePointAt(string, k).
      2. cp.[[IsUnpairedSurrogate]] true 이면 URIError throw.
      3. k = k + cp.[[CodeUnitCount]].
      4. Octets = cp.[[CodePoint]] 에 UTF-8 변환 적용한 octet 리스트.
      5. octetOctets 에 대해
        1. hex = octet 의 대문자 16진 문자열.
        2. R = R + "%" + StringPad(hex, 2, "0", start).
  7. R 반환.
Note

퍼센트 인코딩은 개별 octet 을 표현하므로 하나의 코드 포인트가 여러 연속 escape 시퀀스(각각 하나의 8비트 UTF-8 코드 유닛)에 의해 표현될 수 있다.

19.2.6.6 Decode ( string, preserveEscapeSet )

The abstract operation Decode takes arguments string (String) and preserveEscapeSet (String) and returns String 을 담은 정상 completion 또는 throw completion. preserveEscapeSet 에 포함된 Basic Latin 문자에 대응하는 escape 시퀀스를 보존하면서 URI unescape 및 디코딩을 수행한다. It performs the following steps when called:

  1. len = string 길이.
  2. R = 빈 문자열.
  3. k = 0.
  4. 반복 (k < len)
    1. C = string[k] 코드 유닛.
    2. S = C.
    3. C = 0x0025 ( %) 이면
      1. k + 3 > len 이면 URIError throw.
      2. escape = string[k .. k+3).
      3. B = ParseHexOctet(string, k + 1).
      4. B 가 정수가 아니면 URIError throw.
      5. k = k + 2.
      6. n = B 의 선행 1 비트 개수.
      7. n = 0 이면
        1. asciiChar = 값이 B 인 코드 유닛.
        2. preserveEscapeSetasciiChar 포함하면 S = escape, 아니면 S = asciiChar.
      8. Else
        1. n = 1 또는 n > 4 이면 URIError throw.
        2. Octets = « B ».
        3. j = 1.
        4. 반복 (j < n)
          1. k = k + 1.
          2. k + 3 > len 이면 URIError throw.
          3. string[k] ≠ 0x0025 이면 URIError throw.
          4. continuationByte = ParseHexOctet(string, k + 1).
          5. continuationByte 가 정수가 아니면 URIError throw.
          6. Octets 에 append(continuationByte).
          7. k = k + 2.
          8. j = j + 1.
        5. 단언: Octets 길이 = n.
        6. Octets 가 유효한 UTF-8 코드 포인트 인코딩이 아니면 URIError throw.
        7. V = UTF-8 변환을 적용해 얻은 코드 포인트.
        8. S = UTF16EncodeCodePoint(V).
    4. R = R + S.
    5. k = k + 1.
  5. R 반환.
Note

RFC 3629 는 잘못된 UTF-8 옥텟 시퀀스 디코딩을 금지한다. 예: 잘못된 시퀀스 0xC0 0x80 은 0x0000 으로 디코딩되어서는 안 된다. 구현은 그러한 시퀀스를 만나면 URIError 를 던져야 한다.

19.2.6.7 ParseHexOctet ( string, position )

The abstract operation ParseHexOctet takes arguments string (String) and position (음이 아닌 정수) and returns 음이 아닌 정수 또는 비어있지 않은 SyntaxError 객체 리스트. stringposition 위치에 있는 두 개 16진 문자를 부호 없는 8비트 정수로 파싱한다. It performs the following steps when called:

  1. len = string 길이.
  2. 단언: position + 2 ≤ len.
  3. hexDigits = string[position .. position+2).
  4. parseResult = ParseText(hexDigits, HexDigits[~Sep]).
  5. parseResult 가 Parse Node 가 아니면 parseResult 반환.
  6. n = parseResult 의 MV.
  7. 단언: 0 ≤ n ≤ 255.
  8. n 반환.

19.3 전역 객체의 생성자(Constructor) 프로퍼티

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 BigInt ( . . . )

21.2.1 참조.

19.3.5 BigInt64Array ( . . . )

23.2.5 참조.

19.3.6 BigUint64Array ( . . . )

23.2.5 참조.

19.3.7 Boolean ( . . . )

20.3.1 참조.

19.3.8 DataView ( . . . )

25.3.2 참조.

19.3.9 Date ( . . . )

21.4.2 참조.

19.3.10 Error ( . . . )

20.5.1 참조.

19.3.11 EvalError ( . . . )

20.5.5.1 참조.

19.3.12 FinalizationRegistry ( . . . )

26.2.1 참조.

19.3.13 Float16Array ( . . . )

23.2.5 참조.

19.3.14 Float32Array ( . . . )

23.2.5 참조.

19.3.15 Float64Array ( . . . )

23.2.5 참조.

19.3.16 Function ( . . . )

20.2.1 참조.

19.3.17 Int8Array ( . . . )

23.2.5 참조.

19.3.18 Int16Array ( . . . )

23.2.5 참조.

19.3.19 Int32Array ( . . . )

23.2.5 참조.

19.3.20 Iterator ( . . . )

27.1.3.1 참조.

19.3.21 Map ( . . . )

24.1.1 참조.

19.3.22 Number ( . . . )

21.1.1 참조.

19.3.23 Object ( . . . )

20.1.1 참조.

19.3.24 Promise ( . . . )

27.2.3 참조.

19.3.25 Proxy ( . . . )

28.2.1 참조.

19.3.26 RangeError ( . . . )

20.5.5.2 참조.

19.3.27 ReferenceError ( . . . )

20.5.5.3 참조.

19.3.28 RegExp ( . . . )

22.2.4 참조.

19.3.29 Set ( . . . )

24.2.2 참조.

19.3.30 SharedArrayBuffer ( . . . )

25.2.3 참조.

19.3.31 String ( . . . )

22.1.1 참조.

19.3.32 Symbol ( . . . )

20.4.1 참조.

19.3.33 SyntaxError ( . . . )

20.5.5.4 참조.

19.3.34 TypeError ( . . . )

20.5.5.5 참조.

19.3.35 Uint8Array ( . . . )

23.2.5 참조.

19.3.36 Uint8ClampedArray ( . . . )

23.2.5 참조.

19.3.37 Uint16Array ( . . . )

23.2.5 참조.

19.3.38 Uint32Array ( . . . )

23.2.5 참조.

19.3.39 URIError ( . . . )

20.5.5.6 참조.

19.3.40 WeakMap ( . . . )

24.3.1 참조.

19.3.41 WeakRef ( . . . )

26.1.1 참조.

19.3.42 WeakSet ( . . . )

24.4 참조.

19.4 전역 객체의 기타 프로퍼티

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 객체

20.1.1 Object 생성자

Object 생성자는 다음과 같다:

  • %Object% 이다.
  • 전역 객체 "Object" 프로퍼티의 초기 값이다.
  • 생성자로 호출될 때 새로운 일반(ordinary) 객체를 생성한다.
  • 생성자가 아니라 함수로 호출될 때 타입 변환을 수행한다.
  • 클래스 정의의 extends 절 값으로 사용할 수 있다.

20.1.1.1 Object ( [ value ] )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. NewTarget 이 undefined 도 아니고 활성 함수 객체도 아니면
    1. OrdinaryCreateFromConstructor(NewTarget, "%Object.prototype%") 를 반환한다.
  2. valueundefined 또는 null 이면 OrdinaryObjectCreate(%Object.prototype%) 를 반환한다.
  3. ToObject(value) 를 반환한다.

20.1.2 Object 생성자의 프로퍼티

Object 생성자는:

  • 값이 %Function.prototype%[[Prototype]] 내부 슬롯을 갖는다.
  • 값이 1𝔽"length" 프로퍼티를 갖는다.
  • 다음 추가 프로퍼티들을 갖는다:

20.1.2.1 Object.assign ( target, ...sources )

이 함수는 하나 이상의 소스 객체의 열거 가능하고 자체(own)인 모든 프로퍼티 값을 target 객체로 복사한다.

호출될 때 다음 단계를 수행한다:

  1. to 를 ? ToObject(target) 로 둔다.
  2. 인수가 하나만 전달되었다면 to 를 반환한다.
  3. sources 의 각 요소 nextSource 에 대해
    1. nextSourceundefinednull 도 아니면
      1. from 을 ! ToObject(nextSource) 로 둔다.
      2. keys 를 ? from.[[OwnPropertyKeys]]() 로 둔다.
      3. keys 의 각 요소 nextKey 에 대해
        1. desc 를 ? from.[[GetOwnProperty]](nextKey) 로 둔다.
        2. descundefined 가 아니고 desc.[[Enumerable]]true 이면
          1. propValue 를 ? Get(from, nextKey) 로 둔다.
          2. Set(to, nextKey, propValue, true) 를 수행한다.
  4. to 를 반환한다.

이 함수의 "length" 프로퍼티는 2𝔽 이다.

20.1.2.2 Object.create ( O, Properties )

이 함수는 지정된 프로토타입을 가진 새 객체를 생성한다.

호출될 때 다음 단계를 수행한다:

  1. O 가 Object 가 아니고 null 도 아니면 TypeError 예외를 throw 한다.
  2. objOrdinaryObjectCreate(O) 로 둔다.
  3. Propertiesundefined 가 아니면
    1. ObjectDefineProperties(obj, Properties) 를 반환한다.
  4. obj 를 반환한다.

20.1.2.3 Object.defineProperties ( O, Properties )

이 함수는 객체에 자체 프로퍼티를 추가하고/또는 기존 자체 프로퍼티의 특성을 갱신한다.

호출될 때 다음 단계를 수행한다:

  1. O 가 Object 가 아니면 TypeError 예외를 throw 한다.
  2. ObjectDefineProperties(O, Properties) 를 반환한다.

20.1.2.3.1 ObjectDefineProperties ( O, Properties )

The abstract operation ObjectDefineProperties takes arguments O (Object) and Properties (ECMAScript 언어 값) and returns Object 를 담은 정상 completion 또는 throw completion. It performs the following steps when called:

  1. props 를 ? ToObject(Properties) 로 둔다.
  2. keys 를 ? props.[[OwnPropertyKeys]]() 로 둔다.
  3. descriptors 를 새 빈 리스트로 둔다.
  4. keys 의 각 요소 nextKey 에 대해
    1. propDesc 를 ? props.[[GetOwnProperty]](nextKey) 로 둔다.
    2. propDescundefined 가 아니고 propDesc.[[Enumerable]]true 이면
      1. descObj 를 ? Get(props, nextKey) 로 둔다.
      2. desc 를 ? ToPropertyDescriptor(descObj) 로 둔다.
      3. Record { [[Key]]: nextKey, [[Descriptor]]: desc } 를 descriptors 에 추가한다.
  5. descriptors 의 각 요소 property 에 대해
    1. DefinePropertyOrThrow(O, property.[[Key]], property.[[Descriptor]]) 를 수행한다.
  6. O 를 반환한다.

20.1.2.4 Object.defineProperty ( O, P, Attributes )

이 함수는 객체에 자체 프로퍼티를 추가하고/또는 기존 자체 프로퍼티의 특성을 갱신한다.

호출될 때 다음 단계를 수행한다:

  1. O 가 Object 가 아니면 TypeError 예외를 throw 한다.
  2. key 를 ? ToPropertyKey(P) 로 둔다.
  3. desc 를 ? ToPropertyDescriptor(Attributes) 로 둔다.
  4. DefinePropertyOrThrow(O, key, desc) 를 수행한다.
  5. O 를 반환한다.

20.1.2.5 Object.entries ( O )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. obj 를 ? ToObject(O) 로 둔다.
  2. entryList 를 ? EnumerableOwnProperties(obj, key+value) 로 둔다.
  3. CreateArrayFromList(entryList) 를 반환한다.

20.1.2.6 Object.freeze ( O )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. O 가 Object 가 아니면 O 를 반환한다.
  2. status 를 ? SetIntegrityLevel(O, frozen) 으로 둔다.
  3. statusfalse 이면 TypeError 예외를 throw 한다.
  4. O 를 반환한다.

20.1.2.7 Object.fromEntries ( iterable )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. RequireObjectCoercible(iterable) 를 수행한다.
  2. objOrdinaryObjectCreate(%Object.prototype%) 로 둔다.
  3. 단언: obj 는 확장 가능하고 자체 프로퍼티가 없는 ordinary 객체.
  4. closure 를 (key, value) 매개변수로 하고 obj 를 캡처하며 호출 시 다음 단계를 수행하는 새 Abstract Closure 로 둔다:
    1. propertyKey 를 ? ToPropertyKey(key) 로 둔다.
    2. CreateDataPropertyOrThrow(obj, propertyKey, value) 를 수행한다.
    3. NormalCompletion(undefined) 를 반환한다.
  5. adderCreateBuiltinFunction(closure, 2, "", « ») 로 둔다.
  6. AddEntriesFromIterable(obj, iterable, adder) 를 반환한다.
Note
adder 용으로 생성된 함수는 ECMAScript 코드에서 직접 접근할 수 없다.

20.1.2.8 Object.getOwnPropertyDescriptor ( O, P )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. obj 를 ? ToObject(O) 로 둔다.
  2. key 를 ? ToPropertyKey(P) 로 둔다.
  3. desc 를 ? obj.[[GetOwnProperty]](key) 로 둔다.
  4. FromPropertyDescriptor(desc) 를 반환한다.

20.1.2.9 Object.getOwnPropertyDescriptors ( O )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. obj 를 ? ToObject(O) 로 둔다.
  2. ownKeys 를 ? obj.[[OwnPropertyKeys]]() 로 둔다.
  3. descriptorsOrdinaryObjectCreate(%Object.prototype%) 로 둔다.
  4. ownKeys 의 각 요소 key 에 대해
    1. desc 를 ? obj.[[GetOwnProperty]](key) 로 둔다.
    2. descriptorFromPropertyDescriptor(desc) 로 둔다.
    3. descriptorundefined 가 아니면 ! CreateDataPropertyOrThrow(descriptors, key, descriptor) 를 수행한다.
  5. descriptors 를 반환한다.

20.1.2.10 Object.getOwnPropertyNames ( O )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. CreateArrayFromList(? GetOwnPropertyKeys(O, string)) 를 반환한다.

20.1.2.11 Object.getOwnPropertySymbols ( O )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. CreateArrayFromList(? GetOwnPropertyKeys(O, symbol)) 를 반환한다.

20.1.2.11.1 GetOwnPropertyKeys ( O, type )

The abstract operation GetOwnPropertyKeys takes arguments O (ECMAScript 언어 값) and type (string 또는 symbol) and returns 프로퍼티 키 리스트를 담은 정상 completion 또는 throw completion. It performs the following steps when called:

  1. obj 를 ? ToObject(O) 로 둔다.
  2. keys 를 ? obj.[[OwnPropertyKeys]]() 로 둔다.
  3. nameList 를 새 빈 리스트로 둔다.
  4. keys 의 각 요소 nextKey 에 대해
    1. nextKey 가 Symbol 이고 typesymbol 이거나, nextKey 가 String 이고 typestring 이면
      1. nextKeynameList 에 추가한다.
  5. nameList 를 반환한다.

20.1.2.12 Object.getPrototypeOf ( O )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. obj 를 ? ToObject(O) 로 둔다.
  2. obj.[[GetPrototypeOf]]() 를 반환한다.

20.1.2.13 Object.groupBy ( items, callback )

Note

callback 은 두 개의 인수를 받는 함수여야 한다. groupByitems 의 각 요소에 대해 (오름차순으로) callback 을 한 번 호출하고 새 객체를 구성한다. callback 이 반환한 각 값은 프로퍼티 키로 강제 변환된다. 그러한 각 프로퍼티 키에 대해 결과 객체는 그 키를 프로퍼티 키로 가지며 값은 해당 키로 강제 변환된 callback 반환 값을 가진 모든 요소를 담은 배열이다.

callback 은 (요소의 값, 요소의 인덱스) 두 인수로 호출된다.

groupBy 의 반환 값은 %Object.prototype% 을 상속하지 않는 객체이다.

이 함수는 호출될 때 다음 단계를 수행한다:

  1. groups 를 ? GroupBy(items, callback, property) 로 둔다.
  2. objOrdinaryObjectCreate(null) 로 둔다.
  3. Record { [[Key]], [[Elements]] } ggroups 에 대해
    1. elementsCreateArrayFromList(g.[[Elements]]) 로 둔다.
    2. CreateDataPropertyOrThrow(obj, g.[[Key]], elements) 를 수행한다.
  4. obj 를 반환한다.

20.1.2.14 Object.hasOwn ( O, P )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. obj 를 ? ToObject(O) 로 둔다.
  2. key 를 ? ToPropertyKey(P) 로 둔다.
  3. HasOwnProperty(obj, key) 를 반환한다.

20.1.2.15 Object.is ( value1, value2 )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. SameValue(value1, value2) 를 반환한다.

20.1.2.16 Object.isExtensible ( O )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. O 가 Object 가 아니면 false 를 반환한다.
  2. IsExtensible(O) 를 반환한다.

20.1.2.17 Object.isFrozen ( O )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. O 가 Object 가 아니면 true 를 반환한다.
  2. TestIntegrityLevel(O, frozen) 을 반환한다.

20.1.2.18 Object.isSealed ( O )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. O 가 Object 가 아니면 true 를 반환한다.
  2. TestIntegrityLevel(O, sealed) 을 반환한다.

20.1.2.19 Object.keys ( O )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. obj 를 ? ToObject(O) 로 둔다.
  2. keyList 를 ? EnumerableOwnProperties(obj, key) 로 둔다.
  3. CreateArrayFromList(keyList) 를 반환한다.

20.1.2.20 Object.preventExtensions ( O )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. O 가 Object 가 아니면 O 를 반환한다.
  2. status 를 ? O.[[PreventExtensions]]() 로 둔다.
  3. statusfalse 이면 TypeError 예외를 throw 한다.
  4. O 를 반환한다.

20.1.2.21 Object.prototype

Object.prototype 의 초기 값은 Object 프로토타입 객체이다.

이 프로퍼티는 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false } 특성을 가진다.

20.1.2.22 Object.seal ( O )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. O 가 Object 가 아니면 O 를 반환한다.
  2. status 를 ? SetIntegrityLevel(O, sealed) 로 둔다.
  3. statusfalse 이면 TypeError 예외를 throw 한다.
  4. O 를 반환한다.

20.1.2.23 Object.setPrototypeOf ( O, proto )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. RequireObjectCoercible(O) 를 수행한다.
  2. proto 가 Object 가 아니고 null 도 아니면 TypeError 예외를 throw 한다.
  3. O 가 Object 가 아니면 O 를 반환한다.
  4. status 를 ? O.[[SetPrototypeOf]](proto) 로 둔다.
  5. statusfalse 이면 TypeError 예외를 throw 한다.
  6. O 를 반환한다.

20.1.2.24 Object.values ( O )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. obj 를 ? ToObject(O) 로 둔다.
  2. valueList 를 ? EnumerableOwnProperties(obj, value) 로 둔다.
  3. CreateArrayFromList(valueList) 를 반환한다.

20.1.3 Object 프로토타입 객체의 프로퍼티

Object 프로토타입 객체는:

  • %Object.prototype% 이다.
  • 값이 true[[Extensible]] 내부 슬롯을 가진다.
  • 일반 객체에 대해 정의된 내부 메서드를 갖되 [[SetPrototypeOf]] 메서드는 10.4.7.1 에 정의된 대로이다. (즉, 변경 불가능한 프로토타입 특수 객체이다.)
  • 값이 null[[Prototype]] 내부 슬롯을 가진다.

20.1.3.1 Object.prototype.constructor

Object.prototype.constructor 의 초기 값은 %Object% 이다.

20.1.3.2 Object.prototype.hasOwnProperty ( V )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. P 를 ? ToPropertyKey(V) 로 둔다.
  2. O 를 ? ToObject(this value) 로 둔다.
  3. HasOwnProperty(O, P) 를 반환한다.
Note

이전 판에서 step 1 가 던졌을 예외가 this 값이 undefined 또는 null 이어도 계속 던져지도록 step 순서를 선택하였다.

20.1.3.3 Object.prototype.isPrototypeOf ( V )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. V 가 Object 가 아니면 false 반환.
  2. O 를 ? ToObject(this value) 로 둔다.
  3. 반복,
    1. V 를 ? V.[[GetPrototypeOf]]() 로 둔다.
    2. Vnull 이면 false 반환.
    3. SameValue(O, V) 가 true 이면 true 반환.
Note

step 12 순서는 V 가 객체가 아니고 this 값이 undefined 또는 null 인 경우 이전 판 행동을 보존한다.

20.1.3.4 Object.prototype.propertyIsEnumerable ( V )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. P 를 ? ToPropertyKey(V) 로 둔다.
  2. O 를 ? ToObject(this value) 로 둔다.
  3. desc 를 ? O.[[GetOwnProperty]](P) 로 둔다.
  4. descundefined 이면 false 반환.
  5. desc.[[Enumerable]] 를 반환한다.
Note 1

이 메서드는 프로토타입 체인 상의 객체를 고려하지 않는다.

Note 2

이전 판에서 step 1 가 던졌을 예외가 this 값이 undefined 또는 null 이어도 계속 던져지도록 순서를 선택하였다.

20.1.3.5 Object.prototype.toLocaleString ( [ reserved1 [ , reserved2 ] ] )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. Othis 값으로 둔다.
  2. Invoke(O, "toString") 를 반환한다.

이 메서드의 선택적 매개변수들은 사용되지 않지만 ECMA-402 toLocaleString 메서드의 매개변수 패턴과 대응하도록 의도되었다. ECMA-402 지원이 없는 구현은 그 매개변수 위치를 다른 목적으로 사용해서는 안 된다.

Note 1

이 메서드는 locale 에 민감한 toString 동작이 없는 객체를 위한 일반 toLocaleString 구현을 제공한다. Array, Number, Date, %TypedArray% 는 자체 locale 의존 toLocaleString 을 제공한다.

Note 2

ECMA-402 는 의도적으로 이 기본 구현의 대안을 제공하지 않는다.

20.1.3.6 Object.prototype.toString ( )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. this 값이 undefined 이면 "[object Undefined]" 를 반환한다.
  2. this 값이 null 이면 "[object Null]" 를 반환한다.
  3. O 를 ! ToObject(this value) 로 둔다.
  4. isArray 를 ? IsArray(O) 로 둔다.
  5. isArraytrue 이면 builtinTag = "Array".
  6. Else O[[ParameterMap]] 내부 슬롯을 가지면 builtinTag = "Arguments".
  7. Else O[[Call]] 내부 메서드를 가지면 builtinTag = "Function".
  8. Else O[[ErrorData]] 내부 슬롯을 가지면 builtinTag = "Error".
  9. Else O[[BooleanData]] 내부 슬롯을 가지면 builtinTag = "Boolean".
  10. Else O[[NumberData]] 내부 슬롯을 가지면 builtinTag = "Number".
  11. Else O[[StringData]] 내부 슬롯을 가지면 builtinTag = "String".
  12. Else O[[DateValue]] 내부 슬롯을 가지면 builtinTag = "Date".
  13. Else O[[RegExpMatcher]] 내부 슬롯을 가지면 builtinTag = "RegExp".
  14. Else builtinTag = "Object".
  15. tag 를 ? Get(O, %Symbol.toStringTag%) 로 둔다.
  16. tag 가 String 이 아니면 tag = builtinTag.
  17. "[object ", tag, "]" 의 문자열 연결을 반환한다.
Note

과거 이 메서드는 이전 판에서 다양한 내장 객체의 공칭 타입 태그로 사용된 [[Class]] 내부 슬롯의 String 값을 얻기 위해 사용되기도 했다. 위 정의는 그러한 특정 종류의 내장 객체를 테스트하기 위해 toString 을 사용하는 레거시 코드와의 호환성을 유지한다. 이는 다른 종류의 내장 혹은 프로그램 정의 객체에 대해 신뢰할 수 있는 타입 테스트 메커니즘을 제공하지 않는다. 또한 프로그램은 %Symbol.toStringTag% 를 이용하여 이러한 레거시 타입 테스트의 신뢰성을 깨뜨릴 수 있다.

20.1.3.7 Object.prototype.valueOf ( )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. ToObject(this value) 를 반환한다.
Normative Optional, Legacy

20.1.3.8 Object.prototype.__proto__

Object.prototype.__proto__ 는 특성 { [[Enumerable]]: false, [[Configurable]]: true } 를 가진 접근자 프로퍼티이다. [[Get]][[Set]] 특성은 다음과 같이 정의된다:

20.1.3.8.1 get Object.prototype.__proto__

[[Get]] 특성의 값은 인수를 요구하지 않는 내장 함수이다. 호출될 때 다음 단계를 수행한다:

  1. O 를 ? ToObject(this value) 로 둔다.
  2. O.[[GetPrototypeOf]]() 를 반환한다.

20.1.3.8.2 set Object.prototype.__proto__

[[Set]] 특성의 값은 인수 proto 를 받는 내장 함수이다. 호출될 때 다음 단계를 수행한다:

  1. Othis 값으로 둔다.
  2. RequireObjectCoercible(O) 를 수행한다.
  3. proto 가 Object 가 아니고 null 도 아니면 undefined 를 반환한다.
  4. O 가 Object 가 아니면 undefined 를 반환한다.
  5. status 를 ? O.[[SetPrototypeOf]](proto) 로 둔다.
  6. statusfalse 이면 TypeError 예외를 throw 한다.
  7. undefined 를 반환한다.
Normative Optional, Legacy

20.1.3.9 레거시 Object.prototype 접근자 메서드

20.1.3.9.1 Object.prototype.__defineGetter__ ( P, getter )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. O 를 ? ToObject(this value) 로 둔다.
  2. IsCallable(getter) 가 false 이면 TypeError 예외를 throw 한다.
  3. desc 를 PropertyDescriptor { [[Get]]: getter, [[Enumerable]]: true, [[Configurable]]: true } 로 둔다.
  4. key 를 ? ToPropertyKey(P) 로 둔다.
  5. DefinePropertyOrThrow(O, key, desc) 를 수행한다.
  6. undefined 를 반환한다.

20.1.3.9.2 Object.prototype.__defineSetter__ ( P, setter )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. O 를 ? ToObject(this value) 로 둔다.
  2. IsCallable(setter) 가 false 이면 TypeError 예외를 throw 한다.
  3. desc 를 PropertyDescriptor { [[Set]]: setter, [[Enumerable]]: true, [[Configurable]]: true } 로 둔다.
  4. key 를 ? ToPropertyKey(P) 로 둔다.
  5. DefinePropertyOrThrow(O, key, desc) 를 수행한다.
  6. undefined 를 반환한다.

20.1.3.9.3 Object.prototype.__lookupGetter__ ( P )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. O 를 ? ToObject(this value) 로 둔다.
  2. key 를 ? ToPropertyKey(P) 로 둔다.
  3. 반복,
    1. desc 를 ? O.[[GetOwnProperty]](key) 로 둔다.
    2. descundefined 가 아니면
      1. IsAccessorDescriptor(desc) 가 true 이면 desc.[[Get]] 를 반환한다.
      2. undefined 를 반환한다.
    3. O 를 ? O.[[GetPrototypeOf]]() 로 둔다.
    4. Onull 이면 undefined 를 반환한다.

20.1.3.9.4 Object.prototype.__lookupSetter__ ( P )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. O 를 ? ToObject(this value) 로 둔다.
  2. key 를 ? ToPropertyKey(P) 로 둔다.
  3. 반복,
    1. desc 를 ? O.[[GetOwnProperty]](key) 로 둔다.
    2. descundefined 가 아니면
      1. IsAccessorDescriptor(desc) 가 true 이면 desc.[[Set]] 를 반환한다.
      2. undefined 를 반환한다.
    3. O 를 ? O.[[GetPrototypeOf]]() 로 둔다.
    4. Onull 이면 undefined 를 반환한다.

20.1.4 Object 인스턴스의 프로퍼티

Object 인스턴스는 Object 프로토타입 객체로부터 상속된 것 외의 특별한 프로퍼티를 가지지 않는다.

20.2 Function 객체

20.2.1 Function 생성자

Function 생성자는 다음과 같다:

  • %Function% 이다.
  • 전역 객체 "Function" 프로퍼티의 초기 값이다.
  • 생성자가 아니라 함수로 호출될 때 새 함수 객체를 생성·초기화한다. 따라서 Function(…) 호출은 동일 인수를 가진 new Function(…) 표현식과 동등하다.
  • 클래스 정의의 extends 절 값으로 사용할 수 있다. 특정 Function 동작을 상속하려는 서브클래스 생성자는 내장 함수 동작에 필요한 내부 슬롯을 가진 서브클래스 인스턴스를 생성·초기화하기 위해 Function 생성자super 호출을 포함해야 한다. 함수 객체를 정의하는 모든 ECMAScript 구문 형태는 Function 인스턴스를 생성한다. built-in GeneratorFunction, AsyncFunction, AsyncGeneratorFunction 서브클래스를 제외하고 Function 서브클래스 인스턴스를 만들 문법적 수단은 없다.

20.2.1.1 Function ( ...parameterArgs, bodyArg )

마지막 인수(있다면)는 함수 본문(실행 코드)을 지정하며 그 앞의 인수들은 형식 매개변수를 지정한다.

이 함수는 호출될 때 다음 단계를 수행한다:

  1. C 를 활성 함수 객체로 둔다.
  2. bodyArg 가 존재하지 않으면 빈 문자열로 설정한다.
  3. CreateDynamicFunction(C, NewTarget, normal, parameterArgs, bodyArg) 를 반환한다.
Note

각 형식 매개변수마다 하나의 인수를 두는 것은 허용되지만 필수는 아니다. 예를 들어 다음 세 표현식은 모두 동일 결과를 생성한다:

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 ( constructor, newTarget, kind, parameterArgs, bodyArg )

The abstract operation CreateDynamicFunction takes arguments constructor (생성자), newTarget (생성자 또는 undefined), kind (normal, generator, async, 또는 async-generator), parameterArgs (ECMAScript 언어 값 리스트), and bodyArg (ECMAScript 언어 값) and returns ECMAScript 함수 객체를 담은 정상 completion 또는 throw completion. constructor 는 이 동작을 수행 중인 생성자 함수. newTarget 은 처음에 new 가 적용된 생성자. parameterArgsbodyArgconstructor 에 전달된 인수 값. It performs the following steps when called:

  1. newTargetundefined 이면 newTarget = constructor.
  2. kindnormal 이면
    1. prefix = "function".
    2. exprSym = FunctionExpression.
    3. bodySym = FunctionBody[~Yield, ~Await].
    4. parameterSym = FormalParameters[~Yield, ~Await].
    5. fallbackProto = "%Function.prototype%".
  3. Else if kind = generator 이면
    1. prefix = "function*".
    2. exprSym = GeneratorExpression.
    3. bodySym = GeneratorBody.
    4. parameterSym = FormalParameters[+Yield, ~Await].
    5. fallbackProto = "%GeneratorFunction.prototype%".
  4. Else if kind = async 이면
    1. prefix = "async function".
    2. exprSym = AsyncFunctionExpression.
    3. bodySym = AsyncFunctionBody.
    4. parameterSym = FormalParameters[~Yield, +Await].
    5. fallbackProto = "%AsyncFunction.prototype%".
  5. Else
    1. 단언: kind = async-generator.
    2. prefix = "async function*".
    3. exprSym = AsyncGeneratorExpression.
    4. bodySym = AsyncGeneratorBody.
    5. parameterSym = FormalParameters[+Yield, +Await].
    6. fallbackProto = "%AsyncGeneratorFunction.prototype%".
  6. argCount = parameterArgs 요소 수.
  7. parameterStrings 를 새 빈 리스트로 둔다.
  8. parameterArgs 의 각 요소 arg 에 대해
    1. ToString(arg) 를 parameterStrings 에 추가한다.
  9. bodyString = ? ToString(bodyArg).
  10. currentRealm = 현재 Realm Record.
  11. HostEnsureCanCompileStrings(currentRealm, parameterStrings, bodyString, false) 수행.
  12. P = 빈 문자열.
  13. argCount > 0 이면
    1. P = parameterStrings[0].
    2. k = 1.
    3. 반복 (k < argCount)
      1. nextArgString = parameterStrings[k].
      2. P = P + "," + nextArgString.
      3. k = k + 1.
  14. bodyParseString = 0x000A, bodyString, 0x000A 의 문자열 연결.
  15. sourceString = prefix, " anonymous(", P, 0x000A, ") {", bodyParseString, "}" 의 문자열 연결.
  16. sourceText = StringToCodePoints(sourceString).
  17. parameters = ParseText(P, parameterSym).
  18. parameters 가 오류 리스트이면 SyntaxError throw.
  19. body = ParseText(bodyParseString, bodySym).
  20. body 가 오류 리스트이면 SyntaxError throw.
  21. NOTE: 매개변수와 본문을 개별적으로 파싱하여 각각 단독으로 유효함을 보장.
  22. NOTE: 이 단계에 도달했다면 sourceTextexprSym 문법을 가져야 한다.
  23. expr = ParseText(sourceText, exprSym).
  24. expr 이 오류 리스트이면 SyntaxError throw.
  25. proto = ? GetPrototypeFromConstructor(newTarget, fallbackProto).
  26. env = currentRealm.[[GlobalEnv]].
  27. privateEnv = null.
  28. F = OrdinaryFunctionCreate(proto, sourceText, parameters, body, non-lexical-this, env, privateEnv).
  29. SetFunctionName(F, "anonymous").
  30. kind = generator 이면
    1. prototype = OrdinaryObjectCreate(%GeneratorPrototype%).
    2. DefinePropertyOrThrow(F, "prototype", PropertyDescriptor { [[Value]]: prototype, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false }).
  31. Else if kind = async-generator 이면
    1. prototype = OrdinaryObjectCreate(%AsyncGeneratorPrototype%).
    2. DefinePropertyOrThrow(F, "prototype", PropertyDescriptor { [[Value]]: prototype, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false }).
  32. Else if kind = normal 이면
    1. MakeConstructor(F) 수행.
  33. NOTE: kindasync 인 함수는 constructable 하지 않다.
  34. F 를 반환한다.
Note

CreateDynamicFunction 은 kindasync 가 아닌 함수에 대해 생성자를 위해 사용할 가능성을 제공하기 위해 "prototype" 프로퍼티를 정의한다.

20.2.2 Function 생성자의 프로퍼티

Function 생성자는:

  • 자체가 내장 함수 객체이다.
  • 값이 %Function.prototype%[[Prototype]] 내부 슬롯을 가진다.
  • 값이 1𝔽"length" 프로퍼티를 가진다.
  • 다음 프로퍼티들을 가진다:

20.2.2.1 Function.prototype

Function.prototype 의 값은 Function 프로토타입 객체이다.

이 프로퍼티는 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false } 특성을 가진다.

20.2.3 Function 프로토타입 객체의 프로퍼티

Function 프로토타입 객체는:

  • %Function.prototype% 이다.
  • 자체가 내장 함수 객체이다.
  • 임의의 인수를 받아 호출되면 undefined 를 반환한다.
  • [[Construct]] 내부 메서드를 가지지 않아 new 와 함께 생성자로 사용할 수 없다.
  • 값이 %Object.prototype%[[Prototype]] 내부 슬롯을 가진다.
  • "prototype" 프로퍼티를 가지지 않는다.
  • 값이 +0𝔽"length" 프로퍼티를 가진다.
  • 값이 빈 문자열인 "name" 프로퍼티를 가진다.
Note

Function 프로토타입 객체를 함수 객체로 지정한 것은 ECMAScript 2015 이전 코드와의 호환성을 보장하기 위함이다.

20.2.3.1 Function.prototype.apply ( thisArg, argArray )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. functhis 값으로 둔다.
  2. IsCallable(func) 이 false 이면 TypeError 예외 throw.
  3. argArrayundefined 또는 null 이면
    1. PrepareForTailCall() 수행.
    2. Call(func, thisArg) 반환.
  4. argList 를 ? CreateListFromArrayLike(argArray) 로 둔다.
  5. PrepareForTailCall() 수행.
  6. Call(func, thisArg, argList) 반환.
Note 1

thisArg 값은 수정 없이 this 값으로 전달된다. 이는 3판과의 차이로, 그때는 undefined 또는 null thisArg전역 객체로 대체되고 다른 값에는 ToObject 가 적용되었다. 비엄격 함수는 진입 시 여전히 이러한 변환을 수행한다.

Note 2

func 이 화살표 함수나 bound 함수 특수 객체라면 step 6[[Call]] 에서 thisArg 는 무시된다.

20.2.3.2 Function.prototype.bind ( thisArg, ...args )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. Targetthis 값으로 둔다.
  2. IsCallable(Target) 이 false 이면 TypeError 예외 throw.
  3. F 를 ? BoundFunctionCreate(Target, thisArg, args) 로 둔다.
  4. L = 0.
  5. targetHasLength = ? HasOwnProperty(Target, "length").
  6. targetHasLength true 이면
    1. targetLen = ? Get(Target, "length").
    2. targetLen 이 Number 이면
      1. targetLen = +∞𝔽 이면 L = +∞.
      2. Else if targetLen = -∞𝔽 이면 L = 0.
      3. Else
        1. targetLenAsInt = ! ToIntegerOrInfinity(targetLen).
        2. 단언: targetLenAsInt 는 finite.
        3. argCount = args 요소 수.
        4. L = max(targetLenAsInt - argCount, 0).
  7. SetFunctionLength(F, L) 수행.
  8. targetName = ? Get(Target, "name").
  9. targetName 이 String 이 아니면 빈 문자열로 설정.
  10. SetFunctionName(F, targetName, "bound") 수행.
  11. F 반환.
Note 1

Function.prototype.bind 로 생성된 함수 객체는 특수(exotic) 객체이며 "prototype" 프로퍼티를 가지지 않는다.

Note 2

Target 이 화살표 함수나 bound 함수 특수 객체이면 이 메서드에 전달된 thisArg 는 이후 F 호출에서 사용되지 않는다.

20.2.3.3 Function.prototype.call ( thisArg, ...args )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. functhis 값으로 둔다.
  2. IsCallable(func) false 이면 TypeError 예외 throw.
  3. PrepareForTailCall() 수행.
  4. Call(func, thisArg, args) 반환.
Note 1

thisArg 는 수정 없이 전달된다(3판과의 차이). 비엄격 함수는 진입 시 변환 수행.

Note 2

func 이 화살표 또는 bound 함수 특수 객체이면 step 4[[Call]] 에서 thisArg 는 무시된다.

20.2.3.4 Function.prototype.constructor

Function.prototype.constructor 의 초기 값은 %Function%.

20.2.3.5 Function.prototype.toString ( )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. functhis 값으로 둔다.
  2. func 이 Object 이고 [[SourceText]] 내부 슬롯을 가지며 func.[[SourceText]] 가 유니코드 코드 포인트 시퀀스이고 HostHasSourceTextAvailable(func) 이 true 이면
    1. CodePointsToString(func.[[SourceText]]) 반환.
  3. func내장 함수 객체 이면 구현 정의 String 소스 표현을 반환한다. 표현은 NativeFunction 문법을 가져야 한다. 또한 func[[InitialName]] 내부 슬롯을 가지고 그것이 String 이면 반환된 String 중 NativeFunctionAccessoropt PropertyName 에 매치될 부분은 그 값이어야 한다.
  4. func 이 Object 이고 IsCallable(func) true 이면 구현 정의 String 소스 표현을 반환하며 문법은 NativeFunction.
  5. TypeError 예외 throw.
NativeFunction : function NativeFunctionAccessoropt PropertyName[~Yield, ~Await]opt ( FormalParameters[~Yield, ~Await] ) { [ native code ] } NativeFunctionAccessor : get set

20.2.3.6 Function.prototype [ %Symbol.hasInstance% ] ( V )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. Fthis 값으로 둔다.
  2. OrdinaryHasInstance(F, V) 를 반환한다.

이 프로퍼티는 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false } 특성을 가진다.

Note

이것은 대부분의 함수가 상속하는 기본 %Symbol.hasInstance% 구현이다. %Symbol.hasInstance%instanceof 연산자가 값이 특정 생성자의 인스턴스인지 판정하기 위해 호출한다. 다음 표현식은

v instanceof F

다음과 같이 평가된다

F[%Symbol.hasInstance%](v)

생성자 함수는 함수에 다른 %Symbol.hasInstance% 메서드를 노출하여 어떤 객체를 자신의 인스턴스로 인식할지 제어할 수 있다.

이 프로퍼티는 bound 함수의 대상 함수를 전역적으로 노출할 수 있는 변조를 막기 위해 writable / configurable 이 아니다.

이 메서드의 "name" 프로퍼티 값은 "[Symbol.hasInstance]" 이다.

20.2.4 Function 인스턴스

모든 Function 인스턴스는 ECMAScript 함수 객체이며 Table 28 에 나열된 내부 슬롯을 가진다. Function.prototype.bind (20.2.3.2) 로 생성된 함수 객체Table 29 에 있는 내부 슬롯을 가진다.

Function 인스턴스는 다음 프로퍼티를 가진다:

20.2.4.1 length

"length" 프로퍼티 값은 함수가 일반적으로 기대하는 인수 수를 나타내는 정수 Number 이다. 언어는 다른 수의 인수로 호출하는 것을 허용한다. 지정된 "length" 와 다른 인수 수로 호출될 때의 동작은 함수에 따라 다르다. 이 프로퍼티는 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true } 특성을 가진다.

20.2.4.2 name

"name" 프로퍼티 값은 함수를 서술하는 String 이다. 이름은 의미론적 중요성을 갖지 않고 보통 ECMAScript 소스에서 정의 지점에서 그 함수를 참조하는 변수 또는 프로퍼티 이름이다. 이 프로퍼티는 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true } 특성을 가진다.

명세에 의해 문맥적 이름이 연관되지 않은 익명 함수 객체는 빈 문자열을 "name" 값으로 사용한다.

20.2.4.3 prototype

생성자로 사용할 수 있는 Function 인스턴스는 "prototype" 프로퍼티를 가진다. 그러한 Function 인스턴스가 생성될 때마다 또 다른 ordinary 객체가 생성되어 함수의 "prototype" 프로퍼티 초기 값이 된다. 달리 명시되지 않는 한 생성자로 그 함수가 호출될 때 생성되는 객체의 [[Prototype]] 내부 슬롯을 초기화하는 데 이 값이 사용된다.

이 프로퍼티는 { [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false } 특성을 가진다.

Note

Function.prototype.bind 로 생성되거나 MethodDefinition (GeneratorMethod 또는 AsyncGeneratorMethod 아님) 평가 또는 ArrowFunction 으로 생성된 함수 객체"prototype" 프로퍼티를 가지지 않는다.

20.2.5 HostHasSourceTextAvailable ( func )

The host-defined abstract operation HostHasSourceTextAvailable takes argument func (함수 객체) and returns Boolean. 호스트 환경func 의 소스 텍스트 제공을 차단할 수 있도록 한다.

HostHasSourceTextAvailable 구현은 다음 요구사항을 따른다:

  • 매개변수에 대해 결정적이어야 한다. 특정 func 로 호출될 때마다 동일 결과를 반환해야 한다.

기본 구현은 true 를 반환한다.

20.3 Boolean 객체

20.3.1 Boolean 생성자

Boolean 생성자는 다음과 같다:

  • %Boolean% 이다.
  • 전역 객체 "Boolean" 프로퍼티의 초기 값이다.
  • 생성자로 호출될 때 새로운 Boolean 객체를 생성·초기화한다.
  • 생성자가 아니라 함수로 호출되면 타입 변환을 수행한다.
  • 클래스 정의의 extends 절 값으로 사용할 수 있다. 지정된 Boolean 동작을 상속하려는 서브클래스 생성자[[BooleanData]] 내부 슬롯을 가진 서브클래스 인스턴스를 생성·초기화하기 위해 Boolean 생성자super 호출을 포함해야 한다.

20.3.1.1 Boolean ( value )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. bToBoolean(value) 로 둔다.
  2. NewTarget 이 undefined 이면 b 를 반환한다.
  3. O 를 ? OrdinaryCreateFromConstructor(NewTarget, "%Boolean.prototype%", « [[BooleanData]] ») 로 둔다.
  4. O.[[BooleanData]] = b 로 설정한다.
  5. O 를 반환한다.

20.3.2 Boolean 생성자의 프로퍼티

Boolean 생성자는:

  • 값이 %Function.prototype%[[Prototype]] 내부 슬롯을 가진다.
  • 다음 프로퍼티들을 가진다:

20.3.2.1 Boolean.prototype

Boolean.prototype 의 초기 값은 Boolean 프로토타입 객체이다.

이 프로퍼티는 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false } 특성을 가진다.

20.3.3 Boolean 프로토타입 객체의 프로퍼티

Boolean 프로토타입 객체는:

  • %Boolean.prototype% 이다.
  • ordinary 객체이다.
  • 자체가 Boolean 객체이며 값이 false[[BooleanData]] 내부 슬롯을 가진다.
  • 값이 %Object.prototype%[[Prototype]] 내부 슬롯을 가진다.

20.3.3.1 Boolean.prototype.constructor

Boolean.prototype.constructor 의 초기 값은 %Boolean%.

20.3.3.2 Boolean.prototype.toString ( )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. b 를 ? ThisBooleanValue(this value) 로 둔다.
  2. btrue 이면 "true" 반환; 아니면 "false" 반환.

20.3.3.3 Boolean.prototype.valueOf ( )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. ThisBooleanValue(this value) 를 반환한다.

20.3.3.3.1 ThisBooleanValue ( value )

The abstract operation ThisBooleanValue takes argument value (ECMAScript 언어 값) and returns Boolean 을 담은 정상 completion 또는 throw completion. It performs the following steps when called:

  1. value 가 Boolean 이면 value 반환.
  2. value 가 Object 이고 [[BooleanData]] 내부 슬롯을 가지면
    1. bvalue.[[BooleanData]] 로 둔다.
    2. 단언: b 는 Boolean.
    3. b 반환.
  3. TypeError 예외 throw.

20.3.4 Boolean 인스턴스의 프로퍼티

Boolean 인스턴스는 Boolean 프로토타입 객체로부터 프로퍼티를 상속하는 ordinary 객체이다. Boolean 인스턴스는 [[BooleanData]] 내부 슬롯을 가진다. [[BooleanData]] 내부 슬롯은 이 Boolean 객체가 나타내는 Boolean 값이다.

20.4 Symbol 객체

20.4.1 Symbol 생성자

Symbol 생성자는 다음과 같다:

  • %Symbol% 이다.
  • 전역 객체 "Symbol" 프로퍼티의 초기 값이다.
  • 함수로 호출되면 새로운 Symbol 값을 반환한다.
  • new 연산자와 함께 사용하도록 의도되지 않았다.
  • 서브클래싱을 의도하지 않는다.
  • 클래스 정의의 extends 절 값으로 사용할 수 있으나 그에 대한 super 호출은 예외를 유발한다.

20.4.1.1 Symbol ( [ description ] )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. NewTarget 가 undefined 가 아니면 TypeError 예외를 throw 한다.
  2. descriptionundefined 이면 descStringundefined 로 둔다.
  3. 그렇지 않으면 descString 을 ? ToString(description) 로 둔다.
  4. [[Description]]descString 인 새 Symbol 을 반환한다.

20.4.2 Symbol 생성자의 프로퍼티

Symbol 생성자는:

  • 값이 %Function.prototype%[[Prototype]] 내부 슬롯을 가진다.
  • 다음 프로퍼티들을 가진다:

20.4.2.1 Symbol.asyncIterator

Symbol.asyncIterator 의 초기 값은 well-known symbol %Symbol.asyncIterator% (Table 1) 이다.

이 프로퍼티는 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false } 특성을 가진다.

20.4.2.2 Symbol.for ( key )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. Let stringKey be ? ToString(key).
  2. For each element e of the GlobalSymbolRegistry List, do
    1. If e.[[Key]] is stringKey, return e.[[Symbol]].
  3. Assert: The GlobalSymbolRegistry List does not currently contain an entry for stringKey.
  4. Let newSymbol be a new Symbol whose [[Description]] is stringKey.
  5. Append the GlobalSymbolRegistry Record { [[Key]]: stringKey, [[Symbol]]: newSymbol } to the GlobalSymbolRegistry List.
  6. Return newSymbol.

GlobalSymbolRegistry List 는 전역적으로 이용 가능한 append-only 리스트이다. 모든 realm 이 공유한다. 어떤 ECMAScript 코드도 평가되기 전에 새 빈 리스트로 초기화된다. 요소는 Table 61 에 정의된 구조의 Record 이다.

Table 61: GlobalSymbolRegistry Record 필드
Field Name Value Usage
[[Key]] a String 전역적으로 Symbol 을 식별하는 문자열 키.
[[Symbol]] a Symbol 어떤 realm 에서든 조회 가능한 symbol.

20.4.2.3 Symbol.hasInstance

Symbol.hasInstance 의 초기 값은 well-known symbol %Symbol.hasInstance% (Table 1) 이다.

이 프로퍼티는 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false } 특성을 가진다.

20.4.2.4 Symbol.isConcatSpreadable

Symbol.isConcatSpreadable 의 초기 값은 well-known symbol %Symbol.isConcatSpreadable% (Table 1) 이다.

이 프로퍼티는 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false } 특성을 가진다.

20.4.2.5 Symbol.iterator

Symbol.iterator 의 초기 값은 well-known symbol %Symbol.iterator% (Table 1) 이다.

이 프로퍼티는 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false } 특성을 가진다.

20.4.2.6 Symbol.keyFor ( sym )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. sym 이 Symbol 이 아니면 TypeError 예외 throw.
  2. KeyForSymbol(sym) 을 반환한다.

20.4.2.7 Symbol.match

Symbol.match 의 초기 값은 well-known symbol %Symbol.match% (Table 1) 이다.

이 프로퍼티는 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false } 특성을 가진다.

20.4.2.8 Symbol.matchAll

Symbol.matchAll 의 초기 값은 well-known symbol %Symbol.matchAll% (Table 1) 이다.

이 프로퍼티는 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false } 특성을 가진다.

20.4.2.9 Symbol.prototype

Symbol.prototype 의 초기 값은 Symbol 프로토타입 객체이다.

이 프로퍼티는 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false } 특성을 가진다.

20.4.2.10 Symbol.replace

Symbol.replace 의 초기 값은 well-known symbol %Symbol.replace% (Table 1) 이다.

이 프로퍼티는 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false } 특성을 가진다.

20.4.2.11 Symbol.search

Symbol.search 의 초기 값은 well-known symbol %Symbol.search% (Table 1) 이다.

이 프로퍼티는 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false } 특성을 가진다.

20.4.2.12 Symbol.species

Symbol.species 의 초기 값은 well-known symbol %Symbol.species% (Table 1) 이다.

이 프로퍼티는 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false } 특성을 가진다.

20.4.2.13 Symbol.split

Symbol.split 의 초기 값은 well-known symbol %Symbol.split% (Table 1) 이다.

이 프로퍼티는 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false } 특성을 가진다.

20.4.2.14 Symbol.toPrimitive

Symbol.toPrimitive 의 초기 값은 well-known symbol %Symbol.toPrimitive% (Table 1) 이다.

이 프로퍼티는 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false } 특성을 가진다.

20.4.2.15 Symbol.toStringTag

Symbol.toStringTag 의 초기 값은 well-known symbol %Symbol.toStringTag% (Table 1) 이다.

이 프로퍼티는 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false } 특성을 가진다.

20.4.2.16 Symbol.unscopables

Symbol.unscopables 의 초기 값은 well-known symbol %Symbol.unscopables% (Table 1) 이다.

이 프로퍼티는 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false } 특성을 가진다.

20.4.3 Symbol 프로토타입 객체의 프로퍼티

Symbol 프로토타입 객체는:

  • %Symbol.prototype% 이다.
  • ordinary 객체이다.
  • Symbol 인스턴스가 아니며 [[SymbolData]] 내부 슬롯을 갖지 않는다.
  • 값이 %Object.prototype%[[Prototype]] 내부 슬롯을 가진다.

20.4.3.1 Symbol.prototype.constructor

Symbol.prototype.constructor 의 초기 값은 %Symbol%.

20.4.3.2 get Symbol.prototype.description

Symbol.prototype.description 은 set 접근자 함수가 undefined접근자 프로퍼티이다. 그 get 접근자 함수는 호출 시 다음 단계를 수행한다:

  1. sthis 값으로 둔다.
  2. sym 을 ? ThisSymbolValue(s) 로 둔다.
  3. sym.[[Description]] 를 반환한다.

20.4.3.3 Symbol.prototype.toString ( )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. sym 을 ? ThisSymbolValue(this value) 로 둔다.
  2. SymbolDescriptiveString(sym) 을 반환한다.

20.4.3.3.1 SymbolDescriptiveString ( sym )

The abstract operation SymbolDescriptiveString takes argument sym (Symbol) and returns String. It performs the following steps when called:

  1. desc = sym.[[Description]].
  2. descundefined 이면 빈 문자열로 설정.
  3. 단언: desc 는 String.
  4. "Symbol(", desc, ")" 의 문자열 연결을 반환.

20.4.3.4 Symbol.prototype.valueOf ( )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. ThisSymbolValue(this value) 를 반환한다.

20.4.3.4.1 ThisSymbolValue ( value )

The abstract operation ThisSymbolValue takes argument value (ECMAScript 언어 값) and returns Symbol 을 담은 정상 completion 또는 throw completion. It performs the following steps when called:

  1. value 가 Symbol 이면 value 반환.
  2. value 가 Object 이고 [[SymbolData]] 내부 슬롯을 가지면
    1. svalue.[[SymbolData]] 로 둔다.
    2. 단언: s 는 Symbol.
    3. s 반환.
  3. TypeError 예외 throw.

20.4.3.5 Symbol.prototype [ %Symbol.toPrimitive% ] ( hint )

이 메서드는 ECMAScript 언어 연산자가 Symbol 객체를 원시 값으로 변환할 때 호출된다.

호출될 때 다음 단계를 수행한다:

  1. ThisSymbolValue(this value) 를 반환한다.
Note

인수는 무시된다.

이 프로퍼티는 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true } 특성을 가진다.

이 메서드의 "name" 프로퍼티 값은 "[Symbol.toPrimitive]" 이다.

20.4.3.6 Symbol.prototype [ %Symbol.toStringTag% ]

%Symbol.toStringTag% 프로퍼티의 초기 값은 "Symbol" String 값이다.

이 프로퍼티는 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true } 특성을 가진다.

20.4.4 Symbol 인스턴스의 프로퍼티

Symbol 인스턴스는 Symbol 프로토타입 객체로부터 프로퍼티를 상속하는 ordinary 객체이다. Symbol 인스턴스는 [[SymbolData]] 내부 슬롯을 가진다. [[SymbolData]] 내부 슬롯은 이 Symbol 객체가 나타내는 Symbol 값이다.

20.4.5 Symbol 을 위한 추상 연산

20.4.5.1 KeyForSymbol ( sym )

The abstract operation KeyForSymbol takes argument sym (Symbol) and returns String 또는 undefined. symGlobalSymbolRegistry List 에 있으면 sym 을 등록하는 데 사용된 String 이 반환된다. It performs the following steps when called:

  1. GlobalSymbolRegistry List 의 각 요소 e 에 대해
    1. SameValue(e.[[Symbol]], sym) 가 true 이면 e.[[Key]] 반환.
  2. 단언: GlobalSymbolRegistry List 에 현재 sym 항목 없음.
  3. undefined 반환.

20.5 Error 객체

Error 객체 인스턴스는 런타임 오류 발생 시 예외로 throw 된다. Error 객체는 사용자 정의 예외 클래스의 기반 객체로도 사용될 수 있다.

ECMAScript 구현이 런타임 오류를 감지하면 20.5.5 에 정의된 NativeError 객체 중 하나의 새 인스턴스나 20.5.7 에 정의된 AggregateError 객체의 새 인스턴스를 throw 한다.

20.5.1 Error 생성자

Error 생성자는 다음과 같다:

  • %Error% 이다.
  • 전역 객체 "Error" 프로퍼티의 초기 값이다.
  • 생성자가 아니라 함수로 호출될 때 새 Error 객체를 생성·초기화한다. 따라서 Error(…) 호출은 동일 인수를 가진 new Error(…) 와 동등하다.
  • 클래스 정의의 extends 절 값으로 사용할 수 있다. 지정된 Error 동작을 상속하려는 서브클래스 생성자[[ErrorData]] 내부 슬롯을 가진 서브클래스 인스턴스를 만들기 위해 Error 생성자super 호출을 포함해야 한다.

20.5.1.1 Error ( message [ , options ] )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. NewTarget 이 undefined 이면 newTarget = 활성 함수 객체; 아니면 newTarget = NewTarget.
  2. O 를 ? OrdinaryCreateFromConstructor(newTarget, "%Error.prototype%", « [[ErrorData]] ») 로 둔다.
  3. messageundefined 가 아니면
    1. msg = ? ToString(message).
    2. CreateNonEnumerableDataPropertyOrThrow(O, "message", msg) 수행.
  4. InstallErrorCause(O, options) 수행.
  5. O 반환.

20.5.2 Error 생성자의 프로퍼티

Error 생성자는:

  • 값이 %Function.prototype%[[Prototype]] 내부 슬롯을 가진다.
  • 다음 프로퍼티들을 가진다:

20.5.2.1 Error.isError ( arg )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. arg 가 Object 가 아니면 false 반환.
  2. arg[[ErrorData]] 내부 슬롯을 가지지 않으면 false 반환.
  3. true 반환.

20.5.2.2 Error.prototype

Error.prototype 의 초기 값은 Error 프로토타입 객체이다.

이 프로퍼티는 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false } 특성을 가진다.

20.5.3 Error 프로토타입 객체의 프로퍼티

Error 프로토타입 객체는:

  • %Error.prototype% 이다.
  • ordinary 객체이다.
  • Error 인스턴스가 아니며 [[ErrorData]] 내부 슬롯을 갖지 않는다.
  • 값이 %Object.prototype%[[Prototype]] 내부 슬롯을 가진다.

20.5.3.1 Error.prototype.constructor

Error.prototype.constructor 의 초기 값은 %Error%.

20.5.3.2 Error.prototype.message

Error.prototype.message 의 초기 값은 빈 문자열이다.

20.5.3.3 Error.prototype.name

Error.prototype.name 의 초기 값은 "Error".

20.5.3.4 Error.prototype.toString ( )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. Othis 값으로 둔다.
  2. O 가 Object 가 아니면 TypeError 예외 throw.
  3. name = ? Get(O, "name").
  4. nameundefined 이면 name = "Error"; 아니면 name = ? ToString(name).
  5. msg = ? Get(O, "message").
  6. msgundefined 이면 msg = 빈 문자열; 아니면 msg = ? ToString(msg).
  7. name 이 빈 문자열이면 msg 반환.
  8. msg 가 빈 문자열이면 name 반환.
  9. name, 0x003A, 0x0020, msg 의 문자열 연결을 반환.

20.5.4 Error 인스턴스의 프로퍼티

Error 인스턴스는 Error 프로토타입 객체로부터 프로퍼티를 상속하는 ordinary 객체이며 값이 undefined[[ErrorData]] 내부 슬롯을 가진다. [[ErrorData]] 의 유일한 지정 용도는 Object.prototype.toStringError.isError 에서 Error, AggregateError, NativeError 인스턴스를 식별하는 것이다.

20.5.5 이 표준에서 사용되는 Native Error 타입

런타임 오류가 감지되면 아래 NativeError 객체 중 하나 또는 AggregateError 객체의 새 인스턴스가 throw 된다. 모든 NativeError 객체는 20.5.6 에 설명된 동일 구조를 공유한다.

20.5.5.1 EvalError

EvalError 생성자%EvalError% 이다.

이 예외는 현재 이 명세 내부에서는 사용되지 않는다. 이전 판과의 호환성을 위해 남아 있다.

20.5.5.2 RangeError

RangeError 생성자%RangeError% 이다.

허용 가능한 값의 집합 또는 범위에 속하지 않는 값을 나타낸다.

20.5.5.3 ReferenceError

ReferenceError 생성자%ReferenceError% 이다.

잘못된 참조가 감지되었음을 나타낸다.

20.5.5.4 SyntaxError

SyntaxError 생성자%SyntaxError% 이다.

파싱 오류가 발생했음을 나타낸다.

20.5.5.5 TypeError

TypeError 생성자%TypeError% 이다.

다른 NativeError 객체 어느 것도 실패 원인을 적절히 나타내지 못할 때 실패한 연산을 나타내는 데 사용된다.

20.5.5.6 URIError

URIError 생성자%URIError% 이다.

글로벌 URI 처리 함수 중 하나가 그 정의와 호환되지 않는 방식으로 사용되었음을 나타낸다.

20.5.6 NativeError 객체 구조

이 객체 각각은 아래에 설명된 구조를 가지며, 생성자 이름과 프로토타입 객체의 "name" 프로퍼티만 다르다.

각 error 객체에 대해 정의 내 NativeError 참조는 20.5.5 의 해당 error 객체 이름으로 대체되어야 한다.

20.5.6.1 NativeError 생성자

NativeError 생성자는:

  • 생성자가 아니라 함수로 호출될 때 새 NativeError 객체를 생성·초기화한다. 함수 호출 NativeError(…) 는 동일 인수를 가진 new NativeError(…) 와 동등하다.
  • 클래스 정의의 extends 절 값으로 사용할 수 있다. 지정된 NativeError 동작을 상속하려는 서브클래스 생성자[[ErrorData]] 내부 슬롯을 가진 서브클래스 인스턴스를 생성·초기화하기 위해 NativeError 생성자super 호출을 포함해야 한다.

20.5.6.1.1 NativeError ( message [ , options ] )

NativeError 함수는 호출될 때 다음 단계를 수행한다:

  1. NewTarget 이 undefined 이면 newTarget = 활성 함수 객체; 아니면 newTarget = NewTarget.
  2. O 를 ? OrdinaryCreateFromConstructor(newTarget, "%NativeError.prototype%", « [[ErrorData]] ») 로 둔다.
  3. messageundefined 가 아니면
    1. msg = ? ToString(message).
    2. CreateNonEnumerableDataPropertyOrThrow(O, "message", msg) 수행.
  4. InstallErrorCause(O, options) 수행.
  5. O 반환.

step 2 에 전달되는 문자열의 실제 값은 정의 중인 NativeError 생성자에 따라 "%EvalError.prototype%", "%RangeError.prototype%", "%ReferenceError.prototype%", "%SyntaxError.prototype%", "%TypeError.prototype%", "%URIError.prototype%" 중 하나이다.

20.5.6.2 NativeError 생성자의 프로퍼티

NativeError 생성자는:

  • 값이 %Error%[[Prototype]] 내부 슬롯을 가진다.
  • 값이 String "NativeError""name" 프로퍼티를 가진다.
  • 다음 프로퍼티들을 가진다:

20.5.6.2.1 NativeError.prototype

NativeError.prototype 의 초기 값은 NativeError 프로토타입 객체 (20.5.6.3). 각 NativeError 생성자는 서로 다른 프로토타입 객체를 가진다.

이 프로퍼티는 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false } 특성을 가진다.

20.5.6.3 NativeError 프로토타입 객체의 프로퍼티

NativeError 프로토타입 객체는:

  • ordinary 객체이다.
  • Error 인스턴스가 아니며 [[ErrorData]] 내부 슬롯을 갖지 않는다.
  • 값이 %Error.prototype%[[Prototype]] 내부 슬롯을 가진다.

20.5.6.3.1 NativeError.prototype.constructor

특정 NativeError 생성자에 대한 프로토타입의 "constructor" 프로퍼티 초기 값은 그 생성자 자체이다.

20.5.6.3.2 NativeError.prototype.message

특정 NativeError 생성자 프로토타입의 "message" 프로퍼티 초기 값은 빈 문자열이다.

20.5.6.3.3 NativeError.prototype.name

특정 NativeError 생성자 프로토타입의 "name" 프로퍼티 초기 값은 ( NativeError 대신 사용되는 ) 생성자의 이름으로 이루어진 String 값이다.

20.5.6.4 NativeError 인스턴스의 프로퍼티

NativeError 인스턴스는 해당 NativeError 프로토타입 객체로부터 프로퍼티를 상속하는 ordinary 객체이며 값이 undefined[[ErrorData]] 내부 슬롯을 가진다. [[ErrorData]] 의 유일한 지정 용도는 Object.prototype.toString (20.1.3.6) 과 Error.isError (20.5.2.1) 에서 Error, AggregateError 또는 NativeError 인스턴스를 식별하는 것이다.

20.5.7 AggregateError 객체

20.5.7.1 AggregateError 생성자

AggregateError 생성자는 다음과 같다:

  • %AggregateError% 이다.
  • 전역 객체 "AggregateError" 프로퍼티의 초기 값이다.
  • 생성자가 아니라 함수로 호출될 때 새 AggregateError 객체를 생성·초기화한다. 따라서 AggregateError(…) 호출은 동일 인수를 가진 new AggregateError(…) 와 동등하다.
  • 클래스 정의의 extends 절 값으로 사용할 수 있다. 지정된 AggregateError 동작을 상속하려는 서브클래스 생성자[[ErrorData]] 내부 슬롯을 가진 서브클래스 인스턴스를 생성·초기화하기 위해 AggregateError 생성자super 호출을 포함해야 한다.

20.5.7.1.1 AggregateError ( errors, message [ , options ] )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. NewTarget 이 undefined 이면 newTarget = 활성 함수 객체; 아니면 newTarget = NewTarget.
  2. O 를 ? OrdinaryCreateFromConstructor(newTarget, "%AggregateError.prototype%", « [[ErrorData]] ») 로 둔다.
  3. messageundefined 가 아니면
    1. msg = ? ToString(message).
    2. CreateNonEnumerableDataPropertyOrThrow(O, "message", msg) 수행.
  4. InstallErrorCause(O, options) 수행.
  5. errorsList 를 ? IteratorToList(? GetIterator(errors, sync)) 로 둔다.
  6. DefinePropertyOrThrow(O, "errors", PropertyDescriptor { [[Configurable]]: true, [[Enumerable]]: false, [[Writable]]: true, [[Value]]: CreateArrayFromList(errorsList) }) 수행.
  7. O 반환.

20.5.7.2 AggregateError 생성자의 프로퍼티

AggregateError 생성자는:

  • 값이 %Error%[[Prototype]] 내부 슬롯을 가진다.
  • 다음 프로퍼티들을 가진다:

20.5.7.2.1 AggregateError.prototype

AggregateError.prototype 의 초기 값은 %AggregateError.prototype% 이다.

이 프로퍼티는 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false } 특성을 가진다.

20.5.7.3 AggregateError 프로토타입 객체의 프로퍼티

AggregateError 프로토타입 객체는:

  • %AggregateError.prototype% 이다.
  • ordinary 객체이다.
  • Error 인스턴스나 AggregateError 인스턴스가 아니며 [[ErrorData]] 내부 슬롯을 갖지 않는다.
  • 값이 %Error.prototype%[[Prototype]] 내부 슬롯을 가진다.

20.5.7.3.1 AggregateError.prototype.constructor

AggregateError.prototype.constructor 의 초기 값은 %AggregateError%.

20.5.7.3.2 AggregateError.prototype.message

AggregateError.prototype.message 의 초기 값은 빈 문자열이다.

20.5.7.3.3 AggregateError.prototype.name

AggregateError.prototype.name 의 초기 값은 "AggregateError".

20.5.7.4 AggregateError 인스턴스의 프로퍼티

AggregateError 인스턴스는 해당 AggregateError 프로토타입 객체로부터 프로퍼티를 상속하는 ordinary 객체이며 값이 undefined[[ErrorData]] 내부 슬롯을 가진다. [[ErrorData]] 의 유일한 지정 용도는 Object.prototype.toString (20.1.3.6) 과 Error.isError (20.5.2.1) 에서 Error, AggregateError, NativeError 인스턴스를 식별하는 것이다.

20.5.8 Error 객체를 위한 추상 연산

20.5.8.1 InstallErrorCause ( O, options )

The abstract operation InstallErrorCause takes arguments O (Object) and options (ECMAScript 언어 값) and returns unused 를 담은 정상 completion 또는 throw completion. options"cause" 프로퍼티가 존재할 때 O"cause" 프로퍼티를 생성하는 데 사용된다. It performs the following steps when called:

  1. options 가 Object 이고 ? HasProperty(options, "cause") 가 true 이면
    1. cause 를 ? Get(options, "cause") 로 둔다.
    2. CreateNonEnumerableDataPropertyOrThrow(O, "cause", cause) 수행.
  2. unused 를 반환한다.

21 숫자와 날짜 (Numbers and Dates)

21.1 Number 객체 (Number Objects)

21.1.1 Number 생성자 (The Number Constructor)

Number 생성자는 다음과 같다:

  • %Number% 이다.
  • 전역 객체 "Number" 프로퍼티의 초기 값이다.
  • 생성자로 호출될 때 새로운 Number 객체를 생성하고 초기화한다.
  • 생성자가 아니라 함수로 호출될 때 타입 변환을 수행한다.
  • 클래스 정의의 extends 절 값으로 사용할 수 있다. 지정된 Number 동작을 상속하려는 서브클래스 생성자[[NumberData]] 내부 슬롯을 가진 서브클래스 인스턴스를 생성·초기화하기 위해 Number 생성자에 대한 super 호출을 포함해야 한다.

21.1.1.1 Number ( value )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. value 가 존재하면
    1. prim 을 ? ToNumeric(value) 로 둔다.
    2. prim 이 BigInt 이면 n𝔽((prim)) 로 둔다.
    3. 그렇지 않으면 nprim 으로 둔다.
  2. 그렇지 않으면,
    1. n+0𝔽 로 둔다.
  3. NewTarget 이 undefined 이면 n 을 반환한다.
  4. O 를 ? OrdinaryCreateFromConstructor(NewTarget, "%Number.prototype%", « [[NumberData]] ») 로 둔다.
  5. O.[[NumberData]]n 으로 설정한다.
  6. O 를 반환한다.

21.1.2 Number 생성자의 프로퍼티 (Properties of the Number Constructor)

Number 생성자는:

  • 값이 %Function.prototype%[[Prototype]] 내부 슬롯을 가진다.
  • 다음 프로퍼티들을 가진다:

21.1.2.1 Number.EPSILON

Number.EPSILON 의 값은 1과, Number 값으로 표현 가능한 1보다 큰 가장 작은 값 사이의 차이의 크기(Number 값)이며, 약 2.2204460492503130808472633361816 × 10-16이다.

이 프로퍼티는 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false } 특성을 가진다.

21.1.2.2 Number.isFinite ( number )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. number 가 Number 가 아니면 false 반환.
  2. number 가 finite 가 아니면 false 반환.
  3. 그렇지 않으면 true 반환.

21.1.2.3 Number.isInteger ( number )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. number 가 정수(Number) 이면 true 반환.
  2. false 반환.

21.1.2.4 Number.isNaN ( number )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. number 가 Number 가 아니면 false 반환.
  2. numberNaN 이면 true 반환.
  3. 그렇지 않으면 false 반환.
Note

이 함수는 인수를 NaN 인지 판정하기 전에 Number 로 변환한다는 점에서 전역 isNaN 함수(19.2.3)와 다르다.

21.1.2.5 Number.isSafeInteger ( number )

Note

정수 n 이 "안전한 정수(safe integer)" 이려면, 그리고 그럴 때에 한해 n 의 Number 값이 다른 어떤 정수의 Number 값과 같지 않아야 한다.

이 함수는 호출될 때 다음 단계를 수행한다:

  1. number 가 정수(Number) 이면
    1. abs((number)) ≤ 253 - 1 이면 true 반환.
  2. false 반환.

21.1.2.6 Number.MAX_SAFE_INTEGER

Note

IEEE 754-2019의 정밀도 한계로 인한 반올림 동작 때문에 Number.MAX_SAFE_INTEGER 보다 큰 모든 정수의 Number 값은 최소 하나 이상의 다른 정수와 공유된다. 그러한 큰 크기의 정수들은 안전하지 않으며 Number 값으로 정확히 표현되거나 서로 구별될 수 있음을 보장하지 않는다. 예를 들어 90071992547409929007199254740993 은 모두 Number 값 9007199254740992𝔽 로 평가된다.

Number.MAX_SAFE_INTEGER 의 값은 9007199254740991𝔽 (𝔽(253 - 1)) 이다.

이 프로퍼티는 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false } 특성을 가진다.

21.1.2.7 Number.MAX_VALUE

Number.MAX_VALUE 의 값은 Number 타입의 가장 큰 양의 유한 값이며, 이는 대략 1.7976931348623157 × 10308 이다.

이 프로퍼티는 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false } 특성을 가진다.

21.1.2.8 Number.MIN_SAFE_INTEGER

Note

IEEE 754-2019의 정밀도 한계로 인한 반올림 동작 때문에 Number.MIN_SAFE_INTEGER 보다 작은 모든 정수의 Number 값은 최소 하나 이상의 다른 정수와 공유된다. 그러한 큰 크기의(절대값이 큰) 정수들은 안전하지 않으며 Number 값으로 정확히 표현되거나 서로 구별될 수 있음을 보장하지 않는다. 예를 들어 -9007199254740992-9007199254740993 은 모두 Number 값 -9007199254740992𝔽 로 평가된다.

Number.MIN_SAFE_INTEGER 의 값은 -9007199254740991𝔽 (𝔽(-(253 - 1))) 이다.

이 프로퍼티는 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false } 특성을 가진다.

21.1.2.9 Number.MIN_VALUE

Number.MIN_VALUE 의 값은 Number 타입의 가장 작은 양의 값이며, 이는 대략 5 × 10-324 이다.

IEEE 754-2019 배정밀도 이진 표현에서 가장 작은 가능한 값은 비정규(denormalized) 수이다. 구현이 비정규 값을 지원하지 않는다면 Number.MIN_VALUE 의 값은 구현이 실제로 표현할 수 있는 가장 작은 0이 아닌 양의 값이어야 한다.

이 프로퍼티는 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false } 특성을 가진다.

21.1.2.10 Number.NaN

Number.NaN 의 값은 NaN 이다.

이 프로퍼티는 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false } 특성을 가진다.

21.1.2.11 Number.NEGATIVE_INFINITY

Number.NEGATIVE_INFINITY 의 값은 -∞𝔽 이다.

이 프로퍼티는 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false } 특성을 가진다.

21.1.2.12 Number.parseFloat ( string )

"parseFloat" 프로퍼티의 초기 값은 %parseFloat% 이다.

21.1.2.13 Number.parseInt ( string, radix )

"parseInt" 프로퍼티의 초기 값은 %parseInt% 이다.

21.1.2.14 Number.POSITIVE_INFINITY

Number.POSITIVE_INFINITY 의 값은 +∞𝔽 이다.

이 프로퍼티는 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false } 특성을 가진다.

21.1.2.15 Number.prototype

Number.prototype 의 초기 값은 Number 프로토타입 객체이다.

이 프로퍼티는 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false } 특성을 가진다.

21.1.3 Number 프로토타입 객체의 프로퍼티 (Properties of the Number Prototype Object)

Number 프로토타입 객체는:

  • %Number.prototype% 이다.
  • ordinary 객체이다.
  • 자체가 Number 객체이며 값이 +0𝔽[[NumberData]] 내부 슬롯을 가진다.
  • 값이 %Object.prototype%[[Prototype]] 내부 슬롯을 가진다.

명시적으로 달리 언급되지 않는 한 아래 정의된 Number 프로토타입 객체의 메서드는 generic 하지 않으며, 그들에게 전달된 this 값은 Number 값이거나 Number 값으로 초기화된 [[NumberData]] 내부 슬롯을 가진 객체여야 한다.

메서드 명세 안의 “this Number value” 라는 문구는 해당 메서드 호출의 this 값을 인수로 하여 추상 연산 ThisNumberValue 를 호출한 결과를 의미한다.

21.1.3.1 Number.prototype.constructor

Number.prototype.constructor 의 초기 값은 %Number% 이다.

21.1.3.2 Number.prototype.toExponential ( fractionDigits )

이 메서드는 이 Number 값을 십진 지수 표기(유효숫자 부분의 소수점 앞에 한 자리, 소수점 뒤에 fractionDigits 자리)로 표현한 String 을 반환한다. fractionDigitsundefined 이면, (항상 지수 표기로 출력된다는 점을 제외하면 ToString 과 같이) Number 를 유일하게 지정하는 데 필요한 만큼의 유효숫자 자릿수를 포함한다.

호출될 때 다음 단계를 수행한다:

  1. x 를 ? ThisNumberValue(this value) 로 둔다.
  2. f 를 ? ToIntegerOrInfinity(fractionDigits) 로 둔다.
  3. 단언: fractionDigitsundefined 이면 f 는 0.
  4. x 가 finite 가 아니면 Number::toString(x, 10) 반환.
  5. f < 0 또는 f > 100 이면 RangeError 예외 throw.
  6. x(x) 로 설정.
  7. s 를 빈 문자열로 둔다.
  8. x < 0 이면
    1. s = "-".
    2. x = -x.
  9. x = 0 이면
    1. mf + 1 번의 코드 유닛 0x0030 (DIGIT ZERO) 로 구성된 String 값으로 둔다.
    2. e = 0.
  10. 그렇지 않으면,
    1. fractionDigitsundefined 가 아니면
      1. 10fn < 10f + 1 이고 n × 10e - f - x 가 0 에 가장 가깝도록 하는 정수 e, n 을 둔다. 그러한 ( e, n ) 이 두 개 있으면 n × 10e - f 가 더 큰 것을 고른다.
    2. 그렇지 않으면,
      1. ff ≥ 0, 10ffn < 10ff + 1, 𝔽(n × 10e - ff) 가 𝔽(x), 그리고 ff 가 가능한 한 작은 정수인 e, n, ff 를 둔다. 이때 n 의 십진 표현은 ff + 1 자리이며, n 은 10 으로 나누어떨어지지 않고, n 의 최하위 자리는 유일하게 결정되지 않을 수 있다.
      2. f = ff.
    3. mn 의 십진 표현의 자릿수들(선행 0 없이 순서대로)로 구성된 String 값으로 둔다.
  11. f ≠ 0 이면
    1. a = m 의 첫 코드 유닛.
    2. b = 나머지 f 개의 코드 유닛.
    3. m = a, ".", b 의 문자열 연결.
  12. e = 0 이면
    1. c = "+".
    2. d = "0".
  13. 그렇지 않으면,
    1. e > 0 이면
      1. c = "+".
    2. 그렇지 않으면
      1. 단언: e < 0.
      2. c = "-".
      3. e = -e.
    3. d = e 의 십진 표현 자릿수들(선행 0 없이)로 구성된 String 값.
  14. m = m, "e", c, d 의 문자열 연결.
  15. sm 의 문자열 연결을 반환한다.
Note

위 규칙이 요구하는 것보다 더 정확한 변환을 제공하는 구현은 step 10.b.i 의 다음 대안 버전을 지침으로 사용하는 것이 권장된다:

  1. f ≥ 0, 10fn < 10f + 1, 𝔽(n × 10e - f) 가 𝔽(x), 그리고 f 가 가능한 한 작은 정수인 e, n, f 를 둔다. n 의 후보가 여러 개면 𝔽(n × 10e - f) 가 𝔽(x) 에 가장 가까운 값을 선택한다. 그런 후보가 두 개면 짝수인 것을 선택한다.

21.1.3.3 Number.prototype.toFixed ( fractionDigits )

Note 1

이 메서드는 이 Number 값을 십진 고정 소수점 표기로 표시한 String 을 반환하며 소수점 이하 자리수는 fractionDigits 이다. fractionDigitsundefined 이면 0 으로 간주한다.

호출될 때 다음 단계를 수행한다:

  1. x 를 ? ThisNumberValue(this value) 로 둔다.
  2. f 를 ? ToIntegerOrInfinity(fractionDigits) 로 둔다.
  3. 단언: fractionDigitsundefined 이면 f = 0.
  4. f 가 finite 가 아니면 RangeError 예외 throw.
  5. f < 0 또는 f > 100 이면 RangeError 예외 throw.
  6. x 가 finite 가 아니면 Number::toString(x, 10) 반환.
  7. x = (x).
  8. s = 빈 문자열.
  9. x < 0 이면
    1. s = "-".
    2. x = -x.
  10. x ≥ 1021 이면
    1. m = ! ToString(𝔽(x)).
  11. 그렇지 않으면
    1. nn / 10f - x 가 0 에 가장 가깝도록 하는 정수로 둔다. 그런 n 이 두 개면 더 큰 n 선택.
    2. n = 0 이면 m = "0"; 아니면 m = n 의 십진 표현 자릿수(선행 0 없이).
    3. f ≠ 0 이면
      1. k = m 의 길이.
      2. kf 이면
        1. z = f + 1 - k 번의 코드 유닛 0x0030 (DIGIT ZERO) 로 구성된 String.
        2. m = zm 의 문자열 연결.
        3. k = f + 1.
      3. a = m 의 처음 k - f 코드 유닛.
      4. b = 나머지 f 코드 유닛.
      5. m = a, ".", b 의 문자열 연결.
  12. sm 의 문자열 연결을 반환한다.
Note 2

toFixed 의 출력은 어떤 값들에 대해 toString 보다 더 정밀할 수 있다. 이는 toString 이 인접한 Number 값들과 구별하기 위한 충분한 유효숫자만을 출력하기 때문이다. 예를 들어,

(1000000000000000128).toString()"1000000000000000100" 을 반환하고,
(1000000000000000128).toFixed(0)"1000000000000000128" 을 반환한다.

21.1.3.4 Number.prototype.toLocaleString ( [ reserved1 [ , reserved2 ] ] )

ECMA-402 국제화 API 를 포함하는 ECMAScript 구현은 이 메서드를 ECMA-402 명세에 따라 구현해야 한다. 구현이 ECMA-402 API 를 포함하지 않는 경우 다음 명세가 사용된다:

이 메서드는 호스트 환경의 현재 로케일 관례에 따라 포맷된 이 Number 값을 나타내는 String 값을 생성한다. 이 메서드는 구현 정의이며 toString 과 같은 결과를 반환하는 것이 허용되나 권장되지는 않는다.

이 메서드의 선택적 매개변수 의미는 ECMA-402 명세에 정의된다; ECMA-402 를 지원하지 않는 구현은 그 매개변수 위치를 다른 용도로 사용해서는 안 된다.

21.1.3.5 Number.prototype.toPrecision ( precision )

이 메서드는 이 Number 값을 (유효숫자 부분 소수점 앞에 한 자리, 소수점 뒤에 precision - 1 자리)인 십진 지수 표기 또는 precision 개의 유효숫자를 갖는 십진 고정 표기 중 하나로 표현한 String 을 반환한다. precisionundefined 이면 대신 ToString 을 호출한다.

호출될 때 다음 단계를 수행한다:

  1. x 를 ? ThisNumberValue(this value) 로 둔다.
  2. precisionundefined 이면 ! ToString(x) 반환.
  3. p 를 ? ToIntegerOrInfinity(precision) 로 둔다.
  4. x 가 finite 가 아니면 Number::toString(x, 10) 반환.
  5. p < 1 또는 p > 100 이면 RangeError 예외 throw.
  6. x = (x).
  7. s = 빈 문자열.
  8. x < 0 이면
    1. s = 코드 유닛 0x002D (HYPHEN-MINUS).
    2. x = -x.
  9. x = 0 이면
    1. m = p 번의 코드 유닛 0x0030 (DIGIT ZERO) 로 구성된 String.
    2. e = 0.
  10. 그렇지 않으면
    1. 10p - 1n < 10p 이고 n × 10e - p + 1 - x 가 0 에 가장 가깝도록 하는 정수 e, n 을 둔다. 그러한 ( e, n ) 이 두 개면 n × 10e - p + 1 이 더 큰 것을 선택.
    2. mn 의 십진 표현 자릿수들(선행 0 없이)로 구성된 String 값으로 둔다.
    3. e < -6 또는 ep 이면
      1. 단언: e ≠ 0.
      2. p ≠ 1 이면
        1. a = m 의 첫 코드 유닛.
        2. b = 나머지 p - 1 코드 유닛.
        3. m = a, ".", b 의 문자열 연결.
      3. e > 0 이면
        1. c = 코드 유닛 0x002B (PLUS SIGN).
      4. 그렇지 않으면
        1. 단언: e < 0.
        2. c = 코드 유닛 0x002D (HYPHEN-MINUS).
        3. e = -e.
      5. d = e 의 십진 표현 자릿수들(선행 0 없이)로 구성된 String.
      6. s, m, 코드 유닛 0x0065 (e), c, d 의 문자열 연결을 반환.
  11. e = p - 1 이면 sm 의 문자열 연결 반환.
  12. e ≥ 0 이면
    1. m = 처음 e + 1 코드 유닛, 코드 유닛 0x002E (FULL STOP), 그리고 남은 p - (e + 1) 코드 유닛의 문자열 연결.
  13. 그렇지 않으면
    1. m = 코드 유닛 0x0030 (DIGIT ZERO), 코드 유닛 0x002E (FULL STOP), -(e + 1) 번의 코드 유닛 0x0030 (DIGIT ZERO), 그리고 String m 의 문자열 연결.
  14. sm 의 문자열 연결 반환.

21.1.3.6 Number.prototype.toString ( [ radix ] )

Note

선택적 radix2𝔽 에서 36𝔽 사이(포함)의 정수 Number 값이어야 한다. radixundefined 이면 10𝔽radix 값으로 사용된다.

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. x 를 ? ThisNumberValue(this value) 로 둔다.
  2. radixundefined 이면 radixMV = 10.
  3. 그렇지 않으면 radixMV = ? ToIntegerOrInfinity(radix).
  4. radixMV 가 2 이상 36 이하 구간에 없으면 RangeError 예외 throw.
  5. Number::toString(x, radixMV) 반환.

이 메서드는 generic 하지 않으며, this 값이 Number 또는 Number 객체가 아니면 TypeError 예외를 던진다. 따라서 다른 종류의 객체로 이전하여 메서드로 사용할 수 없다.

이 메서드의 "length" 프로퍼티 값은 1𝔽 이다.

21.1.3.7 Number.prototype.valueOf ( )

  1. ThisNumberValue(this value) 를 반환한다.

21.1.3.7.1 ThisNumberValue ( value )

The abstract operation ThisNumberValue takes argument value (ECMAScript 언어 값) and returns Number 를 담은 정상 completion 또는 throw completion. It performs the following steps when called:

  1. value 가 Number 이면 value 반환.
  2. value 가 Object 이고 [[NumberData]] 내부 슬롯을 가지면
    1. n = value.[[NumberData]].
    2. 단언: n 은 Number.
    3. n 반환.
  3. TypeError 예외 throw.

21.1.4 Number 인스턴스의 프로퍼티 (Properties of Number Instances)

Number 인스턴스는 Number 프로토타입 객체로부터 프로퍼티를 상속하는 ordinary 객체이다. Number 인스턴스는 또한 [[NumberData]] 내부 슬롯을 가진다. [[NumberData]] 내부 슬롯은 이 Number 객체가 나타내는 Number 값이다.

21.2 BigInt 객체 (BigInt Objects)

21.2.1 BigInt 생성자 (The BigInt Constructor)

BigInt 생성자는 다음과 같다:

  • %BigInt% 이다.
  • 전역 객체"BigInt" 프로퍼티 초기 값이다.
  • 생성자가 아니라 함수로 호출될 때 타입 변환을 수행한다.
  • new 연산자와 함께 사용하거나 서브클래싱하도록 의도되지 않았다. 클래스 정의의 extends 절 값으로 사용할 수는 있으나 BigInt 생성자에 대한 super 호출은 예외를 발생시킨다.

21.2.1.1 BigInt ( value )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. NewTarget 이 undefined 가 아니면 TypeError 예외를 throw 한다.
  2. prim 을 ? ToPrimitive(value, number) 로 둔다.
  3. prim 이 Number 이면 ? NumberToBigInt(prim) 를 반환한다.
  4. 그렇지 않으면 ? ToBigInt(prim) 를 반환한다.

21.2.1.1.1 NumberToBigInt ( number )

The abstract operation NumberToBigInt takes argument number (a Number) and returns BigInt 를 담은 정상 completion 또는 throw completion. It performs the following steps when called:

  1. number 가 정수(Number)가 아니면 RangeError 예외를 throw 한다.
  2. ((number)) 를 반환한다.

21.2.2 BigInt 생성자의 프로퍼티 (Properties of the BigInt Constructor)

BigInt 생성자는:

  • 값이 %Function.prototype%[[Prototype]] 내부 슬롯을 가진다.
  • 다음 프로퍼티들을 가진다:

21.2.2.1 BigInt.asIntN ( bits, bigint )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. bits 를 ? ToIndex(bits) 로 설정한다.
  2. bigint 를 ? ToBigInt(bigint) 로 설정한다.
  3. mod(bigint) mod 2bits 로 둔다.
  4. mod ≥ 2bits - 1 이면 (mod - 2bits) 를 반환; 그렇지 않으면 (mod) 를 반환한다.

21.2.2.2 BigInt.asUintN ( bits, bigint )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. bits 를 ? ToIndex(bits) 로 설정한다.
  2. bigint 를 ? ToBigInt(bigint) 로 설정한다.
  3. ((bigint) mod 2bits) 를 반환한다.

21.2.2.3 BigInt.prototype

BigInt.prototype 의 초기 값은 BigInt 프로토타입 객체이다.

이 프로퍼티는 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false } 특성을 가진다.

21.2.3 BigInt 프로토타입 객체의 프로퍼티 (Properties of the BigInt Prototype Object)

BigInt 프로토타입 객체는:

  • %BigInt.prototype% 이다.
  • ordinary 객체이다.
  • BigInt 객체가 아니며 [[BigIntData]] 내부 슬롯을 갖지 않는다.
  • 값이 %Object.prototype%[[Prototype]] 내부 슬롯을 가진다.

메서드 명세 내 “this BigInt value” 라는 표현은 그 메서드 호출의 this 값을 인수로 하여 추상 연산 ThisBigIntValue 를 호출한 결과를 가리킨다.

21.2.3.1 BigInt.prototype.constructor

BigInt.prototype.constructor 의 초기 값은 %BigInt% 이다.

21.2.3.2 BigInt.prototype.toLocaleString ( [ reserved1 [ , reserved2 ] ] )

ECMA-402 국제화 API 를 포함하는 ECMAScript 구현은 이 메서드를 ECMA-402 명세에 따라 구현해야 한다. 구현이 ECMA-402 API 를 포함하지 않는 경우 아래 명세가 사용된다:

이 메서드는 호스트 환경의 현재 로케일 관례에 따라 포맷된 이 BigInt 값을 나타내는 String 값을 생성한다. 이 메서드는 구현 정의이며 toString 과 동일한 결과를 반환하는 것이 허용되나 권장되지는 않는다.

이 메서드의 선택적 매개변수 의미는 ECMA-402 명세에 정의되며, ECMA-402 지원이 없는 구현은 해당 매개변수 위치를 다른 목적으로 사용해서는 안 된다.

21.2.3.3 BigInt.prototype.toString ( [ radix ] )

Note

선택적 radix2𝔽 이상 36𝔽 이하(포함)의 정수 Number 값이어야 한다. radixundefined 이면 10𝔽radix 값으로 사용된다.

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. x 를 ? ThisBigIntValue(this value) 로 둔다.
  2. radixundefined 이면 radixMV = 10.
  3. 그렇지 않으면 radixMV = ? ToIntegerOrInfinity(radix).
  4. radixMV 가 2 이상 36 이하 구간에 없으면 RangeError 예외를 throw 한다.
  5. BigInt::toString(x, radixMV) 를 반환한다.

이 메서드는 generic 하지 않으며 this 값이 BigInt 또는 BigInt 객체가 아니면 TypeError 예외를 던진다. 따라서 다른 종류의 객체로 이전하여 메서드로 사용할 수 없다.

21.2.3.4 BigInt.prototype.valueOf ( )

  1. ThisBigIntValue(this value) 를 반환한다.

21.2.3.4.1 ThisBigIntValue ( value )

The abstract operation ThisBigIntValue takes argument value (an ECMAScript language value) and returns BigInt 를 담은 정상 completion 또는 throw completion. It performs the following steps when called:

  1. value 가 BigInt 이면 value 를 반환한다.
  2. value 가 Object 이고 [[BigIntData]] 내부 슬롯을 가진다면
    1. 단언: value.[[BigIntData]] 는 BigInt 이다.
    2. value.[[BigIntData]] 를 반환한다.
  3. TypeError 예외를 throw 한다.

21.2.3.5 BigInt.prototype [ %Symbol.toStringTag% ]

%Symbol.toStringTag% 프로퍼티의 초기 값은 String 값 "BigInt" 이다.

이 프로퍼티는 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true } 특성을 가진다.

21.2.4 BigInt 인스턴스의 프로퍼티 (Properties of BigInt Instances)

BigInt 인스턴스는 BigInt 프로토타입 객체로부터 프로퍼티를 상속하는 ordinary 객체이다. BigInt 인스턴스는 또한 [[BigIntData]] 내부 슬롯을 가진다. [[BigIntData]] 내부 슬롯은 해당 BigInt 객체가 나타내는 BigInt 값이다.

21.3 Math 객체 (The Math Object)

Math 객체는 다음과 같다:

  • %Math% 이다.
  • 전역 객체 "Math" 프로퍼티의 초기 값이다.
  • ordinary 객체이다.
  • 값이 %Object.prototype%[[Prototype]] 내부 슬롯을 가진다.
  • 함수 객체가 아니다.
  • [[Construct]] 내부 메서드를 가지지 않아 new 연산자로 생성자로 사용할 수 없다.
  • [[Call]] 내부 메서드를 가지지 않아 함수로 호출될 수 없다.
Note

이 명세에서 “the Number value for x” 라는 구문은 6.1.6.1 에 정의된 기술적 의미를 가진다.

21.3.1 Math 객체의 값 프로퍼티 (Value Properties of the Math Object)

21.3.1.1 Math.E

자연로그의 밑 e 에 대한 Number 값. 대략 2.7182818284590452354.

이 프로퍼티는 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false } 특성을 가진다.

21.3.1.2 Math.LN10

10 의 자연로그에 대한 Number 값. 대략 2.302585092994046.

이 프로퍼티는 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false } 특성을 가진다.

21.3.1.3 Math.LN2

2 의 자연로그에 대한 Number 값. 대략 0.6931471805599453.

이 프로퍼티는 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false } 특성을 가진다.

21.3.1.4 Math.LOG10E

자연로그의 밑 e 의 밑-10 로그(Number 값). 대략 0.4342944819032518.

이 프로퍼티는 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false } 특성을 가진다.

Note

Math.LOG10E 값은 Math.LN10 값의 역수에 가까운 값이다.

21.3.1.5 Math.LOG2E

자연로그의 밑 e 의 밑-2 로그(Number 값). 대략 1.4426950408889634.

이 프로퍼티는 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false } 특성을 가진다.

Note

Math.LOG2E 값은 Math.LN2 값의 역수에 가까운 값이다.

21.3.1.6 Math.PI

원주율 π (원둘레/지름) 에 대한 Number 값. 대략 3.1415926535897932.

이 프로퍼티는 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false } 특성을 가진다.

21.3.1.7 Math.SQRT1_2

½ 의 제곱근(Number 값). 대략 0.7071067811865476.

이 프로퍼티는 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false } 특성을 가진다.

Note

Math.SQRT1_2 값은 Math.SQRT2 값의 역수에 가까운 값이다.

21.3.1.8 Math.SQRT2

2 의 제곱근(Number 값). 대략 1.4142135623730951.

이 프로퍼티는 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false } 특성을 가진다.

21.3.1.9 Math [ %Symbol.toStringTag% ]

%Symbol.toStringTag% 프로퍼티의 초기 값은 String 값 "Math" 이다.

이 프로퍼티는 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true } 특성을 가진다.

21.3.2 Math 객체의 함수 프로퍼티 (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 함수의 동작은 경계 사례에 대해 특정 결과를 요구하는 것 외에는 여기서 정확히 규정되지 않는다. 다른 인수 값에 대해서는 익숙한 수학 함수의 결과를 근사하도록 의도되며, 근사 알고리즘 선택에 다소 재량이 허용된다. 일반적인 의도는 구현자가 해당 하드웨어 플랫폼에서 C 프로그래머가 사용할 수 있는 동일한 수학 라이브러리를 ECMAScript 에도 사용할 수 있도록 하는 것이다.

알고리즘 선택은 구현에 맡기지만(표준에서 강제하지 않음) IEEE 754-2019 산술 근사 알고리즘을 포함하는 Sun Microsystems 의 자유 배포 수학 라이브러리 fdlibm 사용이 권장된다 (http://www.netlib.org/fdlibm).

21.3.2.1 Math.abs ( x )

x 의 절대값을 반환한다; 결과는 부호만 양수이고 크기는 x 와 동일하다.

호출될 때 다음 단계를 수행한다:

  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 )

x 의 아크코사인(역코사인)을 반환한다. 결과는 라디안으로 표현되며 +0𝔽 이상 𝔽(π) 이하 구간에 있다.

호출될 때 다음 단계를 수행한다:

  1. n 을 ? ToNumber(x) 로 둔다.
  2. nNaN 이거나 n > 1𝔽 이거나 n < -1𝔽 이면 NaN 반환.
  3. n1𝔽 이면 +0𝔽 반환.
  4. (n) 의 역코사인을 나타내는 구현 근사 Number 값을 반환한다.

21.3.2.3 Math.acosh ( x )

x 의 역쌍곡코사인(acosh)을 반환한다.

호출될 때 다음 단계를 수행한다:

  1. n 을 ? ToNumber(x) 로 둔다.
  2. nNaN 이거나 +∞𝔽 이면 n 반환.
  3. n1𝔽 이면 +0𝔽 반환.
  4. n < 1𝔽 이면 NaN 반환.
  5. (n) 의 역쌍곡코사인을 나타내는 구현 근사 Number 값을 반환한다.

21.3.2.4 Math.asin ( x )

x 의 아크사인(역사인)을 반환한다. 결과는 라디안이며 𝔽(-π / 2) 이상 𝔽(π / 2) 이하 구간에 있다.

호출될 때 다음 단계를 수행한다:

  1. n 을 ? ToNumber(x) 로 둔다.
  2. nNaN, +0𝔽, -0𝔽 중 하나이면 n 반환.
  3. n > 1𝔽 또는 n < -1𝔽 이면 NaN 반환.
  4. (n) 의 역사인을 나타내는 구현 근사 Number 값을 반환한다.

21.3.2.5 Math.asinh ( x )

x 의 역쌍곡사인(asinh)을 반환한다.

호출될 때 다음 단계를 수행한다:

  1. n 을 ? ToNumber(x) 로 둔다.
  2. n 이 finite 가 아니거나 +0𝔽 또는 -0𝔽 이면 n 반환.
  3. (n) 의 역쌍곡사인을 나타내는 구현 근사 Number 값을 반환한다.

21.3.2.6 Math.atan ( x )

x 의 아크탄젠트(역탄젠트)를 반환한다. 결과는 라디안이며 𝔽(-π / 2) 이상 𝔽(π / 2) 이하 구간.

호출될 때:

  1. n = ? ToNumber(x).
  2. nNaN, +0𝔽, -0𝔽 중 하나이면 n 반환.
  3. n+∞𝔽 이면 π / 2 를 나타내는 구현 근사 Number 값 반환.
  4. n-∞𝔽 이면 -π / 2 를 나타내는 구현 근사 Number 값 반환.
  5. (n) 의 역탄젠트를 나타내는 구현 근사 Number 값 반환.

21.3.2.7 Math.atanh ( x )

x 의 역쌍곡탄젠트(atanh)를 반환한다.

호출될 때:

  1. n = ? ToNumber(x).
  2. nNaN, +0𝔽, -0𝔽 중 하나이면 n 반환.
  3. n > 1𝔽 또는 n < -1𝔽 이면 NaN 반환.
  4. n1𝔽 이면 +∞𝔽 반환.
  5. n-1𝔽 이면 -∞𝔽 반환.
  6. (n) 의 역쌍곡탄젠트를 나타내는 구현 근사 Number 값 반환.

21.3.2.8 Math.atan2 ( y, x )

두 인수 y, x 의 몫 y / x 에 대한 역탄젠트를 반환하며, yx 의 부호를 사용해 사분면을 결정한다. 2인수 역탄젠트에서 y 가 첫 번째, x 가 두 번째 인수인 것은 의도적이며 전통이다. 결과는 라디안으로 -π 이상 +π 이하 구간.

호출될 때:

  1. ny = ? ToNumber(y).
  2. nx = ? ToNumber(x).
  3. ny 또는 nxNaN 이면 NaN 반환.
  4. ny = +∞𝔽 이면
    1. nx = +∞𝔽 이면 π / 4 근사값 반환.
    2. nx = -∞𝔽 이면 3π / 4 근사값 반환.
    3. 그렇지 않으면 π / 2 근사값 반환.
  5. ny = -∞𝔽 이면
    1. nx = +∞𝔽 이면 -π / 4 근사값 반환.
    2. nx = -∞𝔽 이면 -3π / 4 근사값 반환.
    3. 그렇지 않으면 -π / 2 근사값 반환.
  6. ny = +0𝔽 이면
    1. nx > +0𝔽 또는 nx = +0𝔽 이면 +0𝔽 반환.
    2. 그렇지 않으면 π 근사값 반환.
  7. ny = -0𝔽 이면
    1. nx > +0𝔽 또는 nx = +0𝔽 이면 -0𝔽 반환.
    2. 그렇지 않으면 -π 근사값 반환.
  8. 단언: ny 는 finite 이고 ±0 아님.
  9. ny > +0𝔽 이면
    1. nx = +∞𝔽 이면 +0𝔽 반환.
    2. nx = -∞𝔽 이면 π 근사값 반환.
    3. nx+0𝔽 또는 -0𝔽 이면 π / 2 근사값 반환.
  10. ny < -0𝔽 이면
    1. nx = +∞𝔽 이면 -0𝔽 반환.
    2. nx = -∞𝔽 이면 -π 근사값 반환.
    3. nx+0𝔽 또는 -0𝔽 이면 -π / 2 근사값 반환.
  11. 단언: nx 는 finite 이고 ±0 아님.
  12. rabs((ny)/(nx)) 의 역탄젠트로 둔다.
  13. nx < -0𝔽 이면
    1. ny > +0𝔽 이면 r = π - r.
    2. 그렇지 않으면 r = -π + r.
  14. 그렇지 않으면
    1. ny < -0𝔽 이면 r = -r.
  15. r 를 나타내는 구현 근사 Number 값 반환.

21.3.2.9 Math.cbrt ( x )

x 의 세제곱근을 반환한다.

호출될 때:

  1. n = ? ToNumber(x).
  2. n 이 finite 가 아니거나 +0𝔽 또는 -0𝔽 이면 n 반환.
  3. (n) 의 세제곱근을 나타내는 구현 근사 Number 값 반환.

21.3.2.10 Math.ceil ( x )

x 보다 작지 않은 가장 작은( -∞ 에 가장 가까운 ) 정수 Number 값을 반환한다. x 가 이미 정수이면 결과는 x.

호출될 때:

  1. n = ? ToNumber(x).
  2. n 이 finite 가 아니거나 ±0 이면 n 반환.
  3. n < -0𝔽 이고 n > -1𝔽 이면 -0𝔽 반환.
  4. n 이 정수이면 n 반환.
  5. n 보다 작지 않은 가장 작은 정수 Number 값 반환.
Note

Math.ceil(x) 값은 -Math.floor(-x) 값과 같다.

21.3.2.11 Math.clz32 ( x )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. n = ? ToUint32(x).
  2. pn 의 부호 없는 32비트 이진 표현에서 선행 0 비트 개수로 둔다.
  3. 𝔽(p) 를 반환한다.
Note

n+0𝔽 또는 -0𝔽 이면 32𝔽 반환. 최상위 비트가 1 이면 +0𝔽 반환.

21.3.2.12 Math.cos ( x )

라디안 인수 x 의 코사인을 반환한다.

호출될 때:

  1. n = ? ToNumber(x).
  2. n 이 finite 가 아니면 NaN 반환.
  3. n 이 ±0 이면 1𝔽 반환.
  4. (n) 의 코사인을 나타내는 구현 근사 Number 값 반환.

21.3.2.13 Math.cosh ( x )

x 의 쌍곡코사인을 반환한다.

호출될 때:

  1. n = ? ToNumber(x).
  2. nNaN 이면 NaN 반환.
  3. n 이 ±∞ 이면 +∞𝔽 반환.
  4. n 이 ±0 이면 1𝔽 반환.
  5. (n) 의 쌍곡코사인을 나타내는 구현 근사 Number 값 반환.
Note

Math.cosh(x) = (Math.exp(x) + Math.exp(-x)) / 2.

21.3.2.14 Math.exp ( x )

x 의 지수 함수(e^x) 값을 반환한다.

호출될 때:

  1. n = ? ToNumber(x).
  2. nNaN 또는 +∞𝔽 이면 n 반환.
  3. n 이 ±0 이면 1𝔽 반환.
  4. n-∞𝔽 이면 +0𝔽 반환.
  5. (n) 의 지수 함수를 나타내는 구현 근사 Number 값 반환.

21.3.2.15 Math.expm1 ( x )

e^x - 1 값을, x 가 0 에 가까운 경우에도 정확하게 계산해 반환한다.

호출될 때:

  1. n = ? ToNumber(x).
  2. nNaN, +0𝔽, -0𝔽, +∞𝔽 중 하나이면 n 반환.
  3. n-∞𝔽 이면 -1𝔽 반환.
  4. exp(n) 의 지수 함수 값으로 둔다.
  5. exp - 1 을 나타내는 구현 근사 Number 값 반환.

21.3.2.16 Math.floor ( x )

x 보다 크지 않은 가장 큰( +∞ 에 가장 가까운 ) 정수 Number 값을 반환. 이미 정수이면 x.

호출될 때:

  1. n = ? ToNumber(x).
  2. n 이 finite 가 아니거나 ±0 이면 n 반환.
  3. n < 1𝔽 그리고 n > +0𝔽 이면 +0𝔽 반환.
  4. n 이 정수이면 n 반환.
  5. n 보다 크지 않은 가장 큰 정수 Number 값 반환.
Note

Math.floor(x) = -Math.ceil(-x).

21.3.2.17 Math.fround ( x )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. n = ? ToNumber(x).
  2. nNaN 이면 NaN 반환.
  3. n 이 ±0, ±∞ 중 하나이면 n 반환.
  4. n32 = n 을 roundTiesToEven 모드로 IEEE 754-2019 binary32 로 변환한 결과.
  5. n64 = n32IEEE 754-2019 binary64 로 변환한 결과.
  6. n64 에 대응하는 ECMAScript Number 값 반환.

21.3.2.18 Math.f16round ( x )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. n = ? ToNumber(x).
  2. nNaN 이면 NaN 반환.
  3. n 이 ±0, ±∞ 중 하나이면 n 반환.
  4. n16 = n 을 roundTiesToEven 모드로 IEEE 754-2019 binary16 으로 변환한 결과.
  5. n64 = n16IEEE 754-2019 binary64 로 변환한 결과.
  6. n64 에 대응하는 ECMAScript Number 값 반환.
Note

이 연산은 먼저 binary32 로 변환 후 binary16 으로 변환하는 것과 다르다(이중 반올림 가능성). 예: k = 1.00048828125000022204𝔽 에 대해 Math.f16round(k) 는 1.0009765625𝔽 이지만 Math.f16round(Math.fround(k)) 는 1𝔽 이다.

모든 플랫폼이 binary64→binary16 캐스팅을 네이티브 지원하지는 않는다. MIT 라이선스 half 라이브러리 등 사용 가능. 또는 binary64→binary32 (roundTiesToEven) 후 잘못된 이중 반올림 가능성 검사, 해당 경우 mantissa 조정(odd 라운드에 해당) 후 최종 binary16 캐스팅 등으로 구현 가능.

21.3.2.19 Math.hypot ( ...args )

0개 이상의 인수에 대해 제곱들의 합의 제곱근을 반환한다.

호출될 때:

  1. coerced = 새 빈 리스트.
  2. argsarg 에 대해
    1. n = ? ToNumber(arg).
    2. coercedn 추가.
  3. coercednumber 에 대해
    1. number 가 ±∞ 이면 +∞𝔽 반환.
  4. onlyZero = true.
  5. coercednumber 에 대해
    1. numberNaN 이면 NaN 반환.
    2. number+0𝔽-0𝔽 도 아니면 onlyZero = false.
  6. onlyZerotrue 이면 +0𝔽 반환.
  7. coerced 요소들의 수학적 값 각각 제곱 합의 제곱근을 나타내는 구현 근사 Number 값 반환.

이 함수의 "length" 프로퍼티는 2𝔽 이다.

Note

두 개 이상 인수 시 단순 구현에서 발생하기 쉬운 overflow/underflow 로 인한 정밀도 손실을 피해야 한다.

21.3.2.20 Math.imul ( x, y )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. a = (? ToUint32(x)).
  2. b = (? ToUint32(y)).
  3. product = (a × b) mod 232.
  4. product ≥ 231 이면 𝔽(product - 232) 반환; 아니면 𝔽(product) 반환.

21.3.2.21 Math.log ( x )

x 의 자연로그를 반환한다.

호출될 때:

  1. n = ? ToNumber(x).
  2. nNaN 또는 +∞𝔽 이면 n 반환.
  3. n = 1𝔽 이면 +0𝔽 반환.
  4. n 이 ±0 이면 -∞𝔽 반환.
  5. n < -0𝔽 이면 NaN 반환.
  6. (n) 의 자연로그를 나타내는 구현 근사 Number 값 반환.

21.3.2.22 Math.log1p ( x )

1 + x 의 자연로그를 반환하며 x 가 0 에 매우 가까울 때도 정확하도록 계산된다.

호출될 때:

  1. n = ? ToNumber(x).
  2. nNaN, +0𝔽, -0𝔽, +∞𝔽 중 하나이면 n 반환.
  3. n = -1𝔽 이면 -∞𝔽 반환.
  4. n < -1𝔽 이면 NaN 반환.
  5. 1 + (n) 의 자연로그를 나타내는 구현 근사 Number 값 반환.

21.3.2.23 Math.log10 ( x )

x 의 밑 10 로그를 반환한다.

호출될 때:

  1. n = ? ToNumber(x).
  2. nNaN 또는 +∞𝔽 이면 n 반환.
  3. n = 1𝔽 이면 +0𝔽 반환.
  4. n 이 ±0 이면 -∞𝔽 반환.
  5. n < -0𝔽 이면 NaN 반환.
  6. (n) 의 밑 10 로그 구현 근사 값 반환.

21.3.2.24 Math.log2 ( x )

x 의 밑 2 로그를 반환한다.

호출될 때:

  1. n = ? ToNumber(x).
  2. nNaN 또는 +∞𝔽 이면 n 반환.
  3. n = 1𝔽 이면 +0𝔽 반환.
  4. n 이 ±0 이면 -∞𝔽 반환.
  5. n < -0𝔽 이면 NaN 반환.
  6. (n) 의 밑 2 로그 구현 근사 값 반환.

21.3.2.25 Math.max ( ...args )

0개 이상의 인수에 대해 각 인수에 ToNumber 를 적용한 결과 중 최댓값을 반환한다.

호출될 때:

  1. coerced = 새 빈 리스트.
  2. argsarg 에 대해
    1. n = ? ToNumber(arg).
    2. coercedn 추가.
  3. highest = -∞𝔽.
  4. coercednumber 에 대해
    1. numberNaN 이면 NaN 반환.
    2. number = +0𝔽 이고 highest = -0𝔽 이면 highest = +0𝔽.
    3. number > highest 이면 highest = number.
  5. highest 반환.
Note

최댓값 비교는 IsLessThan 알고리즘을 사용하되 +0𝔽-0𝔽 보다 큰 것으로 간주한다.

이 함수의 "length" 프로퍼티는 2𝔽 이다.

21.3.2.26 Math.min ( ...args )

0개 이상의 인수에 대해 각 인수에 ToNumber 를 적용한 결과 중 최솟값을 반환한다.

호출될 때:

  1. coerced = 새 빈 리스트.
  2. argsarg 에 대해
    1. n = ? ToNumber(arg).
    2. coercedn 추가.
  3. lowest = +∞𝔽.
  4. coercednumber 에 대해
    1. numberNaN 이면 NaN 반환.
    2. number = -0𝔽 이고 lowest = +0𝔽 이면 lowest = -0𝔽.
    3. number < lowest 이면 lowest = number.
  5. lowest 반환.
Note

최솟값 결정 비교도 IsLessThan 을 사용하되 +0𝔽-0𝔽 보다 큰 것으로 취급한다.

이 함수의 "length" 프로퍼티는 2𝔽 이다.

21.3.2.27 Math.pow ( base, exponent )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. base = ? ToNumber(base).
  2. exponent = ? ToNumber(exponent).
  3. Number::exponentiate(base, exponent) 를 반환한다.

21.3.2.28 Math.random ( )

+0𝔽 이상 1𝔽 미만 구간에서 양의 부호를 가지는 Number 값을 (구현 정의 알고리즘/전략으로) 균등 분포에 가깝게 무작위 또는 의사난수로 반환한다.

서로 다른 realm 에 대해 생성된 각 Math.random 함수는 연속 호출에서 서로 다른 수열을 생성해야 한다.

21.3.2.29 Math.round ( x )

x 에 가장 가까운 정수 Number 값을 반환한다. 두 정수가 동일하게 가깝다면 +∞ 에 더 가까운 값을 반환. x 가 이미 정수면 x 반환.

호출될 때:

  1. n = ? ToNumber(x).
  2. n 이 finite 가 아니거나 정수이면 n 반환.
  3. n < 0.5𝔽 그리고 n > +0𝔽 이면 +0𝔽 반환.
  4. n < -0𝔽 그리고 n-0.5𝔽 이면 -0𝔽 반환.
  5. n 과 가장 가까운 정수 Number 값을 반환(동일 거리면 +∞ 쪽 선택).
Note 1

Math.round(3.5) 는 4, Math.round(-3.5) 는 -3.

Note 2

Math.round(x) 는 항상 Math.floor(x + 0.5) 와 같지 않다. 예를 들어 x-0𝔽 이거나 -0𝔽 보다 작고 -0.5𝔽 이상이면 Math.round(x)-0𝔽 반환하지만 Math.floor(x + 0.5)+0𝔽 를 반환. 또한 내부 반올림으로 인해 차이날 수 있다.

21.3.2.30 Math.sign ( x )

x 의 부호(양수/음수/0)를 나타내는 값을 반환한다.

호출될 때:

  1. n = ? ToNumber(x).
  2. nNaN, +0𝔽, -0𝔽 중 하나면 n 반환.
  3. n < -0𝔽 이면 -1𝔽 반환.
  4. 1𝔽 반환.

21.3.2.31 Math.sin ( x )

라디안 인수 x 의 사인 값을 반환한다.

호출될 때:

  1. n = ? ToNumber(x).
  2. nNaN, +0𝔽, -0𝔽 중 하나면 n 반환.
  3. n 이 ±∞ 이면 NaN 반환.
  4. (n) 의 사인을 나타내는 구현 근사 Number 값 반환.

21.3.2.32 Math.sinh ( x )

x 의 쌍곡사인을 반환한다.

호출될 때:

  1. n = ? ToNumber(x).
  2. n 이 finite 가 아니거나 ±0 이면 n 반환.
  3. (n) 의 쌍곡사인을 나타내는 구현 근사 Number 값 반환.
Note

Math.sinh(x) = (Math.exp(x) - Math.exp(-x)) / 2.

21.3.2.33 Math.sqrt ( x )

x 의 제곱근을 반환한다.

호출될 때:

  1. n = ? ToNumber(x).
  2. nNaN, +0𝔽, -0𝔽, +∞𝔽 중 하나이면 n 반환.
  3. n < -0𝔽 이면 NaN 반환.
  4. 𝔽((n) 의 제곱근) 반환.

21.3.2.34 Math.sumPrecise ( items )

Number 들로 이루어진 iterable 을 받아 모든 값을 더해 합을 반환한다. 어떤 값이 Number 가 아니면 TypeError 예외를 던진다.

호출될 때:

  1. RequireObjectCoercible(items) 수행.
  2. iteratorRecord = ? GetIterator(items, sync).
  3. state = minus-zero.
  4. sum = 0.
  5. count = 0.
  6. next = not-started.
  7. nextdone 이 아닐 동안 반복
    1. next = ? IteratorStepValue(iteratorRecord).
    2. nextdone 이 아니면
      1. count ≥ 253 - 1 이면
        1. NOTE: 현실적으로 도달하지 않는 단계이며 입력이 “적당한 크기” 임을 가정 가능하게 하기 위한 것.
        2. error = ThrowCompletion(새 RangeError 객체).
        3. IteratorClose(iteratorRecord, error) 반환.
      2. next 가 Number 가 아니면
        1. error = ThrowCompletion(새 TypeError 객체).
        2. IteratorClose(iteratorRecord, error) 반환.
      3. n = next.
      4. statenot-a-number 이면
        1. nNaN 이면
          1. state = not-a-number.
        2. Else if n = +∞𝔽
          1. state = minus-infinity 이면 not-a-number, 아니면 plus-infinity.
        3. Else if n = -∞𝔽
          1. state = plus-infinity 이면 not-a-number, 아니면 minus-infinity.
        4. Else if n-0𝔽 가 아니고 stateminus-zero 또는 finite 이면
          1. state = finite.
          2. sum = sum + (n).
      5. count = count + 1.
  8. state = not-a-number 이면 NaN 반환.
  9. state = plus-infinity 이면 +∞𝔽 반환.
  10. state = minus-infinity 이면 -∞𝔽 반환.
  11. state = minus-zero 이면 -0𝔽 반환.
  12. 𝔽(sum) 반환.
Note

sum 은 임의 정밀도 산술 없이 여러 알고리즘으로 계산 가능. 예: Jonathan Richard Shewchuk 의 Adaptive Precision Floating-Point Arithmetic and Fast Robust Geometric Predicates 에 나오는 "Grow-Expansion" 알고리즘. 또는 "Fast exact summation using small and large superaccumulators" (코드: https://gitlab.com/radfordneal/xsum).

21.3.2.35 Math.tan ( x )

라디안 인수 x 의 탄젠트를 반환한다.

호출될 때:

  1. n = ? ToNumber(x).
  2. nNaN, +0𝔽, -0𝔽 중 하나면 n 반환.
  3. n 이 ±∞ 이면 NaN 반환.
  4. (n) 의 탄젠트를 나타내는 구현 근사 Number 값 반환.

21.3.2.36 Math.tanh ( x )

x 의 쌍곡탄젠트를 반환한다.

호출될 때:

  1. n = ? ToNumber(x).
  2. nNaN, +0𝔽, -0𝔽 중 하나면 n 반환.
  3. n = +∞𝔽 이면 1𝔽 반환.
  4. n = -∞𝔽 이면 -1𝔽 반환.
  5. (n) 의 쌍곡탄젠트를 나타내는 구현 근사 Number 값 반환.
Note

Math.tanh(x) = (Math.exp(x) - Math.exp(-x)) / (Math.exp(x) + Math.exp(-x)).

21.3.2.37 Math.trunc ( x )

x 의 정수 부분(소수부 제거)을 반환. x 가 이미 정수이면 x 반환.

호출될 때:

  1. n = ? ToNumber(x).
  2. n 이 finite 가 아니거나 ±0 이면 n 반환.
  3. n < 1𝔽 그리고 n > +0𝔽 이면 +0𝔽 반환.
  4. n < -0𝔽 그리고 n > -1𝔽 이면 -0𝔽 반환.
  5. +0𝔽 방향으로 n 에 가장 가까운 정수 Number 값 반환.

21.4 Date 객체

21.4.1 Date 객체 개요 및 추상 연산 정의

다음의 추상 연산들은 시간 값(21.4.1.1에서 정의됨)에 대해 동작합니다. 모든 경우에 이 함수들에 인수로 NaN이 들어오면 결과도 NaN이 됨을 유의하세요.

21.4.1.1 시간 값과 시간 범위

ECMAScript의 시간 측정은 POSIX의 시간 측정과 유사하며, 특히 전환 그레고리력(proleptic Gregorian calendar), 1970년 1월 1일 0시 UTC의 기점(epoch), 그리고 하루가 정확히 86,400초(각 초는 1000밀리초)로 구성된다는 정의를 공유합니다.

ECMAScript의 시간 값은 Number로, 밀리초 단위의 한 순간을 나타내는 유한 정수 Number이거나 특정 순간을 나타내지 않는 NaN일 수 있습니다. 24 × 60 × 60 × 1000 = 86,400,000의 배수(즉, 정수 d에 대해 86,400,000 × d)인 시간 값은 기점 이후 d일이 지난 UTC 일의 시작 순간(음수 d라면 기점 이전)을 나타냅니다. 그 외의 유한 시간 값 t는 그와 가장 가까운 이전 배수 시간 값 s를 기준으로 정의되며, s와 동일한 UTC 일 내에서 (t - s) 밀리초가 지난 순간을 나타냅니다.

시간 값은 UTC 윤초(leap seconds)를 고려하지 않습니다—양의 윤초 내의 순간을 나타내는 시간 값은 없으며, 음의 윤초로 인해 UTC 타임라인에서 제거된 순간을 나타내는 시간 값은 있습니다. 그럼에도 불구하고 시간 값의 정의는 윤초 경계에서만 불연속이 있고 그 외에는 UTC와 부분적으로 일치함을 보장합니다.

Number는 -9,007,199,254,740,992에서 9,007,199,254,740,992(21.1.2.821.1.2.6 참고)까지의 모든 정수를 정확하게 표현할 수 있습니다. 시간 값은 -8,640,000,000,000,000에서 8,640,000,000,000,000 밀리초까지의 약간 더 작은 범위를 지원합니다. 이는 1970년 1월 1일 0시 UTC 기준으로 -100,000,000일부터 100,000,000일까지의 시간 값 범위를 제공합니다.

1970년 1월 1일 0시 UTC의 정확한 순간은 시간 값 +0𝔽으로 표현됩니다.

Note

전환 그레고리력에서는 윤년이 4로 나누어떨어지고, 400으로 나누어떨어지거나 100으로 나누어떨어지지 않는 해입니다.

전환 그레고리력의 400년 주기에는 97번의 윤년이 있습니다. 평균적으로 연간 365.2425일, 즉 31,556,952,000 밀리초가 됩니다. 따라서 Number가 밀리초 단위로 정확하게 표현할 수 있는 최대 범위는 1970년 기준으로 약 -285,426년에서 285,426년입니다. 이 절에서 명시된 시간 값의 더 작은 범위는 약 -273,790년에서 273,790년(1970년 기준)입니다.

21.4.1.2 시간 관련 상수

이 상수들은 다음 섹션의 알고리즘에서 참조됩니다.

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 ( t )

The abstract operation Day takes argument t (유한시간 값) and returns 정수 Number. t가 속한 날짜의 일 번호(day number)를 반환합니다. It performs the following steps when called:

  1. 𝔽(floor((t / msPerDay)))를 반환합니다.

21.4.1.4 TimeWithinDay ( t )

The abstract operation TimeWithinDay takes argument t (유한시간 값) and returns +0𝔽 (포함)부터 msPerDay (제외)까지의 정수 Number. t가 속한 날짜의 시작부터 지난 밀리초 수를 반환합니다. It performs the following steps when called:

  1. 𝔽((t) modulo (msPerDay))를 반환합니다.

21.4.1.5 DaysInYear ( y )

The abstract operation DaysInYear takes argument y (정수 Number) and returns 365𝔽 또는 366𝔽. y년의 일(day) 수를 반환합니다. 윤년은 366일, 그 외는 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 (정수 Number) and returns 정수 Number. y년의 첫날의 일 번호(day number)를 반환합니다. It performs the following steps when called:

  1. ry(y)로 합니다.
  2. 다음 단계에서 numYears1, numYears4, numYears100, numYears400은 기점 이후 y년 시작까지 1, 4, 100, 400으로 나누어떨어지는 연도 수를 나타냅니다. y가 기점 이전이면 음수입니다.
  3. numYears1에 (ry - 1970)을 할당합니다.
  4. numYears4floor((ry - 1969) / 4)을 할당합니다.
  5. numYears100floor((ry - 1901) / 100)을 할당합니다.
  6. numYears400floor((ry - 1601) / 400)을 할당합니다.
  7. 𝔽(365 × numYears1 + numYears4 - numYears100 + numYears400)을 반환합니다.

21.4.1.7 TimeFromYear ( y )

The abstract operation TimeFromYear takes argument y (정수 Number) and returns 시간 값. y년의 시작 순간의 시간 값을 반환합니다. It performs the following steps when called:

  1. msPerDay × DayFromYear(y)를 반환합니다.

21.4.1.8 YearFromTime ( t )

The abstract operation YearFromTime takes argument t (유한시간 값) and returns 정수 Number. t가 속한 연도를 반환합니다. It performs the following steps when called:

  1. TimeFromYear(y) ≤ t를 만족하는 가장 큰 정수 y를 반환합니다 (+∞에 가장 가까움).

21.4.1.9 DayWithinYear ( t )

The abstract operation DayWithinYear takes argument t (유한시간 값) and returns +0𝔽부터 365𝔽까지 포함하는 구간의 정수 Number. It performs the following steps when called:

  1. Day(t) - DayFromYear(YearFromTime(t))을 반환합니다.

21.4.1.10 InLeapYear ( t )

The abstract operation InLeapYear takes argument t (유한시간 값) and returns +0𝔽 또는 1𝔽. t가 윤년 내에 있으면 1𝔽, 아니면 +0𝔽을 반환합니다. It performs the following steps when called:

  1. DaysInYear(YearFromTime(t))이 366𝔽이면 1𝔽을, 아니면 +0𝔽을 반환합니다.

21.4.1.11 MonthFromTime ( t )

The abstract operation MonthFromTime takes argument t (유한시간 값) and returns +0𝔽부터 11𝔽까지 포함하는 구간의 정수 Number. t가 속한 월(month)을 식별하는 Number를 반환합니다. +0𝔽은 1월, 1𝔽은 2월, … 11𝔽은 12월을 의미합니다. MonthFromTime(+0𝔽) = +0𝔽은 1970년 1월 1일 목요일에 해당합니다. It performs the following steps when called:

  1. inLeapYearInLeapYear(t)를 할당합니다.
  2. dayWithinYearDayWithinYear(t)를 할당합니다.
  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 ( t )

The abstract operation DateFromTime takes argument t (유한시간 값) and returns 1𝔽부터 31𝔽까지 포함하는 구간의 정수 Number. t가 속한 월의 날짜(day of month)를 반환합니다. It performs the following steps when called:

  1. inLeapYearInLeapYear(t)를 할당합니다.
  2. dayWithinYearDayWithinYear(t)를 할당합니다.
  3. monthMonthFromTime(t)를 할당합니다.
  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 ( t )

The abstract operation WeekDay takes argument t (유한시간 값) and returns +0𝔽부터 6𝔽까지 포함하는 구간의 정수 Number. t가 속한 요일(week day)을 식별하는 Number를 반환합니다. +0𝔽은 일요일, 1𝔽은 월요일, … 6𝔽은 토요일을 의미합니다. WeekDay(+0𝔽) = 4𝔽은 1970년 1월 1일 목요일에 해당합니다. It performs the following steps when called:

  1. 𝔽((Day(t) + 4𝔽) modulo 7)을 반환합니다.

21.4.1.14 HourFromTime ( t )

The abstract operation HourFromTime takes argument t (유한시간 값) and returns +0𝔽부터 23𝔽까지 포함하는 구간의 정수 Number. t가 속한 시(hour)를 반환합니다. It performs the following steps when called:

  1. 𝔽(floor((t / msPerHour)) modulo HoursPerDay)을 반환합니다.

21.4.1.15 MinFromTime ( t )

The abstract operation MinFromTime takes argument t (유한시간 값) and returns +0𝔽부터 59𝔽까지 포함하는 구간의 정수 Number. t가 속한 분(minute)을 반환합니다. It performs the following steps when called:

  1. 𝔽(floor((t / msPerMinute)) modulo MinutesPerHour)을 반환합니다.

21.4.1.16 SecFromTime ( t )

The abstract operation SecFromTime takes argument t (유한시간 값) and returns +0𝔽부터 59𝔽까지 포함하는 구간의 정수 Number. It performs the following steps when called:

  1. 𝔽(floor((t / msPerSecond)) modulo SecondsPerMinute)를 반환한다.

21.4.1.17 msFromTime ( t )

The abstract operation msFromTime takes argument t (유한시간 값) and returns +0𝔽부터 999𝔽까지 포함하는 구간의 정수 Number. It performs the following steps when called:

  1. 𝔽((t) modulo (msPerSecond))를 반환한다.

21.4.1.18 GetUTCEpochNanoseconds ( year, month, day, hour, minute, second, millisecond, microsecond, nanosecond )

The abstract operation GetUTCEpochNanoseconds takes arguments year (정수), month (1~12의 정수), day (1~31의 정수), hour (0~23의 정수), minute (0~59의 정수), second (0~59의 정수), millisecond (0~999의 정수), microsecond (0~999의 정수), and nanosecond (0~999의 정수) and returns BigInt. 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: ms는 정수 Number이다.
  5. ((ms) × 106 + microsecond × 103 + nanosecond)를 반환한다.

21.4.1.19 시간대 식별자

ECMAScript에서 시간대는 시간대 식별자로 표현되며, 이는 0x0000~0x007F의 코드 유닛으로만 구성된 문자열입니다. ECMAScript 구현이 지원하는 시간대는 사용 가능한 명명된 시간대일 수 있고, 이는 AvailableNamedTimeZoneIdentifiers가 반환하는 시간대 식별자 레코드[[Identifier]] 필드로 표현됩니다. 또는 오프셋 시간대일 수 있고, 이는 IsTimeZoneOffsetStringtrue를 반환하는 문자열로 표현됩니다.

기본 시간대 식별자는 사용 가능한 명명된 시간대의 대표 식별자입니다. 비기본 시간대 식별자는 명명된 시간대를 나타내지만 기본 식별자가 아닌 식별자입니다. 사용 가능한 명명된 시간대 식별자는 기본 또는 비기본 식별자입니다. 각 사용 가능한 명명된 시간대 식별자는 정확히 하나의 명명된 시간대와 연결됩니다. 각 명명된 시간대는 정확히 하나의 기본 시간대 식별자와 0개 이상의 비기본 식별자와 연결됩니다.

ECMAScript 구현은 "UTC" 식별자를 가진 명명된 시간대를 지원해야 하며, 이는 UTC 시간대의 기본 식별자여야 합니다. 추가로, 구현은 다른 명명된 시간대를 임의로 지원할 수 있습니다.

ECMA-402 국제화 API 명세의 시간대 요구 사항을 따르는 구현은 시간대 지원 구현(time zone aware)이라고 합니다. 시간대 지원 구현은 IANA Time Zone Database의 Zone 및 Link 이름에 해당하는 명명된 시간대를 지원해야 하며, 오직 그러한 이름만 지원해야 합니다. 시간대 지원 구현에서는 기본 식별자가 Zone 이름, 비기본 식별자가 Link 이름에 해당합니다(ECMA-402에서 특별히 재정의한 경우 제외). 전체 IANA Time Zone Database를 지원하지 않더라도 IANA 이름을 식별자로 사용하는 것이 권장됩니다.

21.4.1.20 GetNamedTimeZoneEpochNanoseconds ( timeZoneIdentifier, year, month, day, hour, minute, second, millisecond, microsecond, nanosecond )

The implementation-defined abstract operation GetNamedTimeZoneEpochNanoseconds takes arguments timeZoneIdentifier (문자열), year (정수), month (1~12의 정수), day (1~31의 정수), hour (0~23의 정수), minute (0~59의 정수), second (0~59의 정수), millisecond (0~999의 정수), microsecond (0~999의 정수), and nanosecond (0~999의 정수) and returns BigInt 리스트.

입력값이 음의 시간대 전환(예: 서머타임 종료나 시간대 오프셋 감소) 때문에 지역 시간이 두 번 발생하면, 반환 리스트에 두 개 이상의 요소가 들어가고 오름차순으로 정렬됩니다. 입력값이 양의 시간대 전환(예: 서머타임 시작이나 시간대 오프셋 증가) 때문에 지역 시간이 건너뛰어진 경우, 반환 리스트는 비어 있습니다. 그 외에는 반환 리스트에 하나의 요소가 들어갑니다.

지역 정치적 규칙이 없는 ECMAScript 구현에서 사용하는 GetNamedTimeZoneEpochNanoseconds 기본 구현은 다음과 같은 단계로 동작합니다:

  1. Assert: timeZoneIdentifier"UTC"임을 보장한다.
  2. epochNanosecondsGetUTCEpochNanoseconds(year, month, day, hour, minute, second, millisecond, microsecond, nanosecond)로 한다.
  3. « epochNanoseconds »를 반환한다.
Note

시간대 지원 구현(및 모든 구현에 권장됨)은 IANA Time Zone Database의 시간대 정보를 사용해야 합니다 https://www.iana.org/time-zones/.

2017년 11월 5일 America/New_York의 오전 1:30은 두 번 반복되므로, GetNamedTimeZoneEpochNanoseconds("America/New_York", 2017, 11, 5, 1, 30, 0, 0, 0, 0)은 길이 2인 리스트를 반환하며 첫 번째 요소는 05:30 UTC(미국 동부 일광절약시 UTC-04:00의 01:30)에, 두 번째 요소는 06:30 UTC(미국 동부 표준시 UTC-05:00의 01:30)에 해당합니다.

2017년 3월 12일 America/New_York의 오전 2:30은 존재하지 않으므로, GetNamedTimeZoneEpochNanoseconds("America/New_York", 2017, 3, 12, 2, 30, 0, 0, 0, 0)은 빈 리스트를 반환합니다.

21.4.1.21 GetNamedTimeZoneOffsetNanoseconds ( timeZoneIdentifier, epochNanoseconds )

The implementation-defined abstract operation GetNamedTimeZoneOffsetNanoseconds takes arguments timeZoneIdentifier (문자열) and epochNanoseconds (BigInt) and returns 정수.

반환되는 정수는 timeZoneIdentifier로 지정된 명명된 시간대에서, epochNanoseconds에 해당하는 순간의 UTC로부터의 오프셋(나노초 단위)을 나타냅니다.

지역 정치적 규칙이 없는 ECMAScript 구현에서 사용하는 기본 구현은 다음과 같이 동작합니다:

  1. Assert: timeZoneIdentifier"UTC"임을 보장한다.
  2. 0을 반환한다.
Note

시간대 오프셋 값은 양수일 수도 음수일 수도 있습니다.

21.4.1.22 시간대 식별자 레코드

시간대 식별자 레코드사용 가능한 명명된 시간대 식별자와 해당 기본 시간대 식별자를 설명하는 데 사용되는 레코드입니다.

시간대 식별자 레코드는 Table 62에 나열된 필드를 가집니다.

Table 62: 시간대 식별자 레코드 필드
필드 이름 의미
[[Identifier]] 문자열 구현에서 지원하는 사용 가능한 명명된 시간대 식별자입니다.
[[PrimaryIdentifier]] 문자열 [[Identifier]]가 resolve되는 기본 시간대 식별자입니다.
Note

[[Identifier]]기본 시간대 식별자라면, [[Identifier]][[PrimaryIdentifier]]입니다.

21.4.1.23 AvailableNamedTimeZoneIdentifiers ( )

The implementation-defined abstract operation AvailableNamedTimeZoneIdentifiers takes no arguments and returns 시간대 식별자 레코드 리스트.

ECMA-402 국제화 API를 구현하는 모든 시간대 지원 구현은 ECMA-402 명세에 따라 AvailableNamedTimeZoneIdentifiers 추상 연산을 구현해야 합니다. 시간대 지원하지 않는 구현에서는 다음과 같이 동작합니다:

  1. 구현에 지역 정치적 규칙이 없으면,
    1. « 시간대 식별자 레코드 { [[Identifier]]: "UTC", [[PrimaryIdentifier]]: "UTC" } »를 반환한다.
  2. identifiers를 고유한 사용 가능한 명명된 시간대 식별자 리스트(코드 유닛 사전순으로 정렬)로 한다.
  3. result를 새로운 빈 리스트로 한다.
  4. identifiers의 요소 identifier에 대해,
    1. primaryidentifier로 한다.
    2. identifier가 이 구현에서 비기본 시간대 식별자이고 "UTC"가 아니면,
      1. primaryidentifier와 연결된 기본 시간대 식별자로 설정한다.
      2. NOTE: 기본 식별자를 얻기 위해 identifier를 반복적으로 resolve해야 할 수도 있다.
    3. record시간대 식별자 레코드 { [[Identifier]]: identifier, [[PrimaryIdentifier]]: primary }로 한다.
    4. resultrecord를 추가한다.
  5. Assert: result[[Identifier]]"UTC"이고 [[PrimaryIdentifier]]"UTC"인 레코드 r가 포함됨을 보장한다.
  6. result를 반환한다.

21.4.1.24 SystemTimeZoneIdentifier ( )

The implementation-defined abstract operation SystemTimeZoneIdentifier takes no arguments and returns 문자열. It performs the following steps when called:

  1. 구현이 UTC 시간대만 지원하면 "UTC"를 반환한다.
  2. systemTimeZoneString호스트 환경의 현재 시간대를 나타내는 문자열(기본 시간대 식별자 또는 오프셋 시간대 식별자)로 한다.
  3. systemTimeZoneString을 반환한다.
Note

Date 객체의 메서드가 일반적으로 제공하는 기능 수준을 보장하려면, SystemTimeZoneIdentifier가 호스트 환경의 시간대 설정에 대응하는 IANA 시간대 이름을 반환하는 것이 권장됩니다(존재한다면). GetNamedTimeZoneEpochNanosecondsGetNamedTimeZoneOffsetNanoseconds는 해당 시간대의 표준시 및 서머타임에 대한 지역 정치적 규칙을 반영해야 합니다(존재한다면).

예를 들어, 호스트 환경이 미국 동부 시간대로 설정된 브라우저라면 SystemTimeZoneIdentifier는 "America/New_York"을 반환합니다.

21.4.1.25 LocalTime ( t )

The abstract operation LocalTime takes argument t (유한시간 값) and returns 정수 Number. It performs the following steps when called:

  1. systemTimeZoneIdentifierSystemTimeZoneIdentifier()로 한다.
  2. IsTimeZoneOffsetString(systemTimeZoneIdentifier)이 true이면
    1. offsetNsParseTimeZoneOffsetString(systemTimeZoneIdentifier)로 한다.
  3. 그렇지 않으면,
    1. offsetNsGetNamedTimeZoneOffsetNanoseconds(systemTimeZoneIdentifier, ((t) × 106))로 한다.
  4. offsetMstruncate(offsetNs / 106)로 한다.
  5. t + 𝔽(offsetMs)를 반환한다.
Note 1

구현에 지역 시간 t에 대한 정치적 규칙이 없으면, 결과는 t입니다. SystemTimeZoneIdentifier"UTC"이고 GetNamedTimeZoneOffsetNanoseconds가 0을 반환하기 때문입니다.

Note 2

시간대 지원 구현(및 모든 구현에 권장됨)은 IANA Time Zone Database의 시간대 정보를 사용해야 합니다 https://www.iana.org/time-zones/.

Note 3

음의 시간대 전환(예: 서머타임 종료나 시간대 조정 감소)으로 인해 지역 시간이 반복될 때 서로 다른 입력 시간 값 tUTC이 동일한 지역 시간 tlocal으로 변환될 수 있습니다.

LocalTime(UTC(tlocal))이 항상 tlocal과 같지 않을 수 있습니다. 이에 대응하여 UTC(LocalTime(tUTC)) 또한 항상 tUTC과 같지 않을 수 있습니다.

21.4.1.26 UTC ( t )

The abstract operation UTC takes argument t (Number) and returns 시간 값. It performs the following steps when called:

  1. t유한하지 않으면 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: 다음 단계는 t가 음의 시간대 전환(예: 서머타임 종료나 시간대 오프셋 감소)에서 지역 시간이 여러 번 반복되거나, 양의 시간대 전환(예: 서머타임 시작이나 시간대 오프셋 증가)에서 지역 시간이 건너뛰어진 경우에, 전환 직전의 시간대 오프셋을 사용해 t를 해석할 수 있도록 한다.
    3. possibleInstants가 비어 있지 않으면
      1. disambiguatedInstantpossibleInstants[0]로 한다.
    4. 그렇지 않으면,
      1. NOTE: t가 양의 시간대 전환에서 건너뛰어진 지역 시간을 나타낸다(예: 서머타임 시작이나 시간대 오프셋 증가).
      2. possibleInstantsBeforeGetNamedTimeZoneEpochNanoseconds(systemTimeZoneIdentifier, (YearFromTime(tBefore)), (MonthFromTime(tBefore)) + 1, (DateFromTime(tBefore)), (HourFromTime(tBefore)), (MinFromTime(tBefore)), (SecFromTime(tBefore)), (msFromTime(tBefore)), 0, 0)로 한다. 여기서 tBeforepossibleInstantsBefore가 비어 있지 않은 가장 큰 정수(< t)이다(즉, tBefore는 전환 직전의 마지막 지역 시간을 나타낸다).
      3. disambiguatedInstantpossibleInstantsBefore의 마지막 요소로 한다.
    5. offsetNsGetNamedTimeZoneOffsetNanoseconds(systemTimeZoneIdentifier, disambiguatedInstant)로 한다.
  5. offsetMstruncate(offsetNs / 106)로 한다.
  6. t - 𝔽(offsetMs)를 반환한다.

입력 t는 명목상 시간 값이지만, 어떤 Number 값도 될 수 있습니다. 알고리즘은 t시간 값 범위로 제한해서는 안 되며, 지역 UTC 오프셋에 관계없이 경계값에 해당하는 입력도 지원할 수 있어야 합니다. 예를 들어, 최대 시간 값은 8.64 × 1015으로 "+275760-09-13T00:00:00Z"에 대응합니다. 해당 순간의 지역 시간대 오프셋이 UTC보다 1시간 빠른 환경에서는, 입력값이 8.64 × 1015 + 3.6 × 106이 되고 이는 "+275760-09-13T01:00:00+01:00"에 해당합니다.

구현에 지역 시간 t에 대한 정치적 규칙이 없으면, 결과는 t입니다. SystemTimeZoneIdentifier"UTC"이고 GetNamedTimeZoneOffsetNanoseconds가 0을 반환하기 때문입니다.

Note 1

시간대 지원 구현(및 모든 구현에 권장됨)은 IANA Time Zone Database의 시간대 정보를 사용해야 합니다 https://www.iana.org/time-zones/.

2017년 11월 5일 America/New_York의 오전 1:30은 두 번 반복되지만, 반드시 1:30 AM UTC-04로 해석되어야 하며 1:30 AM UTC-05로 해석되어서는 안 됩니다. UTC(TimeClip(MakeDate(MakeDay(2017, 10, 5), MakeTime(1, 30, 0, 0))))에서 offsetMs 값은 -4 × msPerHour입니다.

2017년 3월 12일 America/New_York의 오전 2:30은 존재하지 않지만, 반드시 2:30 AM UTC-05(동일한 3:30 AM UTC-04와 동일)로 해석되어야 합니다. UTC(TimeClip(MakeDate(MakeDay(2017, 2, 12), MakeTime(2, 30, 0, 0))))에서 offsetMs 값은 -5 × msPerHour입니다.

Note 2

UTC(LocalTime(tUTC))이 항상 tUTC과 같지 않을 수 있습니다. 이에 대응하여 LocalTime(UTC(tlocal)) 또한 항상 tlocal과 같지 않을 수 있습니다.

21.4.1.27 MakeTime ( hour, min, sec, ms )

The abstract operation MakeTime takes arguments hour (Number), min (Number), sec (Number), and ms (Number) and returns Number. It performs the following steps when called:

  1. hour, min, sec, ms유한하지 않으면 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의 연산은 부동소수점 연산(floating-point arithmetic)으로, 결합법칙이 성립하지 않으므로 반드시 올바른 순서로 연산해야 합니다.

21.4.1.28 MakeDay ( year, month, date )

The abstract operation MakeDay takes arguments year (Number), month (Number), and date (Number) and returns Number. It performs the following steps when called:

  1. year, month, date유한하지 않으면 NaN을 반환한다.
  2. y𝔽(! ToIntegerOrInfinity(year))로 한다.
  3. m𝔽(! ToIntegerOrInfinity(month))로 한다.
  4. dt𝔽(! ToIntegerOrInfinity(date))로 한다.
  5. ymy + 𝔽(floor((m) / 12))로 한다.
  6. ym유한하지 않으면 NaN을 반환한다.
  7. mn𝔽((m) modulo 12)로 한다.
  8. YearFromTime(t)가 ym, MonthFromTime(t)가 mn, DateFromTime(t)가 1𝔽유한시간 값 t를 찾는다. 단, 찾을 수 없다면(인수가 범위 밖인 경우 등) NaN을 반환한다.
  9. Day(t) + dt - 1𝔽를 반환한다.

21.4.1.29 MakeDate ( day, time )

The abstract operation MakeDate takes arguments day (Number) and time (Number) and returns Number. It performs the following steps when called:

  1. day, time유한하지 않으면 NaN을 반환한다.
  2. tvday × msPerDay + time으로 한다.
  3. tv유한하지 않으면 NaN을 반환한다.
  4. tv를 반환한다.

21.4.1.30 MakeFullYear ( year )

The abstract operation MakeFullYear takes argument year (Number) and returns 정수 Number 또는 NaN. It performs the following steps when called:

  1. yearNaN이면 NaN을 반환한다.
  2. truncated를 ! ToIntegerOrInfinity(year)로 한다.
  3. truncated가 0~99 구간에 있으면 1900𝔽 + 𝔽(truncated)를 반환한다.
  4. 𝔽(truncated)를 반환한다.

21.4.1.31 TimeClip ( time )

The abstract operation TimeClip takes argument time (Number) and returns Number. It performs the following steps when called:

  1. time유한하지 않으면 NaN을 반환한다.
  2. abs((time)) > 8.64 × 1015이면 NaN을 반환한다.
  3. 𝔽(! ToIntegerOrInfinity(time))를 반환한다.

21.4.1.32 날짜-시간 문자열 형식

ECMAScript는 ISO 8601 달력 날짜 확장 형식을 단순화한 날짜-시간 문자열 교환 형식을 정의합니다. 형식은 다음과 같습니다: YYYY-MM-DDTHH:mm:ss.sssZ

각 요소의 의미는 다음과 같습니다:

YYYY 전환 그레고리력의 연도. 0000~9999의 4자리 십진수, 또는 확장 연도(expanded year)로서 "+" 또는 "-" 뒤에 6자리 십진수.
- "-" (하이픈)은 문자열에 두 번 그대로 나타납니다.
MM 연도의 월(month). 01(1월)~12(12월)까지 두 자리 십진수.
DD 월의 날짜(day). 01~31의 두 자리 십진수.
T "T"는 문자열에 그대로 나타나며, 시간 요소의 시작임을 나타냅니다.
HH 자정 이후 지난 전체 시간(hour) 수. 00~24의 두 자리 십진수.
: ":" (콜론)은 문자열에 두 번 그대로 나타납니다.
mm 시간(hour) 시작 이후 지난 전체 분(minute) 수. 00~59의 두 자리 십진수.
ss 분(minute) 시작 이후 지난 전체 초(second) 수. 00~59의 두 자리 십진수.
. "." (점)은 문자열에 그대로 나타납니다.
sss 초(second) 시작 이후 지난 전체 밀리초(millisecond) 수. 세 자리 십진수.
Z UTC 오프셋 표현. "Z" (오프셋 없는 UTC), 혹은 "+" 또는 "-" 뒤에 시간 표현 HH:mm (UTC 앞 또는 뒤의 지역 시간을 나타내는 시간대 오프셋 문자열 형식의 부분집합)

이 형식은 날짜만을 포함하는 형태도 지원합니다:

YYYY
YYYY-MM
YYYY-MM-DD
        

또한 위의 날짜만 형식 뒤에 다음 시간 형식이 바로 붙고 선택적 UTC 오프셋 표현이 뒤따르는 “날짜-시간” 형식도 지원합니다:

THH:mm
THH:mm:ss
THH:mm:ss.sss
        

형식에 맞지 않거나 범위를 벗어난 요소를 포함한 문자열은 이 형식의 유효한 인스턴스가 아닙니다.

Note 1

모든 날짜는 자정으로 시작하고 자정으로 끝나므로, 00:0024:00 표기법 모두 한 날짜에 연관된 두 자정을 구분할 수 있습니다. 즉, 1995-02-04T24:001995-02-05T00:00은 정확히 같은 시점을 의미합니다. 후자의 형식을 “달력 날짜의 끝”으로 해석하는 것은 ISO 8601과 일치합니다(이 명세는 시간 구간을 설명할 때만 이 표기를 허용하며 단일 시점 표현에는 허용하지 않음).

Note 2

CET, EST 등과 같은 민간 시간대 약어에 대한 국제 표준은 없으며, 약어가 서로 다른 두 시간대를 동시에 나타낼 수도 있습니다. 이런 이유로 ISO 8601과 이 형식 모두 시간대 오프셋을 숫자 표현으로 지정합니다.

21.4.1.32.1 확장 연도

1970년 1월 1일 기준 약 273,790년 전후의 전체 시간 값 범위를 나타내려면 0년 이전 또는 9999년 이후의 연도 표현이 필요합니다(21.4.1.1). ISO 8601은 연도 표현의 확장을 허용하지만, 정보 교환 당사자 간의 합의가 있을 때만 허용합니다. ECMAScript 단순화 형식에서는 확장 연도 표현이 6자리 숫자로 되어야 하며 항상 + 또는 - 기호가 붙습니다. 0년은 양수로 간주하고 반드시 + 기호를 붙여야 합니다. -000000 형식의 0년 표현은 유효하지 않습니다. 확장 연도가 시간 값 범위를 벗어나는 경우, 날짜-시간 문자열 형식과 일치하는 문자열이라도 Date.parse에서 인식되지 않으며, 해당 함수는 구현별 동작이나 휴리스틱 없이 NaN을 반환합니다.

Note

확장 연도가 포함된 날짜-시간 값 예시:

-271821-04-20T00:00:00Z 기원전 271822년
-000001-01-01T00:00:00Z 기원전 2년
+000000-01-01T00:00:00Z 기원전 1년
+000001-01-01T00:00:00Z 서기 1년
+001970-01-01T00:00:00Z 서기 1970년
+002009-12-15T00:00:00Z 서기 2009년
+275760-09-13T00:00:00Z 서기 275760년

21.4.1.33 시간대 오프셋 문자열 형식

ECMAScript는 ISO 8601에서 파생된 UTC 오프셋의 문자열 교환 형식을 정의합니다. 이 형식은 다음 문법으로 설명됩니다.

문법

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 (문자열) and returns 불리언(Boolean). It performs the following steps when called:

  1. parseResult를 ParseText(offsetString, UTCOffset)로 한다.
  2. parseResult가 오류 목록이면 false를 반환한다.
  3. true를 반환한다.

21.4.1.33.2 ParseTimeZoneOffsetString ( offsetString )

The abstract operation ParseTimeZoneOffsetString takes argument offsetString (문자열) and returns 정수. It performs the following steps when called:

  1. parseResult를 ParseText(offsetString, UTCOffset)로 한다.
  2. Assert: parseResult가 오류 목록이 아님을 보장한다.
  3. Assert: parseResultASCIISign Parse Node가 포함됨을 보장한다.
  4. parsedSignparseResult에 포함된 ASCIISign Parse Node가 일치시킨 소스 텍스트로 한다.
  5. parsedSign이 U+002D(하이픈) 단일 코드 포인트면
    1. sign을 -1로 한다.
  6. 그렇지 않으면
    1. sign을 1로 한다.
  7. NOTE: 아래 StringToNumber 이용 시 정밀도 손실 없음(파싱된 값은 충분히 짧은 십진수 문자열임이 보장됨).
  8. Assert: parseResultHour Parse Node가 포함됨을 보장한다.
  9. parsedHoursparseResult에 포함된 Hour Parse Node가 일치시킨 소스 텍스트로 한다.
  10. hours(StringToNumber(CodePointsToString(parsedHours)))로 한다.
  11. parseResultMinuteSecond Parse Node가 없으면
    1. minutes를 0으로 한다.
  12. 그렇지 않으면
    1. parsedMinutesparseResult에 포함된 첫 MinuteSecond Parse Node가 일치시킨 소스 텍스트로 한다.
    2. minutes(StringToNumber(CodePointsToString(parsedMinutes)))로 한다.
  13. parseResult에 두 번째 MinuteSecond Parse Node가 없으면
    1. seconds를 0으로 한다.
  14. 그렇지 않으면
    1. parsedSecondsparseResult에 포함된 두 번째 MinuteSecond Parse Node가 일치시킨 소스 텍스트로 한다.
    2. seconds(StringToNumber(CodePointsToString(parsedSeconds)))로 한다.
  15. parseResultTemporalDecimalFraction Parse Node가 없으면
    1. nanoseconds를 0으로 한다.
  16. 그렇지 않으면
    1. parsedFractionparseResult에 포함된 TemporalDecimalFraction Parse Node가 일치시킨 소스 텍스트로 한다.
    2. fraction을 CodePointsToString(parsedFraction)과 "000000000"을 이어붙인 문자열로 한다.
    3. nanosecondsStringfraction의 1~10번째 부분 문자열로 한다.
    4. nanoseconds(StringToNumber(nanosecondsString))로 한다.
  17. sign × (((hours × 60 + minutes) × 60 + seconds) × 109 + nanoseconds)를 반환한다.

21.4.2 Date 생성자

Date 생성자:

  • %Date%이다.
  • 전역 객체"Date" 프로퍼티의 초기값이다.
  • 생성자로 호출될 때 새로운 Date를 생성하고 초기화한다.
  • 생성자가 아닌 함수로 호출될 때 현재 시간(UTC)을 나타내는 문자열을 반환한다.
  • 인수의 개수와 타입에 따라 동작이 달라지는 함수이다.
  • 클래스 정의의 extends 절 값으로 사용할 수 있다. 지정된 Date 동작을 상속하려는 서브클래스 생성자[[DateValue]] 내부 슬롯을 가진 서브클래스 인스턴스를 생성 및 초기화하기 위해 반드시 Date 생성자로의 super 호출을 포함해야 한다.

21.4.2.1 Date ( ...values )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. NewTarget이 undefined이면
    1. now를 현재 시간(UTC)을 식별하는 시간 값으로 설정한다.
    2. ToDateString(now)을 반환한다.
  2. numberOfArgsvalues의 요소 개수로 설정한다.
  3. numberOfArgs = 0이면
    1. dv를 현재 시간(UTC)을 식별하는 시간 값으로 설정한다.
  4. 그렇지 않고 numberOfArgs = 1이면
    1. valuevalues[0]으로 설정한다.
    2. value가 객체이고 [[DateValue]] 내부 슬롯이 있으면
      1. tvvalue.[[DateValue]]로 설정한다.
    3. 그렇지 않으면
      1. v를 ? ToPrimitive(value)로 설정한다.
      2. v가 문자열이면
        1. 다음 단계에서 갑작스런 완료가 발생하지 않음을 단언한다(v는 문자열이므로).
        2. tvparse 메서드(21.4.3.2)와 동일한 방식으로 v를 날짜로 파싱한 결과로 설정한다.
      3. 그렇지 않으면
        1. tv를 ? ToNumber(v)로 설정한다.
    4. dvTimeClip(tv)로 설정한다.
  5. 그렇지 않으면
    1. 단언: 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. O를 ? OrdinaryCreateFromConstructor(NewTarget, "%Date.prototype%", « [[DateValue]] »)로 설정한다.
  7. O.[[DateValue]]dv를 설정한다.
  8. O를 반환한다.

21.4.3 Date 생성자의 프로퍼티

Date 생성자:

  • [[Prototype]] 내부 슬롯의 값이 %Function.prototype%이다.
  • "length" 프로퍼티의 값이 7𝔽이다.
  • 다음과 같은 프로퍼티를 가진다:

21.4.3.1 Date.now ( )

이 함수는 호출 시점의 UTC 날짜와 시간을 나타내는 시간 값을 반환한다.

21.4.3.2 Date.parse ( string )

이 함수는 인수에 ToString 연산자를 적용한다. ToString 결과가 갑작스런 완료라면 즉시 Completion Record를 반환한다. 그렇지 않으면, 이 함수는 결과 문자열을 날짜와 시간으로 해석하여 해당 날짜와 시간에 해당하는 UTC 시간 값을 Number로 반환한다. 문자열의 내용에 따라 지역 시간, UTC 시간, 또는 다른 시간대의 시간으로 해석될 수 있다. 함수는 먼저 Date Time String Format (21.4.1.32)에 설명된 형식(확장된 연도 포함)에 따라 문자열을 파싱하려 시도한다. 문자열이 해당 형식에 맞지 않으면 구현별 휴리스틱 또는 구현별 날짜 형식으로 대체할 수 있다. 인식 불가하거나 형식 요소 값이 범위를 벗어난 문자열은 이 함수가 NaN을 반환하게 한다.

문자열이 Date Time String Format에 맞는 경우, 대체 값이 없는 형식 요소에는 대체 값이 사용된다. MM 또는 DD 요소가 없으면 "01"이 사용된다. HH, mm, ss 요소가 없으면 "00"이 사용된다. sss 요소가 없으면 "000"이 사용된다. UTC 오프셋 표현이 없으면 날짜만 있는 형식은 UTC로, 날짜-시간 형식은 지역 시간으로 해석된다.

어떤 ECMAScript 구현에서 밀리초가 0인 Date x에 대해 다음 모든 표현식은 모든 관련 프로퍼티가 초기값일 때 동일한 숫자 값을 반환해야 한다:

x.valueOf()
Date.parse(x.toString())
Date.parse(x.toUTCString())
Date.parse(x.toISOString())

그러나 다음 표현식은

Date.parse(x.toLocaleString())

앞의 세 표현식과 동일한 Number 값을 반환할 필요는 없으며, 일반적으로 이 함수가 Date Time String Format (21.4.1.32)에 맞지 않고 해당 구현에서 toString 또는 toUTCString 메서드로 생성할 수 없는 문자열 값을 받으면 반환 값은 구현에 따라 달라진다.

21.4.3.3 Date.prototype

Date.prototype의 초기값은 Date 프로토타입 객체이다.

이 프로퍼티의 속성은 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }이다.

21.4.3.4 Date.UTC ( year [ , month [ , date [ , hours [ , minutes [ , seconds [ , ms ] ] ] ] ] ] )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. y를 ? ToNumber(year)로 설정한다.
  2. month가 있으면 m를 ? ToNumber(month)로, 아니면 m+0𝔽로 설정한다.
  3. date가 있으면 dt를 ? ToNumber(date)로, 아니면 dt1𝔽로 설정한다.
  4. hours가 있으면 h를 ? ToNumber(hours)로, 아니면 h+0𝔽로 설정한다.
  5. minutes가 있으면 min을 ? ToNumber(minutes)로, 아니면 min+0𝔽로 설정한다.
  6. seconds가 있으면 s를 ? ToNumber(seconds)로, 아니면 s+0𝔽로 설정한다.
  7. ms가 있으면 milli를 ? ToNumber(ms)로, 아니면 milli+0𝔽로 설정한다.
  8. yrMakeFullYear(y)로 설정한다.
  9. TimeClip(MakeDate(MakeDay(yr, m, dt), MakeTime(h, min, s, milli)))를 반환한다.

이 함수의 "length" 프로퍼티 값은 7𝔽이다.

Note

이 함수는 Date 생성자와 두 가지 차이가 있다: Date를 생성하는 대신 시간 값을 Number로 반환하며, 인수를 지역 시간 대신 UTC로 해석한다.

21.4.4 Date 프로토타입 객체의 프로퍼티

Date 프로토타입 객체:

  • %Date.prototype%이다.
  • 자체적으로 일반 객체이다.
  • Date 인스턴스가 아니며 [[DateValue]] 내부 슬롯을 가지지 않는다.
  • [[Prototype]] 내부 슬롯 값이 %Object.prototype%이다.

명시적으로 정의된 경우를 제외하고, 아래에 정의된 Date 프로토타입 객체의 메서드는 제네릭하지 않으며, this 값은 반드시 시간 값으로 초기화된 [[DateValue]] 내부 슬롯을 가진 객체여야 한다.

21.4.4.1 Date.prototype.constructor

Date.prototype.constructor의 초기값은 %Date%이다.

21.4.4.2 Date.prototype.getDate ( )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. dateObjectthis 값으로 설정한다.
  2. RequireInternalSlot(dateObject, [[DateValue]])를 수행한다.
  3. tdateObject.[[DateValue]]로 설정한다.
  4. tNaN이면 NaN을 반환한다.
  5. DateFromTime(LocalTime(t))을 반환한다.

21.4.4.3 Date.prototype.getDay ( )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. dateObjectthis 값으로 설정한다.
  2. RequireInternalSlot(dateObject, [[DateValue]])를 수행한다.
  3. tdateObject.[[DateValue]]로 설정한다.
  4. tNaN이면 NaN을 반환한다.
  5. WeekDay(LocalTime(t))을 반환한다.

21.4.4.4 Date.prototype.getFullYear ( )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. dateObjectthis 값으로 설정한다.
  2. RequireInternalSlot(dateObject, [[DateValue]])를 수행한다.
  3. tdateObject.[[DateValue]]로 설정한다.
  4. tNaN이면 NaN을 반환한다.
  5. YearFromTime(LocalTime(t))을 반환한다.

21.4.4.5 Date.prototype.getHours ( )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. dateObjectthis 값으로 설정한다.
  2. RequireInternalSlot(dateObject, [[DateValue]])를 수행한다.
  3. tdateObject.[[DateValue]]로 설정한다.
  4. tNaN이면 NaN을 반환한다.
  5. HourFromTime(LocalTime(t))을 반환한다.

21.4.4.6 Date.prototype.getMilliseconds ( )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. dateObjectthis 값으로 설정한다.
  2. RequireInternalSlot(dateObject, [[DateValue]])를 수행한다.
  3. tdateObject.[[DateValue]]로 설정한다.
  4. tNaN이면 NaN을 반환한다.
  5. msFromTime(LocalTime(t))을 반환한다.

21.4.4.7 Date.prototype.getMinutes ( )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. dateObjectthis 값으로 설정한다.
  2. RequireInternalSlot(dateObject, [[DateValue]])를 수행한다.
  3. tdateObject.[[DateValue]]로 설정한다.
  4. tNaN이면 NaN을 반환한다.
  5. MinFromTime(LocalTime(t))을 반환한다.

21.4.4.8 Date.prototype.getMonth ( )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. dateObjectthis 값으로 설정한다.
  2. RequireInternalSlot(dateObject, [[DateValue]])를 수행한다.
  3. tdateObject.[[DateValue]]로 설정한다.
  4. tNaN이면 NaN을 반환한다.
  5. MonthFromTime(LocalTime(t))을 반환한다.

21.4.4.9 Date.prototype.getSeconds ( )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. dateObjectthis 값으로 설정한다.
  2. RequireInternalSlot(dateObject, [[DateValue]])를 수행한다.
  3. tdateObject.[[DateValue]]로 설정한다.
  4. tNaN이면 NaN을 반환한다.
  5. SecFromTime(LocalTime(t))을 반환한다.

21.4.4.10 Date.prototype.getTime ( )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. dateObjectthis 값으로 설정한다.
  2. RequireInternalSlot(dateObject, [[DateValue]])를 수행한다.
  3. dateObject.[[DateValue]]를 반환한다.

21.4.4.11 Date.prototype.getTimezoneOffset ( )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. dateObjectthis 값으로 설정한다.
  2. RequireInternalSlot(dateObject, [[DateValue]])를 수행한다.
  3. tdateObject.[[DateValue]]로 설정한다.
  4. tNaN이면 NaN을 반환한다.
  5. (t - LocalTime(t)) / msPerMinute를 반환한다.

21.4.4.12 Date.prototype.getUTCDate ( )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. dateObjectthis 값으로 설정한다.
  2. RequireInternalSlot(dateObject, [[DateValue]])를 수행한다.
  3. tdateObject.[[DateValue]]로 설정한다.
  4. tNaN이면 NaN을 반환한다.
  5. DateFromTime(t)를 반환한다.

21.4.4.13 Date.prototype.getUTCDay ( )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. dateObjectthis 값으로 설정한다.
  2. RequireInternalSlot(dateObject, [[DateValue]])를 수행한다.
  3. tdateObject.[[DateValue]]로 설정한다.
  4. tNaN이면 NaN을 반환한다.
  5. WeekDay(t)를 반환한다.

21.4.4.14 Date.prototype.getUTCFullYear ( )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. dateObjectthis 값으로 설정한다.
  2. RequireInternalSlot(dateObject, [[DateValue]])를 수행한다.
  3. tdateObject.[[DateValue]]로 설정한다.
  4. tNaN이면 NaN을 반환한다.
  5. YearFromTime(t)를 반환한다.

21.4.4.15 Date.prototype.getUTCHours ( )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. dateObjectthis 값으로 설정한다.
  2. RequireInternalSlot(dateObject, [[DateValue]])를 수행한다.
  3. tdateObject.[[DateValue]]로 설정한다.
  4. tNaN이면 NaN을 반환한다.
  5. HourFromTime(t)를 반환한다.

21.4.4.16 Date.prototype.getUTCMilliseconds ( )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. dateObjectthis 값으로 설정한다.
  2. RequireInternalSlot(dateObject, [[DateValue]])를 수행한다.
  3. tdateObject.[[DateValue]]로 설정한다.
  4. tNaN이면 NaN을 반환한다.
  5. msFromTime(t)를 반환한다.

21.4.4.17 Date.prototype.getUTCMinutes ( )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. dateObjectthis 값으로 설정한다.
  2. RequireInternalSlot(dateObject, [[DateValue]])를 수행한다.
  3. tdateObject.[[DateValue]]로 설정한다.
  4. tNaN이면 NaN을 반환한다.
  5. MinFromTime(t)를 반환한다.

21.4.4.18 Date.prototype.getUTCMonth ( )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. dateObjectthis 값으로 설정한다.
  2. RequireInternalSlot(dateObject, [[DateValue]])를 수행한다.
  3. tdateObject.[[DateValue]]로 설정한다.
  4. tNaN이면 NaN을 반환한다.
  5. MonthFromTime(t)를 반환한다.

21.4.4.19 Date.prototype.getUTCSeconds ( )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. dateObjectthis 값으로 설정한다.
  2. RequireInternalSlot(dateObject, [[DateValue]])를 수행한다.
  3. tdateObject.[[DateValue]]로 설정한다.
  4. tNaN이면 NaN을 반환한다.
  5. SecFromTime(t)를 반환한다.

21.4.4.20 Date.prototype.setDate ( date )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. dateObjectthis 값으로 설정한다.
  2. RequireInternalSlot(dateObject, [[DateValue]])를 수행한다.
  3. tdateObject.[[DateValue]]로 설정한다.
  4. dt를 ? ToNumber(date)로 설정한다.
  5. tNaN이면 NaN을 반환한다.
  6. tLocalTime(t)로 설정한다.
  7. newDateMakeDate(MakeDay(YearFromTime(t), MonthFromTime(t), dt), TimeWithinDay(t))로 설정한다.
  8. uTimeClip(UTC(newDate))로 설정한다.
  9. dateObject.[[DateValue]]u를 설정한다.
  10. u를 반환한다.

21.4.4.21 Date.prototype.setFullYear ( year [ , month [ , date ] ] )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. dateObjectthis 값으로 설정한다.
  2. RequireInternalSlot(dateObject, [[DateValue]])를 수행한다.
  3. tdateObject.[[DateValue]]로 설정한다.
  4. y를 ? ToNumber(year)로 설정한다.
  5. tNaN이면 t+0𝔽로 설정하고; 아니면 tLocalTime(t)로 설정한다.
  6. month가 없으면 mMonthFromTime(t)로 설정하고; 있으면 m를 ? ToNumber(month)로 설정한다.
  7. date가 없으면 dtDateFromTime(t)로 설정하고; 있으면 dt를 ? ToNumber(date)로 설정한다.
  8. newDateMakeDate(MakeDay(y, m, dt), TimeWithinDay(t))로 설정한다.
  9. uTimeClip(UTC(newDate))로 설정한다.
  10. dateObject.[[DateValue]]u를 설정한다.
  11. u를 반환한다.

이 메서드의 "length" 프로퍼티는 3𝔽이다.

Note

month가 없으면 이 메서드는 getMonth() 값이 있는 것처럼 동작한다. date가 없으면 getDate() 값이 있는 것처럼 동작한다.

21.4.4.22 Date.prototype.setHours ( hour [ , min [ , sec [ , ms ] ] ] )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. dateObjectthis 값으로 설정한다.
  2. RequireInternalSlot(dateObject, [[DateValue]])를 수행한다.
  3. tdateObject.[[DateValue]]로 설정한다.
  4. h를 ? ToNumber(hour)로 설정한다.
  5. min이 있으면 m를 ? ToNumber(min)로 설정한다.
  6. sec이 있으면 s를 ? ToNumber(sec)로 설정한다.
  7. ms가 있으면 milli를 ? ToNumber(ms)로 설정한다.
  8. tNaN이면 NaN을 반환한다.
  9. tLocalTime(t)로 설정한다.
  10. min이 없으면 mMinFromTime(t)로 설정한다.
  11. sec이 없으면 sSecFromTime(t)로 설정한다.
  12. ms가 없으면 millimsFromTime(t)로 설정한다.
  13. dateMakeDate(Day(t), MakeTime(h, m, s, milli))로 설정한다.
  14. uTimeClip(UTC(date))로 설정한다.
  15. dateObject.[[DateValue]]u를 설정한다.
  16. u를 반환한다.

이 메서드의 "length" 프로퍼티는 4𝔽이다.

Note

min이 없으면 getMinutes() 값이 있는 것처럼 동작한다. sec이 없으면 getSeconds() 값이 있는 것처럼, ms가 없으면 getMilliseconds() 값이 있는 것처럼 동작한다.

21.4.4.23 Date.prototype.setMilliseconds ( ms )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. dateObjectthis 값으로 설정한다.
  2. RequireInternalSlot(dateObject, [[DateValue]])를 수행한다.
  3. tdateObject.[[DateValue]]로 설정한다.
  4. ms를 ? ToNumber(ms)로 설정한다.
  5. tNaN이면 NaN을 반환한다.
  6. tLocalTime(t)로 설정한다.
  7. timeMakeTime(HourFromTime(t), MinFromTime(t), SecFromTime(t), ms)로 설정한다.
  8. uTimeClip(UTC(MakeDate(Day(t), time)))로 설정한다.
  9. dateObject.[[DateValue]]u를 설정한다.
  10. u를 반환한다.

21.4.4.24 Date.prototype.setMinutes ( min [ , sec [ , ms ] ] )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. dateObjectthis 값으로 설정한다.
  2. RequireInternalSlot(dateObject, [[DateValue]])를 수행한다.
  3. tdateObject.[[DateValue]]로 설정한다.
  4. m를 ? ToNumber(min)로 설정한다.
  5. sec이 있으면 s를 ? ToNumber(sec)로 설정한다.
  6. ms가 있으면 milli를 ? ToNumber(ms)로 설정한다.
  7. tNaN이면 NaN을 반환한다.
  8. tLocalTime(t)로 설정한다.
  9. sec이 없으면 sSecFromTime(t)로 설정한다.
  10. ms가 없으면 millimsFromTime(t)로 설정한다.
  11. dateMakeDate(Day(t), MakeTime(HourFromTime(t), m, s, milli))로 설정한다.
  12. uTimeClip(UTC(date))로 설정한다.
  13. dateObject.[[DateValue]]u를 설정한다.
  14. u를 반환한다.

이 메서드의 "length" 프로퍼티는 3𝔽이다.

Note

sec이 없으면 getSeconds() 값이 있는 것처럼, ms가 없으면 getMilliseconds() 값이 있는 것처럼 동작한다.

21.4.4.25 Date.prototype.setMonth ( month [ , date ] )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. dateObjectthis 값으로 설정한다.
  2. RequireInternalSlot(dateObject, [[DateValue]])를 수행한다.
  3. tdateObject.[[DateValue]]로 설정한다.
  4. m를 ? ToNumber(month)로 설정한다.
  5. date가 있으면 dt를 ? ToNumber(date)로 설정한다.
  6. tNaN이면 NaN을 반환한다.
  7. tLocalTime(t)로 설정한다.
  8. date가 없으면 dtDateFromTime(t)로 설정한다.
  9. newDateMakeDate(MakeDay(YearFromTime(t), m, dt), TimeWithinDay(t))로 설정한다.
  10. uTimeClip(UTC(newDate))로 설정한다.
  11. dateObject.[[DateValue]]u를 설정한다.
  12. u를 반환한다.

이 메서드의 "length" 프로퍼티는 2𝔽이다.

Note

date가 없으면 getDate() 값이 있는 것처럼 동작한다.

21.4.4.26 Date.prototype.setSeconds ( sec [ , ms ] )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. dateObjectthis 값으로 설정한다.
  2. RequireInternalSlot(dateObject, [[DateValue]])를 수행한다.
  3. tdateObject.[[DateValue]]로 설정한다.
  4. s를 ? ToNumber(sec)로 설정한다.
  5. ms가 있으면 milli를 ? ToNumber(ms)로 설정한다.
  6. tNaN이면 NaN을 반환한다.
  7. tLocalTime(t)로 설정한다.
  8. ms가 없으면 millimsFromTime(t)로 설정한다.
  9. dateMakeDate(Day(t), MakeTime(HourFromTime(t), MinFromTime(t), s, milli))로 설정한다.
  10. uTimeClip(UTC(date))로 설정한다.
  11. dateObject.[[DateValue]]u를 설정한다.
  12. u를 반환한다.

이 메서드의 "length" 프로퍼티는 2𝔽이다.

Note

ms가 없으면 getMilliseconds() 값이 있는 것처럼 동작한다.

21.4.4.27 Date.prototype.setTime ( time )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. dateObjectthis 값으로 설정한다.
  2. RequireInternalSlot(dateObject, [[DateValue]])를 수행한다.
  3. t를 ? ToNumber(time)로 설정한다.
  4. vTimeClip(t)로 설정한다.
  5. dateObject.[[DateValue]]v를 설정한다.
  6. v를 반환한다.

21.4.4.28 Date.prototype.setUTCDate ( date )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. dateObjectthis 값으로 설정한다.
  2. RequireInternalSlot(dateObject, [[DateValue]])를 수행한다.
  3. tdateObject.[[DateValue]]로 설정한다.
  4. dt를 ? ToNumber(date)로 설정한다.
  5. tNaN이면 NaN을 반환한다.
  6. newDateMakeDate(MakeDay(YearFromTime(t), MonthFromTime(t), dt), TimeWithinDay(t))로 설정한다.
  7. vTimeClip(newDate)로 설정한다.
  8. dateObject.[[DateValue]]v를 설정한다.
  9. v를 반환한다.

21.4.4.29 Date.prototype.setUTCFullYear ( year [ , month [ , date ] ] )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. dateObjectthis 값으로 설정한다.
  2. RequireInternalSlot(dateObject, [[DateValue]])를 수행한다.
  3. tdateObject.[[DateValue]]로 설정한다.
  4. tNaN이면 t+0𝔽로 설정한다.
  5. y를 ? ToNumber(year)로 설정한다.
  6. month가 없으면 mMonthFromTime(t)로 설정하고; 있으면 m를 ? ToNumber(month)로 설정한다.
  7. date가 없으면 dtDateFromTime(t)로 설정하고; 있으면 dt를 ? ToNumber(date)로 설정한다.
  8. newDateMakeDate(MakeDay(y, m, dt), TimeWithinDay(t))로 설정한다.
  9. vTimeClip(newDate)로 설정한다.
  10. dateObject.[[DateValue]]v를 설정한다.
  11. v를 반환한다.

이 메서드의 "length" 프로퍼티는 3𝔽이다.

Note

month가 없으면 getUTCMonth() 값이 있는 것처럼, date가 없으면 getUTCDate() 값이 있는 것처럼 동작한다.

21.4.4.30 Date.prototype.setUTCHours ( hour [ , min [ , sec [ , ms ] ] ] )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. dateObjectthis 값으로 설정한다.
  2. RequireInternalSlot(dateObject, [[DateValue]])를 수행한다.
  3. tdateObject.[[DateValue]]로 설정한다.
  4. h를 ? ToNumber(hour)로 설정한다.
  5. min이 있으면 m를 ? ToNumber(min)로 설정한다.
  6. sec이 있으면 s를 ? ToNumber(sec)로 설정한다.
  7. ms가 있으면 milli를 ? ToNumber(ms)로 설정한다.
  8. tNaN이면 NaN을 반환한다.
  9. min이 없으면 mMinFromTime(t)로 설정한다.
  10. sec이 없으면 sSecFromTime(t)로 설정한다.
  11. ms가 없으면 millimsFromTime(t)로 설정한다.
  12. dateMakeDate(Day(t), MakeTime(h, m, s, milli))로 설정한다.
  13. vTimeClip(date)로 설정한다.
  14. dateObject.[[DateValue]]v를 설정한다.
  15. v를 반환한다.

이 메서드의 "length" 프로퍼티는 4𝔽이다.

Note

min이 없으면 getUTCMinutes() 값이 있는 것처럼, sec이 없으면 getUTCSeconds() 값이 있는 것처럼, ms가 없으면 getUTCMilliseconds() 값이 있는 것처럼 동작한다.

21.4.4.31 Date.prototype.setUTCMilliseconds ( ms )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. dateObjectthis 값으로 설정한다.
  2. RequireInternalSlot(dateObject, [[DateValue]])를 수행한다.
  3. tdateObject.[[DateValue]]로 설정한다.
  4. ms를 ? ToNumber(ms)로 설정한다.
  5. tNaN이면 NaN을 반환한다.
  6. timeMakeTime(HourFromTime(t), MinFromTime(t), SecFromTime(t), ms)로 설정한다.
  7. vTimeClip(MakeDate(Day(t), time))로 설정한다.
  8. dateObject.[[DateValue]]v를 설정한다.
  9. v를 반환한다.

21.4.4.32 Date.prototype.setUTCMinutes ( min [ , sec [ , ms ] ] )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. dateObjectthis 값으로 설정한다.
  2. RequireInternalSlot(dateObject, [[DateValue]])를 수행한다.
  3. tdateObject.[[DateValue]]로 설정한다.
  4. m를 ? ToNumber(min)로 설정한다.
  5. sec이 있으면 s를 ? ToNumber(sec)로 설정한다.
  6. ms가 있으면 milli를 ? ToNumber(ms)로 설정한다.
  7. tNaN이면 NaN을 반환한다.
  8. sec이 없으면 sSecFromTime(t)로 설정한다.
  9. ms가 없으면 millimsFromTime(t)로 설정한다.
  10. dateMakeDate(Day(t), MakeTime(HourFromTime(t), m, s, milli))로 설정한다.
  11. vTimeClip(date)로 설정한다.
  12. dateObject.[[DateValue]]v를 설정한다.
  13. v를 반환한다.

이 메서드의 "length" 프로퍼티는 3𝔽이다.

Note

sec이 없으면 getUTCSeconds() 값이 있는 것처럼, ms가 없으면 getUTCMilliseconds() 값이 있는 것처럼 동작한다.

21.4.4.33 Date.prototype.setUTCMonth ( month [ , date ] )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. dateObjectthis 값으로 설정한다.
  2. RequireInternalSlot(dateObject, [[DateValue]])를 수행한다.
  3. tdateObject.[[DateValue]]로 설정한다.
  4. m를 ? ToNumber(month)로 설정한다.
  5. date가 있으면 dt를 ? ToNumber(date)로 설정한다.
  6. tNaN이면 NaN을 반환한다.
  7. date가 없으면 dtDateFromTime(t)로 설정한다.
  8. newDateMakeDate(MakeDay(YearFromTime(t), m, dt), TimeWithinDay(t))로 설정한다.
  9. vTimeClip(newDate)로 설정한다.
  10. dateObject.[[DateValue]]v를 설정한다.
  11. v를 반환한다.

이 메서드의 "length" 프로퍼티는 2𝔽이다.

Note

date가 없으면 getUTCDate() 값이 있는 것처럼 동작한다.

21.4.4.34 Date.prototype.setUTCSeconds ( sec [ , ms ] )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. dateObjectthis 값으로 설정한다.
  2. RequireInternalSlot(dateObject, [[DateValue]])를 수행한다.
  3. tdateObject.[[DateValue]]로 설정한다.
  4. s를 ? ToNumber(sec)로 설정한다.
  5. ms가 있으면 milli를 ? ToNumber(ms)로 설정한다.
  6. tNaN이면 NaN을 반환한다.
  7. ms가 없으면 millimsFromTime(t)로 설정한다.
  8. dateMakeDate(Day(t), MakeTime(HourFromTime(t), MinFromTime(t), s, milli))로 설정한다.
  9. vTimeClip(date)로 설정한다.
  10. dateObject.[[DateValue]]v를 설정한다.
  11. v를 반환한다.

이 메서드의 "length" 프로퍼티는 2𝔽이다.

Note

ms가 없으면 getUTCMilliseconds() 값이 있는 것처럼 동작한다.

21.4.4.35 Date.prototype.toDateString ( )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. dateObjectthis 값으로 설정한다.
  2. RequireInternalSlot(dateObject, [[DateValue]])를 수행한다.
  3. tvdateObject.[[DateValue]]로 설정한다.
  4. tvNaN이면 "Invalid Date"를 반환한다.
  5. tLocalTime(tv)로 설정한다.
  6. DateString(t)을 반환한다.

21.4.4.36 Date.prototype.toISOString ( )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. dateObjectthis 값으로 설정한다.
  2. RequireInternalSlot(dateObject, [[DateValue]])를 수행한다.
  3. tvdateObject.[[DateValue]]로 설정한다.
  4. tvNaN이면 RangeError 예외를 throw 한다.
  5. 단언: tv는 정수 Number이다.
  6. tvDate Time String Format에서 표현할 수 없는 연도라면 RangeError 예외를 throw 한다.
  7. tvDate Time String Format의 UTC 타임스케일로 모든 형식 요소와 UTC 오프셋 표현 "Z"를 포함한 문자열로 반환한다.

21.4.4.37 Date.prototype.toJSON ( key )

이 메서드는 JSON.stringify(25.5.2)에서 사용할 Date의 문자열 표현을 제공한다.

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. O를 ? ToObject(this 값)으로 설정한다.
  2. tv를 ? ToPrimitive(O, number)로 설정한다.
  3. tv가 Number이고 유한하지 않으면 null을 반환한다.
  4. Invoke(O, "toISOString")을 반환한다.
Note 1

인수는 무시된다.

Note 2

이 메서드는 일부러 제네릭이다; this 값이 Date일 필요는 없다. 따라서 다른 종류의 객체로 이전해 메서드로 사용할 수 있다. 단, 해당 객체는 반드시 toISOString 메서드를 가지고 있어야 한다.

21.4.4.38 Date.prototype.toLocaleDateString ( [ reserved1 [ , reserved2 ] ] )

ECMA-402 국제화 API를 포함하는 ECMAScript 구현은 ECMA-402 명세에 따라 이 메서드를 구현해야 한다. ECMA-402 API를 포함하지 않는 ECMAScript 구현에서는 다음 명세에 따른다:

이 메서드는 문자열 값을 반환한다. 문자열 내용은 구현 정의이지만, 현재 시간대의 Date의 “날짜” 부분을 편리하고 사람이 읽기 쉬운 형태로, 호스트 환경의 현재 로캘 관습에 맞게 나타내야 한다.

이 메서드의 선택적 매개변수 의미는 ECMA-402 명세에 정의되어 있다. ECMA-402를 지원하지 않는 구현에서는 해당 위치에 다른 용도를 사용하면 안 된다.

21.4.4.39 Date.prototype.toLocaleString ( [ reserved1 [ , reserved2 ] ] )

ECMA-402 국제화 API를 포함하는 ECMAScript 구현은 ECMA-402 명세에 따라 이 메서드를 구현해야 한다. ECMA-402 API를 포함하지 않는 ECMAScript 구현에서는 다음 명세에 따른다:

이 메서드는 문자열 값을 반환한다. 문자열 내용은 구현 정의이지만, 현재 시간대의 Date를 편리하고 사람이 읽기 쉬운 형태로, 호스트 환경의 현재 로캘 관습에 맞게 나타내야 한다.

이 메서드의 선택적 매개변수 의미는 ECMA-402 명세에 정의되어 있다. ECMA-402를 지원하지 않는 구현에서는 해당 위치에 다른 용도를 사용하면 안 된다.

21.4.4.40 Date.prototype.toLocaleTimeString ( [ reserved1 [ , reserved2 ] ] )

ECMA-402 국제화 API를 포함하는 ECMAScript 구현은 ECMA-402 명세에 따라 이 메서드를 구현해야 한다. ECMA-402 API를 포함하지 않는 ECMAScript 구현에서는 다음 명세에 따른다:

이 메서드는 문자열 값을 반환한다. 문자열 내용은 구현 정의이지만, 현재 시간대의 Date의 “시간” 부분을 편리하고 사람이 읽기 쉬운 형태로, 호스트 환경의 현재 로캘 관습에 맞게 나타내야 한다.

이 메서드의 선택적 매개변수 의미는 ECMA-402 명세에 정의되어 있다. ECMA-402를 지원하지 않는 구현에서는 해당 위치에 다른 용도를 사용하면 안 된다.

21.4.4.41 Date.prototype.toString ( )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. dateObjectthis 값으로 설정한다.
  2. RequireInternalSlot(dateObject, [[DateValue]])를 수행한다.
  3. tvdateObject.[[DateValue]]로 설정한다.
  4. ToDateString(tv)을 반환한다.
Note 1

어떤 Date d에서 d.[[DateValue]]가 1000으로 나누어 떨어진다면, Date.parse(d.toString())의 결과는 d.valueOf()와 같다. 21.4.3.2 참조.

Note 2

이 메서드는 제네릭하지 않다; this 값이 Date가 아니면 TypeError 예외를 throw 한다. 따라서 다른 객체로 이전해 메서드로 사용할 수 없다.

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, 코드 유닛 0x0020(공백), "GMT"를 차례로 연결한 문자열을 반환한다.

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. weekdayTable 63에서 Number WeekDay(tv)에 해당하는 Name으로 설정한다.
  2. monthTable 64에서 Number MonthFromTime(tv)에 해당하는 Name으로 설정한다.
  3. dayToZeroPaddedDecimalString((DateFromTime(tv)), 2)로 설정한다.
  4. yvYearFromTime(tv)로 설정한다.
  5. yv+0𝔽이거나 yv > +0𝔽이면 yearSign을 빈 문자열로, 아니면 yearSign"-"로 설정한다.
  6. paddedYearToZeroPaddedDecimalString(abs((yv)), 4)로 설정한다.
  7. weekday, 코드 유닛 0x0020(공백), month, 코드 유닛 0x0020(공백), day, 코드 유닛 0x0020(공백), yearSign, paddedYear를 차례로 연결한 문자열을 반환한다.
Table 63: Names of days of the week
Number Name
+0𝔽 "Sun"
1𝔽 "Mon"
2𝔽 "Tue"
3𝔽 "Wed"
4𝔽 "Thu"
5𝔽 "Fri"
6𝔽 "Sat"
Table 64: 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구현 정의 문자열(빈 문자열 또는 코드 유닛 0x0020(공백), 0x0028(왼쪽 괄호), 구현 정의 타임존 이름, 0x0029(오른쪽 괄호) 연결)로 설정한다.
  10. offsetSign, offsetHour, offsetMin, tzName을 차례로 연결한 문자열을 반환한다.

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. tLocalTime(tv)로 설정한다.
  3. DateString(t), 코드 유닛 0x0020(공백), TimeString(t), TimeZoneString(tv)를 차례로 연결한 문자열을 반환한다.

21.4.4.42 Date.prototype.toTimeString ( )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. dateObjectthis 값으로 설정한다.
  2. RequireInternalSlot(dateObject, [[DateValue]])를 수행한다.
  3. tvdateObject.[[DateValue]]로 설정한다.
  4. tvNaN이면 "Invalid Date"를 반환한다.
  5. tLocalTime(tv)로 설정한다.
  6. TimeString(t), TimeZoneString(tv)를 차례로 연결한 문자열을 반환한다.

21.4.4.43 Date.prototype.toUTCString ( )

이 메서드는 this 값에 해당하는 순간을 나타내는 문자열 값을 반환한다. 문자열 형식은 RFC 7231의 "HTTP-date"를 기반으로 ECMAScript Date가 지원하는 전체 시간 범위에 맞게 일반화된 것이다.

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. dateObjectthis 값으로 설정한다.
  2. RequireInternalSlot(dateObject, [[DateValue]])를 수행한다.
  3. tvdateObject.[[DateValue]]로 설정한다.
  4. tvNaN이면 "Invalid Date"를 반환한다.
  5. weekdayTable 63에서 Number WeekDay(tv)에 해당하는 Name으로 설정한다.
  6. monthTable 64에서 Number MonthFromTime(tv)에 해당하는 Name으로 설정한다.
  7. dayToZeroPaddedDecimalString((DateFromTime(tv)), 2)로 설정한다.
  8. yvYearFromTime(tv)로 설정한다.
  9. yv+0𝔽이거나 yv > +0𝔽이면 yearSign을 빈 문자열로, 아니면 yearSign"-"로 설정한다.
  10. paddedYearToZeroPaddedDecimalString(abs((yv)), 4)로 설정한다.
  11. weekday, ",", 코드 유닛 0x0020(공백), day, 코드 유닛 0x0020(공백), month, 코드 유닛 0x0020(공백), yearSign, paddedYear, 코드 유닛 0x0020(공백), TimeString(tv)를 차례로 연결한 문자열을 반환한다.

21.4.4.44 Date.prototype.valueOf ( )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. dateObjectthis 값으로 설정한다.
  2. RequireInternalSlot(dateObject, [[DateValue]])를 수행한다.
  3. dateObject.[[DateValue]]를 반환한다.

21.4.4.45 Date.prototype [ %Symbol.toPrimitive% ] ( hint )

이 메서드는 ECMAScript 언어 연산자가 Date를 원시 값으로 변환할 때 호출된다. hint에 허용되는 값은 "default", "number", "string"이다. Date는 내장 ECMAScript 객체 중 유일하게 "default""string"과 동등하게 취급한다. 다른 내장 객체는 "default""number"와 동등하게 취급한다.

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. Othis 값으로 설정한다.
  2. O가 객체가 아니면 TypeError 예외를 throw 한다.
  3. hint"string" 또는 "default"이면
    1. tryFirststring으로 설정한다.
  4. 아니고 hint"number"이면
    1. tryFirstnumber로 설정한다.
  5. 아니면
    1. TypeError 예외를 throw 한다.
  6. OrdinaryToPrimitive(O, tryFirst)를 반환한다.

이 프로퍼티의 속성은 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }이다.

이 메서드의 "name" 프로퍼티 값은 "[Symbol.toPrimitive]"이다.

21.4.5 Date 인스턴스의 프로퍼티

Date 인스턴스는 Date 프로토타입 객체에서 속성을 상속받는 일반 객체이다. Date 인스턴스는 또한 [[DateValue]] 내부 슬롯을 가진다. [[DateValue]] 내부 슬롯은 해당 Date가 나타내는 시간 값이다.

22 텍스트 처리

22.1 String 객체

22.1.1 String 생성자

String 생성자:

  • %String%이다.
  • 전역 객체"String" 프로퍼티 초기값이다.
  • 생성자로 호출될 때 새로운 String 객체를 생성하고 초기화한다.
  • 생성자가 아니라 함수로 호출되면 타입 변환을 수행한다.
  • 클래스 정의의 extends 절 값으로 사용할 수 있다. 지정된 String 동작을 상속하려는 서브클래스 생성자[[StringData]] 내부 슬롯을 가진 서브클래스 인스턴스를 생성 및 초기화하기 위해 반드시 String 생성자에 대한 super 호출을 포함해야 한다.

22.1.1.1 String ( value )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. value가 존재하지 않으면
    1. s를 빈 문자열로 둔다.
  2. 그렇지 않으면,
    1. NewTarget이 undefined 이고 value 가 Symbol 이면 SymbolDescriptiveString(value)를 반환한다.
    2. s를 ? ToString(value)로 둔다.
  3. NewTarget이 undefined이면 s를 반환한다.
  4. StringCreate(s, ? GetPrototypeFromConstructor(NewTarget, "%String.prototype%"))를 반환한다.

22.1.2 String 생성자의 프로퍼티

String 생성자:

  • 값이 %Function.prototype%[[Prototype]] 내부 슬롯을 가진다.
  • 다음 프로퍼티들을 가진다:

22.1.2.1 String.fromCharCode ( ...codeUnits )

이 함수는 나머지 매개변수 codeUnits 를 형성하는 임의 개수의 인수와 함께 호출될 수 있다.

호출되면 다음 단계를 수행한다:

  1. result를 빈 문자열로 둔다.
  2. codeUnits 의 각 요소 next 에 대해
    1. nextCU(? ToUint16(next))의 숫자 값을 갖는 코드 유닛으로 둔다.
    2. resultresultnextCU의 문자열 결합으로 설정한다.
  3. result를 반환한다.

이 함수의 "length" 프로퍼티 값은 1𝔽이다.

22.1.2.2 String.fromCodePoint ( ...codePoints )

이 함수는 나머지 매개변수 codePoints 를 형성하는 임의 개수의 인수와 함께 호출될 수 있다.

호출되면 다음 단계를 수행한다:

  1. result를 빈 문자열로 둔다.
  2. codePoints 의 각 요소 next 에 대해
    1. nextCP를 ? ToNumber(next)로 둔다.
    2. nextCP가 정수 Number가 아니면 RangeError 예외를 던진다.
    3. (nextCP) < 0 또는 (nextCP) > 0x10FFFF 이면 RangeError 예외를 던진다.
    4. resultresult와 UTF16EncodeCodePoint((nextCP))의 문자열 결합으로 설정한다.
  3. 단언: codePoints 가 비어 있다면 result 는 빈 문자열이다.
  4. result를 반환한다.

이 함수의 "length" 프로퍼티 값은 1𝔽이다.

22.1.2.3 String.prototype

String.prototype의 초기값은 String 프로토타입 객체이다.

이 프로퍼티는 속성 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }를 가진다.

22.1.2.4 String.raw ( template, ...substitutions )

이 함수는 가변 개수의 인수와 함께 호출될 수 있다. 첫 번째 인수는 template 이고 나머지는 리스트 substitutions 를 이룬다.

호출되면 다음 단계를 수행한다:

  1. substitutionCountsubstitutions의 요소 개수로 둔다.
  2. cooked를 ? ToObject(template)로 둔다.
  3. literals를 ? ToObject(? Get(cooked, "raw")))로 둔다.
  4. literalCount를 ? LengthOfArrayLike(literals)로 둔다.
  5. literalCount ≤ 0 이면 빈 문자열을 반환한다.
  6. R을 빈 문자열로 둔다.
  7. nextIndex를 0으로 둔다.
  8. 반복,
    1. nextLiteralVal을 ? Get(literals, ! ToString(𝔽(nextIndex)))로 둔다.
    2. nextLiteral을 ? ToString(nextLiteralVal)로 둔다.
    3. RRnextLiteral의 문자열 결합으로 설정한다.
    4. nextIndex + 1 = literalCount 이면 R을 반환한다.
    5. nextIndex < substitutionCount 이면
      1. nextSubValsubstitutions[nextIndex]로 둔다.
      2. nextSub를 ? ToString(nextSubVal)로 둔다.
      3. RRnextSub의 문자열 결합으로 설정한다.
    6. nextIndexnextIndex + 1로 둔다.
Note

이 함수는 태그드 템플릿(13.3.11)의 태그 함수로 사용하도록 의도되었다. 그렇게 호출될 때 첫 번째 인수는 올바른 템플릿 객체이고 나머지 매개변수는 치환 값들을 담는다.

22.1.3 String 프로토타입 객체의 프로퍼티

String 프로토타입 객체:

  • %String.prototype%이다.
  • String 특수(exotic) 객체이며 그러한 객체에 지정된 내부 메서드를 가진다.
  • 값이 빈 문자열인 [[StringData]] 내부 슬롯을 가진다.
  • 초기값이 +0𝔽이고 속성이 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }인 "length" 프로퍼티를 가진다.
  • 값이 %Object.prototype%[[Prototype]] 내부 슬롯을 가진다.

명시적으로 달리 기술되지 않는 한, 아래에 정의된 String 프로토타입 객체의 메서드는 제네릭하지 않으며, 그들에게 전달되는 this 값은 String 값이거나 String 값으로 초기화된 [[StringData]] 내부 슬롯을 가진 객체여야 한다.

22.1.3.1 String.prototype.at ( index )

  1. Othis 값으로 둔다.
  2. RequireObjectCoercible(O)를 수행한다.
  3. S를 ? ToString(O)로 둔다.
  4. lenS의 길이로 둔다.
  5. relativeIndex를 ? ToIntegerOrInfinity(index)로 둔다.
  6. relativeIndex ≥ 0이면
    1. krelativeIndex로 둔다.
  7. 아니면
    1. klen + relativeIndex로 둔다.
  8. k < 0 또는 klen이면 undefined를 반환한다.
  9. Sk부터 k + 1 전까지 부분 문자열을 반환한다.

22.1.3.2 String.prototype.charAt ( pos )

Note 1

이 메서드는 이 객체를 String으로 변환한 값 내에서 인덱스 pos 위치의 코드 유닛을 포함하는 단일 요소 String을 반환한다. 해당 인덱스에 요소가 없으면 결과는 빈 문자열이다. 결과는 String 객체가 아닌 String 값이다.

pos가 정수 Number이면 x.charAt(pos)의 결과는 x.substring(pos, pos + 1) 결과와 동일하다.

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. Othis 값으로 둔다.
  2. RequireObjectCoercible(O)를 수행한다.
  3. S를 ? ToString(O)로 둔다.
  4. position을 ? ToIntegerOrInfinity(pos)로 둔다.
  5. sizeS의 길이로 둔다.
  6. position < 0 또는 positionsize이면 빈 문자열을 반환한다.
  7. Sposition부터 position + 1 전까지 부분 문자열을 반환한다.
Note 2

이 메서드는 의도적으로 제네릭이다; this 값이 String 객체일 필요가 없다. 따라서 다른 종류의 객체에 이전하여 메서드로 사용할 수 있다.

22.1.3.3 String.prototype.charCodeAt ( pos )

Note 1

이 메서드는 이 객체를 String으로 변환한 값 내에서 인덱스 pos 위치 코드 유닛의 숫자 값을 나타내는 Number (0 이상 216 미만의 음이 아닌 정수 Number)를 반환한다. 해당 인덱스에 요소가 없으면 결과는 NaN이다.

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. Othis 값으로 둔다.
  2. RequireObjectCoercible(O)를 수행한다.
  3. S를 ? ToString(O)로 둔다.
  4. position을 ? ToIntegerOrInfinity(pos)로 둔다.
  5. sizeS의 길이로 둔다.
  6. position < 0 또는 positionsize이면 NaN을 반환한다.
  7. S 내 인덱스 position 코드 유닛의 숫자 값에 대한 Number 값을 반환한다.
Note 2

이 메서드는 의도적으로 제네릭이다; this 값이 String 객체일 필요가 없다. 따라서 다른 종류의 객체에 이전하여 메서드로 사용할 수 있다.

22.1.3.4 String.prototype.codePointAt ( pos )

Note 1

이 메서드는 이 객체를 String으로 변환한 결과에서 인덱스 pos 위치의 문자열 요소에서 시작하는 UTF-16 인코딩 코드 포인트(6.1.4)의 숫자 값을 나타내는 0x10FFFF𝔽 이하의 음이 아닌 정수 Number를 반환한다. 그 위치에 요소가 없으면 undefined를 반환한다. pos에서 유효한 UTF-16 서로게이트 쌍이 시작하지 않으면 결과는 pos의 코드 유닛이다.

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. Othis 값으로 둔다.
  2. RequireObjectCoercible(O)를 수행한다.
  3. S를 ? ToString(O)로 둔다.
  4. position을 ? ToIntegerOrInfinity(pos)로 둔다.
  5. sizeS의 길이로 둔다.
  6. position < 0 또는 positionsize이면 undefined를 반환한다.
  7. cp를 CodePointAt(S, position)로 둔다.
  8. 𝔽(cp.[[CodePoint]])를 반환한다.
Note 2

이 메서드는 의도적으로 제네릭이다; this 값이 String 객체일 필요가 없다. 따라서 다른 종류의 객체에 이전하여 메서드로 사용할 수 있다.

22.1.3.5 String.prototype.concat ( ...args )

Note 1

이 메서드는 this 값(문자열로 변환)의 코드 유닛 뒤에 각 인수를 문자열로 변환한 코드 유닛을 이어붙인 String 값을 반환한다. 결과는 String 객체가 아닌 String 값이다.

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. Othis 값으로 둔다.
  2. RequireObjectCoercible(O)를 수행한다.
  3. S를 ? ToString(O)로 둔다.
  4. RS로 둔다.
  5. args의 각 요소 next 에 대해
    1. nextString을 ? ToString(next)로 둔다.
    2. RRnextString의 문자열 결합으로 설정한다.
  6. R을 반환한다.

이 메서드의 "length" 프로퍼티 값은 1𝔽이다.

Note 2

이 메서드는 의도적으로 제네릭이다; this 값이 String 객체일 필요가 없다. 따라서 다른 종류의 객체에 이전하여 메서드로 사용할 수 있다.

22.1.3.6 String.prototype.constructor

String.prototype.constructor의 초기값은 %String%이다.

22.1.3.7 String.prototype.endsWith ( searchString [ , endPosition ] )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. Othis 값으로 둔다.
  2. RequireObjectCoercible(O)를 수행한다.
  3. S를 ? ToString(O)로 둔다.
  4. isRegExp를 ? IsRegExp(searchString)로 둔다.
  5. isRegExptrue이면 TypeError 예외를 던진다.
  6. searchStr를 ? ToString(searchString)로 둔다.
  7. lenS의 길이로 둔다.
  8. endPositionundefined이면 poslen으로, 아니면 pos를 ? ToIntegerOrInfinity(endPosition)로 둔다.
  9. endpos를 0과 len 사이로 클램프한 결과로 둔다.
  10. searchLengthsearchStr의 길이로 둔다.
  11. searchLength = 0이면 true를 반환한다.
  12. startend - searchLength로 둔다.
  13. start < 0이면 false를 반환한다.
  14. substringSstart부터 end 전까지 부분 문자열로 둔다.
  15. substringsearchStr이면 true를 반환한다.
  16. false를 반환한다.
Note 1

이 메서드는 searchString의 코드 유닛 시퀀스(문자열로 변환)가 이 객체(문자열로 변환)의 해당 코드 유닛과 endPosition - length(this) 지점부터 일치하면 true를 반환한다. 그렇지 않으면 false를 반환한다.

Note 2

첫 번째 인수가 RegExp이면 예외를 던지는 것은 향후 버전에서 그러한 인수 값을 허용하는 확장을 정의할 수 있도록 하기 위한 것이다.

Note 3

이 메서드는 의도적으로 제네릭이다; this 값이 String 객체일 필요가 없다. 따라서 다른 객체로 이전하여 사용할 수 있다.

22.1.3.8 String.prototype.includes ( searchString [ , position ] )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. Othis 값으로 둔다.
  2. RequireObjectCoercible(O)를 수행한다.
  3. S를 ? ToString(O)로 둔다.
  4. isRegExp를 ? IsRegExp(searchString)로 둔다.
  5. isRegExptrue이면 TypeError 예외를 던진다.
  6. searchStr를 ? ToString(searchString)로 둔다.
  7. pos를 ? ToIntegerOrInfinity(position)로 둔다.
  8. 단언: positionundefined이면 pos는 0이다.
  9. lenS의 길이로 둔다.
  10. startpos를 0과 len 사이로 클램프한 결과로 둔다.
  11. indexStringIndexOf(S, searchStr, start)로 둔다.
  12. indexnot-found이면 false를 반환한다.
  13. true를 반환한다.
Note 1

searchString이 이 객체를 String으로 변환한 결과의 position 이상 인덱스들에서 하나 이상 substring으로 나타나면 true를 반환하고, 아니면 false를 반환한다. positionundefined이면 0을 가정하여 전체 문자열을 검색한다.

Note 2

첫 번째 인수가 RegExp이면 예외를 던지는 것은 향후 버전 확장을 위해서이다.

Note 3

이 메서드는 의도적으로 제네릭이다; this 값이 String 객체일 필요가 없다.

22.1.3.9 String.prototype.indexOf ( searchString [ , position ] )

Note 1

searchString이 이 객체를 String으로 변환한 결과의 position 이상 인덱스 중 하나 이상에서 substring으로 나타나면 그중 가장 작은 인덱스를 반환하고, 아니면 -1𝔽을 반환한다. positionundefined이면 +0𝔽을 가정하여 전체 문자열을 검색한다.

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. Othis 값으로 둔다.
  2. RequireObjectCoercible(O)를 수행한다.
  3. S를 ? ToString(O)로 둔다.
  4. searchStr를 ? ToString(searchString)로 둔다.
  5. pos를 ? ToIntegerOrInfinity(position)로 둔다.
  6. 단언: positionundefined이면 pos는 0이다.
  7. lenS의 길이로 둔다.
  8. startpos를 0과 len 사이로 클램프한 결과로 둔다.
  9. resultStringIndexOf(S, searchStr, start)로 둔다.
  10. resultnot-found이면 -1𝔽을 반환한다.
  11. 𝔽(result)를 반환한다.
Note 2

이 메서드는 의도적으로 제네릭이다.

22.1.3.10 String.prototype.isWellFormed ( )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. Othis 값으로 둔다.
  2. RequireObjectCoercible(O)를 수행한다.
  3. S를 ? ToString(O)로 둔다.
  4. IsStringWellFormedUnicode(S)를 반환한다.

22.1.3.11 String.prototype.lastIndexOf ( searchString [ , position ] )

Note 1

searchString이 이 객체를 String으로 변환한 결과에서 position 이하 인덱스 하나 이상에서 substring으로 나타나면 그중 가장 큰 인덱스를 반환하고 아니면 -1𝔽을 반환한다. positionundefined이면 문자열 길이를 가정하여 전체를 검색한다.

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. Othis 값으로 둔다.
  2. RequireObjectCoercible(O)를 수행한다.
  3. S를 ? ToString(O)로 둔다.
  4. searchStr를 ? ToString(searchString)로 둔다.
  5. numPos를 ? ToNumber(position)로 둔다.
  6. 단언: positionundefined이면 numPosNaN이다.
  7. numPosNaN이면 pos를 +∞로, 아니면 pos를 ! ToIntegerOrInfinity(numPos)로 둔다.
  8. lenS의 길이로 둔다.
  9. searchLensearchStr의 길이로 둔다.
  10. startpos를 0과 len - searchLen 사이로 클램프한 결과로 둔다.
  11. resultStringLastIndexOf(S, searchStr, start)로 둔다.
  12. resultnot-found이면 -1𝔽을 반환한다.
  13. 𝔽(result)를 반환한다.
Note 2

이 메서드는 의도적으로 제네릭이다.

22.1.3.12 String.prototype.localeCompare ( that [ , reserved1 [ , reserved2 ] ] )

ECMA-402 국제화 API를 포함하는 구현은 ECMA-402 명세에 따라 이 메서드를 구현해야 한다. 포함하지 않는 구현은 다음 명세를 사용한다:

이 메서드는 this 값(문자열로 변환된 S)과 that(문자열로 변환된 thatValue)의 구현 정의 로케일 민감 문자열 비교 결과를 나타내는 NaN이 아닌 Number를 반환한다. 결과는 호스트 환경 현재 로케일 관례에 따른 정렬 순서를 반영하며, SthatValue 앞이면 음수, 뒤면 양수, 그 외 경우(상대적 순서 없음) 0을 반환한다.

비교 수행 전 다음 준비 단계를 거친다:

  1. Othis 값으로 둔다.
  2. RequireObjectCoercible(O)를 수행한다.
  3. S를 ? ToString(O)로 둔다.
  4. thatValue를 ? ToString(that)로 둔다.

두 번째와 세 번째 선택적 매개변수 의미는 ECMA-402 명세에 정의된다; 이를 포함하지 않는 구현은 다른 해석을 부여해서는 안 된다.

실제 반환 값은 추가 정보를 인코딩할 수 있도록 구현 정의이지만, 두 인수 메서드로 간주될 때 모든 문자열에 대해 총순서를 정의하는 일관된 비교자여야 한다. 또한 이 메서드는 Unicode 표준에 따른 정규( canonical ) 등가성을 인지하고 존중하여 구분 가능하지만 정규 등가인 문자열 비교 시 +0𝔽을 반환해야 한다.

Note 1

이 메서드 자체는 Array.prototype.sort에 직접 넘기기 적합하지 않다. 후자는 두 인수 함수를 요구한다.

Note 2

이 메서드는 호스트 환경이 제공하는 언어/로케일 민감 비교 기능을 사용할 수 있으며, 현재 로케일 규칙에 따라 비교하도록 의도되었다. 그러나 어떤 비교 능력이든 Unicode 표준의 정규 등가성은 반드시 존중해야 한다 — 예: 아래 모든 비교는 +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")

정규 등가성 정의와 논의는 Unicode 표준 2, 3장 및 UAX #15, Unicode Technical Note #5, UTS #10를 참조.

Unicode 호환 등가 또는 호환 분해는 존중하지 않는 것이 권장된다.

Note 3

이 메서드는 의도적으로 제네릭이다.

22.1.3.13 String.prototype.match ( regexp )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. Othis 값으로 둔다.
  2. RequireObjectCoercible(O)를 수행한다.
  3. regexpundefinednull도 아니면
    1. matcher를 ? GetMethod(regexp, %Symbol.match%)로 둔다.
    2. matcherundefined가 아니면
      1. Call(matcher, regexp, « O »)를 반환한다.
  4. S를 ? ToString(O)로 둔다.
  5. rx를 ? RegExpCreate(regexp, undefined)로 둔다.
  6. Invoke(rx, %Symbol.match%, « S »)를 반환한다.
Note

이 메서드는 의도적으로 제네릭이다.

22.1.3.14 String.prototype.matchAll ( regexp )

이 메서드는 this 값이 나타내는 문자열에 대해 정규 표현식 매칭을 수행하고 매치 결과를 내는 이터레이터를 반환한다. 각 매치 결과는 첫 요소가 매치된 부분 문자열이고 이후 캡처 그룹에 매치된 부분을 담는 배열이다. 정규 표현식이 전혀 매치되지 않으면 이터레이터는 아무것도 산출하지 않는다.

호출되면 다음 단계를 수행한다:

  1. Othis 값으로 둔다.
  2. RequireObjectCoercible(O)를 수행한다.
  3. regexpundefinednull도 아니면
    1. isRegExp를 ? IsRegExp(regexp)로 둔다.
    2. isRegExptrue이면
      1. flags를 ? Get(regexp, "flags")로 둔다.
      2. RequireObjectCoercible(flags)를 수행한다.
      3. ToString(flags)에 "g"가 없으면 TypeError 예외를 던진다.
    3. matcher를 ? GetMethod(regexp, %Symbol.matchAll%)로 둔다.
    4. matcherundefined가 아니면
      1. Call(matcher, regexp, « O »)를 반환한다.
  4. S를 ? ToString(O)로 둔다.
  5. rx를 ? RegExpCreate(regexp, "g")로 둔다.
  6. Invoke(rx, %Symbol.matchAll%, « S »)를 반환한다.
Note 1
이 메서드는 의도적으로 제네릭이며 this 값이 String 객체일 필요가 없다.
Note 2
String.prototype.split과 유사하게 일반적으로 입력을 변형하지 않도록 설계되었다.

22.1.3.15 String.prototype.normalize ( [ form ] )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. Othis 값으로 둔다.
  2. RequireObjectCoercible(O)를 수행한다.
  3. S를 ? ToString(O)로 둔다.
  4. formundefined이면 f"NFC"로 둔다.
  5. 아니면 f를 ? ToString(form)으로 둔다.
  6. f"NFC", "NFD", "NFKC", "NFKD" 중 하나가 아니면 RangeError 예외를 던진다.
  7. ns를 최신 Unicode Standard 의 Normalization Forms 에 지정된 대로 Sf가 명명하는 정규화 형식으로 정규화한 결과 String 값으로 둔다.
  8. ns를 반환한다.
Note

이 메서드는 의도적으로 제네릭이다.

22.1.3.16 String.prototype.padEnd ( maxLength [ , fillString ] )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. Othis 값으로 둔다.
  2. RequireObjectCoercible(O)를 수행한다.
  3. StringPaddingBuiltinsImpl(O, maxLength, fillString, end)를 반환한다.

22.1.3.17 String.prototype.padStart ( maxLength [ , fillString ] )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. Othis 값으로 둔다.
  2. RequireObjectCoercible(O)를 수행한다.
  3. StringPaddingBuiltinsImpl(O, maxLength, fillString, start)를 반환한다.

22.1.3.17.1 StringPaddingBuiltinsImpl ( O, maxLength, fillString, placement )

The abstract operation StringPaddingBuiltinsImpl takes arguments O (ECMAScript 언어 값), maxLength (ECMAScript 언어 값), fillString (ECMAScript 언어 값), and placement (start 또는 end) and returns 정상 완료(문자열) 또는 throw 완료. It performs the following steps when called:

  1. S를 ? ToString(O)로 둔다.
  2. intMaxLength(? ToLength(maxLength))로 둔다.
  3. stringLengthS의 길이로 둔다.
  4. intMaxLengthstringLength이면 S를 반환한다.
  5. fillStringundefined이면 fillString을 코드 유닛 0x0020 (SPACE) 하나로 이루어진 문자열 값으로 둔다.
  6. 아니면 fillString을 ? ToString(fillString)으로 둔다.
  7. StringPad(S, intMaxLength, fillString, placement)를 반환한다.

22.1.3.17.2 StringPad ( S, maxLength, fillString, placement )

The abstract operation StringPad takes arguments S (문자열), maxLength (음이 아닌 정수), fillString (문자열), and placement (start 또는 end) and returns 문자열. It performs the following steps when called:

  1. stringLengthS의 길이로 둔다.
  2. maxLengthstringLength이면 S를 반환한다.
  3. fillString이 빈 문자열이면 S를 반환한다.
  4. fillLenmaxLength - stringLength로 둔다.
  5. truncatedStringFillerfillString을 반복 결합한 뒤 길이 fillLen으로 자른 문자열 값으로 둔다.
  6. placementstart이면 truncatedStringFillerS의 문자열 결합을 반환한다.
  7. 그렇지 않으면 StruncatedStringFiller의 문자열 결합을 반환한다.
Note 1

인수 maxLengthS의 길이보다 작아질 수 없도록 클램프된다.

Note 2

인수 fillString의 기본값은 " " (코드 유닛 0x0020 SPACE 하나)이다.

22.1.3.17.3 ToZeroPaddedDecimalString ( n, minLength )

The abstract operation ToZeroPaddedDecimalString takes arguments n (음이 아닌 정수) and minLength (음이 아닌 정수) and returns 문자열. It performs the following steps when called:

  1. Sn의 10진수 형식 문자열 표현으로 둔다.
  2. StringPad(S, minLength, "0", start)를 반환한다.

22.1.3.18 String.prototype.repeat ( count )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. Othis 값으로 둔다.
  2. RequireObjectCoercible(O)를 수행한다.
  3. S를 ? ToString(O)로 둔다.
  4. n을 ? ToIntegerOrInfinity(count)로 둔다.
  5. n < 0 또는 n = +∞이면 RangeError 예외를 던진다.
  6. n = 0이면 빈 문자열을 반환한다.
  7. Sn번 이어붙여 만든 문자열 값을 반환한다.
Note 1

이 메서드는 this 값을 문자열로 변환한 것의 코드 유닛을 count 번 반복한 String 값을 만든다.

Note 2

이 메서드는 의도적으로 제네릭이다.

22.1.3.19 String.prototype.replace ( searchValue, replaceValue )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. Othis 값으로 둔다.
  2. RequireObjectCoercible(O)를 수행한다.
  3. searchValueundefinednull도 아니면
    1. replacer를 ? GetMethod(searchValue, %Symbol.replace%)로 둔다.
    2. replacerundefined가 아니면
      1. Call(replacer, searchValue, « O, replaceValue »)를 반환한다.
  4. string을 ? ToString(O)로 둔다.
  5. searchString을 ? ToString(searchValue)로 둔다.
  6. functionalReplaceIsCallable(replaceValue)로 둔다.
  7. functionalReplacefalse이면
    1. replaceValue를 ? ToString(replaceValue)로 둔다.
  8. searchLengthsearchString의 길이로 둔다.
  9. positionStringIndexOf(string, searchString, 0)으로 둔다.
  10. positionnot-found이면 string을 반환한다.
  11. precedingstring의 0부터 position 전까지 부분 문자열로 둔다.
  12. followingstringposition + searchLength부터 끝까지 부분 문자열로 둔다.
  13. functionalReplacetrue이면
    1. replacement를 ? ToString(? Call(replaceValue, undefined, « searchString, 𝔽(position), string »))로 둔다.
  14. 아니면
    1. 단언: replaceValue는 문자열이다.
    2. captures를 새 빈 리스트로 둔다.
    3. replacement를 ! GetSubstitution(searchString, string, position, captures, undefined, replaceValue)로 둔다.
  15. preceding, replacement, following의 문자열 결합을 반환한다.
Note

이 메서드는 의도적으로 제네릭이다.

22.1.3.19.1 GetSubstitution ( matched, str, position, captures, namedCaptures, replacementTemplate )

The abstract operation GetSubstitution takes arguments matched (문자열), str (문자열), position (음이 아닌 정수), captures (문자열 또는 undefined 요소를 갖는 리스트), namedCaptures (객체 또는 undefined), and replacementTemplate (문자열) and returns 정상 완료(문자열) 또는 throw 완료. 이 추상 연산에서 10진 숫자(digital digit)는 0x0030 (DIGIT ZERO)부터 0x0039 (DIGIT NINE)까지 포함 구간의 코드 유닛이다. It performs the following steps when called:

  1. stringLengthstr의 길이로 둔다.
  2. 단언: positionstringLength.
  3. result를 빈 문자열로 둔다.
  4. templateRemainderreplacementTemplate로 둔다.
  5. templateRemainder가 빈 문자열이 아닐 동안 반복,
    1. 주: 다음 단계들은 ref ( templateRemainder의 접두사 )를 분리하고 refReplacement (그 치환)를 결정한 뒤 result에 추가한다.
    2. templateRemainder"$$"로 시작하면
      1. ref"$$"로.
      2. refReplacement"$"로.
    3. 아니고 "$`"로 시작하면
      1. ref"$`"로.
      2. refReplacementstr의 0부터 position 전까지 부분 문자열로.
    4. 아니고 "$&"로 시작하면
      1. ref"$&"로.
      2. refReplacementmatched로.
    5. 아니고 "$'" (0x0024 DOLLAR SIGN + 0x0027 APOSTROPHE)로 시작하면
      1. ref"$'"로.
      2. matchLengthmatched의 길이로.
      3. tailPosposition + matchLength로.
      4. refReplacementstrmin(tailPos, stringLength)부터 끝까지 부분 문자열로.
      5. 참고: tailPosstringLength를 넘을 수 있는 경우는 이 추상 연산이 본래 내장 %RegExp.prototype.exec%가 아닌 "exec" 프로퍼티를 가진 객체에서 %RegExp.prototype%의 본래 %Symbol.replace% 호출로 유래했을 때뿐이다.
    6. 아니고 "$" 뒤에 1개 이상의 10진 숫자로 시작하면
      1. "$" 뒤에 두 자리 이상 숫자로 시작하면 digitCount를 2로, 아니면 1로 둔다.
      2. digitstemplateRemainder의 1부터 1 + digitCount 전까지 부분 문자열로.
      3. index(StringToNumber(digits))로.
      4. 단언: 0 ≤ index ≤ 99.
      5. captureLencaptures의 요소 개수로.
      6. index > captureLen 이고 digitCount = 2 이면
        1. 주: 두 자리 패턴이 캡처 개수를 넘는 인덱스를 지정하면 한 자리 패턴 + 리터럴 숫자로 취급된다.
        2. digitCount를 1로.
        3. digitsdigits의 0부터 1 전까지 부분 문자열로.
        4. index(StringToNumber(digits))로.
      7. reftemplateRemainder의 0부터 1 + digitCount 전까지 부분 문자열로.
      8. 1 ≤ indexcaptureLen 이면
        1. capturecaptures[index - 1]로.
        2. captureundefined이면
          1. refReplacement를 빈 문자열로.
        3. 아니면
          1. refReplacementcapture로.
      9. 아니면
        1. refReplacementref로.
    7. 아니고 "$<"로 시작하면
      1. gtPosStringIndexOf(templateRemainder, ">", 0)으로.
      2. gtPosnot-found 이거나 namedCapturesundefined이면
        1. ref"$<"로.
        2. refReplacementref로.
      3. 아니면
        1. reftemplateRemainder의 0부터 gtPos + 1 전까지 부분 문자열로.
        2. groupNametemplateRemainder의 2부터 gtPos 전까지 부분 문자열로.
        3. 단언: namedCaptures는 객체이다.
        4. capture를 ? Get(namedCaptures, groupName)으로.
        5. captureundefined이면
          1. refReplacement를 빈 문자열로.
        6. 아니면
          1. refReplacement를 ? ToString(capture)로.
    8. 아니면
      1. reftemplateRemainder의 0부터 1 전까지 부분 문자열로.
      2. refReplacementref로.
    9. refLengthref의 길이로.
    10. templateRemaindertemplateRemainderrefLength부터 끝까지 부분 문자열로 둔다.
    11. resultresultrefReplacement의 문자열 결합으로 설정한다.
  6. result를 반환한다.

22.1.3.20 String.prototype.replaceAll ( searchValue, replaceValue )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. Othis 값으로 둔다.
  2. RequireObjectCoercible(O)를 수행한다.
  3. searchValueundefinednull도 아니면
    1. isRegExp를 ? IsRegExp(searchValue)로 둔다.
    2. isRegExptrue이면
      1. flags를 ? Get(searchValue, "flags")로 둔다.
      2. RequireObjectCoercible(flags)를 수행한다.
      3. ToString(flags)에 "g"가 없으면 TypeError 예외를 던진다.
    3. replacer를 ? GetMethod(searchValue, %Symbol.replace%)로 둔다.
    4. replacerundefined가 아니면
      1. Call(replacer, searchValue, « O, replaceValue »)를 반환한다.
  4. string을 ? ToString(O)로 둔다.
  5. searchString을 ? ToString(searchValue)로 둔다.
  6. functionalReplaceIsCallable(replaceValue)로 둔다.
  7. functionalReplacefalse이면
    1. replaceValue를 ? ToString(replaceValue)로 둔다.
  8. searchLengthsearchString의 길이로 둔다.
  9. advanceBymax(1, searchLength)로 둔다.
  10. matchPositions를 새 빈 리스트로 둔다.
  11. positionStringIndexOf(string, searchString, 0)으로 둔다.
  12. positionnot-found가 아닐 동안 반복,
    1. matchPositionsposition을 추가한다.
    2. positionStringIndexOf(string, searchString, position + advanceBy)로 둔다.
  13. endOfLastMatch를 0으로 둔다.
  14. result를 빈 문자열로 둔다.
  15. matchPositions의 각 요소 p 에 대해
    1. preservedstringendOfLastMatch부터 p 전까지 부분 문자열로 둔다.
    2. functionalReplacetrue이면
      1. replacement를 ? ToString(? Call(replaceValue, undefined, « searchString, 𝔽(p), string »))로 둔다.
    3. 아니면
      1. 단언: replaceValue는 문자열이다.
      2. captures를 새 빈 리스트로 둔다.
      3. replacement를 ! GetSubstitution(searchString, string, p, captures, undefined, replaceValue)로 둔다.
    4. resultresult, preserved, replacement의 문자열 결합으로 설정한다.
    5. endOfLastMatchp + searchLength로 둔다.
  16. endOfLastMatch < string 길이면
    1. resultresultstringendOfLastMatch부터 끝까지 부분 문자열 결합으로 설정한다.
  17. result를 반환한다.

22.1.3.21 String.prototype.search ( regexp )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. Othis 값으로 둔다.
  2. RequireObjectCoercible(O)를 수행한다.
  3. regexpundefinednull도 아니면
    1. searcher를 ? GetMethod(regexp, %Symbol.search%)로 둔다.
    2. searcherundefined가 아니면
      1. Call(searcher, regexp, « O »)를 반환한다.
  4. string을 ? ToString(O)로 둔다.
  5. rx를 ? RegExpCreate(regexp, undefined)로 둔다.
  6. Invoke(rx, %Symbol.search%, « string »)를 반환한다.
Note

이 메서드는 의도적으로 제네릭이다.

22.1.3.22 String.prototype.slice ( start, end )

이 메서드는 이 객체를 문자열로 변환한 결과에서 인덱스 start부터 end (포함하지 않음) 전까지(endundefined이면 끝까지) substring을 반환한다. start가 음수면 sourceLength + start로 처리하고, end가 음수면 sourceLength + end로 처리한다 (sourceLength는 문자열 길이). 결과는 String 객체가 아닌 String 값이다.

호출되면 다음 단계를 수행한다:

  1. Othis 값으로 둔다.
  2. RequireObjectCoercible(O)를 수행한다.
  3. S를 ? ToString(O)로 둔다.
  4. lenS의 길이로 둔다.
  5. intStart를 ? ToIntegerOrInfinity(start)로 둔다.
  6. intStart = -∞이면 from을 0으로.
  7. 아니고 intStart < 0이면 frommax(len + intStart, 0)으로.
  8. 아니면 frommin(intStart, len)으로.
  9. endundefined이면 intEndlen으로, 아니면 intEnd를 ? ToIntegerOrInfinity(end)로.
  10. intEnd = -∞이면 to를 0으로.
  11. 아니고 intEnd < 0이면 tomax(len + intEnd, 0)으로.
  12. 아니면 tomin(intEnd, len)으로.
  13. fromto이면 빈 문자열을 반환한다.
  14. Sfrom부터 to 전까지 부분 문자열을 반환한다.
Note

이 메서드는 의도적으로 제네릭이다.

22.1.3.23 String.prototype.split ( separator, limit )

이 메서드는 이 객체를 문자열로 변환한 결과를 분할해 그 부분 문자열들을 담은 배열을 반환한다. 왼쪽에서 오른쪽으로 separator 발생 지점을 찾으며, 이 지점들은 결과 배열 문자열 일부가 아니고 경계를 나눈다. separator 값은 임의 길이의 문자열이거나 %Symbol.split% 메서드를 가진 객체(예: RegExp)일 수 있다.

호출되면 다음 단계를 수행한다:

  1. Othis 값으로 둔다.
  2. RequireObjectCoercible(O)를 수행한다.
  3. separatorundefinednull도 아니면
    1. splitter를 ? GetMethod(separator, %Symbol.split%)로 둔다.
    2. splitterundefined가 아니면
      1. Call(splitter, separator, « O, limit »)를 반환한다.
  4. S를 ? ToString(O)로 둔다.
  5. limitundefined이면 lim을 232 - 1로, 아니면 lim(? ToUint32(limit))로.
  6. R을 ? ToString(separator)로 둔다.
  7. lim = 0이면
    1. CreateArrayFromList(« »)를 반환한다.
  8. separatorundefined이면
    1. CreateArrayFromListS »)를 반환한다.
  9. separatorLengthR의 길이로 둔다.
  10. separatorLength = 0이면
    1. strLenS의 길이로.
    2. outLenlim을 0과 strLen 사이로 클램프한 결과로.
    3. headS의 0부터 outLen 전까지 부분 문자열로.
    4. codeUnitshead 요소 코드 유닛 시퀀스로 이루어진 리스트로.
    5. CreateArrayFromList(codeUnits)를 반환한다.
  11. S가 빈 문자열이면 CreateArrayFromListS »)를 반환한다.
  12. substrings를 새 빈 리스트로 둔다.
  13. i를 0으로 둔다.
  14. jStringIndexOf(S, R, 0)으로 둔다.
  15. jnot-found가 아닐 동안 반복,
    1. TSi부터 j 전까지 부분 문자열로 둔다.
    2. substringsT를 추가한다.
    3. substrings 요소 수가 lim이면 CreateArrayFromList(substrings)를 반환한다.
    4. ij + separatorLength로 둔다.
    5. jStringIndexOf(S, R, i)로 둔다.
  16. TSi부터 끝까지 부분 문자열로 둔다.
  17. substringsT를 추가한다.
  18. CreateArrayFromList(substrings)를 반환한다.
Note 1

separator 값은 빈 문자열일 수 있다. 이 경우 separator는 시작/끝의 빈 substring이나 직전 매치 후의 빈 substring와 매치하지 않는다. separator가 빈 문자열이면 문자열은 개별 코드 유닛 요소로 분리되며 결과 배열 길이는 문자열 길이와 같고 각 substring은 한 코드 유닛을 포함한다.

this 값이(또는 변환 결과가) 빈 문자열이면 separator가 빈 문자열과 매치 가능한지 여부에 따라 결과가 달라진다. 매치 가능하면 결과 배열은 비어 있다. 아니면 빈 문자열 하나를 요소로 가진다.

separatorundefined이면 결과 배열은 this 값(문자열로 변환) 하나만 가진다. limitundefined가 아니면 결과 배열은 limit 요소를 넘지 않도록 잘린다.

Note 2

이 메서드는 의도적으로 제네릭이다.

22.1.3.24 String.prototype.startsWith ( searchString [ , position ] )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. Othis 값으로 둔다.
  2. RequireObjectCoercible(O)를 수행한다.
  3. S를 ? ToString(O)로 둔다.
  4. isRegExp를 ? IsRegExp(searchString)로 둔다.
  5. isRegExptrue이면 TypeError 예외를 던진다.
  6. searchStr를 ? ToString(searchString)로 둔다.
  7. lenS의 길이로 둔다.
  8. positionundefined이면 pos를 0으로, 아니면 pos를 ? ToIntegerOrInfinity(position)로 둔다.
  9. startpos를 0과 len 사이로 클램프한 결과로 둔다.
  10. searchLengthsearchStr의 길이로 둔다.
  11. searchLength = 0이면 true를 반환한다.
  12. endstart + searchLength로 둔다.
  13. end > len이면 false를 반환한다.
  14. substringSstart부터 end 전까지 부분 문자열로 둔다.
  15. substringsearchStr이면 true를 반환한다.
  16. false를 반환한다.
Note 1

이 메서드는 searchString이 문자열로 변환된 코드 유닛 시퀀스가 position 인덱스에서 시작하는 이 객체(문자열 변환)의 대응 코드 유닛과 같으면 true를 반환한다.

Note 2

첫 번째 인수가 RegExp이면 예외를 던지는 것은 향후 확장을 위해서이다.

Note 3

이 메서드는 의도적으로 제네릭이다.

22.1.3.25 String.prototype.substring ( start, end )

이 메서드는 이 객체를 String으로 변환한 결과에서 인덱스 start부터 end (포함하지 않음) 전까지(endundefined이면 끝까지) substring을 반환한다. 결과는 String 객체가 아닌 String 값이다.

어느 인수라도 NaN 또는 음수면 0으로 대체되고, 어느 인수가 문자열 길이를 초과하면 그 길이로 대체된다.

start > end이면 둘을 교환한다.

호출되면 다음 단계를 수행한다:

  1. Othis 값으로 둔다.
  2. RequireObjectCoercible(O)를 수행한다.
  3. S를 ? ToString(O)로 둔다.
  4. lenS의 길이로 둔다.
  5. intStart를 ? ToIntegerOrInfinity(start)로 둔다.
  6. endundefined이면 intEndlen으로, 아니면 intEnd를 ? ToIntegerOrInfinity(end)로 둔다.
  7. finalStartintStart를 0과 len 사이로 클램프한 결과로 둔다.
  8. finalEndintEnd를 0과 len 사이로 클램프한 결과로 둔다.
  9. frommin(finalStart, finalEnd)로 둔다.
  10. tomax(finalStart, finalEnd)로 둔다.
  11. Sfrom부터 to 전까지 부분 문자열을 반환한다.
Note

이 메서드는 의도적으로 제네릭이다.

22.1.3.26 String.prototype.toLocaleLowerCase ( [ reserved1 [ , reserved2 ] ] )

ECMA-402 국제화 API를 포함한 구현은 ECMA-402 명세에 따라 구현해야 한다. 포함하지 않으면 다음 명세를 따른다:

이 메서드는 6.1.4에 설명된 대로 문자열 값을 UTF-16 인코딩 코드 포인트 시퀀스로 해석한다.

toLowerCase와 동일하게 동작하지만 로케일에 민감한 결과(예: 터키어의 특수 규칙)를 낸다.

선택적 매개변수 의미는 ECMA-402 명세에 정의되며, 이를 지원하지 않는 구현은 다른 의미를 부여해서는 안 된다.

Note

이 메서드는 의도적으로 제네릭이다.

22.1.3.27 String.prototype.toLocaleUpperCase ( [ reserved1 [ , reserved2 ] ] )

ECMA-402 국제화 API를 포함한 구현은 ECMA-402 명세에 따라 구현해야 한다. 포함하지 않으면 다음 명세를 따른다:

이 메서드는 문자열 값을 UTF-16 인코딩 코드 포인트 시퀀스로 해석한다.

toUpperCase와 동일하게 동작하지만 로케일 민감한 결과를 낸다.

선택적 매개변수 의미는 ECMA-402 명세에 정의되며, 비지원 구현은 다른 의미를 부여할 수 없다.

Note

이 메서드는 의도적으로 제네릭이다.

22.1.3.28 String.prototype.toLowerCase ( )

이 메서드는 6.1.4에 설명된 대로 문자열 값을 UTF-16 코드 포인트 시퀀스로 해석한다.

호출되면 다음 단계를 수행한다:

  1. Othis 값으로 둔다.
  2. RequireObjectCoercible(O)를 수행한다.
  3. S를 ? ToString(O)로 둔다.
  4. sText를 StringToCodePoints(S)로 둔다.
  5. lowerText를 Unicode 기본 대소문자 변환 알고리즘에 따라 toLowercase(sText)로 둔다.
  6. L을 CodePointsToString(lowerText)로 둔다.
  7. L을 반환한다.

결과는 Unicode Character Database의 로케일 비의존 매핑( UnicodeData.txt 및 그것과 동반하는 SpecialCasing.txt 의 로케일 비의존 매핑 )을 따라 파생되어야 한다.

Note 1

몇몇 코드 포인트의 대소문자 매핑은 여러 코드 포인트를 생성할 수 있다. 이 경우 결과 문자열 길이는 원본과 다를 수 있다. toUpperCasetoLowerCase는 문맥 민감하므로 대칭이 아니다.

Note 2

이 메서드는 의도적으로 제네릭이다.

22.1.3.29 String.prototype.toString ( )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. ThisStringValue(this value)을 반환한다.
Note

String 객체의 경우 이 메서드는 valueOf와 동일한 것을 반환한다.

22.1.3.30 String.prototype.toUpperCase ( )

이 메서드는 문자열 값을 UTF-16 코드 포인트 시퀀스로 해석한다.

Unicode 기본 대소문자 변환의 toUppercase 알고리즘을 사용한다는 점만 제외하고 String.prototype.toLowerCase와 동일하게 동작한다.

Note

이 메서드는 의도적으로 제네릭이다.

22.1.3.31 String.prototype.toWellFormed ( )

이 메서드는 고립된 선행 또는 후행 서로게이트(서로게이트 쌍을 이루지 않는)를 U+FFFD (REPLACEMENT CHARACTER)로 치환한 이 객체의 문자열 표현을 반환한다.

호출되면 다음 단계를 수행한다:

  1. Othis 값으로 둔다.
  2. RequireObjectCoercible(O)를 수행한다.
  3. S를 ? ToString(O)로 둔다.
  4. strLenS의 길이로 둔다.
  5. k를 0으로 둔다.
  6. result를 빈 문자열로 둔다.
  7. k < strLen 동안 반복,
    1. cp를 CodePointAt(S, k)로 둔다.
    2. cp.[[IsUnpairedSurrogate]]true이면
      1. resultresult와 0xFFFD (REPLACEMENT CHARACTER) 결합으로 둔다.
    3. 아니면
      1. resultresult와 UTF16EncodeCodePoint(cp.[[CodePoint]]) 결합으로 둔다.
    4. kk + cp.[[CodeUnitCount]]로 둔다.
  8. result를 반환한다.

22.1.3.32 String.prototype.trim ( )

이 메서드는 문자열 값을 UTF-16 코드 포인트 시퀀스로 해석한다.

호출되면 다음 단계를 수행한다:

  1. Sthis 값으로 둔다.
  2. TrimString(S, start+end)를 반환한다.
Note

이 메서드는 의도적으로 제네릭이다.

22.1.3.32.1 TrimString ( string, where )

The abstract operation TrimString takes arguments string (ECMAScript 언어 값) and where (start, end, 또는 start+end) and returns 정상 완료(문자열) 또는 throw 완료. string을 UTF-16 인코딩 코드 포인트 시퀀스로 해석한다. It performs the following steps when called:

  1. RequireObjectCoercible(string)를 수행한다.
  2. S를 ? ToString(string)으로 둔다.
  3. wherestart이면
    1. TS의 선행 공백을 제거한 복사본으로 둔다.
  4. 아니고 whereend이면
    1. TS의 후행 공백을 제거한 복사본으로 둔다.
  5. 아니면
    1. 단언: wherestart+end이다.
    2. TS의 선행 및 후행 공백을 제거한 복사본으로 둔다.
  6. T를 반환한다.

공백 정의는 WhiteSpaceLineTerminator의 합집합이다. Unicode 일반 카테고리 “Space_Separator”(“Zs”) 판별 시 코드 유닛 시퀀스는 6.1.4에 규정된 UTF-16 인코딩 코드 포인트 시퀀스로 해석된다.

22.1.3.33 String.prototype.trimEnd ( )

이 메서드는 문자열 값을 UTF-16 코드 포인트 시퀀스로 해석한다.

호출되면 다음 단계를 수행한다:

  1. Sthis 값으로 둔다.
  2. TrimString(S, end)를 반환한다.
Note

이 메서드는 의도적으로 제네릭이다.

22.1.3.34 String.prototype.trimStart ( )

이 메서드는 문자열 값을 UTF-16 코드 포인트 시퀀스로 해석한다.

호출되면 다음 단계를 수행한다:

  1. Sthis 값으로 둔다.
  2. TrimString(S, start)를 반환한다.
Note

이 메서드는 의도적으로 제네릭이다.

22.1.3.35 String.prototype.valueOf ( )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. ThisStringValue(this value)을 반환한다.

22.1.3.35.1 ThisStringValue ( value )

The abstract operation ThisStringValue takes argument value (ECMAScript 언어 값) and returns 정상 완료(문자열) 또는 throw 완료. It performs the following steps when called:

  1. value가 문자열이면 value를 반환한다.
  2. value가 객체이고 [[StringData]] 내부 슬롯을 가지면
    1. svalue.[[StringData]]로 둔다.
    2. 단언: s는 문자열이다.
    3. s를 반환한다.
  3. TypeError 예외를 던진다.

22.1.3.36 String.prototype [ %Symbol.iterator% ] ( )

이 메서드는 문자열 값의 코드 포인트를 순회하며 각 코드 포인트를 문자열 값으로 반환하는 이터레이터 객체를 반환한다.

호출되면 다음 단계를 수행한다:

  1. Othis 값으로 둔다.
  2. RequireObjectCoercible(O)를 수행한다.
  3. s를 ? ToString(O)로 둔다.
  4. closures를 캡처하는 파라미터 없는 새 추상 클로저로 두고 호출 시 다음 단계를 수행하게 한다:
    1. lens의 길이로 둔다.
    2. position을 0으로 둔다.
    3. position < len 동안 반복,
      1. cp를 CodePointAt(s, position)로 둔다.
      2. nextIndexposition + cp.[[CodeUnitCount]]로 둔다.
      3. resultStringsposition부터 nextIndex 전까지 부분 문자열로 둔다.
      4. positionnextIndex로 둔다.
      5. GeneratorYield(CreateIteratorResultObject(resultString, false))를 수행한다.
    4. NormalCompletion(unused)을 반환한다.
  5. CreateIteratorFromClosure(closure, "%StringIteratorPrototype%", %StringIteratorPrototype%)를 반환한다.

이 메서드의 "name" 프로퍼티 값은 "[Symbol.iterator]"이다.

22.1.4 String 인스턴스의 프로퍼티

String 인스턴스는 String 특수(exotic) 객체이며 해당 객체에 지정된 내부 메서드를 가진다. String 인스턴스는 String 프로토타입 객체로부터 프로퍼티를 상속한다. 또한 [[StringData]] 내부 슬롯을 가지며, 이는 이 String 객체가 표현하는 문자열 값이다.

String 인스턴스는 "length" 프로퍼티와 정수 인덱스 이름을 가진 열거 가능한 프로퍼티 집합을 가진다.

22.1.4.1 length

이 String 객체가 표현하는 문자열 값의 요소 개수.

String 객체가 초기화된 후 이 프로퍼티는 변하지 않는다. 속성은 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }이다.

22.1.5 String 이터레이터 객체

String Iterator는 특정 String 인스턴스 객체에 대한 특정 순회를 나타내는 객체이다. String Iterator 객체에 대한 명명된 생성자는 없다. 대신 특정 String 인스턴스의 메서드를 호출하여 생성된다.

22.1.5.1 %StringIteratorPrototype% 객체

%StringIteratorPrototype% 객체:

22.1.5.1.1 %StringIteratorPrototype%.next ( )

  1. GeneratorResume(this value, empty, "%StringIteratorPrototype%")를 반환한다.

22.1.5.1.2 %StringIteratorPrototype% [ %Symbol.toStringTag% ]

%Symbol.toStringTag% 프로퍼티 초기값은 문자열 "String Iterator"이다.

이 프로퍼티는 속성 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }를 가진다.

22.2 RegExp (정규 표현식) 객체

RegExp 객체는 하나의 정규 표현식과 그에 연관된 플래그들을 포함한다.

Note

정규 표현식의 형식과 기능은 Perl 5 프로그래밍 언어의 정규 표현식 기능을 본뜬 것이다.

22.2.1 패턴 (Patterns)

RegExp 생성자는 입력 패턴 문자열에 아래의 문법을 적용한다. 해당 문법이 그 문자열을 Pattern 의 전개로 해석할 수 없으면 오류가 발생한다.

구문 (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

연결될 수 있는 \u HexLeadSurrogate 의 선택이 모호한 각 \u HexTrailSurrogate 는, 그렇지 않으면 해당하는 \u HexTrailSurrogate 를 갖지 않게 될 가장 가까운 가능한 u HexLeadSurrogate 와 연결되어야 한다.

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

여기 처음 두 줄은 CharacterClass 와 동등하다.

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

이 절의 여러 생성 규칙들은 B.1.2 절에서 대체 정의를 가진다.

22.2.1.1 정적 의미론: 조기 오류 (Early Errors)

Note

이 절은 B.1.2.1 에서 수정된다.

Pattern :: Disjunction
  • CountLeftCapturingParensWithin(Pattern) ≥ 232 - 1 이면 구문 오류이다.
  • Pattern 이 서로 다른 두 GroupSpecifier xy 를 포함하고, x 의 CapturingGroupName 이 y 의 CapturingGroupName 과 같으며 MightBothParticipate(x, y) 가 true 이면 구문 오류이다.
QuantifierPrefix :: { DecimalDigits , DecimalDigits } Atom :: (? RegularExpressionModifiers : Disjunction )
  • RegularExpressionModifiers 가 매치한 소스 텍스트에 동일한 코드 포인트가 두 번 이상 나타나면 구문 오류이다.
Atom :: (? RegularExpressionModifiers - RegularExpressionModifiers : Disjunction ) AtomEscape :: k GroupName
  • GroupSpecifiersThatMatch(GroupName) 이 비어 있으면 구문 오류이다.
AtomEscape :: DecimalEscape
  • DecimalEscape 의 CapturingGroupNumber 가 AtomEscape 를 포함하는 Pattern 내의 CountLeftCapturingParensWithin 값보다 엄격히 크면 구문 오류이다.
NonemptyClassRanges :: ClassAtom - ClassAtom ClassContents
  • 첫 번째 ClassAtom 의 IsCharacterClass 가 true 이거나 두 번째 ClassAtom 의 IsCharacterClass 가 true 이면 구문 오류이다.
  • 첫 번째 ClassAtom 의 IsCharacterClass 가 false, 두 번째 ClassAtom 의 IsCharacterClass 가 false 이고 첫 번째 ClassAtom 의 CharacterValue 가 두 번째 ClassAtom 의 CharacterValue 보다 엄격히 크면 구문 오류이다.
NonemptyClassRangesNoDash :: ClassAtomNoDash - ClassAtom ClassContents RegExpIdentifierStart :: \ RegExpUnicodeEscapeSequence RegExpIdentifierStart :: UnicodeLeadSurrogate UnicodeTrailSurrogate RegExpIdentifierPart :: \ RegExpUnicodeEscapeSequence RegExpIdentifierPart :: UnicodeLeadSurrogate UnicodeTrailSurrogate UnicodePropertyValueExpression :: UnicodePropertyName = UnicodePropertyValue
  • UnicodePropertyName 이 매치한 소스 텍스트가 Table 67 의 “Property name and aliases” 열에 열거된 유니코드 속성 이름 또는 속성 별칭이 아니면 구문 오류이다.
  • UnicodePropertyValue 가 매치한 소스 텍스트가 UnicodePropertyName 이 매치한 소스 텍스트로 주어진 유니코드 속성 또는 속성 별칭에 대해 PropertyValueAliases.txt 에 열거된 속성 값 또는 속성 값 별칭이 아니면 구문 오류이다.
UnicodePropertyValueExpression :: LoneUnicodePropertyNameOrValue
  • LoneUnicodePropertyNameOrValue 가 매치한 소스 텍스트가 General_Category (gc) 속성에 대한 PropertyValueAliases.txt 에 열거된 속성 값 또는 그 별칭도 아니고, Table 68 의 “Property name and aliases” 열에 열거된 바이너리 속성 또는 그 별칭도 아니며, Table 69 의 “Property name” 열에 열거된 문자열의 바이너리 속성도 아니면 구문 오류이다.
  • 둘러싼 Pattern[UnicodeSetsMode] 매개변수를 가지지 않고 LoneUnicodePropertyNameOrValue 가 매치한 소스 텍스트가 Table 69 의 “Property name” 열에 열거된 문자열의 바이너리 속성이라면 구문 오류이다.
CharacterClassEscape :: P{ UnicodePropertyValueExpression } CharacterClass :: [^ ClassContents ]
  • ClassContents 의 MayContainStrings 가 true 이면 구문 오류이다.
NestedClass :: [^ ClassContents ]
  • ClassContents 의 MayContainStrings 가 true 이면 구문 오류이다.
ClassSetRange :: ClassSetCharacter - ClassSetCharacter

22.2.1.2 정적 의미론: CountLeftCapturingParensWithin ( node: 구문 노드, ): 음이 아닌 정수

The abstract operation UNKNOWN takes UNPARSEABLE ARGUMENTS. node 에 있는 좌측 캡처 괄호(left-capturing parentheses)의 개수를 반환한다. 좌측 캡처 괄호 Atom :: ( GroupSpecifieropt Disjunction ) 생성 규칙의 ( 단말 기호에 의해 매치되는 모든 ( 패턴 문자이다.

Note

이 절은 B.1.2.2 에서 수정된다.

It performs the following steps when called:

  1. Assert: nodeRegExp 패턴 문법 의 어떤 생성 규칙 인스턴스이다.
  2. node 에 포함된 Atom :: ( GroupSpecifieropt Disjunction ) 구문 노드들의 개수를 반환한다.

22.2.1.3 정적 의미론: CountLeftCapturingParensBefore ( node: 구문 노드, ): 음이 아닌 정수

The abstract operation UNKNOWN takes UNPARSEABLE ARGUMENTS. 포함하는 패턴 내에서 node 의 왼쪽에 나타나는 좌측 캡처 괄호의 개수를 반환한다.

Note

이 절은 B.1.2.2 에서 수정된다.

It performs the following steps when called:

  1. Assert: nodeRegExp 패턴 문법 의 어떤 생성 규칙 인스턴스이다.
  2. patternnode 를 포함하는 Pattern 으로 둔다.
  3. pattern 내에서 node 앞에 나타나거나 node 를 포함하는 Atom :: ( GroupSpecifieropt Disjunction ) 구문 노드의 개수를 반환한다.

22.2.1.4 정적 의미론: MightBothParticipate ( x: 구문 노드, y: 구문 노드, ): 불리언

The abstract operation UNKNOWN takes UNPARSEABLE ARGUMENTS. It performs the following steps when called:

  1. Assert: xy 는 동일한 둘러싼 Pattern 을 가진다.
  2. 둘러싼 Pattern Disjunction :: Alternative | Disjunction 구문 노드를 포함하고 xAlternative 내에, y 가 파생된 Disjunction 내에 있거나 그 반대라면 false 를 반환한다.
  3. true 를 반환한다.

22.2.1.5 정적 의미론: CapturingGroupNumber : 양의 정수

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS.

Note

이 절은 B.1.2.1 에서 수정된다.

It is defined piecewise over the following productions:

DecimalEscape :: NonZeroDigit
  1. NonZeroDigit 의 MV 를 반환한다.
DecimalEscape :: NonZeroDigit DecimalDigits
  1. nDecimalDigits 의 코드 포인트 개수로 둔다.
  2. (NonZeroDigit 의 MV × 10n + DecimalDigits 의 MV) 를 반환한다.

NonZeroDigit 의 MV”, “DecimalDigits 의 MV” 정의는 12.9.3 에 있다.

22.2.1.6 정적 의미론: IsCharacterClass : 불리언

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS.

Note

이 절은 B.1.2.3 에서 수정된다.

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 정적 의미론: CharacterValue : 음이 아닌 정수

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS.

Note 1

이 절은 B.1.2.4 에서 수정된다.

It is defined piecewise over the following productions:

ClassAtom :: -
  1. U+002D (HYPHEN-MINUS) 의 수치 값을 반환한다.
ClassAtomNoDash :: SourceCharacter but not one of \ or ] or -
  1. chSourceCharacter 가 매치한 코드 포인트로 둔다.
  2. ch 의 수치 값을 반환한다.
ClassEscape :: b
  1. U+0008 (BACKSPACE) 의 수치 값을 반환한다.
ClassEscape :: -
  1. U+002D (HYPHEN-MINUS) 의 수치 값을 반환한다.
CharacterEscape :: ControlEscape
  1. Table 65 에 따라 수치 값을 반환한다.
Table 65: ControlEscape 코드 포인트 값
ControlEscape 수치 값 코드 포인트 유니코드 이름 기호
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. chAsciiLetter 가 매치한 코드 포인트로 둔다.
  2. ich 의 수치 값으로 둔다.
  3. i 를 32 로 나눈 나머지를 반환한다.
CharacterEscape :: 0 [lookahead ∉ DecimalDigit]
  1. U+0000 (NULL) 의 수치 값을 반환한다.
Note 2

\0 은 <NUL> 문자를 나타내며 10진 숫자가 뒤따를 수 없다.

CharacterEscape :: HexEscapeSequence
  1. HexEscapeSequence 의 MV 를 반환한다.
RegExpUnicodeEscapeSequence :: u HexLeadSurrogate \u HexTrailSurrogate
  1. leadHexLeadSurrogate 의 CharacterValue 로 둔다.
  2. trailHexTrailSurrogate 의 CharacterValue 로 둔다.
  3. cp 를 UTF16SurrogatePairToCodePoint(lead, trail) 로 둔다.
  4. cp 의 수치 값을 반환한다.
RegExpUnicodeEscapeSequence :: u Hex4Digits
  1. Hex4Digits 의 MV 를 반환한다.
RegExpUnicodeEscapeSequence :: u{ CodePoint }
  1. CodePoint 의 MV 를 반환한다.
HexLeadSurrogate :: Hex4Digits HexTrailSurrogate :: Hex4Digits HexNonSurrogate :: Hex4Digits
  1. Hex4Digits 의 MV 를 반환한다.
CharacterEscape :: IdentityEscape
  1. chIdentityEscape 가 매치한 코드 포인트로 둔다.
  2. ch 의 수치 값을 반환한다.
ClassSetCharacter :: SourceCharacter but not ClassSetSyntaxCharacter
  1. chSourceCharacter 가 매치한 코드 포인트로 둔다.
  2. ch 의 수치 값을 반환한다.
ClassSetCharacter :: \ ClassSetReservedPunctuator
  1. chClassSetReservedPunctuator 가 매치한 코드 포인트로 둔다.
  2. ch 의 수치 값을 반환한다.
ClassSetCharacter :: \b
  1. U+0008 (BACKSPACE) 의 수치 값을 반환한다.

22.2.1.8 정적 의미론: MayContainStrings : 불리언

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. 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 가 매치한 소스 텍스트가 Table 69 의 “Property name” 열에 열거된 문자열의 바이너리 속성이면 true 를 반환한다.
  2. false 를 반환한다.
ClassUnion :: ClassSetRange ClassUnionopt
  1. ClassUnion 이 존재하면 그 ClassUnion 의 MayContainStrings 를 반환한다.
  2. false 를 반환한다.
ClassUnion :: ClassSetOperand ClassUnionopt
  1. ClassSetOperand 의 MayContainStrings 가 true 이면 true 를 반환한다.
  2. ClassUnion 이 존재하면 그 ClassUnion 의 MayContainStrings 를 반환한다.
  3. false 를 반환한다.
ClassIntersection :: ClassSetOperand && ClassSetOperand
  1. 첫 번째 ClassSetOperand 의 MayContainStrings 가 false 이면 false 를 반환한다.
  2. 두 번째 ClassSetOperand 의 MayContainStrings 가 false 이면 false 를 반환한다.
  3. true 를 반환한다.
ClassIntersection :: ClassIntersection && ClassSetOperand
  1. ClassIntersection 의 MayContainStrings 가 false 이면 false 를 반환한다.
  2. ClassSetOperand 의 MayContainStrings 가 false 이면 false 를 반환한다.
  3. true 를 반환한다.
ClassSubtraction :: ClassSetOperand -- ClassSetOperand
  1. 첫 번째 ClassSetOperand 의 MayContainStrings 를 반환한다.
ClassSubtraction :: ClassSubtraction -- ClassSetOperand
  1. ClassSubtraction 의 MayContainStrings 를 반환한다.
ClassStringDisjunctionContents :: ClassString | ClassStringDisjunctionContents
  1. ClassString 의 MayContainStrings 가 true 이면 true 를 반환한다.
  2. ClassStringDisjunctionContents 의 MayContainStrings 를 반환한다.
ClassString :: [empty]
  1. true 를 반환한다.
ClassString :: NonEmptyClassString
  1. NonEmptyClassString 의 MayContainStrings 를 반환한다.
NonEmptyClassString :: ClassSetCharacter NonEmptyClassStringopt
  1. NonEmptyClassString 이 존재하면 true 를 반환한다.
  2. false 를 반환한다.

22.2.1.9 정적 의미론: GroupSpecifiersThatMatch ( thisGroupName: GroupName 구문 노드, ): GroupSpecifier 구문 노드들의 리스트

The abstract operation UNKNOWN takes UNPARSEABLE ARGUMENTS. It performs the following steps when called:

  1. namethisGroupName 의 CapturingGroupName 으로 둔다.
  2. patternthisGroupName 을 포함하는 Pattern 으로 둔다.
  3. result 를 새 빈 리스트로 둔다.
  4. pattern 이 포함하는 각 GroupSpecifier gs 에 대해,
    1. gs 의 CapturingGroupName 이 name 과 같다면
      1. gsresult 에 추가한다.
  5. result 를 반환한다.

22.2.1.10 정적 의미론: CapturingGroupName : 문자열

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. It is defined piecewise over the following productions:

GroupName :: < RegExpIdentifierName >
  1. idTextUnescapedRegExpIdentifierName 의 RegExpIdentifierCodePoints 로 둔다.
  2. CodePointsToString(idTextUnescaped) 을 반환한다.

22.2.1.11 정적 의미론: RegExpIdentifierCodePoints : 코드 포인트들의 리스트

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. It is defined piecewise over the following productions:

RegExpIdentifierName :: RegExpIdentifierStart
  1. cpRegExpIdentifierStart 의 RegExpIdentifierCodePoint 로 둔다.
  2. « cp » 를 반환한다.
RegExpIdentifierName :: RegExpIdentifierName RegExpIdentifierPart
  1. cps 를 파생된 RegExpIdentifierName 의 RegExpIdentifierCodePoints 로 둔다.
  2. cpRegExpIdentifierPart 의 RegExpIdentifierCodePoint 로 둔다.
  3. cps 와 « cp » 의 리스트 연결(list-concatenation)을 반환한다.

22.2.1.12 정적 의미론: RegExpIdentifierCodePoint : 코드 포인트

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. It is defined piecewise over the following productions:

RegExpIdentifierStart :: IdentifierStartChar
  1. IdentifierStartChar 가 매치한 코드 포인트를 반환한다.
RegExpIdentifierPart :: IdentifierPartChar
  1. IdentifierPartChar 가 매치한 코드 포인트를 반환한다.
RegExpIdentifierStart :: \ RegExpUnicodeEscapeSequence RegExpIdentifierPart :: \ RegExpUnicodeEscapeSequence
  1. 수치 값이 RegExpUnicodeEscapeSequence 의 CharacterValue 인 코드 포인트를 반환한다.
RegExpIdentifierStart :: UnicodeLeadSurrogate UnicodeTrailSurrogate RegExpIdentifierPart :: UnicodeLeadSurrogate UnicodeTrailSurrogate
  1. leadUnicodeLeadSurrogate 가 매치한 코드 포인트의 수치 값과 동일한 수치 값을 가진 코드 유닛으로 둔다.
  2. trailUnicodeTrailSurrogate 가 매치한 코드 포인트의 수치 값과 동일한 수치 값을 가진 코드 유닛으로 둔다.
  3. UTF16SurrogatePairToCodePoint(lead, trail) 을 반환한다.

22.2.2 패턴 의미론 (Pattern Semantics)

정규 표현식 패턴은 아래에 서술된 과정을 통해 추상 클로저(Abstract Closure)로 변환된다. 구현체는 결과가 동일한 한, 아래에 열거된 것보다 더 효율적인 알고리즘을 사용하는 것이 권장된다. 이렇게 생성된 추상 클로저는 RegExp 객체의 [[RegExpMatcher]] 내부 슬롯 값으로 사용된다.

Pattern 은 관련 플래그에 uv 둘 다 포함되지 않으면 BMP 패턴이고, 그렇지 않으면 유니코드 패턴이다. BMP 패턴은 입력 문자열을 BMP(기본 다국어 평면) 범위의 유니코드 코드 포인트들로 구성된 16비트 값 시퀀스로 해석하여 매칭한다. 유니코드 패턴은 입력 문자열을 UTF-16 으로 인코딩된 유니코드 코드 포인트 시퀀스로 해석하여 매칭한다. BMP 패턴의 동작을 설명하는 문맥에서 “문자(character)”는 단일 16비트 유니코드 BMP 코드 포인트를 의미한다. 유니코드 패턴의 동작을 설명하는 문맥에서 “문자”는 UTF-16 으로 인코딩된 하나의 코드 포인트를 의미한다 (6.1.4). 두 문맥 모두에서 “문자 값(character value)”은 해당 (인코딩되지 않은) 코드 포인트의 수치 값을 의미한다.

Pattern 의 구문 및 의미는 Pattern 의 소스 텍스트가 각 SourceCharacter 가 하나의 유니코드 코드 포인트에 대응하는 SourceCharacter 값들의 리스트인 것처럼 정의된다. 만약 BMP 패턴이 BMP가 아닌 SourceCharacter 를 포함한다면 전체 패턴은 UTF-16 으로 인코딩되고, 그 인코딩을 이루는 개별 코드 유닛들이 리스트의 요소로 사용된다.

Note

예를 들어, 소스 텍스트에서 하나의 비-BMP 문자 U+1D11E (MUSICAL SYMBOL G CLEF) 로 표현된 패턴을 생각하자. 유니코드 패턴으로 해석하면 단일 코드 포인트 U+1D11E 를 포함하는 (문자 1개짜리) 단일 요소 리스트가 된다. 그러나 BMP 패턴으로 해석하면 먼저 UTF-16 으로 인코딩되어 코드 유닛 0xD834 와 0xDD1E 두 요소로 이루어진 리스트가 된다.

패턴은 RegExp 생성자에 비-BMP 문자가 UTF-16 으로 인코딩된 ECMAScript 문자열 값으로 전달된다. 예를 들어, 단일 문자 MUSICAL SYMBOL G CLEF 패턴은 길이 2의 문자열로서 그 요소가 코드 유닛 0xD834 와 0xDD1E 이다. 따라서 이를 두 개의 패턴 문자로 이루어진 BMP 패턴으로 처리하기 위해 추가 변환이 필요하지 않다. 그러나 이를 유니코드 패턴으로 처리하려면 UTF16SurrogatePairToCodePoint 를 사용하여 하나의 패턴 문자(코드 포인트 U+1D11E)만을 요소로 갖는 리스트를 생성해야 한다.

구현체는 실제로 UTF-16 으로의 변환이나 역변환을 수행하지 않을 수 있으나, 이 명세의 의미론은 패턴 매칭 결과가 마치 그러한 변환이 수행된 것과 동일해야 한다고 요구한다.

22.2.2.1 표기법 (Notation)

아래 설명에서는 다음의 내부 데이터 구조를 사용한다:

  • CharSetElement 는 다음 두 가지 중 하나이다:
    • rer.[[UnicodeSets]]false 이면 CharSetElement 는 위 패턴 의미론의 문맥에서 “문자” 하나이다.
    • rer.[[UnicodeSets]]true 이면 CharSetElement 는 위 패턴 의미론의 문맥에서 “문자”들로 이루어진 시퀀스이다. 여기에는 빈 시퀀스, 한 문자 시퀀스, 두 문자 이상 시퀀스가 모두 포함된다. 편의를 위해 이런 종류의 CharSetElement 를 다룰 때 개별 문자는 한 문자로 이루어진 시퀀스와 상호 교환적으로 취급된다.
  • CharSet 은 CharSetElement 들의 수학적 집합이다.
  • CaptureRange 는 { [[StartIndex]], [[EndIndex]] } 형태의 레코드로, 캡처에 포함된 문자 범위를 나타낸다. [[StartIndex]]Input 내에서 범위 시작(포함)의 정수 인덱스, [[EndIndex]] 는 범위 끝(배타)의 정수 인덱스이다. 모든 CaptureRange 에 대해 [[StartIndex]][[EndIndex]] 조건(불변식)을 만족해야 한다.
  • MatchState 는 { [[Input]], [[EndIndex]], [[Captures]] } 형태의 레코드이며, [[Input]] 은 매칭 중인 문자열을 나타내는 문자들의 리스트, [[EndIndex]] 는 정수, [[Captures]] 는 패턴 안의 각 좌측 캡처 괄호에 대응하는 값들의 리스트이다. MatchState 는 정규 표현식 매칭 알고리즘에서 부분 매칭 상태를 표현한다. [[EndIndex]] 는 지금까지 패턴이 매치한 마지막 입력 문자의 인덱스보다 1 큰 값이며, [[Captures]] 는 캡처 괄호의 결과를 담는다. [[Captures]]n번째 요소는 n번째 캡처 괄호가 캡처한 문자 범위를 나타내는 CaptureRange 이거나, 해당 캡처 괄호에 아직 도달하지 않았다면 undefined 이다. 백트래킹 때문에 매칭 과정 중 언제든 다수의 MatchState 가 사용될 수 있다.
  • MatcherContinuation 은 하나의 MatchState 인수를 받아 MatchState 또는 failure 를 반환하는 추상 클로저이다. MatcherContinuation 은 (클로저의 캡처된 값들에 의해 지정되는) 패턴의 남은 부분을 Input 에 대해, 인수로 전달된 MatchState 가 나타내는 중간 상태부터 매칭하려 시도한다. 매칭이 성공하면 도달한 최종 MatchState 를 반환하고, 실패하면 failure 를 반환한다.
  • Matcher 는 두 인수(하나는 MatchState, 다른 하나는 MatcherContinuation)를 받아 MatchState 또는 failure 를 반환하는 추상 클로저이다. Matcher 는 (클로저의 캡처된 값들에 의해 지정되는) 패턴의 중간 부분(subpattern)을 MatchState[[Input]] 에 대해, 인수 MatchState 가 나타내는 중간 상태부터 매칭하려 시도한다. MatcherContinuation 인수는 패턴의 나머지를 매칭하는 클로저여야 한다. 서브패턴을 매칭해 새 MatchState 를 얻은 뒤, Matcher 는 그 새 MatchStateMatcherContinuation 을 호출하여 패턴의 나머지 부분도 매칭 가능한지 시험한다. 가능하면 MatcherMatcherContinuation 이 반환한 MatchState 를 반환하며, 그렇지 않으면 가능한 선택 지점(choice point)에서 다른 선택을 시도하고, 성공하거나 모든 가능성이 소진될 때까지 MatcherContinuation 을 반복 호출할 수 있다.

22.2.2.1.1 RegExp 레코드 (RegExp Records)

RegExp Record 는 컴파일 과정 및 (필요하다면) 매칭 과정에서 필요한 RegExp 관련 정보를 저장하기 위해 사용되는 레코드 값이다.

다음 필드들을 가진다:

Table 66: RegExp Record 필드
필드 이름 의미
[[IgnoreCase]] Boolean RegExp 플래그에 "i" 가 나타나는지 여부
[[Multiline]] Boolean RegExp 플래그에 "m" 가 나타나는지 여부
[[DotAll]] Boolean RegExp 플래그에 "s" 가 나타나는지 여부
[[Unicode]] Boolean RegExp 플래그에 "u" 가 나타나는지 여부
[[UnicodeSets]] Boolean RegExp 플래그에 "v" 가 나타나는지 여부
[[CapturingGroupsCount]] 음이 아닌 정수 패턴 내 좌측 캡처 괄호의 개수

22.2.2.2 런타임 의미론: CompilePattern : 문자 리스트와 음이 아닌 정수를 받아 MatchState 또는 failure 를 반환하는 추상 클로저

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. It is defined piecewise over the following productions:

Pattern :: Disjunction
  1. mDisjunction 에 대해 인수 rer, forward 로 CompileSubpattern 한 결과로 둔다.
  2. rerm 을 캡처하고, 매개변수 (Input, index) 를 가지며 호출 시 다음 단계를 수행하는 새 추상 클로저를 반환한다:
    1. Assert: Input 은 문자들의 리스트이다.
    2. Assert: 0 ≤ indexInput 의 요소 개수.
    3. c 를 매개변수 (y) 를 가지며 아무것도 캡처하지 않고 호출 시 다음 단계를 수행하는 새 MatcherContinuation 으로 둔다:
      1. Assert: yMatchState.
      2. y 를 반환한다.
    4. caprer.[[CapturingGroupsCount]] 개의 undefined 값(인덱스 1..rer.[[CapturingGroupsCount]])을 가진 리스트로 둔다.
    5. xMatchState { [[Input]]: Input, [[EndIndex]]: index, [[Captures]]: cap } 로 둔다.
    6. m(x, c) 를 반환한다.
Note

Pattern 은 추상 클로저 값으로 컴파일된다. RegExpBuiltinExec 는 그런 절차를 문자 리스트와 그 안의 오프셋에 적용하여, 패턴이 정확히 그 오프셋에서 매칭되는지, 그리고 매칭된다면 캡처 괄호 값이 무엇인지 결정할 수 있다. 22.2.2 의 알고리즘들은 패턴 컴파일이 SyntaxError 예외를 던질 수 있도록 설계되어 있다; 반면 패턴이 성공적으로 컴파일된 후에는 (메모리 부족 등 구현 정의 예외를 제외하고) 결과 추상 클로저를 적용하여 문자 리스트에서 매칭을 찾는 동작이 예외를 던지지 않는다.

22.2.2.3 런타임 의미론: CompileSubpattern : Matcher

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS.

Note 1

이 절은 B.1.2.5 에서 수정된다.

It is defined piecewise over the following productions:

Disjunction :: Alternative | Disjunction
  1. m1Alternative 에 대해 인수 rer, direction 으로 CompileSubpattern 한 결과로 둔다.
  2. m2Disjunction 에 대해 인수 rer, direction 으로 CompileSubpattern 한 결과로 둔다.
  3. MatchTwoAlternatives(m1, m2) 를 반환한다.
Note 2

| 연산자는 두 개의 대안을 구분한다. 패턴은 먼저 왼쪽 Alternative (및 뒤따르는 정규 표현식 나머지)를 매칭 시도하고, 실패하면 오른쪽 Disjunction (및 나머지)를 매칭 시도한다. 왼쪽 Alternative, 오른쪽 Disjunction, 그리고 나머지가 모두 선택 지점(choice point)을 가진다면, 왼쪽 Alternative 의 다음 선택으로 진행하기 전에 나머지의 모든 선택을 시도한다. 왼쪽 Alternative 의 선택이 다 소진되면 왼쪽 대신 오른쪽 Disjunction 을 시도한다. | 로 건너뛰어진 패턴 부분 내의 캡처 괄호는 문자열이 아니라 undefined 값을 생성한다. 예:

/a|ab/.exec("abc")

는 결과 "a" 를 반환하며 "ab" 가 아니다. 또한,

/((a)|(ab))((c)|(bc))/.exec("abc")

는 배열

["abc", "a", "a", undefined, "bc", undefined, "bc"]

를 반환하고,

["abc", "ab", undefined, "ab", "c", "c", undefined]

는 아니다. 두 대안을 시도하는 순서는 direction 값과 무관하다.

Alternative :: [empty]
  1. EmptyMatcher() 를 반환한다.
Alternative :: Alternative Term
  1. m1Alternative 에 대해 인수 rer, direction 으로 CompileSubpattern 한 결과로 둔다.
  2. m2Term 에 대해 인수 rer, direction 으로 CompileSubpattern 한 결과로 둔다.
  3. MatchSequence(m1, m2, direction) 를 반환한다.
Note 3

연속된 Term 들은 Input 의 연속된 부분들을 동시에 매칭하려 시도한다. directionforward 일 때, 왼쪽 Alternative, 오른쪽 Term, 그리고 나머지에 모두 선택 지점이 있다면 오른쪽 Term 의 다음 선택으로 가기 전에 나머지의 모든 선택을 시도하고, 왼쪽 Alternative 의 다음 선택으로 가기 전에 오른쪽 Term 의 모든 선택을 시도한다. directionbackward 이면 AlternativeTerm 의 평가 순서가 반전된다.

Term :: Assertion
  1. Assertion 에 대해 인수 rer 로 CompileAssertion 한 결과를 반환한다.
Note 4

결과 Matcherdirection 과 무관하다.

Term :: Atom
  1. Atom 에 대해 인수 rer, direction 으로 CompileAtom 한 결과를 반환한다.
Term :: Atom Quantifier
  1. mAtom 에 대해 인수 rer, direction 으로 CompileAtom 한 결과로 둔다.
  2. qQuantifier 에 대해 CompileQuantifier 한 결과로 둔다.
  3. Assert: q.[[Min]]q.[[Max]].
  4. parenIndex 를 CountLeftCapturingParensBefore(Term) 로 둔다.
  5. parenCount 를 CountLeftCapturingParensWithin(Atom) 으로 둔다.
  6. m, q, parenIndex, parenCount 를 캡처하고 매개변수 (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, x, c, parenIndex, parenCount )

The abstract operation RepeatMatcher takes arguments m (Matcher), min (음이 아닌 정수), max (음이 아닌 정수 또는 +∞), greedy (Boolean), x (MatchState), c (MatcherContinuation), parenIndex (음이 아닌 정수), and parenCount (음이 아닌 정수) and returns MatchState 또는 failure. It performs the following steps when called:

  1. max = 0 이면 c(x) 를 반환한다.
  2. d 를 매개변수 (y) 를 가지며 m, min, max, greedy, x, c, parenIndex, parenCount 를 캡처하고 호출 시 다음을 수행하는 새 MatcherContinuation 으로 둔다:
    1. Assert: yMatchState.
    2. min = 0 이고 y.[[EndIndex]] = x.[[EndIndex]] 이면 failure 를 반환한다.
    3. min = 0 이면 min2 = 0, 그렇지 않으면 min2 = min - 1 로 둔다.
    4. max = +∞ 이면 max2 = +∞, 아니면 max2 = max - 1 로 둔다.
    5. RepeatMatcher(m, min2, max2, greedy, y, c, parenIndex, parenCount) 를 반환한다.
  3. capx.[[Captures]] 의 복사본으로 둔다.
  4. parenIndex + 1 부터 parenIndex + parenCount 까지 (포함) 정수 k 각각에 대해 cap[k] = undefined 로 설정한다.
  5. Inputx.[[Input]] 으로 둔다.
  6. ex.[[EndIndex]] 로 둔다.
  7. xrMatchState { [[Input]]: Input, [[EndIndex]]: e, [[Captures]]: cap } 로 둔다.
  8. min ≠ 0 이면 m(xr, d) 를 반환한다.
  9. greedyfalse 이면
    1. zc(x) 로 둔다.
    2. zfailure 가 아니면 z 반환.
    3. m(xr, d) 를 반환한다.
  10. zm(xr, d) 로 둔다.
  11. zfailure 가 아니면 z 반환.
  12. c(x) 를 반환한다.
Note 1

Atom 뒤에 Quantifier 가 오면 Quantifier 가 지정한 횟수만큼 Atom 이 반복된다. Quantifier 는 비탐욕적(non-greedy)일 수 있으며, 이 경우 Atom 패턴은 나머지를 매칭 가능하게 유지하는 최소 횟수만 반복된다. 탐욕적(greedy)이면 가능한 한 많이 반복된다. 반복되는 것은 입력 문자 시퀀스가 아니라 Atom 패턴이므로 각 반복은 서로 다른 입력 부분 문자열을 매칭할 수 있다.

Note 2

Atom 과 정규 표현식의 나머지가 모두 선택 지점을 가진다면, Atom 은 먼저 가능한 많이(또는 비탐욕적이면 가능한 적게) 매칭된다. 나머지 부분의 모든 선택이 소진되기 전까지 Atom 의 마지막 반복의 다음 선택으로 이동하지 않는다. 마지막 (n번째) 반복의 모든 선택이 소진되기 전까지 (n - 1)번째 반복의 다음 선택으로 이동하지 않는다. 그 시점에서 Atom 을 더 많이 또는 더 적게 반복할 수 있게 될 수도 있으며, (다시 최소 또는 최대부터 시작하여) 이것들을 소진한 뒤 (n - 1)번째 반복의 다음 선택으로 이동한다.

비교:

/a[a-z]{2,4}/.exec("abcdefghi")

"abcde" 를 반환하고,

/a[a-z]{2,4}?/.exec("abcdefghi")

"abc" 를 반환한다.

또한,

/(aa|aabaac|ba|b|c)*/.exec("aabaac")

는 위 선택 지점 순서에 따라 배열

["aaba", "ba"]

를 반환하며, 아래 어느 것도 아니다:

["aabaac", "aabaac"]
["aabaac", "c"]

위 선택 지점 순서는 (단항 표기) 두 수의 최대공약수를 계산하는 정규 표현식을 작성하는 데 사용될 수 있다. 다음 예는 10 과 15 의 gcd 를 계산한다:

"aaaaaaaaaa,aaaaaaaaaaaaaaa".replace(/^(a+)\1*,\1+$/, "$1")

이는 단항 표기 gcd "aaaaa" 를 반환한다.

Note 3

RepeatMatcher 의 단계 4Atom 이 반복될 때마다 해당 Atom 의 캡처를 지운다. 이는 다음 정규 표현식을 통해 확인할 수 있다:

/(z)((a+)?(b+)?(c))*/.exec("zaacbbbcac")

이 표현식은 배열

["zaacbbbcac", "z", "ac", "a", undefined, "c"]

를 반환하고,

["zaacbbbcac", "z", "ac", "a", "bbb", "c"]

를 반환하지 않는다. 이는 가장 바깥 * 의 각 반복이 수량자 적용 대상 Atom 에 포함된 모든 캡처 문자열(여기서는 2, 3, 4, 5 번 캡처)을 비우기 때문이다.

Note 4

RepeatMatcher 의 단계 2.b 는 최소 반복 횟수를 만족한 후, 빈 문자 시퀀스를 매칭하는 Atom 의 추가 확장은 더 이상 고려하지 않는다고 명시한다. 이는 다음과 같은 패턴에서 엔진이 무한 루프에 빠지는 것을 방지한다:

/(a*)*/.exec("b")

혹은 조금 더 복잡한 패턴:

/(a*)b\1+/.exec("baaaac")

이는 배열

["b", ""]

를 반환한다.

22.2.2.3.2 EmptyMatcher ( )

The abstract operation EmptyMatcher takes no arguments and returns Matcher. It performs the following steps when called:

  1. 아무것도 캡처하지 않고 매개변수 (x, c) 를 가지며 호출 시 다음을 수행하는 새 Matcher 를 반환한다:
    1. Assert: xMatchState.
    2. Assert: cMatcherContinuation.
    3. c(x) 를 반환한다.

22.2.2.3.3 MatchTwoAlternatives ( m1, m2 )

The abstract operation MatchTwoAlternatives takes arguments m1 (Matcher) and m2 (Matcher) and returns Matcher. It performs the following steps when called:

  1. m1, m2 를 캡처하고 매개변수 (x, c) 를 가지며 호출 시 다음을 수행하는 새 Matcher 를 반환한다:
    1. Assert: xMatchState.
    2. Assert: cMatcherContinuation.
    3. rm1(x, c) 로 둔다.
    4. rfailure 가 아니면 r 반환.
    5. m2(x, c) 를 반환한다.

22.2.2.3.4 MatchSequence ( m1, m2, direction )

The abstract operation MatchSequence takes arguments m1 (Matcher), m2 (Matcher), and direction (forward 또는 backward) and returns Matcher. It performs the following steps when called:

  1. directionforward 이면
    1. m1, m2 를 캡처하고 매개변수 (x, c) 를 가지며 호출 시 다음을 수행하는 새 Matcher 를 반환한다:
      1. Assert: xMatchState.
      2. Assert: cMatcherContinuation.
      3. d 를 매개변수 (y) 를 가지며 c, m2 를 캡처하고 호출 시 다음을 수행하는 새 MatcherContinuation 으로 둔다:
        1. Assert: yMatchState.
        2. m2(y, c) 를 반환한다.
      4. m1(x, d) 를 반환한다.
  2. 그렇지 않으면,
    1. Assert: directionbackward.
    2. m1, m2 를 캡처하고 매개변수 (x, c) 를 가지며 호출 시 다음을 수행하는 새 Matcher 를 반환한다:
      1. Assert: xMatchState.
      2. Assert: cMatcherContinuation.
      3. d 를 매개변수 (y) 를 가지며 c, m1 을 캡처하고 호출 시 다음을 수행하는 새 MatcherContinuation 으로 둔다:
        1. Assert: yMatchState.
        2. m1(y, c) 를 반환한다.
      4. m2(x, d) 를 반환한다.

22.2.2.4 런타임 의미론: CompileAssertion : Matcher

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS.

Note 1

이 절은 B.1.2.6 에서 수정된다.

It is defined piecewise over the following productions:

Assertion :: ^
  1. rer 를 캡처하고 매개변수 (x, c) 를 가지며 호출 시 다음을 수행하는 새 Matcher 를 반환한다:
    1. Assert: xMatchState.
    2. Assert: cMatcherContinuation.
    3. Inputx.[[Input]] 으로 둔다.
    4. ex.[[EndIndex]] 로 둔다.
    5. e = 0 이거나 (rer.[[Multiline]]true 이고 문자 Input[e - 1] 이 LineTerminator 에 매치되면)
      1. c(x) 를 반환한다.
    6. failure 를 반환한다.
Note 2

y 플래그를 사용해도 ^ 는 항상 Input 의 시작(또는 rer.[[Multiline]]true 이면 줄의 시작)에서만 매치된다.

Assertion :: $
  1. rer 를 캡처하고 매개변수 (x, c) 를 가지며 호출 시 다음을 수행하는 새 Matcher 를 반환한다:
    1. Assert: xMatchState.
    2. Assert: cMatcherContinuation.
    3. Inputx.[[Input]] 으로 둔다.
    4. ex.[[EndIndex]] 로 둔다.
    5. InputLengthInput 의 요소 개수로 둔다.
    6. e = InputLength 이거나 (rer.[[Multiline]]true 이고 문자 Input[e] 가 LineTerminator 에 매치되면)
      1. c(x) 를 반환한다.
    7. failure 를 반환한다.
Assertion :: \b
  1. rer 를 캡처하고 매개변수 (x, c) 를 가지며 호출 시 다음을 수행하는 새 Matcher 를 반환한다:
    1. Assert: xMatchState.
    2. Assert: cMatcherContinuation.
    3. Inputx.[[Input]] 으로 둔다.
    4. ex.[[EndIndex]] 로 둔다.
    5. aIsWordChar(rer, Input, e - 1) 로 둔다.
    6. bIsWordChar(rer, Input, e) 로 둔다.
    7. (atrue 이고 bfalse) 또는 (afalse 이고 btrue) 이면 c(x) 반환.
    8. failure 반환.
Assertion :: \B
  1. rer 를 캡처하고 매개변수 (x, c) 를 가지며 호출 시 다음을 수행하는 새 Matcher 를 반환한다:
    1. Assert: xMatchState.
    2. Assert: cMatcherContinuation.
    3. Inputx.[[Input]] 으로 둔다.
    4. ex.[[EndIndex]] 로 둔다.
    5. aIsWordChar(rer, Input, e - 1) 로 둔다.
    6. bIsWordChar(rer, Input, e) 로 둔다.
    7. (ab 가 모두 true) 또는 (ab 가 모두 false) 이면 c(x) 반환.
    8. failure 반환.
Assertion :: (?= Disjunction )
  1. mDisjunction 에 대해 인수 rer, forward 로 CompileSubpattern 한 결과로 둔다.
  2. m 을 캡처하고 매개변수 (x, c) 를 가지며 호출 시 다음을 수행하는 새 Matcher 를 반환한다:
    1. Assert: xMatchState.
    2. Assert: cMatcherContinuation.
    3. d 를 매개변수 (y) 를 가지며 아무것도 캡처하지 않고 호출 시 다음을 수행하는 새 MatcherContinuation 으로 둔다:
      1. Assert: yMatchState.
      2. y 반환.
    4. rm(x, d) 로 둔다.
    5. rfailure 이면 failure 반환.
    6. Assert: rMatchState.
    7. capr.[[Captures]] 로 둔다.
    8. Inputx.[[Input]] 으로 둔다.
    9. xex.[[EndIndex]] 로 둔다.
    10. zMatchState { [[Input]]: Input, [[EndIndex]]: xe, [[Captures]]: cap } 로 둔다.
    11. c(z) 반환.
Note 3

(?= Disjunction ) 형식은 폭 0 양수 전방 탐색(positive lookahead)을 지정한다. 성공하려면 Disjunction 내부 패턴이 현재 위치에서 매치되어야 하지만, 나머지를 매칭하기 전에 현재 위치는 전진하지 않는다. Disjunction 이 현재 위치에서 여러 방식으로 매치 가능하면 첫 번째 방식만 시도된다. 다른 정규 표현식 연산자와 달리 (?= 형식 안으로의 백트래킹은 없다(이 비정상적 동작은 Perl 에서 유래). 이는 Disjunction 이 캡처 괄호를 포함하고 패턴의 나머지 부분이 그 캡처에 대한 역참조를 포함할 때에만 중요하다.

예:

/(?=(a+))/.exec("baaabac")

는 첫 번째 b 직후 빈 문자열을 매치하므로 배열:

["", "aaa"]

를 반환한다.

전방 탐색 내부로의 백트래킹 부재를 보여주기 위해:

/(?=(a+))a*b\1/.exec("baaabac")

이 표현식은

["aba", "a"]

를 반환하며,

["aaaba", "a"]

는 아니다.

Assertion :: (?! Disjunction )
  1. mDisjunction 에 대해 인수 rer, forward 로 CompileSubpattern 한 결과로 둔다.
  2. m 을 캡처하고 매개변수 (x, c) 를 가지며 호출 시 다음을 수행하는 새 Matcher 를 반환한다:
    1. Assert: xMatchState.
    2. Assert: cMatcherContinuation.
    3. d 를 매개변수 (y) 를 가지며 아무것도 캡처하지 않고 호출 시 다음을 수행하는 새 MatcherContinuation 으로 둔다:
      1. Assert: yMatchState.
      2. y 반환.
    4. rm(x, d) 로 둔다.
    5. rfailure 가 아니면 failure 반환.
    6. c(x) 반환.
Note 4

(?! Disjunction ) 형식은 폭 0 음수 전방 탐색(negative lookahead)을 지정한다. 성공하려면 Disjunction 내부 패턴이 현재 위치에서 매치에 실패해야 한다. 현재 위치는 나머지를 매칭하기 전에 전진하지 않는다. Disjunction 은 캡처 괄호를 포함할 수 있지만, 그 캡처에 대한 역참조는 Disjunction 내부에서만 의미가 있다. 패턴의 다른 부분에서 이 캡처에 대한 역참조는 항상 undefined 를 반환하는데, 음수 전방 탐색은 실패해야 전체 패턴이 성공하기 때문이다. 예:

/(.*?)a(?!(a+)b\2c)\2(.*)/.exec("baaabaac")

이 표현식은 a 뒤에 즉시 n 개의 a, 하나의 b, 다시 n 개의 a(첫 번째 \2 로 지정), 그리고 c 가 오는 패턴이 아닌 경우를 찾는다. 두 번째 \2 는 음수 전방 탐색 밖에 있으므로 undefined 와 매치되어 항상 성공한다. 전체 표현식은 배열:

["baaabaac", "ba", undefined, "abaac"]

을 반환한다.

Assertion :: (?<= Disjunction )
  1. mDisjunction 에 대해 인수 rer, backward 로 CompileSubpattern 한 결과로 둔다.
  2. m 을 캡처하고 매개변수 (x, c) 를 가지며 호출 시 다음을 수행하는 새 Matcher 를 반환한다:
    1. Assert: xMatchState.
    2. Assert: cMatcherContinuation.
    3. d 를 매개변수 (y) 를 가지며 아무것도 캡처하지 않고 호출 시 다음을 수행하는 새 MatcherContinuation 으로 둔다:
      1. Assert: yMatchState.
      2. y 반환.
    4. rm(x, d) 로 둔다.
    5. rfailure 이면 failure 반환.
    6. Assert: rMatchState.
    7. capr.[[Captures]] 로 둔다.
    8. Inputx.[[Input]] 으로 둔다.
    9. xex.[[EndIndex]] 로 둔다.
    10. zMatchState { [[Input]]: Input, [[EndIndex]]: xe, [[Captures]]: cap } 로 둔다.
    11. c(z) 반환.
Assertion :: (?<! Disjunction )
  1. mDisjunction 에 대해 인수 rer, backward 로 CompileSubpattern 한 결과로 둔다.
  2. m 을 캡처하고 매개변수 (x, c) 를 가지며 호출 시 다음을 수행하는 새 Matcher 를 반환한다:
    1. Assert: xMatchState.
    2. Assert: cMatcherContinuation.
    3. d 를 매개변수 (y) 를 가지며 아무것도 캡처하지 않고 호출 시 다음을 수행하는 새 MatcherContinuation 으로 둔다:
      1. Assert: yMatchState.
      2. y 반환.
    4. rm(x, d) 로 둔다.
    5. rfailure 가 아니면 failure 반환.
    6. c(x) 반환.

22.2.2.4.1 IsWordChar ( rer, Input, e )

The abstract operation IsWordChar takes arguments rer (RegExp Record), Input (문자 리스트), and e (정수) and returns Boolean. It performs the following steps when called:

  1. InputLengthInput 의 요소 개수로 둔다.
  2. e = -1 또는 e = InputLength 이면 false 반환.
  3. c 를 문자 Input[e] 로 둔다.
  4. WordCharacters(rer) 가 c 를 포함하면 true 반환.
  5. false 반환.

22.2.2.5 런타임 의미론: CompileQuantifier 필드를 갖는 레코드

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. It is defined piecewise over the following productions:

Quantifier :: QuantifierPrefix
  1. qpQuantifierPrefix 에 대해 CompileQuantifierPrefix 한 결과로 둔다.
  2. { [[Min]]: qp.[[Min]], [[Max]]: qp.[[Max]], [[Greedy]]: true } 레코드를 반환한다.
Quantifier :: QuantifierPrefix ?
  1. qpQuantifierPrefix 에 대해 CompileQuantifierPrefix 한 결과로 둔다.
  2. { [[Min]]: qp.[[Min]], [[Max]]: qp.[[Max]], [[Greedy]]: false } 레코드를 반환한다.

22.2.2.6 런타임 의미론: CompileQuantifierPrefix 필드를 갖는 레코드

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. It is defined piecewise over the following productions:

QuantifierPrefix :: *
  1. { [[Min]]: 0, [[Max]]: +∞ } 반환.
QuantifierPrefix :: +
  1. { [[Min]]: 1, [[Max]]: +∞ } 반환.
QuantifierPrefix :: ?
  1. { [[Min]]: 0, [[Max]]: 1 } 반환.
QuantifierPrefix :: { DecimalDigits }
  1. iDecimalDigits 의 MV ( 12.9.3 참조 ) 로 둔다.
  2. { [[Min]]: i, [[Max]]: i } 반환.
QuantifierPrefix :: { DecimalDigits ,}
  1. iDecimalDigits 의 MV 로 둔다.
  2. { [[Min]]: i, [[Max]]: +∞ } 반환.
QuantifierPrefix :: { DecimalDigits , DecimalDigits }
  1. i 를 첫 번째 DecimalDigits 의 MV 로 둔다.
  2. j 를 두 번째 DecimalDigits 의 MV 로 둔다.
  3. { [[Min]]: i, [[Max]]: j } 반환.

22.2.2.7 런타임 의미론: CompileAtom : Matcher

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS.

Note 1

이 절은 B.1.2.7 에서 수정된다.

It is defined piecewise over the following productions:

Atom :: PatternCharacter
  1. chPatternCharacter 가 매치한 문자로 둔다.
  2. A 를 문자 ch 하나를 포함하는 1요소 CharSet 으로 둔다.
  3. CharacterSetMatcher(rer, A, false, direction) 반환.
Atom :: .
  1. AAllCharacters(rer) 로 둔다.
  2. rer.[[DotAll]]true 가 아니면
    1. LineTerminator 생성 규칙 우변의 코드 포인트에 대응하는 문자들을 A 에서 제거한다.
  3. CharacterSetMatcher(rer, A, false, direction) 반환.
Atom :: CharacterClass
  1. ccCharacterClass 에 대해 인수 rer 로 CompileCharacterClass 한 결과로 둔다.
  2. cscc.[[CharSet]] 로 둔다.
  3. rer.[[UnicodeSets]]false 이거나, cs 의 모든 CharSetElement 가 단일 문자(또는 cs 가 비어 있음)로 구성된다면 CharacterSetMatcher(rer, cs, cc.[[Invert]], direction) 반환.
  4. Assert: cc.[[Invert]]false.
  5. lm 을 빈 Matcher 리스트로 둔다.
  6. cs 내에서 2 문자 이상인 각 CharSetElement s 에 대해 길이 내림차순으로 반복:
    1. cs2s 의 마지막 코드 포인트 하나를 포함하는 1요소 CharSet 으로 둔다.
    2. m2CharacterSetMatcher(rer, cs2, false, direction) 로 둔다.
    3. s 의 뒤에서 두 번째부터 역순으로 각 코드 포인트 c1 에 대해:
      1. cs1 을 코드 포인트 c1 하나를 포함하는 1요소 CharSet 으로 둔다.
      2. m1CharacterSetMatcher(rer, cs1, false, direction) 로 둔다.
      3. m2 = MatchSequence(m1, m2, direction) 로 설정.
    4. m2lm 에 추가.
  7. singles 를 단일 문자로 구성된 cs 의 모든 CharSetElement 를 포함하는 CharSet 으로 둔다.
  8. CharacterSetMatcher(rer, singles, false, direction) 를 lm 에 추가.
  9. cs 가 빈 문자 시퀀스를 포함하면 EmptyMatcher() 를 lm 에 추가.
  10. m2lm 의 마지막 Matcher 로 둔다.
  11. lm 의 뒤에서 두 번째 요소부터 역순으로 각 Matcher m1 에 대해:
    1. m2 = MatchTwoAlternatives(m1, m2) 로 설정.
  12. m2 반환.
Atom :: ( GroupSpecifieropt Disjunction )
  1. mDisjunction 에 대해 인수 rer, direction 으로 CompileSubpattern 한 결과로 둔다.
  2. parenIndex 를 CountLeftCapturingParensBefore(Atom) 로 둔다.
  3. direction, m, parenIndex 를 캡처하고 매개변수 (x, c) 를 가지며 호출 시 다음을 수행하는 새 Matcher 반환:
    1. Assert: xMatchState.
    2. Assert: cMatcherContinuation.
    3. d 를 매개변수 (y) 를 가지며 x, c, direction, parenIndex 를 캡처하고 호출 시 다음을 수행하는 새 MatcherContinuation 으로 둔다:
      1. Assert: yMatchState.
      2. capy.[[Captures]] 의 복사본으로 둔다.
      3. Inputx.[[Input]] 으로 둔다.
      4. xex.[[EndIndex]] 로 둔다.
      5. yey.[[EndIndex]] 로 둔다.
      6. directionforward 이면
        1. Assert: xeye.
        2. rCaptureRange { [[StartIndex]]: xe, [[EndIndex]]: ye } 로 둔다.
      7. 그렇지 않으면
        1. Assert: directionbackward.
        2. Assert: yexe.
        3. rCaptureRange { [[StartIndex]]: ye, [[EndIndex]]: xe } 로 둔다.
      8. cap[parenIndex + 1] = r 로 설정.
      9. zMatchState { [[Input]]: Input, [[EndIndex]]: ye, [[Captures]]: cap } 로 둔다.
      10. c(z) 반환.
    4. m(x, d) 반환.
Note 2

( Disjunction ) 형태의 괄호는 Disjunction 패턴 구성요소를 그룹화하고 매치 결과를 저장한다. 결과는 역참조(\ + 0이 아닌 10진수), 치환 문자열(replace String)에서 참조, 또는 정규 표현식 매칭 추상 클로저가 반환하는 배열의 일부로 사용될 수 있다. 괄호의 캡처 동작을 억제하려면 (?: Disjunction ) 형태를 사용한다.

Atom :: (? RegularExpressionModifiers : Disjunction )
  1. addModifiersRegularExpressionModifiers 가 매치한 소스 텍스트로 둔다.
  2. removeModifiers 를 빈 문자열로 둔다.
  3. modifiedRerUpdateModifiers(rer, CodePointsToString(addModifiers), removeModifiers) 로 둔다.
  4. Disjunction 에 대해 인수 modifiedRer, direction 으로 CompileSubpattern 한 결과 반환.
Atom :: (? RegularExpressionModifiers - RegularExpressionModifiers : Disjunction )
  1. addModifiers 를 첫 번째 RegularExpressionModifiers 가 매치한 소스 텍스트로 둔다.
  2. removeModifiers 를 두 번째 RegularExpressionModifiers 가 매치한 소스 텍스트로 둔다.
  3. modifiedRerUpdateModifiers(rer, CodePointsToString(addModifiers), CodePointsToString(removeModifiers)) 로 둔다.
  4. Disjunction 에 대해 인수 modifiedRer, direction 으로 CompileSubpattern 한 결과 반환.
AtomEscape :: DecimalEscape
  1. nDecimalEscape 의 CapturingGroupNumber 로 둔다.
  2. Assert: nrer.[[CapturingGroupsCount]].
  3. BackreferenceMatcher(rer, « n », direction) 반환.
Note 3

\ + 0이 아닌 10진수 n 형태의 이스케이프는 n번째 캡처 괄호의 결과(22.2.2.1)와 매치된다. 정규 표현식이 n 개보다 적은 캡처 괄호를 가지면 오류이다. 정규 표현식이 n 개 이상 캡처 괄호를 가지지만 n번째 괄호가 아무 것도 캡처하지 않아 undefined 이면 해당 역참조는 항상 성공한다.

AtomEscape :: CharacterEscape
  1. cvCharacterEscape 의 CharacterValue 로 둔다.
  2. ch 를 문자 값이 cv 인 문자로 둔다.
  3. A 를 문자 ch 하나를 포함하는 1요소 CharSet 으로 둔다.
  4. CharacterSetMatcher(rer, A, false, direction) 반환.
AtomEscape :: CharacterClassEscape
  1. csCharacterClassEscape 에 대해 인수 rer 로 CompileToCharSet 한 결과로 둔다.
  2. rer.[[UnicodeSets]]false 이거나 cs 의 모든 CharSetElement 가 단일 문자(또는 cs 가 비어 있음)라면 CharacterSetMatcher(rer, cs, false, direction) 반환.
  3. lm 을 빈 Matcher 리스트로 둔다.
  4. cs 내 2 문자 이상인 각 CharSetElement s 에 대해 길이 내림차순 반복:
    1. cs2s 의 마지막 코드 포인트를 포함하는 CharSet 으로 둔다.
    2. m2CharacterSetMatcher(rer, cs2, false, direction) 로 둔다.
    3. s 의 뒤에서 두 번째부터 역순으로 각 코드 포인트 c1 에 대해:
      1. cs1 를 코드 포인트 c1 포함하는 CharSet 으로 둔다.
      2. m1CharacterSetMatcher(rer, cs1, false, direction) 로 둔다.
      3. m2 = MatchSequence(m1, m2, direction) 로 설정.
    4. m2lm 에 추가.
  5. singles 를 단일 문자 CharSetElement 로 이루어진 CharSet 으로 둔다.
  6. CharacterSetMatcher(rer, singles, false, direction) 를 lm 에 추가.
  7. cs 가 빈 문자 시퀀스를 포함하면 EmptyMatcher() 를 lm 에 추가.
  8. m2lm 의 마지막 Matcher 로 둔다.
  9. lm 의 뒤에서 두 번째부터 역순으로 각 Matcher m1 에 대해
    1. m2 = MatchTwoAlternatives(m1, m2) 로 설정.
  10. m2 반환.
AtomEscape :: k GroupName
  1. matchingGroupSpecifiers 를 GroupSpecifiersThatMatch(GroupName) 로 둔다.
  2. parenIndices 를 새 빈 리스트로 둔다.
  3. matchingGroupSpecifiers 의 각 GroupSpecifier groupSpecifier 에 대해:
    1. parenIndex 를 CountLeftCapturingParensBefore(groupSpecifier) 로 둔다.
    2. parenIndexparenIndices 에 추가.
  4. BackreferenceMatcher(rer, parenIndices, direction) 반환.

22.2.2.7.1 CharacterSetMatcher ( rer, A, invert, direction )

The abstract operation CharacterSetMatcher takes arguments rer (RegExp Record), A (CharSet), invert (Boolean), and direction (forward 또는 backward) and returns Matcher. It performs the following steps when called:

  1. rer.[[UnicodeSets]]true 이면
    1. Assert: invertfalse.
    2. Assert: A 의 모든 CharSetElement 는 단일 문자.
  2. rer, A, invert, direction 을 캡처하고 매개변수 (x, c) 를 가지며 호출 시 다음을 수행하는 새 Matcher 반환:
    1. Assert: xMatchState.
    2. Assert: cMatcherContinuation.
    3. Inputx.[[Input]] 로 둔다.
    4. ex.[[EndIndex]] 로 둔다.
    5. directionforward 이면 f = e + 1.
    6. 그렇지 않으면 f = e - 1.
    7. InputLengthInput 요소 수로 둔다.
    8. f < 0 또는 f > InputLength 이면 failure 반환.
    9. index = min(e, f) 로 둔다.
    10. ch 를 문자 Input[index] 로 둔다.
    11. ccCanonicalize(rer, ch) 로 둔다.
    12. A 내에서 정확히 한 문자를 포함하는 CharSetElementCanonicalize(rer, a) 가 cca 가 존재하면 found = true; 아니면 false.
    13. invert = false 이고 found = false 이면 failure 반환.
    14. invert = true 이고 found = true 이면 failure 반환.
    15. capx.[[Captures]] 로 둔다.
    16. yMatchState { [[Input]]: Input, [[EndIndex]]: f, [[Captures]]: cap } 로 둔다.
    17. c(y) 반환.

22.2.2.7.2 BackreferenceMatcher ( rer, ns, direction )

The abstract operation BackreferenceMatcher takes arguments rer (RegExp Record), ns (양의 정수 리스트), and direction (forward 또는 backward) and returns Matcher. It performs the following steps when called:

  1. rer, ns, direction 을 캡처하고 매개변수 (x, c) 를 가지며 호출 시 다음을 수행하는 새 Matcher 반환:
    1. Assert: xMatchState.
    2. Assert: cMatcherContinuation.
    3. Inputx.[[Input]] 로 둔다.
    4. capx.[[Captures]] 로 둔다.
    5. rundefined 로 둔다.
    6. ns 의 각 정수 n 에 대해:
      1. cap[n] 이 undefined 가 아니면
        1. Assert: rundefined.
        2. r = cap[n] 로 설정.
    7. rundefined 이면 c(x) 반환.
    8. ex.[[EndIndex]] 로 둔다.
    9. rsr.[[StartIndex]] 로 둔다.
    10. rer.[[EndIndex]] 로 둔다.
    11. len = re - rs 로 둔다.
    12. directionforward 이면 f = e + len, 아니면 f = e - len.
    13. InputLengthInput 요소 수로 둔다.
    14. f < 0 또는 f > InputLength 이면 failure 반환.
    15. g = min(e, f) 로 둔다.
    16. 0 ≤ i < len 인 어떤 정수 iCanonicalize(rer, Input[rs + i]) ≠ Canonicalize(rer, Input[g + i]) 이면 failure 반환.
    17. yMatchState { [[Input]]: Input, [[EndIndex]]: f, [[Captures]]: cap } 로 둔다.
    18. c(y) 반환.

22.2.2.7.3 Canonicalize ( rer, ch )

The abstract operation Canonicalize takes arguments rer (RegExp Record) and ch (문자) and returns 문자. It performs the following steps when called:

  1. HasEitherUnicodeFlag(rer) 가 true 이고 rer.[[IgnoreCase]]true 이면
    1. Unicode Character Database 의 CaseFolding.txtch 에 대한 simple 또는 common case folding 매핑을 제공하면 그 매핑을 적용한 결과 반환.
    2. ch 반환.
  2. rer.[[IgnoreCase]]false 이면 ch 반환.
  3. Assert: ch 는 UTF-16 코드 유닛.
  4. cp 를 수치 값이 ch 의 수치 값인 코드 포인트로 둔다.
  5. u 를 Unicode Default Case Conversion 알고리즘에 따라 toUppercase(« cp ») 로 둔다.
  6. uStr 를 CodePointsToString(u) 로 둔다.
  7. uStr 길이 ≠ 1 이면 ch 반환.
  8. cuuStr 의 단일 코드 유닛 요소로 둔다.
  9. ch 의 수치 값 ≥ 128 이고 cu 의 수치 값 < 128 이면 ch 반환.
  10. cu 반환.
Note

HasEitherUnicodeFlag(rer) 가 true 이고 대소문자 구분이 무시될 때, 모든 문자는 비교 직전에 Unicode Standard 가 제공하는 simple case folding 으로 암묵적으로 폴딩된다. simple 매핑은 항상 단일 코드 포인트로 매핑하므로 ß (U+00DF) 를 ssSS 로 매핑하지 않는다. 그러나 Basic Latin 블록 밖의 코드 포인트를 그 안으로 매핑할 수 있다 (예: ſs, k). 이런 코드 포인트를 포함하는 문자열은 /[a-z]/ui 같은 정규 표현식에 매치된다.

HasEitherUnicodeFlag(rer) 가 false 인 대소문자 비구분 매칭에서는 toCasefold 대신 Unicode 기본 대문자 변환 toUppercase 기반 매핑을 사용하므로 약간 차이가 난다. 예를 들어 (U+2126) 는 toUppercase 로 자기 자신을 반환하지만 toCasefold 로는 ω (U+03C9) 와 Ω (U+03A9) 와 함께 ω 로 매핑된다. 따라서 "\u2126"/[ω]/ui, /[\u03A9]/ui 에 매치되지만 /[ω]/i, /[\u03A9]/i 에는 매치되지 않는다. 또한 Basic Latin 블록 밖 코드 포인트가 그 안으로 매핑되지 않으므로 "\u017F ſ", "\u212A K"/[a-z]/i 에 매치되지 않는다.

22.2.2.7.4 UpdateModifiers ( rer, add, remove )

The abstract operation UpdateModifiers takes arguments rer (RegExp Record), add (String), and remove (String) and returns RegExp Record. It performs the following steps when called:

  1. Assert: addremove 는 공통 요소가 없다.
  2. ignoreCase = rer.[[IgnoreCase]].
  3. multiline = rer.[[Multiline]].
  4. dotAll = rer.[[DotAll]].
  5. unicode = rer.[[Unicode]].
  6. unicodeSets = rer.[[UnicodeSets]].
  7. capturingGroupsCount = rer.[[CapturingGroupsCount]].
  8. remove"i" 포함하면 ignoreCase = false.
  9. Else add"i" 포함하면 ignoreCase = true.
  10. remove"m" 포함하면 multiline = false.
  11. Else add"m" 포함하면 multiline = true.
  12. remove"s" 포함하면 dotAll = false.
  13. Else add"s" 포함하면 dotAll = true.
  14. RegExp Record { [[IgnoreCase]]: ignoreCase, [[Multiline]]: multiline, [[DotAll]]: dotAll, [[Unicode]]: unicode, [[UnicodeSets]]: unicodeSets, [[CapturingGroupsCount]]: capturingGroupsCount } 반환.

22.2.2.8 런타임 의미론: CompileCharacterClass 필드를 가진 레코드

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. It is defined piecewise over the following productions:

CharacterClass :: [ ClassContents ]
  1. AClassContents 에 대해 인수 rer 로 CompileToCharSet 한 결과로 둔다.
  2. { [[CharSet]]: A, [[Invert]]: false } 반환.
CharacterClass :: [^ ClassContents ]
  1. AClassContents 에 대해 인수 rer 로 CompileToCharSet 한 결과로 둔다.
  2. rer.[[UnicodeSets]]true 이면
    1. { [[CharSet]]: CharacterComplement(rer, A), [[Invert]]: false } 반환.
  3. { [[CharSet]]: A, [[Invert]]: true } 반환.

22.2.2.9 런타임 의미론: CompileToCharSet : CharSet

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS.

Note 1

이 절은 B.1.2.8 에서 수정된다.

It is defined piecewise over the following productions:

ClassContents :: [empty]
  1. CharSet 반환.
NonemptyClassRanges :: ClassAtom NonemptyClassRangesNoDash
  1. AClassAtom 에 대해 인수 rer 로 CompileToCharSet 한 결과로 둔다.
  2. BNonemptyClassRangesNoDash 에 대해 인수 rer 로 CompileToCharSet 한 결과로 둔다.
  3. CharSet AB 의 합집합 반환.
NonemptyClassRanges :: ClassAtom - ClassAtom ClassContents
  1. A 를 첫 번째 ClassAtom 에 대해 인수 rer 로 CompileToCharSet 한 결과로 둔다.
  2. B 를 두 번째 ClassAtom 에 대해 인수 rer 로 CompileToCharSet 한 결과로 둔다.
  3. CClassContents 에 대해 인수 rer 로 CompileToCharSet 한 결과로 둔다.
  4. DCharacterRange(A, B) 로 둔다.
  5. DC 의 합집합 반환.
NonemptyClassRangesNoDash :: ClassAtomNoDash NonemptyClassRangesNoDash
  1. AClassAtomNoDash 에 대해 인수 rer 로 CompileToCharSet 한 결과로 둔다.
  2. BNonemptyClassRangesNoDash 에 대해 인수 rer 로 CompileToCharSet 한 결과로 둔다.
  3. CharSet AB 의 합집합 반환.
NonemptyClassRangesNoDash :: ClassAtomNoDash - ClassAtom ClassContents
  1. AClassAtomNoDash 에 대해 인수 rer 로 CompileToCharSet 한 결과로 둔다.
  2. BClassAtom 에 대해 인수 rer 로 CompileToCharSet 한 결과로 둔다.
  3. CClassContents 에 대해 인수 rer 로 CompileToCharSet 한 결과로 둔다.
  4. DCharacterRange(A, B) 로 둔다.
  5. DC 의 합집합 반환.
Note 2

ClassContents 는 하나의 ClassAtom 이나 - 로 구분된 두 ClassAtom 범위로 확장될 수 있다. 후자의 경우 첫 번째와 두 번째 ClassAtom 사이(포함)의 모든 문자를 포함한다. 어느 ClassAtom 도 단일 문자를 나타내지 않으면(예: \w) 또는 첫 번째 ClassAtom 의 문자 값이 두 번째보다 엄격히 크면 오류이다.

Note 3

패턴이 대소문자를 무시하더라도 범위의 두 끝 문자 대소문자는 범위에 속하는 문자를 결정하는 데 여전히 중요하다. 예를 들어 /[E-F]/iE, F, e, f 만 매치하지만 /[E-f]/i 는 Unicode Basic Latin 블록의 모든 대소문자와 [, \, ], ^, _, ` 기호를 매치한다.

Note 4

- 문자는 리터럴로 취급되거나 범위를 나타낼 수 있다. ClassContents 의 첫/마지막 문자, 범위의 시작/끝 경계, 또는 범위 지정 직후에 나타나면 리터럴로 취급된다.

ClassAtom :: -
  1. 문자 - (U+002D HYPHEN-MINUS) 하나를 포함하는 CharSet 반환.
ClassAtomNoDash :: SourceCharacter but not one of \ or ] or -
  1. SourceCharacter 가 매치한 문자를 포함하는 CharSet 반환.
ClassEscape :: b - CharacterEscape
  1. cv 를 이 ClassEscape 의 CharacterValue 로 둔다.
  2. c 를 문자 값이 cv 인 문자로 둔다.
  3. 문자 c 하나를 포함하는 CharSet 반환.
Note 5

ClassAtom 은 정규 표현식 다른 부분에서 허용되는 이스케이프 대부분을 사용할 수 있으나 \b, \B, 역참조는 제외된다. CharacterClass 내부에서 \b 는 백스페이스 문자를 의미하며, \B 와 역참조는 오류이다. ClassAtom 내에서 역참조를 사용하면 오류가 발생한다.

CharacterClassEscape :: d
  1. 문자 0..9 10개를 포함하는 CharSet 반환.
CharacterClassEscape :: D
  1. S CharacterClassEscape :: d 가 반환한 CharSet 으로 둔다.
  2. CharacterComplement(rer, S) 반환.
CharacterClassEscape :: s
  1. WhiteSpace 또는 LineTerminator 생성 규칙 우변의 코드 포인트에 대응하는 모든 문자를 포함하는 CharSet 반환.
CharacterClassEscape :: S
  1. S CharacterClassEscape :: s 가 반환한 CharSet 으로 둔다.
  2. CharacterComplement(rer, S) 반환.
CharacterClassEscape :: w
  1. MaybeSimpleCaseFolding(rer, WordCharacters(rer)) 반환.
CharacterClassEscape :: W
  1. S CharacterClassEscape :: w 가 반환한 CharSet 으로 둔다.
  2. CharacterComplement(rer, S) 반환.
CharacterClassEscape :: p{ UnicodePropertyValueExpression }
  1. UnicodePropertyValueExpression 에 대해 인수 rer 로 CompileToCharSet 한 결과 반환.
CharacterClassEscape :: P{ UnicodePropertyValueExpression }
  1. SUnicodePropertyValueExpression 에 대해 인수 rer 로 CompileToCharSet 한 결과로 둔다.
  2. Assert: S 는 단일 코드 포인트만 포함한다.
  3. CharacterComplement(rer, S) 반환.
UnicodePropertyValueExpression :: UnicodePropertyName = UnicodePropertyValue
  1. psUnicodePropertyName 이 매치한 소스 텍스트로 둔다.
  2. pUnicodeMatchProperty(rer, ps) 로 둔다.
  3. Assert: pTable 67 의 “Property name and aliases” 열에 열거된 유니코드 속성 이름 또는 별칭.
  4. vsUnicodePropertyValue 가 매치한 소스 텍스트로 둔다.
  5. vUnicodeMatchPropertyValue(p, vs) 로 둔다.
  6. A 를 속성 pv 를 포함하는 모든 유니코드 코드 포인트를 담는 CharSet 으로 둔다.
  7. MaybeSimpleCaseFolding(rer, A) 반환.
UnicodePropertyValueExpression :: LoneUnicodePropertyNameOrValue
  1. sLoneUnicodePropertyNameOrValue 가 매치한 소스 텍스트로 둔다.
  2. UnicodeMatchPropertyValue(General_Category, s) 가 General_Category (gc) 속성의 유효한 속성 값(또는 별칭)이면
    1. 속성 “General_Category” 값 s 를 포함하는 모든 유니코드 코드 포인트의 CharSet 반환.
  3. pUnicodeMatchProperty(rer, s) 로 둔다.
  4. Assert: pTable 68 의 “Property name and aliases” 열에 열거된 바이너리 유니코드 속성(또는 별칭) 혹은 Table 69 “Property name” 열에 열거된 문자열 바이너리 속성.
  5. A 를 속성 p 값 “True” 를 가지는 모든 CharSetElement 를 담는 CharSet 으로 둔다.
  6. MaybeSimpleCaseFolding(rer, A) 반환.
ClassUnion :: ClassSetRange ClassUnionopt
  1. AClassSetRange 에 대해 인수 rer 로 CompileToCharSet 한 결과로 둔다.
  2. ClassUnion 이 존재하면
    1. BClassUnion 에 대해 인수 rer 로 CompileToCharSet 한 결과로 둔다.
    2. CharSet A, B 의 합집합 반환.
  3. A 반환.
ClassUnion :: ClassSetOperand ClassUnionopt
  1. AClassSetOperand 에 대해 인수 rer 로 CompileToCharSet 한 결과로 둔다.
  2. ClassUnion 존재하면
    1. BClassUnion 에 대해 인수 rer 로 CompileToCharSet 한 결과로 둔다.
    2. CharSet A, B 합집합 반환.
  3. A 반환.
ClassIntersection :: ClassSetOperand && ClassSetOperand
  1. A 를 첫 번째 ClassSetOperand 에 대해 인수 rer 로 CompileToCharSet 한 결과로 둔다.
  2. B 를 두 번째 ClassSetOperand 에 대해 인수 rer 로 CompileToCharSet 한 결과로 둔다.
  3. CharSet A, B 교집합 반환.
ClassIntersection :: ClassIntersection && ClassSetOperand
  1. AClassIntersection 에 대해 인수 rer 로 CompileToCharSet 한 결과로 둔다.
  2. BClassSetOperand 에 대해 인수 rer 로 CompileToCharSet 한 결과로 둔다.
  3. CharSet A, B 교집합 반환.
ClassSubtraction :: ClassSetOperand -- ClassSetOperand
  1. A 를 첫 번째 ClassSetOperand 에 대해 인수 rer 로 CompileToCharSet 한 결과로 둔다.
  2. B 를 두 번째 ClassSetOperand 에 대해 인수 rer 로 CompileToCharSet 한 결과로 둔다.
  3. AB 에 속하지 않는 CharSetElement 들만 포함하는 CharSet 반환.
ClassSubtraction :: ClassSubtraction -- ClassSetOperand
  1. AClassSubtraction 에 대해 인수 rer 로 CompileToCharSet 한 결과로 둔다.
  2. BClassSetOperand 에 대해 인수 rer 로 CompileToCharSet 한 결과로 둔다.
  3. AB 에 속하지 않는 CharSetElement 들만 포함하는 CharSet 반환.
ClassSetRange :: ClassSetCharacter - ClassSetCharacter
  1. A 를 첫 번째 ClassSetCharacter 에 대해 인수 rer 로 CompileToCharSet 한 결과로 둔다.
  2. B 를 두 번째 ClassSetCharacter 에 대해 인수 rer 로 CompileToCharSet 한 결과로 둔다.
  3. MaybeSimpleCaseFolding(rer, CharacterRange(A, B)) 반환.
Note 6

결과는 종종 두 개 이상의 범위로 구성된다. UnicodeSets true, IgnoreCase true 인 경우 MaybeSimpleCaseFolding(rer, [Ā-č]) 는 해당 범위의 홀수 코드 포인트만 포함할 수 있다.

ClassSetOperand :: ClassSetCharacter
  1. AClassSetCharacter 에 대해 인수 rer 로 CompileToCharSet 한 결과로 둔다.
  2. MaybeSimpleCaseFolding(rer, A) 반환.
ClassSetOperand :: ClassStringDisjunction
  1. AClassStringDisjunction 에 대해 인수 rer 로 CompileToCharSet 한 결과로 둔다.
  2. MaybeSimpleCaseFolding(rer, A) 반환.
ClassSetOperand :: NestedClass
  1. NestedClass 에 대해 인수 rer 로 CompileToCharSet 한 결과 반환.
NestedClass :: [ ClassContents ]
  1. ClassContents 에 대해 인수 rer 로 CompileToCharSet 한 결과 반환.
NestedClass :: [^ ClassContents ]
  1. AClassContents 에 대해 인수 rer 로 CompileToCharSet 한 결과로 둔다.
  2. CharacterComplement(rer, A) 반환.
NestedClass :: \ CharacterClassEscape
  1. CharacterClassEscape 에 대해 인수 rer 로 CompileToCharSet 한 결과 반환.
ClassStringDisjunction :: \q{ ClassStringDisjunctionContents }
  1. ClassStringDisjunctionContents 에 대해 인수 rer 로 CompileToCharSet 한 결과 반환.
ClassStringDisjunctionContents :: ClassString
  1. sClassString 에 대해 인수 rer 로 CompileClassSetString 한 결과로 둔다.
  2. 문자열 s 하나를 포함하는 CharSet 반환.
ClassStringDisjunctionContents :: ClassString | ClassStringDisjunctionContents
  1. sClassString 에 대해 인수 rer 로 CompileClassSetString 한 결과로 둔다.
  2. A 를 문자열 s 하나를 포함하는 CharSet 으로 둔다.
  3. BClassStringDisjunctionContents 에 대해 인수 rer 로 CompileToCharSet 한 결과로 둔다.
  4. CharSet A, B 합집합 반환.
ClassSetCharacter :: SourceCharacter but not ClassSetSyntaxCharacter \ CharacterEscape \ ClassSetReservedPunctuator
  1. cv 를 이 ClassSetCharacter 의 CharacterValue 로 둔다.
  2. c 를 문자 값이 cv 인 문자로 둔다.
  3. 문자 c 하나를 포함하는 CharSet 반환.
ClassSetCharacter :: \b
  1. U+0008 (BACKSPACE) 문자 하나를 포함하는 CharSet 반환.

22.2.2.9.1 CharacterRange ( A, B )

The abstract operation CharacterRange takes arguments A (CharSet) and B (CharSet) and returns CharSet. It performs the following steps when called:

  1. Assert: A, B 는 각각 정확히 한 문자만 포함.
  2. aCharSet A 의 그 문자로 둔다.
  3. bCharSet B 의 그 문자로 둔다.
  4. i 를 문자 a 의 문자 값으로 둔다.
  5. j 를 문자 b 의 문자 값으로 둔다.
  6. Assert: ij.
  7. 문자 값이 i..j (포함) 범위에 속하는 모든 문자를 포함하는 CharSet 반환.

22.2.2.9.2 HasEitherUnicodeFlag ( rer )

The abstract operation HasEitherUnicodeFlag takes argument rer (RegExp Record) and returns Boolean. It performs the following steps when called:

  1. rer.[[Unicode]]true 이거나 rer.[[UnicodeSets]]true 이면
    1. true 반환.
  2. false 반환.

22.2.2.9.3 WordCharacters ( rer )

The abstract operation WordCharacters takes argument rer (RegExp Record) and returns CharSet. \b, \B, \w, \W 판단에 사용되는 “단어 문자”들을 포함하는 CharSet 반환 It performs the following steps when called:

  1. basicWordChars 를 ASCII 단어 문자를 모두 포함하는 CharSet 으로 둔다.
  2. extraWordCharsbasicWordChars 에 없지만 Canonicalize(rer, c) 가 basicWordChars 에 있는 문자 c 전부를 포함하는 CharSet 으로 둔다.
  3. Assert: extraWordCharsHasEitherUnicodeFlag(rer) 가 true 이고 rer.[[IgnoreCase]]true 인 경우를 제외하면 비어 있음.
  4. basicWordCharsextraWordChars 합집합 반환.

22.2.2.9.4 AllCharacters ( rer )

The abstract operation AllCharacters takes argument rer (RegExp Record) and returns CharSet. 정규 표현식 플래그에 따른 “모든 문자” 집합을 반환한다. It performs the following steps when called:

  1. rer.[[UnicodeSets]] true, rer.[[IgnoreCase]] true 이면
    1. Simple Case Folding 매핑이 없는(즉 scf(c) = c) 모든 유니코드 코드 포인트 c 를 포함하는 CharSet 반환.
  2. Else HasEitherUnicodeFlag(rer) true 이면
    1. 모든 코드 포인트 값을 포함하는 CharSet 반환.
  3. Else
    1. 모든 코드 유닛 값을 포함하는 CharSet 반환.

22.2.2.9.5 MaybeSimpleCaseFolding ( rer, A )

The abstract operation MaybeSimpleCaseFolding takes arguments rer (RegExp Record) and A (CharSet) and returns CharSet. rer.[[UnicodeSets]]false 이거나 rer.[[IgnoreCase]]false 이면 A 를 반환한다. 그렇지 않으면 Unicode Character Database 의 Simple Case Folding (scf(cp)) 정의(각각 단일 코드 포인트를 다른 단일 코드 포인트로 매핑)를 사용하여 A 의 각 CharSetElement 를 문자 단위로 정규 형태로 매핑한 결과 CharSet 을 반환한다. It performs the following steps when called:

  1. rer.[[UnicodeSets]] false 또는 rer.[[IgnoreCase]] false 이면 A 반환.
  2. B 를 새 빈 CharSet 으로 둔다.
  3. A 의 각 CharSetElement s 에 대해:
    1. t 를 빈 문자 시퀀스로 둔다.
    2. s 의 각 단일 코드 포인트 cp 에 대해:
      1. scf(cp) 를 t 에 추가.
    3. tB 에 추가.
  4. B 반환.

22.2.2.9.6 CharacterComplement ( rer, S )

The abstract operation CharacterComplement takes arguments rer (RegExp Record) and S (CharSet) and returns CharSet. It performs the following steps when called:

  1. AAllCharacters(rer) 로 둔다.
  2. AS 에 속하지 않는 CharSetElement 들만 포함하는 CharSet 반환.

22.2.2.9.7 UnicodeMatchProperty ( rer, p )

The abstract operation UnicodeMatchProperty takes arguments rer (RegExp Record) and p (ECMAScript 소스 텍스트) and returns 유니코드 속성 이름. It performs the following steps when called:

  1. rer.[[UnicodeSets]]true 이고 pTable 69 의 “Property name” 열에 열거된 유니코드 property name 이면
    1. 유니코드 코드 포인트 p 의 리스트 반환.
  2. Assert: pTable 67 또는 Table 68 의 “Property name and aliases” 열에 열거된 유니코드 property name 또는 별칭.
  3. c 를 해당 행의 “Canonical property name” 열에 주어진 p 의 canonical property name 리스트로 둔다.
  4. 유니코드 코드 포인트 c 리스트 반환.

구현체는 Table 67, Table 68, Table 69 에 열거된 유니코드 속성 이름 및 별칭을 지원해야 한다. 상호 운용성을 위해 다른 이름이나 별칭은 지원하면 안 된다.

Note 1

예: Script_Extensions (속성 이름) 과 scx (별칭)는 유효하지만 script_extensions, Scx 는 유효하지 않다.

Note 2

열거된 속성은 UTS18 RL1.2 요구 사항의 상위 집합이다.

Note 3

이 표의 항목 철자(대소문자 포함)는 Unicode Character Database 의 PropertyAliases.txt 파일에 사용된 철자와 일치하며, 그 철자는 안정성 정책에 따라 안정적으로 유지된다.

Table 67: 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 68: 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 69: 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 소스 텍스트) and v (ECMAScript 소스 텍스트) and returns 유니코드 속성 값. It performs the following steps when called:

  1. Assert: pTable 67 의 “Canonical property name” 열에 열거된 canonical, 비별칭 유니코드 속성 이름.
  2. Assert: vPropertyValueAliases.txt 에 해당 속성 p 의 속성 값 또는 속성 값 별칭으로 열거됨.
  3. value 를 해당 행 “Canonical property value” 열의 v 의 canonical 속성 값 리스트로 둔다.
  4. 유니코드 코드 포인트 value 리스트 반환.

구현체는 Table 67 에 열거된 속성에 대해 PropertyValueAliases.txt 에 열거된 속성 값 및 별칭을 지원해야 한다. 상호 운용성을 위해 다른 속성 값 또는 별칭은 지원하면 안 된다.

Note 1

예: Xpeo, Old_PersianScript_Extensions 값으로 유효하지만 xpeo, Old Persian 은 유효하지 않다.

Note 2

이 알고리즘은 UAX44 의 심볼릭 값 매칭 규칙과 다르다: 대소문자, 공백, U+002D (HYPHEN-MINUS), U+005F (LOW LINE)이 무시되지 않고 Is 접두사도 지원되지 않는다.

22.2.2.10 런타임 의미론: CompileClassSetString : 문자 시퀀스

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. It is defined piecewise over the following productions:

ClassString :: [empty]
  1. 빈 문자 시퀀스 반환.
ClassString :: NonEmptyClassString
  1. NonEmptyClassString 에 대해 인수 rer 로 CompileClassSetString 한 결과 반환.
NonEmptyClassString :: ClassSetCharacter NonEmptyClassStringopt
  1. csClassSetCharacter 에 대해 인수 rer 로 CompileToCharSet 한 결과로 둔다.
  2. s1cs 의 단일 CharSetElement 인 문자 시퀀스로 둔다.
  3. NonEmptyClassString 이 존재하면
    1. s2NonEmptyClassString 에 대해 인수 rer 로 CompileClassSetString 한 결과로 둔다.
    2. s1s2 의 연결(concatenation) 반환.
  4. s1 반환.

22.2.3 RegExp 생성용 추상 연산 (Abstract Operations for RegExp Creation)

22.2.3.1 RegExpCreate ( P, F )

The abstract operation RegExpCreate takes arguments P (ECMAScript 언어 값) and F (String 또는 undefined) and returns Object 를 포함하는 정상 완료(normal completion) 또는 throw completion. It performs the following steps when called:

  1. obj 를 ! RegExpAlloc(%RegExp%) 의 결과로 둔다.
  2. RegExpInitialize(obj, P, F) 를 반환한다.

22.2.3.2 RegExpAlloc ( newTarget )

The abstract operation RegExpAlloc takes argument newTarget (생성자(constructor)) and returns Object 를 포함하는 정상 완료 또는 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 (Object), pattern (ECMAScript 언어 값), and flags (ECMAScript 언어 값) and returns Object 를 포함하는 정상 완료 또는 throw completion. It performs the following steps when called:

  1. patternundefined 이면 P 를 빈 String 으로 둔다.
  2. 아니면 P 를 ? ToString(pattern) 으로 둔다.
  3. flagsundefined 이면 F 를 빈 String 으로 둔다.
  4. 아니면 F 를 ? ToString(flags) 로 둔다.
  5. F"d", "g", "i", "m", "s", "u", "v", "y" 외의 코드 유닛을 포함하거나, 어떤 코드 유닛이든 두 번 이상 포함하면 SyntaxError 예외를 throw 한다.
  6. F"i" 를 포함하면 i = true; 아니면 false.
  7. F"m" 를 포함하면 m = true; 아니면 false.
  8. F"s" 를 포함하면 s = true; 아니면 false.
  9. F"u" 를 포함하면 u = true; 아니면 false.
  10. F"v" 를 포함하면 v = true; 아니면 false.
  11. utrue 이거나 vtrue 이면
    1. patternText 를 StringToCodePoints(P) 로 둔다.
  12. 아니면
    1. patternTextP 의 각 16-bit 요소를 UTF-16 디코딩 없이 Unicode BMP 코드 포인트로 해석한 결과로 둔다.
  13. parseResult 를 ParsePattern(patternText, u, v) 로 둔다.
  14. parseResult 가 비어 있지 않은 SyntaxError 객체들의 List 이면 SyntaxError 예외를 throw 한다.
  15. Assert: parseResultPattern Parse Node 이다.
  16. obj.[[OriginalSource]] = P.
  17. obj.[[OriginalFlags]] = F.
  18. capturingGroupsCount 를 CountLeftCapturingParensWithin(parseResult) 로 둔다.
  19. rerRegExp Record { [[IgnoreCase]]: i, [[Multiline]]: m, [[DotAll]]: s, [[Unicode]]: u, [[UnicodeSets]]: v, [[CapturingGroupsCount]]: capturingGroupsCount } 로 둔다.
  20. obj.[[RegExpRecord]] = rer.
  21. obj.[[RegExpMatcher]] = CompilePattern of parseResult with argument rer.
  22. Set(obj, "lastIndex", +0𝔽, true) 를 수행한다.
  23. obj 를 반환한다.

22.2.3.4 정적 의미론: ParsePattern ( patternText: Unicode 코드 포인트 시퀀스, u: Boolean, v: Boolean, ): Parse Node 또는 비어 있지 않은 SyntaxError 객체 List

The abstract operation UNKNOWN takes UNPARSEABLE ARGUMENTS.

Note

이 절은 B.1.2.9 에서 수정된다.

It performs the following steps when called:

  1. vtrue 이고 utrue 이면
    1. parseResult 를 하나 이상의 SyntaxError 객체를 포함하는 List 로 둔다.
  2. Else if vtrue 이면
    1. parseResult = ParseText(patternText, Pattern[+UnicodeMode, +UnicodeSetsMode, +NamedCaptureGroups]).
  3. Else if utrue 이면
    1. parseResult = ParseText(patternText, Pattern[+UnicodeMode, ~UnicodeSetsMode, +NamedCaptureGroups]).
  4. Else
    1. parseResult = ParseText(patternText, Pattern[~UnicodeMode, ~UnicodeSetsMode, +NamedCaptureGroups]).
  5. parseResult 를 반환한다.

22.2.4 RegExp 생성자 (The RegExp Constructor)

RegExp 생성자는 다음을 만족한다:

  • %RegExp% 이다.
  • 전역 객체"RegExp" 프로퍼티 초기 값이다.
  • 생성자로 호출될 때 새로운 RegExp 객체를 생성·초기화한다.
  • 생성자가 아닌 함수로 호출될 때, 새 RegExp 객체를 반환하거나 인자가 RegExp 객체 하나뿐이면 그 인자를 그대로 반환한다.
  • 클래스 정의의 extends 절 값으로 사용할 수 있다. 지정된 RegExp 동작을 상속하려는 서브클래스 생성자는 필요한 내부 슬롯을 가진 인스턴스를 생성·초기화하기 위해 반드시 super 호출을 포함해야 한다.

22.2.4.1 RegExp ( pattern, flags )

이 함수가 호출되면 다음 단계를 수행한다:

  1. patternIsRegExp 를 ? IsRegExp(pattern) 로 둔다.
  2. NewTarget 이 undefined 이면
    1. newTarget = 활성 함수 객체.
    2. patternIsRegExptrue 이고 flagsundefined 이면
      1. patternConstructor = ? Get(pattern, "constructor").
      2. SameValue(newTarget, patternConstructor) 가 true 이면 pattern 반환.
  3. Else
    1. newTarget = NewTarget.
  4. pattern 이 Object 이고 [[RegExpMatcher]] 내부 슬롯을 가지면
    1. P = pattern.[[OriginalSource]].
    2. flagsundefined 이면 F = pattern.[[OriginalFlags]]; 아니면 F = flags.
  5. Else if patternIsRegExp = true 이면
    1. P = ? Get(pattern, "source").
    2. flagsundefined 이면
      1. F = ? Get(pattern, "flags").
    3. Else
      1. F = flags.
  6. Else
    1. P = pattern.
    2. F = flags.
  7. O = ? RegExpAlloc(newTarget).
  8. RegExpInitialize(O, P, F) 를 반환한다.
Note

패턴이 StringLiteral 로 제공되면, 본 함수가 처리하기 전에 일반적인 이스케이프 시퀀스 치환이 수행된다. 패턴이 이스케이프 시퀀스를 포함해야 인식되는 경우, StringLiteral 구성 시 제거되지 않도록 U+005C (REVERSE SOLIDUS) 코드 포인트는 이중 이스케이프되어야 한다.

22.2.5 RegExp 생성자의 프로퍼티 (Properties of the RegExp Constructor)

RegExp 생성자는 다음을 만족한다:

  • 값이 %Function.prototype%[[Prototype]] 내부 슬롯을 가진다.
  • 다음 프로퍼티들을 가진다:

22.2.5.1 RegExp.escape ( S )

이 함수는 정규 표현식 Pattern 내에서 특수 의미가 될 수 있는 문자들을 동등한 이스케이프 시퀀스로 치환한 S 의 복사본을 반환한다.

호출 시 다음 단계를 수행한다:

  1. S 가 String 이 아니면 TypeError 예외를 throw.
  2. escaped 를 빈 String 으로 둔다.
  3. cpList = StringToCodePoints(S).
  4. cpList 의 각 코드 포인트 cp 에 대해
    1. escaped 가 빈 String 이고 cpDecimalDigit 또는 AsciiLetter 에 매치되면
      1. NOTE: 선행 숫자를 이스케이프하면 \0 이나 \1 같은 DecimalEscape 뒤에서도 확장으로 해석되지 않고 S 와 매치되도록 보장한다. 선행 ASCII 문자 이스케이프는 \c 이후 문맥에 대해 동일한 목적을 가진다.
      2. numericValue = cp 의 수치 값.
      3. hex = Number::toString(𝔽(numericValue), 16).
      4. Assert: hex 길이는 2.
      5. escaped = 0x005C (REVERSE SOLIDUS) + "x" + hex.
    2. Else
      1. escaped = escaped + EncodeForRegExpEscape(cp).
  5. escaped 반환.
Note

이름이 비슷하지만 EscapeRegExpPatternRegExp.escape 는 다른 일을 한다. 전자는 패턴을 문자열로 표현하기 위해 이스케이프하고, 후자는 문자열을 패턴 안에 표현하기 위해 이스케이프한다.

22.2.5.1.1 EncodeForRegExpEscape ( cp )

The abstract operation EncodeForRegExpEscape takes argument cp (코드 포인트) and returns String. cp 를 매칭하는 Pattern 을 나타내는 String 을 반환한다. cp 가 공백 또는 ASCII 구두점이면 이스케이프 시퀀스를 반환하고, 그렇지 않으면 cp 자체의 String 표현을 반환한다. It performs the following steps when called:

  1. cpSyntaxCharacter 에 매치되거나 U+002F (SOLIDUS)이면
    1. 0x005C (REVERSE SOLIDUS) 와 UTF16EncodeCodePoint(cp) 의 연결을 반환.
  2. Else if cpTable 65 “Code Point” 열에 나온 코드 포인트이면
    1. 0x005C (REVERSE SOLIDUS) 와 해당 행 “ControlEscape” 열의 문자열 연결을 반환.
  3. otherPunctuators = ",-=<>#&!%:;@~'`" + 코드 유닛 0x0022 (QUOTATION MARK).
  4. toEscape = StringToCodePoints(otherPunctuators).
  5. toEscapecp 를 포함하거나, cpWhiteSpace 또는 LineTerminator 에 매치되거나, cp 가 리드 서러게이트 또는 트레일 서러게이트와 같은 수치 값을 가지면
    1. cpNum = cp 의 수치 값.
    2. cpNum ≤ 0xFF 이면
      1. hex = Number::toString(𝔽(cpNum), 16).
      2. 0x005C (REVERSE SOLIDUS) + "x" + StringPad(hex, 2, "0", start) 반환.
    3. escaped = 빈 String.
    4. codeUnits = UTF16EncodeCodePoint(cp).
    5. 각 코드 유닛 cu 에 대해
      1. escaped = escaped + UnicodeEscape(cu).
    6. escaped 반환.
  6. UTF16EncodeCodePoint(cp) 반환.

22.2.5.2 RegExp.prototype

RegExp.prototype 의 초기 값은 RegExp 프로토타입 객체이다.

이 프로퍼티는 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false } 특성을 가진다.

22.2.5.3 get RegExp [ %Symbol.species% ]

RegExp[%Symbol.species%] 는 set 접근자가 undefined접근자 프로퍼티이다. get 접근자는 호출 시 다음을 수행한다:

  1. this 값을 반환한다.

이 함수의 "name" 프로퍼티 값은 "get [Symbol.species]" 이다.

Note

RegExp 프로토타입 메서드는 일반적으로 자신의 this 값의 생성자를 사용해 파생 객체를 만든다. 그러나 서브클래스 생성자%Symbol.species% 재정의를 통해 그 기본 동작을 바꿀 수 있다.

22.2.6 RegExp 프로토타입 객체의 프로퍼티 (Properties of the RegExp Prototype Object)

RegExp 프로토타입 객체는 다음을 만족한다:

  • %RegExp.prototype% 이다.
  • 일반(ordinary) 객체이다.
  • RegExp 인스턴스가 아니며 [[RegExpMatcher]] 내부 슬롯이나 그 밖의 RegExp 인스턴스 내부 슬롯을 가지지 않는다.
  • 값이 %Object.prototype%[[Prototype]] 내부 슬롯을 가진다.
Note

RegExp 프로토타입 객체는 자체 "valueOf" 프로퍼티를 갖지 않고 Object 프로토타입 객체로부터 상속받는다.

22.2.6.1 RegExp.prototype.constructor

RegExp.prototype.constructor 의 초기 값은 %RegExp% 이다.

22.2.6.2 RegExp.prototype.exec ( string )

이 메서드는 string 에서 정규 표현식 패턴의 발생을 검색하고 매치 결과를 담은 Array 또는 매치 실패 시 null 을 반환한다.

호출 시 다음을 수행한다:

  1. R = this 값.
  2. RequireInternalSlot(R, [[RegExpMatcher]]) 수행.
  3. S = ? ToString(string).
  4. RegExpBuiltinExec(R, S) 반환.

22.2.6.3 get RegExp.prototype.dotAll

RegExp.prototype.dotAll 은 set 접근자가 undefined접근자 프로퍼티이며 get 접근자는 다음을 수행한다:

  1. R = this 값.
  2. cu = 코드 유닛 0x0073 (LATIN SMALL LETTER S).
  3. RegExpHasFlag(R, cu) 반환.

22.2.6.4 get RegExp.prototype.flags

RegExp.prototype.flags 는 set 접근자가 undefined접근자 프로퍼티이며 get 접근자는 다음을 수행한다:

  1. R = this 값.
  2. R 이 Object 가 아니면 TypeError 예외 throw.
  3. codeUnits = 새 빈 List.
  4. hasIndices = ToBoolean(? Get(R, "hasIndices")).
  5. hasIndicestrue 이면 코드 유닛 0x0064 (d) 를 codeUnits 에 추가.
  6. global = ToBoolean(? Get(R, "global")).
  7. globaltrue 이면 0x0067 (g) 추가.
  8. ignoreCase = ToBoolean(? Get(R, "ignoreCase")).
  9. ignoreCasetrue 이면 0x0069 (i) 추가.
  10. multiline = ToBoolean(? Get(R, "multiline")).
  11. multilinetrue 이면 0x006D (m) 추가.
  12. dotAll = ToBoolean(? Get(R, "dotAll")).
  13. dotAlltrue 이면 0x0073 (s) 추가.
  14. unicode = ToBoolean(? Get(R, "unicode")).
  15. unicodetrue 이면 0x0075 (u) 추가.
  16. unicodeSets = ToBoolean(? Get(R, "unicodeSets")).
  17. unicodeSetstrue 이면 0x0076 (v) 추가.
  18. sticky = ToBoolean(? Get(R, "sticky")).
  19. stickytrue 이면 0x0079 (y) 추가.
  20. codeUnits 요소들로 이루어진 String 반환. codeUnits 비어 있으면 빈 String 반환.

22.2.6.4.1 RegExpHasFlag ( R, codeUnit )

The abstract operation RegExpHasFlag takes arguments R (ECMAScript 언어 값) and codeUnit (코드 유닛) and returns Boolean 또는 undefined 를 포함하는 정상 완료 또는 throw completion. It performs the following steps when called:

  1. R 이 Object 가 아니면 TypeError 예외.
  2. R[[OriginalFlags]] 내부 슬롯을 갖지 않으면
    1. SameValue(R, %RegExp.prototype%) 가 true 이면 undefined 반환.
    2. 아니면 TypeError 예외.
  3. flags = R.[[OriginalFlags]].
  4. flagscodeUnit 을 포함하면 true 반환.
  5. false 반환.

22.2.6.5 get RegExp.prototype.global

RegExp.prototype.global 접근자 get 은 다음을 수행한다:

  1. R = this 값.
  2. cu = 0x0067 (LATIN SMALL LETTER G).
  3. RegExpHasFlag(R, cu) 반환.

22.2.6.6 get RegExp.prototype.hasIndices

RegExp.prototype.hasIndices 접근자 get 은 다음을 수행한다:

  1. R = this 값.
  2. cu = 0x0064 (LATIN SMALL LETTER D).
  3. RegExpHasFlag(R, cu) 반환.

22.2.6.7 get RegExp.prototype.ignoreCase

RegExp.prototype.ignoreCase 접근자 get 은 다음을 수행한다:

  1. R = this 값.
  2. cu = 0x0069 (LATIN SMALL LETTER I).
  3. RegExpHasFlag(R, cu) 반환.

22.2.6.8 RegExp.prototype [ %Symbol.match% ] ( string )

이 메서드는 호출 시 다음을 수행한다:

  1. rx = this 값.
  2. rx 가 Object 가 아니면 TypeError 예외.
  3. S = ? ToString(string).
  4. flags = ? ToString(? Get(rx, "flags")).
  5. flags"g" 를 포함하지 않으면
    1. RegExpExec(rx, S) 반환.
  6. Else
    1. flags"u" 또는 "v" 포함하면 fullUnicode = true; 아니면 false.
    2. Set(rx, "lastIndex", +0𝔽, true).
    3. A = ! ArrayCreate(0).
    4. n = 0.
    5. 반복:
      1. result = ? RegExpExec(rx, S).
      2. resultnull 이면
        1. n = 0 이면 null 반환.
        2. A 반환.
      3. Else
        1. matchStr = ? ToString(? Get(result, "0")).
        2. CreateDataPropertyOrThrow(A, ! ToString(𝔽(n)), matchStr).
        3. matchStr 가 빈 String 이면
          1. thisIndex = (? ToLength(? Get(rx, "lastIndex"))).
          2. nextIndex = AdvanceStringIndex(S, thisIndex, fullUnicode).
          3. Set(rx, "lastIndex", 𝔽(nextIndex), true).
        4. n = n + 1.

이 메서드의 "name" 프로퍼티 값은 "[Symbol.match]" 이다.

Note

%Symbol.match% 프로퍼티는 IsRegExp 추상 연산이 객체가 정규 표현식 기본 동작을 가지는지 식별하는 데 사용된다. 해당 프로퍼티가 없거나 Boolean 으로 true 로 강제되지 않는 값이면 정규 표현식 객체로 의도되지 않은 것이다.

22.2.6.9 RegExp.prototype [ %Symbol.matchAll% ] ( string )

이 메서드는 호출 시 다음을 수행한다:

  1. R = this 값.
  2. R 이 Object 아니면 TypeError.
  3. S = ? ToString(string).
  4. C = ? SpeciesConstructor(R, %RegExp%).
  5. flags = ? ToString(? Get(R, "flags")).
  6. matcher = ? Construct(C, « R, flags »).
  7. lastIndex = ? ToLength(? Get(R, "lastIndex")).
  8. Set(matcher, "lastIndex", lastIndex, true).
  9. flags"g" 포함하면 global = true; 아니면 false.
  10. flags"u" 또는 "v" 포함하면 fullUnicode = true; 아니면 false.
  11. CreateRegExpStringIterator(matcher, S, global, fullUnicode) 반환.

이 메서드의 "name" 프로퍼티 값은 "[Symbol.matchAll]" 이다.

22.2.6.10 get RegExp.prototype.multiline

RegExp.prototype.multiline 접근자 get 은 다음을 수행한다:

  1. R = this.
  2. cu = 0x006D (m).
  3. RegExpHasFlag(R, cu) 반환.

22.2.6.11 RegExp.prototype [ %Symbol.replace% ] ( string, replaceValue )

이 메서드는 호출 시 다음을 수행한다:

  1. rx = this.
  2. rx Object 아니면 TypeError.
  3. S = ? ToString(string).
  4. lengthS = S 길이.
  5. functionalReplace = IsCallable(replaceValue).
  6. functionalReplace = false 이면 replaceValue = ? ToString(replaceValue).
  7. flags = ? ToString(? Get(rx, "flags")).
  8. flags"g" 포함하면 global = true; 아니면 false.
  9. global = true 이면 ? Set(rx, "lastIndex", +0𝔽, true).
  10. results = 새 빈 List.
  11. done = false.
  12. donefalse 인 동안 반복
    1. result = ? RegExpExec(rx, S).
    2. result = null 이면 done = true.
    3. Else
      1. resultsresult 추가.
      2. global = false 이면 done = true.
      3. Else
        1. matchStr = ? ToString(? Get(result, "0")).
        2. matchStr 가 빈 String 이면
          1. thisIndex = (? ToLength(? Get(rx, "lastIndex")) ).
          2. flags"u" 또는 "v" 포함하면 fullUnicode = true; 아니면 false.
          3. nextIndex = AdvanceStringIndex(S, thisIndex, fullUnicode).
          4. Set(rx, "lastIndex", 𝔽(nextIndex), true).
  13. accumulatedResult = 빈 String.
  14. nextSourcePosition = 0.
  15. resultresults 에 대해
    1. resultLength = ? LengthOfArrayLike(result).
    2. nCaptures = max(resultLength - 1, 0).
    3. matched = ? ToString(? Get(result, "0")).
    4. matchLength = matched 길이.
    5. position = ? ToIntegerOrInfinity(? Get(result, "index")).
    6. position = 0..lengthS 로 clamp.
    7. captures = 새 빈 List.
    8. n = 1.
    9. nnCaptures 동안
      1. capN = ? Get(result, ! ToString(𝔽(n))).
      2. capNundefined 이면 capN = ? ToString(capN).
      3. capturescapN 추가.
      4. NOTE: n = 1 때 첫 캡처가 인덱스 0에 들어간다.
      5. n = n + 1.
    10. namedCaptures = ? Get(result, "groups").
    11. functionalReplace = true 이면
      1. replacerArgs = « matched » ⧺ captures ⧺ « 𝔽(position), S ».
      2. namedCapturesundefined 이면 replacerArgs 끝에 추가.
      3. replacementValue = ? Call(replaceValue, undefined, replacerArgs).
      4. replacementString = ? ToString(replacementValue).
    12. Else
      1. namedCapturesundefined 이면 namedCaptures = ? ToObject(namedCaptures).
      2. replacementString = ? GetSubstitution(matched, S, position, captures, namedCaptures, replaceValue).
    13. positionnextSourcePosition 이면
      1. NOTE: position 이 뒤로 가면 비정상 서브클래스 동작일 수 있으며 그 치환은 무시.
      2. accumulatedResult = accumulatedResult + S 의 [nextSourcePosition, position) + replacementString.
      3. nextSourcePosition = position + matchLength.
  16. nextSourcePositionlengthS 이면 accumulatedResult 반환.
  17. accumulatedResult + S 의 [nextSourcePosition, 끝) 반환.

이 메서드의 "name" 값은 "[Symbol.replace]" 이다.

22.2.6.12 RegExp.prototype [ %Symbol.search% ] ( string )

호출 시 다음을 수행한다:

  1. rx = this.
  2. rx Object 아니면 TypeError.
  3. S = ? ToString(string).
  4. previousLastIndex = ? Get(rx, "lastIndex").
  5. previousLastIndex+0𝔽 이면 ? Set(rx, "lastIndex", +0𝔽, true).
  6. result = ? RegExpExec(rx, S).
  7. currentLastIndex = ? Get(rx, "lastIndex").
  8. SameValue(currentLastIndex, previousLastIndex) = false 이면 ? Set(rx, "lastIndex", previousLastIndex, true).
  9. result = null 이면 -1𝔽 반환.
  10. Get(result, "index") 반환.

이 메서드의 "name" 값은 "[Symbol.search]" 이다.

Note

검색 수행 시 이 RegExp 객체의 "lastIndex""global" 프로퍼티는 무시되며 "lastIndex" 는 변경되지 않는다.

22.2.6.13 get RegExp.prototype.source

RegExp.prototype.source 접근자 get 은 다음을 수행한다:

  1. R = this.
  2. R Object 아니면 TypeError.
  3. R[[OriginalSource]] 슬롯 없으면
    1. SameValue(R, %RegExp.prototype%) true 이면 "(?:)" 반환.
    2. 아니면 TypeError.
  4. Assert: R[[OriginalFlags]] 슬롯을 가진다.
  5. src = R.[[OriginalSource]].
  6. flags = R.[[OriginalFlags]].
  7. EscapeRegExpPattern(src, flags) 반환.

22.2.6.13.1 EscapeRegExpPattern ( P, F )

The abstract operation EscapeRegExpPattern takes arguments P (String) and F (String) and returns String. It performs the following steps when called:

  1. F"v" 포함하면 patternSymbol = Pattern[+UnicodeMode, +UnicodeSetsMode].
  2. Else if F"u" 포함하면 patternSymbol = Pattern[+UnicodeMode, ~UnicodeSetsMode].
  3. Else patternSymbol = Pattern[~UnicodeMode, ~UnicodeSetsMode].
  4. S 를: P 를 UTF-16 인코딩된 코드 포인트로 해석(6.1.4)한 것과 동등한 patternSymbol 형태의 String 으로 하고, 아래에서 기술한 특정 코드 포인트를 이스케이프한 값으로 둔다. SP 와 다를 수도 동일할 수도 있다. SpatternSymbol 로 평가해 얻는 추상 클로저는 객체의 [[RegExpMatcher]] 가 주는 추상 클로저와 동일하게 동작해야 한다. 동일한 P, F 로 여러 번 호출 시 결과는 동일해야 한다.
  5. 패턴에 나타나는 / 또는 LineTerminator"/", S, "/", F 의 연결이 동등한 동작의 RegularExpressionLiteral 로 파싱 가능하도록 필요 시 이스케이프해야 한다. 예: P = "/" 이면 S"\/" 또는 "\u002F" 등 가능하나 "/" 는 불가 ( ///+FSingleLineComment 로 파싱 ). P 가 빈 String 이면 S = "(?:)" 로 충족할 수 있다.
  6. S 반환.
Note

RegExp.escape 와 EscapeRegExpPattern 은 목적이 다르다. 전자는 문자열을 패턴 내부 표현용으로, 후자는 패턴을 문자열 표현용으로 이스케이프한다.

22.2.6.14 RegExp.prototype [ %Symbol.split% ] ( string, limit )

Note 1

이 메서드는 string 을 String 으로 변환한 결과를 왼쪽에서 오른쪽으로 정규 표현식 매치 경계를 찾아 나눈 부분 문자열들을 Array 에 저장해 반환한다. 매치된 부분들은 반환 배열에 포함되지 않고 구분자로만 사용된다.

this 값이 빈 정규식이거나 빈 String 과 매치 가능한 정규식일 수 있다. 이 경우 입력 String 시작·끝 혹은 이전 구분자 매치 끝의 빈 substring 과는 매치하지 않는다. (예: 패턴이 빈 String 과 매치하면 문자열은 개별 코드 유닛 요소로 분해되어 결과 배열 길이는 문자열 길이와 같고 각 substring 은 한 코드 유닛을 가진다.) 특정 인덱스에서 백트래킹으로 비어 있지 않은 매치가 가능하더라도 첫 번째 매치만 고려한다. (예: /a*?/[Symbol.split]("ab")["a", "b"], /a*/[Symbol.split]("ab")["","b"])

string 이 빈 String (또는 변환 결과가 빈 String)이면 정규식이 빈 String 과 매치 가능한지 여부에 따라 결과가 달라진다. 가능하면 결과 배열은 비어 있고, 불가능하면 결과 배열은 빈 String 하나를 가진다.

정규식이 캡처 괄호를 포함하면 separator 매치 때마다 ( undefined 포함 ) 각 캡처 결과가 출력 배열에 삽입된다. 예:

/<(\/)?([^<>]+)>/[Symbol.split]("A<B>bold</B>and<CODE>coded</CODE>")

결과:

["A", undefined, "B", "bold", "/", "B", "and", undefined, "CODE", "coded", "/", "CODE", ""]

limitundefined 가 아니면 결과 배열은 최대 limit 요소로 잘린다.

호출 시 다음을 수행한다:

  1. rx = this.
  2. rx Object 아니면 TypeError.
  3. S = ? ToString(string).
  4. C = ? SpeciesConstructor(rx, %RegExp%).
  5. flags = ? ToString(? Get(rx, "flags")).
  6. flags"u" 또는 "v" 포함하면 unicodeMatching = true; 아니면 false.
  7. flags"y" 포함하면 newFlags = flags; 아니면 newFlags = flags + "y".
  8. splitter = ? Construct(C, « rx, newFlags »).
  9. A = ! ArrayCreate(0).
  10. lengthA = 0.
  11. limit = undefined 이면 lim = 232 - 1; 아니면 lim = (? ToUint32(limit)).
  12. lim = 0 이면 A 반환.
  13. S 가 빈 String 이면
    1. z = ? RegExpExec(splitter, S).
    2. znull 이면 A 반환.
    3. CreateDataPropertyOrThrow(A, "0", S).
    4. A 반환.
  14. size = S 길이.
  15. p = 0.
  16. q = p.
  17. q < size 동안 반복
    1. Set(splitter, "lastIndex", 𝔽(q), true).
    2. z = ? RegExpExec(splitter, S).
    3. z = null 이면
      1. q = AdvanceStringIndex(S, q, unicodeMatching).
    4. Else
      1. e = (? ToLength(? Get(splitter, "lastIndex")) ).
      2. e = min(e, size).
      3. e = p 이면
        1. q = AdvanceStringIndex(S, q, unicodeMatching).
      4. Else
        1. T = S 의 [p, q) 부분 문자열.
        2. CreateDataPropertyOrThrow(A, ! ToString(𝔽(lengthA)), T).
        3. lengthA = lengthA + 1.
        4. lengthA = lim 이면 A 반환.
        5. p = e.
        6. numberOfCaptures = ? LengthOfArrayLike(z).
        7. numberOfCaptures = max(numberOfCaptures - 1, 0).
        8. i = 1.
        9. inumberOfCaptures 동안
          1. nextCapture = ? Get(z, ! ToString(𝔽(i))).
          2. CreateDataPropertyOrThrow(A, ! ToString(𝔽(lengthA)), nextCapture).
          3. i = i + 1.
          4. lengthA = lengthA + 1.
          5. lengthA = lim 이면 A 반환.
        10. q = p.
  18. T = S 의 [p, size) 부분 문자열.
  19. CreateDataPropertyOrThrow(A, ! ToString(𝔽(lengthA)), T).
  20. A 반환.

이 메서드의 "name" 값은 "[Symbol.split]" 이다.

Note 2

이 메서드는 이 RegExp 객체의 "global", "sticky" 프로퍼티 값을 무시한다.

22.2.6.15 get RegExp.prototype.sticky

RegExp.prototype.sticky 접근자 get 은 다음을 수행한다:

  1. R = this.
  2. cu = 0x0079 (y).
  3. RegExpHasFlag(R, cu) 반환.

22.2.6.16 RegExp.prototype.test ( S )

호출 시 다음을 수행한다:

  1. R = this.
  2. R Object 아니면 TypeError.
  3. string = ? ToString(S).
  4. match = ? RegExpExec(R, string).
  5. matchnull 이면 true 반환; 아니면 false.

22.2.6.17 RegExp.prototype.toString ( )

  1. R = this.
  2. R Object 아니면 TypeError.
  3. pattern = ? ToString(? Get(R, "source")).
    1. flags = ? ToString(? Get(R, "flags")).
  4. result = "/" + pattern + "/" + flags.
  5. result 반환.
Note

반환된 String 은 동일한 동작을 하는 또 다른 RegExp 객체로 평가되는 RegularExpressionLiteral 형태이다.

22.2.6.18 get RegExp.prototype.unicode

RegExp.prototype.unicode 접근자 get 은 다음을 수행한다:

  1. R = this.
  2. cu = 0x0075 (u).
  3. RegExpHasFlag(R, cu) 반환.

22.2.6.19 get RegExp.prototype.unicodeSets

RegExp.prototype.unicodeSets 접근자 get 은 다음을 수행한다:

  1. R = this.
  2. cu = 0x0076 (v).
  3. RegExpHasFlag(R, cu) 반환.

22.2.7 RegExp 매칭용 추상 연산 (Abstract Operations for RegExp Matching)

22.2.7.1 RegExpExec ( R, S )

The abstract operation RegExpExec takes arguments R (Object) and S (String) and returns Object 또는 null 을 포함하는 정상 완료 또는 throw completion. It performs the following steps when called:

  1. exec = ? Get(R, "exec").
  2. IsCallable(exec) = true 이면
    1. result = ? Call(exec, R, « S »).
    2. result 가 Object 도 null 도 아니면 TypeError.
    3. result 반환.
  3. RequireInternalSlot(R, [[RegExpMatcher]]).
  4. RegExpBuiltinExec(R, S) 반환.
Note

호출 가능한 "exec" 프로퍼티가 없으면 내장 매칭 알고리즘을 사용한다. 이는 이전 버전과의 호환을 위해, 당시 대부분의 내장 알고리즘이 "exec" 의 동적 조회를 수행하지 않았던 동작을 유지한다.

22.2.7.2 RegExpBuiltinExec ( R, S )

The abstract operation RegExpBuiltinExec takes arguments R (초기화된 RegExp 인스턴스) and S (String) and returns Array exotic object 또는 null 을 포함하는 정상 완료 또는 throw completion. It performs the following steps when called:

  1. length = S 길이.
  2. lastIndex = (? ToLength(! Get(R, "lastIndex"))).
  3. flags = R.[[OriginalFlags]].
  4. flags"g" 포함하면 global = true; 아니면 false.
  5. flags"y" 포함하면 sticky = true; 아니면 false.
  6. flags"d" 포함하면 hasIndices = true; 아니면 false.
  7. global = false 이고 sticky = false 이면 lastIndex = 0.
  8. matcher = R.[[RegExpMatcher]].
  9. flags"u" 또는 "v" 포함하면 fullUnicode = true; 아니면 false.
  10. matchSucceeded = false.
  11. fullUnicode = true 이면 input = StringToCodePoints(S); 아니면 input = S 코드 유닛 List.
  12. NOTE: input 의 각 요소는 문자로 간주.
  13. matchSucceeded = false 동안 반복
    1. lastIndex > length 이면
      1. global 또는 stickytrue 이면
        1. Set(R, "lastIndex", +0𝔽, true).
      2. null 반환.
    2. inputIndex = SlastIndex 위치에서 얻은 문자의 input 내 인덱스.
    3. r = matcher(input, inputIndex).
    4. r = failure 이면
      1. sticky = true 이면
        1. Set(R, "lastIndex", +0𝔽, true).
        2. null 반환.
      2. lastIndex = AdvanceStringIndex(S, lastIndex, fullUnicode).
    5. Else
      1. Assert: rMatchState.
      2. matchSucceeded = true.
  14. e = r.[[EndIndex]].
  15. fullUnicode = true 이면 e = GetStringIndex(S, e).
  16. global 또는 sticky = true 이면
    1. Set(R, "lastIndex", 𝔽(e), true).
  17. n = r.[[Captures]] 요소 수.
  18. Assert: n = R.[[RegExpRecord]].[[CapturingGroupsCount]].
  19. Assert: n < 232 - 1.
  20. A = ! ArrayCreate(n + 1).
  21. Assert: A."length" = n + 1.
  22. CreateDataPropertyOrThrow(A, "index", 𝔽(lastIndex)).
  23. CreateDataPropertyOrThrow(A, "input", S).
  24. match = Match Record { [[StartIndex]]: lastIndex, [[EndIndex]]: e }.
  25. indices = 새 빈 List.
  26. groupNames = 새 빈 List.
  27. indicesmatch 추가.
  28. matchedSubstr = GetMatchString(S, match).
  29. CreateDataPropertyOrThrow(A, "0", matchedSubstr).
  30. RGroupName 을 하나라도 포함하면
    1. groups = OrdinaryObjectCreate(null).
    2. hasGroups = true.
  31. Else
    1. groups = undefined.
    2. hasGroups = false.
  32. CreateDataPropertyOrThrow(A, "groups", groups).
  33. matchedGroupNames = 새 빈 List.
  34. 1 ≤ in 에 대해 상승 순서 반복
    1. captureI = r.[[Captures]]i 번째 요소.
    2. captureI = undefined 이면
      1. capturedValue = undefined.
      2. indicesundefined 추가.
    3. Else
      1. captureStart = captureI.[[StartIndex]].
      2. captureEnd = captureI.[[EndIndex]].
      3. fullUnicode = true 이면
        1. captureStart = GetStringIndex(S, captureStart).
        2. captureEnd = GetStringIndex(S, captureEnd).
      4. capture = Match Record { [[StartIndex]]: captureStart, [[EndIndex]]: captureEnd }.
      5. capturedValue = GetMatchString(S, capture).
      6. indicescapture 추가.
    4. CreateDataPropertyOrThrow(A, ! ToString(𝔽(i)), capturedValue).
    5. i 번째 캡처가 GroupName 으로 정의된 경우
      1. s = 그 GroupName 의 CapturingGroupName.
      2. matchedGroupNamess 포함하면
        1. Assert: capturedValueundefined.
        2. groupNamesundefined 추가.
      3. Else
        1. capturedValueundefined 이면 matchedGroupNamess 추가.
        2. CreateDataPropertyOrThrow(groups, s, capturedValue).
        3. groupNamess 추가.
    6. Else
      1. groupNamesundefined 추가.
  35. hasIndices = true 이면
    1. indicesArray = MakeMatchIndicesIndexPairArray(S, indices, groupNames, hasGroups).
    2. CreateDataPropertyOrThrow(A, "indices", indicesArray).
  36. A 반환.

22.2.7.3 AdvanceStringIndex ( S, index, unicode )

The abstract operation AdvanceStringIndex takes arguments S (String), index (음이 아닌 정수), and unicode (Boolean) and returns 정수. It performs the following steps when called:

  1. Assert: index ≤ 253 - 1.
  2. unicode = false 이면 index + 1 반환.
  3. length = S 길이.
  4. index + 1 ≥ length 이면 index + 1 반환.
  5. cp = CodePointAt(S, index).
  6. index + cp.[[CodeUnitCount]] 반환.

22.2.7.4 GetStringIndex ( S, codePointIndex )

The abstract operation GetStringIndex takes arguments S (String) and codePointIndex (음이 아닌 정수) and returns 음이 아닌 정수. S 를 UTF-16 인코딩된 코드 포인트 시퀀스로 해석하고 codePointIndex 번째 코드 포인트에 대응하는 코드 유닛 인덱스를 반환한다. 존재하지 않으면 S 길이를 반환한다. It performs the following steps when called:

  1. S 가 빈 String 이면 0 반환.
  2. len = S 길이.
  3. codeUnitCount = 0.
  4. codePointCount = 0.
  5. codeUnitCount < len 동안
    1. codePointCount = codePointIndex 이면 codeUnitCount 반환.
    2. cp = CodePointAt(S, codeUnitCount).
    3. codeUnitCount += cp.[[CodeUnitCount]].
    4. codePointCount += 1.
  6. len 반환.

22.2.7.5 매치 레코드 (Match Records)

Match Record 는 정규 표현식 매치 또는 캡처의 시작·끝 인덱스를 캡슐화하는 Record 값이다.

Match Record 는 Table 70 의 필드를 가진다.

Table 70: Match Record 필드
Field Name Value Meaning
[[StartIndex]] 음이 아닌 정수 문자열 시작으로부터 (포함) 매치가 시작되는 코드 유닛 수.
[[EndIndex]] [[StartIndex]] 이상 정수 문자열 시작으로부터 (배타) 매치가 끝나는 코드 유닛 수.

22.2.7.6 GetMatchString ( S, match )

The abstract operation GetMatchString takes arguments S (String) and match (Match Record) and returns String. It performs the following steps when called:

  1. Assert: match.[[StartIndex]]match.[[EndIndex]]S 길이.
  2. S 의 [match.[[StartIndex]], match.[[EndIndex]]) 부분 문자열 반환.

22.2.7.7 GetMatchIndexPair ( S, match )

The abstract operation GetMatchIndexPair takes arguments S (String) and match (Match Record) and returns Array. It performs the following steps when called:

  1. Assert: match.[[StartIndex]]match.[[EndIndex]]S 길이.
  2. CreateArrayFromList𝔽(match.[[StartIndex]]), 𝔽(match.[[EndIndex]]) ») 반환.

22.2.7.8 MakeMatchIndicesIndexPairArray ( S, indices, groupNames, hasGroups )

The abstract operation MakeMatchIndicesIndexPairArray takes arguments S (String), indices (Match Record 또는 undefinedList), groupNames (String 또는 undefinedList), and hasGroups (Boolean) and returns Array. It performs the following steps when called:

  1. n = indices 요소 수.
  2. Assert: n < 232 - 1.
  3. Assert: groupNamesn - 1 요소.
  4. NOTE: groupNamesindices[1] 부터 정렬 대응.
  5. A = ! ArrayCreate(n).
  6. hasGroups = true 이면 groups = OrdinaryObjectCreate(null); 아니면 undefined.
  7. CreateDataPropertyOrThrow(A, "groups", groups).
  8. 0 ≤ i < n 에 대해 상승 순서 반복
    1. matchIndices = indices[i].
    2. matchIndicesundefined 이면 matchIndexPair = GetMatchIndexPair(S, matchIndices); 아니면 undefined.
    3. CreateDataPropertyOrThrow(A, ! ToString(𝔽(i)), matchIndexPair).
    4. i > 0 이면
      1. s = groupNames[i - 1].
      2. sundefined 이면
        1. Assert: groupsundefined.
        2. CreateDataPropertyOrThrow(groups, s, matchIndexPair).
  9. A 반환.

22.2.8 RegExp 인스턴스의 프로퍼티 (Properties of RegExp Instances)

RegExp 인스턴스는 RegExp 프로토타입으로부터 프로퍼티를 상속하는 일반 객체다. [[OriginalSource]], [[OriginalFlags]], [[RegExpRecord]], [[RegExpMatcher]] 내부 슬롯을 가지며 [[RegExpMatcher]] 값은 해당 RegExp 객체 Pattern 의 추상 클로저 표현이다.

Note

ECMAScript 2015 이전에는 RegExp 인스턴스가 자체 데이터 프로퍼티 "source", "global", "ignoreCase", "multiline" 를 가진다고 명세되었으나, 이제 RegExp.prototype접근자 프로퍼티로 정의된다.

RegExp 인스턴스는 다음 프로퍼티도 가진다:

22.2.8.1 lastIndex

"lastIndex" 프로퍼티 값은 다음 매치를 시작할 String 인덱스를 지정한다. 사용 시 정수 Number 로 강제된다( 22.2.7.2 참조 ). 이 프로퍼티 특성은 { [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false } 이다.

22.2.9 RegExp 문자열 이터레이터 객체 (RegExp String Iterator Objects)

RegExp String Iterator 는 특정 RegExp 인스턴스 객체를 사용하여 특정 String 인스턴스 객체 위를 순회(iteration)하는 과정을 표현하는 객체이다. RegExp String Iterator 객체에 대한 이름 있는 생성자는 없으며, 대신 RegExp 인스턴스 객체의 특정 메서드를 호출할 때 생성된다.

22.2.9.1 CreateRegExpStringIterator ( R, S, global, fullUnicode )

The abstract operation CreateRegExpStringIterator takes arguments R (Object), S (String), global (Boolean), and fullUnicode (Boolean) and returns Object. It performs the following steps when called:

  1. iteratorOrdinaryObjectCreate(%RegExpStringIteratorPrototype%, « [[IteratingRegExp]], [[IteratedString]], [[Global]], [[Unicode]], [[Done]] ») 로 둔다.
  2. iterator.[[IteratingRegExp]] = R.
  3. iterator.[[IteratedString]] = S.
  4. iterator.[[Global]] = global.
  5. iterator.[[Unicode]] = fullUnicode.
  6. iterator.[[Done]] = false.
  7. iterator 를 반환한다.

22.2.9.2 %RegExpStringIteratorPrototype% 객체 (The %RegExpStringIteratorPrototype% Object)

%RegExpStringIteratorPrototype% 객체는 다음을 만족한다:

  • 모든 RegExp String Iterator 객체들이 상속하는 프로퍼티들을 가진다.
  • 일반(ordinary) 객체이다.
  • 값이 %Iterator.prototype%[[Prototype]] 내부 슬롯을 가진다.
  • 다음 프로퍼티들을 가진다:

22.2.9.2.1 %RegExpStringIteratorPrototype%.next ( )

  1. Othis 값으로 둔다.
  2. O 가 Object 가 아니면 TypeError 예외를 throw 한다.
  3. ORegExp String Iterator Object Instance 의 모든 내부 슬롯( 22.2.9.3 참조 )을 갖지 않으면 TypeError 예외를 throw 한다.
  4. O.[[Done]]true 이면
    1. CreateIteratorResultObject(undefined, true) 를 반환한다.
  5. R = O.[[IteratingRegExp]].
  6. S = O.[[IteratedString]].
  7. global = O.[[Global]].
  8. fullUnicode = O.[[Unicode]].
  9. match = ? RegExpExec(R, S).
  10. matchnull 이면
    1. O.[[Done]] = true 로 설정한다.
    2. CreateIteratorResultObject(undefined, true) 를 반환한다.
  11. globalfalse 이면
    1. O.[[Done]] = true 로 설정한다.
    2. CreateIteratorResultObject(match, false) 를 반환한다.
  12. matchStr = ? ToString(? Get(match, "0")).
  13. matchStr 가 빈 String 이면
    1. thisIndex = (? ToLength(? Get(R, "lastIndex"))).
    2. nextIndex = AdvanceStringIndex(S, thisIndex, fullUnicode).
    3. Set(R, "lastIndex", 𝔽(nextIndex), true) 를 수행한다.
  14. CreateIteratorResultObject(match, false) 를 반환한다.

22.2.9.2.2 %RegExpStringIteratorPrototype% [ %Symbol.toStringTag% ]

%Symbol.toStringTag% 프로퍼티의 초기 값은 String 값 "RegExp String Iterator" 이다.

이 프로퍼티는 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true } 특성을 가진다.

22.2.9.3 RegExp 문자열 이터레이터 인스턴스의 프로퍼티 (Properties of RegExp String Iterator Instances)

RegExp String Iterator 인스턴스는 %RegExpStringIteratorPrototype% 본질(intrinsic) 객체로부터 프로퍼티를 상속하는 일반 객체이다. 이러한 인스턴스는 Table 71 에 열거된 내부 슬롯들과 함께 초기 생성된다.

Table 71: RegExp String Iterator 인스턴스의 내부 슬롯 (Internal Slots of RegExp String Iterator Instances)
Internal Slot Type Description
[[IteratingRegExp]] an Object 순회에 사용되는 정규 표현식. IsRegExp([[IteratingRegExp]]) 는 초기에는 true 이다.
[[IteratedString]] a String 순회 대상이 되는 String 값.
[[Global]] a Boolean [[IteratingRegExp]] 가 global 인지 여부.
[[Unicode]] a Boolean [[IteratingRegExp]] 가 Unicode 모드인지 여부.
[[Done]] a Boolean 순회가 완료되었는지 여부.

23 인덱스드 컬렉션 (Indexed Collections)

23.1 Array 객체 (Array Objects)

Array 는 특정 클래스의 프로퍼티 이름에 특별한 처리를 부여하는 이그조틱(exotic) 객체이다. 이러한 특별 처리에 대한 정의는 10.4.2 를 참고.

23.1.1 Array 생성자 (The Array Constructor)

Array 생성자:

  • %Array% 이다.
  • 전역 객체"Array" 프로퍼티 초기 값이다.
  • 생성자로 호출될 때 새 Array 를 생성하고 초기화한다.
  • 생성자가 아니라 함수로 호출될 때도 새 Array 를 생성하고 초기화한다. 따라서 함수 호출 Array(…) 는 동일한 인자를 갖는 객체 생성 식 new Array(…) 와 동등하다.
  • 인자 개수와 타입에 따라 동작이 달라지는 함수이다.
  • 클래스 정의의 extends 절 값으로 사용할 수 있다. 이그조틱 Array 동작을 상속하려는 서브클래스 생성자Array 이그조틱 객체인 서브클래스 인스턴스를 초기화하기 위해 Array 생성자에 대한 super 호출을 포함해야 한다. 그러나 대부분의 Array.prototype 메서드는 this 값이 Array 이그조틱 객체일 필요가 없는 제네릭 메서드이다.

23.1.1.1 Array ( ...values )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. NewTarget 이 undefined 이면 newTarget 을 활성 함수 객체로; 아니면 newTarget = NewTarget.
  2. proto 를 ? GetPrototypeFromConstructor(newTarget, "%Array.prototype%") 로 둔다.
  3. numberOfArgsvalues 의 요소 개수로 둔다.
  4. numberOfArgs = 0 이면
    1. ArrayCreate(0, proto) 를 반환.
  5. Else if numberOfArgs = 1 이면
    1. len = values[0].
    2. array = ! ArrayCreate(0, proto).
    3. len 이 Number 가 아니면
      1. CreateDataPropertyOrThrow(array, "0", len) 수행.
      2. intLen = 1𝔽.
    4. Else,
      1. intLen = ! ToUint32(len).
      2. SameValueZero(intLen, len) 이 false 이면 RangeError 예외.
    5. Set(array, "length", intLen, true) 수행.
    6. array 반환.
  6. Else,
    1. Assert: numberOfArgs ≥ 2.
    2. array = ? ArrayCreate(numberOfArgs, proto).
    3. k = 0.
    4. k < numberOfArgs 인 동안 반복
      1. Pk = ! ToString(𝔽(k)).
      2. itemK = values[k].
      3. CreateDataPropertyOrThrow(array, Pk, itemK) 수행.
      4. k = k + 1.
    5. Assert: array"length" 프로퍼티의 수학적 값numberOfArgs.
    6. array 반환.

23.1.2 Array 생성자의 프로퍼티 (Properties of the Array Constructor)

Array 생성자:

  • 값이 %Function.prototype%[[Prototype]] 내부 슬롯을 가진다.
  • 값이 1𝔽"length" 프로퍼티를 가진다.
  • 다음 프로퍼티들을 가진다:

23.1.2.1 Array.from ( items [ , mapper [ , thisArg ] ] )

이 메서드는 호출 시 다음 단계를 수행한다:

  1. Cthis 값으로 둔다.
  2. mapperundefined 이면
    1. mapping = false.
  3. Else,
    1. IsCallable(mapper) 가 false 이면 TypeError 예외.
    2. mapping = true.
  4. usingIterator = ? GetMethod(items, %Symbol.iterator%).
  5. usingIteratorundefined 가 아니면
    1. IsConstructor(C) 가 true 이면
      1. A = ? Construct(C).
    2. Else,
      1. A = ! ArrayCreate(0).
    3. iteratorRecord = ? GetIteratorFromMethod(items, usingIterator).
    4. k = 0.
    5. 반복:
      1. k ≥ 253 - 1 이면
        1. error = ThrowCompletion(새 TypeError 객체).
        2. Return ? IteratorClose(iteratorRecord, error).
      2. Pk = ! ToString(𝔽(k)).
      3. next = ? IteratorStepValue(iteratorRecord).
      4. nextdone 이면
        1. Set(A, "length", 𝔽(k), true) 수행.
        2. A 반환.
      5. mapping = true 이면
        1. mappedValue = Completion(Call(mapper, thisArg, « next, 𝔽(k) »)).
        2. IfAbruptCloseIterator(mappedValue, iteratorRecord).
      6. Else,
        1. mappedValue = next.
      7. defineStatus = Completion(CreateDataPropertyOrThrow(A, Pk, mappedValue)).
      8. IfAbruptCloseIterator(defineStatus, iteratorRecord).
      9. k = k + 1.
  6. NOTE: items 는 이터러블이 아니므로 array-like 객체로 가정.
  7. arrayLike = ! ToObject(items).
  8. len = ? LengthOfArrayLike(arrayLike).
  9. IsConstructor(C) 가 true 이면
    1. A = ? Construct(C, « 𝔽(len) »).
  10. Else,
    1. A = ? ArrayCreate(len).
  11. k = 0.
  12. k < len 동안 반복
    1. Pk = ! ToString(𝔽(k)).
    2. kValue = ? Get(arrayLike, Pk).
    3. mapping = true 이면
      1. mappedValue = ? Call(mapper, thisArg, « kValue, 𝔽(k) »).
    4. Else,
      1. mappedValue = kValue.
    5. CreateDataPropertyOrThrow(A, Pk, mappedValue) 수행.
    6. k = k + 1.
  13. Set(A, "length", 𝔽(len), true) 수행.
  14. A 반환.
Note

이 메서드는 의도적으로 제네릭한 팩토리 메서드이며 this 값이 Array 생성자일 필요가 없다. 따라서 단일 숫자 인자를 취할 수 있는 다른 생성자들로 이전되거나 상속될 수 있다.

23.1.2.2 Array.isArray ( arg )

이 함수는 호출 시 다음 단계를 수행한다:

  1. IsArray(arg) 를 반환.

23.1.2.3 Array.of ( ...items )

이 메서드는 호출 시 다음 단계를 수행한다:

  1. len = items 의 요소 개수.
  2. lenNumber = 𝔽(len).
  3. C = this 값.
  4. IsConstructor(C) true 이면
    1. A = ? Construct(C, « lenNumber »).
  5. Else,
    1. A = ? ArrayCreate(len).
  6. k = 0.
  7. k < len 동안 반복
    1. kValue = items[k].
    2. Pk = ! ToString(𝔽(k)).
    3. CreateDataPropertyOrThrow(A, Pk, kValue) 수행.
    4. k = k + 1.
  8. Set(A, "length", lenNumber, true) 수행.
  9. A 반환.
Note

이 메서드는 의도적으로 제네릭한 팩토리 메서드이며 this 값이 Array 생성자일 필요가 없다. 그러므로 단일 숫자 인자를 받을 수 있는 다른 생성자들에게 이전되거나 상속될 수 있다.

23.1.2.4 Array.prototype

Array.prototype 의 값은 Array 프로토타입 객체이다.

이 프로퍼티는 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false } 특성을 가진다.

23.1.2.5 get Array [ %Symbol.species% ]

Array[%Symbol.species%] 는 set 접근자 함수가 undefined접근자 프로퍼티이다. get 접근자 함수는 호출 시 다음을 수행한다:

  1. this 값을 반환한다.

이 함수의 "name" 프로퍼티 값은 "get [Symbol.species]" 이다.

Note

Array 프로토타입 메서드는 일반적으로 this 값의 생성자를 사용해 파생 객체를 생성한다. 그러나 서브클래스 생성자%Symbol.species% 프로퍼티 재정의를 통해 기본 동작을 재정의할 수 있다.

23.1.3 Array 프로토타입 객체의 프로퍼티 (Properties of the Array Prototype Object)

Array 프로토타입 객체:

  • %Array.prototype% 이다.
  • Array 이그조틱 객체이며 그에 지정된 내부 메서드를 가진다.
  • 초기 값이 +0𝔽 이고 특성이 { [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false } 인 "length" 프로퍼티를 가진다.
  • 값이 %Object.prototype%[[Prototype]] 내부 슬롯을 가진다.
Note

Array 프로토타입 객체는 ECMAScript 2015 이전에 작성된 코드와의 호환성을 보장하기 위해 Array 이그조틱 객체로 명세된다.

23.1.3.1 Array.prototype.at ( index )

  1. O = ? ToObject(this value).
  2. len = ? LengthOfArrayLike(O).
  3. relativeIndex = ? ToIntegerOrInfinity(index).
  4. relativeIndex ≥ 0 이면
    1. k = relativeIndex.
  5. Else,
    1. k = len + relativeIndex.
  6. k < 0 또는 klen 이면 undefined 반환.
  7. Get(O, ! ToString(𝔽(k))) 반환.

23.1.3.2 Array.prototype.concat ( ...items )

이 메서드는 객체의 배열 요소 뒤에 각 인자의 배열 요소들을 이어붙인 배열을 반환한다.

호출 시 다음 단계를 수행한다:

  1. O = ? ToObject(this value).
  2. A = ? ArraySpeciesCreate(O, 0).
  3. n = 0.
  4. items 앞에 O 를 prepend.
  5. items 의 요소 E 에 대해
    1. spreadable = ? IsConcatSpreadable(E).
    2. spreadable = true 이면
      1. len = ? LengthOfArrayLike(E).
      2. n + len > 253 - 1 이면 TypeError 예외.
      3. k = 0.
      4. k < len 동안 반복
        1. Pk = ! ToString(𝔽(k)).
        2. exists = ? HasProperty(E, Pk).
        3. exists = true 이면
          1. subElement = ? Get(E, Pk).
          2. CreateDataPropertyOrThrow(A, ! ToString(𝔽(n)), subElement) 수행.
        4. n = n + 1.
        5. k = k + 1.
    3. Else,
      1. NOTE: E 는 펼치지 않고 단일 항목으로 추가된다.
      2. n ≥ 253 - 1 이면 TypeError 예외.
      3. CreateDataPropertyOrThrow(A, ! ToString(𝔽(n)), E) 수행.
      4. n = n + 1.
  6. Set(A, "length", 𝔽(n), true) 수행.
  7. A 반환.

이 메서드의 "length" 프로퍼티는 1𝔽 이다.

Note 1

단계 6 에서 "length" 프로퍼티를 명시적으로 설정하는 것은 items 의 마지막 비어 있지 않은 요소에 후행 홀(holes)이 있거나 A 가 내장 Array 가 아닌 경우 길이가 정확하도록 하기 위함이다.

Note 2

이 메서드는 의도적으로 제네릭하며 this 값이 Array 일 필요가 없다. 따라서 다른 종류의 객체에 메서드로 이전 가능하다.

23.1.3.2.1 IsConcatSpreadable ( O )

The abstract operation IsConcatSpreadable takes argument O (ECMAScript 언어 값) and returns Boolean 을 포함하는 정상 완료 또는 throw completion. It performs the following steps when called:

  1. O 가 Object 가 아니면 false 반환.
  2. spreadable = ? Get(O, %Symbol.isConcatSpreadable%).
  3. spreadableundefined 가 아니면 ToBoolean(spreadable) 반환.
  4. IsArray(O) 반환.

23.1.3.3 Array.prototype.constructor

Array.prototype.constructor 의 초기 값은 %Array% 이다.

23.1.3.4 Array.prototype.copyWithin ( target, start [ , end ] )

Note 1

end 인자는 선택적이다. 주어지지 않으면 this 값의 길이가 사용된다.

Note 2

target 이 음수이면 배열 길이 length 에 대해 length + target 으로 간주된다. start 가 음수이면 length + start, end 가 음수이면 length + end 으로 간주.

이 메서드는 호출 시 다음 단계를 수행한다:

  1. O = ? ToObject(this value).
  2. len = ? LengthOfArrayLike(O).
  3. relativeTarget = ? ToIntegerOrInfinity(target).
  4. relativeTarget = -∞ 이면 to = 0.
  5. Else if relativeTarget < 0 이면 to = max(len + relativeTarget, 0).
  6. Else to = min(relativeTarget, len).
  7. relativeStart = ? ToIntegerOrInfinity(start).
  8. relativeStart = -∞ 이면 from = 0.
  9. Else if relativeStart < 0 이면 from = max(len + relativeStart, 0).
  10. Else from = min(relativeStart, len).
  11. endundefined 이면 relativeEnd = len; else relativeEnd = ? ToIntegerOrInfinity(end).
  12. relativeEnd = -∞ 이면 final = 0.
  13. Else if relativeEnd < 0 이면 final = max(len + relativeEnd, 0).
  14. Else final = min(relativeEnd, len).
  15. count = min(final - from, len - to).
  16. from < to 그리고 to < from + count 이면
    1. direction = -1.
    2. from = from + count - 1.
    3. to = to + count - 1.
  17. Else,
    1. direction = 1.
  18. count > 0 동안 반복
    1. fromKey = ! ToString(𝔽(from)).
    2. toKey = ! ToString(𝔽(to)).
    3. fromPresent = ? HasProperty(O, fromKey).
    4. fromPresent = true 이면
      1. fromValue = ? Get(O, fromKey).
      2. Set(O, toKey, fromValue, true) 수행.
    5. Else,
      1. Assert: fromPresent = false.
      2. DeletePropertyOrThrow(O, toKey) 수행.
    6. from = from + direction.
    7. to = to + direction.
    8. count = count - 1.
  19. O 반환.
Note 3

이 메서드는 의도적으로 제네릭하다; this 값이 Array 일 필요가 없다. 따라서 다른 객체에 이전 가능.

23.1.3.5 Array.prototype.entries ( )

이 메서드는 호출 시 다음 단계를 수행한다:

  1. O = ? ToObject(this value).
  2. CreateArrayIterator(O, key+value) 반환.

23.1.3.6 Array.prototype.every ( callback [ , thisArg ] )

Note 1

callback 은 세 인자를 받고 Boolean 으로 강제 가능한 값을 반환하는 함수여야 한다. every 는 배열에 존재하는 각 요소에 대해(누락 요소 제외) 오름차순으로 callback 을 호출하며 callbackfalse 를 반환하는 요소를 찾으면 즉시 false 를 반환한다. 찾지 못하면 true 반환. 배열의 누락된 요소에 대해서는 호출되지 않는다.

thisArg 가 제공되면 각 호출의 this 값으로 사용되고, 아니면 undefined 사용.

callback 은 (요소 값, 요소 인덱스, 탐색 중인 객체) 3개 인자로 호출.

every 자체는 객체를 직접 변경하지 않지만 callback 호출로 인해 변경될 수 있다.

every 가 처리할 요소 범위는 첫 호출 전에 고정된다. 이후 추가된 요소는 방문되지 않고, 값이 변경된 기존 요소는 방문 시점의 값이 전달되며, 방문 전에 삭제된 요소는 방문하지 않는다. 공집합(빈 배열)에 대해 true 를 반환한다.

이 메서드는 호출 시 다음 단계를 수행한다:

  1. O = ? ToObject(this value).
  2. len = ? LengthOfArrayLike(O).
  3. IsCallable(callback) false 이면 TypeError 예외.
  4. k = 0.
  5. k < len 동안 반복
    1. Pk = ! ToString(𝔽(k)).
    2. kPresent = ? HasProperty(O, Pk).
    3. kPresent = true 이면
      1. kValue = ? Get(O, Pk).
      2. testResult = ToBoolean(? Call(callback, thisArg, « kValue, 𝔽(k), O »)).
      3. testResult = false 이면 false 반환.
    4. k = k + 1.
  6. true 반환.
Note 2

이 메서드는 제네릭하여 this 값이 Array 일 필요가 없다.

23.1.3.7 Array.prototype.fill ( value [ , start [ , end ] ] )

Note 1

start 인자는 선택적이며, 없으면 +0𝔽 사용.

end 인자는 선택적이며, 없으면 this 값의 길이 사용.

Note 2

start 음수 → length + start, end 음수 → length + end.

호출 시:

  1. O = ? ToObject(this value).
  2. len = ? LengthOfArrayLike(O).
  3. relativeStart = ? ToIntegerOrInfinity(start).
  4. relativeStart = -∞ 이면 k = 0.
  5. Else if relativeStart < 0 이면 k = max(len + relativeStart, 0).
  6. Else k = min(relativeStart, len).
  7. endundefined 이면 relativeEnd = len; else relativeEnd = ? ToIntegerOrInfinity(end).
  8. relativeEnd = -∞ 이면 final = 0.
  9. Else if relativeEnd < 0 이면 final = max(len + relativeEnd, 0).
  10. Else final = min(relativeEnd, len).
  11. k < final 동안 반복
    1. Pk = ! ToString(𝔽(k)).
    2. Set(O, Pk, value, true) 수행.
    3. k = k + 1.
  12. O 반환.
Note 3

이 메서드는 제네릭.

23.1.3.8 Array.prototype.filter ( callback [ , thisArg ] )

Note 1

callback 은 세 인자를 받고 Boolean 으로 강제 가능한 값을 반환하는 함수. filter 는 배열 존재 요소(누락 제외)에 대해 오름차순 호출하며 true 를 반환한 값들로 새 배열을 만든다.

thisArg 제공 시 각 호출의 this 값, 아니면 undefined.

인자: (요소 값, 인덱스, 순회 객체).

filter 자체는 직접 변이하지 않으나 callback 으로 변이 가능.

처리 범위는 시작 전에 고정. 이후 추가 요소 방문 안 함; 값 변경된 요소는 방문 시 값; 방문 전 삭제된 요소는 방문 안 함.

호출 시:

  1. O = ? ToObject(this value).
  2. len = ? LengthOfArrayLike(O).
  3. IsCallable(callback) false 이면 TypeError.
  4. A = ? ArraySpeciesCreate(O, 0).
  5. k = 0.
  6. to = 0.
  7. k < len 동안 반복
    1. Pk = ! ToString(𝔽(k)).
    2. kPresent = ? HasProperty(O, Pk).
    3. kPresent = true 이면
      1. kValue = ? Get(O, Pk).
      2. selected = ToBoolean(? Call(callback, thisArg, « kValue, 𝔽(k), O »)).
      3. selected = true 이면
        1. CreateDataPropertyOrThrow(A, ! ToString(𝔽(to)), kValue) 수행.
        2. to = to + 1.
    4. k = k + 1.
  8. A 반환.
Note 2

제네릭.

23.1.3.9 Array.prototype.find ( predicate [ , thisArg ] )

Note 1

오름차순으로 predicate 실행하여 true 로 강제 가능한 값을 반환하는 첫 요소 값을 즉시 반환, 없으면 undefined. 추가 정보는 FindViaPredicate 참조.

호출 시:

  1. O = ? ToObject(this value).
  2. len = ? LengthOfArrayLike(O).
  3. findRec = ? FindViaPredicate(O, len, ascending, predicate, thisArg).
  4. findRec.[[Value]] 반환.
Note 2

제네릭.

23.1.3.10 Array.prototype.findIndex ( predicate [ , thisArg ] )

Note 1

오름차순으로 predicate 실행해 true 로 강제 가능한 값인 첫 요소의 인덱스 반환, 없으면 -1. FindViaPredicate 참조.

호출 시:

  1. O = ? ToObject(this value).
  2. len = ? LengthOfArrayLike(O).
  3. findRec = ? FindViaPredicate(O, len, ascending, predicate, thisArg).
  4. findRec.[[Index]] 반환.
Note 2

제네릭.

23.1.3.11 Array.prototype.findLast ( predicate [ , thisArg ] )

Note 1

내림차순으로 predicate 실행하여 true 로 강제 가능한 첫 요소 값 반환, 없으면 undefined. FindViaPredicate 참조.

호출 시:

  1. O = ? ToObject(this value).
  2. len = ? LengthOfArrayLike(O).
  3. findRec = ? FindViaPredicate(O, len, descending, predicate, thisArg).
  4. findRec.[[Value]] 반환.
Note 2

제네릭 (Array object 일 필요 없음).

23.1.3.12 Array.prototype.findLastIndex ( predicate [ , thisArg ] )

Note 1

내림차순으로 predicate 실행하여 true 로 강제 가능한 첫 요소 인덱스 반환, 없으면 -1. FindViaPredicate 참조.

호출 시:

  1. O = ? ToObject(this value).
  2. len = ? LengthOfArrayLike(O).
  3. findRec = ? FindViaPredicate(O, len, descending, predicate, thisArg).
  4. findRec.[[Index]] 반환.
Note 2

제네릭 (Array object 일 필요 없음).

23.1.3.12.1 FindViaPredicate ( O, len, direction, predicate, thisArg )

The abstract operation FindViaPredicate takes arguments O (Object), len (음이 아닌 정수), direction (ascending 또는 descending), predicate (ECMAScript 언어 값), and thisArg (ECMAScript 언어 값) and returns [[Index]] (정수 Number), [[Value]] (ECMAScript 언어 값) 필드를 가진 Record 를 포함하는 정상 완료 또는 throw completion.

O 는 배열 유사 객체 또는 TypedArray 여야 한다. 이 연산은 direction 에 따라 오름차순 또는 내림차순 인덱스 순서로 각 요소에 대해 predicate 를 호출하고, true 로 강제 가능한 값을 반환하면 그 요소의 인덱스와 값을 담은 Record 를 반환한다. 없다면 인덱스 -1𝔽, 값 undefinedRecord 반환.

predicate 는 함수여야 하며 (요소 값, 요소 인덱스, 순회 객체)의 인자를 받는다. 반환값은 Boolean 으로 강제된다.

thisArg 는 각 호출의 this 값.

이 연산 자체는 객체를 직접 변이하지 않지만 predicate 호출로 변이될 수 있다.

처리 범위는 순회 직전 고정. 이후 추가 요소는 방문되지 않고, 변경된 요소 값은 방문 시 값, 순회 시작 후 방문 전 삭제된 요소는 여전히 방문되며 프로토타입에서 조회되거나 undefined 가 된다.

It performs the following steps when called:

  1. IsCallable(predicate) false 이면 TypeError 예외.
  2. directionascending 이면
    1. indices = 0 (포함) 부터 len (배타) 까지 정수의 오름차순 List.
  3. Else,
    1. indices = 0 (포함) 부터 len (배타) 까지 정수의 내림차순 List.
  4. 각 정수 kindices 에 대해
    1. Pk = ! ToString(𝔽(k)).
    2. NOTE: OTypedArray 인 경우 이하 Get 호출은 정상 완료.
    3. kValue = ? Get(O, Pk).
    4. testResult = ? Call(predicate, thisArg, « kValue, 𝔽(k), O »).
    5. ToBoolean(testResult) true 이면 Record { [[Index]]: 𝔽(k), [[Value]]: kValue } 반환.
  5. Record { [[Index]]: -1𝔽, [[Value]]: undefined } 반환.

23.1.3.13 Array.prototype.flat ( [ depth ] )

이 메서드는 호출 시 다음 단계를 수행한다:

  1. O = ? ToObject(this value).
  2. sourceLen = ? LengthOfArrayLike(O).
  3. depthNum = 1.
  4. depthundefined 가 아니면
    1. depthNum = ? ToIntegerOrInfinity(depth).
    2. depthNum < 0 이면 depthNum = 0.
  5. A = ? ArraySpeciesCreate(O, 0).
  6. FlattenIntoArray(A, O, sourceLen, 0, depthNum) 수행.
  7. A 반환.

23.1.3.13.1 FlattenIntoArray ( target, source, sourceLen, start, depth [ , mapperFunction [ , thisArg ] ] )

The abstract operation FlattenIntoArray takes arguments target (Object), source (Object), sourceLen (음이 아닌 정수), start (음이 아닌 정수), and depth (음이 아닌 정수 또는 +∞) and optional arguments mapperFunction (함수 객체) and thisArg (ECMAScript 언어 값) and returns 음이 아닌 정수를 포함하는 정상 완료 또는 throw completion. It performs the following steps when called:

  1. Assert: mapperFunction 이 존재하면 IsCallable(mapperFunction) = true, thisArg 존재, 그리고 depth = 1.
  2. targetIndex = start.
  3. sourceIndex = +0𝔽.
  4. (sourceIndex) < sourceLen 동안 반복
    1. P = ! ToString(sourceIndex).
    2. exists = ? HasProperty(source, P).
    3. exists = true 이면
      1. element = ? Get(source, P).
      2. mapperFunction 존재하면
        1. element = ? Call(mapperFunction, thisArg, « element, sourceIndex, source »).
      3. shouldFlatten = false.
      4. depth > 0 이면
        1. shouldFlatten = ? IsArray(element).
      5. shouldFlatten = true 이면
        1. depth = +∞ 이면 newDepth = +∞; Else newDepth = depth - 1.
        2. elementLen = ? LengthOfArrayLike(element).
        3. targetIndex = ? FlattenIntoArray(target, element, elementLen, targetIndex, newDepth).
      6. Else
        1. targetIndex ≥ 253 - 1 이면 TypeError 예외.
        2. CreateDataPropertyOrThrow(target, ! ToString(𝔽(targetIndex)), element) 수행.
        3. targetIndex = targetIndex + 1.
    4. sourceIndex = sourceIndex + 1𝔽.
  5. targetIndex 반환.

23.1.3.14 Array.prototype.flatMap ( mapperFunction [ , thisArg ] )

이 메서드는 호출 시 다음 단계를 수행한다:

  1. O = ? ToObject(this value).
  2. sourceLen = ? LengthOfArrayLike(O).
  3. IsCallable(mapperFunction) false 이면 TypeError 예외.
  4. A = ? ArraySpeciesCreate(O, 0).
  5. FlattenIntoArray(A, O, sourceLen, 0, 1, mapperFunction, thisArg) 수행.
  6. A 반환.

23.1.3.15 Array.prototype.forEach ( callback [ , thisArg ] )

Note 1

callback 은 3 인자를 받는 함수. forEach 는 배열 존재 요소(누락 제외)에 대해 오름차순 1회 호출한다.

thisArg 제공 시 this, 아니면 undefined.

인자: (값, 인덱스, 객체).

직접 변이하지 않지만 callback 으로 변이 가능.

처리 범위는 시작 전에 고정; 이후 추가 요소 방문 안 함; 변경 요소 값은 방문 시; 삭제된 요소는 방문 안 함.

호출 시:

  1. O = ? ToObject(this value).
  2. len = ? LengthOfArrayLike(O).
  3. IsCallable(callback) false 이면 TypeError.
  4. k = 0.
  5. k < len 동안
    1. Pk = ! ToString(𝔽(k)).
    2. kPresent = ? HasProperty(O, Pk).
    3. kPresent = true 이면
      1. kValue = ? Get(O, Pk).
      2. Call(callback, thisArg, « kValue, 𝔽(k), O ») 수행.
    4. k = k + 1.
  6. undefined 반환.
Note 2

제네릭.

23.1.3.16 Array.prototype.includes ( searchElement [ , fromIndex ] )

Note 1

오름차순으로 SameValueZero 알고리즘을 사용해 searchElement 를 비교하며 위치가 있으면 true, 없으면 false 반환.

두 번째 인자 fromIndex 기본값 +0𝔽. 길이 이상이면 false. -0𝔽 보다 작으면 배열 끝에서의 오프셋으로 사용. 계산된 인덱스 ≤ +0𝔽 이면 전체 검색.

호출 시:

  1. O = ? ToObject(this value).
  2. len = ? LengthOfArrayLike(O).
  3. len = 0 이면 false 반환.
  4. n = ? ToIntegerOrInfinity(fromIndex).
  5. Assert: fromIndexundefined 이면 n = 0.
  6. n = +∞ 이면 false 반환.
  7. Else if n = -∞ 이면 n = 0.
  8. n ≥ 0 이면
    1. k = n.
  9. Else,
    1. k = len + n.
    2. k < 0 이면 k = 0.
  10. k < len 동안
    1. elementK = ? Get(O, ! ToString(𝔽(k))).
    2. SameValueZero(searchElement, elementK) true 이면 true 반환.
    3. k = k + 1.
  11. false 반환.
Note 2

제네릭.

Note 3

indexOf 와 다르게 SameValueZero 사용으로 NaN 탐지 가능하며 누락 요소를 건너뛰지 않고 undefined 로 처리.

23.1.3.17 Array.prototype.indexOf ( searchElement [ , fromIndex ] )

오름차순으로 IsStrictlyEqual 알고리즘으로 비교하여 발견된 가장 작은 인덱스 반환, 없으면 -1𝔽.

Note 1

두 번째 인자 fromIndex 기본 +0𝔽. 길이 이상이면 -1𝔽. -0𝔽 보다 작으면 끝에서 오프셋. 계산 인덱스 ≤ +0𝔽 이면 전체 검색.

호출 시:

  1. O = ? ToObject(this value).
  2. len = ? LengthOfArrayLike(O).
  3. len = 0 이면 -1𝔽 반환.
  4. n = ? ToIntegerOrInfinity(fromIndex).
  5. Assert: fromIndex undefinedn = 0.
  6. n = +∞ 이면 -1𝔽 반환.
  7. Else if n = -∞ ⇒ n = 0.
  8. n ≥ 0 이면
    1. k = n.
  9. Else
    1. k = len + n.
    2. k < 0 ⇒ k = 0.
  10. k < len 동안
    1. Pk = ! ToString(𝔽(k)).
    2. kPresent = ? HasProperty(O, Pk).
    3. kPresent = true 이면
      1. elementK = ? Get(O, Pk).
      2. IsStrictlyEqual(searchElement, elementK) true 이면 𝔽(k) 반환.
    4. k = k + 1.
  11. -1𝔽 반환.
Note 2

제네릭.

23.1.3.18 Array.prototype.join ( separator )

요소들을 String 으로 변환 후 separator 로 구분해 연결한 String 반환. 구분자 생략 시 쉼표 사용.

호출 시:

  1. O = ? ToObject(this value).
  2. len = ? LengthOfArrayLike(O).
  3. separatorundefined 이면 sep = ",".
  4. Else sep = ? ToString(separator).
  5. R = 빈 String.
  6. k = 0.
  7. k < len 동안
    1. k > 0 이면 R = R + sep.
    2. element = ? Get(O, ! ToString(𝔽(k))).
    3. elementundefined, null 이 아니면
      1. S = ? ToString(element).
      2. R = R + S.
    4. k = k + 1.
  8. R 반환.
Note

제네릭.

23.1.3.19 Array.prototype.keys ( )

호출 시:

  1. O = ? ToObject(this value).
  2. CreateArrayIterator(O, key) 반환.

23.1.3.20 Array.prototype.lastIndexOf ( searchElement [ , fromIndex ] )

Note 1

내림차순 IsStrictlyEqual 로 비교, 발견된 가장 큰 인덱스 반환, 없으면 -1𝔽. fromIndex 기본은 길이 - 1.

호출 시:

  1. O = ? ToObject(this value).
  2. len = ? LengthOfArrayLike(O).
  3. len = 0 이면 -1𝔽 반환.
  4. fromIndex 존재하면 n = ? ToIntegerOrInfinity(fromIndex); else n = len - 1.
  5. n = -∞ 이면 -1𝔽 반환.
  6. n ≥ 0 이면
    1. k = min(n, len - 1).
  7. Else
    1. k = len + n.
  8. k ≥ 0 동안
    1. Pk = ! ToString(𝔽(k)).
    2. kPresent = ? HasProperty(O, Pk).
    3. kPresent = true 이면
      1. elementK = ? Get(O, Pk).
      2. IsStrictlyEqual(searchElement, elementK) true 이면 𝔽(k) 반환.
    4. k = k - 1.
  9. -1𝔽 반환.
Note 2

제네릭.

23.1.3.21 Array.prototype.map ( callback [ , thisArg ] )

Note 1

각 존재 요소에 대해 오름차순으로 callback 실행하고 결과로 새 Array 구성. 누락 요소는 호출 안 함.

thisArg 있으면 this, 없으면 undefined.

인자: (값, 인덱스, 객체).

map 은 직접 변이 안 하지만 callback 으로 변이 가능.

범위는 시작 전 고정. 이후 추가 요소 방문 안 함; 변경 요소는 방문 시 값; 삭제된 요소는 방문 안 함.

호출 시:

  1. O = ? ToObject(this value).
  2. len = ? LengthOfArrayLike(O).
  3. IsCallable(callback) false 이면 TypeError.
  4. A = ? ArraySpeciesCreate(O, len).
  5. k = 0.
  6. k < len 동안
    1. Pk = ! ToString(𝔽(k)).
    2. kPresent = ? HasProperty(O, Pk).
    3. kPresent = true 이면
      1. kValue = ? Get(O, Pk).
      2. mappedValue = ? Call(callback, thisArg, « kValue, 𝔽(k), O »).
      3. CreateDataPropertyOrThrow(A, Pk, mappedValue) 수행.
    4. k = k + 1.
  7. A 반환.
Note 2

제네릭.

23.1.3.22 Array.prototype.pop ( )

Note 1

배열의 마지막 요소를 제거하고 그 값을 반환.

호출 시:

  1. O = ? ToObject(this value).
  2. len = ? LengthOfArrayLike(O).
  3. len = 0 이면
    1. Set(O, "length", +0𝔽, true).
    2. undefined 반환.
  4. Else
    1. Assert: len > 0.
    2. newLen = 𝔽(len - 1).
    3. index = ! ToString(newLen).
    4. element = ? Get(O, index).
    5. DeletePropertyOrThrow(O, index).
    6. Set(O, "length", newLen, true).
    7. element 반환.
Note 2

제네릭.

23.1.3.23 Array.prototype.push ( ...items )

Note 1

인자들을 나타나는 순서대로 배열 끝에 추가하고 새 길이를 반환.

호출 시:

  1. O = ? ToObject(this value).
  2. len = ? LengthOfArrayLike(O).
  3. argCount = items 요소 개수.
  4. len + argCount > 253 - 1 이면 TypeError 예외.
  5. items 요소 E 에 대해
    1. Set(O, ! ToString(𝔽(len)), E, true) 수행.
    2. len = len + 1.
  6. Set(O, "length", 𝔽(len), true) 수행.
  7. 𝔽(len) 반환.

이 메서드의 "length" 프로퍼티는 1𝔽.

Note 2

제네릭.

23.1.3.24 Array.prototype.reduce ( callback [ , initialValue ] )

Note 1

callback 은 네 인자를 받는 함수. reduce 는 첫 요소 이후 각 존재 요소에 대해 오름차순 호출.

인자: previousValue, currentValue, currentIndex, 순회 객체. 첫 호출 시 initialValue 가 제공되면 previousValue = initialValue, currentValue = 첫 값; 없으면 previousValue = 첫 값, currentValue = 두 번째 값. 요소 없고 initialValue 미제공 시 TypeError.

직접 변이하지 않지만 호출로 변이될 수 있음.

처리 범위는 시작 전 고정. 이후 추가 요소 방문 안 함; 변경 요소 값은 방문 시 값; 삭제된 요소 방문 안 함.

호출 시:

  1. O = ? ToObject(this value).
  2. len = ? LengthOfArrayLike(O).
  3. IsCallable(callback) false 이면 TypeError.
  4. len = 0 이고 initialValue 미존재이면 TypeError.
  5. k = 0.
  6. accumulator = undefined.
  7. initialValue 존재하면
    1. accumulator = initialValue.
  8. Else
    1. kPresent = false.
    2. kPresent = false 그리고 k < len 동안
      1. Pk = ! ToString(𝔽(k)).
      2. kPresent = ? HasProperty(O, Pk).
      3. kPresent = true 이면
        1. accumulator = ? Get(O, Pk).
      4. k = k + 1.
    3. kPresent = false 이면 TypeError.
  9. k < len 동안
    1. Pk = ! ToString(𝔽(k)).
    2. kPresent = ? HasProperty(O, Pk).
    3. kPresent = true 이면
      1. kValue = ? Get(O, Pk).
      2. accumulator = ? Call(callback, undefined, « accumulator, kValue, 𝔽(k), O »).
    4. k = k + 1.
  10. accumulator 반환.
Note 2

제네릭.

23.1.3.25 Array.prototype.reduceRight ( callback [ , initialValue ] )

Note 1

callback 은 네 인자를 받는 함수. reduceRight 는 마지막 요소 이전 각 존재 요소를 내림차순 호출.

첫 호출 시 initialValue 있으면 previousValue = initialValue, currentValue = 마지막 값; 없으면 previousValue = 마지막 값, currentValue = 끝에서 두 번째. 요소 없고 initialValue 없으면 TypeError.

변이 규칙은 reduce 와 유사.

호출 시:

  1. O = ? ToObject(this value).
  2. len = ? LengthOfArrayLike(O).
  3. IsCallable(callback) false 이면 TypeError.
  4. len = 0 이고 initialValue 미존재이면 TypeError.
  5. k = len - 1.
  6. accumulator = undefined.
  7. initialValue 존재하면
    1. accumulator = initialValue.
  8. Else
    1. kPresent = false.
    2. kPresent = false 그리고 k ≥ 0 동안
      1. Pk = ! ToString(𝔽(k)).
      2. kPresent = ? HasProperty(O, Pk).
      3. kPresent = true 이면
        1. accumulator = ? Get(O, Pk).
      4. k = k - 1.
    3. kPresent = false 이면 TypeError.
  9. k ≥ 0 동안
    1. Pk = ! ToString(𝔽(k)).
    2. kPresent = ? HasProperty(O, Pk).
    3. kPresent = true 이면
      1. kValue = ? Get(O, Pk).
      2. accumulator = ? Call(callback, undefined, « accumulator, kValue, 𝔽(k), O »).
    4. k = k - 1.
  10. accumulator 반환.
Note 2

제네릭.

23.1.3.26 Array.prototype.reverse ( )

Note 1

배열 요소 순서를 반대로 재배열하고 그 배열을 반환.

호출 시:

  1. O = ? ToObject(this value).
  2. len = ? LengthOfArrayLike(O).
  3. middle = floor(len / 2).
  4. lower = 0.
  5. lowermiddle 동안
    1. upper = len - lower - 1.
    2. upperP = ! ToString(𝔽(upper)).
    3. lowerP = ! ToString(𝔽(lower)).
    4. lowerExists = ? HasProperty(O, lowerP).
    5. lowerExists = true 이면
      1. lowerValue = ? Get(O, lowerP).
    6. upperExists = ? HasProperty(O, upperP).
    7. upperExists = true 이면
      1. upperValue = ? Get(O, upperP).
    8. lowerExists = true 그리고 upperExists = true 이면
      1. Set(O, lowerP, upperValue, true).
      2. Set(O, upperP, lowerValue, true).
    9. Else if lowerExists = false 그리고 upperExists = true
      1. Set(O, lowerP, upperValue, true).
      2. DeletePropertyOrThrow(O, upperP).
    10. Else if lowerExists = true 그리고 upperExists = false
      1. DeletePropertyOrThrow(O, lowerP).
      2. Set(O, upperP, lowerValue, true).
    11. Else
      1. Assert: 둘 다 false.
      2. NOTE: 동작 없음.
    12. lower = lower + 1.
  6. O 반환.
Note 2

제네릭.

23.1.3.27 Array.prototype.shift ( )

배열의 첫 요소를 제거하고 그 값을 반환한다.

호출 시:

  1. O = ? ToObject(this value).
  2. len = ? LengthOfArrayLike(O).
  3. len = 0 이면
    1. Set(O, "length", +0𝔽, true).
    2. undefined 반환.
  4. first = ? Get(O, "0").
  5. k = 1.
  6. k < len 동안
    1. from = ! ToString(𝔽(k)).
    2. to = ! ToString(𝔽(k - 1)).
    3. fromPresent = ? HasProperty(O, from).
    4. fromPresent = true 이면
      1. fromValue = ? Get(O, from).
      2. Set(O, to, fromValue, true).
    5. Else
      1. Assert: fromPresent = false.
      2. DeletePropertyOrThrow(O, to).
    6. k = k + 1.
  7. DeletePropertyOrThrow(O, ! ToString(𝔽(len - 1))).
  8. Set(O, "length", 𝔽(len - 1), true).
  9. first 반환.
Note

제네릭.

23.1.3.28 Array.prototype.slice ( start, end )

배열의 start 부터 (포함), end (배타) 까지 요소를 포함하는 배열을 반환 (endundefined 이면 끝까지). start 음수 → length + start, end 음수 → length + end.

호출 시:

  1. O = ? ToObject(this value).
  2. len = ? LengthOfArrayLike(O).
  3. relativeStart = ? ToIntegerOrInfinity(start).
  4. relativeStart = -∞ 이면 k = 0.
  5. Else if relativeStart < 0 이면 k = max(len + relativeStart, 0).
  6. Else k = min(relativeStart, len).
  7. end undefined 이면 relativeEnd = len; else relativeEnd = ? ToIntegerOrInfinity(end).
  8. relativeEnd = -∞ 이면 final = 0.
  9. Else if relativeEnd < 0 이면 final = max(len + relativeEnd, 0).
  10. Else final = min(relativeEnd, len).
  11. count = max(final - k, 0).
  12. A = ? ArraySpeciesCreate(O, count).
  13. n = 0.
  14. k < final 동안
    1. Pk = ! ToString(𝔽(k)).
    2. kPresent = ? HasProperty(O, Pk).
    3. kPresent = true 이면
      1. kValue = ? Get(O, Pk).
      2. CreateDataPropertyOrThrow(A, ! ToString(𝔽(n)), kValue) 수행.
    4. k = k + 1.
    5. n = n + 1.
  15. Set(A, "length", 𝔽(n), true) 수행.
  16. A 반환.
Note 1

단계 15 에서 "length" 를 명시적으로 설정하는 것은 A 가 내장 Array 가 아닌 경우에도 길이가 정확하도록 하기 위함.

Note 2

제네릭.

23.1.3.29 Array.prototype.some ( callback [ , thisArg ] )

Note 1

callback 은 세 인자를 받고 Boolean 으로 강제 가능한 값을 반환. some 은 존재 요소를 오름차순으로 호출하다가 true 반환 시 즉시 true, 없으면 false. 누락 요소는 호출 안 함.

thisArg 제공 시 this, 아니면 undefined.

인자: (요소 값, 인덱스, 객체).

직접 변이하지 않지만 callback 으로 변이 가능.

처리 범위는 시작 전 고정. 이후 추가 요소 방문 안 함; 변경 요소 값은 방문 시 값; 삭제된 요소 방문 안 함. 빈 배열이면 false.

호출 시:

  1. O = ? ToObject(this value).
  2. len = ? LengthOfArrayLike(O).
  3. IsCallable(callback) false 이면 TypeError.
  4. k = 0.
  5. k < len 동안
    1. Pk = ! ToString(𝔽(k)).
    2. kPresent = ? HasProperty(O, Pk).
    3. kPresent = true 이면
      1. kValue = ? Get(O, Pk).
      2. testResult = ToBoolean(? Call(callback, thisArg, « kValue, 𝔽(k), O »)).
      3. testResult = true 이면 true 반환.
    4. k = k + 1.
  6. false 반환.
Note 2

제네릭.

23.1.3.30 Array.prototype.sort ( comparator )

배열 요소를 정렬한다. comparatorundefined 가 아니면 두 인자 x, y 를 받아 x < y 이면 음수, x > y 이면 양수, 같으면 0인 Number 를 반환하는 함수여야 한다.

호출 시:

  1. comparatorundefined 이고 IsCallable(comparator) = false 이면 TypeError.
  2. obj = ? ToObject(this value).
  3. len = ? LengthOfArrayLike(obj).
  4. SortCompare 를 (x, y) 매개변수로 하고 comparator 캡처하여 호출 시 ? CompareArrayElements(x, y, comparator) 를 반환하는 새 추상 클로저로 둔다.
  5. sortedList = ? SortIndexedProperties(obj, len, SortCompare, skip-holes).
  6. itemCount = sortedList 의 요소 수.
  7. j = 0.
  8. j < itemCount 동안
    1. Set(obj, ! ToString(𝔽(j)), sortedList[j], true) 수행.
    2. j = j + 1.
  9. NOTE: 단계 5 에서 skip-holes 사용. 남은 인덱스는 감지된 홀 수를 유지하기 위해 삭제된다.
  10. j < len 동안
    1. DeletePropertyOrThrow(obj, ! ToString(𝔽(j))) 수행.
    2. j = j + 1.
  11. obj 반환.
Note 1

존재하지 않는 프로퍼티 값은 항상 undefined 프로퍼티 값보다 크고, undefined 는 다른 어떤 값보다 크기 때문에 (CompareArrayElements 참조) undefined 값이 결과 끝에, 그 뒤에 존재하지 않는 값이 온다.

Note 2

단계 5, 6ToString 호출은 SortCompare일관 비교자가 아니게 만들 수 있다.

Note 3

제네릭.

23.1.3.30.1 SortIndexedProperties ( obj, len, SortCompare, holes )

The abstract operation SortIndexedProperties takes arguments obj (Object), len (음이 아닌 정수), SortCompare (두 매개변수 추상 클로저), and holes (skip-holes 또는 read-through-holes) and returns ECMAScript 언어 값 List 를 포함하는 정상 완료 또는 throw completion. It performs the following steps when called:

  1. items = 새 빈 List.
  2. k = 0.
  3. k < len 동안
    1. Pk = ! ToString(𝔽(k)).
    2. holesskip-holes 이면
      1. kRead = ? HasProperty(obj, Pk).
    3. Else
      1. Assert: holes = read-through-holes.
      2. kRead = true.
    4. kRead = true 이면
      1. kValue = ? Get(obj, Pk).
      2. itemskValue 추가.
    5. k = k + 1.
  4. 구현 정의 순서의 SortCompare 호출items 정렬. abrupt completion 반환 시 추가 호출 중지 후 그 Completion Record 반환.
  5. items 반환.

정렬 순서 는 위 알고리즘 단계 4 완료 후 items 의 순서. SortCompare일관 비교자가 아니면 구현 정의. Array.prototype.sort 또는 Array.prototype.toSorted 가 호출할 때 comparatorundefined 이고 특정 값에 대한 모든 ToString 적용 결과가 동일하지 않으면 정렬 순서 역시 구현 정의.

구현 정의 아닌 경우 다음 조건 충족 필요:

  • itemCount 보다 작은 음이 아닌 정수의 어떤 수학적 순열 π 가 존재하여, 모든 j 에 대해 old[j] 와 new[π(j)] 는 정확히 동일해야 한다.
  • 모든 j, k (각각 itemCount 미만) 대해 (SortCompare(old[j], old[k])) < 0이면 π(j) < π(k).
  • j < k < itemCount 이고 (SortCompare(old[j], old[k])) = 0 이면 π(j) < π(k) (안정 정렬).

old[j] 표기는 단계 4 실행 전 items[j] 를, new[j] 표기는 실행 후 items[j] 를 의미.

추상 클로저 또는 함수 comparator 가 집합 S 에 대한 일관 비교자 이려면 S 내 값 a, b, c (동일 가능)에 대해 다음 조건 만족: a <C b(comparator(a, b)) < 0, a =C b 는 0, a >C b 는 > 0 뜻.

  • 특정 (a, b) 쌍에 대해 comparator(a, b) 는 항상 동일 v (Number, NaN 아님) 반환. 따라서 정확히 하나만 성립.
  • comparator(a, b) 호출은 obj 또는 그 프로토타입 체인 객체를 수정하지 않는다.
  • a =C a (반사성)
  • a =C bb =C a (대칭성)
  • a =C b, b =C ca =C c (이행성)
  • a <C b, b <C ca <C c
  • a >C b, b >C ca >C c
Note

위 조건은 comparatorS 를 등가류로 나누고 그 등가류가 전순서를 갖도록 하는 데 필요충분.

23.1.3.30.2 CompareArrayElements ( x, y, comparator )

The abstract operation CompareArrayElements takes arguments x (ECMAScript 언어 값), y (ECMAScript 언어 값), and comparator (함수 객체 또는 undefined) and returns Number 를 포함하는 정상 완료 또는 abrupt completion. It performs the following steps when called:

  1. x, y 둘 다 undefined 이면 +0𝔽 반환.
  2. xundefined 이면 1𝔽 반환.
  3. yundefined 이면 -1𝔽 반환.
  4. comparatorundefined 이면
    1. v = ? ToNumber(? Call(comparator, undefined, « x, y »)).
    2. vNaN 이면 +0𝔽 반환.
    3. v 반환.
  5. xString = ? ToString(x).
  6. yString = ? ToString(y).
  7. xSmaller = ! IsLessThan(xString, yString, true).
  8. xSmaller = true 이면 -1𝔽 반환.
  9. ySmaller = ! IsLessThan(yString, xString, true).
  10. ySmaller = true 이면 1𝔽 반환.
  11. +0𝔽 반환.

23.1.3.31 Array.prototype.splice ( start, deleteCount, ...items )

Note 1

이 메서드는 정수 인덱스 start 부터 deleteCount 개 요소를 삭제하고 items 요소로 대체한다. 삭제된 요소(있다면)를 담은 Array 반환.

호출 시:

  1. O = ? ToObject(this value).
  2. len = ? LengthOfArrayLike(O).
  3. relativeStart = ? ToIntegerOrInfinity(start).
  4. relativeStart = -∞ 이면 actualStart = 0.
  5. Else if relativeStart < 0 이면 actualStart = max(len + relativeStart, 0).
  6. Else actualStart = min(relativeStart, len).
  7. itemCount = items 요소 개수.
  8. start 미존재이면
    1. actualDeleteCount = 0.
  9. Else if deleteCount 미존재이면
    1. actualDeleteCount = len - actualStart.
  10. Else
    1. dc = ? ToIntegerOrInfinity(deleteCount).
    2. actualDeleteCount = dc 를 0 과 len - actualStart 사이로 clamp 한 값.
  11. len + itemCount - actualDeleteCount > 253 - 1 이면 TypeError.
  12. A = ? ArraySpeciesCreate(O, actualDeleteCount).
  13. k = 0.
  14. k < actualDeleteCount 동안
    1. from = ! ToString(𝔽(actualStart + k)).
    2. HasProperty(O, from) = true 이면
      1. fromValue = ? Get(O, from).
      2. CreateDataPropertyOrThrow(A, ! ToString(𝔽(k)), fromValue) 수행.
    3. k = k + 1.
  15. Set(A, "length", 𝔽(actualDeleteCount), true) 수행.
  16. itemCount < actualDeleteCount 이면
    1. k = actualStart.
    2. k < (len - actualDeleteCount) 동안
      1. from = ! ToString(𝔽(k + actualDeleteCount)).
      2. to = ! ToString(𝔽(k + itemCount)).
      3. HasProperty(O, from) = true 이면
        1. fromValue = ? Get(O, from).
        2. Set(O, to, fromValue, true).
      4. Else
        1. DeletePropertyOrThrow(O, to).
      5. k = k + 1.
    3. k = len.
    4. k > (len - actualDeleteCount + itemCount) 동안
      1. DeletePropertyOrThrow(O, ! ToString(𝔽(k - 1))).
      2. k = k - 1.
  17. Else if itemCount > actualDeleteCount 이면
    1. k = (len - actualDeleteCount).
    2. k > actualStart 동안
      1. from = ! ToString(𝔽(k + actualDeleteCount - 1)).
      2. to = ! ToString(𝔽(k + itemCount - 1)).
      3. HasProperty(O, from) = true 이면
        1. fromValue = ? Get(O, from).
        2. Set(O, to, fromValue, true).
      4. Else
        1. DeletePropertyOrThrow(O, to).
      5. k = k - 1.
  18. k = actualStart.
  19. items 요소 E 에 대해
    1. Set(O, ! ToString(𝔽(k)), E, true).
    2. k = k + 1.
  20. Set(O, "length", 𝔽(len - actualDeleteCount + itemCount), true) 수행.
  21. A 반환.
Note 2

단계 15, 20 의 명시적 설정은 내장 Array 가 아닌 경우에도 길이가 정확하도록 하기 위함.

Note 3

제네릭.

23.1.3.32 Array.prototype.toLocaleString ( [ reserved1 [ , reserved2 ] ] )

ECMA-402 국제화 API 를 포함하는 구현은 ECMA-402 명세에 따라 이 메서드를 구현해야 한다. 포함하지 않으면 아래 명세를 사용.

Note 1

ECMA-402 첫 에디션은 이 메서드의 대체 명세를 포함하지 않았다.

선택적 매개변수의 의미는 ECMA-402 명세에서 정의되며, 이를 포함하지 않는 구현은 다른 용도로 사용해서는 안 된다.

호출 시:

  1. array = ? ToObject(this value).
  2. len = ? LengthOfArrayLike(array).
  3. separator = 호스트 환경 현재 로캘에 적합한 구현 정의 목록 구분자 String (예: ", ").
  4. R = 빈 String.
  5. k = 0.
  6. k < len 동안
    1. k > 0 이면 R = R + separator.
    2. element = ? Get(array, ! ToString(𝔽(k))).
    3. elementundefined, null 이 아니면
      1. S = ? ToString(? Invoke(element, "toLocaleString")).
      2. R = R + S.
    4. k = k + 1.
  7. R 반환.
Note 2

각 요소를 toLocaleString 으로 변환하고 로캘 민감 구분자 String 으로 결합. toString 과 유사하나 로캘 민감 결과를 의도.

Note 3

제네릭.

23.1.3.33 Array.prototype.toReversed ( )

호출 시:

  1. O = ? ToObject(this value).
  2. len = ? LengthOfArrayLike(O).
  3. A = ? ArrayCreate(len).
  4. k = 0.
  5. k < len 동안
    1. from = ! ToString(𝔽(len - k - 1)).
    2. Pk = ! ToString(𝔽(k)).
    3. fromValue = ? Get(O, from).
    4. CreateDataPropertyOrThrow(A, Pk, fromValue) 수행.
    5. k = k + 1.
  6. A 반환.

23.1.3.34 Array.prototype.toSorted ( comparator )

호출 시:

  1. comparatorundefined 그리고 IsCallable(comparator) = false 이면 TypeError.
  2. O = ? ToObject(this value).
  3. len = ? LengthOfArrayLike(O).
  4. A = ? ArrayCreate(len).
  5. SortCompare 를 (x, y) → ? CompareArrayElements(x, y, comparator) 클로저로 둔다.
  6. sortedList = ? SortIndexedProperties(O, len, SortCompare, read-through-holes).
  7. j = 0.
  8. j < len 동안
    1. CreateDataPropertyOrThrow(A, ! ToString(𝔽(j)), sortedList[j]) 수행.
    2. j = j + 1.
  9. A 반환.

23.1.3.35 Array.prototype.toSpliced ( start, skipCount, ...items )

호출 시:

  1. O = ? ToObject(this value).
  2. len = ? LengthOfArrayLike(O).
  3. relativeStart = ? ToIntegerOrInfinity(start).
  4. relativeStart = -∞ 이면 actualStart = 0.
  5. Else if relativeStart < 0 이면 actualStart = max(len + relativeStart, 0).
  6. Else actualStart = min(relativeStart, len).
  7. insertCount = items 요소 개수.
  8. start 미존재이면
    1. actualSkipCount = 0.
  9. Else if skipCount 미존재이면
    1. actualSkipCount = len - actualStart.
  10. Else
    1. sc = ? ToIntegerOrInfinity(skipCount).
    2. actualSkipCount = sc 를 0 과 len - actualStart 사이로 clamp.
  11. newLen = len + insertCount - actualSkipCount.
  12. newLen > 253 - 1 이면 TypeError.
  13. A = ? ArrayCreate(newLen).
  14. i = 0.
  15. r = actualStart + actualSkipCount.
  16. i < actualStart 동안
    1. Pi = ! ToString(𝔽(i)).
    2. iValue = ? Get(O, Pi).
    3. CreateDataPropertyOrThrow(A, Pi, iValue) 수행.
    4. i = i + 1.
  17. items 요소 E 에 대해
    1. Pi = ! ToString(𝔽(i)).
    2. CreateDataPropertyOrThrow(A, Pi, E) 수행.
    3. i = i + 1.
  18. i < newLen 동안
    1. Pi = ! ToString(𝔽(i)).
    2. from = ! ToString(𝔽(r)).
    3. fromValue = ? Get(O, from).
    4. CreateDataPropertyOrThrow(A, Pi, fromValue) 수행.
    5. i = i + 1.
    6. r = r + 1.
  19. A 반환.

23.1.3.36 Array.prototype.toString ( )

호출 시:

  1. array = ? ToObject(this value).
  2. func = ? Get(array, "join").
  3. IsCallable(func) false 이면 func = 본질 함수 %Object.prototype.toString%.
  4. Call(func, array) 반환.
Note

제네릭.

23.1.3.37 Array.prototype.unshift ( ...items )

인자를 배열 앞에 추가하며, 추가된 순서를 유지.

호출 시:

  1. O = ? ToObject(this value).
  2. len = ? LengthOfArrayLike(O).
  3. argCount = items 요소 개수.
  4. argCount > 0 이면
    1. len + argCount > 253 - 1 이면 TypeError.
    2. k = len.
    3. k > 0 동안
      1. from = ! ToString(𝔽(k - 1)).
      2. to = ! ToString(𝔽(k + argCount - 1)).
      3. fromPresent = ? HasProperty(O, from).
      4. fromPresent = true 이면
        1. fromValue = ? Get(O, from).
        2. Set(O, to, fromValue, true).
      5. Else
        1. Assert: fromPresent = false.
        2. DeletePropertyOrThrow(O, to).
      6. k = k - 1.
    4. j = +0𝔽.
    5. items 요소 E 에 대해
      1. Set(O, ! ToString(j), E, true).
      2. j = j + 1𝔽.
  5. Set(O, "length", 𝔽(len + argCount), true) 수행.
  6. 𝔽(len + argCount) 반환.

이 메서드의 "length" 프로퍼티는 1𝔽.

Note

제네릭.

23.1.3.38 Array.prototype.values ( )

호출 시:

  1. O = ? ToObject(this value).
  2. CreateArrayIterator(O, value) 반환.

23.1.3.39 Array.prototype.with ( index, value )

호출 시:

  1. O = ? ToObject(this value).
  2. len = ? LengthOfArrayLike(O).
  3. relativeIndex = ? ToIntegerOrInfinity(index).
  4. relativeIndex ≥ 0 이면 actualIndex = relativeIndex; Else actualIndex = len + relativeIndex.
  5. actualIndexlen 또는 actualIndex < 0 이면 RangeError 예외.
  6. A = ? ArrayCreate(len).
  7. k = 0.
  8. k < len 동안
    1. Pk = ! ToString(𝔽(k)).
    2. k = actualIndex 이면 fromValue = value; Else fromValue = ? Get(O, Pk).
    3. CreateDataPropertyOrThrow(A, Pk, fromValue) 수행.
    4. k = k + 1.
  9. A 반환.

23.1.3.40 Array.prototype [ %Symbol.iterator% ] ( )

%Symbol.iterator% 프로퍼티의 초기 값은 23.1.3.38 에 정의된 %Array.prototype.values% 이다.

23.1.3.41 Array.prototype [ %Symbol.unscopables% ]

%Symbol.unscopables% 데이터 프로퍼티의 초기 값은 다음 단계를 통해 생성된 객체이다:

  1. unscopableList = OrdinaryObjectCreate(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 반환.

이 프로퍼티 특성은 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }.

Note

이 객체의 자체 프로퍼티 이름들은 ECMAScript 2015 이전 Array.prototype 표준 프로퍼티가 아니던 이름들이다. 이 이름들은 with 문 바인딩 목적에서 무시되어, Array 를 바인딩 객체로 사용하는 with 문에 의해 외부 스코프 바인딩이 가려지는 기존 코드 동작을 보존한다.

"with"unscopableList 에 포함되지 않는 이유는 이미 예약어 이기 때문이다.

23.1.4 Array 인스턴스의 프로퍼티 (Properties of Array Instances)

Array 인스턴스는 Array 이그조틱 객체이며 해당 객체에 지정된 내부 메서드를 가진다. 또한 Array 프로토타입 객체로부터 프로퍼티를 상속한다.

Array 인스턴스는 "length" 프로퍼티와 배열 인덱스 이름을 가진 열거 가능한 프로퍼티 집합을 가진다.

23.1.4.1 length

Array 인스턴스의 "length" 프로퍼티는 그 값이 배열 인덱스 이름을 가진 모든 설정 가능( configurable ) 자체 프로퍼티 이름보다 항상 수치적으로 큰 데이터 프로퍼티이다.

"length" 프로퍼티는 초기 특성 { [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false } 를 가진다.

Note

"length" 값을 줄이면 이전 길이와 새 길이 사이의 인덱스를 가진 자체 배열 요소가 삭제된다. 단, non-configurable 프로퍼티는 삭제되지 않는다. 배열의 "length" 를 기존 non-configurable array-indexed 프로퍼티의 가장 큰 수치적 이름보다 작거나 같은 값으로 설정하려 하면 길이는 그 프로퍼티 이름보다 1 큰 값으로 설정된다. 10.4.2.1 참조.

23.1.5 Array 이터레이터 객체 (Array Iterator Objects)

Array Iterator 는 특정 Array 인스턴스 객체 위의 특정 순회를 표현하는 객체이다. 이름 있는 생성자는 없으며 Array 인스턴스 객체의 특정 메서드를 호출하여 생성된다.

23.1.5.1 CreateArrayIterator ( array, kind )

The abstract operation CreateArrayIterator takes arguments array (Object) and kind (key+value, key, 또는 value) and returns Object. 이터레이터를 반환하는 Array 메서드들이 사용할 이터레이터 객체를 생성하는 데 사용된다. It performs the following steps when called:

  1. iterator = OrdinaryObjectCreate(%ArrayIteratorPrototype%, « [[IteratedArrayLike]], [[ArrayLikeNextIndex]], [[ArrayLikeIterationKind]] »).
  2. iterator.[[IteratedArrayLike]] = array.
  3. iterator.[[ArrayLikeNextIndex]] = 0.
  4. iterator.[[ArrayLikeIterationKind]] = kind.
  5. iterator 반환.

23.1.5.2 %ArrayIteratorPrototype% 객체 (The %ArrayIteratorPrototype% Object)

%ArrayIteratorPrototype% 객체:

23.1.5.2.1 %ArrayIteratorPrototype%.next ( )

  1. O = this 값.
  2. O 가 Object 가 아니면 TypeError 예외.
  3. OArray Iterator Instance 의 모든 내부 슬롯(23.1.5.3)을 갖지 않으면 TypeError 예외.
  4. array = O.[[IteratedArrayLike]].
  5. array = undefined 이면 CreateIteratorResultObject(undefined, true) 반환.
  6. index = O.[[ArrayLikeNextIndex]].
  7. kind = O.[[ArrayLikeIterationKind]].
  8. array[[TypedArrayName]] 내부 슬롯을 가지면
    1. taRecord = MakeTypedArrayWithBufferWitnessRecord(array, seq-cst).
    2. IsTypedArrayOutOfBounds(taRecord) true 이면 TypeError 예외.
    3. len = TypedArrayLength(taRecord).
  9. Else
    1. len = ? LengthOfArrayLike(array).
  10. indexlen 이면
    1. O.[[IteratedArrayLike]] = undefined.
    2. CreateIteratorResultObject(undefined, true) 반환.
  11. O.[[ArrayLikeNextIndex]] = index + 1.
  12. indexNumber = 𝔽(index).
  13. kindkey 이면
    1. result = indexNumber.
  14. Else
    1. elementKey = ! ToString(indexNumber).
    2. elementValue = ? Get(array, elementKey).
    3. kindvalue 이면
      1. result = elementValue.
    4. Else
      1. Assert: kind = key+value.
      2. result = CreateArrayFromListindexNumber, elementValue »).
  15. CreateIteratorResultObject(result, false) 반환.

23.1.5.2.2 %ArrayIteratorPrototype% [ %Symbol.toStringTag% ]

%Symbol.toStringTag% 프로퍼티 초기 값은 String "Array Iterator".

이 프로퍼티 특성 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }.

23.1.5.3 Array 이터레이터 인스턴스의 프로퍼티 (Properties of Array Iterator Instances)

Array 이터레이터 인스턴스는 %ArrayIteratorPrototype% 본질 객체로부터 프로퍼티를 상속하는 일반 객체이다. 초기 생성 시 내부 슬롯은 Table 72 에 나열된 것을 갖는다.

Table 72: Array 이터레이터 인스턴스의 내부 슬롯 (Internal Slots of Array Iterator Instances)
Internal Slot Type Description
[[IteratedArrayLike]] an Object or undefined 순회 중인 array-like 객체.
[[ArrayLikeNextIndex]] a non-negative integer 이 이터레이터가 다음에 검사할 요소의 정수 인덱스.
[[ArrayLikeIterationKind]] key+value, key, or value 각 요소에 대해 반환되는 내용을 식별하는 값.

23.2 TypedArray 객체

TypedArray 는 기본 이진 데이터 버퍼(25.1)에 대한 배열 유사 뷰를 제공한다. TypedArray 요소 타입은 특정 TypedArray 인스턴스의 모든 요소가 갖는 기본 이진 스칼라 데이터 타입이다. 지원되는 각 요소 타입마다 Table 73에 열거된 고유한 TypedArray 생성자가 있다. Table 73의 각 생성자는 그에 상응하는 별도의 프로토타입 객체를 가진다.

Table 73: TypedArray 생성자
생성자 이름 및 내재 객체 요소 타입 요소 크기 변환 연산 설명
Int8Array
%Int8Array%
int8 1 ToInt8 8비트 2의 보수 부호 있는 정수
Uint8Array
%Uint8Array%
uint8 1 ToUint8 8비트 부호 없는 정수
Uint8ClampedArray
%Uint8ClampedArray%
uint8clamped 1 ToUint8Clamp 8비트 부호 없는 정수 (클램프 변환)
Int16Array
%Int16Array%
int16 2 ToInt16 16비트 2의 보수 부호 있는 정수
Uint16Array
%Uint16Array%
uint16 2 ToUint16 16비트 부호 없는 정수
Int32Array
%Int32Array%
int32 4 ToInt32 32비트 2의 보수 부호 있는 정수
Uint32Array
%Uint32Array%
uint32 4 ToUint32 32비트 부호 없는 정수
BigInt64Array
%BigInt64Array%
bigint64 8 ToBigInt64 64비트 2의 보수 부호 있는 정수
BigUint64Array
%BigUint64Array%
biguint64 8 ToBigUint64 64비트 부호 없는 정수
Float16Array
%Float16Array%
float16 2 16비트 IEEE 부동소수점
Float32Array
%Float32Array%
float32 4 32비트 IEEE 부동소수점
Float64Array
%Float64Array%
float64 8 64비트 IEEE 부동소수점

아래 정의들에서 TypedArray 에 대한 참조는 위 표에서 해당하는 적절한 생성자 이름으로 치환되어야 한다.

23.2.1 %TypedArray% 내재 객체

%TypedArray% 내재 객체는 다음과 같다:

  • 모든 TypedArray 생성자 객체가 상속하는 생성자 함수 객체이다.
  • 연관된 프로토타입 객체와 함께 모든 TypedArray 생성자와 그 인스턴스가 상속하는 공통 프로퍼티를 제공한다.
  • 전역 이름을 가지지 않으며 전역 객체의 프로퍼티로 나타나지 않는다.
  • 여러 TypedArray 생성자의 추상 상위(super) 클래스 역할을 한다.
  • 추상 클래스 생성자이므로 호출 시 오류를 던진다. TypedArray 생성자들은 이에 대한 super 호출을 수행하지 않는다.

23.2.1.1 %TypedArray% ( )

이 함수는 호출 시 다음 단계를 수행한다:

  1. TypeError 예외를 던진다.

이 함수의 "length" 프로퍼티 값은 +0𝔽 이다.

23.2.2 %TypedArray% 내재 객체의 프로퍼티

%TypedArray% 내재 객체는 다음을 가진다:

  • 값이 %Function.prototype%[[Prototype]] 내부 슬롯.
  • 값이 "TypedArray""name" 프로퍼티.
  • 다음 프로퍼티들:

23.2.2.1 %TypedArray%.from ( source [ , mapper [ , thisArg ] ] )

이 메서드는 호출 시 다음 단계를 수행한다:

  1. Cthis 값으로 둔다.
  2. IsConstructor(C) 가 false 이면 TypeError 예외.
  3. mapperundefined 이면
    1. mapping = false.
  4. Else,
    1. IsCallable(mapper) 가 false 이면 TypeError 예외.
    2. mapping = true.
  5. usingIterator = ? GetMethod(source, %Symbol.iterator%).
  6. usingIteratorundefined 가 아니면
    1. values = ? IteratorToList(? GetIteratorFromMethod(source, usingIterator)).
    2. len = values 의 요소 개수.
    3. targetObj = ? TypedArrayCreateFromConstructor(C, « 𝔽(len) »).
    4. k = 0.
    5. k < len 동안 반복
      1. Pk = ! ToString(𝔽(k)).
      2. kValue = values 의 첫 번째 요소.
      3. values 의 첫 요소를 제거.
      4. mapping = true 이면
        1. mappedValue = ? Call(mapper, thisArg, « kValue, 𝔽(k) »).
      5. Else,
        1. mappedValue = kValue.
      6. Set(targetObj, Pk, mappedValue, true) 수행.
      7. k = k + 1.
    6. Assert: values 는 이제 빈 List.
    7. targetObj 반환.
  7. NOTE: source 는 이터러블이 아니므로 배열 유사 객체로 간주.
  8. arrayLike = ! ToObject(source).
  9. len = ? LengthOfArrayLike(arrayLike).
  10. targetObj = ? TypedArrayCreateFromConstructor(C, « 𝔽(len) »).
  11. k = 0.
  12. k < len 동안 반복
    1. Pk = ! ToString(𝔽(k)).
    2. kValue = ? Get(arrayLike, Pk).
    3. mapping = true 이면
      1. mappedValue = ? Call(mapper, thisArg, « kValue, 𝔽(k) »).
    4. Else,
      1. mappedValue = kValue.
    5. Set(targetObj, Pk, mappedValue, true) 수행.
    6. k = k + 1.
  13. targetObj 반환.

23.2.2.2 %TypedArray%.of ( ...items )

이 메서드는 호출 시 다음 단계를 수행한다:

  1. len = items 의 요소 개수.
  2. C = this 값.
  3. IsConstructor(C) 가 false 이면 TypeError 예외.
  4. newObj = ? TypedArrayCreateFromConstructor(C, « 𝔽(len) »).
  5. k = 0.
  6. k < len 동안 반복
    1. kValue = items[k].
    2. Pk = ! ToString(𝔽(k)).
    3. Set(newObj, Pk, kValue, true) 수행.
    4. k = k + 1.
  7. newObj 반환.

23.2.2.3 %TypedArray%.prototype

%TypedArray%.prototype 의 초기 값은 %TypedArray% 프로토타입 객체이다.

이 프로퍼티는 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false } 특성을 가진다.

23.2.2.4 get %TypedArray% [ %Symbol.species% ]

%TypedArray%[%Symbol.species%] 는 set 접근자 함수가 undefined접근자 프로퍼티이다. get 접근자 함수는 호출 시 다음을 수행한다:

  1. this 값을 반환.

이 함수의 "name" 프로퍼티 값은 "get [Symbol.species]" 이다.

Note

%TypedArray.prototype% 메서드는 일반적으로 자신의 this 값의 생성자를 사용해 파생 객체를 생성한다. 하지만 서브클래스 생성자%Symbol.species% 프로퍼티 재정의를 통해 그 기본 동작을 바꿀 수 있다.

23.2.3 %TypedArray% 프로토타입 객체의 프로퍼티

%TypedArray% 프로토타입 객체는 다음과 같다:

  • 값이 %Object.prototype%[[Prototype]] 내부 슬롯을 가진다.
  • %TypedArray.prototype% 이다.
  • 일반 객체이다.
  • [[ViewedArrayBuffer]] 또는 TypedArray 인스턴스 전용의 다른 내부 슬롯을 가지지 않는다.

23.2.3.1 %TypedArray%.prototype.at ( index )

  1. Othis 값으로 둔다.
  2. taRecord = ? ValidateTypedArray(O, seq-cst).
  3. len = TypedArrayLength(taRecord).
  4. relativeIndex = ? ToIntegerOrInfinity(index).
  5. relativeIndex ≥ 0 이면
    1. k = relativeIndex.
  6. Else,
    1. k = len + relativeIndex.
  7. k < 0 또는 klen 이면 undefined 반환.
  8. Get(O, ! ToString(𝔽(k))) 반환.

23.2.3.2 get %TypedArray%.prototype.buffer

%TypedArray%.prototype.buffer 는 set 접근자 함수가 undefined접근자 프로퍼티이다. 그 get 접근자 함수는 호출 시 다음을 수행한다:

  1. O = this 값.
  2. RequireInternalSlot(O, [[TypedArrayName]]) 수행.
  3. Assert: O[[ViewedArrayBuffer]] 내부 슬롯을 가진다.
  4. buffer = O.[[ViewedArrayBuffer]].
  5. buffer 반환.

23.2.3.3 get %TypedArray%.prototype.byteLength

%TypedArray%.prototype.byteLength 는 set 접근자 함수가 undefined접근자 프로퍼티이다. 그 get 접근자 함수는 다음을 수행한다:

  1. O = this 값.
  2. RequireInternalSlot(O, [[TypedArrayName]]) 수행.
  3. Assert: O[[ViewedArrayBuffer]] 내부 슬롯을 가진다.
  4. taRecord = MakeTypedArrayWithBufferWitnessRecord(O, seq-cst).
  5. size = TypedArrayByteLength(taRecord).
  6. 𝔽(size) 반환.

23.2.3.4 get %TypedArray%.prototype.byteOffset

%TypedArray%.prototype.byteOffset 는 set 접근자 함수가 undefined접근자 프로퍼티이다. 그 get 접근자 함수는 다음을 수행한다:

  1. O = this 값.
  2. RequireInternalSlot(O, [[TypedArrayName]]) 수행.
  3. Assert: O[[ViewedArrayBuffer]] 내부 슬롯을 가진다.
  4. taRecord = MakeTypedArrayWithBufferWitnessRecord(O, seq-cst).
  5. IsTypedArrayOutOfBounds(taRecord) 가 true 이면 +0𝔽 반환.
  6. offset = O.[[ByteOffset]].
  7. 𝔽(offset) 반환.

23.2.3.5 %TypedArray%.prototype.constructor

%TypedArray%.prototype.constructor 의 초기 값은 %TypedArray% 이다.

23.2.3.6 %TypedArray%.prototype.copyWithin ( target, start [ , end ] )

이 메서드의 인자 해석과 사용은 23.1.3.4에 정의된 Array.prototype.copyWithin 과 동일하다.

이 메서드는 호출 시 다음 단계를 수행한다:

  1. O = this 값.
  2. taRecord = ? ValidateTypedArray(O, seq-cst).
  3. len = TypedArrayLength(taRecord).
  4. relativeTarget = ? ToIntegerOrInfinity(target).
  5. relativeTarget = -∞ 이면 targetIndex = 0.
  6. Else if relativeTarget < 0 이면 targetIndex = max(len + relativeTarget, 0).
  7. Else targetIndex = min(relativeTarget, len).
  8. relativeStart = ? ToIntegerOrInfinity(start).
  9. relativeStart = -∞ 이면 startIndex = 0.
  10. Else if relativeStart < 0 이면 startIndex = max(len + relativeStart, 0).
  11. Else startIndex = min(relativeStart, len).
  12. endundefined 이면 relativeEnd = len; else relativeEnd = ? ToIntegerOrInfinity(end).
  13. relativeEnd = -∞ 이면 endIndex = 0.
  14. Else if relativeEnd < 0 이면 endIndex = max(len + relativeEnd, 0).
  15. Else endIndex = min(relativeEnd, len).
  16. count = min(endIndex - startIndex, len - targetIndex).
  17. count > 0 이면
    1. NOTE: 복사는 소스 데이터의 비트 수준 인코딩이 유지되도록 수행되어야 한다.
    2. buffer = O.[[ViewedArrayBuffer]].
    3. taRecord = MakeTypedArrayWithBufferWitnessRecord(O, seq-cst).
    4. IsTypedArrayOutOfBounds(taRecord) true 이면 TypeError 예외.
    5. len = TypedArrayLength(taRecord).
    6. elementSize = TypedArrayElementSize(O).
    7. byteOffset = O.[[ByteOffset]].
    8. bufferByteLimit = (len × elementSize) + byteOffset.
    9. toByteIndex = (targetIndex × elementSize) + byteOffset.
    10. fromByteIndex = (startIndex × elementSize) + byteOffset.
    11. countBytes = count × elementSize.
    12. fromByteIndex < toByteIndex 그리고 toByteIndex < fromByteIndex + countBytes 이면
      1. direction = -1.
      2. fromByteIndex = fromByteIndex + countBytes - 1.
      3. toByteIndex = toByteIndex + countBytes - 1.
    13. Else,
      1. direction = 1.
    14. countBytes > 0 동안 반복
      1. fromByteIndex < bufferByteLimit 그리고 toByteIndex < bufferByteLimit 이면
        1. value = GetValueFromBuffer(buffer, fromByteIndex, uint8, true, unordered).
        2. SetValueInBuffer(buffer, toByteIndex, uint8, value, true, unordered) 수행.
        3. fromByteIndex = fromByteIndex + direction.
        4. toByteIndex = toByteIndex + direction.
        5. countBytes = countBytes - 1.
      2. Else
        1. countBytes = 0.
  18. O 반환.

23.2.3.7 %TypedArray%.prototype.entries ( )

이 메서드는 호출 시 다음 단계를 수행한다:

  1. O = this 값.
  2. ValidateTypedArray(O, seq-cst) 수행.
  3. CreateArrayIterator(O, key+value) 반환.

23.2.3.8 %TypedArray%.prototype.every ( callback [ , thisArg ] )

이 메서드의 인자 해석과 사용은 23.1.3.6에 정의된 Array.prototype.every 와 동일하다.

이 메서드는 호출 시 다음 단계를 수행한다:

  1. O = this 값.
  2. taRecord = ? ValidateTypedArray(O, seq-cst).
  3. len = TypedArrayLength(taRecord).
  4. IsCallable(callback) false 이면 TypeError 예외.
  5. k = 0.
  6. k < len 동안 반복
    1. Pk = ! ToString(𝔽(k)).
    2. kValue = ! Get(O, Pk).
    3. testResult = ToBoolean(? Call(callback, thisArg, « kValue, 𝔽(k), O »)).
    4. testResult = false 이면 false 반환.
    5. k = k + 1.
  7. true 반환.

이 메서드는 제네릭이 아니다. this 값은 [[TypedArrayName]] 내부 슬롯을 가진 객체여야 한다.

23.2.3.9 %TypedArray%.prototype.fill ( value [ , start [ , end ] ] )

이 메서드의 인자 해석과 사용은 23.1.3.7에 정의된 Array.prototype.fill 과 동일하다.

이 메서드는 호출 시 다음 단계를 수행한다:

  1. O = this 값.
  2. taRecord = ? ValidateTypedArray(O, seq-cst).
  3. len = TypedArrayLength(taRecord).
  4. O.[[ContentType]]bigint 이면 value = ? ToBigInt(value).
  5. 아니면 value = ? ToNumber(value).
  6. relativeStart = ? ToIntegerOrInfinity(start).
  7. relativeStart = -∞ 이면 startIndex = 0.
  8. Else if relativeStart < 0 이면 startIndex = max(len + relativeStart, 0).
  9. Else startIndex = min(relativeStart, len).
  10. endundefined 이면 relativeEnd = len; else relativeEnd = ? ToIntegerOrInfinity(end).
  11. relativeEnd = -∞ 이면 endIndex = 0.
  12. Else if relativeEnd < 0 이면 endIndex = max(len + relativeEnd, 0).
  13. Else endIndex = min(relativeEnd, len).
  14. taRecord = MakeTypedArrayWithBufferWitnessRecord(O, seq-cst).
  15. IsTypedArrayOutOfBounds(taRecord) true 이면 TypeError 예외.
  16. len = TypedArrayLength(taRecord).
  17. endIndex = min(endIndex, len).
  18. k = startIndex.
  19. k < endIndex 동안 반복
    1. Pk = ! ToString(𝔽(k)).
    2. Set(O, Pk, value, true) 수행.
    3. k = k + 1.
  20. O 반환.

23.2.3.10 %TypedArray%.prototype.filter ( callback [ , thisArg ] )

이 메서드의 인자 해석과 사용은 23.1.3.8에 정의된 Array.prototype.filter 와 동일하다.

이 메서드는 호출 시 다음 단계를 수행한다:

  1. O = this 값.
  2. taRecord = ? ValidateTypedArray(O, seq-cst).
  3. len = TypedArrayLength(taRecord).
  4. IsCallable(callback) false 이면 TypeError 예외.
  5. kept = 새 빈 List.
  6. captured = 0.
  7. k = 0.
  8. k < len 동안 반복
    1. Pk = ! ToString(𝔽(k)).
    2. kValue = ! Get(O, Pk).
    3. selected = ToBoolean(? Call(callback, thisArg, « kValue, 𝔽(k), O »)).
    4. selected = true 이면
      1. keptkValue 추가.
      2. captured = captured + 1.
    5. k = k + 1.
  9. A = ? TypedArraySpeciesCreate(O, « 𝔽(captured) »).
  10. n = 0.
  11. kept 요소 e 에 대해
    1. Set(A, ! ToString(𝔽(n)), e, true) 수행.
    2. n = n + 1.
  12. A 반환.

이 메서드는 제네릭이 아니다. this 값은 [[TypedArrayName]] 내부 슬롯을 가진 객체여야 한다.

23.2.3.11 %TypedArray%.prototype.find ( predicate [ , thisArg ] )

이 메서드의 인자 해석과 사용은 23.1.3.9에 정의된 Array.prototype.find 와 동일하다.

이 메서드는 호출 시 다음 단계를 수행한다:

  1. O = this 값.
  2. taRecord = ? ValidateTypedArray(O, seq-cst).
  3. len = TypedArrayLength(taRecord).
  4. findRec = ? FindViaPredicate(O, len, ascending, predicate, thisArg).
  5. findRec.[[Value]] 반환.

이 메서드는 제네릭이 아니다. this 값은 [[TypedArrayName]] 내부 슬롯을 가진 객체여야 한다.

23.2.3.12 %TypedArray%.prototype.findIndex ( predicate [ , thisArg ] )

이 메서드의 인자 해석과 사용은 23.1.3.10에 정의된 Array.prototype.findIndex 와 동일하다.

이 메서드는 호출 시 다음 단계를 수행한다:

  1. O = this 값.
  2. taRecord = ? ValidateTypedArray(O, seq-cst).
  3. len = TypedArrayLength(taRecord).
  4. findRec = ? FindViaPredicate(O, len, ascending, predicate, thisArg).
  5. findRec.[[Index]] 반환.

이 메서드는 제네릭이 아니다. this 값은 [[TypedArrayName]] 내부 슬롯을 가진 객체여야 한다.

23.2.3.13 %TypedArray%.prototype.findLast ( predicate [ , thisArg ] )

이 메서드의 인자 해석과 사용은 23.1.3.11에 정의된 Array.prototype.findLast 와 동일하다.

이 메서드는 호출 시 다음 단계를 수행한다:

  1. O = this 값.
  2. taRecord = ? ValidateTypedArray(O, seq-cst).
  3. len = TypedArrayLength(taRecord).
  4. findRec = ? FindViaPredicate(O, len, descending, predicate, thisArg).
  5. findRec.[[Value]] 반환.

이 메서드는 제네릭이 아니다. this 값은 [[TypedArrayName]] 내부 슬롯을 가진 객체여야 한다.

23.2.3.14 %TypedArray%.prototype.findLastIndex ( predicate [ , thisArg ] )

이 메서드의 인자 해석과 사용은 23.1.3.12에 정의된 Array.prototype.findLastIndex 와 동일하다.

이 메서드는 호출 시 다음 단계를 수행한다:

  1. O = this 값.
  2. taRecord = ? ValidateTypedArray(O, seq-cst).
  3. len = TypedArrayLength(taRecord).
  4. findRec = ? FindViaPredicate(O, len, descending, predicate, thisArg).
  5. findRec.[[Index]] 반환.

이 메서드는 제네릭이 아니다. this 값은 [[TypedArrayName]] 내부 슬롯을 가진 객체여야 한다.

23.2.3.15 %TypedArray%.prototype.forEach ( callback [ , thisArg ] )

이 메서드의 인자 해석과 사용은 23.1.3.15에 정의된 Array.prototype.forEach 와 동일하다.

이 메서드는 호출 시 다음 단계를 수행한다:

  1. O = this 값.
  2. taRecord = ? ValidateTypedArray(O, seq-cst).
  3. len = TypedArrayLength(taRecord).
  4. IsCallable(callback) false 이면 TypeError 예외.
  5. k = 0.
  6. k < len 동안 반복
    1. Pk = ! ToString(𝔽(k)).
    2. kValue = ! Get(O, Pk).
    3. Call(callback, thisArg, « kValue, 𝔽(k), O ») 수행.
    4. k = k + 1.
  7. undefined 반환.

이 메서드는 제네릭이 아니다. this 값은 [[TypedArrayName]] 내부 슬롯을 가진 객체여야 한다.

23.2.3.16 %TypedArray%.prototype.includes ( searchElement [ , fromIndex ] )

이 메서드의 인자 해석과 사용은 23.1.3.16에 정의된 Array.prototype.includes 와 동일하다.

이 메서드는 호출 시 다음 단계를 수행한다:

  1. O = this 값.
  2. taRecord = ? ValidateTypedArray(O, seq-cst).
  3. len = TypedArrayLength(taRecord).
  4. len = 0 이면 false 반환.
  5. n = ? ToIntegerOrInfinity(fromIndex).
  6. Assert: fromIndexundefined 이면 n = 0.
  7. n = +∞ 이면 false 반환.
  8. Else if n = -∞ 이면 n = 0.
  9. n ≥ 0 이면
    1. k = n.
  10. Else
    1. k = len + n.
    2. k < 0 이면 k = 0.
  11. k < len 동안 반복
    1. elementK = ! Get(O, ! ToString(𝔽(k))).
    2. SameValueZero(searchElement, elementK) true 이면 true 반환.
    3. k = k + 1.
  12. false 반환.

이 메서드는 제네릭이 아니다. this 값은 [[TypedArrayName]] 내부 슬롯을 가진 객체여야 한다.

23.2.3.17 %TypedArray%.prototype.indexOf ( searchElement [ , fromIndex ] )

이 메서드의 인자 해석과 사용은 23.1.3.17에 정의된 Array.prototype.indexOf 와 동일하다.

이 메서드는 호출 시 다음 단계를 수행한다:

  1. O = this 값.
  2. taRecord = ? ValidateTypedArray(O, seq-cst).
  3. len = TypedArrayLength(taRecord).
  4. len = 0 이면 -1𝔽 반환.
  5. n = ? ToIntegerOrInfinity(fromIndex).
  6. Assert: fromIndex undefinedn = 0.
  7. n = +∞ 이면 -1𝔽 반환.
  8. Else if n = -∞ 이면 n = 0.
  9. n ≥ 0 이면
    1. k = n.
  10. Else
    1. k = len + n.
    2. k < 0 이면 k = 0.
  11. k < len 동안 반복
    1. Pk = ! ToString(𝔽(k)).
    2. kPresent = ! HasProperty(O, Pk).
    3. kPresent = true 이면
      1. elementK = ! Get(O, Pk).
      2. IsStrictlyEqual(searchElement, elementK) true 이면 𝔽(k) 반환.
    4. k = k + 1.
  12. -1𝔽 반환.

이 메서드는 제네릭이 아니다. this 값은 [[TypedArrayName]] 내부 슬롯을 가진 객체여야 한다.

23.2.3.18 %TypedArray%.prototype.join ( separator )

이 메서드의 인자 해석과 사용은 23.1.3.18에 정의된 Array.prototype.join 과 동일하다.

이 메서드는 호출 시 다음 단계를 수행한다:

  1. O = this 값.
  2. taRecord = ? ValidateTypedArray(O, seq-cst).
  3. len = TypedArrayLength(taRecord).
  4. separatorundefined 이면 sep = ",".
  5. Else sep = ? ToString(separator).
  6. R = 빈 String.
  7. k = 0.
  8. k < len 동안 반복
    1. k > 0 이면 R = R + sep.
    2. element = ! Get(O, ! ToString(𝔽(k))).
    3. elementundefined 이면
      1. S = ! ToString(element).
      2. R = R + S.
    4. k = k + 1.
  9. R 반환.

이 메서드는 제네릭이 아니다. this 값은 [[TypedArrayName]] 내부 슬롯을 가진 객체여야 한다.

23.2.3.19 %TypedArray%.prototype.keys ( )

이 메서드는 호출 시 다음 단계를 수행한다:

  1. O = this 값.
  2. ValidateTypedArray(O, seq-cst) 수행.
  3. CreateArrayIterator(O, key) 반환.

23.2.3.20 %TypedArray%.prototype.lastIndexOf ( searchElement [ , fromIndex ] )

이 메서드의 인자 해석과 사용은 23.1.3.20에 정의된 Array.prototype.lastIndexOf 와 동일하다.

이 메서드는 호출 시 다음 단계를 수행한다:

  1. O = this 값.
  2. taRecord = ? ValidateTypedArray(O, seq-cst).
  3. len = TypedArrayLength(taRecord).
  4. len = 0 이면 -1𝔽 반환.
  5. fromIndex 존재하면 n = ? ToIntegerOrInfinity(fromIndex); else n = len - 1.
  6. n = -∞ 이면 -1𝔽 반환.
  7. n ≥ 0 이면
    1. k = min(n, len - 1).
  8. Else
    1. k = len + n.
  9. k ≥ 0 동안 반복
    1. Pk = ! ToString(𝔽(k)).
    2. kPresent = ! HasProperty(O, Pk).
    3. kPresent = true 이면
      1. elementK = ! Get(O, Pk).
      2. IsStrictlyEqual(searchElement, elementK) true 이면 𝔽(k) 반환.
    4. k = k - 1.
  10. -1𝔽 반환.

이 메서드는 제네릭이 아니다. this 값은 [[TypedArrayName]] 내부 슬롯을 가진 객체여야 한다.

23.2.3.21 get %TypedArray%.prototype.length

%TypedArray%.prototype.length 는 set 접근자 함수가 undefined접근자 프로퍼티이다. 그 get 접근자 함수는 다음을 수행한다:

  1. O = this 값.
  2. RequireInternalSlot(O, [[TypedArrayName]]) 수행.
  3. Assert: O[[ViewedArrayBuffer]], [[ArrayLength]] 내부 슬롯을 가진다.
  4. taRecord = MakeTypedArrayWithBufferWitnessRecord(O, seq-cst).
  5. IsTypedArrayOutOfBounds(taRecord) true 이면 +0𝔽 반환.
  6. length = TypedArrayLength(taRecord).
  7. 𝔽(length) 반환.

이 함수는 제네릭이 아니다. this 값은 [[TypedArrayName]] 내부 슬롯을 가진 객체여야 한다.

23.2.3.22 %TypedArray%.prototype.map ( callback [ , thisArg ] )

이 메서드의 인자 해석과 사용은 23.1.3.21에 정의된 Array.prototype.map 과 동일하다.

이 메서드는 호출 시 다음 단계를 수행한다:

  1. O = this 값.
  2. taRecord = ? ValidateTypedArray(O, seq-cst).
  3. len = TypedArrayLength(taRecord).
  4. IsCallable(callback) false 이면 TypeError 예외.
  5. A = ? TypedArraySpeciesCreate(O, « 𝔽(len) »).
  6. k = 0.
  7. k < len 동안 반복
    1. Pk = ! ToString(𝔽(k)).
    2. kValue = ! Get(O, Pk).
    3. mappedValue = ? Call(callback, thisArg, « kValue, 𝔽(k), O »).
    4. Set(A, Pk, mappedValue, true) 수행.
    5. k = k + 1.
  8. A 반환.

이 메서드는 제네릭이 아니다. this 값은 [[TypedArrayName]] 내부 슬롯을 가진 객체여야 한다.

23.2.3.23 %TypedArray%.prototype.reduce ( callback [ , initialValue ] )

이 메서드의 인자 해석과 사용은 23.1.3.24에 정의된 Array.prototype.reduce 와 동일하다.

이 메서드는 호출 시 다음 단계를 수행한다:

  1. O = this 값.
  2. taRecord = ? ValidateTypedArray(O, seq-cst).
  3. len = TypedArrayLength(taRecord).
  4. IsCallable(callback) false 이면 TypeError 예외.
  5. len = 0 이고 initialValue 미존재이면 TypeError 예외.
  6. k = 0.
  7. accumulator = undefined.
  8. initialValue 존재하면
    1. accumulator = initialValue.
  9. Else
    1. Pk = ! ToString(𝔽(k)).
    2. accumulator = ! Get(O, Pk).
    3. k = k + 1.
  10. k < len 동안 반복
    1. Pk = ! ToString(𝔽(k)).
    2. kValue = ! Get(O, Pk).
    3. accumulator = ? Call(callback, undefined, « accumulator, kValue, 𝔽(k), O »).
    4. k = k + 1.
  11. accumulator 반환.

이 메서드는 제네릭이 아니다. this 값은 [[TypedArrayName]] 내부 슬롯을 가진 객체여야 한다.

23.2.3.24 %TypedArray%.prototype.reduceRight ( callback [ , initialValue ] )

이 메서드의 인자 해석과 사용은 23.1.3.25에 정의된 Array.prototype.reduceRight 와 동일하다.

이 메서드는 호출 시 다음 단계를 수행한다:

  1. O = this 값.
  2. taRecord = ? ValidateTypedArray(O, seq-cst).
  3. len = TypedArrayLength(taRecord).
  4. IsCallable(callback) false 이면 TypeError 예외.
  5. len = 0 이고 initialValue 미존재이면 TypeError 예외.
  6. k = len - 1.
  7. accumulator = undefined.
  8. initialValue 존재하면
    1. accumulator = initialValue.
  9. Else
    1. Pk = ! ToString(𝔽(k)).
    2. accumulator = ! Get(O, Pk).
    3. k = k - 1.
  10. k ≥ 0 동안 반복
    1. Pk = ! ToString(𝔽(k)).
    2. kValue = ! Get(O, Pk).
    3. accumulator = ? Call(callback, undefined, « accumulator, kValue, 𝔽(k), O »).
    4. k = k - 1.
  11. accumulator 반환.

이 메서드는 제네릭이 아니다. this 값은 [[TypedArrayName]] 내부 슬롯을 가진 객체여야 한다.

23.2.3.25 %TypedArray%.prototype.reverse ( )

이 메서드의 인자 해석과 사용은 23.1.3.26에 정의된 Array.prototype.reverse 와 동일하다.

이 메서드는 호출 시 다음 단계를 수행한다:

  1. O = this 값.
  2. taRecord = ? ValidateTypedArray(O, seq-cst).
  3. len = TypedArrayLength(taRecord).
  4. middle = floor(len / 2).
  5. lower = 0.
  6. lowermiddle 동안
    1. upper = len - lower - 1.
    2. upperP = ! ToString(𝔽(upper)).
    3. lowerP = ! ToString(𝔽(lower)).
    4. lowerValue = ! Get(O, lowerP).
    5. upperValue = ! Get(O, upperP).
    6. Set(O, lowerP, upperValue, true).
    7. Set(O, upperP, lowerValue, true).
    8. lower = lower + 1.
  7. O 반환.

이 메서드는 제네릭이 아니다. this 값은 [[TypedArrayName]] 내부 슬롯을 가진 객체여야 한다.

23.2.3.26 %TypedArray%.prototype.set ( source [ , offset ] )

이 메서드는 source 로부터 값을 읽어 이 TypedArray 에 여러 값을 설정한다. 구체적 동작은 source 타입에 따라 다르다. 선택적 offset 값은 이 TypedArray 내에서 값이 기록될 첫 요소 인덱스를 나타내며 생략되면 0 으로 간주된다.

호출 시 다음 단계를 수행한다:

  1. target = this 값.
  2. RequireInternalSlot(target, [[TypedArrayName]]) 수행.
  3. Assert: target[[ViewedArrayBuffer]] 내부 슬롯을 가진다.
  4. targetOffset = ? ToIntegerOrInfinity(offset).
  5. targetOffset < 0 이면 RangeError 예외.
  6. source[[TypedArrayName]] 내부 슬롯을 가진 Object 이면
    1. SetTypedArrayFromTypedArray(target, targetOffset, source) 수행.
  7. Else
    1. SetTypedArrayFromArrayLike(target, targetOffset, source) 수행.
  8. undefined 반환.

이 메서드는 제네릭이 아니다. this 값은 [[TypedArrayName]] 내부 슬롯을 가진 객체여야 한다.

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 unused 또는 throw completion. targetOffset 인덱스부터 시작하여 source 로부터 읽은 여러 값을 target 에 설정한다. It performs the following steps when called:

  1. targetRecord = MakeTypedArrayWithBufferWitnessRecord(target, seq-cst).
  2. IsTypedArrayOutOfBounds(targetRecord) true 이면 TypeError 예외.
  3. targetLength = TypedArrayLength(targetRecord).
  4. src = ? ToObject(source).
  5. srcLength = ? LengthOfArrayLike(src).
  6. targetOffset = +∞ 이면 RangeError 예외.
  7. srcLength + targetOffset > targetLength 이면 RangeError 예외.
  8. k = 0.
  9. k < srcLength 동안 반복
    1. Pk = ! ToString(𝔽(k)).
    2. value = ? Get(src, Pk).
    3. targetIndex = 𝔽(targetOffset + k).
    4. TypedArraySetElement(target, targetIndex, value) 수행.
    5. k = k + 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 unused 또는 throw completion. targetOffset 인덱스부터 시작하여 source 로부터 읽은 여러 값을 target 에 설정한다. It performs the following steps when called:

  1. targetBuffer = target.[[ViewedArrayBuffer]].
  2. targetRecord = MakeTypedArrayWithBufferWitnessRecord(target, seq-cst).
  3. IsTypedArrayOutOfBounds(targetRecord) true 이면 TypeError 예외.
  4. targetLength = TypedArrayLength(targetRecord).
  5. srcBuffer = source.[[ViewedArrayBuffer]].
  6. srcRecord = MakeTypedArrayWithBufferWitnessRecord(source, seq-cst).
  7. IsTypedArrayOutOfBounds(srcRecord) true 이면 TypeError 예외.
  8. srcLength = TypedArrayLength(srcRecord).
  9. targetType = TypedArrayElementType(target).
  10. targetElementSize = TypedArrayElementSize(target).
  11. targetByteOffset = target.[[ByteOffset]].
  12. srcType = TypedArrayElementType(source).
  13. srcElementSize = TypedArrayElementSize(source).
  14. srcByteOffset = source.[[ByteOffset]].
  15. targetOffset = +∞ 이면 RangeError 예외.
  16. srcLength + targetOffset > targetLength 이면 RangeError 예외.
  17. target.[[ContentType]]source.[[ContentType]] 이면 TypeError 예외.
  18. IsSharedArrayBuffer(srcBuffer) = true, IsSharedArrayBuffer(targetBuffer) = true, 그리고 srcBuffer.[[ArrayBufferData]]targetBuffer.[[ArrayBufferData]] 와 동일하면 sameSharedArrayBuffer = true; 아니면 false.
  19. SameValue(srcBuffer, targetBuffer) = true 또는 sameSharedArrayBuffer = true 이면
    1. srcByteLength = TypedArrayByteLength(srcRecord).
    2. srcBuffer = ? CloneArrayBuffer(srcBuffer, srcByteOffset, srcByteLength).
    3. srcByteIndex = 0.
  20. Else
    1. srcByteIndex = srcByteOffset.
  21. targetByteIndex = (targetOffset × targetElementSize) + targetByteOffset.
  22. limit = targetByteIndex + (targetElementSize × srcLength).
  23. srcType = targetType 이면
    1. NOTE: 전송은 소스 데이터의 비트 수준 인코딩을 보존해야 한다.
    2. targetByteIndex < limit 동안 반복
      1. value = GetValueFromBuffer(srcBuffer, srcByteIndex, uint8, true, unordered).
      2. SetValueInBuffer(targetBuffer, targetByteIndex, uint8, value, true, unordered) 수행.
      3. srcByteIndex = srcByteIndex + 1.
      4. targetByteIndex = targetByteIndex + 1.
  24. Else
    1. targetByteIndex < limit 동안 반복
      1. value = GetValueFromBuffer(srcBuffer, srcByteIndex, srcType, true, unordered).
      2. SetValueInBuffer(targetBuffer, targetByteIndex, targetType, value, true, unordered) 수행.
      3. srcByteIndex = srcByteIndex + srcElementSize.
      4. targetByteIndex = targetByteIndex + targetElementSize.
  25. unused 반환.

23.2.3.27 %TypedArray%.prototype.slice ( start, end )

이 메서드의 인자 해석과 사용은 23.1.3.28에 정의된 Array.prototype.slice 와 동일하다.

이 메서드는 호출 시 다음 단계를 수행한다:

  1. O = this 값.
  2. taRecord = ? ValidateTypedArray(O, seq-cst).
  3. srcArrayLength = TypedArrayLength(taRecord).
  4. relativeStart = ? ToIntegerOrInfinity(start).
  5. relativeStart = -∞ 이면 startIndex = 0.
  6. Else if relativeStart < 0 이면 startIndex = max(srcArrayLength + relativeStart, 0).
  7. Else startIndex = min(relativeStart, srcArrayLength).
  8. end undefined 이면 relativeEnd = srcArrayLength; else relativeEnd = ? ToIntegerOrInfinity(end).
  9. relativeEnd = -∞ 이면 endIndex = 0.
  10. Else if relativeEnd < 0 이면 endIndex = max(srcArrayLength + relativeEnd, 0).
  11. Else endIndex = min(relativeEnd, srcArrayLength).
  12. countBytes = max(endIndex - startIndex, 0).
  13. A = ? TypedArraySpeciesCreate(O, « 𝔽(countBytes) »).
  14. countBytes > 0 이면
    1. taRecord = MakeTypedArrayWithBufferWitnessRecord(O, seq-cst).
    2. IsTypedArrayOutOfBounds(taRecord) true 이면 TypeError 예외.
    3. endIndex = min(endIndex, TypedArrayLength(taRecord)).
    4. countBytes = max(endIndex - startIndex, 0).
    5. srcType = TypedArrayElementType(O).
    6. targetType = TypedArrayElementType(A).
    7. srcType = targetType 이면
      1. NOTE: 전송은 소스 데이터의 비트 수준 인코딩을 보존해야 한다.
      2. srcBuffer = O.[[ViewedArrayBuffer]].
      3. targetBuffer = A.[[ViewedArrayBuffer]].
      4. elementSize = TypedArrayElementSize(O).
      5. srcByteOffset = O.[[ByteOffset]].
      6. srcByteIndex = (startIndex × elementSize) + srcByteOffset.
      7. targetByteIndex = A.[[ByteOffset]].
      8. endByteIndex = targetByteIndex + (countBytes × elementSize).
      9. targetByteIndex < endByteIndex 동안 반복
        1. value = GetValueFromBuffer(srcBuffer, srcByteIndex, uint8, true, unordered).
        2. SetValueInBuffer(targetBuffer, targetByteIndex, uint8, value, true, unordered) 수행.
        3. srcByteIndex = srcByteIndex + 1.
        4. targetByteIndex = targetByteIndex + 1.
    8. Else
      1. n = 0.
      2. k = startIndex.
      3. k < endIndex 동안 반복
        1. Pk = ! ToString(𝔽(k)).
        2. kValue = ! Get(O, Pk).
        3. Set(A, ! ToString(𝔽(n)), kValue, true) 수행.
        4. k = k + 1.
        5. n = n + 1.
  15. A 반환.

이 메서드는 제네릭이 아니다. this 값은 [[TypedArrayName]] 내부 슬롯을 가진 객체여야 한다.

23.2.3.28 %TypedArray%.prototype.some ( callback [ , thisArg ] )

이 메서드의 인자 해석과 사용은 23.1.3.29에 정의된 Array.prototype.some 과 동일하다.

이 메서드는 호출 시 다음 단계를 수행한다:

  1. O = this 값.
  2. taRecord = ? ValidateTypedArray(O, seq-cst).
  3. len = TypedArrayLength(taRecord).
  4. IsCallable(callback) false 이면 TypeError 예외.
  5. k = 0.
  6. k < len 동안 반복
    1. Pk = ! ToString(𝔽(k)).
    2. kValue = ! Get(O, Pk).
    3. testResult = ToBoolean(? Call(callback, thisArg, « kValue, 𝔽(k), O »)).
    4. testResult = true 이면 true 반환.
    5. k = k + 1.
  7. false 반환.

이 메서드는 제네릭이 아니다. this 값은 [[TypedArrayName]] 내부 슬롯을 가진 객체여야 한다.

23.2.3.29 %TypedArray%.prototype.sort ( comparator )

이는 별도의 메서드로서 아래 설명된 부분을 제외하면 23.1.3.30에 정의된 Array.prototype.sort 와 동일한 요구사항을 구현한다. 이 메서드 구현은 this 값이 길이가 고정된 객체이며 정수 인덱스 프로퍼티가 희소하지 않다는 사실을 활용해 최적화될 수 있다.

이 메서드는 제네릭이 아니다. this 값은 [[TypedArrayName]] 내부 슬롯을 가진 객체여야 한다.

호출 시 다음 단계를 수행한다:

  1. comparatorundefined 이고 IsCallable(comparator) = false 이면 TypeError 예외.
  2. obj = this 값.
  3. taRecord = ? ValidateTypedArray(obj, seq-cst).
  4. len = TypedArrayLength(taRecord).
  5. NOTE: 다음 클로저는 23.1.3.30에서 수행되는 문자열 비교 대신 수치 비교를 수행한다.
  6. SortCompare 를 (x, y) 매개변수로 하고 comparator 를 캡처하여 호출 시 ? CompareTypedArrayElements(x, y, comparator) 를 반환하는 새 추상 클로저로 둔다.
  7. sortedList = ? SortIndexedProperties(obj, len, SortCompare, read-through-holes).
  8. j = 0.
  9. j < len 동안 반복
    1. Set(obj, ! ToString(𝔽(j)), sortedList[j], true) 수행.
    2. j = j + 1.
  10. obj 반환.
Note

NaN 은 (CompareTypedArrayElements 참조) 다른 어떤 값보다 항상 크게 비교되므로 comparator 가 제공되지 않을 때 NaN 값은 결과 끝에 정렬된다.

23.2.3.30 %TypedArray%.prototype.subarray ( start, end )

이 메서드는 새로운 TypedArray 를 반환하며 그 요소 타입은 이 TypedArray 의 요소 타입과 같고, ArrayBuffer 는 동일한 ArrayBuffer 를 사용하며 start (포함) 부터 end (배타) 전까지의 요소를 참조한다. start 또는 end 가 음수이면 배열의 끝을 기준으로 하는 인덱스를 의미한다.

호출 시 다음 단계를 수행한다:

  1. O = this 값.
  2. RequireInternalSlot(O, [[TypedArrayName]]) 수행.
  3. Assert: O[[ViewedArrayBuffer]] 내부 슬롯을 가진다.
  4. buffer = O.[[ViewedArrayBuffer]].
  5. srcRecord = MakeTypedArrayWithBufferWitnessRecord(O, seq-cst).
  6. IsTypedArrayOutOfBounds(srcRecord) true 이면
    1. srcLength = 0.
  7. Else
    1. srcLength = TypedArrayLength(srcRecord).
  8. relativeStart = ? ToIntegerOrInfinity(start).
  9. relativeStart = -∞ 이면 startIndex = 0.
  10. Else if relativeStart < 0 이면 startIndex = max(srcLength + relativeStart, 0).
  11. Else startIndex = min(relativeStart, srcLength).
  12. elementSize = TypedArrayElementSize(O).
  13. srcByteOffset = O.[[ByteOffset]].
  14. beginByteOffset = srcByteOffset + (startIndex × elementSize).
  15. O.[[ArrayLength]]auto 이고 endundefined 이면
    1. argumentsList = « buffer, 𝔽(beginByteOffset) ».
  16. Else
    1. end undefined 이면 relativeEnd = srcLength; else relativeEnd = ? ToIntegerOrInfinity(end).
    2. relativeEnd = -∞ 이면 endIndex = 0.
    3. Else if relativeEnd < 0 이면 endIndex = max(srcLength + relativeEnd, 0).
    4. Else endIndex = min(relativeEnd, srcLength).
    5. newLength = max(endIndex - startIndex, 0).
    6. argumentsList = « buffer, 𝔽(beginByteOffset), 𝔽(newLength) ».
  17. TypedArraySpeciesCreate(O, argumentsList) 반환.

이 메서드는 제네릭이 아니다. this 값은 [[TypedArrayName]] 내부 슬롯을 가진 객체여야 한다.

23.2.3.31 %TypedArray%.prototype.toLocaleString ( [ reserved1 [ , reserved2 ] ] )

이 별도 메서드는 23.1.3.32에 정의된 Array.prototype.toLocaleString 과 동일한 알고리즘을 구현하되 "length" 에 대한 [[Get]] 대신 TypedArrayLength 를 호출한다. 기본 버퍼가 리사이즈 가능하지 않고 정수 인덱스 프로퍼티가 희소하지 않음을 이용해 최적화할 수 있으나, 그러한 최적화는 알고리즘의 지정된 동작에 관측 가능한 변화를 초래해서는 안 된다.

이 메서드는 제네릭이 아니다. 알고리즘 평가 전에 this 값과 seq-cst 를 인자로 ValidateTypedArray 가 호출된다. 그 결과가 abrupt completion 이면 해당 예외가 알고리즘 대신 던져진다.

Note

ECMAScript 구현이 ECMA-402 국제화 API 를 포함한다면 이 메서드는 ECMA-402 명세에 있는 Array.prototype.toLocaleString 알고리즘을 기반으로 한다.

23.2.3.32 %TypedArray%.prototype.toReversed ( )

이 메서드는 호출 시 다음 단계를 수행한다:

  1. O = this 값.
  2. taRecord = ? ValidateTypedArray(O, seq-cst).
  3. len = TypedArrayLength(taRecord).
  4. A = ? TypedArrayCreateSameType(O, len).
  5. k = 0.
  6. k < len 동안 반복
    1. from = ! ToString(𝔽(len - k - 1)).
    2. Pk = ! ToString(𝔽(k)).
    3. fromValue = ! Get(O, from).
    4. Set(A, Pk, fromValue, true) 수행.
    5. k = k + 1.
  7. A 반환.

23.2.3.33 %TypedArray%.prototype.toSorted ( comparator )

이 메서드는 호출 시 다음 단계를 수행한다:

  1. comparatorundefined 그리고 IsCallable(comparator) = false 이면 TypeError 예외.
  2. O = this 값.
  3. taRecord = ? ValidateTypedArray(O, seq-cst).
  4. len = TypedArrayLength(taRecord).
  5. A = ? TypedArrayCreateSameType(O, len).
  6. NOTE: 다음 클로저는 23.1.3.34 에서의 문자열 비교 대신 수치 비교를 수행한다.
  7. SortCompare 를 (x, y) → ? CompareTypedArrayElements(x, y, comparator) 클로저로 둔다.
  8. sortedList = ? SortIndexedProperties(O, len, SortCompare, read-through-holes).
  9. j = 0.
  10. j < len 동안 반복
    1. Set(A, ! ToString(𝔽(j)), sortedList[j], true) 수행.
    2. j = j + 1.
  11. A 반환.

23.2.3.34 %TypedArray%.prototype.toString ( )

"toString" 프로퍼티의 초기 값은 23.1.3.36에 정의된 %Array.prototype.toString% 이다.

23.2.3.35 %TypedArray%.prototype.values ( )

이 메서드는 호출 시 다음 단계를 수행한다:

  1. O = this 값.
  2. ValidateTypedArray(O, seq-cst) 수행.
  3. CreateArrayIterator(O, value) 반환.

23.2.3.36 %TypedArray%.prototype.with ( index, value )

이 메서드는 호출 시 다음 단계를 수행한다:

  1. O = this 값.
  2. taRecord = ? ValidateTypedArray(O, seq-cst).
  3. len = TypedArrayLength(taRecord).
  4. relativeIndex = ? ToIntegerOrInfinity(index).
  5. relativeIndex ≥ 0 이면 actualIndex = relativeIndex; Else actualIndex = len + relativeIndex.
  6. O.[[ContentType]] = bigint 이면 numericValue = ? ToBigInt(value).
  7. Else numericValue = ? ToNumber(value).
  8. IsValidIntegerIndex(O, 𝔽(actualIndex)) false 이면 RangeError 예외.
  9. A = ? TypedArrayCreateSameType(O, len).
  10. k = 0.
  11. k < len 동안 반복
    1. Pk = ! ToString(𝔽(k)).
    2. k = actualIndex 이면 fromValue = numericValue; Else fromValue = ! Get(O, Pk).
    3. Set(A, Pk, fromValue, true) 수행.
    4. k = k + 1.
  12. A 반환.

23.2.3.37 %TypedArray%.prototype [ %Symbol.iterator% ] ( )

%Symbol.iterator% 프로퍼티의 초기 값은 23.2.3.35에 정의된 %TypedArray.prototype.values% 이다.

23.2.3.38 get %TypedArray%.prototype [ %Symbol.toStringTag% ]

%TypedArray%.prototype[%Symbol.toStringTag%] 는 set 접근자 함수가 undefined접근자 프로퍼티이다. 그 get 접근자 함수는 호출 시 다음을 수행한다:

  1. O = this 값.
  2. O 가 Object 가 아니면 undefined 반환.
  3. O[[TypedArrayName]] 내부 슬롯을 가지지 않으면 undefined 반환.
  4. name = O.[[TypedArrayName]].
  5. Assert: name 은 String.
  6. name 반환.

이 프로퍼티는 { [[Enumerable]]: false, [[Configurable]]: true } 특성을 가진다.

이 함수의 "name" 프로퍼티 초기 값은 "get [Symbol.toStringTag]" 이다.

23.2.4 TypedArray 객체를 위한 추상 연산

23.2.4.1 TypedArrayCreateFromConstructor ( constructor, argumentList )

The abstract operation TypedArrayCreateFromConstructor takes arguments constructor (a constructor) and argumentList (a List of ECMAScript language values) and returns TypedArray 또는 throw completion. 생성자 함수를 사용하여 새로운 TypedArray 를 생성하는 과정을 지정한다. It performs the following steps when called:

  1. newTypedArray = ? Construct(constructor, argumentList).
  2. taRecord = ? ValidateTypedArray(newTypedArray, seq-cst).
  3. Assert: newTypedArrayTypedArray 인스턴스의 프로퍼티에 언급된 모든 내부 슬롯을 가진다.
  4. argumentList 요소 수가 1 이고 argumentList[0] 이 Number 이면
    1. IsTypedArrayOutOfBounds(taRecord) true 이면 TypeError 예외.
    2. length = TypedArrayLength(taRecord).
    3. length < (argumentList[0]) 이면 TypeError 예외.
  5. newTypedArray 반환.

23.2.4.2 TypedArrayCreateSameType ( exemplar, length )

The abstract operation TypedArrayCreateSameType takes arguments exemplar (a TypedArray) and length (a non-negative integer) and returns TypedArray 또는 throw completion. exemplar 에서 파생된 생성자length 를 사용해 새로운 TypedArray 를 생성한다. %Symbol.species% 를 사용하는 커스텀 서브클래스를 만들 수 있는 TypedArraySpeciesCreate 와 달리, 이 연산은 항상 내장 TypedArray 생성자 중 하나를 사용한다. It performs the following steps when called:

  1. constructor = Table 73 에서 exemplar.[[TypedArrayName]] 생성자 이름에 연관된 내재 객체.
  2. result = ? TypedArrayCreateFromConstructor(constructor, « 𝔽(length) »).
  3. Assert: result[[TypedArrayName]], [[ContentType]] 내부 슬롯을 가진다.
  4. Assert: result.[[ContentType]] = exemplar.[[ContentType]].
  5. result 반환.

23.2.4.3 TypedArraySpeciesCreate ( exemplar, argumentList )

The abstract operation TypedArraySpeciesCreate takes arguments exemplar (a TypedArray) and argumentList (a List of ECMAScript language values) and returns TypedArray 또는 throw completion. exemplar 에서 파생된 생성자 함수를 사용하여 새로운 TypedArray 를 생성한다. ArraySpeciesCreate%Symbol.species% 를 통해 비-Array 객체를 만들 수 있는 것과 달리 이 연산은 실제 TypedArray 생성자임을 강제한다. It performs the following steps when called:

  1. defaultConstructor = Table 73 에서 exemplar.[[TypedArrayName]] 생성자 이름에 연관된 내재 객체.
  2. constructor = ? SpeciesConstructor(exemplar, defaultConstructor).
  3. result = ? TypedArrayCreateFromConstructor(constructor, argumentList).
  4. result.[[ContentType]]exemplar.[[ContentType]] 이면 TypeError 예외.
  5. result 반환.

23.2.4.4 ValidateTypedArray ( O, order )

The abstract operation ValidateTypedArray takes arguments O (an ECMAScript language value) and order (seq-cst or unordered) and returns TypedArray With Buffer Witness Record 또는 throw completion. It performs the following steps when called:

  1. RequireInternalSlot(O, [[TypedArrayName]]) 수행.
  2. Assert: O[[ViewedArrayBuffer]] 내부 슬롯을 가진다.
  3. taRecord = MakeTypedArrayWithBufferWitnessRecord(O, order).
  4. IsTypedArrayOutOfBounds(taRecord) true 이면 TypeError 예외.
  5. taRecord 반환.

23.2.4.5 TypedArrayElementSize ( O )

The abstract operation TypedArrayElementSize takes argument O (a TypedArray) and returns 음이 아닌 정수. It performs the following steps when called:

  1. Table 73 에서 O.[[TypedArrayName]] 에 대해 지정된 요소 크기(Element Size) 값을 반환.

23.2.4.6 TypedArrayElementType ( O )

The abstract operation TypedArrayElementType takes argument O (a TypedArray) and returns TypedArray element type. It performs the following steps when called:

  1. Table 73 에서 O.[[TypedArrayName]] 에 대해 지정된 요소 타입(Element Type) 값을 반환.

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 Number 또는 abrupt completion. It performs the following steps when called:

  1. Assert: x, y 둘 다 Number 이거나 둘 다 BigInt.
  2. comparatorundefined 이면
    1. v = ? ToNumber(? Call(comparator, undefined, « x, y »)).
    2. vNaN 이면 +0𝔽 반환.
    3. v 반환.
  3. xy 모두 NaN 이면 +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에서의 문자열 비교 대신 수치 비교를 수행한다.

23.2.5 TypedArray 생성자

TypedArray 생성자는 다음을 만족한다:

  • Table 73에서 TypedArray 대신 생성자 이름만 다른, 아래에서 설명된 구조를 갖는 내재 객체이다.
  • 인자의 개수와 타입에 따라 동작이 달라지는 함수이다. TypedArray 호출의 실제 동작은 전달된 인자의 개수와 종류에 의존한다.
  • 함수로 호출하도록 의도되지 않았으며 그러한 방식으로 호출되면 예외를 던진다.
  • 클래스 정의의 extends 절 값으로 사용될 수 있다. 지정된 TypedArray 동작을 상속하려는 서브클래스 생성자%TypedArray%.prototype 내장 메서드를 지원하는 데 필요한 내부 상태로 서브클래스 인스턴스를 생성·초기화하기 위해 TypedArray 생성자에 대한 super 호출을 포함해야 한다.

23.2.5.1 TypedArray ( ...args )

TypedArray 생성자는 호출 시 다음 단계를 수행한다:

  1. NewTarget 이 undefined 이면 TypeError 예외.
  2. constructorName = 이 TypedArray 생성자에 대해 Table 73에 지정된 Constructor Name 값의 String.
  3. proto = "%TypedArray.prototype%".
  4. numberOfArgs = args 의 요소 개수.
  5. numberOfArgs = 0 이면
    1. AllocateTypedArray(constructorName, NewTarget, proto, 0) 반환.
  6. Else
    1. firstArgument = args[0].
    2. firstArgument 가 Object 이면
      1. O = ? AllocateTypedArray(constructorName, NewTarget, proto).
      2. firstArgument[[TypedArrayName]] 내부 슬롯을 가지면
        1. InitializeTypedArrayFromTypedArray(O, firstArgument) 수행.
      3. Else if firstArgument[[ArrayBufferData]] 내부 슬롯을 가지면
        1. numberOfArgs > 1 이면 byteOffset = args[1]; else byteOffset = undefined.
        2. numberOfArgs > 2 이면 length = args[2]; else length = undefined.
        3. InitializeTypedArrayFromArrayBuffer(O, firstArgument, byteOffset, length) 수행.
      4. Else
        1. Assert: firstArgument[[TypedArrayName]][[ArrayBufferData]] 도 없는 Object.
        2. usingIterator = ? GetMethod(firstArgument, %Symbol.iterator%).
        3. usingIteratorundefined 이면
          1. values = ? IteratorToList(? GetIteratorFromMethod(firstArgument, usingIterator)).
          2. InitializeTypedArrayFromList(O, values) 수행.
        4. Else
          1. NOTE: firstArgument 는 이터러블이 아니므로 배열 유사 객체로 간주.
          2. InitializeTypedArrayFromArrayLike(O, firstArgument) 수행.
      5. O 반환.
    3. Else
      1. Assert: firstArgument 는 Object 가 아님.
      2. elementLength = ? ToIndex(firstArgument).
      3. AllocateTypedArray(constructorName, NewTarget, proto, elementLength) 반환.

23.2.5.1.1 AllocateTypedArray ( constructorName, newTarget, defaultProto [ , length ] )

The abstract operation AllocateTypedArray takes arguments constructorName (Table 73에 있는 TypedArray 생성자 이름인 String), newTarget (a constructor), and defaultProto (a String) and optional argument length (a non-negative integer) and returns TypedArray 또는 throw completion. TypedArray 생성자의 인스턴스를 검증하고 생성하는 데 사용된다. length 인자가 전달되면 해당 길이의 ArrayBuffer 를 할당해 새 TypedArray 인스턴스와 연관시킨다. AllocateTypedArray 는 TypedArray 가 사용하는 공통 의미를 제공한다. It performs the following steps when called:

  1. proto = ? GetPrototypeFromConstructor(newTarget, defaultProto).
  2. obj = TypedArrayCreate(proto).
  3. Assert: obj.[[ViewedArrayBuffer]]undefined.
  4. obj.[[TypedArrayName]] = constructorName.
  5. constructorName"BigInt64Array" 또는 "BigUint64Array" 이면 obj.[[ContentType]] = bigint.
  6. 아니면 obj.[[ContentType]] = number.
  7. length 미존재이면
    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 ( O, srcArray )

The abstract operation InitializeTypedArrayFromTypedArray takes arguments O (a TypedArray) and srcArray (a TypedArray) and returns unused 또는 throw completion. It performs the following steps when called:

  1. srcData = srcArray.[[ViewedArrayBuffer]].
  2. elementType = TypedArrayElementType(O).
  3. elementSize = TypedArrayElementSize(O).
  4. srcType = TypedArrayElementType(srcArray).
  5. srcElementSize = TypedArrayElementSize(srcArray).
  6. srcByteOffset = srcArray.[[ByteOffset]].
  7. srcRecord = MakeTypedArrayWithBufferWitnessRecord(srcArray, seq-cst).
  8. IsTypedArrayOutOfBounds(srcRecord) true 이면 TypeError 예외.
  9. elementLength = TypedArrayLength(srcRecord).
  10. byteLength = elementSize × elementLength.
  11. elementType = srcType 이면
    1. data = ? CloneArrayBuffer(srcData, srcByteOffset, byteLength).
  12. Else
    1. data = ? AllocateArrayBuffer(%ArrayBuffer%, byteLength).
    2. srcArray.[[ContentType]]O.[[ContentType]] 이면 TypeError 예외.
    3. srcByteIndex = srcByteOffset.
    4. targetByteIndex = 0.
    5. count = elementLength.
    6. count > 0 동안 반복
      1. value = GetValueFromBuffer(srcData, srcByteIndex, srcType, true, unordered).
      2. SetValueInBuffer(data, targetByteIndex, elementType, value, true, unordered) 수행.
      3. srcByteIndex = srcByteIndex + srcElementSize.
      4. targetByteIndex = targetByteIndex + elementSize.
      5. count = count - 1.
  13. O.[[ViewedArrayBuffer]] = data.
  14. O.[[ByteLength]] = byteLength.
  15. O.[[ByteOffset]] = 0.
  16. O.[[ArrayLength]] = elementLength.
  17. unused 반환.

23.2.5.1.3 InitializeTypedArrayFromArrayBuffer ( O, buffer, byteOffset, length )

The abstract operation InitializeTypedArrayFromArrayBuffer takes arguments O (a TypedArray), buffer (an ArrayBuffer or a SharedArrayBuffer), byteOffset (an ECMAScript language value), and length (an ECMAScript language value) and returns unused 또는 throw completion. It performs the following steps when called:

  1. elementSize = TypedArrayElementSize(O).
  2. offset = ? ToIndex(byteOffset).
  3. offset modulo elementSize ≠ 0 이면 RangeError 예외.
  4. bufferIsFixedLength = IsFixedLengthArrayBuffer(buffer).
  5. lengthundefined 이면
    1. newLength = ? ToIndex(length).
  6. IsDetachedBuffer(buffer) true 이면 TypeError 예외.
  7. bufferByteLength = ArrayBufferByteLength(buffer, seq-cst).
  8. length = undefined 이고 bufferIsFixedLength = false 이면
    1. offset > bufferByteLength 이면 RangeError 예외.
    2. O.[[ByteLength]] = auto.
    3. O.[[ArrayLength]] = auto.
  9. Else
    1. length = undefined 이면
      1. bufferByteLength modulo elementSize ≠ 0 이면 RangeError 예외.
      2. newByteLength = bufferByteLength - offset.
      3. newByteLength < 0 이면 RangeError 예외.
    2. Else
      1. newByteLength = newLength × elementSize.
      2. offset + newByteLength > bufferByteLength 이면 RangeError 예외.
    3. O.[[ByteLength]] = newByteLength.
    4. O.[[ArrayLength]] = newByteLength / elementSize.
  10. O.[[ViewedArrayBuffer]] = buffer.
  11. O.[[ByteOffset]] = offset.
  12. unused 반환.

23.2.5.1.4 InitializeTypedArrayFromList ( O, values )

The abstract operation InitializeTypedArrayFromList takes arguments O (a TypedArray) and values (a List of ECMAScript language values) and returns unused 또는 throw completion. It performs the following steps when called:

  1. len = values 요소 개수.
  2. AllocateTypedArrayBuffer(O, len) 수행.
  3. k = 0.
  4. k < len 동안 반복
    1. Pk = ! ToString(𝔽(k)).
    2. kValue = values 의 첫 요소.
    3. values 의 첫 요소 제거.
    4. Set(O, Pk, kValue, true) 수행.
    5. k = k + 1.
  5. Assert: values 는 이제 빈 List.
  6. unused 반환.

23.2.5.1.5 InitializeTypedArrayFromArrayLike ( O, arrayLike )

The abstract operation InitializeTypedArrayFromArrayLike takes arguments O (a TypedArray) and arrayLike (an Object, but not a TypedArray or an ArrayBuffer) and returns unused 또는 throw completion. It performs the following steps when called:

  1. len = ? LengthOfArrayLike(arrayLike).
  2. AllocateTypedArrayBuffer(O, len) 수행.
  3. k = 0.
  4. k < len 동안 반복
    1. Pk = ! ToString(𝔽(k)).
    2. kValue = ? Get(arrayLike, Pk).
    3. Set(O, Pk, kValue, true) 수행.
    4. k = k + 1.
  5. unused 반환.

23.2.5.1.6 AllocateTypedArrayBuffer ( O, length )

The abstract operation AllocateTypedArrayBuffer takes arguments O (a TypedArray) and length (a non-negative integer) and returns unused 또는 throw completion. O 에 ArrayBuffer 를 할당하고 연관시킨다. It performs the following steps when called:

  1. Assert: O.[[ViewedArrayBuffer]]undefined.
  2. elementSize = TypedArrayElementSize(O).
  3. byteLength = elementSize × length.
  4. data = ? AllocateArrayBuffer(%ArrayBuffer%, byteLength).
  5. O.[[ViewedArrayBuffer]] = data.
  6. O.[[ByteLength]] = byteLength.
  7. O.[[ByteOffset]] = 0.
  8. O.[[ArrayLength]] = length.
  9. unused 반환.

23.2.6 TypedArray 생성자들의 프로퍼티

TypedArray 생성자는 다음을 가진다:

  • 값이 %TypedArray%[[Prototype]] 내부 슬롯.
  • 값이 3𝔽"length" 프로퍼티.
  • Table 73에 지정된 생성자 이름의 String 값인 "name" 프로퍼티.
  • 다음 프로퍼티들:

23.2.6.1 TypedArray.BYTES_PER_ELEMENT

TypedArray.BYTES_PER_ELEMENT 의 값은 Table 73에서 TypedArray 에 대해 지정된 요소 크기(Element Size) 값이다.

이 프로퍼티는 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false } 특성을 가진다.

23.2.6.2 TypedArray.prototype

TypedArray.prototype 의 초기 값은 해당하는 TypedArray 프로토타입 내재 객체(23.2.7)이다.

이 프로퍼티는 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false } 특성을 가진다.

23.2.7 TypedArray 프로토타입 객체들의 프로퍼티

TypedArray 프로토타입 객체는 다음을 가진다:

23.2.7.1 TypedArray.prototype.BYTES_PER_ELEMENT

TypedArray.prototype.BYTES_PER_ELEMENT 의 값은 Table 73에서 TypedArray 에 대해 지정된 요소 크기(Element Size) 값이다.

이 프로퍼티는 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false } 특성을 가진다.

23.2.7.2 TypedArray.prototype.constructor

주어진 TypedArray 생성자에 대한 프로토타입의 "constructor" 프로퍼티 초기 값은 그 생성자 자신이다.

23.2.8 TypedArray 인스턴스의 프로퍼티

TypedArray 인스턴스는 TypedArray 이다. 각 TypedArray 인스턴스는 해당 TypedArray 프로토타입 객체로부터 프로퍼티를 상속한다. 각 TypedArray 인스턴스는 내부 슬롯 [[ViewedArrayBuffer]], [[TypedArrayName]], [[ContentType]], [[ByteLength]], [[ByteOffset]], [[ArrayLength]] 를 가진다.

24 키드 컬렉션(Keyed Collections)

24.1 Map 객체

Map 은 키/값 쌍의 컬렉션이며 키와 값 모두 임의의 ECMAScript 언어 값을 사용할 수 있다. 하나의 고유 키 값은 그 Map 컬렉션 안에서 하나의 키/값 쌍에만 등장할 수 있다. 고유 키 값의 구분은 SameValueZero 비교 알고리즘의 의미론을 사용한다.

Map 은 평균적으로 컬렉션의 요소 수에 대해 준선형(sublinear) 접근 시간을 제공하는 해시 테이블 또는 다른 메커니즘을 사용하여 구현되어야 한다. 이 명세에서 사용하는 자료 구조는 Map 의 요구되는 관측 가능 의미를 설명하기 위한 것이며 실제 구현 모델이 되려는 목적은 아니다.

24.1.1 Map 생성자

Map 생성자:

  • %Map% 이다.
  • 전역 객체"Map" 프로퍼티 초기 값이다.
  • 생성자로 호출될 때 새 Map 을 생성하고 초기화한다.
  • 함수로 호출하도록 의도되지 않았으며 그렇게 호출하면 예외를 던진다.
  • 클래스 정의의 extends 절 값으로 사용할 수 있다. 지정된 Map 동작을 상속하려는 서브클래스 생성자Map.prototype 내장 메서드를 지원하는 데 필요한 내부 상태로 서브클래스 인스턴스를 생성·초기화하기 위해 Map 생성자에 대한 super 호출을 포함해야 한다.

24.1.1.1 Map ( [ iterable ] )

이 함수는 호출 시 다음 단계를 수행한다:

  1. NewTarget 이 undefined 이면 TypeError 예외.
  2. map = ? OrdinaryCreateFromConstructor(NewTarget, "%Map.prototype%", « [[MapData]] »).
  3. map.[[MapData]] 를 새 빈 List 로 설정.
  4. iterableundefined 또는 null 이면 map 반환.
  5. adder = ? Get(map, "set").
  6. IsCallable(adder) 가 false 이면 TypeError 예외.
  7. Return ? AddEntriesFromIterable(map, iterable, adder).
Note

매개변수 iterable 이 존재하면, 첫 번째 요소가 Map 키로 사용될 값이고 두 번째 요소가 그 키에 연결할 값인 2-요소 배열 유사 객체를 생성하는 이터레이터 객체를 반환하는 %Symbol.iterator% 메서드를 구현한 객체일 것으로 기대된다.

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 정상 완료(ECMAScript 언어 값 포함) 또는 throw completion. addertarget 을 receiver 로 하여 호출된다. It performs the following steps when called:

  1. iteratorRecord = ? GetIterator(iterable, sync).
  2. 반복:
    1. next = ? IteratorStepValue(iteratorRecord).
    2. nextdone 이면 target 반환.
    3. next 가 Object 가 아니면
      1. error = ThrowCompletion(새로 생성된 TypeError 객체).
      2. Return ? IteratorClose(iteratorRecord, error).
    4. k = Completion(Get(next, "0")).
    5. IfAbruptCloseIterator(k, iteratorRecord).
    6. v = Completion(Get(next, "1")).
    7. IfAbruptCloseIterator(v, iteratorRecord).
    8. status = Completion(Call(adder, target, « k, v »)).
    9. IfAbruptCloseIterator(status, iteratorRecord).
Note

매개변수 iterable 은 2-요소 배열 유사 객체를 생성하는 이터레이터 객체를 반환하는 %Symbol.iterator% 메서드를 구현한 객체일 것으로 기대된다. 첫 요소는 Map 키로, 두 번째 요소는 그 키에 연결할 값이다.

24.1.2 Map 생성자의 프로퍼티

Map 생성자:

  • 값이 %Function.prototype%[[Prototype]] 내부 슬롯을 가진다.
  • 다음 프로퍼티를 가진다:

24.1.2.1 Map.groupBy ( items, callback )

Note

callback 은 두 인자를 받는 함수여야 한다. groupByitems 의 각 요소에 대해 오름차순으로 한 번씩 callback 을 호출하고 새 Map 을 구성한다. callback 이 반환한 각 값은 Map 의 키로 사용된다. 그러한 키마다 결과 Map 은 그 키를 키로 하고 callback 이 그 키를 반환한 모든 요소가 담긴 배열을 값으로 갖는 엔트리를 가진다.

callback 은 요소의 값과 요소의 인덱스 두 인자로 호출된다.

groupBy 의 반환 값은 Map 이다.

이 함수는 호출 시 다음 단계를 수행한다:

  1. groups = ? GroupBy(items, callback, collection).
  2. map = ! Construct(%Map%).
  3. Record { [[Key]], [[Elements]] } ggroups 에 대해
    1. elements = CreateArrayFromList(g.[[Elements]]).
    2. entry = Record { [[Key]]: g.[[Key]], [[Value]]: elements }.
    3. entrymap.[[MapData]] 에 append.
  4. map 반환.

24.1.2.2 Map.prototype

Map.prototype 의 초기 값은 Map 프로토타입 객체이다.

이 프로퍼티는 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false } 특성을 가진다.

24.1.2.3 get Map [ %Symbol.species% ]

Map[%Symbol.species%] 는 set 접근자 함수가 undefined접근자 프로퍼티이다. 그 get 접근자 함수는 호출 시 다음을 수행한다:

  1. this 값을 반환.

이 함수의 "name" 프로퍼티 값은 "get [Symbol.species]" 이다.

Note

파생 컬렉션 객체를 생성하는 메서드는 파생 객체를 생성할 때 사용할 생성자를 결정하기 위해 %Symbol.species% 를 호출해야 한다. 서브클래스 생성자는 기본 생성자 할당을 변경하기 위해 %Symbol.species% 를 재정의할 수 있다.

24.1.3 Map 프로토타입 객체의 프로퍼티

Map 프로토타입 객체는:

  • %Map.prototype% 이다.
  • 값이 %Object.prototype%[[Prototype]] 내부 슬롯을 가진다.
  • 일반 객체이다.
  • [[MapData]] 내부 슬롯을 가지지 않는다.

24.1.3.1 Map.prototype.clear ( )

이 메서드는 호출 시 다음 단계를 수행한다:

  1. M = this 값.
  2. RequireInternalSlot(M, [[MapData]]) 수행.
  3. M.[[MapData]] 의 각 Record { [[Key]], [[Value]] } p 에 대해
    1. p.[[Key]] = empty 로 설정.
    2. p.[[Value]] = empty 로 설정.
  4. undefined 반환.
Note

기존 [[MapData]] List 는 그 List 순회를 중간에 일시중단한 기존 Map Iterator 객체가 있을 수 있으므로 유지된다.

24.1.3.2 Map.prototype.constructor

Map.prototype.constructor 의 초기 값은 %Map% 이다.

24.1.3.3 Map.prototype.delete ( key )

이 메서드는 호출 시 다음 단계를 수행한다:

  1. M = this 값.
  2. RequireInternalSlot(M, [[MapData]]) 수행.
  3. key = CanonicalizeKeyedCollectionKey(key).
  4. M.[[MapData]] 의 각 Record { [[Key]], [[Value]] } p 에 대해
    1. p.[[Key]]empty 이고 SameValue(p.[[Key]], key) = true 이면
      1. p.[[Key]] = empty.
      2. p.[[Value]] = empty.
      3. true 반환.
  5. false 반환.
Note

empty 는 엔트리가 삭제되었음을 나타내는 명세 기법이다. 실제 구현은 내부 자료 구조에서 물리적으로 제거하는 등의 다른 동작을 할 수 있다.

24.1.3.4 Map.prototype.entries ( )

이 메서드는 호출 시 다음 단계를 수행한다:

  1. M = this 값.
  2. Return ? CreateMapIterator(M, key+value).

24.1.3.5 Map.prototype.forEach ( callback [ , thisArg ] )

이 메서드는 호출 시 다음 단계를 수행한다:

  1. M = this 값.
  2. RequireInternalSlot(M, [[MapData]]) 수행.
  3. IsCallable(callback) false 이면 TypeError 예외.
  4. entries = M.[[MapData]].
  5. numEntries = entries 요소 수.
  6. index = 0.
  7. 반복, index < numEntries 동안
    1. e = entries[index].
    2. index = index + 1.
    3. e.[[Key]]empty 이면
      1. Call(callback, thisArg, « e.[[Value]], e.[[Key]], M ») 수행.
      2. NOTE: callback 실행 중 entries 요소 수가 증가할 수 있다.
      3. numEntries = entries 요소 수로 재설정.
  8. undefined 반환.
Note

callback 은 세 인자를 받는 함수여야 한다. forEach 는 Map 에 존재하는 각 키/값 쌍을 키 삽입 순서대로 한 번씩 callback 에 전달한다. callback 은 실제 존재하는 키에 대해서만 호출되며 Map 에서 삭제된 키에 대해서는 호출되지 않는다.

thisArg 가 제공되면 각 호출의 this 값으로 사용되며, 제공되지 않으면 undefined 사용.

callback 은 (값, 키, 순회 중인 Map) 세 인자로 호출된다.

forEach 자체는 호출된 객체를 직접 변이하지 않지만 callback 호출에 의해 변이될 수 있다. Map 의 [[MapData]] 각 엔트리는 한 번만 방문된다. 호출 시작 후 추가된 새 키는 방문된다. 이미 방문된 키가 삭제되고 다시 추가되면 다시 방문된다. 시작 후 방문되기 전에 삭제된 키는 재추가되지 않는 한 방문되지 않는다.

24.1.3.6 Map.prototype.get ( key )

이 메서드는 호출 시 다음 단계를 수행한다:

  1. M = this 값.
  2. RequireInternalSlot(M, [[MapData]]) 수행.
  3. key = CanonicalizeKeyedCollectionKey(key).
  4. M.[[MapData]] 의 각 Record { [[Key]], [[Value]] } p 에 대해
    1. p.[[Key]]empty 그리고 SameValue(p.[[Key]], key) = true 이면 p.[[Value]] 반환.
  5. undefined 반환.

24.1.3.7 Map.prototype.has ( key )

이 메서드는 호출 시 다음 단계를 수행한다:

  1. M = this 값.
  2. RequireInternalSlot(M, [[MapData]]) 수행.
  3. key = CanonicalizeKeyedCollectionKey(key).
  4. M.[[MapData]] 의 각 Record { [[Key]], [[Value]] } p 에 대해
    1. p.[[Key]]empty 그리고 SameValue(p.[[Key]], key) = true 이면 true 반환.
  5. false 반환.

24.1.3.8 Map.prototype.keys ( )

이 메서드는 호출 시 다음 단계를 수행한다:

  1. M = this 값.
  2. Return ? CreateMapIterator(M, key).

24.1.3.9 Map.prototype.set ( key, value )

이 메서드는 호출 시 다음 단계를 수행한다:

  1. M = this 값.
  2. RequireInternalSlot(M, [[MapData]]) 수행.
  3. key = CanonicalizeKeyedCollectionKey(key).
  4. M.[[MapData]] 의 각 Record { [[Key]], [[Value]] } p 에 대해
    1. p.[[Key]]empty 그리고 SameValue(p.[[Key]], key) = true 이면
      1. p.[[Value]] = value.
      2. M 반환.
  5. p = Record { [[Key]]: key, [[Value]]: value }.
  6. pM.[[MapData]] 에 append.
  7. M 반환.

24.1.3.10 get Map.prototype.size

Map.prototype.size 는 set 접근자 함수가 undefined접근자 프로퍼티이다. 그 get 접근자 함수는 호출 시 다음 단계를 수행한다:

  1. M = this 값.
  2. RequireInternalSlot(M, [[MapData]]) 수행.
  3. count = 0.
  4. M.[[MapData]] 의 각 Record { [[Key]], [[Value]] } p 에 대해
    1. p.[[Key]]empty 이면 count = count + 1.
  5. 𝔽(count) 반환.

24.1.3.11 Map.prototype.values ( )

이 메서드는 호출 시 다음 단계를 수행한다:

  1. M = this 값.
  2. Return ? CreateMapIterator(M, value).

24.1.3.12 Map.prototype [ %Symbol.iterator% ] ( )

%Symbol.iterator% 프로퍼티의 초기 값은 24.1.3.4에 정의된 %Map.prototype.entries% 이다.

24.1.3.13 Map.prototype [ %Symbol.toStringTag% ]

%Symbol.toStringTag% 프로퍼티 초기 값은 String "Map" 이다.

이 프로퍼티 특성은 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }.

24.1.4 Map 인스턴스의 프로퍼티

Map 인스턴스는 일반 객체이며 Map 프로토타입 객체로부터 프로퍼티를 상속한다. 또한 [[MapData]] 내부 슬롯을 가진다.

24.1.5 Map 이터레이터 객체

Map Iterator 는 특정 Map 인스턴스 객체에 대한 특정 순회를 나타내는 객체이다. Map Iterator 객체에 대한 이름 있는 생성자는 없다. 대신 Map 인스턴스 객체의 특정 메서드를 호출하여 생성된다.

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 Generator 또는 throw completion. Map 메서드 중 그러한 이터레이터를 반환하는 것들이 사용할 이터레이터 객체를 생성한다. It performs the following steps when called:

  1. RequireInternalSlot(map, [[MapData]]) 수행.
  2. closure 를 매개변수 없고 map, kind 를 캡처하며 호출 시 다음 단계를 수행하는 새 추상 클로저로 둔다:
    1. entries = map.[[MapData]].
    2. index = 0.
    3. numEntries = entries 요소 수.
    4. 반복, index < numEntries 동안
      1. e = entries[index].
      2. index = index + 1.
      3. e.[[Key]]empty 이면
        1. kindkey 이면
          1. result = e.[[Key]].
        2. Else if kind = value 이면
          1. result = e.[[Value]].
        3. Else
          1. Assert: kind = key+value.
          2. result = CreateArrayFromListe.[[Key]], e.[[Value]] »).
        4. GeneratorYield(CreateIteratorResultObject(result, false)) 수행.
        5. NOTE: GeneratorYield 로 일시 중단된 동안 entries 요소 수가 증가할 수 있다.
        6. numEntries = entries 요소 수로 재설정.
    5. Return NormalCompletion(unused).
  3. Return CreateIteratorFromClosure(closure, "%MapIteratorPrototype%", %MapIteratorPrototype%).

24.1.5.2 %MapIteratorPrototype% 객체

%MapIteratorPrototype% 객체:

24.1.5.2.1 %MapIteratorPrototype%.next ( )

  1. Return ? GeneratorResume(this value, empty, "%MapIteratorPrototype%").

24.1.5.2.2 %MapIteratorPrototype% [ %Symbol.toStringTag% ]

%Symbol.toStringTag% 프로퍼티 초기 값은 String "Map Iterator" 이다.

이 프로퍼티 특성은 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }.

24.2 Set 객체

Set 객체는 ECMAScript 언어 값들의 컬렉션이다. 하나의 고유 값은 Set 컬렉션에서 한 번만 요소로 등장할 수 있다. 고유 값의 구분은 SameValueZero 비교 알고리즘 의미론을 사용한다.

Set 객체는 평균적으로 컬렉션 요소 수에 대해 준선형 접근 시간을 제공하는 해시 테이블 또는 다른 메커니즘으로 구현되어야 한다. 이 명세의 자료 구조는 Set 객체의 요구되는 관측 가능 의미를 설명하기 위한 것으로 실제 구현 모델을 의도하지 않는다.

24.2.1 Set 객체를 위한 추상 연산

24.2.1.1 Set Record

Set Record 는 Set 또는 유사 객체의 인터페이스를 캡슐화하기 위해 사용되는 Record 값이다.

Set Record 는 Table 74 에 나열된 필드를 가진다.

Table 74: Set Record 필드
필드 이름 의미
[[SetObject]] an Object 해당 Set 또는 유사 객체.
[[Size]] a non-negative integer or +∞ 객체의 보고된 크기.
[[Has]] a function object 객체의 has 메서드.
[[Keys]] a function object 객체의 keys 메서드.

24.2.1.2 GetSetRecord ( obj )

The abstract operation GetSetRecord takes argument obj (an ECMAScript language value) and returns Set Record 또는 throw completion. It performs the following steps when called:

  1. obj 가 Object 가 아니면 TypeError 예외.
  2. rawSize = ? Get(obj, "size").
  3. numSize = ? ToNumber(rawSize).
  4. NOTE: rawSizeundefined 이면 numSizeNaN.
  5. numSizeNaN 이면 TypeError 예외.
  6. intSize = ! ToIntegerOrInfinity(numSize).
  7. intSize < 0 이면 RangeError 예외.
  8. has = ? Get(obj, "has").
  9. IsCallable(has) false 이면 TypeError 예외.
  10. keys = ? Get(obj, "keys").
  11. IsCallable(keys) false 이면 TypeError 예외.
  12. Set Record { [[SetObject]]: obj, [[Size]]: intSize, [[Has]]: has, [[Keys]]: keys } 반환.

24.2.1.3 SetDataHas ( setData, value )

The abstract operation SetDataHas takes arguments setData (a List of either ECMAScript language values or empty) and value (an ECMAScript language value) and returns 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 음이 아닌 정수 또는 not-found. It performs the following steps when called:

  1. value = CanonicalizeKeyedCollectionKey(value).
  2. size = setData 요소 수.
  3. index = 0.
  4. 반복, index < size 동안
    1. e = setData[index].
    2. eempty 그리고 evalue 이면
      1. index 반환.
    3. index = index + 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 음이 아닌 정수. It performs the following steps when called:

  1. count = 0.
  2. setData 의 각 요소 e 에 대해
    1. eempty 이면 count = count + 1.
  3. count 반환.

24.2.2 Set 생성자

Set 생성자:

  • %Set% 이다.
  • 전역 객체"Set" 프로퍼티 초기 값이다.
  • 생성자로 호출될 때 새 Set 객체를 생성·초기화한다.
  • 함수로 호출하도록 의도되지 않았으며 그렇게 호출하면 예외를 던진다.
  • 클래스 정의의 extends 절 값으로 사용할 수 있다. 지정된 Set 동작을 상속하려는 서브클래스 생성자Set.prototype 내장 메서드를 지원하는 데 필요한 내부 상태로 서브클래스 인스턴스를 생성·초기화하기 위해 Set 생성자에 대한 super 호출을 포함해야 한다.

24.2.2.1 Set ( [ iterable ] )

이 함수는 호출 시 다음 단계를 수행한다:

  1. NewTarget 이 undefined 이면 TypeError 예외.
  2. set = ? OrdinaryCreateFromConstructor(NewTarget, "%Set.prototype%", « [[SetData]] »).
  3. set.[[SetData]] 를 새 빈 List 로 설정.
  4. iterableundefined 또는 null 이면 set 반환.
  5. adder = ? Get(set, "add").
  6. IsCallable(adder) false 이면 TypeError 예외.
  7. iteratorRecord = ? GetIterator(iterable, sync).
  8. 반복:
    1. next = ? IteratorStepValue(iteratorRecord).
    2. nextdone 이면 set 반환.
    3. status = Completion(Call(adder, set, « next »)).
    4. IfAbruptCloseIterator(status, iteratorRecord).

24.2.3 Set 생성자의 프로퍼티

Set 생성자:

  • 값이 %Function.prototype%[[Prototype]] 내부 슬롯을 가진다.
  • 다음 프로퍼티를 가진다:

24.2.3.1 Set.prototype

Set.prototype 의 초기 값은 Set 프로토타입 객체이다.

이 프로퍼티는 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false } 특성을 가진다.

24.2.3.2 get Set [ %Symbol.species% ]

Set[%Symbol.species%] 는 set 접근자 함수가 undefined접근자 프로퍼티이다. 그 get 접근자 함수는 호출 시 다음을 수행한다:

  1. this 값을 반환.

이 함수의 "name" 프로퍼티 값은 "get [Symbol.species]" 이다.

Note

파생 컬렉션 객체를 생성하는 메서드는 파생 객체 생성을 위해 사용할 생성자를 결정하기 위해 %Symbol.species% 를 호출해야 한다. 서브클래스 생성자는 기본 생성자 할당을 변경하기 위해 %Symbol.species% 를 재정의할 수 있다.

24.2.4 Set 프로토타입 객체의 프로퍼티

Set 프로토타입 객체는:

  • %Set.prototype% 이다.
  • 값이 %Object.prototype%[[Prototype]] 내부 슬롯을 가진다.
  • 일반 객체이다.
  • [[SetData]] 내부 슬롯을 가지지 않는다.

24.2.4.1 Set.prototype.add ( value )

이 메서드는 호출 시 다음 단계를 수행한다:

  1. S = this 값.
  2. RequireInternalSlot(S, [[SetData]]) 수행.
  3. value = CanonicalizeKeyedCollectionKey(value).
  4. S.[[SetData]] 의 각 요소 e 에 대해
    1. eempty 그리고 SameValue(e, value) = true 이면
      1. S 반환.
  5. valueS.[[SetData]] 에 append.
  6. S 반환.

24.2.4.2 Set.prototype.clear ( )

이 메서드는 호출 시 다음 단계를 수행한다:

  1. S = this 값.
  2. RequireInternalSlot(S, [[SetData]]) 수행.
  3. S.[[SetData]] 의 각 요소 e 에 대해
    1. 값이 eS.[[SetData]] 의 요소를 값이 empty 인 요소로 교체.
  4. undefined 반환.
Note

기존 [[SetData]] List 는 그 List 순회를 중간에 일시중단한 Set Iterator 객체가 있을 수 있으므로 유지된다.

24.2.4.3 Set.prototype.constructor

Set.prototype.constructor 의 초기 값은 %Set% 이다.

24.2.4.4 Set.prototype.delete ( value )

이 메서드는 호출 시 다음 단계를 수행한다:

  1. S = this 값.
  2. RequireInternalSlot(S, [[SetData]]) 수행.
  3. value = CanonicalizeKeyedCollectionKey(value).
  4. S.[[SetData]] 의 각 요소 e 에 대해
    1. eempty 그리고 SameValue(e, value) = true 이면
      1. 값이 eS.[[SetData]] 요소를 값이 empty 인 요소로 교체.
      2. true 반환.
  5. false 반환.
Note

empty 는 엔트리가 삭제되었음을 나타내는 명세 기법이다. 실제 구현은 내부 자료 구조에서 물리적으로 제거하는 등의 다른 동작을 할 수 있다.

24.2.4.5 Set.prototype.difference ( other )

이 메서드는 호출 시 다음 단계를 수행한다:

  1. O = this 값.
  2. RequireInternalSlot(O, [[SetData]]) 수행.
  3. otherRec = ? GetSetRecord(other).
  4. resultSetData = O.[[SetData]] 의 복사본.
  5. If SetDataSize(O.[[SetData]]) ≤ otherRec.[[Size]] 이면
    1. thisSize = O.[[SetData]] 요소 수.
    2. index = 0.
    3. 반복, index < thisSize 동안
      1. e = resultSetData[index].
      2. eempty 이면
        1. inOther = ToBoolean(? Call(otherRec.[[Has]], otherRec.[[SetObject]], « e »)).
        2. inOther = true 이면
          1. resultSetData[index] = empty.
      3. index = index + 1.
  6. Else
    1. keysIter = ? GetIteratorFromMethod(otherRec.[[SetObject]], otherRec.[[Keys]]).
    2. next = not-started.
    3. 반복, nextdone 동안
      1. next = ? IteratorStepValue(keysIter).
      2. nextdone 이면
        1. next = CanonicalizeKeyedCollectionKey(next).
        2. valueIndex = SetDataIndex(resultSetData, next).
        3. valueIndexnot-found 이면
          1. resultSetData[valueIndex] = empty.
  7. result = OrdinaryObjectCreate(%Set.prototype%, « [[SetData]] »).
  8. result.[[SetData]] = resultSetData.
  9. result 반환.

24.2.4.6 Set.prototype.entries ( )

이 메서드는 호출 시 다음 단계를 수행한다:

  1. S = this 값.
  2. Return ? CreateSetIterator(S, key+value).
Note

순회 목적상 Set 은 각 엔트리의 키와 값이 같은 Map 과 유사하게 보인다.

24.2.4.7 Set.prototype.forEach ( callback [ , thisArg ] )

이 메서드는 호출 시 다음 단계를 수행한다:

  1. S = this 값.
  2. RequireInternalSlot(S, [[SetData]]) 수행.
  3. IsCallable(callback) false 이면 TypeError 예외.
  4. entries = S.[[SetData]].
  5. numEntries = entries 요소 수.
  6. index = 0.
  7. 반복, index < numEntries 동안
    1. e = entries[index].
    2. index = index + 1.
    3. eempty 이면
      1. Call(callback, thisArg, « e, e, S ») 수행.
      2. NOTE: callback 실행 중 entries 요소 수가 증가할 수 있다.
      3. numEntries = entries 요소 수로 재설정.
  8. undefined 반환.
Note

callback 은 세 인자를 받는 함수여야 한다. forEach 는 Set 객체에 존재하는 각 값을 값 삽입 순서대로 한 번씩 callback 에 전달한다. callback 은 실제 존재하는 값에 대해서만 호출되며 삭제된 값에 대해서는 호출되지 않는다.

thisArg 가 제공되면 각 호출의 this 값으로 사용되고, 제공되지 않으면 undefined 사용.

callback 은 세 인자로 호출되며 처음 두 인자는 Set 에 포함된 같은 값이고 세 번째 인자는 순회 중인 Set 객체이다.

세 인자 호출 형태는 Map 과 Array 의 forEach 콜백 형태와 일관성을 유지하기 위함이다. Set 에서는 각 항목 값이 키이자 값으로 간주된다.

forEach 는 대상 객체를 직접 변이하지 않지만 callback 호출에 의해 변이될 수 있다.

각 값은 일반적으로 한 번만 방문된다. 그러나 방문 후 삭제됐다가 forEach 완료 전에 재추가되면 다시 방문된다. 시작 후 방문되기 전에 삭제된 값은 재추가되지 않는 한 방문되지 않는다. 시작 후 추가된 새 값은 방문된다.

24.2.4.8 Set.prototype.has ( value )

이 메서드는 호출 시 다음 단계를 수행한다:

  1. S = this 값.
  2. RequireInternalSlot(S, [[SetData]]) 수행.
  3. value = CanonicalizeKeyedCollectionKey(value).
  4. S.[[SetData]] 의 각 요소 e 에 대해
    1. eempty 그리고 SameValue(e, value) = true 이면 true 반환.
  5. false 반환.

24.2.4.9 Set.prototype.intersection ( other )

이 메서드는 호출 시 다음 단계를 수행한다:

  1. O = this 값.
  2. RequireInternalSlot(O, [[SetData]]) 수행.
  3. otherRec = ? GetSetRecord(other).
  4. resultSetData = 새 빈 List.
  5. If SetDataSize(O.[[SetData]]) ≤ otherRec.[[Size]] 이면
    1. thisSize = O.[[SetData]] 요소 수.
    2. index = 0.
    3. 반복, index < thisSize 동안
      1. e = O.[[SetData]][index].
      2. index = index + 1.
      3. eempty 이면
        1. inOther = ToBoolean(? Call(otherRec.[[Has]], otherRec.[[SetObject]], « e »)).
        2. inOther = true 이면
          1. NOTE: 이전 otherRec.[[Has]] 호출이 O.[[SetData]] 요소를 제거 후 재추가하여 같은 요소가 두 번 방문될 수 있다.
          2. SetDataHas(resultSetData, e) = false 이면
            1. eresultSetData 에 append.
        3. NOTE: otherRec.[[Has]] 실행 중 O.[[SetData]] 요소 수가 증가할 수 있다.
        4. thisSize = O.[[SetData]] 요소 수로 재설정.
  6. Else
    1. keysIter = ? GetIteratorFromMethod(otherRec.[[SetObject]], otherRec.[[Keys]]).
    2. next = not-started.
    3. 반복, nextdone 동안
      1. next = ? IteratorStepValue(keysIter).
      2. nextdone 이면
        1. next = CanonicalizeKeyedCollectionKey(next).
        2. inThis = SetDataHas(O.[[SetData]], next).
        3. inThis = true 이면
          1. NOTE: other 는 임의 객체이므로 "keys" 이터레이터가 같은 값을 여러 번 낼 수 있다.
          2. SetDataHas(resultSetData, next) = false 이면
            1. nextresultSetData 에 append.
  7. result = OrdinaryObjectCreate(%Set.prototype%, « [[SetData]] »).
  8. result.[[SetData]] = resultSetData.
  9. result 반환.

24.2.4.10 Set.prototype.isDisjointFrom ( other )

이 메서드는 호출 시 다음 단계를 수행한다:

  1. O = this 값.
  2. RequireInternalSlot(O, [[SetData]]) 수행.
  3. otherRec = ? GetSetRecord(other).
  4. If SetDataSize(O.[[SetData]]) ≤ otherRec.[[Size]] 이면
    1. thisSize = O.[[SetData]] 요소 수.
    2. index = 0.
    3. 반복, index < thisSize 동안
      1. e = O.[[SetData]][index].
      2. index = index + 1.
      3. eempty 이면
        1. inOther = ToBoolean(? Call(otherRec.[[Has]], otherRec.[[SetObject]], « e »)).
        2. inOther = true 이면 false 반환.
        3. NOTE: otherRec.[[Has]] 실행 중 O.[[SetData]] 요소 수가 증가할 수 있다.
        4. thisSize = O.[[SetData]] 요소 수로 재설정.
  5. Else
    1. keysIter = ? GetIteratorFromMethod(otherRec.[[SetObject]], otherRec.[[Keys]]).
    2. next = not-started.
    3. 반복, nextdone 동안
      1. next = ? IteratorStepValue(keysIter).
      2. nextdone 이면
        1. SetDataHas(O.[[SetData]], next) = true 이면
          1. IteratorClose(keysIter, NormalCompletion(unused)) 수행.
          2. false 반환.
  6. true 반환.

24.2.4.11 Set.prototype.isSubsetOf ( other )

이 메서드는 호출 시 다음 단계를 수행한다:

  1. O = this 값.
  2. RequireInternalSlot(O, [[SetData]]) 수행.
  3. otherRec = ? GetSetRecord(other).
  4. SetDataSize(O.[[SetData]]) > otherRec.[[Size]] 이면 false 반환.
  5. thisSize = O.[[SetData]] 요소 수.
  6. index = 0.
  7. 반복, index < thisSize 동안
    1. e = O.[[SetData]][index].
    2. index = index + 1.
    3. eempty 이면
      1. inOther = ToBoolean(? Call(otherRec.[[Has]], otherRec.[[SetObject]], « e »)).
      2. inOther = false 이면 false 반환.
      3. NOTE: otherRec.[[Has]] 실행 중 O.[[SetData]] 요소 수가 증가할 수 있다.
      4. thisSize = O.[[SetData]] 요소 수로 재설정.
  8. true 반환.

24.2.4.12 Set.prototype.isSupersetOf ( other )

이 메서드는 호출 시 다음 단계를 수행한다:

  1. O = this 값.
  2. RequireInternalSlot(O, [[SetData]]) 수행.
  3. otherRec = ? GetSetRecord(other).
  4. SetDataSize(O.[[SetData]]) < otherRec.[[Size]] 이면 false 반환.
  5. keysIter = ? GetIteratorFromMethod(otherRec.[[SetObject]], otherRec.[[Keys]]).
  6. next = not-started.
  7. 반복, nextdone 동안
    1. next = ? IteratorStepValue(keysIter).
    2. nextdone 이면
      1. SetDataHas(O.[[SetData]], next) = false 이면
        1. IteratorClose(keysIter, NormalCompletion(unused)) 수행.
        2. false 반환.
  8. true 반환.

24.2.4.13 Set.prototype.keys ( )

"keys" 프로퍼티의 초기 값은 24.2.4.17에 정의된 %Set.prototype.values% 이다.

Note

순회 목적상 Set 은 각 엔트리의 키와 값이 같은 Map 과 유사하게 보인다.

24.2.4.14 get Set.prototype.size

Set.prototype.size 는 set 접근자 함수가 undefined접근자 프로퍼티이다. 그 get 접근자 함수는 호출 시 다음 단계를 수행한다:

  1. S = this 값.
  2. RequireInternalSlot(S, [[SetData]]) 수행.
  3. size = SetDataSize(S.[[SetData]]).
  4. 𝔽(size) 반환.

24.2.4.15 Set.prototype.symmetricDifference ( other )

이 메서드는 호출 시 다음 단계를 수행한다:

  1. O = this 값.
  2. RequireInternalSlot(O, [[SetData]]) 수행.
  3. otherRec = ? GetSetRecord(other).
  4. keysIter = ? GetIteratorFromMethod(otherRec.[[SetObject]], otherRec.[[Keys]]).
  5. resultSetData = O.[[SetData]] 의 복사본.
  6. next = not-started.
  7. 반복, nextdone 동안
    1. next = ? IteratorStepValue(keysIter).
    2. nextdone 이면
      1. next = CanonicalizeKeyedCollectionKey(next).
      2. resultIndex = SetDataIndex(resultSetData, next).
      3. resultIndex = not-found 이면 alreadyInResult = false; 아니면 true.
      4. SetDataHas(O.[[SetData]], next) = true 이면
        1. alreadyInResult = true 이고 resultIndexnot-found 이 아님이면 resultSetData[resultIndex] = empty.
      5. Else
        1. alreadyInResult = false 이면 nextresultSetData 에 append.
  8. result = OrdinaryObjectCreate(%Set.prototype%, « [[SetData]] »).
  9. result.[[SetData]] = resultSetData.
  10. result 반환.

24.2.4.16 Set.prototype.union ( other )

이 메서드는 호출 시 다음 단계를 수행한다:

  1. O = this 값.
  2. RequireInternalSlot(O, [[SetData]]) 수행.
  3. otherRec = ? GetSetRecord(other).
  4. keysIter = ? GetIteratorFromMethod(otherRec.[[SetObject]], otherRec.[[Keys]]).
  5. resultSetData = O.[[SetData]] 의 복사본.
  6. next = not-started.
  7. 반복, nextdone 동안
    1. next = ? IteratorStepValue(keysIter).
    2. nextdone 이면
      1. next = CanonicalizeKeyedCollectionKey(next).
      2. SetDataHas(resultSetData, next) = false 이면
        1. nextresultSetData 에 append.
  8. result = OrdinaryObjectCreate(%Set.prototype%, « [[SetData]] »).
  9. result.[[SetData]] = resultSetData.
  10. result 반환.

24.2.4.17 Set.prototype.values ( )

이 메서드는 호출 시 다음 단계를 수행한다:

  1. S = this 값.
  2. Return ? CreateSetIterator(S, value).

24.2.4.18 Set.prototype [ %Symbol.iterator% ] ( )

%Symbol.iterator% 프로퍼티 초기 값은 24.2.4.17에 정의된 %Set.prototype.values% 이다.

24.2.4.19 Set.prototype [ %Symbol.toStringTag% ]

%Symbol.toStringTag% 프로퍼티 초기 값은 String "Set" 이다.

이 프로퍼티 특성은 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }.

24.2.5 Set 인스턴스의 프로퍼티

Set 인스턴스는 일반 객체이며 Set 프로토타입 객체로부터 프로퍼티를 상속한다. 또한 [[SetData]] 내부 슬롯을 가진다.

24.2.6 Set 이터레이터 객체

Set Iterator 는 아래 정의된 구조를 가지며 특정 Set 인스턴스 객체에 대한 특정 순회를 나타내는 일반 객체이다. Set Iterator 객체에 대한 이름 있는 생성자는 없다. 대신 Set 인스턴스 객체의 특정 메서드를 호출하여 생성된다.

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 Generator 또는 throw completion. Set 메서드 중 그러한 이터레이터를 반환하는 것들이 사용할 이터레이터 객체를 생성한다. It performs the following steps when called:

  1. RequireInternalSlot(set, [[SetData]]) 수행.
  2. closure 를 매개변수 없고 set, kind 를 캡처하며 호출 시 다음 단계를 수행하는 새 추상 클로저로 둔다:
    1. index = 0.
    2. entries = set.[[SetData]].
    3. numEntries = entries 요소 수.
    4. 반복, index < numEntries 동안
      1. e = entries[index].
      2. index = index + 1.
      3. eempty 이면
        1. kind = key+value 이면
          1. result = CreateArrayFromListe, e »).
          2. GeneratorYield(CreateIteratorResultObject(result, false)) 수행.
        2. Else
          1. Assert: kind = value.
          2. GeneratorYield(CreateIteratorResultObject(e, false)) 수행.
        3. NOTE: GeneratorYield 로 일시 중단된 동안 entries 요소 수가 증가할 수 있다.
        4. numEntries = entries 요소 수로 재설정.
    5. Return NormalCompletion(unused).
  3. Return CreateIteratorFromClosure(closure, "%SetIteratorPrototype%", %SetIteratorPrototype%).

24.2.6.2 %SetIteratorPrototype% 객체

%SetIteratorPrototype% 객체:

24.2.6.2.1 %SetIteratorPrototype%.next ( )

  1. Return ? GeneratorResume(this value, empty, "%SetIteratorPrototype%").

24.2.6.2.2 %SetIteratorPrototype% [ %Symbol.toStringTag% ]

%Symbol.toStringTag% 프로퍼티 초기 값은 String "Set Iterator" 이다.

이 프로퍼티 특성은 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }.

24.3 WeakMap 객체

WeakMap 은 키가 객체 및/또는 심볼이고 값이 임의의 ECMAScript 언어 값일 수 있는 키/값 쌍의 컬렉션이다. WeakMap 은 특정 키를 가진 키/값 쌍이 포함되는지 질의할 수 있지만, 보유한 키/값 쌍을 열거하는 메커니즘은 제공되지 않는다. 특정 조건에서, live 가 아닌 값들은 9.9.3 에 설명된 바와 같이 WeakMap 키로서 제거된다.

구현은 WeakMap 의 키/값 쌍이 더 이상 접근 불가능(inaccessible) 해진 시점과 그 키/값 쌍이 WeakMap 에서 제거되는 시점 사이에 임의로 결정된 지연(latency)을 부과할 수 있다. 이 지연이 ECMAScript 프로그램에 관측 가능하다면 프로그램 실행에 영향을 줄 수 있는 불확정성의 원천이 될 것이다. 이러한 이유로 ECMAScript 구현은 관찰자가 관찰하려는 키를 제시하지 않고 WeakMap 의 키를 관찰할 수 있는 어떤 수단도 제공해서는 안 된다.

WeakMap 은 평균적으로 컬렉션의 키/값 쌍 수에 대해 준선형 접근 시간을 제공하는 해시 테이블 또는 다른 메커니즘으로 구현되어야 한다. 명세에서 사용하는 자료 구조는 WeakMap 의 요구되는 관측 가능 의미를 설명하기 위한 것이며 실제 구현 모델을 의도하지 않는다.

Note

WeakMap 과 WeakSet 은 WeakMap 또는 WeakSet 인스턴스가 없었다면 해당 객체 혹은 심볼이 접근 불가능해져서 구현의 가비지 컬렉션 메커니즘에 의해 자원 회수 대상이 되었을 경우 메모리 자원을 “누출”하지 않는 방식으로 객체나 심볼에 상태를 동적으로 연관시키기 위한 메커니즘을 제공하기 위해 설계되었다. 이 특성은 WeakMap 또는 WeakSet 인스턴스에서 키로 객체/심볼을 역으로 매핑(inverted per-object/symbol mapping)하는 방식으로 달성할 수 있다. 또는 각 WeakMap/WeakSet 인스턴스가 내부적으로 키와 값 데이터를 저장할 수도 있으나 이 방식은 구현과 가비지 컬렉터 사이의 협조가 필요하다. 다음 참조들은 WeakMap 과 WeakSet 구현에 유용할 수 있는 메커니즘을 설명한다:

Barry Hayes. 1997. Ephemerons: a new finalization mechanism. In Proceedings of the 12th ACM SIGPLAN conference on Object-oriented programming, systems, languages, and applications (OOPSLA '97), A. Michael Berman (Ed.). ACM, New York, NY, USA, 176-183, http://doi.acm.org/10.1145/263698.263733.

Alexandra Barros, Roberto Ierusalimschy, Eliminating Cycles in Weak Tables. Journal of Universal Computer Science - J.UCS, vol. 14, no. 21, pp. 3481-3497, 2008, http://www.jucs.org/jucs_14_21/eliminating_cycles_in_weak

24.3.1 WeakMap 생성자

WeakMap 생성자:

  • %WeakMap% 이다.
  • 전역 객체"WeakMap" 프로퍼티 초기 값이다.
  • 생성자로 호출될 때 새 WeakMap 을 생성·초기화한다.
  • 함수로 호출하도록 의도되지 않았으며 그렇게 호출하면 예외를 던진다.
  • 클래스 정의의 extends 절 값으로 사용할 수 있다. 지정된 WeakMap 동작을 상속하려는 서브클래스 생성자WeakMap.prototype 내장 메서드를 지원하는 데 필요한 내부 상태로 서브클래스 인스턴스를 생성·초기화하기 위해 WeakMap 생성자에 대한 super 호출을 포함해야 한다.

24.3.1.1 WeakMap ( [ iterable ] )

이 함수는 호출 시 다음 단계를 수행한다:

  1. NewTarget 이 undefined 이면 TypeError 예외.
  2. map = ? OrdinaryCreateFromConstructor(NewTarget, "%WeakMap.prototype%", « [[WeakMapData]] »).
  3. map.[[WeakMapData]] 를 새 빈 List 로 설정.
  4. iterableundefined 또는 null 이면 map 반환.
  5. adder = ? Get(map, "set").
  6. IsCallable(adder) false 이면 TypeError 예외.
  7. Return ? AddEntriesFromIterable(map, iterable, adder).
Note

매개변수 iterable 이 존재하면 첫 요소가 WeakMap 키로 사용될 값이고 두 번째 요소가 그 키에 연결할 값인 2-요소 배열 유사 객체를 생성하는 이터레이터 객체를 반환하는 %Symbol.iterator% 메서드를 구현한 객체일 것으로 기대된다.

24.3.2 WeakMap 생성자의 프로퍼티

WeakMap 생성자:

  • 값이 %Function.prototype%[[Prototype]] 내부 슬롯을 가진다.
  • 다음 프로퍼티를 가진다:

24.3.2.1 WeakMap.prototype

WeakMap.prototype 의 초기 값은 WeakMap 프로토타입 객체이다.

이 프로퍼티는 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false } 특성을 가진다.

24.3.3 WeakMap 프로토타입 객체의 프로퍼티

WeakMap 프로토타입 객체는:

  • %WeakMap.prototype% 이다.
  • 값이 %Object.prototype%[[Prototype]] 내부 슬롯을 가진다.
  • 일반 객체이다.
  • [[WeakMapData]] 내부 슬롯을 가지지 않는다.

24.3.3.1 WeakMap.prototype.constructor

WeakMap.prototype.constructor 의 초기 값은 %WeakMap% 이다.

24.3.3.2 WeakMap.prototype.delete ( key )

이 메서드는 호출 시 다음 단계를 수행한다:

  1. M = this 값.
  2. RequireInternalSlot(M, [[WeakMapData]]) 수행.
  3. CanBeHeldWeakly(key) false 이면 false 반환.
  4. M.[[WeakMapData]] 의 각 Record { [[Key]], [[Value]] } p 에 대해
    1. p.[[Key]]empty 그리고 SameValue(p.[[Key]], key) = true 이면
      1. p.[[Key]] = empty.
      2. p.[[Value]] = empty.
      3. true 반환.
  5. false 반환.
Note

empty 는 엔트리가 삭제되었음을 나타내는 명세 기법이다. 실제 구현은 엔트리를 내부 자료 구조에서 물리적으로 제거하는 등의 다른 동작을 할 수 있다.

24.3.3.3 WeakMap.prototype.get ( key )

이 메서드는 호출 시 다음 단계를 수행한다:

  1. M = this 값.
  2. RequireInternalSlot(M, [[WeakMapData]]) 수행.
  3. CanBeHeldWeakly(key) false 이면 undefined 반환.
  4. M.[[WeakMapData]] 의 각 Record { [[Key]], [[Value]] } p 에 대해
    1. p.[[Key]]empty 그리고 SameValue(p.[[Key]], key) = true 이면 p.[[Value]] 반환.
  5. undefined 반환.

24.3.3.4 WeakMap.prototype.has ( key )

이 메서드는 호출 시 다음 단계를 수행한다:

  1. M = this 값.
  2. RequireInternalSlot(M, [[WeakMapData]]) 수행.
  3. CanBeHeldWeakly(key) false 이면 false 반환.
  4. M.[[WeakMapData]] 의 각 Record { [[Key]], [[Value]] } p 에 대해
    1. p.[[Key]]empty 그리고 SameValue(p.[[Key]], key) = true 이면 true 반환.
  5. false 반환.

24.3.3.5 WeakMap.prototype.set ( key, value )

이 메서드는 호출 시 다음 단계를 수행한다:

  1. M = this 값.
  2. RequireInternalSlot(M, [[WeakMapData]]) 수행.
  3. CanBeHeldWeakly(key) false 이면 TypeError 예외.
  4. M.[[WeakMapData]] 의 각 Record { [[Key]], [[Value]] } p 에 대해
    1. p.[[Key]]empty 그리고 SameValue(p.[[Key]], key) = true 이면
      1. p.[[Value]] = value.
      2. M 반환.
  5. p = Record { [[Key]]: key, [[Value]]: value }.
  6. pM.[[WeakMapData]] 에 append.
  7. M 반환.

24.3.3.6 WeakMap.prototype [ %Symbol.toStringTag% ]

%Symbol.toStringTag% 프로퍼티 초기 값은 String "WeakMap" 이다.

이 프로퍼티 특성은 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }.

24.3.4 WeakMap 인스턴스의 프로퍼티

WeakMap 인스턴스는 일반 객체이며 WeakMap 프로토타입 객체로부터 프로퍼티를 상속한다. 또한 [[WeakMapData]] 내부 슬롯을 가진다.

24.4 WeakSet 객체

WeakSet 은 객체 및/또는 심볼의 컬렉션이다. 하나의 고유 객체나 심볼은 WeakSet 컬렉션에서 한 번만 요소로 등장할 수 있다. WeakSet 은 특정 값을 포함하는지 질의할 수 있지만, 보유한 값을 열거하는 메커니즘은 제공되지 않는다. 특정 조건에서 live 가 아닌 값들은 9.9.3 에 설명된 바와 같이 WeakSet 요소로서 제거된다.

구현은 WeakSet 이 포함한 값이 접근 불가능하게 된 시점과 그 값이 WeakSet 에서 제거되는 시점 사이에 임의로 결정된 지연을 부과할 수 있다. 이 지연이 ECMAScript 프로그램에 관측 가능하다면 프로그램 실행에 영향을 줄 수 있는 불확정성의 원인이 된다. 이러한 이유로 ECMAScript 구현은 관찰자가 관찰된 값을 제시하지 않고 WeakSet 이 특정 값을 포함하는지 결정할 수 있는 수단을 제공해서는 안 된다.

WeakSet 은 평균적으로 컬렉션 요소 수에 대해 준선형 접근 시간을 제공하는 해시 테이블 또는 다른 메커니즘으로 구현되어야 한다. 명세에서 사용하는 자료 구조는 WeakSet 의 요구되는 관측 가능 의미를 설명하기 위한 것이며 실제 구현 모델을 의도하지 않는다.

Note

24.3 의 NOTE 참고.

24.4.1 WeakSet 생성자

WeakSet 생성자:

  • %WeakSet% 이다.
  • 전역 객체"WeakSet" 프로퍼티 초기 값이다.
  • 생성자로 호출될 때 새 WeakSet 을 생성·초기화한다.
  • 함수로 호출하도록 의도되지 않았으며 그렇게 호출하면 예외를 던진다.
  • 클래스 정의의 extends 절 값으로 사용할 수 있다. 지정된 WeakSet 동작을 상속하려는 서브클래스 생성자WeakSet.prototype 내장 메서드를 지원하는 데 필요한 내부 상태로 서브클래스 인스턴스를 생성·초기화하기 위해 WeakSet 생성자에 대한 super 호출을 포함해야 한다.

24.4.1.1 WeakSet ( [ iterable ] )

이 함수는 호출 시 다음 단계를 수행한다:

  1. NewTarget 이 undefined 이면 TypeError 예외.
  2. set = ? OrdinaryCreateFromConstructor(NewTarget, "%WeakSet.prototype%", « [[WeakSetData]] »).
  3. set.[[WeakSetData]] 를 새 빈 List 로 설정.
  4. iterableundefined 또는 null 이면 set 반환.
  5. adder = ? Get(set, "add").
  6. IsCallable(adder) false 이면 TypeError 예외.
  7. iteratorRecord = ? GetIterator(iterable, sync).
  8. 반복:
    1. next = ? IteratorStepValue(iteratorRecord).
    2. nextdone 이면 set 반환.
    3. status = Completion(Call(adder, set, « next »)).
    4. IfAbruptCloseIterator(status, iteratorRecord).

24.4.2 WeakSet 생성자의 프로퍼티

WeakSet 생성자:

  • 값이 %Function.prototype%[[Prototype]] 내부 슬롯을 가진다.
  • 다음 프로퍼티를 가진다:

24.4.2.1 WeakSet.prototype

WeakSet.prototype 의 초기 값은 WeakSet 프로토타입 객체이다.

이 프로퍼티는 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false } 특성을 가진다.

24.4.3 WeakSet 프로토타입 객체의 프로퍼티

WeakSet 프로토타입 객체는:

  • %WeakSet.prototype% 이다.
  • 값이 %Object.prototype%[[Prototype]] 내부 슬롯을 가진다.
  • 일반 객체이다.
  • [[WeakSetData]] 내부 슬롯을 가지지 않는다.

24.4.3.1 WeakSet.prototype.add ( value )

이 메서드는 호출 시 다음 단계를 수행한다:

  1. S = this 값.
  2. RequireInternalSlot(S, [[WeakSetData]]) 수행.
  3. CanBeHeldWeakly(value) false 이면 TypeError 예외.
  4. S.[[WeakSetData]] 의 각 요소 e 에 대해
    1. eempty 그리고 SameValue(e, value) = true 이면
      1. S 반환.
  5. valueS.[[WeakSetData]] 에 append.
  6. S 반환.

24.4.3.2 WeakSet.prototype.constructor

WeakSet.prototype.constructor 의 초기 값은 %WeakSet% 이다.

24.4.3.3 WeakSet.prototype.delete ( value )

이 메서드는 호출 시 다음 단계를 수행한다:

  1. S = this 값.
  2. RequireInternalSlot(S, [[WeakSetData]]) 수행.
  3. CanBeHeldWeakly(value) false 이면 false 반환.
  4. S.[[WeakSetData]] 의 각 요소 e 에 대해
    1. eempty 그리고 SameValue(e, value) = true 이면
      1. 값이 eS.[[WeakSetData]] 요소를 값이 empty 인 요소로 교체.
      2. true 반환.
  5. false 반환.
Note

empty 는 엔트리가 삭제되었음을 나타내는 명세 기법이다. 실제 구현은 내부 자료 구조에서 물리적으로 제거하는 등의 다른 동작을 할 수 있다.

24.4.3.4 WeakSet.prototype.has ( value )

이 메서드는 호출 시 다음 단계를 수행한다:

  1. S = this 값.
  2. RequireInternalSlot(S, [[WeakSetData]]) 수행.
  3. CanBeHeldWeakly(value) false 이면 false 반환.
  4. S.[[WeakSetData]] 의 각 요소 e 에 대해
    1. eempty 그리고 SameValue(e, value) = true 이면 true 반환.
  5. false 반환.

24.4.3.5 WeakSet.prototype [ %Symbol.toStringTag% ]

%Symbol.toStringTag% 프로퍼티 초기 값은 String "WeakSet" 이다.

이 프로퍼티 특성은 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }.

24.4.4 WeakSet 인스턴스의 프로퍼티

WeakSet 인스턴스는 일반 객체이며 WeakSet 프로토타입 객체로부터 프로퍼티를 상속한다. 또한 [[WeakSetData]] 내부 슬롯을 가진다.

24.5 키드 컬렉션을 위한 추상 연산

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 구조화된 데이터 (Structured Data)

25.1 ArrayBuffer 객체

25.1.1 표기 (Notation)

본 절, 25.4, 그리고 29 에서의 아래 설명들은 read-modify-write 수정 함수 내부 데이터 구조를 사용한다.

read-modify-write 수정 함수란 두 개의 바이트 값 List 를 인수로 받고 바이트 값 List 를 반환하는 추상 클로저로 표현되는 수학적 함수이다. 이러한 추상 클로저는 다음 모든 성질을 만족한다:

  • 알고리즘 단계 전부를 원자적으로 수행한다.
  • 개별 알고리즘 단계는 관측 불가능하다.
Note

read-modify-write 수정 함수의 알고리즘 단계가 순수한 수학적 함수임을 검증하는 데 도움을 주기 위해 다음 편집 지침을 권장한다:

  • 직접 또는 호출된 추상 연산과 추상 클로저를 통한 간접 접근을 포함하여, 매개변수와 캡처된 값 외의 어떤 언어/명세 값에도 접근하지 않는다.
  • Completion Record 를 반환하는 추상 연산이나 추상 클로저를 직접 또는 간접으로 호출하지 않는다.
  • Completion Record 를 반환하지 않는다.

25.1.2 고정 길이 및 크기 변경 가능(ArrayBuffer) 객체

fixed-length ArrayBuffer 는 생성 후 바이트 길이가 변하지 않는 ArrayBuffer 이다.

resizable ArrayBufferArrayBuffer.prototype.resize ( newLength ) 호출을 통해 생성 후 바이트 길이가 변할 수 있는 ArrayBuffer 이다.

어떤 종류의 ArrayBuffer 객체가 생성되는지는 ArrayBuffer ( length [ , options ] ) 에 전달된 인수에 따라 결정된다.

25.1.3 ArrayBuffer 객체를 위한 추상 연산

25.1.3.1 AllocateArrayBuffer ( constructor, byteLength [ , maxByteLength ] )

The abstract operation AllocateArrayBuffer takes arguments constructor (a constructor) and byteLength (a non-negative integer) and optional argument maxByteLength (a non-negative integer or empty) and returns ArrayBuffer 를 포함하는 정상 완료 또는 throw completion. ArrayBuffer 를 생성하는 데 사용된다. It performs the following steps when called:

  1. slots = « [[ArrayBufferData]], [[ArrayBufferByteLength]], [[ArrayBufferDetachKey]] ».
  2. maxByteLength 가 존재하고 empty 가 아니면 allocatingResizableBuffer = true; 그렇지 않으면 false.
  3. allocatingResizableBuffer = true 이면
    1. byteLength > maxByteLength 이면 RangeError 예외.
    2. slots[[ArrayBufferMaxByteLength]] 추가.
  4. obj = ? OrdinaryCreateFromConstructor(constructor, "%ArrayBuffer.prototype%", slots).
  5. block = ? CreateByteDataBlock(byteLength).
  6. obj.[[ArrayBufferData]] = block.
  7. obj.[[ArrayBufferByteLength]] = byteLength.
  8. allocatingResizableBuffer = true 이면
    1. 길이가 maxByteLength 바이트인 Data Block block 을 생성할 수 없다면 RangeError 예외.
    2. NOTE: Resizable ArrayBuffer 는 제자리(in-place) 증가로 구현 가능하도록 설계되었다. 예를 들어 가상 메모리를 미리 예약할 수 없는 경우 구현은 예외를 던질 수 있다.
    3. obj.[[ArrayBufferMaxByteLength]] = maxByteLength.
  9. obj 반환.

25.1.3.2 ArrayBufferByteLength ( arrayBuffer, order )

The abstract operation ArrayBufferByteLength takes arguments arrayBuffer (an ArrayBuffer or SharedArrayBuffer) and order (seq-cst or unordered) and returns 음이 아닌 정수. It performs the following steps when called:

  1. IsSharedArrayBuffer(arrayBuffer) = true 그리고 arrayBuffer[[ArrayBufferByteLengthData]] 내부 슬롯을 가지면
    1. bufferByteLengthBlock = arrayBuffer.[[ArrayBufferByteLengthData]].
    2. rawLength = GetRawBytesFromSharedBlock(bufferByteLengthBlock, 0, biguint64, true, order).
    3. isLittleEndian = 주변 에이전트의 Agent Record[[LittleEndian]] 필드 값.
    4. Return (RawBytesToNumeric(biguint64, rawLength, isLittleEndian)).
  2. Assert: IsDetachedBuffer(arrayBuffer) = false.
  3. Return arrayBuffer.[[ArrayBufferByteLength]].

25.1.3.3 ArrayBufferCopyAndDetach ( arrayBuffer, newLength, preserveResizability )

The abstract operation ArrayBufferCopyAndDetach takes arguments arrayBuffer (an ECMAScript language value), newLength (an ECMAScript language value), and preserveResizability (preserve-resizability or fixed-length) and returns ArrayBuffer 를 포함하는 정상 완료 또는 throw completion. It performs the following steps when called:

  1. RequireInternalSlot(arrayBuffer, [[ArrayBufferData]]) 수행.
  2. IsSharedArrayBuffer(arrayBuffer) = true 이면 TypeError 예외.
  3. newLengthundefined 이면
    1. newByteLength = arrayBuffer.[[ArrayBufferByteLength]].
  4. Else
    1. newByteLength = ? ToIndex(newLength).
  5. IsDetachedBuffer(arrayBuffer) = true 이면 TypeError 예외.
  6. preserveResizability = preserve-resizability 그리고 IsFixedLengthArrayBuffer(arrayBuffer) = false 이면
    1. newMaxByteLength = arrayBuffer.[[ArrayBufferMaxByteLength]].
  7. Else
    1. newMaxByteLength = empty.
  8. arrayBuffer.[[ArrayBufferDetachKey]]undefined 이면 TypeError 예외.
  9. newBuffer = ? AllocateArrayBuffer(%ArrayBuffer%, newByteLength, newMaxByteLength).
  10. copyLength = min(newByteLength, arrayBuffer.[[ArrayBufferByteLength]]).
  11. fromBlock = arrayBuffer.[[ArrayBufferData]].
  12. toBlock = newBuffer.[[ArrayBufferData]].
  13. CopyDataBlockBytes(toBlock, 0, fromBlock, 0, copyLength) 수행.
  14. NOTE: 새 Data Block 생성과 구 Data Block 으로부터의 복사는 관측 불가능하다. 구현은 zero-copy 이동 또는 realloc 으로 최적화할 수 있다.
  15. DetachArrayBuffer(arrayBuffer) 수행.
  16. newBuffer 반환.

25.1.3.4 IsDetachedBuffer ( arrayBuffer )

The abstract operation IsDetachedBuffer takes argument arrayBuffer (an ArrayBuffer or a 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 (an ArrayBuffer) and optional argument key (anything) and returns unused 를 포함하는 정상 완료 또는 throw completion. It performs the following steps when called:

  1. Assert: IsSharedArrayBuffer(arrayBuffer) = false.
  2. key 가 존재하지 않으면 key = undefined.
  3. arrayBuffer.[[ArrayBufferDetachKey]]key 이면 TypeError 예외.
  4. arrayBuffer.[[ArrayBufferData]] = null.
  5. arrayBuffer.[[ArrayBufferByteLength]] = 0.
  6. unused 반환.
Note

ArrayBuffer 인스턴스를 분리(detach)하면 그 인스턴스가 사용하던 Data Block 과의 연결이 끊어지고 버퍼의 바이트 길이는 0이 된다.

25.1.3.6 CloneArrayBuffer ( srcBuffer, srcByteOffset, srcLength )

The abstract operation CloneArrayBuffer takes arguments srcBuffer (an ArrayBuffer or a SharedArrayBuffer), srcByteOffset (a non-negative integer), and srcLength (a non-negative integer) and returns ArrayBuffer 를 포함하는 정상 완료 또는 throw completion. srcByteOffset 부터 srcLength 바이트 범위의 srcBuffer 데이터를 복사한 새 ArrayBuffer 를 생성한다. It performs the following steps when called:

  1. Assert: IsDetachedBuffer(srcBuffer) = false.
  2. targetBuffer = ? AllocateArrayBuffer(%ArrayBuffer%, srcLength).
  3. srcBlock = srcBuffer.[[ArrayBufferData]].
  4. targetBlock = targetBuffer.[[ArrayBufferData]].
  5. CopyDataBlockBytes(targetBlock, 0, srcBlock, srcByteOffset, srcLength) 수행.
  6. targetBuffer 반환.

25.1.3.7 GetArrayBufferMaxByteLengthOption ( options )

The abstract operation GetArrayBufferMaxByteLengthOption takes argument options (an ECMAScript language value) and returns 음이 아닌 정수 또는 empty 를 포함하는 정상 완료, 또는 throw completion. It performs the following steps when called:

  1. options 가 Object 가 아니면 empty 반환.
  2. maxByteLength = ? Get(options, "maxByteLength").
  3. maxByteLength = undefined 이면 empty 반환.
  4. Return ? 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 handled 또는 unhandled 를 포함하는 정상 완료, 또는 throw completion. 호스트buffer 에 대한 구현 정의 크기 조정을 수행할 기회를 제공한다. 크기 조정을 처리하지 않으려면 기본 동작을 위해 unhandled 를 반환할 수 있다.

HostResizeArrayBuffer 구현은 다음 요구사항을 준수해야 한다:

  • buffer 를 분리(detach)하지 않는다.
  • 정상 완료로 handled 를 반환하면 buffer.[[ArrayBufferByteLength]] = newByteLength 이다.

기본 구현은 NormalCompletion(unhandled) 를 반환한다.

25.1.3.9 IsFixedLengthArrayBuffer ( arrayBuffer )

The abstract operation IsFixedLengthArrayBuffer takes argument arrayBuffer (an ArrayBuffer or a 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 (a TypedArray element type) 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 (a TypedArray element type) and returns Boolean. 인수 typeuint8clamped 를 제외한 정수 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 (a TypedArray element type) 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 Boolean. It performs the following steps when called:

  1. IsUnclampedIntegerElementType(type) = true 이면 true 반환.
  2. IsBigIntElementType(type) = true 이고 orderinit, unordered 가 아니면 true 반환.
  3. false 반환.

25.1.3.14 RawBytesToNumeric ( type, rawBytes, isLittleEndian )

The abstract operation RawBytesToNumeric takes arguments type (a TypedArray element type), rawBytes (a List of byte values), and isLittleEndian (a Boolean) and returns Number 또는 BigInt. It performs the following steps when called:

  1. elementSize = Table 73 에서 요소 타입 type 에 대해 지정된 Element Size 값.
  2. isLittleEndian = false 이면 rawBytes 요소 순서를 반전.
  3. type = float16 이면
    1. value = rawBytes 바이트들을 이어 붙인 후 little-endian 비트열로 해석한 IEEE 754-2019 binary16 값.
    2. value 가 NaN 이면 NaN 반환.
    3. value 에 해당하는 Number 값 반환.
  4. type = float32 이면
    1. (동일 절차, binary32) → NaN 처리 동일.
  5. type = float64 이면
    1. (동일 절차, binary64) → NaN 처리 동일.
  6. IsUnsignedElementType(type) = true 이면
    1. intValue = rawBytes 바이트들을 이어 붙여 해석한 unsigned little-endian 이진 수.
  7. Else
    1. intValue = rawBytes 바이트들을 이어 붙여 해석한 길이 (elementSize × 8) 비트의 little-endian 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 (a Shared Data Block), byteIndex (a non-negative integer), type (a TypedArray element type), isTypedArray (a Boolean), and order (seq-cst or unordered) and returns 바이트 값 List. It performs the following steps when called:

  1. elementSize = Table 73 에서 요소 타입 type 의 Element Size 값.
  2. execution = 주변 에이전트의 Agent Record[[CandidateExecution]] 필드.
  3. eventsRecord = execution.[[EventsRecords]][[AgentSignifier]] = AgentSignifier() 인 Agent Events Record.
  4. isTypedArray = true 그리고 IsNoTearConfiguration(type, order) = true 이면 noTear = true, 아니면 false.
  5. rawValue = 길이 elementSize 이고 요소가 비결정적으로 선택된 바이트 값인 List.
  6. NOTE: 구현에서 rawValue 는 하드웨어의 비원자/원자 읽기 결과이다. 비결정성은 약한 일관성 하드웨어의 관측 가능 동작을 기술하기 위한 의미적 규정이다.
  7. readEvent = ReadSharedMemory { [[Order]]: order, [[NoTear]]: noTear, [[Block]]: block, [[ByteIndex]]: byteIndex, [[ElementSize]]: elementSize }.
  8. eventsRecord.[[EventList]]readEvent 추가.
  9. execution.[[ChosenValues]]Chosen Value Record { [[Event]]: readEvent, [[ChosenValue]]: rawValue } 추가.
  10. rawValue 반환.

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

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

  1. Assert: IsDetachedBuffer(arrayBuffer) = false.
  2. Assert: byteIndex 에서 시작하여 type 값을 표현하기에 충분한 바이트가 존재.
  3. block = arrayBuffer.[[ArrayBufferData]].
  4. elementSize = Table 73 에서 type 의 Element Size.
  5. IsSharedArrayBuffer(arrayBuffer) = true 이면
    1. Assert: blockShared Data Block.
    2. rawValue = GetRawBytesFromSharedBlock(block, byteIndex, type, isTypedArray, order).
  6. Else
    1. rawValue = block 에서 [byteIndex, byteIndex + elementSize) 구간의 바이트 List.
  7. Assert: rawValue 길이 = elementSize.
  8. isLittleEndian 미지정이면 주변 에이전트 Agent Record[[LittleEndian]] 값으로 설정.
  9. Return RawBytesToNumeric(type, rawValue, isLittleEndian).

25.1.3.17 NumericToRawBytes ( type, value, isLittleEndian )

The abstract operation NumericToRawBytes takes arguments type (a TypedArray element type), value (a Number or a BigInt), and isLittleEndian (a Boolean) and returns 바이트 값 List. It performs the following steps when called:

  1. type = float16 이면
    1. rawBytes = value 를 roundTiesToEven 방식으로 IEEE 754-2019 binary16 형식으로 변환한 2바이트 List (little endian). valueNaN 이면 구현이 선택한 binary16 NaN 인코딩(구현 구분 가능한 동일 NaN 에 대해 항상 동일 인코딩)을 사용.
  2. Else if type = float32
    1. (동일, 4바이트 binary32)
  3. Else if type = float64
    1. (동일, 8바이트 binary64)
  4. Else
    1. n = Table 73 에서 type 의 Element Size.
    2. conversionOperation = Table 73 변환 연산 열의 type 에 해당하는 추상 연산.
    3. intValue = (! conversionOperation(value)).
    4. intValue ≥ 0 이면
      1. rawBytes = intValuen 바이트 이진 인코딩 (little endian).
    5. Else
      1. rawBytes = intValuen 바이트 2의 보수 이진 인코딩 (little endian).
  5. isLittleEndian = false 이면 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 값을 표현하기 충분한 바이트 존재.
  3. Assert: IsBigIntElementType(type) = true 이면 value 는 BigInt; 아니면 Number.
  4. block = arrayBuffer.[[ArrayBufferData]].
  5. elementSize = Table 73 에서 type 의 Element Size.
  6. isLittleEndian 미지정이면 주변 에이전트 Agent Record[[LittleEndian]] 값으로 설정.
  7. rawBytes = NumericToRawBytes(type, value, isLittleEndian).
  8. IsSharedArrayBuffer(arrayBuffer) = true 이면
    1. execution = 주변 에이전트 Agent Record[[CandidateExecution]].
    2. eventsRecord = execution.[[EventsRecords]] 중 현재 AgentSignifier() 와 일치하는 것.
    3. isTypedArray = true 그리고 IsNoTearConfiguration(type, order) = true 이면 noTear = true; 아니면 false.
    4. WriteSharedMemory { [[Order]]: order, [[NoTear]]: noTear, [[Block]]: block, [[ByteIndex]]: byteIndex, [[ElementSize]]: elementSize, [[Payload]]: rawBytes } 를 eventsRecord.[[EventList]] 에 추가.
  9. Else
    1. rawBytes 개별 바이트를 block[byteIndex] 부터 순서대로 저장.
  10. unused 반환.

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

The abstract operation GetModifySetValueInBuffer takes arguments arrayBuffer (an ArrayBuffer or a SharedArrayBuffer), byteIndex (a non-negative integer), type (a TypedArray element type), value (a Number or a BigInt), and op (a read-modify-write modification function) and returns Number 또는 BigInt. It performs the following steps when called:

  1. Assert: IsDetachedBuffer(arrayBuffer) = false.
  2. Assert: byteIndex 에서 시작하여 type 값을 표현하기 충분한 바이트 존재.
  3. Assert: IsBigIntElementType(type) = true 이면 value 는 BigInt; 아니면 Number.
  4. block = arrayBuffer.[[ArrayBufferData]].
  5. elementSize = Table 73 에서 type 의 Element Size.
  6. isLittleEndian = 주변 에이전트 Agent Record[[LittleEndian]] 값.
  7. rawBytes = NumericToRawBytes(type, value, isLittleEndian).
  8. IsSharedArrayBuffer(arrayBuffer) = true 이면
    1. execution = 주변 에이전트 Agent Record[[CandidateExecution]].
    2. eventsRecord = execution.[[EventsRecords]] 중 현재 AgentSignifier() 에 해당하는 것.
    3. rawBytesRead = 길이 elementSize 인, 비결정적으로 선택된 바이트 값 List.
    4. NOTE: 구현에서 rawBytesRead 는 하드웨어의 load-link / load-exclusive / read-modify-write 명령의 피연산자 결과. 비결정성은 약한 일관성 하드웨어의 관측 가능 행위를 기술.
    5. rmwEvent = ReadModifyWriteSharedMemory { [[Order]]: seq-cst, [[NoTear]]: true, [[Block]]: block, [[ByteIndex]]: byteIndex, [[ElementSize]]: elementSize, [[Payload]]: rawBytes, [[ModifyOp]]: op }.
    6. eventsRecord.[[EventList]]rmwEvent 추가.
    7. execution.[[ChosenValues]]Chosen Value Record { [[Event]]: rmwEvent, [[ChosenValue]]: rawBytesRead } 추가.
  9. Else
    1. rawBytesRead = 길이 elementSize 인 바이트 시퀀스 (block[byteIndex] 부터).
    2. rawBytesModified = op(rawBytesRead, rawBytes).
    3. rawBytesModified 바이트를 block[byteIndex] 부터 저장.
  10. Return RawBytesToNumeric(type, rawBytesRead, isLittleEndian).

25.1.4 ArrayBuffer 생성자

ArrayBuffer 생성자:

  • %ArrayBuffer% 이다.
  • 전역 객체 "ArrayBuffer" 프로퍼티의 초기 값이다.
  • 생성자로 호출될 때 새 ArrayBuffer 를 생성·초기화한다.
  • 함수로 호출하도록 의도되지 않았으며 그렇게 호출하면 예외를 던진다.
  • 클래스 정의 extends 절의 값으로 사용할 수 있다. 지정된 ArrayBuffer 동작을 상속하려면 서브클래스 생성자ArrayBuffer.prototype 내장 메서드 지원에 필요한 내부 상태로 서브클래스 인스턴스를 생성·초기화하기 위해 ArrayBuffer 생성자에 대한 super 호출을 포함해야 한다.

25.1.4.1 ArrayBuffer ( length [ , options ] )

이 함수는 호출 시 다음 단계를 수행한다:

  1. NewTarget 이 undefined 이면 TypeError 예외.
  2. byteLength = ? ToIndex(length).
  3. requestedMaxByteLength = ? GetArrayBufferMaxByteLengthOption(options).
  4. Return ? AllocateArrayBuffer(NewTarget, byteLength, requestedMaxByteLength).

25.1.5 ArrayBuffer 생성자의 프로퍼티

ArrayBuffer 생성자:

  • 값이 %Function.prototype%[[Prototype]] 내부 슬롯을 가진다.
  • 다음 프로퍼티를 가진다:

25.1.5.1 ArrayBuffer.isView ( arg )

이 함수는 호출 시 다음 단계를 수행한다:

  1. arg 가 Object 가 아니면 false 반환.
  2. arg[[ViewedArrayBuffer]] 내부 슬롯을 가지면 true 반환.
  3. false 반환.

25.1.5.2 ArrayBuffer.prototype

ArrayBuffer.prototype 의 초기 값은 ArrayBuffer 프로토타입 객체이다.

이 프로퍼티 특성은 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }.

25.1.5.3 get ArrayBuffer [ %Symbol.species% ]

ArrayBuffer[%Symbol.species%] 는 set 접근자 함수가 undefined접근자 프로퍼티이다. 그 get 접근자 함수는 호출 시 다음을 수행한다:

  1. this 값 반환.

이 함수의 "name" 프로퍼티 값은 "get [Symbol.species]" 이다.

Note

ArrayBuffer.prototype.slice ( start, end ) 는 보통 자신의 this 값의 생성자를 사용해 파생 객체를 생성한다. 그러나 서브클래스 생성자%Symbol.species% 재정의를 통해 ArrayBuffer.prototype.slice ( start, end ) 메서드에 대한 기본 동작을 변경할 수 있다.

25.1.6 ArrayBuffer 프로토타입 객체의 프로퍼티

ArrayBuffer 프로토타입 객체:

  • %ArrayBuffer.prototype% 이다.
  • 값이 %Object.prototype%[[Prototype]] 내부 슬롯을 가진다.
  • 일반 객체이다.
  • [[ArrayBufferData]] 또는 [[ArrayBufferByteLength]] 내부 슬롯을 가지지 않는다.

25.1.6.1 get ArrayBuffer.prototype.byteLength

ArrayBuffer.prototype.byteLength 는 set 접근자 함수가 undefined접근자 프로퍼티이다. 그 get 접근자 함수는 호출 시 다음 단계를 수행한다:

  1. O = this 값.
  2. RequireInternalSlot(O, [[ArrayBufferData]]) 수행.
  3. IsSharedArrayBuffer(O) = true 이면 TypeError 예외.
  4. IsDetachedBuffer(O) = true 이면 +0𝔽 반환.
  5. length = O.[[ArrayBufferByteLength]].
  6. 𝔽(length) 반환.

25.1.6.2 ArrayBuffer.prototype.constructor

ArrayBuffer.prototype.constructor 의 초기 값은 %ArrayBuffer% 이다.

25.1.6.3 get ArrayBuffer.prototype.detached

ArrayBuffer.prototype.detached 는 set 접근자 함수가 undefined접근자 프로퍼티이다. 그 get 접근자 함수는 호출 시 다음 단계를 수행한다:

  1. O = this 값.
  2. RequireInternalSlot(O, [[ArrayBufferData]]) 수행.
  3. IsSharedArrayBuffer(O) = true 이면 TypeError 예외.
  4. Return IsDetachedBuffer(O).

25.1.6.4 get ArrayBuffer.prototype.maxByteLength

ArrayBuffer.prototype.maxByteLength 는 set 접근자 함수가 undefined접근자 프로퍼티이다. 그 get 접근자 함수는 호출 시 다음 단계를 수행한다:

  1. O = this 값.
  2. RequireInternalSlot(O, [[ArrayBufferData]]) 수행.
  3. IsSharedArrayBuffer(O) = true 이면 TypeError 예외.
  4. IsDetachedBuffer(O) = true 이면 +0𝔽 반환.
  5. IsFixedLengthArrayBuffer(O) = true 이면
    1. length = O.[[ArrayBufferByteLength]].
  6. Else
    1. length = O.[[ArrayBufferMaxByteLength]].
  7. 𝔽(length) 반환.

25.1.6.5 get ArrayBuffer.prototype.resizable

ArrayBuffer.prototype.resizable 는 set 접근자 함수가 undefined접근자 프로퍼티이다. 그 get 접근자 함수는 호출 시 다음 단계를 수행한다:

  1. O = this 값.
  2. RequireInternalSlot(O, [[ArrayBufferData]]) 수행.
  3. IsSharedArrayBuffer(O) = true 이면 TypeError 예외.
  4. IsFixedLengthArrayBuffer(O) = false 이면 true 반환; 아니면 false 반환.

25.1.6.6 ArrayBuffer.prototype.resize ( newLength )

이 메서드는 호출 시 다음 단계를 수행한다:

  1. O = this 값.
  2. RequireInternalSlot(O, [[ArrayBufferMaxByteLength]]) 수행.
  3. IsSharedArrayBuffer(O) = true 이면 TypeError 예외.
  4. newByteLength = ? ToIndex(newLength).
  5. IsDetachedBuffer(O) = true 이면 TypeError 예외.
  6. newByteLength > O.[[ArrayBufferMaxByteLength]] 이면 RangeError 예외.
  7. hostHandled = ? HostResizeArrayBuffer(O, newByteLength).
  8. hostHandled = handled 이면 undefined 반환.
  9. oldBlock = O.[[ArrayBufferData]].
  10. newBlock = ? CreateByteDataBlock(newByteLength).
  11. copyLength = min(newByteLength, O.[[ArrayBufferByteLength]]).
  12. CopyDataBlockBytes(newBlock, 0, oldBlock, 0, copyLength) 수행.
  13. NOTE: 새 Data Block 생성과 복사는 관측 불가능하며, 구현은 제자리 증가/축소로 구현할 수 있다.
  14. O.[[ArrayBufferData]] = newBlock.
  15. O.[[ArrayBufferByteLength]] = newByteLength.
  16. undefined 반환.

25.1.6.7 ArrayBuffer.prototype.slice ( start, end )

이 메서드는 호출 시 다음 단계를 수행한다:

  1. O = this 값.
  2. RequireInternalSlot(O, [[ArrayBufferData]]) 수행.
  3. IsSharedArrayBuffer(O) = true 이면 TypeError 예외.
  4. IsDetachedBuffer(O) = true 이면 TypeError 예외.
  5. len = O.[[ArrayBufferByteLength]].
  6. relativeStart = ? ToIntegerOrInfinity(start).
  7. relativeStart = -∞ 이면 first = 0.
  8. Else if relativeStart < 0 이면 first = max(len + relativeStart, 0).
  9. Else first = min(relativeStart, len).
  10. end = undefined 이면 relativeEnd = len; 아니면 relativeEnd = ? ToIntegerOrInfinity(end).
  11. relativeEnd = -∞ 이면 final = 0.
  12. Else if relativeEnd < 0 이면 final = max(len + relativeEnd, 0).
  13. Else final = min(relativeEnd, len).
  14. newLen = max(final - first, 0).
  15. ctor = ? SpeciesConstructor(O, %ArrayBuffer%).
  16. new = ? Construct(ctor, « 𝔽(newLen) »).
  17. RequireInternalSlot(new, [[ArrayBufferData]]) 수행.
  18. IsSharedArrayBuffer(new) = true 이면 TypeError 예외.
  19. IsDetachedBuffer(new) = true 이면 TypeError 예외.
  20. SameValue(new, O) = true 이면 TypeError 예외.
  21. new.[[ArrayBufferByteLength]] < newLen 이면 TypeError 예외.
  22. NOTE: 위 단계의 부작용으로 O 가 분리 또는 크기 변경되었을 수 있다.
  23. IsDetachedBuffer(O) = true 이면 TypeError 예외.
  24. fromBuf = O.[[ArrayBufferData]].
  25. toBuf = new.[[ArrayBufferData]].
  26. currentLen = O.[[ArrayBufferByteLength]].
  27. first < currentLen 이면
    1. count = min(newLen, currentLen - first).
    2. CopyDataBlockBytes(toBuf, 0, fromBuf, first, count) 수행.
  28. new 반환.

25.1.6.8 ArrayBuffer.prototype.transfer ( [ newLength ] )

이 메서드는 호출 시 다음 단계를 수행한다:

  1. O = this 값.
  2. Return ? ArrayBufferCopyAndDetach(O, newLength, preserve-resizability).

25.1.6.9 ArrayBuffer.prototype.transferToFixedLength ( [ newLength ] )

이 메서드는 호출 시 다음 단계를 수행한다:

  1. O = this 값.
  2. Return ? ArrayBufferCopyAndDetach(O, newLength, fixed-length).

25.1.6.10 ArrayBuffer.prototype [ %Symbol.toStringTag% ]

%Symbol.toStringTag% 프로퍼티 초기 값은 String "ArrayBuffer" 이다.

이 프로퍼티 특성은 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }.

25.1.7 ArrayBuffer 인스턴스의 프로퍼티

ArrayBuffer 인스턴스는 ArrayBuffer 프로토타입 객체로부터 프로퍼티를 상속한다. 각 ArrayBuffer 인스턴스는 [[ArrayBufferData]], [[ArrayBufferByteLength]], [[ArrayBufferDetachKey]] 내부 슬롯을 갖는다. 크기 변경 가능한 인스턴스는 [[ArrayBufferMaxByteLength]] 내부 슬롯도 갖는다.

[[ArrayBufferData]]null 인 ArrayBuffer 인스턴스는 분리(detached)된 것으로 간주되며 해당 ArrayBuffer 내 데이터에 접근·수정하는 모든 연산은 실패한다.

[[ArrayBufferDetachKey]]undefined 가 아닌 값으로 설정된 ArrayBuffer 인스턴스는 DetachArrayBuffer 호출 시 동일 "detach key" 를 인수로 전달해야 하며, 그렇지 않으면 TypeError 가 발생한다. 이 내부 슬롯은 명세 알고리즘이 아닌 특정 임베딩 환경에서만 설정된다.

25.1.8 크기 변경 가능 ArrayBuffer 가이드라인

Note 1

다음은 크기 변경 가능 ArrayBuffer 를 사용하는 ECMAScript 프로그래머를 위한 지침이다.

가능하다면 배포 환경에서 프로그램을 테스트하는 것을 권장한다. 사용 가능한 물리 메모리 양은 하드웨어 장치마다 크게 다르다. 유사하게 가상 메모리 서브시스템 역시 하드웨어 및 운영체제에 따라 크게 다르다. 64비트 데스크톱 웹 브라우저에서 메모리 부족 없이 동작하는 애플리케이션이 32비트 모바일 웹 브라우저에서는 메모리를 소진할 수 있다.

크기 변경 가능 ArrayBuffer 의 "maxByteLength" 옵션 값을 선택할 때는 애플리케이션에 필요한 최소 가능한 값을 선택할 것을 권장한다. "maxByteLength" 가 1,073,741,824 (230 바이트, 1GiB) 를 초과하지 않도록 권장한다.

특정 최대 크기에 대해 크기 변경 가능 ArrayBuffer 를 성공적으로 생성했다 해서 이후 모든 크기 변경이 성공함을 보장하지 않는다.

Note 2

다음은 크기 변경 가능 ArrayBuffer 를 구현하는 ECMAScript 구현자들을 위한 지침이다.

Resizable ArrayBuffer 는 크기 변경 시 복사를 수행하거나, 가상 메모리를 미리 예약하는 제자리 증가(in-place growth), 또는 생성자 "maxByteLength" 값에 따라 양자의 혼합으로 구현될 수 있다.

호스트가 다중 테넌트(예: 동시에 여러 ECMAScript 애플리케이션 실행) 환경(웹 브라우저 등)이고 구현이 가상 메모리 예약을 통한 제자리 증가를 선택한다면, 32비트와 64비트 구현 모두에서 "maxByteLength" ≥ 1GiB~1.5GiB 값에 대해 예외를 던질 것을 권장한다. 이는 단일 애플리케이션이 가상 주소 공간을 고갈시킬 가능성과 상호 운용성 위험을 줄이기 위함이다.

호스트에 가상 메모리가 없거나(예: MMU 없는 임베디드 장치), 혹은 호스트가 복사 기반 크기 조정만 구현한다면 "maxByteLength" 옵션에 대해 임의의 Number value for 를 받을 수 있다. 하지만 요청된 크기의 메모리 블록을 절대 할당할 수 없다면 RangeError 를 던질 것을 권장한다(예: 요청 크기가 장치에서 사용 가능한 최대 메모리보다 큰 경우).

25.2 SharedArrayBuffer 객체

25.2.1 고정 길이 및 증가 가능(Growable) SharedArrayBuffer 객체

fixed-length SharedArrayBuffer 는 생성 후 바이트 길이가 변경될 수 없는 SharedArrayBuffer 이다.

growable SharedArrayBufferSharedArrayBuffer.prototype.grow ( newLength ) 호출을 통해 생성 후 바이트 길이가 증가할 수 있는 SharedArrayBuffer 이다.

생성되는 SharedArrayBuffer 객체의 종류는 SharedArrayBuffer ( length [ , options ] ) 에 전달되는 인수에 따라 결정된다.

25.2.2 SharedArrayBuffer 객체를 위한 추상 연산

25.2.2.1 AllocateSharedArrayBuffer ( constructor, byteLength [ , maxByteLength ] )

The abstract operation AllocateSharedArrayBuffer takes arguments constructor (a constructor) and byteLength (a non-negative integer) and optional argument maxByteLength (a non-negative integer or empty) and returns SharedArrayBuffer 를 포함하는 정상 완료 또는 throw completion. SharedArrayBuffer 를 생성하는 데 사용된다. It performs the following steps when called:

  1. slots = « [[ArrayBufferData]] ».
  2. maxByteLength 가 존재하고 empty 가 아니면 allocatingGrowableBuffer = true; 아니면 false.
  3. allocatingGrowableBuffer = true 이면
    1. byteLength > maxByteLength 이면 RangeError 예외.
    2. slots[[ArrayBufferByteLengthData]][[ArrayBufferMaxByteLength]] 추가.
  4. Else
    1. slots[[ArrayBufferByteLength]] 추가.
  5. obj = ? OrdinaryCreateFromConstructor(constructor, "%SharedArrayBuffer.prototype%", slots).
  6. allocatingGrowableBuffer = true 이면 allocLength = maxByteLength; 아니면 allocLength = byteLength.
  7. block = ? CreateSharedByteDataBlock(allocLength).
  8. obj.[[ArrayBufferData]] = block.
  9. allocatingGrowableBuffer = true 이면
    1. Assert: byteLengthmaxByteLength.
    2. byteLengthBlock = ? CreateSharedByteDataBlock(8).
    3. SetValueInBuffer(byteLengthBlock, 0, biguint64, (byteLength), true, seq-cst) 수행.
    4. obj.[[ArrayBufferByteLengthData]] = byteLengthBlock.
    5. obj.[[ArrayBufferMaxByteLength]] = maxByteLength.
  10. Else
    1. obj.[[ArrayBufferByteLength]] = byteLength.
  11. obj 반환.

25.2.2.2 IsSharedArrayBuffer ( obj )

The abstract operation IsSharedArrayBuffer takes argument obj (an ArrayBuffer or a SharedArrayBuffer) and returns Boolean. 객체가 ArrayBuffer, SharedArrayBuffer, 또는 그 서브타입인지 검사한다. It performs the following steps when called:

  1. bufferData = obj.[[ArrayBufferData]].
  2. bufferDatanull 이면 false 반환.
  3. bufferDataData Block 이면 false 반환.
  4. Assert: bufferDataShared Data Block.
  5. true 반환.

25.2.2.3 HostGrowSharedArrayBuffer ( buffer, newByteLength )

The host-defined abstract operation HostGrowSharedArrayBuffer takes arguments buffer (a SharedArrayBuffer) and newByteLength (a non-negative integer) and returns handled 또는 unhandled 를 포함하는 정상 완료 또는 throw completion. 호스트buffer 에 대해 구현 정의 증가(grow)를 수행할 기회를 제공한다. 처리하지 않으려면 기본 동작을 위해 unhandled 를 반환할 수 있다.

HostGrowSharedArrayBuffer 구현은 다음 요구사항을 따른다:

  • 추상 연산이 unhandled 로 정상 완료하지 않고, newByteLength < buffer 의 현재 바이트 길이이거나 newByteLength > buffer.[[ArrayBufferMaxByteLength]] 이면 RangeError 예외.
  • isLittleEndian = 주변 에이전트 Agent Record[[LittleEndian]] 필드 값. 연산이 handled 로 정상 완료하면, [[Order]] = seq-cst, [[Payload]] = NumericToRawBytes(biguint64, newByteLength, isLittleEndian), [[Block]] = buffer.[[ArrayBufferByteLengthData]], [[ByteIndex]] = 0, [[ElementSize]] = 8 인 WriteSharedMemory 또는 ReadModifyWriteSharedMemory 이벤트가 후보 실행에 추가되어, SharedArrayBuffer.prototype.grow 에 대한 경합 호출이 “소실”(조용히 아무 것도 하지 않음)되지 않도록 한다.
Note

두 번째 요구사항은 buffer 의 현재 바이트 길이를 언제/어떻게 읽는지에 대해 의도적으로 모호하다. 길이 갱신은 하드웨어의 원자적 read-modify-write 명령을 통해 이루어져야 하므로 load-link/store-conditional 또는 load-exclusive/store-exclusive 쌍을 사용하는 구조에서는 명령을 가깝게 유지하고 싶을 수 있다. 따라서 SharedArrayBuffer.prototype.grow 자체는 HostGrowSharedArrayBuffer 호출 전 newByteLength 에 대한 경계 검사를 수행하지 않으며, 현재 바이트 길이를 언제 읽어야 한다는 요구도 없다.

이는 newByteLength 가 0 이상이며 buffer.[[ArrayBufferMaxByteLength]] 이하임이 보장되는 HostResizeArrayBuffer 와 대조적이다.

기본 구현은 NormalCompletion(unhandled) 를 반환한다.

25.2.3 SharedArrayBuffer 생성자

SharedArrayBuffer 생성자:

  • %SharedArrayBuffer% 이다.
  • 해당 프로퍼티가 존재한다면 전역 객체 "SharedArrayBuffer" 프로퍼티의 초기 값이다 (아래 참조).
  • 생성자로 호출되면 새 SharedArrayBuffer 를 생성·초기화한다.
  • 함수로 호출하도록 의도되지 않았으며 그렇게 호출하면 예외를 던진다.
  • 클래스 정의 extends 절의 값으로 사용할 수 있다. 지정된 SharedArrayBuffer 동작을 상속하려는 서브클래스 생성자SharedArrayBuffer.prototype 내장 메서드 동작을 지원하는 데 필요한 내부 상태로 서브클래스 인스턴스를 생성·초기화하기 위해 SharedArrayBuffer 생성자에 대한 super 호출을 포함해야 한다.

호스트가 SharedArrayBuffer 에 대한 동시 접근을 제공하지 않는 경우 전역 객체"SharedArrayBuffer" 프로퍼티를 생략할 수 있다.

Note

ArrayBuffer 와 달리 SharedArrayBuffer 는 분리(detach)되지 않으며 그 내부 [[ArrayBufferData]] 슬롯은 null 이 되지 않는다.

25.2.3.1 SharedArrayBuffer ( length [ , options ] )

이 함수는 호출 시 다음 단계를 수행한다:

  1. NewTarget 이 undefined 이면 TypeError 예외.
  2. byteLength = ? ToIndex(length).
  3. requestedMaxByteLength = ? GetArrayBufferMaxByteLengthOption(options).
  4. Return ? AllocateSharedArrayBuffer(NewTarget, byteLength, requestedMaxByteLength).

25.2.4 SharedArrayBuffer 생성자의 프로퍼티

SharedArrayBuffer 생성자:

  • 값이 %Function.prototype%[[Prototype]] 내부 슬롯을 가진다.
  • 다음 프로퍼티를 가진다:

25.2.4.1 SharedArrayBuffer.prototype

SharedArrayBuffer.prototype 의 초기 값은 SharedArrayBuffer 프로토타입 객체이다.

이 프로퍼티 특성은 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }.

25.2.4.2 get SharedArrayBuffer [ %Symbol.species% ]

SharedArrayBuffer[%Symbol.species%] 는 set 접근자 함수가 undefined접근자 프로퍼티이다. 그 get 접근자 함수는 호출 시 다음을 수행한다:

  1. this 값 반환.

이 함수의 "name" 프로퍼티 값은 "get [Symbol.species]" 이다.

25.2.5 SharedArrayBuffer 프로토타입 객체의 프로퍼티

SharedArrayBuffer 프로토타입 객체:

  • %SharedArrayBuffer.prototype% 이다.
  • 값이 %Object.prototype%[[Prototype]] 내부 슬롯을 가진다.
  • 일반 객체이다.
  • [[ArrayBufferData]] 또는 [[ArrayBufferByteLength]] 내부 슬롯을 가지지 않는다.

25.2.5.1 get SharedArrayBuffer.prototype.byteLength

SharedArrayBuffer.prototype.byteLength 는 set 접근자 함수가 undefined접근자 프로퍼티이다. 그 get 접근자 함수는 호출 시 다음 단계를 수행한다:

  1. O = this 값.
  2. RequireInternalSlot(O, [[ArrayBufferData]]) 수행.
  3. IsSharedArrayBuffer(O) = false 이면 TypeError 예외.
  4. length = ArrayBufferByteLength(O, seq-cst).
  5. 𝔽(length) 반환.

25.2.5.2 SharedArrayBuffer.prototype.constructor

SharedArrayBuffer.prototype.constructor 의 초기 값은 %SharedArrayBuffer% 이다.

25.2.5.3 SharedArrayBuffer.prototype.grow ( newLength )

이 메서드는 호출 시 다음 단계를 수행한다:

  1. O = this 값.
  2. RequireInternalSlot(O, [[ArrayBufferMaxByteLength]]) 수행.
  3. IsSharedArrayBuffer(O) = false 이면 TypeError 예외.
  4. newByteLength = ? ToIndex(newLength).
  5. hostHandled = ? HostGrowSharedArrayBuffer(O, newByteLength).
  6. hostHandled = handled 이면 undefined 반환.
  7. isLittleEndian = 주변 에이전트 Agent Record[[LittleEndian]] 값.
  8. byteLengthBlock = O.[[ArrayBufferByteLengthData]].
  9. currentByteLengthRawBytes = GetRawBytesFromSharedBlock(byteLengthBlock, 0, biguint64, true, seq-cst).
  10. newByteLengthRawBytes = NumericToRawBytes(biguint64, (newByteLength), isLittleEndian).
  11. 반복:
    1. NOTE: 동일 버퍼에 대한 경합 증가 호출이 완전 순서화되고 유실되지 않으며 침묵 실패하지 않도록 하는 compare-and-exchange 루프이다. 경합 없이 증가 시도 가능하면 루프 종료.
    2. currentByteLength = (RawBytesToNumeric(biguint64, currentByteLengthRawBytes, isLittleEndian)).
    3. newByteLength = currentByteLength 이면 undefined 반환.
    4. newByteLength < currentByteLength 또는 newByteLength > O.[[ArrayBufferMaxByteLength]] 이면 RangeError 예외.
    5. byteLengthDelta = newByteLength - currentByteLength.
    6. byteLengthDelta 바이트로 구성된 새 Shared Data Block 값을 생성할 수 없으면 RangeError 예외.
    7. NOTE: 새 Shared Data Block 은 여기서 구성/사용되지 않는다. 증가 가능한 SharedArrayBuffer 의 관측 가능 동작은 생성 시 최대 크기 Shared Data Block 할당으로 지정되며, 구현이 메모리를 소진하면 RangeError 를 던져야 함을 이 단계가 반영.
    8. readByteLengthRawBytes = AtomicCompareExchangeInSharedBlock(byteLengthBlock, 0, 8, currentByteLengthRawBytes, newByteLengthRawBytes).
    9. ByteListEqual(readByteLengthRawBytes, currentByteLengthRawBytes) = true 이면 undefined 반환.
    10. currentByteLengthRawBytes = readByteLengthRawBytes.
Note

길이 갱신 compare-exchange 의 허위 실패는 금지된다. 새 길이에 대한 경계 검사 통과 및 메모리 부족이 아니면 항상 ReadModifyWriteSharedMemory 이벤트(성공한 compare-exchange)가 후보 실행에 추가된다.

SharedArrayBuffer.prototype.grow 에 대한 병렬 호출은 완전 순서화된다. 예를 들어 sab.grow(10)sab.grow(20) 이 경합할 때 둘 중 하나가 승리하며, sab.grow(20) 이 먼저 일어났다면 sab.grow(10) 호출은 버퍼를 축소하지 않고 대신 RangeError 를 던진다.

25.2.5.4 get SharedArrayBuffer.prototype.growable

SharedArrayBuffer.prototype.growable 는 set 접근자 함수가 undefined접근자 프로퍼티이다. 그 get 접근자 함수는 호출 시 다음을 수행한다:

  1. O = this 값.
  2. RequireInternalSlot(O, [[ArrayBufferData]]) 수행.
  3. IsSharedArrayBuffer(O) = false 이면 TypeError 예외.
  4. IsFixedLengthArrayBuffer(O) = false 이면 true 반환; 아니면 false 반환.

25.2.5.5 get SharedArrayBuffer.prototype.maxByteLength

SharedArrayBuffer.prototype.maxByteLength 는 set 접근자 함수가 undefined접근자 프로퍼티이다. 그 get 접근자 함수는 호출 시 다음을 수행한다:

  1. O = this 값.
  2. RequireInternalSlot(O, [[ArrayBufferData]]) 수행.
  3. IsSharedArrayBuffer(O) = false 이면 TypeError 예외.
  4. IsFixedLengthArrayBuffer(O) = true 이면
    1. length = O.[[ArrayBufferByteLength]].
  5. Else
    1. length = O.[[ArrayBufferMaxByteLength]].
  6. 𝔽(length) 반환.

25.2.5.6 SharedArrayBuffer.prototype.slice ( start, end )

이 메서드는 호출 시 다음 단계를 수행한다:

  1. O = this 값.
  2. RequireInternalSlot(O, [[ArrayBufferData]]) 수행.
  3. IsSharedArrayBuffer(O) = false 이면 TypeError 예외.
  4. len = ArrayBufferByteLength(O, seq-cst).
  5. relativeStart = ? ToIntegerOrInfinity(start).
  6. relativeStart = -∞ 이면 first = 0.
  7. Else if relativeStart < 0 이면 first = max(len + relativeStart, 0).
  8. Else first = min(relativeStart, len).
  9. end = undefined 이면 relativeEnd = len; 아니면 relativeEnd = ? ToIntegerOrInfinity(end).
  10. relativeEnd = -∞ 이면 final = 0.
  11. Else if relativeEnd < 0 이면 final = max(len + relativeEnd, 0).
  12. Else final = min(relativeEnd, len).
  13. newLen = max(final - first, 0).
  14. ctor = ? SpeciesConstructor(O, %SharedArrayBuffer%).
  15. new = ? Construct(ctor, « 𝔽(newLen) »).
  16. RequireInternalSlot(new, [[ArrayBufferData]]) 수행.
  17. IsSharedArrayBuffer(new) = false 이면 TypeError 예외.
  18. new.[[ArrayBufferData]]O.[[ArrayBufferData]] 와 같으면 TypeError 예외.
  19. ArrayBufferByteLength(new, seq-cst) < newLen 이면 TypeError 예외.
  20. fromBuf = O.[[ArrayBufferData]].
  21. toBuf = new.[[ArrayBufferData]].
  22. CopyDataBlockBytes(toBuf, 0, fromBuf, first, newLen) 수행.
  23. new 반환.

25.2.5.7 SharedArrayBuffer.prototype [ %Symbol.toStringTag% ]

%Symbol.toStringTag% 프로퍼티 초기 값은 String "SharedArrayBuffer" 이다.

이 프로퍼티 특성은 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }.

25.2.6 SharedArrayBuffer 인스턴스의 프로퍼티

SharedArrayBuffer 인스턴스는 SharedArrayBuffer 프로토타입 객체로부터 프로퍼티를 상속한다. 각 SharedArrayBuffer 인스턴스는 [[ArrayBufferData]] 내부 슬롯을 가진다. 증가 불가능 인스턴스는 [[ArrayBufferByteLength]] 내부 슬롯을 가진다. 증가 가능 인스턴스는 [[ArrayBufferByteLengthData]][[ArrayBufferMaxByteLength]] 내부 슬롯을 가진다.

Note

SharedArrayBuffer 인스턴스는 ArrayBuffer 인스턴스와 달리 분리(detach)되지 않는다.

25.2.7 증가 가능 SharedArrayBuffer 가이드라인

Note 1

다음은 증가 가능 SharedArrayBuffer 를 사용하는 ECMAScript 프로그래머를 위한 지침이다.

가능하다면 배포 환경에서 프로그램을 테스트할 것을 권장한다. 사용 가능한 물리 메모리 양은 하드웨어 장치마다 크게 다르다. 가상 메모리 서브시스템 또한 하드웨어와 운영체제에 따라 매우 다르다. 64비트 데스크톱 웹 브라우저에서 메모리 부족 없이 실행되는 애플리케이션이 32비트 모바일 웹 브라우저에서는 메모리를 소진할 수 있다.

증가 가능 SharedArrayBuffer 의 "maxByteLength" 옵션 값은 애플리케이션에 필요한 최소 크기를 선택할 것을 권장한다. "maxByteLength" 가 1073741824 (1GiB) 를 넘지 않도록 권장한다.

특정 최대 크기로 증가 가능 SharedArrayBuffer 를 성공적으로 생성했더라도 향후 grow 가 항상 성공함을 보장하지 않는다.

증가 가능 SharedArrayBuffer 의 길이(load) 중 모두가 동기화 seq-cst load 는 아니다. 예를 들어 정수 인덱스 프로퍼티 접근의 경계 검사 목적(u8[idx])으로 수행되는 길이 load 는 동기화되지 않는다. 일반적으로 명시적 동기화가 없으면 한 프로퍼티 접근이 경계 내라는 사실이 같은 에이전트의 이후 접근도 경계 내임을 의미하지 않는다. 반면 SharedArrayBuffer 의 length, byteLength 게터, %TypedArray%.prototype, DataView.prototype 을 통한 명시적 길이 load 는 동기화된다. TypedArray 가 완전히 out-of-bounds 인지 검사하기 위해 내장 메서드가 수행하는 길이 load 역시 동기화된다.

Note 2

다음은 증가 가능 SharedArrayBuffer 를 구현하는 ECMAScript 구현자를 위한 지침이다.

증가 가능 SharedArrayBuffer 는 가상 메모리를 미리 예약한 제자리 증가 방식으로 구현할 것을 권장한다.

grow 연산은 증가 가능 SharedArrayBuffer 에 대한 메모리 접근과 병렬로 일어날 수 있으므로, 메모리 모델 제약은 unordered 접근조차 ‘찢어짐(tearing)’이 없어야 함을 요구한다. 실제로 이는 기반 데이터 블록을 ‘세계 정지’ 없이 복사로 증가시킬 수 없음을 의미한다. 직렬화 지점을 만들고 느리기 때문에 ‘세계 정지’ 전략은 권장되지 않는다.

증가된 메모리는 생성 순간부터(경합 접근 포함) 0 으로 보이는 형태여야 한다. 이는 온디맨드 zero-filled 가상 메모리 페이지나 수동 초기화 시 주의 깊은 동기화로 달성할 수 있다.

증가 가능 SharedArrayBuffer 의 TypedArray 뷰에 대한 정수 인덱스 프로퍼티 접근은 (위 프로그래머 지침에서 언급했듯) 기반 버퍼 길이에 대한 동기화 load 가 아니므로 비증가 SharedArrayBuffer 의 TypedArray 접근과 유사하게 최적화될 수 있도록 의도되었다. 예: 경계 검사를 루프 밖으로 끌어올릴 수 있다.

가상 메모리가 없는(예: MMU 없는 임베디드 장치) 호스트에서는 복사 방식으로 증가 가능 SharedArrayBuffer 를 구현하기 어렵다. 이런 호스트에서 메모리 사용 행태는 가상 메모리가 있는 호스트와 크게 다를 수 있으므로 사용자에게 명확히 알릴 필요가 있다.

25.3 DataView 객체

25.3.1 DataView 객체를 위한 추상 연산

25.3.1.1 버퍼 증명(버퍼 위트니스) Record 를 가진 DataView

DataView With Buffer Witness Record 는 DataView 와, 뷰 대상 버퍼의 캐시된 바이트 길이를 함께 캡슐화하기 위해 사용되는 Record 값이다. 이는 뷰 대상 버퍼가 증가 가능 SharedArrayBuffer 인 경우 바이트 길이 데이터 블록에 대해 단일 공유 메모리 읽기 이벤트가 되도록 돕는 용도로 사용된다.

DataView With Buffer Witness Record 는 Table 75 에 나열된 필드를 갖는다.

Table 75: DataView With Buffer Witness Record 필드
필드 이름 의미
[[Object]] a DataView 버퍼의 바이트 길이를 로드한 해당 DataView 객체.
[[CachedBufferByteLength]] a non-negative integer or detached Record 생성 시점의 객체 [[ViewedArrayBuffer]] 바이트 길이.

25.3.1.2 MakeDataViewWithBufferWitnessRecord ( obj, order )

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

  1. buffer = obj.[[ViewedArrayBuffer]].
  2. IsDetachedBuffer(buffer) = true 이면
    1. byteLength = detached.
  3. Else
    1. byteLength = ArrayBufferByteLength(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 음이 아닌 정수. It performs the following steps when called:

  1. Assert: IsViewOutOfBounds(viewRecord) = false.
  2. view = viewRecord.[[Object]].
  3. view.[[ByteLength]]auto 이면 view.[[ByteLength]] 반환.
  4. Assert: IsFixedLengthArrayBuffer(view.[[ViewedArrayBuffer]]) = false.
  5. byteOffset = view.[[ByteOffset]].
  6. byteLength = viewRecord.[[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 Boolean. It performs the following steps when called:

  1. view = viewRecord.[[Object]].
  2. bufferByteLength = viewRecord.[[CachedBufferByteLength]].
  3. Assert: IsDetachedBuffer(view.[[ViewedArrayBuffer]]) = truebufferByteLength = detached.
  4. bufferByteLength = detached 이면 true 반환.
  5. byteOffsetStart = view.[[ByteOffset]].
  6. view.[[ByteLength]] = auto 이면
    1. byteOffsetEnd = bufferByteLength.
  7. Else
    1. byteOffsetEnd = byteOffsetStart + view.[[ByteLength]].
  8. byteOffsetStart > bufferByteLength 또는 byteOffsetEnd > bufferByteLength 이면 true 반환.
  9. NOTE: 길이 0 DataView 는 out-of-bounds 로 간주되지 않는다.
  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 Number 또는 BigInt 를 포함하는 정상 완료 또는 throw completion. DataView 인스턴스 함수들이 뷰의 버퍼에서 값을 읽어올 때 사용된다. It performs the following steps when called:

  1. RequireInternalSlot(view, [[DataView]]) 수행.
  2. Assert: view[[ViewedArrayBuffer]] 내부 슬롯을 가진다.
  3. getIndex = ? ToIndex(requestIndex).
  4. isLittleEndian = ToBoolean(isLittleEndian).
  5. viewOffset = view.[[ByteOffset]].
  6. viewRecord = MakeDataViewWithBufferWitnessRecord(view, unordered).
  7. NOTE: 뷰의 백업 버퍼가 증가 가능 SharedArrayBuffer 인 경우 경계 검사는 동기화 연산이 아니다.
  8. IsViewOutOfBounds(viewRecord) = true 이면 TypeError 예외.
  9. viewSize = GetViewByteLength(viewRecord).
  10. elementSize = Table 73 에서 type 의 Element Size.
  11. getIndex + elementSize > viewSize 이면 RangeError 예외.
  12. bufferIndex = getIndex + viewOffset.
  13. Return 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 undefined 를 포함하는 정상 완료 또는 throw completion. DataView 인스턴스 함수들이 뷰의 버퍼에 값을 저장할 때 사용된다. It performs the following steps when called:

  1. RequireInternalSlot(view, [[DataView]]) 수행.
  2. Assert: view[[ViewedArrayBuffer]] 내부 슬롯을 가진다.
  3. getIndex = ? ToIndex(requestIndex).
  4. IsBigIntElementType(type) = true 이면 numberValue = ? ToBigInt(value); 아니면 numberValue = ? ToNumber(value).
  5. isLittleEndian = ToBoolean(isLittleEndian).
  6. viewOffset = view.[[ByteOffset]].
  7. viewRecord = MakeDataViewWithBufferWitnessRecord(view, unordered).
  8. NOTE: 뷰의 백업 버퍼가 증가 가능 SharedArrayBuffer 인 경우 경계 검사는 동기화 연산이 아니다.
  9. IsViewOutOfBounds(viewRecord) = true 이면 TypeError 예외.
  10. viewSize = GetViewByteLength(viewRecord).
  11. elementSize = Table 73 에서 type 의 Element Size.
  12. getIndex + elementSize > viewSize 이면 RangeError 예외.
  13. bufferIndex = getIndex + viewOffset.
  14. SetValueInBuffer(view.[[ViewedArrayBuffer]], bufferIndex, type, numberValue, false, unordered, isLittleEndian) 수행.
  15. undefined 반환.

25.3.2 DataView 생성자

DataView 생성자:

  • %DataView% 이다.
  • 전역 객체 "DataView" 프로퍼티의 초기 값이다.
  • 생성자로 호출될 때 새 DataView 를 생성·초기화한다.
  • 함수로 호출하도록 의도되지 않았으며 그렇게 호출하면 예외를 던진다.
  • 클래스 정의 extends 절 값으로 사용할 수 있다. 지정된 DataView 동작을 상속하려는 서브클래스 생성자DataView.prototype 내장 메서드 지원에 필요한 내부 상태로 서브클래스 인스턴스를 생성·초기화하기 위해 DataView 생성자에 대한 super 호출을 포함해야 한다.

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

이 함수는 호출 시 다음 단계를 수행한다:

  1. NewTarget 이 undefined 이면 TypeError 예외.
  2. RequireInternalSlot(buffer, [[ArrayBufferData]]) 수행.
  3. offset = ? ToIndex(byteOffset).
  4. IsDetachedBuffer(buffer) = true 이면 TypeError 예외.
  5. bufferByteLength = ArrayBufferByteLength(buffer, seq-cst).
  6. offset > bufferByteLength 이면 RangeError 예외.
  7. bufferIsFixedLength = IsFixedLengthArrayBuffer(buffer).
  8. byteLength = undefined 이면
    1. bufferIsFixedLength = true 이면
      1. viewByteLength = bufferByteLength - offset.
    2. Else
      1. viewByteLength = auto.
  9. Else
    1. viewByteLength = ? ToIndex(byteLength).
    2. offset + viewByteLength > bufferByteLength 이면 RangeError 예외.
  10. O = ? OrdinaryCreateFromConstructor(NewTarget, "%DataView.prototype%", « [[DataView]], [[ViewedArrayBuffer]], [[ByteLength]], [[ByteOffset]] »).
  11. IsDetachedBuffer(buffer) = true 이면 TypeError 예외.
  12. bufferByteLength = ArrayBufferByteLength(buffer, seq-cst).
  13. offset > bufferByteLength 이면 RangeError 예외.
  14. byteLengthundefined 이면
    1. offset + viewByteLength > bufferByteLength 이면 RangeError 예외.
  15. O.[[ViewedArrayBuffer]] = buffer.
  16. O.[[ByteLength]] = viewByteLength.
  17. O.[[ByteOffset]] = offset.
  18. O 반환.

25.3.3 DataView 생성자의 프로퍼티

DataView 생성자:

  • 값이 %Function.prototype%[[Prototype]] 내부 슬롯을 가진다.
  • 다음 프로퍼티를 가진다:

25.3.3.1 DataView.prototype

DataView.prototype 의 초기 값은 DataView 프로토타입 객체이다.

이 프로퍼티 특성은 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }.

25.3.4 DataView 프로토타입 객체의 프로퍼티

DataView 프로토타입 객체:

  • %DataView.prototype% 이다.
  • 값이 %Object.prototype%[[Prototype]] 내부 슬롯을 가진다.
  • 일반 객체이다.
  • [[DataView]], [[ViewedArrayBuffer]], [[ByteLength]], [[ByteOffset]] 내부 슬롯을 가지지 않는다.

25.3.4.1 get DataView.prototype.buffer

DataView.prototype.buffer 는 set 접근자 함수가 undefined접근자 프로퍼티이다. 그 get 접근자 함수는 호출 시 다음 단계를 수행한다:

  1. O = this 값.
  2. RequireInternalSlot(O, [[DataView]]) 수행.
  3. Assert: O[[ViewedArrayBuffer]] 내부 슬롯을 가진다.
  4. buffer = O.[[ViewedArrayBuffer]].
  5. buffer 반환.

25.3.4.2 get DataView.prototype.byteLength

DataView.prototype.byteLength 는 set 접근자 함수가 undefined접근자 프로퍼티이다. 그 get 접근자 함수는 호출 시 다음 단계를 수행한다:

  1. O = this 값.
  2. RequireInternalSlot(O, [[DataView]]) 수행.
  3. Assert: O[[ViewedArrayBuffer]] 내부 슬롯을 가진다.
  4. viewRecord = MakeDataViewWithBufferWitnessRecord(O, seq-cst).
  5. IsViewOutOfBounds(viewRecord) = true 이면 TypeError 예외.
  6. size = GetViewByteLength(viewRecord).
  7. 𝔽(size) 반환.

25.3.4.3 get DataView.prototype.byteOffset

DataView.prototype.byteOffset 는 set 접근자 함수가 undefined접근자 프로퍼티이다. 그 get 접근자 함수는 호출 시 다음 단계를 수행한다:

  1. O = this 값.
  2. RequireInternalSlot(O, [[DataView]]) 수행.
  3. Assert: O[[ViewedArrayBuffer]] 내부 슬롯을 가진다.
  4. viewRecord = MakeDataViewWithBufferWitnessRecord(O, seq-cst).
  5. IsViewOutOfBounds(viewRecord) = true 이면 TypeError 예외.
  6. offset = O.[[ByteOffset]].
  7. 𝔽(offset) 반환.

25.3.4.4 DataView.prototype.constructor

DataView.prototype.constructor 의 초기 값은 %DataView% 이다.

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

이 메서드는 호출 시 다음 단계를 수행한다:

  1. view = this 값.
  2. Return ? GetViewValue(view, byteOffset, littleEndian, bigint64).

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

이 메서드는 호출 시 다음 단계를 수행한다:

  1. view = this 값.
  2. Return ? GetViewValue(view, byteOffset, littleEndian, biguint64).

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

이 메서드는 호출 시 다음 단계를 수행한다:

  1. view = this 값.
  2. littleEndian 미지정이면 littleEndian = false.
  3. Return ? GetViewValue(view, byteOffset, littleEndian, float16).

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

이 메서드는 호출 시 다음 단계를 수행한다:

  1. view = this 값.
  2. littleEndian 미지정이면 littleEndian = false.
  3. Return ? GetViewValue(view, byteOffset, littleEndian, float32).

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

이 메서드는 호출 시 다음 단계를 수행한다:

  1. view = this 값.
  2. littleEndian 미지정이면 littleEndian = false.
  3. Return ? GetViewValue(view, byteOffset, littleEndian, float64).

25.3.4.10 DataView.prototype.getInt8 ( byteOffset )

이 메서드는 호출 시 다음 단계를 수행한다:

  1. view = this 값.
  2. Return ? GetViewValue(view, byteOffset, true, int8).

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

이 메서드는 호출 시 다음 단계를 수행한다:

  1. view = this 값.
  2. littleEndian 미지정이면 littleEndian = false.
  3. Return ? GetViewValue(view, byteOffset, littleEndian, int16).

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

이 메서드는 호출 시 다음 단계를 수행한다:

  1. view = this 값.
  2. littleEndian 미지정이면 littleEndian = false.
  3. Return ? GetViewValue(view, byteOffset, littleEndian, int32).

25.3.4.13 DataView.prototype.getUint8 ( byteOffset )

이 메서드는 호출 시 다음 단계를 수행한다:

  1. view = this 값.
  2. Return ? GetViewValue(view, byteOffset, true, uint8).

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

이 메서드는 호출 시 다음 단계를 수행한다:

  1. view = this 값.
  2. littleEndian 미지정이면 littleEndian = false.
  3. Return ? GetViewValue(view, byteOffset, littleEndian, uint16).

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

이 메서드는 호출 시 다음 단계를 수행한다:

  1. view = this 값.
  2. littleEndian 미지정이면 littleEndian = false.
  3. Return ? GetViewValue(view, byteOffset, littleEndian, uint32).

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

이 메서드는 호출 시 다음 단계를 수행한다:

  1. view = this 값.
  2. Return ? SetViewValue(view, byteOffset, littleEndian, bigint64, value).

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

이 메서드는 호출 시 다음 단계를 수행한다:

  1. view = this 값.
  2. Return ? SetViewValue(view, byteOffset, littleEndian, biguint64, value).

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

이 메서드는 호출 시 다음 단계를 수행한다:

  1. view = this 값.
  2. littleEndian 미지정이면 littleEndian = false.
  3. Return ? SetViewValue(view, byteOffset, littleEndian, float16, value).

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

이 메서드는 호출 시 다음 단계를 수행한다:

  1. view = this 값.
  2. littleEndian 미지정이면 littleEndian = false.
  3. Return ? SetViewValue(view, byteOffset, littleEndian, float32, value).

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

이 메서드는 호출 시 다음 단계를 수행한다:

  1. view = this 값.
  2. littleEndian 미지정이면 littleEndian = false.
  3. Return ? SetViewValue(view, byteOffset, littleEndian, float64, value).

25.3.4.21 DataView.prototype.setInt8 ( byteOffset, value )

이 메서드는 호출 시 다음 단계를 수행한다:

  1. view = this 값.
  2. Return ? SetViewValue(view, byteOffset, true, int8, value).

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

이 메서드는 호출 시 다음 단계를 수행한다:

  1. view = this 값.
  2. littleEndian 미지정이면 littleEndian = false.
  3. Return ? SetViewValue(view, byteOffset, littleEndian, int16, value).

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

이 메서드는 호출 시 다음 단계를 수행한다:

  1. view = this 값.
  2. littleEndian 미지정이면 littleEndian = false.
  3. Return ? SetViewValue(view, byteOffset, littleEndian, int32, value).

25.3.4.24 DataView.prototype.setUint8 ( byteOffset, value )

이 메서드는 호출 시 다음 단계를 수행한다:

  1. view = this 값.
  2. Return ? SetViewValue(view, byteOffset, true, uint8, value).

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

이 메서드는 호출 시 다음 단계를 수행한다:

  1. view = this 값.
  2. littleEndian 미지정이면 littleEndian = false.
  3. Return ? SetViewValue(view, byteOffset, littleEndian, uint16, value).

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

이 메서드는 호출 시 다음 단계를 수행한다:

  1. view = this 값.
  2. littleEndian 미지정이면 littleEndian = false.
  3. Return ? SetViewValue(view, byteOffset, littleEndian, uint32, value).

25.3.4.27 DataView.prototype [ %Symbol.toStringTag% ]

%Symbol.toStringTag% 프로퍼티 초기 값은 String "DataView" 이다.

이 프로퍼티 특성은 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }.

25.3.5 DataView 인스턴스의 프로퍼티

DataView 인스턴스는 DataView 프로토타입 객체로부터 프로퍼티를 상속한다. 각 DataView 인스턴스는 [[DataView]], [[ViewedArrayBuffer]], [[ByteLength]], [[ByteOffset]] 내부 슬롯을 가진다.

Note

[[DataView]] 내부 슬롯의 값 자체는 명세 내에서 사용되지 않는다. 이 내부 슬롯의 존재 여부가 해당 객체가 DataView 생성자를 사용해 생성되었음을 식별하는 데 사용된다.

25.4 Atomics 객체

Atomics 객체:

  • %Atomics% 이다.
  • 전역 객체 "Atomics" 프로퍼티의 초기 값이다.
  • 일반 객체이다.
  • 값이 %Object.prototype%[[Prototype]] 내부 슬롯을 가진다.
  • [[Construct]] 내부 메서드가 없다; new 연산자로 생성자로 사용할 수 없다.
  • [[Call]] 내부 메서드가 없다; 함수로 호출될 수 없다.

Atomics 객체는 공유 메모리 배열 셀에 대해 분리 불가능(원자적)하게 동작하는 함수들과 에이전트가 원시적 이벤트를 대기/디스패치할 수 있게 하는 함수들을 제공한다. 규범적으로 사용하면 Atomics 함수는 공유 메모리를 통해 통신하는 다중 에이전트 프로그램이 병렬 CPU 상에서도 잘 이해된 순서로 실행되도록 한다. 공유 메모리 통신을 지배하는 규칙은 아래에 정의된 메모리 모델이 제공한다.

Note

ECMAScript 에서 공유 메모리를 프로그래밍/구현하기 위한 비규범적 가이드라인은 메모리 모델 절 끝부분의 주석을 참고하라.

25.4.1 Waiter Record

Waiter Record 는 특정 Atomics.wait 또는 Atomics.waitAsync 호출을 나타내기 위해 사용되는 Record 값이다.

Waiter Record 는 Table 76 에 나열된 필드를 가진다.

Table 76: Waiter Record 필드
필드 이름 의미
[[AgentSignifier]] agent signifier Atomics.wait 또는 Atomics.waitAsync 를 호출한 에이전트.
[[PromiseCapability]] PromiseCapability Record 또는 blocking Atomics.waitAsync 호출을 나타내면 결과 promise, 아니면 blocking.
[[TimeoutTime]] 음이 아닌 확장 수학적 값 타임아웃이 트리거될 수 있는 가장 이른 시각; 시간 값으로 계산.
[[Result]] "ok" 또는 "timed-out" 호출의 반환 값.

25.4.2 WaiterList Records

WaiterList RecordAtomics.wait, Atomics.waitAsync, Atomics.notify 를 통한 에이전트 대기 및 알림을 설명하는 데 사용된다.

WaiterList Record 는 Table 77 에 나열된 필드를 가진다.

Table 77: WaiterList Record 필드
필드 이름 의미
[[Waiters]] Waiter Record 들의 List 이 WaiterList 가 연관된 위치에서 대기 중인 Atomics.wait / Atomics.waitAsync 호출들.
[[MostRecentLeaveEvent]] Synchronize 이벤트 또는 empty 가장 최근 임계 구역 이탈 이벤트, 또는 한번도 진입한 적 없으면 empty.

같은 agent signifier 를 가진 여러 Waiter Record 가 하나의 WaiterList 에 있을 수 있다.

에이전트 클러스터는 WaiterList Record 의 저장소를 가진다; 저장소는 (block, i) 로 인덱싱되고 blockShared Data Block, iblock 메모리의 바이트 오프셋이다. WaiterList Record 는 에이전트 독립적이다: (block, i) 로 조회하면 클러스터 내 어떤 에이전트에서도 동일한 WaiterList Record 가 결과로 나온다.

각 WaiterList Record 는 평가 중 그 WaiterList Record 에 대한 배타적 접근을 제어하는 critical section 을 가진다. 한 번에 하나의 에이전트만 critical section 에 진입할 수 있다. 진입/이탈은 추상 연산 EnterCriticalSectionLeaveCriticalSection 이 제어한다. WaiterList Record 에 대한 연산—대기 에이전트 추가/제거, 목록 순회, 목록의 에이전트 일시중단/알림, Synchronize 이벤트 설정/조회—는 critical section 에 진입한 에이전트만 수행할 수 있다.

25.4.3 Atomics 를 위한 추상 연산

25.4.3.1 ValidateIntegerTypedArray ( typedArray, waitable )

The abstract operation ValidateIntegerTypedArray takes arguments typedArray (an ECMAScript language value) and waitable (a Boolean) and returns 정상 완료(TypedArray With Buffer Witness Record 포함) 또는 throw completion. It performs the following steps when called:

  1. taRecord = ? ValidateTypedArray(typedArray, unordered).
  2. NOTE: typedArray 의 백업 버퍼가 증가 가능 SharedArrayBuffer 인 경우 경계 검사는 동기화 연산이 아니다.
  3. waitable = true 이면
    1. typedArray.[[TypedArrayName]]"Int32Array", "BigInt64Array" 둘 다 아니면 TypeError 예외.
  4. Else
    1. type = TypedArrayElementType(typedArray).
    2. IsUnclampedIntegerElementType(type) = false 그리고 IsBigIntElementType(type) = false 이면 TypeError 예외.
  5. Return 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 정상 완료(정수) 또는 throw completion. It performs the following steps when called:

  1. length = TypedArrayLength(taRecord).
  2. accessIndex = ? ToIndex(requestIndex).
  3. Assert: accessIndex ≥ 0.
  4. accessIndexlength 이면 RangeError 예외.
  5. typedArray = taRecord.[[Object]].
  6. elementSize = TypedArrayElementSize(typedArray).
  7. offset = typedArray.[[ByteOffset]].
  8. Return (accessIndex × elementSize) + offset.

25.4.3.3 ValidateAtomicAccessOnIntegerTypedArray ( typedArray, requestIndex )

The abstract operation ValidateAtomicAccessOnIntegerTypedArray takes arguments typedArray (an ECMAScript language value) and requestIndex (an ECMAScript language value) and returns 정상 완료(정수) 또는 throw completion. It performs the following steps when called:

  1. taRecord = ? ValidateIntegerTypedArray(typedArray, false).
  2. Return ? ValidateAtomicAccess(taRecord, requestIndex).

25.4.3.4 RevalidateAtomicAccess ( typedArray, byteIndexInBuffer )

The abstract operation RevalidateAtomicAccess takes arguments typedArray (a TypedArray) and byteIndexInBuffer (an integer) and returns 정상 완료(unused) 또는 throw completion. 이 연산은 Atomics 메서드에서 모든 인수 강제가 수행된 후 버퍼가 경계 밖이 되었을 수 있으므로 원자 연산용 인덱스를 다시 검증한다. typedArray 의 백업 버퍼가 SharedArrayBuffer 인 경우 이 연산은 throw 하지 않는다. It performs the following steps when called:

  1. taRecord = MakeTypedArrayWithBufferWitnessRecord(typedArray, unordered).
  2. NOTE: typedArray 의 백업 버퍼가 증가 가능 SharedArrayBuffer 인 경우 경계 검사는 동기화되지 않는다.
  3. IsTypedArrayOutOfBounds(taRecord) = true 이면 TypeError 예외.
  4. Assert: byteIndexInBuffertypedArray.[[ByteOffset]].
  5. byteIndexInBuffertaRecord.[[CachedBufferByteLength]] 이면 RangeError 예외.
  6. Return 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 WaiterList Record. It performs the following steps when called:

  1. Assert: ii + 3 은 block 메모리의 유효 바이트 오프셋.
  2. Return (block, i) 쌍이 참조하는 WaiterList Record.

25.4.3.6 EnterCriticalSection ( WL )

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

  1. Assert: 주변 에이전트는 어떤 WaiterList Recordcritical section 안에 있지 않다.
  2. 어떤 에이전트도 WLcritical section 에 없을 때까지 대기한 후 다른 에이전트가 진입하지 못하게 한 상태로 진입.
  3. WL.[[MostRecentLeaveEvent]]empty 이면
    1. NOTE: 최소 1번 진입된 WLLeaveCriticalSection 에 의해 Synchronize 이벤트가 설정된다.
    2. execution = 주변 에이전트의 Agent Record.[[CandidateExecution]].
    3. eventsRecord = execution.[[EventsRecords]][[AgentSignifier]] = AgentSignifier() 인 Agent Events Record.
    4. enterEvent = 새로운 Synchronize 이벤트.
    5. eventsRecord.[[EventList]]enterEvent 추가.
    6. eventsRecord.[[AgentSynchronizesWith]] 에 (WL.[[MostRecentLeaveEvent]], enterEvent) 추가.
  4. Return unused.

EnterCriticalSection 은 에이전트가 다른 에이전트가 떠나기를 기다려야 할 때 경합(contention) 이 있다. 경합이 없을 때 EnterCriticalSection 호출의 FIFO 순서가 관측 가능하다. 경합이 있을 때 구현은 임의 순서를 선택할 수 있으나 무기한 대기는 유발할 수 없다.

25.4.3.7 LeaveCriticalSection ( WL )

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

  1. Assert: 주변 에이전트는 WLcritical section 안에 있다.
  2. execution = 주변 에이전트 Agent Record.[[CandidateExecution]].
  3. eventsRecord = execution.[[EventsRecords]][[AgentSignifier]] = AgentSignifier() 인 것.
  4. leaveEvent = 새로운 Synchronize 이벤트.
  5. eventsRecord.[[EventList]]leaveEvent 추가.
  6. WL.[[MostRecentLeaveEvent]] = leaveEvent 로 설정.
  7. WLcritical section 떠남.
  8. Return unused.

25.4.3.8 AddWaiter ( WL, waiterRecord )

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

  1. Assert: 주변 에이전트는 WL critical section 안에 있다.
  2. Assert: WL.[[Waiters]][[PromiseCapability]][[AgentSignifier]] 가 각각 waiterRecord 와 동일한 Waiter Record 가 없다.
  3. WL.[[Waiters]]waiterRecord 추가.
  4. Return unused.

25.4.3.9 RemoveWaiter ( WL, waiterRecord )

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

  1. Assert: 주변 에이전트는 WL critical section 안에 있다.
  2. Assert: WL.[[Waiters]]waiterRecord 를 포함한다.
  3. WL.[[Waiters]] 에서 waiterRecord 제거.
  4. Return unused.

25.4.3.10 RemoveWaiters ( WL, c )

The abstract operation RemoveWaiters takes arguments WL (a WaiterList Record) and c (a non-negative integer or +∞) and returns Waiter Record 들의 List. It performs the following steps when called:

  1. Assert: 주변 에이전트는 WL critical section 안에 있다.
  2. len = WL.[[Waiters]] 요소 수.
  3. n = min(c, len).
  4. L = WL.[[Waiters]] 의 처음 n 요소로 이루어진 List.
  5. WL.[[Waiters]] 의 처음 n 요소 제거.
  6. Return L.

25.4.3.11 SuspendThisAgent ( WL, waiterRecord )

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

  1. Assert: 주변 에이전트는 WL critical section 안에 있다.
  2. Assert: WL.[[Waiters]]waiterRecord 포함.
  3. thisAgent = AgentSignifier().
  4. Assert: waiterRecord.[[AgentSignifier]]thisAgent.
  5. Assert: waiterRecord.[[PromiseCapability]]blocking.
  6. Assert: AgentCanSuspend() = true.
  7. LeaveCriticalSection(WL) 수행 후 주변 에이전트를 waiterRecord.[[TimeoutTime]] 시각까지 일시중단하되, critical section 을 벗어난 직후부터 suspend 적용 전 사이 도착한 알림이 손실되지 않도록 결합된 연산으로 수행. 주변 에이전트는 타임아웃 또는 다른 에이전트가 NotifyWaiter(WL, thisAgent) (즉 Atomics.notify) 를 호출하여 깨어날 수 있다.
  8. EnterCriticalSection(WL) 수행.
  9. Return unused.

25.4.3.12 NotifyWaiter ( WL, waiterRecord )

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

  1. Assert: 주변 에이전트는 WL critical section 안에 있다.
  2. waiterRecord.[[PromiseCapability]]blocking 이면
    1. signifier 가 waiterRecord.[[AgentSignifier]] 인 에이전트를 suspend 에서 깨움.
    2. NOTE: 이는 SuspendThisAgent 내 실행 재개를 유발.
  3. Else if AgentSignifier() 가 waiterRecord.[[AgentSignifier]] 이면
    1. promiseCapability = waiterRecord.[[PromiseCapability]].
    2. Call(promiseCapability.[[Resolve]], undefined, « waiterRecord.[[Result]] ») 수행.
  4. Else
    1. EnqueueResolveInAgentJob(waiterRecord.[[AgentSignifier]], waiterRecord.[[PromiseCapability]], waiterRecord.[[Result]]) 수행.
  5. Return unused.
Note

에이전트는 호스트에 전달하는 것 외에 다른 에이전트의 promise capability 에 접근해서는 안 된다.

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 = 매개변수 없고 agentSignifier, promiseCapability, resolution 을 캡처하며 호출 시:
    1. Assert: AgentSignifier() = agentSignifier.
    2. Call(promiseCapability.[[Resolve]], undefined, « resolution ») 수행.
    3. Return unused.
  2. realmInTargetAgent = ! GetFunctionRealm(promiseCapability.[[Resolve]]).
  3. Assert: agentSignifier = realmInTargetAgent.[[AgentSignifier]].
  4. HostEnqueueGenericJob(resolveJob, realmInTargetAgent) 수행.
  5. Return unused.

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

The abstract operation DoWait takes arguments mode (sync or async), typedArray (an ECMAScript language value), index (an ECMAScript language value), value (an ECMAScript language value), and timeout (an ECMAScript language value) and returns 정상 완료(Object, "not-equal", "timed-out", "ok" 중 하나) 또는 throw completion. It performs the following steps when called:

  1. taRecord = ? ValidateIntegerTypedArray(typedArray, true).
  2. buffer = taRecord.[[Object]].[[ViewedArrayBuffer]].
  3. IsSharedArrayBuffer(buffer) = false 이면 TypeError 예외.
  4. i = ? ValidateAtomicAccess(taRecord, index).
  5. arrayTypeName = typedArray.[[TypedArrayName]].
  6. arrayTypeName = "BigInt64Array" 이면 v = ? ToBigInt64(value); Else v = ? ToInt32(value).
  7. q = ? ToNumber(timeout).
  8. qNaN 또는 +∞𝔽 이면 t = +∞; else if q = -∞𝔽 이면 t = 0; else t = max((q), 0).
  9. mode = sync 그리고 AgentCanSuspend() = false 이면 TypeError 예외.
  10. block = buffer.[[ArrayBufferData]].
  11. offset = typedArray.[[ByteOffset]].
  12. byteIndexInBuffer = (i × 4) + offset.
  13. WL = GetWaiterList(block, byteIndexInBuffer).
  14. mode = sync 이면
    1. promiseCapability = blocking.
    2. resultObject = undefined.
  15. Else
    1. promiseCapability = ! NewPromiseCapability(%Promise%).
    2. resultObject = OrdinaryObjectCreate(%Object.prototype%).
  16. EnterCriticalSection(WL) 수행.
  17. elementType = TypedArrayElementType(typedArray).
  18. w = GetValueFromBuffer(buffer, byteIndexInBuffer, elementType, true, seq-cst).
  19. vw 이면
    1. LeaveCriticalSection(WL) 수행.
    2. mode = sync 이면 "not-equal" 반환.
    3. CreateDataPropertyOrThrow(resultObject, "async", false) 수행.
    4. CreateDataPropertyOrThrow(resultObject, "value", "not-equal") 수행.
    5. Return resultObject.
  20. t = 0 그리고 mode = async 이면
    1. NOTE: 동기 즉시 타임아웃은 특별 처리 없음. 비동기 즉시 타임아웃은 빠른 실패를 위해 특별 처리.
    2. LeaveCriticalSection(WL) 수행.
    3. CreateDataPropertyOrThrow(resultObject, "async", false) 수행.
    4. CreateDataPropertyOrThrow(resultObject, "value", "timed-out") 수행.
    5. Return resultObject.
  21. thisAgent = AgentSignifier().
  22. now = 현재 시간(UTC) time value.
  23. additionalTimeout = 구현 정의 음이 아닌 수학적 값.
  24. timeoutTime = (now) + t + additionalTimeout.
  25. NOTE: t = +∞ 이면 timeoutTime 도 +∞.
  26. waiterRecord = 새 Waiter Record { [[AgentSignifier]]: thisAgent, [[PromiseCapability]]: promiseCapability, [[TimeoutTime]]: timeoutTime, [[Result]]: "ok" }.
  27. AddWaiter(WL, waiterRecord) 수행.
  28. mode = sync 이면
    1. SuspendThisAgent(WL, waiterRecord) 수행.
  29. Else if timeoutTime 유한이면
    1. EnqueueAtomicsWaitAsyncTimeoutJob(WL, waiterRecord) 수행.
  30. LeaveCriticalSection(WL) 수행.
  31. mode = sync 이면 waiterRecord.[[Result]] 반환.
  32. CreateDataPropertyOrThrow(resultObject, "async", true) 수행.
  33. CreateDataPropertyOrThrow(resultObject, "value", promiseCapability.[[Promise]]) 수행.
  34. Return resultObject.
Note

additionalTimeout 은 전력 소비 감소나 타이밍 공격 완화를 위한 타이머 해상도 조정 등 필요 시 타임아웃에 패딩을 허용한다. 호출마다 값이 다를 수 있다.

25.4.3.15 EnqueueAtomicsWaitAsyncTimeoutJob ( WL, waiterRecord )

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

  1. timeoutJob = 매개변수 없고 WL, waiterRecord 캡처하며 호출 시:
    1. EnterCriticalSection(WL) 수행.
    2. WL.[[Waiters]]waiterRecord 포함하면
      1. timeOfJobExecution = 현재 시간(UTC) time value.
      2. Assert: (timeOfJobExecution) ≥ waiterRecord.[[TimeoutTime]] (시간 비단조 가능성 무시).
      3. waiterRecord.[[Result]] = "timed-out".
      4. RemoveWaiter(WL, waiterRecord) 수행.
      5. NotifyWaiter(WL, waiterRecord) 수행.
    3. LeaveCriticalSection(WL) 수행.
    4. Return unused.
  2. now = 현재 시간(UTC) time value.
  3. currentRealm = 현재 Realm Record.
  4. HostEnqueueTimeoutJob(timeoutJob, currentRealm, 𝔽(waiterRecord.[[TimeoutTime]]) - now) 수행.
  5. Return 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 바이트 값 List. It performs the following steps when called:

  1. execution = 주변 에이전트 Agent Record.[[CandidateExecution]].
  2. eventsRecord = execution.[[EventsRecords]][[AgentSignifier]] = AgentSignifier() 인 것.
  3. rawBytesRead = 길이 elementSize 이고 요소가 비결정적으로 선택된 바이트 값 List.
  4. NOTE: 구현에서 rawBytesRead 는 load-link, load-exclusive, 또는 read-modify-write 명령의 피연산자 결과. 비결정성은 약한 일관성 하드웨어 관측 가능 동작을 기술.
  5. NOTE: 기대값과 읽은 값 비교는 기대값 불일치 시 불필요한 강한 동기화를 피하기 위해 read-modify-write 수정 함수 밖에서 수행.
  6. ByteListEqual(rawBytesRead, expectedBytes) = true 이면
    1. second = 매개변수 (oldBytes, newBytes) 를 가지고 아무것도 캡처하지 않으며 호출 시 원자적으로 newBytes 반환하는 새 read-modify-write 수정 함수.
    2. event = ReadModifyWriteSharedMemory { [[Order]]: seq-cst, [[NoTear]]: true, [[Block]]: block, [[ByteIndex]]: byteIndexInBuffer, [[ElementSize]]: elementSize, [[Payload]]: replacementBytes, [[ModifyOp]]: second }.
  7. Else
    1. event = ReadSharedMemory { [[Order]]: seq-cst, [[NoTear]]: true, [[Block]]: block, [[ByteIndex]]: byteIndexInBuffer, [[ElementSize]]: elementSize }.
  8. eventsRecord.[[EventList]]event 추가.
  9. execution.[[ChosenValues]]Chosen Value Record { [[Event]]: event, [[ChosenValue]]: rawBytesRead } 추가.
  10. Return rawBytesRead.

25.4.3.17 AtomicReadModifyWrite ( typedArray, index, value, op )

The abstract operation AtomicReadModifyWrite takes arguments typedArray (an ECMAScript language value), index (an ECMAScript language value), value (an ECMAScript language value), and op (a read-modify-write modification function) and returns 정상 완료(Number 또는 BigInt) 또는 throw completion. op 는 두 List (바이트 값) 인수를 받아 바이트 값 List 를 반환한다. 이 연산은 원자적으로 값을 로드하고 다른 값과 결합 후 저장하며 로드한 값을 반환한다. It performs the following steps when called:

  1. byteIndexInBuffer = ? ValidateAtomicAccessOnIntegerTypedArray(typedArray, index).
  2. typedArray.[[ContentType]] = bigint 이면 v = ? ToBigInt(value); 아니면 v = 𝔽(? ToIntegerOrInfinity(value)).
  3. RevalidateAtomicAccess(typedArray, byteIndexInBuffer) 수행.
  4. buffer = typedArray.[[ViewedArrayBuffer]].
  5. elementType = TypedArrayElementType(typedArray).
  6. Return GetModifySetValueInBuffer(buffer, byteIndexInBuffer, elementType, v, 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 바이트 값 List. 모든 바이트에 대한 비트 연산을 수행하고 바이트 값 List 를 원자적으로 반환한다. It performs the following steps when called:

  1. Assert: xBytesyBytes 는 동일한 길이.
  2. result = 새 빈 List.
  3. i = 0.
  4. xBytes 요소 xByte 에 대해
    1. yByte = yBytes[i].
    2. op = & 이면
      1. resultByte = xByte AND yByte.
    3. Else if op = ^ 이면
      1. resultByte = xByte XOR yByte.
    4. Else
      1. Assert: op = |.
      2. resultByte = xByte OR yByte.
    5. i = i + 1.
    6. resultresultByte 추가.
  5. Return 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 Boolean. It performs the following steps when called:

  1. xBytes, yBytes 길이 다르면 false 반환.
  2. i = 0.
  3. xBytes 요소 xByte 에 대해
    1. yByte = yBytes[i].
    2. xByteyByte 이면 false 반환.
    3. i = i + 1.
  4. Return true.

25.4.4 Atomics.add ( typedArray, index, value )

이 함수는 호출 시 다음 단계를 수행한다:

  1. add = 매개변수 (xBytes, yBytes) 를 가지고 typedArray 를 캡처하며 호출 시 원자적으로:
    1. type = TypedArrayElementType(typedArray).
    2. isLittleEndian = 주변 에이전트 Agent Record[[LittleEndian]] 값.
    3. x = RawBytesToNumeric(type, xBytes, isLittleEndian).
    4. y = RawBytesToNumeric(type, yBytes, isLittleEndian).
    5. x 가 Number 이면
      1. sum = Number::add(x, y).
    6. Else
      1. Assert: x 는 BigInt.
      2. sum = BigInt::add(x, y).
    7. sumBytes = NumericToRawBytes(type, sum, isLittleEndian).
    8. Assert: sumBytes, xBytes, yBytes 길이 동일.
    9. Return sumBytes.
  2. Return ? AtomicReadModifyWrite(typedArray, index, value, add).

25.4.5 Atomics.and ( typedArray, index, value )

이 함수는 호출 시 다음 단계를 수행한다:

  1. and = 매개변수 (xBytes, yBytes) 를 가지고 아무것도 캡처하지 않으며 호출 시 원자적으로:
    1. Return ByteListBitwiseOp(&, xBytes, yBytes).
  2. Return ? AtomicReadModifyWrite(typedArray, index, value, and).

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

이 함수는 호출 시 다음 단계를 수행한다:

  1. byteIndexInBuffer = ? ValidateAtomicAccessOnIntegerTypedArray(typedArray, index).
  2. buffer = typedArray.[[ViewedArrayBuffer]].
  3. block = buffer.[[ArrayBufferData]].
  4. typedArray.[[ContentType]] = bigint 이면
    1. expected = ? ToBigInt(expectedValue).
    2. replacement = ? ToBigInt(replacementValue).
  5. Else
    1. expected = 𝔽(? ToIntegerOrInfinity(expectedValue)).
    2. replacement = 𝔽(? ToIntegerOrInfinity(replacementValue)).
  6. RevalidateAtomicAccess(typedArray, byteIndexInBuffer) 수행.
  7. elementType = TypedArrayElementType(typedArray).
  8. elementSize = TypedArrayElementSize(typedArray).
  9. isLittleEndian = 주변 에이전트 Agent Record.[[LittleEndian]].
  10. expectedBytes = NumericToRawBytes(elementType, expected, isLittleEndian).
  11. replacementBytes = NumericToRawBytes(elementType, replacement, isLittleEndian).
  12. IsSharedArrayBuffer(buffer) = true 이면
    1. rawBytesRead = AtomicCompareExchangeInSharedBlock(block, byteIndexInBuffer, elementSize, expectedBytes, replacementBytes).
  13. Else
    1. rawBytesRead = 길이 elementSizeList ( block[byteIndexInBuffer] 로부터 elementSize 바이트 ).
    2. ByteListEqual(rawBytesRead, expectedBytes) = true 이면
      1. replacementBytes 바이트들을 block[byteIndexInBuffer] 부터 저장.
  14. Return RawBytesToNumeric(elementType, rawBytesRead, isLittleEndian).

25.4.7 Atomics.exchange ( typedArray, index, value )

이 함수는 호출 시 다음 단계를 수행한다:

  1. second = 매개변수 (oldBytes, newBytes) 를 가지며 아무것도 캡처하지 않고 호출 시 원자적으로 newBytes 반환하는 read-modify-write 수정 함수.
  2. Return ? AtomicReadModifyWrite(typedArray, index, value, second).

25.4.8 Atomics.isLockFree ( size )

이 함수는 호출 시 다음 단계를 수행한다:

  1. n = ? ToIntegerOrInfinity(size).
  2. AR = 주변 에이전트의 Agent Record.
  3. n = 1 이면 AR.[[IsLockFree1]] 반환.
  4. n = 2 이면 AR.[[IsLockFree2]] 반환.
  5. n = 4 이면 true 반환.
  6. n = 8 이면 AR.[[IsLockFree8]] 반환.
  7. Return false.
Note

이 함수는 최적화용 프리미티브이다. 크기 n 바이트 데이터에 대한 atomic primitive (compareExchange, load, store, add, sub, and, or, xor, exchange) 의 원자 단계가 주변 에이전트가 데이터 범위를 넘어서는 lock 을 획득하지 않고 수행된다면 Atomics.isLockFree(n) 은 true 를 반환한다는 직관을 제공한다. 고성능 알고리즘은 이 함수를 사용해 임계 영역에서 락 vs 원자 연산 사용을 결정한다. 원자 프리미티브가 lock-free 가 아니면 자체 락을 제공하는 편이 종종 더 효율적이다.

Atomics.isLockFree(4) 는 관련 하드웨어 모두에서 지원 가능하므로 항상 true 를 반환한다. 이는 프로그램 단순화에 도움된다.

이 함수 반환값과 무관하게 모든 원자 연산은 원자성이 보장된다. 즉 중간 연산(예: “tearing”)이 관측되지 않는다.

25.4.9 Atomics.load ( typedArray, index )

이 함수는 호출 시 다음 단계를 수행한다:

  1. byteIndexInBuffer = ? ValidateAtomicAccessOnIntegerTypedArray(typedArray, index).
  2. RevalidateAtomicAccess(typedArray, byteIndexInBuffer) 수행.
  3. buffer = typedArray.[[ViewedArrayBuffer]].
  4. elementType = TypedArrayElementType(typedArray).
  5. Return GetValueFromBuffer(buffer, byteIndexInBuffer, elementType, true, seq-cst).

25.4.10 Atomics.or ( typedArray, index, value )

이 함수는 호출 시 다음 단계를 수행한다:

  1. or = 매개변수 (xBytes, yBytes) 를 가지고 아무것도 캡처하지 않으며 호출 시 원자적으로:
    1. Return ByteListBitwiseOp(|, xBytes, yBytes).
  2. Return ? AtomicReadModifyWrite(typedArray, index, value, or).

25.4.11 Atomics.store ( typedArray, index, value )

이 함수는 호출 시 다음 단계를 수행한다:

  1. byteIndexInBuffer = ? ValidateAtomicAccessOnIntegerTypedArray(typedArray, index).
  2. typedArray.[[ContentType]] = bigint 이면 v = ? ToBigInt(value); 아니면 v = 𝔽(? ToIntegerOrInfinity(value)).
  3. RevalidateAtomicAccess(typedArray, byteIndexInBuffer) 수행.
  4. buffer = typedArray.[[ViewedArrayBuffer]].
  5. elementType = TypedArrayElementType(typedArray).
  6. SetValueInBuffer(buffer, byteIndexInBuffer, elementType, v, true, seq-cst) 수행.
  7. Return v.

25.4.12 Atomics.sub ( typedArray, index, value )

이 함수는 호출 시 다음 단계를 수행한다:

  1. subtract = 매개변수 (xBytes, yBytes) 를 가지고 typedArray 를 캡처하며 호출 시 원자적으로:
    1. type = TypedArrayElementType(typedArray).
    2. isLittleEndian = 주변 에이전트 Agent Record.[[LittleEndian]].
    3. x = RawBytesToNumeric(type, xBytes, isLittleEndian).
    4. y = RawBytesToNumeric(type, yBytes, isLittleEndian).
    5. x 가 Number 이면
      1. difference = Number::subtract(x, y).
    6. Else
      1. Assert: x 는 BigInt.
      2. difference = BigInt::subtract(x, y).
    7. differenceBytes = NumericToRawBytes(type, difference, isLittleEndian).
    8. Assert: differenceBytes, xBytes, yBytes 길이 동일.
    9. Return differenceBytes.
  2. Return ? AtomicReadModifyWrite(typedArray, index, value, subtract).

25.4.13 Atomics.wait ( typedArray, index, value, timeout )

이 함수는 주변 에이전트를 대기 큐에 두고 알림 또는 타임아웃까지 일시중단하며 결과 구분 문자열을 반환한다.

호출 시 다음 단계를 수행한다:

  1. Return ? DoWait(sync, typedArray, index, value, timeout).

25.4.14 Atomics.waitAsync ( typedArray, index, value, timeout )

이 함수는 호출 에이전트가 알림을 받거나 타임아웃에 도달했을 때 resolve 되는 Promise 를 반환한다.

호출 시 다음 단계를 수행한다:

  1. Return ? DoWait(async, typedArray, index, value, timeout).

25.4.15 Atomics.notify ( typedArray, index, count )

이 함수는 대기 큐에서 잠자고 있는 일부 에이전트를 깨운다.

호출 시 다음 단계를 수행한다:

  1. taRecord = ? ValidateIntegerTypedArray(typedArray, true).
  2. byteIndexInBuffer = ? ValidateAtomicAccess(taRecord, index).
  3. count = undefined 이면
    1. c = +∞.
  4. Else
    1. intCount = ? ToIntegerOrInfinity(count).
    2. c = max(intCount, 0).
  5. buffer = typedArray.[[ViewedArrayBuffer]].
  6. block = buffer.[[ArrayBufferData]].
  7. IsSharedArrayBuffer(buffer) = false 이면 +0𝔽 반환.
  8. WL = GetWaiterList(block, byteIndexInBuffer).
  9. EnterCriticalSection(WL) 수행.
  10. S = RemoveWaiters(WL, c).
  11. S 요소 W 에 대해
    1. NotifyWaiter(WL, W) 수행.
  12. LeaveCriticalSection(WL) 수행.
  13. n = S 요소 수.
  14. Return 𝔽(n).

25.4.16 Atomics.xor ( typedArray, index, value )

이 함수는 호출 시 다음 단계를 수행한다:

  1. xor = 매개변수 (xBytes, yBytes) 를 가지고 아무것도 캡처하지 않으며 호출 시 원자적으로:
    1. Return ByteListBitwiseOp(^, xBytes, yBytes).
  2. Return ? AtomicReadModifyWrite(typedArray, index, value, xor).

25.4.17 Atomics [ %Symbol.toStringTag% ]

%Symbol.toStringTag% 프로퍼티 초기 값은 String "Atomics" 이다.

이 프로퍼티 특성은 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }.

25.5 JSON 객체

JSON 객체:

  • %JSON% 이다.
  • 전역 객체 "JSON" 프로퍼티의 초기 값이다.
  • 일반 객체이다.
  • JSON 텍스트를 파싱 및 구성하기 위한 parsestringify 두 함수 포함.
  • 값이 %Object.prototype%[[Prototype]] 내부 슬롯을 가진다.
  • [[Construct]] 내부 메서드가 없어 new 생성자로 사용할 수 없다.
  • [[Call]] 내부 메서드가 없어 함수로 호출할 수 없다.

JSON 데이터 교환 형식은 ECMA-404 에 정의된다. 본 명세에서 사용하는 JSON 교환 형식은 ECMA-404 에 기술된 것과 정확히 동일하다. JSON.parseJSON.stringify 의 적합 구현은 ECMA-404 명세에 기술된 교환 형식을 삭제나 확장 없이 정확히 지원해야 한다.

25.5.1 JSON.parse ( text [ , reviver ] )

이 함수는 JSON 텍스트(JSON 형식 문자열)를 파싱하여 ECMAScript 언어 값을 생성한다. JSON 형식은 ECMAScript 리터럴, 배열 초기자, 객체 초기자와 유사한 구문으로 리터럴, 배열, 객체를 표현한다. 파싱 후 JSON 객체는 ECMAScript 객체로, JSON 배열은 ECMAScript Array 인스턴스로 실현된다. JSON 문자열, 숫자, 불리언, null 은 ECMAScript String, Number, Boolean 및 null 로 실현된다.

선택적 reviver 매개변수는 key, value 두 매개변수를 받는 함수로 결과를 필터/변환할 수 있다. 파싱에서 생성된 각 key/value 쌍에 대해 호출되며 반환값이 원래 값 대신 사용된다. 받은 값을 그대로 반환하면 구조는 수정되지 않는다. undefined 를 반환하면 그 프로퍼티는 결과에서 삭제된다.

  1. jsonString = ? ToString(text).
  2. unfiltered = ? ParseJSON(jsonString).
  3. IsCallable(reviver) = true 이면
    1. root = OrdinaryObjectCreate(%Object.prototype%).
    2. rootName = 빈 문자열.
    3. CreateDataPropertyOrThrow(root, rootName, unfiltered) 수행.
    4. Return ? InternalizeJSONProperty(root, rootName, reviver).
  4. Else
    1. Return unfiltered.

이 함수의 "length" 프로퍼티는 2𝔽이다.

25.5.1.1 ParseJSON ( text )

The abstract operation ParseJSON takes argument text (a String) and returns 정상 완료(ECMAScript 언어 값) 또는 throw completion. It performs the following steps when called:

  1. StringToCodePoints(text) 가 ECMA-404 에 지정된 유효한 JSON 텍스트가 아니면 SyntaxError 예외.
  2. scriptString = "("text");" 의 문자열 연결.
  3. script = ParseText(scriptString, Script).
  4. NOTE: 13.2.5.1 에 정의된 초기 에러 규칙은 위 ParseText 호출에 대해 특별 처리.
  5. Assert: script 는 Parse Node.
  6. result = ! Evaluation of script.
  7. NOTE: 13.2.5.5 에 정의된 PropertyDefinitionEvaluation 의미론은 위 평가에 대해 특별 처리.
  8. Assert: result 는 String, Number, Boolean, ArrayLiteral 또는 ObjectLiteral 로 정의된 Object, 또는 null.
  9. Return result.

적합한 JSON.parse 구현은 JSON 문법을 확장할 수 없다. 수정/확장된 JSON 교환 형식을 지원하려면 다른 parse 함수를 정의해야 한다.

Note 1

유효 JSON 텍스트는 ECMAScript PrimaryExpression 구문의 부분집합이다. 단계 1jsonString 이 그 부분집합에 부합하는지 검증하고, 8 는 평가 결과가 적절한 타입임을 단언한다.

그러나 13.2.5.5 가 ParseJSON 중 다르게 동작하므로, 동일 소스 텍스트가 PrimaryExpression 으로 평가될 때와 JSON 으로 평가될 때 다른 결과를 낼 수 있다. 또한 객체 리터럴에서 중복 "__proto__" 프로퍼티에 대한 Early Error 가 ParseJSON 중에는 적용되지 않으므로 문법과 일치해도 ParseJSON 이 허용하는 텍스트 일부는 PrimaryExpression 으로 유효하지 않다.

Note 2

객체 내 이름 문자열이 중복될 경우 동일 키의 앞선 값들은 덮어써진다.

25.5.1.2 InternalizeJSONProperty ( holder, name, reviver )

The abstract operation InternalizeJSONProperty takes arguments holder (an Object), name (a String), and reviver (a function object) and returns 정상 완료(ECMAScript 언어 값) 또는 throw completion.

Note

이 알고리즘은 [[Delete]] 또는 CreateDataPropertyfalse 를 반환해도 예외를 던지지 않도록 의도되었다.

호출 시 다음 단계를 수행한다:

  1. val = ? Get(holder, name).
  2. val 이 Object 이면
    1. isArray = ? IsArray(val).
    2. isArray = true 이면
      1. len = ? LengthOfArrayLike(val).
      2. I = 0.
      3. 반복, I < len 동안
        1. prop = ! ToString(𝔽(I)).
        2. newElement = ? InternalizeJSONProperty(val, prop, reviver).
        3. newElement = undefined 이면
          1. val.[[Delete]](prop) 수행.
        4. Else
          1. CreateDataProperty(val, prop, newElement) 수행.
        5. I = I + 1.
    3. Else
      1. keys = ? EnumerableOwnProperties(val, key).
      2. 각 String Pkeys 에 대해
        1. newElement = ? InternalizeJSONProperty(val, P, reviver).
        2. newElement = undefined 이면
          1. val.[[Delete]](P) 수행.
        3. Else
          1. CreateDataProperty(val, P, newElement) 수행.
  3. Return ? Call(reviver, holder, « name, val »).

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

이 함수는 ECMAScript 언어 값을 UTF-16 인코딩된 JSON 형식 String 또는 undefined 로 반환한다. 세 매개변수를 받을 수 있다. value 는 일반적으로 객체나 배열이지만 String, Boolean, Number, null 일 수도 있다. 선택적 replacer 는 객체/배열을 문자열화하는 방식을 바꾸는 함수이거나 문자열/숫자 배열(포함 리스트)이다. 선택적 space 는 결과에 공백을 삽입해 가독성을 높이기 위한 String 또는 Number 이다.

호출 시 다음 단계를 수행한다:

  1. stack = 새 빈 List.
  2. indent = 빈 문자열.
  3. PropertyList = undefined.
  4. ReplacerFunction = undefined.
  5. replacer 가 Object 이면
    1. IsCallable(replacer) = true 이면
      1. ReplacerFunction = replacer.
    2. Else
      1. isArray = ? IsArray(replacer).
      2. isArray = true 이면
        1. PropertyList = 새 빈 List.
        2. len = ? LengthOfArrayLike(replacer).
        3. k = 0.
        4. 반복, k < len 동안
          1. prop = ! ToString(𝔽(k)).
          2. v = ? Get(replacer, prop).
          3. item = undefined.
          4. v 가 String 이면
            1. item = v.
          5. Else if v 가 Number 이면
            1. item = ! ToString(v).
          6. Else if v 가 Object 이면
            1. v[[StringData]] 또는 [[NumberData]] 내부 슬롯이 있으면 item = ? ToString(v).
          7. itemundefined 그리고 PropertyListitem 이 없으면
            1. PropertyListitem 추가.
          8. k = k + 1.
  6. space 가 Object 이면
    1. space[[NumberData]] 내부 슬롯을 가지면
      1. space = ? ToNumber(space).
    2. Else if space[[StringData]] 내부 슬롯을 가지면
      1. space = ? ToString(space).
  7. space 가 Number 이면
    1. spaceMV = ! ToIntegerOrInfinity(space).
    2. spaceMV = min(10, spaceMV).
    3. spaceMV < 1 이면 gap = 빈 문자열; 아니면 gap = 코드 유닛 0x0020 (SPACE) * spaceMV 개.
  8. Else if space 가 String 이면
    1. space 길이 ≤ 10 이면 gap = space; 아니면 gap = space 의 0~10 부분 문자열.
  9. Else
    1. gap = 빈 문자열.
  10. wrapper = OrdinaryObjectCreate(%Object.prototype%).
  11. CreateDataPropertyOrThrow(wrapper, 빈 문자열, value) 수행.
  12. state = JSON Serialization Record { [[ReplacerFunction]]: ReplacerFunction, [[Stack]]: stack, [[Indent]]: indent, [[Gap]]: gap, [[PropertyList]]: PropertyList }.
  13. Return ? SerializeJSONProperty(state, 빈 문자열, wrapper).

이 함수의 "length" 프로퍼티는 3𝔽이다.

Note 1

JSON 구조는 임의 깊이로 중첩 가능하지만 비순환이어야 한다. value 가 순환 구조이면 TypeError 예외를 던져야 한다. 예:

a = [];
a[0] = a;
my_text = JSON.stringify(a); // 여기서는 TypeError 가 발생해야 함.
Note 2

기호적(심볼이 아님) 기본 값들은 다음과 같이 표현된다:

  • null 값 → 문자열 "null".
  • undefined 값 → 렌더되지 않음.
  • true 값 → 문자열 "true".
  • false 값 → 문자열 "false".
Note 3

문자열 값은 QUOTATION MARK (") 코드 유닛으로 둘러싸인다. 코드 유닛 "\\ 접두로 이스케이프. 제어 문자 코드 유닛은 \uHHHH 또는 더 짧은 \b, \f, \n, \r, \t 로 대체.

Note 4

유한수는 ToString(number) 호출과 같이 문자열화된다. 부호와 무관하게 NaN, Infinity 는 문자열 "null" 로 표현.

Note 5

JSON 표현이 없는 값(undefined, 함수 등)은 문자열을 생성하지 않고 undefined 반환. 배열에서는 "null" 로, 객체에서는 해당 프로퍼티가 제외된다.

Note 6

객체는 U+007B 후 0개 이상 프로퍼티 (U+002C 로 구분), U+007D 로 닫힘. 프로퍼티는 따옴표로 둘러싼 이름, U+003A, 문자열화된 값. 배열은 U+005B 후 값들(콤마 구분), U+005D 로 닫힘.

25.5.2.1 JSON Serialization Record

JSON Serialization Record 는 JSON 형식 직렬화를 가능하게 하는 Record 값이다.

JSON Serialization Record 는 Table 78 필드를 가진다.

Table 78: JSON Serialization Record 필드
필드 이름 의미
[[ReplacerFunction]] 함수 객체 또는 undefined 객체 프로퍼티 대체 값을 제공 (JSON.stringify 의 replacer).
[[PropertyList]] 문자열 List 또는 undefined 비배열 객체 직렬화 시 포함할 프로퍼티 이름들 (replacer).
[[Gap]] String 들여쓰기 단위 (space).
[[Stack]] Object List 직렬화 진행 중 중첩 객체 집합 (순환 감지).
[[Indent]] String 현재 들여쓰기.

25.5.2.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 정상 완료(String 또는 undefined) 또는 throw completion. It performs the following steps when called:

  1. value = ? Get(holder, key).
  2. value 가 Object 또는 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. [[NumberData]] 슬롯 있으면 value = ? ToNumber(value).
    2. Else if [[StringData]] 슬롯 있으면 value = ? ToString(value).
    3. Else if [[BooleanData]] 슬롯 있으면 value = value.[[BooleanData]].
    4. Else if [[BigIntData]] 슬롯 있으면 value = value.[[BigIntData]].
  5. value = null 이면 "null" 반환.
  6. value = true 이면 "true" 반환.
  7. value = false 이면 "false" 반환.
  8. value 가 String 이면 QuoteJSONString(value) 반환.
  9. value 가 Number 이면
    1. value유한수면 ! ToString(value) 반환.
    2. "null" 반환.
  10. value 가 BigInt 이면 TypeError 예외.
  11. value 가 Object 이고 IsCallable(value) = false 이면
    1. isArray = ? IsArray(value).
    2. isArray = true 이면 ? SerializeJSONArray(state, value) 반환.
    3. Return ? SerializeJSONObject(state, value).
  12. Return undefined.

25.5.2.3 QuoteJSONString ( value )

The abstract operation QuoteJSONString takes argument value (a String) and returns String. value 를 0x0022 (QUOTATION MARK) 코드 유닛으로 감싸고 특정 코드 유닛을 이스케이프한다. 이 연산은 6.1.4 에 기술된 대로 value 를 UTF-16 인코딩 코드 포인트 시퀀스로 해석한다. It performs the following steps when called:

  1. product = 코드 유닛 0x0022 로만 구성된 String.
  2. StringToCodePoints(value) 의 각 코드 포인트 C 에 대해
    1. CTable 79 “Code Point” 열에 나열되면
      1. product = product + 해당 행 “Escape Sequence” 열의 이스케이프 시퀀스.
    2. Else if C 의 수치값 < 0x0020 또는 선행/후행 서로게이트와 동일 수치값이면
      1. unit = C 의 수치값을 가진 코드 유닛.
      2. product = product + UnicodeEscape(unit).
    3. Else
      1. product = product + UTF16EncodeCodePoint(C).
  3. product = product + 코드 유닛 0x0022.
  4. Return product.
Table 79: JSON 단일 문자 이스케이프 시퀀스
Code Point 유니코드 이름 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.2.4 UnicodeEscape ( C )

The abstract operation UnicodeEscape takes argument C (a code unit) and returns String. C 를 유니코드 이스케이프 시퀀스로 표현한다. It performs the following steps when called:

  1. n = C 의 수치값.
  2. Assert: n ≤ 0xFFFF.
  3. hex = n 의 소문자 16진수 문자열 표현.
  4. Return 코드 유닛 0x005C (REVERSE SOLIDUS) + "u" + StringPad(hex, 4, "0", start).

25.5.2.5 SerializeJSONObject ( state, value )

The abstract operation SerializeJSONObject takes arguments state (a JSON Serialization Record) and value (an Object) and returns 정상 완료(String) 또는 throw completion. 객체를 직렬화한다. It performs the following steps when called:

  1. state.[[Stack]]value 를 포함하면 순환 구조이므로 TypeError 예외.
  2. state.[[Stack]]value 추가.
  3. stepBack = state.[[Indent]].
  4. state.[[Indent]] = state.[[Indent]] + state.[[Gap]].
  5. state.[[PropertyList]]undefined 이면
    1. K = state.[[PropertyList]].
  6. Else
    1. K = ? EnumerableOwnProperties(value, key).
  7. partial = 새 빈 List.
  8. K 요소 P 에 대해
    1. strP = ? SerializeJSONProperty(state, P, value).
    2. strPundefined 이면
      1. member = QuoteJSONString(P).
      2. member = member + ":".
      3. state.[[Gap]] ≠ 빈 문자열이면
        1. member = member + 코드 유닛 0x0020 (SPACE).
      4. member = member + strP.
      5. partialmember 추가.
  9. partial 이 비어 있으면
    1. final = "{}".
  10. Else
    1. state.[[Gap]] = 빈 문자열이면
      1. properties = partial 요소를 0x002C (COMMA) 로 연결한 String (선/후방 콤마 없음).
      2. final = "{" + properties + "}".
    2. Else
      1. separator = 0x002C (COMMA) + 0x000A (LINE FEED) + state.[[Indent]].
      2. properties = partial 요소를 separator 로 연결한 String.
      3. final = "{" + 0x000A + state.[[Indent]] + properties + 0x000A + stepBack + "}".
  11. state.[[Stack]] 마지막 요소 제거.
  12. state.[[Indent]] = stepBack.
  13. Return final.

25.5.2.6 SerializeJSONArray ( state, value )

The abstract operation SerializeJSONArray takes arguments state (a JSON Serialization Record) and value (an ECMAScript language value) and returns 정상 완료(String) 또는 throw completion. 배열을 직렬화한다. It performs the following steps when called:

  1. state.[[Stack]]value 포함하면 순환이므로 TypeError 예외.
  2. state.[[Stack]]value 추가.
  3. stepBack = state.[[Indent]].
  4. state.[[Indent]] = state.[[Indent]] + state.[[Gap]].
  5. partial = 새 빈 List.
  6. len = ? LengthOfArrayLike(value).
  7. index = 0.
  8. 반복, index < len 동안
    1. strP = ? SerializeJSONProperty(state, ! ToString(𝔽(index)), value).
    2. strP = undefined 이면
      1. partial"null" 추가.
    3. Else
      1. partialstrP 추가.
    4. index = index + 1.
  9. partial 비어 있으면
    1. final = "[]".
  10. Else
    1. state.[[Gap]] = 빈 문자열이면
      1. properties = partial 요소를 0x002C (COMMA) 로 연결.
      2. final = "[" + properties + "]".
    2. Else
      1. separator = 0x002C (COMMA) + 0x000A (LINE FEED) + state.[[Indent]].
      2. properties = partial 요소를 separator 로 연결.
      3. final = "[" + 0x000A + state.[[Indent]] + properties + 0x000A + stepBack + "]".
  11. state.[[Stack]] 마지막 요소 제거.
  12. state.[[Indent]] = stepBack.
  13. Return final.
Note

배열 표현은 +0𝔽 이상 array.length 미만 인덱스 요소만 포함한다. 배열 인덱스가 아닌 키 프로퍼티는 제외된다. 배열은 여는 대괄호, 콤마로 구분된 요소, 닫는 대괄호로 문자열화된다.

25.5.3 JSON [ %Symbol.toStringTag% ]

%Symbol.toStringTag% 프로퍼티 초기 값은 String "JSON" 이다.

이 프로퍼티 특성은 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }.

26 메모리 관리 (Managing Memory)

26.1 WeakRef 객체

WeakRef 는 대상 객체나 심볼을 가비지 컬렉션으로부터 유지하지(보호하지) 않은 채로 참조하기 위해 사용되는 객체이다. WeakRef 는 대상이 아직 가비지 컬렉션에 의해 회수되지 않았다면 대상 값에 접근할 수 있도록 역참조(dereference)될 수 있다.

26.1.1 WeakRef 생성자

WeakRef 생성자:

  • %WeakRef% 이다.
  • 전역 객체"WeakRef" 프로퍼티 초기 값이다.
  • 생성자로 호출될 때 새 WeakRef 를 생성하고 초기화한다.
  • 함수로 호출하도록 의도되지 않았으며 그렇게 호출되면 예외를 던진다.
  • 클래스 정의의 extends 절 값으로 사용할 수 있다. 지정된 WeakRef 동작을 상속하려는 서브클래스 생성자WeakRef.prototype 내장 메서드를 지원하는 데 필요한 내부 상태로 서브클래스 인스턴스를 생성·초기화하기 위해 WeakRef 생성자에 대한 super 호출을 포함해야 한다.

26.1.1.1 WeakRef ( target )

이 함수는 호출 시 다음 단계를 수행한다:

  1. NewTarget 이 undefined 이면 TypeError 예외를 던진다.
  2. CanBeHeldWeakly(target) 이 false 이면 TypeError 예외를 던진다.
  3. weakRef = ? OrdinaryCreateFromConstructor(NewTarget, "%WeakRef.prototype%", « [[WeakRefTarget]] »).
  4. AddToKeptObjects(target) 수행.
  5. weakRef.[[WeakRefTarget]]target 으로 설정.
  6. weakRef 반환.

26.1.2 WeakRef 생성자의 프로퍼티

WeakRef 생성자:

  • 값이 %Function.prototype%[[Prototype]] 내부 슬롯을 가진다.
  • 다음 프로퍼티를 가진다:

26.1.2.1 WeakRef.prototype

WeakRef.prototype 의 초기 값은 WeakRef 프로토타입 객체이다.

이 프로퍼티는 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false } 속성을 가진다.

26.1.3 WeakRef 프로토타입 객체의 프로퍼티

WeakRef 프로토타입 객체:

  • %WeakRef.prototype% 이다.
  • 값이 %Object.prototype%[[Prototype]] 내부 슬롯을 가진다.
  • 일반 객체이다.
  • [[WeakRefTarget]] 내부 슬롯을 가지지 않는다.
Normative Optional

26.1.3.1 WeakRef.prototype.constructor

WeakRef.prototype.constructor 의 초기 값은 %WeakRef% 이다.

26.1.3.2 WeakRef.prototype.deref ( )

이 메서드는 호출 시 다음 단계를 수행한다:

  1. weakRefthis 값으로 둔다.
  2. RequireInternalSlot(weakRef, [[WeakRefTarget]]) 수행.
  3. WeakRefDeref(weakRef) 를 반환.
Note

WeakRefundefined 가 아닌 target 값을 반환한다면, 현재 ECMAScript 코드 실행이 완료될 때까지 이 target 값은 가비지 컬렉션되지 않아야 한다. AddToKeptObjects 연산이 읽기 일관성이 유지되도록 보장한다.

let target = { foo() {} };
let weakRef = new WeakRef(target);

// ... later ...

if (weakRef.deref()) {
  weakRef.deref().foo();
}

위 예에서 첫 번째 deref 가 undefined 로 평가되지 않는다면 두 번째 deref 또한 undefined 가 될 수 없다.

26.1.3.3 WeakRef.prototype [ %Symbol.toStringTag% ]

%Symbol.toStringTag% 프로퍼티 초기 값은 String "WeakRef" 이다.

이 프로퍼티는 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true } 속성을 가진다.

26.1.4 WeakRef 추상 연산

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. target = weakRef.[[WeakRefTarget]].
  2. targetempty 가 아니면
    1. AddToKeptObjects(target) 수행.
    2. target 반환.
  3. undefined 반환.
Note

이 추상 연산은 liveness 를 간단히 정의할 수 있도록 WeakRef.prototype.deref 와 분리되어 정의된다.

26.1.5 WeakRef 인스턴스의 프로퍼티

WeakRef 인스턴스는 WeakRef 프로토타입 객체로부터 프로퍼티를 상속하는 일반 객체이다. 또한 [[WeakRefTarget]] 내부 슬롯을 가진다.

26.2 FinalizationRegistry 객체

FinalizationRegistry 는 대상 객체와 심볼이 가비지 컬렉션될 때 수행되는 정리(cleanup) 동작의 등록 및 등록 해제를 관리하는 객체이다.

26.2.1 FinalizationRegistry 생성자

FinalizationRegistry 생성자:

  • %FinalizationRegistry% 이다.
  • 전역 객체"FinalizationRegistry" 프로퍼티 초기 값이다.
  • 생성자로 호출될 때 새 FinalizationRegistry 를 생성·초기화한다.
  • 함수로 호출하도록 의도되지 않았으며 그렇게 호출되면 예외를 던진다.
  • 클래스 정의의 extends 절 값으로 사용할 수 있다. 지정된 FinalizationRegistry 동작을 상속하려는 서브클래스 생성자FinalizationRegistry.prototype 내장 메서드를 지원하는 데 필요한 내부 상태로 서브클래스 인스턴스를 생성·초기화하기 위해 FinalizationRegistry 생성자에 대한 super 호출을 포함해야 한다.

26.2.1.1 FinalizationRegistry ( cleanupCallback )

이 함수는 호출 시 다음 단계를 수행한다:

  1. NewTarget 이 undefined 이면 TypeError 예외를 던진다.
  2. IsCallable(cleanupCallback) 이 false 이면 TypeError 예외를 던진다.
  3. finalizationRegistry = ? OrdinaryCreateFromConstructor(NewTarget, "%FinalizationRegistry.prototype%", « [[Realm]], [[CleanupCallback]], [[Cells]] »).
  4. fn = 활성 함수 객체로 둔다.
  5. finalizationRegistry.[[Realm]] = fn.[[Realm]] 로 설정.
  6. finalizationRegistry.[[CleanupCallback]] = HostMakeJobCallback(cleanupCallback) 로 설정.
  7. finalizationRegistry.[[Cells]] = 새 빈 List 로 설정.
  8. finalizationRegistry 반환.

26.2.2 FinalizationRegistry 생성자의 프로퍼티

FinalizationRegistry 생성자:

  • 값이 %Function.prototype%[[Prototype]] 내부 슬롯을 가진다.
  • 다음 프로퍼티를 가진다:

26.2.2.1 FinalizationRegistry.prototype

FinalizationRegistry.prototype 의 초기 값은 FinalizationRegistry 프로토타입 객체이다.

이 프로퍼티는 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false } 속성을 가진다.

26.2.3 FinalizationRegistry 프로토타입 객체의 프로퍼티

FinalizationRegistry 프로토타입 객체:

  • %FinalizationRegistry.prototype% 이다.
  • 값이 %Object.prototype%[[Prototype]] 내부 슬롯을 가진다.
  • 일반 객체이다.
  • [[Cells]][[CleanupCallback]] 내부 슬롯을 가지지 않는다.

26.2.3.1 FinalizationRegistry.prototype.constructor

FinalizationRegistry.prototype.constructor 의 초기 값은 %FinalizationRegistry% 이다.

26.2.3.2 FinalizationRegistry.prototype.register ( target, heldValue [ , unregisterToken ] )

이 메서드는 호출 시 다음 단계를 수행한다:

  1. finalizationRegistrythis 값으로 둔다.
  2. RequireInternalSlot(finalizationRegistry, [[Cells]]) 수행.
  3. CanBeHeldWeakly(target) 이 false 이면 TypeError 예외.
  4. SameValue(target, heldValue) = true 이면 TypeError 예외.
  5. CanBeHeldWeakly(unregisterToken) 이 false 이면
    1. unregisterTokenundefined 가 아니면 TypeError 예외.
    2. unregisterToken = empty 로 설정.
  6. cell = Record { [[WeakRefTarget]]: target, [[HeldValue]]: heldValue, [[UnregisterToken]]: unregisterToken }.
  7. finalizationRegistry.[[Cells]]cell 추가.
  8. undefined 반환.
Note

명세의 알고리즘과 정의에 따르면 finalizationRegistry.[[Cells]]cell 을 포함하는 동안 cell.[[HeldValue]]live 이다; 그러나 이것이 반드시 cell.[[UnregisterToken]] 또는 cell.[[Target]]live 임을 의미하지는 않는다. 예를 들어 객체를 자기 자신을 unregister token 으로 하여 등록해도 그 객체를 영원히 살려 두지 않는다.

26.2.3.3 FinalizationRegistry.prototype.unregister ( unregisterToken )

이 메서드는 호출 시 다음 단계를 수행한다:

  1. finalizationRegistrythis 값으로 둔다.
  2. RequireInternalSlot(finalizationRegistry, [[Cells]]) 수행.
  3. CanBeHeldWeakly(unregisterToken) 이 false 이면 TypeError 예외.
  4. removed = false 로 둔다.
  5. finalizationRegistry.[[Cells]] 의 각 Record { [[WeakRefTarget]], [[HeldValue]], [[UnregisterToken]] } cell 에 대해
    1. cell.[[UnregisterToken]]empty 가 아니고 SameValue(cell.[[UnregisterToken]], unregisterToken) = true 이면
      1. finalizationRegistry.[[Cells]] 에서 cell 제거.
      2. removed = true 로 설정.
  6. removed 반환.

26.2.3.4 FinalizationRegistry.prototype [ %Symbol.toStringTag% ]

%Symbol.toStringTag% 프로퍼티 초기 값은 String "FinalizationRegistry" 이다.

이 프로퍼티는 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true } 속성을 가진다.

26.2.4 FinalizationRegistry 인스턴스의 프로퍼티

FinalizationRegistry 인스턴스는 FinalizationRegistry 프로토타입 객체로부터 프로퍼티를 상속하는 일반 객체이다. 또한 [[Cells]][[CleanupCallback]] 내부 슬롯을 가진다.

27 제어 추상화 객체 (Control Abstraction Objects)

27.1 반복 (Iteration)

27.1.1 공통 반복 인터페이스 (Common Iteration Interfaces)

인터페이스는 특정 명세를 만족하는 값들을 갖는 프로퍼티 키들의 집합이다. 어떤 객체가 한 인터페이스 명세에 기술된 모든 프로퍼티를 제공하면 그 객체는 그 인터페이스를 준수(conform)한다고 한다. 인터페이스 자체가 별도의 객체로 표현되지는 않는다. 하나의 인터페이스를 준수하는 개별적으로 구현된 객체는 여럿 있을 수 있다. 하나의 객체가 여러 인터페이스를 동시에 준수할 수도 있다.

27.1.1.1 Iterable 인터페이스 (The Iterable Interface)

iterable 인터페이스Table 80에 기술된 프로퍼티를 포함한다:

Table 80: Iterable 인터페이스 필수 프로퍼티 (Iterable Interface Required Properties)
프로퍼티 (Property) 값 (Value) 요구사항 (Requirements)
%Symbol.iterator% 이터레이터 객체를 반환하는 함수 반환된 객체는 iterator 인터페이스를 준수해야 한다.

27.1.1.2 Iterator 인터페이스 (The Iterator Interface)

iterator 인터페이스를 구현하는 객체는 Table 81의 프로퍼티를 포함해야 한다. 그러한 객체는 Table 82의 프로퍼티를 추가로 구현할 수도 있다.

Table 81: Iterator 인터페이스 필수 프로퍼티 (Iterator Interface Required Properties)
프로퍼티 요구사항
"next" IteratorResult 객체를 반환하는 함수 반환된 객체는 IteratorResult 인터페이스를 준수해야 한다. 어떤 이터레이터의 next 메서드에 대한 이전 호출이 "done" 프로퍼티가 true인 IteratorResult 객체를 반환했다면, 그 객체에 대한 이후의 모든 next 호출도 "done" 프로퍼티가 true인 IteratorResult 객체를 반환해야 한다. 그러나 이 요구사항은 강제되지 않는다.
Note 1

next 함수에 인수를 전달할 수 있지만, 그것들의 해석 및 유효성은 대상 이터레이터에 의존한다. for-of 문 및 기타 일반적인 이터레이터 소비자는 어떤 인수도 전달하지 않으므로, 그러한 방식으로 사용될 것을 기대하는 이터레이터 객체는 인수 없이 호출되는 상황을 처리할 준비가 되어 있어야 한다.

Table 82: Iterator 인터페이스 선택적 프로퍼티 (Iterator Interface Optional Properties)
프로퍼티 요구사항
"return" IteratorResult 객체를 반환하는 함수 반환된 객체는 IteratorResult 인터페이스를 준수해야 한다. 이 메서드를 호출하면 호출자가 더 이상 이터레이터의 next 메서드를 호출할 의도가 없음을 이터레이터 객체에 알린다. 반환된 IteratorResult 객체는 대개 "done" 프로퍼티 값이 true이고, return 메서드의 인수로 전달된 값을 가진 "value" 프로퍼티를 가진다. 그러나 이 요구사항은 강제되지 않는다.
"throw" IteratorResult 객체를 반환하는 함수 반환된 객체는 IteratorResult 인터페이스를 준수해야 한다. 이 메서드를 호출하면 호출자가 에러 상태를 감지했음을 이터레이터 객체에 알린다. 인수는 에러 상태를 식별하는 데 사용될 수 있고 일반적으로 예외 객체일 것이다. 일반적인 반응은 인수로 전달된 값을 throw하는 것이다. 메서드가 throw하지 않는 경우, 반환된 IteratorResult 객체는 대개 "done" 프로퍼티 값이 true이다.
Note 2

보통 이러한 메서드의 호출자는 호출 전에 그 존재를 확인해야 한다. for-of, yield*, 배열 구조 분해 등을 포함한 특정 ECMAScript 언어 기능은 존재 여부를 확인한 후 이들 메서드를 호출한다. 이터러블 객체를 인수로 받는 대부분의 ECMAScript 라이브러리 함수도 조건부로 이들을 호출한다.

27.1.1.3 Async Iterable 인터페이스 (The Async Iterable Interface)

async iterable 인터페이스Table 83에 기술된 프로퍼티를 포함한다:

Table 83: Async Iterable 인터페이스 필수 프로퍼티 (Async Iterable Interface Required Properties)
프로퍼티 요구사항
%Symbol.asyncIterator% async 이터레이터 객체를 반환하는 함수 반환된 객체는 async iterator 인터페이스를 준수해야 한다.

27.1.1.4 Async Iterator 인터페이스 (The Async Iterator Interface)

async iterator 인터페이스를 구현하는 객체는 Table 84의 프로퍼티를 포함해야 한다. 그러한 객체는 Table 85의 프로퍼티를 추가로 구현할 수도 있다.

Table 84: Async Iterator 인터페이스 필수 프로퍼티 (Async Iterator Interface Required Properties)
프로퍼티 요구사항
"next" IteratorResult 객체에 대한 promise 를 반환하는 함수

반환된 promise가 이행(fulfill)될 때, IteratorResult 인터페이스를 준수하는 객체로 이행해야 한다. 어떤 async iteratornext 메서드에 대한 이전 호출이 "done" 프로퍼티가 true인 IteratorResult 객체에 대한 promise를 반환했다면, 그 객체의 이후 모든 next 호출 역시 "done" 프로퍼티가 true인 IteratorResult 객체에 대한 promise를 반환해야 한다. 그러나 이 요구사항은 강제되지 않는다.

추가로, 이행 값으로 사용되는 IteratorResult 객체는 promise(또는 "thenable")가 아닌 값을 가진 "value" 프로퍼티를 가져야 한다. 하지만 이 요구사항 또한 강제되지 않는다.

Note 1

next 함수에 인수를 전달할 수 있지만, 그것들의 해석 및 유효성은 대상 async iterator에 의존한다. for-await-of 문 및 기타 일반적인 async iterator 소비자는 인수를 전달하지 않으므로, 그러한 방식으로 사용될 것을 기대하는 async iterator 객체는 인수 없이 호출되는 상황을 처리할 준비가 되어 있어야 한다.

Table 85: Async Iterator 인터페이스 선택적 프로퍼티 (Async Iterator Interface Optional Properties)
프로퍼티 요구사항
"return" IteratorResult 객체에 대한 promise 를 반환하는 함수

반환된 promise가 이행될 때, IteratorResult 인터페이스를 준수하는 객체로 이행해야 한다. 이 메서드를 호출하면 호출자가 async iteratornext 메서드를 더 이상 호출할 의도가 없음을 async iterator 객체에 알린다. 반환되는 promise는 대개 "done" 프로퍼티 값이 true이고, return 메서드의 인수로 전달된 값을 가진 "value" 프로퍼티가 있는 IteratorResult 객체로 이행된다. 그러나 이 요구사항은 강제되지 않는다.

추가로, 이행 값으로 사용되는 IteratorResult 객체는 promise(또는 "thenable")가 아닌 값을 가진 "value" 프로퍼티를 가져야 한다. 인수 값이 일반적인 방식으로 사용되는 경우, 만약 그것이 거부된(rejected) promise라면 동일한 reason으로 거부된 promise가 반환되어야 하고, 이행된(fulfilled) promise라면 그 이행 값을 반환 promise의 IteratorResult 객체 이행 값의 "value" 프로퍼티로 사용해야 한다. 그러나 이러한 요구사항들도 강제되지 않는다.

"throw" IteratorResult 객체에 대한 promise 를 반환하는 함수

반환된 promise가 이행될 때, IteratorResult 인터페이스를 준수하는 객체로 이행해야 한다. 이 메서드를 호출하면 호출자가 에러 상태를 감지했음을 async iterator 객체에 알린다. 인수는 에러 상태를 식별하는 데 사용될 수 있으며 일반적으로 예외 객체일 것이다. 전형적인 반응은 인수로 전달된 값으로 거부되는(rejected) promise를 반환하는 것이다.

반환된 promise가 이행되는 경우, IteratorResult 객체 이행 값은 보통 "done" 프로퍼티 값이 true이다. 또한 "value" 프로퍼티는 promise(또는 "thenable")가 아닌 값을 가져야 하지만, 이 요구사항은 강제되지 않는다.

Note 2

일반적으로 이러한 메서드의 호출자는 호출 전에 그 존재를 확인해야 한다. for-await-ofyield* 등을 포함한 특정 ECMAScript 언어 기능은 존재 여부를 확인한 뒤 이들 메서드를 호출한다.

27.1.1.5 IteratorResult 인터페이스 (The IteratorResult Interface)

IteratorResult 인터페이스Table 86에 열거된 프로퍼티를 포함한다:

Table 86: IteratorResult 인터페이스 프로퍼티 (IteratorResult Interface Properties)
프로퍼티 요구사항
"done" Boolean 이는 이터레이터 next 메서드 호출의 결과 상태이다. 이터레이터의 끝에 도달했다면 "done"true이다. 끝에 도달하지 않았다면 "done"false이며 값이 존재한다. "done" 프로퍼티(소유 또는 상속)가 존재하지 않는다면 그 값은 false로 간주한다.
"value" ECMAScript 언어 값 done 이 false이면, 이는 현재 반복 요소 값이다. done 이 true이면, 이는 이터레이터가 제공했다면 그 반환 값이다. 이터레이터에 반환 값이 없다면 "value"undefined이다. 그 경우, 객체가 명시적 "value" 프로퍼티를 상속하지 않는다면 "value" 프로퍼티는 준수 객체에서 생략될 수 있다.

27.1.2 Iterator Helper 객체 (Iterator Helper Objects)

Iterator Helper 객체는 특정 소스 이터레이터 객체의 지연(lazy) 변환을 표현하는 일반 객체이다. Iterator Helper 객체에 대한 명명된 생성자는 없다. 대신, Iterator Helper 객체는 Iterator 인스턴스 객체의 특정 메서드를 호출하여 생성된다.

27.1.2.1 %IteratorHelperPrototype% 객체 (The %IteratorHelperPrototype% Object)

%IteratorHelperPrototype% 객체:

27.1.2.1.1 %IteratorHelperPrototype%.next ( )

  1. GeneratorResume(this value, undefined, "Iterator Helper")를 반환한다.

27.1.2.1.2 %IteratorHelperPrototype%.return ( )

  1. Othis 값으로 둔다.
  2. RequireInternalSlot(O, [[UnderlyingIterator]])를 수행한다.
  3. O[[GeneratorState]] 내부 슬롯을 가지고 있음을 단언(Assert)한다.
  4. O.[[GeneratorState]]suspended-start 이면,
    1. O.[[GeneratorState]]completed 로 설정한다.
    2. 주: 한 번 generator가 completed 상태에 들어가면 다시 나오지 않고 그 연관 실행 컨텍스트는 재개되지 않는다. O 와 연관된 어떤 실행 상태도 이 시점에서 폐기될 수 있다.
    3. IteratorClose(O.[[UnderlyingIterator]], NormalCompletion(unused))를 수행한다.
    4. CreateIteratorResultObject(undefined, true)를 반환한다.
  5. CReturnCompletion(undefined)로 둔다.
  6. GeneratorResumeAbrupt(O, C, "Iterator Helper")를 반환한다.

27.1.2.1.3 %IteratorHelperPrototype% [ %Symbol.toStringTag% ]

%Symbol.toStringTag% 프로퍼티의 초기 값은 문자열 "Iterator Helper" 이다.

이 프로퍼티는 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true } 특성을 가진다.

27.1.3 Iterator 객체 (Iterator Objects)

27.1.3.1 Iterator 생성자 (The Iterator Constructor)

Iterator 생성자:

  • %Iterator% 이다.
  • 전역 객체"Iterator" 프로퍼티의 초기 값이다.
  • 서브클래싱 가능하도록 설계되었다. 클래스 정의의 extends 절 값으로 사용할 수 있다.

27.1.3.1.1 Iterator ( )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. NewTarget 이 undefined 이거나 활성 함수 객체라면 TypeError 예외를 던진다.
  2. OrdinaryCreateFromConstructor(NewTarget, "%Iterator.prototype%")를 반환한다.

27.1.3.2 Iterator 생성자의 프로퍼티 (Properties of the Iterator Constructor)

Iterator 생성자:

  • [[Prototype]] 내부 슬롯 값이 %Function.prototype%이다.
  • 다음 프로퍼티들을 가진다:

27.1.3.2.1 Iterator.from ( O )

  1. iteratorRecord 를 ? GetIteratorFlattenable(O, 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.1.1 %WrapForValidIteratorPrototype% 객체 (The %WrapForValidIteratorPrototype% Object)

%WrapForValidIteratorPrototype% 객체:

27.1.3.2.1.1.1 %WrapForValidIteratorPrototype%.next ( )

  1. Othis 값으로 둔다.
  2. RequireInternalSlot(O, [[Iterated]])를 수행한다.
  3. iteratorRecordO.[[Iterated]] 로 둔다.
  4. Call(iteratorRecord.[[NextMethod]], iteratorRecord.[[Iterator]])를 반환한다.

27.1.3.2.1.1.2 %WrapForValidIteratorPrototype%.return ( )

  1. Othis 값으로 둔다.
  2. RequireInternalSlot(O, [[Iterated]])를 수행한다.
  3. iteratorO.[[Iterated]].[[Iterator]] 로 둔다.
  4. iterator 가 Object 임을 단언한다.
  5. returnMethod 를 ? GetMethod(iterator, "return")로 둔다.
  6. returnMethodundefined 이면
    1. CreateIteratorResultObject(undefined, true)를 반환한다.
  7. Call(returnMethod, iterator)를 반환한다.

27.1.3.2.2 Iterator.prototype

Iterator.prototype의 초기 값은 Iterator 프로토타입 객체이다.

이 프로퍼티는 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false } 특성을 가진다.

27.1.4 Iterator 프로토타입 객체의 프로퍼티 (Properties of the Iterator Prototype Object)

Iterator 프로토타입 객체:

Note

이 명세에서 iterator 인터페이스를 구현하는 모든 객체는 %Iterator.prototype%을 상속한다. ECMAScript 코드는 또한 %Iterator.prototype%을 상속하는 객체를 정의할 수 있다. %Iterator.prototype%은 모든 iterator 객체에 적용 가능한 추가 메서드를 추가할 수 있는 장소를 제공한다.

다음 식은 ECMAScript 코드가 %Iterator.prototype% 객체에 접근할 수 있는 한 가지 방법이다:

Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()))

27.1.4.1 Iterator.prototype.constructor

Iterator.prototype.constructor 는 { [[Enumerable]]: false, [[Configurable]]: true } 특성을 가진 접근자 프로퍼티이다. [[Get]][[Set]] 특성은 다음과 같이 정의된다:

27.1.4.1.1 get Iterator.prototype.constructor

[[Get]] 특성의 값은 인수가 필요 없는 내장 함수이다. 호출 시 다음 단계를 수행한다:

  1. %Iterator% 를 반환한다.

27.1.4.1.2 set Iterator.prototype.constructor

[[Set]] 특성의 값은 인수 v 를 받는 내장 함수이다. 호출 시 다음 단계를 수행한다:

  1. SetterThatIgnoresPrototypeProperties(this value, %Iterator.prototype%, "constructor", v)를 수행한다.
  2. undefined 를 반환한다.
Note

대부분의 내장 프로토타입에 있는 "constructor" 프로퍼티와 달리, 웹 호환성 이유로 이 프로퍼티는 접근자여야 한다.

27.1.4.2 Iterator.prototype.drop ( limit )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. Othis 값으로 둔다.
  2. O 가 Object 가 아니면 TypeError 예외를 던진다.
  3. iteratedIterator Record { [[Iterator]]: O, [[NextMethod]]: undefined, [[Done]]: false } 로 둔다.
  4. numLimitCompletion(ToNumber(limit))로 둔다.
  5. IfAbruptCloseIterator(numLimit, iterated).
  6. numLimitNaN 이면,
    1. errorThrowCompletion(새로 생성된 RangeError 객체)로 둔다.
    2. IteratorClose(iterated, error)를 반환한다.
  7. integerLimit 를 ! ToIntegerOrInfinity(numLimit)로 둔다.
  8. integerLimit < 0 이면,
    1. errorThrowCompletion(새로 생성된 RangeError 객체)로 둔다.
    2. IteratorClose(iterated, error)를 반환한다.
  9. iterated 를 ? GetIteratorDirect(O)로 설정한다.
  10. closureiteratedintegerLimit 를 포획(capture)하는 매개변수 없는 새로운 Abstract Closure 로 두고, 호출 시 다음 단계를 수행하게 한다:
    1. remainingintegerLimit 로 둔다.
    2. remaining > 0 인 동안 반복,
      1. remaining ≠ +∞ 이면,
        1. remainingremaining - 1 로 설정한다.
      2. next 를 ? IteratorStep(iterated)로 둔다.
      3. nextdone 이면, ReturnCompletion(undefined)를 반환한다.
    3. 반복,
      1. value 를 ? IteratorStepValue(iterated)로 둔다.
      2. valuedone 이면, ReturnCompletion(undefined)를 반환한다.
      3. completionCompletion(Yield(value))로 둔다.
      4. IfAbruptCloseIterator(completion, iterated).
  11. resultCreateIteratorFromClosure(closure, "Iterator Helper", %IteratorHelperPrototype%, « [[UnderlyingIterator]] »)로 둔다.
  12. result.[[UnderlyingIterator]]iterated 로 설정한다.
  13. result 를 반환한다.

27.1.4.3 Iterator.prototype.every ( predicate )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. Othis 값으로 둔다.
  2. O 가 Object 가 아니면 TypeError 예외를 던진다.
  3. iteratedIterator Record { [[Iterator]]: O, [[NextMethod]]: undefined, [[Done]]: false } 로 둔다.
  4. IsCallable(predicate) 가 false 이면,
    1. errorThrowCompletion(새로 생성된 TypeError 객체)로 둔다.
    2. IteratorClose(iterated, error)를 반환한다.
  5. iterated 를 ? GetIteratorDirect(O)로 설정한다.
  6. counter 를 0 으로 둔다.
  7. 반복,
    1. value 를 ? IteratorStepValue(iterated)로 둔다.
    2. valuedone 이면 true 를 반환한다.
    3. resultCompletion(Call(predicate, undefined, « value, 𝔽(counter) »))로 둔다.
    4. IfAbruptCloseIterator(result, iterated).
    5. ToBoolean(result) 가 false 이면, ? IteratorClose(iterated, NormalCompletion(false))를 반환한다.
    6. countercounter + 1 로 설정한다.

27.1.4.4 Iterator.prototype.filter ( predicate )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. Othis 값으로 둔다.
  2. O 가 Object 가 아니면 TypeError 예외를 던진다.
  3. iteratedIterator Record { [[Iterator]]: O, [[NextMethod]]: undefined, [[Done]]: false } 로 둔다.
  4. IsCallable(predicate) 가 false 이면,
    1. errorThrowCompletion(새로 생성된 TypeError 객체)로 둔다.
    2. IteratorClose(iterated, error)를 반환한다.
  5. iterated 를 ? GetIteratorDirect(O)로 설정한다.
  6. closureiteratedpredicate 를 포획하는 매개변수 없는 새로운 Abstract Closure 로 두고, 호출 시 다음 단계를 수행하게 한다:
    1. counter 를 0 으로 둔다.
    2. 반복,
      1. value 를 ? IteratorStepValue(iterated)로 둔다.
      2. valuedone 이면 ReturnCompletion(undefined)를 반환한다.
      3. selectedCompletion(Call(predicate, undefined, « value, 𝔽(counter) »))로 둔다.
      4. IfAbruptCloseIterator(selected, iterated).
      5. ToBoolean(selected) 가 true 이면,
        1. completionCompletion(Yield(value))로 둔다.
        2. IfAbruptCloseIterator(completion, iterated).
      6. countercounter + 1 로 설정한다.
  7. resultCreateIteratorFromClosure(closure, "Iterator Helper", %IteratorHelperPrototype%, « [[UnderlyingIterator]] »)로 둔다.
  8. result.[[UnderlyingIterator]]iterated 로 설정한다.
  9. result 를 반환한다.

27.1.4.5 Iterator.prototype.find ( predicate )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. Othis 값으로 둔다.
  2. O 가 Object 가 아니면 TypeError 예외를 던진다.
  3. iteratedIterator Record { [[Iterator]]: O, [[NextMethod]]: undefined, [[Done]]: false } 로 둔다.
  4. IsCallable(predicate) 가 false 이면,
    1. errorThrowCompletion(새로 생성된 TypeError 객체)로 둔다.
    2. IteratorClose(iterated, error)를 반환한다.
  5. iterated 를 ? GetIteratorDirect(O)로 설정한다.
  6. counter 를 0 으로 둔다.
  7. 반복,
    1. value 를 ? IteratorStepValue(iterated)로 둔다.
    2. valuedone 이면 undefined 를 반환한다.
    3. resultCompletion(Call(predicate, undefined, « value, 𝔽(counter) »))로 둔다.
    4. IfAbruptCloseIterator(result, iterated).
    5. ToBoolean(result) 가 true 이면, ? IteratorClose(iterated, NormalCompletion(value))를 반환한다.
    6. countercounter + 1 로 설정한다.

27.1.4.6 Iterator.prototype.flatMap ( mapper )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. Othis 값으로 둔다.
  2. O 가 Object 가 아니면 TypeError 예외를 던진다.
  3. iteratedIterator Record { [[Iterator]]: O, [[NextMethod]]: undefined, [[Done]]: false } 로 둔다.
  4. IsCallable(mapper) 가 false 이면,
    1. errorThrowCompletion(새로 생성된 TypeError 객체)로 둔다.
    2. IteratorClose(iterated, error)를 반환한다.
  5. iterated 를 ? GetIteratorDirect(O)로 설정한다.
  6. closureiteratedmapper 를 포획하는 매개변수 없는 새로운 Abstract Closure 로 두고, 호출 시 다음 단계를 수행하게 한다:
    1. counter 를 0 으로 둔다.
    2. 반복,
      1. value 를 ? IteratorStepValue(iterated)로 둔다.
      2. valuedone 이면 ReturnCompletion(undefined)를 반환한다.
      3. mappedCompletion(Call(mapper, undefined, « value, 𝔽(counter) »))로 둔다.
      4. IfAbruptCloseIterator(mapped, iterated).
      5. innerIteratorCompletion(GetIteratorFlattenable(mapped, reject-primitives))로 둔다.
      6. IfAbruptCloseIterator(innerIterator, iterated).
      7. innerAlivetrue 로 둔다.
      8. innerAlivetrue 인 동안 반복,
        1. innerValueCompletion(IteratorStepValue(innerIterator))로 둔다.
        2. IfAbruptCloseIterator(innerValue, iterated).
        3. innerValuedone 이면,
          1. innerAlivefalse 로 설정한다.
        4. 그렇지 않으면,
          1. completionCompletion(Yield(innerValue))로 둔다.
          2. completionabrupt completion 이면,
            1. backupCompletionCompletion(IteratorClose(innerIterator, completion))로 둔다.
            2. IfAbruptCloseIterator(backupCompletion, iterated).
            3. IteratorClose(iterated, completion)를 반환한다.
      9. countercounter + 1 로 설정한다.
  7. resultCreateIteratorFromClosure(closure, "Iterator Helper", %IteratorHelperPrototype%, « [[UnderlyingIterator]] »)로 둔다.
  8. result.[[UnderlyingIterator]]iterated 로 설정한다.
  9. result 를 반환한다.

27.1.4.7 Iterator.prototype.forEach ( procedure )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. Othis 값으로 둔다.
  2. O 가 Object 가 아니면 TypeError 예외를 던진다.
  3. iteratedIterator Record { [[Iterator]]: O, [[NextMethod]]: undefined, [[Done]]: false } 로 둔다.
  4. IsCallable(procedure) 가 false 이면,
    1. errorThrowCompletion(새로 생성된 TypeError 객체)로 둔다.
    2. IteratorClose(iterated, error)를 반환한다.
  5. iterated 를 ? GetIteratorDirect(O)로 설정한다.
  6. counter 를 0 으로 둔다.
  7. 반복,
    1. value 를 ? IteratorStepValue(iterated)로 둔다.
    2. valuedone 이면 undefined 를 반환한다.
    3. resultCompletion(Call(procedure, undefined, « value, 𝔽(counter) »))로 둔다.
    4. IfAbruptCloseIterator(result, iterated).
    5. countercounter + 1 로 설정한다.

27.1.4.8 Iterator.prototype.map ( mapper )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. Othis 값으로 둔다.
  2. O 가 Object 가 아니면 TypeError 예외를 던진다.
  3. iteratedIterator Record { [[Iterator]]: O, [[NextMethod]]: undefined, [[Done]]: false } 로 둔다.
  4. IsCallable(mapper) 가 false 이면,
    1. errorThrowCompletion(새로 생성된 TypeError 객체)로 둔다.
    2. IteratorClose(iterated, error)를 반환한다.
  5. iterated 를 ? GetIteratorDirect(O)로 설정한다.
  6. closureiteratedmapper 를 포획하는 매개변수 없는 새로운 Abstract Closure 로 두고, 호출 시 다음 단계를 수행하게 한다:
    1. counter 를 0 으로 둔다.
    2. 반복,
      1. value 를 ? IteratorStepValue(iterated)로 둔다.
      2. valuedone 이면 ReturnCompletion(undefined)를 반환한다.
      3. mappedCompletion(Call(mapper, undefined, « value, 𝔽(counter) »))로 둔다.
      4. IfAbruptCloseIterator(mapped, iterated).
      5. completionCompletion(Yield(mapped))로 둔다.
      6. IfAbruptCloseIterator(completion, iterated).
      7. countercounter + 1 로 설정한다.
  7. resultCreateIteratorFromClosure(closure, "Iterator Helper", %IteratorHelperPrototype%, « [[UnderlyingIterator]] »)로 둔다.
  8. result.[[UnderlyingIterator]]iterated 로 설정한다.
  9. result 를 반환한다.

27.1.4.9 Iterator.prototype.reduce ( reducer [ , initialValue ] )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. Othis 값으로 둔다.
  2. O 가 Object 가 아니면 TypeError 예외를 던진다.
  3. iteratedIterator Record { [[Iterator]]: O, [[NextMethod]]: undefined, [[Done]]: false } 로 둔다.
  4. IsCallable(reducer) 가 false 이면,
    1. errorThrowCompletion(새로 생성된 TypeError 객체)로 둔다.
    2. IteratorClose(iterated, error)를 반환한다.
  5. iterated 를 ? GetIteratorDirect(O)로 설정한다.
  6. initialValue 가 존재하지 않으면,
    1. accumulator 를 ? IteratorStepValue(iterated)로 둔다.
    2. accumulatordone 이면 TypeError 예외를 던진다.
    3. counter 를 1 로 둔다.
  7. 그렇지 않으면,
    1. accumulatorinitialValue 로 둔다.
    2. counter 를 0 으로 둔다.
  8. 반복,
    1. value 를 ? IteratorStepValue(iterated)로 둔다.
    2. valuedone 이면 accumulator 를 반환한다.
    3. resultCompletion(Call(reducer, undefined, « accumulator, value, 𝔽(counter) »))로 둔다.
    4. IfAbruptCloseIterator(result, iterated).
    5. accumulatorresult 로 설정한다.
    6. countercounter + 1 로 설정한다.

27.1.4.10 Iterator.prototype.some ( predicate )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. Othis 값으로 둔다.
  2. O 가 Object 가 아니면 TypeError 예외를 던진다.
  3. iteratedIterator Record { [[Iterator]]: O, [[NextMethod]]: undefined, [[Done]]: false } 로 둔다.
  4. IsCallable(predicate) 가 false 이면,
    1. errorThrowCompletion(새로 생성된 TypeError 객체)로 둔다.
    2. IteratorClose(iterated, error)를 반환한다.
  5. iterated 를 ? GetIteratorDirect(O)로 설정한다.
  6. counter 를 0 으로 둔다.
  7. 반복,
    1. value 를 ? IteratorStepValue(iterated)로 둔다.
    2. valuedone 이면 false 를 반환한다.
    3. resultCompletion(Call(predicate, undefined, « value, 𝔽(counter) »))로 둔다.
    4. IfAbruptCloseIterator(result, iterated).
    5. ToBoolean(result) 가 true 이면, ? IteratorClose(iterated, NormalCompletion(true))를 반환한다.
    6. countercounter + 1 로 설정한다.

27.1.4.11 Iterator.prototype.take ( limit )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. Othis 값으로 둔다.
  2. O 가 Object 가 아니면 TypeError 예외를 던진다.
  3. iteratedIterator Record { [[Iterator]]: O, [[NextMethod]]: undefined, [[Done]]: false } 로 둔다.
  4. numLimitCompletion(ToNumber(limit))로 둔다.
  5. IfAbruptCloseIterator(numLimit, iterated).
  6. numLimitNaN 이면,
    1. errorThrowCompletion(새로 생성된 RangeError 객체)로 둔다.
    2. IteratorClose(iterated, error)를 반환한다.
  7. integerLimit 를 ! ToIntegerOrInfinity(numLimit)로 둔다.
  8. integerLimit < 0 이면,
    1. errorThrowCompletion(새로 생성된 RangeError 객체)로 둔다.
    2. IteratorClose(iterated, error)를 반환한다.
  9. iterated 를 ? GetIteratorDirect(O)로 설정한다.
  10. closureiteratedintegerLimit 를 포획하는 매개변수 없는 새로운 Abstract Closure 로 두고, 호출 시 다음 단계를 수행하게 한다:
    1. remainingintegerLimit 로 둔다.
    2. 반복,
      1. remaining = 0 이면,
        1. IteratorClose(iterated, ReturnCompletion(undefined))를 반환한다.
      2. remaining ≠ +∞ 이면,
        1. remainingremaining - 1 로 설정한다.
      3. value 를 ? IteratorStepValue(iterated)로 둔다.
      4. valuedone 이면 ReturnCompletion(undefined)를 반환한다.
      5. completionCompletion(Yield(value))로 둔다.
      6. IfAbruptCloseIterator(completion, iterated).
  11. resultCreateIteratorFromClosure(closure, "Iterator Helper", %IteratorHelperPrototype%, « [[UnderlyingIterator]] »)로 둔다.
  12. result.[[UnderlyingIterator]]iterated 로 설정한다.
  13. result 를 반환한다.

27.1.4.12 Iterator.prototype.toArray ( )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. Othis 값으로 둔다.
  2. O 가 Object 가 아니면 TypeError 예외를 던진다.
  3. iterated 를 ? GetIteratorDirect(O)로 둔다.
  4. items 를 새로운 빈 List 로 둔다.
  5. 반복,
    1. value 를 ? IteratorStepValue(iterated)로 둔다.
    2. valuedone 이면 CreateArrayFromList(items)를 반환한다.
    3. valueitems 에 추가한다.

27.1.4.13 Iterator.prototype [ %Symbol.iterator% ] ( )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. this 값을 반환한다.

이 함수의 "name" 프로퍼티 값은 "[Symbol.iterator]" 이다.

27.1.4.14 Iterator.prototype [ %Symbol.toStringTag% ]

Iterator.prototype[%Symbol.toStringTag%] 는 { [[Enumerable]]: false, [[Configurable]]: true } 특성을 가진 접근자 프로퍼티이다. [[Get]][[Set]] 특성은 다음과 같이 정의된다:

27.1.4.14.1 get Iterator.prototype [ %Symbol.toStringTag% ]

[[Get]] 특성의 값은 인수가 필요 없는 내장 함수이다. 호출 시 다음 단계를 수행한다:

  1. "Iterator" 를 반환한다.

27.1.4.14.2 set Iterator.prototype [ %Symbol.toStringTag% ]

[[Set]] 특성의 값은 인수 v 를 받는 내장 함수이다. 호출 시 다음 단계를 수행한다:

  1. SetterThatIgnoresPrototypeProperties(this value, %Iterator.prototype%, %Symbol.toStringTag%, v)를 수행한다.
  2. undefined 를 반환한다.
Note

대부분의 내장 프로토타입에 있는 %Symbol.toStringTag% 프로퍼티와 달리, 웹 호환성 이유로 이 프로퍼티는 접근자여야 한다.

27.1.5 %AsyncIteratorPrototype% 객체 (The %AsyncIteratorPrototype% Object)

%AsyncIteratorPrototype% 객체:

Note

이 명세에서 async iterator 인터페이스를 구현하는 모든 객체는 %AsyncIteratorPrototype%을 상속한다. ECMAScript 코드는 또한 %AsyncIteratorPrototype%을 상속하는 객체를 정의할 수 있다. %AsyncIteratorPrototype% 객체는 모든 async iterator 객체에 적용 가능한 추가 메서드를 추가할 수 있는 장소를 제공한다.

27.1.5.1 %AsyncIteratorPrototype% [ %Symbol.asyncIterator% ] ( )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. this 값을 반환한다.

이 함수의 "name" 프로퍼티 값은 "[Symbol.asyncIterator]" 이다.

27.1.6 Sync 이터레이터 기반 Async 이터레이터 객체 (Async-from-Sync Iterator Objects)

Async-from-Sync Iterator 객체는 특정 동기(synchronous) 이터레이터를 적응(adapt)한 async 이터레이터이다. Async-from-Sync Iterator 객체는 ECMAScript 코드에서 직접 접근할 수 없다. Async-from-Sync Iterator 객체에 대한 명명된 생성자는 없다. 대신, 필요할 때 CreateAsyncFromSyncIterator 추상 연산에 의해 생성된다.

27.1.6.1 CreateAsyncFromSyncIterator ( syncIteratorRecord )

The abstract operation CreateAsyncFromSyncIterator takes argument syncIteratorRecord (an Iterator Record) and returns an Iterator Record. 동기 Iterator Record 로부터 async Iterator Record 를 생성하는 데 사용된다. 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.6.2 %AsyncFromSyncIteratorPrototype% 객체 (The %AsyncFromSyncIteratorPrototype% Object)

%AsyncFromSyncIteratorPrototype% 객체:

27.1.6.2.1 %AsyncFromSyncIteratorPrototype%.next ( [ value ] )

  1. Othis 값으로 둔다.
  2. O[[SyncIteratorRecord]] 내부 슬롯을 가진 Object 임을 단언한다.
  3. promiseCapability 를 ! NewPromiseCapability(%Promise%)로 둔다.
  4. syncIteratorRecordO.[[SyncIteratorRecord]] 로 둔다.
  5. value 가 존재하면,
    1. resultCompletion(IteratorNext(syncIteratorRecord, value))로 둔다.
  6. 그렇지 않으면,
    1. resultCompletion(IteratorNext(syncIteratorRecord))로 둔다.
  7. IfAbruptRejectPromise(result, promiseCapability).
  8. AsyncFromSyncIteratorContinuation(result, promiseCapability, syncIteratorRecord, true)를 반환한다.

27.1.6.2.2 %AsyncFromSyncIteratorPrototype%.return ( [ value ] )

  1. Othis 값으로 둔다.
  2. O[[SyncIteratorRecord]] 내부 슬롯을 가진 Object 임을 단언한다.
  3. promiseCapability 를 ! NewPromiseCapability(%Promise%)로 둔다.
  4. syncIteratorRecordO.[[SyncIteratorRecord]] 로 둔다.
  5. syncIteratorsyncIteratorRecord.[[Iterator]] 로 둔다.
  6. returnCompletion(GetMethod(syncIterator, "return" ))로 둔다.
  7. IfAbruptRejectPromise(return, promiseCapability).
  8. returnundefined 이면,
    1. iteratorResultCreateIteratorResultObject(value, true)로 둔다.
    2. Call(promiseCapability.[[Resolve]], undefined, « iteratorResult »)를 수행한다.
    3. promiseCapability.[[Promise]] 를 반환한다.
  9. value 가 존재하면,
    1. resultCompletion(Call(return, syncIterator, « value »))로 둔다.
  10. 그렇지 않으면,
    1. resultCompletion(Call(return, syncIterator))로 둔다.
  11. IfAbruptRejectPromise(result, promiseCapability).
  12. result 가 Object 가 아니면,
    1. Call(promiseCapability.[[Reject]], undefined, « 새로 생성된 TypeError 객체 »)를 수행한다.
    2. promiseCapability.[[Promise]] 를 반환한다.
  13. AsyncFromSyncIteratorContinuation(result, promiseCapability, syncIteratorRecord, false)를 반환한다.

27.1.6.2.3 %AsyncFromSyncIteratorPrototype%.throw ( [ value ] )

Note
이 명세에서 value 는 항상 제공되지만, %AsyncFromSyncIteratorPrototype%.return ( [ value ] )과의 일관성을 위해 선택적으로 남겨 둔다.
  1. Othis 값으로 둔다.
  2. O[[SyncIteratorRecord]] 내부 슬롯을 가진 Object 임을 단언한다.
  3. promiseCapability 를 ! NewPromiseCapability(%Promise%)로 둔다.
  4. syncIteratorRecordO.[[SyncIteratorRecord]] 로 둔다.
  5. syncIteratorsyncIteratorRecord.[[Iterator]] 로 둔다.
  6. throwCompletion(GetMethod(syncIterator, "throw" ))로 둔다.
  7. IfAbruptRejectPromise(throw, promiseCapability).
  8. throwundefined 이면,
    1. 주: syncIteratorthrow 메서드가 없다면, capability 거부 전에 정리할 기회를 주기 위해 그것을 닫는다.
    2. closeCompletionNormalCompletion(empty)로 둔다.
    3. resultCompletion(IteratorClose(syncIteratorRecord, closeCompletion))로 둔다.
    4. IfAbruptRejectPromise(result, promiseCapability).
    5. 주: 다음 단계는 프로토콜 위반(syncIteratorthrow 메서드가 없음)을 나타내기 위해 TypeError 를 던진다.
    6. 주: syncIterator 를 닫는 것이 throw 하지 않으면 그 연산 결과는, 거부된 promise 를 산출한다 해도, 무시된다.
    7. Call(promiseCapability.[[Reject]], undefined, « 새로 생성된 TypeError 객체 »)를 수행한다.
    8. promiseCapability.[[Promise]] 를 반환한다.
  9. value 가 존재하면,
    1. resultCompletion(Call(throw, syncIterator, « value »))로 둔다.
  10. 그렇지 않으면,
    1. resultCompletion(Call(throw, syncIterator))로 둔다.
  11. IfAbruptRejectPromise(result, promiseCapability).
  12. result 가 Object 가 아니면,
    1. Call(promiseCapability.[[Reject]], undefined, « 새로 생성된 TypeError 객체 »)를 수행한다.
    2. promiseCapability.[[Promise]] 를 반환한다.
  13. AsyncFromSyncIteratorContinuation(result, promiseCapability, syncIteratorRecord, true)를 반환한다.

27.1.6.3 Async-from-Sync Iterator 인스턴스의 프로퍼티 (Properties of Async-from-Sync Iterator Instances)

Async-from-Sync Iterator 인스턴스는 %AsyncFromSyncIteratorPrototype% 내재 객체를 상속하는 일반 객체이다. Async-from-Sync Iterator 인스턴스는 Table 87에 열거된 내부 슬롯을 가지고 초기화된다.

Table 87: Async-from-Sync Iterator 인스턴스의 내부 슬롯 (Internal Slots of Async-from-Sync Iterator Instances)
내부 슬롯 (Internal Slot) 타입 (Type) 설명 (Description)
[[SyncIteratorRecord]] Iterator Record 적응되고 있는 원래의 동기 이터레이터를 나타낸다.

27.1.6.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. 주: promiseCapability 가 내재 %Promise% 로부터 유도되었으므로, 이후 IfAbruptRejectPromise 사용이 수반하는 promiseCapability.[[Reject]] 호출은 throw 하지 않는 것이 보장된다.
  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 을 매개변수 (v) 를 가지고 done 을 포획하는 새로운 Abstract Closure 로 두고, 호출 시 다음 단계를 수행하게 한다:
    1. CreateIteratorResultObject(v, done)를 반환한다.
  10. onFulfilledCreateBuiltinFunction(unwrap, 1, "", « »)로 둔다.
  11. 주: onFulfilled 는 IteratorResult 객체의 "value" 프로퍼티를 처리할 때 그 값이 promise 인 경우 이를 대기하고 새 "언랩된" IteratorResult 객체로 재포장하기 위해 사용된다.
  12. donetrue 이거나 closeOnRejectionfalse 이면,
    1. onRejectedundefined 로 둔다.
  13. 그렇지 않으면,
    1. closeIterator 를 매개변수 (error) 를 가지고 syncIteratorRecord 를 포획하는 새로운 Abstract Closure 로 두고, 호출 시 다음 단계를 수행하게 한다:
      1. IteratorClose(syncIteratorRecord, ThrowCompletion(error))를 반환한다.
    2. onRejectedCreateBuiltinFunction(closeIterator, 1, "", « »)로 둔다.
    3. 주: onRejected 는 IteratorResult 객체가 내놓는 "value" 프로퍼티가 거부된 promise 인 경우 이터레이터를 닫는 데 사용된다.
  14. PerformPromiseThen(valueWrapper, onFulfilled, onRejected, promiseCapability)를 수행한다.
  15. promiseCapability.[[Promise]] 를 반환한다.

27.2 Promise Objects

Promise 는 지연(그리고 비동기일 수도 있는) 계산의 최종 결과에 대한 자리표시자로 사용되는 객체이다.

모든 Promise 는 상호 배타적인 세 가지 상태 중 하나이다: fulfilled, rejected, pending:

  • Promise pp.then(f, r) 이 즉시 함수 f 를 호출하는 Job 을 큐잉(enqueue)하면 fulfilled 상태이다.
  • Promise pp.then(f, r) 이 즉시 함수 r 를 호출하는 Job 을 큐잉하면 rejected 상태이다.
  • Promise 가 fulfilled 도 rejected 도 아니면 pending 상태이다.

Promise 가 pending 이 아니면, 즉 fulfilled 이거나 rejected 이면 settled 되었다고 말한다.

Promise 가 settled 이거나 다른 promise 의 상태에 “고정(lock in)” 되었으면 resolved 되었다고 한다. 이미 resolved 된 promise 를 resolve 또는 reject 하려는 시도는 아무 효과가 없다. Promise 가 resolved 가 아니면 unresolved 이다. Unresolved promise 는 항상 pending 상태이다. Resolved promise 는 pending, fulfilled 또는 rejected 일 수 있다.

27.2.1 Promise 추상 연산 (Promise Abstract Operations)

27.2.1.1 PromiseCapability Records

PromiseCapability Record 는 특정 Promise 또는 Promise 유사 객체와 그것을 resolve 또는 reject 할 수 있는 함수들을 함께 캡슐화하기 위해 사용되는 Record 값이다. PromiseCapability Record 는 NewPromiseCapability 추상 연산에 의해 생성된다.

PromiseCapability Record 는 Table 88에 열거된 필드를 가진다.

Table 88: PromiseCapability Record Fields (PromiseCapability 레코드 필드)
Field Name Value Meaning
[[Promise]] an Object Promise 로 사용할 수 있는 객체.
[[Resolve]] a function object 해당 promise 를 resolve 하는 데 사용되는 함수.
[[Reject]] a function object 해당 promise 를 reject 하는 데 사용되는 함수.

27.2.1.1.1 IfAbruptRejectPromise ( value, capability )

IfAbruptRejectPromise 는 PromiseCapability Record 를 사용하는 알고리즘 단계 시퀀스의 축약 표현이다. 다음과 같은 알고리즘 단계:

  1. IfAbruptRejectPromise(value, capability).

는 다음과 동일한 의미이다:

  1. Assert: valueCompletion Record 이다.
  2. valueabrupt completion 이면,
    1. Call(capability.[[Reject]], undefined, « value.[[Value]] »)를 수행한다.
    2. capability.[[Promise]] 를 반환한다.
  3. 그렇지 않으면,
    1. value 를 ! value 로 설정한다.

27.2.1.2 PromiseReaction Records

PromiseReaction Record 는 promise 가 특정 값으로 resolved 또는 rejected 될 때 어떻게 반응해야 하는지를 저장하기 위한 Record 값이다. PromiseReaction Record 는 PerformPromiseThen 추상 연산에 의해 생성되며, NewPromiseReactionJob 이 반환하는 Abstract Closure 에 의해 사용된다.

PromiseReaction Record 는 Table 89에 열거된 필드를 가진다.

Table 89: PromiseReaction Record Fields (PromiseReaction 레코드 필드)
Field Name Value Meaning
[[Capability]] a PromiseCapability Record or undefined 이 레코드가 반응 핸들러를 제공하는 promise 의 capability.
[[Type]] fulfill or reject [[Handler]]empty 일 때 처리 유형별 동작을 허용하기 위해 사용된다.
[[Handler]] a JobCallback Record or empty 들어오는 값에 적용되어 그 반환 값이 파생된 promise 에서 일어날 일을 결정하는 함수. [[Handler]]empty 이면 [[Type]] 값에 따라 결정되는 함수가 대신 사용된다.

27.2.1.3 CreateResolvingFunctions ( promise )

The abstract operation CreateResolvingFunctions takes argument promise (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. alreadyResolvedRecord { [[Value]]: false } 로 둔다.
  2. stepsResolvePromise Resolve Functions 에 정의된 알고리즘 단계로 둔다.
  3. lengthResolvePromise Resolve Functions 에 있는 함수 정의의 선택적이 아닌 매개변수 개수로 둔다.
  4. resolveCreateBuiltinFunction(stepsResolve, lengthResolve, "", « [[Promise]], [[AlreadyResolved]] ») 로 둔다.
  5. resolve.[[Promise]]promise 로 설정한다.
  6. resolve.[[AlreadyResolved]]alreadyResolved 로 설정한다.
  7. stepsRejectPromise Reject Functions 에 정의된 알고리즘 단계로 둔다.
  8. lengthRejectPromise Reject Functions 에 있는 함수 정의의 선택적이 아닌 매개변수 개수로 둔다.
  9. rejectCreateBuiltinFunction(stepsReject, lengthReject, "", « [[Promise]], [[AlreadyResolved]] ») 로 둔다.
  10. reject.[[Promise]]promise 로 설정한다.
  11. reject.[[AlreadyResolved]]alreadyResolved 로 설정한다.
  12. Record { [[Resolve]]: resolve, [[Reject]]: reject } 를 반환한다.

27.2.1.3.1 Promise Reject Functions

Promise reject 함수는 [[Promise]][[AlreadyResolved]] 내부 슬롯을 가진 익명 내장 함수이다.

Promise reject 함수가 인수 reason 과 함께 호출되면 다음 단계를 수행한다:

  1. F 를 활성 함수 객체로 둔다.
  2. Assert: F 는 값이 Object 인 [[Promise]] 내부 슬롯을 가진다.
  3. promiseF.[[Promise]] 로 둔다.
  4. alreadyResolvedF.[[AlreadyResolved]] 로 둔다.
  5. alreadyResolved.[[Value]]true 이면 undefined 를 반환한다.
  6. alreadyResolved.[[Value]]true 로 설정한다.
  7. RejectPromise(promise, reason) 를 수행한다.
  8. undefined 를 반환한다.

Promise reject 함수의 "length" 프로퍼티는 1𝔽 이다.

27.2.1.3.2 Promise Resolve Functions

Promise resolve 함수는 [[Promise]][[AlreadyResolved]] 내부 슬롯을 가진 익명 내장 함수이다.

Promise resolve 함수가 인수 resolution 과 함께 호출되면 다음 단계를 수행한다:

  1. F 를 활성 함수 객체로 둔다.
  2. Assert: F 는 값이 Object 인 [[Promise]] 내부 슬롯을 가진다.
  3. promiseF.[[Promise]] 로 둔다.
  4. alreadyResolvedF.[[AlreadyResolved]] 로 둔다.
  5. alreadyResolved.[[Value]]true 이면 undefined 를 반환한다.
  6. alreadyResolved.[[Value]]true 로 설정한다.
  7. SameValue(resolution, promise) 가 true 이면,
    1. selfResolutionError 를 새로 생성된 TypeError 객체로 둔다.
    2. RejectPromise(promise, selfResolutionError) 를 수행한다.
    3. undefined 를 반환한다.
  8. resolution 이 Object 가 아니면,
    1. FulfillPromise(promise, resolution) 를 수행한다.
    2. undefined 를 반환한다.
  9. thenCompletion(Get(resolution, "then" )) 로 둔다.
  10. thenabrupt completion 이면,
    1. RejectPromise(promise, then.[[Value]]) 를 수행한다.
    2. undefined 를 반환한다.
  11. thenActionthen.[[Value]] 로 둔다.
  12. IsCallable(thenAction) 이 false 이면,
    1. FulfillPromise(promise, resolution) 를 수행한다.
    2. undefined 를 반환한다.
  13. thenJobCallbackHostMakeJobCallback(thenAction) 로 둔다.
  14. jobNewPromiseResolveThenableJob(promise, resolution, thenJobCallback) 로 둔다.
  15. HostEnqueuePromiseJob(job.[[Job]], job.[[Realm]]) 를 수행한다.
  16. undefined 를 반환한다.

Promise resolve 함수의 "length" 프로퍼티는 1𝔽 이다.

27.2.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.2.1.5 NewPromiseCapability ( C )

The abstract operation NewPromiseCapability takes argument C (an ECMAScript language value) and returns either a normal completion containing a PromiseCapability Record or a throw completion. 내장 Promise 생성자 방식으로 C생성자로 사용하여 promise 를 만들고 그 resolve, reject 함수를 추출하려 시도한다. 그 promise 와 두 함수는 새로운 PromiseCapability Record 를 초기화하는 데 사용된다. It performs the following steps when called:

  1. IsConstructor(C) 가 false 이면 TypeError 예외를 던진다.
  2. 주: C 는 Promise 생성자의 매개변수 규약을 지원하는 생성자 함수라고 가정한다 (27.2.3.1 참조).
  3. resolvingFunctionsRecord { [[Resolve]]: undefined, [[Reject]]: undefined } 로 둔다.
  4. executorClosure 를 매개변수 (resolve, reject) 를 가지고 resolvingFunctions 를 포획하며 호출 시 다음을 수행하는 새로운 Abstract Closure 로 둔다:
    1. resolvingFunctions.[[Resolve]]undefined 가 아니면 TypeError 예외를 던진다.
    2. resolvingFunctions.[[Reject]]undefined 가 아니면 TypeError 예외를 던진다.
    3. resolvingFunctions.[[Resolve]]resolve 로 설정한다.
    4. resolvingFunctions.[[Reject]]reject 로 설정한다.
    5. NormalCompletion(undefined) 를 반환한다.
  5. executorCreateBuiltinFunction(executorClosure, 2, "", « ») 로 둔다.
  6. promise 를 ? Construct(C, « executor ») 로 둔다.
  7. IsCallable(resolvingFunctions.[[Resolve]]) 가 false 이면 TypeError 예외를 던진다.
  8. IsCallable(resolvingFunctions.[[Reject]]) 가 false 이면 TypeError 예외를 던진다.
  9. PromiseCapability Record { [[Promise]]: promise, [[Resolve]]: resolvingFunctions.[[Resolve]], [[Reject]]: resolvingFunctions.[[Reject]] } 를 반환한다.
Note

이 추상 연산은 전달된 executor 함수 인수를 Promise 생성자와 동일한 방식으로 호출하는 어떤 생성자에도 일반화되어 Promise 서브클래싱을 지원한다. 이는 Promise 생성자의 정적 메서드들을 임의의 서브클래스로 일반화하는 데 사용된다.

27.2.1.6 IsPromise ( x )

The abstract operation IsPromise takes argument x (an ECMAScript language value) and returns a Boolean. 객체에 promise 브랜드가 있는지 검사한다. It performs the following steps when called:

  1. x 가 Object 가 아니면 false 를 반환한다.
  2. x[[PromiseState]] 내부 슬롯이 없으면 false 를 반환한다.
  3. true 를 반환한다.

27.2.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 이다.
    1. reactionspromise.[[PromiseRejectReactions]] 로 둔다.
    2. promise.[[PromiseResult]]reason 으로 설정한다.
    3. promise.[[PromiseFulfillReactions]]undefined 로 설정한다.
    4. promise.[[PromiseRejectReactions]]undefined 로 설정한다.
    5. promise.[[PromiseState]]rejected 로 설정한다.
    6. promise.[[PromiseIsHandled]]false 이면 HostPromiseRejectionTracker(promise, "reject") 를 수행한다.
    7. TriggerPromiseReactions(reactions, reason) 를 수행한다.
    8. unused 를 반환한다.

27.2.1.8 TriggerPromiseReactions ( reactions, argument )

The abstract operation TriggerPromiseReactions takes arguments reactions (a List of PromiseReaction Records) and argument (an ECMAScript language value) and returns unused. reactions 의 각 레코드에 대해 새로운 Job 을 큐잉한다. 각 JobPromiseReaction Record[[Type]][[Handler]] 를 처리하며, [[Handler]]empty 가 아니면 주어진 인수를 전달하여 호출한다. [[Handler]]empty 이면 동작은 [[Type]] 에 의해 결정된다. It performs the following steps when called:

  1. reactions 의 각 요소 reaction 에 대해,
    1. jobNewPromiseReactionJob(reaction, argument) 로 둔다.
    2. HostEnqueuePromiseJob(job.[[Job]], job.[[Realm]]) 를 수행한다.
  2. unused 를 반환한다.

27.2.1.9 HostPromiseRejectionTracker ( promise, operation )

The host-defined abstract operation HostPromiseRejectionTracker takes arguments promise (a Promise) and operation ("reject" or "handle") and returns unused. 호스트 환경이 promise rejection 을 추적할 수 있도록 한다.

HostPromiseRejectionTracker 의 기본 구현은 unused 를 반환하는 것이다.

Note 1

HostPromiseRejectionTracker 는 두 시나리오에서 호출된다:

  • Promise 가 핸들러 없이 reject 될 때 operation 인수가 "reject" 로 호출된다.
  • 처음으로 핸들러가 reject 된 promise 에 추가될 때 operation 인수가 "handle" 로 호출된다.

전형적인 구현은 처리되지 않은 rejection 을 개발자에게 알리려고 시도하며, 이후 새로운 핸들러가 부착되어 이전 알림이 무효화되는 경우도 알리도록 주의할 수 있다.

Note 2

operation"handle" 이면 구현은 가비지 컬렉션을 방해하는 방식으로 promise 에 대한 참조를 보유하지 않아야 한다. operation"reject" 이면, rejection 은 드물고 핫 코드 경로가 아닐 것으로 예상되므로 promise 에 대한 참조를 보유할 수 있다.

27.2.2 Promise 작업 (Promise Jobs)

27.2.2.1 NewPromiseReactionJob ( reaction, argument )

The abstract operation NewPromiseReactionJob takes arguments reaction (a PromiseReaction Record) and argument (an ECMAScript language value) and returns a Record with fields [[Job]] (a Job Abstract Closure) and [[Realm]] (a Realm Record or null). 들어오는 값에 적절한 핸들러를 적용하고, 그 핸들러의 반환 값을 사용하여 그 핸들러와 연관된 파생 promise 를 resolve 또는 reject 하는 새로운 Job 추상 클로저를 반환한다. It performs the following steps when called:

  1. job 을 매개변수 없고 reactionargument 를 포획(capture)하며 호출 시 다음 단계를 수행하는 새로운 Job 추상 클로저로 둔다:
    1. promiseCapabilityreaction.[[Capability]] 로 둔다.
    2. typereaction.[[Type]] 로 둔다.
    3. handlerreaction.[[Handler]] 로 둔다.
    4. handlerempty 이면,
      1. typefulfill 이면
        1. handlerResultNormalCompletion(argument) 로 둔다.
      2. 그렇지 않으면,
        1. Assert: typereject.
        2. handlerResultThrowCompletion(argument) 로 둔다.
    5. 그렇지 않으면,
      1. handlerResultCompletion(HostCallJobCallback(handler, undefined, « argument »)) 로 둔다.
    6. promiseCapabilityundefined 이면,
      1. Assert: handlerResultabrupt completion 이 아님.
      2. empty 를 반환한다.
    7. Assert: promiseCapabilityPromiseCapability Record.
    8. handlerResultabrupt completion 이면,
      1. Call(promiseCapability.[[Reject]], undefined, « handlerResult.[[Value]] ») 를 반환한다.
    9. 그렇지 않으면,
      1. Call(promiseCapability.[[Resolve]], undefined, « handlerResult.[[Value]] ») 를 반환한다.
  2. handlerRealmnull 로 둔다.
  3. reaction.[[Handler]]empty 가 아니면,
    1. getHandlerRealmResultCompletion(GetFunctionRealm(reaction.[[Handler]].[[Callback]])) 로 둔다.
    2. getHandlerRealmResultnormal completion 이면 handlerRealmgetHandlerRealmResult.[[Value]] 로 설정한다.
    3. 그렇지 않으면 handlerRealm 을 현재 Realm Record 로 설정한다.
    4. 주: handlerRealm 은 핸들러가 undefined 인 경우를 제외하고 null 이 아니다. 핸들러가 취소된 Proxy 이고 어떤 ECMAScript 코드도 실행되지 않을 때 handlerRealm 은 에러 객체를 생성하는 데 사용된다.
  4. Record { [[Job]]: job, [[Realm]]: handlerRealm } 를 반환한다.

27.2.2.2 NewPromiseResolveThenableJob ( promiseToResolve, thenable, then )

The abstract operation NewPromiseResolveThenableJob takes arguments promiseToResolve (a Promise), thenable (an Object), and then (a JobCallback Record) and returns a Record with fields [[Job]] (a Job Abstract Closure) and [[Realm]] (a Realm Record). It performs the following steps when called:

  1. job 을 매개변수 없고 promiseToResolve, thenable, then 을 포획하며 호출 시 다음 단계를 수행하는 새로운 Job 추상 클로저로 둔다:
    1. resolvingFunctionsCreateResolvingFunctions(promiseToResolve) 로 둔다.
    2. thenCallResultCompletion(HostCallJobCallback(then, thenable, « resolvingFunctions.[[Resolve]], resolvingFunctions.[[Reject]] »)) 로 둔다.
    3. thenCallResultabrupt completion 이면,
      1. Call(resolvingFunctions.[[Reject]], undefined, « thenCallResult.[[Value]] ») 를 반환한다.
    4. thenCallResult 를 반환한다.
  2. getThenRealmResultCompletion(GetFunctionRealm(then.[[Callback]])) 로 둔다.
  3. getThenRealmResultnormal completion 이면 thenRealmgetThenRealmResult.[[Value]] 로 둔다.
  4. 그렇지 않으면 thenRealm 을 현재 Realm Record 로 둔다.
  5. 주: thenRealmnull 이 아니다. then.[[Callback]] 이 취소된 Proxy 이고 어떤 코드도 실행되지 않을 때 thenRealm 은 에러 객체 생성을 위해 사용된다.
  6. Record { [[Job]]: job, [[Realm]]: thenRealm } 를 반환한다.
Note

Job 은 제공된 thenable 과 그 then 메서드를 사용하여 주어진 promise 를 resolve 한다. 이 과정은 then 메서드의 평가가 주변 코드의 평가가 끝난 후에 일어나도록 Job 으로 수행되어야 한다.

27.2.3 Promise 생성자 (The Promise Constructor)

Promise 생성자:

  • %Promise% 이다.
  • 전역 객체"Promise" 프로퍼티 초기 값이다.
  • 생성자로 호출될 때 새로운 Promise 를 생성하고 초기화한다.
  • 함수로 호출하는 것은 의도되지 않았으며 그렇게 호출하면 예외를 던진다.
  • 클래스 정의의 extends 절 값으로 사용될 수 있다. 지정된 Promise 동작을 상속하려는 서브클래스 생성자PromisePromise.prototype 내장 메서드를 지원하는 데 필요한 내부 상태로 서브클래스 인스턴스를 생성 및 초기화하기 위해 Promise 생성자에 대한 super 호출을 포함해야 한다.

27.2.3.1 Promise ( executor )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. NewTarget 이 undefined 이면 TypeError 예외를 던진다.
  2. IsCallable(executor) 가 false 이면 TypeError 예외를 던진다.
  3. promise 를 ? OrdinaryCreateFromConstructor(NewTarget, "%Promise.prototype%", « [[PromiseState]], [[PromiseResult]], [[PromiseFulfillReactions]], [[PromiseRejectReactions]], [[PromiseIsHandled]] ») 로 둔다.
  4. promise.[[PromiseState]]pending 으로 설정한다.
  5. promise.[[PromiseResult]]empty 로 설정한다.
  6. promise.[[PromiseFulfillReactions]] 를 새로운 빈 List 로 설정한다.
  7. promise.[[PromiseRejectReactions]] 를 새로운 빈 List 로 설정한다.
  8. promise.[[PromiseIsHandled]]false 로 설정한다.
  9. resolvingFunctionsCreateResolvingFunctions(promise) 로 둔다.
  10. completionCompletion(Call(executor, undefined, « resolvingFunctions.[[Resolve]], resolvingFunctions.[[Reject]] »)) 로 둔다.
  11. completionabrupt completion 이면,
    1. Call(resolvingFunctions.[[Reject]], undefined, « completion.[[Value]] ») 를 수행한다.
  12. promise 를 반환한다.
Note

executor 인수는 함수 객체여야 한다. 이는 이 Promise 가 표현하는 (지연될 수 있는) 동작을 시작하고 완료를 보고하기 위해 호출된다. Executor 는 두 인수: resolvereject 로 호출된다. 이들은 지연 계산의 최종 완료 또는 실패를 보고하기 위해 executor 함수에서 사용할 수 있는 함수이다. Executor 함수에서 반환하는 것은 지연 동작이 완료되었음을 의미하지 않고 단지 나중에 그 지연 동작을 수행하라는 요청이 수락되었음을 의미한다.

executor 에 전달되는 resolve 함수는 단일 인수를 받는다. executor 코드는 결국 resolve 함수를 호출해 관련 Promise 를 resolve 하려 함을 나타낼 수 있다. resolve 함수에 전달되는 인수는 지연 동작의 최종 값을 나타내며 실제 이행 값이거나 그것이 이행될 경우 값을 제공할 다른 promise 일 수 있다.

executor 에 전달되는 reject 함수는 단일 인수를 받는다. executor 코드는 결국 reject 함수를 호출해 관련 Promise 가 rejected 되었고 결코 fulfilled 되지 않을 것임을 나타낼 수 있다. reject 함수에 전달되는 인수는 promise 의 rejection 값으로 사용되며 일반적으로 Error 객체이다.

Promise 생성자executor 함수에 전달하는 resolve 및 reject 함수는 실제로 해당 promise 를 resolve 및 reject 할 수 있는 능력을 가진다. 서브클래스는 resolve 와 reject 에 대해 사용자 정의 값을 전달하는 다른 생성자 동작을 가질 수 있다.

27.2.4 Promise 생성자의 프로퍼티 (Properties of the Promise Constructor)

Promise 생성자:

  • [[Prototype]] 내부 슬롯 값이 %Function.prototype% 이다.
  • 다음 프로퍼티들을 가진다:

27.2.4.1 Promise.all ( iterable )

이 함수는 전달된 promise 들의 이행 값 배열로 이행되는 새로운 promise 를 반환하거나, 가장 먼저 reject 된 promise 의 reason 으로 reject 된다. 이 알고리즘을 수행하면서 전달된 iterable 의 모든 요소를 promise 로 resolve 한다.

  1. Cthis 값으로 둔다.
  2. promiseCapability 를 ? NewPromiseCapability(C) 로 둔다.
  3. promiseResolveCompletion(GetPromiseResolve(C)) 로 둔다.
  4. IfAbruptRejectPromise(promiseResolve, promiseCapability).
  5. iteratorRecordCompletion(GetIterator(iterable, sync)) 로 둔다.
  6. IfAbruptRejectPromise(iteratorRecord, promiseCapability).
  7. resultCompletion(PerformPromiseAll(iteratorRecord, C, promiseCapability, promiseResolve)) 로 둔다.
  8. resultabrupt completion 이면,
    1. iteratorRecord.[[Done]]false 이면 resultCompletion(IteratorClose(iteratorRecord, result)) 로 설정한다.
    2. IfAbruptRejectPromise(result, promiseCapability).
  9. result 를 반환한다.
Note

이 함수는 this 값이 Promise 생성자의 매개변수 규약을 지원하는 생성자 함수이기를 요구한다.

27.2.4.1.1 GetPromiseResolve ( promiseConstructor )

The abstract operation GetPromiseResolve takes argument promiseConstructor (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(promiseConstructor, "resolve") 로 둔다.
  2. IsCallable(promiseResolve) 가 false 이면 TypeError 예외를 던진다.
  3. promiseResolve 를 반환한다.

27.2.4.1.2 PerformPromiseAll ( iteratorRecord, constructor, resultCapability, promiseResolve )

The abstract operation PerformPromiseAll takes arguments iteratorRecord (an Iterator Record), constructor (a constructor), resultCapability (a PromiseCapability Record), and promiseResolve (a function object) and returns either a normal completion containing an ECMAScript language value or a throw completion. It performs the following steps when called:

  1. values 를 새로운 빈 List 로 둔다.
  2. remainingElementsCountRecord { [[Value]]: 1 } 로 둔다.
  3. index 를 0 으로 둔다.
  4. 반복,
    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 에 추가한다.
    4. nextPromise 를 ? Call(promiseResolve, constructor, « next ») 로 둔다.
    5. stepsPromise.all Resolve Element Functions 에 정의된 알고리즘 단계로 둔다.
    6. lengthPromise.all Resolve Element Functions 에 있는 함수 정의의 선택적이 아닌 매개변수 개수로 둔다.
    7. onFulfilledCreateBuiltinFunction(steps, length, "", « [[AlreadyCalled]], [[Index]], [[Values]], [[Capability]], [[RemainingElements]] ») 로 둔다.
    8. onFulfilled.[[AlreadyCalled]]false 로 설정한다.
    9. onFulfilled.[[Index]]index 로 설정한다.
    10. onFulfilled.[[Values]]values 로 설정한다.
    11. onFulfilled.[[Capability]]resultCapability 로 설정한다.
    12. onFulfilled.[[RemainingElements]]remainingElementsCount 로 설정한다.
    13. remainingElementsCount.[[Value]]remainingElementsCount.[[Value]] + 1 로 설정한다.
    14. Invoke(nextPromise, "then", « onFulfilled, resultCapability.[[Reject]] ») 를 수행한다.
    15. indexindex + 1 로 설정한다.

27.2.4.1.3 Promise.all Resolve Element Functions

Promise.all resolve 요소 함수는 특정 Promise.all 요소를 resolve 하는 데 사용되는 익명 내장 함수이다. 각 Promise.all resolve 요소 함수는 [[Index]], [[Values]], [[Capability]], [[RemainingElements]], [[AlreadyCalled]] 내부 슬롯을 가진다.

Promise.all resolve 요소 함수가 인수 x 와 함께 호출되면 다음 단계를 수행한다:

  1. F 를 활성 함수 객체로 둔다.
  2. F.[[AlreadyCalled]]true 이면 undefined 를 반환한다.
  3. F.[[AlreadyCalled]]true 로 설정한다.
  4. indexF.[[Index]] 로 둔다.
  5. valuesF.[[Values]] 로 둔다.
  6. promiseCapabilityF.[[Capability]] 로 둔다.
  7. remainingElementsCountF.[[RemainingElements]] 로 둔다.
  8. values[index] 를 x 로 설정한다.
  9. remainingElementsCount.[[Value]]remainingElementsCount.[[Value]] - 1 로 설정한다.
  10. remainingElementsCount.[[Value]] = 0 이면,
    1. valuesArrayCreateArrayFromList(values) 로 둔다.
    2. Call(promiseCapability.[[Resolve]], undefined, « valuesArray ») 를 반환한다.
  11. undefined 를 반환한다.

Promise.all resolve 요소 함수의 "length" 프로퍼티는 1𝔽 이다.

27.2.4.2 Promise.allSettled ( iterable )

이 함수는 모든 원래 promise 가 settled(즉 fulfilled 또는 rejected) 된 후에, promise 상태 스냅샷 객체들의 배열로 이행되는 promise 를 반환한다. 이 알고리즘을 수행하면서 전달된 iterable 의 모든 요소를 promise 로 resolve 한다.

  1. Cthis 값으로 둔다.
  2. promiseCapability 를 ? NewPromiseCapability(C) 로 둔다.
  3. promiseResolveCompletion(GetPromiseResolve(C)) 로 둔다.
  4. IfAbruptRejectPromise(promiseResolve, promiseCapability).
  5. iteratorRecordCompletion(GetIterator(iterable, sync)) 로 둔다.
  6. IfAbruptRejectPromise(iteratorRecord, promiseCapability).
  7. resultCompletion(PerformPromiseAllSettled(iteratorRecord, C, promiseCapability, promiseResolve)) 로 둔다.
  8. resultabrupt completion 이면,
    1. iteratorRecord.[[Done]]false 이면 resultCompletion(IteratorClose(iteratorRecord, result)) 로 설정한다.
    2. IfAbruptRejectPromise(result, promiseCapability).
  9. result 를 반환한다.
Note

이 함수는 this 값이 Promise 생성자의 매개변수 규약을 지원하는 생성자 함수이기를 요구한다.

27.2.4.2.1 PerformPromiseAllSettled ( iteratorRecord, constructor, resultCapability, promiseResolve )

The abstract operation PerformPromiseAllSettled takes arguments iteratorRecord (an Iterator Record), constructor (a constructor), resultCapability (a PromiseCapability Record), and promiseResolve (a function object) and returns either a normal completion containing an ECMAScript language value or a throw completion. It performs the following steps when called:

  1. values 를 새로운 빈 List 로 둔다.
  2. remainingElementsCountRecord { [[Value]]: 1 } 로 둔다.
  3. index 를 0 으로 둔다.
  4. 반복,
    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 에 추가한다.
    4. nextPromise 를 ? Call(promiseResolve, constructor, « next ») 로 둔다.
    5. stepsFulfilledPromise.allSettled Resolve Element Functions 에 정의된 알고리즘 단계로 둔다.
    6. lengthFulfilledPromise.allSettled Resolve Element Functions 에 있는 함수 정의의 선택적이 아닌 매개변수 개수로 둔다.
    7. onFulfilledCreateBuiltinFunction(stepsFulfilled, lengthFulfilled, "", « [[AlreadyCalled]], [[Index]], [[Values]], [[Capability]], [[RemainingElements]] ») 로 둔다.
    8. alreadyCalledRecord { [[Value]]: false } 로 둔다.
    9. onFulfilled.[[AlreadyCalled]]alreadyCalled 로 설정한다.
    10. onFulfilled.[[Index]]index 로 설정한다.
    11. onFulfilled.[[Values]]values 로 설정한다.
    12. onFulfilled.[[Capability]]resultCapability 로 설정한다.
    13. onFulfilled.[[RemainingElements]]remainingElementsCount 로 설정한다.
    14. stepsRejectedPromise.allSettled Reject Element Functions 에 정의된 알고리즘 단계로 둔다.
    15. lengthRejectedPromise.allSettled Reject Element Functions 에 있는 함수 정의의 선택적이 아닌 매개변수 개수로 둔다.
    16. onRejectedCreateBuiltinFunction(stepsRejected, lengthRejected, "", « [[AlreadyCalled]], [[Index]], [[Values]], [[Capability]], [[RemainingElements]] ») 로 둔다.
    17. onRejected.[[AlreadyCalled]]alreadyCalled 로 설정한다.
    18. onRejected.[[Index]]index 로 설정한다.
    19. onRejected.[[Values]]values 로 설정한다.
    20. onRejected.[[Capability]]resultCapability 로 설정한다.
    21. onRejected.[[RemainingElements]]remainingElementsCount 로 설정한다.
    22. remainingElementsCount.[[Value]]remainingElementsCount.[[Value]] + 1 로 설정한다.
    23. Invoke(nextPromise, "then", « onFulfilled, onRejected ») 를 수행한다.
    24. indexindex + 1 로 설정한다.

27.2.4.2.2 Promise.allSettled Resolve Element Functions

Promise.allSettled resolve 요소 함수는 특정 Promise.allSettled 요소를 resolve 하는 데 사용되는 익명 내장 함수이다. 각 함수는 [[Index]], [[Values]], [[Capability]], [[RemainingElements]], [[AlreadyCalled]] 내부 슬롯을 가진다.

Promise.allSettled resolve 요소 함수가 인수 x 로 호출되면 다음 단계를 수행한다:

  1. F 를 활성 함수 객체로 둔다.
  2. alreadyCalledF.[[AlreadyCalled]] 로 둔다.
  3. alreadyCalled.[[Value]]true 이면 undefined 를 반환한다.
  4. alreadyCalled.[[Value]]true 로 설정한다.
  5. indexF.[[Index]] 로 둔다.
  6. valuesF.[[Values]] 로 둔다.
  7. promiseCapabilityF.[[Capability]] 로 둔다.
  8. remainingElementsCountF.[[RemainingElements]] 로 둔다.
  9. objOrdinaryObjectCreate(%Object.prototype%) 로 둔다.
  10. CreateDataPropertyOrThrow(obj, "status", "fulfilled") 를 수행한다.
  11. CreateDataPropertyOrThrow(obj, "value", x) 를 수행한다.
  12. values[index] 를 obj 로 설정한다.
  13. remainingElementsCount.[[Value]]remainingElementsCount.[[Value]] - 1 로 설정한다.
  14. remainingElementsCount.[[Value]] = 0 이면,
    1. valuesArrayCreateArrayFromList(values) 로 둔다.
    2. Call(promiseCapability.[[Resolve]], undefined, « valuesArray ») 를 반환한다.
  15. undefined 를 반환한다.

Promise.allSettled resolve 요소 함수의 "length" 프로퍼티는 1𝔽 이다.

27.2.4.2.3 Promise.allSettled Reject Element Functions

Promise.allSettled reject 요소 함수는 특정 Promise.allSettled 요소를 reject 하는 데 사용되는 익명 내장 함수이다. 각 함수는 [[Index]], [[Values]], [[Capability]], [[RemainingElements]], [[AlreadyCalled]] 내부 슬롯을 가진다.

Promise.allSettled reject 요소 함수가 인수 x 로 호출되면 다음 단계를 수행한다:

  1. F 를 활성 함수 객체로 둔다.
  2. alreadyCalledF.[[AlreadyCalled]] 로 둔다.
  3. alreadyCalled.[[Value]]true 이면 undefined 를 반환한다.
  4. alreadyCalled.[[Value]]true 로 설정한다.
  5. indexF.[[Index]] 로 둔다.
  6. valuesF.[[Values]] 로 둔다.
  7. promiseCapabilityF.[[Capability]] 로 둔다.
  8. remainingElementsCountF.[[RemainingElements]] 로 둔다.
  9. objOrdinaryObjectCreate(%Object.prototype%) 로 둔다.
  10. CreateDataPropertyOrThrow(obj, "status", "rejected") 를 수행한다.
  11. CreateDataPropertyOrThrow(obj, "reason", x) 를 수행한다.
  12. values[index] 를 obj 로 설정한다.
  13. remainingElementsCount.[[Value]]remainingElementsCount.[[Value]] - 1 로 설정한다.
  14. remainingElementsCount.[[Value]] = 0 이면,
    1. valuesArrayCreateArrayFromList(values) 로 둔다.
    2. Call(promiseCapability.[[Resolve]], undefined, « valuesArray ») 를 반환한다.
  15. undefined 를 반환한다.

Promise.allSettled reject 요소 함수의 "length" 프로퍼티는 1𝔽 이다.

27.2.4.3 Promise.any ( iterable )

이 함수는 전달된 promise 중 처음 fulfilled 되는 promise 로 fulfilled 되거나, 모두 rejected 되면 rejection reason 들을 담은 AggregateError 로 reject 되는 promise 를 반환한다. 이 알고리즘을 수행하면서 전달된 iterable 의 모든 요소를 promise 로 resolve 한다.

  1. Cthis 값으로 둔다.
  2. promiseCapability 를 ? NewPromiseCapability(C) 로 둔다.
  3. promiseResolveCompletion(GetPromiseResolve(C)) 로 둔다.
  4. IfAbruptRejectPromise(promiseResolve, promiseCapability).
  5. iteratorRecordCompletion(GetIterator(iterable, sync)) 로 둔다.
  6. IfAbruptRejectPromise(iteratorRecord, promiseCapability).
  7. resultCompletion(PerformPromiseAny(iteratorRecord, C, promiseCapability, promiseResolve)) 로 둔다.
  8. resultabrupt completion 이면,
    1. iteratorRecord.[[Done]]false 이면 resultCompletion(IteratorClose(iteratorRecord, result)) 로 설정한다.
    2. IfAbruptRejectPromise(result, promiseCapability).
  9. result 를 반환한다.
Note

이 함수는 this 값이 Promise 생성자의 매개변수 규약을 지원하는 생성자 함수이기를 요구한다.

27.2.4.3.1 PerformPromiseAny ( iteratorRecord, constructor, resultCapability, promiseResolve )

The abstract operation PerformPromiseAny takes arguments iteratorRecord (an Iterator Record), constructor (a constructor), resultCapability (a PromiseCapability Record), and promiseResolve (a function object) and returns either a normal completion containing an ECMAScript language value or a throw completion. It performs the following steps when called:

  1. errors 를 새로운 빈 List 로 둔다.
  2. remainingElementsCountRecord { [[Value]]: 1 } 로 둔다.
  3. index 를 0 으로 둔다.
  4. 반복,
    1. next 를 ? IteratorStepValue(iteratorRecord) 로 둔다.
    2. nextdone 이면,
      1. remainingElementsCount.[[Value]]remainingElementsCount.[[Value]] - 1 로 설정한다.
      2. remainingElementsCount.[[Value]] = 0 이면,
        1. error 를 새로 생성된 AggregateError 객체로 둔다.
        2. DefinePropertyOrThrow(error, "errors", PropertyDescriptor { [[Configurable]]: true, [[Enumerable]]: false, [[Writable]]: true, [[Value]]: CreateArrayFromList(errors) }) 를 수행한다.
        3. ThrowCompletion(error) 를 반환한다.
      3. resultCapability.[[Promise]] 를 반환한다.
    3. undefinederrors 에 추가한다.
    4. nextPromise 를 ? Call(promiseResolve, constructor, « next ») 로 둔다.
    5. stepsRejectedPromise.any Reject Element Functions 에 정의된 알고리즘 단계로 둔다.
    6. lengthRejectedPromise.any Reject Element Functions 에 있는 함수 정의의 선택적이 아닌 매개변수 개수로 둔다.
    7. onRejectedCreateBuiltinFunction(stepsRejected, lengthRejected, "", « [[AlreadyCalled]], [[Index]], [[Errors]], [[Capability]], [[RemainingElements]] ») 로 둔다.
    8. onRejected.[[AlreadyCalled]]false 로 설정한다.
    9. onRejected.[[Index]]index 로 설정한다.
    10. onRejected.[[Errors]]errors 로 설정한다.
    11. onRejected.[[Capability]]resultCapability 로 설정한다.
    12. onRejected.[[RemainingElements]]remainingElementsCount 로 설정한다.
    13. remainingElementsCount.[[Value]]remainingElementsCount.[[Value]] + 1 로 설정한다.
    14. Invoke(nextPromise, "then", « resultCapability.[[Resolve]], onRejected ») 를 수행한다.
    15. indexindex + 1 로 설정한다.

27.2.4.3.2 Promise.any Reject Element Functions

Promise.any reject 요소 함수는 특정 Promise.any 요소를 reject 하는 데 사용되는 익명 내장 함수이다. 각 함수는 [[Index]], [[Errors]], [[Capability]], [[RemainingElements]], [[AlreadyCalled]] 내부 슬롯을 가진다.

Promise.any reject 요소 함수가 인수 x 로 호출되면 다음 단계를 수행한다:

  1. F 를 활성 함수 객체로 둔다.
  2. F.[[AlreadyCalled]]true 이면 undefined 를 반환한다.
  3. F.[[AlreadyCalled]]true 로 설정한다.
  4. indexF.[[Index]] 로 둔다.
  5. errorsF.[[Errors]] 로 둔다.
  6. promiseCapabilityF.[[Capability]] 로 둔다.
  7. remainingElementsCountF.[[RemainingElements]] 로 둔다.
  8. errors[index] 를 x 로 설정한다.
  9. remainingElementsCount.[[Value]]remainingElementsCount.[[Value]] - 1 로 설정한다.
  10. remainingElementsCount.[[Value]] = 0 이면,
    1. error 를 새로 생성된 AggregateError 객체로 둔다.
    2. DefinePropertyOrThrow(error, "errors", PropertyDescriptor { [[Configurable]]: true, [[Enumerable]]: false, [[Writable]]: true, [[Value]]: CreateArrayFromList(errors) }) 를 수행한다.
    3. Call(promiseCapability.[[Reject]], undefined, « error ») 를 반환한다.
  11. undefined 를 반환한다.

Promise.any reject 요소 함수의 "length" 프로퍼티는 1𝔽 이다.

27.2.4.4 Promise.prototype

Promise.prototype 의 초기 값은 Promise 프로토타입 객체이다.

이 프로퍼티는 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false } 특성을 가진다.

27.2.4.5 Promise.race ( iterable )

이 함수는 가장 먼저 settle 되는 전달된 promise 와 동일한 방식으로 settle 되는 새 promise 를 반환한다. 이 알고리즘을 수행하면서 전달된 iterable 의 모든 요소를 promise 로 resolve 한다.

  1. Cthis 값으로 둔다.
  2. promiseCapability 를 ? NewPromiseCapability(C) 로 둔다.
  3. promiseResolveCompletion(GetPromiseResolve(C)) 로 둔다.
  4. IfAbruptRejectPromise(promiseResolve, promiseCapability).
  5. iteratorRecordCompletion(GetIterator(iterable, sync)) 로 둔다.
  6. IfAbruptRejectPromise(iteratorRecord, promiseCapability).
  7. resultCompletion(PerformPromiseRace(iteratorRecord, C, promiseCapability, promiseResolve)) 로 둔다.
  8. resultabrupt completion 이면,
    1. iteratorRecord.[[Done]]false 이면 resultCompletion(IteratorClose(iteratorRecord, result)) 로 설정한다.
    2. IfAbruptRejectPromise(result, promiseCapability).
  9. result 를 반환한다.
Note 1

iterable 인수가 어떤 값도 산출하지 않거나 iterable 이 산출한 promise 들 중 어느 것도 settle 되지 않으면, 이 메서드가 반환하는 pending promise 는 결코 settle 되지 않는다.

Note 2

이 함수는 this 값이 Promise 생성자의 매개변수 규약을 지원하는 생성자 함수이며 또한 resolve 메서드를 제공한다고 기대한다.

27.2.4.5.1 PerformPromiseRace ( iteratorRecord, constructor, resultCapability, promiseResolve )

The abstract operation PerformPromiseRace takes arguments iteratorRecord (an Iterator Record), constructor (a constructor), resultCapability (a PromiseCapability Record), and promiseResolve (a function object) and returns either a normal completion containing an ECMAScript language value or a throw completion. It performs the following steps when called:

  1. 반복,
    1. next 를 ? IteratorStepValue(iteratorRecord) 로 둔다.
    2. nextdone 이면,
      1. resultCapability.[[Promise]] 를 반환한다.
    3. nextPromise 를 ? Call(promiseResolve, constructor, « next ») 로 둔다.
    4. Invoke(nextPromise, "then", « resultCapability.[[Resolve]], resultCapability.[[Reject]] ») 를 수행한다.

27.2.4.6 Promise.reject ( r )

이 함수는 전달된 인수로 reject 된 새로운 promise 를 반환한다.

  1. Cthis 값으로 둔다.
  2. promiseCapability 를 ? NewPromiseCapability(C) 로 둔다.
  3. Call(promiseCapability.[[Reject]], undefined, « r ») 를 수행한다.
  4. promiseCapability.[[Promise]] 를 반환한다.
Note

이 함수는 this 값이 Promise 생성자의 매개변수 규약을 지원하는 생성자 함수이기를 기대한다.

27.2.4.7 Promise.resolve ( x )

이 함수는 전달된 인수로 resolve 된 새로운 promise 를 반환하거나, 인수가 이 생성자가 생성한 promise 라면 그 인수 자체를 반환한다.

  1. Cthis 값으로 둔다.
  2. C 가 Object 가 아니면 TypeError 예외를 던진다.
  3. PromiseResolve(C, x) 를 반환한다.
Note

이 함수는 this 값이 Promise 생성자의 매개변수 규약을 지원하는 생성자 함수이기를 기대한다.

27.2.4.7.1 PromiseResolve ( C, x )

The abstract operation PromiseResolve takes arguments C (an Object) and x (an ECMAScript language value) and returns either a normal completion containing an ECMAScript language value or a throw completion. x 로 resolve 된 새로운 promise 를 반환한다. It performs the following steps when called:

  1. IsPromise(x) 가 true 이면,
    1. xConstructor 를 ? Get(x, "constructor") 로 둔다.
    2. SameValue(xConstructor, C) 가 true 이면 x 를 반환한다.
  2. promiseCapability 를 ? NewPromiseCapability(C) 로 둔다.
  3. Call(promiseCapability.[[Resolve]], undefined, « x ») 를 수행한다.
  4. promiseCapability.[[Promise]] 를 반환한다.

27.2.4.8 Promise.try ( callback, ...args )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. Cthis 값으로 둔다.
  2. C 가 Object 가 아니면 TypeError 예외를 던진다.
  3. promiseCapability 를 ? NewPromiseCapability(C) 로 둔다.
  4. statusCompletion(Call(callback, undefined, args)) 로 둔다.
  5. statusabrupt completion 이면,
    1. Call(promiseCapability.[[Reject]], undefined, « status.[[Value]] ») 를 수행한다.
  6. 그렇지 않으면,
    1. Call(promiseCapability.[[Resolve]], undefined, « status.[[Value]] ») 를 수행한다.
  7. promiseCapability.[[Promise]] 를 반환한다.
Note

이 함수는 this 값이 Promise 생성자의 매개변수 규약을 지원하는 생성자 함수이기를 기대한다.

27.2.4.9 Promise.withResolvers ( )

이 함수는 세 개의 프로퍼티를 가진 객체를 반환한다: 새로운 promise 와 그에 연관된 resolvereject 함수.

  1. Cthis 값으로 둔다.
  2. promiseCapability 를 ? NewPromiseCapability(C) 로 둔다.
  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.2.4.10 get Promise [ %Symbol.species% ]

Promise[%Symbol.species%] 는 set 접근자 함수가 undefined접근자 프로퍼티이다. 그 get 접근자 함수는 호출 시 다음 단계를 수행한다:

  1. this 값을 반환한다.

이 함수의 "name" 프로퍼티 값은 "get [Symbol.species]" 이다.

Note

Promise 프로토타입 메서드는 일반적으로 파생 객체를 생성하기 위해 this 값의 생성자를 사용한다. 그러나 서브클래스 생성자는 그 %Symbol.species% 프로퍼티를 재정의하여 기본 동작을 바꿀 수 있다.

27.2.5 Promise 프로토타입 객체의 프로퍼티 (Properties of the Promise Prototype Object)

Promise 프로토타입 객체는 다음과 같다:

  • %Promise.prototype% 이다.
  • [[Prototype]] 내부 슬롯의 값이 %Object.prototype% 이다.
  • 일반 객체이다.
  • [[PromiseState]] 내부 슬롯이나 Promise 인스턴스의 다른 어떤 내부 슬롯도 가지지 않는다.

27.2.5.1 Promise.prototype.catch ( onRejected )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. promisethis 값으로 둔다.
  2. Invoke(promise, "then", « undefined, onRejected ») 를 반환한다.

27.2.5.2 Promise.prototype.constructor

Promise.prototype.constructor 의 초기 값은 %Promise% 이다.

27.2.5.3 Promise.prototype.finally ( onFinally )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. promisethis 값으로 둔다.
  2. promise 가 Object 가 아니면 TypeError 예외를 던진다.
  3. C 를 ? SpeciesConstructor(promise, %Promise%) 로 둔다.
  4. Assert: IsConstructor(C) 는 true.
  5. IsCallable(onFinally) 가 false 이면,
    1. thenFinallyonFinally 로 둔다.
    2. catchFinallyonFinally 로 둔다.
  6. 그렇지 않으면,
    1. thenFinallyClosure 를 매개변수 (value) 를 가지고 onFinallyC 를 포획하며 호출 시 다음 단계를 수행하는 새로운 Abstract Closure 로 둔다:
      1. result 를 ? Call(onFinally, undefined) 로 둔다.
      2. p 를 ? PromiseResolve(C, result) 로 둔다.
      3. returnValue 를 매개변수 없는 새로운 Abstract Closure 로 두고 value 를 포획하며 호출 시 다음 단계를 수행하게 한다:
        1. NormalCompletion(value) 를 반환한다.
      4. valueThunkCreateBuiltinFunction(returnValue, 0, "", « ») 로 둔다.
      5. Invoke(p, "then", « valueThunk ») 를 반환한다.
    2. thenFinallyCreateBuiltinFunction(thenFinallyClosure, 1, "", « ») 로 둔다.
    3. catchFinallyClosure 를 매개변수 (reason) 를 가지고 onFinallyC 를 포획하며 호출 시 다음 단계를 수행하는 새로운 Abstract Closure 로 둔다:
      1. result 를 ? Call(onFinally, undefined) 로 둔다.
      2. p 를 ? PromiseResolve(C, result) 로 둔다.
      3. throwReason 을 매개변수 없는 새로운 Abstract Closure 로 두고 reason 을 포획하며 호출 시 다음 단계를 수행하게 한다:
        1. ThrowCompletion(reason) 를 반환한다.
      4. throwerCreateBuiltinFunction(throwReason, 0, "", « ») 로 둔다.
      5. Invoke(p, "then", « thrower ») 를 반환한다.
    4. catchFinallyCreateBuiltinFunction(catchFinallyClosure, 1, "", « ») 로 둔다.
  7. Invoke(promise, "then", « thenFinally, catchFinally ») 를 반환한다.

27.2.5.4 Promise.prototype.then ( onFulfilled, onRejected )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. promisethis 값으로 둔다.
  2. IsPromise(promise) 가 false 이면 TypeError 예외를 던진다.
  3. C 를 ? SpeciesConstructor(promise, %Promise%) 로 둔다.
  4. resultCapability 를 ? NewPromiseCapability(C) 로 둔다.
  5. PerformPromiseThen(promise, onFulfilled, onRejected, resultCapability) 를 반환한다.

27.2.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 ECMAScript language value. promise 에 대해 onFulfilledonRejected 를 정착(settlement) 동작으로 사용하여 “then” 연산을 수행한다. resultCapability 가 전달되면 그 promise 를 갱신하여 결과를 저장한다. 전달되지 않은 경우, 결과가 중요하지 않은 명세 내부 연산에 의해 호출된 것이다. It performs the following steps when called:

  1. Assert: IsPromise(promise) 는 true.
  2. resultCapability 가 존재하지 않으면,
    1. resultCapabilityundefined 로 설정한다.
  3. IsCallable(onFulfilled) 가 false 이면
    1. onFulfilledJobCallbackempty 로 둔다.
  4. 그렇지 않으면,
    1. onFulfilledJobCallbackHostMakeJobCallback(onFulfilled) 로 둔다.
  5. IsCallable(onRejected) 가 false 이면
    1. onRejectedJobCallbackempty 로 둔다.
  6. 그렇지 않으면,
    1. onRejectedJobCallbackHostMakeJobCallback(onRejected) 로 둔다.
  7. fulfillReactionPromiseReaction Record { [[Capability]]: resultCapability, [[Type]]: fulfill, [[Handler]]: onFulfilledJobCallback } 로 둔다.
  8. rejectReactionPromiseReaction Record { [[Capability]]: resultCapability, [[Type]]: reject, [[Handler]]: onRejectedJobCallback } 로 둔다.
  9. promise.[[PromiseState]]pending 이면,
    1. fulfillReactionpromise.[[PromiseFulfillReactions]] 에 추가한다.
    2. rejectReactionpromise.[[PromiseRejectReactions]] 에 추가한다.
  10. 그렇지 않고 promise.[[PromiseState]]fulfilled 이면,
    1. valuepromise.[[PromiseResult]] 로 둔다.
    2. fulfillJobNewPromiseReactionJob(fulfillReaction, value) 로 둔다.
    3. HostEnqueuePromiseJob(fulfillJob.[[Job]], fulfillJob.[[Realm]]) 를 수행한다.
  11. 그렇지 않으면,
    1. Assert: promise.[[PromiseState]]rejected.
    2. reasonpromise.[[PromiseResult]] 로 둔다.
    3. promise.[[PromiseIsHandled]]false 이면 HostPromiseRejectionTracker(promise, "handle") 를 수행한다.
    4. rejectJobNewPromiseReactionJob(rejectReaction, reason) 로 둔다.
    5. HostEnqueuePromiseJob(rejectJob.[[Job]], rejectJob.[[Realm]]) 를 수행한다.
  12. promise.[[PromiseIsHandled]]true 로 설정한다.
  13. resultCapabilityundefined 이면
    1. undefined 를 반환한다.
  14. 그렇지 않으면
    1. resultCapability.[[Promise]] 를 반환한다.

27.2.5.5 Promise.prototype [ %Symbol.toStringTag% ]

%Symbol.toStringTag% 프로퍼티의 초기 값은 문자열 "Promise" 이다.

이 프로퍼티는 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true } 특성을 가진다.

27.2.6 Promise 인스턴스의 프로퍼티 (Properties of Promise Instances)

Promise 인스턴스는 (내재 %Promise.prototype%) Promise 프로토타입 객체로부터 프로퍼티를 상속하는 일반 객체이다. Promise 인스턴스는 Table 90에 기술된 내부 슬롯을 가지고 초기화된다.

Table 90: Promise 인스턴스의 내부 슬롯 (Internal Slots of Promise Instances)
Internal Slot Type Description
[[PromiseState]] pending, fulfilled, or rejected 해당 promise 의 then 메서드로의 호출에 어떻게 반응할지 결정한다.
[[PromiseResult]] an ECMAScript language value or empty promise 가 fulfilled 또는 rejected 된 값(있다면). [[PromiseState]]pending 일 때 그리고 그 때에만 empty.
[[PromiseFulfillReactions]] a List of PromiseReaction Records promise 가 pending 에서 fulfilled 상태로 전이할 때 처리될 기록들.
[[PromiseRejectReactions]] a List of PromiseReaction Records promise 가 pending 에서 rejected 상태로 전이할 때 처리될 기록들.
[[PromiseIsHandled]] a Boolean 이 promise 가 한 번이라도 fulfillment 또는 rejection 핸들러를 가졌는지 나타내며, 처리되지 않은 거부 추적(unhandled rejection tracking)에 사용된다.

27.3 GeneratorFunction 객체 (GeneratorFunction Objects)

GeneratorFunction 들은 보통 GeneratorDeclaration, GeneratorExpression, GeneratorMethod 를 평가하여 생성되는 함수들이다. 또한 %GeneratorFunction% 내재(intrinsic)를 호출하여 생성될 수도 있다.

Figure 6 (Informative): Generator 객체 간의 관계 (Generator Objects Relationships)
수많은 상자와 화살표의 구조도.

27.3.1 GeneratorFunction 생성자 (The GeneratorFunction Constructor)

GeneratorFunction 생성자는 다음과 같다:

  • %GeneratorFunction% 이다.
  • Function 의 서브클래스이다.
  • 생성자가 아니라 함수로 호출될 때 새 GeneratorFunction 을 생성하고 초기화한다. 따라서 함수 호출 GeneratorFunction (…) 은 동일한 인수로 new GeneratorFunction (…) 객체 생성 표현식과 동등하다.
  • 클래스 정의의 extends 절 값으로 사용할 수 있다. 지정된 GeneratorFunction 동작을 상속하려는 서브클래스 생성자는 내장 GeneratorFunction 동작에 필요한 내부 슬롯을 가진 서브클래스 인스턴스를 생성·초기화하기 위해 GeneratorFunction 생성자에 대한 super 호출을 포함해야 한다. 제너레이터 함수 객체를 정의하는 모든 ECMAScript 문법 형태는 GeneratorFunction 의 직접 인스턴스를 생성한다. GeneratorFunction 서브클래스 인스턴스를 만들 수 있는 문법적 수단은 없다.

27.3.1.1 GeneratorFunction ( ...parameterArgs, bodyArg )

마지막 인수(있다면)는 제너레이터 함수의 본문(실행 코드)을 지정한다; 그 앞의 인수들은 형식 매개변수를 지정한다.

이 함수는 호출될 때 다음 단계를 수행한다:

  1. C 를 활성 함수 객체로 둔다.
  2. bodyArg 가 존재하지 않으면 bodyArg 를 빈 문자열로 설정한다.
  3. CreateDynamicFunction(C, NewTarget, generator, parameterArgs, bodyArg) 를 반환한다.
Note

20.2.1.1 의 NOTE 를 참조.

27.3.2 GeneratorFunction 생성자의 프로퍼티 (Properties of the GeneratorFunction Constructor)

GeneratorFunction 생성자는 다음과 같다:

  • Function 생성자로부터 상속하는 표준 내장 함수 객체이다.
  • [[Prototype]] 내부 슬롯 값이 %Function% 이다.
  • 𝔽 이다.
  • "name" 프로퍼티 값이 "GeneratorFunction" 이다.
  • 다음 프로퍼티들을 가진다:

27.3.2.1 GeneratorFunction.prototype

GeneratorFunction.prototype 의 초기 값은 GeneratorFunction 프로토타입 객체이다.

이 프로퍼티는 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false } 특성을 가진다.

27.3.3 GeneratorFunction 프로토타입 객체의 프로퍼티 (Properties of the GeneratorFunction Prototype Object)

GeneratorFunction 프로토타입 객체는 다음과 같다:

27.3.3.1 GeneratorFunction.prototype.constructor

GeneratorFunction.prototype.constructor 의 초기 값은 %GeneratorFunction% 이다.

이 프로퍼티는 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true } 특성을 가진다.

27.3.3.2 GeneratorFunction.prototype.prototype

GeneratorFunction.prototype.prototype 의 초기 값은 %GeneratorPrototype% 이다.

이 프로퍼티는 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true } 특성을 가진다.

27.3.3.3 GeneratorFunction.prototype [ %Symbol.toStringTag% ]

%Symbol.toStringTag% 프로퍼티의 초기 값은 문자열 "GeneratorFunction" 이다.

이 프로퍼티는 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true } 특성을 가진다.

27.3.4 GeneratorFunction 인스턴스 (GeneratorFunction Instances)

모든 GeneratorFunction 인스턴스는 ECMAScript 함수 객체이며 Table 28 에 열거된 내부 슬롯을 가진다. 그러한 모든 인스턴스의 [[IsClassConstructor]] 내부 슬롯 값은 false 이다.

각 GeneratorFunction 인스턴스는 다음 자체 프로퍼티들을 가진다:

27.3.4.1 length

20.2.4.1 에 기술된 Function 인스턴스의 "length" 프로퍼티 명세는 GeneratorFunction 인스턴스에도 적용된다.

27.3.4.2 name

20.2.4.2 에 기술된 Function 인스턴스의 "name" 프로퍼티 명세는 GeneratorFunction 인스턴스에도 적용된다.

27.3.4.3 prototype

GeneratorFunction 인스턴스가 생성될 때마다 또 다른 일반 객체가 생성되어 해당 제너레이터 함수의 "prototype" 프로퍼티 초기 값이 된다. 이 prototype 프로퍼티의 값은 제너레이터 함수 객체[[Call]] 로 호출될 때 새로 생성되는 Generator 의 [[Prototype]] 내부 슬롯을 초기화하는 데 사용된다.

이 프로퍼티는 { [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false } 특성을 가진다.

Note

Function 인스턴스와 달리, GeneratorFunction 의 "prototype" 프로퍼티 값인 객체는 그 값이 해당 GeneratorFunction 인스턴스인 "constructor" 프로퍼티를 가지지 않는다.

27.4 AsyncGeneratorFunction 객체 (AsyncGeneratorFunction Objects)

AsyncGeneratorFunction 들은 보통 AsyncGeneratorDeclaration, AsyncGeneratorExpression, AsyncGeneratorMethod 문법 생산물을 평가하여 생성된다. 또한 %AsyncGeneratorFunction% 내재를 호출하여 생성될 수 있다.

27.4.1 AsyncGeneratorFunction 생성자 (The AsyncGeneratorFunction Constructor)

AsyncGeneratorFunction 생성자는 다음과 같다:

  • %AsyncGeneratorFunction% 이다.
  • Function 의 서브클래스이다.
  • 생성자가 아니라 함수로 호출될 때 새 AsyncGeneratorFunction 을 생성하고 초기화한다. 따라서 AsyncGeneratorFunction (...) 호출은 동일한 인수의 new AsyncGeneratorFunction (...) 과 동등하다.
  • 클래스 정의의 extends 절 값으로 사용할 수 있다. 지정된 AsyncGeneratorFunction 동작을 상속하려는 서브클래스 생성자는 내장 AsyncGeneratorFunction 동작에 필요한 내부 슬롯을 가진 서브클래스 인스턴스를 생성·초기화하기 위해 AsyncGeneratorFunction 생성자에 대한 super 호출을 포함해야 한다. async generator 함수 객체를 정의하는 모든 ECMAScript 문법 형태는 AsyncGeneratorFunction 의 직접 인스턴스를 생성한다. AsyncGeneratorFunction 서브클래스 인스턴스를 만들 수 있는 문법적 수단은 없다.

27.4.1.1 AsyncGeneratorFunction ( ...parameterArgs, bodyArg )

마지막 인수(있다면)는 async generator 함수의 본문(실행 코드)을 지정한다; 그 앞의 인수들은 형식 매개변수를 지정한다.

이 함수는 호출될 때 다음 단계를 수행한다:

  1. C 를 활성 함수 객체로 둔다.
  2. bodyArg 가 존재하지 않으면 bodyArg 를 빈 문자열로 설정한다.
  3. CreateDynamicFunction(C, NewTarget, async-generator, parameterArgs, bodyArg) 를 반환한다.
Note

20.2.1.1 의 NOTE 를 참조.

27.4.2 AsyncGeneratorFunction 생성자의 프로퍼티 (Properties of the AsyncGeneratorFunction Constructor)

AsyncGeneratorFunction 생성자는 다음과 같다:

  • Function 생성자로부터 상속하는 표준 내장 함수 객체이다.
  • [[Prototype]] 내부 슬롯 값이 %Function% 이다.
  • 𝔽 이다.
  • "name" 프로퍼티 값이 "AsyncGeneratorFunction" 이다.
  • 다음 프로퍼티들을 가진다:

27.4.2.1 AsyncGeneratorFunction.prototype

AsyncGeneratorFunction.prototype 의 초기 값은 AsyncGeneratorFunction 프로토타입 객체이다.

이 프로퍼티는 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false } 특성을 가진다.

27.4.3 AsyncGeneratorFunction 프로토타입 객체의 프로퍼티 (Properties of the AsyncGeneratorFunction Prototype Object)

AsyncGeneratorFunction 프로토타입 객체는 다음과 같다:

27.4.3.1 AsyncGeneratorFunction.prototype.constructor

AsyncGeneratorFunction.prototype.constructor 의 초기 값은 %AsyncGeneratorFunction% 이다.

이 프로퍼티는 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true } 특성을 가진다.

27.4.3.2 AsyncGeneratorFunction.prototype.prototype

AsyncGeneratorFunction.prototype.prototype 의 초기 값은 %AsyncGeneratorPrototype% 이다.

이 프로퍼티는 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true } 특성을 가진다.

27.4.3.3 AsyncGeneratorFunction.prototype [ %Symbol.toStringTag% ]

%Symbol.toStringTag% 프로퍼티의 초기 값은 문자열 "AsyncGeneratorFunction" 이다.

이 프로퍼티는 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true } 특성을 가진다.

27.4.4 AsyncGeneratorFunction 인스턴스 (AsyncGeneratorFunction Instances)

모든 AsyncGeneratorFunction 인스턴스는 ECMAScript 함수 객체이며 Table 28 에 열거된 내부 슬롯을 가진다. 그러한 모든 인스턴스의 [[IsClassConstructor]] 내부 슬롯 값은 false 이다.

각 AsyncGeneratorFunction 인스턴스는 다음 자체 프로퍼티들을 가진다:

27.4.4.1 length

"length" 프로퍼티의 값은 AsyncGeneratorFunction 이 일반적으로 기대하는 인수 개수를 나타내는 정수 Number 이다. 그러나 언어는 다른 개수의 인수로 호출하는 것을 허용한다. "length" 프로퍼티에 지정된 것과 다른 인수 개수로 호출될 때의 AsyncGeneratorFunction 동작은 함수에 따라 다르다.

이 프로퍼티는 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true } 특성을 가진다.

27.4.4.2 name

20.2.4.2 에 기술된 Function 인스턴스의 "name" 프로퍼티 명세는 AsyncGeneratorFunction 인스턴스에도 적용된다.

27.4.4.3 prototype

AsyncGeneratorFunction 인스턴스가 생성될 때마다 또 다른 일반 객체가 생성되어 해당 async generator 함수의 "prototype" 프로퍼티 초기 값이 된다. 이 prototype 프로퍼티 값은 generator 함수 객체[[Call]] 로 호출될 때 새로 생성되는 AsyncGenerator 의 [[Prototype]] 내부 슬롯을 초기화하는 데 사용된다.

이 프로퍼티는 { [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false } 특성을 가진다.

Note

function 인스턴스와 달리, AsyncGeneratorFunction 의 "prototype" 프로퍼티 값인 객체는 그 값이 해당 AsyncGeneratorFunction 인스턴스인 "constructor" 프로퍼티를 가지지 않는다.

27.5 Generator 객체 (Generator Objects)

Generator 는 제너레이터 함수를 호출하여 생성되며 이터레이터 인터페이스와 iterable 인터페이스를 모두 준수한다.

Generator 인스턴스는 그것을 생성한 제너레이터 함수의 "prototype" 프로퍼티 초기 값으로부터 직접 프로퍼티를 상속한다. Generator 인스턴스는 %GeneratorPrototype% 으로부터 간접적으로 프로퍼티를 상속한다.

27.5.1 %GeneratorPrototype% 객체 (The %GeneratorPrototype% Object)

%GeneratorPrototype% 객체는 다음과 같다:

  • %GeneratorFunction.prototype.prototype% 이다.
  • 일반 객체이다.
  • Generator 인스턴스가 아니며 [[GeneratorState]] 내부 슬롯을 가지지 않는다.
  • [[Prototype]] 내부 슬롯 값이 %Iterator.prototype% 이다.
  • 모든 Generator 인스턴스가 간접적으로 상속하는 프로퍼티들을 가진다.

27.5.1.1 %GeneratorPrototype%.constructor

%GeneratorPrototype%.constructor 의 초기 값은 %GeneratorFunction.prototype% 이다.

이 프로퍼티는 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true } 특성을 가진다.

27.5.1.2 %GeneratorPrototype%.next ( value )

  1. GeneratorResume(this value, value, empty) 를 반환한다.

27.5.1.3 %GeneratorPrototype%.return ( value )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. gthis 값으로 둔다.
  2. CReturnCompletion(value) 로 둔다.
  3. GeneratorResumeAbrupt(g, C, empty) 를 반환한다.

27.5.1.4 %GeneratorPrototype%.throw ( exception )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. gthis 값으로 둔다.
  2. CThrowCompletion(exception) 로 둔다.
  3. GeneratorResumeAbrupt(g, C, empty) 를 반환한다.

27.5.1.5 %GeneratorPrototype% [ %Symbol.toStringTag% ]

%Symbol.toStringTag% 프로퍼티의 초기 값은 문자열 "Generator" 이다.

이 프로퍼티는 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true } 특성을 가진다.

27.5.2 Generator 인스턴스의 프로퍼티 (Properties of Generator Instances)

Generator 인스턴스는 Table 91 에 기술된 내부 슬롯을 가지고 초기화된다.

Table 91: Generator 인스턴스의 내부 슬롯 (Internal Slots of Generator Instances)
Internal Slot Type Description
[[GeneratorState]] suspended-start, suspended-yield, executing, or completed 제너레이터의 현재 실행 상태.
[[GeneratorContext]] an execution context 이 제너레이터의 코드를 실행할 때 사용되는 실행 컨텍스트.
[[GeneratorBrand]] a String or empty 서로 다른 종류의 제너레이터를 구분하는 브랜드. ECMAScript 소스 텍스트로 선언된 제너레이터의 [[GeneratorBrand]] 는 항상 empty.

27.5.3 Generator 추상 연산 (Generator Abstract Operations)

27.5.3.1 GeneratorStart ( generator, generatorBody )

The abstract operation GeneratorStart takes arguments generator (a Generator) and generatorBody (a FunctionBody Parse Node or an Abstract Closure with no parameters) and returns unused. It performs the following steps when called:

  1. Assert: generator.[[GeneratorState]]suspended-start.
  2. genContext 를 실행 중인 실행 컨텍스트로 둔다.
  3. genContext 의 Generator 컴포넌트를 generator 로 설정한다.
  4. closure 를 매개변수 없고 generatorBody 를 포획하며 호출 시 다음 단계를 수행하는 새로운 Abstract Closure 로 둔다:
    1. acGenContext 를 실행 중인 실행 컨텍스트로 둔다.
    2. acGeneratoracGenContext 의 Generator 컴포넌트로 둔다.
    3. generatorBody 가 Parse Node 이면
      1. resultCompletion(Evaluation of generatorBody) 로 둔다.
    4. 그렇지 않으면
      1. Assert: generatorBody 는 매개변수 없는 Abstract Closure.
      2. resultCompletion(generatorBody()) 로 둔다.
    5. Assert: 여기로 돌아오면 제너레이터는 예외를 던졌거나 암시적 또는 명시적 return 을 수행했다.
    6. acGenContext 를 실행 컨텍스트 스택에서 제거하고 스택 꼭대기 실행 컨텍스트를 실행 중인 컨텍스트로 복원한다.
    7. acGenerator.[[GeneratorState]]completed 로 설정한다.
    8. 주: 제너레이터가 completed 상태에 들어가면 다시 나오지 않고 그 연관 실행 컨텍스트는 재개되지 않는다. acGenerator 와 연관된 실행 상태는 이 시점에서 폐기 가능.
    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 의 코드 평가 상태를 설정하여 해당 실행 컨텍스트가 재개될 때 closure 가 인수 없이 호출되도록 한다.
  6. generator.[[GeneratorContext]]genContext 로 설정한다.
  7. unused 를 반환한다.

27.5.3.2 GeneratorValidate ( generator, generatorBrand )

The abstract operation GeneratorValidate takes arguments generator (an ECMAScript language value) and generatorBrand (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(generator, [[GeneratorState]]) 를 수행한다.
  2. RequireInternalSlot(generator, [[GeneratorBrand]]) 를 수행한다.
  3. generator.[[GeneratorBrand]]generatorBrand 와 다르면 TypeError 예외를 던진다.
  4. Assert: generator 는 또한 [[GeneratorContext]] 내부 슬롯을 가진다.
  5. stategenerator.[[GeneratorState]] 로 둔다.
  6. stateexecuting 이면 TypeError 예외를 던진다.
  7. state 를 반환한다.

27.5.3.3 GeneratorResume ( generator, value, generatorBrand )

The abstract operation GeneratorResume takes arguments generator (an ECMAScript language value), value (an ECMAScript language value or empty), and generatorBrand (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(generator, generatorBrand) 로 둔다.
  2. statecompleted 이면 CreateIteratorResultObject(undefined, true) 를 반환한다.
  3. Assert: statesuspended-start 또는 suspended-yield.
  4. genContextgenerator.[[GeneratorContext]] 로 둔다.
  5. methodContext 를 실행 중인 실행 컨텍스트로 둔다.
  6. methodContext 를 suspend 한다.
  7. generator.[[GeneratorState]]executing 으로 설정한다.
  8. genContext 를 실행 컨텍스트 스택에 push; 이제 genContext 가 실행 중인 실행 컨텍스트.
  9. genContext 의 중단된 평가를 재개 하되 그것을 중단시킨 연산의 결과로 NormalCompletion(value) 를 사용한다. result 를 재개된 계산이 반환한 값으로 둔다.
  10. Assert: 여기로 돌아올 때 genContext 는 이미 실행 컨텍스트 스택에서 제거되었고 methodContext 가 현재 실행 중인 실행 컨텍스트.
  11. result 를 반환한다.

27.5.3.4 GeneratorResumeAbrupt ( generator, abruptCompletion, generatorBrand )

The abstract operation GeneratorResumeAbrupt takes arguments generator (an ECMAScript language value), abruptCompletion (a return completion or a throw completion), and generatorBrand (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(generator, generatorBrand) 로 둔다.
  2. statesuspended-start 이면
    1. generator.[[GeneratorState]]completed 로 설정한다.
    2. 주: 제너레이터가 completed 상태에 들어가면 다시 나오지 않고 연관 실행 컨텍스트는 재개되지 않는다. generator 와 연관된 실행 상태는 이 시점에서 폐기 가능.
    3. statecompleted 로 설정한다.
  3. statecompleted 이면
    1. abruptCompletionreturn completion 이면
      1. CreateIteratorResultObject(abruptCompletion.[[Value]], true) 를 반환한다.
    2. abruptCompletion 를 반환한다.
  4. Assert: statesuspended-yield.
  5. genContextgenerator.[[GeneratorContext]] 로 둔다.
  6. methodContext 를 실행 중인 실행 컨텍스트로 둔다.
  7. methodContext 를 suspend 한다.
  8. generator.[[GeneratorState]]executing 으로 설정한다.
  9. genContext 를 실행 컨텍스트 스택에 push; 이제 genContext 가 실행 중인 실행 컨텍스트.
  10. genContext 의 중단된 평가를 재개 하되 그것을 중단시킨 연산의 결과로 abruptCompletion 을 사용한다. result 를 재개된 계산이 반환한 Completion Record 로 둔다.
  11. Assert: 여기로 돌아올 때 genContext 는 이미 실행 컨텍스트 스택에서 제거되었고 methodContext 가 현재 실행 중인 실행 컨텍스트.
  12. result 를 반환한다.

27.5.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. genContext 를 실행 중인 실행 컨텍스트로 둔다.
  2. genContext 가 Generator 컴포넌트를 가지지 않으면 non-generator 를 반환한다.
  3. generatorgenContext 의 Generator 컴포넌트 값으로 둔다.
  4. generator[[AsyncGeneratorState]] 내부 슬롯이 있으면 async 를 반환한다.
  5. 아니면 sync 를 반환한다.

27.5.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. generatorgenContext 의 Generator 컴포넌트 값으로 둔다.
  4. Assert: GetGeneratorKind() 는 sync.
  5. generator.[[GeneratorState]]suspended-yield 로 설정한다.
  6. genContext 를 실행 컨텍스트 스택에서 제거하고 스택 꼭대기 실행 컨텍스트를 실행 중인 컨텍스트로 복원한다.
  7. callerContext 를 실행 중인 실행 컨텍스트로 둔다.
  8. callerContextNormalCompletion(iteratorResult) 를 전달하며 재개한다. genContext 가 다시 재개되면 resumptionValue 를 재개된 Completion Record 로 둔다.
  9. Assert: 여기 도달했다면 genContext 가 다시 실행 중인 실행 컨텍스트이다.
  10. resumptionValue 를 반환한다.

27.5.3.7 Yield ( value )

The abstract operation Yield takes argument value (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. generatorKindGetGeneratorKind() 로 둔다.
  2. generatorKindasync 이면 ? AsyncGeneratorYield(? Await(value)) 를 반환한다.
  3. 그렇지 않으면 ? GeneratorYield(CreateIteratorResultObject(value, false)) 를 반환한다.

27.5.3.8 CreateIteratorFromClosure ( closure, generatorBrand, generatorPrototype [ , extraSlots ] )

The abstract operation CreateIteratorFromClosure takes arguments closure (an Abstract Closure with no parameters), generatorBrand (a String or empty), and generatorPrototype (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. 주: closure 는 IteratorResult 객체를 산출하기 위해 Yield 연산을 사용할 수 있다.
  2. extraSlots 가 존재하지 않으면 새 빈 List 로 설정한다.
  3. internalSlotsListextraSlots 와 « [[GeneratorState]], [[GeneratorContext]], [[GeneratorBrand]] » 의 리스트 연결로 둔다.
  4. generatorOrdinaryObjectCreate(generatorPrototype, internalSlotsList) 로 둔다.
  5. generator.[[GeneratorBrand]]generatorBrand 로 설정한다.
  6. generator.[[GeneratorState]]suspended-start 로 설정한다.
  7. callerContext 를 실행 중인 실행 컨텍스트로 둔다.
  8. calleeContext 를 새로운 실행 컨텍스트로 둔다.
  9. calleeContext 의 Function 을 null 로 설정한다.
  10. calleeContextRealm 을 현재 Realm Record 로 설정한다.
  11. calleeContext 의 ScriptOrModule 을 callerContext 의 ScriptOrModule 로 설정한다.
  12. callerContext 가 이미 suspend 상태가 아니면 suspend 한다.
  13. calleeContext 를 실행 컨텍스트 스택에 push; 이제 calleeContext 가 실행 중인 실행 컨텍스트.
  14. GeneratorStart(generator, closure) 를 수행한다.
  15. calleeContext 를 실행 컨텍스트 스택에서 제거하고 callerContext 를 실행 중인 실행 컨텍스트로 복원한다.
  16. generator 를 반환한다.

27.6 AsyncGenerator 객체 (AsyncGenerator Objects)

AsyncGenerator 는 async 제너레이터 함수를 호출하여 생성되며 async 이터레이터 인터페이스와 async iterable 인터페이스를 모두 준수한다.

AsyncGenerator 인스턴스는 그것을 생성한 async 제너레이터 함수의 "prototype" 프로퍼티 초기 값으로부터 직접 프로퍼티를 상속한다. AsyncGenerator 인스턴스는 %AsyncGeneratorPrototype% 으로부터 간접적으로 프로퍼티를 상속한다.

27.6.1 %AsyncGeneratorPrototype% 객체 (The %AsyncGeneratorPrototype% Object)

%AsyncGeneratorPrototype% 객체:

  • %AsyncGeneratorFunction.prototype.prototype% 이다.
  • 일반 객체이다.
  • AsyncGenerator 인스턴스가 아니며 [[AsyncGeneratorState]] 내부 슬롯을 갖지 않는다.
  • [[Prototype]] 내부 슬롯 값이 %AsyncIteratorPrototype% 이다.
  • 모든 AsyncGenerator 인스턴스가 간접적으로 상속하는 프로퍼티들을 가진다.

27.6.1.1 %AsyncGeneratorPrototype%.constructor

%AsyncGeneratorPrototype%.constructor 의 초기 값은 %AsyncGeneratorFunction.prototype% 이다.

이 프로퍼티는 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true } 특성을 가진다.

27.6.1.2 %AsyncGeneratorPrototype%.next ( value )

  1. generatorthis 값으로 둔다.
  2. promiseCapability 를 ! NewPromiseCapability(%Promise%) 로 둔다.
  3. resultCompletion(AsyncGeneratorValidate(generator, empty)) 로 둔다.
  4. IfAbruptRejectPromise(result, promiseCapability).
  5. stategenerator.[[AsyncGeneratorState]] 로 둔다.
  6. statecompleted 이면,
    1. iteratorResultCreateIteratorResultObject(undefined, true) 로 둔다.
    2. Call(promiseCapability.[[Resolve]], undefined, « iteratorResult ») 를 수행한다.
    3. promiseCapability.[[Promise]] 를 반환한다.
  7. completionNormalCompletion(value) 로 둔다.
  8. AsyncGeneratorEnqueue(generator, completion, promiseCapability) 를 수행한다.
  9. statesuspended-start 또는 suspended-yield 이면,
    1. AsyncGeneratorResume(generator, completion) 를 수행한다.
  10. 그렇지 않으면,
    1. Assert: stateexecuting 또는 draining-queue.
  11. promiseCapability.[[Promise]] 를 반환한다.

27.6.1.3 %AsyncGeneratorPrototype%.return ( value )

  1. generatorthis 값으로 둔다.
  2. promiseCapability 를 ! NewPromiseCapability(%Promise%) 로 둔다.
  3. resultCompletion(AsyncGeneratorValidate(generator, empty)) 로 둔다.
  4. IfAbruptRejectPromise(result, promiseCapability).
  5. completionReturnCompletion(value) 로 둔다.
  6. AsyncGeneratorEnqueue(generator, completion, promiseCapability) 를 수행한다.
  7. stategenerator.[[AsyncGeneratorState]] 로 둔다.
  8. statesuspended-start 또는 completed 이면
    1. generator.[[AsyncGeneratorState]]draining-queue 로 설정한다.
    2. AsyncGeneratorAwaitReturn(generator) 를 수행한다.
  9. Else if statesuspended-yield 이면
    1. AsyncGeneratorResume(generator, completion) 를 수행한다.
  10. 그렇지 않으면,
    1. Assert: stateexecuting 또는 draining-queue.
  11. promiseCapability.[[Promise]] 를 반환한다.

27.6.1.4 %AsyncGeneratorPrototype%.throw ( exception )

  1. generatorthis 값으로 둔다.
  2. promiseCapability 를 ! NewPromiseCapability(%Promise%) 로 둔다.
  3. resultCompletion(AsyncGeneratorValidate(generator, empty)) 로 둔다.
  4. IfAbruptRejectPromise(result, promiseCapability).
  5. stategenerator.[[AsyncGeneratorState]] 로 둔다.
  6. statesuspended-start 이면
    1. generator.[[AsyncGeneratorState]]completed 로 설정한다.
    2. statecompleted 로 설정한다.
  7. statecompleted 이면
    1. Call(promiseCapability.[[Reject]], undefined, « exception ») 를 수행한다.
    2. promiseCapability.[[Promise]] 를 반환한다.
  8. completionThrowCompletion(exception) 로 둔다.
  9. AsyncGeneratorEnqueue(generator, completion, promiseCapability) 를 수행한다.
  10. statesuspended-yield 이면
    1. AsyncGeneratorResume(generator, completion) 를 수행한다.
  11. 그렇지 않으면,
    1. Assert: stateexecuting 또는 draining-queue.
  12. promiseCapability.[[Promise]] 를 반환한다.

27.6.1.5 %AsyncGeneratorPrototype% [ %Symbol.toStringTag% ]

%Symbol.toStringTag% 프로퍼티의 초기 값은 문자열 "AsyncGenerator" 이다.

이 프로퍼티는 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true } 특성을 가진다.

27.6.2 AsyncGenerator 인스턴스의 프로퍼티 (Properties of AsyncGenerator Instances)

AsyncGenerator 인스턴스는 아래에 기술된 내부 슬롯을 가지고 초기화된다:

Table 92: AsyncGenerator 인스턴스의 내부 슬롯 (Internal Slots of AsyncGenerator Instances)
Internal Slot Type Description
[[AsyncGeneratorState]] suspended-start, suspended-yield, executing, draining-queue, or completed async 제너레이터의 현재 실행 상태.
[[AsyncGeneratorContext]] an execution context 이 async 제너레이터의 코드를 실행할 때 사용되는 실행 컨텍스트.
[[AsyncGeneratorQueue]] a List of AsyncGeneratorRequest Records async 제너레이터 재개 요청을 나타내는 레코드. 상태 전이 중을 제외하면 [[AsyncGeneratorState]]executing 또는 draining-queue 일 때 그리고 그 때에만 비어 있지 않다.
[[GeneratorBrand]] a String or empty 서로 다른 종류의 async 제너레이터를 구분하는 브랜드. ECMAScript 소스 텍스트로 선언된 async 제너레이터의 [[GeneratorBrand]] 는 항상 empty.

27.6.3 AsyncGenerator 추상 연산 (AsyncGenerator Abstract Operations)

27.6.3.1 AsyncGeneratorRequest 레코드 (AsyncGeneratorRequest Records)

AsyncGeneratorRequest 는 async 제너레이터를 어떻게 재개해야 하는지에 대한 정보를 저장하고 해당 promise 를 이행하거나 거부하기 위한 capability 를 포함하는 Record 값이다.

다음 필드를 가진다:

Table 93: AsyncGeneratorRequest Record Fields
Field Name Value Meaning
[[Completion]] a Completion Record async 제너레이터를 재개할 때 사용할 Completion Record.
[[Capability]] a PromiseCapability Record 이 요청과 연관된 promise capability.

27.6.3.2 AsyncGeneratorStart ( generator, generatorBody )

The abstract operation AsyncGeneratorStart takes arguments generator (an AsyncGenerator) and generatorBody (a FunctionBody Parse Node or an Abstract Closure with no parameters) and returns unused. It performs the following steps when called:

  1. Assert: generator.[[AsyncGeneratorState]]suspended-start.
  2. genContext 를 실행 중인 실행 컨텍스트로 둔다.
  3. genContext 의 Generator 컴포넌트를 generator 로 설정한다.
  4. closure 를 매개변수 없고 generatorBody 를 포획하며 호출 시 다음 단계를 수행하는 새로운 Abstract Closure 로 둔다:
    1. acGenContext 를 실행 중인 실행 컨텍스트로 둔다.
    2. acGeneratoracGenContext 의 Generator 컴포넌트로 둔다.
    3. generatorBody 가 Parse Node 이면
      1. resultCompletion(Evaluation of generatorBody) 로 둔다.
    4. 그렇지 않으면
      1. Assert: generatorBody 는 매개변수 없는 Abstract Closure.
      2. resultCompletion(generatorBody()) 로 둔다.
    5. Assert: 여기로 돌아오면 async 제너레이터는 예외를 던졌거나 암시적 또는 명시적 return 을 수행한 것이다.
    6. acGenContext 를 실행 컨텍스트 스택에서 제거하고 스택 꼭대기 실행 컨텍스트를 실행 중인 컨텍스트로 복원한다.
    7. acGenerator.[[AsyncGeneratorState]]draining-queue 로 설정한다.
    8. resultnormal completion 이면 resultNormalCompletion(undefined) 로 설정한다.
    9. resultreturn completion 이면 resultNormalCompletion(result.[[Value]]) 로 설정한다.
    10. AsyncGeneratorCompleteStep(acGenerator, result, true) 를 수행한다.
    11. AsyncGeneratorDrainQueue(acGenerator) 를 수행한다.
    12. NormalCompletion(undefined) 를 반환한다.
  5. genContext 의 코드 평가 상태를 설정하여 그 실행 컨텍스트가 재개될 때 closure 가 인수 없이 호출되도록 한다.
  6. generator.[[AsyncGeneratorContext]]genContext 로 설정한다.
  7. generator.[[AsyncGeneratorQueue]] 를 새 빈 List 로 설정한다.
  8. unused 를 반환한다.

27.6.3.3 AsyncGeneratorValidate ( generator, generatorBrand )

The abstract operation AsyncGeneratorValidate takes arguments generator (an ECMAScript language value) and generatorBrand (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(generator, [[AsyncGeneratorContext]]) 를 수행한다.
  2. RequireInternalSlot(generator, [[AsyncGeneratorState]]) 를 수행한다.
  3. RequireInternalSlot(generator, [[AsyncGeneratorQueue]]) 를 수행한다.
  4. generator.[[GeneratorBrand]]generatorBrand 와 다르면 TypeError 예외를 던진다.
  5. unused 를 반환한다.

27.6.3.4 AsyncGeneratorEnqueue ( generator, completion, promiseCapability )

The abstract operation AsyncGeneratorEnqueue takes arguments generator (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. requestgenerator.[[AsyncGeneratorQueue]] 에 추가한다.
  3. unused 를 반환한다.

27.6.3.5 AsyncGeneratorCompleteStep ( generator, completion, done [ , realm ] )

The abstract operation AsyncGeneratorCompleteStep takes arguments generator (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: generator.[[AsyncGeneratorQueue]] 는 비어 있지 않다.
  2. nextgenerator.[[AsyncGeneratorQueue]] 의 첫 번째 요소로 둔다.
  3. 첫 번째 요소를 generator.[[AsyncGeneratorQueue]] 에서 제거한다.
  4. promiseCapabilitynext.[[Capability]] 로 둔다.
  5. valuecompletion.[[Value]] 로 둔다.
  6. completionthrow completion 이면,
    1. Call(promiseCapability.[[Reject]], undefined, « value ») 를 수행한다.
  7. 그렇지 않으면,
    1. Assert: completionnormal completion.
    2. realm 이 존재하면,
      1. oldRealm 을 실행 중인 실행 컨텍스트의 Realm 으로 둔다.
      2. 실행 중인 실행 컨텍스트의 Realmrealm 으로 설정한다.
      3. iteratorResultCreateIteratorResultObject(value, done) 로 둔다.
      4. 실행 중인 실행 컨텍스트의 RealmoldRealm 으로 되돌린다.
    3. 그렇지 않으면,
      1. iteratorResultCreateIteratorResultObject(value, done) 로 둔다.
    4. Call(promiseCapability.[[Resolve]], undefined, « iteratorResult ») 를 수행한다.
  8. unused 를 반환한다.

27.6.3.6 AsyncGeneratorResume ( generator, completion )

The abstract operation AsyncGeneratorResume takes arguments generator (an AsyncGenerator) and completion (a Completion Record) and returns unused. It performs the following steps when called:

  1. Assert: generator.[[AsyncGeneratorState]]suspended-start 또는 suspended-yield.
  2. genContextgenerator.[[AsyncGeneratorContext]] 로 둔다.
  3. callerContext 를 실행 중인 실행 컨텍스트로 둔다.
  4. callerContext 를 suspend 한다.
  5. generator.[[AsyncGeneratorState]]executing 으로 설정한다.
  6. genContext 를 실행 컨텍스트 스택에 push; 이제 genContext 가 실행 중인 실행 컨텍스트.
  7. genContext 의 중단된 평가를 재개 하되 그것을 중단시킨 연산의 결과로 completion 을 사용한다. result 를 재개된 계산이 반환한 Completion Record 로 둔다.
  8. Assert: result 는 절대 abrupt completion 이 아니다.
  9. Assert: 여기로 돌아오면 genContext 는 이미 실행 컨텍스트 스택에서 제거되었고 callerContext 가 현재 실행 컨텍스트이다.
  10. unused 를 반환한다.

27.6.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.6.3.8 AsyncGeneratorYield ( value )

The abstract operation AsyncGeneratorYield takes argument value (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. generatorgenContext 의 Generator 컴포넌트 값으로 둔다.
  4. Assert: GetGeneratorKind() 는 async.
  5. completionNormalCompletion(value) 로 둔다.
  6. Assert: 실행 컨텍스트 스택은 최소 두 개의 요소를 가진다.
  7. previousContext 를 실행 컨텍스트 스택의 위에서 두 번째 요소로 둔다.
  8. previousRealmpreviousContextRealm 으로 둔다.
  9. AsyncGeneratorCompleteStep(generator, completion, false, previousRealm) 를 수행한다.
  10. queuegenerator.[[AsyncGeneratorQueue]] 로 둔다.
  11. queue 가 비어 있지 않으면,
    1. 주: 제너레이터를 suspend 하지 않고 실행을 계속한다.
    2. toYieldqueue 의 첫 요소로 둔다.
    3. resumptionValueCompletion(toYield.[[Completion]]) 로 둔다.
    4. AsyncGeneratorUnwrapYieldResumption(resumptionValue) 를 반환한다.
  12. 그렇지 않으면,
    1. generator.[[AsyncGeneratorState]]suspended-yield 로 설정한다.
    2. genContext 를 실행 컨텍스트 스택에서 제거하고 스택 꼭대기 실행 컨텍스트를 실행 중인 컨텍스트로 복원한다.
    3. callerContext 를 실행 중인 실행 컨텍스트로 둔다.
    4. callerContextundefined 를 전달하며 재개한다. genContext 가 다시 재개되면 resumptionValue 를 그 재개에 사용된 Completion Record 로 둔다.
    5. Assert: 여기 도달하면 genContext 가 다시 실행 중인 실행 컨텍스트이다.
    6. AsyncGeneratorUnwrapYieldResumption(resumptionValue) 를 반환한다.

27.6.3.9 AsyncGeneratorAwaitReturn ( generator )

The abstract operation AsyncGeneratorAwaitReturn takes argument generator (an AsyncGenerator) and returns unused. It performs the following steps when called:

  1. Assert: generator.[[AsyncGeneratorState]]draining-queue.
  2. queuegenerator.[[AsyncGeneratorQueue]] 로 둔다.
  3. Assert: queue 는 비어 있지 않다.
  4. nextqueue 의 첫 요소로 둔다.
  5. completionCompletion(next.[[Completion]]) 로 둔다.
  6. Assert: completionreturn completion.
  7. promiseCompletionCompletion(PromiseResolve(%Promise%, completion.[[Value]])) 로 둔다.
  8. promiseCompletionabrupt completion 이면,
    1. AsyncGeneratorCompleteStep(generator, promiseCompletion, true) 를 수행한다.
    2. AsyncGeneratorDrainQueue(generator) 를 수행한다.
    3. unused 를 반환한다.
  9. Assert: promiseCompletionnormal completion.
  10. promisepromiseCompletion.[[Value]] 로 둔다.
  11. fulfilledClosure 를 매개변수 (value) 를 가지고 generator 를 포획하며 호출 시 다음 단계를 수행하는 새로운 Abstract Closure 로 둔다:
    1. Assert: generator.[[AsyncGeneratorState]]draining-queue.
    2. resultNormalCompletion(value) 로 둔다.
    3. AsyncGeneratorCompleteStep(generator, result, true) 를 수행한다.
    4. AsyncGeneratorDrainQueue(generator) 를 수행한다.
    5. NormalCompletion(undefined) 를 반환한다.
  12. onFulfilledCreateBuiltinFunction(fulfilledClosure, 1, "", « ») 로 둔다.
  13. rejectedClosure 를 매개변수 (reason) 를 가지고 generator 를 포획하며 호출 시 다음 단계를 수행하는 새로운 Abstract Closure 로 둔다:
    1. Assert: generator.[[AsyncGeneratorState]]draining-queue.
    2. resultThrowCompletion(reason) 로 둔다.
    3. AsyncGeneratorCompleteStep(generator, result, true) 를 수행한다.
    4. AsyncGeneratorDrainQueue(generator) 를 수행한다.
    5. NormalCompletion(undefined) 를 반환한다.
  14. onRejectedCreateBuiltinFunction(rejectedClosure, 1, "", « ») 로 둔다.
  15. PerformPromiseThen(promise, onFulfilled, onRejected) 를 수행한다.
  16. unused 를 반환한다.

27.6.3.10 AsyncGeneratorDrainQueue ( generator )

The abstract operation AsyncGeneratorDrainQueue takes argument generator (an AsyncGenerator) and returns unused. return completion 을 보유한 AsyncGeneratorRequest 를 만날 때까지 제너레이터의 AsyncGeneratorQueue 를 비운다. It performs the following steps when called:

  1. Assert: generator.[[AsyncGeneratorState]]draining-queue.
  2. queuegenerator.[[AsyncGeneratorQueue]] 로 둔다.
  3. 반복, queue 가 비어 있지 않은 동안,
    1. nextqueue 의 첫 요소로 둔다.
    2. completionCompletion(next.[[Completion]]) 로 둔다.
    3. completionreturn completion 이면,
      1. AsyncGeneratorAwaitReturn(generator) 를 수행한다.
      2. unused 를 반환한다.
    4. 그렇지 않으면,
      1. completionnormal completion 이면
        1. completionNormalCompletion(undefined) 로 설정한다.
      2. AsyncGeneratorCompleteStep(generator, completion, true) 를 수행한다.
  4. generator.[[AsyncGeneratorState]]completed 로 설정한다.
  5. unused 를 반환한다.

27.6.3.11 CreateAsyncIteratorFromClosure ( closure, generatorBrand, generatorPrototype )

The abstract operation CreateAsyncIteratorFromClosure takes arguments closure (an Abstract Closure with no parameters), generatorBrand (a String or empty), and generatorPrototype (an Object) and returns an AsyncGenerator. It performs the following steps when called:

  1. NOTE: closureAwait 연산과 IteratorResult 객체를 산출하기 위한 Yield 연산을 포함할 수 있다.
  2. internalSlotsList 를 « [[AsyncGeneratorState]], [[AsyncGeneratorContext]], [[AsyncGeneratorQueue]], [[GeneratorBrand]] » 로 둔다.
  3. generatorOrdinaryObjectCreate(generatorPrototype, internalSlotsList) 로 둔다.
  4. generator.[[GeneratorBrand]]generatorBrand 로 설정한다.
  5. generator.[[AsyncGeneratorState]]suspended-start 로 설정한다.
  6. callerContext 를 실행 중인 실행 컨텍스트로 둔다.
  7. calleeContext 를 새로운 실행 컨텍스트로 둔다.
  8. calleeContext 의 Function 을 null 로 설정한다.
  9. calleeContextRealm 을 현재 Realm Record 로 설정한다.
  10. calleeContext 의 ScriptOrModule 을 callerContext 의 ScriptOrModule 로 설정한다.
  11. callerContext 가 이미 suspend 상태가 아니면 suspend 한다.
  12. calleeContext 를 실행 컨텍스트 스택에 push; 이제 calleeContext 가 실행 중인 실행 컨텍스트.
  13. AsyncGeneratorStart(generator, closure) 를 수행한다.
  14. calleeContext 를 실행 컨텍스트 스택에서 제거하고 callerContext 를 실행 중인 실행 컨텍스트로 복원한다.
  15. generator 를 반환한다.

27.7 AsyncFunction 객체 (AsyncFunction Objects)

AsyncFunction 들은 보통 AsyncFunctionDeclaration, AsyncFunctionExpression, AsyncMethod, AsyncArrowFunction 을 평가하여 생성되는 함수들이다. 또한 %AsyncFunction% 내재를 호출하여 생성될 수도 있다.

27.7.1 AsyncFunction 생성자 (The AsyncFunction Constructor)

AsyncFunction 생성자는 다음과 같다:

  • %AsyncFunction% 이다.
  • Function 의 서브클래스이다.
  • 생성자가 아니라 함수로 호출될 때 새 AsyncFunction 을 생성하고 초기화한다. 따라서 함수 호출 AsyncFunction(…) 은 동일한 인수의 new AsyncFunction(…) 객체 생성 표현식과 동등하다.
  • 클래스 정의의 extends 절 값으로 사용할 수 있다. 지정된 AsyncFunction 동작을 상속하려는 서브클래스 생성자는 내장 async 함수 동작에 필요한 내부 슬롯을 갖춘 서브클래스 인스턴스를 생성·초기화하기 위해 AsyncFunction 생성자에 대한 super 호출을 포함해야 한다. async 함수 객체를 정의하는 모든 ECMAScript 문법 형태는 AsyncFunction 의 직접 인스턴스를 생성한다. AsyncFunction 서브클래스 인스턴스를 만들 수 있는 문법적 수단은 없다.

27.7.1.1 AsyncFunction ( ...parameterArgs, bodyArg )

마지막 인수(있다면)는 async 함수의 본문(실행 코드)을 지정한다. 그 앞의 인수들은 형식 매개변수를 지정한다.

이 함수는 호출될 때 다음 단계를 수행한다:

  1. C 를 활성 함수 객체로 둔다.
  2. bodyArg 가 존재하지 않으면 bodyArg 를 빈 문자열로 설정한다.
  3. CreateDynamicFunction(C, NewTarget, async, parameterArgs, bodyArg) 를 반환한다.
Note
20.2.1.1 의 NOTE 참조.

27.7.2 AsyncFunction 생성자의 프로퍼티 (Properties of the AsyncFunction Constructor)

AsyncFunction 생성자는 다음과 같다:

  • Function 생성자로부터 상속하는 표준 내장 함수 객체이다.
  • [[Prototype]] 내부 슬롯 값이 %Function% 이다.
  • "length" 프로퍼티 값이 1𝔽 이다.
  • "name" 프로퍼티 값이 "AsyncFunction" 이다.
  • 다음 프로퍼티들을 가진다:

27.7.2.1 AsyncFunction.prototype

AsyncFunction.prototype 의 초기 값은 AsyncFunction 프로토타입 객체이다.

이 프로퍼티는 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false } 특성을 가진다.

27.7.3 AsyncFunction 프로토타입 객체의 프로퍼티 (Properties of the AsyncFunction Prototype Object)

AsyncFunction 프로토타입 객체:

27.7.3.1 AsyncFunction.prototype.constructor

AsyncFunction.prototype.constructor 의 초기 값은 %AsyncFunction% 이다.

이 프로퍼티는 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true } 특성을 가진다.

27.7.3.2 AsyncFunction.prototype [ %Symbol.toStringTag% ]

%Symbol.toStringTag% 프로퍼티의 초기 값은 문자열 "AsyncFunction" 이다.

이 프로퍼티는 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true } 특성을 가진다.

27.7.4 AsyncFunction 인스턴스 (AsyncFunction Instances)

모든 AsyncFunction 인스턴스는 ECMAScript 함수 객체이며 Table 28 에 열거된 내부 슬롯을 가진다. 그러한 모든 인스턴스의 [[IsClassConstructor]] 내부 슬롯 값은 false 이다. AsyncFunction 인스턴스는 생성자가 아니며 [[Construct]] 내부 메서드를 갖지 않는다. AsyncFunction 인스턴스는 생성 불가능하므로 prototype 프로퍼티를 갖지 않는다.

각 AsyncFunction 인스턴스는 다음 자체 프로퍼티를 가진다:

27.7.4.1 length

20.2.4.1 에 기술된 Function 인스턴스 "length" 프로퍼티 명세는 AsyncFunction 인스턴스에도 적용된다.

27.7.4.2 name

20.2.4.2 에 기술된 Function 인스턴스 "name" 프로퍼티 명세는 AsyncFunction 인스턴스에도 적용된다.

27.7.5 Async 함수 추상 연산 (Async Functions Abstract Operations)

27.7.5.1 AsyncFunctionStart ( promiseCapability, asyncFunctionBody )

The abstract operation AsyncFunctionStart takes arguments promiseCapability (a PromiseCapability Record) and asyncFunctionBody (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. runningContext 를 실행 중인 실행 컨텍스트로 둔다.
  2. asyncContextrunningContext 의 복사본으로 둔다.
  3. NOTE: 실행 상태 복사는 AsyncBlockStart 가 그 실행을 재개하기 위해 필요하다. 현재 실행 중인 컨텍스트를 재개하는 것은 잘 정의되지 않는다.
  4. AsyncBlockStart(promiseCapability, asyncFunctionBody, asyncContext) 를 수행한다.
  5. unused 를 반환한다.

27.7.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. runningContext 를 실행 중인 실행 컨텍스트로 둔다.
  2. closure 를 매개변수 없고 promiseCapability, asyncBody 를 포획하며 호출 시 다음 단계를 수행하는 새로운 Abstract Closure 로 둔다:
    1. acAsyncContext 를 실행 중인 실행 컨텍스트로 둔다.
    2. asyncBody 가 Parse Node 이면
      1. resultCompletion(Evaluation of asyncBody) 로 둔다.
    3. 그렇지 않으면
      1. Assert: asyncBody 는 매개변수 없는 Abstract Closure.
      2. resultCompletion(asyncBody()) 로 둔다.
    4. Assert: 여기로 돌아오면 async 함수는 예외를 던졌거나 암시적 또는 명시적 return 을 수행했고 모든 await 가 완료되었다.
    5. acAsyncContext 를 실행 컨텍스트 스택에서 제거하고 스택 꼭대기 실행 컨텍스트를 실행 중인 컨텍스트로 복원한다.
    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) 를 반환한다.
  3. asyncContext 의 코드 평가 상태를 설정하여 그 실행 컨텍스트가 재개될 때 closure 가 인수 없이 호출되도록 한다.
  4. asyncContext 를 실행 컨텍스트 스택에 push; 이제 asyncContext 가 실행 중인 실행 컨텍스트.
  5. asyncContext 의 중단된 평가를 재개 한다. result 를 재개된 계산이 반환한 값으로 둔다.
  6. Assert: 여기로 돌아오면 asyncContext 는 이미 실행 컨텍스트 스택에서 제거되었고 runningContext 가 현재 실행 컨텍스트이다.
  7. Assert: result 는 값이 unusednormal completion. 이 값의 가능한 출처는 Await 이거나, async 함수가 어떤 것도 await 하지 않는 경우 위 2.i 단계이다.
  8. unused 를 반환한다.

27.7.5.3 Await ( value )

The abstract operation Await takes argument value (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%, value) 로 둔다.
  3. fulfilledClosure 를 매개변수 (v) 를 가지고 asyncContext 를 포획하며 호출 시 다음 단계를 수행하는 새로운 Abstract Closure 로 둔다:
    1. prevContext 를 실행 중인 실행 컨텍스트로 둔다.
    2. prevContext 를 suspend 한다.
    3. asyncContext 를 실행 컨텍스트 스택에 push; 이제 asyncContext 가 실행 중인 실행 컨텍스트.
    4. asyncContext 의 중단된 평가를 재개 하되 그것을 중단시킨 연산의 결과로 NormalCompletion(v) 를 사용한다.
    5. Assert: 이 단계에 도달하면 asyncContext 는 이미 실행 컨텍스트 스택에서 제거되었고 prevContext 가 현재 실행 컨텍스트이다.
    6. NormalCompletion(undefined) 를 반환한다.
  4. onFulfilledCreateBuiltinFunction(fulfilledClosure, 1, "", « ») 로 둔다.
  5. rejectedClosure 를 매개변수 (reason) 를 가지고 asyncContext 를 포획하며 호출 시 다음 단계를 수행하는 새로운 Abstract Closure 로 둔다:
    1. prevContext 를 실행 중인 실행 컨텍스트로 둔다.
    2. prevContext 를 suspend 한다.
    3. asyncContext 를 실행 컨텍스트 스택에 push; 이제 asyncContext 가 실행 중인 실행 컨텍스트.
    4. asyncContext 의 중단된 평가를 재개 하되 그것을 중단시킨 연산의 결과로 ThrowCompletion(reason) 를 사용한다.
    5. Assert: 이 단계에 도달하면 asyncContext 는 이미 실행 컨텍스트 스택에서 제거되었고 prevContext 가 현재 실행 컨텍스트이다.
    6. NormalCompletion(undefined) 를 반환한다.
  6. onRejectedCreateBuiltinFunction(rejectedClosure, 1, "", « ») 로 둔다.
  7. PerformPromiseThen(promise, onFulfilled, onRejected) 를 수행한다.
  8. asyncContext 를 실행 컨텍스트 스택에서 제거하고 스택 꼭대기 실행 컨텍스트를 실행 중인 컨텍스트로 복원한다.
  9. callerContext 를 실행 중인 실행 컨텍스트로 둔다.
  10. callerContextempty 를 전달하며 재개한다. asyncContext 가 다시 재개되면 completion 을 그 재개에 사용된 Completion Record 로 둔다.
  11. Assert: 여기 도달하면 asyncContext 가 다시 실행 중인 실행 컨텍스트이다.
  12. completion 을 반환한다.

28 반사 (Reflection)

28.1 Reflect 객체 (The Reflect Object)

Reflect 객체:

  • %Reflect%이다.
  • 전역 객체"Reflect" 프로퍼티 초기 값이다.
  • 일반 객체이다.
  • [[Prototype]] 내부 슬롯 값이 %Object.prototype%이다.
  • 함수 객체가 아니다.
  • [[Construct]] 내부 메서드가 없다; new 연산자로 생성자로 사용할 수 없다.
  • [[Call]] 내부 메서드가 없다; 함수로 호출될 수 없다.

28.1.1 Reflect.apply ( target, thisArgument, argumentsList )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. IsCallable(target) 이 false이면 TypeError 예외를 던진다.
  2. args 를 ? CreateListFromArrayLike(argumentsList)로 둔다.
  3. PrepareForTailCall()을 수행한다.
  4. Call(target, thisArgument, args)를 반환한다.

28.1.2 Reflect.construct ( target, argumentsList [ , newTarget ] )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. IsConstructor(target) 가 false이면 TypeError 예외를 던진다.
  2. newTarget 이 존재하지 않으면 newTargettarget 으로 설정한다.
  3. 아니고 IsConstructor(newTarget) 이 false이면 TypeError 예외를 던진다.
  4. args 를 ? CreateListFromArrayLike(argumentsList)로 둔다.
  5. Construct(target, args, newTarget) 를 반환한다.

28.1.3 Reflect.defineProperty ( target, propertyKey, attributes )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. target 이 Object 가 아니면 TypeError 예외를 던진다.
  2. key 를 ? ToPropertyKey(propertyKey) 로 둔다.
  3. desc 를 ? ToPropertyDescriptor(attributes) 로 둔다.
  4. target.[[DefineOwnProperty]](key, desc) 를 반환한다.

28.1.4 Reflect.deleteProperty ( target, propertyKey )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. target 이 Object 가 아니면 TypeError 예외를 던진다.
  2. key 를 ? ToPropertyKey(propertyKey) 로 둔다.
  3. target.[[Delete]](key) 를 반환한다.

28.1.5 Reflect.get ( target, propertyKey [ , receiver ] )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. target 이 Object 가 아니면 TypeError 예외를 던진다.
  2. key 를 ? ToPropertyKey(propertyKey) 로 둔다.
  3. receiver 가 존재하지 않으면
    1. receivertarget 으로 설정한다.
  4. target.[[Get]](key, receiver) 를 반환한다.

28.1.6 Reflect.getOwnPropertyDescriptor ( target, propertyKey )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. target 이 Object 가 아니면 TypeError 예외를 던진다.
  2. key 를 ? ToPropertyKey(propertyKey) 로 둔다.
  3. desc 를 ? target.[[GetOwnProperty]](key) 로 둔다.
  4. FromPropertyDescriptor(desc) 를 반환한다.

28.1.7 Reflect.getPrototypeOf ( target )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. target 이 Object 가 아니면 TypeError 예외를 던진다.
  2. target.[[GetPrototypeOf]]() 를 반환한다.

28.1.8 Reflect.has ( target, propertyKey )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. target 이 Object 가 아니면 TypeError 예외를 던진다.
  2. key 를 ? ToPropertyKey(propertyKey) 로 둔다.
  3. target.[[HasProperty]](key) 를 반환한다.

28.1.9 Reflect.isExtensible ( target )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. target 이 Object 가 아니면 TypeError 예외를 던진다.
  2. target.[[IsExtensible]]() 를 반환한다.

28.1.10 Reflect.ownKeys ( target )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. target 이 Object 가 아니면 TypeError 예외를 던진다.
  2. keys 를 ? target.[[OwnPropertyKeys]]() 로 둔다.
  3. CreateArrayFromList(keys) 를 반환한다.

28.1.11 Reflect.preventExtensions ( target )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. target 이 Object 가 아니면 TypeError 예외를 던진다.
  2. target.[[PreventExtensions]]() 를 반환한다.

28.1.12 Reflect.set ( target, propertyKey, V [ , receiver ] )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. target 이 Object 가 아니면 TypeError 예외를 던진다.
  2. key 를 ? ToPropertyKey(propertyKey) 로 둔다.
  3. receiver 가 존재하지 않으면
    1. receivertarget 으로 설정한다.
  4. target.[[Set]](key, V, receiver) 를 반환한다.

28.1.13 Reflect.setPrototypeOf ( target, proto )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. target 이 Object 가 아니면 TypeError 예외를 던진다.
  2. proto 가 Object 가 아니고 null 도 아니면 TypeError 예외를 던진다.
  3. target.[[SetPrototypeOf]](proto) 를 반환한다.

28.1.14 Reflect [ %Symbol.toStringTag% ]

%Symbol.toStringTag% 프로퍼티 초기 값은 문자열 "Reflect" 이다.

이 프로퍼티의 특성은 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }이다.

28.2 Proxy 객체 (Proxy Objects)

28.2.1 Proxy 생성자 (The Proxy Constructor)

Proxy 생성자:

  • %Proxy%이다.
  • 전역 객체"Proxy" 프로퍼티 초기 값이다.
  • 생성자로 호출될 때 새 Proxy 객체를 생성·초기화한다.
  • 함수로 호출하도록 의도되지 않았으며 그렇게 호출하면 예외를 던진다.

28.2.1.1 Proxy ( target, handler )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. NewTarget 이 undefined 이면 TypeError 예외를 던진다.
  2. ProxyCreate(target, handler) 를 반환한다.

28.2.2 Proxy 생성자의 프로퍼티 (Properties of the Proxy Constructor)

Proxy 생성자:

  • [[Prototype]] 내부 슬롯 값이 %Function.prototype%이다.
  • "prototype" 프로퍼티가 없다 (Proxy 객체는 초기화가 필요한 [[Prototype]] 내부 슬롯을 갖지 않는다).
  • 다음 프로퍼티들을 가진다:

28.2.2.1 Proxy.revocable ( target, handler )

이 함수는 취소(revocable) 가능한 Proxy 객체를 생성한다.

호출 시 다음 단계를 수행한다:

  1. proxy 를 ? ProxyCreate(target, handler) 로 둔다.
  2. revokerClosure 를 아무 것도 포획하지 않고 매개변수 없는 새로운 Abstract Closure 로 두어 호출 시 다음 단계를 수행하게 한다:
    1. F 를 활성 함수 객체로 둔다.
    2. pF.[[RevocableProxy]] 로 둔다.
    3. pnull 이면 NormalCompletion(undefined) 를 반환한다.
    4. F.[[RevocableProxy]]null 로 설정한다.
    5. Assert: p 는 Proxy 특이(exotic) 객체이다.
    6. p.[[ProxyTarget]]null 로 설정한다.
    7. p.[[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 Objects)

모듈 네임스페이스 객체는 모듈의 내보낸 바인딩에 속성 기반 런타임 접근을 제공하는 모듈 네임스페이스 특이 객체이다. 이를 위한 생성자 함수는 없다. 대신 NameSpaceImport 를 포함하는 ImportDeclaration 으로 가져온 각 모듈마다 이러한 객체가 생성된다.

10.4.6 에 명시된 프로퍼티 외에 각 모듈 네임스페이스 객체는 다음 자체 프로퍼티를 가진다:

28.3.1 %Symbol.toStringTag%

%Symbol.toStringTag% 프로퍼티 초기 값은 문자열 "Module" 이다.

이 프로퍼티 특성은 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }이다.

29 메모리 모델 (Memory Model)

메모리 일관성 모델 또는 memory model 은 SharedArrayBuffer 로 백업된 TypedArray 인스턴스 접근과 Atomics 객체의 메서드를 통해 발생하는 Shared Data Block 이벤트의 가능한 순서를 지정한다. 프로그램에 (아래 정의된) 데이터 레이스가 없을 때 이벤트들의 순서는 각 에이전트의 동작을 인터리빙한 것과 같이 순차적 일관성(sequentially consistent)으로 보인다. 프로그램에 데이터 레이스가 있을 때 공유 메모리 연산은 순차적 비일관성처럼 보일 수 있다. 예를 들어, 프로그램은 인과성 위반 동작 및 그 밖의 놀라운 현상을 보일 수 있다. 이러한 놀라움은 컴파일러 변환과 CPU 설계(예: 순서 재배치 실행 및 추측 실행)에서 비롯된다. 메모리 모델은 프로그램이 순차적 일관성 동작을 보이는 정확한 조건과 데이터 레이스에서 읽힐 수 있는 가능한 값들을 모두 정의한다. 즉, 정의되지 않은 동작은 없다.

메모리 모델은 SharedArrayBuffer 의 추상 연산 또는 평가 중 Atomics 객체 메서드에 의해 도입된 이벤트에 대한 관계 제약으로 정의된다.

Note

이 절은 SharedArrayBuffer 추상 연산이 도입하는 이벤트에 대한 공리적(axiomatic) 모델을 제공한다. 모델은 명세의 나머지와 달리 알고리즘적으로 표현될 수 없음을 강조해야 한다. 추상 연산에 의한 비결정적 이벤트 도입은 ECMAScript 평가의 실행 의미와 메모리 모델의 공리적 의미 사이의 인터페이스이다. 이러한 이벤트의 의미는 평가 내 모든 이벤트의 그래프를 고려하여 정의된다. 이것들은 정적 의미(Static Semantics)나 런타임 의미(Runtime Semantics)가 아니다. 입증된 알고리즘 구현이 아니라 특정 이벤트 그래프가 허용되는지 금지되는지를 결정하는 제약 집합이다.

29.1 메모리 모델 기초 (Memory Model Fundamentals)

공유 메모리 접근(읽기/쓰기)은 아래에서 정의되는 두 그룹, atomic 접근과 data 접근으로 나뉜다. Atomic 접근은 순차적 일관성을 가지며, 즉 에이전트 클러스터의 모든 에이전트가 동의하는 엄격한 전체 순서가 있다. 비-atomic 접근은 모든 에이전트가 동의하는 엄격한 전체 순서가 없으므로 정렬되지(unordered) 않는다.

Note 1

순차적 일관성과 unordered 보다 약하거나 강한(예: release-acquire) 순서는 지원되지 않는다.

Shared Data Block eventReadSharedMemory, WriteSharedMemory 또는 ReadModifyWriteSharedMemory Record 이다.

Table 94: ReadSharedMemory 이벤트 필드 (ReadSharedMemory Event Fields)
Field Name Value Meaning
[[Order]] seq-cst 또는 unordered 이벤트에 대해 메모리 모델이 보장하는 가장 약한 순서.
[[NoTear]] Boolean 이 이벤트가 동일 범위를 가진 여러 write 이벤트로부터 읽을 수 있는지 여부.
[[Block]] Shared Data Block 이벤트가 동작하는 블록.
[[ByteIndex]] 음이 아닌 정수 [[Block]] 내 읽기의 바이트 주소.
[[ElementSize]] 음이 아닌 정수 읽기의 크기.
Table 95: WriteSharedMemory 이벤트 필드 (WriteSharedMemory Event Fields)
Field Name Value Meaning
[[Order]] seq-cst, unordered, 또는 init 이벤트에 대해 메모리 모델이 보장하는 가장 약한 순서.
[[NoTear]] Boolean 이 이벤트가 동일 범위를 가진 여러 read 이벤트로부터 읽힐 수 있는지 여부.
[[Block]] Shared Data Block 이벤트가 동작하는 블록.
[[ByteIndex]] 음이 아닌 정수 [[Block]] 내 쓰기의 바이트 주소.
[[ElementSize]] 음이 아닌 정수 쓰기의 크기.
[[Payload]] 바이트 값 List 다른 이벤트가 읽을 바이트 값 List.
Table 96: ReadModifyWriteSharedMemory 이벤트 필드 (ReadModifyWriteSharedMemory Event Fields)
Field Name Value Meaning
[[Order]] seq-cst Read-modify-write 이벤트는 항상 순차적 일관성.
[[NoTear]] true Read-modify-write 이벤트는 tear 될 수 없다.
[[Block]] Shared Data Block 이벤트가 동작하는 블록.
[[ByteIndex]] 음이 아닌 정수 [[Block]] 내 read-modify-write 의 바이트 주소.
[[ElementSize]] 음이 아닌 정수 read-modify-write 의 크기.
[[Payload]] 바이트 값 List [[ModifyOp]] 에 전달될 바이트 값 List.
[[ModifyOp]] read-modify-write 수정 함수 읽은 바이트 List[[Payload]] 로부터 수정된 바이트 List 를 반환하는 추상 클로저.

이러한 이벤트는 추상 연산 또는 Atomics 객체 메서드에 의해 도입된다.

일부 연산은 Synchronize 이벤트도 도입할 수 있다. Synchronize event 는 필드가 없으며, 다른 이벤트의 허용 순서를 직접 제한하기 위해 존재한다.

Shared Data Block 및 Synchronize 이벤트 외에 호스트 특화 이벤트가 있다.

ReadSharedMemory, WriteSharedMemory, ReadModifyWriteSharedMemory 이벤트의 범위(range)는 [[ByteIndex]] 부터 [[ByteIndex]] + [[ElementSize]] - 1 까지의 연속 정수 집합이다. 두 이벤트의 [[Block]] 이 같고 범위가 원소별 동일하면 범위가 같다. [[Block]] 이 같고 범위가 동일하지 않으며 교집합이 비어 있지 않으면 범위가 겹친다(overlapping). [[Block]] 이 다르거나 범위가 같지도 겹치지도 않으면 범위는 분리(disjoint)되었다.

Note 2

계정해야 할 호스트 특화 동기화 이벤트 예: 한 에이전트에서 다른 에이전트로 SharedArrayBuffer 를 보내기(브라우저의 postMessage), 에이전트 시작/종료, 공유 메모리 외 채널을 통한 에이전트 클러스터 내 통신. 특정 실행 execution 에 대해 이러한 이벤트는 host-synchronizes-with 엄격 부분 순서로 호스트에 의해 제공된다. 추가로, 호스트execution.[[EventList]]호스트 특화 동기화 이벤트를 추가하여 is-agent-order-before 관계에 참여할 수 있다.

이벤트는 아래에 정의된 관계에 의해 후보 실행 내에서 순서화된다.

29.2 에이전트 이벤트 레코드 (Agent Events Records)

Agent Events Record 는 다음 필드를 가진 Record 이다.

Table 97: Agent Events Record 필드 (Agent Events Record Fields)
Field Name Value Meaning
[[AgentSignifier]] 에이전트 식별자 이 순서를 발생시킨 평가의 에이전트.
[[EventList]] 이벤트 List 평가 중 리스트에 이벤트가 추가된다.
[[AgentSynchronizesWith]] Synchronize 이벤트 쌍 List 운영상 의미가 도입한 동기화 관계.

29.3 Chosen Value 레코드 (Chosen Value Records)

Chosen Value Record 는 다음 필드를 가진 Record 이다.

Table 98: Chosen Value Record 필드 (Chosen Value Record Fields)
Field Name Value Meaning
[[Event]] Shared Data Block event 이 선택 값에 대해 도입된 ReadSharedMemory 또는 ReadModifyWriteSharedMemory 이벤트.
[[ChosenValue]] 바이트 값 List 평가 동안 비결정적으로 선택된 바이트.

29.4 후보 실행 (Candidate Executions)

candidate execution 은 에이전트 클러스터 평가의 다음 필드를 가진 Record 이다.

Table 99: Candidate Execution Record 필드 (Candidate Execution Record Fields)
Field Name Value Meaning
[[EventsRecords]] Agent Events Records List 평가 중 추가된 이벤트 List 를 에이전트에 매핑.
[[ChosenValues]] Chosen Value Records List 평가 중 선택된 바이트 값 ListReadSharedMemory 또는 ReadModifyWriteSharedMemory 이벤트에 매핑.

empty candidate execution 은 필드가 빈 List 인 candidate execution Record 이다.

29.5 메모리 모델을 위한 추상 연산 (Abstract Operations for the Memory Model)

29.5.1 EventSet ( execution )

The abstract operation EventSet takes argument execution (a candidate execution) and returns a Set of events. It performs the following steps when called:

  1. events 를 빈 Set 으로 둔다.
  2. execution.[[EventsRecords]] 의 각 Agent Events Record aer 에 대해,
    1. aer.[[EventList]] 의 각 이벤트 E 에 대해
      1. Eevents 에 추가한다.
  3. events 를 반환한다.

29.5.2 SharedDataBlockEventSet ( execution )

The abstract operation SharedDataBlockEventSet takes argument execution (a candidate execution) and returns a Set of events. It performs the following steps when called:

  1. events 를 빈 Set 으로 둔다.
  2. EventSet(execution) 의 각 이벤트 E 에 대해
    1. EReadSharedMemory, WriteSharedMemory, ReadModifyWriteSharedMemory 이벤트이면 Eevents 에 추가한다.
  3. events 를 반환한다.

29.5.3 HostEventSet ( execution )

The abstract operation HostEventSet takes argument execution (a candidate execution) and returns a Set of events. It performs the following steps when called:

  1. events 를 빈 Set 으로 둔다.
  2. EventSet(execution) 의 각 이벤트 E 에 대해
    1. ESharedDataBlockEventSet(execution) 에 없으면 Eevents 에 추가한다.
  3. events 를 반환한다.

29.5.4 ComposeWriteEventBytes ( execution, byteIndex, Ws )

The abstract operation ComposeWriteEventBytes takes arguments execution (a candidate execution), byteIndex (a non-negative integer), and Ws (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 를 새 빈 List 로 둔다.
  3. Ws 의 각 요소 W 에 대해
    1. Assert: W 는 자신의 범위에 byteLocation 을 포함한다.
    2. payloadIndexbyteLocation - W.[[ByteIndex]] 로 둔다.
    3. WWriteSharedMemory 이벤트이면
      1. byteW.[[Payload]][payloadIndex] 로 둔다.
    4. 아니면
      1. Assert: WReadModifyWriteSharedMemory 이벤트.
      2. bytesValueOfReadEvent(execution, W) 로 둔다.
      3. bytesModifiedW.[[ModifyOp]](bytes, W.[[Payload]]) 로 둔다.
      4. bytebytesModified[payloadIndex] 로 둔다.
    5. bytebytesRead 끝에 추가한다.
    6. byteLocationbyteLocation + 1 로 설정한다.
  4. bytesRead 를 반환한다.
Note 1

read-modify-write 수정 [[ModifyOp]]ReadModifyWriteSharedMemory 이벤트를 도입하는 Atomics 객체의 함수 프로퍼티로 제공된다.

Note 2

이 추상 연산은 write 이벤트 List 를 바이트 값 List 로 합성한다. 이는 ReadSharedMemoryReadModifyWriteSharedMemory 이벤트의 이벤트 의미에서 사용된다.

29.5.5 ValueOfReadEvent ( execution, R )

The abstract operation ValueOfReadEvent takes arguments execution (a candidate execution) and R (a ReadSharedMemory or ReadModifyWriteSharedMemory event) and returns a List of byte values. It performs the following steps when called:

  1. Wsexecution 에서 reads-bytes-from(R) 로 둔다.
  2. Assert: Ws 는 길이가 R.[[ElementSize]] 와 같은 WriteSharedMemory 또는 ReadModifyWriteSharedMemory 이벤트 List 이다.
  3. ComposeWriteEventBytes(execution, R.[[ByteIndex]], Ws) 를 반환한다.

29.6 후보 실행의 관계 (Relations of Candidate Executions)

다음 관계와 수학적 함수는 특정 후보 실행 위에서 매개변수화되며 그 이벤트들을 순서화한다.

29.6.1 is-agent-order-before

후보 실행 execution 에 대해, 그 is-agent-order-before 관계는 다음을 만족하는 최소 관계이다.

  • 이벤트 E, D 에 대해 execution.[[EventsRecords]] 의 어떤 Agent Events Record aer 가 있어 aer.[[EventList]]ED 둘 다 포함되고 EList 순서에서 D 앞에 있으면 E is-agent-order-before D 이다.
Note

각 에이전트는 평가 중 per-agent 엄격 전체 순서로 이벤트를 도입한다. 이것은 그 엄격 전체 순서들의 합집합이다.

29.6.2 reads-bytes-from

후보 실행 execution 에 대해, 그 reads-bytes-from 함수는 SharedDataBlockEventSet(execution) 의 이벤트를 SharedDataBlockEventSet(execution) 내 이벤트 List 로 매핑하는 수학적 함수이며 다음 조건을 만족한다.

후보 실행은 항상 reads-bytes-from 함수를 허용한다.

29.6.3 reads-from

후보 실행 execution 에 대해, 그 reads-from 관계는 다음을 만족하는 최소 관계이다.

29.6.4 host-synchronizes-with

후보 실행 execution 에 대해, 그 host-synchronizes-with 관계는 적어도 다음을 만족하는 호스트 제공 엄격 부분 순서이다.

  • E host-synchronizes-with D 이면 HostEventSet(execution) 이 ED 를 포함한다.
  • host-synchronizes-with 와 is-agent-order-before 의 합집합은 순환이 없다.
Note 1

호스트 특화 이벤트 E, D 에 대해 E host-synchronizes-with D 이면 E happens-before D 이다.

Note 2

이 관계는 HTML 워커 간 postMessage 같은 추가 동기화 메커니즘을 호스트가 제공할 수 있게 한다.

29.6.5 synchronizes-with

후보 실행 execution 에 대해, 그 synchronizes-with 관계는 다음을 만족하는 최소 관계이다.

  • 이벤트 R, W 에 대해 R reads-from W, R.[[Order]]seq-cst, W.[[Order]]seq-cst, 그리고 R, W 범위가 같으면 W synchronizes-with R.
  • execution.[[EventsRecords]] 의 각 eventsRecord 에 대해:
    • eventsRecord.[[AgentSynchronizesWith]] 가 (S, Sw) 를 포함하면 S synchronizes-with Sw.
  • execution.[[HostSynchronizesWith]] 가 (E, D) 를 포함하면 E synchronizes-with D.
Note 1

문헌 관례상 write 이벤트가 read 이벤트와 synchronizes-with 관계를 가진다.

Note 2

init 이벤트는 이 관계에 참여하지 않고 happens-before 에 의해 직접 제약된다.

Note 3

reads-from 로 연결된 모든 seq-cst 이벤트가 synchronizes-with 로 연결되지는 않는다. 범위가 같은 경우에만 그렇다.

Note 4

W synchronizes-with R 라도 RW 이외의 write 로부터 reads-from 할 수 있다.

29.6.6 happens-before

후보 실행 execution 에 대해, 그 happens-before 관계는 다음을 만족하는 최소 관계이다.

  • 이벤트 E, D 에 대해 다음 중 하나가 참이면 E happens-before D:

Note

happens-before 는 agent-order 의 상위 집합이므로 후보 실행은 단일 스레드 평가 의미와 합치된다.

29.7 유효한 실행의 속성 (Properties of Valid Executions)

29.7.1 Valid Chosen Reads

후보 실행 execution 이 아래 알고리즘이 true 를 반환하면 valid chosen reads 를 가진다.

  1. SharedDataBlockEventSet(execution) 의 각 ReadSharedMemory 또는 ReadModifyWriteSharedMemory 이벤트 R 에 대해
    1. chosenValueRecordexecution.[[ChosenValues]][[Event]]R 인 요소로 둔다.
    2. chosenValuechosenValueRecord.[[ChosenValue]] 로 둔다.
    3. readValueValueOfReadEvent(execution, R) 로 둔다.
    4. chosenLenchosenValue 의 원소 수로 둔다.
    5. readLenreadValue 의 원소 수로 둔다.
    6. chosenLenreadLen 이면
      1. false 반환.
    7. 0 이상 chosenLen 미만 정수 i 중 일부에 대해 chosenValue[i] ≠ readValue[i] 이면
      1. false 반환.
  2. true 반환.

29.7.2 Coherent Reads

후보 실행 execution 이 아래 알고리즘이 true 면 coherent reads 를 가진다.

  1. SharedDataBlockEventSet(execution) 의 각 ReadSharedMemory 또는 ReadModifyWriteSharedMemory 이벤트 R 에 대해
    1. Wsreads-bytes-from(R) 로 둔다.
    2. byteLocationR.[[ByteIndex]] 로 둔다.
    3. Ws 의 각 요소 W 에 대해
      1. R happens-before W 이면 false 반환.
      2. byteLocation 을 범위에 가지는 WriteSharedMemory 또는 ReadModifyWriteSharedMemory 이벤트 V 가 존재하고 W happens-before VV happens-before R 이면 false 반환.
      3. byteLocationbyteLocation + 1 로 설정.
  2. true 반환.

29.7.3 Tear Free Reads

후보 실행 execution 이 아래 알고리즘이 true 면 tear free reads 를 가진다.

  1. SharedDataBlockEventSet(execution) 의 각 ReadSharedMemory 또는 ReadModifyWriteSharedMemory 이벤트 R 에 대해
    1. R.[[NoTear]]true 이면
      1. R.[[ByteIndex]] % R.[[ElementSize]] == 0 임을 단언.
      2. R reads-from W 이고 W.[[NoTear]]true 인 각 이벤트 W 에 대해
        1. R, W 범위가 같고 이벤트 V 가 존재하여 V, W 범위가 같고 V.[[NoTear]] true 이며 WV, 그리고 R reads-from V 이면 false 반환.
  2. true 반환.
Note

이벤트의 [[NoTear]]true 는 해당 이벤트가 정수 TypedArray 접근으로 도입되었을 때이고, 부동소수 TypedArray 또는 DataView 접근이면 false 이다.

직관적으로 이는 정렬된(integer TypedArray) 방식으로 메모리 범위를 접근할 때 동일 범위를 가진 여러 write 이벤트와 경쟁 중 한 write 이벤트가 “승리”해야 함을 의미한다. 보다 정확히, 정렬된 read 이벤트는 같은 범위를 가진 서로 다른 여러 write 이벤트들의 바이트를 혼합해 읽을 수 없다. 다만 겹치는 범위를 가진 여러 write 이벤트로부터 읽는 것은 가능하다.

29.7.4 순차적 일관 Atomics (Sequentially Consistent Atomics)

후보 실행 execution 에 대해 is-memory-order-beforeEventSet(execution) 의 모든 이벤트에 대한 엄격 전체 순서이며 다음을 만족한다.

후보 실행이 is-memory-order-before 관계를 허용하면 sequentially consistent atomics 를 가진다.

Note 3

is-memory-order-before 는 EventSet(execution) 의 모든 이벤트를 포함하지만 happens-beforesynchronizes-with 로 제약되지 않은 이벤트는 순서에서 어디든 위치할 수 있다.

29.7.5 유효한 실행 (Valid Executions)

후보 실행 execution 이 아래 모두 참이면 유효 실행(또는 실행)이다.

  • 호스트execution 에 대한 host-synchronizes-with 관계를 제공.
  • execution 이 엄격 부분 순서인 happens-before 관계를 허용.
  • execution 은 valid chosen reads.
  • execution 은 coherent reads.
  • execution 은 tear free reads.
  • execution 은 sequentially consistent atomics.

모든 프로그램은 적어도 하나의 유효 실행을 가진다.

29.8 경쟁 (Races)

실행 executionSharedDataBlockEventSet(execution) 에 포함된 이벤트 E, D 에 대해 아래 알고리즘이 true 를 반환하면 E, Drace 관계이다.

  1. E, D 가 동일 Shared Data Block 이벤트가 아니면
    1. E happens-before DD happens-before E 둘 다가 아닌 경우
      1. E, D 가 모두 WriteSharedMemory 또는 ReadModifyWriteSharedMemory 이벤트이고 범위가 분리되지 않으면
        1. true 반환.
      2. E reads-from D 또는 D reads-from E 이면
        1. true 반환.
  2. false 반환.

29.9 데이터 레이스 (Data Races)

실행 executionSharedDataBlockEventSet(execution) 에 포함된 이벤트 E, D 에 대해 아래 알고리즘이 true 이면 E, Ddata race 관계이다.

  1. E, Drace 이면
    1. E.[[Order]]seq-cst 가 아니거나 D.[[Order]]seq-cst 가 아니면
      1. true 반환.
    2. E, D 범위가 겹치면
      1. true 반환.
  2. false 반환.

29.10 데이터 레이스 자유 (Data Race Freedom)

실행 executionSharedDataBlockEventSet(execution) 내 어떤 두 이벤트도 data race 가 아니면 data race free 이다.

모든 실행이 data race free 이면 프로그램은 data race free 이다.

메모리 모델은 data race free 프로그램에 대해 모든 이벤트의 순차적 일관성을 보장한다.

29.11 공유 메모리 가이드라인 (Shared Memory Guidelines)

Note 1

다음은 공유 메모리를 사용하는 ECMAScript 프로그래머를 위한 지침이다.

프로그램을 data race free 로 유지(즉 동일 메모리 위치에서 동시 비-atomic 연산이 불가능하도록)할 것을 권장한다. Data race free 프로그램은 각 에이전트 평가 의미 단계가 서로 인터리빙되는 의미를 갖는다. 이런 경우 메모리 모델 세부사항을 이해할 필요가 없다.

더 일반적으로, 프로그램이 data race free 가 아니어도 atomic 연산이 어떤 data race 에도 관여하지 않고 경쟁하는 연산이 모두 동일 접근 크기라면 예측 가능한 동작을 가질 수 있다. 가장 단순한 방법은 atomic 과 비-atomic 연산이 다른 메모리 셀을 사용하고 서로 다른 크기의 atomic 접근이 동시에 같은 셀을 접근하지 않게 하는 것이다. 즉 가능한 한 공유 메모리를 강한 타입처럼 다루어야 한다. 경쟁 중 비-atomic 접근의 순서와 타이밍에 의존할 수는 없지만 강한 타입처럼 다루면 값이 “찢어지는(tear)” 일은 없다.

Note 2

다음은 공유 메모리를 사용하는 프로그램에 대한 컴파일러 변환을 작성하는 ECMAScript 구현자를 위한 지침이다.

단일 에이전트 환경에서 유효한 대부분의 프로그램 변환이 다중 에이전트 환경에서도 유효하도록 허용하는 것이 바람직하다. 종종 이러한 변환은 판단이 어렵다. 우리는 메모리 모델이 함축하거나 그보다 강한 규칙 몇 가지를 개략적으로 제시한다.

agent-order slice 를 단일 에이전트에 속하는 is-agent-order-before 부분집합이라 하자.

read 이벤트의 possible read values 는 모든 유효 실행에서 그 이벤트에 대한 ValueOfReadEvent 값들의 집합이다.

공유 메모리가 없을 때 유효한 agent-order slice 변환은 아래 예외를 제외하고 공유 메모리 존재 시에도 유효하다.

  • Atomics 는 고정: 변환은 agent-order slice 의 seq-cst 이벤트를 그 unordered 연산과 재배열하거나 서로 재배열하거나 제거해서는 안 된다.

    (실제로 재배열 금지는 seq-cst 연산이 동기화임을 가정하게 강제한다.)

  • 읽기는 안정적: 주어진 shared memory read 는 한 실행에서 단일 값만 관찰해야 한다.

  • 쓰기는 안정적: 관찰 가능한 모든 shared memory write 는 실행의 프로그램 의미에서 비롯해야 한다.

  • 가능한 읽기 값은 공집합이 아님: 변환은 가능한 읽기 값 집합을 비게 할 수 없다.

여전히 유효한 변환 예: 동일 위치 다수 비-atomic 읽기 병합, 비-atomic 읽기 재배열, 추측 비-atomic 읽기 도입, 동일 위치 다수 비-atomic 쓰기 병합, 서로 다른 위치 비-atomic 쓰기 재배열, 루프 밖으로 비-atomic 읽기 hoist (종료 영향 있어도). 일반적으로 alias 된 TypedArray 는 위치 구분을 어렵게 한다.

Note 3

다음은 공유 메모리 접근에 대한 기계어 코드를 생성하는 ECMAScript 구현자를 위한 지침이다.

ARM 또는 Power 보다 약하지 않은 메모리 모델을 가진 아키텍처에서 비-atomic store/load 는 일반 store/load 로 컴파일할 수 있다. Atomic store/load 는 순차적 일관성을 보장하는 명령으로 컴파일한다. 없으면 메모리 배리어 사용. Read-modify-write 는 아키텍처의 read-modify-write 명령(예: x86 LOCK prefix, ARM load-exclusive/store-exclusive, Power load-link/store-conditional)으로 컴파일.

구체적으로 메모리 모델은 다음과 같은 코드 생성을 허용한다.

  • 프로그램의 모든 atomic 연산은 필요하다고 가정.
  • Atomic 연산은 서로 또는 비-atomic 과 재배열되지 않는다.
  • 함수는 항상 atomic 연산 수행 가능하다고 가정.
  • Atomic 연산은 더 큰 데이터의 read-modify-write 로 구현되지 않는다(플랫폼에 그 크기 atomic 없으면 lock-free 아니게 구현).

단순 코드 생성 패턴:

  • 일반 load/store → 단일 load/store 명령.
  • Lock-free atomic load/store → 전체 펜스, load/store, 전체 펜스.
  • Lock-free atomic RMW → 전체 펜스, atomic RMW 시퀀스, 전체 펜스.
  • Non-lock-free atomic → 스핀락 획득, 전체 펜스, 비-atomic load/store 시리즈, 전체 펜스, 스핀락 해제.

이 매핑은 주소 범위에 대한 atomic 연산이 비-atomic 쓰기나 다른 크기 atomic 과 race 하지 않는 한 올바르다. 메모리 모델은 race 에 관여한 atomic 을 비-atomic 수준으로 강등하여 충분하다. 다만 이 단순 매핑은 atomic 연산을 순차적 일관성 펜스로 사용할 수 있게 하는 등 꽤 강하다.

허용되는 로컬 개선 예:

  • 플랫폼 의존 중복 펜스 제거 (예: x86 에서 load/store 전후 펜스 일부 생략 등).
  • 대부분 플랫폼은 필요한 모든 크기 lock-free atomic 지원.
  • 두 back-to-back 펜스 → 하나로 대체; x86 에서 store 뒤 펜스만 유지 등.

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) 인스턴스
PrimaryExpression[Yield, Await] : CoverParenthesizedExpressionAndArrowParameterList[?Yield, ?Await]
를 처리할 때 CoverParenthesizedExpressionAndArrowParameterList 의 해석은 아래 문법을 사용하여 정제된다:

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

생성식 인스턴스
CallExpression[Yield, Await] : CoverCallExpressionAndAsyncArrowHead[?Yield, ?Await]
를 처리할 때 CoverCallExpressionAndAsyncArrowHead 의 해석은 아래 문법으로 정제된다:

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] AwaitExpression[?Yield] 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 *= /= %= += -= <<= >>= >>>= &= ^= |= **=

특정 상황에서 생성식 인스턴스
AssignmentExpression[In, Yield, Await] : LeftHandSideExpression[?Yield, ?Await] = AssignmentExpression[?In, ?Yield, ?Await]
를 처리할 때 LeftHandSideExpression 의 해석은 아래 문법을 사용하여 정제된다:

AssignmentPattern[Yield, Await] : ObjectAssignmentPattern[?Yield, ?Await] ArrayAssignmentPattern[?Yield, ?Await] ObjectAssignmentPattern[Yield, Await] : { } { AssignmentRestProperty[?Yield, ?Await] } { AssignmentPropertyList[?Yield, ?Await] } { AssignmentPropertyList[?Yield, ?Await] , AssignmentRestProperty[?Yield, ?Await]opt } ArrayAssignmentPattern[Yield, Await] : [ Elisionopt AssignmentRestElement[?Yield, ?Await]opt ] [ AssignmentElementList[?Yield, ?Await] ] [ AssignmentElementList[?Yield, ?Await] , Elisionopt AssignmentRestElement[?Yield, ?Await]opt ] AssignmentRestProperty[Yield, Await] : ... DestructuringAssignmentTarget[?Yield, ?Await] AssignmentPropertyList[Yield, Await] : AssignmentProperty[?Yield, ?Await] AssignmentPropertyList[?Yield, ?Await] , AssignmentProperty[?Yield, ?Await] AssignmentElementList[Yield, Await] : AssignmentElisionElement[?Yield, ?Await] AssignmentElementList[?Yield, ?Await] , AssignmentElisionElement[?Yield, ?Await] AssignmentElisionElement[Yield, Await] : Elisionopt AssignmentElement[?Yield, ?Await] AssignmentProperty[Yield, Await] : IdentifierReference[?Yield, ?Await] Initializer[+In, ?Yield, ?Await]opt PropertyName[?Yield, ?Await] : AssignmentElement[?Yield, ?Await] AssignmentElement[Yield, Await] : DestructuringAssignmentTarget[?Yield, ?Await] Initializer[+In, ?Yield, ?Await]opt AssignmentRestElement[Yield, Await] : ... DestructuringAssignmentTarget[?Yield, ?Await] DestructuringAssignmentTarget[Yield, Await] : LeftHandSideExpression[?Yield, ?Await]

 

Expression[In, Yield, Await] : AssignmentExpression[?In, ?Yield, ?Await] Expression[?In, ?Yield, ?Await] , AssignmentExpression[?In, ?Yield, ?Await]

A.3 문(Statements)

Statement[Yield, Await, Return] : BlockStatement[?Yield, ?Await, ?Return] VariableStatement[?Yield, ?Await] EmptyStatement ExpressionStatement[?Yield, ?Await] IfStatement[?Yield, ?Await, ?Return] BreakableStatement[?Yield, ?Await, ?Return] ContinueStatement[?Yield, ?Await] BreakStatement[?Yield, ?Await] [+Return] ReturnStatement[?Yield, ?Await] WithStatement[?Yield, ?Await, ?Return] LabelledStatement[?Yield, ?Await, ?Return] ThrowStatement[?Yield, ?Await] TryStatement[?Yield, ?Await, ?Return] DebuggerStatement Declaration[Yield, Await] : HoistableDeclaration[?Yield, ?Await, ~Default] ClassDeclaration[?Yield, ?Await, ~Default] LexicalDeclaration[+In, ?Yield, ?Await] HoistableDeclaration[Yield, Await, Default] : FunctionDeclaration[?Yield, ?Await, ?Default] GeneratorDeclaration[?Yield, ?Await, ?Default] AsyncFunctionDeclaration[?Yield, ?Await, ?Default] AsyncGeneratorDeclaration[?Yield, ?Await, ?Default] BreakableStatement[Yield, Await, Return] : IterationStatement[?Yield, ?Await, ?Return] SwitchStatement[?Yield, ?Await, ?Return] BlockStatement[Yield, Await, Return] : Block[?Yield, ?Await, ?Return] Block[Yield, Await, Return] : { StatementList[?Yield, ?Await, ?Return]opt } StatementList[Yield, Await, Return] : StatementListItem[?Yield, ?Await, ?Return] StatementList[?Yield, ?Await, ?Return] StatementListItem[?Yield, ?Await, ?Return] StatementListItem[Yield, Await, Return] : Statement[?Yield, ?Await, ?Return] Declaration[?Yield, ?Await] LexicalDeclaration[In, Yield, Await] : LetOrConst BindingList[?In, ?Yield, ?Await] ; LetOrConst : let const BindingList[In, Yield, Await] : LexicalBinding[?In, ?Yield, ?Await] BindingList[?In, ?Yield, ?Await] , LexicalBinding[?In, ?Yield, ?Await] LexicalBinding[In, Yield, Await] : BindingIdentifier[?Yield, ?Await] Initializer[?In, ?Yield, ?Await]opt BindingPattern[?Yield, ?Await] Initializer[?In, ?Yield, ?Await] 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] in Expression[+In, ?Yield, ?Await] ) Statement[?Yield, ?Await, ?Return] for ( ForDeclaration[?Yield, ?Await] 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] of AssignmentExpression[+In, ?Yield, ?Await] ) Statement[?Yield, ?Await, ?Return] for ( ForDeclaration[?Yield, ?Await] 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] of AssignmentExpression[+In, ?Yield, ?Await] ) Statement[?Yield, ?Await, ?Return] [+Await] for await ( ForDeclaration[?Yield, ?Await] of AssignmentExpression[+In, ?Yield, ?Await] ) Statement[?Yield, ?Await, ?Return] ForDeclaration[Yield, Await] : LetOrConst ForBinding[?Yield, ?Await] ForBinding[Yield, Await] : BindingIdentifier[?Yield, ?Await] 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]

생성식 인스턴스
ArrowParameters[Yield, Await] : CoverParenthesizedExpressionAndArrowParameterList[?Yield, ?Await]
를 처리할 때 CoverParenthesizedExpressionAndArrowParameterList 의 해석은 아래 문법을 사용해 정제된다:

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]

생성식 인스턴스
AsyncArrowFunction[In, Yield, Await] : CoverCallExpressionAndAsyncArrowHead[?Yield, ?Await] [no LineTerminator here] => AsyncConciseBody[?In]
를 처리할 때 CoverCallExpressionAndAsyncArrowHead 의 해석은 아래 문법으로 정제된다:

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 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 숫자 변환

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 문법에 의해 명시적으로 정의되지 않은 모든 문법 기호는 숫자 리터럴을 위한 어휘 문법에서 사용된 정의를 가진다.

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

A.7 시간대 오프셋 문자열 형식

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

연결될 \u HexLeadSurrogate 선택이 모호한 각 \u HexTrailSurrogate 는 그렇지 않으면 대응하는 \u HexTrailSurrogate 가 없게 될 가장 가까운 u HexLeadSurrogate 와 연결되어야 한다.

 

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 기능

이 부록에 정의된 ECMAScript 언어 구문과 의미는 ECMAScript 호스트가 웹 브라우저인 경우 필수이다. 이 부록의 내용은 규범적이지만 ECMAScript 호스트가 웹 브라우저가 아닌 경우 선택 사항이다.

이 부록에 정의된 일부 기능은 이 부록에서, 또 일부는 본문에서 정의된다.

기능이 본문에서 정의되는 경우, 문서에 영향을 미치는 각 지점은 색상 박스 안의 "Normative Optional" 문구로 표시된다. 또한 어떤 기능이 알고리즘이나 초기 에러 규칙의 특정 문구를 수반할 때는 그것이 관련 기능에 대해 “the host supports”하는 조건으로 보호된다. 웹 브라우저는 그러한 모든 기능을 지원해야 한다.

Note

이 부록은 다양한 레거시 기능과 웹 브라우저 ECMAScript 호스트의 기타 특성을 설명한다. 이 부록에 명시된 모든 언어 기능과 동작은 하나 이상의 바람직하지 않은 특성을 가지며 레거시 사용이 없다면 이 명세에서 제거되었을 것이다. 그러나 다수의 기존 웹 페이지가 이러한 기능을 사용하기 때문에 웹 브라우저는 계속해서 이를 지원해야 한다. 이 부록의 명세는 이러한 레거시 기능의 상호 운용 구현 요구 사항을 정의한다.

이 기능들은 핵심 ECMAScript 언어의 일부로 간주되지 않는다. 프로그래머는 새로운 ECMAScript 코드를 작성할 때 이러한 기능과 동작의 존재를 사용하거나 가정해서는 안 된다. ECMAScript 구현은 구현이 웹 브라우저의 일부이거나 웹 브라우저가 마주치는 동일한 레거시 ECMAScript 코드를 실행해야 하는 경우가 아니면 이러한 기능을 구현하지 않는 것이 권장된다.

B.1 추가 구문

B.1.1 HTML 유사 주석

12.4의 구문과 의미는 다음과 같이 확장되지만, 이 확장은 목표 심볼 Module 로 소스 텍스트를 파싱할 때는 허용되지 않는다:

구문

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

줄 종결자 코드 포인트를 포함하는 MultiLineComment 와 유사하게, SingleLineHTMLCloseComment 는 구문 문법에 의한 파싱 목적상 LineTerminator 로 간주된다.

B.1.2 정규 표현식 패턴

22.2.1의 구문은 다음과 같이 수정·확장된다. 이러한 변경은 문법 생성식의 순서 및 문맥 정보를 통해 해소되는 모호성을 도입한다. 아래 문법을 사용하여 파싱할 때 각 대안은 이전 생성식 대안이 일치하지 않을 경우에만 고려된다.

이 대안 패턴 문법과 의미는 BMP 패턴의 구문과 의미만 변경한다. 다음 문법 확장은 [UnicodeMode] 매개변수를 가진 생성식을 포함한다. 그러나 이러한 확장 중 어느 것도 목표 심볼에 [UnicodeMode] 매개변수가 존재할 때 인식되는 유니코드 패턴의 구문을 변경하지 않는다.

구문

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

동일한 좌변이 [+UnicodeMode] 와 [~UnicodeMode] 가드를 모두 가지는 경우 이는 모호성 해소 우선순위를 제어하기 위한 것이다.

B.1.2.1 정적 의미: 초기 에러

22.2.1.1의 의미는 다음과 같이 확장된다:

ExtendedAtom :: InvalidBracedQuantifier
  • 이 생성식이 어떤 소스 텍스트와 일치하면 Syntax Error 이다.

또한 다음 생성식의 규칙은 강조된 텍스트를 추가하여 수정된다:

NonemptyClassRanges :: ClassAtom - ClassAtom ClassContents
  • 첫 번째 ClassAtom 의 IsCharacterClass 가 true 이거나 두 번째 ClassAtom 의 IsCharacterClass 가 true 이고 이 생성식이 [UnicodeMode] 매개변수를 가진 경우 Syntax Error 이다.
  • 첫 번째 ClassAtom 의 IsCharacterClass 가 false, 두 번째 ClassAtom 의 IsCharacterClass 가 false 이고 첫 번째 ClassAtom 의 CharacterValue 가 두 번째 ClassAtom 의 CharacterValue 보다 엄격하게 크면 Syntax Error 이다.
NonemptyClassRangesNoDash :: ClassAtomNoDash - ClassAtom ClassContents
  • ClassAtomNoDash 의 IsCharacterClass 가 true 이거나 ClassAtom 의 IsCharacterClass 가 true 이고 이 생성식이 [UnicodeMode] 매개변수를 가진 경우 Syntax Error 이다.
  • ClassAtomNoDash 의 IsCharacterClass 가 false, ClassAtom 의 IsCharacterClass 가 false 이고 ClassAtomNoDash 의 CharacterValue 가 ClassAtom 의 CharacterValue 보다 엄격하게 크면 Syntax Error 이다.

B.1.2.2 정적 의미: CountLeftCapturingParensWithin 및 CountLeftCapturingParensBefore

CountLeftCapturingParensWithin 및 CountLeftCapturingParensBefore 정의에서 “ Atom :: ( GroupSpecifieropt Disjunction ) ”에 대한 참조는 “ Atom :: ( GroupSpecifieropt Disjunction ) ” 또는 “ ExtendedAtom :: ( GroupSpecifieropt Disjunction ) ”를 의미하는 것으로 해석된다.

B.1.2.3 정적 의미: IsCharacterClass

22.2.1.6의 의미는 다음과 같이 확장된다:

ClassAtomNoDash :: \ [lookahead = c]
  1. false를 반환한다.

B.1.2.4 정적 의미: CharacterValue

22.2.1.7의 의미는 다음과 같이 확장된다:

ClassAtomNoDash :: \ [lookahead = c]
  1. U+005C (REVERSE SOLIDUS)의 숫자 값을 반환한다.
ClassEscape :: c ClassControlLetter
  1. chClassControlLetter 가 매칭한 코드 포인트로 둔다.
  2. ich 의 숫자 값으로 둔다.
  3. i 를 32로 나눈 나머지를 반환한다.
CharacterEscape :: LegacyOctalEscapeSequence
  1. LegacyOctalEscapeSequence 의 MV 를 반환한다(12.9.4.3 참조).

B.1.2.5 런타임 의미: CompileSubpattern

CompileSubpattern 의 의미는 다음과 같이 확장된다:

Term :: QuantifiableAssertion Quantifier 에 대한 규칙은 Atom 대신 QuantifiableAssertion 을 대입한 것을 제외하면 Term :: Atom Quantifier 의 규칙과 동일하다.

Term :: ExtendedAtom Quantifier 에 대한 규칙은 Atom 대신 ExtendedAtom 을 대입한 것을 제외하면 Term :: Atom Quantifier 와 동일하다.

Term :: ExtendedAtom 에 대한 규칙은 Atom 대신 ExtendedAtom 을 대입한 것을 제외하면 Term :: Atom 과 동일하다.

B.1.2.6 런타임 의미: CompileAssertion

Assertion :: (?= Disjunction ) Assertion :: (?! Disjunction ) 생성식에 대한 CompileAssertion 규칙은 Assertion 대신 QuantifiableAssertion 을 대입하여 QuantifiableAssertion 생성식에도 사용된다.

B.1.2.7 런타임 의미: CompileAtom

Atom :: PatternCharacter 를 제외한 Atom 생성식에 대한 CompileAtom 규칙은 Atom 대신 ExtendedAtom 을 대입하여 ExtendedAtom 생성식에도 사용된다. 다음 규칙(매개변수 direction)이 추가된다:

ExtendedAtom :: \ [lookahead = c]
  1. A 를 단일 문자 \ U+005C (REVERSE SOLIDUS)를 포함하는 CharSet 으로 둔다.
  2. CharacterSetMatcher(rer, A, false, direction) 를 반환한다.
ExtendedAtom :: ExtendedPatternCharacter
  1. chExtendedPatternCharacter 가 표현하는 문자로 둔다.
  2. A 를 문자 ch 하나만 포함하는 CharSet 으로 둔다.
  3. CharacterSetMatcher(rer, A, false, direction) 를 반환한다.

B.1.2.8 런타임 의미: CompileToCharSet

22.2.2.9의 의미는 다음과 같이 확장된다:

다음 두 규칙은 CompileToCharSet 의 해당 규칙을 대체한다.

NonemptyClassRanges :: ClassAtom - ClassAtom ClassContents
  1. A 를 첫 번째 ClassAtom 에 대한 CompileToCharSet(rer) 결과로 둔다.
  2. B 를 두 번째 ClassAtom 에 대한 CompileToCharSet(rer) 결과로 둔다.
  3. CClassContents 에 대한 CompileToCharSet(rer) 결과로 둔다.
  4. DCharacterRangeOrUnion(rer, A, B) 로 둔다.
  5. DC 의 합집합을 반환한다.
NonemptyClassRangesNoDash :: ClassAtomNoDash - ClassAtom ClassContents
  1. AClassAtomNoDash 에 대한 CompileToCharSet(rer) 결과로 둔다.
  2. BClassAtom 에 대한 CompileToCharSet(rer) 결과로 둔다.
  3. CClassContents 에 대한 CompileToCharSet(rer) 결과로 둔다.
  4. DCharacterRangeOrUnion(rer, A, B) 로 둔다.
  5. DC 의 합집합을 반환한다.

추가로 다음 규칙이 CompileToCharSet 에 추가된다.

ClassEscape :: c ClassControlLetter
  1. cv 를 이 ClassEscape 의 CharacterValue 로 둔다.
  2. c 를 문자 값이 cv 인 문자로 둔다.
  3. 문자 c 하나만 포함하는 CharSet 을 반환한다.
ClassAtomNoDash :: \ [lookahead = c]
  1. 단일 문자 \ U+005C (REVERSE SOLIDUS)를 포함하는 CharSet 을 반환한다.
Note
이 생성식은 허용 가능한 제어 문자가 뒤따르지 않는 문자 클래스 내부의 \c 시퀀스로부터만 도달될 수 있다.

B.1.2.8.1 CharacterRangeOrUnion ( rer, A, B )

The abstract operation CharacterRangeOrUnion takes arguments rer (a RegExp Record), A (a CharSet), and B (a CharSet) and returns a CharSet. It performs the following steps when called:

  1. HasEitherUnicodeFlag(rer) 가 false 이면
    1. A 가 정확히 한 문자를 포함하지 않거나 B 가 정확히 한 문자를 포함하지 않으면
      1. C 를 단일 문자 - U+002D (HYPHEN-MINUS)를 포함하는 CharSet 으로 둔다.
      2. CharSet A, B, C 의 합집합을 반환한다.
  2. CharacterRange(A, B) 를 반환한다.

B.1.2.9 정적 의미: ParsePattern ( patternText, u, v )

22.2.3.4의 의미는 다음과 같이 확장된다:

추상 연산 ParsePattern 은 인수 patternText(유니코드 코드 포인트 시퀀스), u(Boolean), v(Boolean)을 받고 호출 시 다음 단계를 수행한다:

  1. vtrue 이고 utrue 이면
    1. parseResult 를 하나 이상의 SyntaxError 객체를 포함하는 List 로 둔다.
  2. Else if vtrue 이면
    1. parseResult 를 ParseText(patternText, Pattern[+UnicodeMode, +UnicodeSetsMode, +NamedCaptureGroups]) 로 둔다.
  3. Else if utrue 이면
    1. parseResult 를 ParseText(patternText, Pattern[+UnicodeMode, ~UnicodeSetsMode, +NamedCaptureGroups]) 로 둔다.
  4. Else,
    1. parseResult 를 ParseText(patternText, Pattern[~UnicodeMode, ~UnicodeSetsMode, ~NamedCaptureGroups]) 로 둔다.
    2. parseResult 가 Parse Node 이고 GroupName 을 포함하면
      1. parseResult 를 ParseText(patternText, Pattern[~UnicodeMode, ~UnicodeSetsMode, +NamedCaptureGroups]) 로 설정한다.
  5. parseResult 를 반환한다.

B.2 추가 내장 프로퍼티

ECMAScript 호스트가 웹 브라우저인 경우 표준 내장 객체의 다음 추가 프로퍼티가 정의된다.

B.2.1 전역 객체의 추가 프로퍼티

Table 100의 항목을 Table 6에 추가한다.

Table 100: 추가 잘 알려진 내재 객체
Intrinsic Name Global Name ECMAScript Language Association
%escape% escape escape 함수 (B.2.1.1)
%unescape% unescape unescape 함수 (B.2.1.2)

B.2.1.1 escape ( string )

이 함수는 전역 객체의 프로퍼티이다. 특정 코드 유닛이 16진수 이스케이프 시퀀스로 교체된 새로운 String 값을 계산한다.

숫자 값이 0x00FF 이하인 코드 유닛을 교체할 때는 %xx 형태의 2자리 이스케이프 시퀀스를 사용한다. 숫자 값이 0x00FF 를 초과하는 코드 유닛을 교체할 때는 %uxxxx 형태의 4자리 이스케이프 시퀀스를 사용한다.

이것은 %escape% 내재 객체이다.

호출 시 다음 단계를 수행한다:

  1. string 을 ? ToString(string) 으로 설정한다.
  2. lenstring 의 길이로 둔다.
  3. R 을 빈 String 으로 둔다.
  4. unescapedSet 을 ASCII 단어 문자와 "@*+-./" 의 문자열 연결로 둔다.
  5. k 를 0으로 둔다.
  6. 반복, k < len 인 동안
    1. Cstring 내 인덱스 k 의 코드 유닛으로 둔다.
    2. unescapedSetC 를 포함하면
      1. SC 로 둔다.
    3. 아니면
      1. nC 의 숫자 값으로 둔다.
      2. n < 256 이면
        1. hexn 을 대문자 16진수로 서식화한 String 표현으로 둔다.
        2. S"%"StringPad(hex, 2, "0", start) 의 문자열 연결로 둔다.
      3. 그렇지 않으면
        1. hexn 을 대문자 16진수로 서식화한 String 표현으로 둔다.
        2. S"%u"StringPad(hex, 4, "0", start) 의 문자열 연결로 둔다.
    4. RRS 의 문자열 연결로 설정한다.
    5. kk + 1 로 설정한다.
  7. R 을 반환한다.
Note

이 인코딩은 부분적으로 RFC 1738 의 인코딩을 기반으로 하지만, 이 표준에 명시된 전체 인코딩은 RFC 1738 의 내용과 무관하게 위에서 설명된다. 이 인코딩은 RFC 3986 이 RFC 1738 에 적용한 변경 사항을 반영하지 않는다.

B.2.1.2 unescape ( string )

이 함수는 전역 객체의 프로퍼티이다. escape 함수가 도입했을 수 있는 형태의 각 이스케이프 시퀀스를 그것이 표현하는 코드 유닛으로 교체한 새로운 String 값을 계산한다.

이것은 %unescape% 내재 객체이다.

호출 시 다음 단계를 수행한다:

  1. string 을 ? ToString(string) 으로 설정한다.
  2. lenstring 의 길이로 둔다.
  3. R 을 빈 String 으로 둔다.
  4. k 를 0으로 둔다.
  5. 반복, k < len 인 동안
    1. Cstring 내 인덱스 k 의 코드 유닛으로 둔다.
    2. C 가 코드 유닛 0x0025 (PERCENT SIGN)이면
      1. hexDigits 를 빈 String 으로 둔다.
      2. optionalAdvance 를 0으로 둔다.
      3. k + 5 < len 이고 string 내 인덱스 k + 1 의 코드 유닛이 0x0075 (LATIN SMALL LETTER U)이면
        1. hexDigitsstringk + 2 부터 k + 6 까지의 부분 문자열로 설정한다.
        2. optionalAdvance 를 5로 설정한다.
      4. Else if k + 3 ≤ len 이면
        1. hexDigitsstringk + 1 부터 k + 3 까지의 부분 문자열로 설정한다.
        2. optionalAdvance 를 2로 설정한다.
      5. parseResult 를 ParseText(hexDigits, HexDigits[~Sep]) 로 둔다.
      6. parseResult 가 Parse Node 이면
        1. nparseResult 의 MV 로 둔다.
        2. C 를 숫자 값이 n 인 코드 유닛으로 설정한다.
        3. kk + optionalAdvance 로 설정한다.
    3. RRC 의 문자열 연결로 설정한다.
    4. kk + 1 로 설정한다.
  6. R 을 반환한다.

B.2.2 String.prototype 객체의 추가 프로퍼티

B.2.2.1 String.prototype.substr ( start, length )

이 메서드는 this 값을 String 으로 변환한 결과에서 인덱스 start 에서 시작하여 length 코드 유닛(또는 lengthundefined 이면 문자열 끝까지) 길이의 substring 을 반환한다. start 가 음수이면 sourceLength 를 문자열 길이로 하여 sourceLength + start 로 처리한다. 결과는 String 객체가 아닌 String 값이다.

호출 시 다음 단계를 수행한다:

  1. Othis 값으로 둔다.
  2. RequireObjectCoercible(O) 를 수행한다.
  3. S 를 ? ToString(O) 로 둔다.
  4. sizeS 의 길이로 둔다.
  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 사이로 클램프한 결과로 설정한다.
  11. intEndmin(intStart + intLength, size) 로 둔다.
  12. SintStart 부터 intEnd 까지의 substring 을 반환한다.
Note

이 메서드는 의도적으로 제네릭하다; this 값이 String 객체일 필요가 없다. 따라서 다른 종류의 객체에 메서드로 이전하여 사용할 수 있다.

B.2.2.2 String.prototype.anchor ( name )

이 메서드는 호출 시 다음 단계를 수행한다:

  1. Sthis 값으로 둔다.
  2. CreateHTML(S, "a", "name", name) 를 반환한다.

B.2.2.2.1 CreateHTML ( string, tag, attribute, value )

The abstract operation CreateHTML takes arguments string (an ECMAScript language value), tag (a String), attribute (a String), and value (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(string) 를 수행한다.
  2. S 를 ? ToString(string) 로 둔다.
  3. p1"<"tag 의 문자열 연결로 둔다.
  4. attribute 가 빈 String 이 아니면
    1. V 를 ? ToString(value) 로 둔다.
    2. escapedVV 와 같되 V 내 코드 유닛 0x0022 (QUOTATION MARK) 의 각 출현이 6 코드 유닛 "&quot;" 로 대체된 String 값으로 둔다.
    3. p1 을 다음의 문자열 연결로 설정한다:
      • p1
      • 코드 유닛 0x0020 (SPACE)
      • attribute
      • 코드 유닛 0x003D (EQUALS SIGN)
      • 코드 유닛 0x0022 (QUOTATION MARK)
      • escapedV
      • 코드 유닛 0x0022 (QUOTATION MARK)
  5. p2p1">" 의 문자열 연결로 둔다.
  6. p3p2S 의 문자열 연결로 둔다.
  7. p4p3, "</", tag, ">" 의 문자열 연결로 둔다.
  8. p4 를 반환한다.

B.2.2.3 String.prototype.big ( )

이 메서드는 호출 시 다음 단계를 수행한다:

  1. Sthis 값으로 둔다.
  2. CreateHTML(S, "big", "", "") 를 반환한다.

B.2.2.4 String.prototype.blink ( )

이 메서드는 호출 시 다음 단계를 수행한다:

  1. Sthis 값으로 둔다.
  2. CreateHTML(S, "blink", "", "") 를 반환한다.

B.2.2.5 String.prototype.bold ( )

이 메서드는 호출 시 다음 단계를 수행한다:

  1. Sthis 값으로 둔다.
  2. CreateHTML(S, "b", "", "") 를 반환한다.

B.2.2.6 String.prototype.fixed ( )

이 메서드는 호출 시 다음 단계를 수행한다:

  1. Sthis 값으로 둔다.
  2. CreateHTML(S, "tt", "", "") 를 반환한다.

B.2.2.7 String.prototype.fontcolor ( colour )

이 메서드는 호출 시 다음 단계를 수행한다:

  1. Sthis 값으로 둔다.
  2. CreateHTML(S, "font", "color", colour) 를 반환한다.

B.2.2.8 String.prototype.fontsize ( size )

이 메서드는 호출 시 다음 단계를 수행한다:

  1. Sthis 값으로 둔다.
  2. CreateHTML(S, "font", "size", size) 를 반환한다.

B.2.2.9 String.prototype.italics ( )

이 메서드는 호출 시 다음 단계를 수행한다:

  1. Sthis 값으로 둔다.
  2. CreateHTML(S, "i", "", "") 를 반환한다.

B.2.2.10 String.prototype.link ( url )

이 메서드는 호출 시 다음 단계를 수행한다:

  1. Sthis 값으로 둔다.
  2. CreateHTML(S, "a", "href", url) 를 반환한다.

B.2.2.11 String.prototype.small ( )

이 메서드는 호출 시 다음 단계를 수행한다:

  1. Sthis 값으로 둔다.
  2. CreateHTML(S, "small", "", "") 를 반환한다.

B.2.2.12 String.prototype.strike ( )

이 메서드는 호출 시 다음 단계를 수행한다:

  1. Sthis 값으로 둔다.
  2. CreateHTML(S, "strike", "", "") 를 반환한다.

B.2.2.13 String.prototype.sub ( )

이 메서드는 호출 시 다음 단계를 수행한다:

  1. Sthis 값으로 둔다.
  2. CreateHTML(S, "sub", "", "") 를 반환한다.

B.2.2.14 String.prototype.sup ( )

이 메서드는 호출 시 다음 단계를 수행한다:

  1. Sthis 값으로 둔다.
  2. CreateHTML(S, "sup", "", "") 를 반환한다.

B.2.2.15 String.prototype.trimLeft ( )

Note

"trimStart" 프로퍼티가 더 선호된다. "trimLeft" 프로퍼티는 주로 오래된 코드와의 호환성을 위해 제공된다. 새로운 ECMAScript 코드에서는 "trimStart" 프로퍼티 사용이 권장된다.

"trimLeft" 프로퍼티의 초기 값은 22.1.3.34에 정의된 %String.prototype.trimStart% 이다.

B.2.2.16 String.prototype.trimRight ( )

Note

"trimEnd" 프로퍼티가 더 선호된다. "trimRight" 프로퍼티는 주로 오래된 코드와의 호환성을 위해 제공된다. 새로운 ECMAScript 코드에서는 "trimEnd" 프로퍼티 사용이 권장된다.

"trimRight" 프로퍼티의 초기 값은 22.1.3.33에 정의된 %String.prototype.trimEnd% 이다.

B.2.3 Date.prototype 객체의 추가 프로퍼티

B.2.3.1 Date.prototype.getYear ( )

Note

getFullYear 메서드가 “year 2000 문제”를 피하기 때문에 거의 모든 용도에 더 권장된다.

이 메서드는 호출 시 다음 단계를 수행한다:

  1. dateObjectthis 값으로 둔다.
  2. RequireInternalSlot(dateObject, [[DateValue]]) 를 수행한다.
  3. tdateObject.[[DateValue]] 로 둔다.
  4. tNaN 이면 NaN 을 반환한다.
  5. YearFromTime(LocalTime(t)) - 1900𝔽 을 반환한다.

B.2.3.2 Date.prototype.setYear ( year )

Note

setFullYear 메서드가 “year 2000 문제”를 피하기 때문에 거의 모든 용도에 더 권장된다.

이 메서드는 호출 시 다음 단계를 수행한다:

  1. dateObjectthis 값으로 둔다.
  2. RequireInternalSlot(dateObject, [[DateValue]]) 를 수행한다.
  3. tdateObject.[[DateValue]] 로 둔다.
  4. y 를 ? ToNumber(year) 로 둔다.
  5. tNaN 이면 t+0𝔽 로; 아니면 tLocalTime(t) 로 설정한다.
  6. yyyyMakeFullYear(y) 로 둔다.
  7. dMakeDay(yyyy, MonthFromTime(t), DateFromTime(t)) 로 둔다.
  8. dateMakeDate(d, TimeWithinDay(t)) 로 둔다.
  9. uTimeClip(UTC(date)) 로 둔다.
  10. dateObject.[[DateValue]]u 로 설정한다.
  11. u 를 반환한다.

B.2.3.3 Date.prototype.toGMTString ( )

Note

toUTCString 메서드가 더 선호된다. 이 메서드는 주로 오래된 코드와의 호환성을 위해 제공된다.

"toGMTString" 프로퍼티의 초기 값은 21.4.4.43에 정의된 %Date.prototype.toUTCString% 이다.

B.2.4 RegExp.prototype 객체의 추가 프로퍼티

B.2.4.1 RegExp.prototype.compile ( pattern, flags )

이 메서드는 호출 시 다음 단계를 수행한다:

  1. Othis 값으로 둔다.
  2. RequireInternalSlot(O, [[RegExpMatcher]]) 를 수행한다.
  3. pattern 이 Object 이고 [[RegExpMatcher]] 내부 슬롯을 가지면
    1. flagsundefined 가 아니면 TypeError 예외를 던진다.
    2. Ppattern.[[OriginalSource]] 로 둔다.
    3. Fpattern.[[OriginalFlags]] 로 둔다.
  4. 아니면
    1. Ppattern 으로 둔다.
    2. Fflags 로 둔다.
  5. RegExpInitialize(O, P, F) 를 반환한다.
Note

이 메서드는 this 값 RegExp 를 새로운 패턴과 플래그로 완전히 재초기화한다. 구현은 이 메서드 사용을 결과 RegExp 객체가 여러 번 사용될 것이며 추가 최적화 후보라는 주장으로 해석할 수 있다.

B.3 기타 추가 기능

B.3.1 레이블된 함수 선언

ECMAScript 2015 이전에는 LabelledStatement 의 명세가 문장 레이블을 FunctionDeclaration 과 연결하는 것을 허용하지 않았다. 그러나 레이블된 FunctionDeclaration 은 비엄격 코드에 대한 허용 확장이었고 대부분의 브라우저 호스트 ECMAScript 구현이 이를 지원했다. ECMAScript 2015 이후 문법 생성식 LabelledStatementFunctionDeclarationLabelledItem 으로 사용하는 것을 허용하지만 14.13.1 는 그것이 발생하면 Syntax Error 를 생성하는 초기 에러 규칙을 포함한다. 그 규칙은 호스트가 이 기능을 지원하는 비엄격 코드에서 Syntax Error 를 억제하도록 수정된다.

Note

WithStatement, IfStatement, IterationStatement 의 초기 에러 규칙은 비엄격 코드에서 이러한 문장이 레이블된 FunctionDeclaration 을 포함하는 것을 방지한다.

B.3.2 블록 수준 함수 선언 웹 레거시 호환 의미

ECMAScript 2015 이전에는 Block 문장의 StatementList 요소로 FunctionDeclaration 이 등장하는 것이 ECMAScript 명세에 정의되지 않았다. 그러나 해당 형태의 FunctionDeclaration 지원은 허용 확장이었고 대부분의 브라우저 호스트 ECMAScript 구현이 이를 허용했다. 불행히도 그러한 선언의 의미는 구현마다 다르다. 이러한 의미 차이 때문에 Block 수준 함수 선언을 사용하는 기존 웹 ECMAScript 소스 텍스트는 그러한 선언에 대해 모든 브라우저 구현의 의미 교집합에만 의존하는 경우에만 브라우저 구현 간 이식 가능하다. 다음이 그 교집합 의미에 속하는 사용 사례이다:

  1. 함수가 선언되고 단일 블록 내에서만 참조된다.

  2. 함수가 단일 Block 내에서 선언 및 사용될 수 있지만 동일한 Block 에 포함되지 않은 내부 함수 정의에서 참조된다.

    • 이름 fBindingIdentifier 를 가진 하나 이상의 FunctionDeclaration 이 둘러싼 함수 g 의 함수 코드 내에 나타나고 그 선언은 Block 에 중첩된다.
    • g 의 함수 코드 내에 var 선언이 아닌 다른 f 선언이 존재하지 않는다.
    • fIdentifierReference 출현이 선언을 포함하는 BlockStatementList 내에 있을 수 있다.
    • g 에 중첩된 다른 함수 h 내에 fIdentifierReference 출현이 적어도 하나 있고, h 로부터 f 참조를 가리는 다른 f 선언이 없다.
    • h 의 모든 호출은 f 선언이 평가된 이후에 발생한다.
  3. 함수가 단일 블록에서 선언 및 사용될 수 있지만 후속 블록에서 참조된다.

    • 이름 fBindingIdentifier 를 가진 하나 이상의 FunctionDeclaration 이 둘러싼 함수 g 의 함수 코드 내에 나타나고 그 선언은 Block 에 중첩된다.
    • g 의 함수 코드 내에 var 선언이 아닌 다른 f 선언이 존재하지 않는다.
    • fIdentifierReference 출현이 선언을 포함하는 BlockStatementList 내에 있을 수 있다.
    • f 선언을 포함하는 Block 을 어휘적으로 뒤따르는 g 의 함수 코드 내에 fIdentifierReference 출현이 적어도 하나 있다.

첫 번째 사용 사례는 ECMAScript 2015 가 제공하는 Block 수준 함수 선언 의미와 상호 운용된다. 그 사용 사례를 사용하는 모든 기존 ECMAScript 소스 텍스트는 10, 14, 15 절에 의해 정의된 블록 수준 함수 선언 의미를 사용하여 동작한다.

두 번째 및 세 번째 사용 사례에 대한 ECMAScript 2015 상호 운용성은 10 절, 15 절, 19.2.1 절 및 16.1.7 절 의미에 대한 다음 확장을 필요로 한다.

ECMAScript 구현에 진단 경고 메시지를 보고하는 메커니즘이 있는 경우, 이러한 호환 의미가 적용되어 비호환 의미와 관찰 가능한 차이를 만드는 FunctionDeclaration 이 있는 코드를 포함하면 경고가 생성되어야 한다. 예를 들어, var 바인딩 도입이 초기 에러를 만들기 때문에 도입되지 않는 경우 경고 메시지는 생성되지 않아야 한다.

이 기능은 다음 지점에서 특별한 의미를 포함한다:

B.3.3 IfStatement 문 절의 FunctionDeclaration

다음은 14.6IfStatement 생성식을 확장한다:

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]

이 생성식은 비엄격 코드를 파싱할 때만 적용된다. 이 생성식과 일치하는 소스 텍스트는 각 FunctionDeclaration[?Yield, ?Await, ~Default] 출현이 소스 텍스트에서 그 위치를 차지하는 BlockStatement 의 유일한 StatementListItem 인 것처럼 처리된다. 그러한 합성 BlockStatement 의 의미에는 B.3.2 에 명시된 웹 레거시 호환 의미가 포함된다.

B.3.4 Catch 블록 내 VariableStatement

이 기능에서는 Catch 절의 BlockCatchParameter 에 의해 바인딩된 이름을 또한 바인딩하는 var 선언을 포함할 수 있다. 이는 Catch : catch ( CatchParameter ) Block 에 대한 14.15.1 의 초기 에러 규칙을 수정하여 달성된다.

Note

런타임에는 이러한 바인딩이 VariableDeclarationEnvironment 에서 인스턴스화된다. 이들은 CatchParameter 가 도입한 동일 이름 바인딩을 가리지 않으므로 해당 var 선언의 Initializervar 바인딩이 아니라 대응 catch 매개변수에 할당한다.

이 수정된 동작은 Catch 절의 Block 내 직접 eval 호출로 도입된 varfunction 선언에도 적용된다. 이 변경은 EvalDeclarationInstantiation3.d.i.2.a.i13.b.ii.4.a.i.i 단계를 수정하여 달성된다.

B.3.5 ForIn 문 Head 의 Initializer

다음은 14.7.5ForInOfStatement 생성식을 확장한다:

ForInOfStatement[Yield, Await, Return] : for ( var BindingIdentifier[?Yield, ?Await] Initializer[~In, ?Yield, ?Await] in Expression[+In, ?Yield, ?Await] ) Statement[?Yield, ?Await, ?Return]

이 생성식은 비엄격 코드를 파싱할 때만 적용된다.

8.3.1 의 ContainsDuplicateLabels 정적 의미는 다음으로 확장된다:

ForInOfStatement : for ( var BindingIdentifier Initializer in Expression ) Statement
  1. Statement 의 ContainsDuplicateLabels(labelSet) 를 반환한다.

8.3.2 의 ContainsUndefinedBreakTarget 정적 의미는 다음으로 확장된다:

ForInOfStatement : for ( var BindingIdentifier Initializer in Expression ) Statement
  1. Statement 의 ContainsUndefinedBreakTarget(labelSet) 를 반환한다.

8.3.3 의 ContainsUndefinedContinueTarget 정적 의미는 다음으로 확장된다:

ForInOfStatement : for ( var BindingIdentifier Initializer in Expression ) Statement
  1. Statement 의 ContainsUndefinedContinueTarget(iterationSet, « ») 를 반환한다.

14.7.5.2 의 IsDestructuring 정적 의미는 다음으로 확장된다:

BindingIdentifier : Identifier yield await
  1. false 를 반환한다.

8.2.6 의 VarDeclaredNames 정적 의미는 다음으로 확장된다:

ForInOfStatement : for ( var BindingIdentifier Initializer in Expression ) Statement
  1. names1BindingIdentifier 의 BoundNames 로 둔다.
  2. names2Statement 의 VarDeclaredNames 로 둔다.
  3. names1names2 의 리스트 연결을 반환한다.

8.2.7 의 VarScopedDeclarations 정적 의미는 다음으로 확장된다:

ForInOfStatement : for ( var BindingIdentifier Initializer in Expression ) Statement
  1. declarations1 을 « BindingIdentifier » 로 둔다.
  2. declarations2Statement 의 VarScopedDeclarations 로 둔다.
  3. declarations1declarations2 의 리스트 연결을 반환한다.

14.7.5.5 의 ForInOfLoopEvaluation 런타임 의미는 다음으로 확장된다:

ForInOfStatement : for ( var BindingIdentifier Initializer in Expression ) Statement
  1. bindingIdBindingIdentifier 의 StringValue 로 둔다.
  2. lhs 를 ? ResolveBinding(bindingId) 로 둔다.
  3. IsAnonymousFunctionDefinition(Initializer) 이 true 이면
    1. valueInitializer 의 NamedEvaluation(bindingId) 로 둔다.
  4. Else,
    1. rhsInitializer 의 Evaluation 결과로 둔다.
    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]] 내부 슬롯

[[IsHTMLDDA]] 내부 슬롯호스트 정의 객체에 존재할 수 있다. [[IsHTMLDDA]] 내부 슬롯을 가진 객체는 ToBoolean, IsLooselyEqual 추상 연산 및 typeof 연산자의 피연산자로 사용될 때 undefined 처럼 동작한다.

Note

[[IsHTMLDDA]] 내부 슬롯을 가진 객체는 이 명세에서 생성되지 않는다. 그러나 웹 브라우저의 document.all 객체 는 웹 호환성 목적을 위해 이 슬롯을 가진 호스트 정의 특이 객체이다. 이 종류 객체의 다른 알려진 예는 없으며 구현에서는 document.all 을 제외하고 새로 만들지 않아야 한다.

이 기능은 다음 지점에서 특별한 의미를 포함한다:

B.3.7 HostMakeJobCallback 의 비기본 동작

HostMakeJobCallback 추상 연산은 웹 브라우저인 호스트가 비기본 동작을 지정할 수 있게 한다.

B.3.8 HostEnsureCanAddPrivateElement 의 비기본 동작

HostEnsureCanAddPrivateElement 추상 연산은 웹 브라우저인 호스트가 비기본 동작을 지정할 수 있게 한다.

B.3.9 함수 호출 대입 대상으로 인한 런타임 에러

함수 호출(13.3.6)이 비엄격 코드에서 대입 대상(assignment target)으로 사용될 때 초기 에러를 생성하는 대신 평가 중 ReferenceError 예외가 발생한다.

Note

대입 대상이 AssignmentExpressionLeftHandSideExpression 인 경우 대입 연산자는 = 또는 AssignmentOperator 여야 한다; 특히 논리 대입 연산자(??=, &&=, ||=)에는 이 허용이 적용되지 않는다.

CallExpression : CoverCallExpressionAndAsyncArrowHead CallExpression : CallExpression Arguments 에 대해 AssignmentTargetType 의 1 단계를 참조하라.

Annex C (informative) ECMAScript의 엄격 모드 (Strict Mode)

엄격 모드의 제한과 예외

Annex D (informative) 호스트 계층화 지점 (Host Layering Points)

호스트의 정의는 4.2 를 보라.

D.1 호스트 훅 (Host Hooks)

HostCallJobCallback(...)

HostEnqueueFinalizationRegistryCleanupJob(...)

HostEnqueueGenericJob(...)

HostEnqueuePromiseJob(...)

HostEnqueueTimeoutJob(...)

HostEnsureCanCompileStrings(...)

HostFinalizeImportMeta(...)

HostGetImportMetaProperties(...)

HostGrowSharedArrayBuffer(...)

HostHasSourceTextAvailable(...)

HostLoadImportedModule(...)

HostGetSupportedImportAttributes(...)

HostMakeJobCallback(...)

HostPromiseRejectionTracker(...)

HostResizeArrayBuffer(...)

InitializeHostDefinedRealm(...)

D.2 호스트 정의 필드

Realm Record[[HostDefined]]: Table 22 참조.

Script Record[[HostDefined]]: Table 37 참조.

Module Record[[HostDefined]]: Table 41 참조.

JobCallback Record[[HostDefined]]: Table 26 참조.

Candidate Executions 의 [[HostSynchronizesWith]]: Table 99 참조.

[[IsHTMLDDA]]: B.3.6 참조.

D.3 호스트 정의 객체

전역 객체: 19 절 참조.

D.4 작업 실행 (Running Jobs)

Job 추상 클로저 호출 전 준비 단계와 호출 후 정리 단계. 9.5 참조.

D.5 특이 객체의 내부 메서드

이 명세에 명시되지 않은 어떤 특이 객체에 대해 Table 4 의 필수 내부 메서드.

D.6 내장 객체와 메서드

17.1 에서 제한된 것을 제외하고 이 명세에 정의되지 않은 내장 객체와 메서드.

Annex E (informative) ECMAScript 2015의 정정 및 명확화 (호환성 영향 가능)

9.1.1.4.14-9.1.1.4.17: 5 및 5.1판은 새로운 전역 선언에 해당하는 전역 객체 프로퍼티가 이미 존재하는지 판단하기 위해 프로퍼티 존재 테스트를 사용했다. ECMAScript 2015는 own 프로퍼티 존재 테스트를 사용한다. 이는 웹 브라우저에서 가장 일반적으로 구현된 방식과 일치한다.

10.4.2.1: 5판은 배열 인덱스 또는 새로운 길이 값의 정수 변환 이전에 현재 배열 길이 캡처로 이동했다. 그러나 변환 과정이 배열 길이를 변경하는 부작용을 가지면 캡처된 길이 값은 무효화될 수 있었다. ECMAScript 2015는 그러한 부작용 발생 가능성 이후에 현재 배열 길이를 캡처해야 함을 명시한다.

21.4.1.31: 이전 판은 0 시간 값 표현으로 +0𝔽 또는 -0𝔽TimeClip 추상 연산이 반환하도록 허용했다. ECMAScript 2015는 항상 +0𝔽 를 반환하도록 명시한다. 이는 2015판에서는 Date 의 시간 값이 관찰 가능하게 -0𝔽 가 아니며 시간 값을 반환하는 메서드는 -0𝔽 를 반환하지 않음을 의미한다.

21.4.1.32: UTC 오프셋 표현이 없으면 로컬 시간대를 사용한다. 5.1판은 빠진 시간대를 "z" 로 해석해야 한다고 잘못 기술했다.

21.4.4.36: 연도가 Date Time String Format (21.4.1.32) 으로 표현될 수 없으면 RangeError 예외가 던져진다. 이전 판은 이 경우의 동작을 명시하지 않았다.

21.4.4.41: 이전 판은 시간 값NaN 일 때 Date.prototype.toString 이 반환하는 값을 명시하지 않았다. ECMAScript 2015는 결과가 문자열 "Invalid Date" 임을 명시한다.

22.2.4.1, 22.2.6.13.1: RegExp 인스턴스의 "source" 프로퍼티 값 내 LineTerminator 코드 포인트는 이스케이프 시퀀스로 표현되어야 한다. 5.1판은 / 만 이스케이프하도록 요구했다.

22.2.6.8, 22.2.6.11: 이전 판에서 String.prototype.matchString.prototype.replace 의 명세는 global 플래그가 설정된 RegExp 값 패턴 인수에 대해 잘못되었다. 이전 명세는 각 매칭 시도에서 lastIndex 가 변하지 않으면 1 증가해야 한다고 했다. 올바른 동작은 패턴이 빈 문자열과 일치한 경우에만 lastIndex 를 1 증가시키는 것이다.

23.1.3.30: 이전 판은 comparator 가 반환한 NaN 값이 Array.prototype.sort 에 의해 어떻게 해석되는지 명시하지 않았다. ECMAScript 2015는 그 값이 comparator+0𝔽 를 반환한 것처럼 취급된다고 명시한다. 또한 2015판은 comparator 가 반환한 결과에 ToNumber 가 적용된다고 명시한다. 이전 판에서는 Number 값이 아닌 comparator 결과의 영향이 구현 정의였다. 실제로 구현은 ToNumber 를 호출한다.

Annex F (informative) 이전 판과의 비호환성을 도입하는 추가 및 변경

6.2.5: ECMAScript 2015에서 함수 호출은 Reference Record 를 반환할 수 없다.

7.1.4.1: ECMAScript 2015에서 ToNumber 는 String 값에 적용될 때 BinaryIntegerLiteralOctalIntegerLiteral 숫자 문자열을 인식하고 변환한다. 이전 판에서는 그러한 문자열이 NaN 으로 변환되었다.

9.3: ECMAScript 2018에서 템플릿 객체는 이전 판의 Realm 내 템플릿 리터럴 또는 태그된 템플릿 모든 출현 간이 아니라 Parse Node (소스 위치) 기반으로 정규화된다.

12.2: ECMAScript 2016에서 Unicode 8.0.0 이상이 요구된다(2015판은 Unicode 5.1 요구). 특히 U+180E MONGOLIAN VOWEL SEPARATOR 가 Space_Separator (Zs) 범주에서 Format (Cf) 범주로 이동(Unicode 6.3.0)하여 공백 처리 메서드의 동작이 달라진다. 예: "\u180E".trim().length 는 이전 판에서 0 이었지만 ECMAScript 2016 이후 1. 또한 ECMAScript 2017은 항상 최신 Unicode 표준 사용을 요구.

12.7: ECMAScript 2015에서 IdentifierName 유효 코드 포인트는 Unicode 속성 “ID_Start”, “ID_Continue” 로 지정된다. 이전 판에서는 유효 IdentifierName 또는 Identifier 코드 포인트가 다양한 Unicode 범주를 열거하여 지정되었다.

12.10.1: ECMAScript 2015에서 자동 세미콜론 삽입은 do-while 문 끝에 세미콜론이 없으면 추가한다. 이 변경은 대부분 구현의 실제 동작과 일치.

13.2.5.1: ECMAScript 2015에서 Object Initializer 내 중복 프로퍼티 이름은 더 이상 초기 에러가 아니다.

13.15.1: ECMAScript 2015에서 FunctionExpression 의 함수 이름과 같은 불변 바인딩에 대한 대입을 포함한 엄격 모드 코드는 초기 에러를 발생시키지 않고 런타임 에러를 발생시킨다.

14.2: ECMAScript 2015에서 토큰 let 으로 시작하고 그 뒤에 입력 요소 LineTerminatorIdentifier 가 따라오는 StatementListLexicalDeclaration 시작이다. 이전 판에서는 자동 세미콜론 삽입이 항상 Identifier 입력 요소 앞에 세미콜론 삽입.

14.5: ECMAScript 2015에서 토큰 let 으로 시작하고 토큰 [ 가 뒤따르는 StatementListItemLexicalDeclaration 시작이다. 이전 판에서는 그러한 시퀀스가 ExpressionStatement 시작이었다.

14.6.2: ECMAScript 2015에서 IfStatement 의 정상 결과는 결코 empty 값이 아니다. 어떤 Statement 부분도 평가되지 않거나 평가된 Statement 부분이 empty 를 포함하는 정상 완료를 생성하면 결과는 undefined.

14.7: ECMAScript 2015에서 for 문 ( 토큰 바로 뒤에 토큰 시퀀스 let [ 가 오면 letLexicalDeclaration 시작으로 처리된다. 이전 판에서는 그 시퀀스가 Expression 시작.

14.7: ECMAScript 2015에서 for-in 문 ( 토큰 바로 뒤에 토큰 시퀀스 let [ 가 오면 letForDeclaration 시작으로 처리된다. 이전 판에서는 그 시퀀스가 LeftHandSideExpression 시작.

14.7: ECMAScript 2015 이전에는 초기화 식이 in 키워드 앞 VariableDeclaration 일부로 나타날 수 있었다. ECMAScript 2015에서 동일 위치의 ForBinding 은 그러한 초기화자의 출현을 허용하지 않는다. ECMAScript 2017에서 그러한 초기화자는 비엄격 코드에서만 허용.

14.7: ECMAScript 2015에서 IterationStatement 평가 결과는 결코 [[Value]]empty 인 정상 완료가 아니다. Statement 부분이 평가되지 않았거나 최종 평가가 [[Value]] empty 인 정상 완료를 생성하면 결과 [[Value]]undefined 인 정상 완료.

14.11.2: ECMAScript 2015에서 WithStatement 평가 결과는 결코 [[Value]]empty 인 정상 완료가 아니다. Statement 부분 평가가 [[Value]] empty 인 정상 완료를 생성하면 결과 [[Value]]undefined.

14.12.4: ECMAScript 2015에서 SwitchStatement 평가 결과는 결코 [[Value]]empty 인 정상 완료가 아니다. CaseBlock 부분 평가가 [[Value]] empty 인 정상 완료를 생성하면 결과 [[Value]]undefined.

14.15: ECMAScript 2015에서 Catch 절이 매개변수와 동일한 Identifier 에 대해 var 선언을 포함하면 초기 에러이다. 이전 판에서는 그러한 변수 선언이 둘러싼 변수 환경에서 인스턴스화되지만 선언의 Initializer 값이 Catch 매개변수에 할당되었다.

14.15, 19.2.1.3: ECMAScript 2015에서 Catch 절이 동일한 Identifier 를 바인딩하는 var 또는 FunctionDeclaration 을 포함하는 비엄격 direct eval 을 평가하면 런타임 SyntaxError 가 던져진다.

14.15.3: ECMAScript 2015에서 TryStatement 결과는 결코 empty 값이 아니다. Block 부분이 empty 를 포함하는 정상 완료로 평가되면 결과는 undefined. Block 부분이 throw 완료로 평가되고 Catch 부분이 empty 정상 완료를 평가하면 Finally 가 없거나 Finallyempty 정상 완료로 평가되는 경우 결과는 undefined.

15.4.5: ECMAScript 2015에서 ObjectLiteral접근자 프로퍼티 [[Get]] 또는 [[Set]] 속성 값으로 생성된 함수 객체생성자 함수가 아니며 "prototype" own 프로퍼티를 갖지 않는다. 이전 판에서는 생성자이며 "prototype" 프로퍼티가 있었다.

20.1.2.6: ECMAScript 2015에서 Object.freeze 인수가 객체가 아니면 자체 프로퍼티가 없는 비확장 ordinary 객체처럼 취급된다. 이전 판에서는 비객체 인수는 항상 TypeError 발생.

20.1.2.8: ECMAScript 2015에서 Object.getOwnPropertyDescriptor 인수가 객체가 아니면 ToObject 사용 강제를 시도한다. 성공 시 결과가 원래 인수 대신 사용. 이전 판에서는 비객체 인수가 항상 TypeError.

20.1.2.10: ECMAScript 2015에서 Object.getOwnPropertyNames 인수가 객체가 아니면 ToObject 강제를 시도. 성공 시 결과 사용. 이전 판에서는 TypeError.

20.1.2.12: ECMAScript 2015에서 Object.getPrototypeOf 인수가 객체가 아니면 ToObject 강제를 시도. 성공하면 결과 사용. 이전 판에서는 TypeError.

20.1.2.16: ECMAScript 2015에서 Object.isExtensible 인수가 객체가 아니면 자체 프로퍼티 없는 비확장 ordinary 객체처럼 취급. 이전 판에서는 TypeError.

20.1.2.17: ECMAScript 2015에서 Object.isFrozen 인수가 객체가 아니면 자체 프로퍼티 없는 비확장 ordinary 객체처럼 취급. 이전 판에서는 TypeError.

20.1.2.18: ECMAScript 2015에서 Object.isSealed 인수가 객체가 아니면 자체 프로퍼티 없는 비확장 ordinary 객체처럼 취급. 이전 판에서는 TypeError.

20.1.2.19: ECMAScript 2015에서 Object.keys 인수가 객체가 아니면 ToObject 강제를 시도. 성공 시 결과 사용. 이전 판에서는 TypeError.

20.1.2.20: ECMAScript 2015에서 Object.preventExtensions 인수가 객체가 아니면 자체 프로퍼티 없는 비확장 ordinary 객체처럼 취급. 이전 판에서는 TypeError.

20.1.2.22: ECMAScript 2015에서 Object.seal 인수가 객체가 아니면 자체 프로퍼티 없는 비확장 ordinary 객체처럼 취급. 이전 판에서는 TypeError.

20.2.3.2: ECMAScript 2015에서 바운드 함수의 [[Prototype]] 내부 슬롯은 대상 함수의 [[GetPrototypeOf]] 값으로 설정된다. 이전 판에서는 항상 %Function.prototype%.

20.2.4.1: ECMAScript 2015에서 함수 인스턴스의 "length" 프로퍼티는 설정 가능(configurable)하다. 이전 판에서는 불가능.

20.5.6.2: ECMAScript 2015에서 NativeError 생성자[[Prototype]] 내부 슬롯은 Error 생성자이다. 이전 판에서는 Function prototype 객체.

21.4.4: ECMAScript 2015에서 Date 프로토타입 객체는 Date 인스턴스가 아니다. 이전 판에서는 TimeValue 가 NaN 인 Date 인스턴스였다.

22.1.3.12: ECMAScript 2015에서 String.prototype.localeCompare 는 Unicode 표준에 따라 정규 동등(canonical equivalence)한 문자열을 동일하게 취급해야 한다. 이전 판에서는 구현이 이를 무시하고 비트 단위 비교 사용 가능.

22.1.3.2822.1.3.30: ECMAScript 2015에서 소문자/대문자 변환 처리는 코드 포인트에 작동한다. 이전 판에서는 개별 코드 유닛에만 적용. 영향받는 코드는 Deseret 블록.

22.1.3.32: ECMAScript 2015에서 String.prototype.trim 은 Unicode BMP 밖에 존재할 수 있는 공백 코드 포인트 인식을 정의. Unicode 7 시점에는 그런 코드 포인트 없음. 이전 판에서는 그런 코드 포인트를 공백으로 인식하지 않았을 것.

22.2.4.1: ECMAScript 2015에서 pattern 인수가 RegExp 인스턴스이고 flags 인수가 undefined 가 아니면 pattern 의 플래그를 flags 로 교체한 새로운 RegExp 인스턴스 생성. 이전 판에서는 pattern 이 RegExp 인스턴스이고 flagsundefined 가 아니면 TypeError.

22.2.6: ECMAScript 2015에서 RegExp 프로토타입 객체는 RegExp 인스턴스가 아니다. 이전 판에서는 패턴이 빈 문자열인 RegExp 인스턴스였다.

22.2.6: ECMAScript 2015에서 "source", "global", "ignoreCase", "multiline"RegExp 프로토타입 객체에 정의된 접근자 프로퍼티이다. 이전 판에서는 RegExp 인스턴스에 정의된 데이터 프로퍼티.

25.4.15: ECMAScript 2019에서 Atomics.wakeAtomics.wait 와의 혼동을 방지하기 위해 Atomics.notify 로 이름 변경.

27.1.6.4, 27.6.3.6: ECMAScript 2019에서 await 가 큐에 넣는 Job 수가 감소하여 then() 호출과 await 표현식 간 해석 순서의 관찰 가능 차이가 생길 수 있음.

참고 문헌 (Bibliography)

  1. IEEE 754-2019: IEEE Standard for Floating-Point Arithmetic. Institute of Electrical and Electronic Engineers, New York (2019) Note

    IEEE 754-2008 과 IEEE 754-2019 사이 ECMA-262 명세에 영향을 주는 규범적 변경은 없다.

  2. The Unicode Standard, <https://unicode.org/versions/latest> 에서 이용 가능
  3. Unicode Technical Note #5: Canonical Equivalence in Applications, <https://unicode.org/notes/tn5/> 에서 이용 가능
  4. Unicode Technical Standard #10: Unicode Collation Algorithm, <https://unicode.org/reports/tr10/> 에서 이용 가능
  5. Unicode Standard Annex #15, Unicode Normalization Forms, <https://unicode.org/reports/tr15/> 에서 이용 가능
  6. Unicode Standard Annex #18: Unicode Regular Expressions, <https://unicode.org/reports/tr18/> 에서 이용 가능
  7. Unicode Standard Annex #24: Unicode Script Property, <https://unicode.org/reports/tr24/> 에서 이용 가능
  8. Unicode Standard Annex #31, Unicode Identifiers and Pattern Syntax, <https://unicode.org/reports/tr31/> 에서 이용 가능
  9. Unicode Standard Annex #44: Unicode Character Database, <https://unicode.org/reports/tr44/> 에서 이용 가능
  10. Unicode Technical Standard #51: Unicode Emoji, <https://unicode.org/reports/tr51/> 에서 이용 가능
  11. IANA Time Zone Database, <https://www.iana.org/time-zones> 에서 이용 가능
  12. ISO 8601:2004(E) Data elements and interchange formats — Information interchange — Representation of dates and times
  13. RFC 1738 “Uniform Resource Locators (URL)”, <https://tools.ietf.org/html/rfc1738>
  14. RFC 2396 “Uniform Resource Identifiers (URI): Generic Syntax”, <https://tools.ietf.org/html/rfc2396>
  15. RFC 3629 “UTF-8, a transformation format of ISO 10646”, <https://tools.ietf.org/html/rfc3629>
  16. RFC 7231 “Hypertext Transfer Protocol (HTTP/1.1): Semantics and Content”, <https://tools.ietf.org/html/rfc7231>

콜로폰 (Colophon)

이 명세는 GitHub 에서 Ecmarkup 라는 플레인텍스트 소스 포맷으로 작성된다. Ecmarkup 은 HTML 과 Markdown 방언으로, 플레인텍스트로 Ecma 명세를 작성하고 이를 본 문서의 편집 관례를 따르는 기능 완비 HTML 렌더링으로 처리하기 위한 프레임워크 및 도구 세트를 제공한다. Ecmarkup 은 구문 정의를 위한 Grammarkdown, 알고리즘 단계를 작성하기 위한 Ecmarkdown 등 여러 형식과 기술을 통합한다. 이 명세의 PDF 렌더링은 CSS Paged Media 명세를 활용하는 인쇄 스타일시트를 사용하여 생성되며 PrinceXML 을 사용해 변환된다.

이전 판은 Word 를 사용해 작성되었으며—이 판의 기반이 된 Ecmarkup 소스 텍스트는 ECMAScript 2015 Word 문서를 자동 변환 도구로 Ecmarkup 으로 변환하여 생성되었다.

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.