14 ECMAScript 语言:语句与声明 (ECMAScript Language: Statements and Declarations)

语法 (Syntax)

Statement[Yield, Await, Return] : BlockStatement[?Yield, ?Await, ?Return] VariableStatement[?Yield, ?Await] EmptyStatement ExpressionStatement[?Yield, ?Await] IfStatement[?Yield, ?Await, ?Return] BreakableStatement[?Yield, ?Await, ?Return] ContinueStatement[?Yield, ?Await] BreakStatement[?Yield, ?Await] [+Return] ReturnStatement[?Yield, ?Await] WithStatement[?Yield, ?Await, ?Return] LabelledStatement[?Yield, ?Await, ?Return] ThrowStatement[?Yield, ?Await] TryStatement[?Yield, ?Await, ?Return] DebuggerStatement Declaration[Yield, Await] : HoistableDeclaration[?Yield, ?Await, ~Default] ClassDeclaration[?Yield, ?Await, ~Default] LexicalDeclaration[+In, ?Yield, ?Await] HoistableDeclaration[Yield, Await, Default] : FunctionDeclaration[?Yield, ?Await, ?Default] GeneratorDeclaration[?Yield, ?Await, ?Default] AsyncFunctionDeclaration[?Yield, ?Await, ?Default] AsyncGeneratorDeclaration[?Yield, ?Await, ?Default] BreakableStatement[Yield, Await, Return] : IterationStatement[?Yield, ?Await, ?Return] SwitchStatement[?Yield, ?Await, ?Return]

14.1 语句语义 (Statement Semantics)

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

HoistableDeclaration : GeneratorDeclaration AsyncFunctionDeclaration AsyncGeneratorDeclaration
  1. 返回 empty.
HoistableDeclaration : FunctionDeclaration
  1. 返回 ? Evaluation of FunctionDeclaration.
BreakableStatement : IterationStatement SwitchStatement
  1. newLabelSet 为新空 List
  2. 返回 ? LabelledEvaluation of 此 BreakableStatement,参数 newLabelSet

14.2 块 (Block)

语法 (Syntax)

BlockStatement[Yield, Await, Return] : Block[?Yield, ?Await, ?Return] Block[Yield, Await, Return] : { StatementList[?Yield, ?Await, ?Return]opt } StatementList[Yield, Await, Return] : StatementListItem[?Yield, ?Await, ?Return] StatementList[?Yield, ?Await, ?Return] StatementListItem[?Yield, ?Await, ?Return] StatementListItem[Yield, Await, Return] : Statement[?Yield, ?Await, ?Return] Declaration[?Yield, ?Await]

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

Block : { StatementList }
  • StatementList 的 LexicallyDeclaredNames 含有重复条目则为语法错误;除非宿主是 web 浏览器或支持 块级函数声明 Web 历史兼容语义 且以下两条件同时为真:

    • IsStrict(this production) 为 false
    • 重复条目仅由 FunctionDeclarations 绑定。
  • StatementList 的 LexicallyDeclaredNames 中任一元素也出现在其 VarDeclaredNames 中,则为语法错误。

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

Block : { }
  1. 返回 empty
Block : { StatementList }
  1. oldEnv 为当前执行上下文的 LexicalEnvironment。
  2. blockEnvNewDeclarativeEnvironment(oldEnv)。
  3. 执行 BlockDeclarationInstantiation(StatementList, blockEnv)。
  4. 将当前执行上下文的 LexicalEnvironment 设为 blockEnv
  5. blockValueCompletion(Evaluation of StatementList)。
  6. 将当前执行上下文的 LexicalEnvironment 设回 oldEnv
  7. 返回 ? blockValue
Note 1

无论控制如何离开 Block,LexicalEnvironment 均会恢复到之前状态。

StatementList : StatementList StatementListItem
  1. sl 为 ? Evaluation of StatementList
  2. sCompletion(Evaluation of StatementListItem)。
  3. 返回 ? UpdateEmpty(s, sl)。
Note 2

StatementList 的值是其中最后一个产生值的项。例如下列对 eval 的调用都返回 1:

eval("1;;;;;")
eval("1;{}")
eval("1;var a;")

14.2.3 BlockDeclarationInstantiation ( code, env )

The abstract operation BlockDeclarationInstantiation takes arguments code (一个 Parse Node) and env (一个 Declarative Environment Record) and returns unused. code 是块主体对应的 Parse Node。env 是要在其中创建绑定的 Environment Record

Note

当求值一个 BlockCaseBlock 时会创建新的 Declarative Environment Record,并为块内每个块级变量、常量、函数、类实例化绑定。

调用时执行以下步骤:

  1. declarationscode 的 LexicallyScopedDeclarations。
  2. privateEnv 为当前执行上下文的 PrivateEnvironment。
  3. declarations 中每个元素 d
    1. d 的 BoundNames 每个元素 dn
      1. 若 IsConstantDeclaration of dtrue,则
        1. 执行 ! env.CreateImmutableBinding(dn, true)。
      2. 否则,
        1. Normative Optional
          宿主是 web 浏览器或支持 块级函数声明 Web 历史兼容语义,则
          1. 若 ! env.HasBinding(dn) 为 false,执行 ! env.CreateMutableBinding(dn, false)。
        2. 否则,
          1. 执行 ! env.CreateMutableBinding(dn, false)。
    2. dFunctionDeclarationGeneratorDeclarationAsyncFunctionDeclarationAsyncGeneratorDeclaration,则
      1. fnd 的唯一 BoundName。
      2. fo 为 InstantiateFunctionObject of d,参数 envprivateEnv
      3. Normative Optional
        宿主是 web 浏览器或支持 块级函数声明 Web 历史兼容语义,则
        1. envfn 的绑定是未初始化,执行 ! env.InitializeBinding(fn, fo)。
        2. 否则,
          1. 断言:dFunctionDeclaration
          2. 执行 ! env.SetMutableBinding(fn, fo, false)。
      4. 否则,
        1. 执行 ! env.InitializeBinding(fn, fo)。
  4. 返回 unused

14.3 声明与变量语句 (Declarations and the Variable Statement)

14.3.1 Let 与 Const 声明 (Let and Const Declarations)

Note

letconst 声明的变量作用域为当前执行上下文的 LexicalEnvironment。变量在其包含的 Environment Record 实例化时创建,但在其 LexicalBinding 求值前不可访问。带 InitializerLexicalBinding 其变量在求值时(而非创建时)赋值为 InitializerAssignmentExpression 结果。let 声明中无 InitializerLexicalBinding 在求值时变量被赋值 undefined

语法 (Syntax)

LexicalDeclaration[In, Yield, Await] : LetOrConst BindingList[?In, ?Yield, ?Await] ; LetOrConst : let const BindingList[In, Yield, Await] : LexicalBinding[?In, ?Yield, ?Await] BindingList[?In, ?Yield, ?Await] , LexicalBinding[?In, ?Yield, ?Await] LexicalBinding[In, Yield, Await] : BindingIdentifier[?Yield, ?Await] Initializer[?In, ?Yield, ?Await]opt BindingPattern[?Yield, ?Await] Initializer[?In, ?Yield, ?Await]

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

LexicalDeclaration : LetOrConst BindingList ;
  • BindingList 的 BoundNames 含 "let",语法错误。
  • BindingList 的 BoundNames 含重复条目,语法错误。
LexicalBinding : BindingIdentifier Initializeropt

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

LexicalDeclaration : LetOrConst BindingList ;
  1. 执行 ? Evaluation of BindingList
  2. 返回 empty
BindingList : BindingList , LexicalBinding
  1. 执行 ? Evaluation of BindingList
  2. 返回 ? Evaluation of LexicalBinding
LexicalBinding : BindingIdentifier
  1. lhs 为 ! ResolveBinding(StringValue of BindingIdentifier)。
  2. 执行 ! InitializeReferencedBinding(lhs, undefined)。
  3. 返回 empty
Note

静态语义确保此形式不会出现在 const 声明中。

LexicalBinding : BindingIdentifier Initializer
  1. bindingIdBindingIdentifier 的 StringValue。
  2. lhs 为 ! ResolveBinding(bindingId)。
  3. 若 IsAnonymousFunctionDefinition(Initializer) 为 true,则
    1. value 为 ? NamedEvaluation of Initializer,参数 bindingId
  4. 否则,
    1. rhs 为 ? Evaluation of Initializer
    2. value 为 ? GetValue(rhs)。
  5. 执行 ! InitializeReferencedBinding(lhs, value)。
  6. 返回 empty
LexicalBinding : BindingPattern Initializer
  1. rhs 为 ? Evaluation of Initializer
  2. value 为 ? GetValue(rhs)。
  3. env 为当前执行上下文的 LexicalEnvironment。
  4. 返回 ? BindingInitialization of BindingPattern,参数 valueenv

14.3.2 变量语句 (Variable Statement)

Note

var 声明的变量作用域为当前执行上下文的 VariableEnvironment。此类变量在其环境记录实例化时创建并初始化为 undefined。在同一 VariableEnvironment 作用域中,相同 BindingIdentifier 可以出现在多个 VariableDeclaration 中,但这些声明共同定义一个变量。带 InitializerVariableDeclaration 在执行时赋值,而非创建时。

语法 (Syntax)

VariableStatement[Yield, Await] : var VariableDeclarationList[+In, ?Yield, ?Await] ; VariableDeclarationList[In, Yield, Await] : VariableDeclaration[?In, ?Yield, ?Await] VariableDeclarationList[?In, ?Yield, ?Await] , VariableDeclaration[?In, ?Yield, ?Await] VariableDeclaration[In, Yield, Await] : BindingIdentifier[?Yield, ?Await] Initializer[?In, ?Yield, ?Await]opt BindingPattern[?Yield, ?Await] Initializer[?In, ?Yield, ?Await]

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

VariableStatement : var VariableDeclarationList ;
  1. 执行 ? Evaluation of VariableDeclarationList
  2. 返回 empty
VariableDeclarationList : VariableDeclarationList , VariableDeclaration
  1. 执行 ? Evaluation of VariableDeclarationList
  2. 返回 ? Evaluation of VariableDeclaration
VariableDeclaration : BindingIdentifier
  1. 返回 empty
VariableDeclaration : BindingIdentifier Initializer
  1. bindingIdBindingIdentifier 的 StringValue。
  2. lhs 为 ? ResolveBinding(bindingId)。
  3. 若 IsAnonymousFunctionDefinition(Initializer) 为 true,则
    1. value 为 ? NamedEvaluation of Initializer,参数 bindingId
  4. 否则,
    1. rhs 为 ? Evaluation of Initializer
    2. value 为 ? GetValue(rhs)。
  5. 执行 ? PutValue(lhs, value)。
  6. 返回 empty
Note

VariableDeclaration 嵌套于 with 语句,且其 BindingIdentifier 与 with 绑定对象的属性同名,则步骤 5 会把 value 赋给该属性,而不是 VariableEnvironment 中的变量绑定。

VariableDeclaration : BindingPattern Initializer
  1. rhs 为 ? Evaluation of Initializer
  2. rVal 为 ? GetValue(rhs)。
  3. 返回 ? BindingInitialization of BindingPattern,参数 rValundefined

14.3.3 解构绑定模式 (Destructuring Binding Patterns)

语法 (Syntax)

BindingPattern[Yield, Await] : ObjectBindingPattern[?Yield, ?Await] ArrayBindingPattern[?Yield, ?Await] ObjectBindingPattern[Yield, Await] : { } { BindingRestProperty[?Yield, ?Await] } { BindingPropertyList[?Yield, ?Await] } { BindingPropertyList[?Yield, ?Await] , BindingRestProperty[?Yield, ?Await]opt } ArrayBindingPattern[Yield, Await] : [ Elisionopt BindingRestElement[?Yield, ?Await]opt ] [ BindingElementList[?Yield, ?Await] ] [ BindingElementList[?Yield, ?Await] , Elisionopt BindingRestElement[?Yield, ?Await]opt ] BindingRestProperty[Yield, Await] : ... BindingIdentifier[?Yield, ?Await] BindingPropertyList[Yield, Await] : BindingProperty[?Yield, ?Await] BindingPropertyList[?Yield, ?Await] , BindingProperty[?Yield, ?Await] BindingElementList[Yield, Await] : BindingElisionElement[?Yield, ?Await] BindingElementList[?Yield, ?Await] , BindingElisionElement[?Yield, ?Await] BindingElisionElement[Yield, Await] : Elisionopt BindingElement[?Yield, ?Await] BindingProperty[Yield, Await] : SingleNameBinding[?Yield, ?Await] PropertyName[?Yield, ?Await] : BindingElement[?Yield, ?Await] BindingElement[Yield, Await] : SingleNameBinding[?Yield, ?Await] BindingPattern[?Yield, ?Await] Initializer[+In, ?Yield, ?Await]opt SingleNameBinding[Yield, Await] : BindingIdentifier[?Yield, ?Await] Initializer[+In, ?Yield, ?Await]opt BindingRestElement[Yield, Await] : ... BindingIdentifier[?Yield, ?Await] ... BindingPattern[?Yield, ?Await]

14.3.3.1 运行时语义:PropertyBindingInitialization

The syntax-directed operation 运行时语义:PropertyBindingInitialization takes arguments value (一个 ECMAScript 语言值) and environment (一个 Environment Recordundefined) and returns 返回一个含属性键列表的正常完成或一个突然完成. 收集所有绑定的属性名列表。 It is defined piecewise over the following productions:

BindingPropertyList : BindingPropertyList , BindingProperty
  1. boundNames 为 ? PropertyBindingInitialization of BindingPropertyList,参数 valueenvironment
  2. nextNames 为 ? PropertyBindingInitialization of BindingProperty,参数 valueenvironment
  3. 返回列表连接 boundNamesnextNames
BindingProperty : SingleNameBinding
  1. nameSingleNameBinding 的 BoundNames 唯一元素。
  2. 执行 ? KeyedBindingInitialization of SingleNameBinding,参数 valueenvironmentname
  3. 返回 « name »。
BindingProperty : PropertyName : BindingElement
  1. P 为 ? Evaluation of PropertyName
  2. 执行 ? KeyedBindingInitialization of BindingElement,参数 valueenvironmentP
  3. 返回 « P »。

14.3.3.2 运行时语义:RestBindingInitialization

The syntax-directed operation 运行时语义:RestBindingInitialization takes arguments value (一个 ECMAScript 语言值), environment (一个 Environment Recordundefined), and excludedNames (属性键列表) and returns 返回含 unused正常完成或一个突然完成. It is defined piecewise over the following productions:

BindingRestProperty : ... BindingIdentifier
  1. lhs 为 ? ResolveBinding(StringValue of BindingIdentifier, environment)。
  2. restObjOrdinaryObjectCreate(%Object.prototype%)。
  3. 执行 ? CopyDataProperties(restObj, value, excludedNames)。
  4. environmentundefined,返回 ? PutValue(lhs, restObj)。
  5. 返回 ? InitializeReferencedBinding(lhs, restObj)。

14.3.3.3 运行时语义:KeyedBindingInitialization

The syntax-directed operation 运行时语义:KeyedBindingInitialization takes arguments value (一个 ECMAScript 语言值), environment (一个 Environment Recordundefined), and propertyName (一个属性键) and returns 返回含 unused正常完成或一个突然完成.

Note

environmentundefined 表示需使用 PutValue 赋值。这发生在非严格函数形参列表等场景;此时形参绑定已预初始化,以应对重复名称。

It is defined piecewise over the following productions:

BindingElement : BindingPattern Initializeropt
  1. v 为 ? GetV(value, propertyName)。
  2. 若存在 Initializervundefined,则
    1. defaultValue 为 ? Evaluation of Initializer
    2. v 为 ? GetValue(defaultValue)。
  3. 返回 ? BindingInitialization of BindingPattern,参数 venvironment
SingleNameBinding : BindingIdentifier Initializeropt
  1. bindingIdBindingIdentifier 的 StringValue。
  2. lhs 为 ? ResolveBinding(bindingId, environment)。
  3. v 为 ? GetV(value, propertyName)。
  4. 若存在 Initializervundefined,则
    1. 若 IsAnonymousFunctionDefinition(Initializer) 为 true,则
      1. v 为 ? NamedEvaluation of Initializer,参数 bindingId
    2. 否则,
      1. defaultValue 为 ? Evaluation of Initializer
      2. v 为 ? GetValue(defaultValue)。
  5. environmentundefined,返回 ? PutValue(lhs, v)。
  6. 返回 ? InitializeReferencedBinding(lhs, v)。

14.4 空语句 (Empty Statement)

语法 (Syntax)

EmptyStatement : ;

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

EmptyStatement : ;
  1. 返回 empty

14.5 表达式语句 (Expression Statement)

语法 (Syntax)

ExpressionStatement[Yield, Await] : [lookahead ∉ { {, function, async [no LineTerminator here] function, class, let [ }] Expression[+In, ?Yield, ?Await] ; Note

ExpressionStatement 不能以 U+007B { 开始以避免与 Block 歧义;不能以 functionclass 开头以避免与 FunctionDeclarationGeneratorDeclarationClassDeclaration 歧义;不能以 async function 开头避免与 AsyncFunctionDeclarationAsyncGeneratorDeclaration 歧义;不能以 let [ 开头避免与以数组绑定模式为首绑定的 let LexicalDeclaration 歧义。

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

ExpressionStatement : Expression ;
  1. exprRef 为 ? Evaluation of Expression
  2. 返回 ? GetValue(exprRef)。

14.6 if 语句 (The if Statement)

语法 (Syntax)

IfStatement[Yield, Await, Return] : if ( Expression[+In, ?Yield, ?Await] ) Statement[?Yield, ?Await, ?Return] else Statement[?Yield, ?Await, ?Return] if ( Expression[+In, ?Yield, ?Await] ) Statement[?Yield, ?Await, ?Return] [lookahead ≠ else] Note
lookahead 限制 [lookahead ≠ else] 以传统方式解决“悬挂的 else”问题:当关联的 if 有歧义时,将 else 归属最近的尚未匹配的 if

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

IfStatement : if ( Expression ) Statement else Statement
  • 若 IsLabelledFunction(第一个 Statement) 为 true,语法错误。
  • 若 IsLabelledFunction(第二个 Statement) 为 true,语法错误。
IfStatement : if ( Expression ) Statement
  • 若 IsLabelledFunction(Statement) 为 true,语法错误。
Note

仅当实现了 B.3.1 中的扩展时才需应用此规则。

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

IfStatement : if ( Expression ) Statement else Statement
  1. exprRef 为 ? Evaluation of Expression
  2. exprValueToBoolean(? GetValue(exprRef))。
  3. exprValuetrue,则
    1. stmtCompletionCompletion(Evaluation of 第一个 Statement)。
  4. 否则,
    1. stmtCompletionCompletion(Evaluation of 第二个 Statement)。
  5. 返回 ? UpdateEmpty(stmtCompletion, undefined)。
IfStatement : if ( Expression ) Statement
  1. exprRef 为 ? Evaluation of Expression
  2. exprValueToBoolean(? GetValue(exprRef))。
  3. exprValuefalse,返回 undefined
  4. 否则,
    1. stmtCompletionCompletion(Evaluation of Statement)。
    2. 返回 ? UpdateEmpty(stmtCompletion, undefined)。

14.7 迭代语句 (Iteration Statements)

语法 (Syntax)

IterationStatement[Yield, Await, Return] : DoWhileStatement[?Yield, ?Await, ?Return] WhileStatement[?Yield, ?Await, ?Return] ForStatement[?Yield, ?Await, ?Return] ForInOfStatement[?Yield, ?Await, ?Return]

14.7.1 语义 (Semantics)

14.7.1.1 LoopContinues ( completion, labelSet )

The abstract operation LoopContinues takes arguments completion (一个 Completion Record) and labelSet (字符串列表) and returns 一个 Boolean. It performs the following steps when called:

  1. completion 是 normal 完成,返回 true
  2. completion 不是 continue 完成,返回 false
  3. completion.[[Target]]empty,返回 true
  4. labelSetcompletion.[[Target]],返回 true
    1. 返回 false
Note

IterationStatementStatement 部分可以使用 ContinueStatement 开启新一轮迭代。

14.7.1.2 运行时语义:LoopEvaluation

The syntax-directed operation 运行时语义:LoopEvaluation takes argument labelSet (字符串列表) and returns 返回含 ECMAScript 语言值的正常或突然完成. It is defined piecewise over the following productions:

IterationStatement : DoWhileStatement
  1. 返回 ? DoWhileLoopEvaluation of DoWhileStatement,参数 labelSet
IterationStatement : WhileStatement
  1. 返回 ? WhileLoopEvaluation of WhileStatement,参数 labelSet
IterationStatement : ForStatement
  1. 返回 ? ForLoopEvaluation of ForStatement,参数 labelSet
IterationStatement : ForInOfStatement
  1. 返回 ? ForInOfLoopEvaluation of ForInOfStatement,参数 labelSet

14.7.2 do-while 语句 (The do-while Statement)

语法 (Syntax)

DoWhileStatement[Yield, Await, Return] : do Statement[?Yield, ?Await, ?Return] while ( Expression[+In, ?Yield, ?Await] ) ;

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

DoWhileStatement : do Statement while ( Expression ) ;
  • 若 IsLabelledFunction(Statement) 为 true,语法错误。
Note

仅当实现了 B.3.1 的扩展时需应用此规则。

14.7.2.2 运行时语义:DoWhileLoopEvaluation

The syntax-directed operation 运行时语义:DoWhileLoopEvaluation takes argument labelSet (字符串列表) and returns 正常或突然完成. It is defined piecewise over the following productions:

DoWhileStatement : do Statement while ( Expression ) ;
  1. Vundefined
  2. 重复,
    1. stmtResultCompletion(Evaluation of Statement)。
    2. LoopContinues(stmtResult, labelSet) 为 false,返回 ? UpdateEmpty(stmtResult, V)。
    3. stmtResult.[[Value]]empty,令 V = 该值。
    4. exprRef 为 ? Evaluation of Expression
    5. exprValue 为 ? GetValue(exprRef)。
    6. ToBoolean(exprValue) 为 false,返回 V

14.7.3 while 语句 (The while Statement)

语法 (Syntax)

WhileStatement[Yield, Await, Return] : while ( Expression[+In, ?Yield, ?Await] ) Statement[?Yield, ?Await, ?Return]

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

WhileStatement : while ( Expression ) Statement
  • 若 IsLabelledFunction(Statement) 为 true,语法错误。
Note

仅当实现了 B.3.1 扩展时需应用。

14.7.3.2 运行时语义:WhileLoopEvaluation

The syntax-directed operation 运行时语义:WhileLoopEvaluation takes argument labelSet (字符串列表) and returns 正常或突然完成. It is defined piecewise over the following productions:

WhileStatement : while ( Expression ) Statement
  1. Vundefined
  2. 重复,
    1. exprRef 为 ? Evaluation of Expression
    2. exprValue 为 ? GetValue(exprRef)。
    3. ToBoolean(exprValue) 为 false,返回 V
    4. stmtResultCompletion(Evaluation of Statement)。
    5. LoopContinues(stmtResult, labelSet) 为 false,返回 ? UpdateEmpty(stmtResult, V)。
    6. stmtResult.[[Value]]empty,设 V 为该值。

14.7.4 for 语句 (The for Statement)

语法 (Syntax)

ForStatement[Yield, Await, Return] : for ( [lookahead ≠ let [] Expression[~In, ?Yield, ?Await]opt ; Expression[+In, ?Yield, ?Await]opt ; Expression[+In, ?Yield, ?Await]opt ) Statement[?Yield, ?Await, ?Return] for ( var VariableDeclarationList[~In, ?Yield, ?Await] ; Expression[+In, ?Yield, ?Await]opt ; Expression[+In, ?Yield, ?Await]opt ) Statement[?Yield, ?Await, ?Return] for ( LexicalDeclaration[~In, ?Yield, ?Await] Expression[+In, ?Yield, ?Await]opt ; Expression[+In, ?Yield, ?Await]opt ) Statement[?Yield, ?Await, ?Return]

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

ForStatement : for ( Expressionopt ; Expressionopt ; Expressionopt ) Statement for ( var VariableDeclarationList ; Expressionopt ; Expressionopt ) Statement for ( LexicalDeclaration Expressionopt ; Expressionopt ) Statement
  • 若 IsLabelledFunction(Statement) 为 true,语法错误。
Note

仅当实现 B.3.1 扩展时适用。

ForStatement : for ( LexicalDeclaration Expressionopt ; Expressionopt ) Statement

14.7.4.2 运行时语义:ForLoopEvaluation

The syntax-directed operation 运行时语义:ForLoopEvaluation takes argument labelSet (字符串列表) and returns 正常或突然完成. It is defined piecewise over the following productions:

ForStatement : for ( Expressionopt ; Expressionopt ; Expressionopt ) Statement
  1. 若首个 Expression 存在,令 exprRef 为其求值;执行 ? GetValue(exprRef)。
  2. 若第二个存在,令 test 为该表达式,否则 empty
  3. 若第三个存在,令 increment 为该表达式,否则 empty
  4. 返回 ? ForBodyEvaluation(test, increment, Statement, « », labelSet)。
ForStatement : for ( var VariableDeclarationList ; Expressionopt ; Expressionopt ) Statement
  1. 执行 ? Evaluation of VariableDeclarationList
  2. 若首个 Expression 存在令 test = 它,否则 empty
  3. 若第二个 Expression 存在令 increment = 它,否则 empty
  4. 返回 ? ForBodyEvaluation(test, increment, Statement, « », labelSet)。
ForStatement : for ( LexicalDeclaration Expressionopt ; Expressionopt ) Statement
  1. oldEnv 为当前执行上下文的 LexicalEnvironment。
  2. loopEnvNewDeclarativeEnvironment(oldEnv)。
  3. isConstLexicalDeclaration 的 IsConstantDeclaration。
  4. boundNamesLexicalDeclaration 的 BoundNames。
  5. boundNames 中每个 dn
    1. isConsttrue,执行 ! loopEnv.CreateImmutableBinding(dn, true)。
    2. 否则执行 ! loopEnv.CreateMutableBinding(dn, false)。
  6. 设置当前执行上下文 LexicalEnvironment 为 loopEnv
  7. forDclCompletion(Evaluation of LexicalDeclaration)。
  8. forDcl 为突然完成:
    1. 恢复 LexicalEnvironment 为 oldEnv
    2. 返回 ? forDcl
  9. isConstfalse,令 perIterationLets = boundNames;否则为空列表。
  10. 若首个 Expression 存在令 test 为其,否则 empty
  11. 若第二个 Expression 存在令 increment 为其,否则 empty
  12. bodyResultCompletion(ForBodyEvaluation(test, increment, Statement, perIterationLets, labelSet))。
  13. 恢复 LexicalEnvironment 为 oldEnv
  14. 返回 ? bodyResult

14.7.4.3 ForBodyEvaluation ( test, increment, stmt, perIterationBindings, labelSet )

The abstract operation ForBodyEvaluation takes arguments test (Expression Parse Node 或 empty), increment (Expression Parse Node 或 empty), stmt (Statement Parse Node), perIterationBindings (字符串列表), and labelSet (字符串列表) and returns 正常或突然完成. It performs the following steps when called:

  1. V = undefined
  2. 执行 ? CreatePerIterationEnvironment(perIterationBindings)。
  3. 重复:
    1. testempty
      1. testRef 为 ? Evaluation of test
      2. testValue 为 ? GetValue(testRef)。
      3. ToBoolean(testValue) 为 false,返回 V
    2. resultCompletion(Evaluation of stmt)。
    3. LoopContinues(result, labelSet) 为 false,返回 ? UpdateEmpty(result, V)。
    4. result.[[Value]]empty,设 V 为该值。
    5. 执行 ? CreatePerIterationEnvironment(perIterationBindings)。
    6. incrementempty
      1. incRef 为 ? Evaluation of increment
      2. 执行 ? GetValue(incRef)。

14.7.4.4 CreatePerIterationEnvironment ( perIterationBindings )

The abstract operation CreatePerIterationEnvironment takes argument perIterationBindings (字符串列表) and returns 返回 unused 的正常或抛出完成. It performs the following steps when called:

  1. perIterationBindings 非空:
    1. lastIterationEnv 为当前执行上下文的 LexicalEnvironment。
    2. outerlastIterationEnv.[[OuterEnv]]
    3. 断言 outernull
    4. thisIterationEnvNewDeclarativeEnvironment(outer)。
    5. perIterationBindings 中每个 bn
      1. 执行 ! thisIterationEnv.CreateMutableBinding(bn, false)。
      2. lastValue 为 ? lastIterationEnv.GetBindingValue(bn, true)。
      3. 执行 ! thisIterationEnv.InitializeBinding(bn, lastValue)。
    6. 将当前 LexicalEnvironment 设为 thisIterationEnv
  2. 返回 unused

14.7.5 for-infor-offor-await-of 语句

语法 (Syntax)

ForInOfStatement[Yield, Await, Return] : for ( [lookahead ≠ let [] LeftHandSideExpression[?Yield, ?Await] in Expression[+In, ?Yield, ?Await] ) Statement[?Yield, ?Await, ?Return] for ( var ForBinding[?Yield, ?Await] in Expression[+In, ?Yield, ?Await] ) Statement[?Yield, ?Await, ?Return] for ( ForDeclaration[?Yield, ?Await] in Expression[+In, ?Yield, ?Await] ) Statement[?Yield, ?Await, ?Return] for ( [lookahead ∉ { let, async of }] LeftHandSideExpression[?Yield, ?Await] of AssignmentExpression[+In, ?Yield, ?Await] ) Statement[?Yield, ?Await, ?Return] for ( var ForBinding[?Yield, ?Await] of AssignmentExpression[+In, ?Yield, ?Await] ) Statement[?Yield, ?Await, ?Return] for ( ForDeclaration[?Yield, ?Await] of AssignmentExpression[+In, ?Yield, ?Await] ) Statement[?Yield, ?Await, ?Return] [+Await] for await ( [lookahead ≠ let] LeftHandSideExpression[?Yield, ?Await] of AssignmentExpression[+In, ?Yield, ?Await] ) Statement[?Yield, ?Await, ?Return] [+Await] for await ( var ForBinding[?Yield, ?Await] of AssignmentExpression[+In, ?Yield, ?Await] ) Statement[?Yield, ?Await, ?Return] [+Await] for await ( ForDeclaration[?Yield, ?Await] of AssignmentExpression[+In, ?Yield, ?Await] ) Statement[?Yield, ?Await, ?Return] ForDeclaration[Yield, Await] : LetOrConst ForBinding[?Yield, ?Await] ForBinding[Yield, Await] : BindingIdentifier[?Yield, ?Await] BindingPattern[?Yield, ?Await] Note

本节由附录 B.3.5 扩展。

14.7.5.1 静态语义:早期错误 (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
  • 若 IsLabelledFunction(Statement) 为 true,语法错误。
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
  • ForDeclaration 的 BoundNames 含 "let",语法错误。
  • 若 BoundNames 的任一元素出现在 Statement 的 VarDeclaredNames 中,语法错误。
  • 若 BoundNames 含重复条目,语法错误。

14.7.5.2 静态语义:IsDestructuring

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

MemberExpression : PrimaryExpression
  1. PrimaryExpressionObjectLiteralArrayLiteral,返回 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. 返回 IsDestructuring of ForBinding
ForBinding : BindingIdentifier
  1. 返回 false
ForBinding : BindingPattern
  1. 返回 true
Note

本节由附录 B.3.5 扩展。

14.7.5.3 运行时语义:ForDeclarationBindingInitialization

The syntax-directed operation 运行时语义:ForDeclarationBindingInitialization takes arguments value (ECMAScript 语言值) and environment (Environment Recordundefined) and returns 正常或突然完成.

Note

undefined 表示应使用 PutValue 赋值。适用于 var 语句以及某些非严格函数形参(参见 10.2.11)。这些场景下词法绑定被提升并预初始化。

It is defined piecewise over the following productions:

ForDeclaration : LetOrConst ForBinding
  1. 返回 ? BindingInitialization of ForBinding,参数 valueenvironment

14.7.5.4 运行时语义:ForDeclarationBindingInstantiation

The syntax-directed operation 运行时语义:ForDeclarationBindingInstantiation takes argument environment (一个 Declarative Environment Record) and returns unused. It is defined piecewise over the following productions:

ForDeclaration : LetOrConst ForBinding
  1. ForBinding 的 BoundNames 每个 name
    1. 若 IsConstantDeclaration of LetOrConsttrue,执行 ! environment.CreateImmutableBinding(name, true)。
    2. 否则执行 ! environment.CreateMutableBinding(name, false)。
  2. 返回 unused

14.7.5.5 运行时语义:ForInOfLoopEvaluation

The syntax-directed operation 运行时语义:ForInOfLoopEvaluation takes argument labelSet (字符串列表) and returns 正常或突然完成. 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 (字符串列表), expr (ExpressionAssignmentExpression Parse Node), and iterationKind (enumerate / iterate / async-iterate) and returns Iterator Record 或突然完成. It performs the following steps when called:

  1. oldEnv 为当前执行上下文 LexicalEnvironment。
  2. uninitializedBoundNames 非空:
    1. 断言无重复。
    2. newEnvNewDeclarativeEnvironment(oldEnv)。
    3. 对每个 name 执行 ! newEnv.CreateMutableBinding(name, false)。
    4. 设置当前 LexicalEnvironment 为 newEnv
  3. exprRefCompletion(Evaluation of expr)。
  4. 恢复 LexicalEnvironment 为 oldEnv
  5. exprValue 为 ? GetValue(? exprRef)。
  6. iterationKindenumerate
    1. exprValueundefinednull
      1. 返回 Completion Record { [[Type]]: break, [[Value]]: empty, [[Target]]: empty }。
    2. obj = ! ToObject(exprValue)。
    3. iterator = EnumerateObjectProperties(obj)。
    4. nextMethod = ! GetV(iterator, "next")。
    5. 返回 Iterator Record { [[Iterator]]: iterator, [[NextMethod]]: nextMethod, [[Done]]: false }。
  7. 否则:
    1. 断言 iterationKinditerateasync-iterate
    2. 若为 async-iterateiteratorKind = async 否则 sync
    3. 返回 ? GetIterator(exprValue, iteratorKind)。

14.7.5.7 ForIn/OfBodyEvaluation ( lhs: Parse Node, stmt: Statement Parse Node, iteratorRecord: Iterator Record, iterationKind: enumerateiterate, lhsKind: assignment / var-binding / lexical-binding, labelSet: 字符串列表, 可选 iteratorKind: sync / async, ): 正常或突然完成

The abstract operation UNKNOWN takes UNPARSEABLE ARGUMENTS. It performs the following steps when called:

  1. 若未给出 iteratorKind,设为 sync
  2. oldEnv 为当前 LexicalEnvironment。
  3. V = undefined
  4. destructuring = IsDestructuring of lhs
  5. destructuringtruelhsKindassignment
    1. 断言 lhsLeftHandSideExpression
    2. assignmentPattern 为其覆盖AssignmentPattern
  6. 循环:
    1. nextResult = ? Call(iteratorRecord.[[NextMethod]], iteratorRecord.[[Iterator]])。
    2. iteratorKindasync,设 nextResult = ? Await(nextResult)。
    3. nextResult 非 Object 抛 TypeError
    4. done = ? IteratorComplete(nextResult)。
    5. donetrue,返回 V
    6. nextValue = ? IteratorValue(nextResult)。
    7. lhsKindassignmentvar-binding
      1. destructuringtrue
        1. lhsKindassignment
          1. status = Completion(DestructuringAssignmentEvaluation of assignmentPattern,参数 nextValue)。
        2. 否则 (var-binding):
          1. 断言 lhsForBinding
          2. status = Completion(BindingInitialization of lhs, 参数 nextValueundefined)。
      2. 否则:
        1. lhsRef = Completion(Evaluation of lhs)(可重复求值)。
        2. lhsKindassignment 且 AssignmentTargetType 为 web-compatReferenceError
        3. lhsRef 为突然完成则 status = lhsRef;否则 status = Completion(PutValue(lhsRef.[[Value]], nextValue))。
    8. 否则 (lexical-binding):
      1. 断言 lhsForDeclaration
      2. iterationEnv = NewDeclarativeEnvironment(oldEnv)。
      3. 执行 ForDeclarationBindingInstantiation of lhs 参数 iterationEnv
      4. 设当前 LexicalEnvironment = iterationEnv
      5. destructuringtrue
        1. status = Completion(ForDeclarationBindingInitialization of lhs, 参数 nextValueiterationEnv)。
      6. 否则:
        1. 断言 lhs 绑定单一名字。
        2. lhsName 为唯一 BoundName。
        3. lhsRef = ! ResolveBinding(lhsName)。
        4. status = Completion(InitializeReferencedBinding(lhsRef, nextValue))。
    9. status 为突然完成:
      1. 恢复 LexicalEnvironment 为 oldEnv
      2. iteratorKindasync 返回 ? AsyncIteratorClose(iteratorRecord, status)。
      3. iterationKindenumerate 返回 ? status
      4. 否则返回 ? IteratorClose(iteratorRecord, status)。
    10. resultCompletion(Evaluation of stmt)。
    11. 恢复 LexicalEnvironment 为 oldEnv
    12. LoopContinues(result, labelSet) 为 false
      1. iterationKindenumerate 返回 ? UpdateEmpty(result, V)。
      2. 否则:
        1. status = Completion(UpdateEmpty(result, V))。
        2. iteratorKindasync 返回 ? AsyncIteratorClose(iteratorRecord, status)。
        3. 返回 ? IteratorClose(iteratorRecord, status)。
    13. result.[[Value]]empty,设 V = 该值。

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

BindingIdentifier : Identifier yield await
  1. bindingIdBindingIdentifier 的 StringValue。
  2. 返回 ? ResolveBinding(bindingId)。

14.7.5.9 EnumerateObjectProperties ( O )

The abstract operation EnumerateObjectProperties takes argument O (一个 Object) and returns 一个迭代器对象. It performs the following steps when called:

  1. 返回一个迭代器对象,其 next 方法按规则遍历 O 的可枚举属性的字符串键。该迭代器对象不可被 ECMAScript 代码直接获取。枚举顺序未指定,但必须符合下述规则。

迭代器的 throwreturn 方法为 null 且不会被调用。next 决定是否返回一个属性键;不返回 Symbol 键。枚举期间可删除目标对象属性,被删且尚未处理的属性被忽略;新增属性不保证出现在当前枚举。每个名称最多返回一次。

枚举包括原型链上可枚举属性;若某原型属性与已处理属性同名则跳过,不比较 [[Enumerable]]。原型对象的可枚举属性名通过再次调用 EnumerateObjectProperties 获得。目标对象的自有属性键通过其 [[OwnPropertyKeys]] 获得,属性属性值通过 [[GetOwnProperty]] 获得。

另外,若 O 及其原型链均非 Proxy / TypedArray / module namespace 或实现自定义 exotic,则该迭代器行为须与 CreateForInIterator(O) 所给迭代器一致,直到出现以下任一情况:

  • 原型链中任意对象的 [[Prototype]] 发生变化;
  • O 或其原型链某对象删除属性;
  • 原型链某对象新增属性;
  • O 或原型链某对象属性的 [[Enumerable]] 值改变。
Note 1

实现无需直接实现 14.7.5.10.2.1 的算法,只要行为一致即可。

下列生成器函数是符合规则的示例:

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
例外 exotic 列表基于历史实现差异,其余保持一致。

14.7.5.10 For-In 迭代器对象 (For-In Iterator Objects)

For-In Iterator 表示对特定对象的一次具体迭代,不能被脚本直接访问,仅用于描述 EnumerateObjectProperties 的行为。

14.7.5.10.1 CreateForInIterator ( object )

The abstract operation CreateForInIterator takes argument object (一个 Object) and returns 一个 For-In Iterator. 创建针对 object 自有及继承可枚举字符串属性按特定顺序遍历的 For-In Iterator 对象。 It performs the following steps when called:

  1. iterator = OrdinaryObjectCreate(%ForInIteratorPrototype%, « [[Object]], [[ObjectWasVisited]], [[VisitedKeys]], [[RemainingKeys]] »)。
  2. iterator.[[Object]]object
  3. iterator.[[ObjectWasVisited]]false
  4. iterator.[[VisitedKeys]] ← 空 List
  5. iterator.[[RemainingKeys]] ← 空 List
  6. 返回 iterator

14.7.5.10.2 %ForInIteratorPrototype% 对象

%ForInIteratorPrototype% 对象:

14.7.5.10.2.1 %ForInIteratorPrototype%.next ( )

  1. Othis
  2. 断言 O 是 Object
  3. 断言 OFor-In Iterator 所有内部槽。
  4. object = O.[[Object]]
  5. 重复:
    1. O.[[ObjectWasVisited]]false
      1. keys = ? object.[[OwnPropertyKeys]]()
      2. keys 每个 key
        1. key 是 String,追加到 O.[[RemainingKeys]]
      3. O.[[ObjectWasVisited]] = true
    2. O.[[RemainingKeys]] 非空重复:
      1. r 为首元素。
      2. 移除之。
      3. O.[[VisitedKeys]] 不含 r
        1. desc = ? object.[[GetOwnProperty]](r)。
        2. descundefined
          1. 追加 rO.[[VisitedKeys]]
          2. desc.[[Enumerable]]true,返回 CreateIteratorResultObject(r, false)。
    3. object = ? object.[[GetPrototypeOf]]()
    4. O.[[Object]] = object
    5. O.[[ObjectWasVisited]] = false
    6. objectnull,返回 CreateIteratorResultObject(undefined, true)。

14.7.5.10.3 For-In 迭代器实例属性 (Properties of For-In Iterator Instances)

实例为普通对象,继承自 %ForInIteratorPrototype%,初始拥有下表内部槽:

Table 36: For-In 迭代器实例内部槽 (Internal Slots of For-In Iterator Instances)
内部槽 类型 描述
[[Object]] Object 枚举属性的对象。
[[ObjectWasVisited]] Boolean 若已在 [[Object]] 上调用 [[OwnPropertyKeys]]true,否则 false
[[VisitedKeys]] 字符串列表 迄今已发出的键。
[[RemainingKeys]] 字符串列表 当前对象剩余未发出的键(在遍历原型链之前)。

14.8 continue 语句 (The continue Statement)

语法 (Syntax)

ContinueStatement[Yield, Await] : continue ; continue [no LineTerminator here] LabelIdentifier[?Yield, ?Await] ;

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

ContinueStatement : continue ; continue LabelIdentifier ;

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

ContinueStatement : continue ;
  1. 返回 Completion Record { [[Type]]: continue, [[Value]]: empty, [[Target]]: empty }。
ContinueStatement : continue LabelIdentifier ;
  1. labelLabelIdentifier 的 StringValue。
  2. 返回 Completion Record { [[Type]]: continue, [[Value]]: empty, [[Target]]: label }。

14.9 break 语句 (The break Statement)

语法 (Syntax)

BreakStatement[Yield, Await] : break ; break [no LineTerminator here] LabelIdentifier[?Yield, ?Await] ;

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

BreakStatement : break ;

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

BreakStatement : break ;
  1. 返回 Completion Record { [[Type]]: break, [[Value]]: empty, [[Target]]: empty }。
BreakStatement : break LabelIdentifier ;
  1. labelLabelIdentifier 的 StringValue。
  2. 返回 Completion Record { [[Type]]: break, [[Value]]: empty, [[Target]]: label }。

14.10 return 语句 (The return Statement)

语法 (Syntax)

ReturnStatement[Yield, Await] : return ; return [no LineTerminator here] Expression[+In, ?Yield, ?Await] ; Note

return 语句使函数终止执行并(大多数情况下)向调用者返回值;若省略 Expression,返回 undefined。在某些上下文(如 try/finally)中,返回值可能被之后的 Completion 替换。

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

ReturnStatement : return ;
  1. 返回 ReturnCompletion(undefined)。
ReturnStatement : return Expression ;
  1. exprRef 为 ? Evaluation of Expression
  2. exprValue 为 ? GetValue(exprRef)。
  3. GetGeneratorKind() 为 async,设 exprValue = ? Await(exprValue)。
  4. 返回 ReturnCompletion(exprValue)。
Legacy

14.11 with 语句 (The with Statement)

Note 1

不建议在新代码中使用遗留 with 语句;可考虑在严格和非严格模式都允许的替代方案,如 解构赋值

语法 (Syntax)

WithStatement[Yield, Await, Return] : with ( Expression[+In, ?Yield, ?Await] ) Statement[?Yield, ?Await, ?Return] Note 2

with 语句把对象环境记录加入当前词法环境,然后使用扩展环境执行语句,结束后恢复原环境。

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

WithStatement : with ( Expression ) Statement
  • 若 IsStrict(this production) 为 true,语法错误。
  • 若 IsLabelledFunction(Statement) 为 true,语法错误。
Note

仅在实现 B.3.1 扩展时需应用第二条。

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

WithStatement : with ( Expression ) Statement
  1. val 为 ? Evaluation of Expression
  2. obj 为 ? ToObject(? GetValue(val))。
  3. oldEnv 为当前 LexicalEnvironment。
  4. newEnvNewObjectEnvironment(obj, true, oldEnv)。
  5. 设置当前 LexicalEnvironment 为 newEnv
  6. CCompletion(Evaluation of Statement)。
  7. 恢复 LexicalEnvironment 为 oldEnv
  8. 返回 ? UpdateEmpty(C, undefined)。
Note

无论 Statement 如何结束(正常与否),LexicalEnvironment 都会被恢复。

14.12 switch 语句 (The switch Statement)

语法 (Syntax)

SwitchStatement[Yield, Await, Return] : switch ( Expression[+In, ?Yield, ?Await] ) CaseBlock[?Yield, ?Await, ?Return] CaseBlock[Yield, Await, Return] : { CaseClauses[?Yield, ?Await, ?Return]opt } { CaseClauses[?Yield, ?Await, ?Return]opt DefaultClause[?Yield, ?Await, ?Return] CaseClauses[?Yield, ?Await, ?Return]opt } CaseClauses[Yield, Await, Return] : CaseClause[?Yield, ?Await, ?Return] CaseClauses[?Yield, ?Await, ?Return] CaseClause[?Yield, ?Await, ?Return] CaseClause[Yield, Await, Return] : case Expression[+In, ?Yield, ?Await] : StatementList[?Yield, ?Await, ?Return]opt DefaultClause[Yield, Await, Return] : default : StatementList[?Yield, ?Await, ?Return]opt

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

SwitchStatement : switch ( Expression ) CaseBlock
  • CaseBlock 的 LexicallyDeclaredNames 含重复条目则语法错误;除非宿主是 web 浏览器或支持 块级函数声明 Web 历史兼容语义 且:

    • IsStrict(this production) 为 false
    • 重复条目仅由 FunctionDeclarations 绑定。
  • CaseBlock 的 LexicallyDeclaredNames 与其 VarDeclaredNames 有交集,语法错误。

14.12.2 运行时语义:CaseBlockEvaluation

The syntax-directed operation 运行时语义:CaseBlockEvaluation takes argument input (ECMAScript 语言值) and returns 正常或突然完成. It is defined piecewise over the following productions:

CaseBlock : { }
  1. 返回 undefined
CaseBlock : { CaseClauses }
  1. Vundefined
  2. A ← 按源码顺序的 CaseClause 列表。
  3. foundfalse
  4. 对每个 CA
    1. foundfalse,设 found ← ? CaseClauseIsSelected(C, input)。
    2. foundtrue
      1. RCompletion(Evaluation of C)。
      2. R.[[Value]]emptyVR.[[Value]]
      3. R 为突然完成,返回 ? UpdateEmpty(R, V)。
  5. 返回 V
CaseBlock : { CaseClausesopt DefaultClause CaseClausesopt }
  1. Vundefined
  2. 若首个 CaseClauses 存在,A ← 其 CaseClause 列表;否则空列表。
  3. foundfalse
  4. A 中每个 C
    1. foundfalsefound ← ? CaseClauseIsSelected(C, input)。
    2. foundtrue
      1. RCompletion(Evaluation of C)。
      2. R.[[Value]]emptyVR.[[Value]]
      3. R 为突然完成,返回 ? UpdateEmpty(R, V)。
  5. foundInBfalse
  6. 若第二个 CaseClauses 存在,B ← 其列表;否则空列表。
  7. foundfalse
    1. B 中每个 C
      1. foundInBfalsefoundInB ← ? CaseClauseIsSelected(C, input)。
      2. foundInBtrue
        1. RCompletion(Evaluation of C)。
        2. R.[[Value]]emptyVR.[[Value]]
        3. R 为突然完成,返回 ? UpdateEmpty(R, V)。
  8. foundInBtrue,返回 V
  9. defaultRCompletion(Evaluation of DefaultClause)。
  10. defaultR.[[Value]]emptyVdefaultR.[[Value]]
  11. defaultR 为突然完成,返回 ? UpdateEmpty(defaultR, V)。
  12. 注:以下再次遍历 B
  13. B 中每个 C
    1. RCompletion(Evaluation of C)。
    2. R.[[Value]]emptyVR.[[Value]]
    3. R 为突然完成,返回 ? UpdateEmpty(R, V)。
  14. 返回 V

14.12.3 CaseClauseIsSelected ( C, input )

The abstract operation CaseClauseIsSelected takes arguments C (CaseClause Parse Node) and input (ECMAScript 语言值) and returns 正常完成含 Boolean 或突然完成. 判断 C 是否匹配 input。 It performs the following steps when called:

  1. 断言 C 为产生式 CaseClause : case Expression : StatementListopt 实例。
  2. exprRef 为 ? Evaluation of CExpression
  3. clauseSelector 为 ? GetValue(exprRef)。
  4. 返回 IsStrictlyEqual(input, clauseSelector)。
Note

该操作不执行 CStatementListCaseBlock 算法根据其返回值决定从哪个 StatementList 开始。

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

SwitchStatement : switch ( Expression ) CaseBlock
  1. exprRef ← ? Evaluation of Expression
  2. switchValue ← ? GetValue(exprRef)。
  3. oldEnv ← 当前 LexicalEnvironment。
  4. blockEnvNewDeclarativeEnvironment(oldEnv)。
  5. 执行 BlockDeclarationInstantiation(CaseBlock, blockEnv)。
  6. 设置 LexicalEnvironment = blockEnv
  7. RCompletion(CaseBlockEvaluation of CaseBlock, 参数 switchValue)。
  8. 恢复 LexicalEnvironment = oldEnv
  9. 返回 R
Note

无论控制如何离开 SwitchStatement,LexicalEnvironment 皆被恢复。

CaseClause : case Expression :
  1. 返回 empty
CaseClause : case Expression : StatementList
  1. 返回 ? Evaluation of StatementList
DefaultClause : default :
  1. 返回 empty
DefaultClause : default : StatementList
  1. 返回 ? Evaluation of StatementList

14.13 带标签语句 (Labelled Statements)

语法 (Syntax)

LabelledStatement[Yield, Await, Return] : LabelIdentifier[?Yield, ?Await] : LabelledItem[?Yield, ?Await, ?Return] LabelledItem[Yield, Await, Return] : Statement[?Yield, ?Await, ?Return] FunctionDeclaration[?Yield, ?Await, ~Default] Note

Statement 可带标签。标签语句仅配合带标签的 break / continue;语言无 goto。标签递归嵌套形成“当前标签集合”。

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

LabelledItem : FunctionDeclaration

14.13.2 静态语义:IsLabelledFunction ( stmt )

The abstract operation 静态语义:IsLabelledFunction takes argument stmt (Statement Parse Node) and returns Boolean. It performs the following steps when called:

  1. stmt 不是 LabelledStatement,返回 false
  2. item 为其 LabelledItem
  3. item LabelledItem : FunctionDeclaration ,返回 true
  4. subStmtitemStatement
  5. 返回 IsLabelledFunction(subStmt)。

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

LabelledStatement : LabelIdentifier : LabelledItem
  1. 返回 ? LabelledEvaluation of 此 LabelledStatement,参数 « »。

14.13.4 运行时语义:LabelledEvaluation

The syntax-directed operation 运行时语义:LabelledEvaluation takes argument labelSet (字符串列表) and returns 正常完成ECMAScript 语言值empty,或突然完成. It is defined piecewise over the following productions:

BreakableStatement : IterationStatement
  1. stmtResultCompletion(LoopEvaluation of IterationStatement, 参数 labelSet)。
  2. stmtResultbreak 完成
    1. stmtResult.[[Target]]empty
      1. stmtResult.[[Value]]empty,设其为 NormalCompletion(undefined);否则设为其值的 NormalCompletion
  3. 返回 ? stmtResult
BreakableStatement : SwitchStatement
  1. stmtResultCompletion(Evaluation of SwitchStatement)。
  2. 若为 break 且 [[Target]]empty
    1. [[Value]]empty 设为 NormalCompletion(undefined) 否则为该值。
  3. 返回 ? stmtResult
Note 1

BreakableStatement 是能被无标签 BreakStatement 退出的语句。

LabelledStatement : LabelIdentifier : LabelledItem
  1. label ← StringValue of LabelIdentifier
  2. newLabelSet ← 连接 labelSet 与 « label »。
  3. stmtResultCompletion(LabelledEvaluation of LabelledItem, 参数 newLabelSet)。
  4. stmtResult 是 break 且 [[Target]]label,则设为 NormalCompletion(stmtResult.[[Value]])。
  5. 返回 ? stmtResult
LabelledItem : FunctionDeclaration
  1. 返回 ? Evaluation of FunctionDeclaration
Statement : BlockStatement VariableStatement EmptyStatement ExpressionStatement IfStatement ContinueStatement BreakStatement ReturnStatement WithStatement ThrowStatement TryStatement DebuggerStatement
  1. 返回 ? Evaluation of Statement
Note 2

Statement 中仅 BreakableStatementLabelledStatement 在 LabelledEvaluation 有特殊语义。

14.14 throw 语句 (The throw Statement)

语法 (Syntax)

ThrowStatement[Yield, Await] : throw [no LineTerminator here] Expression[+In, ?Yield, ?Await] ;

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

ThrowStatement : throw Expression ;
  1. exprRef ← ? Evaluation of Expression
  2. exprValue ← ? GetValue(exprRef)。
  3. 返回 ThrowCompletion(exprValue)。

14.15 try 语句 (The try Statement)

语法 (Syntax)

TryStatement[Yield, Await, Return] : try Block[?Yield, ?Await, ?Return] Catch[?Yield, ?Await, ?Return] try Block[?Yield, ?Await, ?Return] Finally[?Yield, ?Await, ?Return] try Block[?Yield, ?Await, ?Return] Catch[?Yield, ?Await, ?Return] Finally[?Yield, ?Await, ?Return] Catch[Yield, Await, Return] : catch ( CatchParameter[?Yield, ?Await] ) Block[?Yield, ?Await, ?Return] catch Block[?Yield, ?Await, ?Return] Finally[Yield, Await, Return] : finally Block[?Yield, ?Await, ?Return] CatchParameter[Yield, Await] : BindingIdentifier[?Yield, ?Await] BindingPattern[?Yield, ?Await] Note

try 语句封装可能发生异常的代码块;catch 提供处理逻辑;被捕获异常绑定到 CatchParameter

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

Catch : catch ( CatchParameter ) Block

14.15.2 运行时语义:CatchClauseEvaluation

The syntax-directed operation 运行时语义:CatchClauseEvaluation takes argument thrownValue (ECMAScript 语言值) and returns 正常完成ECMAScript 语言值empty,或突然完成. It is defined piecewise over the following productions:

Catch : catch ( CatchParameter ) Block
  1. oldEnv ← 当前 LexicalEnvironment。
  2. catchEnvNewDeclarativeEnvironment(oldEnv)。
  3. CatchParameter 的 BoundNames 中每个 argName
    1. 执行 ! catchEnv.CreateMutableBinding(argName, false)。
  4. 设置 LexicalEnvironment = catchEnv
  5. statusCompletion(BindingInitialization of CatchParameter,参数 thrownValuecatchEnv)。
  6. status 为突然完成:
    1. 恢复 LexicalEnvironment = oldEnv
    2. 返回 ? status
  7. BCompletion(Evaluation of Block)。
  8. 恢复 LexicalEnvironment = oldEnv
  9. 返回 ? B
Catch : catch Block
  1. 返回 ? Evaluation of Block
Note

无论 Block 如何离开,LexicalEnvironment 都被恢复。

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

TryStatement : try Block Catch
  1. BCompletion(Evaluation of Block)。
  2. Bthrow 完成CCompletion(CatchClauseEvaluation of Catch, 参数 B.[[Value]]);否则 CB
  3. 返回 ? UpdateEmpty(C, undefined)。
TryStatement : try Block Finally
  1. BCompletion(Evaluation of Block)。
  2. FCompletion(Evaluation of Finally)。
  3. F 为 normal,设 FB
  4. 返回 ? UpdateEmpty(F, undefined)。
TryStatement : try Block Catch Finally
  1. BCompletion(Evaluation of Block)。
  2. B 为 throw,CCompletion(CatchClauseEvaluation of Catch, 参数 B.[[Value]]);否则 CB
  3. FCompletion(Evaluation of Finally)。
  4. F 为 normal,设 FC
  5. 返回 ? UpdateEmpty(F, undefined)。

14.16 debugger 语句 (The debugger Statement)

语法 (Syntax)

DebuggerStatement : debugger ;

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

Note

求值 DebuggerStatement 时实现可在调试器下触发断点;若无调试器则无可观察效果。

DebuggerStatement : debugger ;
  1. 若实现定义的调试设施可用且启用:
    1. 执行实现定义调试动作。
    2. 返回实现定义的新 Completion Record
  2. 否则返回 empty