Draft ECMA-262 / May 16, 2026

ECMAScript® 2027 Language Specification

이 명세서에 대하여

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

이 문서는 단일 페이지다중 페이지 형식으로 제공됩니다.

이 명세서에 기여하기

이 명세서는 ECMAScript 커뮤니티의 도움으로 GitHub에서 개발됩니다. 해당 명세서 개발에 기여할 수 있는 여러 방법이 있습니다:

이 문서가 어떻게 생성되는지에 관한 추가 정보는 colophon을 참고하세요.

소개

이 Ecma 표준은 ECMAScript 2027 언어를 정의합니다. 이것은 ECMAScript 언어 명세의 열여덟 번째 판입니다. ECMAScript는 여러 기원 기술을 바탕으로 하였으며, 가장 잘 알려진 것은 JavaScript(넷스케이프)와 JScript(마이크로소프트) 입니다. 이 언어는 Brendan Eich가 넷스케이프에서 만들었으며, 넷스케이프의 Navigator 2.0 브라우저에 처음 나타났습니다. 웹 브라우저에 포함된 언어로 가장 널리 알려져 있지만, 브라우저 이외 서버 및 내장 응용프로그램 분야에서도 많이 사용되어, 세계에서 가장 널리 쓰이는 범용 프로그래밍 언어 중 하나로 성장했습니다.

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

해당 Ecma 표준은 패스트 트랙 절차를 거쳐 ISO/IEC JTC 1에 제출되었고, 1998년 4월 국제 표준 ISO/IEC 16262로 승인되었습니다. 1998년 6월 Ecma 총회에서 두 번째 ECMA-262 판이 ISO/IEC 16262와 완전히 일치하도록 승인되었습니다. 1판과 2판 사이의 변화는 편집적 차이입니다.

세 번째 판은 강력한 정규 표현식, 더 좋은 문자열 처리, 새로운 제어문, try/catch 예외 처리, 엄격한 오류 정의, 숫자 출력 포맷, 미래 언어 확장을 위한 소규모 변경 사항을 도입했습니다. ECMAScript 표준의 세 번째 판은 1999년 12월 Ecma 총회에서 채택되었으며, 2002년 6월 ISO/IEC 16262:2002로 발행되었습니다.

세 번째 판 이후 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 사용을 개선하는 것이었습니다. 주요 확장은 모듈, 클래스 선언, 렉시컬 블록 스코프, 이터레이터와 제너레이터, 비동기 프로그래밍용 프로미스, 구조 분해 패턴, 꼬리 호출 최적화 등입니다. 내장 ECMAScript 라이브러리는 맵/셋/이진 수 배열 등 데이터 추상화, 문자열과 정규 표현식용 추가 유니코드 지원 등으로 확장되었습니다. 내장 객체는 서브클래싱을 통한 확장이 가능해졌습니다. 여섯 번째 판은 지속적, 점진적 언어와 라이브러리 확장 기반을 마련합니다. 여섯 번째 판은 2015년 6월 총회에서 채택되었습니다.

ECMAScript 2016은 Ecma TC39가 연간 릴리스와 오픈 개발 프로세스를 도입한 첫 ECMAScript 판입니다. ECMAScript 2015 원본에서 일반 텍스트 문서를 만들어 GitHub에서만 개발이 진행되었습니다. 표준 개발 1년 동안 수백 건의 풀 리퀘스트와 이슈가 제출되었고 수천 건의 버그, 편집상의 수정 등 다양한 개선이 이루어졌습니다. 또한 Ecmarkup, Ecmarkdown, Grammarkdown 등 수많은 소프트웨어 도구도 개발 지원에 사용되었습니다. ES2016에는 새 지수 연산자와 Array.prototypeincludes 메서드 지원이 포함됐습니다.

ECMAScript 2017은 Async 함수, Shared Memory, Atomics와 더불어 여러 소규모 언어/라이브러리 개선, 버그 수정, 편집 갱신을 도입했습니다. Async 함수는 promise 반환 함수 구문을 제공해 비동기 프로그래밍 경험을 개선했고, Shared Memory와 Atomics는 병렬 CPU 상에서도 확정적 실행 순서를 보장하는 원자적 연산을 통한 멀티 에이전트 프로그램 통신 방식을 도입했습니다. 또한 Object.values, Object.entries, Object.getOwnPropertyDescriptors 등 새 Object 정적 메서드를 포함시켰습니다.

ECMAScript 2018은 async 이터레이터 프로토콜 및 async 제너레이터를 통한 비동기 반복 지원을 도입했습니다. 또한 정규 표현식 dotAll 플래그, 명명된 캡처 그룹, 유니코드 속성 이스케이프, 후방 탐색 어설션 등 4가지 신규 기능과 객체 잔여/전개 속성도 추가했습니다.

ECMAScript 2019는 배열 평탄화를 위한 Array.prototype.flatflatMap, Object.entries 반환값을 객체로 변환하는 Object.fromEntries, 널리 구현됐으나 비표준이었던 String.prototype.trimLefttrimRight의 더 나은 명칭인 trimStart, trimEnd를 도입했습니다. 또한 몇 가지 구문, 의미적 소규모 수정을 포함하고 있는데, 동적 catch 바인딩 매개변수, JSON 정합을 위한 문자열 리터럴의 U+2028/U+2029 허용 등이 있습니다. 또 Array.prototype.sort를 안정 정렬로 강제, JSON.stringify의 모든 입력에 대해 올바른 UTF-8 반환, Function.prototype.toString이 원본 소스 혹은 표준 자리 표시자를 반환하도록 명확화했습니다.

ECMAScript 2020, 11판은 문자열의 모든 일치 객체 이터레이터를 생성하는 matchAll 메서드, 동적 지정자로 모듈을 비동기 임포트하는 import(), 임의 정밀도 정수형인 BigInt, 단락없는 Promise.allSettled, 전역 this 접근용 globalThis, 모듈내 export * as ns from 'module' 구문, for-in 열거 순서 표준화, 모듈 컨텍스트용 import.meta, “nullish” 값 처리를 개선한 nullish 병합 및 옵셔널 체이닝 구문을 도입했습니다.

ECMAScript 2021, 12판은 문자열의 replaceAll, input 값이 만족되면 단락하는 Promise.any, 여러 오류를 한 번에 표현하는 AggregateError, 논리 대입 연산자(??=, &&=, ||=), 객체를 참조하나 가비지 컬렉션을 막지 않는 WeakRef, 대상 객체의 정리 작업 관리를 위한 FinalizationRegistry, 숫자 구분 기호(1_000), 그리고 구현 정의 정렬량을 줄인 배열 정렬을 도입했습니다.

ECMAScript 2022, 13판은 모듈 최상위 await, 클래스 내 공개/비공개 인스턴스 필드, 공개/비공개 정적 필드, 비공개 인스턴스 메서드와 접근자, 비공개 정적 메서드와 접근자, 정적 블록, 객체의 비공개 필드 존재 확인(#x in obj), /d 플래그로 정규식 매칭 인덱스 제공, 에러의 cause 속성, 문자열/배열/TypedArray의 상대 인덱싱용 at 메서드, Object.hasOwn을 도입했습니다.

ECMAScript 2023, 14판은 Array.prototype, TypedArray.prototypetoSorted, toReversed, with, findLast, findLastIndexArray.prototype.toSpliced를 추가하고, 파일 앞부분 #! 주석 지원, 약한 콜렉션에서 대부분의 Symbol을 키로 허용하도록 했습니다.

ECMAScript 2024, 15판은 ArrayBuffer와 SharedArrayBuffer의 리사이즈/전송 기능, 문자열 집합 작업을 위한 새로운 /v 정규식 플래그, Promise 생성을 위한 편의 메서드 Promise.withResolvers, 데이터 집계용 Object.groupBy, Map.groupBy, 공유 메모리 변동 비동기 대기 Atomics.waitAsync, 문자열의 정상 유니코드 확인/보장용 String.prototype.isWellFormed, toWellFormed를 도입했습니다.

ECMAScript 2025, 16판은 이터레이터 연산용 새 글로벌 Iterator와 관련 메서드, Set 연산용 Set.prototype 메서드, JSON 모듈 임포트 지원, 가져온 모듈의 속성 선언, 정규식 안전 이스케이프용 RegExp.escape 메서드, 정규식 내 인라인 플래그 설정/해제, 항상 Promise로 결과를 보장하는 Promise.try, 새 TypedArray 종류인 Float16Array 및 관련 DataView.prototype.getFloat16, setFloat16, Math.f16round를 도입했습니다.

ECMAScript 2026, 17판은 다양한 크기의 숫자 합산 정밀 손실 최소화를 위한 Math.sumPrecise, 이터레이터 연결 Iterator.concat, 비동기 반복원/소스에서 배열을 만드는 Array.fromAsync, 오류 객체 식별용 Error.isError, Map.prototype, WeakMap.prototype의 조회 시 기본값 제공, Uint8Array의 16진수·base64 인코딩 변환, JSON.parse reviver에서 소스 세그먼트 접근 가능, 원시값의 JSON.stringify 결과 조절용 JSON.rawJSON 등을 도입했습니다.

많은 조직을 대표하는 수십 명이 Ecma TC39 표준의 이 판과 이전 판 개발에 중요한 기여를 했습니다. 활발한 커뮤니티도 TC39 ECMAScript 활동을 뒷받침합니다. 이 커뮤니티는 여러 초안을 검토하고, 수천 건 버그를 보고하고, 구현 실험, 테스트스위트 기여, 전세계 개발자에게 ECMAScript 교육을 해왔습니다. 모든 기여자와 단체를 하나하나 밝히고 인정하는 것은 현실적으로 어렵습니다.

Allen Wirfs-Brock
ECMA-262, 프로젝트 에디터, 6판

Brian Terlson
ECMA-262, 프로젝트 에디터, 7판~10판

Jordan Harband
ECMA-262, 프로젝트 에디터, 10판~12판

Kevin Gibbons
ECMA-262, 프로젝트 에디터, 12판~17판

Shu-yu Guo
ECMA-262, 프로젝트 에디터, 12판~18판

Michael Ficarra
ECMA-262, 프로젝트 에디터, 12판~18판

Richard Gibson
ECMA-262, 프로젝트 에디터, 18판

Ron Buckton
ECMA-262, 프로젝트 에디터, 18판

Nicolò Ribaudo
ECMA-262, 프로젝트 에디터, 18판

Linus Groh
ECMA-262, 프로젝트 에디터, 18판

1 범위

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

2 적합성

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

ECMAScript의 적합한 구현은 최신 버전의 Unicode 표준 및 ISO/IEC 10646에 부합하도록 소스 텍스트 입력을 해석해야 한다.

서로 다른 인간 언어와 국가에서 사용되는 언어적·문화적 관례에 프로그램이 적응할 필요를 지원하는 애플리케이션 프로그래밍 인터페이스(API)를 제공하는 ECMAScript의 적합한 구현은, 이 명세서와 호환되는 최신판 ECMA-402에서 정의한 인터페이스를 구현해야 한다.

ECMAScript의 적합한 구현은 이 명세서에 설명된 것 외의 추가적인 타입, 값, 객체, 프로퍼티 및 함수를 제공할 수 있다. 특히 ECMAScript의 적합한 구현은 이 명세서에 설명된 객체에 대해, 이 명세서에 설명되지 않은 프로퍼티와 그 프로퍼티들의 값을 제공할 수 있다.

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

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

ECMAScript의 적합한 구현은 구현 정의, 구현 근사, 또는 호스트 정의가 아닌 어떤 기능도 재정의해서는 안 된다.

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) 및 수정 1:2005, 수정 2:2006, 수정 3:2008, 수정 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 내부에 나타나며, 표시되는 페이지는 사용자 인터페이스 요소와 고정 및 계산된 텍스트와 이미지의 조합이다. 스크립트 코드는 사용자 상호작용에 반응하며, 메인 프로그램이 필요 없다.

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

ECMAScript를 지원하는 각 웹 브라우저와 서버는 자체 호스트 환경을 제공하여 ECMAScript 실행 환경을 완성한다.

4.2 호스트와 구현

ECMAScript를 호스트 환경에 통합하는 데 도움을 주기 위해, 이 명세서는 특정 기능(예: 추상 연산)의 정의를 전부 또는 일부에 대해 이 명세서 외부의 출처에 위임한다. 편집상, 이 명세서는 다음과 같은 종류의 위임을 구분한다.

구현은 부속서 D에 열거된 기능이나 구현 정의 또는 구현 근사로 표시된 기능을 추가로 정의하는 외부 출처이다. 비공식적으로는 특정 웹 브라우저와 같은 구체적 산출물을 구현이라고 부른다.

구현 정의(implementation-defined) 기능은 추가적인 한정 없이 그 정의를 외부 출처에 위임하는 기능이다. 이 명세서는 특정 동작에 대해 어떤 권고도 하지 않으며, 적합한 구현은 이 명세서가 제시한 제약 내에서 자유롭게 어떤 동작이든 선택할 수 있다.

구현 근사(implementation-approximated) 기능은 이상적인 동작을 권고하면서도 그 정의를 외부 출처에 위임하는 기능이다. 적합한 구현은 이 명세서가 제시한 제약 내에서 자유롭게 어떤 동작이든 선택할 수 있지만, 이상적인 동작에 근사하도록 노력하는 것이 권장된다. Math.exp와 같은 일부 수학 연산은 구현 근사이다.

호스트는 부속서 D에 나열된 기능을 추가로 정의하지만, 다른 구현 정의 또는 구현 근사 기능은 추가로 정의하지 않는 외부 출처이다. 비공식적으로는, 호스트는 부속서 D를 통해 이 명세서와 동일한 방식으로 인터페이스하는 모든 구현의 집합, 예를 들어 모든 웹 브라우저의 집합을 가리킨다. 호스트는 종종 WHATWG HTML(https://html.spec.whatwg.org/)과 같은 외부 명세이다. 다시 말해, 호스트 정의 기능은 종종 외부 명세에서 추가로 정의된다.

호스트 훅은 외부 출처에 의해 전부 또는 일부가 정의되는 추상 연산이다. 모든 호스트 훅은 부속서 D에 나열되어야 한다. 호스트 훅은 최소한 다음 요구 사항을 충족해야 한다.

  • 반드시 정상 완료 또는 던지기 완료를 반환해야 한다.

호스트 정의(host-defined) 기능은 추가적인 한정 없이 그 정의를 외부 출처에 위임하며, 부속서 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와 각 요소가 특정 숫자 데이터 표현을 갖는 아홉 가지 서로 다른 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" 프로퍼티 값에 대한 암묵적 참조(객체의 프로토타입이라 불린다)를 가진다. 또한 프로토타입은 자기 자신의 프로토타입에 대한 비-null 암묵적 참조를 가질 수 있고, 이런 식으로 계속 이어질 수 있다. 이를 프로토타입 체인이라고 한다. 객체의 어떤 프로퍼티를 참조할 때, 그 참조는 해당 이름의 프로퍼티를 포함하는 프로토타입 체인의 첫 번째 객체 안의 그 이름의 프로퍼티를 가리킨다. 다시 말해, 먼저 직접 언급된 객체를 검사하여 그런 프로퍼티가 있는지 본다. 그 객체가 그 이름의 프로퍼티를 가지고 있다면 참조는 그 프로퍼티를 가리킨다. 그 객체가 그 이름의 프로퍼티를 가지고 있지 않다면, 다음으로 그 객체의 프로토타입을 검사하며, 이런 방식으로 계속된다.

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

클래스 기반 객체지향 언어에서는 일반적으로 상태는 인스턴스가 가지며, 메서드는 클래스가 가지며, 상속은 구조와 동작에 대해서만 이루어진다. ECMAScript에서는 상태와 메서드를 객체가 가지며, 구조, 동작, 상태가 모두 상속된다.

자신의 프로토타입이 가진 특정 프로퍼티를 직접 포함하지 않는 모든 객체는 그 프로퍼티와 그 값을 공유한다. 그림 1은 이를 보여 준다.

CF는 생성자(이자 객체)이 다. new 표현식을 사용하여 다섯 개의 객체가 생성되었다: cf1, cf2, cf3, cf4, 그리고 cf5. 이들 각각의 객체는 "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 사이에는 암묵적 프로토타입 연결이 없다는 점에 유의하라.

대부분의 클래스 기반 객체 언어와 달리, 프로퍼티는 값 할당을 통해 객체에 동적으로 추가될 수 있다. 즉, 생성자는 생성된 객체의 프로퍼티 전부 또는 일부에 이름을 붙이거나 값을 할당할 필요가 없다. 위 그림에서는 CFp의 프로퍼티에 새 값을 할당함으로써 cf1, cf2, cf3, cf4, 그리고 cf5를 위한 새로운 공유 프로퍼티를 추가할 수 있다.

ECMAScript 객체는 본질적으로 클래스 기반이 아니지만, 생성자 함수, 프로토타입 객체, 메서드의 공통 패턴에 기초한 클래스 유사 추상을 정의하는 것이 종종 편리하다. ECMAScript 내장 객체 자체도 그러한 클래스 유사 패턴을 따른다. ECMAScript 2015부터 ECMAScript 언어는 프로그래머가 내장 객체에서 사용되는 것과 동일한 클래스 유사 추상 패턴을 따르는 객체를 간결하게 정의할 수 있도록 하는 구문적 클래스 정의를 포함한다.

4.3.2 ECMAScript의 엄격 변형

ECMAScript 언어는 일부 사용자가 언어에서 사용 가능한 몇몇 기능의 사용을 제한하고 싶어 할 수 있다는 가능성을 인정한다. 그들은 보안상의 이유, 오류를 유발하기 쉽다고 여기는 기능을 피하기 위해, 더 강화된 오류 검사를 얻기 위해, 또는 그 밖에 스스로 선택한 다른 이유로 그렇게 할 수 있다. 이러한 가능성을 지원하기 위해 ECMAScript는 언어의 엄격 변형을 정의한다. 언어의 엄격 변형은 일반 ECMAScript 언어의 특정 구문 및 의미 기능 일부를 제외하고, 일부 기능의 상세 의미론을 수정한다. 또한 엄격 변형은 비엄격 형태의 언어에서는 오류로 명세되지 않은 상황에서 오류 예외를 던짐으로써 반드시 보고되어야 하는 추가 오류 조건을 명세한다.

ECMAScript의 엄격 변형은 일반적으로 언어의 엄격 모드라고 불린다. ECMAScript의 엄격 모드 선택과 엄격 모드 구문 및 의미론의 사용은 11.2.2에서 설명된 바와 같이 개별 ECMAScript 소스 텍스트 단위 수준에서 명시적으로 이루어진다. 엄격 모드는 구문적 소스 텍스트 단위 수준에서 선택되므로, 엄격 모드는 그러한 소스 텍스트 단위 내에서만 국소적 효과를 가지는 제한만 부과한다. 엄격 모드는 여러 소스 텍스트 단위에 걸쳐 일관되게 작동해야 하는 ECMAScript 의미론의 어떤 측면도 제한하거나 수정하지 않는다. 완전한 ECMAScript 프로그램은 엄격 모드와 비엄격 모드 ECMAScript 소스 텍스트 단위가 혼합되어 구성될 수 있다. 이 경우 엄격 모드는 실제로 엄격 모드 소스 텍스트 단위 안에 정의된 코드를 실행할 때에만 적용된다.

이 명세서에 부합하려면, ECMAScript 구현은 이 명세서가 정의한 완전한 비제한 ECMAScript 언어와 ECMAScript 언어의 엄격 변형을 모두 구현해야 한다. 또한 구현은 비제한 및 엄격 모드 소스 텍스트 단위를 하나의 복합 프로그램으로 결합하는 것을 지원해야 한다.

4.4 용어와 정의

이 문서의 목적상, 다음 용어와 정의를 적용한다.

4.4.1 implementation-approximated

구현 근사 기능은 외부 출처에 의해 전부 또는 일부가 정의되지만, 이 명세서에서 권장되는 이상적 동작을 가진다

4.4.2 implementation-defined

구현 정의 기능은 이 명세서 외부의 출처에 의해 전부 또는 일부가 정의된다

4.4.3 host-defined

implementation-defined와 동일

Note

편집상으로는 절 4.2를 보라.

4.4.4 type

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

4.4.5 primitive value

6에서 정의된 Undefined, Null, Boolean, Number, BigInt, Symbol, 또는 String 타입 중 하나의 구성원

Note

원시 값은 언어 구현의 최하위 수준에서 직접 표현되는 데이터이다.

4.4.6 object

Object 타입의 구성원

Note

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

4.4.7 constructor

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

Note

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

4.4.8 prototype

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

Note

생성자가 객체를 생성할 때, 그 객체는 프로퍼티 참조를 해석하기 위해 생성자의 "prototype" 프로퍼티를 암묵적으로 참조한다. 생성자의 "prototype" 프로퍼티는 프로그램 표현식 constructor.prototype으로 참조할 수 있으며, 객체의 프로토타입에 추가된 프로퍼티는 상속을 통해 그 프로토타입을 공유하는 모든 객체에 공유된다. 또는 Object.create 내장 함수를 사용하여 명시적으로 지정된 프로토타입을 가진 새 객체를 생성할 수도 있다.

4.4.9 ordinary object

모든 객체가 지원해야 하는 필수 내부 메서드에 대해 기본 동작을 가지는 객체

4.4.10 exotic object

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

Note

보통 객체가 아닌 모든 객체는 이색 객체이다.

4.4.11 standard object

그 의미론이 이 명세서에 의해 정의되는 객체

4.4.12 built-in object

ECMAScript 구현에 의해 명세되고 제공되는 객체

Note

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

4.4.13 undefined value

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

4.4.14 Undefined type

유일한 값이 undefined 값인 타입

4.4.15 null value

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

4.4.16 Null type

유일한 값이 null 값인 타입

4.4.17 Boolean value

Boolean 타입의 구성원

Note

Boolean 값은 truefalse 두 개뿐이다.

4.4.18 Boolean type

원시 값 truefalse로 이루어진 타입

4.4.19 Boolean object

표준 내장 Boolean 생성자의 인스턴스인 Object 타입의 구성원

Note

Boolean 객체는 new 표현식에서 Boolean 생성자를 사용하고, 인수로 Boolean 값을 제공하여 생성된다. 생성된 객체는 그 값이 Boolean 값인 내부 슬롯을 가진다. Boolean 객체는 Boolean 값으로 강제 변환될 수 있다.

4.4.20 String value

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

Note

String 값은 String 타입의 구성원이다. 순서열의 각 정수 값은 일반적으로 UTF-16 텍스트의 단일 16비트 단위를 나타낸다. 그러나 ECMAScript는 그 값들이 16비트 부호 없는 정수여야 한다는 점 외에는 어떠한 제한이나 요구 사항도 두지 않는다.

4.4.21 String type

가능한 모든 String 값의 집합

4.4.22 String object

표준 내장 String 생성자의 인스턴스인 Object 타입의 구성원

Note

String 객체는 new 표현식에서 String 생성자를 사용하고, 인수로 String 값을 제공하여 생성된다. 생성된 객체는 그 값이 String 값인 내부 슬롯을 가진다. String 객체는 String 생성자를 함수로 호출하여(22.1.1.1) String 값으로 강제 변환될 수 있다.

4.4.23 Number value

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

Note

Number 값은 Number 타입의 구성원이며 숫자의 직접적인 표현이다.

4.4.24 Number type

NaN(“숫자가 아님”), +∞𝔽(양의 무한대), 그리고 -∞𝔽(음의 무한대)를 포함한 가능한 모든 Number 값의 집합

4.4.25 Number object

표준 내장 Number 생성자의 인스턴스인 Object 타입의 구성원

Note

Number 객체는 new 표현식에서 Number 생성자를 사용하고, 인수로 Number 값을 제공하여 생성된다. 생성된 객체는 그 값이 Number 값인 내부 슬롯을 가진다. Number 객체는 Number 생성자를 함수로 호출하여(21.1.1.1) Number 값으로 강제 변환될 수 있다.

4.4.26 Infinity

양의 무한 Number 값인 Number 값

4.4.27 NaN

IEEE 754-2019 NaN(“숫자가 아님”) 값인 Number 값

4.4.28 BigInt value

임의 정밀도 정수 값에 대응하는 원시 값

4.4.29 BigInt type

가능한 모든 BigInt 값의 집합

4.4.30 BigInt object

표준 내장 BigInt 생성자의 인스턴스인 Object 타입의 구성원

4.4.31 Symbol value

유한 비-String 객체 프로퍼티 키를 나타내는 원시 값

4.4.32 Symbol type

가능한 모든 Symbol 값의 집합

4.4.33 Symbol object

표준 내장 Symbol 생성자의 인스턴스인 Object 타입의 구성원

4.4.34 function

서브루틴으로 호출될 수 있는 Object 타입의 구성원

Note

함수는 자신의 프로퍼티 외에도, 호출될 때 어떻게 동작하는지를 결정하는 실행 가능한 코드와 상태를 포함한다. 함수의 코드는 ECMAScript로 작성될 수도 있고 아닐 수도 있다.

4.4.35 built-in function

함수인 내장 객체

Note

내장 함수의 예로는 parseIntMath.exp가 있다. 호스트나 구현은 이 명세서에 설명되지 않은 추가 내장 함수를 제공할 수 있다.

4.4.36 built-in constructor

생성자인 내장 함수

Note

내장 생성자의 예로는 ObjectFunction이 있다. 호스트나 구현은 이 명세서에 설명되지 않은 추가 내장 생성자를 제공할 수 있다.

4.4.37 property

키(String 값 또는 Symbol 값)와 값을 연관시키는 객체의 일부

Note

프로퍼티의 형태에 따라 그 값은 데이터 값(원시 값, 객체, 또는 함수 객체)으로 직접 표현될 수도 있고, 접근자 함수 쌍을 통해 간접적으로 표현될 수도 있다.

4.4.38 method

프로퍼티의 값인 함수

Note

함수가 객체의 메서드로 호출될 때, 그 객체는 함수의 this 값으로 전달된다.

4.4.39 built-in method

내장 함수인 메서드

Note

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

4.4.40 attribute

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

4.4.41 own property

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

4.4.42 inherited property

자기 자신의 프로퍼티는 아니지만, 객체의 프로토타입의 프로퍼티(자기 자신의 것이든 상속된 것이든)인 객체의 프로퍼티

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 어휘 문법과 RegExp 문법

ECMAScript의 어휘 문법은 절 12에 제시되어 있다. 이 문법의 단말 기호는 11.1에서 정의된 SourceCharacter 규칙에 부합하는 유니코드 코드 포인트이다. 이 문법은 목표 기호 InputElementDiv, InputElementTemplateTail, InputElementRegExp, InputElementRegExpOrTemplateTail, 또는 InputElementHashbangOrRegExp로부터 시작하는 일련의 생성 규칙을 정의하며, 이러한 코드 포인트 시퀀스가 어떻게 입력 요소 시퀀스로 변환되는지를 설명한다.

공백과 주석을 제외한 입력 요소는 ECMAScript 구문 문법의 단말 기호를 이루며 ECMAScript 토큰이라 불린다. 이러한 토큰은 ECMAScript 언어의 예약어, 식별자, 리터럴, 구두점이다. 또한 줄 종료자는 토큰으로 간주되지는 않지만, 입력 요소 스트림의 일부가 되어 자동 세미콜론 삽입 과정(12.10)을 안내한다. 단순 공백과 단일 행 주석은 버려지며 구문 문법을 위한 입력 요소 스트림에 나타나지 않는다. MultiLineComment(/**/` 형태의 주석으로, 한 줄을 넘는지 여부와 관계없음)도 줄 종료자를 포함하지 않으면 마찬가지로 단순히 버려진다. 그러나 |MultiLineComment|가 하나 이상의 줄 종료자를 포함하면, 그것은 단일 줄 종료자로 대체되며, 이는 구문 문법을 위한 입력 요소 스트림의 일부가 된다.

ECMAScript의 RegExp 문법22.2.1에 제시되어 있다. 이 문법 역시 SourceCharacter로 정의되는 코드 포인트를 단말 기호로 가진다. 이 문법은 목표 기호 Pattern로부터 시작하는 생성 규칙 집합을 정의하며, 코드 포인트 시퀀스가 어떻게 정규 표현식 패턴으로 변환되는지를 설명한다.

어휘 문법과 RegExp 문법의 생성 규칙은 구분 구두점으로 콜론 두 개 “::”를 가진다는 점으로 구별된다. 어휘 문법과 RegExp 문법은 일부 생성 규칙을 공유한다.

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)의 단일 인스턴스로, 남는 토큰 없이 파싱될 수 없다면 입력 스트림은 구문 오류이다.

파싱이 성공하면 파스 트리가 구성된다. 이는 각 노드가 파스 노드인 루트가 있는 트리 구조이다. 각 파스 노드는 문법의 기호 하나의 인스턴스이며, 그 기호로부터 유도될 수 있는 소스 텍스트의 범위를 나타낸다. 전체 소스 텍스트를 나타내는 파스 트리의 루트 노드는 파스의 목표 기호의 인스턴스이다. 파스 노드가 비단말의 인스턴스인 경우, 그것은 또한 그 비단말을 왼쪽 항으로 가지는 어떤 생성 규칙의 인스턴스이기도 하다. 또한 그것은 0개 이상의 자식을 가지며, 각 자식은 생성 규칙 오른쪽 항의 각 기호 하나에 대응한다. 각 자식은 대응하는 기호의 인스턴스인 파스 노드이다.

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

Note 1

같은 String을 여러 번 파싱하면 서로 다른 파스 노드가 생성된다. 예를 들어 다음을 보라.

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

eval을 호출할 때마다 str의 값은 ECMAScript 소스 텍스트로 변환되고, 그 자체의 별도 파스 노드 트리를 생성하는 독립적인 파싱이 수행된다. 각 파스가 동일한 String 값으로부터 유도된 소스 텍스트를 대상으로 하더라도, 그 트리들은 서로 구별된다.

Note 2
파스 노드는 명세상의 인공물이며, 구현이 이에 상응하는 자료 구조를 사용할 필요는 없다.

구문 문법의 생성 규칙은 구두점으로 단 하나의 콜론 “:”만 가진다는 점으로 구별된다.

13부터 16까지에 제시된 구문 문법은 어떤 토큰 시퀀스가 올바른 ECMAScript Script 또는 Module로 받아들여지는지에 대한 완전한 설명은 아니다. 특정 위치(예: 줄 종료 문자 앞)에 세미콜론을 추가하기만 하면 문법으로 기술될 수 있는 추가 토큰 시퀀스도 받아들여진다. 또한 문법으로 기술되더라도 특정 “어색한” 위치에 줄 종료 문자가 나타나면 받아들여지지 않는 토큰 시퀀스도 있다.

어떤 경우에는 모호성을 피하기 위해, 구문 문법이 유효한 ECMAScript Script 또는 Module을 형성하지 않는 토큰 시퀀스를 허용하는 일반화된 생성 규칙을 사용한다. 예를 들어 이 기법은 객체 리터럴과 객체 구조 분해 패턴에 사용된다. 그러한 경우 허용 가능한 토큰 시퀀스를 추가로 제한하는 더 엄격한 보충 문법이 제공된다. 일반적으로 조기 오류 규칙은 특정 맥락에서 "p must cover an n"이라고 기술한다. 여기서 p는 파스 노드(일반화된 생성 규칙의 인스턴스)이고 n은 보충 문법의 비단말이다. 이는 다음을 의미한다.

  1. 원래 p와 일치한 토큰 시퀀스를 목표 기호n을 사용하여 다시 파싱한다. n이 문법 매개변수를 가진다면, p가 원래 파싱될 때 사용된 것과 같은 값으로 설정된다.
  2. 그 토큰 시퀀스가 남는 토큰 없이 n의 단일 인스턴스로 파싱될 수 있다면:
    1. n의 인스턴스(주어진 p에 대해 유일한 파스 노드)를 "p에 의해 덮이는 n"이라고 부른다.
    2. n 및 그것으로부터 유도된 생성 규칙에 대한 모든 조기 오류 규칙p에 의해 덮이는 n에도 적용된다.
  3. 그렇지 않으면(파싱이 실패하면), 이는 조기 Syntax Error이다.

5.1.5 문법 표기법

5.1.5.1 단말 기호

ECMAScript 문법에서 일부 단말 기호는 fixed-width 글꼴로 표시된다. 이러한 것은 소스 텍스트에 정확히 적힌 그대로 나타나야 한다. 이 방식으로 명세된 모든 단말 기호 코드 포인트는 다른 유니코드 범위의 유사하게 생긴 코드 포인트가 아니라 Basic Latin 블록의 적절한 유니코드 코드 포인트로 이해되어야 한다. 단말 기호 안의 코드 포인트는 \ UnicodeEscapeSequence로 표현될 수 없다.

단말 기호가 개별 유니코드 코드 포인트인 문법(즉, 어휘, RegExp, 숫자 문자열 문법)에서는, 생성 규칙에 나타나는 여러 개의 고정 폭 코드 포인트의 연속은 그것들을 각각 독립된 단말 기호로 쓴 것과 같은 코드 포인트 시퀀스에 대한 단순한 약식 표기이다.

예를 들어, 생성 규칙

HexIntegerLiteral :: 0x HexDigits

는 다음의 약식이다.

HexIntegerLiteral :: 0 x HexDigits

반대로, 구문 문법에서는 고정 폭 코드 포인트의 연속이 하나의 단말 기호이다.

단말 기호는 두 가지 다른 형태도 가진다.

  • 어휘 및 RegExp 문법에서, 관례적인 인쇄 표현이 없는 유니코드 코드 포인트는 대신 "<ABBREV>" 형식으로 표시되며, 여기서 "ABBREV"는 그 코드 포인트 또는 코드 포인트 집합을 나타내는 기억 보조어이다. 이러한 형태는 유니코드 형식 제어 문자, 공백, 그리고 줄 종결자에서 정의된다.
  • 구문 문법에서, 특정 단말 기호(예: IdentifierNameRegularExpressionLiteral)는 같은 이름의 어휘 문법 비단말을 가리키므로 이탤릭체로 표시된다.

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일 때에만 그 생성 규칙을 사용할 수 있음을 뜻한다. 마찬가지로, set유한하고 비어 있지 않은 토큰 시퀀스 집합일 때 “[lookahead ∈ set]”는 즉시 뒤따르는 토큰 시퀀스의 접두사가 set의 어떤 원소일 때에만 그 생성 규칙을 사용할 수 있음을 뜻한다. 편의를 위해, 그 집합은 비단말로도 쓸 수 있으며, 이 경우 그것은 그 비단말이 확장될 수 있는 모든 토큰 시퀀스의 집합을 나타낸다. 그 비단말이 무한히 많은 서로 다른 토큰 시퀀스로 확장될 수 있다면 이는 편집 오류로 간주된다.

이러한 조건은 부정될 수 있다. “[lookahead ≠ seq]”는 포함하는 생성 규칙이 즉시 뒤따르는 입력 토큰 시퀀스의 접두사가 seq아닐 때에만 사용 가능함을 뜻하고, “[lookahead ∉ set]”는 즉시 뒤따르는 토큰 시퀀스의 접두사가 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 [no LineTerminator here]

구문 문법의 생성 규칙 오른쪽 항에 “[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 :: 임의의 유니코드 코드 포인트

5.2 알고리즘 관례

이 명세서는 종종 알고리즘의 단계를 명세하기 위해 번호가 매겨진 목록을 사용한다. 이러한 알고리즘은 ECMAScript 언어 구성 요소에 요구되는 의미론을 정확하게 명세하기 위해 사용된다. 이 알고리즘들은 특정 구현 기법의 사용을 암시하려는 의도가 아니다. 실제로는 주어진 기능을 구현하기 위해 더 효율적인 알고리즘이 있을 수 있다.

알고리즘은 위치별로 전달된 인수를 참조하기 위해 알고리즘 단계 내에서 사용할 수 있는 별칭 이름의 순서 있는 쉼표 구분 시퀀스로 명시적으로 매개변수화될 수 있다. 선택 매개변수는 대괄호([ , name ])로 표시되며 알고리즘 단계 안에서는 필수 매개변수와 다르지 않다. 가변(rest) 매개변수는 매개변수 목록의 끝에 나타날 수 있으며, 앞에 생략 부호를 붙여 (, ...name) 표기한다. 가변 매개변수는 필수 및 선택 매개변수 뒤에 제공되는 모든 인수를 List로 포착한다. 그러한 추가 인수가 없다면, 그 List는 비어 있다.

알고리즘 단계는 순차적인 하위 단계로 세분될 수 있다. 하위 단계는 들여쓰기되며, 그 자체로도 더 들여쓰기된 하위 단계로 세분될 수 있다. 윤곽 번호 매기기 관례를 사용하여 하위 단계를 식별하며, 첫 번째 수준의 하위 단계는 소문자 알파벳으로, 두 번째 수준의 하위 단계는 소문자 로마 숫자로 표기한다. 세 수준보다 더 많은 수준이 필요하면, 네 번째 수준에서 숫자 레이블을 사용하는 방식으로 이 규칙이 반복된다. 예를 들면 다음과 같다.

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

어떤 단계나 하위 단계는 그 하위 단계들에 조건을 거는 “if” 술어로 작성될 수 있다. 이 경우 그 하위 단계들은 술어가 참일 때에만 적용된다. 어떤 단계나 하위 단계가 “else”라는 단어로 시작하면, 그것은 같은 수준의 바로 앞 “if” 술어 단계의 부정이다.

어떤 단계는 그 하위 단계들의 반복 적용을 명시하기 위해 "For each" 또는 "Repeat"로 시작할 수 있다.

Assert:”로 시작하는 단계는 그 알고리즘의 불변 조건을 주장한다. 이러한 주장은 그렇지 않으면 암묵적일 알고리즘 불변식을 명시적으로 드러내는 데 사용된다. 마찬가지로 “NOTE:”로 시작하는 단계는 인근 단계들에 대한 관련 맥락을 제공한다. Assertion 단계와 note 단계는 엄격히 정보 제공용이며, 추가적인 의미론적 요구 사항을 더하지 않으므로 구현이 이를 검사할 필요는 없다.

알고리즘 단계는 “Let x be someValue” 형식을 사용하여 어떤 값에 대해서도 이름 있는 별칭을 선언할 수 있다. 이러한 별칭은 xsomeValue가 동일한 기저 데이터를 참조하고 어느 한쪽에 대한 수정이 양쪽 모두에 보인다는 점에서 참조와 유사하다. 이러한 참조 유사 동작을 피하고자 하는 알고리즘 단계는 오른쪽 항의 복사본을 명시적으로 만들어야 한다. “Let x be a copy of someValue”는 someValue의 얕은 복사본을 만든다.

한번 선언된 별칭은 이후 어떤 단계에서든 참조될 수 있으며, 그 선언 이전의 단계에서 참조되어서는 안 된다. 별칭은 “Set x to someOtherValue” 형식으로 수정될 수 있다.

5.2.1 평가 순서

복잡한 표현식이 알고리즘 단계에 나타날 때, 그것들은 왼쪽에서 오른쪽으로, 안쪽에서 바깥쪽으로 평가되는 것으로 이해해야 한다. 예를 들어 다음 단계

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

는 다음과 동등하다.

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

여기서 다양한 tmpN 별칭은 일시적이며 이 단계들 안에서만 보인다.

5.2.2 추상 연산

이 명세서의 여러 부분에서 사용하기 쉽게 하기 위해, 추상 연산이라 불리는 일부 알고리즘은 이름이 주어지고 매개변수화된 함수 형태로 작성되어, 다른 알고리즘 안에서 이름으로 참조될 수 있다. 추상 연산은 일반적으로 OperationName(arg1, arg2)와 같은 함수 적용 스타일로 참조된다. 일부 추상 연산은 클래스 유사 명세 추상의 다형적으로 디스패치되는 메서드처럼 취급된다. 이러한 메서드형 추상 연산은 일반적으로 someValue.OperationName(arg1, arg2)와 같은 메서드 적용 스타일로 참조된다.

5.2.3 구문 지시 연산

구문 지시 연산은 정의가 알고리즘들로 이루어진 이름 있는 연산이며, 각 알고리즘은 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 연산은 암묵적으로 다음과 같은 연관을 포함한다.

Runtime Semantics: Evaluation

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

5.2.4 런타임 의미론

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

5.2.4.1 Completion ( completionRecord )

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

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

5.2.4.2 Throw

알고리즘 단계에서 "throw"라는 단어는 ThrowCompletion을 호출한 결과를 반환하는 것의 축약형이다. 예를 들어,

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

는 다음과 동등하다.

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

특정 타입의 예외를 던지라고 말하는 알고리즘 단계는, 던질 그 타입의 예외를 생성한다. 예를 들어,

  1. Throw a TypeError exception.

는 다음과 동등하다.

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

5.2.4.3 Completion Record 언래핑 축약형

접두사 ?!Completion Record를 언래핑하는 축약형으로 사용된다. ?는 급작 완료를 호출자에게 전파하거나, 그렇지 않으면 정상 완료를 언래핑하는 데 사용된다. !Completion Record가 정상임을 단정하고 이를 언래핑하는 데 사용된다. 형식적으로, 다음 단계

  1. Let result be ? record.

는 다음과 동등하다.

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

마찬가지로, 다음 단계

  1. Let result be ! record.

는 다음과 동등하다.

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

? 또는 !가 다른 어떤 맥락에서 사용될 때는, 먼저 평가 순서에 주어진 재작성 규칙을 이 규칙을 적용할 수 있을 때까지 적용한 다음, 이 규칙을 적용한다. 예를 들어 다음 단계

  1. Perform AO(? Other()).

는 다음과 같이 재작성될 수 있다.

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

이는 다시 다음으로 확장된다.

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

5.2.4.4 암묵적 정상 완료

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

? 축약형 확장을 통해, 다음 예시는 허용된다는 점에 유의하라. 확장된 단계들 안에서는 급작 경우에 Completion 적용 결과가 직접 반환되고, 정상 경우에는 언래핑 후 암묵적 NormalCompletion 적용이 일어나기 때문이다.

  1. Return ? completion.

다음 예시는 그 단계에서 표시되지 않은 채 Completion Record가 반환되고 있으므로 편집 오류가 된다.

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

5.2.5 정적 의미론

문맥 자유 문법은 입력 요소 스트림이 평가될 수 있는 유효한 ECMAScript Script 또는 Module을 형성하는지 여부를 정의하는 모든 규칙을 표현하기에 충분히 강력하지 않다. 어떤 상황에서는 ECMAScript 알고리즘 관례나 산문 요구 사항을 사용하여 표현할 수 있는 추가 규칙이 필요하다. 이러한 규칙은 항상 문법의 생성 규칙과 연관되며, 그 생성 규칙의 정적 의미론이라 불린다.

정적 의미론 규칙은 이름을 가지며 일반적으로 알고리즘을 사용하여 정의된다. 이름 있는 정적 의미론 규칙은 문법 생성 규칙과 연관되며, 여러 대안 정의를 가진 생성 규칙은 일반적으로 각 대안마다 적용 가능한 각 이름 있는 정적 의미론 규칙에 대해 서로 다른 알고리즘을 가진다.

정적 의미론 규칙의 특별한 종류는 조기 오류 규칙이다. 조기 오류 규칙은 특정 문법 생성 규칙과 연관된 조기 오류 조건(절 17 참조)을 정의한다. 대부분의 조기 오류 규칙 평가는 이 명세서의 알고리즘 안에서 명시적으로 호출되지 않는다. 적합한 구현은 Script 또는 Module의 첫 번째 평가 전에, 그 Script 또는 Module을 파싱하는 데 사용된 생성 규칙들의 모든 조기 오류 규칙을 검증해야 한다. 어떤 조기 오류 규칙이라도 위반되면, 그 Script 또는 Module은 유효하지 않으며 평가될 수 없다.

5.2.6 수학 연산

이 명세서는 다음과 같은 종류의 숫자 값을 참조한다.

  • 수학적 값: 기본 숫자 타입으로 사용되는 임의의 실수.
  • 확장 수학적 값: 수학적 값에 +∞ 및 -∞를 더한 것.
  • Numbers: IEEE 754-2019 binary64(배정밀도 부동소수점) 값.
  • BigInts: 임의의 정수와 일대일 대응을 이루는 ECMAScript 언어 값.

이 명세서의 언어에서는 숫자 값들이 아래첨자 접미사를 사용하여 서로 다른 숫자 종류 사이에서 구별된다. 아래첨자 𝔽는 Number를, 아래첨자 는 BigInt를 가리킨다. 아래첨자 접미사가 없는 숫자 값은 수학적 값을 가리킨다. 이 명세서는 대부분의 숫자 값을 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 number of code points in …" 또는 "the BigInt value for …"와 같다.

이 명세서에서 정수라는 용어가 사용될 때, 달리 명시되지 않는 한 그것은 정수 집합에 속하는 수학적 값을 가리킨다. 이 명세서에서 정수형 Number라는 용어가 사용될 때, 그것은 그 수학적 값정수 집합에 속하는 유한한 Number 값을 가리킨다.

+, ×, =, ≥와 같은 숫자 연산자는 피연산자의 타입에 의해 결정되는 해당 연산을 가리킨다. 수학적 값에 적용될 때, 연산자는 일반적인 수학 연산을 가리킨다. 확장 수학적 값에 적용될 때, 연산자는 확장 실수에 대한 일반적인 수학 연산을 가리킨다. 부정형은 정의되지 않으며, 이 명세서에서 그것을 사용하는 것은 편집 오류로 간주되어야 한다. Number에 적용될 때, 연산자는 IEEE 754-2019 내의 შესაბამის 연산을 가리킨다. BigInt에 적용될 때, 연산자는 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이다. 유한하지 않은 값의 수학적 값은 정의되지 않는다. xextended mathematical value of유한한 값들에 대해서는 x수학적 값이며, +∞𝔽-∞𝔽에 대해서는 각각 +∞와 -∞이다. NaN에 대해서는 정의되지 않는다.

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

수학 함수 ln(x)x의 자연 로그를 생성한다. 수학 함수 log10(x)x의 밑 10 로그를 생성한다. 수학 함수 log2(x)x의 밑 2 로그를 생성한다.

수학 함수 min(x1, x2, … , xN)x1부터 xN까지 중 수학적으로 가장 작은 값을 생성한다. 수학 함수 max(x1, x2, ..., xN)x1부터 xN까지 중 수학적으로 가장 큰 값을 생성한다. 이 수학 함수들의 정의역과 공역은 확장 수학적 값이다.

표기 “x modulo y”(y유한하고 0이 아니어야 함)는, y와 같은 부호를 가지는(또는 0인) 값 k를 계산하며, 어떤 정수 q에 대해 abs(k) < abs(y) and x - k = q × y를 만족한다.

"the result of clamping x between lower and upper"라는 구(여기서 x확장 수학적 값이고 lowerupperlowerupper를 만족하는 수학적 값이다)는, x < lower이면 lower를 생성하고, x > upper이면 upper를 생성하며, 그렇지 않으면 x를 생성한다.

수학 함수 floor(x)x보다 크지 않은 가장 큰 정수(+∞에 가장 가까운)를 생성한다.

Note

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

수학 함수 truncate(x)는 0 쪽으로 반올림하여 x의 소수 부분을 제거하며, x < 0이면 -floor(-x)를 생성하고 그렇지 않으면 floor(x)를 생성한다.

수학 함수 min, max, abs, floor, truncate는 Number와 BigInt에 대해 정의되지 않으며, 수학적 값이 아닌 인수를 가진 그러한 메서드 사용은 이 명세서에서 편집 오류가 된다.

하한 a에서 상한 b까지의 구간은 동일한 숫자 타입의 숫자 값들로 이루어진, 무한할 수도 있고 비어 있을 수도 있는 집합이다. 각 경계는 포함 또는 배제 중 하나로 기술되며, 둘 다로 기술되지는 않는다. 구간에는 다음 네 가지 종류가 있다.

  • a(포함)에서 b(포함)까지의 구간a에서 b까지의 포함 구간이라고도 하며, 동일한 숫자 타입의 모든 값 xaxb를 만족하는 것만 포함한다.
  • a(포함)에서 b(배제)까지의 구간은 동일한 숫자 타입의 모든 값 xax < b를 만족하는 것만 포함한다.
  • a(배제)에서 b(포함)까지의 구간은 동일한 숫자 타입의 모든 값 xa < xb를 만족하는 것만 포함한다.
  • a(배제)에서 b(배제)까지의 구간은 동일한 숫자 타입의 모든 값 xa < x < b를 만족하는 것만 포함한다.

예를 들어, 1(포함)에서 2(배제)까지의 구간은 1과 2 사이의 모든 수학적 값을 포함하며, 1은 포함하고 2는 포함하지 않는다. 구간을 정의하는 목적상, -0𝔽 < +0𝔽 이므로, 예를 들어 하한이 +0𝔽포함 구간+0𝔽는 포함하지만 -0𝔽는 포함하지 않는다. NaN은 어떤 구간에도 결코 포함되지 않는다.

5.2.7 값 표기

이 명세서에서 ECMAScript 언어 값은 굵게 표시된다. 예로는 null, true, 또는 "hello"가 있다. 이는 Function.prototype.apply 또는 let n = 42;와 같은 ECMAScript 소스 텍스트와 구별된다.

5.2.8 동일성

이 명세서에서 명세 값과 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 소스 텍스트, 서로게이트 쌍, Directive Prologue 등, UTF-16 코드 단위, 유니코드 코드 포인트, enum, 구문 지시 연산, 호스트 훅 등을 포함한 추상 연산, 그리고 순서쌍. 명세 동일성이 있는 값의 예에는 다음이 포함되며 이에 국한되지 않는다: Property Descriptor, PrivateElement 등을 포함한 모든 종류의 Record, Parse Node, List, SetRelation, Abstract Closure, Data Block, Private Name, 실행 컨텍스트 및 실행 컨텍스트 스택, 에이전트 식별자, WaiterList Record.

명세 동일성은 Symbol.for에 의해 생성된 Symbol 값을 제외한 모든 ECMAScript 언어 값에 대해 언어 동일성과 일치한다. 명세 동일성도 언어 동일성도 없는 ECMAScript 언어 값은 undefined, null, Boolean, String, Number, 그리고 BigInt이다. 명세 동일성과 언어 동일성을 모두 가지는 ECMAScript 언어 값은 SymbolSymbol.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 타입은 최대 길이 253 - 1 요소까지의, 0개 이상의 16비트 부호 없는 정수 값(“요소”)으로 이루어진 모든 순서 있는 시퀀스의 집합이다. String 타입은 일반적으로 실행 중인 ECMAScript 프로그램에서 텍스트 데이터를 나타내는 데 사용되며, 이 경우 String의 각 요소는 UTF-16 코드 유닛 값으로 취급된다. 각 요소는 시퀀스 안에서 하나의 위치를 차지하는 것으로 간주된다. 이러한 위치는 음이 아닌 정수로 인덱싱된다. 첫 번째 요소(존재하는 경우)는 인덱스 0에 있고, 다음 요소(존재하는 경우)는 인덱스 1에 있으며, 그 이후도 마찬가지이다. String의 길이는 그 안의 요소(즉, 16비트 값)의 개수이다. 빈 String은 길이가 0이므로 요소를 전혀 포함하지 않는다.

String 내용을 해석하지 않는 ECMAScript 연산은 추가 의미를 적용하지 않는다. String 값을 해석하는 연산은 각 요소를 단일 UTF-16 코드 유닛으로 취급한다. 그러나 ECMAScript는 이 코드 유닛들의 값이나 상호 관계를 제한하지 않으므로, String 내용을 UTF-16으로 인코딩된 유니코드 코드 포인트의 시퀀스로 더 해석하는 연산은 잘못 형성된 부분 시퀀스를 고려해야 한다. 이러한 연산은 숫자 값이 0xD800에서 0xDBFF까지의 포함 구간에 있는 모든 코드 유닛(Unicode 표준에서 leading surrogate 로 정의되며, 더 형식적으로는 high-surrogate code unit 이라고 함)과, 숫자 값이 0xDC00에서 0xDFFF까지의 포함 구간에 있는 모든 코드 유닛(trailing surrogate로 정의되며, 더 형식적으로는 low-surrogate code unit 이라고 함)에 대해 다음 규칙을 사용하여 특별 처리를 적용한다.

String.prototype.normalize 함수(참조 22.1.3.15)는 String 값을 명시적으로 정규화하는 데 사용할 수 있다. String.prototype.localeCompare(참조 22.1.3.12)는 내부적으로 String 값을 정규화하지만, 다른 어떤 연산도 자신이 작동하는 문자열을 암묵적으로 정규화하지 않는다. 달리 명시되지 않는 한, 연산 결과는 언어 및/또는 로캘 민감하지 않다.

Note

이 설계의 근거는 String 구현을 가능한 한 단순하고 고성능으로 유지하는 것이었다. ECMAScript 소스 텍스트가 정규화 형식 C에 있으면, 유니코드 이스케이프 시퀀스를 포함하지 않는 한 문자열 리터럴도 정규화되어 있음이 보장된다.

이 명세에서 "A, B, ...의 string-concatenation "이라는 구(각 인수는 String 값, 코드 유닛, 또는 코드 유닛 시퀀스이다)는 각 인수의 코드 유닛을 (순서대로) 이어 붙인 코드 유닛 시퀀스를 가지는 String 값을 뜻한다.

"inclusiveStart부터 exclusiveEnd까지의 strsubstring"이라는 구(str은 String 값 또는 코드 유닛 시퀀스이고 inclusiveStartexclusiveEnd정수이다)는 인덱스 inclusiveStart에서 시작하여 인덱스 exclusiveEnd 바로 앞에서 끝나는 str의 연속된 코드 유닛으로 이루어진 String 값을 뜻한다 (inclusiveStart = exclusiveEnd이면 빈 String이다). "to" 접미사가 생략되면 str의 길이가 exclusiveEnd 값으로 사용된다.

"ASCII 단어 문자들"이라는 구는 다음 String 값을 뜻하며, 이는 U+005F (LOW LINE)와 함께 Unicode Basic Latin 블록의 모든 문자와 숫자만으로 구성된다:
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_".
역사적인 이유로, 이것은 다양한 알고리즘에서 의미를 가진다.

6.1.4.1 StringIndexOf ( string, searchValue, fromIndex )

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

  1. lenstring의 길이라고 하자.
  2. searchValue가 빈 String이고 fromIndexlen이면, fromIndex를 반환한다.
  3. searchLensearchValue의 길이라고 하자.
  4. fromIndexilen - searchLen을 만족하는 각 정수 i에 대해, 오름차순으로 다음을 수행한다.
    1. candidatestringi부터 i + searchLen까지의 substring이라고 하자.
    2. candidatesearchValue이면, i를 반환한다.
  5. not-found를 반환한다.
Note 1

searchValue가 빈 String이고 fromIndexstring의 길이면, 이 알고리즘은 fromIndex를 반환한다. 빈 String은 마지막 코드 유닛 뒤를 포함하여 문자열의 모든 위치에서 사실상 발견된다.

Note 2

이 알고리즘은 fromIndex + searchValue의 길이 > string의 길이인 경우 항상 not-found를 반환한다.

6.1.4.2 StringLastIndexOf ( string, searchValue, fromIndex )

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

  1. lenstring의 길이라고 하자.
  2. searchLensearchValue의 길이라고 하자.
  3. Assert: fromIndex + searchLenlen.
  4. 0 ≤ ifromIndex를 만족하는 각 정수 i에 대해, 내림차순으로 다음을 수행한다.
    1. candidatestringi부터 i + searchLen까지의 substring이라고 하자.
    2. candidatesearchValue이면, i를 반환한다.
  5. not-found를 반환한다.
Note

searchValue가 빈 String이면, 이 알고리즘은 fromIndex를 반환한다. 빈 String은 마지막 코드 유닛 뒤를 포함하여 문자열의 모든 위치에서 사실상 발견된다.

6.1.5 Symbol 타입

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

각 Symbol은 고유하며 불변이다.

각 Symbol은 값이 String 또는 undefined인 불변의 [[Description]] 내부 슬롯을 가진다.

6.1.5.1 Well-Known Symbols

well-known symbol은 이 명세의 알고리즘에서 명시적으로 참조되는 내장 Symbol 값이다. 이들은 일반적으로 명세 알고리즘의 확장 지점으로 기능하는 값을 가지는 프로퍼티의 키로 사용된다. 달리 명시되지 않는 한, well-known symbol 값은 모든 realm에서 공유된다 (9.3).

이 명세에서 well-known symbol은, intrinsic이 Table 1에 나열된 값 중 하나인 표준 intrinsic 표기법 을 사용하여 참조된다.

Note
이 명세의 이전 판에서는 @@name 형식의 표기법을 사용했으며, 현재 판에서는 %Symbol.name%를 사용한다. 특히 다음 이름들이 사용되었다: @@asyncIterator, @@hasInstance, @@isConcatSpreadable, @@iterator, @@match, @@matchAll, @@replace, @@search, @@species, @@split, @@toPrimitive, @@toStringTag, @@unscopables.
Table 1: Well-known Symbols
명세 이름 [[Description]] 값과 목적
%Symbol.asyncIterator% "Symbol.asyncIterator" 객체의 기본 async iterator를 반환하는 메서드. for-await-of 문의 의미론에 의해 호출된다.
%Symbol.hasInstance% "Symbol.hasInstance" 생성자 객체가 어떤 객체를 해당 생성자의 인스턴스 중 하나로 인식하는지를 결정하는 메서드. instanceof 연산자의 의미론에 의해 호출된다.
%Symbol.isConcatSpreadable% "Symbol.isConcatSpreadable" 값이 참이면 객체가 Array.prototype.concat에 의해 자신의 배열 요소들로 평탄화되어야 함을 나타내는 Boolean 값 프로퍼티.
%Symbol.iterator% "Symbol.iterator" 객체의 기본 iterator를 반환하는 메서드. for-of 문의 의미론에 의해 호출된다.
%Symbol.match% "Symbol.match" 정규 표현식을 문자열에 매치시키는 정규 표현식 메서드. String.prototype.match 메서드에 의해 호출된다.
%Symbol.matchAll% "Symbol.matchAll" 문자열에 대한 정규 표현식의 매치를 산출하는 iterator를 반환하는 정규 표현식 메서드. 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" 열은 반환 타입을 보여 주며, 해당 연산의 일부 호출이 급작 완료를 반환할 가능성이 있는지 여부도 함께 나타낸다.

Table 2: Numeric Type Operations
연산 예시 소스 ...의 Evaluation 의미론에 의해 호출됨 결과
Number::unaryMinus -x 단항 - 연산자 Number
BigInt::unaryMinus BigInt
Number::bitwiseNOT ~x 비트 NOT 연산자 ( ~ ) Number
BigInt::bitwiseNOT BigInt
Number::exponentiate x ** y 거듭제곱 연산자 and Math.pow ( base, exponent ) Number
BigInt::exponentiate BigInt를 포함하는 정상 완료 또는 throw 완료
Number::multiply x * y 곱셈 연산자 Number
BigInt::multiply BigInt
Number::divide x / y 곱셈 연산자 Number
BigInt::divide BigInt를 포함하는 정상 완료 또는 throw 완료
Number::remainder x % y 곱셈 연산자 Number
BigInt::remainder BigInt를 포함하는 정상 완료 또는 throw 완료
Number::add x ++
++ x
x + y
후위 증가 연산자, 전위 증가 연산자, and 덧셈 연산자 ( + ) Number
BigInt::add BigInt
Number::subtract x --
-- x
x - y
후위 감소 연산자, 전위 감소 연산자, and 뺄셈 연산자 ( - ) Number
BigInt::subtract BigInt
Number::leftShift x << y 좌측 시프트 연산자 ( << ) Number
BigInt::leftShift BigInt
Number::signedRightShift x >> y 부호 있는 우측 시프트 연산자 ( >> ) Number
BigInt::signedRightShift BigInt
Number::unsignedRightShift x >>> y 부호 없는 우측 시프트 연산자 ( >>> ) Number
BigInt::unsignedRightShift throw 완료
Number::lessThan x < y
x > y
x <= y
x >= y
관계 연산자, via IsLessThan ( x, y, leftFirst ) Boolean 또는 undefined (순서가 정해지지 않은 입력의 경우)
BigInt::lessThan Boolean
Number::equal x == y
x != y
x === y
x !== y
동등 연산자, via IsStrictlyEqual ( x, y ) Boolean
BigInt::equal
Number::sameValue Object.is(x, y) Object internal methods, via SameValue ( x, y ), to test exact value equality Boolean
Number::sameValueZero [x].includes(y) via SameValueZero ( x, y ), to test value equality, ignoring the difference between +0𝔽 and -0𝔽, as in Array, Map, and Set methods Boolean
Number::bitwiseAND x & y 이항 비트 연산자 Number
BigInt::bitwiseAND BigInt
Number::bitwiseXOR x ^ y Number
BigInt::bitwiseXOR BigInt
Number::bitwiseOR x | y Number
BigInt::bitwiseOR BigInt
Number::toString String(x) Many expressions and built-in functions, via 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 Standard for Binary Floating-Point Arithmetic에 명시된 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 값의 내부 표현과 반드시 동일할 필요는 없다.

또 다른 두 개의 특수 값이 있으며, positive Infinitynegative Infinity라고 부른다. 간결함을 위해 설명 목적상 이 값들은 각각 기호 +∞𝔽-∞𝔽로도 지칭된다. (이 두 개의 무한 Number 값은 프로그램 표현식 +Infinity (또는 단순히 Infinity)와 -Infinity에 의해 생성된다는 점에 유의하라.)

나머지 18,437,736,874,454,810,624개(즉, 264 - 253)의 값은 유한 수라고 불린다. 이들 중 절반은 양수이고 절반은 음수이며, 모든 유한 양의 Number 값마다 같은 크기를 가지는 대응 음의 값이 존재한다.

positive zeronegative zero가 모두 존재한다는 점에 유의하라. 간결함을 위해 설명 목적상 이 값들은 각각 기호 +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 (위에 제시된 두 형식 중 하나에서)이 홀수이면 홀수 유효숫자 (odd significand)를 가진다. 그렇지 않으면 짝수 유효숫자 를 가진다.

이 명세에서 “x에 대한 Number value for ”라는 구는, 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까지의 포함 구간이나, 0에서 216 - 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를 계산한다.

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𝔽이면, +∞𝔽를 반환한다.
    2. +0𝔽를 반환한다.
  5. base-∞𝔽이면,
    1. exponent > +0𝔽이면,
      1. exponent가 홀수 정수 Number이면, -∞𝔽를 반환한다.
      2. +∞𝔽를 반환한다.
    2. exponent가 홀수 정수 Number이면, -0𝔽를 반환한다.
    3. +0𝔽를 반환한다.
  6. base+0𝔽이면,
    1. exponent > +0𝔽이면, +0𝔽를 반환한다.
    2. +∞𝔽를 반환한다.
  7. base-0𝔽이면,
    1. exponent > +0𝔽이면,
      1. exponent가 홀수 정수 Number이면, -0𝔽를 반환한다.
      2. +0𝔽를 반환한다.
    2. exponent가 홀수 정수 Number이면, -∞𝔽를 반환한다.
    3. +∞𝔽를 반환한다.
  8. Assert: base유한하고 +0𝔽-0𝔽도 아니다.
  9. exponent+∞𝔽이면,
    1. abs((base)) > 1이면, +∞𝔽를 반환한다.
    2. abs((base)) = 1이면, NaN을 반환한다.
    3. +0𝔽를 반환한다.
  10. exponent-∞𝔽이면,
    1. abs((base)) > 1이면, +0𝔽를 반환한다.
    2. abs((base)) = 1이면, NaN을 반환한다.
    3. +∞𝔽를 반환한다.
  11. Assert: 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 초판은 이 연산에 대해 NaN 결과를 명시했으나, 이후 IEEE 754 개정은 1𝔽를 명시했다. 역사적인 ECMAScript 동작은 호환성 이유로 보존된다.

6.1.6.1.4 Number::multiply ( x, y )

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

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

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

6.1.6.1.5 Number::divide ( x, y )

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

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

6.1.6.1.6 Number::remainder ( 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. nNaN이거나 dNaN이면, NaN을 반환한다.
  2. n+∞𝔽 또는 -∞𝔽이면, NaN을 반환한다.
  3. d+∞𝔽 또는 -∞𝔽이면, n을 반환한다.
  4. d+0𝔽 또는 -0𝔽이면, NaN을 반환한다.
  5. n+0𝔽 또는 -0𝔽이면, n을 반환한다.
  6. Assert: 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++에서 remainder 연산자는 정수 피연산자만 허용하지만, ECMAScript에서는 부동소수점 피연산자도 허용한다.

Note 2
% 연산자가 계산하는 부동소수점 remainder 연산의 결과는 IEEE 754-2019에서 정의한 “remainder” 연산과 동일하지 않다. IEEE 754-2019 “remainder” 연산은 절단 나눗셈이 아니라 반올림 나눗셈의 나머지를 계산하므로, 그 동작은 일반적인 integer remainder 연산자와 유사하지 않다. 대신 ECMAScript 언어는 부동소수점 연산에서 %가 Java의 integer remainder 연산자와 유사한 방식으로 동작하도록 정의한다. 이는 C 라이브러리 함수 fmod와 비교할 수 있다.

6.1.6.1.7 Number::add ( x, y )

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

  1. xNaN이거나 yNaN이면, NaN을 반환한다.
  2. x+∞𝔽이고 y-∞𝔽이면, NaN을 반환한다.
  3. x-∞𝔽이고 y+∞𝔽이면, NaN을 반환한다.
  4. x+∞𝔽 또는 -∞𝔽이면, x를 반환한다.
  5. y+∞𝔽 또는 -∞𝔽이면, y를 반환한다.
  6. Assert: xy는 모두 유한하다.
  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 - yx + (-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) modulo 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) modulo 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) modulo 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. Assert: xy유한하다.
  11. (x) < (y)이면, true를 반환한다.
  12. false를 반환한다.

6.1.6.1.13 Number::equal ( x, y )

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

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

6.1.6.1.14 Number::sameValue ( x, y )

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

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

6.1.6.1.15 Number::sameValueZero ( x, y )

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

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

6.1.6.1.16 NumberBitwiseOp ( op, x, y )

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

  1. 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에 비트 배타적 OR (XOR) 연산을 적용한 결과라고 하자.
  7. 그렇지 않으면,
    1. Assert: op|이다.
    2. resultlBitsrBits에 비트 포괄적 OR 연산을 적용한 결과라고 하자.
  8. 32비트 2의 보수 비트 문자열 result가 나타내는 정수에 대한 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의 위치 표기 수 체계를 사용하여 String으로 나타낸다. 기수 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)의 string-concatenation을 반환한다.
  4. x+∞𝔽이면, "Infinity"를 반환한다.
  5. n, k, s를 다음을 만족하는 정수라고 하자: k ≥ 1, radixk - 1s < radixk, 𝔽(s × radixn - k)가 x이며, k는 가능한 한 작다. k는 기수 radix를 사용한 s 표현의 자릿수이고, sradix로 나누어떨어지지 않으며, s의 최하위 자릿수는 이 기준들만으로는 반드시 유일하게 결정되지 않는다는 점에 유의하라.
  6. radix ≠ 10이거나 n이 -5부터 21까지의 포함 구간에 있으면,
    1. nk이면,
      1. 다음의 string-concatenation을 반환한다:
        • 기수 radix를 사용한 s 표현의 k개 숫자의 코드 유닛들
        • 코드 유닛 0x0030 (DIGIT ZERO)의 n - k회 반복
    2. n > 0이면,
      1. 다음의 string-concatenation을 반환한다:
        • 기수 radix를 사용한 s 표현의 최상위 n개 숫자의 코드 유닛들
        • 코드 유닛 0x002E (FULL STOP)
        • 기수 radix를 사용한 s 표현의 나머지 k - n개 숫자의 코드 유닛들
    3. Assert: n ≤ 0.
    4. 다음의 string-concatenation을 반환한다:
      • 코드 유닛 0x0030 (DIGIT ZERO)
      • 코드 유닛 0x002E (FULL STOP)
      • 코드 유닛 0x0030 (DIGIT ZERO)의 -n회 반복
      • 기수 radix를 사용한 s 표현의 k개 숫자의 코드 유닛들
  7. NOTE: 이 경우 입력은 1.2e+3과 같은 과학적 E 표기법을 사용하여 표현된다.
  8. Assert: radix는 10이다.
  9. n < 0이면,
    1. exponentSign을 코드 유닛 0x002D (HYPHEN-MINUS)라고 하자.
  10. 그렇지 않으면,
    1. exponentSign을 코드 유닛 0x002B (PLUS SIGN)라고 하자.
  11. k = 1이면,
    1. 다음의 string-concatenation을 반환한다:
      • s의 단일 숫자 코드 유닛
      • 코드 유닛 0x0065 (LATIN SMALL LETTER E)
      • exponentSign
      • abs(n - 1)의 십진 표현 코드 유닛들
  12. 다음의 string-concatenation을 반환한다:
    • s의 십진 표현에서 최상위 숫자의 코드 유닛
    • 코드 유닛 0x002E (FULL STOP)
    • s의 십진 표현에서 나머지 k - 1개 숫자의 코드 유닛들
    • 코드 유닛 0x0065 (LATIN SMALL LETTER E)
    • exponentSign
    • abs(n - 1)의 십진 표현 코드 유닛들
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는 가능한 한 작다. s에 대해 여러 가능성이 있으면, s × radixn - k(x)에 가장 가까워지도록 s를 선택한다. 그런 s 값이 둘이면, 짝수인 쪽을 선택한다. k는 기수 radix를 사용한 s 표현의 자릿수이고 sradix로 나누어떨어지지 않는다는 점에 유의하라.
Note 3

ECMAScript 구현자는 부동소수점 수의 이진-십진 변환을 위해 David M. Gay가 작성한 논문과 코드가 유용할 수 있다.

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

6.1.6.2 BigInt 타입

BigInt 타입정수 값을 나타낸다. 이 값은 어떤 크기든 될 수 있으며 특정 비트폭으로 제한되지 않는다. 일반적으로, 별도로 언급되지 않는 한, 연산은 정확한 수학적 기반의 답을 반환하도록 설계된다. 이항 연산에서 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 예외를 던진다.
  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 예외를 던진다.
  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 예외를 던진다.
  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 예외를 던진다.

6.1.6.2.12 BigInt::lessThan ( x, y )

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

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

6.1.6.2.13 BigInt::equal ( x, y )

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

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

6.1.6.2.14 BinaryAnd ( x, y )

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

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

6.1.6.2.15 BinaryOr ( x, y )

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

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

6.1.6.2.16 BinaryXor ( x, y )

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

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

6.1.6.2.17 BigIntBitwiseOp ( op, x, y )

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

  1. x(x)로 설정한다.
  2. y(y)로 설정한다.
  3. result를 0이라고 하자.
  4. shift를 0이라고 하자.
  5. (x = 0 또는 x = -1) 그리고 (y = 0 또는 y = -1)이 될 때까지, 다음을 반복한다.
    1. xDigitx modulo 2라고 하자.
    2. yDigity modulo 2라고 하자.
    3. op&이면,
      1. resultresult + 2shift × BinaryAnd(xDigit, yDigit)로 설정한다.
    4. 그렇지 않고 op|이면,
      1. resultresult + 2shift × BinaryOr(xDigit, yDigit)로 설정한다.
    5. 그렇지 않으면,
      1. Assert: op^이다.
      2. resultresult + 2shift × BinaryXor(xDigit, yDigit)로 설정한다.
    6. shiftshift + 1로 설정한다.
    7. x를 (x - xDigit) / 2로 설정한다.
    8. y를 (y - yDigit) / 2로 설정한다.
  6. op&이면,
    1. tmpBinaryAnd(x modulo 2, y modulo 2)라고 하자.
  7. 그렇지 않고 op|이면,
    1. tmpBinaryOr(x modulo 2, y modulo 2)라고 하자.
  8. 그렇지 않으면,
    1. Assert: op^이다.
    2. tmpBinaryXor(x modulo 2, y modulo 2)라고 하자.
  9. tmp ≠ 0이면,
    1. resultresult - 2shift로 설정한다.
    2. NOTE: 이것은 부호를 확장한다.
  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의 위치 표기 수 체계를 사용하여 String으로 나타낸다. 기수 r을 사용하는 BigInt 표현에 사용되는 숫자들은 "0123456789abcdefghijklmnopqrstuvwxyz"의 처음 r개 코드 유닛을 순서대로 취한 것이다. 0이 아닌 BigInt의 표현에는 앞쪽 0이 결코 포함되지 않는다. It performs the following steps when called:

  1. x < 0이면, "-"BigInt::toString(-x, radix)의 string-concatenation을 반환한다.
  2. 기수 radix를 사용한 x의 표현으로 이루어진 String 값을 반환한다.

6.1.7 Object 타입

Object 타입의 각 인스턴스, 즉 간단히 “an Object”라고도 불리는 것은 프로퍼티들의 집합을 나타낸다. 각 프로퍼티는 데이터 프로퍼티이거나 접근자 프로퍼티이다.

  • data property는 키 값을 ECMAScript 언어 값 및 Boolean 속성 집합과 연관시킨다.
  • accessor property는 키 값을 하나 또는 두 개의 접근자 함수 및 Boolean 속성 집합과 연관시킨다. 접근자 함수는 해당 프로퍼티와 연관된 ECMAScript 언어 값을 저장하거나 검색하는 데 사용된다.

객체의 프로퍼티는 프로퍼티 키를 사용하여 고유하게 식별된다. property key 는 String 또는 Symbol이다. 빈 String을 포함한 모든 String과 Symbol은 프로퍼티 키로 유효하다. property name은 String인 프로퍼티 키이다.

integer index CanonicalNumericIndexString(n)이 +0𝔽에서 𝔽(253 - 1)까지의 포함 구간에 있는 정수 Number를 반환하는 프로퍼티 이름 n이다. array indexCanonicalNumericIndexString(n)이 +0𝔽에서 𝔽(232 - 2)까지의 포함 구간에 있는 정수 Number를 반환하는 integer index n이다.

Note

모든 음이 아닌 안전 정수는 대응하는 integer index를 가진다. 232 - 1을 제외한 모든 32비트 부호 없는 정수는 대응하는 array index를 가진다. "-0"는 integer index도 array index도 아니다.

프로퍼티 키는 프로퍼티와 그 값을 접근하는 데 사용된다. 프로퍼티 접근에는 두 종류가 있다: getset으로, 각각 값 검색과 값 할당에 대응한다. get 및 set 접근을 통해 접근 가능한 프로퍼티에는, 객체의 직접적인 일부인 own properties와, 프로퍼티 상속 관계를 통해 다른 연관 객체가 제공하는 inherited properties가 모두 포함된다. 상속된 프로퍼티는 그 연관 객체의 own 프로퍼티일 수도 있고 상속된 프로퍼티일 수도 있다. 객체의 각 own 프로퍼티는 반드시 그 객체의 다른 own 프로퍼티의 키 값들과 구별되는 키 값을 가져야 한다.

모든 객체는 논리적으로 프로퍼티들의 집합이지만, 프로퍼티 접근과 조작의 의미론이 서로 다른 여러 형태의 객체가 존재한다. 여러 형태의 객체 정의는 6.1.7.2 를 보라.

또한 일부 객체는 호출 가능하다. 이들은 함수 또는 함수 객체라고 불리며 아래에서 더 설명된다. ECMAScript의 모든 함수는 Object 타입의 구성원이다.

6.1.7.1 프로퍼티 속성

속성은 이 명세에서 Table 3에 설명된 대로 Object 프로퍼티의 상태를 정의하고 설명하는 데 사용된다. 명시적으로 지정되지 않는 한, 각 속성의 초기 값은 그 Default Value이다.

Table 3: Attributes of an Object property
속성 이름 존재하는 프로퍼티 유형 값의 영역 기본값 설명
[[Value]] 데이터 프로퍼티 ECMAScript 언어 값 undefined 프로퍼티에 대한 get 접근 시 검색되는 값.
[[Writable]] 데이터 프로퍼티 Boolean false false이면, ECMAScript 코드가 [[Set]]을 사용하여 해당 프로퍼티의 [[Value]] 속성을 변경하려는 시도는 성공하지 못한다.
[[Get]] 접근자 프로퍼티 Object 또는 undefined undefined 값이 Object인 경우 반드시 함수 객체여야 한다. 그 함수의 [[Call]] 내부 메서드(Table 5)는 프로퍼티에 대한 get 접근이 수행될 때마다 빈 인수 목록으로 호출되어 프로퍼티 값을 검색한다.
[[Set]] 접근자 프로퍼티 Object 또는 undefined undefined 값이 Object인 경우 반드시 함수 객체여야 한다. 그 함수의 [[Call]] 내부 메서드(Table 5)는 프로퍼티에 대한 set 접근이 수행될 때마다 할당된 값을 유일한 인수로 포함하는 인수 목록과 함께 호출된다. 프로퍼티의 [[Set]] 내부 메서드의 효과는 이후 그 프로퍼티의 [[Get]] 내부 메서드 호출이 반환하는 값에 영향을 줄 수도 있지만, 반드시 그래야 하는 것은 아니다.
[[Enumerable]] 데이터 프로퍼티 또는 접근자 프로퍼티 Boolean false true이면, 이 프로퍼티는 for-in 열거에 의해 열거된다 (참조 14.7.5). 그렇지 않으면, 이 프로퍼티는 열거 불가능하다고 한다.
[[Configurable]] 데이터 프로퍼티 또는 접근자 프로퍼티 Boolean false false이면, 해당 프로퍼티를 삭제하거나, 데이터 프로퍼티에서 접근자 프로퍼티로 또는 접근자 프로퍼티에서 데이터 프로퍼티로 바꾸거나, 그 속성들에 어떤 변경이든 가하려는 시도는(기존 [[Value]]를 교체하거나 [[Writable]]false로 설정하는 경우를 제외하고) 실패한다.

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

ECMAScript에서 객체의 실제 의미론은 internal methods라고 불리는 알고리즘을 통해 명세된다. ECMAScript 엔진의 각 객체는 그 객체의 런타임 동작을 정의하는 내부 메서드 집합과 연관된다. 이러한 내부 메서드는 ECMAScript 언어의 일부가 아니다. 이들은 순전히 설명 목적을 위해 이 명세에서 정의된다. 그러나 ECMAScript 구현 내의 각 객체는 자신과 연관된 내부 메서드가 명세한 대로 동작해야 한다. 이를 정확히 어떤 방식으로 달성하는지는 구현이 결정한다.

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

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

모든 객체는 [[PrivateElements]]라는 이름의 내부 슬롯을 가지며, 이는 PrivateElementsList이다. 이 List는 그 객체의 private field, method, accessor의 값을 나타낸다. 초기에는 빈 List이다.

이 명세에서 내부 메서드와 내부 슬롯은 이중 대괄호 [[ ]]로 둘러싼 이름으로 식별된다.

Table 4는 ECMAScript 코드에 의해 생성되거나 조작되는 모든 객체에 적용되는, 이 명세에서 사용하는 essential internal methods를 요약한다. 모든 객체는 모든 essential internal method에 대한 알고리즘을 가져야 한다. 그러나 모든 객체가 반드시 그 메서드들에 대해 동일한 알고리즘을 사용하는 것은 아니다.

ordinary object는 다음 기준을 모두 만족하는 객체이다.

  • Table 4에 나열된 내부 메서드에 대해, 그 객체는 10.1 에 정의된 것을 사용한다.
  • 객체가 [[Call]] 내부 메서드를 가진다면, 10.2.1 에 정의된 것이나 10.3.1 에 정의된 것 중 하나를 사용한다.
  • 객체가 [[Construct]] 내부 메서드를 가진다면, 10.2.2 에 정의된 것이나 10.3.2 에 정의된 것 중 하나를 사용한다.

exotic objectordinary object가 아닌 객체이다.

이 명세는 객체들의 내부 메서드를 기준으로 서로 다른 종류의 exotic object를 인식한다. 특정 종류의 exotic object(예: Array exotic object 또는 bound function exotic object)와 동작적으로 동등하더라도, 그 종류에 대해 명세된 동일한 내부 메서드 집합을 가지고 있지 않다면, 그 객체는 해당 종류의 exotic object로 인식되지 않는다.

Table 4 및 다른 유사 표의 “Signature” 열은 각 내부 메서드의 호출 패턴을 설명한다. 호출 패턴은 항상 설명적인 매개변수 이름의 괄호 친 목록을 포함한다. 매개변수 이름이 ECMAScript 타입 이름과 같다면, 그 이름은 매개변수 값의 요구 타입을 설명한다. 내부 메서드가 명시적으로 값을 반환하는 경우, 그 매개변수 목록 뒤에는 기호 “→”와 반환 값의 타입 이름이 따른다. 시그니처에 사용되는 타입 이름은 절 6에서 정의된 타입을 가리키며, 여기에 다음 추가 이름들이 더해진다. “any”는 값이 어떤 ECMAScript 언어 타입이라도 될 수 있음을 의미한다.

매개변수 외에도, 내부 메서드는 항상 그 메서드 호출의 target인 객체에 접근할 수 있다.

내부 메서드는 암묵적으로 Completion Record를 반환하며, 이는 호출 패턴에 표시된 반환 타입의 값을 감싼 정상 완료이거나 throw 완료이다.

Table 4: Essential Internal Methods
내부 메서드 시그니처 설명
[[GetPrototypeOf]] ( ) Object | Null 이 객체에 상속된 프로퍼티를 제공하는 객체를 결정한다. null 값은 상속된 프로퍼티가 없음을 나타낸다.
[[SetPrototypeOf]] (Object | Null) Boolean 이 객체를 상속된 프로퍼티를 제공하는 다른 객체와 연관시킨다. null을 전달하는 것은 상속된 프로퍼티가 없음을 나타낸다. 연산이 성공적으로 완료되었음을 나타내는 true 또는 성공하지 못했음을 나타내는 false를 반환한다.
[[IsExtensible]] ( ) Boolean 이 객체에 추가 프로퍼티를 더하는 것이 허용되는지를 결정한다.
[[PreventExtensions]] ( ) Boolean 이 객체에 새로운 프로퍼티를 추가할 수 있는지를 제어한다. 연산이 성공하면 true, 실패하면 false를 반환한다.
[[GetOwnProperty]] (propertyKey) Undefined | Property Descriptor 키가 propertyKey인 이 객체의 own 프로퍼티에 대한 Property Descriptor를 반환하거나, 그러한 프로퍼티가 없으면 undefined를 반환한다.
[[DefineOwnProperty]] (propertyKey, propertyDescriptor) Boolean 키가 propertyKey인 own 프로퍼티를 생성하거나 변경하여 propertyDescriptor가 설명하는 상태를 가지게 한다. 그 프로퍼티가 성공적으로 생성/갱신되면 true를 반환하고, 생성 또는 갱신할 수 없으면 false를 반환한다.
[[HasProperty]] (propertyKey) Boolean 이 객체가 이미 키가 propertyKey인 own 또는 상속 프로퍼티를 가지고 있는지를 나타내는 Boolean 값을 반환한다.
[[Get]] (propertyKey, receiver) any 키가 propertyKey인 프로퍼티의 값을 이 객체로부터 반환한다. 프로퍼티 값을 검색하기 위해 ECMAScript 코드를 실행해야 한다면, receiver는 그 코드를 평가할 때 this 값으로 사용된다.
[[Set]] (propertyKey, value, receiver) Boolean 키가 propertyKey인 프로퍼티의 값을 value로 설정한다. 프로퍼티 값을 설정하기 위해 ECMAScript 코드를 실행해야 한다면, receiver는 그 코드를 평가할 때 this 값으로 사용된다. 프로퍼티 값이 설정되면 true, 설정할 수 없으면 false를 반환한다.
[[Delete]] (propertyKey) Boolean 키가 propertyKey인 own 프로퍼티를 이 객체에서 제거한다. 프로퍼티가 삭제되지 않았고 여전히 존재하면 false를 반환한다. 프로퍼티가 삭제되었거나 존재하지 않으면 true를 반환한다.
[[OwnPropertyKeys]] ( ) List of property keys 객체의 모든 own 프로퍼티 키를 요소로 가지는 List를 반환한다.

Table 5 는 함수처럼 호출될 수 있는 객체가 지원하는 추가적인 essential internal methods를 요약한다. function object[[Call]] 내부 메서드를 지원하는 객체이다. constructor[[Construct]] 내부 메서드를 지원하는 객체이다. [[Construct]]를 지원하는 모든 객체는 [[Call]]도 지원해야 한다. 즉, 모든 constructorfunction object여야 한다. 따라서 constructorconstructor function 또는 constructor function object라고도 불릴 수 있다.

Table 5: Additional Essential Internal Methods of Function Objects
내부 메서드 시그니처 설명
[[Call]] (any, a List of any) any 이 객체와 연관된 코드를 실행한다. 함수 호출 표현식을 통해 호출된다. 내부 메서드의 인수는 this 값과, 호출 표현식에 의해 함수에 전달된 인수들을 요소로 가지는 List이다. 이 내부 메서드를 구현하는 객체는 callable하다.
[[Construct]] (a List of any, Object) Object 객체를 생성한다. new 연산자나 super 호출을 통해 호출된다. 내부 메서드의 첫 번째 인수는 constructor 호출 또는 super 호출의 인수들을 요소로 가지는 List이다. 두 번째 인수는 new 연산자가 처음 적용된 객체이다. 이 내부 메서드를 구현하는 객체를 constructors라고 부른다. function object가 반드시 constructor인 것은 아니며, 그런 non-constructor function object[[Construct]] 내부 메서드를 가지지 않는다.

ordinary object 및 표준 exotic object의 essential internal methods의 의미론은 절 10 에 명세되어 있다. exotic object의 내부 메서드에 대한 어떤 명세된 사용이 구현에서 지원되지 않는다면, 그러한 사용이 시도될 때 반드시 TypeError 예외를 던져야 한다.

6.1.7.3 Essential Internal Methods의 불변식

ECMAScript 엔진의 객체 내부 메서드는 아래에 명세된 불변식 목록을 준수해야 한다. ordinary ECMAScript 객체와 이 명세의 모든 표준 exotic object는 이러한 불변식을 유지한다. ECMAScript Proxy 객체는 [[ProxyHandler]] 객체에서 호출된 trap 결과에 대한 런타임 검사를 통해 이러한 불변식을 유지한다.

구현이 제공하는 모든 exotic object 또한 그 객체들에 대해 이러한 불변식을 유지해야 한다. 이러한 불변식의 위반은 ECMAScript 코드가 예측할 수 없는 동작을 하게 하거나 보안 문제를 만들 수 있다. 그러나 이러한 불변식의 위반이 구현의 메모리 안전성을 훼손해서는 결코 안 된다.

구현은 essential internal methods의 기능을 구현하면서 그 불변식을 강제하지 않는 대체 인터페이스를 제공하는 방식 등을 포함하여, 어떤 방법으로든 이러한 불변식이 우회되도록 허용해서는 안 된다.

정의:

  • 내부 메서드의 target은 그 내부 메서드가 호출되는 객체이다.
  • target이 자신의 [[IsExtensible]] 내부 메서드에서 false를 반환하거나, 자신의 [[PreventExtensions]] 내부 메서드에서 true를 반환하는 것이 관찰되었다면, 그 target은 non-extensible이다.
  • non-existent 프로퍼티는 non-extensible target 위에 own 프로퍼티로 존재하지 않는 프로퍼티이다.
  • SameValue에 대한 모든 참조는 SameValue 알고리즘의 정의에 따른다.

반환 값:

어떤 내부 메서드가 반환하는 값은 반드시 다음 중 하나를 가지는 Completion Record여야 한다.

  • [[Type]] = normal, [[Target]] = empty, 그리고 [[Value]] = 아래에 그 내부 메서드의 "normal return type"으로 제시된 타입의 값, 또는
  • [[Type]] = throw, [[Target]] = empty, 그리고 [[Value]] = 임의의 ECMAScript 언어 값.
Note 1

내부 메서드는 continue 완료, break 완료, 또는 return 완료를 반환해서는 안 된다.

[[GetPrototypeOf]] ( )

  • 정상 반환 타입은 Object 또는 Null이다.
  • target이 non-extensible이고 [[GetPrototypeOf]]가 값 proto를 반환했다면, 이후의 모든 [[GetPrototypeOf]] 호출은 protoSameValue인 값을 반환해야 한다.
Note 2

객체의 프로토타입 체인은 유한 길이를 가져야 한다 (즉, 어떤 객체에서 시작해 [[GetPrototypeOf]] 내부 메서드를 그 결과에 재귀적으로 적용하면 결국 null 값에 도달해야 한다). 그러나 이 요구는 프로토타입 체인에 [[GetPrototypeOf]]에 대해 ordinary object 정의를 사용하지 않는 exotic object가 포함되는 경우 객체 수준 불변식으로는 강제할 수 없다. 그러한 순환 프로토타입 체인은 객체 프로퍼티 접근 시 무한 루프를 초래할 수 있다.

[[SetPrototypeOf]] ( proto )

  • 정상 반환 타입은 Boolean이다.
  • target이 non-extensible이면, proto가 target의 관찰된 [[GetPrototypeOf]] 값과 SameValue인 경우를 제외하고 [[SetPrototypeOf]]는 반드시 false를 반환해야 한다.

[[IsExtensible]] ( )

  • 정상 반환 타입은 Boolean이다.
  • [[IsExtensible]]false를 반환하면, 이후 target에 대한 모든 [[IsExtensible]] 호출은 반드시 false를 반환해야 한다.

[[PreventExtensions]] ( )

  • 정상 반환 타입은 Boolean이다.
  • [[PreventExtensions]]true를 반환하면, 이후 target에 대한 모든 [[IsExtensible]] 호출은 반드시 false를 반환해야 하며, target은 이제 non-extensible로 간주된다.

[[GetOwnProperty]] ( propertyKey )

  • 정상 반환 타입은 Property Descriptor 또는 Undefined이다.
  • 반환 값이 Property Descriptor이면, 그것은 완전히 채워진 Property Descriptor여야 한다.
  • propertyKey가 non-configurable이고 non-writable인 own 데이터 프로퍼티로 기술되었다면, 이후의 모든 [[GetOwnProperty]] ( propertyKey ) 호출은 [[Value]]propertyKey[[Value]] 속성과 SameValueProperty Descriptor를 반환해야 한다.
  • propertyKey[[Writable]][[Value]] 이외의 속성이 시간에 따라 변할 수 있거나, 프로퍼티가 삭제될 수 있다면, propertyKey[[Configurable]] 속성은 반드시 true여야 한다.
  • [[Writable]] 속성이 false에서 true로 바뀔 수 있다면, [[Configurable]] 속성은 반드시 true여야 한다.
  • target이 non-extensible이고 propertyKey가 non-existent이면, 이후 target에 대한 모든 [[GetOwnProperty]] (propertyKey) 호출은 propertyKey를 non-existent로 기술해야 한다 (즉, [[GetOwnProperty]] (propertyKey)는 반드시 undefined를 반환해야 한다).
Note 3

세 번째 불변식의 결과로, 어떤 프로퍼티가 데이터 프로퍼티로 기술되었고 시간이 지나며 다른 값을 반환할 수 있다면, 값을 바꾸는 메커니즘이 다른 essential internal methods를 통해 노출되지 않더라도 [[Writable]][[Configurable]] 속성 중 하나 또는 둘 다 반드시 true여야 한다.

[[DefineOwnProperty]] ( propertyKey, desc )

  • 정상 반환 타입은 Boolean이다.
  • [[DefineOwnProperty]]propertyKey가 이전에 target의 non-configurable own 프로퍼티로 관찰된 적이 있다면 반드시 false를 반환해야 한다. 단, 다음 경우는 예외이다.
    1. propertyKey가 writable 데이터 프로퍼티인 경우. non-configurable writable 데이터 프로퍼티는 non-configurable non-writable 데이터 프로퍼티로 변경될 수 있다.
    2. desc의 모든 속성이 propertyKey의 속성과 SameValue인 경우.
  • target이 non-extensible이고 propertyKey가 non-existent own 프로퍼티이면, [[DefineOwnProperty]] (propertyKey, desc)는 반드시 false를 반환해야 한다. 즉, non-extensible target 객체는 새로운 프로퍼티로 확장될 수 없다.

[[HasProperty]] ( propertyKey )

  • 정상 반환 타입은 Boolean이다.
  • propertyKey가 이전에 target의 non-configurable own 데이터 또는 접근자 프로퍼티로 관찰된 적이 있다면, [[HasProperty]]는 반드시 true를 반환해야 한다.

[[Get]] ( propertyKey, receiver )

  • 정상 반환 타입은 임의의 ECMAScript 언어 타입이다.
  • propertyKey가 이전에 값이 value인 target의 non-configurable, non-writable own 데이터 프로퍼티로 관찰된 적이 있다면, [[Get]]은 반드시 valueSameValue인 값을 반환해야 한다.
  • propertyKey가 이전에 [[Get]] 속성이 undefined인 target의 non-configurable own 접근자 프로퍼티로 관찰된 적이 있다면, [[Get]] 연산은 반드시 undefined를 반환해야 한다.

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

  • 정상 반환 타입은 Boolean이다.
  • propertyKey가 이전에 target의 non-configurable, non-writable own 데이터 프로퍼티로 관찰된 적이 있다면, [[Set]]valuepropertyKey[[Value]] 속성과 SameValue인 경우를 제외하고 반드시 false를 반환해야 한다.
  • propertyKey가 이전에 [[Set]] 속성이 undefined인 target의 non-configurable own 접근자 프로퍼티로 관찰된 적이 있다면, [[Set]] 연산은 반드시 false를 반환해야 한다.

[[Delete]] ( propertyKey )

  • 정상 반환 타입은 Boolean이다.
  • propertyKey가 이전에 target의 non-configurable own 데이터 또는 접근자 프로퍼티로 관찰된 적이 있다면, [[Delete]]는 반드시 false를 반환해야 한다.

[[OwnPropertyKeys]] ( )

  • 정상 반환 타입은 List이다.
  • 반환된 List는 중복 항목을 포함해서는 안 된다.
  • 반환된 List의 각 요소는 반드시 property key여야 한다.
  • 반환된 List는 이전에 관찰된 모든 non-configurable own 프로퍼티의 키를 적어도 포함해야 한다.
  • target이 non-extensible이면, 반환된 List[[GetOwnProperty]]를 사용해 관찰 가능한 target의 모든 own 프로퍼티의 키만 포함해야 한다.

[[Call]] ( )

[[Construct]] ( )

  • 정상 반환 타입은 Object이다.
  • target은 또한 [[Call]] 내부 메서드도 가져야 한다.

6.1.7.4 Well-Known Intrinsic Objects

well-known intrinsic은 이 명세의 알고리즘에서 명시적으로 참조되며, 보통 realm별 identity를 가지는 내장 객체들이다. 달리 명시되지 않는 한, 각 intrinsic object는 실제로 realm마다 하나씩 존재하는 유사 객체들의 집합에 대응한다.

이 명세에서 %name%과 같은 참조는 현재 realm과 연관된, 그 이름에 대응하는 intrinsic object를 의미한다. %name.a.b%와 같은 참조는, 마치 intrinsic object %name%의 "a" 프로퍼티 값의 "b" 프로퍼티가 어떤 ECMAScript 코드도 평가되기 전에 접근된 것처럼 의미한다. 현재 realm과 그 intrinsic의 결정은 9.4에 설명되어 있다. well-known intrinsic은 Table 6에 나열되어 있다.

Table 6: Well-Known Intrinsic Objects
Intrinsic 이름 전역 이름 ECMAScript 언어 연관
%AggregateError% AggregateError AggregateError 생성자 (20.5.7.1)
%Array% Array Array 생성자 (23.1.1)
%ArrayBuffer% ArrayBuffer ArrayBuffer 생성자 (25.1.4)
%ArrayIteratorPrototype% Array Iterator 객체들의 prototype (23.1.5)
%AsyncFromSyncIteratorPrototype% Async-from-Sync Iterator 객체들의 prototype (27.1.5)
%AsyncFunction% async function 객체들의 생성자 (27.7.1)
%AsyncGeneratorFunction% async generator function 객체들의 생성자 (27.4.1)
%AsyncGeneratorPrototype% async generator 객체들의 prototype (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 객체들의 prototype (14.7.5.10)
%Function% Function Function 생성자 (20.2.1)
%GeneratorFunction% generator function 객체들의 생성자 (27.3.1)
%GeneratorPrototype% generator 객체들의 prototype (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 객체들의 prototype (27.1.2.1)
%JSON% JSON JSON 객체 (25.5)
%Map% Map Map 생성자 (24.1.1)
%MapIteratorPrototype% Map Iterator 객체들의 prototype (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 객체들의 prototype (22.2.9)
%Set% Set Set 생성자 (24.2.2)
%SetIteratorPrototype% Set Iterator 객체들의 prototype (24.2.6)
%SharedArrayBuffer% SharedArrayBuffer SharedArrayBuffer 생성자 (25.2.3)
%String% String String 생성자 (22.1.1)
%StringIteratorPrototype% String Iterator 객체들의 prototype (22.1.5)
%Symbol% Symbol Symbol 생성자 (20.4.1)
%SyntaxError% SyntaxError SyntaxError 생성자 (20.5.5.4)
%ThrowTypeError% 조건 없이 새로운 %TypeError% 인스턴스를 던지는 함수 객체
%TypedArray% 모든 typed Array 생성자의 상위 클래스 (23.2.1)
%TypeError% TypeError TypeError 생성자 (20.5.5.5)
%Uint8Array% Uint8Array Uint8Array 생성자 (23.2)
%Uint8ClampedArray% Uint8ClampedArray Uint8ClampedArray 생성자 (23.2)
%Uint16Array% Uint16Array Uint16Array 생성자 (23.2)
%Uint32Array% Uint32Array Uint32Array 생성자 (23.2)
%URIError% URIError URIError 생성자 (20.5.5.6)
%WeakMap% WeakMap WeakMap 생성자 (24.3.1)
%WeakRef% WeakRef WeakRef 생성자 (26.1.1)
%WeakSet% WeakSet WeakSet 생성자 (24.4.1)
%WrapForValidIteratorPrototype% Iterator.from이 반환하는 wrapped iterator 객체들의 prototype (27.1.3.2.2.1)
Note

Table 98 에 추가 항목이 있다.

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 서체를 사용한 upper kebab case로 표기된다. 예를 들어, Completion Record[[Type]] 필드는 normal, return, throw 같은 값을 가진다. Enum은 이름 외에 다른 특성을 가지지 않는다. enum의 이름은 다른 enum과 구별하기 위한 목적 외에는 아무 역할도 하지 않으며, 문맥 속 사용법이나 의미에 대해 아무것도 시사하지 않는다.

6.2.2 List와 Record 명세 타입

List 타입은 new 표현식, 함수 호출, 그리고 단순한 순서 있는 값 목록이 필요한 다른 알고리즘에서 인수 목록의 평가(참조 13.3.8)를 설명하는 데 사용된다. List 타입의 값은 개별 값을 포함하는 list 요소들의 순서 있는 시퀀스일 뿐이다. 이러한 시퀀스는 임의의 길이를 가질 수 있다. list의 요소는 0부터 시작하는 인덱스를 사용하여 임의 접근할 수 있다. 표기상 편의를 위해 배열과 유사한 문법을 사용하여 List 요소에 접근할 수 있다. 예를 들어, arguments[2]는 List arguments의 세 번째 요소를 말하는 축약 표현이다.

알고리즘이 List의 요소를 순서를 명시하지 않고 반복할 때, 사용되는 순서는 List 안의 요소 순서이다.

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

이 명세에서 "A, B, ...의 list-concatenation"이라는 구 (각 인수는 비어 있을 수도 있는 List이다)는 각 인수의 요소들을 (순서대로) 이어 붙인 요소들을 가지는 새로운 List 값을 뜻한다.

String들의 List에 적용될 때, " lexicographic code unit order에 따라 정렬됨 "이라는 구는, 더 짧은 문자열의 길이까지 각 코드 유닛의 숫자 값을 기준으로 정렬하고, 모두 같다면 짧은 문자열을 긴 문자열보다 앞에 두는 것을 의미하며, 이는 추상 연산 IsLessThan에 설명되어 있다.

Record 타입은 이 명세의 알고리즘 안에서 데이터 집합을 설명하는 데 사용된다. Record 타입 값은 하나 이상의 이름 붙은 필드로 이루어진다. 각 필드의 값은 ECMAScript 언어 값 또는 명세 값이다. 필드 이름은 항상 이중 대괄호로 둘러싸인다. 예를 들어 [[Value]] 와 같다.

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

명세 텍스트와 알고리즘에서는 점 표기법을 사용하여 Record 값의 특정 필드를 참조할 수 있다. 예를 들어, R이 앞 문단에 표시된 record라면 R.[[Field2]]는 “R의 [[Field2]]라는 이름의 필드”를 말하는 축약 표현이다.

자주 사용되는 Record 필드 조합의 스키마에는 이름이 붙을 수 있으며, 그 이름은 특정 종류의 집합을 식별하기 위해 리터럴 Record 값의 접두사로 사용될 수 있다. 예: PropertyDescriptor { [[Value]]: 42, [[Writable]]: false, [[Configurable]]: true }.

6.2.3 Set과 Relation 명세 타입

Set 타입은 메모리 모델에서 사용할 무순서 요소들의 집합을 설명하는 데 사용된다. 이것은 같은 이름의 ECMAScript 컬렉션 타입과는 구별된다. 혼동을 피하기 위해, ECMAScript 컬렉션의 인스턴스는 이 명세에서 일관되게 "Set objects"라고 부른다. Set 타입의 값은 어떤 요소도 두 번 이상 나타나지 않는 단순한 요소 집합이다. 요소는 Set에 추가되거나 제거될 수 있다. Set은 서로 합집합, 교집합, 차집합을 취할 수 있다.

Relation 타입은 Set에 대한 제약을 설명하는 데 사용된다. Relation 타입의 값은 자신의 값 영역으로부터의 값들의 순서쌍들의 Set이다. 예를 들어, Memory event 위의 Relation은 Memory event 순서쌍들의 집합이다. Relation RR의 값 영역 안의 두 값 a, b에 대해, a R b는 순서쌍 (a, b)가 R의 원소임을 말하는 축약 표현이다. 어떤 조건들에 대한 least Relation은 그 조건들을 만족하는 가장 작은 Relation이다.

strict partial order는 다음을 만족하는 Relation 값 R이다.

  • R의 영역에 있는 모든 a, b, c에 대해:

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

위 두 성질은 각각 irreflexivity와 transitivity라고 불린다.

strict total order는 다음을 만족하는 Relation 값 R이다.

  • R의 영역에 있는 모든 a, b, c에 대해:

    • a is b 또는 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 Fields
필드 이름 의미
[[Type]] normal, break, continue, return, 또는 throw 발생한 완료의 유형.
[[Value]] Completion Record가 아닌 모든 값 생성된 값.
[[Target]] String 또는 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 [[Value]] 필드에 그 타입의 값을 가진 normal completion을 가리킨다.

이 명세에 정의된 callable object는 normal completion 또는 throw completion만 반환한다. 다른 종류의 Completion Record를 반환하는 것은 편집상의 오류로 간주된다.

구현 정의 callable object는 normal completion 또는 throw completion 중 하나를 반환해야 한다.

6.2.4.1 NormalCompletion ( value )

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

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

6.2.4.2 ThrowCompletion ( value )

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

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

6.2.4.3 ReturnCompletion ( value )

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

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

6.2.4.4 UpdateEmpty ( completionRecord, value )

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

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

6.2.5 Reference Record 명세 타입

Reference Record 타입은 delete, typeof, 할당 연산자들, super 키워드 및 다른 언어 기능과 같은 연산자의 동작을 설명하는 데 사용된다. 예를 들어, 할당의 왼쪽 피연산자는 Reference Record를 생성할 것으로 기대된다.

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

Table 8: Reference Record Fields
필드 이름 의미
[[Base]] ECMAScript 언어 값, Environment Record, 또는 unresolvable 바인딩을 보유하는 값 또는 Environment Record. [[Base]]unresolvable이면 바인딩을 해석할 수 없었음을 나타낸다.
[[ReferencedName]] ECMAScript 언어 값 또는 Private Name 바인딩의 이름. [[Base]] 값이 Environment Record인 경우에는 항상 String이다. 그렇지 않으면, ToPropertyKey가 수행될 때까지는 String이나 Symbol이 아닌 ECMAScript 언어 값일 수도 있다.
[[Strict]] Boolean Reference Recordstrict mode 코드에서 유래했으면 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 ( referenceRecord )

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

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

6.2.5.2 IsUnresolvableReference ( referenceRecord )

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

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

6.2.5.3 IsSuperReference ( referenceRecord )

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

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

6.2.5.4 IsPrivateReference ( referenceRecord )

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

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

6.2.5.5 GetValue ( referenceRecord )

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

  1. referenceRecordReference Record가 아니면, referenceRecord를 반환한다.
  2. IsUnresolvableReference(referenceRecord)가 true이면, ReferenceError 예외를 던진다.
  3. IsPropertyReference(referenceRecord)가 true이면,
    1. baseObj를 ? ToObject(referenceRecord.[[Base]])라고 하자.
    2. IsPrivateReference(referenceRecord)가 true이면,
      1. PrivateGet(baseObj, referenceRecord.[[ReferencedName]])를 반환한다.
    3. referenceRecord.[[ReferencedName]]가 property key가 아니면,
      1. referenceRecord.[[ReferencedName]]를 ? ToPropertyKey(referenceRecord.[[ReferencedName]])로 설정한다.
    4. baseObj.[[Get]](referenceRecord.[[ReferencedName]], GetThisValue(referenceRecord))를 반환한다.
  4. basereferenceRecord.[[Base]]라고 하자.
  5. Assert: baseEnvironment Record이다.
  6. base.GetBindingValue(referenceRecord.[[ReferencedName]], referenceRecord.[[Strict]])를 반환한다 (참조 9.1).
Note

단계 3.a에서 생성될 수도 있는 객체는 위 추상 연산ordinary object [[Get]] 내부 메서드 밖에서는 접근할 수 없다. 구현은 그 객체를 실제로 생성하지 않기로 선택할 수도 있다.

6.2.5.6 PutValue ( referenceRecord, value )

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

  1. referenceRecordReference Record가 아니면, ReferenceError 예외를 던진다.
  2. IsUnresolvableReference(referenceRecord)가 true이면,
    1. referenceRecord.[[Strict]]true이면, ReferenceError 예외를 던진다.
    2. globalObjGetGlobalObject()라고 하자.
    3. Set(globalObj, referenceRecord.[[ReferencedName]], value, false)를 수행한다.
    4. unused를 반환한다.
  3. IsPropertyReference(referenceRecord)가 true이면,
    1. baseObj를 ? ToObject(referenceRecord.[[Base]])라고 하자.
    2. IsPrivateReference(referenceRecord)가 true이면,
      1. PrivateSet(baseObj, referenceRecord.[[ReferencedName]], value)를 반환한다.
    3. referenceRecord.[[ReferencedName]]가 property key가 아니면,
      1. referenceRecord.[[ReferencedName]]를 ? ToPropertyKey(referenceRecord.[[ReferencedName]])로 설정한다.
    4. succeeded를 ? baseObj.[[Set]](referenceRecord.[[ReferencedName]], value, GetThisValue(referenceRecord))라고 하자.
    5. succeededfalse이고 referenceRecord.[[Strict]]true이면, TypeError 예외를 던진다.
    6. unused를 반환한다.
  4. basereferenceRecord.[[Base]]라고 하자.
  5. Assert: baseEnvironment Record이다.
  6. base.SetMutableBinding(referenceRecord.[[ReferencedName]], value, referenceRecord.[[Strict]])를 반환한다 (참조 9.1).
Note

단계 3.a에서 생성될 수도 있는 객체는 위 추상 연산ordinary object [[Set]] 내부 메서드 밖에서는 접근할 수 없다. 구현은 그 객체를 실제로 생성하지 않기로 선택할 수도 있다.

6.2.5.7 GetThisValue ( referenceRecord )

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

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

6.2.5.8 InitializeReferencedBinding ( referenceRecord, value )

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

  1. Assert: IsUnresolvableReference(referenceRecord)는 false이다.
  2. basereferenceRecord.[[Base]]라고 하자.
  3. Assert: baseEnvironment Record이다.
  4. base.InitializeBinding(referenceRecord.[[ReferencedName]], value)를 반환한다.

6.2.5.9 MakePrivateReference ( baseValue, privateIdentifier )

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

  1. privateEnv를 현재 실행 컨텍스트의 PrivateEnvironment라고 하자.
  2. Assert: privateEnvnull이 아니다.
  3. privateNameResolvePrivateIdentifier(privateEnv, privateIdentifier)라고 하자.
  4. Reference Record { [[Base]]: baseValue, [[ReferencedName]]: privateName, [[Strict]]: true, [[ThisValue]]: empty }를 반환한다.

6.2.6 Property Descriptor 명세 타입

Property Descriptor 타입은 Object 프로퍼티 속성의 조작과 재현을 설명하는 데 사용된다. Property Descriptor는 0개 이상의 필드를 가진 Record이며, 각 필드의 이름은 속성 이름이고 그 값은 6.1.7.1에 명세된 대응 속성 값이다. 이 명세에서 Property Descriptor record의 리터럴 설명에 태그를 붙이는 데 사용되는 schema 이름은 “PropertyDescriptor”이다.

Property Descriptor 값은 특정 필드의 존재 또는 사용에 따라 데이터 Property Descriptor와 접근자 Property Descriptor로 더 분류될 수 있다. 데이터 Property Descriptor는 [[Value]] 또는 [[Writable]]라는 이름의 필드를 포함하는 것이다. 접근자 Property Descriptor는 [[Get]] 또는 [[Set]]라는 이름의 필드를 포함하는 것이다. 모든 Property Descriptor는 [[Enumerable]][[Configurable]]라는 이름의 필드를 가질 수 있다. Property Descriptor 값은 데이터 Property Descriptor이면서 동시에 접근자 Property Descriptor일 수는 없다. 그러나 둘 다 아닐 수는 있다 (이 경우 generic Property Descriptor이다). fully populated Property Descriptor는 접근자 Property Descriptor 또는 데이터 Property Descriptor 중 하나이며, 그에 대응하는 모든 필드가 Table 3에 정의되어 있는 것이다.

다음 추상 연산들은 이 명세에서 Property Descriptor 값에 대해 연산하는 데 사용된다.

6.2.6.1 IsAccessorDescriptor ( desc )

The abstract operation IsAccessorDescriptor takes argument desc (a Property Descriptor) and returns a 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 (a Property Descriptor) and returns a 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 (a Property Descriptor) and returns a Boolean. It performs the following steps when called:

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

6.2.6.4 FromPropertyDescriptor ( desc )

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

  1. descundefined이면, undefined를 반환한다.
  2. objOrdinaryObjectCreate(%Object.prototype%)라고 하자.
  3. Assert: obj는 own 프로퍼티가 없는 확장 가능한 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 (an ECMAScript language value) and returns either a normal completion containing a Property Descriptor or a throw completion. It performs the following steps when called:

  1. obj가 Object가 아니면, TypeError 예외를 던진다.
  2. 처음에는 아무 필드도 없는 새로운 Property Descriptordesc라고 하자.
  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 예외를 던진다.
    3. desc.[[Get]]getter로 설정한다.
  13. hasSet을 ? HasProperty(obj, "set")라고 하자.
  14. hasSettrue이면,
    1. setter를 ? Get(obj, "set")라고 하자.
    2. IsCallable(setter)가 false이고 setterundefined가 아니면, TypeError 예외를 던진다.
    3. desc.[[Set]]setter로 설정한다.
  15. desc[[Get]] 필드 또는 [[Set]] 필드를 가지면,
    1. desc[[Value]] 필드 또는 [[Writable]] 필드를 가지면, TypeError 예외를 던진다.
  16. desc를 반환한다.

6.2.6.6 CompletePropertyDescriptor ( desc )

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

  1. likeRecord { [[Value]]: undefined, [[Writable]]: false, [[Get]]: undefined, [[Set]]: undefined, [[Enumerable]]: false, [[Configurable]]: false }라고 하자.
  2. IsGenericDescriptor(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"라는 동사 뒤에 alias 목록을 사용하여 값을 포착한다. Abstract Closure가 생성될 때, 각 alias와 연관된 값을 그 시점에 포착한다. Abstract Closure가 호출될 때 수행할 알고리즘을 명시하는 단계에서는, 각 포착된 값이 그 값을 포착하는 데 사용된 alias로 참조된다.

Abstract Closure가 Completion Record를 반환한다면, 그 Completion Recordnormal completion 또는 throw completion 중 하나여야 한다.

Abstract Closure는 다른 알고리즘의 일부로 인라인으로 생성되며, 다음 예시에 나타나 있다.

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

6.2.9 Data Blocks

Data Block 명세 타입은 서로 구별되며 가변적인 바이트 크기(8비트) 숫자 값들의 시퀀스를 설명하는 데 사용된다. byte value는 0에서 255까지의 포함 구간에 있는 정수이다. Data Block 값은 고정된 개수의 바이트로 생성되며, 각 바이트의 초기 값은 0이다.

이 명세에서는 표기상 편의를 위해 배열과 유사한 문법을 사용하여 Data Block 값의 개별 바이트에 접근할 수 있다. 이 표기법은 Data Block 값을 0부터 시작하는 integer-indexed 바이트 시퀀스로 나타낸다. 예를 들어, db가 5바이트 Data Block 값이라면 db[2]를 사용하여 세 번째 바이트에 접근할 수 있다.

여러 agent가 동시에 참조할 수 있는 메모리에 존재하는 data block은 Shared Data Block으로 지정된다. Shared Data Block은 (Shared Data Block 값의 동등성 검사를 위한 목적상) address-free한 identity를 가진다. 즉, 이 identity는 어떤 프로세스에서 그 블록이 매핑되는 가상 주소에 묶이지 않고, 그 블록이 나타내는 메모리 위치들의 집합에 묶인다. 두 data block은 자신들이 포함하는 위치의 집합이 같을 때에만 같으며, 그렇지 않으면 같지 않고, 포함하는 위치 집합의 교집합은 공집합이다. 마지막으로, Shared Data Block은 Data Block과 구별될 수 있다.

Shared Data Block의 의미론은 메모리 모델에 의해 Shared Data Block event를 사용해 정의된다. 아래 추상 연산들은 Shared Data Block event를 도입하고, 평가 의미론과 메모리 모델의 event 의미론 사이의 인터페이스 역할을 한다. 이 event들은 candidate execution을 형성하며, 메모리 모델은 여기에 필터로 작용한다. 전체 의미론은 메모리 모델을 참조하라.

Shared Data Block event는 메모리 모델에 정의된 Record로 모델링된다.

다음 추상 연산들은 이 명세에서 Data Block 값에 대해 연산하는 데 사용된다.

6.2.9.1 CreateByteDataBlock ( size )

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

  1. size > 253 - 1이면, RangeError 예외를 던진다.
  2. size 바이트로 이루어진 새로운 Data Blockdb를 생성한다. 그런 Data Block을 생성할 수 없으면, RangeError 예외를 던진다.
  3. db의 모든 바이트를 0으로 설정한다.
  4. db를 반환한다.

6.2.9.2 CreateSharedByteDataBlock ( size )

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

  1. size 바이트로 이루어진 새로운 Shared Data Blockdb를 생성한다. 그런 Shared Data Block을 생성할 수 없으면, RangeError 예외를 던진다.
  2. agentRecord를 주변 agent의 Agent Record라고 하자.
  3. executionagentRecord.[[CandidateExecution]]라고 하자.
  4. eventsRecordexecution.[[EventsRecords]][[AgentSignifier]]AgentSignifier()인 Agent Events Record라고 하자.
  5. zero를 « 0 »이라고 하자.
  6. db의 각 인덱스 i에 대해, 다음을 수행한다.
    1. WriteSharedMemory { [[Order]]: init, [[NoTear]]: true, [[Block]]: db, [[ByteIndex]]: i, [[ElementSize]]: 1, [[Payload]]: zero }를 eventsRecord.[[EventList]]에 추가한다.
  7. db를 반환한다.

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

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

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

6.2.10 PrivateElement 명세 타입

PrivateElement 타입은 private class field, method, accessor의 명세에 사용되는 Record이다. Property Descriptor는 private element에 사용되지 않지만, private field는 non-configurable, non-enumerable, writable 데이터 프로퍼티와 유사하게 동작하고, private method는 non-configurable, non-enumerable, non-writable 데이터 프로퍼티와 유사하게 동작하며, private accessor는 non-configurable, non-enumerable 접근자 프로퍼티와 유사하게 동작한다.

PrivateElement 타입의 값은 Table 9에 정의된 필드를 가지는 Record 값이다. 이러한 값은 PrivateElements라고 불린다.

Table 9: PrivateElement Fields
필드 이름 존재하는 [[Kind]] 필드 값 의미
[[Key]] 모두 Private Name field, method, 또는 accessor의 이름.
[[Kind]] 모두 field, method, 또는 accessor element의 종류.
[[Value]] fieldmethod ECMAScript 언어 값 field의 값.
[[Get]] accessor 함수 객체 또는 undefined private accessor의 getter.
[[Set]] accessor 함수 객체 또는 undefined private accessor의 setter.

6.2.11 ClassFieldDefinition Record 명세 타입

ClassFieldDefinition 타입은 class field의 명세에 사용되는 Record이다.

ClassFieldDefinition 타입의 값은 Table 10에 정의된 필드를 가지는 Record 값이다. 이러한 값은 ClassFieldDefinition Records 라고 불린다.

Table 10: ClassFieldDefinition Record Fields
필드 이름 의미
[[Name]] Private Name, String, 또는 Symbol field의 이름.
[[Initializer]] ECMAScript 함수 객체 또는 empty 존재하는 경우 field의 initializer.

6.2.12 Private Names

Private Name 명세 타입은 private class element(field, method, accessor)의 키를 나타내는, 전역적으로 고유한 값(다른 모든 Private Name과 구별되는 값으로, 다른 점에서 구별되지 않더라도 다름)을 설명하는 데 사용된다. 각 Private Name은 String인 불변의 [[Description]] 내부 슬롯을 가진다. Private Name은 PrivateFieldAdd 또는 PrivateMethodOrAccessorAdd를 사용하여 어떤 ECMAScript 객체에도 설치될 수 있고, 이후 PrivateGetPrivateSet을 사용하여 읽거나 쓸 수 있다.

6.2.13 ClassStaticBlockDefinition Record 명세 타입

ClassStaticBlockDefinition Record 는 class static initialization block의 실행 가능한 코드를 캡슐화하는 데 사용되는 Record 값이다.

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

Table 11: ClassStaticBlockDefinition Record Fields
필드 이름 의미
[[BodyFunction]] ECMAScript 함수 객체 class의 static initialization 동안 호출될 함수 객체.

7 추상 연산

이 연산들은 ECMAScript 언어의 일부가 아니다. 이들은 오직 ECMAScript 언어의 의미론 명세를 돕기 위해 여기서 정의된다. 더 특수화된 다른 추상 연산들은 이 명세 전반에 걸쳐 정의된다.

7.1 타입 변환

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

BigInt 타입은 ECMAScript 언어에서 암묵적 변환을 가지지 않는다. 프로그래머는 다른 타입의 값을 변환하기 위해 BigInt를 명시적으로 호출해야 한다.

7.1.1 ToPrimitive ( input [ , preferredType ] )

The abstract operation ToPrimitive takes argument input (an ECMAScript language value) and optional argument preferredType (string or number) and returns either a normal completion containing an ECMAScript language value or a throw completion. 이것은 input 인수를 비-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. 그렇지 않고 preferredTypestring이면,
        1. hint"string"이라고 하자.
      3. 그렇지 않으면,
        1. Assert: 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% 메서드를 정의함으로써 이 동작을 재정의할 수 있다. 이 명세에서 정의된 객체 중 기본 ToPrimitive 동작을 재정의하는 것은 Date(참조 21.4.4.45) 와 Symbol 객체(참조 20.4.3.5) 뿐이다. Date는 힌트가 없는 경우를 힌트가 string인 것처럼 취급한다.

7.1.1.1 OrdinaryToPrimitive ( obj, hint )

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

  1. hintstring이면,
    1. methodNames를 « "toString", "valueOf" »라고 하자.
  2. 그렇지 않으면,
    1. methodNames를 « "valueOf", "toString" »라고 하자.
  3. methodNames의 각 요소 name에 대해, 다음을 수행한다.
    1. method를 ? Get(obj, name)이라고 하자.
    2. IsCallable(method)가 true이면,
      1. result를 ? Call(method, obj)라고 하자.
      2. result가 Object가 아니면, result를 반환한다.
  4. TypeError 예외를 던진다.

7.1.2 ToBoolean ( argument )

The abstract operation ToBoolean takes argument argument (an ECMAScript language value) and returns a 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 (an ECMAScript language value) and returns either a normal completion containing either a Number or a BigInt, or a 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 (an ECMAScript language value) and returns either a normal completion containing a Number or a 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. Assert: argument는 Object이다.
  8. primValue를 ? ToPrimitive(argument, number)라고 하자.
  9. Assert: primValue는 Object가 아니다.
  10. ToNumber(primValue)를 반환한다.

7.1.4.1 String 타입에 적용된 ToNumber

추상 연산 StringToNumber는 다음 문법을 사용하여 String 값을 Number 값으로 변환하는 방법을 명세한다.

구문

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

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

Note

StringNumericLiteral의 구문과 NumericLiteral의 구문 사이에는 몇 가지 차이가 있음을 주의해야 한다.

7.1.4.1.1 StringToNumber ( str )

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

  1. literalParseText(str, StringNumericLiteral)라고 하자.
  2. literal이 오류들의 List이면, NaN을 반환한다.
  3. literalStringNumericValue를 반환한다.

7.1.4.1.2 Runtime Semantics: StringNumericValue

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

Note

StringNumericLiteral을 Number 값으로 변환하는 것은 전반적으로 NumericLiteralNumericValue를 결정하는 것 (참조 12.9.3) 과 유사하지만, 세부 사항 중 일부는 다르다.

It is defined piecewise over the following productions:

StringNumericLiteral ::: StrWhiteSpaceopt
  1. +0𝔽를 반환한다.
StringNumericLiteral ::: StrWhiteSpaceopt StrNumericLiteral StrWhiteSpaceopt
  1. StrNumericLiteralStringNumericValue를 반환한다.
StrNumericLiteral ::: NonDecimalIntegerLiteral
  1. 𝔽(MV of NonDecimalIntegerLiteral)를 반환한다.
StrDecimalLiteral ::: - StrUnsignedDecimalLiteral
  1. aStrUnsignedDecimalLiteralStringNumericValue라고 하자.
  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의 code point 수라고 하자.
  3. 그렇지 않으면,
    1. b를 0이라고 하자.
    2. n을 0이라고 하자.
  4. ExponentPart가 존재하면 eExponentPart의 MV라고 하고, 그렇지 않으면 e를 0이라고 하자.
  5. RoundMVResult((a + (b × 10-n)) × 10e)를 반환한다.
StrUnsignedDecimalLiteral ::: . DecimalDigits ExponentPartopt
  1. bDecimalDigits의 MV라고 하자.
  2. ExponentPart가 존재하면 eExponentPart의 MV라고 하고, 그렇지 않으면 e를 0이라고 하자.
  3. nDecimalDigits의 code point 수라고 하자.
  4. RoundMVResult(b × 10e - n)를 반환한다.
StrUnsignedDecimalLiteral ::: DecimalDigits ExponentPartopt
  1. aDecimalDigits의 MV라고 하자.
  2. ExponentPart가 존재하면 eExponentPart의 MV라고 하고, 그렇지 않으면 e를 0이라고 하자.
  3. RoundMVResult(a × 10e)를 반환한다.

7.1.4.1.3 RoundMVResult ( n )

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

  1. n의 십진 표현이 20개 이하의 유효 숫자를 가지면, 𝔽(n)을 반환한다.
  2. option1n의 십진 표현에서 20번째 이후의 각 유효 숫자를 모두 0 숫자로 바꾼 결과가 나타내는 수학적 값이라고 하자.
  3. option2n의 십진 표현에서 20번째 이후의 각 유효 숫자를 모두 0 숫자로 바꾼 뒤, 20번째 위치의 숫자를 증가시킨 결과(필요하면 받아올림 포함)가 나타내는 수학적 값이라고 하자.
  4. chosenoption1 또는 option2구현 정의로 선택된 값이라고 하자.
  5. 𝔽(chosen)를 반환한다.

7.1.5 ToIntegerOrInfinity ( argument )

The abstract operation ToIntegerOrInfinity takes argument argument (an ECMAScript language value) and returns either a normal completion containing either an integer, +∞, or -∞, or a 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 ToFixedSizeInteger ( int, signed, bitWidth )

The abstract operation ToFixedSizeInteger takes arguments int (an integer, +∞, or -∞), signed (unsigned or signed), and bitWidth (a positive integer) and returns an integer. 이는 int를 0부터 2bitWidth - 1까지의 포함 구간에 있는 2bitWidth개의 정수 중 하나로(unsigned인 경우), 또는 -2bitWidth - 1부터 2bitWidth - 1 - 1까지의 포함 구간에 있는 정수 중 하나로(signed인 경우) 매핑한다. It performs the following steps when called:

  1. int = +∞ 또는 int = -∞이면, 0을 반환한다.
  2. fixedIntint modulo 2bitWidth라 하자.
  3. NOTE: 다음 단계는 fixedInt의 2의 보수 표현을 변경하지 않는다.
  4. signedsigned이고 fixedInt ≥ 2bitWidth - 1이면, fixedIntfixedInt - 2bitWidth로 설정한다.
  5. fixedInt를 반환한다.
Note

ToFixedSizeInteger는 멱등적이다. 즉, 임의의 ECMAScript 언어 값 x에 대해 ToFixedSizeInteger(ToFixedSizeInteger(x, signed, bitWidth), signed, bitWidth)는 ToFixedSizeInteger(x, signed, bitWidth)와 같다. 실제로 +∞와 -∞는 0으로 매핑되므로, 이 불변성은 signed의 반전에서도 유지된다(예: ToFixedSizeInteger(ToFixedSizeInteger(x, signed, 32), unsigned, 32)는 ToFixedSizeInteger(x, unsigned, 32)와 같다).

7.1.7 ToInt32 ( argument )

The abstract operation ToInt32 takes argument argument (ECMAScript 언어 값) and returns 정수 Number를 포함하는 정상 완료 또는 throw 완료. 이는 argument𝔽(-231)부터 𝔽(231 - 1)까지의 포함 구간에 있는 232개의 정수 Number 값 중 하나로 변환하며, -0𝔽는 제외한다. It performs the following steps when called:

  1. int를 ? ToIntegerOrInfinity(argument)라 하자.
  2. 𝔽(ToFixedSizeInteger(int, signed, 32))를 반환한다.

7.1.8 ToUint32 ( argument )

The abstract operation ToUint32 takes argument argument (ECMAScript 언어 값) and returns 정수 Number를 포함하는 정상 완료 또는 throw 완료. 이는 argument+0𝔽부터 𝔽(232 - 1)까지의 포함 구간에 있는 232개의 정수 Number 값 중 하나로 변환한다. It performs the following steps when called:

  1. int를 ? ToIntegerOrInfinity(argument)라 하자.
  2. 𝔽(ToFixedSizeInteger(int, unsigned, 32))를 반환한다.

7.1.9 ToInt16 ( argument )

The abstract operation ToInt16 takes argument argument (ECMAScript 언어 값) and returns 정수 Number를 포함하는 정상 완료 또는 throw 완료. 이는 argument𝔽(-215)부터 𝔽(215 - 1)까지의 포함 구간에 있는 216개의 정수 Number 값 중 하나로 변환하며, -0𝔽는 제외한다. It performs the following steps when called:

  1. int를 ? ToIntegerOrInfinity(argument)라 하자.
  2. 𝔽(ToFixedSizeInteger(int, signed, 16))를 반환한다.

7.1.10 ToUint16 ( argument )

The abstract operation ToUint16 takes argument argument (ECMAScript 언어 값) and returns 정수 Number를 포함하는 정상 완료 또는 throw 완료. 이는 argument+0𝔽부터 𝔽(216 - 1)까지의 포함 구간에 있는 216개의 정수 Number 값 중 하나로 변환한다. It performs the following steps when called:

  1. int를 ? ToIntegerOrInfinity(argument)라 하자.
  2. 𝔽(ToFixedSizeInteger(int, unsigned, 16))를 반환한다.

7.1.11 ToInt8 ( argument )

The abstract operation ToInt8 takes argument argument (ECMAScript 언어 값) and returns 정수 Number를 포함하는 정상 완료 또는 throw 완료. 이는 argument-128𝔽부터 127𝔽까지의 포함 구간에 있는 28개의 정수 Number 값 중 하나로 변환하며, -0𝔽는 제외한다. It performs the following steps when called:

  1. int를 ? ToIntegerOrInfinity(argument)라 하자.
  2. 𝔽(ToFixedSizeInteger(int, signed, 8))를 반환한다.

7.1.12 ToUint8 ( argument )

The abstract operation ToUint8 takes argument argument (ECMAScript 언어 값) and returns 정수 Number를 포함하는 정상 완료 또는 throw 완료. 이는 argument+0𝔽부터 255𝔽까지의 포함 구간에 있는 28개의 정수 Number 값 중 하나로 변환한다. It performs the following steps when called:

  1. int를 ? ToIntegerOrInfinity(argument)라 하자.
  2. 𝔽(ToFixedSizeInteger(int, unsigned, 8))를 반환한다.

7.1.13 ToUint8Clamp ( argument )

The abstract operation ToUint8Clamp takes argument argument (ECMAScript 언어 값) and returns 정수 Number를 포함하는 정상 완료 또는 throw 완료. 이는 argument를 0부터 255까지의 포함 구간에 있는 28개의 정수 Number 값 중 하나로 클램프하고 반올림한다. 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)를 반환한다.
  9. 𝔽(f + 1)를 반환한다.
Note

대부분의 다른 ECMAScript 정수 변환 연산과 달리, ToUint8Clamp는 비정수 값을 자르지 않고 반올림한다. 또한 “절반은 짝수로 반올림” 동률 처리 방식을 사용하는데, 이는 Math.round의 “절반 올림” 동률 처리 방식과 다르다.

7.1.14 ToBigInt ( argument )

The abstract operation ToBigInt takes argument argument (ECMAScript 언어 값) and returns BigInt를 포함하는 정상 완료 또는 throw 완료. 이는 argument를 BigInt 값으로 변환하거나, Number에서의 암시적 변환이 필요한 경우 던진다. It performs the following steps when called:

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

7.1.15 StringToBigInt ( str )

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

  1. literalParseText(str, StringIntegerLiteral)라 하자.
  2. literal이 오류의 List이면, undefined를 반환한다.
  3. mvliteral의 MV라 하자.
  4. Assert: mv정수이다.
  5. (mv)를 반환한다.

7.1.15.1 StringIntegerLiteral 문법

StringToBigInt는 다음 문법을 사용한다.

구문

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

7.1.15.2 런타임 의미론: MV

7.1.16 ToBigInt64 ( argument )

The abstract operation ToBigInt64 takes argument argument (ECMAScript 언어 값) and returns BigInt를 포함하는 정상 완료 또는 throw 완료. 이는 argument(-263)부터 (263 - 1)까지의 포함 구간에 있는 264개의 BigInt 값 중 하나로 변환한다. It performs the following steps when called:

  1. int(? ToBigInt(argument))라 하자.
  2. (ToFixedSizeInteger(int, signed, 64))를 반환한다.

7.1.17 ToBigUint64 ( argument )

The abstract operation ToBigUint64 takes argument argument (ECMAScript 언어 값) and returns BigInt를 포함하는 정상 완료 또는 throw 완료. 이는 argument0부터 (264 - 1)까지의 포함 구간에 있는 264개의 BigInt 값 중 하나로 변환한다. It performs the following steps when called:

  1. int(? ToBigInt(argument))라 하자.
  2. (ToFixedSizeInteger(int, unsigned, 64))를 반환한다.

7.1.18 ToString ( argument )

The abstract operation ToString takes argument argument (ECMAScript 언어 값) and returns String을 포함하는 정상 완료 또는 throw 완료. 이는 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. Assert: argument는 Object이다.
  10. primValue를 ? ToPrimitive(argument, string)이라 하자.
  11. Assert: primValue는 Object가 아니다.
  12. ToString(primValue)를 반환한다.

7.1.19 ToObject ( argument )

The abstract operation ToObject takes argument argument (ECMAScript 언어 값) and returns Object를 포함하는 정상 완료 또는 throw 완료. 이는 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. Assert: argument는 Object이다.
  8. argument를 반환한다.

7.1.20 ToPropertyKey ( argument )

The abstract operation ToPropertyKey takes argument argument (ECMAScript 언어 값) and returns 속성 키를 포함하는 정상 완료 또는 throw 완료. 이는 argument를 속성 키로 사용할 수 있는 값으로 변환한다. It performs the following steps when called:

  1. key를 ? ToPrimitive(argument, string)이라 하자.
  2. key가 Symbol이면, 다음을 수행한다.
    1. key를 반환한다.
  3. ToString(key)를 반환한다.

7.1.21 ToLength ( argument )

The abstract operation ToLength takes argument argument (ECMAScript 언어 값) and returns 음이 아닌 정수 Number를 포함하는 정상 완료 또는 throw 완료. 이는 argument를 배열 유사 객체의 길이로 사용하기에 적합한 음이 아닌 정수 Number로 클램프하고 자른다. It performs the following steps when called:

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

7.1.22 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를 반환한다.

표준 숫자 문자열은 CanonicalNumericIndexString 추상 연산undefined를 반환하지 않는 모든 String이다.

7.1.23 ToIndex ( value )

The abstract operation ToIndex takes argument value (an ECMAScript language value) and returns either a normal completion containing a non-negative integer or a throw completion. 이것은 value정수로 변환하고, 그 정수가 음이 아니며 integer index에 대응하면 그 정수를 반환한다. 그렇지 않으면 예외를 던진다. It performs the following steps when called:

  1. integer를 ? ToIntegerOrInfinity(value)라고 하자.
  2. integer가 0부터 253 - 1까지의 포함 구간 안에 있지 않으면, RangeError 예외를 던진다.
  3. integer를 반환한다.

7.2 테스트 및 비교 연산

7.2.1 RequireObjectCoercible ( argument )

The abstract operation RequireObjectCoercible takes argument argument (an ECMAScript language value) and returns either a normal completion containing unused or a 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 (an ECMAScript language value) and returns either a normal completion containing a Boolean or a throw completion. It performs the following steps when called:

  1. argument가 Object가 아니면, false를 반환한다.
  2. argument가 Array exotic object이면, true를 반환한다.
  3. argument가 Proxy exotic object이면,
    1. ValidateNonRevokedProxy(argument)를 수행한다.
    2. proxyTargetargument.[[ProxyTarget]]라고 하자.
    3. IsArray(proxyTarget)를 반환한다.
  4. false를 반환한다.

7.2.3 IsCallable ( argument )

The abstract operation IsCallable takes argument argument (an ECMAScript language value) and returns a 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 (an ECMAScript language value) and returns a Boolean. 이것은 argument[[Construct]] 내부 메서드를 가진 함수 객체인지 결정한다. It performs the following steps when called:

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

7.2.5 IsExtensible ( obj )

The abstract operation IsExtensible takes argument obj (an Object) and returns either a normal completion containing a Boolean or a throw completion. 이것은 obj에 추가 프로퍼티를 더할 수 있는지 결정하는 데 사용된다. It performs the following steps when called:

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

7.2.6 IsRegExp ( argument )

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

  1. 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 (a String) and returns a Boolean. 이것은 string6.1.4 에 설명된 대로 UTF-16으로 인코딩된 code point 시퀀스로 해석하고, 그것이 well formed UTF-16 시퀀스인지 결정한다. It performs the following steps when called:

  1. lenstring의 길이라고 하자.
  2. k를 0이라고 하자.
  3. k < len인 동안, 다음을 반복한다.
    1. cpCodePointAt(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 (an ECMAScript language value) and y (an ECMAScript language value) and returns a 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 (an ECMAScript language value) and y (an ECMAScript language value) and returns a Boolean. 이것은 두 인수가 같은 값인지 아닌지를 결정한다. It performs the following steps when called:

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

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

7.2.10 SameValueZero ( x, y )

The abstract operation SameValueZero takes arguments x (an ECMAScript language value) and y (an ECMAScript language value) and returns a Boolean. 이것은 두 인수가 같은 값인지 아닌지를 결정한다 (+0𝔽-0𝔽의 차이는 무시한다). It performs the following steps when called:

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

SameValueZero는 +0𝔽-0𝔽를 동등하게 취급한다는 점에서만 SameValue와 다르다.

7.2.11 SameValueNonNumber ( x, y )

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

  1. Assert: SameType(x, y)는 true이다.
  2. xundefined 또는 null이면, true를 반환한다.
  3. x가 BigInt이면,
    1. BigInt::equal(x, y)를 반환한다.
  4. x가 String이면,
    1. xy의 길이가 같고 같은 위치에 같은 code unit을 가지면, true를 반환한다.
    2. false를 반환한다.
  5. x가 Boolean이면,
    1. xtrue이고 ytrue이면, true를 반환한다.
    2. xfalse이고 yfalse이면, true를 반환한다.
    3. false를 반환한다.
  6. NOTE: 다른 모든 ECMAScript 언어 값은 identity로 비교된다.
  7. xy이면, true를 반환한다.
  8. false를 반환한다.
Note 1
설명 목적상, 필요하지 않더라도 일부 경우는 이 알고리즘 안에서 별도로 처리된다.
Note 2
"xy이다"가 의미하는 구체적인 사항은 5.2.8에 자세히 설명되어 있다.

7.2.12 IsLessThan ( x, y, leftFirst )

The abstract operation IsLessThan takes arguments x (an ECMAScript language value), y (an ECMAScript language value), and leftFirst (a Boolean) and returns either a normal completion containing either a Boolean or undefined, or a throw completion. x < y 비교에 대한 의미론을 제공하며, true, false 또는 undefined를 반환한다(undefined는 피연산자를 동일한 수치 타입의 비교 가능한 값으로 강제 변환할 수 없음을 나타낸다). leftFirst 플래그는 xy에 대해 잠재적으로 관찰 가능한 부수 효과가 있는 연산이 수행되는 순서를 제어하는 데 사용된다. ECMAScript는 표현식의 왼쪽에서 오른쪽으로의 평가를 명시하므로 이것이 필요하다. leftFirsttrue이면, x 매개변수는 y 매개변수에 대응하는 표현식의 왼쪽에 나타나는 표현식에 대응한다. leftFirstfalse이면 그 반대의 경우이며, 연산은 x보다 y에 대해 먼저 수행되어야 한다. It performs the following steps when called:

  1. leftFirsttrue이면,
    1. px를 ? ToPrimitive(x, number)라고 하자.
    2. py를 ? ToPrimitive(y, number)라고 하자.
  2. 그렇지 않으면,
    1. NOTE: 왼쪽에서 오른쪽 평가를 보존하기 위해 평가 순서를 뒤집어야 한다.
    2. py를 ? ToPrimitive(y, number)라고 하자.
    3. px를 ? ToPrimitive(x, number)라고 하자.
  3. px가 String이고 py가 String이면,
    1. lxpx의 길이라고 하자.
    2. lypy의 길이라고 하자.
    3. 0 ≤ i < min(lx, ly)를 만족하는 각 정수 i에 대해, 오름차순으로 다음을 수행한다.
      1. cxpx 안의 인덱스 i 위치 code unit의 숫자 값이라고 하자.
      2. cypy 안의 인덱스 i 위치 code unit의 숫자 값이라고 하자.
      3. cx < cy이면, true를 반환한다.
      4. cx > cy이면, false를 반환한다.
    4. lx < ly이면, true를 반환한다.
    5. false를 반환한다.
  4. px가 BigInt이고 py가 String이면,
    1. nyStringToBigInt(py)라고 하자.
    2. nyundefined이면, undefined를 반환한다.
    3. BigInt::lessThan(px, ny)를 반환한다.
  5. px가 String이고 py가 BigInt이면,
    1. nxStringToBigInt(px)라고 하자.
    2. nxundefined이면, undefined를 반환한다.
    3. BigInt::lessThan(nx, py)를 반환한다.
  6. NOTE: pxpy는 원시 값이므로, 평가 순서는 중요하지 않다.
  7. nx를 ? ToNumeric(px)라고 하자.
  8. ny를 ? ToNumeric(py)라고 하자.
  9. SameType(nx, ny)가 true이면,
    1. nx가 Number이면, Number::lessThan(nx, ny)를 반환한다.
    2. Assert: nx는 BigInt이다.
    3. BigInt::lessThan(nx, ny)를 반환한다.
  10. Assert: nx는 BigInt이고 ny는 Number이거나, nx는 Number이고 ny는 BigInt이다.
  11. nxNaN이거나 nyNaN이면, undefined를 반환한다.
  12. nx-∞𝔽이거나 ny+∞𝔽이면, true를 반환한다.
  13. nx+∞𝔽이거나 ny-∞𝔽이면, false를 반환한다.
  14. (nx) < (ny)이면, true를 반환한다.
  15. false를 반환한다.
Note 1

단계 3는, 덧셈 연산자 +를 처리하는 알고리즘 (13.15.3) 의 단계 1.c와 달리 논리합이 아니라 논리곱 연산을 사용한다는 점에서 다르다.

Note 2

String 비교는 UTF-16 code unit 값들의 시퀀스에 대한 단순한 사전식 순서를 사용한다. Unicode 명세에 정의된 문자 또는 문자열 동등성과 정렬 순서의 더 복잡하고 의미 지향적인 정의를 사용하려는 시도는 하지 않는다. 따라서 Unicode 표준에 따라 정준적으로 같지만 같은 정규화 형식이 아닌 String 값은 서로 같지 않은 것으로 테스트될 수 있다. 또한 surrogate pair를 포함한 String에 대해 code unit에 의한 사전식 순서가 code point에 의한 순서와 다르다는 점도 유의하라.

7.2.13 IsLooselyEqual ( x, y )

The abstract operation IsLooselyEqual takes arguments x (an ECMAScript language value) and y (an ECMAScript language value) and returns either a normal completion containing a Boolean or a throw completion. 이것은 == 연산자의 의미론을 제공한다. It performs the following steps when called:

  1. SameType(x, y)가 true이면,
    1. IsStrictlyEqual(x, y)를 반환한다.
  2. xnull이고 yundefined이면, true를 반환한다.
  3. xundefined이고 ynull이면, true를 반환한다.
  4. 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를 반환한다.
    3. false를 반환한다.
  14. false를 반환한다.

7.2.14 IsStrictlyEqual ( x, y )

The abstract operation IsStrictlyEqual takes arguments x (an ECMAScript language value) and y (an ECMAScript language value) and returns a Boolean. 이것은 === 연산자의 의미론을 제공한다. It performs the following steps when called:

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

이 알고리즘은 signed zero와 NaN을 처리하는 방식에서 SameValue 알고리즘과 다르다.

7.3 객체에 대한 연산

7.3.1 MakeBasicObject ( internalSlotsList )

The abstract operation MakeBasicObject takes argument internalSlotsList (a List of internal slot names) and returns an Object. 이것은 ordinary objectexotic object를 포함하여 알고리즘적으로 생성되는 모든 ECMAScript 객체의 원천이다. 이것은 모든 객체 생성에 사용되는 공통 단계를 분리해내고, 객체 생성을 중앙화한다. It performs the following steps when called:

  1. internalSlotsListinternalSlotsList와 « [[PrivateElements]] »의 list-concatenation으로 설정한다.
  2. internalSlotsList 안의 각 이름에 대해 내부 슬롯을 하나씩 가진 새로 생성된 객체를 obj라고 하자.
  3. NOTE: Object 내부 메서드와 내부 슬롯에 설명된 대로, 달리 명시되지 않는 한 각 내부 슬롯의 초기 값은 undefined이다.
  4. obj.[[PrivateElements]]를 새로운 빈 List로 설정한다.
  5. obj의 essential internal methods를 10.1에 명세된 기본 ordinary object 정의로 설정한다.
  6. Assert: 호출자가 obj[[GetPrototypeOf]][[SetPrototypeOf]] essential internal methods를 둘 다 재정의하지 않을 것이라면, internalSlotsList[[Prototype]]을 포함한다.
  7. Assert: 호출자가 obj[[SetPrototypeOf]], [[IsExtensible]], [[PreventExtensions]] essential internal methods를 모두 재정의하지 않을 것이라면, internalSlotsList[[Extensible]]을 포함한다.
  8. internalSlotsList[[Extensible]]을 포함하면, obj.[[Extensible]]true로 설정한다.
  9. obj를 반환한다.
Note

이 명세에서 exotic objectArrayCreate, BoundFunctionCreate와 같은 추상 연산에서 먼저 MakeBasicObject를 호출하여 기초적인 기반 객체를 얻은 뒤, 그 객체의 내부 메서드 일부 또는 전부를 재정의함으로써 생성된다. exotic object 생성을 캡슐화하기 위해, 객체의 essential internal methods는 그러한 연산들 밖에서는 결코 수정되지 않는다.

7.3.2 Get ( obj, propertyKey )

The abstract operation Get takes arguments obj (an Object) and propertyKey (a property key) and returns either a normal completion containing an ECMAScript language value or a throw completion. 이것은 객체의 특정 프로퍼티 값을 검색하는 데 사용된다. It performs the following steps when called:

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

7.3.3 GetV ( value, propertyKey )

The abstract operation GetV takes arguments value (an ECMAScript language value) and propertyKey (a property key) and returns either a normal completion containing an ECMAScript language value or a throw completion. 이것은 ECMAScript 언어 값의 특정 프로퍼티 값을 검색하는 데 사용된다. 값이 객체가 아니면, 프로퍼티 조회는 그 값의 타입에 적합한 래퍼 객체를 사용하여 수행된다. It performs the following steps when called:

  1. obj를 ? ToObject(value)라고 하자.
  2. obj.[[Get]](propertyKey, value)를 반환한다.

7.3.4 Set ( obj, propertyKey, value, throw )

The abstract operation Set takes arguments obj (an Object), propertyKey (a property key), value (an ECMAScript language value), and throw (a Boolean) and returns either a normal completion containing unused or a throw completion. 이것은 객체의 특정 프로퍼티 값을 설정하는 데 사용된다. value는 그 프로퍼티의 새 값이다. It performs the following steps when called:

  1. success를 ? obj.[[Set]](propertyKey, value, obj)라고 하자.
  2. successfalse이고 throwtrue이면, TypeError 예외를 던진다.
  3. unused를 반환한다.

7.3.5 CreateDataProperty ( obj, propertyKey, value )

The abstract operation CreateDataProperty takes arguments obj (an Object), propertyKey (a property key), and value (an ECMAScript language value) and returns either a normal completion containing a Boolean or a throw completion. 이것은 객체의 새로운 own 프로퍼티를 생성하는 데 사용된다. It performs the following steps when called:

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

추상 연산은 ECMAScript 언어 할당 연산자가 생성하는 프로퍼티에 사용되는 것과 동일한 기본 속성을 가진 프로퍼티를 생성한다. 일반적으로 그 프로퍼티는 아직 존재하지 않을 것이다. 만약 이미 존재하고 configurable이 아니거나 obj가 extensible하지 않다면, [[DefineOwnProperty]]false를 반환할 것이다.

7.3.6 CreateDataPropertyOrThrow ( obj, propertyKey, value )

The abstract operation CreateDataPropertyOrThrow takes arguments obj (an Object), propertyKey (a property key), and value (an ECMAScript language value) and returns either a normal completion containing unused or a throw completion. 이것은 객체의 새로운 own 프로퍼티를 생성하는 데 사용된다. 요청된 프로퍼티 갱신을 수행할 수 없으면 TypeError 예외를 던진다. It performs the following steps when called:

  1. success를 ? CreateDataProperty(obj, propertyKey, value)라고 하자.
  2. successfalse이면, TypeError 예외를 던진다.
  3. unused를 반환한다.
Note

추상 연산은 ECMAScript 언어 할당 연산자가 생성하는 프로퍼티에 사용되는 것과 동일한 기본 속성을 가진 프로퍼티를 생성한다. 일반적으로 그 프로퍼티는 아직 존재하지 않을 것이다. 만약 이미 존재하고 configurable이 아니거나 obj가 extensible하지 않다면, [[DefineOwnProperty]]false를 반환하여 이 연산이 TypeError 예외를 던지게 한다.

7.3.7 CreateNonEnumerableDataPropertyOrThrow ( obj, propertyKey, value )

The abstract operation CreateNonEnumerableDataPropertyOrThrow takes arguments obj (an Object), propertyKey (a property key), and value (an ECMAScript language value) and returns unused. 이것은 ordinary object의 새로운 non-enumerable own 프로퍼티를 생성하는 데 사용된다. It performs the following steps when called:

  1. Assert: obj는 ordinary하고 extensible하며 non-configurable 프로퍼티를 가지지 않는 객체이다.
  2. newDesc를 PropertyDescriptor { [[Value]]: value, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: true }라고 하자.
  3. DefinePropertyOrThrow(obj, propertyKey, newDesc)를 수행한다.
  4. unused를 반환한다.
Note

추상 연산은 ECMAScript 언어 할당 연산자가 생성하는 프로퍼티에 사용되는 것과 동일한 기본 속성을 가지되 enumerable하지 않은 프로퍼티를 생성한다. 일반적으로 그 프로퍼티는 아직 존재하지 않을 것이다. 만약 존재하더라도, DefinePropertyOrThrow는 정상적으로 완료됨이 보장된다.

7.3.8 DefinePropertyOrThrow ( obj, propertyKey, desc )

The abstract operation DefinePropertyOrThrow takes arguments obj (an Object), propertyKey (a property key), and desc (a Property Descriptor) and returns either a normal completion containing unused or a throw completion. 이것은 객체의 [[DefineOwnProperty]] 내부 메서드를, 요청된 프로퍼티 갱신을 수행할 수 없으면 TypeError 예외를 던지는 방식으로 호출하는 데 사용된다. It performs the following steps when called:

  1. success를 ? obj.[[DefineOwnProperty]](propertyKey, desc)라고 하자.
  2. successfalse이면, TypeError 예외를 던진다.
  3. unused를 반환한다.

7.3.9 DeletePropertyOrThrow ( obj, propertyKey )

The abstract operation DeletePropertyOrThrow takes arguments obj (an Object) and propertyKey (a property key) and returns either a normal completion containing unused or a throw completion. 이것은 객체의 특정 own 프로퍼티를 제거하는 데 사용된다. 프로퍼티가 configurable하지 않으면 예외를 던진다. It performs the following steps when called:

  1. success를 ? obj.[[Delete]](propertyKey)라고 하자.
  2. successfalse이면, TypeError 예외를 던진다.
  3. unused를 반환한다.

7.3.10 GetMethod ( value, propertyKey )

The abstract operation GetMethod takes arguments value (an ECMAScript language value) and propertyKey (a property key) and returns either a normal completion containing either a function object or undefined, or a throw completion. 이것은 ECMAScript 언어 값의 특정 프로퍼티 값을 얻는 데 사용되며, 그 프로퍼티 값은 함수일 것으로 기대된다. It performs the following steps when called:

  1. func를 ? GetV(value, propertyKey)라고 하자.
  2. funcundefined 또는 null이면, undefined를 반환한다.
  3. IsCallable(func)가 false이면, TypeError 예외를 던진다.
  4. func를 반환한다.

7.3.11 HasProperty ( obj, propertyKey )

The abstract operation HasProperty takes arguments obj (an Object) and propertyKey (a property key) and returns either a normal completion containing a Boolean or a throw completion. 이것은 객체가 지정된 property key를 가진 프로퍼티를 가지는지 결정하는 데 사용된다. 그 프로퍼티는 own일 수도 있고 상속된 것일 수도 있다. It performs the following steps when called:

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

7.3.12 HasOwnProperty ( obj, propertyKey )

The abstract operation HasOwnProperty takes arguments obj (an Object) and propertyKey (a property key) and returns either a normal completion containing a Boolean or a throw completion. 이것은 객체가 지정된 property key를 가진 own 프로퍼티를 가지는지 결정하는 데 사용된다. It performs the following steps when called:

  1. desc를 ? obj.[[GetOwnProperty]](propertyKey)라고 하자.
  2. descundefined이면, false를 반환한다.
  3. true를 반환한다.

7.3.13 Call ( func, thisValue [ , argumentsList ] )

The abstract operation Call takes arguments func (an ECMAScript language value) and thisValue (an ECMAScript language value) and optional argument argumentsList (a List of ECMAScript language values) and returns either a normal completion containing an ECMAScript language value or a throw completion. 이것은 함수 객체의 [[Call]] 내부 메서드를 호출하는 데 사용된다. func는 함수 객체이고, thisValue[[Call]]this 값이 되는 ECMAScript 언어 값이며, argumentsList는 내부 메서드의 대응 인수에 전달되는 값이다. argumentsList가 존재하지 않으면, 새로운 빈 List가 그 값으로 사용된다. It performs the following steps when called:

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

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

The abstract operation Construct takes argument constructor (a constructor) and optional arguments argumentsList (a List of ECMAScript language values) and newTarget (a constructor) and returns either a normal completion containing an Object or a throw completion. 이것은 함수 객체의 [[Construct]] 내부 메서드를 호출하는 데 사용된다. argumentsListnewTarget은 내부 메서드의 대응 인수로 전달될 값들이다. argumentsList가 존재하지 않으면, 새로운 빈 List가 그 값으로 사용된다. newTarget이 존재하지 않으면, constructor가 그 값으로 사용된다. It performs the following steps when called:

  1. newTarget이 존재하지 않으면, newTargetconstructor로 설정한다.
  2. argumentsList가 존재하지 않으면, argumentsList를 새로운 빈 List로 설정한다.
  3. constructor.[[Construct]](argumentsList, newTarget)를 반환한다.
Note

newTarget이 존재하지 않으면, 이 연산은 new F(...argumentsList)와 동등하다.

7.3.15 SetIntegrityLevel ( obj, level )

The abstract operation SetIntegrityLevel takes arguments obj (an Object) and level (sealed or frozen) and returns either a normal completion containing a Boolean or a throw completion. 이것은 객체의 own 프로퍼티 집합을 고정하는 데 사용된다. It performs the following steps when called:

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

7.3.16 TestIntegrityLevel ( obj, level )

The abstract operation TestIntegrityLevel takes arguments obj (an Object) and level (sealed or frozen) and returns either a normal completion containing a Boolean or a throw completion. 이것은 객체의 own 프로퍼티 집합이 고정되어 있는지 결정하는 데 사용된다. It performs the following steps when called:

  1. extensible을 ? IsExtensible(obj)라고 하자.
  2. extensibletrue이면, false를 반환한다.
  3. NOTE: 객체가 extensible이면, 그 어떤 프로퍼티도 검사되지 않는다.
  4. keys를 ? obj.[[OwnPropertyKeys]]()라고 하자.
  5. keys의 각 요소 key에 대해, 다음을 수행한다.
    1. currentDesc를 ? obj.[[GetOwnProperty]](key)라고 하자.
    2. currentDescundefined가 아니면,
      1. currentDesc.[[Configurable]]true이면, false를 반환한다.
      2. levelfrozen이고 IsDataDescriptor(currentDesc)가 true이면,
        1. currentDesc.[[Writable]]true이면, false를 반환한다.
  6. true를 반환한다.

7.3.17 CreateArrayFromList ( elements )

The abstract operation CreateArrayFromList takes argument elements (a List of ECMAScript language values) and returns an Array. 이것은 elements가 제공하는 요소들을 가진 Array를 생성하는 데 사용된다. It performs the following steps when called:

  1. array를 ! ArrayCreate(0)라고 하자.
  2. n을 0이라고 하자.
  3. elements의 각 요소 e에 대해, 다음을 수행한다.
    1. CreateDataPropertyOrThrow(array, ! ToString(𝔽(n)), e)를 수행한다.
    2. nn + 1로 설정한다.
  4. array를 반환한다.

7.3.18 LengthOfArrayLike ( obj )

The abstract operation LengthOfArrayLike takes argument obj (an Object) and returns either a normal completion containing a non-negative integer or a throw completion. 이것은 배열 유사 객체의 "length" 프로퍼티 값을 반환한다. It performs the following steps when called:

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

이 연산이 정상 완료를 반환하는 모든 객체를 array-like object라고 한다.

Note 1
일반적으로 array-like object는 integer index 이름을 가진 일부 프로퍼티도 가질 것이다. 그러나 그것은 이 정의의 요구 사항은 아니다.
Note 2
Array와 String 객체는 array-like object의 예이다.

7.3.19 CreateListFromArrayLike ( obj [ , validElementTypes ] )

The abstract operation CreateListFromArrayLike takes argument obj (an ECMAScript language value) and optional argument validElementTypes (all or property-key) and returns either a normal completion containing a List of ECMAScript language values or a throw completion. 이것은 obj의 인덱스된 프로퍼티들이 제공하는 요소들로 구성된 List 값을 생성하는 데 사용된다. validElementTypes는 요소로 허용되는 값의 타입들을 나타낸다. It performs the following steps when called:

  1. validElementTypes가 존재하지 않으면, validElementTypesall로 설정한다.
  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가 property key가 아니면, TypeError 예외를 던진다.
    4. nextlist에 추가한다.
    5. indexindex + 1로 설정한다.
  7. list를 반환한다.

7.3.20 Invoke ( value, propertyKey [ , argumentsList ] )

The abstract operation Invoke takes arguments value (an ECMAScript language value) and propertyKey (a property key) and optional argument argumentsList (a List of ECMAScript language values) and returns either a normal completion containing an ECMAScript language value or a throw completion. 이것은 ECMAScript 언어 값의 메서드 프로퍼티를 호출하는 데 사용된다. value는 프로퍼티 조회 지점이자 호출의 this 값 역할을 모두 한다. argumentsList는 메서드에 전달되는 인수 값들의 목록이다. argumentsList가 존재하지 않으면, 새로운 빈 List가 그 값으로 사용된다. It performs the following steps when called:

  1. argumentsList가 존재하지 않으면, argumentsList를 새로운 빈 List로 설정한다.
  2. func를 ? GetV(value, propertyKey)라고 하자.
  3. Call(func, value, argumentsList)를 반환한다.

7.3.21 OrdinaryHasInstance ( constructor, instance )

The abstract operation OrdinaryHasInstance takes arguments constructor (an ECMAScript language value) and instance (an ECMAScript language value) and returns either a normal completion containing a Boolean or a throw completion. 이것은 instanceconstructor가 제공하는 인스턴스 객체 상속 경로를 상속하는지를 결정하는 기본 알고리즘을 구현한다. It performs the following steps when called:

  1. IsCallable(constructor)가 false이면, false를 반환한다.
  2. constructor[[BoundTargetFunction]] 내부 슬롯을 가지면,
    1. boundConstructorconstructor.[[BoundTargetFunction]]라고 하자.
    2. InstanceofOperator(instance, boundConstructor)를 반환한다.
  3. instance가 Object가 아니면, false를 반환한다.
  4. proto를 ? Get(constructor, "prototype")이라고 하자.
  5. proto가 Object가 아니면, TypeError 예외를 던진다.
  6. 다음을 반복한다.
    1. instance를 ? instance.[[GetPrototypeOf]]()로 설정한다.
    2. instancenull이면, false를 반환한다.
    3. SameValue(proto, instance)가 true이면, true를 반환한다.

7.3.22 SpeciesConstructor ( obj, defaultConstructor )

The abstract operation SpeciesConstructor takes arguments obj (an Object) and defaultConstructor (a constructor) and returns either a normal completion containing a constructor or a throw completion. 이것은 obj에서 파생되는 새 객체를 생성하는 데 사용되어야 할 생성자를 검색하는 데 사용된다. defaultConstructorobj에서부터 시작해 생성자 %Symbol.species% 프로퍼티를 찾을 수 없을 때 사용할 생성자이다. It performs the following steps when called:

  1. constructor를 ? Get(obj, "constructor")라고 하자.
  2. constructorundefined이면, defaultConstructor를 반환한다.
  3. constructor가 Object가 아니면, TypeError 예외를 던진다.
  4. species를 ? Get(constructor, %Symbol.species%)라고 하자.
  5. speciesundefined 또는 null 중 하나이면, defaultConstructor를 반환한다.
  6. IsConstructor(species)가 true이면, species를 반환한다.
  7. TypeError 예외를 던진다.

7.3.23 EnumerableOwnProperties ( obj, kind )

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

  1. ownKeys를 ? obj.[[OwnPropertyKeys]]()라고 하자.
  2. results를 새로운 빈 List라고 하자.
  3. ownKeys의 각 요소 key에 대해, 다음을 수행한다.
    1. key가 String이면,
      1. desc를 ? obj.[[GetOwnProperty]](key)라고 하자.
      2. descundefined가 아니고 desc.[[Enumerable]]true이면,
        1. kindkey이면,
          1. keyresults에 추가한다.
        2. 그렇지 않으면,
          1. value를 ? Get(obj, key)라고 하자.
          2. kindvalue이면,
            1. valueresults에 추가한다.
          3. 그렇지 않으면,
            1. Assert: kindkey+value이다.
            2. entryCreateArrayFromListkey, value »)라고 하자.
            3. entryresults에 추가한다.
  4. results를 반환한다.

7.3.24 GetFunctionRealm ( func )

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

  1. func[[Realm]] 내부 슬롯을 가지면,
    1. func.[[Realm]]을 반환한다.
  2. func가 bound function exotic object이면,
    1. boundTargetFunctionfunc.[[BoundTargetFunction]]이라고 하자.
    2. GetFunctionRealm(boundTargetFunction)을 반환한다.
  3. func가 Proxy exotic object이면,
    1. ValidateNonRevokedProxy(func)를 수행한다.
    2. proxyTargetfunc.[[ProxyTarget]]이라고 하자.
    3. Assert: proxyTargetfunction object이다.
    4. GetFunctionRealm(proxyTarget)을 반환한다.
  4. 현재 Realm Record를 반환한다.
Note

단계 4func[[Realm]] 내부 슬롯을 가지지 않는 비표준 function exotic object인 경우에만 도달하게 된다.

7.3.25 CopyDataProperties ( target, source, excludedItems )

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

  1. sourceundefined 또는 null 중 하나이면, unused를 반환한다.
  2. from을 ! ToObject(source)라고 하자.
  3. keys를 ? from.[[OwnPropertyKeys]]()라고 하자.
  4. keys의 각 요소 nextKey에 대해, 다음을 수행한다.
    1. excludedfalse라고 하자.
    2. excludedItems의 각 요소 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 ( obj, privateName )

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

  1. obj.[[PrivateElements]]pe.[[Key]]privateNamePrivateElement pe를 포함하면,
    1. pe를 반환한다.
  2. empty를 반환한다.

7.3.27 PrivateFieldAdd ( obj, privateName, value )

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

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

7.3.28 PrivateMethodOrAccessorAdd ( obj, method )

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

  1. Assert: method.[[Kind]]method 또는 accessor 중 하나이다.
  2. 호스트가 웹 브라우저이면,
    1. HostEnsureCanAddPrivateElement(obj)를 수행한다.
  3. entryPrivateElementFind(obj, method.[[Key]])라고 하자.
  4. entryempty가 아니면, TypeError 예외를 던진다.
  5. methodobj.[[PrivateElements]]에 추가한다.
  6. unused를 반환한다.
Note

private method와 accessor의 값은 인스턴스 간에 공유된다. 이 연산은 method나 accessor의 새 복사본을 생성하지 않는다.

7.3.29 HostEnsureCanAddPrivateElement ( obj )

The host-defined abstract operation HostEnsureCanAddPrivateElement takes argument obj (an Object) and returns either a normal completion containing unused or a throw completion. 이것은 호스트 환경이 특정 호스트 정의 exotic object에 private element를 추가하는 것을 막을 수 있게 한다.

HostEnsureCanAddPrivateElement의 구현은 다음 요구 사항을 준수해야 한다.

HostEnsureCanAddPrivateElement의 기본 구현은 NormalCompletion(unused)를 반환하는 것이다.

추상 연산은 웹 브라우저인 ECMAScript 호스트에서만 호출된다.

7.3.30 PrivateGet ( obj, privateName )

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

  1. entryPrivateElementFind(obj, privateName)라고 하자.
  2. entryempty이면, TypeError 예외를 던진다.
  3. entry.[[Kind]]field 또는 method 중 하나이면,
    1. entry.[[Value]]를 반환한다.
  4. Assert: entry.[[Kind]]accessor이다.
  5. entry.[[Get]]undefined이면, TypeError 예외를 던진다.
  6. getterentry.[[Get]]이라고 하자.
  7. Call(getter, obj)를 반환한다.

7.3.31 PrivateSet ( obj, privateName, value )

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

  1. entryPrivateElementFind(obj, privateName)라고 하자.
  2. entryempty이면, TypeError 예외를 던진다.
  3. entry.[[Kind]]method이면, TypeError 예외를 던진다.
  4. entry.[[Kind]]field이면,
    1. entry.[[Value]]value로 설정한다.
  5. 그렇지 않으면,
    1. Assert: entry.[[Kind]]accessor이다.
    2. entry.[[Set]]undefined이면, TypeError 예외를 던진다.
    3. setterentry.[[Set]]이라고 하자.
    4. Call(setter, obj, « value »)를 수행한다.
  6. unused를 반환한다.

7.3.32 DefineField ( receiver, fieldRecord )

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

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

7.3.33 InitializeInstanceElements ( obj, constructor )

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

  1. methodsconstructor.[[PrivateMethods]]라고 하자.
  2. methods의 각 PrivateElement method에 대해, 다음을 수행한다.
    1. PrivateMethodOrAccessorAdd(obj, method)를 수행한다.
  3. fieldsconstructor.[[Fields]]라고 하자.
  4. fields의 각 요소 fieldRecord에 대해, 다음을 수행한다.
    1. DefineField(obj, fieldRecord)를 수행한다.
  5. unused를 반환한다.

7.3.34 AddValueToKeyedGroup ( groups, key, value )

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

  1. groups의 각 Record { [[Key]], [[Elements]] } group에 대해, 다음을 수행한다.
    1. SameValue(group.[[Key]], key)가 true이면,
      1. Assert: 정확히 하나의 groups 원소만 이 기준을 만족한다.
      2. valuegroup.[[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 (an ECMAScript language value), callback (an ECMAScript language value), and keyCoercion (property or collection) and returns either a normal completion containing a List of Records with fields [[Key]] (an ECMAScript language value) and [[Elements]] (a List of ECMAScript language values), or a throw completion. It performs the following steps when called:

  1. RequireObjectCoercible(items)를 수행한다.
  2. IsCallable(callback)가 false이면, TypeError 예외를 던진다.
  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. 그렇지 않으면,
      1. Assert: keyCoercioncollection이다.
      2. keyCanonicalizeKeyedCollectionKey(key)로 설정한다.
    9. AddValueToKeyedGroup(groups, key, value)를 수행한다.
    10. kk + 1로 설정한다.

7.3.36 GetOptionsObject ( options )

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

  1. optionsundefined이면,
    1. OrdinaryObjectCreate(null)를 반환한다.
  2. options가 Object이면,
    1. options를 반환한다.
  3. TypeError 예외를 던진다.

7.3.37 SetterThatIgnoresPrototypeProperties ( thisValue, home, propertyKey, value )

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

  1. thisValue가 Object가 아니면,
    1. TypeError 예외를 던진다.
  2. SameValue(thisValue, home)가 true이면,
    1. NOTE: 여기서 던지는 것은 strict mode 코드에서 home 객체의 non-writable 데이터 프로퍼티에 대한 할당을 흉내 낸다.
    2. TypeError 예외를 던진다.
  3. desc를 ? thisValue.[[GetOwnProperty]](propertyKey)라고 하자.
  4. descundefined이면,
    1. CreateDataPropertyOrThrow(thisValue, propertyKey, value)를 수행한다.
  5. 그렇지 않으면,
    1. Set(thisValue, propertyKey, value, true)를 수행한다.
  6. unused를 반환한다.

7.4 Iterator 객체에 대한 연산

공통 반복 인터페이스를 보라 (27.1).

7.4.1 Iterator Record

Iterator Recorditerator 또는 async iteratornext 메서드를 함께 캡슐화하는 데 사용되는 Record 값이다.

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

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

7.4.2 GetIteratorDirect ( obj )

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

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

7.4.3 GetIteratorFromMethod ( obj, method )

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

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

7.4.4 GetIterator ( obj, kind )

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

  1. kindasync이면,
    1. method를 ? GetMethod(obj, %Symbol.asyncIterator%)라고 하자.
    2. methodundefined이면,
      1. syncMethod를 ? GetMethod(obj, %Symbol.iterator%)라고 하자.
      2. syncMethodundefined이면, TypeError 예외를 던진다.
      3. syncIteratorRecord를 ? GetIteratorFromMethod(obj, syncMethod)라고 하자.
      4. CreateAsyncFromSyncIterator(syncIteratorRecord)를 반환한다.
  2. 그렇지 않으면,
    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 (an ECMAScript language value) and primitiveHandling (iterate-string-primitives or reject-primitives) and returns either a normal completion containing an Iterator Record or a throw completion. It performs the following steps when called:

  1. obj가 Object가 아니면,
    1. primitiveHandlingreject-primitives이면, TypeError 예외를 던진다.
    2. Assert: primitiveHandlingiterate-string-primitives이다.
    3. obj가 String이 아니면, TypeError 예외를 던진다.
  2. method를 ? GetMethod(obj, %Symbol.iterator%)라고 하자.
  3. methodundefined이면,
    1. iteratorobj라고 하자.
  4. 그렇지 않으면,
    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 (an Iterator Record) and optional argument value (an ECMAScript language value) and returns either a normal completion containing an Object or a throw completion. It performs the following steps when called:

  1. value가 존재하지 않으면,
    1. resultCompletion(Call(iteratorRecord.[[NextMethod]], iteratorRecord.[[Iterator]]))라고 하자.
  2. 그렇지 않으면,
    1. resultCompletion(Call(iteratorRecord.[[NextMethod]], iteratorRecord.[[Iterator]], « value »))라고 하자.
  3. resultthrow completion이면,
    1. iteratorRecord.[[Done]]true로 설정한다.
    2. result를 반환한다.
  4. result를 ! result로 설정한다.
  5. result가 Object가 아니면,
    1. iteratorRecord.[[Done]]true로 설정한다.
    2. TypeError 예외를 던진다.
  6. result를 반환한다.

7.4.7 IteratorComplete ( iteratorResult )

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

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

7.4.8 IteratorValue ( iteratorResult )

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

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

7.4.9 IteratorStep ( iteratorRecord )

The abstract operation IteratorStep takes argument iteratorRecord (an Iterator Record) and returns either a normal completion containing either an Object or done, or a throw completion. 이것은 iteratorRecord.[[Iterator]]로부터 다음 값을 요청하기 위해 iteratorRecord.[[NextMethod]]를 호출하고, iterator가 끝에 도달했음을 나타내는 done 또는 다음 값이 사용 가능하다면 IteratorResult 객체를 반환한다. It performs the following steps when called:

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

7.4.10 IteratorStepValue ( iteratorRecord )

The abstract operation IteratorStepValue takes argument iteratorRecord (an Iterator Record) and returns either a normal completion containing either an ECMAScript language value or done, or a throw completion. 이것은 iteratorRecord.[[Iterator]]로부터 다음 값을 요청하기 위해 iteratorRecord.[[NextMethod]]를 호출하고, iterator가 끝에 도달했음을 나타내는 done 또는 다음 값이 사용 가능하다면 IteratorResult 객체의 값을 반환한다. It performs the following steps when called:

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

7.4.11 IteratorClose ( iteratorRecord, completion )

The abstract operation IteratorClose takes arguments iteratorRecord (an Iterator Record) and completion (a Completion Record) and returns a Completion Record. 이것은 iterator에게, 완료 상태에 도달했을 때 통상 수행했을 동작을 수행해야 함을 알리는 데 사용된다. It performs the following steps when called:

  1. Assert: iteratorRecord.[[Iterator]]는 Object이다.
  2. iteratoriteratorRecord.[[Iterator]]라고 하자.
  3. innerResultCompletion(GetMethod(iterator, "return"))라고 하자.
  4. innerResultnormal completion이면,
    1. returninnerResult.[[Value]]라고 하자.
    2. returnundefined이면, ? completion을 반환한다.
    3. innerResultCompletion(Call(return, iterator))로 설정한다.
  5. completionthrow completion이면, ? completion을 반환한다.
  6. innerResultthrow completion이면, ? innerResult를 반환한다.
  7. innerResult.[[Value]]가 Object가 아니면, TypeError 예외를 던진다.
  8. completion을 반환한다.

7.4.12 IteratorCloseAll ( iters, completion )

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

  1. iters의 각 요소 iter에 대해, List의 역순으로 다음을 수행한다.
    1. completionCompletion(IteratorClose(iter, completion))로 설정한다.
  2. completion을 반환한다.

7.4.13 IfAbruptCloseIterator ( value, iteratorRecord )

IfAbruptCloseIterator는 Iterator Record를 사용하는 알고리즘 단계 시퀀스의 축약형이다. 다음 형식의 알고리즘 단계:

  1. IfAbruptCloseIterator(value, iteratorRecord).

은 다음과 같은 의미이다:

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

7.4.14 AsyncIteratorClose ( iteratorRecord, completion )

The abstract operation AsyncIteratorClose takes arguments iteratorRecord (an Iterator Record) and completion (a Completion Record) and returns a Completion Record. 이것은 async iterator에게, 완료 상태에 도달했을 때 통상 수행했을 동작을 수행해야 함을 알리는 데 사용된다. It performs the following steps when called:

  1. Assert: iteratorRecord.[[Iterator]]는 Object이다.
  2. iteratoriteratorRecord.[[Iterator]]라고 하자.
  3. innerResultCompletion(GetMethod(iterator, "return"))라고 하자.
  4. innerResultnormal completion이면,
    1. returninnerResult.[[Value]]라고 하자.
    2. returnundefined이면, ? completion을 반환한다.
    3. innerResultCompletion(Call(return, iterator))로 설정한다.
    4. innerResultnormal completion이면, innerResultCompletion(Await(innerResult.[[Value]]))로 설정한다.
  5. completionthrow completion이면, ? completion을 반환한다.
  6. innerResultthrow completion이면, ? innerResult를 반환한다.
  7. innerResult.[[Value]]가 Object가 아니면, TypeError 예외를 던진다.
  8. completion을 반환한다.

7.4.15 IfAbruptCloseAsyncIterator ( value, iteratorRecord )

IfAbruptCloseAsyncIterator는 Iterator Record를 사용하는 알고리즘 단계 시퀀스의 축약형이다. 다음 형식의 알고리즘 단계:

  1. IfAbruptCloseAsyncIterator(value, iteratorRecord).

은 다음과 같은 의미이다:

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

7.4.16 CreateIteratorResultObject ( value, done )

The abstract operation CreateIteratorResultObject takes arguments value (an ECMAScript language value) and done (a Boolean) and returns an Object that conforms to the IteratorResult interface. 이것은 IteratorResult 인터페이스에 부합하는 객체를 생성한다. 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.17 CreateListIteratorRecord ( list )

The abstract operation CreateListIteratorRecord takes argument list (a List of ECMAScript language values) and returns an Iterator Record. 이것은 [[NextMethod]]list의 연속된 요소를 반환하는 Iterator Record를 생성한다. It performs the following steps when called:

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

이 list iterator 객체는 ECMAScript 코드에서 직접 접근할 수 없다.

7.4.18 IteratorToList ( iteratorRecord )

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

  1. values를 새로운 빈 List라고 하자.
  2. 다음을 반복한다.
    1. next를 ? IteratorStepValue(iteratorRecord)라고 하자.
    2. nextdone이면,
      1. values를 반환한다.
    3. nextvalues에 추가한다.

8 구문 지시 연산

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

8.1 Runtime Semantics: Evaluation

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

Note
이 연산의 정의들은 이 명세의 "ECMAScript Language" 절들에 분산되어 있다. 각 정의는 관련 production의 정의 위치 뒤에 나타난다.

8.2 스코프 분석

8.2.1 Static Semantics: BoundNames

The syntax-directed operation BoundNames takes no arguments and returns a List of Strings.

Note

"*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. 유일한 요소가 IdentifierStringValueList를 반환한다.
BindingIdentifier : yield
  1. « "yield" »를 반환한다.
BindingIdentifier : await
  1. « "await" »를 반환한다.
LexicalDeclaration : LetOrConst BindingList ;
  1. BindingListBoundNames를 반환한다.
BindingList : BindingList , LexicalBinding
  1. names1BindingListBoundNames라고 하자.
  2. names2LexicalBindingBoundNames라고 하자.
  3. names1names2list-concatenation을 반환한다.
LexicalBinding : BindingIdentifier Initializeropt
  1. BindingIdentifierBoundNames를 반환한다.
LexicalBinding : BindingPattern Initializer
  1. BindingPatternBoundNames를 반환한다.
VariableDeclarationList : VariableDeclarationList , VariableDeclaration
  1. names1VariableDeclarationListBoundNames라고 하자.
  2. names2VariableDeclarationBoundNames라고 하자.
  3. names1names2list-concatenation을 반환한다.
VariableDeclaration : BindingIdentifier Initializeropt
  1. BindingIdentifierBoundNames를 반환한다.
VariableDeclaration : BindingPattern Initializer
  1. BindingPatternBoundNames를 반환한다.
ObjectBindingPattern : { }
  1. 새로운 빈 List를 반환한다.
ObjectBindingPattern : { BindingPropertyList , BindingRestProperty }
  1. names1BindingPropertyListBoundNames라고 하자.
  2. names2BindingRestPropertyBoundNames라고 하자.
  3. names1names2list-concatenation을 반환한다.
ArrayBindingPattern : [ Elisionopt ]
  1. 새로운 빈 List를 반환한다.
ArrayBindingPattern : [ Elisionopt BindingRestElement ]
  1. BindingRestElementBoundNames를 반환한다.
ArrayBindingPattern : [ BindingElementList , Elisionopt ]
  1. BindingElementListBoundNames를 반환한다.
ArrayBindingPattern : [ BindingElementList , Elisionopt BindingRestElement ]
  1. names1BindingElementListBoundNames라고 하자.
  2. names2BindingRestElementBoundNames라고 하자.
  3. names1names2list-concatenation을 반환한다.
BindingPropertyList : BindingPropertyList , BindingProperty
  1. names1BindingPropertyListBoundNames라고 하자.
  2. names2BindingPropertyBoundNames라고 하자.
  3. names1names2list-concatenation을 반환한다.
BindingElementList : BindingElementList , BindingElisionElement
  1. names1BindingElementListBoundNames라고 하자.
  2. names2BindingElisionElementBoundNames라고 하자.
  3. names1names2list-concatenation을 반환한다.
BindingElisionElement : Elisionopt BindingElement
  1. BindingElementBoundNames를 반환한다.
BindingProperty : PropertyName : BindingElement
  1. BindingElementBoundNames를 반환한다.
SingleNameBinding : BindingIdentifier Initializeropt
  1. BindingIdentifierBoundNames를 반환한다.
BindingElement : BindingPattern Initializeropt
  1. BindingPatternBoundNames를 반환한다.
ForDeclaration : LetOrConst ForBinding
  1. ForBindingBoundNames를 반환한다.
FunctionDeclaration : function BindingIdentifier ( FormalParameters ) { FunctionBody }
  1. BindingIdentifierBoundNames를 반환한다.
FunctionDeclaration : function ( FormalParameters ) { FunctionBody }
  1. « "*default*" »를 반환한다.
FormalParameters : [empty]
  1. 새로운 빈 List를 반환한다.
FormalParameters : FormalParameterList , FunctionRestParameter
  1. names1FormalParameterListBoundNames라고 하자.
  2. names2FunctionRestParameterBoundNames라고 하자.
  3. names1names2list-concatenation을 반환한다.
FormalParameterList : FormalParameterList , FormalParameter
  1. names1FormalParameterListBoundNames라고 하자.
  2. names2FormalParameterBoundNames라고 하자.
  3. names1names2list-concatenation을 반환한다.
ArrowParameters : CoverParenthesizedExpressionAndArrowParameterList
  1. formalsCoverParenthesizedExpressionAndArrowParameterList가 덮고 있는 ArrowFormalParameters라고 하자.
  2. formalsBoundNames를 반환한다.
GeneratorDeclaration : function * BindingIdentifier ( FormalParameters ) { GeneratorBody }
  1. BindingIdentifierBoundNames를 반환한다.
GeneratorDeclaration : function * ( FormalParameters ) { GeneratorBody }
  1. « "*default*" »를 반환한다.
AsyncGeneratorDeclaration : async function * BindingIdentifier ( FormalParameters ) { AsyncGeneratorBody }
  1. BindingIdentifierBoundNames를 반환한다.
AsyncGeneratorDeclaration : async function * ( FormalParameters ) { AsyncGeneratorBody }
  1. « "*default*" »를 반환한다.
ClassDeclaration : class BindingIdentifier ClassTail
  1. BindingIdentifierBoundNames를 반환한다.
ClassDeclaration : class ClassTail
  1. « "*default*" »를 반환한다.
AsyncFunctionDeclaration : async function BindingIdentifier ( FormalParameters ) { AsyncFunctionBody }
  1. BindingIdentifierBoundNames를 반환한다.
AsyncFunctionDeclaration : async function ( FormalParameters ) { AsyncFunctionBody }
  1. « "*default*" »를 반환한다.
CoverCallExpressionAndAsyncArrowHead : MemberExpression Arguments
  1. headCoverCallExpressionAndAsyncArrowHead가 덮고 있는 AsyncArrowHead라고 하자.
  2. headBoundNames를 반환한다.
ImportDeclaration : import ImportClause FromClause WithClauseopt ;
  1. ImportClauseBoundNames를 반환한다.
ImportDeclaration : import ModuleSpecifier WithClauseopt ;
  1. 새로운 빈 List를 반환한다.
ImportClause : ImportedDefaultBinding , NameSpaceImport
  1. names1ImportedDefaultBindingBoundNames라고 하자.
  2. names2NameSpaceImportBoundNames라고 하자.
  3. names1names2list-concatenation을 반환한다.
ImportClause : ImportedDefaultBinding , NamedImports
  1. names1ImportedDefaultBindingBoundNames라고 하자.
  2. names2NamedImportsBoundNames라고 하자.
  3. names1names2list-concatenation을 반환한다.
NamedImports : { }
  1. 새로운 빈 List를 반환한다.
ImportsList : ImportsList , ImportSpecifier
  1. names1ImportsListBoundNames라고 하자.
  2. names2ImportSpecifierBoundNames라고 하자.
  3. names1names2list-concatenation을 반환한다.
ImportSpecifier : ModuleExportName as ImportedBinding
  1. ImportedBindingBoundNames를 반환한다.
ExportDeclaration : export ExportFromClause FromClause WithClauseopt ; export NamedExports ;
  1. 새로운 빈 List를 반환한다.
ExportDeclaration : export VariableStatement
  1. VariableStatementBoundNames를 반환한다.
ExportDeclaration : export Declaration
  1. DeclarationBoundNames를 반환한다.
ExportDeclaration : export default HoistableDeclaration
  1. declarationNamesHoistableDeclarationBoundNames라고 하자.
  2. declarationNames"*default*" 요소를 포함하지 않으면, "*default*"declarationNames에 추가한다.
  3. declarationNames을 반환한다.
ExportDeclaration : export default ClassDeclaration
  1. declarationNamesClassDeclarationBoundNames라고 하자.
  2. declarationNames"*default*" 요소를 포함하지 않으면, "*default*"declarationNames에 추가한다.
  3. declarationNames을 반환한다.
ExportDeclaration : export default AssignmentExpression ;
  1. « "*default*" »를 반환한다.

8.2.2 Static Semantics: DeclarationPart

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

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

8.2.3 Static Semantics: IsConstantDeclaration

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

LexicalDeclaration : LetOrConst BindingList ;
  1. LetOrConstIsConstantDeclaration을 반환한다.
LetOrConst : let
  1. false를 반환한다.
LetOrConst : const
  1. true를 반환한다.
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 Static Semantics: LexicallyDeclaredNames

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

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

Script의 최상위 수준에서는 함수 선언이 lexical declaration처럼 아니라 var declaration처럼 취급된다.

Note 2

Module의 LexicallyDeclaredNames에는 그 모듈의 모든 imported binding 이름이 포함된다.

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

Module의 최상위 수준에서는 함수 선언이 var declaration처럼이 아니라 lexical declaration처럼 취급된다.

8.2.5 Static Semantics: LexicallyScopedDeclarations

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

StatementList : StatementList StatementListItem
  1. declarations1StatementListLexicallyScopedDeclarations라고 하자.
  2. declarations2StatementListItemLexicallyScopedDeclarations라고 하자.
  3. declarations1declarations2list-concatenation을 반환한다.
StatementListItem : Statement
  1. Statement Statement : LabelledStatement 이면, LabelledStatementLexicallyScopedDeclarations를 반환한다.
  2. 새로운 빈 List를 반환한다.
StatementListItem : Declaration
  1. 유일한 요소가 DeclarationDeclarationPartList를 반환한다.
CaseBlock : { }
  1. 새로운 빈 List를 반환한다.
CaseBlock : { CaseClausesopt DefaultClause CaseClausesopt }
  1. 첫 번째 CaseClauses가 존재하면, declarations1을 첫 번째 CaseClausesLexicallyScopedDeclarations라고 하자.
  2. 그렇지 않으면, declarations1을 새로운 빈 List라고 하자.
  3. declarations2DefaultClauseLexicallyScopedDeclarations라고 하자.
  4. 두 번째 CaseClauses가 존재하면, declarations3을 두 번째 CaseClausesLexicallyScopedDeclarations라고 하자.
  5. 그렇지 않으면, declarations3을 새로운 빈 List라고 하자.
  6. declarations1, declarations2, declarations3list-concatenation을 반환한다.
CaseClauses : CaseClauses CaseClause
  1. declarations1CaseClausesLexicallyScopedDeclarations라고 하자.
  2. declarations2CaseClauseLexicallyScopedDeclarations라고 하자.
  3. declarations1declarations2list-concatenation을 반환한다.
CaseClause : case Expression : StatementListopt
  1. StatementList가 존재하면, StatementListLexicallyScopedDeclarations를 반환한다.
  2. 새로운 빈 List를 반환한다.
DefaultClause : default : StatementListopt
  1. StatementList가 존재하면, StatementListLexicallyScopedDeclarations를 반환한다.
  2. 새로운 빈 List를 반환한다.
LabelledStatement : LabelIdentifier : LabelledItem
  1. LabelledItemLexicallyScopedDeclarations를 반환한다.
LabelledItem : Statement
  1. 새로운 빈 List를 반환한다.
LabelledItem : FunctionDeclaration
  1. « FunctionDeclaration »를 반환한다.
FunctionStatementList : [empty]
  1. 새로운 빈 List를 반환한다.
FunctionStatementList : StatementList
  1. StatementListTopLevelLexicallyScopedDeclarations를 반환한다.
ClassStaticBlockStatementList : [empty]
  1. 새로운 빈 List를 반환한다.
ClassStaticBlockStatementList : StatementList
  1. StatementListTopLevelLexicallyScopedDeclarations를 반환한다.
ConciseBody : ExpressionBody
  1. 새로운 빈 List를 반환한다.
AsyncConciseBody : ExpressionBody
  1. 새로운 빈 List를 반환한다.
Script : [empty]
  1. 새로운 빈 List를 반환한다.
ScriptBody : StatementList
  1. StatementListTopLevelLexicallyScopedDeclarations를 반환한다.
Module : [empty]
  1. 새로운 빈 List를 반환한다.
ModuleItemList : ModuleItemList ModuleItem
  1. declarations1ModuleItemListLexicallyScopedDeclarations라고 하자.
  2. declarations2ModuleItemLexicallyScopedDeclarations라고 하자.
  3. declarations1declarations2list-concatenation을 반환한다.
ModuleItem : ImportDeclaration
  1. 새로운 빈 List를 반환한다.
ExportDeclaration : export ExportFromClause FromClause WithClauseopt ; export NamedExports ; export VariableStatement
  1. 새로운 빈 List를 반환한다.
ExportDeclaration : export Declaration
  1. 유일한 요소가 DeclarationDeclarationPartList를 반환한다.
ExportDeclaration : export default HoistableDeclaration
  1. 유일한 요소가 HoistableDeclarationDeclarationPartList를 반환한다.
ExportDeclaration : export default ClassDeclaration
  1. 유일한 요소가 ClassDeclarationList를 반환한다.
ExportDeclaration : export default AssignmentExpression ;
  1. 유일한 요소가 이 ExportDeclarationList를 반환한다.

8.2.6 Static Semantics: VarDeclaredNames

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

Statement : EmptyStatement ExpressionStatement ContinueStatement BreakStatement ReturnStatement ThrowStatement DebuggerStatement
  1. 새로운 빈 List를 반환한다.
Block : { }
  1. 새로운 빈 List를 반환한다.
StatementList : StatementList StatementListItem
  1. names1StatementListVarDeclaredNames라고 하자.
  2. names2StatementListItemVarDeclaredNames라고 하자.
  3. names1names2list-concatenation을 반환한다.
StatementListItem : Declaration
  1. 새로운 빈 List를 반환한다.
VariableStatement : var VariableDeclarationList ;
  1. VariableDeclarationListBoundNames를 반환한다.
IfStatement : if ( Expression ) Statement else Statement
  1. names1을 첫 번째 StatementVarDeclaredNames라고 하자.
  2. names2를 두 번째 StatementVarDeclaredNames라고 하자.
  3. names1names2list-concatenation을 반환한다.
IfStatement : if ( Expression ) Statement
  1. StatementVarDeclaredNames를 반환한다.
DoWhileStatement : do Statement while ( Expression ) ;
  1. StatementVarDeclaredNames를 반환한다.
WhileStatement : while ( Expression ) Statement
  1. StatementVarDeclaredNames를 반환한다.
ForStatement : for ( Expressionopt ; Expressionopt ; Expressionopt ) Statement
  1. StatementVarDeclaredNames를 반환한다.
ForStatement : for ( var VariableDeclarationList ; Expressionopt ; Expressionopt ) Statement
  1. names1VariableDeclarationListBoundNames라고 하자.
  2. names2StatementVarDeclaredNames라고 하자.
  3. names1names2list-concatenation을 반환한다.
ForStatement : for ( LexicalDeclaration Expressionopt ; Expressionopt ) Statement
  1. StatementVarDeclaredNames를 반환한다.
ForInOfStatement : for ( LeftHandSideExpression in Expression ) Statement for ( ForDeclaration in Expression ) Statement for ( LeftHandSideExpression of AssignmentExpression ) Statement for ( ForDeclaration of AssignmentExpression ) Statement for await ( LeftHandSideExpression of AssignmentExpression ) Statement for await ( ForDeclaration of AssignmentExpression ) Statement
  1. StatementVarDeclaredNames를 반환한다.
ForInOfStatement : for ( var ForBinding in Expression ) Statement for ( var ForBinding of AssignmentExpression ) Statement for await ( var ForBinding of AssignmentExpression ) Statement
  1. names1ForBindingBoundNames라고 하자.
  2. names2StatementVarDeclaredNames라고 하자.
  3. names1names2list-concatenation을 반환한다.
Note

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

WithStatement : with ( Expression ) Statement
  1. StatementVarDeclaredNames를 반환한다.
SwitchStatement : switch ( Expression ) CaseBlock
  1. CaseBlockVarDeclaredNames를 반환한다.
CaseBlock : { }
  1. 새로운 빈 List를 반환한다.
CaseBlock : { CaseClausesopt DefaultClause CaseClausesopt }
  1. 첫 번째 CaseClauses가 존재하면, names1을 첫 번째 CaseClausesVarDeclaredNames라고 하자.
  2. 그렇지 않으면, names1을 새로운 빈 List라고 하자.
  3. names2DefaultClauseVarDeclaredNames라고 하자.
  4. 두 번째 CaseClauses가 존재하면, names3을 두 번째 CaseClausesVarDeclaredNames라고 하자.
  5. 그렇지 않으면, names3을 새로운 빈 List라고 하자.
  6. names1, names2, names3list-concatenation을 반환한다.
CaseClauses : CaseClauses CaseClause
  1. names1CaseClausesVarDeclaredNames라고 하자.
  2. names2CaseClauseVarDeclaredNames라고 하자.
  3. names1names2list-concatenation을 반환한다.
CaseClause : case Expression : StatementListopt
  1. StatementList가 존재하면, StatementListVarDeclaredNames를 반환한다.
  2. 새로운 빈 List를 반환한다.
DefaultClause : default : StatementListopt
  1. StatementList가 존재하면, StatementListVarDeclaredNames를 반환한다.
  2. 새로운 빈 List를 반환한다.
LabelledStatement : LabelIdentifier : LabelledItem
  1. LabelledItemVarDeclaredNames를 반환한다.
LabelledItem : FunctionDeclaration
  1. 새로운 빈 List를 반환한다.
TryStatement : try Block Catch
  1. names1BlockVarDeclaredNames라고 하자.
  2. names2CatchVarDeclaredNames라고 하자.
  3. names1names2list-concatenation을 반환한다.
TryStatement : try Block Finally
  1. names1BlockVarDeclaredNames라고 하자.
  2. names2FinallyVarDeclaredNames라고 하자.
  3. names1names2list-concatenation을 반환한다.
TryStatement : try Block Catch Finally
  1. names1BlockVarDeclaredNames라고 하자.
  2. names2CatchVarDeclaredNames라고 하자.
  3. names3FinallyVarDeclaredNames라고 하자.
  4. names1, names2, names3list-concatenation을 반환한다.
Catch : catch ( CatchParameter ) Block
  1. BlockVarDeclaredNames를 반환한다.
FunctionStatementList : [empty]
  1. 새로운 빈 List를 반환한다.
FunctionStatementList : StatementList
  1. StatementListTopLevelVarDeclaredNames를 반환한다.
ClassStaticBlockStatementList : [empty]
  1. 새로운 빈 List를 반환한다.
ClassStaticBlockStatementList : StatementList
  1. StatementListTopLevelVarDeclaredNames를 반환한다.
ConciseBody : ExpressionBody
  1. 새로운 빈 List를 반환한다.
AsyncConciseBody : ExpressionBody
  1. 새로운 빈 List를 반환한다.
Script : [empty]
  1. 새로운 빈 List를 반환한다.
ScriptBody : StatementList
  1. StatementListTopLevelVarDeclaredNames를 반환한다.
ModuleItemList : ModuleItemList ModuleItem
  1. names1ModuleItemListVarDeclaredNames라고 하자.
  2. names2ModuleItemVarDeclaredNames라고 하자.
  3. names1names2list-concatenation을 반환한다.
ModuleItem : ImportDeclaration
  1. 새로운 빈 List를 반환한다.
ModuleItem : ExportDeclaration
  1. ExportDeclarationexport VariableStatement이면, ExportDeclarationBoundNames를 반환한다.
  2. 새로운 빈 List를 반환한다.

8.2.7 Static Semantics: VarScopedDeclarations

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

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

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

WithStatement : with ( Expression ) Statement
  1. StatementVarScopedDeclarations를 반환한다.
SwitchStatement : switch ( Expression ) CaseBlock
  1. CaseBlockVarScopedDeclarations를 반환한다.
CaseBlock : { }
  1. 새로운 빈 List를 반환한다.
CaseBlock : { CaseClausesopt DefaultClause CaseClausesopt }
  1. 첫 번째 CaseClauses가 존재하면, declarations1을 첫 번째 CaseClausesVarScopedDeclarations라고 하자.
  2. 그렇지 않으면, declarations1을 새로운 빈 List라고 하자.
  3. declarations2DefaultClauseVarScopedDeclarations라고 하자.
  4. 두 번째 CaseClauses가 존재하면, declarations3을 두 번째 CaseClausesVarScopedDeclarations라고 하자.
  5. 그렇지 않으면, declarations3을 새로운 빈 List라고 하자.
  6. declarations1, declarations2, declarations3list-concatenation을 반환한다.
CaseClauses : CaseClauses CaseClause
  1. declarations1CaseClausesVarScopedDeclarations라고 하자.
  2. declarations2CaseClauseVarScopedDeclarations라고 하자.
  3. declarations1declarations2list-concatenation을 반환한다.
CaseClause : case Expression : StatementListopt
  1. StatementList가 존재하면, StatementListVarScopedDeclarations를 반환한다.
  2. 새로운 빈 List를 반환한다.
DefaultClause : default : StatementListopt
  1. StatementList가 존재하면, StatementListVarScopedDeclarations를 반환한다.
  2. 새로운 빈 List를 반환한다.
LabelledStatement : LabelIdentifier : LabelledItem
  1. LabelledItemVarScopedDeclarations를 반환한다.
LabelledItem : FunctionDeclaration
  1. 새로운 빈 List를 반환한다.
TryStatement : try Block Catch
  1. declarations1BlockVarScopedDeclarations라고 하자.
  2. declarations2CatchVarScopedDeclarations라고 하자.
  3. declarations1declarations2list-concatenation을 반환한다.
TryStatement : try Block Finally
  1. declarations1BlockVarScopedDeclarations라고 하자.
  2. declarations2FinallyVarScopedDeclarations라고 하자.
  3. declarations1declarations2list-concatenation을 반환한다.
TryStatement : try Block Catch Finally
  1. declarations1BlockVarScopedDeclarations라고 하자.
  2. declarations2CatchVarScopedDeclarations라고 하자.
  3. declarations3FinallyVarScopedDeclarations라고 하자.
  4. declarations1, declarations2, declarations3list-concatenation을 반환한다.
Catch : catch ( CatchParameter ) Block
  1. BlockVarScopedDeclarations를 반환한다.
FunctionStatementList : [empty]
  1. 새로운 빈 List를 반환한다.
FunctionStatementList : StatementList
  1. StatementListTopLevelVarScopedDeclarations를 반환한다.
ClassStaticBlockStatementList : [empty]
  1. 새로운 빈 List를 반환한다.
ClassStaticBlockStatementList : StatementList
  1. StatementListTopLevelVarScopedDeclarations를 반환한다.
ConciseBody : ExpressionBody
  1. 새로운 빈 List를 반환한다.
AsyncConciseBody : ExpressionBody
  1. 새로운 빈 List를 반환한다.
Script : [empty]
  1. 새로운 빈 List를 반환한다.
ScriptBody : StatementList
  1. StatementListTopLevelVarScopedDeclarations를 반환한다.
Module : [empty]
  1. 새로운 빈 List를 반환한다.
ModuleItemList : ModuleItemList ModuleItem
  1. declarations1ModuleItemListVarScopedDeclarations라고 하자.
  2. declarations2ModuleItemVarScopedDeclarations라고 하자.
  3. declarations1declarations2list-concatenation을 반환한다.
ModuleItem : ImportDeclaration
  1. 새로운 빈 List를 반환한다.
ModuleItem : ExportDeclaration
  1. ExportDeclarationexport VariableStatement이면, VariableStatementVarScopedDeclarations를 반환한다.
  2. 새로운 빈 List를 반환한다.

8.2.8 Static Semantics: TopLevelLexicallyDeclaredNames

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

StatementList : StatementList StatementListItem
  1. names1StatementListTopLevelLexicallyDeclaredNames라고 하자.
  2. names2StatementListItemTopLevelLexicallyDeclaredNames라고 하자.
  3. names1names2list-concatenation을 반환한다.
StatementListItem : Statement
  1. 새로운 빈 List를 반환한다.
StatementListItem : Declaration
  1. Declaration Declaration : HoistableDeclaration 이면,
    1. 새로운 빈 List를 반환한다.
  2. DeclarationBoundNames를 반환한다.
Note

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

8.2.9 Static Semantics: TopLevelLexicallyScopedDeclarations

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

StatementList : StatementList StatementListItem
  1. declarations1StatementListTopLevelLexicallyScopedDeclarations라고 하자.
  2. declarations2StatementListItemTopLevelLexicallyScopedDeclarations라고 하자.
  3. declarations1declarations2list-concatenation을 반환한다.
StatementListItem : Statement
  1. 새로운 빈 List를 반환한다.
StatementListItem : Declaration
  1. Declaration Declaration : HoistableDeclaration 이면,
    1. 새로운 빈 List를 반환한다.
  2. « Declaration »를 반환한다.

8.2.10 Static Semantics: TopLevelVarDeclaredNames

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

StatementList : StatementList StatementListItem
  1. names1StatementListTopLevelVarDeclaredNames라고 하자.
  2. names2StatementListItemTopLevelVarDeclaredNames라고 하자.
  3. names1names2list-concatenation을 반환한다.
StatementListItem : Declaration
  1. Declaration Declaration : HoistableDeclaration 이면,
    1. HoistableDeclarationBoundNames를 반환한다.
  2. 새로운 빈 List를 반환한다.
StatementListItem : Statement
  1. Statement Statement : LabelledStatement 이면, StatementTopLevelVarDeclaredNames를 반환한다.
  2. StatementVarDeclaredNames를 반환한다.
Note

함수나 스크립트의 최상위 수준에서는 내부 함수 선언이 var declaration처럼 취급된다.

LabelledStatement : LabelIdentifier : LabelledItem
  1. LabelledItemTopLevelVarDeclaredNames를 반환한다.
LabelledItem : Statement
  1. Statement Statement : LabelledStatement 이면, StatementTopLevelVarDeclaredNames를 반환한다.
  2. StatementVarDeclaredNames를 반환한다.
LabelledItem : FunctionDeclaration
  1. FunctionDeclarationBoundNames를 반환한다.

8.2.11 Static Semantics: TopLevelVarScopedDeclarations

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

StatementList : StatementList StatementListItem
  1. declarations1StatementListTopLevelVarScopedDeclarations라고 하자.
  2. declarations2StatementListItemTopLevelVarScopedDeclarations라고 하자.
  3. declarations1declarations2list-concatenation을 반환한다.
StatementListItem : Statement
  1. Statement Statement : LabelledStatement 이면, StatementTopLevelVarScopedDeclarations를 반환한다.
  2. StatementVarScopedDeclarations를 반환한다.
StatementListItem : Declaration
  1. Declaration Declaration : HoistableDeclaration 이면,
    1. declarationHoistableDeclarationDeclarationPart라고 하자.
    2. « declaration »를 반환한다.
  2. 새로운 빈 List를 반환한다.
LabelledStatement : LabelIdentifier : LabelledItem
  1. LabelledItemTopLevelVarScopedDeclarations를 반환한다.
LabelledItem : Statement
  1. Statement Statement : LabelledStatement 이면, StatementTopLevelVarScopedDeclarations를 반환한다.
  2. StatementVarScopedDeclarations를 반환한다.
LabelledItem : FunctionDeclaration
  1. « FunctionDeclaration »를 반환한다.

8.3 레이블

8.3.1 Static Semantics: ContainsDuplicateLabels

The syntax-directed operation ContainsDuplicateLabels takes argument labelSet (a List of Strings) and returns a Boolean. It is defined piecewise over the following productions:

Statement : VariableStatement EmptyStatement ExpressionStatement ContinueStatement BreakStatement ReturnStatement ThrowStatement DebuggerStatement Block : { } StatementListItem : Declaration
  1. false를 반환한다.
StatementList : StatementList StatementListItem
  1. hasDuplicates를 인수 labelSet을 사용한 StatementListContainsDuplicateLabels라고 하자.
  2. hasDuplicatestrue이면, true를 반환한다.
  3. 인수 labelSet을 사용한 StatementListItemContainsDuplicateLabels를 반환한다.
IfStatement : if ( Expression ) Statement else Statement
  1. hasDuplicate를 인수 labelSet을 사용한 첫 번째 StatementContainsDuplicateLabels라고 하자.
  2. hasDuplicatetrue이면, true를 반환한다.
  3. 인수 labelSet을 사용한 두 번째 StatementContainsDuplicateLabels를 반환한다.
IfStatement : if ( Expression ) Statement
  1. 인수 labelSet을 사용한 StatementContainsDuplicateLabels를 반환한다.
DoWhileStatement : do Statement while ( Expression ) ;
  1. 인수 labelSet을 사용한 StatementContainsDuplicateLabels를 반환한다.
WhileStatement : while ( Expression ) Statement
  1. 인수 labelSet을 사용한 StatementContainsDuplicateLabels를 반환한다.
ForStatement : for ( Expressionopt ; Expressionopt ; Expressionopt ) Statement for ( var VariableDeclarationList ; Expressionopt ; Expressionopt ) Statement for ( LexicalDeclaration Expressionopt ; Expressionopt ) Statement
  1. 인수 labelSet을 사용한 StatementContainsDuplicateLabels를 반환한다.
ForInOfStatement : for ( LeftHandSideExpression in Expression ) Statement for ( var ForBinding in Expression ) Statement for ( ForDeclaration in Expression ) Statement for ( LeftHandSideExpression of AssignmentExpression ) Statement for ( var ForBinding of AssignmentExpression ) Statement for ( ForDeclaration of AssignmentExpression ) Statement for await ( LeftHandSideExpression of AssignmentExpression ) Statement for await ( var ForBinding of AssignmentExpression ) Statement for await ( ForDeclaration of AssignmentExpression ) Statement
  1. 인수 labelSet을 사용한 StatementContainsDuplicateLabels를 반환한다.
Note

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

WithStatement : with ( Expression ) Statement
  1. 인수 labelSet을 사용한 StatementContainsDuplicateLabels를 반환한다.
SwitchStatement : switch ( Expression ) CaseBlock
  1. 인수 labelSet을 사용한 CaseBlockContainsDuplicateLabels를 반환한다.
CaseBlock : { }
  1. false를 반환한다.
CaseBlock : { CaseClausesopt DefaultClause CaseClausesopt }
  1. 첫 번째 CaseClauses가 존재하면,
    1. 인수 labelSet을 사용한 첫 번째 CaseClausesContainsDuplicateLabelstrue이면, true를 반환한다.
  2. 인수 labelSet을 사용한 DefaultClauseContainsDuplicateLabelstrue이면, true를 반환한다.
  3. 두 번째 CaseClauses가 존재하지 않으면, false를 반환한다.
  4. 인수 labelSet을 사용한 두 번째 CaseClausesContainsDuplicateLabels를 반환한다.
CaseClauses : CaseClauses CaseClause
  1. hasDuplicates를 인수 labelSet을 사용한 CaseClausesContainsDuplicateLabels라고 하자.
  2. hasDuplicatestrue이면, true를 반환한다.
  3. 인수 labelSet을 사용한 CaseClauseContainsDuplicateLabels를 반환한다.
CaseClause : case Expression : StatementListopt
  1. StatementList가 존재하면, 인수 labelSet을 사용한 StatementListContainsDuplicateLabels를 반환한다.
  2. false를 반환한다.
DefaultClause : default : StatementListopt
  1. StatementList가 존재하면, 인수 labelSet을 사용한 StatementListContainsDuplicateLabels를 반환한다.
  2. false를 반환한다.
LabelledStatement : LabelIdentifier : LabelledItem
  1. labelLabelIdentifierStringValue라고 하자.
  2. labelSetlabel을 포함하면, true를 반환한다.
  3. newLabelSetlabelSet과 « label »의 list-concatenation이라고 하자.
  4. 인수 newLabelSet을 사용한 LabelledItemContainsDuplicateLabels를 반환한다.
LabelledItem : FunctionDeclaration
  1. false를 반환한다.
TryStatement : try Block Catch
  1. hasDuplicates를 인수 labelSet을 사용한 BlockContainsDuplicateLabels라고 하자.
  2. hasDuplicatestrue이면, true를 반환한다.
  3. 인수 labelSet을 사용한 CatchContainsDuplicateLabels를 반환한다.
TryStatement : try Block Finally
  1. hasDuplicates를 인수 labelSet을 사용한 BlockContainsDuplicateLabels라고 하자.
  2. hasDuplicatestrue이면, true를 반환한다.
  3. 인수 labelSet을 사용한 FinallyContainsDuplicateLabels를 반환한다.
TryStatement : try Block Catch Finally
  1. 인수 labelSet을 사용한 BlockContainsDuplicateLabelstrue이면, true를 반환한다.
  2. 인수 labelSet을 사용한 CatchContainsDuplicateLabelstrue이면, true를 반환한다.
  3. 인수 labelSet을 사용한 FinallyContainsDuplicateLabels를 반환한다.
Catch : catch ( CatchParameter ) Block
  1. 인수 labelSet을 사용한 BlockContainsDuplicateLabels를 반환한다.
FunctionStatementList : [empty]
  1. false를 반환한다.
ClassStaticBlockStatementList : [empty]
  1. false를 반환한다.
ModuleItemList : ModuleItemList ModuleItem
  1. hasDuplicates를 인수 labelSet을 사용한 ModuleItemListContainsDuplicateLabels라고 하자.
  2. hasDuplicatestrue이면, true를 반환한다.
  3. 인수 labelSet을 사용한 ModuleItemContainsDuplicateLabels를 반환한다.
ModuleItem : ImportDeclaration ExportDeclaration
  1. false를 반환한다.

8.3.2 Static Semantics: ContainsUndefinedBreakTarget

The syntax-directed operation ContainsUndefinedBreakTarget takes argument labelSet (a List of Strings) and returns a Boolean. It is defined piecewise over the following productions:

Statement : VariableStatement EmptyStatement ExpressionStatement ContinueStatement ReturnStatement ThrowStatement DebuggerStatement Block : { } StatementListItem : Declaration
  1. false를 반환한다.
StatementList : StatementList StatementListItem
  1. hasUndefinedLabels를 인수 labelSet을 사용한 StatementListContainsUndefinedBreakTarget이라고 하자.
  2. hasUndefinedLabelstrue이면, true를 반환한다.
  3. 인수 labelSet을 사용한 StatementListItemContainsUndefinedBreakTarget을 반환한다.
IfStatement : if ( Expression ) Statement else Statement
  1. hasUndefinedLabels를 인수 labelSet을 사용한 첫 번째 StatementContainsUndefinedBreakTarget이라고 하자.
  2. hasUndefinedLabelstrue이면, true를 반환한다.
  3. 인수 labelSet을 사용한 두 번째 StatementContainsUndefinedBreakTarget을 반환한다.
IfStatement : if ( Expression ) Statement
  1. 인수 labelSet을 사용한 StatementContainsUndefinedBreakTarget을 반환한다.
DoWhileStatement : do Statement while ( Expression ) ;
  1. 인수 labelSet을 사용한 StatementContainsUndefinedBreakTarget을 반환한다.
WhileStatement : while ( Expression ) Statement
  1. 인수 labelSet을 사용한 StatementContainsUndefinedBreakTarget을 반환한다.
ForStatement : for ( Expressionopt ; Expressionopt ; Expressionopt ) Statement for ( var VariableDeclarationList ; Expressionopt ; Expressionopt ) Statement for ( LexicalDeclaration Expressionopt ; Expressionopt ) Statement
  1. 인수 labelSet을 사용한 StatementContainsUndefinedBreakTarget을 반환한다.
ForInOfStatement : for ( LeftHandSideExpression in Expression ) Statement for ( var ForBinding in Expression ) Statement for ( ForDeclaration in Expression ) Statement for ( LeftHandSideExpression of AssignmentExpression ) Statement for ( var ForBinding of AssignmentExpression ) Statement for ( ForDeclaration of AssignmentExpression ) Statement for await ( LeftHandSideExpression of AssignmentExpression ) Statement for await ( var ForBinding of AssignmentExpression ) Statement for await ( ForDeclaration of AssignmentExpression ) Statement
  1. 인수 labelSet을 사용한 StatementContainsUndefinedBreakTarget을 반환한다.
Note

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

BreakStatement : break ;
  1. false를 반환한다.
BreakStatement : break LabelIdentifier ;
  1. labelSetLabelIdentifierStringValue를 포함하면, false를 반환한다.
  2. true를 반환한다.
WithStatement : with ( Expression ) Statement
  1. 인수 labelSet을 사용한 StatementContainsUndefinedBreakTarget을 반환한다.
SwitchStatement : switch ( Expression ) CaseBlock
  1. 인수 labelSet을 사용한 CaseBlockContainsUndefinedBreakTarget을 반환한다.
CaseBlock : { }
  1. false를 반환한다.
CaseBlock : { CaseClausesopt DefaultClause CaseClausesopt }
  1. 첫 번째 CaseClauses가 존재하면,
    1. 인수 labelSet을 사용한 첫 번째 CaseClausesContainsUndefinedBreakTargettrue이면, true를 반환한다.
  2. 인수 labelSet을 사용한 DefaultClauseContainsUndefinedBreakTargettrue이면, true를 반환한다.
  3. 두 번째 CaseClauses가 존재하지 않으면, false를 반환한다.
  4. 인수 labelSet을 사용한 두 번째 CaseClausesContainsUndefinedBreakTarget을 반환한다.
CaseClauses : CaseClauses CaseClause
  1. hasUndefinedLabels를 인수 labelSet을 사용한 CaseClausesContainsUndefinedBreakTarget이라고 하자.
  2. hasUndefinedLabelstrue이면, true를 반환한다.
  3. 인수 labelSet을 사용한 CaseClauseContainsUndefinedBreakTarget을 반환한다.
CaseClause : case Expression : StatementListopt
  1. StatementList가 존재하면, 인수 labelSet을 사용한 StatementListContainsUndefinedBreakTarget을 반환한다.
  2. false를 반환한다.
DefaultClause : default : StatementListopt
  1. StatementList가 존재하면, 인수 labelSet을 사용한 StatementListContainsUndefinedBreakTarget을 반환한다.
  2. false를 반환한다.
LabelledStatement : LabelIdentifier : LabelledItem
  1. labelLabelIdentifierStringValue라고 하자.
  2. newLabelSetlabelSet과 « label »의 list-concatenation이라고 하자.
  3. 인수 newLabelSet을 사용한 LabelledItemContainsUndefinedBreakTarget을 반환한다.
LabelledItem : FunctionDeclaration
  1. false를 반환한다.
TryStatement : try Block Catch
  1. hasUndefinedLabels를 인수 labelSet을 사용한 BlockContainsUndefinedBreakTarget이라고 하자.
  2. hasUndefinedLabelstrue이면, true를 반환한다.
  3. 인수 labelSet을 사용한 CatchContainsUndefinedBreakTarget을 반환한다.
TryStatement : try Block Finally
  1. hasUndefinedLabels를 인수 labelSet을 사용한 BlockContainsUndefinedBreakTarget이라고 하자.
  2. hasUndefinedLabelstrue이면, true를 반환한다.
  3. 인수 labelSet을 사용한 FinallyContainsUndefinedBreakTarget을 반환한다.
TryStatement : try Block Catch Finally
  1. 인수 labelSet을 사용한 BlockContainsUndefinedBreakTargettrue이면, true를 반환한다.
  2. 인수 labelSet을 사용한 CatchContainsUndefinedBreakTargettrue이면, true를 반환한다.
  3. 인수 labelSet을 사용한 FinallyContainsUndefinedBreakTarget을 반환한다.
Catch : catch ( CatchParameter ) Block
  1. 인수 labelSet을 사용한 BlockContainsUndefinedBreakTarget을 반환한다.
FunctionStatementList : [empty]
  1. false를 반환한다.
ClassStaticBlockStatementList : [empty]
  1. false를 반환한다.
ModuleItemList : ModuleItemList ModuleItem
  1. hasUndefinedLabels를 인수 labelSet을 사용한 ModuleItemListContainsUndefinedBreakTarget이라고 하자.
  2. hasUndefinedLabelstrue이면, true를 반환한다.
  3. 인수 labelSet을 사용한 ModuleItemContainsUndefinedBreakTarget을 반환한다.
ModuleItem : ImportDeclaration ExportDeclaration
  1. false를 반환한다.

8.3.3 Static Semantics: ContainsUndefinedContinueTarget

The syntax-directed operation ContainsUndefinedContinueTarget takes arguments iterationSet (a List of Strings) and labelSet (a List of Strings) and returns a Boolean. It is defined piecewise over the following productions:

Statement : VariableStatement EmptyStatement ExpressionStatement BreakStatement ReturnStatement ThrowStatement DebuggerStatement Block : { } StatementListItem : Declaration
  1. false를 반환한다.
Statement : BlockStatement
  1. 인수 iterationSet와 « »를 사용한 BlockStatementContainsUndefinedContinueTarget을 반환한다.
BreakableStatement : IterationStatement
  1. newIterationSetiterationSetlabelSetlist-concatenation이라고 하자.
  2. 인수 newIterationSet와 « »를 사용한 IterationStatementContainsUndefinedContinueTarget을 반환한다.
StatementList : StatementList StatementListItem
  1. hasUndefinedLabels를 인수 iterationSet와 « »를 사용한 StatementListContainsUndefinedContinueTarget이라고 하자.
  2. hasUndefinedLabelstrue이면, true를 반환한다.
  3. 인수 iterationSet와 « »를 사용한 StatementListItemContainsUndefinedContinueTarget을 반환한다.
IfStatement : if ( Expression ) Statement else Statement
  1. hasUndefinedLabels를 인수 iterationSet와 « »를 사용한 첫 번째 StatementContainsUndefinedContinueTarget이라고 하자.
  2. hasUndefinedLabelstrue이면, true를 반환한다.
  3. 인수 iterationSet와 « »를 사용한 두 번째 StatementContainsUndefinedContinueTarget을 반환한다.
IfStatement : if ( Expression ) Statement
  1. 인수 iterationSet와 « »를 사용한 StatementContainsUndefinedContinueTarget을 반환한다.
DoWhileStatement : do Statement while ( Expression ) ;
  1. 인수 iterationSet와 « »를 사용한 StatementContainsUndefinedContinueTarget을 반환한다.
WhileStatement : while ( Expression ) Statement
  1. 인수 iterationSet와 « »를 사용한 StatementContainsUndefinedContinueTarget을 반환한다.
ForStatement : for ( Expressionopt ; Expressionopt ; Expressionopt ) Statement for ( var VariableDeclarationList ; Expressionopt ; Expressionopt ) Statement for ( LexicalDeclaration Expressionopt ; Expressionopt ) Statement
  1. 인수 iterationSet와 « »를 사용한 StatementContainsUndefinedContinueTarget을 반환한다.
ForInOfStatement : for ( LeftHandSideExpression in Expression ) Statement for ( var ForBinding in Expression ) Statement for ( ForDeclaration in Expression ) Statement for ( LeftHandSideExpression of AssignmentExpression ) Statement for ( var ForBinding of AssignmentExpression ) Statement for ( ForDeclaration of AssignmentExpression ) Statement for await ( LeftHandSideExpression of AssignmentExpression ) Statement for await ( var ForBinding of AssignmentExpression ) Statement for await ( ForDeclaration of AssignmentExpression ) Statement
  1. 인수 iterationSet와 « »를 사용한 StatementContainsUndefinedContinueTarget을 반환한다.
Note

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

ContinueStatement : continue ;
  1. false를 반환한다.
ContinueStatement : continue LabelIdentifier ;
  1. iterationSetLabelIdentifierStringValue를 포함하면, false를 반환한다.
  2. true를 반환한다.
WithStatement : with ( Expression ) Statement
  1. 인수 iterationSet와 « »를 사용한 StatementContainsUndefinedContinueTarget을 반환한다.
SwitchStatement : switch ( Expression ) CaseBlock
  1. 인수 iterationSet와 « »를 사용한 CaseBlockContainsUndefinedContinueTarget을 반환한다.
CaseBlock : { }
  1. false를 반환한다.
CaseBlock : { CaseClausesopt DefaultClause CaseClausesopt }
  1. 첫 번째 CaseClauses가 존재하면,
    1. 인수 iterationSet와 « »를 사용한 첫 번째 CaseClausesContainsUndefinedContinueTargettrue이면, true를 반환한다.
  2. 인수 iterationSet와 « »를 사용한 DefaultClauseContainsUndefinedContinueTargettrue이면, true를 반환한다.
  3. 두 번째 CaseClauses가 존재하지 않으면, false를 반환한다.
  4. 인수 iterationSet와 « »를 사용한 두 번째 CaseClausesContainsUndefinedContinueTarget을 반환한다.
CaseClauses : CaseClauses CaseClause
  1. hasUndefinedLabels를 인수 iterationSet와 « »를 사용한 CaseClausesContainsUndefinedContinueTarget이라고 하자.
  2. hasUndefinedLabelstrue이면, true를 반환한다.
  3. 인수 iterationSet와 « »를 사용한 CaseClauseContainsUndefinedContinueTarget을 반환한다.
CaseClause : case Expression : StatementListopt
  1. StatementList가 존재하면, 인수 iterationSet와 « »를 사용한 StatementListContainsUndefinedContinueTarget을 반환한다.
  2. false를 반환한다.
DefaultClause : default : StatementListopt
  1. StatementList가 존재하면, 인수 iterationSet와 « »를 사용한 StatementListContainsUndefinedContinueTarget을 반환한다.
  2. false를 반환한다.
LabelledStatement : LabelIdentifier : LabelledItem
  1. labelLabelIdentifierStringValue라고 하자.
  2. newLabelSetlabelSet과 « label »의 list-concatenation이라고 하자.
  3. 인수 iterationSetnewLabelSet을 사용한 LabelledItemContainsUndefinedContinueTarget을 반환한다.
LabelledItem : FunctionDeclaration
  1. false를 반환한다.
TryStatement : try Block Catch
  1. hasUndefinedLabels를 인수 iterationSet와 « »를 사용한 BlockContainsUndefinedContinueTarget이라고 하자.
  2. hasUndefinedLabelstrue이면, true를 반환한다.
  3. 인수 iterationSet와 « »를 사용한 CatchContainsUndefinedContinueTarget을 반환한다.
TryStatement : try Block Finally
  1. hasUndefinedLabels를 인수 iterationSet와 « »를 사용한 BlockContainsUndefinedContinueTarget이라고 하자.
  2. hasUndefinedLabelstrue이면, true를 반환한다.
  3. 인수 iterationSet와 « »를 사용한 FinallyContainsUndefinedContinueTarget을 반환한다.
TryStatement : try Block Catch Finally
  1. 인수 iterationSet와 « »를 사용한 BlockContainsUndefinedContinueTargettrue이면, true를 반환한다.
  2. 인수 iterationSet와 « »를 사용한 CatchContainsUndefinedContinueTargettrue이면, true를 반환한다.
  3. 인수 iterationSet와 « »를 사용한 FinallyContainsUndefinedContinueTarget을 반환한다.
Catch : catch ( CatchParameter ) Block
  1. 인수 iterationSet와 « »를 사용한 BlockContainsUndefinedContinueTarget을 반환한다.
FunctionStatementList : [empty]
  1. false를 반환한다.
ClassStaticBlockStatementList : [empty]
  1. false를 반환한다.
ModuleItemList : ModuleItemList ModuleItem
  1. hasUndefinedLabels를 인수 iterationSet와 « »를 사용한 ModuleItemListContainsUndefinedContinueTarget이라고 하자.
  2. hasUndefinedLabelstrue이면, true를 반환한다.
  3. 인수 iterationSet와 « »를 사용한 ModuleItemContainsUndefinedContinueTarget을 반환한다.
ModuleItem : ImportDeclaration ExportDeclaration
  1. false를 반환한다.

8.4 함수 이름 추론

8.4.1 Static Semantics: HasName

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

PrimaryExpression : CoverParenthesizedExpressionAndArrowParameterList
  1. exprCoverParenthesizedExpressionAndArrowParameterList가 덮고 있는 ParenthesizedExpression이라고 하자.
  2. exprIsFunctionDefinitionfalse이면, false를 반환한다.
  3. exprHasName을 반환한다.
FunctionExpression : function ( FormalParameters ) { FunctionBody } GeneratorExpression : function * ( FormalParameters ) { GeneratorBody } AsyncGeneratorExpression : async function * ( FormalParameters ) { AsyncGeneratorBody } AsyncFunctionExpression : async function ( FormalParameters ) { AsyncFunctionBody } ArrowFunction : ArrowParameters => ConciseBody AsyncArrowFunction : async AsyncArrowBindingIdentifier => AsyncConciseBody CoverCallExpressionAndAsyncArrowHead => AsyncConciseBody ClassExpression : class ClassTail
  1. false를 반환한다.
FunctionExpression : function BindingIdentifier ( FormalParameters ) { FunctionBody } GeneratorExpression : function * BindingIdentifier ( FormalParameters ) { GeneratorBody } AsyncGeneratorExpression : async function * BindingIdentifier ( FormalParameters ) { AsyncGeneratorBody } AsyncFunctionExpression : async function BindingIdentifier ( FormalParameters ) { AsyncFunctionBody } ClassExpression : class BindingIdentifier ClassTail
  1. true를 반환한다.

8.4.2 Static Semantics: IsFunctionDefinition

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

PrimaryExpression : CoverParenthesizedExpressionAndArrowParameterList
  1. exprCoverParenthesizedExpressionAndArrowParameterList가 덮고 있는 ParenthesizedExpression이라고 하자.
  2. exprIsFunctionDefinition을 반환한다.
PrimaryExpression : this IdentifierReference Literal ArrayLiteral ObjectLiteral RegularExpressionLiteral TemplateLiteral MemberExpression : MemberExpression [ Expression ] MemberExpression . IdentifierName MemberExpression TemplateLiteral SuperProperty MetaProperty new MemberExpression Arguments MemberExpression . PrivateIdentifier NewExpression : new NewExpression LeftHandSideExpression : CallExpression OptionalExpression UpdateExpression : LeftHandSideExpression ++ LeftHandSideExpression -- ++ UnaryExpression -- UnaryExpression UnaryExpression : delete UnaryExpression void UnaryExpression typeof UnaryExpression + UnaryExpression - UnaryExpression ~ UnaryExpression ! UnaryExpression 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 Static Semantics: IsAnonymousFunctionDefinition ( expr )

The abstract operation IsAnonymousFunctionDefinition takes argument expr (an AssignmentExpression Parse Node, an Initializer Parse Node, or an Expression Parse Node) and returns a Boolean. 이것은 자신의 인수가 이름을 바인딩하지 않는 함수 정의인지 결정한다. It performs the following steps when called:

  1. exprIsFunctionDefinitionfalse이면, false를 반환한다.
  2. hasNameexprHasName이라고 하자.
  3. hasNametrue이면, false를 반환한다.
  4. true를 반환한다.

8.4.4 Static Semantics: IsIdentifierRef

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

PrimaryExpression : IdentifierReference
  1. true를 반환한다.
PrimaryExpression : this Literal ArrayLiteral ObjectLiteral FunctionExpression ClassExpression GeneratorExpression AsyncFunctionExpression AsyncGeneratorExpression RegularExpressionLiteral TemplateLiteral CoverParenthesizedExpressionAndArrowParameterList MemberExpression : MemberExpression [ Expression ] MemberExpression . IdentifierName MemberExpression TemplateLiteral SuperProperty MetaProperty new MemberExpression Arguments MemberExpression . PrivateIdentifier NewExpression : new NewExpression LeftHandSideExpression : CallExpression OptionalExpression
  1. false를 반환한다.

8.4.5 Runtime Semantics: NamedEvaluation

The syntax-directed operation NamedEvaluation takes argument name (a property key or a Private Name) and returns either a normal completion containing a function object or an abrupt completion. It is defined piecewise over the following productions:

PrimaryExpression : CoverParenthesizedExpressionAndArrowParameterList
  1. exprCoverParenthesizedExpressionAndArrowParameterList가 덮고 있는 ParenthesizedExpression이라고 하자.
  2. 인수 name을 사용한 exprNamedEvaluation을 ? 반환한다.
ParenthesizedExpression : ( Expression )
  1. Assert: IsAnonymousFunctionDefinition(Expression)는 true이다.
  2. 인수 name을 사용한 ExpressionNamedEvaluation을 ? 반환한다.
FunctionExpression : function ( FormalParameters ) { FunctionBody }
  1. 인수 name을 사용한 FunctionExpressionInstantiateOrdinaryFunctionExpression을 반환한다.
GeneratorExpression : function * ( FormalParameters ) { GeneratorBody }
  1. 인수 name을 사용한 GeneratorExpressionInstantiateGeneratorFunctionExpression을 반환한다.
AsyncGeneratorExpression : async function * ( FormalParameters ) { AsyncGeneratorBody }
  1. 인수 name을 사용한 AsyncGeneratorExpressionInstantiateAsyncGeneratorFunctionExpression을 반환한다.
AsyncFunctionExpression : async function ( FormalParameters ) { AsyncFunctionBody }
  1. 인수 name을 사용한 AsyncFunctionExpressionInstantiateAsyncFunctionExpression을 반환한다.
ArrowFunction : ArrowParameters => ConciseBody
  1. 인수 name을 사용한 ArrowFunctionInstantiateArrowFunctionExpression을 반환한다.
AsyncArrowFunction : async AsyncArrowBindingIdentifier => AsyncConciseBody CoverCallExpressionAndAsyncArrowHead => AsyncConciseBody
  1. 인수 name을 사용한 AsyncArrowFunctionInstantiateAsyncArrowFunctionExpression을 반환한다.
ClassExpression : class ClassTail
  1. sourceTextClassExpression일치한 소스 텍스트라고 하자.
  2. 인수 undefined, name, sourceText를 사용한 ClassTailClassDefinitionEvaluation을 ? 반환한다.

8.5 Contains

8.5.1 Static Semantics: Contains

The syntax-directed operation Contains takes argument symbol (a grammar symbol) and returns a Boolean.

이 명세에서 아래에 나열되지 않은 모든 문법 생산 대안은 암묵적으로 다음 기본 Contains 정의를 가진다.

  1. 이 Parse Node의 각 자식 노드 child에 대해, 다음을 수행한다.
    1. childsymbol의 인스턴스이면, true를 반환한다.
    2. child가 비종단 기호의 인스턴스이면,
      1. containedchild Contains symbol의 결과라고 하자.
      2. containedtrue이면, true를 반환한다.
  2. false를 반환한다.
FunctionDeclaration : function BindingIdentifier ( FormalParameters ) { FunctionBody } function ( FormalParameters ) { FunctionBody } FunctionExpression : function BindingIdentifieropt ( FormalParameters ) { FunctionBody } GeneratorDeclaration : function * BindingIdentifier ( FormalParameters ) { GeneratorBody } function * ( FormalParameters ) { GeneratorBody } GeneratorExpression : function * BindingIdentifieropt ( FormalParameters ) { GeneratorBody } AsyncGeneratorDeclaration : async function * BindingIdentifier ( FormalParameters ) { AsyncGeneratorBody } async function * ( FormalParameters ) { AsyncGeneratorBody } AsyncGeneratorExpression : async function * BindingIdentifieropt ( FormalParameters ) { AsyncGeneratorBody } AsyncFunctionDeclaration : async function BindingIdentifier ( FormalParameters ) { AsyncFunctionBody } async function ( FormalParameters ) { AsyncFunctionBody } AsyncFunctionExpression : async function BindingIdentifieropt ( FormalParameters ) { AsyncFunctionBody }
  1. false를 반환한다.
Note 1

하위 구조에 의존하는 정적 의미론 규칙은 일반적으로 함수 정의 내부를 들여다보지 않는다.

ClassTail : ClassHeritageopt { ClassBody }
  1. symbolClassBody이면, true를 반환한다.
  2. symbolClassHeritage이면,
    1. ClassHeritage가 존재하면, true를 반환한다.
    2. false를 반환한다.
  3. ClassHeritage가 존재하면,
    1. ClassHeritage Contains symboltrue이면, true를 반환한다.
  4. 인수 symbol을 사용한 ClassBodyComputedPropertyContains 결과를 반환한다.
Note 2

하위 구조에 의존하는 정적 의미론 규칙은 일반적으로 class body 내부를 들여다보지 않으며, 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. 인수 symbol을 사용한 MethodDefinitionComputedPropertyContains 결과를 반환한다.
LiteralPropertyName : IdentifierName
  1. false를 반환한다.
MemberExpression : MemberExpression . IdentifierName
  1. MemberExpression Contains symboltrue이면, true를 반환한다.
  2. false를 반환한다.
SuperProperty : super . IdentifierName
  1. symbolReservedWord super이면, true를 반환한다.
  2. false를 반환한다.
CallExpression : CallExpression . IdentifierName
  1. CallExpression Contains symboltrue이면, true를 반환한다.
  2. false를 반환한다.
OptionalChain : ?. IdentifierName
  1. false를 반환한다.
OptionalChain : OptionalChain . IdentifierName
  1. OptionalChain Contains symboltrue이면, true를 반환한다.
  2. false를 반환한다.

8.5.2 Static Semantics: ComputedPropertyContains

The syntax-directed operation ComputedPropertyContains takes argument symbol (a grammar symbol) and returns a Boolean. It is defined piecewise over the following productions:

ClassElementName : PrivateIdentifier PropertyName : LiteralPropertyName
  1. false를 반환한다.
PropertyName : ComputedPropertyName
  1. ComputedPropertyName Contains symbol의 결과를 반환한다.
MethodDefinition : ClassElementName ( UniqueFormalParameters ) { FunctionBody } get ClassElementName ( ) { FunctionBody } set ClassElementName ( PropertySetParameterList ) { FunctionBody }
  1. 인수 symbol을 사용한 ClassElementNameComputedPropertyContains 결과를 반환한다.
GeneratorMethod : * ClassElementName ( UniqueFormalParameters ) { GeneratorBody }
  1. 인수 symbol을 사용한 ClassElementNameComputedPropertyContains 결과를 반환한다.
AsyncGeneratorMethod : async * ClassElementName ( UniqueFormalParameters ) { AsyncGeneratorBody }
  1. 인수 symbol을 사용한 ClassElementNameComputedPropertyContains 결과를 반환한다.
ClassElementList : ClassElementList ClassElement
  1. inList를 인수 symbol을 사용한 ClassElementListComputedPropertyContains라고 하자.
  2. inListtrue이면, true를 반환한다.
  3. 인수 symbol을 사용한 ClassElementComputedPropertyContains 결과를 반환한다.
ClassElement : ClassStaticBlock
  1. false를 반환한다.
ClassElement : ;
  1. false를 반환한다.
AsyncMethod : async ClassElementName ( UniqueFormalParameters ) { AsyncFunctionBody }
  1. 인수 symbol을 사용한 ClassElementNameComputedPropertyContains 결과를 반환한다.
FieldDefinition : ClassElementName Initializeropt
  1. 인수 symbol을 사용한 ClassElementNameComputedPropertyContains 결과를 반환한다.

8.6 기타

이 연산들은 명세 전반의 여러 위치에서 사용된다.

8.6.1 Runtime Semantics: InstantiateFunctionObject

The syntax-directed operation InstantiateFunctionObject takes arguments env (an Environment Record) and privateEnv (a PrivateEnvironment Record or null) and returns an ECMAScript function object. It is defined piecewise over the following productions:

FunctionDeclaration : function BindingIdentifier ( FormalParameters ) { FunctionBody } function ( FormalParameters ) { FunctionBody }
  1. 인수 envprivateEnv를 사용한 FunctionDeclarationInstantiateOrdinaryFunctionObject를 반환한다.
GeneratorDeclaration : function * BindingIdentifier ( FormalParameters ) { GeneratorBody } function * ( FormalParameters ) { GeneratorBody }
  1. 인수 envprivateEnv를 사용한 GeneratorDeclarationInstantiateGeneratorFunctionObject를 반환한다.
AsyncGeneratorDeclaration : async function * BindingIdentifier ( FormalParameters ) { AsyncGeneratorBody } async function * ( FormalParameters ) { AsyncGeneratorBody }
  1. 인수 envprivateEnv를 사용한 AsyncGeneratorDeclarationInstantiateAsyncGeneratorFunctionObject를 반환한다.
AsyncFunctionDeclaration : async function BindingIdentifier ( FormalParameters ) { AsyncFunctionBody } async function ( FormalParameters ) { AsyncFunctionBody }
  1. 인수 envprivateEnv를 사용한 AsyncFunctionDeclarationInstantiateAsyncFunctionObject를 반환한다.

8.6.2 Runtime Semantics: BindingInitialization

The syntax-directed operation BindingInitialization takes arguments value (an ECMAScript language value) and environment (an Environment Record or undefined) and returns either a normal completion containing unused or an abrupt completion.

Note

environmentundefined가 전달되면, 초기화 값을 할당하기 위해 PutValue 연산을 사용해야 함을 나타낸다. 이는 var 문과 일부 non-strict 함수의 형식 매개변수 목록의 경우이다 (참조 10.2.11). 이런 경우에는 lexical binding이 hoist되고, initializer 평가 전에 사전 초기화된다.

It is defined piecewise over the following productions:

BindingIdentifier : Identifier
  1. nameIdentifierStringValue라고 하자.
  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. 인수 valueenvironment를 사용한 ObjectBindingPatternBindingInitialization을 ? 반환한다.
BindingPattern : ArrayBindingPattern
  1. iteratorRecord를 ? GetIterator(value, sync)라고 하자.
  2. result를 인수 iteratorRecordenvironment를 사용한 ArrayBindingPatternIteratorBindingInitialization에 대한 Completion이라고 하자.
  3. iteratorRecord.[[Done]]false이면, ? IteratorClose(iteratorRecord, result)를 반환한다.
  4. result를 반환한다.
ObjectBindingPattern : { }
  1. unused를 반환한다.
ObjectBindingPattern : { BindingPropertyList } { BindingPropertyList , }
  1. 인수 valueenvironment를 사용한 BindingPropertyListPropertyBindingInitialization을 ? 수행한다.
  2. unused를 반환한다.
ObjectBindingPattern : { BindingRestProperty }
  1. excludedNames를 새로운 빈 List라고 하자.
  2. 인수 value, environment, excludedNames를 사용한 BindingRestPropertyRestBindingInitialization을 ? 반환한다.
ObjectBindingPattern : { BindingPropertyList , BindingRestProperty }
  1. excludedNames을 인수 valueenvironment를 사용한 BindingPropertyListPropertyBindingInitialization 결과라고 하자.
  2. 인수 value, environment, excludedNames을 사용한 BindingRestPropertyRestBindingInitialization을 ? 반환한다.

8.6.2.1 InitializeBoundName ( name, value, environment )

The abstract operation InitializeBoundName takes arguments name (a String), value (an ECMAScript language value), and environment (an Environment Record or undefined) and returns either a normal completion containing unused or an abrupt completion. It performs the following steps when called:

  1. environmentundefined가 아니면,
    1. environment.InitializeBinding(name, value)를 수행한다.
    2. unused를 반환한다.
  2. lhs를 ? ResolveBinding(name)이라고 하자.
  3. PutValue(lhs, value)를 반환한다.

8.6.3 Runtime Semantics: IteratorBindingInitialization

The syntax-directed operation IteratorBindingInitialization takes arguments iteratorRecord (an Iterator Record) and environment (an Environment Record or undefined) and returns either a normal completion containing unused or an abrupt completion.

Note

environmentundefined가 전달되면, 초기화 값을 할당하기 위해 PutValue 연산을 사용해야 함을 나타낸다. 이는 non-strict 함수의 형식 매개변수 목록의 경우이다. 이 경우에는 같은 이름의 매개변수가 여러 개 있을 가능성을 처리하기 위해 형식 매개변수 바인딩이 사전 초기화된다.

It is defined piecewise over the following productions:

ArrayBindingPattern : [ ]
  1. unused를 반환한다.
ArrayBindingPattern : [ Elision ]
  1. 인수 iteratorRecord를 사용한 ElisionIteratorDestructuringAssignmentEvaluation을 ? 반환한다.
ArrayBindingPattern : [ Elisionopt BindingRestElement ]
  1. Elision이 존재하면,
    1. 인수 iteratorRecord를 사용한 ElisionIteratorDestructuringAssignmentEvaluation을 ? 수행한다.
  2. 인수 iteratorRecordenvironment를 사용한 BindingRestElementIteratorBindingInitialization을 ? 반환한다.
ArrayBindingPattern : [ BindingElementList , Elision ]
  1. 인수 iteratorRecordenvironment를 사용한 BindingElementListIteratorBindingInitialization을 ? 수행한다.
  2. 인수 iteratorRecord를 사용한 ElisionIteratorDestructuringAssignmentEvaluation을 ? 반환한다.
ArrayBindingPattern : [ BindingElementList , Elisionopt BindingRestElement ]
  1. 인수 iteratorRecordenvironment를 사용한 BindingElementListIteratorBindingInitialization을 ? 수행한다.
  2. Elision이 존재하면,
    1. 인수 iteratorRecord를 사용한 ElisionIteratorDestructuringAssignmentEvaluation을 ? 수행한다.
  3. 인수 iteratorRecordenvironment를 사용한 BindingRestElementIteratorBindingInitialization을 ? 반환한다.
BindingElementList : BindingElementList , BindingElisionElement
  1. 인수 iteratorRecordenvironment를 사용한 BindingElementListIteratorBindingInitialization을 ? 수행한다.
  2. 인수 iteratorRecordenvironment를 사용한 BindingElisionElementIteratorBindingInitialization을 ? 반환한다.
BindingElisionElement : Elision BindingElement
  1. 인수 iteratorRecord를 사용한 ElisionIteratorDestructuringAssignmentEvaluation을 ? 수행한다.
  2. 인수 iteratorRecordenvironment를 사용한 BindingElementIteratorBindingInitialization을 ? 반환한다.
SingleNameBinding : BindingIdentifier Initializeropt
  1. bindingIdBindingIdentifierStringValue라고 하자.
  2. lhs를 ? ResolveBinding(bindingId, environment)라고 하자.
  3. vundefined라고 하자.
  4. iteratorRecord.[[Done]]false이면,
    1. next를 ? IteratorStepValue(iteratorRecord)라고 하자.
    2. nextdone이 아니면,
      1. vnext로 설정한다.
  5. Initializer가 존재하고 vundefined이면,
    1. IsAnonymousFunctionDefinition(Initializer)가 true이면,
      1. v를 인수 bindingId를 사용한 InitializerNamedEvaluation 결과로 ? 설정한다.
    2. 그렇지 않으면,
      1. defaultValueInitializerEvaluation 결과로 ? 하자.
      2. v를 ? GetValue(defaultValue)로 설정한다.
  6. environmentundefined이면, ? PutValue(lhs, v)를 반환한다.
  7. InitializeReferencedBinding(lhs, v)를 반환한다.
BindingElement : BindingPattern Initializeropt
  1. vundefined라고 하자.
  2. iteratorRecord.[[Done]]false이면,
    1. next를 ? IteratorStepValue(iteratorRecord)라고 하자.
    2. nextdone이 아니면,
      1. vnext로 설정한다.
  3. Initializer가 존재하고 vundefined이면,
    1. defaultValueInitializerEvaluation 결과로 ? 하자.
    2. v를 ? GetValue(defaultValue)로 설정한다.
  4. 인수 venvironment를 사용한 BindingPatternBindingInitialization을 ? 반환한다.
BindingRestElement : ... BindingIdentifier
  1. lhs를 ? ResolveBinding(BindingIdentifierStringValue, environment)라고 하자.
  2. array를 ! ArrayCreate(0)라고 하자.
  3. n을 0이라고 하자.
  4. 다음을 반복한다.
    1. nextdone이라고 하자.
    2. iteratorRecord.[[Done]]false이면,
      1. next를 ? IteratorStepValue(iteratorRecord)로 설정한다.
    3. nextdone이면,
      1. environmentundefined이면, ? PutValue(lhs, array)를 반환한다.
      2. InitializeReferencedBinding(lhs, array)를 반환한다.
    4. CreateDataPropertyOrThrow(array, ! ToString(𝔽(n)), next)를 수행한다.
    5. nn + 1로 설정한다.
BindingRestElement : ... BindingPattern
  1. array를 ! ArrayCreate(0)라고 하자.
  2. n을 0이라고 하자.
  3. 다음을 반복한다.
    1. nextdone이라고 하자.
    2. iteratorRecord.[[Done]]false이면,
      1. next를 ? IteratorStepValue(iteratorRecord)로 설정한다.
    3. nextdone이면,
      1. 인수 arrayenvironment를 사용한 BindingPatternBindingInitialization을 ? 반환한다.
    4. CreateDataPropertyOrThrow(array, ! ToString(𝔽(n)), next)를 수행한다.
    5. nn + 1로 설정한다.
FormalParameters : [empty]
  1. unused를 반환한다.
FormalParameters : FormalParameterList , FunctionRestParameter
  1. 인수 iteratorRecordenvironment를 사용한 FormalParameterListIteratorBindingInitialization을 ? 수행한다.
  2. 인수 iteratorRecordenvironment를 사용한 FunctionRestParameterIteratorBindingInitialization을 ? 반환한다.
FormalParameterList : FormalParameterList , FormalParameter
  1. 인수 iteratorRecordenvironment를 사용한 FormalParameterListIteratorBindingInitialization을 ? 수행한다.
  2. 인수 iteratorRecordenvironment를 사용한 FormalParameterIteratorBindingInitialization을 ? 반환한다.
ArrowParameters : BindingIdentifier
  1. vundefined라고 하자.
  2. Assert: iteratorRecord.[[Done]]false이다.
  3. next를 ? IteratorStepValue(iteratorRecord)라고 하자.
  4. nextdone이 아니면,
    1. vnext로 설정한다.
  5. 인수 venvironment를 사용한 BindingIdentifierBindingInitialization을 ? 반환한다.
ArrowParameters : CoverParenthesizedExpressionAndArrowParameterList
  1. formalsCoverParenthesizedExpressionAndArrowParameterList가 덮고 있는 ArrowFormalParameters라고 하자.
  2. 인수 iteratorRecordenvironment를 사용한 formalsIteratorBindingInitialization을 ? 반환한다.
AsyncArrowBindingIdentifier : BindingIdentifier
  1. vundefined라고 하자.
  2. Assert: iteratorRecord.[[Done]]false이다.
  3. next를 ? IteratorStepValue(iteratorRecord)라고 하자.
  4. nextdone이 아니면,
    1. vnext로 설정한다.
  5. 인수 venvironment를 사용한 BindingIdentifierBindingInitialization을 ? 반환한다.

8.6.4 Static Semantics: AssignmentTargetType

The syntax-directed operation AssignmentTargetType takes no arguments and returns simple, web-compat, or invalid. It is defined piecewise over the following productions:

IdentifierReference : Identifier
  1. IsStrict(this IdentifierReference)가 true이고 IdentifierStringValue"eval" 또는 "arguments" 중 하나이면, invalid를 반환한다.
  2. simple을 반환한다.
IdentifierReference : yield await CallExpression : CallExpression [ Expression ] CallExpression . IdentifierName CallExpression . PrivateIdentifier MemberExpression : MemberExpression [ Expression ] MemberExpression . IdentifierName SuperProperty MemberExpression . PrivateIdentifier
  1. simple을 반환한다.
PrimaryExpression : CoverParenthesizedExpressionAndArrowParameterList
  1. exprCoverParenthesizedExpressionAndArrowParameterList가 덮고 있는 ParenthesizedExpression이라고 하자.
  2. exprAssignmentTargetType을 반환한다.
CallExpression : CoverCallExpressionAndAsyncArrowHead CallExpression Arguments
  1. Normative Optional
    호스트가 웹 브라우저이거나 Function Call Assignment Target에 대한 Runtime Error를 지원하고 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 Static Semantics: PropName

The syntax-directed operation PropName takes no arguments and returns a String or empty. It is defined piecewise over the following productions:

PropertyDefinition : IdentifierReference
  1. IdentifierReferenceStringValue를 반환한다.
PropertyDefinition : ... AssignmentExpression
  1. empty를 반환한다.
PropertyDefinition : PropertyName : AssignmentExpression
  1. PropertyNamePropName을 반환한다.
LiteralPropertyName : IdentifierName AttributeKey : IdentifierName
  1. IdentifierNameStringValue를 반환한다.
LiteralPropertyName : StringLiteral AttributeKey : StringLiteral
  1. StringLiteralSV를 반환한다.
LiteralPropertyName : NumericLiteral
  1. nbrNumericLiteralNumericValue라고 하자.
  2. ToString(nbr)을 반환한다.
ComputedPropertyName : [ AssignmentExpression ]
  1. empty를 반환한다.
MethodDefinition : ClassElementName ( UniqueFormalParameters ) { FunctionBody } get ClassElementName ( ) { FunctionBody } set ClassElementName ( PropertySetParameterList ) { FunctionBody }
  1. ClassElementNamePropName을 반환한다.
GeneratorMethod : * ClassElementName ( UniqueFormalParameters ) { GeneratorBody }
  1. ClassElementNamePropName을 반환한다.
AsyncGeneratorMethod : async * ClassElementName ( UniqueFormalParameters ) { AsyncGeneratorBody }
  1. ClassElementNamePropName을 반환한다.
ClassElement : ClassStaticBlock
  1. empty를 반환한다.
ClassElement : ;
  1. empty를 반환한다.
AsyncMethod : async ClassElementName ( UniqueFormalParameters ) { AsyncFunctionBody }
  1. ClassElementNamePropName을 반환한다.
FieldDefinition : ClassElementName Initializeropt
  1. ClassElementNamePropName을 반환한다.
ClassElementName : PrivateIdentifier
  1. empty를 반환한다.

9 실행 가능한 코드와 실행 컨텍스트

9.1 Environment Record

Environment Record는 ECMAScript 코드의 어휘적 중첩 구조를 바탕으로 Identifier를 특정 변수 및 함수와 연관시키는 것을 정의하는 데 사용되는 명세 타입이다. 보통 Environment Record는 FunctionDeclaration, BlockStatement, 또는 TryStatementCatch 절과 같은 ECMAScript 코드의 특정 구문 구조와 연관된다. 이러한 코드가 평가될 때마다, 해당 코드에 의해 생성되는 식별자 바인딩을 기록하기 위해 새로운 Environment Record가 생성된다.

모든 Environment Record는 [[OuterEnv]] 필드를 가지며, 그 값은 null 또는 바깥쪽 Environment Record에 대한 참조이다. 이것은 Environment Record 값들의 논리적 중첩을 모델링하는 데 사용된다. 어떤 (안쪽) Environment Record의 outer reference는 그 안쪽 Environment Record를 논리적으로 둘러싸는 Environment Record에 대한 참조이다. 바깥쪽 Environment Record는 물론 자기 자신의 바깥쪽 Environment Record를 가질 수 있다. 하나의 Environment Record는 여러 안쪽 Environment Record의 outer environment 역할을 할 수 있다. 예를 들어, FunctionDeclaration이 두 개의 중첩된 FunctionDeclaration을 포함한다면, 각 중첩 함수의 Environment Record는 둘러싸고 있는 함수의 현재 평가에 대한 Environment Record를 자신의 outer Environment Record로 가진다.

Environment Record는 순전히 명세 메커니즘이며, ECMAScript 구현의 어떤 특정 산출물과 대응할 필요는 없다. ECMAScript 프로그램이 이러한 값에 직접 접근하거나 조작하는 것은 불가능하다.

9.1.1 Environment Record 타입 계층

Environment Record는 단순한 객체지향 계층에 존재하는 것으로 생각할 수 있으며, 여기서 Environment Record는 추상 클래스이고 세 개의 구체적 서브클래스인 Declarative Environment Record, Object Environment Record, Global Environment Record를 가진다. Function Environment RecordModule Environment RecordDeclarative Environment Record의 서브클래스이다.

  • Environment Record (추상)

    • Declarative Environment RecordFunctionDeclaration, VariableDeclaration, Catch 절과 같이 식별자 바인딩을 ECMAScript 언어 값에 직접 연관시키는 ECMAScript 언어 구문 요소의 효과를 정의하는 데 사용된다.

      • Function Environment Record는 ECMAScript 함수 객체의 호출에 대응하며, 그 함수 내부의 최상위 선언에 대한 바인딩을 포함한다. 이는 새로운 this 바인딩을 설정할 수 있다. 또한 super 메서드 호출을 지원하는 데 필요한 상태도 포착한다.

      • Module Environment RecordModule의 최상위 선언에 대한 바인딩을 포함한다. 또한 Module에 의해 명시적으로 import된 바인딩도 포함한다. 그 [[OuterEnv]]Global Environment Record이다.

    • Object Environment RecordWithStatement와 같이 식별자 바인딩을 어떤 객체의 프로퍼티와 연관시키는 ECMAScript 요소의 효과를 정의하는 데 사용된다.

    • Global Environment RecordScript의 전역 선언에 사용된다. 이것은 바깥 환경을 가지지 않으며, 그 [[OuterEnv]]null이다. 식별자 바인딩으로 미리 채워질 수 있으며, 그 프로퍼티가 전역 환경의 일부 식별자 바인딩을 제공하는 연관된 전역 객체를 포함한다. ECMAScript 코드가 실행됨에 따라 추가 프로퍼티가 전역 객체에 추가될 수 있고 초기 프로퍼티가 수정될 수 있다.

Environment Record 추상 클래스는 Table 14에 정의된 추상 명세 메서드를 포함한다. 이 추상 메서드들은 각 구체적 서브클래스에 대해 서로 다른 구체 알고리즘을 가진다.

Table 14: Abstract Methods of Environment Records
메서드 목적 정의
HasBinding ( name )

The abstract method HasBinding takes argument name (a String) and returns either a normal completion containing a Boolean or a throw completion.

이것은 Environment Recordname에 대한 바인딩을 가지는지 결정한다.
이것은 다음 타입들에 구체 정의를 가진다:
CreateMutableBinding ( name, deletable )

The abstract method CreateMutableBinding takes arguments name (a String) and deletable (a Boolean) and returns either a normal completion containing unused or a throw completion.

이것은 Environment Record 안에 초기화되지 않은 새로운 가변 바인딩을 생성한다. name은 바인딩된 이름의 텍스트이다. deletabletrue이면 그 바인딩은 이후 삭제될 수 있다.
이것은 다음 타입들에 구체 정의를 가진다:
CreateImmutableBinding ( name, strict )

The abstract method CreateImmutableBinding takes arguments name (a String) and strict (a Boolean) and returns either a normal completion containing unused or a throw completion.

이것은 Environment Record 안에 초기화되지 않은 새로운 불변 바인딩을 생성한다. name은 바인딩된 이름의 텍스트이다. stricttrue이면, 그것이 초기화된 후 값을 설정하려는 시도는 그 바인딩을 참조하는 연산의 strict mode 설정과 관계없이 항상 예외를 던진다.
이것은 다음 타입들에 구체 정의를 가진다:
InitializeBinding ( name, value )

The abstract method InitializeBinding takes arguments name (a String) and value (an ECMAScript language value) and returns either a normal completion containing unused or a throw completion.

이것은 Environment Record 안에 이미 존재하지만 아직 초기화되지 않은 바인딩의 값을 설정한다. name은 바인딩된 이름의 텍스트이다. value는 그 바인딩에 대한 값이다.
이것은 다음 타입들에 구체 정의를 가진다:
SetMutableBinding ( name, value, strict )

The abstract method SetMutableBinding takes arguments name (a String), value (an ECMAScript language value), and strict (a Boolean) and returns either a normal completion containing unused or a throw completion.

이것은 Environment Record 안에 이미 존재하는 가변 바인딩의 값을 설정한다. name은 바인딩된 이름의 텍스트이다. value는 그 바인딩에 대한 값이다. stricttrue이고 바인딩을 설정할 수 없으면, 이것은 TypeError 예외를 던진다.
이것은 다음 타입들에 구체 정의를 가진다:
GetBindingValue ( name, strict )

The abstract method GetBindingValue takes arguments name (a String) and strict (a Boolean) and returns either a normal completion containing an ECMAScript language value or a throw completion.

이것은 Environment Record에서 이미 존재하는 바인딩의 값을 반환한다. name은 바인딩된 이름의 텍스트이다. strictstrict mode 코드에서 유래한 참조이거나 그 밖에 strict mode 참조 의미론을 요구하는 참조를 식별하는 데 사용된다. stricttrue이고 바인딩이 존재하지 않으면, 이것은 ReferenceError 예외를 던진다. 바인딩이 존재하지만 초기화되지 않았다면, strict의 값과 관계없이 ReferenceError가 던져진다.
이것은 다음 타입들에 구체 정의를 가진다:
DeleteBinding ( name )

The abstract method DeleteBinding takes argument name (a String) and returns either a normal completion containing a Boolean or a throw completion.

이것은 Environment Record에서 바인딩을 삭제한다. name은 바인딩된 이름의 텍스트이다. name에 대한 바인딩이 존재하면, 이것은 그 바인딩을 제거하고 true를 반환한다. 바인딩이 존재하지만 제거할 수 없으면, 이것은 false를 반환한다. 바인딩이 존재하지 않으면, 이것은 true를 반환한다.
이것은 다음 타입들에 구체 정의를 가진다:
HasThisBinding ( )

The abstract method HasThisBinding takes no arguments and returns a Boolean.

이것은 Environment Recordthis 바인딩을 설정하는지 결정한다. 설정한다면 true를, 그렇지 않다면 false를 반환한다.
이것은 다음 타입들에 구체 정의를 가진다:
GetThisBinding ( )

The abstract method GetThisBinding takes no arguments and returns either a normal completion containing an ECMAScript language value or a throw completion.

이것은 이 Environment Recordthis 바인딩 값을 반환한다. this 바인딩이 초기화되지 않았다면 ReferenceError를 던진다.
이것은 다음 타입들에 구체 정의를 가진다:
HasSuperBinding ( )

The abstract method HasSuperBinding takes no arguments and returns a Boolean.

이것은 Environment Recordsuper 메서드 바인딩을 설정하는지 결정한다. 설정한다면 true를, 그렇지 않다면 false를 반환한다. 이것이 true를 반환하면, 그 Environment RecordFunction Environment Record임을 뜻하지만, 그 역은 성립하지 않는다.
이것은 다음 타입들에 구체 정의를 가진다:
WithBaseObject ( )

The abstract method WithBaseObject takes no arguments and returns an Object or undefined.

Environment Recordwith 문과 연관되어 있으면, with 객체를 반환한다. 그렇지 않으면 undefined를 반환한다.
이것은 다음 타입들에 구체 정의를 가진다:

9.1.1.1 Declarative Environment Record

Declarative Environment Record는 변수, 상수, let, class, module, import 및/또는 함수 선언을 포함하는 ECMAScript 프로그램 스코프와 연관된다. Declarative Environment Record는 그 스코프 안에 포함된 선언들이 정의하는 식별자 집합을 바인딩한다.

9.1.1.1.1 HasBinding ( name )

The HasBinding concrete method of a Declarative Environment Record envRec takes argument name (a String) and returns a normal completion containing a Boolean. 이것은 인수 식별자가 record에 의해 바인딩된 식별자들 중 하나인지 결정한다. It performs the following steps when called:

  1. envRecname에 대한 바인딩을 가지면, true를 반환한다.
  2. false를 반환한다.

9.1.1.1.2 CreateMutableBinding ( name, deletable )

The CreateMutableBinding concrete method of a Declarative Environment Record envRec takes arguments name (a String) and deletable (a Boolean) and returns a normal completion containing unused. 이것은 name이라는 이름에 대해 초기화되지 않은 새로운 가변 바인딩을 생성한다. 이 Environment Record 안에는 name에 대한 바인딩이 이미 존재해서는 안 된다. deletabletrue이면, 새 바인딩은 삭제 가능 대상으로 표시된다. It performs the following steps when called:

  1. Assert: envRecname에 대한 바인딩을 이미 가지고 있지 않다.
  2. envRec 안에 name에 대한 가변 바인딩을 생성하고, 그것이 초기화되지 않았음을 기록한다. deletabletrue이면, 새로 생성된 바인딩이 이후 DeleteBinding 호출에 의해 삭제될 수 있음을 기록한다.
  3. unused를 반환한다.

9.1.1.1.3 CreateImmutableBinding ( name, strict )

The CreateImmutableBinding concrete method of a Declarative Environment Record envRec takes arguments name (a String) and strict (a Boolean) and returns a normal completion containing unused. 이것은 name이라는 이름에 대해 초기화되지 않은 새로운 불변 바인딩을 생성한다. 이 Environment Record 안에는 name에 대한 바인딩이 이미 존재해서는 안 된다. stricttrue이면, 새 바인딩은 strict 바인딩으로 표시된다. It performs the following steps when called:

  1. Assert: envRecname에 대한 바인딩을 이미 가지고 있지 않다.
  2. envRec 안에 name에 대한 불변 바인딩을 생성하고, 그것이 초기화되지 않았음을 기록한다. stricttrue이면, 새로 생성된 바인딩이 strict 바인딩임을 기록한다.
  3. unused를 반환한다.

9.1.1.1.4 InitializeBinding ( name, value )

The InitializeBinding concrete method of a Declarative Environment Record envRec takes arguments name (a String) and value (an ECMAScript language value) and returns a normal completion containing unused. 이것은 이름이 name인 식별자의 현재 바인딩 값으로 value를 설정하는 데 사용된다. name에 대한 초기화되지 않은 바인딩이 이미 존재해야 한다. It performs the following steps when called:

  1. Assert: envRecname에 대한 초기화되지 않은 바인딩을 가지고 있어야 한다.
  2. envRec 안에서 name에 대한 바인딩 값을 value로 설정한다.
  3. envRec 안의 name에 대한 바인딩이 초기화되었음을 기록한다.
  4. unused를 반환한다.

9.1.1.1.5 SetMutableBinding ( name, value, strict )

The SetMutableBinding concrete method of a Declarative Environment Record envRec takes arguments name (a String), value (an ECMAScript language value), and strict (a Boolean) and returns either a normal completion containing unused or a throw completion. 이것은 이름이 name인 식별자의 현재 바인딩 값을 value로 바꾸려 시도한다. 보통 name에 대한 바인딩은 이미 존재하지만, 드물게는 존재하지 않을 수도 있다. 바인딩이 불변 바인딩이면, stricttrue일 때 TypeError가 던져진다. It performs the following steps when called:

  1. envRecname에 대한 바인딩을 가지고 있지 않다면,
    1. stricttrue이면, ReferenceError 예외를 던진다.
    2. envRec.CreateMutableBinding(name, true)를 수행한다.
    3. envRec.InitializeBinding(name, value)를 수행한다.
    4. unused를 반환한다.
  2. envRec 안의 name에 대한 바인딩이 strict 바인딩이면, stricttrue로 설정한다.
  3. envRec 안의 name에 대한 바인딩이 아직 초기화되지 않았다면,
    1. ReferenceError 예외를 던진다.
  4. 그렇지 않고 envRec 안의 name에 대한 바인딩이 가변 바인딩이면,
    1. 그 바인딩 값을 value로 바꾼다.
  5. 그렇지 않으면,
    1. Assert: 이것은 불변 바인딩의 값을 바꾸려는 시도이다.
    2. stricttrue이면, TypeError 예외를 던진다.
  6. unused를 반환한다.
Note

단계 1에서 바인딩이 없는 경우를 초래하는 ECMAScript 코드의 예는 다음과 같다:

function f() { eval("var x; x = (delete x, 0);"); }

9.1.1.1.6 GetBindingValue ( name, strict )

The GetBindingValue concrete method of a Declarative Environment Record envRec takes arguments name (a String) and strict (a Boolean) and returns either a normal completion containing an ECMAScript language value or a throw completion. 이것은 이름이 name인 바인딩된 식별자의 값을 반환한다. 바인딩이 존재하지만 초기화되지 않았다면, strict의 값과 관계없이 ReferenceError가 던져진다. It performs the following steps when called:

  1. Assert: envRecname에 대한 바인딩을 가지고 있다.
  2. envRec 안의 name에 대한 바인딩이 초기화되지 않은 바인딩이면, ReferenceError 예외를 던진다.
  3. envRec 안에서 현재 name에 바인딩된 값을 반환한다.

9.1.1.1.7 DeleteBinding ( name )

The DeleteBinding concrete method of a Declarative Environment Record envRec takes argument name (a String) and returns a normal completion containing a Boolean. 이것은 명시적으로 삭제 가능 대상으로 지정된 바인딩만 삭제할 수 있다. It performs the following steps when called:

  1. Assert: envRecname에 대한 바인딩을 가지고 있다.
  2. envRec 안의 name에 대한 바인딩을 삭제할 수 없으면, false를 반환한다.
  3. envRec에서 name에 대한 바인딩을 제거한다.
  4. true를 반환한다.

9.1.1.1.8 HasThisBinding ( )

The HasThisBinding concrete method of a 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 GetThisBinding ( )

Declarative Environment RecordGetThisBinding 구체 메서드는 이 명세에서 결코 사용되지 않는다.

9.1.1.1.10 HasSuperBinding ( )

The HasSuperBinding concrete method of a 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도 아닌 것)는 super 바인딩을 제공하지 않는다.

9.1.1.1.11 WithBaseObject ( )

The WithBaseObject concrete method of a 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 Record는 자신의 binding object라고 불리는 객체와 연관된다. Object Environment Record는 자신의 binding object의 프로퍼티 이름과 직접 대응하는 문자열 식별자 이름들의 집합을 바인딩한다. IdentifierName 형태의 문자열이 아닌 프로퍼티 키는 바인딩된 식별자 집합에 포함되지 않는다. own 프로퍼티와 상속된 프로퍼티는 [[Enumerable]] 속성의 설정과 관계없이 모두 집합에 포함된다. 객체에는 프로퍼티가 동적으로 추가되거나 삭제될 수 있으므로, Object Environment Record에 의해 바인딩되는 식별자 집합은 프로퍼티를 추가하거나 삭제하는 어떤 연산의 부작용으로 잠재적으로 변할 수 있다. 그러한 부작용의 결과로 생성되는 모든 바인딩은, 대응하는 프로퍼티의 Writable 속성이 false이더라도, 가변 바인딩으로 간주된다. 불변 바인딩은 Object Environment Record에는 존재하지 않는다.

with 문(14.11)을 위해 생성된 Object Environment Record는 함수 호출에 사용될 암묵적 this 값으로 자신의 binding object를 제공할 수 있다. 이 기능은 Boolean [[IsWithEnvironment]] 필드로 제어된다.

Object Environment Record는 Table 15에 나열된 추가 상태 필드를 가진다.

Table 15: Additional Fields of Object Environment Records
필드 이름 의미
[[BindingObject]] an Object Environment Record의 binding object.
[[IsWithEnvironment]] a Boolean Environment Recordwith 문을 위해 생성되었는지를 나타낸다.

9.1.1.2.1 HasBinding ( name )

The HasBinding concrete method of an Object Environment Record envRec takes argument name (a String) and returns either a normal completion containing a Boolean or a throw completion. 이것은 연관된 binding object가 이름이 name인 프로퍼티를 가지는지 결정한다. It performs the following steps when called:

  1. bindingObjectenvRec.[[BindingObject]]라고 하자.
  2. foundBinding을 ? HasProperty(bindingObject, name)이라고 하자.
  3. foundBindingfalse이면, false를 반환한다.
  4. envRec.[[IsWithEnvironment]]false이면, true를 반환한다.
  5. unscopables를 ? Get(bindingObject, %Symbol.unscopables%)라고 하자.
  6. unscopables가 Object이면,
    1. blockedToBoolean(? Get(unscopables, name))라고 하자.
    2. blockedtrue이면, false를 반환한다.
  7. true를 반환한다.

9.1.1.2.2 CreateMutableBinding ( name, deletable )

The CreateMutableBinding concrete method of an Object Environment Record envRec takes arguments name (a String) and deletable (a Boolean) and returns either a normal completion containing unused or a throw completion. 이것은 Environment Record와 연관된 binding object에 이름이 name인 프로퍼티를 만들고 그 값을 undefined로 초기화한다. deletabletrue이면 새 프로퍼티의 [[Configurable]] 속성은 true로 설정되고, 그렇지 않으면 false로 설정된다. It performs the following steps when called:

  1. bindingObjectenvRec.[[BindingObject]]라고 하자.
  2. DefinePropertyOrThrow(bindingObject, name, PropertyDescriptor { [[Value]]: undefined, [[Writable]]: true, [[Enumerable]]: true, [[Configurable]]: deletable })를 수행한다.
  3. unused를 반환한다.
Note

보통 envRecname에 대한 바인딩을 가지고 있지 않지만, 만약 가지고 있다면 DefinePropertyOrThrow의 의미론에 따라 기존 바인딩이 교체되거나 가려질 수 있으며, 또는 abrupt completion이 반환될 수 있다.

9.1.1.2.3 CreateImmutableBinding ( name, strict )

Object Environment RecordCreateImmutableBinding 구체 메서드는 이 명세에서 결코 사용되지 않는다.

9.1.1.2.4 InitializeBinding ( name, value )

The InitializeBinding concrete method of an Object Environment Record envRec takes arguments name (a String) and value (an ECMAScript language value) and returns either a normal completion containing unused or a throw completion. 이것은 이름이 name인 식별자의 현재 바인딩 값을 value로 설정하는 데 사용된다. It performs the following steps when called:

  1. envRec.SetMutableBinding(name, value, false)를 수행한다.
  2. unused를 반환한다.
Note

이 명세에서 Object Environment Record에 대한 CreateMutableBinding의 모든 사용은 같은 이름에 대한 InitializeBinding 호출이 즉시 뒤따른다. 따라서 이 명세는 Object Environment Record 안의 바인딩 초기화 상태를 명시적으로 추적하지 않는다.

9.1.1.2.5 SetMutableBinding ( name, value, strict )

The SetMutableBinding concrete method of an Object Environment Record envRec takes arguments name (a String), value (an ECMAScript language value), and strict (a Boolean) and returns either a normal completion containing unused or a throw completion. 이것은 Environment Record와 연관된 binding object에서 이름이 name인 프로퍼티의 값을 value로 설정하려 시도한다. 이름이 name인 프로퍼티는 보통 이미 존재하지만, 존재하지 않거나 현재 writable하지 않은 경우 오류 처리는 strict에 의해 결정된다. It performs the following steps when called:

  1. bindingObjectenvRec.[[BindingObject]]라고 하자.
  2. stillExists를 ? HasProperty(bindingObject, name)라고 하자.
  3. stillExistsfalse이고 stricttrue이면, ReferenceError 예외를 던진다.
  4. Set(bindingObject, name, value, strict)를 수행한다.
  5. unused를 반환한다.

9.1.1.2.6 GetBindingValue ( name, strict )

The GetBindingValue concrete method of an Object Environment Record envRec takes arguments name (a String) and strict (a Boolean) and returns either a normal completion containing an ECMAScript language value or a throw completion. 이것은 연관된 binding object에서 이름이 name인 프로퍼티의 값을 반환한다. 그 프로퍼티는 보통 이미 존재해야 하지만, 존재하지 않는 경우 결과는 strict에 따라 달라진다. It performs the following steps when called:

  1. bindingObjectenvRec.[[BindingObject]]라고 하자.
  2. value를 ? HasProperty(bindingObject, name)라고 하자.
  3. valuefalse이면,
    1. strictfalse이면, undefined를 반환한다.
    2. ReferenceError 예외를 던진다.
  4. Get(bindingObject, name)를 반환한다.

9.1.1.2.7 DeleteBinding ( name )

The DeleteBinding concrete method of an Object Environment Record envRec takes argument name (a String) and returns either a normal completion containing a Boolean or a throw completion. 이것은 환경 객체의 [[Configurable]] 속성이 true인 프로퍼티에 대응하는 바인딩만 삭제할 수 있다. It performs the following steps when called:

  1. bindingObjectenvRec.[[BindingObject]]라고 하자.
  2. bindingObject.[[Delete]](name)를 반환한다.

9.1.1.2.8 HasThisBinding ( )

The HasThisBinding concrete method of an 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 GetThisBinding ( )

Object Environment RecordGetThisBinding 구체 메서드는 이 명세에서 결코 사용되지 않는다.

9.1.1.2.10 HasSuperBinding ( )

The HasSuperBinding concrete method of an 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.11 WithBaseObject ( )

The WithBaseObject concrete method of an Object Environment Record envRec takes no arguments and returns an Object or 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: Additional Fields of Function Environment Records
필드 이름 의미
[[ThisValue]] an ECMAScript language value 이것은 이 함수 호출에 사용되는 this 값이다.
[[ThisBindingStatus]] lexical, initialized, or uninitialized 값이 lexical이면, 이것은 ArrowFunction이며 로컬 this 값을 가지지 않는다.
[[FunctionObject]] an ECMAScript function object Environment Record가 생성되게 한 함수 객체 호출의 함수 객체.
[[NewTarget]] a constructor or undefined Environment Record[[Construct]] 내부 메서드에 의해 생성되었다면, [[NewTarget]][[Construct]]newTarget 매개변수 값이다. 그렇지 않으면 그 값은 undefined이다.

Function Environment Record는 Table 14에 나열된 모든 Declarative Environment Record 메서드를 지원하며, HasThisBinding, GetThisBinding, HasSuperBinding을 제외한 모든 메서드에 대해 같은 명세를 공유한다.

9.1.1.3.1 BindThisValue ( envRec, value )

The abstract operation BindThisValue takes arguments envRec (a Function Environment Record) and value (an ECMAScript language value) and returns either a normal completion containing unused or a throw completion. 이것은 envRec.[[ThisValue]]를 설정하고 그것이 초기화되었음을 기록한다. It performs the following steps when called:

  1. Assert: envRec.[[ThisBindingStatus]]lexical이 아니다.
  2. envRec.[[ThisBindingStatus]]initialized이면, ReferenceError 예외를 던진다.
  3. envRec.[[ThisValue]]value로 설정한다.
  4. envRec.[[ThisBindingStatus]]initialized로 설정한다.
  5. unused를 반환한다.

9.1.1.3.2 HasThisBinding ( )

The HasThisBinding concrete method of a Function Environment Record envRec takes no arguments and returns a Boolean. It performs the following steps when called:

  1. envRec.[[ThisBindingStatus]]lexical이면, false를 반환한다.
  2. true를 반환한다.

9.1.1.3.3 GetThisBinding ( )

The GetThisBinding concrete method of a Function Environment Record envRec takes no arguments and returns either a normal completion containing an ECMAScript language value or a throw completion. It performs the following steps when called:

  1. Assert: envRec.[[ThisBindingStatus]]lexical이 아니다.
  2. envRec.[[ThisBindingStatus]]uninitialized이면, ReferenceError 예외를 던진다.
  3. envRec.[[ThisValue]]를 반환한다.

9.1.1.3.4 HasSuperBinding ( )

The HasSuperBinding concrete method of a Function Environment Record envRec takes no arguments and returns a Boolean. It performs the following steps when called:

  1. envRec.[[ThisBindingStatus]]lexical이면, false를 반환한다.
  2. envRec.[[FunctionObject]].[[HomeObject]]undefined이면, false를 반환한다.
  3. true를 반환한다.

9.1.1.3.5 GetSuperBase ( envRec )

The abstract operation GetSuperBase takes argument envRec (a Function Environment Record) and returns an Object, null, or undefined. 이것은 envRec 안에 바인딩된 super 프로퍼티 접근의 기반 객체를 반환한다. 값 undefined는 그러한 접근이 런타임 오류를 발생시킬 것임을 나타낸다. It performs the following steps when called:

  1. homeenvRec.[[FunctionObject]].[[HomeObject]]라고 하자.
  2. homeundefined이면, undefined를 반환한다.
  3. Assert: homeordinary object이다.
  4. home.[[GetPrototypeOf]]()를 반환한다.

9.1.1.4 Global Environment Record

Global Environment Record는 공통 realm에서 처리되는 모든 ECMAScript Script 요소가 공유하는 가장 바깥쪽 스코프를 나타내는 데 사용된다. Global Environment Record는 내장 전역(clause 19), 전역 객체의 프로퍼티, 그리고 Script 내부에 나타나는 모든 최상위 선언(8.2.9, 8.2.11)에 대한 바인딩을 제공한다.

Global Environment Record는 논리적으로는 단일 record이지만, Object Environment RecordDeclarative Environment Record를 캡슐화하는 합성체로 명세된다. Object Environment Record는 연관된 Realm Record전역 객체를 자신의 base object로 가진다. 이 전역 객체는 Global Environment Record의 GetThisBinding 구체 메서드가 반환하는 값이다. Global Environment Record의 Object Environment Record 구성요소는 모든 내장 전역(clause 19)과, 전역 코드 안에 포함된 FunctionDeclaration, GeneratorDeclaration, AsyncFunctionDeclaration, AsyncGeneratorDeclaration, VariableStatement에 의해 도입되는 모든 바인딩을 포함한다. 전역 코드 안의 다른 모든 ECMAScript 선언에 대한 바인딩은 Global Environment Record의 Declarative Environment Record 구성요소에 포함된다.

프로퍼티는 전역 객체 위에 직접 생성될 수 있다. 따라서 Global Environment Record의 Object Environment Record 구성요소는 FunctionDeclaration, GeneratorDeclaration, AsyncFunctionDeclaration, AsyncGeneratorDeclaration, VariableDeclaration 선언에 의해 명시적으로 생성된 바인딩과 전역 객체의 프로퍼티로 암묵적으로 생성된 바인딩을 모두 포함할 수 있다.

Global Environment Record는 Table 17에 나열된 추가 필드를 가진다.

Table 17: Additional Fields of Global Environment Records
필드 이름 의미
[[ObjectRecord]] an Object Environment Record Binding object는 전역 객체이다. 이것은 전역 내장 바인딩뿐 아니라 연관된 realm에 대한 전역 코드 안의 FunctionDeclaration, GeneratorDeclaration, AsyncFunctionDeclaration, AsyncGeneratorDeclaration, VariableDeclaration 바인딩도 포함한다.
[[GlobalThisValue]] an Object 전역 스코프에서 this가 반환하는 값. 호스트는 어떤 ECMAScript Object 값이든 제공할 수 있다.
[[DeclarativeRecord]] a Declarative Environment Record 연관된 realm 코드에 대한 전역 코드 안의 모든 선언 중 FunctionDeclaration, GeneratorDeclaration, AsyncFunctionDeclaration, AsyncGeneratorDeclaration, VariableDeclaration 바인딩을 제외한 모든 선언의 바인딩을 포함한다.

9.1.1.4.1 HasBinding ( name )

The HasBinding concrete method of a Global Environment Record envRec takes argument name (a String) and returns either a normal completion containing a Boolean or a throw completion. 이것은 인수 식별자가 record에 의해 바인딩된 식별자들 중 하나인지 결정한다. It performs the following steps when called:

  1. declarativeRecordenvRec.[[DeclarativeRecord]]라고 하자.
  2. declarativeRecord.HasBinding(name)이 true이면, true를 반환한다.
  3. objectRecordenvRec.[[ObjectRecord]]라고 하자.
  4. objectRecord.HasBinding(name)를 반환한다.

9.1.1.4.2 CreateMutableBinding ( name, deletable )

The CreateMutableBinding concrete method of a Global Environment Record envRec takes arguments name (a String) and deletable (a Boolean) and returns either a normal completion containing unused or a throw completion. 이것은 name이라는 이름에 대해 초기화되지 않은 새로운 가변 바인딩을 생성한다. 그 바인딩은 연관된 DeclarativeRecord 안에 생성된다. DeclarativeRecord 안에는 name에 대한 바인딩이 이미 존재해서는 안 된다. deletabletrue이면, 새 바인딩은 삭제 가능 대상으로 표시된다. It performs the following steps when called:

  1. declarativeRecordenvRec.[[DeclarativeRecord]]라고 하자.
  2. declarativeRecord.HasBinding(name)이 true이면, TypeError 예외를 던진다.
  3. declarativeRecord.CreateMutableBinding(name, deletable)를 반환한다.

9.1.1.4.3 CreateImmutableBinding ( name, strict )

The CreateImmutableBinding concrete method of a Global Environment Record envRec takes arguments name (a String) and strict (a Boolean) and returns either a normal completion containing unused or a throw completion. 이것은 name이라는 이름에 대해 초기화되지 않은 새로운 불변 바인딩을 생성한다. 이 Environment Record 안에는 name에 대한 바인딩이 이미 존재해서는 안 된다. stricttrue이면, 새 바인딩은 strict 바인딩으로 표시된다. It performs the following steps when called:

  1. declarativeRecordenvRec.[[DeclarativeRecord]]라고 하자.
  2. declarativeRecord.HasBinding(name)이 true이면, TypeError 예외를 던진다.
  3. declarativeRecord.CreateImmutableBinding(name, strict)를 반환한다.

9.1.1.4.4 InitializeBinding ( name, value )

The InitializeBinding concrete method of a Global Environment Record envRec takes arguments name (a String) and value (an ECMAScript language value) and returns either a normal completion containing unused or a throw completion. 이것은 이름이 name인 식별자의 현재 바인딩 값을 value로 설정하는 데 사용된다. name에 대한 초기화되지 않은 바인딩이 이미 존재해야 한다. It performs the following steps when called:

  1. declarativeRecordenvRec.[[DeclarativeRecord]]라고 하자.
  2. declarativeRecord.HasBinding(name)이 true이면,
    1. declarativeRecord.InitializeBinding(name, value)를 반환한다.
  3. Assert: 바인딩이 존재한다면, 그것은 반드시 Object Environment Record 안에 있어야 한다.
  4. objectRecordenvRec.[[ObjectRecord]]라고 하자.
  5. objectRecord.InitializeBinding(name, value)를 반환한다.

9.1.1.4.5 SetMutableBinding ( name, value, strict )

The SetMutableBinding concrete method of a Global Environment Record envRec takes arguments name (a String), value (an ECMAScript language value), and strict (a Boolean) and returns either a normal completion containing unused or a throw completion. 이것은 이름이 name인 식별자의 현재 바인딩 값을 value로 바꾸려 시도한다. 바인딩이 불변 바인딩이고 stricttrue이면, TypeError가 던져진다. 이름이 name인 바인딩은 보통 이미 존재하지만, 존재하지 않거나 현재 writable하지 않은 경우 오류 처리는 strict에 의해 결정된다. It performs the following steps when called:

  1. declarativeRecordenvRec.[[DeclarativeRecord]]라고 하자.
  2. declarativeRecord.HasBinding(name)이 true이면,
    1. declarativeRecord.SetMutableBinding(name, value, strict)를 반환한다.
  3. objectRecordenvRec.[[ObjectRecord]]라고 하자.
  4. objectRecord.SetMutableBinding(name, value, strict)를 반환한다.

9.1.1.4.6 GetBindingValue ( name, strict )

The GetBindingValue concrete method of a Global Environment Record envRec takes arguments name (a String) and strict (a Boolean) and returns either a normal completion containing an ECMAScript language value or a throw completion. 이것은 이름이 name인 바인딩된 식별자의 값을 반환한다. 바인딩이 초기화되지 않은 바인딩이면, ReferenceError 예외를 던진다. 이름이 name인 바인딩은 보통 이미 존재하지만, 존재하지 않거나 현재 writable하지 않은 경우 오류 처리는 strict에 의해 결정된다. It performs the following steps when called:

  1. declarativeRecordenvRec.[[DeclarativeRecord]]라고 하자.
  2. declarativeRecord.HasBinding(name)이 true이면,
    1. declarativeRecord.GetBindingValue(name, strict)를 반환한다.
  3. objectRecordenvRec.[[ObjectRecord]]라고 하자.
  4. objectRecord.GetBindingValue(name, strict)를 반환한다.

9.1.1.4.7 DeleteBinding ( name )

The DeleteBinding concrete method of a Global Environment Record envRec takes argument name (a String) and returns either a normal completion containing a Boolean or a throw completion. 이것은 명시적으로 삭제 가능 대상으로 지정된 바인딩만 삭제할 수 있다. It performs the following steps when called:

  1. declarativeRecordenvRec.[[DeclarativeRecord]]라고 하자.
  2. declarativeRecord.HasBinding(name)이 true이면,
    1. declarativeRecord.DeleteBinding(name)를 반환한다.
  3. objectRecordenvRec.[[ObjectRecord]]라고 하자.
  4. globalObjectobjectRecord.[[BindingObject]]라고 하자.
  5. existingProp를 ? HasOwnProperty(globalObject, name)라고 하자.
  6. existingProptrue이면,
    1. objectRecord.DeleteBinding(name)를 반환한다.
  7. true를 반환한다.

9.1.1.4.8 HasThisBinding ( )

The HasThisBinding concrete method of a 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 GetThisBinding ( )

The GetThisBinding concrete method of a Global Environment Record envRec takes no arguments and returns a normal completion containing an Object. It performs the following steps when called:

  1. envRec.[[GlobalThisValue]]를 반환한다.

9.1.1.4.10 HasSuperBinding ( )

The HasSuperBinding concrete method of a 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.11 WithBaseObject ( )

The WithBaseObject concrete method of a Global Environment Record envRec takes no arguments and returns undefined. It performs the following steps when called:

  1. undefined를 반환한다.

9.1.1.4.12 HasLexicalDeclaration ( envRec, name )

The abstract operation HasLexicalDeclaration takes arguments envRec (a Global Environment Record) and name (a String) and returns a Boolean. 이것은 인수 식별자가 LexicalDeclaration이나 ClassDeclaration과 같은 lexical declaration을 사용해 envRec 안에 생성된 바인딩을 가지는지 결정한다. It performs the following steps when called:

  1. declarativeRecordenvRec.[[DeclarativeRecord]]라고 하자.
  2. declarativeRecord.HasBinding(name)를 반환한다.

9.1.1.4.13 HasRestrictedGlobalProperty ( envRec, name )

The abstract operation HasRestrictedGlobalProperty takes arguments envRec (a Global Environment Record) and name (a String) and returns either a normal completion containing a Boolean or a throw completion. 이것은 인수 식별자가 전역 lexical 바인딩에 의해 가려져서는 안 되는 전역 객체의 프로퍼티 이름인지 결정한다. It performs the following steps when called:

  1. objectRecordenvRec.[[ObjectRecord]]라고 하자.
  2. globalObjectobjectRecord.[[BindingObject]]라고 하자.
  3. existingProp를 ? globalObject.[[GetOwnProperty]](name)라고 하자.
  4. existingPropundefined이면, false를 반환한다.
  5. existingProp.[[Configurable]]true이면, false를 반환한다.
  6. true를 반환한다.
Note

전역 객체에는 var 또는 함수 선언을 사용해 선언된 것이 아니라 직접 생성된 프로퍼티가 존재할 수 있다. 전역 lexical 바인딩은 전역 객체의 non-configurable 프로퍼티와 같은 이름으로 생성될 수 없다. 전역 프로퍼티 "undefined"는 그러한 프로퍼티의 예이다.

9.1.1.4.14 CanDeclareGlobalVar ( envRec, name )

The abstract operation CanDeclareGlobalVar takes arguments envRec (a Global Environment Record) and name (a String) and returns either a normal completion containing a Boolean or a throw completion. 이것은 동일한 인수 name에 대해 대응하는 CreateGlobalVarBinding 호출이 수행된다면 성공할지를 결정한다. 중복 var 선언과 기존 전역 객체 프로퍼티에 대한 var 선언은 허용된다. It performs the following steps when called:

  1. objectRecordenvRec.[[ObjectRecord]]라고 하자.
  2. globalObjectobjectRecord.[[BindingObject]]라고 하자.
  3. hasProperty를 ? HasOwnProperty(globalObject, name)라고 하자.
  4. hasPropertytrue이면, true를 반환한다.
  5. IsExtensible(globalObject)를 반환한다.

9.1.1.4.15 CanDeclareGlobalFunction ( envRec, name )

The abstract operation CanDeclareGlobalFunction takes arguments envRec (a Global Environment Record) and name (a String) and returns either a normal completion containing a Boolean or a throw completion. 이것은 동일한 인수 name에 대해 대응하는 CreateGlobalFunctionBinding 호출이 수행된다면 성공할지를 결정한다. It performs the following steps when called:

  1. objectRecordenvRec.[[ObjectRecord]]라고 하자.
  2. globalObjectobjectRecord.[[BindingObject]]라고 하자.
  3. existingProp를 ? globalObject.[[GetOwnProperty]](name)라고 하자.
  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, name, deletable )

The abstract operation CreateGlobalVarBinding takes arguments envRec (a Global Environment Record), name (a String), and deletable (a Boolean) and returns either a normal completion containing unused or a throw completion. 이것은 연관된 Object Environment Record 안에 가변 바인딩을 생성하고 초기화한다. 바인딩이 이미 존재하면, 그것을 재사용하며 이미 초기화된 것으로 간주한다. It performs the following steps when called:

  1. objectRecordenvRec.[[ObjectRecord]]라고 하자.
  2. globalObjectobjectRecord.[[BindingObject]]라고 하자.
  3. hasProperty를 ? HasOwnProperty(globalObject, name)라고 하자.
  4. extensible을 ? IsExtensible(globalObject)라고 하자.
  5. hasPropertyfalse이고 extensibletrue이면,
    1. objectRecord.CreateMutableBinding(name, deletable)를 수행한다.
    2. objectRecord.InitializeBinding(name, undefined)를 수행한다.
  6. unused를 반환한다.

9.1.1.4.17 CreateGlobalFunctionBinding ( envRec, name, value, deletable )

The abstract operation CreateGlobalFunctionBinding takes arguments envRec (a Global Environment Record), name (a String), value (an ECMAScript function object), and deletable (a Boolean) and returns either a normal completion containing unused or a throw completion. 이것은 연관된 Object Environment Record 안에 가변 바인딩을 생성하고 초기화한다. 바인딩이 이미 존재하면, 그것을 교체한다. It performs the following steps when called:

  1. objectRecordenvRec.[[ObjectRecord]]라고 하자.
  2. globalObjectobjectRecord.[[BindingObject]]라고 하자.
  3. existingProp를 ? globalObject.[[GetOwnProperty]](name)라고 하자.
  4. existingPropundefined이거나 existingProp.[[Configurable]]true이면,
    1. desc를 PropertyDescriptor { [[Value]]: value, [[Writable]]: true, [[Enumerable]]: true, [[Configurable]]: deletable }라고 하자.
  5. 그렇지 않으면,
    1. desc를 PropertyDescriptor { [[Value]]: value }라고 하자.
  6. DefinePropertyOrThrow(globalObject, name, desc)를 수행한다.
  7. Set(globalObject, name, value, false)를 수행한다.
  8. unused를 반환한다.
Note

전역 함수 선언은 항상 전역 객체의 own 프로퍼티로 표현된다. 가능하다면 기존 own 프로퍼티는 표준 속성 값 집합을 가지도록 재구성된다. 단계 7InitializeBinding 구체 메서드를 호출했을 때 하는 일과 동등하며, globalObject가 Proxy라면 같은 순서의 Proxy trap 호출을 발생시킨다.

9.1.1.5 Module Environment Record

Module Environment Record는 ECMAScript Module의 바깥 스코프를 나타내는 데 사용되는 Declarative Environment Record이다. 일반적인 가변 및 불변 바인딩에 더해, Module Environment Record는 불변 import 바인딩도 제공하는데, 이것은 다른 Environment Record에 존재하는 대상 바인딩에 대한 간접 접근을 제공하는 바인딩이다.

Module Environment Record는 Table 14에 나열된 모든 Declarative Environment Record 메서드를 지원하며, GetBindingValue, DeleteBinding, HasThisBinding, GetThisBinding을 제외한 모든 메서드에 대해 같은 명세를 공유한다.

9.1.1.5.1 GetBindingValue ( name, strict )

The GetBindingValue concrete method of a Module Environment Record envRec takes arguments name (a String) and strict (a Boolean) and returns either a normal completion containing an ECMAScript language value or a throw completion. 이것은 이름이 name인 바인딩된 식별자의 값을 반환한다. 그러나 바인딩이 간접 바인딩이면, 대상 바인딩의 값을 반환한다. 바인딩이 존재하지만 초기화되지 않았다면 ReferenceError가 던져진다. It performs the following steps when called:

  1. Assert: stricttrue이다.
  2. Assert: envRecname에 대한 바인딩을 가지고 있다.
  3. name에 대한 바인딩이 간접 바인딩이면,
    1. moduletargetName을 이 name에 대한 바인딩이 생성될 때 제공된 간접 참조 값이라고 하자.
    2. targetEnvmodule.[[Environment]]라고 하자.
    3. targetEnvempty이면, ReferenceError 예외를 던진다.
    4. targetEnv.GetBindingValue(targetName, true)를 반환한다.
  4. envRec 안의 name에 대한 바인딩이 초기화되지 않은 바인딩이면, ReferenceError 예외를 던진다.
  5. envRec 안에서 현재 name에 바인딩된 값을 반환한다.
Note

Module은 항상 strict mode 코드이기 때문에 strict은 항상 true이다.

9.1.1.5.2 DeleteBinding ( name )

Module Environment RecordDeleteBinding 구체 메서드는 이 명세에서 결코 사용되지 않는다.

Note

Module Environment Record는 오직 strict 코드 안에서만 사용되며, early error 규칙은 strict 코드에서 delete 연산자가 Module Environment Record 바인딩으로 해석될 Reference Record에 적용되는 것을 방지한다. 13.5.1.1를 보라.

9.1.1.5.3 HasThisBinding ( )

The HasThisBinding concrete method of a 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 a Module Environment Record envRec takes no arguments and returns a normal completion containing undefined. It performs the following steps when called:

  1. undefined를 반환한다.

9.1.1.5.5 CreateImportBinding ( envRec, name, targetModule, targetName )

The abstract operation CreateImportBinding takes arguments envRec (a Module Environment Record), name (a String), targetModule (a Module Record), and targetName (a String) and returns unused. 이것은 이름 name에 대해 초기화된 새로운 불변 간접 바인딩을 생성한다. envRec 안에는 name에 대한 바인딩이 이미 존재해서는 안 된다. targetNametargetModuleModule Environment Record 안에 존재하는 바인딩의 이름이다. 새 바인딩 값에 대한 접근은 대상 바인딩의 바인딩된 값에 간접적으로 접근하게 된다. It performs the following steps when called:

  1. Assert: envRecname에 대한 바인딩을 이미 가지고 있지 않다.
  2. Assert: targetModule.[[Environment]]가 instantiate될 때, 그것은 targetName에 대한 직접 바인딩을 가질 것이다.
  3. envRec 안에 name에 대한 불변 간접 바인딩을 생성하고, 그 대상 바인딩으로 targetModuletargetName을 참조하도록 한 뒤, 그 바인딩이 초기화되었음을 기록한다.
  4. unused를 반환한다.

9.1.2 Environment Record 연산

다음 추상 연산들은 이 명세에서 Environment Record를 조작하는 데 사용된다:

9.1.2.1 GetIdentifierReference ( env, name, strict )

The abstract operation GetIdentifierReference takes arguments env (an Environment Record or null), name (a String), and strict (a Boolean) and returns either a normal completion containing a Reference Record or a throw completion. It performs the following steps when called:

  1. 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. outerenv.[[OuterEnv]]라고 하자.
  5. GetIdentifierReference(outer, name, strict)를 반환한다.

9.1.2.2 NewDeclarativeEnvironment ( outerEnv )

The abstract operation NewDeclarativeEnvironment takes argument outerEnv (an Environment Record or null) and returns a Declarative Environment Record. It performs the following steps when called:

  1. 아무 바인딩도 포함하지 않는 새로운 Declarative Environment Recordenv라고 하자.
  2. env.[[OuterEnv]]outerEnv로 설정한다.
  3. env를 반환한다.

9.1.2.3 NewObjectEnvironment ( obj, isWithEnvironment, outerEnv )

The abstract operation NewObjectEnvironment takes arguments obj (an Object), isWithEnvironment (a Boolean), and outerEnv (an Environment Record or null) and returns an Object Environment Record. It performs the following steps when called:

  1. 새로운 Object Environment Recordenv라고 하자.
  2. env.[[BindingObject]]obj로 설정한다.
  3. env.[[IsWithEnvironment]]isWithEnvironment로 설정한다.
  4. env.[[OuterEnv]]outerEnv로 설정한다.
  5. env를 반환한다.

9.1.2.4 NewFunctionEnvironment ( func, newTarget )

The abstract operation NewFunctionEnvironment takes arguments func (an ECMAScript function object) and newTarget (an Object or undefined) and returns a Function Environment Record. It performs the following steps when called:

  1. 아무 바인딩도 포함하지 않는 새로운 Function Environment Recordenv라고 하자.
  2. env.[[FunctionObject]]func로 설정한다.
  3. func.[[ThisMode]]lexical이면, env.[[ThisBindingStatus]]lexical로 설정한다.
  4. 그렇지 않으면, env.[[ThisBindingStatus]]uninitialized로 설정한다.
  5. env.[[NewTarget]]newTarget으로 설정한다.
  6. env.[[OuterEnv]]func.[[Environment]]로 설정한다.
  7. env를 반환한다.

9.1.2.5 NewGlobalEnvironment ( obj, thisValue )

The abstract operation NewGlobalEnvironment takes arguments obj (an Object) and thisValue (an Object) and returns a Global Environment Record. It performs the following steps when called:

  1. objRecNewObjectEnvironment(obj, false, null)라고 하자.
  2. dclRecNewDeclarativeEnvironment(null)라고 하자.
  3. 새로운 Global Environment Recordenv라고 하자.
  4. env.[[ObjectRecord]]objRec로 설정한다.
  5. env.[[GlobalThisValue]]thisValue로 설정한다.
  6. env.[[DeclarativeRecord]]dclRec로 설정한다.
  7. env.[[OuterEnv]]null로 설정한다.
  8. env를 반환한다.

9.1.2.6 NewModuleEnvironment ( outerEnv )

The abstract operation NewModuleEnvironment takes argument outerEnv (a Global Environment Record) and returns a Module Environment Record. It performs the following steps when called:

  1. 아무 바인딩도 포함하지 않는 새로운 Module Environment Recordenv라고 하자.
  2. env.[[OuterEnv]]outerEnv로 설정한다.
  3. env를 반환한다.

9.2 PrivateEnvironment Record

PrivateEnvironment Record는 ECMAScript 코드 안의 ClassDeclarationClassExpression의 어휘적 중첩 구조를 바탕으로 Private Name을 추적하는 데 사용되는 명세 메커니즘이다. 이것들은 Environment Record와 유사하지만, 서로 구별된다. 각 PrivateEnvironment RecordClassDeclaration 또는 ClassExpression과 연관된다. 그러한 클래스가 평가될 때마다, 그 클래스에 의해 선언된 Private Name을 기록하기 위해 새로운 PrivateEnvironment Record가 생성된다.

PrivateEnvironment RecordTable 18에 정의된 필드를 가진다.

Table 18: PrivateEnvironment Record Fields
필드 이름 값 타입 의미
[[OuterPrivateEnvironment]] a PrivateEnvironment Record or null 가장 가까운 바깥 클래스의 PrivateEnvironment Record. 이 PrivateEnvironment Record와 연관된 클래스가 다른 어떤 클래스 안에도 포함되어 있지 않다면 null이다.
[[Names]] a List of Private Names 이 클래스에 의해 선언된 Private Name.

9.2.1 PrivateEnvironment Record 연산

다음 추상 연산들은 이 명세에서 PrivateEnvironment Record를 조작하는 데 사용된다:

9.2.1.1 NewPrivateEnvironment ( outerPrivateEnv )

The abstract operation NewPrivateEnvironment takes argument outerPrivateEnv (a PrivateEnvironment Record or null) and returns a PrivateEnvironment Record. It performs the following steps when called:

  1. names를 새로운 빈 List라고 하자.
  2. PrivateEnvironment Record { [[OuterPrivateEnvironment]]: outerPrivateEnv, [[Names]]: names }를 반환한다.

9.2.1.2 ResolvePrivateIdentifier ( privateEnv, identifier )

The abstract operation ResolvePrivateIdentifier takes arguments privateEnv (a PrivateEnvironment Record) and identifier (a String) and returns a Private Name. It performs the following steps when called:

  1. namesprivateEnv.[[Names]]라고 하자.
  2. names의 각 Private Name pn에 대해, 다음을 수행한다.
    1. pn.[[Description]]identifier이면,
      1. pn을 반환한다.
  3. outerPrivateEnvprivateEnv.[[OuterPrivateEnvironment]]라고 하자.
  4. Assert: outerPrivateEnvnull이 아니다.
  5. ResolvePrivateIdentifier(outerPrivateEnv, identifier)를 반환한다.

9.3 Realm

평가되기 전에, 모든 ECMAScript 코드는 반드시 realm과 연관되어야 한다. 개념적으로 realm은 intrinsic object들의 집합, ECMAScript 전역 환경, 그 전역 환경의 범위 안에서 로드된 모든 ECMAScript 코드, 그리고 다른 연관된 상태 및 자원으로 구성된다.

realm은 이 명세에서 Table 19에 명시된 필드를 가진 Realm Record로 표현된다:

Table 19: Realm Record Fields
필드 이름 의미
[[AgentSignifier]] an agent signifier realm을 소유하는 agent
[[Intrinsics]] 필드 이름이 intrinsic key이고 값이 객체인 Record realm과 연관된 코드가 사용하는 intrinsic 값
[[GlobalObject]] an Object realm전역 객체
[[GlobalEnv]] a Global Environment Record realm의 전역 환경
[[TemplateMap]] [[Site]] (a TemplateLiteral Parse Node)와 [[Array]] (an Array) 필드를 가진 Record들의 List

템플릿 객체는 각 realmRealm Record[[TemplateMap]]을 사용해 별도로 canonicalize된다. 각 [[Site]] 값은 TemplateLiteral인 Parse Node이다. 연관된 [[Array]] 값은 tag 함수에 전달되는 대응 템플릿 객체이다.

Note 1
어떤 Parse Node가 도달 불가능해지면, 대응하는 [[Array]]도 역시 도달 불가능해지며, 구현이 그 쌍을 [[TemplateMap]] 리스트에서 제거하더라도 관찰 불가능하다.
[[LoadedModules]] LoadedModuleRequest Record들의 List

realm이 import한 specifier 문자열에서 해석된 Module Record로의 맵. 이 리스트는 ModuleRequestsEqual(r1, r2)가 true인 서로 다른 두 Record r1r2를 포함하지 않는다.

Note 2
HostLoadImportedModule에서 언급했듯이 (16.2.1.10 Note 1), Realm Record[[LoadedModules]]는 활성 script나 module이 없는 문맥에서 import() 표현식을 실행할 때에만 사용된다.
[[HostDefined]] anything (기본값은 undefined) Realm Record와 추가 정보를 연관시켜야 하는 호스트를 위해 예약된 필드.

9.3.1 InitializeHostDefinedRealm ( )

The abstract operation InitializeHostDefinedRealm takes no arguments and returns either a normal completion containing unused or a throw completion. It performs the following steps when called:

  1. 새로운 Realm Recordrealm이라고 하자.
  2. CreateIntrinsics(realm)를 수행한다.
  3. realm.[[AgentSignifier]]AgentSignifier()로 설정한다.
  4. realm.[[TemplateMap]]를 새로운 빈 List로 설정한다.
  5. 새로운 execution contextnewContext라고 하자.
  6. newContext의 Function을 null로 설정한다.
  7. newContextRealmrealm으로 설정한다.
  8. newContext의 ScriptOrModule을 null로 설정한다.
  9. newContextexecution context stack에 push한다; 이제 newContextrunning execution context이다.
  10. 호스트realm전역 객체로 사용될 특정 객체를 요구하면,
    1. global호스트 정의 방식으로 생성된 그러한 객체라고 하자.
  11. 그렇지 않으면,
    1. globalOrdinaryObjectCreate(realm.[[Intrinsics]].[[%Object.prototype%]])라고 하자.
  12. 호스트realm의 전역 스코프에서 this 바인딩이 전역 객체가 아닌 다른 객체를 반환하도록 요구하면,
    1. thisValue호스트 정의 방식으로 생성된 그러한 객체라고 하자.
  13. 그렇지 않으면,
    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 (a Realm Record) and returns unused. It performs the following steps when called:

  1. realmRec.[[Intrinsics]]를 새로운 Record로 설정한다.
  2. Table 6에 나열된 값으로 realmRec.[[Intrinsics]]의 필드를 설정한다. 필드 이름은 표의 “Intrinsic Name” 열에 나열된 이름들이다. 각 필드의 값은 19부터 28까지의 절에서 각 객체의 명세에 따라 완전하고 재귀적으로 프로퍼티 값이 채워진 새로운 객체 값이다. 모든 객체 프로퍼티 값은 새로 생성된 객체 값이다. 내장 함수 객체인 모든 값은, steps가 이 명세에 제공된 그 함수의 정의이고, name이 함수의 "name" 프로퍼티의 초기값이며, length가 함수의 "length" 프로퍼티의 초기값이고, slots가 함수의 명시된 internal slot 이름들의 리스트(있다면)이며, prototype이 함수의 [[Prototype]] internal slot의 명시된 값이고, async가 함수가 “async”로 설명되는 경우 true 아니면 false일 때, CreateBuiltinFunction(steps, length, name, slots, realmRec, prototype, async)를 수행함으로써 생성된다. intrinsic 및 그 프로퍼티의 생성은 아직 생성되지 않은 객체에 대한 의존성을 피할 수 있도록 순서가 정해져야 한다.
  3. AddRestrictedFunctionProperties(realmRec.[[Intrinsics]].[[%Function.prototype%]], realmRec)를 수행한다.
  4. unused를 반환한다.

9.3.3 SetDefaultGlobalBindings ( realmRec )

The abstract operation SetDefaultGlobalBindings takes argument realmRec (a Realm Record) and returns either a normal completion containing unused or a throw completion. It performs the following steps when called:

  1. globalrealmRec.[[GlobalObject]]라고 하자.
  2. 19에 명시된 Global Object의 각 프로퍼티에 대해, 다음을 수행한다.
    1. name을 프로퍼티 이름의 String 값이라고 하자.
    2. desc를 그 프로퍼티에 대해 명시된 속성을 포함하는, 완전히 채워진 데이터 Property Descriptor라고 하자. 19.2, 19.3, 또는 19.4에 나열된 프로퍼티들에 대해서는 [[Value]] 속성의 값이 realmRec의 대응 intrinsic object이다.
    3. DefinePropertyOrThrow(global, name, desc)를 수행한다.
  3. unused를 반환한다.

9.4 Execution Context

execution context는 ECMAScript 구현에 의한 코드의 런타임 평가를 추적하는 데 사용되는 명세 장치이다. 어떤 시점에도 실제로 코드를 실행 중인 execution context는 agent당 최대 하나뿐이다. 이것을 그 agent의 running execution context라고 한다. 이 명세에서 running execution context에 대한 모든 참조는 주변 agent의 running execution context를 의미한다.

execution context stack은 execution context를 추적하는 데 사용된다. running execution context는 항상 이 스택의 최상단 요소이다. 현재 running execution context와 연관된 실행 가능한 코드에서 그 execution context와 연관되지 않은 실행 가능한 코드로 제어가 이전될 때마다 새로운 execution context가 생성된다. 새로 생성된 execution context는 스택에 push되고 running execution context가 된다.

execution context는 연관된 코드의 실행 진행을 추적하는 데 필요한 구현 특화 상태를 포함한다. 각 execution context는 최소한 Table 20에 나열된 상태 구성요소를 가진다.

Table 20: State Components for All Execution Contexts
구성요소 목적
코드 평가 상태 execution context와 연관된 코드의 평가를 수행, 중단, 재개하는 데 필요한 모든 상태.
Function execution context가 함수 객체의 코드를 평가 중이라면, 이 구성요소의 값은 그 함수 객체이다. context가 Script 또는 Module의 코드를 평가 중이라면, 값은 null이다.
Realm 연관된 코드가 ECMAScript 자원에 접근하는 Realm Record.
ScriptOrModule 연관된 코드의 기원이 되는 Module Record 또는 Script Record. InitializeHostDefinedRealm에서 생성되는 최초 execution context의 경우처럼 원래의 script나 module이 없다면, 값은 null이다.

running execution context에 의한 코드 평가는 이 명세 안에 정의된 여러 지점에서 중단될 수 있다. running execution context가 한 번 중단되면, 다른 execution context가 running execution context가 되어 자신의 코드를 평가하기 시작할 수 있다. 이후 어느 시점에 중단된 execution context가 다시 running execution context가 되어, 이전에 중단되었던 지점부터 자신의 코드 평가를 계속할 수 있다. execution context들 사이에서 running execution context 상태의 전이는 보통 스택과 같은 후입선출 방식으로 일어난다. 그러나 일부 ECMAScript 기능은 running execution context의 비-LIFO 전이를 요구한다.

running execution contextRealm 구성요소 값은 current Realm Record라고도 한다. running execution context의 Function 구성요소 값은 active function object라고도 한다.

ECMAScript 코드 실행 컨텍스트Table 21에 나열된 추가 상태 구성 요소를 가진다.

Table 21: Additional State Components for ECMAScript Code Execution Contexts
구성요소 목적
LexicalEnvironment execution context 안의 코드가 만드는 식별자 참조를 해석하는 데 사용되는 Environment Record를 식별한다.
VariableEnvironment execution context 안의 VariableStatement에 의해 생성된 바인딩을 보유하는 Environment Record를 식별한다.
PrivateEnvironment 가장 가까운 바깥 클래스의 ClassElement에 의해 생성된 Private Name을 보유하는 PrivateEnvironment Record를 식별한다. 바깥 클래스가 없으면 null이다.

execution context의 LexicalEnvironment와 VariableEnvironment 구성요소는 항상 Environment Record이다.

Generator 평가를 나타내는 execution context는 Table 22에 나열된 추가 상태 구성요소를 가진다.

Table 22: Additional State Components for Generator Execution Contexts
구성요소 목적
Generator execution context가 평가하고 있는 Generator.

대부분의 상황에서는 오직 running execution context(즉 execution context stack의 최상단)만이 이 명세의 알고리즘에 의해 직접 조작된다. 따라서 “LexicalEnvironment”, “VariableEnvironment”라는 용어가 한정 없이 사용될 때는 running execution context의 해당 구성요소를 가리킨다.

execution context는 순전히 명세 메커니즘이며, ECMAScript 구현의 어떤 특정 산출물과 대응할 필요는 없다. ECMAScript 코드가 execution context에 직접 접근하거나 관찰하는 것은 불가능하다.

9.4.1 GetActiveScriptOrModule ( )

The abstract operation GetActiveScriptOrModule takes no arguments and returns a Script Record, a Module Record, or null. 이것은 running execution context를 바탕으로 현재 실행 중인 script 또는 module을 결정하는 데 사용된다. It performs the following steps when called:

  1. execution context stack이 비어 있으면, null을 반환한다.
  2. ecexecution context stack에서 ScriptOrModule 구성요소가 null이 아닌 최상단 execution context라고 하자.
  3. 그러한 execution context가 존재하지 않으면, null을 반환한다.
  4. ec의 ScriptOrModule을 반환한다.

9.4.2 ResolveBinding ( name [ , env ] )

The abstract operation ResolveBinding takes argument name (a String) and optional argument env (an Environment Record or undefined) and returns either a normal completion containing a Reference Record or a throw completion. 이것은 name의 바인딩을 결정하는 데 사용된다. env는 바인딩을 검색할 Environment Record를 명시적으로 제공하는 데 사용될 수 있다. It performs the following steps when called:

  1. env가 주어지지 않았거나 envundefined이면,
    1. envrunning execution context의 LexicalEnvironment로 설정한다.
  2. Assert: envEnvironment Record이다.
  3. strict을 평가 중인 구문 production의 IsStrict라고 하자.
  4. GetIdentifierReference(env, name, strict)를 반환한다.
Note

ResolveBinding의 결과는 항상 [[ReferencedName]] 필드가 nameReference Record이다.

9.4.3 GetThisEnvironment ( )

The abstract operation GetThisEnvironment takes no arguments and returns an 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. Assert: outernull이 아니다.
    5. envouter로 설정한다.
Note

단계 2의 반복은 항상 종료된다. 왜냐하면 환경 리스트는 언제나 this 바인딩을 가지는 전역 환경에서 끝나기 때문이다.

9.4.4 ResolveThisBinding ( )

The abstract operation ResolveThisBinding takes no arguments and returns either a normal completion containing an ECMAScript language value or a throw completion. 이것은 running execution context의 LexicalEnvironment를 사용해 키워드 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 an Object or undefined. 이것은 running execution context의 LexicalEnvironment를 사용해 NewTarget 값을 결정한다. It performs the following steps when called:

  1. envRecGetThisEnvironment()라고 하자.
  2. Assert: envRec[[NewTarget]] 필드를 가진다.
  3. envRec.[[NewTarget]]를 반환한다.

9.4.6 GetGlobalObject ( )

The abstract operation GetGlobalObject takes no arguments and returns an Object. 이것은 현재 running execution context가 사용하는 전역 객체를 반환한다. It performs the following steps when called:

  1. currentRealmcurrent Realm Record라고 하자.
  2. currentRealm.[[GlobalObject]]를 반환한다.

9.4.7 RunSuspendedContext ( context, completionRecord )

The abstract operation RunSuspendedContext takes arguments context (an execution context) and completionRecord (a Completion Record) and returns either a normal completion containing either an ECMAScript language value or unused, or an abrupt completion. 이는 context를 재개하고(completionRecord를 재개 값으로 전송), 그 결과를 기다린다. It performs the following steps when called:

  1. callerContext를 실행 중인 실행 컨텍스트라 하자.
  2. callerContext를 일시 중단한다.
  3. context를 실행 컨텍스트 스택에 푸시한다. 이제 context가 실행 중인 실행 컨텍스트이다.
  4. context의 일시 중단된 평가를 재개한다. 이때 completionRecord를 그것을 일시 중단한 연산의 결과로 사용한다. 재개된 계산이 반환한 Completion Recordresult라 하자.
  5. Assert: 이 단계에 도달했을 때, context는 이미 실행 컨텍스트 스택에서 제거되었고 callerContext가 다시 실행 중인 실행 컨텍스트이다.
  6. Completion(result)를 반환한다.

9.5 Job과 Job을 enqueue하기 위한 호스트 연산

Job은 매개변수가 없는 Abstract Closure이며, 현재 다른 ECMAScript 계산이 진행 중이 아닐 때 ECMAScript 계산을 시작한다.

Job은 ECMAScript 호스트 환경에 의해 특정 agent에서 실행되도록 스케줄된다. 이 명세는 Job을 스케줄하기 위해 HostEnqueueGenericJob, HostEnqueueFinalizationRegistryCleanupJob, HostEnqueuePromiseJob, HostEnqueueTimeoutJob이라는 호스트 훅을 설명한다. 이 명세의 호스트 훅Job 스케줄링에 부과되는 추가 제약에 따라 조직되어 있다. 호스트Job을 스케줄하는 추가 추상 연산을 정의할 수 있다. 이러한 연산은 Job Abstract Closurerealm(Realm Record 또는 null)을 매개변수로 받는다. Realm Record가 제공되면, 이 연산은 제공된 realm 안에서, 그 realm을 소유한 agent 안에서, 미래의 어느 시점에 job이 수행되도록 스케줄한다. 대신 realmnull이 제공되면, 그 job은 ECMAScript 코드를 평가하지 않는다. 이들의 구현은 다음 요구 사항을 준수해야 한다:

  • 미래의 어느 시점에, job이 스케줄된 agent에 running context가 없고 그 agent의 execution context stack이 비어 있을 때, 구현은 반드시:
    1. 호스트 정의 준비 단계를 수행해야 한다.
    2. Job Abstract Closure호출해야 한다.
    3. 호스트 정의 정리 단계를 수행해야 하며, 그 후 execution context stack은 반드시 비어 있어야 한다.
  • 한 agent 안에서 어느 시점에도 평가가 활발히 진행 중인 Job은 오직 하나뿐이어야 한다.
  • Job의 평가가 시작되면, 그 agent 안에서 다른 Job의 평가가 시작되기 전에 반드시 완료까지 실행되어야 한다.
  • Abstract Closure는 정상 완료를 반환해야 하며, 오류 처리는 자체적으로 구현해야 한다.
Note 1
호스트 환경은 스케줄링과 관련해 Job을 균일하게 취급할 필요가 없다. 예를 들어, 웹 브라우저와 Node.js는 Promise 처리 Job을 다른 작업보다 더 높은 우선순위로 취급한다; 미래의 기능은 이렇게 높은 우선순위로 취급되지 않는 Job을 추가할 수 있다.

어떤 특정 시점에, scriptOrModule(Script Record, Module Record, 또는 null)은 다음 조건이 모두 참이면 active script or module이다:

어떤 특정 시점에, 다음 조건이 모두 참이면 하나의 execution은 ECMAScript 코드를 평가할 준비가 되어 있다:

Note 2

호스트 환경execution contextexecution context stack에 push함으로써 execution이 코드를 평가할 준비가 되게 만들 수 있다. 구체적인 단계는 구현 정의이다.

Realm의 구체적인 선택은 호스트 환경에 달려 있다. 이 초기 execution contextRealm은 어떤 callback 함수도 호출되기 전까지만 사용된다. Promise handler처럼 Job과 관련된 callback 함수가 호출되면, 그 호출은 자신의 execution contextRealm을 push한다.

특정 종류의 Job에는 추가 적합성 요구 사항이 있다.

9.5.1 JobCallback Record

JobCallback Record는 함수 객체와 호스트 정의 값을 저장하는 데 사용되는 Record 값이다. 호스트에 의해 enqueue된 Job을 통해 호출되는 함수 객체는 추가적인 호스트 정의 문맥을 가질 수 있다. 이 상태를 전파하기 위해, Job Abstract Closure는 함수 객체를 직접 캡처해서 호출해서는 안 된다. 대신 HostMakeJobCallbackHostCallJobCallback을 사용한다.

Note

예를 들어 WHATWG HTML 명세 (https://html.spec.whatwg.org/)는 Promise callback에 대한 incumbent settings object를 전파하기 위해 호스트 정의 값을 사용한다.

JobCallback Record는 Table 23에 나열된 필드를 가진다.

Table 23: JobCallback Record Fields
필드 이름 의미
[[Callback]] a function object Job이 호출될 때 호출할 함수.
[[HostDefined]] anything (기본값은 empty) 호스트용으로 예약된 필드.

9.5.2 HostMakeJobCallback ( callback )

The host-defined abstract operation HostMakeJobCallback takes argument callback (a function object) and returns a JobCallback Record.

HostMakeJobCallback의 구현은 다음 요구 사항을 준수해야 한다:

HostMakeJobCallback의 기본 구현은 호출되었을 때 다음 단계를 수행한다:

  1. JobCallback Record { [[Callback]]: callback, [[HostDefined]]: empty }를 반환한다.

웹 브라우저가 아닌 ECMAScript 호스트는 HostMakeJobCallback의 기본 구현을 사용해야 한다.

Note

이것은 callback이 결국 스케줄되고 실행되도록 책임지는 함수에 전달되는 시점에 호출된다. 예를 들어, promise.then(thenAction)은 reaction Job이 스케줄되는 시점이 아니라 Promise.prototype.then 호출 시점에 thenAction에 대해 MakeJobCallback을 호출한다.

9.5.3 HostCallJobCallback ( jobCallback, value, argumentsList )

The host-defined abstract operation HostCallJobCallback takes arguments jobCallback (a JobCallback Record), value (an ECMAScript language value), and argumentsList (a List of ECMAScript language values) and returns either a normal completion containing an ECMAScript language value or a throw completion.

HostCallJobCallback의 구현은 다음 요구 사항을 준수해야 한다:

  • 반드시 Call(jobCallback.[[Callback]], value, argumentsList)를 수행하고 그 결과를 반환해야 한다.
Note

이 요구 사항은 호스트가 이 명세에 정의된 함수 객체의 [[Call]] 동작을 변경할 수 없음을 의미한다.

HostCallJobCallback의 기본 구현은 호출되었을 때 다음 단계를 수행한다:

  1. Assert: IsCallable(jobCallback.[[Callback]])는 true이다.
  2. Call(jobCallback.[[Callback]], value, argumentsList)를 반환한다.

웹 브라우저가 아닌 ECMAScript 호스트는 HostCallJobCallback의 기본 구현을 사용해야 한다.

9.5.4 HostEnqueueGenericJob ( job, realm )

The host-defined abstract operation HostEnqueueGenericJob takes arguments job (a Job Abstract Closure) and realm (a Realm Record) and returns unused. 이것은 realm.[[AgentSignifier]]로 표시되는 agent 안의 realm realm에서 job이 미래의 어느 시점에 수행되도록 스케줄한다. 이 알고리즘과 함께 사용되는 Abstract Closure는 우선순위나 순서 같은 추가 제약 없이 스케줄되도록 의도된다.

HostEnqueueGenericJob의 구현은 9.5의 요구 사항을 준수해야 한다.

9.5.5 HostEnqueuePromiseJob ( job, realm )

The host-defined abstract operation HostEnqueuePromiseJob takes arguments job (a Job Abstract Closure) and realm (a Realm Record or null) and returns unused. 이것은 job이 미래의 어느 시점에 수행되도록 스케줄한다. 이 알고리즘과 함께 사용되는 Abstract Closure는 Promise 처리와 관련되거나, 또는 Promise 처리 연산과 동등한 우선순위로 스케줄되도록 의도된다.

HostEnqueuePromiseJob의 구현은 9.5의 요구 사항뿐 아니라 다음도 준수해야 한다:

  • realmnull이 아니면, job이 호출될 때마다 구현은 job 호출 시점에 execution이 ECMAScript 코드를 평가할 준비가 되어 있도록 구현 정의 단계를 수행해야 한다.
  • HostEnqueuePromiseJob이 호출되는 시점의 GetActiveScriptOrModule()을 scriptOrModule이라 하자. realmnull이 아니면, job이 호출될 때마다 구현은 job 호출 시점에 scriptOrModule이 active script 또는 module이 되도록 구현 정의 단계를 수행해야 한다.
  • Job은 그것들을 스케줄한 HostEnqueuePromiseJob 호출과 같은 순서로 실행되어야 한다.
Note

NewPromiseResolveThenableJob이 반환하는 Job에 대한 realm은 보통 then 함수 객체에 대해 GetFunctionRealm을 호출한 결과이다. NewPromiseReactionJob이 반환하는 Job에 대한 realm은 handler가 undefined가 아닐 경우 보통 handler에 대해 GetFunctionRealm을 호출한 결과이다. handler가 undefined이면, realmnull이다. 두 종류의 Job 모두에서, GetFunctionRealm이 비정상 완료하는 경우(즉 취소된 Proxy에 대해 호출된 경우), realmGetFunctionRealm 호출 시점의 current Realm Record이다. realmnull일 때는 사용자 ECMAScript 코드는 평가되지 않으며 새로운 ECMAScript 객체(예: Error 객체)도 생성되지 않는다. 예를 들어 WHATWG HTML 명세 (https://html.spec.whatwg.org/)는 스크립트를 실행할 수 있는지 여부와 entry 개념을 확인하기 위해 realm을 사용한다.

9.5.6 HostEnqueueTimeoutJob ( timeoutJob, realm, milliseconds )

The host-defined abstract operation HostEnqueueTimeoutJob takes arguments timeoutJob (a Job Abstract Closure), realm (a Realm Record), and milliseconds (a non-negative finite Number) and returns unused. 이것은 realm.[[AgentSignifier]]로 표시되는 agent 안의 realm realm에서 timeoutJob이 적어도 milliseconds 밀리초 이후에 수행되도록 스케줄한다.

HostEnqueueTimeoutJob의 구현은 9.5의 요구 사항을 준수해야 한다.

9.6 에이전트

에이전트는 ECMAScript 실행 컨텍스트들의 집합, 실행 컨텍스트 스택, 실행 중인 실행 컨텍스트, 에이전트 레코드, 그리고 실행 스레드로 구성된다. 실행 스레드를 제외하면, 에이전트의 구성 요소는 오직 해당 에이전트에만 속한다.

에이전트실행 스레드는 다른 에이전트들과 독립적으로 그 에이전트의 실행 컨텍스트들에 대해 알고리즘 단계를 수행한다. 단, 스레드를 공유하는 에이전트들 중 어느 것도 [[CanBlock]] 필드가 true에이전트 레코드를 가지지 않는다면, 하나의 실행 스레드가 여러 에이전트실행 스레드로 사용될 수 있다.

Note 1

예를 들어, 일부 웹 브라우저는 브라우저 창의 서로 관련 없는 여러 탭 사이에서 하나의 실행 스레드를 공유한다.

에이전트실행 스레드가 알고리즘 단계를 실행하고 있는 동안, 그 단계들에 대해 해당 에이전트주변 에이전트이다. 그 단계들은 주변 에이전트를 사용하여 에이전트 내부에 보관된 명세 수준 실행 객체들, 즉 실행 중인 실행 컨텍스트, 실행 컨텍스트 스택, 그리고 에이전트 레코드의 필드들에 접근한다.

에이전트 식별자에이전트를 식별하는 데 사용되는 전역적으로 고유한 불투명 값이다.

Table 24: Agent Record Fields
필드 이름 의미
[[LittleEndian]] a Boolean GetValueFromBufferSetValueInBuffer 알고리즘이 isLittleEndian 매개변수를 필요로 할 때 계산되는 기본값이다. 이 선택은 구현 정의이며, 구현에 가장 효율적인 대안이어야 한다.
[[CanBlock]] a Boolean 에이전트가 블록될 수 있는지 여부를 결정한다.
[[Signifier]] an agent signifier 자신의 에이전트 클러스터 내에서 해당 에이전트를 고유하게 식별한다.
[[IsLockFree1]] a Boolean 1-바이트 값에 대한 원자적 연산이 lock-free이면 true, 그렇지 않으면 false이다.
[[IsLockFree2]] a Boolean 2-바이트 값에 대한 원자적 연산이 lock-free이면 true, 그렇지 않으면 false이다.
[[IsLockFree8]] a Boolean 8-바이트 값에 대한 원자적 연산이 lock-free이면 true, 그렇지 않으면 false이다.
[[CandidateExecution]] a candidate execution Record 메모리 모델을 보라.
[[KeptAlive]] a List of either Objects or Symbols 초기값은 새로운 빈 List이며, 현재 Job이 끝날 때까지 살아 있도록 유지해야 하는 객체 및/또는 심벌들의 목록을 나타낸다
[[ModuleAsyncEvaluationCount]] an integer 초기값은 0이며, 비동기적이거나 비동기 의존성을 가진 모듈의 [[AsyncEvaluationOrder]] 필드에 고유하게 증가하는 값을 할당하는 데 사용된다.

[[LittleEndian]], [[Signifier]], [[IsLockFree1]], [[IsLockFree2]], 그리고 [[IsLockFree8]]의 값은 변경될 수 없다.

Note 2

[[IsLockFree1]], [[IsLockFree2]], 그리고 [[IsLockFree8]]의 값은 반드시 하드웨어에 의해 결정되는 것은 아니며, ECMAScript 구현마다 그리고 시간에 따라 달라질 수 있는 구현 선택을 반영할 수도 있다.

[[IsLockFree4]] 필드는 없다: 4바이트 원자적 연산은 항상 lock-free이다.

실제로, 원자적 연산이 어떤 종류의 락으로 구현된다면 그 연산은 lock-free가 아니다. Lock-free는 wait-free를 의미하지 않는다: lock-free 원자적 연산을 완료하는 데 얼마나 많은 머신 단계가 필요할지에 대한 상한은 없다.

크기 n의 원자적 접근이 lock-free라는 사실은 크기 n의 비원자적 접근의 (인지된) 원자성에 대해 아무것도 의미하지 않는다. 특히 비원자적 접근은 여전히 여러 개의 개별 메모리 접근 시퀀스로 수행될 수 있다. 자세한 내용은 ReadSharedMemoryWriteSharedMemory를 보라.

Note 3

에이전트는 명세 메커니즘이며, ECMAScript 구현의 어떤 특정 산출물과 대응할 필요는 없다.

9.6.1 AgentSignifier ( )

The abstract operation AgentSignifier takes no arguments and returns an agent signifier. It performs the following steps when called:

  1. agentRecord주변 에이전트에이전트 레코드라고 하자.
  2. agentRecord.[[Signifier]]를 반환한다.

9.6.2 AgentCanSuspend ( )

The abstract operation AgentCanSuspend takes no arguments and returns a Boolean. It performs the following steps when called:

  1. agentRecord주변 에이전트에이전트 레코드라고 하자.
  2. agentRecord.[[CanBlock]]를 반환한다.
Note

일부 환경에서는 특정 에이전트가 중단될 수 있도록 하는 것이 합리적이지 않을 수 있다. 예를 들어 웹 브라우저 환경에서는 문서의 메인 이벤트 처리 스레드의 중단을 허용하지 않는 것이 합리적일 수 있지만, 워커의 이벤트 처리 스레드는 여전히 중단을 허용할 수 있다.

9.6.3 IncrementModuleAsyncEvaluationCount ( )

The abstract operation IncrementModuleAsyncEvaluationCount takes no arguments and returns a non-negative integer. It performs the following steps when called:

  1. agentRecord주변 에이전트에이전트 레코드라고 하자.
  2. countagentRecord.[[ModuleAsyncEvaluationCount]]라고 하자.
  3. agentRecord.[[ModuleAsyncEvaluationCount]]count + 1로 설정한다.
  4. count를 반환한다.
Note

이 값은 보류 중인 모듈들 사이의 상대적 평가 순서를 추적하는 데만 사용된다. 구현은 보류 중인 모듈이 없을 때마다 [[ModuleAsyncEvaluationCount]]를 관찰 불가능하게 0으로 재설정할 수 있다.

9.7 에이전트 클러스터

에이전트 클러스터는 공유 메모리에서 동작함으로써 통신할 수 있는 에이전트들의 최대 집합이다.

Note 1

서로 다른 에이전트 내의 프로그램들은 명시되지 않은 수단으로 메모리를 공유할 수 있다. 최소한 SharedArrayBuffer의 백킹 메모리는 클러스터 내 에이전트들 사이에서 공유될 수 있다.

메시지 전달로는 통신할 수 있지만 메모리를 공유할 수는 없는 에이전트들이 있을 수 있으며, 그러한 에이전트들은 결코 같은 에이전트 클러스터에 속하지 않는다.

모든 에이전트는 정확히 하나의 에이전트 클러스터에 속한다.

Note 2

클러스터에 속한 에이전트들이 어떤 특정 시점에 모두 살아 있을 필요는 없다. 에이전트 A가 다른 에이전트 B를 생성하고, 그 후 A가 종료되며 B에이전트 C를 생성하는 경우, AB와 어떤 메모리를 공유할 수 있었고 BC와 어떤 메모리를 공유할 수 있었다면 이 세 에이전트는 같은 클러스터에 속한다.

클러스터 내의 모든 에이전트는 각자의 에이전트 레코드에서 [[LittleEndian]] 필드에 대해 같은 값을 가져야 한다.

Note 3

에이전트 클러스터 내의 서로 다른 에이전트들이 [[LittleEndian]]의 서로 다른 값을 가지면 다중 바이트 데이터에 공유 메모리를 사용하는 것이 어려워진다.

클러스터 내의 모든 에이전트는 각자의 에이전트 레코드에서 [[IsLockFree1]] 필드에 대해 같은 값을 가져야 하며, [[IsLockFree2]][[IsLockFree8]] 필드도 마찬가지이다.

클러스터 내의 모든 에이전트는 각자의 에이전트 레코드에서 [[Signifier]] 필드에 대해 서로 다른 값을 가져야 한다.

임베딩은 에이전트의 지식이나 협조 없이 에이전트를 비활성화(전진 진행 중지)하거나 활성화(전진 진행 재개)할 수 있다. 임베딩이 그렇게 하는 경우, 클러스터 내 일부 에이전트는 활성 상태로 두면서 다른 에이전트들은 무기한 비활성화된 상태로 남겨두어서는 안 된다.

Note 4

앞선 제한의 목적은 다른 에이전트가 비활성화되었기 때문에 어떤 에이전트가 교착 상태에 빠지거나 기아 상태에 빠지는 상황을 피하는 것이다. 예를 들어, 어떤 창의 문서들과 독립된 수명을 가진 HTML 공유 워커가, 그러한 독립 문서의 전용 워커와 메모리를 공유하는 것이 허용되었고, 문서와 그 전용 워커가 전용 워커가 락을 쥔 상태에서 비활성화된다면(예를 들어 문서가 자신의 창 기록으로 밀려나는 경우), 그 후 공유 워커가 그 락을 획득하려고 하면 공유 워커는 전용 워커가 다시 활성화될 때까지, 혹은 영원히, 블록될 것이다. 그 사이 다른 창에서 공유 워커에 접근하려는 다른 워커들은 기아 상태에 빠질 것이다.

이 제한의 함의는, 임베딩 내에서 같은 suspend/wake 집합에 속하지 않는 에이전트들 사이에서는 메모리를 공유하는 것이 불가능하다는 점이다.

임베딩은 클러스터의 다른 에이전트들의 사전 지식이나 협조 없이 에이전트를 종료할 수 있다. 에이전트가 자기 자신이나 클러스터 내 다른 에이전트의 프로그램적 동작이 아니라 클러스터 외부의 힘에 의해 종료되는 경우, 임베딩은 두 가지 전략 중 하나를 선택해야 한다: 클러스터의 모든 에이전트를 종료하거나, 또는 클러스터 내 에이전트들이 조정할 수 있도록 신뢰할 수 있는 API를 제공하여 적어도 하나의 남아 있는 클러스터 구성원이 종료를 감지할 수 있게 해야 하며, 종료 데이터는 종료된 에이전트를 식별하기에 충분한 정보를 포함해야 한다.

Note 5

그러한 유형의 종료 예시는 다음과 같다: 별도 프로세스에서 실행 중인 에이전트를 운영체제나 사용자가 종료하는 경우; 또는 임베딩 자체가 다른 에이전트들과 같은 프로세스 내에서 실행 중인 에이전트를 종료하는 경우로, 에이전트별 자원 회계 결과 그 에이전트가 폭주 중이라고 나타나는 경우이다.

다음 명세 값 각각과, 그것들로부터 전이적으로 도달 가능한 값들은 정확히 하나의 에이전트 클러스터에 속한다.

클러스터 내 어떤 에이전트에 의한 어떤 ECMAScript 코드 평가보다도 먼저, 클러스터 내 모든 에이전트에 대한 에이전트 레코드[[CandidateExecution]] 필드는 초기 candidate execution으로 설정된다. 초기 candidate execution은 빈 candidate execution이며, 그 [[EventsRecords]] 필드는 각 에이전트마다 하나씩 Agent Events Record를 포함하는 List이다. 각 Agent Events Record[[AgentSignifier]] 필드는 해당 에이전트에이전트 식별자이고, [[EventList]][[AgentSynchronizesWith]] 필드는 빈 List이다.

Note 6

에이전트 클러스터 내의 모든 에이전트에이전트 레코드[[CandidateExecution]] 필드 안에서 같은 candidate execution을 공유한다. candidate execution메모리 모델에서 사용되는 명세 메커니즘이다.

Note 7

에이전트 클러스터는 명세 메커니즘이며, ECMAScript 구현의 어떤 특정 산출물과 대응할 필요는 없다.

9.8 전진 진행

에이전트전진 진행을 한다는 것은 이 명세에 따라 평가 단계를 수행하는 것을 의미한다.

에이전트의 실행 중인 실행 컨텍스트가 외부 이벤트를 동기적으로 그리고 무기한 기다릴 때, 그 에이전트블록된다. 이러한 의미에서 블록될 수 있는 것은 에이전트 레코드[[CanBlock]] 필드가 true에이전트뿐이다. 블록되지 않은 에이전트는 블록되지 않은 에이전트이다.

구현은 반드시 다음을 보장해야 한다:

Note

이것은 메모리 모델의 liveness 보장과 함께, 모든 seq-cst 쓰기가 결국 모든 에이전트에서 관찰 가능해짐을 보장한다.

9.9 WeakRef 및 FinalizationRegistry 대상의 처리 모델

9.9.1 목표

이 명세는 어떤 객체나 심벌이 가비지 컬렉션될 것이라는 어떠한 보장도 하지 않는다. 살아 있지 않은 객체나 심벌은 오랜 시간이 지난 뒤에 해제될 수도 있고, 아예 해제되지 않을 수도 있다. 이러한 이유로, 이 명세는 가비지 컬렉션에 의해 유발되는 동작을 설명할 때 "may"라는 용어를 사용한다.

WeakRefFinalizationRegistry의 의미론은 특정 시점에 일어나는 두 연산을 기반으로 한다:

이 두 동작(ClearKeptObjects 또는 CleanupFinalizationRegistry) 중 어느 것도 동기 ECMAScript 실행을 중단시켜서는 안 된다. 호스트는 더 긴 동기 ECMAScript 실행 구간을 구성할 수 있기 때문에, 이 명세는 ClearKeptObjectsCleanupFinalizationRegistry의 스케줄링을 호스트 환경에 위임한다.

일부 ECMAScript 구현은 ECMAScript가 유휴 상태일 때를 포함해 백그라운드에서 실행되는 가비지 컬렉터 구현을 포함한다. 호스트 환경CleanupFinalizationRegistry를 스케줄할 수 있게 하면, finalizer 작업을 실행하기 위해 ECMAScript 실행을 재개할 수 있고, 이로 인해 held value를 해제하여 전체 메모리 사용량을 줄일 수 있다.

9.9.2 Liveness

어떤 객체 및/또는 심벌들의 집합 objectSet에 대해, objectSet에 관한 가정적 WeakRef-무시 실행이란, referent가 objectSet의 원소인 WeakRef추상 연산 WeakRefDeref가 항상 undefined를 반환하는 실행을 말한다.

Note 1
WeakRef-무시성과 liveness는 함께 두 가지 개념을 포착한다. 첫째, WeakRef 자체는 referent를 살아 있게 유지하지 않는다는 점이다. 둘째, liveness의 순환이 어떤 값이 살아 있음을 의미하지는 않는다는 점이다. 구체적으로 말하면, v의 liveness를 결정하는 일이 WeakRef referent인 r의 liveness를 결정하는 데 의존한다면, r의 liveness는 v의 liveness를 가정할 수 없는데, 이는 순환 논법이 되기 때문이다.
Note 2
WeakRef-무시성은 순환을 고려하기 위해 개별 값이 아니라 객체나 심벌의 집합에 대해 정의된다. 만약 개별 값에 대해 정의된다면, 순환 안에 있는 WeakRef referent는 그 정체성이 오직 순환 안의 다른 WeakRef referent를 통해서만 관찰되더라도 살아 있는 것으로 간주될 것이다.
Note 3
구어적으로, 어떤 개별 객체 또는 심벌을 포함하는 모든 집합이 live라면 그 객체 또는 심벌은 live하다고 말한다.

평가 중 어느 시점에서든, 객체 및/또는 심벌들의 집합 objectSet은 다음 조건 중 하나라도 만족하면 live하다고 간주된다:

  • objectSet의 어떤 원소든 임의의 에이전트[[KeptAlive]] List에 포함된다.
  • objectSet에 관해 유효한 미래의 가정적 WeakRef-무시 실행이 존재하며, 그 실행이 objectSet 안의 어떤 값의 정체성을 관찰한다.
Note 4
위의 두 번째 조건은 어떤 값의 정체성이 비-WeakRef 수단으로 관찰 가능하다면 그 값이 live하다는 직관을 포착하려는 것이다. 값의 정체성은 strict equality 비교를 관찰하거나, 그 값이 Map의 key로 사용되는 것을 관찰함으로써 관찰될 수 있다.
Note 5

객체나 심벌이 어떤 필드, 내부 슬롯, 또는 프로퍼티 안에 존재한다고 해서 그 값이 live하다는 뜻은 아니다. 예를 들어 해당 값이 결코 프로그램으로 다시 전달되지 않는다면, 그 값은 관찰될 수 없다.

이는 WeakMap의 key, WeakSet의 member, 그리고 FinalizationRegistry Cell record의 [[WeakRefTarget]][[UnregisterToken]] 필드의 경우에 해당한다.

위 정의는, WeakMap의 key가 live하지 않다면 그에 대응하는 value도 반드시 live한 것은 아니라는 점을 함의한다.

Note 6
Liveness는 엔진이 비워서는 안 되는 WeakRef를 보장하는 하한이다. 여기서 정의된 liveness는 결정 불가능하다. 실제로 엔진은 도달 가능성과 같은 보수적 근사를 사용한다. 구현에는 상당한 재량이 기대된다.

9.9.3 실행

어느 시점에서든, 객체 및/또는 심벌들의 집합 objectSetlive하지 않다면, ECMAScript 구현은 다음 단계를 원자적으로 수행할 수 있다:

  1. objectSet의 각 원소 value에 대해, 다음을 수행한다
    1. ref.[[WeakRefTarget]]value인 각 WeakRef ref에 대해, 다음을 수행한다
      1. ref.[[WeakRefTarget]]empty로 설정한다.
    2. fg.[[Cells]]cell.[[WeakRefTarget]]valueRecord cell을 포함하는 각 FinalizationRegistry fg에 대해, 다음을 수행한다
      1. cell.[[WeakRefTarget]]empty로 설정한다.
      2. 선택적으로, HostEnqueueFinalizationRegistryCleanupJob(fg)를 수행한다.
    3. map.[[WeakMapData]]r.[[Key]]valueRecord r을 포함하는 각 WeakMap map에 대해, 다음을 수행한다
      1. r.[[Key]]empty로 설정한다.
      2. r.[[Value]]empty로 설정한다.
    4. set.[[WeakSetData]]value를 포함하는 각 WeakSet set에 대해, 다음을 수행한다.
      1. set.[[WeakSetData]]에서 값이 value인 원소를 값이 empty인 원소로 교체한다.
Note 1

liveness의 정의와 함께, 이 절은 구현이 WeakRef와 관련하여 적용할 수 있는 최적화를 규정한다.

객체의 정체성을 관찰하지 않고도 객체에 접근하는 것은 가능하다. 정체성이 관찰되지 않는 비탈출 객체의 프로퍼티에 대한 dead variable elimination이나 scalar replacement 같은 최적화는 허용된다. 따라서 이러한 최적화는 그러한 객체를 가리키는 WeakRef를 관찰 가능하게 비우는 것도 허용된다.

반면에 어떤 객체의 정체성이 관찰 가능하고, 그 객체가 WeakRef[[WeakRefTarget]] 내부 슬롯 안에 있다면, WeakRef를 관찰 가능하게 비우는 rematerialization 같은 최적화는 금지된다.

HostEnqueueFinalizationRegistryCleanupJob 호출은 선택적이므로, FinalizationRegistry에 등록된 객체가 반드시 그 FinalizationRegistrylive하게 유지하는 것은 아니다. 구현은 예를 들어 FinalizationRegistry 자체가 죽었거나, 애플리케이션이 종료 중인 경우 등 어떤 이유로든 FinalizationRegistry callback을 생략할 수 있다.

Note 2

구현은 live하지 않은 객체나 심벌의 최대 집합에 대해 WeakRef를 비울 의무가 없다.

구현이 WeakRef를 비울 live하지 않은 집합 objectSet을 선택한다면, 이 정의는 objectSet 안의 모든 값에 대한 WeakRef를 동시에 비워야 함을 요구한다. 즉, 구현이 어떤 값 v를 가리키는 WeakRef를 비우면서, 비워지지 않을 경우 v의 값을 관찰하는 실행이 가능해질 수 있는 다른 WeakRef는 비우지 않는 것은 적합하지 않다.

9.9.4 호스트 훅

9.9.4.1 HostEnqueueFinalizationRegistryCleanupJob ( finalizationRegistry )

The host-defined abstract operation HostEnqueueFinalizationRegistryCleanupJob takes argument finalizationRegistry (a FinalizationRegistry) and returns unused.

finalizationRegistry를 캡처하고, 호출될 때 다음 단계를 수행하는 매개변수 없는 새로운 Job Abstract ClosurecleanupJob이라고 하자:

  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주변 에이전트에이전트 레코드라고 하자.
  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주변 에이전트에이전트 레코드라고 하자.
  2. valueagentRecord.[[KeptAlive]]에 추가한다.
  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. Assert: finalizationRegistry[[Cells]][[CleanupCallback]] 내부 슬롯을 가진다.
  2. callbackfinalizationRegistry.[[CleanupCallback]]이라고 하자.
  3. finalizationRegistry.[[Cells]]cell.[[WeakRefTarget]]emptyRecord cell을 포함하는 동안, 구현은 다음 단계를 수행할 수 있다:
    1. 그러한 cell 중 임의의 것을 선택한다.
    2. cellfinalizationRegistry.[[Cells]]에서 제거한다.
    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가 약한 참조로 사용되기에 적합한 경우에만 true를 반환한다. 약한 참조로 사용되기에 적합한 값만이 WeakMap의 키, WeakSet의 원소, WeakRef의 대상, 또는 FinalizationRegistry의 대상들 중 하나가 될 수 있다. It performs the following steps when called:

  1. v가 Object이면, true를 반환한다.
  2. v가 Symbol이고 KeyForSymbol(v)가 undefined이면, true를 반환한다.
  3. false를 반환한다.
Note

언어적 동일성이 없는 언어 값은 사전 참조 없이도 나타날 수 있으며, 약한 참조로 사용되기에 부적합하다. Symbol.for에 의해 생성된 Symbol 값은 다른 Symbol 값과 달리 언어적 동일성을 가지지 않으며, 약한 참조로 사용되기에 부적합하다. well-known symbol은 수집되지 않을 가능성이 높지만, 개수가 제한되어 있어 다양한 구현 접근법으로 관리 가능하므로 여전히 약한 참조로 사용되기에 적합한 것으로 취급된다. 그러나 live한 WeakMap 안에서 well-known symbol에 연관된 어떤 값이든 수집되지 않을 가능성이 높으며, 구현에서 메모리 자원을 “누수”시킬 수 있다.

10 일반 객체 및 이색 객체 동작

10.1 일반 객체 내부 메서드와 내부 슬롯

모든 일반 객체는 [[Prototype]]이라는 내부 슬롯을 가진다. 이 내부 슬롯의 값은 null 또는 객체이며 상속을 구현하는 데 사용된다. propertyKey라는 이름의 프로퍼티가 일반 객체 obj에는 없지만 그 [[Prototype]] 객체에는 존재한다고 가정하자. propertyKey[[Prototype]] 객체의 데이터 프로퍼티를 가리키면, obj는 get 접근에 대해 그것을 상속받아 propertyKeyobj의 프로퍼티인 것처럼 동작한다. propertyKey[[Prototype]] 객체의 쓰기 가능한 데이터 프로퍼티를 가리키면, obj에서 propertyKey에 대한 set 접근은 objpropertyKey라는 이름의 새로운 데이터 프로퍼티를 생성한다. propertyKey[[Prototype]] 객체의 쓰기 불가능한 데이터 프로퍼티를 가리키면, obj에서 propertyKey에 대한 set 접근은 실패한다. propertyKey[[Prototype]] 객체의 접근자 프로퍼티를 가리키면, 그 접근자는 get 접근과 set 접근 모두에 대해 obj에 상속된다.

모든 일반 객체는 Boolean 값의 [[Extensible]] 내부 슬롯을 가지며, 이는 6.1.7.3에 명시된 확장 가능성과 관련된 내부 메서드 불변식을 충족하는 데 사용된다. 즉, 객체의 [[Extensible]] 내부 슬롯 값이 한 번 false로 설정되면, 더 이상 그 객체에 프로퍼티를 추가하거나, 객체의 [[Prototype]] 내부 슬롯 값을 수정하거나, 이후 [[Extensible]]의 값을 true로 다시 변경하는 것은 불가능하다.

다음 알고리즘 설명에서, obj는 일반 객체이고, propertyKey는 프로퍼티 키 값이며, value는 임의의 ECMAScript 언어 값이고, descProperty Descriptor 레코드라고 가정한다.

각 일반 객체 내부 메서드는 유사한 이름의 추상 연산에 위임한다. 그러한 추상 연산이 다른 내부 메서드에 의존한다면, 유사한 이름의 추상 연산을 직접 호출하는 대신 그 내부 메서드가 obj에 대해 호출된다. 이러한 의미론은 일반 객체 내부 메서드가 이색 객체에 적용될 때, 이색 객체가 재정의한 내부 메서드가 호출되도록 보장한다.

10.1.1 [[GetPrototypeOf]] ( )

The [[GetPrototypeOf]] internal method of 일반 객체 obj takes no arguments and returns a normal completion containing either an Object or null. It performs the following steps when called:

  1. OrdinaryGetPrototypeOf(obj)를 반환한다.

10.1.1.1 OrdinaryGetPrototypeOf ( obj )

The abstract operation OrdinaryGetPrototypeOf takes argument obj (an Object) and returns an Object or null. It performs the following steps when called:

  1. obj.[[Prototype]]를 반환한다.

10.1.2 [[SetPrototypeOf]] ( proto )

The [[SetPrototypeOf]] internal method of 일반 객체 obj takes argument proto (an Object or null) and returns a normal completion containing a Boolean. It performs the following steps when called:

  1. OrdinarySetPrototypeOf(obj, proto)를 반환한다.

10.1.2.1 OrdinarySetPrototypeOf ( obj, proto )

The abstract operation OrdinarySetPrototypeOf takes arguments obj (an Object) and proto (an Object or null) and returns a Boolean. It performs the following steps when called:

  1. currentobj.[[Prototype]]라고 하자.
  2. SameValue(proto, current)가 true이면, true를 반환한다.
  3. extensibleobj.[[Extensible]]이라고 하자.
  4. extensiblefalse이면, false를 반환한다.
  5. cursorproto라고 하자.
  6. donefalse라고 하자.
  7. donefalse인 동안, 다음을 반복한다.
    1. cursornull이면,
      1. donetrue로 설정한다.
    2. 그렇지 않고 SameValue(cursor, obj)가 true이면,
      1. false를 반환한다.
    3. 그렇지 않으면,
      1. cursor.[[GetPrototypeOf]]10.1.1에 정의된 일반 객체 내부 메서드가 아니면, donetrue로 설정한다.
      2. 그렇지 않으면, cursorcursor.[[Prototype]]로 설정한다.
  8. obj.[[Prototype]]proto로 설정한다.
  9. true를 반환한다.
Note

단계 7의 반복은 [[GetPrototypeOf]][[SetPrototypeOf]]에 대해 일반 객체 정의를 사용하는 객체만 포함하는 모든 프로토타입 체인에 순환이 없음을 보장한다.

10.1.3 [[IsExtensible]] ( )

The [[IsExtensible]] internal method of 일반 객체 obj takes no arguments and returns a normal completion containing a Boolean. It performs the following steps when called:

  1. OrdinaryIsExtensible(obj)를 반환한다.

10.1.3.1 OrdinaryIsExtensible ( obj )

The abstract operation OrdinaryIsExtensible takes argument obj (an Object) and returns a Boolean. It performs the following steps when called:

  1. obj.[[Extensible]]를 반환한다.

10.1.4 [[PreventExtensions]] ( )

The [[PreventExtensions]] internal method of 일반 객체 obj takes no arguments and returns a normal completion containing true. It performs the following steps when called:

  1. OrdinaryPreventExtensions(obj)를 반환한다.

10.1.4.1 OrdinaryPreventExtensions ( obj )

The abstract operation OrdinaryPreventExtensions takes argument obj (an Object) and returns true. It performs the following steps when called:

  1. obj.[[Extensible]]false로 설정한다.
  2. true를 반환한다.

10.1.5 [[GetOwnProperty]] ( propertyKey )

The [[GetOwnProperty]] internal method of 일반 객체 obj takes argument propertyKey (a property key) and returns a normal completion containing either a Property Descriptor or undefined. It performs the following steps when called:

  1. OrdinaryGetOwnProperty(obj, propertyKey)를 반환한다.

10.1.5.1 OrdinaryGetOwnProperty ( obj, propertyKey )

The abstract operation OrdinaryGetOwnProperty takes arguments obj (an Object) and propertyKey (a property key) and returns a Property Descriptor or undefined. It performs the following steps when called:

  1. obj가 키가 propertyKey인 자체 프로퍼티를 가지지 않으면, undefined를 반환한다.
  2. 필드가 없는 새로 생성된 Property Descriptordesc라고 하자.
  3. ownProperty를 키가 propertyKeyobj의 자체 프로퍼티라고 하자.
  4. ownProperty가 데이터 프로퍼티이면,
    1. desc.[[Value]]ownProperty[[Value]] 속성 값으로 설정한다.
    2. desc.[[Writable]]ownProperty[[Writable]] 속성 값으로 설정한다.
  5. 그렇지 않으면,
    1. Assert: ownProperty는 접근자 프로퍼티이다.
    2. desc.[[Get]]ownProperty[[Get]] 속성 값으로 설정한다.
    3. desc.[[Set]]ownProperty[[Set]] 속성 값으로 설정한다.
  6. desc.[[Enumerable]]ownProperty[[Enumerable]] 속성 값으로 설정한다.
  7. desc.[[Configurable]]ownProperty[[Configurable]] 속성 값으로 설정한다.
  8. desc를 반환한다.

10.1.6 [[DefineOwnProperty]] ( propertyKey, desc )

The [[DefineOwnProperty]] internal method of 일반 객체 obj takes arguments propertyKey (a property key) and desc (a Property Descriptor) and returns either a normal completion containing a Boolean or a throw completion. It performs the following steps when called:

  1. OrdinaryDefineOwnProperty(obj, propertyKey, desc)를 반환한다.

10.1.6.1 OrdinaryDefineOwnProperty ( obj, propertyKey, desc )

The abstract operation OrdinaryDefineOwnProperty takes arguments obj (an Object), propertyKey (a property key), and desc (a Property Descriptor) and returns either a normal completion containing a Boolean or a throw completion. It performs the following steps when called:

  1. current를 ? obj.[[GetOwnProperty]](propertyKey)라고 하자.
  2. extensible을 ? IsExtensible(obj)라고 하자.
  3. ValidateAndApplyPropertyDescriptor(obj, propertyKey, extensible, 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 ( obj, propertyKey, extensible, desc, current )

The abstract operation ValidateAndApplyPropertyDescriptor takes arguments obj (an Object or undefined), propertyKey (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를 반환한다. 그러한 적용이 가능하고 objundefined가 아니면, propertyKey라는 이름의 프로퍼티에 대해 그 적용이 수행된다(필요하면 생성된다). It performs the following steps when called:

  1. Assert: propertyKey는 프로퍼티 키이다.
  2. currentundefined이면,
    1. extensiblefalse이면, false를 반환한다.
    2. objundefined이면, true를 반환한다.
    3. IsAccessorDescriptor(desc)가 true이면,
      1. desc에 해당 필드가 있으면 그 값으로, 없으면 해당 속성의 기본값으로 [[Get]], [[Set]], [[Enumerable]], [[Configurable]] 속성이 설정된 propertyKey라는 이름의 자체 접근자 프로퍼티를 객체 obj에 생성한다.
    4. 그렇지 않으면,
      1. desc에 해당 필드가 있으면 그 값으로, 없으면 해당 속성의 기본값으로 [[Value]], [[Writable]], [[Enumerable]], [[Configurable]] 속성이 설정된 propertyKey라는 이름의 자체 데이터 프로퍼티를 객체 obj에 생성한다.
    5. true를 반환한다.
  3. Assert: 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. 그렇지 않고 current.[[Writable]]false이면,
      1. desc[[Writable]] 필드를 가지고 있고 desc.[[Writable]]true이면, false를 반환한다.
      2. NOTE: SameValue는 다른 수단으로 구별될 수 있는 NaN 값에 대해서도 true를 반환한다. 여기서 반환함으로써 obj의 기존 프로퍼티가 수정되지 않도록 보장한다.
      3. desc[[Value]] 필드를 가지고 있으면, SameValue(desc.[[Value]], current.[[Value]])를 반환한다.
  6. objundefined가 아니면,
    1. IsDataDescriptor(current)가 true이고 IsAccessorDescriptor(desc)가 true이면,
      1. desc[[Configurable]] 필드를 가지면 configurabledesc.[[Configurable]]라고 하자; 그렇지 않으면 configurablecurrent.[[Configurable]]라고 하자.
      2. desc[[Enumerable]] 필드를 가지면 enumerabledesc.[[Enumerable]]라고 하자; 그렇지 않으면 enumerablecurrent.[[Enumerable]]라고 하자.
      3. 객체 objpropertyKey라는 이름의 프로퍼티를, [[Configurable]][[Enumerable]] 속성은 각각 configurableenumerable로 설정하고, [[Get]][[Set]] 속성은 desc에 해당 필드가 있으면 그 값으로, 없으면 해당 속성의 기본값으로 설정한 접근자 프로퍼티로 교체한다.
    2. 그렇지 않고 IsAccessorDescriptor(current)가 true이며 IsDataDescriptor(desc)가 true이면,
      1. desc[[Configurable]] 필드를 가지면 configurabledesc.[[Configurable]]라고 하자; 그렇지 않으면 configurablecurrent.[[Configurable]]라고 하자.
      2. desc[[Enumerable]] 필드를 가지면 enumerabledesc.[[Enumerable]]라고 하자; 그렇지 않으면 enumerablecurrent.[[Enumerable]]라고 하자.
      3. 객체 objpropertyKey라는 이름의 프로퍼티를, [[Configurable]][[Enumerable]] 속성은 각각 configurableenumerable로 설정하고, [[Value]][[Writable]] 속성은 desc에 해당 필드가 있으면 그 값으로, 없으면 해당 속성의 기본값으로 설정한 데이터 프로퍼티로 교체한다.
    3. 그렇지 않으면,
      1. desc의 각 필드 이름 fieldName에 대해, 객체 objpropertyKey라는 이름의 프로퍼티에서 fieldName이라는 속성을 descfieldName 필드 값으로 설정한다.
  7. true를 반환한다.

10.1.7 [[HasProperty]] ( propertyKey )

The [[HasProperty]] internal method of 일반 객체 obj takes argument propertyKey (a property key) and returns either a normal completion containing a Boolean or a throw completion. It performs the following steps when called:

  1. OrdinaryHasProperty(obj, propertyKey)를 반환한다.

10.1.7.1 OrdinaryHasProperty ( obj, propertyKey )

The abstract operation OrdinaryHasProperty takes arguments obj (an Object) and propertyKey (a property key) and returns either a normal completion containing a Boolean or a throw completion. It performs the following steps when called:

  1. hasOwn을 ? obj.[[GetOwnProperty]](propertyKey)라고 하자.
  2. hasOwnundefined가 아니면, true를 반환한다.
  3. parent를 ? obj.[[GetPrototypeOf]]()라고 하자.
  4. parentnull이 아니면,
    1. parent.[[HasProperty]](propertyKey)를 반환한다.
  5. false를 반환한다.

10.1.8 [[Get]] ( propertyKey, receiver )

The [[Get]] internal method of 일반 객체 obj takes arguments propertyKey (a property key) and receiver (an ECMAScript language value) and returns either a normal completion containing an ECMAScript language value or a throw completion. It performs the following steps when called:

  1. OrdinaryGet(obj, propertyKey, receiver)를 반환한다.

10.1.8.1 OrdinaryGet ( obj, propertyKey, receiver )

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

  1. desc를 ? obj.[[GetOwnProperty]](propertyKey)라고 하자.
  2. descundefined이면,
    1. parent를 ? obj.[[GetPrototypeOf]]()라고 하자.
    2. parentnull이면, undefined를 반환한다.
    3. parent.[[Get]](propertyKey, receiver)를 반환한다.
  3. IsDataDescriptor(desc)가 true이면, desc.[[Value]]를 반환한다.
  4. Assert: IsAccessorDescriptor(desc)는 true이다.
  5. getterdesc.[[Get]]이라고 하자.
  6. getterundefined이면, undefined를 반환한다.
  7. Call(getter, receiver)를 반환한다.

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

The [[Set]] internal method of 일반 객체 obj takes arguments propertyKey (a property key), value (an ECMAScript language value), and receiver (an ECMAScript language value) and returns either a normal completion containing a Boolean or a throw completion. It performs the following steps when called:

  1. OrdinarySet(obj, propertyKey, value, receiver)를 반환한다.

10.1.9.1 OrdinarySet ( obj, propertyKey, value, receiver )

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

  1. ownDesc를 ? obj.[[GetOwnProperty]](propertyKey)라고 하자.
  2. OrdinarySetWithOwnDescriptor(obj, propertyKey, value, receiver, ownDesc)를 반환한다.

10.1.9.2 OrdinarySetWithOwnDescriptor ( obj, propertyKey, value, receiver, ownDesc )

The abstract operation OrdinarySetWithOwnDescriptor takes arguments obj (an Object), propertyKey (a property key), value (an ECMAScript language value), receiver (an ECMAScript language value), and ownDesc (a Property Descriptor or undefined) and returns either a normal completion containing a Boolean or a throw completion. It performs the following steps when called:

  1. ownDescundefined이면,
    1. parent를 ? obj.[[GetPrototypeOf]]()라고 하자.
    2. parentnull이 아니면, ? parent.[[Set]](propertyKey, value, receiver)를 반환한다.
    3. ownDesc를 PropertyDescriptor { [[Value]]: undefined, [[Writable]]: true, [[Enumerable]]: true, [[Configurable]]: true }로 설정한다.
  2. IsDataDescriptor(ownDesc)가 true이면,
    1. ownDesc.[[Writable]]false이면, false를 반환한다.
    2. receiver가 Object가 아니면, false를 반환한다.
    3. existingDescriptor를 ? receiver.[[GetOwnProperty]](propertyKey)라고 하자.
    4. existingDescriptorundefined이면,
      1. Assert: receiver는 현재 propertyKey 프로퍼티를 가지고 있지 않다.
      2. CreateDataProperty(receiver, propertyKey, value)를 반환한다.
    5. IsAccessorDescriptor(existingDescriptor)가 true이면, false를 반환한다.
    6. existingDescriptor.[[Writable]]false이면, false를 반환한다.
    7. valueDesc를 PropertyDescriptor { [[Value]]: value }라고 하자.
    8. receiver.[[DefineOwnProperty]](propertyKey, valueDesc)를 반환한다.
  3. Assert: IsAccessorDescriptor(ownDesc)는 true이다.
  4. setterownDesc.[[Set]]이라고 하자.
  5. setterundefined이면, false를 반환한다.
  6. Call(setter, receiver, « value »)를 수행한다.
  7. true를 반환한다.

10.1.10 [[Delete]] ( propertyKey )

The [[Delete]] internal method of 일반 객체 obj takes argument propertyKey (a property key) and returns either a normal completion containing a Boolean or a throw completion. It performs the following steps when called:

  1. OrdinaryDelete(obj, propertyKey)를 반환한다.

10.1.10.1 OrdinaryDelete ( obj, propertyKey )

The abstract operation OrdinaryDelete takes arguments obj (an Object) and propertyKey (a property key) and returns either a normal completion containing a Boolean or a throw completion. It performs the following steps when called:

  1. desc를 ? obj.[[GetOwnProperty]](propertyKey)라고 하자.
  2. descundefined이면, true를 반환한다.
  3. desc.[[Configurable]]true이면,
    1. obj에서 이름이 propertyKey인 자체 프로퍼티를 제거한다.
    2. true를 반환한다.
  4. false를 반환한다.

10.1.11 [[OwnPropertyKeys]] ( )

The [[OwnPropertyKeys]] internal method of 일반 객체 obj takes no arguments and returns a normal completion containing a List of property keys. It performs the following steps when called:

  1. OrdinaryOwnPropertyKeys(obj)를 반환한다.

10.1.11.1 OrdinaryOwnPropertyKeys ( obj )

The abstract operation OrdinaryOwnPropertyKeys takes argument obj (an Object) and returns a List of property keys. It performs the following steps when called:

  1. 새로운 빈 Listkeys라고 하자.
  2. obj의 각 자체 프로퍼티 키 propertyKeypropertyKey가 배열 인덱스인 것에 대해, 숫자 인덱스 오름차순으로, 다음을 수행한다
    1. propertyKeykeys에 추가한다.
  3. obj의 각 자체 프로퍼티 키 propertyKeypropertyKey가 String이고 배열 인덱스가 아닌 것에 대해, 프로퍼티 생성의 시간순 오름차순으로, 다음을 수행한다
    1. propertyKeykeys에 추가한다.
  4. obj의 각 자체 프로퍼티 키 propertyKeypropertyKey가 Symbol인 것에 대해, 프로퍼티 생성의 시간순 오름차순으로, 다음을 수행한다
    1. propertyKeykeys에 추가한다.
  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가 존재하면, internalSlotsListinternalSlotsListadditionalInternalSlotsList의 리스트 연결로 설정한다.
  3. objMakeBasicObject(internalSlotsList)라고 하자.
  4. obj.[[Prototype]]proto로 설정한다.
  5. obj를 반환한다.
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 either a normal completion containing an Object or a throw completion. 이것은 [[Prototype]] 값이 생성자의 "prototype" 프로퍼티에서 존재하면 거기서 가져와지는 일반 객체를 생성한다. 그렇지 않으면 intrinsicDefaultProto로 명명된 intrinsic이 [[Prototype]]에 사용된다. internalSlotsList는 객체의 일부로 정의되어야 하는 추가 내부 슬롯들의 이름을 담고 있다. internalSlotsList가 제공되지 않으면, 새로운 빈 List가 사용된다. It performs the following steps when called:

  1. Assert: 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 either a normal completion containing an Object or a throw completion. 이것은 특정 생성자에 대응하는 객체를 만들 때 사용해야 하는 [[Prototype]] 값을 결정한다. 그 값은 생성자의 "prototype" 프로퍼티가 존재하면 거기서 가져온다. 그렇지 않으면 intrinsicDefaultProto로 명명된 intrinsic이 [[Prototype]]에 사용된다. It performs the following steps when called:

  1. Assert: intrinsicDefaultProto는 이 명세에서 intrinsic 객체의 이름이다. 대응하는 객체는 객체의 [[Prototype]] 값으로 사용되도록 의도된 intrinsic이어야 한다.
  2. proto를 ? Get(constructor, "prototype")이라고 하자.
  3. proto가 Object가 아니면,
    1. realm을 ? GetFunctionRealm(constructor)이라고 하자.
    2. protorealmintrinsicDefaultProto라는 이름의 intrinsic 객체로 설정한다.
  4. proto를 반환한다.
Note

constructor[[Prototype]] 값을 제공하지 않으면, 사용되는 기본값은 실행 중인 실행 컨텍스트가 아니라 constructor 함수의 realm에서 가져온다.

10.1.15 RequireInternalSlot ( obj, internalSlot )

The abstract operation RequireInternalSlot takes arguments obj (an ECMAScript language value) and internalSlot (an internal slot name) and returns either a normal completion containing unused or a throw completion. 이것은 obj가 Object이고 주어진 내부 슬롯을 가지는 경우가 아니면 예외를 던진다. It performs the following steps when called:

  1. obj가 Object가 아니면, TypeError 예외를 던진다.
  2. objinternalSlot 내부 슬롯을 가지지 않으면, TypeError 예외를 던진다.
  3. unused를 반환한다.

10.2 ECMAScript 함수 객체

ECMAScript 함수 객체는 어휘 환경에 대해 닫힌 매개변수화된 ECMAScript 코드를 캡슐화하며, 그 코드의 동적 평가를 지원한다. ECMAScript 함수 객체는 일반 객체이며, 다른 일반 객체와 동일한 내부 슬롯과 동일한 내부 메서드를 가진다. ECMAScript 함수 객체의 코드는 strict mode 코드(11.2.2)이거나 non-strict 코드일 수 있다. 코드가 strict mode 코드인 ECMAScript 함수 객체는 strict function 이라고 한다. 코드가 strict mode 코드가 아닌 것은 non-strict function이라고 한다.

[[Extensible]][[Prototype]] 외에도, ECMAScript 함수 객체는 Table 25 에 나열된 내부 슬롯도 가진다.

Table 25: Internal Slots of ECMAScript Function Objects
내부 슬롯 타입 설명
[[Environment]] an Environment Record 함수가 닫혀 있던 Environment Record이다. 함수의 코드를 평가할 때 바깥 환경으로 사용된다.
[[PrivateEnvironment]] a PrivateEnvironment Record or null 함수가 닫혀 있던 Private Name들을 위한 PrivateEnvironment 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 함수가 생성된 script 또는 module.
[[ThisMode]] lexical, strict, or global 함수의 형식 매개변수와 코드 본문 안에서 this 참조가 어떻게 해석되는지를 정의한다. lexicalthis가 어휘적으로 둘러싼 함수의 this 값을 가리킨다는 뜻이다. strictthis 값이 함수 호출 시 제공된 그대로 사용된다는 뜻이다. globalthis 값이 undefined 또는 null이면 전역 객체에 대한 참조로 해석되고, 그 외의 this 값은 먼저 ToObject에 전달된다는 뜻이다.
[[Strict]] a Boolean 이것이 strict function이면 true, non-strict function이면 false.
[[HomeObject]] an Object or undefined 함수가 super를 사용한다면, 이것은 [[GetPrototypeOf]]super 프로퍼티 조회가 시작되는 객체를 제공하는 객체이다.
[[SourceText]] a sequence of Unicode code points 함수를 정의하는 source text.
[[Fields]] a List of ClassFieldDefinition Records 함수가 클래스라면, 이것은 클래스의 non-static 필드와 그에 대응하는 initializer를 나타내는 Record들의 리스트이다.
[[PrivateMethods]] a List of PrivateElements 함수가 클래스라면, 이것은 클래스의 non-static private 메서드와 접근자를 나타내는 리스트이다.
[[ClassFieldInitializerName]] a String, a Symbol, a Private Name, or empty 함수가 클래스 필드의 initializer로 생성된 경우, 필드의 NamedEvaluation에 사용할 이름이며, 그렇지 않으면 empty이다.
[[IsClassConstructor]] a Boolean 함수가 클래스 생성자인지 여부를 나타낸다. (true이면, 함수의 [[Call]]을 호출할 때 즉시 TypeError 예외를 던진다.)

모든 ECMAScript 함수 객체는 여기 정의된 [[Call]] 내부 메서드를 가진다. 추가로 생성자이기도 한 ECMAScript 함수는 [[Construct]] 내부 메서드도 가진다.

10.2.1 [[Call]] ( thisArgument, argumentsList )

The [[Call]] internal method of an ECMAScript function object func takes arguments thisArgument (an ECMAScript language value) and argumentsList (a List of ECMAScript language values) and returns either a normal completion containing an ECMAScript language value or a throw completion. It performs the following steps when called:

  1. callerContext를 현재 실행 중인 execution context라고 하자.
  2. calleeContextPrepareForOrdinaryCall(func, undefined)라고 하자.
  3. Assert: 이제 calleeContext가 현재 실행 중인 execution context이다.
  4. func.[[IsClassConstructor]]true이면,
    1. 새로 생성된 TypeError 객체를 error라고 하자.
    2. NOTE: errorfunc와 연관된 Realm Record를 사용하여 calleeContext 안에서 생성된다.
    3. execution context stack에서 calleeContext를 제거하고, callerContext를 현재 실행 중인 execution context로 복원한다.
    4. error를 던진다.
  5. OrdinaryCallBindThis(func, calleeContext, thisArgument)를 수행한다.
  6. resultCompletion(OrdinaryCallEvaluateBody(func, argumentsList))라고 하자.
  7. execution context stack에서 calleeContext를 제거하고, callerContext를 현재 실행 중인 execution context로 복원한다.
  8. resultreturn completion이면, result.[[Value]]를 반환한다.
  9. Assert: resultthrow completion이다.
  10. result를 반환한다.
Note

단계 7에서 calleeContextexecution context stack에서 제거될 때, 그것이 중단된 상태로 나중에 접근 가능한 Generator에 의해 재개를 위해 유지되고 있다면 파괴되어서는 안 된다.

10.2.1.1 PrepareForOrdinaryCall ( func, newTarget )

The abstract operation PrepareForOrdinaryCall takes arguments func (an ECMAScript function object) and newTarget (an Object or undefined) and returns an execution context. It performs the following steps when called:

  1. callerContext를 현재 실행 중인 execution context라고 하자.
  2. 새로운 ECMAScript 코드 execution contextcalleeContext라고 하자.
  3. calleeContext의 Function을 func로 설정한다.
  4. calleeRealmfunc.[[Realm]]이라고 하자.
  5. calleeContextRealmcalleeRealm으로 설정한다.
  6. calleeContext의 ScriptOrModule을 func.[[ScriptOrModule]]로 설정한다.
  7. localEnvNewFunctionEnvironment(func, newTarget)라고 하자.
  8. calleeContext의 LexicalEnvironment를 localEnv로 설정한다.
  9. calleeContext의 VariableEnvironment를 localEnv로 설정한다.
  10. calleeContext의 PrivateEnvironment를 func.[[PrivateEnvironment]]로 설정한다.
  11. callerContext가 아직 중단되지 않았다면, callerContext를 중단한다.
  12. execution context stackcalleeContext를 push한다; calleeContext는 이제 현재 실행 중인 execution context이다.
  13. NOTE: 이 지점 이후에 생성되는 모든 예외 객체는 calleeRealm과 연관된다.
  14. calleeContext를 반환한다.

10.2.1.2 OrdinaryCallBindThis ( func, calleeContext, thisArgument )

The abstract operation OrdinaryCallBindThis takes arguments func (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. thisModefunc.[[ThisMode]]라고 하자.
  2. thisModelexical이면, unused를 반환한다.
  3. calleeRealmfunc.[[Realm]]이라고 하자.
  4. localEnvcalleeContext의 LexicalEnvironment라고 하자.
  5. thisModestrict이면,
    1. thisValuethisArgument라고 하자.
  6. 그렇지 않으면,
    1. thisArgumentundefined 또는 null 중 하나이면,
      1. globalEnvcalleeRealm.[[GlobalEnv]]라고 하자.
      2. Assert: globalEnvGlobal Environment Record이다.
      3. thisValueglobalEnv.[[GlobalThisValue]]라고 하자.
    2. 그렇지 않으면,
      1. thisValue를 ! ToObject(thisArgument)라고 하자.
      2. NOTE: ToObjectcalleeRealm을 사용하여 wrapper 객체를 생성한다.
  7. Assert: localEnvFunction Environment Record이다.
  8. Assert: 다음 단계는 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 func (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. 인수 funcargumentsList를 사용한 FunctionBodyEvaluateFunctionBody를 ? 반환한다.
ConciseBody : ExpressionBody
  1. 인수 funcargumentsList를 사용한 ConciseBodyEvaluateConciseBody를 ? 반환한다.
GeneratorBody : FunctionBody
  1. 인수 funcargumentsList를 사용한 GeneratorBodyEvaluateGeneratorBody를 ? 반환한다.
AsyncGeneratorBody : FunctionBody
  1. 인수 funcargumentsList를 사용한 AsyncGeneratorBodyEvaluateAsyncGeneratorBody를 ? 반환한다.
AsyncFunctionBody : FunctionBody
  1. 인수 funcargumentsList를 사용한 AsyncFunctionBodyEvaluateAsyncFunctionBody를 ? 반환한다.
AsyncConciseBody : ExpressionBody
  1. 인수 funcargumentsList를 사용한 AsyncConciseBodyEvaluateAsyncConciseBody를 ? 반환한다.
Initializer : = AssignmentExpression
  1. Assert: argumentsList는 비어 있다.
  2. Assert: func.[[ClassFieldInitializerName]]empty가 아니다.
  3. IsAnonymousFunctionDefinition(AssignmentExpression)이 true이면,
    1. value를 인수 func.[[ClassFieldInitializerName]]를 사용한 InitializerNamedEvaluation 결과로 ? 하자.
  4. 그렇지 않으면,
    1. rhsAssignmentExpressionEvaluation 결과로 ? 하자.
    2. value를 ? GetValue(rhs)라고 하자.
  5. ReturnCompletion(value)를 반환한다.
Note

필드 initializer가 함수 경계를 구성하더라도, FunctionDeclarationInstantiation 호출은 관찰 가능한 효과를 갖지 않으므로 생략된다.

ClassStaticBlockBody : ClassStaticBlockStatementList
  1. Assert: argumentsList는 비어 있다.
  2. 인수 func를 사용한 ClassStaticBlockBodyEvaluateClassStaticBlockBody를 ? 반환한다.

10.2.1.4 OrdinaryCallEvaluateBody ( func, argumentsList )

The abstract operation OrdinaryCallEvaluateBody takes arguments func (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. 인수 funcargumentsList를 사용한 func.[[ECMAScriptCode]]EvaluateBody를 ? 반환한다.

10.2.2 [[Construct]] ( argumentsList, newTarget )

The [[Construct]] internal method of an ECMAScript function object func takes arguments argumentsList (a List of ECMAScript language values) and newTarget (a constructor) and returns either a normal completion containing an Object or a throw completion. It performs the following steps when called:

  1. callerContext를 현재 실행 중인 execution context라고 하자.
  2. kindfunc.[[ConstructorKind]]라고 하자.
  3. kindbase이면,
    1. thisArgument를 ? OrdinaryCreateFromConstructor(newTarget, "%Object.prototype%")라고 하자.
  4. calleeContextPrepareForOrdinaryCall(func, newTarget)라고 하자.
  5. Assert: 이제 calleeContext가 현재 실행 중인 execution context이다.
  6. kindbase이면,
    1. OrdinaryCallBindThis(func, calleeContext, thisArgument)를 수행한다.
    2. initializeResultCompletion(InitializeInstanceElements( thisArgument, func))라고 하자.
    3. initializeResultabrupt completion이면,
      1. execution context stack에서 calleeContext를 제거하고, callerContext를 현재 실행 중인 execution context로 복원한다.
      2. initializeResult를 반환한다.
  7. constructorEnvcalleeContext의 LexicalEnvironment라고 하자.
  8. resultCompletion(OrdinaryCallEvaluateBody(func, argumentsList))라고 하자.
  9. execution context stack에서 calleeContext를 제거하고, callerContext를 현재 실행 중인 execution context로 복원한다.
  10. resultthrow completion이면,
    1. result를 반환한다.
  11. Assert: resultreturn completion이다.
  12. result.[[Value]]가 Object이면, result.[[Value]]를 반환한다.
  13. kindbase이면, thisArgument를 반환한다.
  14. result.[[Value]]undefined가 아니면, TypeError 예외를 던진다.
  15. thisBinding을 ? constructorEnv.GetThisBinding()이라고 하자.
  16. Assert: thisBinding은 Object이다.
  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는 생성될 함수의 구문 정의에 대한 source text이다. It performs the following steps when called:

  1. internalSlotsListTable 25 에 나열된 내부 슬롯이라고 하자.
  2. funcOrdinaryObjectCreate(functionPrototype, internalSlotsList)라고 하자.
  3. func.[[Call]]10.2.1 에 명시된 정의로 설정한다.
  4. func.[[SourceText]]sourceText로 설정한다.
  5. func.[[FormalParameters]]parameterList로 설정한다.
  6. func.[[ECMAScriptCode]]body로 설정한다.
  7. strictIsStrict(body)라고 하자.
  8. func.[[Strict]]strict로 설정한다.
  9. thisModelexical-this이면, func.[[ThisMode]]lexical로 설정한다.
  10. 그렇지 않고 stricttrue이면, func.[[ThisMode]]strict로 설정한다.
  11. 그렇지 않으면, func.[[ThisMode]]global로 설정한다.
  12. func.[[IsClassConstructor]]false로 설정한다.
  13. func.[[Environment]]env로 설정한다.
  14. func.[[PrivateEnvironment]]privateEnv로 설정한다.
  15. func.[[ScriptOrModule]]GetActiveScriptOrModule()로 설정한다.
  16. func.[[Realm]]를 현재 Realm Record로 설정한다.
  17. func.[[HomeObject]]undefined로 설정한다.
  18. func.[[Fields]]를 새로운 빈 List로 설정한다.
  19. func.[[PrivateMethods]]를 새로운 빈 List로 설정한다.
  20. func.[[ClassFieldInitializerName]]empty로 설정한다.
  21. lenparameterListExpectedArgumentCount라고 하자.
  22. SetFunctionLength(func, len)를 수행한다.
  23. func를 반환한다.

10.2.4 AddRestrictedFunctionProperties ( func, realm )

The abstract operation AddRestrictedFunctionProperties takes arguments func (a function object) and realm (a Realm Record) and returns unused. It performs the following steps when called:

  1. Assert: realm.[[Intrinsics]].[[%ThrowTypeError%]]가 존재하며 초기화되어 있다.
  2. throwerrealm.[[Intrinsics]].[[%ThrowTypeError%]]라고 하자.
  3. DefinePropertyOrThrow(func, "caller", PropertyDescriptor { [[Get]]: thrower, [[Set]]: thrower, [[Enumerable]]: false, [[Configurable]]: true })를 수행한다.
  4. DefinePropertyOrThrow(func, "arguments", PropertyDescriptor { [[Get]]: thrower, [[Set]]: thrower, [[Enumerable]]: false, [[Configurable]]: true })를 수행한다.
  5. unused를 반환한다.

10.2.4.1 %ThrowTypeError% ( )

이 함수는 %ThrowTypeError% intrinsic 객체이다.

이것은 각 realm마다 한 번 정의되는 익명 built-in 함수 객체이다.

호출되면 다음 단계를 수행한다:

  1. TypeError 예외를 던진다.

이 함수의 [[Extensible]] 내부 슬롯 값은 false이다.

이 함수의 "length" 프로퍼티는 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false } 속성을 가진다.

이 함수의 "name" 프로퍼티는 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false } 속성을 가진다.

10.2.5 MakeConstructor ( func [ , writablePrototype [ , prototype ] ] )

The abstract operation MakeConstructor takes argument func (an ECMAScript function object or a built-in function object) and optional arguments writablePrototype (a Boolean) and prototype (an Object) and returns unused. 이것은 func를 생성자로 변환한다. It performs the following steps when called:

  1. func가 ECMAScript 함수 객체이면,
    1. Assert: IsConstructor(func)는 false이다.
    2. Assert: func"prototype" 자체 프로퍼티를 가지지 않는 확장 가능한 객체이다.
    3. func.[[Construct]]10.2.2 에 명시된 정의로 설정한다.
  2. 그렇지 않으면,
    1. func.[[Construct]]10.3.2 에 명시된 정의로 설정한다.
  3. func.[[ConstructorKind]]base로 설정한다.
  4. writablePrototype이 존재하지 않으면, writablePrototypetrue로 설정한다.
  5. prototype이 존재하지 않으면,
    1. prototypeOrdinaryObjectCreate(%Object.prototype%)로 설정한다.
    2. DefinePropertyOrThrow(prototype, "constructor", PropertyDescriptor { [[Value]]: func, [[Writable]]: writablePrototype, [[Enumerable]]: false, [[Configurable]]: true })를 수행한다.
  6. DefinePropertyOrThrow(func, "prototype", PropertyDescriptor { [[Value]]: prototype, [[Writable]]: writablePrototype, [[Enumerable]]: false, [[Configurable]]: false })를 수행한다.
  7. unused를 반환한다.

10.2.6 MakeClassConstructor ( func )

The abstract operation MakeClassConstructor takes argument func (an ECMAScript function object) and returns unused. It performs the following steps when called:

  1. Assert: func.[[IsClassConstructor]]false이다.
  2. func.[[IsClassConstructor]]true로 설정한다.
  3. unused를 반환한다.

10.2.7 MakeMethod ( func, homeObject )

The abstract operation MakeMethod takes arguments func (an ECMAScript function object) and homeObject (an Object) and returns unused. 이것은 func를 메서드로 구성한다. It performs the following steps when called:

  1. Assert: homeObject는 일반 객체이다.
  2. func.[[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 either a normal completion containing either a PrivateElement or unused, or an abrupt completion. It performs the following steps when called:

  1. Assert: homeObject는 일반적이고 확장 가능한 객체이다.
  2. keyPrivate Name이면, PrivateElement { [[Key]]: key, [[Kind]]: method, [[Value]]: closure }를 반환한다.
  3. desc를 PropertyDescriptor { [[Value]]: closure, [[Writable]]: true, [[Enumerable]]: enumerable, [[Configurable]]: true }라고 하자.
  4. DefinePropertyOrThrow(homeObject, key, desc)를 수행한다.
  5. NOTE: DefinePropertyOrThrowkey"prototype"인 클래스 static 메서드를 정의하려고 시도할 때만 abrupt completion을 반환한다.
  6. unused를 반환한다.

10.2.9 SetFunctionName ( func, name [ , prefix ] )

The abstract operation SetFunctionName takes arguments func (a function object) and name (a property key or Private Name) and optional argument prefix (a String) and returns unused. 이것은 func"name" 프로퍼티를 추가한다. It performs the following steps when called:

  1. Assert: func"name" 자체 프로퍼티를 가지지 않는 확장 가능한 객체이다.
  2. name이 Symbol이면,
    1. descriptionname.[[Description]]이라고 하자.
    2. descriptionundefined이면, name을 빈 String으로 설정한다.
    3. 그렇지 않으면, name"[", description, "]"의 string-concatenation으로 설정한다.
  3. 그렇지 않고 namePrivate Name이면,
    1. namename.[[Description]]으로 설정한다.
  4. func[[InitialName]] 내부 슬롯을 가지면,
    1. func.[[InitialName]]name으로 설정한다.
  5. prefix가 존재하면,
    1. nameprefix, 코드 단위 0x0020 (SPACE), name의 string-concatenation으로 설정한다.
    2. func[[InitialName]] 내부 슬롯을 가지면,
      1. NOTE: 다음 단계의 선택은 이 Abstract Operation이 호출될 때마다 독립적으로 이루어진다.
      2. 선택적으로, func.[[InitialName]]name으로 설정한다.
  6. DefinePropertyOrThrow(func, "name", PropertyDescriptor { [[Value]]: name, [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true })를 수행한다.
  7. unused를 반환한다.

10.2.10 SetFunctionLength ( func, length )

The abstract operation SetFunctionLength takes arguments func (a function object) and length (a non-negative integer or +∞) and returns unused. 이것은 func"length" 프로퍼티를 추가한다. It performs the following steps when called:

  1. Assert: func"length" 자체 프로퍼티를 가지지 않는 확장 가능한 객체이다.
  2. DefinePropertyOrThrow(func, "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 either a normal completion containing unused or a throw completion. funcexecution context가 설정되고 있는 대상 함수 객체이다.

Note

ECMAScript 함수를 평가하기 위한 execution context가 설정될 때, 새로운 Function Environment Record가 생성되고 각 형식 매개변수에 대한 바인딩이 그 Environment Record 안에 instantiate된다. 함수 본문 안의 각 선언도 역시 instantiate된다. 함수의 형식 매개변수에 기본값 initializer가 포함되어 있지 않다면, 본문 선언은 매개변수와 같은 Environment Record 안에 instantiate된다. 기본값 매개변수 initializer가 존재하면, 본문 선언을 위해 두 번째 Environment Record가 생성된다. 형식 매개변수와 함수는 FunctionDeclarationInstantiation의 일부로 초기화된다. 다른 모든 바인딩은 함수 본문 평가 중에 초기화된다.

호출되면 다음 단계를 수행한다:

  1. calleeContext를 현재 실행 중인 execution context라고 하자.
  2. codefunc.[[ECMAScriptCode]]라고 하자.
  3. strictfunc.[[Strict]]라고 하자.
  4. formalsfunc.[[FormalParameters]]라고 하자.
  5. parameterNamesformalsBoundNames라고 하자.
  6. parameterNames에 중복 항목이 하나라도 있으면, hasDuplicatestrue라고 하자; 그렇지 않으면 hasDuplicatesfalse라고 하자.
  7. simpleParameterListformalsIsSimpleParameterList라고 하자.
  8. hasParameterExpressionsformalsContainsExpression이라고 하자.
  9. varNamescodeVarDeclaredNames라고 하자.
  10. varDeclarationscodeVarScopedDeclarations라고 하자.
  11. lexicalNamescodeLexicallyDeclaredNames라고 하자.
  12. functionNames를 새로운 빈 List라고 하자.
  13. functionsToInitialize를 새로운 빈 List라고 하자.
  14. varDeclarations의 각 요소 varDecl에 대해, 역순 List 순서로, 다음을 수행한다
    1. varDeclVariableDeclarationForBindingBindingIdentifier도 아니면,
      1. Assert: varDeclFunctionDeclaration, GeneratorDeclaration, AsyncFunctionDeclaration, AsyncGeneratorDeclaration 중 하나이다.
      2. fnvarDeclBoundNames의 유일한 요소라고 하자.
      3. functionNamesfn을 포함하지 않으면,
        1. functionNames의 첫 번째 요소로 fn을 삽입한다.
        2. NOTE: 같은 이름에 대한 함수 선언이 여러 개 있으면, 마지막 선언이 사용된다.
        3. functionsToInitialize의 첫 번째 요소로 varDecl을 삽입한다.
  15. argumentsObjectNeededtrue라고 하자.
  16. func.[[ThisMode]]lexical이면,
    1. NOTE: 화살표 함수는 결코 arguments 객체를 가지지 않는다.
    2. argumentsObjectNeededfalse로 설정한다.
  17. 그렇지 않고 parameterNames"arguments"를 포함하면,
    1. argumentsObjectNeededfalse로 설정한다.
  18. 그렇지 않고 hasParameterExpressionsfalse이면,
    1. functionNames"arguments"를 포함하거나 lexicalNames"arguments"를 포함하면,
      1. argumentsObjectNeededfalse로 설정한다.
  19. stricttrue이거나 hasParameterExpressionsfalse이면,
    1. NOTE: strict mode 코드에서 eval 호출은 eval 바깥에서 보이는 새 바인딩을 만들 수 없으므로, 매개변수에는 하나의 Environment Record만 필요하다.
    2. envcalleeContext의 LexicalEnvironment라고 하자.
  20. 그렇지 않으면,
    1. NOTE: 형식 매개변수 목록 안의 직접 eval 호출로 생성된 바인딩이 매개변수가 선언된 환경 바깥에 있도록 보장하기 위해 별도의 Environment Record가 필요하다.
    2. calleeEnvcalleeContext의 LexicalEnvironment라고 하자.
    3. envNewDeclarativeEnvironment(calleeEnv)라고 하자.
    4. Assert: calleeContext의 VariableEnvironment와 calleeEnv는 같은 Environment Record이다.
    5. calleeContext의 LexicalEnvironment를 env로 설정한다.
  21. parameterNames의 각 String paramName에 대해, 다음을 수행한다
    1. alreadyDeclared를 ! env.HasBinding(paramName)라고 하자.
    2. NOTE: Early Error는 중복 매개변수 이름이 매개변수 기본값이나 rest parameter가 없는 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. 그렇지 않으면,
      1. NOTE: 매핑된 인수 객체는 rest parameter, 매개변수 기본값 initializer, 구조 분해 매개변수가 없는 non-strict 함수에 대해서만 제공된다.
      2. aoCreateMappedArgumentsObject(func, formals, argumentsList, env)라고 하자.
    3. stricttrue이면,
      1. env.CreateImmutableBinding("arguments", false)를 수행한다.
      2. NOTE: strict mode 코드에서는 early error가 이 바인딩에 대한 할당 시도를 막기 때문에, 그 가변성은 관찰 가능하지 않다.
    4. 그렇지 않으면,
      1. env.CreateMutableBinding("arguments", false)를 수행한다.
    5. env.InitializeBinding("arguments", ao)를 수행한다.
    6. parameterBindingsparameterNames와 « "arguments" »의 list-concatenation이라고 하자.
  23. 그렇지 않으면,
    1. parameterBindingsparameterNames라고 하자.
  24. iteratorRecordCreateListIteratorRecord(argumentsList)라고 하자.
  25. hasDuplicatestrue이면,
    1. usedEnvundefined라고 하자.
  26. 그렇지 않으면,
    1. usedEnvenv라고 하자.
  27. NOTE: 다음 단계는 ReturnCompletion을 반환할 수 없는데, 표현식 위치에서 그러한 completion이 발생할 수 있는 유일한 방법은 YieldExpression의 사용뿐이며, 이것은 15.5.115.6.1의 Early Error 규칙에 의해 매개변수 목록에서 금지되기 때문이다.
  28. 인수 iteratorRecordusedEnv를 사용한 formalsIteratorBindingInitialization을 ? 수행한다.
  29. hasParameterExpressionsfalse이면,
    1. NOTE: 매개변수와 최상위 var에는 하나의 Environment Record만 필요하다.
    2. instantiatedVarNamesList parameterBindings의 복사본이라고 하자.
    3. varNames의 각 요소 n에 대해, 다음을 수행한다
      1. instantiatedVarNamesn을 포함하지 않으면,
        1. ninstantiatedVarNames에 추가한다.
        2. env.CreateMutableBinding(n, false)를 수행한다.
        3. env.InitializeBinding(n, undefined)를 수행한다.
    4. varEnvenv라고 하자.
  30. 그렇지 않으면,
    1. NOTE: 형식 매개변수 목록 안의 표현식에 의해 생성된 closure가 함수 본문의 선언을 볼 수 없도록 보장하기 위해 별도의 Environment Record가 필요하다.
    2. varEnvNewDeclarativeEnvironment(env)라고 하자.
    3. calleeContext의 VariableEnvironment를 varEnv로 설정한다.
    4. instantiatedVarNames를 새로운 빈 List라고 하자.
    5. varNames의 각 요소 n에 대해, 다음을 수행한다
      1. instantiatedVarNamesn을 포함하지 않으면,
        1. ninstantiatedVarNames에 추가한다.
        2. varEnv.CreateMutableBinding(n, false)를 수행한다.
        3. parameterBindingsn을 포함하지 않거나 functionNamesn을 포함하면,
          1. initialValueundefined라고 하자.
        4. 그렇지 않으면,
          1. initialValue를 ! env.GetBindingValue(n, false)라고 하자.
        5. varEnv.InitializeBinding(n, initialValue)를 수행한다.
        6. NOTE: 형식 매개변수와 같은 이름의 var는 초기에 대응하는 초기화된 매개변수와 같은 값을 가진다.
  31. stricttrue이면,
    1. lexEnvvarEnv라고 하자.
  32. 그렇지 않으면,
    1. Normative Optional
      호스트가 웹 브라우저이거나 또는 Block-Level Function Declaration 웹 Legacy 호환성 의미론를 지원하면,
      1. code Contains xtrue인 임의의 Block, CaseClause, DefaultClause xStatementList에 직접 포함된 각 FunctionDeclaration fnDecl에 대해, 다음을 수행한다
        1. funcNamefnDeclBindingIdentifierStringValue라고 하자.
        2. FunctionDeclaration fnDeclfuncNameBindingIdentifier로 가지는 VariableStatement로 바꾸더라도 func에 대해 어떤 Early Error도 발생하지 않고 parameterNamesfuncName을 포함하지 않으면,
          1. NOTE: funcName에 대한 var 바인딩은 여기서, 그것이 VarDeclaredName도, 형식 매개변수의 이름도, 다른 FunctionDeclaration도 아닐 때에만 instantiate된다.
          2. instantiatedVarNamesfuncName을 포함하지 않고 funcName"arguments"가 아니면,
            1. varEnv.CreateMutableBinding(funcName, false)를 수행한다.
            2. varEnv.InitializeBinding(funcName, undefined)를 수행한다.
            3. funcNameinstantiatedVarNames에 추가한다.
          3. FunctionDeclaration fnDecl이 평가될 때, 15.2.6에 제공된 FunctionDeclaration Evaluation 알고리즘 대신 다음 단계를 수행한다:
            1. fEnv를 현재 실행 중인 execution context의 VariableEnvironment라고 하자.
            2. bEnv를 현재 실행 중인 execution context의 LexicalEnvironment라고 하자.
            3. fObj를 ! bEnv.GetBindingValue(funcName, false)라고 하자.
            4. fEnv.SetMutableBinding(funcName, fObj, false)를 수행한다.
            5. unused를 반환한다.
    2. lexEnvNewDeclarativeEnvironment(varEnv)라고 하자.
    3. NOTE: non-strict 함수는 최상위 lexical declaration을 위해 별도의 Environment Record를 사용하는데, 이는 direct eval이 eval 코드에 의해 도입된 var 스코프 선언이 기존 최상위 lexical 스코프 선언과 충돌하는지를 판별할 수 있도록 하기 위함이다. strict 함수에는 이것이 필요하지 않은데, strict direct eval은 항상 모든 선언을 새로운 Environment Record에 배치하기 때문이다.
  33. calleeContext의 LexicalEnvironment를 lexEnv로 설정한다.
  34. lexDeclarationscodeLexicallyScopedDeclarations라고 하자.
  35. lexDeclarations의 각 요소 lexDecl에 대해, 다음을 수행한다
    1. NOTE: lexical로 선언된 이름은 함수/제너레이터 선언, 형식 매개변수, var 이름과 같을 수 없다. lexical로 선언된 이름은 여기서 instantiate만 되고 초기화되지는 않는다.
    2. lexDeclBoundNames의 각 요소 dn에 대해, 다음을 수행한다
      1. lexDeclIsConstantDeclarationtrue이면,
        1. lexEnv.CreateImmutableBinding(dn, true)를 수행한다.
      2. 그렇지 않으면,
        1. lexEnv.CreateMutableBinding(dn, false)를 수행한다.
  36. privateEnvcalleeContext의 PrivateEnvironment라고 하자.
  37. functionsToInitialize의 각 Parse Node fnDecl에 대해, 다음을 수행한다
    1. fnfnDeclBoundNames의 유일한 요소라고 하자.
    2. fo를 인수 lexEnvprivateEnv를 사용한 fnDeclInstantiateFunctionObject라고 하자.
    3. varEnv.SetMutableBinding(fn, fo, false)를 수행한다.
  38. unused를 반환한다.

10.3 내장 함수 객체

내장 함수 객체는 일반 객체이다; 그것은 10.1 에 규정된 일반 객체에 대한 요구사항을 충족해야 한다.

모든 일반 객체에 요구되는 내부 슬롯(참조: 10.1) 외에도, 내장 함수 객체는 다음 내부 슬롯도 가져야 한다:

  • [[Realm]], 함수가 생성된 realm을 나타내는 Realm Record.
  • [[InitialName]], 함수의 초기 이름인 String. 20.2.3.5에서 사용된다.
  • [[Async]], 함수가 BuiltinCallOrConstruct에서 async 함수 호출 및 construct 동작을 가지는지를 나타내는 Boolean.

내장 함수 객체의 [[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 내장 함수 객체 func takes arguments thisArgument (an ECMAScript language value) and argumentsList (a List of ECMAScript language values) and returns either a normal completion containing an ECMAScript language value or a throw completion. It performs the following steps when called:

  1. BuiltinCallOrConstruct(func, thisArgument, argumentsList, undefined)를 반환한다.

10.3.2 [[Construct]] ( argumentsList, newTarget )

The [[Construct]] internal method of 내장 함수 객체 func (메서드가 존재할 때) takes arguments argumentsList (a List of ECMAScript language values) and newTarget (a constructor) and returns either a normal completion containing an Object or a throw completion. It performs the following steps when called:

  1. result를 ? BuiltinCallOrConstruct(func, uninitialized, argumentsList, newTarget)라고 하자.
  2. Assert: result는 Object이다.
  3. result를 반환한다.

10.3.3 BuiltinCallOrConstruct ( func, thisArgument, argumentsList, newTarget )

The abstract operation BuiltinCallOrConstruct takes arguments func (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 either a normal completion containing an ECMAScript language value or a throw completion. It performs the following steps when called:

  1. callerContext를 현재 실행 중인 execution context라고 하자.
  2. callerContext가 아직 중단되지 않았다면, callerContext를 중단한다.
  3. 새로운 execution contextcalleeContext라고 하자.
  4. calleeContext의 Function을 func로 설정한다.
  5. calleeRealmfunc.[[Realm]]이라고 하자.
  6. calleeContextRealmcalleeRealm으로 설정한다.
  7. calleeContext의 ScriptOrModule을 null로 설정한다.
  8. calleeContext에 대해 필요한 구현 정의 초기화를 수행한다.
  9. execution context stackcalleeContext를 push한다; calleeContext는 이제 현재 실행 중인 execution context이다.
  10. func.[[Async]]true이면,
    1. promiseCapability를 ! NewPromiseCapability(%Promise%)라고 하자.
    2. func, thisArgument, argumentsList, newTarget을 캡처하고, 호출될 때 다음 단계를 수행하는 매개변수 없는 새로운 Abstract ClosureresultsClosure라고 하자:
      1. result를, func의 명세에 부합하는 방식으로 func평가한 결과Completion Record라고 하자. thisArgumentuninitialized이면 this 값은 초기화되지 않은 상태이고; 그렇지 않으면 thisArgumentthis 값을 제공한다. argumentsList는 이름 있는 매개변수를 제공한다. newTarget은 NewTarget 값을 제공한다.
      2. NOTE: func가 이 문서에 정의되어 있다면, “func의 명세”는 알고리즘 단계나 다른 수단을 통해 명시된 그 동작이다.
      3. Completion(result)를 반환한다.
    3. AsyncFunctionStart(promiseCapability, resultsClosure)를 수행한다.
    4. execution context stack에서 calleeContext를 제거하고 callerContext를 현재 실행 중인 execution context로 복원한다.
    5. promiseCapability.[[Promise]]를 반환한다.
  11. result를, func의 명세에 부합하는 방식으로 func평가한 결과Completion Record라고 하자. thisArgumentuninitialized이면 this 값은 초기화되지 않은 상태이고; 그렇지 않으면 thisArgumentthis 값을 제공한다. argumentsList는 이름 있는 매개변수를 제공한다. newTarget은 NewTarget 값을 제공한다.
  12. NOTE: func가 이 문서에 정의되어 있다면, “func의 명세”는 알고리즘 단계나 다른 수단을 통해 명시된 그 동작이다.
  13. execution context stack에서 calleeContext를 제거하고 callerContext를 현재 실행 중인 execution context로 복원한다.
  14. result를 반환한다.
Note

calleeContextexecution context stack에서 제거될 때, 그것이 접근 가능한 Generator에 의해 나중 재개를 위해 중단된 채 유지되고 있다면 파괴되어서는 안 된다.

10.3.4 CreateBuiltinFunction ( behaviour, length, name, additionalInternalSlotsList [ , realm [ , prototype [ , prefix [ , async ] ] ] ] )

The abstract operation CreateBuiltinFunction takes arguments behaviour (an Abstract Closure, a set of algorithm steps, or some other definition of a function's behaviour provided in this specification), length (a non-negative integer or +∞), name (a property key or a Private Name), and additionalInternalSlotsList (a List of names of internal slots) and optional arguments realm (a Realm Record), prototype (an Object or null), prefix (a String), and async (a Boolean) and returns a built-in function object. additionalInternalSlotsList는 객체의 일부로 정의되어야 하는 추가 내부 슬롯의 이름들을 담고 있다. 이 연산은 내장 함수 객체를 생성한다. It performs the following steps when called:

  1. realm이 존재하지 않으면, realm을 현재 Realm Record로 설정한다.
  2. prototype이 존재하지 않으면, prototyperealm.[[Intrinsics]].[[%Function.prototype%]]로 설정한다.
  3. async가 존재하지 않으면, asyncfalse로 설정한다.
  4. internalSlotsList를, 생성되려는 내장 함수 객체에 대해 10.3가 요구하는 모든 내부 슬롯의 이름을 포함하는 List라고 하자.
  5. additionalInternalSlotsList의 요소들을 internalSlotsList에 추가한다.
  6. func를, 호출되었을 때 제공된 인수들을 behaviour가 명시하는 대응 매개변수의 값으로 사용하여 behaviour가 설명하는 동작을 수행하는 새로운 내장 함수 객체라고 하자. 이 새로운 함수 객체는 이름이 internalSlotsList의 요소인 내부 슬롯들과 [[InitialName]] 내부 슬롯을 가진다.
  7. func.[[Async]]async로 설정한다.
  8. func.[[Prototype]]prototype으로 설정한다.
  9. func.[[Extensible]]true로 설정한다.
  10. func.[[Realm]]realm으로 설정한다.
  11. func.[[InitialName]]null로 설정한다.
  12. SetFunctionLength(func, length)를 수행한다.
  13. prefix가 존재하지 않으면,
    1. SetFunctionName(func, name)을 수행한다.
  14. 그렇지 않으면,
    1. SetFunctionName(func, name, prefix)를 수행한다.
  15. func를 반환한다.

이 명세에 정의된 각 내장 함수는 CreateBuiltinFunction 추상 연산을 호출하여 생성된다.

10.4 내장 이색 객체 내부 메서드와 슬롯

이 명세는 여러 종류의 내장 이색 객체를 정의한다. 이 객체들은 일반적으로 몇몇 특정 상황을 제외하면 일반 객체와 유사하게 동작한다. 다음 이색 객체들은, 아래에서 명시적으로 달리 규정된 경우를 제외하고는, 일반 객체 내부 메서드를 사용한다:

10.4.1 바인드 함수 이색 객체

바인드 함수 이색 객체는 다른 함수 객체를 감싸는 이색 객체이다. 바인드 함수 이색 객체는 호출 가능하다([[Call]] 내부 메서드를 가지며, [[Construct]] 내부 메서드를 가질 수도 있다). 바인드 함수 이색 객체를 호출하면 일반적으로 그것이 감싸고 있는 함수가 호출된다.

객체는 그 [[Call]] 및 (해당하는 경우) [[Construct]] 내부 메서드가 다음 구현을 사용하고, 다른 essential 내부 메서드는 10.1 에서 찾을 수 있는 정의를 사용할 때 바인드 함수 이색 객체 이다. 이 메서드들은 BoundFunctionCreate에서 설치된다.

바인드 함수 이색 객체Table 25 에 나열된 ECMAScript 함수 객체의 내부 슬롯을 가지지 않는다. 대신 [[Prototype]][[Extensible]] 외에 Table 26 에 나열된 내부 슬롯을 가진다.

Table 26: Internal Slots of Bound Function Exotic Objects
내부 슬롯 타입 설명
[[BoundTargetFunction]] a callable Object 감싸고 있는 함수 객체.
[[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 바인드 함수 이색 객체 func takes arguments thisArgument (an ECMAScript language value) and argumentsList (a List of ECMAScript language values) and returns either a normal completion containing an ECMAScript language value or a throw completion. It performs the following steps when called:

  1. targetfunc.[[BoundTargetFunction]]이라고 하자.
  2. boundThisfunc.[[BoundThis]]라고 하자.
  3. boundArgsfunc.[[BoundArguments]]라고 하자.
  4. argsboundArgsargumentsListlist-concatenation이라고 하자.
  5. Call(target, boundThis, args)를 반환한다.

10.4.1.2 [[Construct]] ( argumentsList, newTarget )

The [[Construct]] internal method of 바인드 함수 이색 객체 func takes arguments argumentsList (a List of ECMAScript language values) and newTarget (a constructor) and returns either a normal completion containing an Object or a throw completion. It performs the following steps when called:

  1. targetfunc.[[BoundTargetFunction]]이라고 하자.
  2. Assert: IsConstructor(target)는 true이다.
  3. boundArgsfunc.[[BoundArguments]]라고 하자.
  4. argsboundArgsargumentsListlist-concatenation이라고 하자.
  5. SameValue(func, 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 either a normal completion containing a function object or a throw completion. 이것은 새로운 바인드 함수 이색 객체의 생성을 명세하는 데 사용된다. It performs the following steps when called:

  1. proto를 ? targetFunction.[[GetPrototypeOf]]() 라고 하자.
  2. internalSlotsList를 « [[Prototype]], [[Extensible]] »와 Table 26 에 나열된 내부 슬롯들의 list-concatenation이라고 하자.
  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는 배열 인덱스 프로퍼티 키를 특별하게 처리하는 이색 객체이다 (참조: 6.1.7). 프로퍼티 이름이 배열 인덱스인 프로퍼티는 element라고도 불린다. 모든 Array는 non-configurable한 "length" 프로퍼티를 가지며, 그 값은 수학적 값이 엄격히 232보다 작은, 항상 음이 아닌 정수 Number이다. "length" 프로퍼티의 값은 이름이 배열 인덱스인 모든 자체 프로퍼티의 이름보다 수치적으로 더 크며; Array의 자체 프로퍼티가 생성되거나 변경될 때마다, 이 불변식을 유지하기 위해 다른 프로퍼티들이 필요에 따라 조정된다. 구체적으로, 이름이 배열 인덱스인 자체 프로퍼티가 추가될 때마다, "length" 프로퍼티의 값은 필요하면 그 배열 인덱스의 수치값보다 1 큰 값으로 변경된다; 그리고 "length" 프로퍼티의 값이 변경될 때마다, 값이 새로운 length보다 작지 않은 이름의 배열 인덱스인 모든 자체 프로퍼티는 삭제된다. 이 제약은 Array의 자체 프로퍼티에만 적용되며, 그 프로토타입으로부터 상속될 수 있는 "length" 또는 배열 인덱스 프로퍼티의 영향을 받지 않는다.

객체는 그 [[DefineOwnProperty]] 내부 메서드가 다음 구현을 사용하고, 다른 essential 내부 메서드는 10.1 에서 찾을 수 있는 정의를 사용할 때 Array 이색 객체(또는 단순히 Array)이다. 이 메서드들은 ArrayCreate에서 설치된다.

10.4.2.1 [[DefineOwnProperty]] ( propertyKey, desc )

The [[DefineOwnProperty]] internal method of Array 이색 객체 array takes arguments propertyKey (a property key) and desc (a Property Descriptor) and returns either a normal completion containing a Boolean or a throw completion. It performs the following steps when called:

  1. propertyKey"length"이면, ? ArraySetLength(array, desc)를 반환한다.
  2. propertyKey가 배열 인덱스이면,
    1. lengthDescOrdinaryGetOwnProperty(array, "length") 라고 하자.
    2. Assert: lengthDescundefined가 아니다.
    3. Assert: IsDataDescriptor(lengthDesc)는 true이다.
    4. Assert: lengthDesc.[[Configurable]]false이다.
    5. lengthlengthDesc.[[Value]]라고 하자.
    6. Assert: length는 음이 아닌 정수 Number이다.
    7. index를 ! ToUint32(propertyKey)라고 하자.
    8. indexlength이고 lengthDesc.[[Writable]]false이면, false를 반환한다.
    9. succeeded를 ! OrdinaryDefineOwnProperty(array, propertyKey, desc)라고 하자.
    10. succeededfalse이면, false를 반환한다.
    11. indexlength이면,
      1. lengthDesc.[[Value]]index + 1𝔽로 설정한다.
      2. succeeded를 ! OrdinaryDefineOwnProperty(array, "length", lengthDesc)로 설정한다.
      3. Assert: succeededtrue이다.
    12. true를 반환한다.
  3. OrdinaryDefineOwnProperty(array, propertyKey, 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 either a normal completion containing an Array exotic object or a throw completion. 이것은 새로운 Array의 생성을 명세하는 데 사용된다. It performs the following steps when called:

  1. length > 232 - 1이면, RangeError 예외를 던진다.
  2. proto가 존재하지 않으면, proto%Array.prototype%로 설정한다.
  3. arrayMakeBasicObject[[Prototype]], [[Extensible]] »)라고 하자.
  4. array.[[Prototype]]proto로 설정한다.
  5. array.[[DefineOwnProperty]]10.4.2.1 에 명시된 대로 설정한다.
  6. OrdinaryDefineOwnProperty(array, "length", PropertyDescriptor { [[Value]]: 𝔽(length), [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false })를 수행한다.
  7. array를 반환한다.

10.4.2.3 ArraySpeciesCreate ( originalArray, length )

The abstract operation ArraySpeciesCreate takes arguments originalArray (an Object) and length (a non-negative integer) and returns either a normal completion containing an Object or a throw completion. 이것은 originalArray로부터 파생된 생성자 함수를 사용하여 새로운 Array 또는 유사 객체를 생성하는 것을 명세하는 데 사용된다. 이 연산은 생성자 함수가 Array를 반환해야 한다고 강제하지는 않는다. It performs the following steps when called:

  1. isArray를 ? IsArray(originalArray)라고 하자.
  2. isArrayfalse이면, ? ArrayCreate(length)를 반환한다.
  3. constructor를 ? Get(originalArray, "constructor") 라고 하자.
  4. IsConstructor(constructor)가 true이면,
    1. thisRealm을 현재 Realm Record라고 하자.
    2. constructorRealm을 ? GetFunctionRealm(constructor) 라고 하자.
    3. thisRealmconstructorRealm이 같은 Realm Record가 아니면,
      1. SameValue(constructor, constructorRealm.[[Intrinsics]].[[%Array%]])가 true이면, constructorundefined로 설정한다.
  5. constructor가 Object이면,
    1. constructor를 ? Get(constructor, %Symbol.species%)로 설정한다.
    2. constructornull이면, constructorundefined로 설정한다.
  6. constructorundefined이면, ? ArrayCreate(length)를 반환한다.
  7. IsConstructor(constructor)가 false이면, TypeError 예외를 던진다.
  8. Construct(constructor, « 𝔽(length) »)를 반환한다.
Note

originalArray가 현재 실행 중인 execution contextrealm이 아닌 realm에 대한 표준 내장 Array 생성자를 사용하여 생성되었다면, 새로운 Array는 현재 실행 중인 execution contextrealm을 사용하여 생성된다. 이것은 현재 ArraySpeciesCreate를 사용하여 정의되는 Array.prototype 메서드들에 대해 역사적으로 그러한 동작을 가져온 웹 브라우저와의 호환성을 유지한다.

10.4.2.4 ArraySetLength ( array, desc )

The abstract operation ArraySetLength takes arguments array (an Array) and desc (a Property Descriptor) and returns either a normal completion containing a Boolean or a throw completion. It performs the following steps when called:

  1. desc[[Value]] 필드를 가지지 않으면,
    1. OrdinaryDefineOwnProperty(array, "length", desc)를 반환한다.
  2. newLenDescdesc의 복사본이라고 하자.
  3. newLen을 ? ToUint32(desc.[[Value]])라고 하자.
  4. numberLen을 ? ToNumber(desc.[[Value]])라고 하자.
  5. SameValueZero(newLen, numberLen)가 false이면, RangeError 예외를 던진다.
  6. newLenDesc.[[Value]]newLen으로 설정한다.
  7. oldLenDescOrdinaryGetOwnProperty(array, "length") 라고 하자.
  8. Assert: oldLenDescundefined가 아니다.
  9. Assert: IsDataDescriptor(oldLenDesc)는 true이다.
  10. Assert: oldLenDesc.[[Configurable]]false이다.
  11. oldLenoldLenDesc.[[Value]]라고 하자.
  12. newLenoldLen이면,
    1. OrdinaryDefineOwnProperty(array, "length", newLenDesc)를 반환한다.
  13. oldLenDesc.[[Writable]]false이면, false를 반환한다.
  14. newLenDesc[[Writable]] 필드를 가지지 않거나 newLenDesc.[[Writable]]true이면,
    1. newWritabletrue라고 하자.
  15. 그렇지 않으면,
    1. NOTE: 어떤 element라도 삭제할 수 없는 경우에 대비해, [[Writable]] 속성을 false로 설정하는 것은 연기된다.
    2. newWritablefalse라고 하자.
    3. newLenDesc.[[Writable]]true로 설정한다.
  16. succeeded를 ! OrdinaryDefineOwnProperty(array, "length", newLenDesc)라고 하자.
  17. succeededfalse이면, false를 반환한다.
  18. array의 각 자체 프로퍼티 키 propertyKey 중, propertyKey가 배열 인덱스이고 ! ToUint32(propertyKey) ≥ newLen인 것에 대해, 숫자 인덱스 내림차순으로, 다음을 수행한다
    1. deleteSucceeded를 ! array.[[Delete]](propertyKey) 라고 하자.
    2. deleteSucceededfalse이면,
      1. newLenDesc.[[Value]]를 ! ToUint32(propertyKey) + 1𝔽로 설정한다.
      2. newWritablefalse이면, newLenDesc.[[Writable]]false로 설정한다.
      3. OrdinaryDefineOwnProperty(array, "length", newLenDesc)를 수행한다.
      4. false를 반환한다.
  19. newWritablefalse이면,
    1. succeeded를 ! OrdinaryDefineOwnProperty(array, "length", PropertyDescriptor { [[Writable]]: false })로 설정한다.
    2. Assert: succeededtrue이다.
  20. true를 반환한다.
Note

단계 34에서, desc.[[Value]]가 객체라면 그 valueOf 메서드는 두 번 호출된다. 이것은 이 명세 제2판부터 이러한 효과를 갖도록 명시된 legacy 동작이다.

10.4.3 문자열 이색 객체

String 객체는 String 값을 캡슐화하고, 그 String 값의 개별 코드 유닛 요소에 대응하는 가상 정수 인덱스 데이터 프로퍼티를 노출하는 이색 객체이다. 문자열 이색 객체는 항상 "length"라는 데이터 프로퍼티를 가지며, 그 값은 캡슐화된 String 값의 길이이다. 코드 유닛 데이터 프로퍼티와 "length" 프로퍼티는 모두 non-writable이고 non-configurable이다.

객체는 그 [[GetOwnProperty]], [[DefineOwnProperty]], 그리고 [[OwnPropertyKeys]] 내부 메서드가 다음 구현을 사용하고, 다른 essential 내부 메서드는 10.1 에서 찾을 수 있는 정의를 사용할 때 문자열 이색 객체(또는 단순히 String 객체)이다. 이 메서드들은 StringCreate에서 설치된다.

문자열 이색 객체는 일반 객체와 동일한 내부 슬롯을 가진다. 또한 [[StringData]] 내부 슬롯도 가진다.

10.4.3.1 [[GetOwnProperty]] ( propertyKey )

The [[GetOwnProperty]] internal method of 문자열 이색 객체 str takes argument propertyKey (a property key) and returns a normal completion containing either a Property Descriptor or undefined. It performs the following steps when called:

  1. descOrdinaryGetOwnProperty(str, propertyKey)라고 하자.
  2. descundefined가 아니면, desc를 반환한다.
  3. StringGetOwnProperty(str, propertyKey)를 반환한다.

10.4.3.2 [[DefineOwnProperty]] ( propertyKey, desc )

The [[DefineOwnProperty]] internal method of 문자열 이색 객체 str takes arguments propertyKey (a property key) and desc (a Property Descriptor) and returns a normal completion containing a Boolean. It performs the following steps when called:

  1. stringDescStringGetOwnProperty(str, propertyKey) 라고 하자.
  2. stringDescundefined가 아니면,
    1. extensiblestr.[[Extensible]]이라고 하자.
    2. IsCompatiblePropertyDescriptor(extensible, desc, stringDesc)를 반환한다.
  3. OrdinaryDefineOwnProperty(str, propertyKey, desc)를 반환한다.

10.4.3.3 [[OwnPropertyKeys]] ( )

The [[OwnPropertyKeys]] internal method of 문자열 이색 객체 obj takes no arguments and returns a normal completion containing a List of property keys. It performs the following steps when called:

  1. keys를 새로운 빈 List라고 하자.
  2. strobj.[[StringData]]라고 하자.
  3. Assert: str는 String이다.
  4. lenstr의 길이라고 하자.
  5. 0 ≤ i < len인 각 정수 i에 대해, 오름차순으로, 다음을 수행한다
    1. ToString(𝔽(i))를 keys에 추가한다.
  6. obj의 각 자체 프로퍼티 키 propertyKey 중, propertyKey가 배열 인덱스이고 ! ToIntegerOrInfinity(propertyKey) ≥ len인 것에 대해, 숫자 인덱스 오름차순으로, 다음을 수행한다
    1. propertyKeykeys에 추가한다.
  7. obj의 각 자체 프로퍼티 키 propertyKey 중, propertyKey가 String이고 배열 인덱스가 아닌 것에 대해, 프로퍼티 생성의 시간순 오름차순으로, 다음을 수행한다
    1. propertyKeykeys에 추가한다.
  8. obj의 각 자체 프로퍼티 키 propertyKey 중, propertyKey가 Symbol인 것에 대해, 프로퍼티 생성의 시간순 오름차순으로, 다음을 수행한다
    1. propertyKeykeys에 추가한다.
  9. keys를 반환한다.

10.4.3.4 StringCreate ( value, prototype )

The abstract operation StringCreate takes arguments value (a String) and prototype (an Object) and returns a String exotic object. 이것은 새로운 문자열 이색 객체의 생성을 명세하는 데 사용된다. It performs the following steps when called:

  1. strMakeBasicObject[[Prototype]], [[Extensible]], [[StringData]] »)라고 하자.
  2. str.[[Prototype]]prototype으로 설정한다.
  3. str.[[StringData]]value로 설정한다.
  4. str.[[GetOwnProperty]]10.4.3.1 에 명시된 대로 설정한다.
  5. str.[[DefineOwnProperty]]10.4.3.2 에 명시된 대로 설정한다.
  6. str.[[OwnPropertyKeys]]10.4.3.3 에 명시된 대로 설정한다.
  7. lengthvalue의 길이라고 하자.
  8. DefinePropertyOrThrow(str, "length", PropertyDescriptor { [[Value]]: 𝔽(length), [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false })를 수행한다.
  9. str를 반환한다.

10.4.3.5 StringGetOwnProperty ( str, propertyKey )

The abstract operation StringGetOwnProperty takes arguments str (an Object that has a [[StringData]] internal slot) and propertyKey (a property key) and returns a Property Descriptor or undefined. It performs the following steps when called:

  1. propertyKey가 String이 아니면, undefined를 반환한다.
  2. indexCanonicalNumericIndexString(propertyKey)이라고 하자.
  3. index정수 Number가 아니면, undefined를 반환한다.
  4. index-0𝔽이거나 index < -0𝔽이면, undefined를 반환한다.
  5. stringDatastr.[[StringData]]라고 하자.
  6. Assert: stringData는 String이다.
  7. lenstringData의 길이라고 하자.
  8. (index) ≥ len이면, undefined를 반환한다.
  9. resultStrstringData(index)부터 (index) + 1까지의 substring이라고 하자.
  10. PropertyDescriptor { [[Value]]: resultStr, [[Writable]]: false, [[Enumerable]]: true, [[Configurable]]: false }를 반환한다.

10.4.4 Arguments 이색 객체

대부분의 ECMAScript 함수는 자신의 코드에서 arguments 객체를 사용할 수 있게 한다. 함수 정의의 특성에 따라, 그 arguments 객체는 일반 객체이거나 arguments 이색 객체이다. arguments 이색 객체는 그 배열 인덱스 프로퍼티들이 연관된 ECMAScript 함수의 호출에 대한 형식 매개변수 바인딩에 매핑되는 이색 객체이다.

객체는, 여기에서 명시되지 않은 내부 메서드는 10.1 에 있는 정의를 사용하면서, 그 내부 메서드가 다음 구현을 사용할 때 arguments 이색 객체 이다. 이 메서드들은 CreateMappedArgumentsObject에서 설치된다.

Note 1

CreateUnmappedArgumentsObject는 이 절에 함께 묶여 있지만, arguments 이색 객체가 아니라 일반 객체를 생성한다.

arguments 이색 객체는 일반 객체와 동일한 내부 슬롯을 가진다. 또한 [[ParameterMap]] 내부 슬롯도 가진다. 일반 arguments 객체도 [[ParameterMap]] 내부 슬롯을 가지며, 그 값은 항상 undefined이다. 일반 arguments 객체의 경우 [[ParameterMap]] 내부 슬롯은 Object.prototype.toString (20.1.3.6)에서 그것들을 그러한 것으로 식별하기 위해서만 사용된다.

Note 2

숫자 이름 값이 해당 함수 객체의 형식 매개변수 개수보다 작은 arguments 이색 객체정수 인덱스 데이터 프로퍼티는 처음에는 함수의 execution context 안의 대응 인수 바인딩과 그 값을 공유한다. 이는 프로퍼티를 변경하면 대응하는 인수 바인딩의 값도 바뀌고 그 반대도 마찬가지임을 뜻한다. 그러한 프로퍼티가 삭제된 뒤 다시 정의되거나, 그 프로퍼티가 접근자 프로퍼티로 변경되면 이 대응 관계는 깨진다. arguments 객체가 일반 객체인 경우, 그 프로퍼티 값은 단순히 함수에 전달된 인수의 복사본이며, 프로퍼티 값과 형식 매개변수 값 사이에 동적 연결은 없다.

Note 3

ParameterMap 객체와 그 프로퍼티 값은 arguments 객체와 인수 바인딩 사이의 대응을 명세하기 위한 장치로 사용된다. ParameterMap 객체와 그 프로퍼티 값인 객체들은 ECMAScript 코드로부터 직접 관찰될 수 없다. ECMAScript 구현은 명시된 의미론을 구현하기 위해 실제로 그러한 객체를 생성하거나 사용할 필요가 없다.

Note 4

일반 arguments 객체는 "callee"라는 이름의 non-configurable 접근자 프로퍼티를 정의하며, 이에 접근하면 TypeError 예외를 던진다. "callee" 프로퍼티는 오직 일부 non-strict 함수들에 대해서만 생성되는 arguments 이색 객체에서는 더 구체적인 의미를 가진다. 일반 변형에서 이 프로퍼티를 이렇게 정의하는 것은, ECMAScript 적합 구현이 그것을 다른 방식으로 정의하지 않도록 보장하기 위해 존재한다.

Note 5

ECMAScript 구현의 arguments 이색 객체는 역사적으로 "caller"라는 이름의 접근자 프로퍼티를 포함해 왔다. ECMAScript 2017 이전에는, 이 명세는 일반 arguments 객체에 대해 예외를 던지는 "caller" 프로퍼티를 정의하고 있었다. 구현들이 더 이상 이 확장을 포함하지 않기 때문에, ECMAScript 2017은 예외를 던지는 "caller" 접근자 요구사항을 제거했다.

10.4.4.1 [[GetOwnProperty]] ( propertyKey )

The [[GetOwnProperty]] internal method of arguments 이색 객체 args takes argument propertyKey (a property key) and returns a normal completion containing either a Property Descriptor or undefined. It performs the following steps when called:

  1. descOrdinaryGetOwnProperty(args, propertyKey)라고 하자.
  2. descundefined이면, undefined를 반환한다.
  3. mapargs.[[ParameterMap]]이라고 하자.
  4. isMapped를 ! HasOwnProperty(map, propertyKey)라고 하자.
  5. isMappedtrue이면,
    1. desc.[[Value]]를 ! Get(map, propertyKey)로 설정한다.
  6. desc를 반환한다.

10.4.4.2 [[DefineOwnProperty]] ( propertyKey, desc )

The [[DefineOwnProperty]] internal method of arguments 이색 객체 args takes arguments propertyKey (a property key) and desc (a Property Descriptor) and returns a normal completion containing a Boolean. It performs the following steps when called:

  1. mapargs.[[ParameterMap]]이라고 하자.
  2. isMapped를 ! HasOwnProperty(map, propertyKey)라고 하자.
  3. newArgDescdesc라고 하자.
  4. isMappedtrue이고 IsDataDescriptor(desc)가 true이면,
    1. desc[[Value]] 필드를 가지지 않고, desc[[Writable]] 필드를 가지며, desc.[[Writable]]false이면,
      1. newArgDescdesc의 복사본으로 설정한다.
      2. newArgDesc.[[Value]]를 ! Get(map, propertyKey)로 설정한다.
  5. allowed를 ! OrdinaryDefineOwnProperty(args, propertyKey, newArgDesc)라고 하자.
  6. allowedfalse이면, false를 반환한다.
  7. isMappedtrue이면,
    1. IsAccessorDescriptor(desc)가 true이면,
      1. map.[[Delete]](propertyKey)를 수행한다.
    2. 그렇지 않으면,
      1. desc[[Value]] 필드를 가지면,
        1. Assert: 다음 Set은 성공할 것인데, arguments 객체에 의해 매핑되는 형식 매개변수는 항상 쓰기 가능하기 때문이다.
        2. Set(map, propertyKey, desc.[[Value]], false) 를 수행한다.
      2. desc[[Writable]] 필드를 가지고 desc.[[Writable]]false이면,
        1. map.[[Delete]](propertyKey)를 수행한다.
  8. true를 반환한다.

10.4.4.3 [[Get]] ( propertyKey, receiver )

The [[Get]] internal method of arguments 이색 객체 args takes arguments propertyKey (a property key) and receiver (an ECMAScript language value) and returns either a normal completion containing an ECMAScript language value or a throw completion. It performs the following steps when called:

  1. mapargs.[[ParameterMap]]이라고 하자.
  2. isMapped를 ! HasOwnProperty(map, propertyKey)라고 하자.
  3. isMappedfalse이면, ? OrdinaryGet(args, propertyKey, receiver)를 반환한다.
  4. Assert: mappropertyKey에 대한 형식 매개변수 매핑을 포함한다.
  5. Get(map, propertyKey)를 반환한다.

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

The [[Set]] internal method of arguments 이색 객체 args takes arguments propertyKey (a property key), value (an ECMAScript language value), and receiver (an ECMAScript language value) and returns either a normal completion containing a Boolean or a throw completion. It performs the following steps when called:

  1. SameValue(args, receiver)가 false이면,
    1. isMappedfalse라고 하자.
  2. 그렇지 않으면,
    1. mapargs.[[ParameterMap]]이라고 하자.
    2. isMapped를 ! HasOwnProperty(map, propertyKey)라고 하자.
  3. isMappedtrue이면,
    1. Assert: 다음 Set은 성공할 것인데, arguments 객체에 의해 매핑되는 형식 매개변수는 항상 쓰기 가능하기 때문이다.
    2. Set(map, propertyKey, value, false)를 수행한다.
  4. OrdinarySet(args, propertyKey, value, receiver)를 반환한다.

10.4.4.5 [[Delete]] ( propertyKey )

The [[Delete]] internal method of arguments 이색 객체 args takes argument propertyKey (a property key) and returns either a normal completion containing a Boolean or a throw completion. It performs the following steps when called:

  1. mapargs.[[ParameterMap]]이라고 하자.
  2. isMapped를 ! HasOwnProperty(map, propertyKey)라고 하자.
  3. result를 ? OrdinaryDelete(args, propertyKey)라고 하자.
  4. resulttrue이고 isMappedtrue이면,
    1. map.[[Delete]](propertyKey)를 수행한다.
  5. result를 반환한다.

10.4.4.6 CreateUnmappedArgumentsObject ( 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 ECMAScript function 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. Assert: formals는 rest parameter, 어떤 binding pattern, 어떤 initializer도 포함하지 않는다. 중복 식별자는 포함할 수 있다.
  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. parameterNamesformalsBoundNames라고 하자.
  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. namemappedNames에 추가한다.
      2. index < len이면,
        1. getterMakeArgGetter(name, env)라고 하자.
        2. setterMakeArgSetter(name, env)라고 하자.
        3. map.[[DefineOwnProperty]](! ToString(𝔽(index)), PropertyDescriptor { [[Set]]: setter, [[Get]]: getter, [[Enumerable]]: false, [[Configurable]]: true }) 를 수행한다.
    3. indexindex - 1로 설정한다.
  20. DefinePropertyOrThrow(obj, %Symbol.iterator%, PropertyDescriptor { [[Value]]: %Array.prototype.values%, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: true })를 수행한다.
  21. DefinePropertyOrThrow(obj, "callee", PropertyDescriptor { [[Value]]: func, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: true })를 수행한다.
  22. obj를 반환한다.

10.4.4.7.1 MakeArgGetter ( name, env )

The abstract operation MakeArgGetter takes arguments name (a String) and env (an Environment Record) and returns a function object. 이것은 실행되었을 때 env 안에서 name에 바인딩된 값을 반환하는 built-in 함수 객체를 생성한다. It performs the following steps when called:

  1. nameenv를 캡처하고, 호출될 때 다음 단계를 수행하는 매개변수 없는 새로운 Abstract ClosuregetterClosure라고 하자:
    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에 바인딩된 값을 설정하는 built-in 함수 객체를 생성한다. It performs the following steps when called:

  1. nameenv를 캡처하고, (value) 매개변수를 가지며 호출될 때 다음 단계를 수행하는 새로운 Abstract ClosuresetterClosure라고 하자:
    1. NormalCompletion(! env.SetMutableBinding(name, value, false))를 반환한다.
  2. setterCreateBuiltinFunction(setterClosure, 1, "", « ») 라고 하자.
  3. NOTE: setter는 ECMAScript 코드에서 직접 접근할 수 없다.
  4. setter를 반환한다.

10.4.5 TypedArray 이색 객체

TypedArray는 canonical numeric string인 프로퍼티 키를 특별하게 처리하는 이색 객체이며, 그 중 경계 내 정수 인덱스인 부분집합을 사용해 균일한 타입의 element에 인덱싱하고, 나머지는 프로토타입 체인 탐색을 발생시키지 않고 존재하지 않음을 보장하는 불변식을 강제한다.

Note

임의의 Number n에 대한 ToString(n)은 canonical numeric string이므로, 구현은 TypedArray의 프로퍼티 키로 Number를 실제 문자열 변환 없이 취급할 수 있다.

TypedArray는 일반 객체와 동일한 내부 슬롯을 가지며, 추가로 [[ViewedArrayBuffer]], [[TypedArrayName]], [[ContentType]], [[ByteLength]], [[ByteOffset]], [[ArrayLength]] 내부 슬롯을 가진다.

객체는 그 [[PreventExtensions]], [[GetOwnProperty]], [[HasProperty]], [[DefineOwnProperty]], [[Get]], [[Set]], [[Delete]], [[OwnPropertyKeys]] 내부 메서드가 이 절의 정의를 사용하고, 다른 essential 내부 메서드는 10.1 에서 찾을 수 있는 정의를 사용할 때 TypedArray 이다. 이 메서드들은 TypedArrayCreate에 의해 설치된다.

10.4.5.1 [[PreventExtensions]] ( )

The [[PreventExtensions]] internal method of TypedArray obj takes no arguments and returns a normal completion containing a Boolean. It performs the following steps when called:

  1. NOTE: 6.1.7.3 에 명시된 확장 가능성과 관련된 불변식은, obj가 프로퍼티를 얻을 수 있거나(또는 잃었다가 다시 얻을 수 있거나), 이는 그 기반 버퍼가 리사이즈될 때 정수 인덱스 이름을 가진 프로퍼티에서 발생할 수 있는데, 그 경우 이 메서드가 true를 반환하는 것을 허용하지 않는다.
  2. IsTypedArrayFixedLength(obj)가 false이면, false를 반환한다.
  3. OrdinaryPreventExtensions(obj)를 반환한다.

10.4.5.2 [[GetOwnProperty]] ( propertyKey )

The [[GetOwnProperty]] internal method of TypedArray obj takes argument propertyKey (a property key) and returns a normal completion containing either a Property Descriptor or undefined. It performs the following steps when called:

  1. propertyKey가 String이면,
    1. numericIndexCanonicalNumericIndexString(propertyKey) 라고 하자.
    2. numericIndexundefined가 아니면,
      1. valueTypedArrayGetElement(obj, numericIndex) 라고 하자.
      2. valueundefined이면, undefined를 반환한다.
      3. PropertyDescriptor { [[Value]]: value, [[Writable]]: true, [[Enumerable]]: true, [[Configurable]]: true } 를 반환한다.
  2. OrdinaryGetOwnProperty(obj, propertyKey)를 반환한다.

10.4.5.3 [[HasProperty]] ( propertyKey )

The [[HasProperty]] internal method of TypedArray obj takes argument propertyKey (a property key) and returns either a normal completion containing a Boolean or a throw completion. It performs the following steps when called:

  1. propertyKey가 String이면,
    1. numericIndexCanonicalNumericIndexString(propertyKey) 라고 하자.
    2. numericIndexundefined가 아니면, IsValidIntegerIndex(obj, numericIndex)를 반환한다.
  2. OrdinaryHasProperty(obj, propertyKey)를 반환한다.

10.4.5.4 [[DefineOwnProperty]] ( propertyKey, desc )

The [[DefineOwnProperty]] internal method of TypedArray obj takes arguments propertyKey (a property key) and desc (a Property Descriptor) and returns either a normal completion containing a Boolean or a throw completion. It performs the following steps when called:

  1. propertyKey가 String이면,
    1. numericIndexCanonicalNumericIndexString(propertyKey) 라고 하자.
    2. numericIndexundefined가 아니면,
      1. IsValidIntegerIndex(obj, numericIndex)가 false이면, false를 반환한다.
      2. desc[[Configurable]] 필드를 가지고 desc.[[Configurable]]false이면, false를 반환한다.
      3. desc[[Enumerable]] 필드를 가지고 desc.[[Enumerable]]false이면, false를 반환한다.
      4. IsAccessorDescriptor(desc)가 true이면, false를 반환한다.
      5. desc[[Writable]] 필드를 가지고 desc.[[Writable]]false이면, false를 반환한다.
      6. desc[[Value]] 필드를 가지면, ? TypedArraySetElement(obj, numericIndex, desc.[[Value]]) 를 수행한다.
      7. true를 반환한다.
  2. OrdinaryDefineOwnProperty(obj, propertyKey, desc)를 반환한다.

10.4.5.5 [[Get]] ( propertyKey, receiver )

The [[Get]] internal method of TypedArray obj takes arguments propertyKey (a property key) and receiver (an ECMAScript language value) and returns either a normal completion containing an ECMAScript language value or a throw completion. It performs the following steps when called:

  1. propertyKey가 String이면,
    1. numericIndexCanonicalNumericIndexString(propertyKey) 라고 하자.
    2. numericIndexundefined가 아니면,
      1. TypedArrayGetElement(obj, numericIndex)를 반환한다.
  2. OrdinaryGet(obj, propertyKey, receiver)를 반환한다.

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

The [[Set]] internal method of TypedArray obj takes arguments propertyKey (a property key), value (an ECMAScript language value), and receiver (an ECMAScript language value) and returns either a normal completion containing a Boolean or a throw completion. It performs the following steps when called:

  1. propertyKey가 String이면,
    1. numericIndexCanonicalNumericIndexString(propertyKey) 라고 하자.
    2. numericIndexundefined가 아니면,
      1. SameValue(obj, receiver)가 true이면,
        1. TypedArraySetElement(obj, numericIndex, value)를 수행한다.
        2. true를 반환한다.
      2. IsValidIntegerIndex(obj, numericIndex)가 false이면, true를 반환한다.
  2. OrdinarySet(obj, propertyKey, value, receiver)를 반환한다.

10.4.5.7 [[Delete]] ( propertyKey )

The [[Delete]] internal method of TypedArray obj takes argument propertyKey (a property key) and returns a normal completion containing a Boolean. It performs the following steps when called:

  1. propertyKey가 String이면,
    1. numericIndexCanonicalNumericIndexString(propertyKey) 라고 하자.
    2. numericIndexundefined가 아니면,
      1. IsValidIntegerIndex(obj, numericIndex)가 false이면, true를 반환한다.
      2. false를 반환한다.
  2. OrdinaryDelete(obj, propertyKey)를 반환한다.

10.4.5.8 [[OwnPropertyKeys]] ( )

The [[OwnPropertyKeys]] internal method of TypedArray obj takes no arguments and returns a normal completion containing a List of property keys. It performs the following steps when called:

  1. taRecordMakeTypedArrayWithBufferWitnessRecord(obj, seq-cst)라고 하자.
  2. keys를 새로운 빈 List라고 하자.
  3. IsTypedArrayOutOfBounds(taRecord)가 false이면,
    1. lengthTypedArrayLength(taRecord)라고 하자.
    2. 0 ≤ i < length인 각 정수 i에 대해, 오름차순으로, 다음을 수행한다
      1. ToString(𝔽(i))를 keys에 추가한다.
  4. obj의 각 자체 프로퍼티 키 propertyKey 중, propertyKey가 String이고 정수 인덱스가 아닌 것에 대해, 프로퍼티 생성의 시간순 오름차순으로, 다음을 수행한다
    1. propertyKeykeys에 추가한다.
  5. obj의 각 자체 프로퍼티 키 propertyKey 중, propertyKey가 Symbol인 것에 대해, 프로퍼티 생성의 시간순 오름차순으로, 다음을 수행한다
    1. propertyKeykeys에 추가한다.
  6. keys를 반환한다.

10.4.5.9 버퍼 witness record를 가진 TypedArray

TypedArray With Buffer Witness Record 는 viewed buffer의 캐시된 바이트 길이와 함께 TypedArray를 캡슐화하는 데 사용되는 Record 값이다. 이는 viewed buffer가 growable SharedArrayBuffer일 때 byte length data block에 대한 ReadSharedMemory event가 하나만 존재하도록 보장하는 데 도움을 주기 위해 사용된다.

TypedArray With Buffer Witness Record는 Table 27 에 나열된 필드를 가진다.

Table 27: TypedArray With Buffer Witness Record Fields
필드 이름 의미
[[Object]] a TypedArray 버퍼의 바이트 길이가 로드되는 TypedArray.
[[CachedBufferByteLength]] a non-negative integer or detached Record가 생성되었을 때 객체의 [[ViewedArrayBuffer]]의 바이트 길이.

10.4.5.10 MakeTypedArrayWithBufferWitnessRecord ( obj, order )

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

  1. bufferobj.[[ViewedArrayBuffer]]라고 하자.
  2. IsDetachedBuffer(buffer)가 true이면,
    1. byteLengthdetached라고 하자.
  3. 그렇지 않으면,
    1. byteLengthArrayBufferByteLength(buffer, order) 라고 하자.
  4. TypedArray With Buffer Witness Record { [[Object]]: obj, [[CachedBufferByteLength]]: byteLength }를 반환한다.

10.4.5.11 TypedArrayCreate ( 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. typedArrayMakeBasicObject(internalSlotsList)라고 하자.
  3. typedArray.[[PreventExtensions]]10.4.5.1 에 명시된 대로 설정한다.
  4. typedArray.[[GetOwnProperty]]10.4.5.2 에 명시된 대로 설정한다.
  5. typedArray.[[HasProperty]]10.4.5.3 에 명시된 대로 설정한다.
  6. typedArray.[[DefineOwnProperty]]10.4.5.4 에 명시된 대로 설정한다.
  7. typedArray.[[Get]]10.4.5.5 에 명시된 대로 설정한다.
  8. typedArray.[[Set]]10.4.5.6 에 명시된 대로 설정한다.
  9. typedArray.[[Delete]]10.4.5.7 에 명시된 대로 설정한다.
  10. typedArray.[[OwnPropertyKeys]]10.4.5.8 에 명시된 대로 설정한다.
  11. typedArray.[[Prototype]]prototype으로 설정한다.
  12. typedArray를 반환한다.

10.4.5.12 TypedArrayByteLength ( taRecord )

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

  1. Assert: IsTypedArrayOutOfBounds(taRecord)는 false이다.
  2. objtaRecord.[[Object]]라고 하자.
  3. obj.[[ByteLength]]auto가 아니면, obj.[[ByteLength]]를 반환한다.
  4. lengthTypedArrayLength(taRecord)라고 하자.
  5. elementSizeTypedArrayElementSize(obj)라고 하자.
  6. NOTE: 반환되는 byte length는, 기반 버퍼가 정수배가 아닌 크기로 리사이즈된 경우에도 항상 elementSize정수배이다.
  7. length × elementSize를 반환한다.

10.4.5.13 TypedArrayLength ( taRecord )

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

  1. Assert: IsTypedArrayOutOfBounds(taRecord)는 false이다.
  2. objtaRecord.[[Object]]라고 하자.
  3. obj.[[ArrayLength]]auto가 아니면, obj.[[ArrayLength]]를 반환한다.
  4. Assert: IsFixedLengthArrayBuffer(obj.[[ViewedArrayBuffer]]) 는 false이다.
  5. byteOffsetobj.[[ByteOffset]]라고 하자.
  6. elementSizeTypedArrayElementSize(obj)라고 하자.
  7. byteLengthtaRecord.[[CachedBufferByteLength]]라고 하자.
  8. Assert: byteLengthdetached가 아니다.
  9. floor((byteLength - byteOffset) / elementSize)를 반환한다.

10.4.5.14 IsTypedArrayOutOfBounds ( taRecord )

The abstract operation IsTypedArrayOutOfBounds takes argument taRecord (a TypedArray With Buffer Witness Record) and returns a Boolean. 이것은 객체의 수치 프로퍼티 중 어느 하나라도 기반 버퍼의 경계 안에 포함되지 않는 인덱스의 값을 참조하는지를 검사한다. It performs the following steps when called:

  1. objtaRecord.[[Object]]라고 하자.
  2. bufferByteLengthtaRecord.[[CachedBufferByteLength]] 라고 하자.
  3. IsDetachedBuffer(obj.[[ViewedArrayBuffer]])가 true이면,
    1. Assert: bufferByteLengthdetached이다.
    2. true를 반환한다.
  4. Assert: bufferByteLength는 음이 아닌 정수이다.
  5. byteOffsetStartobj.[[ByteOffset]]라고 하자.
  6. obj.[[ArrayLength]]auto이면,
    1. byteOffsetEndbufferByteLength라고 하자.
  7. 그렇지 않으면,
    1. elementSizeTypedArrayElementSize(obj)라고 하자.
    2. arrayByteLengthobj.[[ArrayLength]] × elementSize 라고 하자.
    3. byteOffsetEndbyteOffsetStart + arrayByteLength라고 하자.
  8. NOTE: [[ByteOffset]]bufferByteLength인 길이 0의 TypedArray는 out-of-bounds로 간주되지 않는다.
  9. byteOffsetStart > bufferByteLength이거나 byteOffsetEnd > bufferByteLength이면, true를 반환한다.
  10. false를 반환한다.

10.4.5.15 IsTypedArrayFixedLength ( obj )

The abstract operation IsTypedArrayFixedLength takes argument obj (a TypedArray) and returns a Boolean. It performs the following steps when called:

  1. obj.[[ArrayLength]]auto이면, false를 반환한다.
  2. bufferobj.[[ViewedArrayBuffer]]라고 하자.
  3. IsFixedLengthArrayBuffer(buffer)가 false이고 IsSharedArrayBuffer(buffer)도 false이면, false를 반환한다.
  4. true를 반환한다.

10.4.5.16 IsValidIntegerIndex ( obj, index )

The abstract operation IsValidIntegerIndex takes arguments obj (a TypedArray) and index (a Number) and returns a Boolean. It performs the following steps when called:

  1. IsDetachedBuffer(obj.[[ViewedArrayBuffer]])가 true이면, false를 반환한다.
  2. index정수 Number가 아니면, false를 반환한다.
  3. index-0𝔽이거나 index < -0𝔽이면, false를 반환한다.
  4. taRecordMakeTypedArrayWithBufferWitnessRecord(obj, unordered)라고 하자.
  5. NOTE: obj의 backing buffer가 growable SharedArrayBuffer인 경우, 경계 검사는 동기화 연산이 아니다.
  6. IsTypedArrayOutOfBounds(taRecord)가 true이면, false를 반환한다.
  7. lengthTypedArrayLength(taRecord)라고 하자.
  8. (index) ≥ length이면, false를 반환한다.
  9. true를 반환한다.

10.4.5.17 TypedArrayGetElement ( obj, index )

The abstract operation TypedArrayGetElement takes arguments obj (a TypedArray) and index (a Number) and returns a Number, a BigInt, or undefined. It performs the following steps when called:

  1. IsValidIntegerIndex(obj, index)가 false이면, undefined를 반환한다.
  2. offsetobj.[[ByteOffset]]라고 하자.
  3. elementSizeTypedArrayElementSize(obj)라고 하자.
  4. byteIndexInBuffer를 ((index) × elementSize) + offset 이라고 하자.
  5. elementTypeTypedArrayElementType(obj)라고 하자.
  6. GetValueFromBuffer(obj.[[ViewedArrayBuffer]], byteIndexInBuffer, elementType, true, unordered)를 반환한다.

10.4.5.18 TypedArraySetElement ( obj, index, value )

The abstract operation TypedArraySetElement takes arguments obj (a TypedArray), index (a Number), and value (an ECMAScript language value) and returns either a normal completion containing unused or a throw completion. It performs the following steps when called:

  1. obj.[[ContentType]]bigint이면, numValue를 ? ToBigInt(value)라고 하자.
  2. 그렇지 않으면, numValue를 ? ToNumber(value)라고 하자.
  3. IsValidIntegerIndex(obj, index)가 true이면,
    1. offsetobj.[[ByteOffset]]라고 하자.
    2. elementSizeTypedArrayElementSize(obj)라고 하자.
    3. byteIndexInBuffer를 ((index) × elementSize) + offset 이라고 하자.
    4. elementTypeTypedArrayElementType(obj)라고 하자.
    5. SetValueInBuffer(obj.[[ViewedArrayBuffer]], byteIndexInBuffer, elementType, numValue, true, unordered)를 수행한다.
  4. unused를 반환한다.
Note

이 연산은 항상 성공한 것처럼 보이지만, TypedArray의 끝을 넘어 쓰려고 시도하거나 detached ArrayBuffer를 backing으로 가진 TypedArray에 쓰려고 시도할 때는 아무 효과가 없다.

10.4.5.19 IsArrayBufferViewOutOfBounds ( obj )

The abstract operation IsArrayBufferViewOutOfBounds takes argument obj (a TypedArray or a DataView) and returns a Boolean. 이것은 TypedArray의 수치 프로퍼티들이나 DataView 객체의 메서드 중 어느 하나라도 기반 data block의 경계 안에 포함되지 않는 인덱스의 값을 참조할 수 있는지를 검사한다. 이 추상 연산은 상위 명세를 위한 편의 기능으로 존재한다. It performs the following steps when called:

  1. obj[[DataView]] 내부 슬롯을 가지면,
    1. viewRecordMakeDataViewWithBufferWitnessRecord(obj, seq-cst)라고 하자.
    2. IsViewOutOfBounds(viewRecord)를 반환한다.
  2. taRecordMakeTypedArrayWithBufferWitnessRecord(obj, seq-cst)라고 하자.
  3. IsTypedArrayOutOfBounds(taRecord)를 반환한다.

10.4.6 모듈 네임스페이스 이색 객체

모듈 네임스페이스 이색 객체는 ECMAScript Module에서 export된 바인딩을 노출하는 이색 객체이다 (참조: 16.2.3). 모듈 네임스페이스 이색 객체의 String 키를 가진 자체 프로퍼티와 Module이 export한 바인딩 이름 사이에는 일대일 대응이 있다. export된 바인딩에는 export * export item을 사용하여 간접적으로 export된 바인딩도 포함된다. 각 String 값의 자체 프로퍼티 키는 대응하는 export된 바인딩 이름의 StringValue이다. 이것들만이 모듈 네임스페이스 이색 객체의 String 키 프로퍼티이다. 각 그러한 프로퍼티는 { [[Writable]]: true, [[Enumerable]]: true, [[Configurable]]: false } 속성을 가진다. 모듈 네임스페이스 이색 객체는 확장 가능하지 않다.

객체는 그 [[GetPrototypeOf]], [[SetPrototypeOf]], [[IsExtensible]], [[PreventExtensions]], [[GetOwnProperty]], [[DefineOwnProperty]], [[HasProperty]], [[Get]], [[Set]], [[Delete]], [[OwnPropertyKeys]] 내부 메서드가 이 절의 정의를 사용하고, 다른 essential 내부 메서드는 10.1 에서 찾을 수 있는 정의를 사용할 때 모듈 네임스페이스 이색 객체 이다. 이 메서드들은 ModuleNamespaceCreate에 의해 설치된다.

모듈 네임스페이스 이색 객체Table 28 에 정의된 내부 슬롯을 가진다.

Table 28: Internal Slots of Module Namespace Exotic Objects
내부 슬롯 타입 설명
[[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 a normal completion containing null. It performs the following steps when called:

  1. null을 반환한다.

10.4.6.2 [[SetPrototypeOf]] ( proto )

The [[SetPrototypeOf]] internal method of 모듈 네임스페이스 이색 객체 obj takes argument proto (an Object or null) and returns a normal completion containing a Boolean. It performs the following steps when called:

  1. SetImmutablePrototype(obj, proto)를 반환한다.

10.4.6.3 [[IsExtensible]] ( )

The [[IsExtensible]] internal method of 모듈 네임스페이스 이색 객체 takes no arguments and returns a normal completion containing false. It performs the following steps when called:

  1. false를 반환한다.

10.4.6.4 [[PreventExtensions]] ( )

The [[PreventExtensions]] internal method of 모듈 네임스페이스 이색 객체 takes no arguments and returns a normal completion containing true. It performs the following steps when called:

  1. true를 반환한다.

10.4.6.5 [[GetOwnProperty]] ( propertyKey )

The [[GetOwnProperty]] internal method of 모듈 네임스페이스 이색 객체 obj takes argument propertyKey (a property key) and returns either a normal completion containing either a Property Descriptor or undefined, or a throw completion. It performs the following steps when called:

  1. propertyKey가 Symbol이면, OrdinaryGetOwnProperty(obj, propertyKey)를 반환한다.
  2. exportsobj.[[Exports]]라고 하자.
  3. exportspropertyKey를 포함하지 않으면, undefined를 반환한다.
  4. value를 ? obj.[[Get]](propertyKey, obj)라고 하자.
  5. PropertyDescriptor { [[Value]]: value, [[Writable]]: true, [[Enumerable]]: true, [[Configurable]]: false }를 반환한다.

10.4.6.6 [[DefineOwnProperty]] ( propertyKey, desc )

The [[DefineOwnProperty]] internal method of 모듈 네임스페이스 이색 객체 obj takes arguments propertyKey (a property key) and desc (a Property Descriptor) and returns either a normal completion containing a Boolean or a throw completion. It performs the following steps when called:

  1. propertyKey가 Symbol이면, ! OrdinaryDefineOwnProperty(obj, propertyKey, desc)를 반환한다.
  2. current를 ? obj.[[GetOwnProperty]](propertyKey)라고 하자.
  3. currentundefined이면, false를 반환한다.
  4. desc[[Configurable]] 필드를 가지고 desc.[[Configurable]]true이면, false를 반환한다.
  5. desc[[Enumerable]] 필드를 가지고 desc.[[Enumerable]]false이면, false를 반환한다.
  6. IsAccessorDescriptor(desc)가 true이면, false를 반환한다.
  7. desc[[Writable]] 필드를 가지고 desc.[[Writable]]false이면, false를 반환한다.
  8. desc[[Value]] 필드를 가지면, SameValue(desc.[[Value]], current.[[Value]])를 반환한다.
  9. true를 반환한다.

10.4.6.7 [[HasProperty]] ( propertyKey )

The [[HasProperty]] internal method of 모듈 네임스페이스 이색 객체 obj takes argument propertyKey (a property key) and returns a normal completion containing a Boolean. It performs the following steps when called:

  1. propertyKey가 Symbol이면, ! OrdinaryHasProperty(obj, propertyKey)를 반환한다.
  2. exportsobj.[[Exports]]라고 하자.
  3. exportspropertyKey를 포함하면, true를 반환한다.
  4. false를 반환한다.

10.4.6.8 [[Get]] ( propertyKey, receiver )

The [[Get]] internal method of 모듈 네임스페이스 이색 객체 obj takes arguments propertyKey (a property key) and receiver (an ECMAScript language value) and returns either a normal completion containing an ECMAScript language value or a throw completion. It performs the following steps when called:

  1. propertyKey가 Symbol이면,
    1. OrdinaryGet(obj, propertyKey, receiver)를 반환한다.
  2. exportsobj.[[Exports]]라고 하자.
  3. exportspropertyKey를 포함하지 않으면, undefined를 반환한다.
  4. moduleobj.[[Module]]이라고 하자.
  5. bindingmodule.ResolveExport(propertyKey)라고 하자.
  6. Assert: binding은 ResolvedBinding Record이다.
  7. targetModulebinding.[[Module]]이라고 하자.
  8. Assert: targetModuleundefined가 아니다.
  9. binding.[[BindingName]]namespace이면,
    1. GetModuleNamespace(targetModule)를 반환한다.
  10. targetEnvtargetModule.[[Environment]]라고 하자.
  11. targetEnvempty이면, ReferenceError 예외를 던진다.
  12. targetEnv.GetBindingValue(binding.[[BindingName]], true) 를 반환한다.
Note

ResolveExport는 부작용이 없다. 이 연산이 특정 exportName, resolveSet 쌍을 인수로 호출될 때마다 반드시 같은 결과를 반환해야 한다. 구현은 각 모듈 네임스페이스 이색 객체[[Exports]]에 대한 ResolveExport 결과를 미리 계산하거나 캐시하도록 선택할 수 있다.

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

The [[Set]] internal method of 모듈 네임스페이스 이색 객체 takes arguments propertyKey (a property key), value (an ECMAScript language value), and receiver (an ECMAScript language value) and returns a normal completion containing false. It performs the following steps when called:

  1. false를 반환한다.

10.4.6.10 [[Delete]] ( propertyKey )

The [[Delete]] internal method of 모듈 네임스페이스 이색 객체 obj takes argument propertyKey (a property key) and returns a normal completion containing a Boolean. It performs the following steps when called:

  1. propertyKey가 Symbol이면,
    1. OrdinaryDelete(obj, propertyKey)를 반환한다.
  2. exportsobj.[[Exports]]라고 하자.
  3. exportspropertyKey를 포함하면, false를 반환한다.
  4. true를 반환한다.

10.4.6.11 [[OwnPropertyKeys]] ( )

The [[OwnPropertyKeys]] internal method of 모듈 네임스페이스 이색 객체 obj takes no arguments and returns a normal completion containing a List of property keys. It performs the following steps when called:

  1. exportsobj.[[Exports]]라고 하자.
  2. symbolKeysOrdinaryOwnPropertyKeys(obj)라고 하자.
  3. exportssymbolKeyslist-concatenation을 반환한다.

10.4.6.12 ModuleNamespaceCreate ( module, exports )

The abstract operation ModuleNamespaceCreate takes arguments module (a Module Record) and exports (a List of Strings) and returns a module namespace exotic object. 이것은 새로운 모듈 네임스페이스 이색 객체의 생성을 명세하는 데 사용된다. It performs the following steps when called:

  1. Assert: module.[[Namespace]]empty이다.
  2. internalSlotsListTable 28 에 나열된 내부 슬롯이라고 하자.
  3. namespaceMakeBasicObject(internalSlotsList)라고 하자.
  4. namespace의 essential 내부 메서드를 10.4.6 에 명시된 정의로 설정한다.
  5. namespace.[[Module]]module로 설정한다.
  6. sortedExportsexports의 요소들을 코드 유닛 사전식 순서에 따라 정렬한 List라고 하자.
  7. namespace.[[Exports]]sortedExports로 설정한다.
  8. 28.3의 정의에 대응하는 namespace의 자체 프로퍼티를 생성한다.
  9. module.[[Namespace]]namespace로 설정한다.
  10. namespace를 반환한다.

10.4.7 불변 프로토타입 이색 객체

불변 프로토타입 이색 객체는, 한 번 초기화되면 더 이상 바뀌지 않는 [[Prototype]] 내부 슬롯을 가진 이색 객체이다.

객체는 그 [[SetPrototypeOf]] 내부 메서드가 다음 구현을 사용할 때 불변 프로토타입 이색 객체 이다. (다른 essential 내부 메서드는, 해당 불변 프로토타입 이색 객체의 구체적 성격에 따라, 임의의 구현을 사용할 수 있다.)

Note

다른 이색 객체와 달리, 불변 프로토타입 이색 객체를 위한 전용 생성 추상 연산은 제공되지 않는다. 이는 그것들이 오직 %Object.prototype%호스트 환경에서만 사용되기 때문이며, 호스트 환경에서는 관련 객체들이 다른 방식으로도 이색적일 수 있으므로 별도의 전용 생성 연산이 필요하다.

10.4.7.1 [[SetPrototypeOf]] ( proto )

The [[SetPrototypeOf]] internal method of 불변 프로토타입 이색 객체 obj takes argument proto (an Object or null) and returns either a normal completion containing a Boolean or a throw completion. It performs the following steps when called:

  1. SetImmutablePrototype(obj, proto)를 반환한다.

10.4.7.2 SetImmutablePrototype ( obj, proto )

The abstract operation SetImmutablePrototype takes arguments obj (an Object) and proto (an Object or null) and returns either a normal completion containing a Boolean or a throw completion. It performs the following steps when called:

  1. current를 ? obj.[[GetPrototypeOf]]() 라고 하자.
  2. SameValue(proto, current)가 true이면, true를 반환한다.
  3. false를 반환한다.

10.5 프록시 객체 내부 메서드와 내부 슬롯

프록시 객체는 essential 내부 메서드가 부분적으로 ECMAScript 코드를 사용하여 구현되는 이색 객체이다. 모든 프록시 객체는 [[ProxyHandler]]라는 내부 슬롯을 가진다. [[ProxyHandler]]의 값은 프록시의 handler object라고 불리는 객체이거나 null이다. handler object의 메서드(참조: Table 29)는 프록시 객체의 하나 이상의 내부 메서드 구현을 보강하는 데 사용될 수 있다. 모든 프록시 객체는 또한 [[ProxyTarget]]이라는 내부 슬롯을 가지며, 그 값은 객체 또는 null이다. 이 객체는 프록시의 target object라고 불린다.

객체는 그 essential 내부 메서드(해당하는 경우 [[Call]][[Construct]] 포함)가 이 절의 정의를 사용할 때 프록시 이색 객체 이다. 이 내부 메서드들은 ProxyCreate에서 설치된다.

Table 29: Proxy Handler Methods
내부 메서드 핸들러 메서드
[[GetPrototypeOf]] getPrototypeOf
[[SetPrototypeOf]] setPrototypeOf
[[IsExtensible]] isExtensible
[[PreventExtensions]] preventExtensions
[[GetOwnProperty]] getOwnPropertyDescriptor
[[DefineOwnProperty]] defineProperty
[[HasProperty]] has
[[Get]] get
[[Set]] set
[[Delete]] deleteProperty
[[OwnPropertyKeys]] ownKeys
[[Call]] apply
[[Construct]] construct

프록시 객체 내부 메서드의 구현을 제공하기 위해 handler 메서드가 호출될 때, 그 handler 메서드에는 프록시의 target object가 매개변수로 전달된다. 프록시의 handler object가 반드시 모든 essential 내부 메서드에 대응하는 메서드를 가지는 것은 아니다. 프록시에 대한 내부 메서드 호출은, handler object가 대응하는 내부 trap에 대한 메서드를 가지지 않을 경우, 프록시의 target object에 대한 대응 내부 메서드 호출이 일어나게 한다.

프록시 객체의 [[ProxyHandler]][[ProxyTarget]] 내부 슬롯은 객체가 생성될 때 항상 초기화되며, 일반적으로 수정될 수 없다. 일부 프록시 객체는 나중에 revoked될 수 있도록 허용하는 방식으로 생성된다. 프록시가 revoked되면, 그 [[ProxyHandler]][[ProxyTarget]] 내부 슬롯은 null로 설정되며, 그 결과 그 프록시 객체에 대한 이후의 내부 메서드 호출은 TypeError 예외를 던지게 된다.

프록시 객체는 내부 메서드의 구현을 임의의 ECMAScript 코드로 제공할 수 있게 허용하기 때문에, 6.1.7.3 에 정의된 불변식을 위반하는 handler 메서드를 가진 프록시 객체를 정의하는 것이 가능하다. 6.1.7.3 에 정의된 내부 메서드 불변식 중 일부는 essential 무결성 불변식이다. 이러한 불변식은 이 절에 명시된 프록시 객체 내부 메서드에 의해 명시적으로 강제된다. ECMAScript 구현은 가능한 모든 불변식 위반이 존재하는 상황에서도 견고해야 한다.

다음 알고리즘 설명에서, obj는 ECMAScript 프록시 객체이고, propertyKey는 프로퍼티 키 값이며, value는 임의의 ECMAScript 언어 값이고, descProperty Descriptor 레코드라고 가정한다.

10.5.1 [[GetPrototypeOf]] ( )

The [[GetPrototypeOf]] internal method of 프록시 이색 객체 obj takes no arguments and returns either a normal completion containing either an Object or null, or a throw completion. It performs the following steps when called:

  1. ValidateNonRevokedProxy(obj)를 수행한다.
  2. targetobj.[[ProxyTarget]]이라고 하자.
  3. handlerobj.[[ProxyHandler]]라고 하자.
  4. Assert: handler는 Object이다.
  5. trap을 ? GetMethod(handler, "getPrototypeOf")라고 하자.
  6. trapundefined이면,
    1. target.[[GetPrototypeOf]]()를 반환한다.
  7. handlerProto를 ? Call(trap, handler, « target »)라고 하자.
  8. handlerProto가 Object도 아니고 null도 아니면, TypeError 예외를 던진다.
  9. extensibleTarget을 ? IsExtensible(target)이라고 하자.
  10. extensibleTargettrue이면, handlerProto를 반환한다.
  11. targetProto를 ? target.[[GetPrototypeOf]]()라고 하자.
  12. SameValue(handlerProto, targetProto)가 false이면, TypeError 예외를 던진다.
  13. handlerProto를 반환한다.
Note

프록시 객체에 대한 [[GetPrototypeOf]]는 다음 불변식을 강제한다:

  • [[GetPrototypeOf]]의 결과는 반드시 Object 또는 null이어야 한다.
  • target 객체가 확장 가능하지 않다면, 프록시 객체에 적용된 [[GetPrototypeOf]]는 프록시 객체의 target 객체에 적용된 [[GetPrototypeOf]]와 같은 값을 반환해야 한다.

10.5.2 [[SetPrototypeOf]] ( proto )

The [[SetPrototypeOf]] internal method of 프록시 이색 객체 obj takes argument proto (an Object or null) and returns either a normal completion containing a Boolean or a throw completion. It performs the following steps when called:

  1. ValidateNonRevokedProxy(obj)를 수행한다.
  2. targetobj.[[ProxyTarget]]이라고 하자.
  3. handlerobj.[[ProxyHandler]]라고 하자.
  4. Assert: handler는 Object이다.
  5. trap을 ? GetMethod(handler, "setPrototypeOf")라고 하자.
  6. trapundefined이면,
    1. target.[[SetPrototypeOf]](proto)를 반환한다.
  7. booleanTrapResultToBoolean(? Call(trap, handler, « target, proto »))라고 하자.
  8. booleanTrapResultfalse이면, false를 반환한다.
  9. extensibleTarget을 ? IsExtensible(target)이라고 하자.
  10. extensibleTargettrue이면, true를 반환한다.
  11. targetProto를 ? target.[[GetPrototypeOf]]()라고 하자.
  12. SameValue(proto, targetProto)가 false이면, TypeError 예외를 던진다.
  13. true를 반환한다.
Note

프록시 객체에 대한 [[SetPrototypeOf]]는 다음 불변식을 강제한다:

  • [[SetPrototypeOf]]의 결과는 Boolean 값이다.
  • target 객체가 확장 가능하지 않다면, 인수 값은 target 객체에 [[GetPrototypeOf]]를 적용한 결과와 같아야 한다.

10.5.3 [[IsExtensible]] ( )

The [[IsExtensible]] internal method of 프록시 이색 객체 obj takes no arguments and returns either a normal completion containing a Boolean or a throw completion. It performs the following steps when called:

  1. ValidateNonRevokedProxy(obj)를 수행한다.
  2. targetobj.[[ProxyTarget]]이라고 하자.
  3. handlerobj.[[ProxyHandler]]라고 하자.
  4. Assert: handler는 Object이다.
  5. trap을 ? GetMethod(handler, "isExtensible")라고 하자.
  6. trapundefined이면,
    1. IsExtensible(target)를 반환한다.
  7. booleanTrapResultToBoolean(? Call(trap, handler, « target »))라고 하자.
  8. targetResult를 ? IsExtensible(target)라고 하자.
  9. booleanTrapResulttargetResult와 다르면, TypeError 예외를 던진다.
  10. booleanTrapResult를 반환한다.
Note

프록시 객체에 대한 [[IsExtensible]]는 다음 불변식을 강제한다:

  • [[IsExtensible]]의 결과는 Boolean 값이다.
  • 프록시 객체에 적용된 [[IsExtensible]]는 같은 인수로 프록시 객체의 target 객체에 적용된 [[IsExtensible]]와 같은 값을 반환해야 한다.

10.5.4 [[PreventExtensions]] ( )

The [[PreventExtensions]] internal method of 프록시 이색 객체 obj takes no arguments and returns either a normal completion containing a Boolean or a throw completion. It performs the following steps when called:

  1. ValidateNonRevokedProxy(obj)를 수행한다.
  2. targetobj.[[ProxyTarget]]이라고 하자.
  3. handlerobj.[[ProxyHandler]]라고 하자.
  4. Assert: handler는 Object이다.
  5. trap을 ? GetMethod(handler, "preventExtensions")라고 하자.
  6. trapundefined이면,
    1. target.[[PreventExtensions]]()를 반환한다.
  7. booleanTrapResultToBoolean(? Call(trap, handler, « target »))라고 하자.
  8. booleanTrapResulttrue이면,
    1. extensibleTarget을 ? IsExtensible(target)이라고 하자.
    2. extensibleTargettrue이면, TypeError 예외를 던진다.
  9. booleanTrapResult를 반환한다.
Note

프록시 객체에 대한 [[PreventExtensions]]는 다음 불변식을 강제한다:

  • [[PreventExtensions]]의 결과는 Boolean 값이다.
  • 프록시 객체에 적용된 [[PreventExtensions]]는 프록시 객체의 target 객체에 [[IsExtensible]]를 적용했을 때 false인 경우에만 true를 반환한다.

10.5.5 [[GetOwnProperty]] ( propertyKey )

The [[GetOwnProperty]] internal method of 프록시 이색 객체 obj takes argument propertyKey (a property key) and returns either a normal completion containing either a Property Descriptor or undefined, or a throw completion. It performs the following steps when called:

  1. ValidateNonRevokedProxy(obj)를 수행한다.
  2. targetobj.[[ProxyTarget]]이라고 하자.
  3. handlerobj.[[ProxyHandler]]라고 하자.
  4. Assert: handler는 Object이다.
  5. trap을 ? GetMethod(handler, "getOwnPropertyDescriptor") 라고 하자.
  6. trapundefined이면,
    1. target.[[GetOwnProperty]](propertyKey)를 반환한다.
  7. trapResultObj를 ? Call(trap, handler, « target, propertyKey »)라고 하자.
  8. trapResultObj가 Object도 아니고 undefined도 아니면, TypeError 예외를 던진다.
  9. targetDesc를 ? target.[[GetOwnProperty]](propertyKey)라고 하자.
  10. trapResultObjundefined이면,
    1. targetDescundefined이면, undefined를 반환한다.
    2. targetDesc.[[Configurable]]false이면, TypeError 예외를 던진다.
    3. extensibleTarget을 ? IsExtensible(target)이라고 하자.
    4. extensibleTargetfalse이면, TypeError 예외를 던진다.
    5. undefined를 반환한다.
  11. extensibleTarget을 ? IsExtensible(target)이라고 하자.
  12. resultDesc를 ? ToPropertyDescriptor(trapResultObj)라고 하자.
  13. CompletePropertyDescriptor(resultDesc)를 수행한다.
  14. validIsCompatiblePropertyDescriptor(extensibleTarget, resultDesc, targetDesc)라고 하자.
  15. validfalse이면, TypeError 예외를 던진다.
  16. resultDesc.[[Configurable]]false이면,
    1. targetDescundefined이거나 targetDesc.[[Configurable]]true이면,
      1. TypeError 예외를 던진다.
    2. resultDesc[[Writable]] 필드를 가지고 resultDesc.[[Writable]]false이면,
      1. Assert: targetDesc[[Writable]] 필드를 가진다.
      2. targetDesc.[[Writable]]true이면, TypeError 예외를 던진다.
  17. resultDesc를 반환한다.
Note

프록시 객체에 대한 [[GetOwnProperty]]는 다음 불변식을 강제한다:

  • [[GetOwnProperty]]의 결과는 반드시 Property Descriptor 또는 undefined여야 한다.
  • target 객체에 non-configurable 자체 프로퍼티로 존재하는 프로퍼티는 존재하지 않는 것으로 보고될 수 없다.
  • non-extensible target 객체의 자체 프로퍼티로 존재하는 프로퍼티는 존재하지 않는 것으로 보고될 수 없다.
  • target 객체에 자체 프로퍼티로 존재하지 않고 target 객체가 확장 가능하지 않은 경우, 그 프로퍼티는 존재하는 것으로 보고될 수 없다.
  • 프로퍼티는 target 객체의 대응하는 non-configurable 자체 프로퍼티로 존재하지 않는 한 non-configurable로 보고될 수 없다.
  • 프로퍼티는 target 객체의 대응하는 non-configurable, non-writable 자체 프로퍼티로 존재하지 않는 한, non-configurable이면서 non-writable인 것으로 보고될 수 없다.

10.5.6 [[DefineOwnProperty]] ( propertyKey, desc )

The [[DefineOwnProperty]] internal method of 프록시 이색 객체 obj takes arguments propertyKey (a property key) and desc (a Property Descriptor) and returns either a normal completion containing a Boolean or a throw completion. It performs the following steps when called:

  1. ValidateNonRevokedProxy(obj)를 수행한다.
  2. targetobj.[[ProxyTarget]]이라고 하자.
  3. handlerobj.[[ProxyHandler]]라고 하자.
  4. Assert: handler는 Object이다.
  5. trap을 ? GetMethod(handler, "defineProperty")라고 하자.
  6. trapundefined이면,
    1. target.[[DefineOwnProperty]](propertyKey, desc)를 반환한다.
  7. descObjFromPropertyDescriptor(desc)라고 하자.
  8. booleanTrapResultToBoolean(? Call(trap, handler, « target, propertyKey, descObj »))라고 하자.
  9. booleanTrapResultfalse이면, false를 반환한다.
  10. targetDesc를 ? target.[[GetOwnProperty]](propertyKey)라고 하자.
  11. extensibleTarget을 ? IsExtensible(target)이라고 하자.
  12. desc[[Configurable]] 필드를 가지고 desc.[[Configurable]]false이면,
    1. settingConfigFalsetrue라고 하자.
  13. 그렇지 않으면,
    1. settingConfigFalsefalse라고 하자.
  14. targetDescundefined이면,
    1. extensibleTargetfalse이면, TypeError 예외를 던진다.
    2. settingConfigFalsetrue이면, TypeError 예외를 던진다.
  15. 그렇지 않으면,
    1. IsCompatiblePropertyDescriptor(extensibleTarget, desc, targetDesc)가 false이면, TypeError 예외를 던진다.
    2. settingConfigFalsetrue이고 targetDesc.[[Configurable]]true이면, TypeError 예외를 던진다.
    3. IsDataDescriptor(targetDesc)가 true이고, targetDesc.[[Configurable]]false이며, targetDesc.[[Writable]]true이면,
      1. desc[[Writable]] 필드를 가지고 desc.[[Writable]]false이면, TypeError 예외를 던진다.
  16. true를 반환한다.
Note

프록시 객체에 대한 [[DefineOwnProperty]]는 다음 불변식을 강제한다:

  • [[DefineOwnProperty]]의 결과는 Boolean 값이다.
  • target 객체가 확장 가능하지 않다면 프로퍼티는 추가될 수 없다.
  • target 객체에 대응하는 non-configurable 자체 프로퍼티가 존재하지 않는 한, 프로퍼티는 non-configurable일 수 없다.
  • target 객체에 대응하는 non-configurable, non-writable 자체 프로퍼티가 존재하지 않는 한, non-configurable 프로퍼티는 non-writable일 수 없다.
  • 프로퍼티가 대응하는 target 객체 프로퍼티를 가지는 경우, 그 프로퍼티의 Property Descriptor[[DefineOwnProperty]]를 사용하여 target 객체에 적용해도 예외를 던지지 않는다.

10.5.7 [[HasProperty]] ( propertyKey )

The [[HasProperty]] internal method of 프록시 이색 객체 obj takes argument propertyKey (a property key) and returns either a normal completion containing a Boolean or a throw completion. It performs the following steps when called:

  1. ValidateNonRevokedProxy(obj)를 수행한다.
  2. targetobj.[[ProxyTarget]]이라고 하자.
  3. handlerobj.[[ProxyHandler]]라고 하자.
  4. Assert: handler는 Object이다.
  5. trap을 ? GetMethod(handler, "has")라고 하자.
  6. trapundefined이면,
    1. target.[[HasProperty]](propertyKey)를 반환한다.
  7. booleanTrapResultToBoolean(? Call(trap, handler, « target, propertyKey »))라고 하자.
  8. booleanTrapResultfalse이면,
    1. targetDesc를 ? target.[[GetOwnProperty]](propertyKey)라고 하자.
    2. targetDescundefined가 아니면,
      1. targetDesc.[[Configurable]]false이면, TypeError 예외를 던진다.
      2. extensibleTarget을 ? IsExtensible(target)이라고 하자.
      3. extensibleTargetfalse이면, TypeError 예외를 던진다.
  9. booleanTrapResult를 반환한다.
Note

프록시 객체에 대한 [[HasProperty]]는 다음 불변식을 강제한다:

  • [[HasProperty]]의 결과는 Boolean 값이다.
  • target 객체에 non-configurable 자체 프로퍼티로 존재하는 프로퍼티는 존재하지 않는 것으로 보고될 수 없다.
  • target 객체의 자체 프로퍼티로 존재하고 target 객체가 확장 가능하지 않은 경우, 그 프로퍼티는 존재하지 않는 것으로 보고될 수 없다.

10.5.8 [[Get]] ( propertyKey, receiver )

The [[Get]] internal method of 프록시 이색 객체 obj takes arguments propertyKey (a property key) and receiver (an ECMAScript language value) and returns either a normal completion containing an ECMAScript language value or a throw completion. It performs the following steps when called:

  1. ValidateNonRevokedProxy(obj)를 수행한다.
  2. targetobj.[[ProxyTarget]]이라고 하자.
  3. handlerobj.[[ProxyHandler]]라고 하자.
  4. Assert: handler는 Object이다.
  5. trap을 ? GetMethod(handler, "get")라고 하자.
  6. trapundefined이면,
    1. target.[[Get]](propertyKey, receiver)를 반환한다.
  7. trapResult를 ? Call(trap, handler, « target, propertyKey, receiver »)라고 하자.
  8. targetDesc를 ? target.[[GetOwnProperty]](propertyKey)라고 하자.
  9. targetDescundefined가 아니고 targetDesc.[[Configurable]]false이면,
    1. IsDataDescriptor(targetDesc)가 true이고 targetDesc.[[Writable]]false이면,
      1. SameValue(trapResult, targetDesc.[[Value]])가 false이면, TypeError 예외를 던진다.
    2. IsAccessorDescriptor(targetDesc)가 true이고 targetDesc.[[Get]]undefined이면,
      1. trapResultundefined가 아니면, TypeError 예외를 던진다.
  10. trapResult를 반환한다.
Note

프록시 객체에 대한 [[Get]]은 다음 불변식을 강제한다:

  • target 객체의 대응 프로퍼티가 non-writable, non-configurable 자체 데이터 프로퍼티라면, 프로퍼티에 대해 보고된 값은 그 target 객체 프로퍼티의 값과 같아야 한다.
  • target 객체의 대응 프로퍼티가 [[Get]] 속성으로 undefined를 가진 non-configurable 자체 접근자 프로퍼티라면, 프로퍼티에 대해 보고된 값은 반드시 undefined이어야 한다.

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

The [[Set]] internal method of 프록시 이색 객체 obj takes arguments propertyKey (a property key), value (an ECMAScript language value), and receiver (an ECMAScript language value) and returns either a normal completion containing a Boolean or a throw completion. It performs the following steps when called:

  1. ValidateNonRevokedProxy(obj)를 수행한다.
  2. targetobj.[[ProxyTarget]]이라고 하자.
  3. handlerobj.[[ProxyHandler]]라고 하자.
  4. Assert: handler는 Object이다.
  5. trap을 ? GetMethod(handler, "set")라고 하자.
  6. trapundefined이면,
    1. target.[[Set]](propertyKey, value, receiver)를 반환한다.
  7. booleanTrapResultToBoolean(? Call(trap, handler, « target, propertyKey, value, receiver »))라고 하자.
  8. booleanTrapResultfalse이면, false를 반환한다.
  9. targetDesc를 ? target.[[GetOwnProperty]](propertyKey)라고 하자.
  10. targetDescundefined가 아니고 targetDesc.[[Configurable]]false이면,
    1. IsDataDescriptor(targetDesc)가 true이고 targetDesc.[[Writable]]false이면,
      1. SameValue(value, targetDesc.[[Value]])가 false이면, TypeError 예외를 던진다.
    2. IsAccessorDescriptor(targetDesc)가 true이면,
      1. targetDesc.[[Set]]undefined이면, TypeError 예외를 던진다.
  11. true를 반환한다.
Note

프록시 객체에 대한 [[Set]]은 다음 불변식을 강제한다:

  • [[Set]]의 결과는 Boolean 값이다.
  • 대응하는 target 객체 프로퍼티가 non-writable, non-configurable 자체 데이터 프로퍼티인 경우, 그 프로퍼티의 값을 대응하는 target 객체 프로퍼티의 값과 다르게 변경할 수 없다.
  • 대응하는 target 객체 프로퍼티가 [[Set]] 속성으로 undefined를 가진 non-configurable 자체 접근자 프로퍼티인 경우, 그 프로퍼티의 값을 설정할 수 없다.

10.5.10 [[Delete]] ( propertyKey )

The [[Delete]] internal method of 프록시 이색 객체 obj takes argument propertyKey (a property key) and returns either a normal completion containing a Boolean or a throw completion. It performs the following steps when called:

  1. ValidateNonRevokedProxy(obj)를 수행한다.
  2. targetobj.[[ProxyTarget]]이라고 하자.
  3. handlerobj.[[ProxyHandler]]라고 하자.
  4. Assert: handler는 Object이다.
  5. trap을 ? GetMethod(handler, "deleteProperty")라고 하자.
  6. trapundefined이면,
    1. target.[[Delete]](propertyKey)를 반환한다.
  7. booleanTrapResultToBoolean(? Call(trap, handler, « target, propertyKey »))라고 하자.
  8. booleanTrapResultfalse이면, false를 반환한다.
  9. targetDesc를 ? target.[[GetOwnProperty]](propertyKey)라고 하자.
  10. targetDescundefined이면, true를 반환한다.
  11. targetDesc.[[Configurable]]false이면, TypeError 예외를 던진다.
  12. extensibleTarget을 ? IsExtensible(target)이라고 하자.
  13. extensibleTargetfalse이면, TypeError 예외를 던진다.
  14. true를 반환한다.
Note

프록시 객체에 대한 [[Delete]]는 다음 불변식을 강제한다:

  • [[Delete]]의 결과는 Boolean 값이다.
  • target 객체에 non-configurable 자체 프로퍼티로 존재하는 프로퍼티는 삭제된 것으로 보고될 수 없다.
  • target 객체에 자체 프로퍼티로 존재하고 target 객체가 non-extensible인 경우, 그 프로퍼티는 삭제된 것으로 보고될 수 없다.

10.5.11 [[OwnPropertyKeys]] ( )

The [[OwnPropertyKeys]] internal method of 프록시 이색 객체 obj takes no arguments and returns either a normal completion containing a List of property keys or a throw completion. It performs the following steps when called:

  1. ValidateNonRevokedProxy(obj)를 수행한다.
  2. targetobj.[[ProxyTarget]]이라고 하자.
  3. handlerobj.[[ProxyHandler]]라고 하자.
  4. Assert: handler는 Object이다.
  5. trap을 ? GetMethod(handler, "ownKeys")라고 하자.
  6. trapundefined이면,
    1. target.[[OwnPropertyKeys]]()를 반환한다.
  7. trapResultArray를 ? Call(trap, handler, « target ») 라고 하자.
  8. trapResult를 ? CreateListFromArrayLike(trapResultArray, property-key)라고 하자.
  9. trapResult가 중복 항목을 하나라도 포함하면, TypeError 예외를 던진다.
  10. extensibleTarget을 ? IsExtensible(target)이라고 하자.
  11. targetKeys를 ? target.[[OwnPropertyKeys]]()라고 하자.
  12. Assert: targetKeys는 프로퍼티 키의 List이다.
  13. Assert: targetKeys는 중복 항목을 포함하지 않는다.
  14. targetConfigurableKeys를 새로운 빈 List라고 하자.
  15. targetNonconfigurableKeys를 새로운 빈 List라고 하자.
  16. targetKeys의 각 요소 key에 대해, 다음을 수행한다
    1. desc를 ? target.[[GetOwnProperty]](key)라고 하자.
    2. descundefined가 아니고 desc.[[Configurable]]false이면,
      1. keytargetNonconfigurableKeys에 추가한다.
    3. 그렇지 않으면,
      1. keytargetConfigurableKeys에 추가한다.
  17. extensibleTargettrue이고 targetNonconfigurableKeys가 비어 있으면,
    1. trapResult를 반환한다.
  18. uncheckedResultKeystrapResult의 요소들을 요소로 가지는 List라고 하자.
  19. targetNonconfigurableKeys의 각 요소 key에 대해, 다음을 수행한다
    1. uncheckedResultKeyskey를 포함하지 않으면, TypeError 예외를 던진다.
    2. uncheckedResultKeys에서 key를 제거한다.
  20. extensibleTargettrue이면, trapResult를 반환한다.
  21. targetConfigurableKeys의 각 요소 key에 대해, 다음을 수행한다
    1. uncheckedResultKeyskey를 포함하지 않으면, TypeError 예외를 던진다.
    2. uncheckedResultKeys에서 key를 제거한다.
  22. uncheckedResultKeys가 비어 있지 않으면, TypeError 예외를 던진다.
  23. trapResult를 반환한다.
Note

프록시 객체에 대한 [[OwnPropertyKeys]]는 다음 불변식을 강제한다:

  • [[OwnPropertyKeys]]의 결과는 List이다.
  • 반환된 List는 중복 항목을 포함하지 않는다.
  • 반환된 List의 각 요소는 프로퍼티 키이다.
  • 결과 List는 target 객체의 모든 non-configurable 자체 프로퍼티의 키를 포함해야 한다.
  • target 객체가 확장 가능하지 않다면, 결과 List는 target 객체의 모든 자체 프로퍼티의 키를 포함해야 하며 다른 값은 포함해서는 안 된다.

10.5.12 [[Call]] ( thisArgument, argumentsList )

The [[Call]] internal method of 프록시 이색 객체 obj takes arguments thisArgument (an ECMAScript language value) and argumentsList (a List of ECMAScript language values) and returns either a normal completion containing an ECMAScript language value or a throw completion. It performs the following steps when called:

  1. ValidateNonRevokedProxy(obj)를 수행한다.
  2. targetobj.[[ProxyTarget]]이라고 하자.
  3. handlerobj.[[ProxyHandler]]라고 하자.
  4. Assert: handler는 Object이다.
  5. trap을 ? GetMethod(handler, "apply")라고 하자.
  6. trapundefined이면,
    1. Call(target, thisArgument, argumentsList)를 반환한다.
  7. argArrayCreateArrayFromList(argumentsList)라고 하자.
  8. Call(trap, handler, « target, thisArgument, argArray »)를 반환한다.
Note

프록시 이색 객체는 그 [[ProxyTarget]] 내부 슬롯의 초기값이 [[Call]] 내부 메서드를 가진 객체인 경우에만 [[Call]] 내부 메서드를 가진다.

10.5.13 [[Construct]] ( argumentsList, newTarget )

The [[Construct]] internal method of 프록시 이색 객체 obj takes arguments argumentsList (a List of ECMAScript language values) and newTarget (a constructor) and returns either a normal completion containing an Object or a throw completion. It performs the following steps when called:

  1. ValidateNonRevokedProxy(obj)를 수행한다.
  2. targetobj.[[ProxyTarget]]이라고 하자.
  3. Assert: IsConstructor(target)는 true이다.
  4. handlerobj.[[ProxyHandler]]라고 하자.
  5. Assert: handler는 Object이다.
  6. trap을 ? GetMethod(handler, "construct")라고 하자.
  7. trapundefined이면,
    1. Construct(target, argumentsList, newTarget)를 반환한다.
  8. argArrayCreateArrayFromList(argumentsList)라고 하자.
  9. newObj를 ? Call(trap, handler, « target, argArray, newTarget »)라고 하자.
  10. newObj가 Object가 아니면, TypeError 예외를 던진다.
  11. newObj를 반환한다.
Note 1

프록시 이색 객체는 그 [[ProxyTarget]] 내부 슬롯의 초기값이 [[Construct]] 내부 메서드를 가진 객체인 경우에만 [[Construct]] 내부 메서드를 가진다.

Note 2

프록시 객체에 대한 [[Construct]]는 다음 불변식을 강제한다:

  • [[Construct]]의 결과는 반드시 Object여야 한다.

10.5.14 ValidateNonRevokedProxy ( proxy )

The abstract operation ValidateNonRevokedProxy takes argument proxy (a Proxy exotic object) and returns either a normal completion containing unused or a throw completion. proxy가 revoked되었으면 TypeError 예외를 던진다. It performs the following steps when called:

  1. proxy.[[ProxyTarget]]null이면, TypeError 예외를 던진다.
  2. Assert: proxy.[[ProxyHandler]]null이 아니다.
  3. unused를 반환한다.

10.5.15 ProxyCreate ( target, handler )

The abstract operation ProxyCreate takes arguments target (an ECMAScript language value) and handler (an ECMAScript language value) and returns either a normal completion containing a Proxy exotic object or a throw completion. 이것은 새로운 프록시 객체의 생성을 명세하는 데 사용된다. It performs the following steps when called:

  1. target이 Object가 아니면, TypeError 예외를 던진다.
  2. handler가 Object가 아니면, TypeError 예외를 던진다.
  3. proxyMakeBasicObject[[ProxyHandler]], [[ProxyTarget]] ») 라고 하자.
  4. proxy의 essential 내부 메서드 중 [[Call]][[Construct]]를 제외한 것들을 10.5 에 명시된 정의로 설정한다.
  5. IsCallable(target)가 true이면,
    1. proxy.[[Call]]10.5.12 에 명시된 대로 설정한다.
    2. IsConstructor(target)가 true이면,
      1. proxy.[[Construct]]10.5.13 에 명시된 대로 설정한다.
  6. proxy.[[ProxyTarget]]target으로 설정한다.
  7. proxy.[[ProxyHandler]]handler로 설정한다.
  8. proxy를 반환한다.

11 ECMAScript 언어: 소스 텍스트

11.1 소스 텍스트

구문

SourceCharacter :: 임의의 유니코드 코드 포인트

ECMAScript 소스 텍스트는 유니코드 코드 포인트들의 시퀀스이다. ECMAScript 문법이 허용하는 곳에서는, 서로게이트 코드 포인트를 포함하여 U+0000부터 U+10FFFF까지의 모든 유니코드 코드 포인트 값이 ECMAScript 소스 텍스트에 나타날 수 있다. ECMAScript 소스 텍스트를 저장하고 교환하는 데 사용되는 실제 인코딩은 이 명세와 관련이 없다. 외부 소스 텍스트 인코딩과 관계없이, 적합한 ECMAScript 구현은 소스 텍스트를 마치 동등한 SourceCharacter 값들의 시퀀스인 것처럼 처리하는데, 각 SourceCharacter는 하나의 유니코드 코드 포인트이다. 적합한 ECMAScript 구현은 소스 텍스트에 대해 어떤 정규화도 수행할 필요가 없으며, 마치 소스 텍스트 정규화를 수행하는 것처럼 동작할 필요도 없다.

결합 문자 시퀀스의 구성 요소들은, 사용자가 전체 시퀀스를 하나의 문자로 생각할 수 있더라도, 각각 개별 유니코드 코드 포인트로 취급된다.

Note

문자열 리터럴, 정규식 리터럴, 템플릿 리터럴, 식별자 안에서는, 임의의 유니코드 코드 포인트를 그 코드 포인트의 수치 값을 명시적으로 표현하는 유니코드 이스케이프 시퀀스를 사용해 나타낼 수도 있다. 주석 안에서 그러한 이스케이프 시퀀스는 사실상 주석의 일부로 무시된다.

ECMAScript는 유니코드 이스케이프 시퀀스의 동작에서 자바 프로그래밍 언어와 다르다. 예를 들어 자바 프로그램에서 유니코드 이스케이프 시퀀스 \u000A가 단일 행 주석 안에 나타나면, 그것은 줄 종결자(유니코드 코드 포인트 U+000A는 LINE FEED (LF)이다)로 해석되며, 따라서 다음 코드 포인트는 더 이상 주석의 일부가 아니다. 마찬가지로 자바 프로그램에서 유니코드 이스케이프 시퀀스 \u000A가 문자열 리터럴 안에 나타나면, 역시 줄 종결자로 해석되는데, 이는 문자열 리터럴 안에서는 허용되지 않는다—문자열 리터럴 값의 일부로 LINE FEED (LF)를 포함시키려면 \u000A 대신 \n을 써야 한다. ECMAScript 프로그램에서는 주석 안에 나타난 유니코드 이스케이프 시퀀스는 결코 해석되지 않으므로 주석의 종료에 기여할 수 없다. 마찬가지로 ECMAScript 프로그램에서 문자열 리터럴 안에 나타난 유니코드 이스케이프 시퀀스는 항상 그 리터럴의 일부에 기여하며, 결코 줄 종결자나 문자열 리터럴을 종료시킬 수 있는 코드 포인트로 해석되지 않는다.

11.1.1 Static Semantics: UTF16EncodeCodePoint ( cp )

The abstract operation UTF16EncodeCodePoint takes argument cp (a Unicode code point) and returns a String. It performs the following steps when called:

  1. Assert: 0 ≤ cp ≤ 0x10FFFF.
  2. cp ≤ 0xFFFF이면, 수치 값이 cp인 코드 단위로 이루어진 String 값을 반환한다.
  3. cu1을 수치 값이 floor((cp - 0x10000) / 0x400) + 0xD800인 코드 단위라고 하자.
  4. cu2를 수치 값이 ((cp - 0x10000) modulo 0x400) + 0xDC00인 코드 단위라고 하자.
  5. cu1cu2의 문자열 연결을 반환한다.

11.1.2 Static Semantics: CodePointsToString ( text )

The abstract operation CodePointsToString takes argument text (a sequence of Unicode code points) and returns a String. 이것은 6.1.4에 설명된 대로 text를 String 값으로 변환한다. It performs the following steps when called:

  1. result를 빈 String이라고 하자.
  2. text의 각 코드 포인트 cp에 대해, 다음을 수행한다
    1. resultresultUTF16EncodeCodePoint(cp)의 문자열 연결로 설정한다.
  3. result를 반환한다.

11.1.3 Static Semantics: UTF16SurrogatePairToCodePoint ( lead, trail )

The abstract operation UTF16SurrogatePairToCodePoint takes arguments lead (a code unit) and trail (a code unit) and returns a code point. UTF-16 서로게이트 쌍을 이루는 두 코드 단위는 하나의 코드 포인트로 변환된다. It performs the following steps when called:

  1. Assert: leadleading surrogate이고 trailtrailing surrogate이다.
  2. cp를 (lead - 0xD800) × 0x400 + (trail - 0xDC00) + 0x10000이라고 하자.
  3. 코드 포인트 cp를 반환한다.

11.1.4 Static Semantics: CodePointAt ( string, position )

The abstract operation CodePointAt takes arguments string (a String) and position (a non-negative integer) and returns a Record with fields [[CodePoint]] (a code point), [[CodeUnitCount]] (a positive integer), and [[IsUnpairedSurrogate]] (a Boolean). 이것은 6.1.4에 설명된 대로 string을 UTF-16으로 인코딩된 코드 포인트들의 시퀀스로 해석하고, 인덱스 position의 코드 단위에서 시작하는 하나의 코드 포인트를 읽는다. It performs the following steps when called:

  1. sizestring의 길이라고 하자.
  2. Assert: position ≥ 0 and position < size.
  3. firststring 안의 인덱스 position에 있는 코드 단위라고 하자.
  4. cp를 수치 값이 first의 수치 값인 코드 포인트라고 하자.
  5. firstleading surrogate도 아니고 trailing surrogate도 아니면,
    1. Record { [[CodePoint]]: cp, [[CodeUnitCount]]: 1, [[IsUnpairedSurrogate]]: false }를 반환한다.
  6. firsttrailing surrogate이거나 position + 1 = size이면,
    1. Record { [[CodePoint]]: cp, [[CodeUnitCount]]: 1, [[IsUnpairedSurrogate]]: true }를 반환한다.
  7. secondstring 안의 인덱스 position + 1에 있는 코드 단위라고 하자.
  8. secondtrailing surrogate가 아니면,
    1. Record { [[CodePoint]]: cp, [[CodeUnitCount]]: 1, [[IsUnpairedSurrogate]]: true }를 반환한다.
  9. cpUTF16SurrogatePairToCodePoint(first, second)로 설정한다.
  10. Record { [[CodePoint]]: cp, [[CodeUnitCount]]: 2, [[IsUnpairedSurrogate]]: false }를 반환한다.

11.1.5 Static Semantics: StringToCodePoints ( string )

The abstract operation StringToCodePoints takes argument string (a String) and returns a List of code points. 이것은 6.1.4에 설명된 대로 string을 UTF-16으로 인코딩된 유니코드 텍스트로 해석한 결과 얻어지는 유니코드 코드 포인트들의 시퀀스를 반환한다. It performs the following steps when called:

  1. codePoints를 새로운 빈 List라고 하자.
  2. sizestring의 길이라고 하자.
  3. position을 0이라고 하자.
  4. position < size인 동안, 다음을 반복한다
    1. cpCodePointAt(string, position)라고 하자.
    2. cp.[[CodePoint]]codePoints에 추가한다.
    3. positionposition + cp.[[CodeUnitCount]]로 설정한다.
  5. codePoints를 반환한다.

11.1.6 Static Semantics: ParseText ( sourceText, goalSymbol )

The abstract operation ParseText takes arguments sourceText (a String or a sequence of Unicode code points) and goalSymbol (a nonterminal in one of the ECMAScript grammars) and returns a Parse Node or a non-empty List of SyntaxError objects. It performs the following steps when called:

  1. sourceText가 String이면, sourceTextStringToCodePoints(sourceText)로 설정한다.
  2. goalSymbol을 goal symbol로 사용하여 sourceText를 파싱하려 시도하고, 파싱 결과를 early error 조건에 대해 분석한다. 파싱과 early error 검출은 구현 정의된 방식으로 상호 교차되어 수행될 수 있다.
  3. 파싱이 성공하고 early error가 발견되지 않았다면, 파싱 결과로 생성된 파스 트리의 루트에 있는 Parse Node(goalSymbol의 인스턴스)를 반환한다.
  4. 파싱 오류 및/또는 early error를 나타내는 하나 이상의 SyntaxError 객체의 List를 반환한다. 둘 이상의 파싱 오류 또는 early error가 존재하는 경우, 리스트 안의 오류 객체의 개수와 순서는 구현 정의이지만, 최소 하나는 반드시 존재해야 한다.
Note 1

특정 지점에 early error가 있고, 더 뒤의 지점에 syntax error도 있는 텍스트를 생각해 보자. 먼저 파싱 패스를 수행한 다음 early errors 패스를 수행하는 구현은 syntax error를 보고하고 early errors 패스로 진행하지 않을 수 있다. 두 작업을 상호 교차하여 수행하는 구현은 early error를 보고하고 syntax error를 찾으러 진행하지 않을 수 있다. 세 번째 구현은 두 오류를 모두 보고할 수도 있다. 이 모든 동작은 적합하다.

Note 2

17 절도 보라.

11.2 소스 코드의 종류

ECMAScript 코드에는 네 가지 종류가 있다:

Note 1

함수 코드는 일반적으로 함수 정의(15.2), 화살표 함수 정의(15.3), 메서드 정의(15.4), 제너레이터 함수 정의(15.5), 비동기 함수 정의(15.8), 비동기 제너레이터 함수 정의(15.6), 비동기 화살표 함수(15.9)의 본문으로 제공된다. 함수 코드는 또한 Function 생성자(20.2.1.1), GeneratorFunction 생성자(27.3.1.1), AsyncFunction 생성자(27.7.1.1), AsyncGeneratorFunction 생성자(27.4.1.1)에 대한 인수로부터도 파생된다.

Note 2

BindingIdentifier를 함수 코드에 포함시키는 실질적인 효과는, 둘러싼 코드가 strict mode 코드가 아니더라도, 본문 안에 "use strict" 지시어를 포함하는 함수의 이름인 BindingIdentifier에 대해 strict mode 코드의 Early Error가 적용된다는 점이다.

11.2.1 지시어 프롤로그와 Use Strict 지시어

지시어 프롤로그FunctionBody, ScriptBody, 또는 ModuleBody의 처음 StatementListItem들이나 ModuleItem들로 나타나는 ExpressionStatement들의 가장 긴 시퀀스이며, 그 시퀀스의 각 ExpressionStatement는 전적으로 StringLiteral 토큰 뒤에 세미콜론이 오는 형태로 이루어진다. 세미콜론은 명시적으로 나타날 수도 있고 자동 세미콜론 삽입(12.10)에 의해 삽입될 수도 있다. 지시어 프롤로그는 빈 시퀀스일 수도 있다.

Use Strict 지시어지시어 프롤로그 안의 ExpressionStatement로서, 그 StringLiteral이 정확한 코드 포인트 시퀀스 "use strict" 또는 'use strict' 중 하나인 것이다. Use Strict 지시어EscapeSequenceLineContinuation을 포함할 수 없다.

지시어 프롤로그는 하나 이상의 Use Strict 지시어를 포함할 수 있다. 그러나 이 경우 구현은 경고를 낼 수 있다.

Note

지시어 프롤로그ExpressionStatement들은 그것을 포함하는 production의 평가 중에 정상적으로 평가된다. 구현은 Use Strict 지시어가 아니면서 지시어 프롤로그 안에 나타나는 ExpressionStatement에 대해 구현 특화 의미를 정의할 수 있다. 적절한 알림 메커니즘이 존재한다면, 구현은 Use Strict 지시어가 아니고 구현에 의해 정의된 의미도 가지지 않는 ExpressionStatement지시어 프롤로그 안에서 만나면 경고를 내야 한다.

11.2.2 Strict Mode 코드

ECMAScript 구문 단위는 unrestricted 또는 strict mode 구문 및 의미론(4.3.2)을 사용하여 처리될 수 있다. 코드는 다음 상황에서 strict mode 코드로 해석된다:

strict mode 코드가 아닌 ECMAScript 코드는 non-strict 코드라고 한다.

11.2.2.1 Static Semantics: IsStrict ( node )

The abstract operation IsStrict takes argument node (a Parse Node) and returns a Boolean. It performs the following steps when called:

  1. node에 매칭되는 소스 텍스트가 strict mode 코드이면, true를 반환한다.
  2. false를 반환한다.

11.2.3 비-ECMAScript 함수

ECMAScript 구현은 평가 동작이 ECMAScript 소스 텍스트가 아닌 어떤 호스트 정의 실행 코드 형식으로 표현되는 함수 이색 객체의 평가를 지원할 수 있다. 함수 객체가 ECMAScript 코드 안에서 정의되었는지, 또는 내장 함수인지는, 그러한 함수 객체를 호출하거나 그러한 함수 객체에 의해 호출되는 ECMAScript 코드의 관점에서는 관찰 가능하지 않다.

12 ECMAScript 언어: 어휘 문법

ECMAScript Script 또는 Module의 소스 텍스트는 먼저 입력 요소들의 시퀀스로 변환되며, 이들은 토큰, 줄 종결자, 주석, 또는 공백이다. 소스 텍스트는 왼쪽에서 오른쪽으로 스캔되며, 가능한 한 가장 긴 코드 포인트 시퀀스를 다음 입력 요소로 반복해서 취한다.

어휘 입력 요소의 식별이 입력 요소를 소비하는 구문 문법 문맥에 민감한 여러 상황이 있다. 이 때문에 어휘 문법에는 여러 goal symbol이 필요하다. InputElementHashbangOrRegExp goal은 Script 또는 Module의 시작에서 사용된다. InputElementRegExpOrTemplateTail goal은 RegularExpressionLiteral, TemplateMiddle, 또는 TemplateTail이 허용되는 구문 문법 문맥에서 사용된다. InputElementRegExp goal symbol은 RegularExpressionLiteral은 허용되지만 TemplateMiddleTemplateTail도 허용되지 않는 모든 구문 문법 문맥에서 사용된다. InputElementTemplateTail goal은 TemplateMiddle 또는 TemplateTail은 허용되지만 RegularExpressionLiteral은 허용되지 않는 모든 구문 문법 문맥에서 사용된다. 그 외 모든 문맥에서는 InputElementDiv가 어휘 goal symbol로 사용된다.

Note

여러 어휘 goal을 사용하는 것은 자동 세미콜론 삽입에 영향을 줄 수 있는 어휘적 모호성이 없도록 보장한다. 예를 들어, 선행 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);

구문

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 유니코드 형식 제어 문자

유니코드 형식 제어 문자(즉, LEFT-TO-RIGHT MARK 또는 RIGHT-TO-LEFT MARK와 같은 Unicode Character Database의 “Cf” 범주에 속하는 문자)는, 상위 수준 프로토콜(예: 마크업 언어)이 없는 상황에서 텍스트 범위의 형식을 제어하는 데 사용되는 제어 코드이다.

편집과 표시를 용이하게 하기 위해 소스 텍스트에서 형식 제어 문자를 허용하는 것이 유용하다. 모든 형식 제어 문자는 주석 안에서, 그리고 문자열 리터럴, 템플릿 리터럴, 정규식 리터럴 안에서 사용할 수 있다.

U+FEFF (ZERO WIDTH NO-BREAK SPACE)는 주로 텍스트 시작 부분에서 그것이 Unicode임을 표시하고 텍스트의 인코딩 및 바이트 순서를 감지할 수 있도록 하는 데 사용되는 형식 제어 문자이다. 이런 목적의 <ZWNBSP> 문자는 파일을 연결한 결과처럼 텍스트 시작 뒤에도 나타날 수 있다. ECMAScript 소스 텍스트에서 <ZWNBSP> 코드 포인트는 주석, 문자열 리터럴, 템플릿 리터럴, 정규식 리터럴 바깥에서는 공백 문자로 취급된다(참조: 12.2).

12.2 공백

공백 코드 포인트는 소스 텍스트의 가독성을 높이고 토큰(분해할 수 없는 어휘 단위)들을 서로 분리하는 데 사용되지만, 그 외에는 중요하지 않다. 공백 코드 포인트는 임의의 두 토큰 사이와 입력의 시작 또는 끝에 나타날 수 있다. 공백 코드 포인트는 StringLiteral, RegularExpressionLiteral, Template, 또는 TemplateSubstitutionTail 안에 나타날 수 있으며, 이 경우 리터럴 값의 일부를 이루는 중요한 코드 포인트로 간주된다. 또한 Comment 안에도 나타날 수 있지만, 다른 종류의 토큰 안에는 나타날 수 없다.

ECMAScript 공백 코드 포인트는 Table 30에 나열되어 있다.

Table 30: White Space Code Points
코드 포인트 이름 약어
U+0009 CHARACTER TABULATION <TAB>
U+000B LINE TABULATION <VT>
U+000C FORM FEED (FF) <FF>
U+FEFF ZERO WIDTH NO-BREAK SPACE <ZWNBSP>
general category “Space_Separator”에 속하는 임의의 코드 포인트 <USP>
Note 1

U+0020 (SPACE) 및 U+00A0 (NO-BREAK SPACE) 코드 포인트는 <USP>의 일부이다.

Note 2

Table 30에 나열된 코드 포인트를 제외하면, ECMAScript WhiteSpace는 유니코드 “White_Space” 속성을 가지지만 general category “Space_Separator” (“Zs”)로 분류되지 않는 모든 코드 포인트를 의도적으로 제외한다.

구문

WhiteSpace :: <TAB> <VT> <FF> <ZWNBSP> <USP>

12.3 줄 종결자

공백 코드 포인트와 마찬가지로, 줄 종결자 코드 포인트는 소스 텍스트의 가독성을 높이고 토큰(분해할 수 없는 어휘 단위)들을 서로 분리하는 데 사용된다. 그러나 공백 코드 포인트와 달리, 줄 종결자는 구문 문법의 동작에 어느 정도 영향을 미친다. 일반적으로 줄 종결자는 임의의 두 토큰 사이에 나타날 수 있지만, 구문 문법에 의해 금지되는 몇몇 위치가 있다. 줄 종결자는 자동 세미콜론 삽입 과정에도 영향을 미친다(12.10). 줄 종결자는 StringLiteral, Template, 또는 TemplateSubstitutionTail을 제외한 어떤 토큰 안에도 나타날 수 없다. <LF> 및 <CR> 줄 종결자는 LineContinuation의 일부인 경우를 제외하면 StringLiteral 토큰 안에 나타날 수 없다.

줄 종결자는 MultiLineComment 안에는 나타날 수 있지만 SingleLineComment 안에는 나타날 수 없다.

줄 종결자는 정규식의 \s 클래스가 매치하는 공백 코드 포인트 집합에 포함된다.

ECMAScript 줄 종결자 코드 포인트는 Table 31에 나열되어 있다.

Table 31: Line Terminator Code Points
코드 포인트 유니코드 이름 약어
U+000A LINE FEED (LF) <LF>
U+000D CARRIAGE RETURN (CR) <CR>
U+2028 LINE SEPARATOR <LS>
U+2029 PARAGRAPH SEPARATOR <PS>

Table 31의 유니코드 코드 포인트만 줄 종결자로 취급된다. 다른 새 줄 또는 줄 바꿈 유니코드 코드 포인트는 줄 종결자로 취급되지 않지만, Table 30에 나열된 요구사항을 만족하면 공백으로 취급된다. <CR><LF> 시퀀스는 흔히 줄 종결자로 사용된다. 줄 번호를 보고하는 목적상 이것은 하나의 SourceCharacter로 간주되어야 한다.

구문

LineTerminator :: <LF> <CR> <LS> <PS> LineTerminatorSequence :: <LF> <CR> [lookahead ≠ <LF>] <LS> <PS> <CR> <LF>

12.4 주석

주석은 단일 행 또는 여러 행일 수 있다. 여러 행 주석은 중첩될 수 없다.

단일 행 주석은 LineTerminator 코드 포인트를 제외한 임의의 유니코드 코드 포인트를 포함할 수 있고, 토큰은 항상 가능한 한 길다는 일반 규칙 때문에, 단일 행 주석은 항상 // 표시부터 줄 끝까지의 모든 코드 포인트로 구성된다. 그러나 줄 끝의 LineTerminator는 단일 행 주석의 일부로 간주되지 않으며; 어휘 문법에 의해 별도로 인식되어 구문 문법을 위한 입력 요소 스트림의 일부가 된다. 이 점은 매우 중요한데, 단일 행 주석의 존재 여부가 자동 세미콜론 삽입 과정에 영향을 주지 않음을 의미하기 때문이다(참조: 12.10).

주석은 공백처럼 동작하며 버려지지만, MultiLineComment가 줄 종결자 코드 포인트를 포함하는 경우에는 전체 주석이 구문 문법에 의한 파싱 목적상 LineTerminator로 간주된다.

구문

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

이 절의 여러 production에는 B.1.1 절에서 대체 정의가 제공된다

12.5 Hashbang 주석

Hashbang 주석은 위치에 민감하며, 다른 종류의 주석과 마찬가지로 구문 문법을 위한 입력 요소 스트림에서 버려진다.

구문

HashbangComment :: #! SingleLineCommentCharsopt

12.6 토큰

구문

CommonToken :: IdentifierName PrivateIdentifier Punctuator NumericLiteral StringLiteral Template Note

DivPunctuator, RegularExpressionLiteral, RightBracePunctuator, TemplateSubstitutionTail production은 CommonToken production에 포함되지 않는 추가 토큰을 도출한다.

12.7 이름과 키워드

IdentifierNameReservedWord는, 약간의 수정과 함께 Unicode Standard Annex #31, Identifier and Pattern Syntax에 주어진 Default Identifier Syntax에 따라 해석되는 토큰이다. ReservedWordIdentifierName의 열거된 부분집합이다. 구문 문법은 IdentifierReservedWord가 아닌 IdentifierName으로 정의한다. 유니코드 식별자 문법은 Unicode Standard에 명시된 문자 속성에 기반한다. Unicode Standard 최신 버전에서 지정된 범주에 속하는 유니코드 코드 포인트는 모든 적합한 ECMAScript 구현에서 그 범주에 속하는 것으로 취급되어야 한다. ECMAScript 구현은 Unicode Standard의 더 이후 판에서 정의된 식별자 코드 포인트를 인식할 수 있다.

Note 1

이 표준은 특정 코드 포인트 추가를 명시한다: U+0024 (DOLLAR SIGN)와 U+005F (LOW LINE)는 IdentifierName 어디에서나 허용된다.

구문

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 :: 유니코드 속성 “ID_Start”를 가진 임의의 유니코드 코드 포인트 UnicodeIDContinue :: 유니코드 속성 “ID_Continue”를 가진 임의의 유니코드 코드 포인트

비단말 UnicodeEscapeSequence의 정의는 12.9.4에 주어진다.

Note 2

비단말 IdentifierPartUnicodeIDContinue를 통해 _를 도출한다.

Note 3

유니코드 속성 “ID_Start”와 “ID_Continue”를 가진 코드 포인트 집합은 각각 유니코드 속성 “Other_ID_Start”와 “Other_ID_Continue”를 가진 코드 포인트를 포함한다.

12.7.1 식별자 이름

유니코드 이스케이프 시퀀스는 IdentifierName 안에서 허용되며, 이때 그것들은 UnicodeEscapeSequenceIdentifierCodePoint와 같은 하나의 유니코드 코드 포인트를 기여한다. UnicodeEscapeSequence 앞의 \는 어떤 코드 포인트도 기여하지 않는다. UnicodeEscapeSequence는 그 코드 포인트가 원래는 유효하지 않았을 IdentifierName에 코드 포인트를 기여하는 데 사용할 수 없다. 즉, \ UnicodeEscapeSequence 시퀀스를 그것이 기여하는 SourceCharacter로 대체했을 때, 결과는 여전히 유효한 IdentifierName이어야 하며 원래 IdentifierName와 정확히 같은 SourceCharacter 요소 시퀀스를 가져야 한다. 이 명세 안에서 IdentifierName에 대한 모든 해석은, 특정 코드 포인트를 기여하는 데 이스케이프 시퀀스가 사용되었는지 여부와 관계없이, 그 실제 코드 포인트에 기반한다.

Unicode Standard에 따라 canonical equivalent한 두 IdentifierName은, 각 UnicodeEscapeSequence를 치환한 뒤 정확히 같은 코드 포인트 시퀀스로 표현되지 않는 한, 같지 않다.

12.7.1.1 Static Semantics: Early Errors

IdentifierStart :: \ UnicodeEscapeSequence IdentifierPart :: \ UnicodeEscapeSequence

12.7.1.2 Static Semantics: IdentifierCodePoints

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

IdentifierName :: IdentifierStart
  1. cpIdentifierStartIdentifierCodePoint라고 하자.
  2. « cp »를 반환한다.
IdentifierName :: IdentifierName IdentifierPart
  1. cps를 도출된 IdentifierNameIdentifierCodePoints라고 하자.
  2. cpIdentifierPartIdentifierCodePoint라고 하자.
  3. cps와 « cp »의 list-concatenation을 반환한다.

12.7.1.3 Static Semantics: IdentifierCodePoint

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

IdentifierStart :: IdentifierStartChar
  1. IdentifierStartChar에 매치된 코드 포인트를 반환한다.
IdentifierPart :: IdentifierPartChar
  1. IdentifierPartChar에 매치된 코드 포인트를 반환한다.
UnicodeEscapeSequence :: u Hex4Digits
  1. 수치 값이 Hex4Digits의 MV인 코드 포인트를 반환한다.
UnicodeEscapeSequence :: u{ CodePoint }
  1. 수치 값이 CodePoint의 MV인 코드 포인트를 반환한다.

12.7.2 키워드와 예약어

키워드IdentifierName에 매치되는 토큰이지만, 동시에 구문적 용법도 가진다; 즉, 어떤 구문 production 안에서 fixed width 글꼴로 문자 그대로 나타난다. ECMAScript의 키워드에는 if, while, async, await 등 많은 것들이 포함된다.

예약어는 식별자로 사용할 수 없는 IdentifierName이다. 많은 키워드가 예약어이지만, 일부는 그렇지 않고, 일부는 특정 문맥에서만 예약된다. ifwhile은 예약어이다. await는 async 함수와 모듈 내부에서만 예약된다. async는 예약어가 아니다; 제한 없이 변수 이름이나 문장 라벨로 사용할 수 있다.

이 명세는 문법 production과 early error 규칙의 조합을 사용하여 어떤 이름이 유효한 식별자이고 어떤 이름이 예약어인지 명시한다. 아래 ReservedWord 목록의 모든 토큰은 awaityield를 제외하고는 무조건 예약된다. awaityield에 대한 예외는 13.1에서 매개변수화된 구문 production을 사용하여 명시된다. 마지막으로, 여러 early error 규칙이 유효한 식별자의 집합을 제한한다. 13.1.1, 14.3.1.1, 14.7.5.1, 그리고 15.7.1를 보라. 요약하면, 식별자 이름에는 다섯 가지 범주가 있다:

  • Math, window, toString, _처럼, 항상 식별자로 허용되고 키워드가 아닌 것들;

  • awaityield를 제외한 아래 나열된 ReservedWord들처럼, 절대로 식별자로 허용되지 않는 것들;

  • awaityield처럼, 문맥적으로 식별자로 허용되는 것들;

  • strict mode 코드에서 문맥적으로 식별자로 허용되지 않는 것들: let, static, implements, interface, package, private, protected, public;

  • 항상 식별자로 허용되지만, Identifier가 허용되지 않는 특정 구문 production 안에서는 키워드로도 나타나는 것들: as, async, from, get, meta, of, set, target.

조건부 키워드 또는 문맥 키워드라는 용어는 때때로 마지막 세 범주에 속하는 키워드를 가리키는 데 사용되며, 따라서 어떤 문맥에서는 식별자로, 다른 문맥에서는 키워드로 사용될 수 있다.

구문

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의 early error 규칙은 예약어와 같은 StringValue를 가지는 식별자를 배제한다.

Note 2

enum은 현재 이 명세에서 키워드로 사용되지 않는다. 이것은 미래 언어 확장에서 키워드로 사용하기 위해 남겨둔 미래 예약어이다.

마찬가지로, implements, interface, package, private, protected, publicstrict mode 코드에서 미래 예약어이다.

Note 3

argumentseval이라는 이름은 키워드는 아니지만, strict mode 코드에서는 몇 가지 제한을 받는다. 13.1.1, 8.6.4, 15.2.1, 15.5.1, 15.6.1, 그리고 15.8.1를 보라.

12.8 구두점

구문

Punctuator :: OptionalChainingPunctuator OtherPunctuator OptionalChainingPunctuator :: ?. [lookahead ∉ DecimalDigit] OtherPunctuator :: one of { ( ) [ ] . ... ; , < > <= >= == != === !== + - * % ** ++ -- << >> >>> & | ^ ! ~ && || ?? ? : = += -= *= %= **= <<= >>= >>>= &= |= ^= &&= ||= ??= => DivPunctuator :: / /= RightBracePunctuator :: }

12.9 리터럴

12.9.1 Null 리터럴

구문

NullLiteral :: null

12.9.2 Boolean 리터럴

구문

BooleanLiteral :: true false

12.9.3 숫자 리터럴

구문

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 Static Semantics: Early Errors

NumericLiteral :: LegacyOctalIntegerLiteral DecimalIntegerLiteral :: NonOctalDecimalIntegerLiteral
  • IsStrict(this production)가 true이면 Syntax Error이다.
Note
non-strict 코드에서 이 구문은 레거시이다.

12.9.3.2 Static Semantics: MV

숫자 리터럴은 Number 타입 또는 BigInt 타입의 값을 나타낸다.

12.9.3.3 Static Semantics: NumericValue

The syntax-directed operation NumericValue takes no arguments and returns a Number or a BigInt. It is defined piecewise over the following productions:

NumericLiteral :: DecimalLiteral
  1. RoundMVResult(MV of DecimalLiteral)를 반환한다.
NumericLiteral :: NonDecimalIntegerLiteral
  1. 𝔽(MV of NonDecimalIntegerLiteral)를 반환한다.
NumericLiteral :: LegacyOctalIntegerLiteral
  1. 𝔽(MV of LegacyOctalIntegerLiteral)를 반환한다.
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. nNumericLiteralSeparator의 모든 발생을 제외한 DecimalDigits의 코드 포인트 개수라고 하자.
  2. mv를 (NonZeroDigit의 MV × 10n)에 DecimalDigits의 MV를 더한 값이라고 하자.
  3. (mv)를 반환한다.

12.9.4 문자열 리터럴

Note 1

문자열 리터럴은 작은따옴표 또는 큰따옴표로 둘러싸인 0개 이상의 유니코드 코드 포인트이다. 유니코드 코드 포인트는 이스케이프 시퀀스를 사용해 표현될 수도 있다. 닫는 따옴표 코드 포인트, U+005C (REVERSE SOLIDUS), U+000D (CARRIAGE RETURN), U+000A (LINE FEED)를 제외한 모든 코드 포인트는 문자열 리터럴 안에 문자 그대로 나타날 수 있다. 어떤 코드 포인트든 이스케이프 시퀀스 형태로 나타날 수 있다. 문자열 리터럴은 ECMAScript String 값으로 평가된다. 이 String 값을 생성할 때 유니코드 코드 포인트는 11.1.1에 정의된 대로 UTF-16으로 인코딩된다. Basic Multilingual Plane에 속하는 코드 포인트는 문자열의 하나의 코드 단위 요소로 인코딩된다. 그 외 모든 코드 포인트는 문자열의 두 개 코드 단위 요소로 인코딩된다.

구문

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의 일부인 경우를 제외하고 문자열 리터럴 안에 나타날 수 없다. 문자열 리터럴의 String 값 안에 이들 중 하나를 포함하는 올바른 방법은 \n 또는 \u000A 같은 이스케이프 시퀀스를 사용하는 것이다.

12.9.4.1 Static Semantics: Early Errors

EscapeSequence :: LegacyOctalEscapeSequence NonOctalDecimalEscapeSequence
  • IsStrict(this production)가 true이면 Syntax Error이다.
Note 1
non-strict 코드에서 이 구문은 레거시이다.
Note 2

문자열 리터럴이, 둘러싼 코드를 strict mode로 두는 Use Strict 지시어보다 앞에 올 수도 있으며, 구현은 그러한 리터럴에 대해서도 위 규칙을 강제하도록 주의해야 한다. 예를 들어, 다음 소스 텍스트는 Syntax Error를 포함한다:

function invalid() { "\7"; "use strict"; }

12.9.4.2 Static Semantics: SV

The syntax-directed operation SV takes no arguments and returns a String.

문자열 리터럴은 String 타입의 값을 나타낸다. SV는 문자열 리터럴의 여러 부분에 재귀적으로 적용되어 문자열 리터럴의 String 값을 생성한다. 이 정의 일부로, 문자열 리터럴 안의 일부 유니코드 코드 포인트는 아래 또는 12.9.3에 설명된 대로 수학적 값을 가지는 것으로 해석된다.

Table 32: String Single Character Escape Sequences
이스케이프 시퀀스 코드 단위 값 유니코드 문자 이름 기호
\b 0x0008 BACKSPACE <BS>
\t 0x0009 CHARACTER TABULATION <HT>
\n 0x000A LINE FEED (LF) <LF>
\v 0x000B LINE TABULATION <VT>
\f 0x000C FORM FEED (FF) <FF>
\r 0x000D CARRIAGE RETURN (CR) <CR>
\" 0x0022 QUOTATION MARK "
\' 0x0027 APOSTROPHE '
\\ 0x005C REVERSE SOLIDUS \

12.9.4.3 Static Semantics: MV

12.9.5 정규식 리터럴

Note 1

정규식 리터럴은, 그 리터럴이 평가될 때마다 RegExp 객체(참조: 22.2)로 변환되는 입력 요소이다. 프로그램 안의 두 정규식 리터럴은, 두 리터럴의 내용이 동일하더라도, 서로 ===로 비교해 같아지는 정규식 객체로 평가되지 않는다. RegExp 객체는 new RegExp 또는 RegExp 생성자를 함수로 호출함으로써 런타임에 생성될 수도 있다(참조: 22.2.4).

아래 production은 정규식 리터럴의 구문을 설명하며, 입력 요소 스캐너가 정규식 리터럴의 끝을 찾는 데 사용된다. RegularExpressionBodyRegularExpressionFlags를 구성하는 소스 텍스트는 이후 더 엄격한 ECMAScript 정규식 문법(22.2.1)을 사용하여 다시 파싱된다.

구현은 22.2.1에 정의된 ECMAScript 정규식 문법을 확장할 수 있지만, 아래 정의된 RegularExpressionBodyRegularExpressionFlags production이나 이 production들이 사용하는 production은 확장해서는 안 된다.

구문

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 Static Semantics: BodyText

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

RegularExpressionLiteral :: / RegularExpressionBody / RegularExpressionFlags
  1. RegularExpressionBody로 인식된 소스 텍스트를 반환한다.

12.9.5.2 Static Semantics: FlagText

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

RegularExpressionLiteral :: / RegularExpressionBody / RegularExpressionFlags
  1. RegularExpressionFlags로 인식된 소스 텍스트를 반환한다.

12.9.6 템플릿 리터럴 어휘 구성 요소

구문

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 대체 어휘 goal에 사용된다.

12.9.6.1 Static Semantics: TV

The syntax-directed operation TV takes no arguments and returns a String or undefined. 템플릿 리터럴 구성 요소는 TV에 의해 String 타입의 값으로 해석된다. TV는 템플릿 객체의 인덱스된 구성 요소(구어적으로 템플릿 값)를 구성하는 데 사용된다. TV에서는 이스케이프 시퀀스가 그 이스케이프 시퀀스가 나타내는 유니코드 코드 포인트의 UTF-16 코드 단위(들)로 치환된다.

12.9.6.2 Static Semantics: TRV

The syntax-directed operation TRV takes no arguments and returns a String. 템플릿 리터럴 구성 요소는 TRV에 의해 String 타입의 값으로 해석된다. TRV는 템플릿 객체의 raw 구성 요소(구어적으로 템플릿 raw 값)를 구성하는 데 사용된다. TRV는 TV와 유사하지만, TRV에서는 이스케이프 시퀀스가 리터럴 안에 나타난 그대로 해석된다는 차이가 있다.

Note

TVLineContinuation의 코드 단위를 제외하지만 TRV는 포함한다. <CR><LF> 및 <CR> LineTerminatorSequenceTV와 TRV 모두에서 <LF>로 정규화된다. <CR> 또는 <CR><LF> 시퀀스를 포함하려면 명시적인 TemplateEscapeSequence가 필요하다.

12.10 자동 세미콜론 삽입

대부분의 ECMAScript 문장과 선언은 세미콜론으로 끝나야 한다. 그러한 세미콜론은 언제나 소스 텍스트에 명시적으로 나타날 수 있다. 그러나 편의를 위해, 어떤 상황에서는 그러한 세미콜론을 소스 텍스트에서 생략할 수 있다. 이러한 상황은 그런 경우 소스 코드 토큰 스트림에 세미콜론이 자동으로 삽입된다고 설명된다.

12.10.1 자동 세미콜론 삽입 규칙

다음 규칙에서 “token”은 12 절에 설명된 대로 현재 어휘 goal symbol을 사용하여 결정된 실제 인식된 어휘 토큰을 의미한다.

세미콜론 삽입에는 세 가지 기본 규칙이 있다:

  1. 소스 텍스트를 왼쪽에서 오른쪽으로 파싱할 때, 문법의 어떤 production에도 허용되지 않는 토큰(이를 문제가 되는 토큰이라고 부른다)을 만나면, 다음 조건 중 하나 이상이 참일 경우 문제가 되는 토큰 앞에 세미콜론이 자동으로 삽입된다:

    • 문제가 되는 토큰이 이전 토큰과 적어도 하나의 LineTerminator로 분리되어 있다.
    • 문제가 되는 토큰이 }이다.
    • 이전 토큰이 )이고, 삽입된 세미콜론이 do-while 문(14.7.2)의 종료 세미콜론으로 파싱된다.
  2. 소스 텍스트를 왼쪽에서 오른쪽으로 파싱할 때, 토큰 입력 스트림의 끝에 도달했고 파서가 그 입력 토큰 스트림을 goal 비단말의 단일 인스턴스로 파싱할 수 없으면, 입력 스트림 끝에 세미콜론이 자동으로 삽입된다.
  3. 소스 텍스트를 왼쪽에서 오른쪽으로 파싱할 때, 문법의 어떤 production에는 허용되지만 그 production이 제한된 production이고, 그 토큰이 제한된 production 안에서 “[no LineTerminator here]” 주석 바로 뒤의 terminal 또는 nonterminal에 대한 첫 번째 토큰이 될 경우(따라서 그런 토큰을 제한된 토큰이라 부른다), 그리고 제한된 토큰이 이전 토큰과 적어도 하나의 LineTerminator로 분리되어 있으면, 제한된 토큰 앞에 세미콜론이 자동으로 삽입된다.

그러나 앞선 규칙들에 대한 추가적인 우선 조건이 있다: 그 세미콜론이 빈 문장으로 파싱되거나, 또는 그 세미콜론이 for 문의 헤더 안의 두 세미콜론 중 하나가 된다면(참조: 14.7.4), 세미콜론은 결코 자동으로 삽입되지 않는다.

Note

문법에서 제한된 production은 다음뿐이다:

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]

이러한 제한된 production의 실질적 효과는 다음과 같다:

  • 파서가 ++ 또는 -- 토큰을 후위 연산자로 처리하려는 위치에서 그것을 만났고, 이전 토큰과 ++ 또는 -- 토큰 사이에 적어도 하나의 LineTerminator가 있었다면, ++ 또는 -- 토큰 앞에 세미콜론이 자동으로 삽입된다.
  • continue, break, return, throw, 또는 yield 토큰을 만났고 다음 토큰 전에 LineTerminator를 만나면, continue, break, return, throw, 또는 yield 토큰 뒤에 세미콜론이 자동으로 삽입된다.
  • 화살표 함수의 매개변수 뒤에 => 토큰 전에 LineTerminator가 오면, 세미콜론이 자동으로 삽입되고 그 구두점은 syntax error를 일으킨다.
  • async 토큰 뒤에 function 또는 IdentifierName 또는 ( 토큰 전에 LineTerminator가 오면, 세미콜론이 자동으로 삽입되고 async 토큰은 뒤따르는 토큰들과 같은 표현식 또는 클래스 요소의 일부로 취급되지 않는다.
  • async 토큰 뒤에 * 토큰 전에 LineTerminator가 오면, 세미콜론이 자동으로 삽입되고 그 구두점은 syntax error를 일으킨다.

이에 따른 ECMAScript 프로그래머에 대한 실질적 조언은 다음과 같다:

  • 후위 ++ 또는 -- 연산자는 그 피연산자와 같은 줄에 있어야 한다.
  • return 또는 throw 문 안의 Expression이나 yield 표현식 안의 AssignmentExpressionreturn, throw, 또는 yield 토큰과 같은 줄에서 시작해야 한다.
  • break 또는 continue 문 안의 LabelIdentifierbreak 또는 continue 토큰과 같은 줄에 있어야 한다.
  • 화살표 함수 매개변수의 끝과 그 =>는 같은 줄에 있어야 한다.
  • 비동기 함수 또는 메서드 앞의 async 토큰은 바로 다음 토큰과 같은 줄에 있어야 한다.

12.10.2 자동 세미콜론 삽입의 예

이 절은 비규범적이다.

소스

{ 1 2 } 3

는 자동 세미콜론 삽입 규칙을 적용해도 ECMAScript 문법에서 유효한 문장이 아니다. 반면 소스

{ 1
2 } 3

도 역시 유효한 ECMAScript 문장이 아니지만, 자동 세미콜론 삽입에 의해 다음과 같이 변환된다:

{ 1
;2 ;} 3;

이는 유효한 ECMAScript 문장이다.

소스

for (a; b
)

는 유효한 ECMAScript 문장이 아니며, 세미콜론이 for 문의 헤더에 필요하기 때문에 자동 세미콜론 삽입에 의해 변경되지 않는다. 자동 세미콜론 삽입은 for 문의 헤더에 있는 두 세미콜론 중 어느 것도 결코 삽입하지 않는다.

소스

return
a + b

는 자동 세미콜론 삽입에 의해 다음과 같이 변환된다:

return;
a + b;
Note 1

표현식 a + breturn 문이 반환할 값으로 취급되지 않는데, 그것이 return 토큰과 LineTerminator로 분리되어 있기 때문이다.

소스

a = b
++c

는 자동 세미콜론 삽입에 의해 다음과 같이 변환된다:

a = b;
++c;
Note 2

토큰 ++는 변수 b에 적용되는 후위 연산자로 취급되지 않는데, b++ 사이에 LineTerminator가 있기 때문이다.

소스

if (a > b)
else c = d

는 유효한 ECMAScript 문장이 아니며, 그 지점에서 문법의 어떤 production도 적용되지 않더라도, 자동으로 삽입된 세미콜론이 빈 문장으로 파싱되기 때문에 else 토큰 앞에서 자동 세미콜론 삽입에 의해 변경되지 않는다.

소스

a = b + c
(d + e).print()

는 자동 세미콜론 삽입에 의해 변환되지 않는다. 왜냐하면 두 번째 줄을 시작하는 괄호로 둘러싸인 표현식은 함수 호출의 인수 목록으로 해석될 수 있기 때문이다:

a = b + c(d + e).print()

대입문이 반드시 왼쪽 괄호로 시작해야 하는 상황에서는, 프로그래머가 자동 세미콜론 삽입에 의존하기보다 앞선 문장의 끝에 명시적인 세미콜론을 제공하는 것이 좋다.

12.10.3 자동 세미콜론 삽입의 흥미로운 경우

이 절은 비규범적이다.

ECMAScript 프로그램은 자동 세미콜론 삽입에 의존하여 매우 적은 수의 세미콜론만 사용하는 스타일로 작성될 수 있다. 위에서 설명했듯이, 세미콜론은 모든 개행마다 삽입되는 것이 아니며, 자동 세미콜론 삽입은 줄 종결자를 가로지르는 여러 토큰에 의존할 수 있다.

새로운 구문 기능이 ECMAScript에 추가되면, 그 앞에서 자동 세미콜론 삽입에 의존하던 줄이 파싱될 때 다른 문법 production으로 바뀌게 만드는 추가 문법 production이 추가될 수 있다.

이 절의 목적상, 자동 세미콜론 삽입의 경우는 그것 앞에 오는 소스 텍스트에 따라 세미콜론이 삽입될 수도 있고 안 될 수도 있는 위치라면 흥미로운 것으로 간주된다. 이 절의 나머지는 이 버전의 ECMAScript에서 나타나는 자동 세미콜론 삽입의 여러 흥미로운 경우를 설명한다.

12.10.3.1 문장 목록에서의 자동 세미콜론 삽입의 흥미로운 경우

StatementList 안에서 많은 StatementListItem은 세미콜론으로 끝나며, 이는 자동 세미콜론 삽입을 사용해 생략할 수 있다. 위 규칙의 결과로, 표현식으로 끝나는 줄의 끝에서는 다음 줄이 다음 중 하나로 시작하면 세미콜론이 필요하다:

  • 여는 괄호 ((). 세미콜론이 없으면 두 줄은 함께 CallExpression으로 취급된다.
  • 여는 대괄호 ([). 세미콜론이 없으면 두 줄은 ArrayLiteral 또는 ArrayAssignmentPattern이 아니라 프로퍼티 접근으로 함께 취급된다.
  • 템플릿 리터럴 (`). 세미콜론이 없으면 두 줄은 이전 표현식을 MemberExpression로 하는 태그된 Template(13.3.11)로 함께 해석된다.
  • 단항 + 또는 -. 세미콜론이 없으면 두 줄은 대응하는 이항 연산자의 사용으로 함께 해석된다.
  • RegExp 리터럴. 세미콜론이 없으면 두 줄은 대신 / MultiplicativeOperator로 파싱될 수 있는데, 예를 들어 RegExp에 플래그가 있는 경우 그렇다.

12.10.3.2 자동 세미콜론 삽입과 “[no LineTerminator here]”의 경우

이 절은 비규범적이다.

ECMAScript는 “[no LineTerminator here]”를 포함하는 문법 production을 가진다. 이러한 production은 때때로 문법 안에서 선택적 피연산자를 두기 위한 수단이다. 이런 위치에 LineTerminator를 도입하면 선택적 피연산자가 없는 문법 production을 사용하게 되어 소스 텍스트의 문법 production이 바뀌게 된다.

이 절의 나머지는 이 버전의 ECMAScript에서 “[no LineTerminator here]”를 사용하는 여러 production을 설명한다.

12.10.3.2.1 선택적 피연산자와 “[no LineTerminator here]”를 가진 문법 production 목록

13 ECMAScript 언어: 표현식

13.1 식별자

구문

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 Static Semantics: Early Errors

BindingIdentifier : Identifier IdentifierReference : yield BindingIdentifier : yield LabelIdentifier : yield
  • IsStrict(this production)가 true이면 Syntax Error이다.
IdentifierReference : await BindingIdentifier : await LabelIdentifier : await
  • 구문 문법의 goal symbol이 Module이면 Syntax Error이다.
BindingIdentifier[Yield, Await] : yield
  • 이 production이 [Yield] 매개변수를 가지면 Syntax Error이다.
BindingIdentifier[Yield, Await] : await
  • 이 production이 [Await] 매개변수를 가지면 Syntax Error이다.
IdentifierReference[Yield, Await] : Identifier BindingIdentifier[Yield, Await] : Identifier LabelIdentifier[Yield, Await] : Identifier
  • 이 production이 [Yield] 매개변수를 가지고 IdentifierStringValue"yield"이면 Syntax Error이다.
  • 이 production이 [Await] 매개변수를 가지고 IdentifierStringValue"await"이면 Syntax Error이다.
Identifier : IdentifierName but not ReservedWord Note

IdentifierNameStringValueIdentifierName 안의 모든 유니코드 이스케이프 시퀀스를 정규화하므로, 그런 이스케이프를 사용해서 코드 포인트 시퀀스가 ReservedWord와 같은 Identifier를 작성할 수는 없다.

13.1.2 Static Semantics: StringValue

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

IdentifierName :: IdentifierStart IdentifierName IdentifierPart
  1. idTextUnescapedIdentifierNameIdentifierCodePoints라고 하자.
  2. CodePointsToString(idTextUnescaped)를 반환한다.
IdentifierReference : yield BindingIdentifier : yield LabelIdentifier : yield
  1. "yield"를 반환한다.
IdentifierReference : await BindingIdentifier : await LabelIdentifier : await
  1. "await"를 반환한다.
Identifier : IdentifierName but not ReservedWord
  1. IdentifierNameStringValue를 반환한다.
PrivateIdentifier :: # IdentifierName
  1. 0x0023 (NUMBER SIGN)와 IdentifierNameStringValue의 문자열 연결을 반환한다.
ModuleExportName : StringLiteral
  1. StringLiteralSV를 반환한다.

13.1.3 Runtime Semantics: Evaluation

IdentifierReference : Identifier
  1. ResolveBinding(StringValue of Identifier)를 반환한다.
IdentifierReference : yield
  1. ResolveBinding("yield")를 반환한다.
IdentifierReference : await
  1. ResolveBinding("await")를 반환한다.
Note 1

IdentifierReference를 평가한 결과는 언제나 Reference 타입의 값이다.

Note 2

non-strict 코드에서는 키워드 yield를 식별자로 사용할 수 있다. IdentifierReference를 평가하면 마치 그것이 Identifier인 것처럼 yield의 바인딩을 해석한다. Early Error 제한은 이런 평가가 오직 non-strict 코드에서만 일어날 수 있도록 보장한다.

13.2 기본 표현식

구문

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] )

13.2.1 this 키워드

13.2.1.1 Runtime Semantics: Evaluation

PrimaryExpression : this
  1. ResolveThisBinding()을 반환한다.

13.2.2 식별자 참조

IdentifierReference에 대해서는 13.1를 보라.

13.2.3 리터럴

구문

Literal : NullLiteral BooleanLiteral NumericLiteral StringLiteral

13.2.3.1 Runtime Semantics: Evaluation

Literal : NullLiteral
  1. null을 반환한다.
Literal : BooleanLiteral
  1. BooleanLiteral이 토큰 false이면, false를 반환한다.
  2. BooleanLiteral이 토큰 true이면, true를 반환한다.
Literal : NumericLiteral
  1. 12.9.3에 정의된 NumericLiteralNumericValue를 반환한다.
Literal : StringLiteral
  1. 12.9.4.2에 정의된 StringLiteralSV를 반환한다.

13.2.4 배열 초기자

Note

ArrayLiteral은 대괄호로 둘러싸인, 0개 이상의 표현식 목록을 사용하여 Array의 초기화를 기술하는 표현식이며, 각 표현식은 배열 요소를 나타낸다. 요소는 리터럴일 필요가 없으며; 배열 초기자가 평가될 때마다 각각 평가된다.

배열 요소는 요소 목록의 처음, 중간, 또는 끝에서 생략될 수 있다. 요소 목록에서 콤마 앞에 AssignmentExpression이 없을 때마다(즉, 처음의 콤마이거나 다른 콤마 뒤의 콤마인 경우), 빠진 배열 요소는 Array의 길이에 기여하고 이후 요소들의 인덱스를 증가시킨다. 생략된 배열 요소는 정의되지 않는다. 배열 끝에서 요소가 생략되면, 그 요소는 Array의 길이에 기여하지 않는다.

구문

ArrayLiteral[Yield, Await] : [ Elisionopt ] [ ElementList[?Yield, ?Await] ] [ ElementList[?Yield, ?Await] , Elisionopt ] ElementList[Yield, Await] : Elisionopt AssignmentExpression[+In, ?Yield, ?Await] Elisionopt SpreadElement[?Yield, ?Await] ElementList[?Yield, ?Await] , Elisionopt AssignmentExpression[+In, ?Yield, ?Await] ElementList[?Yield, ?Await] , Elisionopt SpreadElement[?Yield, ?Await] Elision : , Elision , SpreadElement[Yield, Await] : ... AssignmentExpression[+In, ?Yield, ?Await]

13.2.4.1 Runtime Semantics: ArrayAccumulation

The syntax-directed operation ArrayAccumulation takes arguments array (an Array) and nextIndex (an integer) and returns either a normal completion containing an integer or an abrupt completion. It is defined piecewise over the following productions:

Elision : ,
  1. lennextIndex + 1이라고 하자.
  2. Set(array, "length", 𝔽(len), true)를 수행한다.
  3. NOTE: 위 단계는 len이 232 - 1을 초과하면 예외를 던진다.
  4. len을 반환한다.
Elision : Elision ,
  1. 인수 array와 (nextIndex + 1)을 사용한 ElisionArrayAccumulation을 ? 반환한다.
ElementList : Elisionopt AssignmentExpression
  1. Elision이 존재하면,
    1. nextIndex를 인수 arraynextIndex를 사용한 ElisionArrayAccumulation 결과 ?로 설정한다.
  2. initResultAssignmentExpressionEvaluation 결과 ?라고 하자.
  3. initValue를 ? GetValue(initResult)라고 하자.
  4. CreateDataPropertyOrThrow(array, ! ToString(𝔽(nextIndex)), initValue)를 수행한다.
  5. nextIndex + 1을 반환한다.
ElementList : Elisionopt SpreadElement
  1. Elision이 존재하면,
    1. nextIndex를 인수 arraynextIndex를 사용한 ElisionArrayAccumulation 결과 ?로 설정한다.
  2. 인수 arraynextIndex를 사용한 SpreadElementArrayAccumulation을 ? 반환한다.
ElementList : ElementList , Elisionopt AssignmentExpression
  1. nextIndex를 인수 arraynextIndex를 사용한 도출된 ElementListArrayAccumulation 결과 ?로 설정한다.
  2. Elision이 존재하면,
    1. nextIndex를 인수 arraynextIndex를 사용한 ElisionArrayAccumulation 결과 ?로 설정한다.
  3. initResultAssignmentExpressionEvaluation 결과 ?라고 하자.
  4. initValue를 ? GetValue(initResult)라고 하자.
  5. CreateDataPropertyOrThrow(array, ! ToString(𝔽(nextIndex)), initValue)를 수행한다.
  6. nextIndex + 1을 반환한다.
ElementList : ElementList , Elisionopt SpreadElement
  1. nextIndex를 인수 arraynextIndex를 사용한 도출된 ElementListArrayAccumulation 결과 ?로 설정한다.
  2. Elision이 존재하면,
    1. nextIndex를 인수 arraynextIndex를 사용한 ElisionArrayAccumulation 결과 ?로 설정한다.
  3. 인수 arraynextIndex를 사용한 SpreadElementArrayAccumulation을 ? 반환한다.
SpreadElement : ... AssignmentExpression
  1. spreadRefAssignmentExpressionEvaluation 결과 ?라고 하자.
  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 Runtime Semantics: Evaluation

ArrayLiteral : [ Elisionopt ]
  1. array를 ! ArrayCreate(0)라고 하자.
  2. Elision이 존재하면,
    1. 인수 array와 0을 사용한 ElisionArrayAccumulation을 ? 수행한다.
  3. array를 반환한다.
ArrayLiteral : [ ElementList ]
  1. array를 ! ArrayCreate(0)라고 하자.
  2. 인수 array와 0을 사용한 ElementListArrayAccumulation을 ? 수행한다.
  3. array를 반환한다.
ArrayLiteral : [ ElementList , Elisionopt ]
  1. array를 ! ArrayCreate(0)라고 하자.
  2. nextIndex를 인수 array와 0을 사용한 ElementListArrayAccumulation 결과 ?라고 하자.
  3. Elision이 존재하면,
    1. 인수 arraynextIndex를 사용한 ElisionArrayAccumulation을 ? 수행한다.
  4. array를 반환한다.

13.2.5 객체 초기자

Note 1

객체 초기자는 리터럴과 유사한 형태로 작성된, Object의 초기화를 기술하는 표현식이다. 이것은 중괄호로 둘러싸인, 0개 이상의 프로퍼티 키와 연관된 값의 쌍 목록이다. 값은 리터럴일 필요가 없으며; 객체 초기자가 평가될 때마다 각각 평가된다.

구문

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차 문법을 위한 커버 문법으로 사용된다. CoverInitializedName production은 이 2차 문법들을 완전히 덮기 위해 필요하다. 그러나 이 production을 사용하면 실제 ObjectLiteral이 기대되는 일반 문맥에서는 이른 Syntax Error가 발생한다.

13.2.5.1 Static Semantics: Early Errors

PropertyDefinition : MethodDefinition

실제 객체 초기자를 기술하는 것 외에도 ObjectLiteral production은 ObjectAssignmentPattern을 위한 커버 문법으로도 사용되며 CoverParenthesizedExpressionAndArrowParameterList의 일부로 인식될 수 있다. ObjectLiteralObjectAssignmentPattern이 필요한 문맥에 나타날 때는 다음 Early Error 규칙이 적용되지 않는다. 또한 CoverParenthesizedExpressionAndArrowParameterList 또는 CoverCallExpressionAndAsyncArrowHead를 처음 파싱할 때에도 적용되지 않는다.

PropertyDefinition : CoverInitializedName
  • 이 production에 의해 어떤 소스 텍스트라도 매치되면 Syntax Error이다.
Note 1

이 production은 ObjectLiteralObjectAssignmentPattern의 커버 문법 역할을 할 수 있도록 존재한다. 실제 객체 초기자에서는 나타날 수 없다.

ObjectLiteral : { PropertyDefinitionList } { PropertyDefinitionList , } Note 2

PropertyNameList가 반환하는 ListComputedPropertyName을 사용해 정의된 프로퍼티 이름을 포함하지 않는다.

13.2.5.2 Static Semantics: IsComputedPropertyKey

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

PropertyName : LiteralPropertyName
  1. false를 반환한다.
PropertyName : ComputedPropertyName
  1. true를 반환한다.

13.2.5.3 Static Semantics: PropertyDefinitionNodes

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

ObjectLiteral : { }
  1. 새로운 빈 List를 반환한다.
PropertyDefinitionList : PropertyDefinition
  1. « PropertyDefinition »를 반환한다.
PropertyDefinitionList : PropertyDefinitionList , PropertyDefinition
  1. head를 도출된 PropertyDefinitionListPropertyDefinitionNodes라고 하자.
  2. head와 « PropertyDefinition »의 list-concatenation을 반환한다.

13.2.5.4 Static Semantics: PropertyNameList

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

PropertyDefinitionList : PropertyDefinition
  1. propNamePropertyDefinitionPropName이라고 하자.
  2. propNameempty이면, 새로운 빈 List를 반환한다.
  3. « propName »를 반환한다.
PropertyDefinitionList : PropertyDefinitionList , PropertyDefinition
  1. listPropertyDefinitionListPropertyNameList라고 하자.
  2. propNamePropertyDefinitionPropName이라고 하자.
  3. propNameempty이면, list를 반환한다.
  4. list와 « propName »의 list-concatenation을 반환한다.

13.2.5.5 Runtime Semantics: Evaluation

ObjectLiteral : { }
  1. OrdinaryObjectCreate(%Object.prototype%)를 반환한다.
ObjectLiteral : { PropertyDefinitionList } { PropertyDefinitionList , }
  1. objOrdinaryObjectCreate(%Object.prototype%)라고 하자.
  2. 인수 obj를 사용한 PropertyDefinitionListPropertyDefinitionEvaluation을 ? 수행한다.
  3. obj를 반환한다.
LiteralPropertyName : IdentifierName
  1. IdentifierNameStringValue를 반환한다.
LiteralPropertyName : StringLiteral
  1. StringLiteralSV를 반환한다.
LiteralPropertyName : NumericLiteral
  1. nbrNumericLiteralNumericValue라고 하자.
  2. ToString(nbr)를 반환한다.
ComputedPropertyName : [ AssignmentExpression ]
  1. exprValueAssignmentExpressionEvaluation 결과 ?라고 하자.
  2. propName을 ? GetValue(exprValue)라고 하자.
  3. ToPropertyKey(propName)를 반환한다.

13.2.5.6 Runtime Semantics: PropertyDefinitionEvaluation

The syntax-directed operation PropertyDefinitionEvaluation takes argument object (an Object) and returns either a normal completion containing unused or an abrupt completion. It is defined piecewise over the following productions:

PropertyDefinitionList : PropertyDefinitionList , PropertyDefinition
  1. 인수 object를 사용한 PropertyDefinitionListPropertyDefinitionEvaluation을 ? 수행한다.
  2. 인수 object를 사용한 PropertyDefinitionPropertyDefinitionEvaluation을 ? 수행한다.
  3. unused를 반환한다.
PropertyDefinition : ... AssignmentExpression
  1. exprValueAssignmentExpressionEvaluation 결과 ?라고 하자.
  2. fromValue를 ? GetValue(exprValue)라고 하자.
  3. excludedNames를 새로운 빈 List라고 하자.
  4. CopyDataProperties(object, fromValue, excludedNames)를 수행한다.
  5. unused를 반환한다.
PropertyDefinition : IdentifierReference
  1. propNameIdentifierReferenceStringValue라고 하자.
  2. exprValueIdentifierReferenceEvaluation 결과 ?라고 하자.
  3. propValue를 ? GetValue(exprValue)라고 하자.
  4. Assert: object는 non-configurable 프로퍼티가 없는 일반적이고 확장 가능한 객체이다.
  5. CreateDataPropertyOrThrow(object, propName, propValue)를 수행한다.
  6. unused를 반환한다.
PropertyDefinition : PropertyName : AssignmentExpression
  1. propertyKeyPropertyNameEvaluation 결과 ?라고 하자.
  2. PropertyDefinitionParseJSON의 평가를 위해 평가되는 Script 안에 포함된 경우라면(참조: ParseJSON의 단계 6),
    1. isProtoSetterfalse라고 하자.
  3. 그렇지 않고 propertyKey"__proto__"이며 PropertyNameIsComputedPropertyKeyfalse이면,
    1. isProtoSettertrue라고 하자.
  4. 그렇지 않으면,
    1. isProtoSetterfalse라고 하자.
  5. IsAnonymousFunctionDefinition(AssignmentExpression)이 true이고 isProtoSetterfalse이면,
    1. propValue를 인수 propertyKey를 사용한 AssignmentExpressionNamedEvaluation 결과 ?라고 하자.
  6. 그렇지 않으면,
    1. exprValueRefAssignmentExpressionEvaluation 결과 ?라고 하자.
    2. propValue를 ? GetValue(exprValueRef)라고 하자.
  7. isProtoSettertrue이면,
    1. propValue가 Object이거나 propValuenull이면,
      1. object.[[SetPrototypeOf]](propValue)를 수행한다.
    2. unused를 반환한다.
  8. Assert: object는 non-configurable 프로퍼티가 없는 일반적이고 확장 가능한 객체이다.
  9. CreateDataPropertyOrThrow(object, propertyKey, propValue)를 수행한다.
  10. unused를 반환한다.
PropertyDefinition : MethodDefinition
  1. 인수 objecttrue를 사용한 MethodDefinitionMethodDefinitionEvaluation을 ? 수행한다.
  2. unused를 반환한다.

13.2.6 함수 정의 표현식

PrimaryExpression : FunctionExpression 에 대해서는 15.2를 보라.

PrimaryExpression : GeneratorExpression 에 대해서는 15.5를 보라.

PrimaryExpression : ClassExpression 에 대해서는 15.7를 보라.

PrimaryExpression : AsyncFunctionExpression 에 대해서는 15.8를 보라.

PrimaryExpression : AsyncGeneratorExpression 에 대해서는 15.6를 보라.

13.2.7 정규식 리터럴

구문

12.9.5를 보라.

13.2.7.1 Static Semantics: Early Errors

PrimaryExpression : RegularExpressionLiteral

13.2.7.2 Static Semantics: IsValidRegularExpressionLiteral ( literal )

The abstract operation IsValidRegularExpressionLiteral takes argument literal (a RegularExpressionLiteral Parse Node) and returns a Boolean. 이것은 인수가 유효한 정규식 리터럴인지 결정한다. It performs the following steps when called:

  1. flagsliteralFlagText라고 하자.
  2. flagsd, g, i, m, s, u, v, y 이외의 코드 포인트를 하나라도 포함하면 false를 반환한다.
  3. flags가 어떤 코드 포인트든 두 번 이상 포함하면 false를 반환한다.
  4. flagsu를 포함하면 utrue로 하자; 그렇지 않으면 ufalse로 하자.
  5. flagsv를 포함하면 vtrue로 하자; 그렇지 않으면 vfalse로 하자.
  6. patternTextliteralBodyText라고 하자.
  7. ufalse이고 vfalse이면,
    1. stringValueCodePointsToString(patternText)라고 하자.
    2. patternTextstringValue의 각 16비트 요소를 유니코드 BMP 코드 포인트로 해석한 결과의 코드 포인트 시퀀스로 설정한다. 요소들에는 UTF-16 디코딩이 적용되지 않는다.
  8. parseResultParsePattern(patternText, u, v)라고 하자.
  9. parseResult가 Parse Node이면 true를 반환한다.
  10. false를 반환한다.

13.2.7.3 Runtime Semantics: Evaluation

PrimaryExpression : RegularExpressionLiteral
  1. patternCodePointsToString(BodyText of RegularExpressionLiteral)라고 하자.
  2. flagsCodePointsToString(FlagText of RegularExpressionLiteral)라고 하자.
  3. RegExpCreate(pattern, flags)를 반환한다.

13.2.8 템플릿 리터럴

구문

TemplateLiteral[Yield, Await, Tagged] : NoSubstitutionTemplate SubstitutionTemplate[?Yield, ?Await, ?Tagged] SubstitutionTemplate[Yield, Await, Tagged] : TemplateHead Expression[+In, ?Yield, ?Await] TemplateSpans[?Yield, ?Await, ?Tagged] TemplateSpans[Yield, Await, Tagged] : TemplateTail TemplateMiddleList[?Yield, ?Await, ?Tagged] TemplateTail TemplateMiddleList[Yield, Await, Tagged] : TemplateMiddle Expression[+In, ?Yield, ?Await] TemplateMiddleList[?Yield, ?Await, ?Tagged] TemplateMiddle Expression[+In, ?Yield, ?Await]

13.2.8.1 Static Semantics: Early Errors

TemplateLiteral[Yield, Await, Tagged] : NoSubstitutionTemplate TemplateLiteral[Yield, Await, Tagged] : SubstitutionTemplate[?Yield, ?Await, ?Tagged] SubstitutionTemplate[Yield, Await, Tagged] : TemplateHead Expression[+In, ?Yield, ?Await] TemplateSpans[?Yield, ?Await, ?Tagged] TemplateSpans[Yield, Await, Tagged] : TemplateTail TemplateMiddleList[Yield, Await, Tagged] : TemplateMiddle Expression[+In, ?Yield, ?Await] TemplateMiddleList[?Yield, ?Await, ?Tagged] TemplateMiddle Expression[+In, ?Yield, ?Await]

13.2.8.2 Static Semantics: TemplateStrings

The syntax-directed operation TemplateStrings takes argument raw (a Boolean) and returns a List of either Strings or undefined. It is defined piecewise over the following productions:

TemplateLiteral : NoSubstitutionTemplate
  1. « TemplateString(NoSubstitutionTemplate, raw) »를 반환한다.
SubstitutionTemplate : TemplateHead Expression TemplateSpans
  1. head를 « TemplateString(TemplateHead, raw) »라고 하자.
  2. tail을 인수 raw를 사용한 TemplateSpansTemplateStrings라고 하자.
  3. headtaillist-concatenation을 반환한다.
TemplateSpans : TemplateTail
  1. « TemplateString(TemplateTail, raw) »를 반환한다.
TemplateSpans : TemplateMiddleList TemplateTail
  1. middle을 인수 raw를 사용한 TemplateMiddleListTemplateStrings라고 하자.
  2. tail을 « TemplateString(TemplateTail, raw) »라고 하자.
  3. middletaillist-concatenation을 반환한다.
TemplateMiddleList : TemplateMiddle Expression
  1. « TemplateString(TemplateMiddle, raw) »를 반환한다.
TemplateMiddleList : TemplateMiddleList TemplateMiddle Expression
  1. front를 인수 raw를 사용한 TemplateMiddleListTemplateStrings라고 하자.
  2. last를 « TemplateString(TemplateMiddle, raw) »라고 하자.
  3. frontlastlist-concatenation을 반환한다.

13.2.8.3 Static Semantics: TemplateString ( templateToken, raw )

The abstract operation TemplateString takes arguments templateToken (a NoSubstitutionTemplate Parse Node, a TemplateHead Parse Node, a TemplateMiddle Parse Node, or a TemplateTail Parse Node) and raw (a Boolean) and returns a String or undefined. It performs the following steps when called:

  1. rawtrue이면,
    1. stringtemplateTokenTRV라고 하자.
  2. 그렇지 않으면,
    1. stringtemplateTokenTV라고 하자.
  3. string을 반환한다.
Note

이 연산은 rawfalse이고 templateTokenNotEscapeSequence를 포함하면 undefined를 반환한다. 그 외 모든 경우에는 String을 반환한다.

13.2.8.4 GetTemplateObject ( templateLiteral )

The abstract operation GetTemplateObject takes argument templateLiteral (a Parse Node) and returns an Array. It performs the following steps when called:

  1. realm을 현재 Realm Record라고 하자.
  2. templateRegistryrealm.[[TemplateMap]]라고 하자.
  3. templateRegistry의 각 요소 e에 대해, 다음을 수행한다
    1. e.[[Site]]templateLiteral과 같은 Parse Node이면,
      1. e.[[Array]]를 반환한다.
  4. rawStrings를 인수 true를 사용한 templateLiteralTemplateStrings라고 하자.
  5. Assert: rawStrings는 Strings의 List이다.
  6. cookedStrings를 인수 false를 사용한 templateLiteralTemplateStrings라고 하자.
  7. countList cookedStrings의 요소 개수라고 하자.
  8. Assert: count ≤ 232 - 1.
  9. template를 ! ArrayCreate(count)라고 하자.
  10. rawObj를 ! ArrayCreate(count)라고 하자.
  11. index를 0이라고 하자.
  12. index < count인 동안, 다음을 반복한다
    1. propertyKey를 ! ToString(𝔽(index))라고 하자.
    2. cookedValuecookedStrings[index]라고 하자.
    3. DefinePropertyOrThrow(template, propertyKey, PropertyDescriptor { [[Value]]: cookedValue, [[Writable]]: false, [[Enumerable]]: true, [[Configurable]]: false })를 수행한다.
    4. rawValue를 String 값 rawStrings[index]라고 하자.
    5. DefinePropertyOrThrow(rawObj, propertyKey, PropertyDescriptor { [[Value]]: rawValue, [[Writable]]: false, [[Enumerable]]: true, [[Configurable]]: false })를 수행한다.
    6. indexindex + 1로 설정한다.
  13. SetIntegrityLevel(rawObj, frozen)를 수행한다.
  14. DefinePropertyOrThrow(template, "raw", PropertyDescriptor { [[Value]]: rawObj, [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false })를 수행한다.
  15. SetIntegrityLevel(template, frozen)를 수행한다.
  16. Record { [[Site]]: templateLiteral, [[Array]]: template }를 realm.[[TemplateMap]]에 추가한다.
  17. template를 반환한다.
Note 1

템플릿 객체의 생성은 abrupt completion을 발생시킬 수 없다.

Note 2

realm의 프로그램 코드 안의 각 TemplateLiteral은 태그된 Template의 평가(13.2.8.6)에 사용되는 고유한 템플릿 객체와 연관된다. 템플릿 객체는 동결되며, 특정 태그된 Template가 평가될 때마다 같은 템플릿 객체가 사용된다. 템플릿 객체가 TemplateLiteral의 첫 평가 시점에 지연 생성되는지, 또는 첫 평가 전에 미리 생성되는지는 ECMAScript 코드에서 관찰할 수 없는 구현 선택이다.

Note 3

이 명세의 미래 판은 템플릿 객체의 추가적인 non-enumerable 프로퍼티를 정의할 수 있다.

13.2.8.5 Runtime Semantics: SubstitutionEvaluation

The syntax-directed operation SubstitutionEvaluation takes no arguments and returns either a normal completion containing a List of ECMAScript language values or an abrupt completion. It is defined piecewise over the following productions:

TemplateSpans : TemplateTail
  1. 새로운 빈 List를 반환한다.
TemplateSpans : TemplateMiddleList TemplateTail
  1. TemplateMiddleListSubstitutionEvaluation을 ? 반환한다.
TemplateMiddleList : TemplateMiddle Expression
  1. subRefExpressionEvaluation 결과 ?라고 하자.
  2. sub를 ? GetValue(subRef)라고 하자.
  3. « sub »를 반환한다.
TemplateMiddleList : TemplateMiddleList TemplateMiddle Expression
  1. precedingTemplateMiddleListSubstitutionEvaluation 결과 ?라고 하자.
  2. nextRefExpressionEvaluation 결과 ?라고 하자.
  3. next를 ? GetValue(nextRef)라고 하자.
  4. preceding과 « next »의 list-concatenation을 반환한다.

13.2.8.6 Runtime Semantics: Evaluation

TemplateLiteral : NoSubstitutionTemplate
  1. 12.9.6에 정의된 NoSubstitutionTemplateTV를 반환한다.
SubstitutionTemplate : TemplateHead Expression TemplateSpans
  1. head12.9.6에 정의된 TemplateHeadTV라고 하자.
  2. subRefExpressionEvaluation 결과 ?라고 하자.
  3. sub를 ? GetValue(subRef)라고 하자.
  4. middle을 ? ToString(sub)라고 하자.
  5. tailTemplateSpansEvaluation 결과 ?라고 하자.
  6. head, middle, tail의 문자열 연결을 반환한다.
Note 1

Expression 값에 적용되는 문자열 변환 의미론은 + 연산자라기보다 String.prototype.concat과 같다.

TemplateSpans : TemplateTail
  1. 12.9.6에 정의된 TemplateTailTV를 반환한다.
TemplateSpans : TemplateMiddleList TemplateTail
  1. headTemplateMiddleListEvaluation 결과 ?라고 하자.
  2. tail12.9.6에 정의된 TemplateTailTV라고 하자.
  3. headtail의 문자열 연결을 반환한다.
TemplateMiddleList : TemplateMiddle Expression
  1. head12.9.6에 정의된 TemplateMiddleTV라고 하자.
  2. subRefExpressionEvaluation 결과 ?라고 하자.
  3. sub를 ? GetValue(subRef)라고 하자.
  4. middle을 ? ToString(sub)라고 하자.
  5. headmiddle의 문자열 연결을 반환한다.
Note 2

Expression 값에 적용되는 문자열 변환 의미론은 + 연산자라기보다 String.prototype.concat과 같다.

TemplateMiddleList : TemplateMiddleList TemplateMiddle Expression
  1. restTemplateMiddleListEvaluation 결과 ?라고 하자.
  2. middle12.9.6에 정의된 TemplateMiddleTV라고 하자.
  3. subRefExpressionEvaluation 결과 ?라고 하자.
  4. sub를 ? GetValue(subRef)라고 하자.
  5. last를 ? ToString(sub)라고 하자.
  6. rest, middle, last의 문자열 연결을 반환한다.
Note 3

Expression 값에 적용되는 문자열 변환 의미론은 + 연산자라기보다 String.prototype.concat과 같다.

13.2.9 그룹화 연산자

13.2.9.1 Static Semantics: Early Errors

PrimaryExpression : CoverParenthesizedExpressionAndArrowParameterList

13.2.9.2 Runtime Semantics: Evaluation

PrimaryExpression : CoverParenthesizedExpressionAndArrowParameterList
  1. exprCoverParenthesizedExpressionAndArrowParameterList이 커버하는 ParenthesizedExpression이라고 하자.
  2. exprEvaluation을 ? 반환한다.
ParenthesizedExpression : ( Expression )
  1. ExpressionEvaluation을 ? 반환한다. 이것은 Reference 타입일 수 있다.
Note

이 알고리즘은 ExpressionEvaluationGetValue를 적용하지 않는다. 그 주된 동기는 deletetypeof 같은 연산자가 괄호로 둘러싸인 표현식에 적용될 수 있도록 하기 위해서이다.

13.3 좌변 표현식

구문

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]

보충 구문

production의 인스턴스를 처리할 때
CallExpression : CoverCallExpressionAndAsyncArrowHead
CoverCallExpressionAndAsyncArrowHead의 해석은 다음 문법을 사용하여 정제된다:

CallMemberExpression[Yield, Await] : MemberExpression[?Yield, ?Await] Arguments[?Yield, ?Await]

13.3.1 Static Semantics

13.3.1.1 Static Semantics: Early Errors

OptionalChain : ?. TemplateLiteral OptionalChain TemplateLiteral
  • 이 production에 의해 어떤 소스 텍스트라도 매치되면 Syntax Error이다.
Note

이 production은 자동 세미콜론 삽입 규칙(12.10)이 다음 코드에 적용되는 것을 막기 위해 존재한다:

a?.b
`c`

그 결과 이것이 두 개의 유효한 문장으로 해석되지 않도록 하기 위함이다. 목적은 optional chaining이 없는 유사한 코드와의 일관성을 유지하는 것이다:

a.b
`c`

이것은 유효한 문장이며 자동 세미콜론 삽입이 적용되지 않는다.

ImportMeta : import . meta
  • 구문 goal symbol이 Module이 아니면 Syntax Error이다.

13.3.2 프로퍼티 접근자

Note

프로퍼티는 이름으로 접근되며, 점 표기법을 사용하거나:

또는 대괄호 표기법을 사용한다:

점 표기법은 다음 구문 변환으로 설명된다:

은 동작상 다음과 동일하다

MemberExpression [ <identifier-name-string> ]

그리고 마찬가지로

은 동작상 다음과 동일하다

CallExpression [ <identifier-name-string> ]

여기서 <identifier-name-string>는 IdentifierNameStringValue이다.

13.3.2.1 Runtime Semantics: Evaluation

MemberExpression : MemberExpression [ Expression ]
  1. baseReferenceMemberExpressionEvaluation 결과 ?라고 하자.
  2. baseValue를 ? GetValue(baseReference)라고 하자.
  3. strict를 this MemberExpressionIsStrict라고 하자.
  4. 인수 baseValue, Expression, strict를 사용하여 ? EvaluatePropertyAccessWithExpressionKey를 반환한다.
MemberExpression : MemberExpression . IdentifierName
  1. baseReferenceMemberExpressionEvaluation 결과 ?라고 하자.
  2. baseValue를 ? GetValue(baseReference)라고 하자.
  3. strict를 this MemberExpressionIsStrict라고 하자.
  4. EvaluatePropertyAccessWithIdentifierKey(baseValue, IdentifierName, strict)를 반환한다.
MemberExpression : MemberExpression . PrivateIdentifier
  1. baseReferenceMemberExpressionEvaluation 결과 ?라고 하자.
  2. baseValue를 ? GetValue(baseReference)라고 하자.
  3. fieldNameStringPrivateIdentifierStringValue라고 하자.
  4. MakePrivateReference(baseValue, fieldNameString)를 반환한다.
CallExpression : CallExpression [ Expression ]
  1. baseReferenceCallExpressionEvaluation 결과 ?라고 하자.
  2. baseValue를 ? GetValue(baseReference)라고 하자.
  3. strict를 this CallExpressionIsStrict라고 하자.
  4. 인수 baseValue, Expression, strict를 사용하여 ? EvaluatePropertyAccessWithExpressionKey를 반환한다.
CallExpression : CallExpression . IdentifierName
  1. baseReferenceCallExpressionEvaluation 결과 ?라고 하자.
  2. baseValue를 ? GetValue(baseReference)라고 하자.
  3. strict를 this CallExpressionIsStrict라고 하자.
  4. EvaluatePropertyAccessWithIdentifierKey(baseValue, IdentifierName, strict)를 반환한다.
CallExpression : CallExpression . PrivateIdentifier
  1. baseReferenceCallExpressionEvaluation 결과 ?라고 하자.
  2. baseValue를 ? GetValue(baseReference)라고 하자.
  3. fieldNameStringPrivateIdentifierStringValue라고 하자.
  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 either a normal completion containing a Reference Record or an abrupt completion. It performs the following steps when called:

  1. propertyNameReferenceexpressionEvaluation 결과 ?라고 하자.
  2. propertyNameValue를 ? GetValue(propertyNameReference)라고 하자.
  3. NOTE: 대부분의 경우, 이 단계 직후 propertyNameValueToPropertyKey가 수행된다. 그러나 a[b] = c의 경우에는 c의 평가 이후까지 수행되지 않는다.
  4. Reference Record { [[Base]]: baseValue, [[ReferencedName]]: propertyNameValue, [[Strict]]: strict, [[ThisValue]]: empty }를 반환한다.

13.3.4 EvaluatePropertyAccessWithIdentifierKey ( baseValue, identifierName, strict )

The abstract operation EvaluatePropertyAccessWithIdentifierKey takes arguments baseValue (an ECMAScript language value), identifierName (an IdentifierName Parse Node), and strict (a Boolean) and returns a Reference Record. It performs the following steps when called:

  1. propertyNameStringidentifierNameStringValue라고 하자.
  2. Reference Record { [[Base]]: baseValue, [[ReferencedName]]: propertyNameString, [[Strict]]: strict, [[ThisValue]]: empty }를 반환한다.

13.3.5 new 연산자

13.3.5.1 Runtime Semantics: Evaluation

NewExpression : new NewExpression
  1. EvaluateNew(NewExpression, empty)를 반환한다.
MemberExpression : new MemberExpression Arguments
  1. EvaluateNew(MemberExpression, Arguments)를 반환한다.

13.3.5.1.1 EvaluateNew ( constructExpr, 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 either a normal completion containing an Object or an abrupt completion. It performs the following steps when called:

  1. refconstructExprEvaluation 결과 ?라고 하자.
  2. constructor를 ? GetValue(ref)라고 하자.
  3. argumentsempty이면,
    1. argList를 새로운 빈 List라고 하자.
  4. 그렇지 않으면,
    1. argListArgumentsArgumentListEvaluation 결과 ?라고 하자.
  5. IsConstructor(constructor)가 false이면, TypeError 예외를 던진다.
  6. Construct(constructor, argList)를 반환한다.

13.3.6 함수 호출

13.3.6.1 Runtime Semantics: Evaluation

CallExpression : CoverCallExpressionAndAsyncArrowHead
  1. exprCoverCallExpressionAndAsyncArrowHead가 커버하는 CallMemberExpression이라고 하자.
  2. memberExprexprMemberExpression이라고 하자.
  3. argumentsexprArguments라고 하자.
  4. refmemberExprEvaluation 결과 ?라고 하자.
  5. func를 ? GetValue(ref)라고 하자.
  6. refReference Record이고, IsPropertyReference(ref)가 false이며, ref.[[ReferencedName]]"eval"이면,
    1. SameValue(func, %eval%)가 true이면,
      1. argListArgumentsArgumentListEvaluation 결과 ?라고 하자.
      2. argList에 요소가 없으면 undefined를 반환한다.
      3. evalArgargList의 첫 번째 요소라고 하자.
      4. IsStrict(this CallExpression)가 true이면 strictCallertrue로 하자; 그렇지 않으면 strictCallerfalse로 하자.
      5. PerformEval(evalArg, strictCaller, true)를 반환한다.
  7. thisCall을 this CallExpression이라고 하자.
  8. tailCallIsInTailPosition(thisCall)이라고 하자.
  9. EvaluateCall(func, ref, arguments, tailCall)을 반환한다.

단계 6.a.v를 실행하는 CallExpression 평가는 직접 eval이다.

CallExpression : CallExpression Arguments
  1. refCallExpressionEvaluation 결과 ?라고 하자.
  2. func를 ? GetValue(ref)라고 하자.
  3. thisCall을 this CallExpression이라고 하자.
  4. tailCallIsInTailPosition(thisCall)이라고 하자.
  5. EvaluateCall(func, ref, Arguments, tailCall)을 반환한다.

13.3.6.2 EvaluateCall ( func, 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 either a normal completion containing an ECMAScript language value or an abrupt completion. It performs the following steps when called:

  1. refReference Record이면,
    1. IsPropertyReference(ref)가 true이면,
      1. thisValueGetThisValue(ref)라고 하자.
    2. 그렇지 않으면,
      1. refEnvref.[[Base]]라고 하자.
      2. Assert: refEnvEnvironment Record이다.
      3. thisValuerefEnv.WithBaseObject()라고 하자.
  2. 그렇지 않으면,
    1. thisValueundefined라고 하자.
  3. argList를 |_arguments_|의 ArgumentListEvaluation 결과 ?라고 하자.
  4. func가 Object가 아니면, TypeError 예외를 던진다.
  5. IsCallable(func)가 false이면, TypeError 예외를 던진다.
  6. tailPositiontrue이면, PrepareForTailCall()을 수행한다.
  7. Call(func, thisValue, argList)를 반환한다.

13.3.7 super 키워드

13.3.7.1 Runtime Semantics: Evaluation

SuperProperty : super [ Expression ]
  1. envGetThisEnvironment()라고 하자.
  2. actualThis를 ? env.GetThisBinding()이라고 하자.
  3. propertyNameReferenceExpressionEvaluation 결과 ?라고 하자.
  4. propertyNameValue를 ? GetValue(propertyNameReference)라고 하자.
  5. strict를 this SuperPropertyIsStrict라고 하자.
  6. NOTE: 대부분의 경우, 이 단계 직후 propertyNameValueToPropertyKey가 수행된다. 그러나 super[b] = c의 경우에는 c의 평가 이후까지 수행되지 않는다.
  7. MakeSuperPropertyReference(actualThis, propertyNameValue, strict)를 반환한다.
SuperProperty : super . IdentifierName
  1. envGetThisEnvironment()라고 하자.
  2. actualThis를 ? env.GetThisBinding()이라고 하자.
  3. propertyKeyIdentifierNameStringValue라고 하자.
  4. strict를 this SuperPropertyIsStrict라고 하자.
  5. MakeSuperPropertyReference(actualThis, propertyKey, strict)를 반환한다.
SuperCall : super Arguments
  1. newTargetGetNewTarget()이라고 하자.
  2. Assert: newTargetconstructor이다.
  3. superConstructorGetSuperConstructor()라고 하자.
  4. argListArgumentsArgumentListEvaluation 결과 ?라고 하자.
  5. IsConstructor(superConstructor)가 false이면, TypeError 예외를 던진다.
  6. result를 ? Construct(superConstructor, argList, newTarget)라고 하자.
  7. thisERGetThisEnvironment()라고 하자.
  8. Assert: thisERFunction Environment Record이다.
  9. BindThisValue(thisER, result)를 수행한다.
  10. funcObjthisER.[[FunctionObject]]라고 하자.
  11. Assert: funcObj는 ECMAScript 함수 객체이다.
  12. InitializeInstanceElements(result, funcObj)를 수행한다.
  13. result를 반환한다.

13.3.7.2 GetSuperConstructor ( )

The abstract operation GetSuperConstructor takes no arguments and returns an Object or null. It performs the following steps when called:

  1. envRecGetThisEnvironment()라고 하자.
  2. Assert: envRecFunction Environment Record이다.
  3. activeFunctionenvRec.[[FunctionObject]]라고 하자.
  4. Assert: 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 a Super Reference Record. It performs the following steps when called:

  1. envGetThisEnvironment()라고 하자.
  2. Assert: env.HasSuperBinding()은 true이다.
  3. Assert: envFunction Environment Record이다.
  4. baseValueGetSuperBase(env)라고 하자.
  5. Reference Record { [[Base]]: baseValue, [[ReferencedName]]: propertyKey, [[Strict]]: strict, [[ThisValue]]: actualThis }를 반환한다.

13.3.8 인수 목록

Note

인수 목록의 평가는 값들의 List를 생성한다.

13.3.8.1 Runtime Semantics: ArgumentListEvaluation

The syntax-directed operation ArgumentListEvaluation takes no arguments and returns either a normal completion containing a List of ECMAScript language values or an abrupt completion. It is defined piecewise over the following productions:

Arguments : ( )
  1. 새로운 빈 List를 반환한다.
ArgumentList : AssignmentExpression
  1. refAssignmentExpressionEvaluation 결과 ?라고 하자.
  2. arg를 ? GetValue(ref)라고 하자.
  3. « arg »를 반환한다.
ArgumentList : ... AssignmentExpression
  1. list를 새로운 빈 List라고 하자.
  2. spreadRefAssignmentExpressionEvaluation 결과 ?라고 하자.
  3. spreadObj를 ? GetValue(spreadRef)라고 하자.
  4. iteratorRecord를 ? GetIterator(spreadObj, sync)라고 하자.
  5. 반복한다,
    1. next를 ? IteratorStepValue(iteratorRecord)라고 하자.
    2. nextdone이면, list를 반환한다.
    3. nextlist에 추가한다.
ArgumentList : ArgumentList , AssignmentExpression
  1. precedingArgsArgumentListArgumentListEvaluation 결과 ?라고 하자.
  2. refAssignmentExpressionEvaluation 결과 ?라고 하자.
  3. arg를 ? GetValue(ref)라고 하자.
  4. precedingArgs와 « arg »의 list-concatenation을 반환한다.
ArgumentList : ArgumentList , ... AssignmentExpression
  1. precedingArgsArgumentListArgumentListEvaluation 결과 ?라고 하자.
  2. spreadRefAssignmentExpressionEvaluation 결과 ?라고 하자.
  3. iteratorRecord를 ? GetIterator(? GetValue(spreadRef), sync)라고 하자.
  4. 반복한다,
    1. next를 ? IteratorStepValue(iteratorRecord)라고 하자.
    2. nextdone이면, precedingArgs를 반환한다.
    3. nextprecedingArgs에 추가한다.
TemplateLiteral : NoSubstitutionTemplate
  1. templateLiteral을 this TemplateLiteral이라고 하자.
  2. siteObjGetTemplateObject(templateLiteral)라고 하자.
  3. « siteObj »를 반환한다.
TemplateLiteral : SubstitutionTemplate
  1. templateLiteral을 this TemplateLiteral이라고 하자.
  2. siteObjGetTemplateObject(templateLiteral)라고 하자.
  3. remainingSubstitutionTemplateArgumentListEvaluation 결과 ?라고 하자.
  4. « siteObj »와 remaininglist-concatenation을 반환한다.
SubstitutionTemplate : TemplateHead Expression TemplateSpans
  1. firstSubRefExpressionEvaluation 결과 ?라고 하자.
  2. firstSub를 ? GetValue(firstSubRef)라고 하자.
  3. restSubTemplateSpansSubstitutionEvaluation 결과 ?라고 하자.
  4. Assert: restSub는 비어 있을 수도 있는 List이다.
  5. « firstSub »와 restSublist-concatenation을 반환한다.

13.3.9 선택적 체인

Note
선택적 체인은 하나 이상의 프로퍼티 접근과 함수 호출로 이루어진 체인이며, 그 첫 번째는 토큰 ?.로 시작한다.

13.3.9.1 Runtime Semantics: Evaluation

OptionalExpression : MemberExpression OptionalChain
  1. baseReferenceMemberExpressionEvaluation 결과 ?라고 하자.
  2. baseValue를 ? GetValue(baseReference)라고 하자.
  3. baseValueundefined 또는 null 중 하나이면,
    1. undefined를 반환한다.
  4. 인수 baseValuebaseReference를 사용하여 OptionalChainChainEvaluation을 ? 반환한다.
OptionalExpression : CallExpression OptionalChain
  1. baseReferenceCallExpressionEvaluation 결과 ?라고 하자.
  2. baseValue를 ? GetValue(baseReference)라고 하자.
  3. baseValueundefined 또는 null 중 하나이면,
    1. undefined를 반환한다.
  4. 인수 baseValuebaseReference를 사용하여 OptionalChainChainEvaluation을 ? 반환한다.
OptionalExpression : OptionalExpression OptionalChain
  1. baseReferenceOptionalExpressionEvaluation 결과 ?라고 하자.
  2. baseValue를 ? GetValue(baseReference)라고 하자.
  3. baseValueundefined 또는 null 중 하나이면,
    1. undefined를 반환한다.
  4. 인수 baseValuebaseReference를 사용하여 OptionalChainChainEvaluation을 ? 반환한다.

13.3.9.2 Runtime Semantics: ChainEvaluation

The syntax-directed operation ChainEvaluation takes arguments baseValue (an ECMAScript language value) and baseReference (an ECMAScript language value or a Reference Record) and returns either a normal completion containing either an ECMAScript language value or a Reference Record, or an abrupt completion. It is defined piecewise over the following productions:

OptionalChain : ?. Arguments
  1. thisChain을 this OptionalChain이라고 하자.
  2. tailCallIsInTailPosition(thisChain)이라고 하자.
  3. EvaluateCall(baseValue, baseReference, Arguments, tailCall)을 반환한다.
OptionalChain : ?. [ Expression ]
  1. strict를 this OptionalChainIsStrict라고 하자.
  2. 인수 baseValue, Expression, strict를 사용하여 ? EvaluatePropertyAccessWithExpressionKey를 반환한다.
OptionalChain : ?. IdentifierName
  1. strict를 this OptionalChainIsStrict라고 하자.
  2. EvaluatePropertyAccessWithIdentifierKey(baseValue, IdentifierName, strict)를 반환한다.
OptionalChain : ?. PrivateIdentifier
  1. fieldNameStringPrivateIdentifierStringValue라고 하자.
  2. MakePrivateReference(baseValue, fieldNameString)를 반환한다.
OptionalChain : OptionalChain Arguments
  1. optionalChainOptionalChain이라고 하자.
  2. newReference를 인수 baseValuebaseReference를 사용한 optionalChainChainEvaluation 결과 ?라고 하자.
  3. newValue를 ? GetValue(newReference)라고 하자.
  4. thisChain을 this OptionalChain이라고 하자.
  5. tailCallIsInTailPosition(thisChain)이라고 하자.
  6. EvaluateCall(newValue, newReference, Arguments, tailCall)을 반환한다.
OptionalChain : OptionalChain [ Expression ]
  1. optionalChainOptionalChain이라고 하자.
  2. newReference를 인수 baseValuebaseReference를 사용한 optionalChainChainEvaluation 결과 ?라고 하자.
  3. newValue를 ? GetValue(newReference)라고 하자.
  4. strict를 this OptionalChainIsStrict라고 하자.
  5. 인수 newValue, Expression, strict를 사용하여 ? EvaluatePropertyAccessWithExpressionKey를 반환한다.
OptionalChain : OptionalChain . IdentifierName
  1. optionalChainOptionalChain이라고 하자.
  2. newReference를 인수 baseValuebaseReference를 사용한 optionalChainChainEvaluation 결과 ?라고 하자.
  3. newValue를 ? GetValue(newReference)라고 하자.
  4. strict를 this OptionalChainIsStrict라고 하자.
  5. EvaluatePropertyAccessWithIdentifierKey(newValue, IdentifierName, strict)를 반환한다.
OptionalChain : OptionalChain . PrivateIdentifier
  1. optionalChainOptionalChain이라고 하자.
  2. newReference를 인수 baseValuebaseReference를 사용한 optionalChainChainEvaluation 결과 ?라고 하자.
  3. newValue를 ? GetValue(newReference)라고 하자.
  4. fieldNameStringPrivateIdentifierStringValue라고 하자.
  5. MakePrivateReference(newValue, fieldNameString)를 반환한다.

13.3.10 Import 호출

13.3.10.1 Runtime Semantics: Evaluation

ImportCall : import ( AssignmentExpression ,opt )
  1. EvaluateImportCall(AssignmentExpression)을 반환한다.
ImportCall : import ( AssignmentExpression , AssignmentExpression ,opt )
  1. EvaluateImportCall(the first AssignmentExpression, the second 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 either a normal completion containing a Promise or an abrupt completion. It performs the following steps when called:

  1. referrerGetActiveScriptOrModule()이라고 하자.
  2. referrernull이면, referrer를 현재 Realm Record로 설정한다.
  3. specifierRefspecifierExpressionEvaluation 결과 ?라고 하자.
  4. specifier를 ? GetValue(specifierRef)라고 하자.
  5. optionsExpression이 존재하면,
    1. optionsRefoptionsExpressionEvaluation 결과 ?라고 하자.
    2. options를 ? GetValue(optionsRef)라고 하자.
  6. 그렇지 않으면,
    1. optionsundefined라고 하자.
  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, « a newly created TypeError object »)를 수행한다.
      2. promiseCapability.[[Promise]]를 반환한다.
    2. attributesObjCompletion(Get(options, "with"))라고 하자.
    3. IfAbruptRejectPromise(attributesObj, promiseCapability).
    4. attributesObjundefined가 아니면,
      1. attributesObj가 Object가 아니면,
        1. Call(promiseCapability.[[Reject]], undefined, « a newly created TypeError object »)를 수행한다.
        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, « a newly created TypeError object »)를 수행한다.
            2. promiseCapability.[[Promise]]를 반환한다.
          2. ImportAttribute Record { [[Key]]: key, [[Value]]: value }를 attributes에 추가한다.
    5. AllImportAttributesSupported(attributes)가 false이면,
      1. Call(promiseCapability.[[Reject]], undefined, « a newly created TypeError object »)를 수행한다.
      2. promiseCapability.[[Promise]]를 반환한다.
    6. attributes[[Key]] 필드 값들을 UTF-16 코드 단위 값 시퀀스로 취급하여 그 사전식 순서에 따라 attributes를 정렬한다. 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 (either a normal completion containing a Module Record or a 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]]라고 하자.
  3. loadPromisemodule.LoadRequestedModules()라고 하자.
  4. promiseCapability를 캡처하고, 호출될 때 다음 단계를 수행하는 매개변수 (reason)를 가진 새로운 Abstract ClosurerejectedClosure라고 하자:
    1. Call(promiseCapability.[[Reject]], undefined, « reason »)를 수행한다.
    2. NormalCompletion(undefined)를 반환한다.
  5. onRejectedCreateBuiltinFunction(rejectedClosure, 1, "", « »)라고 하자.
  6. module, promiseCapability, onRejected를 캡처하고, 호출될 때 다음 단계를 수행하는 매개변수 없는 새로운 Abstract ClosurelinkAndEvaluateClosure라고 하자:
    1. linkCompletion(module.Link())라고 하자.
    2. linkabrupt completion이면,
      1. Call(promiseCapability.[[Reject]], undefined, « link.[[Value]] »)를 수행한다.
      2. NormalCompletion(undefined)를 반환한다.
    3. evaluatePromisemodule.Evaluate()라고 하자.
    4. modulepromiseCapability를 캡처하고, 호출될 때 다음 단계를 수행하는 매개변수 없는 새로운 Abstract ClosurefulfilledClosure라고 하자:
      1. namespaceGetModuleNamespace(module)라고 하자.
      2. Call(promiseCapability.[[Resolve]], undefined, « namespace »)를 수행한다.
      3. NormalCompletion(undefined)를 반환한다.
    5. onFulfilledCreateBuiltinFunction(fulfilledClosure, 0, "", « »)라고 하자.
    6. PerformPromiseThen(evaluatePromise, onFulfilled, onRejected)를 수행한다.
    7. unused를 반환한다.
  7. linkAndEvaluateCreateBuiltinFunction(linkAndEvaluateClosure, 0, "", « »)라고 하자.
  8. PerformPromiseThen(loadPromise, linkAndEvaluate, onRejected)를 수행한다.
  9. unused를 반환한다.

13.3.11 태그된 템플릿

Note

태그된 템플릿은 호출 인수가 TemplateLiteral(13.2.8)로부터 파생되는 함수 호출이다. 실제 인수에는 템플릿 객체(13.2.8.4)와 TemplateLiteral 안에 포함된 표현식들을 평가해서 생성된 값들이 포함된다.

13.3.11.1 Runtime Semantics: Evaluation

MemberExpression : MemberExpression TemplateLiteral
  1. tagRefMemberExpressionEvaluation 결과 ?라고 하자.
  2. tagFunc를 ? GetValue(tagRef)라고 하자.
  3. thisCall을 this MemberExpression이라고 하자.
  4. tailCallIsInTailPosition(thisCall)이라고 하자.
  5. EvaluateCall(tagFunc, tagRef, TemplateLiteral, tailCall)을 반환한다.
CallExpression : CallExpression TemplateLiteral
  1. tagRefCallExpressionEvaluation 결과 ?라고 하자.
  2. tagFunc를 ? GetValue(tagRef)라고 하자.
  3. thisCall을 this CallExpression이라고 하자.
  4. tailCallIsInTailPosition(thisCall)이라고 하자.
  5. EvaluateCall(tagFunc, tagRef, TemplateLiteral, tailCall)을 반환한다.

13.3.12 메타 프로퍼티

13.3.12.1 Runtime Semantics: Evaluation

NewTarget : new . target
  1. GetNewTarget()을 반환한다.
ImportMeta : import . meta
  1. moduleGetActiveScriptOrModule()이라고 하자.
  2. Assert: moduleSource Text Module Record이다.
  3. importMetamodule.[[ImportMeta]]라고 하자.
  4. importMetaempty이면,
    1. importMetaOrdinaryObjectCreate(null)로 설정한다.
    2. importMetaValuesHostGetImportMetaProperties(module)라고 하자.
    3. importMetaValues의 각 Record { [[Key]], [[Value]] } p에 대해, 다음을 수행한다
      1. CreateDataPropertyOrThrow(importMeta, p.[[Key]], p.[[Value]])를 수행한다.
    4. HostFinalizeImportMeta(importMeta, module)를 수행한다.
    5. module.[[ImportMeta]]importMeta로 설정한다.
    6. importMeta를 반환한다.
  5. Assert: importMeta는 Object이다.
  6. importMeta를 반환한다.

13.3.12.1.1 HostGetImportMetaProperties ( moduleRecord )

The host-defined abstract operation HostGetImportMetaProperties takes argument moduleRecord (a Module Record) and returns a List of Records with fields [[Key]] (a property key) and [[Value]] (an ECMAScript language value). 이것은 호스트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에서 반환되는 객체를 준비하기 위해 특별한 연산을 수행할 수 있게 한다.

대부분의 호스트는 단순히 HostGetImportMetaProperties를 정의하고, HostFinalizeImportMeta는 기본 동작 그대로 둘 수 있다. 그러나 HostFinalizeImportMeta는 객체가 ECMAScript 코드에 노출되기 전에 호스트가 직접 조작해야 하는 경우를 위한 "탈출구"를 제공한다.

HostFinalizeImportMeta의 기본 구현은 unused를 반환하는 것이다.

13.4 업데이트 표현식

구문

UpdateExpression[Yield, Await] : LeftHandSideExpression[?Yield, ?Await] LeftHandSideExpression[?Yield, ?Await] [no LineTerminator here] ++ LeftHandSideExpression[?Yield, ?Await] [no LineTerminator here] -- ++ UnaryExpression[?Yield, ?Await] -- UnaryExpression[?Yield, ?Await]

13.4.1 Static Semantics: Early Errors

UpdateExpression : LeftHandSideExpression ++ LeftHandSideExpression -- UpdateExpression : ++ UnaryExpression -- UnaryExpression

13.4.2 후위 증가 연산자

13.4.2.1 Runtime Semantics: Evaluation

UpdateExpression : LeftHandSideExpression ++
  1. lhsLeftHandSideExpressionEvaluation 결과 ?라고 하자.
  2. LeftHandSideExpressionAssignmentTargetTypeweb-compat이면, ReferenceError 예외를 던진다.
  3. oldValue를 ? ToNumeric(? GetValue(lhs))라고 하자.
  4. oldValue가 Number이면,
    1. newValueNumber::add(oldValue, 1𝔽)라고 하자.
  5. 그렇지 않으면,
    1. Assert: oldValue는 BigInt이다.
    2. newValueBigInt::add(oldValue, 1)라고 하자.
  6. PutValue(lhs, newValue)를 수행한다.
  7. oldValue를 반환한다.

13.4.3 후위 감소 연산자

13.4.3.1 Runtime Semantics: Evaluation

UpdateExpression : LeftHandSideExpression --
  1. lhsLeftHandSideExpressionEvaluation 결과 ?라고 하자.
  2. LeftHandSideExpressionAssignmentTargetTypeweb-compat이면, ReferenceError 예외를 던진다.
  3. oldValue를 ? ToNumeric(? GetValue(lhs))라고 하자.
  4. oldValue가 Number이면,
    1. newValueNumber::subtract(oldValue, 1𝔽)라고 하자.
  5. 그렇지 않으면,
    1. Assert: oldValue는 BigInt이다.
    2. newValueBigInt::subtract(oldValue, 1)라고 하자.
  6. PutValue(lhs, newValue)를 수행한다.
  7. oldValue를 반환한다.

13.4.4 전위 증가 연산자

13.4.4.1 Runtime Semantics: Evaluation

UpdateExpression : ++ UnaryExpression
  1. exprUnaryExpressionEvaluation 결과 ?라고 하자.
  2. UnaryExpressionAssignmentTargetTypeweb-compat이면, ReferenceError 예외를 던진다.
  3. oldValue를 ? ToNumeric(? GetValue(expr))라고 하자.
  4. oldValue가 Number이면,
    1. newValueNumber::add(oldValue, 1𝔽)라고 하자.
  5. 그렇지 않으면,
    1. Assert: oldValue는 BigInt이다.
    2. newValueBigInt::add(oldValue, 1)라고 하자.
  6. PutValue(expr, newValue)를 수행한다.
  7. newValue를 반환한다.

13.4.5 전위 감소 연산자

13.4.5.1 Runtime Semantics: Evaluation

UpdateExpression : -- UnaryExpression
  1. exprUnaryExpressionEvaluation 결과 ?라고 하자.
  2. UnaryExpressionAssignmentTargetTypeweb-compat이면, ReferenceError 예외를 던진다.
  3. oldValue를 ? ToNumeric(? GetValue(expr))라고 하자.
  4. oldValue가 Number이면,
    1. newValueNumber::subtract(oldValue, 1𝔽)라고 하자.
  5. 그렇지 않으면,
    1. Assert: oldValue는 BigInt이다.
    2. newValueBigInt::subtract(oldValue, 1)라고 하자.
  6. PutValue(expr, newValue)를 수행한다.
  7. newValue를 반환한다.

13.5 단항 연산자

구문

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 연산자

13.5.1.1 Static Semantics: Early Errors

UnaryExpression : delete UnaryExpression Note

마지막 규칙은 delete (((foo))) 같은 표현식이 첫 번째 규칙의 재귀적 적용으로 인해 early error를 발생시킨다는 뜻이다.

13.5.1.2 Runtime Semantics: Evaluation

UnaryExpression : delete UnaryExpression
  1. refUnaryExpressionEvaluation 결과 ?라고 하자.
  2. refReference Record가 아니면, true를 반환한다.
  3. IsUnresolvableReference(ref)가 true이면,
    1. Assert: ref.[[Strict]]false이다.
    2. true를 반환한다.
  4. IsPropertyReference(ref)가 true이면,
    1. Assert: IsPrivateReference(ref)는 false이다.
    2. IsSuperReference(ref)가 true이면, ReferenceError 예외를 던진다.
    3. baseObj를 ? ToObject(ref.[[Base]])라고 하자.
    4. ref.[[ReferencedName]]이 프로퍼티 키가 아니면,
      1. ref.[[ReferencedName]]를 ? ToPropertyKey(ref.[[ReferencedName]])로 설정한다.
    5. deleteStatus를 ? baseObj.[[Delete]](ref.[[ReferencedName]])라고 하자.
    6. deleteStatusfalse이고 ref.[[Strict]]true이면, TypeError 예외를 던진다.
    7. deleteStatus를 반환한다.
  5. baseref.[[Base]]라고 하자.
  6. Assert: baseEnvironment Record이다.
  7. base.DeleteBinding(ref.[[ReferencedName]])를 반환한다.
Note 1

delete 연산자가 strict mode 코드 안에 나타나면, 그 UnaryExpression이 변수, 함수 인수, 또는 함수 이름에 대한 직접 참조일 경우 SyntaxError 예외가 던져진다. 또한 delete 연산자가 strict mode 코드 안에 나타나고 삭제하려는 프로퍼티가 { [[Configurable]]: false } 속성을 가지는 경우(또는 다른 이유로 삭제할 수 없는 경우), TypeError 예외가 던져진다.

Note 2

단계 4.c에서 생성될 수 있는 객체는 위 추상 연산과 일반 객체 [[Delete]] 내부 메서드 밖에서는 접근할 수 없다. 구현은 그 객체를 실제로 만들지 않도록 선택할 수 있다.

13.5.2 void 연산자

13.5.2.1 Runtime Semantics: Evaluation

UnaryExpression : void UnaryExpression
  1. exprUnaryExpressionEvaluation 결과 ?라고 하자.
  2. GetValue(expr)를 수행한다.
  3. undefined를 반환한다.
Note

GetValue의 값은 사용되지 않더라도 관찰 가능한 부작용이 있을 수 있으므로 반드시 호출해야 한다.

13.5.3 typeof 연산자

13.5.3.1 Runtime Semantics: Evaluation

UnaryExpression : typeof UnaryExpression
  1. valUnaryExpressionEvaluation 결과 ?라고 하자.
  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. Assert: val은 Object이다.
  12. Normative Optional
    호스트가 웹 브라우저이거나 또는 [[IsHTMLDDA]] 내부 슬롯를 지원하면,
    1. val[[IsHTMLDDA]] 내부 슬롯을 가지면 "undefined"를 반환한다.
  13. val[[Call]] 내부 메서드를 가지면 "function"을 반환한다.
  14. "object"를 반환한다.

13.5.4 단항 + 연산자

Note

단항 + 연산자는 피연산자를 Number 타입으로 변환한다.

13.5.4.1 Runtime Semantics: Evaluation

UnaryExpression : + UnaryExpression
  1. exprUnaryExpressionEvaluation 결과 ?라고 하자.
  2. ToNumber(? GetValue(expr))를 반환한다.

13.5.5 단항 - 연산자

Note

단항 - 연산자는 피연산자를 수치 값으로 변환한 뒤 부호를 반전시킨다. +0𝔽를 부정하면 -0𝔽가 되고, -0𝔽를 부정하면 +0𝔽가 된다.

13.5.5.1 Runtime Semantics: Evaluation

UnaryExpression : - UnaryExpression
  1. exprUnaryExpressionEvaluation 결과 ?라고 하자.
  2. oldValue를 ? ToNumeric(? GetValue(expr))라고 하자.
  3. oldValue가 Number이면 Number::unaryMinus(oldValue)를 반환한다.
  4. Assert: oldValue는 BigInt이다.
  5. BigInt::unaryMinus(oldValue)를 반환한다.

13.5.6 비트 NOT 연산자 ( ~ )

13.5.6.1 Runtime Semantics: Evaluation

UnaryExpression : ~ UnaryExpression
  1. exprUnaryExpressionEvaluation 결과 ?라고 하자.
  2. oldValue를 ? ToNumeric(? GetValue(expr))라고 하자.
  3. oldValue가 Number이면 Number::bitwiseNOT(oldValue)를 반환한다.
  4. Assert: oldValue는 BigInt이다.
  5. BigInt::bitwiseNOT(oldValue)를 반환한다.

13.5.7 논리 NOT 연산자 ( ! )

13.5.7.1 Runtime Semantics: Evaluation

UnaryExpression : ! UnaryExpression
  1. exprUnaryExpressionEvaluation 결과 ?라고 하자.
  2. oldValueToBoolean(? GetValue(expr))라고 하자.
  3. oldValuetrue이면 false를 반환한다.
  4. true를 반환한다.

13.6 거듭제곱 연산자

구문

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 곱셈 연산자

구문

MultiplicativeExpression[Yield, Await] : ExponentiationExpression[?Yield, ?Await] MultiplicativeExpression[?Yield, ?Await] MultiplicativeOperator ExponentiationExpression[?Yield, ?Await] MultiplicativeOperator : one of * / % Note
  • * 연산자는 곱셈을 수행하여 피연산자의 곱을 생성한다.
  • / 연산자는 나눗셈을 수행하여 피연산자의 몫을 생성한다.
  • % 연산자는 암묵적인 나눗셈에서 피연산자의 나머지를 산출한다.

13.7.1 Runtime Semantics: Evaluation

MultiplicativeExpression : MultiplicativeExpression MultiplicativeOperator ExponentiationExpression
  1. opTextMultiplicativeOperator에 매치된 소스 텍스트라고 하자.
  2. EvaluateStringOrNumericBinaryExpression(MultiplicativeExpression, opText, ExponentiationExpression)을 반환한다.

13.8 덧셈 연산자

구문

AdditiveExpression[Yield, Await] : MultiplicativeExpression[?Yield, ?Await] AdditiveExpression[?Yield, ?Await] + MultiplicativeExpression[?Yield, ?Await] AdditiveExpression[?Yield, ?Await] - MultiplicativeExpression[?Yield, ?Await]

13.8.1 덧셈 연산자 ( + )

Note

덧셈 연산자는 문자열 연결 또는 수치 덧셈을 수행한다.

13.8.1.1 Runtime Semantics: Evaluation

AdditiveExpression : AdditiveExpression + MultiplicativeExpression
  1. EvaluateStringOrNumericBinaryExpression(AdditiveExpression, +, MultiplicativeExpression)을 반환한다.

13.8.2 뺄셈 연산자 ( - )

Note

- 연산자는 뺄셈을 수행하여 피연산자의 차를 생성한다.

13.8.2.1 Runtime Semantics: Evaluation

AdditiveExpression : AdditiveExpression - MultiplicativeExpression
  1. EvaluateStringOrNumericBinaryExpression(AdditiveExpression, -, MultiplicativeExpression)을 반환한다.

13.9 비트 시프트 연산자

구문

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 좌측 시프트 연산자 ( << )

Note

왼쪽 피연산자에 대해 오른쪽 피연산자가 지정한 양만큼 비트 단위 왼쪽 시프트 연산을 수행한다.

13.9.1.1 Runtime Semantics: Evaluation

ShiftExpression : ShiftExpression << AdditiveExpression
  1. EvaluateStringOrNumericBinaryExpression(ShiftExpression, <<, AdditiveExpression)을 반환한다.

13.9.2 부호 있는 우측 시프트 연산자 ( >> )

Note

왼쪽 피연산자에 대해 오른쪽 피연산자가 지정한 양만큼 부호 확장 비트 단위 오른쪽 시프트 연산을 수행한다.

13.9.2.1 Runtime Semantics: Evaluation

ShiftExpression : ShiftExpression >> AdditiveExpression
  1. EvaluateStringOrNumericBinaryExpression(ShiftExpression, >>, AdditiveExpression)을 반환한다.

13.9.3 부호 없는 우측 시프트 연산자 ( >>> )

Note

왼쪽 피연산자에 대해 오른쪽 피연산자가 지정한 양만큼 0 확장 비트 단위 오른쪽 시프트 연산을 수행한다.

13.9.3.1 Runtime Semantics: Evaluation

ShiftExpression : ShiftExpression >>> AdditiveExpression
  1. EvaluateStringOrNumericBinaryExpression(ShiftExpression, >>>, AdditiveExpression)을 반환한다.

13.10 관계 연산자

Note 1

관계 연산자를 평가한 결과는 언제나 Boolean 타입이며, 연산자가 이름 붙인 관계가 두 피연산자 사이에 성립하는지를 반영한다.

구문

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. lRefRelationalExpressionEvaluation 결과 ?라고 하자.
  2. lVal를 ? GetValue(lRef)라고 하자.
  3. rRefShiftExpressionEvaluation 결과 ?라고 하자.
  4. rVal를 ? GetValue(rRef)라고 하자.
  5. result를 ? IsLessThan(lVal, rVal, true)라고 하자.
  6. resultundefined이면 false를 반환한다.
  7. result를 반환한다.
RelationalExpression : RelationalExpression > ShiftExpression
  1. lRefRelationalExpressionEvaluation 결과 ?라고 하자.
  2. lVal를 ? GetValue(lRef)라고 하자.
  3. rRefShiftExpressionEvaluation 결과 ?라고 하자.
  4. rVal를 ? GetValue(rRef)라고 하자.
  5. result를 ? IsLessThan(rVal, lVal, false)라고 하자.
  6. resultundefined이면 false를 반환한다.
  7. result를 반환한다.
RelationalExpression : RelationalExpression <= ShiftExpression
  1. lRefRelationalExpressionEvaluation 결과 ?라고 하자.
  2. lVal를 ? GetValue(lRef)라고 하자.
  3. rRefShiftExpressionEvaluation 결과 ?라고 하자.
  4. rVal를 ? GetValue(rRef)라고 하자.
  5. result를 ? IsLessThan(rVal, lVal, false)라고 하자.
  6. resulttrue 또는 undefined 중 하나이면 false를 반환한다.
  7. true를 반환한다.
RelationalExpression : RelationalExpression >= ShiftExpression
  1. lRefRelationalExpressionEvaluation 결과 ?라고 하자.
  2. lVal를 ? GetValue(lRef)라고 하자.
  3. rRefShiftExpressionEvaluation 결과 ?라고 하자.
  4. rVal를 ? GetValue(rRef)라고 하자.
  5. result를 ? IsLessThan(lVal, rVal, true)라고 하자.
  6. resulttrue 또는 undefined 중 하나이면 false를 반환한다.
  7. true를 반환한다.
RelationalExpression : RelationalExpression instanceof ShiftExpression
  1. lRefRelationalExpressionEvaluation 결과 ?라고 하자.
  2. lVal를 ? GetValue(lRef)라고 하자.
  3. rRefShiftExpressionEvaluation 결과 ?라고 하자.
  4. rVal를 ? GetValue(rRef)라고 하자.
  5. InstanceofOperator(lVal, rVal)를 반환한다.
RelationalExpression : RelationalExpression in ShiftExpression
  1. lRefRelationalExpressionEvaluation 결과 ?라고 하자.
  2. lVal를 ? GetValue(lRef)라고 하자.
  3. rRefShiftExpressionEvaluation 결과 ?라고 하자.
  4. rVal를 ? GetValue(rRef)라고 하자.
  5. rVal가 Object가 아니면 TypeError 예외를 던진다.
  6. HasProperty(rVal, ? ToPropertyKey(lVal))를 반환한다.
RelationalExpression : PrivateIdentifier in ShiftExpression
  1. privateIdentifierPrivateIdentifierStringValue라고 하자.
  2. rRefShiftExpressionEvaluation 결과 ?라고 하자.
  3. rVal를 ? GetValue(rRef)라고 하자.
  4. rVal가 Object가 아니면 TypeError 예외를 던진다.
  5. privateEnv를 현재 실행 중인 execution context의 PrivateEnvironment라고 하자.
  6. Assert: privateEnvnull이 아니다.
  7. privateNameResolvePrivateIdentifier(privateEnv, privateIdentifier)라고 하자.
  8. PrivateElementFind(rVal, privateName)가 empty이면 false를 반환한다.
  9. true를 반환한다.

13.10.2 InstanceofOperator ( value, target )

The abstract operation InstanceofOperator takes arguments value (an ECMAScript language value) and target (an ECMAScript language value) and returns either a normal completion containing a Boolean or a throw completion. 이것은 valuetarget의 인스턴스인지 결정하는 일반 알고리즘을 구현하는데, target%Symbol.hasInstance% 메서드를 조회하거나, 그것이 없으면 target"prototype" 프로퍼티 값이 value의 프로토타입 체인 안에 존재하는지를 결정한다. It performs the following steps when called:

  1. target이 Object가 아니면 TypeError 예외를 던진다.
  2. instOfHandler를 ? GetMethod(target, %Symbol.hasInstance%)라고 하자.
  3. instOfHandlerundefined가 아니면,
    1. ToBoolean(? Call(instOfHandler, target, « value »))를 반환한다.
  4. IsCallable(target)가 false이면 TypeError 예외를 던진다.
  5. OrdinaryHasInstance(target, value)를 반환한다.
Note

단계 45instanceof 연산자 의미론을 정의하기 위해 %Symbol.hasInstance% 메서드를 사용하지 않았던 이전 ECMAScript 판과의 호환성을 제공한다. 객체가 %Symbol.hasInstance%를 정의하거나 상속하지 않으면 기본 instanceof 의미론을 사용한다.

13.11 동등 연산자

Note

동등 연산자를 평가한 결과는 언제나 Boolean 타입이며, 연산자가 이름 붙인 관계가 두 피연산자 사이에 성립하는지를 반영한다.

구문

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. lRefEqualityExpressionEvaluation 결과 ?라고 하자.
  2. lVal를 ? GetValue(lRef)라고 하자.
  3. rRefRelationalExpressionEvaluation 결과 ?라고 하자.
  4. rVal를 ? GetValue(rRef)라고 하자.
  5. IsLooselyEqual(rVal, lVal)를 반환한다.
EqualityExpression : EqualityExpression != RelationalExpression
  1. lRefEqualityExpressionEvaluation 결과 ?라고 하자.
  2. lVal를 ? GetValue(lRef)라고 하자.
  3. rRefRelationalExpressionEvaluation 결과 ?라고 하자.
  4. rVal를 ? GetValue(rRef)라고 하자.
  5. r를 ? IsLooselyEqual(rVal, lVal)라고 하자.
  6. rtrue이면 false를 반환한다.
  7. true를 반환한다.
EqualityExpression : EqualityExpression === RelationalExpression
  1. lRefEqualityExpressionEvaluation 결과 ?라고 하자.
  2. lVal를 ? GetValue(lRef)라고 하자.
  3. rRefRelationalExpressionEvaluation 결과 ?라고 하자.
  4. rVal를 ? GetValue(rRef)라고 하자.
  5. IsStrictlyEqual(rVal, lVal)를 반환한다.
EqualityExpression : EqualityExpression !== RelationalExpression
  1. lRefEqualityExpressionEvaluation 결과 ?라고 하자.
  2. lVal를 ? GetValue(lRef)라고 하자.
  3. rRefRelationalExpressionEvaluation 결과 ?라고 하자.
  4. rVal를 ? GetValue(rRef)라고 하자.
  5. rIsStrictlyEqual(rVal, lVal)라고 하자.
  6. rtrue이면 false를 반환한다.
  7. true를 반환한다.
Note 1

동등 연산자는 다음 불변식을 유지한다:

  • A != B!(A == B)와 동등하다.
  • A == BAB의 평가 순서를 제외하면 B == A와 동등하다.
Note 2

동등 연산자는 항상 추이적이지는 않다. 예를 들어, 같은 String 값을 나타내는 서로 다른 두 String 객체가 있을 수 있다; 각 String 객체는 == 연산자에 의해 그 String 값과는 같다고 간주되지만, 두 String 객체는 서로 같지 않다. 예를 들어:

  • new String("a") == "a""a" == new String("a")는 둘 다 true이다.
  • new String("a") == new String("a")false이다.
Note 3

String 비교는 코드 단위 값 시퀀스에 대한 단순한 동등성 테스트를 사용한다. Unicode 명세에 정의된 보다 복잡하고 의미 지향적인 문자 또는 문자열 동등성 및 정렬 순서 정의를 사용하려는 시도는 없다. 따라서 Unicode Standard에 따라 canonical equal한 String 값들이 서로 같지 않게 테스트될 수 있다. 실제로 이 알고리즘은 두 String이 이미 정규화된 형태라고 가정한다.

13.12 이항 비트 연산자

구문

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 이항 논리 연산자

구문

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. lRefLogicalANDExpressionEvaluation 결과 ?라고 하자.
  2. lVal를 ? GetValue(lRef)라고 하자.
  3. ToBoolean(lVal)가 false이면, lVal를 반환한다.
  4. rRefBitwiseORExpressionEvaluation 결과 ?라고 하자.
  5. GetValue(rRef)를 반환한다.
LogicalORExpression : LogicalORExpression || LogicalANDExpression
  1. lRefLogicalORExpressionEvaluation 결과 ?라고 하자.
  2. lVal를 ? GetValue(lRef)라고 하자.
  3. ToBoolean(lVal)가 true이면, lVal를 반환한다.
  4. rRefLogicalANDExpressionEvaluation 결과 ?라고 하자.
  5. GetValue(rRef)를 반환한다.
CoalesceExpression : CoalesceExpressionHead ?? BitwiseORExpression
  1. lRefCoalesceExpressionHeadEvaluation 결과 ?라고 하자.
  2. lVal를 ? GetValue(lRef)라고 하자.
  3. lValundefined도 아니고 null도 아니면, lVal를 반환한다.
  4. rRefBitwiseORExpressionEvaluation 결과 ?라고 하자.
  5. GetValue(rRef)를 반환한다.

13.14 조건 연산자 ( ? : )

구문

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의 그것과 약간 다르며, 이 둘은 각각 두 번째 하위 표현식으로 Expression을 허용하지만 세 번째 표현식은 ConditionalExpression으로 제한한다. ECMAScript에서 이 차이의 동기는 조건식의 어느 쪽 가지에도 대입 표현식이 오도록 허용하고, 가운데 표현식이 콤마 표현식인 혼란스럽고 거의 쓸모없는 경우를 제거하기 위함이다.

13.14.1 Runtime Semantics: Evaluation

ConditionalExpression : ShortCircuitExpression ? AssignmentExpression : AssignmentExpression
  1. lRefShortCircuitExpressionEvaluation 결과 ?라고 하자.
  2. lValToBoolean(? GetValue(lRef))라고 하자.
  3. lValtrue이면,
    1. trueRef를 첫 번째 AssignmentExpressionEvaluation 결과 ?라고 하자.
    2. GetValue(trueRef)를 반환한다.
  4. falseRef를 두 번째 AssignmentExpressionEvaluation 결과 ?라고 하자.
  5. GetValue(falseRef)를 반환한다.

13.15 대입 연산자

구문

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. lRefLeftHandSideExpressionEvaluation 결과 ?라고 하자.
    2. LeftHandSideExpressionAssignmentTargetTypeweb-compat이면, ReferenceError 예외를 던진다.
    3. IsAnonymousFunctionDefinition(AssignmentExpression)이 true이고 IsIdentifierRef of LeftHandSideExpressiontrue이면,
      1. lhsLeftHandSideExpressionStringValue라고 하자.
      2. rVal를 인수 lhs를 사용한 AssignmentExpressionNamedEvaluation 결과 ?라고 하자.
    4. 그렇지 않으면,
      1. rRefAssignmentExpressionEvaluation 결과 ?라고 하자.
      2. rVal를 ? GetValue(rRef)라고 하자.
    5. PutValue(lRef, rVal)를 수행한다.
    6. rVal를 반환한다.
  2. assignmentPatternLeftHandSideExpression이 커버하는 AssignmentPattern이라고 하자.
  3. rRefAssignmentExpressionEvaluation 결과 ?라고 하자.
  4. rVal를 ? GetValue(rRef)라고 하자.
  5. 인수 rVal를 사용한 assignmentPatternDestructuringAssignmentEvaluation을 ? 수행한다.
  6. rVal를 반환한다.
AssignmentExpression : LeftHandSideExpression AssignmentOperator AssignmentExpression
  1. lRefLeftHandSideExpressionEvaluation 결과 ?라고 하자.
  2. LeftHandSideExpressionAssignmentTargetTypeweb-compat이면, ReferenceError 예외를 던진다.
  3. lVal를 ? GetValue(lRef)라고 하자.
  4. rRefAssignmentExpressionEvaluation 결과 ?라고 하자.
  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. lRefLeftHandSideExpressionEvaluation 결과 ?라고 하자.
  2. lVal를 ? GetValue(lRef)라고 하자.
  3. ToBoolean(lVal)가 false이면, lVal를 반환한다.
  4. IsAnonymousFunctionDefinition(AssignmentExpression)이 true이고 IsIdentifierRef of LeftHandSideExpressiontrue이면,
    1. lhsLeftHandSideExpressionStringValue라고 하자.
    2. rVal를 인수 lhs를 사용한 AssignmentExpressionNamedEvaluation 결과 ?라고 하자.
  5. 그렇지 않으면,
    1. rRefAssignmentExpressionEvaluation 결과 ?라고 하자.
    2. rVal를 ? GetValue(rRef)라고 하자.
  6. PutValue(lRef, rVal)를 수행한다.
  7. rVal를 반환한다.
AssignmentExpression : LeftHandSideExpression ||= AssignmentExpression
  1. lRefLeftHandSideExpressionEvaluation 결과 ?라고 하자.
  2. lVal를 ? GetValue(lRef)라고 하자.
  3. ToBoolean(lVal)가 true이면, lVal를 반환한다.
  4. IsAnonymousFunctionDefinition(AssignmentExpression)이 true이고 IsIdentifierRef of LeftHandSideExpressiontrue이면,
    1. lhsLeftHandSideExpressionStringValue라고 하자.
    2. rVal를 인수 lhs를 사용한 AssignmentExpressionNamedEvaluation 결과 ?라고 하자.
  5. 그렇지 않으면,
    1. rRefAssignmentExpressionEvaluation 결과 ?라고 하자.
    2. rVal를 ? GetValue(rRef)라고 하자.
  6. PutValue(lRef, rVal)를 수행한다.
  7. rVal를 반환한다.
AssignmentExpression : LeftHandSideExpression ??= AssignmentExpression
  1. lRefLeftHandSideExpressionEvaluation 결과 ?라고 하자.
  2. lVal를 ? GetValue(lRef)라고 하자.
  3. lValundefined도 아니고 null도 아니면, lVal를 반환한다.
  4. IsAnonymousFunctionDefinition(AssignmentExpression)이 true이고 IsIdentifierRef of LeftHandSideExpressiontrue이면,
    1. lhsLeftHandSideExpressionStringValue라고 하자.
    2. rVal를 인수 lhs를 사용한 AssignmentExpressionNamedEvaluation 결과 ?라고 하자.
  5. 그렇지 않으면,
    1. rRefAssignmentExpressionEvaluation 결과 ?라고 하자.
    2. rVal를 ? GetValue(rRef)라고 하자.
  6. PutValue(lRef, rVal)를 수행한다.
  7. rVal를 반환한다.
Note

이 표현식이 strict mode 코드 안에 나타날 때, 단계 1.e, 3, 2, 2, 2에서의 lRef가 해석 불가능한 참조이면 런타임 오류이다. 그런 경우 ReferenceError 예외가 던져진다. 또한 단계 9, 6, 6, 6에서의 lRef가 { [[Writable]]: false } 속성 값을 가진 데이터 프로퍼티, { [[Set]]: undefined } 속성 값을 가진 접근자 프로퍼티, 또는 IsExtensible 판정이 false를 반환하는 객체의 존재하지 않는 프로퍼티에 대한 참조이면 런타임 오류이다. 이 경우 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 either a normal completion containing either a String, a BigInt, or a Number, or a throw completion. It performs the following steps when called:

  1. opText+이면,
    1. 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 예외를 던진다.
  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. Assert: 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.a1.b에서 ToPrimitive 호출에는 힌트가 제공되지 않는다. Date를 제외한 모든 표준 객체는 힌트가 없는 경우 number가 주어진 것처럼 처리한다; Date는 힌트가 없는 경우 string이 주어진 것처럼 처리한다. 이색 객체는 힌트의 부재를 다른 방식으로 처리할 수 있다.

Note 2

단계 1.c는 논리곱 대신 논리합 연산을 사용한다는 점에서 IsLessThan 알고리즘의 단계 3와 다르다.

13.15.4 EvaluateStringOrNumericBinaryExpression ( leftOperand, opText, rightOperand )

The abstract operation EvaluateStringOrNumericBinaryExpression takes arguments leftOperand (a Parse Node), opText (**, *, /, %, +, -, <<, >>, >>>, &, ^, or |), and rightOperand (a Parse Node) and returns either a normal completion containing either a String, a BigInt, or a Number, or an abrupt completion. It performs the following steps when called:

  1. lRefleftOperandEvaluation 결과 ?라고 하자.
  2. lVal를 ? GetValue(lRef)라고 하자.
  3. rRefrightOperandEvaluation 결과 ?라고 하자.
  4. rVal를 ? GetValue(rRef)라고 하자.
  5. ApplyStringOrNumericBinaryOperator(lVal, opText, rVal)를 반환한다.

13.15.5 구조 분해 대입

보충 구문

특정 상황에서 production의 인스턴스를 처리할 때
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 Runtime Semantics: DestructuringAssignmentEvaluation

The syntax-directed operation DestructuringAssignmentEvaluation takes argument value (an ECMAScript language value) and returns either a normal completion containing unused or an abrupt completion. It is defined piecewise over the following productions:

ObjectAssignmentPattern : { }
  1. RequireObjectCoercible(value)를 수행한다.
  2. unused를 반환한다.
ObjectAssignmentPattern : { AssignmentPropertyList } { AssignmentPropertyList , }
  1. RequireObjectCoercible(value)를 수행한다.
  2. 인수 value를 사용한 AssignmentPropertyListPropertyDestructuringAssignmentEvaluation을 ? 수행한다.
  3. unused를 반환한다.
ObjectAssignmentPattern : { AssignmentRestProperty }
  1. RequireObjectCoercible(value)를 수행한다.
  2. excludedNames를 새로운 빈 List라고 하자.
  3. 인수 valueexcludedNames를 사용한 AssignmentRestPropertyRestDestructuringAssignmentEvaluation을 ? 반환한다.
ObjectAssignmentPattern : { AssignmentPropertyList , AssignmentRestProperty }
  1. RequireObjectCoercible(value)를 수행한다.
  2. excludedNames를 인수 value를 사용한 AssignmentPropertyListPropertyDestructuringAssignmentEvaluation 결과 ?라고 하자.
  3. 인수 valueexcludedNames를 사용한 AssignmentRestPropertyRestDestructuringAssignmentEvaluation을 ? 반환한다.
ArrayAssignmentPattern : [ ]
  1. iteratorRecord를 ? GetIterator(value, sync)라고 하자.
  2. IteratorClose(iteratorRecord, NormalCompletion(unused))를 반환한다.
ArrayAssignmentPattern : [ Elision ]
  1. iteratorRecord를 ? GetIterator(value, sync)라고 하자.
  2. result를 인수 iteratorRecord를 사용한 ElisionIteratorDestructuringAssignmentEvaluationCompletion이라고 하자.
  3. iteratorRecord.[[Done]]false이면, ? IteratorClose(iteratorRecord, result)를 반환한다.
  4. result를 반환한다.
ArrayAssignmentPattern : [ Elisionopt AssignmentRestElement ]
  1. iteratorRecord를 ? GetIterator(value, sync)라고 하자.
  2. Elision이 존재하면,
    1. status를 인수 iteratorRecord를 사용한 ElisionIteratorDestructuringAssignmentEvaluationCompletion이라고 하자.
    2. statusabrupt completion이면,
      1. Assert: iteratorRecord.[[Done]]true이다.
      2. status를 반환한다.
  3. result를 인수 iteratorRecord를 사용한 AssignmentRestElementIteratorDestructuringAssignmentEvaluationCompletion이라고 하자.
  4. iteratorRecord.[[Done]]false이면, ? IteratorClose(iteratorRecord, result)를 반환한다.
  5. result를 반환한다.
ArrayAssignmentPattern : [ AssignmentElementList ]
  1. iteratorRecord를 ? GetIterator(value, sync)라고 하자.
  2. result를 인수 iteratorRecord를 사용한 AssignmentElementListIteratorDestructuringAssignmentEvaluationCompletion이라고 하자.
  3. iteratorRecord.[[Done]]false이면, ? IteratorClose(iteratorRecord, result)를 반환한다.
  4. result를 반환한다.
ArrayAssignmentPattern : [ AssignmentElementList , Elisionopt AssignmentRestElementopt ]
  1. iteratorRecord를 ? GetIterator(value, sync)라고 하자.
  2. status를 인수 iteratorRecord를 사용한 AssignmentElementListIteratorDestructuringAssignmentEvaluationCompletion이라고 하자.
  3. statusabrupt completion이면,
    1. iteratorRecord.[[Done]]false이면, ? IteratorClose(iteratorRecord, status)를 반환한다.
    2. status를 반환한다.
  4. Elision이 존재하면,
    1. status를 인수 iteratorRecord를 사용한 ElisionIteratorDestructuringAssignmentEvaluationCompletion으로 설정한다.
    2. statusabrupt completion이면,
      1. Assert: iteratorRecord.[[Done]]true이다.
      2. status를 반환한다.
  5. AssignmentRestElement이 존재하면,
    1. status를 인수 iteratorRecord를 사용한 AssignmentRestElementIteratorDestructuringAssignmentEvaluationCompletion으로 설정한다.
  6. iteratorRecord.[[Done]]false이면, ? IteratorClose(iteratorRecord, status)를 반환한다.
  7. status를 반환한다.

13.15.5.3 Runtime Semantics: PropertyDestructuringAssignmentEvaluation

The syntax-directed operation PropertyDestructuringAssignmentEvaluation takes argument value (an ECMAScript language value) and returns either a normal completion containing a List of property keys or an abrupt completion. 이것은 구조 분해된 모든 프로퍼티 키의 리스트를 수집한다. It is defined piecewise over the following productions:

AssignmentPropertyList : AssignmentPropertyList , AssignmentProperty
  1. propertyNames를 인수 value를 사용한 AssignmentPropertyListPropertyDestructuringAssignmentEvaluation 결과 ?라고 하자.
  2. nextNames를 인수 value를 사용한 AssignmentPropertyPropertyDestructuringAssignmentEvaluation 결과 ?라고 하자.
  3. propertyNamesnextNameslist-concatenation을 반환한다.
AssignmentProperty : IdentifierReference Initializeropt
  1. propertyNameIdentifierReferenceStringValue라고 하자.
  2. lRef를 ? ResolveBinding(propertyName)이라고 하자.
  3. v를 ? GetV(value, propertyName)라고 하자.
  4. Initializer가 존재하고 vundefined이면,
    1. IsAnonymousFunctionDefinition(Initializer)이 true이면,
      1. v를 인수 propertyName을 사용한 InitializerNamedEvaluation 결과 ?로 설정한다.
    2. 그렇지 않으면,
      1. defaultValueInitializerEvaluation 결과 ?라고 하자.
      2. v를 ? GetValue(defaultValue)로 설정한다.
  5. PutValue(lRef, v)를 수행한다.
  6. « propertyName »를 반환한다.
AssignmentProperty : PropertyName : AssignmentElement
  1. namePropertyNameEvaluation 결과 ?라고 하자.
  2. 인수 valuename을 사용한 AssignmentElementKeyedDestructuringAssignmentEvaluation을 ? 수행한다.
  3. « name »를 반환한다.

13.15.5.4 Runtime Semantics: RestDestructuringAssignmentEvaluation

The syntax-directed operation RestDestructuringAssignmentEvaluation takes arguments value (an ECMAScript language value) and excludedNames (a List of property keys) and returns either a normal completion containing unused or an abrupt completion. It is defined piecewise over the following productions:

AssignmentRestProperty : ... DestructuringAssignmentTarget
  1. lRefDestructuringAssignmentTargetEvaluation 결과 ?라고 하자.
  2. restObjOrdinaryObjectCreate(%Object.prototype%)라고 하자.
  3. CopyDataProperties(restObj, value, excludedNames)를 수행한다.
  4. PutValue(lRef, restObj)를 반환한다.

13.15.5.5 Runtime Semantics: IteratorDestructuringAssignmentEvaluation

The syntax-directed operation IteratorDestructuringAssignmentEvaluation takes argument iteratorRecord (an Iterator Record) and returns either a normal completion containing unused or an abrupt completion. It is defined piecewise over the following productions:

AssignmentElementList : AssignmentElisionElement
  1. 인수 iteratorRecord를 사용한 AssignmentElisionElementIteratorDestructuringAssignmentEvaluation을 ? 반환한다.
AssignmentElementList : AssignmentElementList , AssignmentElisionElement
  1. 인수 iteratorRecord를 사용한 AssignmentElementListIteratorDestructuringAssignmentEvaluation을 ? 수행한다.
  2. 인수 iteratorRecord를 사용한 AssignmentElisionElementIteratorDestructuringAssignmentEvaluation을 ? 반환한다.
AssignmentElisionElement : AssignmentElement
  1. 인수 iteratorRecord를 사용한 AssignmentElementIteratorDestructuringAssignmentEvaluation을 ? 반환한다.
AssignmentElisionElement : Elision AssignmentElement
  1. 인수 iteratorRecord를 사용한 ElisionIteratorDestructuringAssignmentEvaluation을 ? 수행한다.
  2. 인수 iteratorRecord를 사용한 AssignmentElementIteratorDestructuringAssignmentEvaluation을 ? 반환한다.
Elision : ,
  1. iteratorRecord.[[Done]]false이면,
    1. IteratorStep(iteratorRecord)를 수행한다.
  2. unused를 반환한다.
Elision : Elision ,
  1. 인수 iteratorRecord를 사용한 ElisionIteratorDestructuringAssignmentEvaluation을 ? 수행한다.
  2. iteratorRecord.[[Done]]false이면,
    1. IteratorStep(iteratorRecord)를 수행한다.
  3. unused를 반환한다.
AssignmentElement : DestructuringAssignmentTarget Initializeropt
  1. DestructuringAssignmentTargetObjectLiteral도 아니고 ArrayLiteral도 아니면,
    1. lRefDestructuringAssignmentTargetEvaluation 결과 ?라고 하자.
  2. valueundefined라고 하자.
  3. iteratorRecord.[[Done]]false이면,
    1. next를 ? IteratorStepValue(iteratorRecord)라고 하자.
    2. nextdone가 아니면,
      1. valuenext로 설정한다.
  4. Initializer가 존재하고 valueundefined이면,
    1. IsAnonymousFunctionDefinition(Initializer)이 true이고 IsIdentifierRef of DestructuringAssignmentTargettrue이면,
      1. targetDestructuringAssignmentTargetStringValue라고 하자.
      2. v를 인수 target을 사용한 InitializerNamedEvaluation 결과 ?라고 하자.
    2. 그렇지 않으면,
      1. defaultValueInitializerEvaluation 결과 ?라고 하자.
      2. v를 ? GetValue(defaultValue)라고 하자.
  5. 그렇지 않으면,
    1. vvalue라고 하자.
  6. DestructuringAssignmentTargetObjectLiteral 또는 ArrayLiteral 중 하나이면,
    1. nestedAssignmentPatternDestructuringAssignmentTarget이 커버하는 AssignmentPattern이라고 하자.
    2. 인수 v를 사용한 nestedAssignmentPatternDestructuringAssignmentEvaluation을 ? 반환한다.
  7. PutValue(lRef, v)를 반환한다.
Note

좌에서 우로의 평가 순서는, 구조 분해 패턴이 아닌 DestructuringAssignmentTarget을 이터레이터 접근이나 Initializer 평가보다 먼저 평가함으로써 유지된다.

AssignmentRestElement : ... DestructuringAssignmentTarget
  1. DestructuringAssignmentTargetObjectLiteral도 아니고 ArrayLiteral도 아니면,
    1. lRefDestructuringAssignmentTargetEvaluation 결과 ?라고 하자.
  2. array를 ! ArrayCreate(0)라고 하자.
  3. n을 0이라고 하자.
  4. iteratorRecord.[[Done]]false인 동안, 다음을 반복한다
    1. next를 ? IteratorStepValue(iteratorRecord)라고 하자.
    2. nextdone가 아니면,
      1. CreateDataPropertyOrThrow(array, ! ToString(𝔽(n)), next)를 수행한다.
      2. nn + 1로 설정한다.
  5. DestructuringAssignmentTargetObjectLiteral도 아니고 ArrayLiteral도 아니면,
    1. PutValue(lRef, array)를 반환한다.
  6. nestedAssignmentPatternDestructuringAssignmentTarget이 커버하는 AssignmentPattern이라고 하자.
  7. 인수 array를 사용한 nestedAssignmentPatternDestructuringAssignmentEvaluation을 ? 반환한다.

13.15.5.6 Runtime Semantics: KeyedDestructuringAssignmentEvaluation

The syntax-directed operation KeyedDestructuringAssignmentEvaluation takes arguments value (an ECMAScript language value) and propertyName (a property key) and returns either a normal completion containing unused or an abrupt completion. It is defined piecewise over the following productions:

AssignmentElement : DestructuringAssignmentTarget Initializeropt
  1. DestructuringAssignmentTargetObjectLiteral도 아니고 ArrayLiteral도 아니면,
    1. lRefDestructuringAssignmentTargetEvaluation 결과 ?라고 하자.
  2. v를 ? GetV(value, propertyName)라고 하자.
  3. Initializer가 존재하고 vundefined이면,
    1. IsAnonymousFunctionDefinition(Initializer)이 true이고 IsIdentifierRef of DestructuringAssignmentTargettrue이면,
      1. targetDestructuringAssignmentTargetStringValue라고 하자.
      2. rhsValue를 인수 target을 사용한 InitializerNamedEvaluation 결과 ?라고 하자.
    2. 그렇지 않으면,
      1. defaultValueInitializerEvaluation 결과 ?라고 하자.
      2. rhsValue를 ? GetValue(defaultValue)라고 하자.
  4. 그렇지 않으면,
    1. rhsValuev라고 하자.
  5. DestructuringAssignmentTargetObjectLiteral 또는 ArrayLiteral 중 하나이면,
    1. assignmentPatternDestructuringAssignmentTarget이 커버하는 AssignmentPattern이라고 하자.
    2. 인수 rhsValue를 사용한 assignmentPatternDestructuringAssignmentEvaluation을 ? 반환한다.
  6. PutValue(lRef, rhsValue)를 반환한다.

13.16 콤마 연산자 ( , )

구문

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. lRefExpressionEvaluation 결과 ?라고 하자.
  2. GetValue(lRef)를 수행한다.
  3. rRefAssignmentExpressionEvaluation 결과 ?라고 하자.
  4. GetValue(rRef)를 반환한다.
Note

GetValue의 값은 사용되지 않더라도 관찰 가능한 부작용이 있을 수 있으므로 반드시 호출해야 한다.

14 ECMAScript 언어: 문장과 선언

구문

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 문장 의미론

14.1.1 Runtime Semantics: Evaluation

HoistableDeclaration : GeneratorDeclaration AsyncFunctionDeclaration AsyncGeneratorDeclaration
  1. empty를 반환한다.
HoistableDeclaration : FunctionDeclaration
  1. FunctionDeclarationEvaluation을 ? 반환한다.
BreakableStatement : IterationStatement SwitchStatement
  1. newLabelSet을 새로운 빈 List라고 하자.
  2. 인수 newLabelSet을 사용한 this BreakableStatementLabelledEvaluation을 ? 반환한다.

14.2 블록

구문

BlockStatement[Yield, Await, Return] : Block[?Yield, ?Await, ?Return] Block[Yield, Await, Return] : { StatementList[?Yield, ?Await, ?Return]opt } StatementList[Yield, Await, Return] : StatementListItem[?Yield, ?Await, ?Return] StatementList[?Yield, ?Await, ?Return] StatementListItem[?Yield, ?Await, ?Return] StatementListItem[Yield, Await, Return] : Statement[?Yield, ?Await, ?Return] Declaration[?Yield, ?Await]

14.2.1 Static Semantics: Early Errors

Block : { StatementList }

14.2.2 Runtime Semantics: Evaluation

Block : { }
  1. empty를 반환한다.
Block : { StatementList }
  1. oldEnv를 현재 실행 중인 execution context의 LexicalEnvironment라고 하자.
  2. blockEnvNewDeclarativeEnvironment(oldEnv)라고 하자.
  3. BlockDeclarationInstantiation(StatementList, blockEnv)를 수행한다.
  4. 현재 실행 중인 execution context의 LexicalEnvironment를 blockEnv로 설정한다.
  5. blockValueCompletion(Evaluation of StatementList)라고 하자.
  6. 현재 실행 중인 execution context의 LexicalEnvironment를 oldEnv로 설정한다.
  7. blockValue를 반환한다.
Note 1

제어가 Block을 어떤 방식으로 떠나더라도 LexicalEnvironment는 항상 이전 상태로 복원된다.

StatementList : StatementList StatementListItem
  1. slStatementListEvaluation 결과 ?라고 하자.
  2. sCompletion(Evaluation of StatementListItem)라고 하자.
  3. UpdateEmpty(s, sl)를 반환한다.
Note 2

StatementList의 값은 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. declarationscodeLexicallyScopedDeclarations라고 하자.
  2. privateEnv를 현재 실행 중인 execution context의 PrivateEnvironment라고 하자.
  3. declarations의 각 요소 decl에 대해, 다음을 수행한다
    1. declBoundNames의 각 요소 dn에 대해, 다음을 수행한다
      1. declIsConstantDeclarationtrue이면,
        1. env.CreateImmutableBinding(dn, true)를 수행한다.
      2. 그렇지 않으면,
        1. Normative Optional
          호스트가 웹 브라우저이거나 또는 Block-Level Function Declaration 웹 Legacy 호환성 의미론를 지원하면,
          1. env.HasBinding(dn)이 false이면,
            1. env.CreateMutableBinding(dn, false)를 수행한다.
        2. 그렇지 않으면,
          1. env.CreateMutableBinding(dn, false)를 수행한다.
    2. declFunctionDeclaration, GeneratorDeclaration, AsyncFunctionDeclaration, AsyncGeneratorDeclaration 중 하나이면,
      1. fndeclBoundNames의 유일한 요소라고 하자.
      2. fo를 인수 envprivateEnv를 사용한 declInstantiateFunctionObject라고 하자.
      3. Normative Optional
        호스트가 웹 브라우저이거나 또는 Block-Level Function Declaration 웹 Legacy 호환성 의미론를 지원하면,
        1. env 안의 fn에 대한 바인딩이 초기화되지 않은 바인딩이면,
          1. env.InitializeBinding(fn, fo)를 수행한다.
        2. 그렇지 않으면,
          1. Assert: declFunctionDeclaration이다.
          2. env.SetMutableBinding(fn, fo, false)를 수행한다.
      4. 그렇지 않으면,
        1. env.InitializeBinding(fn, fo)를 수행한다.
  4. unused를 반환한다.

14.3 선언과 변수 문장

14.3.1 Let 및 Const 선언

Note

letconst 선언은 현재 실행 중인 execution context의 LexicalEnvironment에 스코프를 가지는 변수를 정의한다. 변수들은 자신을 포함하는 Environment Record가 구체화될 때 생성되지만, 변수의 LexicalBinding이 평가되기 전까지는 어떤 방식으로도 접근할 수 없다. Initializer를 가진 LexicalBinding에 의해 정의된 변수는 변수가 생성될 때가 아니라 LexicalBinding이 평가될 때 자신의 InitializerAssignmentExpression 값을 할당받는다. let 선언 안의 LexicalBindingInitializer가 없으면, 그 변수는 LexicalBinding이 평가될 때 값 undefined를 할당받는다.

구문

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 Static Semantics: Early Errors

LexicalDeclaration : LetOrConst BindingList ; LexicalBinding : BindingIdentifier Initializeropt

14.3.1.2 Runtime Semantics: Evaluation

LexicalDeclaration : LetOrConst BindingList ;
  1. BindingListEvaluation을 ? 수행한다.
  2. empty를 반환한다.
BindingList : BindingList , LexicalBinding
  1. BindingListEvaluation을 ? 수행한다.
  2. LexicalBindingEvaluation을 ? 반환한다.
LexicalBinding : BindingIdentifier
  1. lhs를 ! ResolveBinding(StringValue of BindingIdentifier) 라고 하자.
  2. InitializeReferencedBinding(lhs, undefined)를 수행한다.
  3. empty를 반환한다.
Note

정적 의미론 규칙에 의해, 이 형태의 LexicalBindingconst 선언에서는 결코 나타나지 않음이 보장된다.

LexicalBinding : BindingIdentifier Initializer
  1. bindingIdBindingIdentifierStringValue라고 하자.
  2. lhs를 ! ResolveBinding(bindingId)라고 하자.
  3. IsAnonymousFunctionDefinition(Initializer)가 true이면,
    1. value를 인수 bindingId를 사용한 InitializerNamedEvaluation 결과 ?라고 하자.
  4. 그렇지 않으면,
    1. rhsInitializerEvaluation 결과 ?라고 하자.
    2. value를 ? GetValue(rhs)라고 하자.
  5. InitializeReferencedBinding(lhs, value)를 수행한다.
  6. empty를 반환한다.
LexicalBinding : BindingPattern Initializer
  1. rhsInitializerEvaluation 결과 ?라고 하자.
  2. value를 ? GetValue(rhs)라고 하자.
  3. env를 현재 실행 중인 execution context의 LexicalEnvironment라고 하자.
  4. 인수 valueenv를 사용한 BindingPatternBindingInitialization을 ? 반환한다.

14.3.2 변수 문장

Note

var 문장은 현재 실행 중인 execution context의 VariableEnvironment에 스코프를 가지는 변수를 선언한다. Var 변수는 자신을 포함하는 Environment Record가 구체화될 때 생성되며, 생성될 때 undefined로 초기화된다. 어떤 VariableEnvironment의 스코프 안에서는 동일한 BindingIdentifier가 둘 이상의 VariableDeclaration에 나타날 수 있지만, 그 선언들은 합쳐서 오직 하나의 변수만을 정의한다. Initializer를 가진 VariableDeclaration에 의해 정의된 변수는 변수가 생성될 때가 아니라 VariableDeclaration이 실행될 때 자신의 InitializerAssignmentExpression 값을 할당받는다.

구문

VariableStatement[Yield, Await] : var VariableDeclarationList[+In, ?Yield, ?Await] ; VariableDeclarationList[In, Yield, Await] : VariableDeclaration[?In, ?Yield, ?Await] VariableDeclarationList[?In, ?Yield, ?Await] , VariableDeclaration[?In, ?Yield, ?Await] VariableDeclaration[In, Yield, Await] : BindingIdentifier[?Yield, ?Await] Initializer[?In, ?Yield, ?Await]opt BindingPattern[?Yield, ?Await] Initializer[?In, ?Yield, ?Await]

14.3.2.1 Runtime Semantics: Evaluation

VariableStatement : var VariableDeclarationList ;
  1. VariableDeclarationListEvaluation을 ? 수행한다.
  2. empty를 반환한다.
VariableDeclarationList : VariableDeclarationList , VariableDeclaration
  1. VariableDeclarationListEvaluation을 ? 수행한다.
  2. VariableDeclarationEvaluation을 ? 반환한다.
VariableDeclaration : BindingIdentifier
  1. empty를 반환한다.
VariableDeclaration : BindingIdentifier Initializer
  1. bindingIdBindingIdentifierStringValue라고 하자.
  2. lhs를 ? ResolveBinding(bindingId)이라고 하자.
  3. IsAnonymousFunctionDefinition(Initializer)가 true이면,
    1. value를 인수 bindingId를 사용한 InitializerNamedEvaluation 결과 ?라고 하자.
  4. 그렇지 않으면,
    1. rhsInitializerEvaluation 결과 ?라고 하자.
    2. value를 ? GetValue(rhs)라고 하자.
  5. PutValue(lhs, value)를 수행한다.
  6. empty를 반환한다.
Note

VariableDeclaration이 with 문 안에 중첩되어 있고, VariableDeclaration 안의 BindingIdentifier가 with 문의 Object Environment Record의 바인딩 객체의 프로퍼티 이름과 같다면, 단계 5valueIdentifier의 VariableEnvironment 바인딩에 할당하는 대신 그 프로퍼티에 할당한다.

VariableDeclaration : BindingPattern Initializer
  1. rhsInitializerEvaluation 결과 ?라고 하자.
  2. rVal를 ? GetValue(rhs)라고 하자.
  3. 인수 rValundefined를 사용한 BindingPatternBindingInitialization을 ? 반환한다.

14.3.3 구조 분해 바인딩 패턴

구문

BindingPattern[Yield, Await] : ObjectBindingPattern[?Yield, ?Await] ArrayBindingPattern[?Yield, ?Await] ObjectBindingPattern[Yield, Await] : { } { BindingRestProperty[?Yield, ?Await] } { BindingPropertyList[?Yield, ?Await] } { BindingPropertyList[?Yield, ?Await] , BindingRestProperty[?Yield, ?Await]opt } ArrayBindingPattern[Yield, Await] : [ Elisionopt BindingRestElement[?Yield, ?Await]opt ] [ BindingElementList[?Yield, ?Await] ] [ BindingElementList[?Yield, ?Await] , Elisionopt BindingRestElement[?Yield, ?Await]opt ] BindingRestProperty[Yield, Await] : ... BindingIdentifier[?Yield, ?Await] BindingPropertyList[Yield, Await] : BindingProperty[?Yield, ?Await] BindingPropertyList[?Yield, ?Await] , BindingProperty[?Yield, ?Await] BindingElementList[Yield, Await] : BindingElisionElement[?Yield, ?Await] BindingElementList[?Yield, ?Await] , BindingElisionElement[?Yield, ?Await] BindingElisionElement[Yield, Await] : Elisionopt BindingElement[?Yield, ?Await] BindingProperty[Yield, Await] : SingleNameBinding[?Yield, ?Await] PropertyName[?Yield, ?Await] : BindingElement[?Yield, ?Await] BindingElement[Yield, Await] : SingleNameBinding[?Yield, ?Await] BindingPattern[?Yield, ?Await] Initializer[+In, ?Yield, ?Await]opt SingleNameBinding[Yield, Await] : BindingIdentifier[?Yield, ?Await] Initializer[+In, ?Yield, ?Await]opt BindingRestElement[Yield, Await] : ... BindingIdentifier[?Yield, ?Await] ... BindingPattern[?Yield, ?Await]

14.3.3.1 Runtime Semantics: PropertyBindingInitialization

The syntax-directed operation PropertyBindingInitialization takes arguments value (an ECMAScript language value) and environment (an Environment Record or undefined) and returns either a normal completion containing a List of property keys or an abrupt completion. 이것은 바인딩된 모든 프로퍼티 이름의 리스트를 수집한다. It is defined piecewise over the following productions:

BindingPropertyList : BindingPropertyList , BindingProperty
  1. boundNames를 인수 valueenvironment를 사용한 BindingPropertyListPropertyBindingInitialization 결과 ?라고 하자.
  2. nextNames를 인수 valueenvironment를 사용한 BindingPropertyPropertyBindingInitialization 결과 ?라고 하자.
  3. boundNamesnextNameslist-concatenation을 반환한다.
BindingProperty : SingleNameBinding
  1. nameSingleNameBindingBoundNames의 유일한 요소라고 하자.
  2. 인수 value, environment, name을 사용한 SingleNameBindingKeyedBindingInitialization을 ? 수행한다.
  3. « name »를 반환한다.
BindingProperty : PropertyName : BindingElement
  1. propertyKeyPropertyNameEvaluation 결과 ?라고 하자.
  2. 인수 value, environment, propertyKey를 사용한 BindingElementKeyedBindingInitialization을 ? 수행한다.
  3. « propertyKey »를 반환한다.

14.3.3.2 Runtime Semantics: RestBindingInitialization

The syntax-directed operation RestBindingInitialization takes arguments value (an ECMAScript language value), environment (an Environment Record or undefined), and excludedNames (a List of property keys) and returns either a normal completion containing unused or an abrupt completion. It is defined piecewise over the following productions:

BindingRestProperty : ... BindingIdentifier
  1. lhs를 ? ResolveBinding(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 Runtime Semantics: KeyedBindingInitialization

The syntax-directed operation KeyedBindingInitialization takes arguments value (an ECMAScript language value), environment (an Environment Record or undefined), and propertyName (a property key) and returns either a normal completion containing unused or an abrupt completion.

Note

environmentundefined가 전달되면, 초기화 값을 할당하기 위해 PutValue 연산을 사용해야 함을 나타낸다. 이것은 non-strict 함수의 형식 매개변수 목록의 경우이다. 그 경우, 같은 이름을 가진 여러 매개변수의 가능성을 처리하기 위해 형식 매개변수 바인딩은 미리 초기화된다.

It is defined piecewise over the following productions:

BindingElement : BindingPattern Initializeropt
  1. v를 ? GetV(value, propertyName)라고 하자.
  2. Initializer가 존재하고 vundefined이면,
    1. defaultValueInitializerEvaluation 결과 ?라고 하자.
    2. v를 ? GetValue(defaultValue)로 설정한다.
  3. 인수 venvironment를 사용한 BindingPatternBindingInitialization을 ? 반환한다.
SingleNameBinding : BindingIdentifier Initializeropt
  1. bindingIdBindingIdentifierStringValue라고 하자.
  2. lhs를 ? ResolveBinding(bindingId, environment)라고 하자.
  3. v를 ? GetV(value, propertyName)라고 하자.
  4. Initializer가 존재하고 vundefined이면,
    1. IsAnonymousFunctionDefinition(Initializer)가 true이면,
      1. v를 인수 bindingId를 사용한 InitializerNamedEvaluation 결과 ?로 설정한다.
    2. 그렇지 않으면,
      1. defaultValueInitializerEvaluation 결과 ?라고 하자.
      2. v를 ? GetValue(defaultValue)로 설정한다.
  5. environmentundefined이면, ? PutValue(lhs, v)를 반환한다.
  6. InitializeReferencedBinding(lhs, v)를 반환한다.

14.4 빈 문장

구문

EmptyStatement : ;

14.4.1 Runtime Semantics: Evaluation

EmptyStatement : ;
  1. empty를 반환한다.

14.5 표현식 문장

구문

ExpressionStatement[Yield, Await] : [lookahead ∉ { {, function, async [no LineTerminator here] function, class, let [ }] Expression[+In, ?Yield, ?Await] ; Note

ExpressionStatement는 U+007B (LEFT CURLY BRACKET)로 시작할 수 없는데, 그러면 Block과 모호해질 수 있기 때문이다. ExpressionStatementfunction 또는 class 키워드로 시작할 수 없는데, 그러면 FunctionDeclaration, GeneratorDeclaration, 또는 ClassDeclaration과 모호해지기 때문이다. ExpressionStatementasync function으로 시작할 수 없는데, 그러면 AsyncFunctionDeclaration 또는 AsyncGeneratorDeclaration과 모호해지기 때문이다. ExpressionStatement는 두 토큰 시퀀스 let [로 시작할 수 없는데, 그러면 첫 번째 LexicalBindingArrayBindingPatternlet LexicalDeclaration과 모호해지기 때문이다.

14.5.1 Runtime Semantics: Evaluation

ExpressionStatement : Expression ;
  1. exprRefExpressionEvaluation 결과 ?라고 하자.
  2. GetValue(exprRef)를 반환한다.

14.6 if

구문

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 ≠ else] 선행탐색 제한은 고전적인 "dangling else" 문제를 통상적인 방식으로 해결한다. 즉, 연관된 if의 선택이 달리 모호할 때, else는 후보 if들 중 가장 가까운(가장 안쪽의) 것과 연관된다

14.6.1 Static Semantics: Early Errors

IfStatement : if ( Expression ) Statement else Statement IfStatement : if ( Expression ) Statement Note

이 규칙은 B.3.1에 명시된 확장이 구현된 경우에만 적용할 필요가 있다.

14.6.2 Runtime Semantics: Evaluation

IfStatement : if ( Expression ) Statement else Statement
  1. exprRefExpressionEvaluation 결과 ?라고 하자.
  2. exprValueToBoolean(? GetValue(exprRef))라고 하자.
  3. exprValuetrue이면,
    1. stmtCompletion을 첫 번째 StatementEvaluationCompletion이라고 하자.
  4. 그렇지 않으면,
    1. stmtCompletion을 두 번째 StatementEvaluationCompletion이라고 하자.
  5. UpdateEmpty(stmtCompletion, undefined)를 반환한다.
IfStatement : if ( Expression ) Statement
  1. exprRefExpressionEvaluation 결과 ?라고 하자.
  2. exprValueToBoolean(? GetValue(exprRef))라고 하자.
  3. exprValuefalse이면 undefined를 반환한다.
  4. stmtCompletionStatementEvaluationCompletion이라고 하자.
  5. UpdateEmpty(stmtCompletion, undefined)를 반환한다.

14.7 반복 문

구문

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. completionnormal completion이면 true를 반환한다.
  2. completioncontinue completion이 아니면 false를 반환한다.
  3. completion.[[Target]]empty이면 true를 반환한다.
  4. labelSetcompletion.[[Target]]을 포함하면 true를 반환한다.
  5. false를 반환한다.
Note

IterationStatementStatement 부분 안에서는 ContinueStatement를 사용해 새로운 반복을 시작할 수 있다.

14.7.1.2 Runtime Semantics: LoopEvaluation

The syntax-directed operation LoopEvaluation takes argument labelSet (a List of Strings) and returns either a normal completion containing an ECMAScript language value or an abrupt completion. It is defined piecewise over the following productions:

IterationStatement : DoWhileStatement
  1. 인수 labelSet을 사용한 DoWhileStatementDoWhileLoopEvaluation을 ? 반환한다.
IterationStatement : WhileStatement
  1. 인수 labelSet을 사용한 WhileStatementWhileLoopEvaluation을 ? 반환한다.
IterationStatement : ForStatement
  1. 인수 labelSet을 사용한 ForStatementForLoopEvaluation을 ? 반환한다.
IterationStatement : ForInOfStatement
  1. 인수 labelSet을 사용한 ForInOfStatementForInOfLoopEvaluation을 ? 반환한다.

14.7.2 do-while

구문

DoWhileStatement[Yield, Await, Return] : do Statement[?Yield, ?Await, ?Return] while ( Expression[+In, ?Yield, ?Await] ) ;

14.7.2.1 Static Semantics: Early Errors

DoWhileStatement : do Statement while ( Expression ) ; Note

이 규칙은 B.3.1에 명시된 확장이 구현된 경우에만 적용할 필요가 있다.

14.7.2.2 Runtime Semantics: DoWhileLoopEvaluation

The syntax-directed operation DoWhileLoopEvaluation takes argument labelSet (a List of Strings) and returns either a normal completion containing an ECMAScript language value or an abrupt completion. It is defined piecewise over the following productions:

DoWhileStatement : do Statement while ( Expression ) ;
  1. iterationResultundefined라고 하자.
  2. 반복한다,
    1. stmtResultStatementEvaluationCompletion이라고 하자.
    2. LoopContinues(stmtResult, labelSet)가 false이면, ? UpdateEmpty(stmtResult, iterationResult)를 반환한다.
    3. stmtResult.[[Value]]empty가 아니면, iterationResultstmtResult.[[Value]]로 설정한다.
    4. exprRefExpressionEvaluation 결과 ?라고 하자.
    5. exprValue를 ? GetValue(exprRef)라고 하자.
    6. ToBoolean(exprValue)가 false이면, iterationResult를 반환한다.

14.7.3 while

구문

WhileStatement[Yield, Await, Return] : while ( Expression[+In, ?Yield, ?Await] ) Statement[?Yield, ?Await, ?Return]

14.7.3.1 Static Semantics: Early Errors

WhileStatement : while ( Expression ) Statement Note

이 규칙은 B.3.1에 명시된 확장이 구현된 경우에만 적용할 필요가 있다.

14.7.3.2 Runtime Semantics: WhileLoopEvaluation

The syntax-directed operation WhileLoopEvaluation takes argument labelSet (a List of Strings) and returns either a normal completion containing an ECMAScript language value or an abrupt completion. It is defined piecewise over the following productions:

WhileStatement : while ( Expression ) Statement
  1. iterationResultundefined라고 하자.
  2. 반복한다,
    1. exprRefExpressionEvaluation 결과 ?라고 하자.
    2. exprValue를 ? GetValue(exprRef)라고 하자.
    3. ToBoolean(exprValue)가 false이면, iterationResult를 반환한다.
    4. stmtResultStatementEvaluationCompletion이라고 하자.
    5. LoopContinues(stmtResult, labelSet)가 false이면, ? UpdateEmpty(stmtResult, iterationResult)를 반환한다.
    6. stmtResult.[[Value]]empty가 아니면, iterationResultstmtResult.[[Value]]로 설정한다.

14.7.4 for

구문

ForStatement[Yield, Await, Return] : for ( [lookahead ≠ let [] Expression[~In, ?Yield, ?Await]opt ; Expression[+In, ?Yield, ?Await]opt ; Expression[+In, ?Yield, ?Await]opt ) Statement[?Yield, ?Await, ?Return] for ( var VariableDeclarationList[~In, ?Yield, ?Await] ; Expression[+In, ?Yield, ?Await]opt ; Expression[+In, ?Yield, ?Await]opt ) Statement[?Yield, ?Await, ?Return] for ( LexicalDeclaration[~In, ?Yield, ?Await] Expression[+In, ?Yield, ?Await]opt ; Expression[+In, ?Yield, ?Await]opt ) Statement[?Yield, ?Await, ?Return]

14.7.4.1 Static Semantics: Early Errors

ForStatement : for ( Expressionopt ; Expressionopt ; Expressionopt ) Statement for ( var VariableDeclarationList ; Expressionopt ; Expressionopt ) Statement for ( LexicalDeclaration Expressionopt ; Expressionopt ) Statement Note

이 규칙은 B.3.1에 명시된 확장이 구현된 경우에만 적용할 필요가 있다.

ForStatement : for ( LexicalDeclaration Expressionopt ; Expressionopt ) Statement

14.7.4.2 Runtime Semantics: ForLoopEvaluation

The syntax-directed operation ForLoopEvaluation takes argument labelSet (a List of Strings) and returns either a normal completion containing an ECMAScript language value or an abrupt completion. It is defined piecewise over the following productions:

ForStatement : for ( Expressionopt ; Expressionopt ; Expressionopt ) Statement
  1. 첫 번째 Expression이 존재하면,
    1. exprRef를 첫 번째 ExpressionEvaluation 결과 ?라고 하자.
    2. GetValue(exprRef)를 수행한다.
  2. 두 번째 Expression이 존재하면 test를 두 번째 Expression로 하자; 그렇지 않으면 testempty로 하자.
  3. 세 번째 Expression이 존재하면 increment를 세 번째 Expression로 하자; 그렇지 않으면 incrementempty로 하자.
  4. ForBodyEvaluation(test, increment, Statement, « », labelSet)를 반환한다.
ForStatement : for ( var VariableDeclarationList ; Expressionopt ; Expressionopt ) Statement
  1. VariableDeclarationListEvaluation을 ? 수행한다.
  2. 첫 번째 Expression이 존재하면 test를 첫 번째 Expression로 하자; 그렇지 않으면 testempty로 하자.
  3. 두 번째 Expression이 존재하면 increment를 두 번째 Expression로 하자; 그렇지 않으면 incrementempty로 하자.
  4. ForBodyEvaluation(test, increment, Statement, « », labelSet)를 반환한다.
ForStatement : for ( LexicalDeclaration Expressionopt ; Expressionopt ) Statement
  1. oldEnv를 현재 실행 중인 execution context의 LexicalEnvironment라고 하자.
  2. loopEnvNewDeclarativeEnvironment(oldEnv)라고 하자.
  3. isConstLexicalDeclarationIsConstantDeclaration이라고 하자.
  4. boundNamesLexicalDeclarationBoundNames라고 하자.
  5. boundNames의 각 요소 dn에 대해, 다음을 수행한다
    1. isConsttrue이면,
      1. loopEnv.CreateImmutableBinding(dn, true)를 수행한다.
    2. 그렇지 않으면,
      1. loopEnv.CreateMutableBinding(dn, false)를 수행한다.
  6. 현재 실행 중인 execution context의 LexicalEnvironment를 loopEnv로 설정한다.
  7. forDclLexicalDeclarationEvaluationCompletion이라고 하자.
  8. forDclabrupt completion이면,
    1. 현재 실행 중인 execution context의 LexicalEnvironment를 oldEnv로 설정한다.
    2. forDcl을 반환한다.
  9. isConstfalse이면 perIterationLetsboundNames로 하자; 그렇지 않으면 perIterationLets를 새로운 빈 List로 하자.
  10. 첫 번째 Expression이 존재하면 test를 첫 번째 Expression로 하자; 그렇지 않으면 testempty로 하자.
  11. 두 번째 Expression이 존재하면 increment를 두 번째 Expression로 하자; 그렇지 않으면 incrementempty로 하자.
  12. bodyResultCompletion(ForBodyEvaluation(test, increment, Statement, perIterationLets, labelSet))라고 하자.
  13. 현재 실행 중인 execution context의 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 either a normal completion containing an ECMAScript language value or an abrupt completion. It performs the following steps when called:

  1. iterationResultundefined라고 하자.
  2. CreatePerIterationEnvironment(perIterationBindings)를 수행한다.
  3. 반복한다,
    1. testempty가 아니면,
      1. testReftestEvaluation 결과 ?라고 하자.
      2. testValue를 ? GetValue(testRef)라고 하자.
      3. ToBoolean(testValue)가 false이면, iterationResult를 반환한다.
    2. resultEvaluation of stmtCompletion이라고 하자.
    3. LoopContinues(result, labelSet)가 false이면, ? UpdateEmpty(result, iterationResult)를 반환한다.
    4. result.[[Value]]empty가 아니면, iterationResultresult.[[Value]]로 설정한다.
    5. CreatePerIterationEnvironment(perIterationBindings)를 수행한다.
    6. incrementempty가 아니면,
      1. incRefincrementEvaluation 결과 ?라고 하자.
      2. GetValue(incRef)를 수행한다.

14.7.4.4 CreatePerIterationEnvironment ( perIterationBindings )

The abstract operation CreatePerIterationEnvironment takes argument perIterationBindings (a List of Strings) and returns either a normal completion containing unused or a throw completion. It performs the following steps when called:

  1. perIterationBindings에 요소가 하나라도 있으면,
    1. lastIterationEnv를 현재 실행 중인 execution context의 LexicalEnvironment라고 하자.
    2. outerlastIterationEnv.[[OuterEnv]]라고 하자.
    3. Assert: outernull이 아니다.
    4. thisIterationEnvNewDeclarativeEnvironment(outer) 라고 하자.
    5. perIterationBindings의 각 요소 bn에 대해, 다음을 수행한다
      1. thisIterationEnv.CreateMutableBinding(bn, false) 를 수행한다.
      2. lastValue를 ? lastIterationEnv.GetBindingValue(bn, true)라고 하자.
      3. thisIterationEnv.InitializeBinding(bn, lastValue) 를 수행한다.
    6. 현재 실행 중인 execution context의 LexicalEnvironment를 thisIterationEnv로 설정한다.
  2. unused를 반환한다.

14.7.5 for-in, for-of, for-await-of

구문

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 Static Semantics: Early Errors

ForInOfStatement : for ( LeftHandSideExpression in Expression ) Statement for ( var ForBinding in Expression ) Statement for ( ForDeclaration in Expression ) Statement for ( LeftHandSideExpression of AssignmentExpression ) Statement for ( var ForBinding of AssignmentExpression ) Statement for ( ForDeclaration of AssignmentExpression ) Statement for await ( LeftHandSideExpression of AssignmentExpression ) Statement for await ( var ForBinding of AssignmentExpression ) Statement for await ( ForDeclaration of AssignmentExpression ) Statement Note

이 규칙은 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 Static Semantics: IsDestructuring

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

MemberExpression : PrimaryExpression
  1. PrimaryExpressionObjectLiteral 또는 ArrayLiteral 중 하나이면 true를 반환한다.
  2. false를 반환한다.
MemberExpression : MemberExpression [ Expression ] MemberExpression . IdentifierName MemberExpression TemplateLiteral SuperProperty MetaProperty new MemberExpression Arguments MemberExpression . PrivateIdentifier NewExpression : new NewExpression LeftHandSideExpression : CallExpression OptionalExpression
  1. false를 반환한다.
ForDeclaration : LetOrConst ForBinding
  1. ForBindingIsDestructuring을 반환한다.
ForBinding : BindingIdentifier
  1. false를 반환한다.
ForBinding : BindingPattern
  1. true를 반환한다.
Note

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

14.7.5.3 Runtime Semantics: ForDeclarationBindingInitialization

The syntax-directed operation ForDeclarationBindingInitialization takes arguments value (an ECMAScript language value) and environment (an Environment Record) and returns either a normal completion containing unused or an abrupt completion. It is defined piecewise over the following productions:

ForDeclaration : LetOrConst ForBinding
  1. 인수 valueenvironment를 사용한 ForBindingBindingInitialization을 ? 반환한다.

14.7.5.4 Runtime Semantics: ForDeclarationBindingInstantiation

The syntax-directed operation ForDeclarationBindingInstantiation takes argument environment (a Declarative Environment Record) and returns unused. It is defined piecewise over the following productions:

ForDeclaration : LetOrConst ForBinding
  1. ForBindingBoundNames의 각 요소 name에 대해, 다음을 수행한다
    1. LetOrConstIsConstantDeclarationtrue이면,
      1. environment.CreateImmutableBinding(name, true)를 수행한다.
    2. 그렇지 않으면,
      1. environment.CreateMutableBinding(name, false)를 수행한다.
  2. unused를 반환한다.

14.7.5.5 Runtime Semantics: ForInOfLoopEvaluation

The syntax-directed operation ForInOfLoopEvaluation takes argument labelSet (a List of Strings) and returns either a normal completion containing an ECMAScript language value or an abrupt completion. It is defined piecewise over the following productions:

ForInOfStatement : for ( LeftHandSideExpression in Expression ) Statement
  1. keyResult를 ? ForIn/OfHeadEvaluation(« », Expression, enumerate)라고 하자.
  2. ForIn/OfBodyEvaluation(LeftHandSideExpression, Statement, keyResult, enumerate, assignment, labelSet)를 반환한다.
ForInOfStatement : for ( var ForBinding in Expression ) Statement
  1. keyResult를 ? ForIn/OfHeadEvaluation(« », Expression, enumerate)라고 하자.
  2. ForIn/OfBodyEvaluation(ForBinding, Statement, keyResult, enumerate, var-binding, labelSet)를 반환한다.
ForInOfStatement : for ( ForDeclaration in Expression ) Statement
  1. keyResult를 ? ForIn/OfHeadEvaluation(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 either a normal completion containing an Iterator Record or an abrupt completion. It performs the following steps when called:

  1. oldEnv를 현재 실행 중인 execution context의 LexicalEnvironment라고 하자.
  2. uninitializedBoundNames가 비어 있지 않으면,
    1. Assert: uninitializedBoundNames는 중복 항목을 포함하지 않는다.
    2. newEnvNewDeclarativeEnvironment(oldEnv)라고 하자.
    3. uninitializedBoundNames의 각 String name에 대해, 다음을 수행한다
      1. newEnv.CreateMutableBinding(name, false)를 수행한다.
    4. 현재 실행 중인 execution context의 LexicalEnvironment를 newEnv로 설정한다.
  3. exprRefexprEvaluationCompletion이라고 하자.
  4. 현재 실행 중인 execution context의 LexicalEnvironment를 oldEnv로 설정한다.
  5. exprValue를 ? GetValue(? exprRef)라고 하자.
  6. iterationKindenumerate이면,
    1. exprValueundefined 또는 null 중 하나이면,
      1. Completion Record { [[Type]]: break, [[Value]]: empty, [[Target]]: empty }를 반환한다.
    2. obj를 ! ToObject(exprValue)라고 하자.
    3. iteratorEnumerateObjectProperties(obj)라고 하자.
    4. nextMethod를 ! GetV(iterator, "next")라고 하자.
    5. Iterator Record { [[Iterator]]: iterator, [[NextMethod]]: nextMethod, [[Done]]: false }를 반환한다.
  7. Assert: iterationKinditerate 또는 async-iterate 중 하나이다.
  8. iterationKindasync-iterate이면 iteratorKindasync로 하자.
  9. 그렇지 않으면, iteratorKindsync로 하자.
  10. GetIterator(exprValue, iteratorKind)를 반환한다.

14.7.5.7 ForIn/OfBodyEvaluation ( lhs, stmt, iteratorRecord, iterationKind, lhsKind, labelSet [ , iteratorKind ] )

The abstract operation ForIn/OfBodyEvaluation takes arguments lhs (a Parse Node), stmt (a Statement Parse Node), iteratorRecord (an Iterator Record), iterationKind (enumerate or iterate), lhsKind (assignment, var-binding, or lexical-binding), and labelSet (a List of Strings) and optional argument iteratorKind (sync or async) and returns either a normal completion containing an ECMAScript language value or an abrupt completion. It performs the following steps when called:

  1. iteratorKind가 존재하지 않으면, iteratorKindsync로 설정한다.
  2. oldEnv를 현재 실행 중인 execution context의 LexicalEnvironment라고 하자.
  3. iterationResultundefined라고 하자.
  4. destructuringlhsIsDestructuring이라고 하자.
  5. destructuringtrue이고 lhsKindassignment이면,
    1. Assert: lhsLeftHandSideExpression이다.
    2. assignmentPatternlhs가 커버하는 AssignmentPattern 이라고 하자.
  6. 반복한다,
    1. nextResult를 ? Call(iteratorRecord.[[NextMethod]], iteratorRecord.[[Iterator]])라고 하자.
    2. iteratorKindasync이면, nextResult를 ? Await(nextResult)로 설정한다.
    3. nextResult가 Object가 아니면, TypeError 예외를 던진다.
    4. done을 ? IteratorComplete(nextResult)라고 하자.
    5. donetrue이면, iterationResult를 반환한다.
    6. nextValue를 ? IteratorValue(nextResult)라고 하자.
    7. lhsKindassignment 또는 var-binding 중 하나이면,
      1. destructuringtrue이면,
        1. lhsKindassignment이면,
          1. status를 인수 nextValue를 사용한 assignmentPatternDestructuringAssignmentEvaluationCompletion이라고 하자.
        2. 그렇지 않으면,
          1. Assert: lhsKindvar-binding이다.
          2. Assert: lhsForBinding이다.
          3. status를 인수 nextValueundefined를 사용한 lhsBindingInitializationCompletion이라고 하자.
      2. 그렇지 않으면,
        1. lhsReflhsEvaluationCompletion이라고 하자. (반복적으로 평가될 수 있다.)
        2. lhsKindassignment이고 lhsAssignmentTargetTypeweb-compat이면, ReferenceError 예외를 던진다.
        3. lhsRefabrupt completion이면,
          1. statuslhsRef라고 하자.
        4. 그렇지 않으면,
          1. statusCompletion(PutValue(lhsRef.[[Value]], nextValue))라고 하자.
    8. 그렇지 않으면,
      1. Assert: lhsKindlexical-binding이다.
      2. Assert: lhsForDeclaration이다.
      3. iterationEnvNewDeclarativeEnvironment(oldEnv) 라고 하자.
      4. 인수 iterationEnv를 사용한 lhsForDeclarationBindingInstantiation을 수행한다.
      5. 현재 실행 중인 execution context의 LexicalEnvironment를 iterationEnv로 설정한다.
      6. destructuringtrue이면,
        1. status를 인수 nextValueiterationEnv를 사용한 lhsForDeclarationBindingInitializationCompletion 이라고 하자.
      7. 그렇지 않으면,
        1. Assert: lhs는 하나의 이름만 바인딩한다.
        2. lhsNamelhsBoundNames의 유일한 요소라고 하자.
        3. lhsRef를 ! ResolveBinding(lhsName)이라고 하자.
        4. statusCompletion(InitializeReferencedBinding(lhsRef, nextValue))라고 하자.
    9. statusabrupt completion이면,
      1. 현재 실행 중인 execution context의 LexicalEnvironment를 oldEnv로 설정한다.
      2. iterationKindenumerate이면, ? status를 반환한다.
      3. Assert: iterationKinditerate이다.
      4. iteratorKindasync이면, ? AsyncIteratorClose(iteratorRecord, status)를 반환한다.
      5. IteratorClose(iteratorRecord, status)를 반환한다.
    10. resultEvaluation of stmtCompletion이라고 하자.
    11. 현재 실행 중인 execution context의 LexicalEnvironment를 oldEnv로 설정한다.
    12. LoopContinues(result, labelSet)가 false이면,
      1. statusCompletion(UpdateEmpty(result, iterationResult))로 설정한다.
      2. iterationKindenumerate이면, ? status를 반환한다.
      3. Assert: iterationKinditerate이다.
      4. iteratorKindasync이면, ? AsyncIteratorClose(iteratorRecord, status)를 반환한다.
      5. IteratorClose(iteratorRecord, status)를 반환한다.
    13. result.[[Value]]empty가 아니면, iterationResultresult.[[Value]]로 설정한다.

14.7.5.8 Runtime Semantics: Evaluation

BindingIdentifier : Identifier yield await
  1. bindingIdBindingIdentifierStringValue라고 하자.
  2. ResolveBinding(bindingId)를 반환한다.

14.7.5.9 EnumerateObjectProperties ( obj )

The abstract operation EnumerateObjectProperties takes argument obj (an Object) and returns an iterator object. It performs the following steps when called:

  1. 열거 가능한 obj의 모든 String 값 키의 프로퍼티를 순회하는 next 메서드를 가진 이터레이터 객체를 반환한다. 이터레이터 객체는 ECMAScript 코드에서 직접 접근할 수 없다. 프로퍼티를 열거하는 방식과 순서는 명시되지 않지만 아래에 명시된 규칙에는 부합해야 한다.

이 이터레이터의 throwreturn 메서드는 null이며 결코 호출되지 않는다. 이 이터레이터의 next 메서드는 프로퍼티 키가 이터레이터 값으로 반환되어야 하는지를 결정하기 위해 객체 프로퍼티를 처리한다. 반환되는 프로퍼티 키에는 Symbol인 키는 포함되지 않는다. 대상 객체의 프로퍼티는 열거 도중 삭제될 수 있다. 이터레이터의 next 메서드가 처리하기 전에 삭제된 프로퍼티는 무시된다. 열거 도중 대상 객체에 새 프로퍼티가 추가되더라도, 새로 추가된 프로퍼티가 현재 진행 중인 열거에서 처리된다는 보장은 없다. 어떤 프로퍼티 이름이든 한 번의 열거에서 이터레이터의 next 메서드에 의해 최대 한 번만 반환된다.

대상 객체의 프로퍼티 열거에는 그 프로토타입, 프로토타입의 프로토타입 등도 재귀적으로 포함된다; 하지만 프로토타입의 프로퍼티는, 이터레이터의 next 메서드에 의해 이미 처리된 프로퍼티와 같은 이름을 가지면 처리되지 않는다. 프로토타입 객체의 프로퍼티가 이미 처리되었는지 결정할 때 [[Enumerable]] 속성 값은 고려되지 않는다. 프로토타입 객체의 열거 가능한 프로퍼티 이름은 그 프로토타입 객체를 인수로 전달하여 EnumerateObjectProperties를 호출함으로써 얻어져야 한다. EnumerateObjectProperties는 대상 객체의 자체 프로퍼티 키를 [[OwnPropertyKeys]] 내부 메서드를 호출하여 얻어야 한다. 대상 객체의 프로퍼티 속성은 [[GetOwnProperty]] 내부 메서드를 호출하여 얻어야 한다.

추가로, obj와 그 프로토타입 체인 안의 어떤 객체도 Proxy 이색 객체, TypedArray, 모듈 네임스페이스 이색 객체, 또는 구현이 제공한 이색 객체가 아니라면, 이터레이터는 다음 중 하나가 발생할 때까지는 CreateForInIterator(obj)가 제공하는 이터레이터처럼 동작해야 한다:

  • obj 또는 그 프로토타입 체인 안의 객체의 [[Prototype]] 내부 슬롯 값이 바뀌거나,
  • obj 또는 그 프로토타입 체인 안의 객체에서 프로퍼티가 제거되거나,
  • obj의 프로토타입 체인 안의 객체에 프로퍼티가 추가되거나, 또는
  • obj 또는 그 프로토타입 체인 안의 객체의 프로퍼티의 [[Enumerable]] 속성 값이 바뀌는 경우.
Note 1

ECMAScript 구현은 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와 일치할 필요가 없는 이색 객체들의 목록은, 역사적으로 구현들이 그러한 경우에는 동작이 달랐고 다른 모든 경우에는 일치했기 때문에 선택되었다.

14.7.5.10 For-In 이터레이터 객체

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 a For-In Iterator. 이것은 object의 자체 및 상속된 열거 가능한 문자열 프로퍼티를 특정 순서로 순회하는 For-In Iterator 객체를 생성하는 데 사용된다. It performs the following steps when called:

  1. iteratorOrdinaryObjectCreate(%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 객체가 상속하는 프로퍼티를 가진다.
  • 일반 객체이다.
  • [[Prototype]] 내부 슬롯 값이 %Iterator.prototype%이다.
  • ECMAScript 코드에서 직접 접근할 수 없다.
  • 다음 프로퍼티를 가진다:

14.7.5.10.2.1 %ForInIteratorPrototype%.next ( )

  1. iterthis 값이라고 하자.
  2. Assert: iter는 Object이다.
  3. Assert: iterFor-In Iterator 인스턴스의 모든 내부 슬롯을 가진다 (14.7.5.10.3).
  4. objectiter.[[Object]]라고 하자.
  5. 반복한다,
    1. iter.[[ObjectWasVisited]]false이면,
      1. keys를 ? object.[[OwnPropertyKeys]]()라고 하자.
      2. keys의 각 요소 key에 대해, 다음을 수행한다
        1. key가 String이면,
          1. keyiter.[[RemainingKeys]]에 추가한다.
      3. iter.[[ObjectWasVisited]]true로 설정한다.
    2. iter.[[RemainingKeys]]가 비어 있지 않은 동안, 반복한다
      1. keyiter.[[RemainingKeys]]의 첫 번째 요소라고 하자.
      2. iter.[[RemainingKeys]]에서 첫 번째 요소를 제거한다.
      3. iter.[[VisitedKeys]]key를 포함하지 않으면,
        1. desc를 ? object.[[GetOwnProperty]](key)라고 하자.
        2. descundefined가 아니면,
          1. keyiter.[[VisitedKeys]]에 추가한다.
          2. desc.[[Enumerable]]true이면, CreateIteratorResultObject(key, false)를 반환한다.
    3. object를 ? object.[[GetPrototypeOf]]()로 설정한다.
    4. iter.[[Object]]object로 설정한다.
    5. iter.[[ObjectWasVisited]]false로 설정한다.
    6. objectnull이면, CreateIteratorResultObject(undefined, true)를 반환한다.

14.7.5.10.3 For-In Iterator 인스턴스의 프로퍼티

For-In Iterator 인스턴스는 %ForInIteratorPrototype% 내재 객체로부터 프로퍼티를 상속하는 일반 객체이다. For-In Iterator 인스턴스는 처음 생성될 때 Table 33 에 나열된 내부 슬롯들을 가진다.

Table 33: Internal Slots of For-In Iterator Instances
내부 슬롯 타입 설명
[[Object]] an Object 프로퍼티가 순회되고 있는 Object 값.
[[ObjectWasVisited]] a Boolean 이 이터레이터가 [[Object]]에 대해 [[OwnPropertyKeys]]를 호출했으면 true, 아니면 false.
[[VisitedKeys]] a List of Strings 지금까지 이 이터레이터에 의해 방출된 값들.
[[RemainingKeys]] a List of Strings 현재 객체에 대해 아직 방출되지 않은 값들. 이 값들은 그 프로토타입의 프로퍼티를 순회하기 전에 방출된다 (프로토타입이 null이 아닌 경우).

14.8 continue

구문

ContinueStatement[Yield, Await] : continue ; continue [no LineTerminator here] LabelIdentifier[?Yield, ?Await] ;

14.8.1 Static Semantics: Early Errors

ContinueStatement : continue ; continue LabelIdentifier ;
  • ContinueStatementIterationStatement 안에 직접 또는 간접적으로 중첩되어 있지 않다면(단 함수 또는 static 초기화 블록 경계를 넘지 않아야 함), Syntax Error이다.

14.8.2 Runtime Semantics: Evaluation

ContinueStatement : continue ;
  1. Completion Record { [[Type]]: continue, [[Value]]: empty, [[Target]]: empty }를 반환한다.
ContinueStatement : continue LabelIdentifier ;
  1. labelLabelIdentifierStringValue라고 하자.
  2. Completion Record { [[Type]]: continue, [[Value]]: empty, [[Target]]: label }를 반환한다.

14.9 break

구문

BreakStatement[Yield, Await] : break ; break [no LineTerminator here] LabelIdentifier[?Yield, ?Await] ;

14.9.1 Static Semantics: Early Errors

BreakStatement : break ;

14.9.2 Runtime Semantics: Evaluation

BreakStatement : break ;
  1. Completion Record { [[Type]]: break, [[Value]]: empty, [[Target]]: empty }를 반환한다.
BreakStatement : break LabelIdentifier ;
  1. labelLabelIdentifierStringValue라고 하자.
  2. Completion Record { [[Type]]: break, [[Value]]: empty, [[Target]]: label }를 반환한다.

14.10 return

구문

ReturnStatement[Yield, Await] : return ; return [no LineTerminator here] Expression[+In, ?Yield, ?Await] ; Note

return 문은 함수가 실행을 중단하게 하며, 대부분의 경우 호출자에게 값을 반환한다. Expression이 생략되면 반환값은 undefined이다. 그렇지 않으면 반환값은 Expression의 값이다. return 문은 주변 문맥에 따라 실제로 호출자에게 값을 반환하지 않을 수도 있다. 예를 들어 try 블록 안에서는 return 문의 Completion Recordfinally 블록 평가 중 다른 Completion Record로 대체될 수 있다.

14.10.1 Runtime Semantics: Evaluation

ReturnStatement : return ;
  1. ReturnCompletion(undefined)를 반환한다.
ReturnStatement : return Expression ;
  1. exprRefExpressionEvaluation 결과 ?라고 하자.
  2. exprValue를 ? GetValue(exprRef)라고 하자.
  3. GetGeneratorKind()가 async이면, exprValue를 ? Await(exprValue)로 설정한다.
  4. ReturnCompletion(exprValue)를 반환한다.
Legacy

14.11 with

Note 1

레거시 with 문의 사용은 새로운 ECMAScript 코드에서는 권장되지 않는다. 구조 분해 대입처럼 strict mode 코드non-strict 코드 모두에서 허용되는 대안을 고려하라.

구문

WithStatement[Yield, Await, Return] : with ( Expression[+In, ?Yield, ?Await] ) Statement[?Yield, ?Await, ?Return] Note 2

with 문은 계산된 객체에 대한 Object Environment Record를 현재 실행 중인 execution context의 어휘 환경에 추가한다. 그런 다음 이 확장된 어휘 환경을 사용하여 문장을 실행한다. 마지막으로 원래의 어휘 환경을 복원한다.

14.11.1 Static Semantics: Early Errors

WithStatement : with ( Expression ) Statement Note

두 번째 규칙은 B.3.1에 명시된 확장이 구현된 경우에만 적용할 필요가 있다.

14.11.2 Runtime Semantics: Evaluation

WithStatement : with ( Expression ) Statement
  1. valExpressionEvaluation 결과 ?라고 하자.
  2. obj를 ? ToObject(? GetValue(val))라고 하자.
  3. oldEnv를 현재 실행 중인 execution context의 LexicalEnvironment라고 하자.
  4. newEnvNewObjectEnvironment(obj, true, oldEnv) 라고 하자.
  5. 현재 실행 중인 execution context의 LexicalEnvironment를 newEnv로 설정한다.
  6. stmtCompletionStatementEvaluationCompletion이라고 하자.
  7. 현재 실행 중인 execution context의 LexicalEnvironment를 oldEnv로 설정한다.
  8. UpdateEmpty(stmtCompletion, undefined)를 반환한다.
Note

제어가 포함된 Statement를 어떤 방식으로 떠나더라도, 정상적이든 어떤 형태의 abrupt completion이나 예외에 의하든, LexicalEnvironment는 항상 이전 상태로 복원된다.

14.12 switch

구문

SwitchStatement[Yield, Await, Return] : switch ( Expression[+In, ?Yield, ?Await] ) CaseBlock[?Yield, ?Await, ?Return] CaseBlock[Yield, Await, Return] : { CaseClauses[?Yield, ?Await, ?Return]opt } { CaseClauses[?Yield, ?Await, ?Return]opt DefaultClause[?Yield, ?Await, ?Return] CaseClauses[?Yield, ?Await, ?Return]opt } CaseClauses[Yield, Await, Return] : CaseClause[?Yield, ?Await, ?Return] CaseClauses[?Yield, ?Await, ?Return] CaseClause[?Yield, ?Await, ?Return] CaseClause[Yield, Await, Return] : case Expression[+In, ?Yield, ?Await] : StatementList[?Yield, ?Await, ?Return]opt DefaultClause[Yield, Await, Return] : default : StatementList[?Yield, ?Await, ?Return]opt

14.12.1 Static Semantics: Early Errors

SwitchStatement : switch ( Expression ) CaseBlock

14.12.2 Runtime Semantics: CaseBlockEvaluation

The syntax-directed operation CaseBlockEvaluation takes argument input (an ECMAScript language value) and returns either a normal completion containing an ECMAScript language value or an abrupt completion. It is defined piecewise over the following productions:

CaseBlock : { }
  1. undefined를 반환한다.
CaseBlock : { CaseClauses }
  1. resultValueundefined라고 하자.
  2. caseClausesCaseClauses 안의 CaseClause 항목들의 List로, 소스 텍스트 순서대로라고 하자.
  3. foundfalse라고 하자.
  4. caseClauses의 각 CaseClause clause에 대해, 다음을 수행한다
    1. foundfalse이면,
      1. found를 ? CaseClauseIsSelected(clause, input)로 설정한다.
    2. foundtrue이면,
      1. completionEvaluation of clauseCompletion이라고 하자.
      2. completion.[[Value]]empty가 아니면, resultValuecompletion.[[Value]]로 설정한다.
      3. completionabrupt completion이면, ? UpdateEmpty(completion, resultValue)를 반환한다.
  5. resultValue를 반환한다.
CaseBlock : { CaseClausesopt DefaultClause CaseClausesopt }
  1. resultValueundefined라고 하자.
  2. 첫 번째 CaseClauses가 존재하면,
    1. caseClauses를 첫 번째 CaseClauses 안의 CaseClause 항목들의 List로, 소스 텍스트 순서대로라고 하자.
  3. 그렇지 않으면,
    1. caseClauses를 새로운 빈 List라고 하자.
  4. foundfalse라고 하자.
  5. caseClauses의 각 CaseClause clause에 대해, 다음을 수행한다
    1. foundfalse이면,
      1. found를 ? CaseClauseIsSelected(clause, input)로 설정한다.
    2. foundtrue이면,
      1. completionEvaluation of clauseCompletion이라고 하자.
      2. completion.[[Value]]empty가 아니면, resultValuecompletion.[[Value]]로 설정한다.
      3. completionabrupt completion이면, ? UpdateEmpty(completion, resultValue)를 반환한다.
  6. foundInBfalse라고 하자.
  7. 두 번째 CaseClauses가 존재하면,
    1. secondCaseClauses를 두 번째 CaseClauses 안의 CaseClause 항목들의 List로, 소스 텍스트 순서대로라고 하자.
  8. 그렇지 않으면,
    1. secondCaseClauses를 새로운 빈 List라고 하자.
  9. foundfalse이면,
    1. secondCaseClauses의 각 CaseClause clause에 대해, 다음을 수행한다
      1. foundInBfalse이면,
        1. foundInB를 ? CaseClauseIsSelected(clause, input)로 설정한다.
      2. foundInBtrue이면,
        1. completionEvaluation of CaseClause clauseCompletion이라고 하자.
        2. completion.[[Value]]empty가 아니면, resultValuecompletion.[[Value]]로 설정한다.
        3. completionabrupt completion이면, ? UpdateEmpty(completion, resultValue)를 반환한다.
  10. foundInBtrue이면, resultValue를 반환한다.
  11. defaultREvaluation of DefaultClauseCompletion이라고 하자.
  12. defaultR.[[Value]]empty가 아니면, resultValuedefaultR.[[Value]]로 설정한다.
  13. defaultRabrupt completion이면, ? UpdateEmpty(defaultR, resultValue)를 반환한다.
  14. NOTE: 다음은 두 번째 CaseClauses에 대한 또 하나의 완전한 반복이다.
  15. secondCaseClauses의 각 CaseClause clause에 대해, 다음을 수행한다
    1. completionEvaluation of CaseClause clauseCompletion이라고 하자.
    2. completion.[[Value]]empty가 아니면, resultValuecompletion.[[Value]]로 설정한다.
    3. completionabrupt completion이면, ? UpdateEmpty(completion, resultValue)를 반환한다.
  16. resultValue를 반환한다.

14.12.3 CaseClauseIsSelected ( constructor, input )

The abstract operation CaseClauseIsSelected takes arguments constructor (a CaseClause Parse Node) and input (an ECMAScript language value) and returns either a normal completion containing a Boolean or an abrupt completion. 이것은 constructorinput과 일치하는지를 결정한다. It performs the following steps when called:

  1. Assert: constructor는 production CaseClause : case Expression : StatementListopt 의 인스턴스이다.
  2. exprRefconstructorExpressionEvaluation 결과 ?라고 하자.
  3. clauseSelector를 ? GetValue(exprRef)라고 하자.
  4. IsStrictlyEqual(input, clauseSelector)를 반환한다.
Note

이 연산은 constructorStatementList(있다면)를 실행하지 않는다. CaseBlock 알고리즘은 그 반환값을 사용해 어느 StatementList 부터 실행할지 결정한다.

14.12.4 Runtime Semantics: Evaluation

SwitchStatement : switch ( Expression ) CaseBlock
  1. exprRefExpressionEvaluation 결과 ?라고 하자.
  2. switchValue를 ? GetValue(exprRef)라고 하자.
  3. oldEnv를 현재 실행 중인 execution context의 LexicalEnvironment라고 하자.
  4. blockEnvNewDeclarativeEnvironment(oldEnv)라고 하자.
  5. BlockDeclarationInstantiation(CaseBlock, blockEnv)를 수행한다.
  6. 현재 실행 중인 execution context의 LexicalEnvironment를 blockEnv로 설정한다.
  7. blockResult를 인수 switchValue를 사용한 CaseBlockCaseBlockEvaluationCompletion이라고 하자.
  8. 현재 실행 중인 execution context의 LexicalEnvironment를 oldEnv로 설정한다.
  9. blockResult를 반환한다.
Note

제어가 SwitchStatement를 어떤 방식으로 떠나더라도 LexicalEnvironment는 항상 이전 상태로 복원된다.

CaseClause : case Expression :
  1. empty를 반환한다.
CaseClause : case Expression : StatementList
  1. StatementListEvaluation을 ? 반환한다.
DefaultClause : default :
  1. empty를 반환한다.
DefaultClause : default : StatementList
  1. StatementListEvaluation을 ? 반환한다.

14.13 레이블된 문

구문

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는 레이블로 접두될 수 있다. 레이블된 문은 오직 레이블된 breakcontinue 문과 함께만 사용된다. ECMAScript에는 goto 문이 없다. StatementLabelledStatement의 일부가 될 수 있고, 그것은 다시 LabelledStatement의 일부가 될 수 있으며, 이런 식으로 계속될 수 있다. 이렇게 도입된 레이블들은 개별 문장의 의미론을 설명할 때 집합적으로 “현재 레이블 집합”이라고 불린다.

14.13.1 Static Semantics: Early Errors

LabelledItem : FunctionDeclaration

14.13.2 Static Semantics: IsLabelledFunction ( stmt )

The abstract operation IsLabelledFunction takes argument stmt (a Statement Parse Node) and returns a Boolean. It performs the following steps when called:

  1. stmtLabelledStatement가 아니면, false를 반환한다.
  2. itemstmtLabelledItem이라고 하자.
  3. item LabelledItem : FunctionDeclaration 이면, true를 반환한다.
  4. subStmtitemStatement라고 하자.
  5. IsLabelledFunction(subStmt)를 반환한다.

14.13.3 Runtime Semantics: Evaluation

LabelledStatement : LabelIdentifier : LabelledItem
  1. 인수 « »를 사용한 this LabelledStatementLabelledEvaluation을 ? 반환한다.

14.13.4 Runtime Semantics: LabelledEvaluation

The syntax-directed operation LabelledEvaluation takes argument labelSet (a List of Strings) and returns either a normal completion containing either an ECMAScript language value or empty, or an abrupt completion. It is defined piecewise over the following productions:

BreakableStatement : IterationStatement
  1. stmtResult를 인수 labelSet을 사용한 IterationStatementLoopEvaluationCompletion이라고 하자.
  2. stmtResultbreak completion이면,
    1. stmtResult.[[Target]]empty이면,
      1. stmtResult.[[Value]]empty이면, stmtResultNormalCompletion(undefined)로 설정한다.
      2. 그렇지 않으면, stmtResultNormalCompletion(stmtResult.[[Value]])로 설정한다.
  3. stmtResult를 반환한다.
BreakableStatement : SwitchStatement
  1. stmtResultSwitchStatementEvaluationCompletion이라고 하자.
  2. stmtResultbreak completion이면,
    1. stmtResult.[[Target]]empty이면,
      1. stmtResult.[[Value]]empty이면, stmtResultNormalCompletion(undefined)로 설정한다.
      2. 그렇지 않으면, stmtResultNormalCompletion(stmtResult.[[Value]])로 설정한다.
  3. stmtResult를 반환한다.
Note 1

BreakableStatement는 레이블 없는 BreakStatement로 빠져나올 수 있는 문이다.

LabelledStatement : LabelIdentifier : LabelledItem
  1. labelLabelIdentifierStringValue라고 하자.
  2. newLabelSetlabelSet과 « label »의 list-concatenation 이라고 하자.
  3. stmtResult를 인수 newLabelSet을 사용한 LabelledItemLabelledEvaluationCompletion이라고 하자.
  4. stmtResultbreak completion이고 stmtResult.[[Target]]label이면,
    1. stmtResultNormalCompletion(stmtResult.[[Value]])로 설정한다.
  5. stmtResult를 반환한다.
LabelledItem : FunctionDeclaration
  1. FunctionDeclarationEvaluation을 ? 반환한다.
Statement : BlockStatement VariableStatement EmptyStatement ExpressionStatement IfStatement ContinueStatement BreakStatement ReturnStatement WithStatement ThrowStatement TryStatement DebuggerStatement
  1. StatementEvaluation을 ? 반환한다.
Note 2

Statement의 두 production만이 LabelledEvaluation에 대해 특별한 의미론을 가진다: BreakableStatementLabelledStatement이다.

14.14 throw

구문

ThrowStatement[Yield, Await] : throw [no LineTerminator here] Expression[+In, ?Yield, ?Await] ;

14.14.1 Runtime Semantics: Evaluation

ThrowStatement : throw Expression ;
  1. exprRefExpressionEvaluation 결과 ?라고 하자.
  2. exprValue를 ? GetValue(exprRef)라고 하자.
  3. exprValue를 던진다.

14.15 try

구문

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 Static Semantics: Early Errors

Catch : catch ( CatchParameter ) Block

14.15.2 Runtime Semantics: CatchClauseEvaluation

The syntax-directed operation CatchClauseEvaluation takes argument thrownValue (an ECMAScript language value) and returns either a normal completion containing either an ECMAScript language value or empty, or an abrupt completion. It is defined piecewise over the following productions:

Catch : catch ( CatchParameter ) Block
  1. oldEnv를 현재 실행 중인 execution context의 LexicalEnvironment라고 하자.
  2. catchEnvNewDeclarativeEnvironment(oldEnv)라고 하자.
  3. CatchParameterBoundNames의 각 요소 argName에 대해, 다음을 수행한다
    1. catchEnv.CreateMutableBinding(argName, false)를 수행한다.
  4. 현재 실행 중인 execution context의 LexicalEnvironment를 catchEnv로 설정한다.
  5. status를 인수 thrownValuecatchEnv를 사용한 CatchParameterBindingInitializationCompletion이라고 하자.
  6. statusabrupt completion이면,
    1. 현재 실행 중인 execution context의 LexicalEnvironment를 oldEnv로 설정한다.
    2. status를 반환한다.
  7. blockCompletionBlockEvaluationCompletion이라고 하자.
  8. 현재 실행 중인 execution context의 LexicalEnvironment를 oldEnv로 설정한다.
  9. blockCompletion을 반환한다.
Catch : catch Block
  1. BlockEvaluation을 ? 반환한다.
Note

제어가 Block을 어떤 방식으로 떠나더라도 LexicalEnvironment는 항상 이전 상태로 복원된다.

14.15.3 Runtime Semantics: Evaluation

TryStatement : try Block Catch
  1. blockResultBlockEvaluationCompletion이라고 하자.
  2. blockResultthrow completion이면, catchResult를 인수 blockResult.[[Value]]를 사용한 CatchCatchClauseEvaluationCompletion이라고 하자.
  3. 그렇지 않으면, catchResultblockResult라고 하자.
  4. UpdateEmpty(catchResult, undefined)를 반환한다.
TryStatement : try Block Finally
  1. blockResultBlockEvaluationCompletion이라고 하자.
  2. finallyResultFinallyEvaluationCompletion이라고 하자.
  3. finallyResultnormal completion이면, finallyResultblockResult로 설정한다.
  4. UpdateEmpty(finallyResult, undefined)를 반환한다.
TryStatement : try Block Catch Finally
  1. blockResultBlockEvaluationCompletion이라고 하자.
  2. blockResultthrow completion이면, catchResult를 인수 blockResult.[[Value]]를 사용한 CatchCatchClauseEvaluationCompletion이라고 하자.
  3. 그렇지 않으면, catchResultblockResult라고 하자.
  4. finallyResultFinallyEvaluationCompletion이라고 하자.
  5. finallyResultnormal completion이면, finallyResultcatchResult로 설정한다.
  6. UpdateEmpty(finallyResult, undefined)를 반환한다.

14.16 debugger

구문

DebuggerStatement : debugger ;

14.16.1 Runtime Semantics: Evaluation

Note

DebuggerStatement를 평가하면 구현이 디버거 아래에서 실행될 때 중단점을 발생시킬 수 있다. 디버거가 존재하지 않거나 활성화되어 있지 않으면 이 문장은 관찰 가능한 효과를 가지지 않는다.

DebuggerStatement : debugger ;
  1. 구현 정의된 디버깅 기능이 사용 가능하고 활성화되어 있으면,
    1. 구현 정의된 디버깅 동작을 수행한다.
    2. 새로운 구현 정의 Completion Record를 반환한다.
  2. empty를 반환한다.

15 ECMAScript 언어: 함수와 클래스

Note

다양한 ECMAScript 언어 요소는 ECMAScript 함수 객체의 생성을 유발한다 (10.2). 이러한 함수의 평가는 해당 [[Call]] 내부 메서드의 실행으로 시작된다 (10.2.1).

15.1 매개변수 목록

구문

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: 조기 오류

UniqueFormalParameters : FormalParameters FormalParameters : FormalParameterList Note

FormalParameterList에서 동일한 BindingIdentifier가 여러 번 나타나는 것은 단순 매개변수 목록을 가지며 엄격 모드 코드에서 정의되지 않은 함수에 대해서만 허용된다.

15.1.2 Static Semantics: ContainsExpression

The syntax-directed operation ContainsExpression takes no arguments and returns 불리언. It is defined piecewise over the following productions:

ObjectBindingPattern : { } { BindingRestProperty }
  1. false를 반환한다.
ObjectBindingPattern : { BindingPropertyList , BindingRestProperty }
  1. BindingPropertyListContainsExpression을 반환한다.
ArrayBindingPattern : [ Elisionopt ]
  1. false를 반환한다.
ArrayBindingPattern : [ Elisionopt BindingRestElement ]
  1. BindingRestElementContainsExpression을 반환한다.
ArrayBindingPattern : [ BindingElementList , Elisionopt ]
  1. BindingElementListContainsExpression을 반환한다.
ArrayBindingPattern : [ BindingElementList , Elisionopt BindingRestElement ]
  1. hasBindingElementListContainsExpression으로 설정한다.
  2. hastrue이면, true를 반환한다.
  3. BindingRestElementContainsExpression을 반환한다.
BindingPropertyList : BindingPropertyList , BindingProperty
  1. hasBindingPropertyListContainsExpression으로 설정한다.
  2. hastrue이면, true를 반환한다.
  3. BindingPropertyContainsExpression을 반환한다.
BindingElementList : BindingElementList , BindingElisionElement
  1. hasBindingElementListContainsExpression으로 설정한다.
  2. hastrue이면, true를 반환한다.
  3. BindingElisionElementContainsExpression을 반환한다.
BindingElisionElement : Elisionopt BindingElement
  1. BindingElementContainsExpression을 반환한다.
BindingProperty : PropertyName : BindingElement
  1. hasPropertyNameIsComputedPropertyKey로 설정한다.
  2. hastrue이면, true를 반환한다.
  3. BindingElementContainsExpression을 반환한다.
BindingElement : BindingPattern Initializer
  1. true를 반환한다.
SingleNameBinding : BindingIdentifier
  1. false를 반환한다.
SingleNameBinding : BindingIdentifier Initializer
  1. true를 반환한다.
BindingRestElement : ... BindingIdentifier
  1. false를 반환한다.
BindingRestElement : ... BindingPattern
  1. BindingPatternContainsExpression을 반환한다.
FormalParameters : [empty]
  1. false를 반환한다.
FormalParameters : FormalParameterList , FunctionRestParameter
  1. FormalParameterListContainsExpressiontrue이면, true를 반환한다.
  2. FunctionRestParameterContainsExpression을 반환한다.
FormalParameterList : FormalParameterList , FormalParameter
  1. FormalParameterListContainsExpressiontrue이면, true를 반환한다.
  2. FormalParameterContainsExpression을 반환한다.
ArrowParameters : BindingIdentifier
  1. false를 반환한다.
ArrowParameters : CoverParenthesizedExpressionAndArrowParameterList
  1. formalsCoverParenthesizedExpressionAndArrowParameterList가 포함하는 ArrowFormalParameters로 설정한다.
  2. formalsContainsExpression을 반환한다.
AsyncArrowBindingIdentifier : BindingIdentifier
  1. false를 반환한다.

15.1.3 Static Semantics: IsSimpleParameterList

The syntax-directed operation IsSimpleParameterList takes no arguments and returns 불리언. It is defined piecewise over the following productions:

BindingElement : BindingPattern
  1. false를 반환한다.
BindingElement : BindingPattern Initializer
  1. false를 반환한다.
SingleNameBinding : BindingIdentifier
  1. true를 반환한다.
SingleNameBinding : BindingIdentifier Initializer
  1. false를 반환한다.
FormalParameters : [empty]
  1. true를 반환한다.
FormalParameters : FunctionRestParameter
  1. false를 반환한다.
FormalParameters : FormalParameterList , FunctionRestParameter
  1. false를 반환한다.
FormalParameterList : FormalParameterList , FormalParameter
  1. FormalParameterListIsSimpleParameterListfalse이면, false를 반환한다.
  2. FormalParameterIsSimpleParameterList를 반환한다.
FormalParameter : BindingElement
  1. BindingElementIsSimpleParameterList를 반환한다.
ArrowParameters : BindingIdentifier
  1. true를 반환한다.
ArrowParameters : CoverParenthesizedExpressionAndArrowParameterList
  1. formalsCoverParenthesizedExpressionAndArrowParameterList가 포함하는 ArrowFormalParameters로 설정한다.
  2. formalsIsSimpleParameterList를 반환한다.
AsyncArrowBindingIdentifier : BindingIdentifier
  1. true를 반환한다.
CoverCallExpressionAndAsyncArrowHead : MemberExpression Arguments
  1. headCoverCallExpressionAndAsyncArrowHead가 포함하는 AsyncArrowHead로 설정한다.
  2. headIsSimpleParameterList를 반환한다.

15.1.4 Static Semantics: HasInitializer

The syntax-directed operation HasInitializer takes no arguments and returns 불리언. It is defined piecewise over the following productions:

BindingElement : BindingPattern
  1. false를 반환한다.
BindingElement : BindingPattern Initializer
  1. true를 반환한다.
SingleNameBinding : BindingIdentifier
  1. false를 반환한다.
SingleNameBinding : BindingIdentifier Initializer
  1. true를 반환한다.
FormalParameterList : FormalParameterList , FormalParameter
  1. FormalParameterListHasInitializertrue이면, true를 반환한다.
  2. FormalParameterHasInitializer를 반환한다.

15.1.5 Static Semantics: ExpectedArgumentCount

The syntax-directed operation ExpectedArgumentCount takes no arguments and returns 음이 아닌 정수. It is defined piecewise over the following productions:

FormalParameters : [empty] FunctionRestParameter
  1. 0을 반환한다.
FormalParameters : FormalParameterList , FunctionRestParameter
  1. FormalParameterListExpectedArgumentCount를 반환한다.
Note

FormalParameterList의 ExpectedArgumentCount는 rest 매개변수 또는 Initializer를 가진 첫 번째 FormalParameter의 왼쪽에 있는 FormalParameters의 개수이다. Initializer가 없는 FormalParameter는 Initializer가 있는 첫 번째 매개변수 이후에도 허용되지만, 이러한 매개변수는 기본값으로 undefined를 가지는 선택적 매개변수로 간주된다.

FormalParameterList : FormalParameter
  1. FormalParameterHasInitializertrue이면, 0을 반환한다.
  2. 1을 반환한다.
FormalParameterList : FormalParameterList , FormalParameter
  1. countFormalParameterListExpectedArgumentCount로 설정한다.
  2. FormalParameterListHasInitializertrue이거나 FormalParameterHasInitializertrue이면, count를 반환한다.
  3. count + 1을 반환한다.
ArrowParameters : BindingIdentifier
  1. 1을 반환한다.
ArrowParameters : CoverParenthesizedExpressionAndArrowParameterList
  1. formalsCoverParenthesizedExpressionAndArrowParameterList가 포함하는 ArrowFormalParameters로 설정한다.
  2. formalsExpectedArgumentCount를 반환한다.
PropertySetParameterList : FormalParameter
  1. FormalParameterHasInitializertrue이면, 0을 반환한다.
  2. 1을 반환한다.
AsyncArrowBindingIdentifier : BindingIdentifier
  1. 1을 반환한다.

15.2 함수 정의

구문

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: 조기 오류

FunctionDeclaration : function BindingIdentifier ( FormalParameters ) { FunctionBody } function ( FormalParameters ) { FunctionBody } FunctionExpression : function BindingIdentifieropt ( FormalParameters ) { FunctionBody } Note

FunctionBodyLexicallyDeclaredNames에는 var 또는 함수 선언을 사용하여 바인딩된 식별자가 포함되지 않는다.

FunctionBody : FunctionStatementList

15.2.2 Static Semantics: FunctionBodyContainsUseStrict

The syntax-directed operation FunctionBodyContainsUseStrict takes no arguments and returns 불리언. It is defined piecewise over the following productions:

FunctionBody : FunctionStatementList
  1. FunctionBody의 지시어 서두가 Use Strict 지시어를 포함하면 true를 반환한다.
  2. false를 반환한다.

15.2.3 Runtime Semantics: EvaluateFunctionBody

The syntax-directed operation EvaluateFunctionBody takes arguments functionObject (ECMAScript 함수 객체) and argumentsList (ECMAScript 언어 값의 리스트) and returns return 완료 또는 throw 완료. It is defined piecewise over the following productions:

FunctionBody : FunctionStatementList
  1. FunctionDeclarationInstantiation(functionObject, argumentsList)를 수행한다.
  2. FunctionStatementList의 ? Evaluation을 수행한다.
  3. NOTE: 이전 단계가 정상 완료로 이어졌다면, 평가는 FunctionStatementList의 끝을 지나 진행하여 종료된 것이다.
  4. ReturnCompletion(undefined)을 반환한다.

15.2.4 Runtime Semantics: InstantiateOrdinaryFunctionObject

The syntax-directed operation InstantiateOrdinaryFunctionObject takes arguments env (Environment Record) and privateEnv (PrivateEnvironment Record 또는 null) and returns ECMAScript 함수 객체. It is defined piecewise over the following productions:

FunctionDeclaration : function BindingIdentifier ( FormalParameters ) { FunctionBody }
  1. nameBindingIdentifierStringValue로 둔다.
  2. sourceTextFunctionDeclaration에 의해 매치된 소스 텍스트로 둔다.
  3. closureOrdinaryFunctionCreate(%Function.prototype%, sourceText, FormalParameters, FunctionBody, non-lexical-this, env, privateEnv)로 둔다.
  4. SetFunctionName(closure, name)을 수행한다.
  5. MakeConstructor(closure)를 수행한다.
  6. closure를 반환한다.
FunctionDeclaration : function ( FormalParameters ) { FunctionBody }
  1. sourceTextFunctionDeclaration에 의해 매치된 소스 텍스트로 둔다.
  2. closureOrdinaryFunctionCreate(%Function.prototype%, sourceText, FormalParameters, FunctionBody, non-lexical-this, env, privateEnv)로 둔다.
  3. SetFunctionName(closure, "default")를 수행한다.
  4. MakeConstructor(closure)를 수행한다.
  5. closure를 반환한다.
Note

익명 FunctionDeclarationexport default 선언의 일부로만 나타날 수 있으므로, 그 함수 코드는 항상 엄격 모드 코드이다.

15.2.5 Runtime Semantics: InstantiateOrdinaryFunctionExpression

The syntax-directed operation InstantiateOrdinaryFunctionExpression takes optional argument name (프로퍼티 키 또는 Private Name) and returns ECMAScript 함수 객체. 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. Assert: name은 존재하지 않는다.
  2. nameBindingIdentifierStringValue로 설정한다.
  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

FunctionExpression 안의 BindingIdentifier는 함수가 자기 자신을 재귀적으로 호출할 수 있도록 FunctionExpressionFunctionBody 내부에서 참조될 수 있다. 그러나 FunctionDeclaration에서와 달리, FunctionExpression 안의 BindingIdentifierFunctionExpression을 둘러싼 스코프에서 참조될 수 없으며 그 스코프에 영향을 주지 않는다.

15.2.6 Runtime Semantics: Evaluation

FunctionDeclaration : function BindingIdentifier ( FormalParameters ) { FunctionBody }
  1. empty를 반환한다.
Note 1 FunctionDeclaration : function ( FormalParameters ) { FunctionBody }
  1. empty를 반환한다.
FunctionExpression : function BindingIdentifieropt ( FormalParameters ) { FunctionBody }
  1. FunctionExpressionInstantiateOrdinaryFunctionExpression을 반환한다.
Note 2

FunctionDeclaration 또는 FunctionExpression을 사용하여 정의된 모든 함수에는, 그 함수가 생성자로 사용될 가능성을 허용하기 위해 "prototype" 프로퍼티가 자동으로 생성된다.

FunctionStatementList : [empty]
  1. undefined를 반환한다.

15.3 화살표 함수 정의

구문

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] )

15.3.1 Static Semantics: 조기 오류

ArrowFunction : ArrowParameters => ConciseBody ArrowParameters : CoverParenthesizedExpressionAndArrowParameterList

15.3.2 Static Semantics: ConciseBodyContainsUseStrict

The syntax-directed operation ConciseBodyContainsUseStrict takes no arguments and returns 불리언. It is defined piecewise over the following productions:

ConciseBody : ExpressionBody
  1. false를 반환한다.
ConciseBody : { FunctionBody }
  1. FunctionBodyFunctionBodyContainsUseStrict를 반환한다.

15.3.3 Runtime Semantics: EvaluateConciseBody

The syntax-directed operation EvaluateConciseBody takes arguments functionObject (ECMAScript 함수 객체) and argumentsList (ECMAScript 언어 값들의 List) and returns 반환 완료 또는 던짐 완료. It is defined piecewise over the following productions:

ConciseBody : ExpressionBody
  1. FunctionDeclarationInstantiation(functionObject, argumentsList)를 수행한다.
  2. ExpressionBody의 ? Evaluation을 반환한다.

15.3.4 Runtime Semantics: InstantiateArrowFunctionExpression

The syntax-directed operation InstantiateArrowFunctionExpression takes optional argument name (속성 키 또는 Private Name) and returns ECMAScript 함수 객체. It is defined piecewise over the following productions:

ArrowFunction : ArrowParameters => ConciseBody
  1. name이 존재하지 않으면, name을 빈 String으로 설정한다.
  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 내에서 arguments, super, this, 또는 new.target에 대한 모든 참조는 렉시컬하게 둘러싸는 환경의 바인딩으로 해석되어야 한다. 일반적으로 이는 바로 둘러싸는 함수의 Function Environment가 된다. ArrowFunctionsuper에 대한 참조를 포함할 수 있더라도, 단계 5에서 생성된 함수 객체는 MakeMethod를 수행하여 메서드로 만들어지지 않는다. super를 참조하는 ArrowFunction은 항상 비-ArrowFunction 내에 포함되며, super를 구현하는 데 필요한 상태는 ArrowFunction의 함수 객체가 캡처한 env를 통해 접근할 수 있다.

15.3.5 Runtime Semantics: Evaluation

ArrowFunction : ArrowParameters => ConciseBody
  1. ArrowFunctionInstantiateArrowFunctionExpression을 반환한다.
ExpressionBody : AssignmentExpression
  1. exprRefAssignmentExpression의 ? Evaluation으로 둔다.
  2. exprValue를 ? GetValue(exprRef)로 둔다.
  3. ReturnCompletion(exprValue)를 반환한다.

15.4 메서드 정의

구문

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: 조기 오류

MethodDefinition : ClassElementName ( UniqueFormalParameters ) { FunctionBody } MethodDefinition : set ClassElementName ( PropertySetParameterList ) { FunctionBody }

15.4.2 Static Semantics: HasDirectSuper

The syntax-directed operation HasDirectSuper takes no arguments and returns 불리언. It is defined piecewise over the following productions:

MethodDefinition : ClassElementName ( UniqueFormalParameters ) { FunctionBody }
  1. UniqueFormalParameters Contains SuperCalltrue이면, true를 반환한다.
  2. FunctionBody Contains SuperCall을 반환한다.
MethodDefinition : get ClassElementName ( ) { FunctionBody }
  1. FunctionBody Contains SuperCall을 반환한다.
MethodDefinition : set ClassElementName ( PropertySetParameterList ) { FunctionBody }
  1. PropertySetParameterList Contains SuperCalltrue이면, true를 반환한다.
  2. FunctionBody Contains SuperCall을 반환한다.
GeneratorMethod : * ClassElementName ( UniqueFormalParameters ) { GeneratorBody }
  1. UniqueFormalParameters Contains SuperCalltrue이면, true를 반환한다.
  2. GeneratorBody Contains SuperCall을 반환한다.
AsyncGeneratorMethod : async * ClassElementName ( UniqueFormalParameters ) { AsyncGeneratorBody }
  1. UniqueFormalParameters Contains SuperCalltrue이면, true를 반환한다.
  2. AsyncGeneratorBody Contains SuperCall을 반환한다.
AsyncMethod : async ClassElementName ( UniqueFormalParameters ) { AsyncFunctionBody }
  1. UniqueFormalParameters Contains SuperCalltrue이면, true를 반환한다.
  2. AsyncFunctionBody Contains SuperCall을 반환한다.

15.4.3 Static Semantics: SpecialMethod

The syntax-directed operation SpecialMethod takes no arguments and returns 불리언. It is defined piecewise over the following productions:

MethodDefinition : ClassElementName ( UniqueFormalParameters ) { FunctionBody }
  1. false를 반환한다.
MethodDefinition : GeneratorMethod AsyncMethod AsyncGeneratorMethod get ClassElementName ( ) { FunctionBody } set ClassElementName ( PropertySetParameterList ) { FunctionBody }
  1. true를 반환한다.

15.4.4 Runtime Semantics: DefineMethod

The syntax-directed operation DefineMethod takes argument object (객체) and optional argument functionPrototype (객체) and returns [[Key]](속성 키) 및 [[Closure]](ECMAScript 함수 객체) 필드를 가진 Record를 포함하는 정상 완료 또는 갑작스러운 완료. It is defined piecewise over the following productions:

MethodDefinition : ClassElementName ( UniqueFormalParameters ) { FunctionBody }
  1. propertyKeyClassElementName의 ? Evaluation으로 둔다.
  2. env를 실행 중인 실행 컨텍스트의 LexicalEnvironment로 둔다.
  3. privateEnv를 실행 중인 실행 컨텍스트의 PrivateEnvironment로 둔다.
  4. functionPrototype이 존재하면,
    1. prototypefunctionPrototype으로 둔다.
  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]]: propertyKey, [[Closure]]: closure }를 반환한다.

15.4.5 Runtime Semantics: MethodDefinitionEvaluation

The syntax-directed operation MethodDefinitionEvaluation takes arguments object (an Object) and enumerable (a Boolean) and returns either a normal completion containing either a PrivateElement or unused, or an abrupt completion. It is defined piecewise over the following productions:

MethodDefinition : ClassElementName ( UniqueFormalParameters ) { FunctionBody }
  1. methodDef를 인수 object와 함께 MethodDefinition의 ? DefineMethod로 둔다.
  2. SetFunctionName(methodDef.[[Closure]], methodDef.[[Key]])을 수행한다.
  3. DefineMethodProperty(object, methodDef.[[Key]], methodDef.[[Closure]], enumerable)를 반환한다.
MethodDefinition : get ClassElementName ( ) { FunctionBody }
  1. propertyKeyClassElementName의 ? Evaluation으로 둔다.
  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, propertyKey, "get")을 수행한다.
  9. propertyKeyPrivate Name이면,
    1. PrivateElement { [[Key]]: propertyKey, [[Kind]]: accessor, [[Get]]: closure, [[Set]]: undefined }를 반환한다.
  10. desc를 PropertyDescriptor { [[Get]]: closure, [[Enumerable]]: enumerable, [[Configurable]]: true }로 둔다.
  11. DefinePropertyOrThrow(object, propertyKey, desc)를 수행한다.
  12. unused를 반환한다.
MethodDefinition : set ClassElementName ( PropertySetParameterList ) { FunctionBody }
  1. propertyKeyClassElementName의 ? Evaluation으로 둔다.
  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, propertyKey, "set")을 수행한다.
  8. propertyKeyPrivate Name이면,
    1. PrivateElement { [[Key]]: propertyKey, [[Kind]]: accessor, [[Get]]: undefined, [[Set]]: closure }를 반환한다.
  9. desc를 PropertyDescriptor { [[Set]]: closure, [[Enumerable]]: enumerable, [[Configurable]]: true }로 둔다.
  10. DefinePropertyOrThrow(object, propertyKey, desc)를 수행한다.
  11. unused를 반환한다.
GeneratorMethod : * ClassElementName ( UniqueFormalParameters ) { GeneratorBody }
  1. propertyKeyClassElementName의 ? Evaluation으로 둔다.
  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, propertyKey)을 수행한다.
  8. prototypeOrdinaryObjectCreate(%GeneratorPrototype%)로 둔다.
  9. DefinePropertyOrThrow(closure, "prototype", PropertyDescriptor { [[Value]]: prototype, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false })를 수행한다.
  10. DefineMethodProperty(object, propertyKey, closure, enumerable)를 반환한다.
AsyncGeneratorMethod : async * ClassElementName ( UniqueFormalParameters ) { AsyncGeneratorBody }
  1. propertyKeyClassElementName의 ? Evaluation으로 둔다.
  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, propertyKey)을 수행한다.
  8. prototypeOrdinaryObjectCreate(%AsyncGeneratorPrototype%)로 둔다.
  9. DefinePropertyOrThrow(closure, "prototype", PropertyDescriptor { [[Value]]: prototype, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false })를 수행한다.
  10. DefineMethodProperty(object, propertyKey, closure, enumerable)를 반환한다.
AsyncMethod : async ClassElementName ( UniqueFormalParameters ) { AsyncFunctionBody }
  1. propertyKeyClassElementName의 ? Evaluation으로 둔다.
  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, propertyKey)을 수행한다.
  8. DefineMethodProperty(object, propertyKey, closure, enumerable)를 반환한다.

15.5 제너레이터 함수 정의

구문

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 렉시컬 목표의 사용을 요구한다.

Note 2

YieldExpression은 제너레이터 함수의 FormalParameters 내에서 사용할 수 없다. FormalParameters의 일부인 모든 표현식은 결과 Generator가 재개 가능한 상태가 되기 전에 평가되기 때문이다.

Note 3

Generators와 관련된 추상 연산27.5.3에 정의되어 있다.

15.5.1 Static Semantics: 조기 오류

GeneratorMethod : * ClassElementName ( UniqueFormalParameters ) { GeneratorBody } GeneratorDeclaration : function * BindingIdentifier ( FormalParameters ) { GeneratorBody } function * ( FormalParameters ) { GeneratorBody } GeneratorExpression : function * BindingIdentifieropt ( FormalParameters ) { GeneratorBody }

15.5.2 Runtime Semantics: EvaluateGeneratorBody

The syntax-directed operation EvaluateGeneratorBody takes arguments functionObject (ECMAScript 함수 객체) and argumentsList (ECMAScript 언어 값들의 List) and returns 던짐 완료 또는 반환 완료. It is defined piecewise over the following productions:

GeneratorBody : FunctionBody
  1. FunctionDeclarationInstantiation(functionObject, argumentsList)를 수행한다.
  2. generator를 ? OrdinaryCreateFromConstructor(functionObject, "%GeneratorPrototype%", « [[GeneratorState]], [[GeneratorContext]], [[GeneratorBrand]] »)로 둔다.
  3. generator.[[GeneratorBrand]]empty로 설정한다.
  4. generator.[[GeneratorState]]suspended-start로 설정한다.
  5. GeneratorStart(generator, FunctionBody)를 수행한다.
  6. ReturnCompletion(generator)를 반환한다.

15.5.3 Runtime Semantics: InstantiateGeneratorFunctionObject

The syntax-directed operation InstantiateGeneratorFunctionObject takes arguments env (Environment Record) and privateEnv (PrivateEnvironment Record 또는 null) and returns ECMAScript 함수 객체. It is defined piecewise over the following productions:

GeneratorDeclaration : function * BindingIdentifier ( FormalParameters ) { GeneratorBody }
  1. nameBindingIdentifierStringValue로 둔다.
  2. sourceTextGeneratorDeclaration에 의해 일치된 소스 텍스트로 둔다.
  3. closureOrdinaryFunctionCreate(%GeneratorFunction.prototype%, sourceText, FormalParameters, GeneratorBody, non-lexical-this, env, privateEnv)로 둔다.
  4. SetFunctionName(closure, name)을 수행한다.
  5. prototypeOrdinaryObjectCreate(%GeneratorPrototype%)로 둔다.
  6. DefinePropertyOrThrow(closure, "prototype", PropertyDescriptor { [[Value]]: prototype, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false })를 수행한다.
  7. closure를 반환한다.
GeneratorDeclaration : function * ( FormalParameters ) { GeneratorBody }
  1. sourceTextGeneratorDeclaration에 의해 일치된 소스 텍스트로 둔다.
  2. closureOrdinaryFunctionCreate(%GeneratorFunction.prototype%, sourceText, FormalParameters, GeneratorBody, non-lexical-this, env, privateEnv)로 둔다.
  3. SetFunctionName(closure, "default")를 수행한다.
  4. prototypeOrdinaryObjectCreate(%GeneratorPrototype%)로 둔다.
  5. DefinePropertyOrThrow(closure, "prototype", PropertyDescriptor { [[Value]]: prototype, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false })를 수행한다.
  6. closure를 반환한다.
Note

익명 GeneratorDeclarationexport default 선언의 일부로만 나타날 수 있으며, 따라서 그 함수 코드는 항상 엄격 모드 코드이다.

15.5.4 Runtime Semantics: InstantiateGeneratorFunctionExpression

The syntax-directed operation InstantiateGeneratorFunctionExpression takes optional argument name (속성 키 또는 Private Name) and returns ECMAScript 함수 객체. It is defined piecewise over the following productions:

GeneratorExpression : function * ( FormalParameters ) { GeneratorBody }
  1. name이 존재하지 않으면, name을 빈 String으로 설정한다.
  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. Assert: name은 존재하지 않는다.
  2. nameBindingIdentifierStringValue로 설정한다.
  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

GeneratorExpressionBindingIdentifierGeneratorExpressionFunctionBody 내부에서 참조될 수 있어 제너레이터 코드가 자신을 재귀적으로 호출할 수 있게 한다. 그러나 GeneratorDeclaration에서와 달리, GeneratorExpressionBindingIdentifierGeneratorExpression을 둘러싸는 스코프에서 참조될 수 없고 그 스코프에 영향을 주지 않는다.

15.5.5 Runtime Semantics: Evaluation

GeneratorExpression : function * BindingIdentifieropt ( FormalParameters ) { GeneratorBody }
  1. GeneratorExpressionInstantiateGeneratorFunctionExpression을 반환한다.
YieldExpression : yield
  1. Yield(undefined)를 반환한다.
YieldExpression : yield AssignmentExpression
  1. exprRefAssignmentExpression의 ? Evaluation으로 둔다.
  2. value를 ? GetValue(exprRef)로 둔다.
  3. Yield(value)를 반환한다.
YieldExpression : yield * AssignmentExpression
  1. generatorKindGetGeneratorKind()로 둔다.
  2. Assert: generatorKindsync 또는 async이다.
  3. exprRefAssignmentExpression의 ? Evaluation으로 둔다.
  4. value를 ? GetValue(exprRef)로 둔다.
  5. iteratorRecord를 ? GetIterator(value, generatorKind)로 둔다.
  6. iteratoriteratorRecord.[[Iterator]]로 둔다.
  7. receivedNormalCompletion(undefined)로 둔다.
  8. 반복한다,
    1. received가 정상 완료이면,
      1. innerResult를 ? Call(iteratorRecord.[[NextMethod]], iteratorRecord.[[Iterator]], « received.[[Value]] »)로 둔다.
      2. generatorKindasync이면, innerResult를 ? Await(innerResult)로 설정한다.
      3. innerResult가 객체가 아니면, TypeError 예외를 던진다.
      4. done을 ? IteratorComplete(innerResult)로 둔다.
      5. donetrue이면,
        1. IteratorValue(innerResult)를 반환한다.
      6. generatorKindasync이면, receivedCompletion(AsyncGeneratorYield(? IteratorValue(innerResult)))로 설정한다.
      7. 그렇지 않으면, receivedCompletion(GeneratorYield(innerResult))로 설정한다.
    2. 그렇지 않고 received가 던짐 완료이면,
      1. throw를 ? GetMethod(iterator, "throw")로 둔다.
      2. throwundefined가 아니면,
        1. innerResult를 ? Call(throw, iterator, « received.[[Value]] »)로 둔다.
        2. generatorKindasync이면, innerResult를 ? Await(innerResult)로 설정한다.
        3. NOTE: 내부 반복자의 throw 메서드에서 발생한 예외는 전파된다. 내부 throw 메서드의 정상 완료는 내부 next와 유사하게 처리된다.
        4. innerResult가 객체가 아니면, TypeError 예외를 던진다.
        5. done을 ? IteratorComplete(innerResult)로 둔다.
        6. donetrue이면,
          1. IteratorValue(innerResult)를 반환한다.
        7. generatorKindasync이면, receivedCompletion(AsyncGeneratorYield(? IteratorValue(innerResult)))로 설정한다.
        8. 그렇지 않으면, receivedCompletion(GeneratorYield(innerResult))로 설정한다.
      3. 그렇지 않으면,
        1. NOTE: iteratorthrow 메서드가 없으면, 이 throw는 yield* 루프를 종료하게 된다. 그러나 먼저 iterator에게 정리할 기회를 제공해야 한다.
        2. closeCompletionNormalCompletion(empty)으로 둔다.
        3. generatorKindasync이면, ? AsyncIteratorClose(iteratorRecord, closeCompletion)를 수행한다.
        4. 그렇지 않으면, ? IteratorClose(iteratorRecord, closeCompletion)를 수행한다.
        5. NOTE: 다음 단계는 iteratorthrow 메서드가 없다는 yield* 프로토콜 위반을 나타내기 위해 TypeError를 던진다.
        6. TypeError 예외를 던진다.
    3. 그렇지 않으면,
      1. Assert: received는 반환 완료이다.
      2. return을 ? GetMethod(iterator, "return")로 둔다.
      3. returnundefined이면,
        1. receivedValuereceived.[[Value]]로 둔다.
        2. generatorKindasync이면,
          1. receivedValue를 ? Await(receivedValue)로 설정한다.
        3. ReturnCompletion(receivedValue)를 반환한다.
      4. innerReturnResult를 ? Call(return, iterator, « received.[[Value]] »)로 둔다.
      5. generatorKindasync이면, innerReturnResult를 ? Await(innerReturnResult)로 설정한다.
      6. innerReturnResult가 객체가 아니면, TypeError 예외를 던진다.
      7. done을 ? IteratorComplete(innerReturnResult)로 둔다.
      8. donetrue이면,
        1. returnedValue를 ? IteratorValue(innerReturnResult)로 둔다.
        2. ReturnCompletion(returnedValue)를 반환한다.
      9. generatorKindasync이면, receivedCompletion(AsyncGeneratorYield(? IteratorValue(innerReturnResult)))로 설정한다.
      10. 그렇지 않으면, receivedCompletion(GeneratorYield(innerReturnResult))로 설정한다.

15.6 비동기 제너레이터 함수 정의

구문

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은 비동기 제너레이터 함수의 FormalParameters 내에서 사용할 수 없다. FormalParameters의 일부인 모든 표현식은 결과 AsyncGenerator가 재개 가능한 상태가 되기 전에 평가되기 때문이다.

Note 2

AsyncGenerators와 관련된 추상 연산27.6.3에 정의되어 있다.

15.6.1 Static Semantics: 조기 오류

AsyncGeneratorMethod : async * ClassElementName ( UniqueFormalParameters ) { AsyncGeneratorBody } AsyncGeneratorDeclaration : async function * BindingIdentifier ( FormalParameters ) { AsyncGeneratorBody } async function * ( FormalParameters ) { AsyncGeneratorBody } AsyncGeneratorExpression : async function * BindingIdentifieropt ( FormalParameters ) { AsyncGeneratorBody }

15.6.2 Runtime Semantics: EvaluateAsyncGeneratorBody

The syntax-directed operation EvaluateAsyncGeneratorBody takes arguments functionObject (ECMAScript 함수 객체) and argumentsList (ECMAScript 언어 값들의 List) and returns 던짐 완료 또는 반환 완료. 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 Runtime Semantics: InstantiateAsyncGeneratorFunctionObject

The syntax-directed operation InstantiateAsyncGeneratorFunctionObject takes arguments env (Environment Record) and privateEnv (PrivateEnvironment Record 또는 null) and returns ECMAScript 함수 객체. It is defined piecewise over the following productions:

AsyncGeneratorDeclaration : async function * BindingIdentifier ( FormalParameters ) { AsyncGeneratorBody }
  1. nameBindingIdentifierStringValue로 둔다.
  2. sourceTextAsyncGeneratorDeclaration에 의해 일치된 소스 텍스트로 둔다.
  3. closureOrdinaryFunctionCreate(%AsyncGeneratorFunction.prototype%, sourceText, FormalParameters, AsyncGeneratorBody, non-lexical-this, env, privateEnv)로 둔다.
  4. SetFunctionName(closure, name)을 수행한다.
  5. prototypeOrdinaryObjectCreate(%AsyncGeneratorPrototype%)로 둔다.
  6. DefinePropertyOrThrow(closure, "prototype", PropertyDescriptor { [[Value]]: prototype, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false })를 수행한다.
  7. closure를 반환한다.
AsyncGeneratorDeclaration : async function * ( FormalParameters ) { AsyncGeneratorBody }
  1. sourceTextAsyncGeneratorDeclaration에 의해 일치된 소스 텍스트로 둔다.
  2. closureOrdinaryFunctionCreate(%AsyncGeneratorFunction.prototype%, sourceText, FormalParameters, AsyncGeneratorBody, non-lexical-this, env, privateEnv)로 둔다.
  3. SetFunctionName(closure, "default")를 수행한다.
  4. prototypeOrdinaryObjectCreate(%AsyncGeneratorPrototype%)로 둔다.
  5. DefinePropertyOrThrow(closure, "prototype", PropertyDescriptor { [[Value]]: prototype, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false })를 수행한다.
  6. closure를 반환한다.
Note

익명 AsyncGeneratorDeclarationexport default 선언의 일부로만 나타날 수 있다.

15.6.4 Runtime Semantics: InstantiateAsyncGeneratorFunctionExpression

The syntax-directed operation InstantiateAsyncGeneratorFunctionExpression takes optional argument name (속성 키 또는 Private Name) and returns ECMAScript 함수 객체. It is defined piecewise over the following productions:

AsyncGeneratorExpression : async function * ( FormalParameters ) { AsyncGeneratorBody }
  1. name이 존재하지 않으면, name을 빈 String으로 설정한다.
  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. Assert: name은 존재하지 않는다.
  2. nameBindingIdentifierStringValue로 설정한다.
  3. outerEnv를 실행 중인 실행 컨텍스트의 LexicalEnvironment로 둔다.
  4. funcEnvNewDeclarativeEnvironment(outerEnv)로 둔다.
  5. funcEnv.CreateImmutableBinding(name, false)를 수행한다.
  6. privateEnv를 실행 중인 실행 컨텍스트의 PrivateEnvironment로 둔다.
  7. sourceTextAsyncGeneratorExpression에 의해 일치된 소스 텍스트로 둔다.
  8. closureOrdinaryFunctionCreate(%AsyncGeneratorFunction.prototype%, sourceText, FormalParameters, AsyncGeneratorBody, non-lexical-this, funcEnv, privateEnv)로 둔다.
  9. SetFunctionName(closure, name)을 수행한다.
  10. prototypeOrdinaryObjectCreate(%AsyncGeneratorPrototype%)로 둔다.
  11. DefinePropertyOrThrow(closure, "prototype", PropertyDescriptor { [[Value]]: prototype, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false })를 수행한다.
  12. funcEnv.InitializeBinding(name, closure)를 수행한다.
  13. closure를 반환한다.
Note

AsyncGeneratorExpressionBindingIdentifierAsyncGeneratorExpressionAsyncGeneratorBody 내부에서 참조될 수 있어 제너레이터 코드가 자신을 재귀적으로 호출할 수 있게 한다. 그러나 AsyncGeneratorDeclaration에서와 달리, AsyncGeneratorExpressionBindingIdentifierAsyncGeneratorExpression을 둘러싸는 스코프에서 참조될 수 없고 그 스코프에 영향을 주지 않는다.

15.6.5 Runtime Semantics: Evaluation

AsyncGeneratorExpression : async function * BindingIdentifieropt ( FormalParameters ) { AsyncGeneratorBody }
  1. AsyncGeneratorExpressionInstantiateAsyncGeneratorFunctionExpression을 반환한다.

15.7 클래스 정의

구문

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

클래스 정의는 항상 엄격 모드 코드이다.

15.7.1 Static Semantics: 조기 오류

ClassTail : ClassHeritageopt { ClassBody } ClassBody : ClassElementList
  • ClassElementListPrototypePropertyNameList"constructor"를 두 번 이상 포함하면 구문 오류이다.
  • ClassElementListPrivateBoundIdentifiers에 중복 항목이 있으면 구문 오류이다. 단, 이름이 getter에 한 번, setter에 한 번만 사용되고 다른 항목에는 사용되지 않으며, getter와 setter가 둘 다 정적이거나 둘 다 비정적인 경우는 예외이다.
ClassElement : MethodDefinition ClassElement : static MethodDefinition ClassElement : FieldDefinition ; ClassElement : static FieldDefinition ; FieldDefinition : ClassElementName Initializeropt ClassElementName : PrivateIdentifier ClassStaticBlockBody : ClassStaticBlockStatementList

15.7.2 Static Semantics: ClassElementKind

The syntax-directed operation ClassElementKind takes no arguments and returns constructor-method, non-constructor-method, or empty. It is defined piecewise over the following productions:

ClassElement : MethodDefinition
  1. MethodDefinitionPropName"constructor"이면, constructor-method를 반환한다.
  2. non-constructor-method를 반환한다.
ClassElement : static MethodDefinition FieldDefinition ; static FieldDefinition ;
  1. non-constructor-method를 반환한다.
ClassElement : ClassStaticBlock
  1. non-constructor-method를 반환한다.
ClassElement : ;
  1. empty를 반환한다.

15.7.3 Static Semantics: ConstructorMethod

The syntax-directed operation ConstructorMethod takes no arguments and returns ClassElement 파스 노드 또는 empty. It is defined piecewise over the following productions:

ClassElementList : ClassElement
  1. ClassElementClassElementKindconstructor-method이면, ClassElement를 반환한다.
  2. empty를 반환한다.
ClassElementList : ClassElementList ClassElement
  1. headClassElementListConstructorMethod로 둔다.
  2. headempty가 아니면, head를 반환한다.
  3. ClassElementClassElementKindconstructor-method이면, ClassElement를 반환한다.
  4. empty를 반환한다.
Note

조기 오류 규칙"constructor"라는 이름의 메서드 정의가 하나만 존재하고 그것이 접근자 속성이나 제너레이터 정의가 아님을 보장한다.

15.7.4 Static Semantics: IsStatic

The syntax-directed operation IsStatic takes no arguments and returns 불리언. It is defined piecewise over the following productions:

ClassElement : MethodDefinition
  1. false를 반환한다.
ClassElement : static MethodDefinition
  1. true를 반환한다.
ClassElement : FieldDefinition ;
  1. false를 반환한다.
ClassElement : static FieldDefinition ;
  1. true를 반환한다.
ClassElement : ClassStaticBlock
  1. true를 반환한다.
ClassElement : ;
  1. false를 반환한다.

15.7.5 Static Semantics: NonConstructorElements

The syntax-directed operation NonConstructorElements takes no arguments and returns ClassElement 파스 노드들의 List. It is defined piecewise over the following productions:

ClassElementList : ClassElement
  1. ClassElementClassElementKindnon-constructor-method이면,
    1. « ClassElement »를 반환한다.
  2. 새로운 빈 List를 반환한다.
ClassElementList : ClassElementList ClassElement
  1. listClassElementListNonConstructorElements로 둔다.
  2. ClassElementClassElementKindnon-constructor-method이면,
    1. ClassElementlist에 추가한다.
  3. list를 반환한다.

15.7.6 Static Semantics: PrototypePropertyNameList

The syntax-directed operation PrototypePropertyNameList takes no arguments and returns 속성 키들의 List. It is defined piecewise over the following productions:

ClassElementList : ClassElement
  1. propNameClassElementPropName으로 둔다.
  2. propNameempty이면, 새로운 빈 List를 반환한다.
  3. ClassElementIsStatictrue이면, 새로운 빈 List를 반환한다.
  4. « propName »을 반환한다.
ClassElementList : ClassElementList ClassElement
  1. listClassElementListPrototypePropertyNameList로 둔다.
  2. propNameClassElementPropName으로 둔다.
  3. propNameempty이면, list를 반환한다.
  4. ClassElementIsStatictrue이면, list를 반환한다.
  5. list와 « propName »의 list-concatenation을 반환한다.

15.7.7 Static Semantics: AllPrivateIdentifiersValid

The syntax-directed operation AllPrivateIdentifiersValid takes argument names (String들의 List) and returns 불리언.

이 명세에서 아래에 나열되지 않은 모든 문법 생성식 대안은 암시적으로 AllPrivateIdentifiersValid에 대해 다음 기본 정의를 가진다:

  1. 파스 노드의 각 자식 노드 child에 대해, 다음을 수행한다
    1. child가 비단말의 인스턴스이면,
      1. 인수 names와 함께 childAllPrivateIdentifiersValidfalse이면, false를 반환한다.
  2. true를 반환한다.
MemberExpression : MemberExpression . PrivateIdentifier
  1. namesPrivateIdentifierStringValue를 포함하면,
    1. 인수 names와 함께 MemberExpressionAllPrivateIdentifiersValid를 반환한다.
  2. false를 반환한다.
CallExpression : CallExpression . PrivateIdentifier
  1. namesPrivateIdentifierStringValue를 포함하면,
    1. 인수 names와 함께 CallExpressionAllPrivateIdentifiersValid를 반환한다.
  2. false를 반환한다.
OptionalChain : ?. PrivateIdentifier
  1. namesPrivateIdentifierStringValue를 포함하면, true를 반환한다.
  2. false를 반환한다.
OptionalChain : OptionalChain . PrivateIdentifier
  1. namesPrivateIdentifierStringValue를 포함하면,
    1. 인수 names와 함께 OptionalChainAllPrivateIdentifiersValid를 반환한다.
  2. false를 반환한다.
ClassBody : ClassElementList
  1. newNamesnamesClassBodyPrivateBoundIdentifierslist-concatenation으로 둔다.
  2. 인수 newNames와 함께 ClassElementListAllPrivateIdentifiersValid를 반환한다.
RelationalExpression : PrivateIdentifier in ShiftExpression
  1. namesPrivateIdentifierStringValue를 포함하면,
    1. 인수 names와 함께 ShiftExpressionAllPrivateIdentifiersValid를 반환한다.
  2. false를 반환한다.

15.7.8 Static Semantics: PrivateBoundIdentifiers

The syntax-directed operation PrivateBoundIdentifiers takes no arguments and returns String들의 List. It is defined piecewise over the following productions:

FieldDefinition : ClassElementName Initializeropt
  1. ClassElementNamePrivateBoundIdentifiers를 반환한다.
ClassElementName : PrivateIdentifier
  1. 유일한 원소가 PrivateIdentifierStringValueList를 반환한다.
ClassElementName : PropertyName ClassElement : ClassStaticBlock ;
  1. 새로운 빈 List를 반환한다.
ClassElementList : ClassElementList ClassElement
  1. names1ClassElementListPrivateBoundIdentifiers로 둔다.
  2. names2ClassElementPrivateBoundIdentifiers로 둔다.
  3. names1names2list-concatenation을 반환한다.
MethodDefinition : ClassElementName ( UniqueFormalParameters ) { FunctionBody } get ClassElementName ( ) { FunctionBody } set ClassElementName ( PropertySetParameterList ) { FunctionBody } GeneratorMethod : * ClassElementName ( UniqueFormalParameters ) { GeneratorBody } AsyncMethod : async ClassElementName ( UniqueFormalParameters ) { AsyncFunctionBody } AsyncGeneratorMethod : async * ClassElementName ( UniqueFormalParameters ) { AsyncGeneratorBody }
  1. ClassElementNamePrivateBoundIdentifiers를 반환한다.

15.7.9 Static Semantics: ContainsArguments

The syntax-directed operation ContainsArguments takes no arguments and returns 불리언.

이 명세에서 아래에 나열되지 않은 모든 문법 생성식 대안은 암시적으로 ContainsArguments에 대해 다음 기본 정의를 가진다:

  1. 파스 노드의 각 자식 노드 child에 대해, 다음을 수행한다
    1. child가 비단말의 인스턴스이면,
      1. childContainsArgumentstrue이면, true를 반환한다.
  2. false를 반환한다.
IdentifierReference : Identifier
  1. IdentifierStringValue"arguments"이면, true를 반환한다.
  2. false를 반환한다.
FunctionDeclaration : function BindingIdentifier ( FormalParameters ) { FunctionBody } function ( FormalParameters ) { FunctionBody } FunctionExpression : function BindingIdentifieropt ( FormalParameters ) { FunctionBody } GeneratorDeclaration : function * BindingIdentifier ( FormalParameters ) { GeneratorBody } function * ( FormalParameters ) { GeneratorBody } GeneratorExpression : function * BindingIdentifieropt ( FormalParameters ) { GeneratorBody } AsyncGeneratorDeclaration : async function * BindingIdentifier ( FormalParameters ) { AsyncGeneratorBody } async function * ( FormalParameters ) { AsyncGeneratorBody } AsyncGeneratorExpression : async function * BindingIdentifieropt ( FormalParameters ) { AsyncGeneratorBody } AsyncFunctionDeclaration : async function BindingIdentifier ( FormalParameters ) { AsyncFunctionBody } async function ( FormalParameters ) { AsyncFunctionBody } AsyncFunctionExpression : async function BindingIdentifieropt ( FormalParameters ) { AsyncFunctionBody }
  1. false를 반환한다.
MethodDefinition : ClassElementName ( UniqueFormalParameters ) { FunctionBody } get ClassElementName ( ) { FunctionBody } set ClassElementName ( PropertySetParameterList ) { FunctionBody } GeneratorMethod : * ClassElementName ( UniqueFormalParameters ) { GeneratorBody } AsyncGeneratorMethod : async * ClassElementName ( UniqueFormalParameters ) { AsyncGeneratorBody } AsyncMethod : async ClassElementName ( UniqueFormalParameters ) { AsyncFunctionBody }
  1. ClassElementNameContainsArguments를 반환한다.

15.7.10 Runtime Semantics: ClassFieldDefinitionEvaluation

The syntax-directed operation ClassFieldDefinitionEvaluation takes argument homeObject (객체) and returns ClassFieldDefinition Record를 포함하는 정상 완료 또는 갑작스러운 완료. It is defined piecewise over the following productions:

FieldDefinition : ClassElementName Initializeropt
  1. nameClassElementName의 ? Evaluation으로 둔다.
  2. Initializer가 존재하면,
    1. formalParameterList를 생성식 FormalParameters : [empty] 의 인스턴스로 둔다.
    2. env를 실행 중인 실행 컨텍스트의 LexicalEnvironment로 둔다.
    3. privateEnv를 실행 중인 실행 컨텍스트의 PrivateEnvironment로 둔다.
    4. sourceText를 빈 유니코드 코드 포인트 시퀀스로 둔다.
    5. initializerOrdinaryFunctionCreate(%Function.prototype%, sourceText, formalParameterList, Initializer, non-lexical-this, env, privateEnv)로 둔다.
    6. MakeMethod(initializer, homeObject)를 수행한다.
    7. initializer.[[ClassFieldInitializerName]]name으로 설정한다.
  3. 그렇지 않으면,
    1. initializerempty로 둔다.
  4. ClassFieldDefinition Record { [[Name]]: name, [[Initializer]]: initializer }를 반환한다.
Note
initializer를 위해 생성된 함수는 ECMAScript 코드에서 직접 접근할 수 없다.

15.7.11 Runtime Semantics: ClassStaticBlockDefinitionEvaluation

The syntax-directed operation ClassStaticBlockDefinitionEvaluation takes argument homeObject (객체) and returns ClassStaticBlockDefinition Record. It is defined piecewise over the following productions:

ClassStaticBlock : static { ClassStaticBlockBody }
  1. lex를 실행 중인 실행 컨텍스트의 LexicalEnvironment로 둔다.
  2. privateEnv를 실행 중인 실행 컨텍스트의 PrivateEnvironment로 둔다.
  3. sourceText를 빈 유니코드 코드 포인트 시퀀스로 둔다.
  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 Runtime Semantics: EvaluateClassStaticBlockBody

The syntax-directed operation EvaluateClassStaticBlockBody takes argument functionObject (ECMAScript 함수 객체) and returns 반환 완료 또는 던짐 완료. It is defined piecewise over the following productions:

ClassStaticBlockBody : ClassStaticBlockStatementList
  1. Assert: functionObjectClassStaticBlockDefinitionEvaluation 단계 5에서 생성된 합성 함수이다.
  2. FunctionDeclarationInstantiation(functionObject, « »)를 수행한다.
  3. ClassStaticBlockStatementList의 ? Evaluation을 수행한다.
  4. ReturnCompletion(undefined)를 반환한다.

15.7.13 Runtime Semantics: ClassElementEvaluation

The syntax-directed operation ClassElementEvaluation takes argument object (an Object) and returns either a normal completion containing either a ClassFieldDefinition Record, a ClassStaticBlockDefinition Record, a PrivateElement, or unused, or an abrupt completion. It is defined piecewise over the following productions:

ClassElement : FieldDefinition ; static FieldDefinition ;
  1. 인수 object와 함께 FieldDefinition의 ? ClassFieldDefinitionEvaluation을 반환한다.
ClassElement : MethodDefinition static MethodDefinition
  1. 인수 objectfalse와 함께 MethodDefinition의 ? MethodDefinitionEvaluation을 반환한다.
ClassElement : ClassStaticBlock
  1. 인수 object와 함께 ClassStaticBlockClassStaticBlockDefinitionEvaluation을 반환한다.
ClassElement : ;
  1. unused를 반환한다.

15.7.14 Runtime Semantics: ClassDefinitionEvaluation

The syntax-directed operation ClassDefinitionEvaluation takes arguments classBinding (String 또는 undefined), className (속성 키 또는 Private Name), and sourceText (ECMAScript 소스 텍스트) and returns 함수 객체를 포함하는 정상 완료 또는 갑작스러운 완료.

Note

명세의 편의를 위해 private 메서드와 접근자는 클래스 인스턴스의 [[PrivateElements]] 슬롯에서 private 필드와 함께 포함된다. 그러나 주어진 객체는 주어진 클래스가 정의한 private 메서드와 접근자를 모두 가지거나 전혀 가지지 않는다. 이 기능은 구현체가 각 메서드나 접근자를 개별적으로 추적할 필요가 없는 전략을 사용하여 private 메서드와 접근자를 구현할 수 있도록 설계되었다.

예를 들어, 구현체는 인스턴스 private 메서드를 해당 Private Name과 직접 연결하고, 각 객체에 대해 어떤 클래스 생성자가 그 객체를 this 값으로 하여 실행되었는지를 추적할 수 있다. 그러면 객체에서 인스턴스 private 메서드를 조회하는 것은 그 메서드를 정의한 클래스 생성자가 해당 객체를 초기화하는 데 사용되었는지 확인한 뒤, Private Name과 연결된 메서드를 반환하는 것으로 이루어진다.

이는 private 필드와 다르다. 필드 초기자는 클래스 인스턴스화 중에 던질 수 있으므로, 개별 객체는 주어진 클래스의 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. ClassBodyPrivateBoundIdentifiers의 각 String dn에 대해,
      1. classPrivateEnvironment.[[Names]]pn.[[Description]]dnPrivate Name pn을 포함하면,
        1. Assert: 이는 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. NOTE: ClassHeritage를 평가할 때 실행 중인 실행 컨텍스트의 PrivateEnvironment는 outerPrivateEnvironment이다.
    3. superclassRefClassHeritage 평가의 Completion이라고 하자.
    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. 그렇지 않으면, constructorClassBodyConstructorMethod라고 하자.
  12. 실행 중인 실행 컨텍스트의 LexicalEnvironment를 classEnv로 설정한다.
  13. 실행 중인 실행 컨텍스트의 PrivateEnvironment를 classPrivateEnvironment로 설정한다.
  14. constructorempty이면,
    1. defaultConstructor를, 매개변수가 없고 아무것도 캡처하지 않으며 호출될 때 다음 단계를 수행하는 새로운 Abstract Closure라고 하자:
      1. args[[Call]] 또는 [[Construct]]에 의해 이 함수에 전달된 인수들의 List라고 하자.
      2. NewTarget이 undefined이면, TypeError 예외를 던진다.
      3. constructorFunction을 활성 함수 객체라고 하자.
      4. constructorFunction.[[ConstructorKind]]derived이면,
        1. NOTE: 이 분기는 constructor(...args) { super(...args); }와 유사하게 동작한다. 가장 주목할 만한 차이점은, 앞서 언급한 ECMAScript 소스 텍스트%Array.prototype%%Symbol.iterator% 메서드를 관찰 가능하게 호출하지만, 이 함수는 그렇게 하지 않는다는 점이다.
        2. func를 ! constructorFunction.[[GetPrototypeOf]]()라고 하자.
        3. IsConstructor(func)가 false이면, TypeError 예외를 던진다.
        4. result를 ? Construct(func, args, NewTarget)라고 하자.
      5. 그렇지 않으면,
        1. NOTE: 이 분기는 constructor() {}와 유사하게 동작한다.
        2. result를 ? OrdinaryCreateFromConstructor(NewTarget, "%Object.prototype%")라고 하자.
      6. InitializeInstanceElements(result, constructorFunction)를 수행한다.
      7. NormalCompletion(result)을 반환한다.
    2. constructorFunctionCreateBuiltinFunction(defaultConstructor, 0, className, « [[ConstructorKind]], [[SourceText]], [[PrivateMethods]], [[Fields]] », the current Realm Record, constructorParent)라고 하자.
  15. 그렇지 않으면,
    1. constructorInfoprotoconstructorParent를 인수로 한 constructor의 ! DefineMethod라고 하자.
    2. constructorFunctionconstructorInfo.[[Closure]]라고 하자.
    3. MakeClassConstructor(constructorFunction)를 수행한다.
    4. SetFunctionName(constructorFunction, className)을 수행한다.
  16. constructorFunction.[[SourceText]]sourceText로 설정한다.
  17. MakeConstructor(constructorFunction, false, proto)를 수행한다.
  18. ClassHeritage가 존재하면, constructorFunction.[[ConstructorKind]]derived로 설정한다.
  19. DefineMethodProperty(proto, "constructor", constructorFunction, false)를 수행한다.
  20. ClassBody가 존재하지 않으면, elements를 새로운 빈 List라고 하자.
  21. 그렇지 않으면, elementsClassBodyNonConstructorElements라고 하자.
  22. instancePrivateMethods를 새로운 빈 List라고 하자.
  23. staticPrivateMethods를 새로운 빈 List라고 하자.
  24. instanceFields를 새로운 빈 List라고 하자.
  25. staticElements를 새로운 빈 List라고 하자.
  26. elements의 각 ClassElement e에 대해,
    1. eIsStaticfalse이면,
      1. elementproto를 인수로 한 eClassElementEvaluationCompletion이라고 하자.
    2. 그렇지 않으면,
      1. elementconstructorFunction을 인수로 한 eClassElementEvaluationCompletion이라고 하자.
    3. elementabrupt completion이면,
      1. 실행 중인 실행 컨텍스트의 LexicalEnvironment를 env로 설정한다.
      2. 실행 중인 실행 컨텍스트의 PrivateEnvironment를 outerPrivateEnvironment로 설정한다.
      3. element를 반환한다.
    4. element를 ! element로 설정한다.
    5. elementPrivateElement이면,
      1. Assert: element.[[Kind]]method 또는 accessor 중 하나이다.
      2. eIsStaticfalse이면, containerinstancePrivateMethods라고 하자.
      3. 그렇지 않으면, containerstaticPrivateMethods라고 하자.
      4. container[[Key]]element.[[Key]]PrivateElement pe를 포함하면,
        1. Assert: 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로 교체한다.
      5. 그렇지 않으면,
        1. elementcontainer에 추가한다.
    6. 아니고 elementClassFieldDefinition Record이면,
      1. eIsStaticfalse이면, elementinstanceFields에 추가한다.
      2. 그렇지 않으면, elementstaticElements에 추가한다.
    7. 아니고 elementClassStaticBlockDefinition Record이면,
      1. elementstaticElements에 추가한다.
  27. 실행 중인 실행 컨텍스트의 LexicalEnvironment를 env로 설정한다.
  28. classBindingundefined가 아니면,
    1. classEnv.InitializeBinding(classBinding, constructorFunction)을 수행한다.
  29. constructorFunction.[[PrivateMethods]]instancePrivateMethods로 설정한다.
  30. constructorFunction.[[Fields]]instanceFields로 설정한다.
  31. staticPrivateMethods의 각 PrivateElement method에 대해,
    1. PrivateMethodOrAccessorAdd(constructorFunction, method)를 수행한다.
  32. staticElements의 각 요소 elementRecord에 대해,
    1. elementRecordClassFieldDefinition Record이면,
      1. resultCompletion(DefineField(constructorFunction, elementRecord))라고 하자.
    2. 그렇지 않으면,
      1. Assert: elementRecordClassStaticBlockDefinition Record이다.
      2. resultCompletion(Call(elementRecord.[[BodyFunction]], constructorFunction))라고 하자.
    3. resultabrupt completion이면,
      1. 실행 중인 실행 컨텍스트의 PrivateEnvironment를 outerPrivateEnvironment로 설정한다.
      2. result를 반환한다.
  33. 실행 중인 실행 컨텍스트의 PrivateEnvironment를 outerPrivateEnvironment로 설정한다.
  34. constructorFunction을 반환한다.

15.7.15 Runtime Semantics: BindingClassDeclarationEvaluation

The syntax-directed operation BindingClassDeclarationEvaluation takes no arguments and returns 함수 객체를 포함하는 정상 완료 또는 갑작스러운 완료. It is defined piecewise over the following productions:

ClassDeclaration : class BindingIdentifier ClassTail
  1. classNameBindingIdentifierStringValue로 둔다.
  2. sourceTextClassDeclaration에 의해 일치된 소스 텍스트로 둔다.
  3. value를 인수 className, className, 및 sourceText와 함께 ClassTail의 ? ClassDefinitionEvaluation으로 둔다.
  4. env를 실행 중인 실행 컨텍스트의 LexicalEnvironment로 둔다.
  5. InitializeBoundName(className, value, env)를 수행한다.
  6. value를 반환한다.
ClassDeclaration : class ClassTail
  1. sourceTextClassDeclaration에 의해 일치된 소스 텍스트로 둔다.
  2. 인수 undefined, "default", 및 sourceText와 함께 ClassTail의 ? ClassDefinitionEvaluation을 반환한다.
Note

ClassDeclaration : class ClassTail ExportDeclaration의 일부로만 나타나며 그 바인딩의 설정은 해당 생성식의 평가 동작 일부로 처리된다. 16.2.3.7를 보라.

15.7.16 Runtime Semantics: Evaluation

ClassDeclaration : class BindingIdentifier ClassTail
  1. ClassDeclaration의 ? BindingClassDeclarationEvaluation을 수행한다.
  2. empty를 반환한다.
Note

ClassDeclaration : class ClassTail ExportDeclaration의 일부로만 나타나며 직접 평가되지 않는다.

ClassExpression : class ClassTail
  1. sourceTextClassExpression에 의해 일치된 소스 텍스트로 둔다.
  2. 인수 undefined, 빈 String, 및 sourceText와 함께 ClassTail의 ? ClassDefinitionEvaluation을 반환한다.
ClassExpression : class BindingIdentifier ClassTail
  1. classNameBindingIdentifierStringValue로 둔다.
  2. sourceTextClassExpression에 의해 일치된 소스 텍스트로 둔다.
  3. 인수 className, className, 및 sourceText와 함께 ClassTail의 ? ClassDefinitionEvaluation을 반환한다.
ClassElementName : PrivateIdentifier
  1. privateIdentifierPrivateIdentifierStringValue로 둔다.
  2. privateEnvRec를 실행 중인 실행 컨텍스트의 PrivateEnvironment로 둔다.
  3. namesprivateEnvRec.[[Names]]로 둔다.
  4. Assert: names의 정확히 하나의 원소가 [[Description]]privateIdentifierPrivate Name이다.
  5. privateNamenames 내에서 [[Description]]privateIdentifierPrivate Name으로 둔다.
  6. privateName을 반환한다.
ClassStaticBlockStatementList : [empty]
  1. undefined를 반환한다.

15.8 비동기 함수 정의

구문

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] 매개변수가 존재할 때 awaitAwaitExpression키워드로 파싱된다. [Await] 매개변수는 다음 컨텍스트의 최상위 수준에 존재하지만, FunctionBody와 같은 비단말에 따라 일부 컨텍스트에서는 매개변수가 없을 수 있다:

Script가 구문 목표 기호일 때, [Await] 매개변수가 없으면 await는 식별자로 파싱될 수 있다. 여기에는 다음 컨텍스트가 포함된다:

Note 2

YieldExpression과 달리, AwaitExpression의 피연산자를 생략하는 것은 구문 오류이다. 반드시 무언가를 await해야 한다.

15.8.1 Static Semantics: 조기 오류

AsyncMethod : async ClassElementName ( UniqueFormalParameters ) { AsyncFunctionBody } AsyncFunctionDeclaration : async function BindingIdentifier ( FormalParameters ) { AsyncFunctionBody } async function ( FormalParameters ) { AsyncFunctionBody } AsyncFunctionExpression : async function BindingIdentifieropt ( FormalParameters ) { AsyncFunctionBody }

15.8.2 Runtime Semantics: InstantiateAsyncFunctionObject

The syntax-directed operation InstantiateAsyncFunctionObject takes arguments env (Environment Record) and privateEnv (PrivateEnvironment Record 또는 null) and returns ECMAScript 함수 객체. It is defined piecewise over the following productions:

AsyncFunctionDeclaration : async function BindingIdentifier ( FormalParameters ) { AsyncFunctionBody }
  1. nameBindingIdentifierStringValue로 둔다.
  2. sourceTextAsyncFunctionDeclaration에 의해 일치된 소스 텍스트로 둔다.
  3. closureOrdinaryFunctionCreate(%AsyncFunction.prototype%, sourceText, FormalParameters, AsyncFunctionBody, non-lexical-this, env, privateEnv)로 둔다.
  4. SetFunctionName(closure, name)을 수행한다.
  5. closure를 반환한다.
AsyncFunctionDeclaration : async function ( FormalParameters ) { AsyncFunctionBody }
  1. sourceTextAsyncFunctionDeclaration에 의해 일치된 소스 텍스트로 둔다.
  2. closureOrdinaryFunctionCreate(%AsyncFunction.prototype%, sourceText, FormalParameters, AsyncFunctionBody, non-lexical-this, env, privateEnv)로 둔다.
  3. SetFunctionName(closure, "default")를 수행한다.
  4. closure를 반환한다.

15.8.3 Runtime Semantics: InstantiateAsyncFunctionExpression

The syntax-directed operation InstantiateAsyncFunctionExpression takes optional argument name (속성 키 또는 Private Name) and returns ECMAScript 함수 객체. It is defined piecewise over the following productions:

AsyncFunctionExpression : async function ( FormalParameters ) { AsyncFunctionBody }
  1. name이 존재하지 않으면, name을 빈 String으로 설정한다.
  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. Assert: name은 존재하지 않는다.
  2. nameBindingIdentifierStringValue로 설정한다.
  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

AsyncFunctionExpressionBindingIdentifierAsyncFunctionExpressionAsyncFunctionBody 내부에서 참조될 수 있어 함수가 자신을 재귀적으로 호출할 수 있게 한다. 그러나 FunctionDeclaration에서와 달리, AsyncFunctionExpressionBindingIdentifierAsyncFunctionExpression을 둘러싸는 스코프에서 참조될 수 없고 그 스코프에 영향을 주지 않는다.

15.8.4 Runtime Semantics: EvaluateAsyncFunctionBody

The syntax-directed operation EvaluateAsyncFunctionBody takes arguments functionObject (ECMAScript 함수 객체) and argumentsList (ECMAScript 언어 값들의 List) and returns 반환 완료. It is defined piecewise over the following productions:

AsyncFunctionBody : FunctionBody
  1. promiseCapability를 ! NewPromiseCapability(%Promise%)로 둔다.
  2. completionCompletion(FunctionDeclarationInstantiation(functionObject, argumentsList))으로 둔다.
  3. completion이 갑작스러운 완료이면,
    1. Call(promiseCapability.[[Reject]], undefined, « completion.[[Value]] »)를 수행한다.
  4. 그렇지 않으면,
    1. AsyncFunctionStart(promiseCapability, FunctionBody)를 수행한다.
  5. ReturnCompletion(promiseCapability.[[Promise]])를 반환한다.

15.8.5 Runtime Semantics: Evaluation

AsyncFunctionExpression : async function BindingIdentifieropt ( FormalParameters ) { AsyncFunctionBody }
  1. AsyncFunctionExpressionInstantiateAsyncFunctionExpression을 반환한다.
AwaitExpression : await UnaryExpression
  1. exprRefUnaryExpression의 ? Evaluation으로 둔다.
  2. value를 ? GetValue(exprRef)로 둔다.
  3. Await(value)를 반환한다.

15.9 비동기 화살표 함수 정의

구문

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 Static Semantics: 조기 오류

AsyncArrowFunction : async AsyncArrowBindingIdentifier => AsyncConciseBody AsyncArrowFunction : CoverCallExpressionAndAsyncArrowHead => AsyncConciseBody

15.9.2 Static Semantics: AsyncConciseBodyContainsUseStrict

The syntax-directed operation AsyncConciseBodyContainsUseStrict takes no arguments and returns 불리언. It is defined piecewise over the following productions:

AsyncConciseBody : ExpressionBody
  1. false를 반환한다.
AsyncConciseBody : { AsyncFunctionBody }
  1. AsyncFunctionBodyFunctionBodyContainsUseStrict를 반환한다.

15.9.3 Runtime Semantics: EvaluateAsyncConciseBody

The syntax-directed operation EvaluateAsyncConciseBody takes arguments functionObject (ECMAScript 함수 객체) and argumentsList (ECMAScript 언어 값들의 List) and returns 반환 완료. It is defined piecewise over the following productions:

AsyncConciseBody : ExpressionBody
  1. promiseCapability를 ! NewPromiseCapability(%Promise%)로 둔다.
  2. completionCompletion(FunctionDeclarationInstantiation(functionObject, argumentsList))으로 둔다.
  3. completion이 갑작스러운 완료이면,
    1. Call(promiseCapability.[[Reject]], undefined, « completion.[[Value]] »)를 수행한다.
  4. 그렇지 않으면,
    1. AsyncFunctionStart(promiseCapability, ExpressionBody)를 수행한다.
  5. ReturnCompletion(promiseCapability.[[Promise]])를 반환한다.

15.9.4 Runtime Semantics: InstantiateAsyncArrowFunctionExpression

The syntax-directed operation InstantiateAsyncArrowFunctionExpression takes optional argument name (속성 키 또는 Private Name) and returns ECMAScript 함수 객체. It is defined piecewise over the following productions:

AsyncArrowFunction : async AsyncArrowBindingIdentifier => AsyncConciseBody
  1. name이 존재하지 않으면, name을 빈 String으로 설정한다.
  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을 빈 String으로 설정한다.
  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 Runtime Semantics: Evaluation

AsyncArrowFunction : async AsyncArrowBindingIdentifier => AsyncConciseBody CoverCallExpressionAndAsyncArrowHead => AsyncConciseBody
  1. AsyncArrowFunctionInstantiateAsyncArrowFunctionExpression을 반환한다.

15.10 꼬리 위치 호출

15.10.1 Static Semantics: IsInTailPosition ( call )

The abstract operation IsInTailPosition takes argument call (a CallExpression Parse Node, a MemberExpression Parse Node, or an OptionalChain Parse Node) and returns a Boolean. It performs the following steps when called:

  1. IsStrict(call)가 false이면, false를 반환한다.
  2. callFunctionBody, ConciseBody, 또는 AsyncConciseBody 내에 포함되어 있지 않으면, false를 반환한다.
  3. bodycall을 가장 가깝게 포함하는 FunctionBody, ConciseBody, 또는 AsyncConciseBody로 둔다.
  4. bodyGeneratorBodyFunctionBody이면, false를 반환한다.
  5. bodyAsyncFunctionBodyFunctionBody이면, false를 반환한다.
  6. bodyAsyncGeneratorBodyFunctionBody이면, false를 반환한다.
  7. bodyAsyncConciseBody이면, false를 반환한다.
  8. 인수 call과 함께 bodyHasCallInTailPosition 결과를 반환한다.
Note

꼬리 위치 호출은 호출자 컨텍스트 체인의 관찰을 가능하게 하는 일반적인 비표준 언어 확장(10.2.4 참조) 때문에 엄격 모드 코드에서만 정의된다.

15.10.2 Static Semantics: HasCallInTailPosition

The syntax-directed operation HasCallInTailPosition takes argument call (a CallExpression Parse Node, a MemberExpression Parse Node, or an OptionalChain Parse Node) and returns a Boolean.

Note 1

call은 특정 소스 텍스트 범위를 나타내는 파스 노드이다. 다음 알고리즘이 call을 다른 파스 노드와 비교할 때, 그것은 이들이 동일한 소스 텍스트를 나타내는지에 대한 테스트이다.

Note 2

호출 결과의 GetValue 반환이 바로 뒤따르는 잠재적 꼬리 위치 호출도 가능한 꼬리 위치 호출이다. 함수 호출은 Reference Record를 반환할 수 없으므로, 그러한 GetValue 연산은 항상 실제 함수 호출 결과와 같은 값을 반환한다.

It is defined piecewise over the following productions:

StatementList : StatementList StatementListItem
  1. has를 인수 call과 함께 StatementListHasCallInTailPosition으로 둔다.
  2. hastrue이면, true를 반환한다.
  3. 인수 call과 함께 StatementListItemHasCallInTailPosition을 반환한다.
FunctionStatementList : [empty] StatementListItem : Declaration Statement : VariableStatement EmptyStatement ExpressionStatement ContinueStatement BreakStatement ThrowStatement DebuggerStatement Block : { } ReturnStatement : return ; LabelledItem : FunctionDeclaration ForInOfStatement : for ( LeftHandSideExpression of AssignmentExpression ) Statement for ( var ForBinding of AssignmentExpression ) Statement for ( ForDeclaration of AssignmentExpression ) Statement CaseBlock : { }
  1. false를 반환한다.
IfStatement : if ( Expression ) Statement else Statement
  1. has를 인수 call과 함께 첫 번째 StatementHasCallInTailPosition으로 둔다.
  2. hastrue이면, true를 반환한다.
  3. 인수 call과 함께 두 번째 StatementHasCallInTailPosition을 반환한다.
IfStatement : if ( Expression ) Statement DoWhileStatement : do Statement while ( Expression ) ; WhileStatement : while ( Expression ) Statement ForStatement : for ( Expressionopt ; Expressionopt ; Expressionopt ) Statement for ( var VariableDeclarationList ; Expressionopt ; Expressionopt ) Statement for ( LexicalDeclaration Expressionopt ; Expressionopt ) Statement ForInOfStatement : for ( LeftHandSideExpression in Expression ) Statement for ( var ForBinding in Expression ) Statement for ( ForDeclaration in Expression ) Statement WithStatement : with ( Expression ) Statement
  1. 인수 call과 함께 StatementHasCallInTailPosition을 반환한다.
LabelledStatement : LabelIdentifier : LabelledItem
  1. 인수 call과 함께 LabelledItemHasCallInTailPosition을 반환한다.
ReturnStatement : return Expression ;
  1. 인수 call과 함께 ExpressionHasCallInTailPosition을 반환한다.
SwitchStatement : switch ( Expression ) CaseBlock
  1. 인수 call과 함께 CaseBlockHasCallInTailPosition을 반환한다.
CaseBlock : { CaseClausesopt DefaultClause CaseClausesopt }
  1. hasfalse로 둔다.
  2. 첫 번째 CaseClauses가 존재하면, has를 인수 call과 함께 첫 번째 CaseClausesHasCallInTailPosition으로 설정한다.
  3. hastrue이면, true를 반환한다.
  4. has를 인수 call과 함께 DefaultClauseHasCallInTailPosition으로 설정한다.
  5. hastrue이면, true를 반환한다.
  6. 두 번째 CaseClauses가 존재하면, has를 인수 call과 함께 두 번째 CaseClausesHasCallInTailPosition으로 설정한다.
  7. has를 반환한다.
CaseClauses : CaseClauses CaseClause
  1. has를 인수 call과 함께 CaseClausesHasCallInTailPosition으로 둔다.
  2. hastrue이면, true를 반환한다.
  3. 인수 call과 함께 CaseClauseHasCallInTailPosition을 반환한다.
CaseClause : case Expression : StatementListopt DefaultClause : default : StatementListopt
  1. StatementList가 존재하면, 인수 call과 함께 StatementListHasCallInTailPosition을 반환한다.
  2. false를 반환한다.
TryStatement : try Block Catch
  1. 인수 call과 함께 CatchHasCallInTailPosition을 반환한다.
TryStatement : try Block Finally try Block Catch Finally
  1. 인수 call과 함께 FinallyHasCallInTailPosition을 반환한다.
Catch : catch ( CatchParameter ) Block
  1. 인수 call과 함께 BlockHasCallInTailPosition을 반환한다.
AssignmentExpression : YieldExpression ArrowFunction AsyncArrowFunction LeftHandSideExpression = AssignmentExpression LeftHandSideExpression AssignmentOperator AssignmentExpression LeftHandSideExpression &&= AssignmentExpression LeftHandSideExpression ||= AssignmentExpression LeftHandSideExpression ??= AssignmentExpression BitwiseANDExpression : BitwiseANDExpression & EqualityExpression BitwiseXORExpression : BitwiseXORExpression ^ BitwiseANDExpression BitwiseORExpression : BitwiseORExpression | BitwiseXORExpression EqualityExpression : EqualityExpression == RelationalExpression EqualityExpression != RelationalExpression EqualityExpression === RelationalExpression EqualityExpression !== RelationalExpression RelationalExpression : RelationalExpression < ShiftExpression RelationalExpression > ShiftExpression RelationalExpression <= ShiftExpression RelationalExpression >= ShiftExpression RelationalExpression instanceof ShiftExpression RelationalExpression in ShiftExpression PrivateIdentifier in ShiftExpression ShiftExpression : ShiftExpression << AdditiveExpression ShiftExpression >> AdditiveExpression ShiftExpression >>> AdditiveExpression AdditiveExpression : AdditiveExpression + MultiplicativeExpression AdditiveExpression - MultiplicativeExpression MultiplicativeExpression : MultiplicativeExpression MultiplicativeOperator ExponentiationExpression ExponentiationExpression : UpdateExpression ** ExponentiationExpression UpdateExpression : LeftHandSideExpression ++ LeftHandSideExpression -- ++ UnaryExpression -- UnaryExpression UnaryExpression : delete UnaryExpression void UnaryExpression typeof UnaryExpression + UnaryExpression - UnaryExpression ~ UnaryExpression ! UnaryExpression 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. 인수 call과 함께 AssignmentExpressionHasCallInTailPosition을 반환한다.
ConditionalExpression : ShortCircuitExpression ? AssignmentExpression : AssignmentExpression
  1. has를 인수 call과 함께 첫 번째 AssignmentExpressionHasCallInTailPosition으로 둔다.
  2. hastrue이면, true를 반환한다.
  3. 인수 call과 함께 두 번째 AssignmentExpressionHasCallInTailPosition을 반환한다.
LogicalANDExpression : LogicalANDExpression && BitwiseORExpression
  1. 인수 call과 함께 BitwiseORExpressionHasCallInTailPosition을 반환한다.
LogicalORExpression : LogicalORExpression || LogicalANDExpression
  1. 인수 call과 함께 LogicalANDExpressionHasCallInTailPosition을 반환한다.
CoalesceExpression : CoalesceExpressionHead ?? BitwiseORExpression
  1. 인수 call과 함께 BitwiseORExpressionHasCallInTailPosition을 반환한다.
CallExpression : CoverCallExpressionAndAsyncArrowHead CallExpression Arguments CallExpression TemplateLiteral
  1. CallExpressioncall이면, true를 반환한다.
  2. false를 반환한다.
OptionalExpression : MemberExpression OptionalChain CallExpression OptionalChain OptionalExpression OptionalChain
  1. 인수 call과 함께 OptionalChainHasCallInTailPosition을 반환한다.
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. 인수 call과 함께 exprHasCallInTailPosition을 반환한다.
ParenthesizedExpression : ( Expression )
  1. 인수 call과 함께 ExpressionHasCallInTailPosition을 반환한다.

15.10.3 PrepareForTailCall ( )

The abstract operation PrepareForTailCall takes no arguments and returns unused. It performs the following steps when called:

  1. Assert: 현재 실행 컨텍스트는 이후 어떤 ECMAScript 코드나 내장 함수의 평가에도 사용되지 않는다. 이 추상 연산 호출 이후의 Call 호출은 그러한 평가를 수행하기 전에 새 실행 컨텍스트를 생성하고 푸시한다.
  2. 현재 실행 컨텍스트와 관련된 모든 자원을 폐기한다.
  3. unused를 반환한다.

꼬리 위치 호출은 대상 함수를 호출하기 전에 현재 실행 중인 함수 실행 컨텍스트와 관련된 일시적 내부 자원을 해제하거나, 대상 함수를 지원하기 위해 그 자원을 재사용해야 한다.

Note

예를 들어, 꼬리 위치 호출은 대상 함수의 활성화 레코드 크기가 호출 함수의 활성화 레코드 크기를 초과하는 양만큼만 구현체의 활성화 레코드 스택을 증가시켜야 한다. 대상 함수의 활성화 레코드가 더 작으면, 스택의 전체 크기는 감소해야 한다.

16 ECMAScript 언어: 스크립트와 모듈

16.1 스크립트

구문

Script : ScriptBodyopt ScriptBody : StatementList[~Yield, ~Await, ~Return]

16.1.1 Static Semantics: 조기 오류

Script : ScriptBody ScriptBody : StatementList

16.1.2 Static Semantics: ScriptIsStrict

The syntax-directed operation ScriptIsStrict takes no arguments and returns 불리언. It is defined piecewise over the following productions:

Script : ScriptBodyopt
  1. ScriptBody가 존재하고 ScriptBody의 Directive Prologue가 Use Strict Directive를 포함하면, true를 반환한다.
  2. false를 반환한다.

16.1.3 Runtime Semantics: Evaluation

Script : [empty]
  1. undefined를 반환한다.

16.1.4 Script Records

Script Record는 평가 중인 스크립트에 대한 정보를 캡슐화한다. 각 script record는 Table 34에 나열된 필드를 포함한다.

Table 34: Script Record Fields
필드 이름 값 타입 의미
[[Realm]] Realm Record 이 스크립트가 생성된 realm.
[[ECMAScriptCode]] Script 파스 노드 이 스크립트의 소스 텍스트를 파싱한 결과.
[[LoadedModules]] LoadedModuleRequest RecordsList 이 스크립트가 import한 지정자 문자열에서 해석된 Module Record로의 맵. 이 list는 ModuleRequestsEqual(r1, r2)가 true인 서로 다른 Record r1r2를 포함하지 않는다.
[[HostDefined]] 아무 값(기본값은 empty) 스크립트와 추가 정보를 연결해야 하는 호스트 환경에서 사용하도록 예약된 필드.

16.1.5 ParseScript ( sourceText, realm, hostDefined )

The abstract operation ParseScript takes arguments sourceText (ECMAScript 소스 텍스트), realm (Realm Record), and hostDefined (아무 값) and returns Script Record 또는 비어 있지 않은 SyntaxError 객체들의 List. sourceTextScript로 파싱한 결과에 기반하여 Script Record를 생성한다. It performs the following steps when called:

  1. scriptParseText(sourceText, Script)로 둔다.
  2. script가 오류들의 List이면, 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 언어 값을 포함하는 정상 완료 또는 갑작스러운 완료. 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(scriptEvaluation)으로 설정한다.
    2. result가 정상 완료이고 result.[[Value]]empty이면,
      1. resultNormalCompletion(undefined)으로 설정한다.
  14. scriptContext를 일시 중단하고 실행 컨텍스트 스택에서 제거한다.
  15. Assert: 실행 컨텍스트 스택은 비어 있지 않다.
  16. 이제 실행 컨텍스트 스택의 맨 위에 있는 컨텍스트를 실행 중인 실행 컨텍스트로 재개한다.
  17. result를 반환한다.

16.1.7 GlobalDeclarationInstantiation ( script, env )

The abstract operation GlobalDeclarationInstantiation takes arguments script (Script 파스 노드) and env (Global Environment Record) and returns unused를 포함하는 정상 완료 또는 던짐 완료. script는 실행 컨텍스트가 설정되는 Script이다. env는 바인딩이 생성될 전역 환경이다.

Note 1

스크립트를 평가하기 위해 실행 컨텍스트가 설정될 때, 선언은 현재 전역 환경에서 인스턴스화된다. 코드에서 선언된 각 전역 바인딩이 인스턴스화된다.

호출될 때 다음 단계를 수행한다:

  1. lexNamesscriptLexicallyDeclaredNames로 둔다.
  2. varNamesscriptVarDeclaredNames로 둔다.
  3. lexNames의 각 원소 name에 대해, 다음을 수행한다
    1. HasLexicalDeclaration(env, name)이 true이면, SyntaxError 예외를 던진다.
    2. hasRestrictedGlobal을 ? HasRestrictedGlobalProperty(env, name)로 둔다.
    3. NOTE: 전역 varfunction 바인딩(비엄격 직접 eval에 의해 도입된 것은 제외)은 구성 불가능하므로 제한된 전역 속성이다.
    4. hasRestrictedGlobaltrue이면, SyntaxError 예외를 던진다.
  4. varNames의 각 원소 name에 대해, 다음을 수행한다
    1. HasLexicalDeclaration(env, name)이 true이면, SyntaxError 예외를 던진다.
  5. varDeclarationsscriptVarScopedDeclarations로 둔다.
  6. functionsToInitialize를 새로운 빈 List로 둔다.
  7. declaredFunctionNames를 새로운 빈 List로 둔다.
  8. varDeclarations의 각 원소 varDecl에 대해, List의 역순으로 다음을 수행한다
    1. varDeclVariableDeclaration, ForBinding, 또는 BindingIdentifier 중 하나가 아니면,
      1. Assert: varDeclFunctionDeclaration, GeneratorDeclaration, AsyncFunctionDeclaration, 또는 AsyncGeneratorDeclaration 중 하나이다.
      2. NOTE: 같은 이름에 대해 여러 함수 선언이 있으면, 마지막 선언이 사용된다.
      3. fnvarDeclBoundNames의 유일한 원소로 둔다.
      4. declaredFunctionNamesfn을 포함하지 않으면,
        1. fnDefinable을 ? CanDeclareGlobalFunction(env, fn)으로 둔다.
        2. fnDefinablefalse이면, TypeError 예외를 던진다.
        3. fndeclaredFunctionNames에 추가한다.
        4. varDeclfunctionsToInitialize의 첫 번째 원소로 삽입한다.
  9. declaredVarNames를 새로운 빈 List로 둔다.
  10. varDeclarations의 각 원소 varDecl에 대해, 다음을 수행한다
    1. varDeclVariableDeclaration, ForBinding, 또는 BindingIdentifier 중 하나이면,
      1. varDeclBoundNames의 각 String vn에 대해, 다음을 수행한다
        1. declaredFunctionNamesvn을 포함하지 않으면,
          1. vnDefinable을 ? CanDeclareGlobalVar(env, vn)로 둔다.
          2. vnDefinablefalse이면, TypeError 예외를 던진다.
          3. declaredVarNamesvn을 포함하지 않으면,
            1. vndeclaredVarNames에 추가한다.
  11. NOTE: 전역 객체가 일반 객체이면 이 알고리즘 단계 이후 비정상 종료는 발생하지 않는다. 그러나 전역 객체가 Proxy exotic 객체이면 다음 단계 중 일부에서 비정상 종료를 유발하는 동작을 보일 수 있다.
  12. Normative Optional
    호스트가 웹 브라우저이거나 달리 Block-Level Function Declaration 웹 Legacy 호환성 의미론를 지원하면,
    1. strictscriptScriptIsStrict로 둔다.
    2. strictfalse이면,
      1. declaredFunctionOrVarNamesdeclaredFunctionNamesdeclaredVarNameslist-concatenation으로 둔다.
      2. script Contains xtrue인 임의의 Block, CaseClause, 또는 DefaultClause xStatementList에 직접 포함된 각 FunctionDeclaration f에 대해, 다음을 수행한다
        1. funcNamefBindingIdentifierStringValue로 둔다.
        2. FunctionDeclaration fBindingIdentifierfuncName을 가진 VariableStatement로 대체해도 script에 대해 조기 오류가 발생하지 않으면,
          1. HasLexicalDeclaration(env, funcName)이 false이면,
            1. fnDefinable을 ? CanDeclareGlobalVar(env, funcName)로 둔다.
            2. fnDefinabletrue이면,
              1. NOTE: funcName에 대한 var 바인딩은 그것이 VarDeclaredName도 아니고 다른 FunctionDeclaration의 이름도 아닐 때만 여기서 인스턴스화된다.
              2. declaredFunctionOrVarNamesfuncName을 포함하지 않으면,
                1. CreateGlobalVarBinding(env, funcName, false)를 수행한다.
                2. funcNamedeclaredFunctionOrVarNames에 추가한다.
              3. FunctionDeclaration f가 평가될 때, 15.2.6에 제공된 FunctionDeclaration Evaluation 알고리즘 대신 다음 단계를 수행한다:
                1. gEnv를 실행 중인 실행 컨텍스트의 VariableEnvironment로 둔다.
                2. bEnv를 실행 중인 실행 컨텍스트의 LexicalEnvironment로 둔다.
                3. fObj를 ! bEnv.GetBindingValue(funcName, false)로 둔다.
                4. gEnv.SetMutableBinding(funcName, fObj, false)를 수행한다.
                5. unused를 반환한다.
  13. lexDeclarationsscriptLexicallyScopedDeclarations로 둔다.
  14. privateEnvnull로 둔다.
  15. lexDeclarations의 각 원소 lexDecl에 대해, 다음을 수행한다
    1. NOTE: 렉시컬하게 선언된 이름은 여기서 인스턴스화만 되고 초기화되지는 않는다.
    2. lexDeclBoundNames의 각 원소 dn에 대해, 다음을 수행한다
      1. lexDeclIsConstantDeclarationtrue이면,
        1. env.CreateImmutableBinding(dn, true)를 수행한다.
      2. 그렇지 않으면,
        1. env.CreateMutableBinding(dn, false)를 수행한다.
  16. functionsToInitialize의 각 Parse Node f에 대해, 다음을 수행한다
    1. fnfBoundNames의 유일한 원소로 둔다.
    2. fo를 인수 envprivateEnv와 함께 fInstantiateFunctionObject로 둔다.
    3. CreateGlobalFunctionBinding(env, fn, fo, false)를 수행한다.
  17. declaredVarNames의 각 String vn에 대해, 다음을 수행한다
    1. CreateGlobalVarBinding(env, vn, false)를 수행한다.
  18. unused를 반환한다.
Note 2

16.1.1에 지정된 조기 오류는 단일 Script 내에 포함된 선언에 대해 function/var 선언과 let/const/class 선언 사이의 이름 충돌 및 let/const/class 바인딩의 재선언을 방지한다. 그러나 둘 이상의 Script에 걸친 이러한 충돌과 재선언은 GlobalDeclarationInstantiation 중 런타임 오류로 감지된다. 그러한 오류가 감지되면, 해당 스크립트에 대해 어떤 바인딩도 인스턴스화되지 않는다. 그러나 전역 객체가 Proxy exotic 객체를 사용하여 정의되면 충돌 선언에 대한 런타임 테스트가 신뢰할 수 없어 갑작스러운 완료가 발생하고 일부 전역 선언이 인스턴스화되지 않을 수 있다. 이런 일이 발생하면 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 Static Semantics: 조기 오류

ModuleBody : ModuleItemList Note

중복 ExportedNames 규칙은 ModuleBody 내에 여러 개의 export default ExportDeclaration 항목이 존재하면 구문 오류가 됨을 의미한다. 충돌 또는 중복 선언과 관련된 추가 오류 조건은 모듈 평가 이전의 모듈 링크 단계에서 검사된다. 이러한 오류가 발견되면 해당 Module은 평가되지 않는다.

ModuleExportName : StringLiteral

16.2.1.2 Static Semantics: ImportedLocalNames ( importEntries )

The abstract operation ImportedLocalNames takes argument importEntries (ImportEntry Record들의 List) and returns String들의 List. importEntries에 의해 정의된 모든 로컬 이름 바인딩의 List를 생성한다. It performs the following steps when called:

  1. localNames를 새로운 빈 List로 둔다.
  2. importEntries의 각 ImportEntry Record i에 대해, 다음을 수행한다
    1. i.[[LocalName]]localNames에 추가한다.
  3. localNames를 반환한다.

16.2.1.3 ModuleRequest Records

ModuleRequest Record는 주어진 import 속성과 함께 모듈을 가져오기 위한 요청을 나타낸다. 다음 필드로 구성된다:

Table 35: ModuleRequest Record Fields
필드 이름 값 타입 의미
[[Specifier]] String 모듈 지정자
[[Attributes]] ImportAttribute Record들의 List import 속성들

LoadedModuleRequest Record는 모듈 요청과 해당 결과 Module Record를 함께 나타낸다. 이는 Table 35에 정의된 동일한 필드에 [[Module]]이 추가된 형태이다:

Table 36: LoadedModuleRequest Record Fields
필드 이름 값 타입 의미
[[Specifier]] String 모듈 지정자
[[Attributes]] ImportAttribute Record들의 List import 속성들
[[Module]] Module Record 이 모듈 요청에 해당하는 로드된 모듈

ImportAttribute Record는 다음 필드로 구성된다:

Table 37: ImportAttribute Record Fields
필드 이름 값 타입 의미
[[Key]] String 속성 키
[[Value]] String 속성 값

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 불리언. 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 Static Semantics: ModuleRequests

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

Module : [empty]
  1. 새로운 빈 List를 반환한다.
ModuleItemList : ModuleItem
  1. ModuleItemModuleRequests를 반환한다.
ModuleItemList : ModuleItemList ModuleItem
  1. requestsModuleItemListModuleRequests라고 하자.
  2. additionalRequestsModuleItemModuleRequests라고 하자.
  3. additionalRequests의 각 ModuleRequest Record mr에 대해,
    1. requestsModuleRequestsEqual(mr, mr2)이 trueModuleRequest Record mr2를 포함하지 않으면,
      1. mrrequests에 추가한다.
  4. requests를 반환한다.
ModuleItem : StatementListItem
  1. 새로운 빈 List를 반환한다.
ImportDeclaration : import ImportClause FromClause ;
  1. specifierFromClauseSV라고 하자.
  2. 유일한 요소가 ModuleRequest Record { [[Specifier]]: specifier, [[Attributes]]: « » }인 List를 반환한다.
ImportDeclaration : import ImportClause FromClause WithClause ;
  1. specifierFromClauseSV라고 하자.
  2. attributesWithClauseWithClauseToAttributes라고 하자.
  3. 유일한 요소가 ModuleRequest Record { [[Specifier]]: specifier, [[Attributes]]: attributes }인 List를 반환한다.
ImportDeclaration : import ModuleSpecifier ;
  1. specifierModuleSpecifierSV라고 하자.
  2. 유일한 요소가 ModuleRequest Record { [[Specifier]]: specifier, [[Attributes]]: « » }인 List를 반환한다.
ImportDeclaration : import ModuleSpecifier WithClause ;
  1. specifierModuleSpecifierSV라고 하자.
  2. attributesWithClauseWithClauseToAttributes라고 하자.
  3. 유일한 요소가 ModuleRequest Record { [[Specifier]]: specifier, [[Attributes]]: attributes }인 List를 반환한다.
ExportDeclaration : export ExportFromClause FromClause ;
  1. specifierFromClauseSV라고 하자.
  2. 유일한 요소가 ModuleRequest Record { [[Specifier]]: specifier, [[Attributes]]: « » }인 List를 반환한다.
ExportDeclaration : export ExportFromClause FromClause WithClause ;
  1. specifierFromClauseSV라고 하자.
  2. attributesWithClauseWithClauseToAttributes라고 하자.
  3. 유일한 요소가 ModuleRequest Record { [[Specifier]]: specifier, [[Attributes]]: attributes }인 List를 반환한다.
ExportDeclaration : export NamedExports ; export VariableStatement export Declaration export default HoistableDeclaration export default ClassDeclaration export default AssignmentExpression ;
  1. 새로운 빈 List를 반환한다.

16.2.1.5 추상 모듈 레코드

모듈 레코드는 단일 모듈의 import/export에 대한 구조적 정보를 캡슐화합니다. 이 정보는 연결된 모듈 집합의 import/export 연결에 사용됩니다. 모듈 레코드에는 모듈 평가 시에만 사용되는 네 개의 필드가 포함되어 있습니다.

명세 목적상, 모듈 레코드는 Record 명세 타입의 값이며 간단한 객체지향 계층 구조에서 모듈 레코드가 추상 클래스이고 그 아래에 추상 및 구체 서브클래스가 존재하는 것으로 간주할 수 있습니다. 이 명세는 Cyclic Module Record라는 이름의 추상 서브클래스와 Source Text Module Record라는 이름의 구체 서브클래스를 정의합니다. 다른 명세와 구현에서는 자체적으로 정의한 대체 모듈 정의 수단에 상응하는 추가적인 모듈 레코드 서브클래스를 정의할 수 있습니다.

모듈 레코드는 Table 38 에 나열된 필드를 정의합니다. 모든 모듈 정의 서브클래스는 적어도 이들 필드를 포함합니다. 또한 Table 39 에 있는 추상 메서드 목록도 정의하며, 모든 모듈 정의 서브클래스는 해당 추상 메서드에 대한 구체 구현을 제공해야 합니다.

Table 38: Module Record Fields
필드 이름 값 타입 의미
[[Realm]] 영역(Realm) 레코드 이 모듈이 생성된 영역(Realm).
[[Environment]] 모듈 환경 레코드 또는 empty 이 모듈의 최상위 바인딩을 포함하는 환경 레코드. 이 필드는 모듈이 링크될 때 설정됩니다.
[[Namespace]] 객체 또는 empty 만약 이 모듈에 대해 생성된 경우, 모듈 네임스페이스 객체 (28.3).
[[HostDefined]] 임의 (기본값은 undefined) 호스트 환경이 모듈과 추가 정보를 연관시키기 위해 사용하는 예약 필드.
Table 39: Abstract Methods of Module Records
메서드 목적 정의
LoadRequestedModules ( [ hostDefined ] )

The abstract method LoadRequestedModules takes optional argument hostDefined (anything) and returns 프라미스(Promise).

모든 의존성을 재귀적으로 로드하여 모듈을 링크 준비 상태로 만든다.

이 명세에서는 다음 타입에 정의되어 있으며, 호스트는 자체 정의가 있는 추가 타입을 제공할 수 있습니다:
GetExportedNames ( [ exportStarSet ] )

The abstract method GetExportedNames takes optional argument exportStarSet (a List of Source Text Module Records) and returns a List of Strings.

이 모듈에서 직접 또는 간접적으로 내보내는 모든 이름의 목록을 반환한다.

이 메서드를 호출하기 전에 LoadRequestedModules가 성공적으로 완료되어야 한다.

이 명세에서는 다음 타입에 정의되어 있으며, 호스트는 자체 정의가 있는 추가 타입을 제공할 수 있습니다:
ResolveExport ( exportName [ , resolveSet ] )

The abstract method ResolveExport takes argument exportName (a String) and optional argument resolveSet (a List of Records with fields [[Module]] (a Module Record) and [[ExportName]] (a String)) and returns a ResolvedBinding Record, null, or ambiguous.

이 모듈이 내보내는 이름의 바인딩을 반환한다. 바인딩은 {[[Module]]: 모듈 레코드, [[BindingName]]: 문자열 | namespace} 형식의 ResolvedBinding 레코드 로 표현된다. 내보내기가 모듈 네임스페이스 객체이고 어느 모듈에도 직접 바인딩이 없으면 [[BindingName]]namespace가 들어간다. 이름을 해결할 수 없으면 null을, 여러 바인딩이 발견되면 ambiguous를 반환.

이 연산은 같은 exportName, resolveSet 쌍에 대해 호출할 때마다 동일한 결과를 반환해야 한다.

이 메서드를 호출하기 전에 LoadRequestedModules가 성공적으로 완료되어야 한다.

이 명세에서는 다음 타입에 정의되어 있으며, 호스트는 자체 정의가 있는 추가 타입을 제공할 수 있습니다:
Evaluate ( )

The abstract method Evaluate takes no arguments and returns 프라미스(Promise).

이 모듈과 그 의존성의 평가에 대한 프라미스를 반환하며, 성공하면 resolve 되고 이미 성공한 경우에도 resolve 되고, 평가 오류이거나 이전에 실패했다면 reject. reject 시 호스트는 프라미스 거부를 처리하고 평가 오류를 재throw해야 함. 이 모듈이 Cyclic Module Record가 아니라면, 반환된 프라미스는 이미 판정(settled)된 상태여야 한다.

이 메서드 호출 전 Link가 성공적으로 완료되어야 한다.

이 명세에서는 다음 타입에 정의되어 있으며, 호스트는 자체 정의가 있는 추가 타입을 제공할 수 있습니다:

16.2.1.5.1 EvaluateModuleSync ( module )

The abstract operation EvaluateModuleSync takes argument module (a Module Record) and returns either a normal completion containing unused or a throw completion. 호출자가 module의 평가가 이미 정착(settled)된 프로미스를 반환한다는 것을 보장할 경우, module을 동기적으로 평가한다. It performs the following steps when called:

  1. Assert: moduleCyclic Module Record가 아님을 보장한다.
  2. promisemodule.Evaluate()로 둔다.
  3. Assert: promise.[[PromiseState]]fulfilled 또는 rejected여야 한다.
  4. 만약 promise.[[PromiseState]]rejected라면,
    1. promise.[[PromiseIsHandled]]false이면, HostPromiseRejectionTracker(promise, "handle")를 수행한다.
    2. promise.[[PromiseIsHandled]]true로 설정한다.
    3. promise.[[PromiseResult]]를 throw한다.
  5. unused를 반환한다.

16.2.1.6 Cyclic Module Records

Cyclic Module Record는 다른 Cyclic Module Record 타입의 하위 클래스인 모듈들과 함께 의존성 순환에 참여할 수 있는 모듈에 대한 정보를 나타내기 위해 사용된다. Cyclic Module Record 타입의 하위 클래스가 아닌 Module RecordSource Text Module Records와의 의존성 순환에 참여해서는 안 된다.

Table 38에서 정의된 필드에 추가로, Cyclic Module RecordsTable 40에 나열된 추가 필드를 가진다.

Table 40: Cyclic Module Records의 추가 필드
Field Name Value Type Meaning
[[Status]] new, unlinked, linking, linked, evaluating, evaluating-async, 또는 evaluated 초기값은 new이다. 모듈이 생명주기를 따라 진행됨에 따라 unlinked, linking, linked, evaluating, (필요 시) evaluating-async, evaluated 순으로 전이된다. evaluating-async는 이 모듈이 비동기 의존성 완료 후 실행 대기 중이거나 [[HasTLA]] 필드가 true인 모듈로 이미 실행되었지만 top-level 완료를 기다리는 상태임을 나타낸다.
[[EvaluationError]] throw completion 또는 empty 평가 중 발생한 예외를 나타내는 throw completion이다. 예외가 발생하지 않았거나 [[Status]]evaluated가 아닌 경우 empty이다.
[[DFSAncestorIndex]] 정수 또는 empty LinkEvaluate 과정에서만 사용되는 보조 필드이다. [[Status]]linking 또는 evaluating인 경우, 이는 모듈의 깊이 우선 탐색 인덱스이거나 동일한 강결합 컴포넌트 내의 더 "이전" 모듈의 인덱스이다.
[[RequestedModules]] ModuleRequest Records의 리스트 이 모듈의 import와 관련된 ModuleRequest Records의 리스트이다. 리스트는 소스 코드에서의 import 등장 순서를 따른다.
[[LoadedModules]] LoadedModuleRequest Records의 리스트 이 레코드가 나타내는 모듈이 상대적 import 속성과 함께 모듈을 요청할 때 사용한 specifier 문자열을, 해결된 Module Record로 매핑하는 구조이다. 이 리스트에는 ModuleRequestsEqual(r1, r2)가 true가 되는 서로 다른 두 레코드 r1, r2가 포함되지 않는다.
[[CycleRoot]] Cyclic Module Record 또는 empty 순환의 최초 방문 모듈이며, 강결합 컴포넌트의 루트 DFS 조상이다. 순환에 속하지 않은 모듈의 경우 자기 자신이 된다. Evaluate가 완료되면, 모듈의 [[DFSAncestorIndex]][[CycleRoot]]의 깊이 우선 탐색 인덱스가 된다.
[[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 객체를 해결하기 위해 사용된다. 해당 모듈의 의존성들에서는, 그 의존성 중 일부에 대해 top-level Evaluate()가 시작된 경우가 아니라면 이 필드는 empty이다.
[[AsyncParentModules]] Cyclic Module Records의 리스트 이 모듈 또는 의존성 중 하나가 [[HasTLA]]true이고 실행이 진행 중인 경우, top-level 실행 작업에서 이 모듈의 부모 import 모듈들을 추적한다. 이 부모 모듈들은 이 모듈의 실행이 성공적으로 완료되기 전까지 실행을 시작하지 않는다.
[[PendingAsyncDependencies]] 정수 또는 empty 이 모듈이 비동기 의존성을 가지는 경우, 아직 실행되지 않은 비동기 의존 모듈의 개수를 추적한다. 이 값이 0이 되고 실행 오류가 없을 때 모듈이 실행된다.

Table 39에서 정의된 메서드에 추가로, Cyclic Module RecordsTable 41에 나열된 추가 메서드를 가진다:

Table 41: Cyclic Module Records의 추가 추상 메서드
Method Purpose Definitions
InitializeEnvironment ( )

The abstract method InitializeEnvironment takes no arguments and returns unused 포함하는 normal completion 또는 throw completion.

모듈의 Environment Record를 초기화하며, 모든 import 바인딩을 해결하고 모듈의 실행 컨텍스트를 생성한다.
이 명세에서는 다음 타입들에 정의가 존재하며, 호스트는 자체 정의를 가진 추가 타입을 제공할 수 있다:
ExecuteModule ( [ capability ] )

The abstract method ExecuteModule takes optional argument capability (PromiseCapability Record) and returns unused 포함하는 normal completion 또는 throw completion.

실행 컨텍스트 내에서 모듈 코드를 평가한다. 이 모듈의 [[HasTLA]]true인 경우 PromiseCapability Record가 인자로 전달되며, 메서드는 해당 capability를 resolve 또는 reject해야 한다. 이 경우 메서드는 예외를 throw해서는 안 되며, 필요 시 PromiseCapability Record를 reject해야 한다.
이 명세에서는 다음 타입들에 정의가 존재하며, 호스트는 자체 정의를 가진 추가 타입을 제공할 수 있다:

GraphLoadingState Record는 모듈 그래프의 로딩 과정에 대한 정보를 포함하는 Record이다. 이는 HostLoadImportedModule 호출 이후 로딩을 계속하기 위해 사용된다. 각 GraphLoadingState RecordTable 42에 정의된 필드를 가진다:

Table 42: GraphLoadingState Record 필드
Field Name Value Type Meaning
[[PromiseCapability]] PromiseCapability Record 로딩 프로세스가 완료되면 resolve될 promise이다.
[[IsLoading]] Boolean 로딩 프로세스가 아직 완료되지 않았고, 성공도 실패도 아닌 상태일 때 true이다.
[[PendingModulesCount]] 0 이상의 정수 대기 중인 HostLoadImportedModule 호출의 수를 추적한다.
[[Visited]] Cyclic Module Records의 리스트 현재 로딩 과정에서 이미 로드된 Cyclic Module Records의 리스트로, 순환 의존성으로 인한 무한 루프를 방지한다.
[[HostDefined]] 아무 값 (기본값은 empty) LoadRequestedModules 호출자로부터 HostLoadImportedModule로 전달하기 위한 호스트 정의 데이터를 포함한다.

16.2.1.6.1 Module Record 추상 메서드의 구현

다음은 Table 39에 정의된 해당 Module Record 추상 메서드를 구현하는 Cyclic Module Record의 구체적인 메서드이다.

16.2.1.6.1.1 LoadRequestedModules ( [ hostDefined ] )

The LoadRequestedModules concrete method of a Cyclic Module Record module takes optional argument hostDefined (anything) and returns a Promise. module의 의존성 그래프에 있는 모든 Module Record[[LoadedModules]]를 채운다(대부분의 작업은 보조 함수 InnerModuleLoading이 수행한다). HostLoadImportedModule 훅에 전달되는 optional hostDefined 매개변수를 받는다. 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 매개변수는 가져온 모듈을 fetch하는 데 필요한 추가 정보를 전달하는 데 사용할 수 있다. 예를 들어 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 (a GraphLoadingState Record) and module (a Module Record) and returns unused. LoadRequestedModulesmodule의 의존성 그래프에 대한 실제 로딩 과정을 재귀적으로 수행하는 데 사용한다. It performs the following steps when called:

  1. Assert: state.[[IsLoading]]true이다.
  2. moduleCyclic Module Record이고, module.[[Status]]new이며, state.[[Visited]]module을 포함하지 않으면,
    1. modulestate.[[Visited]]에 추가한다.
    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. 그렇지 않고 module.[[LoadedModules]]ModuleRequestsEqual(record, request)가 trueLoadedModuleRequest Record record를 포함하면,
        1. InnerModuleLoading(state, record.[[Module]])을 수행한다.
      3. 그렇지 않으면,
        1. HostLoadImportedModule(module, request, state.[[HostDefined]], state)를 수행한다.
        2. NOTE: HostLoadImportedModuleFinishLoadingImportedModule을 호출하며, 이는 ContinueModuleLoading을 통해 그래프 로딩 과정에 다시 진입한다.
      4. state.[[IsLoading]]false이면, unused를 반환한다.
  3. Assert: state.[[PendingModulesCount]] ≥ 1.
  4. state.[[PendingModulesCount]]state.[[PendingModulesCount]] - 1로 설정한다.
  5. state.[[PendingModulesCount]] = 0이면,
    1. state.[[IsLoading]]false로 설정한다.
    2. state.[[Visited]]의 각 Cyclic Module Record loaded에 대해,
      1. loaded.[[Status]]new이면, loaded.[[Status]]unlinked로 설정한다.
    3. Call(state.[[PromiseCapability]].[[Resolve]], undefined, « undefined »)을 수행한다.
  6. unused를 반환한다.

16.2.1.6.1.1.2 ContinueModuleLoading ( state, moduleCompletion )

The abstract operation ContinueModuleLoading takes arguments state (a GraphLoadingState Record) and moduleCompletion (either a normal completion containing a Module Record or a throw completion) and returns unused. HostLoadImportedModule 호출 이후 로딩 과정에 다시 진입하는 데 사용된다. It performs the following steps when called:

  1. state.[[IsLoading]]false이면, unused를 반환한다.
  2. moduleCompletionnormal completion이면,
    1. InnerModuleLoading(state, moduleCompletion.[[Value]])을 수행한다.
  3. 그렇지 않으면,
    1. state.[[IsLoading]]false로 설정한다.
    2. Call(state.[[PromiseCapability]].[[Reject]], undefined, « moduleCompletion.[[Value]] »)을 수행한다.
  4. unused를 반환한다.

16.2.1.6.1.2 Link ( )

The Link concrete method of a Cyclic Module Record module takes no arguments and returns either a normal completion containing unused or a throw completion. 성공 시, Link는 이 모듈의 [[Status]]unlinked에서 linked로 전환한다. 실패 시, 예외가 던져지고 이 모듈의 [[Status]]unlinked로 남는다. (대부분의 작업은 보조 함수 InnerModuleLinking이 수행한다.) It performs the following steps when called:

  1. Assert: module.[[Status]]unlinked, linked, evaluating-async, 또는 evaluated 중 하나이다.
  2. stack을 새 빈 List로 둔다.
  3. resultCompletion(InnerModuleLinking(module, stack, 0))으로 둔다.
  4. resultabrupt completion이면,
    1. stack의 각 Cyclic Module Record m에 대해,
      1. Assert: m.[[Status]]linking이다.
      2. m.[[Status]]unlinked로 설정한다.
    2. Assert: module.[[Status]]unlinked이다.
    3. result를 반환한다.
  5. Assert: module.[[Status]]linked, evaluating-async, 또는 evaluated 중 하나이다.
  6. Assert: stack은 비어 있다.
  7. unused를 반환한다.

16.2.1.6.1.2.1 InnerModuleLinking ( module, stack, index )

The abstract operation InnerModuleLinking takes arguments module (a Module Record), stack (a List of Cyclic Module Records), and index (a non-negative integer) and returns either a normal completion containing a non-negative integer or a throw completion. Linkmodule에 대한 실제 링킹 과정을 수행하고, 의존성 그래프의 다른 모든 모듈에도 재귀적으로 수행하는 데 사용한다. 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. Assert: 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. Assert: requiredModule.[[Status]]linking, linked, evaluating-async, 또는 evaluated 중 하나이다.
      2. Assert: requiredModule.[[Status]]linking인 것은 stackrequiredModule을 포함할 때 그리고 그때뿐이다.
      3. requiredModule.[[Status]]linking이면,
        1. module.[[DFSAncestorIndex]]min(module.[[DFSAncestorIndex]], requiredModule.[[DFSAncestorIndex]])로 설정한다.
  10. module.InitializeEnvironment()를 수행한다.
  11. Assert: modulestack 안에 정확히 한 번 나타난다.
  12. Assert: module.[[DFSAncestorIndex]]moduleIndex.
  13. module.[[DFSAncestorIndex]] = moduleIndex이면,
    1. donefalse로 둔다.
    2. donefalse인 동안 반복한다.
      1. requiredModulestack의 마지막 요소로 둔다.
      2. stack의 마지막 요소를 제거한다.
      3. Assert: requiredModuleCyclic Module Record이다.
      4. requiredModule.[[Status]]linked로 설정한다.
      5. requiredModulemodule이 같은 Module Record이면, donetrue로 설정한다.
  14. index를 반환한다.

16.2.1.6.1.3 Evaluate ( )

The Evaluate concrete method of a Cyclic Module Record module takes no arguments and returns a Promise. Evaluate는 이 모듈의 [[Status]]linked에서 evaluating-async 또는 evaluated로 전환한다. 주어진 강한 연결 요소 안의 모듈에서 처음 호출될 때, Evaluate는 모듈 평가가 끝나면 resolve되는 Promise를 생성하고 반환한다. 이 Promise는 해당 요소의 [[CycleRoot]][[TopLevelCapability]] 필드에 저장된다. 그 요소 안의 어떤 모듈에서 Evaluate가 나중에 호출되더라도 같은 Promise를 반환한다. (대부분의 작업은 보조 함수 InnerModuleEvaluation이 수행한다.) It performs the following steps when called:

  1. Assert: Evaluate에 대한 이 호출은 주변 agent 안에서 Evaluate에 대한 다른 호출과 동시에 일어나고 있지 않다.
  2. Assert: module.[[Status]]linked, evaluating-async, 또는 evaluated 중 하나이다.
  3. module.[[Status]]evaluating-async 또는 evaluated이면,
    1. module.[[CycleRoot]]empty가 아니면,
      1. modulemodule.[[CycleRoot]]로 설정한다.
    2. 그렇지 않으면,
      1. Assert: module.[[Status]]evaluated이고 module.[[EvaluationError]]throw completion이다.
  4. module.[[TopLevelCapability]]empty가 아니면,
    1. module.[[TopLevelCapability]].[[Promise]]를 반환한다.
  5. stack을 새 빈 List로 둔다.
  6. capability를 ! NewPromiseCapability(%Promise%)로 둔다.
  7. module.[[TopLevelCapability]]capability로 설정한다.
  8. resultCompletion(InnerModuleEvaluation(module, stack, 0))으로 둔다.
  9. resultabrupt completion이면,
    1. stack의 각 Cyclic Module Record m에 대해,
      1. Assert: m.[[Status]]evaluating이다.
      2. m.[[Status]]evaluated로 설정한다.
      3. m.[[EvaluationError]]result로 설정한다.
    2. Assert: module.[[Status]]evaluated이다.
    3. Assert: module.[[EvaluationError]]result는 같은 Completion Record이다.
    4. Call(capability.[[Reject]], undefined, « result.[[Value]] »)을 수행한다.
  10. 그렇지 않으면,
    1. Assert: module.[[Status]]evaluating-async 또는 evaluated이다.
    2. Assert: module.[[EvaluationError]]empty이다.
    3. module.[[Status]]evaluated이면,
      1. Assert: module.[[AsyncEvaluationOrder]]unset 또는 done이다.
      2. NOTE: module이 이미 평가되었고 그 평가가 비동기였을 때 그리고 그때에만 module.[[AsyncEvaluationOrder]]done이다.
      3. Call(capability.[[Resolve]], undefined, « undefined »)을 수행한다.
    4. Assert: stack은 비어 있다.
  11. capability.[[Promise]]를 반환한다.

16.2.1.6.1.3.1 InnerModuleEvaluation ( module, stack, index )

The abstract operation InnerModuleEvaluation takes arguments module (a Module Record), stack (a List of Cyclic Module Records), and index (a non-negative integer) and returns either a normal completion containing a non-negative integer or a throw completion. Evaluatemodule에 대한 실제 평가 과정을 수행하고, 의존성 그래프의 다른 모든 모듈에도 재귀적으로 수행하는 데 사용한다. stackindex 매개변수와 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. Assert: module.[[Status]]linked이다.
  5. module.[[Status]]evaluating으로 설정한다.
  6. moduleIndexindex로 둔다.
  7. module.[[DFSAncestorIndex]]index로 설정한다.
  8. module.[[PendingAsyncDependencies]]를 0으로 설정한다.
  9. indexindex + 1로 설정한다.
  10. modulestack에 추가한다.
  11. module.[[RequestedModules]]의 각 ModuleRequest Record request에 대해,
    1. requiredModuleGetImportedModule(module, request)로 둔다.
    2. index를 ? InnerModuleEvaluation(requiredModule, stack, index)로 설정한다.
    3. requiredModuleCyclic Module Record이면,
      1. Assert: requiredModule.[[Status]]evaluating, evaluating-async, 또는 evaluated 중 하나이다.
      2. Assert: requiredModule.[[Status]]evaluating인 것은 stackrequiredModule을 포함할 때 그리고 그때뿐이다.
      3. requiredModule.[[Status]]evaluating이면,
        1. module.[[DFSAncestorIndex]]min(module.[[DFSAncestorIndex]], requiredModule.[[DFSAncestorIndex]])로 설정한다.
      4. 그렇지 않으면,
        1. requiredModulerequiredModule.[[CycleRoot]]로 설정한다.
        2. Assert: requiredModule.[[Status]]evaluating-async 또는 evaluated이다.
        3. requiredModule.[[EvaluationError]]empty가 아니면, ? requiredModule.[[EvaluationError]]를 반환한다.
      5. requiredModule.[[AsyncEvaluationOrder]]정수이면,
        1. module.[[PendingAsyncDependencies]]module.[[PendingAsyncDependencies]] + 1로 설정한다.
        2. modulerequiredModule.[[AsyncParentModules]]에 추가한다.
  12. module.[[PendingAsyncDependencies]] > 0이거나 module.[[HasTLA]]true이면,
    1. Assert: module.[[AsyncEvaluationOrder]]unset이다.
    2. module.[[AsyncEvaluationOrder]]IncrementModuleAsyncEvaluationCount()로 설정한다.
    3. module.[[PendingAsyncDependencies]] = 0이면, ExecuteAsyncModule(module)을 수행한다.
  13. 그렇지 않으면,
    1. module.ExecuteModule()을 수행한다.
  14. Assert: modulestack 안에 정확히 한 번 나타난다.
  15. Assert: module.[[DFSAncestorIndex]]moduleIndex.
  16. module.[[DFSAncestorIndex]] = moduleIndex이면,
    1. donefalse로 둔다.
    2. donefalse인 동안 반복한다.
      1. requiredModulestack의 마지막 요소로 둔다.
      2. stack의 마지막 요소를 제거한다.
      3. Assert: requiredModuleCyclic Module Record이다.
      4. Assert: requiredModule.[[AsyncEvaluationOrder]]정수 또는 unset이다.
      5. requiredModule.[[AsyncEvaluationOrder]]unset이면, requiredModule.[[Status]]evaluated로 설정한다.
      6. 그렇지 않으면, requiredModule.[[Status]]evaluating-async로 설정한다.
      7. requiredModulemodule이 같은 Module Record이면, donetrue로 설정한다.
      8. requiredModule.[[CycleRoot]]module로 설정한다.
  17. index를 반환한다.
Note 1

모듈은 InnerModuleEvaluation에 의해 순회되는 동안 evaluating이다. 모듈은 실행 완료 시 evaluated가 되거나, [[HasTLA]] 필드가 true이거나 비동기 의존성이 있으면 실행 중 evaluating-async가 된다.

Note 2

비동기 cycle의 모듈에 의존하는 모든 모듈은, 그 cycle이 evaluating이 아닐 때, 대신 [[CycleRoot]]를 통해 cycle의 루트 실행에 의존한다. 이는 cycle 상태를 루트 모듈 상태를 통해 하나의 강한 연결 요소로 취급할 수 있게 보장한다.

16.2.1.6.1.3.2 ExecuteAsyncModule ( module )

The abstract operation ExecuteAsyncModule takes argument module (a Cyclic Module Record) and returns unused. It performs the following steps when called:

  1. Assert: module.[[Status]]evaluating 또는 evaluating-async이다.
  2. Assert: module.[[HasTLA]]true이다.
  3. capability를 ! NewPromiseCapability(%Promise%)로 둔다.
  4. fulfilledClosuremodule을 캡처하고 호출될 때 다음 단계를 수행하는, 매개변수가 없는 새 Abstract Closure로 둔다.
    1. AsyncModuleExecutionFulfilled(module)을 수행한다.
    2. NormalCompletion(undefined)을 반환한다.
  5. onFulfilledCreateBuiltinFunction(fulfilledClosure, 0, "", « »)로 둔다.
  6. rejectedClosuremodule을 캡처하고 호출될 때 다음 단계를 수행하는, 매개변수 (error)를 가진 새 Abstract Closure로 둔다.
    1. AsyncModuleExecutionRejected(module, error)를 수행한다.
    2. NormalCompletion(undefined)을 반환한다.
  7. onRejectedCreateBuiltinFunction(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 (a Cyclic Module Record) and execList (a List of Cyclic Module Records) and returns unused. It performs the following steps when called:

  1. module.[[AsyncParentModules]]의 각 Cyclic Module Record m에 대해,
    1. execListm을 포함하지 않고 m.[[CycleRoot]].[[EvaluationError]]empty이면,
      1. Assert: m.[[Status]]evaluating-async이다.
      2. Assert: m.[[EvaluationError]]empty이다.
      3. Assert: m.[[AsyncEvaluationOrder]]정수이다.
      4. Assert: m.[[PendingAsyncDependencies]] > 0.
      5. m.[[PendingAsyncDependencies]]m.[[PendingAsyncDependencies]] - 1로 설정한다.
      6. m.[[PendingAsyncDependencies]] = 0이면,
        1. mexecList에 추가한다.
        2. m.[[HasTLA]]false이면, GatherAvailableAncestors(m, execList)를 수행한다.
  2. unused를 반환한다.
Note

루트 module에 대한 비동기 실행이 fulfilled되면, 이 함수는 이 완료에서 함께 동기적으로 실행할 수 있는 모듈들의 목록을 결정하여 execList에 채운다.

16.2.1.6.1.3.4 AsyncModuleExecutionFulfilled ( module )

The abstract operation AsyncModuleExecutionFulfilled takes argument module (a Cyclic Module Record) and returns unused. It performs the following steps when called:

  1. module.[[Status]]evaluated이면,
    1. Assert: module.[[EvaluationError]]empty가 아니다.
    2. unused를 반환한다.
  2. Assert: module.[[Status]]evaluating-async이다.
  3. Assert: module.[[AsyncEvaluationOrder]]정수이다.
  4. Assert: module.[[EvaluationError]]empty이다.
  5. module.[[AsyncEvaluationOrder]]done으로 설정한다.
  6. module.[[Status]]evaluated로 설정한다.
  7. module.[[TopLevelCapability]]empty가 아니면,
    1. Assert: module.[[CycleRoot]]module은 같은 Module Record이다.
    2. Call(module.[[TopLevelCapability]].[[Resolve]], undefined, « undefined »)을 수행한다.
  8. execList를 새 빈 List로 둔다.
  9. GatherAvailableAncestors(module, execList)를 수행한다.
  10. Assert: execList의 모든 요소는 [[AsyncEvaluationOrder]] 필드가 정수로 설정되어 있고, [[PendingAsyncDependencies]] 필드가 0으로 설정되어 있으며, [[EvaluationError]] 필드가 empty로 설정되어 있다.
  11. sortedExecListexecList의 요소들을 [[AsyncEvaluationOrder]] 필드의 오름차순으로 정렬한 요소들을 갖는 List로 둔다.
  12. sortedExecList의 각 Cyclic Module Record m에 대해,
    1. m.[[Status]]evaluated이면,
      1. Assert: m.[[EvaluationError]]empty가 아니다.
    2. 그렇지 않고 m.[[HasTLA]]true이면,
      1. ExecuteAsyncModule(m)을 수행한다.
    3. 그렇지 않으면,
      1. resultCompletion(m.ExecuteModule())으로 둔다.
      2. resultabrupt completion이면,
        1. AsyncModuleExecutionRejected(m, result.[[Value]])를 수행한다.
      3. 그렇지 않으면,
        1. m.[[AsyncEvaluationOrder]]done으로 설정한다.
        2. m.[[Status]]evaluated로 설정한다.
        3. m.[[TopLevelCapability]]empty가 아니면,
          1. Assert: m.[[CycleRoot]]m은 같은 Module Record이다.
          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 (a Cyclic Module Record) and error (an ECMAScript language value) and returns unused. It performs the following steps when called:

  1. module.[[Status]]evaluated이면,
    1. Assert: module.[[EvaluationError]]empty가 아니다.
    2. unused를 반환한다.
  2. Assert: module.[[Status]]evaluating-async이다.
  3. Assert: module.[[AsyncEvaluationOrder]]정수이다.
  4. Assert: module.[[EvaluationError]]empty이다.
  5. module.[[EvaluationError]]ThrowCompletion(error)로 설정한다.
  6. module.[[Status]]evaluated로 설정한다.
  7. module.[[AsyncEvaluationOrder]]done으로 설정한다.
  8. NOTE: module.[[AsyncEvaluationOrder]]AsyncModuleExecutionFulfilled와의 대칭성을 위해 done으로 설정된다. InnerModuleEvaluation에서 모듈의 [[AsyncEvaluationOrder]] 내부 슬롯 값은 그 [[EvaluationError]] 내부 슬롯이 empty가 아닐 때 사용되지 않는다.
  9. module.[[TopLevelCapability]]empty가 아니면,
    1. Assert: module.[[CycleRoot]]module은 같은 Module Record이다.
    2. Call(module.[[TopLevelCapability]].[[Reject]], undefined, « error »)을 수행한다.
  10. module.[[AsyncParentModules]]의 각 Cyclic Module Record m에 대해,
    1. AsyncModuleExecutionRejected(m, error)를 수행한다.
  11. unused를 반환한다.

16.2.1.6.2 Cyclic Module Record 그래프 예시

이 비규범 절은 몇 가지 일반적인 모듈 그래프의 링킹 및 평가 예시를, 오류가 어떻게 발생할 수 있는지에 특히 초점을 맞추어 제시한다.

먼저 다음의 단순한 모듈 그래프를 생각해 보자.

Figure 2: 단순한 모듈 그래프
모듈 A가 모듈 B에 의존하고, 모듈 B가 모듈 C에 의존하는 모듈 그래프

먼저 오류 조건이 없다고 가정하자. 호스트가 처음 A.LoadRequestedModules()를 호출하면, 가정에 따라 성공적으로 완료되고 BC의 의존성도 각각 재귀적으로 로드한다(각각 C 및 없음). 그런 다음 A.[[Status]] = B.[[Status]] = C.[[Status]] = unlinked로 설정한다. 이어서 호스트A.Link()를 호출하면, 이 역시 가정에 따라 성공적으로 완료되어 A.[[Status]] = B.[[Status]] = C.[[Status]] = linked가 된다. 이러한 준비 단계는 언제든 수행할 수 있다. 나중에 호스트가 모듈의 가능한 부수 효과를 감수할 준비가 되면 A.Evaluate()를 호출할 수 있으며, 이는 성공적으로 완료되어 undefined로 resolve되는 Promise를 반환한다(역시 가정에 따라). 이 과정에서 먼저 C, 그다음 B가 재귀적으로 평가된다. 이 시점에서 각 모듈의 [[Status]]evaluated가 된다.

그다음 A.LoadRequestedModules() 호출이 성공한 뒤 링킹 오류가 관련된 경우를 생각해 보자. CInnerModuleLinking은 성공하지만 그 이후 B에서 실패한다면, 예를 들어 C가 제공하지 않는 것을 import하기 때문이라면, 원래의 A.Link()는 실패하고 AB[[Status]]는 모두 unlinked로 남는다. 하지만 C[[Status]]linked가 된다.

마지막으로, Link() 호출이 성공한 뒤 평가 오류가 관련된 경우를 생각해 보자. CInnerModuleEvaluation은 성공하지만 그 이후 B에서 실패한다면, 예를 들어 B에 예외를 던지는 코드가 포함되어 있기 때문이라면, 원래의 A.Evaluate()는 실패하고 rejected Promise를 반환한다. 그 결과 예외는 AB[[EvaluationError]] 필드 모두에 기록되고, 이들의 [[Status]]evaluated가 된다. Cevaluated가 되지만, AB와 달리 평가를 성공적으로 완료했으므로 [[EvaluationError]] 없이 남는다. 예외를 저장하면 호스트Evaluate() 메서드를 호출해 A 또는 B를 재사용하려 할 때마다 같은 예외를 만나게 된다. (호스트Cyclic Module Record를 재사용해야 하는 것은 아니며, 마찬가지로 호스트가 이 메서드들이 던진 예외 객체를 노출해야 하는 것도 아니다. 그러나 명세는 그러한 사용을 가능하게 한다.)

이제 다른 유형의 오류 조건을 생각해 보자.

Figure 3: 해결할 수 없는 모듈이 있는 모듈 그래프
모듈 A가 ???로 표시된 누락된(해결할 수 없는) 모듈에 의존하는 모듈 그래프

이 시나리오에서 모듈 A는 어떤 다른 모듈에 대한 의존성을 선언하지만, 그 모듈에 대한 Module Record가 존재하지 않는다. 즉 HostLoadImportedModule은 그것을 요청받았을 때 예외와 함께 FinishLoadingImportedModule을 호출한다. 이는 해당 리소스가 존재하지 않거나, 리소스는 존재하지만 결과 소스 텍스트를 파싱하려 할 때 ParseModule이 오류를 반환하는 등 다양한 이유로 발생할 수 있다. 호스트FinishLoadingImportedModule에 전달하는 completion을 통해 실패 원인을 노출하도록 선택할 수 있다. 어떤 경우든 이 예외는 로딩 실패를 일으키며, 그 결과 A[[Status]]new로 남는다.

여기서 로딩, 링킹, 평가 오류 사이의 차이는 다음 특성 때문이다.

  • 평가는 부수 효과를 일으킬 수 있으므로 한 번만 수행되어야 한다. 따라서 평가가 이미 수행되었는지, 성공하지 못했더라도, 기억하는 것이 중요하다. (오류의 경우, 예외도 기억하는 것이 타당하다. 그렇지 않으면 이후 Evaluate() 호출이 새 예외를 합성해야 하기 때문이다.)
  • 반면 링킹은 부수 효과가 없으므로, 실패하더라도 나중에 문제없이 다시 시도할 수 있다.
  • 로딩은 호스트와 밀접하게 상호작용하며, 일부 호스트에서는 사용자가 실패한 로드를 다시 시도하도록 허용하는 것이 바람직할 수 있다(예를 들어 일시적인 네트워크 상태 불량으로 실패가 발생한 경우).

이제 cycle이 있는 모듈 그래프를 생각해 보자.

Figure 4: 순환 모듈 그래프
모듈 A가 모듈 B와 C에 의존하지만, 모듈 B도 모듈 A에 의존하는 모듈 그래프

여기서는 진입점이 모듈 A라고 가정하므로, 호스트A.LoadRequestedModules()를 호출하여 진행하고, 이는 A에 대해 InnerModuleLoading을 수행한다. 이는 다시 BC에 대해 InnerModuleLoading을 호출한다. cycle 때문에 다시 A에 대해 InnerModuleLoading이 트리거되지만, 이 시점에는 이 LoadRequestedModules 과정 중 A의 의존성 로딩이 이미 트리거되었으므로 no-op이다. 그래프의 모든 모듈이 성공적으로 로드되면, 이들의 [[Status]]는 동시에 new에서 unlinked로 전환된다.

그다음 호스트A.Link()를 호출하여 진행하고, 이는 A에 대해 InnerModuleLinking을 수행한다. 이는 다시 B에 대해 InnerModuleLinking을 호출한다. cycle 때문에 다시 A에 대해 InnerModuleLinking이 트리거되지만, 이 시점에는 A.[[Status]]가 이미 linking이므로 no-op이다. 제어가 A로 돌아와 C에 대해 InnerModuleLinking이 트리거될 때 B.[[Status]] 자체는 linking으로 남아 있다. 이것이 C.[[Status]]linked인 상태로 반환된 뒤, AB는 함께 linking에서 linked로 전환된다. 이는 이들이 강한 연결 요소를 형성하므로 의도된 동작이다. 이 단계에서는 모듈 그래프가 깊이 우선 탐색으로 순회되기 때문에 같은 SCC 안의 모듈들의 상태를 동시에 전환할 수 있다.

순환 모듈 그래프의 평가 단계에서도 성공 사례에서는 이와 유사한 이야기가 발생한다.

이제 A에 링킹 오류가 있는 경우를 생각해 보자. 예를 들어 C에 존재하지 않는 binding을 import하려 한다고 하자. 이 경우에도 A에 대한 두 번째 InnerModuleLinking 호출에서 조기 반환하는 것을 포함해 위 단계들은 여전히 발생한다. 그러나 원래의 A에 대한 InnerModuleLinking으로 되감아 돌아오면, InitializeEnvironment 중, 즉 C.ResolveExport() 직후에 실패한다. 던져진 SyntaxError 예외는 A.Link까지 전파되며, 이는 현재 자신의 stack 위에 있는 모든 모듈을 재설정한다(이들은 항상 아직 linking인 모듈과 정확히 같다). 따라서 AB는 모두 unlinked가 된다. Clinked로 남는다는 점에 유의하라.

또는 A에 평가 오류가 있는 경우를 생각해 보자. 예를 들어 그 소스 코드가 예외를 던진다고 하자. 이 경우에도 A에 대한 두 번째 InnerModuleEvaluation 호출에서 조기 반환하는 것을 포함해 위 단계들의 평가 시점 대응 과정은 여전히 발생한다. 그러나 원래의 A에 대한 InnerModuleEvaluation으로 되감아 돌아오면, 가정에 따라 실패한다. 던져진 예외는 A.Evaluate()까지 전파되며, 이는 현재 자신의 stack 위에 있는 모든 모듈(즉 아직 evaluating인 모듈)뿐 아니라 [[AsyncParentModules]]를 통해서도 오류를 기록한다. [[AsyncParentModules]]AsyncModuleExecutionRejected 알고리즘을 통해 전체 의존성 그래프에서 top-level await를 포함하거나 이에 의존하는 모듈들을 위한 체인을 형성한다. 따라서 AB는 모두 evaluated가 되고 예외는 AB[[EvaluationError]] 필드 모두에 기록되며, C[[EvaluationError]] 없이 evaluated로 남는다.

마지막으로, 모든 모듈이 비동기적으로 완료되는 cycle이 있는 모듈 그래프를 생각해 보자.

Figure 5: 비동기 순환 모듈 그래프
모듈 A가 모듈 B와 C에 의존하고, 모듈 B는 모듈 D에 의존하며, 모듈 C는 모듈 D와 E에 의존하고, 모듈 D는 모듈 A에 의존하는 모듈 그래프

로딩과 링킹은 이전과 같이 발생하며, 모든 모듈은 [[Status]]linked로 설정된 상태가 된다.

A.Evaluate()를 호출하면 A, B, D에 대해 InnerModuleEvaluation을 호출하며, 이들은 모두 evaluating으로 전환된다. 그런 다음 A에 대해 InnerModuleEvaluation이 다시 호출되는데, 이미 evaluating이므로 no-op이다. 이 시점에서 D.[[PendingAsyncDependencies]]는 0이므로 ExecuteAsyncModule(D)가 호출되고, D의 비동기 실행을 추적하는 새 PromiseCapability와 함께 D.ExecuteModule을 호출한다. B에 대한 InnerModuleEvaluation으로 되감아 돌아와 B.[[PendingAsyncDependencies]]를 1로 설정하고 B.[[AsyncEvaluationOrder]]를 1로 설정한다. 원래의 A에 대한 InnerModuleEvaluation으로 되감아 돌아와 A.[[PendingAsyncDependencies]]를 1로 설정한다. A의 의존성에 대한 루프의 다음 반복에서 C에 대해, 따라서 D(다시 no-op)와 E에 대해 InnerModuleEvaluation을 호출한다. E는 의존성이 없고 cycle의 일부가 아니므로, D와 같은 방식으로 ExecuteAsyncModule(E)를 호출하고 E는 즉시 stack에서 제거된다. 다시 C에 대한 InnerModuleEvaluation으로 되감아 돌아와 C.[[AsyncEvaluationOrder]]를 3으로 설정한다. 이제 A의 의존성에 대한 루프를 끝내고, A.[[AsyncEvaluationOrder]]를 4로 설정한 뒤, 전체 강한 연결 요소를 stack에서 제거하여 모든 모듈을 한 번에 evaluating-async로 전환한다. 이 시점에서 모듈들의 필드는 Table 43에 주어진 것과 같다.

Table 43: 초기 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 (BC) 1 (D) 2 (DE) 0 0

E가 먼저 실행을 마친다고 가정하자. 그 일이 발생하면 AsyncModuleExecutionFulfilled가 호출되고, E.[[Status]]evaluated로 설정되며, C.[[PendingAsyncDependencies]]는 감소하여 1이 된다. 갱신된 모듈들의 필드는 Table 44에 주어진 것과 같다.

Table 44: 모듈 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로 설정된다. 실행 가능한 조상은 B([[AsyncEvaluationOrder]]가 1)와 C([[AsyncEvaluationOrder]]가 3)이므로, B가 먼저 처리된다. B.[[PendingAsyncDependencies]]는 감소하여 0이 되고, B에 대해 ExecuteAsyncModule이 호출되어 실행을 시작한다. C.[[PendingAsyncDependencies]]도 감소하여 0이 되고, C도 실행을 시작한다(Bawait를 포함한다면 B와 병렬로 실행될 수도 있다). 갱신된 모듈들의 필드는 Table 45에 주어진 것과 같다.

Table 45: 모듈 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가 다음으로 실행을 마친다고 가정하자. 그 일이 발생하면 AsyncModuleExecutionFulfilled가 다시 호출되고, C.[[Status]]evaluated로 설정되며, A.[[PendingAsyncDependencies]]는 감소하여 1이 된다. 갱신된 모듈들의 필드는 Table 46에 주어진 것과 같다.

Table 46: 모듈 C가 실행을 마친 뒤의 모듈 필드
필드
모듈
A C
[[DFSAncestorIndex]] 0 0
[[Status]] evaluating-async evaluated
[[AsyncEvaluationOrder]] 4 done
[[AsyncParentModules]] « » « A »
[[PendingAsyncDependencies]] 1 (B) 0

그런 다음 B가 실행을 마친다. 그 일이 발생하면 AsyncModuleExecutionFulfilled가 다시 호출되고 B.[[Status]]evaluated로 설정된다. A.[[PendingAsyncDependencies]]는 감소하여 0이 되므로, ExecuteAsyncModule이 호출되고 실행을 시작한다. 갱신된 모듈들의 필드는 Table 47에 주어진 것과 같다.

Table 47: 모듈 B가 실행을 마친 뒤의 모듈 필드
필드
모듈
A B
[[DFSAncestorIndex]] 0 0
[[Status]] evaluating-async evaluated
[[AsyncEvaluationOrder]] 4 done
[[AsyncParentModules]] « » « A »
[[PendingAsyncDependencies]] 0 0

마지막으로 A가 실행을 마친다. 그 일이 발생하면 AsyncModuleExecutionFulfilled가 다시 호출되고 A.[[Status]]evaluated로 설정된다. 이 시점에서 A.[[TopLevelCapability]] 안의 Promise(A.Evaluate()에서 반환된 것)가 resolve되고, 이것으로 이 모듈 그래프의 처리가 끝난다. 갱신된 모듈의 필드는 Table 48에 주어진 것과 같다.

Table 48: 모듈 A가 실행을 마친 뒤의 모듈 필드
필드
모듈
A
[[DFSAncestorIndex]] 0
[[Status]] evaluated
[[AsyncEvaluationOrder]] done
[[AsyncParentModules]] « »
[[PendingAsyncDependencies]] 0

또는 B가 실행을 마치기 전에 C가 실행에 실패하고 오류를 반환하는 실패 사례를 생각해 보자. 그 일이 발생하면 AsyncModuleExecutionRejected가 호출되어 C.[[Status]]evaluated로 설정하고 C.[[EvaluationError]]를 그 오류로 설정한다. 그런 다음 각 AsyncParentModules에 대해 AsyncModuleExecutionRejected를 수행하여 이 오류를 모든 AsyncParentModules로 전파한다. 갱신된 모듈들의 필드는 Table 49에 주어진 것과 같다.

Table 49: 모듈 C가 오류와 함께 완료된 뒤의 모듈 필드
필드
모듈
A C
[[DFSAncestorIndex]] 0 0
[[Status]] evaluated evaluated
[[AsyncEvaluationOrder]] done done
[[AsyncParentModules]] « » « A »
[[PendingAsyncDependencies]] 1 (B) 0
[[EvaluationError]] empty C의 평가 오류

CC의 오류로 A에 대해 AsyncModuleExecutionRejected를 호출하므로, AC와 같은 오류로 reject된다. A.[[Status]]evaluated로 설정된다. 이 시점에서 A.[[TopLevelCapability]] 안의 Promise(A.Evaluate()에서 반환된 것)는 reject된다. 갱신된 모듈의 필드는 Table 50에 주어진 것과 같다.

Table 50: 모듈 A가 reject된 뒤의 모듈 필드
필드
모듈
A
[[DFSAncestorIndex]] 0
[[Status]] evaluated
[[AsyncEvaluationOrder]] done
[[AsyncParentModules]] « »
[[PendingAsyncDependencies]] 0
[[EvaluationError]] CEvaluation Error

그런 다음 B가 오류 없이 실행을 마친다. 그 일이 발생하면 AsyncModuleExecutionFulfilled가 다시 호출되고 B.[[Status]]evaluated로 설정된다. GatherAvailableAncestorsB에 대해 호출된다. 그러나 A.[[CycleRoot]]는 평가 오류가 있는 A이므로 반환되는 sortedExecList에 추가되지 않으며 AsyncModuleExecutionFulfilled는 추가 처리 없이 반환된다. 이후 B를 import하는 모든 모듈은 cycle root A에 설정된 C의 평가 오류에서 나온 B.[[CycleRoot]].[[EvaluationError]]의 rejection을 resolve하게 된다. 갱신된 모듈들의 필드는 Table 51에 주어진 것과 같다.

Table 51: 오류가 있는 그래프에서 모듈 B가 실행을 마친 뒤의 모듈 필드
필드
모듈
A B
[[DFSAncestorIndex]] 0 0
[[Status]] evaluated evaluated
[[AsyncEvaluationOrder]] 4 1
[[AsyncParentModules]] « » « A »
[[PendingAsyncDependencies]] 0 0
[[EvaluationError]] CEvaluation Error empty

16.2.1.7 Source Text Module Record

Source Text Module Record목표 기호 Module을 사용해 파싱된 ECMAScript 소스 텍스트(11)로부터 정의된 모듈에 관한 정보를 나타내는 데 사용된다. 그 필드들은 모듈이 import하고 export하는 이름에 관한 요약 정보를 포함하며, 그 구체 메서드들은 이 요약 정보를 사용해 모듈을 링크하고 평가한다.

Source Text Module Record는 추상 Module Record 타입의 다른 서브클래스들과 함께 모듈 그래프 안에 존재할 수 있으며, Cyclic Module Record 타입의 다른 서브클래스들과 cycle에 참여할 수 있다.

Table 40에 정의된 필드에 더해, Source Text Module RecordTable 52에 나열된 추가 필드를 가진다. 이 각 필드는 처음에 ParseModule에서 설정된다.

Table 52: Source Text Module Record의 추가 필드
필드 이름 값 타입 의미
[[ECMAScriptCode]] Parse Node 이 모듈의 소스 텍스트를 Module목표 기호로 사용해 파싱한 결과.
[[Context]] ECMAScript 코드 실행 컨텍스트 또는 empty 이 모듈과 관련된 실행 컨텍스트. 모듈의 환경이 초기화될 때까지 empty이다.
[[ImportMeta]] Object 또는 empty import.meta meta property를 통해 노출되는 객체. ECMAScript 코드에 의해 접근될 때까지 empty이다.
[[ImportEntries]] ImportEntry RecordList 이 모듈의 코드에서 파생된 ImportEntry record의 List.
[[LocalExportEntries]] ExportEntry RecordList 모듈 안에서 발생하는 선언에 대응하는, 이 모듈의 코드에서 파생된 ExportEntry record의 List.
[[IndirectExportEntries]] ExportEntry RecordList 모듈 안에서 발생하는 재export된 import 또는 export * as namespace 선언의 export에 대응하는, 이 모듈의 코드에서 파생된 ExportEntry record의 List.
[[StarExportEntries]] ExportEntry RecordList 모듈 안에서 발생하는 export * 선언에 대응하는, 이 모듈의 코드에서 파생된 ExportEntry record의 List. export * as namespace 선언은 포함하지 않는다.

ImportEntry Record는 단일 선언적 import에 관한 정보를 요약하는 Record이다. 각 ImportEntry RecordTable 53에 정의된 필드를 가진다:

Table 53: ImportEntry Record 필드
필드 이름 값 타입 의미
[[ModuleRequest]] ModuleRequest Record ImportDeclarationModuleSpecifier 및 import attributes를 나타내는 ModuleRequest Record.
[[ImportName]] String 또는 namespace 원하는 binding이 [[ModuleRequest]]로 식별되는 모듈에 의해 export되는 이름. 값 namespace는 import 요청이 대상 모듈의 namespace object에 대한 것임을 나타낸다.
[[LocalName]] String import하는 모듈 안에서 import된 값을 로컬로 접근하는 데 사용되는 이름.
Note 1

Table 54는 구문적 import 형식을 나타내는 데 사용되는 ImportEntry record 필드의 예를 제공한다:

Table 54 (Informative): Import 형식의 ImportEntry Record 매핑
Import 문 형식 [[ModuleRequest]] [[ImportName]] [[LocalName]]
import v from "mod"; "mod" "default" "v"
import * as ns from "mod"; "mod" namespace "ns"
import {x} from "mod"; "mod" "x" "x"
import {x as v} from "mod"; "mod" "x" "v"
import "mod"; ImportEntry Record는 생성되지 않는다.

ExportEntry Record는 단일 선언적 export에 관한 정보를 요약하는 Record이다. 각 ExportEntry RecordTable 55에 정의된 필드를 가진다:

Table 55: ExportEntry Record 필드
필드 이름 값 타입 의미
[[ExportName]] String 또는 null 이 모듈이 이 binding을 export하는 데 사용하는 이름.
[[ModuleRequest]] ModuleRequest Record 또는 null ExportDeclarationModuleSpecifier 및 import attributes를 나타내는 ModuleRequest Record. ExportDeclarationModuleSpecifier를 가지지 않으면 null.
[[ImportName]] String, null, namespace, 또는 all-but-default 원하는 binding이 [[ModuleRequest]]로 식별되는 모듈에 의해 export되는 이름. ExportDeclarationModuleSpecifier를 가지지 않으면 null. namespaceexport * as ns from "mod" 선언에 사용된다. all-but-defaultexport * from "mod" 선언에 사용된다.
[[LocalName]] String 또는 null import하는 모듈 안에서 export된 값에 로컬로 접근하는 데 사용되는 이름. export된 값이 모듈 안에서 로컬로 접근 가능하지 않으면 null.
Note 2

Table 56는 구문적 export 형식을 나타내는 데 사용되는 ExportEntry record 필드의 예를 제공한다:

Table 56 (Informative): Export 형식의 ExportEntry Record 매핑
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" namespace null

다음 정의들은 Source Text Module Record에 필요한 구체 메서드와 기타 추상 연산을 명시한다

16.2.1.7.1 ParseModule ( sourceText, realm, hostDefined )

The abstract operation ParseModule takes arguments sourceText (ECMAScript source text), realm (a Realm Record), and hostDefined (anything) and returns a Source Text Module Record or a non-empty List of SyntaxError objects. sourceTextModule로 파싱한 결과를 기반으로 Source Text Module Record를 생성한다. It performs the following steps when called:

  1. bodyParseText(sourceText, Module)로 둔다.
  2. body가 오류들의 List이면, body를 반환한다.
  3. requestedModulesbodyModuleRequests로 둔다.
  4. importEntriesbodyImportEntries로 둔다.
  5. importedBoundNamesImportedLocalNames(importEntries)로 둔다.
  6. indirectExportEntries를 새 빈 List로 둔다.
  7. localExportEntries를 새 빈 List로 둔다.
  8. starExportEntries를 새 빈 List로 둔다.
  9. exportEntriesbodyExportEntries로 둔다.
  10. exportEntries의 각 ExportEntry Record ee에 대해,
    1. ee.[[ModuleRequest]]null이면,
      1. importedBoundNamesee.[[LocalName]]을 포함하지 않으면,
        1. eelocalExportEntries에 추가한다.
      2. 그렇지 않으면,
        1. NOTE: 원래 다른 모듈에서 import된 binding 또는 namespace object를 export할 때, ExportEntry Record는 그 binding 또는 namespace object가 import된 뒤 export된 것이 아니라 원래 모듈에서 직접 재export되었다면 가졌을 형식과 일치하도록 다시 작성된다. 이를 통해 export * from을 통해 같은 이름 아래 같은 binding 또는 namespace를 두 번 export하여 생기는 충돌을 Source Text Module Record의 ResolveExport 구체 메서드9.e.iii 단계에서 ambiguous로 처리하지 않고 무시할 수 있다.
        2. ie[[LocalName]]ee.[[LocalName]]importEntries의 요소로 둔다.
        3. ExportEntry Record { [[ModuleRequest]]: ie.[[ModuleRequest]], [[ImportName]]: ie.[[ImportName]], [[LocalName]]: null, [[ExportName]]: ee.[[ExportName]] }를 indirectExportEntries에 추가한다.
    2. 그렇지 않고 ee.[[ImportName]]all-but-default이면,
      1. Assert: ee.[[ExportName]]null이다.
      2. eestarExportEntries에 추가한다.
    3. 그렇지 않으면,
      1. eeindirectExportEntries에 추가한다.
  11. asyncbody Contains await로 둔다.
  12. Source Text Module Record { [[Realm]]: realm, [[Environment]]: empty, [[Namespace]]: empty, [[CycleRoot]]: empty, [[HasTLA]]: async, [[AsyncEvaluationOrder]]: unset, [[TopLevelCapability]]: empty, [[AsyncParentModules]]: « », [[PendingAsyncDependencies]]: empty, [[Status]]: new, [[EvaluationError]]: empty, [[HostDefined]]: hostDefined, [[ECMAScriptCode]]: body, [[Context]]: empty, [[ImportMeta]]: empty, [[RequestedModules]]: requestedModules, [[LoadedModules]]: « », [[ImportEntries]]: importEntries, [[LocalExportEntries]]: localExportEntries, [[IndirectExportEntries]]: indirectExportEntries, [[StarExportEntries]]: starExportEntries, [[DFSAncestorIndex]]: empty }를 반환한다.
Note

구현은 해당 모듈 소스 텍스트에 대해 ParseModule을 평가하기 전에 모듈 소스 텍스트를 파싱하고 Early Error 조건을 분석할 수 있다. 그러나 모든 오류 보고는 이 명세가 실제로 해당 소스 텍스트에 대해 ParseModule을 수행하는 시점까지 지연되어야 한다.

16.2.1.7.2 Module Record 추상 메서드의 구현

다음은 Table 39에 정의된 해당 Module Record 추상 메서드를 구현하는 Source Text Module Record의 구체 메서드이다.

16.2.1.7.2.1 GetExportedNames ( [ exportStarSet ] )

The GetExportedNames concrete method of a Source Text Module Record module takes optional argument exportStarSet (a List of Source Text Module Records) and returns a List of Strings. It performs the following steps when called:

  1. Assert: module.[[Status]]new가 아니다.
  2. exportStarSet이 존재하지 않으면, exportStarSet을 새 빈 List로 설정한다.
  3. exportStarSetmodule을 포함하면,
    1. Assert: export * 순환성의 시작점에 도달했다.
    2. 새 빈 List를 반환한다.
  4. moduleexportStarSet에 추가한다.
  5. exportedNames를 새 빈 List로 둔다.
  6. module.[[LocalExportEntries]]의 각 ExportEntry Record e에 대해,
    1. Assert: module은 이 export에 대한 직접 binding을 제공한다.
    2. Assert: e.[[ExportName]]null이 아니다.
    3. e.[[ExportName]]exportedNames에 추가한다.
  7. module.[[IndirectExportEntries]]의 각 ExportEntry Record e에 대해,
    1. Assert: module은 이 export에 대한 특정 binding을 import한다.
    2. Assert: e.[[ExportName]]null이 아니다.
    3. e.[[ExportName]]exportedNames에 추가한다.
  8. module.[[StarExportEntries]]의 각 ExportEntry Record e에 대해,
    1. Assert: e.[[ModuleRequest]]null이 아니다.
    2. requestedModuleGetImportedModule(module, e.[[ModuleRequest]])로 둔다.
    3. starNamesrequestedModule.GetExportedNames(exportStarSet)로 둔다.
    4. starNames의 각 요소 n에 대해,
      1. n"default"가 아니면,
        1. exportedNamesn을 포함하지 않으면,
          1. nexportedNames에 추가한다.
  9. exportedNames를 반환한다.
Note

GetExportedNames는 ambiguous star export binding을 가진 이름을 걸러내거나 그에 대해 예외를 던지지 않는다.

16.2.1.7.2.2 ResolveExport ( exportName [ , resolveSet ] )

The ResolveExport concrete method of a Source Text Module Record module takes argument exportName (a String) and optional argument resolveSet (a List of Records with fields [[Module]] (a Module Record) and [[ExportName]] (a String)) and returns a ResolvedBinding Record, null, or ambiguous.

ResolveExport는 import된 binding을 실제 정의 모듈과 로컬 binding 이름으로 해석하려고 시도한다. 정의 모듈은 이 메서드가 호출된 Module Record가 나타내는 모듈일 수도 있고, 그 모듈이 import하는 다른 모듈일 수도 있다. resolveSet 매개변수는 해소되지 않은 순환 import/export 경로를 감지하는 데 사용된다. 특정 Module RecordexportName으로 구성된 쌍이 이미 resolveSet에 있는 상태로 도달하면, import 순환성이 발견된 것이다. ResolveExport를 재귀적으로 호출하기 전에 moduleexportName으로 구성된 쌍이 resolveSet에 추가된다.

정의 모듈이 발견되면 ResolvedBinding Record { [[Module]], [[BindingName]] }가 반환된다. 이 record는 원래 요청된 export의 해소된 binding을 식별한다. 단, 로컬 binding이 없는 namespace의 export인 경우는 예외이다. 이 경우 [[BindingName]]namespace로 설정된다. 정의가 발견되지 않았거나 요청이 순환적인 것으로 밝혀지면 null이 반환된다. 요청이 ambiguous한 것으로 밝혀지면 ambiguous가 반환된다.

It performs the following steps when called:

  1. Assert: module.[[Status]]new가 아니다.
  2. resolveSet이 존재하지 않으면, resolveSet을 새 빈 List로 설정한다.
  3. resolveSet의 각 Record { [[Module]], [[ExportName]] } r에 대해,
    1. moduler.[[Module]]이 같은 Module Record이고 exportNamer.[[ExportName]]이면,
      1. Assert: 이것은 순환 import 요청이다.
      2. null을 반환한다.
  4. Record { [[Module]]: module, [[ExportName]]: exportName }를 resolveSet에 추가한다.
  5. module.[[LocalExportEntries]]의 각 ExportEntry Record e에 대해,
    1. e.[[ExportName]]exportName이면,
      1. Assert: module은 이 export에 대한 직접 binding을 제공한다.
      2. ResolvedBinding Record { [[Module]]: module, [[BindingName]]: e.[[LocalName]] }를 반환한다.
  6. module.[[IndirectExportEntries]]의 각 ExportEntry Record e에 대해,
    1. e.[[ExportName]]exportName이면,
      1. Assert: e.[[ModuleRequest]]null이 아니다.
      2. importedModuleGetImportedModule(module, e.[[ModuleRequest]])로 둔다.
      3. e.[[ImportName]]namespace이면,
        1. Assert: module은 이 export에 대한 직접 binding을 제공하지 않는다.
        2. ResolvedBinding Record { [[Module]]: importedModule, [[BindingName]]: namespace }를 반환한다.
      4. Assert: module은 이 export에 대한 특정 binding을 import한다.
      5. Assert: e.[[ImportName]]은 String이다.
      6. importedModule.ResolveExport(e.[[ImportName]], resolveSet)를 반환한다.
  7. exportName"default"이면,
    1. Assert: default export는 이 모듈에 의해 명시적으로 정의되지 않았다.
    2. null을 반환한다.
    3. NOTE: default export는 export * from "mod" 선언으로 제공될 수 없다.
  8. starResolutionnull로 둔다.
  9. module.[[StarExportEntries]]의 각 ExportEntry Record e에 대해,
    1. Assert: e.[[ModuleRequest]]null이 아니다.
    2. importedModuleGetImportedModule(module, e.[[ModuleRequest]])로 둔다.
    3. resolutionimportedModule.ResolveExport(exportName, resolveSet)로 둔다.
    4. resolutionambiguous이면, ambiguous를 반환한다.
    5. resolutionnull이 아니면,
      1. Assert: resolution은 ResolvedBinding Record이다.
      2. starResolutionnull이면,
        1. starResolutionresolution으로 설정한다.
      3. 그렇지 않으면,
        1. Assert: 요청된 이름을 포함하는 * export가 둘 이상 있다.
        2. resolution.[[Module]]starResolution.[[Module]]이 같은 Module Record가 아니면, ambiguous를 반환한다.
        3. resolution.[[BindingName]]starResolution.[[BindingName]]이 아니면, ambiguous를 반환한다.
  10. starResolution을 반환한다.

16.2.1.7.3 Cyclic Module Record 추상 메서드의 구현

다음은 Table 41에 정의된 해당 Cyclic Module Record 추상 메서드를 구현하는 Source Text Module Record의 구체 메서드이다.

16.2.1.7.3.1 InitializeEnvironment ( )

The InitializeEnvironment concrete method of a Source Text Module Record module takes no arguments and returns either a normal completion containing unused or a throw completion. It performs the following steps when called:

  1. module.[[IndirectExportEntries]]의 각 ExportEntry Record e에 대해,
    1. Assert: e.[[ExportName]]null이 아니다.
    2. resolutionmodule.ResolveExport(e.[[ExportName]])로 둔다.
    3. resolutionnull 또는 ambiguous이면, SyntaxError 예외를 던진다.
    4. Assert: resolution은 ResolvedBinding Record이다.
  2. Assert: module의 모든 named export는 해소 가능하다.
  3. realmmodule.[[Realm]]로 둔다.
  4. Assert: realmundefined가 아니다.
  5. envNewModuleEnvironment(realm.[[GlobalEnv]])로 둔다.
  6. module.[[Environment]]env로 설정한다.
  7. module.[[ImportEntries]]의 각 ImportEntry Record in에 대해,
    1. importedModuleGetImportedModule(module, in.[[ModuleRequest]])로 둔다.
    2. in.[[ImportName]]namespace이면,
      1. namespaceGetModuleNamespace(importedModule)로 둔다.
      2. env.CreateImmutableBinding(in.[[LocalName]], true)를 수행한다.
      3. env.InitializeBinding(in.[[LocalName]], namespace)를 수행한다.
    3. 그렇지 않으면,
      1. Assert: in.[[ImportName]]은 String이다.
      2. resolutionimportedModule.ResolveExport(in.[[ImportName]])로 둔다.
      3. resolutionnull 또는 ambiguous이면, SyntaxError 예외를 던진다.
      4. resolution.[[BindingName]]namespace이면,
        1. namespaceGetModuleNamespace(resolution.[[Module]])로 둔다.
        2. env.CreateImmutableBinding(in.[[LocalName]], true)를 수행한다.
        3. env.InitializeBinding(in.[[LocalName]], namespace)를 수행한다.
      5. 그렇지 않으면,
        1. CreateImportBinding(env, in.[[LocalName]], resolution.[[Module]], resolution.[[BindingName]])을 수행한다.
  8. moduleContext를 새 ECMAScript 코드 실행 컨텍스트로 둔다.
  9. moduleContext의 Function을 null로 설정한다.
  10. Assert: module.[[Realm]]undefined가 아니다.
  11. moduleContextRealmmodule.[[Realm]]로 설정한다.
  12. moduleContext의 ScriptOrModule을 module로 설정한다.
  13. moduleContext의 VariableEnvironment를 module.[[Environment]]로 설정한다.
  14. moduleContext의 LexicalEnvironment를 module.[[Environment]]로 설정한다.
  15. moduleContext의 PrivateEnvironment를 null로 설정한다.
  16. module.[[Context]]moduleContext로 설정한다.
  17. moduleContext를 실행 컨텍스트 stack에 push한다; 이제 moduleContext가 실행 중인 실행 컨텍스트이다.
  18. codemodule.[[ECMAScriptCode]]로 둔다.
  19. varDeclarationscodeVarScopedDeclarations로 둔다.
  20. declaredVarNames를 새 빈 List로 둔다.
  21. varDeclarations의 각 요소 d에 대해,
    1. dBoundNames의 각 요소 dn에 대해,
      1. declaredVarNamesdn을 포함하지 않으면,
        1. env.CreateMutableBinding(dn, false)를 수행한다.
        2. env.InitializeBinding(dn, undefined)를 수행한다.
        3. dndeclaredVarNames에 추가한다.
  22. lexDeclarationscodeLexicallyScopedDeclarations로 둔다.
  23. privateEnvnull로 둔다.
  24. lexDeclarations의 각 요소 d에 대해,
    1. dBoundNames의 각 요소 dn에 대해,
      1. dIsConstantDeclarationtrue이면,
        1. env.CreateImmutableBinding(dn, true)를 수행한다.
      2. 그렇지 않으면,
        1. env.CreateMutableBinding(dn, false)를 수행한다.
      3. dFunctionDeclaration, GeneratorDeclaration, AsyncFunctionDeclaration, 또는 AsyncGeneratorDeclaration 중 하나이면,
        1. fo를 인수 envprivateEnv를 사용한 dInstantiateFunctionObject로 둔다.
        2. env.InitializeBinding(dn, fo)를 수행한다.
  25. 실행 컨텍스트 stack에서 moduleContext를 제거한다.
  26. unused를 반환한다.

16.2.1.7.3.2 ExecuteModule ( [ capability ] )

The ExecuteModule concrete method of a Source Text Module Record module takes optional argument capability (a PromiseCapability Record) and returns either a normal completion containing unused or a throw completion. It performs the following steps when called:

  1. Assert: module은 링크되었고 그 모듈 환경의 선언들이 인스턴스화되었다.
  2. moduleContextmodule.[[Context]]로 둔다.
  3. module.[[HasTLA]]false이면,
    1. Assert: capability는 존재하지 않는다.
    2. 실행 중인 실행 컨텍스트를 suspend한다.
    3. moduleContext를 실행 컨텍스트 stack에 push한다; 이제 moduleContext가 실행 중인 실행 컨텍스트이다.
    4. resultCompletion(module.[[ECMAScriptCode]]Evaluation)으로 둔다.
    5. moduleContext를 suspend하고 실행 컨텍스트 stack에서 제거한다.
    6. 이제 실행 컨텍스트 stack의 top에 있는 컨텍스트를 실행 중인 실행 컨텍스트로 resume한다.
    7. resultabrupt completion이면,
      1. result를 반환한다.
  4. 그렇지 않으면,
    1. Assert: capability는 PromiseCapability Record이다.
    2. AsyncBlockStart(capability, module.[[ECMAScriptCode]], moduleContext)를 수행한다.
  5. unused를 반환한다.

16.2.1.8 Synthetic Module Records

Synthetic Module Record는 명세에 의해 정의된 모듈에 대한 정보를 나타내는 데 사용된다. 그 export된 이름들은 생성 시 정적으로 정의되지만, 해당 값들은 SetSyntheticModuleExport를 사용하여 시간이 지남에 따라 변경될 수 있다. 이들은 import나 의존성을 가지지 않는다.

Note
Synthetic Module Record는 다양한 모듈 타입을 정의하는 데 사용될 수 있다. 예를 들어 JSON 모듈이나 CSS 모듈 등이 있다.

Table 38에 정의된 필드에 더해, Synthetic Module Record는 Table 57에 나열된 추가 필드를 가진다.

Table 57: Synthetic Module Record의 추가 필드
필드 이름 값 타입 의미
[[ExportNames]] String의 List 모듈의 export 이름들. 이 리스트에는 중복이 없다.
[[EvaluationSteps]] Abstract Closure 모듈 평가 시 수행할 초기화 로직으로, Synthetic Module Record를 유일한 인수로 받는다. [[ExportNames]]를 수정해서는 안 된다. abrupt completion을 반환할 수 있다.

16.2.1.8.1 CreateDefaultExportSyntheticModule ( defaultExport )

The abstract operation CreateDefaultExportSyntheticModule takes argument defaultExport (an ECMAScript language value) and returns a Synthetic Module Record. default export가 defaultExportSynthetic Module Record를 생성한다. It performs the following steps when called:

  1. realm을 현재 Realm Record로 둔다.
  2. setDefaultExport를 (module)을 매개변수로 가지는 새로운 Abstract Closure로 두고, defaultExport를 캡처하며 호출 시 다음 단계를 수행한다:
    1. SetSyntheticModuleExport(module, "default", defaultExport)를 수행한다.
    2. NormalCompletion(unused)을 반환한다.
  3. Synthetic Module Record { [[Realm]]: realm, [[Environment]]: empty, [[Namespace]]: empty, [[HostDefined]]: undefined, [[ExportNames]]: « "default" », [[EvaluationSteps]]: setDefaultExport }를 반환한다.

16.2.1.8.2 ParseJSONModule ( source )

The abstract operation ParseJSONModule takes argument source (a String) and returns either a normal completion containing a Synthetic Module Record, or a throw completion. It performs the following steps when called:

  1. parseResult를 ? ParseJSON(source)로 둔다.
  2. CreateDefaultExportSyntheticModule(parseResult.[[Value]])를 반환한다.

16.2.1.8.3 SetSyntheticModuleExport ( module, exportName, exportValue )

The abstract operation SetSyntheticModuleExport takes arguments module (a Synthetic Module Record), exportName (a String), and exportValue (an ECMAScript language value) and returns unused. 기존 Synthetic Module Record의 export 값을 설정하거나 변경하는 데 사용할 수 있다. It performs the following steps when called:

  1. Assert: module.[[ExportNames]]exportName을 포함한다.
  2. envRecmodule.[[Environment]]로 둔다.
  3. Assert: envRecempty가 아니다.
  4. envRec.SetMutableBinding(exportName, exportValue, true)를 수행한다.
  5. unused를 반환한다.

16.2.1.8.4 Module Record 추상 메서드의 구현

다음은 Table 39에 정의된 해당 Module Record 추상 메서드를 구현하는 Synthetic Module Record의 구체 메서드이다.

16.2.1.8.4.1 LoadRequestedModules ( [ hostDefined ] )

The LoadRequestedModules concrete method of a Synthetic Module Record module takes optional argument hostDefined (anything) and returns a Promise. It performs the following steps when called:

  1. NOTE: 이 LoadRequestedModules 구현은 hostDefined를 사용하지 않는다.
  2. PromiseResolve(%Promise%, undefined)를 반환한다.
Note
Synthetic Module Record는 의존성이 없다.

16.2.1.8.4.2 GetExportedNames ( [ exportStarSet ] )

The GetExportedNames concrete method of a Synthetic Module Record module takes optional argument exportStarSet (a List of Source Text Module Records) and returns a List of Strings. It performs the following steps when called:

  1. NOTE: 이 GetExportedNames 구현은 exportStarSet을 사용하지 않는다.
  2. module.[[ExportNames]]를 반환한다.

16.2.1.8.4.3 ResolveExport ( exportName [ , resolveSet ] )

The ResolveExport concrete method of a Synthetic Module Record module takes argument exportName (a String) and optional argument resolveSet (a List of Records with fields [[Module]] (a Module Record) and [[ExportName]] (a String)) and returns a ResolvedBinding Record, null, or ambiguous. It performs the following steps when called:

  1. NOTE: 이 ResolveExport 구현은 resolveSet을 사용하지 않는다.
  2. module.[[ExportNames]]exportName을 포함하지 않으면, null을 반환한다.
  3. ResolvedBinding Record { [[Module]]: module, [[BindingName]]: exportName }를 반환한다.

16.2.1.8.4.4 Link ( )

The Link concrete method of a Synthetic Module Record module takes no arguments and returns a normal completion containing unused. It performs the following steps when called:

  1. realmmodule.[[Realm]]로 둔다.
  2. envNewModuleEnvironment(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 a Synthetic Module Record module takes no arguments and returns a Promise. It performs the following steps when called:

  1. moduleContext를 새로운 ECMAScript 코드 실행 컨텍스트로 둔다.
  2. moduleContext의 Function을 null로 설정한다.
  3. moduleContextRealmmodule.[[Realm]]로 설정한다.
  4. moduleContext의 ScriptOrModule을 module로 설정한다.
  5. moduleContext의 VariableEnvironment를 module.[[Environment]]로 설정한다.
  6. moduleContext의 LexicalEnvironment를 module.[[Environment]]로 설정한다.
  7. 실행 중인 실행 컨텍스트를 suspend한다.
  8. moduleContext를 실행 컨텍스트 stack에 push한다; 이제 moduleContext가 실행 중인 실행 컨텍스트이다.
  9. stepsmodule.[[EvaluationSteps]]로 둔다.
  10. resultCompletion(steps(module))로 둔다.
  11. moduleContext를 suspend하고 실행 컨텍스트 stack에서 제거한다.
  12. 이제 실행 컨텍스트 stack의 top에 있는 컨텍스트를 실행 중인 실행 컨텍스트로 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 (a Cyclic Module Record) and request (a ModuleRequest Record) and returns a Module Record. It performs the following steps when called:

  1. recordsreferrer.[[LoadedModules]]의 각 LoadedModuleRequest Record rModuleRequestsEqual(r, request)가 true인 것들로 구성된 List로 둔다.
  2. Assert: LoadRequestedModules가 이 추상 연산을 호출하기 전에 referrer에서 성공적으로 완료되었으므로 records는 정확히 하나의 요소를 가진다.
  3. recordrecords의 유일한 요소로 둔다.
  4. record.[[Module]]을 반환한다.

16.2.1.10 HostLoadImportedModule ( referrer, moduleRequest, hostDefined, payload )

The host-defined abstract operation HostLoadImportedModule takes arguments referrer (a Script Record, a Cyclic Module Record, or a Realm Record), moduleRequest (a ModuleRequest Record), hostDefined (anything), and payload (a GraphLoadingState Record or a PromiseCapability Record) and returns unused.

Note 1

referrerRealm Record가 될 수 있는 예는 웹 브라우저 호스트에서 찾을 수 있다. 예를 들어 사용자가 다음과 같은 컨트롤을 클릭할 때

<button type="button" onclick="import('./foo.mjs')">Click me</button>

import() 표현식이 실행되는 시점에는 활성 script나 module이 존재하지 않는다. 더 일반적으로는, 호스트가 ScriptOrModule 구성 요소가 null인 실행 컨텍스트를 실행 컨텍스트 스택에 push하는 모든 상황에서 발생할 수 있다.

HostLoadImportedModule의 구현은 다음 요구 사항을 준수해야 한다:

실제 수행되는 과정은 호스트 정의이지만, 일반적으로 적절한 Module Record를 로드하기 위해 필요한 I/O 작업을 수행하는 것으로 구성된다. 서로 다른 (referrer, moduleRequest.[[Specifier]], moduleRequest.[[Attributes]]) 삼중 조합이 동일한 Module Record 인스턴스로 매핑될 수 있다. 실제 매핑 의미론은 호스트 정의이지만, 일반적으로 매핑 과정에서 specifier에 대한 정규화 과정이 적용된다. 전형적인 정규화 과정에는 상대 경로 및 축약된 경로 지정자의 확장과 같은 작업이 포함된다.

Note 2

위의 텍스트는 type: "json"으로 import될 때 JSON 모듈을 지원해야 함을 요구하지만(HostLoadImportedModule이 정상적으로 완료되는 경우), type: "json" 없이 import될 때 JSON 모듈을 지원하는 것을 금지하지는 않는다.

16.2.1.11 FinishLoadingImportedModule ( referrer, moduleRequest, payload, result )

The abstract operation FinishLoadingImportedModule takes arguments referrer (a Script Record, a Cyclic Module Record, or a Realm Record), moduleRequest (a ModuleRequest Record), payload (a GraphLoadingState Record or a PromiseCapability Record), and result (either a normal completion containing a Module Record or a throw completion) and returns unused. It performs the following steps when called:

  1. resultnormal completion이면,
    1. referrer.[[LoadedModules]]ModuleRequestsEqual(record, moduleRequest)가 trueLoadedModuleRequest Record record가 포함되어 있으면,
      1. Assert: 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 (a List of ImportAttribute Records) and returns a 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 a List of Strings. 호스트 환경이 지원하는 import attributes를 지정할 수 있도록 한다. 지원되는 키를 가진 attribute만 호스트에 전달된다.

HostGetSupportedImportAttributes의 구현은 다음 요구 사항을 준수해야 한다:

  • 각각 지원되는 attribute를 나타내는 String의 List를 반환해야 한다.
  • 이 연산이 호출될 때마다 동일한 순서와 동일한 내용을 가진 List를 반환해야 한다.

HostGetSupportedImportAttributes의 기본 구현은 새로운 빈 List를 반환하는 것이다.

Note
호스트가 처리할 attribute를 선택하도록 모든 attribute를 전달하는 대신, 지원되는 import attribute를 명시하도록 요구하는 목적은 지원되지 않는 attribute가 서로 다른 호스트 간에 일관되게 처리되도록 보장하기 위함이다.

16.2.1.13 GetModuleNamespace ( module )

The abstract operation GetModuleNamespace takes argument module (an instance of a concrete subclass of Module Record) and returns a Module Namespace Object. module의 export를 나타내는 Module Namespace Object를 가져오며, 처음 요청될 때 지연 생성하고 이후 재사용을 위해 module.[[Namespace]]에 저장한다. It performs the following steps when called:

  1. Assert: moduleCyclic Module Record이면, module.[[Status]]new 또는 unlinked가 아니다.
  2. namespacemodule.[[Namespace]]로 둔다.
  3. namespaceempty이면,
    1. exportedNamesmodule.GetExportedNames()로 둔다.
    2. unambiguousNames를 새 빈 List로 둔다.
    3. exportedNames의 각 요소 name에 대해,
      1. resolutionmodule.ResolveExport(name)로 둔다.
      2. resolution이 ResolvedBinding Record이면 nameunambiguousNames에 추가한다.
    4. namespaceModuleNamespaceCreate(module, unambiguousNames)로 설정한다.
  4. namespace를 반환한다.
Note

GetModuleNamespace는 절대 예외를 던지지 않는다. 대신 해소할 수 없는 이름은 이 시점에서 단순히 namespace에서 제외된다. 이러한 이름들은 나중에 실제 링크 오류로 이어지지만, 어디에서도 명시적으로 요청되지 않는 ambiguous star export인 경우에는 예외가 발생하지 않을 수 있다.

16.2.1.14 Runtime Semantics: Evaluation

Module : [empty]
  1. undefined를 반환한다.
ModuleBody : ModuleItemList
  1. resultModuleItemListEvaluationCompletion으로 둔다.
  2. resultnormal completion이고 result.[[Value]]empty이면,
    1. undefined를 반환한다.
  3. result를 반환한다.
ModuleItemList : ModuleItemList ModuleItem
  1. sl을 ? ModuleItemListEvaluation으로 둔다.
  2. sModuleItemEvaluationCompletion으로 둔다.
  3. UpdateEmpty(s, sl)를 반환한다.
Note

ModuleItemList의 값은 해당 리스트에서 값을 생성하는 마지막 항목의 값이다.

ModuleItem : ImportDeclaration
  1. empty를 반환한다.

16.2.2 Imports

Syntax

ImportDeclaration : import ImportClause FromClause WithClauseopt ; import ModuleSpecifier WithClauseopt ; ImportClause : ImportedDefaultBinding NameSpaceImport NamedImports ImportedDefaultBinding , NameSpaceImport ImportedDefaultBinding , NamedImports ImportedDefaultBinding : ImportedBinding NameSpaceImport : * as ImportedBinding NamedImports : { } { ImportsList } { ImportsList , } FromClause : from ModuleSpecifier ImportsList : ImportSpecifier ImportsList , ImportSpecifier ImportSpecifier : ImportedBinding ModuleExportName as ImportedBinding ModuleSpecifier : StringLiteral ImportedBinding : BindingIdentifier[~Yield, +Await] WithClause : with { } with { WithEntries ,opt } WithEntries : AttributeKey : StringLiteral AttributeKey : StringLiteral , WithEntries AttributeKey : IdentifierName StringLiteral

16.2.2.1 Static Semantics: Early Errors

ModuleItem : ImportDeclaration WithClause : with { WithEntries ,opt }

16.2.2.2 Static Semantics: ImportEntries

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

Module : [empty]
  1. 새 빈 List를 반환한다.
ModuleItemList : ModuleItemList ModuleItem
  1. entries1ModuleItemListImportEntries로 둔다.
  2. entries2ModuleItemImportEntries로 둔다.
  3. entries1entries2list-concatenation을 반환한다.
ModuleItem : ExportDeclaration StatementListItem
  1. 새 빈 List를 반환한다.
ImportDeclaration : import ImportClause FromClause WithClauseopt ;
  1. moduleImportDeclarationModuleRequests의 유일한 요소로 둔다.
  2. 인수 module을 사용한 ImportClauseImportEntriesForModule을 반환한다.
ImportDeclaration : import ModuleSpecifier WithClauseopt ;
  1. 새 빈 List를 반환한다.

16.2.2.3 Static Semantics: ImportEntriesForModule

The syntax-directed operation ImportEntriesForModule takes argument module (a ModuleRequest Record) and returns a List of ImportEntry Records. It is defined piecewise over the following productions:

ImportClause : ImportedDefaultBinding , NameSpaceImport
  1. entries1을 인수 module을 사용한 ImportedDefaultBindingImportEntriesForModule로 둔다.
  2. entries2를 인수 module을 사용한 NameSpaceImportImportEntriesForModule로 둔다.
  3. entries1entries2list-concatenation을 반환한다.
ImportClause : ImportedDefaultBinding , NamedImports
  1. entries1을 인수 module을 사용한 ImportedDefaultBindingImportEntriesForModule로 둔다.
  2. entries2를 인수 module을 사용한 NamedImportsImportEntriesForModule로 둔다.
  3. entries1entries2list-concatenation을 반환한다.
ImportedDefaultBinding : ImportedBinding
  1. localNameImportedBindingBoundNames의 유일한 요소로 둔다.
  2. defaultEntryImportEntry Record { [[ModuleRequest]]: module, [[ImportName]]: "default", [[LocalName]]: localName }로 둔다.
  3. « defaultEntry »를 반환한다.
NameSpaceImport : * as ImportedBinding
  1. localNameImportedBindingStringValue로 둔다.
  2. entryImportEntry Record { [[ModuleRequest]]: module, [[ImportName]]: namespace, [[LocalName]]: localName }로 둔다.
  3. « entry »를 반환한다.
NamedImports : { }
  1. 새 빈 List를 반환한다.
ImportsList : ImportsList , ImportSpecifier
  1. specs1을 인수 module을 사용한 ImportsListImportEntriesForModule로 둔다.
  2. specs2를 인수 module을 사용한 ImportSpecifierImportEntriesForModule로 둔다.
  3. specs1specs2list-concatenation을 반환한다.
ImportSpecifier : ImportedBinding
  1. localNameImportedBindingBoundNames의 유일한 요소로 둔다.
  2. entryImportEntry Record { [[ModuleRequest]]: module, [[ImportName]]: localName, [[LocalName]]: localName }로 둔다.
  3. « entry »를 반환한다.
ImportSpecifier : ModuleExportName as ImportedBinding
  1. importNameModuleExportNameStringValue로 둔다.
  2. localNameImportedBindingStringValue로 둔다.
  3. entryImportEntry Record { [[ModuleRequest]]: module, [[ImportName]]: importName, [[LocalName]]: localName }로 둔다.
  4. « entry »를 반환한다.

16.2.2.4 Static Semantics: WithClauseToAttributes

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

WithClause : with { }
  1. 새 빈 List를 반환한다.
WithClause : with { WithEntries ,opt }
  1. attributesWithEntriesWithClauseToAttributes로 둔다.
  2. attributes[[Key]] 필드의 사전식 순서에 따라 정렬하되, 각 해당 필드의 값을 UTF-16 코드 단위 값의 시퀀스로 취급한다. NOTE: 이 정렬은 호스트가 attribute가 열거되는 순서를 기반으로 동작을 변경하는 것이 금지된다는 점에서만 관찰 가능하다.
  3. attributes를 반환한다.
WithEntries : AttributeKey : StringLiteral
  1. keyAttributeKeyPropName으로 둔다.
  2. entryImportAttribute Record { [[Key]]: key, [[Value]]: StringLiteralSV }로 둔다.
  3. « entry »를 반환한다.
WithEntries : AttributeKey : StringLiteral , WithEntries
  1. keyAttributeKeyPropName으로 둔다.
  2. entryImportAttribute Record { [[Key]]: key, [[Value]]: StringLiteralSV }로 둔다.
  3. restWithEntriesWithClauseToAttributes로 둔다.
  4. « entry »와 restlist-concatenation을 반환한다.

16.2.3 Exports

Syntax

ExportDeclaration : export ExportFromClause FromClause WithClauseopt ; export NamedExports ; export VariableStatement[~Yield, +Await] export Declaration[~Yield, +Await] export default HoistableDeclaration[~Yield, +Await, +Default] export default ClassDeclaration[~Yield, +Await, +Default] export default [lookahead ∉ { function, async [no LineTerminator here] function, class }] AssignmentExpression[+In, ~Yield, +Await] ; ExportFromClause : * * as ModuleExportName NamedExports NamedExports : { } { ExportsList } { ExportsList , } ExportsList : ExportSpecifier ExportsList , ExportSpecifier ExportSpecifier : ModuleExportName ModuleExportName as ModuleExportName

16.2.3.1 Static Semantics: Early Errors

ExportDeclaration : export NamedExports ; Note

위 규칙은 NamedExports의 각 ReferencedBindingsIdentifierReference로 취급됨을 의미한다.

16.2.3.2 Static Semantics: ExportedBindings

The syntax-directed operation ExportedBindings takes no arguments and returns a List of Strings.

Note

ExportedBindings는 ModuleExportedNames와 명시적으로 연결된 로컬 바인딩 이름이다.

It is defined piecewise over the following productions:

ModuleItemList : ModuleItemList ModuleItem
  1. names1ModuleItemListExportedBindings로 둔다.
  2. names2ModuleItemExportedBindings로 둔다.
  3. names1names2list-concatenation을 반환한다.
ModuleItem : ImportDeclaration StatementListItem
  1. 새 빈 List를 반환한다.
ExportDeclaration : export ExportFromClause FromClause WithClauseopt ;
  1. 새 빈 List를 반환한다.
ExportDeclaration : export NamedExports ;
  1. NamedExportsExportedBindings를 반환한다.
ExportDeclaration : export VariableStatement
  1. VariableStatementBoundNames를 반환한다.
ExportDeclaration : export Declaration
  1. DeclarationBoundNames를 반환한다.
ExportDeclaration : export default HoistableDeclaration export default ClassDeclaration export default AssignmentExpression ;
  1. ExportDeclarationBoundNames를 반환한다.
NamedExports : { }
  1. 새 빈 List를 반환한다.
ExportsList : ExportsList , ExportSpecifier
  1. names1ExportsListExportedBindings로 둔다.
  2. names2ExportSpecifierExportedBindings로 둔다.
  3. names1names2list-concatenation을 반환한다.
ExportSpecifier : ModuleExportName
  1. 유일한 요소가 ModuleExportNameStringValueList를 반환한다.
ExportSpecifier : ModuleExportName as ModuleExportName
  1. 유일한 요소가 첫 번째 ModuleExportNameStringValueList를 반환한다.

16.2.3.3 Static Semantics: ExportedNames

The syntax-directed operation ExportedNames takes no arguments and returns a List of Strings.

Note

ExportedNames는 Module이 자신의 로컬 이름 binding 중 하나에 명시적으로 매핑하는 외부에 보이는 이름이다.

It is defined piecewise over the following productions:

ModuleItemList : ModuleItemList ModuleItem
  1. names1ModuleItemListExportedNames로 둔다.
  2. names2ModuleItemExportedNames로 둔다.
  3. names1names2list-concatenation을 반환한다.
ModuleItem : ExportDeclaration
  1. ExportDeclarationExportedNames를 반환한다.
ModuleItem : ImportDeclaration StatementListItem
  1. 새 빈 List를 반환한다.
ExportDeclaration : export ExportFromClause FromClause WithClauseopt ;
  1. ExportFromClauseExportedNames를 반환한다.
ExportFromClause : *
  1. 새 빈 List를 반환한다.
ExportFromClause : * as ModuleExportName
  1. 유일한 요소가 ModuleExportNameStringValueList를 반환한다.
ExportFromClause : NamedExports
  1. NamedExportsExportedNames를 반환한다.
ExportDeclaration : export VariableStatement
  1. VariableStatementBoundNames를 반환한다.
ExportDeclaration : export Declaration
  1. DeclarationBoundNames를 반환한다.
ExportDeclaration : export default HoistableDeclaration export default ClassDeclaration export default AssignmentExpression ;
  1. « "default" »를 반환한다.
NamedExports : { }
  1. 새 빈 List를 반환한다.
ExportsList : ExportsList , ExportSpecifier
  1. names1ExportsListExportedNames로 둔다.
  2. names2ExportSpecifierExportedNames로 둔다.
  3. names1names2list-concatenation을 반환한다.
ExportSpecifier : ModuleExportName
  1. 유일한 요소가 ModuleExportNameStringValueList를 반환한다.
ExportSpecifier : ModuleExportName as ModuleExportName
  1. 유일한 요소가 두 번째 ModuleExportNameStringValueList를 반환한다.

16.2.3.4 Static Semantics: ExportEntries

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

Module : [empty]
  1. 새 빈 List를 반환한다.
ModuleItemList : ModuleItemList ModuleItem
  1. entries1ModuleItemListExportEntries로 둔다.
  2. entries2ModuleItemExportEntries로 둔다.
  3. entries1entries2list-concatenation을 반환한다.
ModuleItem : ImportDeclaration StatementListItem
  1. 새 빈 List를 반환한다.
ExportDeclaration : export ExportFromClause FromClause WithClauseopt ;
  1. moduleExportDeclarationModuleRequests의 유일한 요소로 둔다.
  2. 인수 module을 사용한 ExportFromClauseExportEntriesForModule을 반환한다.
ExportDeclaration : export NamedExports ;
  1. 인수 null을 사용한 NamedExportsExportEntriesForModule을 반환한다.
ExportDeclaration : export VariableStatement
  1. entries를 새 빈 List로 둔다.
  2. namesVariableStatementBoundNames로 둔다.
  3. names의 각 요소 name에 대해,
    1. ExportEntry Record { [[ModuleRequest]]: null, [[ImportName]]: null, [[LocalName]]: name, [[ExportName]]: name }를 entries에 추가한다.
  4. entries를 반환한다.
ExportDeclaration : export Declaration
  1. entries를 새 빈 List로 둔다.
  2. namesDeclarationBoundNames로 둔다.
  3. names의 각 요소 name에 대해,
    1. ExportEntry Record { [[ModuleRequest]]: null, [[ImportName]]: null, [[LocalName]]: name, [[ExportName]]: name }를 entries에 추가한다.
  4. entries를 반환한다.
ExportDeclaration : export default HoistableDeclaration
  1. namesHoistableDeclarationBoundNames로 둔다.
  2. localNamenames의 유일한 요소로 둔다.
  3. 유일한 요소가 새 ExportEntry Record { [[ModuleRequest]]: null, [[ImportName]]: null, [[LocalName]]: localName, [[ExportName]]: "default" }인 List를 반환한다.
ExportDeclaration : export default ClassDeclaration
  1. namesClassDeclarationBoundNames로 둔다.
  2. localNamenames의 유일한 요소로 둔다.
  3. 유일한 요소가 새 ExportEntry Record { [[ModuleRequest]]: null, [[ImportName]]: null, [[LocalName]]: localName, [[ExportName]]: "default" }인 List를 반환한다.
ExportDeclaration : export default AssignmentExpression ;
  1. entryExportEntry Record { [[ModuleRequest]]: null, [[ImportName]]: null, [[LocalName]]: "*default*", [[ExportName]]: "default" }로 둔다.
  2. « entry »를 반환한다.
Note

"*default*"는 이 명세 안에서 익명 default export 값에 대한 synthetic name으로 사용된다. 자세한 내용은 이 노트를 보라.

16.2.3.5 Static Semantics: ExportEntriesForModule

The syntax-directed operation ExportEntriesForModule takes argument module (a ModuleRequest Record or null) and returns a List of ExportEntry Records. It is defined piecewise over the following productions:

ExportFromClause : *
  1. entryExportEntry Record { [[ModuleRequest]]: module, [[ImportName]]: all-but-default, [[LocalName]]: null, [[ExportName]]: null }로 둔다.
  2. « entry »를 반환한다.
ExportFromClause : * as ModuleExportName
  1. exportNameModuleExportNameStringValue로 둔다.
  2. entryExportEntry Record { [[ModuleRequest]]: module, [[ImportName]]: namespace, [[LocalName]]: null, [[ExportName]]: exportName }로 둔다.
  3. « entry »를 반환한다.
NamedExports : { }
  1. 새 빈 List를 반환한다.
ExportsList : ExportsList , ExportSpecifier
  1. specs1을 인수 module을 사용한 ExportsListExportEntriesForModule로 둔다.
  2. specs2를 인수 module을 사용한 ExportSpecifierExportEntriesForModule로 둔다.
  3. specs1specs2list-concatenation을 반환한다.
ExportSpecifier : ModuleExportName
  1. sourceNameModuleExportNameStringValue로 둔다.
  2. modulenull이면,
    1. localNamesourceName으로 둔다.
    2. importNamenull로 둔다.
  3. 그렇지 않으면,
    1. localNamenull로 둔다.
    2. importNamesourceName으로 둔다.
  4. 유일한 요소가 새 ExportEntry Record { [[ModuleRequest]]: module, [[ImportName]]: importName, [[LocalName]]: localName, [[ExportName]]: sourceName }인 List를 반환한다.
ExportSpecifier : ModuleExportName as ModuleExportName
  1. sourceName을 첫 번째 ModuleExportNameStringValue로 둔다.
  2. exportName을 두 번째 ModuleExportNameStringValue로 둔다.
  3. modulenull이면,
    1. localNamesourceName으로 둔다.
    2. importNamenull로 둔다.
  4. 그렇지 않으면,
    1. localNamenull로 둔다.
    2. importNamesourceName으로 둔다.
  5. 유일한 요소가 새 ExportEntry Record { [[ModuleRequest]]: module, [[ImportName]]: importName, [[LocalName]]: localName, [[ExportName]]: exportName }인 List를 반환한다.

16.2.3.6 Static Semantics: ReferencedBindings

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

NamedExports : { }
  1. 새 빈 List를 반환한다.
ExportsList : ExportsList , ExportSpecifier
  1. names1ExportsListReferencedBindings로 둔다.
  2. names2ExportSpecifierReferencedBindings로 둔다.
  3. names1names2list-concatenation을 반환한다.
ExportSpecifier : ModuleExportName as ModuleExportName
  1. 첫 번째 ModuleExportNameReferencedBindings를 반환한다.
ModuleExportName : IdentifierName
  1. 유일한 요소가 IdentifierNameList를 반환한다.
ModuleExportName : StringLiteral
  1. 유일한 요소가 StringLiteralList를 반환한다.

16.2.3.7 Runtime Semantics: Evaluation

ExportDeclaration : export ExportFromClause FromClause WithClauseopt ; export NamedExports ;
  1. empty를 반환한다.
ExportDeclaration : export VariableStatement
  1. VariableStatementEvaluation을 반환한다.
ExportDeclaration : export Declaration
  1. DeclarationEvaluation을 반환한다.
ExportDeclaration : export default HoistableDeclaration
  1. HoistableDeclarationEvaluation을 반환한다.
ExportDeclaration : export default ClassDeclaration
  1. value를 ? ClassDeclarationBindingClassDeclarationEvaluation으로 둔다.
  2. classNameClassDeclarationBoundNames의 유일한 요소로 둔다.
  3. className"*default*"이면,
    1. env를 실행 중인 실행 컨텍스트의 LexicalEnvironment로 둔다.
    2. InitializeBoundName("*default*", value, env)를 수행한다.
  4. empty를 반환한다.
ExportDeclaration : export default AssignmentExpression ;
  1. IsAnonymousFunctionDefinition(AssignmentExpression)이 true이면,
    1. value를 인수 "default"를 사용한 AssignmentExpression의 ? NamedEvaluation으로 둔다.
  2. 그렇지 않으면,
    1. rhs를 ? AssignmentExpressionEvaluation으로 둔다.
    2. value를 ? GetValue(rhs)로 둔다.
  3. env를 실행 중인 실행 컨텍스트의 LexicalEnvironment로 둔다.
  4. InitializeBoundName("*default*", value, env)를 수행한다.
  5. empty를 반환한다.

17 오류 처리 및 언어 확장

구현체는 관련된 ECMAScript 언어 구성요소가 평가될 때 대부분의 오류를 보고해야 한다. An 조기 오류는 오류를 포함하는 Script의 어떤 구성도 평가되기 전에 감지되어 보고될 수 있는 오류이다. 조기 오류의 존재는 해당 구성의 평가를 방지한다. 구현체는 ParseScript에서 해당 Script를 파싱하는 과정의 일부로 Script에 있는 조기 오류를 보고해야 한다. Module조기 오류Module이 평가되는 시점에 보고되며 그 Module은 초기화되지 않는다. eval 코드의 조기 오류eval이 호출될 때 보고되며 eval 코드의 평가를 방지한다. 조기 오류가 아닌 모든 오류는 런타임 오류이다.

구현체는 본 명세서의 “Static Semantics: Early Errors” 하위절에 열거된 상태가 발생하면 이를 조기 오류로 보고해야 한다.

컴파일러가 어떤 구성체가 어떤 상황에서도 오류 없이 실행될 수 없음을 증명할 수 있더라도, 구현체는 다른 종류의 오류를 조기 오류로 취급해서는 안 된다. 구현체는 그러한 경우에 조기 경고를 발행할 수는 있지만, 관련 구성체가 실제로 실행될 때까지 오류를 보고해서는 안 된다.

구현체는 명시된 대로 모든 오류를 보고해야 하며, 다음의 경우는 예외이다:

17.1 금지된 확장

구현체는 다음 방식으로 이 명세를 확장해서는 안 된다:

  • strict 모드 코드에서 구문 생성자를 사용하여 정의된 ECMAScript 함수 객체는 "caller" 또는 "arguments"라는 이름의 자체 소유 속성을 갖고 생성되어서는 안 된다. 이러한 자체 소유 속성은 ArrowFunction, MethodDefinition, GeneratorDeclaration, GeneratorExpression, AsyncGeneratorDeclaration, AsyncGeneratorExpression, ClassDeclaration, ClassExpression, AsyncFunctionDeclaration, AsyncFunctionExpression 또는 AsyncArrowFunction을 사용하여 정의된 함수 객체에도 생성되어서는 안 되며, 정의가 strict 모드 코드에 포함되어 있는지 여부와 관계없이 해당된다. 내장 함수, Function 생성자를 사용하여 생성된 strict 함수, Generator 생성자를 사용하여 생성된 제너레이터 함수, AsyncFunction 생성자를 사용하여 생성된 async 함수, 그리고 bind 메서드를 사용하여 생성된 함수 또한 이러한 자체 소유 속성으로 생성되어서는 안 된다.
  • 구현체가 어떤 함수 객체에 "caller"라는 이름의 자체 소유 속성을 확장하면, 그 속성의 값은 [[Get]] 또는 [[GetOwnProperty]]를 통해 관찰될 때 strict 함수 객체가 되어서는 안 된다. 만약 그것이 접근자 속성이라면, 그 속성의 [[Get]] 속성값인 함수는 호출될 때 결코 strict 함수를 반환해서는 안 된다.
  • 매핑된 arguments 객체이건 매핑되지 않은 arguments 객체이건 "caller"라는 이름의 자체 소유 속성을 가진 객체로 생성되어서는 안 된다.
  • toLocaleString과 같이 ECMA-402에 명시된 내장 메서드의 동작은 ECMA-402에서 명시한 경우를 제외하고 확장되어서는 안 된다.
  • 22.2.1B.1.2에 있는 RegExp 패턴 문법은 [UnicodeMode] 문법 매개변수가 존재할 때 소스 문자 A-Z 또는 a-z 중 어느 것도 IdentityEscape[+UnicodeMode]로 인식하도록 확장되어서는 안 된다.
  • Syntactic Grammar는 BindingIdentifier 비단말 기호와 매치되는 소스 텍스트 바로 뒤에 토큰 :가 즉시 올 수 있도록 허용하는 어떤 방식으로도 확장되어서는 안 된다.
  • strict 모드 코드를 처리할 때, 구현체는 12.9.3.1조기 오류 규칙을 완화해서는 안 된다.
  • TemplateEscapeSequence12.9.4에 정의된 LegacyOctalEscapeSequence 또는 NonOctalDecimalEscapeSequence를 포함하도록 확장되어서는 안 된다.
  • strict 모드 코드를 처리할 때, B.3.1, B.3.2, B.3.3, 및 B.3.5에 정의된 확장은 지원되어서는 안 된다.
  • Module 목표 기호로 파싱할 때, B.1.1에 정의된 렉시컬 문법 확장은 지원되어서는 안 된다.
  • ImportCall은 확장되어서는 안 된다.

18 ECMAScript 표준 내장 객체

ECMAScript Script 또는 Module이 실행을 시작할 때 항상 이용 가능한 특정 내장 객체들이 있다. 그중 하나인 전역 객체는 실행 프로그램의 전역 환경의 일부이다. 나머지 객체들은 전역 객체의 초기 속성으로 접근 가능하거나 접근 가능한 내장 객체의 속성으로 간접적으로 접근 가능하다.

별도 명시가 없는 한, 함수로 호출 가능한 내장 객체는 10.3에 설명된 특성을 갖는 내장 함수 객체이다. 별도 명시가 없는 한, 내장 객체의 [[Extensible]] 내부 슬롯은 초기값으로 true를 가진다. 모든 내장 함수 객체는 [[Realm]] 내부 슬롯을 가지며 그 값은 객체가 처음 생성된 realmRealm 레코드이다.

많은 내장 객체들이 함수이다: 인수와 함께 호출될 수 있다. 그중 일부는 또한 생성자이다: new 연산자와 함께 사용하도록 의도된 함수이다. 각 내장 함수에 대해 이 명세서는 그 함수가 요구하는 인수와 그 함수 객체의 속성을 설명한다. 각 내장 생성자에 대해서는, 해당 생성자를 호출하는 new 표현식이 반환하는 특정 객체 인스턴스의 속성 및 그 생성자의 프로토타입 객체의 속성도 추가로 설명한다.

특정 함수의 설명에서 달리 명시되지 않는 한, 내장 함수나 생성자에 요구된 것보다 적은 인수가 제공되면, 그 함수나 생성자는 충분한 추가 인수가 제공된 것과 정확히 동일하게 동작해야 하며, 각각의 추가 인수는 undefined 값이다. 이러한 누락된 인수는 “존재하지 않음”으로 간주되며 명세 알고리즘에서 그 방식으로 식별될 수 있다. 특정 함수의 설명에서 “this 값”과 “NewTarget” 용어는 10.3에 주어진 의미를 갖는다.

특정 함수의 설명에서 달리 명시되지 않는 한, 내장 함수나 생성자에 허용된 것보다 더 많은 인수가 제공되면 초과 인수들은 호출 시 평가된 다음 함수에 의해 무시된다. 그러나 구현체는 그러한 인수들에 관해 구현체 특정 동작을 정의할 수 있으며, 그 동작이 단지 초과 인수의 존재만을 근거로 TypeError 예외를 던지는 방식이어서는 안 된다.

Note 1

내장 함수 집합에 추가 기능을 더하는 구현체는 기존 함수에 새로운 매개변수를 추가하기보다는 새로운 함수를 추가하는 방식으로 하는 것이 권장된다.

달리 명시되지 않는 한, 모든 내장 함수와 모든 내장 생성자는 Function 프로토타입 객체, 즉 표현식 Function.prototype(20.2.3)의 초기값을 [[Prototype]] 내부 슬롯의 값으로 가진다.

달리 명시되지 않는 한, 모든 내장 프로토타입 객체는 Object 프로토타입 객체, 즉 표현식 Object.prototype(20.1.3)의 초기값을 [[Prototype]] 내부 슬롯의 값으로 가진다. 단, Object 프로토타입 객체 자신은 예외이다.

만약 이 명세서가 내장 생성자의 동작을 알고리즘 단계로 정의하면, 그 알고리즘이 [[Call]][[Construct]]의 목적상 그 동작이다. 만약 알고리즘이 이 두 경우를 구분할 필요가 있으면, NewTarget이 undefined인지 확인하는데, 이는 [[Call]] 호출을 나타낸다.

내장 함수 객체로 식별되지만 생성자로 식별되지 않은 함수 객체는, 특정 함수 설명에서 달리 명시되지 않는 한, [[Construct]] 내부 메서드를 구현하지 않는다.

생성자가 아닌 내장 함수 객체는 특정 함수 설명에서 달리 명시되지 않는 한 "prototype" 속성을 갖지 않는다.

이 명세서에 정의된 모든 내장 함수는 CreateBuiltinFunction 추상 연산(10.3.4)을 호출하여 생성된다. lengthname 매개변수의 값은 아래에서 논의되는 "length""name" 속성의 초기값이다. prefix 매개변수의 값도 아래에서 유사하게 논의된다.

모든 내장 함수 객체는 생성자를 포함하여 "length" 속성을 가지며 그 값은 음이 아닌 정수 Number이다. 달리 명시되지 않는 한, 이 값은 함수 설명의 하위절 제목에 표시된 필수 매개변수의 수이다. 선택적 매개변수와 나머지 매개변수는 매개변수 수에 포함되지 않는다.

Note 2

예를 들어, Array 프로토타입 객체"map" 속성의 초기값인 함수 객체는 하위절 제목 «Array.prototype.map (callback [ , thisArg])» 아래에 설명되어 있으며 여기에는 두 개의 명명된 인수 callback과 thisArg가 표시되고 후자는 선택적이다; 따라서 그 함수 객체의 "length" 속성의 값은 1𝔽이다.

달리 명시되지 않는 한, 내장 함수 객체의 "length" 속성은 속성 어트리뷰트 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }를 가진다.

모든 내장 함수 객체는 생성자를 포함하여 "name" 속성을 가지며 그 값은 문자열이다. 달리 명시되지 않는 한, 이 값은 명세에서 함수에 부여된 이름이다. 익명 함수로 식별된 함수는 "name" 속성의 값으로 빈 문자열을 사용한다. 객체의 속성으로 지정된 함수에 대해 이름 값은 함수를 접근하는 데 사용되는 속성 이름 문자열이다. 내장 속성의 get 또는 set 접근자 함수로 지정된 함수들은 CreateBuiltinFunction을 호출할 때 prefix 매개변수로 "get" 또는 "set"이 전달된다.

만약 내장 함수의 속성 키가 Symbol 값인 경우 그 "name" 속성의 값은 명시적으로 지정된다. 만약 그러한 명시된 값이 접두사 "get " 또는 "set "으로 시작하고 그 값이 지정된 함수가 내장 속성의 get 또는 set 접근자 함수라면, 접두사를 제외한 값이 name 매개변수로 전달되고 "get" 또는 "set"(각각)이 prefix 매개변수로 전달되어 CreateBuiltinFunction을 호출한다.

달리 명시되지 않는 한, 내장 함수 객체의 "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 전역 객체

다음은 전역 객체이다:

19.1 전역 객체의 값 속성들

19.1.1 globalThis

Realm 기록 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 전역 객체의 함수 속성들

19.2.1 eval ( source )

이 함수는 %eval% 내재 객체이다.

호출될 때 다음 단계를 수행한다:

  1. PerformEval(source, false, false)를 반환한다.

19.2.1.1 PerformEval ( source, strictCaller, direct )

The abstract operation PerformEval takes arguments source (an ECMAScript language value), strictCaller (a Boolean), and direct (a Boolean) and returns either a normal completion containing an ECMAScript language value or a throw completion. It performs the following steps when called:

  1. 단언: 만약 directfalse이면, strictCallerfalse여야 한다.
  2. 만약 source가 문자열이 아니면, source를 반환한다.
  3. evalRealm을 현재 Realm 기록으로 하자.
  4. 참고: 직접 eval의 경우, evalRealmeval의 호출자와 eval 함수 자체의 영역(realm)이다.
  5. 수행 ? HostEnsureCanCompileStrings(evalRealm, « », source, direct).
  6. inFunctionfalse로 하자.
  7. inMethodfalse로 하자.
  8. inDerivedConstructorfalse로 하자.
  9. inClassFieldInitializerfalse로 하자.
  10. 만약 directtrue이면,
    1. thisEnvRecGetThisEnvironment()로 하자.
    2. 만약 thisEnvRecFunction Environment Record라면,
      1. functhisEnvRec.[[FunctionObject]]로 하자.
      2. inFunctiontrue로 설정하라.
      3. inMethodthisEnvRec.HasSuperBinding()로 설정하라.
      4. 만약 func.[[ConstructorKind]]derived라면 inDerivedConstructortrue로 설정하라.
      5. classFieldInitializerNamefunc.[[ClassFieldInitializerName]]로 하라.
      6. 만약 classFieldInitializerNameempty가 아니면 inClassFieldInitializertrue로 설정하라.
  11. 구현 정의된 순서로, 파싱과 오류 검출을 섞어 수행할 수 있는 다음 하위단계를 수행한다:
    1. scriptParseText(source, Script)로 하자.
    2. 만약 script가 오류 목록이면, SyntaxError 예외를 던진다.
    3. 만약 scriptScriptBody를 포함하지 않으면, undefined를 반환한다.
    4. bodyscriptScriptBody로 하자.
    5. 만약 inFunctionfalse이고 bodyNewTarget을 포함하면, SyntaxError 예외를 던진다.
    6. 만약 inMethodfalse이고 bodySuperProperty를 포함하면, SyntaxError 예외를 던진다.
    7. 만약 inDerivedConstructorfalse이고 bodySuperCall을 포함하면, SyntaxError 예외를 던진다.
    8. 만약 inClassFieldInitializertrue이고 bodyContainsArgumentstrue이면, SyntaxError 예외를 던진다.
  12. 만약 strictCallertrue이면, strictEvaltrue로 한다.
  13. 그렇지 않으면, strictEvalscriptScriptIsStrict로 한다.
  14. runningContext를 실행 중인 실행 컨텍스트로 하자.
  15. 참고: 만약 directtrue이면, runningContext직접 eval을 수행한 실행 컨텍스트가 된다. 만약 directfalse이면, runningContexteval 함수 호출의 실행 컨텍스트가 된다.
  16. 만약 directtrue이면,
    1. lexEnvNewDeclarativeEnvironment(runningContext's LexicalEnvironment)로 하라.
    2. varEnvrunningContext's VariableEnvironment로 하라.
    3. privateEnvrunningContext's PrivateEnvironment로 하라.
  17. 그렇지 않으면,
    1. lexEnvNewDeclarativeEnvironment(evalRealm.[[GlobalEnv]])로 하라.
    2. varEnvevalRealm.[[GlobalEnv]]로 하라.
    3. privateEnvnull로 하라.
  18. 만약 strictEvaltrue이면 varEnvlexEnv로 설정하라.
  19. 만약 runningContext가 이미 일시중단되어 있지 않다면, runningContext를 일시중단하라.
  20. evalContext를 새로운 ECMAScript 코드 실행 컨텍스트로 하자.
  21. evalContext의 Function을 null로 설정하라.
  22. evalContextRealmevalRealm로 설정하라.
  23. evalContext의 ScriptOrModule을 runningContext's ScriptOrModule로 설정하라.
  24. evalContext의 VariableEnvironment을 varEnv로 설정하라.
  25. evalContext의 LexicalEnvironment을 lexEnv로 설정하라.
  26. evalContext의 PrivateEnvironment을 privateEnv로 설정하라.
  27. 실행 컨텍스트 스택에 evalContext를 푸시하라; 이제 evalContext가 실행 중인 실행 컨텍스트이다.
  28. resultCompletion(EvalDeclarationInstantiation(body, varEnv, lexEnv, privateEnv, strictEval))의 결과로 하라.
  29. 만약 result가 정상 완료이면,
    1. resultCompletion(Evaluation of body)의 결과로 설정하라.
  30. 만약 result가 정상 완료이고 result.[[Value]]empty이면,
    1. resultNormalCompletion(undefined)로 설정하라.
  31. evalContext를 일시중단하고 실행 컨텍스트 스택에서 제거하라.
  32. 실행 컨텍스트 스택의 맨 위에 있는 컨텍스트를 다시 실행 중인 실행 컨텍스트로 재개하라.
  33. result를 반환하라.
Note

eval 코드는 호출한 컨텍스트 또는 eval 코드 자체의 코드 중 어느 쪽이라도 엄격 모드 코드인 경우, 호출한 컨텍스트의 변수 환경에 변수나 함수 바인딩을 생성할 수 없다. 대신 그러한 바인딩들은 eval 코드에서만 접근 가능한 새로운 VariableEnvironment에 인스턴스화된다. let, const, 또는 class 선언으로 도입된 바인딩은 항상 새로운 LexicalEnvironment에 인스턴스화된다.

19.2.1.2 HostEnsureCanCompileStrings ( calleeRealm, parameterStrings, bodyString, direct )

The host-defined abstract operation HostEnsureCanCompileStrings takes arguments calleeRealm (a Realm Record), parameterStrings (a List of Strings), bodyString (a String), and direct (a Boolean) and returns either a normal completion containing unused or a throw completion. 호스트 환경이 문자열을 ECMAScript 코드로 해석·평가하는 것을 허용하는 특정 ECMAScript 함수들을 차단할 수 있도록 한다.

parameterStrings는 함수 생성자들을 사용할 때 매개변수 목록을 만들기 위해 연결될 문자열들을 나타낸다. bodyString은 함수 본문 또는 eval 호출에 전달된 문자열을 나타낸다. direct는 평가가 직접 eval인지 여부를 나타낸다.

HostEnsureCanCompileStrings의 기본 구현은 NormalCompletion(unused)을 반환하는 것이다.

19.2.1.3 EvalDeclarationInstantiation ( body, varEnv, lexEnv, privateEnv, strict )

The abstract operation EvalDeclarationInstantiation takes arguments body (a ScriptBody Parse Node), varEnv (an Environment Record), lexEnv (a Declarative Environment Record), privateEnv (a PrivateEnvironment Record or null), and strict (a Boolean) and returns either a normal completion containing unused or a throw completion. It performs the following steps when called:

  1. varNamesbodyVarDeclaredNames로 하자.
  2. varDeclarationsbodyVarScopedDeclarations로 하자.
  3. 만약 strictfalse이면,
    1. 만약 varEnvGlobal Environment Record이면,
      1. varNames의 각 요소 name에 대해,
        1. 만약 HasLexicalDeclaration(varEnv, name)가 true이면, SyntaxError 예외를 던진다.
        2. 참고: eval은 전역 lexical 선언으로 가려질 글로벌 var 선언을 만들지 않는다.
    2. thisEnvlexEnv로 하자.
    3. 단언: 다음 루프는 종료된다.
    4. thisEnvvarEnv가 동일한 환경 레코드가 아닐 동안 반복,
      1. 만약 thisEnvObject Environment Record가 아니면,
        1. 참고: with 문(environment)은 어떠한 lexical 선언도 포함할 수 없으므로 var/let 호이스팅 충돌을 검사할 필요가 없다.
        2. varNames의 각 요소 name에 대해,
          1. 만약 ! thisEnv.HasBinding(name)가 true이면,
            1. Normative Optional
              호스트가 웹 브라우저이거나 Catch Block 안의 VariableStatement를 지원하면,
              1. 만약 thisEnvCatch 절의 Environment Record가 아니면 SyntaxError 예외를 던진다.
            2. 그렇지 않으면,
              1. SyntaxError 예외를 던진다.
          2. 참고: 직접 eval은 같은 이름의 lexical 선언보다 var 선언을 끌어올리지 않는다.
      2. thisEnvthisEnv.[[OuterEnv]]로 설정하라.
  4. privateIdentifiers를 새로운 빈 목록으로 하자.
  5. pointerprivateEnv로 하자.
  6. pointernull이 아닐 동안 반복,
    1. pointer.[[Names]]의 각 Private Name binding에 대해,
      1. 만약 privateIdentifiersbinding.[[Description]]을 포함하지 않으면, binding.[[Description]]privateIdentifiers에 추가하라.
    2. pointerpointer.[[OuterPrivateEnvironment]]로 설정하라.
  7. 만약 AllPrivateIdentifiersValid of bodyprivateIdentifiers를 인자로 호출한 결과가 false이면, SyntaxError 예외를 던진다.
  8. functionsToInitialize를 새로운 빈 목록으로 하자.
  9. declaredFunctionNames를 새로운 빈 목록으로 하자.
  10. varDeclarations의 각 요소 d에 대해, 역순으로,
    1. 만약 dVariableDeclaration, ForBinding, 또는 BindingIdentifier가 아니면,
      1. 단언: dFunctionDeclaration, GeneratorDeclaration, AsyncFunctionDeclaration, 또는 AsyncGeneratorDeclaration 중 하나이다.
      2. 참고: 동일 이름에 대한 함수 선언이 여러 개 있으면 마지막 선언이 사용된다.
      3. fndBoundNames의 유일한 요소로 하자.
      4. 만약 declaredFunctionNamesfn이 포함되어 있지 않으면,
        1. 만약 varEnvGlobal Environment Record이면,
          1. fnDefinable을 ? CanDeclareGlobalFunction(varEnv, fn)로 하라.
          2. 만약 fnDefinablefalse이면, TypeError 예외를 던진다.
        2. fndeclaredFunctionNames에 추가하라.
        3. dfunctionsToInitialize의 첫 번째 요소로 삽입하라.
  11. declaredVarNames를 새로운 빈 목록으로 하자.
  12. varDeclarations의 각 요소 d에 대해,
    1. 만약 dVariableDeclaration, ForBinding, 또는 BindingIdentifier이면,
      1. dBoundNames의 각 문자열 vn에 대해,
        1. 만약 declaredFunctionNamesvn을 포함하지 않으면,
          1. 만약 varEnvGlobal Environment Record이면,
            1. vnDefinable을 ? CanDeclareGlobalVar(varEnv, vn)로 하라.
            2. 만약 vnDefinablefalse이면, TypeError 예외를 던진다.
          2. 만약 declaredVarNamesvn을 포함하지 않으면,
            1. vndeclaredVarNames에 추가하라.
  13. Normative Optional
    만약 strictfalse이고 호스트가 웹 브라우저이거나 Block-Level Function Declaration 웹 Legacy 호환성 의미론를 지원하면,
    1. declaredFunctionOrVarNamesdeclaredFunctionNamesdeclaredVarNames의 리스트 이어붙이기로 하라.
    2. 어떤 Block, CaseClause, 또는 DefaultClause xStatementList에 직접 포함된 각 FunctionDeclaration f에 대해, 조건: bodyx를 포함하면,
      1. funcNamefBindingIdentifierStringValue로 하라.
      2. 만약 FunctionDeclaration f를 같은 이름의 BindingIdentifier를 가진 VariableStatement으로 바꿔도 body에 대한 Early Errors가 발생하지 않으면,
        1. bindingExistsfalse로 하자.
        2. thisEnvlexEnv로 설정하라.
        3. 단언: 다음 루프는 종료된다.
        4. thisEnvvarEnv가 아닐 동안 반복,
          1. 만약 thisEnvObject Environment Record가 아니면,
            1. 만약 ! thisEnv.HasBinding(funcName)가 true이면,
              1. Normative Optional
                호스트가 웹 브라우저이거나 Catch Block 안의 VariableStatement를 지원하면,
                1. 만약 thisEnvCatch 절의 Environment Record가 아니면 bindingExiststrue로 설정하라.
              2. 그렇지 않으면,
                1. bindingExiststrue로 설정하라.
          2. thisEnvthisEnv.[[OuterEnv]]로 설정하라.
        5. 만약 bindingExistsfalse이고 varEnvGlobal Environment Record이면,
          1. 만약 HasLexicalDeclaration(varEnv, funcName)가 false이면,
            1. fnDefinable을 ? CanDeclareGlobalVar(varEnv, funcName)로 하라.
          2. 그렇지 않으면,
            1. fnDefinablefalse로 하라.
        6. 그렇지 않으면,
          1. fnDefinabletrue로 하라.
        7. 만약 bindingExistsfalse이고 fnDefinabletrue이면,
          1. 만약 declaredFunctionOrVarNamesfuncName을 포함하지 않으면,
            1. 만약 varEnvGlobal Environment Record이면,
              1. 수행 ? CreateGlobalVarBinding(varEnv, funcName, true).
            2. 그렇지 않으면,
              1. bindingExists를 ! varEnv.HasBinding(funcName)로 설정하라.
              2. 만약 bindingExistsfalse이면,
                1. 수행 ! varEnv.CreateMutableBinding(funcName, true).
                2. 수행 ! varEnv.InitializeBinding(funcName, undefined).
            3. funcNamedeclaredFunctionOrVarNames에 추가하라.
          2. FunctionDeclaration f가 평가될 때, 15.2.6에 제공된 FunctionDeclaration 평가 알고리즘 대신 다음 단계를 수행하라:
            1. gEnv를 실행 중인 실행 컨텍스트의 VariableEnvironment로 하라.
            2. bEnv를 실행 중인 실행 컨텍스트의 LexicalEnvironment로 하라.
            3. fObj를 ! bEnv.GetBindingValue(funcName, false)로 하라.
            4. 수행 ? gEnv.SetMutableBinding(funcName, fObj, false).
            5. unused를 반환하라.
  14. 참고: 이 알고리즘 단계 이후에는 varEnvGlobal Environment Record이고 전역 객체가 Proxy 특수 객체가 아닌 한 비정상 종료가 발생하지 않는다.
  15. lexDeclarationsbodyLexicallyScopedDeclarations로 하자.
  16. lexDeclarations의 각 요소 d에 대해,
    1. 참고: 렉시컬 선언 이름들은 여기서만 인스턴스화되며 초기화되지는 않는다.
    2. dBoundNames의 각 요소 dn에 대해,
      1. 만약 IsConstantDeclaration of dtrue이면,
        1. 수행 ? lexEnv.CreateImmutableBinding(dn, true).
      2. 그렇지 않으면,
        1. 수행 ? lexEnv.CreateMutableBinding(dn, false).
  17. functionsToInitialize의 각 Parse Node f에 대해,
    1. fnfBoundNames의 유일한 요소로 하라.
    2. foInstantiateFunctionObject of f에 인자 lexEnvprivateEnv로 하여 얻는다.
    3. 만약 varEnvGlobal Environment Record이면,
      1. 수행 ? CreateGlobalFunctionBinding(varEnv, fn, fo, true).
    4. 그렇지 않으면,
      1. bindingExists를 ! varEnv.HasBinding(fn)로 하라.
      2. 만약 bindingExistsfalse이면,
        1. 참고: 다음 호출은 14 이전의 검증 때문에 비정상 종료를 반환할 수 없다.
        2. 수행 ! varEnv.CreateMutableBinding(fn, true).
        3. 수행 ! varEnv.InitializeBinding(fn, fo).
      3. 그렇지 않으면,
        1. 수행 ! varEnv.SetMutableBinding(fn, fo, false).
  18. declaredVarNames의 각 문자열 vn에 대해,
    1. 만약 varEnvGlobal Environment Record이면,
      1. 수행 ? CreateGlobalVarBinding(varEnv, vn, true).
    2. 그렇지 않으면,
      1. bindingExists를 ! varEnv.HasBinding(vn)로 하라.
      2. 만약 bindingExistsfalse이면,
        1. 참고: 다음 호출은 14 이전의 검증 때문에 비정상 종료를 반환할 수 없다.
        2. 수행 ! varEnv.CreateMutableBinding(vn, true).
        3. 수행 ! varEnv.InitializeBinding(vn, undefined).
  19. unused를 반환하라.

19.2.2 isFinite ( number )

이 함수는 %isFinite% 내재 객체이다.

호출될 때 다음 단계를 수행한다:

  1. num을 ? ToNumber(number)로 하라.
  2. 만약 num유한이면, true를 반환한다.
  3. false를 반환한다.

19.2.3 isNaN ( number )

이 함수는 %isNaN% 내재 객체이다.

호출될 때 다음 단계를 수행한다:

  1. num을 ? ToNumber(number)로 하라.
  2. 만약 numNaN이면, true를 반환한다.
  3. false를 반환한다.
Note

XNaN인지 테스트하는 신뢰할 수 있는 방법은 X !== X 형식의 표현식이다. 그 결과는 오직 XNaN일 때만 true가 된다.

19.2.4 parseFloat ( string )

이 함수는 string 인수의 내용을 십진 리터럴로 해석하여 결정된 Number 값을 생성한다.

이 함수는 %parseFloat% 내재 객체이다.

호출될 때 다음 단계를 수행한다:

  1. inputString을 ? ToString(string)로 하라.
  2. trimmedString을 ! TrimString(inputString, start)로 하라.
  3. trimmedStringToCodePoints(trimmedString)로 하라.
  4. trimmedPrefixStrDecimalLiteral 문법을 만족하는 trimmed의 가장 긴 접두사로 하라; 없으면 NaN을 반환한다.
  5. parsedNumberParseText(trimmedPrefix, StrDecimalLiteral)로 하라.
  6. 단언: parsedNumber는 Parse Node이다.
  7. parsedNumberStringNumericValue를 반환한다.
Note

이 함수는 string의 선행 부분만을 Number 값으로 해석할 수 있다; 십진수 표기법의 일부로 해석할 수 없는 코드 유닛은 무시되며, 무시된 코드 유닛이 있었다는 표시를 제공하지 않는다.

19.2.5 parseInt ( string, radix )

이 함수는 지정된 radix에 따라 string의 내용을 해석하여 정수 Number를 생성한다. string의 선행 공백은 무시된다. 만약 radix가 0으로 강제 변환되면(예: undefined일 때), 숫자 표기법이 "0x" 또는 "0X"으로 시작하지 않는 한 10으로 간주된다; 시작이 "0x" 또는 "0X"이면 16으로 간주된다. 만약 radix가 16이면, 숫자 표기법은 선택적으로 "0x" 또는 "0X"으로 시작할 수 있다.

이 함수는 %parseInt% 내재 객체이다.

호출될 때 다음 단계를 수행한다:

  1. inputString을 ? ToString(string)로 하라.
  2. trimmedString을 ! TrimString(inputString, start)로 하라.
  3. sign을 1로 하라.
  4. 만약 trimmedString이 비어있지 않고 첫 코드 유닛이 코드 유닛 0x002D (HYPHEN-MINUS)이면, sign을 -1로 설정하라.
  5. 만약 trimmedString이 비어있지 않고 첫 코드 유닛이 0x002B (PLUS SIGN) 또는 0x002D (HYPHEN-MINUS)이면, trimmedString을 인덱스 1부터의 부분 문자열로 설정하라.
  6. radixMV(? ToInt32(radix))로 하라.
  7. stripPrefixtrue로 하라.
  8. 만약 radixMV ≠ 0이면,
    1. 만약 radixMV < 2 또는 radixMV > 36이면, NaN을 반환한다.
    2. 만약 radixMV ≠ 16이면, stripPrefixfalse로 설정하라.
  9. 그렇지 않으면,
    1. radixMV를 10으로 설정하라.
  10. 만약 stripPrefixtrue이면,
    1. 만약 trimmedString의 길이 ≥ 2이고 처음 두 코드 유닛이 "0x" 또는 "0X"이면,
      1. trimmedString을 인덱스 2부터의 부분 문자열로 설정하라.
      2. radixMV를 16으로 설정하라.
  11. 만약 trimmedString이 radix-radixMV 자릿수가 아닌 코드 유닛을 포함하면, 그 첫 번째 그런 코드 유닛의 인덱스를 end로 하라; 그렇지 않으면 endtrimmedString의 길이로 하라.
  12. numberStringtrimmedString의 0부터 end까지의 부분 문자열로 하라.
  13. 만약 numberString이 비어있으면, NaN을 반환한다.
  14. mathIntnumberString이 radix-radixMV 표기법으로 나타내는 정수 값으로 하라; 값 10~35에 대해 문자 AZaz를 사용한다. (단, 만약 radixMV = 10이고 numberString이 20개를 초과하는 유효 숫자를 포함하면 구현은 20번째 이후의 모든 유효 숫자를 0으로 대체할 수 있다; 그리고 radixMV가 2,4,8,10,16,32 중 하나가 아니면, mathInt는 구현이 근사한 정수일 수 있다.)
  15. 만약 mathInt = 0이면,
    1. 만약 sign = -1이면, -0𝔽를 반환한다.
    2. +0𝔽를 반환한다.
  16. 𝔽(sign × mathInt)을 반환한다.
Note

이 함수는 string의 선행 부분만을 정수 값으로 해석할 수 있다; 정수 표기법의 일부로 해석할 수 없는 코드 유닛은 무시되며, 무시된 코드 유닛이 있었다는 표시를 제공하지 않는다.

19.2.6 URI 처리 함수들

Uniform Resource Identifier(URI)는 리소스(예: 웹 페이지나 파일)와 이를 접근하는 전송 프로토콜(예: HTTP 또는 FTP)을 식별하는 문자열이다. ECMAScript 언어 자체는 URI 사용을 위한 추가 지원을 제공하지 않으며, 이 절에서 설명된 대로 URI를 인코딩하고 디코딩하는 함수들만 제공한다. encodeURIdecodeURI는 전체 URI와 함께 동작하도록 설계되었으며, 예약된 문자가 특별한 의미(예: 구분자)를 갖는 것으로 간주하여 인코딩하지 않는다. encodeURIComponentdecodeURIComponent는 URI의 개별 구성 요소와 함께 동작하도록 설계되었으며, 예약된 문자가 텍스트를 나타내고 구성 요소가 전체 URI의 일부일 때 특별한 의미를 피하기 위해 인코딩되어야 한다고 가정한다.

Note 1

예약 문자의 집합은 RFC 2396을 기반으로 하며 더 최근의 RFC 3986이 도입한 변경을 반영하지 않는다.

Note 2

많은 ECMAScript 구현은 웹 페이지를 조작하는 추가 함수와 메서드를 제공한다; 이러한 함수들은 이 표준의 범위를 벗어난다.

19.2.6.1 decodeURI ( encodedURI )

이 함수는 encodeURI 함수가 도입했을 수 있는 형태의 이스케이프 시퀀스와 UTF-8 인코딩을 해당 코드 포인트가 나타내는 UTF-16 인코딩으로 대체한 새로운 URI 버전을 계산한다. encodeURI가 도입했을 수 없는 이스케이프 시퀀스는 대체하지 않는다.

이 함수는 %decodeURI% 내재 객체이다.

호출될 때 다음 단계를 수행한다:

  1. uriString을 ? ToString(encodedURI)로 하라.
  2. preserveEscapeSet";/?:@&=+$,#"로 하라.
  3. Return ? Decode(uriString, preserveEscapeSet).

19.2.6.2 decodeURIComponent ( encodedURIComponent )

이 함수는 encodeURIComponent 함수가 도입했을 수 있는 형태의 이스케이프 시퀀스와 UTF-8 인코딩을 해당 코드 포인트가 나타내는 UTF-16 인코딩으로 대체한 새로운 URI 버전을 계산한다.

이 함수는 %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 인코딩을 나타내는 하나, 둘, 셋 또는 네 개의 이스케이프 시퀀스로 대체한 새로운 버전을 계산한다.

이 함수는 %encodeURI% 내재 객체이다.

호출될 때 다음 단계를 수행한다:

  1. uriString을 ? ToString(uri)로 하라.
  2. extraUnescaped";/?:@&=+$,#"로 하라.
  3. Return ? Encode(uriString, extraUnescaped).

19.2.6.4 encodeURIComponent ( uriComponent )

이 함수는 UTF-16로 인코딩된 (6.1.4) URI 구성 요소에서 특정 코드 포인트의 각 인스턴스를 해당 코드 포인트의 UTF-8 인코딩을 나타내는 하나, 둘, 셋 또는 네 개의 이스케이프 시퀀스로 대체한 새로운 버전을 계산한다.

이 함수는 %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 (a String) and extraUnescaped (a String) and returns either a normal completion containing a String or a throw completion. UTF-16로 인코딩된 코드 포인트의 시퀀스로서 string을 해석하면서 URI 인코딩과 이스케이프를 수행한다(참조 6.1.4). RFC 2396에서 예약되지 않은 것으로 식별되었거나 extraUnescaped에 나타나는 문자는 이스케이프되지 않는다. It performs the following steps when called:

  1. lenstring의 길이로 하라.
  2. result를 빈 문자열로 하라.
  3. alwaysUnescaped를 ASCII 단어 문자와 "-.!~*'()"의 문자열 이어붙이기로 하라.
  4. unescapedSetalwaysUnescapedextraUnescaped의 문자열 이어붙이기로 하라.
  5. k를 0으로 하라.
  6. k < len인 동안 반복,
    1. codeUnitstring의 인덱스 k의 코드 유닛으로 하라.
    2. 만약 unescapedSetcodeUnit을 포함하면,
      1. kk + 1로 설정하라.
      2. resultresultcodeUnit의 문자열 이어붙이기로 설정하라.
    3. 그렇지 않으면,
      1. cpCodePointAt(string, k)로 하라.
      2. 만약 cp.[[IsUnpairedSurrogate]]true이면, URIError 예외를 던진다.
      3. kk + cp.[[CodeUnitCount]]로 설정하라.
      4. octetscp.[[CodePoint]]에 UTF-8 변환을 적용하여 얻은 옥텟들의 목록으로 하라.
      5. octets의 각 요소 octet에 대해,
        1. hex를 대문자 16진수로 포맷된 octet의 문자열 표현으로 하라.
        2. resultresult, "%", 및 StringPad(hex, 2, "0", start)의 문자열 이어붙이기로 설정하라.
  7. result를 반환한다.
Note

퍼센트 인코딩은 개별 옥텟을 표현하기 위해 사용되므로, 단일 코드 포인트가 여러 연속된 이스케이프 시퀀스(각 8비트 UTF-8 코드 유닛마다 하나)로 표현될 수 있다.

19.2.6.6 Decode ( string, preserveEscapeSet )

The abstract operation Decode takes arguments string (a String) and preserveEscapeSet (a String) and returns either a normal completion containing a String or a throw completion. Basic Latin 문자들 중 preserveEscapeSet에 해당하는 이스케이프 시퀀스는 보존하면서 URI 언이스케이프와 디코딩을 수행한다. It performs the following steps when called:

  1. lenstring의 길이로 하라.
  2. result를 빈 문자열로 하라.
  3. k를 0으로 하라.
  4. k < len인 동안 반복,
    1. codeUnitstring의 인덱스 k의 코드 유닛으로 하라.
    2. segmentcodeUnit로 하라.
    3. 만약 codeUnit이 코드 유닛 0x0025 (PERCENT SIGN)이면,
      1. 만약 k + 3 > len이면, URIError 예외를 던진다.
      2. escapestringk부터 k + 3까지의 부분 문자열로 하라.
      3. firstOctetParseHexOctet(string, k + 1)로 하라.
      4. 만약 firstOctet정수가 아니면, URIError 예외를 던진다.
      5. kk + 2로 설정하라.
      6. nfirstOctet의 선행 1 비트 수로 하라.
      7. 만약 n = 0이면,
        1. asciiChar를 숫자 값이 firstOctet인 코드 유닛으로 하라.
        2. 만약 preserveEscapeSetasciiChar를 포함하면 segmentescape로 설정; 그렇지 않으면 segmentasciiChar로 설정하라.
      8. 그렇지 않으면,
        1. 만약 n = 1 또는 n > 4이면, URIError 예외를 던진다.
        2. octets를 « firstOctet »로 하라.
        3. j를 1로 하라.
        4. j < n인 동안 반복,
          1. kk + 1로 설정하라.
          2. 만약 k + 3 > len이면, URIError 예외를 던진다.
          3. 만약 string의 인덱스 k의 코드 유닛이 코드 유닛 0x0025 (PERCENT SIGN)이 아니면, URIError 예외를 던진다.
          4. continuationByteParseHexOctet(string, k + 1)로 하라.
          5. 만약 continuationByte정수가 아니면, URIError 예외를 던진다.
          6. continuationByteoctets에 추가하라.
          7. kk + 2로 설정하라.
          8. jj + 1로 설정하라.
        5. 단언: octets의 길이는 n이다.
        6. 만약 octets가 유효한 UTF-8 인코딩을 포함하지 않으면, URIError 예외를 던진다.
        7. codePointoctets에 UTF-8 변환을 적용해 얻은 코드 포인트로 하라.
        8. segmentUTF16EncodeCodePoint(codePoint)로 설정하라.
    4. resultresultsegment의 문자열 이어붙이기로 설정하라.
    5. kk + 1로 설정하라.
  5. result를 반환한다.
Note

RFC 3629는 잘못된 UTF-8 옥텟 시퀀스의 디코딩을 금지한다. 예를 들어 잘못된 시퀀스 0xC0 0x80은 코드 유닛 0x0000으로 디코딩되어서는 안 된다. Decode 알고리즘의 구현체는 이러한 잘못된 시퀀스를 만났을 때 URIError를 던져야 한다.

19.2.6.7 ParseHexOctet ( string, position )

The abstract operation ParseHexOctet takes arguments string (a String) and position (a non-negative integer) and returns either a non-negative integer or a non-empty List of SyntaxError objects. 문자열의 지정된 position에서 두 개의 16진수 문자를 파싱하여 부호 없는 8비트 정수로 변환한다. It performs the following steps when called:

  1. lenstring의 길이로 하라.
  2. 단언: position + 2 ≤ len.
  3. hexDigitsstringposition부터 position + 2까지의 부분 문자열로 하라.
  4. parseResultParseText(hexDigits, HexDigits[~Sep])로 하라.
  5. 만약 parseResult가 Parse Node가 아니면, parseResult를 반환한다.
  6. nparseResult의 MV로 하라.
  7. 단언: n은 0에서 255의 포함 구간에 있다.
  8. n을 반환한다.

19.3 전역 객체의 생성자 속성들

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 기본 객체

20.1 Object 객체들

20.1.1 Object 생성자

Object 생성자:

  • %Object%이다.
  • 전역 객체"Object" 속성의 초기 값이다.
  • 생성자로 호출될 때 새로운 일반 객체를 생성한다.
  • 생성자가 아닌 함수로 호출될 때 형 변환을 수행한다.
  • 클래스 정의의 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]] 내부 슬롯을 가진다.
  • 다음의 추가적인 속성들을 가진다:

20.1.2.1 Object.assign ( target, ...sources )

이 함수는 하나 이상의 소스 객체로부터 열거 가능한 모든 자체 속성의 값을 target 객체로 복사한다.

호출될 때 다음 단계를 수행한다:

  1. to를 ? ToObject(target)로 하자.
  2. 인수가 하나만 전달된다면 to를 반환한다.
  3. sources의 각 요소 nextSource에 대해
    1. 만약 nextSourceundefined도 아니고 null도 아니면,
      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. Perform ? Set(to, nextKey, propValue, true).
  4. to를 반환한다.

이 함수의 "length" 속성은 2𝔽이다.

20.1.2.2 Object.create ( proto, properties )

이 함수는 지정된 프로토타입을 가진 새로운 객체를 만든다.

호출될 때 다음 단계를 수행한다:

  1. 만약 proto가 객체가 아니고 protonull도 아니면, TypeError 예외를 던진다.
  2. objOrdinaryObjectCreate(proto)로 하자.
  3. 만약 propertiesundefined가 아니면,
    1. ObjectDefineProperties(obj, properties)를 반환한다.
  4. obj를 반환한다.

20.1.2.3 Object.defineProperties ( obj, properties )

이 함수는 객체의 자체 속성을 추가하고/또는 기존 자체 속성의 속성들을 갱신한다.

호출될 때 다음 단계를 수행한다:

  1. 만약 obj가 객체가 아니면, TypeError 예외를 던진다.
  2. ObjectDefineProperties(obj, properties)를 반환한다.

20.1.2.3.1 ObjectDefineProperties ( obj, properties )

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

  1. 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. 레코드 { [[Key]]: nextKey, [[Descriptor]]: desc }를 descriptors에 추가하라.
  5. descriptors의 각 요소 property에 대해
    1. Perform ? DefinePropertyOrThrow(obj, property.[[Key]], property.[[Descriptor]]).
  6. obj를 반환하라.

20.1.2.4 Object.defineProperty ( obj, propertyKey, attributes )

이 함수는 객체의 자체 속성을 추가하고/또는 기존 자체 속성의 속성을 갱신한다.

호출될 때 다음 단계를 수행한다:

  1. 만약 obj가 객체가 아니면, TypeError 예외를 던진다.
  2. key를 ? ToPropertyKey(propertyKey)로 하자.
  3. desc를 ? ToPropertyDescriptor(attributes)로 하자.
  4. Perform ? DefinePropertyOrThrow(obj, key, desc).
  5. obj를 반환하라.

20.1.2.5 Object.entries ( obj )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. coerced를 ? ToObject(obj)로 하자.
  2. entryList를 ? EnumerableOwnProperties(coerced, key+value)로 하자.
  3. CreateArrayFromList(entryList)를 반환하라.

20.1.2.6 Object.freeze ( obj )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. 만약 obj가 객체가 아니면 obj를 반환한다.
  2. status를 ? SetIntegrityLevel(obj, frozen)로 하자.
  3. 만약 statusfalse이면 TypeError 예외를 던진다.
  4. obj를 반환한다.

20.1.2.7 Object.fromEntries ( iterable )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. Perform ? RequireObjectCoercible(iterable).
  2. objOrdinaryObjectCreate(%Object.prototype%)로 하자.
  3. 단언: obj는 자체 속성이 없는 확장 가능한 일반 객체이다.
  4. closureobj를 캡처하고 호출될 때 다음 단계를 수행하는 매개변수 (key, value)를 가진 새로운 추상 클로저로 하자:
    1. propertyKey를 ? ToPropertyKey(key)로 하자.
    2. Perform ! CreateDataPropertyOrThrow(obj, propertyKey, value).
    3. NormalCompletion(undefined)를 반환하라.
  5. adderCreateBuiltinFunction(closure, 2, "", « »)로 하자.
  6. Return ? AddEntriesFromIterable(obj, iterable, adder).
Note
adder를 위해 생성된 함수는 ECMAScript 코드에서 직접 접근할 수 없다.

20.1.2.8 Object.getOwnPropertyDescriptor ( obj, propertyKey )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. coerced를 ? ToObject(obj)로 하자.
  2. key를 ? ToPropertyKey(propertyKey)로 하자.
  3. desc를 ? coerced.[[GetOwnProperty]](key)로 하자.
  4. FromPropertyDescriptor(desc)를 반환하라.

20.1.2.9 Object.getOwnPropertyDescriptors ( obj )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. coerced를 ? ToObject(obj)로 하자.
  2. ownKeys를 ? coerced.[[OwnPropertyKeys]]()로 하자.
  3. descriptorsOrdinaryObjectCreate(%Object.prototype%)로 하자.
  4. ownKeys의 각 요소 key에 대해
    1. desc를 ? coerced.[[GetOwnProperty]](key)로 하자.
    2. descriptorFromPropertyDescriptor(desc)로 하자.
    3. 만약 descriptorundefined가 아니면, Perform ! CreateDataPropertyOrThrow(descriptors, key, descriptor).
  5. descriptors를 반환하라.

20.1.2.10 Object.getOwnPropertyNames ( obj )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. CreateArrayFromList(? GetOwnPropertyKeys(obj, string))를 반환한다.

20.1.2.11 Object.getOwnPropertySymbols ( obj )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. CreateArrayFromList(? GetOwnPropertyKeys(obj, symbol))를 반환한다.

20.1.2.11.1 GetOwnPropertyKeys ( value, type )

The abstract operation GetOwnPropertyKeys takes arguments value (an ECMAScript language value) and type (string or symbol) and returns either a normal completion containing a List of property keys or a throw completion. It performs the following steps when called:

  1. obj를 ? ToObject(value)로 하자.
  2. keys를 ? obj.[[OwnPropertyKeys]]()로 하자.
  3. nameList를 새로운 빈 목록으로 하자.
  4. keys의 각 요소 nextKey에 대해
    1. 만약 nextKey가 Symbol이고 typesymbol이거나, 또는 nextKey가 String이고 typestring이면,
      1. nextKeynameList에 추가하라.
  5. nameList를 반환하라.

20.1.2.12 Object.getPrototypeOf ( obj )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. coerced를 ? ToObject(obj)로 하자.
  2. Return ? coerced.[[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. groups의 각 레코드 { [[Key]], [[Elements]] } g에 대해
    1. elementsCreateArrayFromList(g.[[Elements]])로 하자.
    2. Perform ! CreateDataPropertyOrThrow(obj, g.[[Key]], elements).
  4. obj를 반환하라.

20.1.2.14 Object.hasOwn ( obj, propertyKey )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. coerced를 ? ToObject(obj)로 하자.
  2. key를 ? ToPropertyKey(propertyKey)로 하자.
  3. HasOwnProperty(coerced, key)를 반환하라.

20.1.2.15 Object.is ( value1, value2 )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. SameValue(value1, value2)를 반환한다.

20.1.2.16 Object.isExtensible ( obj )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. 만약 obj가 객체가 아니면 false를 반환한다.
  2. Return ? IsExtensible(obj).

20.1.2.17 Object.isFrozen ( obj )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. 만약 obj가 객체가 아니면 true를 반환한다.
  2. Return ? TestIntegrityLevel(obj, frozen).

20.1.2.18 Object.isSealed ( obj )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. 만약 obj가 객체가 아니면 true를 반환한다.
  2. Return ? TestIntegrityLevel(obj, sealed).

20.1.2.19 Object.keys ( obj )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. coerced를 ? ToObject(obj)로 하자.
  2. keyList를 ? EnumerableOwnProperties(coerced, key)로 하자.
  3. CreateArrayFromList(keyList)를 반환하라.

20.1.2.20 Object.preventExtensions ( obj )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. 만약 obj가 객체가 아니면 obj를 반환한다.
  2. status를 ? obj.[[PreventExtensions]]()로 하자.
  3. 만약 statusfalse이면 TypeError 예외를 던진다.
  4. obj를 반환하라.

20.1.2.21 Object.prototype

Object.prototype의 초기 값은 Object 프로토타입 객체이다.

이 속성은 속성들 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }을 가진다.

20.1.2.22 Object.seal ( obj )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. 만약 obj가 객체가 아니면 obj를 반환한다.
  2. status를 ? SetIntegrityLevel(obj, sealed)로 하자.
  3. 만약 statusfalse이면 TypeError 예외를 던진다.
  4. obj를 반환하라.

20.1.2.23 Object.setPrototypeOf ( obj, proto )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. Perform ? RequireObjectCoercible(obj).
  2. 만약 proto가 객체가 아니고 protonull도 아니면, TypeError 예외를 던진다.
  3. 만약 obj가 객체가 아니면 obj를 반환한다.
  4. status를 ? obj.[[SetPrototypeOf]](proto)로 하자.
  5. 만약 statusfalse이면 TypeError 예외를 던진다.
  6. obj를 반환하라.

20.1.2.24 Object.values ( obj )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. coerced를 ? ToObject(obj)로 하자.
  2. valueList를 ? EnumerableOwnProperties(coerced, 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 ( value )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. propertyKey를 ? ToPropertyKey(value)로 하자.
  2. obj를 ? ToObject(this value)로 하자.
  3. HasOwnProperty(obj, propertyKey)를 반환하라.
Note

단계 12의 순서는 이전 판본의 이 명세에서 단계 1에 의해 던져졌을 예외가 this 값이 undefined 또는 null인 경우에도 계속 던져지도록 보장하기 위해 선택되었다.

20.1.3.3 Object.prototype.isPrototypeOf ( value )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. 만약 value가 객체가 아니면 false를 반환한다.
  2. obj를 ? ToObject(this value)로 하자.
  3. 반복,
    1. value를 ? value.[[GetPrototypeOf]]()로 설정하라.
    2. 만약 valuenull이면 false를 반환하라.
    3. 만약 SameValue(obj, value)가 true이면 true를 반환하라.
Note

단계 12의 순서는 이전 판본의 이 명세에서 value가 객체가 아니고 this 값이 undefined 또는 null인 경우에 지정된 동작을 보존한다.

20.1.3.4 Object.prototype.propertyIsEnumerable ( value )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. propertyKey를 ? ToPropertyKey(value)로 하자.
  2. obj를 ? ToObject(this value)로 하자.
  3. desc를 ? obj.[[GetOwnProperty]](propertyKey)로 하자.
  4. 만약 descundefined이면 false를 반환하라.
  5. desc.[[Enumerable]]를 반환하라.
Note 1

이 메서드는 프로토타입 체인의 객체들은 고려하지 않는다.

Note 2

단계 12의 순서는 이전 판본의 이 명세에서 단계 1에 의해 던져졌을 예외가 this 값이 undefined 또는 null인 경우에도 계속 던져지도록 보장하기 위해 선택되었다.

20.1.3.5 Object.prototype.toLocaleString ( [ reserved1 [ , reserved2 ] ] )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. thisValuethis 값으로 하자.
  2. Invoke(thisValue, "toString")를 반환하라.

이 메서드의 선택적 매개변수들은 사용되지 않지만 ECMA-402의 toLocaleString 메서드에서 사용되는 매개변수 패턴에 대응하도록 의도되었다. ECMA-402 지원을 포함하지 않는 구현체는 그 매개변수 위치들을 다른 목적으로 사용해서는 안 된다.

Note 1

이 메서드는 로케일에 민감한 toString 동작이 없는 객체들을 위한 일반적인 toLocaleString 구현을 제공한다. Array, Number, Date, 및 %TypedArray%는 자체적인 로케일 민감 toLocaleString 메서드를 제공한다.

Note 2

ECMA-402는 의도적으로 이 기본 구현에 대한 대안을 제공하지 않는다.

20.1.3.6 Object.prototype.toString ( )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. 만약 this 값이 undefined이면 "[object Undefined]"를 반환한다.
  2. 만약 this 값이 null이면 "[object Null]"를 반환한다.
  3. obj를 ! ToObject(this value)로 하자.
  4. isArray를 ? IsArray(obj)로 하자.
  5. 만약 isArraytrue이면 builtinTag"Array"로 하자.
  6. 그렇지 않고 obj[[ParameterMap]] 내부 슬롯을 가지고 있으면 builtinTag"Arguments"로 하자.
  7. 그렇지 않고 obj[[Call]] 내부 메서드를 가지고 있으면 builtinTag"Function"로 하자.
  8. 그렇지 않고 obj[[ErrorData]] 내부 슬롯을 가지고 있으면 builtinTag"Error"로 하자.
  9. 그렇지 않고 obj[[BooleanData]] 내부 슬롯을 가지고 있으면 builtinTag"Boolean"로 하자.
  10. 그렇지 않고 obj[[NumberData]] 내부 슬롯을 가지고 있으면 builtinTag"Number"로 하자.
  11. 그렇지 않고 obj[[StringData]] 내부 슬롯을 가지고 있으면 builtinTag"String"로 하자.
  12. 그렇지 않고 obj[[DateValue]] 내부 슬롯을 가지고 있으면 builtinTag"Date"로 하자.
  13. 그렇지 않고 obj[[RegExpMatcher]] 내부 슬롯을 가지고 있으면 builtinTag"RegExp"로 하자.
  14. 그렇지 않으면 builtinTag"Object"로 하자.
  15. tag를 ? Get(obj, %Symbol.toStringTag%)로 하자.
  16. 만약 tag가 문자열이 아니면 tagbuiltinTag로 설정하라.
  17. "[object ", tag, 및 "]"의 문자열 이어붙이기를 반환하라.
Note

역사적으로 이 메서드는 이전 판본의 이 명세에서 다양한 내장 객체들에 대한 명목형 타입 태그로 사용되었던 [[Class]] 내부 슬롯의 문자열 값을 접근하기 위해 가끔 사용되었다. 위의 toString 정의는 이러한 특정 종류의 내장 객체들에 대해 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. obj를 ? ToObject(this value)로 하자.
  2. Return ? obj.[[GetPrototypeOf]]().

20.1.3.8.2 set Object.prototype.__proto__

[[Set]] 속성의 값은 매개변수 proto를 받는 내장 함수이다. 이 함수는 호출될 때 다음 단계를 수행한다:

  1. thisValuethis 값으로 하자.
  2. Perform ? RequireObjectCoercible(thisValue).
  3. 만약 proto가 객체가 아니고 protonull도 아니면 undefined를 반환하라.
  4. 만약 thisValue가 객체가 아니면 undefined를 반환하라.
  5. status를 ? thisValue.[[SetPrototypeOf]](proto)로 하자.
  6. 만약 statusfalse이면 TypeError 예외를 던진다.
  7. undefined를 반환하라.
Normative Optional, Legacy

20.1.3.9 레거시 Object.prototype 접근자 메서드들

20.1.3.9.1 Object.prototype.__defineGetter__ ( propertyKey, getter )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. obj를 ? ToObject(this value)로 하자.
  2. 만약 IsCallable(getter)가 false이면 TypeError 예외를 던진다.
  3. desc를 PropertyDescriptor { [[Get]]: getter, [[Enumerable]]: true, [[Configurable]]: true }로 하자.
  4. key를 ? ToPropertyKey(propertyKey)로 하자.
  5. Perform ? DefinePropertyOrThrow(obj, key, desc).
  6. undefined를 반환하라.

20.1.3.9.2 Object.prototype.__defineSetter__ ( propertyKey, setter )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. obj를 ? ToObject(this value)로 하자.
  2. 만약 IsCallable(setter)가 false이면 TypeError 예외를 던진다.
  3. desc를 PropertyDescriptor { [[Set]]: setter, [[Enumerable]]: true, [[Configurable]]: true }로 하자.
  4. key를 ? ToPropertyKey(propertyKey)로 하자.
  5. Perform ? DefinePropertyOrThrow(obj, key, desc).
  6. undefined를 반환하라.

20.1.3.9.3 Object.prototype.__lookupGetter__ ( propertyKey )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. obj를 ? ToObject(this value)로 하자.
  2. key를 ? ToPropertyKey(propertyKey)로 하자.
  3. 반복,
    1. desc를 ? obj.[[GetOwnProperty]](key)로 하자.
    2. 만약 descundefined가 아니면,
      1. 만약 IsAccessorDescriptor(desc)가 true이면 desc.[[Get]]를 반환하라.
      2. undefined를 반환하라.
    3. obj를 ? obj.[[GetPrototypeOf]]()로 설정하라.
    4. 만약 objnull이면 undefined를 반환하라.

20.1.3.9.4 Object.prototype.__lookupSetter__ ( propertyKey )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. obj를 ? ToObject(this value)로 하자.
  2. key를 ? ToPropertyKey(propertyKey)로 하자.
  3. 반복,
    1. desc를 ? obj.[[GetOwnProperty]](key)로 하자.
    2. 만약 descundefined가 아니면,
      1. 만약 IsAccessorDescriptor(desc)가 true이면 desc.[[Set]]를 반환하라.
      2. undefined를 반환하라.
    3. obj를 ? obj.[[GetPrototypeOf]]()로 설정하라.
    4. 만약 objnull이면 undefined를 반환하라.

20.1.4 객체 인스턴스의 속성들

객체 인스턴스는 Object 프로토타입 객체로부터 상속되는 것 이외에 특별한 속성을 가지지 않는다.

20.2 함수 객체들

20.2.1 Function 생성자

Function 생성자:

  • %Function%이다.
  • 전역 객체"Function" 속성의 초기 값이다.
  • 생성자가 아닌 함수로 호출될 때 새로운 함수 객체를 생성하고 초기화한다. 따라서 함수 호출 Function(…)은 동일한 인수로 new Function(…) 객체 생성 표현식과 동등하다.
  • 클래스 정의의 extends 절의 값으로 사용될 수 있다. 지정된 Function 동작을 상속하려는 서브클래스 생성자는 내장 함수 동작에 필요한 내부 슬롯들로 서브클래스 인스턴스를 생성하고 초기화하기 위해 Function 생성자에 대한 super 호출을 포함해야 한다. 함수 객체를 정의하는 모든 ECMAScript 문법 형태는 Function의 인스턴스를 생성한다. 내장된 GeneratorFunction, AsyncFunction, AsyncGeneratorFunction 서브클래스를 제외하고는 Function 서브클래스의 인스턴스를 생성하는 문법적 수단은 없다.

20.2.1.1 Function ( ...parameterArgs, bodyArg )

마지막 인수(있다면)는 함수의 본문(실행 가능한 코드)을 지정한다; 앞의 인수들은 형식 매개변수를 지정한다.

이 함수는 호출될 때 다음 단계를 수행한다:

  1. constructor를 활성 함수 객체로 하자.
  2. 만약 bodyArg가 존재하지 않으면 bodyArg를 빈 문자열로 설정하라.
  3. Return ? CreateDynamicFunction(constructor, 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 (a constructor), newTarget (a constructor or undefined), kind (normal, generator, async, or async-generator), parameterArgs (a List of ECMAScript language values), and bodyArg (an ECMAScript language value) and returns either a normal completion containing an ECMAScript function object or a throw completion. constructor는 이 동작을 수행하는 생성자 함수이다. newTargetnew가 처음 적용된 생성자이다. parameterArgsbodyArgconstructor에 전달된 인수 값을 반영한다. It performs the following steps when called:

  1. 만약 newTargetundefined이면 newTargetconstructor로 설정하라.
  2. 만약 kindnormal이면,
    1. prefix"function"으로 하자.
    2. exprSym를 문법 기호 FunctionExpression으로 하자.
    3. bodySym를 문법 기호 FunctionBody[~Yield, ~Await]으로 하자.
    4. parameterSym를 문법 기호 FormalParameters[~Yield, ~Await]으로 하자.
    5. fallbackProto"%Function.prototype%"로 하자.
  3. 그렇지 않고 kindgenerator이면,
    1. prefix"function*"으로 하자.
    2. exprSym를 문법 기호 GeneratorExpression으로 하자.
    3. bodySym를 문법 기호 GeneratorBody으로 하자.
    4. parameterSym를 문법 기호 FormalParameters[+Yield, ~Await]으로 하자.
    5. fallbackProto"%GeneratorFunction.prototype%"로 하자.
  4. 그렇지 않고 kindasync이면,
    1. prefix"async function"으로 하자.
    2. exprSym를 문법 기호 AsyncFunctionExpression으로 하자.
    3. bodySym를 문법 기호 AsyncFunctionBody으로 하자.
    4. parameterSym를 문법 기호 FormalParameters[~Yield, +Await]으로 하자.
    5. fallbackProto"%AsyncFunction.prototype%"으로 하자.
  5. 그렇지 않으면,
    1. 단언: kindasync-generator이다.
    2. prefix"async function*"으로 하자.
    3. exprSym를 문법 기호 AsyncGeneratorExpression으로 하자.
    4. bodySym를 문법 기호 AsyncGeneratorBody으로 하자.
    5. parameterSym를 문법 기호 FormalParameters[+Yield, +Await]으로 하자.
    6. fallbackProto"%AsyncGeneratorFunction.prototype%"로 하자.
  6. argCountparameterArgs의 요소 수로 하자.
  7. parameterStrings를 새로운 빈 목록으로 하자.
  8. parameterArgs의 각 요소 arg에 대해
    1. ToString(arg)를 parameterStrings에 추가하라.
  9. bodyString를 ? ToString(bodyArg)로 하자.
  10. currentRealm을 현재 Realm 기록으로 하자.
  11. Perform ? HostEnsureCanCompileStrings(currentRealm, parameterStrings, bodyString, false).
  12. parameterString를 빈 문자열로 하자.
  13. 만약 argCount > 0이면,
    1. parameterStringparameterStrings[0]로 설정하라.
    2. k를 1로 하자.
    3. 반복, k < argCount인 동안,
      1. nextArgStringparameterStrings[k]로 하자.
      2. parameterStringparameterString, ","(쉼표), 및 nextArgString의 문자열 이어붙이기로 설정하라.
      3. kk + 1로 설정하라.
  14. bodyParseString를 0x000A (LINE FEED), bodyString, 및 0x000A (LINE FEED)의 문자열 이어붙이기로 하자.
  15. sourceStringprefix, " anonymous(", parameterString, 0x000A (LINE FEED), ") {", bodyParseString, 및 "}"의 문자열 이어붙이기로 하자.
  16. sourceTextStringToCodePoints(sourceString)로 하자.
  17. parametersParseText(parameterString, parameterSym)로 하자.
  18. 만약 parameters가 오류 목록이면 SyntaxError 예외를 던진다.
  19. bodyParseText(bodyParseString, bodySym)로 하자.
  20. 만약 body가 오류 목록이면 SyntaxError 예외를 던진다.
  21. 참고: 매개변수와 본문은 각각 단독으로 유효한지 확인하기 위해 별도로 파싱된다. 예를 들어 new Function("/*", "*/ ) {")는 함수로 평가되지 않는다.
  22. 참고: 이 단계에 도달하면 sourceTextexprSym의 문법을 가져야 한다(역은 성립하지 않을 수 있다). 다음 두 단계의 목적은 exprSym에 직접 적용되는 조기 오류 규칙을 강제하기 위함이다.
  23. exprParseText(sourceText, exprSym)로 하자.
  24. 만약 expr가 오류 목록이면 SyntaxError 예외를 던진다.
  25. proto를 ? GetPrototypeFromConstructor(newTarget, fallbackProto)로 하자.
  26. envcurrentRealm.[[GlobalEnv]]로 하자.
  27. privateEnvnull로 하자.
  28. funcOrdinaryFunctionCreate(proto, sourceText, parameters, body, non-lexical-this, env, privateEnv)로 하자.
  29. Perform SetFunctionName(func, "anonymous").
  30. 만약 kindgenerator이면,
    1. prototypeOrdinaryObjectCreate(%GeneratorPrototype%)로 하자.
    2. Perform ! DefinePropertyOrThrow(func, "prototype", PropertyDescriptor { [[Value]]: prototype, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false }).
  31. 그렇지 않고 kindasync-generator이면,
    1. prototypeOrdinaryObjectCreate(%AsyncGeneratorPrototype%)로 하자.
    2. Perform ! DefinePropertyOrThrow(func, "prototype", PropertyDescriptor { [[Value]]: prototype, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false }).
  32. 그렇지 않고 kindnormal이면,
    1. Perform MakeConstructor(func).
  33. 참고: kindasync인 함수는 생성 가능하지 않으며 [[Construct]] 내부 메서드나 "prototype" 속성을 가지지 않는다.
  34. func를 반환하라.
Note

CreateDynamicFunction은 생성하는 함수 중 kindasync가 아닌 함수에 대해 "prototype" 속성을 정의하여 그 함수가 생성자로 사용될 가능성에 대비한다.

20.2.2 Function 생성자의 속성들

Function 생성자:

  • 자체가 내장 함수 객체이다.
  • 값이 %Function.prototype%[[Prototype]] 내부 슬롯을 가진다.
  • "length" 속성의 값은 1𝔽이다.
  • 다음의 속성들을 가진다:

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" 속성을 가지지 않는다.
  • "length" 속성의 값은 +0𝔽이다.
  • "name" 속성의 값은 빈 문자열이다.
Note

Function 프로토타입 객체는 ECMAScript 2015 이전에 생성된 ECMAScript 코드와의 호환성을 보장하기 위해 함수 객체로 지정되어 있다.

20.2.3.1 Function.prototype.apply ( thisArg, argArray )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. functhis 값으로 하자.
  2. 만약 IsCallable(func)가 false이면 TypeError 예외를 던진다.
  3. 만약 argArrayundefined 또는 null이면,
    1. Perform PrepareForTailCall().
    2. Return ? Call(func, thisArg).
  4. argList를 ? CreateListFromArrayLike(argArray)로 하자.
  5. Perform PrepareForTailCall().
  6. Return ? Call(func, thisArg, argList).
Note 1

thisArg 값은 변경 없이 this 값으로 전달된다. 이는 Edition 3에서 undefined 또는 nullthisArg전역 객체로 대체되고 다른 모든 값에 ToObject가 적용되어 그 결과가 this 값으로 전달되던 동작에서의 변경이다. thisArg가 변경 없이 전달되더라도, 비엄격 함수들은 함수 진입 시에 여전히 이러한 변환을 수행한다.

Note 2

만약 func가 화살표 함수이거나 바인드된 함수 이국적 객체이면, thisArg는 단계 6의 함수 [[Call]]에 의해 무시될 것이다.

20.2.3.2 Function.prototype.bind ( thisArg, ...args )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. targetthis 값으로 하자.
  2. 만약 IsCallable(target)가 false이면 TypeError 예외를 던진다.
  3. boundFunc를 ? BoundFunctionCreate(target, thisArg, args)로 하자.
  4. length를 0으로 하자.
  5. targetHasLength를 ? HasOwnProperty(target, "length")로 하자.
  6. 만약 targetHasLengthtrue이면,
    1. targetLen을 ? Get(target, "length")로 하자.
    2. 만약 targetLen이 Number이면,
      1. 만약 targetLen+∞𝔽이면,
        1. length를 +∞로 설정하라.
      2. 그렇지 않고 targetLen-∞𝔽이면,
        1. length를 0으로 설정하라.
      3. 그렇지 않으면,
        1. targetLenAsInt를 ! ToIntegerOrInfinity(targetLen)로 하자.
        2. 단언: targetLenAsInt유한하다.
        3. argCountargs의 요소 수로 하자.
        4. lengthmax(targetLenAsInt - argCount, 0)으로 설정하라.
  7. Perform SetFunctionLength(boundFunc, length).
  8. targetName를 ? Get(target, "name")로 하자.
  9. 만약 targetName이 문자열이 아니면 targetName를 빈 문자열로 설정하라.
  10. Perform SetFunctionName(boundFunc, targetName, "bound").
  11. boundFunc를 반환하라.
Note 1

Function.prototype.bind를 사용하여 생성된 함수 객체는 이국적 객체이다. 또한 이들은 "prototype" 속성을 가지지 않는다.

Note 2

만약 target이 화살표 함수이거나 바인드된 함수 이국적 객체이면, 이 메서드에 전달된 thisArg는 이후의 func 호출에서 사용되지 않을 것이다.

20.2.3.3 Function.prototype.call ( thisArg, ...args )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. functhis 값으로 하자.
  2. 만약 IsCallable(func)가 false이면 TypeError 예외를 던진다.
  3. Perform PrepareForTailCall().
  4. Return ? Call(func, thisArg, args).
Note 1

thisArg 값은 변경 없이 this 값으로 전달된다. 이는 Edition 3에서의 동작에서의 변경이다. 비엄격 함수들은 여전히 진입 시 변환을 수행한다.

Note 2

만약 func가 화살표 함수이거나 바인드된 함수 이국적 객체이면, thisArg는 단계 4의 함수 [[Call]]에서 무시될 것이다.

20.2.3.4 Function.prototype.constructor

Function.prototype.constructor의 초기 값은 %Function%이다.

20.2.3.5 Function.prototype.toString ( )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. functhis 값으로 하자.
  2. 만약 func가 객체이고, func[[SourceText]] 내부 슬롯을 가지며, func.[[SourceText]]가 유니코드 코드 포인트의 시퀀스이고 HostHasSourceTextAvailable(func)가 true이면,
    1. CodePointsToString(func.[[SourceText]])를 반환하라.
  3. 만약 func내장 함수 객체이면, 구현 정의의 문자열 소스 코드 표현을 반환하라. 그 표현은 NativeFunction의 문법을 가져야 한다. 추가로, 만약 func[[InitialName]] 내부 슬롯을 가지고 있고 func.[[InitialName]]이 문자열이면, 반환된 문자열에서 NativeFunctionAccessoropt PropertyName에 매칭될 부분은 func.[[InitialName]]이어야 한다.
  4. 만약 func가 객체이고 IsCallable(func)가 true이면, 구현 정의의 문자열 소스 코드 표현을 반환하라. 그 표현은 NativeFunction의 문법을 가져야 한다.
  5. TypeError 예외를 던진다.
NativeFunction : function NativeFunctionAccessoropt PropertyName[~Yield, ~Await]opt ( FormalParameters[~Yield, ~Await] ) { [ native code ] } NativeFunctionAccessor : get set

20.2.3.6 Function.prototype [ %Symbol.hasInstance% ] ( value )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. thisValuethis 값으로 하자.
  2. Return ? OrdinaryHasInstance(thisValue, value).

이 속성은 속성들 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }을 가진다.

Note

이것은 대부분의 함수가 상속하는 %Symbol.hasInstance%의 기본 구현이다. %Symbol.hasInstance%instanceof 연산자가 값이 특정 생성자의 인스턴스인지 결정할 때 호출된다. 예를 들어 식

v instanceof F

는 다음과 같이 평가된다

F[%Symbol.hasInstance%](v)

생성자 함수는 함수에 다른 %Symbol.hasInstance% 메서드를 노출함으로써 instanceof가 인식하는 객체들을 제어할 수 있다.

이 속성은 바인드된 함수의 대상 함수를 전역적으로 노출하는 데 사용될 수 있는 변조를 방지하기 위해 쓰기 불가 및 구성 불가로 설정되어 있다.

이 메서드의 "name" 속성의 값은 "[Symbol.hasInstance]"이다.

20.2.4 함수 인스턴스들

모든 Function 인스턴스는 ECMAScript 함수 객체이며 Table 25에 나열된 내부 슬롯들을 가진다. Function.prototype.bind 메서드(20.2.3.2)를 사용하여 생성된 함수 객체는 Table 26에 나열된 내부 슬롯들을 가진다.

함수 인스턴스는 다음 속성들을 가진다:

20.2.4.1 length

"length" 속성의 값은 함수가 기대하는 인수의 전형적인 수를 나타내는 정수 Number이다. 그러나 언어는 함수가 다른 수의 인수로 호출되는 것을 허용한다. "length" 속성에 명시된 수와 다른 수의 인수로 호출될 때 함수의 동작은 함수에 따라 다르다. 이 속성은 속성들 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }을 가진다.

20.2.4.2 name

"name" 속성의 값은 함수에 대해 설명적인 문자열이다. 이름은 의미론적 중요성은 없지만 일반적으로 ECMAScript 소스 텍스트에서 정의 지점에서 함수를 참조하는 변수나 속성 이름이다. 이 속성은 속성들 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }을 가진다.

이 명세에 의해 컨텍스트 이름이 연관되지 않은 익명 함수 객체는 "name" 속성의 값으로 빈 문자열을 사용한다.

20.2.4.3 prototype

생성자로 사용될 수 있는 함수 인스턴스는 "prototype" 속성을 가진다. 그러한 Function 인스턴스가 생성될 때마다 또 다른 일반 객체가 생성되며 그 객체는 해당 함수의 "prototype" 속성의 초기 값이다. 달리 명시되지 않는 한, "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 (a function object) and returns a Boolean. 호스트 환경func에 대한 소스 텍스트 제공을 방지할 수 있게 한다.

HostHasSourceTextAvailable의 구현은 다음 요구사항을 충족해야 한다:

  • 매개변수에 대해 결정론적이어야 한다. 특정 func을 인수로 받아 호출될 때마다 동일한 결과를 반환해야 한다.

HostHasSourceTextAvailable의 기본 구현은 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. obj를 ? OrdinaryCreateFromConstructor(NewTarget, "%Boolean.prototype%", « [[BooleanData]] »)로 하자.
  4. obj.[[BooleanData]]b로 설정하라.
  5. obj를 반환하라.

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%이다.
  • 일반 객체이다.
  • 자체가 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"를 반환한다.
  3. "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 (an ECMAScript language value) and returns either a normal completion containing a Boolean or a throw completion. It performs the following steps when called:

  1. 만약 value가 Boolean이면 value를 반환한다.
  2. 만약 value가 객체이고 value[[BooleanData]] 내부 슬롯을 가지고 있으면,
    1. bvalue.[[BooleanData]]로 하자.
    2. 단언: b는 Boolean이다.
    3. b를 반환하라.
  3. TypeError 예외를 던진다.

20.3.4 Boolean 인스턴스의 속성들

Boolean 인스턴스는 Boolean 프로토타입 객체로부터 속성을 상속하는 일반 객체이다. 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. If NewTarget is not undefined, throw a TypeError exception.
  2. If description is undefined, let descString be undefined.
  3. Else, let descString be ? ToString(description).
  4. Return a new Symbol whose [[Description]] is descString.

20.4.2 Symbol 생성자의 속성

Symbol 생성자는:

  • 그 값이 %Function.prototype%[[Prototype]] 내부 슬롯을 가진다.
  • 다음 속성을 가진다:

20.4.2.1 Symbol.asyncIterator

Symbol.asyncIterator의 초기값은 잘 알려진 Symbol %Symbol.asyncIterator%이다(Table 1).

이 속성은 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false } 특성을 가진다.

20.4.2.2 Symbol.for ( key )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. stringKey를 ? ToString(key)으로 둔다.
  2. GlobalSymbolRegistry List의 각 요소 e에 대해, 다음을 수행한다
    1. e.[[Key]]stringKey이면, e.[[Symbol]]을 반환한다.
  3. Assert: GlobalSymbolRegistry List는 현재 stringKey에 대한 항목을 포함하지 않는다.
  4. newSymbol[[Description]]stringKey인 새로운 Symbol로 둔다.
  5. GlobalSymbolRegistry Record { [[Key]]: stringKey, [[Symbol]]: newSymbol }를 GlobalSymbolRegistry List에 추가한다.
  6. newSymbol을 반환한다.

GlobalSymbolRegistry List는 전역적으로 사용 가능한 추가 전용 List이다. 이는 모든 Realm이 공유한다. 어떤 ECMAScript 코드의 평가보다 먼저, 새로운 빈 List로 초기화된다. GlobalSymbolRegistry List의 요소는 Table 58에 정의된 구조를 가진 Record이다.

Table 58: GlobalSymbolRegistry Record 필드
필드 이름 용도
[[Key]] String Symbol을 전역적으로 식별하는 데 사용되는 문자열 키.
[[Symbol]] Symbol 어떤 Realm에서도 가져올 수 있는 Symbol.

20.4.2.3 Symbol.hasInstance

Symbol.hasInstance의 초기값은 잘 알려진 Symbol %Symbol.hasInstance%이다(Table 1).

이 속성은 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false } 특성을 가진다.

20.4.2.4 Symbol.isConcatSpreadable

Symbol.isConcatSpreadable의 초기값은 잘 알려진 Symbol %Symbol.isConcatSpreadable%이다(Table 1).

이 속성은 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false } 특성을 가진다.

20.4.2.5 Symbol.iterator

Symbol.iterator의 초기값은 잘 알려진 Symbol %Symbol.iterator%이다(Table 1).

이 속성은 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false } 특성을 가진다.

20.4.2.6 Symbol.keyFor ( sym )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. sym이 Symbol이 아니면, TypeError 예외를 던진다.
  2. KeyForSymbol(sym)을 반환한다.

20.4.2.7 Symbol.match

Symbol.match의 초기값은 잘 알려진 Symbol %Symbol.match%이다(Table 1).

이 속성은 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false } 특성을 가진다.

20.4.2.8 Symbol.matchAll

Symbol.matchAll의 초기값은 잘 알려진 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의 초기값은 잘 알려진 Symbol %Symbol.replace%이다(Table 1).

이 속성은 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false } 특성을 가진다.

20.4.2.11 Symbol.search

Symbol.search의 초기값은 잘 알려진 Symbol %Symbol.search%이다(Table 1).

이 속성은 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false } 특성을 가진다.

20.4.2.12 Symbol.species

Symbol.species의 초기값은 잘 알려진 Symbol %Symbol.species%이다(Table 1).

이 속성은 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false } 특성을 가진다.

20.4.2.13 Symbol.split

Symbol.split의 초기값은 잘 알려진 Symbol %Symbol.split%이다(Table 1).

이 속성은 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false } 특성을 가진다.

20.4.2.14 Symbol.toPrimitive

Symbol.toPrimitive의 초기값은 잘 알려진 Symbol %Symbol.toPrimitive%이다(Table 1).

이 속성은 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false } 특성을 가진다.

20.4.2.15 Symbol.toStringTag

Symbol.toStringTag의 초기값은 잘 알려진 Symbol %Symbol.toStringTag%이다(Table 1).

이 속성은 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false } 특성을 가진다.

20.4.2.16 Symbol.unscopables

Symbol.unscopables의 초기값은 잘 알려진 Symbol %Symbol.unscopables%이다(Table 1).

이 속성은 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false } 특성을 가진다.

20.4.3 Symbol 프로토타입 객체의 속성

Symbol 프로토타입 객체는:

  • %Symbol.prototype%이다.
  • ordinary object이다.
  • 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 (a Symbol) and returns a String. It performs the following steps when called:

  1. descsym.[[Description]]으로 둔다.
  2. descundefined이면, desc를 빈 String으로 설정한다.
  3. Assert: 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 (an ECMAScript language value) and returns either a normal completion containing a Symbol or a throw completion. It performs the following steps when called:

  1. value가 Symbol이면, value를 반환한다.
  2. value가 Object이고 value[[SymbolData]] 내부 슬롯을 가지면, 다음을 수행한다
    1. svalue.[[SymbolData]]로 둔다.
    2. Assert: s는 Symbol이다.
    3. s를 반환한다.
  3. TypeError 예외를 던진다.

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% 속성의 초기값은 String 값 "Symbol"이다.

이 속성은 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true } 특성을 가진다.

20.4.4 Symbol 인스턴스의 속성

Symbol 인스턴스는 Symbol 프로토타입 객체로부터 속성을 상속하는 ordinary object이다. Symbol 인스턴스는 [[SymbolData]] 내부 슬롯을 가진다. [[SymbolData]] 내부 슬롯은 이 Symbol 객체가 나타내는 Symbol 값이다.

20.4.5 Symbol을 위한 추상 연산

20.4.5.1 KeyForSymbol ( sym )

The abstract operation KeyForSymbol takes argument sym (a Symbol) and returns a String or 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. Assert: GlobalSymbolRegistry List는 현재 sym에 대한 항목을 포함하지 않는다.
  3. undefined를 반환한다.

20.5 Error 객체들

Error 객체의 인스턴스는 런타임 오류가 발생할 때 예외로 던져진다. Error 객체는 사용자 정의 예외 클래스의 기반 객체로도 사용될 수 있다.

ECMAScript 구현이 런타임 오류를 감지하면, 20.5.5에 정의된 NativeError 객체들 중 하나의 새 인스턴스 또는 20.5.7에 정의된 AggregateError 객체의 새 인스턴스를 던진다.

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. obj를 ? OrdinaryCreateFromConstructor(newTarget, "%Error.prototype%", « [[ErrorData]] »)로 하자.
  3. 만약 messageundefined가 아니면,
    1. msg를 ? ToString(message)로 하자.
    2. Perform CreateNonEnumerableDataPropertyOrThrow(obj, "message", msg).
  4. Perform ? InstallErrorCause(obj, options).
  5. obj를 반환하라.

20.5.2 Error 생성자의 속성들

Error 생성자:

  • 값이 %Function.prototype%[[Prototype]] 내부 슬롯을 가진다.
  • 다음의 속성들을 가진다:

20.5.2.1 Error.isError ( arg )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. 만약 arg가 객체가 아니면 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%이다.
  • 일반 객체이다.
  • 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. objthis 값으로 하자.
  2. 만약 obj가 객체가 아니면 TypeError 예외를 던진다.
  3. name를 ? Get(obj, "name")로 하자.
  4. 만약 nameundefined이면 name"Error"로 설정; 그렇지 않으면 name을 ? ToString(name)로 설정하라.
  5. msg를 ? Get(obj, "message")로 하자.
  6. 만약 msgundefined이면 msg를 빈 문자열로 설정; 그렇지 않으면 msg를 ? ToString(msg)로 설정하라.
  7. 만약 name이 빈 문자열이면 msg를 반환하라.
  8. 만약 msg가 빈 문자열이면 name을 반환하라.
  9. name, 코드 유닛 0x003A (COLON), 코드 유닛 0x0020 (SPACE), 및 msg의 문자열 이어붙이기를 반환하라.

20.5.4 Error 인스턴스의 속성들

Error 인스턴스는 Error 프로토타입 객체로부터 속성을 상속하는 일반 객체이며 값이 undefined[[ErrorData]] 내부 슬롯을 가진다. [[ErrorData]]의 유일한 명시된 용도는 Object.prototype.toStringError.isError에서 Error, AggregateError, 및 NativeError 인스턴스를 Error 객체로 식별하는 것이다.

20.5.5 이 표준에서 사용되는 네이티브 오류 유형들

런타임 오류가 감지되면 아래의 NativeError 객체들 중 하나 또는 AggregateError 객체의 새 인스턴스가 던져진다. 모든 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" 속성에 사용되는 이름만 다르다.

각 오류 객체에 대해 정의에서 NativeError에 대한 참조는 20.5.5에서 적절한 오류 객체 이름으로 대체되어야 한다.

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. obj를 ? OrdinaryCreateFromConstructor(newTarget, "%NativeError.prototype%", « [[ErrorData]] »)로 하자.
  3. 만약 messageundefined가 아니면,
    1. msg를 ? ToString(message)로 하자.
    2. Perform CreateNonEnumerableDataPropertyOrThrow(obj, "message", msg).
  4. Perform ? InstallErrorCause(obj, options).
  5. obj를 반환하라.

단계 2에서 전달되는 문자열의 실제 값은 정의되는 NativeError 생성자에 해당하여 "%EvalError.prototype%", "%RangeError.prototype%", "%ReferenceError.prototype%", "%SyntaxError.prototype%", "%TypeError.prototype%", 또는 "%URIError.prototype%" 중 하나이다.

20.5.6.2 NativeError 생성자들의 속성들

NativeError 생성자:

  • 값이 %Error%[[Prototype]] 내부 슬롯을 가진다.
  • "name" 속성의 값은 문자열 "NativeError"이다.
  • 다음의 속성들을 가진다:

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 프로토타입 객체는:

  • 일반 객체이다.
  • 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 대신 사용되는 이름)으로 구성된 문자열 값이다.

20.5.6.4 NativeError 인스턴스의 속성들

NativeError 인스턴스는 자신의 NativeError 프로토타입 객체로부터 속성을 상속하는 일반 객체이며 값이 undefined[[ErrorData]] 내부 슬롯을 가진다. [[ErrorData]]의 유일한 명시된 사용은 Object.prototype.toStringError.isError에서 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. obj를 ? OrdinaryCreateFromConstructor(newTarget, "%AggregateError.prototype%", « [[ErrorData]] »)로 하자.
  3. 만약 messageundefined가 아니면,
    1. msg를 ? ToString(message)로 하자.
    2. Perform CreateNonEnumerableDataPropertyOrThrow(obj, "message", msg).
  4. Perform ? InstallErrorCause(obj, options).
  5. errorsList를 ? IteratorToList(? GetIterator(errors, sync))로 하자.
  6. Perform ! DefinePropertyOrThrow(obj, "errors", PropertyDescriptor { [[Configurable]]: true, [[Enumerable]]: false, [[Writable]]: true, [[Value]]: CreateArrayFromList(errorsList) }).
  7. obj를 반환하라.

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%이다.
  • 일반 객체이다.
  • 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 프로토타입 객체로부터 속성을 상속하는 일반 객체이며 값이 undefined[[ErrorData]] 내부 슬롯을 가진다. [[ErrorData]]의 유일한 명시된 사용은 Object.prototype.toStringError.isError에서 Error, AggregateError, 또는 NativeError 인스턴스를 식별하는 것이다.

20.5.8 Error 객체들을 위한 추상 연산들

20.5.8.1 InstallErrorCause ( obj, options )

The abstract operation InstallErrorCause takes arguments obj (an Object) and options (an ECMAScript language value) and returns either a normal completion containing unused or a throw completion. 옵션 options"cause" 속성이 존재할 때 obj"cause" 속성을 생성하는 데 사용된다. It performs the following steps when called:

  1. 만약 options가 객체이고 ? HasProperty(options, "cause")가 true이면,
    1. cause를 ? Get(options, "cause")로 하자.
    2. Perform CreateNonEnumerableDataPropertyOrThrow(obj, "cause", cause).
  2. unused를 반환하라.

21 숫자와 날짜

21.1 Number 객체

21.1.1 Number 생성자

Number 생성자는:

  • is %Number%.
  • 전역 객체"Number" 속성의 초기값이다.
  • 생성자로 호출될 때 새로운 Number 객체를 생성하고 초기화한다.
  • 생성자가 아닌 함수로 호출될 때 타입 변환을 수행한다.
  • 클래스 정의의 extends 절의 값으로 사용될 수 있다. 지정된 Number 동작을 상속하려는 서브클래스 생성자는 서브클래스 인스턴스를 [[NumberData]] 내부 슬롯으로 생성하고 초기화하기 위해 Number 생성자에 대한 super 호출을 포함해야 한다.

21.1.1.1 Number ( value )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. If value is present, then
    1. Let prim be ? ToNumeric(value).
    2. If prim is a BigInt, let n be 𝔽((prim)).
    3. Else, let n be prim.
  2. Else,
    1. Let n be +0𝔽.
  3. If NewTarget is undefined, return n.
  4. Let obj be ? OrdinaryCreateFromConstructor(NewTarget, "%Number.prototype%", « [[NumberData]] »).
  5. Set obj.[[NumberData]] to n.
  6. Return obj.

21.1.2 Number 생성자의 속성

Number 생성자는:

  • 값이 %Function.prototype%[[Prototype]] 내부 슬롯을 가진다.
  • 다음 속성을 가진다:

21.1.2.1 Number.EPSILON

Number.EPSILON의 값은 1과 1보다 큰 Number 값 중 표현 가능한 가장 작은 값과 1 사이의 차이의 크기에 대한 Number 값이며, 대략 2.2204460492503130808472633361816 × 10-16이다.

이 속성의 속성값은 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }이다.

21.1.2.2 Number.isFinite ( number )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. If number is not a Number, return false.
  2. If number is not finite, return false.
  3. Return true.

21.1.2.3 Number.isInteger ( number )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. If number is an integral Number, return true.
  2. Return false.

21.1.2.4 Number.isNaN ( number )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. If number is not a Number, return false.
  2. If number is NaN, return true.
  3. Return false.
Note

이 함수는 전역 isNaN 함수 (19.2.3)와 다른데, 인수를 Number로 변환한 뒤에 NaN인지 판단하지 않는다는 점에서 다르다.

21.1.2.5 Number.isSafeInteger ( number )

Note

정수 n은 오직 그때에만 "안전 정수"이다: Number 값으로서의 n이 어떠한 다른 정수의 Number 값과도 같지 않을 때.

이 함수는 호출될 때 다음 단계를 수행한다:

  1. If number is an integral Number, then
    1. If abs((number)) ≤ 253 - 1, return true.
  2. Return 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 프로토타입 객체의 속성

Number 프로토타입 객체:

  • is %Number.prototype%.
  • 일반 객체(ordinary object)이다.
  • 자신이 Number 객체이며; [[NumberData]] 내부 슬롯의 값은 +0𝔽이다.
  • 값이 %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 )

이 메서드는 유효 숫자 부분의 소수점 앞에 한 자리 그리고 유효숫자 소수점 뒤에 fractionDigits 자리를 갖는 10진 지수 표기법으로 표현된 이 Number 값을 포함하는 문자열을 반환한다. 만약 fractionDigitsundefined이면, 필요한 만큼의 유효숫자 자릿수를 포함하여 Number를 고유하게 지정한다(이는 ToString과 유사하되, 이 경우 항상 지수 표기법으로 출력된다는 점이 다르다).

호출될 때 다음 단계를 수행한다:

  1. Let numberValue be ? ThisNumberValue(this value).
  2. Let fractionCount be ? ToIntegerOrInfinity(fractionDigits).
  3. Assert: If fractionDigits is undefined, then fractionCount is 0.
  4. If numberValue is not finite, return Number::toString(numberValue, 10).
  5. If fractionCount < 0 or fractionCount > 100, throw a RangeError exception.
  6. Set numberValue to (numberValue).
  7. Let sign be the empty String.
  8. If numberValue < 0, then
    1. Set sign to "-".
    2. Set numberValue to -numberValue.
  9. If numberValue = 0, then
    1. Let significand be the String value consisting of fractionCount + 1 occurrences of the code unit 0x0030 (DIGIT ZERO).
    2. Let exponent be 0.
  10. Else,
    1. If fractionDigits is not undefined, then
      1. Let exponent and intSignificand be integers such that 10fractionCountintSignificand < 10fractionCount + 1 and for which intSignificand × 10exponent - fractionCount - numberValue is as close to zero as possible. If there are two such sets of exponent and intSignificand, pick the exponent and intSignificand for which intSignificand × 10exponent - fractionCount is larger.
    2. Else,
      1. Let exponent, intSignificand, and ff be integers such that ff ≥ 0, 10ffintSignificand < 10ff + 1, 𝔽(intSignificand × 10exponent - ff) is 𝔽(numberValue), and ff is as small as possible. Note that the decimal representation of intSignificand has ff + 1 digits, intSignificand is not divisible by 10, and the least significant digit of intSignificand is not necessarily uniquely determined by these criteria.
      2. Set fractionCount to ff.
    3. Let significand be the String value consisting of the digits of the decimal representation of intSignificand (in order, with no leading zeroes).
  11. If fractionCount ≠ 0, then
    1. Let integerPart be the first code unit of significand.
    2. Let fractionalPart be the other fractionCount code units of significand.
    3. Set significand to the string-concatenation of integerPart, ".", and fractionalPart.
  12. If exponent = 0, then
    1. Let exponentSign be "+".
    2. Let exponentDigits be "0".
  13. Else,
    1. If exponent > 0, then
      1. Let exponentSign be "+".
    2. Else,
      1. Assert: exponent < 0.
      2. Let exponentSign be "-".
      3. Set exponent to -exponent.
    3. Let exponentDigits be the String value consisting of the digits of the decimal representation of exponent (in order, with no leading zeroes).
  14. Set significand to the string-concatenation of significand, "e", exponentSign, and exponentDigits.
  15. Return the string-concatenation of sign and significand.
Note

위 규칙보다 더 정확한 변환을 제공하는 구현체를 위해, 다음의 대체 버전의 단계 10.b.i를 지침으로 사용하는 것이 권장된다:

  1. Let exponent, intSignificand, and ff be integers such that ff ≥ 0, 10ffintSignificand < 10ff + 1, 𝔽(intSignificand × 10exponent - ff) is 𝔽(numberValue), and ff is as small as possible. If there are multiple possibilities for intSignificand, choose intSignificand such that 𝔽(intSignificand × 10exponent - ff) is closest to 𝔽(numberValue). If there are two such possible values of intSignificand, choose the one that is even.

21.1.3.3 Number.prototype.toFixed ( fractionDigits )

Note 1

이 메서드는 소수점 뒤에 fractionDigits 자리를 가지는 10진 고정 소수점 표기법으로 표현된 이 Number 값을 포함하는 문자열을 반환한다. 만약 fractionDigitsundefined이면 0으로 간주된다.

호출될 때 다음 단계를 수행한다:

  1. Let numberValue be ? ThisNumberValue(this value).
  2. Let fractionCount be ? ToIntegerOrInfinity(fractionDigits).
  3. Assert: If fractionDigits is undefined, then fractionCount is 0.
  4. If fractionCount is not finite, throw a RangeError exception.
  5. If fractionCount < 0 or fractionCount > 100, throw a RangeError exception.
  6. If numberValue is not finite, return Number::toString(numberValue, 10).
  7. Set numberValue to (numberValue).
  8. Let sign be the empty String.
  9. If numberValue < 0, then
    1. Set sign to "-".
    2. Set numberValue to -numberValue.
  10. If numberValue ≥ 1021, then
    1. Let digitString be ! ToString(𝔽(numberValue)).
  11. Else,
    1. Let intValue be an integer for which intValue / 10fractionCount - numberValue is as close to zero as possible. If there are two such intValue, pick the larger intValue.
    2. If intValue = 0, let digitString be "0"; else let digitString be the String value consisting of the digits of the decimal representation of intValue (in order, with no leading zeroes).
    3. If fractionCount ≠ 0, then
      1. Let digitCount be the length of digitString.
      2. If digitCountfractionCount, then
        1. Let zeroPad be the String value consisting of fractionCount + 1 - digitCount occurrences of the code unit 0x0030 (DIGIT ZERO).
        2. Set digitString to the string-concatenation of zeroPad and digitString.
        3. Set digitCount to fractionCount + 1.
      3. Let integerPart be the first digitCount - fractionCount code units of digitString.
      4. Let fractionalPart be the other fractionCount code units of digitString.
      5. Set digitString to the string-concatenation of integerPart, ".", and fractionalPart.
  12. Return the string-concatenation of sign and digitString.
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 값을 포맷한 문자열 값을 생성한다. 이 메서드는 구현체 정의(implementation-defined)이며, toString과 같은 값을 반환해도 허용되지만 권장되지는 않는다.

이 메서드의 선택적 매개변수 의미는 ECMA-402 명세에 정의되어 있다; ECMA-402를 포함하지 않는 구현체는 해당 매개변수 위치를 다른 용도로 사용해서는 안 된다.

21.1.3.5 Number.prototype.toPrecision ( precision )

이 메서드는 이 Number 값을 다음 중 하나로 표현한 문자열을 반환한다: 유효숫자 소수점 앞에 한 자리와 유효숫자 소수점 뒤에 precision - 1 자리를 갖는 10진 지수 표기법 또는 precision 유효숫자를 갖는 10진 고정 표기법. 만약 precisionundefined이면 ToString을 대신 호출한다.

호출될 때 다음 단계를 수행한다:

  1. Let numberValue be ? ThisNumberValue(this value).
  2. If precision is undefined, return ! ToString(numberValue).
  3. Let precisionCount be ? ToIntegerOrInfinity(precision).
  4. If numberValue is not finite, return Number::toString(numberValue, 10).
  5. If precisionCount < 1 or precisionCount > 100, throw a RangeError exception.
  6. Set numberValue to (numberValue).
  7. Let sign be the empty String.
  8. If numberValue < 0, then
    1. Set sign to the code unit 0x002D (HYPHEN-MINUS).
    2. Set numberValue to -numberValue.
  9. If numberValue = 0, then
    1. Let significand be the String value consisting of precisionCount occurrences of the code unit 0x0030 (DIGIT ZERO).
    2. Let exponent be 0.
  10. Else,
    1. Let exponent and intSignificand be integers such that 10precisionCount - 1intSignificand < 10precisionCount and for which intSignificand × 10exponent - precisionCount + 1 - numberValue is as close to zero as possible. If there are two such sets of exponent and intSignificand, pick the exponent and intSignificand for which intSignificand × 10exponent - precisionCount + 1 is larger.
    2. Let significand be the String value consisting of the digits of the decimal representation of intSignificand (in order, with no leading zeroes).
    3. If exponent < -6 or exponentprecisionCount, then
      1. Assert: exponent ≠ 0.
      2. If precisionCount ≠ 1, then
        1. Let integerPart be the first code unit of significand.
        2. Let fractionalPart be the other precisionCount - 1 code units of significand.
        3. Set significand to the string-concatenation of integerPart, ".", and fractionalPart.
      3. If exponent > 0, then
        1. Let exponentSign be the code unit 0x002B (PLUS SIGN).
      4. Else,
        1. Assert: exponent < 0.
        2. Let exponentSign be the code unit 0x002D (HYPHEN-MINUS).
        3. Set exponent to -exponent.
      5. Let exponentDigits be the String value consisting of the digits of the decimal representation of exponent (in order, with no leading zeroes).
      6. Return the string-concatenation of sign, significand, the code unit 0x0065 (LATIN SMALL LETTER E), exponentSign, and exponentDigits.
  11. If exponent = precisionCount - 1, return the string-concatenation of sign and significand.
  12. If exponent ≥ 0, then
    1. Set significand to the string-concatenation of the first exponent + 1 code units of significand, the code unit 0x002E (FULL STOP), and the remaining precisionCount - (exponent + 1) code units of significand.
  13. Else,
    1. Set significand to the string-concatenation of the code unit 0x0030 (DIGIT ZERO), the code unit 0x002E (FULL STOP), -(exponent + 1) occurrences of the code unit 0x0030 (DIGIT ZERO), and the String significand.
  14. Return the string-concatenation of sign and significand.

21.1.3.6 Number.prototype.toString ( [ radix ] )

Note

선택적 radix2𝔽에서 36𝔽포함 구간에 있는 정수 Number 값이어야 한다. 만약 radixundefined이면, radix의 값으로 10𝔽가 사용된다.

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. Let x be ? ThisNumberValue(this value).
  2. If radix is undefined, let radixMV be 10.
  3. Else, let radixMV be ? ToIntegerOrInfinity(radix).
  4. If radixMV is not in the inclusive interval from 2 to 36, throw a RangeError exception.
  5. Return Number::toString(x, radixMV).

이 메서드는 일반적이지 않다; this 값이 Number 또는 Number 객체가 아니면 TypeError 예외를 던진다. 따라서 다른 종류의 객체로 옮겨져 메서드로 사용할 수 없다.

이 메서드의 "length" 속성은 1𝔽이다.

21.1.3.7 Number.prototype.valueOf ( )

  1. Return ? ThisNumberValue(this value).

21.1.3.7.1 ThisNumberValue ( value )

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

  1. If value is a Number, return value.
  2. If value is an Object and value has a [[NumberData]] internal slot, then
    1. Let n be value.[[NumberData]].
    2. Assert: n is a Number.
    3. Return n.
  3. Throw a TypeError exception.

21.1.4 Number 인스턴스의 속성

Number 인스턴스는 Number 프로토타입 객체로부터 속성을 상속받는 일반 객체이다. Number 인스턴스는 또한 [[NumberData]] 내부 슬롯을 가진다. [[NumberData]] 내부 슬롯은 이 Number 객체가 나타내는 Number 값이다.

21.2 BigInt 객체

21.2.1 BigInt 생성자

BigInt 생성자는:

  • is %BigInt%.
  • 전역 객체"BigInt" 속성의 초기값이다.
  • 함수로 호출될 때 타입 변환을 수행한다 (생성자로 호출될 때는 아님).
  • new 연산자와 함께 사용되거나 서브클래싱하기 위한 용도는 아니다. 클래스 정의의 extends 절의 값으로 사용될 수 있으나, BigInt 생성자에 대한 super 호출은 예외를 발생시킬 것이다.

21.2.1.1 BigInt ( value )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. If NewTarget is not undefined, throw a TypeError exception.
  2. Let prim be ? ToPrimitive(value, number).
  3. If prim is a Number, return ? NumberToBigInt(prim).
  4. Return ? ToBigInt(prim).

21.2.1.1.1 NumberToBigInt ( number )

The abstract operation NumberToBigInt takes argument number (a Number) and returns either a normal completion containing a BigInt or a throw completion. It performs the following steps when called:

  1. If number is not an integral Number, throw a RangeError exception.
  2. Return ((number)).

21.2.2 BigInt 생성자의 속성

BigInt 생성자는:

  • 값이 %Function.prototype%[[Prototype]] 내부 슬롯을 가진다.
  • 다음 속성을 가진다:

21.2.2.1 BigInt.asIntN ( bits, bigint )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. Set bits to ? ToIndex(bits).
  2. Set bigint to ? ToBigInt(bigint).
  3. Let mod be (bigint) modulo 2bits.
  4. If mod ≥ 2bits - 1, return (mod - 2bits).
  5. Return (mod).

21.2.2.2 BigInt.asUintN ( bits, bigint )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. Set bits to ? ToIndex(bits).
  2. Set bigint to ? ToBigInt(bigint).
  3. Return ((bigint) modulo 2bits).

21.2.2.3 BigInt.prototype

BigInt.prototype의 초기값은 BigInt 프로토타입 객체이다.

이 속성의 속성값은 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }이다.

21.2.3 BigInt 프로토타입 객체의 속성

BigInt 프로토타입 객체:

  • is %BigInt.prototype%.
  • 일반 객체이다.
  • 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 값을 포맷한 문자열 값을 생성한다. 이 메서드는 구현체 정의이며, toString과 같은 값을 반환해도 허용되지만 권장되지는 않는다.

이 메서드의 선택적 매개변수 의미는 ECMA-402 명세에 정의되어 있다; ECMA-402를 포함하지 않는 구현체는 해당 매개변수 위치를 다른 용도로 사용해서는 안 된다.

21.2.3.3 BigInt.prototype.toString ( [ radix ] )

Note

선택적 radix2𝔽에서 36𝔽포함 구간에 있는 정수 Number 값이어야 한다. 만약 radixundefined이면, radix의 값으로 10𝔽가 사용된다.

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. Let x be ? ThisBigIntValue(this value).
  2. If radix is undefined, let radixMV be 10.
  3. Else, let radixMV be ? ToIntegerOrInfinity(radix).
  4. If radixMV is not in the inclusive interval from 2 to 36, throw a RangeError exception.
  5. Return BigInt::toString(x, radixMV).

이 메서드는 일반적이지 않다; this 값이 BigInt 또는 BigInt 객체가 아니면 TypeError 예외를 던진다. 따라서 다른 종류의 객체로 옮겨져 메서드로 사용할 수 없다.

21.2.3.4 BigInt.prototype.valueOf ( )

  1. Return ? ThisBigIntValue(this value).

21.2.3.4.1 ThisBigIntValue ( value )

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

  1. If value is a BigInt, return value.
  2. If value is an Object and value has a [[BigIntData]] internal slot, then
    1. Assert: value.[[BigIntData]] is a BigInt.
    2. Return value.[[BigIntData]].
  3. Throw a TypeError exception.

21.2.3.5 BigInt.prototype [ %Symbol.toStringTag% ]

%Symbol.toStringTag% 속성의 초기값은 문자열 값 "BigInt"이다.

이 속성의 속성값은 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }이다.

21.2.4 BigInt 인스턴스의 속성

BigInt 인스턴스는 BigInt 프로토타입 객체로부터 속성을 상속받는 일반 객체이다. BigInt 인스턴스는 또한 [[BigIntData]] 내부 슬롯을 가진다. [[BigIntData]] 내부 슬롯은 이 BigInt 객체가 나타내는 BigInt 값이다.

21.3 Math 객체

Math 객체는:

  • is %Math%.
  • 전역 객체"Math" 속성의 초기값이다.
  • 일반 객체이다.
  • 값이 %Object.prototype%[[Prototype]] 내부 슬롯을 가진다.
  • 함수 객체가 아니다.
  • [[Construct]] 내부 메서드를 가지지 않는다; new 연산자로 생성자로 사용될 수 없다.
  • [[Call]] 내부 메서드를 가지지 않는다; 함수로 호출될 수 없다.
Note

이 명세에서, “x에 대한 Number 값”이라는 구문은 6.1.6.1에 정의된 기술적 의미를 가진다.

21.3.1 Math 객체의 값 속성

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% 속성의 초기값은 문자열 값 "Math"이다.

이 속성의 속성값은 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }이다.

21.3.2 Math 객체의 함수 속성들

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. Let n be ? ToNumber(x).
  2. If n is NaN, return NaN.
  3. If n is -0𝔽, return +0𝔽.
  4. If n is -∞𝔽, return +∞𝔽.
  5. If n < -0𝔽, return -n.
  6. Return n.

21.3.2.2 Math.acos ( x )

이 함수는 x의 역코사인을 반환한다. 결과는 라디안으로 표현되며 +0𝔽에서 𝔽(π)까지의 포함 구간에 있다.

호출될 때 다음 단계를 수행한다:

  1. Let n be ? ToNumber(x).
  2. If n is NaN, n > 1𝔽, or n < -1𝔽, return NaN.
  3. If n is 1𝔽, return +0𝔽.
  4. Return an implementation-approximated Number value representing the inverse cosine of (n).

21.3.2.3 Math.acosh ( x )

이 함수는 x의 역쌍곡코사인을 반환한다.

호출될 때 다음 단계를 수행한다:

  1. Let n be ? ToNumber(x).
  2. If n is either NaN or +∞𝔽, return n.
  3. If n is 1𝔽, return +0𝔽.
  4. If n < 1𝔽, return NaN.
  5. Return an implementation-approximated Number value representing the inverse hyperbolic cosine of (n).

21.3.2.4 Math.asin ( x )

이 함수는 x의 역사인을 반환한다. 결과는 라디안으로 표현되며 𝔽(-π / 2)에서 𝔽(π / 2)까지의 포함 구간에 있다.

호출될 때 다음 단계를 수행한다:

  1. Let n be ? ToNumber(x).
  2. If n is one of NaN, +0𝔽, or -0𝔽, return n.
  3. If n > 1𝔽 or n < -1𝔽, return NaN.
  4. Return an implementation-approximated Number value representing the inverse sine of (n).

21.3.2.5 Math.asinh ( x )

이 함수는 x의 역쌍곡사인을 반환한다.

호출될 때 다음 단계를 수행한다:

  1. Let n be ? ToNumber(x).
  2. If n is not finite or n is either +0𝔽 or -0𝔽, return n.
  3. Return an implementation-approximated Number value representing the inverse hyperbolic sine of (n).

21.3.2.6 Math.atan ( x )

이 함수는 x의 역탄젠트를 반환한다. 결과는 라디안으로 표현되며 𝔽(-π / 2)에서 𝔽(π / 2)까지의 포함 구간에 있다.

호출될 때 다음 단계를 수행한다:

  1. Let n be ? ToNumber(x).
  2. If n is one of NaN, +0𝔽, or -0𝔽, return n.
  3. If n is +∞𝔽, return an implementation-approximated Number value representing π / 2.
  4. If n is -∞𝔽, return an implementation-approximated Number value representing -π / 2.
  5. Return an implementation-approximated Number value representing the inverse tangent of (n).

21.3.2.7 Math.atanh ( x )

이 함수는 x의 역쌍곡탄젠트를 반환한다.

호출될 때 다음 단계를 수행한다:

  1. Let n be ? ToNumber(x).
  2. If n is one of NaN, +0𝔽, or -0𝔽, return n.
  3. If n > 1𝔽 or n < -1𝔽, return NaN.
  4. If n is 1𝔽, return +∞𝔽.
  5. If n is -1𝔽, return -∞𝔽.
  6. Return an implementation-approximated Number value representing the inverse hyperbolic tangent of (n).

21.3.2.8 Math.atan2 ( y, x )

이 함수는 인수 yx의 몫 y / x의 역탄젠트를 반환한다. 결과의 사분면은 yx의 부호를 사용하여 결정된다. 두 인수를 취하는 역탄젠트 함수에서 인수 이름이 전통적으로 y가 먼저이고 x가 두번째인 것이 의도적이며 전통적이다. 결과는 -π에서 +π까지의 포함 구간으로 라디안으로 표현된다.

호출될 때 다음 단계를 수행한다:

  1. Let ny be ? ToNumber(y).
  2. Let nx be ? ToNumber(x).
  3. If ny is NaN or nx is NaN, return NaN.
  4. If ny is +∞𝔽, then
    1. If nx is +∞𝔽, return an implementation-approximated Number value representing π / 4.
    2. If nx is -∞𝔽, return an implementation-approximated Number value representing 3π / 4.
    3. Return an implementation-approximated Number value representing π / 2.
  5. If ny is -∞𝔽, then
    1. If nx is +∞𝔽, return an implementation-approximated Number value representing -π / 4.
    2. If nx is -∞𝔽, return an implementation-approximated Number value representing -3π / 4.
    3. Return an implementation-approximated Number value representing -π / 2.
  6. If ny is +0𝔽, then
    1. If nx > +0𝔽 or nx is +0𝔽, return +0𝔽.
    2. Return an implementation-approximated Number value representing π.
  7. If ny is -0𝔽, then
    1. If nx > +0𝔽 or nx is +0𝔽, return -0𝔽.
    2. Return an implementation-approximated Number value representing -π.
  8. Assert: ny is finite and is neither +0𝔽 nor -0𝔽.
  9. If ny > +0𝔽, then
    1. If nx is +∞𝔽, return +0𝔽.
    2. If nx is -∞𝔽, return an implementation-approximated Number value representing π.
    3. If nx is either +0𝔽 or -0𝔽, return an implementation-approximated Number value representing π / 2.
  10. If ny < -0𝔽, then
    1. If nx is +∞𝔽, return -0𝔽.
    2. If nx is -∞𝔽, return an implementation-approximated Number value representing -π.
    3. If nx is either +0𝔽 or -0𝔽, return an implementation-approximated Number value representing -π / 2.
  11. Assert: nx is finite and is neither +0𝔽 nor -0𝔽.
  12. Let r be the inverse tangent of abs((ny) / (nx)).
  13. If nx < -0𝔽, then
    1. If ny > +0𝔽, set r to π - r.
    2. Else, set r to -π + r.
  14. Else,
    1. If ny < -0𝔽, set r to -r.
  15. Return an implementation-approximated Number value representing r.

21.3.2.9 Math.cbrt ( x )

이 함수는 x의 세제곱근을 반환한다.

호출될 때 다음 단계를 수행한다:

  1. Let n be ? ToNumber(x).
  2. If n is not finite or n is either +0𝔽 or -0𝔽, return n.
  3. Return an implementation-approximated Number value representing the cube root of (n).

21.3.2.10 Math.ceil ( x )

이 함수는 x보다 작지 않은 가장 작은(−∞에 가장 가까운) 정수 Number 값을 반환한다. 만약 x가 이미 정수 Number이면 결과는 x이다.

호출될 때 다음 단계를 수행한다:

  1. Let n be ? ToNumber(x).
  2. If n is not finite or n is either +0𝔽 or -0𝔽, return n.
  3. If n < -0𝔽 and n > -1𝔽, return -0𝔽.
  4. If n is an integral Number, return n.
  5. Return the smallest (closest to -∞) integral Number value that is not less than n.
Note

Math.ceil(x)의 값은 -Math.floor(-x)의 값과 같다.

21.3.2.11 Math.clz32 ( x )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. Let n be ? ToUint32(x).
  2. Let p be the number of leading zero bits in the unsigned 32-bit binary representation of n.
  3. Return 𝔽(p).
Note

만약 n+0𝔽 또는 -0𝔽이면, 이 메서드는 32𝔽를 반환한다. 32비트 이진 인코딩에서 최상위 비트가 1이면 이 메서드는 +0𝔽를 반환한다.

21.3.2.12 Math.cos ( x )

이 함수는 x의 코사인을 반환한다. 인수는 라디안으로 표현된다.

호출될 때 다음 단계를 수행한다:

  1. Let n be ? ToNumber(x).
  2. If n is not finite, return NaN.
  3. If n is either +0𝔽 or -0𝔽, return 1𝔽.
  4. Return an implementation-approximated Number value representing the cosine of (n).

21.3.2.13 Math.cosh ( x )

이 함수는 x의 쌍곡코사인을 반환한다.

호출될 때 다음 단계를 수행한다:

  1. Let n be ? ToNumber(x).
  2. If n is NaN, return NaN.
  3. If n is either +∞𝔽 or -∞𝔽, return +∞𝔽.
  4. If n is either +0𝔽 or -0𝔽, return 1𝔽.
  5. Return an implementation-approximated Number value representing the hyperbolic cosine of (n).
Note

Math.cosh(x)의 값은 (Math.exp(x) + Math.exp(-x)) / 2의 값과 같다.

21.3.2.14 Math.exp ( x )

이 함수는 x의 지수 함수(ex, 여기서 e는 자연로그의 밑)의 값을 반환한다.

호출될 때 다음 단계를 수행한다:

  1. Let n be ? ToNumber(x).
  2. If n is either NaN or +∞𝔽, return n.
  3. If n is either +0𝔽 or -0𝔽, return 1𝔽.
  4. If n is -∞𝔽, return +0𝔽.
  5. Return an implementation-approximated Number value representing the exponential function of (n).

21.3.2.15 Math.expm1 ( x )

이 함수는 ex에서 1을 뺀 결과를 반환한다. 결과는 x 값이 0에 가깝더라도 정확하도록 계산된다.

호출될 때 다음 단계를 수행한다:

  1. Let n be ? ToNumber(x).
  2. If n is one of NaN, +0𝔽, -0𝔽, or +∞𝔽, return n.
  3. If n is -∞𝔽, return -1𝔽.
  4. Let exp be the exponential function of (n).
  5. Return an implementation-approximated Number value representing exp - 1.

21.3.2.16 Math.floor ( x )

이 함수는 x보다 크지 않은 가장 큰( +∞에 가장 가까운) 정수 Number 값을 반환한다. 만약 x가 이미 정수 Number이면 결과는 x이다.

호출될 때 다음 단계를 수행한다:

  1. Let n be ? ToNumber(x).
  2. If n is not finite or n is either +0𝔽 or -0𝔽, return n.
  3. If n < 1𝔽 and n > +0𝔽, return +0𝔽.
  4. If n is an integral Number, return n.
  5. Return the greatest (closest to +∞) integral Number value that is not greater than n.
Note

Math.floor(x)의 값은 -Math.ceil(-x)의 값과 같다.

21.3.2.17 Math.fround ( x )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. Let n be ? ToNumber(x).
  2. If n is NaN, return NaN.
  3. If n is one of +0𝔽, -0𝔽, +∞𝔽, or -∞𝔽, return n.
  4. Let n32 be the result of converting n to IEEE 754-2019 binary32 format using roundTiesToEven mode.
  5. Let n64 be the result of converting n32 to IEEE 754-2019 binary64 format.
  6. Return the ECMAScript Number value corresponding to n64.

21.3.2.18 Math.f16round ( x )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. Let n be ? ToNumber(x).
  2. If n is NaN, return NaN.
  3. If n is one of +0𝔽, -0𝔽, +∞𝔽, or -∞𝔽, return n.
  4. Let n16 be the result of converting n to IEEE 754-2019 binary16 format using roundTiesToEven mode.
  5. Let n64 be the result of converting n16 to IEEE 754-2019 binary64 format.
  6. Return the ECMAScript Number value corresponding to n64.
Note

이 연산은 binary32로 캐스팅한 다음 binary16으로 캐스팅하는 것과 같지 않다(이중 반올림의 가능성 때문에): 예를 들어 k = 1.00048828125000022204𝔽에 대해 Math.f16round(k)는 1.0009765625𝔽이고, Math.f16round(Math.fround(k))는 1𝔽이다.

모든 플랫폼이 binary64에서 binary16으로의 네이티브 캐스팅을 제공하지는 않는다. 이를 제공할 수 있는 라이브러리들이 있으며, MIT 라이선스의 half 라이브러리가 그 예다. 또는 먼저 binary64를 roundTiesToEven 모드로 binary32로 캐스트한 다음, 결과가 잘못된 이중 반올림을 초래할 수 있는지 확인하고, 그런 경우에는 명시적으로 이들을 처리하여 올바른 결과가 나오도록 할 수 있다.

21.3.2.19 Math.hypot ( ...args )

0개 이상의 인수가 주어지면, 이 함수는 인수들의 제곱합의 제곱근을 반환한다.

호출될 때 다음 단계를 수행한다:

  1. Let coerced be a new empty List.
  2. For each element arg of args, do
    1. Let n be ? ToNumber(arg).
    2. Append n to coerced.
  3. For each element number of coerced, do
    1. If number is either +∞𝔽 or -∞𝔽, return +∞𝔽.
  4. Let onlyZero be true.
  5. For each element number of coerced, do
    1. If number is NaN, return NaN.
    2. If number is neither +0𝔽 nor -0𝔽, set onlyZero to false.
  6. If onlyZero is true, return +0𝔽.
  7. Return an implementation-approximated Number value representing the square root of the sum of squares of the mathematical values of the elements of coerced.

이 함수의 "length" 속성은 2𝔽이다.

Note

구현체는 이 함수가 두 개 이상의 인수와 함께 호출될 때 발생하기 쉬운 오버플로우와 언더플로우로 인한 정밀도 손실을 피하기 위해 주의해야 한다.

21.3.2.20 Math.imul ( x, y )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. Let a be (? ToUint32(x)).
  2. Let b be (? ToUint32(y)).
  3. Let product be (a × b) modulo 232.
  4. If product ≥ 231, return 𝔽(product - 232).
  5. Return 𝔽(product).

21.3.2.21 Math.log ( x )

이 함수는 x의 자연로그를 반환한다.

호출될 때 다음 단계를 수행한다:

  1. Let n be ? ToNumber(x).
  2. If n is either NaN or +∞𝔽, return n.
  3. If n is 1𝔽, return +0𝔽.
  4. If n is either +0𝔽 or -0𝔽, return -∞𝔽.
  5. If n < -0𝔽, return NaN.
  6. Return an implementation-approximated Number value representing ln((n)).

21.3.2.22 Math.log1p ( x )

이 함수는 1 + x의 자연로그를 반환한다. 결과는 x 값이 0에 가까울 때도 정확하도록 계산된다.

호출될 때 다음 단계를 수행한다:

  1. Let n be ? ToNumber(x).
  2. If n is one of NaN, +0𝔽, -0𝔽, or +∞𝔽, return n.
  3. If n is -1𝔽, return -∞𝔽.
  4. If n < -1𝔽, return NaN.
  5. Return an implementation-approximated Number value representing ln(1 + (n)).

21.3.2.23 Math.log10 ( x )

이 함수는 x의 상용로그(밑10)를 반환한다.

호출될 때 다음 단계를 수행한다:

  1. Let n be ? ToNumber(x).
  2. If n is either NaN or +∞𝔽, return n.
  3. If n is 1𝔽, return +0𝔽.
  4. If n is either +0𝔽 or -0𝔽, return -∞𝔽.
  5. If n < -0𝔽, return NaN.
  6. Return an implementation-approximated Number value representing log10((n)).

21.3.2.24 Math.log2 ( x )

이 함수는 x의 밑2 로그를 반환한다.

호출될 때 다음 단계를 수행한다:

  1. Let n be ? ToNumber(x).
  2. If n is either NaN or +∞𝔽, return n.
  3. If n is 1𝔽, return +0𝔽.
  4. If n is either +0𝔽 or -0𝔽, return -∞𝔽.
  5. If n < -0𝔽, return NaN.
  6. Return an implementation-approximated Number value representing log2((n)).

21.3.2.25 Math.max ( ...args )

0개 이상의 인수가 주어지면, 이 함수는 각 인수에 ToNumber를 호출하고 그 결과 값들 중 가장 큰 값을 반환한다.

호출될 때 다음 단계를 수행한다:

  1. Let coerced be a new empty List.
  2. For each element arg of args, do
    1. Let n be ? ToNumber(arg).
    2. Append n to coerced.
  3. Let highest be -∞𝔽.
  4. For each element number of coerced, do
    1. If number is NaN, return NaN.
    2. If number is +0𝔽 and highest is -0𝔽, set highest to +0𝔽.
    3. If number > highest, set highest to number.
  5. Return highest.
Note

가장 큰 값을 결정하기 위한 비교는 IsLessThan 알고리즘을 사용하되 +0𝔽-0𝔽보다 크다고 간주한다.

이 함수의 "length" 속성은 2𝔽이다.

21.3.2.26 Math.min ( ...args )

0개 이상의 인수가 주어지면, 이 함수는 각 인수에 ToNumber를 호출하고 그 결과 값들 중 가장 작은 값을 반환한다.

호출될 때 다음 단계를 수행한다:

  1. Let coerced be a new empty List.
  2. For each element arg of args, do
    1. Let n be ? ToNumber(arg).
    2. Append n to coerced.
  3. Let lowest be +∞𝔽.
  4. For each element number of coerced, do
    1. If number is NaN, return NaN.
    2. If number is -0𝔽 and lowest is +0𝔽, set lowest to -0𝔽.
    3. If number < lowest, set lowest to number.
  5. Return lowest.
Note

가장 작은 값을 결정하기 위한 비교는 IsLessThan 알고리즘을 사용하되 +0𝔽-0𝔽보다 크다고 간주한다.

이 함수의 "length" 속성은 2𝔽이다.

21.3.2.27 Math.pow ( base, exponent )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. Set base to ? ToNumber(base).
  2. Set exponent to ? ToNumber(exponent).
  3. Return 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에 대해 동일하게 가깝다면, 결과는 +∞에 더 가까운 Number 값이다. 만약 x가 이미 정수이면 결과는 x이다.

호출될 때 다음 단계를 수행한다:

  1. Let n be ? ToNumber(x).
  2. If n is not finite or n is an integral Number, return n.
  3. If n < 0.5𝔽 and n > +0𝔽, return +0𝔽.
  4. If n < -0𝔽 and n-0.5𝔽, return -0𝔽.
  5. Return the integral Number closest to n, preferring the Number closer to +∞ in the case of a tie.
Note 1

Math.round(3.5)는 4를 반환하지만 Math.round(-3.5)는 -3을 반환한다.

Note 2

Math.round(x)의 값이 항상 Math.floor(x + 0.5)의 값과 같은 것은 아니다. x-0𝔽이거나 x-0𝔽보다 작지만 -0.5𝔽 이상이면, Math.round(x)-0𝔽를 반환하지만, Math.floor(x + 0.5)+0𝔽를 반환한다. 또한 Math.round(x)x + 0.5를 계산할 때의 내부 rounding 때문에 Math.floor(x + 0.5)의 값과 다를 수 있다.

21.3.2.30 Math.sign ( x )

이 함수는 x의 부호를 반환하여 x가 양수인지 음수인지 또는 0인지 나타낸다.

호출될 때 다음 단계를 수행한다:

  1. Let n be ? ToNumber(x).
  2. If n is one of NaN, +0𝔽, or -0𝔽, return n.
  3. If n < -0𝔽, return -1𝔽.
  4. Return 1𝔽.

21.3.2.31 Math.sin ( x )

이 함수는 x의 사인을 반환한다. 인수는 라디안으로 표현된다.

호출될 때 다음 단계를 수행한다:

  1. Let n be ? ToNumber(x).
  2. If n is one of NaN, +0𝔽, or -0𝔽, return n.
  3. If n is either +∞𝔽 or -∞𝔽, return NaN.
  4. Return an implementation-approximated Number value representing the sine of (n).

21.3.2.32 Math.sinh ( x )

이 함수는 x의 쌍곡사인을 반환한다.

호출될 때 다음 단계를 수행한다:

  1. Let n be ? ToNumber(x).
  2. If n is not finite or n is either +0𝔽 or -0𝔽, return n.
  3. Return an implementation-approximated Number value representing the hyperbolic sine of (n).
Note

Math.sinh(x)의 값은 (Math.exp(x) - Math.exp(-x)) / 2의 값과 같다.

21.3.2.33 Math.sqrt ( x )

이 함수는 x의 제곱근을 반환한다.

호출될 때 다음 단계를 수행한다:

  1. Let n be ? ToNumber(x).
  2. If n is one of NaN, +0𝔽, -0𝔽, or +∞𝔽, return n.
  3. If n < -0𝔽, return NaN.
  4. Return 𝔽(the square root of (n)).

21.3.2.34 Math.sumPrecise ( items )

숫자들의 iterable이 주어지면, 이 함수는 iterable의 각 값을 합산하여 그 합을 반환한다. 만약 어떤 값이 Number가 아니면 TypeError 예외를 던진다.

호출될 때 다음 단계를 수행한다:

  1. Perform ? RequireObjectCoercible(items).
  2. Let iteratorRecord be ? GetIterator(items, sync).
  3. Let state be minus-zero.
  4. Let sum be 0.
  5. Let count be 0.
  6. Let next be not-started.
  7. Repeat, while next is not done,
    1. Set next to ? IteratorStepValue(iteratorRecord).
    2. If next is not done, then
      1. If count ≥ 253 - 1, then
        1. NOTE: This step is not expected to be reached in practice and is included only so that implementations may rely on inputs being "reasonably sized" without violating this specification.
        2. Let error be ThrowCompletion(a newly created RangeError object).
        3. Return ? IteratorClose(iteratorRecord, error).
      2. If next is not a Number, then
        1. Let error be ThrowCompletion(a newly created TypeError object).
        2. Return ? IteratorClose(iteratorRecord, error).
      3. Let n be next.
      4. If state is not not-a-number, then
        1. If n is NaN, then
          1. Set state to not-a-number.
        2. Else if n is +∞𝔽, then
          1. If state is minus-infinity, set state to not-a-number.
          2. Else, set state to plus-infinity.
        3. Else if n is -∞𝔽, then
          1. If state is plus-infinity, set state to not-a-number.
          2. Else, set state to minus-infinity.
        4. Else if n is not -0𝔽 and state is either minus-zero or finite, then
          1. Set state to finite.
          2. Set sum to sum + (n).
      5. Set count to count + 1.
  8. If state is not-a-number, return NaN.
  9. If state is plus-infinity, return +∞𝔽.
  10. If state is minus-infinity, return -∞𝔽.
  11. If state is minus-zero, return -0𝔽.
  12. Return 𝔽(sum).
Note

sum의 값은 임의 정밀도 산술 없이 다양한 알고리즘으로 계산할 수 있다. 한 가지는 Jonathan Richard Shewchuk의 "Grow-Expansion" 알고리즘이다. 보다 최근 알고리즘은 "Fast exact summation using small and large superaccumulators"이며, 코드가 https://gitlab.com/radfordneal/xsum에 있다.

21.3.2.35 Math.tan ( x )

이 함수는 x의 탄젠트를 반환한다. 인수는 라디안으로 표현된다.

호출될 때 다음 단계를 수행한다:

  1. Let n be ? ToNumber(x).
  2. If n is one of NaN, +0𝔽, or -0𝔽, return n.
  3. If n is either +∞𝔽 or -∞𝔽, return NaN.
  4. Return an implementation-approximated Number value representing the tangent of (n).

21.3.2.36 Math.tanh ( x )

이 함수는 x의 쌍곡탄젠트를 반환한다.

호출될 때 다음 단계를 수행한다:

  1. Let n be ? ToNumber(x).
  2. If n is one of NaN, +0𝔽, or -0𝔽, return n.
  3. If n is +∞𝔽, return 1𝔽.
  4. If n is -∞𝔽, return -1𝔽.
  5. Return an implementation-approximated Number value representing the hyperbolic tangent of (n).
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. Let n be ? ToNumber(x).
  2. If n is not finite or n is either +0𝔽 or -0𝔽, return n.
  3. If n < 1𝔽 and n > +0𝔽, return +0𝔽.
  4. If n < -0𝔽 and n > -1𝔽, return -0𝔽.
  5. Return the integral Number nearest n in the direction of +0𝔽.

21.4 Date 객체

21.4.1 Date 객체 개요 및 추상 연산 정의

다음의 추상 연산들은 시간 값들( 21.4.1.1에 정의됨 )에 대해 동작한다. 모든 경우에, 이러한 함수들의 어떤 인수가 NaN이면 결과는 NaN이 된다는 점에 유의하라.

21.4.1.1 시간 값들과 시간 범위

ECMAScript에서 시간 측정은 POSIX의 시간 측정과 유사하며, 특히 윤년 규칙을 사용하는 보정된 필요(프로레프틱) 그레고리력, 에포크(epoch)로 UTC 1970년 1월 1일 자정의 정의, 그리고 하루를 정확히 86,400초(각각 1000밀리초)로 계산하는 것을 공유한다.

ECMAScript에서 시간 값(time value)은 Number이다. 이는 밀리초 정밀도의 순간을 나타내는 유한정수 Number이거나 특정 순간을 나타내지 않는 NaN이다. 만약 시간 값이 24 × 60 × 60 × 1000 = 86,400,000의 배수(즉 86,400,000 × d 꼴의 정수 d)이면, 이는 에포크 이후 정수 d일의 시작에 해당하는 UTC 날짜의 순간을 나타낸다(음수 d의 경우 에포크보다 이전). 그 외의 모든 유한 시간 값 t는 그러한 배수인 가장 큰 이전의 시간 값 s에 대해 정의되며, 같은 UTC 날에 속하고 s 다음으로 (t - s) 밀리초만큼 뒤에 발생하는 순간을 나타낸다.

시간 값들은 UTC 윤초(leap seconds)를 고려하지 않는다—양의 윤초 안에 있는 순간을 나타내는 시간 값은 없고, 음의 윤초로 인해 UTC 타임라인에서 제거된 순간을 나타내는 시간 값은 존재할 수 있다. 하지만 시간 값의 정의는 윤초 경계에서만 불연속성을 갖고 윤초 밖에서는 차이가 0이므로 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까지를 지원한다. 이는 에포크를 기준으로 정확히 -100,000,000일에서 100,000,000일까지의 지원 시간 값 범위를 제공한다.

1970년 1월 1일 자정의 정확한 순간은 시간 값 +0𝔽으로 표현된다.

Note

프로레프틱 그레고리력에서 윤년은 정확히 4로 나누어떨어지고 또한 400으로 나누어떨어지거나 100으로 나누어떨어지지 않는 해들이다.

400년 주기에는 97개의 윤년이 있다. 이는 연평균 365.2425일, 즉 31,556,952,000밀리초를 낳는다. 따라서 Number가 밀리초 정밀도로 정확히 표현할 수 있는 최대 범위는 대략 1970년을 기준으로 -285,426년에서 285,426년이다. 이 절에서 지정한 시간 값의 더 작은 범위는 약 1970년을 기준으로 -273,790년에서 273,790년이다.

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 (a finite time value) and returns an integral Number. 이는 t가 속하는 날의 일 번호를 반환한다. It performs the following steps when called:

  1. Return 𝔽(floor((t / msPerDay))).

21.4.1.4 TimeWithinDay ( t )

The abstract operation TimeWithinDay takes argument t (a finite time value) and returns an integral Number in the interval from +0𝔽 (inclusive) to msPerDay (exclusive). 이는 t가 속하는 날의 시작 이후 경과한 밀리초 수를 반환한다. It performs the following steps when called:

  1. Return 𝔽((t) modulo (msPerDay)).

21.4.1.5 DaysInYear ( y )

The abstract operation DaysInYear takes argument y (an integral Number) and returns 365𝔽 or 366𝔽. 이는 연도 y의 일 수를 반환한다. 윤년은 366일이고, 그 외의 해는 365일이다. It performs the following steps when called:

  1. Let ry be (y).
  2. If (ry modulo 400) = 0, return 366𝔽.
  3. If (ry modulo 100) = 0, return 365𝔽.
  4. If (ry modulo 4) = 0, return 366𝔽.
  5. Return 365𝔽.

21.4.1.6 DayFromYear ( y )

The abstract operation DayFromYear takes argument y (an integral Number) and returns an integral Number. 이는 연도 y의 첫날의 일 번호를 반환한다. It performs the following steps when called:

  1. Let ry be (y).
  2. NOTE: In the following steps, numYears1, numYears4, numYears100, and numYears400 represent the number of years divisible by 1, 4, 100, and 400, respectively, that occur between the epoch and the start of year y. The number is negative if y is before the epoch.
  3. Let numYears1 be (ry - 1970).
  4. Let numYears4 be floor((ry - 1969) / 4).
  5. Let numYears100 be floor((ry - 1901) / 100).
  6. Let numYears400 be floor((ry - 1601) / 400).
  7. Return 𝔽(365 × numYears1 + numYears4 - numYears100 + numYears400).

21.4.1.7 TimeFromYear ( y )

The abstract operation TimeFromYear takes argument y (an integral Number) and returns a time value. 이는 연도 y의 시작 시각의 시간 값을 반환한다. It performs the following steps when called:

  1. Return msPerDay × DayFromYear(y).

21.4.1.8 YearFromTime ( t )

The abstract operation YearFromTime takes argument t (a finite time value) and returns an integral Number. 이는 t가 속하는 연도를 반환한다. It performs the following steps when called:

  1. Return the largest integral Number y (closest to +∞) such that TimeFromYear(y) ≤ t.

21.4.1.9 DayWithinYear ( t )

The abstract operation DayWithinYear takes argument t (a finite time value) and returns an integral Number in the inclusive interval from +0𝔽 to 365𝔽. It performs the following steps when called:

  1. Return Day(t) - DayFromYear(YearFromTime(t)).

21.4.1.10 InLeapYear ( t )

The abstract operation InLeapYear takes argument t (a finite time value) and returns +0𝔽 or 1𝔽. 이는 t가 윤년 내에 있으면 1𝔽을, 그렇지 않으면 +0𝔽을 반환한다. It performs the following steps when called:

  1. If DaysInYear(YearFromTime(t)) is 366𝔽, return 1𝔽.
  2. Return +0𝔽.

21.4.1.11 MonthFromTime ( t )

The abstract operation MonthFromTime takes argument t (a finite time value) and returns an integral Number in the inclusive interval from +0𝔽 to 11𝔽. 이는 t가 속하는 달을 식별하는 Number를 반환한다. 달 값 +0𝔽는 1월, 1𝔽는 2월, ..., 11𝔽는 12월을 지정한다. 참고로 MonthFromTime(+0𝔽) = +0𝔽는 1970년 1월 1일 목요일에 해당한다. It performs the following steps when called:

  1. Let inLeapYear be InLeapYear(t).
  2. Let dayWithinYear be DayWithinYear(t).
  3. If dayWithinYear < 31𝔽, return +0𝔽.
  4. If dayWithinYear < 59𝔽 + inLeapYear, return 1𝔽.
  5. If dayWithinYear < 90𝔽 + inLeapYear, return 2𝔽.
  6. If dayWithinYear < 120𝔽 + inLeapYear, return 3𝔽.
  7. If dayWithinYear < 151𝔽 + inLeapYear, return 4𝔽.
  8. If dayWithinYear < 181𝔽 + inLeapYear, return 5𝔽.
  9. If dayWithinYear < 212𝔽 + inLeapYear, return 6𝔽.
  10. If dayWithinYear < 243𝔽 + inLeapYear, return 7𝔽.
  11. If dayWithinYear < 273𝔽 + inLeapYear, return 8𝔽.
  12. If dayWithinYear < 304𝔽 + inLeapYear, return 9𝔽.
  13. If dayWithinYear < 334𝔽 + inLeapYear, return 10𝔽.
  14. Assert: dayWithinYear < 365𝔽 + inLeapYear.
  15. Return 11𝔽.

21.4.1.12 DateFromTime ( t )

The abstract operation DateFromTime takes argument t (a finite time value) and returns an integral Number in the inclusive interval from 1𝔽 to 31𝔽. 이는 t가 속하는 달의 날짜(일)를 반환한다. It performs the following steps when called:

  1. Let inLeapYear be InLeapYear(t).
  2. Let dayWithinYear be DayWithinYear(t).
  3. Let month be MonthFromTime(t).
  4. If month is +0𝔽, return dayWithinYear + 1𝔽.
  5. If month is 1𝔽, return dayWithinYear - 30𝔽.
  6. If month is 2𝔽, return dayWithinYear - 58𝔽 - inLeapYear.
  7. If month is 3𝔽, return dayWithinYear - 89𝔽 - inLeapYear.
  8. If month is 4𝔽, return dayWithinYear - 119𝔽 - inLeapYear.
  9. If month is 5𝔽, return dayWithinYear - 150𝔽 - inLeapYear.
  10. If month is 6𝔽, return dayWithinYear - 180𝔽 - inLeapYear.
  11. If month is 7𝔽, return dayWithinYear - 211𝔽 - inLeapYear.
  12. If month is 8𝔽, return dayWithinYear - 242𝔽 - inLeapYear.
  13. If month is 9𝔽, return dayWithinYear - 272𝔽 - inLeapYear.
  14. If month is 10𝔽, return dayWithinYear - 303𝔽 - inLeapYear.
  15. Assert: month is 11𝔽.
  16. Return dayWithinYear - 333𝔽 - inLeapYear.

21.4.1.13 WeekDay ( t )

The abstract operation WeekDay takes argument t (a finite time value) and returns an integral Number in the inclusive interval from +0𝔽 to 6𝔽. 이는 t가 속하는 요일을 식별하는 Number를 반환한다. 요일 값 +0𝔽는 일요일, 1𝔽는 월요일, ..., 6𝔽는 토요일을 지정한다. 참고로 WeekDay(+0𝔽) = 4𝔽는 1970년 1월 1일 목요일에 해당한다. It performs the following steps when called:

  1. Return 𝔽((Day(t) + 4𝔽) modulo 7).

21.4.1.14 HourFromTime ( t )

The abstract operation HourFromTime takes argument t (a finite time value) and returns an integral Number in the inclusive interval from +0𝔽 to 23𝔽. 이는 t가 속하는 시간(시)을 반환한다. It performs the following steps when called:

  1. Return 𝔽(floor((t / msPerHour)) modulo HoursPerDay).

21.4.1.15 MinFromTime ( t )

The abstract operation MinFromTime takes argument t (a finite time value) and returns an integral Number in the inclusive interval from +0𝔽 to 59𝔽. 이는 t가 속하는 분(minutes)을 반환한다. It performs the following steps when called:

  1. Return 𝔽(floor((t / msPerMinute)) modulo MinutesPerHour).

21.4.1.16 SecFromTime ( t )

The abstract operation SecFromTime takes argument t (a finite time value) and returns an integral Number in the inclusive interval from +0𝔽 to 59𝔽. 이는 t가 속하는 초(seconds)를 반환한다. It performs the following steps when called:

  1. Return 𝔽(floor((t / msPerSecond)) modulo SecondsPerMinute).

21.4.1.17 msFromTime ( t )

The abstract operation msFromTime takes argument t (a finite time value) and returns an integral Number in the inclusive interval from +0𝔽 to 999𝔽. 이는 t가 속하는 초의 밀리초 부분을 반환한다. It performs the following steps when called:

  1. Return 𝔽((t) modulo (msPerSecond)).

21.4.1.18 GetUTCEpochNanoseconds ( year, month, day, hour, minute, second, millisecond, microsecond, nanosecond )

The abstract operation GetUTCEpochNanoseconds takes arguments year (an integer), month (an integer in the inclusive interval from 1 to 12), day (an integer in the inclusive interval from 1 to 31), hour (an integer in the inclusive interval from 0 to 23), minute (an integer in the inclusive interval from 0 to 59), second (an integer in the inclusive interval from 0 to 59), millisecond (an integer in the inclusive interval from 0 to 999), microsecond (an integer in the inclusive interval from 0 to 999), and nanosecond (an integer in the inclusive interval from 0 to 999) and returns a BigInt. 반환 값은 주어진 ISO 8601 달력 날짜와 UTC의 벽 시계(wall-clock) 시각에 대응하는 에포크 이후의 나노초 수를 나타내는 BigInt이다. It performs the following steps when called:

  1. Let date be MakeDay(𝔽(year), 𝔽(month - 1), 𝔽(day)).
  2. Let time be MakeTime(𝔽(hour), 𝔽(minute), 𝔽(second), 𝔽(millisecond)).
  3. Let ms be MakeDate(date, time).
  4. Assert: ms is an integral Number.
  5. Return ((ms) × 106 + microsecond × 103 + nanosecond).

21.4.1.19 표준시(타임존) 식별자

ECMAScript에서 표준시(time zones)는 0x0000에서 0x007F 범위의 코드 유닛들로만 구성된 문자열인 타임존 식별자로 표현된다. 구현체가 지원하는 타임존은 사용 가능한 명명된 타임존(available named time zones) 또는 오프셋 타임존(offset time zones)일 수 있다. 오프셋 타임존은 IsTimeZoneOffsetString이 참을 반환하는 문자열로 표현된다.

주요(Primary) 타임존 식별자는 사용 가능한 명명된 타임존에 대한 선호 식별자이다. 비주요(Non-primary) 타임존 식별자는 주요 식별자가 아닌 사용 가능한 명명된 타임존의 식별자이다. 사용 가능한 명명된 타임존 식별자은 주요 식별자 또는 비주요 식별자이다. 각각의 사용 가능한 명명된 타임존 식별자는 정확히 하나의 사용 가능한 명명된 타임존과 연관된다. 각각의 사용 가능한 명명된 타임존은 정확히 하나의 주요 타임존 식별자와 0개 이상의 비주요 타임존 식별자와 연관된다.

ECMAScript 구현체는 식별자 "UTC"인 사용 가능한 명명된 타임존을 반드시 지원해야 하며, 이는 UTC 타임존의 주요 타임존 식별자여야 한다. 추가로, 구현체는 다른 많은 사용 가능한 명명된 타임존을 지원할 수 있다.

ECMA-402 국제화 API 요구사항을 따르는 구현체는 타임존 인식(time zone aware)이라고 불린다. 타임존 인식 구현체는 IANA 타임존 데이터베이스의 Zone 및 Link 이름에 해당하는 사용 가능한 명명된 타임존들을 지원해야 하며, 그 외의 이름을 지원해서는 안 된다. 타임존 인식 구현체에서 주요 타임존 식별자는 IANA Time Zone Database의 Zone 이름이고, 비주요 식별자는 Link 이름이다(ECMA-402 명세에서 AvailableNamedTimeZoneIdentifiers로 구체적으로 재정의되지 않는 한). 전체 IANA 타임존 데이터베이스를 지원하지 않는 구현체라도 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 (a String), year (an integer), month (an integer in the inclusive interval from 1 to 12), day (an integer in the inclusive interval from 1 to 31), hour (an integer in the inclusive interval from 0 to 23), minute (an integer in the inclusive interval from 0 to 59), second (an integer in the inclusive interval from 0 to 59), millisecond (an integer in the inclusive interval from 0 to 999), microsecond (an integer in the inclusive interval from 0 to 999), and nanosecond (an integer in the inclusive interval from 0 to 999) and returns a List of BigInts. 반환되는 리스트의 각 값은 주어진 ISO 8601 달력 날짜와 명명된 타임존 timeZoneIdentifier에 해당하는 벽 시계 시각에 대응하는 에포크 이후의 나노초 수를 나타낸다.

입력이 음의 타임존 전환(예: 서머타임 종료로 시간이 반복되거나 타임존 규칙 변경으로 오프셋이 감소하는 경우)으로 인해 두 번 발생하는 지역 시간일 때, 반환 리스트는 두 개 이상의 요소를 가지며 오름차순으로 정렬된다. 입력이 양의 타임존 전환(예: 서머타임 시작으로 시간이 건너뛰어지거나 타임존 규칙 변경으로 오프셋이 증가하는 경우)으로 인해 건너뛰어진 지역 시간이라면, 반환 리스트는 비어있다. 그렇지 않으면 반환 리스트는 한 요소를 가진다.

GetNamedTimeZoneEpochNanoseconds의 기본 구현(로컬 정치적 규칙을 포함하지 않는 ECMAScript 구현체가 사용할)은 호출될 때 다음 단계를 수행한다:

  1. Assert: timeZoneIdentifier is "UTC".
  2. Let epochNanoseconds be GetUTCEpochNanoseconds(year, month, day, hour, minute, second, millisecond, microsecond, nanosecond).
  3. Return « epochNanoseconds ».
Note

타임존 인식 구현체(및 권장되는 다른 구현체들)는 IANA Time Zone Database의 시간대 정보를 사용하는 것이 요구된다: https://www.iana.org/time-zones/.

예: 2017년 11월 5일 1:30 AM America/New_York는 두 번 반복되므로 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(01:30 미국 동부 표준시, 오프셋 -05:00)를 나타낸다.

2017년 3월 12일 2:30 AM America/New_York은 존재하지 않으므로 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 (a String) and epochNanoseconds (a BigInt) and returns an integer.

반환된 정수는 지정된 명명된 타임존 timeZoneIdentifier에 대해, 에포크로부터의 epochNanoseconds에 대응하는 순간에서의 UTC로부터의 오프셋을 나노초 단위로 나타낸다.

로컬 정치적 규칙을 포함하지 않는 구현체에서 사용할 GetNamedTimeZoneOffsetNanoseconds의 기본 구현은 호출될 때 다음 단계를 수행한다:

  1. Assert: timeZoneIdentifier is "UTC".
  2. Return 0.
Note

타임존 오프셋 값은 양수 또는 음수일 수 있다.

21.4.1.22 타임존 식별자 레코드

타임존 식별자 레코드사용 가능한 명명된 타임존 식별자와 해당 주요 타임존 식별자를 설명하기 위해 사용되는 레코드이다.

타임존 식별자 레코드는 Table 59에 열거된 필드를 가진다.

Table 59: 타임존 식별자 레코드 필드
필드 이름 의미
[[Identifier]] a String 구현체가 지원하는 사용 가능한 명명된 타임존 식별자.
[[PrimaryIdentifier]] a String [[Identifier]]가 해석하는 주요 타임존 식별자.
Note

만약 [[Identifier]]가 주요 타임존 식별자이면, [[Identifier]][[PrimaryIdentifier]]와 동일하다.

21.4.1.23 AvailableNamedTimeZoneIdentifiers ( )

The implementation-defined abstract operation AvailableNamedTimeZoneIdentifiers takes no arguments and returns a List of Time Zone Identifier Records. 반환 결과는 이 구현체에서 사용 가능한 모든 명명된 타임존 식별자들과 각 사용 가능한 식별자에 대응하는 주요 타임존 식별자를 설명한다. 리스트는 각 타임존 레코드의 [[Identifier]] 필드에 따라 정렬된다.

ECMA-402 국제화 API를 구현하는 타임존 인식 구현체는 AvailableNamedTimeZoneIdentifiers 추상 연산을 ECMA-402 명세에 지정된 대로 구현해야 한다. 타임존 인식이 아닌 구현체에 대해서는 AvailableNamedTimeZoneIdentifiers는 호출될 때 다음 단계를 수행한다:

  1. If the implementation does not include local political rules for any time zones, then
    1. Return « the Time Zone Identifier Record { [[Identifier]]: "UTC", [[PrimaryIdentifier]]: "UTC" } ».
  2. Let identifiers be the List of unique available named time zone identifiers, sorted according to lexicographic code unit order.
  3. Let result be a new empty List.
  4. For each element identifier of identifiers, do
    1. Let primary be identifier.
    2. If identifier is a non-primary time zone identifier in this implementation and identifier is not "UTC", then
      1. Set primary to the primary time zone identifier associated with identifier.
      2. NOTE: An implementation may need to resolve identifier iteratively to obtain the primary time zone identifier.
    3. Let record be the Time Zone Identifier Record { [[Identifier]]: identifier, [[PrimaryIdentifier]]: primary }.
    4. Append record to result.
  5. Assert: result contains a Time Zone Identifier Record r such that r.[[Identifier]] is "UTC" and r.[[PrimaryIdentifier]] is "UTC".
  6. Return result.

21.4.1.24 SystemTimeZoneIdentifier ( )

The implementation-defined abstract operation SystemTimeZoneIdentifier takes no arguments and returns a String. 이는 호스트 환경의 현재 타임존을 나타내는 문자열을 반환한다. 그 문자열은 IsTimeZoneOffsetString이 참을 반환하는 UTC 오프셋을 나타내는 문자열이거나 주요 타임존 식별자 중 하나이다. It performs the following steps when called:

  1. If the implementation only supports the UTC time zone, return "UTC".
  2. Let systemTimeZoneString be the String representing the host environment's current time zone, either a primary time zone identifier or an offset time zone identifier.
  3. Return systemTimeZoneString.
Note

Date 객체의 메서드들이 일반적으로 제공하는 수준의 기능을 보장하기 위해, SystemTimeZoneIdentifier는 가능하다면 호스트 환경의 시간대 설정에 대응하는 IANA 타임존 이름을 반환하는 것이 권장된다. GetNamedTimeZoneEpochNanosecondsGetNamedTimeZoneOffsetNanoseconds는 해당 타임존의 표준시 및 서머타임에 대한 로컬 정치적 규칙을 반영해야 한다(존재한다면).

예: 호스트 환경이 사용자가 US 동부 시간을 선택한 시스템 상의 브라우저라면, SystemTimeZoneIdentifier는 "America/New_York"을 반환한다.

21.4.1.25 LocalTime ( t )

The abstract operation LocalTime takes argument t (a finite time value) and returns an integral Number. 이는 t를 UTC에서 로컬 시간으로 변환한다. 결과를 결정하기 위해 해당 시각에 적용되는 표준시 및 서머타임에 대한 로컬 정치적 규칙을 사용해야 한다. It performs the following steps when called:

  1. Let systemTimeZoneIdentifier be SystemTimeZoneIdentifier().
  2. If IsTimeZoneOffsetString(systemTimeZoneIdentifier) is true, then
    1. Let offsetNs be ParseTimeZoneOffsetString(systemTimeZoneIdentifier).
  3. Else,
    1. Let offsetNs be GetNamedTimeZoneOffsetNanoseconds(systemTimeZoneIdentifier, ((t) × 106)).
  4. Let offsetMs be truncate(offsetNs / 106).
  5. Return t + 𝔽(offsetMs).
Note 1

만약 구현체 내에 로컬 시각에 대한 정치적 규칙이 없으면, 결과는 t이다. 왜냐하면 SystemTimeZoneIdentifier"UTC"를 반환하고 GetNamedTimeZoneOffsetNanoseconds는 0을 반환하기 때문이다.

Note 2

이 절에서 요구되는 바와 같이 구현체는 IANA Time Zone Database의 시간대 정보를 사용하는 것이 요구되며(권장), 이를 통해 로컬 정치적 규칙을 반영해야 한다.

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 (a Number) and returns a time value. 이는 t를 로컬 시간에서 UTC 시간 값으로 변환한다. 결과를 결정하기 위해 해당 시각에 적용되는 표준시 및 서머타임에 대한 로컬 정치적 규칙을 사용해야 한다. It performs the following steps when called:

  1. If t is not finite, return NaN.
  2. Let systemTimeZoneIdentifier be SystemTimeZoneIdentifier().
  3. If IsTimeZoneOffsetString(systemTimeZoneIdentifier) is true, then
    1. Let offsetNs be ParseTimeZoneOffsetString(systemTimeZoneIdentifier).
  4. Else,
    1. Let possibleInstants be GetNamedTimeZoneEpochNanoseconds(systemTimeZoneIdentifier, (YearFromTime(t)), (MonthFromTime(t)) + 1, (DateFromTime(t)), (HourFromTime(t)), (MinFromTime(t)), (SecFromTime(t)), (msFromTime(t)), 0, 0).
    2. NOTE: The following steps ensure that when t represents local time repeating multiple times at a negative time zone transition (e.g. when the daylight saving time ends or the time zone adjustment is decreased due to a time zone rule change) or skipped local time at a positive time zone transition (e.g. when the daylight saving time starts or the time zone offset is increased due to a time zone rule change), t is interpreted using the time zone offset before the transition.
    3. If possibleInstants is not empty, then
      1. Let disambiguatedInstant be possibleInstants[0].
    4. Else,
      1. NOTE: t represents a local time skipped at a positive time zone transition (e.g. due to daylight saving time starting or a time zone rule change increasing the UTC offset).
      2. Let possibleInstantsBefore be GetNamedTimeZoneEpochNanoseconds(systemTimeZoneIdentifier, (YearFromTime(tBefore)), (MonthFromTime(tBefore)) + 1, (DateFromTime(tBefore)), (HourFromTime(tBefore)), (MinFromTime(tBefore)), (SecFromTime(tBefore)), (msFromTime(tBefore)), 0, 0), where tBefore is the largest integral Number < t for which possibleInstantsBefore is not empty (i.e., tBefore represents the last local time before the transition).
      3. Let disambiguatedInstant be the last element of possibleInstantsBefore.
    5. Let offsetNs be GetNamedTimeZoneOffsetNanoseconds(systemTimeZoneIdentifier, disambiguatedInstant).
  5. Let offsetMs be truncate(offsetNs / 106).
  6. Return 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이다. 왜냐하면 SystemTimeZoneIdentifier"UTC"를 반환하고 GetNamedTimeZoneOffsetNanoseconds는 0을 반환하기 때문이다.

Note 1

타임존 인식 구현체(및 권장되는 다른 구현체들)는 IANA Time Zone Database의 시간대 정보를 사용하는 것이 요구된다.

2017년 11월 5일 1:30 AM America/New_York는 두 번 반복되지만(시계 되돌림), 그것은 1:30 AM UTC-04로 해석되어야 한다(UTC-05가 아니라). UTC(TimeClip(MakeDate(MakeDay(2017, 10, 5), MakeTime(1, 30, 0, 0)))), 여기서 offsetMs-4 × msPerHour이다.

2017년 3월 12일 2:30 AM America/New_York은 존재하지 않지만, 그것은 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 (a Number), min (a Number), sec (a Number), and ms (a Number) and returns a Number. 이는 밀리초 수를 계산한다. It performs the following steps when called:

  1. If hour is not finite, min is not finite, sec is not finite, or ms is not finite, return NaN.
  2. Let h be 𝔽(! ToIntegerOrInfinity(hour)).
  3. Let m be 𝔽(! ToIntegerOrInfinity(min)).
  4. Let s be 𝔽(! ToIntegerOrInfinity(sec)).
  5. Let milli be 𝔽(! ToIntegerOrInfinity(ms)).
  6. Return ((h × msPerHour + m × msPerMinute) + s × msPerSecond) + milli.
Note

MakeTime의 산술은 부동소수점 산술이며 결합법칙이 성립하지 않으므로 연산은 올바른 순서로 수행되어야 한다.

21.4.1.28 MakeDay ( year, month, date )

The abstract operation MakeDay takes arguments year (a Number), month (a Number), and date (a Number) and returns a finite Number or NaN. 이는 일수(days)를 계산한다. It performs the following steps when called:

  1. If year is not finite, month is not finite, or date is not finite, return NaN.
  2. Let y be 𝔽(! ToIntegerOrInfinity(year)).
  3. Let m be 𝔽(! ToIntegerOrInfinity(month)).
  4. Let dt be 𝔽(! ToIntegerOrInfinity(date)).
  5. Let ym be y + 𝔽(floor((m) / 12)).
  6. If ym is not finite, return NaN.
  7. Let mn be 𝔽((m) modulo 12).
  8. Find a finite time value t such that YearFromTime(t) is ym, MonthFromTime(t) is mn, and DateFromTime(t) is 1𝔽; but if this is not possible (because some argument is out of range), return NaN.
  9. Return Day(t) + dt - 1𝔽.

21.4.1.29 MakeDate ( day, time )

The abstract operation MakeDate takes arguments day (a Number) and time (a Number) and returns a finite Number or NaN. 이는 밀리초 수를 계산한다. It performs the following steps when called:

  1. If day is not finite or time is not finite, return NaN.
  2. Let tv be day × msPerDay + time.
  3. If tv is not finite, return NaN.
  4. Return tv.

21.4.1.30 MakeFullYear ( year )

The abstract operation MakeFullYear takes argument year (a Number) and returns an integral Number or NaN. 이는 year정수 부분과 연관된 완전 연도(full year)를 반환한다. 0에서 99 사이의 값은 1900년 시작 이후의 연도로 해석된다. 프로레프틱 그레고리력과 정렬을 위해 "full year"는 연도 0(기원전 1년) 시작 이후의 전체 연도 수로 정의된다. It performs the following steps when called:

  1. If year is one of NaN, +∞𝔽, or -∞𝔽, return NaN.
  2. Let truncated be ! ToIntegerOrInfinity(year).
  3. If truncated is in the inclusive interval from 0 to 99, return 1900𝔽 + 𝔽(truncated).
  4. Return 𝔽(truncated).

21.4.1.31 TimeClip ( time )

The abstract operation TimeClip takes argument time (a Number) and returns a time value. 이는 밀리초 수를 계산한다. It performs the following steps when called:

  1. If time is not finite, return NaN.
  2. If abs((time)) > 8.64 × 1015, return NaN.
  3. Return 𝔽(! ToIntegerOrInfinity(time)).

21.4.1.32 Date Time String Format

ECMAScript는 ISO 8601 달력 날짜 확장 형식의 단순화에 기반한 날짜-시간 문자열 교환 포맷을 정의한다. 형식은 다음과 같다: YYYY-MM-DDTHH:mm:ss.sssZ

요소들은 다음과 같다:

YYYY 프로레프틱 그레고리력에서 연도를 네 자리 십진수로 0000에서 9999까지 표현하거나, 확장 연도로서 부호(+) 또는 (-)와 여섯 자리 십진수를 사용하는 형태일 수 있다.
- 문자열 내에 문자 "-" (하이픈)이 두 번 문자 그대로 나타난다.
MM 연도의 월을 01(1월)에서 12(12월)까지 두 자리 십진수로 나타낸다.
DD 월의 일을 01에서 31까지 두 자리 십진수로 나타낸다.
T 시간 요소의 시작을 나타내기 위해 문자열에 "T"가 문자 그대로 나타난다.
HH 자정 이후 지난 완전한 시간 수를 00에서 24까지 두 자리 십진수로 나타낸다.
: 문자열 내에 문자 ":" (콜론)이 두 번 문자 그대로 나타난다.
mm 시간의 시작 이후의 완전한 분 수를 00에서 59까지 두 자리 십진수로 나타낸다.
ss 분의 시작 이후의 완전한 초 수를 00에서 59까지 두 자리 십진수로 나타낸다.
. 문자열 내에 문자 "." (점)이 문자 그대로 나타난다.
sss 초의 시작 이후의 완전한 밀리초 수를 세 자리 십진수로 나타낸다.
Z UTC 오프셋 표현으로 "Z" (오프셋 없는 UTC) 또는 "+" 또는 "-" 뒤에 시간 표현 HH:mm이 오는 형태로 지정된다(이는 로컬 시간이 UTC보다 앞서거나 뒤처짐을 나타내는 ISO 8601 타임존 오프셋 문자열 형식의 부분집합이다).

이 형식은 날짜 전용 형태도 포함한다:

YYYY
YYYY-MM
YYYY-MM-DD
        

또한 위의 날짜 전용 형태 중 하나에 선택적 UTC 오프셋 표현이 추가된 다음 시간 형태들 중 하나를 바로 이어붙인 “date-time” 형태들도 포함한다:

THH:mm
THH:mm:ss
THH:mm:ss.sss
        

범위를 벗어나거나 형식에 맞지 않는 요소가 포함된 문자열은 이 형식의 유효한 인스턴스가 아니다.

Note 1

모든 날은 자정에서 시작하고 끝나므로 00:0024:00 두 표기법을 사용하여 하나 날짜와 연관된 두 자정을 구별할 수 있다. 이는 다음 두 표기가 정확히 동일한 시간을 가리킨다는 것을 의미한다: 1995-02-04T24:001995-02-05T00:00. 후자의 형태를 "날의 끝"으로 해석하는 것은 ISO 8601과 일치한다(ISO 8601은 시간 간격을 기술할 때 이를 예약하고 단일 시점을 표현할 때는 허용하지 않음에도 불구하고).

Note 2

CET, EST 등과 같은 민간 약어에 대한 국제 표준은 존재하지 않으며, 같은 약어가 서로 다른 타임존에 대해 사용되기도 한다. 이 이유로 ISO 8601과 이 형식은 모두 숫자 기반의 타임존 오프셋 표현을 지정한다.

21.4.1.32.1 확장 연도

시간 값 범위인 약 ±273,790년을 완전히 다루려면 9999년 이전 또는 이후의 연도를 표현해야 한다. ISO 8601은 연도 표기의 확장을 허용하지만 교환 당사자 간 합의에 의해서만 허용한다. 단순화된 ECMAScript 형식에서 그러한 확장 연도 표기는 6자리여야 하며 항상 + 또는 - 기호로 접두된다. 연도 0은 양수로 간주되어 반드시 + 기호로 접두되어야 한다. 연도 0을 -000000으로 표기하는 것은 유효하지 않다. 확장 연도를 사용한 Date Time String Format에 맞는 문자열이 시간 값 범위를 벗어나는 순간을 나타내면 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 (a String) and returns a Boolean. 반환값은 offsetStringUTCOffset 문법에 부합하는지 여부를 나타낸다. It performs the following steps when called:

  1. Let parseResult be ParseText(offsetString, UTCOffset).
  2. If parseResult is a List of errors, return false.
  3. Return true.

21.4.1.33.2 ParseTimeZoneOffsetString ( offsetString )

The abstract operation ParseTimeZoneOffsetString takes argument offsetString (a String) and returns an integer. 반환값은 문자열 offsetString에 해당하는 UTC 오프셋을 나노초 단위의 정수로 나타낸 것이다. It performs the following steps when called:

  1. parseResultParseText(offsetString, UTCOffset)라고 하자.
  2. Assert: parseResult는 오류의 List가 아니다.
  3. Assert: parseResultASCIISign Parse Node를 포함한다.
  4. parsedSignparseResult 안에 포함된 ASCIISign Parse Node와 일치한 소스 텍스트라고 하자.
  5. parsedSign이 단일 코드 포인트 U+002D (HYPHEN-MINUS)이면,
    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. fractionCodePointsToString(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)을 나타내는 String을 반환한다.
  • 인자의 개수와 타입에 따라 동작이 달라지는 함수이다.
  • 클래스 정의의 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가 Object이고 value[[DateValue]] 내부 슬롯을 가지면,
      1. tvvalue.[[DateValue]]라고 하자.
    3. 그렇지 않으면,
      1. v를 ? ToPrimitive(value)라고 하자.
      2. v가 String이면,
        1. Assert: 다음 단계는 v가 String이므로 abrupt completion을 결코 반환하지 않는다.
        2. tvparse 메서드(21.4.3.2)와 정확히 같은 방식으로 v를 날짜로 파싱한 결과라고 하자.
      3. 그렇지 않으면,
        1. tv를 ? ToNumber(v)라고 하자.
    4. dvTimeClip(tv)이라고 하자.
  5. 그렇지 않으면,
    1. Assert: numberOfArgs ≥ 2.
    2. y를 ? ToNumber(values[0])라고 하자.
    3. m을 ? ToNumber(values[1])라고 하자.
    4. numberOfArgs > 2이면 dt를 ? ToNumber(values[2])라고 하자; 그렇지 않으면 dt1𝔽라고 하자.
    5. numberOfArgs > 3이면 h를 ? ToNumber(values[3])라고 하자; 그렇지 않으면 h+0𝔽라고 하자.
    6. numberOfArgs > 4이면 min을 ? ToNumber(values[4])라고 하자; 그렇지 않으면 min+0𝔽라고 하자.
    7. numberOfArgs > 5이면 s를 ? ToNumber(values[5])라고 하자; 그렇지 않으면 s+0𝔽라고 하자.
    8. numberOfArgs > 6이면 milli를 ? ToNumber(values[6])라고 하자; 그렇지 않으면 milli+0𝔽라고 하자.
    9. yrMakeFullYear(y)라고 하자.
    10. finalDateMakeDate(MakeDay(yr, m, dt), MakeTime(h, min, s, milli))라고 하자.
    11. dvTimeClip(UTC(finalDate))라고 하자.
  6. obj를 ? OrdinaryCreateFromConstructor(NewTarget, "%Date.prototype%", « [[DateValue]] »)라고 하자.
  7. obj.[[DateValue]]dv로 설정한다.
  8. obj를 반환한다.

21.4.3 Date 생성자의 속성

Date 생성자는:

  • 값이 %Function.prototype%[[Prototype]] 내부 슬롯을 가진다.
  • 값이 7𝔽"length" 속성을 가진다.
  • 다음 속성들을 가진다:

21.4.3.1 Date.now ( )

이 함수는 호출이 발생한 UTC 날짜와 시간을 지정하는 시간 값을 반환한다.

21.4.3.2 Date.parse ( string )

이 함수는 인자에 ToString 연산자를 적용한다. ToStringabrupt completion으로 끝나면 그 Completion Record가 즉시 반환된다. 그렇지 않으면 이 함수는 결과 String을 날짜와 시간으로 해석한다; 이 함수는 해당 날짜와 시간에 대응하는 UTC 시간 값인 Number를 반환한다. String은 그 내용에 따라 로컬 시간, UTC 시간, 또는 어떤 다른 시간대의 시간으로 해석될 수 있다. 이 함수는 먼저 확장 연도를 포함하여 Date Time String Format(21.4.1.32)에 설명된 형식에 따라 String을 파싱하려고 시도한다. String이 그 형식에 부합하지 않으면, 함수는 구현별 휴리스틱 또는 구현별 날짜 형식으로 대체할 수 있다. 인식할 수 없거나 범위를 벗어난 형식 요소 값을 포함하는 String은 이 함수가 NaN을 반환하게 해야 한다.

String이 Date Time String Format에 부합하면, 부재한 형식 요소를 대체 값이 대신한다. MM 또는 DD 요소가 부재하면 "01"이 사용된다. HH, mm, 또는 ss 요소가 부재하면 "00"이 사용된다. sss 요소가 부재하면 "000"이 사용된다. UTC 오프셋 표현이 부재하면, 날짜 전용 형식은 UTC 시간으로 해석되고 날짜-시간 형식은 로컬 시간으로 해석된다.

x가 ECMAScript의 특정 구현에서 밀리초 양이 0인 Date이면, 참조된 모든 속성이 초기값을 가진 경우, 다음 표현식들은 모두 그 구현에서 같은 숫자 값을 생성해야 한다:

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 메서드로 생성될 수 없는 임의의 String 값이 주어졌을 때 이 함수가 생성하는 값은 구현 정의이다.

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]] 내부 슬롯을 가지지 않는다.
  • 값이 %Object.prototype%[[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가 존재하면 m을 ? ToNumber(month)라고 하자; 그렇지 않으면 mMonthFromTime(t)라고 하자.
  7. date가 존재하면 dt를 ? ToNumber(date)라고 하자; 그렇지 않으면 dtDateFromTime(t)라고 하자.
  8. newDateMakeDate(MakeDay(y, m, dt), TimeWithinDay(t))라고 하자.
  9. uTimeClip(UTC(newDate))라고 하자.
  10. dateObject.[[DateValue]]u로 설정한다.
  11. u를 반환한다.

이 메서드의 "length" 속성은 3𝔽이다.

Note

month가 존재하지 않으면, 이 메서드는 monthgetMonth() 값을 가지고 존재하는 것처럼 동작한다. date가 존재하지 않으면, dategetDate() 값을 가지고 존재하는 것처럼 동작한다.

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이 존재하지 않으면, 이 메서드는 mingetMinutes() 값을 가지고 존재하는 것처럼 동작한다. sec이 존재하지 않으면, secgetSeconds() 값을 가지고 존재하는 것처럼 동작한다. ms가 존재하지 않으면, msgetMilliseconds() 값을 가지고 존재하는 것처럼 동작한다.

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이 존재하지 않으면, 이 메서드는 secgetSeconds() 값을 가지고 존재하는 것처럼 동작한다. ms가 존재하지 않으면, 이것은 msgetMilliseconds() 값을 가지고 존재하는 것처럼 동작한다.

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가 존재하지 않으면, 이 메서드는 dategetDate() 값을 가지고 존재하는 것처럼 동작한다.

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가 존재하지 않으면, 이 메서드는 msgetMilliseconds() 값을 가지고 존재하는 것처럼 동작한다.

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가 존재하면 m을 ? ToNumber(month)라고 하자; 그렇지 않으면 mMonthFromTime(t)라고 하자.
  7. date가 존재하면 dt를 ? ToNumber(date)라고 하자; 그렇지 않으면 dtDateFromTime(t)라고 하자.
  8. newDateMakeDate(MakeDay(y, m, dt), TimeWithinDay(t))라고 하자.
  9. vTimeClip(newDate)라고 하자.
  10. dateObject.[[DateValue]]v로 설정한다.
  11. v를 반환한다.

이 메서드의 "length" 속성은 3𝔽이다.

Note

month가 존재하지 않으면, 이 메서드는 monthgetUTCMonth() 값을 가지고 존재하는 것처럼 동작한다. date가 존재하지 않으면, dategetUTCDate() 값을 가지고 존재하는 것처럼 동작한다.

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이 존재하지 않으면, 이 메서드는 mingetUTCMinutes() 값을 가지고 존재하는 것처럼 동작한다. sec이 존재하지 않으면, secgetUTCSeconds() 값을 가지고 존재하는 것처럼 동작한다. ms가 존재하지 않으면, msgetUTCMilliseconds() 값을 가지고 존재하는 것처럼 동작한다.

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이 존재하지 않으면, 이 메서드는 secgetUTCSeconds() 값을 가지고 존재하는 것처럼 동작한다. ms가 존재하지 않으면, msgetUTCMilliseconds()가 반환한 값을 가지고 존재하는 것처럼 동작한다.

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가 존재하지 않으면, 이 메서드는 dategetUTCDate() 값을 가지고 존재하는 것처럼 동작한다.

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가 존재하지 않으면, 이 메서드는 msgetUTCMilliseconds() 값을 가지고 존재하는 것처럼 동작한다.

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 예외를 던진다.
  5. Assert: tv정수 Number이다.
  6. tvDate Time String Format으로 표현할 수 없는 연도에 대응하면, RangeError 예외를 던진다.
  7. 모든 형식 요소와 UTC 오프셋 표현 "Z"를 포함하여, UTC 시간 척도에서 Date Time String Formattv의 String 표현을 반환한다.

21.4.4.37 Date.prototype.toJSON ( key )

이 메서드는 JSON.stringify(25.5.4)에서 사용하기 위한 Date의 String 표현을 제공한다.

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. obj를 ? ToObject(this value)라고 하자.
  2. tv를 ? ToPrimitive(obj, number)라고 하자.
  3. tv가 Number이고 tv유한하지 않으면 null을 반환한다.
  4. Invoke(obj, "toISOString")를 반환한다.
Note 1

인자는 무시된다.

Note 2

이 메서드는 의도적으로 제네릭이다; 이 메서드는 자신의 this 값이 Date일 것을 요구하지 않는다. 따라서 메서드로 사용하기 위해 다른 종류의 객체로 이전될 수 있다. 그러나 그러한 객체는 toISOString 메서드를 가져야 한다.

21.4.4.38 Date.prototype.toLocaleDateString ( [ reserved1 [ , reserved2 ] ] )

ECMA-402 국제화 API를 포함하는 ECMAScript 구현은 ECMA-402 명세에 지정된 대로 이 메서드를 구현해야 한다. ECMAScript 구현이 ECMA-402 API를 포함하지 않는 경우 이 메서드에 대한 다음 명세가 사용된다:

이 메서드는 String 값을 반환한다. String의 내용은 구현 정의이지만, 현재 시간대에서 Date의 “date” 부분을 호스트 환경의 현재 로캘 관례에 대응하는 편리하고 사람이 읽을 수 있는 형식으로 나타내도록 의도되어 있다.

이 메서드의 선택적 매개변수의 의미는 ECMA-402 명세에 정의되어 있다; ECMA-402 지원을 포함하지 않는 구현은 그 매개변수 위치를 다른 어떤 용도로도 사용해서는 안 된다.

21.4.4.39 Date.prototype.toLocaleString ( [ reserved1 [ , reserved2 ] ] )

ECMA-402 국제화 API를 포함하는 ECMAScript 구현은 ECMA-402 명세에 지정된 대로 이 메서드를 구현해야 한다. ECMAScript 구현이 ECMA-402 API를 포함하지 않는 경우 이 메서드에 대한 다음 명세가 사용된다:

이 메서드는 String 값을 반환한다. String의 내용은 구현 정의이지만, 현재 시간대의 Date를 호스트 환경의 현재 로캘 관례에 대응하는 편리하고 사람이 읽을 수 있는 형식으로 나타내도록 의도되어 있다.

이 메서드의 선택적 매개변수의 의미는 ECMA-402 명세에 정의되어 있다; ECMA-402 지원을 포함하지 않는 구현은 그 매개변수 위치를 다른 어떤 용도로도 사용해서는 안 된다.

21.4.4.40 Date.prototype.toLocaleTimeString ( [ reserved1 [ , reserved2 ] ] )

ECMA-402 국제화 API를 포함하는 ECMAScript 구현은 ECMA-402 명세에 지정된 대로 이 메서드를 구현해야 한다. ECMAScript 구현이 ECMA-402 API를 포함하지 않는 경우 이 메서드에 대한 다음 명세가 사용된다:

이 메서드는 String 값을 반환한다. String의 내용은 구현 정의이지만, 현재 시간대에서 Date의 “time” 부분을 호스트 환경의 현재 로캘 관례에 대응하는 편리하고 사람이 읽을 수 있는 형식으로 나타내도록 의도되어 있다.

이 메서드의 선택적 매개변수의 의미는 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

d.[[DateValue]]가 1000으로 나누어떨어지는 임의의 Date d에 대해, Date.parse(d.toString())의 결과 = d.valueOf()이다. 21.4.3.2를 보라.

Note 2

이 메서드는 제네릭이 아니다; 자신의 this 값이 Date가 아니면 TypeError 예외를 던진다. 따라서 메서드로 사용하기 위해 다른 종류의 객체로 이전될 수 없다.

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 (SPACE), 및 "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. weekday를 Number WeekDay(tv)를 가진 Table 60의 항목의 Name이라고 하자.
  2. month를 Number MonthFromTime(tv)를 가진 Table 61의 항목의 Name이라고 하자.
  3. dayToZeroPaddedDecimalString((DateFromTime(tv)), 2)라고 하자.
  4. yvYearFromTime(tv)라고 하자.
  5. yv+0𝔽이거나 yv > +0𝔽이면 yearSign을 빈 String이라고 하자; 그렇지 않으면 yearSign"-"라고 하자.
  6. paddedYearToZeroPaddedDecimalString(abs((yv)), 4)라고 하자.
  7. weekday, 코드 단위 0x0020 (SPACE), month, 코드 단위 0x0020 (SPACE), day, 코드 단위 0x0020 (SPACE), yearSign, 및 paddedYear의 문자열 연결을 반환한다.
Table 60: 요일 이름
Number Name
+0𝔽 "Sun"
1𝔽 "Mon"
2𝔽 "Tue"
3𝔽 "Wed"
4𝔽 "Thu"
5𝔽 "Fri"
6𝔽 "Sat"
Table 61: 월 이름
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을 빈 String이거나 코드 단위 0x0020 (SPACE), 코드 단위 0x0028 (LEFT PARENTHESIS), 구현 정의 시간대 이름, 및 코드 단위 0x0029 (RIGHT PARENTHESIS)의 문자열 연결인 구현 정의 문자열이라고 하자.
  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 (SPACE), 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 값에 대응하는 시간상 순간을 나타내는 String 값을 반환한다. String의 형식은 RFC 7231의 "HTTP-date"에 기반하며, ECMAScript Dates가 지원하는 전체 시간 범위를 지원하도록 일반화되어 있다.

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. dateObjectthis 값이라고 하자.
  2. RequireInternalSlot(dateObject, [[DateValue]])를 수행한다.
  3. tvdateObject.[[DateValue]]라고 하자.
  4. tvNaN이면 "Invalid Date"를 반환한다.
  5. weekday를 Number WeekDay(tv)를 가진 Table 60의 항목의 Name이라고 하자.
  6. month를 Number MonthFromTime(tv)를 가진 Table 61의 항목의 Name이라고 하자.
  7. dayToZeroPaddedDecimalString((DateFromTime(tv)), 2)라고 하자.
  8. yvYearFromTime(tv)라고 하자.
  9. yv+0𝔽이거나 yv > +0𝔽이면 yearSign을 빈 String이라고 하자; 그렇지 않으면 yearSign"-"라고 하자.
  10. paddedYearToZeroPaddedDecimalString(abs((yv)), 4)라고 하자.
  11. weekday, ",", 코드 단위 0x0020 (SPACE), day, 코드 단위 0x0020 (SPACE), month, 코드 단위 0x0020 (SPACE), yearSign, paddedYear, 코드 단위 0x0020 (SPACE), 및 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"과 동등한 것으로 취급한다는 점에서 고유하다. 다른 모든 내장 ECMAScript 객체들은 "default""number"와 동등한 것으로 취급한다.

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. objthis 값이라고 하자.
  2. obj가 Object가 아니면 TypeError 예외를 던진다.
  3. hint"string" 또는 "default" 중 하나이면,
    1. tryFirststring이라고 하자.
  4. 그렇지 않고 hint"number"이면,
    1. tryFirstnumber라고 하자.
  5. 그렇지 않으면,
    1. TypeError 예외를 던진다.
  6. OrdinaryToPrimitive(obj, 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. str을 빈 String이라고 하자.
  2. 그렇지 않으면,
    1. NewTarget이 undefined이고 value가 Symbol이면, SymbolDescriptiveString(value)을 반환한다.
    2. str을 ? ToString(value)라고 하자.
  3. NewTarget이 undefined이면 str을 반환한다.
  4. StringCreate(str, ? GetPrototypeFromConstructor(NewTarget, "%String.prototype%"))를 반환한다.

22.1.2 String 생성자의 속성

String 생성자는:

  • 값이 %Function.prototype%[[Prototype]] 내부 슬롯을 가진다.
  • 다음 속성들을 가진다:

22.1.2.1 String.fromCharCode ( ...codeUnits )

이 함수는 나머지 매개변수 codeUnits를 형성하는 임의 개수의 인자와 함께 호출될 수 있다.

이 함수는 호출될 때 다음 단계를 수행한다:

  1. result를 빈 String이라고 하자.
  2. codeUnits의 각 요소 next에 대해, 다음을 수행한다.
    1. nextCU를 수치 값이 (? ToUint16(next))인 코드 단위라고 하자.
    2. resultresultnextCU의 문자열 연결로 설정한다.
  3. result를 반환한다.

이 함수의 "length" 속성은 1𝔽이다.

22.1.2.2 String.fromCodePoint ( ...codePoints )

이 함수는 나머지 매개변수 codePoints를 형성하는 임의 개수의 인자와 함께 호출될 수 있다.

이 함수는 호출될 때 다음 단계를 수행한다:

  1. result를 빈 String이라고 하자.
  2. codePoints의 각 요소 next에 대해, 다음을 수행한다.
    1. nextCP를 ? ToNumber(next)라고 하자.
    2. nextCP정수 Number가 아니면 RangeError 예외를 던진다.
    3. (nextCP) < 0이거나 (nextCP) > 0x10FFFF이면 RangeError 예외를 던진다.
    4. resultresultUTF16EncodeCodePoint((nextCP))의 문자열 연결로 설정한다.
  3. Assert: codePoints가 비어 있으면, result는 빈 String이다.
  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이고 나머지 인자들은 List substitutions를 형성한다.

이 함수는 호출될 때 다음 단계를 수행한다:

  1. substitutionCountsubstitutions의 요소 개수라고 하자.
  2. cooked를 ? ToObject(template)라고 하자.
  3. literals를 ? ToObject(? Get(cooked, "raw"))라고 하자.
  4. literalCount를 ? LengthOfArrayLike(literals)라고 하자.
  5. literalCount ≤ 0이면, 빈 String을 반환한다.
  6. result를 빈 String이라고 하자.
  7. nextIndex를 0이라고 하자.
  8. 반복한다.
    1. nextLiteralVal을 ? Get(literals, ! ToString(𝔽(nextIndex)))라고 하자.
    2. nextLiteral을 ? ToString(nextLiteralVal)라고 하자.
    3. resultresultnextLiteral의 문자열 연결로 설정한다.
    4. nextIndex + 1 = literalCount이면, result를 반환한다.
    5. nextIndex < substitutionCount이면,
      1. nextSubValsubstitutions[nextIndex]라고 하자.
      2. nextSub를 ? ToString(nextSubVal)라고 하자.
      3. resultresultnextSub의 문자열 연결로 설정한다.
    6. nextIndexnextIndex + 1로 설정한다.
Note

이 함수는 Tagged Template(13.3.11)의 태그 함수로 사용되도록 의도되어 있다. 그렇게 호출될 때, 첫 번째 인자는 올바른 형식의 템플릿 객체이고 나머지 매개변수는 치환 값을 포함한다.

22.1.3 String 프로토타입 객체의 속성

String 프로토타입 객체는:

  • %String.prototype%이다.
  • String 특수 객체이며 그러한 객체에 대해 지정된 내부 메서드를 가진다.
  • 값이 빈 String인 [[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. thisValuethis 값이라고 하자.
  2. RequireObjectCoercible(thisValue)를 수행한다.
  3. str을 ? ToString(thisValue)라고 하자.
  4. lenstr의 길이라고 하자.
  5. relativeIndex를 ? ToIntegerOrInfinity(index)라고 하자.
  6. relativeIndex ≥ 0이면,
    1. krelativeIndex라고 하자.
  7. 그렇지 않으면,
    1. klen + relativeIndex라고 하자.
  8. k < 0이거나 klen이면, undefined를 반환한다.
  9. strk부터 k + 1까지의 부분 문자열을 반환한다.

22.1.3.2 String.prototype.charAt ( pos )

Note 1

이 메서드는 이 객체를 String으로 변환한 결과인 String 값 안의 인덱스 pos에 있는 코드 단위를 포함하는 단일 요소 String을 반환한다. 그 인덱스에 요소가 없으면 결과는 빈 String이다. 결과는 String 객체가 아니라 String 값이다.

pos정수 Number이면, x.charAt(pos)의 결과는 x.substring(pos, pos + 1)의 결과와 동등하다.

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. thisValuethis 값이라고 하자.
  2. RequireObjectCoercible(thisValue)를 수행한다.
  3. str을 ? ToString(thisValue)라고 하자.
  4. position을 ? ToIntegerOrInfinity(pos)라고 하자.
  5. sizestr의 길이라고 하자.
  6. position < 0이거나 positionsize이면, 빈 String을 반환한다.
  7. strposition부터 position + 1까지의 부분 문자열을 반환한다.
Note 2

이 메서드는 의도적으로 제네릭이다; 이 메서드는 자신의 this 값이 String 객체일 것을 요구하지 않는다. 따라서 메서드로 사용하기 위해 다른 종류의 객체로 이전될 수 있다.

22.1.3.3 String.prototype.charCodeAt ( pos )

Note 1

이 메서드는 이 객체를 String으로 변환한 결과인 String 안의 인덱스 pos에 있는 코드 단위의 수치 값인 Number(216보다 작은 음이 아닌 정수 Number)를 반환한다. 그 인덱스에 요소가 없으면 결과는 NaN이다.

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. thisValuethis 값이라고 하자.
  2. RequireObjectCoercible(thisValue)를 수행한다.
  3. str을 ? ToString(thisValue)라고 하자.
  4. position을 ? ToIntegerOrInfinity(pos)라고 하자.
  5. sizestr의 길이라고 하자.
  6. position < 0이거나 positionsize이면, NaN을 반환한다.
  7. String str 안의 인덱스 position에 있는 코드 단위의 수치 값에 대한 Number 값을 반환한다.
Note 2

이 메서드는 의도적으로 제네릭이다; 이 메서드는 자신의 this 값이 String 객체일 것을 요구하지 않는다. 따라서 메서드로 사용하기 위해 다른 종류의 객체로 이전될 수 있다.

22.1.3.4 String.prototype.codePointAt ( pos )

Note 1

이 메서드는 이 객체를 String으로 변환한 결과인 String 안의 인덱스 pos에 있는 문자열 요소에서 시작하는 UTF-16으로 인코딩된 코드 포인트(6.1.4)의 수치 값인 0x10FFFF𝔽 이하의 음이 아닌 정수 Number를 반환한다. 그 인덱스에 요소가 없으면 결과는 undefined이다. 유효한 UTF-16 서로게이트 쌍이 pos에서 시작하지 않으면, 결과는 pos에 있는 코드 단위이다.

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. thisValuethis 값이라고 하자.
  2. RequireObjectCoercible(thisValue)를 수행한다.
  3. str을 ? ToString(thisValue)라고 하자.
  4. position을 ? ToIntegerOrInfinity(pos)라고 하자.
  5. sizestr의 길이라고 하자.
  6. position < 0이거나 positionsize이면, undefined를 반환한다.
  7. cpCodePointAt(str, position)이라고 하자.
  8. 𝔽(cp.[[CodePoint]])를 반환한다.
Note 2

이 메서드는 의도적으로 제네릭이다; 이 메서드는 자신의 this 값이 String 객체일 것을 요구하지 않는다. 따라서 메서드로 사용하기 위해 다른 종류의 객체로 이전될 수 있다.

22.1.3.5 String.prototype.concat ( ...args )

Note 1

이 메서드가 호출되면, this 값(문자열로 변환됨)의 코드 단위들 뒤에 각각의 인자를 String으로 변환한 코드 단위들이 이어진 String 값을 반환한다. 결과는 String 객체가 아니라 String 값이다.

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. thisValuethis 값이라고 하자.
  2. RequireObjectCoercible(thisValue)를 수행한다.
  3. str을 ? ToString(thisValue)라고 하자.
  4. resultstr이라고 하자.
  5. args의 각 요소 next에 대해, 다음을 수행한다.
    1. nextString을 ? ToString(next)라고 하자.
    2. resultresultnextString의 문자열 연결로 설정한다.
  6. result를 반환한다.

이 메서드의 "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. thisValuethis 값이라고 하자.
  2. RequireObjectCoercible(thisValue)를 수행한다.
  3. str을 ? ToString(thisValue)라고 하자.
  4. isRegExp를 ? IsRegExp(searchString)라고 하자.
  5. isRegExptrue이면, TypeError 예외를 던진다.
  6. searchStr을 ? ToString(searchString)라고 하자.
  7. lenstr의 길이라고 하자.
  8. endPositionundefined이면 poslen이라고 하자; 그렇지 않으면 pos를 ? ToIntegerOrInfinity(endPosition)라고 하자.
  9. endpos를 0과 len 사이로 클램프한 결과라고 하자.
  10. searchLengthsearchStr의 길이라고 하자.
  11. searchLength = 0이면, true를 반환한다.
  12. startend - searchLength라고 하자.
  13. start < 0이면, false를 반환한다.
  14. substringstrstart부터 end까지의 부분 문자열이라고 하자.
  15. substringsearchStr이면, true를 반환한다.
  16. false를 반환한다.
Note 1

첫 번째 인자가 RegExp이면 예외를 던지도록 지정된 것은 그러한 인자 값을 허용하는 확장을 미래 판에서 정의할 수 있게 하기 위한 것이다.

Note 2

이 메서드는 의도적으로 제네릭이다; 이 메서드는 자신의 this 값이 String 객체일 것을 요구하지 않는다. 따라서 메서드로 사용하기 위해 다른 종류의 객체로 이전될 수 있다.

22.1.3.8 String.prototype.includes ( searchString [ , position ] )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. thisValuethis 값이라고 하자.
  2. RequireObjectCoercible(thisValue)를 수행한다.
  3. str을 ? ToString(thisValue)라고 하자.
  4. isRegExp를 ? IsRegExp(searchString)라고 하자.
  5. isRegExptrue이면, TypeError 예외를 던진다.
  6. searchStr을 ? ToString(searchString)라고 하자.
  7. pos를 ? ToIntegerOrInfinity(position)라고 하자.
  8. Assert: positionundefined이면, pos는 0이다.
  9. lenstr의 길이라고 하자.
  10. startpos를 0과 len 사이로 클램프한 결과라고 하자.
  11. indexStringIndexOf(str, searchStr, start)라고 하자.
  12. indexnot-found이면, false를 반환한다.
  13. true를 반환한다.
Note 1

searchString이 이 객체를 String으로 변환한 결과의 부분 문자열로서, position 이상인 하나 이상의 인덱스에 나타나면, 이 함수는 true를 반환한다; 그렇지 않으면 false를 반환한다. positionundefined이면, 전체 String을 검색하기 위해 0이 가정된다.

Note 2

첫 번째 인자가 RegExp이면 예외를 던지도록 지정된 것은 그러한 인자 값을 허용하는 확장을 미래 판에서 정의할 수 있게 하기 위한 것이다.

Note 3

이 메서드는 의도적으로 제네릭이다; 이 메서드는 자신의 this 값이 String 객체일 것을 요구하지 않는다. 따라서 메서드로 사용하기 위해 다른 종류의 객체로 이전될 수 있다.

22.1.3.9 String.prototype.indexOf ( searchString [ , position ] )

Note 1

searchString이 이 객체를 String으로 변환한 결과의 부분 문자열로서, position 이상인 하나 이상의 인덱스에 나타나면, 그러한 가장 작은 인덱스가 반환된다; 그렇지 않으면 -1𝔽이 반환된다. positionundefined이면, 전체 String을 검색하기 위해 +0𝔽이 가정된다.

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. thisValuethis 값이라고 하자.
  2. RequireObjectCoercible(thisValue)를 수행한다.
  3. str을 ? ToString(thisValue)라고 하자.
  4. searchStr을 ? ToString(searchString)라고 하자.
  5. pos를 ? ToIntegerOrInfinity(position)라고 하자.
  6. Assert: positionundefined이면, pos는 0이다.
  7. lenstr의 길이라고 하자.
  8. startpos를 0과 len 사이로 클램프한 결과라고 하자.
  9. resultStringIndexOf(str, searchStr, start)라고 하자.
  10. resultnot-found이면, -1𝔽을 반환한다.
  11. 𝔽(result)를 반환한다.
Note 2

이 메서드는 의도적으로 제네릭이다; 이 메서드는 자신의 this 값이 String 객체일 것을 요구하지 않는다. 따라서 메서드로 사용하기 위해 다른 종류의 객체로 이전될 수 있다.

22.1.3.10 String.prototype.isWellFormed ( )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. thisValuethis 값이라고 하자.
  2. RequireObjectCoercible(thisValue)를 수행한다.
  3. str을 ? ToString(thisValue)라고 하자.
  4. IsStringWellFormedUnicode(str)를 반환한다.

22.1.3.11 String.prototype.lastIndexOf ( searchString [ , position ] )

Note 1

searchString이 이 객체를 String으로 변환한 결과의 부분 문자열로서, position 이하인 하나 이상의 인덱스에 나타나면, 그러한 가장 큰 인덱스가 반환된다; 그렇지 않으면 -1𝔽이 반환된다. positionundefined이면, 전체 String을 검색하기 위해 String 값의 길이가 가정된다.

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. thisValuethis 값이라고 하자.
  2. RequireObjectCoercible(thisValue)를 수행한다.
  3. str을 ? ToString(thisValue)라고 하자.
  4. searchStr을 ? ToString(searchString)라고 하자.
  5. numPos를 ? ToNumber(position)라고 하자.
  6. Assert: positionundefined이면, numPosNaN이다.
  7. numPosNaN이면 pos를 +∞라고 하자; 그렇지 않으면 pos를 ! ToIntegerOrInfinity(numPos)라고 하자.
  8. lenstr의 길이라고 하자.
  9. searchLensearchStr의 길이라고 하자.
  10. len < searchLen이면, -1𝔽을 반환한다.
  11. startpos를 0과 len - searchLen 사이로 클램프한 결과라고 하자.
  12. resultStringLastIndexOf(str, searchStr, start)라고 하자.
  13. resultnot-found이면, -1𝔽을 반환한다.
  14. 𝔽(result)를 반환한다.
Note 2

이 메서드는 의도적으로 제네릭이다; 이 메서드는 자신의 this 값이 String 객체일 것을 요구하지 않는다. 따라서 메서드로 사용하기 위해 다른 종류의 객체로 이전될 수 있다.

22.1.3.12 String.prototype.localeCompare ( that [ , reserved1 [ , reserved2 ] ] )

ECMA-402 국제화 API를 포함하는 ECMAScript 구현은 ECMA-402 명세에 지정된 대로 이 메서드를 구현해야 한다. ECMAScript 구현이 ECMA-402 API를 포함하지 않는 경우 이 메서드에 대한 다음 명세가 사용된다:

이 메서드는 this 값(String str로 변환됨)과 that(String thatValue로 변환됨)의 구현 정의 로캘 민감 String 비교 결과를 나타내는 NaN이 아닌 Number를 반환한다. 결과는 호스트 환경의 현재 로캘 관례에 따른 String 값의 정렬 순서에 대응하도록 의도되어 있으며, strthatValue보다 앞에 정렬되면 음수, strthatValue보다 뒤에 정렬되면 양수, 그 밖의 모든 경우에는 0(strthatValue 사이에 상대적 순서가 없음을 나타냄)이 된다.

비교를 수행하기 전에, 이 메서드는 String들을 준비하기 위해 다음 단계를 수행한다:

  1. thisValuethis 값이라고 하자.
  2. RequireObjectCoercible(thisValue)를 수행한다.
  3. str을 ? ToString(thisValue)라고 하자.
  4. thatValue를 ? ToString(that)라고 하자.

이 메서드의 선택적 두 번째 및 세 번째 매개변수의 의미는 ECMA-402 명세에 정의되어 있다; ECMA-402 지원을 포함하지 않는 구현은 그 매개변수 위치에 다른 어떤 해석도 부여해서는 안 된다.

실제 반환 값은 추가 정보를 인코딩할 수 있도록 구현 정의이지만, 두 인자의 메서드로 간주될 때 이 메서드는 모든 String의 집합에 대한 전순서를 정의하는 일관된 비교자여야 한다. 이 메서드는 또한 Unicode Standard에 따른 정준 동등성을 인식하고 존중해야 하며, 구별 가능한 String들이 정준적으로 동등할 때 +0𝔽을 반환하는 것도 포함한다.

Note 1

후자는 두 인자의 함수를 요구하므로, 이 메서드 자체는 Array.prototype.sort에 대한 인자로 직접 적합하지 않다.

Note 2

이 메서드는 ECMAScript 환경이 호스트 환경으로부터 이용할 수 있는 어떤 언어 및/또는 로캘 민감 비교 기능에 의존할 수 있으며, 호스트 환경의 현재 로캘 관례에 따라 비교하도록 의도되어 있다. 그러나 비교 기능과 관계없이, 이 메서드는 Unicode Standard에 따른 정준 동등성을 인식하고 존중해야 한다. 예를 들어, 다음 비교들은 모두 +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 Standard의 2장과 3장 및 Unicode Standard Annex #15, Unicode Normalization FormsUnicode Technical Note #5, Canonical Equivalence in Applications를 보라. 또한 Unicode Technical Standard #10, Unicode Collation Algorithm도 보라.

이 메서드는 Unicode Standard 3장 3.7절에 정의된 Unicode 호환 동등물 또는 호환 분해를 존중하지 않는 것이 권장된다.

Note 3

이 메서드는 의도적으로 제네릭이다; 이 메서드는 자신의 this 값이 String 객체일 것을 요구하지 않는다. 따라서 메서드로 사용하기 위해 다른 종류의 객체로 이전될 수 있다.

22.1.3.13 String.prototype.match ( regexpOrPattern )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. thisValuethis 값이라고 하자.
  2. RequireObjectCoercible(thisValue)를 수행한다.
  3. regexpOrPattern이 Object이면,
    1. matcher를 ? GetMethod(regexpOrPattern, %Symbol.match%)라고 하자.
    2. matcherundefined가 아니면,
      1. Call(matcher, regexpOrPattern, « thisValue »)를 반환한다.
  4. str을 ? ToString(thisValue)라고 하자.
  5. regexp를 ? RegExpCreate(regexpOrPattern, undefined)라고 하자.
  6. Invoke(regexp, %Symbol.match%, « str »)를 반환한다.
Note

이 메서드는 의도적으로 제네릭이다; 이 메서드는 자신의 this 값이 String 객체일 것을 요구하지 않는다. 따라서 메서드로 사용하기 위해 다른 종류의 객체로 이전될 수 있다.

22.1.3.14 String.prototype.matchAll ( regexpOrPattern )

이 메서드는 this 값을 나타내는 String을 regexpOrPattern에 대해 정규 표현식 매칭하고, 매치 결과를 산출하는 반복자를 반환한다. 각 매치 결과는 String의 매치된 부분을 첫 번째 요소로 포함하고, 이어서 캡처 그룹에 의해 매치된 부분들을 포함하는 Array이다. 정규 표현식이 전혀 매치되지 않으면, 반환된 반복자는 어떤 매치 결과도 산출하지 않는다.

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. thisValuethis 값이라고 하자.
  2. RequireObjectCoercible(thisValue)를 수행한다.
  3. regexpOrPattern이 Object이면,
    1. isRegExp를 ? IsRegExp(regexpOrPattern)라고 하자.
    2. isRegExptrue이면,
      1. flags를 ? Get(regexpOrPattern, "flags")라고 하자.
      2. RequireObjectCoercible(flags)를 수행한다.
      3. ToString(flags)가 "g"를 포함하지 않으면, TypeError 예외를 던진다.
    3. matcher를 ? GetMethod(regexpOrPattern, %Symbol.matchAll%)라고 하자.
    4. matcherundefined가 아니면,
      1. Call(matcher, regexpOrPattern, « thisValue »)를 반환한다.
  4. str을 ? ToString(thisValue)라고 하자.
  5. regexp를 ? RegExpCreate(regexpOrPattern, "g")라고 하자.
  6. Invoke(regexp, %Symbol.matchAll%, « str »)를 반환한다.
Note 1
이 메서드는 의도적으로 제네릭이다. 이 메서드는 자신의 this 값이 String 객체일 것을 요구하지 않는다. 따라서 메서드로 사용하기 위해 다른 종류의 객체로 이전될 수 있다.
Note 2
String.prototype.split과 유사하게, String.prototype.matchAll은 일반적으로 입력을 변경하지 않고 동작하도록 설계되어 있다.

22.1.3.15 String.prototype.normalize ( [ form ] )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. thisValuethis 값이라고 하자.
  2. RequireObjectCoercible(thisValue)를 수행한다.
  3. str을 ? ToString(thisValue)라고 하자.
  4. formundefined이면, f"NFC"라고 하자.
  5. 그렇지 않으면, f를 ? ToString(form)이라고 하자.
  6. f"NFC", "NFD", "NFKC", 또는 "NFKD" 중 하나가 아니면, RangeError 예외를 던진다.
  7. ns최신 Unicode Standard, Normalization Forms에 지정된 대로 f가 이름 붙인 정규화 형식으로 str을 정규화한 결과인 String 값이라고 하자.
  8. ns를 반환한다.
Note

이 메서드는 의도적으로 제네릭이다; 이 메서드는 자신의 this 값이 String 객체일 것을 요구하지 않는다. 따라서 메서드로 사용하기 위해 다른 종류의 객체로 이전될 수 있다.

22.1.3.16 String.prototype.padEnd ( maxLength [ , fillString ] )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. thisValuethis 값이라고 하자.
  2. RequireObjectCoercible(thisValue)를 수행한다.
  3. StringPaddingBuiltinsImpl(thisValue, maxLength, fillString, end)를 반환한다.

22.1.3.17 String.prototype.padStart ( maxLength [ , fillString ] )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. thisValuethis 값이라고 하자.
  2. RequireObjectCoercible(thisValue)를 수행한다.
  3. StringPaddingBuiltinsImpl(thisValue, maxLength, fillString, start)를 반환한다.

22.1.3.17.1 StringPaddingBuiltinsImpl ( thisValue, maxLength, fillString, placement )

The abstract operation StringPaddingBuiltinsImpl takes arguments thisValue (an ECMAScript language value), maxLength (an ECMAScript language value), fillString (an ECMAScript language value), and placement (start or end) and returns either a normal completion containing a String or a throw completion. It performs the following steps when called:

  1. str을 ? ToString(thisValue)라고 하자.
  2. intMaxLength(? ToLength(maxLength))라고 하자.
  3. stringLengthstr의 길이라고 하자.
  4. intMaxLengthstringLength이면, str을 반환한다.
  5. fillStringundefined이면, fillString을 코드 단위 0x0020 (SPACE)만으로 구성된 String 값으로 설정한다.
  6. 그렇지 않으면, fillString을 ? ToString(fillString)으로 설정한다.
  7. StringPad(str, intMaxLength, fillString, placement)를 반환한다.

22.1.3.17.2 StringPad ( str, maxLength, fillString, placement )

The abstract operation StringPad takes arguments str (a String), maxLength (a non-negative integer), fillString (a String), and placement (start or end) and returns a String. It performs the following steps when called:

  1. stringLengthstr의 길이라고 하자.
  2. maxLengthstringLength이면, str을 반환한다.
  3. fillString이 빈 String이면, str을 반환한다.
  4. fillLenmaxLength - stringLength라고 하자.
  5. truncatedStringFillerfillString의 반복 연결로 구성되고 길이 fillLen으로 잘린 String 값이라고 하자.
  6. placementstart이면, truncatedStringFillerstr의 문자열 연결을 반환한다.
  7. strtruncatedStringFiller의 문자열 연결을 반환한다.
Note 1

인자 maxLengthstr의 길이보다 작을 수 없도록 클램프된다.

Note 2

인자 fillString의 기본값은 " " (코드 단위 0x0020 SPACE로 구성된 String 값)이다.

22.1.3.17.3 ToZeroPaddedDecimalString ( n, minLength )

The abstract operation ToZeroPaddedDecimalString takes arguments n (a non-negative integer) and minLength (a non-negative integer) and returns a String. It performs the following steps when called:

  1. strn의 String 표현, 즉 십진수로 형식화된 표현이라고 하자.
  2. StringPad(str, minLength, "0", start)를 반환한다.

22.1.3.18 String.prototype.repeat ( count )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. thisValuethis 값이라고 하자.
  2. RequireObjectCoercible(thisValue)를 수행한다.
  3. str을 ? ToString(thisValue)라고 하자.
  4. n을 ? ToIntegerOrInfinity(count)라고 하자.
  5. n < 0이거나 n = +∞이면, RangeError 예외를 던진다.
  6. n = 0이면, 빈 String을 반환한다.
  7. strn개 사본을 함께 이어 붙여 만든 String 값을 반환한다.
Note 1

이 메서드는 this 값(String으로 변환됨)의 코드 단위들이 count번 반복된 String 값을 생성한다.

Note 2

이 메서드는 의도적으로 제네릭이다; 이 메서드는 자신의 this 값이 String 객체일 것을 요구하지 않는다. 따라서 메서드로 사용하기 위해 다른 종류의 객체로 이전될 수 있다.

22.1.3.19 String.prototype.replace ( searchValue, replaceValue )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. thisValuethis 값이라고 하자.
  2. RequireObjectCoercible(thisValue)를 수행한다.
  3. searchValue가 Object이면,
    1. replacer를 ? GetMethod(searchValue, %Symbol.replace%)라고 하자.
    2. replacerundefined가 아니면,
      1. Call(replacer, searchValue, « thisValue, replaceValue »)를 반환한다.
  4. string을 ? ToString(thisValue)라고 하자.
  5. searchString을 ? ToString(searchValue)라고 하자.
  6. functionalReplaceIsCallable(replaceValue)라고 하자.
  7. functionalReplacefalse이면,
    1. replaceValue를 ? ToString(replaceValue)로 설정한다.
  8. searchLengthsearchString의 길이라고 하자.
  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. Assert: replaceValue는 String이다.
    2. captures를 새로운 빈 List라고 하자.
    3. replacement를 ! GetSubstitution(searchString, string, position, captures, undefined, replaceValue)라고 하자.
  15. preceding, replacement, 및 following의 문자열 연결을 반환한다.
Note

이 메서드는 의도적으로 제네릭이다; 이 메서드는 자신의 this 값이 String 객체일 것을 요구하지 않는다. 따라서 메서드로 사용하기 위해 다른 종류의 객체로 이전될 수 있다.

22.1.3.19.1 GetSubstitution ( matched, str, position, captures, namedCaptures, replacementTemplate )

The abstract operation GetSubstitution takes arguments matched (a String), str (a String), position (a non-negative integer), captures (a List of either Strings or undefined), namedCaptures (an Object or undefined), and replacementTemplate (a String) and returns either a normal completion containing a String or a throw completion. 이 추상 연산의 목적상, 십진 숫자는 0x0030 (DIGIT ZERO)부터 0x0039 (DIGIT NINE)까지의 포함 구간에 있는 코드 단위이다. It performs the following steps when called:

  1. stringLengthstr의 길이라고 하자.
  2. Assert: positionstringLength.
  3. result를 빈 String이라고 하자.
  4. templateRemainderreplacementTemplate이라고 하자.
  5. templateRemainder가 빈 String이 아닌 동안 반복한다.
    1. NOTE: 다음 단계들은 ref(templateRemainder의 접두사)를 분리하고, refReplacement(그 대체)를 결정한 다음, 그 대체를 result에 덧붙인다.
    2. templateRemainder"$$"로 시작하면,
      1. ref"$$"라고 하자.
      2. refReplacement"$"라고 하자.
    3. 그렇지 않고 templateRemainder"$`"로 시작하면,
      1. ref"$`"라고 하자.
      2. refReplacementstr의 0부터 position까지의 부분 문자열이라고 하자.
    4. 그렇지 않고 templateRemainder"$&"로 시작하면,
      1. ref"$&"라고 하자.
      2. refReplacementmatched라고 하자.
    5. 그렇지 않고 templateRemainder"$'" (0x0024 (DOLLAR SIGN) 뒤에 0x0027 (APOSTROPHE))로 시작하면,
      1. ref"$'"라고 하자.
      2. matchLengthmatched의 길이라고 하자.
      3. tailPosposition + matchLength라고 하자.
      4. refReplacementstrmin(tailPos, stringLength)부터의 부분 문자열이라고 하자.
      5. NOTE: tailPos는 이 추상 연산"exec" 속성이 내장 %RegExp.prototype.exec%가 아닌 객체에 대한 %RegExp.prototype%의 내장 %Symbol.replace% 메서드 호출에 의해 호출된 경우에만 stringLength를 초과할 수 있다.
    6. 그렇지 않고 templateRemainder"$" 뒤에 1개 이상의 십진 숫자가 이어지는 것으로 시작하면,
      1. templateRemainder"$" 뒤에 2개 이상의 십진 숫자가 이어지는 것으로 시작하면 digitCount를 2라고 하자; 그렇지 않으면 digitCount를 1이라고 하자.
      2. digitstemplateRemainder의 1부터 1 + digitCount까지의 부분 문자열이라고 하자.
      3. index(StringToNumber(digits))라고 하자.
      4. Assert: 0 ≤ index ≤ 99.
      5. captureLencaptures의 요소 개수라고 하자.
      6. index > captureLen이고 digitCount = 2이면,
        1. NOTE: 두 자리 대체 패턴이 캡처링 그룹 수를 초과하는 인덱스를 지정하면, 한 자리 대체 패턴 뒤에 리터럴 숫자가 이어지는 것으로 취급된다.
        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를 빈 String이라고 하자.
        3. 그렇지 않으면,
          1. refReplacementcapture라고 하자.
      9. 그렇지 않으면,
        1. refReplacementref라고 하자.
    7. 그렇지 않고 templateRemainder"$<"로 시작하면,
      1. gtPosStringIndexOf(templateRemainder, ">", 0)이라고 하자.
      2. gtPosnot-found이거나 namedCapturesundefined이면,
        1. ref"$<"라고 하자.
        2. refReplacementref라고 하자.
      3. 그렇지 않으면,
        1. reftemplateRemainder의 0부터 gtPos + 1까지의 부분 문자열이라고 하자.
        2. groupNametemplateRemainder의 2부터 gtPos까지의 부분 문자열이라고 하자.
        3. Assert: namedCaptures는 Object이다.
        4. capture를 ? Get(namedCaptures, groupName)라고 하자.
        5. captureundefined이면,
          1. refReplacement를 빈 String이라고 하자.
        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. thisValuethis 값이라고 하자.
  2. RequireObjectCoercible(thisValue)를 수행한다.
  3. searchValue가 Object이면,
    1. isRegExp를 ? IsRegExp(searchValue)라고 하자.
    2. isRegExptrue이면,
      1. flags를 ? Get(searchValue, "flags")라고 하자.
      2. RequireObjectCoercible(flags)를 수행한다.
      3. ToString(flags)가 "g"를 포함하지 않으면, TypeError 예외를 던진다.
    3. replacer를 ? GetMethod(searchValue, %Symbol.replace%)라고 하자.
    4. replacerundefined가 아니면,
      1. Call(replacer, searchValue, « thisValue, replaceValue »)를 반환한다.
  4. string을 ? ToString(thisValue)라고 하자.
  5. searchString을 ? ToString(searchValue)라고 하자.
  6. functionalReplaceIsCallable(replaceValue)라고 하자.
  7. functionalReplacefalse이면,
    1. replaceValue를 ? ToString(replaceValue)로 설정한다.
  8. searchLengthsearchString의 길이라고 하자.
  9. advanceBymax(1, searchLength)라고 하자.
  10. matchPositions를 새로운 빈 List라고 하자.
  11. positionStringIndexOf(string, searchString, 0)이라고 하자.
  12. positionnot-found가 아닌 동안 반복한다.
    1. positionmatchPositions에 추가한다.
    2. positionStringIndexOf(string, searchString, position + advanceBy)로 설정한다.
  13. endOfLastMatch를 0이라고 하자.
  14. result를 빈 String이라고 하자.
  15. matchPositions의 각 요소 matchPosition에 대해, 다음을 수행한다.
    1. preservedstringendOfLastMatch부터 matchPosition까지의 부분 문자열이라고 하자.
    2. functionalReplacetrue이면,
      1. replacement를 ? ToString(? Call(replaceValue, undefined, « searchString, 𝔽(matchPosition), string »))라고 하자.
    3. 그렇지 않으면,
      1. Assert: replaceValue는 String이다.
      2. captures를 새로운 빈 List라고 하자.
      3. replacement를 ! GetSubstitution(searchString, string, matchPosition, captures, undefined, replaceValue)라고 하자.
    4. resultresult, preserved, 및 replacement의 문자열 연결로 설정한다.
    5. endOfLastMatchmatchPosition + searchLength로 설정한다.
  16. endOfLastMatch < string의 길이면,
    1. resultresultstringendOfLastMatch부터의 부분 문자열의 문자열 연결로 설정한다.
  17. result를 반환한다.

22.1.3.21 String.prototype.search ( regexpOrPattern )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. thisValuethis 값이라고 하자.
  2. RequireObjectCoercible(thisValue)를 수행한다.
  3. regexpOrPattern이 Object이면,
    1. searcher를 ? GetMethod(regexpOrPattern, %Symbol.search%)라고 하자.
    2. searcherundefined가 아니면,
      1. Call(searcher, regexpOrPattern, « thisValue »)를 반환한다.
  4. string을 ? ToString(thisValue)라고 하자.
  5. regexp를 ? RegExpCreate(regexpOrPattern, undefined)라고 하자.
  6. Invoke(regexp, %Symbol.search%, « string »)를 반환한다.
Note

이 메서드는 의도적으로 제네릭이다; 이 메서드는 자신의 this 값이 String 객체일 것을 요구하지 않는다. 따라서 메서드로 사용하기 위해 다른 종류의 객체로 이전될 수 있다.

22.1.3.22 String.prototype.slice ( start, end )

이 메서드는 이 객체를 String으로 변환한 결과의 부분 문자열을 반환한다. 이 부분 문자열은 인덱스 start에서 시작하여 인덱스 end까지 진행하되 end는 포함하지 않는다(또는 endundefined이면 String의 끝까지). start가 음수이면, String의 길이인 sourceLength에 대해 sourceLength + start로 취급된다. end가 음수이면, String의 길이인 sourceLength에 대해 sourceLength + end로 취급된다. 결과는 String 객체가 아니라 String 값이다.

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. thisValuethis 값이라고 하자.
  2. RequireObjectCoercible(thisValue)를 수행한다.
  3. str을 ? ToString(thisValue)라고 하자.
  4. lenstr의 길이라고 하자.
  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이면, 빈 String을 반환한다.
  14. strfrom부터 to까지의 부분 문자열을 반환한다.
Note

이 메서드는 의도적으로 제네릭이다; 이 메서드는 자신의 this 값이 String 객체일 것을 요구하지 않는다. 따라서 메서드로 사용하기 위해 다른 종류의 객체로 이전될 수 있다.

22.1.3.23 String.prototype.split ( separator, limit )

이 메서드는 이 객체를 String으로 변환한 결과의 부분 문자열들이 저장된 Array를 반환한다. 부분 문자열들은 separator의 출현을 왼쪽에서 오른쪽으로 검색하여 결정된다; 이러한 출현들은 반환된 배열 안의 어떤 String의 일부도 아니지만, String 값을 나누는 역할을 한다. separator의 값은 임의 길이의 String일 수도 있고, RegExp처럼 %Symbol.split% 메서드를 가진 객체일 수도 있다.

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. thisValuethis 값이라고 하자.
  2. RequireObjectCoercible(thisValue)를 수행한다.
  3. separator가 Object이면,
    1. splitter를 ? GetMethod(separator, %Symbol.split%)라고 하자.
    2. splitterundefined가 아니면,
      1. Call(splitter, separator, « thisValue, limit »)를 반환한다.
  4. str을 ? ToString(thisValue)라고 하자.
  5. limitundefined이면 lim을 232 - 1이라고 하자; 그렇지 않으면 lim(? ToUint32(limit))라고 하자.
  6. separatorStr을 ? ToString(separator)라고 하자.
  7. lim = 0이면,
    1. CreateArrayFromList(« »)를 반환한다.
  8. separatorundefined이면,
    1. CreateArrayFromListstr »)를 반환한다.
  9. separatorLengthseparatorStr의 길이라고 하자.
  10. separatorLength = 0이면,
    1. strLenstr의 길이라고 하자.
    2. outLenlim을 0과 strLen 사이로 클램프한 결과라고 하자.
    3. headstr의 0부터 outLen까지의 부분 문자열이라고 하자.
    4. codeUnitshead의 요소인 코드 단위들의 시퀀스로 구성된 List라고 하자.
    5. CreateArrayFromList(codeUnits)를 반환한다.
  11. str이 빈 String이면, CreateArrayFromListstr »)를 반환한다.
  12. substrings를 새로운 빈 List라고 하자.
  13. searchStart를 0이라고 하자.
  14. matchIndexStringIndexOf(str, separatorStr, 0)이라고 하자.
  15. matchIndexnot-found가 아닌 동안 반복한다.
    1. substringstrsearchStart부터 matchIndex까지의 부분 문자열이라고 하자.
    2. substringsubstrings에 추가한다.
    3. substrings의 요소 개수가 lim이면, CreateArrayFromList(substrings)를 반환한다.
    4. searchStartmatchIndex + separatorLength로 설정한다.
    5. matchIndexStringIndexOf(str, separatorStr, searchStart)로 설정한다.
  16. substringstrsearchStart부터의 부분 문자열이라고 하자.
  17. substringsubstrings에 추가한다.
  18. CreateArrayFromList(substrings)를 반환한다.
Note 1

separator의 값은 빈 String일 수 있다. 이 경우 separator는 입력 String의 시작이나 끝에 있는 빈 부분 문자열과 매치되지 않으며, 이전 구분자 매치의 끝에 있는 빈 부분 문자열과도 매치되지 않는다. separator가 빈 String이면, String은 개별 코드 단위 요소들로 분할된다; 결과 배열의 길이는 String의 길이와 같으며, 각 부분 문자열은 하나의 코드 단위를 포함한다.

this 값이 빈 String이거나 빈 String으로 변환되는 경우, 결과는 separator가 빈 String과 매치될 수 있는지에 따라 달라진다. 매치될 수 있으면 결과 배열은 요소를 포함하지 않는다. 그렇지 않으면 결과 배열은 빈 String인 하나의 요소를 포함한다.

separatorundefined이면, 결과 배열은 this 값(String으로 변환됨)인 하나의 String만 포함한다. limitundefined가 아니면, 출력 배열은 limit개 이하의 요소만 포함하도록 잘린다.

Note 2

이 메서드는 의도적으로 제네릭이다; 이 메서드는 자신의 this 값이 String 객체일 것을 요구하지 않는다. 따라서 메서드로 사용하기 위해 다른 종류의 객체로 이전될 수 있다.

22.1.3.24 String.prototype.startsWith ( searchString [ , position ] )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. thisValuethis 값이라고 하자.
  2. RequireObjectCoercible(thisValue)를 수행한다.
  3. str을 ? ToString(thisValue)라고 하자.
  4. isRegExp를 ? IsRegExp(searchString)라고 하자.
  5. isRegExptrue이면, TypeError 예외를 던진다.
  6. searchStr을 ? ToString(searchString)라고 하자.
  7. lenstr의 길이라고 하자.
  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. substringstrstart부터 end까지의 부분 문자열이라고 하자.
  15. substringsearchStr이면, true를 반환한다.
  16. false를 반환한다.
Note 1

첫 번째 인자가 RegExp이면 예외를 던지도록 지정된 것은 그러한 인자 값을 허용하는 확장을 미래 판에서 정의할 수 있게 하기 위한 것이다.

Note 2

이 메서드는 의도적으로 제네릭이다; 이 메서드는 자신의 this 값이 String 객체일 것을 요구하지 않는다. 따라서 메서드로 사용하기 위해 다른 종류의 객체로 이전될 수 있다.

22.1.3.25 String.prototype.substring ( start, end )

이 메서드는 이 객체를 String으로 변환한 결과의 부분 문자열을 반환한다. 이 부분 문자열은 인덱스 start에서 시작하여 String의 인덱스 end까지 진행하되 end는 포함하지 않는다(또는 endundefined이면 String의 끝까지). 결과는 String 객체가 아니라 String 값이다.

어느 인자든 NaN이거나 음수이면 0으로 대체된다; 어느 인자든 String의 길이보다 엄격히 크면 String의 길이로 대체된다.

startend보다 엄격히 크면, 둘은 서로 바뀐다.

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. thisValuethis 값이라고 하자.
  2. RequireObjectCoercible(thisValue)를 수행한다.
  3. str을 ? ToString(thisValue)라고 하자.
  4. lenstr의 길이라고 하자.
  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. strfrom부터 to까지의 부분 문자열을 반환한다.
Note

이 메서드는 의도적으로 제네릭이다; 이 메서드는 자신의 this 값이 String 객체일 것을 요구하지 않는다. 따라서 메서드로 사용하기 위해 다른 종류의 객체로 이전될 수 있다.

22.1.3.26 String.prototype.toLocaleLowerCase ( [ reserved1 [ , reserved2 ] ] )

ECMA-402 국제화 API를 포함하는 ECMAScript 구현은 ECMA-402 명세에 지정된 대로 이 메서드를 구현해야 한다. ECMAScript 구현이 ECMA-402 API를 포함하지 않는 경우 이 메서드에 대한 다음 명세가 사용된다:

이 메서드는 6.1.4에 설명된 대로 String 값을 UTF-16으로 인코딩된 코드 포인트들의 시퀀스로 해석한다.

이 메서드는 호스트 환경의 현재 로캘 관례에 대응하는 로캘 민감 결과를 산출하도록 의도된다는 점을 제외하면 toLowerCase와 정확히 동일하게 동작한다. 해당 언어의 규칙이 일반 Unicode 대소문자 매핑과 충돌하는 몇몇 경우(예: 터키어)에만 차이가 있다.

이 메서드의 선택적 매개변수의 의미는 ECMA-402 명세에 정의되어 있다; ECMA-402 지원을 포함하지 않는 구현은 그 매개변수 위치를 다른 어떤 용도로도 사용해서는 안 된다.

Note

이 메서드는 의도적으로 제네릭이다; 이 메서드는 자신의 this 값이 String 객체일 것을 요구하지 않는다. 따라서 메서드로 사용하기 위해 다른 종류의 객체로 이전될 수 있다.

22.1.3.27 String.prototype.toLocaleUpperCase ( [ reserved1 [ , reserved2 ] ] )

ECMA-402 국제화 API를 포함하는 ECMAScript 구현은 ECMA-402 명세에 지정된 대로 이 메서드를 구현해야 한다. ECMAScript 구현이 ECMA-402 API를 포함하지 않는 경우 이 메서드에 대한 다음 명세가 사용된다:

이 메서드는 6.1.4에 설명된 대로 String 값을 UTF-16으로 인코딩된 코드 포인트들의 시퀀스로 해석한다.

이 메서드는 호스트 환경의 현재 로캘 관례에 대응하는 로캘 민감 결과를 산출하도록 의도된다는 점을 제외하면 toUpperCase와 정확히 동일하게 동작한다. 해당 언어의 규칙이 일반 Unicode 대소문자 매핑과 충돌하는 몇몇 경우(예: 터키어)에만 차이가 있다.

이 메서드의 선택적 매개변수의 의미는 ECMA-402 명세에 정의되어 있다; ECMA-402 지원을 포함하지 않는 구현은 그 매개변수 위치를 다른 어떤 용도로도 사용해서는 안 된다.

Note

이 메서드는 의도적으로 제네릭이다; 이 메서드는 자신의 this 값이 String 객체일 것을 요구하지 않는다. 따라서 메서드로 사용하기 위해 다른 종류의 객체로 이전될 수 있다.

22.1.3.28 String.prototype.toLowerCase ( )

이 메서드는 6.1.4에 설명된 대로 String 값을 UTF-16으로 인코딩된 코드 포인트들의 시퀀스로 해석한다.

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. thisValuethis 값이라고 하자.
  2. RequireObjectCoercible(thisValue)를 수행한다.
  3. str을 ? ToString(thisValue)라고 하자.
  4. sTextStringToCodePoints(str)라고 하자.
  5. lowerText를 Unicode Default Case Conversion 알고리즘에 따라 toLowercase(sText)라고 하자.
  6. lowercaseStringCodePointsToString(lowerText)라고 하자.
  7. lowercaseString을 반환한다.

결과는 Unicode Character Database의 로캘 비민감 대소문자 매핑에 따라 도출되어야 한다(이는 UnicodeData.txt 파일뿐만 아니라 그와 함께 제공되는 SpecialCasing.txt 파일의 모든 로캘 비민감 매핑도 명시적으로 포함한다).

Note 1

일부 코드 포인트의 대소문자 매핑은 여러 코드 포인트를 생성할 수 있다. 이 경우 결과 String은 원본 String과 같은 길이가 아닐 수 있다. toUpperCasetoLowerCase 모두 문맥 민감 동작을 가지므로, 이 메서드들은 대칭적이지 않다. 다시 말해, s.toUpperCase().toLowerCase()는 반드시 s.toLowerCase()와 같지는 않다.

Note 2

이 메서드는 의도적으로 제네릭이다; 이 메서드는 자신의 this 값이 String 객체일 것을 요구하지 않는다. 따라서 메서드로 사용하기 위해 다른 종류의 객체로 이전될 수 있다.

22.1.3.29 String.prototype.toString ( )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. ThisStringValue(this value)를 반환한다.
Note

String 객체의 경우, 이 메서드는 우연히 valueOf 메서드와 같은 것을 반환한다.

22.1.3.30 String.prototype.toUpperCase ( )

이 메서드는 6.1.4에 설명된 대로 String 값을 UTF-16으로 인코딩된 코드 포인트들의 시퀀스로 해석한다.

String이 Unicode Default Case Conversion의 toUppercase 알고리즘을 사용해 매핑된다는 점을 제외하면, 이 메서드는 String.prototype.toLowerCase와 정확히 같은 방식으로 동작한다.

Note

이 메서드는 의도적으로 제네릭이다; 이 메서드는 자신의 this 값이 String 객체일 것을 요구하지 않는다. 따라서 메서드로 사용하기 위해 다른 종류의 객체로 이전될 수 있다.

22.1.3.31 String.prototype.toWellFormed ( )

이 메서드는 서로게이트 쌍의 일부가 아닌 모든 선행 서로게이트와 후행 서로게이트가 U+FFFD (REPLACEMENT CHARACTER)로 대체된 이 객체의 String 표현을 반환한다.

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. thisValuethis 값이라고 하자.
  2. RequireObjectCoercible(thisValue)를 수행한다.
  3. str을 ? ToString(thisValue)라고 하자.
  4. strLenstr의 길이라고 하자.
  5. k를 0이라고 하자.
  6. result를 빈 String이라고 하자.
  7. k < strLen인 동안 반복한다.
    1. cpCodePointAt(str, k)라고 하자.
    2. cp.[[IsUnpairedSurrogate]]true이면,
      1. resultresult와 0xFFFD (REPLACEMENT CHARACTER)의 문자열 연결로 설정한다.
    3. 그렇지 않으면,
      1. resultresultUTF16EncodeCodePoint(cp.[[CodePoint]])의 문자열 연결로 설정한다.
    4. kk + cp.[[CodeUnitCount]]로 설정한다.
  8. result를 반환한다.

22.1.3.32 String.prototype.trim ( )

이 메서드는 6.1.4에 설명된 대로 String 값을 UTF-16으로 인코딩된 코드 포인트들의 시퀀스로 해석한다.

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. thisValuethis 값이라고 하자.
  2. TrimString(thisValue, start+end)를 반환한다.
Note

이 메서드는 의도적으로 제네릭이다; 이 메서드는 자신의 this 값이 String 객체일 것을 요구하지 않는다. 따라서 메서드로 사용하기 위해 다른 종류의 객체로 이전될 수 있다.

22.1.3.32.1 TrimString ( string, where )

The abstract operation TrimString takes arguments string (an ECMAScript language value) and where (start, end, or start+end) and returns either a normal completion containing a String or a throw completion. 이 연산은 6.1.4에 설명된 대로 string을 UTF-16으로 인코딩된 코드 포인트들의 시퀀스로 해석한다. It performs the following steps when called:

  1. RequireObjectCoercible(string)를 수행한다.
  2. str을 ? ToString(string)라고 하자.
  3. wherestart이면,
    1. trimmedStringstr의 선행 공백 문자가 제거된 복사본인 String 값이라고 하자.
  4. 그렇지 않고 whereend이면,
    1. trimmedStringstr의 후행 공백 문자가 제거된 복사본인 String 값이라고 하자.
  5. 그렇지 않으면,
    1. Assert: wherestart+end이다.
    2. trimmedStringstr의 선행 및 후행 공백 문자가 모두 제거된 복사본인 String 값이라고 하자.
  6. trimmedString을 반환한다.

공백 문자의 정의는 WhiteSpaceLineTerminator의 합집합이다. Unicode 코드 포인트가 Unicode 일반 범주 “Space_Separator” (“Zs”)에 속하는지 결정할 때, 코드 단위 시퀀스는 6.1.4에 지정된 대로 UTF-16으로 인코딩된 코드 포인트 시퀀스로 해석된다.

22.1.3.33 String.prototype.trimEnd ( )

이 메서드는 6.1.4에 설명된 대로 String 값을 UTF-16으로 인코딩된 코드 포인트들의 시퀀스로 해석한다.

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. strthis 값이라고 하자.
  2. TrimString(str, end)를 반환한다.
Note

이 메서드는 의도적으로 제네릭이다; 이 메서드는 자신의 this 값이 String 객체일 것을 요구하지 않는다. 따라서 메서드로 사용하기 위해 다른 종류의 객체로 이전될 수 있다.

22.1.3.34 String.prototype.trimStart ( )

이 메서드는 6.1.4에 설명된 대로 String 값을 UTF-16으로 인코딩된 코드 포인트들의 시퀀스로 해석한다.

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. strthis 값이라고 하자.
  2. TrimString(str, start)를 반환한다.
Note

이 메서드는 의도적으로 제네릭이다; 이 메서드는 자신의 this 값이 String 객체일 것을 요구하지 않는다. 따라서 메서드로 사용하기 위해 다른 종류의 객체로 이전될 수 있다.

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 (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. value가 String이면, value를 반환한다.
  2. value가 Object이고 value[[StringData]] 내부 슬롯을 가지면,
    1. strvalue.[[StringData]]라고 하자.
    2. Assert: str은 String이다.
    3. str을 반환한다.
  3. TypeError 예외를 던진다.

22.1.3.36 String.prototype [ %Symbol.iterator% ] ( )

이 메서드는 String 값의 코드 포인트들을 반복하고 각 코드 포인트를 String 값으로 반환하는 반복자 객체를 반환한다.

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. strthis 값이라고 하자.
  2. RequireObjectCoercible(str)를 수행한다.
  3. str을 ? ToString(str)로 설정한다.
  4. closure를 매개변수가 없고 str을 캡처하며 호출될 때 다음 단계를 수행하는 새로운 Abstract Closure라고 하자:
    1. lenstr의 길이라고 하자.
    2. position을 0이라고 하자.
    3. position < len인 동안 반복한다.
      1. cpCodePointAt(str, position)라고 하자.
      2. nextIndexposition + cp.[[CodeUnitCount]]라고 하자.
      3. resultStringstrposition부터 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 특수 객체이며 그러한 객체에 대해 지정된 내부 메서드를 가진다. String 인스턴스는 String 프로토타입 객체로부터 속성을 상속한다. String 인스턴스는 또한 [[StringData]] 내부 슬롯을 가진다. [[StringData]] 내부 슬롯은 이 String 객체가 나타내는 String 값이다.

String 인스턴스는 "length" 속성과, 정수 인덱스 이름을 가진 열거 가능한 속성들의 집합을 가진다.

22.1.4.1 length

이 String 객체가 나타내는 String 값의 요소 개수.

String 객체가 초기화되면, 이 속성은 변하지 않는다. 이 속성은 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false } 속성 특성을 가진다.

22.1.5 String Iterator 객체

String Iterator는 특정 String 인스턴스 객체에 대한 특정 반복을 나타내는 객체이다. String Iterator 객체에는 이름 있는 생성자가 없다. 대신, String Iterator 객체는 String 인스턴스 객체의 특정 메서드를 호출하여 생성된다.

22.1.5.1 %StringIteratorPrototype% 객체

%StringIteratorPrototype% 객체는:

  • 모든 String Iterator 객체가 상속하는 속성들을 가진다.
  • 보통 객체이다.
  • 값이 %Iterator.prototype%[[Prototype]] 내부 슬롯을 가진다.
  • 다음 속성들을 가진다:

22.1.5.1.1 %StringIteratorPrototype%.next ( )

  1. GeneratorResume(this value, empty, "%StringIteratorPrototype%")를 반환한다.

22.1.5.1.2 %StringIteratorPrototype% [ %Symbol.toStringTag% ]

%Symbol.toStringTag% 속성의 초기값은 String 값 "String Iterator"이다.

이 속성은 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true } 속성 특성을 가진다.

22.2 RegExp (정규 표현식) 객체

RegExp 객체는 정규 표현식과 관련 플래그를 포함한다.

Note

정규 표현식의 형식과 기능은 Perl 5 프로그래밍 언어의 정규 표현식 기능을 모델로 한다.

22.2.1 패턴

RegExp 생성자는 입력 패턴 String에 다음 문법을 적용한다. 문법이 해당 String을 Pattern의 전개로 해석할 수 없으면 오류가 발생한다.

구문

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 정적 의미론: 조기 오류

Note

이 절은 B.1.2.1에서 수정된다.

Pattern :: Disjunction QuantifierPrefix :: { DecimalDigits , DecimalDigits } Atom :: (? RegularExpressionModifiers : Disjunction ) Atom :: (? RegularExpressionModifiers - RegularExpressionModifiers : Disjunction ) AtomEscape :: k GroupName AtomEscape :: DecimalEscape NonemptyClassRanges :: ClassAtom - ClassAtom ClassContents NonemptyClassRangesNoDash :: ClassAtomNoDash - ClassAtom ClassContents RegExpIdentifierStart :: \ RegExpUnicodeEscapeSequence RegExpIdentifierStart :: UnicodeLeadSurrogate UnicodeTrailSurrogate RegExpIdentifierPart :: \ RegExpUnicodeEscapeSequence RegExpIdentifierPart :: UnicodeLeadSurrogate UnicodeTrailSurrogate UnicodePropertyValueExpression :: UnicodePropertyName = UnicodePropertyValue UnicodePropertyValueExpression :: LoneUnicodePropertyNameOrValue CharacterClassEscape :: P{ UnicodePropertyValueExpression } CharacterClass :: [^ ClassContents ] NestedClass :: [^ ClassContents ] ClassSetRange :: ClassSetCharacter - ClassSetCharacter

22.2.1.2 Static Semantics: CountLeftCapturingParensWithin ( node )

The abstract operation CountLeftCapturingParensWithin takes argument node (a Parse Node) and returns a non-negative integer. 이 연산은 node 안의 왼쪽 캡처 괄호의 수를 반환한다. 왼쪽 캡처 괄호 Atom :: ( GroupSpecifieropt Disjunction ) 생성식의 ( 터미널과 일치한 임의의 ( 패턴 문자이다.

Note

이 절은 B.1.2.2에서 수정된다.

It performs the following steps when called:

  1. Assert: nodeRegExp Pattern 문법 안의 생성식의 인스턴스이다.
  2. node 안에 포함된 Atom :: ( GroupSpecifieropt Disjunction ) Parse Node의 수를 반환한다.

22.2.1.3 Static Semantics: CountLeftCapturingParensBefore ( node )

The abstract operation CountLeftCapturingParensBefore takes argument node (a Parse Node) and returns a non-negative integer. 이 연산은 둘러싸는 패턴 안에서 node의 왼쪽에 나타나는 왼쪽 캡처 괄호의 수를 반환한다.

Note

이 절은 B.1.2.2에서 수정된다.

It performs the following steps when called:

  1. Assert: nodeRegExp Pattern 문법 안의 생성식의 인스턴스이다.
  2. patternnode를 포함하는 Pattern이라고 하자.
  3. pattern 안에 포함된 Atom :: ( GroupSpecifieropt Disjunction ) Parse Node 중 node보다 앞에 나타나거나 node를 포함하는 것의 수를 반환한다.

22.2.1.4 Static Semantics: MightBothParticipate ( x, y )

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

  1. Assert: xy는 같은 둘러싸는 Pattern을 가진다.
  2. 둘러싸는 Pattern Disjunction :: Alternative | Disjunction Parse Node를 포함하고, xAlternative 안에 포함되며 y가 파생된 Disjunction 안에 포함되거나, x가 파생된 Disjunction 안에 포함되며 yAlternative 안에 포함되면, false를 반환한다.
  3. true를 반환한다.

22.2.1.5 Static Semantics: CapturingGroupNumber

The syntax-directed operation CapturingGroupNumber takes no arguments and returns a positive integer.

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 × 10nDecimalDigits의 MV를 더한 값)을 반환한다.

NonZeroDigit의 MV”와 “DecimalDigits의 MV”의 정의는 12.9.3에 있다.

22.2.1.6 Static Semantics: IsCharacterClass

The syntax-directed operation IsCharacterClass takes no arguments and returns a Boolean.

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 Static Semantics: CharacterValue

The syntax-directed operation CharacterValue takes no arguments and returns a non-negative integer.

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 62에 따른 수치 값을 반환한다.
Table 62: ControlEscape 코드 포인트 값
ControlEscape 수치 값 코드 포인트 Unicode 이름 기호
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> 문자를 나타내며 뒤에 십진 숫자가 올 수 없다.

CharacterEscape :: HexEscapeSequence
  1. HexEscapeSequence의 MV를 반환한다.
RegExpUnicodeEscapeSequence :: u HexLeadSurrogate \u HexTrailSurrogate
  1. leadHexLeadSurrogateCharacterValue라고 하자.
  2. trailHexTrailSurrogateCharacterValue라고 하자.
  3. cpUTF16SurrogatePairToCodePoint(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 Static Semantics: MayContainStrings

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

CharacterClassEscape :: d D s S w W P{ UnicodePropertyValueExpression } UnicodePropertyValueExpression :: UnicodePropertyName = UnicodePropertyValue NestedClass :: [^ ClassContents ] ClassContents :: [empty] NonemptyClassRanges ClassSetOperand :: ClassSetCharacter
  1. false를 반환한다.
UnicodePropertyValueExpression :: LoneUnicodePropertyNameOrValue
  1. LoneUnicodePropertyNameOrValue일치한 소스 텍스트Table 66의 “Property name” 열에 나열된 문자열의 이진 속성이면 true를 반환한다.
  2. false를 반환한다.
ClassUnion :: ClassSetRange ClassUnionopt
  1. ClassUnion이 존재하면, ClassUnionMayContainStrings를 반환한다.
  2. false를 반환한다.
ClassUnion :: ClassSetOperand ClassUnionopt
  1. ClassSetOperandMayContainStringstrue이면, true를 반환한다.
  2. ClassUnion이 존재하면, ClassUnionMayContainStrings를 반환한다.
  3. false를 반환한다.
ClassIntersection :: ClassSetOperand && ClassSetOperand
  1. 첫 번째 ClassSetOperandMayContainStringsfalse이면, false를 반환한다.
  2. 두 번째 ClassSetOperandMayContainStringsfalse이면, false를 반환한다.
  3. true를 반환한다.
ClassIntersection :: ClassIntersection && ClassSetOperand
  1. ClassIntersectionMayContainStringsfalse이면, false를 반환한다.
  2. ClassSetOperandMayContainStringsfalse이면, false를 반환한다.
  3. true를 반환한다.
ClassSubtraction :: ClassSetOperand -- ClassSetOperand
  1. 첫 번째 ClassSetOperandMayContainStrings를 반환한다.
ClassSubtraction :: ClassSubtraction -- ClassSetOperand
  1. ClassSubtractionMayContainStrings를 반환한다.
ClassStringDisjunctionContents :: ClassString | ClassStringDisjunctionContents
  1. ClassStringMayContainStringstrue이면, true를 반환한다.
  2. ClassStringDisjunctionContentsMayContainStrings를 반환한다.
ClassString :: [empty]
  1. true를 반환한다.
ClassString :: NonEmptyClassString
  1. NonEmptyClassStringMayContainStrings를 반환한다.
NonEmptyClassString :: ClassSetCharacter NonEmptyClassStringopt
  1. NonEmptyClassString이 존재하면, true를 반환한다.
  2. false를 반환한다.

22.2.1.9 Static Semantics: GroupSpecifiersThatMatch ( thisGroupName )

The abstract operation GroupSpecifiersThatMatch takes argument thisGroupName (a GroupName Parse Node) and returns a List of GroupSpecifier Parse Nodes. It performs the following steps when called:

  1. namethisGroupNameCapturingGroupName이라고 하자.
  2. patternthisGroupName을 포함하는 Pattern이라고 하자.
  3. result를 새로운 빈 List라고 하자.
  4. pattern이 포함하는 각 GroupSpecifier gs에 대해, 다음을 수행한다.
    1. gsCapturingGroupNamename이면,
      1. gsresult에 추가한다.
  5. result를 반환한다.

22.2.1.10 Static Semantics: CapturingGroupName

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

GroupName :: < RegExpIdentifierName >
  1. idTextUnescapedRegExpIdentifierNameRegExpIdentifierCodePoints라고 하자.
  2. CodePointsToString(idTextUnescaped)를 반환한다.

22.2.1.11 Static Semantics: RegExpIdentifierCodePoints

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

RegExpIdentifierName :: RegExpIdentifierStart
  1. cpRegExpIdentifierStartRegExpIdentifierCodePoint라고 하자.
  2. « cp »를 반환한다.
RegExpIdentifierName :: RegExpIdentifierName RegExpIdentifierPart
  1. cps를 파생된 RegExpIdentifierNameRegExpIdentifierCodePoints라고 하자.
  2. cpRegExpIdentifierPartRegExpIdentifierCodePoint라고 하자.
  3. cps와 « cp »의 리스트 연결을 반환한다.

22.2.1.12 Static Semantics: RegExpIdentifierCodePoint

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

RegExpIdentifierStart :: IdentifierStartChar
  1. IdentifierStartChar와 일치한 코드 포인트를 반환한다.
RegExpIdentifierPart :: IdentifierPartChar
  1. IdentifierPartChar와 일치한 코드 포인트를 반환한다.
RegExpIdentifierStart :: \ RegExpUnicodeEscapeSequence RegExpIdentifierPart :: \ RegExpUnicodeEscapeSequence
  1. 수치 값이 RegExpUnicodeEscapeSequenceCharacterValue인 코드 포인트를 반환한다.
RegExpIdentifierStart :: UnicodeLeadSurrogate UnicodeTrailSurrogate RegExpIdentifierPart :: UnicodeLeadSurrogate UnicodeTrailSurrogate
  1. leadUnicodeLeadSurrogate와 일치한 코드 포인트의 수치 값이 수치 값인 코드 단위라고 하자.
  2. trailUnicodeTrailSurrogate와 일치한 코드 포인트의 수치 값이 수치 값인 코드 단위라고 하자.
  3. UTF16SurrogatePairToCodePoint(lead, trail)를 반환한다.

22.2.2 패턴 의미론

정규 표현식 패턴은 아래에 설명된 과정을 사용하여 Abstract Closure로 변환된다. 구현은 결과가 동일한 한, 아래에 나열된 알고리즘보다 더 효율적인 알고리즘을 사용하는 것이 권장된다. Abstract Closure는 RegExp 객체의 [[RegExpMatcher]] 내부 슬롯 값으로 사용된다.

Pattern은 관련 플래그가 uv도 포함하지 않으면 BMP 패턴이다. 그렇지 않으면 Unicode 패턴이다. BMP 패턴은 Basic Multilingual Plane 범위의 Unicode 코드 포인트인 16비트 값의 시퀀스로 구성된 것으로 해석되는 String에 대해 매치한다. Unicode 패턴은 UTF-16을 사용해 인코딩된 Unicode 코드 포인트들로 구성된 것으로 해석되는 String에 대해 매치한다. BMP 패턴의 동작을 설명하는 문맥에서 “character”는 단일 16비트 Unicode BMP 코드 포인트를 의미한다. Unicode 패턴의 동작을 설명하는 문맥에서 “character”는 UTF-16으로 인코딩된 코드 포인트(6.1.4)를 의미한다. 어느 문맥에서든 “character value”는 대응하는 인코딩되지 않은 코드 포인트의 수치 값을 의미한다.

Pattern의 구문과 의미론은 Pattern의 소스 텍스트가 각 SourceCharacter가 Unicode 코드 포인트에 대응하는 SourceCharacter 값의 List인 것처럼 정의된다. BMP 패턴이 비-BMP SourceCharacter를 포함하면 전체 패턴이 UTF-16을 사용해 인코딩되고, 그 인코딩의 개별 코드 단위들이 List의 요소로 사용된다.

Note

예를 들어, 단일 비-BMP 문자 U+1D11E (MUSICAL SYMBOL G CLEF)로 소스 텍스트에 표현된 패턴을 생각해 보자. Unicode 패턴으로 해석되면, 이는 단일 코드 포인트 U+1D11E로 구성된 단일 요소(character) List가 된다. 그러나 BMP 패턴으로 해석되면, 먼저 UTF-16으로 인코딩되어 코드 단위 0xD834와 0xDD1E로 구성된 두 요소 List를 생성한다.

패턴은 비-BMP 문자가 UTF-16으로 인코딩된 ECMAScript String 값으로 RegExp 생성자에 전달된다. 예를 들어, 단일 문자 MUSICAL SYMBOL G CLEF 패턴은 String 값으로 표현될 때 요소가 코드 단위 0xD834와 0xDD1E인 길이 2의 String이다. 따라서 두 패턴 문자로 구성된 BMP 패턴으로 처리하기 위해서는 문자열에 대한 추가 변환이 필요하지 않다. 그러나 Unicode 패턴으로 처리하기 위해서는 UTF16SurrogatePairToCodePoint를 사용하여 유일한 요소가 단일 패턴 문자인 코드 포인트 U+1D11E인 List를 생성해야 한다.

구현은 실제로 UTF-16으로 또는 UTF-16에서 이러한 변환을 수행하지 않을 수 있지만, 이 명세의 의미론은 패턴 매칭 결과가 그러한 변환이 수행된 것과 같을 것을 요구한다.

22.2.2.1 표기법

아래 설명은 다음 내부 데이터 구조를 사용한다:

  • CharSetElement는 다음 두 엔티티 중 하나이다:
    • regexpRecord.[[UnicodeSets]]false이면, CharSetElement는 위의 Pattern Semantics의 의미에서의 character이다.
    • regexpRecord.[[UnicodeSets]]true이면, CharSetElement는 위의 Pattern Semantics의 의미에서의 character들을 요소로 가지는 시퀀스이다. 여기에는 빈 시퀀스, 하나의 character로 된 시퀀스, 둘 이상의 character로 된 시퀀스가 포함된다. 편의를 위해, 이러한 종류의 CharSetElement를 다룰 때 개별 character는 하나의 character로 된 시퀀스와 상호 교환적으로 취급된다.
  • CharSet는 CharSetElement들의 수학적 집합이다.
  • CaptureRange는 캡처에 포함된 문자 범위를 나타내는 Record { [[StartIndex]], [[EndIndex]] }이다. 여기서 [[StartIndex]]input 안에서 그 범위의 시작 인덱스(포함)를 나타내는 정수이고, [[EndIndex]]input 안에서 그 범위의 끝 인덱스(제외)를 나타내는 정수이다. 어떤 CaptureRange에 대해서도, 이 인덱스들은 [[StartIndex]][[EndIndex]]라는 불변식을 만족해야 한다.
  • MatchStateRecord { [[Input]], [[EndIndex]], [[Captures]] }이다. 여기서 [[Input]]은 매치되는 String을 나타내는 character들의 List이고, [[EndIndex]]정수이며, [[Captures]]는 패턴의 각 왼쪽 캡처 괄호마다 하나씩 있는 값의 List이다. MatchState는 정규 표현식 매칭 알고리즘에서 부분 매치 상태를 나타내는 데 사용된다. [[EndIndex]]는 지금까지 패턴이 매치한 마지막 입력 character의 인덱스에 1을 더한 값이고, [[Captures]]는 캡처 괄호의 결과를 보관한다. [[Captures]]nth 요소는 nth 캡처 괄호 집합이 캡처한 character 범위를 나타내는 CaptureRange이거나, nth 캡처 괄호 집합에 아직 도달하지 않았으면 undefined이다. 백트래킹 때문에, 매칭 과정 중 언제든 많은 MatchState가 사용 중일 수 있다.
  • MatcherContinuation은 하나의 MatchState 인자를 받아 MatchState 또는 failure를 반환하는 Abstract Closure이다. MatcherContinuation은 자신의 캡처된 값들로 지정된 패턴의 나머지 부분을, 자신의 MatchState 인자가 제공한 중간 상태에서 시작하여 input에 대해 매치하려고 시도한다. 매치가 성공하면 MatcherContinuation은 자신이 도달한 최종 MatchState를 반환하고, 매치가 실패하면 MatcherContinuationfailure를 반환한다.
  • Matcher는 두 인자—MatchStateMatcherContinuation—를 받아 MatchState 또는 failure를 반환하는 Abstract Closure이다. Matcher는 자신의 캡처된 값들로 지정된 패턴의 중간 부분 패턴을, 자신의 MatchState 인자가 제공한 중간 상태에서 시작하여 MatchState[[Input]]에 대해 매치하려고 시도한다. MatcherContinuation 인자는 패턴의 나머지를 매치하는 closure여야 한다. 패턴의 부분 패턴을 매치하여 새로운 MatchState를 얻은 뒤, Matcher는 그 새로운 MatchState에 대해 MatcherContinuation을 호출하여 패턴의 나머지도 매치될 수 있는지 테스트한다. 가능하면 MatcherMatcherContinuation이 반환한 MatchState를 반환한다; 그렇지 않으면 Matcher는 자신의 선택 지점에서 다른 선택들을 시도할 수 있으며, 성공하거나 모든 가능성이 소진될 때까지 MatcherContinuation을 반복적으로 호출한다.

22.2.2.1.1 RegExp Records

RegExp Record는 컴파일 중, 그리고 가능하면 매칭 중 필요한 RegExp에 관한 정보를 저장하는 데 사용되는 Record 값이다.

다음 필드들을 가진다:

Table 63: RegExp Record 필드
필드 이름 의미
[[IgnoreCase]] Boolean RegExp의 플래그에 "i"가 나타나는지 나타낸다
[[Multiline]] Boolean RegExp의 플래그에 "m"이 나타나는지 나타낸다
[[DotAll]] Boolean RegExp의 플래그에 "s"가 나타나는지 나타낸다
[[Unicode]] Boolean RegExp의 플래그에 "u"가 나타나는지 나타낸다
[[UnicodeSets]] Boolean RegExp의 플래그에 "v"가 나타나는지 나타낸다
[[CapturingGroupsCount]] 음이 아닌 정수 RegExp 패턴 안의 왼쪽 캡처 괄호의 수

22.2.2.2 Runtime Semantics: CompilePattern

The syntax-directed operation CompilePattern takes argument regexpRecord (a RegExp Record) and returns a Abstract Closure that takes a List of characters and a non-negative integer and returns either a MatchState or failure. It is defined piecewise over the following productions:

Pattern :: Disjunction
  1. m을 인자 regexpRecordforwardDisjunctionCompileSubpattern이라고 하자.
  2. regexpRecordm을 캡처하고 호출될 때 다음 단계를 수행하는, 매개변수 (input, index)를 가진 새로운 Abstract Closure를 반환한다:
    1. Assert: input은 character들의 List이다.
    2. Assert: 0 ≤ indexinput 안의 요소 개수.
    3. c를 아무것도 캡처하지 않고 호출될 때 다음 단계를 수행하는, 매개변수 (y)를 가진 새로운 MatcherContinuation이라고 하자:
      1. Assert: yMatchState이다.
      2. y를 반환한다.
    4. cap을 1부터 regexpRecord.[[CapturingGroupsCount]]까지 인덱스되는, regexpRecord.[[CapturingGroupsCount]]개의 undefined 값으로 된 List라고 하자.
    5. xMatchState { [[Input]]: input, [[EndIndex]]: index, [[Captures]]: cap }라고 하자.
    6. m(x, c)를 반환한다.
Note

Pattern은 Abstract Closure 값으로 컴파일된다. 그러면 RegExpBuiltinExec는 이 절차를 character들의 List와 그 List 안의 오프셋에 적용하여, 패턴이 그 List 안의 정확히 그 오프셋에서 시작하여 매치되는지, 그리고 매치된다면 캡처 괄호들의 값이 무엇인지 결정할 수 있다. 22.2.2의 알고리즘들은 패턴 컴파일이 SyntaxError 예외를 던질 수 있도록 설계되어 있다; 반면 패턴이 성공적으로 컴파일된 뒤에는 character들의 List에서 매치를 찾기 위해 결과 Abstract Closure를 적용해도 예외를 던질 수 없다(메모리 부족처럼 어디서든 발생할 수 있는 구현 정의 예외는 제외).

22.2.2.3 Runtime Semantics: CompileSubpattern

The syntax-directed operation CompileSubpattern takes arguments regexpRecord (a RegExp Record) and direction (forward or backward) and returns a Matcher.

Note 1

이 절은 B.1.2.5에서 수정된다.

It is defined piecewise over the following productions:

Disjunction :: Alternative | Disjunction
  1. m1을 인자 regexpRecorddirection으로 AlternativeCompileSubpattern이라고 하자.
  2. m2를 인자 regexpRecorddirection으로 DisjunctionCompileSubpattern이라고 하자.
  3. MatchTwoAlternatives(m1, m2)를 반환한다.
Note 2

| 정규 표현식 연산자는 두 대안을 구분한다. 패턴은 먼저 왼쪽 Alternative(|regular expression|의 후속 부분이 뒤따름)를 매치하려고 시도한다; 실패하면 오른쪽 Disjunction(|regular expression|의 후속 부분이 뒤따름)를 매치하려고 시도한다. 왼쪽 Alternative, 오른쪽 Disjunction, 그리고 후속 부분 모두 선택 지점을 가지면, 왼쪽 Alternative의 다음 선택으로 넘어가기 전에 후속 부분의 모든 선택이 시도된다. 왼쪽 Alternative의 선택이 소진되면, 왼쪽 Alternative 대신 오른쪽 Disjunction이 시도된다. |에 의해 건너뛴 패턴 부분 안의 캡처 괄호는 String 대신 undefined 값을 생성한다. 따라서 예를 들어,

/a|ab/.exec("abc")

"ab"가 아니라 "a"라는 결과를 반환한다. 또한,

/((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. m1을 인자 regexpRecorddirection으로 AlternativeCompileSubpattern이라고 하자.
  2. m2를 인자 regexpRecorddirection으로 TermCompileSubpattern이라고 하자.
  3. MatchSequence(m1, m2, direction)를 반환한다.
Note 3

연속된 Term들은 input의 연속된 부분들을 동시에 매치하려고 시도한다. directionforward이면, 왼쪽 Alternative, 오른쪽 Term, 그리고 정규 표현식의 후속 부분 모두 선택 지점을 가지는 경우, 오른쪽 Term의 다음 선택으로 넘어가기 전에 후속 부분의 모든 선택이 시도되고, 왼쪽 Alternative의 다음 선택으로 넘어가기 전에 오른쪽 Term의 모든 선택이 시도된다. directionbackward이면, AlternativeTerm의 평가 순서가 반대로 된다.

Term :: Assertion
  1. 인자 regexpRecordAssertionCompileAssertion을 반환한다.
Note 4

결과 Matcherdirection과 무관하다.

Term :: Atom
  1. 인자 regexpRecorddirection으로 AtomCompileAtom을 반환한다.
Term :: Atom Quantifier
  1. m을 인자 regexpRecorddirection으로 AtomCompileAtom이라고 하자.
  2. qQuantifierCompileQuantifier라고 하자.
  3. Assert: q.[[Min]]q.[[Max]].
  4. parenIndexCountLeftCapturingParensBefore(Term)라고 하자.
  5. parenCountCountLeftCapturingParensWithin(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, matchState, continue, parenIndex, parenCount )

The abstract operation RepeatMatcher takes arguments m (a Matcher), min (a non-negative integer), max (a non-negative integer or +∞), greedy (a Boolean), matchState (a MatchState), continue (a MatcherContinuation), parenIndex (a non-negative integer), and parenCount (a non-negative integer) and returns either a MatchState or failure. It performs the following steps when called:

  1. max = 0이면 continue(matchState)를 반환한다.
  2. dm, min, max, greedy, matchState, continue, parenIndex, 및 parenCount를 캡처하고 호출될 때 다음 단계를 수행하는, 매개변수 (y)를 가진 새로운 MatcherContinuation이라고 하자:
    1. Assert: yMatchState이다.
    2. min = 0이고 y.[[EndIndex]] = matchState.[[EndIndex]]이면 failure를 반환한다.
    3. min = 0이면 min2를 0이라고 하자; 그렇지 않으면 min2min - 1이라고 하자.
    4. max = +∞이면 max2를 +∞라고 하자; 그렇지 않으면 max2max - 1이라고 하자.
    5. RepeatMatcher(m, min2, max2, greedy, y, continue, parenIndex, parenCount)를 반환한다.
  3. capmatchState.[[Captures]]의 사본이라고 하자.
  4. parenIndex + 1부터 parenIndex + parenCount까지의 포함 구간에 있는 각 정수 k에 대해, cap[k]를 undefined로 설정한다.
  5. inputmatchState.[[Input]]이라고 하자.
  6. ematchState.[[EndIndex]]라고 하자.
  7. xrMatchState { [[Input]]: input, [[EndIndex]]: e, [[Captures]]: cap }라고 하자.
  8. min ≠ 0이면 m(xr, d)를 반환한다.
  9. greedyfalse이면,
    1. zcontinue(matchState)라고 하자.
    2. zfailure가 아니면 z를 반환한다.
    3. m(xr, d)를 반환한다.
  10. zm(xr, d)라고 하자.
  11. zfailure가 아니면 z를 반환한다.
  12. continue(matchState)를 반환한다.
Note 1

Quantifier가 뒤따르는 AtomQuantifier가 지정한 횟수만큼 반복된다. Quantifier는 비탐욕적일 수 있으며, 이 경우 Atom 패턴은 후속 부분을 여전히 매치하면서 가능한 한 적은 횟수로 반복된다. 또는 탐욕적일 수 있으며, 이 경우 Atom 패턴은 후속 부분을 여전히 매치하면서 가능한 한 많은 횟수로 반복된다. 반복되는 것은 Atom이 매치하는 입력 문자 시퀀스가 아니라 Atom 패턴이므로, Atom의 서로 다른 반복은 서로 다른 입력 부분 문자열과 매치할 수 있다.

Note 2

Atom과 정규 표현식의 후속 부분 모두 선택 지점을 가지면, Atom은 먼저 가능한 한 많은 횟수(또는 비탐욕적인 경우 가능한 한 적은 횟수)로 매치된다. Atom의 마지막 반복의 다음 선택으로 넘어가기 전에 후속 부분의 모든 선택이 시도된다. Atom의 마지막(nth) 반복의 모든 선택은 Atom의 끝에서 두 번째((n - 1)st) 반복의 다음 선택으로 넘어가기 전에 시도된다; 그 시점에서 Atom의 더 많거나 더 적은 반복이 이제 가능하다는 것이 드러날 수 있다; 이들은 (다시, 가능한 한 적게 또는 가능한 한 많이 시작하여) 소진된 뒤 Atom의 (n - 1)st 반복의 다음 선택으로 넘어가고, 이런 식으로 계속된다.

다음과 비교해 보라

/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 안에 포함된 모든 캡처된 String을 지우며, 이 경우 여기에는 번호 2, 3, 4, 5의 캡처 String이 포함되기 때문이다.

Note 4

RepeatMatcher의 단계 2.b는 최소 반복 횟수가 충족된 뒤에는, 빈 character 시퀀스와 매치하는 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 a Matcher. It performs the following steps when called:

  1. 아무것도 캡처하지 않고 호출될 때 다음 단계를 수행하는, 매개변수 (matchState, continue)를 가진 새로운 Matcher를 반환한다:
    1. Assert: matchStateMatchState이다.
    2. Assert: continueMatcherContinuation이다.
    3. continue(matchState)를 반환한다.

22.2.2.3.3 MatchTwoAlternatives ( m1, m2 )

The abstract operation MatchTwoAlternatives takes arguments m1 (a Matcher) and m2 (a Matcher) and returns a Matcher. It performs the following steps when called:

  1. m1m2를 캡처하고 호출될 때 다음 단계를 수행하는, 매개변수 (matchState, continue)를 가진 새로운 Matcher를 반환한다:
    1. Assert: matchStateMatchState이다.
    2. Assert: continueMatcherContinuation이다.
    3. rm1(matchState, continue)라고 하자.
    4. rfailure가 아니면 r를 반환한다.
    5. m2(matchState, continue)를 반환한다.

22.2.2.3.4 MatchSequence ( m1, m2, direction )

The abstract operation MatchSequence takes arguments m1 (a Matcher), m2 (a Matcher), and direction (forward or backward) and returns a Matcher. It performs the following steps when called:

  1. directionforward이면,
    1. m1m2를 캡처하고 호출될 때 다음 단계를 수행하는, 매개변수 (matchState, continue)를 가진 새로운 Matcher를 반환한다:
      1. Assert: matchStateMatchState이다.
      2. Assert: continueMatcherContinuation이다.
      3. dcontinuem2를 캡처하고 호출될 때 다음 단계를 수행하는, 매개변수 (y)를 가진 새로운 MatcherContinuation이라고 하자:
        1. Assert: yMatchState이다.
        2. m2(y, continue)를 반환한다.
      4. m1(matchState, d)를 반환한다.
  2. Assert: directionbackward이다.
  3. m1m2를 캡처하고 호출될 때 다음 단계를 수행하는, 매개변수 (matchState, continue)를 가진 새로운 Matcher를 반환한다:
    1. Assert: matchStateMatchState이다.
    2. Assert: continueMatcherContinuation이다.
    3. dcontinuem1을 캡처하고 호출될 때 다음 단계를 수행하는, 매개변수 (y)를 가진 새로운 MatcherContinuation이라고 하자:
      1. Assert: yMatchState이다.
      2. m1(y, continue)를 반환한다.
    4. m2(matchState, d)를 반환한다.

22.2.2.4 Runtime Semantics: CompileAssertion

The syntax-directed operation CompileAssertion takes argument regexpRecord (a RegExp Record) and returns a Matcher.

Note 1

이 절은 B.1.2.6에서 수정된다.

It is defined piecewise over the following productions:

Assertion :: ^
  1. regexpRecord를 캡처하고 호출될 때 다음 단계를 수행하는, 매개변수 (matchState, continue)를 가진 새로운 Matcher를 반환한다:
    1. Assert: matchStateMatchState이다.
    2. Assert: continueMatcherContinuation이다.
    3. inputmatchState.[[Input]]이라고 하자.
    4. ematchState.[[EndIndex]]라고 하자.
    5. e = 0이거나, regexpRecord.[[Multiline]]true이고 character input[e - 1]이 LineTerminator와 일치하면,
      1. continue(matchState)를 반환한다.
    6. failure를 반환한다.
Note 2

y 플래그가 패턴과 함께 사용되더라도, ^는 항상 input의 시작에서만, 또는 (regexpRecord.[[Multiline]]true이면) 줄의 시작에서만 매치한다.

Assertion :: $
  1. regexpRecord를 캡처하고 호출될 때 다음 단계를 수행하는, 매개변수 (matchState, continue)를 가진 새로운 Matcher를 반환한다:
    1. Assert: matchStateMatchState이다.
    2. Assert: continueMatcherContinuation이다.
    3. inputmatchState.[[Input]]이라고 하자.
    4. ematchState.[[EndIndex]]라고 하자.
    5. inputLengthinput 안의 요소 개수라고 하자.
    6. e = inputLength이거나, regexpRecord.[[Multiline]]true이고 character input[e]가 LineTerminator와 일치하면,
      1. continue(matchState)를 반환한다.
    7. failure를 반환한다.
Assertion :: \b
  1. regexpRecord를 캡처하고 호출될 때 다음 단계를 수행하는, 매개변수 (matchState, continue)를 가진 새로운 Matcher를 반환한다:
    1. Assert: matchStateMatchState이다.
    2. Assert: continueMatcherContinuation이다.
    3. inputmatchState.[[Input]]이라고 하자.
    4. ematchState.[[EndIndex]]라고 하자.
    5. aIsWordChar(regexpRecord, input, e - 1)이라고 하자.
    6. bIsWordChar(regexpRecord, input, e)라고 하자.
    7. atrue이고 bfalse이면, 또는 afalse이고 btrue이면, continue(matchState)를 반환한다.
    8. failure를 반환한다.
Assertion :: \B
  1. regexpRecord를 캡처하고 호출될 때 다음 단계를 수행하는, 매개변수 (matchState, continue)를 가진 새로운 Matcher를 반환한다:
    1. Assert: matchStateMatchState이다.
    2. Assert: continueMatcherContinuation이다.
    3. inputmatchState.[[Input]]이라고 하자.
    4. ematchState.[[EndIndex]]라고 하자.
    5. aIsWordChar(regexpRecord, input, e - 1)이라고 하자.
    6. bIsWordChar(regexpRecord, input, e)라고 하자.
    7. atrue이고 btrue이면, 또는 afalse이고 bfalse이면, continue(matchState)를 반환한다.
    8. failure를 반환한다.
Assertion :: (?= Disjunction )
  1. m을 인자 regexpRecordforwardDisjunctionCompileSubpattern이라고 하자.
  2. m을 캡처하고 호출될 때 다음 단계를 수행하는, 매개변수 (matchState, continue)를 가진 새로운 Matcher를 반환한다:
    1. Assert: matchStateMatchState이다.
    2. Assert: continueMatcherContinuation이다.
    3. d를 아무것도 캡처하지 않고 호출될 때 다음 단계를 수행하는, 매개변수 (y)를 가진 새로운 MatcherContinuation이라고 하자:
      1. Assert: yMatchState이다.
      2. y를 반환한다.
    4. rm(matchState, d)라고 하자.
    5. rfailure이면 failure를 반환한다.
    6. Assert: rMatchState이다.
    7. capr.[[Captures]]라고 하자.
    8. inputmatchState.[[Input]]이라고 하자.
    9. xematchState.[[EndIndex]]라고 하자.
    10. zMatchState { [[Input]]: input, [[EndIndex]]: xe, [[Captures]]: cap }라고 하자.
    11. continue(z)를 반환한다.
Note 3

형식 (?= Disjunction )는 너비가 0인 양의 전방탐색을 지정한다. 성공하려면 Disjunction 안의 패턴이 현재 위치에서 매치되어야 하지만, 후속 부분을 매치하기 전에 현재 위치는 전진하지 않는다. Disjunction이 현재 위치에서 여러 방식으로 매치될 수 있으면, 첫 번째 것만 시도된다. 다른 정규 표현식 연산자와 달리, (?= 형식 안으로의 백트래킹은 없다(이 특이한 동작은 Perl에서 상속되었다). 이는 Disjunction이 캡처 괄호를 포함하고 패턴의 후속 부분이 그 캡처들에 대한 역참조를 포함할 때만 중요하다.

예를 들어,

/(?=(a+))/.exec("baaabac")

는 첫 번째 b 바로 뒤의 빈 String과 매치하므로 배열을 반환한다:

["", "aaa"]

전방탐색 안으로 백트래킹이 없음을 설명하기 위해, 다음을 생각해 보라:

/(?=(a+))a*b\1/.exec("baaabac")

이 표현식은 다음을 반환한다

["aba", "a"]

그리고 다음은 반환하지 않는다:

["aaaba", "a"]
Assertion :: (?! Disjunction )
  1. m을 인자 regexpRecordforwardDisjunctionCompileSubpattern이라고 하자.
  2. m을 캡처하고 호출될 때 다음 단계를 수행하는, 매개변수 (matchState, continue)를 가진 새로운 Matcher를 반환한다:
    1. Assert: matchStateMatchState이다.
    2. Assert: continueMatcherContinuation이다.
    3. d를 아무것도 캡처하지 않고 호출될 때 다음 단계를 수행하는, 매개변수 (y)를 가진 새로운 MatcherContinuation이라고 하자:
      1. Assert: yMatchState이다.
      2. y를 반환한다.
    4. rm(matchState, d)라고 하자.
    5. rfailure가 아니면 failure를 반환한다.
    6. continue(matchState)를 반환한다.
Note 4

형식 (?! Disjunction )는 너비가 0인 음의 전방탐색을 지정한다. 성공하려면 Disjunction 안의 패턴이 현재 위치에서 매치에 실패해야 한다. 후속 부분을 매치하기 전에 현재 위치는 전진하지 않는다. Disjunction은 캡처 괄호를 포함할 수 있지만, 그에 대한 역참조는 Disjunction 자체 안에서만 의미가 있다. 패턴의 다른 곳에서 이 캡처 괄호들에 대한 역참조는 음의 전방탐색이 패턴 성공을 위해 실패해야 하므로 항상 undefined를 반환한다. 예를 들어,

/(.*?)a(?!(a+)b\2c)\2(.*)/.exec("baaabaac")

는 어떤 양수 n개의 a, b, 또 다른 n개의 a(첫 번째 \2로 지정됨), 그리고 c가 바로 뒤따르지 않는 a를 찾는다. 두 번째 \2는 음의 전방탐색 밖에 있으므로 undefined와 매치하여 항상 성공한다. 전체 표현식은 배열을 반환한다:

["baaabaac", "ba", undefined, "abaac"]
Assertion :: (?<= Disjunction )
  1. m을 인자 regexpRecordbackwardDisjunctionCompileSubpattern이라고 하자.
  2. m을 캡처하고 호출될 때 다음 단계를 수행하는, 매개변수 (matchState, continue)를 가진 새로운 Matcher를 반환한다:
    1. Assert: matchStateMatchState이다.
    2. Assert: continueMatcherContinuation이다.
    3. d를 아무것도 캡처하지 않고 호출될 때 다음 단계를 수행하는, 매개변수 (y)를 가진 새로운 MatcherContinuation이라고 하자:
      1. Assert: yMatchState이다.
      2. y를 반환한다.
    4. rm(matchState, d)라고 하자.
    5. rfailure이면 failure를 반환한다.
    6. Assert: rMatchState이다.
    7. capr.[[Captures]]라고 하자.
    8. inputmatchState.[[Input]]이라고 하자.
    9. xematchState.[[EndIndex]]라고 하자.
    10. zMatchState { [[Input]]: input, [[EndIndex]]: xe, [[Captures]]: cap }라고 하자.
    11. continue(z)를 반환한다.
Assertion :: (?<! Disjunction )
  1. m을 인자 regexpRecordbackwardDisjunctionCompileSubpattern이라고 하자.
  2. m을 캡처하고 호출될 때 다음 단계를 수행하는, 매개변수 (matchState, continue)를 가진 새로운 Matcher를 반환한다:
    1. Assert: matchStateMatchState이다.
    2. Assert: continueMatcherContinuation이다.
    3. d를 아무것도 캡처하지 않고 호출될 때 다음 단계를 수행하는, 매개변수 (y)를 가진 새로운 MatcherContinuation이라고 하자:
      1. Assert: yMatchState이다.
      2. y를 반환한다.
    4. rm(matchState, d)라고 하자.
    5. rfailure가 아니면 failure를 반환한다.
    6. continue(matchState)를 반환한다.

22.2.2.4.1 IsWordChar ( regexpRecord, input, e )

The abstract operation IsWordChar takes arguments regexpRecord (a RegExp Record), input (a List of characters), and e (an integer) and returns a Boolean. It performs the following steps when called:

  1. inputLengthinput 안의 요소 개수라고 하자.
  2. e = -1이거나 e = inputLength이면 false를 반환한다.
  3. c를 character input[e]라고 하자.
  4. WordCharacters(regexpRecord)가 c를 포함하면 true를 반환한다.
  5. false를 반환한다.

22.2.2.5 Runtime Semantics: CompileQuantifier

The syntax-directed operation CompileQuantifier takes no arguments and returns a Record with fields [[Min]] (a non-negative integer), [[Max]] (a non-negative integer or +∞), and [[Greedy]] (a Boolean). It is defined piecewise over the following productions:

Quantifier :: QuantifierPrefix
  1. qpQuantifierPrefixCompileQuantifierPrefix라고 하자.
  2. Record { [[Min]]: qp.[[Min]], [[Max]]: qp.[[Max]], [[Greedy]]: true }를 반환한다.
Quantifier :: QuantifierPrefix ?
  1. qpQuantifierPrefixCompileQuantifierPrefix라고 하자.
  2. Record { [[Min]]: qp.[[Min]], [[Max]]: qp.[[Max]], [[Greedy]]: false }를 반환한다.

22.2.2.6 Runtime Semantics: CompileQuantifierPrefix

The syntax-directed operation CompileQuantifierPrefix takes no arguments and returns a Record with fields [[Min]] (a non-negative integer) and [[Max]] (a non-negative integer or +∞). It is defined piecewise over the following productions:

QuantifierPrefix :: *
  1. Record { [[Min]]: 0, [[Max]]: +∞ }를 반환한다.
QuantifierPrefix :: +
  1. Record { [[Min]]: 1, [[Max]]: +∞ }를 반환한다.
QuantifierPrefix :: ?
  1. Record { [[Min]]: 0, [[Max]]: 1 }를 반환한다.
QuantifierPrefix :: { DecimalDigits }
  1. iDecimalDigits의 MV라고 하자(12.9.3를 보라).
  2. Record { [[Min]]: i, [[Max]]: i }를 반환한다.
QuantifierPrefix :: { DecimalDigits ,}
  1. iDecimalDigits의 MV라고 하자.
  2. Record { [[Min]]: i, [[Max]]: +∞ }를 반환한다.
QuantifierPrefix :: { DecimalDigits , DecimalDigits }
  1. i를 첫 번째 DecimalDigits의 MV라고 하자.
  2. j를 두 번째 DecimalDigits의 MV라고 하자.
  3. Record { [[Min]]: i, [[Max]]: j }를 반환한다.

22.2.2.7 Runtime Semantics: CompileAtom

The syntax-directed operation CompileAtom takes arguments regexpRecord (a RegExp Record) and direction (forward or backward) and returns a Matcher.

Note 1

이 절은 B.1.2.7에서 수정된다.

It is defined piecewise over the following productions:

Atom :: PatternCharacter
  1. chPatternCharacter와 일치한 character라고 하자.
  2. charSet을 character ch를 포함하는 단일 요소 CharSet이라고 하자.
  3. CharacterSetMatcher(regexpRecord, charSet, false, direction)를 반환한다.
Atom :: .
  1. charSetAllCharacters(regexpRecord)라고 하자.
  2. regexpRecord.[[DotAll]]true가 아니면,
    1. LineTerminator 생성식의 오른쪽과 대응하는 코드 포인트에 해당하는 모든 character를 charSet에서 제거한다.
  3. CharacterSetMatcher(regexpRecord, charSet, false, direction)를 반환한다.
Atom :: CharacterClass
  1. cc를 인자 regexpRecordCharacterClassCompileCharacterClass라고 하자.
  2. cscc.[[CharSet]]이라고 하자.
  3. regexpRecord.[[UnicodeSets]]false이거나 cs의 모든 CharSetElement가 단일 character로 구성되어 있으면(cs가 비어 있는 경우 포함), CharacterSetMatcher(regexpRecord, cs, cc.[[Invert]], direction)를 반환한다.
  4. Assert: cc.[[Invert]]false이다.
  5. lmMatchers의 빈 List라고 하자.
  6. cs 안의 둘 이상의 character를 포함하는 각 CharSetElement s에 대해, 길이의 내림차순으로 반복하며, 다음을 수행한다.
    1. cs2s의 마지막 코드 포인트를 포함하는 단일 요소 CharSet이라고 하자.
    2. m2CharacterSetMatcher(regexpRecord, cs2, false, direction)라고 하자.
    3. s 안의 각 코드 포인트 c1에 대해, 그 끝에서 두 번째 코드 포인트부터 역순으로 반복하며, 다음을 수행한다.
      1. cs1c1을 포함하는 단일 요소 CharSet이라고 하자.
      2. m1CharacterSetMatcher(regexpRecord, cs1, false, direction)라고 하자.
      3. m2MatchSequence(m1, m2, direction)로 설정한다.
    4. m2lm에 추가한다.
  7. singles를 단일 character로 구성된 cs의 모든 CharSetElement를 포함하는 CharSet이라고 하자.
  8. CharacterSetMatcher(regexpRecord, singles, false, direction)를 lm에 추가한다.
  9. cs가 character들의 빈 시퀀스를 포함하면 EmptyMatcher()를 lm에 추가한다.
  10. m2lm의 마지막 Matcher라고 하자.
  11. lm의 각 Matcher m1에 대해, 끝에서 두 번째 요소부터 역순으로 반복하며, 다음을 수행한다.
    1. m2MatchTwoAlternatives(m1, m2)로 설정한다.
  12. m2를 반환한다.
Atom :: ( GroupSpecifieropt Disjunction )
  1. m을 인자 regexpRecorddirection으로 DisjunctionCompileSubpattern이라고 하자.
  2. parenIndexCountLeftCapturingParensBefore(Atom)라고 하자.
  3. direction, m, 및 parenIndex를 캡처하고 호출될 때 다음 단계를 수행하는, 매개변수 (x, c)를 가진 새로운 Matcher를 반환한다:
    1. Assert: xMatchState이다.
    2. Assert: cMatcherContinuation이다.
    3. dx, c, direction, 및 parenIndex를 캡처하고 호출될 때 다음 단계를 수행하는, 매개변수 (y)를 가진 새로운 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이 아닌 십진수가 옴)에서 사용되거나, replace String에서 참조되거나, 정규 표현식 매칭 Abstract Closure에서 배열의 일부로 반환될 수 있다. 괄호의 캡처 동작을 억제하려면 대신 형식 (?: Disjunction )를 사용한다.

Atom :: (? RegularExpressionModifiers : Disjunction )
  1. addModifiersRegularExpressionModifiers일치한 소스 텍스트라고 하자.
  2. removeModifiers를 빈 String이라고 하자.
  3. modifiedRerUpdateModifiers(regexpRecord, CodePointsToString(addModifiers), removeModifiers)라고 하자.
  4. 인자 modifiedRerdirection으로 DisjunctionCompileSubpattern을 반환한다.
Atom :: (? RegularExpressionModifiers - RegularExpressionModifiers : Disjunction )
  1. addModifiers를 첫 번째 RegularExpressionModifiers일치한 소스 텍스트라고 하자.
  2. removeModifiers를 두 번째 RegularExpressionModifiers일치한 소스 텍스트라고 하자.
  3. modifiedRerUpdateModifiers(regexpRecord, CodePointsToString(addModifiers), CodePointsToString(removeModifiers))라고 하자.
  4. 인자 modifiedRerdirection으로 DisjunctionCompileSubpattern을 반환한다.
AtomEscape :: DecimalEscape
  1. nDecimalEscapeCapturingGroupNumber라고 하자.
  2. Assert: nregexpRecord.[[CapturingGroupsCount]].
  3. BackreferenceMatcher(regexpRecord, « n », direction)를 반환한다.
Note 3

형식 \ 뒤에 0이 아닌 십진수 n이 오는 escape sequence는 nth 캡처 괄호 집합의 결과(22.2.2.1)와 매치한다. 정규 표현식의 캡처 괄호가 n개보다 적으면 오류이다. 정규 표현식의 캡처 괄호가 n개 이상이지만 nth 것이 아무것도 캡처하지 않아 undefined이면, 역참조는 항상 성공한다.

AtomEscape :: CharacterEscape
  1. cvCharacterEscapeCharacterValue라고 하자.
  2. ch를 character value가 cv인 character라고 하자.
  3. charSet을 character ch를 포함하는 단일 요소 CharSet이라고 하자.
  4. CharacterSetMatcher(regexpRecord, charSet, false, direction)를 반환한다.
AtomEscape :: CharacterClassEscape
  1. cs를 인자 regexpRecordCharacterClassEscapeCompileToCharSet이라고 하자.
  2. regexpRecord.[[UnicodeSets]]false이거나 cs의 모든 CharSetElement가 단일 character로 구성되어 있으면(cs가 비어 있는 경우 포함), CharacterSetMatcher(regexpRecord, cs, false, direction)를 반환한다.
  3. lmMatchers의 빈 List라고 하자.
  4. cs 안의 둘 이상의 character를 포함하는 각 CharSetElement s에 대해, 길이의 내림차순으로 반복하며, 다음을 수행한다.
    1. cs2s의 마지막 코드 포인트를 포함하는 단일 요소 CharSet이라고 하자.
    2. m2CharacterSetMatcher(regexpRecord, cs2, false, direction)라고 하자.
    3. s 안의 각 코드 포인트 c1에 대해, 그 끝에서 두 번째 코드 포인트부터 역순으로 반복하며, 다음을 수행한다.
      1. cs1c1을 포함하는 단일 요소 CharSet이라고 하자.
      2. m1CharacterSetMatcher(regexpRecord, cs1, false, direction)라고 하자.
      3. m2MatchSequence(m1, m2, direction)로 설정한다.
    4. m2lm에 추가한다.
  5. singles를 단일 character로 구성된 cs의 모든 CharSetElement를 포함하는 CharSet이라고 하자.
  6. CharacterSetMatcher(regexpRecord, singles, false, direction)를 lm에 추가한다.
  7. cs가 character들의 빈 시퀀스를 포함하면 EmptyMatcher()를 lm에 추가한다.
  8. m2lm의 마지막 Matcher라고 하자.
  9. lm의 각 Matcher m1에 대해, 끝에서 두 번째 요소부터 역순으로 반복하며, 다음을 수행한다.
    1. m2MatchTwoAlternatives(m1, m2)로 설정한다.
  10. m2를 반환한다.
AtomEscape :: k GroupName
  1. matchingGroupSpecifiersGroupSpecifiersThatMatch(GroupName)라고 하자.
  2. parenIndices를 새로운 빈 List라고 하자.
  3. matchingGroupSpecifiers의 각 GroupSpecifier groupSpecifier에 대해, 다음을 수행한다.
    1. parenIndexCountLeftCapturingParensBefore(groupSpecifier)라고 하자.
    2. parenIndexparenIndices에 추가한다.
  4. BackreferenceMatcher(regexpRecord, parenIndices, direction)를 반환한다.

22.2.2.7.1 CharacterSetMatcher ( regexpRecord, charSet, invert, direction )

The abstract operation CharacterSetMatcher takes arguments regexpRecord (a RegExp Record), charSet (a CharSet), invert (a Boolean), and direction (forward or backward) and returns a Matcher. It performs the following steps when called:

  1. regexpRecord.[[UnicodeSets]]true이면,
    1. Assert: invertfalse이다.
    2. Assert: charSet의 모든 CharSetElement는 단일 character로 구성된다.
  2. regexpRecord, charSet, invert, 및 direction을 캡처하고 호출될 때 다음 단계를 수행하는, 매개변수 (x, c)를 가진 새로운 Matcher를 반환한다:
    1. Assert: xMatchState이다.
    2. Assert: cMatcherContinuation이다.
    3. inputx.[[Input]]이라고 하자.
    4. endIndexx.[[EndIndex]]라고 하자.
    5. directionforward이면 fendIndex + 1이라고 하자.
    6. 그렇지 않으면, fendIndex - 1이라고 하자.
    7. inputLengthinput 안의 요소 개수라고 하자.
    8. f < 0이거나 f > inputLength이면 failure를 반환한다.
    9. indexmin(endIndex, f)라고 하자.
    10. ch를 character input[index]라고 하자.
    11. ccCanonicalize(regexpRecord, ch)라고 하자.
    12. Canonicalize(regexpRecord, a)가 cc인 정확히 하나의 character a를 포함하는 CharSetElementcharSet 안에 존재하면 foundtrue라고 하자; 그렇지 않으면 foundfalse라고 하자.
    13. invertfalse이고 foundfalse이면 failure를 반환한다.
    14. inverttrue이고 foundtrue이면 failure를 반환한다.
    15. capx.[[Captures]]라고 하자.
    16. yMatchState { [[Input]]: input, [[EndIndex]]: f, [[Captures]]: cap }라고 하자.
    17. c(y)를 반환한다.

22.2.2.7.2 BackreferenceMatcher ( regexpRecord, ns, direction )

The abstract operation BackreferenceMatcher takes arguments regexpRecord (a RegExp Record), ns (a List of positive integers), and direction (forward or backward) and returns a Matcher. It performs the following steps when called:

  1. regexpRecord, ns, 및 direction을 캡처하고 호출될 때 다음 단계를 수행하는, 매개변수 (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. rcap[n]로 설정한다.
    7. rundefined이면 c(x)를 반환한다.
    8. endIndexx.[[EndIndex]]라고 하자.
    9. rsr.[[StartIndex]]라고 하자.
    10. rer.[[EndIndex]]라고 하자.
    11. lenre - rs라고 하자.
    12. directionforward이면 fendIndex + len이라고 하자.
    13. 그렇지 않으면, fendIndex - len이라고 하자.
    14. inputLengthinput 안의 요소 개수라고 하자.
    15. f < 0이거나 f > inputLength이면 failure를 반환한다.
    16. gmin(endIndex, f)라고 하자.
    17. 0(포함)부터 len(제외)까지의 구간에 있는 정수 iCanonicalize(regexpRecord, input[rs + i])가 Canonicalize(regexpRecord, input[g + i])가 아닌 것이 존재하면 failure를 반환한다.
    18. yMatchState { [[Input]]: input, [[EndIndex]]: f, [[Captures]]: cap }라고 하자.
    19. c(y)를 반환한다.

22.2.2.7.3 Canonicalize ( regexpRecord, ch )

The abstract operation Canonicalize takes arguments regexpRecord (a RegExp Record) and ch (a character) and returns a character. It performs the following steps when called:

  1. HasEitherUnicodeFlag(regexpRecord)가 true이고 regexpRecord.[[IgnoreCase]]true이면,
    1. Unicode Character Database의 파일 CaseFolding.txtch에 대해 simple 또는 common case folding 매핑을 제공하면, 그 매핑을 ch에 적용한 결과를 반환한다.
    2. ch를 반환한다.
  2. regexpRecord.[[IgnoreCase]]false이면 ch를 반환한다.
  3. Assert: ch는 UTF-16 코드 단위이다.
  4. cp를 수치 값이 ch의 수치 값인 코드 포인트라고 하자.
  5. u를 Unicode Default Case Conversion 알고리즘에 따른 toUppercase(« cp »)라고 하자.
  6. uStrCodePointsToString(u)라고 하자.
  7. uStr의 길이가 1이 아니면 ch를 반환한다.
  8. cuuStr의 단일 코드 단위 요소라고 하자.
  9. ch의 수치 값 ≥ 128이고 cu의 수치 값 < 128이면 ch를 반환한다.
  10. cu를 반환한다.
Note

HasEitherUnicodeFlag(regexpRecord)가 true인 대소문자 비구분 매치에서는, 모든 character가 비교되기 직전에 Unicode Standard가 제공하는 simple 매핑을 사용해 암묵적으로 case-fold된다. simple 매핑은 항상 단일 코드 포인트로 매핑하므로, 예를 들어 ß (U+00DF LATIN SMALL LETTER SHARP S)를 ssSS로 매핑하지 않는다. 그러나 Basic Latin 블록 밖의 코드 포인트를 그 안의 코드 포인트로 매핑할 수는 있다. 예를 들어, ſ (U+017F LATIN SMALL LETTER LONG S)는 s (U+0073 LATIN SMALL LETTER S)로 case-fold되고 (U+212A KELVIN SIGN)는 k (U+006B LATIN SMALL LETTER K)로 case-fold된다. 이러한 코드 포인트를 포함하는 String들은 /[a-z]/ui와 같은 정규 표현식에 의해 매치된다.

HasEitherUnicodeFlag(regexpRecord)가 false인 대소문자 비구분 매치에서는, 매핑이 toCasefold가 아니라 Unicode Default Case Conversion 알고리즘 toUppercase에 기반하므로 몇 가지 미묘한 차이가 생긴다. 예를 들어, (U+2126 OHM SIGN)는 toUppercase에 의해 자기 자신으로 매핑되지만 toCasefold에 의해 Ω (U+03A9 GREEK CAPITAL LETTER OMEGA)와 함께 ω (U+03C9 GREEK SMALL LETTER OMEGA)로 매핑되므로, "\u2126"/[ω]/ui/[\u03A9]/ui에는 매치되지만 /[ω]/i/[\u03A9]/i에는 매치되지 않는다. 또한 Basic Latin 블록 밖의 어떤 코드 포인트도 그 안의 코드 포인트로 매핑되지 않으므로, "\u017F ſ""\u212A K"와 같은 String은 /[a-z]/i에 매치되지 않는다.

22.2.2.7.4 UpdateModifiers ( regexpRecord, add, remove )

The abstract operation UpdateModifiers takes arguments regexpRecord (a RegExp Record), add (a String), and remove (a String) and returns a RegExp Record. It performs the following steps when called:

  1. Assert: addremove는 공통 요소를 가지지 않는다.
  2. ignoreCaseregexpRecord.[[IgnoreCase]]라고 하자.
  3. multilineregexpRecord.[[Multiline]]이라고 하자.
  4. dotAllregexpRecord.[[DotAll]]이라고 하자.
  5. unicoderegexpRecord.[[Unicode]]라고 하자.
  6. unicodeSetsregexpRecord.[[UnicodeSets]]라고 하자.
  7. capturingGroupsCountregexpRecord.[[CapturingGroupsCount]]라고 하자.
  8. remove"i"를 포함하면 ignoreCasefalse로 설정한다.
  9. 그렇지 않고 add"i"를 포함하면 ignoreCasetrue로 설정한다.
  10. remove"m"을 포함하면 multilinefalse로 설정한다.
  11. 그렇지 않고 add"m"을 포함하면 multilinetrue로 설정한다.
  12. remove"s"를 포함하면 dotAllfalse로 설정한다.
  13. 그렇지 않고 add"s"를 포함하면 dotAlltrue로 설정한다.
  14. RegExp Record { [[IgnoreCase]]: ignoreCase, [[Multiline]]: multiline, [[DotAll]]: dotAll, [[Unicode]]: unicode, [[UnicodeSets]]: unicodeSets, [[CapturingGroupsCount]]: capturingGroupsCount }를 반환한다.

22.2.2.8 Runtime Semantics: CompileCharacterClass

The syntax-directed operation CompileCharacterClass takes argument regexpRecord (a RegExp Record) and returns a Record with fields [[CharSet]] (a CharSet) and [[Invert]] (a Boolean). It is defined piecewise over the following productions:

CharacterClass :: [ ClassContents ]
  1. charSet을 인자 regexpRecordClassContentsCompileToCharSet이라고 하자.
  2. Record { [[CharSet]]: charSet, [[Invert]]: false }를 반환한다.
CharacterClass :: [^ ClassContents ]
  1. charSet을 인자 regexpRecordClassContentsCompileToCharSet이라고 하자.
  2. regexpRecord.[[UnicodeSets]]true이면,
    1. Record { [[CharSet]]: CharacterComplement(regexpRecord, charSet), [[Invert]]: false }를 반환한다.
  3. Record { [[CharSet]]: charSet, [[Invert]]: true }를 반환한다.

22.2.2.9 Runtime Semantics: CompileToCharSet

The syntax-directed operation CompileToCharSet takes argument regexpRecord (a RegExp Record) and returns a CharSet.

Note 1

이 절은 B.1.2.8에서 수정된다.

It is defined piecewise over the following productions:

ClassContents :: [empty]
  1. CharSet을 반환한다.
NonemptyClassRanges :: ClassAtom NonemptyClassRangesNoDash
  1. charSet을 인자 regexpRecordClassAtomCompileToCharSet이라고 하자.
  2. otherSet을 인자 regexpRecordNonemptyClassRangesNoDashCompileToCharSet이라고 하자.
  3. CharSet charSetotherSet의 합집합을 반환한다.
NonemptyClassRanges :: ClassAtom - ClassAtom ClassContents
  1. charSet을 인자 regexpRecord로 첫 번째 ClassAtomCompileToCharSet이라고 하자.
  2. otherSet을 인자 regexpRecord로 두 번째 ClassAtomCompileToCharSet이라고 하자.
  3. remainingSet을 인자 regexpRecordClassContentsCompileToCharSet이라고 하자.
  4. rangeSetCharacterRange(charSet, otherSet)라고 하자.
  5. rangeSetremainingSet의 합집합을 반환한다.
NonemptyClassRangesNoDash :: ClassAtomNoDash NonemptyClassRangesNoDash
  1. charSet을 인자 regexpRecordClassAtomNoDashCompileToCharSet이라고 하자.
  2. otherSet을 인자 regexpRecordNonemptyClassRangesNoDashCompileToCharSet이라고 하자.
  3. CharSet charSetotherSet의 합집합을 반환한다.
NonemptyClassRangesNoDash :: ClassAtomNoDash - ClassAtom ClassContents
  1. charSet을 인자 regexpRecordClassAtomNoDashCompileToCharSet이라고 하자.
  2. otherSet을 인자 regexpRecordClassAtomCompileToCharSet이라고 하자.
  3. remainingSet을 인자 regexpRecordClassContentsCompileToCharSet이라고 하자.
  4. rangeSetCharacterRange(charSet, otherSet)라고 하자.
  5. rangeSetremainingSet의 합집합을 반환한다.
Note 2

ClassContents는 단일 ClassAtom 및/또는 대시로 구분된 두 ClassAtom의 범위로 전개될 수 있다. 후자의 경우 ClassContents는 첫 번째 ClassAtom과 두 번째 ClassAtom 사이의 모든 character를 포함하며, 양 끝도 포함한다; 어느 ClassAtom이 단일 character를 나타내지 않거나(예를 들어, 하나가 \w인 경우) 첫 번째 ClassAtom의 character value가 두 번째 ClassAtom의 character value보다 엄격히 크면 오류가 발생한다.

Note 3

패턴이 대소문자를 무시하더라도, 범위의 두 끝의 대소문자는 어떤 character가 그 범위에 속하는지 결정하는 데 중요하다. 따라서 예를 들어, 패턴 /[E-F]/i는 문자 E, F, e, f에만 매치하는 반면, 패턴 /[E-f]/i는 Unicode Basic Latin 블록의 모든 대문자와 소문자뿐만 아니라 기호 [, \, ], ^, _, 및 `에도 매치한다.

Note 4

- character는 리터럴로 취급될 수도 있고 범위를 나타낼 수도 있다. ClassContents의 첫 번째 또는 마지막 character이거나, 범위 지정의 시작 또는 끝 한계이거나, 범위 지정 바로 뒤에 오면 리터럴로 취급된다.

ClassAtom :: -
  1. 단일 character - U+002D (HYPHEN-MINUS)를 포함하는 CharSet을 반환한다.
ClassAtomNoDash :: SourceCharacter but not one of \ or ] or -
  1. SourceCharacter와 일치한 character를 포함하는 CharSet을 반환한다.
ClassEscape :: b - CharacterEscape
  1. cv를 이 ClassEscapeCharacterValue라고 하자.
  2. c를 character value가 cv인 character라고 하자.
  3. 단일 character c를 포함하는 CharSet을 반환한다.
Note 5

ClassAtom\b, \B, 및 역참조를 제외하고 정규 표현식의 나머지에서 허용되는 어떤 escape sequence든 사용할 수 있다. CharacterClass 안에서 \b는 백스페이스 character를 의미하고, \B와 역참조는 오류를 일으킨다. ClassAtom 안에서 역참조를 사용하면 오류가 발생한다.

CharacterClassEscape :: d
  1. character 0, 1, 2, 3, 4, 5, 6, 7, 8, 및 9를 포함하는 열 요소 CharSet을 반환한다.
CharacterClassEscape :: D
  1. charSet CharacterClassEscape :: d 가 반환한 CharSet이라고 하자.
  2. CharacterComplement(regexpRecord, charSet)를 반환한다.
CharacterClassEscape :: s
  1. WhiteSpace 또는 LineTerminator 생성식의 오른쪽에 있는 코드 포인트에 대응하는 모든 character를 포함하는 CharSet을 반환한다.
CharacterClassEscape :: S
  1. charSet CharacterClassEscape :: s 가 반환한 CharSet이라고 하자.
  2. CharacterComplement(regexpRecord, charSet)를 반환한다.
CharacterClassEscape :: w
  1. MaybeSimpleCaseFolding(regexpRecord, WordCharacters(regexpRecord))를 반환한다.
CharacterClassEscape :: W
  1. charSet CharacterClassEscape :: w 가 반환한 CharSet이라고 하자.
  2. CharacterComplement(regexpRecord, charSet)를 반환한다.
CharacterClassEscape :: p{ UnicodePropertyValueExpression }
  1. 인자 regexpRecordUnicodePropertyValueExpressionCompileToCharSet을 반환한다.
CharacterClassEscape :: P{ UnicodePropertyValueExpression }
  1. charSet을 인자 regexpRecordUnicodePropertyValueExpressionCompileToCharSet이라고 하자.
  2. Assert: charSet은 단일 코드 포인트만 포함한다.
  3. CharacterComplement(regexpRecord, charSet)를 반환한다.
UnicodePropertyValueExpression :: UnicodePropertyName = UnicodePropertyValue
  1. psUnicodePropertyName일치한 소스 텍스트라고 하자.
  2. pUnicodeMatchProperty(regexpRecord, ps)라고 하자.
  3. Assert: pTable 64의 “Property name and aliases” 열에 나열된 Unicode property name 또는 property alias이다.
  4. vsUnicodePropertyValue일치한 소스 텍스트라고 하자.
  5. vUnicodeMatchPropertyValue(p, vs)라고 하자.
  6. charSet을 character database 정의가 값 v를 가진 속성 p를 포함하는 모든 Unicode 코드 포인트를 포함하는 CharSet이라고 하자.
  7. MaybeSimpleCaseFolding(regexpRecord, charSet)를 반환한다.
UnicodePropertyValueExpression :: LoneUnicodePropertyNameOrValue
  1. sLoneUnicodePropertyNameOrValue일치한 소스 텍스트라고 하자.
  2. UnicodeMatchPropertyValue(General_Category, s)가 PropertyValueAliases.txt에 나열된 General_Category (gc) 속성에 대한 Unicode property value 또는 property value alias이면,
    1. character database 정의가 값 s를 가진 속성 “General_Category”를 포함하는 모든 Unicode 코드 포인트를 포함하는 CharSet을 반환한다.
  3. pUnicodeMatchProperty(regexpRecord, s)라고 하자.
  4. Assert: pTable 65의 “Property name and aliases” 열에 나열된 이진 Unicode 속성 또는 이진 속성 별칭이거나, Table 66의 “Property name” 열에 나열된 문자열의 이진 Unicode 속성이다.
  5. charSet을 character database 정의가 값 “True”를 가진 속성 p를 포함하는 모든 CharSetElement를 포함하는 CharSet이라고 하자.
  6. MaybeSimpleCaseFolding(regexpRecord, charSet)를 반환한다.
ClassUnion :: ClassSetRange ClassUnionopt
  1. charSet을 인자 regexpRecordClassSetRangeCompileToCharSet이라고 하자.
  2. ClassUnion이 존재하면,
    1. otherSet을 인자 regexpRecordClassUnionCompileToCharSet이라고 하자.
    2. CharSet charSetotherSet의 합집합을 반환한다.
  3. charSet을 반환한다.
ClassUnion :: ClassSetOperand ClassUnionopt
  1. charSet을 인자 regexpRecordClassSetOperandCompileToCharSet이라고 하자.
  2. ClassUnion이 존재하면,
    1. otherSet을 인자 regexpRecordClassUnionCompileToCharSet이라고 하자.
    2. CharSet charSetotherSet의 합집합을 반환한다.
  3. charSet을 반환한다.
ClassIntersection :: ClassSetOperand && ClassSetOperand
  1. charSet을 인자 regexpRecord로 첫 번째 ClassSetOperandCompileToCharSet이라고 하자.
  2. otherSet을 인자 regexpRecord로 두 번째 ClassSetOperandCompileToCharSet이라고 하자.
  3. CharSet charSetotherSet의 교집합을 반환한다.
ClassIntersection :: ClassIntersection && ClassSetOperand
  1. charSet을 인자 regexpRecordClassIntersectionCompileToCharSet이라고 하자.
  2. otherSet을 인자 regexpRecordClassSetOperandCompileToCharSet이라고 하자.
  3. CharSet charSetotherSet의 교집합을 반환한다.
ClassSubtraction :: ClassSetOperand -- ClassSetOperand
  1. charSet을 인자 regexpRecord로 첫 번째 ClassSetOperandCompileToCharSet이라고 하자.
  2. otherSet을 인자 regexpRecord로 두 번째 ClassSetOperandCompileToCharSet이라고 하자.
  3. otherSetCharSetElement이기도 하지 않은 charSetCharSetElement를 포함하는 CharSet을 반환한다.
ClassSubtraction :: ClassSubtraction -- ClassSetOperand
  1. charSet을 인자 regexpRecordClassSubtractionCompileToCharSet이라고 하자.
  2. otherSet을 인자 regexpRecordClassSetOperandCompileToCharSet이라고 하자.
  3. otherSetCharSetElement이기도 하지 않은 charSetCharSetElement를 포함하는 CharSet을 반환한다.
ClassSetRange :: ClassSetCharacter - ClassSetCharacter
  1. charSet을 인자 regexpRecord로 첫 번째 ClassSetCharacterCompileToCharSet이라고 하자.
  2. otherSet을 인자 regexpRecord로 두 번째 ClassSetCharacterCompileToCharSet이라고 하자.
  3. MaybeSimpleCaseFolding(regexpRecord, CharacterRange(charSet, otherSet))를 반환한다.
Note 6

결과는 종종 둘 이상의 범위로 구성된다. UnicodeSets가 true이고 IgnoreCase가 true이면, MaybeSimpleCaseFolding(regexpRecord, [Ā-č])는 그 범위의 홀수 번호 코드 포인트만 포함한다.

ClassSetOperand :: ClassSetCharacter
  1. charSet을 인자 regexpRecordClassSetCharacterCompileToCharSet이라고 하자.
  2. MaybeSimpleCaseFolding(regexpRecord, charSet)를 반환한다.
ClassSetOperand :: ClassStringDisjunction
  1. charSet을 인자 regexpRecordClassStringDisjunctionCompileToCharSet이라고 하자.
  2. MaybeSimpleCaseFolding(regexpRecord, charSet)를 반환한다.
ClassSetOperand :: NestedClass
  1. 인자 regexpRecordNestedClassCompileToCharSet을 반환한다.
NestedClass :: [ ClassContents ]
  1. 인자 regexpRecordClassContentsCompileToCharSet을 반환한다.
NestedClass :: [^ ClassContents ]
  1. charSet을 인자 regexpRecordClassContentsCompileToCharSet이라고 하자.
  2. CharacterComplement(regexpRecord, charSet)를 반환한다.
NestedClass :: \ CharacterClassEscape
  1. 인자 regexpRecordCharacterClassEscapeCompileToCharSet을 반환한다.
ClassStringDisjunction :: \q{ ClassStringDisjunctionContents }
  1. 인자 regexpRecordClassStringDisjunctionContentsCompileToCharSet을 반환한다.
ClassStringDisjunctionContents :: ClassString
  1. s를 인자 regexpRecordClassStringCompileClassSetString이라고 하자.
  2. 하나의 string s를 포함하는 CharSet을 반환한다.
ClassStringDisjunctionContents :: ClassString | ClassStringDisjunctionContents
  1. s를 인자 regexpRecordClassStringCompileClassSetString이라고 하자.
  2. charSet을 하나의 string s를 포함하는 CharSet이라고 하자.
  3. otherSet을 인자 regexpRecordClassStringDisjunctionContentsCompileToCharSet이라고 하자.
  4. CharSet charSetotherSet의 합집합을 반환한다.
ClassSetCharacter :: SourceCharacter but not ClassSetSyntaxCharacter \ CharacterEscape \ ClassSetReservedPunctuator
  1. cv를 이 ClassSetCharacterCharacterValue라고 하자.
  2. c를 character value가 cv인 character라고 하자.
  3. 단일 character c를 포함하는 CharSet을 반환한다.
ClassSetCharacter :: \b
  1. 단일 character U+0008 (BACKSPACE)를 포함하는 CharSet을 반환한다.

22.2.2.9.1 CharacterRange ( charSet, otherSet )

The abstract operation CharacterRange takes arguments charSet (a CharSet) and otherSet (a CharSet) and returns a CharSet. It performs the following steps when called:

  1. Assert: charSetotherSet은 각각 정확히 하나의 character를 포함한다.
  2. aCharSet charSet 안의 하나의 character라고 하자.
  3. bCharSet otherSet 안의 하나의 character라고 하자.
  4. i를 character a의 character value라고 하자.
  5. j를 character b의 character value라고 하자.
  6. Assert: ij.
  7. i부터 j까지의 포함 구간에 있는 character value를 가진 모든 character를 포함하는 CharSet을 반환한다.

22.2.2.9.2 HasEitherUnicodeFlag ( regexpRecord )

The abstract operation HasEitherUnicodeFlag takes argument regexpRecord (a RegExp Record) and returns a Boolean. It performs the following steps when called:

  1. regexpRecord.[[Unicode]]true이거나 regexpRecord.[[UnicodeSets]]true이면 true를 반환한다.
  2. false를 반환한다.

22.2.2.9.3 WordCharacters ( regexpRecord )

The abstract operation WordCharacters takes argument regexpRecord (a RegExp Record) and returns a CharSet. \b, \B, \w, 및 \W의 목적상 "word characters"로 간주되는 character들을 포함하는 CharSet을 반환한다. It performs the following steps when called:

  1. basicWordChars를 ASCII word characters 안의 모든 character를 포함하는 CharSet이라고 하자.
  2. extraWordCharsbasicWordChars 안에 없지만 Canonicalize(regexpRecord, c)가 basicWordChars 안에 있는 모든 character c를 포함하는 CharSet이라고 하자.
  3. Assert: HasEitherUnicodeFlag(regexpRecord)가 true이고 regexpRecord.[[IgnoreCase]]true인 경우가 아니면 extraWordChars는 비어 있다.
  4. basicWordCharsextraWordChars의 합집합을 반환한다.

22.2.2.9.4 AllCharacters ( regexpRecord )

The abstract operation AllCharacters takes argument regexpRecord (a RegExp Record) and returns a CharSet. 정규 표현식 플래그에 따른 “all characters”의 집합을 반환한다. It performs the following steps when called:

  1. regexpRecord.[[UnicodeSets]]true이고 regexpRecord.[[IgnoreCase]]true이면,
    1. Simple Case Folding 매핑을 가지지 않는(즉, scf(c)=c인) 모든 Unicode 코드 포인트 c를 포함하는 CharSet을 반환한다.
  2. HasEitherUnicodeFlag(regexpRecord)가 true이면,
    1. 모든 코드 포인트 값을 포함하는 CharSet을 반환한다.
  3. 모든 코드 단위 값을 포함하는 CharSet을 반환한다.

22.2.2.9.5 MaybeSimpleCaseFolding ( regexpRecord, charSet )

The abstract operation MaybeSimpleCaseFolding takes arguments regexpRecord (a RegExp Record) and charSet (a CharSet) and returns a CharSet. regexpRecord.[[UnicodeSets]]false이거나 regexpRecord.[[IgnoreCase]]false이면, charSet을 반환한다. 그렇지 않으면, Unicode Character Database의 파일 CaseFolding.txt에 있는 Simple Case Folding (scf(cp)) 정의(각각 단일 코드 포인트를 다른 단일 코드 포인트로 매핑함)를 사용하여 charSet의 각 CharSetElement를 character별로 정준 형식으로 매핑하고, 그 결과 CharSet을 반환한다. It performs the following steps when called:

  1. regexpRecord.[[UnicodeSets]]false이거나 regexpRecord.[[IgnoreCase]]false이면 charSet을 반환한다.
  2. otherSet을 새로운 빈 CharSet이라고 하자.
  3. charSet의 각 CharSetElement s에 대해, 다음을 수행한다.
    1. t를 빈 character 시퀀스라고 하자.
    2. s 안의 각 단일 코드 포인트 cp에 대해, 다음을 수행한다.
      1. scf(cp)를 t에 추가한다.
    3. totherSet에 추가한다.
  4. otherSet을 반환한다.

22.2.2.9.6 CharacterComplement ( regexpRecord, complement )

The abstract operation CharacterComplement takes arguments regexpRecord (a RegExp Record) and complement (a CharSet) and returns a CharSet. It performs the following steps when called:

  1. charSetAllCharacters(regexpRecord)라고 하자.
  2. complementCharSetElement이기도 하지 않은 charSetCharSetElement를 포함하는 CharSet을 반환한다.

22.2.2.9.7 UnicodeMatchProperty ( regexpRecord, p )

The abstract operation UnicodeMatchProperty takes arguments regexpRecord (a RegExp Record) and p (ECMAScript source text) and returns a Unicode property name. It performs the following steps when called:

  1. regexpRecord.[[UnicodeSets]]true이고 pTable 66의 “Property name” 열에 나열된 Unicode property name이면,
    1. Unicode 코드 포인트의 List p를 반환한다.
  2. Assert: pTable 64 또는 Table 65의 “Property name and aliases” 열에 나열된 Unicode property name 또는 property alias이다.
  3. c를 해당 행의 “Canonical property name” 열에 주어진 p의 정준 property name이라고 하자.
  4. Unicode 코드 포인트의 List c를 반환한다.

구현은 Table 64, Table 65, 및 Table 66에 나열된 Unicode property names와 별칭을 지원해야 한다. 상호 운용성을 보장하기 위해, 구현은 다른 어떤 property names나 별칭도 지원해서는 안 된다.

Note 1

예를 들어, Script_Extensions(property name)와 scx(property alias)는 유효하지만, script_extensionsScx는 유효하지 않다.

Note 2

나열된 속성들은 UTS18 RL1.2가 요구하는 것의 상위 집합을 형성한다.

Note 3

이 표들에 있는 항목들의 철자(대소문자 포함)는 Unicode Character Database의 파일 PropertyAliases.txt에서 사용되는 철자와 일치한다. 그 파일의 정확한 철자는 안정적으로 보장된다.

Table 64: 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 65: 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 66: Binary Unicode properties of strings
Property name
Basic_Emoji
Emoji_Keycap_Sequence
RGI_Emoji_Modifier_Sequence
RGI_Emoji_Flag_Sequence
RGI_Emoji_Tag_Sequence
RGI_Emoji_ZWJ_Sequence
RGI_Emoji

22.2.2.9.8 UnicodeMatchPropertyValue ( p, v )

The abstract operation UnicodeMatchPropertyValue takes arguments p (ECMAScript source text) and v (ECMAScript source text) and returns a Unicode property value. It performs the following steps when called:

  1. Assert: pTable 64의 “Canonical property name” 열에 나열된 정준적이고 별칭이 아닌 Unicode property name이다.
  2. Assert: vPropertyValueAliases.txt에 나열된 Unicode 속성 p에 대한 property value 또는 property value alias이다.
  3. value를 해당 행의 “Canonical property value” 열에 주어진 v의 정준 속성 값이라고 하자.
  4. Unicode 코드 포인트의 List value를 반환한다.

구현은 Table 64에 나열된 속성에 대해 PropertyValueAliases.txt에 나열된 Unicode 속성 값과 속성 값 별칭을 지원해야 한다. 상호 운용성을 보장하기 위해, 구현은 다른 어떤 속성 값이나 속성 값 별칭도 지원해서는 안 된다.

Note 1

예를 들어, XpeoOld_Persian은 유효한 Script_Extensions 값이지만, xpeoOld Persian은 유효하지 않다.

Note 2

이 알고리즘은 UAX44에 나열된 symbolic values에 대한 매칭 규칙과 다르다: 대소문자, white space, U+002D (HYPHEN-MINUS), 및 U+005F (LOW LINE)는 무시되지 않으며, Is 접두사는 지원되지 않는다.

22.2.2.10 Runtime Semantics: CompileClassSetString

The syntax-directed operation CompileClassSetString takes argument regexpRecord (a RegExp Record) and returns a sequence of characters. It is defined piecewise over the following productions:

ClassString :: [empty]
  1. 빈 character 시퀀스를 반환한다.
ClassString :: NonEmptyClassString
  1. 인자 regexpRecordNonEmptyClassStringCompileClassSetString을 반환한다.
NonEmptyClassString :: ClassSetCharacter NonEmptyClassStringopt
  1. cs를 인자 regexpRecordClassSetCharacterCompileToCharSet이라고 하자.
  2. s1cs의 단일 CharSetElement인 character 시퀀스라고 하자.
  3. NonEmptyClassString이 존재하면,
    1. s2를 인자 regexpRecordNonEmptyClassStringCompileClassSetString이라고 하자.
    2. s1s2의 연결을 반환한다.
  4. s1을 반환한다.

22.2.3 RegExp 생성을 위한 추상 연산

22.2.3.1 RegExpCreate ( pattern, flags )

The abstract operation RegExpCreate takes arguments pattern (an ECMAScript language value) and flags (a String or undefined) and returns either a normal completion containing an Object or a throw completion. It performs the following steps when called:

  1. obj를 ! RegExpAlloc(%RegExp%)라고 하자.
  2. RegExpInitialize(obj, pattern, flags)를 반환한다.

22.2.3.2 RegExpAlloc ( newTarget )

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

  1. obj를 ? OrdinaryCreateFromConstructor(newTarget, "%RegExp.prototype%", « [[OriginalSource]], [[OriginalFlags]], [[RegExpRecord]], [[RegExpMatcher]] »)라고 하자.
  2. DefinePropertyOrThrow(obj, "lastIndex", PropertyDescriptor { [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false })를 수행한다.
  3. obj를 반환한다.

22.2.3.3 RegExpInitialize ( obj, pattern, flags )

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

  1. patternundefined이면, pattern을 빈 String으로 설정한다.
  2. 그렇지 않으면, pattern을 ? ToString(pattern)으로 설정한다.
  3. flagsundefined이면, flags를 빈 String으로 설정한다.
  4. 그렇지 않으면, flags를 ? ToString(flags)로 설정한다.
  5. flags"d", "g", "i", "m", "s", "u", "v", 또는 "y"가 아닌 코드 단위를 포함하면, SyntaxError 예외를 던진다.
  6. flags가 어떤 코드 단위든 두 번 이상 포함하면, SyntaxError 예외를 던진다.
  7. flags"i"를 포함하면 itrue라고 하자; 그렇지 않으면 ifalse라고 하자.
  8. flags"m"을 포함하면 mtrue라고 하자; 그렇지 않으면 mfalse라고 하자.
  9. flags"s"를 포함하면 strue라고 하자; 그렇지 않으면 sfalse라고 하자.
  10. flags"u"를 포함하면 utrue라고 하자; 그렇지 않으면 ufalse라고 하자.
  11. flags"v"를 포함하면 vtrue라고 하자; 그렇지 않으면 vfalse라고 하자.
  12. utrue이거나 vtrue이면,
    1. patternTextStringToCodePoints(pattern)라고 하자.
  13. 그렇지 않으면,
    1. patternTextpattern의 각 16비트 요소를 Unicode BMP 코드 포인트로 해석한 결과라고 하자. UTF-16 디코딩은 그 요소들에 적용되지 않는다.
  14. parseResultParsePattern(patternText, u, v)라고 하자.
  15. parseResultSyntaxError 객체들의 비어 있지 않은 List이면, SyntaxError 예외를 던진다.
  16. Assert: parseResultPattern Parse Node이다.
  17. obj.[[OriginalSource]]pattern으로 설정한다.
  18. obj.[[OriginalFlags]]flags로 설정한다.
  19. capturingGroupsCountCountLeftCapturingParensWithin(parseResult)라고 하자.
  20. regexpRecordRegExp Record { [[IgnoreCase]]: i, [[Multiline]]: m, [[DotAll]]: s, [[Unicode]]: u, [[UnicodeSets]]: v, [[CapturingGroupsCount]]: capturingGroupsCount }라고 하자.
  21. obj.[[RegExpRecord]]regexpRecord로 설정한다.
  22. obj.[[RegExpMatcher]]를 인자 regexpRecordparseResultCompilePattern으로 설정한다.
  23. Set(obj, "lastIndex", +0𝔽, true)를 수행한다.
  24. obj를 반환한다.

22.2.3.4 Static Semantics: ParsePattern ( patternText, u, v )

The abstract operation ParsePattern takes arguments patternText (a sequence of Unicode code points), u (a Boolean), and v (a Boolean) and returns a Parse Node or a non-empty List of SyntaxError objects.

Note

이 절은 B.1.2.9에서 수정된다.

It performs the following steps when called:

  1. vtrue이고 utrue이면,
    1. parseResult를 하나 이상의 SyntaxError 객체를 포함하는 List라고 하자.
  2. 그렇지 않고 vtrue이면,
    1. parseResultParseText(patternText, Pattern[+UnicodeMode, +UnicodeSetsMode, +NamedCaptureGroups])라고 하자.
  3. 그렇지 않고 utrue이면,
    1. parseResultParseText(patternText, Pattern[+UnicodeMode, ~UnicodeSetsMode, +NamedCaptureGroups])라고 하자.
  4. 그렇지 않으면,
    1. parseResultParseText(patternText, Pattern[~UnicodeMode, ~UnicodeSetsMode, +NamedCaptureGroups])라고 하자.
  5. parseResult를 반환한다.

22.2.4 RegExp 생성자

RegExp 생성자는:

  • %RegExp%이다.
  • 전역 객체"RegExp" 속성의 초기값이다.
  • 생성자로 호출될 때 새로운 RegExp 객체를 생성하고 초기화한다.
  • 생성자가 아니라 함수로 호출될 때, 새로운 RegExp 객체를 반환하거나 유일한 인자가 RegExp 객체이면 그 인자 자체를 반환한다.
  • 클래스 정의의 extends 절의 값으로 사용될 수 있다. 지정된 RegExp 동작을 상속하려는 서브클래스 생성자는 필요한 내부 슬롯을 가진 서브클래스 인스턴스를 생성하고 초기화하기 위해 RegExp 생성자에 대한 super 호출을 포함해야 한다.

22.2.4.1 RegExp ( patternOrRegexp, flags )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. patternIsRegExp를 ? IsRegExp(patternOrRegexp)라고 하자.
  2. NewTarget이 undefined이면,
    1. newTarget을 활성 함수 객체라고 하자.
    2. patternIsRegExptrue이고 flagsundefined이면,
      1. patternConstructor를 ? Get(patternOrRegexp, "constructor")라고 하자.
      2. SameValue(newTarget, patternConstructor)가 true이면 patternOrRegexp를 반환한다.
  3. 그렇지 않으면,
    1. newTarget을 NewTarget이라고 하자.
  4. patternOrRegexp가 Object이고 [[RegExpMatcher]] 내부 슬롯을 가지면,
    1. patternSourcepatternOrRegexp.[[OriginalSource]]라고 하자.
    2. flagsundefined이면, flagspatternOrRegexp.[[OriginalFlags]]로 설정한다.
  5. 그렇지 않고 patternIsRegExptrue이면,
    1. patternSource를 ? Get(patternOrRegexp, "source")라고 하자.
    2. flagsundefined이면,
      1. flags를 ? Get(patternOrRegexp, "flags")로 설정한다.
  6. 그렇지 않으면,
    1. patternSourcepatternOrRegexp라고 하자.
  7. obj를 ? RegExpAlloc(newTarget)라고 하자.
  8. RegExpInitialize(obj, patternSource, flags)를 반환한다.
Note

pattern이 StringLiteral을 사용해 제공되면, String이 이 함수에 의해 처리되기 전에 일반적인 escape sequence 치환이 수행된다. pattern이 이 함수에 의해 인식되어야 하는 escape sequence를 포함해야 하는 경우, StringLiteral의 내용이 형성될 때 U+005C (REVERSE SOLIDUS) 코드 포인트가 제거되지 않도록 StringLiteral 안에서 escape되어야 한다.

22.2.5 RegExp 생성자의 속성

RegExp 생성자는:

  • 값이 %Function.prototype%[[Prototype]] 내부 슬롯을 가진다.
  • 다음 속성들을 가진다:

22.2.5.1 RegExp.escape ( str )

이 함수는 정규 표현식 Pattern에서 잠재적으로 특별한 문자들이 동등한 escape sequence로 대체된 str의 사본을 반환한다.

이 함수는 호출될 때 다음 단계를 수행한다:

  1. str이 String이 아니면, TypeError 예외를 던진다.
  2. escaped를 빈 String이라고 하자.
  3. cpListStringToCodePoints(str)라고 하자.
  4. cpList의 각 코드 포인트 cp에 대해, 다음을 수행한다.
    1. escaped가 빈 String이고 cpDecimalDigit 또는 AsciiLetter 중 하나와 일치하면,
      1. NOTE: 선행 숫자를 escape하면 출력이 \0 문자 escape 또는 \1과 같은 DecimalEscape 뒤에서 사용될 수 있는 패턴 텍스트와 대응하며, 앞선 escape sequence의 확장으로 해석되지 않고 여전히 str과 매치되도록 보장한다. 선행 ASCII 문자를 escape하는 것은 \c 뒤의 문맥에 대해 같은 일을 한다.
      2. numericValuecp의 수치 값이라고 하자.
      3. hexNumber::toString(𝔽(numericValue), 16)이라고 하자.
      4. Assert: hex의 길이는 2이다.
      5. escaped를 코드 단위 0x005C (REVERSE SOLIDUS), "x", 및 hex의 문자열 연결로 설정한다.
    2. 그렇지 않으면,
      1. escapedescapedEncodeForRegExpEscape(cp)의 문자열 연결로 설정한다.
  5. escaped를 반환한다.
Note

이름이 비슷하지만, EscapeRegExpPatternRegExp.escape는 비슷한 동작을 수행하지 않는다. 전자는 문자열로 표현하기 위해 패턴을 escape하는 반면, 이 함수는 패턴 안에서 표현하기 위해 문자열을 escape한다.

22.2.5.1.1 EncodeForRegExpEscape ( cp )

The abstract operation EncodeForRegExpEscape takes argument cp (a code point) and returns a String. 이 연산은 cp와 매치하기 위한 Pattern을 나타내는 String을 반환한다. cp가 공백 문자이거나 ASCII 구두점이면, 반환값은 escape sequence이다. 그렇지 않으면, 반환값은 cp 자체의 String 표현이다. It performs the following steps when called:

  1. cpSyntaxCharacter와 일치하거나 cp가 U+002F (SOLIDUS)이면,
    1. 0x005C (REVERSE SOLIDUS)와 UTF16EncodeCodePoint(cp)의 문자열 연결을 반환한다.
  2. cpTable 62의 “Code Point” 열에 나열된 코드 포인트이면,
    1. 0x005C (REVERSE SOLIDUS)와 “Code Point” 열이 cp를 포함하는 행의 “ControlEscape” 열에 있는 문자열의 문자열 연결을 반환한다.
  3. otherPunctuators",-=<>#&!%:;@~'`"와 코드 단위 0x0022 (QUOTATION MARK)의 문자열 연결이라고 하자.
  4. toEscapeStringToCodePoints(otherPunctuators)라고 하자.
  5. toEscapecp를 포함하거나, cpWhiteSpace 또는 LineTerminator 중 하나와 일치하거나, cp가 선행 서로게이트 또는 후행 서로게이트와 같은 수치 값을 가지면,
    1. cpNumcp의 수치 값이라고 하자.
    2. cpNum ≤ 0xFF이면,
      1. hexNumber::toString(𝔽(cpNum), 16)이라고 하자.
      2. 코드 단위 0x005C (REVERSE SOLIDUS), "x", 및 StringPad(hex, 2, "0", start)의 문자열 연결을 반환한다.
    3. escaped를 빈 String이라고 하자.
    4. codeUnitsUTF16EncodeCodePoint(cp)라고 하자.
    5. codeUnits의 각 코드 단위 cu에 대해, 다음을 수행한다.
      1. escapedescapedUnicodeEscape(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 프로토타입 객체의 속성

RegExp 프로토타입 객체는:

  • %RegExp.prototype%이다.
  • 보통 객체이다.
  • RegExp 인스턴스가 아니며 [[RegExpMatcher]] 내부 슬롯이나 RegExp 인스턴스 객체의 다른 어떤 내부 슬롯도 가지지 않는다.
  • 값이 %Object.prototype%[[Prototype]] 내부 슬롯을 가진다.
Note

RegExp 프로토타입 객체는 자기 자신의 "valueOf" 속성을 가지지 않는다; 그러나 Object 프로토타입 객체로부터 "valueOf" 속성을 상속한다.

22.2.6.1 RegExp.prototype.constructor

RegExp.prototype.constructor의 초기값은 %RegExp%이다.

22.2.6.2 RegExp.prototype.exec ( string )

이 메서드는 string에서 정규 표현식 패턴의 출현을 검색하고 매치 결과를 포함하는 Array를 반환하거나, string이 매치되지 않았으면 null을 반환한다.

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. regexpthis 값이라고 하자.
  2. RequireInternalSlot(regexp, [[RegExpMatcher]])를 수행한다.
  3. str을 ? ToString(string)이라고 하자.
  4. RegExpBuiltinExec(regexp, str)를 반환한다.

22.2.6.3 get RegExp.prototype.dotAll

RegExp.prototype.dotAll은 set 접근자 함수가 undefined인 접근자 속성이다. 그 get 접근자 함수는 호출될 때 다음 단계를 수행한다:

  1. regexpthis 값이라고 하자.
  2. cu를 코드 단위 0x0073 (LATIN SMALL LETTER S)이라고 하자.
  3. RegExpHasFlag(regexp, cu)를 반환한다.

22.2.6.4 get RegExp.prototype.flags

RegExp.prototype.flags는 set 접근자 함수가 undefined인 접근자 속성이다. 그 get 접근자 함수는 호출될 때 다음 단계를 수행한다:

  1. regexpthis 값이라고 하자.
  2. regexp가 Object가 아니면, TypeError 예외를 던진다.
  3. codeUnits를 새로운 빈 List라고 하자.
  4. hasIndicesToBoolean(? Get(regexp, "hasIndices"))라고 하자.
  5. hasIndicestrue이면, 코드 단위 0x0064 (LATIN SMALL LETTER D)를 codeUnits에 추가한다.
  6. globalToBoolean(? Get(regexp, "global"))이라고 하자.
  7. globaltrue이면, 코드 단위 0x0067 (LATIN SMALL LETTER G)를 codeUnits에 추가한다.
  8. ignoreCaseToBoolean(? Get(regexp, "ignoreCase"))라고 하자.
  9. ignoreCasetrue이면, 코드 단위 0x0069 (LATIN SMALL LETTER I)를 codeUnits에 추가한다.
  10. multilineToBoolean(? Get(regexp, "multiline"))이라고 하자.
  11. multilinetrue이면, 코드 단위 0x006D (LATIN SMALL LETTER M)를 codeUnits에 추가한다.
  12. dotAllToBoolean(? Get(regexp, "dotAll"))이라고 하자.
  13. dotAlltrue이면, 코드 단위 0x0073 (LATIN SMALL LETTER S)를 codeUnits에 추가한다.
  14. unicodeToBoolean(? Get(regexp, "unicode"))라고 하자.
  15. unicodetrue이면, 코드 단위 0x0075 (LATIN SMALL LETTER U)를 codeUnits에 추가한다.
  16. unicodeSetsToBoolean(? Get(regexp, "unicodeSets"))라고 하자.
  17. unicodeSetstrue이면, 코드 단위 0x0076 (LATIN SMALL LETTER V)를 codeUnits에 추가한다.
  18. stickyToBoolean(? Get(regexp, "sticky"))라고 하자.
  19. stickytrue이면, 코드 단위 0x0079 (LATIN SMALL LETTER Y)를 codeUnits에 추가한다.
  20. 코드 단위가 List codeUnits의 요소인 String 값을 반환한다. codeUnits가 요소를 가지지 않으면, 빈 String이 반환된다.

22.2.6.4.1 RegExpHasFlag ( regexp, codeUnit )

The abstract operation RegExpHasFlag takes arguments regexp (an ECMAScript language value) and codeUnit (a code unit) and returns either a normal completion containing either a Boolean or undefined, or a throw completion. It performs the following steps when called:

  1. regexp가 Object가 아니면, TypeError 예외를 던진다.
  2. regexp[[OriginalFlags]] 내부 슬롯을 가지지 않으면,
    1. SameValue(regexp, %RegExp.prototype%)가 true이면, undefined를 반환한다.
    2. TypeError 예외를 던진다.
  3. flagsregexp.[[OriginalFlags]]라고 하자.
  4. flagscodeUnit을 포함하면, true를 반환한다.
  5. false를 반환한다.

22.2.6.5 get RegExp.prototype.global

RegExp.prototype.global은 set 접근자 함수가 undefined인 접근자 속성이다. 그 get 접근자 함수는 호출될 때 다음 단계를 수행한다:

  1. regexpthis 값이라고 하자.
  2. cu를 코드 단위 0x0067 (LATIN SMALL LETTER G)이라고 하자.
  3. RegExpHasFlag(regexp, cu)를 반환한다.

22.2.6.6 get RegExp.prototype.hasIndices

RegExp.prototype.hasIndices는 set 접근자 함수가 undefined인 접근자 속성이다. 그 get 접근자 함수는 호출될 때 다음 단계를 수행한다:

  1. regexpthis 값이라고 하자.
  2. cu를 코드 단위 0x0064 (LATIN SMALL LETTER D)라고 하자.
  3. RegExpHasFlag(regexp, cu)를 반환한다.

22.2.6.7 get RegExp.prototype.ignoreCase

RegExp.prototype.ignoreCase는 set 접근자 함수가 undefined인 접근자 속성이다. 그 get 접근자 함수는 호출될 때 다음 단계를 수행한다:

  1. regexpthis 값이라고 하자.
  2. cu를 코드 단위 0x0069 (LATIN SMALL LETTER I)라고 하자.
  3. RegExpHasFlag(regexp, cu)를 반환한다.

22.2.6.8 RegExp.prototype [ %Symbol.match% ] ( string )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. regexpthis 값이라고 하자.
  2. regexp가 Object가 아니면, TypeError 예외를 던진다.
  3. str을 ? ToString(string)이라고 하자.
  4. flags를 ? ToString(? Get(regexp, "flags"))라고 하자.
  5. flags"g"를 포함하지 않으면, ? RegExpExec(regexp, str)를 반환한다.
  6. flags"u"를 포함하거나 flags"v"를 포함하면 fullUnicodetrue라고 하자; 그렇지 않으면 fullUnicodefalse라고 하자.
  7. Set(regexp, "lastIndex", +0𝔽, true)를 수행한다.
  8. array를 ! ArrayCreate(0)이라고 하자.
  9. matchCount를 0이라고 하자.
  10. 반복한다,
    1. result를 ? RegExpExec(regexp, str)라고 하자.
    2. resultnull이면,
      1. matchCount = 0이면, null을 반환한다.
      2. array를 반환한다.
    3. matchStr을 ? ToString(? Get(result, "0"))라고 하자.
    4. CreateDataPropertyOrThrow(array, ! ToString(𝔽(matchCount)), matchStr)를 수행한다.
    5. matchStr이 빈 String이면,
      1. thisIndex(? ToLength(? Get(regexp, "lastIndex")))라고 하자.
      2. nextIndexAdvanceStringIndex(str, thisIndex, fullUnicode)라고 하자.
      3. Set(regexp, "lastIndex", 𝔽(nextIndex), true)를 수행한다.
    6. matchCountmatchCount + 1로 설정한다.

이 메서드의 "name" 속성의 값은 "[Symbol.match]"이다.

Note

%Symbol.match% 속성은 정규 표현식의 기본 동작을 가진 객체를 식별하기 위해 IsRegExp 추상 연산에서 사용된다. %Symbol.match% 속성이 없거나, 그러한 속성이 존재하지만 그 값이 Boolean으로 강제 변환될 때 true가 아닌 경우, 그 객체가 정규 표현식 객체로 사용되도록 의도되지 않았음을 나타낸다.

22.2.6.9 RegExp.prototype [ %Symbol.matchAll% ] ( string )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. regexpthis 값이라고 하자.
  2. regexp가 Object가 아니면, TypeError 예외를 던진다.
  3. str을 ? ToString(string)이라고 하자.
  4. speciesConstructor를 ? SpeciesConstructor(regexp, %RegExp%)라고 하자.
  5. flags를 ? ToString(? Get(regexp, "flags"))라고 하자.
  6. matcher를 ? Construct(speciesConstructor, « regexp, flags »)라고 하자.
  7. lastIndex를 ? ToLength(? Get(regexp, "lastIndex"))라고 하자.
  8. Set(matcher, "lastIndex", lastIndex, true)를 수행한다.
  9. flags"g"를 포함하면, globaltrue라고 하자.
  10. 그렇지 않으면, globalfalse라고 하자.
  11. flags"u"를 포함하거나 flags"v"를 포함하면, fullUnicodetrue라고 하자.
  12. 그렇지 않으면, fullUnicodefalse라고 하자.
  13. CreateRegExpStringIterator(matcher, str, global, fullUnicode)를 반환한다.

이 메서드의 "name" 속성의 값은 "[Symbol.matchAll]"이다.

22.2.6.10 get RegExp.prototype.multiline

RegExp.prototype.multiline은 set 접근자 함수가 undefined인 접근자 속성이다. 그 get 접근자 함수는 호출될 때 다음 단계를 수행한다:

  1. regexpthis 값이라고 하자.
  2. cu를 코드 단위 0x006D (LATIN SMALL LETTER M)이라고 하자.
  3. RegExpHasFlag(regexp, cu)를 반환한다.

22.2.6.11 RegExp.prototype [ %Symbol.replace% ] ( string, replaceValue )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. regexpthis 값이라고 하자.
  2. regexp가 Object가 아니면, TypeError 예외를 던진다.
  3. str을 ? ToString(string)이라고 하자.
  4. lengthSstr의 길이라고 하자.
  5. functionalReplaceIsCallable(replaceValue)라고 하자.
  6. functionalReplacefalse이면,
    1. replaceValue를 ? ToString(replaceValue)로 설정한다.
  7. flags를 ? ToString(? Get(regexp, "flags"))라고 하자.
  8. flags"g"를 포함하면 globaltrue라고 하자; 그렇지 않으면 globalfalse라고 하자.
  9. globaltrue이면,
    1. Set(regexp, "lastIndex", +0𝔽, true)를 수행한다.
  10. results를 새로운 빈 List라고 하자.
  11. donefalse라고 하자.
  12. donefalse인 동안 반복한다,
    1. result를 ? RegExpExec(regexp, str)라고 하자.
    2. resultnull이면,
      1. donetrue로 설정한다.
    3. 그렇지 않으면,
      1. resultresults에 추가한다.
      2. globalfalse이면,
        1. donetrue로 설정한다.
      3. 그렇지 않으면,
        1. matchStr을 ? ToString(? Get(result, "0"))라고 하자.
        2. matchStr이 빈 String이면,
          1. thisIndex(? ToLength(? Get(regexp, "lastIndex")))라고 하자.
          2. flags"u"를 포함하거나 flags"v"를 포함하면 fullUnicodetrue라고 하자; 그렇지 않으면 fullUnicodefalse라고 하자.
          3. nextIndexAdvanceStringIndex(str, thisIndex, fullUnicode)라고 하자.
          4. Set(regexp, "lastIndex", 𝔽(nextIndex), true)를 수행한다.
  13. accumulatedResult를 빈 String이라고 하자.
  14. nextSourcePosition을 0이라고 하자.
  15. results의 각 요소 result에 대해, 다음을 수행한다.
    1. resultLength를 ? LengthOfArrayLike(result)라고 하자.
    2. nCapturesmax(resultLength - 1, 0)이라고 하자.
    3. matched를 ? ToString(? Get(result, "0"))라고 하자.
    4. matchLengthmatched의 길이라고 하자.
    5. position을 ? ToIntegerOrInfinity(? Get(result, "index"))라고 하자.
    6. position을 0과 lengthS 사이로 클램프한 결과로 설정한다.
    7. captures를 새로운 빈 List라고 하자.
    8. captureNumber를 1이라고 하자.
    9. captureNumbernCaptures인 동안 반복한다,
      1. capN을 ? Get(result, ! ToString(𝔽(captureNumber)))라고 하자.
      2. capNundefined가 아니면,
        1. capN을 ? ToString(capN)으로 설정한다.
      3. capNcaptures에 추가한다.
      4. NOTE: captureNumber = 1이면, 앞 단계는 첫 번째 요소를 captures 안에 넣는다(인덱스 0). 더 일반적으로, captureNumberth 캡처(captureNumberth 캡처 괄호 집합이 캡처한 문자들)는 captures[captureNumber - 1]에 있다.
      5. captureNumbercaptureNumber + 1로 설정한다.
    10. namedCaptures를 ? Get(result, "groups")라고 하자.
    11. functionalReplacetrue이면,
      1. replacerArgs를 « matched », captures, 및 « 𝔽(position), str »의 리스트 연결이라고 하자.
      2. namedCapturesundefined가 아니면,
        1. namedCapturesreplacerArgs에 추가한다.
      3. replacementValue를 ? Call(replaceValue, undefined, replacerArgs)라고 하자.
      4. replacementString을 ? ToString(replacementValue)라고 하자.
    12. 그렇지 않으면,
      1. namedCapturesundefined가 아니면,
        1. namedCaptures를 ? ToObject(namedCaptures)로 설정한다.
      2. replacementString을 ? GetSubstitution(matched, str, position, captures, namedCaptures, replaceValue)라고 하자.
    13. positionnextSourcePosition이면,
      1. NOTE: position은 보통 뒤로 이동해서는 안 된다. 만약 이동한다면, 이는 제대로 동작하지 않는 RegExp 서브클래스이거나 접근으로 촉발된 부수 효과를 사용해 regexp의 global 플래그 또는 다른 특성을 변경했음을 나타낸다. 이러한 경우, 대응하는 치환은 무시된다.
      2. accumulatedResultaccumulatedResult, strnextSourcePosition부터 position까지의 부분 문자열, 및 replacementString의 문자열 연결로 설정한다.
      3. nextSourcePositionposition + matchLength로 설정한다.
  16. nextSourcePositionlengthS이면, accumulatedResult를 반환한다.
  17. accumulatedResultstrnextSourcePosition부터의 부분 문자열의 문자열 연결을 반환한다.

이 메서드의 "name" 속성의 값은 "[Symbol.replace]"이다.

22.2.6.12 RegExp.prototype [ %Symbol.search% ] ( string )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. regexpthis 값이라고 하자.
  2. regexp가 Object가 아니면, TypeError 예외를 던진다.
  3. str을 ? ToString(string)이라고 하자.
  4. previousLastIndex를 ? Get(regexp, "lastIndex")라고 하자.
  5. previousLastIndex+0𝔽가 아니면,
    1. Set(regexp, "lastIndex", +0𝔽, true)를 수행한다.
  6. result를 ? RegExpExec(regexp, str)라고 하자.
  7. currentLastIndex를 ? Get(regexp, "lastIndex")라고 하자.
  8. SameValue(currentLastIndex, previousLastIndex)가 false이면,
    1. Set(regexp, "lastIndex", previousLastIndex, true)를 수행한다.
  9. resultnull이면, -1𝔽을 반환한다.
  10. Get(result, "index")를 반환한다.

이 메서드의 "name" 속성의 값은 "[Symbol.search]"이다.

Note

검색을 수행할 때 이 RegExp 객체의 "lastIndex""global" 속성 값은 무시된다. "lastIndex" 속성은 변경되지 않은 채 남는다.

22.2.6.13 get RegExp.prototype.source

RegExp.prototype.source는 set 접근자 함수가 undefined인 접근자 속성이다. 그 get 접근자 함수는 호출될 때 다음 단계를 수행한다:

  1. regexpthis 값이라고 하자.
  2. regexp가 Object가 아니면, TypeError 예외를 던진다.
  3. regexp[[OriginalSource]] 내부 슬롯을 가지지 않으면,
    1. SameValue(regexp, %RegExp.prototype%)가 true이면, "(?:)"를 반환한다.
    2. TypeError 예외를 던진다.
  4. Assert: regexp[[OriginalFlags]] 내부 슬롯을 가진다.
  5. srcregexp.[[OriginalSource]]라고 하자.
  6. flagsregexp.[[OriginalFlags]]라고 하자.
  7. EscapeRegExpPattern(src, flags)를 반환한다.

22.2.6.13.1 EscapeRegExpPattern ( pattern, flags )

The abstract operation EscapeRegExpPattern takes arguments pattern (a String) and flags (a String) and returns a String. It performs the following steps when called:

  1. flags"v"를 포함하면,
    1. patternSymbolPattern[+UnicodeMode, +UnicodeSetsMode]라고 하자.
  2. 그렇지 않고 flags"u"를 포함하면,
    1. patternSymbolPattern[+UnicodeMode, ~UnicodeSetsMode]라고 하자.
  3. 그렇지 않으면,
    1. patternSymbolPattern[~UnicodeMode, ~UnicodeSetsMode]라고 하자.
  4. escapedPattern을 UTF-16으로 인코딩된 Unicode 코드 포인트(6.1.4)로 해석된 pattern과 동등한 patternSymbol의 형식을 가지며, 특정 코드 포인트가 아래 설명된 대로 escape된 String이라고 하자. escapedPatternpattern과 다를 수도 있고 다르지 않을 수도 있다; 그러나 escapedPatternpatternSymbol로 평가하여 생기는 Abstract Closure는 생성된 객체의 [[RegExpMatcher]] 내부 슬롯이 제공하는 Abstract Closure와 동일하게 동작해야 한다. 같은 patternflags 값으로 이 추상 연산을 여러 번 호출하면 동일한 결과를 생성해야 한다.
  5. 패턴 안에 나타나는 코드 포인트 / 또는 임의의 LineTerminator는, "/", escapedPattern, "/", 및 flags의 문자열 연결이 (적절한 어휘 문맥에서) 생성된 정규 표현식과 동일하게 동작하는 RegularExpressionLiteral로 파싱될 수 있도록 필요에 따라 escapedPattern에서 escape되어야 한다. 예를 들어, pattern"/"이면, escapedPattern은 그 밖의 가능성 중 "\/" 또는 "\u002F"일 수 있지만 "/"일 수는 없다. 왜냐하면 flags가 뒤따르는 ///RegularExpressionLiteral이 아니라 SingleLineComment로 파싱되기 때문이다. pattern이 빈 String이면, escapedPattern"(?:)"로 두어 이 명세를 만족할 수 있다.
  6. escapedPattern을 반환한다.
Note

이름이 비슷하지만, RegExp.escape와 EscapeRegExpPattern은 비슷한 동작을 수행하지 않는다. 전자는 패턴 안에서 표현하기 위해 문자열을 escape하는 반면, 이 함수는 문자열로 표현하기 위해 패턴을 escape한다.

22.2.6.14 RegExp.prototype [ %Symbol.split% ] ( string, limit )

Note 1

이 메서드는 string을 String으로 변환한 결과의 부분 문자열들이 저장된 Array를 반환한다. 부분 문자열들은 this 값 정규 표현식의 매치를 왼쪽에서 오른쪽으로 검색하여 결정된다; 이러한 출현들은 반환된 배열 안의 어떤 String의 일부도 아니지만, String 값을 나누는 역할을 한다.

this 값은 빈 정규 표현식이거나 빈 String과 매치할 수 있는 정규 표현식일 수 있다. 이 경우, 정규 표현식은 입력 String의 시작이나 끝에 있는 빈 부분 문자열과 매치하지 않으며, 이전 구분자 매치의 끝에 있는 빈 부분 문자열과도 매치하지 않는다. (예를 들어, 정규 표현식이 빈 String과 매치하면, String은 개별 코드 단위 요소들로 나뉜다; 결과 배열의 길이는 String의 길이와 같고, 각 부분 문자열은 하나의 코드 단위를 포함한다.) 백트래킹이 그 인덱스에서 비어 있지 않은 부분 문자열 매치를 산출할 수 있더라도, String의 주어진 인덱스에서 첫 번째 매치만 고려된다. (예를 들어, /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. regexpthis 값이라고 하자.
  2. regexp가 Object가 아니면, TypeError 예외를 던진다.
  3. str을 ? ToString(string)이라고 하자.
  4. speciesConstructor를 ? SpeciesConstructor(regexp, %RegExp%)라고 하자.
  5. flags를 ? ToString(? Get(regexp, "flags"))라고 하자.
  6. flags"u"를 포함하거나 flags"v"를 포함하면, unicodeMatchingtrue라고 하자.
  7. 그렇지 않으면, unicodeMatchingfalse라고 하자.
  8. flags"y"를 포함하면, newFlagsflags라고 하자.
  9. 그렇지 않으면, newFlagsflags"y"의 문자열 연결이라고 하자.
  10. splitter를 ? Construct(speciesConstructor, « regexp, newFlags »)라고 하자.
  11. array를 ! ArrayCreate(0)이라고 하자.
  12. lengthA를 0이라고 하자.
  13. limitundefined이면 lim을 232 - 1이라고 하자; 그렇지 않으면 lim(? ToUint32(limit))라고 하자.
  14. lim = 0이면, array를 반환한다.
  15. str이 빈 String이면,
    1. matchResult를 ? RegExpExec(splitter, str)라고 하자.
    2. matchResultnull이 아니면, array를 반환한다.
    3. CreateDataPropertyOrThrow(array, "0", str)를 수행한다.
    4. array를 반환한다.
  16. sizestr의 길이라고 하자.
  17. lastMatchEnd를 0이라고 하자.
  18. searchIndexlastMatchEnd라고 하자.
  19. searchIndex < size인 동안 반복한다,
    1. Set(splitter, "lastIndex", 𝔽(searchIndex), true)를 수행한다.
    2. matchResult를 ? RegExpExec(splitter, str)라고 하자.
    3. matchResultnull이면,
      1. searchIndexAdvanceStringIndex(str, searchIndex, unicodeMatching)로 설정한다.
    4. 그렇지 않으면,
      1. matchEnd(? ToLength(? Get(splitter, "lastIndex")))라고 하자.
      2. matchEndmin(matchEnd, size)로 설정한다.
      3. matchEnd = lastMatchEnd이면,
        1. searchIndexAdvanceStringIndex(str, searchIndex, unicodeMatching)로 설정한다.
      4. 그렇지 않으면,
        1. substringstrlastMatchEnd부터 searchIndex까지의 부분 문자열이라고 하자.
        2. CreateDataPropertyOrThrow(array, ! ToString(𝔽(lengthA)), substring)를 수행한다.
        3. lengthAlengthA + 1로 설정한다.
        4. lengthA = lim이면, array를 반환한다.
        5. lastMatchEndmatchEnd로 설정한다.
        6. numberOfCaptures를 ? LengthOfArrayLike(matchResult)라고 하자.
        7. numberOfCapturesmax(numberOfCaptures - 1, 0)으로 설정한다.
        8. captureIndex를 1이라고 하자.
        9. captureIndexnumberOfCaptures인 동안 반복한다,
          1. nextCapture를 ? Get(matchResult, ! ToString(𝔽(captureIndex)))라고 하자.
          2. CreateDataPropertyOrThrow(array, ! ToString(𝔽(lengthA)), nextCapture)를 수행한다.
          3. captureIndexcaptureIndex + 1로 설정한다.
          4. lengthAlengthA + 1로 설정한다.
          5. lengthA = lim이면, array를 반환한다.
        10. searchIndexlastMatchEnd로 설정한다.
  20. substringstrlastMatchEnd부터 size까지의 부분 문자열이라고 하자.
  21. CreateDataPropertyOrThrow(array, ! ToString(𝔽(lengthA)), substring)를 수행한다.
  22. array를 반환한다.

이 메서드의 "name" 속성의 값은 "[Symbol.split]"이다.

Note 2

이 메서드는 이 RegExp 객체의 "global""sticky" 속성 값을 무시한다.

22.2.6.15 get RegExp.prototype.sticky

RegExp.prototype.sticky는 set 접근자 함수가 undefined인 접근자 속성이다. 그 get 접근자 함수는 호출될 때 다음 단계를 수행한다:

  1. regexpthis 값이라고 하자.
  2. cu를 코드 단위 0x0079 (LATIN SMALL LETTER Y)라고 하자.
  3. RegExpHasFlag(regexp, cu)를 반환한다.

22.2.6.16 RegExp.prototype.test ( str )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. regexpthis 값이라고 하자.
  2. regexp가 Object가 아니면, TypeError 예외를 던진다.
  3. string을 ? ToString(str)이라고 하자.
  4. match를 ? RegExpExec(regexp, string)이라고 하자.
  5. matchnull이면, false를 반환한다.
  6. true를 반환한다.

22.2.6.17 RegExp.prototype.toString ( )

  1. regexpthis 값이라고 하자.
  2. regexp가 Object가 아니면, TypeError 예외를 던진다.
  3. pattern을 ? ToString(? Get(regexp, "source"))라고 하자.
  4. flags를 ? ToString(? Get(regexp, "flags"))라고 하자.
  5. result"/", pattern, "/", 및 flags의 문자열 연결이라고 하자.
  6. result를 반환한다.
Note

반환된 String은 이 객체와 같은 동작을 가진 또 다른 RegExp 객체로 평가되는 RegularExpressionLiteral의 형식을 가진다.

22.2.6.18 get RegExp.prototype.unicode

RegExp.prototype.unicode는 set 접근자 함수가 undefined인 접근자 속성이다. 그 get 접근자 함수는 호출될 때 다음 단계를 수행한다:

  1. regexpthis 값이라고 하자.
  2. cu를 코드 단위 0x0075 (LATIN SMALL LETTER U)라고 하자.
  3. RegExpHasFlag(regexp, cu)를 반환한다.

22.2.6.19 get RegExp.prototype.unicodeSets

RegExp.prototype.unicodeSets는 set 접근자 함수가 undefined인 접근자 속성이다. 그 get 접근자 함수는 호출될 때 다음 단계를 수행한다:

  1. regexpthis 값이라고 하자.
  2. cu를 코드 단위 0x0076 (LATIN SMALL LETTER V)라고 하자.
  3. RegExpHasFlag(regexp, cu)를 반환한다.

22.2.7 RegExp 매칭을 위한 추상 연산

22.2.7.1 RegExpExec ( regexp, str )

The abstract operation RegExpExec takes arguments regexp (an Object) and str (a String) and returns either a normal completion containing either an Object or null, or a throw completion. It performs the following steps when called:

  1. exec를 ? Get(regexp, "exec")라고 하자.
  2. IsCallable(exec)가 true이면,
    1. result를 ? Call(exec, regexp, « str »)라고 하자.
    2. result가 Object가 아니고 resultnull도 아니면, TypeError 예외를 던진다.
    3. result를 반환한다.
  3. RequireInternalSlot(regexp, [[RegExpMatcher]])를 수행한다.
  4. RegExpBuiltinExec(regexp, str)를 반환한다.
Note

호출 가능한 "exec" 속성을 찾지 못하면 이 알고리즘은 내장 RegExp 매칭 알고리즘 사용을 시도하는 것으로 대체된다. 이는 정규 표현식을 사용하는 대부분의 내장 알고리즘이 "exec"의 동적 속성 조회를 수행하지 않았던 이전 판을 위해 작성된 코드와 호환되는 동작을 제공한다.

22.2.7.2 RegExpBuiltinExec ( regexp, str )

The abstract operation RegExpBuiltinExec takes arguments regexp (an initialized RegExp instance) and str (a String) and returns either a normal completion containing either an Array exotic object or null, or a throw completion. It performs the following steps when called:

  1. lengthstr의 길이라고 하자.
  2. lastIndex(? ToLength(! Get(regexp, "lastIndex")))라고 하자.
  3. flagsregexp.[[OriginalFlags]]라고 하자.
  4. flags"g"를 포함하면 globaltrue라고 하자; 그렇지 않으면 globalfalse라고 하자.
  5. flags"y"를 포함하면 stickytrue라고 하자; 그렇지 않으면 stickyfalse라고 하자.
  6. flags"d"를 포함하면 hasIndicestrue라고 하자; 그렇지 않으면 hasIndicesfalse라고 하자.
  7. globalfalse이고 stickyfalse이면, lastIndex를 0으로 설정한다.
  8. matcherregexp.[[RegExpMatcher]]라고 하자.
  9. flags"u"를 포함하거나 flags"v"를 포함하면 fullUnicodetrue라고 하자; 그렇지 않으면 fullUnicodefalse라고 하자.
  10. matchSucceededfalse라고 하자.
  11. fullUnicodetrue이면 inputStringToCodePoints(str)라고 하자; 그렇지 않으면 inputstr의 요소인 코드 단위들을 요소로 가지는 List라고 하자.
  12. NOTE: input의 각 요소는 character로 간주된다.
  13. matchSucceededfalse인 동안 반복한다,
    1. lastIndex > length이면,
      1. globaltrue이거나 stickytrue이면,
        1. Set(regexp, "lastIndex", +0𝔽, true)를 수행한다.
      2. null을 반환한다.
    2. inputIndexstr의 요소 lastIndex에서 얻은 character의 input 안의 인덱스라고 하자.
    3. rmatcher(input, inputIndex)라고 하자.
    4. rfailure이면,
      1. stickytrue이면,
        1. Set(regexp, "lastIndex", +0𝔽, true)를 수행한다.
        2. null을 반환한다.
      2. lastIndexAdvanceStringIndex(str, lastIndex, fullUnicode)로 설정한다.
    5. 그렇지 않으면,
      1. Assert: rMatchState이다.
      2. matchSucceededtrue로 설정한다.
  14. endIndexr.[[EndIndex]]라고 하자.
  15. fullUnicodetrue이면, endIndexGetStringIndex(str, endIndex)로 설정한다.
  16. globaltrue이거나 stickytrue이면,
    1. Set(regexp, "lastIndex", 𝔽(endIndex), true)를 수행한다.
  17. nr.[[Captures]] 안의 요소 개수라고 하자.
  18. Assert: n = regexp.[[RegExpRecord]].[[CapturingGroupsCount]].
  19. Assert: n < 232 - 1.
  20. array를 ! ArrayCreate(n + 1)이라고 하자.
  21. Assert: array"length" 속성의 수학적 값n + 1이다.
  22. CreateDataPropertyOrThrow(array, "index", 𝔽(lastIndex))를 수행한다.
  23. CreateDataPropertyOrThrow(array, "input", str)를 수행한다.
  24. matchMatch Record { [[StartIndex]]: lastIndex, [[EndIndex]]: endIndex }라고 하자.
  25. indices를 새로운 빈 List라고 하자.
  26. groupNames를 새로운 빈 List라고 하자.
  27. matchindices에 추가한다.
  28. matchedSubstrGetMatchString(str, match)라고 하자.
  29. CreateDataPropertyOrThrow(array, "0", matchedSubstr)를 수행한다.
  30. regexp가 어떤 GroupName이든 포함하면,
    1. groupsOrdinaryObjectCreate(null)라고 하자.
    2. hasGroupstrue라고 하자.
  31. 그렇지 않으면,
    1. groupsundefined라고 하자.
    2. hasGroupsfalse라고 하자.
  32. CreateDataPropertyOrThrow(array, "groups", groups)를 수행한다.
  33. matchedGroupNames를 새로운 빈 List라고 하자.
  34. 1 ≤ in을 만족하는 각 정수 i에 대해, 오름차순으로, 다음을 수행한다.
    1. captureIr.[[Captures]]ith 요소라고 하자.
    2. captureIundefined이면,
      1. capturedValueundefined라고 하자.
      2. undefinedindices에 추가한다.
    3. 그렇지 않으면,
      1. captureStartcaptureI.[[StartIndex]]라고 하자.
      2. captureEndcaptureI.[[EndIndex]]라고 하자.
      3. fullUnicodetrue이면,
        1. captureStartGetStringIndex(str, captureStart)로 설정한다.
        2. captureEndGetStringIndex(str, captureEnd)로 설정한다.
      4. captureMatch Record { [[StartIndex]]: captureStart, [[EndIndex]]: captureEnd }라고 하자.
      5. capturedValueGetMatchString(str, capture)라고 하자.
      6. captureindices에 추가한다.
    4. CreateDataPropertyOrThrow(array, ! ToString(𝔽(i)), capturedValue)를 수행한다.
    5. regexpith capture가 GroupName으로 정의되었으면,
      1. s를 그 GroupNameCapturingGroupName이라고 하자.
      2. matchedGroupNamess를 포함하면,
        1. Assert: capturedValueundefined이다.
        2. undefinedgroupNames에 추가한다.
      3. 그렇지 않으면,
        1. capturedValueundefined가 아니면 smatchedGroupNames에 추가한다.
        2. NOTE: s라는 이름의 그룹이 여러 개 있으면, 이 시점에서 groups는 이미 s 속성을 가질 수 있다. 그러나 groups는 모든 속성이 쓰기 가능한 데이터 속성인 보통 객체이므로, CreateDataPropertyOrThrow 호출은 그럼에도 성공하는 것이 보장된다.
        3. CreateDataPropertyOrThrow(groups, s, capturedValue)를 수행한다.
        4. sgroupNames에 추가한다.
    6. 그렇지 않으면,
      1. undefinedgroupNames에 추가한다.
  35. hasIndicestrue이면,
    1. indicesArrayMakeMatchIndicesIndexPairArray(str, indices, groupNames, hasGroups)라고 하자.
    2. CreateDataPropertyOrThrow(array, "indices", indicesArray)를 수행한다.
  36. array를 반환한다.

22.2.7.3 AdvanceStringIndex ( str, index, unicode )

The abstract operation AdvanceStringIndex takes arguments str (a String), index (a non-negative integer), and unicode (a Boolean) and returns a non-negative integer. It performs the following steps when called:

  1. Assert: index ≤ 253 - 1.
  2. unicodefalse이면, index + 1을 반환한다.
  3. lengthstr의 길이라고 하자.
  4. index + 1 ≥ length이면, index + 1을 반환한다.
  5. cpCodePointAt(str, index)라고 하자.
  6. index + cp.[[CodeUnitCount]]를 반환한다.

22.2.7.4 GetStringIndex ( str, codePointIndex )

The abstract operation GetStringIndex takes arguments str (a String) and codePointIndex (a non-negative integer) and returns a non-negative integer. 이 연산은 6.1.4에 설명된 대로 str을 UTF-16으로 인코딩된 코드 포인트들의 시퀀스로 해석하고, 그러한 인덱스가 존재할 때 코드 포인트 인덱스 codePointIndex에 대응하는 코드 단위 인덱스를 반환한다. 그렇지 않으면 str의 길이를 반환한다. It performs the following steps when called:

  1. str이 빈 String이면 0을 반환한다.
  2. lenstr의 길이라고 하자.
  3. codeUnitCount를 0이라고 하자.
  4. codePointCount를 0이라고 하자.
  5. codeUnitCount < len인 동안 반복한다,
    1. codePointCount = codePointIndex이면 codeUnitCount를 반환한다.
    2. cpCodePointAt(str, codeUnitCount)라고 하자.
    3. codeUnitCountcodeUnitCount + cp.[[CodeUnitCount]]로 설정한다.
    4. codePointCountcodePointCount + 1로 설정한다.
  6. len을 반환한다.

22.2.7.5 Match Records

Match Record는 정규 표현식 매치 또는 캡처의 시작 및 끝 인덱스를 캡슐화하는 데 사용되는 Record 값이다.

Match Record는 Table 67에 나열된 필드를 가진다.

Table 67: Match Record 필드
필드 이름 의미
[[StartIndex]] 음이 아닌 정수 매치가 시작되는(포함) 지점까지 문자열의 시작부터 센 코드 단위의 수.
[[EndIndex]] 정수[[StartIndex]] 매치가 끝나는(제외) 지점까지 문자열의 시작부터 센 코드 단위의 수.

22.2.7.6 GetMatchString ( str, match )

The abstract operation GetMatchString takes arguments str (a String) and match (a Match Record) and returns a String. It performs the following steps when called:

  1. Assert: match.[[StartIndex]]match.[[EndIndex]]str의 길이.
  2. strmatch.[[StartIndex]]부터 match.[[EndIndex]]까지의 부분 문자열을 반환한다.

22.2.7.7 GetMatchIndexPair ( str, match )

The abstract operation GetMatchIndexPair takes arguments str (a String) and match (a Match Record) and returns an Array. It performs the following steps when called:

  1. Assert: match.[[StartIndex]]match.[[EndIndex]]str의 길이.
  2. CreateArrayFromList𝔽(match.[[StartIndex]]), 𝔽(match.[[EndIndex]]) »)를 반환한다.

22.2.7.8 MakeMatchIndicesIndexPairArray ( str, indices, groupNames, hasGroups )

The abstract operation MakeMatchIndicesIndexPairArray takes arguments str (a String), indices (a List of either Match Records or undefined), groupNames (a List of either Strings or undefined), and hasGroups (a Boolean) and returns an Array. It performs the following steps when called:

  1. nindices 안의 요소 개수라고 하자.
  2. Assert: n < 232 - 1.
  3. Assert: groupNamesn - 1개의 요소를 가진다.
  4. NOTE: groupNames Listindices[1]부터 시작하여 indices List와 정렬된 요소들을 포함한다.
  5. array를 ! ArrayCreate(n)이라고 하자.
  6. hasGroupstrue이면,
    1. groupsOrdinaryObjectCreate(null)라고 하자.
  7. 그렇지 않으면,
    1. groupsundefined라고 하자.
  8. CreateDataPropertyOrThrow(array, "groups", groups)를 수행한다.
  9. 0 ≤ i < n을 만족하는 각 정수 i에 대해, 오름차순으로, 다음을 수행한다.
    1. matchIndicesindices[i]라고 하자.
    2. matchIndicesundefined가 아니면,
      1. matchIndexPairGetMatchIndexPair(str, matchIndices)라고 하자.
    3. 그렇지 않으면,
      1. matchIndexPairundefined라고 하자.
    4. CreateDataPropertyOrThrow(array, ! ToString(𝔽(i)), matchIndexPair)를 수행한다.
    5. i > 0이면,
      1. namegroupNames[i - 1]이라고 하자.
      2. nameundefined가 아니면,
        1. Assert: groupsundefined가 아니다.
        2. NOTE: name이라는 이름의 그룹이 여러 개 있으면, 이 시점에서 groups는 이미 name 속성을 가질 수 있다. 그러나 groups는 모든 속성이 쓰기 가능한 데이터 속성인 보통 객체이므로, CreateDataPropertyOrThrow 호출은 그럼에도 성공하는 것이 보장된다.
        3. CreateDataPropertyOrThrow(groups, name, matchIndexPair)를 수행한다.
  10. array를 반환한다.

22.2.8 RegExp 인스턴스의 속성

RegExp 인스턴스는 RegExp 프로토타입 객체로부터 속성을 상속하는 보통 객체이다. RegExp 인스턴스는 [[OriginalSource]], [[OriginalFlags]], [[RegExpRecord]], 및 [[RegExpMatcher]] 내부 슬롯을 가진다. [[RegExpMatcher]] 내부 슬롯의 값은 RegExp 객체의 Pattern에 대한 Abstract Closure 표현이다.

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 String Iterator 객체

RegExp String Iterator는 어떤 특정 String 인스턴스 객체에 대한 특정 반복을, 어떤 특정 RegExp 인스턴스 객체에 대해 매치하면서 나타내는 객체이다. RegExp String Iterator 객체에는 이름 있는 생성자가 없다. 대신, RegExp String Iterator 객체는 RegExp 인스턴스 객체의 특정 메서드를 호출하여 생성된다.

22.2.9.1 CreateRegExpStringIterator ( regexp, str, global, fullUnicode )

The abstract operation CreateRegExpStringIterator takes arguments regexp (an Object), str (a String), global (a Boolean), and fullUnicode (a Boolean) and returns an Object. It performs the following steps when called:

  1. iteratorOrdinaryObjectCreate(%RegExpStringIteratorPrototype%, « [[IteratingRegExp]], [[IteratedString]], [[Global]], [[Unicode]], [[Done]] »)라고 하자.
  2. iterator.[[IteratingRegExp]]regexp로 설정한다.
  3. iterator.[[IteratedString]]str로 설정한다.
  4. iterator.[[Global]]global로 설정한다.
  5. iterator.[[Unicode]]fullUnicode로 설정한다.
  6. iterator.[[Done]]false로 설정한다.
  7. iterator를 반환한다.

22.2.9.2 %RegExpStringIteratorPrototype% 객체

%RegExpStringIteratorPrototype% 객체는:

22.2.9.2.1 %RegExpStringIteratorPrototype%.next ( )

  1. iteratorObjthis 값이라고 하자.
  2. iteratorObj가 Object가 아니면, TypeError 예외를 던진다.
  3. iteratorObjRegExp String Iterator Object Instance의 모든 내부 슬롯(22.2.9.3를 보라)을 가지지 않으면, TypeError 예외를 던진다.
  4. iteratorObj.[[Done]]true이면,
    1. CreateIteratorResultObject(undefined, true)를 반환한다.
  5. regexpiteratorObj.[[IteratingRegExp]]라고 하자.
  6. striteratorObj.[[IteratedString]]이라고 하자.
  7. globaliteratorObj.[[Global]]이라고 하자.
  8. fullUnicodeiteratorObj.[[Unicode]]라고 하자.
  9. match를 ? RegExpExec(regexp, str)라고 하자.
  10. matchnull이면,
    1. iteratorObj.[[Done]]true로 설정한다.
    2. CreateIteratorResultObject(undefined, true)를 반환한다.
  11. globalfalse이면,
    1. iteratorObj.[[Done]]true로 설정한다.
    2. CreateIteratorResultObject(match, false)를 반환한다.
  12. matchStr을 ? ToString(? Get(match, "0"))라고 하자.
  13. matchStr이 빈 String이면,
    1. thisIndex(? ToLength(? Get(regexp, "lastIndex")))라고 하자.
    2. nextIndexAdvanceStringIndex(str, thisIndex, fullUnicode)라고 하자.
    3. Set(regexp, "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 String Iterator 인스턴스의 속성

RegExp String Iterator 인스턴스는 %RegExpStringIteratorPrototype% 내재 객체로부터 속성을 상속하는 보통 객체이다. RegExp String Iterator 인스턴스는 처음에 Table 68에 나열된 내부 슬롯을 가지고 생성된다.

Table 68: RegExp String Iterator 인스턴스의 내부 슬롯
내부 슬롯 타입 설명
[[IteratingRegExp]] Object 반복에 사용되는 정규 표현식. IsRegExp([[IteratingRegExp]])는 처음에 true이다.
[[IteratedString]] String 반복 대상인 String 값.
[[Global]] Boolean [[IteratingRegExp]]가 전역인지 아닌지를 나타낸다.
[[Unicode]] Boolean [[IteratingRegExp]]가 Unicode 모드인지 아닌지를 나타낸다.
[[Done]] Boolean 반복이 완료되었는지 아닌지를 나타낸다.

23 인덱스 컬렉션

23.1 Array 객체

Array는 특정 종류의 속성 이름에 특별한 처리를 부여하는 특수 객체이다. 이 특별한 처리의 정의는 10.4.2를 보라.

23.1.1 Array 생성자

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이면, ! ArrayCreate(0, proto)를 반환한다.
  5. numberOfArgs = 1이면,
    1. lenvalues[0]이라고 하자.
    2. array를 ! ArrayCreate(0, proto)라고 하자.
    3. len이 Number가 아니면,
      1. CreateDataPropertyOrThrow(array, "0", len)을 수행한다.
      2. intLen1𝔽이라고 하자.
    4. 그렇지 않으면,
      1. intLen을 ! ToUint32(len)이라고 하자.
      2. SameValueZero(intLen, len)가 false이면, RangeError 예외를 던진다.
    5. Set(array, "length", intLen, true)를 수행한다.
    6. array를 반환한다.
  6. Assert: numberOfArgs ≥ 2.
  7. array를 ? ArrayCreate(numberOfArgs, proto)라고 하자.
  8. k를 0이라고 하자.
  9. k < numberOfArgs인 동안 반복한다,
    1. propertyKey를 ! ToString(𝔽(k))라고 하자.
    2. itemKvalues[k]라고 하자.
    3. CreateDataPropertyOrThrow(array, propertyKey, itemK)를 수행한다.
    4. kk + 1로 설정한다.
  10. Assert: array"length" 속성의 수학적 값numberOfArgs이다.
  11. array를 반환한다.

23.1.2 Array 생성자의 속성

Array 생성자는:

  • 값이 %Function.prototype%[[Prototype]] 내부 슬롯을 가진다.
  • 값이 1𝔽"length" 속성을 가진다.
  • 다음 속성들을 가진다:

23.1.2.1 Array.from ( items [ , mapper [ , thisArg ] ] )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. constructorthis 값이라고 하자.
  2. mapperundefined이면,
    1. mappingfalse라고 하자.
  3. 그렇지 않으면,
    1. IsCallable(mapper)가 false이면, TypeError 예외를 던진다.
    2. mappingtrue라고 하자.
  4. usingIterator를 ? GetMethod(items, %Symbol.iterator%)라고 하자.
  5. usingIteratorundefined가 아니면,
    1. IsConstructor(constructor)가 true이면,
      1. array를 ? Construct(constructor)라고 하자.
    2. 그렇지 않으면,
      1. array를 ! ArrayCreate(0)이라고 하자.
    3. iteratorRecord를 ? GetIteratorFromMethod(items, usingIterator)라고 하자.
    4. k를 0이라고 하자.
    5. 반복한다,
      1. k ≥ 253 - 1이면,
        1. errorThrowCompletion(새로 생성된 TypeError 객체)라고 하자.
        2. IteratorClose(iteratorRecord, error)를 반환한다.
      2. propertyKey를 ! ToString(𝔽(k))라고 하자.
      3. next를 ? IteratorStepValue(iteratorRecord)라고 하자.
      4. nextdone이면,
        1. Set(array, "length", 𝔽(k), true)를 수행한다.
        2. array를 반환한다.
      5. mappingtrue이면,
        1. mappedValueCompletion(Call(mapper, thisArg, « next, 𝔽(k) »))라고 하자.
        2. IfAbruptCloseIterator(mappedValue, iteratorRecord).
      6. 그렇지 않으면,
        1. mappedValuenext라고 하자.
      7. defineStatusCompletion(CreateDataPropertyOrThrow(array, propertyKey, mappedValue))라고 하자.
      8. IfAbruptCloseIterator(defineStatus, iteratorRecord).
      9. kk + 1로 설정한다.
  6. NOTE: items는 반복 가능하지 않으므로 배열 유사 객체라고 가정한다.
  7. arrayLike를 ! ToObject(items)라고 하자.
  8. len을 ? LengthOfArrayLike(arrayLike)라고 하자.
  9. IsConstructor(constructor)가 true이면,
    1. array를 ? Construct(constructor, « 𝔽(len) »)라고 하자.
  10. 그렇지 않으면,
    1. array를 ? ArrayCreate(len)라고 하자.
  11. k를 0이라고 하자.
  12. k < len인 동안 반복한다,
    1. propertyKey를 ! ToString(𝔽(k))라고 하자.
    2. kValue를 ? Get(arrayLike, propertyKey)라고 하자.
    3. mappingtrue이면,
      1. mappedValue를 ? Call(mapper, thisArg, « kValue, 𝔽(k) »)라고 하자.
    4. 그렇지 않으면,
      1. mappedValuekValue라고 하자.
    5. CreateDataPropertyOrThrow(array, propertyKey, mappedValue)를 수행한다.
    6. kk + 1로 설정한다.
  13. Set(array, "length", 𝔽(len), true)를 수행한다.
  14. array를 반환한다.
Note

이 메서드는 의도적으로 제네릭인 팩터리 메서드이다; 이 메서드는 자신의 this 값이 Array 생성자일 것을 요구하지 않는다. 따라서 단일 수치 인자와 함께 호출될 수 있는 다른 생성자로 이전되거나 상속될 수 있다.

23.1.2.2 Array.fromAsync ( items [ , mapper [ , thisArg ] ] )

이 비동기 함수는 호출될 때 다음 단계를 수행한다:

  1. constructorthis 값이라고 하자.
  2. mappingfalse라고 하자.
  3. mapperundefined가 아니면,
    1. IsCallable(mapper)가 false이면, TypeError 예외를 던진다.
    2. mappingtrue로 설정한다.
  4. iteratorRecordundefined라고 하자.
  5. usingAsyncIterator를 ? GetMethod(items, %Symbol.asyncIterator%)라고 하자.
  6. usingAsyncIteratorundefined이면,
    1. usingSyncIterator를 ? GetMethod(items, %Symbol.iterator%)라고 하자.
    2. usingSyncIteratorundefined가 아니면,
      1. iteratorRecordCreateAsyncFromSyncIterator(? GetIteratorFromMethod(items, usingSyncIterator))로 설정한다.
  7. 그렇지 않으면,
    1. iteratorRecord를 ? GetIteratorFromMethod(items, usingAsyncIterator)로 설정한다.
  8. iteratorRecordundefined가 아니면,
    1. IsConstructor(constructor)가 true이면,
      1. array를 ? Construct(constructor)라고 하자.
    2. 그렇지 않으면,
      1. array를 ! ArrayCreate(0)이라고 하자.
    3. k를 0이라고 하자.
    4. 반복한다,
      1. k ≥ 253 - 1이면,
        1. errorThrowCompletion(새로 생성된 TypeError 객체)라고 하자.
        2. AsyncIteratorClose(iteratorRecord, error)를 반환한다.
      2. propertyKey를 ! ToString(𝔽(k))라고 하자.
      3. nextResult를 ? Call(iteratorRecord.[[NextMethod]], iteratorRecord.[[Iterator]])라고 하자.
      4. nextResult를 ? Await(nextResult)로 설정한다.
      5. nextResult가 Object가 아니면, TypeError 예외를 던진다.
      6. done을 ? IteratorComplete(nextResult)라고 하자.
      7. donetrue이면,
        1. Set(array, "length", 𝔽(k), true)를 수행한다.
        2. array를 반환한다.
      8. nextValue를 ? IteratorValue(nextResult)라고 하자.
      9. mappingtrue이면,
        1. mappedValueCompletion(Call(mapper, thisArg, « nextValue, 𝔽(k) »))라고 하자.
        2. IfAbruptCloseAsyncIterator(mappedValue, iteratorRecord).
        3. mappedValueCompletion(Await(mappedValue))로 설정한다.
        4. IfAbruptCloseAsyncIterator(mappedValue, iteratorRecord).
      10. 그렇지 않으면,
        1. mappedValuenextValue라고 하자.
      11. defineStatusCompletion(CreateDataPropertyOrThrow(array, propertyKey, mappedValue))라고 하자.
      12. IfAbruptCloseAsyncIterator(defineStatus, iteratorRecord).
      13. kk + 1로 설정한다.
  9. 그렇지 않으면,
    1. NOTE: items는 비동기 반복 가능하지도 반복 가능하지도 않으므로 배열 유사 객체라고 가정한다.
    2. arrayLike를 ! ToObject(items)라고 하자.
    3. len을 ? LengthOfArrayLike(arrayLike)라고 하자.
    4. IsConstructor(constructor)가 true이면,
      1. array를 ? Construct(constructor, « 𝔽(len) »)라고 하자.
    5. 그렇지 않으면,
      1. array를 ? ArrayCreate(len)라고 하자.
    6. k를 0이라고 하자.
    7. k < len인 동안 반복한다,
      1. propertyKey를 ! ToString(𝔽(k))라고 하자.
      2. kValue를 ? Get(arrayLike, propertyKey)라고 하자.
      3. kValue를 ? Await(kValue)로 설정한다.
      4. mappingtrue이면,
        1. mappedValue를 ? Call(mapper, thisArg, « kValue, 𝔽(k) »)라고 하자.
        2. mappedValue를 ? Await(mappedValue)로 설정한다.
      5. 그렇지 않으면,
        1. mappedValuekValue라고 하자.
      6. CreateDataPropertyOrThrow(array, propertyKey, mappedValue)를 수행한다.
      7. kk + 1로 설정한다.
    8. Set(array, "length", 𝔽(len), true)를 수행한다.
    9. array를 반환한다.
Note

이 메서드는 의도적으로 제네릭인 팩터리 메서드이다; 이 메서드는 자신의 this 값이 Array 생성자일 것을 요구하지 않는다. 따라서 단일 수치 인자와 함께 호출될 수 있는 다른 생성자로 이전되거나 상속될 수 있다.

23.1.2.3 Array.isArray ( arg )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. IsArray(arg)를 반환한다.

23.1.2.4 Array.of ( ...items )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. lenitems의 요소 개수라고 하자.
  2. lenNumber𝔽(len)이라고 하자.
  3. constructorthis 값이라고 하자.
  4. IsConstructor(constructor)가 true이면,
    1. array를 ? Construct(constructor, « lenNumber »)라고 하자.
  5. 그렇지 않으면,
    1. array를 ? ArrayCreate(len)라고 하자.
  6. k를 0이라고 하자.
  7. k < len인 동안 반복한다,
    1. kValueitems[k]라고 하자.
    2. propertyKey를 ! ToString(𝔽(k))라고 하자.
    3. CreateDataPropertyOrThrow(array, propertyKey, kValue)를 수행한다.
    4. kk + 1로 설정한다.
  8. Set(array, "length", lenNumber, true)를 수행한다.
  9. array를 반환한다.
Note

이 메서드는 의도적으로 제네릭인 팩터리 메서드이다; 이 메서드는 자신의 this 값이 Array 생성자일 것을 요구하지 않는다. 따라서 단일 수치 인자와 함께 호출될 수 있는 다른 생성자로 이전되거나 상속될 수 있다.

23.1.2.5 Array.prototype

Array.prototype의 값은 Array 프로토타입 객체이다.

이 속성은 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false } 속성 특성을 가진다.

23.1.2.6 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 프로토타입 객체의 속성

Array 프로토타입 객체는:

  • %Array.prototype%이다.
  • Array 특수 객체이며 그러한 객체에 대해 지정된 내부 메서드를 가진다.
  • 초기값이 +0𝔽이고 속성 특성이 { [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false }인 "length" 속성을 가진다.
  • 값이 %Object.prototype%[[Prototype]] 내부 슬롯을 가진다.
Note

Array 프로토타입 객체는 ECMAScript 2015 명세 이전에 만들어진 ECMAScript 코드와의 호환성을 보장하기 위해 Array 특수 객체로 지정된다.

23.1.3.1 Array.prototype.at ( index )

  1. obj를 ? ToObject(this value)라고 하자.
  2. len을 ? LengthOfArrayLike(obj)라고 하자.
  3. relativeIndex를 ? ToIntegerOrInfinity(index)라고 하자.
  4. relativeIndex ≥ 0이면,
    1. krelativeIndex라고 하자.
  5. 그렇지 않으면,
    1. klen + relativeIndex라고 하자.
  6. k < 0이거나 klen이면, undefined를 반환한다.
  7. Get(obj, ! ToString(𝔽(k)))를 반환한다.

23.1.3.2 Array.prototype.concat ( ...items )

이 메서드는 객체의 배열 요소 뒤에 각 인자의 배열 요소가 이어진 배열을 반환한다.

호출될 때 다음 단계를 수행한다:

  1. obj를 ? ToObject(this value)라고 하자.
  2. array를 ? ArraySpeciesCreate(obj, 0)이라고 하자.
  3. nextIndex를 0이라고 하자.
  4. objitems 앞에 추가한다.
  5. items의 각 요소 item에 대해, 다음을 수행한다.
    1. spreadable을 ? IsConcatSpreadable(item)이라고 하자.
    2. spreadabletrue이면,
      1. len을 ? LengthOfArrayLike(item)이라고 하자.
      2. nextIndex + len > 253 - 1이면, TypeError 예외를 던진다.
      3. sourceIndex를 0이라고 하자.
      4. sourceIndex < len인 동안 반복한다,
        1. propertyKey를 ! ToString(𝔽(sourceIndex))라고 하자.
        2. exists를 ? HasProperty(item, propertyKey)라고 하자.
        3. existstrue이면,
          1. subElement를 ? Get(item, propertyKey)라고 하자.
          2. CreateDataPropertyOrThrow(array, ! ToString(𝔽(nextIndex)), subElement)를 수행한다.
        4. nextIndexnextIndex + 1로 설정한다.
        5. sourceIndexsourceIndex + 1로 설정한다.
    3. 그렇지 않으면,
      1. NOTE: item은 펼쳐지지 않고 단일 항목으로 추가된다.
      2. nextIndex ≥ 253 - 1이면, TypeError 예외를 던진다.
      3. CreateDataPropertyOrThrow(array, ! ToString(𝔽(nextIndex)), item)를 수행한다.
      4. nextIndexnextIndex + 1로 설정한다.
  6. Set(array, "length", 𝔽(nextIndex), true)를 수행한다.
  7. array를 반환한다.

이 메서드의 "length" 속성은 1𝔽이다.

Note 1

단계 6에서 "length" 속성을 명시적으로 설정하는 것은, items의 마지막 비어 있지 않은 요소에 뒤따르는 빈 슬롯이 있거나 array가 내장 Array가 아닐 때 길이가 올바르도록 보장하기 위한 것이다.

Note 2

이 메서드는 의도적으로 제네릭이다; 이 메서드는 자신의 this 값이 Array일 것을 요구하지 않는다. 따라서 메서드로 사용하기 위해 다른 종류의 객체로 이전될 수 있다.

23.1.3.2.1 IsConcatSpreadable ( obj )

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

  1. obj가 Object가 아니면, false를 반환한다.
  2. spreadable을 ? Get(obj, %Symbol.isConcatSpreadable%)라고 하자.
  3. spreadableundefined가 아니면, ToBoolean(spreadable)를 반환한다.
  4. IsArray(obj)를 반환한다.

23.1.3.3 Array.prototype.constructor

Array.prototype.constructor의 초기값은 %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. obj를 ? ToObject(this value)라고 하자.
  2. len을 ? LengthOfArrayLike(obj)라고 하자.
  3. relativeTarget을 ? ToIntegerOrInfinity(target)이라고 하자.
  4. relativeTarget = -∞이면, to를 0이라고 하자.
  5. 그렇지 않고 relativeTarget < 0이면, tomax(len + relativeTarget, 0)이라고 하자.
  6. 그렇지 않으면, tomin(relativeTarget, len)이라고 하자.
  7. relativeStart를 ? ToIntegerOrInfinity(start)라고 하자.
  8. relativeStart = -∞이면, from을 0이라고 하자.
  9. 그렇지 않고 relativeStart < 0이면, frommax(len + relativeStart, 0)이라고 하자.
  10. 그렇지 않으면, frommin(relativeStart, len)이라고 하자.
  11. endundefined이면 relativeEndlen이라고 하자; 그렇지 않으면 relativeEnd를 ? ToIntegerOrInfinity(end)라고 하자.
  12. relativeEnd = -∞이면, final을 0이라고 하자.
  13. 그렇지 않고 relativeEnd < 0이면, finalmax(len + relativeEnd, 0)이라고 하자.
  14. 그렇지 않으면, finalmin(relativeEnd, len)이라고 하자.
  15. countmin(final - from, len - to)라고 하자.
  16. from < to이고 to < from + count이면,
    1. direction을 -1이라고 하자.
    2. fromfrom + count - 1로 설정한다.
    3. toto + count - 1로 설정한다.
  17. 그렇지 않으면,
    1. direction을 1이라고 하자.
  18. count > 0인 동안 반복한다,
    1. fromKey를 ! ToString(𝔽(from))라고 하자.
    2. toKey를 ! ToString(𝔽(to))라고 하자.
    3. fromPresent를 ? HasProperty(obj, fromKey)라고 하자.
    4. fromPresenttrue이면,
      1. fromValue를 ? Get(obj, fromKey)라고 하자.
      2. Set(obj, toKey, fromValue, true)를 수행한다.
    5. 그렇지 않으면,
      1. Assert: fromPresentfalse이다.
      2. DeletePropertyOrThrow(obj, toKey)를 수행한다.
    6. fromfrom + direction으로 설정한다.
    7. toto + direction으로 설정한다.
    8. countcount - 1로 설정한다.
  19. obj를 반환한다.
Note 3

이 메서드는 의도적으로 제네릭이다; 이 메서드는 자신의 this 값이 Array일 것을 요구하지 않는다. 따라서 메서드로 사용하기 위해 다른 종류의 객체로 이전될 수 있다.

23.1.3.5 Array.prototype.entries ( )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. obj를 ? ToObject(this value)라고 하자.
  2. CreateArrayIterator(obj, key+value)를 반환한다.

23.1.3.6 Array.prototype.every ( callback [ , thisArg ] )

Note 1

callback은 세 개의 인자를 받아 Boolean 값으로 강제 변환될 수 있는 값을 반환하는 함수여야 한다. everycallbackfalse를 반환하는 요소를 찾을 때까지 배열에 존재하는 각 요소에 대해 오름차순으로 한 번씩 callback을 호출한다. 그러한 요소를 찾으면, every는 즉시 false를 반환한다. 그렇지 않으면, everytrue를 반환한다. callback은 실제로 존재하는 배열 요소에 대해서만 호출되며, 배열의 누락된 요소에 대해서는 호출되지 않는다.

thisArg 매개변수가 제공되면, callback의 각 호출에서 this 값으로 사용된다. 제공되지 않으면, 대신 undefined가 사용된다.

callback은 세 개의 인자, 즉 요소의 값, 요소의 인덱스, 그리고 순회 중인 객체와 함께 호출된다.

every는 호출 대상 객체를 직접 변경하지 않지만, callback 호출에 의해 객체가 변경될 수 있다.

every가 처리하는 요소의 범위는 callback의 첫 호출 전에 설정된다. every 호출이 시작된 뒤 배열에 추가되는 요소는 callback이 방문하지 않는다. 배열의 기존 요소가 변경되면, callback에 전달되는 값은 every가 해당 요소를 방문하는 시점의 값이 된다; every 호출이 시작된 뒤 방문되기 전에 삭제되는 요소는 방문되지 않는다. every는 수학의 "for all" 한정자처럼 동작한다. 특히 빈 배열에 대해서는 true를 반환한다.

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. obj를 ? ToObject(this value)라고 하자.
  2. len을 ? LengthOfArrayLike(obj)라고 하자.
  3. IsCallable(callback)가 false이면, TypeError 예외를 던진다.
  4. k를 0이라고 하자.
  5. k < len인 동안 반복한다,
    1. propertyKey를 ! ToString(𝔽(k))라고 하자.
    2. kPresent를 ? HasProperty(obj, propertyKey)라고 하자.
    3. kPresenttrue이면,
      1. kValue를 ? Get(obj, propertyKey)라고 하자.
      2. testResultToBoolean(? Call(callback, thisArg, « kValue, 𝔽(k), obj »))라고 하자.
      3. testResultfalse이면, false를 반환한다.
    4. kk + 1로 설정한다.
  6. true를 반환한다.
Note 2

이 메서드는 의도적으로 제네릭이다; 이 메서드는 자신의 this 값이 Array일 것을 요구하지 않는다. 따라서 메서드로 사용하기 위해 다른 종류의 객체로 이전될 수 있다.

23.1.3.7 Array.prototype.fill ( value [ , start [ , end ] ] )

Note 1

start 인자는 선택적이다. 제공되지 않으면, +0𝔽이 사용된다.

end 인자는 선택적이다. 제공되지 않으면, this 값의 길이가 사용된다.

Note 2

start가 음수이면, 배열의 길이인 length에 대해 length + start로 취급된다. end가 음수이면, length + end로 취급된다.

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. obj를 ? ToObject(this value)라고 하자.
  2. len을 ? LengthOfArrayLike(obj)라고 하자.
  3. relativeStart를 ? ToIntegerOrInfinity(start)라고 하자.
  4. relativeStart = -∞이면, k를 0이라고 하자.
  5. 그렇지 않고 relativeStart < 0이면, kmax(len + relativeStart, 0)이라고 하자.
  6. 그렇지 않으면, kmin(relativeStart, len)이라고 하자.
  7. endundefined이면 relativeEndlen이라고 하자; 그렇지 않으면 relativeEnd를 ? ToIntegerOrInfinity(end)라고 하자.
  8. relativeEnd = -∞이면, final을 0이라고 하자.
  9. 그렇지 않고 relativeEnd < 0이면, finalmax(len + relativeEnd, 0)이라고 하자.
  10. 그렇지 않으면, finalmin(relativeEnd, len)이라고 하자.
  11. k < final인 동안 반복한다,
    1. propertyKey를 ! ToString(𝔽(k))라고 하자.
    2. Set(obj, propertyKey, value, true)를 수행한다.
    3. kk + 1로 설정한다.
  12. obj를 반환한다.
Note 3

이 메서드는 의도적으로 제네릭이다; 이 메서드는 자신의 this 값이 Array일 것을 요구하지 않는다. 따라서 메서드로 사용하기 위해 다른 종류의 객체로 이전될 수 있다.

23.1.3.8 Array.prototype.filter ( callback [ , thisArg ] )

Note 1

callback은 세 개의 인자를 받아 Boolean 값으로 강제 변환될 수 있는 값을 반환하는 함수여야 한다. filter는 배열의 각 요소에 대해 오름차순으로 한 번씩 callback을 호출하고, callbacktrue를 반환하는 모든 값으로 새 배열을 구성한다. callback은 실제로 존재하는 배열 요소에 대해서만 호출되며, 배열의 누락된 요소에 대해서는 호출되지 않는다.

thisArg 매개변수가 제공되면, callback의 각 호출에서 this 값으로 사용된다. 제공되지 않으면, 대신 undefined가 사용된다.

callback은 세 개의 인자, 즉 요소의 값, 요소의 인덱스, 그리고 순회 중인 객체와 함께 호출된다.

filter는 호출 대상 객체를 직접 변경하지 않지만, callback 호출에 의해 객체가 변경될 수 있다.

filter가 처리하는 요소의 범위는 callback의 첫 호출 전에 설정된다. filter 호출이 시작된 뒤 배열에 추가되는 요소는 callback이 방문하지 않는다. 배열의 기존 요소가 변경되면 callback에 전달되는 값은 filter가 해당 요소를 방문하는 시점의 값이 된다; filter 호출이 시작된 뒤 방문되기 전에 삭제되는 요소는 방문되지 않는다.

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. obj를 ? ToObject(this value)라고 하자.
  2. len을 ? LengthOfArrayLike(obj)라고 하자.
  3. IsCallable(callback)가 false이면, TypeError 예외를 던진다.
  4. array를 ? ArraySpeciesCreate(obj, 0)이라고 하자.
  5. k를 0이라고 하자.
  6. to를 0이라고 하자.
  7. k < len인 동안 반복한다,
    1. propertyKey를 ! ToString(𝔽(k))라고 하자.
    2. kPresent를 ? HasProperty(obj, propertyKey)라고 하자.
    3. kPresenttrue이면,
      1. kValue를 ? Get(obj, propertyKey)라고 하자.
      2. selectedToBoolean(? Call(callback, thisArg, « kValue, 𝔽(k), obj »))라고 하자.
      3. selectedtrue이면,
        1. CreateDataPropertyOrThrow(array, ! ToString(𝔽(to)), kValue)를 수행한다.
        2. toto + 1로 설정한다.
    4. kk + 1로 설정한다.
  8. array를 반환한다.
Note 2

이 메서드는 의도적으로 제네릭이다; 이 메서드는 자신의 this 값이 Array일 것을 요구하지 않는다. 따라서 메서드로 사용하기 위해 다른 종류의 객체로 이전될 수 있다.

23.1.3.9 Array.prototype.find ( predicate [ , thisArg ] )

Note 1

이 메서드는 predicatetrue로 강제 변환되는 값을 반환하는 요소를 찾을 때까지 배열의 각 요소에 대해 오름차순 인덱스 순서로 한 번씩 predicate를 호출한다. 그러한 요소를 찾으면, find는 즉시 그 요소 값을 반환한다. 그렇지 않으면, findundefined를 반환한다.

추가 정보는 FindViaPredicate를 보라.

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. obj를 ? ToObject(this value)라고 하자.
  2. len을 ? LengthOfArrayLike(obj)라고 하자.
  3. findRec를 ? FindViaPredicate(obj, len, ascending, predicate, thisArg)라고 하자.
  4. findRec.[[Value]]를 반환한다.
Note 2

이 메서드는 의도적으로 제네릭이다; 이 메서드는 자신의 this 값이 Array일 것을 요구하지 않는다. 따라서 메서드로 사용하기 위해 다른 종류의 객체로 이전될 수 있다.

23.1.3.10 Array.prototype.findIndex ( predicate [ , thisArg ] )

Note 1

이 메서드는 predicatetrue로 강제 변환되는 값을 반환하는 요소를 찾을 때까지 배열의 각 요소에 대해 오름차순 인덱스 순서로 한 번씩 predicate를 호출한다. 그러한 요소를 찾으면, findIndex는 즉시 그 요소 값의 인덱스를 반환한다. 그렇지 않으면, findIndex는 -1을 반환한다.

추가 정보는 FindViaPredicate를 보라.

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. obj를 ? ToObject(this value)라고 하자.
  2. len을 ? LengthOfArrayLike(obj)라고 하자.
  3. findRec를 ? FindViaPredicate(obj, len, ascending, predicate, thisArg)라고 하자.
  4. findRec.[[Index]]를 반환한다.
Note 2

이 메서드는 의도적으로 제네릭이다; 이 메서드는 자신의 this 값이 Array일 것을 요구하지 않는다. 따라서 메서드로 사용하기 위해 다른 종류의 객체로 이전될 수 있다.

23.1.3.11 Array.prototype.findLast ( predicate [ , thisArg ] )

Note 1

이 메서드는 predicatetrue로 강제 변환되는 값을 반환하는 요소를 찾을 때까지 배열의 각 요소에 대해 내림차순 인덱스 순서로 한 번씩 predicate를 호출한다. 그러한 요소를 찾으면, findLast는 즉시 그 요소 값을 반환한다. 그렇지 않으면, findLastundefined를 반환한다.

추가 정보는 FindViaPredicate를 보라.

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. obj를 ? ToObject(this value)라고 하자.
  2. len을 ? LengthOfArrayLike(obj)라고 하자.
  3. findRec를 ? FindViaPredicate(obj, len, descending, predicate, thisArg)라고 하자.
  4. findRec.[[Value]]를 반환한다.
Note 2

이 메서드는 의도적으로 제네릭이다; 이 메서드는 자신의 this 값이 Array 객체일 것을 요구하지 않는다. 따라서 메서드로 사용하기 위해 다른 종류의 객체로 이전될 수 있다.

23.1.3.12 Array.prototype.findLastIndex ( predicate [ , thisArg ] )

Note 1

이 메서드는 predicatetrue로 강제 변환되는 값을 반환하는 요소를 찾을 때까지 배열의 각 요소에 대해 내림차순 인덱스 순서로 한 번씩 predicate를 호출한다. 그러한 요소를 찾으면, findLastIndex는 즉시 그 요소 값의 인덱스를 반환한다. 그렇지 않으면, findLastIndex는 -1을 반환한다.

추가 정보는 FindViaPredicate를 보라.

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. obj를 ? ToObject(this value)라고 하자.
  2. len을 ? LengthOfArrayLike(obj)라고 하자.
  3. findRec를 ? FindViaPredicate(obj, len, descending, predicate, thisArg)라고 하자.
  4. findRec.[[Index]]를 반환한다.
Note 2

이 메서드는 의도적으로 제네릭이다; 이 메서드는 자신의 this 값이 Array 객체일 것을 요구하지 않는다. 따라서 메서드로 사용하기 위해 다른 종류의 객체로 이전될 수 있다.

23.1.3.12.1 FindViaPredicate ( obj, len, direction, predicate, thisArg )

The abstract operation FindViaPredicate takes arguments obj (an Object), len (a non-negative integer), direction (ascending or descending), predicate (an ECMAScript language value), and thisArg (an ECMAScript language value) and returns either a normal completion containing a Record with fields [[Index]] (an integral Number) and [[Value]] (an ECMAScript language value) or a throw completion.

obj는 배열 유사 객체 또는 TypedArray여야 한다. 이 연산은 direction이 나타내는 대로 오름차순 인덱스 순서 또는 내림차순 인덱스 순서로 obj의 각 요소에 대해 한 번씩 predicate를 호출하며, predicatetrue로 강제 변환되는 값을 반환하는 요소를 찾을 때까지 계속한다. 그 시점에서 이 연산은 찾은 요소의 인덱스와 값을 제공하는 Record를 반환한다. 그러한 요소를 찾지 못하면, 이 연산은 인덱스로 -1𝔽, 값으로 undefined를 지정하는 Record를 반환한다.

predicate는 함수여야 한다. 배열의 요소에 대해 호출될 때, 요소의 값, 요소의 인덱스, 그리고 순회 중인 객체라는 세 인자가 전달된다. 그 반환값은 Boolean 값으로 강제 변환된다.

thisArgpredicate의 각 호출에서 this 값으로 사용된다.

이 연산은 호출 대상 객체를 직접 변경하지 않지만, predicate 호출에 의해 객체가 변경될 수 있다.

처리되는 요소의 범위는 predicate의 첫 호출 전, 순회가 시작되기 직전에 설정된다. 이후 배열에 추가되는 요소는 predicate가 방문하지 않는다. 배열의 기존 요소가 변경되면, predicate에 전달되는 값은 이 연산이 해당 요소를 방문하는 시점의 값이 된다. 순회가 시작된 뒤 방문되기 전에 삭제되는 요소는 여전히 방문되며, 프로토타입에서 조회되거나 undefined가 된다.

It performs the following steps when called:

  1. IsCallable(predicate)가 false이면, TypeError 예외를 던진다.
  2. directionascending이면,
    1. indices를 0(포함)부터 len(제외)까지의 구간에 있는 정수들의 List로, 오름차순으로 하자.
  3. 그렇지 않으면,
    1. indices를 0(포함)부터 len(제외)까지의 구간에 있는 정수들의 List로, 내림차순으로 하자.
  4. indices의 각 정수 k에 대해, 다음을 수행한다.
    1. propertyKey를 ! ToString(𝔽(k))라고 하자.
    2. NOTE: objTypedArray이면, 다음 Get 호출은 정상 완료를 반환한다.
    3. kValue를 ? Get(obj, propertyKey)라고 하자.
    4. testResult를 ? Call(predicate, thisArg, « kValue, 𝔽(k), obj »)라고 하자.
    5. ToBoolean(testResult)가 true이면, Record { [[Index]]: 𝔽(k), [[Value]]: kValue }를 반환한다.
  5. Record { [[Index]]: -1𝔽, [[Value]]: undefined }를 반환한다.

23.1.3.13 Array.prototype.flat ( [ depth ] )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. obj를 ? ToObject(this value)라고 하자.
  2. sourceLen을 ? LengthOfArrayLike(obj)라고 하자.
  3. depthNum을 1이라고 하자.
  4. depthundefined가 아니면,
    1. depthNum을 ? ToIntegerOrInfinity(depth)로 설정한다.
    2. depthNum < 0이면, depthNum을 0으로 설정한다.
  5. array를 ? ArraySpeciesCreate(obj, 0)이라고 하자.
  6. FlattenIntoArray(array, obj, sourceLen, 0, depthNum)를 수행한다.
  7. array를 반환한다.

23.1.3.13.1 FlattenIntoArray ( target, source, sourceLen, start, depth [ , mapperFunction [ , thisArg ] ] )

The abstract operation FlattenIntoArray takes arguments target (an Object), source (an Object), sourceLen (a non-negative integer), start (a non-negative integer), and depth (a non-negative integer or +∞) and optional arguments mapperFunction (a function object) and thisArg (an ECMAScript language value) and returns either a normal completion containing a non-negative integer or a throw completion. It performs the following steps when called:

  1. Assert: mapperFunction이 존재하면, IsCallable(mapperFunction)는 true이고, thisArg가 존재하며, depth는 1이다.
  2. targetIndexstart라고 하자.
  3. sourceIndex+0𝔽이라고 하자.
  4. (sourceIndex) < sourceLen인 동안 반복한다,
    1. propertyKey를 ! ToString(sourceIndex)라고 하자.
    2. exists를 ? HasProperty(source, propertyKey)라고 하자.
    3. existstrue이면,
      1. element를 ? Get(source, propertyKey)라고 하자.
      2. mapperFunction이 존재하면,
        1. element를 ? Call(mapperFunction, thisArg, « element, sourceIndex, source »)로 설정한다.
      3. shouldFlattenfalse라고 하자.
      4. depth > 0이면,
        1. shouldFlatten을 ? IsArray(element)로 설정한다.
      5. shouldFlattentrue이면,
        1. depth = +∞이면 newDepth를 +∞라고 하자.
        2. 그렇지 않으면, newDepthdepth - 1이라고 하자.
        3. elementLen을 ? LengthOfArrayLike(element)라고 하자.
        4. targetIndex를 ? FlattenIntoArray(target, element, elementLen, targetIndex, newDepth)로 설정한다.
      6. 그렇지 않으면,
        1. targetIndex ≥ 253 - 1이면, TypeError 예외를 던진다.
        2. CreateDataPropertyOrThrow(target, ! ToString(𝔽(targetIndex)), element)를 수행한다.
        3. targetIndextargetIndex + 1로 설정한다.
    4. sourceIndexsourceIndex + 1𝔽로 설정한다.
  5. targetIndex를 반환한다.

23.1.3.14 Array.prototype.flatMap ( mapperFunction [ , thisArg ] )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. obj를 ? ToObject(this value)라고 하자.
  2. sourceLen을 ? LengthOfArrayLike(obj)라고 하자.
  3. IsCallable(mapperFunction)가 false이면, TypeError 예외를 던진다.
  4. array를 ? ArraySpeciesCreate(obj, 0)이라고 하자.
  5. FlattenIntoArray(array, obj, sourceLen, 0, 1, mapperFunction, thisArg)를 수행한다.
  6. array를 반환한다.

23.1.3.15 Array.prototype.forEach ( callback [ , thisArg ] )

Note 1

callback은 세 개의 인자를 받는 함수여야 한다. forEach는 배열에 존재하는 각 요소에 대해 오름차순으로 한 번씩 callback을 호출한다. callback은 실제로 존재하는 배열 요소에 대해서만 호출되며, 배열의 누락된 요소에 대해서는 호출되지 않는다.

thisArg 매개변수가 제공되면, callback의 각 호출에서 this 값으로 사용된다. 제공되지 않으면, 대신 undefined가 사용된다.

callback은 세 개의 인자, 즉 요소의 값, 요소의 인덱스, 그리고 순회 중인 객체와 함께 호출된다.

forEach는 호출 대상 객체를 직접 변경하지 않지만, callback 호출에 의해 객체가 변경될 수 있다.

forEach가 처리하는 요소의 범위는 callback의 첫 호출 전에 설정된다. forEach 호출이 시작된 뒤 배열에 추가되는 요소는 callback이 방문하지 않는다. 배열의 기존 요소가 변경되면, callback에 전달되는 값은 forEach가 해당 요소를 방문하는 시점의 값이 된다; forEach 호출이 시작된 뒤 방문되기 전에 삭제되는 요소는 방문되지 않는다.

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. obj를 ? ToObject(this value)라고 하자.
  2. len을 ? LengthOfArrayLike(obj)라고 하자.
  3. IsCallable(callback)가 false이면, TypeError 예외를 던진다.
  4. k를 0이라고 하자.
  5. k < len인 동안 반복한다,
    1. propertyKey를 ! ToString(𝔽(k))라고 하자.
    2. kPresent를 ? HasProperty(obj, propertyKey)라고 하자.
    3. kPresenttrue이면,
      1. kValue를 ? Get(obj, propertyKey)라고 하자.
      2. Call(callback, thisArg, « kValue, 𝔽(k), obj »)를 수행한다.
    4. kk + 1로 설정한다.
  6. undefined를 반환한다.
Note 2

이 메서드는 의도적으로 제네릭이다; 이 메서드는 자신의 this 값이 Array일 것을 요구하지 않는다. 따라서 메서드로 사용하기 위해 다른 종류의 객체로 이전될 수 있다.

23.1.3.16 Array.prototype.includes ( searchElement [ , fromIndex ] )

Note 1

이 메서드는 SameValueZero 알고리즘을 사용해 searchElement를 배열의 요소들과 오름차순으로 비교하고, 어느 위치에서든 발견되면 true를 반환한다; 그렇지 않으면 false를 반환한다.

선택적 두 번째 인자 fromIndex의 기본값은 +0𝔽이다(즉, 전체 배열을 검색한다). 이 값이 배열의 길이보다 크거나 같으면, false가 반환된다. 즉 배열을 검색하지 않는다. -0𝔽보다 작으면, fromIndex를 계산하기 위해 배열 끝으로부터의 오프셋으로 사용된다. 계산된 인덱스가 +0𝔽 이하이면, 전체 배열을 검색한다.

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. obj를 ? ToObject(this value)라고 하자.
  2. len을 ? LengthOfArrayLike(obj)라고 하자.
  3. len = 0이면, false를 반환한다.
  4. startIndex를 ? ToIntegerOrInfinity(fromIndex)라고 하자.
  5. Assert: fromIndexundefined이면, startIndex는 0이다.
  6. startIndex = +∞이면, false를 반환한다.
  7. startIndex = -∞이면, startIndex를 0으로 설정한다.
  8. startIndex ≥ 0이면,
    1. kstartIndex라고 하자.
  9. 그렇지 않으면,
    1. klen + startIndex라고 하자.
    2. k < 0이면, k를 0으로 설정한다.
  10. k < len인 동안 반복한다,
    1. elementK를 ? Get(obj, ! ToString(𝔽(k)))라고 하자.
    2. SameValueZero(searchElement, elementK)가 true이면, true를 반환한다.
    3. kk + 1로 설정한다.
  11. false를 반환한다.
Note 2

이 메서드는 의도적으로 제네릭이다; 이 메서드는 자신의 this 값이 Array일 것을 요구하지 않는다. 따라서 메서드로 사용하기 위해 다른 종류의 객체로 이전될 수 있다.

Note 3

이 메서드는 유사한 indexOf 메서드와 의도적으로 두 가지 점에서 다르다. 첫째, IsStrictlyEqual 대신 SameValueZero 알고리즘을 사용하므로 NaN 배열 요소를 감지할 수 있다. 둘째, 누락된 배열 요소를 건너뛰지 않고 undefined로 취급한다.

23.1.3.17 Array.prototype.indexOf ( searchElement [ , fromIndex ] )

이 메서드는 IsStrictlyEqual 알고리즘을 사용해 searchElement를 배열의 요소들과 오름차순으로 비교하고, 하나 이상의 인덱스에서 발견되면 그러한 가장 작은 인덱스를 반환한다; 그렇지 않으면 -1𝔽을 반환한다.

Note 1

선택적 두 번째 인자 fromIndex의 기본값은 +0𝔽이다(즉, 전체 배열을 검색한다). 이 값이 배열의 길이보다 크거나 같으면, -1𝔽이 반환된다. 즉 배열을 검색하지 않는다. -0𝔽보다 작으면, 배열 끝으로부터의 오프셋을 계산하는 데 사용된다. 계산된 인덱스가 +0𝔽 이하이면, 전체 배열을 검색한다.

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. obj를 ? ToObject(this value)라고 하자.
  2. len을 ? LengthOfArrayLike(obj)라고 하자.
  3. len = 0이면, -1𝔽을 반환한다.
  4. startIndex를 ? ToIntegerOrInfinity(fromIndex)라고 하자.
  5. Assert: fromIndexundefined이면, startIndex는 0이다.
  6. startIndex = +∞이면, -1𝔽을 반환한다.
  7. startIndex = -∞이면, startIndex를 0으로 설정한다.
  8. startIndex ≥ 0이면,
    1. kstartIndex라고 하자.
  9. 그렇지 않으면,
    1. klen + startIndex라고 하자.
    2. k < 0이면, k를 0으로 설정한다.
  10. k < len인 동안 반복한다,
    1. propertyKey를 ! ToString(𝔽(k))라고 하자.
    2. kPresent를 ? HasProperty(obj, propertyKey)라고 하자.
    3. kPresenttrue이면,
      1. elementK를 ? Get(obj, propertyKey)라고 하자.
      2. IsStrictlyEqual(searchElement, elementK)가 true이면, 𝔽(k)를 반환한다.
    4. kk + 1로 설정한다.
  11. -1𝔽을 반환한다.
Note 2

이 메서드는 의도적으로 제네릭이다; 이 메서드는 자신의 this 값이 Array일 것을 요구하지 않는다. 따라서 메서드로 사용하기 위해 다른 종류의 객체로 이전될 수 있다.

23.1.3.18 Array.prototype.join ( separator )

이 메서드는 배열의 요소들을 String으로 변환한 뒤, separator의 출현으로 구분하여 이 String들을 연결한다. 구분자가 제공되지 않으면, 단일 쉼표가 구분자로 사용된다.

호출될 때 다음 단계를 수행한다:

  1. obj를 ? ToObject(this value)라고 하자.
  2. len을 ? LengthOfArrayLike(obj)라고 하자.
  3. separatorundefined이면, sep","라고 하자.
  4. 그렇지 않으면, sep를 ? ToString(separator)라고 하자.
  5. result를 빈 String이라고 하자.
  6. k를 0이라고 하자.
  7. k < len인 동안 반복한다,
    1. k > 0이면, resultresultsep의 문자열 연결로 설정한다.
    2. element를 ? Get(obj, ! ToString(𝔽(k)))라고 하자.
    3. elementundefined도 아니고 null도 아니면,
      1. elementStr을 ? ToString(element)라고 하자.
      2. resultresultelementStr의 문자열 연결로 설정한다.
    4. kk + 1로 설정한다.
  8. result를 반환한다.
Note

이 메서드는 의도적으로 제네릭이다; 이 메서드는 자신의 this 값이 Array일 것을 요구하지 않는다. 따라서 메서드로 사용하기 위해 다른 종류의 객체로 이전될 수 있다.

23.1.3.19 Array.prototype.keys ( )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. obj를 ? ToObject(this value)라고 하자.
  2. CreateArrayIterator(obj, key)를 반환한다.

23.1.3.20 Array.prototype.lastIndexOf ( searchElement [ , fromIndex ] )

Note 1

이 메서드는 IsStrictlyEqual 알고리즘을 사용해 searchElement를 배열의 요소들과 내림차순으로 비교하고, 하나 이상의 인덱스에서 발견되면 그러한 가장 큰 인덱스를 반환한다; 그렇지 않으면 -1𝔽을 반환한다.

선택적 두 번째 인자 fromIndex의 기본값은 배열의 길이에서 1을 뺀 값이다(즉, 전체 배열을 검색한다). 이 값이 배열의 길이보다 크거나 같으면, 전체 배열을 검색한다. -0𝔽보다 작으면, 배열 끝으로부터의 오프셋을 계산하는 데 사용된다. 계산된 인덱스가 -0𝔽보다 작으면, -1𝔽이 반환된다.

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. obj를 ? ToObject(this value)라고 하자.
  2. len을 ? LengthOfArrayLike(obj)라고 하자.
  3. len = 0이면, -1𝔽을 반환한다.
  4. fromIndex가 존재하면 startIndex를 ? ToIntegerOrInfinity(fromIndex)라고 하자; 그렇지 않으면 startIndexlen - 1이라고 하자.
  5. startIndex = -∞이면, -1𝔽을 반환한다.
  6. startIndex ≥ 0이면,
    1. kmin(startIndex, len - 1)이라고 하자.
  7. 그렇지 않으면,
    1. klen + startIndex라고 하자.
  8. k ≥ 0인 동안 반복한다,
    1. propertyKey를 ! ToString(𝔽(k))라고 하자.
    2. kPresent를 ? HasProperty(obj, propertyKey)라고 하자.
    3. kPresenttrue이면,
      1. elementK를 ? Get(obj, propertyKey)라고 하자.
      2. IsStrictlyEqual(searchElement, elementK)가 true이면, 𝔽(k)를 반환한다.
    4. kk - 1로 설정한다.
  9. -1𝔽을 반환한다.
Note 2

이 메서드는 의도적으로 제네릭이다; 이 메서드는 자신의 this 값이 Array일 것을 요구하지 않는다. 따라서 메서드로 사용하기 위해 다른 종류의 객체로 이전될 수 있다.

23.1.3.21 Array.prototype.map ( callback [ , thisArg ] )

Note 1

callback은 세 개의 인자를 받는 함수여야 한다. map은 배열의 각 요소에 대해 오름차순으로 한 번씩 callback을 호출하고, 그 결과로 새 Array를 구성한다. callback은 실제로 존재하는 배열 요소에 대해서만 호출되며, 배열의 누락된 요소에 대해서는 호출되지 않는다.

thisArg 매개변수가 제공되면, callback의 각 호출에서 this 값으로 사용된다. 제공되지 않으면, 대신 undefined가 사용된다.

callback은 세 개의 인자, 즉 요소의 값, 요소의 인덱스, 그리고 순회 중인 객체와 함께 호출된다.

map은 호출 대상 객체를 직접 변경하지 않지만, callback 호출에 의해 객체가 변경될 수 있다.

map이 처리하는 요소의 범위는 callback의 첫 호출 전에 설정된다. map 호출이 시작된 뒤 배열에 추가되는 요소는 callback이 방문하지 않는다. 배열의 기존 요소가 변경되면, callback에 전달되는 값은 map이 해당 요소를 방문하는 시점의 값이 된다; map 호출이 시작된 뒤 방문되기 전에 삭제되는 요소는 방문되지 않는다.

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. obj를 ? ToObject(this value)라고 하자.
  2. len을 ? LengthOfArrayLike(obj)라고 하자.
  3. IsCallable(callback)가 false이면, TypeError 예외를 던진다.
  4. array를 ? ArraySpeciesCreate(obj, len)라고 하자.
  5. k를 0이라고 하자.
  6. k < len인 동안 반복한다,
    1. propertyKey를 ! ToString(𝔽(k))라고 하자.
    2. kPresent를 ? HasProperty(obj, propertyKey)라고 하자.
    3. kPresenttrue이면,
      1. kValue를 ? Get(obj, propertyKey)라고 하자.
      2. mappedValue를 ? Call(callback, thisArg, « kValue, 𝔽(k), obj »)라고 하자.
      3. CreateDataPropertyOrThrow(array, propertyKey, mappedValue)를 수행한다.
    4. kk + 1로 설정한다.
  7. array를 반환한다.
Note 2

이 메서드는 의도적으로 제네릭이다; 이 메서드는 자신의 this 값이 Array일 것을 요구하지 않는다. 따라서 메서드로 사용하기 위해 다른 종류의 객체로 이전될 수 있다.

23.1.3.22 Array.prototype.pop ( )

Note 1

이 메서드는 배열의 마지막 요소를 제거하고 그것을 반환한다.

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. obj를 ? ToObject(this value)라고 하자.
  2. len을 ? LengthOfArrayLike(obj)라고 하자.
  3. len = 0이면,
    1. Set(obj, "length", +0𝔽, true)를 수행한다.
    2. undefined를 반환한다.
  4. Assert: len > 0.
  5. newLen𝔽(len - 1)이라고 하자.
  6. index를 ! ToString(newLen)이라고 하자.
  7. element를 ? Get(obj, index)라고 하자.
  8. DeletePropertyOrThrow(obj, index)를 수행한다.
  9. Set(obj, "length", newLen, true)를 수행한다.
  10. element를 반환한다.
Note 2

이 메서드는 의도적으로 제네릭이다; 이 메서드는 자신의 this 값이 Array일 것을 요구하지 않는다. 따라서 메서드로 사용하기 위해 다른 종류의 객체로 이전될 수 있다.

23.1.3.23 Array.prototype.push ( ...items )

Note 1

이 메서드는 인자들을 나타나는 순서대로 배열의 끝에 추가한다. 이 메서드는 배열의 새 길이를 반환한다.

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. obj를 ? ToObject(this value)라고 하자.
  2. len을 ? LengthOfArrayLike(obj)라고 하자.
  3. argCountitems의 요소 개수라고 하자.
  4. len + argCount > 253 - 1이면, TypeError 예외를 던진다.
  5. items의 각 요소 item에 대해, 다음을 수행한다.
    1. Set(obj, ! ToString(𝔽(len)), item, true)를 수행한다.
    2. lenlen + 1로 설정한다.
  6. Set(obj, "length", 𝔽(len), true)를 수행한다.
  7. 𝔽(len)를 반환한다.

이 메서드의 "length" 속성은 1𝔽이다.

Note 2

이 메서드는 의도적으로 제네릭이다; 이 메서드는 자신의 this 값이 Array일 것을 요구하지 않는다. 따라서 메서드로 사용하기 위해 다른 종류의 객체로 이전될 수 있다.

23.1.3.24 Array.prototype.reduce ( callback [ , initialValue ] )

Note 1

callback은 네 개의 인수를 받는 함수여야 한다. reduceinitialValue가 제공되지 않는 한 첫 번째 요소를 건너뛰고, 배열에 존재하는 각 요소에 대해 오름차순으로 callback을 한 번씩 호출한다.

callback은 네 개의 인자, 즉 previousValue(callback의 이전 호출에서 온 값), currentValue(현재 요소의 값), currentIndex, 그리고 순회 중인 객체와 함께 호출된다. callback이 처음 호출될 때, previousValuecurrentValue는 두 값 중 하나일 수 있다. reduce 호출에서 initialValue가 제공되었다면, previousValueinitialValue가 되고 currentValue는 배열의 첫 번째 값이 된다. initialValue가 제공되지 않았다면, previousValue는 배열의 첫 번째 값이 되고 currentValue는 두 번째 값이 된다. 배열이 요소를 포함하지 않고 initialValue가 제공되지 않으면 TypeError이다.

reduce는 호출 대상 객체를 직접 변경하지 않지만, callback 호출에 의해 객체가 변경될 수 있다.

reduce가 처리하는 요소의 범위는 callback의 첫 호출 전에 설정된다. reduce 호출이 시작된 뒤 배열에 추가되는 요소는 callback이 방문하지 않는다. 배열의 기존 요소가 변경되면, callback에 전달되는 값은 reduce가 해당 요소를 방문하는 시점의 값이 된다; reduce 호출이 시작된 뒤 방문되기 전에 삭제되는 요소는 방문되지 않는다.

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. obj를 ? ToObject(this value)라고 하자.
  2. len을 ? LengthOfArrayLike(obj)라고 하자.
  3. IsCallable(callback)가 false이면, TypeError 예외를 던진다.
  4. len = 0이고 initialValue가 존재하지 않으면, TypeError 예외를 던진다.
  5. k를 0이라고 하자.
  6. accumulatorundefined라고 하자.
  7. initialValue가 존재하면,
    1. accumulatorinitialValue로 설정한다.
  8. 그렇지 않으면,
    1. kPresentfalse라고 하자.
    2. kPresentfalse이고 k < len인 동안 반복한다,
      1. propertyKey를 ! ToString(𝔽(k))라고 하자.
      2. kPresent를 ? HasProperty(obj, propertyKey)로 설정한다.
      3. kPresenttrue이면,
        1. accumulator를 ? Get(obj, propertyKey)로 설정한다.
      4. kk + 1로 설정한다.
    3. kPresentfalse이면, TypeError 예외를 던진다.
  9. k < len인 동안 반복한다,
    1. propertyKey를 ! ToString(𝔽(k))라고 하자.
    2. kPresent를 ? HasProperty(obj, propertyKey)라고 하자.
    3. kPresenttrue이면,
      1. kValue를 ? Get(obj, propertyKey)라고 하자.
      2. accumulator를 ? Call(callback, undefined, « accumulator, kValue, 𝔽(k), obj »)로 설정한다.
    4. kk + 1로 설정한다.
  10. accumulator를 반환한다.
Note 2

이 메서드는 의도적으로 제네릭이다; 이 메서드는 자신의 this 값이 Array일 것을 요구하지 않는다. 따라서 메서드로 사용하기 위해 다른 종류의 객체로 이전될 수 있다.

23.1.3.25 Array.prototype.reduceRight ( callback [ , initialValue ] )

Note 1

callback은 네 개의 인수를 받는 함수여야 한다. reduceRightinitialValue가 제공되지 않는 한 첫 번째 호출을 건너뛰고, 배열에 존재하는 각 요소에 대해 내림차순으로 callback을 한 번씩 호출한다.

callback은 네 개의 인자, 즉 previousValue(callback의 이전 호출에서 온 값), currentValue(현재 요소의 값), currentIndex, 그리고 순회 중인 객체와 함께 호출된다. 함수가 처음 호출될 때, previousValuecurrentValue는 두 값 중 하나일 수 있다. reduceRight 호출에서 initialValue가 제공되었다면, previousValueinitialValue가 되고 currentValue는 배열의 마지막 값이 된다. initialValue가 제공되지 않았다면, previousValue는 배열의 마지막 값이 되고 currentValue는 끝에서 두 번째 값이 된다. 배열이 요소를 포함하지 않고 initialValue가 제공되지 않으면 TypeError이다.

reduceRight는 호출 대상 객체를 직접 변경하지 않지만, callback 호출에 의해 객체가 변경될 수 있다.

reduceRight가 처리하는 요소의 범위는 callback의 첫 호출 전에 설정된다. reduceRight 호출이 시작된 뒤 배열에 추가되는 요소는 callback이 방문하지 않는다. 배열의 기존 요소가 callback에 의해 변경되면, callback에 전달되는 값은 reduceRight가 해당 요소를 방문하는 시점의 값이 된다; reduceRight 호출이 시작된 뒤 방문되기 전에 삭제되는 요소는 방문되지 않는다.

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. obj를 ? ToObject(this value)라고 하자.
  2. len을 ? LengthOfArrayLike(obj)라고 하자.
  3. IsCallable(callback)가 false이면, TypeError 예외를 던진다.
  4. len = 0이고 initialValue가 존재하지 않으면, TypeError 예외를 던진다.
  5. klen - 1이라고 하자.
  6. accumulatorundefined라고 하자.
  7. initialValue가 존재하면,
    1. accumulatorinitialValue로 설정한다.
  8. 그렇지 않으면,
    1. kPresentfalse라고 하자.
    2. kPresentfalse이고 k ≥ 0인 동안 반복한다,
      1. propertyKey를 ! ToString(𝔽(k))라고 하자.
      2. kPresent를 ? HasProperty(obj, propertyKey)로 설정한다.
      3. kPresenttrue이면,
        1. accumulator를 ? Get(obj, propertyKey)로 설정한다.
      4. kk - 1로 설정한다.
    3. kPresentfalse이면, TypeError 예외를 던진다.
  9. k ≥ 0인 동안 반복한다,
    1. propertyKey를 ! ToString(𝔽(k))라고 하자.
    2. kPresent를 ? HasProperty(obj, propertyKey)라고 하자.
    3. kPresenttrue이면,
      1. kValue를 ? Get(obj, propertyKey)라고 하자.
      2. accumulator를 ? Call(callback, undefined, « accumulator, kValue, 𝔽(k), obj »)로 설정한다.
    4. kk - 1로 설정한다.
  10. accumulator를 반환한다.
Note 2

이 메서드는 의도적으로 제네릭이다; 이 메서드는 자신의 this 값이 Array일 것을 요구하지 않는다. 따라서 메서드로 사용하기 위해 다른 종류의 객체로 이전될 수 있다.

23.1.3.26 Array.prototype.reverse ( )

Note 1

이 메서드는 배열의 요소들을 재배열하여 그 순서를 뒤집는다. 뒤집힌 배열을 반환한다.

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. obj를 ? ToObject(this value)라고 하자.
  2. len을 ? LengthOfArrayLike(obj)라고 하자.
  3. middlefloor(len / 2)라고 하자.
  4. lower를 0이라고 하자.
  5. lowermiddle인 동안 반복한다,
    1. upperlen - lower - 1이라고 하자.
    2. upperP를 ! ToString(𝔽(upper))라고 하자.
    3. lowerP를 ! ToString(𝔽(lower))라고 하자.
    4. lowerExists를 ? HasProperty(obj, lowerP)라고 하자.
    5. lowerExiststrue이면,
      1. lowerValue를 ? Get(obj, lowerP)라고 하자.
    6. upperExists를 ? HasProperty(obj, upperP)라고 하자.
    7. upperExiststrue이면,
      1. upperValue를 ? Get(obj, upperP)라고 하자.
    8. lowerExiststrue이고 upperExiststrue이면,
      1. Set(obj, lowerP, upperValue, true)를 수행한다.
      2. Set(obj, upperP, lowerValue, true)를 수행한다.
    9. 그렇지 않고 lowerExistsfalse이고 upperExiststrue이면,
      1. Set(obj, lowerP, upperValue, true)를 수행한다.
      2. DeletePropertyOrThrow(obj, upperP)를 수행한다.
    10. 그렇지 않고 lowerExiststrue이고 upperExistsfalse이면,
      1. DeletePropertyOrThrow(obj, lowerP)를 수행한다.
      2. Set(obj, upperP, lowerValue, true)를 수행한다.
    11. 그렇지 않으면,
      1. Assert: lowerExistsupperExists는 모두 false이다.
      2. NOTE: 아무 동작도 필요하지 않다.
    12. lowerlower + 1로 설정한다.
  6. obj를 반환한다.
Note 2

이 메서드는 의도적으로 제네릭이다; 이 메서드는 자신의 this 값이 Array일 것을 요구하지 않는다. 따라서 메서드로 사용하기 위해 다른 종류의 객체로 이전될 수 있다.

23.1.3.27 Array.prototype.shift ( )

이 메서드는 배열의 첫 번째 요소를 제거하고 그것을 반환한다.

호출될 때 다음 단계를 수행한다:

  1. obj를 ? ToObject(this value)라고 하자.
  2. len을 ? LengthOfArrayLike(obj)라고 하자.
  3. len = 0이면,
    1. Set(obj, "length", +0𝔽, true)를 수행한다.
    2. undefined를 반환한다.
  4. first를 ? Get(obj, "0")라고 하자.
  5. k를 1이라고 하자.
  6. k < len인 동안 반복한다,
    1. from을 ! ToString(𝔽(k))라고 하자.
    2. to를 ! ToString(𝔽(k - 1))라고 하자.
    3. fromPresent를 ? HasProperty(obj, from)라고 하자.
    4. fromPresenttrue이면,
      1. fromValue를 ? Get(obj, from)라고 하자.
      2. Set(obj, to, fromValue, true)를 수행한다.
    5. 그렇지 않으면,
      1. Assert: fromPresentfalse이다.
      2. DeletePropertyOrThrow(obj, to)를 수행한다.
    6. kk + 1로 설정한다.
  7. DeletePropertyOrThrow(obj, ! ToString(𝔽(len - 1)))를 수행한다.
  8. Set(obj, "length", 𝔽(len - 1), true)를 수행한다.
  9. first를 반환한다.
Note

이 메서드는 의도적으로 제네릭이다; 이 메서드는 자신의 this 값이 Array일 것을 요구하지 않는다. 따라서 메서드로 사용하기 위해 다른 종류의 객체로 이전될 수 있다.

23.1.3.28 Array.prototype.slice ( start, end )

이 메서드는 배열의 요소 start부터 요소 end 전까지(endundefined이면 배열의 끝까지)의 요소들을 포함하는 배열을 반환한다. start가 음수이면, 배열의 길이인 length에 대해 length + start로 취급된다. end가 음수이면, 배열의 길이인 length에 대해 length + end로 취급된다.

호출될 때 다음 단계를 수행한다:

  1. obj를 ? ToObject(this value)라고 하자.
  2. len을 ? LengthOfArrayLike(obj)라고 하자.
  3. relativeStart를 ? ToIntegerOrInfinity(start)라고 하자.
  4. relativeStart = -∞이면, k를 0이라고 하자.
  5. 그렇지 않고 relativeStart < 0이면, kmax(len + relativeStart, 0)이라고 하자.
  6. 그렇지 않으면, kmin(relativeStart, len)이라고 하자.
  7. endundefined이면 relativeEndlen이라고 하자; 그렇지 않으면 relativeEnd를 ? ToIntegerOrInfinity(end)라고 하자.
  8. relativeEnd = -∞이면, final을 0이라고 하자.
  9. 그렇지 않고 relativeEnd < 0이면, finalmax(len + relativeEnd, 0)이라고 하자.
  10. 그렇지 않으면, finalmin(relativeEnd, len)이라고 하자.
  11. countmax(final - k, 0)이라고 하자.
  12. array를 ? ArraySpeciesCreate(obj, count)라고 하자.
  13. resultIndex를 0이라고 하자.
  14. k < final인 동안 반복한다,
    1. propertyKey를 ! ToString(𝔽(k))라고 하자.
    2. kPresent를 ? HasProperty(obj, propertyKey)라고 하자.
    3. kPresenttrue이면,
      1. kValue를 ? Get(obj, propertyKey)라고 하자.
      2. CreateDataPropertyOrThrow(array, ! ToString(𝔽(resultIndex)), kValue)를 수행한다.
    4. kk + 1로 설정한다.
    5. resultIndexresultIndex + 1로 설정한다.
  15. Set(array, "length", 𝔽(resultIndex), true)를 수행한다.
  16. array를 반환한다.
Note 1

단계 15에서 "length" 속성을 명시적으로 설정하는 것은 array가 내장 Array가 아닐 때도 길이가 올바르도록 보장하기 위한 것이다.

Note 2

이 메서드는 의도적으로 제네릭이다; 이 메서드는 자신의 this 값이 Array일 것을 요구하지 않는다. 따라서 메서드로 사용하기 위해 다른 종류의 객체로 이전될 수 있다.

23.1.3.29 Array.prototype.some ( callback [ , thisArg ] )

Note 1

callback은 세 개의 인자를 받아 Boolean 값으로 강제 변환될 수 있는 값을 반환하는 함수여야 한다. somecallbacktrue를 반환하는 요소를 찾을 때까지 배열에 존재하는 각 요소에 대해 오름차순으로 한 번씩 callback을 호출한다. 그러한 요소를 찾으면, some은 즉시 true를 반환한다. 그렇지 않으면, somefalse를 반환한다. callback은 실제로 존재하는 배열 요소에 대해서만 호출되며, 배열의 누락된 요소에 대해서는 호출되지 않는다.

thisArg 매개변수가 제공되면, callback의 각 호출에서 this 값으로 사용된다. 제공되지 않으면, 대신 undefined가 사용된다.

callback은 세 개의 인자, 즉 요소의 값, 요소의 인덱스, 그리고 순회 중인 객체와 함께 호출된다.

some은 호출 대상 객체를 직접 변경하지 않지만, callback 호출에 의해 객체가 변경될 수 있다.

some이 처리하는 요소의 범위는 callback의 첫 호출 전에 설정된다. some 호출이 시작된 뒤 배열에 추가되는 요소는 callback이 방문하지 않는다. 배열의 기존 요소가 변경되면, callback에 전달되는 값은 some이 해당 요소를 방문하는 시점의 값이 된다; some 호출이 시작된 뒤 방문되기 전에 삭제되는 요소는 방문되지 않는다. some은 수학의 "exists" 한정자처럼 동작한다. 특히 빈 배열에 대해서는 false를 반환한다.

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. obj를 ? ToObject(this value)라고 하자.
  2. len을 ? LengthOfArrayLike(obj)라고 하자.
  3. IsCallable(callback)가 false이면, TypeError 예외를 던진다.
  4. k를 0이라고 하자.
  5. k < len인 동안 반복한다,
    1. propertyKey를 ! ToString(𝔽(k))라고 하자.
    2. kPresent를 ? HasProperty(obj, propertyKey)라고 하자.
    3. kPresenttrue이면,
      1. kValue를 ? Get(obj, propertyKey)라고 하자.
      2. testResultToBoolean(? Call(callback, thisArg, « kValue, 𝔽(k), obj »))라고 하자.
      3. testResulttrue이면, true를 반환한다.
    4. kk + 1로 설정한다.
  6. false를 반환한다.
Note 2

이 메서드는 의도적으로 제네릭이다; 이 메서드는 자신의 this 값이 Array일 것을 요구하지 않는다. 따라서 메서드로 사용하기 위해 다른 종류의 객체로 이전될 수 있다.

23.1.3.30 Array.prototype.sort ( comparator )

이 메서드는 이 배열의 요소들을 정렬한다. comparatorundefined가 아니면, 두 인자 xy를 받아 x < y이면 음수 Number, x > y이면 양수 Number, 그 밖의 경우에는 0을 반환하는 함수여야 한다.

호출될 때 다음 단계를 수행한다:

  1. comparatorundefined가 아니고 IsCallable(comparator)가 false이면, TypeError 예외를 던진다.
  2. obj를 ? ToObject(this value)라고 하자.
  3. len을 ? LengthOfArrayLike(obj)라고 하자.
  4. sortComparecomparator를 캡처하고 호출될 때 다음 단계를 수행하는, 매개변수 (x, y)를 가진 새로운 Abstract Closure라고 하자:
    1. CompareArrayElements(x, y, comparator)를 반환한다.
  5. sortedList를 ? SortIndexedProperties(obj, len, sortCompare, skip-holes)라고 하자.
  6. itemCountsortedList의 요소 개수라고 하자.
  7. j를 0이라고 하자.
  8. j < itemCount인 동안 반복한다,
    1. Set(obj, ! ToString(𝔽(j)), sortedList[j], true)를 수행한다.
    2. jj + 1로 설정한다.
  9. NOTE: 단계 5에서 SortIndexedProperties 호출은 skip-holes를 사용한다. 나머지 인덱스는 감지되어 정렬에서 제외된 빈 슬롯의 수를 보존하기 위해 삭제된다.
  10. j < len인 동안 반복한다,
    1. DeletePropertyOrThrow(obj, ! ToString(𝔽(j)))를 수행한다.
    2. jj + 1로 설정한다.
  11. obj를 반환한다.
Note 1

존재하지 않는 속성 값은 항상 undefined 속성 값보다 크게 비교되고, undefined는 항상 다른 어떤 값보다도 크게 비교되므로(CompareArrayElements를 보라), undefined 속성 값은 항상 결과의 끝으로 정렬되고, 그 뒤에 존재하지 않는 속성 값이 온다.

Note 2

단계 56ToString 추상 연산에 의해 수행되는 메서드 호출은 sortCompare일관된 비교자로 동작하지 않게 만들 가능성이 있다.

Note 3

이 메서드는 의도적으로 제네릭이다; 이 메서드는 자신의 this 값이 Array일 것을 요구하지 않는다. 따라서 메서드로 사용하기 위해 다른 종류의 객체로 이전될 수 있다.

23.1.3.30.1 SortIndexedProperties ( obj, len, sortCompare, holes )

The abstract operation SortIndexedProperties takes arguments obj (an Object), len (a non-negative integer), sortCompare (an Abstract Closure with two parameters), and holes (skip-holes or read-through-holes) and returns either a normal completion containing a List of ECMAScript language values or a throw completion. It performs the following steps when called:

  1. items를 새로운 빈 List라고 하자.
  2. k를 0이라고 하자.
  3. k < len인 동안 반복한다,
    1. propertyKey를 ! ToString(𝔽(k))라고 하자.
    2. holesskip-holes이면,
      1. kRead를 ? HasProperty(obj, propertyKey)라고 하자.
    3. 그렇지 않으면,
      1. Assert: holesread-through-holes이다.
      2. kReadtrue라고 하자.
    4. kReadtrue이면,
      1. kValue를 ? Get(obj, propertyKey)라고 하자.
      2. kValueitems에 추가한다.
    5. kk + 1로 설정한다.
  4. 구현 정의 순서의 sortCompare 호출을 사용하여 items를 정렬한다. 그러한 호출 중 하나라도 abrupt completion을 반환하면, sortCompare에 대한 추가 호출을 수행하기 전에 중단하고 그 Completion Record를 반환한다.
  5. items를 반환한다.

정렬 순서는 위 알고리즘의 단계 4가 완료된 후 items의 순서이다. sortCompareitems의 요소들에 대해 일관된 비교자가 아니면 정렬 순서구현 정의이다. SortIndexedProperties가 Array.prototype.sort 또는 Array.prototype.toSorted에 의해 호출될 때, comparatorundefined이고 sortCompare의 인자로 전달된 특정 값에 대한 모든 ToString 적용이 같은 결과를 생성하지 않는 경우에도 정렬 순서구현 정의이다.

정렬 순서구현 정의로 지정되지 않는 한, 다음 조건을 모두 만족해야 한다:

  • itemCount보다 작은 음이 아닌 정수들의 어떤 수학적 순열 π가 존재하여, itemCount보다 작은 모든 음이 아닌 정수 j에 대해 요소 old[j]new[π(j)]와 정확히 같아야 한다.
  • 그러면 itemCount보다 각각 작은 모든 음이 아닌 정수 jk에 대해, (sortCompare(old[j], old[k])) < 0이면 π(j) < π(k)이다.
  • 그리고 j < k < itemCount인 모든 음이 아닌 정수 jk에 대해, (sortCompare(old[j], old[k])) = 0이면 π(j) < π(k)이다; 즉 정렬은 안정적이다.

여기서 표기 old[j]는 단계 4가 실행되기 전의 items[j]를 가리키기 위해 사용되고, 표기 new[j]는 단계 4가 실행된 후의 items[j]를 가리키기 위해 사용된다.

Abstract Closure 또는 함수 comparator는 값들의 집합 values에 대해 다음 요구사항이 그 집합 values 안의 모든 값 a, b, 및 c(같은 값일 수도 있음)에 대해 충족되면 일관된 비교자이다: 표기 a <C b(comparator(a, b)) < 0을 의미하고; a =C b(comparator(a, b)) = 0을 의미하며; a >C b(comparator(a, b)) > 0을 의미한다.

  • comparator(a, b)를 호출하면 특정 값 쌍 ab를 두 인자로 받았을 때 항상 같은 값 v를 반환한다. 또한 v는 Number이고, vNaN이 아니다. 이는 주어진 ab 쌍에 대해 a <C b, a =C b, a >C b 중 정확히 하나가 참임을 함의한다.
  • comparator(a, b)를 호출해도 objobj의 프로토타입 체인상의 어떤 객체도 변경하지 않는다.
  • a =C a (반사성)
  • a =C b이면, b =C a (대칭성)
  • a =C b이고 b =C c이면, a =C c (=C의 추이성)
  • a <C b이고 b <C c이면, a <C c (<C의 추이성)
  • a >C b이고 b >C c이면, a >C c (>C의 추이성)
Note

위 조건들은 comparator가 집합 values를 동치류로 나누고 그 동치류들이 전순서화됨을 보장하기 위한 필요충분조건이다.

23.1.3.30.2 CompareArrayElements ( x, y, comparator )

The abstract operation CompareArrayElements takes arguments x (an ECMAScript language value), y (an ECMAScript language value), and comparator (a function object or undefined) and returns either a normal completion containing a Number or an abrupt completion. It performs the following steps when called:

  1. xundefined이고 yundefined이면, +0𝔽을 반환한다.
  2. xundefined이면, 1𝔽을 반환한다.
  3. yundefined이면, -1𝔽을 반환한다.
  4. comparatorundefined가 아니면,
    1. result를 ? ToNumber(? Call(comparator, undefined, « x, y »))라고 하자.
    2. resultNaN이면, +0𝔽을 반환한다.
    3. result를 반환한다.
  5. xString을 ? ToString(x)라고 하자.
  6. yString을 ? ToString(y)라고 하자.
  7. xSmaller를 ! IsLessThan(xString, yString, true)라고 하자.
  8. xSmallertrue이면, -1𝔽을 반환한다.
  9. ySmaller를 ! IsLessThan(yString, xString, true)라고 하자.
  10. ySmallertrue이면, 1𝔽을 반환한다.
  11. +0𝔽을 반환한다.

23.1.3.31 Array.prototype.splice ( start, deleteCount, ...items )

Note 1

이 메서드는 정수 인덱스 start에서 시작하는 배열의 deleteCount개 요소를 삭제하고, 이를 items의 요소들로 대체한다. 삭제된 요소들을 포함하는 Array를 반환한다(있는 경우).

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. obj를 ? ToObject(this value)라고 하자.
  2. len을 ? LengthOfArrayLike(obj)라고 하자.
  3. relativeStart를 ? ToIntegerOrInfinity(start)라고 하자.
  4. relativeStart = -∞이면, actualStart를 0이라고 하자.
  5. 그렇지 않고 relativeStart < 0이면, actualStartmax(len + relativeStart, 0)이라고 하자.
  6. 그렇지 않으면, actualStartmin(relativeStart, len)이라고 하자.
  7. itemCountitems의 요소 개수라고 하자.
  8. start가 존재하지 않으면,
    1. actualDeleteCount를 0이라고 하자.
  9. 그렇지 않고 deleteCount가 존재하지 않으면,
    1. actualDeleteCountlen - actualStart라고 하자.
  10. 그렇지 않으면,
    1. dc를 ? ToIntegerOrInfinity(deleteCount)라고 하자.
    2. actualDeleteCountdc를 0과 len - actualStart 사이로 클램프한 결과라고 하자.
  11. len + itemCount - actualDeleteCount > 253 - 1이면, TypeError 예외를 던진다.
  12. deletedArray를 ? ArraySpeciesCreate(obj, actualDeleteCount)라고 하자.
  13. k를 0이라고 하자.
  14. k < actualDeleteCount인 동안 반복한다,
    1. from을 ! ToString(𝔽(actualStart + k))라고 하자.
    2. HasProperty(obj, from)가 true이면,
      1. fromValue를 ? Get(obj, from)라고 하자.
      2. CreateDataPropertyOrThrow(deletedArray, ! ToString(𝔽(k)), fromValue)를 수행한다.
    3. kk + 1로 설정한다.
  15. Set(deletedArray, "length", 𝔽(actualDeleteCount), true)를 수행한다.
  16. itemCount < actualDeleteCount이면,
    1. kactualStart로 설정한다.
    2. k < (len - actualDeleteCount)인 동안 반복한다,
      1. from을 ! ToString(𝔽(k + actualDeleteCount))라고 하자.
      2. to를 ! ToString(𝔽(k + itemCount))라고 하자.
      3. HasProperty(obj, from)가 true이면,
        1. fromValue를 ? Get(obj, from)라고 하자.
        2. Set(obj, to, fromValue, true)를 수행한다.
      4. 그렇지 않으면,
        1. DeletePropertyOrThrow(obj, to)를 수행한다.
      5. kk + 1로 설정한다.
    3. klen으로 설정한다.
    4. k > (len - actualDeleteCount + itemCount)인 동안 반복한다,
      1. DeletePropertyOrThrow(obj, ! ToString(𝔽(k - 1)))를 수행한다.
      2. kk - 1로 설정한다.
  17. 그렇지 않고 itemCount > actualDeleteCount이면,
    1. k를 (len - actualDeleteCount)로 설정한다.
    2. k > actualStart인 동안 반복한다,
      1. from을 ! ToString(𝔽(k + actualDeleteCount - 1))라고 하자.
      2. to를 ! ToString(𝔽(k + itemCount - 1))라고 하자.
      3. HasProperty(obj, from)가 true이면,
        1. fromValue를 ? Get(obj, from)라고 하자.
        2. Set(obj, to, fromValue, true)를 수행한다.
      4. 그렇지 않으면,
        1. DeletePropertyOrThrow(obj, to)를 수행한다.
      5. kk - 1로 설정한다.
  18. kactualStart로 설정한다.
  19. items의 각 요소 item에 대해, 다음을 수행한다.
    1. Set(obj, ! ToString(𝔽(k)), item, true)를 수행한다.
    2. kk + 1로 설정한다.
  20. Set(obj, "length", 𝔽(len - actualDeleteCount + itemCount), true)를 수행한다.
  21. deletedArray를 반환한다.
Note 2

단계 1520에서 "length" 속성을 명시적으로 설정하는 것은 객체들이 내장 Array가 아닐 때도 길이가 올바르도록 보장하기 위한 것이다.

Note 3

이 메서드는 의도적으로 제네릭이다; 이 메서드는 자신의 this 값이 Array일 것을 요구하지 않는다. 따라서 메서드로 사용하기 위해 다른 종류의 객체로 이전될 수 있다.

23.1.3.32 Array.prototype.toLocaleString ( [ reserved1 [ , reserved2 ] ] )

ECMA-402 국제화 API를 포함하는 ECMAScript 구현은 ECMA-402 명세에 지정된 대로 이 메서드를 구현해야 한다. ECMAScript 구현이 ECMA-402 API를 포함하지 않는 경우 이 메서드에 대한 다음 명세가 사용된다.

Note 1

ECMA-402의 초판은 이 메서드에 대한 대체 명세를 포함하지 않았다.

이 메서드의 선택적 매개변수의 의미는 ECMA-402 명세에 정의되어 있다; ECMA-402 지원을 포함하지 않는 구현은 그 매개변수 위치를 다른 어떤 용도로도 사용해서는 안 된다.

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. array를 ? ToObject(this value)라고 하자.
  2. len을 ? LengthOfArrayLike(array)라고 하자.
  3. separator호스트 환경의 현재 로캘에 적절한 구현 정의 list-separator String 값(예: ", ")이라고 하자.
  4. result를 빈 String이라고 하자.
  5. k를 0이라고 하자.
  6. k < len인 동안 반복한다,
    1. k > 0이면, resultresultseparator의 문자열 연결로 설정한다.
    2. element를 ? Get(array, ! ToString(𝔽(k)))라고 하자.
    3. elementundefined도 아니고 null도 아니면,
      1. elementStr을 ? ToString(? Invoke(element, "toLocaleString"))라고 하자.
      2. resultresultelementStr의 문자열 연결로 설정한다.
    4. kk + 1로 설정한다.
  7. result를 반환한다.
Note 2

이 메서드는 배열의 요소들을 그들의 toLocaleString 메서드를 사용해 String으로 변환한 뒤, 구현 정의 로캘 민감 구분자 String의 출현으로 구분하여 이 String들을 연결한다. 이 메서드는 toString과 유사하지만, 호스트 환경의 현재 로캘 관례에 대응하는 로캘 민감 결과를 산출하도록 의도되어 있다는 점이 다르다.

Note 3

이 메서드는 의도적으로 제네릭이다; 이 메서드는 자신의 this 값이 Array일 것을 요구하지 않는다. 따라서 메서드로 사용하기 위해 다른 종류의 객체로 이전될 수 있다.

23.1.3.33 Array.prototype.toReversed ( )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. obj를 ? ToObject(this value)라고 하자.
  2. len을 ? LengthOfArrayLike(obj)라고 하자.
  3. array를 ? ArrayCreate(len)라고 하자.
  4. k를 0이라고 하자.
  5. k < len인 동안 반복한다,
    1. from을 ! ToString(𝔽(len - k - 1))라고 하자.
    2. propertyKey를 ! ToString(𝔽(k))라고 하자.
    3. fromValue를 ? Get(obj, from)라고 하자.
    4. CreateDataPropertyOrThrow(array, propertyKey, fromValue)를 수행한다.
    5. kk + 1로 설정한다.
  6. array를 반환한다.

23.1.3.34 Array.prototype.toSorted ( comparator )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. comparatorundefined가 아니고 IsCallable(comparator)가 false이면, TypeError 예외를 던진다.
  2. obj를 ? ToObject(this value)라고 하자.
  3. len을 ? LengthOfArrayLike(obj)라고 하자.
  4. array를 ? ArrayCreate(len)라고 하자.
  5. sortComparecomparator를 캡처하고 호출될 때 다음 단계를 수행하는, 매개변수 (x, y)를 가진 새로운 Abstract Closure라고 하자:
    1. CompareArrayElements(x, y, comparator)를 반환한다.
  6. sortedList를 ? SortIndexedProperties(obj, len, sortCompare, read-through-holes)라고 하자.
  7. j를 0이라고 하자.
  8. j < len인 동안 반복한다,
    1. CreateDataPropertyOrThrow(array, ! ToString(𝔽(j)), sortedList[j])를 수행한다.
    2. jj + 1로 설정한다.
  9. array를 반환한다.

23.1.3.35 Array.prototype.toSpliced ( start, skipCount, ...items )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. obj를 ? ToObject(this value)라고 하자.
  2. len을 ? LengthOfArrayLike(obj)라고 하자.
  3. relativeStart를 ? ToIntegerOrInfinity(start)라고 하자.
  4. relativeStart = -∞이면, actualStart를 0이라고 하자.
  5. 그렇지 않고 relativeStart < 0이면, actualStartmax(len + relativeStart, 0)이라고 하자.
  6. 그렇지 않으면, actualStartmin(relativeStart, len)이라고 하자.
  7. insertCountitems의 요소 개수라고 하자.
  8. start가 존재하지 않으면,
    1. actualSkipCount를 0이라고 하자.
  9. 그렇지 않고 skipCount가 존재하지 않으면,
    1. actualSkipCountlen - actualStart라고 하자.
  10. 그렇지 않으면,
    1. sc를 ? ToIntegerOrInfinity(skipCount)라고 하자.
    2. actualSkipCountsc를 0과 len - actualStart 사이로 클램프한 결과라고 하자.
  11. newLenlen + insertCount - actualSkipCount라고 하자.
  12. newLen > 253 - 1이면, TypeError 예외를 던진다.
  13. newArray를 ? ArrayCreate(newLen)라고 하자.
  14. writeIndex를 0이라고 하자.
  15. readIndexactualStart + actualSkipCount라고 하자.
  16. writeIndex < actualStart인 동안 반복한다,
    1. propertyKey를 ! ToString(𝔽(writeIndex))라고 하자.
    2. iValue를 ? Get(obj, propertyKey)라고 하자.
    3. CreateDataPropertyOrThrow(newArray, propertyKey, iValue)를 수행한다.
    4. writeIndexwriteIndex + 1로 설정한다.
  17. items의 각 요소 item에 대해, 다음을 수행한다.
    1. propertyKey를 ! ToString(𝔽(writeIndex))라고 하자.
    2. CreateDataPropertyOrThrow(newArray, propertyKey, item)를 수행한다.
    3. writeIndexwriteIndex + 1로 설정한다.
  18. writeIndex < newLen인 동안 반복한다,
    1. propertyKey를 ! ToString(𝔽(writeIndex))라고 하자.
    2. from을 ! ToString(𝔽(readIndex))라고 하자.
    3. fromValue를 ? Get(obj, from)라고 하자.
    4. CreateDataPropertyOrThrow(newArray, propertyKey, fromValue)를 수행한다.
    5. writeIndexwriteIndex + 1로 설정한다.
    6. readIndexreadIndex + 1로 설정한다.
  19. newArray를 반환한다.

23.1.3.36 Array.prototype.toString ( )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. array를 ? ToObject(this value)라고 하자.
  2. func를 ? Get(array, "join")라고 하자.
  3. IsCallable(func)가 false이면, func를 내재 함수 %Object.prototype.toString%으로 설정한다.
  4. Call(func, array)를 반환한다.
Note

이 메서드는 의도적으로 제네릭이다; 이 메서드는 자신의 this 값이 Array일 것을 요구하지 않는다. 따라서 메서드로 사용하기 위해 다른 종류의 객체로 이전될 수 있다.

23.1.3.37 Array.prototype.unshift ( ...items )

이 메서드는 인자들을 배열의 시작 부분에 앞에 붙이며, 배열 안에서 그 순서는 인자 목록에 나타난 순서와 같다.

호출될 때 다음 단계를 수행한다:

  1. obj를 ? ToObject(this value)라고 하자.
  2. len을 ? LengthOfArrayLike(obj)라고 하자.
  3. argCountitems의 요소 개수라고 하자.
  4. argCount > 0이면,
    1. len + argCount > 253 - 1이면, TypeError 예외를 던진다.
    2. klen이라고 하자.
    3. k > 0인 동안 반복한다,
      1. from을 ! ToString(𝔽(k - 1))라고 하자.
      2. to를 ! ToString(𝔽(k + argCount - 1))라고 하자.
      3. fromPresent를 ? HasProperty(obj, from)라고 하자.
      4. fromPresenttrue이면,
        1. fromValue를 ? Get(obj, from)라고 하자.
        2. Set(obj, to, fromValue, true)를 수행한다.
      5. 그렇지 않으면,
        1. Assert: fromPresentfalse이다.
        2. DeletePropertyOrThrow(obj, to)를 수행한다.
      6. kk - 1로 설정한다.
    4. j+0𝔽이라고 하자.
    5. items의 각 요소 item에 대해, 다음을 수행한다.
      1. Set(obj, ! ToString(j), item, true)를 수행한다.
      2. jj + 1𝔽로 설정한다.
  5. Set(obj, "length", 𝔽(len + argCount), true)를 수행한다.
  6. 𝔽(len + argCount)를 반환한다.

이 메서드의 "length" 속성은 1𝔽이다.

Note

이 메서드는 의도적으로 제네릭이다; 이 메서드는 자신의 this 값이 Array일 것을 요구하지 않는다. 따라서 메서드로 사용하기 위해 다른 종류의 객체로 이전될 수 있다.

23.1.3.38 Array.prototype.values ( )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. obj를 ? ToObject(this value)라고 하자.
  2. CreateArrayIterator(obj, value)를 반환한다.

23.1.3.39 Array.prototype.with ( index, value )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. obj를 ? ToObject(this value)라고 하자.
  2. len을 ? LengthOfArrayLike(obj)라고 하자.
  3. relativeIndex를 ? ToIntegerOrInfinity(index)라고 하자.
  4. relativeIndex ≥ 0이면, actualIndexrelativeIndex라고 하자.
  5. 그렇지 않으면, actualIndexlen + relativeIndex라고 하자.
  6. actualIndexlen이거나 actualIndex < 0이면, RangeError 예외를 던진다.
  7. array를 ? ArrayCreate(len)라고 하자.
  8. k를 0이라고 하자.
  9. k < len인 동안 반복한다,
    1. propertyKey를 ! ToString(𝔽(k))라고 하자.
    2. k = actualIndex이면 fromValuevalue라고 하자.
    3. 그렇지 않으면, fromValue를 ? Get(obj, propertyKey)라고 하자.
    4. CreateDataPropertyOrThrow(array, propertyKey, fromValue)를 수행한다.
    5. kk + 1로 설정한다.
  10. array를 반환한다.

23.1.3.40 Array.prototype [ %Symbol.iterator% ] ( )

%Symbol.iterator% 속성의 초기값은 23.1.3.38에 정의된 %Array.prototype.values%이다.

23.1.3.41 Array.prototype [ %Symbol.unscopables% ]

%Symbol.unscopables% 데이터 속성의 초기값은 다음 단계들로 생성된 객체이다:

  1. unscopableListOrdinaryObjectCreate(null)라고 하자.
  2. CreateDataPropertyOrThrow(unscopableList, "at", true)를 수행한다.
  3. CreateDataPropertyOrThrow(unscopableList, "copyWithin", true)를 수행한다.
  4. CreateDataPropertyOrThrow(unscopableList, "entries", true)를 수행한다.
  5. CreateDataPropertyOrThrow(unscopableList, "fill", true)를 수행한다.
  6. CreateDataPropertyOrThrow(unscopableList, "find", true)를 수행한다.
  7. CreateDataPropertyOrThrow(unscopableList, "findIndex", true)를 수행한다.
  8. CreateDataPropertyOrThrow(unscopableList, "findLast", true)를 수행한다.
  9. CreateDataPropertyOrThrow(unscopableList, "findLastIndex", true)를 수행한다.
  10. CreateDataPropertyOrThrow(unscopableList, "flat", true)를 수행한다.
  11. CreateDataPropertyOrThrow(unscopableList, "flatMap", true)를 수행한다.
  12. CreateDataPropertyOrThrow(unscopableList, "includes", true)를 수행한다.
  13. CreateDataPropertyOrThrow(unscopableList, "keys", true)를 수행한다.
  14. CreateDataPropertyOrThrow(unscopableList, "toReversed", true)를 수행한다.
  15. CreateDataPropertyOrThrow(unscopableList, "toSorted", true)를 수행한다.
  16. CreateDataPropertyOrThrow(unscopableList, "toSpliced", true)를 수행한다.
  17. CreateDataPropertyOrThrow(unscopableList, "values", true)를 수행한다.
  18. unscopableList를 반환한다.

이 속성은 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true } 속성 특성을 가진다.

Note

이 객체의 자기 자신의 속성 이름들은 ECMAScript 2015 명세 이전에는 Array.prototype의 표준 속성으로 포함되지 않았던 속성 이름들이다. 이러한 이름들은, 이 이름들 중 하나를 외부 스코프의 바인딩으로 사용하고 그 바인딩이 바인딩 객체가 Array인 with 문에 의해 가려질 수 있는 기존 코드의 동작을 보존하기 위해, with 문 바인딩 목적상 무시된다.

"with"unscopableList에 포함되지 않는 이유는 이미 reserved word이기 때문이다.

23.1.4 Array 인스턴스의 속성

Array 인스턴스는 Array 특수 객체이며 그러한 객체에 대해 지정된 내부 메서드를 가진다. Array 인스턴스는 Array 프로토타입 객체로부터 속성을 상속한다.

Array 인스턴스는 "length" 속성과, 배열 인덱스 이름을 가진 열거 가능한 속성들의 집합을 가진다.

23.1.4.1 length

Array 인스턴스의 "length" 속성은 그 값이 배열 인덱스인 이름을 가진 모든 configurable 자기 자신의 속성 이름보다 항상 수치적으로 큰 데이터 속성이다.

"length" 속성은 처음에 { [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false } 속성 특성을 가진다.

Note

"length" 속성의 값을 줄이면, 배열 인덱스가 이전 길이 값과 새 길이 값 사이에 있는 자기 자신의 배열 요소가 삭제되는 부수 효과가 있다. 그러나 non-configurable 속성은 삭제될 수 없다. Array의 "length" 속성을 배열의 기존 non-configurable array-indexed 속성 중 가장 큰 수치 자기 자신의 속성 이름보다 작거나 같은 수치 값으로 설정하려고 하면, 길이는 그 non-configurable 수치 자기 자신의 속성 이름보다 1 큰 수치 값으로 설정된다. 10.4.2.1를 보라.

23.1.5 Array Iterator 객체

Array Iterator는 어떤 특정 Array 인스턴스 객체에 대한 특정 반복을 나타내는 객체이다. Array Iterator 객체에는 이름 있는 생성자가 없다. 대신, Array Iterator 객체는 Array 인스턴스 객체의 특정 메서드를 호출하여 생성된다.

23.1.5.1 CreateArrayIterator ( array, kind )

The abstract operation CreateArrayIterator takes arguments array (an Object) and kind (key+value, key, or value) and returns an Object. 이 연산은 그러한 반복자를 반환하는 Array 메서드를 위한 반복자 객체를 생성하는 데 사용된다. It performs the following steps when called:

  1. iteratorOrdinaryObjectCreate(%ArrayIteratorPrototype%, « [[IteratedArrayLike]], [[ArrayLikeNextIndex]], [[ArrayLikeIterationKind]] »)라고 하자.
  2. iterator.[[IteratedArrayLike]]array로 설정한다.
  3. iterator.[[ArrayLikeNextIndex]]를 0으로 설정한다.
  4. iterator.[[ArrayLikeIterationKind]]kind로 설정한다.
  5. iterator를 반환한다.

23.1.5.2 %ArrayIteratorPrototype% 객체

%ArrayIteratorPrototype% 객체는:

  • 모든 Array Iterator 객체가 상속하는 속성들을 가진다.
  • 보통 객체이다.
  • 값이 %Iterator.prototype%[[Prototype]] 내부 슬롯을 가진다.
  • 다음 속성들을 가진다:

23.1.5.2.1 %ArrayIteratorPrototype%.next ( )

  1. iteratorObjthis 값이라고 하자.
  2. iteratorObj가 Object가 아니면, TypeError 예외를 던진다.
  3. iteratorObjArray Iterator Instance의 모든 내부 슬롯(23.1.5.3)을 가지지 않으면, TypeError 예외를 던진다.
  4. arrayiteratorObj.[[IteratedArrayLike]]라고 하자.
  5. arrayundefined이면, CreateIteratorResultObject(undefined, true)를 반환한다.
  6. indexiteratorObj.[[ArrayLikeNextIndex]]라고 하자.
  7. kinditeratorObj.[[ArrayLikeIterationKind]]라고 하자.
  8. array[[TypedArrayName]] 내부 슬롯을 가지면,
    1. taRecordMakeTypedArrayWithBufferWitnessRecord(array, seq-cst)라고 하자.
    2. IsTypedArrayOutOfBounds(taRecord)가 true이면, TypeError 예외를 던진다.
    3. lenTypedArrayLength(taRecord)라고 하자.
  9. 그렇지 않으면,
    1. len을 ? LengthOfArrayLike(array)라고 하자.
  10. indexlen이면,
    1. iteratorObj.[[IteratedArrayLike]]undefined로 설정한다.
    2. CreateIteratorResultObject(undefined, true)를 반환한다.
  11. iteratorObj.[[ArrayLikeNextIndex]]index + 1로 설정한다.
  12. indexNumber𝔽(index)라고 하자.
  13. kindkey이면,
    1. resultindexNumber라고 하자.
  14. 그렇지 않으면,
    1. elementKey를 ! ToString(indexNumber)라고 하자.
    2. elementValue를 ? Get(array, elementKey)라고 하자.
    3. kindvalue이면,
      1. resultelementValue라고 하자.
    4. 그렇지 않으면,
      1. Assert: kindkey+value이다.
      2. resultCreateArrayFromListindexNumber, elementValue »)라고 하자.
  15. CreateIteratorResultObject(result, false)를 반환한다.

23.1.5.2.2 %ArrayIteratorPrototype% [ %Symbol.toStringTag% ]

%Symbol.toStringTag% 속성의 초기값은 String 값 "Array Iterator"이다.

이 속성은 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true } 속성 특성을 가진다.

23.1.5.3 Array Iterator 인스턴스의 속성

Array Iterator 인스턴스는 %ArrayIteratorPrototype% 내재 객체로부터 속성을 상속하는 보통 객체이다. Array Iterator 인스턴스는 처음에 Table 69에 나열된 내부 슬롯을 가지고 생성된다.

Table 69: Array Iterator 인스턴스의 내부 슬롯
내부 슬롯 타입 설명
[[IteratedArrayLike]] Object 또는 undefined 반복되고 있는 배열 유사 객체.
[[ArrayLikeNextIndex]] 음이 아닌 정수 이 반복자가 다음에 검사할 요소의 정수 인덱스.
[[ArrayLikeIterationKind]] key+value, key, 또는 value 반복의 각 요소에 대해 무엇이 반환되는지 식별하는 값.

23.2 TypedArray 객체

TypedArray는 기반 바이너리 데이터 버퍼(25.1)의 배열 유사 뷰를 제공한다. TypedArray 요소 타입TypedArray 인스턴스의 모든 요소가 가지는 기반 바이너리 스칼라 데이터 타입이다. 지원되는 각 요소 타입마다 Table 70에 나열된 서로 다른 TypedArray 생성자가 있다. Table 70의 각 생성자는 대응하는 서로 다른 프로토타입 객체를 가진다.

Table 70: 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 생성자의 추상 슈퍼클래스처럼 동작한다.
  • 추상 클래스 생성자이므로 호출되면 오류를 던진다. 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. constructorthis 값이라고 하자.
  2. IsConstructor(constructor)가 false이면, TypeError 예외를 던진다.
  3. mapperundefined이면,
    1. mappingfalse라고 하자.
  4. 그렇지 않으면,
    1. IsCallable(mapper)가 false이면, TypeError 예외를 던진다.
    2. mappingtrue라고 하자.
  5. usingIterator를 ? GetMethod(source, %Symbol.iterator%)라고 하자.
  6. usingIteratorundefined가 아니면,
    1. values를 ? IteratorToList(? GetIteratorFromMethod(source, usingIterator))라고 하자.
    2. lenvalues의 요소 개수라고 하자.
    3. targetObj를 ? TypedArrayCreateFromConstructor(constructor, « 𝔽(len) »)라고 하자.
    4. k를 0이라고 하자.
    5. k < len인 동안 반복한다,
      1. propertyKey를 ! ToString(𝔽(k))라고 하자.
      2. kValuevalues의 첫 번째 요소라고 하자.
      3. values에서 첫 번째 요소를 제거한다.
      4. mappingtrue이면,
        1. mappedValue를 ? Call(mapper, thisArg, « kValue, 𝔽(k) »)라고 하자.
      5. 그렇지 않으면,
        1. mappedValuekValue라고 하자.
      6. Set(targetObj, propertyKey, mappedValue, true)를 수행한다.
      7. kk + 1로 설정한다.
    6. Assert: values는 이제 빈 List이다.
    7. targetObj를 반환한다.
  7. NOTE: source는 반복 가능 객체가 아니므로, 이미 배열 유사 객체라고 가정한다.
  8. arrayLike를 ! ToObject(source)라고 하자.
  9. len을 ? LengthOfArrayLike(arrayLike)라고 하자.
  10. targetObj를 ? TypedArrayCreateFromConstructor(constructor, « 𝔽(len) »)라고 하자.
  11. k를 0이라고 하자.
  12. k < len인 동안 반복한다,
    1. propertyKey를 ! ToString(𝔽(k))라고 하자.
    2. kValue를 ? Get(arrayLike, propertyKey)라고 하자.
    3. mappingtrue이면,
      1. mappedValue를 ? Call(mapper, thisArg, « kValue, 𝔽(k) »)라고 하자.
    4. 그렇지 않으면,
      1. mappedValuekValue라고 하자.
    5. Set(targetObj, propertyKey, mappedValue, true)를 수행한다.
    6. kk + 1로 설정한다.
  13. targetObj를 반환한다.

23.2.2.2 %TypedArray%.of ( ...items )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. lenitems의 요소 개수라고 하자.
  2. constructorthis 값이라고 하자.
  3. IsConstructor(constructor)가 false이면, TypeError 예외를 던진다.
  4. newObj를 ? TypedArrayCreateFromConstructor(constructor, « 𝔽(len) »)라고 하자.
  5. k를 0이라고 하자.
  6. k < len인 동안 반복한다,
    1. kValueitems[k]라고 하자.
    2. propertyKey를 ! ToString(𝔽(k))라고 하자.
    3. Set(newObj, propertyKey, kValue, true)를 수행한다.
    4. kk + 1로 설정한다.
  7. newObj를 반환한다.

23.2.2.3 %TypedArray%.prototype

%TypedArray%.prototype의 초기값은 %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. objthis 값이라고 하자.
  2. taRecord를 ? ValidateTypedArray(obj, seq-cst)라고 하자.
  3. lenTypedArrayLength(taRecord)라고 하자.
  4. relativeIndex를 ? ToIntegerOrInfinity(index)라고 하자.
  5. relativeIndex ≥ 0이면,
    1. krelativeIndex라고 하자.
  6. 그렇지 않으면,
    1. klen + relativeIndex라고 하자.
  7. k < 0이거나 klen이면, undefined를 반환한다.
  8. Get(obj, ! ToString(𝔽(k)))를 반환한다.

23.2.3.2 get %TypedArray%.prototype.buffer

%TypedArray%.prototype.buffer는 set 접근자 함수가 undefined인 접근자 속성이다. 그 get 접근자 함수는 호출될 때 다음 단계를 수행한다:

  1. objthis 값이라고 하자.
  2. RequireInternalSlot(obj, [[TypedArrayName]])를 수행한다.
  3. Assert: obj[[ViewedArrayBuffer]] 내부 슬롯을 가진다.
  4. bufferobj.[[ViewedArrayBuffer]]라고 하자.
  5. buffer를 반환한다.

23.2.3.3 get %TypedArray%.prototype.byteLength

%TypedArray%.prototype.byteLength는 set 접근자 함수가 undefined인 접근자 속성이다. 그 get 접근자 함수는 호출될 때 다음 단계를 수행한다:

  1. objthis 값이라고 하자.
  2. RequireInternalSlot(obj, [[TypedArrayName]])를 수행한다.
  3. Assert: obj[[ViewedArrayBuffer]] 내부 슬롯을 가진다.
  4. taRecordMakeTypedArrayWithBufferWitnessRecord(obj, seq-cst)라고 하자.
  5. IsTypedArrayOutOfBounds(taRecord)가 true이면, +0𝔽을 반환한다.
  6. sizeTypedArrayByteLength(taRecord)라고 하자.
  7. 𝔽(size)를 반환한다.

23.2.3.4 get %TypedArray%.prototype.byteOffset

%TypedArray%.prototype.byteOffset는 set 접근자 함수가 undefined인 접근자 속성이다. 그 get 접근자 함수는 호출될 때 다음 단계를 수행한다:

  1. objthis 값이라고 하자.
  2. RequireInternalSlot(obj, [[TypedArrayName]])를 수행한다.
  3. Assert: obj[[ViewedArrayBuffer]] 내부 슬롯을 가진다.
  4. taRecordMakeTypedArrayWithBufferWitnessRecord(obj, seq-cst)라고 하자.
  5. IsTypedArrayOutOfBounds(taRecord)가 true이면, +0𝔽을 반환한다.
  6. offsetobj.[[ByteOffset]]이라고 하자.
  7. 𝔽(offset)을 반환한다.

23.2.3.5 %TypedArray%.prototype.constructor

%TypedArray%.prototype.constructor의 초기값은 %TypedArray%이다.

23.2.3.6 %TypedArray%.prototype.copyWithin ( target, start [ , end ] )

이 메서드의 인자 해석과 사용은 23.1.3.4에 정의된 Array.prototype.copyWithin의 경우와 같다.

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. objthis 값이라고 하자.
  2. taRecord를 ? ValidateTypedArray(obj, seq-cst)라고 하자.
  3. lenTypedArrayLength(taRecord)라고 하자.
  4. relativeTarget을 ? ToIntegerOrInfinity(target)이라고 하자.
  5. relativeTarget = -∞이면, targetIndex를 0이라고 하자.
  6. 그렇지 않고 relativeTarget < 0이면, targetIndexmax(len + relativeTarget, 0)이라고 하자.
  7. 그렇지 않으면, targetIndexmin(relativeTarget, len)이라고 하자.
  8. relativeStart를 ? ToIntegerOrInfinity(start)라고 하자.
  9. relativeStart = -∞이면, startIndex를 0이라고 하자.
  10. 그렇지 않고 relativeStart < 0이면, startIndexmax(len + relativeStart, 0)이라고 하자.
  11. 그렇지 않으면, startIndexmin(relativeStart, len)이라고 하자.
  12. endundefined이면 relativeEndlen이라고 하자; 그렇지 않으면 relativeEnd를 ? ToIntegerOrInfinity(end)라고 하자.
  13. relativeEnd = -∞이면, endIndex를 0이라고 하자.
  14. 그렇지 않고 relativeEnd < 0이면, endIndexmax(len + relativeEnd, 0)이라고 하자.
  15. 그렇지 않으면, endIndexmin(relativeEnd, len)이라고 하자.
  16. countmin(endIndex - startIndex, len - targetIndex)라고 하자.
  17. count > 0이면,
    1. NOTE: 복사는 소스 데이터의 비트 수준 인코딩을 보존하는 방식으로 수행되어야 한다.
    2. bufferobj.[[ViewedArrayBuffer]]라고 하자.
    3. taRecordMakeTypedArrayWithBufferWitnessRecord(obj, seq-cst)로 설정한다.
    4. IsTypedArrayOutOfBounds(taRecord)가 true이면, TypeError 예외를 던진다.
    5. lenTypedArrayLength(taRecord)로 설정한다.
    6. NOTE: 위 단계들의 부수 효과로 obj의 크기가 줄어들었을 수 있으며, 이 경우 복사는 여전히 적용 가능한 가장 긴 접두부로 진행되어야 한다.
    7. countmin(count, len - startIndex, len - targetIndex)로 설정한다.
    8. elementSizeTypedArrayElementSize(obj)라고 하자.
    9. byteOffsetobj.[[ByteOffset]]이라고 하자.
    10. toByteIndex를 (targetIndex × elementSize) + byteOffset이라고 하자.
    11. fromByteIndex를 (startIndex × elementSize) + byteOffset이라고 하자.
    12. countBytescount × elementSize라고 하자.
    13. fromByteIndex < toByteIndex이고 toByteIndex < fromByteIndex + countBytes이면,
      1. direction을 -1이라고 하자.
      2. fromByteIndexfromByteIndex + countBytes - 1로 설정한다.
      3. toByteIndextoByteIndex + countBytes - 1로 설정한다.
    14. 그렇지 않으면,
      1. direction을 1이라고 하자.
    15. countBytes > 0인 동안 반복한다,
      1. valueGetValueFromBuffer(buffer, fromByteIndex, uint8, true, unordered)라고 하자.
      2. SetValueInBuffer(buffer, toByteIndex, uint8, value, true, unordered)를 수행한다.
      3. fromByteIndexfromByteIndex + direction으로 설정한다.
      4. toByteIndextoByteIndex + direction으로 설정한다.
      5. countBytescountBytes - 1로 설정한다.
  18. obj를 반환한다.

23.2.3.7 %TypedArray%.prototype.entries ( )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. objthis 값이라고 하자.
  2. ValidateTypedArray(obj, seq-cst)를 수행한다.
  3. CreateArrayIterator(obj, key+value)를 반환한다.

23.2.3.8 %TypedArray%.prototype.every ( callback [ , thisArg ] )

이 메서드의 인자 해석과 사용은 23.1.3.6에 정의된 Array.prototype.every의 경우와 같다.

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. objthis 값이라고 하자.
  2. taRecord를 ? ValidateTypedArray(obj, seq-cst)라고 하자.
  3. lenTypedArrayLength(taRecord)라고 하자.
  4. IsCallable(callback)가 false이면, TypeError 예외를 던진다.
  5. k를 0이라고 하자.
  6. k < len인 동안 반복한다,
    1. propertyKey를 ! ToString(𝔽(k))라고 하자.
    2. kValue를 ! Get(obj, propertyKey)라고 하자.
    3. testResultToBoolean(? Call(callback, thisArg, « kValue, 𝔽(k), obj »))라고 하자.
    4. testResultfalse이면, false를 반환한다.
    5. kk + 1로 설정한다.
  7. true를 반환한다.

이 메서드는 제네릭이 아니다. this 값은 [[TypedArrayName]] 내부 슬롯을 가진 객체여야 한다.

23.2.3.9 %TypedArray%.prototype.fill ( value [ , start [ , end ] ] )

이 메서드의 인자 해석과 사용은 23.1.3.7에 정의된 Array.prototype.fill의 경우와 같다.

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. objthis 값이라고 하자.
  2. taRecord를 ? ValidateTypedArray(obj, seq-cst)라고 하자.
  3. lenTypedArrayLength(taRecord)라고 하자.
  4. obj.[[ContentType]]bigint이면, value를 ? ToBigInt(value)로 설정한다.
  5. 그렇지 않으면, value를 ? ToNumber(value)로 설정한다.
  6. relativeStart를 ? ToIntegerOrInfinity(start)라고 하자.
  7. relativeStart = -∞이면, startIndex를 0이라고 하자.
  8. 그렇지 않고 relativeStart < 0이면, startIndexmax(len + relativeStart, 0)이라고 하자.
  9. 그렇지 않으면, startIndexmin(relativeStart, len)이라고 하자.
  10. endundefined이면 relativeEndlen이라고 하자; 그렇지 않으면 relativeEnd를 ? ToIntegerOrInfinity(end)라고 하자.
  11. relativeEnd = -∞이면, endIndex를 0이라고 하자.
  12. 그렇지 않고 relativeEnd < 0이면, endIndexmax(len + relativeEnd, 0)이라고 하자.
  13. 그렇지 않으면, endIndexmin(relativeEnd, len)이라고 하자.
  14. taRecordMakeTypedArrayWithBufferWitnessRecord(obj, seq-cst)로 설정한다.
  15. IsTypedArrayOutOfBounds(taRecord)가 true이면, TypeError 예외를 던진다.
  16. lenTypedArrayLength(taRecord)로 설정한다.
  17. endIndexmin(endIndex, len)로 설정한다.
  18. kstartIndex라고 하자.
  19. k < endIndex인 동안 반복한다,
    1. propertyKey를 ! ToString(𝔽(k))라고 하자.
    2. Set(obj, propertyKey, value, true)를 수행한다.
    3. kk + 1로 설정한다.
  20. obj를 반환한다.

23.2.3.10 %TypedArray%.prototype.filter ( callback [ , thisArg ] )

이 메서드의 인자 해석과 사용은 23.1.3.8에 정의된 Array.prototype.filter의 경우와 같다.

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. objthis 값이라고 하자.
  2. taRecord를 ? ValidateTypedArray(obj, seq-cst)라고 하자.
  3. lenTypedArrayLength(taRecord)라고 하자.
  4. IsCallable(callback)가 false이면, TypeError 예외를 던진다.
  5. kept를 새로운 빈 List라고 하자.
  6. captured를 0이라고 하자.
  7. k를 0이라고 하자.
  8. k < len인 동안 반복한다,
    1. propertyKey를 ! ToString(𝔽(k))라고 하자.
    2. kValue를 ! Get(obj, propertyKey)라고 하자.
    3. selectedToBoolean(? Call(callback, thisArg, « kValue, 𝔽(k), obj »))라고 하자.
    4. selectedtrue이면,
      1. kValuekept에 추가한다.
      2. capturedcaptured + 1로 설정한다.
    5. kk + 1로 설정한다.
  9. resultTypedArray를 ? TypedArraySpeciesCreate(obj, « 𝔽(captured) »)라고 하자.
  10. n을 0이라고 하자.
  11. kept의 각 요소 e에 대해, 다음을 수행한다.
    1. Set(resultTypedArray, ! ToString(𝔽(n)), e, true)를 수행한다.
    2. nn + 1로 설정한다.
  12. resultTypedArray를 반환한다.

이 메서드는 제네릭이 아니다. this 값은 [[TypedArrayName]] 내부 슬롯을 가진 객체여야 한다.

23.2.3.11 %TypedArray%.prototype.find ( predicate [ , thisArg ] )

이 메서드의 인자 해석과 사용은 23.1.3.9에 정의된 Array.prototype.find의 경우와 같다.

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. objthis 값이라고 하자.
  2. taRecord를 ? ValidateTypedArray(obj, seq-cst)라고 하자.
  3. lenTypedArrayLength(taRecord)라고 하자.
  4. findRec를 ? FindViaPredicate(obj, 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. objthis 값이라고 하자.
  2. taRecord를 ? ValidateTypedArray(obj, seq-cst)라고 하자.
  3. lenTypedArrayLength(taRecord)라고 하자.
  4. findRec를 ? FindViaPredicate(obj, 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. objthis 값이라고 하자.
  2. taRecord를 ? ValidateTypedArray(obj, seq-cst)라고 하자.
  3. lenTypedArrayLength(taRecord)라고 하자.
  4. findRec를 ? FindViaPredicate(obj, 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. objthis 값이라고 하자.
  2. taRecord를 ? ValidateTypedArray(obj, seq-cst)라고 하자.
  3. lenTypedArrayLength(taRecord)라고 하자.
  4. findRec를 ? FindViaPredicate(obj, 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. objthis 값이라고 하자.
  2. taRecord를 ? ValidateTypedArray(obj, seq-cst)라고 하자.
  3. lenTypedArrayLength(taRecord)라고 하자.
  4. IsCallable(callback)가 false이면, TypeError 예외를 던진다.
  5. k를 0이라고 하자.
  6. k < len인 동안 반복한다,
    1. propertyKey를 ! ToString(𝔽(k))라고 하자.
    2. kValue를 ! Get(obj, propertyKey)라고 하자.
    3. Call(callback, thisArg, « kValue, 𝔽(k), obj »)를 수행한다.
    4. kk + 1로 설정한다.
  7. undefined를 반환한다.

이 메서드는 제네릭이 아니다. this 값은 [[TypedArrayName]] 내부 슬롯을 가진 객체여야 한다.

23.2.3.16 %TypedArray%.prototype.includes ( searchElement [ , fromIndex ] )

이 메서드의 인자 해석과 사용은 23.1.3.16에 정의된 Array.prototype.includes의 경우와 같다.

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. objthis 값이라고 하자.
  2. taRecord를 ? ValidateTypedArray(obj, seq-cst)라고 하자.
  3. lenTypedArrayLength(taRecord)라고 하자.
  4. len = 0이면, false를 반환한다.
  5. n을 ? ToIntegerOrInfinity(fromIndex)라고 하자.
  6. Assert: fromIndexundefined이면, n은 0이다.
  7. n = +∞이면, false를 반환한다.
  8. n = -∞이면, n을 0으로 설정한다.
  9. n ≥ 0이면,
    1. kn이라고 하자.
  10. 그렇지 않으면,
    1. klen + n이라고 하자.
    2. k < 0이면, k를 0으로 설정한다.
  11. k < len인 동안 반복한다,
    1. elementK를 ! Get(obj, ! ToString(𝔽(k)))라고 하자.
    2. SameValueZero(searchElement, elementK)가 true이면, true를 반환한다.
    3. kk + 1로 설정한다.
  12. false를 반환한다.

이 메서드는 제네릭이 아니다. this 값은 [[TypedArrayName]] 내부 슬롯을 가진 객체여야 한다.

23.2.3.17 %TypedArray%.prototype.indexOf ( searchElement [ , fromIndex ] )

이 메서드의 인자 해석과 사용은 23.1.3.17에 정의된 Array.prototype.indexOf의 경우와 같다.

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. objthis 값이라고 하자.
  2. taRecord를 ? ValidateTypedArray(obj, seq-cst)라고 하자.
  3. lenTypedArrayLength(taRecord)라고 하자.
  4. len = 0이면, -1𝔽을 반환한다.
  5. n을 ? ToIntegerOrInfinity(fromIndex)라고 하자.
  6. Assert: fromIndexundefined이면, n은 0이다.
  7. n = +∞이면, -1𝔽을 반환한다.
  8. n = -∞이면, n을 0으로 설정한다.
  9. n ≥ 0이면,
    1. kn이라고 하자.
  10. 그렇지 않으면,
    1. klen + n이라고 하자.
    2. k < 0이면, k를 0으로 설정한다.
  11. k < len인 동안 반복한다,
    1. propertyKey를 ! ToString(𝔽(k))라고 하자.
    2. kPresent를 ! HasProperty(obj, propertyKey)라고 하자.
    3. kPresenttrue이면,
      1. elementK를 ! Get(obj, propertyKey)라고 하자.
      2. IsStrictlyEqual(searchElement, elementK)가 true이면, 𝔽(k)를 반환한다.
    4. kk + 1로 설정한다.
  12. -1𝔽을 반환한다.

이 메서드는 제네릭이 아니다. this 값은 [[TypedArrayName]] 내부 슬롯을 가진 객체여야 한다.

23.2.3.18 %TypedArray%.prototype.join ( separator )

이 메서드의 인자 해석과 사용은 23.1.3.18에 정의된 Array.prototype.join의 경우와 같다.

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. objthis 값이라고 하자.
  2. taRecord를 ? ValidateTypedArray(obj, seq-cst)라고 하자.
  3. lenTypedArrayLength(taRecord)라고 하자.
  4. separatorundefined이면, sep","라고 하자.
  5. 그렇지 않으면, sep를 ? ToString(separator)라고 하자.
  6. result를 빈 String이라고 하자.
  7. k를 0이라고 하자.
  8. k < len인 동안 반복한다,
    1. k > 0이면, resultresultsep의 문자열 연결로 설정한다.
    2. element를 ! Get(obj, ! ToString(𝔽(k)))라고 하자.
    3. elementundefined가 아니면,
      1. elementStr을 ! ToString(element)라고 하자.
      2. resultresultelementStr의 문자열 연결로 설정한다.
    4. kk + 1로 설정한다.
  9. result를 반환한다.

이 메서드는 제네릭이 아니다. this 값은 [[TypedArrayName]] 내부 슬롯을 가진 객체여야 한다.

23.2.3.19 %TypedArray%.prototype.keys ( )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. objthis 값이라고 하자.
  2. ValidateTypedArray(obj, seq-cst)를 수행한다.
  3. CreateArrayIterator(obj, key)를 반환한다.

23.2.3.20 %TypedArray%.prototype.lastIndexOf ( searchElement [ , fromIndex ] )

이 메서드의 인자 해석과 사용은 23.1.3.20에 정의된 Array.prototype.lastIndexOf의 경우와 같다.

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. objthis 값이라고 하자.
  2. taRecord를 ? ValidateTypedArray(obj, seq-cst)라고 하자.
  3. lenTypedArrayLength(taRecord)라고 하자.
  4. len = 0이면, -1𝔽을 반환한다.
  5. fromIndex가 존재하면 n을 ? ToIntegerOrInfinity(fromIndex)라고 하자; 그렇지 않으면 nlen - 1이라고 하자.
  6. n = -∞이면, -1𝔽을 반환한다.
  7. n ≥ 0이면,
    1. kmin(n, len - 1)이라고 하자.
  8. 그렇지 않으면,
    1. klen + n이라고 하자.
  9. k ≥ 0인 동안 반복한다,
    1. propertyKey를 ! ToString(𝔽(k))라고 하자.
    2. kPresent를 ! HasProperty(obj, propertyKey)라고 하자.
    3. kPresenttrue이면,
      1. elementK를 ! Get(obj, propertyKey)라고 하자.
      2. IsStrictlyEqual(searchElement, elementK)가 true이면, 𝔽(k)를 반환한다.
    4. kk - 1로 설정한다.
  10. -1𝔽을 반환한다.

이 메서드는 제네릭이 아니다. this 값은 [[TypedArrayName]] 내부 슬롯을 가진 객체여야 한다.

23.2.3.21 get %TypedArray%.prototype.length

%TypedArray%.prototype.length는 set 접근자 함수가 undefined인 접근자 속성이다. 그 get 접근자 함수는 호출될 때 다음 단계를 수행한다:

  1. objthis 값이라고 하자.
  2. RequireInternalSlot(obj, [[TypedArrayName]])를 수행한다.
  3. Assert: obj[[ViewedArrayBuffer]][[ArrayLength]] 내부 슬롯을 가진다.
  4. taRecordMakeTypedArrayWithBufferWitnessRecord(obj, seq-cst)라고 하자.
  5. IsTypedArrayOutOfBounds(taRecord)가 true이면, +0𝔽을 반환한다.
  6. lengthTypedArrayLength(taRecord)라고 하자.
  7. 𝔽(length)를 반환한다.

이 함수는 제네릭이 아니다. this 값은 [[TypedArrayName]] 내부 슬롯을 가진 객체여야 한다.

23.2.3.22 %TypedArray%.prototype.map ( callback [ , thisArg ] )

이 메서드의 인자 해석과 사용은 23.1.3.21에 정의된 Array.prototype.map의 경우와 같다.

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. objthis 값이라고 하자.
  2. taRecord를 ? ValidateTypedArray(obj, seq-cst)라고 하자.
  3. lenTypedArrayLength(taRecord)라고 하자.
  4. IsCallable(callback)가 false이면, TypeError 예외를 던진다.
  5. resultTypedArray를 ? TypedArraySpeciesCreate(obj, « 𝔽(len) »)라고 하자.
  6. k를 0이라고 하자.
  7. k < len인 동안 반복한다,
    1. propertyKey를 ! ToString(𝔽(k))라고 하자.
    2. kValue를 ! Get(obj, propertyKey)라고 하자.
    3. mappedValue를 ? Call(callback, thisArg, « kValue, 𝔽(k), obj »)라고 하자.
    4. Set(resultTypedArray, propertyKey, mappedValue, true)를 수행한다.
    5. kk + 1로 설정한다.
  8. resultTypedArray를 반환한다.

이 메서드는 제네릭이 아니다. this 값은 [[TypedArrayName]] 내부 슬롯을 가진 객체여야 한다.

23.2.3.23 %TypedArray%.prototype.reduce ( callback [ , initialValue ] )

이 메서드의 인자 해석과 사용은 23.1.3.24에 정의된 Array.prototype.reduce의 경우와 같다.

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. objthis 값이라고 하자.
  2. taRecord를 ? ValidateTypedArray(obj, seq-cst)라고 하자.
  3. lenTypedArrayLength(taRecord)라고 하자.
  4. IsCallable(callback)가 false이면, TypeError 예외를 던진다.
  5. len = 0이고 initialValue가 존재하지 않으면, TypeError 예외를 던진다.
  6. k를 0이라고 하자.
  7. accumulatorundefined라고 하자.
  8. initialValue가 존재하면,
    1. accumulatorinitialValue로 설정한다.
  9. 그렇지 않으면,
    1. propertyKey를 ! ToString(𝔽(k))라고 하자.
    2. accumulator를 ! Get(obj, propertyKey)로 설정한다.
    3. kk + 1로 설정한다.
  10. k < len인 동안 반복한다,
    1. propertyKey를 ! ToString(𝔽(k))라고 하자.
    2. kValue를 ! Get(obj, propertyKey)라고 하자.
    3. accumulator를 ? Call(callback, undefined, « accumulator, kValue, 𝔽(k), obj »)로 설정한다.
    4. kk + 1로 설정한다.
  11. accumulator를 반환한다.

이 메서드는 제네릭이 아니다. this 값은 [[TypedArrayName]] 내부 슬롯을 가진 객체여야 한다.

23.2.3.24 %TypedArray%.prototype.reduceRight ( callback [ , initialValue ] )

이 메서드의 인자 해석과 사용은 23.1.3.25에 정의된 Array.prototype.reduceRight의 경우와 같다.

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. objthis 값이라고 하자.
  2. taRecord를 ? ValidateTypedArray(obj, seq-cst)라고 하자.
  3. lenTypedArrayLength(taRecord)라고 하자.
  4. IsCallable(callback)가 false이면, TypeError 예외를 던진다.
  5. len = 0이고 initialValue가 존재하지 않으면, TypeError 예외를 던진다.
  6. klen - 1이라고 하자.
  7. accumulatorundefined라고 하자.
  8. initialValue가 존재하면,
    1. accumulatorinitialValue로 설정한다.
  9. 그렇지 않으면,
    1. propertyKey를 ! ToString(𝔽(k))라고 하자.
    2. accumulator를 ! Get(obj, propertyKey)로 설정한다.
    3. kk - 1로 설정한다.
  10. k ≥ 0인 동안 반복한다,
    1. propertyKey를 ! ToString(𝔽(k))라고 하자.
    2. kValue를 ! Get(obj, propertyKey)라고 하자.
    3. accumulator를 ? Call(callback, undefined, « accumulator, kValue, 𝔽(k), obj »)로 설정한다.
    4. kk - 1로 설정한다.
  11. accumulator를 반환한다.

이 메서드는 제네릭이 아니다. this 값은 [[TypedArrayName]] 내부 슬롯을 가진 객체여야 한다.

23.2.3.25 %TypedArray%.prototype.reverse ( )

이 메서드의 인자 해석과 사용은 23.1.3.26에 정의된 Array.prototype.reverse의 경우와 같다.

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. objthis 값이라고 하자.
  2. taRecord를 ? ValidateTypedArray(obj, seq-cst)라고 하자.
  3. lenTypedArrayLength(taRecord)라고 하자.
  4. middlefloor(len / 2)라고 하자.
  5. lower를 0이라고 하자.
  6. lowermiddle인 동안 반복한다,
    1. upperlen - lower - 1이라고 하자.
    2. upperP를 ! ToString(𝔽(upper))라고 하자.
    3. lowerP를 ! ToString(𝔽(lower))라고 하자.
    4. lowerValue를 ! Get(obj, lowerP)라고 하자.
    5. upperValue를 ! Get(obj, upperP)라고 하자.
    6. Set(obj, lowerP, upperValue, true)를 수행한다.
    7. Set(obj, upperP, lowerValue, true)를 수행한다.
    8. lowerlower + 1로 설정한다.
  7. obj를 반환한다.

이 메서드는 제네릭이 아니다. this 값은 [[TypedArrayName]] 내부 슬롯을 가진 객체여야 한다.

23.2.3.26 %TypedArray%.prototype.set ( source [ , offset ] )

이 메서드는 source에서 값을 읽어 이 TypedArray 안에 여러 값을 설정한다. 세부 사항은 source의 타입에 따라 다르다. 선택적 offset 값은 값이 쓰이는 이 TypedArray 안의 첫 번째 요소 인덱스를 나타낸다. 생략되면 0으로 가정된다.

호출될 때 다음 단계를 수행한다:

  1. targetthis 값이라고 하자.
  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. 그렇지 않으면,
    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 either a normal completion containing unused or a throw completion. 이 연산은 source에서 값을 읽어 targetOffset 인덱스부터 시작하여 target 안에 여러 값을 설정한다. It performs the following steps when called:

  1. targetRecordMakeTypedArrayWithBufferWitnessRecord(target, seq-cst)라고 하자.
  2. IsTypedArrayOutOfBounds(targetRecord)가 true이면, TypeError 예외를 던진다.
  3. targetLengthTypedArrayLength(targetRecord)라고 하자.
  4. src를 ? ToObject(source)라고 하자.
  5. srcLength를 ? LengthOfArrayLike(src)라고 하자.
  6. targetOffset = +∞이면, RangeError 예외를 던진다.
  7. srcLength + targetOffset > targetLength이면, RangeError 예외를 던진다.
  8. k를 0이라고 하자.
  9. k < srcLength인 동안 반복한다,
    1. propertyKey를 ! ToString(𝔽(k))라고 하자.
    2. value를 ? Get(src, propertyKey)라고 하자.
    3. targetIndex𝔽(targetOffset + k)라고 하자.
    4. TypedArraySetElement(target, targetIndex, value)를 수행한다.
    5. kk + 1로 설정한다.
  10. unused를 반환한다.

23.2.3.26.2 SetTypedArrayFromTypedArray ( target, targetOffset, source )

The abstract operation SetTypedArrayFromTypedArray takes arguments target (a TypedArray), targetOffset (a non-negative integer or +∞), and source (a TypedArray) and returns either a normal completion containing unused or a throw completion. 이 연산은 source에서 값을 읽어 targetOffset 인덱스부터 시작하여 target 안에 여러 값을 설정한다. It performs the following steps when called:

  1. targetBuffertarget.[[ViewedArrayBuffer]]라고 하자.
  2. targetRecordMakeTypedArrayWithBufferWitnessRecord(target, seq-cst)라고 하자.
  3. IsTypedArrayOutOfBounds(targetRecord)가 true이면, TypeError 예외를 던진다.
  4. targetLengthTypedArrayLength(targetRecord)라고 하자.
  5. srcBuffersource.[[ViewedArrayBuffer]]라고 하자.
  6. srcRecordMakeTypedArrayWithBufferWitnessRecord(source, seq-cst)라고 하자.
  7. IsTypedArrayOutOfBounds(srcRecord)가 true이면, TypeError 예외를 던진다.
  8. srcLengthTypedArrayLength(srcRecord)라고 하자.
  9. targetTypeTypedArrayElementType(target)이라고 하자.
  10. targetElementSizeTypedArrayElementSize(target)라고 하자.
  11. targetByteOffsettarget.[[ByteOffset]]이라고 하자.
  12. srcTypeTypedArrayElementType(source)라고 하자.
  13. srcElementSizeTypedArrayElementSize(source)라고 하자.
  14. srcByteOffsetsource.[[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]]이면 sameSharedArrayBuffertrue라고 하자; 그렇지 않으면 sameSharedArrayBufferfalse라고 하자.
  19. SameValue(srcBuffer, targetBuffer)가 true이거나 sameSharedArrayBuffertrue이면,
    1. srcByteLengthTypedArrayByteLength(srcRecord)라고 하자.
    2. srcBuffer를 ? CloneArrayBuffer(srcBuffer, srcByteOffset, srcByteLength)로 설정한다.
    3. srcByteIndex를 0이라고 하자.
  20. 그렇지 않으면,
    1. srcByteIndexsrcByteOffset이라고 하자.
  21. targetByteIndex를 (targetOffset × targetElementSize) + targetByteOffset이라고 하자.
  22. limittargetByteIndex + (targetElementSize × srcLength)라고 하자.
  23. srcTypetargetType이면,
    1. NOTE: 전송은 소스 데이터의 비트 수준 인코딩을 보존하는 방식으로 수행되어야 한다.
    2. targetByteIndex < limit인 동안 반복한다,
      1. valueGetValueFromBuffer(srcBuffer, srcByteIndex, uint8, true, unordered)라고 하자.
      2. SetValueInBuffer(targetBuffer, targetByteIndex, uint8, value, true, unordered)를 수행한다.
      3. srcByteIndexsrcByteIndex + 1로 설정한다.
      4. targetByteIndextargetByteIndex + 1로 설정한다.
  24. 그렇지 않으면,
    1. targetByteIndex < limit인 동안 반복한다,
      1. valueGetValueFromBuffer(srcBuffer, srcByteIndex, srcType, true, unordered)라고 하자.
      2. SetValueInBuffer(targetBuffer, targetByteIndex, targetType, value, true, unordered)를 수행한다.
      3. srcByteIndexsrcByteIndex + srcElementSize로 설정한다.
      4. targetByteIndextargetByteIndex + targetElementSize로 설정한다.
  25. unused를 반환한다.

23.2.3.27 %TypedArray%.prototype.slice ( start, end )

이 메서드의 인자 해석과 사용은 23.1.3.28에 정의된 Array.prototype.slice의 경우와 같다.

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. objthis 값이라고 하자.
  2. taRecord를 ? ValidateTypedArray(obj, seq-cst)라고 하자.
  3. srcArrayLengthTypedArrayLength(taRecord)라고 하자.
  4. relativeStart를 ? ToIntegerOrInfinity(start)라고 하자.
  5. relativeStart = -∞이면, startIndex를 0이라고 하자.
  6. 그렇지 않고 relativeStart < 0이면, startIndexmax(srcArrayLength + relativeStart, 0)이라고 하자.
  7. 그렇지 않으면, startIndexmin(relativeStart, srcArrayLength)이라고 하자.
  8. endundefined이면 relativeEndsrcArrayLength라고 하자; 그렇지 않으면 relativeEnd를 ? ToIntegerOrInfinity(end)라고 하자.
  9. relativeEnd = -∞이면, endIndex를 0이라고 하자.
  10. 그렇지 않고 relativeEnd < 0이면, endIndexmax(srcArrayLength + relativeEnd, 0)이라고 하자.
  11. 그렇지 않으면, endIndexmin(relativeEnd, srcArrayLength)이라고 하자.
  12. countBytesmax(endIndex - startIndex, 0)이라고 하자.
  13. resultArray를 ? TypedArraySpeciesCreate(obj, « 𝔽(countBytes) »)라고 하자.
  14. countBytes > 0이면,
    1. taRecordMakeTypedArrayWithBufferWitnessRecord(obj, seq-cst)로 설정한다.
    2. IsTypedArrayOutOfBounds(taRecord)가 true이면, TypeError 예외를 던진다.
    3. endIndexmin(endIndex, TypedArrayLength(taRecord))로 설정한다.
    4. countBytesmax(endIndex - startIndex, 0)으로 설정한다.
    5. srcTypeTypedArrayElementType(obj)이라고 하자.
    6. targetTypeTypedArrayElementType(resultArray)이라고 하자.
    7. srcTypetargetType이면,
      1. NOTE: 전송은 소스 데이터의 비트 수준 인코딩을 보존하는 방식으로 수행되어야 한다.
      2. srcBufferobj.[[ViewedArrayBuffer]]라고 하자.
      3. targetBufferresultArray.[[ViewedArrayBuffer]]라고 하자.
      4. elementSizeTypedArrayElementSize(obj)라고 하자.
      5. srcByteOffsetobj.[[ByteOffset]]이라고 하자.
      6. srcByteIndex를 (startIndex × elementSize) + srcByteOffset이라고 하자.
      7. targetByteIndexresultArray.[[ByteOffset]]이라고 하자.
      8. endByteIndextargetByteIndex + (countBytes × elementSize)라고 하자.
      9. targetByteIndex < endByteIndex인 동안 반복한다,
        1. valueGetValueFromBuffer(srcBuffer, srcByteIndex, uint8, true, unordered)라고 하자.
        2. SetValueInBuffer(targetBuffer, targetByteIndex, uint8, value, true, unordered)를 수행한다.
        3. srcByteIndexsrcByteIndex + 1로 설정한다.
        4. targetByteIndextargetByteIndex + 1로 설정한다.
    8. 그렇지 않으면,
      1. n을 0이라고 하자.
      2. kstartIndex라고 하자.
      3. k < endIndex인 동안 반복한다,
        1. propertyKey를 ! ToString(𝔽(k))라고 하자.
        2. kValue를 ! Get(obj, propertyKey)라고 하자.
        3. Set(resultArray, ! ToString(𝔽(n)), kValue, true)를 수행한다.
        4. kk + 1로 설정한다.
        5. nn + 1로 설정한다.
  15. resultArray를 반환한다.

이 메서드는 제네릭이 아니다. this 값은 [[TypedArrayName]] 내부 슬롯을 가진 객체여야 한다.

23.2.3.28 %TypedArray%.prototype.some ( callback [ , thisArg ] )

이 메서드의 인자 해석과 사용은 23.1.3.29에 정의된 Array.prototype.some의 경우와 같다.

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. objthis 값이라고 하자.
  2. taRecord를 ? ValidateTypedArray(obj, seq-cst)라고 하자.
  3. lenTypedArrayLength(taRecord)라고 하자.
  4. IsCallable(callback)가 false이면, TypeError 예외를 던진다.
  5. k를 0이라고 하자.
  6. k < len인 동안 반복한다,
    1. propertyKey를 ! ToString(𝔽(k))라고 하자.
    2. kValue를 ! Get(obj, propertyKey)라고 하자.
    3. testResultToBoolean(? Call(callback, thisArg, « kValue, 𝔽(k), obj »))라고 하자.
    4. testResulttrue이면, true를 반환한다.
    5. kk + 1로 설정한다.
  7. false를 반환한다.

이 메서드는 제네릭이 아니다. 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. objthis 값이라고 하자.
  3. taRecord를 ? ValidateTypedArray(obj, seq-cst)라고 하자.
  4. lenTypedArrayLength(taRecord)라고 하자.
  5. NOTE: 다음 클로저는 23.1.3.30에서 사용되는 문자열 비교가 아니라 수치 비교를 수행한다.
  6. sortComparecomparator를 캡처하고 호출될 때 다음 단계를 수행하는, 매개변수 (x, y)를 가진 새로운 Abstract Closure라고 하자:
    1. 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. jj + 1로 설정한다.
  10. obj를 반환한다.
Note

NaN은 항상 다른 어떤 값보다도 크게 비교되므로(CompareTypedArrayElements를 보라), comparator가 제공되지 않으면 NaN 속성 값은 항상 결과의 끝으로 정렬된다.

23.2.3.30 %TypedArray%.prototype.subarray ( start, end )

이 메서드는 요소 타입이 이 TypedArray의 요소 타입이고 ArrayBuffer가 이 TypedArray의 ArrayBuffer이며, start(포함)부터 end(제외)까지의 구간에 있는 요소들을 참조하는 새로운 TypedArray를 반환한다. start 또는 end 중 하나가 음수이면, 처음부터가 아니라 배열의 끝으로부터의 인덱스를 가리킨다.

호출될 때 다음 단계를 수행한다:

  1. objthis 값이라고 하자.
  2. RequireInternalSlot(obj, [[TypedArrayName]])를 수행한다.
  3. Assert: obj[[ViewedArrayBuffer]] 내부 슬롯을 가진다.
  4. bufferobj.[[ViewedArrayBuffer]]라고 하자.
  5. srcRecordMakeTypedArrayWithBufferWitnessRecord(obj, seq-cst)라고 하자.
  6. IsTypedArrayOutOfBounds(srcRecord)가 true이면,
    1. srcLength를 0이라고 하자.
  7. 그렇지 않으면,
    1. srcLengthTypedArrayLength(srcRecord)라고 하자.
  8. relativeStart를 ? ToIntegerOrInfinity(start)라고 하자.
  9. relativeStart = -∞이면, startIndex를 0이라고 하자.
  10. 그렇지 않고 relativeStart < 0이면, startIndexmax(srcLength + relativeStart, 0)이라고 하자.
  11. 그렇지 않으면, startIndexmin(relativeStart, srcLength)이라고 하자.
  12. elementSizeTypedArrayElementSize(obj)라고 하자.
  13. srcByteOffsetobj.[[ByteOffset]]이라고 하자.
  14. beginByteOffsetsrcByteOffset + (startIndex × elementSize)라고 하자.
  15. obj.[[ArrayLength]]auto이고 endundefined이면,
    1. argumentsList를 « buffer, 𝔽(beginByteOffset) »라고 하자.
  16. 그렇지 않으면,
    1. endundefined이면 relativeEndsrcLength라고 하자; 그렇지 않으면 relativeEnd를 ? ToIntegerOrInfinity(end)라고 하자.
    2. relativeEnd = -∞이면, endIndex를 0이라고 하자.
    3. 그렇지 않고 relativeEnd < 0이면, endIndexmax(srcLength + relativeEnd, 0)이라고 하자.
    4. 그렇지 않으면, endIndexmin(relativeEnd, srcLength)이라고 하자.
    5. newLengthmax(endIndex - startIndex, 0)이라고 하자.
    6. argumentsList를 « buffer, 𝔽(beginByteOffset), 𝔽(newLength) »라고 하자.
  17. TypedArraySpeciesCreate(obj, argumentsList)를 반환한다.

이 메서드는 제네릭이 아니다. this 값은 [[TypedArrayName]] 내부 슬롯을 가진 객체여야 한다.

23.2.3.31 %TypedArray%.prototype.toLocaleString ( [ reserved1 [ , reserved2 ] ] )

이는 23.1.3.32에 정의된 Array.prototype.toLocaleString과 같은 알고리즘을 구현하는 별개의 메서드이지만, "length"[[Get]]을 수행하는 대신 TypedArrayLength가 호출된다는 점이 다르다. 이 알고리즘의 구현은 기반 버퍼가 크기 조절 가능하지 않을 때 this 값이 고정 길이를 가지며 정수 인덱스 속성이 희소하지 않다는 지식을 사용해 최적화될 수 있다. 그러나 그러한 최적화는 알고리즘의 지정된 동작에 관찰 가능한 변경을 도입해서는 안 된다.

이 메서드는 제네릭이 아니다. 알고리즘을 평가하기 전에 ValidateTypedArraythis 값과 seq-cst를 인자로 하여 호출된다. 그 결과가 abrupt completion이면 알고리즘을 평가하는 대신 그 예외가 던져진다.

Note

ECMAScript 구현이 ECMA-402 국제화 API를 포함하는 경우, 이 메서드는 ECMA-402 명세에 있는 Array.prototype.toLocaleString 알고리즘에 기반한다.

23.2.3.32 %TypedArray%.prototype.toReversed ( )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. objthis 값이라고 하자.
  2. taRecord를 ? ValidateTypedArray(obj, seq-cst)라고 하자.
  3. lenTypedArrayLength(taRecord)라고 하자.
  4. resultArray를 ? TypedArrayCreateSameType(obj, len)라고 하자.
  5. k를 0이라고 하자.
  6. k < len인 동안 반복한다,
    1. from을 ! ToString(𝔽(len - k - 1))라고 하자.
    2. propertyKey를 ! ToString(𝔽(k))라고 하자.
    3. fromValue를 ! Get(obj, from)라고 하자.
    4. Set(resultArray, propertyKey, fromValue, true)를 수행한다.
    5. kk + 1로 설정한다.
  7. resultArray를 반환한다.

23.2.3.33 %TypedArray%.prototype.toSorted ( comparator )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. comparatorundefined가 아니고 IsCallable(comparator)가 false이면, TypeError 예외를 던진다.
  2. objthis 값이라고 하자.
  3. taRecord를 ? ValidateTypedArray(obj, seq-cst)라고 하자.
  4. lenTypedArrayLength(taRecord)라고 하자.
  5. resultArray를 ? TypedArrayCreateSameType(obj, len)라고 하자.
  6. NOTE: 다음 클로저는 23.1.3.34에서 사용되는 문자열 비교가 아니라 수치 비교를 수행한다.
  7. sortComparecomparator를 캡처하고 호출될 때 다음 단계를 수행하는, 매개변수 (x, y)를 가진 새로운 Abstract Closure라고 하자:
    1. CompareTypedArrayElements(x, y, comparator)를 반환한다.
  8. sortedList를 ? SortIndexedProperties(obj, len, sortCompare, read-through-holes)라고 하자.
  9. j를 0이라고 하자.
  10. j < len인 동안 반복한다,
    1. Set(resultArray, ! ToString(𝔽(j)), sortedList[j], true)를 수행한다.
    2. jj + 1로 설정한다.
  11. resultArray를 반환한다.

23.2.3.34 %TypedArray%.prototype.toString ( )

"toString" 속성의 초기값은 23.1.3.36에 정의된 %Array.prototype.toString%이다.

23.2.3.35 %TypedArray%.prototype.values ( )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. objthis 값이라고 하자.
  2. ValidateTypedArray(obj, seq-cst)를 수행한다.
  3. CreateArrayIterator(obj, value)를 반환한다.

23.2.3.36 %TypedArray%.prototype.with ( index, value )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. objthis 값이라고 하자.
  2. taRecord를 ? ValidateTypedArray(obj, seq-cst)라고 하자.
  3. lenTypedArrayLength(taRecord)라고 하자.
  4. relativeIndex를 ? ToIntegerOrInfinity(index)라고 하자.
  5. relativeIndex ≥ 0이면, actualIndexrelativeIndex라고 하자.
  6. 그렇지 않으면, actualIndexlen + relativeIndex라고 하자.
  7. obj.[[ContentType]]bigint이면, numericValue를 ? ToBigInt(value)라고 하자.
  8. 그렇지 않으면, numericValue를 ? ToNumber(value)라고 하자.
  9. IsValidIntegerIndex(obj, 𝔽(actualIndex))가 false이면, RangeError 예외를 던진다.
  10. resultArray를 ? TypedArrayCreateSameType(obj, len)라고 하자.
  11. k를 0이라고 하자.
  12. k < len인 동안 반복한다,
    1. propertyKey를 ! ToString(𝔽(k))라고 하자.
    2. k = actualIndex이면, fromValuenumericValue라고 하자.
    3. 그렇지 않으면, fromValue를 ! Get(obj, propertyKey)라고 하자.
    4. Set(resultArray, propertyKey, fromValue, true)를 수행한다.
    5. kk + 1로 설정한다.
  13. resultArray를 반환한다.

23.2.3.37 %TypedArray%.prototype [ %Symbol.iterator% ] ( )

%Symbol.iterator% 속성의 초기값은 23.2.3.35에 정의된 %TypedArray.prototype.values%이다.

23.2.3.38 get %TypedArray%.prototype [ %Symbol.toStringTag% ]

%TypedArray%.prototype[%Symbol.toStringTag%]는 set 접근자 함수가 undefined인 접근자 속성이다. 그 get 접근자 함수는 호출될 때 다음 단계를 수행한다:

  1. objthis 값이라고 하자.
  2. obj가 Object가 아니면, undefined를 반환한다.
  3. obj[[TypedArrayName]] 내부 슬롯을 가지지 않으면, undefined를 반환한다.
  4. nameobj.[[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 either a normal completion containing a TypedArray or a 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. lengthTypedArrayLength(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 either a normal completion containing a TypedArray or a throw completion. exemplar에서 파생된 생성자 함수를 사용한 새 TypedArray의 생성을 지정하는 데 사용된다. %Symbol.species%를 사용하여 사용자 정의 TypedArray 서브클래스를 생성할 수 있는 TypedArraySpeciesCreate와 달리, 이 연산은 항상 내장 TypedArray 생성자 중 하나를 사용한다. It performs the following steps when called:

  1. constructorTable 70에서 생성자 이름 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 either a normal completion containing a TypedArray or a throw completion. exemplar에서 파생된 생성자 함수를 사용한 새 TypedArray의 생성을 지정하는 데 사용된다. %Symbol.species%를 사용하여 Array가 아닌 객체를 생성할 수 있는 ArraySpeciesCreate와 달리, 이 연산은 생성자 함수가 실제 TypedArray를 생성하도록 강제한다. It performs the following steps when called:

  1. defaultConstructorTable 70에서 생성자 이름 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 ( obj, order )

The abstract operation ValidateTypedArray takes arguments obj (an ECMAScript language value) and order (seq-cst or unordered) and returns either a normal completion containing a TypedArray With Buffer Witness Record or a throw completion. It performs the following steps when called:

  1. RequireInternalSlot(obj, [[TypedArrayName]])를 수행한다.
  2. Assert: obj[[ViewedArrayBuffer]] 내부 슬롯을 가진다.
  3. taRecordMakeTypedArrayWithBufferWitnessRecord(obj, order)라고 하자.
  4. IsTypedArrayOutOfBounds(taRecord)가 true이면, TypeError 예외를 던진다.
  5. taRecord를 반환한다.

23.2.4.5 TypedArrayElementSize ( obj )

The abstract operation TypedArrayElementSize takes argument obj (a TypedArray) and returns a non-negative integer. It performs the following steps when called:

  1. obj.[[TypedArrayName]]에 대해 Table 70에 지정된 Element Size 값을 반환한다.

23.2.4.6 TypedArrayElementType ( obj )

The abstract operation TypedArrayElementType takes argument obj (a TypedArray) and returns a TypedArray element type. It performs the following steps when called:

  1. obj.[[TypedArrayName]]에 대해 Table 70에 지정된 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 either a normal completion containing a Number or an abrupt completion. It performs the following steps when called:

  1. Assert: x는 Number이고 y는 Number이거나, x는 BigInt이고 y는 BigInt이다.
  2. comparatorundefined가 아니면,
    1. result를 ? ToNumber(? Call(comparator, undefined, « x, y »))라고 하자.
    2. resultNaN이면, +0𝔽을 반환한다.
    3. result를 반환한다.
  3. xNaN이고 yNaN이면, +0𝔽을 반환한다.
  4. xNaN이면, 1𝔽을 반환한다.
  5. yNaN이면, -1𝔽을 반환한다.
  6. x < y이면, -1𝔽을 반환한다.
  7. x > y이면, 1𝔽을 반환한다.
  8. x-0𝔽이고 y+0𝔽이면, -1𝔽을 반환한다.
  9. x+0𝔽이고 y-0𝔽이면, 1𝔽을 반환한다.
  10. +0𝔽을 반환한다.
Note
이는 23.1.3.30.2에서 사용되는 문자열 비교가 아니라 수치 비교를 수행한다.

23.2.5 TypedArray 생성자

TypedArray 생성자는:

  • 달리 명시된 경우를 제외하고, Table 70에서 TypedArray 대신 생성자 이름으로 사용되는 이름만 다를 뿐 아래에 설명된 구조를 가지는 내재 객체이다.
  • 인자의 개수와 타입에 따라 동작이 달라지는 함수이다. TypedArray 호출의 실제 동작은 전달된 인자의 개수와 종류에 의존한다.
  • 함수로 호출되도록 의도되지 않았으며, 그런 방식으로 호출되면 예외를 던진다.
  • 클래스 정의의 extends 절의 값으로 사용될 수 있다. 지정된 TypedArray 동작을 상속하려는 서브클래스 생성자는 %TypedArray%.prototype 내장 메서드를 지원하는 데 필요한 내부 상태로 서브클래스 인스턴스를 생성하고 초기화하기 위해 TypedArray 생성자에 대한 super 호출을 포함해야 한다.

23.2.5.1 TypedArray ( ...args )

TypedArray 생성자는 호출될 때 다음 단계를 수행한다:

  1. NewTarget이 undefined이면, TypeError 예외를 던진다.
  2. constructorName을 이 TypedArray 생성자에 대해 Table 70에 지정된 Constructor Name 값의 String 값이라고 하자.
  3. proto"%TypedArray.prototype%"라고 하자.
  4. numberOfArgsargs의 요소 개수라고 하자.
  5. numberOfArgs = 0이면, ? AllocateTypedArray(constructorName, NewTarget, proto, 0)를 반환한다.
  6. firstArgumentargs[0]이라고 하자.
  7. firstArgument가 Object이면,
    1. obj를 ? AllocateTypedArray(constructorName, NewTarget, proto)라고 하자.
    2. firstArgument[[TypedArrayName]] 내부 슬롯을 가지면,
      1. InitializeTypedArrayFromTypedArray(obj, firstArgument)를 수행한다.
    3. 그렇지 않고 firstArgument[[ArrayBufferData]] 내부 슬롯을 가지면,
      1. numberOfArgs > 1이면 byteOffsetargs[1]이라고 하자; 그렇지 않으면 byteOffsetundefined라고 하자.
      2. numberOfArgs > 2이면 lengthargs[2]라고 하자; 그렇지 않으면 lengthundefined라고 하자.
      3. InitializeTypedArrayFromArrayBuffer(obj, firstArgument, byteOffset, length)를 수행한다.
    4. 그렇지 않으면,
      1. Assert: firstArgument는 Object이고 firstArgument[[TypedArrayName]] 또는 [[ArrayBufferData]] 내부 슬롯 중 어느 것도 가지지 않는다.
      2. usingIterator를 ? GetMethod(firstArgument, %Symbol.iterator%)라고 하자.
      3. usingIteratorundefined가 아니면,
        1. values를 ? IteratorToList(? GetIteratorFromMethod(firstArgument, usingIterator))라고 하자.
        2. InitializeTypedArrayFromList(obj, values)를 수행한다.
      4. 그렇지 않으면,
        1. NOTE: firstArgument는 반복 가능 객체가 아니므로, 이미 배열 유사 객체라고 가정한다.
        2. InitializeTypedArrayFromArrayLike(obj, firstArgument)를 수행한다.
    5. obj를 반환한다.
  8. Assert: firstArgument는 Object가 아니다.
  9. elementLength를 ? ToIndex(firstArgument)라고 하자.
  10. AllocateTypedArray(constructorName, NewTarget, proto, elementLength)를 반환한다.

23.2.5.1.1 AllocateTypedArray ( constructorName, newTarget, defaultProto [ , length ] )

The abstract operation AllocateTypedArray takes arguments constructorName (a String which is the name of a TypedArray constructor in Table 70), newTarget (a constructor), and defaultProto (a String) and optional argument length (a non-negative integer) and returns either a normal completion containing a TypedArray or a throw completion. TypedArray 생성자의 인스턴스를 검증하고 생성하는 데 사용된다. length 인자가 전달되면, 그 길이의 ArrayBuffer도 할당되어 새 TypedArray 인스턴스와 연결된다. AllocateTypedArray는 TypedArray가 사용하는 공통 의미론을 제공한다. It performs the following steps when called:

  1. proto를 ? GetPrototypeFromConstructor(newTarget, defaultProto)라고 하자.
  2. objTypedArrayCreate(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. 그렇지 않으면,
    1. AllocateTypedArrayBuffer(obj, length)를 수행한다.
  9. obj를 반환한다.

23.2.5.1.2 InitializeTypedArrayFromTypedArray ( obj, srcArray )

The abstract operation InitializeTypedArrayFromTypedArray takes arguments obj (a TypedArray) and srcArray (a TypedArray) and returns either a normal completion containing unused or a throw completion. It performs the following steps when called:

  1. srcDatasrcArray.[[ViewedArrayBuffer]]라고 하자.
  2. elementTypeTypedArrayElementType(obj)이라고 하자.
  3. elementSizeTypedArrayElementSize(obj)라고 하자.
  4. srcTypeTypedArrayElementType(srcArray)라고 하자.
  5. srcElementSizeTypedArrayElementSize(srcArray)라고 하자.
  6. srcByteOffsetsrcArray.[[ByteOffset]]이라고 하자.
  7. srcRecordMakeTypedArrayWithBufferWitnessRecord(srcArray, seq-cst)라고 하자.
  8. IsTypedArrayOutOfBounds(srcRecord)가 true이면, TypeError 예외를 던진다.
  9. elementLengthTypedArrayLength(srcRecord)라고 하자.
  10. byteLengthelementSize × elementLength라고 하자.
  11. elementTypesrcType이면,
    1. data를 ? CloneArrayBuffer(srcData, srcByteOffset, byteLength)라고 하자.
  12. 그렇지 않으면,
    1. data를 ? AllocateArrayBuffer(%ArrayBuffer%, byteLength)라고 하자.
    2. srcArray.[[ContentType]]obj.[[ContentType]]가 아니면, TypeError 예외를 던진다.
    3. srcByteIndexsrcByteOffset이라고 하자.
    4. targetByteIndex를 0이라고 하자.
    5. countelementLength라고 하자.
    6. count > 0인 동안 반복한다,
      1. valueGetValueFromBuffer(srcData, srcByteIndex, srcType, true, unordered)라고 하자.
      2. SetValueInBuffer(data, targetByteIndex, elementType, value, true, unordered)를 수행한다.
      3. srcByteIndexsrcByteIndex + srcElementSize로 설정한다.
      4. targetByteIndextargetByteIndex + elementSize로 설정한다.
      5. countcount - 1로 설정한다.
  13. obj.[[ViewedArrayBuffer]]data로 설정한다.
  14. obj.[[ByteLength]]byteLength로 설정한다.
  15. obj.[[ByteOffset]]을 0으로 설정한다.
  16. obj.[[ArrayLength]]elementLength로 설정한다.
  17. unused를 반환한다.

23.2.5.1.3 InitializeTypedArrayFromArrayBuffer ( obj, buffer, byteOffset, length )

The abstract operation InitializeTypedArrayFromArrayBuffer takes arguments obj (a TypedArray), buffer (an ArrayBuffer or a SharedArrayBuffer), byteOffset (an ECMAScript language value), and length (an ECMAScript language value) and returns either a normal completion containing unused or a throw completion. It performs the following steps when called:

  1. elementSizeTypedArrayElementSize(obj)라고 하자.
  2. offset을 ? ToIndex(byteOffset)이라고 하자.
  3. offset modulo elementSize ≠ 0이면, RangeError 예외를 던진다.
  4. bufferIsFixedLengthIsFixedLengthArrayBuffer(buffer)라고 하자.
  5. lengthundefined가 아니면,
    1. newLength를 ? ToIndex(length)라고 하자.
  6. IsDetachedBuffer(buffer)가 true이면, TypeError 예외를 던진다.
  7. bufferByteLengthArrayBufferByteLength(buffer, seq-cst)라고 하자.
  8. lengthundefined이고 bufferIsFixedLengthfalse이면,
    1. offset > bufferByteLength이면, RangeError 예외를 던진다.
    2. obj.[[ByteLength]]auto로 설정한다.
    3. obj.[[ArrayLength]]auto로 설정한다.
  9. 그렇지 않으면,
    1. lengthundefined이면,
      1. bufferByteLength modulo elementSize ≠ 0이면, RangeError 예외를 던진다.
      2. newByteLengthbufferByteLength - offset이라고 하자.
      3. newByteLength < 0이면, RangeError 예외를 던진다.
    2. 그렇지 않으면,
      1. newByteLengthnewLength × elementSize라고 하자.
      2. offset + newByteLength > bufferByteLength이면, RangeError 예외를 던진다.
    3. obj.[[ByteLength]]newByteLength로 설정한다.
    4. obj.[[ArrayLength]]newByteLength / elementSize로 설정한다.
  10. obj.[[ViewedArrayBuffer]]buffer로 설정한다.
  11. obj.[[ByteOffset]]offset으로 설정한다.
  12. unused를 반환한다.

23.2.5.1.4 InitializeTypedArrayFromList ( obj, values )

The abstract operation InitializeTypedArrayFromList takes arguments obj (a TypedArray) and values (a List of ECMAScript language values) and returns either a normal completion containing unused or a throw completion. It performs the following steps when called:

  1. lenvalues의 요소 개수라고 하자.
  2. AllocateTypedArrayBuffer(obj, len)를 수행한다.
  3. k를 0이라고 하자.
  4. k < len인 동안 반복한다,
    1. propertyKey를 ! ToString(𝔽(k))라고 하자.
    2. kValuevalues의 첫 번째 요소라고 하자.
    3. values에서 첫 번째 요소를 제거한다.
    4. Set(obj, propertyKey, kValue, true)를 수행한다.
    5. kk + 1로 설정한다.
  5. Assert: values는 이제 빈 List이다.
  6. unused를 반환한다.

23.2.5.1.5 InitializeTypedArrayFromArrayLike ( obj, arrayLike )

The abstract operation InitializeTypedArrayFromArrayLike takes arguments obj (a TypedArray) and arrayLike (an Object, but not a TypedArray or an ArrayBuffer) and returns either a normal completion containing unused or a throw completion. It performs the following steps when called:

  1. len을 ? LengthOfArrayLike(arrayLike)라고 하자.
  2. AllocateTypedArrayBuffer(obj, len)를 수행한다.
  3. k를 0이라고 하자.
  4. k < len인 동안 반복한다,
    1. propertyKey를 ! ToString(𝔽(k))라고 하자.
    2. kValue를 ? Get(arrayLike, propertyKey)라고 하자.
    3. Set(obj, propertyKey, kValue, true)를 수행한다.
    4. kk + 1로 설정한다.
  5. unused를 반환한다.

23.2.5.1.6 AllocateTypedArrayBuffer ( obj, length )

The abstract operation AllocateTypedArrayBuffer takes arguments obj (a TypedArray) and length (a non-negative integer) and returns either a normal completion containing unused or a throw completion. obj에 ArrayBuffer를 할당하고 연결한다. It performs the following steps when called:

  1. Assert: obj.[[ViewedArrayBuffer]]undefined이다.
  2. elementSizeTypedArrayElementSize(obj)라고 하자.
  3. byteLengthelementSize × length라고 하자.
  4. data를 ? AllocateArrayBuffer(%ArrayBuffer%, byteLength)라고 하자.
  5. obj.[[ViewedArrayBuffer]]data로 설정한다.
  6. obj.[[ByteLength]]byteLength로 설정한다.
  7. obj.[[ByteOffset]]을 0으로 설정한다.
  8. obj.[[ArrayLength]]length로 설정한다.
  9. unused를 반환한다.

23.2.6 TypedArray 생성자의 속성

TypedArray 생성자는:

  • 값이 %TypedArray%[[Prototype]] 내부 슬롯을 가진다.
  • 값이 3𝔽"length" 속성을 가진다.
  • 값이 Table 70에서 그 생성자에 대해 지정된 생성자 이름의 String 값인 "name" 속성을 가진다.
  • 다음 속성들을 가진다:

23.2.6.1 TypedArray.BYTES_PER_ELEMENT

TypedArray.BYTES_PER_ELEMENT의 값은 TypedArray에 대해 Table 70에 지정된 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 프로토타입 객체는:

  • 값이 %TypedArray.prototype%[[Prototype]] 내부 슬롯을 가진다.
  • 보통 객체이다.
  • [[ViewedArrayBuffer]]TypedArray 인스턴스 객체에 특유한 다른 어떤 내부 슬롯도 가지지 않는다.

23.2.7.1 TypedArray.prototype.BYTES_PER_ELEMENT

TypedArray.prototype.BYTES_PER_ELEMENT의 값은 TypedArray에 대해 Table 70에 지정된 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]].

23.3 Uint8Array 객체

Uint8Array는 위에 설명된 TypedArray의 특정 종류이다. 또한 Uint8Array 생성자(23.3.1)와 Uint8Array 프로토타입 객체(23.3.2)에는 추가 메서드가 있다.

23.3.1 Uint8Array 생성자의 추가 속성

23.3.1.1 Uint8Array.fromBase64 ( string [ , options ] )

  1. string이 String이 아니면, TypeError 예외를 던진다.
  2. opts를 ? GetOptionsObject(options)라고 하자.
  3. alphabet을 ? Get(opts, "alphabet")이라고 하자.
  4. alphabetundefined이면, alphabet"base64"로 설정한다.
  5. alphabet"base64""base64url"도 아니면, TypeError 예외를 던진다.
  6. lastChunkHandling을 ? Get(opts, "lastChunkHandling")이라고 하자.
  7. lastChunkHandlingundefined이면, lastChunkHandling"loose"로 설정한다.
  8. lastChunkHandling"loose", "strict", 또는 "stop-before-partial" 중 하나가 아니면, TypeError 예외를 던진다.
  9. resultFromBase64(string, alphabet, lastChunkHandling)라고 하자.
  10. result.[[Error]]none이 아니면,
    1. result.[[Error]]를 던진다.
  11. resultLengthresult.[[Bytes]]의 요소 개수라고 하자.
  12. ta를 ? AllocateTypedArray("Uint8Array", %Uint8Array%, "%Uint8Array.prototype%", resultLength)라고 하자.
  13. Assert: ta.[[ViewedArrayBuffer]].[[ArrayBufferByteLength]]result.[[Bytes]]의 요소 개수이다.
  14. ta.[[ViewedArrayBuffer]].[[ArrayBufferData]]의 각 인덱스 값을 result.[[Bytes]]의 대응하는 인덱스 값으로 설정한다.
  15. ta를 반환한다.

23.3.1.2 Uint8Array.fromHex ( string )

  1. string이 String이 아니면, TypeError 예외를 던진다.
  2. resultFromHex(string)라고 하자.
  3. result.[[Error]]none이 아니면,
    1. result.[[Error]]를 던진다.
  4. resultLengthresult.[[Bytes]]의 요소 개수라고 하자.
  5. ta를 ? AllocateTypedArray("Uint8Array", %Uint8Array%, "%Uint8Array.prototype%", resultLength)라고 하자.
  6. Assert: ta.[[ViewedArrayBuffer]].[[ArrayBufferByteLength]]result.[[Bytes]]의 요소 개수이다.
  7. ta.[[ViewedArrayBuffer]].[[ArrayBufferData]]의 각 인덱스 값을 result.[[Bytes]]의 대응하는 인덱스 값으로 설정한다.
  8. ta를 반환한다.

23.3.2 Uint8Array 프로토타입 객체의 추가 속성

23.3.2.1 Uint8Array.prototype.setFromBase64 ( string [ , options ] )

  1. intothis 값이라고 하자.
  2. ValidateUint8Array(into)를 수행한다.
  3. string이 String이 아니면, TypeError 예외를 던진다.
  4. opts를 ? GetOptionsObject(options)라고 하자.
  5. alphabet을 ? Get(opts, "alphabet")이라고 하자.
  6. alphabetundefined이면, alphabet"base64"로 설정한다.
  7. alphabet"base64""base64url"도 아니면, TypeError 예외를 던진다.
  8. lastChunkHandling을 ? Get(opts, "lastChunkHandling")이라고 하자.
  9. lastChunkHandlingundefined이면, lastChunkHandling"loose"로 설정한다.
  10. lastChunkHandling"loose", "strict", 또는 "stop-before-partial" 중 하나가 아니면, TypeError 예외를 던진다.
  11. taRecordMakeTypedArrayWithBufferWitnessRecord(into, seq-cst)라고 하자.
  12. IsTypedArrayOutOfBounds(taRecord)가 true이면, TypeError 예외를 던진다.
  13. byteLengthTypedArrayLength(taRecord)라고 하자.
  14. resultFromBase64(string, alphabet, lastChunkHandling, byteLength)라고 하자.
  15. bytesresult.[[Bytes]]라고 하자.
  16. writtenbytes의 요소 개수라고 하자.
  17. NOTE: FromBase64는 어떤 사용자 코드도 호출하지 않으므로, into를 뒷받침하는 ArrayBuffer는 detached되거나 축소될 수 없다.
  18. Assert: writtenbyteLength.
  19. SetUint8ArrayBytes(into, bytes)를 수행한다.
  20. result.[[Error]]none이 아니면,
    1. result.[[Error]]를 던진다.
  21. resultObjectOrdinaryObjectCreate(%Object.prototype%)라고 하자.
  22. CreateDataPropertyOrThrow(resultObject, "read", 𝔽(result.[[Read]]))를 수행한다.
  23. CreateDataPropertyOrThrow(resultObject, "written", 𝔽(written))를 수행한다.
  24. resultObject를 반환한다.

23.3.2.2 Uint8Array.prototype.setFromHex ( string )

  1. intothis 값이라고 하자.
  2. ValidateUint8Array(into)를 수행한다.
  3. string이 String이 아니면, TypeError 예외를 던진다.
  4. taRecordMakeTypedArrayWithBufferWitnessRecord(into, seq-cst)라고 하자.
  5. IsTypedArrayOutOfBounds(taRecord)가 true이면, TypeError 예외를 던진다.
  6. byteLengthTypedArrayLength(taRecord)라고 하자.
  7. resultFromHex(string, byteLength)라고 하자.
  8. bytesresult.[[Bytes]]라고 하자.
  9. writtenbytes의 요소 개수라고 하자.
  10. NOTE: FromHex는 어떤 사용자 코드도 호출하지 않으므로, into를 뒷받침하는 ArrayBuffer는 detached되거나 축소될 수 없다.
  11. Assert: writtenbyteLength.
  12. SetUint8ArrayBytes(into, bytes)를 수행한다.
  13. result.[[Error]]none이 아니면,
    1. result.[[Error]]를 던진다.
  14. resultObjectOrdinaryObjectCreate(%Object.prototype%)라고 하자.
  15. CreateDataPropertyOrThrow(resultObject, "read", 𝔽(result.[[Read]]))를 수행한다.
  16. CreateDataPropertyOrThrow(resultObject, "written", 𝔽(written))를 수행한다.
  17. resultObject를 반환한다.

23.3.2.3 Uint8Array.prototype.toBase64 ( [ options ] )

  1. objthis 값이라고 하자.
  2. ValidateUint8Array(obj)를 수행한다.
  3. opts를 ? GetOptionsObject(options)라고 하자.
  4. alphabet을 ? Get(opts, "alphabet")이라고 하자.
  5. alphabetundefined이면, alphabet"base64"로 설정한다.
  6. alphabet"base64""base64url"도 아니면, TypeError 예외를 던진다.
  7. omitPaddingToBoolean(? Get(opts, "omitPadding"))이라고 하자.
  8. toEncode를 ? GetUint8ArrayBytes(obj)라고 하자.
  9. alphabet"base64"이면,
    1. outAsciiRFC 4648의 4절에 지정된 base64 인코딩에 따라 toEncode를 인코딩한 결과인 코드 포인트들의 시퀀스라고 하자. 패딩은 omitPaddingfalse인 경우에만 포함된다.
  10. 그렇지 않으면,
    1. Assert: alphabet"base64url"이다.
    2. outAsciiRFC 4648의 5절에 지정된 base64url 인코딩에 따라 toEncode를 인코딩한 결과인 코드 포인트들의 시퀀스라고 하자. 패딩은 omitPaddingfalse인 경우에만 포함된다.
  11. CodePointsToString(outAscii)를 반환한다.

23.3.2.4 Uint8Array.prototype.toHex ( )

  1. objthis 값이라고 하자.
  2. ValidateUint8Array(obj)를 수행한다.
  3. toEncode를 ? GetUint8ArrayBytes(obj)라고 하자.
  4. out을 빈 String이라고 하자.
  5. toEncode의 각 바이트 byte에 대해, 다음을 수행한다.
    1. hexNumber::toString(𝔽(byte), 16)이라고 하자.
    2. hexStringPad(hex, 2, "0", start)로 설정한다.
    3. outouthex의 문자열 연결로 설정한다.
  6. out을 반환한다.

23.3.3 Uint8Array 객체를 위한 추상 연산

23.3.3.1 ValidateUint8Array ( ta )

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

  1. RequireInternalSlot(ta, [[TypedArrayName]])를 수행한다.
  2. ta.[[TypedArrayName]]"Uint8Array"가 아니면, TypeError 예외를 던진다.
  3. unused를 반환한다.

23.3.3.2 GetUint8ArrayBytes ( ta )

The abstract operation GetUint8ArrayBytes takes argument ta (a Uint8Array) and returns either a normal completion containing a List of byte values or a throw completion. It performs the following steps when called:

  1. bufferta.[[ViewedArrayBuffer]]라고 하자.
  2. taRecordMakeTypedArrayWithBufferWitnessRecord(ta, seq-cst)라고 하자.
  3. IsTypedArrayOutOfBounds(taRecord)가 true이면, TypeError 예외를 던진다.
  4. lenTypedArrayLength(taRecord)라고 하자.
  5. byteOffsetta.[[ByteOffset]]이라고 하자.
  6. bytes를 새로운 빈 List라고 하자.
  7. index를 0이라고 하자.
  8. index < len인 동안 반복한다,
    1. byteIndexbyteOffset + index라고 하자.
    2. byte(GetValueFromBuffer(buffer, byteIndex, uint8, true, unordered))라고 하자.
    3. bytebytes에 추가한다.
    4. indexindex + 1로 설정한다.
  9. bytes를 반환한다.

23.3.3.3 SetUint8ArrayBytes ( into, bytes )

The abstract operation SetUint8ArrayBytes takes arguments into (a Uint8Array) and bytes (a List of byte values) and returns unused. It performs the following steps when called:

  1. offsetinto.[[ByteOffset]]이라고 하자.
  2. lenbytes의 요소 개수라고 하자.
  3. index를 0이라고 하자.
  4. index < len인 동안 반복한다,
    1. bytebytes[index]라고 하자.
    2. byteIndexInBufferindex + offset이라고 하자.
    3. SetValueInBuffer(into.[[ViewedArrayBuffer]], byteIndexInBuffer, uint8, 𝔽(byte), true, unordered)를 수행한다.
    4. indexindex + 1로 설정한다.
  5. unused를 반환한다.

23.3.3.4 SkipAsciiWhitespace ( string, index )

The abstract operation SkipAsciiWhitespace takes arguments string (a String) and index (a non-negative integer) and returns a non-negative integer. It performs the following steps when called:

  1. lengthstring의 길이라고 하자.
  2. index < length인 동안 반복한다,
    1. charstring 안의 인덱스 index에 있는 코드 단위라고 하자.
    2. char가 0x0009 (TAB), 0x000A (LF), 0x000C (FF), 0x000D (CR), 또는 0x0020 (SPACE) 중 하나가 아니면,
      1. index를 반환한다.
    3. indexindex + 1로 설정한다.
  3. index를 반환한다.

23.3.3.5 DecodeFinalBase64Chunk ( chunk, throwOnExtraBits )

The abstract operation DecodeFinalBase64Chunk takes arguments chunk (a String of length 2 or 3) and throwOnExtraBits (a Boolean) and returns either a normal completion containing a List of byte values, or a throw completion. It performs the following steps when called:

  1. chunkLengthchunk의 길이라고 하자.
  2. chunkLength = 2이면,
    1. chunkchunk"AA"의 문자열 연결로 설정한다.
  3. 그렇지 않으면,
    1. Assert: chunkLength는 3이다.
    2. chunkchunk"A"의 문자열 연결로 설정한다.
  4. bytesDecodeFullLengthBase64Chunk(chunk)라고 하자.
  5. chunkLength = 2이면,
    1. throwOnExtraBitstrue이고 bytes[1] ≠ 0이면, SyntaxError 예외를 던진다.
    2. « bytes[0] »를 반환한다.
  6. throwOnExtraBitstrue이고 bytes[2] ≠ 0이면, SyntaxError 예외를 던진다.
  7. « bytes[0], bytes[1] »를 반환한다.

23.3.3.6 DecodeFullLengthBase64Chunk ( chunk )

The abstract operation DecodeFullLengthBase64Chunk takes argument chunk (a String of length 4) and returns a List of byte values of length 3.

표준 base64 알파벳"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"이다. 즉 Unicode Basic Latin 블록의 모든 문자와 숫자에 대응하는 코드 단위들과 "+""/"를 요소로 가지는 String이다.

  1. byteSequencechunk를 base64로 디코딩한 결과인 고유한 3바이트 시퀀스라고 하자(즉, RFC 4648의 4절에 지정된 base64 인코딩을 byteSequence에 적용하면 chunk가 생성되는 그러한 시퀀스).
  2. byteSequence의 요소들을 순서대로 요소로 가지는 List를 반환한다.

23.3.3.7 FromBase64 ( string, alphabet, lastChunkHandling [ , maxLength ] )

The abstract operation FromBase64 takes arguments string (a String), alphabet ("base64" or "base64url"), and lastChunkHandling ("loose", "strict", or "stop-before-partial") and optional argument maxLength (a non-negative integer) and returns a Record with fields [[Read]] (an integer), [[Bytes]] (a List of byte values), and [[Error]] (a SyntaxError object or none). It performs the following steps when called:

  1. maxLength가 존재하지 않으면,
    1. maxLength를 253 - 1로 설정한다.
    2. NOTE: 입력이 String이므로, String의 길이는 253 - 1 문자로 제한되고, 출력은 입력이 가진 문자 수보다 많은 바이트를 요구하지 않으므로, 이 한계에는 결코 도달할 수 없다. 그러나 유한 값을 사용하는 것이 편집상 편리하다.
  2. NOTE: 아래 알고리즘에서 검증과 디코딩의 순서는 관찰 가능하지 않다. 구현은 가장 효율적인 어떤 순서로든, 가능하면 검증과 디코딩을 인터리브하여 수행하는 것이 권장된다.
  3. maxLength = 0이면,
    1. Record { [[Read]]: 0, [[Bytes]]: « », [[Error]]: none }를 반환한다.
  4. read를 0이라고 하자.
  5. bytes를 새로운 빈 List라고 하자.
  6. chunk를 빈 String이라고 하자.
  7. chunkLength를 0이라고 하자.
  8. index를 0이라고 하자.
  9. lengthstring의 길이라고 하자.
  10. 반복한다,
    1. indexSkipAsciiWhitespace(string, index)로 설정한다.
    2. index = length이면,
      1. chunkLength > 0이면,
        1. lastChunkHandling"stop-before-partial"이면,
          1. Record { [[Read]]: read, [[Bytes]]: bytes, [[Error]]: none }를 반환한다.
        2. lastChunkHandling"strict"이면,
          1. error를 새로 생성된 SyntaxError 객체라고 하자.
          2. Record { [[Read]]: read, [[Bytes]]: bytes, [[Error]]: error }를 반환한다.
        3. Assert: lastChunkHandling"loose"이다.
        4. chunkLength = 1이면,
          1. error를 새로 생성된 SyntaxError 객체라고 하자.
          2. Record { [[Read]]: read, [[Bytes]]: bytes, [[Error]]: error }를 반환한다.
        5. bytesbytes와 ! DecodeFinalBase64Chunk(chunk, false)의 리스트 연결로 설정한다.
      2. Record { [[Read]]: length, [[Bytes]]: bytes, [[Error]]: none }를 반환한다.
    3. charstringindex부터 index + 1까지의 부분 문자열이라고 하자.
    4. indexindex + 1로 설정한다.
    5. char"="이면,
      1. chunkLength < 2이면,
        1. error를 새로 생성된 SyntaxError 객체라고 하자.
        2. Record { [[Read]]: read, [[Bytes]]: bytes, [[Error]]: error }를 반환한다.
      2. indexSkipAsciiWhitespace(string, index)로 설정한다.
      3. chunkLength = 2이면,
        1. index = length이면,
          1. lastChunkHandling"stop-before-partial"이면,
            1. Record { [[Read]]: read, [[Bytes]]: bytes, [[Error]]: none }를 반환한다.
          2. error를 새로 생성된 SyntaxError 객체라고 하자.
          3. Record { [[Read]]: read, [[Bytes]]: bytes, [[Error]]: error }를 반환한다.
        2. charstringindex부터 index + 1까지의 부분 문자열로 설정한다.
        3. char"="이면,
          1. indexSkipAsciiWhitespace(string, index + 1)로 설정한다.
      4. index < length이면,
        1. error를 새로 생성된 SyntaxError 객체라고 하자.
        2. Record { [[Read]]: read, [[Bytes]]: bytes, [[Error]]: error }를 반환한다.
      5. lastChunkHandling"strict"이면 throwOnExtraBitstrue라고 하자; 그렇지 않으면 throwOnExtraBitsfalse라고 하자.
      6. decodeResultCompletion(DecodeFinalBase64Chunk(chunk, throwOnExtraBits))라고 하자.
      7. decodeResultabrupt completion이면,
        1. errordecodeResult.[[Value]]라고 하자.
        2. Record { [[Read]]: read, [[Bytes]]: bytes, [[Error]]: error }를 반환한다.
      8. bytesbytes와 ! decodeResult의 리스트 연결로 설정한다.
      9. Record { [[Read]]: length, [[Bytes]]: bytes, [[Error]]: none }를 반환한다.
    6. alphabet"base64url"이면,
      1. char"+" 또는 "/"이면,
        1. error를 새로 생성된 SyntaxError 객체라고 하자.
        2. Record { [[Read]]: read, [[Bytes]]: bytes, [[Error]]: error }를 반환한다.
      2. 그렇지 않고 char"-"이면,
        1. char"+"로 설정한다.
      3. 그렇지 않고 char"_"이면,
        1. char"/"로 설정한다.
    7. char의 유일한 코드 단위가 표준 base64 알파벳의 요소가 아니면,
      1. error를 새로 생성된 SyntaxError 객체라고 하자.
      2. Record { [[Read]]: read, [[Bytes]]: bytes, [[Error]]: error }를 반환한다.
    8. remainingmaxLength - bytes의 요소 개수라고 하자.
    9. remaining = 1이고 chunkLength = 2이거나, remaining = 2이고 chunkLength = 3이면,
      1. Record { [[Read]]: read, [[Bytes]]: bytes, [[Error]]: none }를 반환한다.
    10. chunkchunkchar의 문자열 연결로 설정한다.
    11. chunkLengthchunk의 길이로 설정한다.
    12. chunkLength = 4이면,
      1. bytesbytesDecodeFullLengthBase64Chunk(chunk)의 리스트 연결로 설정한다.
      2. chunk를 빈 String으로 설정한다.
      3. chunkLength를 0으로 설정한다.
      4. readindex로 설정한다.
      5. bytes의 요소 개수 = maxLength이면,
        1. Record { [[Read]]: read, [[Bytes]]: bytes, [[Error]]: none }를 반환한다.

23.3.3.8 FromHex ( string [ , maxLength ] )

The abstract operation FromHex takes argument string (a String) and optional argument maxLength (a non-negative integer) and returns a Record with fields [[Read]] (an integer), [[Bytes]] (a List of byte values), and [[Error]] (a SyntaxError object or none). It performs the following steps when called:

  1. maxLength가 존재하지 않으면, maxLength를 253 - 1로 설정한다.
  2. lengthstring의 길이라고 하자.
  3. bytes를 새로운 빈 List라고 하자.
  4. read를 0이라고 하자.
  5. length modulo 2 ≠ 0이면,
    1. error를 새로 생성된 SyntaxError 객체라고 하자.
    2. Record { [[Read]]: read, [[Bytes]]: bytes, [[Error]]: error }를 반환한다.
  6. read < length이고 bytes의 요소 개수 < maxLength인 동안 반복한다,
    1. hexitsstringread부터 read + 2까지의 부분 문자열이라고 하자.
    2. hexits"0123456789abcdefABCDEF" 안에 있지 않은 코드 단위를 포함하면,
      1. error를 새로 생성된 SyntaxError 객체라고 하자.
      2. Record { [[Read]]: read, [[Bytes]]: bytes, [[Error]]: error }를 반환한다.
    3. readread + 2로 설정한다.
    4. byte를 10부터 15까지의 값을 가진 숫자에 대해 문자 A부터 Fa부터 f를 사용하여, base-16 표기법으로 hexits가 나타내는 정수 값이라고 하자.
    5. bytebytes에 추가한다.
  7. Record { [[Read]]: read, [[Bytes]]: bytes, [[Error]]: none }를 반환한다.

24 키 기반 컬렉션

24.1 Map 객체

Map은 키와 값이 모두 임의의 ECMAScript 언어 값일 수 있는 키/값 쌍의 컬렉션이다. 서로 다른 키 값은 Map의 컬렉션 안에서 하나의 키/값 쌍에만 나타날 수 있다. 서로 다른 키 값은 SameValueZero 비교 알고리즘의 의미론을 사용하여 구별된다.

Map은 평균적으로 컬렉션의 요소 수에 대해 준선형보다 빠른 접근 시간을 제공하는 해시 테이블이나 다른 메커니즘을 사용하여 구현되어야 한다. 이 명세에서 사용되는 자료 구조는 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. AddEntriesFromIterable(map, iterable, adder)를 반환한다.
Note

매개변수 iterable이 존재하면, Map 키로 사용될 값인 첫 번째 요소와 그 키에 연결할 값인 두 번째 요소를 가진 2요소 배열 유사 객체를 생성하는 iterator 객체를 반환하는 %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 either a normal completion containing an Object or a throw completion. addertarget을 수신자로 하여 호출된다. It performs the following steps when called:

  1. iteratorRecord를 ? GetIterator(iterable, sync)라고 하자.
  2. 반복한다,
    1. next를 ? IteratorStepValue(iteratorRecord)라고 하자.
    2. nextdone이면, target을 반환한다.
    3. next가 Object가 아니면,
      1. errorThrowCompletion(새로 생성된 TypeError 객체)라고 하자.
      2. IteratorClose(iteratorRecord, error)를 반환한다.
    4. keyCompletion(Get(next, "0")).
    5. IfAbruptCloseIterator(key, iteratorRecord).
    6. valueCompletion(Get(next, "1")).
    7. IfAbruptCloseIterator(value, iteratorRecord).
    8. statusCompletion(Call(adder, target, « key, value »))라고 하자.
    9. IfAbruptCloseIterator(status, iteratorRecord).
Note

매개변수 iterable은 Map 키로 사용될 값인 첫 번째 요소와 그 키에 연결할 값인 두 번째 요소를 가진 2요소 배열 유사 객체를 생성하는 iterator 객체를 반환하는 %Symbol.iterator% 메서드를 구현한 객체일 것으로 기대된다.

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. groups의 각 Record { [[Key]], [[Elements]] } group에 대해, 다음을 수행한다.
    1. elementsCreateArrayFromList(group.[[Elements]])라고 하자.
    2. entryRecord { [[Key]]: group.[[Key]], [[Value]]: elements }라고 하자.
    3. entrymap.[[MapData]]에 추가한다.
  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. mapthis 값이라고 하자.
  2. RequireInternalSlot(map, [[MapData]])를 수행한다.
  3. map.[[MapData]]의 각 Record { [[Key]], [[Value]] } entry에 대해, 다음을 수행한다.
    1. entry.[[Key]]empty로 설정한다.
    2. entry.[[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. mapthis 값이라고 하자.
  2. RequireInternalSlot(map, [[MapData]])를 수행한다.
  3. keyCanonicalizeKeyedCollectionKey(key)로 설정한다.
  4. map.[[MapData]]의 각 Record { [[Key]], [[Value]] } entry에 대해, 다음을 수행한다.
    1. entry.[[Key]]empty가 아니고 SameValue(entry.[[Key]], key)가 true이면,
      1. entry.[[Key]]empty로 설정한다.
      2. entry.[[Value]]empty로 설정한다.
      3. true를 반환한다.
  5. false를 반환한다.
Note

empty는 엔트리가 삭제되었음을 나타내기 위한 명세상의 장치로 사용된다. 실제 구현은 내부 자료 구조에서 엔트리를 물리적으로 제거하는 것과 같은 다른 동작을 취할 수 있다.

24.1.3.4 Map.prototype.entries ( )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. mapthis 값이라고 하자.
  2. CreateMapIterator(map, key+value)를 반환한다.

24.1.3.5 Map.prototype.forEach ( callback [ , thisArg ] )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. mapthis 값이라고 하자.
  2. RequireInternalSlot(map, [[MapData]])를 수행한다.
  3. IsCallable(callback)가 false이면, TypeError 예외를 던진다.
  4. entriesmap.[[MapData]]라고 하자.
  5. numEntriesentries의 요소 개수라고 하자.
  6. index를 0이라고 하자.
  7. index < numEntries인 동안 반복한다,
    1. eentries[index]라고 하자.
    2. indexindex + 1로 설정한다.
    3. e.[[Key]]empty가 아니면,
      1. Call(callback, thisArg, « e.[[Value]], e.[[Key]], map »)를 수행한다.
      2. NOTE: callback 실행 중에 entries의 요소 개수가 증가했을 수 있다.
      3. numEntriesentries의 요소 개수로 설정한다.
  8. undefined를 반환한다.
Note

callback은 세 인자를 받는 함수여야 한다. forEach는 Map에 존재하는 각 키/값 쌍에 대해 키 삽입 순서대로 한 번씩 callback을 호출한다. callback은 실제로 존재하는 Map의 키에 대해서만 호출되며, Map에서 삭제된 키에 대해서는 호출되지 않는다.

thisArg 매개변수가 제공되면, callback의 각 호출에서 this 값으로 사용된다. 제공되지 않으면, 대신 undefined가 사용된다.

callback은 항목의 값, 항목의 키, 그리고 순회 중인 Map이라는 세 인자와 함께 호출된다.

forEach는 호출 대상 객체를 직접 변경하지 않지만, callback 호출에 의해 객체가 변경될 수 있다. Map의 [[MapData]]의 각 엔트리는 한 번만 방문된다. forEach 호출이 시작된 뒤 추가된 새 키도 방문된다. 어떤 키가 방문된 뒤 삭제되고 forEach 호출이 완료되기 전에 다시 추가되면 그 키는 다시 방문된다. forEach 호출이 시작된 뒤 방문되기 전에 삭제된 키는 forEach 호출이 완료되기 전에 그 키가 다시 추가되지 않는 한 방문되지 않는다.

24.1.3.6 Map.prototype.get ( key )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. mapthis 값이라고 하자.
  2. RequireInternalSlot(map, [[MapData]])를 수행한다.
  3. keyCanonicalizeKeyedCollectionKey(key)로 설정한다.
  4. map.[[MapData]]의 각 Record { [[Key]], [[Value]] } entry에 대해, 다음을 수행한다.
    1. entry.[[Key]]empty가 아니고 SameValue(entry.[[Key]], key)가 true이면, entry.[[Value]]를 반환한다.
  5. undefined를 반환한다.

24.1.3.7 Map.prototype.getOrInsert ( key, value )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. mapthis 값이라고 하자.
  2. RequireInternalSlot(map, [[MapData]])를 수행한다.
  3. keyCanonicalizeKeyedCollectionKey(key)로 설정한다.
  4. map.[[MapData]]의 각 Record { [[Key]], [[Value]] } entry에 대해, 다음을 수행한다.
    1. entry.[[Key]]empty가 아니고 SameValue(entry.[[Key]], key)가 true이면, entry.[[Value]]를 반환한다.
  5. entryRecord { [[Key]]: key, [[Value]]: value }라고 하자.
  6. entrymap.[[MapData]]에 추가한다.
  7. value를 반환한다.

24.1.3.8 Map.prototype.getOrInsertComputed ( key, callback )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. mapthis 값이라고 하자.
  2. RequireInternalSlot(map, [[MapData]])를 수행한다.
  3. IsCallable(callback)가 false이면, TypeError 예외를 던진다.
  4. keyCanonicalizeKeyedCollectionKey(key)로 설정한다.
  5. map.[[MapData]]의 각 Record { [[Key]], [[Value]] } entry에 대해, 다음을 수행한다.
    1. entry.[[Key]]empty가 아니고 SameValue(entry.[[Key]], key)가 true이면, entry.[[Value]]를 반환한다.
  6. value를 ? Call(callback, undefined, « key »)라고 하자.
  7. NOTE: callback 실행 중에 Map이 변경되었을 수 있다.
  8. map.[[MapData]]의 각 Record { [[Key]], [[Value]] } entry에 대해, 다음을 수행한다.
    1. entry.[[Key]]empty가 아니고 SameValue(entry.[[Key]], key)가 true이면,
      1. entry.[[Value]]value로 설정한다.
      2. value를 반환한다.
  9. entryRecord { [[Key]]: key, [[Value]]: value }라고 하자.
  10. entrymap.[[MapData]]에 추가한다.
  11. value를 반환한다.

24.1.3.9 Map.prototype.has ( key )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. mapthis 값이라고 하자.
  2. RequireInternalSlot(map, [[MapData]])를 수행한다.
  3. keyCanonicalizeKeyedCollectionKey(key)로 설정한다.
  4. map.[[MapData]]의 각 Record { [[Key]], [[Value]] } entry에 대해, 다음을 수행한다.
    1. entry.[[Key]]empty가 아니고 SameValue(entry.[[Key]], key)가 true이면, true를 반환한다.
  5. false를 반환한다.

24.1.3.10 Map.prototype.keys ( )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. mapthis 값이라고 하자.
  2. CreateMapIterator(map, key)를 반환한다.

24.1.3.11 Map.prototype.set ( key, value )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. mapthis 값이라고 하자.
  2. RequireInternalSlot(map, [[MapData]])를 수행한다.
  3. keyCanonicalizeKeyedCollectionKey(key)로 설정한다.
  4. map.[[MapData]]의 각 Record { [[Key]], [[Value]] } entry에 대해, 다음을 수행한다.
    1. entry.[[Key]]empty가 아니고 SameValue(entry.[[Key]], key)가 true이면,
      1. entry.[[Value]]value로 설정한다.
      2. map을 반환한다.
  5. entryRecord { [[Key]]: key, [[Value]]: value }라고 하자.
  6. entrymap.[[MapData]]에 추가한다.
  7. map을 반환한다.

24.1.3.12 get Map.prototype.size

Map.prototype.size는 set 접근자 함수가 undefined인 접근자 속성이다. 그 get 접근자 함수는 호출될 때 다음 단계를 수행한다:

  1. mapthis 값이라고 하자.
  2. RequireInternalSlot(map, [[MapData]])를 수행한다.
  3. count를 0이라고 하자.
  4. map.[[MapData]]의 각 Record { [[Key]], [[Value]] } entry에 대해, 다음을 수행한다.
    1. entry.[[Key]]empty가 아니면, countcount + 1로 설정한다.
  5. 𝔽(count)를 반환한다.

24.1.3.13 Map.prototype.values ( )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. mapthis 값이라고 하자.
  2. CreateMapIterator(map, value)를 반환한다.

24.1.3.14 Map.prototype [ %Symbol.iterator% ] ( )

%Symbol.iterator% 속성의 초기값은 24.1.3.4에 정의된 %Map.prototype.entries%이다.

24.1.3.15 Map.prototype [ %Symbol.toStringTag% ]

%Symbol.toStringTag% 속성의 초기값은 String 값 "Map"이다.

이 속성은 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true } 속성 특성을 가진다.

24.1.4 Map 인스턴스의 속성

Map 인스턴스는 Map 프로토타입 객체로부터 속성을 상속하는 보통 객체이다. Map 인스턴스는 또한 [[MapData]] 내부 슬롯을 가진다.

24.1.5 Map Iterator 객체

Map Iterator는 어떤 특정 Map 인스턴스 객체에 대한 특정 반복을 나타내는 객체이다. Map Iterator 객체에는 이름 있는 생성자가 없다. 대신, 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 either a normal completion containing a Generator or a throw completion. 그러한 반복자를 반환하는 Map 메서드를 위한 iterator 객체를 생성하는 데 사용된다. It performs the following steps when called:

  1. RequireInternalSlot(map, [[MapData]])를 수행한다.
  2. closuremapkind를 캡처하고 호출될 때 다음 단계를 수행하는, 매개변수가 없는 새로운 Abstract Closure라고 하자:
    1. entriesmap.[[MapData]]라고 하자.
    2. index를 0이라고 하자.
    3. numEntriesentries의 요소 개수라고 하자.
    4. index < numEntries인 동안 반복한다,
      1. entryentries[index]라고 하자.
      2. indexindex + 1로 설정한다.
      3. entry.[[Key]]empty가 아니면,
        1. kindkey이면,
          1. resultentry.[[Key]]라고 하자.
        2. 그렇지 않고 kindvalue이면,
          1. resultentry.[[Value]]라고 하자.
        3. 그렇지 않으면,
          1. Assert: kindkey+value이다.
          2. resultCreateArrayFromListentry.[[Key]], entry.[[Value]] »)라고 하자.
        4. GeneratorYield(CreateIteratorResultObject(result, false))를 수행한다.
        5. NOTE: GeneratorYield에 의해 이 추상 연산의 실행이 일시 중단된 동안 entries의 요소 개수가 증가했을 수 있다.
        6. numEntriesentries의 요소 개수로 설정한다.
    5. NormalCompletion(unused)를 반환한다.
  3. CreateIteratorFromClosure(closure, "%MapIteratorPrototype%", %MapIteratorPrototype%)를 반환한다.

24.1.5.2 %MapIteratorPrototype% 객체

%MapIteratorPrototype% 객체는:

  • 모든 Map Iterator 객체가 상속하는 속성을 가진다.
  • 보통 객체이다.
  • 값이 %Iterator.prototype%[[Prototype]] 내부 슬롯을 가진다.
  • 다음 속성들을 가진다:

24.1.5.2.1 %MapIteratorPrototype%.next ( )

  1. 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 Records

Set Record는 Set 또는 유사 객체의 인터페이스를 캡슐화하는 데 사용되는 Record 값이다.

Set Record는 Table 71에 나열된 필드를 가진다.

Table 71: Set Record 필드
필드 이름 의미
[[SetObject]] Object Set 또는 유사 객체.
[[Size]] 음이 아닌 정수 또는 +∞ 객체의 보고된 크기.
[[Has]] 함수 객체 객체의 has 메서드.
[[Keys]] 함수 객체 객체의 keys 메서드.

24.2.1.2 GetSetRecord ( obj )

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

  1. obj가 Object가 아니면, TypeError 예외를 던진다.
  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 a Boolean. It performs the following steps when called:

  1. SetDataIndex(setData, value)가 not-found이면, false를 반환한다.
  2. true를 반환한다.

24.2.1.4 SetDataIndex ( setData, value )

The abstract operation SetDataIndex takes arguments setData (a List of either ECMAScript language values or empty) and value (an ECMAScript language value) and returns a non-negative integer or not-found. It performs the following steps when called:

  1. valueCanonicalizeKeyedCollectionKey(value)로 설정한다.
  2. sizesetData의 요소 개수라고 하자.
  3. index를 0이라고 하자.
  4. index < size인 동안 반복한다,
    1. esetData[index]라고 하자.
    2. eempty가 아니고 evalue이면,
      1. index를 반환한다.
    3. indexindex + 1로 설정한다.
  5. not-found를 반환한다.

24.2.1.5 SetDataSize ( setData )

The abstract operation SetDataSize takes argument setData (a List of either ECMAScript language values or empty) and returns a non-negative integer. It performs the following steps when called:

  1. count를 0이라고 하자.
  2. setData의 각 요소 e에 대해, 다음을 수행한다.
    1. eempty가 아니면, countcount + 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. statusCompletion(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. setthis 값이라고 하자.
  2. RequireInternalSlot(set, [[SetData]])를 수행한다.
  3. valueCanonicalizeKeyedCollectionKey(value)로 설정한다.
  4. set.[[SetData]]의 각 요소 entry에 대해, 다음을 수행한다.
    1. entryempty가 아니고 SameValue(entry, value)가 true이면,
      1. set을 반환한다.
  5. valueset.[[SetData]]에 추가한다.
  6. set을 반환한다.

24.2.4.2 Set.prototype.clear ( )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. setthis 값이라고 하자.
  2. RequireInternalSlot(set, [[SetData]])를 수행한다.
  3. set.[[SetData]]의 각 요소 entry에 대해, 다음을 수행한다.
    1. 값이 entryset.[[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. setthis 값이라고 하자.
  2. RequireInternalSlot(set, [[SetData]])를 수행한다.
  3. valueCanonicalizeKeyedCollectionKey(value)로 설정한다.
  4. set.[[SetData]]의 각 요소 entry에 대해, 다음을 수행한다.
    1. entryempty가 아니고 SameValue(entry, value)가 true이면,
      1. 값이 entryset.[[SetData]]의 요소를 값이 empty인 요소로 대체한다.
      2. true를 반환한다.
  5. false를 반환한다.
Note

empty는 엔트리가 삭제되었음을 나타내기 위한 명세상의 장치로 사용된다. 실제 구현은 내부 자료 구조에서 엔트리를 물리적으로 제거하는 것과 같은 다른 동작을 취할 수 있다.

24.2.4.5 Set.prototype.difference ( other )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. setthis 값이라고 하자.
  2. RequireInternalSlot(set, [[SetData]])를 수행한다.
  3. otherRec를 ? GetSetRecord(other)라고 하자.
  4. resultSetDataset.[[SetData]]의 사본이라고 하자.
  5. SetDataSize(set.[[SetData]]) ≤ otherRec.[[Size]]이면,
    1. thisSizeset.[[SetData]]의 요소 개수라고 하자.
    2. index를 0이라고 하자.
    3. index < thisSize인 동안 반복한다,
      1. entryresultSetData[index]라고 하자.
      2. entryempty가 아니면,
        1. inOtherToBoolean(? Call(otherRec.[[Has]], otherRec.[[SetObject]], « entry »))라고 하자.
        2. inOthertrue이면,
          1. resultSetData[index]를 empty로 설정한다.
      3. indexindex + 1로 설정한다.
  6. 그렇지 않으면,
    1. keysIter를 ? GetIteratorFromMethod(otherRec.[[SetObject]], otherRec.[[Keys]])라고 하자.
    2. nextnot-started라고 하자.
    3. nextdone이 아닌 동안 반복한다,
      1. next를 ? IteratorStepValue(keysIter)로 설정한다.
      2. nextdone이 아니면,
        1. nextCanonicalizeKeyedCollectionKey(next)로 설정한다.
        2. valueIndexSetDataIndex(resultSetData, next)라고 하자.
        3. valueIndexnot-found가 아니면,
          1. resultSetData[valueIndex]를 empty로 설정한다.
  7. resultOrdinaryObjectCreate(%Set.prototype%, « [[SetData]] »)라고 하자.
  8. result.[[SetData]]resultSetData로 설정한다.
  9. result를 반환한다.

24.2.4.6 Set.prototype.entries ( )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. setthis 값이라고 하자.
  2. CreateSetIterator(set, key+value)를 반환한다.
Note

반복 목적상 Set은 각 엔트리가 키와 값으로 같은 값을 가지는 Map과 유사하게 보인다.

24.2.4.7 Set.prototype.forEach ( callback [ , thisArg ] )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. setthis 값이라고 하자.
  2. RequireInternalSlot(set, [[SetData]])를 수행한다.
  3. IsCallable(callback)가 false이면, TypeError 예외를 던진다.
  4. entriesset.[[SetData]]라고 하자.
  5. numEntriesentries의 요소 개수라고 하자.
  6. index를 0이라고 하자.
  7. index < numEntries인 동안 반복한다,
    1. entryentries[index]라고 하자.
    2. indexindex + 1로 설정한다.
    3. entryempty가 아니면,
      1. Call(callback, thisArg, « entry, entry, set »)를 수행한다.
      2. NOTE: callback 실행 중에 entries의 요소 개수가 증가했을 수 있다.
      3. numEntriesentries의 요소 개수로 설정한다.
  8. undefined를 반환한다.
Note

callback은 세 인자를 받는 함수여야 한다. forEachSet 객체에 존재하는 각 값에 대해 값 삽입 순서대로 한 번씩 callback을 호출한다. callback은 실제로 존재하는 Set의 값에 대해서만 호출되며, set에서 삭제된 키에 대해서는 호출되지 않는다.

thisArg 매개변수가 제공되면, callback의 각 호출에서 this 값으로 사용된다. 제공되지 않으면, 대신 undefined가 사용된다.

callback은 세 인자와 함께 호출된다: 첫 두 인자는 Set에 포함된 값이다. 두 인자 모두에 같은 값이 전달된다. 순회 중인 Set 객체가 세 번째 인자로 전달된다.

callback은 Map과 Array의 forEach 메서드가 사용하는 콜백 함수와 일관되도록 세 인자와 함께 호출된다. Set의 경우, 각 항목 값은 키이자 값으로 간주된다.

forEach는 호출 대상 객체를 직접 변경하지 않지만, callback 호출에 의해 객체가 변경될 수 있다.

각 값은 보통 한 번만 방문된다. 그러나 어떤 값이 방문된 뒤 삭제되고 forEach 호출이 완료되기 전에 다시 추가되면 그 값은 다시 방문된다. forEach 호출이 시작된 뒤 방문되기 전에 삭제된 값은 forEach 호출이 완료되기 전에 그 값이 다시 추가되지 않는 한 방문되지 않는다. forEach 호출이 시작된 뒤 추가된 새 값은 방문된다.

24.2.4.8 Set.prototype.has ( value )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. setthis 값이라고 하자.
  2. RequireInternalSlot(set, [[SetData]])를 수행한다.
  3. valueCanonicalizeKeyedCollectionKey(value)로 설정한다.
  4. set.[[SetData]]의 각 요소 entry에 대해, 다음을 수행한다.
    1. entryempty가 아니고 SameValue(entry, value)가 true이면, true를 반환한다.
  5. false를 반환한다.

24.2.4.9 Set.prototype.intersection ( other )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. setthis 값이라고 하자.
  2. RequireInternalSlot(set, [[SetData]])를 수행한다.
  3. otherRec를 ? GetSetRecord(other)라고 하자.
  4. resultSetData를 새로운 빈 List라고 하자.
  5. SetDataSize(set.[[SetData]]) ≤ otherRec.[[Size]]이면,
    1. thisSizeset.[[SetData]]의 요소 개수라고 하자.
    2. index를 0이라고 하자.
    3. index < thisSize인 동안 반복한다,
      1. entryset.[[SetData]][index]라고 하자.
      2. indexindex + 1로 설정한다.
      3. entryempty가 아니면,
        1. inOtherToBoolean(? Call(otherRec.[[Has]], otherRec.[[SetObject]], « entry »))라고 하자.
        2. inOthertrue이면,
          1. NOTE: 이전의 otherRec.[[Has]] 호출이 set.[[SetData]]의 요소를 제거하고 다시 추가할 수 있으며, 이는 이 반복 중 같은 요소가 두 번 방문되게 할 수 있다.
          2. SetDataHas(resultSetData, entry)가 false이면,
            1. entryresultSetData에 추가한다.
        3. NOTE: otherRec.[[Has]] 실행 중에 set.[[SetData]]의 요소 개수가 증가했을 수 있다.
        4. thisSizeset.[[SetData]]의 요소 개수로 설정한다.
  6. 그렇지 않으면,
    1. keysIter를 ? GetIteratorFromMethod(otherRec.[[SetObject]], otherRec.[[Keys]])라고 하자.
    2. nextnot-started라고 하자.
    3. nextdone이 아닌 동안 반복한다,
      1. next를 ? IteratorStepValue(keysIter)로 설정한다.
      2. nextdone이 아니면,
        1. nextCanonicalizeKeyedCollectionKey(next)로 설정한다.
        2. inThisSetDataHas(set.[[SetData]], next)라고 하자.
        3. inThistrue이면,
          1. NOTE: other는 임의의 객체이므로, 그 "keys" iterator가 같은 값을 두 번 이상 생성할 수 있다.
          2. SetDataHas(resultSetData, next)가 false이면,
            1. nextresultSetData에 추가한다.
  7. resultOrdinaryObjectCreate(%Set.prototype%, « [[SetData]] »)라고 하자.
  8. result.[[SetData]]resultSetData로 설정한다.
  9. result를 반환한다.

24.2.4.10 Set.prototype.isDisjointFrom ( other )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. setthis 값이라고 하자.
  2. RequireInternalSlot(set, [[SetData]])를 수행한다.
  3. otherRec를 ? GetSetRecord(other)라고 하자.
  4. SetDataSize(set.[[SetData]]) ≤ otherRec.[[Size]]이면,
    1. thisSizeset.[[SetData]]의 요소 개수라고 하자.
    2. index를 0이라고 하자.
    3. index < thisSize인 동안 반복한다,
      1. entryset.[[SetData]][index]라고 하자.
      2. indexindex + 1로 설정한다.
      3. entryempty가 아니면,
        1. inOtherToBoolean(? Call(otherRec.[[Has]], otherRec.[[SetObject]], « entry »))라고 하자.
        2. inOthertrue이면, false를 반환한다.
        3. NOTE: otherRec.[[Has]] 실행 중에 set.[[SetData]]의 요소 개수가 증가했을 수 있다.
        4. thisSizeset.[[SetData]]의 요소 개수로 설정한다.
  5. 그렇지 않으면,
    1. keysIter를 ? GetIteratorFromMethod(otherRec.[[SetObject]], otherRec.[[Keys]])라고 하자.
    2. nextnot-started라고 하자.
    3. nextdone이 아닌 동안 반복한다,
      1. next를 ? IteratorStepValue(keysIter)로 설정한다.
      2. nextdone이 아니면,
        1. SetDataHas(set.[[SetData]], next)가 true이면,
          1. IteratorClose(keysIter, NormalCompletion(unused))를 수행한다.
          2. false를 반환한다.
  6. true를 반환한다.

24.2.4.11 Set.prototype.isSubsetOf ( other )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. setthis 값이라고 하자.
  2. RequireInternalSlot(set, [[SetData]])를 수행한다.
  3. otherRec를 ? GetSetRecord(other)라고 하자.
  4. SetDataSize(set.[[SetData]]) > otherRec.[[Size]]이면, false를 반환한다.
  5. thisSizeset.[[SetData]]의 요소 개수라고 하자.
  6. index를 0이라고 하자.
  7. index < thisSize인 동안 반복한다,
    1. entryset.[[SetData]][index]라고 하자.
    2. indexindex + 1로 설정한다.
    3. entryempty가 아니면,
      1. inOtherToBoolean(? Call(otherRec.[[Has]], otherRec.[[SetObject]], « entry »))라고 하자.
      2. inOtherfalse이면, false를 반환한다.
      3. NOTE: otherRec.[[Has]] 실행 중에 set.[[SetData]]의 요소 개수가 증가했을 수 있다.
      4. thisSizeset.[[SetData]]의 요소 개수로 설정한다.
  8. true를 반환한다.

24.2.4.12 Set.prototype.isSupersetOf ( other )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. setthis 값이라고 하자.
  2. RequireInternalSlot(set, [[SetData]])를 수행한다.
  3. otherRec를 ? GetSetRecord(other)라고 하자.
  4. SetDataSize(set.[[SetData]]) < otherRec.[[Size]]이면, false를 반환한다.
  5. keysIter를 ? GetIteratorFromMethod(otherRec.[[SetObject]], otherRec.[[Keys]])라고 하자.
  6. nextnot-started라고 하자.
  7. nextdone이 아닌 동안 반복한다,
    1. next를 ? IteratorStepValue(keysIter)로 설정한다.
    2. nextdone이 아니면,
      1. SetDataHas(set.[[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. setthis 값이라고 하자.
  2. RequireInternalSlot(set, [[SetData]])를 수행한다.
  3. sizeSetDataSize(set.[[SetData]])라고 하자.
  4. 𝔽(size)를 반환한다.

24.2.4.15 Set.prototype.symmetricDifference ( other )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. setthis 값이라고 하자.
  2. RequireInternalSlot(set, [[SetData]])를 수행한다.
  3. otherRec를 ? GetSetRecord(other)라고 하자.
  4. keysIter를 ? GetIteratorFromMethod(otherRec.[[SetObject]], otherRec.[[Keys]])라고 하자.
  5. resultSetDataset.[[SetData]]의 사본이라고 하자.
  6. nextnot-started라고 하자.
  7. nextdone이 아닌 동안 반복한다,
    1. next를 ? IteratorStepValue(keysIter)로 설정한다.
    2. nextdone이 아니면,
      1. nextCanonicalizeKeyedCollectionKey(next)로 설정한다.
      2. resultIndexSetDataIndex(resultSetData, next)라고 하자.
      3. resultIndexnot-found이면 alreadyInResultfalse라고 하자; 그렇지 않으면 alreadyInResulttrue라고 하자.
      4. SetDataHas(set.[[SetData]], next)가 true이면,
        1. alreadyInResulttrue이면, resultSetData[resultIndex]를 empty로 설정한다.
      5. 그렇지 않으면,
        1. alreadyInResultfalse이면, nextresultSetData에 추가한다.
  8. resultOrdinaryObjectCreate(%Set.prototype%, « [[SetData]] »)라고 하자.
  9. result.[[SetData]]resultSetData로 설정한다.
  10. result를 반환한다.

24.2.4.16 Set.prototype.union ( other )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. setthis 값이라고 하자.
  2. RequireInternalSlot(set, [[SetData]])를 수행한다.
  3. otherRec를 ? GetSetRecord(other)라고 하자.
  4. keysIter를 ? GetIteratorFromMethod(otherRec.[[SetObject]], otherRec.[[Keys]])라고 하자.
  5. resultSetDataset.[[SetData]]의 사본이라고 하자.
  6. nextnot-started라고 하자.
  7. nextdone이 아닌 동안 반복한다,
    1. next를 ? IteratorStepValue(keysIter)로 설정한다.
    2. nextdone이 아니면,
      1. nextCanonicalizeKeyedCollectionKey(next)로 설정한다.
      2. SetDataHas(resultSetData, next)가 false이면,
        1. nextresultSetData에 추가한다.
  8. resultOrdinaryObjectCreate(%Set.prototype%, « [[SetData]] »)라고 하자.
  9. result.[[SetData]]resultSetData로 설정한다.
  10. result를 반환한다.

24.2.4.17 Set.prototype.values ( )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. setthis 값이라고 하자.
  2. CreateSetIterator(set, 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 프로토타입 객체로부터 속성을 상속하는 보통 객체이다. Set 인스턴스는 또한 [[SetData]] 내부 슬롯을 가진다.

24.2.6 Set Iterator 객체

Set Iterator는 아래에 정의된 구조를 가지는 보통 객체로, 어떤 특정 Set 인스턴스 객체에 대한 특정 반복을 나타낸다. Set Iterator 객체에는 이름 있는 생성자가 없다. 대신, 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 either a normal completion containing a Generator or a throw completion. 그러한 반복자를 반환하는 Set 메서드를 위한 iterator 객체를 생성하는 데 사용된다. It performs the following steps when called:

  1. RequireInternalSlot(set, [[SetData]])를 수행한다.
  2. closuresetkind를 캡처하고 호출될 때 다음 단계를 수행하는, 매개변수가 없는 새로운 Abstract Closure라고 하자:
    1. index를 0이라고 하자.
    2. entriesset.[[SetData]]라고 하자.
    3. numEntriesentries의 요소 개수라고 하자.
    4. index < numEntries인 동안 반복한다,
      1. entryentries[index]라고 하자.
      2. indexindex + 1로 설정한다.
      3. entryempty가 아니면,
        1. kindkey+value이면,
          1. resultCreateArrayFromListentry, entry »)라고 하자.
          2. GeneratorYield(CreateIteratorResultObject(result, false))를 수행한다.
        2. 그렇지 않으면,
          1. Assert: kindvalue이다.
          2. GeneratorYield(CreateIteratorResultObject(entry, false))를 수행한다.
        3. NOTE: GeneratorYield에 의해 이 추상 연산의 실행이 일시 중단된 동안 entries의 요소 개수가 증가했을 수 있다.
        4. numEntriesentries의 요소 개수로 설정한다.
    5. NormalCompletion(unused)를 반환한다.
  3. CreateIteratorFromClosure(closure, "%SetIteratorPrototype%", %SetIteratorPrototype%)를 반환한다.

24.2.6.2 %SetIteratorPrototype% 객체

%SetIteratorPrototype% 객체는:

  • 모든 Set Iterator 객체가 상속하는 속성을 가진다.
  • 보통 객체이다.
  • 값이 %Iterator.prototype%[[Prototype]] 내부 슬롯을 가진다.
  • 다음 속성들을 가진다:

24.2.6.2.1 %SetIteratorPrototype%.next ( )

  1. 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의 키/값 쌍이 접근 불가능해진 시점과 그 키/값 쌍이 WeakMap에서 제거되는 시점 사이에 임의로 결정된 지연을 부과할 수 있다. 이 지연이 ECMAScript 프로그램에 관찰 가능하다면, 프로그램 실행에 영향을 줄 수 있는 비결정성의 원천이 될 것이다. 그러므로 ECMAScript 구현은 관찰자가 관찰되는 키를 제시할 것을 요구하지 않는 방식으로 WeakMap의 키를 관찰할 수단을 제공해서는 안 된다.

WeakMap은 평균적으로 컬렉션의 키/값 쌍 수에 대해 준선형보다 빠른 접근 시간을 제공하는 해시 테이블이나 다른 메커니즘을 사용하여 구현되어야 한다. 이 명세에서 사용되는 자료 구조는 WeakMap의 요구되는 관찰 가능한 의미론을 설명하기 위한 것일 뿐이다. 실행 가능한 구현 모델로 의도된 것이 아니다.

Note

WeakMap과 WeakSet은, WeakMap 또는 WeakSet 인스턴스가 없었다면 객체 또는 심벌이 다른 방식으로 접근 불가능해져 구현의 가비지 컬렉션 메커니즘에 의해 자원 회수 대상이 되었을 경우 메모리 자원을 “누수”하지 않는 방식으로, 객체 또는 심벌에 상태를 동적으로 연결하는 메커니즘을 제공하기 위한 것이다. 이 특성은 WeakMap 또는 WeakSet 인스턴스에서 키로의 역방향 객체별/심벌별 매핑을 사용하여 달성할 수 있다. 또는 각 WeakMap 또는 WeakSet 인스턴스가 내부적으로 키와 값 데이터를 저장할 수도 있지만, 이 접근 방식은 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. AddEntriesFromIterable(map, iterable, adder)를 반환한다.
Note

매개변수 iterable이 존재하면, WeakMap 키로 사용될 값인 첫 번째 요소와 그 키에 연결할 값인 두 번째 요소를 가진 2요소 배열 유사 객체를 생성하는 iterator 객체를 반환하는 %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. weakMapthis 값이라고 하자.
  2. RequireInternalSlot(weakMap, [[WeakMapData]])를 수행한다.
  3. CanBeHeldWeakly(key)가 false이면, false를 반환한다.
  4. weakMap.[[WeakMapData]]의 각 Record { [[Key]], [[Value]] } entry에 대해, 다음을 수행한다.
    1. entry.[[Key]]empty가 아니고 SameValue(entry.[[Key]], key)가 true이면,
      1. entry.[[Key]]empty로 설정한다.
      2. entry.[[Value]]empty로 설정한다.
      3. true를 반환한다.
  5. false를 반환한다.
Note

empty는 엔트리가 삭제되었음을 나타내기 위한 명세상의 장치로 사용된다. 실제 구현은 내부 자료 구조에서 엔트리를 물리적으로 제거하는 것과 같은 다른 동작을 취할 수 있다.

24.3.3.3 WeakMap.prototype.get ( key )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. weakMapthis 값이라고 하자.
  2. RequireInternalSlot(weakMap, [[WeakMapData]])를 수행한다.
  3. CanBeHeldWeakly(key)가 false이면, undefined를 반환한다.
  4. weakMap.[[WeakMapData]]의 각 Record { [[Key]], [[Value]] } entry에 대해, 다음을 수행한다.
    1. entry.[[Key]]empty가 아니고 SameValue(entry.[[Key]], key)가 true이면, entry.[[Value]]를 반환한다.
  5. undefined를 반환한다.

24.3.3.4 WeakMap.prototype.getOrInsert ( key, value )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. weakMapthis 값이라고 하자.
  2. RequireInternalSlot(weakMap, [[WeakMapData]])를 수행한다.
  3. CanBeHeldWeakly(key)가 false이면, TypeError 예외를 던진다.
  4. weakMap.[[WeakMapData]]의 각 Record { [[Key]], [[Value]] } entry에 대해, 다음을 수행한다.
    1. entry.[[Key]]empty가 아니고 SameValue(entry.[[Key]], key)가 true이면, entry.[[Value]]를 반환한다.
  5. entryRecord { [[Key]]: key, [[Value]]: value }라고 하자.
  6. entryweakMap.[[WeakMapData]]에 추가한다.
  7. value를 반환한다.

24.3.3.5 WeakMap.prototype.getOrInsertComputed ( key, callback )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. weakMapthis 값이라고 하자.
  2. RequireInternalSlot(weakMap, [[WeakMapData]])를 수행한다.
  3. CanBeHeldWeakly(key)가 false이면, TypeError 예외를 던진다.
  4. IsCallable(callback)가 false이면, TypeError 예외를 던진다.
  5. weakMap.[[WeakMapData]]의 각 Record { [[Key]], [[Value]] } entry에 대해, 다음을 수행한다.
    1. entry.[[Key]]empty가 아니고 SameValue(entry.[[Key]], key)가 true이면, entry.[[Value]]를 반환한다.
  6. value를 ? Call(callback, undefined, « key »)라고 하자.
  7. NOTE: callback 실행 중에 WeakMap이 변경되었을 수 있다.
  8. weakMap.[[WeakMapData]]의 각 Record { [[Key]], [[Value]] } entry에 대해, 다음을 수행한다.
    1. entry.[[Key]]empty가 아니고 SameValue(entry.[[Key]], key)가 true이면,
      1. entry.[[Value]]value로 설정한다.
      2. value를 반환한다.
  9. entryRecord { [[Key]]: key, [[Value]]: value }라고 하자.
  10. entryweakMap.[[WeakMapData]]에 추가한다.
  11. value를 반환한다.

24.3.3.6 WeakMap.prototype.has ( key )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. weakMapthis 값이라고 하자.
  2. RequireInternalSlot(weakMap, [[WeakMapData]])를 수행한다.
  3. CanBeHeldWeakly(key)가 false이면, false를 반환한다.
  4. weakMap.[[WeakMapData]]의 각 Record { [[Key]], [[Value]] } entry에 대해, 다음을 수행한다.
    1. entry.[[Key]]empty가 아니고 SameValue(entry.[[Key]], key)가 true이면, true를 반환한다.
  5. false를 반환한다.

24.3.3.7 WeakMap.prototype.set ( key, value )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. weakMapthis 값이라고 하자.
  2. RequireInternalSlot(weakMap, [[WeakMapData]])를 수행한다.
  3. CanBeHeldWeakly(key)가 false이면, TypeError 예외를 던진다.
  4. weakMap.[[WeakMapData]]의 각 Record { [[Key]], [[Value]] } entry에 대해, 다음을 수행한다.
    1. entry.[[Key]]empty가 아니고 SameValue(entry.[[Key]], key)가 true이면,
      1. entry.[[Value]]value로 설정한다.
      2. weakMap을 반환한다.
  5. entryRecord { [[Key]]: key, [[Value]]: value }라고 하자.
  6. entryweakMap.[[WeakMapData]]에 추가한다.
  7. weakMap을 반환한다.

24.3.3.8 WeakMap.prototype [ %Symbol.toStringTag% ]

%Symbol.toStringTag% 속성의 초기값은 String 값 "WeakMap"이다.

이 속성은 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true } 속성 특성을 가진다.

24.3.4 WeakMap 인스턴스의 속성

WeakMap 인스턴스는 WeakMap 프로토타입 객체로부터 속성을 상속하는 보통 객체이다. WeakMap 인스턴스는 또한 [[WeakMapData]] 내부 슬롯을 가진다.

24.4 WeakSet 객체

WeakSet은 객체 및/또는 심벌의 컬렉션이다. 서로 다른 객체 또는 심벌은 WeakSet의 컬렉션의 요소로 한 번만 나타날 수 있다. WeakSet은 특정 값을 포함하는지 조회할 수 있지만, 보유한 값들을 열거하는 메커니즘은 제공되지 않는다. 특정 조건에서는 live가 아닌 값들이 9.9.3에 설명된 대로 WeakSet 요소에서 제거된다.

구현은 WeakSet에 포함된 값이 접근 불가능해진 시점과 그 값이 WeakSet에서 제거되는 시점 사이에 임의로 결정된 지연을 부과할 수 있다. 이 지연이 ECMAScript 프로그램에 관찰 가능하다면, 프로그램 실행에 영향을 줄 수 있는 비결정성의 원천이 될 것이다. 그러므로 ECMAScript 구현은 관찰자가 관찰되는 값을 제시할 것을 요구하지 않는 방식으로 WeakSet이 특정 값을 포함하는지 결정할 수단을 제공해서는 안 된다.

WeakSet은 평균적으로 컬렉션의 요소 수에 대해 준선형보다 빠른 접근 시간을 제공하는 해시 테이블이나 다른 메커니즘을 사용하여 구현되어야 한다. 이 명세에서 사용되는 자료 구조는 WeakSet의 요구되는 관찰 가능한 의미론을 설명하기 위한 것일 뿐이다. 실행 가능한 구현 모델로 의도된 것이 아니다.

Note

24.3NOTE를 보라.

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. statusCompletion(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. weakSetthis 값이라고 하자.
  2. RequireInternalSlot(weakSet, [[WeakSetData]])를 수행한다.
  3. CanBeHeldWeakly(value)가 false이면, TypeError 예외를 던진다.
  4. weakSet.[[WeakSetData]]의 각 요소 entry에 대해, 다음을 수행한다.
    1. entryempty가 아니고 SameValue(entry, value)가 true이면,
      1. weakSet을 반환한다.
  5. valueweakSet.[[WeakSetData]]에 추가한다.
  6. weakSet을 반환한다.

24.4.3.2 WeakSet.prototype.constructor

WeakSet.prototype.constructor의 초기값은 %WeakSet%이다.

24.4.3.3 WeakSet.prototype.delete ( value )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. weakSetthis 값이라고 하자.
  2. RequireInternalSlot(weakSet, [[WeakSetData]])를 수행한다.
  3. CanBeHeldWeakly(value)가 false이면, false를 반환한다.
  4. weakSet.[[WeakSetData]]의 각 요소 entry에 대해, 다음을 수행한다.
    1. entryempty가 아니고 SameValue(entry, value)가 true이면,
      1. 값이 entryweakSet.[[WeakSetData]]의 요소를 값이 empty인 요소로 대체한다.
      2. true를 반환한다.
  5. false를 반환한다.
Note

empty는 엔트리가 삭제되었음을 나타내기 위한 명세상의 장치로 사용된다. 실제 구현은 내부 자료 구조에서 엔트리를 물리적으로 제거하는 것과 같은 다른 동작을 취할 수 있다.

24.4.3.4 WeakSet.prototype.has ( value )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. weakSetthis 값이라고 하자.
  2. RequireInternalSlot(weakSet, [[WeakSetData]])를 수행한다.
  3. CanBeHeldWeakly(value)가 false이면, false를 반환한다.
  4. weakSet.[[WeakSetData]]의 각 요소 entry에 대해, 다음을 수행한다.
    1. entryempty가 아니고 SameValue(entry, 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 프로토타입 객체로부터 속성을 상속하는 보통 객체이다. 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 구조화된 데이터

25.1 ArrayBuffer 객체

25.1.1 표기법

이 절, 25.4, 그리고 29의 아래 설명들은 read-modify-write 수정 함수 내부 자료 구조를 사용한다.

read-modify-write 수정 함수는 바이트 값의 두 List를 인자로 받아 바이트 값의 List를 반환하는 Abstract Closure로 표현되는 수학적 함수이다. 이러한 Abstract Closure들은 다음 속성을 모두 만족한다:

  • 자신의 모든 알고리즘 단계를 원자적으로 수행한다.
  • 자신의 개별 알고리즘 단계는 관찰 가능하지 않다.
Note

read-modify-write 수정 함수의 알고리즘 단계들이 순수한 수학적 함수를 구성하는지 검증하는 데 도움을 주기 위해, 다음 편집상 규약이 권장된다:

25.1.2 고정 길이 및 크기 조절 가능 ArrayBuffer 객체

고정 길이 ArrayBuffer는 생성 후 바이트 길이가 변경될 수 없는 ArrayBuffer이다.

크기 조절 가능 ArrayBuffer는 생성 후 ArrayBuffer.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 either a normal completion containing an ArrayBuffer or a throw completion. ArrayBuffer를 생성하는 데 사용된다. It performs the following steps when called:

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

25.1.3.2 ArrayBufferByteLength ( arrayBuffer, order )

The abstract operation ArrayBufferByteLength takes arguments arrayBuffer (an ArrayBuffer or SharedArrayBuffer) and order (seq-cst or unordered) and returns a non-negative integer. It performs the following steps when called:

  1. IsGrowableSharedArrayBuffer(arrayBuffer)가 true이면,
    1. bufferByteLengthBlockarrayBuffer.[[ArrayBufferByteLengthData]]라고 하자.
    2. rawLengthGetRawBytesFromSharedBlock(bufferByteLengthBlock, 0, biguint64, true, order)라고 하자.
    3. agentRecord를 주변 agent의 Agent Record라고 하자.
    4. isLittleEndianagentRecord.[[LittleEndian]]이라고 하자.
    5. (RawBytesToNumeric(biguint64, rawLength, isLittleEndian))를 반환한다.
  2. Assert: IsDetachedBuffer(arrayBuffer)는 false이다.
  3. arrayBuffer.[[ArrayBufferByteLength]]를 반환한다.

25.1.3.3 ArrayBufferCopyAndDetach ( arrayBuffer, newLength, preserveResizability )

The abstract operation ArrayBufferCopyAndDetach takes arguments arrayBuffer (an ECMAScript language value), newLength (an ECMAScript language value), and preserveResizability (preserve-resizability or fixed-length) and returns either a normal completion containing an ArrayBuffer or a throw completion. It performs the following steps when called:

  1. RequireInternalSlot(arrayBuffer, [[ArrayBufferData]])를 수행한다.
  2. IsSharedArrayBuffer(arrayBuffer)가 true이면, TypeError 예외를 던진다.
  3. newLengthundefined이면,
    1. newByteLengtharrayBuffer.[[ArrayBufferByteLength]]라고 하자.
  4. 그렇지 않으면,
    1. newByteLength를 ? ToIndex(newLength)라고 하자.
  5. IsDetachedBuffer(arrayBuffer)가 true이면, TypeError 예외를 던진다.
  6. preserveResizabilitypreserve-resizability이고 IsFixedLengthArrayBuffer(arrayBuffer)가 false이면,
    1. newMaxByteLengtharrayBuffer.[[ArrayBufferMaxByteLength]]라고 하자.
  7. 그렇지 않으면,
    1. newMaxByteLengthempty라고 하자.
  8. arrayBuffer.[[ArrayBufferDetachKey]]undefined가 아니면, TypeError 예외를 던진다.
  9. newBuffer를 ? AllocateArrayBuffer(%ArrayBuffer%, newByteLength, newMaxByteLength)라고 하자.
  10. copyLengthmin(newByteLength, arrayBuffer.[[ArrayBufferByteLength]])라고 하자.
  11. fromBlockarrayBuffer.[[ArrayBufferData]]라고 하자.
  12. toBlocknewBuffer.[[ArrayBufferData]]라고 하자.
  13. CopyDataBlockBytes(toBlock, 0, fromBlock, 0, copyLength)를 수행한다.
  14. NOTE: 새 Data Block 생성과 이전 Data Block에서의 복사는 모두 관찰 가능하지 않다. 구현은 이 메서드를 무복사 이동 또는 realloc으로 구현할 수 있다.
  15. DetachArrayBuffer(arrayBuffer)를 수행한다.
  16. newBuffer를 반환한다.

25.1.3.4 IsDetachedBuffer ( arrayBuffer )

The abstract operation IsDetachedBuffer takes argument arrayBuffer (an ArrayBuffer or a SharedArrayBuffer) and returns a 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 either a normal completion containing unused or a throw completion. It performs the following steps when called:

  1. Assert: IsSharedArrayBuffer(arrayBuffer)는 false이다.
  2. key가 존재하지 않으면, keyundefined로 설정한다.
  3. arrayBuffer.[[ArrayBufferDetachKey]]key가 아니면, TypeError 예외를 던진다.
  4. arrayBuffer.[[ArrayBufferData]]null로 설정한다.
  5. arrayBuffer.[[ArrayBufferByteLength]]를 0으로 설정한다.
  6. unused를 반환한다.
Note

ArrayBuffer 인스턴스를 detach하면 그 backing store로 사용된 Data Block을 인스턴스에서 분리하고 버퍼의 바이트 길이를 0으로 설정한다.

25.1.3.6 CloneArrayBuffer ( 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 either a normal completion containing an ArrayBuffer or a throw completion. srcByteOffset에서 시작해 srcLength 바이트 동안 이어지는 범위에 있는 srcBuffer의 데이터를 복사한 데이터를 가진 새로운 ArrayBuffer를 생성한다. It performs the following steps when called:

  1. Assert: IsDetachedBuffer(srcBuffer)는 false이다.
  2. targetBuffer를 ? AllocateArrayBuffer(%ArrayBuffer%, srcLength)라고 하자.
  3. srcBlocksrcBuffer.[[ArrayBufferData]]라고 하자.
  4. targetBlocktargetBuffer.[[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 either a normal completion containing either a non-negative integer or empty, or a throw completion. It performs the following steps when called:

  1. options가 Object가 아니면, empty를 반환한다.
  2. maxByteLength를 ? Get(options, "maxByteLength")라고 하자.
  3. maxByteLengthundefined이면, empty를 반환한다.
  4. ToIndex(maxByteLength)를 반환한다.

25.1.3.8 HostResizeArrayBuffer ( buffer, newByteLength )

The host-defined abstract operation HostResizeArrayBuffer takes arguments buffer (an ArrayBuffer) and newByteLength (a non-negative integer) and returns either a normal completion containing either handled or unhandled, or a throw completion. 호스트에게 buffer구현 정의 크기 조절을 수행할 기회를 제공한다. 호스트buffer의 크기 조절을 처리하지 않기로 선택하면, 기본 동작을 위해 unhandled를 반환할 수 있다.

HostResizeArrayBuffer의 구현은 다음 요구사항을 준수해야 한다:

  • 추상 연산buffer를 detach하지 않는다.
  • 추상 연산handled와 함께 정상 완료하면, buffer.[[ArrayBufferByteLength]]newByteLength이다.

HostResizeArrayBuffer의 기본 구현은 NormalCompletion(unhandled)를 반환하는 것이다.

25.1.3.9 IsFixedLengthArrayBuffer ( arrayBuffer )

The abstract operation IsFixedLengthArrayBuffer takes argument arrayBuffer (an ArrayBuffer or a SharedArrayBuffer) and returns a 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 a 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 a Boolean. 인자 typeuint8clamped를 포함하지 않는 Integer TypedArray 요소 타입인지 검증한다. It performs the following steps when called:

  1. typeint8, uint8, int16, uint16, int32, 또는 uint32 중 하나이면, true를 반환한다.
  2. false를 반환한다.

25.1.3.12 IsBigIntElementType ( type )

The abstract operation IsBigIntElementType takes argument type (a TypedArray element type) and returns a Boolean. 인자 type이 BigInt TypedArray 요소 타입인지 검증한다. It performs the following steps when called:

  1. typebiguint64 또는 bigint64이면, true를 반환한다.
  2. false를 반환한다.

25.1.3.13 IsNoTearConfiguration ( type, order )

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

  1. IsUnclampedIntegerElementType(type)가 true이면, true를 반환한다.
  2. IsBigIntElementType(type)가 true이고 orderinitunordered도 아니면, true를 반환한다.
  3. false를 반환한다.

25.1.3.14 RawBytesToNumeric ( type, rawBytes, isLittleEndian )

The abstract operation RawBytesToNumeric takes arguments type (a TypedArray element type), rawBytes (a List of byte values), and isLittleEndian (a Boolean) and returns a Number or a BigInt. It performs the following steps when called:

  1. elementSize를 요소 타입 type에 대해 Table 70에 지정된 Element Size 값이라고 하자.
  2. isLittleEndianfalse이면, rawBytes 요소들의 순서를 뒤집는다.
  3. typefloat16이면,
    1. valuerawBytes의 바이트 요소들이 연결되어 IEEE 754-2019 binary16 값의 리틀 엔디언 비트 문자열 인코딩으로 해석된 것이라고 하자.
    2. value가 NaN이면, NaN을 반환한다.
    3. value에 대응하는 Number 값을 반환한다.
  4. typefloat32이면,
    1. valuerawBytes의 바이트 요소들이 연결되어 IEEE 754-2019 binary32 값의 리틀 엔디언 비트 문자열 인코딩으로 해석된 것이라고 하자.
    2. value가 NaN이면, NaN을 반환한다.
    3. value에 대응하는 Number 값을 반환한다.
  5. typefloat64이면,
    1. valuerawBytes의 바이트 요소들이 연결되어 IEEE 754-2019 binary64 값의 리틀 엔디언 비트 문자열 인코딩으로 해석된 것이라고 하자.
    2. value가 NaN이면, NaN을 반환한다.
    3. value에 대응하는 Number 값을 반환한다.
  6. IsUnsignedElementType(type)가 true이면,
    1. intValuerawBytes의 바이트 요소들이 연결되어 부호 없는 리틀 엔디언 이진수의 비트 문자열 인코딩으로 해석된 것이라고 하자.
  7. 그렇지 않으면,
    1. intValuerawBytes의 바이트 요소들이 연결되어 비트 길이가 elementSize × 8인 이진 리틀 엔디언 2의 보수 수의 비트 문자열 인코딩으로 해석된 것이라고 하자.
  8. IsBigIntElementType(type)가 true이면, intValue에 대응하는 BigInt 값을 반환한다.
  9. intValue에 대응하는 Number 값을 반환한다.

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

The abstract operation GetRawBytesFromSharedBlock takes arguments block (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 a List of byte values. It performs the following steps when called:

  1. elementSize를 요소 타입 type에 대해 Table 70에 지정된 Element Size 값이라고 하자.
  2. agentRecord를 주변 agent의 Agent Record라고 하자.
  3. executionagentRecord.[[CandidateExecution]]이라고 하자.
  4. eventsRecordexecution.[[EventsRecords]][[AgentSignifier]]AgentSignifier()인 Agent Events Record라고 하자.
  5. isTypedArraytrue이고 IsNoTearConfiguration(type, order)가 true이면 noTeartrue라고 하자; 그렇지 않으면 noTearfalse라고 하자.
  6. rawValue를 요소들이 비결정적으로 선택된 바이트 값인 길이 elementSizeList라고 하자.
  7. NOTE: 구현에서 rawValue는 기반 하드웨어의 비원자적 또는 원자적 읽기 명령의 결과이다. 비결정성은 약한 일관성을 가진 하드웨어의 관찰 가능한 동작을 설명하기 위한 메모리 모델의 의미론적 규정이다.
  8. readEventReadSharedMemory { [[Order]]: order, [[NoTear]]: noTear, [[Block]]: block, [[ByteIndex]]: byteIndex, [[ElementSize]]: elementSize }라고 하자.
  9. readEventeventsRecord.[[EventList]]에 추가한다.
  10. Chosen Value Record { [[Event]]: readEvent, [[ChosenValue]]: rawValue }를 execution.[[ChosenValues]]에 추가한다.
  11. rawValue를 반환한다.

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

The abstract operation GetValueFromBuffer takes arguments arrayBuffer (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 a Number or a BigInt. It performs the following steps when called:

  1. Assert: IsDetachedBuffer(arrayBuffer)는 false이다.
  2. Assert: arrayBufferbyteIndex에서 시작하여 type의 값을 나타내기에 충분한 바이트가 있다.
  3. blockarrayBuffer.[[ArrayBufferData]]라고 하자.
  4. elementSize를 요소 타입 type에 대해 Table 70에 지정된 Element Size 값이라고 하자.
  5. IsSharedArrayBuffer(arrayBuffer)가 true이면,
    1. Assert: blockShared Data Block이다.
    2. rawValueGetRawBytesFromSharedBlock(block, byteIndex, type, isTypedArray, order)라고 하자.
  6. 그렇지 않으면,
    1. rawValueblock에서 byteIndex(포함)부터 byteIndex + elementSize(제외)까지의 구간에 있는 인덱스의 바이트를 요소로 가지는 List라고 하자.
  7. Assert: rawValue의 요소 개수는 elementSize이다.
  8. isLittleEndian이 존재하지 않으면,
    1. agentRecord를 주변 agent의 Agent Record라고 하자.
    2. isLittleEndianagentRecord.[[LittleEndian]]으로 설정한다.
  9. RawBytesToNumeric(type, rawValue, isLittleEndian)를 반환한다.

25.1.3.17 NumericToRawBytes ( type, value, isLittleEndian )

The abstract operation NumericToRawBytes takes arguments type (a TypedArray element type), value (a Number or a BigInt), and isLittleEndian (a Boolean) and returns a List of byte values. It performs the following steps when called:

  1. typefloat16이면,
    1. rawBytesvalue를 roundTiesToEven 모드를 사용하여 IEEE 754-2019 binary16 형식으로 변환한 결과인 2바이트를 요소로 가지는 List라고 하자. 바이트들은 리틀 엔디언 순서로 배치된다. valueNaN이면, rawBytes는 구현이 선택한 임의의 IEEE 754-2019 binary16 형식 NaN 인코딩으로 설정될 수 있다. 구현은 구현이 구별할 수 있는 각 NaN 값에 대해 항상 같은 인코딩을 선택해야 한다.
  2. 그렇지 않고 typefloat32이면,
    1. rawBytesvalue를 roundTiesToEven 모드를 사용하여 IEEE 754-2019 binary32 형식으로 변환한 결과인 4바이트를 요소로 가지는 List라고 하자. 바이트들은 리틀 엔디언 순서로 배치된다. valueNaN이면, rawBytes는 구현이 선택한 임의의 IEEE 754-2019 binary32 형식 NaN 인코딩으로 설정될 수 있다. 구현은 구현이 구별할 수 있는 각 NaN 값에 대해 항상 같은 인코딩을 선택해야 한다.
  3. 그렇지 않고 typefloat64이면,
    1. rawBytesvalueIEEE 754-2019 binary64 형식 인코딩인 8바이트를 요소로 가지는 List라고 하자. 바이트들은 리틀 엔디언 순서로 배치된다. valueNaN이면, rawBytes는 구현이 선택한 임의의 IEEE 754-2019 binary64 형식 NaN 인코딩으로 설정될 수 있다. 구현은 구현이 구별할 수 있는 각 NaN 값에 대해 항상 같은 인코딩을 선택해야 한다.
  4. 그렇지 않으면,
    1. n을 요소 타입 type에 대해 Table 70에 지정된 Element Size 값이라고 하자.
    2. conversionOperation을 요소 타입 type에 대해 Table 70의 “Conversion Operation” 열에 이름이 지정된 추상 연산이라고 하자.
    3. intValue(! conversionOperation(value))라고 하자.
    4. intValue ≥ 0이면,
      1. rawBytesintValuen-바이트 이진 인코딩을 요소로 가지는 List라고 하자. 바이트들은 리틀 엔디언 순서로 정렬된다.
    5. 그렇지 않으면,
      1. rawBytesintValuen-바이트 이진 2의 보수 인코딩을 요소로 가지는 List라고 하자. 바이트들은 리틀 엔디언 순서로 정렬된다.
  5. isLittleEndianfalse이면, rawBytes 요소들의 순서를 뒤집는다.
  6. rawBytes를 반환한다.

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

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

  1. Assert: IsDetachedBuffer(arrayBuffer)는 false이다.
  2. Assert: arrayBufferbyteIndex에서 시작하여 type의 값을 나타내기에 충분한 바이트가 있다.
  3. Assert: IsBigIntElementType(type)가 true이면 value는 BigInt이고, 그렇지 않으면 value는 Number이다.
  4. blockarrayBuffer.[[ArrayBufferData]]라고 하자.
  5. elementSize를 요소 타입 type에 대해 Table 70에 지정된 Element Size 값이라고 하자.
  6. agentRecord를 주변 agent의 Agent Record라고 하자.
  7. isLittleEndian이 존재하지 않으면,
    1. isLittleEndianagentRecord.[[LittleEndian]]으로 설정한다.
  8. rawBytesNumericToRawBytes(type, value, isLittleEndian)라고 하자.
  9. IsSharedArrayBuffer(arrayBuffer)가 true이면,
    1. executionagentRecord.[[CandidateExecution]]이라고 하자.
    2. eventsRecordexecution.[[EventsRecords]][[AgentSignifier]]AgentSignifier()인 Agent Events Record라고 하자.
    3. isTypedArraytrue이고 IsNoTearConfiguration(type, order)가 true이면 noTeartrue라고 하자; 그렇지 않으면 noTearfalse라고 하자.
    4. WriteSharedMemory { [[Order]]: order, [[NoTear]]: noTear, [[Block]]: block, [[ByteIndex]]: byteIndex, [[ElementSize]]: elementSize, [[Payload]]: rawBytes }를 eventsRecord.[[EventList]]에 추가한다.
  10. 그렇지 않으면,
    1. rawBytes의 개별 바이트들을 block[byteIndex]에서 시작하여 block에 저장한다.
  11. unused를 반환한다.

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

The abstract operation GetModifySetValueInBuffer takes arguments arrayBuffer (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 a Number or a BigInt. It performs the following steps when called:

  1. Assert: IsDetachedBuffer(arrayBuffer)는 false이다.
  2. Assert: arrayBufferbyteIndex에서 시작하여 type의 값을 나타내기에 충분한 바이트가 있다.
  3. Assert: IsBigIntElementType(type)가 true이면 value는 BigInt이고, 그렇지 않으면 value는 Number이다.
  4. blockarrayBuffer.[[ArrayBufferData]]라고 하자.
  5. elementSize를 요소 타입 type에 대해 Table 70에 지정된 Element Size 값이라고 하자.
  6. agentRecord를 주변 agent의 Agent Record라고 하자.
  7. isLittleEndianagentRecord.[[LittleEndian]]이라고 하자.
  8. rawBytesNumericToRawBytes(type, value, isLittleEndian)라고 하자.
  9. IsSharedArrayBuffer(arrayBuffer)가 true이면,
    1. executionagentRecord.[[CandidateExecution]]이라고 하자.
    2. eventsRecordexecution.[[EventsRecords]][[AgentSignifier]]AgentSignifier()인 Agent Events Record라고 하자.
    3. rawBytesRead를 요소들이 비결정적으로 선택된 바이트 값인 길이 elementSizeList라고 하자.
    4. NOTE: 구현에서 rawBytesRead는 기반 하드웨어에서 load-link, load-exclusive 또는 read-modify-write 명령의 피연산자 결과이다. 비결정성은 약한 일관성을 가진 하드웨어의 관찰 가능한 동작을 설명하기 위한 메모리 모델의 의미론적 규정이다.
    5. rmwEventReadModifyWriteSharedMemory { [[Order]]: seq-cst, [[NoTear]]: true, [[Block]]: block, [[ByteIndex]]: byteIndex, [[ElementSize]]: elementSize, [[Payload]]: rawBytes, [[ModifyOp]]: op }라고 하자.
    6. rmwEventeventsRecord.[[EventList]]에 추가한다.
    7. Chosen Value Record { [[Event]]: rmwEvent, [[ChosenValue]]: rawBytesRead }를 execution.[[ChosenValues]]에 추가한다.
  10. 그렇지 않으면,
    1. rawBytesReadblock[byteIndex]로 시작하는 elementSize개의 바이트 시퀀스를 요소로 가지는 길이 elementSizeList라고 하자.
    2. rawBytesModifiedop(rawBytesRead, rawBytes)라고 하자.
    3. rawBytesModified의 개별 바이트들을 block[byteIndex]에서 시작하여 block에 저장한다.
  11. RawBytesToNumeric(type, rawBytesRead, isLittleEndian)를 반환한다.

25.1.4 ArrayBuffer 생성자

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. 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. objthis 값이라고 하자.
  2. RequireInternalSlot(obj, [[ArrayBufferData]])를 수행한다.
  3. IsSharedArrayBuffer(obj)가 true이면, TypeError 예외를 던진다.
  4. IsDetachedBuffer(obj)가 true이면, +0𝔽을 반환한다.
  5. lengthobj.[[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. objthis 값이라고 하자.
  2. RequireInternalSlot(obj, [[ArrayBufferData]])를 수행한다.
  3. IsSharedArrayBuffer(obj)가 true이면, TypeError 예외를 던진다.
  4. IsDetachedBuffer(obj)를 반환한다.

25.1.6.4 get ArrayBuffer.prototype.maxByteLength

ArrayBuffer.prototype.maxByteLength는 set 접근자 함수가 undefined인 접근자 속성이다. 그 get 접근자 함수는 호출될 때 다음 단계를 수행한다:

  1. objthis 값이라고 하자.
  2. RequireInternalSlot(obj, [[ArrayBufferData]])를 수행한다.
  3. IsSharedArrayBuffer(obj)가 true이면, TypeError 예외를 던진다.
  4. IsDetachedBuffer(obj)가 true이면, +0𝔽을 반환한다.
  5. IsFixedLengthArrayBuffer(obj)가 true이면,
    1. lengthobj.[[ArrayBufferByteLength]]라고 하자.
  6. 그렇지 않으면,
    1. lengthobj.[[ArrayBufferMaxByteLength]]라고 하자.
  7. 𝔽(length)를 반환한다.

25.1.6.5 get ArrayBuffer.prototype.resizable

ArrayBuffer.prototype.resizable은 set 접근자 함수가 undefined인 접근자 속성이다. 그 get 접근자 함수는 호출될 때 다음 단계를 수행한다:

  1. objthis 값이라고 하자.
  2. RequireInternalSlot(obj, [[ArrayBufferData]])를 수행한다.
  3. IsSharedArrayBuffer(obj)가 true이면, TypeError 예외를 던진다.
  4. IsFixedLengthArrayBuffer(obj)가 false이면, true를 반환한다.
  5. false를 반환한다.

25.1.6.6 ArrayBuffer.prototype.resize ( newLength )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. objthis 값이라고 하자.
  2. RequireInternalSlot(obj, [[ArrayBufferMaxByteLength]])를 수행한다.
  3. IsSharedArrayBuffer(obj)가 true이면, TypeError 예외를 던진다.
  4. newByteLength를 ? ToIndex(newLength)라고 하자.
  5. IsDetachedBuffer(obj)가 true이면, TypeError 예외를 던진다.
  6. newByteLength > obj.[[ArrayBufferMaxByteLength]]이면, RangeError 예외를 던진다.
  7. hostHandled를 ? HostResizeArrayBuffer(obj, newByteLength)라고 하자.
  8. hostHandledhandled이면, undefined를 반환한다.
  9. oldBlockobj.[[ArrayBufferData]]라고 하자.
  10. newBlock을 ? CreateByteDataBlock(newByteLength)라고 하자.
  11. copyLengthmin(newByteLength, obj.[[ArrayBufferByteLength]])라고 하자.
  12. CopyDataBlockBytes(newBlock, 0, oldBlock, 0, copyLength)를 수행한다.
  13. NOTE: 새 Data Block 생성과 이전 Data Block에서의 복사는 모두 관찰 가능하지 않다. 구현은 이 메서드를 제자리 증가 또는 축소로 구현할 수 있다.
  14. obj.[[ArrayBufferData]]newBlock으로 설정한다.
  15. obj.[[ArrayBufferByteLength]]newByteLength로 설정한다.
  16. undefined를 반환한다.

25.1.6.7 ArrayBuffer.prototype.slice ( start, end )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. objthis 값이라고 하자.
  2. RequireInternalSlot(obj, [[ArrayBufferData]])를 수행한다.
  3. IsSharedArrayBuffer(obj)가 true이면, TypeError 예외를 던진다.
  4. IsDetachedBuffer(obj)가 true이면, TypeError 예외를 던진다.
  5. lenobj.[[ArrayBufferByteLength]]라고 하자.
  6. relativeStart를 ? ToIntegerOrInfinity(start)라고 하자.
  7. relativeStart = -∞이면, first를 0이라고 하자.
  8. 그렇지 않고 relativeStart < 0이면, firstmax(len + relativeStart, 0)이라고 하자.
  9. 그렇지 않으면, firstmin(relativeStart, len)이라고 하자.
  10. endundefined이면 relativeEndlen이라고 하자; 그렇지 않으면 relativeEnd를 ? ToIntegerOrInfinity(end)라고 하자.
  11. relativeEnd = -∞이면, final을 0이라고 하자.
  12. 그렇지 않고 relativeEnd < 0이면, finalmax(len + relativeEnd, 0)이라고 하자.
  13. 그렇지 않으면, finalmin(relativeEnd, len)이라고 하자.
  14. newLenmax(final - first, 0)이라고 하자.
  15. ctor를 ? SpeciesConstructor(obj, %ArrayBuffer%)라고 하자.
  16. new를 ? Construct(ctor, « 𝔽(newLen) »)라고 하자.
  17. RequireInternalSlot(new, [[ArrayBufferData]])를 수행한다.
  18. IsSharedArrayBuffer(new)가 true이면, TypeError 예외를 던진다.
  19. IsDetachedBuffer(new)가 true이면, TypeError 예외를 던진다.
  20. SameValue(new, obj)가 true이면, TypeError 예외를 던진다.
  21. new.[[ArrayBufferByteLength]] < newLen이면, TypeError 예외를 던진다.
  22. NOTE: 위 단계들의 부수 효과로 obj가 detach되었거나 크기가 조절되었을 수 있다.
  23. IsDetachedBuffer(obj)가 true이면, TypeError 예외를 던진다.
  24. fromBufobj.[[ArrayBufferData]]라고 하자.
  25. toBufnew.[[ArrayBufferData]]라고 하자.
  26. currentLenobj.[[ArrayBufferByteLength]]라고 하자.
  27. first < currentLen이면,
    1. countmin(newLen, currentLen - first)라고 하자.
    2. CopyDataBlockBytes(toBuf, 0, fromBuf, first, count)를 수행한다.
  28. new를 반환한다.

25.1.6.8 ArrayBuffer.prototype.transfer ( [ newLength ] )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. objthis 값이라고 하자.
  2. ArrayBufferCopyAndDetach(obj, newLength, preserve-resizability)를 반환한다.

25.1.6.9 ArrayBuffer.prototype.transferToFixedLength ( [ newLength ] )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. objthis 값이라고 하자.
  2. ArrayBufferCopyAndDetach(obj, 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]] 내부 슬롯을 가진다. 크기 조절 가능 ArrayBuffer 인스턴스는 각각 [[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를 성공적으로 생성했다고 해서 향후 resize가 성공한다는 보장은 없다는 점에 유의하라.

Note 2

다음은 크기 조절 가능 ArrayBuffer를 구현하는 ECMAScript 구현자를 위한 지침이다.

크기 조절 가능 ArrayBuffer는 resize 시 복사, 가상 메모리를 미리 예약하는 제자리 증가, 또는 생성자의 "maxByteLength" 옵션의 서로 다른 값에 대해 두 방식을 조합하여 구현할 수 있다.

웹 브라우저와 같이 호스트가 멀티 테넌트(즉, 많은 ECMAScript 애플리케이션을 동시에 실행)이고 구현이 가상 메모리를 예약하여 제자리 증가를 구현하기로 선택한 경우, 단일 애플리케이션이 가상 메모리 주소 공간을 고갈시킬 가능성을 줄이고 상호 운용성 위험을 줄이기 위해 32비트와 64비트 구현 모두 "maxByteLength" ≥ 1GiB에서 1.5GiB 사이의 값에 대해 예외를 던질 것을 권장한다.

임베디드 장치처럼 MMU가 없는 환경에서 실행되는 호스트와 같이 가상 메모리가 없거나, 호스트가 복사를 통해서만 크기 조절을 구현하는 경우, "maxByteLength" 옵션에 대해 어떤 Number 값도 허용할 수 있다. 그러나 요청된 크기의 메모리 블록을 결코 할당할 수 없다면 RangeError를 던질 것을 권장한다. 예를 들어 요청된 크기가 장치에서 사용 가능한 최대 메모리 양보다 큰 경우가 그렇다.

25.2 SharedArrayBuffer 객체

25.2.1 고정 길이 및 증가 가능 SharedArrayBuffer 객체

고정 길이 SharedArrayBuffer는 생성 후 바이트 길이가 변경될 수 없는 SharedArrayBuffer이다.

증가 가능 SharedArrayBuffer는 생성 후 SharedArrayBuffer.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 either a normal completion containing a SharedArrayBuffer or a throw completion. SharedArrayBuffer를 생성하는 데 사용된다. It performs the following steps when called:

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

25.2.2.2 IsSharedArrayBuffer ( obj )

The abstract operation IsSharedArrayBuffer takes argument obj (an ArrayBuffer or a SharedArrayBuffer) and returns a Boolean. 객체가 SharedArrayBuffer인지 테스트한다. It performs the following steps when called:

  1. obj.[[ArrayBufferData]]Shared Data Block이면, true를 반환한다.
  2. false를 반환한다.

25.2.2.3 IsGrowableSharedArrayBuffer ( obj )

The abstract operation IsGrowableSharedArrayBuffer takes argument obj (an ArrayBuffer or a SharedArrayBuffer) and returns a Boolean. 객체가 증가 가능 SharedArrayBuffer인지 테스트한다. It performs the following steps when called:

  1. IsSharedArrayBuffer(obj)가 true이고 obj[[ArrayBufferByteLengthData]] 내부 슬롯을 가지면, true를 반환한다.
  2. false를 반환한다.

25.2.2.4 HostGrowSharedArrayBuffer ( buffer, newByteLength )

The host-defined abstract operation HostGrowSharedArrayBuffer takes arguments buffer (a SharedArrayBuffer) and newByteLength (a non-negative integer) and returns either a normal completion containing either handled or unhandled, or a throw completion. 호스트에게 buffer구현 정의 증가를 수행할 기회를 제공한다. 호스트buffer의 증가를 처리하지 않기로 선택하면, 기본 동작을 위해 unhandled를 반환할 수 있다.

HostGrowSharedArrayBuffer의 구현은 다음 요구사항을 준수해야 한다:

  • 추상 연산unhandled와 함께 정상 완료하지 않고, newByteLength < buffer의 현재 바이트 길이이거나 newByteLength > buffer.[[ArrayBufferMaxByteLength]]이면, RangeError 예외를 던진다.
  • agentRecord를 주변 agent의 Agent Record라고 하자. isLittleEndianagentRecord.[[LittleEndian]]이라고 하자. 이 추상 연산handled와 함께 정상 완료하면, [[Order]]seq-cst, [[Payload]]NumericToRawBytes(biguint64, newByteLength, isLittleEndian), [[Block]]buffer.[[ArrayBufferByteLengthData]], [[ByteIndex]]가 0, 그리고 [[ElementSize]]가 8인 WriteSharedMemory 또는 ReadModifyWriteSharedMemory 이벤트가 주변 agent의 candidate execution에 추가되어, SharedArrayBuffer.prototype.grow ( newLength )에 대한 경쟁 호출이 "lost", 즉 조용히 아무것도 하지 않는 일이 없도록 한다.
Note

위 두 번째 요구사항은 buffer의 현재 바이트 길이를 어떻게 또는 언제 읽는지에 대해 의도적으로 모호하다. 바이트 길이는 기반 하드웨어에서 원자적 read-modify-write 연산을 통해 갱신되어야 하므로, load-link/store-conditional 또는 load-exclusive/store-exclusive 명령 쌍을 사용하는 아키텍처는 쌍을 이루는 명령들을 명령 스트림에서 가깝게 유지하고자 할 수 있다. 따라서 SharedArrayBuffer.prototype.grow ( newLength ) 자체는 HostGrowSharedArrayBuffer를 호출하기 전에 newByteLength에 대한 경계 검사를 수행하지 않으며, 현재 바이트 길이가 언제 읽히는지에 대한 요구사항도 없다.

이는 0 ≤ newByteLengthbuffer.[[ArrayBufferMaxByteLength]]가 보장되는 HostResizeArrayBuffer와 대조된다.

HostGrowSharedArrayBuffer의 기본 구현은 NormalCompletion(unhandled)를 반환하는 것이다.

25.2.3 SharedArrayBuffer 생성자

SharedArrayBuffer 생성자는:

  • %SharedArrayBuffer%이다.
  • 해당 속성이 존재한다면(아래 참조), 전역 객체"SharedArrayBuffer" 속성의 초기값이다.
  • 생성자로 호출될 때 새로운 SharedArrayBuffer를 생성하고 초기화한다.
  • 함수로 호출되도록 의도되지 않았으며, 그런 방식으로 호출되면 예외를 던진다.
  • 클래스 정의의 extends 절의 값으로 사용될 수 있다. 지정된 SharedArrayBuffer 동작을 상속하려는 서브클래스 생성자는 SharedArrayBuffer.prototype 내장 메서드를 지원하는 데 필요한 내부 상태로 서브클래스 인스턴스를 생성하고 초기화하기 위해 SharedArrayBuffer 생성자에 대한 super 호출을 포함해야 한다.

호스트가 SharedArrayBuffer에 대한 동시 접근을 제공하지 않을 때마다 전역 객체"SharedArrayBuffer" 속성을 생략할 수 있다.

Note

ArrayBuffer와 달리, SharedArrayBuffer는 detached될 수 없으며 그 내부 [[ArrayBufferData]] 슬롯은 결코 null이 아니다.

25.2.3.1 SharedArrayBuffer ( length [ , options ] )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. NewTarget이 undefined이면, TypeError 예외를 던진다.
  2. byteLength를 ? ToIndex(length)라고 하자.
  3. requestedMaxByteLength를 ? GetArrayBufferMaxByteLengthOption(options)라고 하자.
  4. 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. objthis 값이라고 하자.
  2. RequireInternalSlot(obj, [[ArrayBufferData]])를 수행한다.
  3. IsSharedArrayBuffer(obj)가 false이면, TypeError 예외를 던진다.
  4. lengthArrayBufferByteLength(obj, seq-cst)라고 하자.
  5. 𝔽(length)를 반환한다.

25.2.5.2 SharedArrayBuffer.prototype.constructor

SharedArrayBuffer.prototype.constructor의 초기값은 %SharedArrayBuffer%이다.

25.2.5.3 SharedArrayBuffer.prototype.grow ( newLength )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. objthis 값이라고 하자.
  2. RequireInternalSlot(obj, [[ArrayBufferMaxByteLength]])를 수행한다.
  3. IsSharedArrayBuffer(obj)가 false이면, TypeError 예외를 던진다.
  4. newByteLength를 ? ToIndex(newLength)라고 하자.
  5. hostHandled를 ? HostGrowSharedArrayBuffer(obj, newByteLength)라고 하자.
  6. hostHandledhandled이면, undefined를 반환한다.
  7. agentRecord를 주변 agent의 Agent Record라고 하자.
  8. isLittleEndianagentRecord.[[LittleEndian]]이라고 하자.
  9. byteLengthBlockobj.[[ArrayBufferByteLengthData]]라고 하자.
  10. currentByteLengthRawBytesGetRawBytesFromSharedBlock(byteLengthBlock, 0, biguint64, true, seq-cst)라고 하자.
  11. newByteLengthRawBytesNumericToRawBytes(biguint64, (newByteLength), isLittleEndian)라고 하자.
  12. 반복한다,
    1. NOTE: 이는 동일한 버퍼에 대한 병렬적이고 경쟁하는 grow가 전체 순서화되고, lost되지 않으며, 조용히 아무것도 하지 않는 일이 없도록 보장하는 compare-and-exchange 루프이다. 루프는 경쟁 없이 증가를 시도할 수 있었을 때 종료된다.
    2. currentByteLength(RawBytesToNumeric(biguint64, currentByteLengthRawBytes, isLittleEndian))라고 하자.
    3. newByteLength = currentByteLength이면, undefined를 반환한다.
    4. newByteLength < currentByteLength이거나 newByteLength > obj.[[ArrayBufferMaxByteLength]]이면, RangeError 예외를 던진다.
    5. byteLengthDeltanewByteLength - currentByteLength라고 하자.
    6. byteLengthDelta 바이트로 구성된 새로운 Shared Data Block 값을 생성하는 것이 불가능하면, RangeError 예외를 던진다.
    7. NOTE: 여기서는 새로운 Shared Data Block이 생성되어 사용되지 않는다. 증가 가능 SharedArrayBuffer의 관찰 가능한 동작은 생성 시 최대 크기의 Shared Data Block을 할당함으로써 지정되며, 이 단계는 메모리가 부족한 구현이 RangeError를 던져야 한다는 요구사항을 포착한다.
    8. readByteLengthRawBytesAtomicCompareExchangeInSharedBlock(byteLengthBlock, 0, 8, currentByteLengthRawBytes, newByteLengthRawBytes)라고 하자.
    9. ByteListEqual(readByteLengthRawBytes, currentByteLengthRawBytes)가 true이면, undefined를 반환한다.
    10. currentByteLengthRawBytesreadByteLengthRawBytes로 설정한다.
Note

길이를 갱신하는 compare-exchange의 허위 실패는 금지된다. 새 길이에 대한 경계 검사가 통과하고 구현에 메모리 부족이 없다면, ReadModifyWriteSharedMemory 이벤트(즉 성공적인 compare-exchange)가 항상 candidate execution에 추가된다.

SharedArrayBuffer.prototype.grow에 대한 병렬 호출은 전체 순서화된다. 예를 들어 두 경쟁 호출 sab.grow(10)sab.grow(20)을 생각해 보라. 두 호출 중 하나는 반드시 경쟁에서 이긴다. sab.grow(10) 호출은 sab.grow(20)이 먼저 발생했더라도 결코 sab를 축소하지 않는다. 그 경우 대신 RangeError를 던진다.

25.2.5.4 get SharedArrayBuffer.prototype.growable

SharedArrayBuffer.prototype.growable은 set 접근자 함수가 undefined인 접근자 속성이다. 그 get 접근자 함수는 호출될 때 다음 단계를 수행한다:

  1. objthis 값이라고 하자.
  2. RequireInternalSlot(obj, [[ArrayBufferData]])를 수행한다.
  3. IsSharedArrayBuffer(obj)가 false이면, TypeError 예외를 던진다.
  4. IsFixedLengthArrayBuffer(obj)가 false이면, true를 반환한다.
  5. false를 반환한다.

25.2.5.5 get SharedArrayBuffer.prototype.maxByteLength

SharedArrayBuffer.prototype.maxByteLength는 set 접근자 함수가 undefined인 접근자 속성이다. 그 get 접근자 함수는 호출될 때 다음 단계를 수행한다:

  1. objthis 값이라고 하자.
  2. RequireInternalSlot(obj, [[ArrayBufferData]])를 수행한다.
  3. IsSharedArrayBuffer(obj)가 false이면, TypeError 예외를 던진다.
  4. IsFixedLengthArrayBuffer(obj)가 true이면,
    1. lengthobj.[[ArrayBufferByteLength]]라고 하자.
  5. 그렇지 않으면,
    1. lengthobj.[[ArrayBufferMaxByteLength]]라고 하자.
  6. 𝔽(length)를 반환한다.

25.2.5.6 SharedArrayBuffer.prototype.slice ( start, end )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. objthis 값이라고 하자.
  2. RequireInternalSlot(obj, [[ArrayBufferData]])를 수행한다.
  3. IsSharedArrayBuffer(obj)가 false이면, TypeError 예외를 던진다.
  4. lenArrayBufferByteLength(obj, seq-cst)라고 하자.
  5. relativeStart를 ? ToIntegerOrInfinity(start)라고 하자.
  6. relativeStart = -∞이면, first를 0이라고 하자.
  7. 그렇지 않고 relativeStart < 0이면, firstmax(len + relativeStart, 0)이라고 하자.
  8. 그렇지 않으면, firstmin(relativeStart, len)이라고 하자.
  9. endundefined이면 relativeEndlen이라고 하자; 그렇지 않으면 relativeEnd를 ? ToIntegerOrInfinity(end)라고 하자.
  10. relativeEnd = -∞이면, final을 0이라고 하자.
  11. 그렇지 않고 relativeEnd < 0이면, finalmax(len + relativeEnd, 0)이라고 하자.
  12. 그렇지 않으면, finalmin(relativeEnd, len)이라고 하자.
  13. newLenmax(final - first, 0)이라고 하자.
  14. ctor를 ? SpeciesConstructor(obj, %SharedArrayBuffer%)라고 하자.
  15. new를 ? Construct(ctor, « 𝔽(newLen) »)라고 하자.
  16. RequireInternalSlot(new, [[ArrayBufferData]])를 수행한다.
  17. IsSharedArrayBuffer(new)가 false이면, TypeError 예외를 던진다.
  18. new.[[ArrayBufferData]]obj.[[ArrayBufferData]]이면, TypeError 예외를 던진다.
  19. ArrayBufferByteLength(new, seq-cst) < newLen이면, TypeError 예외를 던진다.
  20. fromBufobj.[[ArrayBufferData]]라고 하자.
  21. toBufnew.[[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]] 내부 슬롯을 가진다. 증가 가능하지 않은 SharedArrayBuffer 인스턴스는 각각 [[ArrayBufferByteLength]] 내부 슬롯을 가진다. 증가 가능한 SharedArrayBuffer 인스턴스는 각각 [[ArrayBufferByteLengthData]] 내부 슬롯과 [[ArrayBufferMaxByteLength]] 내부 슬롯을 가진다.

Note

SharedArrayBuffer 인스턴스는 ArrayBuffer 인스턴스와 달리 결코 detached되지 않는다.

25.2.7 증가 가능 SharedArrayBuffer 지침

Note 1

다음은 증가 가능 SharedArrayBuffer를 사용하는 ECMAScript 프로그래머를 위한 지침이다.

가능한 경우 프로그램은 배포 환경에서 테스트할 것을 권장한다. 사용 가능한 물리 메모리의 양은 하드웨어 장치마다 크게 다르다. 마찬가지로 가상 메모리 서브시스템도 하드웨어 장치와 운영 체제마다 크게 다르다. 64비트 데스크톱 웹 브라우저에서 메모리 부족 오류 없이 실행되는 애플리케이션이 32비트 모바일 웹 브라우저에서는 메모리가 부족해질 수 있다.

증가 가능 SharedArrayBuffer에 대한 "maxByteLength" 옵션 값을 선택할 때는 애플리케이션에 가능한 가장 작은 크기를 선택할 것을 권장한다. "maxByteLength"가 1073741824, 즉 1GiB를 초과하지 않을 것을 권장한다.

특정 최대 크기에 대해 증가 가능 SharedArrayBuffer를 성공적으로 생성했다고 해서 향후 grow가 성공한다는 보장은 없다는 점에 유의하라.

증가 가능 SharedArrayBuffer 길이의 모든 로드가 동기화하는 seq-cst 로드는 아니다. 정수 인덱스 속성 접근, 예를 들어 u8[idx]의 경계 검사를 위한 길이 로드는 동기화하지 않는다. 일반적으로 명시적 동기화가 없으면, 한 속성 접근이 in-bound였다는 사실이 같은 agent의 후속 속성 접근도 in-bound임을 의미하지 않는다. 반대로 SharedArrayBuffer, %TypedArray%.prototype, 그리고 DataView.prototype의 lengthbyteLength getter를 통한 길이의 명시적 로드는 동기화한다. TypedArray가 완전히 out-of-bounds인지 확인하기 위해 내장 메서드가 수행하는 길이 로드도 동기화한다.

Note 2

다음은 증가 가능 SharedArrayBuffer를 구현하는 ECMAScript 구현자를 위한 지침이다.

증가 가능 SharedArrayBuffer는 가상 메모리를 미리 예약하는 제자리 증가로 구현할 것을 권장한다.

증가 연산은 증가 가능 SharedArrayBuffer에 대한 메모리 접근과 병렬로 발생할 수 있으므로, 메모리 모델의 제약은 unordered 접근조차도 "tear"하지 않을 것(값의 비트가 섞이지 않을 것)을 요구한다. 실제로 이는 증가 가능 SharedArrayBuffer의 기반 데이터 블록이 세계를 멈추지 않고는 복사 방식으로 증가될 수 없음을 의미한다. 세계를 멈추는 방식은 직렬화 지점을 도입하고 느리기 때문에 구현 전략으로 권장하지 않는다.

증가된 메모리는 병렬로 발생하는 모든 racy 접근을 포함하여, 생성 순간부터 0으로 채워진 것처럼 보여야 한다. 이는 zero-filled-on-demand 가상 메모리 페이지를 통해 달성하거나, 메모리를 수동으로 0으로 채우는 경우 신중한 동기화를 통해 달성할 수 있다.

증가 가능 SharedArrayBufferTypedArray 뷰에 대한 정수 인덱스 속성 접근은, 기반 버퍼의 길이에 대해 정수 인덱스 속성 로드가 동기화하지 않기 때문에(위 프로그래머 지침 참조), 증가 불가능 SharedArrayBuffer의 TypedArray 뷰에 대한 접근과 유사하게 최적화 가능하도록 의도되어 있다. 예를 들어 속성 접근에 대한 경계 검사는 여전히 루프 밖으로 끌어올려질 수 있다.

실제로 임베디드 장치처럼 MMU가 없는 환경에서 실행되는 호스트와 같이 가상 메모리가 없는 호스트에서 증가 가능 SharedArrayBuffer를 복사 방식으로 구현하는 것은 어렵다. 그러한 호스트에서 증가 가능 SharedArrayBuffer의 메모리 사용 동작은 가상 메모리가 있는 호스트와 크게 다를 수 있다. 그러한 호스트는 사용자에게 메모리 사용 기대치를 명확히 전달해야 한다.

25.3 DataView 객체

25.3.1 DataView 객체를 위한 추상 연산

25.3.1.1 DataView With Buffer Witness Records

DataView With Buffer Witness Record는 DataView와 함께 viewed buffer의 캐시된 바이트 길이를 캡슐화하는 데 사용되는 Record 값이다. 이는 viewed buffer가 증가 가능 SharedArrayBuffer일 때 바이트 길이 데이터 블록에 대해 단일 ReadSharedMemory 이벤트만 있도록 보장하는 데 도움을 주기 위해 사용된다.

DataView With Buffer Witness Records는 Table 72에 나열된 필드를 가진다.

Table 72: DataView With Buffer Witness Record 필드
필드 이름 의미
[[Object]] DataView 그 버퍼의 바이트 길이가 로드되는 DataView 객체.
[[CachedBufferByteLength]] 음이 아닌 정수 또는 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 a DataView With Buffer Witness Record. It performs the following steps when called:

  1. bufferobj.[[ViewedArrayBuffer]]라고 하자.
  2. IsDetachedBuffer(buffer)가 true이면,
    1. byteLengthdetached라고 하자.
  3. 그렇지 않으면,
    1. byteLengthArrayBufferByteLength(buffer, order)라고 하자.
  4. DataView With Buffer Witness Record { [[Object]]: obj, [[CachedBufferByteLength]]: byteLength }를 반환한다.

25.3.1.3 GetViewByteLength ( viewRecord )

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

  1. Assert: IsViewOutOfBounds(viewRecord)는 false이다.
  2. viewviewRecord.[[Object]]라고 하자.
  3. view.[[ByteLength]]auto가 아니면, view.[[ByteLength]]를 반환한다.
  4. Assert: IsFixedLengthArrayBuffer(view.[[ViewedArrayBuffer]])는 false이다.
  5. byteOffsetview.[[ByteOffset]]이라고 하자.
  6. byteLengthviewRecord.[[CachedBufferByteLength]]라고 하자.
  7. Assert: byteLengthdetached가 아니다.
  8. byteLength - byteOffset을 반환한다.

25.3.1.4 IsViewOutOfBounds ( viewRecord )

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

  1. viewviewRecord.[[Object]]라고 하자.
  2. bufferByteLengthviewRecord.[[CachedBufferByteLength]]라고 하자.
  3. IsDetachedBuffer(view.[[ViewedArrayBuffer]])가 true이면,
    1. Assert: bufferByteLengthdetached이다.
    2. true를 반환한다.
  4. Assert: bufferByteLength는 음이 아닌 정수이다.
  5. byteOffsetStartview.[[ByteOffset]]이라고 하자.
  6. view.[[ByteLength]]auto이면,
    1. byteOffsetEndbufferByteLength라고 하자.
  7. 그렇지 않으면,
    1. byteOffsetEndbyteOffsetStart + view.[[ByteLength]]라고 하자.
  8. NOTE: [[ByteOffset]]bufferByteLength인 0길이 DataView는 out-of-bounds로 간주되지 않는다.
  9. byteOffsetStart > bufferByteLength이거나 byteOffsetEnd > bufferByteLength이면, true를 반환한다.
  10. false를 반환한다.

25.3.1.5 GetViewValue ( view, requestIndex, isLittleEndian, type )

The abstract operation GetViewValue takes arguments view (an ECMAScript language value), requestIndex (an ECMAScript language value), isLittleEndian (an ECMAScript language value), and type (a TypedArray element type) and returns either a normal completion containing either a Number or a BigInt, or a throw completion. DataView 인스턴스의 함수가 뷰의 버퍼에서 값을 가져오는 데 사용된다. It performs the following steps when called:

  1. RequireInternalSlot(view, [[DataView]])를 수행한다.
  2. Assert: view[[ViewedArrayBuffer]] 내부 슬롯을 가진다.
  3. getIndex를 ? ToIndex(requestIndex)라고 하자.
  4. isLittleEndianToBoolean(isLittleEndian)으로 설정한다.
  5. viewOffsetview.[[ByteOffset]]이라고 하자.
  6. viewRecordMakeDataViewWithBufferWitnessRecord(view, unordered)라고 하자.
  7. NOTE: view의 backing buffer가 증가 가능 SharedArrayBuffer일 때 경계 검사는 동기화 연산이 아니다.
  8. IsViewOutOfBounds(viewRecord)가 true이면, TypeError 예외를 던진다.
  9. viewSizeGetViewByteLength(viewRecord)라고 하자.
  10. elementSize를 요소 타입 type에 대해 Table 70에 지정된 Element Size 값이라고 하자.
  11. getIndex + elementSize > viewSize이면, RangeError 예외를 던진다.
  12. bufferIndexgetIndex + viewOffset이라고 하자.
  13. GetValueFromBuffer(view.[[ViewedArrayBuffer]], bufferIndex, type, false, unordered, isLittleEndian)를 반환한다.

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

The abstract operation SetViewValue takes arguments view (an ECMAScript language value), requestIndex (an ECMAScript language value), isLittleEndian (an ECMAScript language value), type (a TypedArray element type), and value (an ECMAScript language value) and returns either a normal completion containing undefined or a throw completion. DataView 인스턴스의 함수가 값을 뷰의 버퍼에 저장하는 데 사용된다. 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)라고 하자.
  5. 그렇지 않으면 numberValue를 ? ToNumber(value)라고 하자.
  6. isLittleEndianToBoolean(isLittleEndian)으로 설정한다.
  7. viewOffsetview.[[ByteOffset]]이라고 하자.
  8. viewRecordMakeDataViewWithBufferWitnessRecord(view, unordered)라고 하자.
  9. NOTE: view의 backing buffer가 증가 가능 SharedArrayBuffer일 때 경계 검사는 동기화 연산이 아니다.
  10. IsViewOutOfBounds(viewRecord)가 true이면, TypeError 예외를 던진다.
  11. viewSizeGetViewByteLength(viewRecord)라고 하자.
  12. elementSize를 요소 타입 type에 대해 Table 70에 지정된 Element Size 값이라고 하자.
  13. getIndex + elementSize > viewSize이면, RangeError 예외를 던진다.
  14. bufferIndexgetIndex + viewOffset이라고 하자.
  15. SetValueInBuffer(view.[[ViewedArrayBuffer]], bufferIndex, type, numberValue, false, unordered, isLittleEndian)를 수행한다.
  16. 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. bufferByteLengthArrayBufferByteLength(buffer, seq-cst)라고 하자.
  6. offset > bufferByteLength이면, RangeError 예외를 던진다.
  7. bufferIsFixedLengthIsFixedLengthArrayBuffer(buffer)라고 하자.
  8. byteLengthundefined이면,
    1. bufferIsFixedLengthtrue이면,
      1. viewByteLengthbufferByteLength - offset이라고 하자.
    2. 그렇지 않으면,
      1. viewByteLengthauto라고 하자.
  9. 그렇지 않으면,
    1. viewByteLength를 ? ToIndex(byteLength)라고 하자.
    2. offset + viewByteLength > bufferByteLength이면, RangeError 예외를 던진다.
  10. obj를 ? OrdinaryCreateFromConstructor(NewTarget, "%DataView.prototype%", « [[DataView]], [[ViewedArrayBuffer]], [[ByteLength]], [[ByteOffset]] »)라고 하자.
  11. IsDetachedBuffer(buffer)가 true이면, TypeError 예외를 던진다.
  12. bufferByteLengthArrayBufferByteLength(buffer, seq-cst)로 설정한다.
  13. offset > bufferByteLength이면, RangeError 예외를 던진다.
  14. byteLengthundefined가 아니면,
    1. offset + viewByteLength > bufferByteLength이면, RangeError 예외를 던진다.
  15. obj.[[ViewedArrayBuffer]]buffer로 설정한다.
  16. obj.[[ByteLength]]viewByteLength로 설정한다.
  17. obj.[[ByteOffset]]offset으로 설정한다.
  18. obj를 반환한다.

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. objthis 값이라고 하자.
  2. RequireInternalSlot(obj, [[DataView]])를 수행한다.
  3. Assert: obj[[ViewedArrayBuffer]] 내부 슬롯을 가진다.
  4. bufferobj.[[ViewedArrayBuffer]]라고 하자.
  5. buffer를 반환한다.

25.3.4.2 get DataView.prototype.byteLength

DataView.prototype.byteLength는 set 접근자 함수가 undefined인 접근자 속성이다. 그 get 접근자 함수는 호출될 때 다음 단계를 수행한다:

  1. objthis 값이라고 하자.
  2. RequireInternalSlot(obj, [[DataView]])를 수행한다.
  3. Assert: obj[[ViewedArrayBuffer]] 내부 슬롯을 가진다.
  4. viewRecordMakeDataViewWithBufferWitnessRecord(obj, seq-cst)라고 하자.
  5. IsViewOutOfBounds(viewRecord)가 true이면, TypeError 예외를 던진다.
  6. sizeGetViewByteLength(viewRecord)라고 하자.
  7. 𝔽(size)를 반환한다.

25.3.4.3 get DataView.prototype.byteOffset

DataView.prototype.byteOffset은 set 접근자 함수가 undefined인 접근자 속성이다. 그 get 접근자 함수는 호출될 때 다음 단계를 수행한다:

  1. objthis 값이라고 하자.
  2. RequireInternalSlot(obj, [[DataView]])를 수행한다.
  3. Assert: obj[[ViewedArrayBuffer]] 내부 슬롯을 가진다.
  4. viewRecordMakeDataViewWithBufferWitnessRecord(obj, seq-cst)라고 하자.
  5. IsViewOutOfBounds(viewRecord)가 true이면, TypeError 예외를 던진다.
  6. offsetobj.[[ByteOffset]]이라고 하자.
  7. 𝔽(offset)을 반환한다.

25.3.4.4 DataView.prototype.constructor

DataView.prototype.constructor의 초기값은 %DataView%이다.

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

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. viewthis 값이라고 하자.
  2. GetViewValue(view, byteOffset, littleEndian, bigint64)를 반환한다.

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

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. viewthis 값이라고 하자.
  2. GetViewValue(view, byteOffset, littleEndian, biguint64)를 반환한다.

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

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. viewthis 값이라고 하자.
  2. littleEndian이 존재하지 않으면, littleEndianfalse로 설정한다.
  3. GetViewValue(view, byteOffset, littleEndian, float16)를 반환한다.

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

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. viewthis 값이라고 하자.
  2. littleEndian이 존재하지 않으면, littleEndianfalse로 설정한다.
  3. GetViewValue(view, byteOffset, littleEndian, float32)를 반환한다.

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

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. viewthis 값이라고 하자.
  2. littleEndian이 존재하지 않으면, littleEndianfalse로 설정한다.
  3. GetViewValue(view, byteOffset, littleEndian, float64)를 반환한다.

25.3.4.10 DataView.prototype.getInt8 ( byteOffset )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. viewthis 값이라고 하자.
  2. GetViewValue(view, byteOffset, true, int8)를 반환한다.

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

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. viewthis 값이라고 하자.
  2. littleEndian이 존재하지 않으면, littleEndianfalse로 설정한다.
  3. GetViewValue(view, byteOffset, littleEndian, int16)를 반환한다.

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

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. viewthis 값이라고 하자.
  2. littleEndian이 존재하지 않으면, littleEndianfalse로 설정한다.
  3. GetViewValue(view, byteOffset, littleEndian, int32)를 반환한다.

25.3.4.13 DataView.prototype.getUint8 ( byteOffset )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. viewthis 값이라고 하자.
  2. GetViewValue(view, byteOffset, true, uint8)를 반환한다.

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

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. viewthis 값이라고 하자.
  2. littleEndian이 존재하지 않으면, littleEndianfalse로 설정한다.
  3. GetViewValue(view, byteOffset, littleEndian, uint16)를 반환한다.

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

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. viewthis 값이라고 하자.
  2. littleEndian이 존재하지 않으면, littleEndianfalse로 설정한다.
  3. GetViewValue(view, byteOffset, littleEndian, uint32)를 반환한다.

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

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. viewthis 값이라고 하자.
  2. SetViewValue(view, byteOffset, littleEndian, bigint64, value)를 반환한다.

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

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. viewthis 값이라고 하자.
  2. SetViewValue(view, byteOffset, littleEndian, biguint64, value)를 반환한다.

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

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. viewthis 값이라고 하자.
  2. littleEndian이 존재하지 않으면, littleEndianfalse로 설정한다.
  3. SetViewValue(view, byteOffset, littleEndian, float16, value)를 반환한다.

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

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. viewthis 값이라고 하자.
  2. littleEndian이 존재하지 않으면, littleEndianfalse로 설정한다.
  3. SetViewValue(view, byteOffset, littleEndian, float32, value)를 반환한다.

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

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. viewthis 값이라고 하자.
  2. littleEndian이 존재하지 않으면, littleEndianfalse로 설정한다.
  3. SetViewValue(view, byteOffset, littleEndian, float64, value)를 반환한다.

25.3.4.21 DataView.prototype.setInt8 ( byteOffset, value )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. viewthis 값이라고 하자.
  2. SetViewValue(view, byteOffset, true, int8, value)를 반환한다.

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

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. viewthis 값이라고 하자.
  2. littleEndian이 존재하지 않으면, littleEndianfalse로 설정한다.
  3. SetViewValue(view, byteOffset, littleEndian, int16, value)를 반환한다.

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

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. viewthis 값이라고 하자.
  2. littleEndian이 존재하지 않으면, littleEndianfalse로 설정한다.
  3. SetViewValue(view, byteOffset, littleEndian, int32, value)를 반환한다.

25.3.4.24 DataView.prototype.setUint8 ( byteOffset, value )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. viewthis 값이라고 하자.
  2. SetViewValue(view, byteOffset, true, uint8, value)를 반환한다.

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

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. viewthis 값이라고 하자.
  2. littleEndian이 존재하지 않으면, littleEndianfalse로 설정한다.
  3. SetViewValue(view, byteOffset, littleEndian, uint16, value)를 반환한다.

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

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. viewthis 값이라고 하자.
  2. littleEndian이 존재하지 않으면, littleEndianfalse로 설정한다.
  3. 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 객체는 공유 메모리 배열 셀에 대해 분할 불가능하게(원자적으로) 동작하는 함수와, agent가 primitive 이벤트를 기다리고 dispatch할 수 있게 하는 함수를 제공한다. 규율 있게 사용하면, Atomics 함수는 공유 메모리를 통해 통신하는 multi-agent 프로그램이 병렬 CPU에서도 잘 이해된 순서로 실행될 수 있게 한다. 공유 메모리 통신을 지배하는 규칙은 아래에 정의된 메모리 모델에 의해 제공된다.

Note

ECMAScript에서 공유 메모리를 프로그래밍하고 구현하기 위한 정보성 지침은 메모리 모델 절 끝의 노트를 보라.

25.4.1 Waiter Record

Waiter RecordAtomics.wait 또는 Atomics.waitAsync의 특정 호출을 나타내는 데 사용되는 Record 값이다.

Waiter Record는 Table 73에 나열된 필드를 가진다.

Table 73: Waiter Record 필드
필드 이름 의미
[[AgentSignifier]] agent signifier Atomics.wait 또는 Atomics.waitAsync를 호출한 agent.
[[PromiseCapability]] PromiseCapability Record 또는 blocking Atomics.waitAsync 호출을 나타내는 경우 결과 promise이고, 그렇지 않으면 blocking.
[[TimeoutTime]] 음이 아닌 확장 수학 값 timeout이 트리거될 수 있는 가장 이른 시간. time value를 사용해 계산된다.
[[Result]] "ok" 또는 "timed-out" 호출의 반환값.

25.4.2 WaiterList Records

WaiterList RecordAtomics.wait, Atomics.waitAsync, 그리고 Atomics.notify를 통한 agent의 대기와 알림을 설명하는 데 사용된다.

WaiterList Record는 Table 74에 나열된 필드를 가진다.

Table 74: WaiterList Record 필드
필드 이름 의미
[[Waiters]] Waiter RecordList 이 WaiterList가 연결된 위치에서 대기 중인 Atomics.wait 또는 Atomics.waitAsync 호출들.
[[MostRecentLeaveEvent]] Synchronize 이벤트 또는 empty 자신의 critical section을 가장 최근에 떠난 이벤트, 또는 그 critical section에 한 번도 진입한 적이 없으면 empty.

WaiterList 안에는 같은 agent signifier를 가진 여러 Waiter Record가 있을 수 있다.

agent cluster는 WaiterList Record들의 저장소를 가진다. 이 저장소는 (block, i)로 색인되며, 여기서 blockShared Data Block이고 iblock의 메모리 안의 바이트 오프셋이다. WaiterList Record는 agent와 독립적이다. agent cluster 안의 어떤 agent에서든 (block, i)로 WaiterList Record 저장소를 조회하면 같은 WaiterList Record가 결과로 나온다.

각 WaiterList Record는 평가 중 그 WaiterList Record에 대한 독점 접근을 제어하는 critical section을 가진다. 한 번에 하나의 agent만 WaiterList Record의 critical section에 들어갈 수 있다. WaiterList Record의 critical section에 들어가고 나오는 것은 추상 연산 EnterCriticalSectionLeaveCriticalSection에 의해 제어된다. WaiterList Record에 대한 연산—대기 중인 agent 추가 및 제거, agent 목록 순회, 목록의 agent 일시 중단 및 알림, Synchronize 이벤트 설정 및 검색—은 WaiterList Record의 critical section에 들어간 agent만 수행할 수 있다.

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 either a normal completion containing a TypedArray With Buffer Witness Record, or a throw completion. It performs the following steps when called:

  1. taRecord를 ? ValidateTypedArray(typedArray, unordered)라고 하자.
  2. NOTE: typedArray의 backing buffer가 증가 가능 SharedArrayBuffer일 때 경계 검사는 동기화 연산이 아니다.
  3. waitabletrue이면,
    1. typedArray.[[TypedArrayName]]"Int32Array""BigInt64Array"도 아니면, TypeError 예외를 던진다.
  4. 그렇지 않으면,
    1. typeTypedArrayElementType(typedArray)이라고 하자.
    2. IsUnclampedIntegerElementType(type)가 false이고 IsBigIntElementType(type)가 false이면, TypeError 예외를 던진다.
  5. taRecord를 반환한다.

25.4.3.2 ValidateAtomicAccess ( taRecord, requestIndex )

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

  1. lengthTypedArrayLength(taRecord)라고 하자.
  2. accessIndex를 ? ToIndex(requestIndex)라고 하자.
  3. Assert: accessIndex ≥ 0.
  4. accessIndexlength이면, RangeError 예외를 던진다.
  5. typedArraytaRecord.[[Object]]라고 하자.
  6. elementSizeTypedArrayElementSize(typedArray)라고 하자.
  7. offsettypedArray.[[ByteOffset]]이라고 하자.
  8. (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 either a normal completion containing a non-negative integer or a throw completion. It performs the following steps when called:

  1. taRecord를 ? ValidateIntegerTypedArray(typedArray, false)라고 하자.
  2. ValidateAtomicAccess(taRecord, requestIndex)를 반환한다.

25.4.3.4 RevalidateAtomicAccess ( typedArray, byteIndexInBuffer )

The abstract operation RevalidateAtomicAccess takes arguments typedArray (a TypedArray) and byteIndexInBuffer (a non-negative integer) and returns either a normal completion containing unused or a throw completion. 이 연산은 Atomics 메서드에서 모든 인자 강제가 수행된 뒤 atomic 연산을 위한 backing buffer 내의 인덱스를 다시 검증한다. 인자 강제는 임의의 부수 효과를 가질 수 있고, 이로 인해 버퍼가 out of bounds가 될 수 있기 때문이다. 이 연산은 typedArray의 backing buffer가 SharedArrayBuffer일 때 예외를 던지지 않는다. It performs the following steps when called:

  1. taRecordMakeTypedArrayWithBufferWitnessRecord(typedArray, unordered)라고 하자.
  2. NOTE: typedArray의 backing buffer가 증가 가능 SharedArrayBuffer일 때 경계 검사는 동기화 연산이 아니다.
  3. IsTypedArrayOutOfBounds(taRecord)가 true이면, TypeError 예외를 던진다.
  4. Assert: byteIndexInBuffertypedArray.[[ByteOffset]].
  5. byteIndexInBuffertaRecord.[[CachedBufferByteLength]]이면, RangeError 예외를 던진다.
  6. unused를 반환한다.

25.4.3.5 GetWaiterList ( block, i )

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

  1. Assert: ii + 3은 block의 메모리 안에서 유효한 바이트 오프셋이다.
  2. 쌍 (block, i)가 참조하는 WaiterList Record를 반환한다.

25.4.3.6 EnterCriticalSection ( waiterList )

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

  1. Assert: 주변 agent는 어떤 WaiterList Recordcritical section에도 있지 않다.
  2. 어떤 agent도 waiterListcritical section 안에 있지 않을 때까지 기다린 다음, waiterListcritical section에 들어간다(다른 agent가 들어오도록 허용하지 않고).
  3. waiterList.[[MostRecentLeaveEvent]]empty가 아니면,
    1. NOTE: critical section에 적어도 한 번 들어간 waiterListLeaveCriticalSection에 의해 설정된 Synchronize 이벤트를 가진다.
    2. agentRecord를 주변 agent의 Agent Record라고 하자.
    3. executionagentRecord.[[CandidateExecution]]이라고 하자.
    4. eventsRecordexecution.[[EventsRecords]][[AgentSignifier]]AgentSignifier()인 Agent Events Record라고 하자.
    5. enterEvent를 새로운 Synchronize 이벤트라고 하자.
    6. enterEventeventsRecord.[[EventList]]에 추가한다.
    7. (waiterList.[[MostRecentLeaveEvent]], enterEvent)를 eventsRecord.[[AgentSynchronizesWith]]에 추가한다.
  4. unused를 반환한다.

EnterCriticalSection은 critical section에 들어가려는 agent가 다른 agent가 그것을 떠날 때까지 기다려야 할 때 contention을 가진다. contention이 없을 때 EnterCriticalSection 호출의 FIFO 순서는 관찰 가능하다. contention이 있을 때 구현은 임의의 순서를 선택할 수 있지만, agent가 무기한 기다리게 해서는 안 된다.

25.4.3.7 LeaveCriticalSection ( waiterList )

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

  1. Assert: 주변 agent는 waiterListcritical section 안에 있다.
  2. agentRecord를 주변 agent의 Agent Record라고 하자.
  3. executionagentRecord.[[CandidateExecution]]이라고 하자.
  4. eventsRecordexecution.[[EventsRecords]][[AgentSignifier]]AgentSignifier()인 Agent Events Record라고 하자.
  5. leaveEvent를 새로운 Synchronize 이벤트라고 하자.
  6. leaveEventeventsRecord.[[EventList]]에 추가한다.
  7. waiterList.[[MostRecentLeaveEvent]]leaveEvent로 설정한다.
  8. waiterListcritical section을 떠난다.
  9. unused를 반환한다.

25.4.3.8 AddWaiter ( waiterList, waiterRecord )

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

  1. Assert: 주변 agent는 waiterListcritical section 안에 있다.
  2. Assert: waiterList.[[Waiters]] 안에는 [[PromiseCapability]] 필드가 waiterRecord.[[PromiseCapability]]이고 [[AgentSignifier]] 필드가 waiterRecord.[[AgentSignifier]]Waiter Record가 없다.
  3. waiterRecordwaiterList.[[Waiters]]에 추가한다.
  4. unused를 반환한다.

25.4.3.9 RemoveWaiter ( waiterList, waiterRecord )

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

  1. Assert: 주변 agent는 waiterListcritical section 안에 있다.
  2. Assert: waiterList.[[Waiters]]waiterRecord를 포함한다.
  3. waiterRecordwaiterList.[[Waiters]]에서 제거한다.
  4. unused를 반환한다.

25.4.3.10 RemoveWaiters ( waiterList, count )

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

  1. Assert: 주변 agent는 waiterListcritical section 안에 있다.
  2. lenwaiterList.[[Waiters]]의 요소 개수라고 하자.
  3. countmin(count, len)으로 설정한다.
  4. waiterswaiterList.[[Waiters]]의 처음 count개 요소를 요소로 가지는 List라고 하자.
  5. waiterList.[[Waiters]]의 처음 count개 요소를 제거한다.
  6. waiters를 반환한다.

25.4.3.11 SuspendThisAgent ( waiterList, waiterRecord )

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

  1. Assert: 주변 agent는 waiterListcritical section 안에 있다.
  2. Assert: waiterList.[[Waiters]]waiterRecord를 포함한다.
  3. thisAgentAgentSignifier()라고 하자.
  4. Assert: waiterRecord.[[AgentSignifier]]thisAgent이다.
  5. Assert: waiterRecord.[[PromiseCapability]]blocking이다.
  6. Assert: AgentCanSuspend()는 true이다.
  7. LeaveCriticalSection(waiterList)를 수행하고 waiterRecord.[[TimeoutTime]] 시간이 될 때까지 주변 agent를 일시 중단하되, critical section을 나간 뒤 suspension이 효력을 발생하기 전에 도착한 알림이 lost되지 않는 방식으로 결합 연산을 수행한다. 주변 agent는 timeout으로 인해 또는 다른 agent가 waiterListthisAgent를 인자로 NotifyWaiter를 호출하는 것(즉 Atomics.notify 호출을 통해)으로만 suspension에서 깨어날 수 있다.
  8. EnterCriticalSection(waiterList)를 수행한다.
  9. unused를 반환한다.

25.4.3.12 NotifyWaiter ( waiterList, waiterRecord )

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

  1. Assert: 주변 agent는 waiterListcritical section 안에 있다.
  2. waiterRecord.[[PromiseCapability]]blocking이면,
    1. signifier가 waiterRecord.[[AgentSignifier]]인 agent를 suspension에서 깨운다.
    2. NOTE: 이는 agent가 SuspendThisAgent 안에서 실행을 재개하게 한다.
  3. 그렇지 않고 AgentSignifier()가 waiterRecord.[[AgentSignifier]]이면,
    1. promiseCapabilitywaiterRecord.[[PromiseCapability]]라고 하자.
    2. Call(promiseCapability.[[Resolve]], undefined, « waiterRecord.[[Result]] »)를 수행한다.
  4. 그렇지 않으면,
    1. EnqueueResolveInAgentJob(waiterRecord.[[AgentSignifier]], waiterRecord.[[PromiseCapability]], waiterRecord.[[Result]])를 수행한다.
  5. unused를 반환한다.
Note

agent는 다른 agent의 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. resolveJobagentSignifier, promiseCapability, 그리고 resolution을 캡처하고 호출될 때 다음 단계를 수행하는, 매개변수가 없는 새로운 Job Abstract Closure라고 하자:
    1. Assert: AgentSignifier()는 agentSignifier이다.
    2. Call(promiseCapability.[[Resolve]], undefined, « resolution »)를 수행한다.
    3. unused를 반환한다.
  2. realmInTargetAgent를 ! GetFunctionRealm(promiseCapability.[[Resolve]])라고 하자.
  3. Assert: agentSignifierrealmInTargetAgent.[[AgentSignifier]]이다.
  4. HostEnqueueGenericJob(resolveJob, realmInTargetAgent)를 수행한다.
  5. unused를 반환한다.

25.4.3.14 DoWait ( mode, 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 either a normal completion containing either an Object, "not-equal", "timed-out", or "ok", or a throw completion. It performs the following steps when called:

  1. taRecord를 ? ValidateIntegerTypedArray(typedArray, true)라고 하자.
  2. buffertaRecord.[[Object]].[[ViewedArrayBuffer]]라고 하자.
  3. IsSharedArrayBuffer(buffer)가 false이면, TypeError 예외를 던진다.
  4. byteIndexInBuffer를 ? ValidateAtomicAccess(taRecord, index)라고 하자.
  5. arrayTypeNametypedArray.[[TypedArrayName]]이라고 하자.
  6. arrayTypeName"BigInt64Array"이면, expected를 ? ToBigInt64(value)라고 하자.
  7. 그렇지 않으면, expected를 ? ToInt32(value)라고 하자.
  8. timeoutNumber를 ? ToNumber(timeout)라고 하자.
  9. timeoutNumberNaN 또는 +∞𝔽이면, realTimeout을 +∞라고 하자.
  10. 그렇지 않고 timeoutNumber-∞𝔽이면, realTimeout을 0이라고 하자.
  11. 그렇지 않으면, realTimeoutmax((timeoutNumber), 0)이라고 하자.
  12. modesync이고 AgentCanSuspend()가 false이면, TypeError 예외를 던진다.
  13. blockbuffer.[[ArrayBufferData]]라고 하자.
  14. waiterListGetWaiterList(block, byteIndexInBuffer)라고 하자.
  15. modesync이면,
    1. promiseCapabilityblocking이라고 하자.
    2. resultObjectundefined라고 하자.
  16. 그렇지 않으면,
    1. promiseCapability를 ! NewPromiseCapability(%Promise%)라고 하자.
    2. resultObjectOrdinaryObjectCreate(%Object.prototype%)라고 하자.
  17. EnterCriticalSection(waiterList)를 수행한다.
  18. elementTypeTypedArrayElementType(typedArray)이라고 하자.
  19. witnessGetValueFromBuffer(buffer, byteIndexInBuffer, elementType, true, seq-cst)라고 하자.
  20. expectedwitness이면,
    1. LeaveCriticalSection(waiterList)를 수행한다.
    2. modesync이면, "not-equal"을 반환한다.
    3. CreateDataPropertyOrThrow(resultObject, "async", false)를 수행한다.
    4. CreateDataPropertyOrThrow(resultObject, "value", "not-equal")를 수행한다.
    5. resultObject를 반환한다.
  21. realTimeout = 0이고 modeasync이면,
    1. NOTE: 동기적 즉시 timeout에 대한 특별한 처리는 없다. 비동기적 즉시 timeout은 빠르게 실패하고 불필요한 Promise job을 피하기 위해 특별한 처리를 가진다.
    2. LeaveCriticalSection(waiterList)를 수행한다.
    3. CreateDataPropertyOrThrow(resultObject, "async", false)를 수행한다.
    4. CreateDataPropertyOrThrow(resultObject, "value", "timed-out")를 수행한다.
    5. resultObject를 반환한다.
  22. thisAgentAgentSignifier()라고 하자.
  23. now를 현재 시간을 식별하는 time value(UTC)라고 하자.
  24. additionalTimeout구현 정의 음이 아닌 수학 값이라고 하자.
  25. timeoutTime(now) + realTimeout + additionalTimeout이라고 하자.
  26. NOTE: realTimeout이 +∞이면, timeoutTime도 +∞이다.
  27. waiterRecord를 새로운 Waiter Record { [[AgentSignifier]]: thisAgent, [[PromiseCapability]]: promiseCapability, [[TimeoutTime]]: timeoutTime, [[Result]]: "ok" }라고 하자.
  28. AddWaiter(waiterList, waiterRecord)를 수행한다.
  29. modesync이면,
    1. SuspendThisAgent(waiterList, waiterRecord)를 수행한다.
  30. 그렇지 않고 timeoutTime유한하면,
    1. EnqueueAtomicsWaitAsyncTimeoutJob(waiterList, waiterRecord)를 수행한다.
  31. LeaveCriticalSection(waiterList)를 수행한다.
  32. modesync이면, waiterRecord.[[Result]]를 반환한다.
  33. CreateDataPropertyOrThrow(resultObject, "async", true)를 수행한다.
  34. CreateDataPropertyOrThrow(resultObject, "value", promiseCapability.[[Promise]])를 수행한다.
  35. resultObject를 반환한다.
Note

additionalTimeout은 구현이 전력 소비를 줄이거나 timing attack을 완화하기 위해 타이머 해상도를 거칠게 만드는 것처럼 필요에 따라 timeout을 padding할 수 있게 한다. 이 값은 DoWait 호출마다 다를 수 있다.

25.4.3.15 EnqueueAtomicsWaitAsyncTimeoutJob ( waiterList, waiterRecord )

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

  1. timeoutJobwaiterListwaiterRecord를 캡처하고 호출될 때 다음 단계를 수행하는, 매개변수가 없는 새로운 Job Abstract Closure라고 하자:
    1. EnterCriticalSection(waiterList)를 수행한다.
    2. waiterList.[[Waiters]]waiterRecord를 포함하면,
      1. timeOfJobExecution을 현재 시간을 식별하는 time value(UTC)라고 하자.
      2. Assert: (time value의 잠재적 비단조성을 무시하면) (timeOfJobExecution) ≥ waiterRecord.[[TimeoutTime]]이다.
      3. waiterRecord.[[Result]]"timed-out"으로 설정한다.
      4. RemoveWaiter(waiterList, waiterRecord)를 수행한다.
      5. NotifyWaiter(waiterList, waiterRecord)를 수행한다.
    3. LeaveCriticalSection(waiterList)를 수행한다.
    4. unused를 반환한다.
  2. now를 현재 시간을 식별하는 time value(UTC)라고 하자.
  3. currentRealm을 현재 Realm Record라고 하자.
  4. HostEnqueueTimeoutJob(timeoutJob, currentRealm, 𝔽(waiterRecord.[[TimeoutTime]]) - now)를 수행한다.
  5. unused를 반환한다.

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

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

  1. agentRecord를 주변 agent의 Agent Record라고 하자.
  2. executionagentRecord.[[CandidateExecution]]이라고 하자.
  3. eventsRecordexecution.[[EventsRecords]][[AgentSignifier]]AgentSignifier()인 Agent Events Record라고 하자.
  4. rawBytesRead를 요소들이 비결정적으로 선택된 바이트 값인 길이 elementSizeList라고 하자.
  5. NOTE: 구현에서 rawBytesRead는 기반 하드웨어에서 load-link, load-exclusive 또는 read-modify-write 명령의 피연산자 결과이다. 비결정성은 약한 일관성을 가진 하드웨어의 관찰 가능한 동작을 설명하기 위한 메모리 모델의 의미론적 규정이다.
  6. NOTE: 기대 값과 읽은 값의 비교는 기대 값이 읽은 값과 같지 않을 때 불필요하게 강한 동기화를 피하기 위해 read-modify-write 수정 함수 바깥에서 수행된다.
  7. ByteListEqual(rawBytesRead, expectedBytes)가 true이면,
    1. second를 아무것도 캡처하지 않고 호출될 때 원자적으로 다음 단계를 수행하는, 매개변수 (oldBytes, newBytes)를 가진 새로운 read-modify-write 수정 함수라고 하자:
      1. newBytes를 반환한다.
    2. eventReadModifyWriteSharedMemory { [[Order]]: seq-cst, [[NoTear]]: true, [[Block]]: block, [[ByteIndex]]: byteIndexInBuffer, [[ElementSize]]: elementSize, [[Payload]]: replacementBytes, [[ModifyOp]]: second }라고 하자.
  8. 그렇지 않으면,
    1. eventReadSharedMemory { [[Order]]: seq-cst, [[NoTear]]: true, [[Block]]: block, [[ByteIndex]]: byteIndexInBuffer, [[ElementSize]]: elementSize }라고 하자.
  9. eventeventsRecord.[[EventList]]에 추가한다.
  10. Chosen Value Record { [[Event]]: event, [[ChosenValue]]: rawBytesRead }를 execution.[[ChosenValues]]에 추가한다.
  11. 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 either a normal completion containing either a Number or a BigInt, or a throw completion. op는 바이트 값의 두 List 인자를 받아 바이트 값의 List를 반환한다. 이 연산은 값을 원자적으로 로드하고, 다른 값과 결합한 뒤, 그 결합을 저장한다. 로드된 값을 반환한다. It performs the following steps when called:

  1. byteIndexInBuffer를 ? ValidateAtomicAccessOnIntegerTypedArray(typedArray, index)라고 하자.
  2. typedArray.[[ContentType]]bigint이면 coerced를 ? ToBigInt(value)라고 하자.
  3. 그렇지 않으면, coerced𝔽(? ToIntegerOrInfinity(value))라고 하자.
  4. RevalidateAtomicAccess(typedArray, byteIndexInBuffer)를 수행한다.
  5. buffertypedArray.[[ViewedArrayBuffer]]라고 하자.
  6. elementTypeTypedArrayElementType(typedArray)이라고 하자.
  7. GetModifySetValueInBuffer(buffer, byteIndexInBuffer, elementType, coerced, op)를 반환한다.

25.4.3.18 ByteListBitwiseOp ( op, xBytes, yBytes )

The abstract operation ByteListBitwiseOp takes arguments op (&, ^, or |), xBytes (a List of byte values), and yBytes (a List of byte values) and returns a List of byte values. 이 연산은 인자의 모든 바이트 값에 대해 비트 연산을 원자적으로 수행하고 바이트 값의 List를 반환한다. It performs the following steps when called:

  1. Assert: xBytesyBytes는 같은 수의 요소를 가진다.
  2. result를 새로운 빈 List라고 하자.
  3. i를 0이라고 하자.
  4. xBytes의 각 요소 xByte에 대해, 다음을 수행한다.
    1. yByteyBytes[i]라고 하자.
    2. op&이면,
      1. resultBytexByteyByte에 비트 AND 연산을 적용한 결과라고 하자.
    3. 그렇지 않고 op^이면,
      1. resultBytexByteyByte에 비트 배타적 OR(XOR) 연산을 적용한 결과라고 하자.
    4. 그렇지 않으면,
      1. Assert: op|이다.
      2. resultBytexByteyByte에 비트 포함 OR 연산을 적용한 결과라고 하자.
    5. ii + 1로 설정한다.
    6. resultByteresult에 추가한다.
  5. result를 반환한다.

25.4.3.19 ByteListEqual ( xBytes, yBytes )

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

  1. xBytesyBytes가 같은 수의 요소를 가지지 않으면, false를 반환한다.
  2. i를 0이라고 하자.
  3. xBytes의 각 요소 xByte에 대해, 다음을 수행한다.
    1. yByteyBytes[i]라고 하자.
    2. xByteyByte이면, false를 반환한다.
    3. ii + 1로 설정한다.
  4. true를 반환한다.

25.4.4 Atomics.add ( typedArray, index, value )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. addtypedArray를 캡처하고 호출될 때 원자적으로 다음 단계를 수행하는, 매개변수 (xBytes, yBytes)를 가진 새로운 read-modify-write 수정 함수라고 하자:
    1. typeTypedArrayElementType(typedArray)이라고 하자.
    2. agentRecord를 주변 agent의 Agent Record라고 하자.
    3. isLittleEndianagentRecord.[[LittleEndian]]이라고 하자.
    4. xRawBytesToNumeric(type, xBytes, isLittleEndian)라고 하자.
    5. yRawBytesToNumeric(type, yBytes, isLittleEndian)라고 하자.
    6. x가 Number이면,
      1. sumNumber::add(x, y)라고 하자.
    7. 그렇지 않으면,
      1. Assert: x는 BigInt이다.
      2. sumBigInt::add(x, y)라고 하자.
    8. sumBytesNumericToRawBytes(type, sum, isLittleEndian)라고 하자.
    9. Assert: sumBytes, xBytes, 그리고 yBytes는 같은 수의 요소를 가진다.
    10. sumBytes를 반환한다.
  2. AtomicReadModifyWrite(typedArray, index, value, add)를 반환한다.

25.4.5 Atomics.and ( typedArray, index, value )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. and를 아무것도 캡처하지 않고 호출될 때 원자적으로 다음 단계를 수행하는, 매개변수 (xBytes, yBytes)를 가진 새로운 read-modify-write 수정 함수라고 하자:
    1. ByteListBitwiseOp(&, xBytes, yBytes)를 반환한다.
  2. AtomicReadModifyWrite(typedArray, index, value, and)를 반환한다.

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

이 함수는 호출될 때 다음 단계를 수행한다:

  1. byteIndexInBuffer를 ? ValidateAtomicAccessOnIntegerTypedArray(typedArray, index)라고 하자.
  2. buffertypedArray.[[ViewedArrayBuffer]]라고 하자.
  3. blockbuffer.[[ArrayBufferData]]라고 하자.
  4. typedArray.[[ContentType]]bigint이면,
    1. expected를 ? ToBigInt(expectedValue)라고 하자.
    2. replacement를 ? ToBigInt(replacementValue)라고 하자.
  5. 그렇지 않으면,
    1. expected𝔽(? ToIntegerOrInfinity(expectedValue))라고 하자.
    2. replacement𝔽(? ToIntegerOrInfinity(replacementValue))라고 하자.
  6. RevalidateAtomicAccess(typedArray, byteIndexInBuffer)를 수행한다.
  7. elementTypeTypedArrayElementType(typedArray)이라고 하자.
  8. elementSizeTypedArrayElementSize(typedArray)라고 하자.
  9. agentRecord를 주변 agent의 Agent Record라고 하자.
  10. isLittleEndianagentRecord.[[LittleEndian]]이라고 하자.
  11. expectedBytesNumericToRawBytes(elementType, expected, isLittleEndian)라고 하자.
  12. replacementBytesNumericToRawBytes(elementType, replacement, isLittleEndian)라고 하자.
  13. IsSharedArrayBuffer(buffer)가 true이면,
    1. rawBytesReadAtomicCompareExchangeInSharedBlock(block, byteIndexInBuffer, elementSize, expectedBytes, replacementBytes)라고 하자.
  14. 그렇지 않으면,
    1. rawBytesReadblock[byteIndexInBuffer]로 시작하는 elementSize개의 바이트 시퀀스를 요소로 가지는 길이 elementSizeList라고 하자.
    2. ByteListEqual(rawBytesRead, expectedBytes)가 true이면,
      1. replacementBytes의 개별 바이트들을 block[byteIndexInBuffer]에서 시작하여 block에 저장한다.
  15. RawBytesToNumeric(elementType, rawBytesRead, isLittleEndian)를 반환한다.

25.4.7 Atomics.exchange ( typedArray, index, value )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. second를 아무것도 캡처하지 않고 호출될 때 원자적으로 다음 단계를 수행하는, 매개변수 (oldBytes, newBytes)를 가진 새로운 read-modify-write 수정 함수라고 하자:
    1. newBytes를 반환한다.
  2. AtomicReadModifyWrite(typedArray, index, value, second)를 반환한다.

25.4.8 Atomics.isLockFree ( size )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. n을 ? ToIntegerOrInfinity(size)라고 하자.
  2. agentRecord를 주변 agent의 Agent Record라고 하자.
  3. n = 1이면, agentRecord.[[IsLockFree1]]을 반환한다.
  4. n = 2이면, agentRecord.[[IsLockFree2]]를 반환한다.
  5. n = 4이면, true를 반환한다.
  6. n = 8이면, agentRecord.[[IsLockFree8]]을 반환한다.
  7. false를 반환한다.
Note

이 함수는 최적화 primitive이다. 직관은 크기 n 바이트의 datum에 대한 atomic primitive(compareExchange, load, store, add, sub, and, or, xor, 또는 exchange)의 원자적 단계가 주변 agent가 그 datum을 구성하는 n 바이트 외부의 lock을 획득하지 않고 수행된다면, Atomics.isLockFree(n)가 true를 반환한다는 것이다. 고성능 알고리즘은 이 함수를 사용하여 critical section에서 lock을 사용할지 atomic 연산을 사용할지 결정한다. atomic primitive가 lock-free가 아니면 알고리즘이 자체 locking을 제공하는 것이 종종 더 효율적이다.

Atomics.isLockFree(4)는 알려진 모든 관련 하드웨어에서 지원될 수 있으므로 항상 true를 반환한다. 이를 가정할 수 있으면 일반적으로 프로그램이 단순해진다.

이 함수가 반환하는 값과 관계없이 모든 atomic 연산은 원자적임이 보장된다. 예를 들어 연산 도중에 visible operation이 발생하는 일은 결코 없다(예: "tearing").

25.4.9 Atomics.load ( typedArray, index )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. byteIndexInBuffer를 ? ValidateAtomicAccessOnIntegerTypedArray(typedArray, index)라고 하자.
  2. RevalidateAtomicAccess(typedArray, byteIndexInBuffer)를 수행한다.
  3. buffertypedArray.[[ViewedArrayBuffer]]라고 하자.
  4. elementTypeTypedArrayElementType(typedArray)이라고 하자.
  5. GetValueFromBuffer(buffer, byteIndexInBuffer, elementType, true, seq-cst)를 반환한다.

25.4.10 Atomics.or ( typedArray, index, value )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. or를 아무것도 캡처하지 않고 호출될 때 원자적으로 다음 단계를 수행하는, 매개변수 (xBytes, yBytes)를 가진 새로운 read-modify-write 수정 함수라고 하자:
    1. ByteListBitwiseOp(|, xBytes, yBytes)를 반환한다.
  2. AtomicReadModifyWrite(typedArray, index, value, or)를 반환한다.

25.4.11 Atomics.store ( typedArray, index, value )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. byteIndexInBuffer를 ? ValidateAtomicAccessOnIntegerTypedArray(typedArray, index)라고 하자.
  2. typedArray.[[ContentType]]bigint이면 coerced를 ? ToBigInt(value)라고 하자.
  3. 그렇지 않으면, coerced𝔽(? ToIntegerOrInfinity(value))라고 하자.
  4. RevalidateAtomicAccess(typedArray, byteIndexInBuffer)를 수행한다.
  5. buffertypedArray.[[ViewedArrayBuffer]]라고 하자.
  6. elementTypeTypedArrayElementType(typedArray)이라고 하자.
  7. SetValueInBuffer(buffer, byteIndexInBuffer, elementType, coerced, true, seq-cst)를 수행한다.
  8. coerced를 반환한다.

25.4.12 Atomics.sub ( typedArray, index, value )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. subtracttypedArray를 캡처하고 호출될 때 원자적으로 다음 단계를 수행하는, 매개변수 (xBytes, yBytes)를 가진 새로운 read-modify-write 수정 함수라고 하자:
    1. typeTypedArrayElementType(typedArray)이라고 하자.
    2. agentRecord를 주변 agent의 Agent Record라고 하자.
    3. isLittleEndianagentRecord.[[LittleEndian]]이라고 하자.
    4. xRawBytesToNumeric(type, xBytes, isLittleEndian)라고 하자.
    5. yRawBytesToNumeric(type, yBytes, isLittleEndian)라고 하자.
    6. x가 Number이면,
      1. differenceNumber::subtract(x, y)라고 하자.
    7. 그렇지 않으면,
      1. Assert: x는 BigInt이다.
      2. differenceBigInt::subtract(x, y)라고 하자.
    8. differenceBytesNumericToRawBytes(type, difference, isLittleEndian)라고 하자.
    9. Assert: differenceBytes, xBytes, 그리고 yBytes는 같은 수의 요소를 가진다.
    10. differenceBytes를 반환한다.
  2. AtomicReadModifyWrite(typedArray, index, value, subtract)를 반환한다.

25.4.13 Atomics.wait ( typedArray, index, value, timeout )

이 함수는 주변 agent를 wait queue에 넣고 알림을 받거나 wait가 timeout될 때까지 일시 중단하며, 그 경우들을 구별하는 String을 반환한다.

호출될 때 다음 단계를 수행한다:

  1. DoWait(sync, typedArray, index, value, timeout)를 반환한다.

25.4.14 Atomics.waitAsync ( typedArray, index, value, timeout )

이 함수는 호출하는 agent가 알림을 받거나 timeout에 도달하면 resolve되는 Promise를 반환한다.

호출될 때 다음 단계를 수행한다:

  1. DoWait(async, typedArray, index, value, timeout)를 반환한다.

25.4.15 Atomics.notify ( typedArray, index, count )

이 함수는 wait queue에서 잠자고 있는 일부 agent들에게 알린다.

호출될 때 다음 단계를 수행한다:

  1. taRecord를 ? ValidateIntegerTypedArray(typedArray, true)라고 하자.
  2. byteIndexInBuffer를 ? ValidateAtomicAccess(taRecord, index)라고 하자.
  3. countundefined이면,
    1. count를 +∞로 설정한다.
  4. 그렇지 않으면,
    1. intCount를 ? ToIntegerOrInfinity(count)라고 하자.
    2. countmax(intCount, 0)으로 설정한다.
  5. buffertypedArray.[[ViewedArrayBuffer]]라고 하자.
  6. blockbuffer.[[ArrayBufferData]]라고 하자.
  7. IsSharedArrayBuffer(buffer)가 false이면, +0𝔽을 반환한다.
  8. waiterListGetWaiterList(block, byteIndexInBuffer)라고 하자.
  9. EnterCriticalSection(waiterList)를 수행한다.
  10. waitersRemoveWaiters(waiterList, count)라고 하자.
  11. waiters의 각 요소 waiterRecord에 대해, 다음을 수행한다.
    1. NotifyWaiter(waiterList, waiterRecord)를 수행한다.
  12. LeaveCriticalSection(waiterList)를 수행한다.
  13. nwaiters의 요소 개수라고 하자.
  14. 𝔽(n)를 반환한다.

25.4.16 Atomics.xor ( typedArray, index, value )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. xor를 아무것도 캡처하지 않고 호출될 때 원자적으로 다음 단계를 수행하는, 매개변수 (xBytes, yBytes)를 가진 새로운 read-modify-write 수정 함수라고 하자:
    1. ByteListBitwiseOp(^, xBytes, yBytes)를 반환한다.
  2. 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 Data Interchange Format은 ECMA-404에 정의되어 있다. 이 명세에서 사용되는 JSON interchange format은 ECMA-404에 설명된 것과 정확히 같다. JSON.parseJSON.stringify의 적합한 구현은 형식에서 어떤 삭제나 확장도 없이 ECMA-404 명세에 설명된 정확한 interchange format을 지원해야 한다.

25.5.1 JSON.isRawJSON ( obj )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. obj가 Object이고 obj[[IsRawJSON]] 내부 슬롯을 가지면, true를 반환한다.
  2. false를 반환한다.

25.5.2 JSON.parse ( text [ , reviver ] )

이 함수는 JSON 텍스트(JSON 형식의 String)를 구문 분석하고 ECMAScript 언어 값을 생성한다. JSON 형식은 ECMAScript 리터럴, Array Initializer, Object Initializer의 구문과 유사한 구문으로 리터럴, 배열, 객체를 표현한다. 구문 분석 후 JSON 객체는 ECMAScript 객체로 실현된다. JSON 배열은 ECMAScript Array 인스턴스로 실현된다. JSON 문자열, 숫자, 불리언, null은 ECMAScript String, Number, Boolean, 그리고 null로 실현된다.

선택적 reviver 매개변수는 결과를 필터링하고 변환할 수 있는 함수이다. parse에 의해 생성된 각 값에 대해, reviver는 세 인자(연관된 속성 키, 값, 그리고 context 객체)와 함께 호출된다. 속성이 수정되지 않았고 그 값이 primitive이면, 제공된 context 객체는 대응하는 Parse Node의 소스 텍스트를 포함하는 "source" 속성을 가진다. 호출이 undefined를 반환하면, 속성은 삭제된다. 그렇지 않으면, 속성은 반환값을 사용하도록 재정의된다.

  1. jsonString을 ? ToString(text)라고 하자.
  2. parseResult를 ? ParseJSON(jsonString)라고 하자.
  3. unfilteredparseResult.[[Value]]라고 하자.
  4. IsCallable(reviver)가 false이면, unfiltered를 반환한다.
  5. rootOrdinaryObjectCreate(%Object.prototype%)라고 하자.
  6. rootName을 빈 String이라고 하자.
  7. CreateDataPropertyOrThrow(root, rootName, unfiltered)를 수행한다.
  8. snapshotCreateJSONParseRecord(parseResult.[[ParseNode]], rootName, unfiltered)라고 하자.
  9. InternalizeJSONProperty(root, rootName, reviver, snapshot)를 반환한다.

이 함수의 "length" 속성은 2𝔽이다.

25.5.2.1 ParseJSON ( text )

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

  1. StringToCodePoints(text)가 ECMA-404에 지정된 유효한 JSON 텍스트가 아니면, SyntaxError 예외를 던진다.
  2. scriptString"(", text, 그리고 ");"의 문자열 연결이라고 하자.
  3. scriptParseText(scriptString, Script)라고 하자.
  4. NOTE: 13.2.5.1에 정의된 early error 규칙은 위 ParseText 호출에 대해 특별한 처리를 가진다.
  5. Assert: script는 Parse Node이다.
  6. result를 ! scriptEvaluation이라고 하자.
  7. NOTE: 13.2.5.6에 정의된 PropertyDefinitionEvaluation 의미론은 위 평가에 대해 특별한 처리를 가진다.
  8. Assert: result는 String, Number, Boolean, ArrayLiteral 또는 ObjectLiteral 중 하나에 의해 정의되는 Object, 또는 null 중 하나이다.
  9. Record { [[ParseNode]]: script, [[Value]]: result }를 반환한다.

JSON.parse의 적합한 구현이 JSON 문법을 확장하는 것은 허용되지 않는다. 구현이 수정되거나 확장된 JSON interchange format을 지원하고자 한다면, 다른 parse 함수를 정의하여 그렇게 해야 한다.

Note 1

유효한 JSON 텍스트는 ECMAScript PrimaryExpression 구문의 부분집합이다. 단계 1jsonString이 그 부분집합에 부합하는지 검증하고, 단계 8는 평가가 적절한 타입의 값을 반환함을 단언한다.

그러나 13.2.5.6가 ParseJSON 동안 다르게 동작하기 때문에, 동일한 소스 텍스트가 JSON으로 평가될 때와 PrimaryExpression으로 평가될 때 서로 다른 결과를 생성할 수 있다. 더 나아가, 객체 리터럴에서 중복 "__proto__" 속성에 대한 Early Error 역시 ParseJSON 동안 적용되지 않으므로, ParseJSON이 받아들이는 모든 텍스트가 문법과 일치함에도 PrimaryExpression으로 유효한 것은 아니다.

Note 2

객체 안에 중복 name String이 있는 경우, 같은 키에 대해 어휘적으로 앞서는 값은 덮어써진다.

25.5.2.2 JSON Parse Record

JSON Parse Record는 JSON 텍스트에서 구문 분석된 값의 초기 상태를 설명하는 데 사용되는 Record 값이다.

JSON Parse Record는 Table 75에 나열된 필드를 가진다.

Table 75: JSON Parse Record 필드
필드 이름 의미
[[ParseNode]] Parse Node context Parse Node.
[[Key]] 속성 이름 [[Value]]와 연관된 속성 이름.
[[Value]] ECMAScript 언어 값 [[ParseNode]]의 평가에 의해 생성된 값.
[[Elements]] JSON Parse RecordList [[Value]]가 Array이면, 이는 [[Value]]의 요소에 대응하는 JSON Parse Record들을 포함한다. 그렇지 않으면, 이는 빈 List이다.
[[Entries]] JSON Parse RecordList [[Value]]가 Array가 아닌 Object이면, 이는 [[Value]]의 엔트리에 대응하는 JSON Parse Record들을 포함한다. 그렇지 않으면, 이는 빈 List이다.

25.5.2.3 CreateJSONParseRecord ( parseNode, key, val )

The abstract operation CreateJSONParseRecord takes arguments parseNode (a Parse Node), key (a property name), and val (an ECMAScript language value) and returns a JSON Parse Record. JSON 텍스트에서 구문 분석된 parseNode와 그 평가에 의해 생성된 val을 재귀적으로 결합한다. It performs the following steps when called:

  1. typedValNodeShallowestContainedJSONValue(parseNode)라고 하자.
  2. Assert: typedValNodeempty가 아니다.
  3. elements를 새로운 빈 List라고 하자.
  4. entries를 새로운 빈 List라고 하자.
  5. val이 Object이면,
    1. isArray를 ! IsArray(val)라고 하자.
    2. isArraytrue이면,
      1. Assert: typedValNodeArrayLiteral Parse Node이다.
      2. contentNodestypedValNodeJSONArrayLiteralContentNodes라고 하자.
      3. lencontentNodes의 요소 개수라고 하자.
      4. valLen을 ! LengthOfArrayLike(val)라고 하자.
      5. Assert: valLenlen이다.
      6. index를 0이라고 하자.
      7. index < len인 동안 반복한다,
        1. propName을 ! ToString(𝔽(index))라고 하자.
        2. elementParseRecordCreateJSONParseRecord(contentNodes[index], propName, ! Get(val, propName))라고 하자.
        3. elementParseRecordelements에 추가한다.
        4. indexindex + 1로 설정한다.
    3. 그렇지 않으면,
      1. Assert: typedValNodeObjectLiteral Parse Node이다.
      2. propertyNodestypedValNodePropertyDefinitionNodes라고 하자.
      3. NOTE: val은 JSON 텍스트에서 생성되었고 수정되지 않았으므로, 그 모든 속성 키는 String이며 완전히 열거된다.
      4. keys를 ! EnumerableOwnProperties(val, key)라고 하자.
      5. keys의 각 String propertyKey에 대해, 다음을 수행한다.
        1. NOTE: JSON 텍스트가 단일 객체에 대해 같은 이름을 가진 여러 name/value 쌍(예: {"a":"lost","a":"kept"})을 지정하는 경우, 결과 ECMAScript 객체의 대응 속성 값은 그 이름을 가진 마지막 쌍에 의해 지정된다.
        2. propertyDefinitionempty라고 하자.
        3. propertyNodes의 각 Parse Node propertyNode에 대해, 다음을 수행한다.
          1. propNamepropertyNodePropName이라고 하자.
          2. propNamepropertyKey이면, propertyDefinitionpropertyNode로 설정한다.
        4. Assert: propertyDefinition PropertyDefinition : PropertyName : AssignmentExpression 이다.
        5. propertyValueNodepropertyDefinitionAssignmentExpression이라고 하자.
        6. entryParseRecordCreateJSONParseRecord(propertyValueNode, propertyKey, ! Get(val, propertyKey))라고 하자.
        7. entryParseRecordentries에 추가한다.
  6. 그렇지 않으면,
    1. Assert: typedValNodeArrayLiteral Parse Node도 ObjectLiteral Parse Node도 아니다.
  7. JSON Parse Record { [[ParseNode]]: typedValNode, [[Key]]: key, [[Value]]: val, [[Elements]]: elements, [[Entries]]: entries }를 반환한다.

25.5.2.4 InternalizeJSONProperty ( holder, name, reviver, parseRecord )

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

Note

이 알고리즘은 [[Delete]] 또는 CreateDataPropertyfalse를 반환해도 의도적으로 예외를 던지지 않는다.

호출될 때 다음 단계를 수행한다:

  1. val을 ? Get(holder, name)라고 하자.
  2. contextOrdinaryObjectCreate(%Object.prototype%)라고 하자.
  3. parseRecordJSON Parse Record이고 SameValue(parseRecord.[[Value]], val)가 true이면,
    1. val이 Object가 아니면,
      1. parseNodeparseRecord.[[ParseNode]]라고 하자.
      2. Assert: parseNodeArrayLiteral Parse Node도 ObjectLiteral Parse Node도 아니다.
      3. sourceTextparseNode일치한 소스 텍스트라고 하자.
      4. CreateDataPropertyOrThrow(context, "source", CodePointsToString(sourceText))를 수행한다.
    2. elementRecordsparseRecord.[[Elements]]라고 하자.
    3. entryRecordsparseRecord.[[Entries]]라고 하자.
  4. 그렇지 않으면,
    1. elementRecords를 새로운 빈 List라고 하자.
    2. entryRecords를 새로운 빈 List라고 하자.
  5. val이 Object이면,
    1. isArray를 ? IsArray(val)라고 하자.
    2. isArraytrue이면,
      1. elementRecordsLenelementRecords의 요소 개수라고 하자.
      2. len을 ? LengthOfArrayLike(val)라고 하자.
      3. index를 0이라고 하자.
      4. index < len인 동안 반복한다,
        1. propertyKey를 ! ToString(𝔽(index))라고 하자.
        2. index < elementRecordsLen이면 elementRecordelementRecords[index]라고 하자; 그렇지 않으면 elementRecordempty라고 하자.
        3. newElement를 ? InternalizeJSONProperty(val, propertyKey, reviver, elementRecord)라고 하자.
        4. newElementundefined이면,
          1. val.[[Delete]](propertyKey)를 수행한다.
        5. 그렇지 않으면,
          1. CreateDataProperty(val, propertyKey, newElement)를 수행한다.
        6. indexindex + 1로 설정한다.
    3. 그렇지 않으면,
      1. keys를 ? EnumerableOwnProperties(val, key)라고 하자.
      2. keys의 각 String propertyKey에 대해, 다음을 수행한다.
        1. entryRecords의 요소 entryentry.[[Key]]propertyKey인 것이 존재하면 entryRecordentry라고 하자; 그렇지 않으면 entryRecordempty라고 하자.
        2. newElement를 ? InternalizeJSONProperty(val, propertyKey, reviver, entryRecord)라고 하자.
        3. newElementundefined이면,
          1. val.[[Delete]](propertyKey)를 수행한다.
        4. 그렇지 않으면,
          1. CreateDataProperty(val, propertyKey, newElement)를 수행한다.
  6. Call(reviver, holder, « name, val, context »)를 반환한다.

25.5.2.5 Static Semantics: ShallowestContainedJSONValue ( root )

The abstract operation ShallowestContainedJSONValue takes argument root (a Parse Node) and returns a Parse Node or empty. root에 뿌리를 둔 parse tree에 대해 breadth-first search를 수행하고, JSON 값에 대응하는 nonterminal의 인스턴스인 첫 번째 노드를 반환하거나, 그러한 노드가 없으면 empty를 반환한다. It performs the following steps when called:

  1. activeFuncactive function object라고 하자.
  2. Assert: activeFuncJSON.parse 내장 함수 객체이다(JSON.parse 참조).
  3. types를 « NullLiteral, BooleanLiteral, NumericLiteral, StringLiteral, ArrayLiteral, ObjectLiteral, UnaryExpression »라고 하자.
  4. unaryExpressionempty라고 하자.
  5. queue를 « root »라고 하자.
  6. queue가 비어 있지 않은 동안 반복한다,
    1. candidatequeue의 첫 번째 요소라고 하자.
    2. queue에서 첫 번째 요소를 제거한다.
    3. queuedChildrenfalse라고 하자.
    4. types의 각 nonterminal type에 대해, 다음을 수행한다.
      1. candidatetype의 인스턴스이면,
        1. NOTE: JSON 문법에서 number 토큰은 음수 값을 나타낼 수 있다. ECMAScript에서 부정은 UnaryExpression- 뒤에 파생 UnaryExpression이 오는 것으로 구문 분석되는 단항 연산으로 표현된다.
        2. typeUnaryExpression이면,
          1. candidate의 부모가 UnaryExpression Parse Node가 아니면, unaryExpressioncandidate로 설정한다.
        3. 그렇지 않고 typeNumericLiteral이면,
          1. Assert: candidateunaryExpression 안에 포함되어 있다.
          2. unaryExpression을 반환한다.
        4. 그렇지 않으면,
          1. candidate를 반환한다.
      2. queuedChildrenfalse이고, candidate가 nonterminal의 인스턴스이며, candidate Contains typetrue이면,
        1. childrencandidate의 각 child node를 순서대로 포함하는 List라고 하자.
        2. queuequeuechildren의 리스트 연결로 설정한다.
        3. queuedChildrentrue로 설정한다.
  7. empty를 반환한다.

25.5.2.6 Static Semantics: JSONArrayLiteralContentNodes

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

ArrayLiteral : [ Elisionopt ] [ ElementList ] [ ElementList , Elisionopt ]
  1. Assert: Elision은 존재하지 않는다.
  2. ElementList가 존재하지 않으면, 새로운 빈 List를 반환한다.
  3. ElementListJSONArrayLiteralContentNodes를 반환한다.
ElementList : Elisionopt AssignmentExpression
  1. Assert: Elision은 존재하지 않는다.
  2. « AssignmentExpression »를 반환한다.
ElementList : ElementList , Elisionopt AssignmentExpression
  1. Assert: Elision은 존재하지 않는다.
  2. elements를 파생된 ElementListJSONArrayLiteralContentNodes라고 하자.
  3. elements와 « AssignmentExpression »의 리스트 연결을 반환한다.
ElementList : Elisionopt SpreadElement ElementList , Elisionopt SpreadElement
  1. NOTE: ECMA-404에 지정된 JSON 텍스트는 SpreadElement를 포함하지 않는다.
  2. Assert: 이 단계에는 결코 도달하지 않는다.

25.5.3 JSON.rawJSON ( text )

이 함수는 string, number, boolean, 또는 null 값의 raw JSON 텍스트를 나타내는 객체를 반환한다.

  1. jsonString을 ? ToString(text)라고 하자.
  2. jsonString이 빈 String이면, SyntaxError 예외를 던진다.
  3. jsonString의 첫 번째 코드 단위가 ASCII 소문자 코드 단위(0x0061부터 0x007A까지 포함), ASCII 숫자 코드 단위(0x0030부터 0x0039까지 포함), 0x0022 (QUOTATION MARK), 또는 0x002D (HYPHEN-MINUS) 중 어느 것도 아니면, SyntaxError 예외를 던진다.
  4. jsonString의 마지막 코드 단위가 ASCII 소문자 코드 단위(0x0061부터 0x007A까지 포함), ASCII 숫자 코드 단위(0x0030부터 0x0039까지 포함), 또는 0x0022 (QUOTATION MARK) 중 어느 것도 아니면, SyntaxError 예외를 던진다.
  5. parseResult를 ? ParseJSON(jsonString)라고 하자.
  6. Assert: parseResult.[[Value]]는 String, Number, Boolean, 또는 null 중 하나이다.
  7. internalSlotsList를 « [[IsRawJSON]] »라고 하자.
  8. objOrdinaryObjectCreate(null, internalSlotsList)라고 하자.
  9. CreateDataPropertyOrThrow(obj, "rawJSON", jsonString)를 수행한다.
  10. SetIntegrityLevel(obj, frozen)를 수행한다.
  11. obj를 반환한다.

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

이 함수는 ECMAScript 언어 값을 나타내는 UTF-16 인코딩 JSON 형식의 String 또는 undefined를 반환한다. 세 매개변수를 받을 수 있다. value 매개변수는 ECMAScript 언어 값으로, 보통 객체나 배열이지만 String, Boolean, Number 또는 null일 수도 있다. 선택적 replacer 매개변수는 객체와 배열이 stringified되는 방식을 변경하는 함수이거나, stringified될 객체 속성을 선택하기 위한 포함 목록으로 동작하는 String과 Number의 배열이다. 선택적 space 매개변수는 결과에 공백을 삽입하여 사람이 읽기 쉽게 할 수 있는 String 또는 Number이다.

호출될 때 다음 단계를 수행한다:

  1. stack을 새로운 빈 List라고 하자.
  2. indent를 빈 String이라고 하자.
  3. propertyListundefined라고 하자.
  4. replacerFunctionundefined라고 하자.
  5. replacer가 Object이면,
    1. IsCallable(replacer)가 true이면,
      1. replacerFunctionreplacer로 설정한다.
    2. 그렇지 않으면,
      1. isArray를 ? IsArray(replacer)라고 하자.
      2. isArraytrue이면,
        1. propertyList를 새로운 빈 List로 설정한다.
        2. len을 ? LengthOfArrayLike(replacer)라고 하자.
        3. k를 0이라고 하자.
        4. k < len인 동안 반복한다,
          1. propertyKey를 ! ToString(𝔽(k))라고 하자.
          2. propertyValue를 ? Get(replacer, propertyKey)라고 하자.
          3. itemundefined라고 하자.
          4. propertyValue가 String이면,
            1. itempropertyValue로 설정한다.
          5. 그렇지 않고 propertyValue가 Number이면,
            1. item을 ! ToString(propertyValue)으로 설정한다.
          6. 그렇지 않고 propertyValue가 Object이면,
            1. propertyValue[[StringData]] 또는 [[NumberData]] 내부 슬롯을 가지면, item을 ? ToString(propertyValue)로 설정한다.
          7. itemundefined가 아니고 propertyListitem을 포함하지 않으면,
            1. itempropertyList에 추가한다.
          8. kk + 1로 설정한다.
  6. space가 Object이면,
    1. space[[NumberData]] 내부 슬롯을 가지면,
      1. space를 ? ToNumber(space)로 설정한다.
    2. 그렇지 않고 space[[StringData]] 내부 슬롯을 가지면,
      1. space를 ? ToString(space)로 설정한다.
  7. space가 Number이면,
    1. spaceMV를 ! ToIntegerOrInfinity(space)라고 하자.
    2. spaceMVmin(10, spaceMV)로 설정한다.
    3. spaceMV < 1이면 gap을 빈 String이라고 하자; 그렇지 않으면 gap을 코드 단위 0x0020 (SPACE)의 spaceMV회 발생을 포함하는 String 값이라고 하자.
  8. 그렇지 않고 space가 String이면,
    1. space의 길이가 ≤ 10이면 gapspace라고 하자; 그렇지 않으면 gapspace의 0부터 10까지의 부분 문자열이라고 하자.
  9. 그렇지 않으면,
    1. gap을 빈 String이라고 하자.
  10. wrapperOrdinaryObjectCreate(%Object.prototype%)라고 하자.
  11. CreateDataPropertyOrThrow(wrapper, 빈 String, value)를 수행한다.
  12. stateJSON Serialization Record { [[ReplacerFunction]]: replacerFunction, [[Stack]]: stack, [[Indent]]: indent, [[Gap]]: gap, [[PropertyList]]: propertyList }라고 하자.
  13. SerializeJSONProperty(state, 빈 String, wrapper)를 반환한다.

이 함수의 "length" 속성은 3𝔽이다.

Note 1

JSON 구조는 임의의 깊이로 중첩될 수 있지만, 비순환이어야 한다. value가 순환 구조이거나 순환 구조를 포함하면, 이 함수는 TypeError 예외를 던져야 한다. 다음은 stringify할 수 없는 값의 예이다:

a = [];
a[0] = a;
my_text = JSON.stringify(a); // 이는 TypeError를 던져야 한다.
Note 2

Symbolic primitive 값은 다음과 같이 렌더링된다:

  • null 값은 JSON 텍스트에서 String 값 "null"로 렌더링된다.
  • undefined 값은 렌더링되지 않는다.
  • true 값은 JSON 텍스트에서 String 값 "true"로 렌더링된다.
  • false 값은 JSON 텍스트에서 String 값 "false"로 렌더링된다.
Note 3

String 값은 QUOTATION MARK (") 코드 단위로 감싸진다. 코드 단위 "\\ 접두사로 escape된다. 제어 문자 코드 단위는 escape sequence \uHHHH 또는 더 짧은 형식 \b (BACKSPACE), \f (FORM FEED), \n (LINE FEED), \r (CARRIAGE RETURN), \t (CHARACTER TABULATION)로 대체된다.

Note 4

유한한 숫자는 ToString(number)을 호출한 것처럼 stringify된다. 부호와 관계없이 NaNInfinity는 String 값 "null"로 표현된다.

Note 5

JSON 표현을 가지지 않는 값(예: undefined 및 함수)은 String을 생성하지 않는다. 대신 undefined 값을 생성한다. 배열에서 이러한 값은 String 값 "null"로 표현된다. 객체에서는 표현 불가능한 값으로 인해 해당 속성이 stringification에서 제외된다.

Note 6

객체는 U+007B (LEFT CURLY BRACKET) 뒤에 U+002C (COMMA)로 구분된 0개 이상의 속성이 오고, U+007D (RIGHT CURLY BRACKET)로 닫히는 방식으로 렌더링된다. 속성은 속성 이름을 나타내는 따옴표로 감싼 String, U+003A (COLON), 그리고 stringified된 속성 값이다. 배열은 여는 U+005B (LEFT SQUARE BRACKET) 뒤에 U+002C (COMMA)로 구분된 0개 이상의 값이 오고, 닫는 U+005D (RIGHT SQUARE BRACKET)로 렌더링된다.

25.5.4.1 JSON Serialization Record

JSON Serialization Record는 JSON 형식으로의 직렬화를 가능하게 하는 데 사용되는 Record 값이다.

JSON Serialization Record는 Table 76에 나열된 필드를 가진다.

Table 76: JSON Serialization Record 필드
필드 이름 의미
[[ReplacerFunction]] 함수 객체 또는 undefined 객체 속성에 대한 대체 값을 제공할 수 있는 함수(JSON.stringify의 replacer 매개변수에서 옴).
[[PropertyList]] String의 List 또는 undefined 배열이 아닌 객체를 직렬화할 때 포함할 속성의 이름(JSON.stringify의 replacer 매개변수에서 옴).
[[Gap]] String 들여쓰기의 단위(JSON.stringify의 space 매개변수에서 옴).
[[Stack]] Object의 List 직렬화가 진행 중인 중첩 객체들의 집합. 순환 구조를 감지하는 데 사용된다.
[[Indent]] String 현재 들여쓰기.

25.5.4.2 SerializeJSONProperty ( state, key, holder )

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

  1. value를 ? Get(holder, key)이라고 하라.
  2. value가 Object이거나 value가 BigInt이면,
    1. toJSON을 ? GetV(value, "toJSON")이라고 하라.
    2. IsCallable(toJSON)이 true이면,
      1. value를 ? Call(toJSON, value, « key »)로 설정하라.
  3. state.[[ReplacerFunction]]undefined가 아니면,
    1. value를 ? Call(state.[[ReplacerFunction]], holder, « key, value »)로 설정하라.
  4. value가 Object이면,
    1. value[[IsRawJSON]] 내부 슬롯이 있으면,
      1. rawJSON을 ! Get(value, "rawJSON")이라고 하라.
      2. Assert: rawJSON은 String이다.
      3. rawJSON을 반환하라.
    2. value[[NumberData]] 내부 슬롯이 있으면,
      1. value를 ? ToNumber(value)로 설정하라.
    3. 그렇지 않고 value[[StringData]] 내부 슬롯이 있으면,
      1. value를 ? ToString(value)로 설정하라.
    4. 그렇지 않고 value[[BooleanData]] 내부 슬롯이 있으면,
      1. valuevalue.[[BooleanData]]로 설정하라.
    5. 그렇지 않고 value[[BigIntData]] 내부 슬롯이 있으면,
      1. valuevalue.[[BigIntData]]로 설정하라.
  5. valuenull이면, "null"을 반환하라.
  6. valuetrue이면, "true"를 반환하라.
  7. valuefalse이면, "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. isArraytrue이면,
      1. SerializeJSONArray(state, value)를 반환하라.
    3. SerializeJSONObject(state, value)를 반환하라.
  12. undefined를 반환하라.

25.5.4.3 QuoteJSONString ( value )

The abstract operation QuoteJSONString takes argument value (a String) and returns a String. value를 0x0022 (QUOTATION MARK) 코드 단위로 감싸고 그 안의 특정 다른 코드 단위를 escape한다. 이 연산은 6.1.4에 설명된 대로 value를 UTF-16으로 인코딩된 코드 포인트의 시퀀스로 해석한다. It performs the following steps when called:

  1. product를 코드 단위 0x0022 (QUOTATION MARK)만으로 구성된 String 값이라고 하자.
  2. StringToCodePoints(value)의 각 코드 포인트 cp에 대해, 다음을 수행한다.
    1. cpTable 77의 “Code Point” 열에 나열되어 있으면,
      1. productproduct와 대응하는 행의 “Escape Sequence” 열에 지정된 cp에 대한 escape sequence의 문자열 연결로 설정한다.
    2. 그렇지 않고 cp의 숫자 값이 0x0020 (SPACE)보다 작거나 cpleading surrogate 또는 trailing surrogate와 같은 숫자 값을 가지면,
      1. unitcp의 숫자 값과 같은 숫자 값을 가진 코드 단위라고 하자.
      2. productproductUnicodeEscape(unit)의 문자열 연결로 설정한다.
    3. 그렇지 않으면,
      1. productproductUTF16EncodeCodePoint(cp)의 문자열 연결로 설정한다.
  3. productproduct와 코드 단위 0x0022 (QUOTATION MARK)의 문자열 연결로 설정한다.
  4. product를 반환한다.
Table 77: JSON 단일 문자 escape sequence
코드 포인트 Unicode 문자 이름 Escape Sequence
U+0008 BACKSPACE \b
U+0009 CHARACTER TABULATION \t
U+000A LINE FEED (LF) \n
U+000C FORM FEED (FF) \f
U+000D CARRIAGE RETURN (CR) \r
U+0022 QUOTATION MARK \"
U+005C REVERSE SOLIDUS \\

25.5.4.4 UnicodeEscape ( constructor )

The abstract operation UnicodeEscape takes argument constructor (a code unit) and returns a String. constructor를 Unicode escape sequence로 나타낸다. It performs the following steps when called:

  1. nconstructor의 숫자 값이라고 하자.
  2. Assert: n ≤ 0xFFFF.
  3. hex를 소문자 16진수로 형식화한 n의 String 표현이라고 하자.
  4. 코드 단위 0x005C (REVERSE SOLIDUS), "u", 그리고 StringPad(hex, 4, "0", start)의 문자열 연결을 반환한다.

25.5.4.5 SerializeJSONObject ( state, value )

The abstract operation SerializeJSONObject takes arguments state (a JSON Serialization Record) and value (an Object) and returns either a normal completion containing a String or a throw completion. 객체를 직렬화한다. It performs the following steps when called:

  1. state.[[Stack]]value를 포함하면, 구조가 순환적이므로 TypeError 예외를 던진다.
  2. valuestate.[[Stack]]에 추가한다.
  3. stepBackstate.[[Indent]]라고 하자.
  4. state.[[Indent]]state.[[Indent]]state.[[Gap]]의 문자열 연결로 설정한다.
  5. state.[[PropertyList]]undefined가 아니면,
    1. keysstate.[[PropertyList]]라고 하자.
  6. 그렇지 않으면,
    1. keys를 ? EnumerableOwnProperties(value, key)라고 하자.
  7. partial을 새로운 빈 List라고 하자.
  8. keys의 각 요소 propertyKey에 대해, 다음을 수행한다.
    1. strP를 ? SerializeJSONProperty(state, propertyKey, value)라고 하자.
    2. strPundefined가 아니면,
      1. memberQuoteJSONString(propertyKey)라고 하자.
      2. membermember":"의 문자열 연결로 설정한다.
      3. state.[[Gap]]이 빈 String이 아니면,
        1. membermember와 코드 단위 0x0020 (SPACE)의 문자열 연결로 설정한다.
      4. membermemberstrP의 문자열 연결로 설정한다.
      5. memberpartial에 추가한다.
  9. partial이 비어 있으면,
    1. final"{}"라고 하자.
  10. 그렇지 않으면,
    1. state.[[Gap]]이 빈 String이면,
      1. propertiespartial의 모든 요소 String을 연결하되 인접한 각 String 쌍 사이에 코드 단위 0x002C (COMMA)를 넣어 형성된 String 값이라고 하자. 첫 번째 String 앞이나 마지막 String 뒤에는 쉼표를 삽입하지 않는다.
      2. final"{", properties, 그리고 "}"의 문자열 연결이라고 하자.
    2. 그렇지 않으면,
      1. separator를 코드 단위 0x002C (COMMA), 코드 단위 0x000A (LINE FEED), 그리고 state.[[Indent]]의 문자열 연결이라고 하자.
      2. propertiespartial의 모든 요소 String을 연결하되 인접한 각 String 쌍 사이에 separator를 넣어 형성된 String 값이라고 하자. separator String은 첫 번째 String 앞이나 마지막 String 뒤에는 삽입하지 않는다.
      3. final"{", 코드 단위 0x000A (LINE FEED), state.[[Indent]], properties, 코드 단위 0x000A (LINE FEED), stepBack, 그리고 "}"의 문자열 연결이라고 하자.
  11. state.[[Stack]]의 마지막 요소를 제거한다.
  12. state.[[Indent]]stepBack으로 설정한다.
  13. final을 반환한다.

25.5.4.6 SerializeJSONArray ( state, value )

The abstract operation SerializeJSONArray takes arguments state (a JSON Serialization Record) and value (an Object) and returns either a normal completion containing a String or a throw completion. 배열을 직렬화한다. It performs the following steps when called:

  1. state.[[Stack]]value를 포함하면, 구조가 순환적이므로 TypeError 예외를 던진다.
  2. valuestate.[[Stack]]에 추가한다.
  3. stepBackstate.[[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. strPundefined이면,
      1. "null"partial에 추가한다.
    3. 그렇지 않으면,
      1. strPpartial에 추가한다.
    4. indexindex + 1로 설정한다.
  9. partial이 비어 있으면,
    1. final"[]"라고 하자.
  10. 그렇지 않으면,
    1. state.[[Gap]]이 빈 String이면,
      1. propertiespartial의 모든 요소 String을 연결하되 인접한 각 String 쌍 사이에 코드 단위 0x002C (COMMA)를 넣어 형성된 String 값이라고 하자. 첫 번째 String 앞이나 마지막 String 뒤에는 쉼표를 삽입하지 않는다.
      2. final"[", properties, 그리고 "]"의 문자열 연결이라고 하자.
    2. 그렇지 않으면,
      1. separator를 코드 단위 0x002C (COMMA), 코드 단위 0x000A (LINE FEED), 그리고 state.[[Indent]]의 문자열 연결이라고 하자.
      2. propertiespartial의 모든 요소 String을 연결하되 인접한 각 String 쌍 사이에 separator를 넣어 형성된 String 값이라고 하자. separator String은 첫 번째 String 앞이나 마지막 String 뒤에는 삽입하지 않는다.
      3. final"[", 코드 단위 0x000A (LINE FEED), state.[[Indent]], properties, 코드 단위 0x000A (LINE FEED), stepBack, 그리고 "]"의 문자열 연결이라고 하자.
  11. state.[[Stack]]의 마지막 요소를 제거한다.
  12. state.[[Indent]]stepBack으로 설정한다.
  13. final을 반환한다.
Note

배열의 표현에는 +0𝔽(포함)부터 array.length(제외)까지의 구간에 있는 요소만 포함된다. 키가 배열 인덱스가 아닌 속성은 stringification에서 제외된다. 배열은 여는 LEFT SQUARE BRACKET, COMMA로 구분된 요소들, 그리고 닫는 RIGHT SQUARE BRACKET으로 stringified된다.

25.5.5 JSON [ %Symbol.toStringTag% ]

%Symbol.toStringTag% 속성의 초기값은 String 값 "JSON"이다.

이 속성은 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true } 속성 특성을 가진다.

26 메모리 관리

26.1 WeakRef 객체

WeakRef는 대상 객체 또는 심벌이 가비지 컬렉션으로부터 보존되도록 하지 않으면서 그것을 참조하는 데 사용되는 객체이다. WeakRef는 대상 값이 가비지 컬렉션에 의해 회수되지 않았다면 그 대상 값에 접근할 수 있도록 역참조될 수 있다.

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 값을 반환하면, 이 target 값은 ECMAScript 코드의 현재 실행이 완료될 때까지 가비지 컬렉션되어서는 안 된다. AddToKeptObjects 연산은 읽기 일관성이 유지되도록 보장한다.

let target = { foo() {} };
let weakRef = new WeakRef(target);

// ... 나중에 ...

if (weakRef.deref()) {
  weakRef.deref().foo();
}

위 예에서 첫 번째 deref가 undefined로 평가되지 않으면 두 번째 deref도 그렇게 평가될 수 없다.

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. targetweakRef.[[WeakRefTarget]]이라고 하자.
  2. targetempty가 아니면,
    1. AddToKeptObjects(target)를 수행한다.
    2. target을 반환한다.
  3. undefined를 반환한다.
Note

추상 연산은 liveness를 간결하게 정의할 수 있게 하기 위해서만 WeakRef.prototype.deref와 별도로 정의된다.

26.1.5 WeakRef 인스턴스의 속성

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. fnactive function object라고 하자.
  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. unregisterTokenempty로 설정한다.
  6. cellRecord { [[WeakRefTarget]]: target, [[HeldValue]]: heldValue, [[UnregisterToken]]: unregisterToken }이라고 하자.
  7. cellfinalizationRegistry.[[Cells]]에 추가한다.
  8. undefined를 반환한다.
Note

이 명세의 알고리즘과 정의에 따르면 finalizationRegistry.[[Cells]]cell을 포함할 때 cell.[[HeldValue]]live이다. 그러나 이것이 반드시 cell.[[UnregisterToken]] 또는 cell.[[Target]]live임을 의미하지는 않는다. 예를 들어, 객체를 자기 자신을 unregister token으로 하여 등록한다고 해서 그 객체가 영원히 live 상태로 유지되지는 않는다.

26.2.3.3 FinalizationRegistry.prototype.unregister ( unregisterToken )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. finalizationRegistrythis 값이라고 하자.
  2. RequireInternalSlot(finalizationRegistry, [[Cells]])를 수행한다.
  3. CanBeHeldWeakly(unregisterToken)가 false이면, TypeError 예외를 던진다.
  4. removedfalse라고 하자.
  5. finalizationRegistry.[[Cells]]의 각 Record { [[WeakRefTarget]], [[HeldValue]], [[UnregisterToken]] } cell에 대해, 다음을 수행한다.
    1. cell.[[UnregisterToken]]empty가 아니고 SameValue(cell.[[UnregisterToken]], unregisterToken)가 true이면,
      1. cellfinalizationRegistry.[[Cells]]에서 제거한다.
      2. removedtrue로 설정한다.
  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 프로토타입 객체로부터 속성을 상속하는 보통 객체이다. FinalizationRegistry 인스턴스는 또한 [[Cells]][[CleanupCallback]] 내부 슬롯을 가진다.

27 제어 추상화 객체

27.1 반복

27.1.1 공통 반복 인터페이스

인터페이스는 관련 값이 특정 명세와 일치하는 프로퍼티 키의 집합이다. 인터페이스의 명세에 설명된 모든 프로퍼티를 제공하는 모든 객체는 그 인터페이스를 준수한다. 인터페이스는 별개의 객체로 표현되지 않는다. 어떤 인터페이스를 준수하는 객체는 별도로 구현된 것이 많이 있을 수 있다. 개별 객체는 여러 인터페이스를 준수할 수 있다.

27.1.1.1 Iterable 인터페이스

iterable 인터페이스Table 78에 설명된 프로퍼티를 포함한다:

Table 78: Iterable 인터페이스 필수 프로퍼티
프로퍼티 요구 사항
%Symbol.iterator% iterator 객체를 반환하는 함수 반환된 객체는 iterator 인터페이스를 준수해야 한다.

27.1.1.2 Iterator 인터페이스

iterator 인터페이스를 구현하는 객체는 Table 79의 프로퍼티를 포함해야 한다. 그러한 객체는 Table 80의 프로퍼티도 구현할 수 있다.

Table 79: Iterator 인터페이스 필수 프로퍼티
프로퍼티 요구 사항
"next" IteratorResult 객체를 반환하는 함수 반환된 객체는 IteratorResult 인터페이스를 준수해야 한다. iteratornext 메서드에 대한 이전 호출이 "done" 프로퍼티가 true인 IteratorResult 객체를 반환했다면, 그 객체의 next 메서드에 대한 모든 이후 호출도 "done" 프로퍼티가 true인 IteratorResult 객체를 반환해야 한다. 그러나 이 요구 사항은 강제되지 않는다.
Note 1

next 함수에 인자를 전달할 수 있지만, 그 해석과 유효성은 대상 iterator에 따라 달라진다. for-of 문과 iterator의 다른 일반적인 사용자는 어떤 인자도 전달하지 않으므로, 그러한 방식으로 사용될 것으로 예상하는 iterator 객체는 인자 없이 호출되는 경우를 처리할 준비가 되어 있어야 한다.

Table 80: Iterator 인터페이스 선택 프로퍼티
프로퍼티 요구 사항
"return" IteratorResult 객체를 반환하는 함수 반환된 객체는 IteratorResult 인터페이스를 준수해야 한다. 이 메서드를 호출하면 호출자가 iterator에 대해 더 이상 next 메서드 호출을 할 의도가 없음을 iterator 객체에 알린다. 반환된 IteratorResult 객체는 일반적으로 값이 true"done" 프로퍼티와, return 메서드의 인자로 전달된 값을 갖는 "value" 프로퍼티를 가진다. 그러나 이 요구 사항은 강제되지 않는다.
"throw" IteratorResult 객체를 반환하는 함수 반환된 객체는 IteratorResult 인터페이스를 준수해야 한다. 이 메서드를 호출하면 호출자가 오류 조건을 감지했음을 iterator 객체에 알린다. 인자는 오류 조건을 식별하는 데 사용될 수 있으며 일반적으로 예외 객체가 된다. 전형적인 응답은 인자로 전달된 값을 throw하는 것이다. 메서드가 throw하지 않으면, 반환된 IteratorResult 객체는 일반적으로 값이 true"done" 프로퍼티를 가진다.
Note 2

일반적으로 이러한 메서드의 호출자는 호출하기 전에 그 존재 여부를 확인해야 한다. for-of, yield*, 배열 구조 분해를 포함한 특정 ECMAScript 언어 기능은 존재 여부 확인을 수행한 뒤 이러한 메서드를 호출한다. iterable 객체를 인자로 받는 대부분의 ECMAScript 라이브러리 함수도 이를 조건부로 호출한다.

27.1.1.3 Async Iterable 인터페이스

async iterable 인터페이스Table 81에 설명된 프로퍼티를 포함한다:

Table 81: Async Iterable 인터페이스 필수 프로퍼티
프로퍼티 요구 사항
%Symbol.asyncIterator% async iterator 객체를 반환하는 함수 반환된 객체는 async iterator 인터페이스를 준수해야 한다.

27.1.1.4 Async Iterator 인터페이스

async iterator 인터페이스를 구현하는 객체는 Table 82의 프로퍼티를 포함해야 한다. 그러한 객체는 Table 83의 프로퍼티도 구현할 수 있다.

Table 82: Async Iterator 인터페이스 필수 프로퍼티
프로퍼티 요구 사항
"next" IteratorResult 객체에 대한 promise를 반환하는 함수

반환된 promise는 이행될 때 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 83: Async Iterator 인터페이스 선택 프로퍼티
프로퍼티 요구 사항
"return" IteratorResult 객체에 대한 promise를 반환하는 함수

반환된 promise는 이행될 때 IteratorResult 인터페이스를 준수하는 객체로 이행되어야 한다. 이 메서드를 호출하면 호출자가 async iterator에 대해 더 이상 next 메서드 호출을 할 의도가 없음을 async iterator 객체에 알린다. 반환된 promise는 일반적으로 값이 true"done" 프로퍼티와, return 메서드의 인자로 전달된 값을 갖는 "value" 프로퍼티를 가진 IteratorResult 객체로 이행된다. 그러나 이 요구 사항은 강제되지 않는다.

추가로, 이행 값으로 쓰이는 IteratorResult 객체는 값이 promise(또는 "thenable")가 아닌 "value" 프로퍼티를 가져야 한다. 인자 값이 전형적인 방식으로 사용된다면, 그것이 거부된 promise인 경우 같은 이유로 거부된 promise가 반환되어야 하며, 그것이 이행된 promise인 경우 그 이행 값이 반환된 promise의 IteratorResult 객체 이행 값의 "value" 프로퍼티로 사용되어야 한다. 그러나 이러한 요구 사항도 강제되지 않는다.

"throw" IteratorResult 객체에 대한 promise를 반환하는 함수

반환된 promise는 이행될 때 IteratorResult 인터페이스를 준수하는 객체로 이행되어야 한다. 이 메서드를 호출하면 호출자가 오류 조건을 감지했음을 async iterator 객체에 알린다. 인자는 오류 조건을 식별하는 데 사용될 수 있으며 일반적으로 예외 객체가 된다. 전형적인 응답은 인자로 전달된 값으로 거부되는 거부된 promise를 반환하는 것이다.

반환된 promise가 이행되면, IteratorResult 객체 이행 값은 일반적으로 값이 true"done" 프로퍼티를 가진다. 추가로, 값이 promise(또는 "thenable")가 아닌 "value" 프로퍼티를 가져야 하지만, 이 요구 사항은 강제되지 않는다.

Note 2

일반적으로 이러한 메서드의 호출자는 호출하기 전에 그 존재 여부를 확인해야 한다. for-await-ofyield*를 포함한 특정 ECMAScript 언어 기능은 존재 여부 확인을 수행한 뒤 이러한 메서드를 호출한다.

27.1.1.5 IteratorResult 인터페이스

IteratorResult 인터페이스Table 84에 나열된 프로퍼티를 포함한다:

Table 84: IteratorResult 인터페이스 프로퍼티
프로퍼티 요구 사항
"done" Boolean 이는 iterator next 메서드 호출의 결과 상태이다. iterator의 끝에 도달했다면 "done"true이다. 끝에 도달하지 않았다면 "done"false이며 값을 사용할 수 있다. "done" 프로퍼티(자체 또는 상속된)가 존재하지 않으면, 그 값은 false인 것으로 간주된다.
"value" ECMAScript 언어 값 done이 false이면, 이는 현재 반복 요소 값이다. done이 true이면, 이는 iterator가 제공한 경우 iterator의 반환 값이다. iterator에 반환 값이 없으면, "value"undefined이다. 이 경우, 명시적인 "value" 프로퍼티를 상속하지 않는다면 준수 객체에서 "value" 프로퍼티가 없을 수 있다.

27.1.2 Iterator Helper 객체

Iterator Helper 객체는 어떤 특정 소스 iterator 객체의 지연 변환을 나타내는 ordinary object이다. Iterator Helper 객체에는 이름이 있는 생성자가 없다. 대신, Iterator Helper 객체는 Iterator 인스턴스 객체의 특정 메서드를 호출하여 생성된다.

27.1.2.1 %IteratorHelperPrototype% 객체

%IteratorHelperPrototype% 객체:

27.1.2.1.1 %IteratorHelperPrototype%.next ( )

  1. GeneratorResume(this value, undefined, "Iterator Helper")를 반환한다.

27.1.2.1.2 %IteratorHelperPrototype%.return ( )

  1. objthis value로 둔다.
  2. RequireInternalSlot(obj, [[UnderlyingIterators]])를 수행한다.
  3. Assert: obj[[GeneratorState]] 내부 슬롯을 가진다.
  4. obj.[[GeneratorState]]suspended-start이면,
    1. obj.[[GeneratorState]]completed로 설정한다.
    2. NOTE: generator가 completed 상태에 들어가면 그 상태를 결코 떠나지 않으며 관련 실행 컨텍스트는 다시 재개되지 않는다. obj와 관련된 모든 실행 상태는 이 시점에서 폐기될 수 있다.
    3. IteratorCloseAll(obj.[[UnderlyingIterators]], NormalCompletion(unused))를 수행한다.
    4. CreateIteratorResultObject(undefined, true)를 반환한다.
  5. completionReturnCompletion(undefined)으로 둔다.
  6. GeneratorResumeAbrupt(obj, completion, "Iterator Helper")를 반환한다.

27.1.2.1.3 %IteratorHelperPrototype% [ %Symbol.toStringTag% ]

%Symbol.toStringTag% 프로퍼티의 초기 값은 String 값 "Iterator Helper"이다.

이 프로퍼티는 속성 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }를 가진다.

27.1.3 Iterator 객체

27.1.3.1 Iterator 생성자

Iterator 생성자:

  • %Iterator%이다.
  • 전역 객체"Iterator" 프로퍼티의 초기 값이다.
  • 서브클래싱할 수 있도록 설계되었다. 클래스 정의의 extends 절의 값으로 사용될 수 있다.

27.1.3.1.1 Iterator ( )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. NewTarget이 undefined이거나 활성 함수 객체이면, TypeError 예외를 던진다.
  2. OrdinaryCreateFromConstructor(NewTarget, "%Iterator.prototype%")를 반환한다.

27.1.3.2 Iterator 생성자의 프로퍼티

Iterator 생성자:

  • 값이 %Function.prototype%[[Prototype]] 내부 슬롯을 가진다.
  • 다음 프로퍼티를 가진다:

27.1.3.2.1 Iterator.concat ( ...items )

  1. iterables를 새로운 빈 List로 둔다.
  2. items의 각 요소 item에 대해, 다음을 수행한다
    1. item이 Object가 아니면, TypeError 예외를 던진다.
    2. method를 ? GetMethod(item, %Symbol.iterator%)로 둔다.
    3. methodundefined이면, TypeError 예외를 던진다.
    4. Record { [[OpenMethod]]: method, [[Iterable]]: item }을 iterables에 추가한다.
  3. iterables를 캡처하고 호출될 때 다음 단계를 수행하는, 매개변수가 없는 새로운 Abstract Closureclosure를 둔다:
    1. iterables의 각 Record iterable에 대해, 다음을 수행한다
      1. iter를 ? Call(iterable.[[OpenMethod]], iterable.[[Iterable]])로 둔다.
      2. iter가 Object가 아니면, TypeError 예외를 던진다.
      3. iteratorRecord를 ? GetIteratorDirect(iter)로 둔다.
      4. innerAlivetrue로 둔다.
      5. innerAlivetrue인 동안 반복한다,
        1. innerValue를 ? IteratorStepValue(iteratorRecord)로 둔다.
        2. innerValuedone이면,
          1. innerAlivefalse로 설정한다.
        3. 그렇지 않으면,
          1. completionCompletion(Yield(innerValue))로 둔다.
          2. completionabrupt completion이면,
            1. IteratorClose(iteratorRecord, completion)를 반환한다.
    2. ReturnCompletion(undefined)를 반환한다.
  4. genCreateIteratorFromClosure(closure, "Iterator Helper", %IteratorHelperPrototype%, « [[UnderlyingIterators]] »)로 둔다.
  5. gen.[[UnderlyingIterators]]를 새로운 빈 List로 설정한다.
  6. gen을 반환한다.

27.1.3.2.2 Iterator.from ( obj )

  1. iteratorRecord를 ? GetIteratorFlattenable(obj, iterate-string-primitives)로 둔다.
  2. hasInstance를 ? OrdinaryHasInstance(%Iterator%, iteratorRecord.[[Iterator]])로 둔다.
  3. hasInstancetrue이면,
    1. iteratorRecord.[[Iterator]]를 반환한다.
  4. wrapperOrdinaryObjectCreate(%WrapForValidIteratorPrototype%, « [[Iterated]] »)로 둔다.
  5. wrapper.[[Iterated]]iteratorRecord로 설정한다.
  6. wrapper를 반환한다.

27.1.3.2.2.1 %WrapForValidIteratorPrototype% 객체

%WrapForValidIteratorPrototype% 객체:

27.1.3.2.2.1.1 %WrapForValidIteratorPrototype%.next ( )

  1. objthis value로 둔다.
  2. RequireInternalSlot(obj, [[Iterated]])를 수행한다.
  3. iteratorRecordobj.[[Iterated]]로 둔다.
  4. Call(iteratorRecord.[[NextMethod]], iteratorRecord.[[Iterator]])를 반환한다.

27.1.3.2.2.1.2 %WrapForValidIteratorPrototype%.return ( )

  1. objthis value로 둔다.
  2. RequireInternalSlot(obj, [[Iterated]])를 수행한다.
  3. iteratorobj.[[Iterated]].[[Iterator]]로 둔다.
  4. Assert: iterator는 Object이다.
  5. returnMethod를 ? GetMethod(iterator, "return")로 둔다.
  6. returnMethodundefined이면,
    1. CreateIteratorResultObject(undefined, true)를 반환한다.
  7. Call(returnMethod, iterator)를 반환한다.

27.1.3.2.3 Iterator.prototype

Iterator.prototype의 초기 값은 Iterator prototype object이다.

이 프로퍼티는 속성 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }를 가진다.

27.1.3.3 Iterator Prototype Object의 프로퍼티

Iterator prototype object:

Note

이 명세에서 iterator 인터페이스를 구현하도록 정의된 모든 객체도 %Iterator.prototype%에서 상속한다. ECMAScript 코드도 %Iterator.prototype%에서 상속하는 객체를 정의할 수 있다. %Iterator.prototype%은 모든 iterator 객체에 적용 가능한 추가 메서드가 추가될 수 있는 위치를 제공한다.

다음 표현식은 ECMAScript 코드가 %Iterator.prototype% 객체에 접근할 수 있는 한 가지 방법이다:

Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()))

27.1.3.3.1 Iterator.prototype.constructor

Iterator.prototype.constructor는 속성 { [[Enumerable]]: false, [[Configurable]]: true }를 가진 accessor property이다. [[Get]][[Set]] 속성은 다음과 같이 정의된다:

27.1.3.3.1.1 get Iterator.prototype.constructor

[[Get]] 속성의 값은 인자를 필요로 하지 않는 built-in function이다. 호출될 때 다음 단계를 수행한다:

  1. %Iterator%를 반환한다.

27.1.3.3.1.2 set Iterator.prototype.constructor

[[Set]] 속성의 값은 인자 v를 받는 built-in function이다. 호출될 때 다음 단계를 수행한다:

  1. SetterThatIgnoresPrototypeProperties(this value, %Iterator.prototype%, "constructor", v)를 수행한다.
  2. undefined를 반환한다.
Note

대부분의 built-in prototype의 "constructor" 프로퍼티와 달리, 웹 호환성상의 이유로 이 프로퍼티는 accessor여야 한다.

27.1.3.3.2 Iterator.prototype.drop ( limit )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. objthis value로 둔다.
  2. obj가 Object가 아니면, TypeError 예외를 던진다.
  3. iteratedIterator Record { [[Iterator]]: obj, [[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(obj)로 설정한다.
  10. iteratedintegerLimit를 캡처하고 호출될 때 다음 단계를 수행하는, 매개변수가 없는 새로운 Abstract Closureclosure를 둔다:
    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%, « [[UnderlyingIterators]] »)로 둔다.
  12. result.[[UnderlyingIterators]]를 « iterated »로 설정한다.
  13. result를 반환한다.

27.1.3.3.3 Iterator.prototype.every ( predicate )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. objthis value로 둔다.
  2. obj가 Object가 아니면, TypeError 예외를 던진다.
  3. iteratedIterator Record { [[Iterator]]: obj, [[NextMethod]]: undefined, [[Done]]: false }로 둔다.
  4. IsCallable(predicate)가 false이면,
    1. errorThrowCompletion(새로 생성된 TypeError 객체)로 둔다.
    2. IteratorClose(iterated, error)를 반환한다.
  5. iterated를 ? GetIteratorDirect(obj)로 설정한다.
  6. counter를 0으로 둔다.
  7. 반복한다,
    1. value를 ? IteratorStepValue(iterated)로 둔다.
    2. valuedone이면, true를 반환한다.
    3. resultCompletion(Call(predicate, undefined, « value, 𝔽(counter) »))로 둔다.
    4. IfAbruptCloseIterator(result, iterated).
    5. ToBoolean(result)가 false이면, ? IteratorClose(iterated, NormalCompletion(false))를 반환한다.
    6. countercounter + 1로 설정한다.

27.1.3.3.4 Iterator.prototype.filter ( predicate )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. objthis value로 둔다.
  2. obj가 Object가 아니면, TypeError 예외를 던진다.
  3. iteratedIterator Record { [[Iterator]]: obj, [[NextMethod]]: undefined, [[Done]]: false }로 둔다.
  4. IsCallable(predicate)가 false이면,
    1. errorThrowCompletion(새로 생성된 TypeError 객체)로 둔다.
    2. IteratorClose(iterated, error)를 반환한다.
  5. iterated를 ? GetIteratorDirect(obj)로 설정한다.
  6. iteratedpredicate를 캡처하고 호출될 때 다음 단계를 수행하는, 매개변수가 없는 새로운 Abstract Closureclosure를 둔다:
    1. counter를 0으로 둔다.
    2. 반복한다,
      1. value를 ? IteratorStepValue(iterated)로 둔다.
      2. valuedone이면, ReturnCompletion(undefined)를 반환한다.
      3. selectedCompletion(Call(predicate, undefined, « value, 𝔽(counter) »))로 둔다.
      4. IfAbruptCloseIterator(selected, iterated).
      5. ToBoolean(selected)가 true이면,
        1. completionCompletion(Yield(value))로 둔다.
        2. IfAbruptCloseIterator(completion, iterated).
      6. countercounter + 1로 설정한다.
  7. resultCreateIteratorFromClosure(closure, "Iterator Helper", %IteratorHelperPrototype%, « [[UnderlyingIterators]] »)로 둔다.
  8. result.[[UnderlyingIterators]]를 « iterated »로 설정한다.
  9. result를 반환한다.

27.1.3.3.5 Iterator.prototype.find ( predicate )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. objthis value로 둔다.
  2. obj가 Object가 아니면, TypeError 예외를 던진다.
  3. iteratedIterator Record { [[Iterator]]: obj, [[NextMethod]]: undefined, [[Done]]: false }로 둔다.
  4. IsCallable(predicate)가 false이면,
    1. errorThrowCompletion(새로 생성된 TypeError 객체)로 둔다.
    2. IteratorClose(iterated, error)를 반환한다.
  5. iterated를 ? GetIteratorDirect(obj)로 설정한다.
  6. counter를 0으로 둔다.
  7. 반복한다,
    1. value를 ? IteratorStepValue(iterated)로 둔다.
    2. valuedone이면, undefined를 반환한다.
    3. resultCompletion(Call(predicate, undefined, « value, 𝔽(counter) »))로 둔다.
    4. IfAbruptCloseIterator(result, iterated).
    5. ToBoolean(result)가 true이면, ? IteratorClose(iterated, NormalCompletion(value))를 반환한다.
    6. countercounter + 1로 설정한다.

27.1.3.3.6 Iterator.prototype.flatMap ( mapper )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. objthis value로 둔다.
  2. obj가 Object가 아니면, TypeError 예외를 던진다.
  3. iteratedIterator Record { [[Iterator]]: obj, [[NextMethod]]: undefined, [[Done]]: false }로 둔다.
  4. IsCallable(mapper)가 false이면,
    1. errorThrowCompletion(새로 생성된 TypeError 객체)로 둔다.
    2. IteratorClose(iterated, error)를 반환한다.
  5. iterated를 ? GetIteratorDirect(obj)로 설정한다.
  6. iteratedmapper를 캡처하고 호출될 때 다음 단계를 수행하는, 매개변수가 없는 새로운 Abstract Closureclosure를 둔다:
    1. counter를 0으로 둔다.
    2. 반복한다,
      1. value를 ? IteratorStepValue(iterated)로 둔다.
      2. valuedone이면, ReturnCompletion(undefined)를 반환한다.
      3. mappedCompletion(Call(mapper, undefined, « value, 𝔽(counter) »))로 둔다.
      4. IfAbruptCloseIterator(mapped, iterated).
      5. innerIteratorCompletion(GetIteratorFlattenable(mapped, reject-primitives))로 둔다.
      6. IfAbruptCloseIterator(innerIterator, iterated).
      7. innerAlivetrue로 둔다.
      8. innerAlivetrue인 동안 반복한다,
        1. innerValueCompletion(IteratorStepValue(innerIterator))로 둔다.
        2. IfAbruptCloseIterator(innerValue, iterated).
        3. innerValuedone이면,
          1. innerAlivefalse로 설정한다.
        4. 그렇지 않으면,
          1. completionCompletion(Yield(innerValue))로 둔다.
          2. completionabrupt completion이면,
            1. backupCompletionCompletion(IteratorClose(innerIterator, completion))로 둔다.
            2. IfAbruptCloseIterator(backupCompletion, iterated).
            3. IteratorClose(iterated, completion)를 반환한다.
      9. countercounter + 1로 설정한다.
  7. resultCreateIteratorFromClosure(closure, "Iterator Helper", %IteratorHelperPrototype%, « [[UnderlyingIterators]] »)로 둔다.
  8. result.[[UnderlyingIterators]]를 « iterated »로 설정한다.
  9. result를 반환한다.

27.1.3.3.7 Iterator.prototype.forEach ( procedure )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. objthis value로 둔다.
  2. obj가 Object가 아니면, TypeError 예외를 던진다.
  3. iteratedIterator Record { [[Iterator]]: obj, [[NextMethod]]: undefined, [[Done]]: false }로 둔다.
  4. IsCallable(procedure)가 false이면,
    1. errorThrowCompletion(새로 생성된 TypeError 객체)로 둔다.
    2. IteratorClose(iterated, error)를 반환한다.
  5. iterated를 ? GetIteratorDirect(obj)로 설정한다.
  6. counter를 0으로 둔다.
  7. 반복한다,
    1. value를 ? IteratorStepValue(iterated)로 둔다.
    2. valuedone이면, undefined를 반환한다.
    3. resultCompletion(Call(procedure, undefined, « value, 𝔽(counter) »))로 둔다.
    4. IfAbruptCloseIterator(result, iterated).
    5. countercounter + 1로 설정한다.

27.1.3.3.8 Iterator.prototype.map ( mapper )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. objthis value로 둔다.
  2. obj가 Object가 아니면, TypeError 예외를 던진다.
  3. iteratedIterator Record { [[Iterator]]: obj, [[NextMethod]]: undefined, [[Done]]: false }로 둔다.
  4. IsCallable(mapper)가 false이면,
    1. errorThrowCompletion(새로 생성된 TypeError 객체)로 둔다.
    2. IteratorClose(iterated, error)를 반환한다.
  5. iterated를 ? GetIteratorDirect(obj)로 설정한다.
  6. iteratedmapper를 캡처하고 호출될 때 다음 단계를 수행하는, 매개변수가 없는 새로운 Abstract Closureclosure를 둔다:
    1. counter를 0으로 둔다.
    2. 반복한다,
      1. value를 ? IteratorStepValue(iterated)로 둔다.
      2. valuedone이면, ReturnCompletion(undefined)를 반환한다.
      3. mappedCompletion(Call(mapper, undefined, « value, 𝔽(counter) »))로 둔다.
      4. IfAbruptCloseIterator(mapped, iterated).
      5. completionCompletion(Yield(mapped))로 둔다.
      6. IfAbruptCloseIterator(completion, iterated).
      7. countercounter + 1로 설정한다.
  7. resultCreateIteratorFromClosure(closure, "Iterator Helper", %IteratorHelperPrototype%, « [[UnderlyingIterators]] »)로 둔다.
  8. result.[[UnderlyingIterators]]를 « iterated »로 설정한다.
  9. result를 반환한다.

27.1.3.3.9 Iterator.prototype.reduce ( reducer [ , initialValue ] )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. objthis value로 둔다.
  2. obj가 Object가 아니면, TypeError 예외를 던진다.
  3. iteratedIterator Record { [[Iterator]]: obj, [[NextMethod]]: undefined, [[Done]]: false }로 둔다.
  4. IsCallable(reducer)가 false이면,
    1. errorThrowCompletion(새로 생성된 TypeError 객체)로 둔다.
    2. IteratorClose(iterated, error)를 반환한다.
  5. iterated를 ? GetIteratorDirect(obj)로 설정한다.
  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.3.3.10 Iterator.prototype.some ( predicate )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. objthis value로 둔다.
  2. obj가 Object가 아니면, TypeError 예외를 던진다.
  3. iteratedIterator Record { [[Iterator]]: obj, [[NextMethod]]: undefined, [[Done]]: false }로 둔다.
  4. IsCallable(predicate)가 false이면,
    1. errorThrowCompletion(새로 생성된 TypeError 객체)로 둔다.
    2. IteratorClose(iterated, error)를 반환한다.
  5. iterated를 ? GetIteratorDirect(obj)로 설정한다.
  6. counter를 0으로 둔다.
  7. 반복한다,
    1. value를 ? IteratorStepValue(iterated)로 둔다.
    2. valuedone이면, false를 반환한다.
    3. resultCompletion(Call(predicate, undefined, « value, 𝔽(counter) »))로 둔다.
    4. IfAbruptCloseIterator(result, iterated).
    5. ToBoolean(result)가 true이면, ? IteratorClose(iterated, NormalCompletion(true))를 반환한다.
    6. countercounter + 1로 설정한다.

27.1.3.3.11 Iterator.prototype.take ( limit )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. objthis value로 둔다.
  2. obj가 Object가 아니면, TypeError 예외를 던진다.
  3. iteratedIterator Record { [[Iterator]]: obj, [[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(obj)로 설정한다.
  10. iteratedintegerLimit를 캡처하고 호출될 때 다음 단계를 수행하는, 매개변수가 없는 새로운 Abstract Closureclosure를 둔다:
    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%, « [[UnderlyingIterators]] »)로 둔다.
  12. result.[[UnderlyingIterators]]를 « iterated »로 설정한다.
  13. result를 반환한다.

27.1.3.3.12 Iterator.prototype.toArray ( )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. objthis value로 둔다.
  2. obj가 Object가 아니면, TypeError 예외를 던진다.
  3. iterated를 ? GetIteratorDirect(obj)로 둔다.
  4. items를 새로운 빈 List로 둔다.
  5. 반복한다,
    1. value를 ? IteratorStepValue(iterated)로 둔다.
    2. valuedone이면, CreateArrayFromList(items)를 반환한다.
    3. valueitems에 추가한다.

27.1.3.3.13 Iterator.prototype [ %Symbol.iterator% ] ( )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. this value를 반환한다.

이 함수의 "name" 프로퍼티의 값은 "[Symbol.iterator]"이다.

27.1.3.3.14 Iterator.prototype [ %Symbol.toStringTag% ]

Iterator.prototype[%Symbol.toStringTag%]는 속성 { [[Enumerable]]: false, [[Configurable]]: true }를 가진 accessor property이다. [[Get]][[Set]] 속성은 다음과 같이 정의된다:

27.1.3.3.14.1 get Iterator.prototype [ %Symbol.toStringTag% ]

[[Get]] 속성의 값은 인자를 필요로 하지 않는 built-in function이다. 호출될 때 다음 단계를 수행한다:

  1. "Iterator"를 반환한다.

27.1.3.3.14.2 set Iterator.prototype [ %Symbol.toStringTag% ]

[[Set]] 속성의 값은 인자 v를 받는 built-in function이다. 호출될 때 다음 단계를 수행한다:

  1. SetterThatIgnoresPrototypeProperties(this value, %Iterator.prototype%, %Symbol.toStringTag%, v)를 수행한다.
  2. undefined를 반환한다.
Note

대부분의 built-in prototype의 %Symbol.toStringTag% 프로퍼티와 달리, 웹 호환성상의 이유로 이 프로퍼티는 accessor여야 한다.

27.1.4 %AsyncIteratorPrototype% 객체

%AsyncIteratorPrototype% 객체:

Note

이 명세에서 async iterator 인터페이스를 구현하도록 정의된 모든 객체도 %AsyncIteratorPrototype%에서 상속한다. ECMAScript 코드도 %AsyncIteratorPrototype%에서 상속하는 객체를 정의할 수 있다. %AsyncIteratorPrototype% 객체는 모든 async iterator 객체에 적용 가능한 추가 메서드가 추가될 수 있는 위치를 제공한다.

27.1.4.1 %AsyncIteratorPrototype% [ %Symbol.asyncIterator% ] ( )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. this value를 반환한다.

이 함수의 "name" 프로퍼티의 값은 "[Symbol.asyncIterator]"이다.

27.1.5 Async-from-Sync Iterator 객체

Async-from-Sync Iterator 객체는 특정 동기 iterator를 적응시키는 async iterator이다. Async-from-Sync Iterator 객체는 ECMAScript 코드에서 직접 접근할 수 없다. Async-from-Sync Iterator 객체에는 이름이 있는 생성자가 없다. 대신, Async-from-Sync Iterator 객체는 필요에 따라 CreateAsyncFromSyncIterator abstract operation에 의해 생성된다.

27.1.5.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.5.2 %AsyncFromSyncIteratorPrototype% 객체

%AsyncFromSyncIteratorPrototype% 객체:

27.1.5.2.1 %AsyncFromSyncIteratorPrototype%.next ( [ value ] )

  1. objthis value로 둔다.
  2. Assert: obj[[SyncIteratorRecord]] 내부 슬롯을 가진 Object이다.
  3. promiseCapability를 ! NewPromiseCapability(%Promise%)로 둔다.
  4. syncIteratorRecordobj.[[SyncIteratorRecord]]로 둔다.
  5. value가 존재하면,
    1. resultCompletion(IteratorNext(syncIteratorRecord, value))로 둔다.
  6. 그렇지 않으면,
    1. resultCompletion(IteratorNext(syncIteratorRecord))로 둔다.
  7. IfAbruptRejectPromise(result, promiseCapability).
  8. AsyncFromSyncIteratorContinuation(result, promiseCapability, syncIteratorRecord, true)를 반환한다.

27.1.5.2.2 %AsyncFromSyncIteratorPrototype%.return ( [ value ] )

  1. objthis value로 둔다.
  2. Assert: obj[[SyncIteratorRecord]] 내부 슬롯을 가진 Object이다.
  3. promiseCapability를 ! NewPromiseCapability(%Promise%)로 둔다.
  4. syncIteratorRecordobj.[[SyncIteratorRecord]]로 둔다.
  5. syncIteratorsyncIteratorRecord.[[Iterator]]로 둔다.
  6. returnCompletion(GetMethod(syncIterator, "return"))로 둔다.
  7. IfAbruptRejectPromise(return, promiseCapability).
  8. returnundefined이면,
    1. iteratorResultCreateIteratorResultObject(value, true)로 둔다.
    2. Call(promiseCapability.[[Resolve]], undefined, « iteratorResult »)를 수행한다.
    3. promiseCapability.[[Promise]]를 반환한다.
  9. value가 존재하면,
    1. resultCompletion(Call(return, syncIterator, « value »))로 둔다.
  10. 그렇지 않으면,
    1. resultCompletion(Call(return, syncIterator))로 둔다.
  11. IfAbruptRejectPromise(result, promiseCapability).
  12. result가 Object가 아니면,
    1. Call(promiseCapability.[[Reject]], undefined, « 새로 생성된 TypeError 객체 »)를 수행한다.
    2. promiseCapability.[[Promise]]를 반환한다.
  13. AsyncFromSyncIteratorContinuation(result, promiseCapability, syncIteratorRecord, false)를 반환한다.

27.1.5.2.3 %AsyncFromSyncIteratorPrototype%.throw ( [ value ] )

Note
이 명세에서 value는 항상 제공되지만, %AsyncFromSyncIteratorPrototype%.return ( [ value ] )와의 일관성을 위해 선택 사항으로 남겨져 있다.
  1. objthis value로 둔다.
  2. Assert: obj[[SyncIteratorRecord]] 내부 슬롯을 가진 Object이다.
  3. promiseCapability를 ! NewPromiseCapability(%Promise%)로 둔다.
  4. syncIteratorRecordobj.[[SyncIteratorRecord]]로 둔다.
  5. syncIteratorsyncIteratorRecord.[[Iterator]]로 둔다.
  6. throwCompletion(GetMethod(syncIterator, "throw"))로 둔다.
  7. IfAbruptRejectPromise(throw, promiseCapability).
  8. throwundefined이면,
    1. NOTE: syncIteratorthrow 메서드가 없으면, capability를 거부하기 전에 정리할 기회를 주기 위해 이를 닫는다.
    2. closeCompletionNormalCompletion(empty)으로 둔다.
    3. resultCompletion(IteratorClose(syncIteratorRecord, closeCompletion))로 둔다.
    4. IfAbruptRejectPromise(result, promiseCapability).
    5. NOTE: 다음 단계는 프로토콜 위반이 있었음을 나타내기 위해 TypeError를 던진다: syncIteratorthrow 메서드가 없다.
    6. NOTE: 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.5.3 Async-from-Sync Iterator 인스턴스의 프로퍼티

Async-from-Sync Iterator 인스턴스는 %AsyncFromSyncIteratorPrototype% intrinsic object에서 프로퍼티를 상속하는 ordinary object이다. Async-from-Sync Iterator 인스턴스는 처음에 Table 85에 나열된 내부 슬롯을 가지고 생성된다.

Table 85: Async-from-Sync Iterator 인스턴스의 내부 슬롯
내부 슬롯 타입 설명
[[SyncIteratorRecord]] Iterator Record 적응 중인 원래 동기 iterator를 나타낸다.

27.1.5.4 AsyncFromSyncIteratorContinuation ( result, promiseCapability, syncIteratorRecord, closeOnRejection )

The abstract operation AsyncFromSyncIteratorContinuation takes arguments result (an Object), promiseCapability (a PromiseCapability Record for an intrinsic %Promise%), syncIteratorRecord (an Iterator Record), and closeOnRejection (a Boolean) and returns a Promise. It performs the following steps when called:

  1. NOTE: promiseCapability은 intrinsic %Promise%에서 파생되므로, 아래 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. done을 캡처하고 호출될 때 다음 단계를 수행하는, 매개변수 (v)를 가진 새로운 Abstract Closureunwrap을 둔다:
    1. CreateIteratorResultObject(v, done)를 반환한다.
  10. onFulfilledCreateBuiltinFunction(unwrap, 1, "", « »)로 둔다.
  11. NOTE: onFulfilled는 IteratorResult 객체의 "value" 프로퍼티를 처리할 때, 그 값이 promise인 경우 이를 기다리고 그 결과를 새로운 "unwrapped" IteratorResult 객체에 다시 포장하기 위해 사용된다.
  12. donetrue이거나 closeOnRejectionfalse이면,
    1. onRejectedundefined로 둔다.
  13. 그렇지 않으면,
    1. syncIteratorRecord를 캡처하고 호출될 때 다음 단계를 수행하는, 매개변수 (error)를 가진 새로운 Abstract ClosurecloseIterator를 둔다:
      1. IteratorClose(syncIteratorRecord, ThrowCompletion(error))를 반환한다.
    2. onRejectedCreateBuiltinFunction(closeIterator, 1, "", « »)로 둔다.
    3. NOTE: onRejected는 IteratorResult 객체가 산출한 "value" 프로퍼티가 거부된 promise일 때 Iterator를 닫는 데 사용된다.
  14. PerformPromiseThen(valueWrapper, onFulfilled, onRejected, promiseCapability)를 수행한다.
  15. promiseCapability.[[Promise]]를 반환한다.

27.2 Promise 객체

Promise는 지연된(그리고 가능하게는 비동기적인) 계산의 최종 결과를 위한 자리표시자로 사용되는 객체이다.

모든 Promise는 서로 배타적인 세 상태 중 하나에 있다: fulfilled, rejected, 그리고 pending:

  • promise pp.then(f, r)이 함수 f를 호출하는 Job을 즉시 큐에 넣는다면 fulfilled이다.
  • promise pp.then(f, r)이 함수 r을 호출하는 Job을 즉시 큐에 넣는다면 rejected이다.
  • promise는 fulfilled도 rejected도 아니라면 pending이다.

promise는 pending이 아니면, 즉 fulfilled이거나 rejected이면 settled되었다고 한다.

promise는 settled되었거나 다른 promise의 상태와 일치하도록 “고정”되었다면 resolved되었다. resolved promise를 resolve하거나 reject하려는 시도는 아무 효과가 없다. promise는 resolved가 아니면 unresolved이다. unresolved promise는 항상 pending 상태에 있다. resolved promise는 pending, fulfilled 또는 rejected일 수 있다.

27.2.1 Promise 추상 연산

27.2.1.1 PromiseCapability 레코드

PromiseCapability 레코드는 Promise 또는 promise-like 객체를 그 promise를 resolve하거나 reject할 수 있는 함수들과 함께 캡슐화하는 데 사용되는 Record 값이다. PromiseCapability 레코드는 NewPromiseCapability 추상 연산에 의해 생성된다.

PromiseCapability 레코드는 Table 86에 나열된 필드를 가진다.

Table 86: PromiseCapability 레코드 필드
필드 이름 의미
[[Promise]] Object promise로 사용할 수 있는 객체.
[[Resolve]] 함수 객체 주어진 promise를 resolve하는 데 사용되는 함수.
[[Reject]] 함수 객체 주어진 promise를 reject하는 데 사용되는 함수.

27.2.1.1.1 IfAbruptRejectPromise ( value, capability )

IfAbruptRejectPromise는 PromiseCapability 레코드를 사용하는 일련의 알고리즘 단계에 대한 축약 표기이다. 다음 형식의 알고리즘 단계:

  1. IfAbruptRejectPromise(value, capability).

는 다음과 같은 의미이다:

  1. Assert: valueCompletion Record이다.
  2. valueabrupt completion이면,
    1. Call(capability.[[Reject]], undefined, « value.[[Value]] »)를 수행한다.
    2. capability.[[Promise]]를 반환한다.
  3. value를 ! value로 설정한다.

27.2.1.2 PromiseReaction 레코드

PromiseReaction 레코드는 promise가 주어진 값으로 resolved 또는 rejected될 때 어떻게 반응해야 하는지에 대한 정보를 저장하는 데 사용되는 Record 값이다. PromiseReaction 레코드는 PerformPromiseThen 추상 연산에 의해 생성되며, NewPromiseReactionJob이 반환하는 Abstract Closure에 의해 사용된다.

PromiseReaction 레코드는 Table 87에 나열된 필드를 가진다.

Table 87: PromiseReaction 레코드 필드
필드 이름 의미
[[Capability]] PromiseCapability 레코드 또는 undefined 이 레코드가 reaction handler를 제공하는 promise의 capability.
[[Type]] fulfill 또는 reject [[Type]][[Handler]]empty일 때 settlement 타입에 특정한 동작을 허용하기 위해 사용된다.
[[Handler]] JobCallback 레코드 또는 empty 들어오는 값에 적용되어야 하는 함수이며, 그 반환 값은 파생 promise에 일어날 일을 결정한다. [[Handler]]empty이면, 대신 [[Type]]의 값에 의존하는 함수가 사용된다.

27.2.1.3 CreateResolvingFunctions ( toResolve )

The abstract operation CreateResolvingFunctions takes argument toResolve (a Promise) and returns a Record with fields [[Resolve]] (a function object) and [[Reject]] (a function object). It performs the following steps when called:

  1. promiseOrEmptyRecord { [[Value]]: toResolve }로 둔다.
  2. resolveStepspromiseOrEmpty를 캡처하고 호출될 때 다음 단계를 수행하는, 매개변수 (resolution)를 가진 새로운 Abstract Closure로 둔다:
    1. promiseOrEmpty.[[Value]]empty이면, undefined를 반환한다.
    2. promisepromiseOrEmpty.[[Value]]로 둔다.
    3. promiseOrEmpty.[[Value]]empty로 설정한다.
    4. SameValue(resolution, promise)가 true이면,
      1. selfResolutionError를 새로 생성된 TypeError 객체로 둔다.
      2. RejectPromise(promise, selfResolutionError)를 수행한다.
      3. undefined를 반환한다.
    5. resolution이 Object가 아니면,
      1. FulfillPromise(promise, resolution)를 수행한다.
      2. undefined를 반환한다.
    6. thenCompletion(Get(resolution, "then"))으로 둔다.
    7. thenabrupt completion이면,
      1. RejectPromise(promise, then.[[Value]])를 수행한다.
      2. undefined를 반환한다.
    8. thenActionthen.[[Value]]로 둔다.
    9. IsCallable(thenAction)가 false이면,
      1. FulfillPromise(promise, resolution)를 수행한다.
      2. undefined를 반환한다.
    10. thenJobCallbackHostMakeJobCallback(thenAction)으로 둔다.
    11. jobNewPromiseResolveThenableJob(promise, resolution, thenJobCallback)으로 둔다.
    12. HostEnqueuePromiseJob(job.[[Job]], job.[[Realm]])을 수행한다.
    13. undefined를 반환한다.
  3. resolveCreateBuiltinFunction(resolveSteps, 1, "", « »)로 둔다.
  4. rejectStepspromiseOrEmpty를 캡처하고 호출될 때 다음 단계를 수행하는, 매개변수 (reason)를 가진 새로운 Abstract Closure로 둔다:
    1. promiseOrEmpty.[[Value]]empty이면, undefined를 반환한다.
    2. promisepromiseOrEmpty.[[Value]]로 둔다.
    3. promiseOrEmpty.[[Value]]empty로 설정한다.
    4. RejectPromise(promise, reason)를 수행한다.
    5. undefined를 반환한다.
  5. rejectCreateBuiltinFunction(rejectSteps, 1, "", « »)로 둔다.
  6. Record { [[Resolve]]: resolve, [[Reject]]: reject }를 반환한다.

27.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 ( constructor )

The abstract operation NewPromiseCapability takes argument constructor (an ECMAScript language value) and returns either a normal completion containing a PromiseCapability Record or a throw completion. 이는 built-in Promise 생성자의 방식대로 constructor를 생성자로 사용하여 promise를 만들고 그 resolvereject 함수를 추출하려 시도한다. promise와 resolvereject 함수는 새로운 PromiseCapability 레코드를 초기화하는 데 사용된다. It performs the following steps when called:

  1. IsConstructor(constructor)가 false이면, TypeError 예외를 던진다.
  2. NOTE: constructor는 Promise 생성자의 매개변수 관례를 지원하는 생성자 함수라고 가정된다(27.2.3.1 참조).
  3. resolvingFunctionsRecord { [[Resolve]]: undefined, [[Reject]]: undefined }로 둔다.
  4. executorClosureresolvingFunctions를 캡처하고 호출될 때 다음 단계를 수행하는, 매개변수 (resolve, reject)를 가진 새로운 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(constructor, « 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 ( value )

The abstract operation IsPromise takes argument value (an ECMAScript language value) and returns a Boolean. 객체에서 promise brand를 확인한다. It performs the following steps when called:

  1. value가 Object가 아니면, false를 반환한다.
  2. value[[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이다.
  2. reactionspromise.[[PromiseRejectReactions]]로 둔다.
  3. promise.[[PromiseResult]]reason으로 설정한다.
  4. promise.[[PromiseFulfillReactions]]undefined로 설정한다.
  5. promise.[[PromiseRejectReactions]]undefined로 설정한다.
  6. promise.[[PromiseState]]rejected로 설정한다.
  7. promise.[[PromiseIsHandled]]false이면, HostPromiseRejectionTracker(promise, "reject")를 수행한다.
  8. TriggerPromiseReactions(reactions, reason)를 수행한다.
  9. unused를 반환한다.

27.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 레코드[[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가 handler 없이 rejected될 때, operation 인자가 "reject"로 설정되어 호출된다.
  • rejected promise에 처음으로 handler가 추가될 때, operation 인자가 "handle"로 설정되어 호출된다.

HostPromiseRejectionTracker의 전형적인 구현은 처리되지 않은 rejection을 개발자에게 알리려 할 수 있으며, 동시에 그런 이전 알림이 나중에 새로운 handler의 연결로 무효화되는 경우에도 알리도록 주의할 수 있다.

Note 2

operation"handle"이면, 구현은 garbage collection을 방해하는 방식으로 promise에 대한 참조를 유지해서는 안 된다. operation"reject"이면, rejection은 드물고 hot code path에 있지 않을 것으로 예상되므로 구현은 promise에 대한 참조를 유지할 수 있다.

27.2.2 Promise Job

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). 들어오는 값에 적절한 handler를 적용하고, handler의 반환 값을 사용하여 해당 handler와 관련된 파생 promise를 resolve하거나 reject하는 새로운 Job Abstract Closure를 반환한다. It performs the following steps when called:

  1. jobreactionargument를 캡처하고 호출될 때 다음 단계를 수행하는, 매개변수가 없는 새로운 Job Abstract Closure로 둔다:
    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 레코드이다.
    8. handlerResultabrupt completion이면,
      1. Call(promiseCapability.[[Reject]], undefined, « handlerResult.[[Value]] »)를 반환한다.
    9. Call(promiseCapability.[[Resolve]], undefined, « handlerResult.[[Value]] »)를 반환한다.
  2. handlerRealmnull로 둔다.
  3. reaction.[[Handler]]empty가 아니면,
    1. getHandlerRealmResultCompletion(GetFunctionRealm(reaction.[[Handler]].[[Callback]]))으로 둔다.
    2. getHandlerRealmResultnormal completion이면, handlerRealmgetHandlerRealmResult.[[Value]]로 설정한다.
    3. 그렇지 않으면, handlerRealm을 현재 Realm Record로 설정한다.
    4. NOTE: handler가 undefined가 아닌 한 handlerRealm은 결코 null이 아니다. handler가 revoked 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. jobpromiseToResolve, thenable, 그리고 then을 캡처하고 호출될 때 다음 단계를 수행하는, 매개변수가 없는 새로운 Job Abstract Closure로 둔다:
    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. NOTE: thenRealm은 결코 null이 아니다. then.[[Callback]]이 revoked Proxy이고 어떤 코드도 실행되지 않을 때, thenRealm은 오류 객체를 생성하는 데 사용된다.
  6. Record { [[Job]]: job, [[Realm]]: thenRealm }를 반환한다.
Note

Job은 제공된 thenable과 그 then 메서드를 사용하여 주어진 promise를 resolve한다. 이 과정은 주변 코드의 평가가 완료된 후 then 메서드의 평가가 일어나도록 보장하기 위해 Job으로 수행되어야 한다.

27.2.3 Promise 생성자

Promise 생성자:

  • %Promise%이다.
  • 전역 객체"Promise" 프로퍼티의 초기 값이다.
  • 생성자로 호출될 때 새로운 Promise를 생성하고 초기화한다.
  • 함수로 호출되도록 의도되지 않았으며, 그런 방식으로 호출되면 예외를 던진다.
  • 클래스 정의의 extends 절에서 값으로 사용될 수 있다. 지정된 Promise 동작을 상속하려는 서브클래스 생성자는 PromisePromise.prototype built-in 메서드를 지원하는 데 필요한 내부 상태로 서브클래스 인스턴스를 생성하고 초기화하기 위해 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 코드는 결국 관련 Promise를 resolve하고자 함을 나타내기 위해 resolve 함수를 호출할 수 있다. resolve 함수에 전달된 인자는 지연된 동작의 최종 값을 나타내며, 실제 fulfillment 값이거나 fulfilled되면 그 값을 제공할 다른 promise일 수 있다.

executor 함수에 전달되는 reject 함수는 단일 인자를 받는다. executor 코드는 결국 관련 Promise가 rejected되며 결코 fulfilled되지 않을 것임을 나타내기 위해 reject 함수를 호출할 수 있다. reject 함수에 전달된 인자는 promise의 rejection 값으로 사용된다. 일반적으로 Error 객체가 된다.

Promise 생성자가 executor 함수에 전달하는 resolve 및 reject 함수는 실제로 관련 promise를 resolve하고 reject할 수 있는 capability를 가진다. 서브클래스는 resolve 및 reject에 대해 사용자 정의 값을 전달하는 다른 생성자 동작을 가질 수 있다.

27.2.4 Promise 생성자의 프로퍼티

Promise 생성자:

  • 값이 %Function.prototype%[[Prototype]] 내부 슬롯을 가진다.
  • 다음 프로퍼티를 가진다:

27.2.4.1 Promise.all ( iterable )

이 함수는 전달된 promise들의 fulfillment 값 배열로 fulfilled되는 새 promise를 반환하거나, rejected되는 첫 번째 전달 promise의 reason으로 rejected된다. 이 알고리즘을 실행하면서 전달된 iterable의 모든 요소를 promise로 resolve한다.

  1. constructorthis value로 둔다.
  2. promiseCapability를 ? NewPromiseCapability(constructor)로 둔다.
  3. promiseResolveCompletion(GetPromiseResolve(constructor))로 둔다.
  4. IfAbruptRejectPromise(promiseResolve, promiseCapability).
  5. iteratorRecordCompletion(GetIterator(iterable, sync))으로 둔다.
  6. IfAbruptRejectPromise(iteratorRecord, promiseCapability).
  7. resultCompletion(PerformPromiseAll(iteratorRecord, constructor, promiseCapability, promiseResolve))으로 둔다.
  8. resultabrupt completion이면,
    1. iteratorRecord.[[Done]]false이면, resultCompletion(IteratorClose(iteratorRecord, result))로 설정한다.
    2. IfAbruptRejectPromise(result, promiseCapability).
  9. result를 반환한다.
Note

이 함수는 자신의 this value가 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 Object or a throw completion. It performs the following steps when called:

  1. values를 새로운 빈 List로 둔다.
  2. NOTE: remainingElementsCount는 잘못 동작하는 "then"이 입력 iterator가 소진되기 전에 전달된 callback을 호출하는 경우에도 resultCapability.[[Resolve]]가 한 번만 호출되도록 보장하기 위해 0 대신 1에서 시작한다.
  3. remainingElementsCountRecord { [[Value]]: 1 }로 둔다.
  4. index를 0으로 둔다.
  5. 반복한다,
    1. next를 ? IteratorStepValue(iteratorRecord)로 둔다.
    2. nextdone이면,
      1. remainingElementsCount.[[Value]]remainingElementsCount.[[Value]] - 1로 설정한다.
      2. remainingElementsCount.[[Value]] = 0이면,
        1. valuesArrayCreateArrayFromList(values)로 둔다.
        2. Call(resultCapability.[[Resolve]], undefined, « valuesArray »)를 수행한다.
      3. resultCapability.[[Promise]]를 반환한다.
    3. undefinedvalues에 추가한다.
    4. nextPromise를 ? Call(promiseResolve, constructor, « next »)로 둔다.
    5. fulfilledStepsvalues, resultCapability, 그리고 remainingElementsCount를 캡처하고 호출될 때 다음 단계를 수행하는, 매개변수 (value)를 가진 새로운 Abstract Closure로 둔다:
      1. activeFuncactive function object로 둔다.
      2. activeFunc.[[AlreadyCalled]]true이면, undefined를 반환한다.
      3. activeFunc.[[AlreadyCalled]]true로 설정한다.
      4. thisIndexactiveFunc.[[Index]]로 둔다.
      5. values[thisIndex]를 value로 설정한다.
      6. remainingElementsCount.[[Value]]remainingElementsCount.[[Value]] - 1로 설정한다.
      7. remainingElementsCount.[[Value]] = 0이면,
        1. valuesArrayCreateArrayFromList(values)로 둔다.
        2. Call(resultCapability.[[Resolve]], undefined, « valuesArray »)를 반환한다.
      8. undefined를 반환한다.
    6. onFulfilledCreateBuiltinFunction(fulfilledSteps, 1, "", « [[AlreadyCalled]], [[Index]] »)로 둔다.
    7. onFulfilled.[[AlreadyCalled]]false로 설정한다.
    8. onFulfilled.[[Index]]index로 설정한다.
    9. indexindex + 1로 설정한다.
    10. remainingElementsCount.[[Value]]remainingElementsCount.[[Value]] + 1로 설정한다.
    11. Invoke(nextPromise, "then", « onFulfilled, resultCapability.[[Reject]] »)를 수행한다.

27.2.4.2 Promise.allSettled ( iterable )

이 함수는 모든 원래 promise가 settled, 즉 fulfilled 또는 rejected가 된 뒤에야 promise 상태 snapshot의 배열로 fulfilled되는 promise를 반환한다. 이 알고리즘을 실행하면서 전달된 iterable의 모든 요소를 promise로 resolve한다.

  1. constructorthis value로 둔다.
  2. promiseCapability를 ? NewPromiseCapability(constructor)로 둔다.
  3. promiseResolveCompletion(GetPromiseResolve(constructor))로 둔다.
  4. IfAbruptRejectPromise(promiseResolve, promiseCapability).
  5. iteratorRecordCompletion(GetIterator(iterable, sync))으로 둔다.
  6. IfAbruptRejectPromise(iteratorRecord, promiseCapability).
  7. resultCompletion(PerformPromiseAllSettled(iteratorRecord, constructor, promiseCapability, promiseResolve))으로 둔다.
  8. resultabrupt completion이면,
    1. iteratorRecord.[[Done]]false이면, resultCompletion(IteratorClose(iteratorRecord, result))로 설정한다.
    2. IfAbruptRejectPromise(result, promiseCapability).
  9. result를 반환한다.
Note

이 함수는 자신의 this value가 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 Object or a throw completion. It performs the following steps when called:

  1. values를 새로운 빈 List로 둔다.
  2. NOTE: remainingElementsCount는 잘못 동작하는 "then"이 입력 iterator가 소진되기 전에 전달된 callback 중 하나를 호출하는 경우에도 resultCapability.[[Resolve]]가 한 번만 호출되도록 보장하기 위해 0 대신 1에서 시작한다.
  3. remainingElementsCountRecord { [[Value]]: 1 }로 둔다.
  4. index를 0으로 둔다.
  5. 반복한다,
    1. next를 ? IteratorStepValue(iteratorRecord)로 둔다.
    2. nextdone이면,
      1. remainingElementsCount.[[Value]]remainingElementsCount.[[Value]] - 1로 설정한다.
      2. remainingElementsCount.[[Value]] = 0이면,
        1. valuesArrayCreateArrayFromList(values)로 둔다.
        2. Call(resultCapability.[[Resolve]], undefined, « valuesArray »)를 수행한다.
      3. resultCapability.[[Promise]]를 반환한다.
    3. undefinedvalues에 추가한다.
    4. nextPromise를 ? Call(promiseResolve, constructor, « next »)로 둔다.
    5. alreadyCalledRecord { [[Value]]: false }로 둔다.
    6. fulfilledStepsvalues, resultCapability, 그리고 remainingElementsCount를 캡처하고 호출될 때 다음 단계를 수행하는, 매개변수 (value)를 가진 새로운 Abstract Closure로 둔다:
      1. activeFuncactive function object로 둔다.
      2. activeFunc.[[AlreadyCalled]].[[Value]]true이면, undefined를 반환한다.
      3. activeFunc.[[AlreadyCalled]].[[Value]]true로 설정한다.
      4. objOrdinaryObjectCreate(%Object.prototype%)로 둔다.
      5. CreateDataPropertyOrThrow(obj, "status", "fulfilled")를 수행한다.
      6. CreateDataPropertyOrThrow(obj, "value", value)를 수행한다.
      7. thisIndexactiveFunc.[[Index]]로 둔다.
      8. values[thisIndex]를 obj로 설정한다.
      9. remainingElementsCount.[[Value]]remainingElementsCount.[[Value]] - 1로 설정한다.
      10. remainingElementsCount.[[Value]] = 0이면,
        1. valuesArrayCreateArrayFromList(values)로 둔다.
        2. Call(resultCapability.[[Resolve]], undefined, « valuesArray »)를 반환한다.
      11. undefined를 반환한다.
    7. onFulfilledCreateBuiltinFunction(fulfilledSteps, 1, "", « [[AlreadyCalled]], [[Index]] »)로 둔다.
    8. onFulfilled.[[AlreadyCalled]]alreadyCalled로 설정한다.
    9. onFulfilled.[[Index]]index로 설정한다.
    10. rejectedStepsvalues, resultCapability, 그리고 remainingElementsCount를 캡처하고 호출될 때 다음 단계를 수행하는, 매개변수 (error)를 가진 새로운 Abstract Closure로 둔다:
      1. activeFuncactive function object로 둔다.
      2. activeFunc.[[AlreadyCalled]].[[Value]]true이면, undefined를 반환한다.
      3. activeFunc.[[AlreadyCalled]].[[Value]]true로 설정한다.
      4. objOrdinaryObjectCreate(%Object.prototype%)로 둔다.
      5. CreateDataPropertyOrThrow(obj, "status", "rejected")를 수행한다.
      6. CreateDataPropertyOrThrow(obj, "reason", error)를 수행한다.
      7. thisIndexactiveFunc.[[Index]]로 둔다.
      8. values[thisIndex]를 obj로 설정한다.
      9. remainingElementsCount.[[Value]]remainingElementsCount.[[Value]] - 1로 설정한다.
      10. remainingElementsCount.[[Value]] = 0이면,
        1. valuesArrayCreateArrayFromList(values)로 둔다.
        2. Call(resultCapability.[[Resolve]], undefined, « valuesArray »)를 반환한다.
      11. undefined를 반환한다.
    11. onRejectedCreateBuiltinFunction(rejectedSteps, 1, "", « [[AlreadyCalled]], [[Index]] »)로 둔다.
    12. onRejected.[[AlreadyCalled]]alreadyCalled로 설정한다.
    13. onRejected.[[Index]]index로 설정한다.
    14. indexindex + 1로 설정한다.
    15. remainingElementsCount.[[Value]]remainingElementsCount.[[Value]] + 1로 설정한다.
    16. Invoke(nextPromise, "then", « onFulfilled, onRejected »)를 수행한다.

27.2.4.3 Promise.any ( iterable )

이 함수는 주어진 promise 중 처음으로 fulfilled되는 promise에 의해 fulfilled되거나, 주어진 promise가 모두 rejected되면 rejection reason들을 담은 AggregateError로 rejected되는 promise를 반환한다. 이 알고리즘을 실행하면서 전달된 iterable의 모든 요소를 promise로 resolve한다.

  1. constructorthis value로 둔다.
  2. promiseCapability를 ? NewPromiseCapability(constructor)로 둔다.
  3. promiseResolveCompletion(GetPromiseResolve(constructor))로 둔다.
  4. IfAbruptRejectPromise(promiseResolve, promiseCapability).
  5. iteratorRecordCompletion(GetIterator(iterable, sync))으로 둔다.
  6. IfAbruptRejectPromise(iteratorRecord, promiseCapability).
  7. resultCompletion(PerformPromiseAny(iteratorRecord, constructor, promiseCapability, promiseResolve))으로 둔다.
  8. resultabrupt completion이면,
    1. iteratorRecord.[[Done]]false이면, resultCompletion(IteratorClose(iteratorRecord, result))로 설정한다.
    2. IfAbruptRejectPromise(result, promiseCapability).
  9. result를 반환한다.
Note

이 함수는 자신의 this value가 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 Object or a throw completion. It performs the following steps when called:

  1. errors를 새로운 빈 List로 둔다.
  2. NOTE: remainingElementsCount는 잘못 동작하는 "then"이 입력 iterator가 소진되기 전에 전달된 callback을 호출하는 경우에도 resultCapability.[[Reject]]가 한 번만 호출되도록 보장하기 위해 0 대신 1에서 시작한다.
  3. remainingElementsCountRecord { [[Value]]: 1 }로 둔다.
  4. index를 0으로 둔다.
  5. 반복한다,
    1. next를 ? IteratorStepValue(iteratorRecord)로 둔다.
    2. nextdone이면,
      1. remainingElementsCount.[[Value]]remainingElementsCount.[[Value]] - 1로 설정한다.
      2. remainingElementsCount.[[Value]] = 0이면,
        1. aggregateError를 새로 생성된 AggregateError 객체로 둔다.
        2. DefinePropertyOrThrow(aggregateError, "errors", PropertyDescriptor { [[Configurable]]: true, [[Enumerable]]: false, [[Writable]]: true, [[Value]]: CreateArrayFromList(errors) })를 수행한다.
        3. Call(resultCapability.[[Reject]], undefined, « aggregateError »)를 수행한다.
      3. resultCapability.[[Promise]]를 반환한다.
    3. undefinederrors에 추가한다.
    4. nextPromise를 ? Call(promiseResolve, constructor, « next »)로 둔다.
    5. rejectedStepserrors, resultCapability, 그리고 remainingElementsCount를 캡처하고 호출될 때 다음 단계를 수행하는, 매개변수 (error)를 가진 새로운 Abstract Closure로 둔다:
      1. activeFuncactive function object로 둔다.
      2. activeFunc.[[AlreadyCalled]]true이면, undefined를 반환한다.
      3. activeFunc.[[AlreadyCalled]]true로 설정한다.
      4. thisIndexactiveFunc.[[Index]]로 둔다.
      5. errors[thisIndex]를 error로 설정한다.
      6. remainingElementsCount.[[Value]]remainingElementsCount.[[Value]] - 1로 설정한다.
      7. remainingElementsCount.[[Value]] = 0이면,
        1. aggregateError를 새로 생성된 AggregateError 객체로 둔다.
        2. DefinePropertyOrThrow(aggregateError, "errors", PropertyDescriptor { [[Configurable]]: true, [[Enumerable]]: false, [[Writable]]: true, [[Value]]: CreateArrayFromList(errors) })를 수행한다.
        3. Call(resultCapability.[[Reject]], undefined, « aggregateError »)를 반환한다.
      8. undefined를 반환한다.
    6. onRejectedCreateBuiltinFunction(rejectedSteps, 1, "", « [[AlreadyCalled]], [[Index]] »)로 둔다.
    7. onRejected.[[AlreadyCalled]]false로 설정한다.
    8. onRejected.[[Index]]index로 설정한다.
    9. indexindex + 1로 설정한다.
    10. remainingElementsCount.[[Value]]remainingElementsCount.[[Value]] + 1로 설정한다.
    11. Invoke(nextPromise, "then", « resultCapability.[[Resolve]], onRejected »)를 수행한다.

27.2.4.4 Promise.prototype

Promise.prototype의 초기 값은 Promise prototype object이다.

이 프로퍼티는 속성 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }를 가진다.

27.2.4.5 Promise.race ( iterable )

이 함수는 settled되는 첫 번째 전달 promise와 같은 방식으로 settled되는 새 promise를 반환한다. 이 알고리즘을 실행하면서 전달된 iterable의 모든 요소를 promise로 resolve한다.

  1. constructorthis value로 둔다.
  2. promiseCapability를 ? NewPromiseCapability(constructor)로 둔다.
  3. promiseResolveCompletion(GetPromiseResolve(constructor))로 둔다.
  4. IfAbruptRejectPromise(promiseResolve, promiseCapability).
  5. iteratorRecordCompletion(GetIterator(iterable, sync))으로 둔다.
  6. IfAbruptRejectPromise(iteratorRecord, promiseCapability).
  7. resultCompletion(PerformPromiseRace(iteratorRecord, constructor, 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는 결코 settled되지 않는다.

Note 2

이 함수는 자신의 this value가 Promise 생성자의 매개변수 관례를 지원하는 생성자 함수일 것을 기대한다. 또한 자신의 this value가 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 Object or a throw completion. It performs the following steps when called:

  1. 반복한다,
    1. next를 ? IteratorStepValue(iteratorRecord)로 둔다.
    2. nextdone이면,
      1. resultCapability.[[Promise]]를 반환한다.
    3. nextPromise를 ? Call(promiseResolve, constructor, « next »)로 둔다.
    4. Invoke(nextPromise, "then", « resultCapability.[[Resolve]], resultCapability.[[Reject]] »)를 수행한다.

27.2.4.6 Promise.reject ( reason )

이 함수는 전달된 인자로 rejected된 새 promise를 반환한다.

  1. constructorthis value로 둔다.
  2. promiseCapability를 ? NewPromiseCapability(constructor)로 둔다.
  3. Call(promiseCapability.[[Reject]], undefined, « reason »)를 수행한다.
  4. promiseCapability.[[Promise]]를 반환한다.
Note

이 함수는 자신의 this value가 Promise 생성자의 매개변수 관례를 지원하는 생성자 함수일 것을 기대한다.

27.2.4.7 Promise.resolve ( resolution )

이 함수는 전달된 인자로 resolved된 새 promise를 반환하거나, 인자가 이 생성자에 의해 생성된 promise이면 인자 자체를 반환한다.

  1. constructorthis value로 둔다.
  2. constructor가 Object가 아니면, TypeError 예외를 던진다.
  3. PromiseResolve(constructor, resolution)을 반환한다.
Note

이 함수는 자신의 this value가 Promise 생성자의 매개변수 관례를 지원하는 생성자 함수일 것을 기대한다.

27.2.4.7.1 PromiseResolve ( constructor, resolution )

The abstract operation PromiseResolve takes arguments constructor (an Object) and resolution (an ECMAScript language value) and returns either a normal completion containing an Object or a throw completion. resolution으로 resolved된 새 promise를 반환한다. It performs the following steps when called:

  1. IsPromise(resolution)가 true이면,
    1. xConstructor를 ? Get(resolution, "constructor")로 둔다.
    2. SameValue(xConstructor, constructor)가 true이면, resolution을 반환한다.
  2. promiseCapability를 ? NewPromiseCapability(constructor)로 둔다.
  3. Call(promiseCapability.[[Resolve]], undefined, « resolution »)를 수행한다.
  4. promiseCapability.[[Promise]]를 반환한다.

27.2.4.8 Promise.try ( callback, ...args )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. constructorthis value로 둔다.
  2. constructor가 Object가 아니면, TypeError 예외를 던진다.
  3. promiseCapability를 ? NewPromiseCapability(constructor)로 둔다.
  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 value가 Promise 생성자의 매개변수 관례를 지원하는 생성자 함수일 것을 기대한다.

27.2.4.9 Promise.withResolvers ( )

이 함수는 새 promise와 그와 관련된 resolvereject 함수를 함께 포함하는 세 프로퍼티를 가진 객체를 반환한다.

  1. constructorthis value로 둔다.
  2. promiseCapability를 ? NewPromiseCapability(constructor)로 둔다.
  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 accessor function이 undefinedaccessor property이다. 그 get accessor function은 호출될 때 다음 단계를 수행한다:

  1. this value를 반환한다.

이 함수의 "name" 프로퍼티의 값은 "get [Symbol.species]"이다.

Note

Promise prototype 메서드는 일반적으로 파생 객체를 생성하기 위해 자신의 this value의 생성자를 사용한다. 그러나 서브클래스 생성자는 자신의 %Symbol.species% 프로퍼티를 재정의하여 그 기본 동작을 over-ride할 수 있다.

27.2.5 Promise Prototype Object의 프로퍼티

Promise prototype object:

  • %Promise.prototype%이다.
  • 값이 %Object.prototype%[[Prototype]] 내부 슬롯을 가진다.
  • ordinary object이다.
  • [[PromiseState]] 내부 슬롯이나 Promise 인스턴스의 다른 내부 슬롯을 가지지 않는다.

27.2.5.1 Promise.prototype.catch ( onRejected )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. promisethis value로 둔다.
  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 value로 둔다.
  2. promise가 Object가 아니면, TypeError 예외를 던진다.
  3. constructor를 ? SpeciesConstructor(promise, %Promise%)로 둔다.
  4. Assert: IsConstructor(constructor)는 true이다.
  5. IsCallable(onFinally)가 false이면,
    1. thenFinallyonFinally로 둔다.
    2. catchFinallyonFinally로 둔다.
  6. 그렇지 않으면,
    1. thenFinallyClosureonFinallyconstructor를 캡처하고 호출될 때 다음 단계를 수행하는, 매개변수 (value)를 가진 새로운 Abstract Closure로 둔다:
      1. result를 ? Call(onFinally, undefined)로 둔다.
      2. p를 ? PromiseResolve(constructor, result)로 둔다.
      3. returnValuevalue를 캡처하고 호출될 때 다음 단계를 수행하는, 매개변수가 없는 새로운 Abstract Closure로 둔다:
        1. NormalCompletion(value)를 반환한다.
      4. valueThunkCreateBuiltinFunction(returnValue, 0, "", « »)로 둔다.
      5. Invoke(p, "then", « valueThunk »)를 반환한다.
    2. thenFinallyCreateBuiltinFunction(thenFinallyClosure, 1, "", « »)로 둔다.
    3. catchFinallyClosureonFinallyconstructor를 캡처하고 호출될 때 다음 단계를 수행하는, 매개변수 (reason)를 가진 새로운 Abstract Closure로 둔다:
      1. result를 ? Call(onFinally, undefined)로 둔다.
      2. p를 ? PromiseResolve(constructor, result)로 둔다.
      3. throwReasonreason을 캡처하고 호출될 때 다음 단계를 수행하는, 매개변수가 없는 새로운 Abstract Closure로 둔다:
        1. 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 value로 둔다.
  2. IsPromise(promise)가 false이면, TypeError 예외를 던진다.
  3. constructor를 ? SpeciesConstructor(promise, %Promise%)로 둔다.
  4. resultCapability를 ? NewPromiseCapability(constructor)로 둔다.
  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 Object or undefined. promise에 대해 onFulfilledonRejected를 settlement action으로 사용하여 “then” 연산을 수행한다. resultCapability가 전달되면, 결과는 resultCapability의 promise를 갱신하여 저장된다. 전달되지 않으면, PerformPromiseThen은 결과가 중요하지 않은 명세 내부 연산에 의해 호출되는 것이다. 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. fulfillReaction을 PromiseReaction Record { [[Capability]]: resultCapability, [[Type]]: fulfill, [[Handler]]: onFulfilledJobCallback }로 둔다.
  8. rejectReaction을 PromiseReaction 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이면, undefined를 반환한다.
  14. resultCapability.[[Promise]]를 반환한다.

27.2.5.5 Promise.prototype [ %Symbol.toStringTag% ]

%Symbol.toStringTag% 프로퍼티의 초기 값은 String 값 "Promise"이다.

이 프로퍼티는 속성 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }를 가진다.

27.2.6 Promise 인스턴스의 프로퍼티

Promise 인스턴스는 Promise prototype object(intrinsic, %Promise.prototype%)에서 프로퍼티를 상속하는 ordinary object이다. Promise 인스턴스는 처음에 Table 88에 설명된 내부 슬롯을 가지고 생성된다.

Table 88: Promise 인스턴스의 내부 슬롯
내부 슬롯 타입 설명
[[PromiseState]] pending, fulfilled, 또는 rejected promise가 자신의 then 메서드에 들어오는 호출에 어떻게 반응할지를 지배한다.
[[PromiseResult]] ECMAScript 언어 값 또는 empty promise가 fulfilled 또는 rejected된 값(있는 경우). [[PromiseState]]pending인 경우에 그리고 오직 그 경우에만 empty이다.
[[PromiseFulfillReactions]] PromiseReaction 레코드List promise가 pending 상태에서 fulfilled 상태로 전환될 때/전환된다면 처리될 레코드.
[[PromiseRejectReactions]] PromiseReaction 레코드List promise가 pending 상태에서 rejected 상태로 전환될 때/전환된다면 처리될 레코드.
[[PromiseIsHandled]] Boolean promise가 fulfillment 또는 rejection handler를 가진 적이 있는지 여부를 나타내며, unhandled rejection 추적에 사용된다.

27.3 GeneratorFunction 객체

GeneratorFunction은 보통 GeneratorDeclaration, GeneratorExpression, 및 GeneratorMethod를 평가하여 생성되는 함수이다. %GeneratorFunction% intrinsic을 호출하여 생성될 수도 있다.

Figure 6 (Informative): Generator 객체 관계
엄청나게 다양한 상자와 화살표.

27.3.1 GeneratorFunction 생성자

GeneratorFunction 생성자:

  • %GeneratorFunction%이다.
  • Function의 서브클래스이다.
  • 생성자가 아니라 함수로 호출될 때 새로운 GeneratorFunction을 생성하고 초기화한다. 따라서 함수 호출 GeneratorFunction (…)은 같은 인자를 가진 객체 생성 표현식 new GeneratorFunction (…)과 동등하다.
  • 클래스 정의의 extends 절의 값으로 사용될 수 있다. 지정된 GeneratorFunction 동작을 상속하려는 서브클래스 생성자는 built-in GeneratorFunction 동작에 필요한 내부 슬롯으로 서브클래스 인스턴스를 생성하고 초기화하기 위해 GeneratorFunction 생성자에 대한 super 호출을 포함해야 한다. generator function 객체를 정의하는 모든 ECMAScript 구문 형식은 GeneratorFunction의 직접 인스턴스를 생성한다. GeneratorFunction 서브클래스의 인스턴스를 생성하는 구문적 수단은 없다.

27.3.1.1 GeneratorFunction ( ...parameterArgs, bodyArg )

마지막 인자(있는 경우)는 generator function의 본문(실행 가능한 코드)을 지정하며, 그 앞의 모든 인자는 형식 매개변수를 지정한다.

이 함수는 호출될 때 다음 단계를 수행한다:

  1. activeFuncactive function object로 둔다.
  2. bodyArg가 존재하지 않으면, bodyArg를 빈 String으로 설정한다.
  3. CreateDynamicFunction(activeFunc, NewTarget, generator, parameterArgs, bodyArg)을 반환한다.
Note

20.2.1.1NOTE를 참조하라.

27.3.2 GeneratorFunction 생성자의 프로퍼티

GeneratorFunction 생성자:

  • Function 생성자에서 상속하는 표준 built-in function object이다.
  • 값이 %Function%[[Prototype]] 내부 슬롯을 가진다.
  • 값이 1𝔽"length" 프로퍼티를 가진다.
  • 값이 "GeneratorFunction""name" 프로퍼티를 가진다.
  • 다음 프로퍼티를 가진다:

27.3.2.1 GeneratorFunction.prototype

GeneratorFunction.prototype의 초기 값은 GeneratorFunction prototype object이다.

이 프로퍼티는 속성 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }를 가진다.

27.3.3 GeneratorFunction Prototype Object의 프로퍼티

GeneratorFunction prototype object:

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% 프로퍼티의 초기 값은 String 값 "GeneratorFunction"이다.

이 프로퍼티는 속성 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }를 가진다.

27.3.4 GeneratorFunction 인스턴스

모든 GeneratorFunction 인스턴스는 ECMAScript function object이며 Table 25에 나열된 내부 슬롯을 가진다. 그러한 모든 인스턴스의 [[IsClassConstructor]] 내부 슬롯 값은 false이다.

각 GeneratorFunction 인스턴스는 다음 own 프로퍼티를 가진다:

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 인스턴스가 생성될 때마다 또 다른 ordinary object도 생성되며, 이는 generator function의 "prototype" 프로퍼티의 초기 값이 된다. generator function 객체가 [[Call]]을 사용하여 호출될 때 새로 생성된 Generator의 [[Prototype]] 내부 슬롯을 초기화하기 위해 prototype 프로퍼티의 값이 사용된다.

이 프로퍼티는 속성 { [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false }를 가진다.

Note

Function 인스턴스와 달리, GeneratorFunction의 "prototype" 프로퍼티 값인 객체는 값이 GeneratorFunction 인스턴스인 "constructor" 프로퍼티를 가지지 않는다.

27.4 AsyncGeneratorFunction 객체

AsyncGeneratorFunction은 보통 AsyncGeneratorDeclaration, AsyncGeneratorExpression, 및 AsyncGeneratorMethod 구문 생성을 평가하여 생성되는 함수이다. %AsyncGeneratorFunction% intrinsic을 호출하여 생성될 수도 있다.

27.4.1 AsyncGeneratorFunction 생성자

AsyncGeneratorFunction 생성자:

  • %AsyncGeneratorFunction%이다.
  • Function의 서브클래스이다.
  • 생성자가 아니라 함수로 호출될 때 새로운 AsyncGeneratorFunction을 생성하고 초기화한다. 따라서 함수 호출 AsyncGeneratorFunction (...)은 같은 인자를 가진 객체 생성 표현식 new AsyncGeneratorFunction (...)과 동등하다.
  • 클래스 정의의 extends 절의 값으로 사용될 수 있다. 지정된 AsyncGeneratorFunction 동작을 상속하려는 서브클래스 생성자는 built-in AsyncGeneratorFunction 동작에 필요한 내부 슬롯으로 서브클래스 인스턴스를 생성하고 초기화하기 위해 AsyncGeneratorFunction 생성자에 대한 super 호출을 포함해야 한다. async generator function 객체를 정의하는 모든 ECMAScript 구문 형식은 AsyncGeneratorFunction의 직접 인스턴스를 생성한다. AsyncGeneratorFunction 서브클래스의 인스턴스를 생성하는 구문적 수단은 없다.

27.4.1.1 AsyncGeneratorFunction ( ...parameterArgs, bodyArg )

마지막 인자(있는 경우)는 async generator function의 본문(실행 가능한 코드)을 지정하며, 그 앞의 모든 인자는 형식 매개변수를 지정한다.

이 함수는 호출될 때 다음 단계를 수행한다:

  1. activeFuncactive function object로 둔다.
  2. bodyArg가 존재하지 않으면, bodyArg를 빈 String으로 설정한다.
  3. CreateDynamicFunction(activeFunc, NewTarget, async-generator, parameterArgs, bodyArg)을 반환한다.
Note

20.2.1.1NOTE를 참조하라.

27.4.2 AsyncGeneratorFunction 생성자의 프로퍼티

AsyncGeneratorFunction 생성자:

  • Function 생성자에서 상속하는 표준 built-in function object이다.
  • 값이 %Function%[[Prototype]] 내부 슬롯을 가진다.
  • 값이 1𝔽"length" 프로퍼티를 가진다.
  • 값이 "AsyncGeneratorFunction""name" 프로퍼티를 가진다.
  • 다음 프로퍼티를 가진다:

27.4.2.1 AsyncGeneratorFunction.prototype

AsyncGeneratorFunction.prototype의 초기 값은 AsyncGeneratorFunction prototype object이다.

이 프로퍼티는 속성 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }를 가진다.

27.4.3 AsyncGeneratorFunction Prototype Object의 프로퍼티

AsyncGeneratorFunction prototype object:

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% 프로퍼티의 초기 값은 String 값 "AsyncGeneratorFunction"이다.

이 프로퍼티는 속성 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }를 가진다.

27.4.4 AsyncGeneratorFunction 인스턴스

모든 AsyncGeneratorFunction 인스턴스는 ECMAScript function object이며 Table 25에 나열된 내부 슬롯을 가진다. 그러한 모든 인스턴스의 [[IsClassConstructor]] 내부 슬롯 값은 false이다.

각 AsyncGeneratorFunction 인스턴스는 다음 own 프로퍼티를 가진다:

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 인스턴스가 생성될 때마다 또 다른 ordinary object도 생성되며, 이는 async generator function의 "prototype" 프로퍼티의 초기 값이 된다. generator function 객체가 [[Call]]을 사용하여 호출될 때 새로 생성된 AsyncGenerator의 [[Prototype]] 내부 슬롯을 초기화하기 위해 prototype 프로퍼티의 값이 사용된다.

이 프로퍼티는 속성 { [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false }를 가진다.

Note

function 인스턴스와 달리, AsyncGeneratorFunction의 "prototype" 프로퍼티 값인 객체는 값이 AsyncGeneratorFunction 인스턴스인 "constructor" 프로퍼티를 가지지 않는다.

27.5 Generator 객체

Generator는 generator function을 호출하여 생성되며 iterator 인터페이스iterable 인터페이스를 모두 준수한다.

Generator 인스턴스는 그 인스턴스를 생성한 generator function의 "prototype" 프로퍼티의 초기 값에서 직접 프로퍼티를 상속한다. Generator 인스턴스는 %GeneratorPrototype%에서 간접적으로 프로퍼티를 상속한다.

27.5.1 %GeneratorPrototype% 객체

%GeneratorPrototype% 객체:

  • %GeneratorFunction.prototype.prototype%이다.
  • ordinary object이다.
  • Generator 인스턴스가 아니며 [[GeneratorState]] 내부 슬롯을 가지지 않는다.
  • 값이 %Iterator.prototype%[[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. generatorthis value로 둔다.
  2. completionReturnCompletion(value)로 둔다.
  3. GeneratorResumeAbrupt(generator, completion, empty)를 반환한다.

27.5.1.4 %GeneratorPrototype%.throw ( exception )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. generatorthis value로 둔다.
  2. completionThrowCompletion(exception)으로 둔다.
  3. GeneratorResumeAbrupt(generator, completion, empty)를 반환한다.

27.5.1.5 %GeneratorPrototype% [ %Symbol.toStringTag% ]

%Symbol.toStringTag% 프로퍼티의 초기 값은 String 값 "Generator"이다.

이 프로퍼티는 속성 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }를 가진다.

27.5.2 Generator 인스턴스의 프로퍼티

Generator 인스턴스는 처음에 Table 89에 설명된 내부 슬롯을 가지고 생성된다.

Table 89: Generator 인스턴스의 내부 슬롯
내부 슬롯 타입 설명
[[GeneratorState]] suspended-start, suspended-yield, executing, 또는 completed generator의 현재 실행 상태.
[[GeneratorContext]] execution context 이 generator의 코드를 실행할 때 사용되는 execution context.
[[GeneratorBrand]] String 또는 empty 서로 다른 종류의 generator를 구별하는 데 사용되는 brand. ECMAScript 소스 텍스트로 선언된 generator의 [[GeneratorBrand]]는 항상 empty이다.

27.5.3 Generator 추상 연산

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. genContextrunning execution context로 둔다.
  3. genContext의 Generator component를 generator로 설정한다.
  4. closuregeneratorBody를 캡처하고 호출될 때 다음 단계를 수행하는, 매개변수가 없는 새로운 Abstract Closure로 둔다:
    1. acGenContextrunning execution context로 둔다.
    2. acGeneratoracGenContext의 Generator component로 둔다.
    3. generatorBody가 Parse Node이면,
      1. resultCompletion(generatorBodyEvaluation)으로 둔다.
    4. 그렇지 않으면,
      1. Assert: generatorBody는 매개변수가 없는 Abstract Closure이다.
      2. resultCompletion(generatorBody())로 둔다.
    5. Assert: 여기로 반환된다면, generator는 예외를 던졌거나 암시적 또는 명시적 return을 수행한 것이다.
    6. execution context stack에서 acGenContext를 제거하고 execution context stack의 맨 위에 있는 execution contextrunning execution context로 복원한다.
    7. acGenerator.[[GeneratorState]]completed로 설정한다.
    8. NOTE: generator가 completed 상태에 들어가면 그 상태를 결코 떠나지 않으며 관련 execution context는 다시 재개되지 않는다. acGenerator와 관련된 모든 실행 상태는 이 시점에서 폐기될 수 있다.
    9. resultnormal completion이면,
      1. resultValueundefined로 둔다.
    10. 그렇지 않고 resultreturn completion이면,
      1. resultValueresult.[[Value]]로 둔다.
    11. 그렇지 않으면,
      1. Assert: resultthrow completion이다.
      2. result를 반환한다.
    12. NormalCompletion(CreateIteratorResultObject(resultValue, true))를 반환한다.
  5. execution context에 대해 평가가 재개될 때 closure가 인자 없이 호출되도록 genContext의 code evaluation state를 설정한다.
  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. generator.[[GeneratorState]]executing으로 설정한다.
  6. RunSuspendedContext(genContext, NormalCompletion(value))를 반환한다.

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. NOTE: 생성기가 completed 상태에 들어가면 다시는 그 상태를 벗어나지 않으며, 관련 실행 컨텍스트도 다시 재개되지 않는다. 이 시점에서 generator와 관련된 모든 실행 상태는 폐기될 수 있다.
    3. statecompleted로 설정한다.
  3. statecompleted이면, 다음을 수행한다.
    1. abruptCompletion이 return 완료이면, 다음을 수행한다.
      1. CreateIteratorResultObject(abruptCompletion.[[Value]], true)를 반환한다.
    2. abruptCompletion을 반환한다.
  4. Assert: statesuspended-yield이다.
  5. genContextgenerator.[[GeneratorContext]]라 하자.
  6. generator.[[GeneratorState]]executing으로 설정한다.
  7. RunSuspendedContext(genContext, abruptCompletion)을 반환한다.

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. genContextrunning execution context로 둔다.
  2. genContext가 Generator component를 가지지 않으면, non-generator를 반환한다.
  3. generatorgenContext의 Generator component로 둔다.
  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. genContextrunning execution context로 둔다.
  2. Assert: genContext는 generator의 execution context이다.
  3. generatorgenContext의 Generator component 값으로 둔다.
  4. Assert: GetGeneratorKind()는 sync이다.
  5. generator.[[GeneratorState]]suspended-yield로 설정한다.
  6. execution context stack에서 genContext를 제거하고 execution context stack의 맨 위에 있는 execution contextrunning execution context로 복원한다.
  7. callerContextrunning execution context로 둔다.
  8. NormalCompletion(iteratorResult)를 전달하여 callerContext를 재개한다. genContext가 다시 재개되면, resumptionValue를 그것이 재개될 때의 Completion Record로 둔다.
  9. Assert: 제어가 여기 도달하면, genContext가 다시 running execution context이다.
  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. NOTE: closure는 IteratorResult 객체를 산출하기 위해 Yield 연산의 사용을 포함할 수 있다.
  2. extraSlots가 존재하지 않으면, extraSlots를 새로운 빈 List로 설정한다.
  3. internalSlotsListextraSlots와 « [[GeneratorState]], [[GeneratorContext]], [[GeneratorBrand]] »의 list-concatenation으로 둔다.
  4. generatorOrdinaryObjectCreate(generatorPrototype, internalSlotsList)로 둔다.
  5. generator.[[GeneratorBrand]]generatorBrand로 설정한다.
  6. generator.[[GeneratorState]]suspended-start로 설정한다.
  7. callerContextrunning execution context로 둔다.
  8. calleeContext를 새로운 execution context로 둔다.
  9. calleeContext의 Function을 null로 설정한다.
  10. calleeContextRealm을 현재 Realm Record로 설정한다.
  11. calleeContext의 ScriptOrModule을 callerContext의 ScriptOrModule로 설정한다.
  12. callerContext가 아직 suspended가 아니면, callerContext를 suspend한다.
  13. calleeContextexecution context stack에 push한다; calleeContext는 이제 running execution context이다.
  14. GeneratorStart(generator, closure)를 수행한다.
  15. execution context stack에서 calleeContext를 제거하고 callerContextrunning execution context로 복원한다.
  16. generator를 반환한다.

27.6 AsyncGenerator 객체

AsyncGenerator는 async generator function을 호출하여 생성되며 async iterator 인터페이스async iterable 인터페이스를 모두 준수한다.

AsyncGenerator 인스턴스는 그 인스턴스를 생성한 async generator function의 "prototype" 프로퍼티의 초기 값에서 직접 프로퍼티를 상속한다. AsyncGenerator 인스턴스는 %AsyncGeneratorPrototype%에서 간접적으로 프로퍼티를 상속한다.

27.6.1 %AsyncGeneratorPrototype% 객체

%AsyncGeneratorPrototype% 객체:

  • %AsyncGeneratorFunction.prototype.prototype%이다.
  • ordinary object이다.
  • AsyncGenerator 인스턴스가 아니며 [[AsyncGeneratorState]] 내부 슬롯을 가지지 않는다.
  • 값이 %AsyncIteratorPrototype%[[Prototype]] 내부 슬롯을 가진다.
  • 모든 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 value로 둔다.
  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 value로 둔다.
  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. 그렇지 않고 statesuspended-yield이면,
    1. AsyncGeneratorResume(generator, completion)를 수행한다.
  10. 그렇지 않으면,
    1. Assert: stateexecuting 또는 draining-queue이다.
  11. promiseCapability.[[Promise]]를 반환한다.

27.6.1.4 %AsyncGeneratorPrototype%.throw ( exception )

  1. generatorthis value로 둔다.
  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% 프로퍼티의 초기 값은 String 값 "AsyncGenerator"이다.

이 프로퍼티는 속성 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }를 가진다.

27.6.2 AsyncGenerator 인스턴스의 프로퍼티

AsyncGenerator 인스턴스는 처음에 아래에 설명된 내부 슬롯을 가지고 생성된다:

Table 90: AsyncGenerator 인스턴스의 내부 슬롯
내부 슬롯 타입 설명
[[AsyncGeneratorState]] suspended-start, suspended-yield, executing, draining-queue, 또는 completed async generator의 현재 실행 상태.
[[AsyncGeneratorContext]] execution context 이 async generator의 코드를 실행할 때 사용되는 execution context.
[[AsyncGeneratorQueue]] AsyncGeneratorRequest 레코드의 List async generator를 재개하기 위한 요청을 나타내는 레코드. 상태 전환 중을 제외하면, [[AsyncGeneratorState]]executing 또는 draining-queue인 경우에 그리고 오직 그 경우에만 비어 있지 않다.
[[GeneratorBrand]] String 또는 empty 서로 다른 종류의 async generator를 구별하는 데 사용되는 brand. ECMAScript 소스 텍스트로 선언된 async generator의 [[GeneratorBrand]]는 항상 empty이다.

27.6.3 AsyncGenerator 추상 연산

27.6.3.1 AsyncGeneratorRequest 레코드

AsyncGeneratorRequest는 async generator가 어떻게 재개되어야 하는지에 대한 정보를 저장하고 해당 promise를 fulfill하거나 reject하기 위한 capability를 포함하는 데 사용되는 Record 값이다.

다음 필드를 가진다:

Table 91: AsyncGeneratorRequest 레코드 필드
필드 이름 의미
[[Completion]] Completion Record async generator를 재개하는 데 사용되어야 하는 Completion Record.
[[Capability]] PromiseCapability 레코드 이 요청과 관련된 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. genContextrunning execution context로 둔다.
  3. genContext의 Generator component를 generator로 설정한다.
  4. closuregeneratorBody를 캡처하고 호출될 때 다음 단계를 수행하는, 매개변수가 없는 새로운 Abstract Closure로 둔다:
    1. acGenContextrunning execution context로 둔다.
    2. acGeneratoracGenContext의 Generator component로 둔다.
    3. generatorBody가 Parse Node이면,
      1. resultCompletion(generatorBodyEvaluation)으로 둔다.
    4. 그렇지 않으면,
      1. Assert: generatorBody는 매개변수가 없는 Abstract Closure이다.
      2. resultCompletion(generatorBody())로 둔다.
    5. Assert: 여기로 반환된다면, async generator는 예외를 던졌거나 암시적 또는 명시적 return을 수행한 것이다.
    6. execution context stack에서 acGenContext를 제거하고 execution context stack의 맨 위에 있는 execution contextrunning execution context로 복원한다.
    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. execution context에 대해 평가가 재개될 때 closure가 인자 없이 호출되도록 genContext의 code evaluation state를 설정한다.
  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. oldRealmrunning execution contextRealm으로 둔다.
      2. running execution contextRealmrealm으로 설정한다.
      3. iteratorResultCreateIteratorResultObject(value, done)로 둔다.
      4. running execution contextRealmoldRealm으로 설정한다.
    3. 그렇지 않으면,
      1. iteratorResultCreateIteratorResultObject(value, done)로 둔다.
    4. Call(promiseCapability.[[Resolve]], undefined, « iteratorResult »)를 수행한다.
  8. unused를 반환한다.

27.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. generator.[[AsyncGeneratorState]]executing으로 설정한다.
  4. RunSuspendedContext(genContext, completion)을 수행한다.
  5. 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. genContextrunning execution context로 둔다.
  2. Assert: genContext는 generator의 execution context이다.
  3. generatorgenContext의 Generator component 값으로 둔다.
  4. Assert: GetGeneratorKind()는 async이다.
  5. completionNormalCompletion(value)로 둔다.
  6. Assert: execution context stack은 최소 두 개의 요소를 가진다.
  7. previousContextexecution context stack에서 위에서 두 번째 요소로 둔다.
  8. previousRealmpreviousContextRealm으로 둔다.
  9. AsyncGeneratorCompleteStep(generator, completion, false, previousRealm)을 수행한다.
  10. queuegenerator.[[AsyncGeneratorQueue]]로 둔다.
  11. queue가 비어 있지 않으면,
    1. NOTE: 실행은 generator를 suspend하지 않고 계속된다.
    2. toYieldqueue의 첫 번째 요소로 둔다.
    3. resumptionValueCompletion(toYield.[[Completion]])으로 둔다.
    4. AsyncGeneratorUnwrapYieldResumption(resumptionValue)를 반환한다.
  12. generator.[[AsyncGeneratorState]]suspended-yield로 설정한다.
  13. execution context stack에서 genContext를 제거하고 execution context stack의 맨 위에 있는 execution contextrunning execution context로 복원한다.
  14. callerContextrunning execution context로 둔다.
  15. undefined를 전달하여 callerContext를 재개한다. genContext가 다시 재개되면, resumptionValue를 그것이 재개될 때의 Completion Record로 둔다.
  16. Assert: 제어가 여기 도달하면, genContext가 다시 running execution context이다.
  17. 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. fulfilledClosuregenerator를 캡처하고 호출될 때 다음 단계를 수행하는, 매개변수 (value)를 가진 새로운 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. rejectedClosuregenerator를 캡처하고 호출될 때 다음 단계를 수행하는, 매개변수 (reason)를 가진 새로운 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를 만날 때까지 generator의 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. completionnormal completion이면,
      1. completionNormalCompletion(undefined)로 설정한다.
    5. AsyncGeneratorCompleteStep(generator, completion, true)를 수행한다.
  4. generator.[[AsyncGeneratorState]]completed로 설정한다.
  5. unused를 반환한다.

27.7 AsyncFunction 객체

AsyncFunction은 보통 AsyncFunctionDeclaration, AsyncFunctionExpression, AsyncMethod, 및 AsyncArrowFunction을 평가하여 생성되는 함수이다. %AsyncFunction% intrinsic을 호출하여 생성될 수도 있다.

27.7.1 AsyncFunction 생성자

AsyncFunction 생성자:

  • %AsyncFunction%이다.
  • Function의 서브클래스이다.
  • 생성자가 아니라 함수로 호출될 때 새로운 AsyncFunction을 생성하고 초기화한다. 따라서 함수 호출 AsyncFunction(…)은 같은 인자를 가진 객체 생성 표현식 new AsyncFunction(…)과 동등하다.
  • 클래스 정의의 extends 절의 값으로 사용될 수 있다. 지정된 AsyncFunction 동작을 상속하려는 서브클래스 생성자는 built-in async function 동작에 필요한 내부 슬롯으로 서브클래스 인스턴스를 생성하고 초기화하기 위해 AsyncFunction 생성자에 대한 super 호출을 포함해야 한다. async function 객체를 정의하는 모든 ECMAScript 구문 형식은 AsyncFunction의 직접 인스턴스를 생성한다. AsyncFunction 서브클래스의 인스턴스를 생성하는 구문적 수단은 없다.

27.7.1.1 AsyncFunction ( ...parameterArgs, bodyArg )

마지막 인자(있는 경우)는 async function의 본문(실행 가능한 코드)을 지정한다. 그 앞의 모든 인자는 형식 매개변수를 지정한다.

이 함수는 호출될 때 다음 단계를 수행한다:

  1. activeFuncactive function object로 둔다.
  2. bodyArg가 존재하지 않으면, bodyArg를 빈 String으로 설정한다.
  3. CreateDynamicFunction(activeFunc, NewTarget, async, parameterArgs, bodyArg)을 반환한다.
Note
20.2.1.1NOTE를 참조하라.

27.7.2 AsyncFunction 생성자의 프로퍼티

AsyncFunction 생성자:

  • Function 생성자에서 상속하는 표준 built-in function object이다.
  • 값이 %Function%[[Prototype]] 내부 슬롯을 가진다.
  • 값이 1𝔽"length" 프로퍼티를 가진다.
  • 값이 "AsyncFunction""name" 프로퍼티를 가진다.
  • 다음 프로퍼티를 가진다:

27.7.2.1 AsyncFunction.prototype

AsyncFunction.prototype의 초기 값은 AsyncFunction prototype object이다.

이 프로퍼티는 속성 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }를 가진다.

27.7.3 AsyncFunction Prototype Object의 프로퍼티

AsyncFunction prototype object:

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% 프로퍼티의 초기 값은 String 값 "AsyncFunction"이다.

이 프로퍼티는 속성 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }를 가진다.

27.7.4 AsyncFunction 인스턴스

모든 AsyncFunction 인스턴스는 ECMAScript function object이며 Table 25에 나열된 내부 슬롯을 가진다. 그러한 모든 인스턴스의 [[IsClassConstructor]] 내부 슬롯 값은 false이다. AsyncFunction 인스턴스는 생성자가 아니며 [[Construct]] 내부 메서드를 가지지 않는다. AsyncFunction 인스턴스는 constructable이 아니므로 prototype 프로퍼티를 가지지 않는다.

각 AsyncFunction 인스턴스는 다음 own 프로퍼티를 가진다:

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 Function 추상 연산

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. runningContextrunning execution context로 둔다.
  2. asyncContextrunningContext의 복사본으로 둔다.
  3. NOTE: AsyncBlockStart가 자신의 실행을 재개하려면 실행 상태 복사가 필요하다. 현재 실행 중인 context를 재개하는 것은 잘 정의되어 있지 않다.
  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. promiseCapabilityasyncBody를 캡처하고, 호출될 때 다음 단계를 수행하는, 매개변수가 없는 새로운 Abstract Closureclosure라 하자.
    1. acAsyncContext를 실행 중인 실행 컨텍스트라 하자.
    2. asyncBody가 Parse Node이면, 다음을 수행한다.
      1. resultCompletion(asyncBodyEvaluation)이라 하자.
    3. 그렇지 않으면,
      1. Assert: asyncBody는 매개변수가 없는 Abstract Closure이다.
      2. resultCompletion(asyncBody())라 하자.
    4. Assert: 여기로 반환되었다면, async 함수는 예외를 던졌거나 암시적 또는 명시적 반환을 수행한 것이다. 모든 await는 완료되었다.
    5. acAsyncContext를 실행 컨텍스트 스택에서 제거하고, 실행 컨텍스트 스택의 맨 위에 있는 실행 컨텍스트를 실행 중인 실행 컨텍스트로 복원한다.
    6. result가 정상 완료이면, 다음을 수행한다.
      1. Call(promiseCapability.[[Resolve]], undefined, « undefined »)을 수행한다.
    7. 그렇지 않고 result가 return 완료이면, 다음을 수행한다.
      1. Call(promiseCapability.[[Resolve]], undefined, « result.[[Value]] »)을 수행한다.
    8. 그렇지 않으면,
      1. Assert: result는 throw 완료이다.
      2. Call(promiseCapability.[[Reject]], undefined, « result.[[Value]] »)을 수행한다.
    9. NormalCompletion(unused)을 반환한다.
  2. asyncContext의 코드 평가 상태를 설정하여, 해당 실행 컨텍스트에 대해 평가가 재개될 때 closure가 인수 없이 호출되도록 한다.
  3. result를 ! RunSuspendedContext(asyncContext, NormalCompletion(empty))라 하자.
  4. Assert: resultunused이다.
  5. NOTE: result 값의 가능한 출처는 Await 또는, async 함수가 아무것도 await하지 않는 경우, 위의 단계 1.i이다.
  6. 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. asyncContext를 캡처하고, 호출될 때 다음 단계를 수행하는, 매개변수 (v)를 갖는 새로운 Abstract ClosurefulfilledClosure라 하자.
    1. Completion(RunSuspendedContext(asyncContext, NormalCompletion(v)))를 수행한다.
    2. NOTE: RunSuspendedContext가 반환한 Completion Record는 의도적으로 무시된다.
    3. NormalCompletion(undefined)을 반환한다.
  4. onFulfilledCreateBuiltinFunction(fulfilledClosure, 1, "", « »)라 하자.
  5. asyncContext를 캡처하고, 호출될 때 다음 단계를 수행하는, 매개변수 (reason)를 갖는 새로운 Abstract ClosurerejectedClosure라 하자.
    1. Completion(RunSuspendedContext(asyncContext, ThrowCompletion(reason)))을 수행한다.
    2. NOTE: RunSuspendedContext가 반환한 Completion Record는 의도적으로 무시된다.
    3. NormalCompletion(undefined)을 반환한다.
  6. onRejectedCreateBuiltinFunction(rejectedClosure, 1, "", « »)라 하자.
  7. PerformPromiseThen(promise, onFulfilled, onRejected)를 수행한다.
  8. asyncContext를 실행 컨텍스트 스택에서 제거하고, 실행 컨텍스트 스택의 맨 위에 있는 실행 컨텍스트를 실행 중인 실행 컨텍스트로 복원한다.
  9. callerContext를 실행 중인 실행 컨텍스트라 하자.
  10. empty를 전달하여 callerContext를 재개한다. asyncContext가 다시 재개되는 경우, 그것을 재개하는 데 사용된 Completion Recordcompletion이라 하자.
  11. Assert: 제어가 여기에 도달하면, asyncContext가 다시 실행 중인 실행 컨텍스트이다.
  12. completion을 반환한다.

28 리플렉션

28.1 Reflect 객체

Reflect 객체:

  • %Reflect%이다.
  • 전역 객체"Reflect" 프로퍼티의 초기 값이다.
  • ordinary object이다.
  • 값이 %Object.prototype%[[Prototype]] 내부 슬롯을 가진다.
  • function object가 아니다.
  • [[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, value [ , receiver ] )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. target이 Object가 아니면, TypeError 예외를 던진다.
  2. key를 ? ToPropertyKey(propertyKey)로 둔다.
  3. receiver가 존재하지 않으면,
    1. receivertarget으로 설정한다.
  4. target.[[Set]](key, value, receiver)를 반환한다.

28.1.13 Reflect.setPrototypeOf ( target, proto )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. target이 Object가 아니면, TypeError 예외를 던진다.
  2. proto가 Object가 아니고 protonull도 아니면, TypeError 예외를 던진다.
  3. target.[[SetPrototypeOf]](proto)를 반환한다.

28.1.14 Reflect [ %Symbol.toStringTag% ]

%Symbol.toStringTag% 프로퍼티의 초기 값은 String 값 "Reflect"이다.

이 프로퍼티는 속성 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }를 가진다.

28.2 Proxy 객체

28.2.1 Proxy 생성자

Proxy 생성자:

  • %Proxy%이다.
  • 전역 객체"Proxy" 프로퍼티의 초기 값이다.
  • 생성자로 호출될 때 새로운 Proxy 객체를 생성하고 초기화한다.
  • 함수로 호출되도록 의도되지 않았으며, 그런 방식으로 호출되면 예외를 던진다.

28.2.1.1 Proxy ( target, handler )

이 함수는 호출될 때 다음 단계를 수행한다:

  1. NewTarget이 undefined이면, TypeError 예외를 던진다.
  2. ProxyCreate(target, handler)를 반환한다.

28.2.2 Proxy 생성자의 프로퍼티

Proxy 생성자:

  • 값이 %Function.prototype%[[Prototype]] 내부 슬롯을 가진다.
  • Proxy 객체에는 초기화가 필요한 [[Prototype]] 내부 슬롯이 없기 때문에 "prototype" 프로퍼티를 가지지 않는다.
  • 다음 프로퍼티를 가진다:

28.2.2.1 Proxy.revocable ( target, handler )

이 함수는 revocable Proxy 객체를 생성한다.

호출될 때 다음 단계를 수행한다:

  1. proxy를 ? ProxyCreate(target, handler)로 둔다.
  2. revokerClosure를 아무것도 캡처하지 않고 호출될 때 다음 단계를 수행하는, 매개변수가 없는 새로운 Abstract Closure로 둔다:
    1. activeFuncactive function object로 둔다.
    2. pactiveFunc.[[RevocableProxy]]로 둔다.
    3. pnull이면, NormalCompletion(undefined)를 반환한다.
    4. activeFunc.[[RevocableProxy]]null로 설정한다.
    5. Assert: p는 Proxy exotic object이다.
    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 객체

Module Namespace Object는 모듈의 export된 binding에 대해 런타임 프로퍼티 기반 접근을 제공하는 module namespace exotic object이다. Module Namespace Object에는 생성자 함수가 없다. 대신, 그러한 객체는 NameSpaceImport를 포함하는 ImportDeclaration에 의해 import되는 각 모듈에 대해 생성된다.

10.4.6에 지정된 프로퍼티 외에도 각 Module Namespace Object는 다음 own 프로퍼티를 가진다:

28.3.1 %Symbol.toStringTag%

%Symbol.toStringTag% 프로퍼티의 초기 값은 String 값 "Module"이다.

이 프로퍼티는 속성 { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }를 가진다.

29 메모리 모델

메모리 일관성 모델, 또는 메모리 모델은 SharedArrayBuffer를 기반으로 하는 TypedArray 인스턴스에 접근하거나 Atomics 객체의 메서드를 통해 발생하는 Shared Data Block 이벤트의 가능한 순서를 지정한다. 프로그램에 데이터 레이스(아래에서 정의됨)가 없을 때, 이벤트의 순서는 순차적으로 일관된 것처럼, 즉 각 agent의 동작이 interleaving된 것처럼 보인다. 프로그램에 데이터 레이스가 있으면, 공유 메모리 연산은 순차적으로 일관되지 않게 보일 수 있다. 예를 들어, 프로그램은 인과성을 위반하는 동작 및 다른 놀라운 현상을 보일 수 있다. 이러한 놀라운 현상은 컴파일러 변환과 CPU 설계(예: out-of-order 실행 및 speculation)에서 비롯된다. 메모리 모델은 프로그램이 순차적으로 일관된 동작을 보이는 정확한 조건과 데이터 레이스에서 읽을 수 있는 가능한 값을 모두 정의한다. 즉, undefined behaviour는 없다.

메모리 모델은 평가 중 SharedArrayBuffer의 추상 연산 또는 Atomics 객체의 메서드에 의해 도입되는 Memory 이벤트에 대한 관계적 제약으로 정의된다.

Note

이 절은 SharedArrayBuffer에 대한 추상 연산에 의해 도입되는 Memory 이벤트에 관한 공리적 모델을 제공한다. 이 모델은 이 명세의 나머지 부분과 달리 알고리즘적으로 표현할 수 없다는 점을 강조할 필요가 있다. 추상 연산에 의한 이벤트의 비결정적 도입은 ECMAScript 평가의 조작적 의미론과 메모리 모델의 공리적 의미론 사이의 인터페이스이다. 이러한 이벤트의 의미론은 평가의 모든 이벤트 그래프를 고려하여 정의된다. 이들은 Static Semantics도 Runtime Semantics도 아니다. 입증된 알고리즘적 구현은 없고, 대신 특정 이벤트 그래프가 허용되는지 허용되지 않는지를 결정하는 제약 집합이 있다.

29.1 메모리 모델 기본 사항

공유 메모리 접근(읽기와 쓰기)은 아래에서 정의되는 두 그룹, atomic 접근과 data 접근으로 나뉜다. Atomic 접근은 순차적으로 일관된다. 즉, agent cluster의 모든 agent가 동의하는 이벤트의 엄격한 전체 순서가 있다. Non-atomic 접근은 모든 agent가 동의하는 엄격한 전체 순서를 가지지 않는다. 즉, unordered이다.

Note 1

release-acquire와 같이 순차적 일관성보다 약하고 unordered보다 강한 ordering은 지원되지 않는다.

Shared Data Block 이벤트ReadSharedMemory, WriteSharedMemory, 또는 ReadModifyWriteSharedMemory Record이다. read 이벤트는 ReadSharedMemory 또는 ReadModifyWriteSharedMemory이다. write 이벤트는 WriteSharedMemory 또는 ReadModifyWriteSharedMemory이다.

Table 92: ReadSharedMemory 이벤트 필드
필드 이름 의미
[[Order]] seq-cst 또는 unordered 해당 이벤트에 대해 메모리 모델이 보장하는 가장 약한 ordering.
[[NoTear]] Boolean 이 이벤트와 동일한 memory range를 가진 여러 write 이벤트에서 이 이벤트가 읽을 수 있는지 여부.
[[Block]] Shared Data Block 이벤트가 작동하는 block.
[[ByteIndex]] 음이 아닌 정수 [[Block]] 내 읽기의 바이트 주소.
[[ElementSize]] 음이 아닌 정수 읽기의 크기.
Table 93: WriteSharedMemory 이벤트 필드
필드 이름 의미
[[Order]] seq-cst, unordered, 또는 init 해당 이벤트에 대해 메모리 모델이 보장하는 가장 약한 ordering.
[[NoTear]] Boolean 이 이벤트와 동일한 memory range를 가진 여러 read 이벤트가 이 이벤트에서 읽을 수 있는지 여부.
[[Block]] Shared Data Block 이벤트가 작동하는 block.
[[ByteIndex]] 음이 아닌 정수 [[Block]] 내 쓰기의 바이트 주소.
[[ElementSize]] 음이 아닌 정수 쓰기의 크기.
[[Payload]] 바이트 값의 List 다른 이벤트가 읽을 바이트 값의 List.
Table 94: ReadModifyWriteSharedMemory 이벤트 필드
필드 이름 의미
[[Order]] seq-cst Read-modify-write 이벤트는 항상 순차적으로 일관된다.
[[NoTear]] true Read-modify-write 이벤트는 tear될 수 없다.
[[Block]] Shared Data Block 이벤트가 작동하는 block.
[[ByteIndex]] 음이 아닌 정수 [[Block]] 내 read-modify-write의 바이트 주소.
[[ElementSize]] 음이 아닌 정수 read-modify-write의 크기.
[[Payload]] 바이트 값의 List [[ModifyOp]]에 전달될 바이트 값의 List.
[[ModifyOp]] read-modify-write modification 함수 읽은 바이트 값의 List[[Payload]]로부터 수정된 바이트 값의 List를 반환하는 Abstract Closure.

Shared Data Block 이벤트는 추상 연산 또는 Atomics 객체의 메서드에 의해 candidate execution Agent Events Record에 도입된다. 일부 연산은 또한 필드가 없고 다른 이벤트의 허용된 ordering을 직접 제약하기 위해서만 존재하는 Synchronize 이벤트를 도입한다. 마지막으로, host-specific 이벤트가 있다. Memory 이벤트는 Shared Data Block 이벤트, Synchronize 이벤트, 또는 그러한 host-specific 이벤트이다.

Shared Data Block 이벤트 ememory rangee.[[ByteIndex]](포함)부터 e.[[ByteIndex]] + e.[[ElementSize]](제외)까지의 구간에 있는 모든 정수의 Set으로 둔다. 두 이벤트의 memory range는 이벤트가 같은 [[Block]], [[ByteIndex]], [[ElementSize]]를 가질 때 같다. 두 이벤트의 memory range는 이벤트가 같은 [[Block]]을 가지고, range가 같지 않으며, 교집합이 비어 있지 않을 때 overlapping이다. 두 이벤트의 memory range는 이벤트가 같은 [[Block]]을 가지지 않거나 range가 같지도 overlapping도 아닐 때 disjoint이다.

Note 2

고려되어야 할 host-specific synchronizing 이벤트의 예는 다음과 같다: 한 agent에서 다른 agent로 SharedArrayBuffer 보내기(예: 브라우저에서 postMessage 사용), agent 시작 및 중지, 공유 메모리 이외의 채널을 통한 agent cluster 내 통신. 특정 실행 execution에 대해, 이러한 이벤트는 host가 host-synchronizes-with strict partial order를 통해 제공한다. 추가로, host는 is-agent-order-before Relation에 참여하도록 host-specific synchronizing 이벤트를 execution.[[EventList]]에 추가할 수 있다.

이벤트는 아래에 정의된 관계에 의해 candidate execution 안에서 순서가 정해진다.

29.2 Agent Events Record

Agent Events Record는 다음 필드를 가진 Record이다.

Table 95: Agent Events Record 필드
필드 이름 의미
[[AgentSignifier]] agent signifier 이 ordering을 결과로 낳은 평가를 수행한 agent.
[[EventList]] Memory 이벤트List 이벤트는 평가 중 list에 추가된다.
[[AgentSynchronizesWith]] Synchronize 이벤트 쌍의 List 조작적 의미론에 의해 도입되는 Synchronize 관계.

29.3 Chosen Value Record

Chosen Value Record는 다음 필드를 가진 Record이다.

Table 96: Chosen Value Record 필드
필드 이름 의미
[[Event]] Shared Data Block 이벤트 이 chosen value를 위해 도입된 ReadSharedMemory 또는 ReadModifyWriteSharedMemory 이벤트.
[[ChosenValue]] 바이트 값의 List 평가 중 비결정적으로 선택된 바이트.

29.4 Candidate Execution

agent cluster의 평가에 대한 candidate execution은 다음 필드를 가진 Record이다.

Table 97: Candidate Execution Record 필드
필드 이름 의미
[[EventsRecords]] Agent Events RecordList agent를 평가 중 추가된 Memory 이벤트List에 매핑한다.
[[ChosenValues]] Chosen Value RecordList ReadSharedMemory 또는 ReadModifyWriteSharedMemory 이벤트를 평가 중 선택된 바이트 값의 List에 매핑한다.

empty candidate execution은 필드가 빈 List인 candidate execution Record이다.

29.5 메모리 모델을 위한 추상 연산

29.5.1 EventSet ( execution )

The abstract operation EventSet takes argument execution (a candidate execution) and returns a Set of Memory events. It performs the following steps when called:

  1. events를 빈 Set으로 둔다.
  2. execution.[[EventsRecords]]의 각 Agent Events Record aer에 대해, 다음을 수행한다
    1. aer.[[EventList]]의 각 Memory 이벤트 event에 대해, 다음을 수행한다
      1. eventevents에 추가한다.
  3. events를 반환한다.

29.5.2 SharedDataBlockEventSet ( execution )

The abstract operation SharedDataBlockEventSet takes argument execution (a candidate execution) and returns a Set of Shared Data Block events. It performs the following steps when called:

  1. events를 빈 Set으로 둔다.
  2. EventSet(execution)의 각 Memory 이벤트 event에 대해, 다음을 수행한다
    1. eventShared Data Block 이벤트이면, eventevents에 추가한다.
  3. events를 반환한다.

29.5.3 HostEventSet ( execution )

The abstract operation HostEventSet takes argument execution (a candidate execution) and returns a Set of Memory events. It performs the following steps when called:

  1. SharedDataBlockEventSet(execution)에 없는 EventSet(execution)의 모든 요소를 포함하는 새로운 Set을 반환한다.

29.5.4 ComposeWriteEventBytes ( execution, byteIndex, writes )

The abstract operation ComposeWriteEventBytes takes arguments execution (a candidate execution), byteIndex (a non-negative integer), and writes (a List of either WriteSharedMemory or ReadModifyWriteSharedMemory events) and returns a List of byte values. It performs the following steps when called:

  1. byteLocationbyteIndex로 둔다.
  2. bytesRead를 새로운 빈 List로 둔다.
  3. writes의 각 요소 writeEvent에 대해, 다음을 수행한다
    1. Assert: writeEvent는 자신의 memory rangebyteLocation을 가진다.
    2. payloadIndexbyteLocation - writeEvent.[[ByteIndex]]로 둔다.
    3. writeEventWriteSharedMemory 이벤트이면,
      1. bytewriteEvent.[[Payload]][payloadIndex]로 둔다.
    4. 그렇지 않으면,
      1. Assert: writeEventReadModifyWriteSharedMemory 이벤트이다.
      2. bytesValueOfReadEvent(execution, writeEvent)로 둔다.
      3. bytesModifiedwriteEvent.[[ModifyOp]](bytes, writeEvent.[[Payload]])로 둔다.
      4. bytebytesModified[payloadIndex]로 둔다.
    5. bytebytesRead에 추가한다.
    6. byteLocationbyteLocation + 1로 설정한다.
  4. bytesRead를 반환한다.
Note 1

read-modify-write modification [[ModifyOp]]ReadModifyWriteSharedMemory 이벤트를 도입하는 Atomics 객체의 함수 프로퍼티에 의해 주어진다.

Note 2

추상 연산write 이벤트List를 바이트 값의 List로 구성한다. 이는 ReadSharedMemoryReadModifyWriteSharedMemory 이벤트의 이벤트 의미론에서 사용된다.

29.5.5 ValueOfReadEvent ( execution, readEvent )

The abstract operation ValueOfReadEvent takes arguments execution (a candidate execution) and readEvent (a ReadSharedMemory or ReadModifyWriteSharedMemory event) and returns a List of byte values. It performs the following steps when called:

  1. writesexecutionreads-bytes-from(readEvent)로 둔다.
  2. Assert: writes는 길이가 readEvent.[[ElementSize]]와 같은 WriteSharedMemory 또는 ReadModifyWriteSharedMemory 이벤트의 List이다.
  3. ComposeWriteEventBytes(execution, readEvent.[[ByteIndex]], writes)를 반환한다.

29.6 Candidate Execution의 관계

다음 관계와 수학적 함수는 특정 candidate execution에 대해 매개변수화되며 그 Memory 이벤트에 순서를 부여한다.

29.6.1 is-agent-order-before

candidate execution execution에 대해, 그 is-agent-order-before Relation은 다음을 만족하는 Memory 이벤트에 대한 최소 Relation이다.

  • 이벤트 eventAeventB에 대해, execution.[[EventsRecords]] 안에 어떤 Agent Events Record aer가 있고 aer.[[EventList]]eventAeventB를 모두 포함하며 eventAaer.[[EventList]]List 순서에서 eventB보다 앞에 있다면, eventAexecution에서 eventB보다 is-agent-order-before이다.
Note

각 agent는 평가 중 agent별 엄격한 전체 순서로 이벤트를 도입한다. 이는 그러한 엄격한 전체 순서들의 합집합이다.

29.6.2 reads-bytes-from

candidate execution execution에 대해, 그 reads-bytes-from 함수는 SharedDataBlockEventSet(execution) 안의 Memory 이벤트SharedDataBlockEventSet(execution) 안의 이벤트 List에 매핑하는 수학적 함수이며 다음 조건을 만족한다.

candidate execution은 항상 reads-bytes-from 함수를 허용한다.

29.6.3 reads-from

candidate execution execution에 대해, 그 reads-from Relation은 다음을 만족하는 Memory 이벤트에 대한 최소 Relation이다.

  • 이벤트 readEventwriteEvent에 대해, SharedDataBlockEventSet(execution)이 readEventwriteEvent를 모두 포함하고, execution 안의 reads-bytes-from(readEvent)가 writeEvent를 포함한다면, readEventexecution에서 writeEvent로부터 reads-from한다.

29.6.4 host-synchronizes-with

candidate execution execution에 대해, 그 host-synchronizes-with Relation은 host가 제공하는 host-specific Memory 이벤트에 대한 strict partial order이며 최소한 다음을 만족한다.

  • execution에서 eventA host-synchronizes-with eventB이면, HostEventSet(execution)은 eventAeventB를 포함한다.
  • execution 안에서 host-synchronizes-with와 is-agent-order-before의 합집합에는 cycle이 없다.
Note 1

candidate execution execution 안의 두 host-specific 이벤트 eventAeventB에 대해, execution에서 eventA host-synchronizes-with eventB라는 것은 execution에서 eventA happens-before eventB임을 함의한다.

Note 2

Relation은 host가 HTML worker 사이의 postMessage와 같은 추가 synchronization 메커니즘을 제공할 수 있게 한다.

29.6.5 synchronizes-with

candidate execution execution에 대해, 그 synchronizes-with Relation은 다음을 만족하는 Memory 이벤트에 대한 최소 Relation이다.

  • 이벤트 readEventwriteEvent에 대해, readEventexecution에서 writeEvent로부터 reads-from하고, readEvent.[[Order]]seq-cst이며, writeEvent.[[Order]]seq-cst이고, readEventwriteEvent가 같은 memory range를 가지면, writeEventexecution에서 readEvent와 synchronizes-with한다.
  • execution.[[EventsRecords]]의 각 요소 eventsRecord에 대해, 다음이 참이다.
    • 이벤트 eventAeventB에 대해, eventsRecord.[[AgentSynchronizesWith]]가 (eventA, eventB)를 포함한다면, eventAexecution에서 eventB와 synchronizes-with한다.
  • 이벤트 eventAeventB에 대해, execution.[[HostSynchronizesWith]]가 (eventA, eventB)를 포함한다면, eventAexecution에서 eventB와 synchronizes-with한다.
Note 1

메모리 모델 문헌의 관례 때문에, candidate execution execution에서 read 이벤트write 이벤트와 synchronizes-with하는 대신 write 이벤트read 이벤트와 synchronizes-with한다.

Note 2

candidate execution execution에서, init 이벤트는 이 Relation에 참여하지 않으며 대신 happens-before에 의해 직접 제약된다.

Note 3

candidate execution execution에서 reads-from에 의해 관련된 모든 seq-cst 이벤트가 synchronizes-with에 의해 관련되는 것은 아니다. 같은 memory range도 가지는 이벤트만 synchronizes-with에 의해 관련된다.

Note 4

candidate execution execution 안의 Shared Data Block 이벤트 readEventwriteEvent에 대해, writeEventreadEvent와 synchronizes-with하더라도, readEventwriteEvent가 아닌 다른 write에서 reads-from할 수 있다.

29.6.6 happens-before

candidate execution execution에 대해, 그 happens-before Relation은 다음을 만족하는 Memory 이벤트에 대한 최소 Relation이다.

  • 이벤트 eventAeventB에 대해, 다음 조건 중 하나라도 참이면 eventAexecution에서 eventB보다 happens-before이다.

    • eventAexecution에서 eventB보다 is-agent-order-before이다.
    • eventAexecution에서 eventBsynchronizes-with한다.
    • SharedDataBlockEventSet(execution)이 eventAeventB를 모두 포함하고, eventA.[[Order]]init이며, eventAeventB가 overlapping memory range를 가진다.
    • execution에서 eventAeventC보다 happens-before이고 eventCeventB보다 happens-before인 이벤트 eventC가 있다.
Note

happens-before는 agent-order의 superset이므로, candidate execution은 ECMAScript의 single-thread 평가 의미론과 일치한다.

29.7 Valid Execution의 프로퍼티

29.7.1 Valid Chosen Reads

candidate execution execution은 다음 알고리즘이 true를 반환하면 valid chosen reads를 가진다.

  1. SharedDataBlockEventSet(execution)의 각 ReadSharedMemory 또는 ReadModifyWriteSharedMemory 이벤트 readEvent에 대해, 다음을 수행한다
    1. chosenValueRecord[[Event]] 필드가 readEventexecution.[[ChosenValues]]의 요소로 둔다.
    2. chosenValuechosenValueRecord.[[ChosenValue]]로 둔다.
    3. readValueValueOfReadEvent(execution, readEvent)로 둔다.
    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

candidate execution execution은 다음 알고리즘이 true를 반환하면 coherent reads를 가진다.

  1. SharedDataBlockEventSet(execution)의 각 ReadSharedMemory 또는 ReadModifyWriteSharedMemory 이벤트 readEvent에 대해, 다음을 수행한다
    1. writesexecutionreads-bytes-from(readEvent)로 둔다.
    2. byteLocationreadEvent.[[ByteIndex]]로 둔다.
    3. writes의 각 요소 writeEvent에 대해, 다음을 수행한다
      1. execution에서 readEvent happens-before writeEvent이면,
        1. false를 반환한다.
      2. byteLocation을 자신의 memory range에 가진 WriteSharedMemory 또는 ReadModifyWriteSharedMemory 이벤트 value가 존재하여, execution에서 writeEvent happens-before value이고 value happens-before readEvent이면,
        1. false를 반환한다.
      3. byteLocationbyteLocation + 1로 설정한다.
  2. true를 반환한다.

29.7.3 Tear Free Reads

candidate execution execution은 다음 알고리즘이 true를 반환하면 tear free reads를 가진다.

  1. SharedDataBlockEventSet(execution)의 각 ReadSharedMemory 또는 ReadModifyWriteSharedMemory 이벤트 readEvent에 대해, 다음을 수행한다
    1. readEvent.[[NoTear]]true이면,
      1. Assert: readEvent.[[ByteIndex]]readEvent.[[ElementSize]]로 나눈 나머지는 0이다.
      2. execution에서 readEventwriteEvent로부터 reads-from하고 writeEvent.[[NoTear]]true인 각 Memory 이벤트 writeEvent에 대해, 다음을 수행한다
        1. readEventwriteEvent가 같은 memory range를 가지고, valuewriteEvent가 같은 memory range를 가지며, value.[[NoTear]]true이고, writeEventvalue가 같은 Shared Data Block 이벤트가 아니며, readEventexecution에서 value로부터 reads-from하는 Memory 이벤트 value가 존재하면,
          1. false를 반환한다.
  2. true를 반환한다.
Note

Shared Data Block 이벤트[[NoTear]] 필드는 그 이벤트가 integer TypedArray 접근을 통해 도입되었을 때 true이고, floating point TypedArray 또는 DataView 접근을 통해 도입되었을 때 false이다.

직관적으로 이 요구 사항은 integer TypedArray를 통해 정렬된 방식으로 memory range에 접근할 때, 같은 range를 가진 다른 write 이벤트data race가 있으면 그 range의 단일 write 이벤트가 "win"해야 한다는 뜻이다. 더 정확히 말하면, 이 요구 사항은 정렬된 read 이벤트가 모두 같은 range를 가진 여러 다른 write 이벤트의 바이트로 구성된 값을 읽을 수 없다는 뜻이다. 그러나 정렬된 read 이벤트가 overlapping range를 가진 여러 write 이벤트에서 읽는 것은 가능하다.

29.7.4 순차적으로 일관된 Atomics

candidate execution execution에 대해, is-memory-order-before는 다음을 만족하는 EventSet(execution) 안의 모든 Memory 이벤트의 엄격한 전체 순서이다.

candidate execution은 is-memory-order-before Relation을 허용하면 sequentially consistent atomics를 가진다.

Note 3

is-memory-order-before는 EventSet(execution) 안의 모든 이벤트를 포함하지만, execution에서 happens-before 또는 synchronizes-with에 의해 제약되지 않는 이벤트는 그 순서 어디에나 있을 수 있다.

29.7.5 Valid Execution

candidate execution execution은 다음이 모두 참이면 valid execution(또는 단순히 execution)이다.

모든 프로그램은 최소 하나의 valid execution을 가진다.

29.8 Race

execution executionSharedDataBlockEventSet(execution)에 포함된 이벤트 eventAeventB에 대해, 다음 알고리즘이 true를 반환하면 eventAeventBrace에 있다.

  1. eventAeventB가 같은 Shared Data Block 이벤트가 아니면,
    1. execution에서 eventA happens-before eventB이고 eventB happens-before eventA인 경우가 아니면,
      1. eventAWriteSharedMemory 또는 ReadModifyWriteSharedMemory 이벤트이고, eventBWriteSharedMemory 또는 ReadModifyWriteSharedMemory 이벤트이며, eventAeventB가 서로소인 메모리 범위를 갖지 않으면,
        1. true를 반환한다.
      2. execution에서 eventAeventB로부터 reads-from하거나 eventBeventA로부터 reads-from하면,
        1. true를 반환한다.
  2. false를 반환한다.

29.9 Data Race

execution executionSharedDataBlockEventSet(execution)에 포함된 이벤트 eventAeventB에 대해, 다음 알고리즘이 true를 반환하면 eventAeventBdata race에 있다.

  1. eventAeventBexecution에서 race에 있으면,
    1. eventA.[[Order]]seq-cst가 아니거나 eventB.[[Order]]seq-cst가 아니면,
      1. true를 반환한다.
    2. eventAeventB가 overlapping memory range를 가지면,
      1. true를 반환한다.
  2. false를 반환한다.

29.10 Data Race Freedom

execution executionSharedDataBlockEventSet(execution) 안에 data race에 있는 두 이벤트가 없으면 data race free이다.

프로그램은 자신의 모든 execution이 data race free이면 data race free이다.

메모리 모델은 data race free 프로그램에 대해 모든 이벤트의 순차적 일관성을 보장한다.

29.11 공유 메모리 지침

Note 1

다음은 공유 메모리로 작업하는 ECMAScript 프로그래머를 위한 지침이다.

프로그램을 data race free로 유지할 것을 권장한다. 즉, 같은 메모리 위치에 대한 동시 non-atomic 연산이 존재할 수 없도록 하라. Data race free 프로그램은 각 agent의 평가 의미론에서 각 단계가 서로 interleaving되는 interleaving 의미론을 가진다. Data race free 프로그램의 경우 메모리 모델의 세부 사항을 이해할 필요가 없다. 그 세부 사항은 ECMAScript를 더 잘 작성하는 데 도움이 될 직관을 형성할 가능성이 낮다.

더 일반적으로, 프로그램이 data race free가 아니더라도 atomic 연산이 어떤 data race에도 관여하지 않고 race하는 연산들이 모두 같은 access size를 가지는 한 예측 가능한 동작을 할 수 있다. atomics가 race에 관여하지 않도록 하는 가장 단순한 방법은 atomic 연산과 non-atomic 연산이 서로 다른 memory cell을 사용하도록 하고, 서로 다른 크기의 atomic 접근이 동시에 같은 cell에 접근하는 데 사용되지 않도록 하는 것이다. 사실상 프로그램은 공유 메모리를 가능한 한 strongly typed로 취급해야 한다. race하는 non-atomic 접근의 ordering과 timing에는 여전히 의존할 수 없지만, 메모리가 strongly typed로 취급된다면 race하는 접근은 "tear"되지 않는다(값의 bit가 섞이지 않는다).

Note 2

다음은 공유 메모리를 사용하는 프로그램에 대해 컴파일러 변환을 작성하는 ECMAScript 구현자를 위한 지침이다.

multi-agent 프로그램에서 각 agent의 성능이 single-agent 설정에서와 마찬가지로 좋도록 보장하기 위해, single-agent 설정에서 유효한 대부분의 프로그램 변환을 multi-agent 설정에서도 허용하는 것이 바람직하다. 이러한 변환은 판단하기 어려운 경우가 많다. 우리는 규범적으로 받아들여지도록 의도된(메모리 모델에 의해 함의되거나 메모리 모델이 함의하는 것보다 더 강한) 프로그램 변환에 관한 몇 가지 규칙을 개괄하지만, 이는 완전하지 않을 가능성이 높다. 이러한 규칙은 is-agent-order-before Relation을 구성하는 Memory 이벤트의 도입에 앞서는 프로그램 변환에 적용되도록 의도된다.

agent-order slice를 단일 agent에 관련된 is-agent-order-before Relation의 부분집합으로 둔다.

read 이벤트possible read values를 모든 valid execution에 걸친 그 이벤트의 ValueOfReadEvent 값들의 집합으로 둔다.

공유 메모리가 없는 경우 유효한 agent-order slice의 모든 변환은 공유 메모리가 있는 경우에도 다음 예외를 제외하고 유효하다.

  • Atomics are carved in stone: 프로그램 변환은 [[Order]]seq-cst인 어떤 Shared Data Block 이벤트is-agent-order-before Relation에서 제거되게 해서는 안 되며, 서로에 대해 reorder되게 해서도 안 되고, [[Order]]unordered인 이벤트에 대해 agent-order slice 안에서 reorder되게 해서도 안 된다.

    (실제로 reordering 금지는 컴파일러가 모든 seq-cst 연산이 synchronization이고 최종 is-memory-order-before Relation에 포함된다고 가정하도록 강제하며, inter-agent 프로그램 분석이 없는 경우에도 보통 그렇게 가정해야 한다. 또한 memory-order에 대한 callee의 효과가 알려지지 않은 모든 호출이 seq-cst 연산을 포함할 수 있다고 컴파일러가 가정하도록 강제한다.)

  • Reads must be stable: 주어진 공유 메모리 read는 execution 안에서 단 하나의 값만 관찰해야 한다.

    (예를 들어, 프로그램에서 의미상 단일 read인 것이 여러 번 실행되면, 그 후 프로그램은 읽힌 값들 중 하나만 관찰하도록 허용된다. rematerialization으로 알려진 변환은 이 규칙을 위반할 수 있다.)

  • Writes must be stable: 공유 메모리에 대한 모든 관찰 가능한 write는 execution 안의 프로그램 의미론으로부터 따라야 한다.

    (예를 들어, 더 작은 datum을 쓰기 위해 더 큰 위치에 read-modify-write 연산을 사용하거나, 프로그램이 쓸 수 없었던 값을 메모리에 쓰거나, read 이후 다른 agent가 덮어쓸 수 있었던 위치에 방금 읽은 값을 다시 쓰는 것과 같은 특정 관찰 가능한 write를 변환이 도입해서는 안 된다.)

  • Possible read values must be non-empty: 프로그램 변환은 공유 메모리 read의 possible read values가 비게 만들 수 없다.

    (직관에 반하지만, 이 규칙은 사실상 write에 대한 변환을 제한한다. memory model에서 write는 read 이벤트에 의해 읽힐 수 있다는 점에서 힘을 가지기 때문이다. 예를 들어, write는 이동되고 병합될 수 있으며 때로는 두 seq-cst 연산 사이에서 reorder될 수도 있지만, 변환은 어떤 위치를 갱신하는 모든 write를 제거해서는 안 된다. 일부 write는 보존되어야 한다.)

여전히 유효한 변환의 예는 다음과 같다: 같은 위치에서 여러 non-atomic read 병합, non-atomic read reordering, speculative non-atomic read 도입, 같은 위치에 대한 여러 non-atomic write 병합, 서로 다른 위치에 대한 non-atomic write reordering, 그리고 종료에 영향을 미치더라도 loop 밖으로 non-atomic read hoisting. 일반적으로 aliased TypedArray는 위치가 다르다는 것을 증명하기 어렵게 만든다는 점에 유의하라.

Note 3

다음은 공유 메모리 접근을 위한 machine code를 생성하는 ECMAScript 구현자를 위한 지침이다.

ARM 또는 Power의 메모리 모델보다 약하지 않은 메모리 모델을 가진 아키텍처의 경우, non-atomic store와 load는 대상 아키텍처의 bare store와 load로 컴파일될 수 있다. Atomic store와 load는 순차적 일관성을 보장하는 명령어로 컴파일될 수 있다. 그러한 명령어가 없으면, bare store 또는 load의 양쪽에 barrier를 배치하는 것과 같은 memory barrier를 사용해야 한다. Read-modify-write 연산은 x86의 LOCK-prefix 명령어, ARM의 load-exclusive/store-exclusive 명령어, Power의 load-link/store-conditional 명령어와 같은 대상 아키텍처의 read-modify-write 명령어로 컴파일될 수 있다.

구체적으로, 메모리 모델은 다음과 같은 코드 생성을 허용하도록 의도된다.

  • 프로그램의 모든 atomic 연산은 필요하다고 가정된다.
  • Atomic 연산은 서로 또는 non-atomic 연산과 결코 재배열되지 않는다.
  • 함수는 항상 atomic 연산을 수행한다고 가정된다.
  • Atomic 연산은 더 큰 데이터에 대한 read-modify-write 연산으로 구현되지 않으며, 플랫폼에 적절한 크기의 atomic 연산이 없으면 non-lock-free atomics로 구현된다. (우리는 이미 모든 플랫폼이 모든 흥미로운 크기의 normal memory access 연산을 가진다고 가정한다.)

Naive code generation은 다음 패턴을 사용한다:

  • Regular load와 store는 단일 load 및 store 명령어로 컴파일된다.
  • Lock-free atomic load와 store는 full(순차적으로 일관된) fence, regular load 또는 store, 그리고 full fence로 컴파일된다.
  • Lock-free atomic read-modify-write 접근은 full fence, atomic read-modify-write 명령어 sequence, 그리고 full fence로 컴파일된다.
  • Non-lock-free atomics는 spinlock acquire, full fence, 일련의 non-atomic load 및 store 명령어, full fence, 그리고 spinlock release로 컴파일된다.

그 매핑은 memory range에 대한 atomic 연산이 non-atomic write 또는 다른 크기의 atomic 연산과 race하지 않는 한 올바르다. 그러나 우리가 필요한 것은 그것뿐이다: 메모리 모델은 race에 관여한 atomic 연산을 사실상 non-atomic 상태로 격하시킨다. 한편, naive mapping은 상당히 강하다: 이는 atomic 연산이 순차적으로 일관된 fence로 사용될 수 있게 하는데, 메모리 모델은 실제로 이를 보장하지 않는다.

메모리 모델의 제약을 따르는 한, 이러한 기본 패턴에 대한 local improvement도 허용된다. 예를 들어:

  • 중복 fence를 제거하는 명백한 platform-dependent improvement가 있다. 예를 들어 x86에서는 lock-free atomic load와 store 주변의 fence가 store 뒤의 fence를 제외하면 항상 생략될 수 있으며, lock-free read-modify-write 명령어에는 fence가 필요하지 않다. 이는 모두 LOCK-prefix 명령어를 사용하기 때문이다. 많은 플랫폼에는 여러 강도의 fence가 있으며, 순차적 일관성을 깨뜨리지 않고 특정 context에서 더 약한 fence를 사용할 수 있다.
  • 대부분의 현대 플랫폼은 ECMAScript atomics가 요구하는 모든 데이터 크기에 대해 lock-free atomics를 지원한다. non-lock-free atomics가 필요하다면, atomic 연산 본문을 둘러싼 fence는 보통 lock 및 unlock 단계 안으로 접힐 수 있다. non-lock-free atomics에 대한 가장 단순한 해결책은 SharedArrayBuffer마다 하나의 lock word를 두는 것이다.
  • 또한 일부 코드 분석이 필요한 더 복잡한 platform-dependent local improvement도 있다. 예를 들어, 연속된 두 fence는 종종 단일 fence와 같은 효과를 가지므로, 두 atomic 연산이 연속으로 생성되는 경우 그 사이에는 단 하나의 fence만 필요하다. x86에서는 atomic store를 분리하는 단일 fence조차 생략될 수 있는데, store 뒤의 fence는 store를 후속 load와 분리하는 데만 필요하기 때문이다.

Annex A (informative) 문법 요약

A.1 어휘 문법

SourceCharacter :: 임의의 유니코드 코드 포인트 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 :: 유니코드 속성 “ID_Start”를 가진 임의의 유니코드 코드 포인트 UnicodeIDContinue :: 유니코드 속성 “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

다음 production의 인스턴스를 처리할 때
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 *= /= %= += -= <<= >>= >>>= &= ^= |= **=

특정 상황에서 다음 production의 인스턴스를 처리할 때
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

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]

다음 production의 인스턴스를 처리할 때
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]

다음 production의 인스턴스를 처리할 때
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 Number 변환

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

StringNumericLiteral 문법에 의해 명시적으로 정의되지 않은 모든 문법 기호는 숫자 literal을 위한 어휘 문법에서 사용되는 정의를 가진다.

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 기능

이 annex에 정의된 ECMAScript 언어 구문과 의미론은 ECMAScript host가 웹 브라우저일 때 요구된다. 이 annex의 내용은 normative이지만 ECMAScript host가 웹 브라우저가 아닌 경우에는 선택 사항이다.

이 annex에 정의된 일부 기능은 이 annex에 명시되어 있고, 일부는 이 문서의 본문에 명시되어 있다.

기능이 본문에 명시된 경우, 그것이 문서에 영향을 미치는 각 지점은 색상 상자 안의 "Normative Optional"이라는 단어로 표시된다. 또한 그 기능이 알고리즘이나 early error 규칙의 특정 문구를 포함하는 경우, 이는 관련 기능을 “host가 지원한다”는 조건에 의해 보호된다. 웹 브라우저는 이러한 모든 기능을 지원해야 한다.

Note

이 annex는 웹 브라우저 ECMAScript host의 여러 legacy 기능과 기타 특성을 설명한다. 이 annex에 명시된 모든 언어 기능과 동작은 하나 이상의 바람직하지 않은 특성을 가지고 있으며 legacy 사용이 없다면 이 명세에서 제거되었을 것이다. 그러나 이러한 기능을 사용하는 기존 웹 페이지가 매우 많기 때문에 웹 브라우저는 이를 계속 지원해야 한다. 이 annex의 명세는 이러한 legacy 기능의 상호 운용 가능한 구현에 대한 요구 사항을 정의한다.

이러한 기능은 핵심 ECMAScript 언어의 일부로 간주되지 않는다. 프로그래머는 새로운 ECMAScript 코드를 작성할 때 이러한 기능과 동작을 사용하거나 그 존재를 가정해서는 안 된다. ECMAScript 구현은 해당 구현이 웹 브라우저의 일부이거나 웹 브라우저가 마주치는 동일한 legacy ECMAScript 코드를 실행해야 하는 경우가 아니라면 이러한 기능을 구현하지 않는 것이 권장된다.

B.1 추가 구문

B.1.1 HTML-like 주석

12.4의 구문과 의미론은 다음과 같이 확장된다. 단, goal symbol Module을 사용하여 source text를 파싱할 때는 이 확장이 허용되지 않는다:

구문

InputElementHashbangOrRegExp :: WhiteSpace LineTerminator Comment CommonToken HashbangComment RegularExpressionLiteral HTMLCloseComment Comment :: MultiLineComment SingleLineComment SingleLineHTMLOpenComment SingleLineHTMLCloseComment SingleLineDelimitedComment MultiLineComment :: /* FirstCommentLineopt LineTerminator MultiLineCommentCharsopt */ HTMLCloseCommentopt FirstCommentLine :: SingleLineDelimitedCommentChars SingleLineHTMLOpenComment :: <!-- SingleLineCommentCharsopt SingleLineHTMLCloseComment :: LineTerminatorSequence HTMLCloseComment SingleLineDelimitedComment :: /* SingleLineDelimitedCommentCharsopt */ HTMLCloseComment :: WhiteSpaceSequenceopt SingleLineDelimitedCommentSequenceopt --> SingleLineCommentCharsopt SingleLineDelimitedCommentChars :: SingleLineNotAsteriskChar SingleLineDelimitedCommentCharsopt * SingleLinePostAsteriskCommentCharsopt SingleLineNotAsteriskChar :: SourceCharacter but not one of * or LineTerminator SingleLinePostAsteriskCommentChars :: SingleLineNotForwardSlashOrAsteriskChar SingleLineDelimitedCommentCharsopt * SingleLinePostAsteriskCommentCharsopt SingleLineNotForwardSlashOrAsteriskChar :: SourceCharacter but not one of / or * or LineTerminator WhiteSpaceSequence :: WhiteSpace WhiteSpaceSequenceopt SingleLineDelimitedCommentSequence :: SingleLineDelimitedComment WhiteSpaceSequenceopt SingleLineDelimitedCommentSequenceopt

line terminator code point를 포함하는 MultiLineComment와 유사하게, SingleLineHTMLCloseComment는 syntactic grammar에 의한 파싱 목적상 LineTerminator로 간주된다.

B.1.2 정규 표현식 Pattern

22.2.1의 구문은 다음과 같이 수정 및 확장된다. 이러한 변경은 grammar production의 순서와 contextual information에 의해 해소되는 모호성을 도입한다. 다음 문법을 사용하여 파싱할 때, 각 alternative는 이전 production alternative가 일치하지 않는 경우에만 고려된다.

이 대체 pattern 문법과 의미론은 BMP pattern의 구문과 의미론만 변경한다. 다음 문법 확장은 [UnicodeMode] 매개변수로 매개변수화된 production을 포함한다. 그러나 이러한 확장은 goal symbol에 [UnicodeMode] 매개변수가 존재하는 상태로 파싱할 때 인식되는 Unicode pattern의 구문을 변경하지 않는다.

구문

Term[UnicodeMode, UnicodeSetsMode, NamedCaptureGroups] :: [+UnicodeMode] Assertion[+UnicodeMode, ?UnicodeSetsMode, ?NamedCaptureGroups] [+UnicodeMode] Atom[+UnicodeMode, ?UnicodeSetsMode, ?NamedCaptureGroups] Quantifier [+UnicodeMode] Atom[+UnicodeMode, ?UnicodeSetsMode, ?NamedCaptureGroups] [~UnicodeMode] QuantifiableAssertion[?NamedCaptureGroups] Quantifier [~UnicodeMode] Assertion[~UnicodeMode, ~UnicodeSetsMode, ?NamedCaptureGroups] [~UnicodeMode] ExtendedAtom[?NamedCaptureGroups] Quantifier [~UnicodeMode] ExtendedAtom[?NamedCaptureGroups] Assertion[UnicodeMode, UnicodeSetsMode, NamedCaptureGroups] :: ^ $ \b \B [+UnicodeMode] (?= Disjunction[+UnicodeMode, ?UnicodeSetsMode, ?NamedCaptureGroups] ) [+UnicodeMode] (?! Disjunction[+UnicodeMode, ?UnicodeSetsMode, ?NamedCaptureGroups] ) [~UnicodeMode] QuantifiableAssertion[?NamedCaptureGroups] (?<= Disjunction[?UnicodeMode, ?UnicodeSetsMode, ?NamedCaptureGroups] ) (?<! Disjunction[?UnicodeMode, ?UnicodeSetsMode, ?NamedCaptureGroups] ) QuantifiableAssertion[NamedCaptureGroups] :: (?= Disjunction[~UnicodeMode, ~UnicodeSetsMode, ?NamedCaptureGroups] ) (?! Disjunction[~UnicodeMode, ~UnicodeSetsMode, ?NamedCaptureGroups] ) ExtendedAtom[NamedCaptureGroups] :: . \ AtomEscape[~UnicodeMode, ?NamedCaptureGroups] \ [lookahead = c] CharacterClass[~UnicodeMode, ~UnicodeSetsMode] ( GroupSpecifier[~UnicodeMode]opt Disjunction[~UnicodeMode, ~UnicodeSetsMode, ?NamedCaptureGroups] ) (? RegularExpressionModifiers : Disjunction[~UnicodeMode, ~UnicodeSetsMode, ?NamedCaptureGroups] ) (? RegularExpressionModifiers - RegularExpressionModifiers : Disjunction[~UnicodeMode, ~UnicodeSetsMode, ?NamedCaptureGroups] ) InvalidBracedQuantifier ExtendedPatternCharacter InvalidBracedQuantifier :: { DecimalDigits[~Sep] } { DecimalDigits[~Sep] ,} { DecimalDigits[~Sep] , DecimalDigits[~Sep] } ExtendedPatternCharacter :: SourceCharacter but not one of ^ $ \ . * + ? ( ) [ | AtomEscape[UnicodeMode, NamedCaptureGroups] :: [+UnicodeMode] DecimalEscape [~UnicodeMode] DecimalEscape but only if the CapturingGroupNumber of DecimalEscape is ≤ CountLeftCapturingParensWithin(the Pattern containing DecimalEscape) CharacterClassEscape[?UnicodeMode] CharacterEscape[?UnicodeMode, ?NamedCaptureGroups] [+NamedCaptureGroups] k GroupName[?UnicodeMode] CharacterEscape[UnicodeMode, NamedCaptureGroups] :: ControlEscape c AsciiLetter 0 [lookahead ∉ DecimalDigit] HexEscapeSequence RegExpUnicodeEscapeSequence[?UnicodeMode] [~UnicodeMode] LegacyOctalEscapeSequence IdentityEscape[?UnicodeMode, ?NamedCaptureGroups] IdentityEscape[UnicodeMode, NamedCaptureGroups] :: [+UnicodeMode] SyntaxCharacter [+UnicodeMode] / [~UnicodeMode] SourceCharacterIdentityEscape[?NamedCaptureGroups] SourceCharacterIdentityEscape[NamedCaptureGroups] :: [~NamedCaptureGroups] SourceCharacter but not c [+NamedCaptureGroups] SourceCharacter but not one of c or k ClassAtomNoDash[UnicodeMode, NamedCaptureGroups] :: SourceCharacter but not one of \ or ] or - \ ClassEscape[?UnicodeMode, ?NamedCaptureGroups] \ [lookahead = c] ClassEscape[UnicodeMode, NamedCaptureGroups] :: b [+UnicodeMode] - [~UnicodeMode] c ClassControlLetter CharacterClassEscape[?UnicodeMode] CharacterEscape[?UnicodeMode, ?NamedCaptureGroups] ClassControlLetter :: DecimalDigit _ Note

같은 left-hand side가 [+UnicodeMode]와 [~UnicodeMode] guard 모두와 함께 나타나는 경우, 이는 disambiguation priority를 제어하기 위한 것이다.

B.1.2.1 Static Semantics: Early Errors

22.2.1.1의 의미론은 다음과 같이 확장된다:

ExtendedAtom :: InvalidBracedQuantifier
  • source text가 이 production과 일치하면 Syntax Error이다.

추가로, 다음 production에 대한 규칙은 highlighted text의 추가로 수정된다:

NonemptyClassRanges :: ClassAtom - ClassAtom ClassContents NonemptyClassRangesNoDash :: ClassAtomNoDash - ClassAtom ClassContents

B.1.2.2 Static Semantics: CountLeftCapturingParensWithin 및 CountLeftCapturingParensBefore

CountLeftCapturingParensWithinCountLeftCapturingParensBefore의 정의에서 “ Atom :: ( GroupSpecifieropt Disjunction ) ”에 대한 참조는 “ Atom :: ( GroupSpecifieropt Disjunction ) ” 또는 “ ExtendedAtom :: ( GroupSpecifieropt Disjunction ) ”을 의미하는 것으로 해석되어야 한다.

B.1.2.3 Static Semantics: IsCharacterClass

22.2.1.6의 의미론은 다음과 같이 확장된다:

ClassAtomNoDash :: \ [lookahead = c]
  1. false를 반환한다.

B.1.2.4 Static Semantics: CharacterValue

22.2.1.7의 의미론은 다음과 같이 확장된다:

ClassAtomNoDash :: \ [lookahead = c]
  1. U+005C (REVERSE SOLIDUS)의 numeric value를 반환한다.
ClassEscape :: c ClassControlLetter
  1. chClassControlLetter가 일치시킨 code point로 둔다.
  2. ich의 numeric value로 둔다.
  3. i를 32로 나눈 나머지를 반환한다.
CharacterEscape :: LegacyOctalEscapeSequence
  1. LegacyOctalEscapeSequence의 MV를 반환한다(12.9.4.3 참조).

B.1.2.5 Runtime Semantics: CompileSubpattern

CompileSubpattern의 의미론은 다음과 같이 확장된다:

Term :: QuantifiableAssertion Quantifier 에 대한 규칙은 AtomQuantifiableAssertion로 대체한다는 점을 제외하고 Term :: Atom Quantifier 와 같다.

Term :: ExtendedAtom Quantifier 에 대한 규칙은 AtomExtendedAtom으로 대체한다는 점을 제외하고 Term :: Atom Quantifier 와 같다.

Term :: ExtendedAtom 에 대한 규칙은 AtomExtendedAtom으로 대체한다는 점을 제외하고 Term :: Atom 과 같다.

B.1.2.6 Runtime Semantics: CompileAssertion

Assertion :: (?= Disjunction ) Assertion :: (?! Disjunction ) production에 대한 CompileAssertion 규칙은 AssertionQuantifiableAssertion로 대체하여 QuantifiableAssertion production에도 사용된다.

B.1.2.7 Runtime Semantics: CompileAtom

Atom :: PatternCharacter 를 제외한 Atom production에 대한 CompileAtom 규칙은 AtomExtendedAtom으로 대체하여 ExtendedAtom production에도 사용된다. 매개변수 direction을 가진 다음 규칙도 추가된다:

ExtendedAtom :: \ [lookahead = c]
  1. charSet을 단일 문자 \ U+005C (REVERSE SOLIDUS)를 포함하는 CharSet으로 둔다.
  2. CharacterSetMatcher(regexpRecord, charSet, false, direction)를 반환한다.
ExtendedAtom :: ExtendedPatternCharacter
  1. chExtendedPatternCharacter가 나타내는 문자로 둔다.
  2. charSet을 문자 ch를 포함하는 one-element CharSet으로 둔다.
  3. CharacterSetMatcher(regexpRecord, charSet, false, direction)를 반환한다.

B.1.2.8 Runtime Semantics: CompileToCharSet

22.2.2.9의 의미론은 다음과 같이 확장된다:

다음 두 규칙은 CompileToCharSet의 대응하는 규칙을 대체한다.

NonemptyClassRanges :: ClassAtom - ClassAtom ClassContents
  1. charSet을 인수 regexpRecord를 가진 첫 번째 ClassAtomCompileToCharSet으로 둔다.
  2. otherSet을 인수 regexpRecord를 가진 두 번째 ClassAtomCompileToCharSet으로 둔다.
  3. remainingSet을 인수 regexpRecord를 가진 ClassContentsCompileToCharSet으로 둔다.
  4. rangeSetCharacterRangeOrUnion(regexpRecord, charSet, otherSet)으로 둔다.
  5. rangeSetremainingSet의 union을 반환한다.
NonemptyClassRangesNoDash :: ClassAtomNoDash - ClassAtom ClassContents
  1. charSet을 인수 regexpRecord를 가진 ClassAtomNoDashCompileToCharSet으로 둔다.
  2. otherSet을 인수 regexpRecord를 가진 ClassAtomCompileToCharSet으로 둔다.
  3. remainingSet을 인수 regexpRecord를 가진 ClassContentsCompileToCharSet으로 둔다.
  4. rangeSetCharacterRangeOrUnion(regexpRecord, charSet, otherSet)으로 둔다.
  5. rangeSetremainingSet의 union을 반환한다.

또한 다음 규칙이 CompileToCharSet에 추가된다.

ClassEscape :: c ClassControlLetter
  1. cv를 이 ClassEscapeCharacterValue로 둔다.
  2. c를 character value가 cv인 문자로 둔다.
  3. 단일 문자 c를 포함하는 CharSet을 반환한다.
ClassAtomNoDash :: \ [lookahead = c]
  1. 단일 문자 \ U+005C (REVERSE SOLIDUS)를 포함하는 CharSet을 반환한다.
Note
이 production은 character class 안에서 허용되는 control character가 뒤따르지 않는 sequence \c로부터만 도달할 수 있다.

B.1.2.8.1 CharacterRangeOrUnion ( regexpRecord, charSet, otherSet )

The abstract operation CharacterRangeOrUnion takes arguments regexpRecord (a RegExp Record), charSet (a CharSet), and otherSet (a CharSet) and returns a CharSet. It performs the following steps when called:

  1. HasEitherUnicodeFlag(regexpRecord)가 false이면,
    1. charSet이 정확히 하나의 문자를 포함하지 않거나 otherSet이 정확히 하나의 문자를 포함하지 않으면,
      1. remainingSet을 단일 문자 - U+002D (HYPHEN-MINUS)를 포함하는 CharSet으로 둔다.
      2. CharSet charSet, otherSetremainingSet의 union을 반환한다.
  2. CharacterRange(charSet, otherSet)를 반환한다.

B.1.2.9 Static Semantics: ParsePattern ( patternText, u, v )

22.2.3.4의 의미론은 다음과 같이 확장된다:

추상 연산 ParsePattern은 인수 patternText(Unicode code point의 sequence), u(Boolean), 그리고 v(Boolean)를 받는다. 호출될 때 다음 단계를 수행한다:

  1. vtrue이고 utrue이면,
    1. parseResult를 하나 이상의 SyntaxError 객체를 포함하는 List로 둔다.
  2. 그렇지 않고 vtrue이면,
    1. parseResultParseText(patternText, Pattern[+UnicodeMode, +UnicodeSetsMode, +NamedCaptureGroups])로 둔다.
  3. 그렇지 않고 utrue이면,
    1. parseResultParseText(patternText, Pattern[+UnicodeMode, ~UnicodeSetsMode, +NamedCaptureGroups])로 둔다.
  4. 그렇지 않으면,
    1. parseResultParseText(patternText, Pattern[~UnicodeMode, ~UnicodeSetsMode, ~NamedCaptureGroups])로 둔다.
    2. parseResult가 Parse Node이고 parseResultGroupName을 포함하면,
      1. parseResultParseText(patternText, Pattern[~UnicodeMode, ~UnicodeSetsMode, +NamedCaptureGroups])로 설정한다.
  5. parseResult를 반환한다.

B.2 추가 Built-in 프로퍼티

ECMAScript host가 웹 브라우저일 때 표준 built-in 객체의 다음 추가 프로퍼티가 정의된다.

B.2.1 전역 객체의 추가 프로퍼티

Table 98의 항목이 Table 6에 추가된다.

Table 98: 추가 Well-known Intrinsic 객체
Intrinsic 이름 전역 이름 ECMAScript 언어 연관
%escape% escape escape 함수(B.2.1.1)
%unescape% unescape unescape 함수(B.2.1.2)

B.2.1.1 escape ( string )

이 함수는 전역 객체의 프로퍼티이다. 특정 code unit이 hexadecimal escape sequence로 대체된 String 값의 새로운 버전을 계산한다.

numeric value가 0x00FF 이하인 code unit을 대체할 때는 %xx 형식의 두 자리 escape sequence가 사용된다. numeric value가 0x00FF보다 strictly greater인 code unit을 대체할 때는 %uxxxx 형식의 네 자리 escape sequence가 사용된다.

이는 %escape% intrinsic object이다.

호출될 때 다음 단계를 수행한다:

  1. string을 ? ToString(string)으로 설정한다.
  2. lenstring의 길이로 둔다.
  3. result를 빈 String으로 둔다.
  4. unescapedSet을 ASCII word character와 "@*+-./"의 string-concatenation으로 둔다.
  5. k를 0으로 둔다.
  6. k < len인 동안 반복한다,
    1. codeUnitstring 안의 index k에 있는 code unit으로 둔다.
    2. unescapedSetcodeUnit을 포함하면,
      1. strcodeUnit으로 둔다.
    3. 그렇지 않으면,
      1. ncodeUnit의 numeric value로 둔다.
      2. n < 256이면,
        1. hex를 uppercase hexadecimal number로 형식화된 n의 String 표현으로 둔다.
        2. str"%"StringPad(hex, 2, "0", start)의 string-concatenation으로 둔다.
      3. 그렇지 않으면,
        1. hex를 uppercase hexadecimal number로 형식화된 n의 String 표현으로 둔다.
        2. str"%u"StringPad(hex, 4, "0", start)의 string-concatenation으로 둔다.
    4. resultresultstr의 string-concatenation으로 설정한다.
    5. kk + 1로 설정한다.
  7. result를 반환한다.
Note

이 인코딩은 부분적으로 RFC 1738에 설명된 인코딩에 기반하지만, 이 표준에 명시된 전체 인코딩은 RFC 1738의 내용과 무관하게 위에 설명되어 있다. 이 인코딩은 RFC 3986에 의해 RFC 1738에 이루어진 변경을 반영하지 않는다.

B.2.1.2 unescape ( string )

이 함수는 전역 객체의 프로퍼티이다. escape 함수에 의해 도입될 수 있는 종류의 각 escape sequence가 그것이 나타내는 code unit으로 대체된 String 값의 새로운 버전을 계산한다.

이는 %unescape% intrinsic object이다.

호출될 때 다음 단계를 수행한다:

  1. string을 ? ToString(string)으로 설정한다.
  2. lenstring의 길이로 둔다.
  3. result를 빈 String으로 둔다.
  4. k를 0으로 둔다.
  5. k < len인 동안 반복한다,
    1. codeUnitstring 안의 index k에 있는 code unit으로 둔다.
    2. codeUnit이 code unit 0x0025 (PERCENT SIGN)이면,
      1. hexDigits를 빈 String으로 둔다.
      2. optionalAdvance를 0으로 둔다.
      3. k + 5 < len이고 string 안의 index k + 1에 있는 code unit이 code unit 0x0075 (LATIN SMALL LETTER U)이면,
        1. hexDigitsstringk + 2부터 k + 6까지의 substring으로 설정한다.
        2. optionalAdvance를 5로 설정한다.
      4. 그렇지 않고 k + 3 ≤ len이면,
        1. hexDigitsstringk + 1부터 k + 3까지의 substring으로 설정한다.
        2. optionalAdvance를 2로 설정한다.
      5. parseResultParseText(hexDigits, HexDigits[~Sep])로 둔다.
      6. parseResult가 Parse Node이면,
        1. nparseResult의 MV로 둔다.
        2. codeUnit을 numeric value가 n인 code unit으로 설정한다.
        3. kk + optionalAdvance로 설정한다.
    3. resultresultcodeUnit의 string-concatenation으로 설정한다.
    4. kk + 1로 설정한다.
  6. result를 반환한다.

B.2.2 String.prototype 객체의 추가 프로퍼티

B.2.2.1 String.prototype.substr ( start, length )

이 메서드는 this 값을 String으로 변환한 결과의 substring을 반환하며, index start에서 시작하여 length code unit만큼 진행한다(또는 lengthundefined이면 String의 끝까지). start가 음수이면, String의 길이인 sourceLength에 대해 sourceLength + start로 취급된다. 결과는 String 객체가 아니라 String 값이다.

호출될 때 다음 단계를 수행한다:

  1. objthis value로 둔다.
  2. RequireObjectCoercible(obj)를 수행한다.
  3. str을 ? ToString(obj)로 둔다.
  4. sizestr의 길이로 둔다.
  5. intStart를 ? ToIntegerOrInfinity(start)로 둔다.
  6. intStart = -∞이면, intStart를 0으로 설정한다.
  7. 그렇지 않고 intStart < 0이면, intStartmax(size + intStart, 0)으로 설정한다.
  8. 그렇지 않으면, intStartmin(intStart, size)로 설정한다.
  9. lengthundefined이면, intLengthsize로 둔다; 그렇지 않으면 intLength를 ? ToIntegerOrInfinity(length)로 둔다.
  10. intLength를 0과 size 사이로 clamp한 결과로 설정한다.
  11. intEndmin(intStart + intLength, size)로 둔다.
  12. strintStart부터 intEnd까지의 substring을 반환한다.
Note

이 메서드는 의도적으로 generic하다; this 값이 String 객체일 것을 요구하지 않는다. 따라서 다른 종류의 객체에 메서드로 사용되도록 이전될 수 있다.

B.2.2.2 String.prototype.anchor ( name )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. strthis value로 둔다.
  2. CreateHTML(str, "a", "name", name)를 반환한다.

B.2.2.2.1 CreateHTML ( contents, tag, attribute, attrValue )

The abstract operation CreateHTML takes arguments contents (an ECMAScript language value), tag (a String), attribute (a String), and attrValue (an ECMAScript language value) and returns either a normal completion containing a String or a throw completion. It performs the following steps when called:

  1. RequireObjectCoercible(contents)를 수행한다.
  2. contentsStr을 ? ToString(contents)로 둔다.
  3. p1"<"tag의 string-concatenation으로 둔다.
  4. attribute가 빈 String이 아니면,
    1. attrValueStr을 ? ToString(attrValue)로 둔다.
    2. escapedAttrValueattrValueStr 안의 code unit 0x0022 (QUOTATION MARK)의 각 occurrence가 여섯 code unit sequence "&quot;"로 대체된 것을 제외하면 attrValueStr와 같은 String 값으로 둔다.
    3. p1을 다음의 string-concatenation으로 설정한다:
      • p1
      • code unit 0x0020 (SPACE)
      • attribute
      • code unit 0x003D (EQUALS SIGN)
      • code unit 0x0022 (QUOTATION MARK)
      • escapedAttrValue
      • code unit 0x0022 (QUOTATION MARK)
  5. p2p1">"의 string-concatenation으로 둔다.
  6. p3p2contentsStr의 string-concatenation으로 둔다.
  7. p4p3, "</", tag, 그리고 ">"의 string-concatenation으로 둔다.
  8. p4를 반환한다.

B.2.2.3 String.prototype.big ( )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. strthis value로 둔다.
  2. CreateHTML(str, "big", "", "")를 반환한다.

B.2.2.4 String.prototype.blink ( )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. strthis value로 둔다.
  2. CreateHTML(str, "blink", "", "")를 반환한다.

B.2.2.5 String.prototype.bold ( )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. strthis value로 둔다.
  2. CreateHTML(str, "b", "", "")를 반환한다.

B.2.2.6 String.prototype.fixed ( )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. strthis value로 둔다.
  2. CreateHTML(str, "tt", "", "")를 반환한다.

B.2.2.7 String.prototype.fontcolor ( colour )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. strthis value로 둔다.
  2. CreateHTML(str, "font", "color", colour)를 반환한다.

B.2.2.8 String.prototype.fontsize ( size )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. strthis value로 둔다.
  2. CreateHTML(str, "font", "size", size)를 반환한다.

B.2.2.9 String.prototype.italics ( )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. strthis value로 둔다.
  2. CreateHTML(str, "i", "", "")를 반환한다.

B.2.2.10 String.prototype.link ( url )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. strthis value로 둔다.
  2. CreateHTML(str, "a", "href", url)를 반환한다.

B.2.2.11 String.prototype.small ( )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. strthis value로 둔다.
  2. CreateHTML(str, "small", "", "")를 반환한다.

B.2.2.12 String.prototype.strike ( )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. strthis value로 둔다.
  2. CreateHTML(str, "strike", "", "")를 반환한다.

B.2.2.13 String.prototype.sub ( )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. strthis value로 둔다.
  2. CreateHTML(str, "sub", "", "")를 반환한다.

B.2.2.14 String.prototype.sup ( )

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. strthis value로 둔다.
  2. CreateHTML(str, "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 problem”을 피하기 때문에 거의 모든 목적에서 선호된다.

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. dateObjectthis value로 둔다.
  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 problem”을 피하기 때문에 거의 모든 목적에서 선호된다.

이 메서드는 호출될 때 다음 단계를 수행한다:

  1. dateObjectthis value로 둔다.
  2. RequireInternalSlot(dateObject, [[DateValue]])를 수행한다.
  3. timedateObject.[[DateValue]]로 둔다.
  4. year를 ? ToNumber(year)로 둔다.
  5. timeNaN이면 time+0𝔽으로 설정한다; 그렇지 않으면 timeLocalTime(time)으로 설정한다.
  6. fullYearMakeFullYear(year)로 둔다.
  7. dayMakeDay(fullYear, MonthFromTime(time), DateFromTime(time))으로 둔다.
  8. dateMakeDate(day, TimeWithinDay(time))으로 둔다.
  9. utcTimestampTimeClip(UTC(date))로 둔다.
  10. dateObject.[[DateValue]]utcTimestamp로 설정한다.
  11. utcTimestamp를 반환한다.

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. objthis value로 둔다.
  2. RequireInternalSlot(obj, [[RegExpMatcher]])를 수행한다.
  3. pattern이 Object이고 pattern[[RegExpMatcher]] 내부 슬롯을 가지면,
    1. flagsundefined가 아니면, TypeError 예외를 던진다.
    2. flagspattern.[[OriginalFlags]]로 설정한다.
    3. patternpattern.[[OriginalSource]]로 설정한다.
  4. RegExpInitialize(obj, pattern, flags)를 반환한다.
Note

이 메서드는 this value RegExp를 새로운 pattern과 flag로 완전히 다시 초기화한다. 구현은 이 메서드의 사용을 결과 RegExp 객체가 여러 번 사용될 것이라는 assertion으로 해석할 수 있으며, 따라서 추가 최적화의 후보로 볼 수 있다.

B.3 기타 추가 기능

B.3.1 Labelled Function Declaration

ECMAScript 2015 이전에는 LabelledStatement의 명세가 statement label과 FunctionDeclaration의 연결을 허용하지 않았다. 그러나 labelled FunctionDeclarationnon-strict 코드에 대해 허용 가능한 확장이었고, 대부분의 browser-hosted ECMAScript 구현은 그 확장을 지원했다. ECMAScript 2015 및 이후에서는 LabelledStatement의 grammar production이 FunctionDeclarationLabelledItem으로 사용하는 것을 허용하지만, 14.13.1는 그것이 발생하면 Syntax Error를 생성하는 Early Error 규칙을 포함한다. 그런 다음 host가 이 기능을 지원한다면 non-strict 코드에서 Syntax Error를 억제하도록 그 규칙이 수정된다.

Note

WithStatement, IfStatement, 그리고 IterationStatement에 대한 early error 규칙은 이러한 statement가 non-strict 코드에서 labelled FunctionDeclaration을 포함하는 것을 방지한다.

B.3.2 Block-Level Function Declaration 웹 Legacy 호환성 의미론

ECMAScript 2015 이전에는 ECMAScript 명세가 Block statement의 StatementList 요소로 FunctionDeclaration이 발생하는 것을 정의하지 않았다. 그러나 그런 형태의 FunctionDeclaration 지원은 허용 가능한 확장이었고 대부분의 browser-hosted ECMAScript 구현은 이를 허용했다. 불행히도 그러한 선언의 의미론은 구현마다 다르다. 이러한 의미론적 차이 때문에, Block level function declaration을 사용하는 기존 웹 ECMAScript source text는 그 사용이 그러한 선언에 대한 모든 브라우저 구현의 의미론적 교집합에만 의존할 때에만 브라우저 구현 간에 portable하다. 다음은 그 교집합 의미론 안에 들어가는 사용 사례이다:

  1. 함수가 선언되고 단일 block 안에서만 참조된다.

    • BindingIdentifier가 이름 f인 하나 이상의 FunctionDeclaration이 둘러싸는 함수 g의 function code 안에 발생하고, 그 선언이 Block 안에 중첩되어 있다.
    • var declaration이 아닌 f의 다른 선언이 g의 function code 안에 발생하지 않는다.
    • IdentifierReference로서의 f의 모든 occurrence는 f의 선언을 포함하는 BlockStatementList 안에 있다.
  2. 함수가 선언되고 단일 Block 안에서 사용될 수 있지만, 같은 Block 안에 포함되지 않은 inner function definition에서도 참조된다.

    • BindingIdentifier가 이름 f인 하나 이상의 FunctionDeclaration이 둘러싸는 함수 g의 function code 안에 발생하고, 그 선언이 Block 안에 중첩되어 있다.
    • var declaration이 아닌 f의 다른 선언이 g의 function code 안에 발생하지 않는다.
    • IdentifierReference로서의 f의 occurrence가 f의 선언을 포함하는 BlockStatementList 안에 있을 수 있다.
    • g 안에 중첩된 다른 함수 h 안에 IdentifierReference로서의 f의 occurrence가 최소 하나 있고, h 안에서 f에 대한 참조를 shadow하는 f의 다른 선언이 없다.
    • h의 모든 호출은 f의 선언이 평가된 뒤에 발생한다.
  3. 함수가 선언되고 단일 block 안에서 사용될 수 있지만, 이후 block 안에서도 참조된다.

    • BindingIdentifier가 이름 f인 하나 이상의 FunctionDeclaration이 둘러싸는 함수 g의 function code 안에 발생하고, 그 선언이 Block 안에 중첩되어 있다.
    • var declaration이 아닌 f의 다른 선언이 g의 function code 안에 발생하지 않는다.
    • IdentifierReference로서의 f의 occurrence가 f의 선언을 포함하는 BlockStatementList 안에 있을 수 있다.
    • g의 function code 안에, f의 선언을 포함하는 Block을 lexical하게 뒤따르는 IdentifierReference로서의 f의 occurrence가 최소 하나 있다.

첫 번째 사용 사례는 ECMAScript 2015가 제공하는 Block level function declaration의 의미론과 상호 운용 가능하다. 그 사용 사례를 채택하는 기존 ECMAScript source text는 10, 14, 그리고 15 절에 정의된 Block level function declaration 의미론을 사용하여 동작한다.

두 번째 및 세 번째 사용 사례에 대한 ECMAScript 2015 상호 운용성은 10 절, 15 절, 19.2.1 절 및 16.1.7 절 의미론에 대한 다음 확장을 요구한다.

ECMAScript 구현에 diagnostic warning message를 보고하는 메커니즘이 있다면, 이러한 compatibility semantics가 적용되고 non-compatibility semantics와 관찰 가능한 차이를 도입하는 FunctionDeclaration이 코드에 포함될 때 warning이 생성되어야 한다. 예를 들어, var binding의 도입이 early error를 만들기 때문에 var binding이 도입되지 않는 경우 warning message는 생성되지 않아야 한다.

이 기능은 다음 지점에서 특별한 의미론을 포함한다:

B.3.3 IfStatement Statement Clause 안의 FunctionDeclaration

다음은 14.6IfStatement production을 보강한다:

IfStatement[Yield, Await, Return] : if ( Expression[+In, ?Yield, ?Await] ) FunctionDeclaration[?Yield, ?Await, ~Default] else Statement[?Yield, ?Await, ?Return] if ( Expression[+In, ?Yield, ?Await] ) Statement[?Yield, ?Await, ?Return] else FunctionDeclaration[?Yield, ?Await, ~Default] if ( Expression[+In, ?Yield, ?Await] ) FunctionDeclaration[?Yield, ?Await, ~Default] else FunctionDeclaration[?Yield, ?Await, ~Default] if ( Expression[+In, ?Yield, ?Await] ) FunctionDeclaration[?Yield, ?Await, ~Default] [lookahead ≠ else]

이 production은 non-strict 코드를 파싱할 때에만 적용된다. 이 production과 일치하는 source text는 FunctionDeclaration[?Yield, ?Await, ~Default]의 각 일치 occurrence가 source text의 해당 위치를 차지하는 BlockStatement의 유일한 StatementListItem인 것처럼 처리된다. 그러한 synthetic BlockStatement의 의미론은 B.3.2에 명시된 web legacy compatibility semantics를 포함한다.

B.3.4 Catch Block 안의 VariableStatement

이 기능에서, Catch clause의 BlockCatchParameter에 의해 binding된 이름과 같은 이름을 bind하는 var declaration을 포함할 수 있다. 이는 14.15.1 안의 Catch : catch ( CatchParameter ) Block 에 대한 early error 규칙을 수정하여 달성된다.

Note

Runtime에서 그러한 binding은 VariableDeclarationEnvironment 안에 instantiate된다. 이들은 CatchParameter가 도입한 같은 이름의 binding을 shadow하지 않으므로, 그러한 var declaration의 Initializervar binding이 아니라 대응하는 catch parameter에 할당한다.

이 수정된 동작은 Catch clause의 Block 안에 포함된 direct eval call에 의해 도입되는 varfunction declaration에도 적용된다. 이 변경은 EvalDeclarationInstantiation 안의 단계 3.d.i.2.a.i13.b.ii.4.a.i.i를 수정하여 달성된다.

B.3.5 ForIn Statement Head 안의 Initializer

다음은 14.7.5ForInOfStatement production을 보강한다:

ForInOfStatement[Yield, Await, Return] : for ( var BindingIdentifier[?Yield, ?Await] Initializer[~In, ?Yield, ?Await] in Expression[+In, ?Yield, ?Await] ) Statement[?Yield, ?Await, ?Return]

이 production은 non-strict 코드를 파싱할 때에만 적용된다.

8.3.1ContainsDuplicateLabels static semantics는 다음으로 보강된다:

ForInOfStatement : for ( var BindingIdentifier Initializer in Expression ) Statement
  1. 인수 labelSet을 가진 StatementContainsDuplicateLabels를 반환한다.

8.3.2ContainsUndefinedBreakTarget static semantics는 다음으로 보강된다:

ForInOfStatement : for ( var BindingIdentifier Initializer in Expression ) Statement
  1. 인수 labelSet을 가진 StatementContainsUndefinedBreakTarget을 반환한다.

8.3.3ContainsUndefinedContinueTarget static semantics는 다음으로 보강된다:

ForInOfStatement : for ( var BindingIdentifier Initializer in Expression ) Statement
  1. 인수 iterationSet 및 « »를 가진 StatementContainsUndefinedContinueTarget을 반환한다.

14.7.5.2IsDestructuring static semantics는 다음으로 보강된다:

BindingIdentifier : Identifier yield await
  1. false를 반환한다.

8.2.6VarDeclaredNames static semantics는 다음으로 보강된다:

ForInOfStatement : for ( var BindingIdentifier Initializer in Expression ) Statement
  1. names1BindingIdentifierBoundNames로 둔다.
  2. names2StatementVarDeclaredNames로 둔다.
  3. names1names2list-concatenation을 반환한다.

8.2.7VarScopedDeclarations static semantics는 다음으로 보강된다:

ForInOfStatement : for ( var BindingIdentifier Initializer in Expression ) Statement
  1. declarations1을 « BindingIdentifier »로 둔다.
  2. declarations2StatementVarScopedDeclarations로 둔다.
  3. declarations1declarations2list-concatenation을 반환한다.

14.7.5.5ForInOfLoopEvaluation runtime semantics는 다음으로 보강된다:

ForInOfStatement : for ( var BindingIdentifier Initializer in Expression ) Statement
  1. bindingIdBindingIdentifierStringValue로 둔다.
  2. lhs를 ? ResolveBinding(bindingId)로 둔다.
  3. IsAnonymousFunctionDefinition(Initializer)가 true이면,
    1. value를 인수 bindingId를 가진 Initializer의 ? NamedEvaluation으로 둔다.
  4. 그렇지 않으면,
    1. rhsInitializer의 ? Evaluation으로 둔다.
    2. value를 ? GetValue(rhs)로 둔다.
  5. PutValue(lhs, value)를 수행한다.
  6. keyResult를 ? ForIn/OfHeadEvaluation(« », Expression, enumerate)로 둔다.
  7. ForIn/OfBodyEvaluation(BindingIdentifier, Statement, keyResult, enumerate, var-binding, labelSet)를 반환한다.

B.3.6 [[IsHTMLDDA]] 내부 슬롯

[[IsHTMLDDA]] internal slot은 host-defined 객체에 존재할 수 있다. [[IsHTMLDDA]] 내부 슬롯을 가진 객체는 ToBooleanIsLooselyEqual 추상 연산에서, 그리고 typeof 연산자의 operand로 사용될 때 undefined처럼 동작한다.

Note

[[IsHTMLDDA]] 내부 슬롯을 가진 객체는 이 명세에 의해 생성되지 않는다. 그러나 웹 브라우저의 document.all 객체는 웹 호환성을 위해 존재하는 이 슬롯을 가진 host-defined exotic object이다. 이 종류의 객체에 대한 다른 알려진 예는 없으며 구현은 document.all을 제외하고 이를 만들어서는 안 된다.

이 기능은 다음 지점에서 특별한 의미론을 포함한다:

B.3.7 HostMakeJobCallback의 non-default 동작

HostMakeJobCallback 추상 연산은 웹 브라우저인 host가 non-default 동작을 지정할 수 있게 한다.

B.3.8 HostEnsureCanAddPrivateElement의 non-default 동작

HostEnsureCanAddPrivateElement 추상 연산은 웹 브라우저인 host가 non-default 동작을 지정할 수 있게 한다.

B.3.9 Function Call Assignment Target에 대한 Runtime Error

function call(13.3.6)이 non-strict 코드에서 assignment target으로 사용될 때, early error를 생성하는 대신 assignment 평가 중 ReferenceError 예외가 던져진다.

Note

assignment target이 AssignmentExpressionLeftHandSideExpression이면, assignment operator는 = 또는 AssignmentOperator여야 한다; 특히 여기의 허용은 logical assignment operator(??=, &&=, ||=)에는 적용되지 않는다.

CallExpression : CoverCallExpressionAndAsyncArrowHead CallExpression : CallExpression Arguments 에 대한 AssignmentTargetType의 단계 1를 참조하라.

Annex C (informative) ECMAScript의 엄격 모드

엄격 모드의 제한 및 예외

Annex D (informative) Host Layering Point

host의 정의는 4.2를 참조하라.

D.1 Host Hook

HostCallJobCallback(...)

HostEnqueueFinalizationRegistryCleanupJob(...)

HostEnqueueGenericJob(...)

HostEnqueuePromiseJob(...)

HostEnqueueTimeoutJob(...)

HostEnsureCanCompileStrings(...)

HostFinalizeImportMeta(...)

HostGetImportMetaProperties(...)

HostGrowSharedArrayBuffer(...)

HostHasSourceTextAvailable(...)

HostLoadImportedModule(...)

HostGetSupportedImportAttributes(...)

HostMakeJobCallback(...)

HostPromiseRejectionTracker(...)

HostResizeArrayBuffer(...)

InitializeHostDefinedRealm(...)

D.2 Host-defined 필드

Realm Record[[HostDefined]]: Table 19를 참조하라.

Script Record[[HostDefined]]: Table 34를 참조하라.

Module Record[[HostDefined]]: Table 38를 참조하라.

JobCallback Record[[HostDefined]]: Table 23를 참조하라.

Candidate Execution의 [[HostSynchronizesWith]]: Table 97를 참조하라.

[[IsHTMLDDA]]: B.3.6를 참조하라.

D.3 Host-defined 객체

전역 객체: 19 절을 참조하라.

D.4 Job 실행

Job Abstract Closure 호출 전의 준비 단계와 호출 후의 정리 단계. 9.5를 참조하라.

D.5 Exotic Object의 내부 메서드

이 명세 안에 지정되지 않은 모든 exotic object에 대한 Table 4의 essential internal method 중 임의의 것.

D.6 Built-in 객체와 메서드

17.1에서 제한된 경우를 제외하고, 이 명세 안에 정의되지 않은 모든 built-in 객체와 메서드.

Annex E (informative) 호환성 영향 가능성이 있는 ECMAScript 2015의 수정 및 명확화

9.1.1.4.14-9.1.1.4.17 Edition 5 및 5.1은 새로운 global declaration에 대응하는 global object 프로퍼티가 이미 존재하는지 판단하기 위해 property existence test를 사용했다. ECMAScript 2015는 own property existence test를 사용한다. 이는 웹 브라우저에서 가장 일반적으로 구현되어 온 것과 일치한다.

10.4.2.1: 5th Edition은 현재 array length의 캡처를 array index 또는 새 length 값의 integer conversion 이전으로 이동했다. 그러나 conversion 과정이 array length를 변경하는 side-effect를 가지면 캡처된 length 값은 invalid가 될 수 있었다. ECMAScript 2015는 그러한 side-effect의 가능한 발생 이후에 현재 array length가 캡처되어야 한다고 지정한다.

21.4.1.31: 이전 edition은 TimeClip 추상 연산이 0 time value의 표현으로 +0𝔽 또는 -0𝔽 중 하나를 반환하는 것을 허용했다. ECMAScript 2015는 +0𝔽가 항상 반환된다고 지정한다. 이는 ECMAScript 2015에서 Date의 time value가 관찰 가능하게 -0𝔽가 결코 아니며 time value를 반환하는 메서드도 결코 -0𝔽를 반환하지 않는다는 뜻이다.

21.4.1.32: UTC offset 표현이 없으면 local time zone이 사용된다. Edition 5.1은 누락된 time zone이 "z"로 해석되어야 한다고 잘못 명시했다.

21.4.4.36: 연도를 21.4.1.32에 지정된 Date Time String Format을 사용하여 표현할 수 없으면 RangeError 예외가 던져진다. 이전 edition은 그 경우의 동작을 지정하지 않았다.

21.4.4.41: 이전 edition은 time value가 NaN일 때 Date.prototype.toString이 반환하는 값을 지정하지 않았다. ECMAScript 2015는 결과를 String 값 "Invalid Date"로 지정한다.

22.2.4.1, 22.2.6.13.1: RegExp instance의 "source" 프로퍼티 값 안의 모든 LineTerminator code point는 escape sequence를 사용하여 표현되어야 한다. Edition 5.1은 /만 escape할 것을 요구했다.

22.2.6.8, 22.2.6.11: 이전 edition에서 String.prototype.matchString.prototype.replace의 명세는 pattern 인자가 global flag가 설정된 RegExp 값인 경우에 대해 올바르지 않았다. 이전 명세는 pattern을 match하려는 각 시도마다 lastIndex가 변경되지 않으면 1만큼 증가해야 한다고 명시했다. 올바른 동작은 pattern이 empty String과 match된 경우에만 lastIndex가 1만큼 증가해야 한다는 것이다.

23.1.3.30: 이전 edition은 Array.prototype.sort에서 comparator가 반환한 NaN 값이 어떻게 해석되는지 지정하지 않았다. ECMAScript 2015는 그러한 값이 comparator에서 +0𝔽가 반환된 것처럼 취급된다고 지정한다. ECMAScript 2015는 또한 comparator가 반환한 결과에 ToNumber가 적용된다고 지정한다. 이전 edition에서는 Number 값이 아닌 comparator 결과의 효과가 implementation-defined였다. 실제로 구현은 ToNumber를 호출한다.

Annex F (informative) 이전 Edition과의 비호환성을 도입하는 추가 및 변경

6.2.5: ECMAScript 2015에서 Function call은 Reference Record를 반환할 수 없다.

7.1.4.1: ECMAScript 2015에서 String 값에 적용되는 ToNumber는 이제 BinaryIntegerLiteralOctalIntegerLiteral numeric string을 인식하고 변환한다. 이전 edition에서는 그러한 string이 NaN으로 변환되었다.

9.3: ECMAScript 2018에서 Template object는 이전 edition에서처럼 Realm 안의 해당 template literal 또는 tagged template의 모든 occurrence 전체가 아니라 Parse Node(source location)에 기반하여 canonicalize된다.

12.2: ECMAScript 2016에서는 Unicode 8.0.0 이상이 요구되며, 이는 Unicode 5.1을 요구했던 ECMAScript 2015와 다르다. 특히 이로 인해 U+180E MONGOLIAN VOWEL SEPARATOR가 ECMAScript 2015에서는 Space_Separator(Zs) category에 있어 whitespace로 취급되었지만, Unicode 6.3.0부터 Format(Cf) category로 이동했다. 이는 whitespace-sensitive 메서드가 다르게 동작하게 한다. 예를 들어 "\u180E".trim().length는 이전 edition에서는 0이었지만 ECMAScript 2016 및 이후에서는 1이다. 추가로, ECMAScript 2017은 항상 최신 버전의 Unicode Standard를 사용하도록 요구했다.

12.7: ECMAScript 2015에서 IdentifierName의 valid code point는 Unicode 프로퍼티 “ID_Start” 및 “ID_Continue”의 관점에서 지정된다. 이전 edition에서는 valid IdentifierName 또는 Identifier code point가 여러 Unicode code point category를 열거하여 지정되었다.

12.10.1: ECMAScript 2015에서 Automatic Semicolon Insertion은 semicolon이 누락된 경우 do-while statement의 끝에 semicolon을 추가한다. 이 변경은 명세를 대부분의 기존 구현의 실제 동작과 일치시킨다.

13.2.5.1: ECMAScript 2015에서 Object Initializer 안에 duplicate property name이 있어도 더 이상 early error가 아니다.

13.15.1: ECMAScript 2015에서 FunctionExpression의 function name과 같은 immutable binding에 대한 assignment를 포함하는 strict mode code는 early error를 생성하지 않는다. 대신 runtime error를 생성한다.

14.2: ECMAScript 2015에서 token let으로 시작하고 그 뒤에 input element LineTerminator, 그 다음 Identifier가 오는 StatementListLexicalDeclaration의 시작이다. 이전 edition에서는 automatic semicolon insertion이 항상 Identifier input element 앞에 semicolon을 삽입했다.

14.5: ECMAScript 2015에서 token let으로 시작하고 그 뒤에 token [가 오는 StatementListItemLexicalDeclaration의 시작이다. 이전 edition에서 그러한 sequence는 ExpressionStatement의 시작이었다.

14.6.2: ECMAScript 2015에서 IfStatement의 normal result는 결코 값 empty가 아니다. Statement 부분이 평가되지 않거나 평가된 Statement 부분이 empty를 포함하는 normal completion을 생성하면, IfStatement의 결과는 undefined이다.

14.7: ECMAScript 2015에서 for statement의 ( token 바로 뒤에 token sequence let [가 오면 letLexicalDeclaration의 시작으로 취급된다. 이전 edition에서 그러한 token sequence는 Expression의 시작이었다.

14.7: ECMAScript 2015에서 for-in statement의 ( token 바로 뒤에 token sequence let [가 오면 letForDeclaration의 시작으로 취급된다. 이전 edition에서 그러한 token sequence는 LeftHandSideExpression의 시작이었다.

14.7: ECMAScript 2015 이전에는 in keyword 앞에 오는 VariableDeclaration의 일부로 initialization expression이 나타날 수 있었다. ECMAScript 2015에서는 같은 위치의 ForBinding이 그러한 initializer의 occurrence를 허용하지 않는다. ECMAScript 2017에서는 그러한 initializer가 non-strict code에서만 허용된다.

14.7: ECMAScript 2015에서 IterationStatement를 평가한 결과는 [[Value]]emptynormal completion이 결코 아니다. IterationStatementStatement 부분이 평가되지 않거나 Statement 부분의 최종 평가가 [[Value]]emptynormal completion을 생성하면, IterationStatement 평가 결과는 [[Value]]undefinednormal completion이다.

14.11.2: ECMAScript 2015에서 WithStatement를 평가한 결과는 [[Value]]emptynormal completion이 결코 아니다. WithStatementStatement 부분 평가가 [[Value]]emptynormal completion을 생성하면, WithStatement 평가 결과는 [[Value]]undefinednormal completion이다.

14.12.4: ECMAScript 2015에서 SwitchStatement를 평가한 결과는 [[Value]]emptynormal completion이 결코 아니다. SwitchStatementCaseBlock 부분 평가가 [[Value]]emptynormal completion을 생성하면, SwitchStatement 평가 결과는 [[Value]]undefinednormal completion이다.

14.15: ECMAScript 2015에서 Catch clause가 Catch clause parameter로 나타나는 같은 Identifier에 대한 var declaration을 포함하는 것은 early error이다. 이전 edition에서 그러한 variable declaration은 둘러싸는 variable environment 안에 instantiate되었지만 declaration의 Initializer 값은 Catch parameter에 할당되었다.

14.15, 19.2.1.3: ECMAScript 2015에서 Catch clause가 eval code에 Catch clause parameter로 나타나는 같은 Identifier를 bind하는 var 또는 FunctionDeclaration declaration을 포함하는 non-strict direct eval을 평가하면 runtime SyntaxError가 던져진다.

14.15.3: ECMAScript 2015에서 TryStatement의 결과는 결코 값 empty가 아니다. TryStatementBlock 부분이 empty를 포함하는 normal completion으로 평가되면, TryStatement의 결과는 undefined이다. TryStatementBlock 부분이 throw completion으로 평가되고, 그 Catch 부분이 empty를 포함하는 normal completion으로 평가되면, Finally clause가 없거나 그 Finally clause가 empty normal completion으로 평가되는 경우 TryStatement의 결과는 undefined이다.

15.4.5 ECMAScript 2015에서 ObjectLiteral 안의 accessor property[[Get]] 또는 [[Set]] attribute 값으로 생성되는 function objectconstructor function이 아니며 "prototype" own property를 가지지 않는다. 이전 edition에서는 이들이 constructor였고 "prototype" property를 가졌다.

20.1.2.6: ECMAScript 2015에서 Object.freeze의 인자가 object가 아니면 own property가 없는 non-extensible ordinary object였던 것처럼 취급된다. 이전 edition에서는 non-object 인자가 항상 TypeError를 던지게 했다.

20.1.2.8: ECMAScript 2015에서 Object.getOwnPropertyDescriptor의 인자가 object가 아니면 ToObject를 사용하여 인자를 강제 변환하려는 시도가 이루어진다. 강제 변환이 성공하면 그 결과가 원래 인자 값 대신 사용된다. 이전 edition에서는 non-object 인자가 항상 TypeError를 던지게 했다.

20.1.2.10: ECMAScript 2015에서 Object.getOwnPropertyNames의 인자가 object가 아니면 ToObject를 사용하여 인자를 강제 변환하려는 시도가 이루어진다. 강제 변환이 성공하면 그 결과가 원래 인자 값 대신 사용된다. 이전 edition에서는 non-object 인자가 항상 TypeError를 던지게 했다.

20.1.2.12: ECMAScript 2015에서 Object.getPrototypeOf의 인자가 object가 아니면 ToObject를 사용하여 인자를 강제 변환하려는 시도가 이루어진다. 강제 변환이 성공하면 그 결과가 원래 인자 값 대신 사용된다. 이전 edition에서는 non-object 인자가 항상 TypeError를 던지게 했다.

20.1.2.16: ECMAScript 2015에서 Object.isExtensible의 인자가 object가 아니면 own property가 없는 non-extensible ordinary object였던 것처럼 취급된다. 이전 edition에서는 non-object 인자가 항상 TypeError를 던지게 했다.

20.1.2.17: ECMAScript 2015에서 Object.isFrozen의 인자가 object가 아니면 own property가 없는 non-extensible ordinary object였던 것처럼 취급된다. 이전 edition에서는 non-object 인자가 항상 TypeError를 던지게 했다.

20.1.2.18: ECMAScript 2015에서 Object.isSealed의 인자가 object가 아니면 own property가 없는 non-extensible ordinary object였던 것처럼 취급된다. 이전 edition에서는 non-object 인자가 항상 TypeError를 던지게 했다.

20.1.2.19: ECMAScript 2015에서 Object.keys의 인자가 object가 아니면 ToObject를 사용하여 인자를 강제 변환하려는 시도가 이루어진다. 강제 변환이 성공하면 그 결과가 원래 인자 값 대신 사용된다. 이전 edition에서는 non-object 인자가 항상 TypeError를 던지게 했다.

20.1.2.20: ECMAScript 2015에서 Object.preventExtensions의 인자가 object가 아니면 own property가 없는 non-extensible ordinary object였던 것처럼 취급된다. 이전 edition에서는 non-object 인자가 항상 TypeError를 던지게 했다.

20.1.2.22: ECMAScript 2015에서 Object.seal의 인자가 object가 아니면 own property가 없는 non-extensible ordinary object였던 것처럼 취급된다. 이전 edition에서는 non-object 인자가 항상 TypeError를 던지게 했다.

20.2.3.2: ECMAScript 2015에서 bound function의 [[Prototype]] 내부 슬롯은 target function의 [[GetPrototypeOf]] 값으로 설정된다. 이전 edition에서는 [[Prototype]]이 항상 %Function.prototype%로 설정되었다.

20.2.4.1: ECMAScript 2015에서 function instance의 "length" property는 configurable이다. 이전 edition에서는 non-configurable이었다.

20.5.6.2: ECMAScript 2015에서 NativeError constructor[[Prototype]] 내부 슬롯은 Error constructor이다. 이전 edition에서는 Function prototype object였다.

21.4.4 ECMAScript 2015에서 Date prototype object는 Date instance가 아니다. 이전 edition에서는 TimeValue가 NaN인 Date instance였다.

22.1.3.12 ECMAScript 2015에서 String.prototype.localeCompare 함수는 Unicode Standard에 따라 canonically equivalent인 String을 동일한 것으로 취급해야 한다. 이전 edition에서 구현은 canonical equivalence를 무시하고 대신 bit-wise comparison을 사용할 수 있었다.

22.1.3.2822.1.3.30 ECMAScript 2015에서 lowercase/uppercase 변환 처리는 code point에 대해 작동한다. 이전 edition에서 그러한 변환 처리는 개별 code unit에만 적용되었다. 영향을 받는 유일한 code point는 Unicode의 Deseret block에 있는 것들이다.

22.1.3.32 ECMAScript 2015에서 String.prototype.trim 메서드는 Unicode BMP 밖에 존재할 수 있는 white space code point를 인식하도록 정의된다. 그러나 Unicode 7 기준으로 그러한 code point는 정의되어 있지 않다. 이전 edition에서는 그러한 code point가 white space로 인식되지 않았을 것이다.

22.2.4.1 ECMAScript 2015에서 pattern 인자가 RegExp instance이고 flags 인자가 undefined가 아니면, pattern과 같지만 pattern의 flag가 인자 flags로 대체된 새 RegExp instance가 생성된다. 이전 edition에서는 pattern이 RegExp instance이고 flagsundefined가 아니면 TypeError 예외가 던져졌다.

22.2.6 ECMAScript 2015에서 RegExp prototype object는 RegExp instance가 아니다. 이전 edition에서는 pattern이 empty String인 RegExp instance였다.

22.2.6 ECMAScript 2015에서 "source", "global", "ignoreCase", 및 "multiline"은 RegExp prototype object에 정의된 accessor property이다. 이전 edition에서는 RegExp instance에 정의된 data property였다.

25.4.15: ECMAScript 2019에서 Atomics.wakeAtomics.wait와의 혼동을 방지하기 위해 Atomics.notify로 이름이 변경되었다.

27.1.5.4, 27.6.3.6: ECMAScript 2019에서 await에 의해 enqueue되는 Job의 수가 줄어들었고, 이는 then() 호출과 await expression 사이의 resolution order에 관찰 가능한 차이를 만들 수 있었다.

참고 문헌

  1. IEEE 754-2019: IEEE Standard for Floating-Point Arithmetic. Institute of Electrical and Electronic Engineers, New York (2019) Note

    ECMA-262 명세에 영향을 주는 IEEE 754-2008과 IEEE 754-2019 사이의 normative change는 없다.

  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이라고 하는 plaintext source format으로 작성된다. Ecmarkup은 HTML 및 Markdown dialect로, plaintext로 Ecma 명세를 작성하고 이 문서의 편집 관례를 따르는 full-featured HTML rendering으로 명세를 처리하기 위한 framework와 toolset을 제공한다. Ecmarkup은 구문을 정의하기 위한 Grammarkdown과 algorithm step을 작성하기 위한 Ecmarkdown을 포함한 여러 다른 format과 technology를 기반으로 하고 통합한다. 이 명세의 PDF rendering은 CSS Paged Media specification을 활용하는 print stylesheet를 사용하여 생성되며 PrinceXML을 사용하여 변환된다.

이 명세의 이전 edition은 Word를 사용하여 작성되었다. 이 edition의 기반이 된 Ecmarkup source text는 ECMAScript 2015 Word 문서를 automated conversion tool을 사용하여 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.