15 ECMAScript 语言:函数与类 (ECMAScript Language: Functions and Classes)

Note

多种 ECMAScript 语言元素会创建 ECMAScript 函数对象10.2)。此类函数的求值从其 [[Call]] 内部方法的执行开始(10.2.1)。

15.1 参数列表 (Parameter Lists)

语法 (Syntax)

UniqueFormalParameters[Yield, Await] : FormalParameters[?Yield, ?Await] FormalParameters[Yield, Await] : [empty] FunctionRestParameter[?Yield, ?Await] FormalParameterList[?Yield, ?Await] FormalParameterList[?Yield, ?Await] , FormalParameterList[?Yield, ?Await] , FunctionRestParameter[?Yield, ?Await] FormalParameterList[Yield, Await] : FormalParameter[?Yield, ?Await] FormalParameterList[?Yield, ?Await] , FormalParameter[?Yield, ?Await] FunctionRestParameter[Yield, Await] : BindingRestElement[?Yield, ?Await] FormalParameter[Yield, Await] : BindingElement[?Yield, ?Await]

15.1.1 静态语义:早期错误 (Static Semantics: Early Errors)

UniqueFormalParameters : FormalParameters
  • 如果 FormalParameters 的 BoundNames 包含任意重复元素,则为语法错误。
FormalParameters : FormalParameterList
  • 如果 FormalParameterList 的 IsSimpleParameterList 为 false 且其 BoundNames 含有任意重复元素,则为语法错误。
Note

同一个 BindingIdentifier 在同一个 FormalParameterList 中出现多次只在函数具有简单参数列表并且不是在严格模式代码中定义时才被允许。

15.1.2 静态语义:ContainsExpression

The syntax-directed operation 静态语义:ContainsExpression takes no arguments and returns 一个 Boolean. It is defined piecewise over the following productions:

ObjectBindingPattern : { } { BindingRestProperty }
  1. 返回 false
ObjectBindingPattern : { BindingPropertyList , BindingRestProperty }
  1. 返回 ContainsExpression of BindingPropertyList
ArrayBindingPattern : [ Elisionopt ]
  1. 返回 false
ArrayBindingPattern : [ Elisionopt BindingRestElement ]
  1. 返回 ContainsExpression of BindingRestElement
ArrayBindingPattern : [ BindingElementList , Elisionopt ]
  1. 返回 ContainsExpression of BindingElementList
ArrayBindingPattern : [ BindingElementList , Elisionopt BindingRestElement ]
  1. has 为 ContainsExpression of BindingElementList
  2. 如果 hastrue,返回 true
  3. 返回 ContainsExpression of BindingRestElement
BindingPropertyList : BindingPropertyList , BindingProperty
  1. has 为 ContainsExpression of BindingPropertyList
  2. 如果 hastrue,返回 true
  3. 返回 ContainsExpression of BindingProperty
BindingElementList : BindingElementList , BindingElisionElement
  1. has 为 ContainsExpression of BindingElementList
  2. 如果 hastrue,返回 true
  3. 返回 ContainsExpression of BindingElisionElement
BindingElisionElement : Elisionopt BindingElement
  1. 返回 ContainsExpression of BindingElement
BindingProperty : PropertyName : BindingElement
  1. has 为 IsComputedPropertyKey of PropertyName
  2. 如果 hastrue,返回 true
  3. 返回 ContainsExpression of BindingElement
BindingElement : BindingPattern Initializer
  1. 返回 true
SingleNameBinding : BindingIdentifier
  1. 返回 false
SingleNameBinding : BindingIdentifier Initializer
  1. 返回 true
BindingRestElement : ... BindingIdentifier
  1. 返回 false
BindingRestElement : ... BindingPattern
  1. 返回 ContainsExpression of BindingPattern
FormalParameters : [empty]
  1. 返回 false
FormalParameters : FormalParameterList , FunctionRestParameter
  1. 如果 ContainsExpression of FormalParameterListtrue,返回 true
  2. 返回 ContainsExpression of FunctionRestParameter
FormalParameterList : FormalParameterList , FormalParameter
  1. 如果 ContainsExpression of FormalParameterListtrue,返回 true
  2. 返回 ContainsExpression of FormalParameter
ArrowParameters : BindingIdentifier
  1. 返回 false
ArrowParameters : CoverParenthesizedExpressionAndArrowParameterList
  1. formals 为由 CoverParenthesizedExpressionAndArrowParameterList 覆盖ArrowFormalParameters
  2. 返回 ContainsExpression of formals
AsyncArrowBindingIdentifier : BindingIdentifier
  1. 返回 false

15.1.3 静态语义:IsSimpleParameterList

The syntax-directed operation 静态语义:IsSimpleParameterList takes no arguments and returns 一个 Boolean. It is defined piecewise over the following productions:

BindingElement : BindingPattern
  1. 返回 false
BindingElement : BindingPattern Initializer
  1. 返回 false
SingleNameBinding : BindingIdentifier
  1. 返回 true
SingleNameBinding : BindingIdentifier Initializer
  1. 返回 false
FormalParameters : [empty]
  1. 返回 true
FormalParameters : FunctionRestParameter
  1. 返回 false
FormalParameters : FormalParameterList , FunctionRestParameter
  1. 返回 false
FormalParameterList : FormalParameterList , FormalParameter
  1. 如果 IsSimpleParameterList of FormalParameterListfalse,返回 false
  2. 返回 IsSimpleParameterList of FormalParameter
FormalParameter : BindingElement
  1. 返回 IsSimpleParameterList of BindingElement
ArrowParameters : BindingIdentifier
  1. 返回 true
ArrowParameters : CoverParenthesizedExpressionAndArrowParameterList
  1. formals 为由 CoverParenthesizedExpressionAndArrowParameterList 覆盖ArrowFormalParameters
  2. 返回 IsSimpleParameterList of formals
AsyncArrowBindingIdentifier : BindingIdentifier
  1. 返回 true
CoverCallExpressionAndAsyncArrowHead : MemberExpression Arguments
  1. head 为由 CoverCallExpressionAndAsyncArrowHead 覆盖AsyncArrowHead
  2. 返回 IsSimpleParameterList of head

15.1.4 静态语义:HasInitializer

The syntax-directed operation 静态语义:HasInitializer takes no arguments and returns 一个 Boolean. It is defined piecewise over the following productions:

BindingElement : BindingPattern
  1. 返回 false
BindingElement : BindingPattern Initializer
  1. 返回 true
SingleNameBinding : BindingIdentifier
  1. 返回 false
SingleNameBinding : BindingIdentifier Initializer
  1. 返回 true
FormalParameterList : FormalParameterList , FormalParameter
  1. 如果 HasInitializer of FormalParameterListtrue,返回 true
  2. 返回 HasInitializer of FormalParameter

15.1.5 静态语义: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. 返回 FormalParameterList 的 ExpectedArgumentCount。
Note

FormalParameterList 的 ExpectedArgumentCount 是位于剩余参数或第一个带 Initializer 的 FormalParameter 左侧的 FormalParameters 数目。在第一个带初始值的参数之后仍可出现不带初始值的参数,但这些参数被视为可选,其默认值为 undefined

FormalParameterList : FormalParameter
  1. 如果 HasInitializer of FormalParametertrue,返回 0。
  2. 返回 1。
FormalParameterList : FormalParameterList , FormalParameter
  1. countFormalParameterList 的 ExpectedArgumentCount。
  2. 如果 HasInitializer of FormalParameterListtrue 或 HasInitializer of FormalParametertrue,返回 count
  3. 返回 count + 1。
ArrowParameters : BindingIdentifier
  1. 返回 1。
ArrowParameters : CoverParenthesizedExpressionAndArrowParameterList
  1. formals 为由 CoverParenthesizedExpressionAndArrowParameterList 覆盖ArrowFormalParameters
  2. 返回 formals 的 ExpectedArgumentCount。
PropertySetParameterList : FormalParameter
  1. 如果 HasInitializer of FormalParametertrue,返回 0。
  2. 返回 1。
AsyncArrowBindingIdentifier : BindingIdentifier
  1. 返回 1。

15.2 函数定义 (Function Definitions)

语法 (Syntax)

FunctionDeclaration[Yield, Await, Default] : function BindingIdentifier[?Yield, ?Await] ( FormalParameters[~Yield, ~Await] ) { FunctionBody[~Yield, ~Await] } [+Default] function ( FormalParameters[~Yield, ~Await] ) { FunctionBody[~Yield, ~Await] } FunctionExpression : function BindingIdentifier[~Yield, ~Await]opt ( FormalParameters[~Yield, ~Await] ) { FunctionBody[~Yield, ~Await] } FunctionBody[Yield, Await] : FunctionStatementList[?Yield, ?Await] FunctionStatementList[Yield, Await] : StatementList[?Yield, ?Await, +Return]opt

15.2.1 静态语义:早期错误 (Static Semantics: Early Errors)

FunctionDeclaration : function BindingIdentifier ( FormalParameters ) { FunctionBody } function ( FormalParameters ) { FunctionBody } FunctionExpression : function BindingIdentifieropt ( FormalParameters ) { FunctionBody } Note

FunctionBody 的 LexicallyDeclaredNames 不包含通过 var 或 function 声明绑定的标识符。

FunctionBody : FunctionStatementList

15.2.2 静态语义:FunctionBodyContainsUseStrict

The syntax-directed operation 静态语义:FunctionBodyContainsUseStrict takes no arguments and returns Boolean. It is defined piecewise over the following productions:

FunctionBody : FunctionStatementList
  1. FunctionBody指令序言 (Directive Prologue) 含有 Use Strict 指令,返回 true;否则返回 false

15.2.3 运行时语义:EvaluateFunctionBody

The syntax-directed operation 运行时语义:EvaluateFunctionBody takes arguments functionObject (一个 ECMAScript 函数对象) and argumentsList (ECMAScript 语言值的列表) and returns 一个 return completion 或 throw completion. It is defined piecewise over the following productions:

FunctionBody : FunctionStatementList
  1. 执行 ? FunctionDeclarationInstantiation(functionObject, argumentsList)。
  2. 执行 ? Evaluation of FunctionStatementList
  3. 注:若上一步产生正常完成,则求值已到达 FunctionStatementList 末尾。
  4. 返回 ReturnCompletion(undefined)。

15.2.4 运行时语义:InstantiateOrdinaryFunctionObject

The syntax-directed operation 运行时语义:InstantiateOrdinaryFunctionObject takes arguments env (一个 Environment Record) and privateEnv (一个 PrivateEnvironment Recordnull) and returns 一个 ECMAScript 函数对象. It is defined piecewise over the following productions:

FunctionDeclaration : function BindingIdentifier ( FormalParameters ) { FunctionBody }
  1. nameBindingIdentifier 的 StringValue。
  2. sourceTextFunctionDeclaration 匹配的源文本。
  3. FOrdinaryFunctionCreate(%Function.prototype%, sourceText, FormalParameters, FunctionBody, non-lexical-this, env, privateEnv)。
  4. 执行 SetFunctionName(F, name)。
  5. 执行 MakeConstructor(F)。
  6. 返回 F
FunctionDeclaration : function ( FormalParameters ) { FunctionBody }
  1. sourceTextFunctionDeclaration 匹配的源文本。
  2. FOrdinaryFunctionCreate(%Function.prototype%, sourceText, FormalParameters, FunctionBody, non-lexical-this, env, privateEnv)。
  3. 执行 SetFunctionName(F, "default")。
  4. 执行 MakeConstructor(F)。
  5. 返回 F
Note

匿名 FunctionDeclaration 只能作为 export default 声明的一部分,其函数代码因此总是严格模式代码。

15.2.5 运行时语义:InstantiateOrdinaryFunctionExpression : 一个 ECMAScript 函数对象

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

FunctionExpression : function ( FormalParameters ) { FunctionBody }
  1. name 不存在,设 name""
  2. env 为当前执行上下文的 LexicalEnvironment。
  3. privateEnv 为当前执行上下文的 PrivateEnvironment。
  4. sourceTextFunctionExpression 匹配的源文本。
  5. closureOrdinaryFunctionCreate(%Function.prototype%, sourceText, FormalParameters, FunctionBody, non-lexical-this, env, privateEnv)。
  6. 执行 SetFunctionName(closure, name)。
  7. 执行 MakeConstructor(closure)。
  8. 返回 closure
FunctionExpression : function BindingIdentifier ( FormalParameters ) { FunctionBody }
  1. 断言:name 不存在。
  2. nameBindingIdentifier 的 StringValue。
  3. outerEnv 为当前执行上下文的 LexicalEnvironment。
  4. funcEnvNewDeclarativeEnvironment(outerEnv)。
  5. 执行 ! funcEnv.CreateImmutableBinding(name, false)。
  6. privateEnv 为当前执行上下文的 PrivateEnvironment。
  7. sourceTextFunctionExpression 匹配的源文本。
  8. closureOrdinaryFunctionCreate(%Function.prototype%, sourceText, FormalParameters, FunctionBody, non-lexical-this, funcEnv, privateEnv)。
  9. 执行 SetFunctionName(closure, name)。
  10. 执行 MakeConstructor(closure)。
  11. 执行 ! funcEnv.InitializeBinding(name, closure)。
  12. 返回 closure
Note

FunctionExpression 中的 BindingIdentifier 可在其 FunctionBody 内部引用以实现递归调用。但与 FunctionDeclaration 不同,该标识符不能从包围 FunctionExpression 的外部作用域引用,也不会影响外部作用域。

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. 返回 InstantiateOrdinaryFunctionExpression of FunctionExpression
Note 2

每个通过 FunctionDeclarationFunctionExpression 定义的函数会自动创建一个 "prototype" 属性,以便该函数可作为构造函数使用。

FunctionStatementList : [empty]
  1. 返回 undefined

15.3 箭头函数定义 (Arrow Function Definitions)

语法 (Syntax)

ArrowFunction[In, Yield, Await] : ArrowParameters[?Yield, ?Await] [no LineTerminator here] => ConciseBody[?In] ArrowParameters[Yield, Await] : BindingIdentifier[?Yield, ?Await] CoverParenthesizedExpressionAndArrowParameterList[?Yield, ?Await] ConciseBody[In] : [lookahead ≠ {] ExpressionBody[?In, ~Await] { FunctionBody[~Yield, ~Await] } ExpressionBody[In, Await] : AssignmentExpression[?In, ~Yield, ?Await]

补充语法 (Supplemental Syntax)

当处理产生式实例:
ArrowParameters[Yield, Await] : CoverParenthesizedExpressionAndArrowParameterList[?Yield, ?Await]
时,使用以下语法细化对 CoverParenthesizedExpressionAndArrowParameterList 的解释:

ArrowFormalParameters[Yield, Await] : ( UniqueFormalParameters[?Yield, ?Await] )

15.3.1 静态语义:早期错误 (Static Semantics: Early Errors)

ArrowFunction : ArrowParameters => ConciseBody ArrowParameters : CoverParenthesizedExpressionAndArrowParameterList

15.3.2 静态语义:ConciseBodyContainsUseStrict

The syntax-directed operation 静态语义:ConciseBodyContainsUseStrict takes no arguments and returns Boolean. It is defined piecewise over the following productions:

ConciseBody : ExpressionBody
  1. 返回 false
ConciseBody : { FunctionBody }
  1. 返回 FunctionBodyContainsUseStrict(FunctionBody)。

15.3.3 运行时语义:EvaluateConciseBody

The syntax-directed operation 运行时语义:EvaluateConciseBody takes arguments functionObject (一个 ECMAScript 函数对象) and argumentsList (ECMAScript 语言值的列表) and returns 一个 return completion 或 throw completion. It is defined piecewise over the following productions:

ConciseBody : ExpressionBody
  1. 执行 ? FunctionDeclarationInstantiation(functionObject, argumentsList)。
  2. 返回 ? Evaluation of ExpressionBody

15.3.4 运行时语义:InstantiateArrowFunctionExpression : 一个 ECMAScript 函数对象

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

ArrowFunction : ArrowParameters => ConciseBody
  1. name 不存在,设 name""
  2. env 为当前执行上下文的 LexicalEnvironment。
  3. privateEnv 为当前执行上下文的 PrivateEnvironment。
  4. sourceTextArrowFunction 匹配的源文本。
  5. closureOrdinaryFunctionCreate(%Function.prototype%, sourceText, ArrowParameters, ConciseBody, lexical-this, env, privateEnv)。
  6. 执行 SetFunctionName(closure, name)。
  7. 返回 closure
Note

ArrowFunction 不为 argumentssuperthisnew.target 定义局部绑定;在其内部的此类引用必须解析为词法外层环境中的绑定。尽管 ArrowFunction 可引用 super,但步骤 5 创建的函数对象不会通过 MakeMethod 变成方法;包含 superArrowFunction 始终位于非 ArrowFunction 内,其实现 super 所需状态通过捕获的 env 可用。

15.3.5 运行时语义:求值 (Runtime Semantics: Evaluation)

ArrowFunction : ArrowParameters => ConciseBody
  1. 返回 InstantiateArrowFunctionExpression of ArrowFunction
ExpressionBody : AssignmentExpression
  1. exprRef 为 ? Evaluation of AssignmentExpression
  2. exprValue 为 ? GetValue(exprRef)。
  3. 返回 ReturnCompletion(exprValue)。

15.4 方法定义 (Method Definitions)

语法 (Syntax)

MethodDefinition[Yield, Await] : ClassElementName[?Yield, ?Await] ( UniqueFormalParameters[~Yield, ~Await] ) { FunctionBody[~Yield, ~Await] } GeneratorMethod[?Yield, ?Await] AsyncMethod[?Yield, ?Await] AsyncGeneratorMethod[?Yield, ?Await] get ClassElementName[?Yield, ?Await] ( ) { FunctionBody[~Yield, ~Await] } set ClassElementName[?Yield, ?Await] ( PropertySetParameterList ) { FunctionBody[~Yield, ~Await] } PropertySetParameterList : FormalParameter[~Yield, ~Await]

15.4.1 静态语义:早期错误 (Static Semantics: Early Errors)

MethodDefinition : ClassElementName ( UniqueFormalParameters ) { FunctionBody } MethodDefinition : set ClassElementName ( PropertySetParameterList ) { FunctionBody }

15.4.2 静态语义:HasDirectSuper

The syntax-directed operation 静态语义:HasDirectSuper takes no arguments and returns Boolean. It is defined piecewise over the following productions:

MethodDefinition : ClassElementName ( UniqueFormalParameters ) { FunctionBody }
  1. UniqueFormalParameters Contains SuperCalltrue,返回 true
  2. 返回 FunctionBody Contains SuperCall
MethodDefinition : get ClassElementName ( ) { FunctionBody }
  1. 返回 FunctionBody Contains SuperCall
MethodDefinition : set ClassElementName ( PropertySetParameterList ) { FunctionBody }
  1. PropertySetParameterList Contains SuperCalltrue,返回 true
  2. 返回 FunctionBody Contains SuperCall
GeneratorMethod : * ClassElementName ( UniqueFormalParameters ) { GeneratorBody }
  1. UniqueFormalParameters Contains SuperCalltrue,返回 true
  2. 返回 GeneratorBody Contains SuperCall
AsyncGeneratorMethod : async * ClassElementName ( UniqueFormalParameters ) { AsyncGeneratorBody }
  1. UniqueFormalParameters Contains SuperCalltrue,返回 true
  2. 返回 AsyncGeneratorBody Contains SuperCall
AsyncMethod : async ClassElementName ( UniqueFormalParameters ) { AsyncFunctionBody }
  1. UniqueFormalParameters Contains SuperCalltrue,返回 true
  2. 返回 AsyncFunctionBody Contains SuperCall

15.4.3 静态语义:SpecialMethod

The syntax-directed operation 静态语义:SpecialMethod takes no arguments and returns Boolean. It is defined piecewise over the following productions:

MethodDefinition : ClassElementName ( UniqueFormalParameters ) { FunctionBody }
  1. 返回 false
MethodDefinition : GeneratorMethod AsyncMethod AsyncGeneratorMethod get ClassElementName ( ) { FunctionBody } set ClassElementName ( PropertySetParameterList ) { FunctionBody }
  1. 返回 true

15.4.4 运行时语义:DefineMethod : 正常完成(含 [[Key]][[Closure]] 字段的 Record)或突然完成

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

MethodDefinition : ClassElementName ( UniqueFormalParameters ) { FunctionBody }
  1. propKey 为 ? Evaluation of ClassElementName
  2. env 为当前执行上下文的 LexicalEnvironment。
  3. privateEnv 为当前执行上下文的 PrivateEnvironment。
  4. functionPrototype 存在,令 prototype = functionPrototype;否则令 prototype = %Function.prototype%
  5. sourceTextMethodDefinition 匹配的源文本。
  6. closureOrdinaryFunctionCreate(prototype, sourceText, UniqueFormalParameters, FunctionBody, non-lexical-this, env, privateEnv)。
  7. 执行 MakeMethod(closure, object)。
  8. 返回 Record { [[Key]]: propKey, [[Closure]]: closure }。

15.4.5 运行时语义:MethodDefinitionEvaluation

The syntax-directed operation 运行时语义:MethodDefinitionEvaluation takes arguments object (一个 Object) and enumerable (一个 Boolean) and returns 正常完成(含 PrivateElementunused)或突然完成. It is defined piecewise over the following productions:

MethodDefinition : ClassElementName ( UniqueFormalParameters ) { FunctionBody }
  1. methodDef 为 ? DefineMethod of MethodDefinition,参数 object
  2. 执行 SetFunctionName(methodDef.[[Closure]], methodDef.[[Key]])。
  3. 返回 ? DefineMethodProperty(object, methodDef.[[Key]], methodDef.[[Closure]], enumerable)。
MethodDefinition : get ClassElementName ( ) { FunctionBody }
  1. propKey 为 ? Evaluation of ClassElementName
  2. env 为当前执行上下文的 LexicalEnvironment。
  3. privateEnv 为当前执行上下文的 PrivateEnvironment。
  4. sourceTextMethodDefinition 匹配的源文本。
  5. formalParameterList 为产生式 FormalParameters : [empty] 的一个实例。
  6. closureOrdinaryFunctionCreate(%Function.prototype%, sourceText, formalParameterList, FunctionBody, non-lexical-this, env, privateEnv)。
  7. 执行 MakeMethod(closure, object)。
  8. 执行 SetFunctionName(closure, propKey, "get")。
  9. propKeyPrivate Name,则
    1. 返回 PrivateElement { [[Key]]: propKey, [[Kind]]: accessor, [[Get]]: closure, [[Set]]: undefined }。
  10. 否则,
    1. desc 为 PropertyDescriptor { [[Get]]: closure, [[Enumerable]]: enumerable, [[Configurable]]: true }。
    2. 执行 ? DefinePropertyOrThrow(object, propKey, desc)。
    3. 返回 unused
MethodDefinition : set ClassElementName ( PropertySetParameterList ) { FunctionBody }
  1. propKey 为 ? Evaluation of ClassElementName
  2. env 为当前执行上下文的 LexicalEnvironment。
  3. privateEnv 为当前执行上下文的 PrivateEnvironment。
  4. sourceTextMethodDefinition 匹配的源文本。
  5. closureOrdinaryFunctionCreate(%Function.prototype%, sourceText, PropertySetParameterList, FunctionBody, non-lexical-this, env, privateEnv)。
  6. 执行 MakeMethod(closure, object)。
  7. 执行 SetFunctionName(closure, propKey, "set")。
  8. propKeyPrivate Name,则
    1. 返回 PrivateElement { [[Key]]: propKey, [[Kind]]: accessor, [[Get]]: undefined, [[Set]]: closure }。
  9. 否则,
    1. desc 为 PropertyDescriptor { [[Set]]: closure, [[Enumerable]]: enumerable, [[Configurable]]: true }。
    2. 执行 ? DefinePropertyOrThrow(object, propKey, desc)。
    3. 返回 unused
GeneratorMethod : * ClassElementName ( UniqueFormalParameters ) { GeneratorBody }
  1. propKey 为 ? Evaluation of ClassElementName
  2. env 为当前执行上下文的 LexicalEnvironment。
  3. privateEnv 为当前执行上下文的 PrivateEnvironment。
  4. sourceTextGeneratorMethod 匹配的源文本。
  5. closureOrdinaryFunctionCreate(%GeneratorFunction.prototype%, sourceText, UniqueFormalParameters, GeneratorBody, non-lexical-this, env, privateEnv)。
  6. 执行 MakeMethod(closure, object)。
  7. 执行 SetFunctionName(closure, propKey)。
  8. prototypeOrdinaryObjectCreate(%GeneratorPrototype%)。
  9. 执行 ! DefinePropertyOrThrow(closure, "prototype", PropertyDescriptor { [[Value]]: prototype, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false })。
  10. 返回 ? DefineMethodProperty(object, propKey, closure, enumerable)。
AsyncGeneratorMethod : async * ClassElementName ( UniqueFormalParameters ) { AsyncGeneratorBody }
  1. propKey 为 ? Evaluation of ClassElementName
  2. env 为当前执行上下文的 LexicalEnvironment。
  3. privateEnv 为当前执行上下文的 PrivateEnvironment。
  4. sourceTextAsyncGeneratorMethod 匹配的源文本。
  5. closureOrdinaryFunctionCreate(%AsyncGeneratorFunction.prototype%, sourceText, UniqueFormalParameters, AsyncGeneratorBody, non-lexical-this, env, privateEnv)。
  6. 执行 MakeMethod(closure, object)。
  7. 执行 SetFunctionName(closure, propKey)。
  8. prototypeOrdinaryObjectCreate(%AsyncGeneratorPrototype%)。
  9. 执行 ! DefinePropertyOrThrow(closure, "prototype", PropertyDescriptor { [[Value]]: prototype, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false })。
  10. 返回 ? DefineMethodProperty(object, propKey, closure, enumerable)。
AsyncMethod : async ClassElementName ( UniqueFormalParameters ) { AsyncFunctionBody }
  1. propKey 为 ? Evaluation of ClassElementName
  2. env 为当前执行上下文的 LexicalEnvironment。
  3. privateEnv 为当前执行上下文的 PrivateEnvironment。
  4. sourceTextAsyncMethod 匹配的源文本。
  5. closureOrdinaryFunctionCreate(%AsyncFunction.prototype%, sourceText, UniqueFormalParameters, AsyncFunctionBody, non-lexical-this, env, privateEnv)。
  6. 执行 MakeMethod(closure, object)。
  7. 执行 SetFunctionName(closure, propKey)。
  8. 返回 ? DefineMethodProperty(object, propKey, closure, enumerable)。

15.5 生成器函数定义 (Generator Function Definitions)

语法 (Syntax)

GeneratorDeclaration[Yield, Await, Default] : function * BindingIdentifier[?Yield, ?Await] ( FormalParameters[+Yield, ~Await] ) { GeneratorBody } [+Default] function * ( FormalParameters[+Yield, ~Await] ) { GeneratorBody } GeneratorExpression : function * BindingIdentifier[+Yield, ~Await]opt ( FormalParameters[+Yield, ~Await] ) { GeneratorBody } GeneratorMethod[Yield, Await] : * ClassElementName[?Yield, ?Await] ( UniqueFormalParameters[+Yield, ~Await] ) { GeneratorBody } GeneratorBody : FunctionBody[+Yield, ~Await] YieldExpression[In, Await] : yield yield [no LineTerminator here] AssignmentExpression[?In, +Yield, ?Await] yield [no LineTerminator here] * AssignmentExpression[?In, +Yield, ?Await] Note 1

yield 后紧随的语法上下文需要使用 InputElementRegExpOrTemplateTail 词法目标。

Note 2

YieldExpression 不能用于生成器函数的 FormalParameters 内,因为 FormalParameters 中的表达式会在生成的 Generator 进入可恢复状态之前被求值。

Note 3

与生成器相关的抽象操作定义见 27.5.3

15.5.1 静态语义:早期错误 (Static Semantics: Early Errors)

GeneratorMethod : * ClassElementName ( UniqueFormalParameters ) { GeneratorBody } GeneratorDeclaration : function * BindingIdentifier ( FormalParameters ) { GeneratorBody } function * ( FormalParameters ) { GeneratorBody } GeneratorExpression : function * BindingIdentifieropt ( FormalParameters ) { GeneratorBody }

15.5.2 运行时语义:EvaluateGeneratorBody

The syntax-directed operation 运行时语义:EvaluateGeneratorBody takes arguments functionObject (一个 ECMAScript 函数对象) and argumentsList (ECMAScript 语言值的列表) and returns 一个 throw completion 或 return completion. It is defined piecewise over the following productions:

GeneratorBody : FunctionBody
  1. 执行 ? FunctionDeclarationInstantiation(functionObject, argumentsList)。
  2. G 为 ? OrdinaryCreateFromConstructor(functionObject, "%GeneratorPrototype%", « [[GeneratorState]], [[GeneratorContext]], [[GeneratorBrand]] »)。
  3. G.[[GeneratorBrand]]empty
  4. G.[[GeneratorState]]suspended-start
  5. 执行 GeneratorStart(G, FunctionBody)。
  6. 返回 ReturnCompletion(G)。

15.5.3 运行时语义:InstantiateGeneratorFunctionObject

The syntax-directed operation 运行时语义:InstantiateGeneratorFunctionObject takes arguments env (一个 Environment Record) and privateEnv (一个 PrivateEnvironment Recordnull) and returns 一个 ECMAScript 函数对象. It is defined piecewise over the following productions:

GeneratorDeclaration : function * BindingIdentifier ( FormalParameters ) { GeneratorBody }
  1. nameBindingIdentifier 的 StringValue。
  2. sourceTextGeneratorDeclaration 匹配的源文本。
  3. FOrdinaryFunctionCreate(%GeneratorFunction.prototype%, sourceText, FormalParameters, GeneratorBody, non-lexical-this, env, privateEnv)。
  4. 执行 SetFunctionName(F, name)。
  5. prototypeOrdinaryObjectCreate(%GeneratorPrototype%)。
  6. 执行 ! DefinePropertyOrThrow(F, "prototype", PropertyDescriptor { [[Value]]: prototype, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false })。
  7. 返回 F
GeneratorDeclaration : function * ( FormalParameters ) { GeneratorBody }
  1. sourceTextGeneratorDeclaration 匹配的源文本。
  2. FOrdinaryFunctionCreate(%GeneratorFunction.prototype%, sourceText, FormalParameters, GeneratorBody, non-lexical-this, env, privateEnv)。
  3. 执行 SetFunctionName(F, "default")。
  4. prototypeOrdinaryObjectCreate(%GeneratorPrototype%)。
  5. 执行 ! DefinePropertyOrThrow(F, "prototype", PropertyDescriptor { [[Value]]: prototype, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false })。
  6. 返回 F
Note

匿名 GeneratorDeclaration 只能作为 export default 声明的一部分,因此其函数代码总是严格模式代码。

15.5.4 运行时语义:InstantiateGeneratorFunctionExpression : 一个 ECMAScript 函数对象

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

GeneratorExpression : function * ( FormalParameters ) { GeneratorBody }
  1. name 不存在,设 name""
  2. env 为当前执行上下文的 LexicalEnvironment。
  3. privateEnv 为当前执行上下文的 PrivateEnvironment。
  4. sourceTextGeneratorExpression 匹配的源文本。
  5. closureOrdinaryFunctionCreate(%GeneratorFunction.prototype%, sourceText, FormalParameters, GeneratorBody, non-lexical-this, env, privateEnv)。
  6. 执行 SetFunctionName(closure, name)。
  7. prototypeOrdinaryObjectCreate(%GeneratorPrototype%)。
  8. 执行 ! DefinePropertyOrThrow(closure, "prototype", PropertyDescriptor { [[Value]]: prototype, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false })。
  9. 返回 closure
GeneratorExpression : function * BindingIdentifier ( FormalParameters ) { GeneratorBody }
  1. 断言:name 不存在。
  2. nameBindingIdentifier 的 StringValue。
  3. outerEnv 为当前执行上下文的 LexicalEnvironment。
  4. funcEnvNewDeclarativeEnvironment(outerEnv)。
  5. 执行 ! funcEnv.CreateImmutableBinding(name, false)。
  6. privateEnv 为当前执行上下文的 PrivateEnvironment。
  7. sourceTextGeneratorExpression 匹配的源文本。
  8. closureOrdinaryFunctionCreate(%GeneratorFunction.prototype%, sourceText, FormalParameters, GeneratorBody, non-lexical-this, funcEnv, privateEnv)。
  9. 执行 SetFunctionName(closure, name)。
  10. prototypeOrdinaryObjectCreate(%GeneratorPrototype%)。
  11. 执行 ! DefinePropertyOrThrow(closure, "prototype", PropertyDescriptor { [[Value]]: prototype, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false })。
  12. 执行 ! funcEnv.InitializeBinding(name, closure)。
  13. 返回 closure
Note

GeneratorExpression 中的 BindingIdentifier 可在其 FunctionBody 内被引用以实现生成器代码自递归。但与 GeneratorDeclaration 不同,该 BindingIdentifier 不可从包围 GeneratorExpression 的作用域引用,也不影响该外层作用域。

15.5.5 运行时语义:求值 (Runtime Semantics: Evaluation)

GeneratorExpression : function * BindingIdentifieropt ( FormalParameters ) { GeneratorBody }
  1. 返回 InstantiateGeneratorFunctionExpression of GeneratorExpression
YieldExpression : yield
  1. 返回 ? Yield(undefined)。
YieldExpression : yield AssignmentExpression
  1. exprRef 为 ? Evaluation of AssignmentExpression
  2. value 为 ? GetValue(exprRef)。
  3. 返回 ? Yield(value)。
YieldExpression : yield * AssignmentExpression
  1. generatorKindGetGeneratorKind()。
  2. 断言:generatorKindsyncasync
  3. exprRef 为 ? Evaluation of AssignmentExpression
  4. value 为 ? GetValue(exprRef)。
  5. iteratorRecord 为 ? GetIterator(value, generatorKind)。
  6. iteratoriteratorRecord.[[Iterator]]
  7. receivedNormalCompletion(undefined)。
  8. 重复,
    1. received 为 normal completion,则
      1. innerResult 为 ? Call(iteratorRecord.[[NextMethod]], iteratorRecord.[[Iterator]], « received.[[Value]] »)。
      2. generatorKindasync,设 innerResult 为 ? Await(innerResult)。
      3. innerResult 不是 Object,抛出 TypeError 异常。
      4. done 为 ? IteratorComplete(innerResult)。
      5. donetrue,则
        1. 返回 ? IteratorValue(innerResult)。
      6. generatorKindasync,设 receivedCompletion(AsyncGeneratorYield(? IteratorValue(innerResult)))。
      7. 否则,设 receivedCompletion(GeneratorYield(innerResult))。
    2. 否则若 received 为 throw completion,则
      1. throw 为 ? GetMethod(iterator, "throw")。
      2. throwundefined,则
        1. innerResult 为 ? Call(throw, iterator, « received.[[Value]] »)。
        2. generatorKindasync,设 innerResult 为 ? Await(innerResult)。
        3. 注:内部迭代器 throw 方法抛出的异常会被传播。其正常完成与内部 next 类似处理。
        4. innerResult 不是 Object,抛出 TypeError 异常。
        5. done 为 ? IteratorComplete(innerResult)。
        6. donetrue,则
          1. 返回 ? IteratorValue(innerResult)。
        7. generatorKindasync,设 receivedCompletion(AsyncGeneratorYield(? IteratorValue(innerResult)))。
        8. 否则设 receivedCompletion(GeneratorYield(innerResult))。
      3. 否则,
        1. 注:若 iterator 不具有 throw 方法,则该抛出将终止 yield* 循环。但需先给予 iterator 清理机会。
        2. closeCompletionNormalCompletion(empty)。
        3. generatorKindasync,执行 ? AsyncIteratorClose(iteratorRecord, closeCompletion)。
        4. 否则,执行 ? IteratorClose(iteratorRecord, closeCompletion)。
        5. 注:下一步抛出 TypeError 以指示 yield* 协议违规:iteratorthrow 方法。
        6. 抛出 TypeError 异常。
    3. 否则,
      1. 断言:received 是 return completion。
      2. return 为 ? GetMethod(iterator, "return")。
      3. returnundefined,则
        1. valuereceived.[[Value]]
        2. generatorKindasync,则
          1. value 为 ? Await(value)。
        3. 返回 ReturnCompletion(value)。
      4. innerReturnResult 为 ? Call(return, iterator, « received.[[Value]] »)。
      5. generatorKindasync,设 innerReturnResult 为 ? Await(innerReturnResult)。
      6. innerReturnResult 不是 Object,抛出 TypeError 异常。
      7. done 为 ? IteratorComplete(innerReturnResult)。
      8. donetrue,则
        1. value 为 ? IteratorValue(innerReturnResult)。
        2. 返回 ReturnCompletion(value)。
      9. generatorKindasync,设 receivedCompletion(AsyncGeneratorYield(? IteratorValue(innerReturnResult)))。
      10. 否则设 receivedCompletion(GeneratorYield(innerReturnResult))。

15.6 异步生成器函数定义 (Async Generator Function Definitions)

语法 (Syntax)

AsyncGeneratorDeclaration[Yield, Await, Default] : async [no LineTerminator here] function * BindingIdentifier[?Yield, ?Await] ( FormalParameters[+Yield, +Await] ) { AsyncGeneratorBody } [+Default] async [no LineTerminator here] function * ( FormalParameters[+Yield, +Await] ) { AsyncGeneratorBody } AsyncGeneratorExpression : async [no LineTerminator here] function * BindingIdentifier[+Yield, +Await]opt ( FormalParameters[+Yield, +Await] ) { AsyncGeneratorBody } AsyncGeneratorMethod[Yield, Await] : async [no LineTerminator here] * ClassElementName[?Yield, ?Await] ( UniqueFormalParameters[+Yield, +Await] ) { AsyncGeneratorBody } AsyncGeneratorBody : FunctionBody[+Yield, +Await] Note 1

YieldExpressionAwaitExpression 不能用于异步生成器函数的 FormalParameters 内,因为它们会在 AsyncGenerator 进入可恢复状态前被求值。

Note 2

与 AsyncGenerators 有关的抽象操作27.6.3

15.6.1 静态语义:早期错误 (Static Semantics: Early Errors)

AsyncGeneratorMethod : async * ClassElementName ( UniqueFormalParameters ) { AsyncGeneratorBody } AsyncGeneratorDeclaration : async function * BindingIdentifier ( FormalParameters ) { AsyncGeneratorBody } async function * ( FormalParameters ) { AsyncGeneratorBody } AsyncGeneratorExpression : async function * BindingIdentifieropt ( FormalParameters ) { AsyncGeneratorBody }

15.6.2 运行时语义:EvaluateAsyncGeneratorBody

The syntax-directed operation 运行时语义:EvaluateAsyncGeneratorBody takes arguments functionObject (一个 ECMAScript 函数对象) and argumentsList (ECMAScript 语言值的列表) and returns 一个 throw completion 或 return completion. It is defined piecewise over the following productions:

AsyncGeneratorBody : FunctionBody
  1. 执行 ? FunctionDeclarationInstantiation(functionObject, argumentsList)。
  2. generator 为 ? OrdinaryCreateFromConstructor(functionObject, "%AsyncGeneratorPrototype%", « [[AsyncGeneratorState]], [[AsyncGeneratorContext]], [[AsyncGeneratorQueue]], [[GeneratorBrand]] »)。
  3. generator.[[GeneratorBrand]]empty
  4. generator.[[AsyncGeneratorState]]suspended-start
  5. 执行 AsyncGeneratorStart(generator, FunctionBody)。
  6. 返回 ReturnCompletion(generator)。

15.6.3 运行时语义:InstantiateAsyncGeneratorFunctionObject

The syntax-directed operation 运行时语义:InstantiateAsyncGeneratorFunctionObject takes arguments env (一个 Environment Record) and privateEnv (一个 PrivateEnvironment Recordnull) and returns 一个 ECMAScript 函数对象. It is defined piecewise over the following productions:

AsyncGeneratorDeclaration : async function * BindingIdentifier ( FormalParameters ) { AsyncGeneratorBody }
  1. nameBindingIdentifier 的 StringValue。
  2. sourceTextAsyncGeneratorDeclaration 匹配的源文本。
  3. FOrdinaryFunctionCreate(%AsyncGeneratorFunction.prototype%, sourceText, FormalParameters, AsyncGeneratorBody, non-lexical-this, env, privateEnv)。
  4. 执行 SetFunctionName(F, name)。
  5. prototypeOrdinaryObjectCreate(%AsyncGeneratorPrototype%)。
  6. 执行 ! DefinePropertyOrThrow(F, "prototype", PropertyDescriptor { [[Value]]: prototype, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false })。
  7. 返回 F
AsyncGeneratorDeclaration : async function * ( FormalParameters ) { AsyncGeneratorBody }
  1. sourceTextAsyncGeneratorDeclaration 匹配的源文本。
  2. FOrdinaryFunctionCreate(%AsyncGeneratorFunction.prototype%, sourceText, FormalParameters, AsyncGeneratorBody, non-lexical-this, env, privateEnv)。
  3. 执行 SetFunctionName(F, "default")。
  4. prototypeOrdinaryObjectCreate(%AsyncGeneratorPrototype%)。
  5. 执行 ! DefinePropertyOrThrow(F, "prototype", PropertyDescriptor { [[Value]]: prototype, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false })。
  6. 返回 F
Note

匿名 AsyncGeneratorDeclaration 只能出现在 export default 声明中。

15.6.4 运行时语义:InstantiateAsyncGeneratorFunctionExpression : 一个 ECMAScript 函数对象

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

AsyncGeneratorExpression : async function * ( FormalParameters ) { AsyncGeneratorBody }
  1. name 不存在,设 name""
  2. env 为当前执行上下文的 LexicalEnvironment。
  3. privateEnv 为当前执行上下文的 PrivateEnvironment。
  4. sourceTextAsyncGeneratorExpression 匹配的源文本。
  5. closureOrdinaryFunctionCreate(%AsyncGeneratorFunction.prototype%, sourceText, FormalParameters, AsyncGeneratorBody, non-lexical-this, env, privateEnv)。
  6. 执行 SetFunctionName(closure, name)。
  7. prototypeOrdinaryObjectCreate(%AsyncGeneratorPrototype%)。
  8. 执行 ! DefinePropertyOrThrow(closure, "prototype", PropertyDescriptor { [[Value]]: prototype, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false })。
  9. 返回 closure
AsyncGeneratorExpression : async function * BindingIdentifier ( FormalParameters ) { AsyncGeneratorBody }
  1. 断言:name 不存在。
  2. nameBindingIdentifier 的 StringValue。
  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

AsyncGeneratorExpression 中的 BindingIdentifier 可在其 AsyncGeneratorBody 内被引用以实现自递归。但与 AsyncGeneratorDeclaration 不同,该标识符不可从包围表达式的作用域引用,也不影响外层作用域。

15.6.5 运行时语义:求值 (Runtime Semantics: Evaluation)

AsyncGeneratorExpression : async function * BindingIdentifieropt ( FormalParameters ) { AsyncGeneratorBody }
  1. 返回 InstantiateAsyncGeneratorFunctionExpression of AsyncGeneratorExpression

15.7 类定义 (Class Definitions)

语法 (Syntax)

ClassDeclaration[Yield, Await, Default] : class BindingIdentifier[?Yield, ?Await] ClassTail[?Yield, ?Await] [+Default] class ClassTail[?Yield, ?Await] ClassExpression[Yield, Await] : class BindingIdentifier[?Yield, ?Await]opt ClassTail[?Yield, ?Await] ClassTail[Yield, Await] : ClassHeritage[?Yield, ?Await]opt { ClassBody[?Yield, ?Await]opt } ClassHeritage[Yield, Await] : extends LeftHandSideExpression[?Yield, ?Await] ClassBody[Yield, Await] : ClassElementList[?Yield, ?Await] ClassElementList[Yield, Await] : ClassElement[?Yield, ?Await] ClassElementList[?Yield, ?Await] ClassElement[?Yield, ?Await] ClassElement[Yield, Await] : MethodDefinition[?Yield, ?Await] static MethodDefinition[?Yield, ?Await] FieldDefinition[?Yield, ?Await] ; static FieldDefinition[?Yield, ?Await] ; ClassStaticBlock ; FieldDefinition[Yield, Await] : ClassElementName[?Yield, ?Await] Initializer[+In, ?Yield, ?Await]opt ClassElementName[Yield, Await] : PropertyName[?Yield, ?Await] PrivateIdentifier ClassStaticBlock : static { ClassStaticBlockBody } ClassStaticBlockBody : ClassStaticBlockStatementList ClassStaticBlockStatementList : StatementList[~Yield, +Await, ~Return]opt Note

类定义始终是严格模式代码。

15.7.1 静态语义:早期错误 (Static Semantics: Early Errors)

ClassTail : ClassHeritageopt { ClassBody }
  • 若未出现 ClassHeritage 且下述算法返回 true,则为语法错误:

    1. constructorClassBody 的 ConstructorMethod。
    2. constructorempty,返回 false
    3. 返回 HasDirectSuper(constructor)。
ClassBody : ClassElementList
  • ClassElementList 的 PrototypePropertyNameList 中出现多于一次 "constructor",则语法错误。
  • ClassElementList 的 PrivateBoundIdentifiers 含有重复条目(除非该名称仅用作一次 getter 与一次 setter 且不出现其他条目,且二者同为 static 或同为非 static),则语法错误。
ClassElement : MethodDefinition ClassElement : static MethodDefinition ClassElement : FieldDefinition ; ClassElement : static FieldDefinition ;
  • FieldDefinition 的 PropName 若为 "prototype""constructor" 则语法错误。
FieldDefinition : ClassElementName Initializeropt ClassElementName : PrivateIdentifier ClassStaticBlockBody : ClassStaticBlockStatementList

15.7.2 静态语义:ClassElementKind

The syntax-directed operation 静态语义:ClassElementKind takes no arguments and returns constructor-methodnon-constructor-methodempty. It is defined piecewise over the following productions:

ClassElement : MethodDefinition
  1. MethodDefinition 的 PropName 为 "constructor",返回 constructor-method
  2. 返回 non-constructor-method
ClassElement : static MethodDefinition FieldDefinition ; static FieldDefinition ;
  1. 返回 non-constructor-method
ClassElement : ClassStaticBlock
  1. 返回 non-constructor-method
ClassElement : ;
  1. 返回 empty

15.7.3 静态语义:ConstructorMethod

The syntax-directed operation 静态语义:ConstructorMethod takes no arguments and returns 一个 ClassElement 解析节点empty. It is defined piecewise over the following productions:

ClassElementList : ClassElement
  1. ClassElement 的 ClassElementKind 为 constructor-method,返回 ClassElement
  2. 返回 empty
ClassElementList : ClassElementList ClassElement
  1. headClassElementList 的 ConstructorMethod。
  2. headempty,返回 head
  3. ClassElement 的 ClassElementKind 为 constructor-method,返回 ClassElement
  4. 返回 empty
Note

早期错误规则确保仅存在一个名为 "constructor" 的方法定义,且它不是访问器属性或生成器定义。

15.7.4 静态语义:IsStatic

The syntax-directed operation 静态语义:IsStatic takes no arguments and returns Boolean. It is defined piecewise over the following productions:

ClassElement : MethodDefinition
  1. 返回 false
ClassElement : static MethodDefinition
  1. 返回 true
ClassElement : FieldDefinition ;
  1. 返回 false
ClassElement : static FieldDefinition ;
  1. 返回 true
ClassElement : ClassStaticBlock
  1. 返回 true
ClassElement : ;
  1. 返回 false

15.7.5 静态语义:NonConstructorElements

The syntax-directed operation 静态语义:NonConstructorElements takes no arguments and returns ClassElement 解析节点的列表. It is defined piecewise over the following productions:

ClassElementList : ClassElement
  1. ClassElement 的 ClassElementKind 为 non-constructor-method,则
    1. 返回 « ClassElement »。
  2. 返回新空列表。
ClassElementList : ClassElementList ClassElement
  1. listClassElementList 的 NonConstructorElements。
  2. ClassElement 的 ClassElementKind 为 non-constructor-method,则
    1. ClassElement 追加至 list 末尾。
  3. 返回 list

15.7.6 静态语义:PrototypePropertyNameList

The syntax-directed operation 静态语义:PrototypePropertyNameList takes no arguments and returns 属性键列表. It is defined piecewise over the following productions:

ClassElementList : ClassElement
  1. propNameClassElement 的 PropName。
  2. propNameempty,返回新空列表。
  3. 若 IsStatic(ClassElement) 为 true,返回新空列表。
  4. 返回 « propName »。
ClassElementList : ClassElementList ClassElement
  1. listClassElementList 的 PrototypePropertyNameList。
  2. propNameClassElement 的 PropName。
  3. propNameempty,返回 list
  4. 若 IsStatic(ClassElement) 为 true,返回 list
  5. 返回 列表连接(list, « propName »)。

15.7.7 静态语义:AllPrivateIdentifiersValid

The syntax-directed operation 静态语义:AllPrivateIdentifiersValid takes argument names (字符串列表) and returns Boolean.

本规范中未列出的所有产生式替代都隐式具有如下默认定义:

  1. 对该解析节点的每个子节点 child
    1. child 是非终结符实例,则
      1. 若 AllPrivateIdentifiersValid(child, names) 为 false,返回 false
  2. 返回 true
MemberExpression : MemberExpression . PrivateIdentifier
  1. names 包含 PrivateIdentifier 的 StringValue,则
    1. 返回 AllPrivateIdentifiersValid(MemberExpression, names)。
  2. 返回 false
CallExpression : CallExpression . PrivateIdentifier
  1. names 包含 PrivateIdentifier 的 StringValue,则
    1. 返回 AllPrivateIdentifiersValid(CallExpression, names)。
  2. 返回 false
OptionalChain : ?. PrivateIdentifier
  1. names 包含 PrivateIdentifier 的 StringValue,返回 true
  2. 返回 false
OptionalChain : OptionalChain . PrivateIdentifier
  1. names 包含 PrivateIdentifier 的 StringValue,则
    1. 返回 AllPrivateIdentifiersValid(OptionalChain, names)。
  2. 返回 false
ClassBody : ClassElementList
  1. newNamesnamesClassBody 的 PrivateBoundIdentifiers 的列表连接。
  2. 返回 AllPrivateIdentifiersValid(ClassElementList, newNames)。
RelationalExpression : PrivateIdentifier in ShiftExpression
  1. names 包含 PrivateIdentifier 的 StringValue,则
    1. 返回 AllPrivateIdentifiersValid(ShiftExpression, names)。
  2. 返回 false

15.7.8 静态语义:PrivateBoundIdentifiers

The syntax-directed operation 静态语义:PrivateBoundIdentifiers takes no arguments and returns 字符串列表. It is defined piecewise over the following productions:

FieldDefinition : ClassElementName Initializeropt
  1. 返回 ClassElementName 的 PrivateBoundIdentifiers。
ClassElementName : PrivateIdentifier
  1. 返回仅包含 PrivateIdentifier 的 StringValue 的列表。
ClassElementName : PropertyName ClassElement : ClassStaticBlock ;
  1. 返回新空列表。
ClassElementList : ClassElementList ClassElement
  1. names1ClassElementList 的 PrivateBoundIdentifiers。
  2. names2ClassElement 的 PrivateBoundIdentifiers。
  3. 返回 列表连接(names1, names2)。
MethodDefinition : ClassElementName ( UniqueFormalParameters ) { FunctionBody } get ClassElementName ( ) { FunctionBody } set ClassElementName ( PropertySetParameterList ) { FunctionBody } GeneratorMethod : * ClassElementName ( UniqueFormalParameters ) { GeneratorBody } AsyncMethod : async ClassElementName ( UniqueFormalParameters ) { AsyncFunctionBody } AsyncGeneratorMethod : async * ClassElementName ( UniqueFormalParameters ) { AsyncGeneratorBody }
  1. 返回 ClassElementName 的 PrivateBoundIdentifiers。

15.7.9 静态语义:ContainsArguments

The syntax-directed operation 静态语义:ContainsArguments takes no arguments and returns Boolean.

本规范中未列出的产生式替代默认使用以下定义:

  1. 对该节点的每个子节点 child
    1. child 是非终结符实例:
      1. 若 ContainsArguments(child) 为 true,返回 true
  2. 返回 false
IdentifierReference : Identifier
  1. Identifier 的 StringValue 为 "arguments",返回 true
  2. 返回 false
FunctionDeclaration : function BindingIdentifier ( FormalParameters ) { FunctionBody } function ( FormalParameters ) { FunctionBody } FunctionExpression : function BindingIdentifieropt ( FormalParameters ) { FunctionBody } GeneratorDeclaration : function * BindingIdentifier ( FormalParameters ) { GeneratorBody } function * ( FormalParameters ) { GeneratorBody } GeneratorExpression : function * BindingIdentifieropt ( FormalParameters ) { GeneratorBody } AsyncGeneratorDeclaration : async function * BindingIdentifier ( FormalParameters ) { AsyncGeneratorBody } async function * ( FormalParameters ) { AsyncGeneratorBody } AsyncGeneratorExpression : async function * BindingIdentifieropt ( FormalParameters ) { AsyncGeneratorBody } AsyncFunctionDeclaration : async function BindingIdentifier ( FormalParameters ) { AsyncFunctionBody } async function ( FormalParameters ) { AsyncFunctionBody } AsyncFunctionExpression : async function BindingIdentifieropt ( FormalParameters ) { AsyncFunctionBody }
  1. 返回 false
MethodDefinition : ClassElementName ( UniqueFormalParameters ) { FunctionBody } get ClassElementName ( ) { FunctionBody } set ClassElementName ( PropertySetParameterList ) { FunctionBody } GeneratorMethod : * ClassElementName ( UniqueFormalParameters ) { GeneratorBody } AsyncGeneratorMethod : async * ClassElementName ( UniqueFormalParameters ) { AsyncGeneratorBody } AsyncMethod : async ClassElementName ( UniqueFormalParameters ) { AsyncFunctionBody }
  1. 返回 ContainsArguments(ClassElementName)。

15.7.10 运行时语义:ClassFieldDefinitionEvaluation

The syntax-directed operation 运行时语义:ClassFieldDefinitionEvaluation takes argument homeObject (一个对象) and returns 正常完成(包含一个 ClassFieldDefinition Record)或突然完成. It is defined piecewise over the following productions:

FieldDefinition : ClassElementName Initializeropt
  1. name 为 ? Evaluation of ClassElementName
  2. 若存在 Initializer,则
    1. formalParameterList 为产生式 FormalParameters : [empty] 的一个实例。
    2. env 为当前执行上下文的 LexicalEnvironment。
    3. privateEnv 为当前执行上下文的 PrivateEnvironment。
    4. sourceText 为空的 Unicode 码点序列。
    5. initializerOrdinaryFunctionCreate(%Function.prototype%, sourceText, formalParameterList, Initializer, non-lexical-this, env, privateEnv)。
    6. 执行 MakeMethod(initializer, homeObject)。
    7. initializer.[[ClassFieldInitializerName]]name
  3. 否则,
    1. initializerempty
  4. 返回 ClassFieldDefinition Record { [[Name]]: name, [[Initializer]]: initializer }。
Note
initializer 创建的函数不会被 ECMAScript 代码直接访问。

15.7.11 运行时语义: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 为空的 Unicode 码点序列。
  4. formalParameters 为产生式 FormalParameters : [empty] 的实例。
  5. bodyFunctionOrdinaryFunctionCreate(%Function.prototype%, sourceText, formalParameters, ClassStaticBlockBody, non-lexical-this, lex, privateEnv)。
  6. 执行 MakeMethod(bodyFunction, homeObject)。
  7. 返回 ClassStaticBlockDefinition Record { [[BodyFunction]]: bodyFunction }。
Note
函数 bodyFunction 不会被 ECMAScript 代码直接访问。

15.7.12 运行时语义:EvaluateClassStaticBlockBody

The syntax-directed operation 运行时语义:EvaluateClassStaticBlockBody takes argument functionObject (一个 ECMAScript 函数对象) and returns 一个 return completion 或 throw completion. It is defined piecewise over the following productions:

ClassStaticBlockBody : ClassStaticBlockStatementList
  1. 断言:functionObject 是由 ClassStaticBlockDefinitionEvaluation 步骤 5 创建的合成函数。
  2. 执行 ! FunctionDeclarationInstantiation(functionObject, « »)。
  3. 执行 ? Evaluation of ClassStaticBlockStatementList
  4. 返回 ReturnCompletion(undefined)。

15.7.13 运行时语义:ClassElementEvaluation

The syntax-directed operation 运行时语义:ClassElementEvaluation takes argument object (一个对象) and returns 正常完成(包含 ClassFieldDefinition RecordClassStaticBlockDefinition RecordPrivateElementunused 之一)或突然完成. It is defined piecewise over the following productions:

ClassElement : FieldDefinition ; static FieldDefinition ;
  1. 返回 ? ClassFieldDefinitionEvaluation(FieldDefinition, object)。
ClassElement : MethodDefinition static MethodDefinition
  1. 返回 ? MethodDefinitionEvaluation(MethodDefinition, object, false)。
ClassElement : ClassStaticBlock
  1. 返回 ClassStaticBlockDefinitionEvaluation(ClassStaticBlock, object)。
ClassElement : ;
  1. 返回 unused

15.7.14 运行时语义:ClassDefinitionEvaluation

The syntax-directed operation 运行时语义:ClassDefinitionEvaluation takes arguments classBinding (一个 String 或 undefined), className (一个属性键Private Name), and sourceText (ECMAScript 源文本) and returns 正常完成(包含一个函数对象)或突然完成.

Note

为便于规范说明,私有方法与访问器与私有字段一起被包含在类实例的 [[PrivateElements]] 槽中。然而,任意给定对象要么拥有该类定义的全部私有方法与访问器,要么一个也没有。该特性被设计为允许实现选择不对每个方法或访问器单独跟踪的策略来实现私有方法与访问器。

例如,实现可以将实例私有方法直接与其对应的 Private Name 关联,并为每个对象跟踪哪些类构造函数以该对象作为 this 值运行。随后在对象上查找一个实例私有方法的过程即是检查定义该方法的类构造函数是否已用于初始化该对象,然后返回与该 Private Name 关联的方法。

这不同于私有字段:由于字段初始化器在类实例化期间可能抛出,单个对象可能只拥有某个类私有字段的真子集,因此一般必须单独跟踪私有字段。

It is defined piecewise over the following productions:

ClassTail : ClassHeritageopt { ClassBodyopt }
  1. env 为正在运行的执行上下文的 LexicalEnvironment。
  2. classEnvNewDeclarativeEnvironment(env)。
  3. classBinding 不为 undefined,则
    1. 执行 ! classEnv.CreateImmutableBinding(classBinding, true)。
  4. outerPrivateEnvironment 为正在运行的执行上下文的 PrivateEnvironment。
  5. classPrivateEnvironmentNewPrivateEnvironment(outerPrivateEnvironment)。
  6. 若存在 ClassBody,则
    1. ClassBody 的 PrivateBoundIdentifiers 中每个字符串 dn
      1. classPrivateEnvironment.[[Names]] 包含 Private Name pnpn.[[Description]]dn,则
        1. 断言:仅 getter/setter 成对时可能。
      2. 否则,
        1. name 为新的 Private Name[[Description]]dn
        2. name 追加至 classPrivateEnvironment.[[Names]]
  7. 若不存在 ClassHeritage,则
    1. protoParent%Object.prototype%
    2. constructorParent%Function.prototype%
  8. 否则,
    1. 将正在运行执行上下文的 LexicalEnvironment 设为 classEnv
    2. 注:计算 ClassHeritage 时运行执行上下文的 PrivateEnvironment 为 outerPrivateEnvironment
    3. superclassRefCompletion(Evaluation of ClassHeritage)。
    4. 将运行执行上下文的 LexicalEnvironment 设回 env
    5. superclass 为 ? GetValue(? superclassRef)。
    6. superclassnull,则
      1. protoParentnull
      2. constructorParent%Function.prototype%
    7. 否则若 IsConstructor(superclass) 为 false,则
      1. 抛出 TypeError 异常。
    8. 否则,
      1. protoParent 为 ? Get(superclass, "prototype")。
      2. protoParent不是 Object 且不是 null,抛出 TypeError 异常。
      3. constructorParentsuperclass
  9. protoOrdinaryObjectCreate(protoParent)。
  10. 若不存在 ClassBody,令 constructorempty
  11. 否则,令 constructorClassBody 的 ConstructorMethod。
  12. 将运行执行上下文的 LexicalEnvironment 设为 classEnv
  13. 将运行执行上下文的 PrivateEnvironment 设为 classPrivateEnvironment
  14. constructorempty,则
    1. defaultConstructor 为一个不带参数且不捕获任何内容的新抽象闭包,被调用时执行:
      1. args 为通过 [[Call]][[Construct]] 传给此函数的参数列表。
      2. 若 NewTarget 为 undefined,抛出 TypeError 异常。
      3. F 为活动函数对象
      4. F.[[ConstructorKind]]derived,则
        1. 注:此分支行为类似 constructor(...args) { super(...args); }。最显著区别是上述 ECMAScript 源码会可观察地调用 %Array.prototype% 上的 %Symbol.iterator% 方法,而此函数不会。
        2. func 为 ! F.[[GetPrototypeOf]]()。
        3. IsConstructor(func) 为 false,抛出 TypeError 异常。
        4. result 为 ? Construct(func, args, NewTarget)。
      5. 否则,
        1. 注:此分支类似 constructor() {}
        2. result 为 ? OrdinaryCreateFromConstructor(NewTarget, "%Object.prototype%")。
      6. 执行 ? InitializeInstanceElements(result, F)。
      7. 返回 NormalCompletion(result)。
    2. FCreateBuiltinFunction(defaultConstructor, 0, className, « [[ConstructorKind]], [[SourceText]] », 当前 Realm Record, constructorParent)。
  15. 否则,
    1. constructorInfo 为 ! DefineMethod of constructor,参数 protoconstructorParent
    2. FconstructorInfo.[[Closure]]
    3. 执行 MakeClassConstructor(F)。
    4. 执行 SetFunctionName(F, className)。
  16. F.[[SourceText]]sourceText
  17. 执行 MakeConstructor(F, false, proto)。
  18. 若存在 ClassHeritage,设 F.[[ConstructorKind]]derived
  19. 执行 ! DefineMethodProperty(proto, "constructor", F, false)。
  20. 若不存在 ClassBody,令 elements 为新空 List
  21. 否则,令 elementsClassBody 的 NonConstructorElements。
  22. instancePrivateMethodsstaticPrivateMethodsinstanceFieldsstaticElements 各为新空 List
  23. elements 中每个 ClassElement e
    1. 若 IsStatic of efalse,则
      1. elementCompletion(ClassElementEvaluation of e,参数 proto)。
    2. 否则,
      1. elementCompletion(ClassElementEvaluation of e,参数 F)。
    3. element 是突然完成,
      1. 将运行执行上下文的 LexicalEnvironment 设为 env
      2. 将运行执行上下文的 PrivateEnvironment 设为 outerPrivateEnvironment
      3. 返回 ? element
    4. element 为 ! element
    5. elementPrivateElement,则
      1. 断言:element.[[Kind]]methodaccessor
      2. 若 IsStatic of efalse,令 containerinstancePrivateMethods;否则令其为 staticPrivateMethods
      3. container 中存在 PrivateElement pepe.[[Key]]element.[[Key]],则
        1. 断言:element.[[Kind]]pe.[[Kind]] 均为 accessor
        2. element.[[Get]]undefined,则
          1. combinedPrivateElement { [[Key]]: element.[[Key]], [[Kind]]: accessor, [[Get]]: pe.[[Get]], [[Set]]: element.[[Set]] }。
        3. 否则,
          1. combinedPrivateElement { [[Key]]: element.[[Key]], [[Kind]]: accessor, [[Get]]: element.[[Get]], [[Set]]: pe.[[Set]] }。
        4. combined 替换 container 中的 pe
      4. 否则,
        1. 追加 elementcontainer
    6. 否则若 elementClassFieldDefinition Record,则
      1. 若 IsStatic of efalse,将 element 追加至 instanceFields;否则追加至 staticElements
    7. 否则若 elementClassStaticBlockDefinition Record,则
      1. 追加 elementstaticElements
  24. 将运行执行上下文的 LexicalEnvironment 设回 env
  25. classBinding 不为 undefined,则
    1. 执行 ! classEnv.InitializeBinding(classBinding, F)。
  26. F.[[PrivateMethods]]instancePrivateMethods
  27. F.[[Fields]]instanceFields
  28. staticPrivateMethods 中每个 PrivateElement method
    1. 执行 ! PrivateMethodOrAccessorAdd(F, method)。
  29. staticElements 中每个元素 elementRecord
    1. elementRecordClassFieldDefinition Record,则
      1. resultCompletion(DefineField(F, elementRecord))。
    2. 否则,
      1. 断言:elementRecordClassStaticBlockDefinition Record
      2. resultCompletion(Call(elementRecord.[[BodyFunction]], F))。
    3. result 为突然完成,
      1. 将运行执行上下文的 PrivateEnvironment 设为 outerPrivateEnvironment
      2. 返回 ? result
  30. 将运行执行上下文的 PrivateEnvironment 设为 outerPrivateEnvironment
  31. 返回 F

15.7.15 运行时语义:BindingClassDeclarationEvaluation

The syntax-directed operation 运行时语义:BindingClassDeclarationEvaluation takes no arguments and returns 正常完成(包含一个函数对象)或突然完成. It is defined piecewise over the following productions:

ClassDeclaration : class BindingIdentifier ClassTail
  1. classNameBindingIdentifier 的 StringValue。
  2. sourceTextClassDeclaration 匹配的源文本。
  3. value 为 ? ClassDefinitionEvaluation of ClassTail,参数 classNameclassNamesourceText
  4. env 为正在运行的执行上下文的 LexicalEnvironment。
  5. 执行 ? InitializeBoundName(className, value, env)。
  6. 返回 value
ClassDeclaration : class ClassTail
  1. sourceTextClassDeclaration 匹配的源文本。
  2. 返回 ? ClassDefinitionEvaluation of ClassTail,参数 undefined"default"sourceText
Note

ClassDeclaration : class ClassTail 只会作为 ExportDeclaration 的一部分出现,其绑定的建立由该产生式的求值动作处理。参见 16.2.3.7

15.7.16 运行时语义:求值 (Runtime Semantics: Evaluation)

ClassDeclaration : class BindingIdentifier ClassTail
  1. 执行 ? BindingClassDeclarationEvaluation of 此 ClassDeclaration
  2. 返回 empty
Note

ClassDeclaration : class ClassTail 仅作为 ExportDeclaration 的一部分出现,且不会被直接求值。

ClassExpression : class ClassTail
  1. sourceTextClassExpression 匹配的源文本。
  2. 返回 ? ClassDefinitionEvaluation of ClassTail,参数 undefined""sourceText
ClassExpression : class BindingIdentifier ClassTail
  1. classNameBindingIdentifier 的 StringValue。
  2. sourceTextClassExpression 匹配的源文本。
  3. 返回 ? ClassDefinitionEvaluation of ClassTail,参数 classNameclassNamesourceText
ClassElementName : PrivateIdentifier
  1. privateIdentifierPrivateIdentifier 的 StringValue。
  2. privateEnvRec 为运行执行上下文的 PrivateEnvironment。
  3. namesprivateEnvRec.[[Names]]
  4. 断言:names 中恰有一个 Private Name[[Description]]privateIdentifier
  5. privateNamenames[[Description]]privateIdentifierPrivate Name
  6. 返回 privateName
ClassStaticBlockStatementList : [empty]
  1. 返回 undefined

15.8 异步函数定义 (Async Function Definitions)

语法 (Syntax)

AsyncFunctionDeclaration[Yield, Await, Default] : async [no LineTerminator here] function BindingIdentifier[?Yield, ?Await] ( FormalParameters[~Yield, +Await] ) { AsyncFunctionBody } [+Default] async [no LineTerminator here] function ( FormalParameters[~Yield, +Await] ) { AsyncFunctionBody } AsyncFunctionExpression : async [no LineTerminator here] function BindingIdentifier[~Yield, +Await]opt ( FormalParameters[~Yield, +Await] ) { AsyncFunctionBody } AsyncMethod[Yield, Await] : async [no LineTerminator here] ClassElementName[?Yield, ?Await] ( UniqueFormalParameters[~Yield, +Await] ) { AsyncFunctionBody } AsyncFunctionBody : FunctionBody[~Yield, +Await] AwaitExpression[Yield] : await UnaryExpression[?Yield, +Await] Note 1

[Await] 参数存在时,await 被解析为 AwaitExpression 的关键字。[Await] 参数在以下上下文的顶层存在,尽管在某些上下文中(例如 FunctionBody)该参数可能缺失:

Script 是语法目标符号时,如果 [Await] 参数缺失,await 可以被解析为标识符。包括以下情形:

Note 2

不同于 YieldExpression,省略 AwaitExpression 的操作数是语法错误。必须等待某个值。

15.8.1 静态语义:早期错误 (Static Semantics: Early Errors)

AsyncMethod : async ClassElementName ( UniqueFormalParameters ) { AsyncFunctionBody } AsyncFunctionDeclaration : async function BindingIdentifier ( FormalParameters ) { AsyncFunctionBody } async function ( FormalParameters ) { AsyncFunctionBody } AsyncFunctionExpression : async function BindingIdentifieropt ( FormalParameters ) { AsyncFunctionBody }

15.8.2 运行时语义:InstantiateAsyncFunctionObject

The syntax-directed operation 运行时语义:InstantiateAsyncFunctionObject takes arguments env (一个 Environment Record) and privateEnv (一个 PrivateEnvironment Recordnull) and returns 一个 ECMAScript 函数对象. It is defined piecewise over the following productions:

AsyncFunctionDeclaration : async function BindingIdentifier ( FormalParameters ) { AsyncFunctionBody }
  1. nameBindingIdentifier 的 StringValue。
  2. sourceTextAsyncFunctionDeclaration 匹配的源文本。
  3. FOrdinaryFunctionCreate(%AsyncFunction.prototype%, sourceText, FormalParameters, AsyncFunctionBody, non-lexical-this, env, privateEnv)。
  4. 执行 SetFunctionName(F, name)。
  5. 返回 F
AsyncFunctionDeclaration : async function ( FormalParameters ) { AsyncFunctionBody }
  1. sourceTextAsyncFunctionDeclaration 匹配的源文本。
  2. FOrdinaryFunctionCreate(%AsyncFunction.prototype%, sourceText, FormalParameters, AsyncFunctionBody, non-lexical-this, env, privateEnv)。
  3. 执行 SetFunctionName(F, "default")。
  4. 返回 F

15.8.3 运行时语义:InstantiateAsyncFunctionExpression : 一个 ECMAScript 函数对象

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

AsyncFunctionExpression : async function ( FormalParameters ) { AsyncFunctionBody }
  1. name 不存在,设 name""
  2. env 为运行执行上下文的 LexicalEnvironment。
  3. privateEnv 为运行执行上下文的 PrivateEnvironment。
  4. sourceTextAsyncFunctionExpression 匹配的源文本。
  5. closureOrdinaryFunctionCreate(%AsyncFunction.prototype%, sourceText, FormalParameters, AsyncFunctionBody, non-lexical-this, env, privateEnv)。
  6. 执行 SetFunctionName(closure, name)。
  7. 返回 closure
AsyncFunctionExpression : async function BindingIdentifier ( FormalParameters ) { AsyncFunctionBody }
  1. 断言:name 不存在。
  2. nameBindingIdentifier 的 StringValue。
  3. outerEnv 为运行执行上下文的 LexicalEnvironment。
  4. funcEnvNewDeclarativeEnvironment(outerEnv)。
  5. 执行 ! funcEnv.CreateImmutableBinding(name, false)。
  6. privateEnv 为运行执行上下文的 PrivateEnvironment。
  7. sourceTextAsyncFunctionExpression 匹配的源文本。
  8. closureOrdinaryFunctionCreate(%AsyncFunction.prototype%, sourceText, FormalParameters, AsyncFunctionBody, non-lexical-this, funcEnv, privateEnv)。
  9. 执行 SetFunctionName(closure, name)。
  10. 执行 ! funcEnv.InitializeBinding(name, closure)。
  11. 返回 closure
Note

AsyncFunctionExpression 中的 BindingIdentifier 可在其 AsyncFunctionBody 内引用以允许函数自递归。然而,与 FunctionDeclaration 不同,AsyncFunctionExpression 中的 BindingIdentifier 不能被其外层作用域引用,也不影响外层作用域。

15.8.4 运行时语义:EvaluateAsyncFunctionBody

The syntax-directed operation 运行时语义:EvaluateAsyncFunctionBody takes arguments functionObject (一个 ECMAScript 函数对象) and argumentsList (ECMAScript 语言值列表) and returns 一个 return completion. 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. 返回 InstantiateAsyncFunctionExpression of AsyncFunctionExpression
AwaitExpression : await UnaryExpression
  1. exprRef 为 ? Evaluation of UnaryExpression
  2. value 为 ? GetValue(exprRef)。
  3. 返回 ? Await(value)。

15.9 异步箭头函数定义 (Async Arrow Function Definitions)

语法 (Syntax)

AsyncArrowFunction[In, Yield, Await] : async [no LineTerminator here] AsyncArrowBindingIdentifier[?Yield] [no LineTerminator here] => AsyncConciseBody[?In] CoverCallExpressionAndAsyncArrowHead[?Yield, ?Await] [no LineTerminator here] => AsyncConciseBody[?In] AsyncConciseBody[In] : [lookahead ≠ {] ExpressionBody[?In, +Await] { AsyncFunctionBody } AsyncArrowBindingIdentifier[Yield] : BindingIdentifier[?Yield, +Await] CoverCallExpressionAndAsyncArrowHead[Yield, Await] : MemberExpression[?Yield, ?Await] Arguments[?Yield, ?Await]

补充语法 (Supplemental Syntax)

处理产生式实例:
AsyncArrowFunction : CoverCallExpressionAndAsyncArrowHead => AsyncConciseBody
时,对 CoverCallExpressionAndAsyncArrowHead 的解释使用下列语法细化:

AsyncArrowHead : async [no LineTerminator here] ArrowFormalParameters[~Yield, +Await]

15.9.1 静态语义:早期错误 (Static Semantics: Early Errors)

AsyncArrowFunction : async AsyncArrowBindingIdentifier => AsyncConciseBody AsyncArrowFunction : CoverCallExpressionAndAsyncArrowHead => AsyncConciseBody

15.9.2 静态语义:AsyncConciseBodyContainsUseStrict

The syntax-directed operation 静态语义:AsyncConciseBodyContainsUseStrict takes no arguments and returns Boolean. It is defined piecewise over the following productions:

AsyncConciseBody : ExpressionBody
  1. 返回 false
AsyncConciseBody : { AsyncFunctionBody }
  1. 返回 FunctionBodyContainsUseStrict(AsyncFunctionBody)。

15.9.3 运行时语义:EvaluateAsyncConciseBody

The syntax-directed operation 运行时语义:EvaluateAsyncConciseBody takes arguments functionObject (一个 ECMAScript 函数对象) and argumentsList (ECMAScript 语言值列表) and returns 一个 return completion. 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 运行时语义:InstantiateAsyncArrowFunctionExpression : 一个 ECMAScript 函数对象

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

AsyncArrowFunction : async AsyncArrowBindingIdentifier => AsyncConciseBody
  1. name 不存在,设 name""
  2. env 为当前执行上下文的 LexicalEnvironment。
  3. privateEnv 为当前执行上下文的 PrivateEnvironment。
  4. sourceTextAsyncArrowFunction 匹配的源文本。
  5. parametersAsyncArrowBindingIdentifier
  6. closureOrdinaryFunctionCreate(%AsyncFunction.prototype%, sourceText, parameters, AsyncConciseBody, lexical-this, env, privateEnv)。
  7. 执行 SetFunctionName(closure, name)。
  8. 返回 closure
AsyncArrowFunction : CoverCallExpressionAndAsyncArrowHead => AsyncConciseBody
  1. name 不存在,设 name""
  2. env 为当前执行上下文的 LexicalEnvironment。
  3. privateEnv 为当前执行上下文的 PrivateEnvironment。
  4. sourceTextAsyncArrowFunction 匹配的源文本。
  5. headCoverCallExpressionAndAsyncArrowHead 覆盖AsyncArrowHead
  6. parametersheadArrowFormalParameters
  7. closureOrdinaryFunctionCreate(%AsyncFunction.prototype%, sourceText, parameters, AsyncConciseBody, lexical-this, env, privateEnv)。
  8. 执行 SetFunctionName(closure, name)。
  9. 返回 closure

15.9.5 运行时语义:求值 (Runtime Semantics: Evaluation)

AsyncArrowFunction : async AsyncArrowBindingIdentifier => AsyncConciseBody CoverCallExpressionAndAsyncArrowHead => AsyncConciseBody
  1. 返回 InstantiateAsyncArrowFunctionExpression of AsyncArrowFunction

15.10 尾位置调用 (Tail Position Calls)

15.10.1 静态语义:IsInTailPosition ( call )

The abstract operation 静态语义:IsInTailPosition takes argument call (一个 CallExpression 解析节点MemberExpression 解析节点OptionalChain 解析节点) and returns Boolean. It performs the following steps when called:

  1. 若 IsStrict(call) 为 false,返回 false
  2. call 不被包含在 FunctionBodyConciseBodyAsyncConciseBody 内,返回 false
  3. body 为最贴近包含 callFunctionBodyConciseBodyAsyncConciseBody
  4. bodyGeneratorBodyFunctionBody,返回 false
  5. bodyAsyncFunctionBodyFunctionBody,返回 false
  6. bodyAsyncGeneratorBodyFunctionBody,返回 false
  7. bodyAsyncConciseBody,返回 false
  8. 返回 HasCallInTailPosition(body, call) 的结果。
Note

尾位置调用仅在严格模式代码中定义,这是因为存在常见的非标准语言扩展(参见 10.2.4)允许观察调用者上下文链。

15.10.2 静态语义:HasCallInTailPosition

The syntax-directed operation 静态语义:HasCallInTailPosition takes argument call (一个 CallExpression 解析节点MemberExpression 解析节点OptionalChain 解析节点) and returns Boolean.

Note 1

call 是表示特定源文本范围的解析节点。以下算法比较 call 与另一解析节点时,测试的是它们是否表示同一段源文本。

Note 2

紧随其后的 return GetValue(调用结果) 的潜在尾位置调用同样视为可能的尾位置调用。函数调用不会返回 Reference Record,因此该 GetValue 操作总会返回与函数调用结果相同的值。

It is defined piecewise over the following productions:

StatementList : StatementList StatementListItem
  1. has 为 HasCallInTailPosition(StatementList, call)。
  2. hastrue,返回 true
  3. 返回 HasCallInTailPosition(StatementListItem, call)。
FunctionStatementList : [empty] StatementListItem : Declaration Statement : VariableStatement EmptyStatement ExpressionStatement ContinueStatement BreakStatement ThrowStatement DebuggerStatement Block : { } ReturnStatement : return ; LabelledItem : FunctionDeclaration ForInOfStatement : for ( LeftHandSideExpression of AssignmentExpression ) Statement for ( var ForBinding of AssignmentExpression ) Statement for ( ForDeclaration of AssignmentExpression ) Statement CaseBlock : { }
  1. 返回 false
IfStatement : if ( Expression ) Statement else Statement
  1. has 为第一个 Statement 的 HasCallInTailPosition(call)。
  2. hastrue,返回 true
  3. 返回第二个 Statement 的 HasCallInTailPosition(call)。
IfStatement : if ( Expression ) Statement DoWhileStatement : do Statement while ( Expression ) ; WhileStatement : while ( Expression ) Statement ForStatement : for ( Expressionopt ; Expressionopt ; Expressionopt ) Statement for ( var VariableDeclarationList ; Expressionopt ; Expressionopt ) Statement for ( LexicalDeclaration Expressionopt ; Expressionopt ) Statement ForInOfStatement : for ( LeftHandSideExpression in Expression ) Statement for ( var ForBinding in Expression ) Statement for ( ForDeclaration in Expression ) Statement WithStatement : with ( Expression ) Statement
  1. 返回 HasCallInTailPosition(Statement, call)。
LabelledStatement : LabelIdentifier : LabelledItem
  1. 返回 HasCallInTailPosition(LabelledItem, call)。
ReturnStatement : return Expression ;
  1. 返回 HasCallInTailPosition(Expression, call)。
SwitchStatement : switch ( Expression ) CaseBlock
  1. 返回 HasCallInTailPosition(CaseBlock, call)。
CaseBlock : { CaseClausesopt DefaultClause CaseClausesopt }
  1. hasfalse
  2. 若首个 CaseClauses 存在,设 has 为 HasCallInTailPosition(首个 CaseClauses, call)。
  3. hastrue,返回 true
  4. has 为 HasCallInTailPosition(DefaultClause, call)。
  5. hastrue,返回 true
  6. 若第二个 CaseClauses 存在,设 has 为 HasCallInTailPosition(第二个 CaseClauses, call)。
  7. 返回 has
CaseClauses : CaseClauses CaseClause
  1. has 为 HasCallInTailPosition(CaseClauses, call)。
  2. hastrue,返回 true
  3. 返回 HasCallInTailPosition(CaseClause, call)。
CaseClause : case Expression : StatementListopt DefaultClause : default : StatementListopt
  1. StatementList 存在,返回 HasCallInTailPosition(StatementList, call)。
  2. 返回 false
TryStatement : try Block Catch
  1. 返回 HasCallInTailPosition(Catch, call)。
TryStatement : try Block Finally try Block Catch Finally
  1. 返回 HasCallInTailPosition(Finally, call)。
Catch : catch ( CatchParameter ) Block
  1. 返回 HasCallInTailPosition(Block, call)。
AssignmentExpression : YieldExpression ArrowFunction AsyncArrowFunction LeftHandSideExpression = AssignmentExpression LeftHandSideExpression AssignmentOperator AssignmentExpression LeftHandSideExpression &&= AssignmentExpression LeftHandSideExpression ||= AssignmentExpression LeftHandSideExpression ??= AssignmentExpression BitwiseANDExpression : BitwiseANDExpression & EqualityExpression BitwiseXORExpression : BitwiseXORExpression ^ BitwiseANDExpression BitwiseORExpression : BitwiseORExpression | BitwiseXORExpression EqualityExpression : EqualityExpression == RelationalExpression EqualityExpression != RelationalExpression EqualityExpression === RelationalExpression EqualityExpression !== RelationalExpression RelationalExpression : RelationalExpression < ShiftExpression RelationalExpression > ShiftExpression RelationalExpression <= ShiftExpression RelationalExpression >= ShiftExpression RelationalExpression instanceof ShiftExpression RelationalExpression in ShiftExpression PrivateIdentifier in ShiftExpression ShiftExpression : ShiftExpression << AdditiveExpression ShiftExpression >> AdditiveExpression ShiftExpression >>> AdditiveExpression AdditiveExpression : AdditiveExpression + MultiplicativeExpression AdditiveExpression - MultiplicativeExpression MultiplicativeExpression : MultiplicativeExpression MultiplicativeOperator ExponentiationExpression ExponentiationExpression : UpdateExpression ** ExponentiationExpression UpdateExpression : LeftHandSideExpression ++ LeftHandSideExpression -- ++ UnaryExpression -- UnaryExpression UnaryExpression : delete UnaryExpression void UnaryExpression typeof UnaryExpression + UnaryExpression - UnaryExpression ~ UnaryExpression ! UnaryExpression AwaitExpression CallExpression : SuperCall ImportCall CallExpression [ Expression ] CallExpression . IdentifierName CallExpression . PrivateIdentifier NewExpression : new NewExpression MemberExpression : MemberExpression [ Expression ] MemberExpression . IdentifierName SuperProperty MetaProperty new MemberExpression Arguments MemberExpression . PrivateIdentifier PrimaryExpression : this IdentifierReference Literal ArrayLiteral ObjectLiteral FunctionExpression ClassExpression GeneratorExpression AsyncFunctionExpression AsyncGeneratorExpression RegularExpressionLiteral TemplateLiteral
  1. 返回 false
Expression : AssignmentExpression Expression , AssignmentExpression
  1. 返回 HasCallInTailPosition(AssignmentExpression, call)。
ConditionalExpression : ShortCircuitExpression ? AssignmentExpression : AssignmentExpression
  1. has 为第一个 AssignmentExpression 的 HasCallInTailPosition(call)。
  2. hastrue,返回 true
  3. 返回第二个 AssignmentExpression 的 HasCallInTailPosition(call)。
LogicalANDExpression : LogicalANDExpression && BitwiseORExpression
  1. 返回 HasCallInTailPosition(BitwiseORExpression, call)。
LogicalORExpression : LogicalORExpression || LogicalANDExpression
  1. 返回 HasCallInTailPosition(LogicalANDExpression, call)。
CoalesceExpression : CoalesceExpressionHead ?? BitwiseORExpression
  1. 返回 HasCallInTailPosition(BitwiseORExpression, call)。
CallExpression : CoverCallExpressionAndAsyncArrowHead CallExpression Arguments CallExpression TemplateLiteral
  1. 若此 CallExpressioncall,返回 true
  2. 返回 false
OptionalExpression : MemberExpression OptionalChain CallExpression OptionalChain OptionalExpression OptionalChain
  1. 返回 HasCallInTailPosition(OptionalChain, call)。
OptionalChain : ?. [ Expression ] ?. IdentifierName ?. PrivateIdentifier OptionalChain [ Expression ] OptionalChain . IdentifierName OptionalChain . PrivateIdentifier
  1. 返回 false
OptionalChain : ?. Arguments OptionalChain Arguments
  1. 若此 OptionalChaincall,返回 true
  2. 返回 false
MemberExpression : MemberExpression TemplateLiteral
  1. 若此 MemberExpressioncall,返回 true
  2. 返回 false
PrimaryExpression : CoverParenthesizedExpressionAndArrowParameterList
  1. exprCoverParenthesizedExpressionAndArrowParameterList 覆盖ParenthesizedExpression
  2. 返回 HasCallInTailPosition(expr, call)。
ParenthesizedExpression : ( Expression )
  1. 返回 HasCallInTailPosition(Expression, call)。

15.10.3 PrepareForTailCall ( )

The abstract operation PrepareForTailCall takes no arguments and returns unused. It performs the following steps when called:

  1. 断言:当前执行上下文在后续不会再用于求值任意 ECMAScript 代码或内建函数。调用本抽象操作之后的 Call 调用将在进行任何此类求值前创建并压入一个新的执行上下文。
  2. 丢弃与当前执行上下文关联的所有资源。
  3. 返回 unused

尾位置调用必须在调用目标函数前释放与当前正在执行的函数执行上下文关联的任何瞬态内部资源,或复用这些资源以支持目标函数。

Note

例如,尾位置调用应当只按“目标函数激活记录大小减去调用方激活记录大小”的差额增长实现的激活记录栈;若目标函数的激活记录更小,则栈总大小应减小。